From b1c19bf904a7d537485ab97f04799fe96640eda6 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Thu, 21 Mar 2024 09:59:36 -0700 Subject: [PATCH 01/13] wolfSSL v5.7.0 for Arduino --- .gitignore | 430 +-- ChangeLog.md | 92 +- README | 140 +- README.md | 189 +- examples/wolfssl_client/wolfssl_client.ino | 75 +- examples/wolfssl_server/wolfssl_server.ino | 65 +- examples/wolfssl_version/README.md | 3 + examples/wolfssl_version/wolfssl_version.ino | 24 + library.properties | 2 +- src/src/internal.c | 157 +- src/src/quic.c | 13 + src/src/ssl.c | 2 +- src/src/tls.c | 94 +- src/src/tls13.c | 42 +- src/src/wolfio.c | 86 +- src/src/x509.c | 20 +- src/src/x509_str.c | 1 + src/user_settings.h | 138 +- src/wolfcrypt/src/asn.c | 295 +- src/wolfcrypt/src/cmac.c | 3 +- src/wolfcrypt/src/ecc.c | 40 +- src/wolfcrypt/src/misc.c | 12 + src/wolfcrypt/src/pkcs7.c | 1131 ++++-- src/wolfcrypt/src/sha256.c | 358 +- src/wolfcrypt/src/sha512.c | 29 +- src/wolfcrypt/src/siphash.c | 12 +- src/wolfcrypt/src/sp_int.c | 2 +- src/wolfcrypt/src/tfm.c | 8 +- src/wolfcrypt/src/wc_kyber.c | 1247 ++++++- src/wolfcrypt/src/wc_kyber_poly.c | 3020 ++++++++++++++++- src/wolfcrypt/src/wc_lms.c | 2 +- src/wolfcrypt/src/wc_lms_impl.c | 26 + src/wolfssl/internal.h | 3 +- src/wolfssl/quic.h | 9 + src/wolfssl/ssl.h | 2 +- src/wolfssl/test.h | 132 +- src/wolfssl/version.h | 4 +- src/wolfssl/wolfcrypt/pkcs7.h | 14 +- .../wolfcrypt/port/Espressif/esp32-crypt.h | 7 + src/wolfssl/wolfcrypt/settings.h | 19 +- src/wolfssl/wolfcrypt/sha256.h | 4 + src/wolfssl/wolfcrypt/tfm.h | 3 +- src/wolfssl/wolfcrypt/types.h | 1 + src/wolfssl/wolfcrypt/wc_kyber.h | 280 +- src/wolfssl/wolfcrypt/wc_lms.h | 2 +- 45 files changed, 6863 insertions(+), 1375 deletions(-) create mode 100644 examples/wolfssl_version/README.md create mode 100644 examples/wolfssl_version/wolfssl_version.ino create mode 100644 src/wolfcrypt/src/wc_lms_impl.c diff --git a/.gitignore b/.gitignore index ace2698..d6c4114 100644 --- a/.gitignore +++ b/.gitignore @@ -1,425 +1,5 @@ -ctaocrypt/src/src/ -*.swp -*.lo -*.la -*.o -*.patch -*.deps -*.d -*.libs -*.cache -.dirstamp -*.user -configure -config.* -!cmake/config.in -*Debug/ -*Release/ -*.ncb -*.suo -*.sdf -*.opensdf -*.cmd -ipch/ -build-aux/ -rpm/spec -*.rpm -stamp-h -cyassl/options.h -wolfssl/options.h -.build_params -libtool.m4 -aclocal.m4 -aminclude.am -lt*.m4 -Makefile.in -Makefile -depcomp -missing -libtool -tags -.tags* -cyassl-config -wolfssl-config -cyassl.sublime* -fips.h -fips.c -fips_test.c -fips -wolfcrypt_first.c -wolfcrypt_last.c -selftest.c -fipsv2.c -src/async.c -wolfssl/async.h -wolfcrypt/src/async.c -wolfssl/wolfcrypt/async.h -wolfcrypt/src/port/intel/quickassist.c -wolfcrypt/src/port/intel/quickassist_mem.c -wolfcrypt/src/port/cavium/cavium_nitrox.c -wolfssl/wolfcrypt/port/intel/quickassist.h -wolfssl/wolfcrypt/port/intel/quickassist_mem.h -wolfssl/wolfcrypt/port/cavium/cavium_nitrox.h -ctaocrypt/benchmark/benchmark -ctaocrypt/test/testctaocrypt -wolfcrypt/benchmark/benchmark -wolfcrypt/test/testwolfcrypt -examples/async/async_client -examples/async/async_server -examples/benchmark/tls_bench -examples/client/client -examples/echoclient/echoclient -examples/echoserver/echoserver -examples/server/server -examples/sctp/sctp-server -examples/sctp/sctp-server-dtls -examples/sctp/sctp-client -examples/sctp/sctp-client-dtls -examples/asn1/asn1 -examples/pem/pem -server_ready -snifftest -output -mcapi/test -testsuite/testsuite -tests/unit -testsuite/testsuite.test -tests/unit.test -tests/bio_write_test.txt -tests/test-log-dump-to-file.txt -tests/cert_cache.tmp -test-write-dhparams.pem -testsuite/*.der -testsuite/*.pem -testsuite/*.raw -cert.der -cert.pem -certecc.der -certecc.pem -othercert.der -othercert.pem -certeccrsa.der -certeccrsa.pem -ntru-cert.der -ntru-cert.pem -ntru-key.raw -key.der -key.pem -ecc-public-key.der -ecc-key-pkcs8.der -ecc-key.der -ecc-key.pem -certreq.der -certreq.pem -pkcs7cert.der -pkcs7authEnvelopedDataAES128GCM.der -pkcs7authEnvelopedDataAES128GCM_ECDH_SHA1KDF.der -pkcs7authEnvelopedDataAES128GCM_KEKRI.der -pkcs7authEnvelopedDataAES128GCM_ORI.der -pkcs7authEnvelopedDataAES128GCM_PWRI.der -pkcs7authEnvelopedDataAES192GCM.der -pkcs7authEnvelopedDataAES256GCM.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA256KDF.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA256KDF_authAttribs.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA256KDF_bothAttribs.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA256KDF_fw_bothAttribs.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA256KDF_unauthAttribs.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA512KDF.der -pkcs7authEnvelopedDataAES256GCM_ECDH_SHA512KDF_ukm.der -pkcs7authEnvelopedDataAES256GCM_firmwarePkgData.der -pkcs7authEnvelopedDataAES256GCM_IANDS.der -pkcs7authEnvelopedDataAES256GCM_SKID.der -pkcs7compressedData_data_zlib.der -pkcs7compressedData_firmwarePkgData_zlib.der -pkcs7encryptedDataAES128CBC.der -pkcs7encryptedDataAES192CBC.der -pkcs7encryptedDataAES256CBC.der -pkcs7encryptedDataAES256CBC_attribs.der -pkcs7encryptedDataAES256CBC_firmwarePkgData.der -pkcs7encryptedDataAES256CBC_multi_attribs.der -pkcs7encryptedDataDES.der -pkcs7encryptedDataDES3.der -pkcs7envelopedDataAES128CBC.der -pkcs7envelopedDataAES128CBC_ECDH_SHA1KDF.der -pkcs7envelopedDataAES128CBC_KEKRI.der -pkcs7envelopedDataAES128CBC_PWRI.der -pkcs7envelopedDataAES128CBC_ORI.der -pkcs7envelopedDataAES192CBC.der -pkcs7envelopedDataAES256CBC.der -pkcs7envelopedDataAES256CBC_IANDS.der -pkcs7envelopedDataAES256CBC_SKID.der -pkcs7envelopedDataAES256CBC_ECDH_SHA256KDF.der -pkcs7envelopedDataAES256CBC_ECDH_SHA512KDF.der -pkcs7envelopedDataAES256CBC_ECDH_SHA512KDF_ukm.der -pkcs7envelopedDataDES3.der -pkcs7signedData_ECDSA_SHA224.der -pkcs7signedData_ECDSA_SHA256_custom_contentType.der -pkcs7signedData_ECDSA_SHA256.der -pkcs7signedData_ECDSA_SHA256_firmwarePkgData.der -pkcs7signedData_ECDSA_SHA256_SKID.der -pkcs7signedData_ECDSA_SHA384.der -pkcs7signedData_ECDSA_SHA512.der -pkcs7signedData_ECDSA_SHA.der -pkcs7signedData_ECDSA_SHA_noattr.der -pkcs7signedData_RSA_SHA224.der -pkcs7signedData_RSA_SHA256_custom_contentType.der -pkcs7signedData_RSA_SHA256.der -pkcs7signedData_RSA_SHA256_firmwarePkgData.der -pkcs7signedData_RSA_SHA256_SKID.der -pkcs7signedData_RSA_SHA256_with_ca_cert.der -pkcs7signedData_RSA_SHA256_detachedSig.der -pkcs7signedData_RSA_SHA384.der -pkcs7signedData_RSA_SHA512.der -pkcs7signedData_RSA_SHA.der -pkcs7signedData_RSA_SHA_noattr.der -pkcs7signedCompressedFirmwarePkgData_ECDSA_SHA256.der -pkcs7signedCompressedFirmwarePkgData_ECDSA_SHA256_noattr.der -pkcs7signedCompressedFirmwarePkgData_RSA_SHA256.der -pkcs7signedCompressedFirmwarePkgData_RSA_SHA256_noattr.der -pkcs7signedEncryptedFirmwarePkgData_ECDSA_SHA256.der -pkcs7signedEncryptedFirmwarePkgData_ECDSA_SHA256_noattr.der -pkcs7signedEncryptedFirmwarePkgData_RSA_SHA256.der -pkcs7signedEncryptedFirmwarePkgData_RSA_SHA256_noattr.der -pkcs7signedFirmwarePkgData_ECDSA_SHA256.der -pkcs7signedFirmwarePkgData_ECDSA_SHA256_SKID.der -pkcs7signedFirmwarePkgData_ECDSA_SHA256_noattr.der -pkcs7signedFirmwarePkgData_RSA_SHA256.der -pkcs7signedFirmwarePkgData_RSA_SHA256_SKID.der -pkcs7signedFirmwarePkgData_RSA_SHA256_noattr.der -pkcs7signedFirmwarePkgData_RSA_SHA256_with_ca_cert.der -pkcs7signedEncryptedCompressedFirmwarePkgData_ECDSA_SHA256.der -pkcs7signedEncryptedCompressedFirmwarePkgData_ECDSA_SHA256_noattr.der -pkcs7signedEncryptedCompressedFirmwarePkgData_RSA_SHA256.der -pkcs7signedEncryptedCompressedFirmwarePkgData_RSA_SHA256_noattr.der -diff -sslSniffer/sslSnifferTest/tracefile.txt -tracefile.txt -*.gz -*.zip -*.bak -*.dummy -*.xcworkspace -xcuserdata -compile -NTRU_algorithm/ -NTRU/ -build-test/ -build/ -cyassl.xcodeproj/ -cyassl*rc* -autoscan.log -TAGS -.DS_Store -support/cyassl.pc -support/wolfssl.pc -cyassl/ctaocrypt/stamp-h1 -stamp-h1 -clang_output_* -internal.plist -cov-int -cyassl.tgz -*.log -*.trs -IDE/MDK-ARM/Projects/ -IDE/MDK-ARM/STM32F2xx_StdPeriph_Lib/inc -IDE/MDK-ARM/STM32F2xx_StdPeriph_Lib/src -IDE/MDK-ARM/LPC43xx/Drivers/ -IDE/MDK-ARM/LPC43xx/LPC43xx/ -*.gcno -*.gcda -*.gcov -*.dgcov -!linuxkm/Makefile -/Kbuild -linuxkm/*.ko -linuxkm/*.ko.signed -linuxkm/Module.symvers -linuxkm/built-in.a -linuxkm/modules.order -linuxkm/wolfcrypt -linuxkm/libwolfssl.mod -linuxkm/libwolfssl.mod.c -linuxkm/libwolfssl.lds -linuxkm/module_exports.c -linuxkm/linuxkm/get_thread_size - -# autotools generated -scripts/unit.test -wolfcrypt/test/test_paths.h - -# MPLAB Generated Files (OS X) -mcapi/wolfcrypt_mcapi.X/nbproject/Makefile-* -mcapi/wolfcrypt_mcapi.X/nbproject/Package-default.bash -mcapi/wolfcrypt_test.X/nbproject/Makefile-* -mcapi/wolfcrypt_test.X/nbproject/Package-default.bash -mcapi/wolfssl.X/nbproject/Makefile-* -mcapi/wolfssl.X/nbproject/Package-default.bash -mcapi/zlib.X/nbproject/Makefile-* -mcapi/zlib.X/nbproject/Package-default.bash -mplabx/wolfcrypt_benchmark.X/nbproject/Makefile-* -mplabx/wolfcrypt_benchmark.X/nbproject/Package-default.bash -mplabx/wolfcrypt_test.X/nbproject/Makefile-* -mplabx/wolfcrypt_test.X/nbproject/Package-default.bash -mplabx/wolfssl.X/nbproject/Makefile-* -mplabx/wolfssl.X/nbproject/Package-default.bash -mplabx/wolfssl.X/nbproject/private -mplabx/wolfcrypt_test.X/nbproject/private -mplabx/wolfcrypt_benchmark.X/nbproject/private -mplabx/wolfssl.X/dist/default/ -mplabx/wolfcrypt_test.X/dist/default/ -mplabx/wolfcrypt_benchmark.X/dist/default/ -*.dSYM - -# Vagrant folder -.vagrant/ - -# CodeWarrior Generated Files (Windows) -mqx/cyassl/.settings -mqx/cyassl_client/.settings -mqx/cyassl_client/.cwGeneratedFileSetLog -mqx/cyassl_client/SaAnalysispointsManager.apconfig -mqx/util_lib/.settings -mqx/wolfcrypt_test/.settings -mqx/wolfcrypt_test/.cwGeneratedFileSetLog -mqx/wolfcrypt_test/SaAnalysispointsManager.apconfig -mqx/wolfcrypt_benchmark/.settings -mqx/wolfcrypt_benchmark/.cwGeneratedFileSetLog -mqx/wolfcrypt_benchmark/SaAnalysispointsManager.apconfig - -# wolfSSL CSharp wrapper -wrapper/CSharp/x64/ - -# Visual Studio Code Workspace Files -*.vscode -*.userprefs -*.exe -*.dll -.vs -Backup -UpgradeLog.htm -*.aps -*.VC.db -*.filters - -IDE/INTIME-RTOS/Debug_* -IDE/VS-ARM/.vs - -# Hexiwear -IDE/HEXIWEAR/wolfSSL_HW/Debug - -# Linux-SGX -IDE/LINUX-SGX/*.a - -IDE/iotsafe/*.map -IDE/iotsafe/*.elf -IDE/iotsafe/*.bin - -# Binaries -wolfcrypt/src/port/intel/qat_test -/mplabx/wolfssl.X/dist/default/ -/mplabx/wolfcrypt_test.X/dist/default/ - -# Arduino Generated Files -/IDE/ARDUINO/wolfSSL -scripts/memtest.txt -/IDE/ARDUINO/Arduino_README_prepend.md.tmp -/IDE/ARDUINO/library.properties.tmp -/IDE/ARDUINO/library.properties.tmp.backup - -# Doxygen generated files -doc/doxygen_warnings -doc/html -doc/pdf - -# XCODE Index -IDE/XCODE/Index -IDE/**/xcshareddata -IDE/**/DerivedData - -# ARM DS-5 && Eclipse -\.settings/ -\.cproject -\.project -\.autotools - -# Renesas e2studio -/IDE/Renesas/e2studio/Projects/test/src/smc_gen -/IDE/Renesas/e2studio/Projects/test/trash -/IDE/Renesas/e2studio/Projects/test/*.launch -/IDE/Renesas/e2studio/Projects/test/*.scfg - -/IDE/Renesas/e2studio/RX65N/GR-ROSE/.metadata -/IDE/Renesas/e2studio/RX65N/GR-ROSE/smc/src -/IDE/Renesas/e2studio/RX65N/GR-ROSE/smc/trash -/IDE/Renesas/e2studio/RX65N/GR-ROSE/test/src/smc_gen -/IDE/Renesas/e2studio/RX65N/GR-ROSE/test/generate - -/IDE/Renesas/e2studio/RX65N/RSK/.metadata -/IDE/Renesas/e2studio/RX65N/RSK/smc/src -/IDE/Renesas/e2studio/RX65N/RSK/smc/trash -/IDE/Renesas/e2studio/RX65N/RSK/test/src/smc_gen -/IDE/Renesas/e2studio/RX65N/RSK/test/generate - -/IDE/Renesas/e2studio/RX72N/EnvisionKit/.metadata -/IDE/Renesas/e2studio/RX72N/EnvisionKit/smc/src -/IDE/Renesas/e2studio/RX72N/EnvisionKit/smc/trash -/IDE/Renesas/e2studio/RX72N/EnvisionKit/test/src/smc_gen -/IDE/Renesas/e2studio/RX72N/EnvisionKit/test/generate - -# QNX CAAM -/IDE/QNX/example-server/server-tls -/IDE/QNX/example-client/client-tls -/IDE/QNX/example-cmac/cmac-test -/IDE/QNX/CAAM-DRIVER/wolfCrypt - -# Xilinx -/IDE/XilinxSDK/data - -# Emacs -*~ - -# CMake -CMakeFiles/ -CMakeCache.txt -cmake_install.cmake - -# GDB Settings -\.gdbinit - -libFuzzer - -# Pycharm and other IDEs -\.idea - -# FIPS -XXX-fips-test - -# ASYNC -/wolfAsyncCrypt -/async - -# Generated user_settings_asm.h. -user_settings_asm.h - -# VisualGD -**/.visualgdb - -# Espressif sdk config default should be saved in sdkconfig.defaults -# we won't track the actual working sdkconfig files -/IDE/Espressif/**/sdkconfig -/IDE/Espressif/**/sdkconfig.old - -# auto-created CMake backups -**/CMakeLists.txt.old - -# MagicCrypto (ARIA Cipher) -MagicCrypto - -# CMake build directory -/out -/out_temp - -# debian packaging -debian/changelog -debian/control -*.deb +################################################################################ +# This .gitignore file was automatically created by Microsoft(R) Visual Studio. +################################################################################ + +/.vs diff --git a/ChangeLog.md b/ChangeLog.md index 140d730..c3b2475 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,7 +1,97 @@ -# wolfSSL Release X.Y.Z (TBD) +# wolfSSL Release 5.7.0 (Mar 20, 2024) + +Release 5.7.0 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 + +NOTE: In future releases, --enable-des3 (which is disabled by default) will be insufficient in itself to enable DES3 in TLS cipher suites. A new option, --enable-des3-tls-suites, will need to be supplied in addition. This option should only be used in backward compatibility scenarios, as it is inherently insecure. NOTE: This release switches the default ASN.1 parser to the new ASN template code. If the original ASN.1 code is preferred define `WOLFSSL_ASN_ORIGINAL` to use it. See PR #7199. + +## Vulnerabilities +* [High] CVE-2024-0901 Potential denial of service and out of bounds read. Affects TLS 1.3 on the server side when accepting a connection from a malicious TLS 1.3 client. If using TLS 1.3 on the server side it is recommended to update the version of wolfSSL used. Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7099 + + +* [Med] CVE-2024-1545 Fault Injection vulnerability in RsaPrivateDecryption function that potentially allows an attacker that has access to the same system with a victims process to perform a Rowhammer fault injection. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia)." +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7167 + + +* [Med] Fault injection attack with EdDSA signature operations. This affects ed25519 sign operations where the system could be susceptible to Rowhammer attacks. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia). +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7212 + + +## New Feature Additions + +* Added --enable-experimental configure flag to gate out features that are currently experimental. Now liboqs, kyber, lms, xmss, and dual-alg-certs require the --enable-experimental flag. + +### POST QUANTUM SUPPORT ADDITIONS +* Experimental framework for using wolfSSL’s XMSS implementation (PR 7161) +* Experimental framework for using wolfSSL’s LMS implementation (PR 7283) +* Experimental wolfSSL Kyber implementation and assembly optimizations, enabled with --enable-experimental --enable-kyber (PR 7318) +* Experimental support for post quantum dual key/signature certificates. A few known issues and sanitizer checks are in progress with this feature. Enabled with the configure flags --enable-experimental --enable-dual-alg-certs (PR 7112) +* CryptoCb support for PQC algorithms (PR 7110) + +### OTHER FEATURE ADDITIONS +* The Linux kernel module now supports registration of AES-GCM, AES-XTS, AES-CBC, and AES-CFB with the kernel cryptosystem through the new --enable-linuxkm-lkcapi-register option, enabling automatic use of wolfCrypt implementations by the dm-crypt/luks and ESP subsystems. In particular, wolfCrypt AES-XTS with –enable-aesni is faster than the native kernel implementation. +* CryptoCb hook to one-shot CMAC functions (PR 7059) +* BER content streaming support for PKCS7_VerifySignedData and sign/encrypt operations (PR 6961 & 7184) +* IoT-Safe SHA-384 and SHA-512 support (PR 7176) +* I/O callbacks for content and output with PKCS7 bundle sign/encrypt to reduce peak memory usage (PR 7272) +* Microchip PIC24 support and example project (PR 7151) +* AutoSAR shim layer for RNG, SHA256, and AES (PR 7296) +* wolfSSL_CertManagerUnloadIntermediateCerts API to clear intermediate certs added to certificate store (PR 7245) +* Implement SSL_get_peer_signature_nid and SSL_get_peer_signature_type_nid (PR 7236) + + +## Enhancements and Optimizations + +* Remove obsolete user-crypto functionality and Intel IPP support (PR 7097) +* Support for RSA-PSS signatures with CRL use (PR 7119) +* Enhancement for AES-GCM use with Xilsecure on Microblaze (PR 7051) +* Support for crypto cb only build with ECC and NXP CAAM (PR 7269) +* Improve liboqs integration adding locking and init/cleanup functions (PR 7026) +* Prevent memory access before clientSession->serverRow and clientSession->serverIdx are sanitized (PR 7096) +* Enhancements to reproducible build (PR 7267) +* Update Arduino example TLS Client/Server and improve support for ESP32 (PR 7304 & 7177) +* XC32 compiler version 4.x compatibility (PR 7128) +* Porting for build on PlayStation 3 and 4 (PR 7072) +* Improvements for Espressif use; SHA HW/SW selection and use on ESP32-C2/ESP8684, wolfSSL_NewThread() type, component cmake fix, and update TLS client example for ESP8266 (PR 7081, 7173, 7077, 7148, 7240) +* Allow crypto callbacks with SHA-1 HW (PR 7087) +* Update OpenSSH port to version 9.6p1(PR 7203) +* ARM Thumb2 enhancements, AES-GCM support for GCM_SMALL, alignment fix on key, fix for ASM clobber list (PR 7291,7301,7221) +* Expand heap hint support for static memory build with more x509 functions (PR 7136) +* Improving ARMv8 ChaCha20 ASM (alignment) (PR 7182) +* Unknown extension callback wolfSSL_CertManagerSetUnknownExtCallback added to CertManager (PR 7194) +* Implement wc_rng_new_ex for use with devID’s with crypto callback (PR 7271) +* Allow reading 0-RTT data after writing 0.5-RTT data (PR 7102) +* Send alert on bad PSK binder error (PR 7235) +* Enhancements to CMake build files for use with cross compiling (PR 7188) + + +## Fixes + +* Fix for checking result of MAC verify when no AAD is used with AES-GCM and Xilinx Xilsecure (PR 7051) +* Fix for Aria sign use (PR 7082) +* Fix for invalid `dh_ffdhe_test` test case using Intel QuickAssist (PR 7085) +* Fixes for TI AES and SHA on TM4C with HW acceleration and add full AES GCM and CCM support with TLS (PR 7018) +* Fixes for STM32 PKA use with ECC (PR 7098) +* Fixes for TLS 1.3 with crypto callbacks to offload KDF / HMAC operation (PR 7070) +* Fix include path for FSP 3.5 on Renesas RA6M4 (PR 7101) +* Siphash x64 asm fix for use with older compilers (PR 7299) +* Fix for SGX build with SP (PR 7308) +* Fix to Make it mandatory that the cookie is sent back in new ClientHello when seen in a HelloRetryRequest with (PR 7190) +* Fix for wrap around behavior with BIO pairs (PR 7169) +* OCSP fixes for parsing of response correctly when there was a revocation reason and returning correct error value with date checks (PR 7241 & 7255) +* Fix build with `NO_STDIO_FILESYSTEM` and improve checks for `XGETENV` (PR 7150) +* Fix for DTLS sequence number and cookie when downgrading DTLS version (PR 7214) +* Fix for write_dup use with chacha-poly cipher suites (PR 7206) +* Fix for multiple handshake messages in one record failing with OUT_OF_ORDER_E when downgrading from TLS 1.3 to TLS 1.2 (PR 7141) +* Fix for AES ECB build with Thumb and alignment (PR 7094) +* Fix for negotiate handshake until the end in wolfSSL_read/wolfSSL_write if hitting an edge case with want read/write (PR 7237) + # wolfSSL Release 5.6.6 (Dec 19, 2023) Release 5.6.6 has been developed according to wolfSSL's development and QA diff --git a/README b/README index c344bf8..72d5cb3 100644 --- a/README +++ b/README @@ -70,93 +70,99 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.6.6 (Dec 19, 2023) +# wolfSSL Release 5.7.0 (Mar 20, 2024) -Release 5.6.6 has been developed according to wolfSSL's development and QA +Release 5.7.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is being deprecated and will be removed by 2024 +NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 + +NOTE: In future releases, --enable-des3 (which is disabled by default) will be insufficient in itself to enable DES3 in TLS cipher suites. A new option, --enable-des3-tls-suites, will need to be supplied in addition. This option should only be used in backward compatibility scenarios, as it is inherently insecure. + +NOTE: This release switches the default ASN.1 parser to the new ASN template code. If the original ASN.1 code is preferred define `WOLFSSL_ASN_ORIGINAL` to use it. See PR #7199. -REMINDER: When working with AES Block Cipher algorithms, wc_AesInit() should -always be called first to initialize the `Aes` structure, before calling other -Aes API functions. Recently we found several places in our documentation, -comments, and codebase where this pattern was not observed. We have since -fixed this omission in several PRs for this release. ## Vulnerabilities +* [High] CVE-2024-0901 Potential denial of service and out of bounds read. Affects TLS 1.3 on the server side when accepting a connection from a malicious TLS 1.3 client. If using TLS 1.3 on the server side it is recommended to update the version of wolfSSL used. Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7099 -* [Medium] CVE-2023-6935: After review of the previous RSA timing fix in wolfSSL 5.6.4, additional changes were found to be required. A complete resistant change is delivered in this release. This fix is for the Marvin attack, leading to being able to decrypt a saved TLS connection and potentially forge a signature after probing with a very large number of trial connections. This issue is around RSA decryption and affects the optional static RSA cipher suites on the server side, which are considered weak, not recommended to be used and are off by default in wolfSSL (even with --enable-all). Static RSA cipher suites were also removed from the TLS 1.3 protocol and are only present in TLS 1.2 and lower. All padding versions of RSA decrypt are affected since the code under review is outside of the padding processing. Information about the private keys is NOT compromised in affected code. It is recommended to disable static RSA cipher suites and update the version of wolfSSL used if using RSA private decryption alone outside of TLS. Thanks to Hubert Kario for the report. The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6955. -* [Low] CVE-2023-6936: A potential heap overflow read is possible in servers connecting over TLS 1.3 when the optional WOLFSSL_CALLBACKS has been defined. The out of bounds read can occur when a server receives a malicious malformed ClientHello. Users should either discontinue use of WOLFSSL_CALLBACKS on the server side or update versions of wolfSSL to 5.6.6. Thanks to the tlspuffin fuzzer team for the report which was designed and developed by; Lucca Hirschi (Inria, LORIA), Steve Kremer (Inria, LORIA), and Max Ammann (Trail of Bits). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6949. +* [Med] CVE-2024-1545 Fault Injection vulnerability in RsaPrivateDecryption function that potentially allows an attacker that has access to the same system with a victims process to perform a Rowhammer fault injection. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia)." +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7167 -* [Low] A side channel vulnerability with AES T-Tables is possible in a very controlled environment where precision sub-cache-line inspection can happen, such as inside an Intel SGX enclave. This can lead to recovery of the AES key. To prevent this type of attack, wolfSSL added an AES bitsliced implementation which can be enabled with the “--enable-aes-bitsliced” configure option. Thanks to Florian Sieck, Zhiyuan Zhang, Sebastian Berndt, Chitchanok Chuengsatiansup, Thomas Eisenbarth, and Yuval Yarom for the report (Universities of Lübeck, Melbourne, Adelaide and Bochum). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6854. -* [Low] CVE-2023-6937: wolfSSL prior to 5.6.6 did not check that messages in a single (D)TLS record do not span key boundaries. As a result, it was possible to combine (D)TLS messages using different keys into one (D)TLS record. The most extreme edge case is that, in (D)TLS 1.3, it was possible that an unencrypted (D)TLS 1.3 record from the server containing first a ServerHello message and then the rest of the first server flight would be accepted by a wolfSSL client. In (D)TLS 1.3 the handshake is encrypted after the ServerHello but a wolfSSL client would accept an unencrypted flight from the server. This does not compromise key negotiation and authentication so it is assigned a low severity rating. Thanks to Johannes Wilson for the report (Sectra Communications and Linköping University). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/7029. +* [Med] Fault injection attack with EdDSA signature operations. This affects ed25519 sign operations where the system could be susceptible to Rowhammer attacks. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia). +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7212 + ## New Feature Additions -* Build option for disabling CRL date checks (WOLFSSL_NO_CRL_DATE_CHECK) (PR 6927) -* Support for STM32WL55 and improvements to PKA ECC support (PR 6937) -* Add option to skip cookie exchange on DTLS 1.3 session resumption (PR 6929) -* Add implementation of SRTP KDF and SRTCP KDF (--enable-srtp-kdf) (PR 6888) -* Add wolfSSL_EXTENDED_KEY_USAGE_free() (PR 6916) -* Add AES bitsliced implementation that is cache attack safe (--enable-aes-bitsliced) (PR 6854) -* Add memcached support and automated testing (PR 6430, 7022) -* Add Hardware Encryption Acceleration for ESP32-C3, ESP32-C6, and ESP32-S2 (PR 6990) -* Add (D)TLS 1.3 support for 0.5-RTT data (PR 7010) +* Added --enable-experimental configure flag to gate out features that are currently experimental. Now liboqs, kyber, lms, xmss, and dual-alg-certs require the --enable-experimental flag. + +### POST QUANTUM SUPPORT ADDITIONS +* Experimental framework for using wolfSSL’s XMSS implementation (PR 7161) +* Experimental framework for using wolfSSL’s LMS implementation (PR 7283) +* Experimental wolfSSL Kyber implementation and assembly optimizations, enabled with --enable-experimental --enable-kyber (PR 7318) +* Experimental support for post quantum dual key/signature certificates. A few known issues and sanitizer checks are in progress with this feature. Enabled with the configure flags --enable-experimental --enable-dual-alg-certs (PR 7112) +* CryptoCb support for PQC algorithms (PR 7110) + +### OTHER FEATURE ADDITIONS +* The Linux kernel module now supports registration of AES-GCM, AES-XTS, AES-CBC, and AES-CFB with the kernel cryptosystem through the new --enable-linuxkm-lkcapi-register option, enabling automatic use of wolfCrypt implementations by the dm-crypt/luks and ESP subsystems. In particular, wolfCrypt AES-XTS with –enable-aesni is faster than the native kernel implementation. +* CryptoCb hook to one-shot CMAC functions (PR 7059) +* BER content streaming support for PKCS7_VerifySignedData and sign/encrypt operations (PR 6961 & 7184) +* IoT-Safe SHA-384 and SHA-512 support (PR 7176) +* I/O callbacks for content and output with PKCS7 bundle sign/encrypt to reduce peak memory usage (PR 7272) +* Microchip PIC24 support and example project (PR 7151) +* AutoSAR shim layer for RNG, SHA256, and AES (PR 7296) +* wolfSSL_CertManagerUnloadIntermediateCerts API to clear intermediate certs added to certificate store (PR 7245) +* Implement SSL_get_peer_signature_nid and SSL_get_peer_signature_type_nid (PR 7236) + ## Enhancements and Optimizations -* Better built in testing of “--sys-ca-certs” configure option (PR 6910) -* Updated CMakeLists.txt for Espressif wolfSSL component usage (PR 6877) -* Disable TLS 1.1 by default (unless SSL 3.0 or TLS 1.0 is enabled) (PR 6946) -* Add “--enable-quic” to “--enable-all” configure option (PR 6957) -* Add support to SP C implementation for RSA exponent up to 64-bits (PR 6959) -* Add result of “HAVE___UINT128_T” to options.h for CMake builds (PR 6965) -* Add optimized assembly for AES-GCM on ARM64 using hardware crypto instructions (PR 6967) -* Add built-in cipher suite tests for DTLS 1.3 PQC (PR 6952) -* Add wolfCrypt test and unit test to ctest (PR 6977) -* Move OpenSSL compatibility crypto APIs into ssl_crypto.c file (PR 6935) -* Validate time generated from XGMTIME() (PR 6958) -* Allow wolfCrypt benchmark to run with microsecond accuracy (PR 6868) -* Add GitHub Actions testing with nginx 1.24.0 (PR 6982) -* Allow encoding of CA:FALSE BasicConstraint during cert generation (PR 6953) -* Add CMake option to enable DTLS-SRTP (PR 6991) -* Add CMake options for enabling QUIC and cURL (PR 7049) -* Improve RSA blinding to make code more constant time (PR 6955) -* Refactor AES-NI implementation macros to allow dynamic fallback to C (PR 6981) -* Default to native Windows threading API on MinGW (PR 7015) -* Return better error codes from OCSP response check (PR 7028) -* Updated Espressif ESP32 TLS client and server examples (PR 6844) -* Add/clean up support for ESP-IDF v5.1 for a variety of ESP32 chips (PR 7035, 7037) -* Add API to choose dynamic certs based on client ciphers/sigalgs (PR 6963) -* Improve Arduino IDE 1.5 project file to match recursive style (PR 7007) -* Simplify and improve apple-universal build script (PR 7025) +* Remove obsolete user-crypto functionality and Intel IPP support (PR 7097) +* Support for RSA-PSS signatures with CRL use (PR 7119) +* Enhancement for AES-GCM use with Xilsecure on Microblaze (PR 7051) +* Support for crypto cb only build with ECC and NXP CAAM (PR 7269) +* Improve liboqs integration adding locking and init/cleanup functions (PR 7026) +* Prevent memory access before clientSession->serverRow and clientSession->serverIdx are sanitized (PR 7096) +* Enhancements to reproducible build (PR 7267) +* Update Arduino example TLS Client/Server and improve support for ESP32 (PR 7304 & 7177) +* XC32 compiler version 4.x compatibility (PR 7128) +* Porting for build on PlayStation 3 and 4 (PR 7072) +* Improvements for Espressif use; SHA HW/SW selection and use on ESP32-C2/ESP8684, wolfSSL_NewThread() type, component cmake fix, and update TLS client example for ESP8266 (PR 7081, 7173, 7077, 7148, 7240) +* Allow crypto callbacks with SHA-1 HW (PR 7087) +* Update OpenSSH port to version 9.6p1(PR 7203) +* ARM Thumb2 enhancements, AES-GCM support for GCM_SMALL, alignment fix on key, fix for ASM clobber list (PR 7291,7301,7221) +* Expand heap hint support for static memory build with more x509 functions (PR 7136) +* Improving ARMv8 ChaCha20 ASM (alignment) (PR 7182) +* Unknown extension callback wolfSSL_CertManagerSetUnknownExtCallback added to CertManager (PR 7194) +* Implement wc_rng_new_ex for use with devID’s with crypto callback (PR 7271) +* Allow reading 0-RTT data after writing 0.5-RTT data (PR 7102) +* Send alert on bad PSK binder error (PR 7235) +* Enhancements to CMake build files for use with cross compiling (PR 7188) + ## Fixes -* Fix for async edge case with Intel QuickAssist/Cavium Nitrox (PR 6931) -* Fix for building PKCS#7 with RSA disabled (PR 6902) -* Fix for advancing output pointer in wolfSSL_i2d_X509() (PR 6891) -* Fix for EVP_EncodeBlock() appending a newline (PR 6900) -* Fix for wolfSSL_RSA_verify_PKCS1_PSS() with RSA_PSS_SALTLEN_AUTO (PR 6938) -* Fixes for CODESonar reports around isalpha() and isalnum() calls (PR 6810) -* Fix for SP ARM64 integer math to avoid compiler optimization issues (PR 6942) -* Fix for SP Thumb2 inline assembly to add IAR build support (PR 6943, 6971) -* Fix for SP Thumb2 to make functions not inlined (PR 6993) -* Fix for SP Cortex-M assembly large build with IAR (PR 6954) -* Fix for SP ARM64 assembly montgomery reduction by 4 (PR 6947) -* Fix for SP ARM64 P-256 for not inlining functions for iOS compatibility (PR 6979) -* Fix for WOLFSSL_CALLBACKS and potential memory error (PR 6949) -* Fixes for wolfSSL’s Zephyr OS port (PR 6930) -* Fix for build errors when building for NXP mmCAU (FREESCALE_MMCAU) (PR 6970) -* Fix for TLS 1.3 SendBuffered() return code in non-blocking mode (PR 7001) -* Fix for TLS Hmac_UpdateFinal() when padding byte is invalid (PR 6998) -* Fix for ARMv8 AES-GCM streaming to check size of IV before storing (PR 6996) -* Add missing calls to wc_AesInit() before wc_AesSetKey() (PR 7011) -* Fix build errors with DTLS 1.3 enabled but TLS 1.2 disabled (PR 6976) -* Fixes for building wolfSSL in Visual Studio (PR 7040) +* Fix for checking result of MAC verify when no AAD is used with AES-GCM and Xilinx Xilsecure (PR 7051) +* Fix for Aria sign use (PR 7082) +* Fix for invalid `dh_ffdhe_test` test case using Intel QuickAssist (PR 7085) +* Fixes for TI AES and SHA on TM4C with HW acceleration and add full AES GCM and CCM support with TLS (PR 7018) +* Fixes for STM32 PKA use with ECC (PR 7098) +* Fixes for TLS 1.3 with crypto callbacks to offload KDF / HMAC operation (PR 7070) +* Fix include path for FSP 3.5 on Renesas RA6M4 (PR 7101) +* Siphash x64 asm fix for use with older compilers (PR 7299) +* Fix for SGX build with SP (PR 7308) +* Fix to Make it mandatory that the cookie is sent back in new ClientHello when seen in a HelloRetryRequest with (PR 7190) +* Fix for wrap around behavior with BIO pairs (PR 7169) +* OCSP fixes for parsing of response correctly when there was a revocation reason and returning correct error value with date checks (PR 7241 & 7255) +* Fix build with `NO_STDIO_FILESYSTEM` and improve checks for `XGETENV` (PR 7150) +* Fix for DTLS sequence number and cookie when downgrading DTLS version (PR 7214) +* Fix for write_dup use with chacha-poly cipher suites (PR 7206) +* Fix for multiple handshake messages in one record failing with OUT_OF_ORDER_E when downgrading from TLS 1.3 to TLS 1.2 (PR 7141) +* Fix for AES ECB build with Thumb and alignment (PR 7094) +* Fix for negotiate handshake until the end in wolfSSL_read/wolfSSL_write if hitting an edge case with want read/write (PR 7237) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/README.md b/README.md index 358b387..9b2498f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.6.6 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.0 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -88,93 +88,98 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.6.6 (Dec 19, 2023) +# wolfSSL Release 5.7.0 (Mar 20, 2024) -Release 5.6.6 has been developed according to wolfSSL's development and QA +Release 5.7.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is being deprecated and will be removed by 2024 +NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -REMINDER: When working with AES Block Cipher algorithms, `wc_AesInit()` should -always be called first to initialize the `Aes` structure, before calling other -Aes API functions. Recently we found several places in our documentation, -comments, and codebase where this pattern was not observed. We have since -fixed this omission in several PRs for this release. +NOTE: In future releases, --enable-des3 (which is disabled by default) will be insufficient in itself to enable DES3 in TLS cipher suites. A new option, --enable-des3-tls-suites, will need to be supplied in addition. This option should only be used in backward compatibility scenarios, as it is inherently insecure. + +NOTE: This release switches the default ASN.1 parser to the new ASN template code. If the original ASN.1 code is preferred define `WOLFSSL_ASN_ORIGINAL` to use it. See PR #7199. ## Vulnerabilities +* [High] CVE-2024-0901 Potential denial of service and out of bounds read. Affects TLS 1.3 on the server side when accepting a connection from a malicious TLS 1.3 client. If using TLS 1.3 on the server side it is recommended to update the version of wolfSSL used. Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7099 + -* [Medium] CVE-2023-6935: After review of the previous RSA timing fix in wolfSSL 5.6.4, additional changes were found to be required. A complete resistant change is delivered in this release. This fix is for the Marvin attack, leading to being able to decrypt a saved TLS connection and potentially forge a signature after probing with a very large number of trial connections. This issue is around RSA decryption and affects the optional static RSA cipher suites on the server side, which are considered weak, not recommended to be used and are off by default in wolfSSL (even with `--enable-all`). Static RSA cipher suites were also removed from the TLS 1.3 protocol and are only present in TLS 1.2 and lower. All padding versions of RSA decrypt are affected since the code under review is outside of the padding processing. Information about the private keys is NOT compromised in affected code. It is recommended to disable static RSA cipher suites and update the version of wolfSSL used if using RSA private decryption alone outside of TLS. Thanks to Hubert Kario for the report. The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6955. +* [Med] CVE-2024-1545 Fault Injection vulnerability in RsaPrivateDecryption function that potentially allows an attacker that has access to the same system with a victims process to perform a Rowhammer fault injection. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia)." +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7167 -* [Low] CVE-2023-6936: A potential heap overflow read is possible in servers connecting over TLS 1.3 when the optional `WOLFSSL_CALLBACKS` has been defined. The out of bounds read can occur when a server receives a malicious malformed ClientHello. Users should either discontinue use of `WOLFSSL_CALLBACKS` on the server side or update versions of wolfSSL to 5.6.6. Thanks to the tlspuffin fuzzer team for the report which was designed and developed by; Lucca Hirschi (Inria, LORIA), Steve Kremer (Inria, LORIA), and Max Ammann (Trail of Bits). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6949. -* [Low] A side channel vulnerability with AES T-Tables is possible in a very controlled environment where precision sub-cache-line inspection can happen, such as inside an Intel SGX enclave. This can lead to recovery of the AES key. To prevent this type of attack, wolfSSL added an AES bitsliced implementation which can be enabled with the “`--enable-aes-bitsliced`” configure option. Thanks to Florian Sieck, Zhiyuan Zhang, Sebastian Berndt, Chitchanok Chuengsatiansup, Thomas Eisenbarth, and Yuval Yarom for the report (Universities of Lübeck, Melbourne, Adelaide and Bochum). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6854. +* [Med] Fault injection attack with EdDSA signature operations. This affects ed25519 sign operations where the system could be susceptible to Rowhammer attacks. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia). +Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7212 -* [Low] CVE-2023-6937: wolfSSL prior to 5.6.6 did not check that messages in a single (D)TLS record do not span key boundaries. As a result, it was possible to combine (D)TLS messages using different keys into one (D)TLS record. The most extreme edge case is that, in (D)TLS 1.3, it was possible that an unencrypted (D)TLS 1.3 record from the server containing first a ServerHello message and then the rest of the first server flight would be accepted by a wolfSSL client. In (D)TLS 1.3 the handshake is encrypted after the ServerHello but a wolfSSL client would accept an unencrypted flight from the server. This does not compromise key negotiation and authentication so it is assigned a low severity rating. Thanks to Johannes Wilson for the report (Sectra Communications and Linköping University). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/7029. ## New Feature Additions -* Build option for disabling CRL date checks (`WOLFSSL_NO_CRL_DATE_CHECK`) (PR 6927) -* Support for STM32WL55 and improvements to PKA ECC support (PR 6937) -* Add option to skip cookie exchange on DTLS 1.3 session resumption (PR 6929) -* Add implementation of SRTP KDF and SRTCP KDF (`--enable-srtp-kdf`) (PR 6888) -* Add `wolfSSL_EXTENDED_KEY_USAGE_free()` (PR 6916) -* Add AES bitsliced implementation that is cache attack safe (`--enable-aes-bitsliced`) (PR 6854) -* Add memcached support and automated testing (PR 6430, 7022) -* Add Hardware Encryption Acceleration for ESP32-C3, ESP32-C6, and ESP32-S2 (PR 6990) -* Add (D)TLS 1.3 support for 0.5-RTT data (PR 7010) +* Added --enable-experimental configure flag to gate out features that are currently experimental. Now liboqs, kyber, lms, xmss, and dual-alg-certs require the --enable-experimental flag. + +### POST QUANTUM SUPPORT ADDITIONS +* Experimental framework for using wolfSSL’s XMSS implementation (PR 7161) +* Experimental framework for using wolfSSL’s LMS implementation (PR 7283) +* Experimental wolfSSL Kyber implementation and assembly optimizations, enabled with --enable-experimental --enable-kyber (PR 7318) +* Experimental support for post quantum dual key/signature certificates. A few known issues and sanitizer checks are in progress with this feature. Enabled with the configure flags --enable-experimental --enable-dual-alg-certs (PR 7112) +* CryptoCb support for PQC algorithms (PR 7110) + +### OTHER FEATURE ADDITIONS +* The Linux kernel module now supports registration of AES-GCM, AES-XTS, AES-CBC, and AES-CFB with the kernel cryptosystem through the new --enable-linuxkm-lkcapi-register option, enabling automatic use of wolfCrypt implementations by the dm-crypt/luks and ESP subsystems. In particular, wolfCrypt AES-XTS with –enable-aesni is faster than the native kernel implementation. +* CryptoCb hook to one-shot CMAC functions (PR 7059) +* BER content streaming support for PKCS7_VerifySignedData and sign/encrypt operations (PR 6961 & 7184) +* IoT-Safe SHA-384 and SHA-512 support (PR 7176) +* I/O callbacks for content and output with PKCS7 bundle sign/encrypt to reduce peak memory usage (PR 7272) +* Microchip PIC24 support and example project (PR 7151) +* AutoSAR shim layer for RNG, SHA256, and AES (PR 7296) +* wolfSSL_CertManagerUnloadIntermediateCerts API to clear intermediate certs added to certificate store (PR 7245) +* Implement SSL_get_peer_signature_nid and SSL_get_peer_signature_type_nid (PR 7236) + ## Enhancements and Optimizations -* Better built in testing of “`--sys-ca-certs`” configure option (PR 6910) -* Updated CMakeLists.txt for Espressif wolfSSL component usage (PR 6877) -* Disable TLS 1.1 by default (unless SSL 3.0 or TLS 1.0 is enabled) (PR 6946) -* Add “`--enable-quic`” to “`--enable-all`” configure option (PR 6957) -* Add support to SP C implementation for RSA exponent up to 64-bits (PR 6959) -* Add result of “`HAVE___UINT128_T`” to options.h for CMake builds (PR 6965) -* Add optimized assembly for AES-GCM on ARM64 using hardware crypto instructions (PR 6967) -* Add built-in cipher suite tests for DTLS 1.3 PQC (PR 6952) -* Add wolfCrypt test and unit test to ctest (PR 6977) -* Move OpenSSL compatibility crypto APIs into `ssl_crypto.c` file (PR 6935) -* Validate time generated from XGMTIME() (PR 6958) -* Allow wolfCrypt benchmark to run with microsecond accuracy (PR 6868) -* Add GitHub Actions testing with nginx 1.24.0 (PR 6982) -* Allow encoding of CA:FALSE BasicConstraint during cert generation (PR 6953) -* Add CMake option to enable DTLS-SRTP (PR 6991) -* Add CMake options for enabling QUIC and cURL (PR 7049) -* Improve RSA blinding to make code more constant time (PR 6955) -* Refactor AES-NI implementation macros to allow dynamic fallback to C (PR 6981) -* Default to native Windows threading API on MinGW (PR 7015) -* Return better error codes from OCSP response check (PR 7028) -* Updated Espressif ESP32 TLS client and server examples (PR 6844) -* Add/clean up support for ESP-IDF v5.1 for a variety of ESP32 chips (PR 7035, 7037) -* Add API to choose dynamic certs based on client ciphers/sigalgs (PR 6963) -* Improve Arduino IDE 1.5 project file to match recursive style (PR 7007) -* Simplify and improve apple-universal build script (PR 7025) +* Remove obsolete user-crypto functionality and Intel IPP support (PR 7097) +* Support for RSA-PSS signatures with CRL use (PR 7119) +* Enhancement for AES-GCM use with Xilsecure on Microblaze (PR 7051) +* Support for crypto cb only build with ECC and NXP CAAM (PR 7269) +* Improve liboqs integration adding locking and init/cleanup functions (PR 7026) +* Prevent memory access before clientSession->serverRow and clientSession->serverIdx are sanitized (PR 7096) +* Enhancements to reproducible build (PR 7267) +* Update Arduino example TLS Client/Server and improve support for ESP32 (PR 7304 & 7177) +* XC32 compiler version 4.x compatibility (PR 7128) +* Porting for build on PlayStation 3 and 4 (PR 7072) +* Improvements for Espressif use; SHA HW/SW selection and use on ESP32-C2/ESP8684, wolfSSL_NewThread() type, component cmake fix, and update TLS client example for ESP8266 (PR 7081, 7173, 7077, 7148, 7240) +* Allow crypto callbacks with SHA-1 HW (PR 7087) +* Update OpenSSH port to version 9.6p1(PR 7203) +* ARM Thumb2 enhancements, AES-GCM support for GCM_SMALL, alignment fix on key, fix for ASM clobber list (PR 7291,7301,7221) +* Expand heap hint support for static memory build with more x509 functions (PR 7136) +* Improving ARMv8 ChaCha20 ASM (alignment) (PR 7182) +* Unknown extension callback wolfSSL_CertManagerSetUnknownExtCallback added to CertManager (PR 7194) +* Implement wc_rng_new_ex for use with devID’s with crypto callback (PR 7271) +* Allow reading 0-RTT data after writing 0.5-RTT data (PR 7102) +* Send alert on bad PSK binder error (PR 7235) +* Enhancements to CMake build files for use with cross compiling (PR 7188) + ## Fixes -* Fix for async edge case with Intel QuickAssist/Cavium Nitrox (PR 6931) -* Fix for building PKCS#7 with RSA disabled (PR 6902) -* Fix for advancing output pointer in `wolfSSL_i2d_X509()` (PR 6891) -* Fix for `EVP_EncodeBlock()` appending a newline (PR 6900) -* Fix for `wolfSSL_RSA_verify_PKCS1_PSS()` with `RSA_PSS_SALTLEN_AUTO` (PR 6938) -* Fixes for CODESonar reports around `isalpha()` and `isalnum()` calls (PR 6810) -* Fix for SP ARM64 integer math to avoid compiler optimization issues (PR 6942) -* Fix for SP Thumb2 inline assembly to add IAR build support (PR 6943, 6971) -* Fix for SP Thumb2 to make functions not inlined (PR 6993) -* Fix for SP Cortex-M assembly large build with IAR (PR 6954) -* Fix for SP ARM64 assembly montgomery reduction by 4 (PR 6947) -* Fix for SP ARM64 P-256 for not inlining functions for iOS compatibility (PR 6979) -* Fix for `WOLFSSL_CALLBACKS` and potential memory error (PR 6949) -* Fixes for wolfSSL’s Zephyr OS port (PR 6930) -* Fix for build errors when building for NXP mmCAU (`FREESCALE_MMCAU`) (PR 6970) -* Fix for TLS 1.3 `SendBuffered()` return code in non-blocking mode (PR 7001) -* Fix for TLS `Hmac_UpdateFinal()` when padding byte is invalid (PR 6998) -* Fix for ARMv8 AES-GCM streaming to check size of IV before storing (PR 6996) -* Add missing calls to `wc_AesInit()` before `wc_AesSetKey()` (PR 7011) -* Fix build errors with DTLS 1.3 enabled but TLS 1.2 disabled (PR 6976) -* Fixes for building wolfSSL in Visual Studio (PR 7040) +* Fix for checking result of MAC verify when no AAD is used with AES-GCM and Xilinx Xilsecure (PR 7051) +* Fix for Aria sign use (PR 7082) +* Fix for invalid `dh_ffdhe_test` test case using Intel QuickAssist (PR 7085) +* Fixes for TI AES and SHA on TM4C with HW acceleration and add full AES GCM and CCM support with TLS (PR 7018) +* Fixes for STM32 PKA use with ECC (PR 7098) +* Fixes for TLS 1.3 with crypto callbacks to offload KDF / HMAC operation (PR 7070) +* Fix include path for FSP 3.5 on Renesas RA6M4 (PR 7101) +* Siphash x64 asm fix for use with older compilers (PR 7299) +* Fix for SGX build with SP (PR 7308) +* Fix to Make it mandatory that the cookie is sent back in new ClientHello when seen in a HelloRetryRequest with (PR 7190) +* Fix for wrap around behavior with BIO pairs (PR 7169) +* OCSP fixes for parsing of response correctly when there was a revocation reason and returning correct error value with date checks (PR 7241 & 7255) +* Fix build with `NO_STDIO_FILESYSTEM` and improve checks for `XGETENV` (PR 7150) +* Fix for DTLS sequence number and cookie when downgrading DTLS version (PR 7214) +* Fix for write_dup use with chacha-poly cipher suites (PR 7206) +* Fix for multiple handshake messages in one record failing with OUT_OF_ORDER_E when downgrading from TLS 1.3 to TLS 1.2 (PR 7141) +* Fix for AES ECB build with Thumb and alignment (PR 7094) +* Fix for negotiate handshake until the end in wolfSSL_read/wolfSSL_write if hitting an edge case with want read/write (PR 7237) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ @@ -203,3 +208,51 @@ More info can be found on-line at: https://wolfssl.com/wolfSSL/Docs.html [wolfSSL Vulnerabilities](https://www.wolfssl.com/docs/security-vulnerabilities/) [Additional wolfSSL Examples](https://github.com/wolfssl/wolfssl-examples) + +# Directory structure + +``` + +├── certs [Certificates used in tests and examples] +├── cmake [Cmake build utilities] +├── debian [Debian packaging files] +├── doc [Documentation for wolfSSL (Doxygen)] +├── Docker [Prebuilt Docker environments] +├── examples [wolfSSL examples] +│   ├── asn1 [ASN.1 printing example] +│   ├── async [Asynchronous Cryptography example] +│   ├── benchmark [TLS benchmark example] +│   ├── client [Client example] +│   ├── configs [Example build configurations] +│   ├── echoclient [Echoclient example] +│   ├── echoserver [Echoserver example] +│   ├── pem [Example for convert between PEM and DER] +│   ├── sctp [Servers and clients that demonstrate wolfSSL's DTLS-SCTP support] +│   └── server [Server example] +├── IDE [Contains example projects for various development environments] +├── linuxkm [Linux Kernel Module implementation] +├── m4 [Autotools utilities] +├── mcapi [wolfSSL MPLAB X Project Files] +├── mplabx [wolfSSL MPLAB X Project Files] +├── mqx [wolfSSL Freescale CodeWarrior Project Files] +├── rpm [RPM packaging metadata] +├── RTOS +│   └── nuttx [Port of wolfSSL for NuttX] +├── scripts [Testing scripts] +├── src [wolfSSL source code] +├── sslSniffer [wolfSSL sniffer can be used to passively sniff SSL traffic] +├── support [Contains the pkg-config file] +├── tests [Unit and configuration testing] +├── testsuite [Test application that orchestrates tests] +├── tirtos [Port of wolfSSL for TI RTOS] +├── wolfcrypt [The wolfCrypt component] +│   ├── benchmark [Cryptography benchmarking application] +│   ├── src [wolfCrypt source code] +│   │   └── port [Supported hardware acceleration ports] +│   └── test [Cryptography testing application] +├── wolfssl [Header files] +│   ├── openssl [Compatibility layer headers] +│   └── wolfcrypt [Header files] +├── wrapper [wolfSSL language wrappers] +└── zephyr [Port of wolfSSL for Zephyr RTOS] +``` diff --git a/examples/wolfssl_client/wolfssl_client.ino b/examples/wolfssl_client/wolfssl_client.ino index 514c7dc..21a84de 100644 --- a/examples/wolfssl_client/wolfssl_client.ino +++ b/examples/wolfssl_client/wolfssl_client.ino @@ -43,7 +43,7 @@ Tested with: #define REPEAT_CONNECTION 0 /* Edit this with your other TLS host server address to connect to: */ -#define WOLFSSL_TLS_SERVER_HOST "192.168.1.34" +#define WOLFSSL_TLS_SERVER_HOST "192.168.1.39" /* wolfssl TLS examples communicate on port 11111 */ #define WOLFSSL_PORT 11111 @@ -58,7 +58,7 @@ Tested with: #define RECONNECT_ATTEMPTS 20 /* Optional stress test. Define to consume memory until exhausted: */ -#define MEMORY_STRESS_TEST +/* #define MEMORY_STRESS_TEST */ /* Choose client or server example, not both. */ #define WOLFSSL_CLIENT_EXAMPLE @@ -68,12 +68,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - const char* ssid PROGMEM = CONFIG_ESP_WIFI_SSID; - const char* password PROGMEM = CONFIG_ESP_WIFI_PASSWORD; + static const char* ssid PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char* password PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - const char* ssid PROGMEM = "your_SSID"; - const char* password PROGMEM = "your_PASSWORD"; + static const char* ssid PROGMEM = "your_SSID"; + static const char* password PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -135,7 +135,7 @@ Tested with: #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define USING_WIFI #include - #include + #include /* Needs Arduino WiFiNINA library installed manually */ WiFiClient client; #elif defined(ARDUINO_ARCH_RP2040) @@ -176,21 +176,20 @@ Tested with: || defined(HAVE_SERVER_RENEGOTIATION_INFO) #endif -const char host[] PROGMEM = WOLFSSL_TLS_SERVER_HOST; /* server to connect to */ -const int port PROGMEM = WOLFSSL_PORT; /* port on server to connect to */ -const int serial_baud PROGMEM = SERIAL_BAUD; /* local serial port to monitor */ +static const char host[] PROGMEM = WOLFSSL_TLS_SERVER_HOST; /* server to connect to */ +static const int port PROGMEM = WOLFSSL_PORT; /* port on server to connect to */ -WOLFSSL_CTX* ctx = NULL; -WOLFSSL* ssl = NULL; -char* wc_error_message = (char*)malloc(80 + 1); -char errBuf[80]; +static WOLFSSL_CTX* ctx = NULL; +static WOLFSSL* ssl = NULL; +static char* wc_error_message = (char*)malloc(80 + 1); +static char errBuf[80]; #if defined(MEMORY_STRESS_TEST) #define MEMORY_STRESS_ITERATIONS 100 #define MEMORY_STRESS_BLOCK_SIZE 1024 #define MEMORY_STRESS_INITIAL (4*1024) - char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ - int mem_ctr = 0; + static char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ + static int mem_ctr = 0; #endif static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); @@ -202,8 +201,8 @@ static int lng_index PROGMEM = 0; /* 0 = English */ #include extern char _end; extern "C" char *sbrk(int i); - char *ramstart=(char *)0x20070000; - char *ramend=(char *)0x20088000; + static char *ramstart=(char *)0x20070000; + static char *ramend=(char *)0x20088000; #endif /*****************************************************************************/ @@ -372,28 +371,31 @@ int setup_network(void) { #if defined(USING_WIFI) int status = WL_IDLE_STATUS; - if (WiFi.status() == WL_NO_MODULE) { - Serial.println("Communication with WiFi module failed!"); - /* don't continue if no network */ - while (true) ; - } - - String fv = WiFi.firmwareVersion(); - if (fv < WIFI_FIRMWARE_LATEST_VERSION) { - Serial.println("Please upgrade the firmware"); - } - /* The ESP8266 & ESP32 support both AP and STA. We'll use STA: */ #if defined(ESP8266) || defined(ESP32) WiFi.mode(WIFI_STA); + #else + String fv; + if (WiFi.status() == WL_NO_MODULE) { + Serial.println("Communication with WiFi module failed!"); + /* don't continue if no network */ + while (true) ; + } + + fv = WiFi.firmwareVersion(); + if (fv < WIFI_FIRMWARE_LATEST_VERSION) { + Serial.println("Please upgrade the firmware"); + } #endif Serial.print(F("Connecting to WiFi ")); Serial.print(ssid); + status = WiFi.begin(ssid, password); while (status != WL_CONNECTED) { - status = WiFi.begin(ssid, password); - delay(5000); + delay(1000); Serial.print(F(".")); + Serial.print(status); + status = WiFi.status(); } Serial.println(F(" Connected!")); @@ -598,9 +600,12 @@ int setup_certificates(void) { /*****************************************************************************/ /*****************************************************************************/ void setup(void) { - Serial.begin(serial_baud); - while (!Serial) { + int i = 0; + Serial.begin(SERIAL_BAUD); + while (!Serial && (i < 10)) { /* wait for serial port to connect. Needed for native USB port only */ + delay(1000); + i++; } Serial.println(F("")); Serial.println(F("")); @@ -623,10 +628,10 @@ void setup(void) { setup_hardware(); - setup_datetime(); - setup_network(); + setup_datetime(); + setup_wolfssl(); setup_certificates(); diff --git a/examples/wolfssl_server/wolfssl_server.ino b/examples/wolfssl_server/wolfssl_server.ino index 7471362..3a89432 100644 --- a/examples/wolfssl_server/wolfssl_server.ino +++ b/examples/wolfssl_server/wolfssl_server.ino @@ -68,12 +68,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - const char* ssid PROGMEM = CONFIG_ESP_WIFI_SSID; - const char* password PROGMEM = CONFIG_ESP_WIFI_PASSWORD; + static const char* ssid PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char* password PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - const char* ssid PROGMEM = "your_SSID"; - const char* password PROGMEM = "your_PASSWORD"; + static const char* ssid PROGMEM = "your_SSID"; + static const char* password PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -135,7 +135,7 @@ Tested with: #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define USING_WIFI #include - #include + #include /* Needs Arduino WiFiNINA library installed manually */ WiFiClient client; WiFiServer server(WOLFSSL_PORT); #elif defined(ARDUINO_ARCH_RP2040) @@ -178,19 +178,18 @@ Tested with: /* we expect our IP address from DHCP */ -const int serial_baud = SERIAL_BAUD; /* local serial port to monitor */ -WOLFSSL_CTX* ctx = NULL; -WOLFSSL* ssl = NULL; -char* wc_error_message = (char*)malloc(80 + 1); -char errBuf[80]; +static WOLFSSL_CTX* ctx = NULL; +static WOLFSSL* ssl = NULL; +static char* wc_error_message = (char*)malloc(80 + 1); +static char errBuf[80]; #if defined(MEMORY_STRESS_TEST) #define MEMORY_STRESS_ITERATIONS 100 #define MEMORY_STRESS_BLOCK_SIZE 1024 #define MEMORY_STRESS_INITIAL (4*1024) - char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ - int mem_ctr = 0; + static char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ + static int mem_ctr = 0; #endif static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); @@ -202,8 +201,8 @@ static int lng_index PROGMEM = 0; /* 0 = English */ #include extern char _end; extern "C" char *sbrk(int i); - char *ramstart=(char *)0x20070000; - char *ramend=(char *)0x20088000; + static char *ramstart=(char *)0x20070000; + static char *ramend=(char *)0x20088000; #endif /*****************************************************************************/ @@ -372,28 +371,31 @@ int setup_network(void) { #if defined(USING_WIFI) int status = WL_IDLE_STATUS; - if (WiFi.status() == WL_NO_MODULE) { - Serial.println("Communication with WiFi module failed!"); - /* don't continue if no network */ - while (true) ; - } - - String fv = WiFi.firmwareVersion(); - if (fv < WIFI_FIRMWARE_LATEST_VERSION) { - Serial.println("Please upgrade the firmware"); - } - /* The ESP8266 & ESP32 support both AP and STA. We'll use STA: */ #if defined(ESP8266) || defined(ESP32) WiFi.mode(WIFI_STA); + #else + String fv; + if (WiFi.status() == WL_NO_MODULE) { + Serial.println("Communication with WiFi module failed!"); + /* don't continue if no network */ + while (true) ; + } + + fv = WiFi.firmwareVersion(); + if (fv < WIFI_FIRMWARE_LATEST_VERSION) { + Serial.println("Please upgrade the firmware"); + } #endif Serial.print(F("Connecting to WiFi ")); Serial.print(ssid); + status = WiFi.begin(ssid, password); while (status != WL_CONNECTED) { - status = WiFi.begin(ssid, password); - delay(5000); + delay(1000); Serial.print(F(".")); + Serial.print(status); + status = WiFi.status(); } Serial.println(F(" Connected!")); @@ -582,9 +584,12 @@ int setup_certificates(void) { /*****************************************************************************/ /*****************************************************************************/ void setup(void) { + int i = 0; Serial.begin(SERIAL_BAUD); - while (!Serial) { + while (!Serial && (i < 10)) { /* wait for serial port to connect. Needed for native USB port only */ + delay(1000); + i++; } Serial.println(F("")); @@ -608,10 +613,10 @@ void setup(void) { setup_hardware(); - setup_datetime(); - setup_network(); + setup_datetime(); + setup_wolfssl(); setup_certificates(); diff --git a/examples/wolfssl_version/README.md b/examples/wolfssl_version/README.md new file mode 100644 index 0000000..3abfe82 --- /dev/null +++ b/examples/wolfssl_version/README.md @@ -0,0 +1,3 @@ +# Arduino Basic Hello World + +This example simply compiles in wolfSSL and shows the current version number. diff --git a/examples/wolfssl_version/wolfssl_version.ino b/examples/wolfssl_version/wolfssl_version.ino new file mode 100644 index 0000000..ba34efb --- /dev/null +++ b/examples/wolfssl_version/wolfssl_version.ino @@ -0,0 +1,24 @@ +#include +#include +#include + +/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ +#define SERIAL_BAUD 115200 + +/* Arduino setup */ +void setup() { + Serial.begin(SERIAL_BAUD); + while (!Serial) { + /* wait for serial port to connect. Needed for native USB port only */ + } + Serial.println(F("")); + Serial.println(F("")); + Serial.println(F("wolfSSL setup complete!")); +} + +/* Arduino main application loop. */ +void loop() { + Serial.print("wolfSSL Version: "); + Serial.println(LIBWOLFSSL_VERSION_STRING); + delay(60000); +} diff --git a/library.properties b/library.properties index 67823c1..1a01ade 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.6.6-Arduino.2 +version=5.7.0 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/internal.c b/src/src/internal.c index 552cf10..d889f33 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -5428,9 +5428,7 @@ int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer) keySz = ssl->eccTempKeySz; /* get curve type */ if (ssl->ecdhCurveOID > 0) { - WOLFSSL_MSG("calling ecc_cuve"); /* TODO; review */ ecc_curve = wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, NULL); - WOLFSSL_MSG("ecc_curve done"); } #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && \ (defined(WOLFSSL_SM4_CBC) || defined(WOLFSSL_SM4_GCM) || \ @@ -5464,9 +5462,7 @@ int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer) else #endif { - WOLFSSL_MSG("make key"); /* TODO review */ ret = wc_ecc_make_key_ex(ssl->rng, keySz, key, ecc_curve); - WOLFSSL_MSG("make key done"); } /* make sure the curve is set for TLS */ @@ -31468,23 +31464,13 @@ int SendClientKeyExchange(WOLFSSL* ssl) case psk_kea: { byte* pms = ssl->arrays->preMasterSecret; - int cbret = (int)ssl->options.client_psk_cb(ssl, + ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl, ssl->arrays->server_hint, ssl->arrays->client_identity, MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); - - if (cbret == 0 || cbret > MAX_PSK_KEY_LEN) { - if (cbret != USE_HW_PSK) { - ERROR_OUT(PSK_KEY_ERROR, exit_scke); - } - } - - if (cbret == USE_HW_PSK) { - /* USE_HW_PSK indicates that the hardware has the PSK - * and generates the premaster secret. */ - ssl->arrays->psk_keySz = 0; - } - else { - ssl->arrays->psk_keySz = (word32)cbret; + if (ssl->arrays->psk_keySz == 0 || + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + ERROR_OUT(PSK_KEY_ERROR, exit_scke); } /* Ensure the buffer is null-terminated. */ @@ -31496,7 +31482,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) XMEMCPY(args->encSecret, ssl->arrays->client_identity, args->encSz); ssl->options.peerAuthGood = 1; - if (cbret != USE_HW_PSK) { + if ((int)ssl->arrays->psk_keySz > 0) { /* CLIENT: Pre-shared Key for peer authentication. */ /* make psk pre master secret */ @@ -31512,8 +31498,8 @@ int SendClientKeyExchange(WOLFSSL* ssl) ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2) + (2 * OPAQUE16_LEN); ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); - ssl->arrays->psk_keySz = 0; /* No further need */ } + ssl->arrays->psk_keySz = 0; /* No further need */ break; } #endif /* !NO_PSK */ @@ -31524,12 +31510,14 @@ int SendClientKeyExchange(WOLFSSL* ssl) args->output = args->encSecret; ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl, - ssl->arrays->server_hint, ssl->arrays->client_identity, - MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); + ssl->arrays->server_hint, ssl->arrays->client_identity, + MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { ERROR_OUT(PSK_KEY_ERROR, exit_scke); } + ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */ esSz = (word32)XSTRLEN(ssl->arrays->client_identity); @@ -31605,12 +31593,14 @@ int SendClientKeyExchange(WOLFSSL* ssl) /* Send PSK client identity */ ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl, - ssl->arrays->server_hint, ssl->arrays->client_identity, - MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); + ssl->arrays->server_hint, ssl->arrays->client_identity, + MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { ERROR_OUT(PSK_KEY_ERROR, exit_scke); } + ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */ esSz = (word32)XSTRLEN(ssl->arrays->client_identity); if (esSz > MAX_PSK_ID_LEN) { @@ -31630,7 +31620,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) args->length = MAX_ENCRYPT_SZ; /* Create shared ECC key leaving room at the beginning - of buffer for size of shared key. */ + * of buffer for size of shared key. */ ssl->arrays->preMasterSz = ENCRYPT_LEN - OPAQUE16_LEN; #ifdef HAVE_CURVE25519 @@ -32021,13 +32011,15 @@ int SendClientKeyExchange(WOLFSSL* ssl) pms += ssl->arrays->preMasterSz; /* make psk pre master secret */ - /* length of key + length 0s + length of key + key */ - c16toa((word16)ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; - XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); - ssl->arrays->preMasterSz += - ssl->arrays->psk_keySz + OPAQUE16_LEN; - ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + if ((int)ssl->arrays->psk_keySz > 0) { + /* length of key + length 0s + length of key + key */ + c16toa((word16)ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; + XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ssl->arrays->preMasterSz += + ssl->arrays->psk_keySz + OPAQUE16_LEN; + ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + } ssl->arrays->psk_keySz = 0; /* No further need */ break; } @@ -32048,18 +32040,19 @@ int SendClientKeyExchange(WOLFSSL* ssl) args->encSz += args->length + OPAQUE8_LEN; /* Create pre master secret is the concatenation of - eccSize + eccSharedKey + pskSize + pskKey */ + * eccSize + eccSharedKey + pskSize + pskKey */ c16toa((word16)ssl->arrays->preMasterSz, pms); ssl->arrays->preMasterSz += OPAQUE16_LEN; pms += ssl->arrays->preMasterSz; - c16toa((word16)ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; - XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); - ssl->arrays->preMasterSz += - ssl->arrays->psk_keySz + OPAQUE16_LEN; + if ((int)ssl->arrays->psk_keySz > 0) { + c16toa((word16)ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; + XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN; - ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + } ssl->arrays->psk_keySz = 0; /* No further need */ break; } @@ -38695,31 +38688,35 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { - #if defined(WOLFSSL_EXTRA_ALERTS) || \ - defined(WOLFSSL_PSK_IDENTITY_ALERT) - SendAlert(ssl, alert_fatal, - unknown_psk_identity); - #endif + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + #if defined(WOLFSSL_EXTRA_ALERTS) || \ + defined(WOLFSSL_PSK_IDENTITY_ALERT) + SendAlert(ssl, alert_fatal, + unknown_psk_identity); + #endif ERROR_OUT(PSK_KEY_ERROR, exit_dcke); } /* SERVER: Pre-shared Key for peer authentication. */ ssl->options.peerAuthGood = 1; /* make psk pre master secret */ - /* length of key + length 0s + length of key + key */ - c16toa((word16) ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; + if ((int)ssl->arrays->psk_keySz > 0) { + /* length of key + length 0s + length of key + key */ + c16toa((word16) ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; - XMEMSET(pms, 0, ssl->arrays->psk_keySz); - pms += ssl->arrays->psk_keySz; + XMEMSET(pms, 0, ssl->arrays->psk_keySz); + pms += ssl->arrays->psk_keySz; - c16toa((word16) ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; + c16toa((word16) ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; - XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); - ssl->arrays->preMasterSz = - (ssl->arrays->psk_keySz * 2) + (OPAQUE16_LEN * 2); + XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2) + + (OPAQUE16_LEN * 2); + } + ssl->arrays->psk_keySz = 0; /* no further need */ break; } #endif /* !NO_PSK */ @@ -39534,24 +39531,27 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { - #if defined(WOLFSSL_EXTRA_ALERTS) || \ - defined(WOLFSSL_PSK_IDENTITY_ALERT) - SendAlert(ssl, alert_fatal, - unknown_psk_identity); - #endif + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + #if defined(WOLFSSL_EXTRA_ALERTS) || \ + defined(WOLFSSL_PSK_IDENTITY_ALERT) + SendAlert(ssl, alert_fatal, + unknown_psk_identity); + #endif ERROR_OUT(PSK_KEY_ERROR, exit_dcke); } /* SERVER: Pre-shared Key for peer authentication. */ ssl->options.peerAuthGood = 1; - c16toa((word16) ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; + if ((int)ssl->arrays->psk_keySz > 0) { + c16toa((word16) ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; - XMEMCPY(pms, ssl->arrays->psk_key, - ssl->arrays->psk_keySz); - ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + - OPAQUE16_LEN; + XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN; + ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + } + ssl->arrays->psk_keySz = 0; /* no further need */ break; } #endif /* !NO_DH && !NO_PSK */ @@ -39577,18 +39577,21 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { ERROR_OUT(PSK_KEY_ERROR, exit_dcke); } /* SERVER: Pre-shared Key for peer authentication. */ ssl->options.peerAuthGood = 1; + if ((int)ssl->arrays->psk_keySz > 0) { + c16toa((word16) ssl->arrays->psk_keySz, pms); + pms += OPAQUE16_LEN; - c16toa((word16) ssl->arrays->psk_keySz, pms); - pms += OPAQUE16_LEN; - - XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); - ssl->arrays->preMasterSz += - ssl->arrays->psk_keySz + OPAQUE16_LEN; + XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz); + ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN; + ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz); + } + ssl->arrays->psk_keySz = 0; /* no further need */ break; } #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */ diff --git a/src/src/quic.c b/src/src/quic.c index 02622a7..66f866a 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -83,6 +83,11 @@ static QuicRecord *quic_record_make(WOLFSSL *ssl, } else { qr->capacity = qr->len = qr_length(data, len); + if (qr->capacity > WOLFSSL_QUIC_MAX_RECORD_CAPACITY) { + WOLFSSL_MSG("QUIC length read larger than expected"); + quic_record_free(ssl, qr); + return NULL; + } } if (qr->capacity == 0) { qr->capacity = 2*1024; @@ -129,6 +134,14 @@ static int quic_record_append(WOLFSSL *ssl, QuicRecord *qr, const uint8_t *data, consumed = missing; qr->len = qr_length(qr->data, qr->end); + + /* sanity check on length read from wire before use */ + if (qr->len > WOLFSSL_QUIC_MAX_RECORD_CAPACITY) { + WOLFSSL_MSG("Length read for quic is larger than expected"); + ret = BUFFER_E; + goto cleanup; + } + if (qr->len > qr->capacity) { uint8_t *ndata = (uint8_t*)XREALLOC(qr->data, qr->len, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/src/src/ssl.c b/src/src/ssl.c index 1d501f8..ea66e42 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -1517,7 +1517,7 @@ void wolfSSL_free(WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_free"); if (ssl) { - WOLFSSL_MSG_EX("Free SSL: %p", (uintptr_t)ssl); + WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl); FreeSSL(ssl, ssl->ctx->heap); } else { diff --git a/src/src/tls.c b/src/src/tls.c index 57d0cc3..a28568c 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -3089,8 +3089,8 @@ static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest) return size; } -static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, - byte isRequest) +static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, + byte isRequest) { /* shut up compiler warnings */ (void) csr; (void) output; (void) isRequest; @@ -3119,6 +3119,9 @@ static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, if (ret > 0) { length = (word16)ret; } + else { + return ret; + } } c16toa(length, output + offset); @@ -3127,7 +3130,7 @@ static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, break; } - return offset; + return (int)offset; } #endif #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) @@ -3555,7 +3558,7 @@ static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2, return size; } -static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2, +static int TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2, byte* output, byte isRequest) { /* shut up compiler warnings */ @@ -3600,6 +3603,9 @@ static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2, if (ret > 0) { length = (word16)ret; } + else { + return ret; + } } c16toa(length, output + offset); @@ -3611,7 +3617,7 @@ static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2, /* list size */ c16toa(offset - OPAQUE16_LEN, output); - return offset; + return (int)offset; } #endif @@ -7474,7 +7480,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC); if (kse->key == NULL) { WOLFSSL_MSG_EX("Failed to allocate %d bytes, ssl->heap: %p", - (int)sizeof(ecc_key), (uintptr_t)ssl->heap); + (int)sizeof(ecc_key), (wc_ptr_t)ssl->heap); WOLFSSL_MSG("EccTempKey Memory error!"); return MEMORY_E; } @@ -12614,15 +12620,23 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, case TLSX_STATUS_REQUEST: WOLFSSL_MSG("Certificate Status Request extension to write"); - offset += CSR_WRITE((CertificateStatusRequest*)extension->data, + ret = CSR_WRITE((CertificateStatusRequest*)extension->data, output + offset, isRequest); + if (ret > 0) { + offset += (word16)ret; + ret = 0; + } break; case TLSX_STATUS_REQUEST_V2: WOLFSSL_MSG("Certificate Status Request v2 extension to write"); - offset += CSR2_WRITE( + ret = CSR2_WRITE( (CertificateStatusRequestItemV2*)extension->data, output + offset, isRequest); + if (ret > 0) { + offset += (word16)ret; + ret = 0; + } break; case TLSX_RENEGOTIATION_INFO: @@ -13327,7 +13341,7 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) else #endif if (ssl->options.client_psk_cb != NULL || - ssl->options.client_psk_tls13_cb != NULL) { + ssl->options.client_psk_tls13_cb != NULL) { /* Default cipher suite. */ byte cipherSuite0 = TLS13_BYTE; byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER; @@ -13349,42 +13363,40 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) ssl->arrays->server_hint, ssl->arrays->client_identity, MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); } - #if defined(OPENSSL_EXTRA) - /* OpenSSL treats 0 as a PSK key length of 0 - * and meaning no PSK available. - */ - if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { - return PSK_KEY_ERROR; - } - if (ssl->arrays->psk_keySz > 0) { - #else - if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { - return PSK_KEY_ERROR; + if ( + #ifdef OPENSSL_EXTRA + /* OpenSSL treats a PSK key length of 0 + * to indicate no PSK available. + */ + ssl->arrays->psk_keySz == 0 || + #endif + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + #ifndef OPENSSL_EXTRA + ret = PSK_KEY_ERROR; + #endif } - #endif - ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; - - ssl->options.cipherSuite0 = cipherSuite0; - ssl->options.cipherSuite = cipherSuite; - (void)cipherSuiteFlags; - ret = SetCipherSpecs(ssl); - if (ret != 0) - return ret; + else { + ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; - ret = TLSX_PreSharedKey_Use(&ssl->extensions, - (byte*)ssl->arrays->client_identity, - (word16)XSTRLEN(ssl->arrays->client_identity), - 0, ssl->specs.mac_algorithm, - cipherSuite0, cipherSuite, 0, - NULL, ssl->heap); + ssl->options.cipherSuite0 = cipherSuite0; + ssl->options.cipherSuite = cipherSuite; + (void)cipherSuiteFlags; + ret = SetCipherSpecs(ssl); + if (ret == 0) { + ret = TLSX_PreSharedKey_Use( + &ssl->extensions, + (byte*)ssl->arrays->client_identity, + (word16)XSTRLEN(ssl->arrays->client_identity), + 0, ssl->specs.mac_algorithm, + cipherSuite0, cipherSuite, 0, + NULL, ssl->heap); + } + if (ret == 0) + usingPSK = 1; + } if (ret != 0) return ret; - - usingPSK = 1; - #if defined(OPENSSL_EXTRA) - } - #endif } #endif /* !NO_PSK */ #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) diff --git a/src/src/tls13.c b/src/src/tls13.c index 8088d58..9a2e240 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -1127,6 +1127,12 @@ static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, ret = cb(prk, salt, saltLen, ikm, ikmLen, digest, cb_ctx); } else +#endif +#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) + if ((int)ssl->arrays->psk_keySz < 0) { + ret = PSK_KEY_ERROR; + } + else #endif { #if !defined(HAVE_FIPS) || \ @@ -3943,7 +3949,8 @@ static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello) ssl->options.cipherSuite = WOLFSSL_DEF_PSK_CIPHER; } if (ssl->arrays->psk_keySz == 0 || - ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) { + (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && + (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR); return PSK_KEY_ERROR; } @@ -3956,7 +3963,7 @@ static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello) #endif /* !WOLFSSL_PSK_ONE_ID */ if (!clientHello && (psk->cipherSuite0 != suite[0] || - psk->cipherSuite != suite[1])) { + psk->cipherSuite != suite[1])) { WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR); return PSK_KEY_ERROR; } @@ -5839,7 +5846,8 @@ int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk, byte* psk_key, *found = (*psk_keySz != 0); } if (*found) { - if (*psk_keySz > MAX_PSK_KEY_LEN) { + if (*psk_keySz > MAX_PSK_KEY_LEN && + *((int*)psk_keySz) != USE_HW_PSK) { WOLFSSL_MSG("Key len too long in FindPsk()"); ret = PSK_KEY_ERROR; WOLFSSL_ERROR_VERBOSE(ret); @@ -5894,29 +5902,27 @@ static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, const byte* suite, int* err) ret = FindPskSuite(ssl, psk, ssl->arrays->psk_key, &ssl->arrays->psk_keySz, suite, &found, foundSuite); if (ret == 0 && found) { - if ((ret == 0) && found) { - /* Default to ciphersuite if cb doesn't specify. */ - ssl->options.resuming = 0; - /* Don't send certificate request when using PSK. */ - ssl->options.verifyPeer = 0; + /* Default to ciphersuite if cb doesn't specify. */ + ssl->options.resuming = 0; + /* Don't send certificate request when using PSK. */ + ssl->options.verifyPeer = 0; - /* PSK age is always zero. */ - if (psk->ticketAge != 0) { - ret = PSK_KEY_ERROR; - WOLFSSL_ERROR_VERBOSE(ret); - } + /* PSK age is always zero. */ + if (psk->ticketAge != 0) { + ret = PSK_KEY_ERROR; + WOLFSSL_ERROR_VERBOSE(ret); } - if ((ret == 0) && found) { + if (ret == 0) { /* Set PSK ciphersuite into SSL. */ ssl->options.cipherSuite0 = foundSuite[0]; ssl->options.cipherSuite = foundSuite[1]; ret = SetCipherSpecs(ssl); } - if ((ret == 0) && found) { + if (ret == 0) { /* Derive the early secret using the PSK. */ ret = DeriveEarlySecret(ssl); } - if ((ret == 0) && found) { + if (ret == 0) { /* PSK negotiation has succeeded */ ssl->options.isPSK = 1; /* SERVER: using PSK for peer authentication. */ @@ -7135,6 +7141,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef HAVE_SESSION_TICKET if (ssl->options.resuming) { ssl->options.resuming = 0; + ssl->arrays->psk_keySz = 0; XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size); } #endif @@ -10375,7 +10382,8 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (sniff == NO_SNIFF) { /* Actually check verify data. */ - if (XMEMCMP(input + *inOutIdx, mac, size) != 0){ + if (size > WC_MAX_DIGEST_SIZE || + XMEMCMP(input + *inOutIdx, mac, size) != 0){ WOLFSSL_MSG("Verify finished error on hashes"); SendAlert(ssl, alert_fatal, decrypt_error); WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR); diff --git a/src/src/wolfio.c b/src/src/wolfio.c index 8dd1857..041e0b7 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -41,52 +41,54 @@ #include #include -#ifndef USE_WINDOWS_API - #if defined(WOLFSSL_LWIP) && !defined(WOLFSSL_APACHE_MYNEWT) - #elif defined(ARDUINO) - #elif defined(FREESCALE_MQX) - #elif defined(FREESCALE_KSDK_MQX) - #elif (defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)) - #elif defined(WOLFSSL_CMSIS_RTOS) - #elif defined(WOLFSSL_CMSIS_RTOSv2) - #elif defined(WOLFSSL_TIRTOS) - #elif defined(FREERTOS_TCP) - #elif defined(WOLFSSL_IAR_ARM) - #elif defined(HAVE_NETX_BSD) - #elif defined(WOLFSSL_VXWORKS) - #elif defined(WOLFSSL_NUCLEUS_1_2) - #elif defined(WOLFSSL_LINUXKM) - /* the requisite linux/net.h is included in wc_port.h, with incompatible warnings masked out. */ - #elif defined(WOLFSSL_ATMEL) - #elif defined(INTIME_RTOS) - #include - #elif defined(WOLFSSL_PRCONNECT_PRO) - #include - #include - #elif defined(WOLFSSL_SGX) - #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) - #elif defined(WOLFSSL_DEOS) - #elif defined(WOLFSSL_ZEPHYR) - #elif defined(MICROCHIP_PIC32) - #elif defined(HAVE_NETX) - #elif defined(FUSION_RTOS) - #elif !defined(WOLFSSL_NO_SOCK) - #if defined(HAVE_RTP_SYS) - #elif defined(EBSNET) - #elif defined(NETOS) - #elif !defined(DEVKITPRO) && !defined(WOLFSSL_PICOTCP) \ - && !defined(WOLFSSL_CONTIKI) && !defined(WOLFSSL_WICED) \ - && !defined(WOLFSSL_GNRC) && !defined(WOLFSSL_RIOT_OS) +#if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) + #ifndef USE_WINDOWS_API + #if defined(WOLFSSL_LWIP) && !defined(WOLFSSL_APACHE_MYNEWT) + #elif defined(ARDUINO) + #elif defined(FREESCALE_MQX) + #elif defined(FREESCALE_KSDK_MQX) + #elif (defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)) + #elif defined(WOLFSSL_CMSIS_RTOS) + #elif defined(WOLFSSL_CMSIS_RTOSv2) + #elif defined(WOLFSSL_TIRTOS) + #elif defined(FREERTOS_TCP) + #elif defined(WOLFSSL_IAR_ARM) + #elif defined(HAVE_NETX_BSD) + #elif defined(WOLFSSL_VXWORKS) + #elif defined(WOLFSSL_NUCLEUS_1_2) + #elif defined(WOLFSSL_LINUXKM) + /* the requisite linux/net.h is included in wc_port.h, with incompatible warnings masked out. */ + #elif defined(WOLFSSL_ATMEL) + #elif defined(INTIME_RTOS) #include - #ifdef __PPU - #include - #else - #include + #elif defined(WOLFSSL_PRCONNECT_PRO) + #include + #include + #elif defined(WOLFSSL_SGX) + #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) + #elif defined(WOLFSSL_DEOS) + #elif defined(WOLFSSL_ZEPHYR) + #elif defined(MICROCHIP_PIC32) + #elif defined(HAVE_NETX) + #elif defined(FUSION_RTOS) + #elif !defined(WOLFSSL_NO_SOCK) + #if defined(HAVE_RTP_SYS) + #elif defined(EBSNET) + #elif defined(NETOS) + #elif !defined(DEVKITPRO) && !defined(WOLFSSL_PICOTCP) \ + && !defined(WOLFSSL_CONTIKI) && !defined(WOLFSSL_WICED) \ + && !defined(WOLFSSL_GNRC) && !defined(WOLFSSL_RIOT_OS) + #include + #ifdef __PPU + #include + #else + #include + #endif #endif #endif - #endif -#endif /* USE_WINDOWS_API */ + #endif /* USE_WINDOWS_API */ +#endif /* defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) */ #if defined(HAVE_HTTP_CLIENT) diff --git a/src/src/x509.c b/src/src/x509.c index 05c3a02..eefa69c 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -1545,22 +1545,10 @@ int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, WOLFSSL_MSG("Memory error"); return rc; } - if (sk->next) { - if ((valLen = XSNPRINTF(val, len, "%*s%s,", - indent, "", str->strData)) - >= len) { - XFREE(val, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return rc; - } - } else { - if ((valLen = XSNPRINTF(val, len, "%*s%s", - indent, "", str->strData)) - >= len) { - XFREE(val, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return rc; - } - } - if ((tmpLen + valLen) >= tmpSz) { + valLen = XSNPRINTF(val, len, "%*s%s", indent, "", + str->strData); + if ((valLen < 0) || (valLen >= len) + || ((tmpLen + valLen) >= tmpSz)) { XFREE(val, NULL, DYNAMIC_TYPE_TMP_BUFFER); return rc; } diff --git a/src/src/x509_str.c b/src/src/x509_str.c index d5849ad..a38f93b 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -557,6 +557,7 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) } } else { + wolfSSL_X509_free(x509); WOLFSSL_MSG("Could not find CA for certificate"); } } diff --git a/src/user_settings.h b/src/user_settings.h index 4eb22c0..d102ea8 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -19,7 +19,16 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* This is a sample Arduino user_settings.h for wolfSSL */ +/* This is a sample Arduino user_settings.h for wolfSSL +*/ + +/* Define a macro to display user settings version in example code: */ +#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.0" + +/* Due to limited build control, we'll ignore file warnings. */ +/* See https://github.com/arduino/arduino-cli/issues/631 */ +#undef WOLFSSL_IGNORE_FILE_WARN +#define WOLFSSL_IGNORE_FILE_WARN #define NO_FILESYSTEM #define USE_CERT_BUFFERS_2048 @@ -29,15 +38,26 @@ #define HAVE_ECC #define WOLFSSL_SMALL_STACK -//#define WOLFSSL_SMALL_STACK_EXTRA -//#define WOLFSSL_SMALL_STACK_CIPHERS -//#define NO_DH +/* #define WOLFSSL_SMALL_STACK_EXTRA */ +/* #define WOLFSSL_SMALL_STACK_CIPHERS */ +/* #define NO_DH */ +#define MICRO_SESSION_CACHE /* RSA must be enabled for examples, but can be disabled like this: */ /* #define NO_RSA */ #define RSA_LOW_MEM -//#define NO_OLD_TLS +#define NO_OLD_TLS +/* TLS 1.3 */ +/* #define WOLFSSL_TLS13 */ +#if defined(WOLFSSL_TLS13) + #define HAVE_TLS_EXTENSIONS + #define WC_RSA_PSS + #define HAVE_HKDF + #define HAVE_AEAD +#endif + +/* #define HAVE_SUPPORTED_CURVES */ /* Cannot use WOLFSSL_NO_MALLOC with small stack */ /* #define WOLFSSL_NO_MALLOC */ @@ -45,6 +65,35 @@ #define HAVE_TLS_EXTENSIONS #define HAVE_SUPPORTED_CURVES +/* To further reduce size, client or server functionality can be disabled. + * Here, we check if the example code gave us a hint. + * + * The calling application can define either one of these macros before + * including the Arduino wolfssl.h library file: + * + * WOLFSSL_CLIENT_EXAMPLE + * WOLFSSL_SERVER_EXAMPLE + */ +#if defined(WOLFSSL_CLIENT_EXAMPLE) + #define NO_WOLFSSL_SERVER +#elif defined(WOLFSSL_SERVER_EXAMPLE) + #define NO_WOLFSSL_CLIENT +#else + /* Provide a hint to application that neither WOLFSSL_CLIENT_EXAMPLE + * or WOLFSSL_SERVER_EXAMPLE macro hint was desired but not found. */ + #define NO_WOLFSSL_SERVER_CLIENT_MISSING + #warning "Define WOLFSSL_CLIENT_EXAMPLE or WOLFSSL_SERVER_EXAMPLE to" \ + " optimize memory for small embedded devices." + /* Both can be disabled in wolfssl test & benchmark */ +#endif + + +#define NO_DH +#define NO_DSA +#define USE_FAST_MATH +#define WOLFSSL_SMALL_STACK +#define SINGLE_THREADED +#define WOLFSSL_LOW_MEMORY #define HAVE_AESGCM /* optionally turn off SHA512/224 SHA512/256 */ @@ -241,13 +290,14 @@ #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI /***** END CONFIG_IDF_TARGET_ESP266 *****/ #else - /* Anything else encountered, disable HW accleration */ + /* Anything else encountered, disable HW acceleration */ #define NO_ESP32_CRYPT #define NO_WOLFSSL_ESP32_CRYPT_HASH #define NO_WOLFSSL_ESP32_CRYPT_AES #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI #endif /* CONFIG_IDF_TARGET Check */ +#define DEBUG_WOLFSSL /* Debug options: #define ESP_VERIFY_MEMBLOCK @@ -266,10 +316,10 @@ #define WOLFSSL_ESPIDF_ERROR_PAUSE /* Pause in a loop rather than exit. */ #define WOLFSSL_HW_METRICS - +#define ALT_ECC_SIZE /* #define HASH_SIZE_LIMIT */ /* for test.c */ -/* #define NO_HW_MATH_TEST */ /* Optionall turn off HW math checks */ +/* #define NO_HW_MATH_TEST */ /* Optionally turn off HW math checks */ /* Optionally include alternate HW test library: alt_hw_test.h */ /* When enabling, the ./components/wolfssl/CMakeLists.txt file @@ -302,15 +352,73 @@ */ /* optional SM4 Ciphers. See https://github.com/wolfSSL/wolfsm +/* The section below defines macros used in typically all of the wolfSSL + * examples such as the client and server for certs stored in header files. + * + * There are various certificate examples in this header file: + * https://github.com/wolfSSL/wolfssl/blob/master/wolfssl/certs_test.h + * + * To use the sets of macros below, define *one* of these: + * + * USE_CERT_BUFFERS_1024 - ECC 1024 bit encoded ASN1 + * USE_CERT_BUFFERS_2048 - RSA 2048 bit encoded ASN1 + * WOLFSSL_SM[2,3,4] - SM Ciphers + * + * For example: define USE_CERT_BUFFERS_2048 to use CA Certs used in this + * wolfSSL function for the `ca_cert_der_2048` buffer, size and types: + * + * ret = wolfSSL_CTX_load_verify_buffer(ctx, + * CTX_CA_CERT, + * CTX_CA_CERT_SIZE, + * CTX_CA_CERT_TYPE); + * + * See https://www.wolfssl.com/documentation/manuals/wolfssl/group__CertsKeys.html#function-wolfssl_ctx_load_verify_buffer + * + * In this case the CTX_CA_CERT will be defined as `ca_cert_der_2048` as + * defined here: https://github.com/wolfSSL/wolfssl/blob/master/wolfssl/certs_test.h + * + * The CTX_CA_CERT_SIZE and CTX_CA_CERT_TYPE are similarly used to reference + * array size and cert type respectively. + * + * Similarly for loading the private client key: + * + * ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, + * CTX_CLIENT_KEY, + * CTX_CLIENT_KEY_SIZE, + * CTX_CLIENT_KEY_TYPE); + * + * see https://www.wolfssl.com/documentation/manuals/wolfssl/group__CertsKeys.html#function-wolfssl_ctx_use_privatekey_buffer + * + * Similarly, the other macros are for server certificates and keys: + * `CTX_SERVER_CERT` and `CTX_SERVER_KEY` are available. + * + * The certificate and key names are typically `static const unsigned char` + * arrays. The [NAME]_size are typically `sizeof([array name])`, and the types + * are the known wolfSSL encoding type integers (e.g. WOLFSSL_FILETYPE_PEM). + * + * See `SSL_FILETYPE_[name]` in + * https://github.com/wolfSSL/wolfssl/blob/master/wolfssl/ssl.h + * + * See Abstract Syntax Notation One (ASN.1) in: + * https://github.com/wolfSSL/wolfssl/blob/master/wolfssl/wolfcrypt/asn.h + * + * Optional SM4 Ciphers: + * + * Although the SM ciphers are shown here, the `certs_test_sm.h` may not yet + * be available. See: + * https://github.com/wolfSSL/wolfssl/pull/6825 + * https://github.com/wolfSSL/wolfsm + * + * Uncomment these 3 macros to enable the SM Ciphers and use the macros below. + */ + +/* #define WOLFSSL_SM2 #define WOLFSSL_SM3 #define WOLFSSL_SM4 */ -// #define WOLFSSL_MEMORY_STORAGE __FlashStringHelper * - -#define WOLFSSL_MEMORY_STORAGE - +/* Conditional macros used in wolfSSL TLS client and server examples */ #if defined(WOLFSSL_SM2) || defined(WOLFSSL_SM3) || defined(WOLFSSL_SM4) #include #define CTX_CA_CERT root_sm2 @@ -327,6 +435,9 @@ #define WOLFSSL_BASE16 #else #if defined(USE_CERT_BUFFERS_2048) + #ifdef USE_CERT_BUFFERS_1024 + #error "USE_CERT_BUFFERS_1024 is already defined. Pick one." + #endif #include #define CTX_CA_CERT ca_cert_der_2048 #define CTX_CA_CERT_SIZE sizeof_ca_cert_der_2048 @@ -346,6 +457,9 @@ #define CTX_CLIENT_KEY_SIZE sizeof_client_key_der_2048 #define CTX_CLIENT_KEY_TYPE WOLFSSL_FILETYPE_ASN1 #elif defined(USE_CERT_BUFFERS_1024) + #ifdef USE_CERT_BUFFERS_2048 + #error "USE_CERT_BUFFERS_2048 is already defined. Pick one." + #endif #include #define CTX_CA_CERT ca_cert_der_1024 #define CTX_CA_CERT_SIZE sizeof_ca_cert_der_1024 diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index 4ef94e5..ac50995 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -1065,6 +1065,16 @@ static int GetASN_Integer(const byte* input, word32 idx, int length, #endif } } + /* check for invalid padding on negative integer. + * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1 + */ + else if ((length > 1) && (input[idx] == 0xff) && + ((input[idx + 1] & 0x80) != 0)) { + WOLFSSL_MSG("Bad INTEGER encoding of negative"); + #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY + return ASN_EXPECT_0_E; + #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */ + } /* Check whether a leading zero byte was required. */ else if (positive && (input[idx] & 0x80)) { WOLFSSL_MSG("INTEGER is negative"); @@ -1116,6 +1126,100 @@ static int GetASN_BitString(const byte* input, word32 idx, int length) return 0; } +#ifndef WOLFSSL_NO_ASN_STRICT +/* Check a UTF8STRING's data is valid. + * + * @param [in] input BER encoded data. + * @param [in] idx Index of UTF8STRING data. + * @param [in] length Length of input data. + * @return 0 on success. + * @return ASN_PARSE_E when data is invalid. + */ +static int GetASN_UTF8String(const byte* input, word32 idx, int length) +{ + int ret = 0; + word32 i = 0; + + while ((ret == 0) && ((int)i < length)) { + int cnt; + + /* Check code points and get count of following bytes. */ + if ((input[idx + i] & 0x80) == 0x00) { + cnt = 0; + } + else if ((input[idx + i] & 0xe0) == 0xc0) { + cnt = 1; + } + else if ((input[idx + i] & 0xf0) == 0xe0) { + cnt = 2; + } + else if ((input[idx + i] & 0xf8) == 0xf0) { + cnt = 3; + } + else { + WOLFSSL_MSG("Invalid character in UTF8STRING\n"); + ret = ASN_PARSE_E; + break; + } + + /* Have checked first byte. */ + i++; + /* Check each following byte. */ + for (; cnt > 0; cnt--) { + /* Check we have enough data. */ + if ((int)i == length) { + WOLFSSL_MSG("Missing character in UTF8STRING\n"); + ret = ASN_PARSE_E; + break; + } + /* Check following byte has top bit set. */ + if ((input[idx + i] & 0x80) != 0x80) { + WOLFSSL_MSG("Invalid character in UTF8STRING\n"); + ret = ASN_PARSE_E; + break; + } + i++; + } + } + + return ret; +} +#endif + +/* Check an OBJECT IDENTIFIER's data is valid. + * + * X.690 8.19 + * + * @param [in] input BER encoded data. + * @param [in] idx Index of OBJECT IDENTIFIER data. + * @param [in] length Length of input data. + * @return 0 on success. + * @return ASN_PARSE_E when data is invalid. + */ +static int GetASN_ObjectId(const byte* input, word32 idx, int length) +{ + int ret = 0; + + /* OID data must be at least 3 bytes. */ + if (length < 3) { + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len); + #else + WOLFSSL_MSG("OID length less than 3"); + #endif + ret = ASN_PARSE_E; + } + /* Last octet of a subidentifier has bit 8 clear. Last octet must be last + * of a subidentifier. Ensure last octet hasn't got top bit set indicating. + */ + else if ((input[(int)idx + length - 1] & 0x80) != 0x00) { + WOLFSSL_MSG("OID last octet has top bit set"); + ret = ASN_PARSE_E; + } + + return ret; +} + /* Get the ASN.1 items from the BER encoding. * * @param [in] asn ASN.1 item expected. @@ -1581,11 +1685,20 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, idx++; len--; } - else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) { - #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE - WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len); - #endif - return ASN_PARSE_E; + #ifndef WOLFSSL_NO_ASN_STRICT + else if ((asn[i].tag == ASN_UTF8STRING) || + (data[i].tag == ASN_UTF8STRING)) { + /* Check validity of data. */ + err = GetASN_UTF8String(input, idx, len); + if (err != 0) + return err; + } + #endif + else if (asn[i].tag == ASN_OBJECT_ID) { + /* Check validity of data. */ + err = GetASN_ObjectId(input, idx, len); + if (err != 0) + return err; } /* Don't parse data if only header required. */ @@ -3465,7 +3578,9 @@ word32 SetBitString(word32 len, byte unusedBits, byte* output) #ifdef ASN_BER_TO_DER -#define BER_OCTET_LENGTH 4096 +#ifndef BER_OCTET_LENGTH + #define BER_OCTET_LENGTH 4096 +#endif /* sets the terminating 0x00 0x00 at the end of an indefinite length * returns the number of bytes written */ @@ -12659,6 +12774,17 @@ static int GetHashId(const byte* id, int length, byte* hash, int hashAlg) (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \ (certNameSubject[(id) - 3].strLen > 0)) +/* Set the string for a name component into the issuer name. */ +#define SetCertNameIssuer(cert, id, val) \ + *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].dataI)) = (val) +/* Set the string length for a name component into the issuer name. */ +#define SetCertNameIssuerLen(cert, id, val) \ + *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].lenI)) = (int)(val) +/* Set the encoding for a name component into the issuer name. */ +#define SetCertNameIssuerEnc(cert, id, val) \ + *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].encI)) = (val) + + /* Mapping of certificate name component to useful information. */ typedef struct CertNameData { /* Type string of name component. */ @@ -12672,6 +12798,14 @@ typedef struct CertNameData { size_t len; /* Offset of encoding in subject name component. */ size_t enc; +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + /* Offset of data in subject name component. */ + size_t dataI; + /* Offset of length in subject name component. */ + size_t lenI; + /* Offset of encoding in subject name component. */ + size_t encI; +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE /* NID of type for subject name component. */ @@ -12688,6 +12822,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectCN), OFFSETOF(DecodedCert, subjectCNLen), OFFSETOF(DecodedCert, subjectCNEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerCN), + OFFSETOF(DecodedCert, issuerCNLen), + OFFSETOF(DecodedCert, issuerCNEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_commonName @@ -12700,6 +12839,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectSN), OFFSETOF(DecodedCert, subjectSNLen), OFFSETOF(DecodedCert, subjectSNEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerSN), + OFFSETOF(DecodedCert, issuerSNLen), + OFFSETOF(DecodedCert, issuerSNEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_surname @@ -12712,6 +12856,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectSND), OFFSETOF(DecodedCert, subjectSNDLen), OFFSETOF(DecodedCert, subjectSNDEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerSND), + OFFSETOF(DecodedCert, issuerSNDLen), + OFFSETOF(DecodedCert, issuerSNDEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_serialNumber @@ -12724,6 +12873,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectC), OFFSETOF(DecodedCert, subjectCLen), OFFSETOF(DecodedCert, subjectCEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerC), + OFFSETOF(DecodedCert, issuerCLen), + OFFSETOF(DecodedCert, issuerCEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_countryName @@ -12736,6 +12890,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectL), OFFSETOF(DecodedCert, subjectLLen), OFFSETOF(DecodedCert, subjectLEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerL), + OFFSETOF(DecodedCert, issuerLLen), + OFFSETOF(DecodedCert, issuerLEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_localityName @@ -12748,6 +12907,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectST), OFFSETOF(DecodedCert, subjectSTLen), OFFSETOF(DecodedCert, subjectSTEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerST), + OFFSETOF(DecodedCert, issuerSTLen), + OFFSETOF(DecodedCert, issuerSTEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_stateOrProvinceName @@ -12760,6 +12924,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectStreet), OFFSETOF(DecodedCert, subjectStreetLen), OFFSETOF(DecodedCert, subjectStreetEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_streetAddress @@ -12772,6 +12941,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectO), OFFSETOF(DecodedCert, subjectOLen), OFFSETOF(DecodedCert, subjectOEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerO), + OFFSETOF(DecodedCert, issuerOLen), + OFFSETOF(DecodedCert, issuerOEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_organizationName @@ -12784,6 +12958,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectOU), OFFSETOF(DecodedCert, subjectOULen), OFFSETOF(DecodedCert, subjectOUEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + OFFSETOF(DecodedCert, issuerOU), + OFFSETOF(DecodedCert, issuerOULen), + OFFSETOF(DecodedCert, issuerOUEnc), +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_organizationalUnitName @@ -12796,6 +12975,11 @@ static const CertNameData certNameSubject[] = { 0, 0, 0, +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE 0, @@ -12808,6 +12992,11 @@ static const CertNameData certNameSubject[] = { 0, 0, 0, +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE 0, @@ -12820,6 +13009,11 @@ static const CertNameData certNameSubject[] = { 0, 0, 0, +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE 0, @@ -12832,6 +13026,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectBC), OFFSETOF(DecodedCert, subjectBCLen), OFFSETOF(DecodedCert, subjectBCEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_businessCategory @@ -12844,6 +13043,11 @@ static const CertNameData certNameSubject[] = { 0, 0, 0, +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE 0, @@ -12856,6 +13060,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectPC), OFFSETOF(DecodedCert, subjectPCLen), OFFSETOF(DecodedCert, subjectPCEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_postalCode @@ -12868,6 +13077,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectUID), OFFSETOF(DecodedCert, subjectUIDLen), OFFSETOF(DecodedCert, subjectUIDEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_userId @@ -12881,6 +13095,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectN), OFFSETOF(DecodedCert, subjectNLen), OFFSETOF(DecodedCert, subjectNEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_name @@ -12893,6 +13112,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectGN), OFFSETOF(DecodedCert, subjectGNLen), OFFSETOF(DecodedCert, subjectGNEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_givenName @@ -12905,6 +13129,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectI), OFFSETOF(DecodedCert, subjectILen), OFFSETOF(DecodedCert, subjectIEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_initials @@ -12917,6 +13146,11 @@ static const CertNameData certNameSubject[] = { OFFSETOF(DecodedCert, subjectDNQ), OFFSETOF(DecodedCert, subjectDNQLen), OFFSETOF(DecodedCert, subjectDNQEnc), +#ifdef WOLFSSL_HAVE_ISSUER_NAMES + 0, + 0, + 0, +#endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE NID_dnQualifier @@ -12928,6 +13162,7 @@ static const CertNameData certNameSubject[] = { static const int certNameSubjectSz = (int) (sizeof(certNameSubject) / sizeof(CertNameData)); + /* ASN.1 template for an RDN. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName */ @@ -13268,6 +13503,43 @@ static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen, return ret; } +#if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \ + defined(WOLFSSL_HAVE_ISSUER_NAMES) +/* Set the details of an issuer name component into a certificate. + * + * @param [in, out] cert Certificate object. + * @param [in] id Id of component. + * @param [in] str String for component. + * @param [in] strLen Length of string. + * @param [in] tag BER tag representing encoding of string. + * @return 0 on success, negative values on failure. + */ +static int SetIssuer(DecodedCert* cert, int id, byte* str, int strLen, + byte tag) +{ + int ret = 0; + + /* Put string and encoding into certificate. */ + if (id == ASN_COMMON_NAME) { + cert->issuerCN = (char *)str; + cert->issuerCNLen = (int)strLen; + cert->issuerCNEnc = (char)tag; + } + else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) { + /* Use table and offsets to put data into appropriate fields. */ + SetCertNameIssuer(cert, id, (char*)str); + SetCertNameIssuerLen(cert, id, strLen); + SetCertNameIssuerEnc(cert, id, tag); + } + else if (id == ASN_EMAIL) { + cert->issuerEmail = (char*)str; + cert->issuerEmailLen = strLen; + } + + return ret; +} +#endif + /* Get a RelativeDistinguishedName from the encoding and put in certificate. * * @param [in, out] cert Certificate object. @@ -13400,6 +13672,13 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, /* Store subject field components. */ ret = SetSubject(cert, id, str, (int)strLen, tag); } + #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \ + defined(WOLFSSL_HAVE_ISSUER_NAMES) + /* Put issuer common name string and encoding into certificate. */ + else { + ret = SetIssuer(cert, id, str, (int)strLen, tag); + } + #endif if (ret == 0) { /* Check there is space for this in the full name string and * terminating NUL character. */ @@ -14740,7 +15019,7 @@ int wc_ValidateDate(const byte* date, byte format, int dateType) ltime = wc_Time(0); #ifndef NO_TIME_SIGNEDNESS_CHECK - if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){ + if (sizeof(ltime) == sizeof(word32) && (sword32)ltime < 0){ /* A negative response here could be due to a 32-bit time_t * where the year is 2038 or later. */ WOLFSSL_MSG("wc_Time failed to return a valid value"); @@ -36363,7 +36642,7 @@ word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size) CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap); - if ((ret == 0) && (output != NULL)) { + if (ret == 0) { /* Set nonce extension OID and nonce. */ SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId, sizeof(NonceObjId)); diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index 2065213..c1edfc3 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -460,7 +460,8 @@ int wc_AesCmacVerify(const byte* check, word32 checkSz, Cmac cmac[1]; #endif - if (check == NULL || (in == NULL && inSz > 0) || key == NULL || keySz == 0) { + if (check == NULL || checkSz == 0 || (in == NULL && inSz > 0) || + key == NULL || keySz == 0) { return BAD_FUNC_ARG; } diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index 598e77d..78101ed 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -1650,7 +1650,7 @@ static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, #ifdef ECC_CACHE_CURVE int x; #endif - WOLFSSL_ENTER("wc_ecc_curve_load"); + if (dp == NULL || pCurve == NULL) return BAD_FUNC_ARG; @@ -1751,8 +1751,6 @@ static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, wc_UnLockMutex(&ecc_curve_cache_mutex); #endif - WOLFSSL_LEAVE("wc_ecc_curve_load", ret); - return ret; } @@ -2631,7 +2629,7 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) int err; (void)ct; - WOLFSSL_ENTER("ecc_map_ex"); + if (P == NULL || modulus == NULL) return ECC_BAD_ARG_E; @@ -2660,7 +2658,6 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) #endif /* WOLFSSL_SMALL_STACK_CACHE */ #endif { - WOLFSSL_MSG("ecc new mp"); NEW_MP_INT_SIZE(t1, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); NEW_MP_INT_SIZE(t2, mp_bitsused(modulus), NULL, DYNAMIC_TYPE_ECC); #ifdef MP_INT_SIZE_CHECK_NULL @@ -2686,7 +2683,7 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) #endif #endif } - WOLFSSL_MSG("ecc init"); + err = INIT_MP_INT_SIZE(t1, mp_bitsused(modulus)); if (err == MP_OKAY) { err = INIT_MP_INT_SIZE(t2, mp_bitsused(modulus)); @@ -3838,7 +3835,7 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, ecc_key key; #endif mp_digit mp; - WOLFSSL_ENTER("wc_ecc_mulmod_ex2"); + if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } @@ -4000,7 +3997,6 @@ static int wc_ecc_new_point_ex(ecc_point** point, void* heap) int err = MP_OKAY; ecc_point* p; - WOLFSSL_ENTER("wc_ecc_new_point_ex"); if (point == NULL) { return BAD_FUNC_ARG; } @@ -4008,22 +4004,15 @@ static int wc_ecc_new_point_ex(ecc_point** point, void* heap) p = *point; #ifndef WOLFSSL_NO_MALLOC if (p == NULL) { - WOLFSSL_MSG_EX("XMALLOC ecc_point %d bytes.", sizeof(ecc_point)); - p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC); - WOLFSSL_MSG("XMALLOC ecc_point complete."); - } - else { - WOLFSSL_MSG("XMALLOC ecc_point skipped! (p == NULL)"); + p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC); } #endif if (p == NULL) { - WOLFSSL_MSG("failed to XMALLOC ecc_point"); return MEMORY_E; } XMEMSET(p, 0, sizeof(ecc_point)); #ifndef ALT_ECC_SIZE - WOLFSSL_MSG("mp_init_multi for ecc x,y,z (!ALT_ECC_SIZE)"); err = mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL); if (err != MP_OKAY) { WOLFSSL_MSG("mp_init_multi failed."); @@ -4033,7 +4022,6 @@ static int wc_ecc_new_point_ex(ecc_point** point, void* heap) return err; } #else - WOLFSSL_MSG("alt_fp_init ecc x,y,z (ALT_ECC_SIZE)"); p->x = (mp_int*)&p->xyz[0]; p->y = (mp_int*)&p->xyz[1]; p->z = (mp_int*)&p->xyz[2]; @@ -4044,8 +4032,6 @@ static int wc_ecc_new_point_ex(ecc_point** point, void* heap) *point = p; (void)heap; - WOLFSSL_LEAVE("wc_ecc_new_point_ex", err); - return err; } /* wc_ecc_new_point_ex */ @@ -5192,7 +5178,6 @@ int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) #ifndef WOLFSSL_ECC_GEN_REJECT_SAMPLING int err; byte buf[ECC_MAXSIZE_GEN]; - WOLFSSL_ENTER("wc_ecc_gen_k"); if (rng == NULL || size < 0 || size + 8 > ECC_MAXSIZE_GEN || k == NULL || order == NULL) { @@ -5278,7 +5263,6 @@ int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) wc_MemZero_Check(buf, ECC_MAXSIZE_GEN); #endif - WOLFSSL_LEAVE("wc_ecc_gen_k", err); return err; #endif #else @@ -5318,9 +5302,9 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, #ifdef HAVE_ECC_MAKE_PUB ecc_point* pub; #endif /* HAVE_ECC_MAKE_PUB */ + (void)rng; - WOLFSSL_ENTER("ecc_make_pub_ex"); if (key == NULL) { return BAD_FUNC_ARG; } @@ -5417,7 +5401,6 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, ecc_point lcl_base; base = &lcl_base; #endif - err = wc_ecc_new_point_ex(&base, key->heap); /* read in the x/y for this key */ @@ -5474,7 +5457,7 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, } RESTORE_VECTOR_REGISTERS(); - WOLFSSL_LEAVE("ecc_make_pub_ex", err); + return err; } @@ -5535,8 +5518,6 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id, int flags) { int err = 0; - WOLFSSL_ENTER("_ecc_make_key_ex"); - #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \ !defined(WOLFSSL_ATECC608A) const CRYS_ECPKI_Domain_t* pDomain; @@ -5835,6 +5816,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, err = WC_KEY_SIZE_E; #else DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); + /* setup the key variables */ #ifndef ALT_ECC_SIZE err = mp_init(key->k); @@ -5846,7 +5828,6 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, /* load curve info */ if (err == MP_OKAY) { - WOLFSSL_MSG("load curve specs"); ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); if (err != MP_OKAY) { WOLFSSL_MSG("ALLOC_CURVE_SPECS failed"); @@ -5854,7 +5835,6 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, } if (err == MP_OKAY) { - err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); if (err != MP_OKAY) { WOLFSSL_MSG("wc_ecc_curve_load failed"); @@ -5907,7 +5887,6 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #endif #endif /* HAVE_ECC_MAKE_PUB */ - WOLFSSL_LEAVE("_ecc_make_key_ex", err); return err; #endif /* !WOLF_CRYPTO_CB_ONLY_ECC */ @@ -5918,9 +5897,9 @@ int wc_ecc_make_key_ex2(WC_RNG* rng, int keysize, ecc_key* key, int curve_id, int flags) { int err; - WOLFSSL_ENTER("wc_ecc_make_key_ex2"); SAVE_VECTOR_REGISTERS(return _svr_ret;); + err = _ecc_make_key_ex(rng, keysize, key, curve_id, flags); #if (FIPS_VERSION_GE(5,0) || defined(WOLFSSL_VALIDATE_ECC_KEYGEN)) && \ @@ -5946,7 +5925,6 @@ int wc_ecc_make_key_ex2(WC_RNG* rng, int keysize, ecc_key* key, int curve_id, WOLFSSL_ABI int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id) { - WOLFSSL_ENTER("wc_ecc_make_key_ex"); return wc_ecc_make_key_ex2(rng, keysize, key, curve_id, WC_ECC_FLAG_NONE); } diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index 6be10f6..af5f09a 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -460,10 +460,16 @@ WC_MISC_STATIC WC_INLINE void c16toa(word16 wc_u16, byte* c) /* convert 32 bit integer to opaque */ WC_MISC_STATIC WC_INLINE void c32toa(word32 wc_u32, byte* c) { +#ifdef WOLFSSL_USE_ALIGN c[0] = (byte)((wc_u32 >> 24) & 0xff); c[1] = (byte)((wc_u32 >> 16) & 0xff); c[2] = (byte)((wc_u32 >> 8) & 0xff); c[3] = (byte)(wc_u32 & 0xff); +#elif defined(LITTLE_ENDIAN_ORDER) + *(word32*)c = ByteReverseWord32(wc_u32); +#else + *(word32*)c = wc_u32; +#endif } #endif @@ -492,10 +498,16 @@ WC_MISC_STATIC WC_INLINE void ato16(const byte* c, word16* wc_u16) /* convert opaque to 32 bit integer */ WC_MISC_STATIC WC_INLINE void ato32(const byte* c, word32* wc_u32) { +#ifdef WOLFSSL_USE_ALIGN *wc_u32 = ((word32)c[0] << 24) | ((word32)c[1] << 16) | ((word32)c[2] << 8) | (word32)c[3]; +#elif defined(LITTLE_ENDIAN_ORDER) + *wc_u32 = ByteReverseWord32(*(word32*)c); +#else + *wc_u32 = *(word32*)c; +#endif } /* convert opaque to 32 bit integer. Interpret as little endian. */ diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index 1305609..997fd4f 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -1507,6 +1507,7 @@ typedef struct ESD { wc_HashAlg hash; enum wc_HashType hashType; byte contentDigest[WC_MAX_DIGEST_SIZE + 2]; /* content only + ASN.1 heading */ + byte contentDigestSet:1; byte contentAttribsDigest[WC_MAX_DIGEST_SIZE]; byte encContentDigest[MAX_ENCRYPTED_KEY_SZ]; @@ -1760,27 +1761,10 @@ static int FlattenAttributes(PKCS7* pkcs7, byte* output, EncodedAttrib* ea, #ifndef NO_RSA -/* returns size of signature put into out, negative on error */ -static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +static int wc_PKCS7_ImportRSA(PKCS7* pkcs7, RsaKey* privKey) { int ret; word32 idx; -#ifdef WOLFSSL_SMALL_STACK - RsaKey* privKey; -#else - RsaKey privKey[1]; -#endif - - if (pkcs7 == NULL || pkcs7->rng == NULL || in == NULL || esd == NULL) { - return BAD_FUNC_ARG; - } - -#ifdef WOLFSSL_SMALL_STACK - privKey = (RsaKey*)XMALLOC(sizeof(RsaKey), pkcs7->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (privKey == NULL) - return MEMORY_E; -#endif ret = wc_InitRsaKey_ex(privKey, pkcs7->heap, pkcs7->devId); if (ret == 0) { @@ -1814,6 +1798,32 @@ static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) } } + return ret; +} + + +/* returns size of signature put into out, negative on error */ +static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +{ + int ret; +#ifdef WOLFSSL_SMALL_STACK + RsaKey* privKey; +#else + RsaKey privKey[1]; +#endif + + if (pkcs7 == NULL || pkcs7->rng == NULL || in == NULL || esd == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + privKey = (RsaKey*)XMALLOC(sizeof(RsaKey), pkcs7->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (privKey == NULL) + return MEMORY_E; +#endif + + ret = wc_PKCS7_ImportRSA(pkcs7, privKey); if (ret == 0) { #ifdef WOLFSSL_ASYNC_CRYPT do { @@ -1844,27 +1854,10 @@ static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) #ifdef HAVE_ECC -/* returns size of signature put into out, negative on error */ -static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +static int wc_PKCS7_ImportECC(PKCS7* pkcs7, ecc_key* privKey) { int ret; - word32 outSz, idx; -#ifdef WOLFSSL_SMALL_STACK - ecc_key* privKey; -#else - ecc_key privKey[1]; -#endif - - if (pkcs7 == NULL || pkcs7->rng == NULL || in == NULL || esd == NULL) { - return BAD_FUNC_ARG; - } - -#ifdef WOLFSSL_SMALL_STACK - privKey = (ecc_key*)XMALLOC(sizeof(ecc_key), pkcs7->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (privKey == NULL) - return MEMORY_E; -#endif + word32 idx; ret = wc_ecc_init_ex(privKey, pkcs7->heap, pkcs7->devId); if (ret == 0) { @@ -1894,6 +1887,33 @@ static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) } } + return ret; +} + + +/* returns size of signature put into out, negative on error */ +static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +{ + int ret; + word32 outSz; +#ifdef WOLFSSL_SMALL_STACK + ecc_key* privKey; +#else + ecc_key privKey[1]; +#endif + + if (pkcs7 == NULL || pkcs7->rng == NULL || in == NULL || esd == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + privKey = (ecc_key*)XMALLOC(sizeof(ecc_key), pkcs7->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (privKey == NULL) + return MEMORY_E; +#endif + + ret = wc_PKCS7_ImportECC(pkcs7, privKey); if (ret == 0) { outSz = sizeof(esd->encContentDigest); #ifdef WOLFSSL_ASYNC_CRYPT @@ -1923,6 +1943,67 @@ static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) #endif /* HAVE_ECC */ +/* returns encContentDigestSz based on the signature set to be used */ +static int wc_PKCS7_GetSignSize(PKCS7* pkcs7) +{ + int ret = 0; + + switch (pkcs7->publicKeyOID) { + + #ifndef NO_RSA + case RSAk: + { + #ifndef WOLFSSL_SMALL_STACK + RsaKey privKey[1]; + #else + RsaKey* privKey; + privKey = (RsaKey*)XMALLOC(sizeof(RsaKey), pkcs7->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (privKey == NULL) + return MEMORY_E; + #endif + + ret = wc_PKCS7_ImportRSA(pkcs7, privKey); + if (ret == 0) { + ret = wc_RsaEncryptSize(privKey); + } + wc_FreeRsaKey(privKey); + #ifdef WOLFSSL_SMALL_STACK + XFREE(privKey, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + break; + #endif + + #ifdef HAVE_ECC + case ECDSAk: + { + #ifndef WOLFSSL_SMALL_STACK + ecc_key privKey[1]; + #else + ecc_key* privKey; + privKey = (ecc_key*)XMALLOC(sizeof(ecc_key), pkcs7->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (privKey == NULL) + return MEMORY_E; + #endif + + ret = wc_PKCS7_ImportECC(pkcs7, privKey); + if (ret == 0) { + ret = wc_ecc_sig_size(privKey); + } + wc_ecc_free(privKey); + #ifdef WOLFSSL_SMALL_STACK + XFREE(privKey, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + break; + #endif + } + + return ret; +} + /* builds up SignedData signed attributes, including default ones. * @@ -2365,10 +2446,286 @@ static int wc_PKCS7_SignedDataBuildSignature(PKCS7* pkcs7, return ret; } +#ifndef BER_OCTET_LENGTH + #define BER_OCTET_LENGTH 4096 +#endif + +/** + * This helper function encodes a chunk of content stream and writes it out. + * + * @param pkcs7 Pointer to a PKCS7 structure. + * @param cipherType The type of cipher to use for encryption. + * @param aes Optional pointer to an Aes structure for AES encryption. + * @param encContentOut Buffer to hold the encrypted content. + * @param contentData Buffer holding the content to be encrypted. + * @param contentDataSz Size of the content to be encrypted. + * @param out Buffer to hold the output data. + * @param outIdx Pointer to an index into the output buffer. + * @param esd Pointer to an ESD structure for digest calculation. + * @return Returns 0 on success, and a negative value on failure. + */ +static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, + Aes* aes, byte* encContentOut, byte* contentData, int contentDataSz, + byte* out, word32* outIdx, ESD* esd) +{ + int ret = BAD_FUNC_ARG; + byte encContentOutOct[MAX_OCTET_STR_SZ]; + word32 encContentOutOctSz = 0; + + switch (cipherType) { + case WC_CIPHER_NONE: + XMEMCPY(encContentOut, contentData, contentDataSz); + if (esd && esd->contentDigestSet != 1) { + ret = wc_HashUpdate(&esd->hash, esd->hashType, + contentData, contentDataSz); + } + break; + + #ifndef NO_AES + case WC_CIPHER_AES_CBC: + ret = wc_AesCbcEncrypt(aes, encContentOut, + contentData, contentDataSz); + break; + #endif + + #ifdef WOLFSSL_AESGCM_STREAM + case WC_CIPHER_AES_GCM: + ret = wc_AesGcmEncryptUpdate(aes, encContentOut, + contentData, contentDataSz, NULL, 0); + break; + #endif + } + + #ifdef WOLFSSL_ASYNC_CRYPT + /* async encrypt not available here, so block till done */ + if (ret == WC_PENDING_E && cipherType != WC_CIPHER_NONE) { + ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); + } + #endif + + if (ret == 0) { + encContentOutOctSz = SetOctetString(contentDataSz, encContentOutOct); + wc_PKCS7_WriteOut(pkcs7, (out)? out + *outIdx: NULL, + encContentOutOct, encContentOutOctSz); + *outIdx += encContentOutOctSz; + wc_PKCS7_WriteOut(pkcs7, (out)? out + *outIdx : NULL, + encContentOut, contentDataSz); + *outIdx += contentDataSz; + } + + return ret; +} + + +/* Used for encoding the content, potentially one octet chunck at a time if + * in streaming mode with IO callbacks set. + * Can handle the cipher types: + * - WC_CIPHER_NONE, used for encoding signed bundle where no encryption is + * done. + * - WC_CIPHER_AES_CBC + * - WC_CIPHER_AES_GCM, requires WOLFSSL_AESGCM_STREAM for streaming + * encryption + * If ESD is passed in then hash of the conentet is collected as processed. + * + * Returns 0 on success */ +#ifndef NO_AES +static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, Aes* aes, + byte* in, int inSz, byte* out, int cipherType) +#else +static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, + byte* in, int inSz, byte* out, int cipherType) +#endif +{ + int ret = 0; + int devId = pkcs7->devId; + void* heap = pkcs7->heap; + + if (pkcs7->encodeStream) { + int sz; + word32 totalSz = 0; + byte* buf; + byte* encContentOut; + byte* contentData; + word32 idx = 0, outIdx = 0; + int padSz = 0; + + if (cipherType != WC_CIPHER_NONE) { + padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, + wc_PKCS7_GetOIDBlockSize(pkcs7->encryptOID)); + } + + if (cipherType == WC_CIPHER_NONE && esd && esd->contentDigestSet != 1) { + /* calculate hash for content */ + ret = wc_HashInit(&esd->hash, esd->hashType); + if (ret != 0) { + return ret; + } + } + + encContentOut = (byte *)XMALLOC(BER_OCTET_LENGTH + MAX_OCTET_STR_SZ, + heap, DYNAMIC_TYPE_PKCS7); + contentData = (byte *)XMALLOC(BER_OCTET_LENGTH + padSz, + heap, DYNAMIC_TYPE_PKCS7); + + if (encContentOut == NULL || contentData == NULL) { + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + WOLFSSL_MSG("Memory allocation failed for content data"); + return MEMORY_E; + } + + /* keep pulling from content until empty */ + do { + int contentDataRead = 0; + + #ifdef ASN_BER_TO_DER + if (pkcs7->getContentCb) { + contentDataRead = pkcs7->getContentCb(pkcs7, + &buf, pkcs7->streamCtx); + + if (buf == NULL) { + WOLFSSL_MSG("Get content callback returned null " + "buffer pointer"); + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + return BAD_FUNC_ARG; + } + } + else + #endif + { + int szLeft = BER_OCTET_LENGTH; + + if (in == NULL) { + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + return BAD_FUNC_ARG; + } + + if (szLeft + totalSz > (word32)inSz) + szLeft = inSz - totalSz; + + contentDataRead = szLeft; + buf = in + totalSz; + } + + if (contentDataRead <= 0) { + /* no more data returned from callback */ + break; + } + totalSz += (word32)contentDataRead; + + /* check and handle octet boundary */ + sz = contentDataRead; + if (idx + sz > BER_OCTET_LENGTH) { + sz = BER_OCTET_LENGTH - idx; + contentDataRead -= sz; + + XMEMCPY(contentData + idx, buf, sz); + ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, + aes, encContentOut, contentData, BER_OCTET_LENGTH, out, + &outIdx, esd); + if (ret != 0) { + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + return ret; + } + + /* copy over any remaining data */ + XMEMCPY(contentData, buf + sz, contentDataRead); + idx = contentDataRead; + } + else { + /* was not on an octet boundary, copy full + * amount over */ + XMEMCPY(contentData + idx, buf, sz); + idx += sz; + } + } while (totalSz < pkcs7->contentSz); + + /* add in padding to the end */ + if ((cipherType != WC_CIPHER_NONE) && (totalSz == pkcs7->contentSz)) { + int i; + + if (BER_OCTET_LENGTH < idx) { + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + return BAD_FUNC_ARG; + } + + for (i = 0; i < padSz; i++) { + contentData[idx + i] = (byte)padSz; + } + idx += padSz; + } + + /* encrypt and flush out remainder of content data */ + ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, aes, + encContentOut, contentData, idx, out, &outIdx, esd); + if (ret == 0) { + if (cipherType == WC_CIPHER_NONE && esd && + esd->contentDigestSet != 1) { + ret = wc_HashFinal(&esd->hash, esd->hashType, + esd->contentDigest + 2); + wc_HashFree(&esd->hash, esd->hashType); + } + } + + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + } + else { + if (in == NULL || out == NULL) { + return BAD_FUNC_ARG; + } + + switch (cipherType) { + case WC_CIPHER_NONE: + if (!pkcs7->detached) { + XMEMCPY(out, in, inSz); + } + if (esd && esd->contentDigestSet != 1) { + ret = wc_HashInit(&esd->hash, esd->hashType); + if (ret == 0) + ret = wc_HashUpdate(&esd->hash, esd->hashType, in, + inSz); + if (ret == 0) + ret = wc_HashFinal(&esd->hash, esd->hashType, + esd->contentDigest + 2); + wc_HashFree(&esd->hash, esd->hashType); + } + break; + + #ifndef NO_AES + case WC_CIPHER_AES_CBC: + ret = wc_AesCbcEncrypt(aes, out, in, inSz); + break; + #endif + + #ifdef WOLFSSL_AESGCM_STREAM + case WC_CIPHER_AES_GCM: + ret = wc_AesGcmEncryptUpdate(aes, out, in, inSz, NULL, 0); + break; + #endif + } + #ifdef WOLFSSL_ASYNC_CRYPT + /* async encrypt not available here, so block till done */ + if (cipherType != WC_CIPHER_NONE) { + ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); + } + #endif + } + + (void)devId; + (void)heap; + + return ret; +} + /* build PKCS#7 signedData content type */ /* To get the output size then set output = 0 and *outputSz = 0 */ -static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, +static int PKCS7_EncodeSigned(PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* output, word32* outputSz, byte* output2, word32* output2Sz) { @@ -2398,6 +2755,14 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, byte* flatSignedAttribs = NULL; word32 flatSignedAttribsSz = 0; +#ifdef WOLFSSL_SMALL_STACK + ESD* esd = NULL; +#else + ESD esd[1]; +#endif +#ifdef ASN_BER_TO_DER + word32 streamSz = 0; +#endif #ifdef WOLFSSL_SMALL_STACK byte *signedDataOid = NULL; #else @@ -2408,8 +2773,21 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, byte signingTime[MAX_TIME_STRING_SZ]; if (pkcs7 == NULL || pkcs7->hashOID == 0 || - outputSz == NULL || hashSz == 0 || - hashBuf == NULL) { + outputSz == NULL) { + WOLFSSL_MSG("PKCS7 struct / outputSz null, or hashOID is 0"); + return BAD_FUNC_ARG; + } + + if (hashSz == 0 && hashBuf != NULL) { + return BAD_FUNC_ARG; + } + + /* signature size varies with ECDSA, with a varying sign size the content + * hash must be known in order to create the surrounding ASN1 syntax + * properly before writing out the content and generating the hash on the + * fly and then creating the signature */ + if (hashBuf == NULL && pkcs7->publicKeyOID == ECDSAk) { + WOLFSSL_MSG("Pre-calculated content hash is needed in this case"); return BAD_FUNC_ARG; } @@ -2464,16 +2842,24 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, if (pkcs7->sidType != DEGENERATE_SID) { esd->hashType = wc_OidGetHash(pkcs7->hashOID); - if (wc_HashGetDigestSize(esd->hashType) != (int)hashSz) { + if (hashBuf != NULL && + wc_HashGetDigestSize(esd->hashType) != (int)hashSz) { WOLFSSL_MSG("hashSz did not match hashOID"); idx = BUFFER_E; goto out; } - /* include hash */ + /* include hash if provided, otherwise create hash when processing + * content data */ esd->contentDigest[0] = ASN_OCTET_STRING; - esd->contentDigest[1] = (byte)hashSz; - XMEMCPY(&esd->contentDigest[2], hashBuf, hashSz); + if (hashBuf != NULL) { + esd->contentDigestSet = 1; + esd->contentDigest[1] = (byte)hashSz; + XMEMCPY(&esd->contentDigest[2], hashBuf, hashSz); + } + else { + esd->contentDigest[1] = (byte)wc_HashGetDigestSize(esd->hashType); + } } if (pkcs7->detached == 1) { @@ -2579,9 +2965,13 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, esd->signedAttribSetSz = 0; } - /* Calculate the final hash and encrypt it. */ - ret = wc_PKCS7_SignedDataBuildSignature(pkcs7, flatSignedAttribs, - flatSignedAttribsSz, esd); + if (pkcs7->publicKeyOID != ECDSAk && hashBuf == NULL) { + ret = esd->encContentDigestSz = wc_PKCS7_GetSignSize(pkcs7); + } + else { + ret = wc_PKCS7_SignedDataBuildSignature(pkcs7, flatSignedAttribs, + flatSignedAttribsSz, esd); + } if (ret < 0) { idx = ret; goto out; @@ -2633,11 +3023,12 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { - word32 sz = 0, tmpIdx = 0; + word32 tmpIdx = 0; totalSz += (3 * ASN_INDEF_END_SZ) ; /* 00's for BER with inner content */ - StreamOctetString(pkcs7->content, pkcs7->contentSz, NULL, &sz, &tmpIdx); - totalSz += sz + (3 * ASN_INDEF_END_SZ); + StreamOctetString(pkcs7->content, pkcs7->contentSz, NULL, &streamSz, + &tmpIdx); + totalSz += streamSz + (3 * ASN_INDEF_END_SZ); } else #endif @@ -2693,7 +3084,11 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, totalSz += total2Sz; } - if (totalSz > *outputSz) { + if (totalSz > *outputSz + #ifdef ASN_BER_TO_DER + && pkcs7->streamOutCb == NULL + #endif + ) { if (*outputSz == 0) { #ifdef HAVE_ECC if (pkcs7->publicKeyOID == ECDSAk) { @@ -2708,33 +3103,48 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, goto out; } +#ifdef ASN_BER_TO_DER + if (output == NULL && pkcs7->streamOutCb == NULL) { +#else if (output == NULL) { +#endif idx = BUFFER_E; goto out; } idx = 0; - XMEMCPY(output + idx, esd->outerSeq, esd->outerSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->outerSeq, esd->outerSeqSz); idx += esd->outerSeqSz; - XMEMCPY(output + idx, signedDataOid, signedDataOidSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + signedDataOid, signedDataOidSz); idx += signedDataOidSz; - XMEMCPY(output + idx, esd->outerContent, esd->outerContentSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->outerContent, esd->outerContentSz); idx += esd->outerContentSz; - XMEMCPY(output + idx, esd->innerSeq, esd->innerSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->innerSeq, esd->innerSeqSz); idx += esd->innerSeqSz; - XMEMCPY(output + idx, esd->version, esd->versionSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->version, esd->versionSz); idx += esd->versionSz; - XMEMCPY(output + idx, esd->digAlgoIdSet, esd->digAlgoIdSetSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->digAlgoIdSet, esd->digAlgoIdSetSz); idx += esd->digAlgoIdSetSz; - XMEMCPY(output + idx, esd->singleDigAlgoId, esd->singleDigAlgoIdSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->singleDigAlgoId, esd->singleDigAlgoIdSz); idx += esd->singleDigAlgoIdSz; - XMEMCPY(output + idx, esd->contentInfoSeq, esd->contentInfoSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->contentInfoSeq, esd->contentInfoSeqSz); idx += esd->contentInfoSeqSz; - XMEMCPY(output + idx, pkcs7->contentType, pkcs7->contentTypeSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + pkcs7->contentType, pkcs7->contentTypeSz); idx += pkcs7->contentTypeSz; - XMEMCPY(output + idx, esd->innerContSeq, esd->innerContSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->innerContSeq, esd->innerContSeqSz); idx += esd->innerContSeqSz; - XMEMCPY(output + idx, esd->innerOctets, esd->innerOctetsSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + esd->innerOctets, esd->innerOctetsSz); idx += esd->innerOctetsSz; /* support returning header and footer without content */ @@ -2743,39 +3153,56 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, idx = 0; } else { - if (!pkcs7->detached && pkcs7->content != NULL && pkcs7->contentSz > 0) { + if ( #ifdef ASN_BER_TO_DER - if (pkcs7->encodeStream) { - StreamOctetString(pkcs7->content, pkcs7->contentSz, output, - outputSz, (word32*)&idx); + (pkcs7->content != NULL || pkcs7->getContentCb != NULL) + #else + pkcs7->content != NULL + #endif + && pkcs7->contentSz > 0) { + wc_PKCS7_EncodeContentStream(pkcs7, esd, NULL, pkcs7->content, + pkcs7->contentSz, (output)? output + idx : NULL, WC_CIPHER_NONE); + if (!pkcs7->detached) { + #ifdef ASN_BER_TO_DER + if (pkcs7->encodeStream) { + byte indefEnd[ASN_INDEF_END_SZ * 3]; + word32 localIdx = 0; - /* end of content octet string */ - idx += SetIndefEnd(output + idx); + idx += streamSz; - /* end of inner content seq */ - idx += SetIndefEnd(output + idx); + /* end of content octet string */ + localIdx += SetIndefEnd(indefEnd + localIdx); - /* end of inner content info seq */ - idx += SetIndefEnd(output + idx); - } - else - #endif - { - XMEMCPY(output + idx, pkcs7->content, pkcs7->contentSz); - idx += pkcs7->contentSz; + /* end of inner content seq */ + localIdx += SetIndefEnd(indefEnd + localIdx); + + /* end of inner content info seq */ + localIdx += SetIndefEnd(indefEnd + localIdx); + + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + indefEnd, localIdx); + idx += localIdx; + } + else + #endif + { + idx += pkcs7->contentSz; + } } } output2 = output; } /* certificates */ - XMEMCPY(output2 + idx, esd->certsSet, esd->certsSetSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->certsSet, esd->certsSetSz); idx += esd->certsSetSz; if (pkcs7->noCerts != 1) { certPtr = pkcs7->certList; while (certPtr != NULL) { - XMEMCPY(output2 + idx, certPtr->der, certPtr->derSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + certPtr->der, certPtr->derSz); idx += certPtr->derSz; certPtr = certPtr->next; } @@ -2783,30 +3210,40 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, wc_PKCS7_FreeCertSet(pkcs7); - XMEMCPY(output2 + idx, esd->signerInfoSet, esd->signerInfoSetSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signerInfoSet, esd->signerInfoSetSz); idx += esd->signerInfoSetSz; - XMEMCPY(output2 + idx, esd->signerInfoSeq, esd->signerInfoSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signerInfoSeq, esd->signerInfoSeqSz); idx += esd->signerInfoSeqSz; - XMEMCPY(output2 + idx, esd->signerVersion, esd->signerVersionSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signerVersion, esd->signerVersionSz); idx += esd->signerVersionSz; /* SignerIdentifier */ if (pkcs7->sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { /* IssuerAndSerialNumber */ - XMEMCPY(output2 + idx, esd->issuerSnSeq, esd->issuerSnSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->issuerSnSeq, esd->issuerSnSeqSz); idx += esd->issuerSnSeqSz; - XMEMCPY(output2 + idx, esd->issuerName, esd->issuerNameSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->issuerName, esd->issuerNameSz); idx += esd->issuerNameSz; - XMEMCPY(output2 + idx, pkcs7->issuer, pkcs7->issuerSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + pkcs7->issuer, pkcs7->issuerSz); idx += pkcs7->issuerSz; - XMEMCPY(output2 + idx, esd->issuerSn, esd->issuerSnSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->issuerSn, esd->issuerSnSz); idx += esd->issuerSnSz; } else if (pkcs7->sidType == CMS_SKID) { /* SubjectKeyIdentifier */ - XMEMCPY(output2 + idx, esd->issuerSKIDSeq, esd->issuerSKIDSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->issuerSKIDSeq, esd->issuerSKIDSeqSz); idx += esd->issuerSKIDSeqSz; - XMEMCPY(output2 + idx, esd->issuerSKID, esd->issuerSKIDSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->issuerSKID, esd->issuerSKIDSz); idx += esd->issuerSKIDSz; - XMEMCPY(output2 + idx, pkcs7->issuerSubjKeyId, keyIdSize); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + pkcs7->issuerSubjKeyId, keyIdSize); idx += keyIdSize; } else if (pkcs7->sidType == DEGENERATE_SID) { /* no signer infos in degenerate case */ @@ -2814,34 +3251,92 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, ESD* esd, idx = SKID_E; goto out; } - XMEMCPY(output2 + idx, esd->signerDigAlgoId, esd->signerDigAlgoIdSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signerDigAlgoId, esd->signerDigAlgoIdSz); idx += esd->signerDigAlgoIdSz; /* SignerInfo:Attributes */ if (flatSignedAttribsSz > 0) { - XMEMCPY(output2 + idx, esd->signedAttribSet, esd->signedAttribSetSz); + /* if the original hash buffer passed in was null then recreate the + * signature */ + if (hashBuf == NULL && pkcs7->sidType != DEGENERATE_SID) { + /* recreate flat attribs after the content hash is known if needed + * build up signed attributes, include contentType, signingTime, and + messageDigest by default */ + esd->signedAttribsCount = 0; + esd->signedAttribsSz = 0; + ret = wc_PKCS7_BuildSignedAttributes(pkcs7, esd, pkcs7->contentType, + pkcs7->contentTypeSz, + contentTypeOid, sizeof(contentTypeOid), + messageDigestOid, sizeof(messageDigestOid), + signingTimeOid, sizeof(signingTimeOid), + signingTime, sizeof(signingTime)); + if (ret < 0) { + idx = ret; + goto out; + } + + if (esd->signedAttribsSz > 0) { + if (flatSignedAttribs == NULL) { + idx = MEMORY_E; + goto out; + } + + flatSignedAttribsSz = esd->signedAttribsSz; + FlattenAttributes(pkcs7, flatSignedAttribs, + esd->signedAttribs, esd->signedAttribsCount); + } else { + esd->signedAttribSetSz = 0; + } + } + + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signedAttribSet, esd->signedAttribSetSz); idx += esd->signedAttribSetSz; - XMEMCPY(output2 + idx, flatSignedAttribs, flatSignedAttribsSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + flatSignedAttribs, flatSignedAttribsSz); idx += flatSignedAttribsSz; } - XMEMCPY(output2 + idx, esd->digEncAlgoId, esd->digEncAlgoIdSz); + if (hashBuf == NULL && pkcs7->sidType != DEGENERATE_SID) { + /* Calculate the final hash and encrypt it. */ + WOLFSSL_MSG("Recreating signature with new hash"); + ret = wc_PKCS7_SignedDataBuildSignature(pkcs7, flatSignedAttribs, + flatSignedAttribsSz, esd); + if (ret < 0) { + idx = ret; + goto out; + } + } + + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->digEncAlgoId, esd->digEncAlgoIdSz); idx += esd->digEncAlgoIdSz; - XMEMCPY(output2 + idx, esd->signerDigest, esd->signerDigestSz); + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->signerDigest, esd->signerDigestSz); idx += esd->signerDigestSz; - XMEMCPY(output2 + idx, esd->encContentDigest, esd->encContentDigestSz); + + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + esd->encContentDigest, esd->encContentDigestSz); idx += esd->encContentDigestSz; #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { + byte indefEnd[ASN_INDEF_END_SZ * 3]; + word32 localIdx = 0; + /* end of signedData seq */ - idx += SetIndefEnd(output2 + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of outer content set */ - idx += SetIndefEnd(output2 + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of outer content info seq */ - idx += SetIndefEnd(output2 + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); + + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + indefEnd, localIdx); + idx += localIdx; } #endif @@ -2881,32 +3376,25 @@ int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, word32* outputFootSz) { int ret; -#ifdef WOLFSSL_SMALL_STACK - ESD* esd; -#else - ESD esd[1]; -#endif /* other args checked in wc_PKCS7_EncodeSigned_ex */ - if (pkcs7 == NULL || outputFoot == NULL || outputFootSz == NULL) { + if (pkcs7 == NULL) { return BAD_FUNC_ARG; } -#ifdef WOLFSSL_SMALL_STACK - esd = (ESD*)XMALLOC(sizeof(ESD), pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (esd == NULL) - return MEMORY_E; +#ifndef ASN_BER_TO_DER + if (outputFoot == NULL || outputFootSz == NULL) +#else + if (pkcs7->getContentCb == NULL && + (outputFoot == NULL || outputFootSz == NULL)) #endif + { + return BAD_FUNC_ARG; + } - XMEMSET(esd, 0, sizeof(ESD)); - - ret = PKCS7_EncodeSigned(pkcs7, esd, hashBuf, hashSz, + ret = PKCS7_EncodeSigned(pkcs7, hashBuf, hashSz, outputHead, outputHeadSz, outputFoot, outputFootSz); -#ifdef WOLFSSL_SMALL_STACK - XFREE(esd, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return ret; } @@ -2993,55 +3481,50 @@ int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag) int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) { int ret; - int hashSz; - enum wc_HashType hashType; - byte hashBuf[WC_MAX_DIGEST_SIZE]; -#ifdef WOLFSSL_SMALL_STACK - ESD* esd; -#else - ESD esd[1]; -#endif /* other args checked in wc_PKCS7_EncodeSigned_ex */ - if (pkcs7 == NULL || (pkcs7->contentSz > 0 && pkcs7->content == NULL)) { + if (pkcs7 == NULL || (pkcs7->contentSz > 0 && + #ifdef ASN_BER_TO_DER + (pkcs7->content == NULL && pkcs7->getContentCb == NULL)) + #else + pkcs7->content == NULL) + #endif + ) { return BAD_FUNC_ARG; } - /* get hash type and size, validate hashOID */ - hashType = wc_OidGetHash(pkcs7->hashOID); - hashSz = wc_HashGetDigestSize(hashType); - if (hashSz < 0) - return hashSz; - -#ifdef WOLFSSL_SMALL_STACK - esd = (ESD*)XMALLOC(sizeof(ESD), pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (esd == NULL) - return MEMORY_E; -#endif + /* pre-calculate hash for ECC signatures */ + if (pkcs7->publicKeyOID == ECDSAk) { + int hashSz; + enum wc_HashType hashType; + byte hashBuf[WC_MAX_DIGEST_SIZE]; + wc_HashAlg hash; - XMEMSET(esd, 0, sizeof(ESD)); - esd->hashType = hashType; + /* get hash type and size, validate hashOID */ + hashType = wc_OidGetHash(pkcs7->hashOID); + hashSz = wc_HashGetDigestSize(hashType); + if (hashSz < 0) + return hashSz; - /* calculate hash for content */ - ret = wc_HashInit(&esd->hash, esd->hashType); - if (ret == 0) { - ret = wc_HashUpdate(&esd->hash, esd->hashType, + /* calculate hash for content */ + ret = wc_HashInit(&hash, hashType); + if (ret == 0) { + ret = wc_HashUpdate(&hash, hashType, pkcs7->content, pkcs7->contentSz); + if (ret == 0) { + ret = wc_HashFinal(&hash, hashType, hashBuf); + } + wc_HashFree(&hash, hashType); + } if (ret == 0) { - ret = wc_HashFinal(&esd->hash, esd->hashType, hashBuf); + ret = PKCS7_EncodeSigned(pkcs7, hashBuf, hashSz, + output, &outputSz, NULL, NULL); } - wc_HashFree(&esd->hash, esd->hashType); } - - if (ret == 0) { - ret = PKCS7_EncodeSigned(pkcs7, esd, hashBuf, hashSz, - output, &outputSz, NULL, NULL); + else { + ret = PKCS7_EncodeSigned(pkcs7, NULL, 0, output, &outputSz, + NULL, NULL); } - -#ifdef WOLFSSL_SMALL_STACK - XFREE(esd, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return ret; } @@ -5710,6 +6193,9 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, contentDynamic = (byte*)XMALLOC(contentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (contentDynamic == NULL) { + #ifndef NO_PKCS7_STREAM + pkcs7->stream = stream; + #endif ret = MEMORY_E; break; } @@ -7543,12 +8029,52 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, #endif /* !NO_RSA */ +/* abstraction for writing out PKCS7 bundle during creation + returns 0 on success + */ +int wc_PKCS7_WriteOut(PKCS7* pkcs7, byte* output, const byte* input, + word32 inputSz) +{ + int ret = 0; + + if (inputSz == 0) + return 0; + + if (input == NULL) { + WOLFSSL_MSG("Internal error, trying to write out NULL buffer"); + return -1; + } + +#ifdef ASN_BER_TO_DER + if (pkcs7->streamOutCb) { + ret = pkcs7->streamOutCb(pkcs7, input, inputSz, pkcs7->streamCtx); + /* sanity check on user provided ret value */ + if (ret < 0) { + WOLFSSL_MSG("Return value error from stream out callback"); + ret = BUFFER_E; + } + } + else +#endif + if (output) { + XMEMCPY(output, input, inputSz); + } + else { + WOLFSSL_MSG("No way provided to output bundle"); + ret = BUFFER_E; + } + + (void)pkcs7; + return ret; +} + /* encrypt content using encryptOID algo */ -static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, +static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, + int keySz, byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, word32 authTagSz, byte* in, - int inSz, byte* out, int devId, void* heap) + int inSz, byte* out) { int ret; #ifndef NO_AES @@ -7562,9 +8088,22 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, Des des; Des3 des3; #endif + int devId = pkcs7->devId; + void* heap = pkcs7->heap; - if (key == NULL || iv == NULL || in == NULL || out == NULL) + if (key == NULL || iv == NULL) + return BAD_FUNC_ARG; + +#ifdef ASN_BER_TO_DER + if ((in == NULL && pkcs7->getContentCb == NULL) || + (out == NULL && pkcs7->streamOutCb == NULL)) { + WOLFSSL_MSG("No input or output set for encrypt"); + return BAD_FUNC_ARG; + } +#else + if (in == NULL || out == NULL) return BAD_FUNC_ARG; +#endif switch (encryptOID) { #ifndef NO_AES @@ -7600,11 +8139,8 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, if (ret == 0) { ret = wc_AesSetKey(aes, key, keySz, iv, AES_ENCRYPTION); if (ret == 0) { - ret = wc_AesCbcEncrypt(aes, out, in, inSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async encrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); - #endif + ret = wc_PKCS7_EncodeContentStream(pkcs7, NULL, aes, in, + inSz, out, WC_CIPHER_AES_CBC); } wc_AesFree(aes); } @@ -7637,11 +8173,34 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, if (ret == 0) { ret = wc_AesGcmSetKey(aes, key, keySz); if (ret == 0) { - ret = wc_AesGcmEncrypt(aes, out, in, inSz, iv, ivSz, + #ifndef WOLFSSL_AESGCM_STREAM + if (pkcs7->encodeStream) { + WOLFSSL_MSG("Not AES-GCM stream support compiled in"); + ret = NOT_COMPILED_IN; + } + else { + ret = wc_AesGcmEncrypt(aes, out, in, inSz, iv, ivSz, authTag, authTagSz, aad, aadSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async encrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); + #ifdef WOLFSSL_ASYNC_CRYPT + /* async encrypt not available here, so block till done */ + ret = wc_AsyncWait(ret, &aes->asyncDev, + WC_ASYNC_FLAG_NONE); + #endif + } + #else + ret = wc_AesGcmEncryptInit(aes, key, keySz, iv, ivSz); + if (ret == 0) { + ret = wc_AesGcmEncryptUpdate(aes, NULL, NULL, 0, aad, + aadSz); + } + if (ret == 0) { + ret = wc_PKCS7_EncodeContentStream(pkcs7, NULL, aes, in, + inSz, out, WC_CIPHER_AES_GCM); + } + + if (ret == 0) { + ret = wc_AesGcmEncryptFinal(aes, authTag, authTagSz); + } #endif } wc_AesFree(aes); @@ -7667,6 +8226,11 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, if (authTag == NULL) return BAD_FUNC_ARG; + if (pkcs7->encodeStream) { + WOLFSSL_MSG("Streaming encoding not supported with AES-CCM"); + return BAD_FUNC_ARG; + } + #ifdef WOLFSSL_SMALL_STACK if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, DYNAMIC_TYPE_AES)) == NULL) @@ -7697,6 +8261,11 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, if (keySz != DES_KEYLEN || ivSz != DES_BLOCK_SIZE) return BAD_FUNC_ARG; + if (pkcs7->encodeStream) { + WOLFSSL_MSG("Streaming encoding not supported with DES3"); + return BAD_FUNC_ARG; + } + ret = wc_Des_SetKey(&des, key, iv, DES_ENCRYPTION); if (ret == 0) ret = wc_Des_CbcEncrypt(&des, out, in, inSz); @@ -7707,6 +8276,11 @@ static int wc_PKCS7_EncryptContent(int encryptOID, byte* key, int keySz, if (keySz != DES3_KEYLEN || ivSz != DES_BLOCK_SIZE) return BAD_FUNC_ARG; + if (pkcs7->encodeStream) { + WOLFSSL_MSG("Streaming encoding not supported with DES3"); + return BAD_FUNC_ARG; + } + ret = wc_Des3Init(&des3, heap, devId); if (ret == 0) { ret = wc_Des3_SetKey(&des3, key, iv, DES_ENCRYPTION); @@ -8255,17 +8829,17 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, if (ret == 0) { /* encrypt, normal */ - ret = wc_PKCS7_EncryptContent(algID, (byte*)kek, kekSz, (byte*)iv, - ivSz, NULL, 0, NULL, 0, out, outLen, out, - pkcs7->devId, pkcs7->heap); + ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, kekSz, + (byte*)iv, ivSz, NULL, 0, NULL, 0, out, + outLen, out); } if (ret == 0) { /* encrypt again, using last ciphertext block as IV */ lastBlock = out + (((outLen / blockSz) - 1) * blockSz); - ret = wc_PKCS7_EncryptContent(algID, (byte*)kek, kekSz, lastBlock, - blockSz, NULL, 0, NULL, 0, out, - outLen, out, pkcs7->devId, pkcs7->heap); + ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, kekSz, + lastBlock, blockSz, NULL, 0, NULL, 0, out, + outLen, out); } if (ret == 0) { @@ -8953,8 +9527,8 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) WC_RNG rng; int blockSz, blockKeySz; - byte* plain; - byte* encryptedContent; + byte* plain = NULL; + byte* encryptedContent = NULL; Pkcs7EncodedRecip* tmpRecip = NULL; int recipSz, recipSetSz; @@ -8968,12 +9542,27 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) byte tmpIv[MAX_CONTENT_IV_SIZE]; byte ivOctetString[MAX_OCTET_STR_SZ]; byte encContentOctet[MAX_OCTET_STR_SZ]; +#ifdef ASN_BER_TO_DER + word32 streamSz = 0; +#endif - if (pkcs7 == NULL || pkcs7->content == NULL || pkcs7->contentSz == 0) + if (pkcs7 == NULL + #ifndef ASN_BER_TO_DER + || pkcs7->content == NULL + #endif + || pkcs7->contentSz == 0) { return BAD_FUNC_ARG; + } +#ifndef ASN_BER_TO_DER if (output == NULL || outputSz == 0) return BAD_FUNC_ARG; +#else + /* if both output and callback are not set then error out */ + if ((output == NULL || outputSz == 0) && (pkcs7->streamOutCb == NULL)) { + return BAD_FUNC_ARG; + } +#endif blockKeySz = wc_PKCS7_GetOIDKeySize(pkcs7->encryptOID); if (blockKeySz < 0) @@ -9082,26 +9671,37 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) encryptedOutSz = pkcs7->contentSz + padSz; - plain = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (plain == NULL) { - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - return MEMORY_E; - } +#ifdef ASN_BER_TO_DER + if (pkcs7->getContentCb == NULL) +#endif + { + plain = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + if (plain == NULL) { + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return MEMORY_E; + } + + ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, + encryptedOutSz, blockSz); + if (ret < 0) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return ret; + } - ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, - encryptedOutSz, blockSz); - if (ret < 0) { - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - return ret; } - encryptedContent = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); - if (encryptedContent == NULL) { - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - return MEMORY_E; +#ifdef ASN_BER_TO_DER + if (pkcs7->streamOutCb == NULL) +#endif + { + encryptedContent = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (encryptedContent == NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return MEMORY_E; + } } /* put together IV OCTET STRING */ @@ -9119,19 +9719,6 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) return BAD_FUNC_ARG; } - /* encrypt content */ - ret = wc_PKCS7_EncryptContent(pkcs7->encryptOID, pkcs7->cek, - pkcs7->cekSz, tmpIv, blockSz, NULL, 0, NULL, 0, plain, - encryptedOutSz, encryptedContent, - pkcs7->devId, pkcs7->heap); - - if (ret != 0) { - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - return ret; - } - encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0, encryptedOutSz, encContentOctet, pkcs7->encodeStream); encContentSeqSz = SetSequenceEx(contentTypeSz + contentEncAlgoSz + @@ -9147,7 +9734,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* EnvelopedData */ #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { - word32 streamSz = 0, tmpIdx = 0; + word32 tmpIdx = 0; /* account for ending of encContentOctet */ totalSz += ASN_INDEF_END_SZ; @@ -9158,6 +9745,18 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* account for asn1 syntax around octet strings */ StreamOctetString(NULL, encryptedOutSz, NULL, &streamSz, &tmpIdx); totalSz += (streamSz - encryptedOutSz); + + /* resize encrytped content buffer */ + if (encryptedContent != NULL) { + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encryptedContent = (byte*)XMALLOC(streamSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (encryptedContent == NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return MEMORY_E; + } + } } #endif envDataSeqSz = SetSequenceEx(totalSz, envDataSeq, pkcs7->encodeStream); @@ -9190,7 +9789,11 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) #endif } - if (totalSz > (int)outputSz) { + if ((totalSz > (int)outputSz) + #ifdef ASN_BER_TO_DER + && (pkcs7->streamOutCb == NULL) + #endif + ) { WOLFSSL_MSG("Pkcs7_encrypt output buffer too small"); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -9198,75 +9801,121 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) return BUFFER_E; } + /* begin writing out PKCS7 bundle */ if (pkcs7->contentOID != FIRMWARE_PKG_DATA) { - XMEMCPY(output + idx, contentInfoSeq, contentInfoSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + contentInfoSeq, contentInfoSeqSz); idx += contentInfoSeqSz; - XMEMCPY(output + idx, outerContentType, outerContentTypeSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + outerContentType, outerContentTypeSz); idx += outerContentTypeSz; - XMEMCPY(output + idx, outerContent, outerContentSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + outerContent, outerContentSz); idx += outerContentSz; } - XMEMCPY(output + idx, envDataSeq, envDataSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + envDataSeq, envDataSeqSz); idx += envDataSeqSz; - XMEMCPY(output + idx, ver, verSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + ver, verSz); idx += verSz; - XMEMCPY(output + idx, recipSet, recipSetSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + recipSet, recipSetSz); idx += recipSetSz; /* copy in recipients from list */ tmpRecip = pkcs7->recipList; while (tmpRecip != NULL) { - XMEMCPY(output + idx, tmpRecip->recip, tmpRecip->recipSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + tmpRecip->recip, tmpRecip->recipSz); idx += tmpRecip->recipSz; tmpRecip = tmpRecip->next; } wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - XMEMCPY(output + idx, encContentSeq, encContentSeqSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + encContentSeq, encContentSeqSz); idx += encContentSeqSz; - XMEMCPY(output + idx, contentType, contentTypeSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + contentType, contentTypeSz); idx += contentTypeSz; - XMEMCPY(output + idx, contentEncAlgo, contentEncAlgoSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + contentEncAlgo, contentEncAlgoSz); idx += contentEncAlgoSz; - XMEMCPY(output + idx, ivOctetString, ivOctetStringSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + ivOctetString, ivOctetStringSz); idx += ivOctetStringSz; - XMEMCPY(output + idx, tmpIv, blockSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + tmpIv, blockSz); idx += blockSz; - XMEMCPY(output + idx, encContentOctet, encContentOctetSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + encContentOctet, encContentOctetSz); idx += encContentOctetSz; + /* encrypt content */ + ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, pkcs7->cek, + pkcs7->cekSz, tmpIv, blockSz, NULL, 0, NULL, 0, plain, + encryptedOutSz, encryptedContent); + if (ret != 0) { + if (encryptedContent != NULL) { + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + } + + if (plain != NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + } + + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return ret; + } + #ifdef ASN_BER_TO_DER /* stream the content (octet string with multiple octet elements) */ if (pkcs7->encodeStream) { - if (StreamOctetString(encryptedContent, encryptedOutSz, output, - &outputSz, (word32*)&idx) != 0) { - return BUFFER_E; + byte indefEnd[ASN_INDEF_END_SZ * 5]; + word32 localIdx = 0; + + /* advance index past encrypted content */ + if (!pkcs7->streamOutCb) { + wc_PKCS7_WriteOut(pkcs7, (output)? output + idx : NULL, + encryptedContent, streamSz); } + idx += streamSz; /* end of encrypted content */ - idx += SetIndefEnd(output + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of encrypted content info */ - idx += SetIndefEnd(output + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of Enveloped Data seq */ - idx += SetIndefEnd(output + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of outer content set */ - idx += SetIndefEnd(output + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); /* end of outer content info seq */ - idx += SetIndefEnd(output + idx); + localIdx += SetIndefEnd(indefEnd + localIdx); + + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + indefEnd, localIdx); + idx += localIdx; } else #endif { - XMEMCPY(output + idx, encryptedContent, encryptedOutSz); + wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, + encryptedContent, encryptedOutSz); idx += encryptedOutSz; } - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + if (plain != NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + } + + if (encryptedContent != NULL) { + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + } return idx; } @@ -12198,10 +12847,9 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, } /* encrypt content */ - ret = wc_PKCS7_EncryptContent(pkcs7->encryptOID, pkcs7->cek, + ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, pkcs7->cek, pkcs7->cekSz, nonce, nonceSz, aadBuffer, aadBufferSz, authTag, - sizeof(authTag), plain, encryptedOutSz, encryptedContent, - pkcs7->devId, pkcs7->heap); + sizeof(authTag), plain, encryptedOutSz, encryptedContent); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); plain = NULL; @@ -13138,10 +13786,9 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) return ret; } - ret = wc_PKCS7_EncryptContent(pkcs7->encryptOID, pkcs7->encryptionKey, - pkcs7->encryptionKeySz, tmpIv, blockSz, NULL, 0, NULL, 0, - plain, encryptedOutSz, encryptedContent, - pkcs7->devId, pkcs7->heap); + ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, + pkcs7->encryptionKey, pkcs7->encryptionKeySz, tmpIv, blockSz, NULL, + 0, NULL, 0, plain, encryptedOutSz, encryptedContent); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13707,16 +14354,24 @@ int wc_PKCS7_SetDecodeEncryptedCtx(PKCS7* pkcs7, void* ctx) /* set stream mode for encoding and signing * returns 0 on success */ -int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag) +int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, + CallbackGetContent getContentCb, + CallbackStreamOut streamOutCb, void* ctx) { if (pkcs7 == NULL) { return BAD_FUNC_ARG; } #ifdef ASN_BER_TO_DER pkcs7->encodeStream = flag; + pkcs7->getContentCb = getContentCb; + pkcs7->streamOutCb = streamOutCb; + pkcs7->streamCtx = ctx; return 0; #else (void)flag; + (void)getContentCb; + (void)streamOutCb; + (void)ctx; return NOT_COMPILED_IN; #endif } diff --git a/src/wolfcrypt/src/sha256.c b/src/wolfcrypt/src/sha256.c index 142a3fb..0025e85 100644 --- a/src/wolfcrypt/src/sha256.c +++ b/src/wolfcrypt/src/sha256.c @@ -169,6 +169,38 @@ on the specific device platform. #endif +#if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) + #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP8684) || \ + defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32C6) \ + ) && \ + defined(WOLFSSL_ESP32_CRYPT) && \ + !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ + !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) + /* For Espressif RISC-V Targets, we *may* need to reverse bytes + * depending on if HW is active or not. */ + #define SHA256_REV_BYTES(ctx) \ + (esp_sha_need_byte_reversal(ctx)) + #endif +#endif +#ifndef SHA256_REV_BYTES + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) + #define SHA256_REV_BYTES(ctx) 1 + #else + #define SHA256_REV_BYTES(ctx) 0 + #endif +#endif +#if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) && \ + defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #define SHA256_UPDATE_REV_BYTES(ctx) \ + (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) +#else + #define SHA256_UPDATE_REV_BYTES(ctx) SHA256_REV_BYTES(ctx) +#endif + + #if !defined(WOLFSSL_PIC32MZ_HASH) && !defined(STM32_HASH_SHA2) && \ (!defined(WOLFSSL_IMX6_CAAM) || defined(NO_IMX6_CAAM_HASH) || \ defined(WOLFSSL_QNX_CAAM)) && \ @@ -188,11 +220,6 @@ on the specific device platform. static int InitSha256(wc_Sha256* sha256) { - int ret = 0; - - if (sha256 == NULL) - return BAD_FUNC_ARG; - XMEMSET(sha256->digest, 0, sizeof(sha256->digest)); sha256->digest[0] = 0x6A09E667L; sha256->digest[1] = 0xBB67AE85L; @@ -227,7 +254,7 @@ static int InitSha256(wc_Sha256* sha256) sha256->hSession = NULL; #endif - return ret; + return 0; } #endif @@ -736,10 +763,6 @@ static int InitSha256(wc_Sha256* sha256) { int ret = 0; /* zero = success */ - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - /* We may or may not need initial digest for HW. * Always needed for SW-only. */ sha256->digest[0] = 0x6A09E667L; @@ -1049,21 +1072,13 @@ static int InitSha256(wc_Sha256* sha256) } /* do block size increments/updates */ - static WC_INLINE int Sha256Update(wc_Sha256* sha256, const byte* data, word32 len) + static WC_INLINE int Sha256Update(wc_Sha256* sha256, const byte* data, + word32 len) { int ret = 0; word32 blocksLen; byte* local; - if (sha256 == NULL || (data == NULL && len > 0)) { - return BAD_FUNC_ARG; - } - - if (data == NULL && len == 0) { - /* valid, but do nothing */ - return 0; - } - /* check that internal buffLen is valid */ if (sha256->buffLen >= WC_SHA256_BLOCK_SIZE) { return BUFFER_E; @@ -1092,34 +1107,13 @@ static int InitSha256(wc_Sha256* sha256) } #endif - - #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) - #if defined(WOLFSSL_X86_64_BUILD) && \ - defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) - #endif - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - { - ByteReverseWords(sha256->buffer, sha256->buffer, - WC_SHA256_BLOCK_SIZE); - } - #endif + if (SHA256_UPDATE_REV_BYTES(&sha256->ctx)) { + ByteReverseWords(sha256->buffer, sha256->buffer, + WC_SHA256_BLOCK_SIZE); + } #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - if (sha256->ctx.mode == ESP32_SHA_SW) { #if defined(WOLFSSL_DEBUG_MUTEX) { @@ -1146,7 +1140,6 @@ static int InitSha256(wc_Sha256* sha256) /* Always SW */ ret = XTRANSFORM(sha256, (const byte*)local); #endif - if (ret == 0) sha256->buffLen = 0; else @@ -1161,12 +1154,13 @@ static int InitSha256(wc_Sha256* sha256) if (Transform_Sha256_Len_p != NULL) #endif { - /* get number of blocks */ - /* 64-1 = 0x3F (~ Inverted = 0xFFFFFFC0) */ - /* len (masked by 0xFFFFFFC0) returns block aligned length */ - blocksLen = len & ~((word32)WC_SHA256_BLOCK_SIZE-1); - if (blocksLen > 0) { - /* Byte reversal and alignment handled in function if required */ + if (len >= WC_SHA256_BLOCK_SIZE) { + /* get number of blocks */ + /* 64-1 = 0x3F (~ Inverted = 0xFFFFFFC0) */ + /* len (masked by 0xFFFFFFC0) returns block aligned length */ + blocksLen = len & ~((word32)WC_SHA256_BLOCK_SIZE-1); + /* Byte reversal and alignment handled in function if required + */ XTRANSFORM_LEN(sha256, data, blocksLen); data += blocksLen; len -= blocksLen; @@ -1209,28 +1203,9 @@ static int InitSha256(wc_Sha256* sha256) } #endif - #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - #if defined(WOLFSSL_X86_64_BUILD) && \ - defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) - #endif - { - ByteReverseWords(local32, local32, WC_SHA256_BLOCK_SIZE); - } - #endif + if (SHA256_UPDATE_REV_BYTES(&sha256->ctx)) { + ByteReverseWords(local32, local32, WC_SHA256_BLOCK_SIZE); + } #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) @@ -1267,14 +1242,16 @@ static int InitSha256(wc_Sha256* sha256) #else int wc_Sha256Update(wc_Sha256* sha256, const byte* data, word32 len) { - if (sha256 == NULL || (data == NULL && len > 0)) { + if (sha256 == NULL) { return BAD_FUNC_ARG; } - if (data == NULL && len == 0) { /* valid, but do nothing */ return 0; } + if (data == NULL) { + return BAD_FUNC_ARG; + } #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND @@ -1301,14 +1278,9 @@ static int InitSha256(wc_Sha256* sha256) static WC_INLINE int Sha256Final(wc_Sha256* sha256) { - int ret; byte* local; - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - /* we'll add a 0x80 byte at the end, ** so make sure we have appropriate buffer length. */ if (sha256->buffLen > WC_SHA256_BLOCK_SIZE - 1) { @@ -1326,8 +1298,6 @@ static int InitSha256(wc_Sha256* sha256) WC_SHA256_BLOCK_SIZE - sha256->buffLen); } - sha256->buffLen += WC_SHA256_BLOCK_SIZE - sha256->buffLen; - #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) if (sha256->ctx.mode == ESP32_SHA_INIT) { @@ -1335,28 +1305,10 @@ static int InitSha256(wc_Sha256* sha256) } #endif - #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) - #endif - { - ByteReverseWords(sha256->buffer, sha256->buffer, - WC_SHA256_BLOCK_SIZE); - } - #endif + if (SHA256_UPDATE_REV_BYTES(&sha256->ctx)) { + ByteReverseWords(sha256->buffer, sha256->buffer, + WC_SHA256_BLOCK_SIZE); + } #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) @@ -1393,28 +1345,10 @@ static int InitSha256(wc_Sha256* sha256) #endif /* store lengths */ - #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) - #endif - { + if (SHA256_UPDATE_REV_BYTES(&sha256->ctx)) { ByteReverseWords(sha256->buffer, sha256->buffer, - WC_SHA256_BLOCK_SIZE); + WC_SHA256_PAD_SIZE); } - #endif /* ! 64-bit length ordering dependent on digest endian type ! */ XMEMCPY(&local[WC_SHA256_PAD_SIZE], &sha256->hiLen, sizeof(word32)); XMEMCPY(&local[WC_SHA256_PAD_SIZE + sizeof(word32)], &sha256->loLen, @@ -1496,23 +1430,10 @@ static int InitSha256(wc_Sha256* sha256) } #ifdef LITTLE_ENDIAN_ORDER - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - { - ByteReverseWords((word32*)digest, - (word32*)sha256->digest, - WC_SHA256_DIGEST_SIZE); - } + if (SHA256_REV_BYTES(&sha256->ctx)) { + ByteReverseWords((word32*)digest, (word32*)sha256->digest, + WC_SHA256_DIGEST_SIZE); + } XMEMCPY(hash, digest, WC_SHA256_DIGEST_SIZE); #else XMEMCPY(hash, sha256->digest, WC_SHA256_DIGEST_SIZE); @@ -1556,22 +1477,10 @@ static int InitSha256(wc_Sha256* sha256) } #if defined(LITTLE_ENDIAN_ORDER) - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) - /* For Espressif RISC-V Targets, we *may* need to reverse bytes - * depending on if HW is active or not. */ - if (esp_sha_need_byte_reversal(&sha256->ctx)) - #endif - { - ByteReverseWords(sha256->digest, sha256->digest, - WC_SHA256_DIGEST_SIZE); - } + if (SHA256_REV_BYTES(&sha256->ctx)) { + ByteReverseWords(sha256->digest, sha256->digest, + WC_SHA256_DIGEST_SIZE); + } #endif XMEMCPY(hash, sha256->digest, WC_SHA256_DIGEST_SIZE); @@ -1583,18 +1492,115 @@ static int InitSha256(wc_Sha256* sha256) /* @param sha a pointer to wc_Sha256 structure */ /* @param data data to be applied SHA256 transformation */ /* @return 0 on successful, otherwise non-zero on failure */ - int wc_Sha256Transform(wc_Sha256* sha, const unsigned char* data) + int wc_Sha256Transform(wc_Sha256* sha256, const unsigned char* data) { - if (sha == NULL || data == NULL) { + if (sha256 == NULL || data == NULL) { return BAD_FUNC_ARG; } - return (Transform_Sha256(sha, data)); + return Transform_Sha256(sha256, data); } - #endif -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || HAVE_CURL */ + +#if defined(WOLFSSL_HAVE_LMS) && !defined(WOLFSSL_LMS_FULL_HASH) + /* One block will be used from data. + * hash must be big enough to hold all of digest output. + */ + int wc_Sha256HashBlock(wc_Sha256* sha256, const unsigned char* data, + unsigned char* hash) + { + int ret; + + if ((sha256 == NULL) || (data == NULL)) { + return BAD_FUNC_ARG; + } + + if (SHA256_UPDATE_REV_BYTES(&sha256->ctx)) { + ByteReverseWords(sha256->buffer, (word32*)data, + WC_SHA256_BLOCK_SIZE); + data = (unsigned char*)sha256->buffer; + } + ret = XTRANSFORM(sha256, data); + + if ((ret == 0) && (hash != NULL)) { + if (!SHA256_REV_BYTES(&sha256->ctx)) { + XMEMCPY(hash, sha256->digest, WC_SHA256_DIGEST_SIZE); + } + else { + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) + __asm__ __volatile__ ( + "mov 0x00(%[d]), %%esi\n\t" + "movbe %%esi, 0x00(%[h])\n\t" + "mov 0x04(%[d]), %%esi\n\t" + "movbe %%esi, 0x04(%[h])\n\t" + "mov 0x08(%[d]), %%esi\n\t" + "movbe %%esi, 0x08(%[h])\n\t" + "mov 0x0c(%[d]), %%esi\n\t" + "movbe %%esi, 0x0c(%[h])\n\t" + "mov 0x10(%[d]), %%esi\n\t" + "movbe %%esi, 0x10(%[h])\n\t" + "mov 0x14(%[d]), %%esi\n\t" + "movbe %%esi, 0x14(%[h])\n\t" + "mov 0x18(%[d]), %%esi\n\t" + "movbe %%esi, 0x18(%[h])\n\t" + "mov 0x1c(%[d]), %%esi\n\t" + "movbe %%esi, 0x1c(%[h])\n\t" + : + : [d] "r" (sha256->digest), [h] "r" (hash) + : "memory", "esi" + ); + #else + word32* hash32 = (word32*)hash; + word32* digest = (word32*)sha256->digest; + #if WOLFSSL_GENERAL_ALIGNMENT < 4 + ALIGN16 word32 buf[WC_SHA256_DIGEST_SIZE / sizeof(word32)]; + + if (((size_t)digest & 0x3) != 0) { + if (((size_t)hash32 & 0x3) != 0) { + XMEMCPY(buf, digest, WC_SHA256_DIGEST_SIZE); + hash32 = buf; + digest = buf; + } + else { + XMEMCPY(hash, digest, WC_SHA256_DIGEST_SIZE); + digest = hash32; + } + } + else if (((size_t)hash32 & 0x3) != 0) { + hash32 = digest; + } + #endif + hash32[0] = ByteReverseWord32(digest[0]); + hash32[1] = ByteReverseWord32(digest[1]); + hash32[2] = ByteReverseWord32(digest[2]); + hash32[3] = ByteReverseWord32(digest[3]); + hash32[4] = ByteReverseWord32(digest[4]); + hash32[5] = ByteReverseWord32(digest[5]); + hash32[6] = ByteReverseWord32(digest[6]); + hash32[7] = ByteReverseWord32(digest[7]); + #if WOLFSSL_GENERAL_ALIGNMENT < 4 + if (hash != (byte*)hash32) { + XMEMCPY(hash, hash32, WC_SHA256_DIGEST_SIZE); + } + #endif + #endif /* WOLFSSL_X86_64_BUILD && USE_INTEL_SPEEDUP */ + } + sha256->digest[0] = 0x6A09E667L; + sha256->digest[1] = 0xBB67AE85L; + sha256->digest[2] = 0x3C6EF372L; + sha256->digest[3] = 0xA54FF53AL; + sha256->digest[4] = 0x510E527FL; + sha256->digest[5] = 0x9B05688CL; + sha256->digest[6] = 0x1F83D9ABL; + sha256->digest[7] = 0x5BE0CD19L; + } + return ret; + } +#endif /* WOLFSSL_HAVE_LMS && !WOLFSSL_LMS_FULL_HASH */ #endif /* !WOLFSSL_KCAPI_HASH */ +#endif /* XTRANSFORM */ + #ifdef WOLFSSL_SHA224 @@ -1713,10 +1719,6 @@ static int InitSha256(wc_Sha256* sha256) { int ret = 0; - if (sha224 == NULL) { - return BAD_FUNC_ARG; - } - sha224->digest[0] = 0xc1059ed8; sha224->digest[1] = 0x367cd507; sha224->digest[2] = 0x3070dd17; @@ -1817,7 +1819,14 @@ static int InitSha256(wc_Sha256* sha256) { int ret; - if (sha224 == NULL || (data == NULL && len > 0)) { + if (sha224 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { return BAD_FUNC_ARG; } @@ -1869,18 +1878,7 @@ static int InitSha256(wc_Sha256* sha256) return ret; #if defined(LITTLE_ENDIAN_ORDER) - #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) \ - ) && \ - defined(WOLFSSL_ESP32_CRYPT) && \ - (!defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) || \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA224) \ - ) - if (esp_sha_need_byte_reversal(&sha224->ctx)) - #endif - { + if (SHA256_REV_BYTES(&sha224->ctx)) { ByteReverseWords(sha224->digest, sha224->digest, WC_SHA224_DIGEST_SIZE); diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index ec9a0a9..91bf1e5 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -87,7 +87,7 @@ #endif -#if defined(USE_INTEL_SPEEDUP) +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) #if defined(__GNUC__) && ((__GNUC__ < 4) || \ (__GNUC__ == 4 && __GNUC_MINOR__ <= 8)) #undef NO_AVX2_SUPPORT @@ -318,7 +318,7 @@ static int InitSha512_256(wc_Sha512* sha512) #endif /* WOLFSSL_SHA512 */ /* Hardware Acceleration */ -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) /***** @@ -516,7 +516,7 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, if (ret != 0) return ret; -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) Sha512_SetTransform(); #endif @@ -757,7 +757,7 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le if (sha512->buffLen == WC_SHA512_BLOCK_SIZE) { #if defined(LITTLE_ENDIAN_ORDER) - #if defined(USE_INTEL_SPEEDUP) && \ + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) #endif @@ -792,7 +792,7 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le } } -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (Transform_Sha512_Len_p != NULL) { word32 blocksLen = len & ~((word32)WC_SHA512_BLOCK_SIZE-1); @@ -807,8 +807,9 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le } else #endif -#if !defined(LITTLE_ENDIAN_ORDER) || (defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))) +#if !defined(LITTLE_ENDIAN_ORDER) || (defined(WOLFSSL_X86_64_BUILD) && \ + defined(USE_INTEL_SPEEDUP) && (defined(HAVE_INTEL_AVX1) || \ + defined(HAVE_INTEL_AVX2))) { while (len >= WC_SHA512_BLOCK_SIZE) { XMEMCPY(local, data, WC_SHA512_BLOCK_SIZE); @@ -816,7 +817,7 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le data += WC_SHA512_BLOCK_SIZE; len -= WC_SHA512_BLOCK_SIZE; - #if defined(USE_INTEL_SPEEDUP) && \ + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) { @@ -946,7 +947,7 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) sha512->buffLen += WC_SHA512_BLOCK_SIZE - sha512->buffLen; #if defined(LITTLE_ENDIAN_ORDER) - #if defined(USE_INTEL_SPEEDUP) && \ + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) #endif @@ -992,7 +993,7 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) /* store lengths */ #if defined(LITTLE_ENDIAN_ORDER) - #if defined(USE_INTEL_SPEEDUP) && \ + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) #endif @@ -1011,7 +1012,7 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 1] = sha512->loLen; #endif -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags)) ByteReverseWords64(&(sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2]), @@ -1216,13 +1217,13 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) return MEMORY_E; #endif -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) Sha512_SetTransform(); #endif #if defined(LITTLE_ENDIAN_ORDER) -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) #endif @@ -1459,7 +1460,7 @@ int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) return ret; } -#if defined(USE_INTEL_SPEEDUP) && \ +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) Sha512_SetTransform(); #endif diff --git a/src/wolfcrypt/src/siphash.c b/src/wolfcrypt/src/siphash.c index 0fc2721..173b914 100644 --- a/src/wolfcrypt/src/siphash.c +++ b/src/wolfcrypt/src/siphash.c @@ -468,7 +468,7 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, : [in] "+r" (in), [inSz] "+r" (inSz), [k0] "+r" (k0), [k1] "+r" (k1), [v0] "+r" (v0), [v1] "+r" (v1), [v2] "+r" (v2), [v3] "+r" (v3) - : [key] "r" (key), [out] "r" (out) , [outSz] "r" (outSz) + : [out] "r" (out) , [outSz] "r" (outSz) : "memory" ); @@ -515,16 +515,16 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, #endif "xorq %[k1], %[v0]\n\t" - "cmp $8, %[outSz]\n\t" - "je L_siphash_8_end\n\t" - : [in] "+r" (in), [inSz] "+r" (inSz), [k0] "+r" (k0), [k1] "+r" (k1), [v0] "+r" (v0), [v1] "+r" (v1), [v2] "+r" (v2), [v3] "+r" (v3) - : [key] "r" (key), [out] "r" (out) , [outSz] "r" (outSz) + : [out] "r" (out) , [outSz] "r" (outSz) : "memory" ); __asm__ __volatile__ ( + "cmp $8, %[outSz]\n\t" + "je L_siphash_8_end\n\t" + "xor $0xee, %b[v2]\n\t" #if WOLFSSL_SIPHASH_DROUNDS == 2 SIPHASH_ROUND(%[v0], %[v1], %[v2], %[v3]) @@ -575,7 +575,7 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, : [in] "+r" (in), [inSz] "+r" (inSz), [k0] "+r" (k0), [k1] "+r" (k1), [v0] "+r" (v0), [v1] "+r" (v1), [v2] "+r" (v2), [v3] "+r" (v3) - : [key] "r" (key), [out] "r" (out) , [outSz] "r" (outSz) + : [out] "r" (out) , [outSz] "r" (outSz) : "memory" ); diff --git a/src/wolfcrypt/src/sp_int.c b/src/wolfcrypt/src/sp_int.c index d336fcc..83a1306 100644 --- a/src/wolfcrypt/src/sp_int.c +++ b/src/wolfcrypt/src/sp_int.c @@ -862,7 +862,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "bsr %[a], %[i] \n\t" \ : [i] "=r" (vi) \ : [a] "r" (va) \ - : "cC" \ + : "cc" \ ) #ifndef WOLFSSL_SP_DIV_WORD_HALF diff --git a/src/wolfcrypt/src/tfm.c b/src/wolfcrypt/src/tfm.c index ae69f53..07cd1fe 100644 --- a/src/wolfcrypt/src/tfm.c +++ b/src/wolfcrypt/src/tfm.c @@ -1104,9 +1104,9 @@ void fp_mod_2d(fp_int *a, int b, fp_int *c) bmax = ((unsigned int)b + DIGIT_BIT - 1) / DIGIT_BIT; - /* If a is negative and bmax is larger than FP_SIZE, then the + /* If a is negative and bmax is greater than or equal to FP_SIZE, then the * result can't fit within c. Just return. */ - if (c->sign == FP_NEG && bmax > FP_SIZE) { + if (c->sign == FP_NEG && bmax >= FP_SIZE) { return; } @@ -6092,14 +6092,14 @@ int mp_montgomery_setup(fp_int *a, fp_digit *rho) #endif /* HAVE_ECC || (!NO_RSA && WC_RSA_BLINDING) */ -#ifdef HAVE_ECC - /* fast math conversion */ int mp_sqr(fp_int *A, fp_int *B) { return fp_sqr(A, B); } +#ifdef HAVE_ECC + /* fast math conversion */ int mp_div_2(fp_int * a, fp_int * b) { diff --git a/src/wolfcrypt/src/wc_kyber.c b/src/wolfcrypt/src/wc_kyber.c index 8d516c8..b0b358f 100644 --- a/src/wolfcrypt/src/wc_kyber.c +++ b/src/wolfcrypt/src/wc_kyber.c @@ -1,6 +1,6 @@ /* wc_kyber.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,8 +19,1249 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +/* Implementation based on NIST 3rd Round submission package. + * See link at: + * https://csrc.nist.gov/Projects/post-quantum-cryptography/post-quantum-cryptography-standardization/round-3-submissions + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + #include +#include +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#ifdef WOLFSSL_WC_KYBER + +/******************************************************************************/ + +/* Use SHA3-256 to generate 32-bytes of hash. */ +#define KYBER_HASH_H wc_Sha3_256Hash +/* Use SHA3-512 to generate 64-bytes of hash. */ +#define KYBER_HASH_G wc_Sha3_512Hash +/* Use SHAKE-256 as a key derivation function (KDF). */ +#ifdef USE_INTEL_SPEEDUP +#define KYBER_KDF kyber_kdf +#else +#define KYBER_KDF wc_Shake256Hash +#endif + +/******************************************************************************/ + +/** + * Initialize the Kyber key. + * + * @param [in] type Type of key: KYBER512, KYBER768, KYBER1024. + * @param [out] key Kyber key object to initialize. + * @param [in] heap Dynamic memory hint. + * @param [in] devId Device Id. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or type is unrecognized. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_Init(int type, KyberKey* key, void* heap, int devId) +{ + int ret = 0; + + /* Validate key. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Validate type. */ + switch (type) { + case KYBER512: + #ifndef WOLFSSL_KYBER512 + /* Code not compiled in for Kyber-512. */ + ret = NOT_COMPILED_IN; + #endif + break; + case KYBER768: + #ifndef WOLFSSL_KYBER768 + /* Code not compiled in for Kyber-768. */ + ret = NOT_COMPILED_IN; + #endif + break; + case KYBER1024: + #ifndef WOLFSSL_KYBER1024 + /* Code not compiled in for Kyber-1024. */ + ret = NOT_COMPILED_IN; + #endif + break; + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } + if (ret == 0) { + /* Zero out all data. */ + XMEMSET(key, 0, sizeof(*key)); + + /* Keep type for parameters. */ + key->type = type; + /* Cache heap pointer. */ + key->heap = heap; + #ifdef WOLF_CRYPTO_CB + /* Cache device id - not used in for this algorithm yet. */ + key->devId = devId; + #endif + + /* Initialize the PRF algorithm object. */ + ret = kyber_prf_new(&key->prf, heap, devId); + } + if (ret == 0) { + kyber_init(); + } + + (void)devId; + + return ret; +} + +/** + * Free the Kyber key object. + * + * @param [in, out] key Kyber key object to dispose of. + */ +void wc_KyberKey_Free(KyberKey* key) +{ + if (key != NULL) { + /* Dispose of PRF object. */ + kyber_prf_free(&key->prf); + /* Ensure all private data is zeroed. */ + ForceZero(key, sizeof(*key)); + } +} + +/******************************************************************************/ + +/** + * Make a Kyber key object using a random number generator. + * + * @param [in, out] key Kyber key object. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rng is NULL. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_KyberKey_MakeKey(KyberKey* key, WC_RNG* rng) +{ + int ret = 0; + unsigned char rand[KYBER_MAKEKEY_RAND_SZ]; + + /* Validate parameters. */ + if ((key == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Generate random to with PRFs. */ + ret = wc_RNG_GenerateBlock(rng, rand, KYBER_SYM_SZ); + } + if (ret == 0) { + /* Generate random to with PRFs. */ + ret = wc_RNG_GenerateBlock(rng, rand + KYBER_SYM_SZ, KYBER_SYM_SZ); + } + if (ret == 0) { + /* Make a key pair from the random. */ + ret = wc_KyberKey_MakeKeyWithRandom(key, rand, sizeof(rand)); + } + + /* Ensure seeds are zeroized. */ + ForceZero((void*)rand, (word32)sizeof(rand)); + + return ret; +} + +/** + * Make a Kyber key object using random data. + * + * @param [in, out] key Kyber key ovject. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rand is NULL. + * @return BUFFER_E when length is not KYBER_MAKEKEY_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, + int len) +{ + byte buf[2 * KYBER_SYM_SZ + 1]; + byte* pubSeed = buf; + byte* noiseSeed = buf + KYBER_SYM_SZ; + sword16* a = NULL; + sword16* e; + int ret = 0; + int kp = 0; + + /* Validate parameters. */ + if ((key == NULL) || (rand == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (len != KYBER_MAKEKEY_RAND_SZ)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + kp = KYBER512_K; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + kp = KYBER768_K; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + kp = KYBER1024_K; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + if (ret == 0) { + /* Allocate dynamic memory for matrix and error vector. */ + a = (sword16*)XMALLOC((kp + 1) * kp * KYBER_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (a == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + /* Error vector allocated at end of a. */ + e = a + (kp * kp * KYBER_N); + + /* Expand 16 bytes of random to 32. */ + ret = KYBER_HASH_G(rand, KYBER_SYM_SZ, buf); + } + if (ret == 0) { + /* Cache the public seed for use in encapsulation and encoding public + * key. */ + XMEMCPY(key->pubSeed, pubSeed, KYBER_SYM_SZ); + /* Cache the z value for decapsulation and encoding private key. */ + XMEMCPY(key->z, rand + KYBER_SYM_SZ, sizeof(key->z)); + + /* Generate the matrix A. */ + ret = kyber_gen_matrix(&key->prf, a, kp, pubSeed, 0); + } + + if (ret == 0) { + /* Initialize PRF for use in noise generation. */ + kyber_prf_init(&key->prf); + /* Generate noise using PRF. */ + ret = kyber_get_noise(&key->prf, kp, key->priv, e, NULL, noiseSeed); + } + if (ret == 0) { + /* Generate key pair from random data. */ + kyber_keygen(key->priv, key->pub, e, a, kp); + + /* Private and public key are set/available. */ + key->flags |= KYBER_FLAG_PRIV_SET | KYBER_FLAG_PUB_SET; + } + + /* Free dynamic memory allocated in function. */ + XFREE(a, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} + +/******************************************************************************/ + +/** + * Get the size in bytes of cipher text for key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of cipher text in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the cipher text for the type of this key. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Size of a shared secret in bytes. Always KYBER_SS_SZ. + * + * @param [in] key Kyber key object. Not used. + * @param [out] Size of the shared secret created with a Kyber key. + * @return 0 on success. + * @return 0 to indicate success. + */ +int wc_KyberKey_SharedSecretSize(KyberKey* key, word32* len) +{ + (void)key; + + *len = KYBER_SS_SZ; + + return 0; +} + +/* Encapsulate data and derive secret. + * + * @param [in] key Kyber key object. + * @param [in] msg Message to encapsulate. + * @param [in] coins Coins (seed) to feed to PRF. + * @param [in] ct Calculated cipher text. + * @return 0 on success. + * @return NOT_COMPILED_IN when key type is not supported. + */ +static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, + unsigned char* ct) +{ + int ret = 0; + sword16* sp; + sword16* ep; + sword16* k; + sword16* epp; + unsigned int kp; + unsigned int compVecSz; +#ifndef USE_INTEL_SPEEDUP + sword16* at = NULL; +#else + sword16 at[((KYBER_MAX_K + 3) * KYBER_MAX_K + 3) * KYBER_N]; +#endif + + /* Establish parameters based on key type. */ + switch (key->type) { +#ifdef WOLFSSL_KYBER512 + case KYBER512: + kp = KYBER512_K; + compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER768 + case KYBER768: + kp = KYBER768_K; + compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER1024 + case KYBER1024: + kp = KYBER1024_K; + compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + +#ifndef USE_INTEL_SPEEDUP + if (ret == 0) { + /* Allocate dynamic memory for all matrices, vectors and polynomials. */ + at = (sword16*)XMALLOC(((kp + 3) * kp + 3) * KYBER_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (at == NULL) { + ret = MEMORY_E; + } + } +#endif + + if (ret == 0) { + /* Assign allocated dynamic memory to pointers. + * at (m) | k (p) | sp (v) | sp (v) | epp (v) | bp (p) | v (v) */ + k = at + KYBER_N * kp * kp; + sp = k + KYBER_N; + ep = sp + KYBER_N * kp; + epp = ep + KYBER_N * kp; + + /* Convert msg to a polynomial. */ + kyber_from_msg(k, msg); -#ifdef WOLFSSL_HAVE_KYBER - #error "Contact wolfSSL to get the implementation of this file" + /* Generate the transposed matrix. */ + ret = kyber_gen_matrix(&key->prf, at, kp, key->pubSeed, 1); + } + if (ret == 0) { + /* Initialize the PRF for use in the noise generation. */ + kyber_prf_init(&key->prf); + /* Generate noise using PRF. */ + ret = kyber_get_noise(&key->prf, kp, sp, ep, epp, coins); + } + if (ret == 0) { + sword16* bp; + sword16* v; + + /* Assign remaining allocated dynamic memory to pointers. + * at (m) | k (p) | sp (v) | sp (v) | epp (v) | bp (p) | v (v)*/ + bp = epp + KYBER_N; + v = bp + KYBER_N * kp; + + /* Perform encapsulation maths. */ + kyber_encapsulate(key->pub, bp, v, at, sp, ep, epp, k, kp); + + #ifdef WOLFSSL_KYBER512 + if (kp == KYBER512_K) { + kyber_vec_compress_10(ct, bp, kp); + kyber_compress_4(ct + compVecSz, v); + } + #endif + #ifdef WOLFSSL_KYBER768 + if (kp == KYBER768_K) { + kyber_vec_compress_10(ct, bp, kp); + kyber_compress_4(ct + compVecSz, v); + } + #endif + #ifdef WOLFSSL_KYBER1024 + if (kp == KYBER1024_K) { + kyber_vec_compress_11(ct, bp); + kyber_compress_5(ct + compVecSz, v); + } + #endif + } + +#ifndef USE_INTEL_SPEEDUP + /* Dispose of dynamic memory allocated in function. */ + XFREE(at, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif + + return ret; +} + +/** + * Encapsulate with random number generator and derive secret. + * + * @param [in] key Kyber key object. + * @param [out] ct Cipher text. + * @param [out] ss Shared secret generated. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ct, ss or RNG is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_KyberKey_Encapsulate(KyberKey* key, unsigned char* ct, unsigned char* ss, + WC_RNG* rng) +{ + int ret = 0; + unsigned char rand[KYBER_ENC_RAND_SZ]; + + /* Validate parameters. */ + if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Generate seed for use with PRFs. */ + ret = wc_RNG_GenerateBlock(rng, rand, sizeof(rand)); + } + if (ret == 0) { + /* Encapsulate with the random. */ + ret = wc_KyberKey_EncapsulateWithRandom(key, ct, ss, rand, + sizeof(rand)); + } + + return ret; +} + +/** + * Encapsulate with random data and derive secret. + * + * @param [out] ct Cipher text. + * @param [out] ss Shared secret generated. + * @param [in] rand Random data. + * @param [in] len Random data. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ct, ss or RNG is NULL. + * @return BUFFER_E when len is not KYBER_ENC_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, + unsigned char* ss, const unsigned char* rand, int len) +{ + byte msg[2 * KYBER_SYM_SZ]; + byte kr[2 * KYBER_SYM_SZ + 1]; + int ret = 0; + unsigned int ctSz; + + /* Validate parameters. */ + if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rand == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (len != KYBER_ENC_RAND_SZ)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + ctSz = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + ctSz = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + ctSz = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + /* If public hash (h) is not stored against key, calculate it. */ + if ((ret == 0) && ((key->flags & KYBER_FLAG_H_SET) == 0)) { + byte* pubKey = NULL; + word32 pubKeyLen; + + /* Determine how big an encoded public key will be. */ + ret = wc_KyberKey_PublicKeySize(key, &pubKeyLen); + if (ret == 0) { + /* Allocate dynamic memory for encoded public key. */ + pubKey = (byte*)XMALLOC(pubKeyLen, key->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (pubKey == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + /* Encode public key - h is hash of encoded public key. */ + ret = wc_KyberKey_EncodePublicKey(key, pubKey, pubKeyLen); + } + /* Dispose of encoded public key. */ + XFREE(pubKey, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + if ((ret == 0) && ((key->flags & KYBER_FLAG_H_SET) == 0)) { + /* Implementation issue if h not cached and flag set. */ + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Hash random to anonymize as seed data. */ + ret = KYBER_HASH_H(rand, KYBER_SYM_SZ, msg); + } + if (ret == 0) { + /* Copy the hash of the public key into msg. */ + XMEMCPY(msg + KYBER_SYM_SZ, key->h, KYBER_SYM_SZ); + + /* Hash message into seed buffer. */ + ret = KYBER_HASH_G(msg, 2 * KYBER_SYM_SZ, kr); + } + + if (ret == 0) { + /* Encapsulate the message using the key and the seed (coins). */ + ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, ct); + } + + if (ret == 0) { + /* Hash the cipher text after the seed. */ + ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); + } + if (ret == 0) { + /* Derive the secret from the seed and hash of cipher text. */ + ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); + } + + return ret; +} + +/******************************************************************************/ + +/* Decapsulate cipher text to the message using key. + * + * @param [in] Kyber key object. + * @param [out] Message than was encapsulated. + * @param [in] Cipher text. + * @return 0 on success. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, + unsigned char* msg, const unsigned char* ct) +{ + int ret = 0; + sword16* v; + sword16* mp; + unsigned int kp; + unsigned int compVecSz; +#ifndef USE_INTEL_SPEEDUP + sword16* bp = NULL; +#else + sword16 bp[(KYBER_MAX_K + 2) * KYBER_N]; +#endif + + /* Establish parameters based on key type. */ + switch (key->type) { +#ifdef WOLFSSL_KYBER512 + case KYBER512: + kp = KYBER512_K; + compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER768 + case KYBER768: + kp = KYBER768_K; + compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER1024 + case KYBER1024: + kp = KYBER1024_K; + compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + +#ifndef USE_INTEL_SPEEDUP + if (ret == 0) { + /* Allocate dynamic memory for a vector and two polynomials. */ + bp = (sword16*)XMALLOC((kp + 2) * KYBER_N * sizeof(sword16), key->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (bp == NULL) { + ret = MEMORY_E; + } + } +#endif + if (ret == 0) { + /* Assign allocated dynamic memory to pointers. + * bp (v) | v (p) | mp (p) */ + v = bp + kp * KYBER_N; + mp = v + KYBER_N; + + #ifdef WOLFSSL_KYBER512 + if (kp == KYBER512_K) { + kyber_vec_decompress_10(bp, ct, kp); + kyber_decompress_4(v, ct + compVecSz); + } + #endif + #ifdef WOLFSSL_KYBER768 + if (kp == KYBER768_K) { + kyber_vec_decompress_10(bp, ct, kp); + kyber_decompress_4(v, ct + compVecSz); + } + #endif + #ifdef WOLFSSL_KYBER1024 + if (kp == KYBER1024_K) { + kyber_vec_decompress_11(bp, ct); + kyber_decompress_5(v, ct + compVecSz); + } + #endif + + /* Decapsulate the cipher text into polynomial. */ + kyber_decapsulate(key->priv, mp, bp, v, kp); + + /* Convert the polynomial into a array of bytes (message). */ + kyber_to_msg(msg, mp); + } + +#ifndef USE_INTEL_SPEEDUP + /* Dispose of dynamically memory allocated in function. */ + XFREE(bp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +/** + * Decapsulate the cipher text to calculate the shared secret. + * + * Validates the cipher text by encapsulating and comparing with data passed in. + * + * @param [in] key Kyber key object. + * @param [out] ss Shared secret. + * @param [in] ct Cipher text. + * @param [in] len Length of cipher text. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ss or cr are NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the length of cipher text for the key type. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, + const unsigned char* ct, word32 len) +{ + byte msg[2 * KYBER_SYM_SZ]; + byte kr[2 * KYBER_SYM_SZ + 1]; + int ret = 0; + unsigned int ctSz; + unsigned int i; + int fail; +#ifndef USE_INTEL_SPEEDUP + byte* cmp = NULL; +#else + byte cmp[KYBER_MAX_CIPHER_TEXT_SIZE]; +#endif + + /* Validate parameters. */ + if ((key == NULL) || (ss == NULL) || (ct == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish cipher text size based on key type. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + ctSz = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + ctSz = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + ctSz = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + /* Ensure the cipher text passed in is the correct size. */ + if ((ret == 0) && (len != ctSz)) { + ret = BUFFER_E; + } + +#ifndef USE_INTEL_SPEEDUP + if (ret == 0) { + /* Allocate memory for cipher text that is generated. */ + cmp = (byte*)XMALLOC(ctSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (cmp == NULL) { + ret = MEMORY_E; + } + } +#endif + + if (ret == 0) { + /* Decapsulate the cipher text. */ + ret = kyberkey_decapsulate(key, msg, ct); + } + if (ret == 0) { + /* Copy public hash over after the seed. */ + XMEMCPY(msg + KYBER_SYM_SZ, key->h, KYBER_SYM_SZ); + /* Hash message into seed buffer. */ + ret = KYBER_HASH_G(msg, 2 * KYBER_SYM_SZ, kr); + } + if (ret == 0) { + /* Encapsulate the message. */ + ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, cmp); + } + if (ret == 0) { + /* Compare generated cipher text with that passed in. */ + fail = kyber_cmp(ct, cmp, ctSz); + + /* Hash the cipher text after the seed. */ + ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); + } + if (ret == 0) { + /* Change seed to z on comparison failure. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + kr[i] ^= (kr[i] ^ key->z[i]) & fail; + } + + /* Derive the secret from the seed and hash of cipher text. */ + ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); + } + +#ifndef USE_INTEL_SPEEDUP + /* Dispose of dynamic memory allocated in function. */ + XFREE(cmp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +/******************************************************************************/ + +/** + * Decode the private key. + * + * Private Vector | Public Key | Public Hash | Randomizer + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, word32 len) +{ + int ret = 0; + word32 privLen = 0; + word32 pubLen = 0; + unsigned int k = 0; + unsigned char* p = in; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + privLen = KYBER512_PRIVATE_KEY_SIZE; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + privLen = KYBER768_PRIVATE_KEY_SIZE; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + privLen = KYBER1024_PRIVATE_KEY_SIZE; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Decode private key that is vector of polynomials. */ + kyber_from_bytes(key->priv, p, k); + p += k * KYBER_POLY_SIZE; + + /* Decode the public key that is after the private key. */ + ret = wc_KyberKey_DecodePublicKey(key, p, pubLen); + } + if (ret == 0) { + /* Skip over public key. */ + p += pubLen; + /* Copy the hash of the encoded public key that is after public key. */ + XMEMCPY(key->h, p, sizeof(key->h)); + p += KYBER_SYM_SZ; + /* Copy the z (randomizer) that is after hash. */ + XMEMCPY(key->z, p, sizeof(key->z)); + /* Set that private and public keys, and public hash are set. */ + key->flags |= KYBER_FLAG_H_SET | KYBER_FLAG_BOTH_SET; + } + + return ret; +} + +/** + * Decode public key. + * + * Public vector | Public Seed + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_KyberKey_DecodePublicKey(KyberKey* key, unsigned char* in, word32 len) +{ + int ret = 0; + word32 pubLen = 0; + unsigned int k = 0; + unsigned char* p = in; + + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + unsigned int i; + + /* Decode public key that is vector of polynomials. */ + kyber_from_bytes(key->pub, p, k); + p += k * KYBER_POLY_SIZE; + + /* Read public key seed. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + key->pubSeed[i] = p[i]; + } + /* Calculate public hash. */ + ret = KYBER_HASH_H(in, len, key->h); + } + if (ret == 0) { + /* Record public key and public hash set. */ + key->flags |= KYBER_FLAG_PUB_SET | KYBER_FLAG_H_SET; + } + + return ret; +} + +/** + * Get the size in bytes of encoded private key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded private key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the encoded private key for the type of this + * key. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_PRIVATE_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Get the size in bytes of encoded public key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded public key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the encoded public key for the type of this + * key. */ + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Encode the private key. + * + * Private Vector | Public Key | Public Hash | Randomizer + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or private/public key not + * available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_EncodePrivateKey(KyberKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int k = 0; + unsigned int pubLen = 0; + unsigned int privLen = 0; + unsigned char* p = out; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && + ((key->flags & KYBER_FLAG_BOTH_SET) != KYBER_FLAG_BOTH_SET)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + privLen = KYBER512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + privLen = KYBER768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + privLen = KYBER1024_PRIVATE_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Encode private key that is vector of polynomials. */ + kyber_to_bytes(p, key->priv, k); + p += KYBER_POLY_SIZE * k; + + /* Encode public key. */ + ret = wc_KyberKey_EncodePublicKey(key, p, pubLen); + p += pubLen; + } + /* Ensure hash of public key is available. */ + if ((ret == 0) && ((key->flags & KYBER_FLAG_H_SET) == 0)) { + ret = KYBER_HASH_H(p - pubLen, pubLen, key->h); + } + if (ret == 0) { + /* Public hash is available. */ + key->flags |= KYBER_FLAG_H_SET; + /* Append public hash. */ + XMEMCPY(p, key->h, sizeof(key->h)); + p += KYBER_SYM_SZ; + /* Append z (randomizer). */ + XMEMCPY(p, key->z, sizeof(key->z)); + } + + return ret; +} + +/** + * Encode the public key. + * + * Public vector | Public Seed + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or public key not available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int k = 0; + unsigned int pubLen = 0; + unsigned char* p = out; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && + ((key->flags & KYBER_FLAG_PUB_SET) != KYBER_FLAG_PUB_SET)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + switch (key->type) { + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + int i; + + /* Encode public key polynomial by polynomial. */ + kyber_to_bytes(p, key->pub, k); + p += k * KYBER_POLY_SIZE; + + /* Append public seed. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + p[i] = key->pubSeed[i]; + } + + /* Make sure public hash is set. */ + if ((key->flags & KYBER_FLAG_H_SET) == 0) { + ret = KYBER_HASH_H(out, len, key->h); + } + } + if (ret == 0) { + /* Public hash is set. */ + key->flags |= KYBER_FLAG_H_SET; + } + + return ret; +} + +#endif /* WOLFSSL_WC_KYBER */ diff --git a/src/wolfcrypt/src/wc_kyber_poly.c b/src/wolfcrypt/src/wc_kyber_poly.c index dfb10ac..fe140f4 100644 --- a/src/wolfcrypt/src/wc_kyber_poly.c +++ b/src/wolfcrypt/src/wc_kyber_poly.c @@ -1,6 +1,6 @@ /* wc_kyber_poly.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,8 +19,3020 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#include +/* Implementation based on NIST 3rd Round submission package. + * See link at: + * https://csrc.nist.gov/Projects/post-quantum-cryptography/post-quantum-cryptography-standardization/round-3-submissions + */ + +/* Implementation of the functions that operate on polynomials or vectors of + * polynomials. + */ + +#include +#include +#include + +#ifdef WOLFSSL_WC_KYBER + +#ifdef USE_INTEL_SPEEDUP +static word32 cpuid_flags = 0; +#endif + +/* Half of Q plus one. Converted message bit value of 1. */ +#define KYBER_Q_1_HALF ((KYBER_Q + 1) / 2) +/* Half of Q */ +#define KYBER_Q_HALF (KYBER_Q / 2) + + +/* q^-1 mod 2^16 (inverse of 3329 mod 16384) */ +#define KYBER_QINV 62209 + +/* Used in Barrett Reduction: + * r = a mod q + * => r = a - ((V * a) >> 26) * q), as V based on 2^26 + * V is the mulitplier that gets the quotient after shifting. + */ +#define KYBER_V (((1U << 26) + (KYBER_Q / 2)) / KYBER_Q) + +/* Used in converting to Montgomery form. + * f is the normalizer = 2^k % m. + * 16-bit value cast to sword32 in use. + */ +#define KYBER_F ((1ULL << 32) % KYBER_Q) + +/* Number of bytes in an output block of SHA-3-128 */ +#define SHA3_128_BYTES (WC_SHA3_128_COUNT * 8) +/* Number of bytes in an output block of SHA-3-256 */ +#define SHA3_256_BYTES (WC_SHA3_256_COUNT * 8) + +/* Number of blocks to generate for matrix. */ +#define GEN_MATRIX_NBLOCKS \ + ((12 * KYBER_N / 8 * (1 << 12) / KYBER_Q + XOF_BLOCK_SIZE) / XOF_BLOCK_SIZE) +/* Number of bytes to generate for matrix. */ +#define GEN_MATRIX_SIZE GEN_MATRIX_NBLOCKS * XOF_BLOCK_SIZE + + +/* Number of random bytes to generate for ETA3. */ +#define ETA3_RAND_SIZE ((3 * KYBER_N) / 4) +/* Number of random bytes to generate for ETA2. */ +#define ETA2_RAND_SIZE ((2 * KYBER_N) / 4) + + +/* Montgomery reduce a. + * + * @param [in] a 32-bit value to be reduced. + * @return Montgomery reduction result. + */ +#define KYBER_MONT_RED(a) \ + (sword16)(((a) - (sword32)(((sword16)((sword16)(a) * \ + (sword16)KYBER_QINV)) * \ + (sword32)KYBER_Q)) >> 16) + +/* Barrett reduce a. r = a mod q. + * + * Converted division to multiplication. + * + * @param [in] a 16-bit value to be reduced to range of q. + * @return Modulo result. + */ +#define KYBER_BARRETT_RED(a) \ + (sword16)((sword16)(a) - (sword16)((sword16)( \ + ((sword32)((sword32)KYBER_V * (sword16)(a))) >> 26) * (word16)KYBER_Q)) + + +/* Zetas for NTT. */ +const sword16 zetas[KYBER_N / 2] = { + 2285, 2571, 2970, 1812, 1493, 1422, 287, 202, 3158, 622, 1577, 182, + 962, 2127, 1855, 1468, 573, 2004, 264, 383, 2500, 1458, 1727, 3199, + 2648, 1017, 732, 608, 1787, 411, 3124, 1758, 1223, 652, 2777, 1015, + 2036, 1491, 3047, 1785, 516, 3321, 3009, 2663, 1711, 2167, 126, 1469, + 2476, 3239, 3058, 830, 107, 1908, 3082, 2378, 2931, 961, 1821, 2604, + 448, 2264, 677, 2054, 2226, 430, 555, 843, 2078, 871, 1550, 105, + 422, 587, 177, 3094, 3038, 2869, 1574, 1653, 3083, 778, 1159, 3182, + 2552, 1483, 2727, 1119, 1739, 644, 2457, 349, 418, 329, 3173, 3254, + 817, 1097, 603, 610, 1322, 2044, 1864, 384, 2114, 3193, 1218, 1994, + 2455, 220, 2142, 1670, 2144, 1799, 2051, 794, 1819, 2475, 2459, 478, + 3221, 3021, 996, 991, 958, 1869, 1522, 1628 +}; + +/* Zetas for inverse NTT. */ +const sword16 zetas_inv[KYBER_N / 2] = { + 1701, 1807, 1460, 2371, 2338, 2333, 308, 108, 2851, 870, 854, 1510, + 2535, 1278, 1530, 1185, 1659, 1187, 3109, 874, 1335, 2111, 136, 1215, + 2945, 1465, 1285, 2007, 2719, 2726, 2232, 2512, 75, 156, 3000, 2911, + 2980, 872, 2685, 1590, 2210, 602, 1846, 777, 147, 2170, 2551, 246, + 1676, 1755, 460, 291, 235, 3152, 2742, 2907, 3224, 1779, 2458, 1251, + 2486, 2774, 2899, 1103, 1275, 2652, 1065, 2881, 725, 1508, 2368, 398, + 951, 247, 1421, 3222, 2499, 271, 90, 853, 1860, 3203, 1162, 1618, + 666, 320, 8, 2813, 1544, 282, 1838, 1293, 2314, 552, 2677, 2106, + 1571, 205, 2918, 1542, 2721, 2597, 2312, 681, 130, 1602, 1871, 829, + 2946, 3065, 1325, 2756, 1861, 1474, 1202, 2367, 3147, 1752, 2707, 171, + 3127, 3042, 1907, 1836, 1517, 359, 758, 1441 +}; + + +/* Number-Theoretic Transform. + * + * @param [in, out] r Polynomial to transform. + */ +static void kyber_ntt(sword16* r) +{ +#ifdef WOLFSSL_KYBER_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + + k = 1; + for (len = KYBER_N / 2; len >= 2; len >>= 1) { + unsigned int start; + for (start = 0; start < KYBER_N; start = j + len) { + sword16 zeta = zetas[k++]; + for (j = start; j < start + len; ++j) { + sword32 p = (sword32)zeta * r[j + len]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[j]; + r[j + len] = rj - t; + r[j] = rj + t; + } + } + } + + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < KYBER_N; ++j) { + r[j] = KYBER_BARRETT_RED(r[j]); + } +#else + unsigned int len; + unsigned int k = 1; + unsigned int j; + unsigned int start; + sword16 zeta = zetas[k++]; + + for (j = 0; j < KYBER_N / 2; ++j) { + sword32 p = (sword32)zeta * r[j + KYBER_N / 2]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[j]; + r[j + KYBER_N / 2] = rj - t; + r[j] = rj + t; + } + for (len = KYBER_N / 4; len >= 2; len >>= 1) { + for (start = 0; start < KYBER_N; start = j + len) { + zeta = zetas[k++]; + for (j = start; j < start + len; ++j) { + sword32 p = (sword32)zeta * r[j + len]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[j]; + r[j + len] = rj - t; + r[j] = rj + t; + } + } + } + + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < KYBER_N; ++j) { + r[j] = KYBER_BARRETT_RED(r[j]); + } +#endif +} + +/* Inverse Number-Theoretic Transform. + * + * @param [in, out] r Polynomial to transform. + */ +static void kyber_invntt(sword16* r) +{ +#ifdef WOLFSSL_KYBER_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + sword16 zeta; + + k = 0; + for (len = 2; len <= KYBER_N / 2; len <<= 1) { + unsigned int start; + for (start = 0; start < KYBER_N; start = j + len) { + zeta = zetas_inv[k++]; + for (j = start; j < start + len; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + len]; + sword16 t = rj + rjl; + r[j] = KYBER_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j + len] = KYBER_MONT_RED(p); + } + } + } + + zeta = zetas_inv[127]; + for (j = 0; j < KYBER_N; ++j) { + sword32 p = (sword32)zeta * r[j]; + r[j] = KYBER_MONT_RED(p); + } +#else + unsigned int k; + unsigned int j; + unsigned int start; + sword16 zeta; + sword16 zeta2; + + k = 0; + for (start = 0; start < KYBER_N; start += 2 * 2) { + zeta = zetas_inv[k++]; + for (j = 0; j < 2; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 2]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 2] = KYBER_MONT_RED(p); + } + } + for (start = 0; start < KYBER_N; start += 2 * 4) { + zeta = zetas_inv[k++]; + for (j = 0; j < 4; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 4]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 4] = KYBER_MONT_RED(p); + } + } + for (start = 0; start < KYBER_N; start += 2 * 8) { + zeta = zetas_inv[k++]; + for (j = 0; j < 8; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 8]; + sword16 t = rj + rjl; + /* Reduce. */ + r[start + j] = KYBER_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 8] = KYBER_MONT_RED(p); + } + } + for (start = 0; start < KYBER_N; start += 2 * 16) { + zeta = zetas_inv[k++]; + for (j = 0; j < 16; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 16]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 16] = KYBER_MONT_RED(p); + } + } + for (start = 0; start < KYBER_N; start += 2 * 32) { + zeta = zetas_inv[k++]; + for (j = 0; j < 32; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 32]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 32] = KYBER_MONT_RED(p); + } + } + for (start = 0; start < KYBER_N; start += 2 * 64) { + zeta = zetas_inv[k++]; + for (j = 0; j < 64; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 64]; + sword16 t = rj + rjl; + /* Reduce. */ + r[start + j] = KYBER_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 64] = KYBER_MONT_RED(p); + } + } + zeta = zetas_inv[126]; + zeta2 = zetas_inv[127]; + for (j = 0; j < KYBER_N / 2; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + KYBER_N / 2]; + sword16 t = rj + rjl; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j] = t; + r[j + KYBER_N / 2] = KYBER_MONT_RED(p); + + p = (sword32)zeta2 * r[j]; + r[j] = KYBER_MONT_RED(p); + p = (sword32)zeta2 * r[j + KYBER_N / 2]; + r[j + KYBER_N / 2] = KYBER_MONT_RED(p); + } +#endif +} + +/* Multiplication of polynomials in Zq[X]/(X^2-zeta). + * + * Used for multiplication of elements in Rq in NTT domain. + * + * @param [out] r Result polynomial. + * @param [in] a First factor. + * @param [in] b Second factor. + * @param [in] zeta Integer defining the reduction polynomial. + */ +static void kyber_basemul(sword16* r, const sword16* a, const sword16* b, + sword16 zeta) +{ + sword16 r0; + sword16 a0 = a[0]; + sword16 a1 = a[1]; + sword16 b0 = b[0]; + sword16 b1 = b[1]; + sword32 p1; + sword32 p2; + + p1 = (sword32)a1 * b1; + p2 = (sword32)a0 * b0; + r0 = KYBER_MONT_RED(p1); + p1 = (sword32)zeta * r0; + p1 += p2; + r[0] = KYBER_MONT_RED(p1); + + p1 = (sword32)a0 * b1; + p2 = (sword32)a1 * b0; + p1 += p2; + r[1] = KYBER_MONT_RED(p1); +} + +/* Multiply two polynomials in NTT domain. r = a * b. + * + * @param [out] r Result polynomial. + * @param [in] a First polynomial multiplier. + * @param [in] b Second polynomial multiplier. + */ +static void kyber_basemul_mont(sword16* r, const sword16* a, const sword16* b) +{ + unsigned int i; + const sword16* zeta = zetas + 64; + +#ifdef WOLFSSL_KYBER_SMALL + for (i = 0; i < KYBER_N; i += 4, zeta++) { + kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + } +#else + for (i = 0; i < KYBER_N; i += 8, zeta += 2) { + kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + kyber_basemul(r + i + 4, a + i + 4, b + i + 4, zeta[1]); + kyber_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); + } +#endif +} + +/* Multiply two polynomials in NTT domain and add to result. r += a * b. + * + * @param [in, out] r Result polynomial. + * @param [in] a First polynomial multiplier. + * @param [in] b Second polynomial multiplier. + */ +static void kyber_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b) +{ + unsigned int i; + const sword16* zeta = zetas + 64; + +#ifdef WOLFSSL_KYBER_SMALL + for (i = 0; i < KYBER_N; i += 4, zeta++) { + sword16 t0[2]; + sword16 t2[2]; + + kyber_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + } +#else + for (i = 0; i < KYBER_N; i += 8, zeta += 2) { + sword16 t0[2]; + sword16 t2[2]; + sword16 t4[2]; + sword16 t6[2]; + + kyber_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + kyber_basemul(t4, a + i + 4, b + i + 4, zeta[1]); + kyber_basemul(t6, a + i + 6, b + i + 6, -zeta[1]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + r[i + 4] += t4[0]; + r[i + 5] += t4[1]; + r[i + 6] += t6[0]; + r[i + 7] += t6[1]; + } +#endif +} + +/* Pointwise multiply elements of a and b, into r, and multiply by 2^-16. + * + * @param [out] r Result polynomial. + * @param [in] a First vector polynomial to multiply with. + * @param [in] b Second vector polynomial to multiply with. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_pointwise_acc_mont(sword16* r, const sword16* a, + const sword16* b, unsigned int kp) +{ + unsigned int i; + + kyber_basemul_mont(r, a, b); + for (i = 1; i < kp - 1; ++i) { + kyber_basemul_mont_add(r, a + i * KYBER_N, b + i * KYBER_N); + } + kyber_basemul_mont_add(r, a + (kp - 1) * KYBER_N, b + (kp - 1) * KYBER_N); +} + +/******************************************************************************/ + +/* Initialize Kyber implementation. + */ +void kyber_init(void) +{ +#ifdef USE_INTEL_SPEEDUP + cpuid_flags = cpuid_get_flags(); +#endif +} + +/******************************************************************************/ + +/* Generate a public-private key pair from randomly generated data. + * + * @param [in, out] priv Private key vector of polynomials. + * @param [out] pub Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_keygen_c(sword16* priv, sword16* pub, sword16* e, + const sword16* a, int kp) +{ + int i; + + /* Transform private key. All of result used in public key calculation */ + for (i = 0; i < kp; ++i) { + kyber_ntt(priv + i * KYBER_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < kp; ++i) { + unsigned int j; + + /* Multiply a by private into public polynomial. */ + kyber_pointwise_acc_mont(pub + i * KYBER_N, a + i * kp * KYBER_N, priv, + kp); + /* Convert public polynomial to Montgomery form. */ + for (j = 0; j < KYBER_N; ++j) { + sword32 t = pub[i * KYBER_N + j] * (sword32)KYBER_F; + pub[i * KYBER_N + j] = KYBER_MONT_RED(t); + } + /* Transform error values polynomial. */ + kyber_ntt(e + i * KYBER_N); + /* Add errors to public key and reduce. */ + for (j = 0; j < KYBER_N; ++j) { + sword16 t = pub[i * KYBER_N + j] + e[i * KYBER_N + j]; + pub[i * KYBER_N + j] = KYBER_BARRETT_RED(t); + } + } +} + +/* Generate a public-private key pair from randomly generated data. + * + * @param [in, out] priv Private key vector of polynomials. + * @param [out] pub Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, + int kp) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_keygen_avx2(priv, pub, e, a, kp); + } + else +#endif + { + kyber_keygen_c(priv, pub, e, a, kp); + } +} + +/* Encapsuluate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [out] bp Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] at Array of vector of polynomials. + * @param [in] sp Vector of polynomials. + * @param [in] ep Error Vector of polynomials. + * @param [in] epp Error polynomial. + * @param [in] m Message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_encapsulate_c(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp) +{ + int i; + + /* Transform sp. All of result used in calculation of bp and v. */ + for (i = 0; i < kp; ++i) { + kyber_ntt(sp + i * KYBER_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < kp; ++i) { + unsigned int j; + + /* Multiply at by sp into bp polynomial. */ + kyber_pointwise_acc_mont(bp + i * KYBER_N, at + i * kp * KYBER_N, sp, + kp); + /* Inverse transform bp polynomial. */ + kyber_invntt(bp + i * KYBER_N); + /* Add errors to bp and reduce. */ + for (j = 0; j < KYBER_N; ++j) { + sword16 t = bp[i * KYBER_N + j] + ep[i * KYBER_N + j]; + bp[i * KYBER_N + j] = KYBER_BARRETT_RED(t); + } + } + + /* Multiply public key by sp into v polynomial. */ + kyber_pointwise_acc_mont(v, pub, sp, kp); + /* Inverse transform v. */ + kyber_invntt(v); + /* Add errors and message to v and reduce. */ + for (i = 0; i < KYBER_N; ++i) { + sword16 t = v[i] + epp[i] + m[i]; + v[i] = KYBER_BARRETT_RED(t); + } +} + + +/* Encapsulate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [out] bp Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] at Array of vector of polynomials. + * @param [in] sp Vector of polynomials. + * @param [in] ep Error Vector of polynomials. + * @param [in] epp Error polynomial. + * @param [in] m Message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_encapsulate(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_encapsulate_avx2(pub, bp, v, at, sp, ep, epp, m, kp); + } + else +#endif + { + kyber_encapsulate_c(pub, bp, v, at, sp, ep, epp, m, kp); + } +} + +/* Decapsulate message. + * + * @param [in] priv Private key vector of polynomials. + * @param [out] mp Message polynomial. + * @param [in] bp Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_decapsulate_c(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp) +{ + int i; + + /* Transform bp. All of result used in calculation of mp. */ + for (i = 0; i < kp; ++i) { + kyber_ntt(bp + i * KYBER_N); + } + + /* Multiply private key by bp into mp polynomial. */ + kyber_pointwise_acc_mont(mp, priv, bp, kp); + /* Inverse transform mp. */ + kyber_invntt(mp); + /* Subtract errors (mp) out of v and reduce into mp. */ + for (i = 0; i < KYBER_N; ++i) { + sword16 t = v[i] - mp[i]; + mp[i] = KYBER_BARRETT_RED(t); + } +} + +/* Decapsulate message. + * + * @param [in] priv Private key vector of polynomials. + * @param [out] mp Message polynomial. + * @param [in] bp Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_decapsulate_avx2(priv, mp, bp, v, kp); + } + else +#endif + { + kyber_decapsulate_c(priv, mp, bp, v, kp); + } +} + +/******************************************************************************/ + +#ifdef USE_INTEL_SPEEDUP +#ifdef WOLFSSL_KYBER512 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k2_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + if (!transposed) { + state[4*4 + 0] = 0x1f0000 + 0x000; + state[4*4 + 1] = 0x1f0000 + 0x001; + state[4*4 + 2] = 0x1f0000 + 0x100; + state[4*4 + 3] = 0x1f0000 + 0x101; + } + else { + state[4*4 + 0] = 0x1f0000 + 0x000; + state[4*4 + 1] = 0x1f0000 + 0x100; + state[4*4 + 2] = 0x1f0000 + 0x001; + state[4*4 + 3] = 0x1f0000 + 0x101; + } + + kyber_sha3_128_blocksx4_seed_avx2(state, seed); + kyber_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, rand + i + 0 * GEN_MATRIX_SIZE, + rand + i + 1 * GEN_MATRIX_SIZE, rand + i + 2 * GEN_MATRIX_SIZE, + rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = kyber_rej_uniform_n_avx2(a + 0 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = kyber_rej_uniform_n_avx2(a + 1 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = kyber_rej_uniform_n_avx2(a + 2 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = kyber_rej_uniform_n_avx2(a + 3 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N) || + (ctr3 < KYBER_N)) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += kyber_rej_uniform_avx2(a + 0 * KYBER_N + ctr0, KYBER_N - ctr0, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += kyber_rej_uniform_avx2(a + 1 * KYBER_N + ctr1, KYBER_N - ctr1, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += kyber_rej_uniform_avx2(a + 2 * KYBER_N + ctr2, KYBER_N - ctr2, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += kyber_rej_uniform_avx2(a + 3 * KYBER_N + ctr3, KYBER_N - ctr3, + p, XOF_BLOCK_SIZE); + } + + return 0; +} +#endif + +#ifdef WOLFSSL_KYBER768 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + for (k = 0; k < 2; k++) { + for (i = 0; i < 4; i++) { + if (!transposed) { + state[4*4 + i] = 0x1f0000 + (((k*4+i)/3) << 8) + ((k*4+i)%3); + } + else { + state[4*4 + i] = 0x1f0000 + (((k*4+i)%3) << 8) + ((k*4+i)/3); + } + } + + kyber_sha3_128_blocksx4_seed_avx2(state, seed); + kyber_redistribute_21_rand_avx2(state, + rand + 0 * GEN_MATRIX_SIZE, rand + 1 * GEN_MATRIX_SIZE, + rand + 2 * GEN_MATRIX_SIZE, rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, + rand + i + 0 * GEN_MATRIX_SIZE, rand + i + 1 * GEN_MATRIX_SIZE, + rand + i + 2 * GEN_MATRIX_SIZE, rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = kyber_rej_uniform_n_avx2(a + 0 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = kyber_rej_uniform_n_avx2(a + 1 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = kyber_rej_uniform_n_avx2(a + 2 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = kyber_rej_uniform_n_avx2(a + 3 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N) || + (ctr3 < KYBER_N)) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += kyber_rej_uniform_avx2(a + 0 * KYBER_N + ctr0, + KYBER_N - ctr0, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += kyber_rej_uniform_avx2(a + 1 * KYBER_N + ctr1, + KYBER_N - ctr1, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += kyber_rej_uniform_avx2(a + 2 * KYBER_N + ctr2, + KYBER_N - ctr2, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += kyber_rej_uniform_avx2(a + 3 * KYBER_N + ctr3, + KYBER_N - ctr3, p, XOF_BLOCK_SIZE); + } + + a += 4 * KYBER_N; + } + + state[0] = ((word64*)seed)[0]; + state[1] = ((word64*)seed)[1]; + state[2] = ((word64*)seed)[2]; + state[3] = ((word64*)seed)[3]; + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (2 << 8) + 2; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = 0x8000000000000000UL; + for (i = 0; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags)) { + sha3_block_avx2(state); + } + else { + BlockSha3(state); + } + XMEMCPY(rand + i, state, SHA3_128_BYTES); + } + ctr0 = kyber_rej_uniform_n_avx2(a, KYBER_N, rand, GEN_MATRIX_SIZE); + while (ctr0 < KYBER_N) { + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags)) { + sha3_block_avx2(state); + } + else { + BlockSha3(state); + } + XMEMCPY(rand, state, SHA3_128_BYTES); + ctr0 += kyber_rej_uniform_avx2(a + ctr0, KYBER_N - ctr0, rand, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif +#ifdef WOLFSSL_KYBER1024 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + for (k = 0; k < 4; k++) { + for (i = 0; i < 4; i++) { + if (!transposed) { + state[4*4 + i] = 0x1f0000 + (k << 8) + i; + } + else { + state[4*4 + i] = 0x1f0000 + (i << 8) + k; + } + } + + kyber_sha3_128_blocksx4_seed_avx2(state, seed); + kyber_redistribute_21_rand_avx2(state, + rand + 0 * GEN_MATRIX_SIZE, rand + 1 * GEN_MATRIX_SIZE, + rand + 2 * GEN_MATRIX_SIZE, rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, + rand + i + 0 * GEN_MATRIX_SIZE, rand + i + 1 * GEN_MATRIX_SIZE, + rand + i + 2 * GEN_MATRIX_SIZE, rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = kyber_rej_uniform_n_avx2(a + 0 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = kyber_rej_uniform_n_avx2(a + 1 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = kyber_rej_uniform_n_avx2(a + 2 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = kyber_rej_uniform_n_avx2(a + 3 * KYBER_N, KYBER_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N) || + (ctr3 < KYBER_N)) { + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += kyber_rej_uniform_avx2(a + 0 * KYBER_N + ctr0, + KYBER_N - ctr0, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += kyber_rej_uniform_avx2(a + 1 * KYBER_N + ctr1, + KYBER_N - ctr1, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += kyber_rej_uniform_avx2(a + 2 * KYBER_N + ctr2, + KYBER_N - ctr2, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += kyber_rej_uniform_avx2(a + 3 * KYBER_N + ctr3, + KYBER_N - ctr3, p, XOF_BLOCK_SIZE); + } + + a += 4 * KYBER_N; + } + + return 0; +} +#endif /* KYBER1024 */ +#endif /* USE_INTEL_SPEEDUP */ + +/* Absorb the seed data for squeezing out pseudo-random data. + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] seed Data to absorb. + * @param [in] len Length of data to absorb in bytes. + * @return 0 on success always. + */ +static int kyber_xof_absorb(wc_Shake* shake128, byte* seed, int len) +{ + int ret; + + ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); + if (ret == 0) { + ret = wc_Shake128_Absorb(shake128, seed, len); + } + + return ret; +} + +/* Squeeze the state to produce pseudo-random data. + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [out] out Buffer to write to. + * @param [in] blocks Number of blocks to write. + * @return 0 on success always. + */ +static int kyber_xof_squeezeblocks(wc_Shake* shake128, byte* out, int blocks) +{ + return wc_Shake128_SqueezeBlocks(shake128, out, blocks); +} + +/* Initialize SHAKE-256 object. + * + * @param [in, out] shake256 SHAKE-256 object. + */ +void kyber_prf_init(wc_Shake* prf) +{ + XMEMSET(prf->s, 0, sizeof(prf->s)); +} + +/* New/Initialize SHAKE-256 object. + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] heap Dynamic memory allocator hint. + * @param [in] devId Device id. + * @return 0 on success always. + */ +int kyber_prf_new(wc_Shake* prf, void* heap, int devId) +{ + return wc_InitShake256(prf, heap, devId); +} + +/* Free SHAKE-256 object. + * + * @param [in, out] shake256 SHAKE-256 object. + */ +void kyber_prf_free(wc_Shake* prf) +{ + wc_Shake256_Free(prf); +} + +/* Create pseudo-random data from the key using SHAKE-256. + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to write. + * @param [in] key Data to derive from. Must be KYBER_SYM_SZ + 1 + * bytes in length. + * @return 0 on success always. + */ +static int kyber_prf(wc_Shake* shake256, byte* out, unsigned int outLen, + const byte* key) +{ +#ifdef USE_INTEL_SPEEDUP + int i; + word64 state[25]; + + (void)shake256; + + for (i = 0; i < KYBER_SYM_SZ / 8; i++) { + state[i] = ((word64*)key)[i]; + } + state[KYBER_SYM_SZ / 8] = 0x1f00 | key[KYBER_SYM_SZ]; + XMEMSET(state + KYBER_SYM_SZ / 8 + 1, 0, + (25 - KYBER_SYM_SZ / 8 - 1) * sizeof(word64)); + state[WC_SHA3_256_COUNT - 1] = 0x8000000000000000UL; + + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags)) { + sha3_block_avx2(state); + } + else { + BlockSha3(state); + } + XMEMCPY(out, state, outLen); + + return 0; +#else + int ret; + + ret = wc_Shake256_Update(shake256, key, KYBER_SYM_SZ + 1); + if (ret == 0) { + ret = wc_Shake256_Final(shake256, out, outLen); + } + + return ret; +#endif +} + +#ifdef USE_INTEL_SPEEDUP +/* Create pseudo-random key from the seed using SHAKE-256. + * + * @param [in] seed Data to derive from. + * @param [in] seedLen Length of data to derive from in bytes. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to derive. + * @return 0 on success always. + */ +int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen) +{ + word64 state[25]; + int i; + int len64 = seedLen / 8; + + for (i = 0; i < len64; i++) { + state[i] = ((word64*)seed)[i]; + } + state[len64] = 0x1f; + XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); + state[WC_SHA3_256_COUNT - 1] = 0x8000000000000000UL; + + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags)) { + sha3_block_avx2(state); + } + else { + BlockSha3(state); + } + XMEMCPY(out, state, outLen); + + return 0; +} +#endif + +/* Rejection sampling on uniform random bytes to generate uniform random + * integers mod q. + * + * @param [out] p Uniform random integers mod q. + * @param [in] len Maximum number of integers. + * @param [in] r Uniform random bytes buffer. + * @param [in] rLen Length of random data in buffer. + * @return Number of integers sampled. + */ +static unsigned int kyber_rej_uniform_c(sword16* p, unsigned int len, + const byte* r, unsigned int rLen) +{ + unsigned int i; + unsigned int j; + + /* Keep sampling until maximum number of integers reached or buffer used up. + */ + for (i = 0, j = 0; (i < len) && (j <= rLen - 3); j += 3) { + /* Use 24 bits (3 bytes) as two 12 bits integers. */ + sword16 v0 = ((r[0] >> 0) | ((word16)r[1] << 8)) & 0xFFF; + sword16 v1 = ((r[1] >> 4) | ((word16)r[2] << 4)) & 0xFFF; + + /* Reject first 12-bit integer if greater than or equal to q. */ + if (v0 < KYBER_Q) { + p[i++] = v0; + } + /* Check second if we don't have enough integers yet. + * Reject second 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v1 < KYBER_Q)) { + p[i++] = v1; + } + + /* Move over used bytes. */ + r += 3; + } + + return i; +} + +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [in] prf XOF object. + * @param [out] a Matrix of uniform integers. + * @param [in] kp Number of dimensions. kp x kp polynomials. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_c(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, + int transposed) +{ +#ifdef WOLFSSL_SMALL_STACK + byte* rand; +#else + byte rand[GEN_MATRIX_SIZE + 2]; +#endif + byte extSeed[KYBER_SYM_SZ + 2]; + int ret = 0; + int i; + + XMEMCPY(extSeed, seed, KYBER_SYM_SZ); + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate large amount of memory to hold random bytes to be samples. */ + rand = (byte*)XMALLOC(GEN_MATRIX_SIZE + 2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (rand == NULL) { + ret = MEMORY_E; + } +#endif + + /* Generate each vector of polynomials. */ + for (i = 0; (ret == 0) && (i < kp); i++, a += kp * KYBER_N) { + int j; + /* Generate each polynomial in vector from seed with indices. */ + for (j = 0; (ret == 0) && (j < kp); j++) { + if (transposed) { + extSeed[KYBER_SYM_SZ + 0] = i; + extSeed[KYBER_SYM_SZ + 1] = j; + } + else { + extSeed[KYBER_SYM_SZ + 0] = j; + extSeed[KYBER_SYM_SZ + 1] = i; + } + /* Absorb the index specific seed. */ + ret = kyber_xof_absorb(prf, extSeed, sizeof(extSeed)); + if (ret == 0) { + /* Create out based on the seed. */ + ret = kyber_xof_squeezeblocks(prf, rand, GEN_MATRIX_NBLOCKS); + } + if (ret == 0) { + #if (GEN_MATRIX_SIZE % 3) != 0 + unsigned int randLen; + #endif + unsigned int ctr; + + /* Sample random bytes to create a polynomial. */ + ctr = kyber_rej_uniform_c(a + j * KYBER_N, KYBER_N, rand, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + #if (GEN_MATRIX_SIZE % 3) != 0 + randLen = GEN_MATRIX_SIZE; + while (ctr < KYBER_N) { + int off = randLen % 3; + int k; + for (k = 0; k < off; k++) { + rand[k] = rand[randLen - off + k]; + } + kyber_xof_squeezeblocks(prf, rand + off, 1); + randLen = off + XOF_BLOCK_SIZE; + ctr += kyber_rej_uniform_c(a + j * KYBER_N + ctr, + KYBER_N - ctr, rand, randLen); + } + #else + while (ctr < KYBER_N) { + kyber_xof_squeezeblocks(prf, rand, 1); + ctr += kyber_rej_uniform_c(a + j * KYBER_N + ctr, + KYBER_N - ctr, rand, XOF_BLOCK_SIZE); + } + #endif + } + } + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of temporary buffer. */ + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [in] prf XOF object. + * @param [out] a Matrix of uniform integers. + * @param [in] kp Number of dimensions. kp x kp polynomials. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, + int transposed) +{ + int ret; + +#ifdef WOLFSSL_KYBER512 + if (kp == KYBER512_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_gen_matrix_k2_avx2(a, seed, transposed); + } + else + #endif + { + ret = kyber_gen_matrix_c(prf, a, KYBER512_K, seed, transposed); + } + } + else +#endif +#ifdef WOLFSSL_KYBER768 + if (kp == KYBER768_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_gen_matrix_k3_avx2(a, seed, transposed); + } + else + #endif + { + ret = kyber_gen_matrix_c(prf, a, KYBER768_K, seed, transposed); + } + } + else +#endif +#ifdef WOLFSSL_KYBER1024 + if (kp == KYBER1024_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_gen_matrix_k4_avx2(a, seed, transposed); + } + else + #endif + { + ret = kyber_gen_matrix_c(prf, a, KYBER1024_K, seed, transposed); + } + } + else +#endif + { + ret = BAD_STATE_E; + } + + return ret; +} + +/******************************************************************************/ + +/* Subtract one 2 bit value from another out of a larger number. + * + * @param [in] d Value containing sequential 2 bit values. + * @param [in] i Start index of the two values in 2 bits each. + * @return Difference of the two values with range 0..2. + */ +#define ETA2_SUB(d, i) \ + (((sword16)(((d) >> ((i) * 4 + 0)) & 0x3)) - \ + ((sword16)(((d) >> ((i) * 4 + 2)) & 0x3))) + +/* Compute polynomial with coefficients distributed according to a centered + * binomial distribution with parameter eta2 from uniform random bytes. + * + * @param [out] p Polynomial computed. + * @param [in] r Random bytes. + */ +static void kyber_cbd_eta2(sword16* p, const byte* r) +{ + unsigned int i; + +#ifndef WORD64_AVAILABLE + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 8) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + #endif + /* Take the next 4 bytes, little endian, as a 32 bit value. */ + #ifdef BIG_ENDIAN_ORDER + word32 t = ByteReverseWord32(*(word32*)r); + #else + word32 t = *(word32*)r; + #endif + word32 d; + /* Add second bits to first. */ + d = (t >> 0) & 0x55555555; + d += (t >> 1) & 0x55555555; + /* Values 0, 1 or 2 in consecutive 2 bits. + * 0 - 1/4, 1 - 2/4, 2 - 1/4. */ + + #ifdef WOLFSSL_KYBER_SMALL + for (j = 0; j < 8; j++) { + p[i + j] = ETA2_SUB(d, j); + } + #else + p[i + 0] = ETA2_SUB(d, 0); + p[i + 1] = ETA2_SUB(d, 1); + p[i + 2] = ETA2_SUB(d, 2); + p[i + 3] = ETA2_SUB(d, 3); + p[i + 4] = ETA2_SUB(d, 4); + p[i + 5] = ETA2_SUB(d, 5); + p[i + 6] = ETA2_SUB(d, 6); + p[i + 7] = ETA2_SUB(d, 7); + #endif + /* -2 - 1/16, -1 - 4/16, 0 - 6/16, 1 - 4/16, 2 - 1/16 */ + + /* Move over used bytes. */ + r += 4; + } +#else + /* Calculate sixteen integer coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 16) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + #endif + /* Take the next 8 bytes, little endian, as a 64 bit value. */ + #ifdef BIG_ENDIAN_ORDER + word64 t = ByteReverseWord64(*(word64*)r); + #else + word64 t = *(word64*)r; + #endif + word64 d; + /* Add second bits to first. */ + d = (t >> 0) & 0x5555555555555555L; + d += (t >> 1) & 0x5555555555555555L; + /* Values 0, 1 or 2 in consecutive 2 bits. + * 0 - 1/4, 1 - 2/4, 2 - 1/4. */ + + #ifdef WOLFSSL_KYBER_SMALL + for (j = 0; j < 16; j++) { + p[i + j] = ETA2_SUB(d, j); + } + #else + p[i + 0] = ETA2_SUB(d, 0); + p[i + 1] = ETA2_SUB(d, 1); + p[i + 2] = ETA2_SUB(d, 2); + p[i + 3] = ETA2_SUB(d, 3); + p[i + 4] = ETA2_SUB(d, 4); + p[i + 5] = ETA2_SUB(d, 5); + p[i + 6] = ETA2_SUB(d, 6); + p[i + 7] = ETA2_SUB(d, 7); + p[i + 8] = ETA2_SUB(d, 8); + p[i + 9] = ETA2_SUB(d, 9); + p[i + 10] = ETA2_SUB(d, 10); + p[i + 11] = ETA2_SUB(d, 11); + p[i + 12] = ETA2_SUB(d, 12); + p[i + 13] = ETA2_SUB(d, 13); + p[i + 14] = ETA2_SUB(d, 14); + p[i + 15] = ETA2_SUB(d, 15); + #endif + /* -2 - 1/16, -1 - 4/16, 0 - 6/16, 1 - 4/16, 2 - 1/16 */ + + /* Move over used bytes. */ + r += 8; + } +#endif +} + +#ifdef WOLFSSL_KYBER512 +/* Subtract one 3 bit value from another out of a larger number. + * + * @param [in] d Value containing sequential 3 bit values. + * @param [in] i Start index of the two values in 3 bits each. + * @return Difference of the two values with range 0..3. + */ +#define ETA3_SUB(d, i) \ + (((sword16)(((d) >> ((i) * 6 + 0)) & 0x7)) - \ + ((sword16)(((d) >> ((i) * 6 + 3)) & 0x7))) + +/* Compute polynomial with coefficients distributed according to a centered + * binomial distribution with parameter eta3 from uniform random bytes. + * + * @param [out] p Polynomial computed. + * @param [in] r Random bytes. + */ +static void kyber_cbd_eta3(sword16* p, const byte* r) +{ + unsigned int i; + +#ifndef WORD64_AVAILABLE + /* Calculate four integer coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 4) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + #endif + /* Take the next 3 bytes, little endian, as a 24 bit value. */ + word32 t = (((word32)(r[0])) << 0) | + (((word32)(r[1])) << 8) | + (((word32)(r[2])) << 16); + word32 d; + /* Add second and third bits to first. */ + d = (t >> 0) & 0x00249249; + d += (t >> 1) & 0x00249249; + d += (t >> 2) & 0x00249249; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + #ifdef WOLFSSL_KYBER_SMALL + for (j = 0; j < 4; j++) { + p[i + j] = ETA3_SUB(d, j); + } + #else + p[i + 0] = ETA3_SUB(d, 0); + p[i + 1] = ETA3_SUB(d, 1); + p[i + 2] = ETA3_SUB(d, 2); + p[i + 3] = ETA3_SUB(d, 3); + #endif + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 3; + } +#else + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 8) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + #endif + /* Take the next 6 bytes, little endian, as a 48 bit value. */ + word64 t = (((word64)(r[0])) << 0) | + (((word64)(r[1])) << 8) | + (((word64)(r[2])) << 16) | + (((word64)(r[3])) << 24) | + (((word64)(r[4])) << 32) | + (((word64)(r[5])) << 40); + word64 d; + /* Add second and third bits to first. */ + d = (t >> 0) & 0x0000249249249249L; + d += (t >> 1) & 0x0000249249249249L; + d += (t >> 2) & 0x0000249249249249L; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + #ifdef WOLFSSL_KYBER_SMALL + for (j = 0; j < 8; j++) { + p[i + j] = ETA3_SUB(d, j); + } + #else + p[i + 0] = ETA3_SUB(d, 0); + p[i + 1] = ETA3_SUB(d, 1); + p[i + 2] = ETA3_SUB(d, 2); + p[i + 3] = ETA3_SUB(d, 3); + p[i + 4] = ETA3_SUB(d, 4); + p[i + 5] = ETA3_SUB(d, 5); + p[i + 6] = ETA3_SUB(d, 6); + p[i + 7] = ETA3_SUB(d, 7); + #endif + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 6; + } +#endif +} +#endif + +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Psuedo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @param [in] eta1 Size of noise/error integers. + * @return 0 on success. + */ +static int kyber_get_noise_eta1_c(KYBER_PRF_T* prf, sword16* p, + const byte* seed, byte eta1) +{ + int ret; + + (void)eta1; + +#ifdef WOLFSSL_KYBER512 + if (eta1 == KYBER_CBD_ETA3) { + byte rand[ETA3_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = kyber_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + /* Sample for values in range -3..3 from 3 bits of random. */ + kyber_cbd_eta3(p, rand); + } + } + else +#endif + { + byte rand[ETA2_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = kyber_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + /* Sample for values in range -2..2 from 2 bits of random. */ + kyber_cbd_eta2(p, rand); + } + } + + return ret; +} + +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. Values -2..2 + * + * @param [in, out] prf Psuedo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_eta2_c(KYBER_PRF_T* prf, sword16* p, + const byte* seed) +{ + int ret; + byte rand[ETA2_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = kyber_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + kyber_cbd_eta2(p, rand); + } + + return ret; +} + +#ifdef USE_INTEL_SPEEDUP +#define PRF_RAND_SZ (2 * SHA3_256_BYTES) + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_KYBER1024) +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void kyber_get_noise_x4_eta2_avx2(byte* rand, byte* seed, byte o) +{ + int i; + word64 state[25 * 4]; + + for (i = 0; i < 4; i++) { + state[4*4 + i] = 0x1f00 + i + o; + } + + kyber_sha3_256_blocksx4_seed_avx2(state, seed); + kyber_redistribute_16_rand_avx2(state, rand + 0 * ETA2_RAND_SIZE, + rand + 1 * ETA2_RAND_SIZE, rand + 2 * ETA2_RAND_SIZE, + rand + 3 * ETA2_RAND_SIZE); +} +#endif + +#ifdef WOLFSSL_KYBER512 +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void kyber_get_noise_x4_eta3_avx2(byte* rand, byte* seed) +{ + word64 state[25 * 4]; + int i; + + state[4*4 + 0] = 0x1f00 + 0; + state[4*4 + 1] = 0x1f00 + 1; + state[4*4 + 2] = 0x1f00 + 2; + state[4*4 + 3] = 0x1f00 + 3; + + kyber_sha3_256_blocksx4_seed_avx2(state, seed); + kyber_redistribute_17_rand_avx2(state, rand + 0 * PRF_RAND_SZ, + rand + 1 * PRF_RAND_SZ, rand + 2 * PRF_RAND_SZ, + rand + 3 * PRF_RAND_SZ); + i = SHA3_256_BYTES; + kyber_sha3_blocksx4_avx2(state); + kyber_redistribute_8_rand_avx2(state, rand + i + 0 * PRF_RAND_SZ, + rand + i + 1 * PRF_RAND_SZ, rand + i + 2 * PRF_RAND_SZ, + rand + i + 3 * PRF_RAND_SZ); +} + +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. Values -2..2 + * + * @param [in, out] prf Psuedo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_eta2_avx2(KYBER_PRF_T* prf, sword16* p, + const byte* seed) +{ + int ret; + byte rand[ETA2_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = kyber_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + kyber_cbd_eta2_avx2(p, rand); + } + + return ret; +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Psuedo-random function object. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k2_avx2(KYBER_PRF_T* prf, sword16* vec1, + sword16* vec2, sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[4 * PRF_RAND_SZ]; + + kyber_get_noise_x4_eta3_avx2(rand, seed); + kyber_cbd_eta3_avx2(vec1 , rand + 0 * PRF_RAND_SZ); + kyber_cbd_eta3_avx2(vec1 + KYBER_N, rand + 1 * PRF_RAND_SZ); + if (poly == NULL) { + kyber_cbd_eta3_avx2(vec2 , rand + 2 * PRF_RAND_SZ); + kyber_cbd_eta3_avx2(vec2 + KYBER_N, rand + 3 * PRF_RAND_SZ); + } + else { + kyber_cbd_eta2_avx2(vec2 , rand + 2 * PRF_RAND_SZ); + kyber_cbd_eta2_avx2(vec2 + KYBER_N, rand + 3 * PRF_RAND_SZ); + + seed[KYBER_SYM_SZ] = 4; + ret = kyber_get_noise_eta2_avx2(prf, poly, seed); + } + + return ret; +} +#endif + +#ifdef WOLFSSL_KYBER768 +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k3_avx2(sword16* vec1, sword16* vec2, sword16* poly, + byte* seed) +{ + byte rand[4 * ETA2_RAND_SIZE]; + + kyber_get_noise_x4_eta2_avx2(rand, seed, 0); + kyber_cbd_eta2_avx2(vec1 , rand + 0 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec1 + 1 * KYBER_N, rand + 1 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec1 + 2 * KYBER_N, rand + 2 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec2 , rand + 3 * ETA2_RAND_SIZE); + kyber_get_noise_x4_eta2_avx2(rand, seed, 4); + kyber_cbd_eta2_avx2(vec2 + 1 * KYBER_N, rand + 0 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec2 + 2 * KYBER_N, rand + 1 * ETA2_RAND_SIZE); + if (poly != NULL) { + kyber_cbd_eta2_avx2(poly, rand + 2 * ETA2_RAND_SIZE); + } + + return 0; +} +#endif + +#ifdef WOLFSSL_KYBER1024 +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Psuedo-random function object. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k4_avx2(KYBER_PRF_T* prf, sword16* vec1, + sword16* vec2, sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[4 * ETA2_RAND_SIZE]; + + (void)prf; + + kyber_get_noise_x4_eta2_avx2(rand, seed, 0); + kyber_cbd_eta2_avx2(vec1 , rand + 0 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec1 + 1 * KYBER_N, rand + 1 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec1 + 2 * KYBER_N, rand + 2 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec1 + 3 * KYBER_N, rand + 3 * ETA2_RAND_SIZE); + kyber_get_noise_x4_eta2_avx2(rand, seed, 4); + kyber_cbd_eta2_avx2(vec2 , rand + 0 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec2 + 1 * KYBER_N, rand + 1 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec2 + 2 * KYBER_N, rand + 2 * ETA2_RAND_SIZE); + kyber_cbd_eta2_avx2(vec2 + 3 * KYBER_N, rand + 3 * ETA2_RAND_SIZE); + if (poly != NULL) { + seed[KYBER_SYM_SZ] = 8; + ret = kyber_get_noise_eta2_c(prf, poly, seed); + } + + return ret; +} +#endif +#endif /* USE_INTEL_SPEEDUP */ + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Psuedo-random function object. + * @param [in] kp Number of polynomials in vector. + * @param [out] vec1 First Vector of polynomials. + * @param [in] eta1 Size of noise/error integers with first vector. + * @param [out] vec2 Second Vector of polynomials. + * @param [in] eta2 Size of noise/error integers with second vector. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_c(KYBER_PRF_T* prf, int kp, sword16* vec1, int eta1, + sword16* vec2, int eta2, sword16* poly, byte* seed) +{ + int ret = 0; + int i; + + /* First noise generation has a seed with 0x00 appended. */ + seed[KYBER_SYM_SZ] = 0; + /* Generate noise as private key. */ + for (i = 0; (ret == 0) && (i < kp); i++) { + /* Generate noise for each dimension of vector. */ + ret = kyber_get_noise_eta1_c(prf, vec1 + i * KYBER_N, seed, eta1); + /* Increment value of appended byte. */ + seed[KYBER_SYM_SZ]++; + } + /* Generate noise for error. */ + for (i = 0; (ret == 0) && (i < kp); i++) { + /* Generate noise for each dimension of vector. */ + ret = kyber_get_noise_eta1_c(prf, vec2 + i * KYBER_N, seed, eta2); + /* Increment value of appended byte. */ + seed[KYBER_SYM_SZ]++; + } + if ((ret == 0) && (poly != NULL)) { + /* Generating random error polynomial. */ + ret = kyber_get_noise_eta2_c(prf, poly, seed); + } + + return ret; +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Psuedo-random function object. + * @param [in] kp Number of polynomials in vector. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, + sword16* vec2, sword16* poly, byte* seed) +{ + int ret; + +#ifdef WOLFSSL_KYBER512 + if (kp == KYBER512_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_get_noise_k2_avx2(prf, vec1, vec2, poly, seed); + } + else + #endif + if (poly == NULL) { + ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA3, vec2, + KYBER_CBD_ETA3, NULL, seed); + } + else { + ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA3, vec2, + KYBER_CBD_ETA2, poly, seed); + } + } + else +#endif +#ifdef WOLFSSL_KYBER768 + if (kp == KYBER768_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_get_noise_k3_avx2(vec1, vec2, poly, seed); + } + else + #endif + { + ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA2, vec2, + KYBER_CBD_ETA2, poly, seed); + } + } + else +#endif +#ifdef WOLFSSL_KYBER1024 + if (kp == KYBER1024_K) { + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + ret = kyber_get_noise_k4_avx2(prf, vec1, vec2, poly, seed); + } + else + #endif + { + ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA2, vec2, + KYBER_CBD_ETA2, poly, seed); + } + } + else +#endif + { + ret = BAD_STATE_E; + } + + return ret; +} + +/******************************************************************************/ + +/* Compare two byte arrays of equal size. + * + * @param [in] a First array to compare. + * @param [in] b Second array to compare. + * @param [in] sz Size of arrays in bytes. + * @return 0 on success. + * @return -1 on failure. + */ +static int kyber_cmp_c(const byte* a, const byte* b, int sz) +{ + int i; + byte r = 0; + + /* Constant time comparison of the encapsulated message and cipher text. */ + for (i = 0; i < sz; i++) { + r |= a[i] ^ b[i]; + } + return 0 - ((-(word32)r) >> 31); +} + +/* Compare two byte arrays of equal size. + * + * @param [in] a First array to compare. + * @param [in] b Second array to compare. + * @param [in] sz Size of arrays in bytes. + * @return 0 on success. + * @return -1 on failure. + */ +int kyber_cmp(const byte* a, const byte* b, int sz) +{ + int fail; + +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + fail = kyber_cmp_avx2(a, b, sz); + } + else +#endif + { + fail = kyber_cmp_c(a, b, sz); + } + + return fail; +} + +/******************************************************************************/ + +/* Conditional subtraction of q to each coefficient of a polynomial. + * + * @param [in, out] p Polynomial. + */ +static KYBER_NOINLINE void kyber_csubq_c(sword16* p) +{ + unsigned int i; + + for (i = 0; i < KYBER_N; ++i) { + sword16 t = p[i] - KYBER_Q; + /* When top bit set, -ve number - need to add q back. */ + p[i] = ((t >> 15) & KYBER_Q) + t; + } +} + +/******************************************************************************/ + +#if defined(CONV_WITH_DIV) || !defined(WORD64_AVAILABLE) + +/* Compress value. + * + * Uses div operator that may be slow. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] s Shift amount to apply to value being compressed. + * @param [in] m Mask to apply get the require number of bits. + * @return Compressed value. + */ +#define TO_COMP_WORD_VEC(v, i, j, k, s, m) \ + ((((word32)v[i * KYBER_N + j + k] << s) + KYBER_Q_HALF) / KYBER_Q) & m + +/* Compress value to 10 bits. + * + * Uses mul instead of div. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_10(v, i, j, k) \ + TO_COMP_WORD_VEC(v, i, j, k, 10, 0x3ff) + +/* Compress value to 11 bits. + * + * Uses mul instead of div. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_11(v, i, j, k) \ + TO_COMP_WORD_VEC(v, i, j, k, 11, 0x7ff) + +#else + +/* Multiplier that does div q. + * ((1 << 53) + KYBER_Q_HALF) / KYBER_Q + */ +#define KYBER_V53 0x275f6ed0176UL +/* Multiplier times half of q. + * KYBER_V53 * (KYBER_Q_HALF + 1) + */ +#define KYBER_V53_HALF 0x10013afb768076UL + +/* Multiplier that does div q. + * ((1 << 54) + KYBER_Q_HALF) / KYBER_Q + */ +#define KYBER_V54 0x4ebedda02ecUL +/* Multiplier times half of q. + * KYBER_V54 * (KYBER_Q_HALF + 1) + */ +#define KYBER_V54_HALF 0x200275f6ed00ecUL + +/* Compress value to 10 bits. + * + * Uses mul instead of div. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_10(v, i, j, k) \ + ((((KYBER_V54 << 10) * (v)[(i) * KYBER_N + (j) + (k)]) + KYBER_V54_HALF) >> 54) + +/* Compress value to 11 bits. + * + * Uses mul instead of div. + * Only works for values in range: 0..3228 + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_11(v, i, j, k) \ + ((((KYBER_V53 << 11) * (v)[(i) * KYBER_N + (j) + (k)]) + KYBER_V53_HALF) >> 53) + +#endif /* CONV_WITH_DIV */ + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +/* Compress the vector of polynomials into a byte array with 10 bits each. + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_vec_compress_10_c(byte* r, sword16* v, unsigned int kp) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int k; +#endif + + for (i = 0; i < kp; i++) { + /* Reduce each coefficient to mod q. */ + kyber_csubq_c(v + i * KYBER_N); + /* All values are now positive. */ + } + + /* Each polynomial. */ + for (i = 0; i < kp; i++) { + /* Each 4 polynomial coefficients. */ + for (j = 0; j < KYBER_N; j += 4) { + #ifdef WOLFSSL_KYBER_SMALL + sword16 t[4]; + /* Compress four polynomial values to 10 bits each. */ + for (k = 0; k < 4; k++) { + t[k] = TO_COMP_WORD_10(v, i, j, k); + } + + /* Pack four 10-bit values into byte array. */ + r[ 0] = (t[0] >> 0); + r[ 1] = (t[0] >> 8) | (t[1] << 2); + r[ 2] = (t[1] >> 6) | (t[2] << 4); + r[ 3] = (t[2] >> 4) | (t[3] << 6); + r[ 4] = (t[3] >> 2); + #else + /* Compress four polynomial values to 10 bits each. */ + sword16 t0 = TO_COMP_WORD_10(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_10(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_10(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_10(v, i, j, 3); + + /* Pack four 10-bit values into byte array. */ + r[ 0] = (t0 >> 0); + r[ 1] = (t0 >> 8) | (t1 << 2); + r[ 2] = (t1 >> 6) | (t2 << 4); + r[ 3] = (t2 >> 4) | (t3 << 6); + r[ 4] = (t3 >> 2); + #endif + + /* Move over set bytes. */ + r += 5; + } + } +} + +/* Compress the vector of polynomials into a byte array with 10 bits each. + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_vec_compress_10(byte* r, sword16* v, unsigned int kp) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_compress_10_avx2(r, v, kp); + } + else +#endif + { + kyber_vec_compress_10_c(r, v, kp); + } +} +#endif + +#ifdef WOLFSSL_KYBER1024 +/* Compress the vector of polynomials into a byte array with 11 bits each. + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + */ +static void kyber_vec_compress_11_c(byte* r, sword16* v) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int k; +#endif + + for (i = 0; i < 4; i++) { + /* Reduce each coefficient to mod q. */ + kyber_csubq_c(v + i * KYBER_N); + /* All values are now positive. */ + } + + /* Each polynomial. */ + for (i = 0; i < 4; i++) { + /* Each 8 polynomial coefficients. */ + for (j = 0; j < KYBER_N; j += 8) { + #ifdef WOLFSSL_KYBER_SMALL + sword16 t[8]; + /* Compress eight polynomial values to 11 bits each. */ + for (k = 0; k < 8; k++) { + t[k] = TO_COMP_WORD_11(v, i, j, k); + } + + /* Pack eight 11-bit values into byte array. */ + r[ 0] = (t[0] >> 0); + r[ 1] = (t[0] >> 8) | (t[1] << 3); + r[ 2] = (t[1] >> 5) | (t[2] << 6); + r[ 3] = (t[2] >> 2); + r[ 4] = (t[2] >> 10) | (t[3] << 1); + r[ 5] = (t[3] >> 7) | (t[4] << 4); + r[ 6] = (t[4] >> 4) | (t[5] << 7); + r[ 7] = (t[5] >> 1); + r[ 8] = (t[5] >> 9) | (t[6] << 2); + r[ 9] = (t[6] >> 6) | (t[7] << 5); + r[10] = (t[7] >> 3); + #else + /* Compress eight polynomial values to 11 bits each. */ + sword16 t0 = TO_COMP_WORD_11(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_11(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_11(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_11(v, i, j, 3); + sword16 t4 = TO_COMP_WORD_11(v, i, j, 4); + sword16 t5 = TO_COMP_WORD_11(v, i, j, 5); + sword16 t6 = TO_COMP_WORD_11(v, i, j, 6); + sword16 t7 = TO_COMP_WORD_11(v, i, j, 7); + + /* Pack eight 11-bit values into byte array. */ + r[ 0] = (t0 >> 0); + r[ 1] = (t0 >> 8) | (t1 << 3); + r[ 2] = (t1 >> 5) | (t2 << 6); + r[ 3] = (t2 >> 2); + r[ 4] = (t2 >> 10) | (t3 << 1); + r[ 5] = (t3 >> 7) | (t4 << 4); + r[ 6] = (t4 >> 4) | (t5 << 7); + r[ 7] = (t5 >> 1); + r[ 8] = (t5 >> 9) | (t6 << 2); + r[ 9] = (t6 >> 6) | (t7 << 5); + r[10] = (t7 >> 3); + #endif + + /* Move over set bytes. */ + r += 11; + } + } +} + +/* Compress the vector of polynomials into a byte array with 11 bits each. + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + */ +void kyber_vec_compress_11(byte* r, sword16* v) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_compress_11_avx2(r, v, 4); + } + else +#endif + { + kyber_vec_compress_11_c(r, v); + } +} +#endif + +/* Decompress a 10 bit value. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_10(v, i, j, k, t) \ + v[(i) * KYBER_N + 4 * (j) + (k)] = \ + (word16)((((word32)((t) & 0x3ff) * KYBER_Q) + 512) >> 10) + +/* Decompress an 11 bit value. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_11(v, i, j, k, t) \ + v[(i) * KYBER_N + 8 * (j) + (k)] = \ + (word16)((((word32)((t) & 0x7ff) * KYBER_Q) + 1024) >> 11) + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +/* Decompress the byte array of packed 10 bits into vector of polynomials. + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] kp Number of polynomials in vector. + */ +static void kyber_vec_decompress_10_c(sword16* v, const unsigned char* b, + unsigned int kp) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int k; +#endif + + /* Each polynomial. */ + for (i = 0; i < kp; i++) { + /* Each 4 polynomial coefficients. */ + for (j = 0; j < KYBER_N / 4; j++) { + #ifdef WOLFSSL_KYBER_SMALL + word16 t[4]; + /* Extract out 4 values of 10 bits each. */ + t[0] = (b[0] >> 0) | ((word16)b[ 1] << 8); + t[1] = (b[1] >> 2) | ((word16)b[ 2] << 6); + t[2] = (b[2] >> 4) | ((word16)b[ 3] << 4); + t[3] = (b[3] >> 6) | ((word16)b[ 4] << 2); + b += 5; + + /* Decompress 4 values. */ + for (k = 0; k < 4; k++) { + DECOMP_10(v, i, j, k, t[k]); + } + #else + /* Extract out 4 values of 10 bits each. */ + sword16 t0 = (b[0] >> 0) | ((word16)b[ 1] << 8); + sword16 t1 = (b[1] >> 2) | ((word16)b[ 2] << 6); + sword16 t2 = (b[2] >> 4) | ((word16)b[ 3] << 4); + sword16 t3 = (b[3] >> 6) | ((word16)b[ 4] << 2); + b += 5; + + /* Decompress 4 values. */ + DECOMP_10(v, i, j, 0, t0); + DECOMP_10(v, i, j, 1, t1); + DECOMP_10(v, i, j, 2, t2); + DECOMP_10(v, i, j, 3, t3); + #endif + } + } +} + +/* Decompress the byte array of packed 10 bits into vector of polynomials. + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_vec_decompress_10(sword16* v, const unsigned char* b, + unsigned int kp) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_decompress_10_avx2(v, b, kp); + } + else +#endif + { + kyber_vec_decompress_10_c(v, b, kp); + } +} +#endif +#ifdef WOLFSSL_KYBER1024 +/* Decompress the byte array of packed 11 bits into vector of polynomials. + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + */ +static void kyber_vec_decompress_11_c(sword16* v, const unsigned char* b) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int k; +#endif + + /* Each polynomial. */ + for (i = 0; i < 4; i++) { + /* Each 8 polynomial coefficients. */ + for (j = 0; j < KYBER_N / 8; j++) { + #ifdef WOLFSSL_KYBER_SMALL + word16 t[8]; + /* Extract out 8 values of 11 bits each. */ + t[0] = (b[0] >> 0) | ((word16)b[ 1] << 8); + t[1] = (b[1] >> 3) | ((word16)b[ 2] << 5); + t[2] = (b[2] >> 6) | ((word16)b[ 3] << 2) | + ((word16)b[4] << 10); + t[3] = (b[4] >> 1) | ((word16)b[ 5] << 7); + t[4] = (b[5] >> 4) | ((word16)b[ 6] << 4); + t[5] = (b[6] >> 7) | ((word16)b[ 7] << 1) | + ((word16)b[8] << 9); + t[6] = (b[8] >> 2) | ((word16)b[ 9] << 6); + t[7] = (b[9] >> 5) | ((word16)b[10] << 3); + b += 11; + + /* Decompress 8 values. */ + for (k = 0; k < 8; k++) { + DECOMP_11(v, i, j, k, t[k]); + } + #else + /* Extract out 8 values of 11 bits each. */ + sword16 t0 = (b[0] >> 0) | ((word16)b[ 1] << 8); + sword16 t1 = (b[1] >> 3) | ((word16)b[ 2] << 5); + sword16 t2 = (b[2] >> 6) | ((word16)b[ 3] << 2) | + ((word16)b[4] << 10); + sword16 t3 = (b[4] >> 1) | ((word16)b[ 5] << 7); + sword16 t4 = (b[5] >> 4) | ((word16)b[ 6] << 4); + sword16 t5 = (b[6] >> 7) | ((word16)b[ 7] << 1) | + ((word16)b[8] << 9); + sword16 t6 = (b[8] >> 2) | ((word16)b[ 9] << 6); + sword16 t7 = (b[9] >> 5) | ((word16)b[10] << 3); + b += 11; + + /* Decompress 8 values. */ + DECOMP_11(v, i, j, 0, t0); + DECOMP_11(v, i, j, 1, t1); + DECOMP_11(v, i, j, 2, t2); + DECOMP_11(v, i, j, 3, t3); + DECOMP_11(v, i, j, 4, t4); + DECOMP_11(v, i, j, 5, t5); + DECOMP_11(v, i, j, 6, t6); + DECOMP_11(v, i, j, 7, t7); + #endif + } + } +} + +/* Decompress the byte array of packed 11 bits into vector of polynomials. + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + */ +void kyber_vec_decompress_11(sword16* v, const unsigned char* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_decompress_11_avx2(v, b, 4); + } + else +#endif + { + kyber_vec_decompress_11_c(v, b); + } +} +#endif + +#ifdef CONV_WITH_DIV + +/* Compress value. + * + * Uses div operator that may be slow. + * + * @param [in] v Vector of polynomials. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] s Shift amount to apply to value being compressed. + * @param [in] m Mask to apply get the require number of bits. + * @return Compressed value. + */ +#define TO_COMP_WORD(v, i, j, s, m) \ + ((((word32)v[i + j] << s) + KYBER_Q_HALF) / KYBER_Q) & m + +/* Compress value to 4 bits. + * + * Uses mul instead of div. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_4(p, i, j) \ + TO_COMP_WORD(p, i, j, 4, 0xf) + +/* Compress value to 5 bits. + * + * Uses mul instead of div. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_5(p, i, j) \ + TO_COMP_WORD(p, i, j, 5, 0x1f) + +#else + +/* Multiplier that does div q. */ +#define KYBER_V28 ((word32)(((1U << 28) + KYBER_Q_HALF)) / KYBER_Q) +/* Multiplier times half of q. */ +#define KYBER_V28_HALF ((word32)(KYBER_V28 * (KYBER_Q_HALF + 1))) + +/* Multiplier that does div q. */ +#define KYBER_V27 ((word32)(((1U << 27) + KYBER_Q_HALF)) / KYBER_Q) +/* Multiplier times half of q. */ +#define KYBER_V27_HALF ((word32)(KYBER_V27 * KYBER_Q_HALF)) + +/* Compress value to 4 bits. + * + * Uses mul instead of div. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_4(p, i, j) \ + ((((KYBER_V28 << 4) * (p)[(i) + (j)]) + KYBER_V28_HALF) >> 28) + +/* Compress value to 5 bits. + * + * Uses mul instead of div. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_5(p, i, j) \ + ((((KYBER_V27 << 5) * (p)[(i) + (j)]) + KYBER_V27_HALF) >> 27) + +#endif /* CONV_WITH_DIV */ + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +/* Compress a polynomial into byte array - on coefficients into 4 bits. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +static void kyber_compress_4_c(byte* b, sword16* p) +{ + unsigned int i; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + byte t[8]; +#endif + + /* Reduce each coefficients to mod q. */ + kyber_csubq_c(p); + /* All values are now positive. */ + + /* Each 8 polynomial coefficients. */ + for (i = 0; i < KYBER_N; i += 8) { + #ifdef WOLFSSL_KYBER_SMALL + /* Compress eight polynomial values to 4 bits each. */ + for (j = 0; j < 8; j++) { + t[j] = TO_COMP_WORD_4(p, i, j); + } + + b[0] = t[0] | (t[1] << 4); + b[1] = t[2] | (t[3] << 4); + b[2] = t[4] | (t[5] << 4); + b[3] = t[6] | (t[7] << 4); + #else + /* Compress eight polynomial values to 4 bits each. */ + byte t0 = TO_COMP_WORD_4(p, i, 0); + byte t1 = TO_COMP_WORD_4(p, i, 1); + byte t2 = TO_COMP_WORD_4(p, i, 2); + byte t3 = TO_COMP_WORD_4(p, i, 3); + byte t4 = TO_COMP_WORD_4(p, i, 4); + byte t5 = TO_COMP_WORD_4(p, i, 5); + byte t6 = TO_COMP_WORD_4(p, i, 6); + byte t7 = TO_COMP_WORD_4(p, i, 7); + + /* Pack eight 4-bit values into byte array. */ + b[0] = t0 | (t1 << 4); + b[1] = t2 | (t3 << 4); + b[2] = t4 | (t5 << 4); + b[3] = t6 | (t7 << 4); + #endif + + /* Move over set bytes. */ + b += 4; + } +} + +/* Compress a polynomial into byte array - on coefficients into 4 bits. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +void kyber_compress_4(byte* b, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_compress_4_avx2(b, p); + } + else +#endif + { + kyber_compress_4_c(b, p); + } +} +#endif +#ifdef WOLFSSL_KYBER1024 +/* Compress a polynomial into byte array - on coefficients into 5 bits. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +static void kyber_compress_5_c(byte* b, sword16* p) +{ + unsigned int i; +#ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + byte t[8]; +#endif + + /* Reduce each coefficients to mod q. */ + kyber_csubq_c(p); + /* All values are now positive. */ + + for (i = 0; i < KYBER_N; i += 8) { + #ifdef WOLFSSL_KYBER_SMALL + /* Compress eight polynomial values to 5 bits each. */ + for (j = 0; j < 8; j++) { + t[j] = TO_COMP_WORD_5(p, i, j); + } + + /* Pack 5 bits into byte array. */ + b[0] = (t[0] >> 0) | (t[1] << 5); + b[1] = (t[1] >> 3) | (t[2] << 2) | (t[3] << 7); + b[2] = (t[3] >> 1) | (t[4] << 4); + b[3] = (t[4] >> 4) | (t[5] << 1) | (t[6] << 6); + b[4] = (t[6] >> 2) | (t[7] << 3); + #else + /* Compress eight polynomial values to 5 bits each. */ + byte t0 = TO_COMP_WORD_5(p, i, 0); + byte t1 = TO_COMP_WORD_5(p, i, 1); + byte t2 = TO_COMP_WORD_5(p, i, 2); + byte t3 = TO_COMP_WORD_5(p, i, 3); + byte t4 = TO_COMP_WORD_5(p, i, 4); + byte t5 = TO_COMP_WORD_5(p, i, 5); + byte t6 = TO_COMP_WORD_5(p, i, 6); + byte t7 = TO_COMP_WORD_5(p, i, 7); + + /* Pack eight 5-bit values into byte array. */ + b[0] = (t0 >> 0) | (t1 << 5); + b[1] = (t1 >> 3) | (t2 << 2) | (t3 << 7); + b[2] = (t3 >> 1) | (t4 << 4); + b[3] = (t4 >> 4) | (t5 << 1) | (t6 << 6); + b[4] = (t6 >> 2) | (t7 << 3); + #endif + + /* Move over set bytes. */ + b += 5; + } +} + +/* Compress a polynomial into byte array - on coefficients into 5 bits. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +void kyber_compress_5(byte* b, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_compress_5_avx2(b, p); + } + else +#endif + { + kyber_compress_5_c(b, p); + } +} +#endif + +/* Decompress a 4 bit value. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_4(p, i, j, t) \ + p[(i) + (j)] = ((word16)((t) * KYBER_Q) + 8) >> 4 + +/* Decompress a 5 bit value. + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_5(p, i, j, t) \ + p[(i) + (j)] = (((word32)((t) & 0x1f) * KYBER_Q) + 16) >> 5 + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +/* Decompress the byte array of packed 4 bits into polynomial. + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +static void kyber_decompress_4_c(sword16* p, const unsigned char* b) +{ + unsigned int i; + + /* 2 coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 2) { + /* 2 coefficients decompressed from one byte. */ + DECOMP_4(p, i, 0, b[0] & 0xf); + DECOMP_4(p, i, 1, b[0] >> 4); + b += 1; + } +} + +/* Decompress the byte array of packed 4 bits into polynomial. + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +void kyber_decompress_4(sword16* p, const unsigned char* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_decompress_4_avx2(p, b); + } + else +#endif + { + kyber_decompress_4_c(p, b); + } +} +#endif +#ifdef WOLFSSL_KYBER1024 +/* Decompress the byte array of packed 5 bits into polynomial. + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +static void kyber_decompress_5_c(sword16* p, const unsigned char* b) +{ + unsigned int i; + + /* Each 8 polynomial coefficients. */ + for (i = 0; i < KYBER_N; i += 8) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + byte t[8]; + + /* Extract out 8 values of 5 bits each. */ + t[0] = (b[0] >> 0); + t[1] = (b[0] >> 5) | (b[1] << 3); + t[2] = (b[1] >> 2); + t[3] = (b[1] >> 7) | (b[2] << 1); + t[4] = (b[2] >> 4) | (b[3] << 4); + t[5] = (b[3] >> 1); + t[6] = (b[3] >> 6) | (b[4] << 2); + t[7] = (b[4] >> 3); + b += 5; -#ifdef WOLFSSL_HAVE_KYBER - #error "Contact wolfSSL to get the implementation of this file" + /* Decompress 8 values. */ + for (j = 0; j < 8; j++) { + DECOMP_5(p, i, j, t[j]); + } + #else + /* Extract out 8 values of 5 bits each. */ + byte t0 = (b[0] >> 0); + byte t1 = (b[0] >> 5) | (b[1] << 3); + byte t2 = (b[1] >> 2); + byte t3 = (b[1] >> 7) | (b[2] << 1); + byte t4 = (b[2] >> 4) | (b[3] << 4); + byte t5 = (b[3] >> 1); + byte t6 = (b[3] >> 6) | (b[4] << 2); + byte t7 = (b[4] >> 3); + b += 5; + + /* Decompress 8 values. */ + DECOMP_5(p, i, 0, t0); + DECOMP_5(p, i, 1, t1); + DECOMP_5(p, i, 2, t2); + DECOMP_5(p, i, 3, t3); + DECOMP_5(p, i, 4, t4); + DECOMP_5(p, i, 5, t5); + DECOMP_5(p, i, 6, t6); + DECOMP_5(p, i, 7, t7); + #endif + } +} + +/* Decompress the byte array of packed 5 bits into polynomial. + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +void kyber_decompress_5(sword16* p, const unsigned char* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_decompress_5_avx2(p, b); + } + else +#endif + { + kyber_decompress_5_c(p, b); + } +} +#endif + +/******************************************************************************/ + +/* Convert bit from byte to 0 or (KYBER_Q + 1) / 2. + * + * Constant time implementation. + * + * @param [out] p Polynomial to hold converted value. + * @param [in] msg Message to get bit from byte from. + * @param [in] i Index of byte from message. + * @param [in] j Index of bit in byte. + */ +#define FROM_MSG_BIT(p, msg, i, j) \ + p[8 * (i) + (j)] = ((sword16)0 - (sword16)(((msg)[i] >> (j)) & 1)) & KYBER_Q_1_HALF + +/* Convert message to polynomial. + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +static void kyber_from_msg_c(sword16* p, const byte* msg) +{ + unsigned int i; + + /* For each byte of the message. */ + for (i = 0; i < KYBER_N / 8; i++) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + /* For each bit of the message. */ + for (j = 0; j < 8; j++) { + FROM_MSG_BIT(p, msg, i, j); + } + #else + FROM_MSG_BIT(p, msg, i, 0); + FROM_MSG_BIT(p, msg, i, 1); + FROM_MSG_BIT(p, msg, i, 2); + FROM_MSG_BIT(p, msg, i, 3); + FROM_MSG_BIT(p, msg, i, 4); + FROM_MSG_BIT(p, msg, i, 5); + FROM_MSG_BIT(p, msg, i, 6); + FROM_MSG_BIT(p, msg, i, 7); + #endif + } +} + +/* Convert message to polynomial. + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +void kyber_from_msg(sword16* p, const byte* msg) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + kyber_from_msg_avx2(p, msg); + } + else +#endif + { + kyber_from_msg_c(p, msg); + } +} + +#ifdef CONV_WITH_DIV + +/* Convert to value to bit. + * + * Uses div operator that may be slow. + * + * @param [out] m Message. + * @param [in] p Polynomial. + * @param [in] i Index of byte in message. + * @param [in] j Index of bit in byte. + */ +#define TO_MSG_BIT(m, p, i, j) \ + m[i] |= (((((sword16)p[8 * i + j] << 1) + KYBER_Q_HALF) / KYBER_Q) & 1) << j + +#else + +/* Multiplier that does div q. */ +#define KYBER_V31 (((1U << 31) + (KYBER_Q / 2)) / KYBER_Q) +/* 2 * multiplier that does div q. Only need bit 32 of result. */ +#define KYBER_V31_2 ((word32)(KYBER_V31 * 2)) +/* Multiplier times half of q. */ +#define KYBER_V31_HALF ((word32)(KYBER_V31 * KYBER_Q_HALF)) + +/* Convert to value to bit. + * + * Uses mul instead of div. + * + * @param [out] m Message. + * @param [in] p Polynomial. + * @param [in] i Index of byte in message. + * @param [in] j Index of bit in byte. + */ +#define TO_MSG_BIT(m, p, i, j) \ + (m)[i] |= ((word32)((KYBER_V31_2 * (p)[8 * (i) + (j)]) + KYBER_V31_HALF) >> 31) << (j) + +#endif /* CONV_WITH_DIV */ + +/* Convert polynomial to message. + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +static void kyber_to_msg_c(byte* msg, sword16* p) +{ + unsigned int i; + + /* Reduce each coefficient to mod q. */ + kyber_csubq_c(p); + /* All values are now positive. */ + + for (i = 0; i < KYBER_N / 8; i++) { + #ifdef WOLFSSL_KYBER_SMALL + unsigned int j; + msg[i] = 0; + for (j = 0; j < 8; j++) { + TO_MSG_BIT(msg, p, i, j); + } + #else + msg[i] = 0; + TO_MSG_BIT(msg, p, i, 0); + TO_MSG_BIT(msg, p, i, 1); + TO_MSG_BIT(msg, p, i, 2); + TO_MSG_BIT(msg, p, i, 3); + TO_MSG_BIT(msg, p, i, 4); + TO_MSG_BIT(msg, p, i, 5); + TO_MSG_BIT(msg, p, i, 6); + TO_MSG_BIT(msg, p, i, 7); + #endif + } +} + +/* Convert polynomial to message. + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +void kyber_to_msg(byte* msg, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + /* Convert the polynomial into a array of bytes (message). */ + kyber_to_msg_avx2(msg, p); + } + else +#endif + { + kyber_to_msg_c(msg, p); + } +} + +/******************************************************************************/ + +/* Convert bytes to polynomial. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in decoding private and public keys. + * + * @param [out] p Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +static void kyber_from_bytes_c(sword16* p, const byte* b, int k) +{ + int i; + int j; + + for (j = 0; j < k; j++) { + for (i = 0; i < KYBER_N / 2; i++) { + p[2 * i + 0] = ((b[3 * i + 0] >> 0) | + ((word16)b[3 * i + 1] << 8)) & 0xfff; + p[2 * i + 1] = ((b[3 * i + 1] >> 4) | + ((word16)b[3 * i + 2] << 4)) & 0xfff; + } + p += KYBER_N; + b += KYBER_POLY_SIZE; + } +} + +/* Convert bytes to polynomial. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in decoding private and public keys. + * + * @param [out] p Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +void kyber_from_bytes(sword16* p, const byte* b, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + int i; + + for (i = 0; i < k; i++) { + kyber_from_bytes_avx2(p, b); + p += KYBER_N; + b += KYBER_POLY_SIZE; + } + } + else +#endif + { + kyber_from_bytes_c(p, b, k); + } +} + +/* Convert polynomial to bytes. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in encoding private and public keys. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + * @param [in] k Number of polynomials in vector. + */ +static void kyber_to_bytes_c(byte* b, sword16* p, int k) +{ + int i; + int j; + + /* Reduce each coefficient to mod q. */ + kyber_csubq_c(p); + /* All values are now positive. */ + + for (j = 0; j < k; j++) { + for (i = 0; i < KYBER_N / 2; i++) { + word16 t0 = p[2 * i]; + word16 t1 = p[2 * i + 1]; + b[3 * i + 0] = (t0 >> 0); + b[3 * i + 1] = (t0 >> 8) | t1 << 4; + b[3 * i + 2] = (t1 >> 4); + } + p += KYBER_N; + b += KYBER_POLY_SIZE; + } +} + +/* Convert polynomial to bytes. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in encoding private and public keys. + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + * @param [in] k Number of polynomials in vector. + */ +void kyber_to_bytes(byte* b, sword16* p, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags)) { + int i; + + for (i = 0; i < k; i++) { + kyber_to_bytes_avx2(b, p); + p += KYBER_N; + b += KYBER_POLY_SIZE; + } + } + else #endif + { + kyber_to_bytes_c(b, p, k); + } +} + +#endif /* WOLFSSL_WC_KYBER */ diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index 60e8519..cdc732f 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -1,6 +1,6 @@ /* wc_lms.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c new file mode 100644 index 0000000..dbd5ed6 --- /dev/null +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -0,0 +1,26 @@ +/* wc_lms_impl.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + +#ifdef WOLFSSL_HAVE_LMS + #error "Contact wolfSSL to get the implementation of this file" +#endif diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index 8b65d0a..258cb03 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -1850,7 +1850,8 @@ enum Misc { (MIN_FFHDE_GROUP <= (group) && (group) <= MAX_FFHDE_GROUP) #ifdef HAVE_PQC #define WOLFSSL_NAMED_GROUP_IS_PQC(group) \ - (WOLFSSL_PQC_MIN <= (group) && (group) <= WOLFSSL_PQC_MAX) + ((WOLFSSL_PQC_SIMPLE_MIN <= (group) && (group) <= WOLFSSL_PQC_SIMPLE_MAX) || \ + (WOLFSSL_PQC_HYBRID_MIN <= (group) && (group) <= WOLFSSL_PQC_HYBRID_MAX)) #else #define WOLFSSL_NAMED_GROUP_IS_PQC(group) ((void)(group), 0) #endif /* HAVE_PQC */ diff --git a/src/wolfssl/quic.h b/src/wolfssl/quic.h index 8e173a0..d415242 100644 --- a/src/wolfssl/quic.h +++ b/src/wolfssl/quic.h @@ -290,6 +290,15 @@ int wolfSSL_quic_hkdf(uint8_t* dest, size_t destlen, const uint8_t* salt, size_t saltlen, const uint8_t* info, size_t infolen); +/* most common QUIC packet size as of 2022 was 1,200 bytes + * largest packet size listed in the RFC is 1,392 bytes + * this gives plenty of breathing room for capacity of records but keeps sizes + * read from the wire sane */ +#ifndef WOLFSSL_QUIC_MAX_RECORD_CAPACITY + /* 1024*1024 -- 1 MB */ + #define WOLFSSL_QUIC_MAX_RECORD_CAPACITY (1048576) +#endif + #endif /* WOLFSSL_QUIC */ #ifdef __cplusplus diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index edcff46..804ec44 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -4004,7 +4004,7 @@ enum { WOLFSSL_KYBER_LEVEL5 = 573, /* KYBER_1024 */ WOLFSSL_PQC_SIMPLE_MAX = 573, - WOLFSSL_PQC_HYBRID_MIN = 12052, + WOLFSSL_PQC_HYBRID_MIN = 12090, WOLFSSL_P256_KYBER_LEVEL1 = 12090, WOLFSSL_P384_KYBER_LEVEL3 = 12092, WOLFSSL_P521_KYBER_LEVEL5 = 12093, diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index 52ec492..47abb74 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -289,6 +289,14 @@ #endif #endif + +#if defined(DEBUG_PK_CB) || defined(TEST_PK_PRIVKEY) || defined(TEST_PK_PSK) + #define WOLFSSL_PKMSG(...) printf(__VA_ARGS__) +#else + #define WOLFSSL_PKMSG(...) WC_DO_NOTHING +#endif + + #ifndef MY_EX_USAGE #define MY_EX_USAGE 2 #endif @@ -1807,7 +1815,6 @@ static WC_INLINE void tcp_set_blocking(SOCKET_T* sockfd) #endif } - #ifndef NO_PSK /* identity is OpenSSL testing default for openssl s_client, keep same */ @@ -1817,6 +1824,8 @@ static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, char* identity, unsigned int id_max_len, unsigned char* key, unsigned int key_max_len) { + unsigned int ret; + (void)ssl; (void)hint; (void)key_max_len; @@ -1826,13 +1835,13 @@ static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) { /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using - unsigned binary */ + * unsigned binary */ key[0] = 0x1a; key[1] = 0x2b; key[2] = 0x3c; key[3] = 0x4d; - return 4; /* length of key in octets or 0 for error */ + ret = 4; /* length of key in octets or 0 for error */ } else { int i; @@ -1844,14 +1853,23 @@ static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, key[i] = b; } - return 32; /* length of key in octets or 0 for error */ + ret = 32; /* length of key in octets or 0 for error */ } + +#if defined(HAVE_PK_CALLBACKS) && defined(TEST_PK_PSK) + WOLFSSL_PKMSG("PSK Client using HW (Len %d, Hint %s)\n", ret, hint); + ret = (unsigned int)USE_HW_PSK; +#endif + + return ret; } static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity, unsigned char* key, unsigned int key_max_len) { + unsigned int ret; + (void)ssl; (void)key_max_len; @@ -1861,13 +1879,13 @@ static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identit if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) { /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using - unsigned binary */ + * unsigned binary */ key[0] = 0x1a; key[1] = 0x2b; key[2] = 0x3c; key[3] = 0x4d; - return 4; /* length of key in octets or 0 for error */ + ret = 4; /* length of key in octets or 0 for error */ } else { int i; @@ -1879,8 +1897,14 @@ static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identit key[i] = b; } - return 32; /* length of key in octets or 0 for error */ + ret = 32; /* length of key in octets or 0 for error */ } +#if defined(HAVE_PK_CALLBACKS) && defined(TEST_PK_PSK) + WOLFSSL_PKMSG("PSK Server using HW (Len %d, Hint %s)\n", ret, identity); + ret = (unsigned int)USE_HW_PSK; +#endif + + return ret; } #ifdef WOLFSSL_TLS13 @@ -1888,6 +1912,7 @@ static WC_INLINE unsigned int my_psk_client_tls13_cb(WOLFSSL* ssl, const char* hint, char* identity, unsigned int id_max_len, unsigned char* key, unsigned int key_max_len, const char** ciphersuite) { + unsigned int ret; int i; int b = 0x01; const char* userCipher = (const char*)wolfSSL_get_psk_callback_ctx(ssl); @@ -1907,7 +1932,14 @@ static WC_INLINE unsigned int my_psk_client_tls13_cb(WOLFSSL* ssl, *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; - return 32; /* length of key in octets or 0 for error */ + ret = 32; /* length of key in octets or 0 for error */ + +#if defined(HAVE_PK_CALLBACKS) && defined(TEST_PK_PSK) + WOLFSSL_PKMSG("PSK Client TLS 1.3 using HW (Len %d, Hint %s)\n", ret, hint); + ret = (unsigned int)USE_HW_PSK; +#endif + + return ret; } @@ -1915,6 +1947,7 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, const char* identity, unsigned char* key, unsigned int key_max_len, const char** ciphersuite) { + unsigned int ret; int i; int b = 0x01; int kIdLen = (int)XSTRLEN(kIdentityStr); @@ -1938,7 +1971,15 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; - return 32; /* length of key in octets or 0 for error */ + ret = 32; /* length of key in octets or 0 for error */ + +#if defined(HAVE_PK_CALLBACKS) && defined(TEST_PK_PSK) + WOLFSSL_PKMSG("PSK Server TLS 1.3 using HW (Len %d, Hint %s)\n", + ret, identity); + ret = (unsigned int)USE_HW_PSK; +#endif + + return ret; } #endif @@ -2500,37 +2541,42 @@ static WC_INLINE void CRL_CallBack(const char* url) #endif #ifndef NO_DH -static WC_INLINE void SetDH(WOLFSSL* ssl) -{ - /* dh1024 p */ - static const unsigned char p[] = +#if defined(WOLFSSL_SP_MATH) && !defined(WOLFSS_SP_MATH_ALL) + /* dh2048 p */ + static const unsigned char test_dh_p[] = { - 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3, - 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E, - 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59, - 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2, - 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD, - 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF, - 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02, - 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C, - 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7, - 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50, - 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B, + 0xD3, 0xB2, 0x99, 0x84, 0x5C, 0x0A, 0x4C, 0xE7, 0x37, 0xCC, 0xFC, 0x18, + 0x37, 0x01, 0x2F, 0x5D, 0xC1, 0x4C, 0xF4, 0x5C, 0xC9, 0x82, 0x8D, 0xB7, + 0xF3, 0xD4, 0xA9, 0x8A, 0x9D, 0x34, 0xD7, 0x76, 0x57, 0xE5, 0xE5, 0xC3, + 0xE5, 0x16, 0x85, 0xCA, 0x4D, 0xD6, 0x5B, 0xC1, 0xF8, 0xCF, 0x89, 0x26, + 0xD0, 0x38, 0x8A, 0xEE, 0xF3, 0xCD, 0x33, 0xE5, 0x56, 0xBB, 0x90, 0x83, + 0x9F, 0x97, 0x8E, 0x71, 0xFB, 0x27, 0xE4, 0x35, 0x15, 0x45, 0x86, 0x09, + 0x71, 0xA8, 0x9A, 0xB9, 0x3E, 0x0F, 0x51, 0x8A, 0xC2, 0x75, 0x51, 0x23, + 0x12, 0xFB, 0x94, 0x31, 0x44, 0xBF, 0xCE, 0xF6, 0xED, 0xA6, 0x3A, 0xB7, + 0x92, 0xCE, 0x16, 0xA9, 0x14, 0xB3, 0x88, 0xB7, 0x13, 0x81, 0x71, 0x83, + 0x88, 0xCD, 0xB1, 0xA2, 0x37, 0xE1, 0x59, 0x5C, 0xD0, 0xDC, 0xCA, 0x82, + 0x87, 0xFA, 0x43, 0x44, 0xDD, 0x78, 0x3F, 0xCA, 0x27, 0x7E, 0xE1, 0x6B, + 0x93, 0x19, 0x7C, 0xD9, 0xA6, 0x96, 0x47, 0x0D, 0x12, 0xC1, 0x13, 0xD7, + 0xB9, 0x0A, 0x40, 0xD9, 0x1F, 0xFF, 0xB8, 0xB4, 0x00, 0xC8, 0xAA, 0x5E, + 0xD2, 0x66, 0x4A, 0x05, 0x8E, 0x9E, 0xF5, 0x34, 0xE7, 0xD7, 0x09, 0x7B, + 0x15, 0x49, 0x1D, 0x76, 0x31, 0xD6, 0x71, 0xEC, 0x13, 0x4E, 0x89, 0x8C, + 0x09, 0x22, 0xD8, 0xE7, 0xA3, 0xE9, 0x7D, 0x21, 0x51, 0x26, 0x6E, 0x9F, + 0x30, 0x8A, 0xBB, 0xBC, 0x74, 0xC1, 0xC3, 0x27, 0x6A, 0xCE, 0xA3, 0x12, + 0x60, 0x68, 0x01, 0xD2, 0x34, 0x07, 0x80, 0xCC, 0x2D, 0x7F, 0x5C, 0xAE, + 0xA2, 0x97, 0x40, 0xC8, 0x3C, 0xAC, 0xDB, 0x6F, 0xFE, 0x6C, 0x6D, 0xD2, + 0x06, 0x1C, 0x43, 0xA2, 0xB2, 0x2B, 0x82, 0xB7, 0xD0, 0xAB, 0x3F, 0x2C, + 0xE7, 0x9C, 0x19, 0x16, 0xD1, 0x5E, 0x26, 0x86, 0xC7, 0x92, 0xF9, 0x16, + 0x0B, 0xFA, 0x66, 0x83 }; - /* dh1024 g */ - static const unsigned char g[] = + /* dh2048 g */ + static const unsigned char test_dh_g[] = { 0x02, }; - - wolfSSL_SetTmpDH(ssl, p, sizeof(p), g, sizeof(g)); -} - -static WC_INLINE void SetDHCtx(WOLFSSL_CTX* ctx) -{ +#else /* dh1024 p */ - static const unsigned char p[] = + static const unsigned char test_dh_p[] = { 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3, 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E, @@ -2546,12 +2592,22 @@ static WC_INLINE void SetDHCtx(WOLFSSL_CTX* ctx) }; /* dh1024 g */ - static const unsigned char g[] = + static const unsigned char test_dh_g[] = { 0x02, }; +#endif - wolfSSL_CTX_SetTmpDH(ctx, p, sizeof(p), g, sizeof(g)); +static WC_INLINE void SetDH(WOLFSSL* ssl) +{ + wolfSSL_SetTmpDH(ssl, test_dh_p, sizeof(test_dh_p), test_dh_g, + sizeof(test_dh_g)); +} + +static WC_INLINE void SetDHCtx(WOLFSSL_CTX* ctx) +{ + wolfSSL_CTX_SetTmpDH(ctx, test_dh_p, sizeof(test_dh_p), test_dh_g, + sizeof(test_dh_g)); } #endif /* NO_DH */ @@ -3086,12 +3142,6 @@ typedef struct PkCbInfo { #endif } PkCbInfo; -#if defined(DEBUG_PK_CB) || defined(TEST_PK_PRIVKEY) - #define WOLFSSL_PKMSG(...) printf(__VA_ARGS__) -#else - #define WOLFSSL_PKMSG(...) WC_DO_NOTHING -#endif - #ifdef HAVE_ECC static WC_INLINE int myEccKeyGen(WOLFSSL* ssl, ecc_key* key, word32 keySz, diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index c0cad15..d6193c4 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.6.6" -#define LIBWOLFSSL_VERSION_HEX 0x05006006 +#define LIBWOLFSSL_VERSION_STRING "5.7.0" +#define LIBWOLFSSL_VERSION_HEX 0x05007000 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/pkcs7.h b/src/wolfssl/wolfcrypt/pkcs7.h index 4a6184e..2af117d 100644 --- a/src/wolfssl/wolfcrypt/pkcs7.h +++ b/src/wolfssl/wolfcrypt/pkcs7.h @@ -225,6 +225,11 @@ typedef int (*CallbackWrapCEK)(PKCS7* pkcs7, byte* cek, word32 cekSz, byte* out, word32 outSz, int keyWrapAlgo, int type, int dir); +/* Callbacks for supporting different stream cases */ +typedef int (*CallbackGetContent)(PKCS7* pkcs7, byte** content, void* ctx); +typedef int (*CallbackStreamOut)(PKCS7* pkcs7, const byte* output, + word32 outputSz, void* ctx); + #if defined(HAVE_PKCS7_RSA_RAW_SIGN_CALLBACK) && !defined(NO_RSA) /* RSA sign raw digest callback, user builds DigestInfo */ typedef int (*CallbackRsaSignRawDigest)(PKCS7* pkcs7, byte* digest, @@ -248,6 +253,9 @@ struct PKCS7 { #ifdef ASN_BER_TO_DER byte* der; /* DER encoded version of message */ word32 derSz; + CallbackGetContent getContentCb; + CallbackStreamOut streamOutCb; + void* streamCtx; /* passed to getcontentCb and streamOutCb */ #endif byte encodeStream:1; /* use BER when encoding */ byte noCerts:1; /* if certificates should be added into bundle @@ -499,7 +507,11 @@ WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCb(PKCS7* pkcs7, WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCtx(PKCS7* pkcs7, void* ctx); #endif /* NO_PKCS7_ENCRYPTED_DATA */ -WOLFSSL_API int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag); +/* stream and certs */ +WOLFSSL_LOCAL int wc_PKCS7_WriteOut(PKCS7* pkcs7, byte* output, + const byte* input, word32 inputSz); +WOLFSSL_API int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, + CallbackGetContent getContentCb, CallbackStreamOut streamOutCb, void* ctx); WOLFSSL_API int wc_PKCS7_GetStreamMode(PKCS7* pkcs7); WOLFSSL_API int wc_PKCS7_SetNoCerts(PKCS7* pkcs7, byte flag); WOLFSSL_API int wc_PKCS7_GetNoCerts(PKCS7* pkcs7); diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index 401bef5..72905c9 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -51,6 +51,13 @@ #define WOLFSSL_ESPIDF_BLANKLINE_MESSAGE "." #endif +/* Optional exit message. + * The WOLFSSL_COMPLETE keyword exits wolfSSL test harness script. */ +#define WOLFSSL_ESPIDF_EXIT_MESSAGE \ + "\n\nDone!" \ + "\n\nWOLFSSL_COMPLETE" \ + "\n\nIf running from idf.py monitor, press twice: Ctrl+]" + /* exit codes to be used in tfm.c, sp_int.c, integer.c, etc. * * see wolfssl/wolfcrypt/error-crypt.h diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index e736070..bc544c7 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -266,6 +266,11 @@ /* #define WOLFSSL_MAXQ108X */ #if defined(ARDUINO) + /* Due to limited build control, we'll ignore file warnings. */ + /* See https://github.com/arduino/arduino-cli/issues/631 */ + #undef WOLFSSL_IGNORE_FILE_WARN + #define WOLFSSL_IGNORE_FILE_WARN + /* we don't have the luxury of compiler options, so manually define */ #if defined(__arm__) #undef WOLFSSL_ARDUINO @@ -3257,6 +3262,15 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_NO_KYBER1024 #endif +#if (defined(HAVE_LIBOQS) || \ + defined(WOLFSSL_WC_KYBER) || \ + defined(HAVE_LIBXMSS) || \ + defined(HAVE_LIBLMS) || \ + defined(WOLFSSL_DUAL_ALG_CERTS)) && \ + !defined(WOLFSSL_EXPERIMENTAL_SETTINGS) + #error Experimental settings without WOLFSSL_EXPERIMENTAL_SETTINGS +#endif + #if defined(HAVE_PQC) && !defined(HAVE_LIBOQS) && !defined(HAVE_PQM4) && \ !defined(WOLFSSL_HAVE_KYBER) #error Please do not define HAVE_PQC yourself. @@ -3296,8 +3310,9 @@ extern void uITRON4_free(void *p) ; #define NO_SESSION_CACHE_REF #endif -/* (D)TLS v1.3 requires 64-bit number wrappers */ -#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS_DROP_STATS) +/* (D)TLS v1.3 requires 64-bit number wrappers as does XMSS and LMS. */ +#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS_DROP_STATS) || \ + defined(WOLFSSL_WC_XMSS) || defined(WOLFSSL_WC_LMS) #undef WOLFSSL_W64_WRAPPER #define WOLFSSL_W64_WRAPPER #endif diff --git a/src/wolfssl/wolfcrypt/sha256.h b/src/wolfssl/wolfcrypt/sha256.h index 3651dd3..323c53a 100644 --- a/src/wolfssl/wolfcrypt/sha256.h +++ b/src/wolfssl/wolfcrypt/sha256.h @@ -249,6 +249,10 @@ WOLFSSL_API void wc_Sha256Free(wc_Sha256* sha256); #if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) WOLFSSL_API int wc_Sha256Transform(wc_Sha256* sha, const unsigned char* data); #endif +#if defined(WOLFSSL_HAVE_LMS) && !defined(WOLFSSL_LMS_FULL_HASH) +WOLFSSL_API int wc_Sha256HashBlock(wc_Sha256* sha, const unsigned char* data, + unsigned char* hash); +#endif #if defined(WOLFSSL_HASH_KEEP) WOLFSSL_API int wc_Sha256_Grow(wc_Sha256* sha256, const byte* in, int inSz); #endif diff --git a/src/wolfssl/wolfcrypt/tfm.h b/src/wolfssl/wolfcrypt/tfm.h index 91849f1..915a335 100644 --- a/src/wolfssl/wolfcrypt/tfm.h +++ b/src/wolfssl/wolfcrypt/tfm.h @@ -877,8 +877,9 @@ MP_API int mp_radix_size (mp_int * a, int radix, int *size); MP_API int mp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp); MP_API int mp_montgomery_reduce_ex(fp_int *a, fp_int *m, fp_digit mp, int ct); MP_API int mp_montgomery_setup(fp_int *a, fp_digit *rho); +MP_API int mp_sqr(fp_int *a, fp_int *b); + #ifdef HAVE_ECC - MP_API int mp_sqr(fp_int *a, fp_int *b); MP_API int mp_div_2(fp_int * a, fp_int * b); MP_API int mp_div_2_mod_ct(mp_int *a, mp_int *b, mp_int *c); #endif diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index 8c754dd..01ed929 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -1052,6 +1052,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SPHINCS = 98, DYNAMIC_TYPE_SM4_BUFFER = 99, DYNAMIC_TYPE_DEBUG_TAG = 100, + DYNAMIC_TYPE_LMS = 101, DYNAMIC_TYPE_SNIFFER_SERVER = 1000, DYNAMIC_TYPE_SNIFFER_SESSION = 1001, DYNAMIC_TYPE_SNIFFER_PB = 1002, diff --git a/src/wolfssl/wolfcrypt/wc_kyber.h b/src/wolfssl/wolfcrypt/wc_kyber.h index 62c3ed8..61fe8b2 100644 --- a/src/wolfssl/wolfcrypt/wc_kyber.h +++ b/src/wolfssl/wolfcrypt/wc_kyber.h @@ -1,3 +1,281 @@ +/* wc_kyber.h + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ -#error "Contact wolfSSL to get the implementation of this file" +/*! + \file wolfssl/wolfcrypt/wc_kyber.h +*/ + + +#ifndef WOLF_CRYPT_WC_KYBER_H +#define WOLF_CRYPT_WC_KYBER_H + +#include +#include +#include +#include + +#ifdef WOLFSSL_HAVE_KYBER + +#if defined(_MSC_VER) + #define KYBER_NOINLINE __declspec(noinline) +#elif defined(__GNUC__) + #define KYBER_NOINLINE __attribute__((noinline)) +#else + #define KYBER_NOINLINE +#endif + +/* Define algorithm type when not excluded. */ + +#ifndef WOLFSSL_NO_KYBER512 +#define WOLFSSL_KYBER512 +#endif +#ifndef WOLFSSL_NO_KYBER768 +#define WOLFSSL_KYBER768 +#endif +#ifndef WOLFSSL_NO_KYBER1024 +#define WOLFSSL_KYBER1024 +#endif + +enum { + /* Flags of Kyber keys. */ + KYBER_FLAG_PRIV_SET = 0x0001, + KYBER_FLAG_PUB_SET = 0x0002, + KYBER_FLAG_BOTH_SET = 0x0003, + KYBER_FLAG_H_SET = 0x0004, + + /* 2 bits of random used to create noise value. */ + KYBER_CBD_ETA2 = 2, + /* 3 bits of random used to create noise value. */ + KYBER_CBD_ETA3 = 3, + + /* Number of bits to compress to. */ + KYBER_COMP_4BITS = 4, + KYBER_COMP_5BITS = 5, + KYBER_COMP_10BITS = 10, + KYBER_COMP_11BITS = 11, +}; + + +/* SHAKE128 rate. */ +#define XOF_BLOCK_SIZE 168 + +/* Modulus of co-efficients of polynomial. */ +#define KYBER_Q 3329 + + +/* Kyber-512 parameters */ +#ifdef WOLFSSL_KYBER512 +/* Number of bits of random to create noise from. */ +#define KYBER512_ETA1 KYBER_CBD_ETA3 +#endif /* WOLFSSL_KYBER512 */ + +/* Kyber-768 parameters */ +#ifdef WOLFSSL_KYBER768 +/* Number of bits of random to create noise from. */ +#define KYBER768_ETA1 KYBER_CBD_ETA2 +#endif /* WOLFSSL_KYBER768 */ + +/* Kyber-1024 parameters */ +#ifdef WOLFSSL_KYBER1024 +/* Number of bits of random to create noise from. */ +#define KYBER1024_ETA1 KYBER_CBD_ETA2 +#endif /* WOLFSSL_KYBER1024 */ + + + +/* The data type of the pseudo-random function. */ +#define KYBER_PRF_T wc_Shake + +/* Kyber key. */ +struct KyberKey { + /* Type of key: KYBER512, KYBER768, KYBER1024 */ + int type; + /* Dynamic memory allocation hint. */ + void* heap; +#if defined(WOLF_CRYPTO_CB) + /* Device Id. */ + int devId; +#endif + /* Flags indicating what is stored in the key. */ + int flags; + + /* A pseudo-random function object. */ + KYBER_PRF_T prf; + + /* Private key as a vector. */ + sword16 priv[KYBER_MAX_K * KYBER_N]; + /* Public key as a vector. */ + sword16 pub[KYBER_MAX_K * KYBER_N]; + /* Public seed. */ + byte pubSeed[KYBER_SYM_SZ]; + /* Public hash - hash of encoded public key. */ + byte h[KYBER_SYM_SZ]; + /* Randomizer for decapsulation. */ + byte z[KYBER_SYM_SZ]; +}; + +#ifdef __cplusplus + extern "C" { +#endif + +WOLFSSL_LOCAL +void kyber_init(void); +WOLFSSL_LOCAL +void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, + int kp); +WOLFSSL_LOCAL +void kyber_encapsulate(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp); +WOLFSSL_LOCAL +void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp); + +WOLFSSL_LOCAL +int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, + int transposed); +WOLFSSL_LOCAL +int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, sword16* vec2, + sword16* poly, byte* seed); + +#ifdef USE_INTEL_SPEEDUP +WOLFSSL_LOCAL +int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen); +#endif +WOLFSSL_LOCAL +void kyber_prf_init(KYBER_PRF_T* prf); +WOLFSSL_LOCAL +int kyber_prf_new(KYBER_PRF_T* prf, void* heap, int devId); +WOLFSSL_LOCAL +void kyber_prf_free(KYBER_PRF_T* prf); + +WOLFSSL_LOCAL +int kyber_cmp(const byte* a, const byte* b, int sz); + +WOLFSSL_LOCAL +void kyber_vec_compress_10(byte* r, sword16* v, unsigned int kp); +WOLFSSL_LOCAL +void kyber_vec_compress_11(byte* r, sword16* v); +WOLFSSL_LOCAL +void kyber_vec_decompress_10(sword16* v, const unsigned char* b, + unsigned int kp); +WOLFSSL_LOCAL +void kyber_vec_decompress_11(sword16* v, const unsigned char* b); + +WOLFSSL_LOCAL +void kyber_compress_4(byte* b, sword16* p); +WOLFSSL_LOCAL +void kyber_compress_5(byte* b, sword16* p); +WOLFSSL_LOCAL +void kyber_decompress_4(sword16* p, const unsigned char* b); +WOLFSSL_LOCAL +void kyber_decompress_5(sword16* p, const unsigned char* b); + +WOLFSSL_LOCAL +void kyber_from_msg(sword16* p, const byte* msg); +WOLFSSL_LOCAL +void kyber_to_msg(byte* msg, sword16* p); +WOLFSSL_LOCAL +void kyber_from_bytes(sword16* p, const byte* b, int k); +WOLFSSL_LOCAL +void kyber_to_bytes(byte* b, sword16* p, int k); + +#ifdef USE_INTEL_SPEEDUP +WOLFSSL_LOCAL +void kyber_keygen_avx2(sword16* priv, sword16* pub, sword16* e, + const sword16* a, int kp); +WOLFSSL_LOCAL +void kyber_encapsulate_avx2(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp); +WOLFSSL_LOCAL +void kyber_decapsulate_avx2(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp); + +WOLFSSL_LOCAL +unsigned int kyber_rej_uniform_n_avx2(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); +WOLFSSL_LOCAL +unsigned int kyber_rej_uniform_avx2(sword16* p, unsigned int len, const byte* r, + unsigned int rLen); +WOLFSSL_LOCAL +void kyber_redistribute_21_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void kyber_redistribute_17_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void kyber_redistribute_16_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void kyber_redistribute_8_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); + +WOLFSSL_LOCAL +void kyber_sha3_blocksx4_avx2(word64* s); +WOLFSSL_LOCAL +void kyber_sha3_128_blocksx4_seed_avx2(word64* s, byte* seed); +WOLFSSL_LOCAL +void kyber_sha3_256_blocksx4_seed_avx2(word64* s, byte* seed); + +WOLFSSL_LOCAL +void kyber_cbd_eta2_avx2(sword16* p, const byte* r); +WOLFSSL_LOCAL +void kyber_cbd_eta3_avx2(sword16* p, const byte* r); + +WOLFSSL_LOCAL +void kyber_from_msg_avx2(sword16* p, const byte* msg); +WOLFSSL_LOCAL +void kyber_to_msg_avx2(byte* msg, sword16* p); + +WOLFSSL_LOCAL +void kyber_from_bytes_avx2(sword16* p, const byte* b); +WOLFSSL_LOCAL +void kyber_to_bytes_avx2(byte* b, sword16* p); + +WOLFSSL_LOCAL +void kyber_compress_10_avx2(byte* r, const sword16* p, int n); +WOLFSSL_LOCAL +void kyber_decompress_10_avx2(sword16* p, const byte* r, int n); +WOLFSSL_LOCAL +void kyber_compress_11_avx2(byte* r, const sword16* p, int n); +WOLFSSL_LOCAL +void kyber_decompress_11_avx2(sword16* p, const byte* r, int n); + +WOLFSSL_LOCAL +void kyber_compress_4_avx2(byte* r, const sword16* p); +WOLFSSL_LOCAL +void kyber_decompress_4_avx2(sword16* p, const byte* r); +WOLFSSL_LOCAL +void kyber_compress_5_avx2(byte* r, const sword16* p); +WOLFSSL_LOCAL +void kyber_decompress_5_avx2(sword16* p, const byte* r); + + +WOLFSSL_LOCAL +int kyber_cmp_avx2(const byte* a, const byte* b, int sz); +#endif + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* WOLFSSL_HAVE_KYBER */ + +#endif /* WOLF_CRYPT_WC_KYBER_H */ diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index a0e06e4..f51dad7 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -1,6 +1,6 @@ /* wc_lms.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * From 918f9933d7965d166014e6f1a562322f6bc7887c Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Sat, 20 Jul 2024 13:31:46 -0700 Subject: [PATCH 02/13] ignore some known source file placeholders --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index d6c4114..436e3ed 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,9 @@ ################################################################################ /.vs +/src/wolfcrypt/src/fips.c +/src/wolfcrypt/src/fips_test.c +/src/wolfcrypt/src/selftest.c +/src/wolfcrypt/src/wolfcrypt_first.c +/src/wolfcrypt/src/wolfcrypt_last.c +/src/wolfssl/wolfcrypt/fips.h From de00d3aebaf42789257cd4d72176a6357a7756cb Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Sat, 20 Jul 2024 13:33:07 -0700 Subject: [PATCH 03/13] Add PlatformIO files for v5.7.2 --- library.json.pio | 24 ++++++++++++++++++++++++ library.properties.pio | 9 +++++++++ 2 files changed, 33 insertions(+) create mode 100644 library.json.pio create mode 100644 library.properties.pio diff --git a/library.json.pio b/library.json.pio new file mode 100644 index 0000000..b5f5981 --- /dev/null +++ b/library.json.pio @@ -0,0 +1,24 @@ +{ + "name": "Arduino-wolfSSL", + "version": "5.7.2", + "description": "5.7.2 (Arduino-wolfSSL for PlatformIO) A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments.", + "keywords": "FIPS, DO-178, TLS, DTLS, DSA, PSK, X.509, RSA, ECC, AES, GCM, PQ, SHA, SHA256, 3DES, SHA512, MD5, ASN, CMAC, Blake, camellia, ChaCha, ChaCha20, DH, OCSP, ALPN, SNI, CRL, dilithium, ed25519, ed448, kdf, pkcs7, pkcs12, poly1305, Curve25519, sakke, SM, SM2, SM3, SM4, TFM, PKI, SRP, wolfcrypt, wolfssl, Post-quantum cryptography, Certificate management, SSL-TLS handshake, Session caching, Hash, Secure hashing, Public key infrastructure, Cryptanalysis, Lightweight cryptography, Hardware-based security", + "repository": { + "type": "git", + "url": "https://github.com/wolfSSL/Arduino-wolfSSL.git" + }, + "authors": [ + { + "name": "wolfSSL Inc.", + "email": "support@wolfssl.com", + "url": "https://www.wolfssl.com/contact/", + "maintainer": true + } + ], + "license": "GPL-2.0-only", + "homepage": "https://www.wolfssl.com/", + "dependencies": { + }, + "frameworks": "*", + "platforms": "*" +} diff --git a/library.properties.pio b/library.properties.pio new file mode 100644 index 0000000..9d1ac56 --- /dev/null +++ b/library.properties.pio @@ -0,0 +1,9 @@ +name=Arduino-wolfSSL +version=5.7.2 +author=wolfSSL Inc. +maintainer=wolfSSL inc +sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. +paragraph=Manual: https://www.wolfssl.com/documentation/manuals/wolfssl/index.html. +category=Communication +url=https://www.wolfssl.com/ +architectures=* From 6adf61383f1ca9f6c69e8ee2ac8f05b587f23f5c Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Sat, 20 Jul 2024 13:40:58 -0700 Subject: [PATCH 04/13] Publish wolfSSL v5.7.2 for Arduino --- ChangeLog.md | 107 + README | 156 +- README.md | 159 +- library.properties | 2 +- src/src/bio.c | 56 +- src/src/conf.c | 29 + src/src/crl.c | 59 +- src/src/dtls.c | 33 +- src/src/dtls13.c | 3 +- src/src/internal.c | 3000 +- src/src/keys.c | 50 +- src/src/ocsp.c | 117 +- src/src/pk.c | 2847 +- src/src/quic.c | 104 +- src/src/sniffer.c | 51 +- src/src/ssl.c | 43102 ++++++---------- src/src/ssl_asn1.c | 43 +- src/src/ssl_bn.c | 2 +- src/src/ssl_certman.c | 8 +- src/src/ssl_crypto.c | 12 +- src/src/ssl_load.c | 5831 +++ src/src/ssl_misc.c | 217 +- src/src/ssl_p7p12.c | 2123 + src/src/ssl_sess.c | 4567 ++ src/src/tls.c | 598 +- src/src/tls13.c | 1618 +- src/src/wolfio.c | 116 +- src/src/x509.c | 496 +- src/src/x509_str.c | 213 +- src/user_settings.h | 2 +- src/wolfcrypt/src/aes.c | 740 +- src/wolfcrypt/src/asn.c | 890 +- src/wolfcrypt/src/bio.c | 56 +- src/wolfcrypt/src/chacha.c | 4 + src/wolfcrypt/src/cmac.c | 27 +- src/wolfcrypt/src/coding.c | 2 +- src/wolfcrypt/src/cryptocb.c | 132 +- src/wolfcrypt/src/curve25519.c | 4 +- src/wolfcrypt/src/des3.c | 8 +- src/wolfcrypt/src/dh.c | 21 +- src/wolfcrypt/src/dilithium.c | 8314 ++- src/wolfcrypt/src/dsa.c | 34 +- src/wolfcrypt/src/ecc.c | 520 +- src/wolfcrypt/src/eccsi.c | 2 +- src/wolfcrypt/src/ed25519.c | 212 +- src/wolfcrypt/src/ed448.c | 156 +- src/wolfcrypt/src/error.c | 30 + src/wolfcrypt/src/evp.c | 164 +- src/wolfcrypt/src/ext_kyber.c | 12 +- src/wolfcrypt/src/ext_lms.c | 127 +- src/wolfcrypt/src/ext_xmss.c | 4 +- src/wolfcrypt/src/falcon.c | 19 +- src/wolfcrypt/src/fe_448.c | 21 +- src/wolfcrypt/src/fe_operations.c | 18 +- src/wolfcrypt/src/ge_448.c | 32 +- src/wolfcrypt/src/hash.c | 20 +- src/wolfcrypt/src/hmac.c | 83 +- src/wolfcrypt/src/kdf.c | 186 +- src/wolfcrypt/src/logging.c | 197 +- src/wolfcrypt/src/memory.c | 447 +- src/wolfcrypt/src/misc.c | 19 + src/wolfcrypt/src/pkcs12.c | 47 +- src/wolfcrypt/src/pkcs7.c | 658 +- src/wolfcrypt/src/poly1305.c | 28 +- src/wolfcrypt/src/port/Espressif/esp32_aes.c | 15 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 59 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 1024 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 146 +- .../src/port/Espressif/esp_sdk_mem_lib.c | 280 + .../src/port/Espressif/esp_sdk_time_lib.c | 442 + .../src/port/Espressif/esp_sdk_wifi_lib.c | 468 + src/wolfcrypt/src/port/atmel/atmel.c | 16 +- src/wolfcrypt/src/pwdbased.c | 50 + src/wolfcrypt/src/random.c | 98 +- src/wolfcrypt/src/rsa.c | 289 +- src/wolfcrypt/src/sakke.c | 32 +- src/wolfcrypt/src/sha.c | 18 +- src/wolfcrypt/src/sha256.c | 282 +- src/wolfcrypt/src/sha3.c | 152 +- src/wolfcrypt/src/sha512.c | 336 +- src/wolfcrypt/src/signature.c | 8 +- src/wolfcrypt/src/sp_cortexm.c | 1420 +- src/wolfcrypt/src/sp_int.c | 21 + src/wolfcrypt/src/sphincs.c | 5 +- src/wolfcrypt/src/srp.c | 10 +- src/wolfcrypt/src/wc_encrypt.c | 18 +- src/wolfcrypt/src/wc_kyber.c | 96 +- src/wolfcrypt/src/wc_kyber_poly.c | 711 +- src/wolfcrypt/src/wc_lms.c | 1123 +- src/wolfcrypt/src/wc_lms_impl.c | 3072 +- src/wolfcrypt/src/wc_pkcs11.c | 16 +- src/wolfcrypt/src/wc_port.c | 33 +- src/wolfcrypt/src/wc_xmss.c | 1648 +- src/wolfcrypt/src/wc_xmss_impl.c | 4317 +- src/wolfcrypt/src/wolfevent.c | 2 +- src/wolfcrypt/src/wolfmath.c | 5 +- src/wolfssl/bio.c | 56 +- src/wolfssl/certs_test.h | 3535 +- src/wolfssl/error-ssl.h | 7 + src/wolfssl/evp.c | 164 +- src/wolfssl/internal.h | 288 +- src/wolfssl/openssl/bn.h | 2 + src/wolfssl/openssl/ec.h | 47 +- src/wolfssl/openssl/evp.h | 1 + src/wolfssl/openssl/hmac.h | 4 +- src/wolfssl/openssl/opensslv.h | 1 + src/wolfssl/openssl/sha.h | 4 +- src/wolfssl/openssl/sha3.h | 5 + src/wolfssl/openssl/ssl.h | 35 +- src/wolfssl/openssl/tls1.h | 6 +- src/wolfssl/openssl/x509.h | 2 +- src/wolfssl/openssl/x509v3.h | 2 +- src/wolfssl/ssl.h | 388 +- src/wolfssl/test.h | 85 +- src/wolfssl/version.h | 4 +- src/wolfssl/wolfcrypt/aes.h | 75 +- src/wolfssl/wolfcrypt/asn.h | 89 +- src/wolfssl/wolfcrypt/asn_public.h | 14 +- src/wolfssl/wolfcrypt/chacha.h | 2 +- src/wolfssl/wolfcrypt/cmac.h | 8 +- src/wolfssl/wolfcrypt/cryptocb.h | 27 +- src/wolfssl/wolfcrypt/dh.h | 8 +- src/wolfssl/wolfcrypt/dilithium.h | 680 +- src/wolfssl/wolfcrypt/ecc.h | 77 +- src/wolfssl/wolfcrypt/ed25519.h | 14 +- src/wolfssl/wolfcrypt/ed448.h | 13 +- src/wolfssl/wolfcrypt/error-crypt.h | 33 +- src/wolfssl/wolfcrypt/ext_lms.h | 4 +- src/wolfssl/wolfcrypt/ext_xmss.h | 4 +- src/wolfssl/wolfcrypt/fe_operations.h | 4 +- src/wolfssl/wolfcrypt/fips_test.h | 56 +- src/wolfssl/wolfcrypt/hmac.h | 20 +- src/wolfssl/wolfcrypt/kdf.h | 19 + src/wolfssl/wolfcrypt/kyber.h | 8 +- src/wolfssl/wolfcrypt/lms.h | 57 +- src/wolfssl/wolfcrypt/logging.h | 19 + src/wolfssl/wolfcrypt/mem_track.h | 45 +- src/wolfssl/wolfcrypt/memory.h | 111 +- src/wolfssl/wolfcrypt/misc.h | 2 + src/wolfssl/wolfcrypt/pkcs12.h | 7 +- src/wolfssl/wolfcrypt/poly1305.h | 11 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 229 + .../wolfcrypt/port/Espressif/esp32-crypt.h | 163 +- src/wolfssl/wolfcrypt/pwdbased.h | 4 + src/wolfssl/wolfcrypt/random.h | 12 +- src/wolfssl/wolfcrypt/rsa.h | 38 +- src/wolfssl/wolfcrypt/settings.h | 237 +- src/wolfssl/wolfcrypt/sha.h | 8 +- src/wolfssl/wolfcrypt/sha256.h | 18 +- src/wolfssl/wolfcrypt/sha3.h | 23 +- src/wolfssl/wolfcrypt/sha512.h | 15 +- src/wolfssl/wolfcrypt/sp_int.h | 10 +- src/wolfssl/wolfcrypt/types.h | 44 +- src/wolfssl/wolfcrypt/wc_kyber.h | 4 +- src/wolfssl/wolfcrypt/wc_lms.h | 449 +- src/wolfssl/wolfcrypt/wc_port.h | 38 +- src/wolfssl/wolfcrypt/wc_xmss.h | 264 +- src/wolfssl/wolfcrypt/xmss.h | 8 +- src/wolfssl/wolfio.h | 20 +- 159 files changed, 67228 insertions(+), 35566 deletions(-) create mode 100644 src/src/ssl_load.c create mode 100644 src/src/ssl_p7p12.c create mode 100644 src/src/ssl_sess.c create mode 100644 src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c create mode 100644 src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c create mode 100644 src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c create mode 100644 src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h diff --git a/ChangeLog.md b/ChangeLog.md index c3b2475..01fca46 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,110 @@ +# wolfSSL Release 5.7.2 (July 08, 2024) + +Release 5.7.2 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 + +## Vulnerabilities +* [Medium] CVE-2024-1544 +Potential ECDSA nonce side channel attack in versions of wolfSSL before 5.6.6 with wc_ecc_sign_hash calls. Generating the ECDSA nonce k samples a random number r and then truncates this randomness with a modular reduction mod n where n is the order of the elliptic curve. Analyzing the division through a control-flow revealing side-channel reveals a bias in the most significant bits of k. Depending on the curve this is either a negligible bias or a significant bias large enough to reconstruct k with lattice reduction methods. Thanks to Luca Wilke, Florian Sieck and Thomas Eisenbarth (University of Lübeck) for reporting the vulnerability. Details will appear in the proceedings of CCS 24. +Fixed https://github.com/wolfSSL/wolfssl/pull/7020 + + +* [Medium] CVE-2024-5288 +A private key blinding operation, enabled by defining the macro WOLFSSL_BLIND_PRIVATE_KEY, was added to mitigate a potential row hammer attack on ECC operations. If performing ECC private key operations in an environment where a malicious user could gain fine control over the device and perform row hammer style attacks it is recommended to update the version of wolfSSL used and to build with WOLFSSL_BLIND_PRIVATE_KEY defined. Thanks to Kemal Derya, M. Caner Tol, Berk Sunar for the report (Vernam Applied Cryptography and Cybersecurity Lab at Worcester Polytechnic Institute) +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7416 + + +* [Low] When parsing a provided maliciously crafted certificate directly using wolfSSL API, outside of a TLS connection, a certificate with an excessively large number of extensions could lead to a potential DoS. There are existing sanity checks during a TLS handshake with wolfSSL which mitigate this issue. Thanks to Bing Shi for the report. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7597 + +* [Low] CVE-2024-5991 +In the function MatchDomainName(), input param str is treated as a NULL terminated string despite being user provided and unchecked. Specifically, the Openssl compatibility function X509_check_host() takes in a pointer and length to check against, with no requirements that it be NULL terminated. While calling without a NULL terminated string is very uncommon, it is still technically allowed. If a caller was attempting to do a name check on a non*NULL terminated buffer, the code would read beyond the bounds of the input array until it found a NULL terminator. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7604 + +* [Medium] CVE-2024-5814 +A malicious TLS1.2 server can force a TLS1.3 client with downgrade capability to use a ciphersuite that it did not agree to and achieve a successful connection. This is because, aside from the extensions, the client was skipping fully parsing the server hello when downgrading from TLS 1.3. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7619 + +* [Medium] OCSP stapling version 2 response verification bypass issue when a crafted response of length 0 is received. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 + +* [Medium] OCSP stapling version 2 revocation bypass with a retry of a TLS connection attempt. A revoked CA certificate could incorrectly be loaded into the trusted signers list and used in a repeat connection attempt. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 + + +## New Feature Additions +* Added Dilithium/ML-DSA: Implementation of ML-DSA-44/65/87 (PR 7622) +* AES RISC-V 64-bit ASM: ECB/CBC/CTR/GCM/CCM (PR 7569) +* Added CUDA support for AES encryption (PR 7436) +* Added support for gRPC (PR 7445) +* Added function wc_RsaPrivateKeyDecodeRaw to import raw RSA private keys (PR 7608) +* Added crypto callback for SHA-3 (PR 7670) +* Support for Infineon Modus Toolbox with wolfSSL (PR 7369) +* Allow user to send a user_canceled alert by calling wolfSSL_SendUserCanceled (PR 7590) +* C# wrapper SNI support added (PR 7610) +* Quantum-safe algorithm support added to the Linux kernel module (PR 7574) +* Support for NIST 800-56C Option 1 KDF, using the macro WC_KDF_NIST_SP_800_56C added (PR 7589) +* AES-XTS streaming mode added, along with hardware acceleration and kernel module use (PR 7522, 7560, 7424) +* PlatformIO FreeRTOS with ESP build and addition of benchmark and test example applications (PR 7528, 7413, 7559, 7542) + + +## Enhancements and Optimizations +* Expanded STM32 AES hardware acceleration support for use with STM32H5 (PR 7578) +* Adjusted wc_xmss and wc_lms settings to support use with wolfBoot (PR 7393) +* Added the --enable-rpk option to autotools build for using raw public key support (PR 7379) +* SHA-3 Thumb2, ARM32 assembly implementation added (PR 7667) +* Improvements to RSA padding to expose Pad/Unpad APIs (PR 7612) +* Updates and API additions for supporting socat version 1.8.0.0 (PR 7594) +* cmake build improvements, expanding build options with SINGLE_THREADED and post-quantum algorithms, adjusting the generation of options.h file and using “yes;no” boolean instead of strings (PR 7611, 7546, 7479, 7480, 7380) +* Improvements for Renesas RZ support (PR 7474) +* Improvements to dual algorithm certificates for post-quantum keys (PR 7286) +* Added wolfSSL_SessionIsSetup so the user can check if a session ticket has been sent by the server (PR 7430) +* hostap updates: Implement PACs for EAP-FAST and filter cipher list on TLS version change (PR 7446) +* Changed subject name comparison to match different upper and lower cases (PR 7420) +* Support for DTLS 1.3 downgrade when using PSK (PR 7367) +* Update to static memory build for more generic memory pools used (PR 7418) +* Improved performance of Kyber C implementation (PR 7654) +* Support for ECC_CACHE_CURVE with no malloc (PR 7490) +* Added the configure option --enable-debug-trace-errcodes (macro WOLFSSL_DEBUG_TRACE_ERROR_CODES) which enables more debug tracking of error code values (PR 7634) +* Enhanced wc_MakeRsaKey and wc_RsaKeyToDer to work with WOLFSSL_NO_MALLOC (PR 7362) +* Improvements to assembly implementations of ChaCha20 and Poly1305 ASM for use with MSVC (PR 7319) +* Cortex-M inline assembly labels with unique number appended (PR 7649) +* Added secret logging callback to TLS <= 1.2, enabled with the macro HAVE_SECRET_CALLBACK (PR 7372) +* Made wc_RNG_DRBG_Reseed() a public wolfCrypt API (PR 7386) +* Enabled DES3 support without the DES3 ciphers. To re-enable DES3 cipher suites, use the configure flag --enable-des3-tls-suites (PR 7315) +* Added stubs required for latest nginx (1.25.5) (PR 7449) +* Added option for using a custom salt with the function wc_ecc_ctx_set_own_salt (PR 7552) +* Added PQ files for Windows (PR 7419) +* Enhancements to static memory feature, adding the option for a global heap hint (PR 7478) and build options for a lean or debug setting, enabled with --enable-staticmemory=small or --enable-staticmemory=debug (PR 7597) +* Updated --enable-jni to define SESSION_CERTS for wolfJSSE (PR 7557) +* Exposed DTLS in Ada wrapper and updated examples (PR 7397) +* Added additional minimum TLS extension size sanity checks (PR 7602) +* ESP improvements: updating the examples and libraries, updates for Apple HomeKit SHA/SRP, and fix for endianness with SHA512 software fallback (PR 7607, 7392, 7505, 7535) +* Made the wc_CheckCertSigPubKey API publicly available with the define of the macro WOLFSSL_SMALL_CERT_VERIFY (PR 7599) +* Added an alpha/preview of additional FIPS 140-3 full submission, bringing additional algorithms such as SRTP-KDF, AES-XTS, GCM streaming, AES-CFB, ED25519, and ED448 into the FIPS module boundary (PR 7295) +* XCODE support for v5.2.3 of the FIPS module (PR 7140) +* Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) + +## Fixes +* Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) +* Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) +* Fixed use of %rip with SHA-256 x64 assembly (PR 7409) +* Fixed OCSP response message build for DTLS (PR 7671) +* Handled edge case in wc_ecc_mulmod() with zero (PR 7532) +* Fixed RPK (Raw Public Key) to follow certificate use correctly (PR 7375) +* Added sanity check on record header with QUIC use (PR 7638) +* Added sanity check for empty directory strings in X.509 when parsing (PR 7669) +* Added sanity check on non-conforming serial number of 0 in certificates being parsed (PR 7625) +* Fixed wolfSSL_CTX_set1_sigalgs_list() to make the TLS connection conform to the selected sig hash algorithm (PR 7693) +* Various fixes for dual algorithm certificates including small stack use and support for Certificate Signing Requests (PR 7577) +* Added sanity check for critical policy extension when wolfSSL is built without policy extension support enabled (PR 7388) +* Added sanity check that the ed25519 signature is smaller than the order (PR 7513) +* Fixed Segger emNet to handle non-blocking want read/want write (PR 7581) + + # wolfSSL Release 5.7.0 (Mar 20, 2024) Release 5.7.0 has been developed according to wolfSSL's development and QA diff --git a/README b/README index 72d5cb3..3fa99a5 100644 --- a/README +++ b/README @@ -70,99 +70,113 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.7.0 (Mar 20, 2024) +# wolfSSL Release 5.7.2 (July 08, 2024) -Release 5.7.0 has been developed according to wolfSSL's development and QA +Release 5.7.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -NOTE: In future releases, --enable-des3 (which is disabled by default) will be insufficient in itself to enable DES3 in TLS cipher suites. A new option, --enable-des3-tls-suites, will need to be supplied in addition. This option should only be used in backward compatibility scenarios, as it is inherently insecure. - -NOTE: This release switches the default ASN.1 parser to the new ASN template code. If the original ASN.1 code is preferred define `WOLFSSL_ASN_ORIGINAL` to use it. See PR #7199. - - ## Vulnerabilities -* [High] CVE-2024-0901 Potential denial of service and out of bounds read. Affects TLS 1.3 on the server side when accepting a connection from a malicious TLS 1.3 client. If using TLS 1.3 on the server side it is recommended to update the version of wolfSSL used. Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7099 +* [Medium] CVE-2024-1544 +Potential ECDSA nonce side channel attack in versions of wolfSSL before 5.6.6 with wc_ecc_sign_hash calls. Generating the ECDSA nonce k samples a random number r and then truncates this randomness with a modular reduction mod n where n is the order of the elliptic curve. Analyzing the division through a control-flow revealing side-channel reveals a bias in the most significant bits of k. Depending on the curve this is either a negligible bias or a significant bias large enough to reconstruct k with lattice reduction methods. Thanks to Luca Wilke, Florian Sieck and Thomas Eisenbarth (University of Lübeck) for reporting the vulnerability. Details will appear in the proceedings of CCS 24. +Fixed https://github.com/wolfSSL/wolfssl/pull/7020 -* [Med] CVE-2024-1545 Fault Injection vulnerability in RsaPrivateDecryption function that potentially allows an attacker that has access to the same system with a victims process to perform a Rowhammer fault injection. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia)." -Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7167 +* [Medium] CVE-2024-5288 +A private key blinding operation, enabled by defining the macro WOLFSSL_BLIND_PRIVATE_KEY, was added to mitigate a potential row hammer attack on ECC operations. If performing ECC private key operations in an environment where a malicious user could gain fine control over the device and perform row hammer style attacks it is recommended to update the version of wolfSSL used and to build with WOLFSSL_BLIND_PRIVATE_KEY defined. Thanks to Kemal Derya, M. Caner Tol, Berk Sunar for the report (Vernam Applied Cryptography and Cybersecurity Lab at Worcester Polytechnic Institute) +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7416 -* [Med] Fault injection attack with EdDSA signature operations. This affects ed25519 sign operations where the system could be susceptible to Rowhammer attacks. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia). -Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7212 +* [Low] When parsing a provided maliciously crafted certificate directly using wolfSSL API, outside of a TLS connection, a certificate with an excessively large number of extensions could lead to a potential DoS. There are existing sanity checks during a TLS handshake with wolfSSL which mitigate this issue. Thanks to Bing Shi for the report. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7597 +* [Low] CVE-2024-5991 +In the function MatchDomainName(), input param str is treated as a NULL terminated string despite being user provided and unchecked. Specifically, the Openssl compatibility function X509_check_host() takes in a pointer and length to check against, with no requirements that it be NULL terminated. While calling without a NULL terminated string is very uncommon, it is still technically allowed. If a caller was attempting to do a name check on a non*NULL terminated buffer, the code would read beyond the bounds of the input array until it found a NULL terminator. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7604 -## New Feature Additions - -* Added --enable-experimental configure flag to gate out features that are currently experimental. Now liboqs, kyber, lms, xmss, and dual-alg-certs require the --enable-experimental flag. +* [Medium] CVE-2024-5814 +A malicious TLS1.2 server can force a TLS1.3 client with downgrade capability to use a ciphersuite that it did not agree to and achieve a successful connection. This is because, aside from the extensions, the client was skipping fully parsing the server hello when downgrading from TLS 1.3. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7619 -### POST QUANTUM SUPPORT ADDITIONS -* Experimental framework for using wolfSSL’s XMSS implementation (PR 7161) -* Experimental framework for using wolfSSL’s LMS implementation (PR 7283) -* Experimental wolfSSL Kyber implementation and assembly optimizations, enabled with --enable-experimental --enable-kyber (PR 7318) -* Experimental support for post quantum dual key/signature certificates. A few known issues and sanitizer checks are in progress with this feature. Enabled with the configure flags --enable-experimental --enable-dual-alg-certs (PR 7112) -* CryptoCb support for PQC algorithms (PR 7110) +* [Medium] OCSP stapling version 2 response verification bypass issue when a crafted response of length 0 is received. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 -### OTHER FEATURE ADDITIONS -* The Linux kernel module now supports registration of AES-GCM, AES-XTS, AES-CBC, and AES-CFB with the kernel cryptosystem through the new --enable-linuxkm-lkcapi-register option, enabling automatic use of wolfCrypt implementations by the dm-crypt/luks and ESP subsystems. In particular, wolfCrypt AES-XTS with –enable-aesni is faster than the native kernel implementation. -* CryptoCb hook to one-shot CMAC functions (PR 7059) -* BER content streaming support for PKCS7_VerifySignedData and sign/encrypt operations (PR 6961 & 7184) -* IoT-Safe SHA-384 and SHA-512 support (PR 7176) -* I/O callbacks for content and output with PKCS7 bundle sign/encrypt to reduce peak memory usage (PR 7272) -* Microchip PIC24 support and example project (PR 7151) -* AutoSAR shim layer for RNG, SHA256, and AES (PR 7296) -* wolfSSL_CertManagerUnloadIntermediateCerts API to clear intermediate certs added to certificate store (PR 7245) -* Implement SSL_get_peer_signature_nid and SSL_get_peer_signature_type_nid (PR 7236) +* [Medium] OCSP stapling version 2 revocation bypass with a retry of a TLS connection attempt. A revoked CA certificate could incorrectly be loaded into the trusted signers list and used in a repeat connection attempt. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 -## Enhancements and Optimizations +## New Feature Additions +* Added Dilithium/ML-DSA: Implementation of ML-DSA-44/65/87 (PR 7622) +* AES RISC-V 64-bit ASM: ECB/CBC/CTR/GCM/CCM (PR 7569) +* Added CUDA support for AES encryption (PR 7436) +* Added support for gRPC (PR 7445) +* Added function wc_RsaPrivateKeyDecodeRaw to import raw RSA private keys (PR 7608) +* Added crypto callback for SHA-3 (PR 7670) +* Support for Infineon Modus Toolbox with wolfSSL (PR 7369) +* Allow user to send a user_canceled alert by calling wolfSSL_SendUserCanceled (PR 7590) +* C# wrapper SNI support added (PR 7610) +* Quantum-safe algorithm support added to the Linux kernel module (PR 7574) +* Support for NIST 800-56C Option 1 KDF, using the macro WC_KDF_NIST_SP_800_56C added (PR 7589) +* AES-XTS streaming mode added, along with hardware acceleration and kernel module use (PR 7522, 7560, 7424) +* PlatformIO FreeRTOS with ESP build and addition of benchmark and test example applications (PR 7528, 7413, 7559, 7542) -* Remove obsolete user-crypto functionality and Intel IPP support (PR 7097) -* Support for RSA-PSS signatures with CRL use (PR 7119) -* Enhancement for AES-GCM use with Xilsecure on Microblaze (PR 7051) -* Support for crypto cb only build with ECC and NXP CAAM (PR 7269) -* Improve liboqs integration adding locking and init/cleanup functions (PR 7026) -* Prevent memory access before clientSession->serverRow and clientSession->serverIdx are sanitized (PR 7096) -* Enhancements to reproducible build (PR 7267) -* Update Arduino example TLS Client/Server and improve support for ESP32 (PR 7304 & 7177) -* XC32 compiler version 4.x compatibility (PR 7128) -* Porting for build on PlayStation 3 and 4 (PR 7072) -* Improvements for Espressif use; SHA HW/SW selection and use on ESP32-C2/ESP8684, wolfSSL_NewThread() type, component cmake fix, and update TLS client example for ESP8266 (PR 7081, 7173, 7077, 7148, 7240) -* Allow crypto callbacks with SHA-1 HW (PR 7087) -* Update OpenSSH port to version 9.6p1(PR 7203) -* ARM Thumb2 enhancements, AES-GCM support for GCM_SMALL, alignment fix on key, fix for ASM clobber list (PR 7291,7301,7221) -* Expand heap hint support for static memory build with more x509 functions (PR 7136) -* Improving ARMv8 ChaCha20 ASM (alignment) (PR 7182) -* Unknown extension callback wolfSSL_CertManagerSetUnknownExtCallback added to CertManager (PR 7194) -* Implement wc_rng_new_ex for use with devID’s with crypto callback (PR 7271) -* Allow reading 0-RTT data after writing 0.5-RTT data (PR 7102) -* Send alert on bad PSK binder error (PR 7235) -* Enhancements to CMake build files for use with cross compiling (PR 7188) +## Enhancements and Optimizations +* Expanded STM32 AES hardware acceleration support for use with STM32H5 (PR 7578) +* Adjusted wc_xmss and wc_lms settings to support use with wolfBoot (PR 7393) +* Added the --enable-rpk option to autotools build for using raw public key support (PR 7379) +* SHA-3 Thumb2, ARM32 assembly implementation added (PR 7667) +* Improvements to RSA padding to expose Pad/Unpad APIs (PR 7612) +* Updates and API additions for supporting socat version 1.8.0.0 (PR 7594) +* cmake build improvements, expanding build options with SINGLE_THREADED and post-quantum algorithms, adjusting the generation of options.h file and using “yes;no” boolean instead of strings (PR 7611, 7546, 7479, 7480, 7380) +* Improvements for Renesas RZ support (PR 7474) +* Improvements to dual algorithm certificates for post-quantum keys (PR 7286) +* Added wolfSSL_SessionIsSetup so the user can check if a session ticket has been sent by the server (PR 7430) +* hostap updates: Implement PACs for EAP-FAST and filter cipher list on TLS version change (PR 7446) +* Changed subject name comparison to match different upper and lower cases (PR 7420) +* Support for DTLS 1.3 downgrade when using PSK (PR 7367) +* Update to static memory build for more generic memory pools used (PR 7418) +* Improved performance of Kyber C implementation (PR 7654) +* Support for ECC_CACHE_CURVE with no malloc (PR 7490) +* Added the configure option --enable-debug-trace-errcodes (macro WOLFSSL_DEBUG_TRACE_ERROR_CODES) which enables more debug tracking of error code values (PR 7634) +* Enhanced wc_MakeRsaKey and wc_RsaKeyToDer to work with WOLFSSL_NO_MALLOC (PR 7362) +* Improvements to assembly implementations of ChaCha20 and Poly1305 ASM for use with MSVC (PR 7319) +* Cortex-M inline assembly labels with unique number appended (PR 7649) +* Added secret logging callback to TLS <= 1.2, enabled with the macro HAVE_SECRET_CALLBACK (PR 7372) +* Made wc_RNG_DRBG_Reseed() a public wolfCrypt API (PR 7386) +* Enabled DES3 support without the DES3 ciphers. To re-enable DES3 cipher suites, use the configure flag --enable-des3-tls-suites (PR 7315) +* Added stubs required for latest nginx (1.25.5) (PR 7449) +* Added option for using a custom salt with the function wc_ecc_ctx_set_own_salt (PR 7552) +* Added PQ files for Windows (PR 7419) +* Enhancements to static memory feature, adding the option for a global heap hint (PR 7478) and build options for a lean or debug setting, enabled with --enable-staticmemory=small or --enable-staticmemory=debug (PR 7597) +* Updated --enable-jni to define SESSION_CERTS for wolfJSSE (PR 7557) +* Exposed DTLS in Ada wrapper and updated examples (PR 7397) +* Added additional minimum TLS extension size sanity checks (PR 7602) +* ESP improvements: updating the examples and libraries, updates for Apple HomeKit SHA/SRP, and fix for endianness with SHA512 software fallback (PR 7607, 7392, 7505, 7535) +* Made the wc_CheckCertSigPubKey API publicly available with the define of the macro WOLFSSL_SMALL_CERT_VERIFY (PR 7599) +* Added an alpha/preview of additional FIPS 140-3 full submission, bringing additional algorithms such as SRTP-KDF, AES-XTS, GCM streaming, AES-CFB, ED25519, and ED448 into the FIPS module boundary (PR 7295) +* XCODE support for v5.2.3 of the FIPS module (PR 7140) +* Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) ## Fixes +* Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) +* Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) +* Fixed use of %rip with SHA-256 x64 assembly (PR 7409) +* Fixed OCSP response message build for DTLS (PR 7671) +* Handled edge case in wc_ecc_mulmod() with zero (PR 7532) +* Fixed RPK (Raw Public Key) to follow certificate use correctly (PR 7375) +* Added sanity check on record header with QUIC use (PR 7638) +* Added sanity check for empty directory strings in X.509 when parsing (PR 7669) +* Added sanity check on non-conforming serial number of 0 in certificates being parsed (PR 7625) +* Fixed wolfSSL_CTX_set1_sigalgs_list() to make the TLS connection conform to the selected sig hash algorithm (PR 7693) +* Various fixes for dual algorithm certificates including small stack use and support for Certificate Signing Requests (PR 7577) +* Added sanity check for critical policy extension when wolfSSL is built without policy extension support enabled (PR 7388) +* Added sanity check that the ed25519 signature is smaller than the order (PR 7513) +* Fixed Segger emNet to handle non-blocking want read/want write (PR 7581) + -* Fix for checking result of MAC verify when no AAD is used with AES-GCM and Xilinx Xilsecure (PR 7051) -* Fix for Aria sign use (PR 7082) -* Fix for invalid `dh_ffdhe_test` test case using Intel QuickAssist (PR 7085) -* Fixes for TI AES and SHA on TM4C with HW acceleration and add full AES GCM and CCM support with TLS (PR 7018) -* Fixes for STM32 PKA use with ECC (PR 7098) -* Fixes for TLS 1.3 with crypto callbacks to offload KDF / HMAC operation (PR 7070) -* Fix include path for FSP 3.5 on Renesas RA6M4 (PR 7101) -* Siphash x64 asm fix for use with older compilers (PR 7299) -* Fix for SGX build with SP (PR 7308) -* Fix to Make it mandatory that the cookie is sent back in new ClientHello when seen in a HelloRetryRequest with (PR 7190) -* Fix for wrap around behavior with BIO pairs (PR 7169) -* OCSP fixes for parsing of response correctly when there was a revocation reason and returning correct error value with date checks (PR 7241 & 7255) -* Fix build with `NO_STDIO_FILESYSTEM` and improve checks for `XGETENV` (PR 7150) -* Fix for DTLS sequence number and cookie when downgrading DTLS version (PR 7214) -* Fix for write_dup use with chacha-poly cipher suites (PR 7206) -* Fix for multiple handshake messages in one record failing with OUT_OF_ORDER_E when downgrading from TLS 1.3 to TLS 1.2 (PR 7141) -* Fix for AES ECB build with Thumb and alignment (PR 7094) -* Fix for negotiate handshake until the end in wolfSSL_read/wolfSSL_write if hitting an edge case with want read/write (PR 7237) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/README.md b/README.md index 9b2498f..f6b00c3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.0 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.2 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -10,6 +10,8 @@ See the [Arduino-wolfSSL logs](https://downloads.arduino.cc/libraries/logs/githu The first Official wolfSSL Arduino Library is `5.6.6-Arduino.1`: a slightly modified, post [release 5.6.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.6.6-stable) version update. +The next Official wolfSSL Arduino Library is [5.7.0](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.0-stable) + See other [wolfSSL releases versions](https://github.com/wolfSSL/wolfssl/releases). The `./wolfssl-arduino.sh INSTALL` [script](https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO) can be used to install specific GitHub versions as needed. # wolfSSL Embedded SSL/TLS Library @@ -88,98 +90,111 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.7.0 (Mar 20, 2024) +# wolfSSL Release 5.7.2 (July 08, 2024) -Release 5.7.0 has been developed according to wolfSSL's development and QA +Release 5.7.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -NOTE: In future releases, --enable-des3 (which is disabled by default) will be insufficient in itself to enable DES3 in TLS cipher suites. A new option, --enable-des3-tls-suites, will need to be supplied in addition. This option should only be used in backward compatibility scenarios, as it is inherently insecure. - -NOTE: This release switches the default ASN.1 parser to the new ASN template code. If the original ASN.1 code is preferred define `WOLFSSL_ASN_ORIGINAL` to use it. See PR #7199. - ## Vulnerabilities -* [High] CVE-2024-0901 Potential denial of service and out of bounds read. Affects TLS 1.3 on the server side when accepting a connection from a malicious TLS 1.3 client. If using TLS 1.3 on the server side it is recommended to update the version of wolfSSL used. Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7099 +* [Medium] CVE-2024-1544 +Potential ECDSA nonce side channel attack in versions of wolfSSL before 5.6.6 with wc_ecc_sign_hash calls. Generating the ECDSA nonce k samples a random number r and then truncates this randomness with a modular reduction mod n where n is the order of the elliptic curve. Analyzing the division through a control-flow revealing side-channel reveals a bias in the most significant bits of k. Depending on the curve this is either a negligible bias or a significant bias large enough to reconstruct k with lattice reduction methods. Thanks to Luca Wilke, Florian Sieck and Thomas Eisenbarth (University of Lübeck) for reporting the vulnerability. Details will appear in the proceedings of CCS 24. +Fixed https://github.com/wolfSSL/wolfssl/pull/7020 -* [Med] CVE-2024-1545 Fault Injection vulnerability in RsaPrivateDecryption function that potentially allows an attacker that has access to the same system with a victims process to perform a Rowhammer fault injection. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia)." -Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7167 +* [Medium] CVE-2024-5288 +A private key blinding operation, enabled by defining the macro WOLFSSL_BLIND_PRIVATE_KEY, was added to mitigate a potential row hammer attack on ECC operations. If performing ECC private key operations in an environment where a malicious user could gain fine control over the device and perform row hammer style attacks it is recommended to update the version of wolfSSL used and to build with WOLFSSL_BLIND_PRIVATE_KEY defined. Thanks to Kemal Derya, M. Caner Tol, Berk Sunar for the report (Vernam Applied Cryptography and Cybersecurity Lab at Worcester Polytechnic Institute) +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7416 -* [Med] Fault injection attack with EdDSA signature operations. This affects ed25519 sign operations where the system could be susceptible to Rowhammer attacks. Thanks to Junkai Liang, Zhi Zhang, Xin Zhang, Qingni Shen for the report (Peking University, The University of Western Australia). -Fixed in this GitHub pull request https://github.com/wolfSSL/wolfssl/pull/7212 +* [Low] When parsing a provided maliciously crafted certificate directly using wolfSSL API, outside of a TLS connection, a certificate with an excessively large number of extensions could lead to a potential DoS. There are existing sanity checks during a TLS handshake with wolfSSL which mitigate this issue. Thanks to Bing Shi for the report. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7597 +* [Low] CVE-2024-5991 +In the function MatchDomainName(), input param str is treated as a NULL terminated string despite being user provided and unchecked. Specifically, the Openssl compatibility function X509_check_host() takes in a pointer and length to check against, with no requirements that it be NULL terminated. While calling without a NULL terminated string is very uncommon, it is still technically allowed. If a caller was attempting to do a name check on a non*NULL terminated buffer, the code would read beyond the bounds of the input array until it found a NULL terminator. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7604 -## New Feature Additions - -* Added --enable-experimental configure flag to gate out features that are currently experimental. Now liboqs, kyber, lms, xmss, and dual-alg-certs require the --enable-experimental flag. +* [Medium] CVE-2024-5814 +A malicious TLS1.2 server can force a TLS1.3 client with downgrade capability to use a ciphersuite that it did not agree to and achieve a successful connection. This is because, aside from the extensions, the client was skipping fully parsing the server hello when downgrading from TLS 1.3. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7619 -### POST QUANTUM SUPPORT ADDITIONS -* Experimental framework for using wolfSSL’s XMSS implementation (PR 7161) -* Experimental framework for using wolfSSL’s LMS implementation (PR 7283) -* Experimental wolfSSL Kyber implementation and assembly optimizations, enabled with --enable-experimental --enable-kyber (PR 7318) -* Experimental support for post quantum dual key/signature certificates. A few known issues and sanitizer checks are in progress with this feature. Enabled with the configure flags --enable-experimental --enable-dual-alg-certs (PR 7112) -* CryptoCb support for PQC algorithms (PR 7110) +* [Medium] OCSP stapling version 2 response verification bypass issue when a crafted response of length 0 is received. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 -### OTHER FEATURE ADDITIONS -* The Linux kernel module now supports registration of AES-GCM, AES-XTS, AES-CBC, and AES-CFB with the kernel cryptosystem through the new --enable-linuxkm-lkcapi-register option, enabling automatic use of wolfCrypt implementations by the dm-crypt/luks and ESP subsystems. In particular, wolfCrypt AES-XTS with –enable-aesni is faster than the native kernel implementation. -* CryptoCb hook to one-shot CMAC functions (PR 7059) -* BER content streaming support for PKCS7_VerifySignedData and sign/encrypt operations (PR 6961 & 7184) -* IoT-Safe SHA-384 and SHA-512 support (PR 7176) -* I/O callbacks for content and output with PKCS7 bundle sign/encrypt to reduce peak memory usage (PR 7272) -* Microchip PIC24 support and example project (PR 7151) -* AutoSAR shim layer for RNG, SHA256, and AES (PR 7296) -* wolfSSL_CertManagerUnloadIntermediateCerts API to clear intermediate certs added to certificate store (PR 7245) -* Implement SSL_get_peer_signature_nid and SSL_get_peer_signature_type_nid (PR 7236) +* [Medium] OCSP stapling version 2 revocation bypass with a retry of a TLS connection attempt. A revoked CA certificate could incorrectly be loaded into the trusted signers list and used in a repeat connection attempt. Found with internal testing. +Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 -## Enhancements and Optimizations +## New Feature Additions +* Added Dilithium/ML-DSA: Implementation of ML-DSA-44/65/87 (PR 7622) +* AES RISC-V 64-bit ASM: ECB/CBC/CTR/GCM/CCM (PR 7569) +* Added CUDA support for AES encryption (PR 7436) +* Added support for gRPC (PR 7445) +* Added function wc_RsaPrivateKeyDecodeRaw to import raw RSA private keys (PR 7608) +* Added crypto callback for SHA-3 (PR 7670) +* Support for Infineon Modus Toolbox with wolfSSL (PR 7369) +* Allow user to send a user_canceled alert by calling wolfSSL_SendUserCanceled (PR 7590) +* C# wrapper SNI support added (PR 7610) +* Quantum-safe algorithm support added to the Linux kernel module (PR 7574) +* Support for NIST 800-56C Option 1 KDF, using the macro WC_KDF_NIST_SP_800_56C added (PR 7589) +* AES-XTS streaming mode added, along with hardware acceleration and kernel module use (PR 7522, 7560, 7424) +* PlatformIO FreeRTOS with ESP build and addition of benchmark and test example applications (PR 7528, 7413, 7559, 7542) -* Remove obsolete user-crypto functionality and Intel IPP support (PR 7097) -* Support for RSA-PSS signatures with CRL use (PR 7119) -* Enhancement for AES-GCM use with Xilsecure on Microblaze (PR 7051) -* Support for crypto cb only build with ECC and NXP CAAM (PR 7269) -* Improve liboqs integration adding locking and init/cleanup functions (PR 7026) -* Prevent memory access before clientSession->serverRow and clientSession->serverIdx are sanitized (PR 7096) -* Enhancements to reproducible build (PR 7267) -* Update Arduino example TLS Client/Server and improve support for ESP32 (PR 7304 & 7177) -* XC32 compiler version 4.x compatibility (PR 7128) -* Porting for build on PlayStation 3 and 4 (PR 7072) -* Improvements for Espressif use; SHA HW/SW selection and use on ESP32-C2/ESP8684, wolfSSL_NewThread() type, component cmake fix, and update TLS client example for ESP8266 (PR 7081, 7173, 7077, 7148, 7240) -* Allow crypto callbacks with SHA-1 HW (PR 7087) -* Update OpenSSH port to version 9.6p1(PR 7203) -* ARM Thumb2 enhancements, AES-GCM support for GCM_SMALL, alignment fix on key, fix for ASM clobber list (PR 7291,7301,7221) -* Expand heap hint support for static memory build with more x509 functions (PR 7136) -* Improving ARMv8 ChaCha20 ASM (alignment) (PR 7182) -* Unknown extension callback wolfSSL_CertManagerSetUnknownExtCallback added to CertManager (PR 7194) -* Implement wc_rng_new_ex for use with devID’s with crypto callback (PR 7271) -* Allow reading 0-RTT data after writing 0.5-RTT data (PR 7102) -* Send alert on bad PSK binder error (PR 7235) -* Enhancements to CMake build files for use with cross compiling (PR 7188) +## Enhancements and Optimizations +* Expanded STM32 AES hardware acceleration support for use with STM32H5 (PR 7578) +* Adjusted wc_xmss and wc_lms settings to support use with wolfBoot (PR 7393) +* Added the --enable-rpk option to autotools build for using raw public key support (PR 7379) +* SHA-3 Thumb2, ARM32 assembly implementation added (PR 7667) +* Improvements to RSA padding to expose Pad/Unpad APIs (PR 7612) +* Updates and API additions for supporting socat version 1.8.0.0 (PR 7594) +* cmake build improvements, expanding build options with SINGLE_THREADED and post-quantum algorithms, adjusting the generation of options.h file and using “yes;no” boolean instead of strings (PR 7611, 7546, 7479, 7480, 7380) +* Improvements for Renesas RZ support (PR 7474) +* Improvements to dual algorithm certificates for post-quantum keys (PR 7286) +* Added wolfSSL_SessionIsSetup so the user can check if a session ticket has been sent by the server (PR 7430) +* hostap updates: Implement PACs for EAP-FAST and filter cipher list on TLS version change (PR 7446) +* Changed subject name comparison to match different upper and lower cases (PR 7420) +* Support for DTLS 1.3 downgrade when using PSK (PR 7367) +* Update to static memory build for more generic memory pools used (PR 7418) +* Improved performance of Kyber C implementation (PR 7654) +* Support for ECC_CACHE_CURVE with no malloc (PR 7490) +* Added the configure option --enable-debug-trace-errcodes (macro WOLFSSL_DEBUG_TRACE_ERROR_CODES) which enables more debug tracking of error code values (PR 7634) +* Enhanced wc_MakeRsaKey and wc_RsaKeyToDer to work with WOLFSSL_NO_MALLOC (PR 7362) +* Improvements to assembly implementations of ChaCha20 and Poly1305 ASM for use with MSVC (PR 7319) +* Cortex-M inline assembly labels with unique number appended (PR 7649) +* Added secret logging callback to TLS <= 1.2, enabled with the macro HAVE_SECRET_CALLBACK (PR 7372) +* Made wc_RNG_DRBG_Reseed() a public wolfCrypt API (PR 7386) +* Enabled DES3 support without the DES3 ciphers. To re-enable DES3 cipher suites, use the configure flag --enable-des3-tls-suites (PR 7315) +* Added stubs required for latest nginx (1.25.5) (PR 7449) +* Added option for using a custom salt with the function wc_ecc_ctx_set_own_salt (PR 7552) +* Added PQ files for Windows (PR 7419) +* Enhancements to static memory feature, adding the option for a global heap hint (PR 7478) and build options for a lean or debug setting, enabled with --enable-staticmemory=small or --enable-staticmemory=debug (PR 7597) +* Updated --enable-jni to define SESSION_CERTS for wolfJSSE (PR 7557) +* Exposed DTLS in Ada wrapper and updated examples (PR 7397) +* Added additional minimum TLS extension size sanity checks (PR 7602) +* ESP improvements: updating the examples and libraries, updates for Apple HomeKit SHA/SRP, and fix for endianness with SHA512 software fallback (PR 7607, 7392, 7505, 7535) +* Made the wc_CheckCertSigPubKey API publicly available with the define of the macro WOLFSSL_SMALL_CERT_VERIFY (PR 7599) +* Added an alpha/preview of additional FIPS 140-3 full submission, bringing additional algorithms such as SRTP-KDF, AES-XTS, GCM streaming, AES-CFB, ED25519, and ED448 into the FIPS module boundary (PR 7295) +* XCODE support for v5.2.3 of the FIPS module (PR 7140) +* Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) ## Fixes - -* Fix for checking result of MAC verify when no AAD is used with AES-GCM and Xilinx Xilsecure (PR 7051) -* Fix for Aria sign use (PR 7082) -* Fix for invalid `dh_ffdhe_test` test case using Intel QuickAssist (PR 7085) -* Fixes for TI AES and SHA on TM4C with HW acceleration and add full AES GCM and CCM support with TLS (PR 7018) -* Fixes for STM32 PKA use with ECC (PR 7098) -* Fixes for TLS 1.3 with crypto callbacks to offload KDF / HMAC operation (PR 7070) -* Fix include path for FSP 3.5 on Renesas RA6M4 (PR 7101) -* Siphash x64 asm fix for use with older compilers (PR 7299) -* Fix for SGX build with SP (PR 7308) -* Fix to Make it mandatory that the cookie is sent back in new ClientHello when seen in a HelloRetryRequest with (PR 7190) -* Fix for wrap around behavior with BIO pairs (PR 7169) -* OCSP fixes for parsing of response correctly when there was a revocation reason and returning correct error value with date checks (PR 7241 & 7255) -* Fix build with `NO_STDIO_FILESYSTEM` and improve checks for `XGETENV` (PR 7150) -* Fix for DTLS sequence number and cookie when downgrading DTLS version (PR 7214) -* Fix for write_dup use with chacha-poly cipher suites (PR 7206) -* Fix for multiple handshake messages in one record failing with OUT_OF_ORDER_E when downgrading from TLS 1.3 to TLS 1.2 (PR 7141) -* Fix for AES ECB build with Thumb and alignment (PR 7094) -* Fix for negotiate handshake until the end in wolfSSL_read/wolfSSL_write if hitting an edge case with want read/write (PR 7237) +* Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) +* Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) +* Fixed use of %rip with SHA-256 x64 assembly (PR 7409) +* Fixed OCSP response message build for DTLS (PR 7671) +* Handled edge case in wc_ecc_mulmod() with zero (PR 7532) +* Fixed RPK (Raw Public Key) to follow certificate use correctly (PR 7375) +* Added sanity check on record header with QUIC use (PR 7638) +* Added sanity check for empty directory strings in X.509 when parsing (PR 7669) +* Added sanity check on non-conforming serial number of 0 in certificates being parsed (PR 7625) +* Fixed wolfSSL_CTX_set1_sigalgs_list() to make the TLS connection conform to the selected sig hash algorithm (PR 7693) +* Various fixes for dual algorithm certificates including small stack use and support for Certificate Signing Requests (PR 7577) +* Added sanity check for critical policy extension when wolfSSL is built without policy extension support enabled (PR 7388) +* Added sanity check that the ed25519 signature is smaller than the order (PR 7513) +* Fixed Segger emNet to handle non-blocking want read/want write (PR 7581) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/library.properties b/library.properties index 1a01ade..5f7d802 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.7.0 +version=5.7.2 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index 2dab43e..340cbfd 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -50,7 +50,7 @@ */ static int wolfSSL_BIO_BASE64_read(WOLFSSL_BIO* bio, void* buf, int len) { - word32 frmtSz = len; + word32 frmtSz = (word32)len; WOLFSSL_ENTER("wolfSSL_BIO_BASE64_read"); @@ -77,6 +77,8 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) if (buf == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nread(bio, &pt, len); if (sz1 > 0) { XMEMCPY(buf, pt, sz1); @@ -91,8 +93,10 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } } } - if (sz1 == 0) + if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY; sz1 = -1; + } return sz1; } @@ -175,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } - bio->mem_buf->length = bio->wrSz; + bio->mem_buf->length = (size_t)bio->wrSz; bio->ptr = bio->mem_buf->data; } } @@ -233,13 +237,13 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, - sz) != WOLFSSL_SUCCESS) + (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, sz) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -305,12 +309,12 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFREAD(buf, 1, len, (XFILE)bio->ptr); + ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, len); + ret = (int)XREAD(bio->num, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -399,7 +403,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, /* get the encoded length */ if (bio->flags & WOLFSSL_BIO_FLAG_BASE64_NO_NL) { if (Base64_Encode_NoNl((const byte*)data, inLen, NULL, - &sz) != LENGTH_ONLY_E) { + &sz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -448,7 +452,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, (void)heap; - return inLen; + return (int)inLen; } #endif /* WOLFSSL_BASE64_ENCODE */ @@ -502,8 +506,11 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (bio == NULL || data == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; WOLFSSL_MSG("No room left to write"); return WOLFSSL_BIO_ERROR; } @@ -521,6 +528,8 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (sz2 > 0) { XMEMCPY(buf, data, sz2); sz1 += sz2; + if (len > sz2) + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; } } @@ -591,12 +600,12 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, - len) != WOLFSSL_SUCCESS) { + (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, len) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -652,7 +661,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) if (ret > 0) { /* change so that data is formatted buffer */ data = frmt; - len = frmtSz; + len = (int)frmtSz; } #else WOLFSSL_MSG("WOLFSSL_BIO_BASE64 used without " @@ -670,12 +679,12 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFWRITE(data, 1, len, (XFILE)bio->ptr); + ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, len); + ret = (int)XWRITE(bio->num, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -972,7 +981,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { - ret = szOut; + ret = (int)szOut; } } break; @@ -1257,8 +1266,8 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) bio->rdIdx = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = bio->num; - bio->mem_buf->max = bio->num; + bio->mem_buf->length = (size_t)bio->num; + bio->mem_buf->max = (size_t)bio->num; } return WOLFSSL_SUCCESS; @@ -1608,7 +1617,12 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) XFCLOSE((XFILE)bio->ptr); } - bio->ptr = XFOPEN(name, "w"); + /* 'b' flag is ignored on POSIX targets, but on Windows it assures + * inhibition of LF<->CRLF rewriting, so that there is consistency + * between the size and contents of the representation in memory and on + * disk. + */ + bio->ptr = XFOPEN(name, "wb"); if (((XFILE)bio->ptr) == XBADFILE) { return WOLFSSL_FAILURE; } @@ -2637,7 +2651,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) len = (int)XSTRLEN((const char*)buf) + 1; } - if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, len) == 0) { + if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, (size_t)len) == 0) { wolfSSL_BIO_free(bio); return NULL; } diff --git a/src/src/conf.c b/src/src/conf.c index cfc6085..d177da5 100644 --- a/src/src/conf.c +++ b/src/src/conf.c @@ -1599,4 +1599,33 @@ int wolfSSL_CONF_cmd_value_type(WOLFSSL_CONF_CTX *cctx, const char *cmd) * END OF CONF API ******************************************************************************/ +#if defined(OPENSSL_EXTRA) +OPENSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void) +{ + OPENSSL_INIT_SETTINGS* init = (OPENSSL_INIT_SETTINGS*)XMALLOC( + sizeof(OPENSSL_INIT_SETTINGS), NULL, DYNAMIC_TYPE_OPENSSL); + + return init; +} + +void wolfSSL_OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS* init) +{ + XFREE(init, NULL, DYNAMIC_TYPE_OPENSSL); +} + +#ifndef NO_WOLFSSL_STUB +int wolfSSL_OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS* init, + char* appname) +{ + (void)init; + (void)appname; + WOLFSSL_STUB("OPENSSL_INIT_set_config_appname"); + return WOLFSSL_SUCCESS; +} +#endif + +#endif /* OPENSSL_EXTRA */ + + + #endif /* WOLFSSL_CONF_INCLUDED */ diff --git a/src/src/crl.c b/src/src/crl.c index 3e61ec9..706c1f6 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -110,18 +110,18 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, #if defined(OPENSSL_EXTRA) crle->lastDateAsn1.length = MAX_DATE_SIZE; XMEMCPY (crle->lastDateAsn1.data, crle->lastDate, - crle->lastDateAsn1.length); + (size_t)crle->lastDateAsn1.length); crle->lastDateAsn1.type = crle->lastDateFormat; crle->nextDateAsn1.length = MAX_DATE_SIZE; XMEMCPY (crle->nextDateAsn1.data, crle->nextDate, - crle->nextDateAsn1.length); + (size_t)crle->nextDateAsn1.length); crle->nextDateAsn1.type = crle->nextDateFormat; crle->issuer = NULL; wolfSSL_d2i_X509_NAME(&crle->issuer, (unsigned char**)&dcrl->issuer, dcrl->issuerSz); if (crle->issuer == NULL) { - return WOLFSSL_FAILURE; + return -1; } #endif #ifdef CRL_STATIC_REVOKED_LIST @@ -318,14 +318,14 @@ static int FindRevokedSerial(RevokedCert* rc, byte* serial, int serialSz, while (rc) { if (serialHash == NULL) { if (rc->serialSz == serialSz && - XMEMCMP(rc->serialNumber, serial, rc->serialSz) == 0) { + XMEMCMP(rc->serialNumber, serial, (size_t)rc->serialSz) == 0) { WOLFSSL_MSG("Cert revoked"); ret = CRL_CERT_REVOKED; break; } } else { - ret = CalcHashId(rc->serialNumber, rc->serialSz, hash); + ret = CalcHashId(rc->serialNumber, (word32)rc->serialSz, hash); if (ret != 0) break; if (XMEMCMP(hash, serialHash, SIGNER_DIGEST_SIZE) == 0) { @@ -362,7 +362,7 @@ static int VerifyCRLE(const WOLFSSL_CRL* crl, CRL_Entry* crle) ret = VerifyCRL_Signature(&sigCtx, crle->toBeSigned, crle->tbsSz, crle->signature, crle->signatureSz, crle->signatureOID, #ifdef WC_RSA_PSS - crle->sigParams, crle->sigParamsSz, + crle->sigParams, (int)crle->sigParamsSz, #else NULL, 0, #endif @@ -392,6 +392,8 @@ static int CheckCertCRLList(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, for (crle = crl->crlList; crle != NULL; crle = crle->next) { if (XMEMCMP(crle->issuerHash, issuerHash, CRL_DIGEST_SIZE) == 0) { + int nextDateValid = 1; + WOLFSSL_MSG("Found CRL Entry on list"); if (crle->verified == 0) { @@ -426,17 +428,20 @@ static int CheckCertCRLList(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK) if (!XVALIDATE_DATE(crle->nextDate,crle->nextDateFormat, AFTER)) { WOLFSSL_MSG("CRL next date is no longer valid"); - ret = ASN_AFTER_DATE_E; + nextDateValid = 0; } #endif } - if (ret == 0) { + if (nextDateValid) { foundEntry = 1; ret = FindRevokedSerial(crle->certs, serial, serialSz, serialHash, crle->totalCerts); if (ret != 0) break; } + else if (foundEntry == 0) { + ret = ASN_AFTER_DATE_E; + } } } @@ -498,8 +503,8 @@ int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, /* Loading .rN form CRL file if find at the folder, */ /* and try again checking Cert in the CRL list. */ /* When not set the folder or not use hash_dir, do nothing. */ - if ((foundEntry == 0) && (ret != OCSP_WANT_READ)) { - if (crl->cm->x509_store_p != NULL) { + if ((foundEntry == 0) && (ret != WC_NO_ERR_TRACE(OCSP_WANT_READ))) { + if (crl->cm != NULL && crl->cm->x509_store_p != NULL) { ret = LoadCertByIssuer(crl->cm->x509_store_p, (WOLFSSL_X509_NAME*)issuerName, X509_LU_CRL); if (ret == WOLFSSL_SUCCESS) { @@ -512,18 +517,18 @@ int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, #endif if (foundEntry == 0) { WOLFSSL_MSG("Couldn't find CRL for status check"); - if (ret != CRL_CERT_DATE_ERR) { + if (ret != WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR)) { ret = CRL_MISSING; } - if (crl->cm->cbMissingCRL) { + if (crl->cm != NULL && crl->cm->cbMissingCRL) { char url[256]; WOLFSSL_MSG("Issuing missing CRL callback"); url[0] = '\0'; if (extCrlInfo) { if (extCrlInfoSz < (int)sizeof(url) -1 ) { - XMEMCPY(url, extCrlInfo, extCrlInfoSz); + XMEMCPY(url, extCrlInfo, (size_t)extCrlInfoSz); url[extCrlInfoSz] = '\0'; } else { @@ -650,13 +655,15 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, InitDecodedCRL(dcrl, crl->heap); ret = ParseCRL(crl->currentEntry->certs, dcrl, myBuffer, (word32)sz, verify, crl->cm); - if (ret != 0 && !(ret == ASN_CRL_NO_SIGNER_E && verify == NO_VERIFY)) { + if (ret != 0 && !(ret == WC_NO_ERR_TRACE(ASN_CRL_NO_SIGNER_E) + && verify == NO_VERIFY)) { WOLFSSL_MSG("ParseCRL error"); CRL_Entry_free(crl->currentEntry, crl->heap); crl->currentEntry = NULL; } else { - ret = AddCRL(crl, dcrl, myBuffer, ret != ASN_CRL_NO_SIGNER_E); + ret = AddCRL(crl, dcrl, myBuffer, + ret != WC_NO_ERR_TRACE(ASN_CRL_NO_SIGNER_E)); if (ret != 0) { WOLFSSL_MSG("AddCRL error"); crl->currentEntry = NULL; @@ -680,8 +687,8 @@ static WOLFSSL_X509_CRL* wolfSSL_X509_crl_new(WOLFSSL_CERT_MANAGER* cm) { WOLFSSL_X509_CRL* ret; - ret = (WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), cm->heap, - DYNAMIC_TYPE_CRL); + ret = (WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), + cm != NULL ? cm->heap : NULL, DYNAMIC_TYPE_CRL); if (ret != NULL) { if (InitCRL(ret, cm) < 0) { WOLFSSL_MSG("Unable to initialize new CRL structure"); @@ -844,7 +851,7 @@ static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl) #ifdef HAVE_CRL_MONITOR if (crl->monitors[0].path) { - int pathSz = (int)XSTRLEN(crl->monitors[0].path) + 1; + size_t pathSz = XSTRLEN(crl->monitors[0].path) + 1; dupl->monitors[0].path = (char*)XMALLOC(pathSz, dupl->heap, DYNAMIC_TYPE_CRL_MONITOR); if (dupl->monitors[0].path != NULL) { @@ -856,7 +863,7 @@ static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl) } if (crl->monitors[1].path) { - int pathSz = (int)XSTRLEN(crl->monitors[1].path) + 1; + size_t pathSz = XSTRLEN(crl->monitors[1].path) + 1; dupl->monitors[1].path = (char*)XMALLOC(pathSz, dupl->heap, DYNAMIC_TYPE_CRL_MONITOR); if (dupl->monitors[1].path != NULL) { @@ -880,6 +887,20 @@ static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl) return 0; } +WOLFSSL_X509_CRL* wolfSSL_X509_CRL_dup(const WOLFSSL_X509_CRL* crl) +{ + WOLFSSL_X509_CRL* ret; + + WOLFSSL_ENTER("wolfSSL_X509_CRL_dup"); + + ret = wolfSSL_X509_crl_new(crl->cm); + if (ret != NULL && DupX509_CRL(ret, crl) != 0) { + FreeCRL(ret, 1); + ret = NULL; + } + return ret; +} + /* returns WOLFSSL_SUCCESS on success. Does not take ownership of newcrl */ int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *store, WOLFSSL_X509_CRL *newcrl) { diff --git a/src/src/dtls.c b/src/src/dtls.c index aecd260..52ace7e 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -107,14 +107,14 @@ int DtlsIgnoreError(int err) { /* Whitelist of errors not to ignore */ switch (err) { - case MEMORY_E: - case MEMORY_ERROR: - case ASYNC_INIT_E: - case ASYNC_OP_E: - case SOCKET_ERROR_E: - case WANT_READ: - case WANT_WRITE: - case COOKIE_ERROR: + case WC_NO_ERR_TRACE(MEMORY_E): + case WC_NO_ERR_TRACE(MEMORY_ERROR): + case WC_NO_ERR_TRACE(ASYNC_INIT_E): + case WC_NO_ERR_TRACE(ASYNC_OP_E): + case WC_NO_ERR_TRACE(SOCKET_ERROR_E): + case WC_NO_ERR_TRACE(WANT_READ): + case WC_NO_ERR_TRACE(WANT_WRITE): + case WC_NO_ERR_TRACE(COOKIE_ERROR): return 0; default: return 1; @@ -187,14 +187,14 @@ typedef struct WolfSSL_CH { byte dtls12cookieSet:1; } WolfSSL_CH; -static int ReadVector8(const byte* input, WolfSSL_ConstVector* v) +static word32 ReadVector8(const byte* input, WolfSSL_ConstVector* v) { v->size = *input; v->elements = input + OPAQUE8_LEN; return v->size + OPAQUE8_LEN; } -static int ReadVector16(const byte* input, WolfSSL_ConstVector* v) +static word32 ReadVector16(const byte* input, WolfSSL_ConstVector* v) { word16 size16; ato16(input, &size16); @@ -267,7 +267,7 @@ static int CheckDtlsCookie(const WOLFSSL* ssl, WolfSSL_CH* ch, return BUFFER_E; ret = TlsCheckCookie(ssl, ch->cookieExt.elements + OPAQUE16_LEN, (word16)(ch->cookieExt.size - OPAQUE16_LEN)); - if (ret < 0 && ret != HRR_COOKIE_ERROR) + if (ret < 0 && ret != WC_NO_ERR_TRACE(HRR_COOKIE_ERROR)) return ret; *cookieGood = ret > 0; ret = 0; @@ -1010,11 +1010,20 @@ int DoClientHelloStateless(WOLFSSL* ssl, const byte* input, word32 helloSz, ssl->options.dtlsStateful = 1; /* Update the window now that we enter the stateful parsing */ #ifdef WOLFSSL_DTLS13 - if (isTls13) + if (isTls13) { + /* Set record numbers before current record number as read */ + Dtls13Epoch* e; ret = Dtls13UpdateWindowRecordRecvd(ssl); + e = Dtls13GetEpoch(ssl, ssl->keys.curEpoch64); + if (e != NULL) + XMEMSET(e->window, 0xFF, sizeof(e->window)); + } else #endif DtlsUpdateWindow(ssl); + /* Set record numbers before current record number as read */ + XMEMSET(ssl->keys.peerSeq->window, 0xFF, + sizeof(ssl->keys.peerSeq->window)); } } diff --git a/src/src/dtls13.c b/src/src/dtls13.c index 86e5fb8..0284ffe 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -396,7 +396,8 @@ int Dtls13ProcessBufferedMessages(WOLFSSL* ssl) * WANT_WRITE means that we are done with processing the msg and we are * waiting to flush the output buffer. */ if ((ret == 0 || ret == WANT_WRITE) || (msg->type == certificate_request && - ssl->options.handShakeDone && ret == WC_PENDING_E)) { + ssl->options.handShakeDone && + ret == WC_NO_ERR_TRACE(WC_PENDING_E))) { if (IsAtLeastTLSv1_3(ssl->version)) Dtls13MsgWasProcessed(ssl, (enum HandShakeType)msg->type); else if (downgraded) diff --git a/src/src/internal.c b/src/src/internal.c index d889f33..6bbd38f 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -149,7 +149,7 @@ #endif -#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; } +#define ERROR_OUT(err, eLabel) { ret = (int)(err); goto eLabel; } #ifdef _MSC_VER /* disable for while(0) cases at the .c level for now */ @@ -266,6 +266,49 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, #endif /* !WOLFSSL_NO_TLS12 */ +#if !defined(NO_CERT) && defined(WOLFSSL_BLIND_PRIVATE_KEY) +int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key, DerBuffer** mask) +{ + int ret = 0; + WC_RNG local_rng; + + if (key != NULL) { + if (*mask != NULL) { + FreeDer(mask); + } + ret = AllocDer(mask, key->length, key->type, key->heap); + if ((ret == 0) && (rng == NULL)) { + if (wc_InitRng(&local_rng) != 0) { + ret = RNG_FAILURE_E; + } + else { + rng = &local_rng; + } + } + if (ret == 0) { + ret = wc_RNG_GenerateBlock(rng, (*mask)->buffer, (*mask)->length); + } + if (ret == 0) { + xorbuf(key->buffer, (*mask)->buffer, (*mask)->length); + } + + if (rng == &local_rng) { + wc_FreeRng(rng); + } + } + + return ret; +} + +void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) +{ + if (key != NULL) { + xorbuf(key->buffer, mask->buffer, mask->length); + } +} +#endif + + #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS) #include #endif @@ -517,6 +560,22 @@ int IsTLS(const WOLFSSL* ssl) { if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_MINOR) return 1; +#ifdef WOLFSSL_DTLS + if (ssl->version.major == DTLS_MAJOR) + return 1; +#endif + + return 0; +} + +int IsTLS_ex(const ProtocolVersion pv) +{ + if (pv.major == SSLv3_MAJOR && pv.minor >=TLSv1_MINOR) + return 1; +#ifdef WOLFSSL_DTLS + if (pv.major == DTLS_MAJOR) + return 1; +#endif return 0; } @@ -2108,7 +2167,7 @@ int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf, word32* sz, } } - if (ret != 0 && ret != LENGTH_ONLY_E && buf != NULL) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E) && buf != NULL) { /*in a fail case clear the buffer which could contain partial key info*/ XMEMSET(buf, 0, *sz); } @@ -2169,7 +2228,6 @@ int InitSSL_Side(WOLFSSL* ssl, word16 side) ssl->options.haveECC = 1; /* server turns on with ECC key cert */ } #endif -#ifdef HAVE_PQC #ifdef HAVE_FALCON if (ssl->options.side == WOLFSSL_CLIENT_END) { ssl->options.haveFalconSig = 1; /* always on client side */ @@ -2180,7 +2238,6 @@ int InitSSL_Side(WOLFSSL* ssl, word16 side) ssl->options.haveDilithiumSig = 1; /* always on client side */ } #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT) if (ssl->options.side == WOLFSSL_CLIENT_END) { @@ -2251,6 +2308,9 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) #ifndef NO_CERTS ctx->privateKeyDevId = INVALID_DEVID; +#ifdef WOLFSSL_DUAL_ALG_CERTS + ctx->altPrivateKeyDevId = INVALID_DEVID; +#endif #endif #ifndef NO_DH @@ -2264,14 +2324,12 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) ctx->minEccKeySz = MIN_ECCKEY_SZ; ctx->eccTempKeySz = ECDHE_SIZE; #endif -#ifdef HAVE_PQC #ifdef HAVE_FALCON ctx->minFalconKeySz = MIN_FALCONKEY_SZ; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM ctx->minDilithiumKeySz = MIN_DILITHIUMKEY_SZ; #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ ctx->verifyDepth = MAX_CHAIN_DEPTH; #ifdef OPENSSL_EXTRA ctx->cbioFlag = WOLFSSL_CBIO_NONE; @@ -2335,7 +2393,6 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) wolfSSL_CTX_set_server_cert_type(ctx, NULL, 0); /* set to default */ #endif /* HAVE_RPK */ -#ifdef HAVE_PQC #ifdef HAVE_FALCON if (method->side == WOLFSSL_CLIENT_END) ctx->haveFalconSig = 1; /* always on client side */ @@ -2346,7 +2403,6 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) ctx->haveDilithiumSig = 1; /* always on client side */ /* server can turn on by loading key */ #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ #ifdef HAVE_ECC if (method->side == WOLFSSL_CLIENT_END) { ctx->haveECDSAsig = 1; /* always on client side */ @@ -2398,22 +2454,27 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) return MEMORY_E; } XMEMSET(ctx->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + /* WOLFSSL_X509_LOOKUP */ - if ((ctx->x509_store.lookup.dirs = - (WOLFSSL_BY_DIR*)XMALLOC(sizeof(WOLFSSL_BY_DIR), - heap, DYNAMIC_TYPE_OPENSSL)) == NULL) { - WOLFSSL_MSG("ctx-x509_store.lookup.dir memory allocation error"); - XFREE(ctx->param, heap, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; + if ((ctx->x509_store.lookup.dirs = (WOLFSSL_BY_DIR*)XMALLOC( + sizeof(WOLFSSL_BY_DIR), + heap, DYNAMIC_TYPE_OPENSSL)) == NULL) { + WOLFSSL_MSG("ctx->x509_store.lookup.dirs: allocation error"); return MEMORY_E; } XMEMSET(ctx->x509_store.lookup.dirs, 0, sizeof(WOLFSSL_BY_DIR)); + + /* param */ + if ((ctx->x509_store.param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC( + sizeof(WOLFSSL_X509_VERIFY_PARAM), + heap, DYNAMIC_TYPE_OPENSSL)) == NULL) { + WOLFSSL_MSG("ctx->x509_store.param: allocation error"); + return MEMORY_E; + } + XMEMSET(ctx->x509_store.param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + if (wc_InitMutex(&ctx->x509_store.lookup.dirs->lock) != 0) { WOLFSSL_MSG("Bad mutex init"); - XFREE(ctx->param, heap, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; - XFREE(ctx->x509_store.lookup.dirs, heap, DYNAMIC_TYPE_OPENSSL); - ctx->x509_store.lookup.dirs = NULL; WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E); return BAD_MUTEX_E; } @@ -2585,11 +2646,17 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) ForceZero(ctx->privateKey->buffer, ctx->privateKey->length); } FreeDer(&ctx->privateKey); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ctx->privateKeyMask); +#endif #ifdef WOLFSSL_DUAL_ALG_CERTS if (ctx->altPrivateKey != NULL && ctx->altPrivateKey->buffer != NULL) { ForceZero(ctx->altPrivateKey->buffer, ctx->altPrivateKey->length); } FreeDer(&ctx->altPrivateKey); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ctx->altPrivateKeyMask); +#endif #endif /* WOLFSSL_DUAL_ALG_CERTS */ #ifdef OPENSSL_ALL wolfSSL_EVP_PKEY_free(ctx->privateKeyPKey); @@ -2661,6 +2728,11 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) ctx->param = NULL; } + if (ctx->x509_store.param) { + XFREE(ctx->x509_store.param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL); + ctx->x509_store.param = NULL; + } + if (ctx->x509_store.lookup.dirs) { #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) if (ctx->x509_store.lookup.dirs->dir_entry) { @@ -2732,7 +2804,7 @@ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) if (ret < 0) { /* check error state, if mutex error code then mutex init failed but * CTX was still malloc'd */ - if (ctx->err == CTX_INIT_MUTEX_E) { + if (ctx->err == WC_NO_ERR_TRACE(CTX_INIT_MUTEX_E)) { SSL_CtxResourceFree(ctx); XFREE(ctx, heap, DYNAMIC_TYPE_CTX); #ifdef WOLFSSL_STATIC_MEMORY @@ -2996,7 +3068,6 @@ static WC_INLINE void AddSuiteHashSigAlgo(byte* hashSigAlgo, byte macAlgo, } else #endif - #ifdef HAVE_PQC #ifdef HAVE_FALCON if (sigAlgo == falcon_level1_sa_algo) { ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx, @@ -3026,7 +3097,6 @@ static WC_INLINE void AddSuiteHashSigAlgo(byte* hashSigAlgo, byte macAlgo, } else #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ #ifdef WC_RSA_PSS if (sigAlgo == rsa_pss_sa_algo) { /* RSA PSS is sig then mac */ @@ -3045,7 +3115,7 @@ static WC_INLINE void AddSuiteHashSigAlgo(byte* hashSigAlgo, byte macAlgo, } } -void InitSuitesHashSigAlgo_ex2(byte* hashSigAlgo, int haveSig, int tls1_2, +void InitSuitesHashSigAlgo(byte* hashSigAlgo, int haveSig, int tls1_2, int keySz, word16* len) { word16 idx = 0; @@ -3087,7 +3157,6 @@ void InitSuitesHashSigAlgo_ex2(byte* hashSigAlgo, int haveSig, int tls1_2, &idx); } #endif -#if defined(HAVE_PQC) #ifdef HAVE_FALCON if (haveSig & SIG_FALCON) { AddSuiteHashSigAlgo(hashSigAlgo, no_mac, falcon_level1_sa_algo, keySz, @@ -3106,7 +3175,6 @@ void InitSuitesHashSigAlgo_ex2(byte* hashSigAlgo, int haveSig, int tls1_2, keySz, &idx); } #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ if (haveSig & SIG_RSA) { #ifdef WC_RSA_PSS if (tls1_2) { @@ -3152,30 +3220,6 @@ void InitSuitesHashSigAlgo_ex2(byte* hashSigAlgo, int haveSig, int tls1_2, *len = idx; } -void InitSuitesHashSigAlgo(Suites* suites, int haveECDSAsig, int haveRSAsig, - int haveFalconSig, int haveDilithiumSig, int haveAnon, int tls1_2, - int keySz) -{ - InitSuitesHashSigAlgo_ex(suites->hashSigAlgo, haveECDSAsig, haveRSAsig, - haveFalconSig, haveDilithiumSig, haveAnon, tls1_2, keySz, - &suites->hashSigAlgoSz); -} - -void InitSuitesHashSigAlgo_ex(byte* hashSigAlgo, int haveECDSAsig, - int haveRSAsig, int haveFalconSig, int haveDilithiumSig, int haveAnon, - int tls1_2, int keySz, word16* len) -{ - int have = 0; - - if (haveECDSAsig) have |= SIG_ECDSA; - if (haveRSAsig) have |= SIG_RSA; - if (haveFalconSig) have |= SIG_FALCON; - if (haveDilithiumSig) have |= SIG_DILITHIUM; - if (haveAnon) have |= SIG_ANON; - - InitSuitesHashSigAlgo_ex2(hashSigAlgo, have, tls1_2, keySz, len); -} - int AllocateCtxSuites(WOLFSSL_CTX* ctx) { if (ctx->suites == NULL) { @@ -3238,6 +3282,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, (void)haveStaticRSA; (void)haveStaticECC; (void)haveECC; + (void)haveECDSAsig; (void)side; (void)haveRSA; /* some builds won't read */ (void)haveRSAsig; /* non ecc builds won't read */ @@ -4262,18 +4307,27 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suiteSz = idx; if (suites->hashSigAlgoSz == 0) { - int haveSig = 0; - haveSig |= (haveRSAsig | haveRSA) ? SIG_RSA : 0; - haveSig |= (haveECDSAsig | haveECC) ? SIG_ECDSA : 0; - #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - haveSig |= (haveECDSAsig | haveECC) ? SIG_SM2 : 0; - #endif - haveSig |= haveFalconSig ? SIG_FALCON : 0; - haveSig |= haveDilithiumSig ? SIG_DILITHIUM : 0; - haveSig &= ~SIG_ANON; - InitSuitesHashSigAlgo_ex2(suites->hashSigAlgo, haveSig, tls1_2, keySz, + InitSuitesHashSigAlgo(suites->hashSigAlgo, SIG_ALL, tls1_2, keySz, &suites->hashSigAlgoSz); } + + /* Moved to the end as we set some of the vars but never use them */ + (void)tls; /* shut up compiler */ + (void)tls1_2; + (void)dtls; + (void)haveDH; + (void)havePSK; + (void)haveStaticRSA; + (void)haveStaticECC; + (void)haveECC; + (void)haveECDSAsig; + (void)side; + (void)haveRSA; /* some builds won't read */ + (void)haveRSAsig; /* non ecc builds won't read */ + (void)haveAnon; /* anon ciphers optional */ + (void)haveNull; + (void)haveFalconSig; + (void)haveDilithiumSig; } #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) || \ @@ -4331,13 +4385,17 @@ void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType) } break; #endif -#ifdef HAVE_PQC +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) case PQC_SA_MAJOR: - /* Hash performed as part of sign/verify operation. */ + /* Hash performed as part of sign/verify operation. + * However, if we want a dual alg signature with a + * classic algorithm as alternative, we need an explicit + * hash algo here. + */ #ifdef HAVE_FALCON if (input[1] == FALCON_LEVEL1_SA_MINOR) { *hsType = falcon_level1_sa_algo; - *hashAlgo = sha512_mac; + *hashAlgo = sha256_mac; } else if (input[1] == FALCON_LEVEL5_SA_MINOR) { *hsType = falcon_level5_sa_algo; @@ -4347,11 +4405,11 @@ void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType) #ifdef HAVE_DILITHIUM if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) { *hsType = dilithium_level2_sa_algo; - *hashAlgo = sha512_mac; + *hashAlgo = sha256_mac; } else if (input[1] == DILITHIUM_LEVEL3_SA_MINOR) { *hsType = dilithium_level3_sa_algo; - *hashAlgo = sha512_mac; + *hashAlgo = sha384_mac; } else if (input[1] == DILITHIUM_LEVEL5_SA_MINOR) { *hsType = dilithium_level5_sa_algo; @@ -4852,14 +4910,14 @@ int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (key && ret == WC_PENDING_E) { + if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ /* For positive response return in outSz */ if (ret > 0) { - *outSz = ret; + *outSz = (word32)ret; ret = 0; } @@ -4872,7 +4930,7 @@ int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo, int hashAlgo, RsaKey* key, buffer* keyBufInfo) { - int ret = SIG_VERIFY_E; + int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E); #ifdef HAVE_PK_CALLBACKS const byte* keyBuf = NULL; @@ -4928,7 +4986,7 @@ int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo, !defined(WOLFSSL_RENESAS_TSIP_TLS) else #else - if (!ssl->ctx->RsaVerifyCb || ret == CRYPTOCB_UNAVAILABLE) + if (!ssl->ctx->RsaVerifyCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif #endif /*HAVE_PK_CALLBACKS */ { @@ -4937,7 +4995,7 @@ int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5010,7 +5068,7 @@ int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz, TypeHash(hashAlgo), mgf, keyBuf, keySz, ctx); if (ret > 0) { - ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret, + ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, (word32)ret, hashType); if (ret != 0) { ret = VERIFY_CERT_ERROR; @@ -5028,7 +5086,7 @@ int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz, ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret, hashType); #else - ret = wc_RsaPSS_CheckPadding_ex(plain, plainSz, out, ret, + ret = wc_RsaPSS_CheckPadding_ex(plain, plainSz, out, (word32)ret, hashType, -1, mp_count_bits(&key->n)); #endif @@ -5075,7 +5133,7 @@ int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (key && ret == WC_PENDING_E) { + if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5135,7 +5193,7 @@ int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, word32* outSz, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5155,7 +5213,7 @@ int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, word32* outSz, int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz, RsaKey* key, buffer* keyBufInfo) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); #ifdef HAVE_PK_CALLBACKS const byte* keyBuf = NULL; word32 keySz = 0; @@ -5187,7 +5245,7 @@ int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz, !defined(WOLFSSL_RENESAS_TSIP_TLS) else #else - if (!ssl->ctx->RsaEncCb || ret == CRYPTOCB_UNAVAILABLE) + if (!ssl->ctx->RsaEncCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif #endif /* HAVE_PK_CALLBACKS */ { @@ -5196,14 +5254,14 @@ int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ /* For positive response return in outSz */ if (ret > 0) { - *outSz = ret; + *outSz = (word32)ret; ret = 0; } @@ -5256,7 +5314,7 @@ int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, ret = ssl->ctx->EccSignCb(ssl, in, inSz, out, outSz, keyBuf, keySz, ctx); #if defined(WOLFSSL_RENESAS_TSIP_TLS) - if (ret == CRYPTOCB_UNAVAILABLE) { + if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { ret = wc_ecc_sign_hash(in, inSz, out, outSz, ssl->rng, key); } #endif /* WOLFSSL_RENESAS_TSIP_TLS */ @@ -5269,7 +5327,7 @@ int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (key && ret == WC_PENDING_E) { + if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5282,7 +5340,7 @@ int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out, word32 outSz, ecc_key* key, buffer* keyBufInfo) { - int ret = SIG_VERIFY_E; + int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E); #ifdef HAVE_PK_CALLBACKS const byte* keyBuf = NULL; word32 keySz = 0; @@ -5316,7 +5374,7 @@ int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out, !defined(WOLFSSL_MAXQ108X) else #else - if (!ssl->ctx->EccVerifyCb || ret == CRYPTOCB_UNAVAILABLE) + if (!ssl->ctx->EccVerifyCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif #endif /* HAVE_PK_CALLBACKS */ { @@ -5325,7 +5383,7 @@ int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } else @@ -5398,7 +5456,7 @@ int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key, ecc_key* pub_key, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5457,7 +5515,7 @@ int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer) #ifdef HAVE_PK_CALLBACKS if (ssl->ctx->EccKeyGenCb) { void* ctx = wolfSSL_GetEccKeyGenCtx(ssl); - ret = ssl->ctx->EccKeyGenCb(ssl, key, keySz, ecc_curve, ctx); + ret = ssl->ctx->EccKeyGenCb(ssl, key, (unsigned int)keySz, ecc_curve, ctx); } else #endif @@ -5475,7 +5533,7 @@ int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer) /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5515,7 +5573,7 @@ int Sm2wSm3Verify(WOLFSSL* ssl, const byte* id, word32 idSz, const byte* sig, word32 sigSz, const byte* msg, word32 msgSz, ecc_key* key, buffer* keyBufInfo) { - int ret = SIG_VERIFY_E; + int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E); byte hash[WC_SM3_DIGEST_SIZE]; (void)ssl; @@ -5638,7 +5696,7 @@ int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5712,7 +5770,7 @@ int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } else @@ -5738,7 +5796,6 @@ int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, */ static int X25519GetKey(WOLFSSL* ssl, curve25519_key** otherKey) { - int ret = NO_PEER_KEY; struct curve25519_key* tmpKey = NULL; if (ssl == NULL || otherKey == NULL) { @@ -5761,10 +5818,11 @@ int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, if (tmpKey) { *otherKey = (curve25519_key *)tmpKey; - ret = 0; + return 0; + } + else { + return NO_PEER_KEY; } - - return ret; } #endif /* HAVE_PK_CALLBACKS */ @@ -5808,7 +5866,7 @@ static int X25519SharedSecret(WOLFSSL* ssl, curve25519_key* priv_key, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5854,7 +5912,7 @@ static int X25519MakeKey(WOLFSSL* ssl, curve25519_key* key, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -5962,7 +6020,7 @@ int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -6036,7 +6094,7 @@ int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } else @@ -6062,7 +6120,6 @@ int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, */ static int X448GetKey(WOLFSSL* ssl, curve448_key** otherKey) { - int ret = NO_PEER_KEY; struct curve448_key* tmpKey = NULL; if (ssl == NULL || otherKey == NULL) { @@ -6084,10 +6141,11 @@ int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, if (tmpKey) { *otherKey = (curve448_key *)tmpKey; - ret = 0; + return 0; + } + else { + return NO_PEER_KEY; } - - return ret; } #endif /* HAVE_PK_CALLBACKS */ @@ -6132,7 +6190,7 @@ static int X448SharedSecret(WOLFSSL* ssl, curve448_key* priv_key, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -6177,7 +6235,7 @@ static int X448MakeKey(WOLFSSL* ssl, curve448_key* key, curve448_key* peer) /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &key->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -6214,7 +6272,7 @@ int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey, ret = ssl->ctx->DhGenerateKeyPairCb(dhKey, ssl->rng, priv, privSz, pub, pubSz); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif { PRIVATE_KEY_UNLOCK(); @@ -6224,7 +6282,7 @@ int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -6294,7 +6352,7 @@ int DhAgree(WOLFSSL* ssl, DhKey* dhKey, /* Handle async pending response */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev); } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -6704,14 +6762,12 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #ifdef HAVE_ECC ssl->options.minEccKeySz = ctx->minEccKeySz; #endif -#ifdef HAVE_PQC #ifdef HAVE_FALCON ssl->options.minFalconKeySz = ctx->minFalconKeySz; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM ssl->options.minDilithiumKeySz = ctx->minDilithiumKeySz; #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) ssl->options.verifyDepth = ctx->verifyDepth; #endif @@ -6754,16 +6810,50 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #ifdef WOLFSSL_TLS13 ssl->buffers.certChainCnt = ctx->certChainCnt; #endif +#ifndef WOLFSSL_BLIND_PRIVATE_KEY ssl->buffers.key = ctx->privateKey; +#else + if (ctx->privateKey != NULL) { + AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ctx->privateKey->length, ctx->privateKey->type, + ctx->privateKey->heap); + ssl->buffers.weOwnKey = 1; + /* Blind the private key for the SSL with new random mask. */ + wolfssl_priv_der_unblind(ssl->buffers.key, ctx->privateKeyMask); + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + if (ret != 0) { + return ret; + } + } +#endif ssl->buffers.keyType = ctx->privateKeyType; ssl->buffers.keyId = ctx->privateKeyId; ssl->buffers.keyLabel = ctx->privateKeyLabel; ssl->buffers.keySz = ctx->privateKeySz; ssl->buffers.keyDevId = ctx->privateKeyDevId; #ifdef WOLFSSL_DUAL_ALG_CERTS - ssl->buffers.altKey = ctx->altPrivateKey; - ssl->buffers.altKeySz = ctx->altPrivateKeySz; - ssl->buffers.altKeyType = ctx->altPrivateKeyType; +#ifndef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.altKey = ctx->altPrivateKey; +#else + if (ctx->altPrivateKey != NULL) { + AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, + ctx->altPrivateKey->length, ctx->altPrivateKey->type, + ctx->altPrivateKey->heap); + /* Blind the private key for the SSL with new random mask. */ + wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask); + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, + &ssl->buffers.altKeyMask); + if (ret != 0) { + return ret; + } + } +#endif + ssl->buffers.altKeyType = ctx->altPrivateKeyType; + ssl->buffers.altKeyId = ctx->altPrivateKeyId; + ssl->buffers.altKeyLabel = ctx->altPrivateKeyLabel; + ssl->buffers.altKeySz = ctx->altPrivateKeySz; + ssl->buffers.altKeyDevId = ctx->altPrivateKeyDevId; #endif /* WOLFSSL_DUAL_ALG_CERTS */ #endif #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \ @@ -6951,7 +7041,7 @@ void FreeHandshakeHashes(WOLFSSL* ssl) int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, HS_Hashes** destination) { - int ret = 0; + int ret; HS_Hashes* tmpHashes; if (source == NULL) @@ -6961,7 +7051,11 @@ int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, tmpHashes = ssl->hsHashes; ssl->hsHashes = NULL; - InitHandshakeHashes(ssl); + ret = InitHandshakeHashes(ssl); + if (ret != 0) { + WOLFSSL_MSG_EX("InitHandshakeHashes failed. err = %d", ret); + return ret; + } *destination = ssl->hsHashes; ssl->hsHashes = tmpHashes; @@ -6969,50 +7063,50 @@ int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, /* now copy the source contents to the destination */ #ifndef NO_OLD_TLS #ifndef NO_SHA - ret = wc_ShaCopy(&source->hashSha, &(*destination)->hashSha); + ret = wc_ShaCopy(&source->hashSha, &(*destination)->hashSha); #endif #ifndef NO_MD5 - if (ret == 0) - ret = wc_Md5Copy(&source->hashMd5, &(*destination)->hashMd5); + if (ret == 0) + ret = wc_Md5Copy(&source->hashMd5, &(*destination)->hashMd5); #endif #endif /* !NO_OLD_TLS */ #ifndef NO_SHA256 - if (ret == 0) - ret = wc_Sha256Copy(&source->hashSha256, - &(*destination)->hashSha256); + if (ret == 0) + ret = wc_Sha256Copy(&source->hashSha256, + &(*destination)->hashSha256); #endif #ifdef WOLFSSL_SHA384 - if (ret == 0) - ret = wc_Sha384Copy(&source->hashSha384, - &(*destination)->hashSha384); + if (ret == 0) + ret = wc_Sha384Copy(&source->hashSha384, + &(*destination)->hashSha384); #endif #ifdef WOLFSSL_SHA512 - if (ret == 0) - ret = wc_Sha512Copy(&source->hashSha512, - &(*destination)->hashSha512); + if (ret == 0) + ret = wc_Sha512Copy(&source->hashSha512, + &(*destination)->hashSha512); #endif #ifdef WOLFSSL_SM3 - if (ret == 0) - ret = wc_Sm3Copy(&source->hashSm3, - &(*destination)->hashSm3); + if (ret == 0) + ret = wc_Sm3Copy(&source->hashSm3, + &(*destination)->hashSm3); #endif #if (defined(HAVE_ED25519) || defined(HAVE_ED448) || \ (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \ !defined(WOLFSSL_NO_CLIENT_AUTH) - if (ret == 0 && source->messages != NULL) { - (*destination)->messages = (byte*)XMALLOC(source->length, ssl->heap, - DYNAMIC_TYPE_HASHES); - (*destination)->length = source->length; - (*destination)->prevLen = source->prevLen; + if (ret == 0 && source->messages != NULL) { + (*destination)->messages = (byte*)XMALLOC(source->length, ssl->heap, + DYNAMIC_TYPE_HASHES); + (*destination)->length = source->length; + (*destination)->prevLen = source->prevLen; - if ((*destination)->messages == NULL) { - ret = MEMORY_E; - } - else { - XMEMCPY((*destination)->messages, source->messages, - source->length); - } + if ((*destination)->messages == NULL) { + ret = MEMORY_E; + } + else { + XMEMCPY((*destination)->messages, source->messages, + source->length); } + } #endif return ret; @@ -7139,6 +7233,8 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl_hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap)); ctx_hint = ((WOLFSSL_HEAP_HINT*)(ctx->heap)); + ssl_hint->memory = ctx_hint->memory; + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* lock and check IO count / handshake count */ if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); @@ -7166,7 +7262,6 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) } ctx_hint->memory->curIO++; ctx_hint->memory->curHa++; - ssl_hint->memory = ctx_hint->memory; ssl_hint->haFlag = 1; wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); @@ -7202,6 +7297,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) } wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); } + #endif /* !WOLFSSL_STATIC_MEMORY_LEAN */ #ifdef WOLFSSL_HEAP_TEST } #endif @@ -7573,6 +7669,9 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) defined(WOLFSSL_SSLKEYLOGFILE) && defined(WOLFSSL_TLS13) (void)wolfSSL_set_tls13_secret_cb(ssl, tls13ShowSecrets, NULL); #endif +#if defined(HAVE_SECRET_CALLBACK) && defined(SHOW_SECRETS) + (void)wolfSSL_set_secret_cb(ssl, tlsShowSecrets, NULL); +#endif #ifdef WOLFSSL_DUAL_ALG_CERTS ssl->sigSpec = ctx->sigSpec; ssl->sigSpecSz = ctx->sigSpecSz; @@ -7647,7 +7746,6 @@ void FreeKey(WOLFSSL* ssl, int type, void** pKey) wc_curve448_free((curve448_key*)*pKey); break; #endif /* HAVE_CURVE448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case DYNAMIC_TYPE_FALCON: wc_falcon_free((falcon_key*)*pKey); @@ -7658,7 +7756,6 @@ void FreeKey(WOLFSSL* ssl, int type, void** pKey) wc_dilithium_free((dilithium_key*)*pKey); break; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ #ifndef NO_DH case DYNAMIC_TYPE_DH: wc_FreeDhKey((DhKey*)*pKey); @@ -7676,7 +7773,7 @@ void FreeKey(WOLFSSL* ssl, int type, void** pKey) int AllocKey(WOLFSSL* ssl, int type, void** pKey) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); int sz = 0; #ifdef HAVE_ECC ecc_key* eccKey; @@ -7695,7 +7792,7 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) WOLFSSL_MSG("Key already present!"); #ifdef WOLFSSL_ASYNC_CRYPT /* allow calling this again for async reentry */ - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { return 0; } #endif @@ -7734,7 +7831,6 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) sz = sizeof(curve448_key); break; #endif /* HAVE_CURVE448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case DYNAMIC_TYPE_FALCON: sz = sizeof(falcon_key); @@ -7745,7 +7841,6 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) sz = sizeof(dilithium_key); break; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ #ifndef NO_DH case DYNAMIC_TYPE_DH: sz = sizeof(DhKey); @@ -7809,7 +7904,6 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) ret = 0; break; #endif /* HAVE_CURVE448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case DYNAMIC_TYPE_FALCON: wc_falcon_init_ex((falcon_key*)*pKey, ssl->heap, ssl->devId); @@ -7822,7 +7916,6 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) ret = 0; break; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ #ifdef HAVE_CURVE448 case DYNAMIC_TYPE_CURVE448: wc_curve448_init((curve448_key*)*pKey); @@ -7848,8 +7941,7 @@ int AllocKey(WOLFSSL* ssl, int type, void** pKey) #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \ defined(HAVE_CURVE25519) || defined(HAVE_ED448) || \ - defined(HAVE_CURVE448) || (defined(HAVE_PQC) && defined(HAVE_FALCON)) || \ - (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) + defined(HAVE_CURVE448) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) static int ReuseKey(WOLFSSL* ssl, int type, void* pKey) { int ret = 0; @@ -7895,12 +7987,18 @@ static int ReuseKey(WOLFSSL* ssl, int type, void* pKey) ret = wc_curve448_init((curve448_key*)pKey); break; #endif /* HAVE_CURVE448 */ - #if defined(HAVE_PQC) && defined(HAVE_FALCON) + #if defined(HAVE_FALCON) case DYNAMIC_TYPE_FALCON: wc_falcon_free((falcon_key*)pKey); ret = wc_falcon_init((falcon_key*)pKey); break; - #endif /* HAVE_PQC && HAVE_FALCON */ + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) + case DYNAMIC_TYPE_DILITHIUM: + wc_dilithium_free((dilithium_key*)pKey); + ret = wc_dilithium_init((dilithium_key*)pKey); + break; + #endif /* HAVE_DILITHIUM */ #ifndef NO_DH case DYNAMIC_TYPE_DH: wc_FreeDhKey((DhKey*)pKey); @@ -8194,7 +8292,7 @@ void SSL_ResourceFree(WOLFSSL* ssl) } #endif #endif -#if defined(HAVE_PQC) && defined(HAVE_FALCON) +#if defined(HAVE_FALCON) FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; #endif @@ -8277,14 +8375,17 @@ void SSL_ResourceFree(WOLFSSL* ssl) /* avoid dereferencing a test value */ if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) { #endif + void* heap = ssl->ctx ? ssl->ctx->heap : ssl->heap; + #ifndef WOLFSSL_STATIC_MEMORY_LEAN WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap; WOLFSSL_HEAP* ctx_heap; - void* heap = ssl->ctx ? ssl->ctx->heap : ssl->heap; ctx_heap = ssl_hint->memory; + #ifndef SINGLE_THREADED if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); } + #endif ctx_heap->curIO--; if (FreeFixedIO(ctx_heap, &(ssl_hint->outBuf)) != 1) { WOLFSSL_MSG("Error freeing fixed output buffer"); @@ -8292,15 +8393,20 @@ void SSL_ResourceFree(WOLFSSL* ssl) if (FreeFixedIO(ctx_heap, &(ssl_hint->inBuf)) != 1) { WOLFSSL_MSG("Error freeing fixed output buffer"); } - if (ssl_hint->haFlag && ctx_heap->curHa > 0) { /* check if handshake count has been decreased*/ + + /* check if handshake count has been decreased*/ + if (ssl_hint->haFlag && ctx_heap->curHa > 0) { ctx_heap->curHa--; } + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_heap->memory_mutex)); + #endif /* check if tracking stats */ if (ctx_heap->flag & WOLFMEM_TRACK_STATS) { XFREE(ssl_hint->stats, heap, DYNAMIC_TYPE_SSL); } + #endif /* !WOLFSSL_STATIC_MEMORY_LEAN */ XFREE(ssl->heap, heap, DYNAMIC_TYPE_SSL); #ifdef WOLFSSL_HEAP_TEST } @@ -8437,10 +8543,10 @@ void FreeHandshakeResources(WOLFSSL* ssl) FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key); ssl->peerEd448KeyPresent = 0; #endif /* HAVE_ED448 */ -#if defined(HAVE_PQC) && defined(HAVE_FALCON) +#if defined(HAVE_FALCON) FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; -#endif /* HAVE_PQC */ +#endif /* HAVE_FALCON */ } #ifdef HAVE_ECC @@ -8503,8 +8609,14 @@ void FreeHandshakeResources(WOLFSSL* ssl) } #endif /* !NO_DH */ -#ifndef NO_CERTS - wolfSSL_UnloadCertsKeys(ssl); +#if !defined(NO_CERTS) && !defined(OPENSSL_EXTRA) && \ + !defined(WOLFSSL_WPAS_SMALL) +#ifndef WOLFSSL_POST_HANDSHAKE_AUTH + if (ssl->options.side != WOLFSSL_CLIENT_END) +#endif + { + wolfSSL_UnloadCertsKeys(ssl); + } #endif #ifdef HAVE_PK_CALLBACKS #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) @@ -8562,14 +8674,20 @@ void FreeHandshakeResources(WOLFSSL* ssl) WOLFSSL_HEAP* ctx_heap; ctx_heap = ssl_hint->memory; + #ifndef SINGLE_THREADED if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); } + #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN if (ctx_heap->curHa > 0) { ctx_heap->curHa--; } ssl_hint->haFlag = 0; /* set to zero since handshake has been dec */ + #endif + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_heap->memory_mutex)); + #endif #ifdef WOLFSSL_HEAP_TEST } #endif @@ -9422,7 +9540,7 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) int inputSz, sendSz; input = pool->raw; - inputSz = pool->sz; + inputSz = (int)pool->sz; sendSz = inputSz + cipherExtraData(ssl); #ifdef HAVE_SECURE_RENEGOTIATION @@ -9686,7 +9804,12 @@ ProtocolVersion MakeDTLSv1_3(void) #elif defined(FREERTOS) - #include "task.h" + #ifdef PLATFORMIO + #include + #include + #else + #include "task.h" + #endif unsigned int LowResTimer(void) { @@ -9768,7 +9891,12 @@ ProtocolVersion MakeDTLSv1_3(void) word32 LowResTimer(void) { - return k_uptime_get() / 1000; + int64_t t; + #if defined(CONFIG_ARCH_POSIX) + k_cpu_idle(); + #endif + t = k_uptime_get(); /* returns current uptime in milliseconds */ + return (word32)(t / 1000); } #elif defined(WOLFSSL_LINUXKM) @@ -9861,7 +9989,7 @@ int HashRaw(WOLFSSL* ssl, const byte* data, int sz) #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_StoreMessage(ssl, data, sz); - if (ret != 0 && ret != CRYPTOCB_UNAVAILABLE) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return ret; } #endif /* WOLFSSL_RENESAS_TSIP_TLS */ @@ -9876,7 +10004,7 @@ int HashRaw(WOLFSSL* ssl, const byte* data, int sz) if (IsAtLeastTLSv1_2(ssl)) { #ifndef NO_SHA256 - ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, data, sz); + ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, data, (word32)sz); if (ret != 0) return ret; #ifdef WOLFSSL_DEBUG_TLS @@ -9886,7 +10014,7 @@ int HashRaw(WOLFSSL* ssl, const byte* data, int sz) #endif #endif #ifdef WOLFSSL_SHA384 - ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, data, sz); + ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, data, (word32)sz); if (ret != 0) return ret; #ifdef WOLFSSL_DEBUG_TLS @@ -9896,7 +10024,7 @@ int HashRaw(WOLFSSL* ssl, const byte* data, int sz) #endif #endif #ifdef WOLFSSL_SHA512 - ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, data, sz); + ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, data, (word32)sz); if (ret != 0) return ret; #ifdef WOLFSSL_DEBUG_TLS @@ -10444,7 +10572,7 @@ void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree) ssl->buffers.inputBuffer.dynamicFlag = 0; ssl->buffers.inputBuffer.offset = 0; ssl->buffers.inputBuffer.idx = 0; - ssl->buffers.inputBuffer.length = usedLength; + ssl->buffers.inputBuffer.length = (word32)usedLength; } int SendBuffered(WOLFSSL* ssl) @@ -10561,8 +10689,7 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) #else const byte align = WOLFSSL_GENERAL_ALIGNMENT; #endif - int newSz = size + ssl->buffers.outputBuffer.idx + - ssl->buffers.outputBuffer.length; + word32 newSz; #if WOLFSSL_GENERAL_ALIGNMENT > 0 /* the encrypted data will be offset from the front of the buffer by @@ -10573,7 +10700,15 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size) align *= 2; #endif - tmp = (byte*)XMALLOC(newSz + align, ssl->heap, DYNAMIC_TYPE_OUT_BUFFER); + if (! WC_SAFE_SUM_WORD32(ssl->buffers.outputBuffer.idx, + ssl->buffers.outputBuffer.length, newSz)) + return BUFFER_E; + if (! WC_SAFE_SUM_WORD32(newSz, (word32)size, newSz)) + return BUFFER_E; + if (! WC_SAFE_SUM_WORD32(newSz, align, newSz)) + return BUFFER_E; + tmp = (byte*)XMALLOC(newSz, ssl->heap, DYNAMIC_TYPE_OUT_BUFFER); + newSz -= align; WOLFSSL_MSG("growing output buffer"); if (tmp == NULL) @@ -10692,7 +10827,7 @@ int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength) ssl->buffers.inputBuffer.buffer = tmp; ssl->buffers.inputBuffer.bufferSize = size + usedLength; ssl->buffers.inputBuffer.idx = 0; - ssl->buffers.inputBuffer.length = usedLength; + ssl->buffers.inputBuffer.length = (word32)usedLength; return 0; } @@ -10996,7 +11131,7 @@ static int MsgCheckBoundary(const WOLFSSL* ssl, byte type, * @param ssl The current connection * @param type The enum HandShakeType of the current message * @param msgSz Size of the current message - * @return + * @return int (less than 0 on fail, 0 on success) */ int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type, word32 msgSz) { @@ -11152,7 +11287,9 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, /* version 1.3 already negotiated */ if (ssl->options.tls1_3) { ret = GetDtls13RecordHeader(ssl, inOutIdx, rh, size); - if (ret == 0 || ret != SEQUENCE_ERROR || ret != DTLS_CID_ERROR) + if (ret == 0 || + ret != WC_NO_ERR_TRACE(SEQUENCE_ERROR) || + ret != WC_NO_ERR_TRACE(DTLS_CID_ERROR)) return ret; } @@ -11174,7 +11311,7 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, if (ssl->buffers.inputBuffer.length - *inOutIdx < DTLS_RECORD_HEADER_SZ) { ret = GetInputData(ssl, DTLS_RECORD_HEADER_SZ); /* Check if Dtls13RtxTimeout(ssl) returned socket error */ - if (ret == SOCKET_ERROR_E) + if (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) return ret; if (ret != 0) return LENGTH_ERROR; @@ -11243,7 +11380,13 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, ssl->fuzzerCb(ssl, ssl->buffers.inputBuffer.buffer + *inOutIdx, RECORD_HEADER_SZ, FUZZ_HEAD, ssl->fuzzerCtx); #endif - XMEMCPY(rh, ssl->buffers.inputBuffer.buffer + *inOutIdx, RECORD_HEADER_SZ); + /* Set explicitly rather than make assumptions on struct layout */ + rh->type = ssl->buffers.inputBuffer.buffer[*inOutIdx]; + rh->pvMajor = ssl->buffers.inputBuffer.buffer[*inOutIdx + 1]; + rh->pvMinor = ssl->buffers.inputBuffer.buffer[*inOutIdx + 2]; + rh->length[0] = ssl->buffers.inputBuffer.buffer[*inOutIdx + 3]; + rh->length[1] = ssl->buffers.inputBuffer.buffer[*inOutIdx + 4]; + *inOutIdx += RECORD_HEADER_SZ; ato16(rh->length, size); } @@ -11306,7 +11449,20 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, } } #endif /* WOLFSSL_DTLS13 */ - else { + /* Don't care about protocol version being lower than expected on alerts + * sent back before version negotitation. */ + else if (!(ssl->options.side == WOLFSSL_CLIENT_END && + ssl->options.connectState == CLIENT_HELLO_SENT && + rh->type == alert && + rh->pvMajor == ssl->version.major && + #ifdef WOLFSSL_DTLS + ((ssl->options.dtls && rh->pvMinor == DTLS_MINOR) || + (!ssl->options.dtls && + rh->pvMinor < ssl->version.minor)) + #else + rh->pvMinor < ssl->version.minor + #endif + )) { WOLFSSL_MSG("SSL version error"); WOLFSSL_ERROR_VERBOSE(VERSION_ERROR); return VERSION_ERROR; /* only use requested version */ @@ -12243,53 +12399,77 @@ int CipherRequires(byte first, byte second, int requirement) *.z.com matches y.z.com but not x.y.z.com return 1 on success */ -int MatchDomainName(const char* pattern, int len, const char* str) +int MatchDomainName(const char* pattern, int patternLen, const char* str, + word32 strLen) { int ret = 0; - if (pattern == NULL || str == NULL || len <= 0) + if (pattern == NULL || str == NULL || patternLen <= 0 || strLen == 0) return 0; - while (len > 0) { - - char p = (char)XTOLOWER((unsigned char)*pattern++); + while (patternLen > 0) { + /* Get the next pattern char to evaluate */ + char p = (char)XTOLOWER((unsigned char)*pattern); if (p == '\0') break; + pattern++; + if (p == '*') { char s; + /* We will always match '*' */ + patternLen--; - while (--len > 0) { + /* Consume any extra '*' chars until the next non '*' char. */ + while (patternLen > 0) { p = (char)XTOLOWER((unsigned char)*pattern); pattern++; + if (p == '\0' && patternLen > 0) + return 0; if (p != '*') break; + + patternLen--; } - if (len == 0) - p = '\0'; + /* Consume str until we reach next char in pattern after '*' or + * end of string */ + while (strLen > 0) { + s = (char)XTOLOWER((unsigned char) *str); + str++; + strLen--; + + /* p is next char in pattern after '*', or '*' if '*' is the + * last char in the pattern (in which case patternLen is 1) */ + if ( ((s == p) && (patternLen > 0))) { + /* We had already counted the '*' as matched, this means + * we also matched the next non '*' char in pattern */ + patternLen--; + break; + } - while ( (s = (char)XTOLOWER((unsigned char) *str)) != '\0') { - if (s == p) + /* If strlen is 0, we have consumed the entire string. Count that + * as a match of '*' */ + if (strLen == 0) { break; + } + if (s == '.') return 0; - str++; } } else { + /* Simple case, pattern match exactly */ if (p != (char)XTOLOWER((unsigned char) *str)) return 0; - } - - if (len > 0) { str++; - len--; + strLen--; + patternLen--; } } - if (*str == '\0' && len == 0) { + if (strLen == 0 && patternLen == 0) { ret = 1; /* success */ } @@ -12301,14 +12481,16 @@ int MatchDomainName(const char* pattern, int len, const char* str) * Fail if there are wild patterns and they didn't match. * Check the common name if no alternative names matched. * - * dCert Decoded cert to get the alternative names from. - * domain Domain name to compare against. - * checkCN Whether to check the common name. - * returns 1 : match was found. - * 0 : no match found. - * -1 : No matches and wild pattern match failed. + * dCert Decoded cert to get the alternative names from. + * domain Domain name to compare against. + * domainLen Length of the domain name. + * checkCN Whether to check the common name. + * returns 1 : match was found. + * 0 : no match found. + * -1 : No matches and wild pattern match failed. */ -int CheckForAltNames(DecodedCert* dCert, const char* domain, int* checkCN) +int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, + int* checkCN) { int match = 0; DNS_entry* altName = NULL; @@ -12336,10 +12518,10 @@ int CheckForAltNames(DecodedCert* dCert, const char* domain, int* checkCN) #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ { buf = altName->name; - len = altName->len; + len = (word32)altName->len; } - if (MatchDomainName(buf, len, domain)) { + if (MatchDomainName(buf, (int)len, domain, domainLen)) { match = 1; if (checkCN != NULL) { *checkCN = 0; @@ -12371,12 +12553,11 @@ int CheckForAltNames(DecodedCert* dCert, const char* domain, int* checkCN) int CheckHostName(DecodedCert* dCert, const char *domainName, size_t domainNameLen) { int checkCN; - int ret = DOMAIN_NAME_MISMATCH; - - /* Assume name is NUL terminated. */ - (void)domainNameLen; + int ret = WC_NO_ERR_TRACE(DOMAIN_NAME_MISMATCH); - if (CheckForAltNames(dCert, domainName, &checkCN) != 1) { + if (CheckForAltNames(dCert, domainName, (word32)domainNameLen, + &checkCN) != 1) { + ret = DOMAIN_NAME_MISMATCH; WOLFSSL_MSG("DomainName match on alt names failed"); } else { @@ -12386,10 +12567,11 @@ int CheckHostName(DecodedCert* dCert, const char *domainName, size_t domainNameL #ifndef WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY if (checkCN == 1) { if (MatchDomainName(dCert->subjectCN, dCert->subjectCNLen, - domainName) == 1) { + domainName, (word32)domainNameLen) == 1) { ret = 0; } else { + ret = DOMAIN_NAME_MISMATCH; WOLFSSL_MSG("DomainName match on common name failed"); } } @@ -12412,7 +12594,7 @@ static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain, { if (chain->count < MAX_CHAIN_DEPTH && certSz < MAX_X509_SIZE) { - chain->certs[chain->count].length = certSz; + chain->certs[chain->count].length = (int)certSz; XMEMCPY(chain->certs[chain->count].buffer, certBuf, certSz); chain->count++; } @@ -12426,13 +12608,20 @@ static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain, defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType) { + if (name->dynamicName) { + XFREE(name->name, name->heap, DYNAMIC_TYPE_X509); + name->name = name->staticName; + name->dynamicName = 0; + } + if (nameType == SUBJECT) { XSTRNCPY(name->name, dCert->subject, ASN_NAME_MAX); name->name[ASN_NAME_MAX - 1] = '\0'; name->sz = (int)XSTRLEN(name->name) + 1; #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) name->rawLen = min(dCert->subjectRawLen, ASN_NAME_MAX); - XMEMCPY(name->raw, dCert->subjectRaw, name->rawLen); + if (name->rawLen > 0) + XMEMCPY(name->raw, dCert->subjectRaw, name->rawLen); #endif } else { @@ -12442,59 +12631,44 @@ void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType) #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) \ && (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)) name->rawLen = min(dCert->issuerRawLen, ASN_NAME_MAX); - if (name->rawLen) { + if (name->rawLen > 0) { XMEMCPY(name->raw, dCert->issuerRaw, name->rawLen); } #endif } } - -#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ - !defined(IGNORE_NAME_CONSTRAINTS) -/* copies over additional alt names such as dirName - * returns 0 on success - */ -static int CopyAdditionalAltNames(DNS_entry** to, DNS_entry* from, int type, - void* heap) +static int CopyAltNames(DNS_entry** to, DNS_entry* from, int type, void* heap) { - DNS_entry* cur = from; + /* Copy from to the beginning of to */ + DNS_entry** prev_next = to; + DNS_entry* next; if (to == NULL) { return BAD_FUNC_ARG; } - while (cur != NULL) { - if (cur->type == type) { - DNS_entry* dnsEntry; - int strLen = cur->len; + next = *to; - dnsEntry = AltNameNew(heap); - if (dnsEntry == NULL) { - WOLFSSL_MSG("\tOut of Memory"); - return MEMORY_E; - } + for (; from != NULL; from = from->next) { + DNS_entry* dnsEntry; - dnsEntry->type = type; - dnsEntry->name = (char*)XMALLOC(strLen + 1, heap, - DYNAMIC_TYPE_ALTNAME); - if (dnsEntry->name == NULL) { - WOLFSSL_MSG("\tOut of Memory"); - XFREE(dnsEntry, heap, DYNAMIC_TYPE_ALTNAME); - return MEMORY_E; - } - dnsEntry->len = strLen; - XMEMCPY(dnsEntry->name, cur->name, strLen); - dnsEntry->name[strLen] = '\0'; + if (type != -1 && from->type != type) + continue; - dnsEntry->next = *to; - *to = dnsEntry; + dnsEntry = AltNameDup(from, heap); + if (dnsEntry == NULL) { + WOLFSSL_MSG("\tOut of Memory"); + return MEMORY_E; } - cur = cur->next; + + dnsEntry->next = next; + *prev_next = dnsEntry; + prev_next = &dnsEntry->next; } + return 0; } -#endif /* OPENSSL_EXTRA */ #ifdef WOLFSSL_CERT_REQ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) @@ -12609,8 +12783,6 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) #endif /* WOLFSSL_CERT_REQ */ /* Copy parts X509 needs from Decoded cert, 0 on success */ -/* The same DecodedCert cannot be copied to WOLFSSL_X509 twice otherwise the - * altNames pointers could be free'd by second x509 still active by first */ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) { int ret = 0; @@ -12690,7 +12862,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) { int minSz; if (dCert->beforeDateLen > 0) { - minSz = min(dCert->beforeDate[1], MAX_DATE_SZ); + minSz = (int)min(dCert->beforeDate[1], MAX_DATE_SZ); x509->notBefore.type = dCert->beforeDate[0]; x509->notBefore.length = minSz; XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz); @@ -12698,7 +12870,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) else x509->notBefore.length = 0; if (dCert->afterDateLen > 0) { - minSz = min(dCert->afterDate[1], MAX_DATE_SZ); + minSz = (int)min(dCert->afterDate[1], MAX_DATE_SZ); x509->notAfter.type = dCert->afterDate[0]; x509->notAfter.length = minSz; XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz); @@ -12711,7 +12883,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) x509->pubKey.buffer = (byte*)XMALLOC( dCert->pubKeySize, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY); if (x509->pubKey.buffer != NULL) { - x509->pubKeyOID = dCert->keyOID; + x509->pubKeyOID = (int)dCert->keyOID; x509->pubKey.length = dCert->pubKeySize; XMEMCPY(x509->pubKey.buffer, dCert->publicKey, dCert->pubKeySize); } @@ -12719,7 +12891,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) ret = MEMORY_E; #if defined(OPENSSL_ALL) if (ret == 0) { - x509->key.pubKeyOID = dCert->keyOID; + x509->key.pubKeyOID = (int)dCert->keyOID; if (!x509->key.algor) { x509->key.algor = wolfSSL_X509_ALGOR_new(); @@ -12757,7 +12929,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) else { XMEMCPY(x509->sig.buffer, dCert->signature, dCert->sigLength); x509->sig.length = dCert->sigLength; - x509->sigOID = dCert->signatureOID; + x509->sigOID = (int)dCert->signatureOID; } #if defined(OPENSSL_ALL) wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm); @@ -12781,19 +12953,21 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) } } - x509->altNames = dCert->altNames; - dCert->weOwnAltNames = 0; + /* add alt names from dCert to X509 */ + if (CopyAltNames(&x509->altNames, dCert->altNames, -1, x509->heap) != 0) { + return MEMORY_E; + } #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ !defined(IGNORE_NAME_CONSTRAINTS) /* add copies of email names from dCert to X509 */ - if (CopyAdditionalAltNames(&x509->altNames, dCert->altEmailNames, + if (CopyAltNames(&x509->altNames, dCert->altEmailNames, ASN_RFC822_TYPE, x509->heap) != 0) { return MEMORY_E; } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if defined(OPENSSL_EXTRA) && !defined(IGNORE_NAME_CONSTRAINTS) /* add copies of alternate directory names from dCert to X509 */ - if (CopyAdditionalAltNames(&x509->altNames, dCert->altDirNames, + if (CopyAltNames(&x509->altNames, dCert->altDirNames, ASN_DIR_TYPE, x509->heap) != 0) { return MEMORY_E; } @@ -12963,23 +13137,40 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) /* Copy over alternative sig and pubkey. In this case we will allocate new * buffers for them as we have no knowledge of when the DecodedCert is * freed. */ - x509->sapkiDer = (byte*)XMALLOC(dCert->sapkiLen, x509->heap, - DYNAMIC_TYPE_X509_EXT); - x509->altSigAlgDer = (byte*)XMALLOC(dCert->altSigAlgLen, x509->heap, + if (dCert->extSapkiSet) { + x509->sapkiDer = (byte*)XMALLOC(dCert->sapkiLen, x509->heap, DYNAMIC_TYPE_X509_EXT); - x509->altSigValDer = (byte*)XMALLOC(dCert->altSigValLen, x509->heap, - DYNAMIC_TYPE_X509_EXT); - if ((x509->sapkiDer != NULL) && (x509->altSigAlgDer != NULL) && - (x509->altSigValDer != NULL)) { - XMEMCPY(x509->sapkiDer, dCert->sapkiDer, dCert->sapkiLen); - XMEMCPY(x509->altSigAlgDer, dCert->altSigAlgDer, dCert->altSigAlgLen); - XMEMCPY(x509->altSigValDer, dCert->altSigValDer, dCert->altSigValLen); - x509->sapkiLen = dCert->sapkiLen; - x509->altSigAlgLen = dCert->altSigAlgLen; - x509->altSigValLen = dCert->altSigValLen; + if (x509->sapkiDer != NULL) { + XMEMCPY(x509->sapkiDer, dCert->sapkiDer, dCert->sapkiLen); + x509->sapkiLen = dCert->sapkiLen; + } + else { + ret = MEMORY_E; + } } - else { - ret = MEMORY_E; + if (dCert->extAltSigAlgSet) { + x509->altSigAlgDer = (byte*)XMALLOC(dCert->altSigAlgLen, x509->heap, + DYNAMIC_TYPE_X509_EXT); + if (x509->altSigAlgDer != NULL) { + XMEMCPY(x509->altSigAlgDer, dCert->altSigAlgDer, + dCert->altSigAlgLen); + x509->altSigAlgLen = dCert->altSigAlgLen; + } + else { + ret = MEMORY_E; + } + } + if (dCert->extAltSigValSet) { + x509->altSigValDer = (byte*)XMALLOC(dCert->altSigValLen, x509->heap, + DYNAMIC_TYPE_X509_EXT); + if (x509->altSigValDer != NULL) { + XMEMCPY(x509->altSigValDer, dCert->altSigValDer, + dCert->altSigValLen); + x509->altSigValLen = dCert->altSigValLen; + } + else { + ret = MEMORY_E; + } } #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -13095,7 +13286,7 @@ static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, const unsigned char* keyDer, unsigned int keySz, int* result, void* ctx) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); WOLFSSL* ssl = (WOLFSSL*)ctx; if (ssl && ssl->ctx->EccVerifyCb) { @@ -13110,7 +13301,7 @@ static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, unsigned char** out, const unsigned char* keyDer, unsigned int keySz, void* ctx) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); WOLFSSL* ssl = (WOLFSSL*)ctx; if (ssl && ssl->ctx->RsaVerifyCb) { @@ -13172,24 +13363,26 @@ void DoCertFatalAlert(WOLFSSL* ssl, int ret) /* Determine alert reason */ alertWhy = bad_certificate; - if (ret == ASN_AFTER_DATE_E || ret == ASN_BEFORE_DATE_E) { + if (ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E) || + ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E)) { alertWhy = certificate_expired; } - else if (ret == ASN_NO_SIGNER_E || ret == ASN_PATHLEN_INV_E || - ret == ASN_PATHLEN_SIZE_E) { + else if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) || + ret == WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E) || + ret == WC_NO_ERR_TRACE(ASN_PATHLEN_SIZE_E)) { alertWhy = unknown_ca; } #ifdef OPENSSL_EXTRA - else if (ret == CRL_CERT_REVOKED) { + else if (ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED)) { alertWhy = certificate_revoked; } #endif #if defined(HAVE_RPK) - else if (ret == UNSUPPORTED_CERTIFICATE) { + else if (ret == WC_NO_ERR_TRACE(UNSUPPORTED_CERTIFICATE)) { alertWhy = unsupported_certificate; } #endif /* HAVE_RPK */ - else if (ret == NO_PEER_CERT) { + else if (ret == WC_NO_ERR_TRACE(NO_PEER_CERT)) { #ifdef WOLFSSL_TLS13 if (ssl->options.tls1_3) { alertWhy = certificate_required; @@ -13206,6 +13399,167 @@ void DoCertFatalAlert(WOLFSSL* ssl, int ret) ssl->options.isClosed = 1; } + +int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, + WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args, + int cert_err, void* heap, int* x509Free) +{ + WOLFSSL_X509_STORE_CTX* store = NULL; + char* domain = NULL; +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_X509* x509 = NULL; +#endif + + *x509Free = 0; + + store = wolfSSL_X509_STORE_CTX_new_ex(heap); + if (store == NULL) + goto mem_error; + domain = (char*)XMALLOC(ASN_NAME_MAX, heap, DYNAMIC_TYPE_STRING); + if (domain == NULL) + goto mem_error; + + domain[0] = '\0'; + + /* build subject CN as string to return in store */ + if (args->dCertInit && args->dCert && args->dCert->subjectCN) { + int subjectCNLen = args->dCert->subjectCNLen; + if (subjectCNLen > ASN_NAME_MAX-1) + subjectCNLen = ASN_NAME_MAX-1; + if (subjectCNLen > 0) { + XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen); + domain[subjectCNLen] = '\0'; + } + } + +#ifndef OPENSSL_COMPATIBLE_DEFAULTS + store->error = cert_err; +#else + store->error = GetX509Error(cert_err); +#endif + store->error_depth = args->certIdx; + store->discardSessionCerts = 0; + store->domain = domain; + if (ssl != NULL) { + if (ssl->verifyCbCtx != NULL) { + /* Use the WOLFSSL user context if set */ + store->userCtx = ssl->verifyCbCtx; + } + else { + /* Else use the WOLFSSL_CTX user context */ + store->userCtx = ssl->ctx->verifyCbCtx; + } + } + else { + store->userCtx = cm; + } + store->certs = args->certs; + store->totalCerts = args->totalCerts; +#if defined(HAVE_EX_DATA) && \ + (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) + if (wolfSSL_CRYPTO_set_ex_data(&store->ex_data, 0, ssl) + != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to store ssl context in WOLFSSL_X509_STORE_CTX"); + } +#endif + + if (ssl != NULL) { +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) + store->store = SSL_STORE(ssl); +#if defined(OPENSSL_EXTRA) + store->depth = args->count; + /* Overwrite with non-default param values in SSL */ + if (ssl->param) { + if (ssl->param->check_time) + store->param->check_time = ssl->param->check_time; + + if (ssl->param->flags) + store->param->flags = ssl->param->flags; +#ifdef WOLFSSL_LOCAL_X509_STORE + else if (SSL_STORE(ssl) && SSL_STORE(ssl)->param && + SSL_STORE(ssl)->param->flags) + store->param->flags = SSL_STORE(ssl)->param->flags; +#endif + + + if (ssl->param->hostName[0]) + XMEMCPY(store->param->hostName, ssl->param->hostName, + WOLFSSL_HOST_NAME_MAX); + + } +#endif /* defined(OPENSSL_EXTRA) */ +#endif /* defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)*/ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + #ifdef KEEP_PEER_CERT + if (args->certIdx == 0) { + FreeX509(&ssl->peerCert); + InitX509(&ssl->peerCert, 0, ssl->heap); + if (CopyDecodedToX509(&ssl->peerCert, args->dCert) == 0) + WOLFSSL_MSG("Unable to copy to ssl->peerCert"); + store->current_cert = &ssl->peerCert; /* use existing X509 */ + } + else + #endif + { + x509 = wolfSSL_X509_new_ex(heap); + if (x509 == NULL) + goto mem_error; + if (CopyDecodedToX509(x509, args->dCert) == 0) { + store->current_cert = x509; + *x509Free = 1; + } + else { + goto mem_error; + } + } +#endif +#ifdef SESSION_CERTS + store->sesChain = &ssl->session->chain; +#endif + } + *store_pt = store; + return 0; +mem_error: + if (store != NULL) + wolfSSL_X509_STORE_CTX_free(store); +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + if (x509 != NULL) + wolfSSL_X509_free(x509); +#endif + if (domain != NULL) + XFREE(domain, heap, DYNAMIC_TYPE_STRING); + return MEMORY_E; +} + +void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store, + WOLFSSL* ssl, void* heap, int x509Free) +{ + (void)ssl; + (void)x509Free; + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + wolfSSL_sk_X509_pop_free(store->chain, NULL); + store->chain = NULL; +#endif +#ifdef SESSION_CERTS + if ((ssl != NULL) && (store->discardSessionCerts)) { + WOLFSSL_MSG("Verify callback requested discard sess certs"); + ssl->session->chain.count = 0; + #ifdef WOLFSSL_ALT_CERT_CHAINS + ssl->session->altChain.count = 0; + #endif + } +#endif /* SESSION_CERTS */ + XFREE(store->domain, heap, DYNAMIC_TYPE_STRING); + store->domain = NULL; +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + if (x509Free) + wolfSSL_X509_free(store->current_cert); + store->current_cert = NULL; +#endif + wolfSSL_X509_STORE_CTX_free(store); +} + /* WOLFSSL_ALWAYS_VERIFY_CB: Use verify callback for success or failure cases */ /* WOLFSSL_VERIFY_CB_ALL_CERTS: Issue callback for all intermediate certificates */ @@ -13214,10 +13568,10 @@ void DoCertFatalAlert(WOLFSSL* ssl, int ret) * store->error_depth member to determine index (0=peer, >1 intermediates) */ -int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, +int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int cert_err, ProcPeerCertArgs* args) { - int verify_ok = 0, use_cb = 0; + int verify_ok = 0, use_cb = 0, ret = cert_err; void *heap; if (cm == NULL) { @@ -13227,12 +13581,12 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, heap = (ssl != NULL) ? ssl->heap : cm->heap; /* Determine if verify was okay */ - if (ret == 0) { + if (cert_err == 0) { verify_ok = 1; } /* Determine if verify callback should be used */ - if (ret != 0) { + if (cert_err != 0) { if ((ssl != NULL) && (!ssl->options.verifyNone)) { use_cb = 1; /* always report errors */ } @@ -13257,8 +13611,9 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, ssl->param && ssl->param->hostName[0]) { /* If altNames names is present, then subject common name is ignored */ if (args->dCert->altNames != NULL) { - if (CheckForAltNames(args->dCert, ssl->param->hostName, NULL) != 1) { - if (ret == 0) { + if (CheckForAltNames(args->dCert, ssl->param->hostName, + (word32)XSTRLEN(ssl->param->hostName), NULL) != 1) { + if (cert_err == 0) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); } @@ -13267,10 +13622,12 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, #ifndef WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY else { if (args->dCert->subjectCN) { - if (MatchDomainName(args->dCert->subjectCN, - args->dCert->subjectCNLen, - ssl->param->hostName) == 0) { - if (ret == 0) { + if (MatchDomainName( + args->dCert->subjectCN, + args->dCert->subjectCNLen, + ssl->param->hostName, + (word32)XSTRLEN(ssl->param->hostName)) == 0) { + if (cert_err == 0) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); } @@ -13279,7 +13636,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, } #else else { - if (ret == 0) { + if (cert_err == 0) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); } @@ -13291,7 +13648,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, if ((args->dCertInit != 0) && (args->dCert != NULL) && (ssl != NULL) && (ssl->param != NULL) && (XSTRLEN(ssl->param->ipasc) > 0)) { if (CheckIPAddr(args->dCert, ssl->param->ipasc) != 0) { - if (ret == 0) { + if (cert_err == 0) { ret = IPADDR_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); } @@ -13303,6 +13660,10 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, if ((use_cb && (ssl != NULL) && ((ssl->verifyCallback != NULL) #ifdef OPENSSL_ALL || (ssl->ctx->verifyCertCb != NULL) + #endif + #if defined(WOLFSSL_LOCAL_X509_STORE) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_QT)) + || (SSL_STORE(ssl) != NULL && SSL_STORE(ssl)->verify_cb != NULL) #endif )) #ifndef NO_WOLFSSL_CM_VERIFY @@ -13310,157 +13671,20 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, #endif ) { int verifyFail = 0; - #ifdef WOLFSSL_SMALL_STACK - WOLFSSL_X509_STORE_CTX* store; - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - WOLFSSL_X509* x509; - #endif - char* domain = NULL; - #else - WOLFSSL_X509_STORE_CTX store[1]; - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - WOLFSSL_X509 x509[1]; - #endif - char domain[ASN_NAME_MAX]; - #endif - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_X509_STORE_CTX* store = NULL; int x509Free = 0; - #endif - - #ifdef WOLFSSL_SMALL_STACK - store = (WOLFSSL_X509_STORE_CTX*)XMALLOC( - sizeof(WOLFSSL_X509_STORE_CTX), heap, DYNAMIC_TYPE_X509_STORE); - if (store == NULL) { - return MEMORY_E; - } - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, - DYNAMIC_TYPE_X509); - if (x509 == NULL) { - XFREE(store, heap, DYNAMIC_TYPE_X509_STORE); - return MEMORY_E; - } - #endif - domain = (char*)XMALLOC(ASN_NAME_MAX, heap, DYNAMIC_TYPE_STRING); - if (domain == NULL) { - XFREE(store, heap, DYNAMIC_TYPE_X509_STORE); - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - XFREE(x509, heap, DYNAMIC_TYPE_X509); - #endif - return MEMORY_E; - } - #endif /* WOLFSSL_SMALL_STACK */ - - XMEMSET(store, 0, sizeof(WOLFSSL_X509_STORE_CTX)); - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - XMEMSET(x509, 0, sizeof(WOLFSSL_X509)); - #endif - domain[0] = '\0'; - - /* build subject CN as string to return in store */ - if (args->dCertInit && args->dCert && args->dCert->subjectCN) { - int subjectCNLen = args->dCert->subjectCNLen; - if (subjectCNLen > ASN_NAME_MAX-1) - subjectCNLen = ASN_NAME_MAX-1; - if (subjectCNLen > 0) { - XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen); - domain[subjectCNLen] = '\0'; - } - } - -#ifndef OPENSSL_COMPATIBLE_DEFAULTS - store->error = ret; -#else - store->error = GetX509Error(ret); -#endif - store->error_depth = args->certIdx; - store->discardSessionCerts = 0; - store->domain = domain; - if (ssl != NULL) { - if (ssl->verifyCbCtx != NULL) { - /* Use the WOLFSSL user context if set */ - store->userCtx = ssl->verifyCbCtx; - } - else { - /* Else use the WOLFSSL_CTX user context */ - store->userCtx = ssl->ctx->verifyCbCtx; - } - } - else { - store->userCtx = cm; - } - store->certs = args->certs; - store->totalCerts = args->totalCerts; - #if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) - if (wolfSSL_CRYPTO_set_ex_data(&store->ex_data, 0, ssl) - != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Failed to store ssl context in WOLFSSL_X509_STORE_CTX"); - } - #endif - - if (ssl != NULL) { - #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) - store->store = SSL_STORE(ssl); - #if defined(OPENSSL_EXTRA) - store->depth = args->count; - store->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC( - sizeof(WOLFSSL_X509_VERIFY_PARAM), - heap, DYNAMIC_TYPE_OPENSSL); - if (store->param == NULL) { - #ifdef WOLFSSL_SMALL_STACK - XFREE(domain, heap, DYNAMIC_TYPE_STRING); - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - XFREE(x509, heap, DYNAMIC_TYPE_X509); - #endif - XFREE(store, heap, DYNAMIC_TYPE_X509_STORE); - #endif - return MEMORY_E; - } - XMEMSET(store->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); - /* Overwrite with non-default param values in SSL */ - if (ssl->param) { - if (ssl->param->check_time) - store->param->check_time = ssl->param->check_time; - - if (ssl->param->flags) - store->param->flags = ssl->param->flags; + int setupRet = SetupStoreCtxCallback(&store, ssl, cm, args, cert_err, + heap, &x509Free); - if (ssl->param->hostName[0]) - XMEMCPY(store->param->hostName, ssl->param->hostName, - WOLFSSL_HOST_NAME_MAX); + if (setupRet != 0) + return setupRet; - } - #endif /* defined(OPENSSL_EXTRA) */ - #endif /* defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)*/ - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - #ifdef KEEP_PEER_CERT - if (args->certIdx == 0) { - store->current_cert = &ssl->peerCert; /* use existing X509 */ - } - else - #endif - { - InitX509(x509, 0, heap); - if (CopyDecodedToX509(x509, args->dCert) == 0) { - store->current_cert = x509; - x509Free = 1; - } - else { - FreeX509(x509); - } - } - #endif - #ifdef SESSION_CERTS - store->sesChain = &ssl->session->chain; - #endif - } #ifndef NO_WOLFSSL_CM_VERIFY /* non-zero return code indicates failure override */ if (cm->verifyCallback != NULL) { store->userCtx = cm; if (cm->verifyCallback(verify_ok, store)) { - if (ret != 0) { + if (cert_err != 0) { WOLFSSL_MSG("Verify CM callback overriding error!"); ret = 0; } @@ -13476,7 +13700,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, /* non-zero return code indicates failure override */ if (ssl->ctx->verifyCertCb) { if (ssl->ctx->verifyCertCb(store, ssl->ctx->verifyCertCbArg)) { - if (ret != 0) { + if (cert_err != 0) { WOLFSSL_MSG("Verify Cert callback overriding error!"); ret = 0; } @@ -13486,11 +13710,10 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, } } #endif - /* non-zero return code indicates failure override */ if (ssl->verifyCallback) { if (ssl->verifyCallback(verify_ok, store)) { - if (ret != 0) { + if (cert_err != 0) { WOLFSSL_MSG("Verify callback overriding error!"); ret = 0; } @@ -13499,11 +13722,25 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, verifyFail = 1; } } +#if defined(WOLFSSL_LOCAL_X509_STORE) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_QT)) + if (SSL_STORE(ssl) != NULL && SSL_STORE(ssl)->verify_cb != NULL) { + if (SSL_STORE(ssl)->verify_cb(verify_ok, store)) { + if (cert_err != 0) { + WOLFSSL_MSG("Store Verify callback overriding error!"); + ret = 0; + } + } + else { + verifyFail = 1; + } + } +#endif } if (verifyFail) { /* induce error if one not present */ - if (ret == 0) { + if (cert_err == 0) { ret = VERIFY_CERT_ERROR; WOLFSSL_ERROR_VERBOSE(ret); } @@ -13511,36 +13748,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, /* mark as verify error */ args->verifyErr = 1; } - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - if (x509Free) { - FreeX509(x509); - } - #endif - #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - wolfSSL_sk_X509_pop_free(store->chain, NULL); - store->chain = NULL; - #endif - #ifdef SESSION_CERTS - if ((ssl != NULL) && (store->discardSessionCerts)) { - WOLFSSL_MSG("Verify callback requested discard sess certs"); - ssl->session->chain.count = 0; - #ifdef WOLFSSL_ALT_CERT_CHAINS - ssl->session->altChain.count = 0; - #endif - } - #endif /* SESSION_CERTS */ -#ifdef OPENSSL_EXTRA - if ((ssl != NULL) && (store->param)) { - XFREE(store->param, heap, DYNAMIC_TYPE_OPENSSL); - } -#endif - #ifdef WOLFSSL_SMALL_STACK - XFREE(domain, heap, DYNAMIC_TYPE_STRING); - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - XFREE(x509, heap, DYNAMIC_TYPE_X509); - #endif - XFREE(store, heap, DYNAMIC_TYPE_X509_STORE); - #endif + CleanupStoreCtxCallback(store, ssl, heap, x509Free); } (void)heap; @@ -13548,6 +13756,50 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, return ret; } +#ifdef HAVE_CRL +void DoCrlCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, + ProcPeerCertArgs* args, int* outRet) +{ +#if defined(WOLFSSL_LOCAL_X509_STORE) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_QT)) + int ret = 0; + void* heap = (ssl != NULL) ? ssl->heap : cm->heap; + WOLFSSL_X509_STORE* cert_store = (ssl != NULL) ? SSL_STORE(ssl) : NULL; + + if (cert_store != NULL && cert_store->get_crl_cb != NULL) { + WOLFSSL_CRL* userCrl = NULL; + WOLFSSL_X509_STORE_CTX* store = NULL; + int x509Free = 0; + + ret = SetupStoreCtxCallback(&store, ssl, cm, args, 0, heap, + &x509Free); + if (ret != 0) { + *outRet = ret; + return; + } + + ret = cert_store->get_crl_cb(store, &userCrl, store->current_cert); + if (ret == 1 && userCrl != NULL) { + /* Point to current cm to be able to verify CRL */ + userCrl->cm = SSL_CM(ssl); + *outRet = CheckCertCRL(userCrl, args->dCert); + } + else + *outRet = CRL_MISSING; + + if (userCrl != NULL) + wolfSSL_X509_CRL_free(userCrl); + CleanupStoreCtxCallback(store, ssl, heap, x509Free); + } +#else + (void)cm; + (void)ssl; + (void)args; + (void)outRet; +#endif +} +#endif + static void FreeProcPeerCertArgs(WOLFSSL* ssl, void* pArgs) { ProcPeerCertArgs* args = (ProcPeerCertArgs*)pArgs; @@ -13618,7 +13870,7 @@ int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type) #if defined(NO_SHA) && !defined(NO_SHA256) retHash = wc_Sha256Hash((const byte*)pbuf, len, dgt); #elif !defined(NO_SHA) - retHash = wc_ShaHash((const byte*)pbuf, len, dgt); + retHash = wc_ShaHash((const byte*)pbuf, (word32)len, dgt); #endif if (retHash == 0) { /* 4 bytes in little endian as unsigned long */ @@ -13688,7 +13940,7 @@ int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type) for (; suffix < MAX_SUFFIX; suffix++) { /* /folder-path/.(r)N[0..9] */ - if (XSNPRINTF(filename, len, "%s/%08lx.%s%d", entry->dir_name, + if (XSNPRINTF(filename, (size_t)len, "%s/%08lx.%s%d", entry->dir_name, hash, post, suffix) >= len) { @@ -13783,6 +14035,7 @@ static int ProcessPeerCertParse(WOLFSSL* ssl, ProcPeerCertArgs* args, buffer* cert; byte* subjectHash = NULL; int alreadySigner = 0; + Signer *extraSigners = NULL; #if defined(HAVE_RPK) int cType; #endif @@ -13813,7 +14066,7 @@ PRAGMA_GCC_DIAG_POP /* check if returning from non-blocking OCSP */ /* skip this section because cert is already initialized and parsed */ #ifdef WOLFSSL_NONBLOCK_OCSP - if (args->lastErr == OCSP_WANT_READ) { + if (args->lastErr == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { args->lastErr = 0; /* clear error */ return 0; } @@ -13843,7 +14096,7 @@ PRAGMA_GCC_DIAG_POP } /* perform cert parsing and signature check */ - sigRet = CheckCertSignature(cert->buffer, cert->length, + sigRet = wc_CheckCertSignature(cert->buffer, cert->length, ssl->heap, SSL_CM(ssl)); /* fail on errors here after the ParseCertRelative call, so dCert is populated */ @@ -13884,9 +14137,13 @@ PRAGMA_GCC_DIAG_POP return ret; #endif } - +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 + if (verify != NO_VERIFY && TLSX_CSR2_IsMulti(ssl->extensions)) { + extraSigners = TLSX_CSR2_GetPendingSigners(ssl->extensions); + } +#endif /* Parse Certificate */ - ret = ParseCertRelative(args->dCert, certType, verify, SSL_CM(ssl)); + ret = ParseCertRelative(args->dCert, certType, verify, SSL_CM(ssl), extraSigners); #if defined(HAVE_RPK) /* if cert type has negotiated with peer, confirm the cert received has @@ -13919,7 +14176,9 @@ PRAGMA_GCC_DIAG_POP #endif /* HAVE_RPK */ /* perform below checks for date failure cases */ - if (ret == 0 || ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) { + if (ret == 0 || + ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) || + ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { /* get subject and determine if already loaded */ #ifndef NO_SKID if (args->dCert->extAuthKeyIdSet) @@ -13930,39 +14189,6 @@ PRAGMA_GCC_DIAG_POP alreadySigner = AlreadySigner(SSL_CM(ssl), subjectHash); } -#ifdef WOLFSSL_DUAL_ALG_CERTS - if ((ret == 0) && (args->dCert->sapkiDer != NULL)) { -#ifndef WOLFSSL_SMALL_STACK - byte der[MAX_CERT_VERIFY_SZ]; -#else - byte *der = (byte*)XMALLOC(MAX_CERT_VERIFY_SZ, ssl->heap, - DYNAMIC_TYPE_DCERT); - if (der == NULL) { - ret = MEMORY_E; - } -#endif /* ! WOLFSSL_SMALL_STACK */ - - if (ret == 0) { - ret = wc_GeneratePreTBS(args->dCert, der, MAX_CERT_VERIFY_SZ); - - if (ret > 0) { - ret = wc_ConfirmAltSignature(der, ret, - args->dCert->sapkiDer, args->dCert->sapkiLen, - args->dCert->sapkiOID, - args->dCert->altSigValDer, args->dCert->altSigValLen, - args->dCert->altSigAlgOID, ssl->heap); - } -#ifdef WOLFSSL_SMALL_STACK - XFREE(der, ssl->heap, DYNAMIC_TYPE_DCERT); -#endif /* WOLFSSL_SMALL_STACK */ - - if (ret == 0) { - WOLFSSL_MSG("Alternative signature has been verified!"); - } - } - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - #ifdef WOLFSSL_SMALL_CERT_VERIFY /* get signature check failures from above */ if (ret == 0) @@ -13975,7 +14201,7 @@ PRAGMA_GCC_DIAG_POP *pAlreadySigner = alreadySigner; #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, args->dCert->sigCtx.asyncDev); } @@ -13987,7 +14213,7 @@ PRAGMA_GCC_DIAG_POP * original return code is returned. */ if (ssl->ctx && ssl->ctx->ProcessPeerCertCb) { int new_ret = ssl->ctx->ProcessPeerCertCb(ssl, args->dCert); - if (new_ret != NOT_COMPILED_IN) { + if (new_ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { ret = new_ret; } } @@ -14056,7 +14282,6 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) } break; #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: if (ssl->options.minFalconKeySz < 0 || @@ -14075,7 +14300,6 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) } break; #endif /* HAVE_FALCON */ - #endif /* HAVE_PQC */ #if defined(HAVE_DILITHIUM) case DILITHIUM_LEVEL2k: if (ssl->options.minDilithiumKeySz < 0 || @@ -14113,10 +14337,12 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) } #ifdef HAVE_CRL -static int ProcessPeerCertsChainCRLCheck(WOLFSSL_CERT_MANAGER* cm, Signer* ca) +static int ProcessPeerCertsChainCRLCheck(WOLFSSL* ssl, ProcPeerCertArgs* args) { Signer* prev = NULL; int ret = 0; + WOLFSSL_CERT_MANAGER* cm = SSL_CM(ssl); + Signer* ca = args->dCert->ca; /* End loop if no more issuers found or if we have * found a self signed cert (ca == prev) */ for (; ret == 0 && ca != NULL && ca != prev; @@ -14124,7 +14350,12 @@ static int ProcessPeerCertsChainCRLCheck(WOLFSSL_CERT_MANAGER* cm, Signer* ca) ret = CheckCertCRL_ex(cm->crl, ca->issuerNameHash, NULL, 0, ca->serialHash, NULL, 0, NULL); if (ret != 0) + DoCrlCallback(cm, ssl, args, &ret); + if (ret != 0){ + WOLFSSL_ERROR_VERBOSE(ret); + WOLFSSL_MSG("\tCRL check not ok"); break; + } } return ret; } @@ -14145,6 +14376,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, byte* subjectHash = NULL; int alreadySigner = 0; +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + int addToPendingCAs = 0; +#endif WOLFSSL_ENTER("ProcessPeerCerts"); #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) @@ -14158,7 +14392,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, args = (ProcPeerCertArgs*)ssl->async->args; #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_ppc; @@ -14166,11 +14400,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, else #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_NONBLOCK_OCSP - if (ssl->error == OCSP_WANT_READ) { + if (ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { /* Re-entry after non-blocking OCSP */ #ifdef WOLFSSL_ASYNC_CRYPT /* if async operationg not pending, reset error code */ - if (ret == WC_NO_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E)) ret = 0; #endif } @@ -14288,7 +14522,25 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ERROR_OUT(BUFFER_ERROR, exit_ppc); } c24to32(input + args->idx, &listSz); - args->idx += OPAQUE24_LEN; +#ifdef HAVE_RPK + /* + * If this is RPK from the peer, then single cert (if TLS1.2). + * So, ListSz location is same as CertSz location, so fake + * we have just seen this ListSz. + */ + if (!IsAtLeastTLSv1_3(ssl->version) && + ((ssl->options.side == WOLFSSL_SERVER_END && + ssl->options.rpkState.received_ClientCertTypeCnt == 1 && + ssl->options.rpkState.received_ClientCertTypes[0] == WOLFSSL_CERT_TYPE_RPK) || + (ssl->options.side == WOLFSSL_CLIENT_END && + ssl->options.rpkState.received_ServerCertTypeCnt == 1 && + ssl->options.rpkState.received_ServerCertTypes[0] == WOLFSSL_CERT_TYPE_RPK))) { + listSz += OPAQUE24_LEN; + } else +#endif /* HAVE_RPK */ + { + args->idx += OPAQUE24_LEN; + } if (listSz > MAX_CERTIFICATE_SZ) { ERROR_OUT(BUFFER_ERROR, exit_ppc); } @@ -14488,7 +14740,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \ !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \ !defined(NO_STDIO_FILESYSTEM) - if (ret == ASN_NO_SIGNER_E || ret == ASN_SELF_SIGNED_E) { + if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) || + ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) { WOLFSSL_MSG("try to load certificate if hash dir is set"); ret = LoadCertByIssuer(SSL_STORE(ssl), (WOLFSSL_X509_NAME*)args->dCert->issuerName, @@ -14508,14 +14761,15 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #endif #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) goto exit_ppc; #endif if (ret == 0) { ret = ProcessPeerCertCheckKey(ssl, args); } - else if (ret == ASN_PARSE_E || ret == BUFFER_E || - ret == MEMORY_E) { + else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) || + ret == WC_NO_ERR_TRACE(BUFFER_E) || + ret == WC_NO_ERR_TRACE(MEMORY_E)) { WOLFSSL_MSG( "Got Peer cert ASN PARSE_E, BUFFER E, MEMORY_E"); ERROR_OUT(ret, exit_ppc); @@ -14550,9 +14804,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ret == 0) { #ifdef HAVE_OCSP #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 - if (ssl->status_request_v2) { + addToPendingCAs = 0; + if (ssl->status_request_v2 && TLSX_CSR2_IsMulti(ssl->extensions)) { ret = TLSX_CSR2_InitRequests(ssl->extensions, args->dCert, 0, ssl->heap); + addToPendingCAs = 1; } else /* skips OCSP and force CRL check */ #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ @@ -14562,7 +14818,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = CheckCertOCSP_ex(SSL_CM(ssl)->ocsp, args->dCert, ssl); #ifdef WOLFSSL_NONBLOCK_OCSP - if (ret == OCSP_WANT_READ) { + if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { args->lastErr = ret; goto exit_ppc; } @@ -14586,7 +14842,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, responder, do a CRL lookup. If any other error, skip the CRL lookup and fail the certificate. */ - doCrlLookup = (ret == OCSP_CERT_UNKNOWN); + doCrlLookup = (ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN)); } #endif /* HAVE_OCSP */ @@ -14599,19 +14855,21 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, * same WOULD_BLOCK error code as OCSP's I/O * callback, and it is enabling it using the * same flag. */ - if (ret == OCSP_WANT_READ) { + if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { args->lastErr = ret; goto exit_ppc; } #endif + if (ret != 0) + DoCrlCallback(SSL_CM(ssl), ssl, args, &ret); if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); WOLFSSL_MSG("\tCRL check not ok"); } if (ret == 0 && args->certIdx == args->totalCerts-1) { - ret = ProcessPeerCertsChainCRLCheck( - SSL_CM(ssl), args->dCert->ca); + ret = ProcessPeerCertsChainCRLCheck(ssl, + args); if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); WOLFSSL_MSG("\tCRL chain check not ok"); @@ -14640,7 +14898,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, chain mode only requires that the peer certificate validate to a trusted CA */ if (ret != 0 && args->dCert->isCA) { - if (ret == ASN_NO_SIGNER_E || ret == ASN_SELF_SIGNED_E) { + if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) || + ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) { if (!ssl->options.usingAltCertChain) { WOLFSSL_MSG("Trying alternate cert chain"); ssl->options.usingAltCertChain = 1; @@ -14663,7 +14922,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, * for a CA cert to fail validation here, as we will verify * the entire chain when we hit the peer (leaf) cert */ if ((ssl->ctx->doAppleNativeCertValidationFlag) - && (ret == ASN_NO_SIGNER_E)) { + && (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E))) { WOLFSSL_MSG("Bypassing errors to allow for Apple native" " CA validation"); @@ -14681,8 +14940,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* Do verify callback */ ret = DoVerifyCallback(SSL_CM(ssl), ssl, ret, args); if (ssl->options.verifyNone && - (ret == CRL_MISSING || ret == CRL_CERT_REVOKED || - ret == CRL_CERT_DATE_ERR)) { + (ret == WC_NO_ERR_TRACE(CRL_MISSING) || + ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR))) { WOLFSSL_MSG("Ignoring CRL problem based on verify setting"); ret = ssl->error = 0; } @@ -14693,6 +14953,67 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, skipAddCA = 1; } #endif +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ret == 0 && addToPendingCAs && !alreadySigner) { +#ifdef WOLFSSL_SMALL_STACK + DecodedCert *dCertAdd = NULL; +#else + DecodedCert dCertAdd[1]; +#endif + int dCertAdd_inited = 0; + DerBuffer *derBuffer = NULL; + buffer* cert = &args->certs[args->certIdx]; + Signer *s = NULL; + +#ifdef WOLFSSL_SMALL_STACK + dCertAdd = (DecodedCert *) + XMALLOC(sizeof(*dCertAdd), ssl->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (dCertAdd == NULL) { + ret = MEMORY_E; + goto exit_req_v2; + } +#endif + InitDecodedCert(dCertAdd, cert->buffer, cert->length, + ssl->heap); + dCertAdd_inited = 1; + ret = ParseCert(dCertAdd, CA_TYPE, NO_VERIFY, + SSL_CM(ssl)); + if (ret != 0) { + goto exit_req_v2; + } + ret = AllocDer(&derBuffer, cert->length, CA_TYPE, ssl->heap); + if (ret != 0 || derBuffer == NULL) { + goto exit_req_v2; + } + XMEMCPY(derBuffer->buffer, cert->buffer, cert->length); + s = MakeSigner(SSL_CM(ssl)->heap); + if (s == NULL) { + ret = MEMORY_E; + goto exit_req_v2; + } + ret = FillSigner(s, dCertAdd, CA_TYPE, derBuffer); + if (ret != 0) { + goto exit_req_v2; + } + skipAddCA = 1; + ret = TLSX_CSR2_AddPendingSigner(ssl->extensions, s); + + exit_req_v2: + if (s && (ret != 0)) + FreeSigner(s, SSL_CM(ssl)->heap); + if (derBuffer) + FreeDer(&derBuffer); + if (dCertAdd_inited) + FreeDecodedCert(dCertAdd); +#ifdef WOLFSSL_SMALL_STACK + if (dCertAdd) + XFREE(dCertAdd, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + if (ret != 0) + goto exit_ppc; + } +#endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ /* If valid CA then add to Certificate Manager */ if (ret == 0 && args->dCert->isCA && @@ -14775,7 +15096,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \ !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \ !defined(NO_STDIO_FILESYSTEM) - if (ret == ASN_NO_SIGNER_E || ret == ASN_SELF_SIGNED_E) { + if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) || + ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) { int lastErr = ret; /* save error from last time */ WOLFSSL_MSG("try to load certificate if hash dir is set"); ret = LoadCertByIssuer(SSL_STORE(ssl), @@ -14796,7 +15118,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #endif #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) goto exit_ppc; #endif if (ret == 0) { @@ -14853,8 +15175,10 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, args->fatal = 0; } } - else if (ret == ASN_PARSE_E || ret == BUFFER_E || - ret == MEMORY_E || ret == BAD_FUNC_ARG) { + else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) || + ret == WC_NO_ERR_TRACE(BUFFER_E) || + ret == WC_NO_ERR_TRACE(MEMORY_E) || + ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { WOLFSSL_MSG("Got Peer cert ASN_PARSE_E, BUFFER_E, MEMORY_E," " BAD_FUNC_ARG"); #if defined(WOLFSSL_EXTRA_ALERTS) || defined(OPENSSL_EXTRA) || \ @@ -14872,11 +15196,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) if (ssl->peerVerifyRet == 0) { /* Return first cert error here */ - if (ret == ASN_BEFORE_DATE_E) { + if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E)) { ssl->peerVerifyRet = (unsigned long)WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID; } - else if (ret == ASN_AFTER_DATE_E) { + else if (ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { ssl->peerVerifyRet = (unsigned long)WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED; } @@ -15014,11 +15338,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = CheckCertOCSP_ex(SSL_CM(ssl)->ocsp, args->dCert, ssl); #ifdef WOLFSSL_NONBLOCK_OCSP - if (ret == OCSP_WANT_READ) { + if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { goto exit_ppc; } #endif - doLookup = (ret == OCSP_CERT_UNKNOWN); + doLookup = (ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN)); if (ret != 0) { WOLFSSL_MSG("\tOCSP Lookup not ok"); args->fatal = 0; @@ -15044,10 +15368,12 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, * same WOULD_BLOCK error code as OCSP's I/O * callback, and it is enabling it using the * same flag. */ - if (ret == OCSP_WANT_READ) { + if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { goto exit_ppc; } #endif + if (ret != 0) + DoCrlCallback(SSL_CM(ssl), ssl, args, &ret); if (ret != 0) { WOLFSSL_MSG("\tCRL check not ok"); args->fatal = 0; @@ -15066,8 +15392,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, SSL_CM(ssl)->crlCheckAll && args->totalCerts == 1) { /* Check the entire cert chain */ if (args->dCert->ca != NULL) { - ret = ProcessPeerCertsChainCRLCheck(SSL_CM(ssl), - args->dCert->ca); + ret = ProcessPeerCertsChainCRLCheck(ssl, args); if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); WOLFSSL_MSG("\tCRL chain check not ok"); @@ -15087,28 +15412,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (args->fatal == 0) { int copyRet = 0; - #ifdef WOLFSSL_POST_HANDSHAKE_AUTH - if (ssl->options.handShakeDone) { - FreeX509(&ssl->peerCert); - InitX509(&ssl->peerCert, 0, ssl->heap); - } - else - #endif - #ifdef HAVE_SECURE_RENEGOTIATION - if (ssl->secure_renegotiation && - ssl->secure_renegotiation->enabled) { - /* free old peer cert */ - FreeX509(&ssl->peerCert); - InitX509(&ssl->peerCert, 0, ssl->heap); - } - else - #endif - { - } - - /* set X509 format for peer cert */ + /* free old peer cert */ + FreeX509(&ssl->peerCert); + InitX509(&ssl->peerCert, 0, ssl->heap); copyRet = CopyDecodedToX509(&ssl->peerCert, args->dCert); - if (copyRet == MEMORY_E) { + if (copyRet == WC_NO_ERR_TRACE(MEMORY_E)) { args->fatal = 1; } } @@ -15209,6 +15517,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (args->dCert->altNames) { if (CheckForAltNames(args->dCert, (char*)ssl->buffers.domainName.buffer, + (ssl->buffers.domainName.buffer == NULL ? 0 : + (word32)XSTRLEN( + (const char *)ssl->buffers.domainName.buffer)), NULL) != 1) { WOLFSSL_MSG("DomainName match on alt names failed"); /* try to get peer key still */ @@ -15218,9 +15529,14 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } else { if (MatchDomainName( - args->dCert->subjectCN, - args->dCert->subjectCNLen, - (char*)ssl->buffers.domainName.buffer) == 0) { + args->dCert->subjectCN, + args->dCert->subjectCNLen, + (char*)ssl->buffers.domainName.buffer, + (ssl->buffers.domainName.buffer == NULL ? 0 : + (word32)XSTRLEN( + (const char *)ssl->buffers.domainName.buffer) + )) == 0) + { WOLFSSL_MSG("DomainName match on common name failed"); ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); @@ -15230,10 +15546,15 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* Old behavior. */ if (MatchDomainName(args->dCert->subjectCN, args->dCert->subjectCNLen, - (char*)ssl->buffers.domainName.buffer) == 0) { + (char*)ssl->buffers.domainName.buffer, + (ssl->buffers.domainName.buffer == NULL ? 0 : + (word32)XSTRLEN(ssl->buffers.domainName.buffer))) == 0) + { WOLFSSL_MSG("DomainName match on common name failed"); if (CheckForAltNames(args->dCert, (char*)ssl->buffers.domainName.buffer, + (ssl->buffers.domainName.buffer == NULL ? 0 : + (word32)XSTRLEN(ssl->buffers.domainName.buffer)), NULL) != 1) { WOLFSSL_MSG( "DomainName match on alt names failed too"); @@ -15525,7 +15846,6 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, break; } #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: case FALCON_LEVEL5k: @@ -15575,7 +15895,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, break; } #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) + #if defined(HAVE_DILITHIUM) && \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: @@ -15628,7 +15949,6 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, break; } #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ default: break; } @@ -15687,8 +16007,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = DoVerifyCallback(SSL_CM(ssl), ssl, ret, args); if (ssl->options.verifyNone && - (ret == CRL_MISSING || ret == CRL_CERT_REVOKED || - ret == CRL_CERT_DATE_ERR)) { + (ret == WC_NO_ERR_TRACE(CRL_MISSING) || + ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR))) { WOLFSSL_MSG("Ignoring CRL problem based on verify setting"); ret = ssl->error = 0; } @@ -15735,7 +16056,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) - if (ret == WC_PENDING_E || ret == OCSP_WANT_READ) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) || + ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_certificate = 0; @@ -15781,7 +16103,8 @@ static int DoCertificate(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* Reset the session cert chain count in case the session resume failed, * do not reset if we are resuming after an async wait */ #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) - if (ssl->error != OCSP_WANT_READ && ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ) && + ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { ssl->session->chain.count = 0; @@ -15810,6 +16133,7 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, int ret = 0; byte status_type; word32 status_length; + int endCertificateOK = 0; WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_DO); WOLFSSL_ENTER("DoCertificateStatus"); @@ -15833,6 +16157,7 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* WOLFSSL_CSR_OCSP overlaps with WOLFSSL_CSR2_OCSP */ case WOLFSSL_CSR2_OCSP: ret = ProcessCSR(ssl, input, inOutIdx, status_length); + endCertificateOK = (ret == 0); break; #endif @@ -15843,6 +16168,7 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, OcspRequest* request; word32 list_length = status_length; byte idx = 0; + Signer *pendingCAs = NULL; #ifdef WOLFSSL_SMALL_STACK CertStatus* status; @@ -15854,14 +16180,12 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, OcspResponse response[1]; #endif - do { - if (ssl->status_request_v2) { - ssl->status_request_v2 = 0; - break; - } - + if (!ssl->status_request_v2) return BUFFER_ERROR; - } while(0); + + ssl->status_request_v2 = 0; + + pendingCAs = TLSX_CSR2_GetPendingSigners(ssl->extensions); #ifdef WOLFSSL_SMALL_STACK status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap, @@ -15901,23 +16225,27 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (status_length) { InitOcspResponse(response, single, status, input +*inOutIdx, status_length, ssl->heap); - + response->pendingCAs = pendingCAs; if ((OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, 0) != 0) || (response->responseStatus != OCSP_SUCCESSFUL) || (response->single->status->status != CERT_GOOD)) ret = BAD_CERTIFICATE_STATUS_ERROR; - while (ret == 0) { + if (ret == 0) { request = (OcspRequest*)TLSX_CSR2_GetRequest( - ssl->extensions, status_type, idx++); + ssl->extensions, status_type, idx); - if (request == NULL) + if (request == NULL) { ret = BAD_CERTIFICATE_STATUS_ERROR; - else if (CompareOcspReqResp(request, response) == 0) - break; - else if (idx == 1) /* server cert must be OK */ + } + else if (CompareOcspReqResp(request, response) != 0) { ret = BAD_CERTIFICATE_STATUS_ERROR; + } + else { + if (idx == 0) /* server cert must be OK */ + endCertificateOK = 1; + } } /* only frees 'single' if single->isDynamic is set */ @@ -15926,6 +16254,7 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, *inOutIdx += status_length; list_length -= status_length; } + idx++; } ssl->status_request_v2 = 0; @@ -15945,6 +16274,20 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, ret = BUFFER_ERROR; } + /* end certificate MUST be present */ + if (endCertificateOK == 0) + ret = BAD_CERTIFICATE_STATUS_ERROR; +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ret == 0) { + if (TLSX_CSR2_MergePendingCA(ssl) < 0) { + WOLFSSL_MSG("Failed to merge pending CAs"); + } + } + else { + TLSX_CSR2_ClearPendingCA(ssl); + } +#endif + if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); SendAlert(ssl, alert_fatal, bad_certificate_status_response); @@ -16348,44 +16691,6 @@ static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type) WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E); return OUT_OF_ORDER_E; } -#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ - defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) - if (ssl->msgsReceived.got_certificate_status == 0) { - int csrRet = 0; -#ifdef HAVE_CERTIFICATE_STATUS_REQUEST - if (csrRet == 0 && ssl->status_request) { - WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange"); - csrRet = TLSX_CSR_ForceRequest(ssl); - } -#endif -#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 - if (csrRet == 0 && ssl->status_request_v2) { - WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange"); - csrRet = TLSX_CSR2_ForceRequest(ssl); - } -#endif - if (csrRet != 0) { - /* Error out if OCSP lookups are enabled and failed or if - * the user requires stapling. */ - if (SSL_CM(ssl)->ocspEnabled || SSL_CM(ssl)->ocspMustStaple) - return csrRet; - } - /* Check that a status request extension was seen as the - * CertificateStatus wasn't when an OCSP staple is required. - */ - if ( -#ifdef HAVE_CERTIFICATE_STATUS_REQUEST - !ssl->status_request && -#endif -#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 - !ssl->status_request_v2 && -#endif - SSL_CM(ssl)->ocspMustStaple) { - WOLFSSL_ERROR_VERBOSE(OCSP_CERT_UNKNOWN); - return OCSP_CERT_UNKNOWN; - } - } -#endif break; #endif @@ -16458,6 +16763,54 @@ static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type) return OUT_OF_ORDER_E; } } +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ + defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ssl->msgsReceived.got_certificate_status == 0) { + int csrRet = 0; +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST + if (csrRet == 0 && ssl->status_request) { + WOLFSSL_MSG("No CertificateStatus before ServerHelloDone"); + csrRet = TLSX_CSR_ForceRequest(ssl); + } +#endif +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 + if (csrRet == 0 && ssl->status_request_v2) { + WOLFSSL_MSG("No CertificateStatus before ServerHelloDone"); + csrRet = TLSX_CSR2_ForceRequest(ssl); + } + if (ssl->status_request_v2) { + if (csrRet == 0) { + if (TLSX_CSR2_MergePendingCA(ssl) < 0) { + WOLFSSL_MSG("Failed to merge pending CAs"); + } + } + else { + TLSX_CSR2_ClearPendingCA(ssl); + } + } +#endif + if (csrRet != 0) { + /* Error out if OCSP lookups are enabled and failed or if + * the user requires stapling. */ + if (SSL_CM(ssl)->ocspEnabled || SSL_CM(ssl)->ocspMustStaple) + return csrRet; + } + /* Check that a status request extension was seen as the + * CertificateStatus wasn't when an OCSP staple is required. + */ + if ( +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST + !ssl->status_request && +#endif +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 + !ssl->status_request_v2 && +#endif + SSL_CM(ssl)->ocspMustStaple) { + WOLFSSL_ERROR_VERBOSE(OCSP_CERT_UNKNOWN); + return OCSP_CERT_UNKNOWN; + } + } +#endif break; #endif @@ -16734,7 +17087,7 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, && ssl->error != OCSP_WANT_READ #endif ) { - ret = HashInput(ssl, input + *inOutIdx, size); + ret = HashInput(ssl, input + *inOutIdx, (int)size); if (ret != 0) { WOLFSSL_MSG("Incomplete handshake hashes"); return ret; @@ -16827,7 +17180,8 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, IsAtLeastTLSv1_3(ssl->version)) { #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) - if (ret != WC_PENDING_E && ret != OCSP_WANT_READ) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) && + ret != WC_NO_ERR_TRACE(OCSP_WANT_READ)) #endif { ssl->options.cacheMessages = 0; @@ -16909,7 +17263,8 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ssl->options.resuming || !ssl->options.verifyPeer || \ !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version)) { #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) - if (ret != WC_PENDING_E && ret != OCSP_WANT_READ) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) && + ret != WC_NO_ERR_TRACE(OCSP_WANT_READ)) #endif { ssl->options.cacheMessages = 0; @@ -16975,7 +17330,8 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) /* if async, offset index so this msg will be processed again */ - if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) { + if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) || + ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) && *inOutIdx > 0) { *inOutIdx -= HANDSHAKE_HEADER_SZ; #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { @@ -16985,7 +17341,8 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, } /* make sure async error is cleared */ - if (ret == 0 && (ssl->error == WC_PENDING_E || ssl->error == OCSP_WANT_READ)) { + if (ret == 0 && (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) || + ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) { ssl->error = 0; } #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */ @@ -17108,7 +17465,7 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #ifdef WOLFSSL_ASYNC_CRYPT - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* for async this copy was already done, do not replace, since @@ -17128,7 +17485,7 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->arrays->pendingMsgSz - idx, ssl->arrays->pendingMsgSz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* setup to process fragment again */ ssl->arrays->pendingMsgOffset -= inputLength; *inOutIdx -= inputLength; @@ -17160,43 +17517,41 @@ int SendFatalAlertOnly(WOLFSSL *ssl, int error) switch (error) { /* not fatal errors */ - case WANT_WRITE: - case WANT_READ: - case ZERO_RETURN: + case WC_NO_ERR_TRACE(WANT_WRITE): + case WC_NO_ERR_TRACE(WANT_READ): + case WC_NO_ERR_TRACE(ZERO_RETURN): #ifdef WOLFSSL_NONBLOCK_OCSP - case OCSP_WANT_READ: + case WC_NO_ERR_TRACE(OCSP_WANT_READ): #endif #ifdef WOLFSSL_ASYNC_CRYPT - case WC_PENDING_E: + case WC_NO_ERR_TRACE(WC_PENDING_E): #endif return 0; /* peer already disconnected and ssl is possibly in bad state * don't try to send an alert */ - case SOCKET_ERROR_E: + case WC_NO_ERR_TRACE(SOCKET_ERROR_E): return error; - case BUFFER_ERROR: - case ASN_PARSE_E: - case COMPRESSION_ERROR: + case WC_NO_ERR_TRACE(BUFFER_ERROR): + case WC_NO_ERR_TRACE(ASN_PARSE_E): + case WC_NO_ERR_TRACE(COMPRESSION_ERROR): why = decode_error; break; - case MATCH_SUITE_ERROR: - why = illegal_parameter; - break; - case VERIFY_FINISHED_ERROR: - case SIG_VERIFY_E: + case WC_NO_ERR_TRACE(VERIFY_FINISHED_ERROR): + case WC_NO_ERR_TRACE(SIG_VERIFY_E): why = decrypt_error; break; - case DUPLICATE_MSG_E: - case NO_CHANGE_CIPHER_E: - case OUT_OF_ORDER_E: + case WC_NO_ERR_TRACE(DUPLICATE_MSG_E): + case WC_NO_ERR_TRACE(NO_CHANGE_CIPHER_E): + case WC_NO_ERR_TRACE(OUT_OF_ORDER_E): why = unexpected_message; break; - case ECC_OUT_OF_RANGE_E: + case WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E): why = bad_record_mac; break; - case VERSION_ERROR: + case WC_NO_ERR_TRACE(MATCH_SUITE_ERROR): + case WC_NO_ERR_TRACE(VERSION_ERROR): default: why = handshake_failure; break; @@ -17680,12 +18035,12 @@ int DtlsMsgDrain(WOLFSSL* ssl) DtlsTxMsgListClean(ssl); } else if (!IsAtLeastTLSv1_3(ssl->version)) { - if (SendFatalAlertOnly(ssl, ret) == SOCKET_ERROR_E) { + if (SendFatalAlertOnly(ssl, ret) == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) { ret = SOCKET_ERROR_E; } } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { break; } #endif @@ -18034,7 +18389,7 @@ static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out, /* add cipher info and then its length */ XMEMSET(padding, 0, sizeof(padding)); - if ((ret = wc_Poly1305Update(ssl->auth.poly1305, out, msglen)) != 0) + if ((ret = wc_Poly1305Update(ssl->auth.poly1305, out, (word32)msglen)) != 0) return ret; /* 32 bit size of cipher to 64 bit endian */ @@ -18419,7 +18774,7 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, return ret; } if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add, - sizeof(add), input, msgLen, tag, sizeof(tag))) != 0) { + sizeof(add), input, (word32)msgLen, tag, sizeof(tag))) != 0) { ForceZero(poly, sizeof(poly)); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE); @@ -18443,7 +18798,7 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, /* if the tag was good decrypt message */ if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, plain, - input, msgLen)) != 0) + input, (word32)msgLen)) != 0) return ret; #ifdef CHACHA_AEAD_TEST @@ -18542,7 +18897,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ret = wc_Des3_CbcEncrypt(ssl->encrypt.des3, out, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E && asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif @@ -18560,7 +18915,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #endif ret = wc_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E && asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif @@ -18631,7 +18986,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ssl->encrypt.additional, AEAD_AUTH_DATA_SZ); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif /* HAVE_PK_CALLBACKS */ { ret = aes_auth_fn(ssl->encrypt.aes, @@ -18644,7 +18999,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E && asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif @@ -18734,7 +19089,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #endif ret = wc_Sm4CbcEncrypt(ssl->encrypt.sm4, out, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E && asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif @@ -18798,7 +19153,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ssl->encrypt.additional, AEAD_AUTH_DATA_SZ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E && asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) { ret = wolfSSL_AsyncPush(ssl, asyncDev); } #endif @@ -18828,7 +19183,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #ifdef WOLFSSL_ASYNC_CRYPT /* if async is not okay, then block */ - if (ret == WC_PENDING_E && !asyncOkay) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && !asyncOkay) { ret = wc_AsyncWait(ret, asyncDev, event_flags); } #endif @@ -18842,7 +19197,7 @@ static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, int ret = 0; #ifdef WOLFSSL_ASYNC_CRYPT - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->error = 0; /* clear async */ } #endif @@ -18935,7 +19290,7 @@ static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, #ifdef WOLFSSL_ASYNC_CRYPT /* If pending, then leave and return will resume below */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -19031,7 +19386,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev); } #endif @@ -19049,7 +19404,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, #endif ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } #endif @@ -19115,7 +19470,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->decrypt.additional, AEAD_AUTH_DATA_SZ); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif /* HAVE_PK_CALLBACKS */ { if ((ret = aes_auth_fn(ssl->decrypt.aes, @@ -19127,7 +19482,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->specs.aead_mac_size, ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } @@ -19213,7 +19568,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, #endif ret = wc_Sm4CbcDecrypt(ssl->decrypt.sm4, plain, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } #endif @@ -19274,7 +19629,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->specs.aead_mac_size, ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.sm4->asyncDev); } @@ -19314,9 +19669,9 @@ static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input, word16 sz) #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* check for still pending */ - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; ssl->error = 0; /* clear async */ @@ -19431,7 +19786,7 @@ static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input, word16 sz) #ifdef WOLFSSL_ASYNC_CRYPT /* If pending, leave and return below */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -20076,7 +20431,7 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) idx += rawSz; ssl->buffers.clearOutputBuffer.buffer = rawData; - ssl->buffers.clearOutputBuffer.length = dataSz; + ssl->buffers.clearOutputBuffer.length = (unsigned int)dataSz; } idx += ssl->keys.padSz; @@ -20445,14 +20800,14 @@ static int GetInputData(WOLFSSL *ssl, word32 size) /* remove processed data */ ssl->buffers.inputBuffer.idx = 0; - ssl->buffers.inputBuffer.length = usedLength; + ssl->buffers.inputBuffer.length = (word32)usedLength; /* read data from network */ do { int in = wolfSSLReceive(ssl, ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.length, - inSz); + (word32)inSz); if (in == WANT_READ) return WANT_READ; @@ -20503,7 +20858,7 @@ static WC_INLINE int VerifyMacEnc(WOLFSSL* ssl, const byte* input, word32 msgSz, } ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1, PEER_ORDER); - ret |= ConstantCompare(verify, input + msgSz - digestSz, digestSz); + ret |= ConstantCompare(verify, input + msgSz - digestSz, (int)digestSz); if (ret != 0) { WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR); return VERIFY_MAC_ERROR; @@ -20543,12 +20898,14 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, void* ctx = wolfSSL_GetVerifyMacCtx(ssl); ret = ssl->ctx->VerifyMacCb(ssl, input, (msgSz - ivExtra) - digestSz - pad - 1, - digestSz, content, ctx); - if (ret != 0 && ret != PROTOCOLCB_UNAVAILABLE) { + digestSz, (word32)content, ctx); + if (ret != 0 && + ret != WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) { return ret; } } - if (!ssl->ctx->VerifyMacCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->VerifyMacCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif ret = TimingPadVerify(ssl, input, pad, digestSz, msgSz - ivExtra, content); @@ -20569,9 +20926,9 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, } (void)PadCheck(dummy, (byte)pad, MAX_PAD_SIZE); /* timing only */ ret = ssl->hmac(ssl, verify, input, msgSz - digestSz - pad - 1, - pad, content, 1, PEER_ORDER); + (int)pad, content, 1, PEER_ORDER); if (ConstantCompare(verify, input + msgSz - digestSz - pad - 1, - digestSz) != 0) { + (int)digestSz) != 0) { WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR); return VERIFY_MAC_ERROR; } @@ -20584,7 +20941,7 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, else if (ssl->specs.cipher_type == stream) { ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1, PEER_ORDER); - if (ConstantCompare(verify, input + msgSz - digestSz, digestSz) != 0) { + if (ConstantCompare(verify, input + msgSz - digestSz, (int)digestSz) != 0) { WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR); return VERIFY_MAC_ERROR; } @@ -20640,7 +20997,8 @@ static int DtlsShouldDrop(WOLFSSL* ssl, int retcode) } if ((ssl->options.handShakeDone && retcode != 0) - || retcode == SEQUENCE_ERROR || retcode == DTLS_CID_ERROR) { + || retcode == WC_NO_ERR_TRACE(SEQUENCE_ERROR) + || retcode == WC_NO_ERR_TRACE(DTLS_CID_ERROR)) { WOLFSSL_MSG_EX("Silently dropping DTLS message: %d", retcode); return 1; } @@ -20700,7 +21058,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #ifdef WOLFSSL_NONBLOCK_OCSP && ssl->error != OCSP_WANT_READ #endif - && (allowSocketErr != 1 || ssl->error != SOCKET_ERROR_E) + && (allowSocketErr != 1 || + ssl->error != WC_NO_ERR_TRACE(SOCKET_ERROR_E)) ) { WOLFSSL_MSG("ProcessReply retry in error state, not allowed"); return ssl->error; @@ -20711,7 +21070,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #if defined(WOLFSSL_CHECK_ALERT_ON_ERR) && \ (defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)) if (allowSocketErr == 1 && \ - (ssl->error == WC_PENDING_E || ssl->error == OCSP_WANT_READ)) { + (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) || + ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) { return ssl->error; } #endif @@ -20770,7 +21130,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* get header or return error */ if (!ssl->options.dtls) { - if ((ret = GetInputData(ssl, readSz)) < 0) + if ((ret = GetInputData(ssl, (word32)readSz)) < 0) return ret; } else { #ifdef WOLFSSL_DTLS @@ -20778,7 +21138,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) used = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx; if (used < readSz) { - if ((ret = GetInputData(ssl, readSz)) < 0) + if ((ret = GetInputData(ssl, (word32)readSz)) < 0) return ret; } #endif @@ -20892,7 +21252,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #endif if (ret != 0) { switch (ret) { - case VERSION_ERROR: + case WC_NO_ERR_TRACE(VERSION_ERROR): /* send alert per RFC5246 Appendix E. Backward * Compatibility */ if (ssl->options.side == WOLFSSL_CLIENT_END) @@ -20900,7 +21260,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) wolfssl_alert_protocol_version); break; #ifdef HAVE_MAX_FRAGMENT - case LENGTH_ERROR: + case WC_NO_ERR_TRACE(LENGTH_ERROR): SendAlert(ssl, alert_fatal, record_overflow); break; #endif /* HAVE_MAX_FRAGMENT */ @@ -20987,7 +21347,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->buffers.inputBuffer.idx, ssl->curSize, ssl->curRL.type); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif if (ret < 0) { @@ -21134,7 +21494,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif @@ -21218,7 +21578,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->curSize, ssl->curRL.type, &ssl->keys.padSz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif if (ret < 0) { @@ -21369,14 +21729,15 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->buffers.inputBuffer.buffer, &ssl->buffers.inputBuffer.idx, ssl->buffers.inputBuffer.length); - if (ret == 0 || ret == WC_PENDING_E) { + if (ret == 0 || + ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Reset timeout as we have received a valid * DTLS handshake message */ ssl->dtls_timeout = ssl->dtls_timeout_init; } else { if (SendFatalAlertOnly(ssl, ret) - == SOCKET_ERROR_E) { + == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) { ret = SOCKET_ERROR_E; } } @@ -21417,7 +21778,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) &ssl->buffers.inputBuffer.idx, ssl->buffers.inputBuffer.length); if (ret != 0) { - if (SendFatalAlertOnly(ssl, ret) == SOCKET_ERROR_E) + if (SendFatalAlertOnly(ssl, ret) == + WC_NO_ERR_TRACE(SOCKET_ERROR_E)) ret = SOCKET_ERROR_E; } #else @@ -21457,7 +21819,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) * Current message should have been DtlsMsgStore'ed and * should be processed with DtlsMsgDrain */ && (!ssl->options.dtls - || ret != WC_PENDING_E) + || ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif ) { WOLFSSL_ERROR(ret); @@ -21570,7 +21932,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* Check for duplicate CCS message in DTLS mode. * DTLS allows for duplicate messages, and it should be * skipped. Also skip if out of order. */ - if (ret != DUPLICATE_MSG_E && ret != OUT_OF_ORDER_E) + if (ret != WC_NO_ERR_TRACE(DUPLICATE_MSG_E) && + ret != WC_NO_ERR_TRACE(OUT_OF_ORDER_E)) return ret; /* Reset error */ ret = 0; @@ -21665,7 +22028,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) defined(HAVE_SECURE_RENEGOTIATION) /* Not really an error. We will return after cleaning * up the processReply state. */ - if (ret != APP_DATA_READY) + if (ret != WC_NO_ERR_TRACE(APP_DATA_READY)) #endif return ret; } @@ -21794,7 +22157,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #endif #if defined(WOLFSSL_DTLS13) || defined(HAVE_SECURE_RENEGOTIATION) /* Signal to user that we have application data ready to read */ - if (ret == APP_DATA_READY) + if (ret == WC_NO_ERR_TRACE(APP_DATA_READY)) return ret; #endif /* It is safe to shrink the input buffer here now. local vars will @@ -21868,7 +22231,7 @@ int SendChangeCipher(WOLFSSL* ssl) input[0] = 1; /* turn it on */ #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, inputSz, change_cipher_hs)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, change_cipher_hs)) != 0) { return ret; } #endif @@ -21881,7 +22244,7 @@ int SendChangeCipher(WOLFSSL* ssl) #ifdef WOLFSSL_DTLS else { if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, change_cipher_hs)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, change_cipher_hs)) != 0) return ret; DtlsSEQIncrement(ssl, CUR_ORDER); } @@ -21985,7 +22348,7 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, ret = wc_Md5Final(&md5, result); #ifdef WOLFSSL_ASYNC_CRYPT /* TODO: Make non-blocking */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE); } #endif @@ -22005,7 +22368,7 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, ret = wc_Md5Final(&md5, digest); #ifdef WOLFSSL_ASYNC_CRYPT /* TODO: Make non-blocking */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE); } #endif @@ -22035,7 +22398,7 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, ret = wc_ShaFinal(&sha, result); #ifdef WOLFSSL_ASYNC_CRYPT /* TODO: Make non-blocking */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE); } #endif @@ -22055,7 +22418,7 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, ret = wc_ShaFinal(&sha, digest); #ifdef WOLFSSL_ASYNC_CRYPT /* TODO: Make non-blocking */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE); } #endif @@ -22288,7 +22651,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args = &ssl->async->buildArgs; ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_buildmsg; @@ -22302,7 +22665,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* Reset state */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_NO_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E)) #endif { ret = 0; @@ -22531,7 +22894,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, { if (ssl->ctx->MacEncryptCb) { ret = ssl->ctx->MacEncryptCb(ssl, output + args->idx, - output + args->headerSz + args->ivSz, inSz, + output + args->headerSz + args->ivSz, (unsigned int)inSz, type, 0, output + args->headerSz, output + args->headerSz, args->size, ssl->MacEncryptCtx); @@ -22563,7 +22926,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif ret = ssl->hmac(ssl, hmac, - output + args->headerSz + args->ivSz, inSz, + output + args->headerSz + args->ivSz, (word32)inSz, -1, type, 0, epochOrder); XMEMCPY(output + args->idx, hmac, args->digestSz); @@ -22575,7 +22938,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif { ret = ssl->hmac(ssl, output + args->idx, output + - args->headerSz + args->ivSz, inSz, -1, type, 0, epochOrder); + args->headerSz + args->ivSz, (word32)inSz, -1, type, 0, epochOrder); } } #endif /* WOLFSSL_AEAD_ONLY */ @@ -22636,7 +22999,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, if (ret != 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* Zeroize plaintext. */ @@ -22713,7 +23076,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, WOLFSSL_LEAVE("BuildMessage", ret); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -22728,7 +23091,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* return sz on success */ if (ret == 0) { - ret = args->sz; + ret = (int)args->sz; } else { WOLFSSL_ERROR_VERBOSE(ret); @@ -22925,7 +23288,7 @@ static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, InitDecodedCert(cert, certData, length, ssl->heap); /* TODO: Setup async support here */ - ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, SSL_CM(ssl)); + ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, SSL_CM(ssl), NULL); if (ret != 0) { WOLFSSL_MSG("ParseCert failed"); } @@ -23022,9 +23385,9 @@ int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest, ssl->heap); /* Suppressing, not critical */ - if (ret == OCSP_CERT_REVOKED || - ret == OCSP_CERT_UNKNOWN || - ret == OCSP_LOOKUP_FAIL) { + if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) || + ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) { ret = 0; } } @@ -23076,6 +23439,9 @@ int SendCertificate(WOLFSSL* ssl) int ret = 0; word32 certSz, certChainSz, headerSz, listSz, payloadSz; word32 length, maxFragment; +#ifdef HAVE_RPK + int usingRpkTls12 = 0; +#endif /* HAVE_RPK */ WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND); WOLFSSL_ENTER("SendCertificate"); @@ -23085,6 +23451,21 @@ int SendCertificate(WOLFSSL* ssl) return 0; /* not needed */ } +#ifdef HAVE_RPK + if (!IsAtLeastTLSv1_3(ssl->version)) { + /* If this is (D)TLS1.2 and RPK, then single cert, not list. */ + if (ssl->options.side == WOLFSSL_SERVER_END) { + if (ssl->options.rpkState.sending_ServerCertTypeCnt == 1 && + ssl->options.rpkState.sending_ServerCertTypes[0] == WOLFSSL_CERT_TYPE_RPK) + usingRpkTls12 = 1; + } else if (ssl->options.side == WOLFSSL_CLIENT_END) { + if (ssl->options.rpkState.sending_ClientCertTypeCnt == 1 && + ssl->options.rpkState.sending_ClientCertTypes[0] == WOLFSSL_CERT_TYPE_RPK) + usingRpkTls12 = 1; + } + } +#endif /* HAVE_RPK */ + if (ssl->options.sendVerify == SEND_BLANK_CERT) { #ifdef OPENSSL_EXTRA if (ssl->version.major == SSLv3_MAJOR @@ -23107,10 +23488,19 @@ int SendCertificate(WOLFSSL* ssl) return BUFFER_ERROR; } certSz = ssl->buffers.certificate->length; - headerSz = 2 * CERT_HEADER_SZ; +#ifdef HAVE_RPK + if (usingRpkTls12) { + headerSz = 1 * CERT_HEADER_SZ; + listSz = certSz; + } else { +#endif /* HAVE_RPK */ + headerSz = 2 * CERT_HEADER_SZ; + listSz = certSz + CERT_HEADER_SZ; +#ifdef HAVE_RPK + } +#endif /* HAVE_RPK */ /* list + cert size */ length = certSz + headerSz; - listSz = certSz + CERT_HEADER_SZ; /* may need to send rest of chain, already has leading size(s) */ if (certSz && ssl->buffers.certChain) { @@ -23129,7 +23519,7 @@ int SendCertificate(WOLFSSL* ssl) maxFragment = MAX_RECORD_SIZE; - maxFragment = wolfSSL_GetMaxFragSize(ssl, maxFragment); + maxFragment = (word32)wolfSSL_GetMaxFragSize(ssl, (int)maxFragment); while (length > 0 && ret == 0) { byte* output = NULL; @@ -23203,12 +23593,18 @@ int SendCertificate(WOLFSSL* ssl) } /* list total */ - c32to24(listSz, output + i); - if (ssl->options.dtls || !IsEncryptionOn(ssl, 1)) - HashRaw(ssl, output + i, CERT_HEADER_SZ); - i += CERT_HEADER_SZ; - length -= CERT_HEADER_SZ; - fragSz -= CERT_HEADER_SZ; +#ifdef HAVE_RPK + if (!usingRpkTls12) { +#endif /* HAVE_RPK */ + c32to24(listSz, output + i); + if (ssl->options.dtls || !IsEncryptionOn(ssl, 1)) + HashRaw(ssl, output + i, CERT_HEADER_SZ); + i += CERT_HEADER_SZ; + length -= CERT_HEADER_SZ; + fragSz -= CERT_HEADER_SZ; +#ifdef HAVE_RPK + } +#endif /* HAVE_RPK */ if (certSz) { c32to24(certSz, output + i); if (ssl->options.dtls || !IsEncryptionOn(ssl, 1)) @@ -23218,10 +23614,10 @@ int SendCertificate(WOLFSSL* ssl) fragSz -= CERT_HEADER_SZ; if (ssl->options.dtls || !IsEncryptionOn(ssl, 1)) { - HashRaw(ssl, ssl->buffers.certificate->buffer, certSz); + HashRaw(ssl, ssl->buffers.certificate->buffer, (int)certSz); if (certChainSz) HashRaw(ssl, ssl->buffers.certChain->buffer, - certChainSz); + (int)certChainSz); } } } @@ -23260,7 +23656,7 @@ int SendCertificate(WOLFSSL* ssl) if (IsEncryptionOn(ssl, 1)) { byte* input = NULL; - int inputSz = i; /* build msg adds rec hdr */ + int inputSz = (int)i; /* build msg adds rec hdr */ int recordHeaderSz = RECORD_HEADER_SZ; if (ssl->options.dtls) @@ -23289,7 +23685,7 @@ int SendCertificate(WOLFSSL* ssl) handshake, 1, 0, 0, CUR_ORDER); else /* DTLS 1.2 has to ignore fragmentation in hashing so we need to * calculate the hash ourselves above */ { - if ((ret = DtlsMsgPoolSave(ssl, input, inputSz, certificate)) != 0) { + if ((ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, certificate)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -23304,10 +23700,10 @@ int SendCertificate(WOLFSSL* ssl) return sendSz; } else { - sendSz = i; + sendSz = (int)i; #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, certificate)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, certificate)) != 0) return ret; } if (ssl->options.dtls) @@ -23420,7 +23816,7 @@ int SendCertificateRequest(WOLFSSL* ssl) /* get output buffer */ output = GetOutputBuffer(ssl); - AddHeaders(output, reqSz, certificate_request, ssl); + AddHeaders(output, (word32)reqSz, certificate_request, ssl); /* write to output */ output[i++] = (byte)typeTotal; /* # of types */ @@ -23487,7 +23883,7 @@ int SendCertificateRequest(WOLFSSL* ssl) if (IsEncryptionOn(ssl, 1)) { byte* input = NULL; - int inputSz = i; /* build msg adds rec hdr */ + int inputSz = (int)i; /* build msg adds rec hdr */ int recordHeaderSz = RECORD_HEADER_SZ; if (ssl->options.dtls) @@ -23506,7 +23902,7 @@ int SendCertificateRequest(WOLFSSL* ssl) XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, inputSz, certificate_request)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, certificate_request)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -23518,10 +23914,10 @@ int SendCertificateRequest(WOLFSSL* ssl) if (sendSz < 0) return sendSz; } else { - sendSz = i; + sendSz = (int)i; #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, certificate_request)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, certificate_request)) != 0) return ret; } if (ssl->options.dtls) @@ -23565,6 +23961,7 @@ static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status, byte* output = NULL; word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; word32 length = ENUM_LEN; + word32 headerSz= idx; int sendSz = 0; int ret = 0; int i = 0; @@ -23584,88 +23981,42 @@ static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status, default: return 0; } +#ifdef WOLFSSL_DTLS + if (ssl->options.dtls) { + headerSz = idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ; + sendSz = idx + length; - sendSz = idx + length; + } else +#endif + sendSz = (int)(idx + length); if (ssl->keys.encryptionOn) sendSz += MAX_MSG_EXTRA; - /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state - * is not advanced yet */ - ssl->options.buildingMsg = 1; - - if ((ret = CheckAvailableSize(ssl, sendSz)) == 0) { - output = GetOutputBuffer(ssl); - - AddHeaders(output, length, certificate_status, ssl); - - output[idx++] = type; - - if (type == WOLFSSL_CSR2_OCSP_MULTI) { - c32to24(length - (ENUM_LEN + OPAQUE24_LEN), output + idx); - idx += OPAQUE24_LEN; - } + output =(byte*)XMALLOC(sendSz, ssl->heap, DYNAMIC_TYPE_OCSP); + if (output == NULL) + return MEMORY_E; - for (i = 0; i < count; i++) { - c32to24(status[i].length, output + idx); - idx += OPAQUE24_LEN; + AddHeaders(output, length, certificate_status, ssl); - XMEMCPY(output + idx, status[i].buffer, status[i].length); - idx += status[i].length; - } + output[idx++] = type; - if (IsEncryptionOn(ssl, 1)) { - byte* input; - int inputSz = idx; /* build msg adds rec hdr */ - int recordHeaderSz = RECORD_HEADER_SZ; - - if (ssl->options.dtls) - recordHeaderSz += DTLS_RECORD_EXTRA; - inputSz -= recordHeaderSz; - input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); - if (input == NULL) - return MEMORY_E; - - XMEMCPY(input, output + recordHeaderSz, inputSz); - #ifdef WOLFSSL_DTLS - ret = DtlsMsgPoolSave(ssl, input, inputSz, certificate_status); - #endif - if (ret == 0) - sendSz = BuildMessage(ssl, output, sendSz, input, inputSz, - handshake, 1, 0, 0, CUR_ORDER); - XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); - - if (sendSz < 0) - ret = sendSz; - } - else { - #ifdef WOLFSSL_DTLS - if (ret == 0 && IsDtlsNotSctpMode(ssl)) - ret = DtlsMsgPoolSave(ssl, output, sendSz, certificate_status); - if (ret == 0 && ssl->options.dtls) - DtlsSEQIncrement(ssl, CUR_ORDER); - #endif - ret = HashOutput(ssl, output, sendSz, 0); - } + if (type == WOLFSSL_CSR2_OCSP_MULTI) { + c32to24(length - (ENUM_LEN + OPAQUE24_LEN), output + idx); + idx += OPAQUE24_LEN; + } - #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) - if (ret == 0 && ssl->hsInfoOn) - AddPacketName(ssl, "CertificateStatus"); - if (ret == 0 && ssl->toInfoOn) { - ret = AddPacketInfo(ssl, "CertificateStatus", handshake, output, - sendSz, WRITE_PROTO, 0, ssl->heap); - if (ret != 0) - return ret; - } - #endif + for (i = 0; i < count; i++) { + c32to24(status[i].length, output + idx); + idx += OPAQUE24_LEN; - if (ret == 0) { - ssl->options.buildingMsg = 0; - ssl->buffers.outputBuffer.length += sendSz; - if (!ssl->options.groupMessages) - ret = SendBuffered(ssl); - } + XMEMCPY(output + idx, status[i].buffer, status[i].length); + idx += status[i].length; } + /* Send Message. Handled message fragmentation in the function if needed */ + ret = SendHandshakeMsg(ssl, output, (sendSz - headerSz), certificate_status, + "Certificate Status"); + XFREE(output, ssl->heap, DYNAMIC_TYPE_OCSP); WOLFSSL_LEAVE("BuildCertificateStatus", ret); return ret; @@ -23718,7 +24069,8 @@ int SendCertificateStatus(WOLFSSL* ssl) } /* Let's not error out the connection if we can't verify our cert */ - if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E) + if (ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E) || + ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E)) ret = 0; if (response.buffer) { @@ -23801,9 +24153,9 @@ int SendCertificateStatus(WOLFSSL* ssl) request, &responses[i + 1], ssl->heap); /* Suppressing, not critical */ - if (ret == OCSP_CERT_REVOKED || - ret == OCSP_CERT_UNKNOWN || - ret == OCSP_LOOKUP_FAIL) { + if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) || + ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) { ret = 0; } @@ -23827,9 +24179,9 @@ int SendCertificateStatus(WOLFSSL* ssl) request, &responses[++i], ssl->heap); /* Suppressing, not critical */ - if (ret == OCSP_CERT_REVOKED || - ret == OCSP_CERT_UNKNOWN || - ret == OCSP_LOOKUP_FAIL) { + if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) || + ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) { ret = 0; } } @@ -23850,7 +24202,8 @@ int SendCertificateStatus(WOLFSSL* ssl) } /* Let's not error out the connection if we can't verify our cert */ - if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E) + if (ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E) || + ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E)) ret = 0; break; @@ -24104,7 +24457,8 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) } /* don't allow write after decrypt or mac error */ - if (ssl->error == VERIFY_MAC_ERROR || ssl->error == DECRYPT_ERROR) { + if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || + ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR)) { /* For DTLS allow these possible errors and allow the session to continue despite them */ if (ssl->options.dtls) { @@ -24143,7 +24497,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) { #ifdef WOLFSSL_ASYNC_CRYPT /* if async would block return WANT_WRITE */ - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { return WOLFSSL_CBIO_ERR_WANT_WRITE; } #endif @@ -24160,8 +24514,8 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) WOLFSSL_MSG("output buffer was full, trying to send again"); if ( (ssl->error = SendBuffered(ssl)) < 0) { WOLFSSL_ERROR(ssl->error); - if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset || - ssl->options.isClosed)) { + if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && + (ssl->options.connReset || ssl->options.isClosed)) { ssl->error = SOCKET_PEER_CLOSED_E; WOLFSSL_ERROR(ssl->error); return 0; /* peer reset or closed */ @@ -24307,7 +24661,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) } if (sendSz < 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (sendSz == WC_PENDING_E) + if (sendSz == WC_NO_ERR_TRACE(WC_PENDING_E)) ssl->error = sendSz; #endif return BUILD_MSG_ERROR; @@ -24324,8 +24678,8 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) doesn't present like WANT_WRITE */ ssl->buffers.plainSz = buffSz; ssl->buffers.prevSent = sent; - if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset || - ssl->options.isClosed)) { + if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && + (ssl->options.connReset || ssl->options.isClosed)) { ssl->error = SOCKET_PEER_CLOSED_E; WOLFSSL_ERROR(ssl->error); return 0; /* peer reset or closed */ @@ -24361,9 +24715,9 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) if (ssl->options.dtls) { /* In DTLS mode, we forgive some errors and allow the session * to continue despite them. */ - if (ssl->error == VERIFY_MAC_ERROR || - ssl->error == DECRYPT_ERROR || - ssl->error == DTLS_SIZE_ERROR) { + if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || + ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR) || + ssl->error == WC_NO_ERR_TRACE(DTLS_SIZE_ERROR)) { ssl->error = 0; } @@ -24395,7 +24749,7 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) { #ifdef WOLFSSL_ASYNC_CRYPT /* if async would block return WANT_WRITE */ - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { return WOLFSSL_CBIO_ERR_WANT_READ; } #endif @@ -24422,7 +24776,7 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) WOLFSSL_MSG("Zero return, no more data coming"); return 0; /* no more data coming */ } - if (ssl->error == SOCKET_ERROR_E) { + if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) { if (ssl->options.connReset || ssl->options.isClosed) { WOLFSSL_MSG("Peer reset or closed, connection done"); ssl->error = SOCKET_PEER_CLOSED_E; @@ -24458,7 +24812,7 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) { #ifdef WOLFSSL_ASYNC_CRYPT /* if async would block return WANT_WRITE */ - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { return WOLFSSL_CBIO_ERR_WANT_READ; } #endif @@ -24633,6 +24987,11 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) #endif /* WOLFSSL_DTLS13 */ { AddRecordHeader(output, ALERT_SIZE, alert, ssl, CUR_ORDER); +#ifdef WOLFSSL_DTLS + /* AddRecordHeader doesn't increment the seq number */ + if (ssl->options.dtls) + DtlsSEQIncrement(ssl, CUR_ORDER); +#endif } output += RECORD_HEADER_SZ; @@ -24723,6 +25082,10 @@ int SendAlert(WOLFSSL* ssl, int severity, int type) return SendAlert_ex(ssl, severity, type); } +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H +#include +#endif + const char* wolfSSL_ERR_reason_error_string(unsigned long e) { #ifdef NO_ERROR_STRINGS @@ -25261,6 +25624,10 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) #endif /* NO_ERROR_STRINGS */ } +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#include +#endif + const char* wolfSSL_ERR_func_error_string(unsigned long e) { (void)e; @@ -25299,7 +25666,7 @@ const char* wolfSSL_ERR_lib_error_string(unsigned long e) void SetErrorString(int error, char* str) { - XSTRNCPY(str, wolfSSL_ERR_reason_error_string(error), WOLFSSL_MAX_ERROR_SZ); + XSTRNCPY(str, wolfSSL_ERR_reason_error_string((unsigned long)error), WOLFSSL_MAX_ERROR_SZ); str[WOLFSSL_MAX_ERROR_SZ-1] = 0; } @@ -26202,7 +26569,7 @@ const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl) int GetCipherSuiteFromName(const char* name, byte* cipherSuite0, byte* cipherSuite, int* flags) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); int i; unsigned long len; const char* nameDelim; @@ -26273,8 +26640,11 @@ static int ParseCipherList(Suites* suites, return 0; } - if (next[0] == 0 || XSTRCMP(next, "ALL") == 0 || - XSTRCMP(next, "DEFAULT") == 0 || XSTRCMP(next, "HIGH") == 0) { + if (next[0] == '\0' || + XSTRCMP(next, "ALL") == 0 || + XSTRCMP(next, "DEFAULT") == 0 || + XSTRCMP(next, "HIGH") == 0) + { /* Add all ciphersuites except anonymous and null ciphers. Prefer RSA */ #ifndef NO_RSA haveRSA = 1; @@ -26286,7 +26656,8 @@ static int ParseCipherList(Suites* suites, 0, #endif haveRSA, 1, 1, !haveRSA, 1, haveRSA, !haveRSA, 1, 1, 0, 0, - side); + side + ); return 1; /* wolfSSL default */ } @@ -26306,6 +26677,8 @@ static int ParseCipherList(Suites* suites, if (length > currLen) { length = currLen; } + if (currLen == 0) + break; } #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) @@ -26336,7 +26709,7 @@ static int ParseCipherList(Suites* suites, substrCurrent[length] = '\0'; } else { - length = (int)XSTRLEN(substrCurrent); + length = (word32)XSTRLEN(substrCurrent); } /* check if is a public key type */ @@ -26559,14 +26932,12 @@ static int ParseCipherList(Suites* suites, defined(HAVE_ED448) haveSig |= SIG_ECDSA; #endif - #if defined(HAVE_PQC) #ifdef HAVE_FALCON haveSig |= SIG_FALCON; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM haveSig |= SIG_DILITHIUM; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ } else #ifdef BUILD_TLS_SM4_GCM_SM3 @@ -26629,7 +27000,7 @@ static int ParseCipherList(Suites* suites, } } } - while (next++); /* ++ needed to skip ':' */ + while (next++); /* increment to skip ':' */ if (ret) { int keySz = 0; @@ -26659,7 +27030,7 @@ static int ParseCipherList(Suites* suites, #endif { suites->suiteSz = (word16)idx; - InitSuitesHashSigAlgo_ex2(suites->hashSigAlgo, haveSig, 1, keySz, + InitSuitesHashSigAlgo(suites->hashSigAlgo, haveSig, 1, keySz, &suites->hashSigAlgoSz); } @@ -26678,7 +27049,9 @@ static int ParseCipherList(Suites* suites, suites->setSuites = 1; } +#ifdef NO_CERTS (void)privateKeySz; +#endif return ret; } @@ -26796,14 +27169,12 @@ int SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites, const byte* list, #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) haveECDSAsig = 1; #endif - #if defined(HAVE_PQC) #ifdef HAVE_FALCON haveFalconSig = 1; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM haveDilithiumSig = 1; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ } else #endif /* WOLFSSL_TLS13 */ @@ -26843,7 +27214,7 @@ int SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites, const byte* list, haveSig |= haveFalconSig ? SIG_FALCON : 0; haveSig |= haveDilithiumSig ? SIG_DILITHIUM : 0; haveSig |= haveAnon ? SIG_ANON : 0; - InitSuitesHashSigAlgo_ex2(suites->hashSigAlgo, haveSig, 1, keySz, + InitSuitesHashSigAlgo(suites->hashSigAlgo, haveSig, 1, keySz, &suites->hashSigAlgoSz); #ifdef HAVE_RENEGOTIATION_INDICATION if (ctx->method->side == WOLFSSL_CLIENT_END) { @@ -27044,7 +27415,6 @@ static int MatchSigAlgo(WOLFSSL* ssl, int sigAlgo) return sigAlgo == ed448_sa_algo; } #endif -#ifdef HAVE_PQC #ifdef HAVE_FALCON if (ssl->pkCurveOID == CTC_FALCON_LEVEL1) { /* Certificate has Falcon level 1 key, only match with Falcon level 1 @@ -27071,7 +27441,6 @@ static int MatchSigAlgo(WOLFSSL* ssl, int sigAlgo) return sigAlgo == dilithium_level5_sa_algo; } #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ #ifdef WC_RSA_PSS /* RSA certificate and PSS sig alg. */ if (ssl->options.sigAlgo == rsa_sa_algo) { @@ -27122,10 +27491,43 @@ static byte MinHashAlgo(WOLFSSL* ssl) return sha_mac; } -int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) +/* Check if a given peer hashSigAlgo is supported in our ssl->suites or + * ssl->ctx->suites. + * + * Returns 1 on match. + * Returns 0 otherwise. + * */ +static int SupportedHashSigAlgo(WOLFSSL* ssl, const byte * hashSigAlgo) +{ + const Suites * suites = NULL; + word32 i = 0; + + if (ssl == NULL || hashSigAlgo == NULL) { + return 0; + } + + suites = WOLFSSL_SUITES(ssl); + + if (suites == NULL || suites->hashSigAlgoSz == 0) { + return 0; + } + + for (i = 0; (i+1) < suites->hashSigAlgoSz; i += HELLO_EXT_SIGALGO_SZ) { + if (XMEMCMP(&suites->hashSigAlgo[i], hashSigAlgo, + HELLO_EXT_SIGALGO_SZ) == 0) { + /* Match found. */ + return 1; + } + } + + return 0; +} + +int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz, + int matchSuites) { word32 i; - int ret = MATCH_SUITE_ERROR; + int ret = WC_NO_ERR_TRACE(MATCH_SUITE_ERROR); byte minHash; /* set defaults */ @@ -27163,6 +27565,14 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) if (!MatchSigAlgo(ssl, sigAlgo)) continue; + if (matchSuites) { + /* Keep looking if peer algorithm isn't supported in our ssl->suites + * or ssl->ctx->suites. */ + if (!SupportedHashSigAlgo(ssl, &hashSigAlgo[i])) { + continue; + } + } + #ifdef HAVE_ED25519 if (ssl->pkCurveOID == ECC_ED25519_OID) { /* Matched Ed25519 - set chosen and finished. */ @@ -27181,7 +27591,6 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) break; } #endif - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) if (ssl->pkCurveOID == CTC_FALCON_LEVEL1 || ssl->pkCurveOID == CTC_FALCON_LEVEL5 ) { @@ -27203,7 +27612,6 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) break; } #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ #if defined(WOLFSSL_ECDSA_MATCH_HASH) && defined(USE_ECDSA_KEYSZ_HASH_ALGO) #error "WOLFSSL_ECDSA_MATCH_HASH and USE_ECDSA_KEYSZ_HASH_ALGO cannot " @@ -27564,7 +27972,7 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz) int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, int label, int id, void* heap, int devId) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); if (hsType == DYNAMIC_TYPE_RSA) { #ifndef NO_RSA @@ -27579,7 +27987,7 @@ int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, ret = wc_InitRsaKey_Label(rsaKey, (char*)data, heap, devId); } else if (id) { - ret = wc_InitRsaKey_Id(rsaKey, data, length, heap, devId); + ret = wc_InitRsaKey_Id(rsaKey, data, (int)length, heap, devId); } if (ret == 0) { *pkey = (void*)rsaKey; @@ -27602,7 +28010,7 @@ int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, ret = wc_ecc_init_label(ecKey, (char*)data, heap, devId); } else if (id) { - ret = wc_ecc_init_id(ecKey, data, length, heap, devId); + ret = wc_ecc_init_id(ecKey, data, (int)length, heap, devId); } if (ret == 0) { *pkey = (void*)ecKey; @@ -27613,7 +28021,7 @@ int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, #endif } else if (hsType == DYNAMIC_TYPE_DILITHIUM) { -#if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) dilithium_key* dilithiumKey; dilithiumKey = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, @@ -27638,7 +28046,7 @@ int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, #endif } else if (hsType == DYNAMIC_TYPE_FALCON) { -#if defined(HAVE_PQC) && defined(HAVE_FALCON) +#if defined(HAVE_FALCON) falcon_key* falconKey; falconKey = (falcon_key*)XMALLOC(sizeof(falcon_key), heap, @@ -27676,9 +28084,9 @@ int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, * length The length of a signature. * returns 0 on success, otherwise failure. */ -int DecodePrivateKey(WOLFSSL *ssl, word16* length) +int DecodePrivateKey(WOLFSSL *ssl, word32* length) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); int keySz; word32 idx; @@ -27691,7 +28099,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx) #endif ) { - *length = (word16)GetPrivateKeySigSize(ssl); + *length = (word32)GetPrivateKeySigSize(ssl); return 0; } else @@ -27709,9 +28117,12 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) ssl->hsType = DYNAMIC_TYPE_RSA; else if (ssl->buffers.keyType == ecc_dsa_sa_algo) ssl->hsType = DYNAMIC_TYPE_ECC; - else if (ssl->buffers.keyType == falcon_level5_sa_algo) + else if ((ssl->buffers.keyType == falcon_level1_sa_algo) || + (ssl->buffers.keyType == falcon_level5_sa_algo)) ssl->hsType = DYNAMIC_TYPE_FALCON; - else if (ssl->buffers.keyType == dilithium_level5_sa_algo) + else if ((ssl->buffers.keyType == dilithium_level2_sa_algo) || + (ssl->buffers.keyType == dilithium_level3_sa_algo) || + (ssl->buffers.keyType == dilithium_level5_sa_algo)) ssl->hsType = DYNAMIC_TYPE_DILITHIUM; ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); if (ret != 0) { @@ -27738,7 +28149,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)ssl->buffers.keySz; + *length = (word32)ssl->buffers.keySz; } #else ret = NOT_COMPILED_IN; @@ -27764,14 +28175,15 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)wc_ecc_sig_size_calc(ssl->buffers.keySz); + *length = (word32)wc_ecc_sig_size_calc(ssl->buffers.keySz); } #else ret = NOT_COMPILED_IN; #endif } - else if (ssl->buffers.keyType == falcon_level5_sa_algo) { - #if defined(HAVE_PQC) && defined(HAVE_FALCON) + else if ((ssl->buffers.keyType == falcon_level1_sa_algo) || + (ssl->buffers.keyType == falcon_level5_sa_algo)) { + #if defined(HAVE_FALCON) if (ssl->buffers.keyLabel) { ret = wc_falcon_init_label((falcon_key*)ssl->hsKey, (char*)ssl->buffers.key->buffer, @@ -27783,6 +28195,14 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) ssl->buffers.key->length, ssl->heap, ssl->buffers.keyDevId); } + if (ret == 0) { + if (ssl->buffers.keyType == falcon_level1_sa_algo) { + ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 1); + } + else if (ssl->buffers.keyType == falcon_level5_sa_algo) { + ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 5); + } + } if (ret == 0) { if (ssl->buffers.keySz < ssl->options.minFalconKeySz) { WOLFSSL_MSG("Falcon key size too small"); @@ -27790,14 +28210,16 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)wc_falcon_sig_size((falcon_key*)ssl->hsKey); + *length = wc_falcon_sig_size((falcon_key*)ssl->hsKey); } #else ret = NOT_COMPILED_IN; #endif } - else if (ssl->buffers.keyType == dilithium_level5_sa_algo) { - #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) + else if ((ssl->buffers.keyType == dilithium_level2_sa_algo) || + (ssl->buffers.keyType == dilithium_level3_sa_algo) || + (ssl->buffers.keyType == dilithium_level5_sa_algo)) { + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) if (ssl->buffers.keyLabel) { ret = wc_dilithium_init_label((dilithium_key*)ssl->hsKey, (char*)ssl->buffers.key->buffer, @@ -27809,6 +28231,17 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) ssl->buffers.key->length, ssl->heap, ssl->buffers.keyDevId); } + if (ret == 0) { + if (ssl->buffers.keyType == dilithium_level2_sa_algo) { + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 2); + } + else if (ssl->buffers.keyType == dilithium_level3_sa_algo) { + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 3); + } + else if (ssl->buffers.keyType == dilithium_level5_sa_algo) { + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 5); + } + } if (ret == 0) { if (ssl->buffers.keySz < ssl->options.minDilithiumKeySz) { WOLFSSL_MSG("Dilithium key size too small"); @@ -27816,7 +28249,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)wc_dilithium_sig_size( + *length = wc_dilithium_sig_size( (dilithium_key*)ssl->hsKey); } #else @@ -27870,7 +28303,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)keySz; + *length = (word32)keySz; goto exit_dpk; } @@ -27918,6 +28351,12 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) (ecc_key*)ssl->hsKey, ssl->buffers.key->length); } + #endif + #ifdef WOLFSSL_SM2 + if ((ret == 0) && (ssl->buffers.keyType == sm2_sa_algo)) { + ret = wc_ecc_set_curve((ecc_key*)ssl->hsKey, + WOLFSSL_SM2_KEY_BITS / 8, ECC_SM2P256V1); + } #endif if (ret == 0) { WOLFSSL_MSG("Using ECC private key"); @@ -27930,7 +28369,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } /* Return the maximum signature length. */ - *length = (word16)wc_ecc_sig_size((ecc_key*)ssl->hsKey); + *length = (word32)wc_ecc_sig_size((ecc_key*)ssl->hsKey); goto exit_dpk; } @@ -28050,7 +28489,6 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) } } #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) #if !defined(NO_RSA) || defined(HAVE_ECC) FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey); @@ -28104,19 +28542,21 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) WOLFSSL_MSG("Using Falcon private key"); /* Check it meets the minimum Falcon key size requirements. */ - if (FALCON_MAX_KEY_SIZE < ssl->options.minFalconKeySz) { + keySz = wc_falcon_size((falcon_key*)ssl->hsKey); + if (keySz < ssl->options.minFalconKeySz) { WOLFSSL_MSG("Falcon key size too small"); ERROR_OUT(FALCON_KEY_SIZE_E, exit_dpk); } /* Return the maximum signature length. */ - *length = FALCON_MAX_SIG_SIZE; + *length = wc_falcon_sig_size((falcon_key*)ssl->hsKey); goto exit_dpk; } } #endif /* HAVE_FALCON */ -#if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_ASN1) #if !defined(NO_RSA) || defined(HAVE_ECC) FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey); #endif @@ -28168,26 +28608,27 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) /* Set start of data to beginning of buffer. */ idx = 0; /* Decode the key assuming it is a Dilithium private key. */ - ret = wc_dilithium_import_private_only(ssl->buffers.key->buffer, - ssl->buffers.key->length, - (dilithium_key*)ssl->hsKey); + ret = wc_Dilithium_PrivateKeyDecode(ssl->buffers.key->buffer, + &idx, + (dilithium_key*)ssl->hsKey, + ssl->buffers.key->length); if (ret == 0) { WOLFSSL_MSG("Using Dilithium private key"); /* Check it meets the minimum Dilithium key size requirements. */ - if (DILITHIUM_MAX_KEY_SIZE < ssl->options.minDilithiumKeySz) { + keySz = wc_dilithium_size((dilithium_key*)ssl->hsKey); + if (keySz < ssl->options.minDilithiumKeySz) { WOLFSSL_MSG("Dilithium key size too small"); ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dpk); } /* Return the maximum signature length. */ - *length = DILITHIUM_MAX_SIG_SIZE; + *length = wc_dilithium_sig_size((dilithium_key*)ssl->hsKey); goto exit_dpk; } } #endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ (void)idx; (void)keySz; @@ -28201,12 +28642,15 @@ int DecodePrivateKey(WOLFSSL *ssl, word16* length) return ret; } -#if defined(HAVE_PQC) && defined(WOLFSSL_DUAL_ALG_CERTS) -/* This is just like the above, but only consider Falcon and Dilthium and - * only for the alternative key; not the native key. */ -int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) +#if defined(WOLFSSL_DUAL_ALG_CERTS) +/* This is just like the above, but only consider RSA, ECC, Falcon and + * Dilthium; Furthermore, use the alternative key, not the native key. + */ +int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + int keySz; + word32 idx; /* make sure alt private key exists */ if (ssl->buffers.altKey == NULL || ssl->buffers.altKey->buffer == NULL) { @@ -28214,8 +28658,282 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) ERROR_OUT(NO_PRIVATE_KEY, exit_dapk); } +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.altKey, ssl->buffers.altKeyMask); +#endif + +#ifdef WOLF_PRIVATE_KEY_ID + if (ssl->buffers.altKeyDevId != INVALID_DEVID && + (ssl->buffers.altKeyId || ssl->buffers.altKeyLabel)) { + if (ssl->buffers.altKeyType == rsa_sa_algo) + ssl->hsAltType = DYNAMIC_TYPE_RSA; + else if (ssl->buffers.altKeyType == ecc_dsa_sa_algo) + ssl->hsAltType = DYNAMIC_TYPE_ECC; + else if ((ssl->buffers.altKeyType == falcon_level1_sa_algo) || + (ssl->buffers.altKeyType == falcon_level5_sa_algo)) + ssl->hsAltType = DYNAMIC_TYPE_FALCON; + else if ((ssl->buffers.altKeyType == dilithium_level2_sa_algo) || + (ssl->buffers.altKeyType == dilithium_level3_sa_algo) || + (ssl->buffers.altKeyType == dilithium_level5_sa_algo)) + ssl->hsAltType = DYNAMIC_TYPE_DILITHIUM; + ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey); + if (ret != 0) { + goto exit_dapk; + } + + if (ssl->buffers.altKeyType == rsa_sa_algo) { + #ifndef NO_RSA + if (ssl->buffers.altKeyLabel) { + ret = wc_InitRsaKey_Label((RsaKey*)ssl->hsAltKey, + (char*)ssl->buffers.altKey->buffer, + ssl->heap, ssl->buffers.altKeyDevId); + } + else if (ssl->buffers.altKeyId) { + ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsAltKey, + ssl->buffers.altKey->buffer, + ssl->buffers.altKey->length, ssl->heap, + ssl->buffers.altKeyDevId); + } + if (ret == 0) { + if (ssl->buffers.altKeySz < ssl->options.minRsaKeySz) { + WOLFSSL_MSG("RSA key size too small"); + ERROR_OUT(RSA_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = ssl->buffers.altKeySz; + } + #else + ret = NOT_COMPILED_IN; + #endif + } + else if (ssl->buffers.altKeyType == ecc_dsa_sa_algo) { + #ifdef HAVE_ECC + if (ssl->buffers.altKeyLabel) { + ret = wc_ecc_init_label((ecc_key*)ssl->hsAltKey, + (char*)ssl->buffers.altKey->buffer, + ssl->heap, ssl->buffers.altKeyDevId); + } + else if (ssl->buffers.altKeyId) { + ret = wc_ecc_init_id((ecc_key*)ssl->hsAltKey, + ssl->buffers.altKey->buffer, + ssl->buffers.altKey->length, ssl->heap, + ssl->buffers.altKeyDevId); + } + if (ret == 0) { + if (ssl->buffers.altKeySz < ssl->options.minEccKeySz) { + WOLFSSL_MSG("ECC key size too small"); + ERROR_OUT(ECC_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = wc_ecc_sig_size_calc(ssl->buffers.altKeySz); + } + #else + ret = NOT_COMPILED_IN; + #endif + } + else if ((ssl->buffers.altKeyType == falcon_level1_sa_algo) || + (ssl->buffers.altKeyType == falcon_level5_sa_algo)) { + #if defined(HAVE_FALCON) + if (ssl->buffers.altKeyLabel) { + ret = wc_falcon_init_label((falcon_key*)ssl->hsAltKey, + (char*)ssl->buffers.altKey->buffer, + ssl->heap, ssl->buffers.altKeyDevId); + } + else if (ssl->buffers.altKeyId) { + ret = wc_falcon_init_id((falcon_key*)ssl->hsAltKey, + ssl->buffers.altKey->buffer, + ssl->buffers.altKey->length, ssl->heap, + ssl->buffers.altKeyDevId); + } + if (ret == 0) { + if (ssl->buffers.altKeyType == falcon_level1_sa_algo) { + ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 1); + } + else if (ssl->buffers.altKeyType == falcon_level5_sa_algo) { + ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 5); + } + } + if (ret == 0) { + if (ssl->buffers.altKeySz < ssl->options.minFalconKeySz) { + WOLFSSL_MSG("Falcon key size too small"); + ERROR_OUT(FALCON_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = wc_falcon_sig_size((falcon_key*)ssl->hsAltKey); + } + #else + ret = NOT_COMPILED_IN; + #endif + } + else if ((ssl->buffers.altKeyType == dilithium_level2_sa_algo) || + (ssl->buffers.altKeyType == dilithium_level3_sa_algo) || + (ssl->buffers.altKeyType == dilithium_level5_sa_algo)) { + #if defined(HAVE_DILITHIUM) + if (ssl->buffers.altKeyLabel) { + ret = wc_dilithium_init_label((dilithium_key*)ssl->hsAltKey, + (char*)ssl->buffers.altKey->buffer, + ssl->heap, ssl->buffers.altKeyDevId); + } + else if (ssl->buffers.altKeyId) { + ret = wc_dilithium_init_id((dilithium_key*)ssl->hsAltKey, + ssl->buffers.altKey->buffer, + ssl->buffers.altKey->length, ssl->heap, + ssl->buffers.altKeyDevId); + } + if (ret == 0) { + if (ssl->buffers.altKeyType == dilithium_level2_sa_algo) { + ret = wc_dilithium_set_level( + (dilithium_key*)ssl->hsAltKey, 2); + } + else if (ssl->buffers.altKeyType == dilithium_level3_sa_algo) { + ret = wc_dilithium_set_level( + (dilithium_key*)ssl->hsAltKey, 3); + } + else if (ssl->buffers.altKeyType == dilithium_level5_sa_algo) { + ret = wc_dilithium_set_level( + (dilithium_key*)ssl->hsAltKey, 5); + } + } + if (ret == 0) { + if (ssl->buffers.altKeySz < ssl->options.minDilithiumKeySz) { + WOLFSSL_MSG("Dilithium key size too small"); + ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = wc_dilithium_sig_size( + (dilithium_key*)ssl->hsAltKey); + } + #else + ret = NOT_COMPILED_IN; + #endif + } + goto exit_dapk; + } +#endif /* WOLF_PRIVATE_KEY_ID */ + +#ifndef NO_RSA + if (ssl->buffers.altKeyType == rsa_sa_algo || + ssl->buffers.altKeyType == 0) { + ssl->hsAltType = DYNAMIC_TYPE_RSA; + ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey); + if (ret != 0) { + goto exit_dapk; + } + + WOLFSSL_MSG("Trying RSA private key"); + + /* Set start of data to beginning of buffer. */ + idx = 0; + /* Decode the key assuming it is an RSA private key. */ + ret = wc_RsaPrivateKeyDecode(ssl->buffers.altKey->buffer, &idx, + (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* if using external key then allow using a public key */ + if (ret != 0 && (ssl->devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx) + #endif + )) { + WOLFSSL_MSG("Trying RSA public key with crypto callbacks"); + idx = 0; + ret = wc_RsaPublicKeyDecode(ssl->buffers.altKey->buffer, &idx, + (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey->length); + } + #endif + if (ret == 0) { + WOLFSSL_MSG("Using RSA private key"); + + /* It worked so check it meets minimum key size requirements. */ + keySz = wc_RsaEncryptSize((RsaKey*)ssl->hsAltKey); + if (keySz < 0) { /* check if keySz has error case */ + ERROR_OUT(keySz, exit_dapk); + } + + if (keySz < ssl->options.minRsaKeySz) { + WOLFSSL_MSG("RSA key size too small"); + ERROR_OUT(RSA_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = keySz; + + goto exit_dapk; + } + } +#endif /* !NO_RSA */ + +#ifdef HAVE_ECC +#ifndef NO_RSA + FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey); +#endif /* !NO_RSA */ + + if (ssl->buffers.altKeyType == ecc_dsa_sa_algo || + ssl->buffers.altKeyType == 0 + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + || ssl->buffers.altKeyType == sm2_sa_algo + #endif + ) { + ssl->hsAltType = DYNAMIC_TYPE_ECC; + ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey); + if (ret != 0) { + goto exit_dapk; + } + + #ifndef NO_RSA + WOLFSSL_MSG("Trying ECC private key, RSA didn't work"); + #else + WOLFSSL_MSG("Trying ECC private key"); + #endif + + /* Set start of data to beginning of buffer. */ + idx = 0; + /* Decode the key assuming it is an ECC private key. */ + ret = wc_EccPrivateKeyDecode(ssl->buffers.altKey->buffer, &idx, + (ecc_key*)ssl->hsAltKey, + ssl->buffers.altKey->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* if using external key then allow using a public key */ + if (ret != 0 && (ssl->devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx) + #endif + )) { + WOLFSSL_MSG("Trying ECC public key with crypto callbacks"); + idx = 0; + ret = wc_EccPublicKeyDecode(ssl->buffers.altKey->buffer, &idx, + (ecc_key*)ssl->hsAltKey, + ssl->buffers.altKey->length); + } + #endif + if (ret == 0) { + WOLFSSL_MSG("Using ECC private key"); + + /* Check it meets the minimum ECC key size requirements. */ + keySz = wc_ecc_size((ecc_key*)ssl->hsAltKey); + if (keySz < ssl->options.minEccKeySz) { + WOLFSSL_MSG("ECC key size too small"); + ERROR_OUT(ECC_KEY_SIZE_E, exit_dapk); + } + + /* Return the maximum signature length. */ + *length = wc_ecc_sig_size((ecc_key*)ssl->hsAltKey); + + goto exit_dapk; + } + } +#endif +#if defined(HAVE_FALCON) + #if !defined(NO_RSA) || defined(HAVE_ECC) + FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey); + #endif + if (ssl->buffers.altKeyType == falcon_level1_sa_algo || - ssl->buffers.altKeyType == falcon_level5_sa_algo) { + ssl->buffers.altKeyType == falcon_level5_sa_algo || + ssl->buffers.altKeyType == 0) { ssl->hsAltType = DYNAMIC_TYPE_FALCON; ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey); @@ -28230,14 +28948,25 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 5); } else { + /* What if ssl->buffers.keyType is 0? We might want to do something + * more graceful here. */ ret = ALGO_ID_E; } if (ret != 0) { goto exit_dapk; } - WOLFSSL_MSG("Trying Falcon private key"); + #if defined(HAVE_ECC) + WOLFSSL_MSG("Trying Falcon private key, ECC didn't work"); + #elif !defined(NO_RSA) + WOLFSSL_MSG("Trying Falcon private key, RSA didn't work"); + #else + WOLFSSL_MSG("Trying Falcon private key"); + #endif + + /* Set start of data to beginning of buffer. */ + idx = 0; /* Decode the key assuming it is a Falcon private key. */ ret = wc_falcon_import_private_only(ssl->buffers.altKey->buffer, ssl->buffers.altKey->length, @@ -28246,21 +28975,28 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) WOLFSSL_MSG("Using Falcon private key"); /* Check it meets the minimum Falcon key size requirements. */ - if (FALCON_MAX_KEY_SIZE < ssl->options.minFalconKeySz) { + keySz = wc_falcon_size((falcon_key*)ssl->hsAltKey); + if (keySz < ssl->options.minFalconKeySz) { WOLFSSL_MSG("Falcon key size too small"); ERROR_OUT(FALCON_KEY_SIZE_E, exit_dapk); } + /* Return the maximum signature length. */ *length = wc_falcon_sig_size((falcon_key*)ssl->hsAltKey); goto exit_dapk; } } - FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey); +#endif /* HAVE_FALCON */ +#if defined(HAVE_DILITHIUM) + #if !defined(NO_RSA) || defined(HAVE_ECC) + FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey); + #endif if (ssl->buffers.altKeyType == dilithium_level2_sa_algo || ssl->buffers.altKeyType == dilithium_level3_sa_algo || - ssl->buffers.altKeyType == dilithium_level5_sa_algo) { + ssl->buffers.altKeyType == dilithium_level5_sa_algo || + ssl->buffers.altKeyType == 0) { ssl->hsAltType = DYNAMIC_TYPE_DILITHIUM; ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey); @@ -28278,6 +29014,8 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 5); } else { + /* What if ssl->buffers.keyType is 0? We might want to do something + * more graceful here. */ ret = ALGO_ID_E; } @@ -28285,35 +29023,63 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length) goto exit_dapk; } - WOLFSSL_MSG("Trying Dilithium private key"); + #if defined(HAVE_FALCON) + WOLFSSL_MSG("Trying Dilithium private key, Falcon didn't work"); + #elif defined(HAVE_ECC) + WOLFSSL_MSG("Trying Dilithium private key, ECC didn't work"); + #elif !defined(NO_RSA) + WOLFSSL_MSG("Trying Dilithium private key, RSA didn't work"); + #else + WOLFSSL_MSG("Trying Dilithium private key"); + #endif + /* Set start of data to beginning of buffer. */ + idx = 0; /* Decode the key assuming it is a Dilithium private key. */ - ret = wc_dilithium_import_private_only(ssl->buffers.altKey->buffer, - ssl->buffers.altKey->length, - (dilithium_key*)ssl->hsAltKey); + ret = wc_Dilithium_PrivateKeyDecode(ssl->buffers.altKey->buffer, + &idx, + (dilithium_key*)ssl->hsAltKey, + ssl->buffers.altKey->length); if (ret == 0) { WOLFSSL_MSG("Using Dilithium private key"); /* Check it meets the minimum Dilithium key size requirements. */ - if (DILITHIUM_MAX_KEY_SIZE < ssl->options.minDilithiumKeySz) { + keySz = wc_dilithium_size((dilithium_key*)ssl->hsAltKey); + if (keySz < ssl->options.minDilithiumKeySz) { WOLFSSL_MSG("Dilithium key size too small"); ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dapk); } + /* Return the maximum signature length. */ *length = wc_dilithium_sig_size((dilithium_key*)ssl->hsAltKey); goto exit_dapk; } } +#endif /* HAVE_DILITHIUM */ + + (void)idx; + (void)keySz; + (void)length; exit_dapk: +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, + &ssl->buffers.altKeyMask); + } + else { + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + } +#endif + if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); } return ret; } -#endif /* HAVE_PQC && WOLFSSL_DUAL_ALG_CERTS */ +#endif /* WOLFSSL_DUAL_ALG_CERTS */ #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */ #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_TLS12) @@ -28384,7 +29150,7 @@ static int SigAlgoCachesMsgs(int sigAlgo) } static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, - const byte* data, int sz, byte sigAlgo) + const byte* data, word32 sz, byte sigAlgo) { int ret = 0; int digest_sz = wc_HashGetDigestSize(hashType); @@ -28394,11 +29160,16 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } if (ret == 0) { + word32 new_size = SEED_LEN; /* buffer for signature */ - ssl->buffers.sig.buffer = (byte*)XMALLOC(SEED_LEN + sz, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - if (ssl->buffers.sig.buffer == NULL) { + if (! WC_SAFE_SUM_WORD32(new_size, sz, new_size)) ret = MEMORY_E; + else { + ssl->buffers.sig.buffer = (byte*)XMALLOC(new_size, ssl->heap, + DYNAMIC_TYPE_SIGNATURE); + if (ssl->buffers.sig.buffer == NULL) { + ret = MEMORY_E; + } } } if (ret == 0) { @@ -28477,7 +29248,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, int sendSz; int idSz; int ret; - word16 extSz = 0; + word32 extSz = 0; const Suites* suites; if (ssl == NULL) { @@ -28526,7 +29297,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } #endif length = VERSION_SZ + RAN_LEN - + idSz + ENUM_LEN + + (word32)idSz + ENUM_LEN + SUITE_LEN + COMP_LEN + ENUM_LEN; #ifndef NO_FORCE_SCR_SAME_SUITE @@ -28556,7 +29327,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (extSz != 0) length += extSz + HELLO_EXT_SZ_SZ; #endif - sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; + sendSz = (int)length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; if (ssl->arrays == NULL) { return BAD_FUNC_ARG; @@ -28566,7 +29337,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (ssl->options.dtls) { length += ENUM_LEN; /* cookie */ if (ssl->arrays->cookieSz != 0) length += ssl->arrays->cookieSz; - sendSz = length + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ; + sendSz = (int)length + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ; idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA; } #endif @@ -28697,7 +29468,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (IsEncryptionOn(ssl, 1)) { byte* input; - int inputSz = idx; /* build msg adds rec hdr */ + int inputSz = (int)idx; /* build msg adds rec hdr */ int recordHeaderSz = RECORD_HEADER_SZ; if (ssl->options.dtls) @@ -28710,7 +29481,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, inputSz, client_hello)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, client_hello)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -28724,7 +29495,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } else { #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, client_hello)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, client_hello)) != 0) return ret; } if (ssl->options.dtls) @@ -28818,6 +29589,9 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (!ssl->options.downgrade || ssl->options.minDowngrade <= DTLSv1_3_MINOR) return VERSION_ERROR; + + /* Cannot be DTLS1.3 as HELLO_VERIFY_REQUEST */ + ssl->options.tls1_3 = 0; } #endif /* defined(WOLFSSL_DTLS13) && defined(WOLFSSL_TLS13) */ @@ -29419,7 +30193,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if ((len > size) || ((*inOutIdx - begin) + len > size)) return BUFFER_ERROR; - if (PickHashSigAlgo(ssl, input + *inOutIdx, len) != 0 && + if (PickHashSigAlgo(ssl, input + *inOutIdx, len, 0) != 0 && ssl->buffers.certificate && ssl->buffers.certificate->buffer) { #ifdef HAVE_PK_CALLBACKS @@ -29592,7 +30366,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, static int CheckCurveId(int tlsCurveId) { - int ret = ECC_CURVE_ERROR; + int ret = WC_NO_ERR_TRACE(ECC_CURVE_ERROR); switch (tlsCurveId) { #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160 @@ -29660,7 +30434,9 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, case WOLFSSL_ECC_SECP521R1: return ECC_SECP521R1_OID; #endif /* !NO_ECC_SECP */ #endif - default: break; + default: + ret = WC_NO_ERR_TRACE(ECC_CURVE_ERROR); + break; } return ret; @@ -29986,7 +30762,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, args = (DskeArgs*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_dske; @@ -30038,7 +30814,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } /* get PSK server hint from the wire */ - srvHintLen = min(length, MAX_PSK_ID_LEN); + srvHintLen = (int)min(length, MAX_PSK_ID_LEN); XMEMCPY(ssl->arrays->server_hint, input + args->idx, srvHintLen); ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */ @@ -30081,7 +30857,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, if ((curveOid = CheckCurveId(b)) < 0) { ERROR_OUT(ECC_CURVE_ERROR, exit_dske); } - ssl->ecdhCurveOID = curveOid; + ssl->ecdhCurveOID = (word32)curveOid; #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE) ssl->namedGroup = 0; #endif @@ -30112,9 +30888,9 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, input + args->idx, length, EC25519_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, illegal_parameter); @@ -30155,9 +30931,9 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, input + args->idx, length, EC448_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, illegal_parameter); @@ -30192,7 +30968,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } } - curveId = wc_ecc_get_oid(curveOid, NULL, NULL); + curveId = wc_ecc_get_oid((word32)curveOid, NULL, NULL); if (wc_ecc_import_x963_ex(input + args->idx, length, ssl->peerEccKey, curveId) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS @@ -30225,7 +31001,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } /* get PSK server hint from the wire */ - srvHintLen = min(length, MAX_PSK_ID_LEN); + srvHintLen = (int)min(length, MAX_PSK_ID_LEN); XMEMCPY(ssl->arrays->server_hint, input + args->idx, srvHintLen); ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */ @@ -30258,7 +31034,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } /* get PSK server hint from the wire */ - srvHintLen = min(length, MAX_PSK_ID_LEN); + srvHintLen = (int)min(length, MAX_PSK_ID_LEN); XMEMCPY(ssl->arrays->server_hint, input + args->idx, srvHintLen); ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */ @@ -30281,7 +31057,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, if ((curveOid = CheckCurveId(b)) < 0) { ERROR_OUT(ECC_CURVE_ERROR, exit_dske); } - ssl->ecdhCurveOID = curveOid; + ssl->ecdhCurveOID = (word32)curveOid; length = input[args->idx++]; if ((args->idx - args->begin) + length > size) { @@ -30309,9 +31085,9 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, input + args->idx, length, EC25519_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, illegal_parameter); @@ -30352,9 +31128,9 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, input + args->idx, length, EC448_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, illegal_parameter); @@ -30389,7 +31165,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } } - curveId = wc_ecc_get_oid(curveOid, NULL, NULL); + curveId = wc_ecc_get_oid((word32)curveOid, NULL, NULL); if (wc_ecc_import_x963_ex(input + args->idx, length, ssl->peerEccKey, curveId) != 0) { ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske); @@ -30434,14 +31210,14 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, ERROR_OUT(NOT_COMPILED_IN, exit_dske); #else enum wc_HashType hashType; - word16 verifySz; + word32 verifySz; byte sigAlgo; if (ssl->options.usingAnon_cipher) { break; } - verifySz = (word16)(args->idx - args->begin); + verifySz = (args->idx - args->begin); if (verifySz > MAX_DH_SZ) { ERROR_OUT(BUFFER_ERROR, exit_dske); } @@ -30452,6 +31228,15 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, ERROR_OUT(BUFFER_ERROR, exit_dske); } + /* Check if hashSigAlgo in Server Key Exchange is supported + * in our ssl->suites or ssl->ctx->suites. */ + if (!SupportedHashSigAlgo(ssl, &input[args->idx])) { + #ifdef WOLFSSL_EXTRA_ALERTS + SendAlert(ssl, alert_fatal, handshake_failure); + #endif + ERROR_OUT(MATCH_SUITE_ERROR, exit_dske); + } + DecodeSigAlg(&input[args->idx], &ssl->options.peerHashAlgo, &sigAlgo); #ifndef NO_RSA @@ -30650,7 +31435,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, ret = 0; } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* peerRsaKey */ @@ -30678,7 +31463,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, (ssl->buffers.sig.length - SEED_LEN)); } #endif /* HAVE_PK_CALLBACKS */ - if (ret == NOT_COMPILED_IN) { + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->options.peerSigAlgo == sm2_sa_algo) { ret = Sm2wSm3Verify(ssl, @@ -30712,7 +31497,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* peerEccDsaKey */ @@ -30742,7 +31527,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* peerEccDsaKey */ @@ -30772,7 +31557,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* peerEccDsaKey */ @@ -30989,7 +31774,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_server_key_exchange = 0; @@ -31070,7 +31855,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_scke; @@ -31370,11 +32155,13 @@ int SendClientKeyExchange(WOLFSSL* ssl) void* ctx = wolfSSL_GetGenPreMasterCtx(ssl); ret = ssl->ctx->GenPreMasterCb(ssl, ssl->arrays->preMasterSecret, ENCRYPT_LEN, ctx); - if (ret != 0 && ret != PROTOCOLCB_UNAVAILABLE) { + if (ret != 0 && + ret != WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) { goto exit_scke; } } - if (!ssl->ctx->GenPreMasterCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->GenPreMasterCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif { /* build PreMasterSecret with RNG data */ @@ -31469,7 +32256,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { ERROR_OUT(PSK_KEY_ERROR, exit_scke); } @@ -31514,7 +32301,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { ERROR_OUT(PSK_KEY_ERROR, exit_scke); } @@ -31597,7 +32384,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { ERROR_OUT(PSK_KEY_ERROR, exit_scke); } @@ -31872,7 +32659,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) WOLFSSL_CLIENT_END ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { FreeKey(ssl, DYNAMIC_TYPE_ECC, @@ -32104,7 +32891,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) } idx = HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; - args->sendSz = args->encSz + tlsSz + idx; + args->sendSz = (int)(args->encSz + tlsSz + idx); #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { @@ -32237,7 +33024,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_IO /* Handle async operation */ - if (ret == WC_PENDING_E || ret == WANT_WRITE) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) || ret == WANT_WRITE) { if (ssl->options.buildingMsg) return ret; /* If we have completed all states then we will not enter this function @@ -32285,7 +33072,7 @@ typedef struct ScvArgs { word32 sigSz; int sendSz; int inputSz; - word16 length; + word32 length; byte sigAlgo; } ScvArgs; @@ -32321,6 +33108,10 @@ int SendCertificateVerify(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND); WOLFSSL_ENTER("SendCertificateVerify"); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); +#endif + #ifdef WOLFSSL_ASYNC_IO if (ssl->async == NULL) { ssl->async = (struct WOLFSSL_ASYNC*) @@ -32333,10 +33124,10 @@ int SendCertificateVerify(WOLFSSL* ssl) args = (ScvArgs*)ssl->async->args; #ifdef WOLFSSL_ASYNC_CRYPT /* BuildMessage does its own Pop */ - if (ssl->error != WC_PENDING_E || + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) || ssl->options.asyncState != TLS_ASYNC_END) ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_scv; @@ -32367,6 +33158,10 @@ int SendCertificateVerify(WOLFSSL* ssl) case TLS_ASYNC_BEGIN: { if (ssl->options.sendVerify == SEND_BLANK_CERT) { + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, + ssl->buffers.keyMask); + #endif return 0; /* sent blank cert, can't verify */ } @@ -32504,7 +33299,7 @@ int SendCertificateVerify(WOLFSSL* ssl) } /* prepend hdr */ - c16toa(args->length, args->verify + args->extraSz); + c16toa((word16)args->length, args->verify + args->extraSz); } #ifdef WC_RSA_PSS else if (args->sigAlgo == rsa_pss_sa_algo) { @@ -32514,7 +33309,7 @@ int SendCertificateVerify(WOLFSSL* ssl) args->sigSz = ENCRYPT_LEN; /* prepend hdr */ - c16toa(args->length, args->verify + args->extraSz); + c16toa((word16)args->length, args->verify + args->extraSz); } #endif #endif /* !NO_RSA */ @@ -32693,7 +33488,7 @@ int SendCertificateVerify(WOLFSSL* ssl) #endif args->length = (word16)ssl->buffers.sig.length; /* prepend hdr */ - c16toa(args->length, args->verify + args->extraSz); + c16toa((word16)args->length, args->verify + args->extraSz); XMEMCPY(args->verify + args->extraSz + VERIFY_HEADER, ssl->buffers.sig.buffer, ssl->buffers.sig.length); break; @@ -32722,7 +33517,7 @@ int SendCertificateVerify(WOLFSSL* ssl) ); /* free temporary buffer now */ - if (ret != WC_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) { XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); args->verifySig = NULL; } @@ -32771,6 +33566,15 @@ int SendCertificateVerify(WOLFSSL* ssl) } /* switch(ssl->options.asyncState) */ exit_scv: +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + } + else { + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + } +#endif WOLFSSL_LEAVE("SendCertificateVerify", ret); WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND); @@ -32934,7 +33738,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifndef NO_CERTS -#ifdef WOLF_PRIVATE_KEY_ID +#if defined(WOLF_PRIVATE_KEY_ID) || defined(HAVE_PK_CALLBACKS) int GetPrivateKeySigSize(WOLFSSL* ssl) { int sigSz = 0; @@ -32975,7 +33779,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } return sigSz; } -#endif /* HAVE_PK_CALLBACKS */ +#endif /* WOLF_PRIVATE_KEY_ID || HAVE_PK_CALLBACKS */ #endif /* NO_CERTS */ @@ -33067,29 +33871,47 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, int TranslateErrorToAlert(int err) { switch (err) { - case BUFFER_ERROR: + case WC_NO_ERR_TRACE(BUFFER_ERROR): return decode_error; - case EXT_NOT_ALLOWED: - case PEER_KEY_ERROR: - case ECC_PEERKEY_ERROR: - case BAD_KEY_SHARE_DATA: - case PSK_KEY_ERROR: - case INVALID_PARAMETER: - case HRR_COOKIE_ERROR: - case BAD_BINDER: + case WC_NO_ERR_TRACE(EXT_NOT_ALLOWED): + case WC_NO_ERR_TRACE(PEER_KEY_ERROR): + case WC_NO_ERR_TRACE(ECC_PEERKEY_ERROR): + case WC_NO_ERR_TRACE(BAD_KEY_SHARE_DATA): + case WC_NO_ERR_TRACE(PSK_KEY_ERROR): + case WC_NO_ERR_TRACE(INVALID_PARAMETER): + case WC_NO_ERR_TRACE(HRR_COOKIE_ERROR): + case WC_NO_ERR_TRACE(BAD_BINDER): return illegal_parameter; - case INCOMPLETE_DATA: + case WC_NO_ERR_TRACE(INCOMPLETE_DATA): return missing_extension; - case MATCH_SUITE_ERROR: - case MISSING_HANDSHAKE_DATA: + case WC_NO_ERR_TRACE(MATCH_SUITE_ERROR): + case WC_NO_ERR_TRACE(MISSING_HANDSHAKE_DATA): return handshake_failure; - case VERSION_ERROR: + case WC_NO_ERR_TRACE(VERSION_ERROR): return wolfssl_alert_protocol_version; default: return invalid_alert; } } + /* search suites for specific one, idx on success, negative on error */ + int FindSuite(const Suites* suites, byte first, byte second) + { + int i; + + if (suites == NULL || suites->suiteSz == 0) { + WOLFSSL_MSG("Suites pointer error or suiteSz 0"); + return SUITES_ERROR; + } + + for (i = 0; i < suites->suiteSz-1; i += SUITE_LEN) { + if (suites->suites[i] == first && + suites->suites[i+1] == second ) + return i; + } + + return MATCH_SUITE_ERROR; + } #ifndef NO_WOLFSSL_SERVER @@ -33278,7 +34100,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (IsEncryptionOn(ssl, 1)) { byte* input; - int inputSz = idx; /* build msg adds rec hdr */ + int inputSz = (int)idx; /* build msg adds rec hdr */ int recordHeaderSz = RECORD_HEADER_SZ; if (ssl->options.dtls) @@ -33291,7 +34113,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, inputSz, server_hello)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -33305,7 +34127,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } else { #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, server_hello)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, server_hello)) != 0) return ret; } if (ssl->options.dtls) @@ -33377,7 +34199,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) word32 exportSz; #endif - int sendSz; + word32 sendSz; int inputSz; } SskeArgs; @@ -33416,6 +34238,10 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_SEND); WOLFSSL_ENTER("SendServerKeyExchange"); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + #endif + #ifdef WOLFSSL_ASYNC_IO if (ssl->async == NULL) { ssl->async = (struct WOLFSSL_ASYNC*) @@ -33428,7 +34254,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, args = (SskeArgs*)ssl->async->args; #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_sske; @@ -33718,7 +34544,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->eccTempKeyPresent == 0) { ret = X25519MakeKey(ssl, (curve25519_key*)ssl->eccTempKey, NULL); - if (ret == 0 || ret == WC_PENDING_E) { + if (ret == 0 || + ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->eccTempKeyPresent = DYNAMIC_TYPE_CURVE25519; } @@ -33745,7 +34572,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->eccTempKeyPresent == 0) { ret = X448MakeKey(ssl, (curve448_key*)ssl->eccTempKey, NULL); - if (ret == 0 || ret == WC_PENDING_E) { + if (ret == 0 || + ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->eccTempKeyPresent = DYNAMIC_TYPE_CURVE448; } @@ -33770,7 +34598,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->eccTempKeyPresent == 0) { ret = EccMakeKey(ssl, ssl->eccTempKey, NULL); - if (ret == 0 || ret == WC_PENDING_E) { + if (ret == 0 || + ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->eccTempKeyPresent = DYNAMIC_TYPE_ECC; } } @@ -34094,7 +34923,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->buffers.key == NULL) { #ifdef HAVE_PK_CALLBACKS if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) { - args->tmpSigSz = GetPrivateKeySigSize(ssl); + args->tmpSigSz = (word32)GetPrivateKeySigSize(ssl); if (args->tmpSigSz == 0) { ERROR_OUT(NO_PRIVATE_KEY, exit_sske); } @@ -34111,7 +34940,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif case rsa_sa_algo: { - word16 keySz; + word32 keySz; ssl->buffers.keyType = rsa_sa_algo; ret = DecodePrivateKey(ssl, &keySz); @@ -34129,9 +34958,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif case ecc_dsa_sa_algo: { - word16 keySz; + word32 keySz; - ssl->buffers.keyType = ecc_dsa_sa_algo; + ssl->buffers.keyType = ssl->options.sigAlgo; ret = DecodePrivateKey(ssl, &keySz); if (ret != 0) { goto exit_sske; @@ -34144,7 +34973,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef HAVE_ED25519 case ed25519_sa_algo: { - word16 keySz; + word32 keySz; ssl->buffers.keyType = ed25519_sa_algo; ret = DecodePrivateKey(ssl, &keySz); @@ -34160,7 +34989,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef HAVE_ED448 case ed448_sa_algo: { - word16 keySz; + word32 keySz; ssl->buffers.keyType = ed448_sa_algo; ret = DecodePrivateKey(ssl, &keySz); @@ -34363,7 +35192,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, preSigSz = args->length; if (!ssl->options.usingAnon_cipher) { - word16 keySz = 0; + word32 keySz = 0; /* sig length */ args->length += LENGTH_SZ; @@ -34972,6 +35801,16 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, exit_sske: + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + } + else { + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + } + #endif + WOLFSSL_LEAVE("SendServerKeyExchange", ret); WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_SEND); @@ -35009,30 +35848,6 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; } -#if defined(HAVE_SERVER_RENEGOTIATION_INFO) || defined(HAVE_FALLBACK_SCSV) || \ - defined(OPENSSL_ALL) - - /* search suites for specific one, idx on success, negative on error */ - static int FindSuite(Suites* suites, byte first, byte second) - { - int i; - - if (suites == NULL || suites->suiteSz == 0) { - WOLFSSL_MSG("Suites pointer error or suiteSz 0"); - return SUITES_ERROR; - } - - for (i = 0; i < suites->suiteSz-1; i += SUITE_LEN) { - if (suites->suites[i] == first && - suites->suites[i+1] == second ) - return i; - } - - return MATCH_SUITE_ERROR; - } - -#endif - #endif /* !WOLFSSL_NO_TLS12 */ /* Make sure server cert/key are valid for this suite, true on success @@ -35142,7 +35957,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, int ret = TLSX_KeyShare_Choose(ssl, extensions, first, second, &cs->clientKSE, &searched); - if (ret == MEMORY_E) { + if (ret == WC_NO_ERR_TRACE(MEMORY_E)) { WOLFSSL_MSG("TLSX_KeyShare_Choose() failed in " "VerifyServerSuite() with MEMORY_E"); return 0; @@ -35157,7 +35972,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, cs->doHelloRetry = 1; } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif if (!cs->doHelloRetry && ret != 0) @@ -35224,7 +36039,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, for (i = 0; i < suites->suiteSz; i += 2) { for (j = 0; j < peerSuites->suiteSz; j += 2) { ret = CompareSuites(ssl, suites, peerSuites, i, j, cs, extensions); - if (ret != MATCH_SUITE_ERROR) + if (ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) return ret; } } @@ -35234,7 +36049,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, for (j = 0; j < peerSuites->suiteSz; j += 2) { for (i = 0; i < suites->suiteSz; i += 2) { ret = CompareSuites(ssl, suites, peerSuites, i, j, cs, extensions); - if (ret != MATCH_SUITE_ERROR) + if (ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) return ret; } } @@ -35273,7 +36088,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ret != 0) return ret; ret = PickHashSigAlgo(ssl, peerSuites->hashSigAlgo, - peerSuites->hashSigAlgoSz); + peerSuites->hashSigAlgoSz, 1); if (ret != 0) return ret; @@ -35525,6 +36340,47 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, { int ret = 0; WOLFSSL_SESSION* session; + +#ifdef HAVE_SECRET_CALLBACK + if (ssl->sessionSecretCb != NULL +#ifdef HAVE_SESSION_TICKET + && ssl->session->ticketLen > 0 +#endif + ) { + int secretSz = SECRET_LEN; + WOLFSSL_MSG("Calling session secret callback"); + ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom, + RAN_LEN); + if (ret == 0) { + ret = ssl->sessionSecretCb(ssl, ssl->arrays->masterSecret, + &secretSz, ssl->sessionSecretCtx); + if (secretSz != SECRET_LEN) + ret = SESSION_SECRET_CB_E; + } + if (ret == 0) + ret = MatchSuite(ssl, clSuites); + if (ret == 0) { + #ifdef NO_OLD_TLS + ret = DeriveTlsKeys(ssl); + #else + #ifndef NO_TLS + if (ssl->options.tls) + ret = DeriveTlsKeys(ssl); + #endif + if (!ssl->options.tls) + ret = DeriveKeys(ssl); + #endif + /* SERVER: peer auth based on session secret. */ + ssl->options.peerAuthGood = (ret == 0); + ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE; + } + if (ret != 0) + WOLFSSL_ERROR_VERBOSE(ret); + WOLFSSL_LEAVE("HandleTlsResumption", ret); + return ret; + } +#endif /* HAVE_SECRET_CALLBACK */ + #ifdef HAVE_SESSION_TICKET if (ssl->options.useTicket == 1) { session = ssl->session; @@ -35595,7 +36451,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ret = SetCipherSpecs(ssl); if (ret == 0) { ret = PickHashSigAlgo(ssl, clSuites->hashSigAlgo, - clSuites->hashSigAlgoSz); + clSuites->hashSigAlgoSz, 0); } } else if (ret == 0) { @@ -35671,7 +36527,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* propagate socket errors to avoid re-calling send alert */ err = SendAlert(ssl, alert_fatal, alertType); - if (err == SOCKET_ERROR_E) + if (err == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) ret = SOCKET_ERROR_E; } *inOutIdx += helloSz; @@ -35979,8 +36835,12 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */ ret = TLSX_AddEmptyRenegotiationInfo(&ssl->extensions, ssl->heap); - if (ret != WOLFSSL_SUCCESS) + if (ret != WOLFSSL_SUCCESS) { + ret = SECURE_RENEGOTIATION_E; goto out; + } else { + ret = 0; + } extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO); if (extension) { @@ -36184,6 +37044,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->options.haveSessionId = 1; /* ProcessOld uses same resume code */ + WOLFSSL_MSG_EX("ssl->options.resuming %d", ssl->options.resuming); if (ssl->options.resuming) { ret = HandleTlsResumption(ssl, clSuites); if (ret != 0) @@ -36315,7 +37176,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, args = (DcvArgs*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_dcv; @@ -36480,9 +37341,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ); if (ret >= 0) { if (ssl->options.peerSigAlgo == rsa_sa_algo) - args->sendSz = ret; + args->sendSz = (word32)ret; else { - args->sigSz = ret; + args->sigSz = (word32)ret; args->sendSz = ssl->buffers.digest.length; } ret = 0; @@ -36568,7 +37429,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef WOLFSSL_ASYNC_CRYPT /* handle async pending */ - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) goto exit_dcv; #endif @@ -36706,7 +37567,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_certificate_verify = 0; @@ -36714,9 +37575,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_ERROR) + if (ret == WC_NO_ERR_TRACE(BUFFER_ERROR)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == SIG_VERIFY_E) + else if (ret == WC_NO_ERR_TRACE(SIG_VERIFY_E)) SendAlert(ssl, alert_fatal, decrypt_error); else if (ret != 0) SendAlert(ssl, alert_fatal, bad_certificate); @@ -36798,7 +37659,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, inputSz, server_hello_done)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello_done)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -36812,7 +37673,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } else { #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, server_hello_done)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, server_hello_done)) != 0) return ret; } if (ssl->options.dtls) @@ -36929,7 +37790,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, it = (InternalTicket*)et->enc_ticket; #ifdef WOLFSSL_ASYNC_CRYPT - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { XMEMSET(et, 0, sizeof(*et)); @@ -37036,7 +37897,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } if (ret != WOLFSSL_TICKET_RET_OK) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -37157,7 +38018,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } if (ret != WOLFSSL_TICKET_RET_OK) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -37443,7 +38304,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif if (sess == NULL) { ret = TlsSessionCacheGetAndRdLock(id, &sess, &freeCtx->row, - ssl->options.side); + (byte)ssl->options.side); if (ret != 0) sess = NULL; } @@ -37565,6 +38426,22 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_START(WC_FUNC_TICKET_DO); WOLFSSL_ENTER("DoClientTicket"); +#ifdef HAVE_SECRET_CALLBACK + if (ssl->ticketParseCb != NULL) { + decryptRet = WOLFSSL_TICKET_RET_OK; + if (!ssl->ticketParseCb(ssl, input, len, ssl->ticketParseCtx)) { + /* Failure kills the connection */ + decryptRet = WOLFSSL_TICKET_RET_FATAL; + } + else { + if (wolfSSL_set_SessionTicket(ssl, input, len) != + WOLFSSL_SUCCESS) + decryptRet = WOLFSSL_TICKET_RET_REJECT; + } + goto cleanup; + } + else +#endif #ifdef WOLFSSL_TLS13 if (len == ID_LEN && IsAtLeastTLSv1_3(ssl->version)) { /* This is a stateful ticket. We can be sure about this because @@ -37579,7 +38456,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } else #endif + if (len >= sizeof(*it)) decryptRet = DoDecryptTicket(ssl, input, len, &it); + else + WOLFSSL_MSG("Ticket is smaller than InternalTicket. Rejecting."); + if (decryptRet != WOLFSSL_TICKET_RET_OK && decryptRet != WOLFSSL_TICKET_RET_CREATE) { @@ -37655,7 +38536,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } length += ssl->session->ticketLen; - sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; + sendSz = (int)length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; if (!ssl->options.dtls) { if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) @@ -37697,7 +38578,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) { byte* input; - int inputSz = idx; /* build msg adds rec hdr */ + int inputSz = (int)idx; /* build msg adds rec hdr */ int recordHeaderSz = RECORD_HEADER_SZ; if (ssl->options.dtls) @@ -37718,7 +38599,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, else { #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { - if ((ret = DtlsMsgPoolSave(ssl, output, sendSz, session_ticket)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, session_ticket)) != 0) return ret; DtlsSEQIncrement(ssl, CUR_ORDER); @@ -38135,6 +39016,10 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_ENTER("DefTicketEncCb"); + if ((!enc) && (inLen != sizeof(InternalTicket))) { + return BUFFER_E; + } + /* Check we have setup the RNG, name and primary key. */ if (keyCtx->expirary[0] == 0) { #ifndef SINGLE_THREADED @@ -38372,7 +39257,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi; ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo; } - AddHeaders(output, length, hello_verify_request, ssl); + AddHeaders(output, (word32)length, hello_verify_request, ssl); output[idx++] = DTLS_MAJOR; output[idx++] = DTLS_MINOR; @@ -38456,6 +39341,10 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_DO); WOLFSSL_ENTER("DoClientKeyExchange"); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + #endif + #ifdef WOLFSSL_ASYNC_CRYPT if (ssl->async == NULL) { ssl->async = (struct WOLFSSL_ASYNC*) @@ -38467,7 +39356,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], args = (DckeArgs*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_dcke; @@ -38611,7 +39500,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], #ifndef NO_RSA case rsa_kea: { - word16 keySz; + word32 keySz; ssl->buffers.keyType = rsa_sa_algo; ret = DecodePrivateKey(ssl, &keySz); @@ -38689,7 +39578,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { #if defined(WOLFSSL_EXTRA_ALERTS) || \ defined(WOLFSSL_PSK_IDENTITY_ALERT) SendAlert(ssl, alert_fatal, @@ -38731,7 +39620,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], if (ssl->specs.static_ecdh && ssl->ecdhCurveOID != ECC_X25519_OID && ssl->ecdhCurveOID != ECC_X448_OID) { - word16 keySz; + word32 keySz; ssl->buffers.keyType = ecc_dsa_sa_algo; ret = DecodePrivateKey(ssl, &keySz); @@ -38781,9 +39670,9 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], input + args->idx, args->length, EC25519_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, @@ -38838,9 +39727,9 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], input + args->idx, args->length, EC448_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, @@ -38906,7 +39795,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke); } - ssl->arrays->preMasterSz = private_key->dp->size; + ssl->arrays->preMasterSz = (word32)private_key->dp->size; ssl->peerEccKeyPresent = 1; @@ -39083,9 +39972,9 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], input + args->idx, args->length, EC25519_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, @@ -39142,9 +40031,9 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], input + args->idx, args->length, EC448_LITTLE_ENDIAN)) != 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) SendAlert(ssl, alert_fatal, decode_error); - else if (ret == ECC_OUT_OF_RANGE_E) + else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E)) SendAlert(ssl, alert_fatal, bad_record_mac); else { SendAlert(ssl, alert_fatal, @@ -39245,10 +40134,10 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], * RSA_BUFFER_E, RSA_PAD_E and RSA_PRIVATE_ERROR */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) goto exit_dcke; #endif - if (ret == BAD_FUNC_ARG) + if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) goto exit_dcke; lenErrMask = 0 - (SECRET_LEN != args->sigSz); @@ -39311,7 +40200,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_SERVER_END ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { FreeKey(ssl, DYNAMIC_TYPE_ECC, @@ -39367,7 +40256,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_SERVER_END ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, @@ -39388,7 +40277,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_SERVER_END ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { FreeKey(ssl, DYNAMIC_TYPE_CURVE448, @@ -39532,7 +40421,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { #if defined(WOLFSSL_EXTRA_ALERTS) || \ defined(WOLFSSL_PSK_IDENTITY_ALERT) SendAlert(ssl, alert_fatal, @@ -39578,7 +40467,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { ERROR_OUT(PSK_KEY_ERROR, exit_dcke); } /* SERVER: Pre-shared Key for peer authentication. */ @@ -39650,11 +40539,21 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], exit_dcke: + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + } + else { + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + } + #endif + WOLFSSL_LEAVE("DoClientKeyExchange", ret); WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_DO); #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_client_key_exchange = 0; @@ -39746,7 +40645,8 @@ int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state) event = &asyncDev->event; ret = wolfAsync_EventPop(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL); - if (ret != WC_NO_PENDING_E && ret != WC_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E) && + ret != WC_NO_ERR_TRACE(WC_PENDING_E)) { /* advance key share state if doesn't need called again */ if (state && (asyncDev->event.flags & WC_ASYNC_FLAG_CALL_AGAIN) == 0) { (*state)++; @@ -39759,7 +40659,7 @@ int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state) #if (defined(WOLF_CRYPTO_CB) || defined(HAVE_PK_CALLBACKS)) && \ !defined(WOLFSSL_ASYNC_CRYPT_SW) && !defined(HAVE_INTEL_QA) && \ !defined(HAVE_CAVIUM) - else if (ret == WC_PENDING_E) { + else if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Allow the underlying crypto API to be called again to trigger the * crypto or PK callback. The actual callback must be called, since * the completion is not detected in the poll like Intel QAT or diff --git a/src/src/keys.c b/src/src/keys.c index fa04c4d..f9f9e85 100644 --- a/src/src/keys.c +++ b/src/src/keys.c @@ -105,7 +105,7 @@ int SetCipherSpecs(WOLFSSL* ssl) * @param cipherSuite [in] * @param specs [out] CipherSpecs * @param opts [in/out] Options can be NULL - * @return + * @return int (less than 0 on fail, 0 on success) */ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, CipherSpecs* specs, Options* opts) @@ -672,7 +672,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; break; @@ -690,7 +690,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; break; @@ -708,7 +708,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; break; @@ -1069,7 +1069,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; break; @@ -1087,7 +1087,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; break; @@ -1105,7 +1105,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; if (opts != NULL) @@ -1125,7 +1125,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; if (opts != NULL) @@ -1145,7 +1145,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; if (opts != NULL) @@ -1165,7 +1165,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; if (opts != NULL) @@ -1185,7 +1185,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; if (opts != NULL) @@ -1205,7 +1205,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_IMP_IV_SZ; + specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; if (opts != NULL) @@ -1330,7 +1330,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_NONCE_SZ; + specs->iv_size = AESCCM_NONCE_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; break; @@ -1348,7 +1348,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->block_size = AES_BLOCK_SIZE; - specs->iv_size = AESGCM_NONCE_SZ; + specs->iv_size = AESCCM_NONCE_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; break; @@ -1440,7 +1440,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = SM4_KEY_SIZE; specs->block_size = SM4_BLOCK_SIZE; - specs->iv_size = GCM_IMP_IV_SZ; + specs->iv_size = CCM_IMP_IV_SZ; specs->aead_mac_size = SM4_CCM_AUTH_SZ; break; @@ -3561,7 +3561,8 @@ int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side) void* ctx = wolfSSL_GetEncryptKeysCtx(ssl); ret = ssl->ctx->EncryptKeysCb(ssl, ctx); } - if (!ssl->ctx->EncryptKeysCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->EncryptKeysCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif { ret = SetKeys(wc_encrypt, wc_decrypt, keys, &ssl->specs, ssl->options.side, @@ -3668,7 +3669,8 @@ int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side) /* TLS can call too */ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) { - int sz, i = 0; + size_t sz; + int i = 0; Keys* keys = &ssl->keys; #ifdef WOLFSSL_DTLS /* In case of DTLS, ssl->keys is updated here */ @@ -3712,7 +3714,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) XMEMCPY(keys->client_write_MAC_secret,&keyData[i], sz); XMEMCPY(keys->server_write_MAC_secret,&keyData[i], sz); #endif - i += sz; + i += (int)sz; } sz = ssl->specs.key_size; #ifdef WOLFSSL_DTLS @@ -3725,7 +3727,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) #endif XMEMCPY(keys->client_write_key, &keyData[i], sz); XMEMCPY(keys->server_write_key, &keyData[i], sz); - i += sz; + i += (int)sz; sz = ssl->specs.iv_size; #ifdef WOLFSSL_DTLS @@ -3767,7 +3769,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) #endif XMEMCPY(keys->client_write_MAC_secret,&keyData[i], sz); #endif - i += sz; + i += (int)sz; } if (side & PROVISION_SERVER) { #ifndef WOLFSSL_AEAD_ONLY @@ -3778,7 +3780,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) #endif XMEMCPY(keys->server_write_MAC_secret,&keyData[i], sz); #endif - i += sz; + i += (int)sz; } } sz = ssl->specs.key_size; @@ -3789,7 +3791,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) keys->client_write_key, sz); #endif XMEMCPY(keys->client_write_key, &keyData[i], sz); - i += sz; + i += (int)sz; } if (side & PROVISION_SERVER) { #ifdef WOLFSSL_DTLS @@ -3798,7 +3800,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) keys->server_write_key, sz); #endif XMEMCPY(keys->server_write_key, &keyData[i], sz); - i += sz; + i += (int)sz; } sz = ssl->specs.iv_size; @@ -3809,7 +3811,7 @@ int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side) keys->client_write_IV, sz); #endif XMEMCPY(keys->client_write_IV, &keyData[i], sz); - i += sz; + i += (int)sz; } if (side & PROVISION_SERVER) { #ifdef WOLFSSL_DTLS diff --git a/src/src/ocsp.c b/src/src/ocsp.c index c56ec22..4760c50 100644 --- a/src/src/ocsp.c +++ b/src/src/ocsp.c @@ -144,7 +144,7 @@ static int xstat2err(int st) int CheckCertOCSP_ex(WOLFSSL_OCSP* ocsp, DecodedCert* cert, WOLFSSL* ssl) { - int ret = OCSP_LOOKUP_FAIL; + int ret = WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL); #ifdef WOLFSSL_SMALL_STACK OcspRequest* ocspRequest; @@ -227,7 +227,7 @@ static int GetOcspStatus(WOLFSSL_OCSP* ocsp, OcspRequest* request, OcspEntry* entry, CertStatus** status, buffer* responseBuffer, void* heap) { - int ret = OCSP_INVALID_STATUS; + int ret = WC_NO_ERR_TRACE(OCSP_INVALID_STATUS); WOLFSSL_ENTER("GetOcspStatus"); @@ -241,7 +241,7 @@ static int GetOcspStatus(WOLFSSL_OCSP* ocsp, OcspRequest* request, for (*status = entry->status; *status; *status = (*status)->next) if ((*status)->serialSz == request->serialSz - && !XMEMCMP((*status)->serial, request->serial, (*status)->serialSz)) + && !XMEMCMP((*status)->serial, request->serial, (size_t)(*status)->serialSz)) break; if (responseBuffer && *status && !(*status)->rawOcspResponse) { @@ -326,9 +326,14 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, return MEMORY_E; } #endif - InitOcspResponse(ocspResponse, newSingle, newStatus, response, responseSz, - ocsp->cm->heap); - + InitOcspResponse(ocspResponse, newSingle, newStatus, response, + (word32)responseSz, ocsp->cm->heap); +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ocspRequest != NULL && ocspRequest->ssl != NULL && + TLSX_CSR2_IsMulti(((WOLFSSL*)ocspRequest->ssl)->extensions)) { + ocspResponse->pendingCAs = TLSX_CSR2_GetPendingSigners(((WOLFSSL*)ocspRequest->ssl)->extensions); + } +#endif ret = OcspResponseDecode(ocspResponse, ocsp->cm, ocsp->cm->heap, 0); if (ret != 0) { ocsp->error = ret; @@ -350,12 +355,12 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, } if (responseBuffer) { - responseBuffer->buffer = (byte*)XMALLOC(responseSz, heap, + responseBuffer->buffer = (byte*)XMALLOC((size_t)responseSz, heap, DYNAMIC_TYPE_TMP_BUFFER); if (responseBuffer->buffer) { - responseBuffer->length = responseSz; - XMEMCPY(responseBuffer->buffer, response, responseSz); + responseBuffer->length = (unsigned int)responseSz; + XMEMCPY(responseBuffer->buffer, response, (size_t)responseSz); } } @@ -410,10 +415,10 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, if (ret == 0 && validated == 1) { WOLFSSL_MSG("New OcspResponse validated"); } - else if (ret == OCSP_CERT_REVOKED) { + else if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED)) { WOLFSSL_MSG("OCSP revoked"); } - else if (ret == OCSP_CERT_UNKNOWN) { + else if (ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN)) { WOLFSSL_MSG("OCSP unknown"); } else { @@ -466,7 +471,7 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, ret = GetOcspStatus(ocsp, ocspRequest, entry, &status, responseBuffer, heap); - if (ret != OCSP_INVALID_STATUS) + if (ret != WC_NO_ERR_TRACE(OCSP_INVALID_STATUS)) return ret; if (responseBuffer) { @@ -522,13 +527,13 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, return 0; } - request = (byte*)XMALLOC(requestSz, ocsp->cm->heap, DYNAMIC_TYPE_OCSP); + request = (byte*)XMALLOC((size_t)requestSz, ocsp->cm->heap, DYNAMIC_TYPE_OCSP); if (request == NULL) { WOLFSSL_LEAVE("CheckCertOCSP", MEMORY_ERROR); return MEMORY_ERROR; } - requestSz = EncodeOcspRequest(ocspRequest, request, requestSz); + requestSz = EncodeOcspRequest(ocspRequest, request, (word32)requestSz); if (requestSz > 0 && ocsp->cm->ocspIOCb) { responseSz = ocsp->cm->ocspIOCb(ioCtx, url, urlSz, request, requestSz, &response); @@ -555,7 +560,7 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, #ifndef WOLFSSL_NO_OCSP_ISSUER_CHAIN_CHECK static int CheckOcspResponderChain(OcspEntry* single, DecodedCert *cert, - void* vp) { + void* vp, Signer* pendingCAs) { /* Attempt to build a chain up to cert's issuer */ WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp; Signer* ca = NULL; @@ -574,8 +579,16 @@ static int CheckOcspResponderChain(OcspEntry* single, DecodedCert *cert, /* End loop if no more issuers found or if we have found a self * signed cert (ca == prev) */ - for (ca = GetCAByName(cm, single->issuerHash); ca != NULL && ca != prev; - prev = ca, ca = GetCAByName(cm, ca->issuerNameHash)) { + ca = GetCAByName(cm, single->issuerHash); +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ca == NULL && pendingCAs != NULL) { + ca = findSignerByName(pendingCAs, single->issuerHash); + } +#else + (void)pendingCAs; +#endif + for (; ca != NULL && ca != prev; + prev = ca) { if (XMEMCMP(cert->issuerHash, ca->issuerNameHash, OCSP_DIGEST_SIZE) == 0) { WOLFSSL_MSG("\tOCSP Response signed by authorized " @@ -584,6 +597,12 @@ static int CheckOcspResponderChain(OcspEntry* single, DecodedCert *cert, passed = 1; break; } + ca = GetCAByName(cm, ca->issuerNameHash); +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ca == NULL && pendingCAs != NULL) { + ca = findSignerByName(pendingCAs, single->issuerHash); + } +#endif } return passed; } @@ -632,7 +651,7 @@ int CheckOcspResponder(OcspResponse *bs, DecodedCert *cert, void* vp) } #ifndef WOLFSSL_NO_OCSP_ISSUER_CHAIN_CHECK else if (vp != NULL) { - passed = CheckOcspResponderChain(single, cert, vp); + passed = CheckOcspResponderChain(single, cert, vp, bs->pendingCAs); } #endif } @@ -663,7 +682,7 @@ int wolfSSL_OCSP_resp_find_status(WOLFSSL_OCSP_BASICRESP *bs, single = bs->single; while (single != NULL) { - if ((XMEMCMP(single->status->serial, id->status->serial, single->status->serialSz) == 0) + if ((XMEMCMP(single->status->serial, id->status->serial, (size_t)single->status->serialSz) == 0) && (XMEMCMP(single->issuerHash, id->issuerHash, OCSP_DIGEST_SIZE) == 0) && (XMEMCMP(single->issuerKeyHash, id->issuerKeyHash, OCSP_DIGEST_SIZE) == 0)) { break; @@ -783,14 +802,14 @@ WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_cert_to_id( InitDecodedCert(cert, subject->derCert->buffer, subject->derCert->length, NULL); - if (ParseCertRelative(cert, CERT_TYPE, VERIFY_OCSP, cm) != 0) { + if (ParseCertRelative(cert, CERT_TYPE, VERIFY_OCSP, cm, NULL) != 0) { FreeDecodedCert(cert); goto out; } else { XMEMCPY(certId->issuerHash, cert->issuerHash, OCSP_DIGEST_SIZE); XMEMCPY(certId->issuerKeyHash, cert->issuerKeyHash, OCSP_DIGEST_SIZE); - XMEMCPY(certId->status->serial, cert->serial, cert->serialSz); + XMEMCPY(certId->status->serial, cert->serial, (size_t)cert->serialSz); certId->status->serialSz = cert->serialSz; FreeDecodedCert(cert); } @@ -864,7 +883,7 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, int derSz = 0; const byte* der = wolfSSL_X509_get_der(x, &derSz); if (der != NULL && derSz == (int)bs->certSz && - XMEMCMP(bs->cert, der, derSz) == 0) { + XMEMCMP(bs->cert, der, (size_t)derSz) == 0) { ret = WOLFSSL_SUCCESS; goto out; } @@ -873,7 +892,7 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, InitDecodedCert(cert, bs->cert, bs->certSz, NULL); certInit = 1; - if (ParseCertRelative(cert, CERT_TYPE, VERIFY, st->cm) < 0) + if (ParseCertRelative(cert, CERT_TYPE, VERIFY, st->cm, NULL) < 0) goto out; if (!(flags & OCSP_NOCHECKS)) { @@ -952,7 +971,7 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE_bio(WOLFSSL_BIO* bio, if (fcur > MAX_WOLFSSL_FILE_SIZE || fcur <= 0) return NULL; - data = (byte*)XMALLOC(fcur, 0, DYNAMIC_TYPE_TMP_BUFFER); + data = (byte*)XMALLOC((size_t)fcur, 0, DYNAMIC_TYPE_TMP_BUFFER); if (data == NULL) return NULL; dataAlloced = 1; @@ -997,7 +1016,7 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE(OcspResponse** response, XMEMSET(resp, 0, sizeof(OcspResponse)); } - resp->source = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + resp->source = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (resp->source == NULL) { XFREE(resp, NULL, DYNAMIC_TYPE_OCSP_REQUEST); return NULL; @@ -1021,19 +1040,19 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE(OcspResponse** response, } XMEMSET(resp->single->status, 0, sizeof(CertStatus)); - XMEMCPY(resp->source, *data, len); - resp->maxIdx = len; + XMEMCPY(resp->source, *data, (size_t)len); + resp->maxIdx = (word32)len; ret = OcspResponseDecode(resp, NULL, NULL, 1); - if (ret != 0 && ret != ASN_OCSP_CONFIRM_E) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(ASN_OCSP_CONFIRM_E)) { /* for just converting from a DER to an internal structure the CA may * not yet be known to this function for signature verification */ wolfSSL_OCSP_RESPONSE_free(resp); return NULL; } - if (GetSequence(*data, &idx, &length, len) >= 0) - (*data) += idx + length; + if (GetSequence(*data, &idx, &length, (word32)len) >= 0) + (*data) += (unsigned char) ((int)idx + length); return resp; } @@ -1042,10 +1061,10 @@ int wolfSSL_i2d_OCSP_RESPONSE(OcspResponse* response, unsigned char** data) { if (data == NULL) - return response->maxIdx; + return (int)response->maxIdx; XMEMCPY(*data, response->source, response->maxIdx); - return response->maxIdx; + return (int)response->maxIdx; } int wolfSSL_OCSP_response_status(OcspResponse *response) @@ -1128,7 +1147,7 @@ int wolfSSL_i2d_OCSP_REQUEST(OcspRequest* request, unsigned char** data) if (size <= 0 || data == NULL) return size; - return EncodeOcspRequest(request, *data, size); + return EncodeOcspRequest(request, *data, (word32) size); } WOLFSSL_OCSP_ONEREQ* wolfSSL_OCSP_request_add0_id(OcspRequest *req, @@ -1147,12 +1166,12 @@ WOLFSSL_OCSP_ONEREQ* wolfSSL_OCSP_request_add0_id(OcspRequest *req, if (cid->status->serialSz > req->serialSz) { if (req->serial != NULL) XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP); - req->serial = (byte*)XMALLOC(cid->status->serialSz, + req->serial = (byte*)XMALLOC((size_t)cid->status->serialSz, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); if (req->serial == NULL) return NULL; } - XMEMCPY(req->serial, cid->status->serial, cid->status->serialSz); + XMEMCPY(req->serial, cid->status->serial, (size_t)cid->status->serialSz); req->serialSz = cid->status->serialSz; return req; @@ -1188,7 +1207,7 @@ int wolfSSL_i2d_OCSP_REQUEST_bio(WOLFSSL_BIO* out, size = wolfSSL_i2d_OCSP_REQUEST(req, NULL); if (size > 0) { - data = (unsigned char*) XMALLOC(size, out->heap, + data = (unsigned char*) XMALLOC((size_t)size, out->heap, DYNAMIC_TYPE_TMP_BUFFER); } @@ -1217,15 +1236,15 @@ int wolfSSL_i2d_OCSP_CERTID(WOLFSSL_OCSP_CERTID* id, unsigned char** data) return WOLFSSL_FAILURE; if (*data != NULL) { - XMEMCPY(*data, id->rawCertId, id->rawCertIdSize); + XMEMCPY(*data, id->rawCertId, (size_t)id->rawCertIdSize); *data = *data + id->rawCertIdSize; } else { - *data = (unsigned char*)XMALLOC(id->rawCertIdSize, NULL, DYNAMIC_TYPE_OPENSSL); + *data = (unsigned char*)XMALLOC((size_t)id->rawCertIdSize, NULL, DYNAMIC_TYPE_OPENSSL); if (*data == NULL) { return WOLFSSL_FAILURE; } - XMEMCPY(*data, id->rawCertId, id->rawCertIdSize); + XMEMCPY(*data, id->rawCertId, (size_t)id->rawCertIdSize); } return id->rawCertIdSize; @@ -1254,9 +1273,9 @@ WOLFSSL_OCSP_CERTID* wolfSSL_d2i_OCSP_CERTID(WOLFSSL_OCSP_CERTID** cidOut, } if (cid != NULL) { - cid->rawCertId = (byte*)XMALLOC(length + 1, NULL, DYNAMIC_TYPE_OPENSSL); + cid->rawCertId = (byte*)XMALLOC((size_t)length + 1, NULL, DYNAMIC_TYPE_OPENSSL); if (cid->rawCertId != NULL) { - XMEMCPY(cid->rawCertId, *derIn, length); + XMEMCPY(cid->rawCertId, *derIn, (size_t)length); cid->rawCertIdSize = length; /* Per spec. advance past the data that is being returned @@ -1303,7 +1322,7 @@ int wolfSSL_OCSP_id_cmp(WOLFSSL_OCSP_CERTID *a, WOLFSSL_OCSP_CERTID *b) if (a->status != NULL && b->status != NULL) { if (a->status->serialSz == b->status->serialSz) ret = XMEMCMP(a->status->serial, b->status->serial, - a->status->serialSz); + (size_t)a->status->serialSz); else ret = -1; } @@ -1432,13 +1451,13 @@ int wolfSSL_OCSP_id_get0_info(WOLFSSL_ASN1_STRING **name, if (cid->status->serialSz > (WOLFSSL_ASN1_INTEGER_MAX - 2)) { /* allocate data buffer, +2 for type and length */ - ser->data = (unsigned char*)XMALLOC(cid->status->serialSz + 2, NULL, + ser->data = (unsigned char*)XMALLOC((size_t)cid->status->serialSz + 2, NULL, DYNAMIC_TYPE_OPENSSL); if (ser->data == NULL) { wolfSSL_ASN1_INTEGER_free(ser); return 0; } - ser->dataMax = cid->status->serialSz + 2; + ser->dataMax = (unsigned int)cid->status->serialSz + 2; ser->isDynamic = 1; } else { /* Use array instead of dynamic memory */ @@ -1448,12 +1467,12 @@ int wolfSSL_OCSP_id_get0_info(WOLFSSL_ASN1_STRING **name, #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) /* Serial number starts at 0 index of ser->data */ - XMEMCPY(&ser->data[i], cid->status->serial, cid->status->serialSz); + XMEMCPY(&ser->data[i], cid->status->serial, (size_t)cid->status->serialSz); ser->length = cid->status->serialSz; #else ser->data[i++] = ASN_INTEGER; i += SetLength(cid->status->serialSz, ser->data + i); - XMEMCPY(&ser->data[i], cid->status->serial, cid->status->serialSz); + XMEMCPY(&ser->data[i], cid->status->serial, (size_t)cid->status->serialSz); ser->length = i + cid->status->serialSz; #endif @@ -1493,7 +1512,7 @@ int wolfSSL_OCSP_request_add1_nonce(OcspRequest* req, unsigned char* val, sz = MAX_OCSP_NONCE_SZ; if (val != NULL) { - XMEMCPY(req->nonce, val, sz); + XMEMCPY(req->nonce, val, (size_t)sz); } else { if ( @@ -1506,7 +1525,7 @@ int wolfSSL_OCSP_request_add1_nonce(OcspRequest* req, unsigned char* val, WOLFSSL_MSG("RNG init failed"); return WOLFSSL_FAILURE; } - if (wc_RNG_GenerateBlock(&rng, req->nonce, sz) != 0) { + if (wc_RNG_GenerateBlock(&rng, req->nonce, (word32)sz) != 0) { WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); wc_FreeRng(&rng); return WOLFSSL_FAILURE; @@ -1559,7 +1578,7 @@ int wolfSSL_OCSP_check_nonce(OcspRequest* req, WOLFSSL_OCSP_BASICRESP* bs) /* nonces are present and equal, return 1. Extra NULL check for fixing scan-build warning. */ if (reqNonceSz == rspNonceSz && reqNonce && rspNonce) { - if (XMEMCMP(reqNonce, rspNonce, reqNonceSz) == 0) + if (XMEMCMP(reqNonce, rspNonce, (size_t)reqNonceSz) == 0) return 1; } diff --git a/src/src/pk.c b/src/src/pk.c index d7d32dd..db281f6 100644 --- a/src/src/pk.c +++ b/src/src/pk.c @@ -25,13 +25,19 @@ #include - #include +#include #ifndef WC_NO_RNG #include #endif #ifdef HAVE_ECC #include + #ifdef HAVE_SELFTEST + /* point compression types. */ + #define ECC_POINT_COMP_EVEN 0x02 + #define ECC_POINT_COMP_ODD 0x03 + #define ECC_POINT_UNCOMP 0x04 + #endif #endif #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV /* FIPS build has replaced ecc.h. */ @@ -49,14 +55,6 @@ #include #endif -#if defined(OPENSSL_EXTRA) && !defined(NO_BIO) && defined(WOLFSSL_KEY_GEN) && \ - (defined(HAVE_ECC) || (!defined(NO_DSA) && !defined(HAVE_SELFTEST))) -/* Forward declaration for wolfSSL_PEM_write_bio_DSA_PUBKEY. - * Implementation in ssl.c. - */ -static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key); -#endif - /******************************************************************************* * COMMON FUNCTIONS ******************************************************************************/ @@ -167,8 +165,7 @@ static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb, /* Write left over data back to BIO if not a file BIO */ if ((ret > 0) && ((memSz - ret) > 0) && (bio->type != WOLFSSL_BIO_FILE)) { - int res; - res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret); + int res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret); if (res != memSz - ret) { WOLFSSL_ERROR_MSG("Unable to write back excess data"); if (res < 0) { @@ -180,7 +177,7 @@ static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb, } } if (alloced) { - XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER); } } @@ -229,33 +226,36 @@ static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass, * @param [in] heap Heap hint for dynamic memory allocation. * @param [out] out Allocated buffer containing PEM. * @param [out] outSz Size of PEM encoding. - * @return WOLFSSL_FAILURE on error. - * @return WOLFSSL_SUCCESS on success. + * @return 1 on success. + * @return 0 on error. */ static int der_to_pem_alloc(const unsigned char* der, int derSz, int type, void* heap, byte** out, int* outSz) { - int ret = WOLFSSL_SUCCESS; + int ret = 1; int pemSz; byte* pem = NULL; (void)heap; + /* Convert DER to PEM - to get size. */ pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type); if (pemSz < 0) { - ret = WOLFSSL_FAILURE; + ret = 0; } - if (ret == WOLFSSL_SUCCESS) { + if (ret == 1) { + /* Allocate memory for PEM to be encoded into. */ pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER); if (pem == NULL) { - ret = WOLFSSL_FAILURE; + ret = 0; } } - if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, (word32)derSz, pem, - (word32)pemSz, type) < 0)) { - ret = WOLFSSL_FAILURE; + /* Convert DER to PEM. */ + if ((ret == 1) && (wc_DerToPem(der, (word32)derSz, pem, (word32)pemSz, + type) < 0)) { + ret = 0; XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER); pem = NULL; } @@ -272,8 +272,8 @@ static int der_to_pem_alloc(const unsigned char* der, int derSz, int type, * @param [in] derSz Size of DER data in bytes. * @param [in, out] bio BIO object to write with. * @param [in] type Type of key being encoded. - * @return WOLFSSL_FAILURE on error. - * @return WOLFSSL_SUCCESS on success. + * @return 1 on success. + * @return 0 on error. */ static int der_write_to_bio_as_pem(const unsigned char* der, int derSz, WOLFSSL_BIO* bio, int type) @@ -283,11 +283,11 @@ static int der_write_to_bio_as_pem(const unsigned char* der, int derSz, byte* pem = NULL; ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz); - if (ret == WOLFSSL_SUCCESS) { + if (ret == 1) { int len = wolfSSL_BIO_write(bio, pem, pemSz); if (len != pemSz) { WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO"); - ret = WOLFSSL_FAILURE; + ret = 0; } } @@ -308,8 +308,8 @@ static int der_write_to_bio_as_pem(const unsigned char* der, int derSz, * @param [in] fp File pointer to write with. * @param [in] type Type of key being encoded. * @param [in] heap Heap hint for dynamic memory allocation. - * @return WOLFSSL_FAILURE on error. - * @return WOLFSSL_SUCCESS on success. + * @return 1 on success. + * @return 0 on error. */ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, XFILE fp, int type, void* heap) @@ -319,11 +319,11 @@ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, byte* pem = NULL; ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz); - if (ret == WOLFSSL_SUCCESS) { + if (ret == 1) { int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp); if (len != pemSz) { WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO"); - ret = WOLFSSL_FAILURE; + ret = 0; } } @@ -333,9 +333,153 @@ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, #endif #endif +#if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER) +/* Encrypt private key into PEM format. + * + * DER is encrypted in place. + * + * @param [in] der DER encoding of private key. + * @param [in] derSz Size of DER in bytes. + * @param [in] cipher EVP cipher. + * @param [in] passwd Password to use with encryption. + * @param [in] passedSz Size of password in bytes. + * @param [out] cipherInfo PEM cipher information lines. + * @param [in] maxDerSz Maximum size of DER buffer. + * @return 1 on success. + * @return 0 on error. + */ +int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, + unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz) +{ + int ret = 0; + int paddingSz = 0; + word32 idx; + word32 cipherInfoSz; +#ifdef WOLFSSL_SMALL_STACK + EncryptedInfo* info = NULL; +#else + EncryptedInfo info[1]; +#endif + + WOLFSSL_ENTER("EncryptDerKey"); + + /* Validate parameters. */ + if ((der == NULL) || (derSz == NULL) || (cipher == NULL) || + (passwd == NULL) || (cipherInfo == NULL)) { + ret = BAD_FUNC_ARG; + } + + #ifdef WOLFSSL_SMALL_STACK + if (ret == 0) { + /* Allocate encrypted info. */ + info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL, + DYNAMIC_TYPE_ENCRYPTEDINFO); + if (info == NULL) { + WOLFSSL_MSG("malloc failed"); + ret = 0; + } + } + #endif + if (ret == 0) { + /* Clear the encrypted info and set name. */ + XMEMSET(info, 0, sizeof(EncryptedInfo)); + XSTRNCPY(info->name, cipher, NAME_SZ - 1); + info->name[NAME_SZ - 1] = '\0'; /* null term */ + + /* Get encrypted info from name. */ + ret = wc_EncryptedInfoGet(info, info->name); + if (ret != 0) { + WOLFSSL_MSG("unsupported cipher"); + } + } + + if (ret == 0) { + /* Generate a random salt. */ + if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) { + WOLFSSL_MSG("generate iv failed"); + ret = -1; + } + } + + if (ret == 0) { + /* Calculate padding size - always a padding block. */ + paddingSz = info->ivSz - ((*derSz) % info->ivSz); + /* Check der is big enough. */ + if (maxDerSz < (*derSz) + paddingSz) { + WOLFSSL_MSG("not enough DER buffer allocated"); + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + /* Set padding bytes to padding length. */ + XMEMSET(der + (*derSz), (byte)paddingSz, paddingSz); + /* Add padding to DER size. */ + (*derSz) += (int)paddingSz; + + /* Encrypt DER buffer. */ + ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz, WC_MD5); + if (ret != 0) { + WOLFSSL_MSG("encrypt key failed"); + } + } + + if (ret == 0) { + /* Create cipher info : 'cipher_name,Salt(hex)' */ + cipherInfoSz = (word32)(2 * info->ivSz + XSTRLEN(info->name) + 2); + /* Allocate memory for PEM encryption lines. */ + *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, DYNAMIC_TYPE_STRING); + if (*cipherInfo == NULL) { + WOLFSSL_MSG("malloc failed"); + ret = MEMORY_E; + } + } + if (ret == 0) { + /* Copy in name and add on comma. */ + XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz); + XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz); + + /* Find end of string. */ + idx = (word32)XSTRLEN((char*)*cipherInfo); + /* Calculate remaining bytes. */ + cipherInfoSz -= idx; + + /* Encode IV into PEM encryption lines. */ + ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo + idx, + &cipherInfoSz); + if (ret != 0) { + WOLFSSL_MSG("Base16_Encode failed"); + XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING); + *cipherInfo = NULL; + } + } + +#ifdef WOLFSSL_SMALL_STACK + /* Free dynamically allocated info. */ + XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); +#endif + return ret == 0; +} +#endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */ + + #if defined(WOLFSSL_KEY_GEN) && \ (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \ (!defined(NO_RSA) || defined(HAVE_ECC)) +/* Encrypt the DER in PEM format. + * + * @param [in] der DER encoded private key. + * @param [in] derSz Size of DER in bytes. + * @param [in] cipher EVP cipher. + * @param [in] passwd Password to use in encryption. + * @param [in] passwdSz Size of password in bytes. + * @param [in] type PEM type of write out. + * @param [in] heap Dynamic memory hint. + * @param [out] out Allocated buffer containing PEM encoding. + * heap was NULL and dynamic type is DYNAMIC_TYPE_KEY. + * @param [out] outSz Size of PEM encoding in bytes. + * @return 1 on success. + * @return 0 on failure. + */ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type, void* heap, byte** out, int* outSz) @@ -736,8 +880,11 @@ static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name, #endif /* XSNPRINTF && !NO_BIO && !NO_RSA */ -#if !defined(NO_RSA) || (!defined(NO_DH) && !defined(NO_CERTS) && \ - defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || defined(HAVE_ECC) +#endif /* OPENSSL_EXTRA */ + +#if !defined(NO_CERTS) || (defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || \ + (!defined(NO_DH) && defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || \ + defined(HAVE_ECC))) /* Uses the DER SEQUENCE to determine size of DER data. * @@ -765,9 +912,7 @@ static int wolfssl_der_length(const unsigned char* seq, int len) return ret; } -#endif /* !NO_RSA */ - -#endif /* OPENSSL_EXTRA */ +#endif /******************************************************************************* * START OF RSA API @@ -1659,7 +1804,7 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, rsa->pkcs8HeaderSz = (word16)idx; } /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */ - else if (res != ASN_PARSE_E) { + else if (res != WC_NO_ERR_TRACE(ASN_PARSE_E)) { /* Something went wrong while decoding. */ WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 " "header"); @@ -1787,7 +1932,7 @@ int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa) ret = 0; } if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio, - PUBLICKEY_TYPE) != WOLFSSL_SUCCESS)) { + PUBLICKEY_TYPE) != 1)) { ret = 0; } @@ -1832,7 +1977,7 @@ static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa, ret = 0; } if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type, - rsa->heap) != WOLFSSL_SUCCESS)) { + rsa->heap) != 1)) { ret = 0; } @@ -2559,7 +2704,7 @@ int SetRsaInternal(WOLFSSL_RSA* rsa) } /* Copy down d mod q-1 if available. */ - if ((ret == 1) && (rsa->dmp1 != NULL) && + if ((ret == 1) && (rsa->dmq1 != NULL) && (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) { WOLFSSL_ERROR_MSG("rsa dQ key error"); ret = -1; @@ -3239,7 +3384,7 @@ WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e, ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL); #ifdef HAVE_FIPS /* Keep trying if failed to find a prime. */ - if (ret == PRIME_GEN_E) { + if (ret == WC_NO_ERR_TRACE(PRIME_GEN_E)) { continue; } #endif @@ -3290,7 +3435,7 @@ int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e, int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb); #ifdef HAVE_FIPS /* Keep trying again if public key value didn't work. */ - if (gen_ret == PRIME_GEN_E) { + if (gen_ret == WC_NO_ERR_TRACE(PRIME_GEN_E)) { continue; } #endif @@ -3419,7 +3564,7 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, if (ret == 1) { /* Get length of RSA key - encrypted message length. */ emLen = wolfSSL_RSA_size(rsa); - if (ret <= 0) { + if (emLen <= 0) { WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error"); ret = 0; } @@ -5468,7 +5613,7 @@ int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len, } #endif /* !HAVE_SELFTEST */ -WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa, +int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa, unsigned char** out) { int ret = 0; @@ -5485,7 +5630,7 @@ WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa, if (ret == 0) { key = (DsaKey*)dsa->internal; ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen); - if (ret == LENGTH_ONLY_E) { + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { ret = 0; } } @@ -5577,99 +5722,115 @@ WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der, * Returns 1 or 0 */ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, - const EVP_CIPHER* cipher, - unsigned char* passwd, int len, - wc_pem_password_cb* cb, void* arg) + const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + wc_pem_password_cb* cb, void* arg) { - int ret = 0, der_max_len = 0, derSz = 0; - byte *derBuf; - WOLFSSL_EVP_PKEY* pkey; + int ret = 1; + byte *pem = NULL; + int pLen = 0; WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey"); - if (bio == NULL || dsa == NULL) { + (void)cb; + (void)arg; + + /* Validate parameters. */ + if ((bio == NULL) || (dsa == NULL)) { WOLFSSL_MSG("Bad Function Arguments"); - return 0; + ret = 0; } - pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap); - if (pkey == NULL) { - WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed"); - return 0; + if (ret == 1) { + ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, cipher, passwd, passwdSz, + &pem, &pLen); } - pkey->type = EVP_PKEY_DSA; - pkey->dsa = dsa; - pkey->ownDsa = 0; + /* Write PEM to BIO. */ + if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) { + WOLFSSL_ERROR_MSG("DSA private key BIO write failed"); + ret = 0; + } - /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ - der_max_len = MAX_DSA_PRIVKEY_SZ; + XFREE(pem, NULL, DYNAMIC_TYPE_KEY); + return ret; +} - derBuf = (byte*)XMALLOC((size_t)der_max_len, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (derBuf == NULL) { - WOLFSSL_MSG("Malloc failed"); - wolfSSL_EVP_PKEY_free(pkey); - return 0; - } +#ifndef HAVE_SELFTEST +/* Encode the DSA public key as DER. + * + * @param [in] key DSA key to encode. + * @param [out] der Pointer through which buffer is returned. + * @param [in] heap Heap hint. + * @return Size of encoding on success. + * @return 0 on error. + */ +static int wolfssl_dsa_key_to_pubkey_der(WOLFSSL_DSA* key, unsigned char** der, + void* heap) +{ + int sz; + unsigned char* buf = NULL; - /* convert key to der format */ - derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len); - if (derSz < 0) { - WOLFSSL_MSG("wc_DsaKeyToDer failed"); - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - wolfSSL_EVP_PKEY_free(pkey); - return 0; + /* Use maximum encoded size to allocate. */ + sz = MAX_DSA_PUBKEY_SZ; + /* Allocate memory to hold encoding. */ + buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (buf == NULL) { + WOLFSSL_MSG("malloc failed"); + sz = 0; } - - pkey->pkey.ptr = (char*)XMALLOC((size_t)derSz, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (pkey->pkey.ptr == NULL) { - WOLFSSL_MSG("key malloc failed"); - XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - wolfSSL_EVP_PKEY_free(pkey); - return 0; + if (sz > 0) { + /* Encode public key to DER using wolfSSL. */ + sz = wc_DsaKeyToPublicDer((DsaKey*)key->internal, buf, (word32)sz); + if (sz < 0) { + WOLFSSL_MSG("wc_DsaKeyToPublicDer failed"); + sz = 0; + } } - /* add der info to the evp key */ - pkey->pkey_sz = derSz; - XMEMCPY(pkey->pkey.ptr, derBuf, (size_t)derSz); - XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - - ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len, - cb, arg); - wolfSSL_EVP_PKEY_free(pkey); + /* Return buffer on success. */ + if (sz > 0) { + *der = buf; + } + else { + /* Dispose of any dynamically allocated data not returned. */ + XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER); + } - return ret; + return sz; } -#ifndef HAVE_SELFTEST /* Takes a DSA public key and writes it out to a WOLFSSL_BIO * Returns 1 or 0 */ int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa) { - int ret = 0; - WOLFSSL_EVP_PKEY* pkey; + int ret = 1; + unsigned char* derBuf = NULL; + int derSz = 0; + WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY"); - if (bio == NULL || dsa == NULL) { - WOLFSSL_MSG("Bad function arguments"); + /* Validate parameters. */ + if ((bio == NULL) || (dsa == NULL)) { + WOLFSSL_MSG("Bad Function Arguments"); return 0; } - pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap); - if (pkey == NULL) { - WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed"); - return 0; + /* Encode public key in EC key as DER. */ + derSz = wolfssl_dsa_key_to_pubkey_der(dsa, &derBuf, bio->heap); + if (derSz == 0) { + ret = 0; } - pkey->type = EVP_PKEY_DSA; - pkey->dsa = dsa; - pkey->ownDsa = 0; + /* Write out to BIO the PEM encoding of the DSA public key. */ + if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio, + PUBLICKEY_TYPE) != 1)) { + ret = 0; + } + + /* Dispose of any dynamically allocated data. */ + XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - ret = pem_write_bio_pubkey(bio, pkey); - wolfSSL_EVP_PKEY_free(pkey); return ret; } #endif /* HAVE_SELFTEST */ @@ -7305,7 +7466,7 @@ int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out) *out += len; } /* An error occurred unless only length returned. */ - else if (ret != LENGTH_ONLY_E) { + else if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { err = 1; } } @@ -7455,7 +7616,7 @@ static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh, } if (memAlloced) { /* PEM data no longer needed. */ - XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); } if (!err) { @@ -7610,7 +7771,7 @@ static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out, /* Use wolfSSL API to get length of DER encode DH parameters. */ key = (DhKey*)dh->internal; ret = wc_DhParamsToDer(key, NULL, &derSz); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_ERROR_MSG("Failed to get size of DH params"); err = 1; } @@ -7681,7 +7842,7 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh) } } if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, - DH_PARAM_TYPE, NULL) != WOLFSSL_SUCCESS)) { + DH_PARAM_TYPE, NULL) != 1)) { ret = 0; } @@ -8569,7 +8730,7 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, if (ret == 0) { /* Get the public key into the array. */ pubSz = wolfSSL_BN_bn2bin(otherPub, pub); - if (privSz <= 0) { + if (pubSz <= 0) { ret = -1; } } @@ -9715,7 +9876,6 @@ void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point) #endif } -#ifndef HAVE_SELFTEST /* Convert EC point to hex string that as either uncompressed or compressed. * * ECC point compression types were not included in selftest ecc.h @@ -9828,7 +9988,100 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, return hex; } -#endif /* HAVE_SELFTEST */ +static size_t hex_to_bytes(const char *hex, unsigned char *output, size_t sz) +{ + word32 i; + for (i = 0; i < sz; i++) { + signed char ch1, ch2; + ch1 = HexCharToByte(hex[i * 2]); + ch2 = HexCharToByte(hex[i * 2 + 1]); + if ((ch1 < 0) || (ch2 < 0)) { + WOLFSSL_MSG("hex_to_bytes: syntax error"); + return 0; + } + output[i] = (unsigned char)((ch1 << 4) + ch2); + } + return sz; +} + +WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const EC_GROUP *group, + const char *hex, WOLFSSL_EC_POINT*p, WOLFSSL_BN_CTX *ctx) +{ + /* for uncompressed mode */ + size_t str_sz; + BIGNUM *Gx = NULL; + BIGNUM *Gy = NULL; + char strGx[MAX_ECC_BYTES * 2 + 1]; + + /* for compressed mode */ + int key_sz; + byte *octGx = (byte *)strGx; /* octGx[MAX_ECC_BYTES] */ + + int p_alloc = 0; + int ret; + + WOLFSSL_ENTER("wolfSSL_EC_POINT_hex2point"); + + if (group == NULL || hex == NULL || ctx == NULL) + return NULL; + + if (p == NULL) { + if ((p = wolfSSL_EC_POINT_new(group)) == NULL) { + WOLFSSL_MSG("wolfSSL_EC_POINT_new"); + goto err; + } + p_alloc = 1; + } + + key_sz = (wolfSSL_EC_GROUP_get_degree(group) + 7) / 8; + if (hex[0] == '0' && hex[1] == '4') { /* uncompressed mode */ + str_sz = key_sz * 2; + + XMEMSET(strGx, 0x0, str_sz + 1); + XMEMCPY(strGx, hex + 2, str_sz); + + if (wolfSSL_BN_hex2bn(&Gx, strGx) == 0) + goto err; + + if (wolfSSL_BN_hex2bn(&Gy, hex + 2 + str_sz) == 0) + goto err; + + ret = wolfSSL_EC_POINT_set_affine_coordinates_GFp + (group, p, Gx, Gy, ctx); + + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp"); + goto err; + } + } + else if (hex[0] == '0' && (hex[1] == '2' || hex[1] == '3')) { + size_t sz = XSTRLEN(hex + 2) / 2; + /* compressed mode */ + octGx[0] = ECC_POINT_COMP_ODD; + if (hex_to_bytes(hex + 2, octGx + 1, sz) != sz) { + goto err; + } + if (wolfSSL_ECPoint_d2i(octGx, key_sz + 1, group, p) + != WOLFSSL_SUCCESS) { + goto err; + } + } + else + goto err; + + wolfSSL_BN_free(Gx); + wolfSSL_BN_free(Gy); + return p; + +err: + wolfSSL_BN_free(Gx); + wolfSSL_BN_free(Gy); + if (p_alloc) { + EC_POINT_free(p); + } + return NULL; + +} /* Encode the EC point as an uncompressed point in DER. * @@ -9871,7 +10124,8 @@ int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group, int ret = wc_ecc_export_point_der(group->curve_idx, (ecc_point*)point->internal, out, len); /* Check return. When out is NULL, return will be length only error. */ - if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) { + if ((ret != MP_OKAY) && ((out != NULL) || + (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)))) { WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed"); res = 0; } @@ -11549,7 +11803,8 @@ static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src) if (ret == 0) { /* Copy private key. */ - ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst)); + ret = mp_copy(wc_ecc_key_get_priv((ecc_key*)src), + wc_ecc_key_get_priv(dst)); if (ret != MP_OKAY) { WOLFSSL_MSG("mp_copy error"); } @@ -12005,7 +12260,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, res = 1; } /* Error out on parsing error. */ - else if (ret != ASN_PARSE_E) { + else if (ret != WC_NO_ERR_TRACE(ASN_PARSE_E)) { WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header"); res = -1; } @@ -12076,12 +12331,9 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, * EC key PEM APIs */ -#if (defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM)) || \ - (!defined(NO_BIO) && (defined(WOLFSSL_KEY_GEN) || \ - defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT))) +#ifdef HAVE_ECC_KEY_EXPORT +#if defined(WOLFSSL_KEY_GEN) && (!defined(NO_FILESYSTEM) || !defined(NO_BIO)) /* Encode the EC public key as DER. - * - * Also used by pem_write_pubkey(). * * @param [in] key EC key to encode. * @param [out] der Pointer through which buffer is returned. @@ -12176,6 +12428,7 @@ int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key) return ret; } #endif +#endif #ifndef NO_BIO /* Read a PEM encoded EC public key from a BIO. @@ -12302,7 +12555,7 @@ WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio, } #endif /* !NO_BIO */ -#if defined(WOLFSSL_KEY_GEN) +#if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC_KEY_EXPORT) #ifndef NO_BIO /* Write out the EC public key as PEM to the BIO. * @@ -12331,7 +12584,7 @@ int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec) ret = 0; } - /* Write out to BIO the PEM encoding of the EC private key. */ + /* Write out to BIO the PEM encoding of the EC public key. */ if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio, ECC_PUBLICKEY_TYPE) != 1)) { ret = 0; @@ -12534,7 +12787,7 @@ int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec, } #endif /* NO_FILESYSTEM */ -#endif /* defined(WOLFSSL_KEY_GEN) */ +#endif /* WOLFSSL_KEY_GEN && HAVE_ECC_KEY_EXPORT */ /* * EC key print APIs @@ -13106,13 +13359,17 @@ int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key) /* Check if we know which internal curve index to use. */ if (key->group->curve_idx < 0) { /* Generate key using the default curve. */ +#if FIPS_VERSION3_GE(6,0,0) + key->group->curve_idx = ECC_SECP256R1; /* FIPS default to 256 */ +#else key->group->curve_idx = ECC_CURVE_DEF; +#endif } /* Create a random number generator. */ rng = wolfssl_make_rng(tmpRng, &initTmpRng); if (rng == NULL) { - WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to set RNG"); + WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG"); res = 0; } } @@ -13120,11 +13377,30 @@ int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key) /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid * is 0 then pass ECC_CURVE_DEF as arg */ int eccEnum = key->group->curve_nid ? +#if FIPS_VERSION3_GE(6,0,0) + NIDToEccEnum(key->group->curve_nid) : ECC_SECP256R1; +#else NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF; +#endif /* Get the internal EC key. */ ecc_key* ecKey = (ecc_key*)key->internal; /* Make the key using internal API. */ - int ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum); + int ret = 0; + +#if FIPS_VERSION3_GE(6,0,0) + /* In the case of FIPS only allow key generation with approved curves */ + if (eccEnum != ECC_SECP256R1 && eccEnum != ECC_SECP224R1 && + eccEnum != ECC_SECP384R1 && eccEnum != ECC_SECP521R1) { + WOLFSSL_MSG("Unsupported curve selected in FIPS mode"); + res = 0; + } + if (res == 1) { +#endif + ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum); +#if FIPS_VERSION3_GE(6,0,0) + } +#endif + #if defined(WOLFSSL_ASYNC_CRYPT) /* Wait on asynchronouse operation. */ ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE); @@ -13383,6 +13659,7 @@ WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig, int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) { word32 len = 0; + int update_p = 1; /* Validate parameter. */ if (sig != NULL) { @@ -13402,6 +13679,17 @@ int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) /* Add in the length of the SEQUENCE. */ len += (word32)1 + ASN_LEN_SIZE(len); + #ifdef WOLFSSL_I2D_ECDSA_SIG_ALLOC + if ((pp != NULL) && (*pp == NULL)) { + *pp = (unsigned char *)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL); + if (*pp != NULL) { + WOLFSSL_MSG("malloc error"); + return 0; + } + update_p = 0; + } + #endif + /* Encode only if there is a buffer to encode into. */ if ((pp != NULL) && (*pp != NULL)) { /* Encode using the internal representations of r and s. */ @@ -13410,7 +13698,7 @@ int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp) /* No bytes encoded. */ len = 0; } - else { + else if (update_p) { /* Update pointer to after encoding. */ *pp += len; } @@ -13861,12 +14149,2311 @@ int wolfSSL_ECDH_compute_key(void *out, size_t outLen, /* End ECDH */ -#endif /* OPENSSL_EXTRA */ +#ifndef NO_WOLFSSL_STUB +const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_OpenSSL(void) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_OpenSSL"); -#endif /* HAVE_ECC */ + return NULL; +} -/******************************************************************************* - * END OF EC API +WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_METHOD_new( + const WOLFSSL_EC_KEY_METHOD *meth) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_new"); + + (void)meth; + + return NULL; +} + +void wolfSSL_EC_KEY_METHOD_free(WOLFSSL_EC_KEY_METHOD *meth) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_free"); + + (void)meth; +} + +void wolfSSL_EC_KEY_METHOD_set_init(WOLFSSL_EC_KEY_METHOD *meth, + void* a1, void* a2, void* a3, void* a4, void* a5, void* a6) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_init"); + + (void)meth; + (void)a1; + (void)a2; + (void)a3; + (void)a4; + (void)a5; + (void)a6; +} + +void wolfSSL_EC_KEY_METHOD_set_sign(WOLFSSL_EC_KEY_METHOD *meth, + void* a1, void* a2, void* a3) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_sign"); + + (void)meth; + (void)a1; + (void)a2; + (void)a3; +} + +const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_get_method( + const WOLFSSL_EC_KEY *key) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_get_method"); + + (void)key; + + return NULL; +} + +int wolfSSL_EC_KEY_set_method(WOLFSSL_EC_KEY *key, + const WOLFSSL_EC_KEY_METHOD *meth) +{ + WOLFSSL_STUB("wolfSSL_EC_KEY_set_method"); + + (void)key; + (void)meth; + + return 0; +} + +#endif /* !NO_WOLFSSL_STUB */ + +#endif /* OPENSSL_EXTRA */ + +#endif /* HAVE_ECC */ + +/******************************************************************************* + * END OF EC API + ******************************************************************************/ + +/******************************************************************************* + * START OF EC25519 API + ******************************************************************************/ + +#if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519) + +/* Generate an EC25519 key pair. + * + * Output keys are in little endian format. + * + * @param [out] priv EC25519 private key data. + * @param [in, out] privSz On in, the size of priv in bytes. + * On out, the length of the private key data in bytes. + * @param [out] pub EC25519 public key data. + * @param [in, out] pubSz On in, the size of pub in bytes. + * On out, the length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz, + unsigned char *pub, unsigned int *pubSz) +{ +#ifdef WOLFSSL_KEY_GEN + int res = 1; + int initTmpRng = 0; + WC_RNG *rng = NULL; +#ifdef WOLFSSL_SMALL_STACK + WC_RNG *tmpRng = NULL; +#else + WC_RNG tmpRng[1]; +#endif + curve25519_key key; + + WOLFSSL_ENTER("wolfSSL_EC25519_generate_key"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE25519_KEYSIZE) || + (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE25519_KEYSIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + if (res) { + /* Create a random number generator. */ + rng = wolfssl_make_rng(tmpRng, &initTmpRng); + if (rng == NULL) { + WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG"); + res = 0; + } + } + + /* Initialize a Curve25519 key. */ + if (res && (wc_curve25519_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve25519_init failed"); + res = 0; + } + if (res) { + /* Make a Curve25519 key pair. */ + int ret = wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key); + if (ret != MP_OKAY) { + WOLFSSL_MSG("wc_curve25519_make_key failed"); + res = 0; + } + if (res) { + /* Export Curve25519 key pair to buffers. */ + ret = wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub, + pubSz, EC25519_LITTLE_ENDIAN); + if (ret != MP_OKAY) { + WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed"); + res = 0; + } + } + + /* Dispose of key. */ + wc_curve25519_free(&key); + } + + if (initTmpRng) { + wc_FreeRng(rng); + #ifdef WOLFSSL_SMALL_STACK + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); + #endif + } + + return res; +#else + WOLFSSL_MSG("No Key Gen built in"); + + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN */ +} + +/* Compute a shared secret from private and public EC25519 keys. + * + * Input and output keys are in little endian format + * + * @param [out] shared Shared secret buffer. + * @param [in, out] sharedSz On in, the size of shared in bytes. + * On out, the length of the secret in bytes. + * @param [in] priv EC25519 private key data. + * @param [in] privSz Length of the private key data in bytes. + * @param [in] pub EC25519 public key data. + * @param [in] pubSz Length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz, + const unsigned char *priv, unsigned int privSz, const unsigned char *pub, + unsigned int pubSz) +{ +#ifdef WOLFSSL_KEY_GEN + int res = 1; + curve25519_key privkey; + curve25519_key pubkey; + + WOLFSSL_ENTER("wolfSSL_EC25519_shared_key"); + + /* Validate parameters. */ + if ((shared == NULL) || (sharedSz == NULL) || + (*sharedSz < CURVE25519_KEYSIZE) || (priv == NULL) || + (privSz < CURVE25519_KEYSIZE) || (pub == NULL) || + (pubSz < CURVE25519_KEYSIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize private key object. */ + if (res && (wc_curve25519_init(&privkey) != 0)) { + WOLFSSL_MSG("wc_curve25519_init privkey failed"); + res = 0; + } + if (res) { + /* Initialize public key object. */ + if (wc_curve25519_init(&pubkey) != MP_OKAY) { + WOLFSSL_MSG("wc_curve25519_init pubkey failed"); + res = 0; + } + if (res) { + /* Import our private key. */ + int ret = wc_curve25519_import_private_ex(priv, privSz, &privkey, + EC25519_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve25519_import_private_ex failed"); + res = 0; + } + + if (res) { + /* Import peer's public key. */ + ret = wc_curve25519_import_public_ex(pub, pubSz, &pubkey, + EC25519_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve25519_import_public_ex failed"); + res = 0; + } + } + if (res) { + /* Compute shared secret. */ + ret = wc_curve25519_shared_secret_ex(&privkey, &pubkey, shared, + sharedSz, EC25519_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed"); + res = 0; + } + } + + wc_curve25519_free(&pubkey); + } + wc_curve25519_free(&privkey); + } + + return res; +#else + WOLFSSL_MSG("No Key Gen built in"); + + (void)shared; + (void)sharedSz; + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN */ +} +#endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */ + +/******************************************************************************* + * END OF EC25519 API + ******************************************************************************/ + +/******************************************************************************* + * START OF ED25519 API + ******************************************************************************/ + +#if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519) +/* Generate an ED25519 key pair. + * + * Output keys are in little endian format. + * + * @param [out] priv ED25519 private key data. + * @param [in, out] privSz On in, the size of priv in bytes. + * On out, the length of the private key data in bytes. + * @param [out] pub ED25519 public key data. + * @param [in, out] pubSz On in, the size of pub in bytes. + * On out, the length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz, + unsigned char *pub, unsigned int *pubSz) +{ +#if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED25519_KEY_EXPORT) + int res = 1; + int initTmpRng = 0; + WC_RNG *rng = NULL; +#ifdef WOLFSSL_SMALL_STACK + WC_RNG *tmpRng = NULL; +#else + WC_RNG tmpRng[1]; +#endif + ed25519_key key; + + WOLFSSL_ENTER("wolfSSL_ED25519_generate_key"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz == NULL) || + (*privSz < ED25519_PRV_KEY_SIZE) || (pub == NULL) || + (pubSz == NULL) || (*pubSz < ED25519_PUB_KEY_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + if (res) { + /* Create a random number generator. */ + rng = wolfssl_make_rng(tmpRng, &initTmpRng); + if (rng == NULL) { + WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG"); + res = 0; + } + } + + /* Initialize an Ed25519 key. */ + if (res && (wc_ed25519_init(&key) != 0)) { + WOLFSSL_MSG("wc_ed25519_init failed"); + res = 0; + } + if (res) { + /* Make an Ed25519 key pair. */ + int ret = wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed25519_make_key failed"); + res = 0; + } + if (res) { + /* Export Curve25519 key pair to buffers. */ + ret = wc_ed25519_export_key(&key, priv, privSz, pub, pubSz); + if (ret != 0) { + WOLFSSL_MSG("wc_ed25519_export_key failed"); + res = 0; + } + } + + wc_ed25519_free(&key); + } + + if (initTmpRng) { + wc_FreeRng(rng); + #ifdef WOLFSSL_SMALL_STACK + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); + #endif + } + + return res; +#else +#ifndef WOLFSSL_KEY_GEN + WOLFSSL_MSG("No Key Gen built in"); +#else + WOLFSSL_MSG("No ED25519 key export built in"); +#endif + + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */ +} + +/* Sign a message with Ed25519 using the private key. + * + * Input and output keys are in little endian format. + * Priv is a buffer containing private and public part of key. + * + * @param [in] msg Message to be signed. + * @param [in] msgSz Length of message in bytes. + * @param [in] priv ED25519 private key data. + * @param [in] privSz Length in bytes of private key data. + * @param [out] sig Signature buffer. + * @param [in, out] sigSz On in, the length of the signature buffer in bytes. + * On out, the length of the signature in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz, + const unsigned char *priv, unsigned int privSz, unsigned char *sig, + unsigned int *sigSz) +{ +#if defined(HAVE_ED25519_SIGN) && defined(WOLFSSL_KEY_GEN) && \ + defined(HAVE_ED25519_KEY_IMPORT) + ed25519_key key; + int res = 1; + + WOLFSSL_ENTER("wolfSSL_ED25519_sign"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz != ED25519_PRV_KEY_SIZE) || + (msg == NULL) || (sig == NULL) || (sigSz == NULL) || + (*sigSz < ED25519_SIG_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize Ed25519 key. */ + if (res && (wc_ed25519_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve25519_init failed"); + res = 0; + } + if (res) { + /* Import private and public key. */ + int ret = wc_ed25519_import_private_key(priv, privSz / 2, + priv + (privSz / 2), ED25519_PUB_KEY_SIZE, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed25519_import_private failed"); + res = 0; + } + + if (res) { + /* Sign message with Ed25519. */ + ret = wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed"); + res = 0; + } + } + + wc_ed25519_free(&key); + } + + return res; +#else +#if !defined(HAVE_ED25519_SIGN) + WOLFSSL_MSG("No ED25519 sign built in"); +#elif !defined(WOLFSSL_KEY_GEN) + WOLFSSL_MSG("No Key Gen built in"); +#elif !defined(HAVE_ED25519_KEY_IMPORT) + WOLFSSL_MSG("No ED25519 Key import built in"); +#endif + + (void)msg; + (void)msgSz; + (void)priv; + (void)privSz; + (void)sig; + (void)sigSz; + + return 0; +#endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ +} + +/* Verify a message with Ed25519 using the public key. + * + * Input keys are in little endian format. + * + * @param [in] msg Message to be verified. + * @param [in] msgSz Length of message in bytes. + * @param [in] pub ED25519 public key data. + * @param [in] privSz Length in bytes of public key data. + * @param [in] sig Signature buffer. + * @param [in] sigSz Length of the signature in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz, + const unsigned char *pub, unsigned int pubSz, const unsigned char *sig, + unsigned int sigSz) +{ +#if defined(HAVE_ED25519_VERIFY) && defined(WOLFSSL_KEY_GEN) && \ + defined(HAVE_ED25519_KEY_IMPORT) + ed25519_key key; + int res = 1; + + WOLFSSL_ENTER("wolfSSL_ED25519_verify"); + + /* Validate parameters. */ + if ((pub == NULL) || (pubSz != ED25519_PUB_KEY_SIZE) || (msg == NULL) || + (sig == NULL) || (sigSz != ED25519_SIG_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize Ed25519 key. */ + if (res && (wc_ed25519_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve25519_init failed"); + res = 0; + } + if (res) { + /* Import public key. */ + int ret = wc_ed25519_import_public(pub, pubSz, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed25519_import_public failed"); + res = 0; + } + + if (res) { + int check = 0; + + /* Verify signature with message and public key. */ + ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz, &check, + &key); + /* Check for errors in verification process. */ + if (ret != 0) { + WOLFSSL_MSG("wc_ed25519_verify_msg failed"); + res = 0; + } + /* Check signature is valid. */ + else if (!check) { + WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)"); + res = 0; + } + } + + wc_ed25519_free(&key); + } + + return res; +#else +#if !defined(HAVE_ED25519_VERIFY) + WOLFSSL_MSG("No ED25519 verify built in"); +#elif !defined(WOLFSSL_KEY_GEN) + WOLFSSL_MSG("No Key Gen built in"); +#elif !defined(HAVE_ED25519_KEY_IMPORT) + WOLFSSL_MSG("No ED25519 Key import built in"); +#endif + + (void)msg; + (void)msgSz; + (void)pub; + (void)pubSz; + (void)sig; + (void)sigSz; + + return 0; +#endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ +} + +#endif /* OPENSSL_EXTRA && HAVE_ED25519 */ + +/******************************************************************************* + * END OF ED25519 API + ******************************************************************************/ + +/******************************************************************************* + * START OF EC448 API + ******************************************************************************/ + +#if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448) +/* Generate an EC448 key pair. + * + * Output keys are in little endian format. + * + * @param [out] priv EC448 private key data. + * @param [in, out] privSz On in, the size of priv in bytes. + * On out, the length of the private key data in bytes. + * @param [out] pub EC448 public key data. + * @param [in, out] pubSz On in, the size of pub in bytes. + * On out, the length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz, + unsigned char *pub, unsigned int *pubSz) +{ +#ifdef WOLFSSL_KEY_GEN + int res = 1; + int initTmpRng = 0; + WC_RNG *rng = NULL; +#ifdef WOLFSSL_SMALL_STACK + WC_RNG *tmpRng = NULL; +#else + WC_RNG tmpRng[1]; +#endif + curve448_key key; + + WOLFSSL_ENTER("wolfSSL_EC448_generate_key"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE448_KEY_SIZE) || + (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE448_KEY_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + if (res) { + /* Create a random number generator. */ + rng = wolfssl_make_rng(tmpRng, &initTmpRng); + if (rng == NULL) { + WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG"); + res = 0; + } + } + + /* Initialize a Curve448 key. */ + if (res && (wc_curve448_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve448_init failed"); + res = 0; + } + if (res) { + /* Make a Curve448 key pair. */ + int ret = wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_make_key failed"); + res = 0; + } + if (res) { + /* Export Curve448 key pair to buffers. */ + ret = wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz, + EC448_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed"); + res = 0; + } + } + + /* Dispose of key. */ + wc_curve448_free(&key); + } + + if (initTmpRng) { + wc_FreeRng(rng); + #ifdef WOLFSSL_SMALL_STACK + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); + #endif + } + + return res; +#else + WOLFSSL_MSG("No Key Gen built in"); + + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN */ +} + +/* Compute a shared secret from private and public EC448 keys. + * + * Input and output keys are in little endian format + * + * @param [out] shared Shared secret buffer. + * @param [in, out] sharedSz On in, the size of shared in bytes. + * On out, the length of the secret in bytes. + * @param [in] priv EC448 private key data. + * @param [in] privSz Length of the private key data in bytes. + * @param [in] pub EC448 public key data. + * @param [in] pubSz Length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz, + const unsigned char *priv, unsigned int privSz, + const unsigned char *pub, unsigned int pubSz) +{ +#ifdef WOLFSSL_KEY_GEN + int res = 1; + curve448_key privkey; + curve448_key pubkey; + + WOLFSSL_ENTER("wolfSSL_EC448_shared_key"); + + /* Validate parameters. */ + if ((shared == NULL) || (sharedSz == NULL) || + (*sharedSz < CURVE448_KEY_SIZE) || (priv == NULL) || + (privSz < CURVE448_KEY_SIZE) || (pub == NULL) || + (pubSz < CURVE448_KEY_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize private key object. */ + if (res && (wc_curve448_init(&privkey) != 0)) { + WOLFSSL_MSG("wc_curve448_init privkey failed"); + res = 0; + } + if (res) { + /* Initialize public key object. */ + if (wc_curve448_init(&pubkey) != MP_OKAY) { + WOLFSSL_MSG("wc_curve448_init pubkey failed"); + res = 0; + } + if (res) { + /* Import our private key. */ + int ret = wc_curve448_import_private_ex(priv, privSz, &privkey, + EC448_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_import_private_ex failed"); + res = 0; + } + + if (res) { + /* Import peer's public key. */ + ret = wc_curve448_import_public_ex(pub, pubSz, &pubkey, + EC448_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_import_public_ex failed"); + res = 0; + } + } + if (res) { + /* Compute shared secret. */ + ret = wc_curve448_shared_secret_ex(&privkey, &pubkey, shared, + sharedSz, EC448_LITTLE_ENDIAN); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_shared_secret_ex failed"); + res = 0; + } + } + + wc_curve448_free(&pubkey); + } + wc_curve448_free(&privkey); + } + + return res; +#else + WOLFSSL_MSG("No Key Gen built in"); + + (void)shared; + (void)sharedSz; + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN */ +} +#endif /* OPENSSL_EXTRA && HAVE_CURVE448 */ + +/******************************************************************************* + * END OF EC448 API + ******************************************************************************/ + +/******************************************************************************* + * START OF ED448 API + ******************************************************************************/ + +#if defined(OPENSSL_EXTRA) && defined(HAVE_ED448) +/* Generate an ED448 key pair. + * + * Output keys are in little endian format. + * + * @param [out] priv ED448 private key data. + * @param [in, out] privSz On in, the size of priv in bytes. + * On out, the length of the private key data in bytes. + * @param [out] pub ED448 public key data. + * @param [in, out] pubSz On in, the size of pub in bytes. + * On out, the length of the public key data in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz, + unsigned char *pub, unsigned int *pubSz) +{ +#if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED448_KEY_EXPORT) + int res = 1; + int initTmpRng = 0; + WC_RNG *rng = NULL; +#ifdef WOLFSSL_SMALL_STACK + WC_RNG *tmpRng = NULL; +#else + WC_RNG tmpRng[1]; +#endif + ed448_key key; + + WOLFSSL_ENTER("wolfSSL_ED448_generate_key"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz == NULL) || + (*privSz < ED448_PRV_KEY_SIZE) || (pub == NULL) || + (pubSz == NULL) || (*pubSz < ED448_PUB_KEY_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + if (res) { + /* Create a random number generator. */ + rng = wolfssl_make_rng(tmpRng, &initTmpRng); + if (rng == NULL) { + WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG"); + res = 0; + } + } + + /* Initialize an Ed448 key. */ + if (res && (wc_ed448_init(&key) != 0)) { + WOLFSSL_MSG("wc_ed448_init failed"); + res = 0; + } + if (res) { + /* Make an Ed448 key pair. */ + int ret = wc_ed448_make_key(rng, ED448_KEY_SIZE, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed448_make_key failed"); + res = 0; + } + if (res) { + /* Export Curve448 key pair to buffers. */ + ret = wc_ed448_export_key(&key, priv, privSz, pub, pubSz); + if (ret != 0) { + WOLFSSL_MSG("wc_ed448_export_key failed"); + res = 0; + } + } + + wc_ed448_free(&key); + } + + if (initTmpRng) { + wc_FreeRng(rng); + #ifdef WOLFSSL_SMALL_STACK + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); + #endif + } + + return res; +#else +#ifndef WOLFSSL_KEY_GEN + WOLFSSL_MSG("No Key Gen built in"); +#else + WOLFSSL_MSG("No ED448 key export built in"); +#endif + + (void)priv; + (void)privSz; + (void)pub; + (void)pubSz; + + return 0; +#endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */ +} + +/* Sign a message with Ed448 using the private key. + * + * Input and output keys are in little endian format. + * Priv is a buffer containing private and public part of key. + * + * @param [in] msg Message to be signed. + * @param [in] msgSz Length of message in bytes. + * @param [in] priv ED448 private key data. + * @param [in] privSz Length in bytes of private key data. + * @param [out] sig Signature buffer. + * @param [in, out] sigSz On in, the length of the signature buffer in bytes. + * On out, the length of the signature in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz, + const unsigned char *priv, unsigned int privSz, unsigned char *sig, + unsigned int *sigSz) +{ +#if defined(HAVE_ED448_SIGN) && defined(WOLFSSL_KEY_GEN) && \ + defined(HAVE_ED448_KEY_IMPORT) + ed448_key key; + int res = 1; + + WOLFSSL_ENTER("wolfSSL_ED448_sign"); + + /* Validate parameters. */ + if ((priv == NULL) || (privSz != ED448_PRV_KEY_SIZE) || + (msg == NULL) || (sig == NULL) || (sigSz == NULL) || + (*sigSz < ED448_SIG_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize Ed448 key. */ + if (res && (wc_ed448_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve448_init failed"); + res = 0; + } + if (res) { + /* Import private and public key. */ + int ret = wc_ed448_import_private_key(priv, privSz / 2, + priv + (privSz / 2), ED448_PUB_KEY_SIZE, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed448_import_private failed"); + res = 0; + } + + if (res) { + /* Sign message with Ed448 - no context. */ + ret = wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0); + if (ret != 0) { + WOLFSSL_MSG("wc_curve448_shared_secret_ex failed"); + res = 0; + } + } + + wc_ed448_free(&key); + } + + return res; +#else +#if !defined(HAVE_ED448_SIGN) + WOLFSSL_MSG("No ED448 sign built in"); +#elif !defined(WOLFSSL_KEY_GEN) + WOLFSSL_MSG("No Key Gen built in"); +#elif !defined(HAVE_ED448_KEY_IMPORT) + WOLFSSL_MSG("No ED448 Key import built in"); +#endif + + (void)msg; + (void)msgSz; + (void)priv; + (void)privSz; + (void)sig; + (void)sigSz; + + return 0; +#endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */ +} + +/* Verify a message with Ed448 using the public key. + * + * Input keys are in little endian format. + * + * @param [in] msg Message to be verified. + * @param [in] msgSz Length of message in bytes. + * @param [in] pub ED448 public key data. + * @param [in] privSz Length in bytes of public key data. + * @param [in] sig Signature buffer. + * @param [in] sigSz Length of the signature in bytes. + * @return 1 on success + * @return 0 on failure. + */ +int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz, + const unsigned char *pub, unsigned int pubSz, const unsigned char *sig, + unsigned int sigSz) +{ +#if defined(HAVE_ED448_VERIFY) && defined(WOLFSSL_KEY_GEN) && \ + defined(HAVE_ED448_KEY_IMPORT) + ed448_key key; + int res = 1; + + WOLFSSL_ENTER("wolfSSL_ED448_verify"); + + /* Validate parameters. */ + if ((pub == NULL) || (pubSz != ED448_PUB_KEY_SIZE) || (msg == NULL) || + (sig == NULL) || (sigSz != ED448_SIG_SIZE)) { + WOLFSSL_MSG("Bad arguments"); + res = 0; + } + + /* Initialize Ed448 key. */ + if (res && (wc_ed448_init(&key) != 0)) { + WOLFSSL_MSG("wc_curve448_init failed"); + res = 0; + } + if (res) { + /* Import public key. */ + int ret = wc_ed448_import_public(pub, pubSz, &key); + if (ret != 0) { + WOLFSSL_MSG("wc_ed448_import_public failed"); + res = 0; + } + + if (res) { + int check = 0; + + /* Verify signature with message and public key - no context. */ + ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check, + &key, NULL, 0); + /* Check for errors in verification process. */ + if (ret != 0) { + WOLFSSL_MSG("wc_ed448_verify_msg failed"); + res = 0; + } + /* Check signature is valid. */ + else if (!check) { + WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)"); + res = 0; + } + } + + wc_ed448_free(&key); + } + + return res; +#else +#if !defined(HAVE_ED448_VERIFY) + WOLFSSL_MSG("No ED448 verify built in"); +#elif !defined(WOLFSSL_KEY_GEN) + WOLFSSL_MSG("No Key Gen built in"); +#elif !defined(HAVE_ED448_KEY_IMPORT) + WOLFSSL_MSG("No ED448 Key import built in"); +#endif + + (void)msg; + (void)msgSz; + (void)pub; + (void)pubSz; + (void)sig; + (void)sigSz; + + return 0; +#endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */ +} +#endif /* OPENSSL_EXTRA && HAVE_ED448 */ + +/******************************************************************************* + * END OF ED448 API + ******************************************************************************/ + +/******************************************************************************* + * START OF GENERIC PUBLIC KEY PEM APIs + ******************************************************************************/ + +#ifdef OPENSSL_EXTRA +/* Sets default callback password for PEM. + * + * @param [out] buf Buffer to hold password. + * @param [in] num Number of characters in buffer. + * @param [in] rwFlag Read/write flag. Ignored. + * @param [in] userData User data - assumed to be default password. + * @return Password size on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_def_callback(char* buf, int num, int rwFlag, void* userData) +{ + int sz = 0; + + WOLFSSL_ENTER("wolfSSL_PEM_def_callback"); + + (void)rwFlag; + + /* We assume that the user passes a default password as userdata */ + if ((buf != NULL) && (userData != NULL)) { + sz = (int)XSTRLEN((const char*)userData); + sz = (int)min((word32)sz, (word32)num); + XMEMCPY(buf, userData, sz); + } + else { + WOLFSSL_MSG("Error, default password cannot be created."); + } + + return sz; +} + +#ifndef NO_BIO +/* Writes a public key to a WOLFSSL_BIO encoded in PEM format. + * + * @param [in] bio BIO to write to. + * @param [in] key Public key to write in PEM format. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key) +{ + int ret = 0; + + WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY"); + + if ((bio != NULL) && (key != NULL)) { + switch (key->type) { +#if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) + case EVP_PKEY_RSA: + ret = wolfSSL_PEM_write_bio_RSA_PUBKEY(bio, key->rsa); + break; +#endif /* WOLFSSL_KEY_GEN && !NO_RSA */ +#if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && \ + (defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN)) + case EVP_PKEY_DSA: + ret = wolfSSL_PEM_write_bio_DSA_PUBKEY(bio, key->dsa); + break; +#endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */ +#if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && \ + defined(WOLFSSL_KEY_GEN) + case EVP_PKEY_EC: + ret = wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key->ecc); + break; +#endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */ +#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) + case EVP_PKEY_DH: + /* DH public key not supported. */ + WOLFSSL_MSG("Writing DH PUBKEY not supported!"); + break; +#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */ + default: + /* Key type not supported. */ + WOLFSSL_MSG("Unknown Key type!"); + break; + } + } + + return ret; +} + +/* Writes a private key to a WOLFSSL_BIO encoded in PEM format. + * + * @param [in] bio BIO to write to. + * @param [in] key Public key to write in PEM format. + * @param [in] cipher Encryption cipher to use. + * @param [in] passwd Password to use when encrypting. + * @param [in] len Length of password. + * @param [in] cb Password callback. + * @param [in] arg Password callback argument. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len, + wc_pem_password_cb* cb, void* arg) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey"); + + (void)cipher; + (void)passwd; + (void)len; + (void)cb; + (void)arg; + + /* Validate parameters. */ + if ((bio == NULL) || (key == NULL)) { + WOLFSSL_MSG("Bad Function Arguments"); + ret = 0; + } + + if (ret == 1) { + #ifdef WOLFSSL_KEY_GEN + switch (key->type) { + #ifndef NO_RSA + case EVP_PKEY_RSA: + /* Write using RSA specific API. */ + ret = wolfSSL_PEM_write_bio_RSAPrivateKey(bio, key->rsa, + cipher, passwd, len, cb, arg); + break; + #endif + #ifndef NO_DSA + case EVP_PKEY_DSA: + /* Write using DSA specific API. */ + ret = wolfSSL_PEM_write_bio_DSAPrivateKey(bio, key->dsa, + cipher, passwd, len, cb, arg); + break; + #endif + #ifdef HAVE_ECC + case EVP_PKEY_EC: + #if defined(HAVE_ECC_KEY_EXPORT) + /* Write using EC specific API. */ + ret = wolfSSL_PEM_write_bio_ECPrivateKey(bio, key->ecc, + cipher, passwd, len, cb, arg); + #else + ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, + key->pkey_sz, bio, EC_PRIVATEKEY_TYPE); + #endif + break; + #endif + #ifndef NO_DH + case EVP_PKEY_DH: + /* Write using generic API with DH type. */ + ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, + key->pkey_sz, bio, DH_PRIVATEKEY_TYPE); + break; + #endif + default: + WOLFSSL_MSG("Unknown Key type!"); + ret = 0; + break; + } + #else + int type = 0; + + switch (key->type) { + #ifndef NO_DSA + case EVP_PKEY_DSA: + type = DSA_PRIVATEKEY_TYPE; + break; + #endif + #ifdef HAVE_ECC + case EVP_PKEY_EC: + type = ECC_PRIVATEKEY_TYPE; + break; + #endif + #ifndef NO_DH + case EVP_PKEY_DH: + type = DH_PRIVATEKEY_TYPE; + break; + #endif + #ifndef NO_RSA + case EVP_PKEY_RSA: + type = PRIVATEKEY_TYPE; + break; + #endif + default: + ret = 0; + break; + } + if (ret == 1) { + /* Write using generic API with generic type. */ + ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, key->pkey_sz, + bio, type); + } + #endif + } + + return ret; +} +#endif /* !NO_BIO */ + +#ifndef NO_BIO +/* Create a private key object from the data in the BIO. + * + * @param [in] bio BIO to read from. + * @param [in, out] key Public key object. Object used if passed in. + * @param [in] cb Password callback. + * @param [in] arg Password callback argument. + * @return A WOLFSSL_EVP_PKEY object on success. + * @return NULL on failure. + */ +WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY **key, wc_pem_password_cb *cb, void *arg) +{ + int err = 0; + WOLFSSL_EVP_PKEY* pkey = NULL; + DerBuffer* der = NULL; + + WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY"); + + if (bio == NULL) { + err = 1; + } + + /* Read the PEM public key from the BIO and convert to DER. */ + if ((!err) && (pem_read_bio_key(bio, cb, arg, PUBLICKEY_TYPE, NULL, + &der) < 0)) { + err = 1; + } + + if (!err) { + const unsigned char* ptr = der->buffer; + + /* Use key passed in if set. */ + if ((key != NULL) && (*key != NULL)) { + pkey = *key; + } + + /* Convert DER data to a public key object. */ + if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) { + WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); + pkey = NULL; + err = 1; + } + } + + /* Return the key if possible. */ + if ((!err) && (key != NULL) && (pkey != NULL)) { + *key = pkey; + } + /* Dispose of the DER encoding. */ + FreeDer(&der); + + WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0); + + return pkey; +} + +/* Create a private key object from the data in the BIO. + * + * @param [in] bio BIO to read from. + * @param [in, out] key Private key object. Object used if passed in. + * @param [in] cb Password callback. + * @param [in] arg Password callback argument. + * @return A WOLFSSL_EVP_PKEY object on success. + * @return NULL on failure. + */ +WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY** key, wc_pem_password_cb* cb, void* arg) +{ + int err = 0; + WOLFSSL_EVP_PKEY* pkey = NULL; + DerBuffer* der = NULL; + int keyFormat = 0; + + WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey"); + + /* Validate parameters. */ + if (bio == NULL) { + err = 1; + } + + /* Read the PEM private key from the BIO and convert to DER. */ + if ((!err) && (pem_read_bio_key(bio, cb, arg, PRIVATEKEY_TYPE, &keyFormat, + &der) < 0)) { + err = 1; + } + + if (!err) { + const unsigned char* ptr = der->buffer; + int type = -1; + + /* Set key type based on format returned. */ + switch (keyFormat) { + /* No key format set - default to RSA. */ + case 0: + case RSAk: + type = EVP_PKEY_RSA; + break; + case DSAk: + type = EVP_PKEY_DSA; + break; + case ECDSAk: + type = EVP_PKEY_EC; + break; + case DHk: + type = EVP_PKEY_DH; + break; + default: + break; + } + + /* Use key passed in if set. */ + if ((key != NULL) && (*key != NULL)) { + pkey = *key; + } + + /* Convert DER data to a private key object. */ + if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) { + WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); + pkey = NULL; + err = 1; + } + } + + /* Return the key if possible. */ + if ((!err) && (key != NULL) && (pkey != NULL)) { + *key = pkey; + } + /* Dispose of the DER encoding. */ + FreeDer(&der); + + WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", err); + + return pkey; +} +#endif /* !NO_BIO */ + +#if !defined(NO_FILESYSTEM) +/* Create a private key object from the data in a file. + * + * @param [in] fp File pointer. + * @param [in, out] key Public key object. Object used if passed in. + * @param [in] cb Password callback. + * @param [in] arg Password callback argument. + * @return A WOLFSSL_EVP_PKEY object on success. + * @return NULL on failure. + */ +WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key, + wc_pem_password_cb *cb, void *arg) +{ + int err = 0; + WOLFSSL_EVP_PKEY* pkey = NULL; + DerBuffer* der = NULL; + + WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY"); + + /* Validate parameters. */ + if (fp == XBADFILE) { + err = 1; + } + + /* Read the PEM public key from the file and convert to DER. */ + if ((!err) && ((pem_read_file_key(fp, cb, arg, PUBLICKEY_TYPE, NULL, + &der) < 0) || (der == NULL))) { + err = 1; + } + if (!err) { + const unsigned char* ptr = der->buffer; + + /* Use key passed in if set. */ + if ((key != NULL) && (*key != NULL)) { + pkey = *key; + } + + /* Convert DER data to a public key object. */ + if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) { + WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); + pkey = NULL; + err = 1; + } + } + + /* Return the key if possible. */ + if ((!err) && (key != NULL) && (pkey != NULL)) { + *key = pkey; + } + /* Dispose of the DER encoding. */ + FreeDer(&der); + + WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0); + + return pkey; +} + +#ifndef NO_CERTS +/* Create a private key object from the data in a file. + * + * @param [in] fp File pointer. + * @param [in, out] key Private key object. Object used if passed in. + * @param [in] cb Password callback. + * @param [in] arg Password callback argument. + * @return A WOLFSSL_EVP_PKEY object on success. + * @return NULL on failure. + */ +WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key, + wc_pem_password_cb *cb, void *arg) +{ + int err = 0; + WOLFSSL_EVP_PKEY* pkey = NULL; + DerBuffer* der = NULL; + int keyFormat = 0; + + WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey"); + + /* Validate parameters. */ + if (fp == XBADFILE) { + err = 1; + } + + /* Read the PEM private key from the file and convert to DER. */ + if ((!err) && (pem_read_file_key(fp, cb, arg, PRIVATEKEY_TYPE, &keyFormat, + &der)) < 0) { + err = 1; + } + + if (!err) { + const unsigned char* ptr = der->buffer; + int type = -1; + + /* Set key type based on format returned. */ + switch (keyFormat) { + /* No key format set - default to RSA. */ + case 0: + case RSAk: + type = EVP_PKEY_RSA; + break; + case DSAk: + type = EVP_PKEY_DSA; + break; + case ECDSAk: + type = EVP_PKEY_EC; + break; + case DHk: + type = EVP_PKEY_DH; + break; + default: + break; + } + + /* Use key passed in if set. */ + if ((key != NULL) && (*key != NULL)) { + pkey = *key; + } + + /* Convert DER data to a private key object. */ + if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) { + WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); + pkey = NULL; + err = 1; + } + } + + /* Return the key if possible. */ + if ((!err) && (key != NULL) && (pkey != NULL)) { + *key = pkey; + } + /* Dispose of the DER encoding. */ + FreeDer(&der); + + WOLFSSL_LEAVE("wolfSSL_PEM_read_PrivateKey", 0); + + return pkey; +} +#endif /* !NO_CERTS */ +#endif /* !NO_FILESYSTEM */ + +#ifndef NO_CERTS + +#if !defined(NO_BIO) || !defined(NO_FILESYSTEM) +#define PEM_BEGIN "-----BEGIN " +#define PEM_BEGIN_SZ 11 +#define PEM_END "-----END " +#define PEM_END_SZ 9 +#define PEM_HDR_FIN "-----" +#define PEM_HDR_FIN_SZ 5 +#define PEM_HDR_FIN_EOL_NEWLINE "-----\n" +#define PEM_HDR_FIN_EOL_NULL_TERM "-----\0" +#define PEM_HDR_FIN_EOL_SZ 6 + +/* Find strings and return middle offsets. + * + * Find first string in pem as a prefix and then locate second string as a + * postfix. + * len returning with 0 indicates not found. + * + * @param [in] pem PEM data. + * @param [in] pemLen Length of PEM data. + * @param [in] idx Current index. + * @param [in] prefix First string to find. + * @param [in] postfix Second string to find after first. + * @param [out] start Start index of data between strings. + * @param [out] len Length of data between strings. + */ +static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix, + const char* postfix, int* start, int* len) +{ + int prefixLen = (int)XSTRLEN(prefix); + int postfixLen = (int)XSTRLEN(postfix); + + *start = *len = 0; + /* Find prefix part. */ + for (; idx < pemLen - prefixLen; idx++) { + if ((pem[idx] == prefix[0]) && + (XMEMCMP(pem + idx, prefix, prefixLen) == 0)) { + idx += prefixLen; + *start = idx; + break; + } + } + /* Find postfix part. */ + for (; idx < pemLen - postfixLen; idx++) { + if ((pem[idx] == postfix[0]) && + (XMEMCMP(pem + idx, postfix, postfixLen) == 0)) { + *len = idx - *start; + break; + } + } +} + +/* Parse out content type name, any encryption headers and DER encoding. + * + * @param [in] pem PEM data. + * @param [in] pemLen Length of PEM data. + * @param [out] name Name of content type. + * @param [out] header Encryption headers. + * @param [out] data DER encoding from PEM. + * @param [out] len Length of DER data. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return ASN_NO_PEM_HEADER when no header found or different names found. + */ +static int pem_read_data(char* pem, int pemLen, char **name, char **header, + unsigned char **data, long *len) +{ + int ret = 0; + int start; + int nameLen; + int startHdr = 0; + int hdrLen = 0; + int startEnd = 0; + int endLen; + + *name = NULL; + *header = NULL; + + /* Find header. */ + pem_find_pattern(pem, pemLen, 0, PEM_BEGIN, PEM_HDR_FIN, &start, &nameLen); + /* Allocate memory for header name. */ + *name = (char*)XMALLOC(nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (*name == NULL) { + ret = MEMORY_E; + } + if (ret == 0) { + /* Put in header name. */ + (*name)[nameLen] = '\0'; + if (nameLen == 0) { + ret = ASN_NO_PEM_HEADER; + } + else { + XMEMCPY(*name, pem + start, nameLen); + } + } + if (ret == 0) { + /* Find encryption headers after header. */ + start += nameLen + PEM_HDR_FIN_SZ; + pem_find_pattern(pem, pemLen, start, "\n", "\n\n", &startHdr, &hdrLen); + if (hdrLen > 0) { + /* Include first of two '\n' characters. */ + hdrLen++; + } + /* Allocate memory for encryption header string. */ + *header = (char*)XMALLOC(hdrLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (*header == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + /* Put in encryption header string. */ + (*header)[hdrLen] = '\0'; + if (hdrLen > 0) { + XMEMCPY(*header, pem + startHdr, hdrLen); + start = startHdr + hdrLen + 1; + } + + /* Find footer. */ + pem_find_pattern(pem, pemLen, start, PEM_END, PEM_HDR_FIN, &startEnd, + &endLen); + /* Validate header name and footer name are the same. */ + if ((endLen != nameLen) || + (XMEMCMP(*name, pem + startEnd, nameLen) != 0)) { + ret = ASN_NO_PEM_HEADER; + } + } + if (ret == 0) { + unsigned char* der = (unsigned char*)pem; + word32 derLen; + + /* Convert PEM body to DER. */ + derLen = (word32)(startEnd - PEM_END_SZ - start); + ret = Base64_Decode(der + start, derLen, der, &derLen); + if (ret == 0) { + /* Return the DER data. */ + *data = der; + *len = derLen; + } + } + + return ret; +} + +/* Encode the DER data in PEM format into a newly allocated buffer. + * + * @param [in] name Header/footer name. + * @param [in] header Encryption header. + * @param [in] data DER data. + * @param [in] len Length of DER data. + * @param [out] pemOut PEM encoded data. + * @param [out] pemOutLen Length of PEM encoded data. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int pem_write_data(const char *name, const char *header, + const unsigned char *data, long len, char** pemOut, word32* pemOutLen) +{ + int ret = 0; + int nameLen; + int headerLen; + char* pem = NULL; + word32 pemLen; + word32 derLen = (word32)len; + byte* p; + + nameLen = (int)XSTRLEN(name); + headerLen = (int)XSTRLEN(header); + + /* DER encode for PEM. */ + pemLen = (derLen + 2) / 3 * 4; + pemLen += (pemLen + 63) / 64; + /* Header */ + pemLen += PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ; + if (headerLen > 0) { + /* Encryption lines plus extra carriage return. */ + pemLen += headerLen + 1; + } + /* Trailer */ + pemLen += PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ; + + pem = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (pem == NULL) { + ret = MEMORY_E; + } + p = (byte*)pem; + + if (ret == 0) { + /* Add header. */ + XMEMCPY(p, PEM_BEGIN, PEM_BEGIN_SZ); + p += PEM_BEGIN_SZ; + XMEMCPY(p, name, nameLen); + p += nameLen; + XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ); + p += PEM_HDR_FIN_EOL_SZ; + + if (headerLen > 0) { + /* Add encryption header. */ + XMEMCPY(p, header, headerLen); + p += headerLen; + /* Blank line after a header and before body. */ + *(p++) = '\n'; + } + + /* Add DER data as PEM. */ + pemLen -= (word32)((size_t)p - (size_t)pem); + ret = Base64_Encode(data, derLen, p, &pemLen); + } + if (ret == 0) { + p += pemLen; + + /* Add trailer. */ + XMEMCPY(p, PEM_END, PEM_END_SZ); + p += PEM_END_SZ; + XMEMCPY(p, name, nameLen); + p += nameLen; + XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ); + p += PEM_HDR_FIN_EOL_SZ; + + /* Return buffer and length of data. */ + *pemOut = pem; + *pemOutLen = (word32)((size_t)p - (size_t)pem); + } + + return ret; +} +#endif /* !NO_BIO || !NO_FILESYSTEM */ + +#ifndef NO_BIO +/* Read PEM encoded data from a BIO. + * + * Reads the entire contents in. + * + * @param [in] bio BIO to read from. + * @param [out] name Name of content type. + * @param [out] header Encryption headers. + * @param [out] data DER encoding from PEM. + * @param [out] len Length of DER data. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header, + unsigned char **data, long *len) +{ + int res = 1; + char* pem = NULL; + int pemLen = 0; + int memAlloced = 1; + + /* Validate parameters. */ + if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL) || + (len == NULL)) { + res = 0; + } + + /* Load all the data from the BIO. */ + if ((res == 1) && (wolfssl_read_bio(bio, &pem, &pemLen, &memAlloced) != + 0)) { + res = 0; + } + if ((res == 1) && (!memAlloced)) { + /* Need to return allocated memory - make sure it is allocated. */ + char* p = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (p == NULL) { + res = 0; + } + else { + /* Copy the data into new buffer. */ + XMEMCPY(p, pem, pemLen); + pem = p; + } + } + + /* Read the PEM data. */ + if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) != + 0)) { + /* Dispose of any allocated memory. */ + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER); + *name = NULL; + *header = NULL; + res = 0; + } + + return res; +} + +/* Encode the DER data in PEM format into a BIO. + * + * @param [in] bio BIO to write to. + * @param [in] name Header/footer name. + * @param [in] header Encryption header. + * @param [in] data DER data. + * @param [in] len Length of DER data. + * @return 0 on failure. + */ +int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name, + const char *header, const unsigned char *data, long len) +{ + int err = 0; + char* pem = NULL; + word32 pemLen = 0; + + /* Validate parameters. */ + if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL)) { + err = BAD_FUNC_ARG; + } + + /* Encode into a buffer. */ + if (!err) { + err = pem_write_data(name, header, data, len, &pem, &pemLen); + } + + /* Write PEM into BIO. */ + if ((!err) && (wolfSSL_BIO_write(bio, pem, (int)pemLen) != (int)pemLen)) { + err = IO_FAILED_E; + } + + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return (!err) ? pemLen : 0; +} +#endif /* !NO_BIO */ + +#if !defined(NO_FILESYSTEM) +/* Read PEM encoded data from a file. + * + * Reads the entire contents in. + * + * @param [in] bio BIO to read from. + * @param [out] name Name of content type. + * @param [out] header Encryption headers. + * @param [out] data DER encoding from PEM. + * @param [out] len Length of DER data. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_read(XFILE fp, char **name, char **header, unsigned char **data, + long *len) +{ + int res = 1; + char* pem = NULL; + int pemLen = 0; + + /* Validate parameters. */ + if ((fp == XBADFILE) || (name == NULL) || (header == NULL) || + (data == NULL) || (len == NULL)) { + res = 0; + } + + /* Load all the data from the file. */ + if ((res == 1) && (wolfssl_read_file(fp, &pem, &pemLen) != 0)) { + res = 0; + } + + /* Read the PEM data. */ + if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) != + 0)) { + /* Dispose of any allocated memory. */ + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER); + *name = NULL; + *header = NULL; + res = 0; + } + + return res; +} + +/* Encode the DER data in PEM format into a file. + * + * @param [in] fp File pointer to write to. + * @param [in] name Header/footer name. + * @param [in] header Encryption header. + * @param [in] data DER data. + * @param [in] len Length of DER data. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header, + const unsigned char *data, long len) +{ + int err = 0; + char* pem = NULL; + word32 pemLen = 0; + + /* Validate parameters. */ + if ((fp == XBADFILE) || (name == NULL) || (header == NULL) || + (data == NULL)) { + err = 1; + } + + /* Encode into a buffer. */ + if ((!err) && (pem_write_data(name, header, data, len, &pem, &pemLen) != + 0)) { + pemLen = 0; + err = 1; + } + + /* Write PEM to a file. */ + if ((!err) && (XFWRITE(pem, 1, pemLen, fp) != pemLen)) { + pemLen = 0; + } + + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return (int)pemLen; +} +#endif + +/* Get EVP cipher info from encryption header string. + * + * @param [in] header Encryption header. + * @param [out] cipher EVP Cipher info. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header, EncryptedInfo* cipher) +{ + int res = 1; + + /* Validate parameters. */ + if ((header == NULL) || (cipher == NULL)) { + res = 0; + } + + if (res == 1) { + XMEMSET(cipher, 0, sizeof(*cipher)); + + if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0) { + res = 0; + } + } + + return res; +} + +/* Apply cipher to DER data. + * + * @param [in] cipher EVP cipher info. + * @param [in, out] data On in, encrypted DER data. + * On out, unencrypted DER data. + * @param [in, out] len On in, length of encrypted DER data. + * On out, length of unencrypted DER data. + * @param [in] cb Password callback. + * @param [in] ctx Context for password callback. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len, + wc_pem_password_cb* cb, void* ctx) +{ + int ret = 1; + char password[NAME_SZ]; + int passwordSz = 0; + + /* Validate parameters. */ + if ((cipher == NULL) || (data == NULL) || (len == NULL) || (cb == NULL)) { + ret = 0; + } + + if (ret == 1) { + /* Get password and length. */ + passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx); + if (passwordSz < 0) { + ret = 0; + } + } + + if (ret == 1) { + /* Decrypt the data using password and MD5. */ + if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password, + passwordSz, WC_MD5) != 0) { + ret = WOLFSSL_FAILURE; + } + } + + if (passwordSz > 0) { + /* Ensure password is erased from memory. */ + ForceZero(password, (word32)passwordSz); + } + + return ret; +} + +#endif /* !NO_CERTS */ +#endif /* OPENSSL_EXTRA */ + +#ifdef OPENSSL_ALL +#if !defined(NO_PWDBASED) && defined(HAVE_PKCS8) + +#if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \ + !defined(NO_STDIO_FILESYSTEM)) +/* Encrypt the key into a buffer using PKCS$8 and a password. + * + * @param [in] pkey Private key to encrypt. + * @param [in] enc EVP cipher. + * @param [in] passwd Password to encrypt with. + * @param [in] passwdSz Number of bytes in password. + * @param [in] key Buffer to hold encrypted key. + * @param [in, out] keySz On in, size of buffer in bytes. + * On out, size of encrypted key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when EVP cipher not supported. + */ +static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, + const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key, + word32* keySz) +{ + int ret; + WC_RNG rng; + + /* Initialize a new random number generator. */ + ret = wc_InitRng(&rng); + if (ret == 0) { + int encAlgId = 0; + + /* Convert EVP cipher to a support encryption id. */ + #ifndef NO_DES3 + if (enc == EVP_DES_CBC) { + encAlgId = DESb; + } + else if (enc == EVP_DES_EDE3_CBC) { + encAlgId = DES3b; + } + else + #endif +#if !defined(NO_AES) && defined(HAVE_AES_CBC) + #ifdef WOLFSSL_AES_128 + if (enc == EVP_AES_128_CBC) { + encAlgId = AES128CBCb; + } + else + #endif + #ifdef WOLFSSL_AES_256 + if (enc == EVP_AES_256_CBC) { + encAlgId = AES256CBCb; + } + else + #endif +#endif + { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Encrypt private into buffer. */ + ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz, + key, keySz, passwd, passwdSz, PKCS5, PBES2, encAlgId, + NULL, 0, WC_PKCS12_ITT_DEFAULT, &rng, NULL); + if (ret > 0) { + *keySz = (word32)ret; + } + } + /* Dispose of random number generator. */ + wc_FreeRng(&rng); + } + + return ret; +} + +/* Encode private key in PKCS#8 format. + * + * @param [in] pkey Private key. + * @param [out] key Buffer to hold encoding. + * @param [in, out] keySz On in, size of buffer in bytes. + * @param On out, size of encoded key in bytes. + * @return 0 on success. + */ +static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) +{ + int ret = 0; + int algId; + const byte* curveOid; + word32 oidSz; + + /* Get the details of the private key. */ +#ifdef HAVE_ECC + if (pkey->type == EVP_PKEY_EC) { + /* ECC private and get curve OID information. */ + algId = ECDSAk; + ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid, + &oidSz); + } + else +#endif + if (pkey->type == EVP_PKEY_RSA) { + /* RSA private has no curve information. */ + algId = RSAk; + curveOid = NULL; + oidSz = 0; + } + else { + ret = NOT_COMPILED_IN; + } + + if (ret >= 0) { + /* Encode private key in PKCS#8 format. */ + ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr, + pkey->pkey_sz, algId, curveOid, oidSz); + } + + return ret; +} + +/* Write PEM encoded, PKCS#8 formatted private key to BIO. + * + * @param [out] pem Buffer holding PEM encoding. + * @param [out] pemSz Size of data in buffer in bytes. + * @param [in] pkey Private key to write. + * @param [in] enc Encryption information to use. May be NULL. + * @param [in] passwd Password to use when encrypting. May be NULL. + * @param [in] passwdSz Size of password in bytes. + * @param [in] cb Password callback. Used when passwd is NULL. May be + * NULL. + * @param [in] ctx Context for password callback. + * @return Length of PEM encoding on success. + * @return 0 on failure. + */ +static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz, + WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, + int passwdSz, wc_pem_password_cb* cb, void* ctx) +{ + int res = 1; + int ret = 0; + char password[NAME_SZ]; + byte* key = NULL; + word32 keySz; + int type = PKCS8_PRIVATEKEY_TYPE; + + /* Validate parameters. */ + if (pkey == NULL) { + res = 0; + } + + if (res == 1) { + /* Guestimate key size and PEM size. */ + if (pem_pkcs8_encode(pkey, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { + res = 0; + } + } + if (res == 1) { + if (enc != NULL) { + /* Add on enough for extra DER data when encrypting. */ + keySz += 128; + } + /* PEM encoding size from DER size. */ + *pemSz = (int)(keySz + 2) / 3 * 4; + *pemSz += (*pemSz + 63) / 64; + /* Header and footer. */ + if (enc != NULL) { + /* Name is: 'ENCRYPTED PRIVATE KEY'. */ + *pemSz += 74; + } + else { + /* Name is: 'PRIVATE KEY'. */ + *pemSz += 54; + } + + /* Allocate enough memory to hold PEM encoded encrypted key. */ + *pem = (byte*)XMALLOC((size_t)*pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (*pem == NULL) { + res = 0; + } + else { + /* Use end of PEM buffer for key data. */ + key = *pem + *pemSz - keySz; + } + } + + if ((res == 1) && (enc != NULL)) { + /* Set type for PEM. */ + type = PKCS8_ENC_PRIVATEKEY_TYPE; + + if (passwd == NULL) { + /* Get the password by using callback. */ + passwdSz = cb(password, sizeof(password), 1, ctx); + if (passwdSz < 0) { + res = 0; + } + passwd = password; + } + + if (res == 1) { + /* Encrypt the private key. */ + ret = pem_pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz); + if (ret <= 0) { + res = 0; + } + } + + /* Zeroize the password from memory. */ + if ((password == passwd) && (passwdSz > 0)) { + ForceZero(password, (word32)passwdSz); + } + } + else if ((res == 1) && (enc == NULL)) { + /* Set type for PEM. */ + type = PKCS8_PRIVATEKEY_TYPE; + + /* Encode private key in PKCS#8 format. */ + ret = pem_pkcs8_encode(pkey, key, &keySz); + if (ret < 0) { + res = 0; + } + } + + if (res == 1) { + /* Encode PKCS#8 formatted key to PEM. */ + ret = wc_DerToPemEx(key, keySz, *pem, (word32)*pemSz, NULL, type); + if (ret < 0) { + res = 0; + } + else { + *pemSz = ret; + } + } + + /* Return appropriate return code. */ + return (res == 0) ? 0 : ret; + +} +#endif /* !NO_BIO || (!NO_FILESYSTEM && !NO_STDIO_FILESYSTEM) */ + +#ifndef NO_BIO +/* Write PEM encoded, PKCS#8 formatted private key to BIO. + * + * TODO: OpenSSL returns 1 and 0 only. + * + * @param [in] bio BIO to write to. + * @param [in] pkey Private key to write. + * @param [in] enc Encryption information to use. May be NULL. + * @param [in] passwd Password to use when encrypting. May be NULL. + * @param [in] passwdSz Size of password in bytes. + * @param [in] cb Password callback. Used when passwd is NULL. May be + * NULL. + * @param [in] ctx Context for password callback. + * @return Length of PEM encoding on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, + int passwdSz, wc_pem_password_cb* cb, void* ctx) +{ + byte* pem = NULL; + int pemSz = 0; + int res = 1; + + /* Validate parameters. */ + if (bio == NULL) { + res = 0; + } + if (res == 1) { + /* Write private key to memory. */ + res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd, + passwdSz, cb, ctx); + } + + /* Write encoded key to BIO. */ + if ((res >= 1) && (wolfSSL_BIO_write(bio, pem, pemSz) != pemSz)) { + res = 0; + } + + /* Dispose of dynamically allocated memory (pem and key). */ + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return res; +} +#endif /* !NO_BIO */ + +#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) +/* Write PEM encoded, PKCS#8 formatted private key to BIO. + * + * TODO: OpenSSL returns 1 and 0 only. + * + * @param [in] f File pointer. + * @param [in] pkey Private key to write. + * @param [in] enc Encryption information to use. May be NULL. + * @param [in] passwd Password to use when encrypting. May be NULL. + * @param [in] passwdSz Size of password in bytes. + * @param [in] cb Password callback. Used when passwd is NULL. May be + * NULL. + * @param [in] ctx Context for password callback. + * @return Length of PEM encoding on success. + * @return 0 on failure. + */ +int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey, + const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, + wc_pem_password_cb* cb, void* ctx) +{ + byte* pem = NULL; + int pemSz = 0; + int res = 1; + + /* Validate parameters. */ + if (f == XBADFILE) { + res = 0; + } + if (res == 1) { + /* Write private key to memory. */ + res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd, + passwdSz, cb, ctx); + } + + /* Write encoded key to file. */ + if ((res >= 1) && (XFWRITE(pem, 1, (size_t)pemSz, f) != (size_t)pemSz)) { + res = 0; + } + + /* Dispose of dynamically allocated memory (pem and key). */ + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return res; +} +#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */ + +#endif /* !NO_PWDBASED && HAVE_PKCS8 */ +#endif /* OPENSSL_ALL */ + +/******************************************************************************* + * END OF GENERIC PUBLIC KEY PEM APIs ******************************************************************************/ #endif /* !WOLFSSL_PK_INCLUDED */ diff --git a/src/src/quic.c b/src/src/quic.c index 66f866a..117bb43 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -82,7 +82,7 @@ static QuicRecord *quic_record_make(WOLFSSL *ssl, qr->capacity = qr->len = (word32)len; } else { - qr->capacity = qr->len = qr_length(data, len); + qr->capacity = qr->len = (word32) qr_length(data, len); if (qr->capacity > WOLFSSL_QUIC_MAX_RECORD_CAPACITY) { WOLFSSL_MSG("QUIC length read larger than expected"); quic_record_free(ssl, qr); @@ -123,17 +123,17 @@ static int quic_record_append(WOLFSSL *ssl, QuicRecord *qr, const uint8_t *data, missing = 4 - qr->end; if (len < missing) { XMEMCPY(qr->data + qr->end, data, len); - qr->end += len; + qr->end += (word32)len; consumed = len; goto cleanup; /* len consumed, but qr->len still unknown */ } XMEMCPY(qr->data + qr->end, data, missing); - qr->end += missing; + qr->end += (word32)missing; len -= missing; data += missing; consumed = missing; - qr->len = qr_length(qr->data, qr->end); + qr->len = (word32)qr_length(qr->data, qr->end); /* sanity check on length read from wire before use */ if (qr->len > WOLFSSL_QUIC_MAX_RECORD_CAPACITY) { @@ -163,7 +163,7 @@ static int quic_record_append(WOLFSSL *ssl, QuicRecord *qr, const uint8_t *data, len = missing; } XMEMCPY(qr->data + qr->end, data, len); - qr->end += len; + qr->end += (word32)len; consumed += len; cleanup: @@ -172,7 +172,7 @@ static int quic_record_append(WOLFSSL *ssl, QuicRecord *qr, const uint8_t *data, } -static word32 add_rec_header(byte* output, word32 length, int type) +static word32 add_rec_header(byte* output, word32 length, byte type) { RecordLayerHeader* rl; @@ -188,15 +188,21 @@ static word32 add_rec_header(byte* output, word32 length, int type) return RECORD_HEADER_SZ; } -static word32 quic_record_transfer(QuicRecord* qr, byte* buf, word32 sz) +static sword32 quic_record_transfer(QuicRecord* qr, byte* buf, word32 sz) { word32 len = qr->end - qr->start; word32 offset = 0; - word16 rlen; + word32 rlen; if (len <= 0) { return 0; } + + /* We check if the buf is at least RECORD_HEADER_SZ */ + if (sz < RECORD_HEADER_SZ) { + return -1; + } + if (qr->rec_hdr_remain == 0) { /* start a new TLS record */ rlen = (qr->len <= (word32)MAX_RECORD_SIZE) ? @@ -218,7 +224,7 @@ static word32 quic_record_transfer(QuicRecord* qr, byte* buf, word32 sz) qr->start += len; qr->rec_hdr_remain -= len; } - return len + offset; + return (sword32)(len + offset); } @@ -236,7 +242,7 @@ const QuicTransportParam* QuicTransportParam_new(const uint8_t* data, return NULL; } XMEMCPY((uint8_t*)tp->data, data, len); - tp->len = len; + tp->len = (word16)len; return tp; } @@ -766,7 +772,7 @@ int wolfSSL_provide_quic_data(WOLFSSL* ssl, WOLFSSL_ENCRYPTION_LEVEL level, /* Called internally when SSL wants a certain amount of input. */ int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz) { - word32 n = 0; + sword32 n = 0; int transferred = 0; WOLFSSL_ENTER("wolfSSL_quic_receive"); @@ -774,6 +780,11 @@ int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz) n = 0; if (ssl->quic.input_head) { n = quic_record_transfer(ssl->quic.input_head, buf, sz); + + /* record too small to be fit into a RecordLayerHeader struct. */ + if (n == -1) { + return -1; + } if (quic_record_done(ssl->quic.input_head)) { QuicRecord* qr = ssl->quic.input_head; ssl->quic.input_head = qr->next; @@ -791,9 +802,9 @@ int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz) ssl->error = transferred = WANT_READ; goto cleanup; } - sz -= n; + sz -= (word32)n; buf += n; - transferred += n; + transferred += (int)n; } cleanup: WOLFSSL_LEAVE("wolfSSL_quic_receive", transferred); @@ -836,8 +847,8 @@ static int wolfSSL_quic_send_internal(WOLFSSL* ssl) goto cleanup; } output += len; - length -= len; - ssl->quic.output_rec_remain -= len; + length -= (word32)len; + ssl->quic.output_rec_remain -= (word32)len; } else { /* at start of a TLS Record */ @@ -990,11 +1001,13 @@ const WOLFSSL_EVP_CIPHER* wolfSSL_quic_get_aead(WOLFSSL* ssl) evp_cipher = wolfSSL_EVP_chacha20_poly1305(); break; #endif -#if defined(WOLFSSL_AES_COUNTER) && defined(WOLFSSL_AES_128) +#if !defined(NO_AES) && defined(HAVE_AESCCM) && defined(WOLFSSL_AES_128) case TLS_AES_128_CCM_SHA256: - FALL_THROUGH; + evp_cipher = wolfSSL_EVP_aes_128_ccm(); + break; case TLS_AES_128_CCM_8_SHA256: - evp_cipher = wolfSSL_EVP_aes_128_ctr(); + WOLFSSL_MSG("wolfSSL_quic_get_aead: no CCM-8 support in EVP layer"); + evp_cipher = NULL; break; #endif @@ -1011,7 +1024,8 @@ const WOLFSSL_EVP_CIPHER* wolfSSL_quic_get_aead(WOLFSSL* ssl) return evp_cipher; } -static int evp_cipher_eq(const WOLFSSL_EVP_CIPHER* c1, +/* currently only used if HAVE_CHACHA && HAVE_POLY1305. */ +WC_MAYBE_UNUSED static int evp_cipher_eq(const WOLFSSL_EVP_CIPHER* c1, const WOLFSSL_EVP_CIPHER* c2) { /* We could check on nid equality, but we seem to have singulars */ @@ -1034,27 +1048,40 @@ const WOLFSSL_EVP_CIPHER* wolfSSL_quic_get_hp(WOLFSSL* ssl) } switch (cipher->cipherSuite) { -#if !defined(NO_AES) && defined(HAVE_AESGCM) +#if !defined(NO_AES) && defined(HAVE_AESGCM) && defined(WOLFSSL_AES_COUNTER) + /* This has to be CTR even though the spec says that ECB is used for + * mask generation. ngtcp2_crypto_hp_mask uses a hack where they pass + * in the "ECB" input as the IV for the CTR cipher and then the input + * is just a cleared buffer. They do this so that the EVP + * init-update-final cycle can be used without the padding that is added + * for EVP_aes_(128|256)_ecb. */ +#if defined(WOLFSSL_AES_128) case TLS_AES_128_GCM_SHA256: evp_cipher = wolfSSL_EVP_aes_128_ctr(); break; +#endif +#if defined(WOLFSSL_AES_256) case TLS_AES_256_GCM_SHA384: evp_cipher = wolfSSL_EVP_aes_256_ctr(); break; #endif +#endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) case TLS_CHACHA20_POLY1305_SHA256: evp_cipher = wolfSSL_EVP_chacha20(); break; #endif -#if defined(WOLFSSL_AES_COUNTER) && defined(WOLFSSL_AES_128) +#if !defined(NO_AES) && defined(HAVE_AESCCM) && defined(WOLFSSL_AES_128) && \ + defined(WOLFSSL_AES_COUNTER) + /* This has to be CTR. See comment above. */ case TLS_AES_128_CCM_SHA256: - FALL_THROUGH; - case TLS_AES_128_CCM_8_SHA256: evp_cipher = wolfSSL_EVP_aes_128_ctr(); break; + case TLS_AES_128_CCM_8_SHA256: + WOLFSSL_MSG("wolfSSL_quic_get_hp: no CCM-8 support in EVP layer"); + evp_cipher = NULL; + break; #endif - default: evp_cipher = NULL; break; @@ -1072,8 +1099,7 @@ size_t wolfSSL_quic_get_aead_tag_len(const WOLFSSL_EVP_CIPHER* aead_cipher) { size_t ret; #ifdef WOLFSSL_SMALL_STACK - WOLFSSL_EVP_CIPHER_CTX *ctx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC( - sizeof(*ctx), NULL, DYNAMIC_TYPE_TMP_BUFFER); + WOLFSSL_EVP_CIPHER_CTX *ctx = wolfSSL_EVP_CIPHER_CTX_new(); if (ctx == NULL) return 0; #else @@ -1083,7 +1109,7 @@ size_t wolfSSL_quic_get_aead_tag_len(const WOLFSSL_EVP_CIPHER* aead_cipher) XMEMSET(ctx, 0, sizeof(*ctx)); if (wolfSSL_EVP_CipherInit(ctx, aead_cipher, NULL, NULL, 0) == WOLFSSL_SUCCESS) { - ret = ctx->authTagSz; + ret = (size_t)ctx->authTagSz; } else { ret = 0; } @@ -1098,30 +1124,12 @@ size_t wolfSSL_quic_get_aead_tag_len(const WOLFSSL_EVP_CIPHER* aead_cipher) int wolfSSL_quic_aead_is_gcm(const WOLFSSL_EVP_CIPHER* aead_cipher) { -#if !defined(NO_AES) && defined(HAVE_AESGCM) - if (evp_cipher_eq(aead_cipher, wolfSSL_EVP_aes_128_gcm()) -#ifdef WOLFSSL_AES_256 - || evp_cipher_eq(aead_cipher, wolfSSL_EVP_aes_256_gcm()) -#endif - ) { - return 1; - } -#else - (void)aead_cipher; -#endif - return 0; + return WOLFSSL_EVP_CIPHER_mode(aead_cipher) == WOLFSSL_EVP_CIPH_GCM_MODE; } int wolfSSL_quic_aead_is_ccm(const WOLFSSL_EVP_CIPHER* aead_cipher) { -#if defined(WOLFSSL_AES_COUNTER) && defined(WOLFSSL_AES_128) - if (evp_cipher_eq(aead_cipher, wolfSSL_EVP_aes_128_ctr())) { - return 1; - } -#else - (void)aead_cipher; -#endif - return 0; + return WOLFSSL_EVP_CIPHER_mode(aead_cipher) == WOLFSSL_EVP_CIPH_CCM_MODE; } int wolfSSL_quic_aead_is_chacha20(const WOLFSSL_EVP_CIPHER* aead_cipher) @@ -1358,7 +1366,7 @@ int wolfSSL_quic_aead_decrypt(uint8_t* dest, WOLFSSL_EVP_CIPHER_CTX* ctx, return WOLFSSL_FAILURE; } - enclen -= ctx->authTagSz; + enclen -= (size_t)ctx->authTagSz; tag = enc + enclen; if (wolfSSL_EVP_CipherInit(ctx, NULL, NULL, iv, 0) != WOLFSSL_SUCCESS diff --git a/src/src/sniffer.c b/src/src/sniffer.c index d5fc5c1..94b2a9f 100644 --- a/src/src/sniffer.c +++ b/src/src/sniffer.c @@ -2481,7 +2481,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, args = (SetupKeysArgs*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_sk; @@ -3089,7 +3089,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, #endif /* HAVE_CURVE448 */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Handle async pending response */ ret = wolfSSL_AsyncPush(ssl, asyncDev); break; @@ -3228,7 +3228,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, exit_sk: /* Handle async pending response */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -3897,7 +3897,8 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, #endif #ifdef WOLFSSL_ASYNC_CRYPT - if (session->sslServer->error != WC_PENDING_E && session->pendSeq == 0) + if (session->sslServer->error != WC_NO_ERR_TRACE(WC_PENDING_E) && + session->pendSeq == 0) #endif { /* hash server_hello */ @@ -3931,7 +3932,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, session, error, &session->cliKs); if (ret != 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -4578,7 +4579,8 @@ static int DoHandShake(const byte* input, int* sslBytes, #ifdef WOLFSSL_TLS13 if (type != client_hello && type != server_hello #ifdef WOLFSSL_ASYNC_CRYPT - && session->sslServer->error != WC_PENDING_E && session->pendSeq == 0 + && session->sslServer->error != WC_NO_ERR_TRACE(WC_PENDING_E) + && session->pendSeq == 0 #endif ) { /* For resumption the hash is before / after client_hello PSK binder */ @@ -4696,7 +4698,7 @@ static int DoHandShake(const byte* input, int* sslBytes, if (ret == 0) { ret = ProcessClientKeyExchange(input, sslBytes, session, error); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif if (ret != 0) { @@ -4763,7 +4765,7 @@ static int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev); } #endif @@ -4781,7 +4783,7 @@ static int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, #endif ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } #endif @@ -4826,7 +4828,7 @@ static int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->decrypt.additional, AEAD_AUTH_DATA_SZ, NULL, 0)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } #endif @@ -4884,9 +4886,9 @@ static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input, #ifdef WOLFSSL_ASYNC_CRYPT if (ssl->decrypt.state != CIPHER_STATE_BEGIN) { ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* check for still pending */ - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; ssl->error = 0; /* clear async */ @@ -4942,7 +4944,7 @@ static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input, #ifdef WOLFSSL_ASYNC_CRYPT /* If pending, return now */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -4994,7 +4996,7 @@ static const byte* DecryptMessage(WOLFSSL* ssl, const byte* input, word32 sz, } #ifdef WOLFSSL_ASYNC_CRYPT /* for async the symmetric operations are blocking */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { do { ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW); } while (ret == 0); @@ -5254,7 +5256,7 @@ static int DoOldHello(SnifferSession* session, const byte* sslFrame, ret = ProcessOldClientHello(session->sslServer, input, &idx, *sslBytes, (word16)*rhSize); - if (ret < 0 && ret != MATCH_SUITE_ERROR) { + if (ret < 0 && ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) { SetError(BAD_OLD_CLIENT_STR, error, session, FATAL_ERROR_STATE); return -1; } @@ -5679,7 +5681,7 @@ static int AdjustSequence(TcpInfo* tcpInfo, SnifferSession* session, if (real + *sslBytes > *expected) { #ifdef WOLFSSL_ASYNC_CRYPT - if (session->sslServer->error != WC_PENDING_E && + if (session->sslServer->error != WC_NO_ERR_TRACE(WC_PENDING_E) && session->pendSeq != tcpInfo->sequence) #endif { @@ -5735,7 +5737,7 @@ static int AdjustSequence(TcpInfo* tcpInfo, SnifferSession* session, * already been ack'd during handshake */ if ( #ifdef WOLFSSL_ASYNC_CRYPT - session->sslServer->error != WC_PENDING_E && + session->sslServer->error != WC_NO_ERR_TRACE(WC_PENDING_E) && session->pendSeq != tcpInfo->sequence && #endif FindPrevAck(session, real)) { @@ -6039,7 +6041,7 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, #ifdef WOLFSSL_ASYNC_CRYPT /* if this is a pending async packet do not "grow" on partial (we already did) */ if (session->pendSeq == tcpInfo->sequence) { - if (session->sslServer->error == WC_PENDING_E) { + if (session->sslServer->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { return 0; /* don't check pre-record again */ } /* if record check already done then restore, otherwise process normal */ @@ -6371,7 +6373,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, Trace(GOT_HANDSHAKE_STR); ret = DoHandShake(sslFrame, &sslBytes, session, error, rhSize); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif if (ret != 0 || sslBytes > startIdx) { @@ -6655,7 +6657,7 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) return WOLFSSL_SNIFFER_FATAL_ERROR; #ifdef WOLFSSL_ASYNC_CRYPT - else if (ret == WC_PENDING_E) return WC_PENDING_E; + else if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return WC_PENDING_E; #endif else if (ret == -1) return WOLFSSL_SNIFFER_ERROR; else if (ret == 1) { @@ -6706,7 +6708,8 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, #ifdef WOLFSSL_ASYNC_CRYPT /* make sure this server was polled */ - if (asyncOkay && session->sslServer->error == WC_PENDING_E && + if (asyncOkay && + session->sslServer->error == WC_NO_ERR_TRACE(WC_PENDING_E) && !session->flags.wasPolled) { return WC_PENDING_E; } @@ -6714,7 +6717,7 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, #ifdef WOLFSSL_SNIFFER_STATS #ifdef WOLFSSL_ASYNC_CRYPT - if (session->sslServer->error != WC_PENDING_E) + if (session->sslServer->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { if (sslBytes > 0) { @@ -6736,7 +6739,7 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, session->sslServer->error = ret; #ifdef WOLFSSL_ASYNC_CRYPT /* capture the seq pending for this session */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { session->flags.wasPolled = 0; session->pendSeq = tcpInfo.sequence; if (!asyncOkay || CryptoDeviceId == INVALID_DEVID) { @@ -6751,7 +6754,7 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, else { session->pendSeq = 0; } - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #else (void)asyncOkay; #endif diff --git a/src/src/ssl.c b/src/src/ssl.c index ea66e42..9ba891d 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -54,7 +54,8 @@ #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \ && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \ && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) - #error "No cipher suites defined because DH disabled, ECC disabled, and no static suites defined. Please see top of README" + #error "No cipher suites defined because DH disabled, ECC disabled, " + "and no static suites defined. Please see top of README" #endif #ifdef WOLFSSL_CERT_GEN /* need access to Cert struct for creating certificate */ @@ -115,14 +116,15 @@ #include #include #include - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) #include #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) #include #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ + #if defined(HAVE_SPHINCS) + #include + #endif /* HAVE_SPHINCS */ #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) #ifdef HAVE_OCSP #include @@ -137,12 +139,6 @@ && !defined(WC_NO_RNG) #include #endif - #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) - #include - #endif - #if defined(OPENSSL_ALL) && defined(HAVE_PKCS7) - #include - #endif /* OPENSSL_ALL && HAVE_PKCS7 */ #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) @@ -160,25 +156,6 @@ #endif #endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */ -#ifdef WOLFSSL_SYS_CA_CERTS - -#ifdef _WIN32 - #include - #include - - /* mingw gcc does not support pragma comment, and the - * linking with crypt32 is handled in configure.ac */ - #if !defined(__MINGW32__) && !defined(__MINGW64__) - #pragma comment(lib, "crypt32") - #endif -#endif - -#if defined(__APPLE__) && defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) -#include -#endif - -#endif /* WOLFSSL_SYS_CA_CERTS */ - /* * OPENSSL_COMPATIBLE_DEFAULTS: * Enable default behaviour that is compatible with OpenSSL. For example @@ -215,6 +192,9 @@ #ifndef WOLFCRYPT_ONLY #define WOLFSSL_SSL_CERTMAN_INCLUDED #include "src/ssl_certman.c" + +#define WOLFSSL_SSL_SESS_INCLUDED +#include "src/ssl_sess.c" #endif #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ @@ -307,9 +287,10 @@ int wc_OBJ_sn2nid(const char *sn) #define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */ static WC_RNG globalRNG; -static int initGlobalRNG = 0; +static volatile int initGlobalRNG = 0; -static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex); +static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex); #ifndef WOLFSSL_MUTEX_INITIALIZER static int globalRNGMutex_valid = 0; #endif @@ -408,7 +389,8 @@ WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local) * OPENSSL_EXTRA where RAND callbacks are not used */ #ifndef WOLFSSL_NO_OPENSSL_RAND_CB static const WOLFSSL_RAND_METHOD* gRandMethods = NULL; - static wolfSSL_Mutex gRandMethodMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex); + static wolfSSL_Mutex gRandMethodMutex + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex); #ifndef WOLFSSL_MUTEX_INITIALIZER static int gRandMethodsInit = 0; #endif @@ -428,47 +410,6 @@ WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local) #include -#if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) -const WOLF_EC_NIST_NAME kNistCurves[] = { - {XSTR_SIZEOF("P-192"), "P-192", NID_X9_62_prime192v1}, - {XSTR_SIZEOF("P-256"), "P-256", NID_X9_62_prime256v1}, - {XSTR_SIZEOF("P-112"), "P-112", NID_secp112r1}, - {XSTR_SIZEOF("P-112-2"), "P-112-2", NID_secp112r2}, - {XSTR_SIZEOF("P-128"), "P-128", NID_secp128r1}, - {XSTR_SIZEOF("P-128-2"), "P-128-2", NID_secp128r2}, - {XSTR_SIZEOF("P-160"), "P-160", NID_secp160r1}, - {XSTR_SIZEOF("P-160-2"), "P-160-2", NID_secp160r2}, - {XSTR_SIZEOF("P-224"), "P-224", NID_secp224r1}, - {XSTR_SIZEOF("P-384"), "P-384", NID_secp384r1}, - {XSTR_SIZEOF("P-521"), "P-521", NID_secp521r1}, - {XSTR_SIZEOF("K-160"), "K-160", NID_secp160k1}, - {XSTR_SIZEOF("K-192"), "K-192", NID_secp192k1}, - {XSTR_SIZEOF("K-224"), "K-224", NID_secp224k1}, - {XSTR_SIZEOF("K-256"), "K-256", NID_secp256k1}, - {XSTR_SIZEOF("B-160"), "B-160", NID_brainpoolP160r1}, - {XSTR_SIZEOF("B-192"), "B-192", NID_brainpoolP192r1}, - {XSTR_SIZEOF("B-224"), "B-224", NID_brainpoolP224r1}, - {XSTR_SIZEOF("B-256"), "B-256", NID_brainpoolP256r1}, - {XSTR_SIZEOF("B-320"), "B-320", NID_brainpoolP320r1}, - {XSTR_SIZEOF("B-384"), "B-384", NID_brainpoolP384r1}, - {XSTR_SIZEOF("B-512"), "B-512", NID_brainpoolP512r1}, -#ifdef HAVE_PQC - {XSTR_SIZEOF("KYBER_LEVEL1"), "KYBER_LEVEL1", WOLFSSL_KYBER_LEVEL1}, - {XSTR_SIZEOF("KYBER_LEVEL3"), "KYBER_LEVEL3", WOLFSSL_KYBER_LEVEL3}, - {XSTR_SIZEOF("KYBER_LEVEL5"), "KYBER_LEVEL5", WOLFSSL_KYBER_LEVEL5}, -#ifdef HAVE_LIBOQS - {XSTR_SIZEOF("P256_KYBER_LEVEL1"), "P256_KYBER_LEVEL1", WOLFSSL_P256_KYBER_LEVEL1}, - {XSTR_SIZEOF("P384_KYBER_LEVEL3"), "P384_KYBER_LEVEL3", WOLFSSL_P384_KYBER_LEVEL3}, - {XSTR_SIZEOF("P521_KYBER_LEVEL5"), "P521_KYBER_LEVEL5", WOLFSSL_P521_KYBER_LEVEL5}, -#endif -#endif -#ifdef WOLFSSL_SM2 - {XSTR_SIZEOF("SM2"), "SM2", NID_sm2}, -#endif - {0, NULL, 0}, -}; -#endif - #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) /* create the hpke key and ech config to send to clients */ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, @@ -1037,7 +978,7 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) workingOutputLen = *outputLen - totalLen; /* only error we break on, other 2 we need to keep finding length */ - if (ret == BAD_FUNC_ARG) + if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) return BAD_FUNC_ARG; workingConfig = workingConfig->next; @@ -1067,209 +1008,11 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) #include #endif -#ifdef WOLFSSL_SESSION_EXPORT -/* Used to import a serialized TLS session. - * WARNING: buf contains sensitive information about the state and is best to be - * encrypted before storing if stored. - * - * @param ssl WOLFSSL structure to import the session into - * @param buf serialized session - * @param sz size of buffer 'buf' - * @return the number of bytes read from buffer 'buf' - */ -int wolfSSL_tls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz) -{ - if (ssl == NULL || buf == NULL) { - return BAD_FUNC_ARG; - } - return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS); -} - - -/* Used to export a serialized TLS session. - * WARNING: buf contains sensitive information about the state and is best to be - * encrypted before storing if stored. - * - * @param ssl WOLFSSL structure to export the session from - * @param buf output of serialized session - * @param sz size in bytes set in 'buf' - * @return the number of bytes written into buffer 'buf' - */ -int wolfSSL_tls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz) -{ - if (ssl == NULL || sz == NULL) { - return BAD_FUNC_ARG; - } - return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS); -} - -#ifdef WOLFSSL_DTLS -int wolfSSL_dtls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz) -{ - WOLFSSL_ENTER("wolfSSL_session_import"); - - if (ssl == NULL || buf == NULL) { - return BAD_FUNC_ARG; - } - - /* sanity checks on buffer and protocol are done in internal function */ - return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS); -} - - -/* Sets the function to call for serializing the session. This function is - * called right after the handshake is completed. */ -int wolfSSL_CTX_dtls_set_export(WOLFSSL_CTX* ctx, wc_dtls_export func) -{ - - WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_export"); - - /* purposefully allow func to be NULL */ - if (ctx == NULL) { - return BAD_FUNC_ARG; - } - - ctx->dtls_export = func; - - return WOLFSSL_SUCCESS; -} - - -/* Sets the function in WOLFSSL struct to call for serializing the session. This - * function is called right after the handshake is completed. */ -int wolfSSL_dtls_set_export(WOLFSSL* ssl, wc_dtls_export func) -{ - - WOLFSSL_ENTER("wolfSSL_dtls_set_export"); - - /* purposefully allow func to be NULL */ - if (ssl == NULL) { - return BAD_FUNC_ARG; - } - - ssl->dtls_export = func; - - return WOLFSSL_SUCCESS; -} - - -/* This function allows for directly serializing a session rather than using - * callbacks. It has less overhead by removing a temporary buffer and gives - * control over when the session gets serialized. When using callbacks the - * session is always serialized immediately after the handshake is finished. - * - * buf is the argument to contain the serialized session - * sz is the size of the buffer passed in - * ssl is the WOLFSSL struct to serialize - * returns the size of serialized session on success, 0 on no action, and - * negative value on error */ -int wolfSSL_dtls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz) -{ - WOLFSSL_ENTER("wolfSSL_dtls_export"); - - if (ssl == NULL || sz == NULL) { - return BAD_FUNC_ARG; - } - - if (buf == NULL) { - *sz = MAX_EXPORT_BUFFER; - return 0; - } - - /* if not DTLS do nothing */ - if (!ssl->options.dtls) { - WOLFSSL_MSG("Currently only DTLS export is supported"); - return 0; - } - - /* copy over keys, options, and dtls state struct */ - return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS); -} - - -/* This function is similar to wolfSSL_dtls_export but only exports the portion - * of the WOLFSSL structure related to the state of the connection, i.e. peer - * sequence number, epoch, AEAD state etc. - * - * buf is the argument to contain the serialized state, if null then set "sz" to - * buffer size required - * sz is the size of the buffer passed in - * ssl is the WOLFSSL struct to serialize - * returns the size of serialized session on success, 0 on no action, and - * negative value on error */ -int wolfSSL_dtls_export_state_only(WOLFSSL* ssl, unsigned char* buf, - unsigned int* sz) -{ - WOLFSSL_ENTER("wolfSSL_dtls_export_state_only"); - - if (ssl == NULL || sz == NULL) { - return BAD_FUNC_ARG; - } - - if (buf == NULL) { - *sz = MAX_EXPORT_STATE_BUFFER; - return 0; - } - - /* if not DTLS do nothing */ - if (!ssl->options.dtls) { - WOLFSSL_MSG("Currently only DTLS export state is supported"); - return 0; - } - - /* copy over keys, options, and dtls state struct */ - return wolfSSL_dtls_export_state_internal(ssl, buf, *sz); -} - - -/* returns 0 on success */ -int wolfSSL_send_session(WOLFSSL* ssl) -{ - int ret; - byte* buf; - word32 bufSz = MAX_EXPORT_BUFFER; - - WOLFSSL_ENTER("wolfSSL_send_session"); - - if (ssl == NULL) { - return BAD_FUNC_ARG; - } - - buf = (byte*)XMALLOC(bufSz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (buf == NULL) { - return MEMORY_E; - } - - /* if not DTLS do nothing */ - if (!ssl->options.dtls) { - XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - WOLFSSL_MSG("Currently only DTLS export is supported"); - return 0; - } - - /* copy over keys, options, and dtls state struct */ - ret = wolfSSL_session_export_internal(ssl, buf, &bufSz, WOLFSSL_EXPORT_DTLS); - if (ret < 0) { - XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - return ret; - } - - /* if no error ret has size of buffer */ - ret = ssl->dtls_export(ssl, buf, ret, NULL); - if (ret != WOLFSSL_SUCCESS) { - XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - return ret; - } - - XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - return 0; -} -#endif /* WOLFSSL_DTLS */ -#endif /* WOLFSSL_SESSION_EXPORT */ - /* prevent multiple mutex initializations */ static volatile WOLFSSL_GLOBAL int initRefCount = 0; -static WOLFSSL_GLOBAL wolfSSL_Mutex inits_count_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex); /* init ref count mutex */ +/* init ref count mutex */ +static WOLFSSL_GLOBAL wolfSSL_Mutex inits_count_mutex + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex); #ifndef WOLFSSL_MUTEX_INITIALIZER static WOLFSSL_GLOBAL int inits_count_mutex_valid = 0; #endif @@ -1339,8 +1082,8 @@ WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap) wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); wolfSSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); if (wolfSSL_CTX_set_min_proto_version(ctx, - (method->version.major == DTLS_MAJOR) ? - DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS || + (method->version.major == DTLS_MAJOR) ? + DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS || #ifdef HAVE_ANON wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS || #endif @@ -1610,8 +1353,8 @@ static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl) #ifdef HAVE_ONE_TIME_AUTH #ifdef HAVE_POLY1305 if (ssl->auth.setup && ssl->auth.poly1305 != NULL) { - dup->auth.poly1305 = - (Poly1305*)XMALLOC(sizeof(Poly1305), dup->heap, DYNAMIC_TYPE_CIPHER); + dup->auth.poly1305 = (Poly1305*)XMALLOC(sizeof(Poly1305), dup->heap, + DYNAMIC_TYPE_CIPHER); if (dup->auth.poly1305 == NULL) return MEMORY_E; dup->auth.setup = 1; @@ -1945,7 +1688,7 @@ const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len) return NULL; cipher = wolfSSL_get_cipher_name_iana(ssl); - len = min(len, (int)(XSTRLEN(cipher) + 1)); + len = (int)min((word32)len, (int)(XSTRLEN(cipher) + 1)); XMEMCPY(buf, cipher, len); return buf; } @@ -2218,10 +1961,12 @@ int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu) static const WOLFSSL_SRTP_PROTECTION_PROFILE gSrtpProfiles[] = { /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 80-bits * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */ - {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80, (((128 + 112) * 2) / 8) }, + {"SRTP_AES128_CM_SHA1_80", SRTP_AES128_CM_SHA1_80, + (((128 + 112) * 2) / 8) }, /* AES CCM 128, Salt:112-bits, Auth HMAC-SHA1 Tag: 32-bits * (master_key:128bits + master_salt:112bits) * 2 = 480 bits (60) */ - {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32, (((128 + 112) * 2) / 8) }, + {"SRTP_AES128_CM_SHA1_32", SRTP_AES128_CM_SHA1_32, + (((128 + 112) * 2) / 8) }, /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 80-bits */ {"SRTP_NULL_SHA1_80", SRTP_NULL_SHA1_80, ((112 * 2) / 8)}, /* NULL Cipher, Salt:112-bits, Auth HMAC-SHA1 Tag 32-bits */ @@ -2348,7 +2093,7 @@ int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl, return EXT_MISSING; } if (out == NULL) { - *olen = profile->kdfBits; + *olen = (size_t)profile->kdfBits; return LENGTH_ONLY_E; } @@ -2465,7 +2210,8 @@ int wolfSSL_set_secret(WOLFSSL* ssl, word16 epoch, if (ret == 0) { XMEMCPY(ssl->arrays->preMasterSecret, preMasterSecret, preMasterSz); - XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0, ENCRYPT_LEN - preMasterSz); + XMEMSET(ssl->arrays->preMasterSecret + preMasterSz, 0, + ENCRYPT_LEN - preMasterSz); ssl->arrays->preMasterSz = preMasterSz; XMEMCPY(ssl->arrays->clientRandom, clientRandom, RAN_LEN); XMEMCPY(ssl->arrays->serverRandom, serverRandom, RAN_LEN); @@ -2716,7 +2462,8 @@ int wolfSSL_GetObjectSize(void) #ifdef WOLFSSL_SM4 printf("\tsizeof sm4 = %lu\n", (unsigned long)sizeof(Sm4)); #endif - printf("sizeof cipher specs = %lu\n", (unsigned long)sizeof(CipherSpecs)); + printf("sizeof cipher specs = %lu\n", (unsigned long) + sizeof(CipherSpecs)); printf("sizeof keys = %lu\n", (unsigned long)sizeof(Keys)); printf("sizeof Hashes(2) = %lu\n", (unsigned long)sizeof(Hashes)); #ifndef NO_MD5 @@ -2749,10 +2496,13 @@ int wolfSSL_GetObjectSize(void) #ifdef HAVE_ECC printf("sizeof ecc_key = %lu\n", (unsigned long)sizeof(ecc_key)); #endif - printf("sizeof WOLFSSL_CIPHER = %lu\n", (unsigned long)sizeof(WOLFSSL_CIPHER)); - printf("sizeof WOLFSSL_SESSION = %lu\n", (unsigned long)sizeof(WOLFSSL_SESSION)); + printf("sizeof WOLFSSL_CIPHER = %lu\n", (unsigned long) + sizeof(WOLFSSL_CIPHER)); + printf("sizeof WOLFSSL_SESSION = %lu\n", (unsigned long) + sizeof(WOLFSSL_SESSION)); printf("sizeof WOLFSSL = %lu\n", (unsigned long)sizeof(WOLFSSL)); - printf("sizeof WOLFSSL_CTX = %lu\n", (unsigned long)sizeof(WOLFSSL_CTX)); + printf("sizeof WOLFSSL_CTX = %lu\n", (unsigned long) + sizeof(WOLFSSL_CTX)); #endif return sizeof(WOLFSSL); @@ -2772,13 +2522,11 @@ int wolfSSL_METHOD_GetObjectSize(void) #ifdef WOLFSSL_STATIC_MEMORY -int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, wolfSSL_method_func method, - unsigned char* buf, unsigned int sz, - int flag, int maxSz) +int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, + wolfSSL_method_func method, unsigned char* buf, unsigned int sz, int flag, + int maxSz) { - WOLFSSL_HEAP* heap; - WOLFSSL_HEAP_HINT* hint; - word32 idx = 0; + WOLFSSL_HEAP_HINT* hint = NULL; if (ctx == NULL || buf == NULL) { return BAD_FUNC_ARG; @@ -2788,42 +2536,23 @@ int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, wolfSSL_method_func method return BAD_FUNC_ARG; } - if (*ctx == NULL || (*ctx)->heap == NULL) { - if (sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT) > sz - idx) { - return BUFFER_E; /* not enough memory for structures */ - } - heap = (WOLFSSL_HEAP*)buf; - idx += sizeof(WOLFSSL_HEAP); - if (wolfSSL_init_memory_heap(heap) != 0) { - return WOLFSSL_FAILURE; - } - hint = (WOLFSSL_HEAP_HINT*)(buf + idx); - idx += sizeof(WOLFSSL_HEAP_HINT); - XMEMSET(hint, 0, sizeof(WOLFSSL_HEAP_HINT)); - hint->memory = heap; - - if (*ctx && (*ctx)->heap == NULL) { - (*ctx)->heap = (void*)hint; - } - } - else { -#ifdef WOLFSSL_HEAP_TEST - /* do not load in memory if test has been set */ - if ((*ctx)->heap == (void*)WOLFSSL_HEAP_TEST) { - return WOLFSSL_SUCCESS; - } -#endif - hint = (WOLFSSL_HEAP_HINT*)((*ctx)->heap); - heap = hint->memory; + /* If there is a heap already, capture it in hint. */ + if (*ctx && (*ctx)->heap != NULL) { + hint = (*ctx)->heap; } - if (wolfSSL_load_static_memory(buf + idx, sz - idx, flag, heap) != 1) { - WOLFSSL_MSG("Error partitioning memory"); + if (wc_LoadStaticMemory(&hint, buf, sz, flag, maxSz)) { + WOLFSSL_MSG("Error loading static memory"); return WOLFSSL_FAILURE; } - /* create ctx if needed */ - if (*ctx == NULL) { + if (*ctx) { + if ((*ctx)->heap == NULL) { + (*ctx)->heap = (void*)hint; + } + } + else { + /* create ctx if needed */ *ctx = wolfSSL_CTX_new_ex(method(hint), hint); if (*ctx == NULL) { WOLFSSL_MSG("Error creating ctx"); @@ -2831,19 +2560,6 @@ int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx, wolfSSL_method_func method } } - /* determine what max applies too */ - if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { - heap->maxIO = maxSz; - } - else { /* general memory used in handshakes */ - heap->maxHa = maxSz; - } - - heap->flag |= flag; - - (void)maxSz; - (void)method; - return WOLFSSL_SUCCESS; } @@ -2855,6 +2571,7 @@ int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats) } WOLFSSL_ENTER("wolfSSL_is_static_memory"); +#ifndef WOLFSSL_STATIC_MEMORY_LEAN /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */ if (mem_stats != NULL && ssl->heap != NULL) { WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap)); @@ -2863,7 +2580,9 @@ int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats) XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS)); } } +#endif + (void)mem_stats; return (ssl->heap) ? 1 : 0; } @@ -2875,6 +2594,7 @@ int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats) } WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory"); +#ifndef WOLFSSL_STATIC_MEMORY_LEAN /* fill out statistics if wanted */ if (mem_stats != NULL && ctx->heap != NULL) { WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory; @@ -2882,7 +2602,9 @@ int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats) return MEMORY_E; } } +#endif + (void)mem_stats; return (ctx->heap) ? 1 : 0; } @@ -2922,13 +2644,15 @@ int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz) if (inSz > maxSize) return INPUT_SIZE_E; - return BuildMessage(ssl, NULL, 0, NULL, inSz, application_data, 0, 1, 0, CUR_ORDER); + return BuildMessage(ssl, NULL, 0, NULL, inSz, application_data, 0, 1, 0, + CUR_ORDER); } #ifdef HAVE_ECC int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz) { + WOLFSSL_ENTER("wolfSSL_CTX_SetMinEccKey_Sz"); if (ctx == NULL || keySz < 0 || keySz % 8 != 0) { WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null"); return BAD_FUNC_ARG; @@ -2944,6 +2668,7 @@ int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz) int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz) { + WOLFSSL_ENTER("wolfSSL_SetMinEccKey_Sz"); if (ssl == NULL || keySz < 0 || keySz % 8 != 0) { WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null"); return BAD_FUNC_ARG; @@ -2983,138 +2708,6 @@ int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz) #ifndef NO_DH -#ifdef OPENSSL_EXTRA -long wolfSSL_set_tmp_dh(WOLFSSL *ssl, WOLFSSL_DH *dh) -{ - int pSz, gSz; - byte *p, *g; - int ret = 0; - - WOLFSSL_ENTER("wolfSSL_set_tmp_dh"); - - if (!ssl || !dh) - return BAD_FUNC_ARG; - - /* Get needed size for p and g */ - pSz = wolfSSL_BN_bn2bin(dh->p, NULL); - gSz = wolfSSL_BN_bn2bin(dh->g, NULL); - - if (pSz <= 0 || gSz <= 0) - return -1; - - p = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (!p) - return MEMORY_E; - - g = (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (!g) { - XFREE(p, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - return MEMORY_E; - } - - pSz = wolfSSL_BN_bn2bin(dh->p, p); - gSz = wolfSSL_BN_bn2bin(dh->g, g); - - if (pSz >= 0 && gSz >= 0) /* Conversion successful */ - ret = wolfSSL_SetTmpDH(ssl, p, pSz, g, gSz); - - XFREE(p, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(g, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - - return pSz > 0 && gSz > 0 ? ret : -1; -} -#endif /* OPENSSL_EXTRA */ - -/* server Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */ -int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz, - const unsigned char* g, int gSz) -{ - WOLFSSL_ENTER("wolfSSL_SetTmpDH"); - - if (ssl == NULL || p == NULL || g == NULL) - return BAD_FUNC_ARG; - - if ((word16)pSz < ssl->options.minDhKeySz) - return DH_KEY_SIZE_E; - if ((word16)pSz > ssl->options.maxDhKeySz) - return DH_KEY_SIZE_E; - - /* this function is for server only */ - if (ssl->options.side == WOLFSSL_CLIENT_END) - return SIDE_ERROR; - - #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ - !defined(HAVE_SELFTEST) - ssl->options.dhKeyTested = 0; - ssl->options.dhDoKeyTest = 1; - #endif - - if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) { - XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ssl->buffers.serverDH_P.buffer = NULL; - } - if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) { - XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ssl->buffers.serverDH_G.buffer = NULL; - } - - ssl->buffers.weOwnDH = 1; /* SSL owns now */ - ssl->buffers.serverDH_P.buffer = (byte*)XMALLOC(pSz, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - if (ssl->buffers.serverDH_P.buffer == NULL) - return MEMORY_E; - - ssl->buffers.serverDH_G.buffer = (byte*)XMALLOC(gSz, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - if (ssl->buffers.serverDH_G.buffer == NULL) { - XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ssl->buffers.serverDH_P.buffer = NULL; - return MEMORY_E; - } - - ssl->buffers.serverDH_P.length = pSz; - ssl->buffers.serverDH_G.length = gSz; - - XMEMCPY(ssl->buffers.serverDH_P.buffer, p, pSz); - XMEMCPY(ssl->buffers.serverDH_G.buffer, g, gSz); - - ssl->options.haveDH = 1; - - if (ssl->options.side != WOLFSSL_NEITHER_END) { - word16 havePSK; - word16 haveRSA; - int keySz = 0; - int ret; - - #ifndef NO_PSK - havePSK = ssl->options.havePSK; - #else - havePSK = 0; - #endif - #ifdef NO_RSA - haveRSA = 0; - #else - haveRSA = 1; - #endif - #ifndef NO_CERTS - keySz = ssl->buffers.keySz; - #endif - ret = AllocateSuites(ssl); - if (ret != 0) - return ret; - InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, - ssl->options.haveDH, ssl->options.haveECDSAsig, - ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); - } - - WOLFSSL_LEAVE("wolfSSL_SetTmpDH", 0); - - return WOLFSSL_SUCCESS; -} - - #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ !defined(HAVE_SELFTEST) /* Enables or disables the session's DH key prime test. */ @@ -3135,82 +2728,6 @@ int wolfSSL_SetEnableDhKeyTest(WOLFSSL* ssl, int enable) } #endif - -/* server ctx Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */ -int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz, - const unsigned char* g, int gSz) -{ - WOLFSSL_ENTER("wolfSSL_CTX_SetTmpDH"); - if (ctx == NULL || p == NULL || g == NULL) return BAD_FUNC_ARG; - - if ((word16)pSz < ctx->minDhKeySz) - return DH_KEY_SIZE_E; - if ((word16)pSz > ctx->maxDhKeySz) - return DH_KEY_SIZE_E; - - #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ - !defined(HAVE_SELFTEST) - { - WC_RNG rng; - int error, freeKey = 0; - #ifdef WOLFSSL_SMALL_STACK - DhKey *checkKey = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); - if (checkKey == NULL) - return MEMORY_E; - #else - DhKey checkKey[1]; - #endif - - error = wc_InitRng(&rng); - if (!error) - error = wc_InitDhKey(checkKey); - if (!error) { - freeKey = 1; - error = wc_DhSetCheckKey(checkKey, - p, pSz, g, gSz, NULL, 0, 0, &rng); - } - if (freeKey) - wc_FreeDhKey(checkKey); - #ifdef WOLFSSL_SMALL_STACK - XFREE(checkKey, NULL, DYNAMIC_TYPE_DH); - #endif - wc_FreeRng(&rng); - if (error) - return error; - - ctx->dhKeyTested = 1; - } - #endif - - XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ctx->serverDH_P.buffer = NULL; - XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ctx->serverDH_G.buffer = NULL; - - ctx->serverDH_P.buffer = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (ctx->serverDH_P.buffer == NULL) - return MEMORY_E; - - ctx->serverDH_G.buffer = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (ctx->serverDH_G.buffer == NULL) { - XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - ctx->serverDH_P.buffer = NULL; - return MEMORY_E; - } - - ctx->serverDH_P.length = pSz; - ctx->serverDH_G.length = gSz; - - XMEMCPY(ctx->serverDH_P.buffer, p, pSz); - XMEMCPY(ctx->serverDH_G.buffer, g, gSz); - - ctx->haveDH = 1; - - WOLFSSL_LEAVE("wolfSSL_CTX_SetTmpDH", 0); - return WOLFSSL_SUCCESS; -} - - int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits) { if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0) @@ -3549,7 +3066,7 @@ word16 wolfSSL_SNI_GetRequest(WOLFSSL* ssl, byte type, void** data) *data = NULL; if (ssl && ssl->extensions) - return TLSX_SNI_GetRequest(ssl->extensions, type, data); + return TLSX_SNI_GetRequest(ssl->extensions, type, data, 0); return 0; } @@ -3750,11 +3267,11 @@ static int isValidCurveGroup(word16 name) case WOLFSSL_FFDHE_6144: case WOLFSSL_FFDHE_8192: -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER case WOLFSSL_KYBER_LEVEL1: case WOLFSSL_KYBER_LEVEL3: case WOLFSSL_KYBER_LEVEL5: - #ifdef HAVE_LIBOQS + #if defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS) case WOLFSSL_P256_KYBER_LEVEL1: case WOLFSSL_P384_KYBER_LEVEL3: case WOLFSSL_P521_KYBER_LEVEL5: @@ -3794,7 +3311,7 @@ int wolfSSL_CTX_UseSupportedCurve(WOLFSSL_CTX* ctx, word16 name) #endif /* NO_TLS */ } -#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_TLS13) +#if defined(OPENSSL_EXTRA) int wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups, int count) { @@ -3812,7 +3329,7 @@ int wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups, #ifdef HAVE_ECC else { /* groups may be populated with curve NIDs */ - int oid = nid2oid(groups[i], oidCurveType); + int oid = (int)nid2oid(groups[i], oidCurveType); int name = (int)GetCurveByOID(oid); if (name == 0) { WOLFSSL_MSG("Invalid group name"); @@ -3847,7 +3364,7 @@ int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count) #ifdef HAVE_ECC else { /* groups may be populated with curve NIDs */ - int oid = nid2oid(groups[i], oidCurveType); + int oid = (int)nid2oid(groups[i], oidCurveType); int name = (int)GetCurveByOID(oid); if (name == 0) { WOLFSSL_MSG("Invalid group name"); @@ -3865,7 +3382,7 @@ int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count) return wolfSSL_set_groups(ssl, _groups, count) == WOLFSSL_SUCCESS ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } -#endif /* OPENSSL_EXTRA && WOLFSSL_TLS13 */ +#endif /* OPENSSL_EXTRA */ #endif /* HAVE_SUPPORTED_CURVES */ /* Application-Layer Protocol Negotiation */ @@ -3906,7 +3423,8 @@ int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list, return MEMORY_ERROR; } - token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1), ssl->heap, DYNAMIC_TYPE_ALPN); + token = (char **)XMALLOC(sizeof(char *) * (WOLFSSL_MAX_ALPN_NUMBER+1), + ssl->heap, DYNAMIC_TYPE_ALPN); if (token == NULL) { XFREE(list, ssl->heap, DYNAMIC_TYPE_ALPN); WOLFSSL_MSG("Memory failure"); @@ -4012,12 +3530,14 @@ int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list) /* user is forcing ability to use secure renegotiation, we discourage it */ int wolfSSL_UseSecureRenegotiation(WOLFSSL* ssl) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); #if defined(NO_TLS) (void)ssl; #else if (ssl) ret = TLSX_UseSecureRenegotiation(&ssl->extensions, ssl->heap); + else + ret = BAD_FUNC_ARG; if (ret == WOLFSSL_SUCCESS) { TLSX* extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO); @@ -4339,7 +3859,8 @@ int wolfSSL_set_SessionTicket(WOLFSSL* ssl, const byte* buf, } } else { /* Ticket requires dynamic ticket storage */ - if (ssl->session->ticketLen < bufSz) { /* is dyn buffer big enough */ + /* is dyn buffer big enough */ + if (ssl->session->ticketLen < bufSz) { if (ssl->session->ticketLenAlloc > 0) { XFREE(ssl->session->ticket, ssl->session->heap, DYNAMIC_TYPE_SESSION_TICK); @@ -4452,10 +3973,29 @@ int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags) } #endif - -/* WOLFSSL_SUCCESS on ok */ -WOLFSSL_ABI -int wolfSSL_shutdown(WOLFSSL* ssl) +int wolfSSL_SendUserCanceled(WOLFSSL* ssl) +{ + int ret = WOLFSSL_FAILURE; + WOLFSSL_ENTER("wolfSSL_recv"); + + if (ssl != NULL) { + ssl->error = SendAlert(ssl, alert_warning, user_canceled); + if (ssl->error < 0) { + WOLFSSL_ERROR(ssl->error); + } + else { + ret = wolfSSL_shutdown(ssl); + } + } + + WOLFSSL_LEAVE("wolfSSL_SendUserCanceled", ret); + + return ret; +} + +/* WOLFSSL_SUCCESS on ok */ +WOLFSSL_ABI +int wolfSSL_shutdown(WOLFSSL* ssl) { int ret = WOLFSSL_FATAL_ERROR; WOLFSSL_ENTER("wolfSSL_shutdown"); @@ -4499,13 +4039,14 @@ int wolfSSL_shutdown(WOLFSSL* ssl) /* call wolfSSL_shutdown again for bidirectional shutdown */ if (ssl->options.sentNotify && !ssl->options.closeNotify) { ret = ProcessReply(ssl); - if ((ret == ZERO_RETURN) || (ret == SOCKET_ERROR_E)) { + if ((ret == ZERO_RETURN) || + (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))) { /* simulate OpenSSL behavior */ ssl->options.shutdownDone = 1; /* Clear error */ ssl->error = WOLFSSL_ERROR_NONE; ret = WOLFSSL_SUCCESS; - } else if (ret == MEMORY_E) { + } else if (ret == WC_NO_ERR_TRACE(MEMORY_E)) { ret = WOLFSSL_FATAL_ERROR; } else if (ssl->error == WOLFSSL_ERROR_NONE) { ret = WOLFSSL_SHUTDOWN_NOT_DONE; @@ -4563,14 +4104,10 @@ int wolfSSL_get_error(WOLFSSL* ssl, int ret) else if (ssl->error == ZERO_RETURN || ssl->options.shutdownDone) return WOLFSSL_ERROR_ZERO_RETURN; /* convert to OpenSSL type */ #ifdef OPENSSL_EXTRA - else if (ssl->error == SOCKET_PEER_CLOSED_E) + else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E)) return WOLFSSL_ERROR_SYSCALL; /* convert to OpenSSL type */ #endif -#if defined(WOLFSSL_HAPROXY) - return GetX509Error(ssl->error); -#else - return (ssl->error); -#endif + return ssl->error; } @@ -5709,14 +5246,15 @@ int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify) #endif XMEMCPY(peerCert->subjectNameHash, cert->subjectHash, SIGNER_DIGEST_SIZE); - peerCert->next = NULL; /* If Key Usage not set, all uses valid. */ + /* If Key Usage not set, all uses valid. */ + peerCert->next = NULL; cert->subjectCN = 0; #ifndef IGNORE_NAME_CONSTRAINTS cert->permittedNames = NULL; cert->excludedNames = NULL; #endif - row = TrustedPeerHashSigner(peerCert->subjectNameHash); + row = (int)TrustedPeerHashSigner(peerCert->subjectNameHash); if (wc_LockMutex(&cm->tpLock) == 0) { peerCert->next = cm->tpTable[row]; @@ -5745,6 +5283,38 @@ int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify) } #endif /* WOLFSSL_TRUST_PEER_CERT */ +int AddSigner(WOLFSSL_CERT_MANAGER* cm, Signer *s) +{ + byte* subjectHash; + Signer* signers; + word32 row; + + if (cm == NULL || s == NULL) + return BAD_FUNC_ARG; + +#ifndef NO_SKID + subjectHash = s->subjectKeyIdHash; +#else + subjectHash = s->subjectNameHash; +#endif + + if (AlreadySigner(cm, subjectHash)) { + FreeSigner(s, cm->heap); + return 0; + } + + row = HashSigner(subjectHash); + + if (wc_LockMutex(&cm->caLock) != 0) + return BAD_MUTEX_E; + + signers = cm->caTable[row]; + s->next = signers; + cm->caTable[row] = s; + + wc_UnLockMutex(&cm->caLock); + return 0; +} /* owns der, internal now uses too */ /* type flag ids from user or from chain received during verify @@ -5830,7 +5400,6 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) } break; #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: if (cm->minFalconKeySz < 0 || @@ -5870,7 +5439,6 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) } break; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ default: WOLFSSL_MSG("\tNo key size check done on CA"); @@ -5901,62 +5469,8 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) if (!signer) ret = MEMORY_ERROR; } -#if defined(WOLFSSL_AKID_NAME) || defined(HAVE_CRL) - if (ret == 0 && signer != NULL) - ret = CalcHashId(cert->serial, cert->serialSz, signer->serialHash); -#endif - if (ret == 0 && signer != NULL) { - #ifdef WOLFSSL_SIGNER_DER_CERT - ret = AllocDer(&signer->derCert, der->length, der->type, NULL); - } if (ret == 0 && signer != NULL) { - XMEMCPY(signer->derCert->buffer, der->buffer, der->length); - #endif - signer->keyOID = cert->keyOID; - if (cert->pubKeyStored) { - signer->publicKey = cert->publicKey; - signer->pubKeySize = cert->pubKeySize; - } - -#ifdef WOLFSSL_DUAL_ALG_CERTS - signer->sapkiDer = cert->sapkiDer; - signer->sapkiLen = cert->sapkiLen; -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - - if (cert->subjectCNStored) { - signer->nameLen = cert->subjectCNLen; - signer->name = cert->subjectCN; - } - signer->maxPathLen = cert->maxPathLen; - signer->selfSigned = cert->selfSigned; - #ifndef IGNORE_NAME_CONSTRAINTS - signer->permittedNames = cert->permittedNames; - signer->excludedNames = cert->excludedNames; - #endif - #ifndef NO_SKID - XMEMCPY(signer->subjectKeyIdHash, cert->extSubjKeyId, - SIGNER_DIGEST_SIZE); - #endif - XMEMCPY(signer->subjectNameHash, cert->subjectHash, - SIGNER_DIGEST_SIZE); - #if defined(HAVE_OCSP) || defined(HAVE_CRL) - XMEMCPY(signer->issuerNameHash, cert->issuerHash, - SIGNER_DIGEST_SIZE); - #endif - #ifdef HAVE_OCSP - XMEMCPY(signer->subjectKeyHash, cert->subjectKeyHash, - KEYID_SIZE); - #endif - signer->keyUsage = cert->extKeyUsageSet ? cert->extKeyUsage - : 0xFFFF; - signer->next = NULL; /* If Key Usage not set, all uses valid. */ - cert->publicKey = 0; /* in case lock fails don't free here. */ - cert->subjectCN = 0; - #ifndef IGNORE_NAME_CONSTRAINTS - cert->permittedNames = NULL; - cert->excludedNames = NULL; - #endif - signer->type = (byte)type; + ret = FillSigner(signer, cert, type, der); #ifndef NO_SKID row = HashSigner(signer->subjectKeyIdHash); @@ -5964,7 +5478,8 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) row = HashSigner(signer->subjectNameHash); #endif - if (wc_LockMutex(&cm->caLock) == 0) { + + if (ret == 0 && wc_LockMutex(&cm->caLock) == 0) { signer->next = cm->caTable[row]; cm->caTable[row] = signer; /* takes ownership */ wc_UnLockMutex(&cm->caLock); @@ -6018,191 +5533,6 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) #endif /* !NO_CERTS */ -#ifndef NO_SESSION_CACHE - - /* basic config gives a cache with 33 sessions, adequate for clients and - embedded servers - - TITAN_SESSION_CACHE allows just over 2 million sessions, for servers - with titanic amounts of memory with long session ID timeouts and high - levels of traffic. - - ENABLE_SESSION_CACHE_ROW_LOCK: Allows row level locking for increased - performance with large session caches - - HUGE_SESSION_CACHE yields 65,791 sessions, for servers under heavy load, - allows over 13,000 new sessions per minute or over 200 new sessions per - second - - BIG_SESSION_CACHE yields 20,027 sessions - - MEDIUM_SESSION_CACHE allows 1055 sessions, adequate for servers that - aren't under heavy load, basically allows 200 new sessions per minute - - SMALL_SESSION_CACHE only stores 6 sessions, good for embedded clients - or systems where the default of is too much RAM. - SessionCache takes about 2K, ClientCache takes about 3Kbytes - - MICRO_SESSION_CACHE only stores 1 session, good for embedded clients - or systems where memory is at a premium. - SessionCache takes about 400 bytes, ClientCache takes 576 bytes - - default SESSION_CACHE stores 33 sessions (no XXX_SESSION_CACHE defined) - SessionCache takes about 13K bytes, ClientCache takes 17K bytes - */ - #if defined(TITAN_SESSION_CACHE) - #define SESSIONS_PER_ROW 31 - #define SESSION_ROWS 64937 - #ifndef ENABLE_SESSION_CACHE_ROW_LOCK - #define ENABLE_SESSION_CACHE_ROW_LOCK - #endif - #elif defined(HUGE_SESSION_CACHE) - #define SESSIONS_PER_ROW 11 - #define SESSION_ROWS 5981 - #elif defined(BIG_SESSION_CACHE) - #define SESSIONS_PER_ROW 7 - #define SESSION_ROWS 2861 - #elif defined(MEDIUM_SESSION_CACHE) - #define SESSIONS_PER_ROW 5 - #define SESSION_ROWS 211 - #elif defined(SMALL_SESSION_CACHE) - #define SESSIONS_PER_ROW 2 - #define SESSION_ROWS 3 - #elif defined(MICRO_SESSION_CACHE) - #define SESSIONS_PER_ROW 1 - #define SESSION_ROWS 1 - #else - #define SESSIONS_PER_ROW 3 - #define SESSION_ROWS 11 - #endif - #define INVALID_SESSION_ROW (-1) - - #ifdef NO_SESSION_CACHE_ROW_LOCK - #undef ENABLE_SESSION_CACHE_ROW_LOCK - #endif - - typedef struct SessionRow { - int nextIdx; /* where to place next one */ - int totalCount; /* sessions ever on this row */ -#ifdef SESSION_CACHE_DYNAMIC_MEM - WOLFSSL_SESSION* Sessions[SESSIONS_PER_ROW]; - void* heap; -#else - WOLFSSL_SESSION Sessions[SESSIONS_PER_ROW]; -#endif - - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - /* not included in import/export */ - wolfSSL_RwLock row_lock; - int lock_valid; - #endif - } SessionRow; - #define SIZEOF_SESSION_ROW (sizeof(WOLFSSL_SESSION) + (sizeof(int) * 2)) - - static WOLFSSL_GLOBAL SessionRow SessionCache[SESSION_ROWS]; - - #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS) - static WOLFSSL_GLOBAL word32 PeakSessions; - #endif - - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - #define SESSION_ROW_RD_LOCK(row) wc_LockRwLock_Rd(&(row)->row_lock) - #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&(row)->row_lock) - #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&(row)->row_lock); - #else - static WOLFSSL_GLOBAL wolfSSL_RwLock session_lock; /* SessionCache lock */ - static WOLFSSL_GLOBAL int session_lock_valid = 0; - #define SESSION_ROW_RD_LOCK(row) wc_LockRwLock_Rd(&session_lock) - #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&session_lock) - #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&session_lock); - #endif - - #if !defined(NO_SESSION_CACHE_REF) && defined(NO_CLIENT_CACHE) - #error ClientCache is required when not using NO_SESSION_CACHE_REF - #endif - - #ifndef NO_CLIENT_CACHE - - #ifndef CLIENT_SESSIONS_MULTIPLIER - #ifdef NO_SESSION_CACHE_REF - #define CLIENT_SESSIONS_MULTIPLIER 1 - #else - /* ClientSession objects are lightweight (compared to - * WOLFSSL_SESSION) so to decrease chance that user will reuse - * the wrong session, increase the ClientCache size. This will - * make the entire ClientCache about the size of one - * WOLFSSL_SESSION object. */ - #define CLIENT_SESSIONS_MULTIPLIER 8 - #endif - #endif - #define CLIENT_SESSIONS_PER_ROW \ - (SESSIONS_PER_ROW * CLIENT_SESSIONS_MULTIPLIER) - #define CLIENT_SESSION_ROWS (SESSION_ROWS * CLIENT_SESSIONS_MULTIPLIER) - - #if CLIENT_SESSIONS_PER_ROW > 65535 - #error CLIENT_SESSIONS_PER_ROW too big - #endif - #if CLIENT_SESSION_ROWS > 65535 - #error CLIENT_SESSION_ROWS too big - #endif - - struct ClientSession { - word16 serverRow; /* SessionCache Row id */ - word16 serverIdx; /* SessionCache Idx (column) */ - word32 sessionIDHash; - }; - #ifndef WOLFSSL_CLIENT_SESSION_DEFINED - typedef struct ClientSession ClientSession; - #define WOLFSSL_CLIENT_SESSION_DEFINED - #endif - - typedef struct ClientRow { - int nextIdx; /* where to place next one */ - int totalCount; /* sessions ever on this row */ - ClientSession Clients[CLIENT_SESSIONS_PER_ROW]; - } ClientRow; - - static WOLFSSL_GLOBAL ClientRow ClientCache[CLIENT_SESSION_ROWS]; - /* Client Cache */ - /* uses session mutex */ - - static WOLFSSL_GLOBAL wolfSSL_Mutex clisession_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(clisession_mutex); /* ClientCache mutex */ - #ifndef WOLFSSL_MUTEX_INITIALIZER - static WOLFSSL_GLOBAL int clisession_mutex_valid = 0; - #endif - #endif /* !NO_CLIENT_CACHE */ - - void EvictSessionFromCache(WOLFSSL_SESSION* session) - { -#ifdef HAVE_EX_DATA - int save_ownExData = session->ownExData; - session->ownExData = 1; /* Make sure ex_data access doesn't lead back - * into the cache. */ -#endif -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - if (session->rem_sess_cb != NULL) { - session->rem_sess_cb(NULL, session); - session->rem_sess_cb = NULL; - } -#endif - ForceZero(session->masterSecret, SECRET_LEN); - XMEMSET(session->sessionID, 0, ID_LEN); - session->sessionIDSz = 0; -#ifdef HAVE_SESSION_TICKET - if (session->ticketLenAlloc > 0) { - XFREE(session->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK); - session->ticket = session->staticTicket; - session->ticketLen = 0; - session->ticketLenAlloc = 0; - } -#endif -#ifdef HAVE_EX_DATA - session->ownExData = save_ownExData; -#endif - } - -#endif /* !NO_SESSION_CACHE */ - #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB) static int wolfSSL_RAND_InitMutex(void); #endif @@ -6244,13 +5574,13 @@ int wolfSSL_Init(void) return BAD_MUTEX_E; } - #if FIPS_VERSION_GE(5,1) +#if FIPS_VERSION_GE(5,1) if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) { ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL); if (ret == 0) ret = WOLFSSL_SUCCESS; } - #endif +#endif if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) { /* Initialize crypto for use with TLS connection */ @@ -6340,11 +5670,13 @@ int wolfSSL_Init(void) if (ret == WOLFSSL_SUCCESS) { initRefCount++; } + else { + initRefCount = 1; /* Force cleanup */ + } wc_UnLockMutex(&inits_count_mutex); if (ret != WOLFSSL_SUCCESS) { - initRefCount = 1; /* Force cleanup */ (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */ } @@ -6352,29677 +5684,18939 @@ int wolfSSL_Init(void) } +#define WOLFSSL_SSL_LOAD_INCLUDED +#include + #ifndef NO_CERTS -/* process user cert chain to pass during the handshake */ -static int ProcessUserChain(WOLFSSL_CTX* ctx, const unsigned char* buff, - long sz, int format, int type, WOLFSSL* ssl, - long* used, EncryptedInfo* info, int verify) +#ifdef HAVE_CRL + +int wolfSSL_CTX_LoadCRLBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, + long sz, int type) { - int ret = 0; - void* heap = wolfSSL_CTX_GetHeap(ctx, ssl); + WOLFSSL_ENTER("wolfSSL_CTX_LoadCRLBuffer"); - if ((type == CA_TYPE) && (ctx == NULL)) { - WOLFSSL_MSG("Need context for CA load"); + if (ctx == NULL) return BAD_FUNC_ARG; - } - /* we may have a user cert chain, try to consume */ - if ((type == CERT_TYPE || type == CHAIN_CERT_TYPE || type == CA_TYPE) && - (info->consumed < sz)) { - #ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force heap usage */ - #else - byte staticBuffer[FILE_BUFFER_SIZE]; /* tmp chain buffer */ - #endif - byte* chainBuffer = staticBuffer; - int dynamicBuffer = 0; - word32 bufferSz; - long consumed = info->consumed; - word32 idx = 0; - int gotOne = 0; - #ifdef WOLFSSL_TLS13 - int cnt = 0; - #endif + return wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, buff, sz, type); +} - /* Calculate max possible size, including max headers */ - bufferSz = (word32)(sz - consumed) + (CERT_HEADER_SZ * MAX_CHAIN_DEPTH); - if (bufferSz > sizeof(staticBuffer)) { - WOLFSSL_MSG("Growing Tmp Chain Buffer"); - /* will shrink to actual size */ - chainBuffer = (byte*)XMALLOC(bufferSz, heap, DYNAMIC_TYPE_FILE); - if (chainBuffer == NULL) { - return MEMORY_E; - } - dynamicBuffer = 1; - } - WOLFSSL_MSG("Processing Cert Chain"); - while (consumed < sz) { - DerBuffer* part = NULL; - word32 remain = (word32)(sz - consumed); - info->consumed = 0; +int wolfSSL_LoadCRLBuffer(WOLFSSL* ssl, const unsigned char* buff, + long sz, int type) +{ + WOLFSSL_ENTER("wolfSSL_LoadCRLBuffer"); - if (format == WOLFSSL_FILETYPE_PEM) { - #ifdef WOLFSSL_PEM_TO_DER - ret = PemToDer(buff + consumed, remain, type, &part, - heap, info, NULL); - #else - ret = NOT_COMPILED_IN; - #endif - } - else { - int length = remain; - if (format == WOLFSSL_FILETYPE_ASN1) { - /* get length of der (read sequence) */ - word32 inOutIdx = 0; - if (GetSequence(buff + consumed, &inOutIdx, &length, - remain) < 0) { - ret = ASN_NO_PEM_HEADER; - } - length += inOutIdx; /* include leading sequence */ - } - info->consumed = length; - if (ret == 0) { - ret = AllocDer(&part, length, type, heap); - if (ret == 0) { - XMEMCPY(part->buffer, buff + consumed, length); - } - } - } - if (ret == 0) { - gotOne = 1; -#ifdef WOLFSSL_TLS13 - cnt++; -#endif - if ((idx + part->length + CERT_HEADER_SZ) > bufferSz) { - WOLFSSL_MSG(" Cert Chain bigger than buffer. " - "Consider increasing MAX_CHAIN_DEPTH"); - ret = BUFFER_E; - } - else { - c32to24(part->length, &chainBuffer[idx]); - idx += CERT_HEADER_SZ; - XMEMCPY(&chainBuffer[idx], part->buffer, part->length); - idx += part->length; - consumed += info->consumed; - if (used) - *used += info->consumed; - } + if (ssl == NULL || ssl->ctx == NULL) + return BAD_FUNC_ARG; - /* add CA's to certificate manager */ - if (ret == 0 && type == CA_TYPE) { - /* verify CA unless user set to no verify */ - ret = AddCA(ctx->cm, &part, WOLFSSL_USER_CA, verify); - if (ret == WOLFSSL_SUCCESS) { - ret = 0; /* converted success case */ - } - gotOne = 0; /* don't exit loop for CA type */ - } - } + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerLoadCRLBuffer(SSL_CM(ssl), buff, sz, type); +} - FreeDer(&part); +#endif /* HAVE_CRL */ - if (ret == ASN_NO_PEM_HEADER && gotOne) { - WOLFSSL_MSG("We got one good cert, so stuff at end ok"); - break; - } +#ifdef HAVE_OCSP +int wolfSSL_EnableOCSP(WOLFSSL* ssl, int options) +{ + WOLFSSL_ENTER("wolfSSL_EnableOCSP"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerEnableOCSP(SSL_CM(ssl), options); + } + else + return BAD_FUNC_ARG; +} - if (ret < 0) { - WOLFSSL_MSG(" Error in Cert in Chain"); - if (dynamicBuffer) - XFREE(chainBuffer, heap, DYNAMIC_TYPE_FILE); - return ret; - } - WOLFSSL_MSG(" Consumed another Cert in Chain"); - } - WOLFSSL_MSG("Finished Processing Cert Chain"); +int wolfSSL_DisableOCSP(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_DisableOCSP"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerDisableOCSP(SSL_CM(ssl)); + } + else + return BAD_FUNC_ARG; +} - /* only retain actual size used */ - ret = 0; - if (idx > 0) { - if (ssl) { - if (ssl->buffers.weOwnCertChain) { - FreeDer(&ssl->buffers.certChain); - } - ret = AllocDer(&ssl->buffers.certChain, idx, type, heap); - if (ret == 0) { - XMEMCPY(ssl->buffers.certChain->buffer, chainBuffer, - idx); - ssl->buffers.weOwnCertChain = 1; - } - #ifdef WOLFSSL_TLS13 - ssl->buffers.certChainCnt = cnt; - #endif - } else if (ctx) { - FreeDer(&ctx->certChain); - ret = AllocDer(&ctx->certChain, idx, type, heap); - if (ret == 0) { - XMEMCPY(ctx->certChain->buffer, chainBuffer, idx); - } - #ifdef WOLFSSL_TLS13 - ctx->certChainCnt = cnt; - #endif - } - } - if (dynamicBuffer) - XFREE(chainBuffer, heap, DYNAMIC_TYPE_FILE); +int wolfSSL_EnableOCSPStapling(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_EnableOCSPStapling"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerEnableOCSPStapling(SSL_CM(ssl)); } - - return ret; + else + return BAD_FUNC_ARG; } -#ifndef NO_RSA -#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ - (HAVE_FIPS_VERSION > 2)) -static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - int devId) +int wolfSSL_DisableOCSPStapling(WOLFSSL* ssl) { - int ret; + WOLFSSL_ENTER("wolfSSL_DisableOCSPStapling"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerDisableOCSPStapling(SSL_CM(ssl)); + } + else + return BAD_FUNC_ARG; +} - (void)devId; +int wolfSSL_SetOCSP_OverrideURL(WOLFSSL* ssl, const char* url) +{ + WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerSetOCSPOverrideURL(SSL_CM(ssl), url); + } + else + return BAD_FUNC_ARG; +} - *idx = 0; - ret = wc_RsaPrivateKeyValidate(der->buffer, idx, keySz, der->length); -#ifdef WOLF_PRIVATE_KEY_ID - if ((ret != 0) && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || ((ssl == NULL) ? wolfSSL_CTX_IsPrivatePkSet(ctx) : - wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - #endif - )) { - word32 nSz; - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_RsaPublicKeyDecode_ex(der->buffer, idx, der->length, NULL, - &nSz, NULL, NULL); - if (ret == 0) { - *keySz = (int)nSz; - } - } -#endif - if (ret != 0) { - #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \ - !defined(HAVE_ED448) && !defined(HAVE_PQC) - WOLFSSL_MSG("RSA decode failed and other algorithms " - "not enabled to try"); - ret = WOLFSSL_BAD_FILE; - #else - if (*keyFormat == 0) { - /* Format unknown so keep trying. */ - ret = 0; /* continue trying other algorithms */ - } - #endif +int wolfSSL_SetOCSP_Cb(WOLFSSL* ssl, + CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx) +{ + WOLFSSL_ENTER("wolfSSL_SetOCSP_Cb"); + if (ssl) { + SSL_CM_WARNING(ssl); + ssl->ocspIOCtx = ioCbCtx; /* use SSL specific ioCbCtx */ + return wolfSSL_CertManagerSetOCSP_Cb(SSL_CM(ssl), + ioCb, respFreeCb, NULL); } - else { - /* check that the size of the RSA key is enough */ - int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; - if (*keySz < minRsaSz) { - ret = RSA_KEY_SIZE_E; - WOLFSSL_MSG("Private Key size too small"); - } + else + return BAD_FUNC_ARG; +} - if (ssl) { - ssl->buffers.keyType = rsa_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->privateKeyType = rsa_sa_algo; - ctx->privateKeySz = *keySz; - } +int wolfSSL_CTX_EnableOCSP(WOLFSSL_CTX* ctx, int options) +{ + WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSP"); + if (ctx) + return wolfSSL_CertManagerEnableOCSP(ctx->cm, options); + else + return BAD_FUNC_ARG; +} - *keyFormat = RSAk; - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - ssl->options.haveStaticECC = 0; - *resetSuites = 1; - } - } +int wolfSSL_CTX_DisableOCSP(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSP"); + if (ctx) + return wolfSSL_CertManagerDisableOCSP(ctx->cm); + else + return BAD_FUNC_ARG; +} - return ret; + +int wolfSSL_CTX_SetOCSP_OverrideURL(WOLFSSL_CTX* ctx, const char* url) +{ + WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL"); + if (ctx) + return wolfSSL_CertManagerSetOCSPOverrideURL(ctx->cm, url); + else + return BAD_FUNC_ARG; } -#else -static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int devId) + + +int wolfSSL_CTX_SetOCSP_Cb(WOLFSSL_CTX* ctx, CbOCSPIO ioCb, + CbOCSPRespFree respFreeCb, void* ioCbCtx) { - int ret; + WOLFSSL_ENTER("wolfSSL_CTX_SetOCSP_Cb"); + if (ctx) + return wolfSSL_CertManagerSetOCSP_Cb(ctx->cm, ioCb, + respFreeCb, ioCbCtx); + else + return BAD_FUNC_ARG; +} - /* make sure RSA key can be used */ -#ifdef WOLFSSL_SMALL_STACK - RsaKey* key; -#else - RsaKey key[1]; -#endif +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) +int wolfSSL_CTX_EnableOCSPStapling(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPStapling"); + if (ctx) + return wolfSSL_CertManagerEnableOCSPStapling(ctx->cm); + else + return BAD_FUNC_ARG; +} -#ifdef WOLFSSL_SMALL_STACK - key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA); - if (key == NULL) - return MEMORY_E; -#endif +int wolfSSL_CTX_DisableOCSPStapling(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPStapling"); + if (ctx) + return wolfSSL_CertManagerDisableOCSPStapling(ctx->cm); + else + return BAD_FUNC_ARG; +} - ret = wc_InitRsaKey_ex(key, heap, devId); - if (ret == 0) { - *idx = 0; - ret = wc_RsaPrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || ((ssl == NULL) ? wolfSSL_CTX_IsPrivatePkSet(ctx) : - wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_RsaPublicKeyDecode(der->buffer, idx, key, der->length); - } - #endif - if (ret != 0) { - #if !defined(HAVE_ECC) && !defined(HAVE_ED25519) && \ - !defined(HAVE_ED448) && !defined(HAVE_PQC) - WOLFSSL_MSG("RSA decode failed and other algorithms " - "not enabled to try"); - ret = WOLFSSL_BAD_FILE; - #else - if (*keyFormat == 0) { - /* Format unknown so keep trying. */ - ret = 0; /* continue trying other algorithms */ - } - #endif - } - else { - /* check that the size of the RSA key is enough */ - int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; - *keySz = wc_RsaEncryptSize((RsaKey*)key); - if (*keySz < minRsaSz) { - ret = RSA_KEY_SIZE_E; - WOLFSSL_MSG("Private Key size too small"); - } +int wolfSSL_CTX_EnableOCSPMustStaple(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPMustStaple"); + if (ctx) + return wolfSSL_CertManagerEnableOCSPMustStaple(ctx->cm); + else + return BAD_FUNC_ARG; +} - if (ssl) { - ssl->buffers.keyType = rsa_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->privateKeyType = rsa_sa_algo; - ctx->privateKeySz = *keySz; - } +int wolfSSL_CTX_DisableOCSPMustStaple(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPMustStaple"); + if (ctx) + return wolfSSL_CertManagerDisableOCSPMustStaple(ctx->cm); + else + return BAD_FUNC_ARG; +} +#endif /* HAVE_CERTIFICATE_STATUS_REQUEST || \ + * HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ - *keyFormat = RSAk; +#endif /* HAVE_OCSP */ - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - ssl->options.haveStaticECC = 0; - *resetSuites = 1; - } - } +#ifdef HAVE_CRL - wc_FreeRsaKey(key); +int wolfSSL_EnableCRL(WOLFSSL* ssl, int options) +{ + WOLFSSL_ENTER("wolfSSL_EnableCRL"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerEnableCRL(SSL_CM(ssl), options); } + else + return BAD_FUNC_ARG; +} -#ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_RSA); -#endif - return ret; +int wolfSSL_DisableCRL(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_DisableCRL"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerDisableCRL(SSL_CM(ssl)); + } + else + return BAD_FUNC_ARG; } -#endif -#endif /* !NO_RSA */ -#ifdef HAVE_ECC -static int ProcessBufferTryDecodeEcc(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int devId) +#ifndef NO_FILESYSTEM +int wolfSSL_LoadCRL(WOLFSSL* ssl, const char* path, int type, int monitor) { - int ret = 0; - /* make sure ECC key can be used */ -#ifdef WOLFSSL_SMALL_STACK - ecc_key* key; -#else - ecc_key key[1]; -#endif + WOLFSSL_ENTER("wolfSSL_LoadCRL"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerLoadCRL(SSL_CM(ssl), path, type, monitor); + } + else + return BAD_FUNC_ARG; +} -#ifdef WOLFSSL_SMALL_STACK - key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC); - if (key == NULL) - return MEMORY_E; +int wolfSSL_LoadCRLFile(WOLFSSL* ssl, const char* file, int type) +{ + WOLFSSL_ENTER("wolfSSL_LoadCRLFile"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerLoadCRLFile(SSL_CM(ssl), file, type); + } + else + return BAD_FUNC_ARG; +} #endif - if (wc_ecc_init_ex(key, heap, devId) == 0) { - *idx = 0; - ret = wc_EccPrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || ((ssl == NULL) ? wolfSSL_CTX_IsPrivatePkSet(ctx) : - wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_EccPublicKeyDecode(der->buffer, idx, key, der->length); - } - #endif - if (ret == 0) { - /* check for minimum ECC key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; - *keySz = wc_ecc_size(key); - if (*keySz < minKeySz) { - WOLFSSL_MSG("ECC private key too small"); - ret = ECC_KEY_SIZE_E; - } - - *keyFormat = ECDSAk; - if (ssl) { - ssl->options.haveStaticECC = 1; - ssl->buffers.keyType = ecc_dsa_sa_algo; - #ifdef WOLFSSL_SM2 - if (key->dp->id == ECC_SM2P256V1) - ssl->buffers.keyType = sm2_sa_algo; - else - #endif - ssl->buffers.keyType = ecc_dsa_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->haveStaticECC = 1; - ctx->privateKeyType = ecc_dsa_sa_algo; - #ifdef WOLFSSL_SM2 - if (key->dp->id == ECC_SM2P256V1) - ctx->privateKeyType = sm2_sa_algo; - else - #endif - ctx->privateKeyType = ecc_dsa_sa_algo; - ctx->privateKeySz = *keySz; - } - - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } - } - else if (*keyFormat == 0) { - ret = 0; /* continue trying other algorithms */ - } - - wc_ecc_free(key); +int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb) +{ + WOLFSSL_ENTER("wolfSSL_SetCRL_Cb"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerSetCRL_Cb(SSL_CM(ssl), cb); } - -#ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ECC); -#endif - return ret; + else + return BAD_FUNC_ARG; } -#endif /* HAVE_ECC */ -#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) -static int ProcessBufferTryDecodeEd25519(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int devId) +#ifdef HAVE_CRL_IO +int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb) { - int ret; - /* make sure Ed25519 key can be used */ -#ifdef WOLFSSL_SMALL_STACK - ed25519_key* key; -#else - ed25519_key key[1]; + WOLFSSL_ENTER("wolfSSL_SetCRL_Cb"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerSetCRL_IOCb(SSL_CM(ssl), cb); + } + else + return BAD_FUNC_ARG; +} #endif -#ifdef WOLFSSL_SMALL_STACK - key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap, - DYNAMIC_TYPE_ED25519); - if (key == NULL) - return MEMORY_E; -#endif +int wolfSSL_CTX_EnableCRL(WOLFSSL_CTX* ctx, int options) +{ + WOLFSSL_ENTER("wolfSSL_CTX_EnableCRL"); + if (ctx) + return wolfSSL_CertManagerEnableCRL(ctx->cm, options); + else + return BAD_FUNC_ARG; +} - ret = wc_ed25519_init_ex(key, heap, devId); - if (ret == 0) { - *idx = 0; - ret = wc_Ed25519PrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || ((ssl == NULL) ? wolfSSL_CTX_IsPrivatePkSet(ctx) : - wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_Ed25519PublicKeyDecode(der->buffer, idx, key, der->length); - } - #endif - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; - *keySz = ED25519_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("ED25519 private key too small"); - ret = ECC_KEY_SIZE_E; - } - if (ret == 0) { - if (ssl) { - ssl->buffers.keyType = ed25519_sa_algo; - ssl->buffers.keySz = *keySz; - } - else { - ctx->privateKeyType = ed25519_sa_algo; - ctx->privateKeySz = *keySz; - } - *keyFormat = ED25519k; - if (ssl != NULL) { -#if !defined(WOLFSSL_NO_CLIENT_AUTH) && !defined(NO_ED25519_CLIENT_AUTH) - /* ED25519 requires caching enabled for tracking message - * hash used in EdDSA_Update for signing */ - ssl->options.cacheMessages = 1; -#endif - if (ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } - } - } - } - else if (*keyFormat == 0) { - ret = 0; /* continue trying other algorithms */ - } +int wolfSSL_CTX_DisableCRL(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_DisableCRL"); + if (ctx) + return wolfSSL_CertManagerDisableCRL(ctx->cm); + else + return BAD_FUNC_ARG; +} - wc_ed25519_free(key); - } -#ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ED25519); -#endif - return ret; +#ifndef NO_FILESYSTEM +int wolfSSL_CTX_LoadCRL(WOLFSSL_CTX* ctx, const char* path, + int type, int monitor) +{ + WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL"); + if (ctx) + return wolfSSL_CertManagerLoadCRL(ctx->cm, path, type, monitor); + else + return BAD_FUNC_ARG; } -#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ -#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) -static int ProcessBufferTryDecodeEd448(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int devId) +int wolfSSL_CTX_LoadCRLFile(WOLFSSL_CTX* ctx, const char* file, + int type) { - int ret; - /* make sure Ed448 key can be used */ -#ifdef WOLFSSL_SMALL_STACK - ed448_key* key = NULL; -#else - ed448_key key[1]; + WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL"); + if (ctx) + return wolfSSL_CertManagerLoadCRLFile(ctx->cm, file, type); + else + return BAD_FUNC_ARG; +} #endif -#ifdef WOLFSSL_SMALL_STACK - key = (ed448_key*)XMALLOC(sizeof(ed448_key), heap, DYNAMIC_TYPE_ED448); - if (key == NULL) - return MEMORY_E; + +int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb) +{ + WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_Cb"); + if (ctx) + return wolfSSL_CertManagerSetCRL_Cb(ctx->cm, cb); + else + return BAD_FUNC_ARG; +} + +#ifdef HAVE_CRL_IO +int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb) +{ + WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_IOCb"); + if (ctx) + return wolfSSL_CertManagerSetCRL_IOCb(ctx->cm, cb); + else + return BAD_FUNC_ARG; +} #endif - ret = wc_ed448_init_ex(key, heap, devId); - if (ret == 0) { - *idx = 0; - ret = wc_Ed448PrivateKeyDecode(der->buffer, idx, key, der->length); - #ifdef WOLF_PRIVATE_KEY_ID - if (ret != 0 && (devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || ((ssl == NULL) ? wolfSSL_CTX_IsPrivatePkSet(ctx) : - wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - #endif - )) { - /* if using crypto or PK callbacks, try public key decode */ - *idx = 0; - ret = wc_Ed448PublicKeyDecode(der->buffer, idx, key, der->length); - } - #endif - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; - *keySz = ED448_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("ED448 private key too small"); - ret = ECC_KEY_SIZE_E; - } - } - if (ret == 0) { - if (ssl) { - ssl->buffers.keyType = ed448_sa_algo; - ssl->buffers.keySz = *keySz; - } - else if (ctx) { - ctx->privateKeyType = ed448_sa_algo; - ctx->privateKeySz = *keySz; - } - - *keyFormat = ED448k; - if (ssl != NULL) { - /* ED448 requires caching enabled for tracking message - * hash used in EdDSA_Update for signing */ - ssl->options.cacheMessages = 1; - if (ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } - } - } - else if (*keyFormat == 0) { - ret = 0; /* continue trying other algorithms */ - } - wc_ed448_free(key); +#endif /* HAVE_CRL */ + + +/* Sets the max chain depth when verifying a certificate chain. Default depth + * is set to MAX_CHAIN_DEPTH. + * + * ctx WOLFSSL_CTX structure to set depth in + * depth max depth + */ +void wolfSSL_CTX_set_verify_depth(WOLFSSL_CTX *ctx, int depth) { + WOLFSSL_ENTER("wolfSSL_CTX_set_verify_depth"); + + if (ctx == NULL || depth < 0 || depth > MAX_CHAIN_DEPTH) { + WOLFSSL_MSG("Bad depth argument, too large or less than 0"); + return; } -#ifdef WOLFSSL_SMALL_STACK - XFREE(key, heap, DYNAMIC_TYPE_ED448); -#endif - return ret; + ctx->verifyDepth = (byte)depth; } -#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ -#if defined(HAVE_PQC) -#if defined(HAVE_FALCON) -static int ProcessBufferTryDecodeFalcon(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int type) + +/* get cert chaining depth using ssl struct */ +long wolfSSL_get_verify_depth(WOLFSSL* ssl) { - int ret; - /* make sure Falcon key can be used */ - falcon_key* key = (falcon_key*)XMALLOC(sizeof(falcon_key), heap, - DYNAMIC_TYPE_FALCON); - (void) type; - if (key == NULL) { - return MEMORY_E; + if(ssl == NULL) { + return BAD_FUNC_ARG; } - ret = wc_falcon_init(key); - if (ret == 0) { - if (*keyFormat == FALCON_LEVEL1k) { - ret = wc_falcon_set_level(key, 1); - } - else if (*keyFormat == FALCON_LEVEL5k) { - ret = wc_falcon_set_level(key, 5); - } - else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - wc_falcon_free(key); - ret = ALGO_ID_E; - } +#ifndef OPENSSL_EXTRA + return MAX_CHAIN_DEPTH; +#else + return ssl->options.verifyDepth; +#endif +} + + +/* get cert chaining depth using ctx struct */ +long wolfSSL_CTX_get_verify_depth(WOLFSSL_CTX* ctx) +{ + if (ctx == NULL) { + return BAD_FUNC_ARG; } +#ifndef OPENSSL_EXTRA + return MAX_CHAIN_DEPTH; +#else + return ctx->verifyDepth; +#endif +} - if (ret == 0) { - *idx = 0; - ret = wc_falcon_import_private_only(der->buffer, der->length, key); - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minFalconKeySz : - ctx->minFalconKeySz; - *keySz = FALCON_MAX_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("Falcon private key too small"); - ret = FALCON_KEY_SIZE_E; - } - if (ssl) { -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (type == ALT_PRIVATEKEY_TYPE) { - if (*keyFormat == FALCON_LEVEL1k) { - ssl->buffers.altKeyType = falcon_level1_sa_algo; - } - else { - ssl->buffers.altKeyType = falcon_level5_sa_algo; - } - ssl->buffers.altKeySz = *keySz; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - { - if (*keyFormat == FALCON_LEVEL1k) { - ssl->buffers.keyType = falcon_level1_sa_algo; - } - else { - ssl->buffers.keyType = falcon_level5_sa_algo; - } - ssl->buffers.keySz = *keySz; - } - } - else { -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (type == ALT_PRIVATEKEY_TYPE) { - if (*keyFormat == FALCON_LEVEL1k) { - ctx->altPrivateKeyType = falcon_level1_sa_algo; - } - else { - ctx->altPrivateKeyType = falcon_level5_sa_algo; - } - ctx->altPrivateKeySz = *keySz; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - { - if (*keyFormat == FALCON_LEVEL1k) { - ctx->privateKeyType = falcon_level1_sa_algo; - } - else { - ctx->privateKeyType = falcon_level5_sa_algo; - } - ctx->privateKeySz = *keySz; - } - } +#ifndef NO_CHECK_PRIVATE_KEY - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } - } - else if (*keyFormat == 0) { - ret = 0; /* continue trying other algorithms */ - } +#ifdef WOLF_PRIVATE_KEY_ID +/* Check private against public in certificate for match using external + * device with given devId */ +static int check_cert_key_dev(word32 keyOID, byte* privKey, word32 privSz, + const byte* pubKey, word32 pubSz, int label, int id, void* heap, int devId) +{ + int ret = 0; + int type = 0; + void *pkey = NULL; - wc_falcon_free(key); + if (privKey == NULL) { + return MISSING_KEY; } - XFREE(key, heap, DYNAMIC_TYPE_FALCON); - return ret; -} -#endif +#ifndef NO_RSA + if (keyOID == RSAk) { + type = DYNAMIC_TYPE_RSA; + } +#ifdef WC_RSA_PSS + if (keyOID == RSAPSSk) { + type = DYNAMIC_TYPE_RSA; + } +#endif +#endif +#ifdef HAVE_ECC + if (keyOID == ECDSAk) { + type = DYNAMIC_TYPE_ECC; + } +#endif #if defined(HAVE_DILITHIUM) -static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int type) -{ - int ret; - /* make sure Dilithium key can be used */ - dilithium_key* key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, - DYNAMIC_TYPE_DILITHIUM); - (void) type; - if (key == NULL) { - return MEMORY_E; + if ((keyOID == DILITHIUM_LEVEL2k) || + (keyOID == DILITHIUM_LEVEL3k) || + (keyOID == DILITHIUM_LEVEL5k)) { + type = DYNAMIC_TYPE_DILITHIUM; + } +#endif +#if defined(HAVE_FALCON) + if ((keyOID == FALCON_LEVEL1k) || + (keyOID == FALCON_LEVEL5k)) { + type = DYNAMIC_TYPE_FALCON; } - ret = wc_dilithium_init(key); +#endif + + ret = CreateDevPrivateKey(&pkey, privKey, privSz, type, label, id, + heap, devId); + #ifdef WOLF_CRYPTO_CB if (ret == 0) { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ret = wc_dilithium_set_level(key, 2); + #ifndef NO_RSA + if (keyOID == RSAk + #ifdef WC_RSA_PSS + || keyOID == RSAPSSk + #endif + ) { + ret = wc_CryptoCb_RsaCheckPrivKey((RsaKey*)pkey, pubKey, pubSz); } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ret = wc_dilithium_set_level(key, 3); + #endif + #ifdef HAVE_ECC + if (keyOID == ECDSAk) { + ret = wc_CryptoCb_EccCheckPrivKey((ecc_key*)pkey, pubKey, pubSz); } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ret = wc_dilithium_set_level(key, 5); + #endif + #if defined(HAVE_DILITHIUM) + if ((keyOID == DILITHIUM_LEVEL2k) || + (keyOID == DILITHIUM_LEVEL3k) || + (keyOID == DILITHIUM_LEVEL5k)) { + ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey, + WC_PQC_SIG_TYPE_DILITHIUM, + pubKey, pubSz); } - else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - wc_dilithium_free(key); - ret = ALGO_ID_E; + #endif + #if defined(HAVE_FALCON) + if ((keyOID == FALCON_LEVEL1k) || + (keyOID == FALCON_LEVEL5k)) { + ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey, + WC_PQC_SIG_TYPE_FALCON, + pubKey, pubSz); } + #endif } - - if (ret == 0) { - *idx = 0; - ret = wc_dilithium_import_private_only(der->buffer, der->length, key); - if (ret == 0) { - /* check for minimum key size and then free */ - int minKeySz = ssl ? ssl->options.minDilithiumKeySz : - ctx->minDilithiumKeySz; - *keySz = DILITHIUM_MAX_KEY_SIZE; - if (*keySz < minKeySz) { - WOLFSSL_MSG("Dilithium private key too small"); - ret = DILITHIUM_KEY_SIZE_E; - } - if (ssl) { -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (type == ALT_PRIVATEKEY_TYPE) { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ssl->buffers.altKeyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ssl->buffers.altKeyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ssl->buffers.altKeyType = dilithium_level5_sa_algo; - } - ssl->buffers.altKeySz = *keySz; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ssl->buffers.keyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ssl->buffers.keyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ssl->buffers.keyType = dilithium_level5_sa_algo; - } - ssl->buffers.keySz = *keySz; - } - } - else { -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (type == ALT_PRIVATEKEY_TYPE) { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ctx->altPrivateKeyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ctx->altPrivateKeyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ctx->altPrivateKeyType = dilithium_level5_sa_algo; - } - ctx->altPrivateKeySz = *keySz; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - { - if (*keyFormat == DILITHIUM_LEVEL2k) { - ctx->privateKeyType = dilithium_level2_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - ctx->privateKeyType = dilithium_level3_sa_algo; - } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - ctx->privateKeyType = dilithium_level5_sa_algo; - } - ctx->privateKeySz = *keySz; - } - } - - if (ssl && ssl->options.side == WOLFSSL_SERVER_END) { - *resetSuites = 1; - } + #else + /* devId was set, don't check, for now */ + /* TODO: Add callback for private key check? */ + (void) pubKey; + (void) pubSz; + #endif + if (pkey != NULL) { + #ifndef NO_RSA + if (keyOID == RSAk + #ifdef WC_RSA_PSS + || keyOID == RSAPSSk + #endif + ) { + wc_FreeRsaKey((RsaKey*)pkey); } - else if (*keyFormat == 0) { - ret = 0; /* continue trying other algorithms */ + #endif + #ifdef HAVE_ECC + if (keyOID == ECDSAk) { + wc_ecc_free((ecc_key*)pkey); } - - wc_dilithium_free(key); + #endif + #if defined(HAVE_DILITHIUM) + if ((keyOID == DILITHIUM_LEVEL2k) || + (keyOID == DILITHIUM_LEVEL3k) || + (keyOID == DILITHIUM_LEVEL5k)) { + wc_dilithium_free((dilithium_key*)pkey); + } + #endif + #if defined(HAVE_FALCON) + if ((keyOID == FALCON_LEVEL1k) || + (keyOID == FALCON_LEVEL5k)) { + wc_falcon_free((falcon_key*)pkey); + } + #endif + XFREE(pkey, heap, type); } - XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); return ret; } -#endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ +#endif /* WOLF_PRIVATE_KEY_ID */ -static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - DerBuffer* der, int* keySz, word32* idx, int* resetSuites, int* keyFormat, - void* heap, int devId, int type) +/* Check private against public in certificate for match + * + * Returns WOLFSSL_SUCCESS on good private key + * WOLFSSL_FAILURE if mismatched */ +static int check_cert_key(DerBuffer* cert, DerBuffer* key, DerBuffer* altKey, + void* heap, int devId, int isKeyLabel, int isKeyId, int altDevId, + int isAltKeyLabel, int isAltKeyId) { - int ret = 0; - - (void)heap; - (void)devId; - (void)type; - - if (ctx == NULL && ssl == NULL) - return BAD_FUNC_ARG; - if (!der || !keySz || !idx || !resetSuites || !keyFormat) - return BAD_FUNC_ARG; - -#ifndef NO_RSA - if ((*keyFormat == 0 || *keyFormat == RSAk)) { -#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ - (HAVE_FIPS_VERSION > 2)) - ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keySz, idx, resetSuites, - keyFormat, devId); +#ifdef WOLFSSL_SMALL_STACK + DecodedCert* der = NULL; #else - ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keySz, idx, resetSuites, - keyFormat, heap, devId); + DecodedCert der[1]; #endif - if (ret != 0) - return ret; + word32 size; + byte* buff; + int ret = WOLFSSL_FAILURE; + + WOLFSSL_ENTER("check_cert_key"); + + if (cert == NULL || key == NULL) { + return WOLFSSL_FAILURE; } + +#ifdef WOLFSSL_SMALL_STACK + der = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap, DYNAMIC_TYPE_DCERT); + if (der == NULL) + return MEMORY_E; #endif -#ifdef HAVE_ECC - if ((*keyFormat == 0) || (*keyFormat == ECDSAk) - #ifdef WOLFSSL_SM2 - || (*keyFormat == SM2k) + + size = cert->length; + buff = cert->buffer; + InitDecodedCert_ex(der, buff, size, heap, devId); + if (ParseCertRelative(der, CERT_TYPE, NO_VERIFY, NULL, NULL) != 0) { + FreeDecodedCert(der); + #ifdef WOLFSSL_SMALL_STACK + XFREE(der, heap, DYNAMIC_TYPE_DCERT); #endif - ) { - ret = ProcessBufferTryDecodeEcc(ctx, ssl, der, keySz, idx, resetSuites, - keyFormat, heap, devId); - if (ret != 0) - return ret; + return WOLFSSL_FAILURE; } -#endif /* HAVE_ECC */ -#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) - if ((*keyFormat == 0 || *keyFormat == ED25519k)) { - ret = ProcessBufferTryDecodeEd25519(ctx, ssl, der, keySz, idx, - resetSuites, keyFormat, heap, devId); - if (ret != 0) - return ret; + + size = key->length; + buff = key->buffer; +#ifdef WOLF_PRIVATE_KEY_ID + if (devId != INVALID_DEVID) { + ret = check_cert_key_dev(der->keyOID, buff, size, der->publicKey, + der->pubKeySize, isKeyLabel, isKeyId, heap, + devId); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; + } } -#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ -#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) - if ((*keyFormat == 0 || *keyFormat == ED448k)) { - ret = ProcessBufferTryDecodeEd448(ctx, ssl, der, keySz, idx, - resetSuites, keyFormat, heap, devId); - if (ret != 0) - return ret; + else { + /* fall through if unavailable */ + ret = CRYPTOCB_UNAVAILABLE; } -#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ -#if defined(HAVE_PQC) -#if defined(HAVE_FALCON) - if (((*keyFormat == 0) || (*keyFormat == FALCON_LEVEL1k) || - (*keyFormat == FALCON_LEVEL5k))) { - ret = ProcessBufferTryDecodeFalcon(ctx, ssl, der, keySz, idx, - resetSuites, keyFormat, heap, type); - if (ret != 0) - return ret; + + if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) +#endif /* WOLF_PRIVATE_KEY_ID */ + { + ret = wc_CheckPrivateKeyCert(buff, size, der, 0); + ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; } -#endif /* HAVE_FALCON */ -#if defined(HAVE_DILITHIUM) - if ((*keyFormat == 0) || - (*keyFormat == DILITHIUM_LEVEL2k) || - (*keyFormat == DILITHIUM_LEVEL3k) || - (*keyFormat == DILITHIUM_LEVEL5k)) { - ret = ProcessBufferTryDecodeDilithium(ctx, ssl, der, keySz, idx, - resetSuites, keyFormat, heap, type); - if (ret != 0) { - return ret; + +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (ret == WOLFSSL_SUCCESS && der->extSapkiSet && der->sapkiDer != NULL) { + /* Certificate contains an alternative public key. Hence, we also + * need an alternative private key. */ + if (altKey == NULL) { + ret = MISSING_KEY; + buff = NULL; + size = 0; + } + else { + size = altKey->length; + buff = altKey->buffer; + } +#ifdef WOLF_PRIVATE_KEY_ID + if (ret == WOLFSSL_SUCCESS && altDevId != INVALID_DEVID) { + /* We have to decode the public key first */ + word32 idx = 0; + /* Dilithium has the largest public key at the moment */ + word32 pubKeyLen = DILITHIUM_MAX_PUB_KEY_SIZE; + byte* decodedPubKey = (byte*)XMALLOC(pubKeyLen, heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (decodedPubKey == NULL) { + ret = MEMORY_E; + } + if (ret == WOLFSSL_SUCCESS) { + if (der->sapkiOID == RSAk || der->sapkiOID == ECDSAk) { + /* Simply copy the data */ + XMEMCPY(decodedPubKey, der->sapkiDer, der->sapkiLen); + pubKeyLen = der->sapkiLen; + ret = 0; + } + else { + ret = DecodeAsymKeyPublic(der->sapkiDer, &idx, + der->sapkiLen, decodedPubKey, + &pubKeyLen, der->sapkiOID); + } + } + if (ret == 0) { + ret = check_cert_key_dev(der->sapkiOID, buff, size, + decodedPubKey, pubKeyLen, + isAltKeyLabel, isAltKeyId, + heap, altDevId); + } + XFREE(decodedPubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; + } + } + else { + /* fall through if unavailable */ + ret = CRYPTOCB_UNAVAILABLE; + } + + if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) +#endif /* WOLF_PRIVATE_KEY_ID */ + { + ret = wc_CheckPrivateKeyCert(buff, size, der, 1); + ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; } } -#endif /* HAVE_DILITHIUM */ -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + FreeDecodedCert(der); +#ifdef WOLFSSL_SMALL_STACK + XFREE(der, heap, DYNAMIC_TYPE_DCERT); +#endif + + (void)devId; + (void)isKeyLabel; + (void)isKeyId; + (void)altKey; + (void)altDevId; + (void)isAltKeyLabel; + (void)isAltKeyId; + return ret; } -/* process the buffer buff, length sz, into ctx of format and type - used tracks bytes consumed, userChain specifies a user cert chain - to pass during the handshake */ -int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, - long sz, int format, int type, WOLFSSL* ssl, - long* used, int userChain, int verify) -{ - DerBuffer* der = NULL; - int ret = 0; - int done = 0; - int keyFormat = 0; - int resetSuites = 0; - void* heap = wolfSSL_CTX_GetHeap(ctx, ssl); - int devId = wolfSSL_CTX_GetDevId(ctx, ssl); - word32 idx = 0; - int keySz = 0; -#if (defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)) || \ - defined(HAVE_PKCS8) - word32 algId = 0; +/* Check private against public in certificate for match + * + * ctx WOLFSSL_CTX structure to check private key in + * + * Returns WOLFSSL_SUCCESS on good private key + * WOLFSSL_FAILURE if mismatched. */ +int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx) +{ + int res; + + if (ctx == NULL) { + return WOLFSSL_FAILURE; + } + +#ifdef WOLFSSL_DUAL_ALG_CERTS +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask); + wolfssl_priv_der_unblind(ctx->altPrivateKey, ctx->altPrivateKeyMask); +#endif + res = check_cert_key(ctx->certificate, ctx->privateKey, ctx->altPrivateKey, + ctx->heap, ctx->privateKeyDevId, ctx->privateKeyLabel, + ctx->privateKeyId, ctx->altPrivateKeyDevId, ctx->altPrivateKeyLabel, + ctx->altPrivateKeyId) != 0; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + { + int ret; + ret = wolfssl_priv_der_blind(NULL, ctx->privateKey, + (DerBuffer**)&ctx->privateKeyMask); + if (ret == 0) { + ret = wolfssl_priv_der_blind(NULL, ctx->altPrivateKey, + (DerBuffer**)&ctx->altPrivateKeyMask); + } + if (ret != 0) { + res = WOLFSSL_FAILURE; + } + } #endif -#ifdef WOLFSSL_SMALL_STACK - EncryptedInfo* info = NULL; #else - EncryptedInfo info[1]; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask); +#endif + res = check_cert_key(ctx->certificate, ctx->privateKey, NULL, ctx->heap, + ctx->privateKeyDevId, ctx->privateKeyLabel, ctx->privateKeyId, + INVALID_DEVID, 0, 0); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + { + int ret = wolfssl_priv_der_blind(NULL, ctx->privateKey, + (DerBuffer**)&ctx->privateKeyMask); + if (ret != 0) { + res = WOLFSSL_FAILURE; + } + } +#endif #endif - (void)devId; - (void)idx; - (void)keySz; - - if (used) - *used = sz; /* used bytes default to sz, PEM chain may shorten*/ + return res; +} +#endif /* !NO_CHECK_PRIVATE_KEY */ - /* check args */ - if (format != WOLFSSL_FILETYPE_ASN1 && format != WOLFSSL_FILETYPE_PEM) - return WOLFSSL_BAD_FILETYPE; +#ifdef OPENSSL_ALL +/** + * Return the private key of the WOLFSSL_CTX struct + * @return WOLFSSL_EVP_PKEY* The caller doesn *NOT*` free the returned object. + */ +WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx) +{ + WOLFSSL_EVP_PKEY* res; + const unsigned char *key; + int type; - if (ctx == NULL && ssl == NULL) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wolfSSL_CTX_get0_privatekey"); - /* This API does not handle CHAIN_CERT_TYPE */ - if (type == CHAIN_CERT_TYPE) - return BAD_FUNC_ARG; + if (ctx == NULL || ctx->privateKey == NULL || + ctx->privateKey->buffer == NULL) { + WOLFSSL_MSG("Bad parameter or key not set"); + return NULL; + } -#ifdef WOLFSSL_SMALL_STACK - info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), heap, - DYNAMIC_TYPE_ENCRYPTEDINFO); - if (info == NULL) - return MEMORY_E; + switch (ctx->privateKeyType) { +#ifndef NO_RSA + case rsa_sa_algo: + type = EVP_PKEY_RSA; + break; +#endif +#ifdef HAVE_ECC + case ecc_dsa_sa_algo: + type = EVP_PKEY_EC; + break; +#endif +#ifdef WOLFSSL_SM2 + case sm2_sa_algo: + type = EVP_PKEY_EC; + break; #endif + default: + /* Other key types not supported either as ssl private keys + * or in the EVP layer */ + WOLFSSL_MSG("Unsupported key type"); + return NULL; + } - XMEMSET(info, 0, sizeof(EncryptedInfo)); -#if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) - if (ctx) { - info->passwd_cb = ctx->passwd_cb; - info->passwd_userdata = ctx->passwd_userdata; + key = ctx->privateKey->buffer; + + if (ctx->privateKeyPKey != NULL) { + res = ctx->privateKeyPKey; + } + else { + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask); + #endif + res = wolfSSL_d2i_PrivateKey(type, + (WOLFSSL_EVP_PKEY**)&ctx->privateKeyPKey, &key, + (long)ctx->privateKey->length); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ctx->privateKey, ctx->privateKeyMask); + #endif } + + return res; +} #endif - if (format == WOLFSSL_FILETYPE_PEM) { - #ifdef WOLFSSL_PEM_TO_DER - ret = PemToDer(buff, sz, type, &der, heap, info, &keyFormat); - #else - ret = NOT_COMPILED_IN; +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) + +#if !defined(NO_RSA) +static int d2iTryRsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + word32 keyIdx = 0; + int isRsaKey; + int ret = 1; +#ifndef WOLFSSL_SMALL_STACK + RsaKey rsa[1]; +#else + RsaKey *rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA); + if (rsa == NULL) + return 0; +#endif + + XMEMSET(rsa, 0, sizeof(RsaKey)); + + if (wc_InitRsaKey(rsa, NULL) != 0) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(rsa, NULL, DYNAMIC_TYPE_RSA); #endif + return 0; + } + /* test if RSA key */ + if (priv) { + isRsaKey = + (wc_RsaPrivateKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0); } else { - /* ASN1 (DER) */ - int length = (int)sz; - word32 inOutIdx = 0; - /* get length of der (read sequence or octet string) */ - if (GetSequence(buff, &inOutIdx, &length, (word32)sz) >= 0) { - length += inOutIdx; /* include leading sequence */ - } - /* get length using octet string (allowed for private key types) */ - else if (type == PRIVATEKEY_TYPE && - GetOctetString(buff, &inOutIdx, &length, (word32)sz) >= 0) { - length += inOutIdx; /* include leading oct string */ - } - else { - ret = ASN_PARSE_E; - } + isRsaKey = + (wc_RsaPublicKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0); + } + wc_FreeRsaKey(rsa); +#ifdef WOLFSSL_SMALL_STACK + XFREE(rsa, NULL, DYNAMIC_TYPE_RSA); +#endif - info->consumed = length; + if (!isRsaKey) { + return -1; + } - if (ret == 0) { - ret = AllocDer(&der, (word32)length, type, heap); - if (ret == 0) { - XMEMCPY(der->buffer, buff, length); - } - - #ifdef HAVE_PKCS8 - /* if private key try and remove PKCS8 header */ - if (ret == 0 && type == PRIVATEKEY_TYPE) { - if ((ret = ToTraditional_ex(der->buffer, der->length, - &algId)) > 0) { - /* Found PKCS8 header */ - /* ToTraditional_ex moves buff and returns adjusted length */ - der->length = ret; - keyFormat = algId; - } - ret = 0; /* failures should be ignored */ - } - #endif + if (*out != NULL) { + pkey = *out; + } + else { + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("RSA wolfSSL_EVP_PKEY_new error"); + return 0; } } - if (used) { - *used = info->consumed; + pkey->pkey_sz = (int)keyIdx; + pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + priv ? DYNAMIC_TYPE_PRIVATE_KEY : + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkey->pkey.ptr == NULL) { + ret = 0; } + if (ret == 1) { + XMEMCPY(pkey->pkey.ptr, mem, keyIdx); + pkey->type = EVP_PKEY_RSA; - /* process user chain */ - if (ret >= 0) { - /* Chain should have server cert first, then intermediates, then root. - * First certificate in chain is processed below after ProcessUserChain - * and is loaded into ssl->buffers.certificate. - * Remainder are processed using ProcessUserChain and are loaded into - * ssl->buffers.certChain. */ - if (userChain) { - ret = ProcessUserChain(ctx, buff, sz, format, CHAIN_CERT_TYPE, ssl, - used, info, verify); - if (ret == ASN_NO_PEM_HEADER) { /* Additional chain is optional */ - unsigned long pemErr = 0; - CLEAR_ASN_NO_PEM_HEADER_ERROR(pemErr); - ret = 0; - } + pkey->ownRsa = 1; + pkey->rsa = wolfssl_rsa_d2i(NULL, mem, memSz, + priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC); + if (pkey->rsa == NULL) { + ret = 0; } } - /* info is only used for private key with DER or PEM, so free now */ - if (ret < 0 || type != PRIVATEKEY_TYPE) { + if (ret == 1) { + *out = pkey; + } + + if ((ret == 0) && (*out == NULL)) { + wolfSSL_EVP_PKEY_free(pkey); + } + return ret; +} +#endif /* !NO_RSA */ + +#if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) +static int d2iTryEccKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + word32 keyIdx = 0; + int isEccKey; + int ret = 1; +#ifndef WOLFSSL_SMALL_STACK + ecc_key ecc[1]; +#else + ecc_key *ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, + DYNAMIC_TYPE_ECC); + if (ecc == NULL) + return 0; +#endif + + XMEMSET(ecc, 0, sizeof(ecc_key)); + + if (wc_ecc_init(ecc) != 0) { #ifdef WOLFSSL_SMALL_STACK - XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); + XFREE(ecc, NULL, DYNAMIC_TYPE_ECC); #endif + return 0; } - /* check for error */ - if (ret < 0) { - FreeDer(&der); - done = 1; + if (priv) { + isEccKey = + (wc_EccPrivateKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0); + } + else { + isEccKey = + (wc_EccPublicKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0); } + wc_ecc_free(ecc); +#ifdef WOLFSSL_SMALL_STACK + XFREE(ecc, NULL, DYNAMIC_TYPE_ECC); +#endif - if (done == 1) { - /* No operation, just skip the next section */ + if (!isEccKey) { + return -1; } - /* Handle DER owner */ - else if (type == CA_TYPE) { - if (ctx == NULL) { - WOLFSSL_MSG("Need context for CA load"); - FreeDer(&der); - return BAD_FUNC_ARG; - } - /* verify CA unless user set to no verify */ - ret = AddCA(ctx->cm, &der, WOLFSSL_USER_CA, verify); - done = 1; + + if (*out != NULL) { + pkey = *out; } -#ifdef WOLFSSL_TRUST_PEER_CERT - else if (type == TRUSTED_PEER_TYPE) { - /* add trusted peer cert. der is freed within */ - if (ctx != NULL) - ret = AddTrustedPeer(ctx->cm, &der, verify); - else { - SSL_CM_WARNING(ssl); - ret = AddTrustedPeer(SSL_CM(ssl), &der, verify); - } - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error adding trusted peer"); + else { + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("ECC wolfSSL_EVP_PKEY_new error"); + return 0; } - done = 1; } -#endif /* WOLFSSL_TRUST_PEER_CERT */ - else if (type == CERT_TYPE) { - if (ssl != NULL) { - /* Make sure previous is free'd */ - if (ssl->buffers.weOwnCert) { - FreeDer(&ssl->buffers.certificate); - #ifdef KEEP_OUR_CERT - wolfSSL_X509_free(ssl->ourCert); - ssl->ourCert = NULL; - #endif - } - ssl->buffers.certificate = der; - #ifdef KEEP_OUR_CERT - ssl->keepCert = 1; /* hold cert for ssl lifetime */ - #endif - ssl->buffers.weOwnCert = 1; - } - else if (ctx != NULL) { - FreeDer(&ctx->certificate); /* Make sure previous is free'd */ - #ifdef KEEP_OUR_CERT - if (ctx->ourCert) { - if (ctx->ownOurCert) - wolfSSL_X509_free(ctx->ourCert); - ctx->ourCert = NULL; - } - #endif - ctx->certificate = der; - } + + pkey->pkey_sz = (int)keyIdx; + pkey->pkey.ptr = (char*)XMALLOC(keyIdx, NULL, + priv ? DYNAMIC_TYPE_PRIVATE_KEY : + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkey->pkey.ptr == NULL) { + ret = 0; } - else if (type == PRIVATEKEY_TYPE) { - if (ssl != NULL) { - /* Make sure previous is free'd */ - if (ssl->buffers.weOwnKey) { - ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length); - FreeDer(&ssl->buffers.key); - } - ssl->buffers.key = der; -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("SSL Buffers key", der->buffer, der->length); -#endif - ssl->buffers.weOwnKey = 1; - } - else if (ctx != NULL) { - if (ctx->privateKey != NULL && ctx->privateKey->buffer != NULL) { - ForceZero(ctx->privateKey->buffer, ctx->privateKey->length); - } - FreeDer(&ctx->privateKey); - ctx->privateKey = der; -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("CTX private key", der->buffer, der->length); -#endif + if (ret == 1) { + XMEMCPY(pkey->pkey.ptr, mem, keyIdx); + pkey->type = EVP_PKEY_EC; + + pkey->ownEcc = 1; + pkey->ecc = wolfSSL_EC_KEY_new(); + if (pkey->ecc == NULL) { + ret = 0; } } -#ifdef WOLFSSL_DUAL_ALG_CERTS - else if (type == ALT_PRIVATEKEY_TYPE) { - if (ssl != NULL) { - /* Make sure previous is free'd */ - if (ssl->buffers.weOwnAltKey) { - ForceZero(ssl->buffers.altKey->buffer, - ssl->buffers.altKey->length); - FreeDer(&ssl->buffers.altKey); - } - ssl->buffers.altKey = der; -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("SSL Buffers key", der->buffer, der->length); -#endif - ssl->buffers.weOwnAltKey = 1; - } - else if (ctx != NULL) { - if (ctx->altPrivateKey != NULL && - ctx->altPrivateKey->buffer != NULL) { - ForceZero(ctx->altPrivateKey->buffer, - ctx->altPrivateKey->length); - } - FreeDer(&ctx->altPrivateKey); - ctx->altPrivateKey = der; -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("CTX private key", der->buffer, der->length); + if ((ret == 1) && (wolfSSL_EC_KEY_LoadDer_ex(pkey->ecc, + (const unsigned char*)pkey->pkey.ptr, + pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE + : WOLFSSL_RSA_LOAD_PUBLIC) != 1)) { + ret = 0; + } + if (ret == 1) { + *out = pkey; + } + + if ((ret == 0) && (*out == NULL)) { + wolfSSL_EVP_PKEY_free(pkey); + } + return ret; +} +#endif /* HAVE_ECC && OPENSSL_EXTRA */ + +#if !defined(NO_DSA) +static int d2iTryDsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + word32 keyIdx = 0; + int isDsaKey; + int ret = 1; +#ifndef WOLFSSL_SMALL_STACK + DsaKey dsa[1]; +#else + DsaKey *dsa = (DsaKey*)XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA); + if (dsa == NULL) + return 0; #endif - } + + XMEMSET(dsa, 0, sizeof(DsaKey)); + + if (wc_InitDsaKey(dsa) != 0) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(dsa, NULL, DYNAMIC_TYPE_DSA); + #endif + return 0; + } + + if (priv) { + isDsaKey = + (wc_DsaPrivateKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0); } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ else { - FreeDer(&der); - return WOLFSSL_BAD_CERTTYPE; + isDsaKey = + (wc_DsaPublicKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0); } + wc_FreeDsaKey(dsa); +#ifdef WOLFSSL_SMALL_STACK + XFREE(dsa, NULL, DYNAMIC_TYPE_DSA); +#endif - if (done == 1) { - /* No operation, just skip the next section */ + /* test if DSA key */ + if (!isDsaKey) { + return -1; } - else if (type == PRIVATEKEY_TYPE -#ifdef WOLFSSL_DUAL_ALG_CERTS - || type == ALT_PRIVATEKEY_TYPE -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - ) { - ret = ProcessBufferTryDecode(ctx, ssl, der, &keySz, &idx, &resetSuites, - &keyFormat, heap, devId, type); - - #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) - /* for WOLFSSL_FILETYPE_PEM, PemToDer manages the decryption */ - /* If private key type PKCS8 header wasn't already removed (algoId == 0) */ - if ((ret != 0 || keyFormat == 0) - && format != WOLFSSL_FILETYPE_PEM && info->passwd_cb && algId == 0) - { - int passwordSz = NAME_SZ; - #ifndef WOLFSSL_SMALL_STACK - char password[NAME_SZ]; - #else - char* password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING); - if (password == NULL) { - XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); - FreeDer(&der); - return MEMORY_E; - } - #endif - /* get password */ - ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ, - info->passwd_userdata); - if (ret >= 0) { - passwordSz = ret; - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("ProcessBuffer password", password, passwordSz); - #endif - /* PKCS8 decrypt */ - ret = ToTraditionalEnc(der->buffer, der->length, - password, passwordSz, &algId); - if (ret >= 0) { - ForceZero(der->buffer + ret, der->length - ret); - der->length = ret; - } - /* ignore failures and try parsing as unencrypted */ + if (*out != NULL) { + pkey = *out; + } + else { + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("DSA wolfSSL_EVP_PKEY_new error"); + return 0; + } + } - ForceZero(password, passwordSz); - } + pkey->pkey_sz = (int)keyIdx; + pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + priv ? DYNAMIC_TYPE_PRIVATE_KEY : + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkey->pkey.ptr == NULL) { + ret = 0; + } + if (ret == 1) { + XMEMCPY(pkey->pkey.ptr, mem, keyIdx); + pkey->type = EVP_PKEY_DSA; - #ifdef WOLFSSL_SMALL_STACK - XFREE(password, heap, DYNAMIC_TYPE_STRING); - #elif defined(WOLFSSL_CHECK_MEM_ZERO) - wc_MemZero_Check(password, NAME_SZ); - #endif - ret = ProcessBufferTryDecode(ctx, ssl, der, &keySz, &idx, - &resetSuites, &keyFormat, heap, devId, type); + pkey->ownDsa = 1; + pkey->dsa = wolfSSL_DSA_new(); + if (pkey->dsa == NULL) { + ret = 0; } - #endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */ + } - if (ret != 0) { - #ifdef WOLFSSL_SMALL_STACK - XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); - #endif - return ret; - } - if (keyFormat == 0) { -#ifdef OPENSSL_EXTRA - /* Reaching this point probably means that the - * decryption password is wrong */ - if (info->passwd_cb) - EVPerr(0, EVP_R_BAD_DECRYPT); + if ((ret == 1) && (wolfSSL_DSA_LoadDer_ex(pkey->dsa, + (const unsigned char*)pkey->pkey.ptr, + pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE + : WOLFSSL_RSA_LOAD_PUBLIC) != 1)) { + ret = 0; + } + if (ret == 1) { + *out = pkey; + } + + if ((ret == 0) && (*out == NULL)) { + wolfSSL_EVP_PKEY_free(pkey); + } + return ret; +} +#endif /* NO_DSA */ + +#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) +static int d2iTryDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + int isDhKey; + word32 keyIdx = 0; + int ret = 1; +#ifndef WOLFSSL_SMALL_STACK + DhKey dh[1]; +#else + DhKey *dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); + if (dh == NULL) + return 0; #endif - #ifdef WOLFSSL_SMALL_STACK - XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); - #endif - WOLFSSL_ERROR(WOLFSSL_BAD_FILE); - return WOLFSSL_BAD_FILE; - } + XMEMSET(dh, 0, sizeof(DhKey)); + + if (wc_InitDhKey(dh) != 0) { #ifdef WOLFSSL_SMALL_STACK - XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); + XFREE(dh, NULL, DYNAMIC_TYPE_DH); #endif + return 0; + } + + isDhKey = (wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz) == 0); + wc_FreeDhKey(dh); +#ifdef WOLFSSL_SMALL_STACK + XFREE(dh, NULL, DYNAMIC_TYPE_DH); +#endif - (void)devId; + /* test if DH key */ + if (!isDhKey) { + return -1; } - else if (type == CERT_TYPE) { - #ifdef WOLFSSL_SMALL_STACK - DecodedCert* cert; - #else - DecodedCert cert[1]; - #endif - #ifdef WOLF_PRIVATE_KEY_ID - int keyType = 0; - #endif - #ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap, - DYNAMIC_TYPE_DCERT); - if (cert == NULL) - return MEMORY_E; - #endif + if (*out != NULL) { + pkey = *out; + } + else { + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("DH wolfSSL_EVP_PKEY_new error"); + return 0; + } + } - WOLFSSL_MSG("Checking cert signature type"); - InitDecodedCert_ex(cert, der->buffer, der->length, heap, devId); + pkey->pkey_sz = (int)memSz; + pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + priv ? DYNAMIC_TYPE_PRIVATE_KEY : + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkey->pkey.ptr == NULL) { + ret = 0; + } + if (ret == 1) { + XMEMCPY(pkey->pkey.ptr, mem, memSz); + pkey->type = EVP_PKEY_DH; - if (DecodeToKey(cert, 0) < 0) { - WOLFSSL_MSG("Decode to key failed"); - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, heap, DYNAMIC_TYPE_DCERT); - #endif - return WOLFSSL_BAD_FILE; + pkey->ownDh = 1; + pkey->dh = wolfSSL_DH_new(); + if (pkey->dh == NULL) { + ret = 0; } -#if defined(HAVE_RPK) - if (ssl) { - ssl->options.rpkState.isRPKLoaded = 0; - if (cert->isRPK) { - ssl->options.rpkState.isRPKLoaded = 1; - } + } + + if ((ret == 1) && (wolfSSL_DH_LoadDer(pkey->dh, + (const unsigned char*)pkey->pkey.ptr, + pkey->pkey_sz) != WOLFSSL_SUCCESS)) { + ret = 0; + } + if (ret == 1) { + *out = pkey; + } + + if ((ret == 0) && (*out == NULL)) { + wolfSSL_EVP_PKEY_free(pkey); + } + return ret; +} +#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ +#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */ + +#if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA) +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) +static int d2iTryAltDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + word32 keyIdx = 0; + DhKey* key = NULL; + int elements; + int ret; +#ifndef WOLFSSL_SMALL_STACK + DhKey dh[1]; +#else + DhKey* dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); + if (dh == NULL) + return 0; +#endif + XMEMSET(dh, 0, sizeof(DhKey)); + + /* test if DH-public key */ + if (wc_InitDhKey(dh) != 0) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(dh, NULL, DYNAMIC_TYPE_DH); +#endif + return 0; + } + + ret = wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz); + wc_FreeDhKey(dh); +#ifdef WOLFSSL_SMALL_STACK + XFREE(dh, NULL, DYNAMIC_TYPE_DH); +#endif + + if (ret != 0) { + return -1; + } + + if (*out != NULL) { + pkey = *out; + } + else { + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + return 0; } - else if (ctx) { - ctx->rpkState.isRPKLoaded = 0; - if (cert->isRPK) { - ctx->rpkState.isRPKLoaded = 1; - } + } + + ret = 1; + pkey->type = EVP_PKEY_DH; + pkey->pkey_sz = (int)memSz; + pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + priv ? DYNAMIC_TYPE_PRIVATE_KEY : + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkey->pkey.ptr == NULL) { + ret = 0; + } + if (ret == 1) { + XMEMCPY(pkey->pkey.ptr, mem, memSz); + pkey->ownDh = 1; + pkey->dh = wolfSSL_DH_new(); + if (pkey->dh == NULL) { + ret = 0; } -#endif /* HAVE_RPK */ + } + + if (ret == 1) { + key = (DhKey*)pkey->dh->internal; - if (ssl) { - if (ssl->options.side == WOLFSSL_SERVER_END) - resetSuites = 1; + keyIdx = 0; + if (wc_DhKeyDecode(mem, &keyIdx, key, (word32)memSz) != 0) { + ret = 0; } - else if (ctx && ctx->method->side == WOLFSSL_SERVER_END) { - resetSuites = 1; + } + + if (ret == 1) { + elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | ELEMENT_PUB; + if (priv) { + elements |= ELEMENT_PRV; } - if (ssl && ssl->ctx->haveECDSAsig) { - WOLFSSL_MSG("SSL layer setting cert, CTX had ECDSA, turning off"); - ssl->options.haveECDSAsig = 0; /* may turn back on next */ + if (SetDhExternal_ex(pkey->dh, elements) != WOLFSSL_SUCCESS ) { + ret = 0; } + } + if (ret == 1) { + *out = pkey; + } - switch (cert->signatureOID) { - case CTC_SHAwECDSA: - case CTC_SHA256wECDSA: - case CTC_SHA384wECDSA: - case CTC_SHA512wECDSA: - case CTC_ED25519: - case CTC_ED448: - #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - case CTC_SM3wSM2: - #endif - WOLFSSL_MSG("ECDSA/ED25519/ED448 cert signature"); - if (ssl) - ssl->options.haveECDSAsig = 1; - else if (ctx) - ctx->haveECDSAsig = 1; - break; - case CTC_FALCON_LEVEL1: - case CTC_FALCON_LEVEL5: - WOLFSSL_MSG("Falcon cert signature"); - if (ssl) - ssl->options.haveFalconSig = 1; - else if (ctx) - ctx->haveFalconSig = 1; - break; - case CTC_DILITHIUM_LEVEL2: - case CTC_DILITHIUM_LEVEL3: - case CTC_DILITHIUM_LEVEL5: - WOLFSSL_MSG("Dilithium cert signature"); - if (ssl) - ssl->options.haveDilithiumSig = 1; - else if (ctx) - ctx->haveDilithiumSig = 1; - break; - default: - WOLFSSL_MSG("Not ECDSA cert signature"); - break; - } + if ((ret == 0) && (*out == NULL)) { + wolfSSL_EVP_PKEY_free(pkey); + } + return ret; +} +#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ +#endif /* !NO_DH && OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */ - #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ - (defined(HAVE_PQC) && defined(HAVE_LIBOQS)) || !defined(NO_RSA) - if (ssl) { - #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \ - (defined(HAVE_CURVE448) && defined(HAVE_ED448)) - ssl->pkCurveOID = cert->pkCurveOID; - #endif - #ifndef WC_STRICT_SIG - if (cert->keyOID == ECDSAk) { - ssl->options.haveECC = 1; - } - #ifndef NO_RSA - else if (cert->keyOID == RSAk) { - ssl->options.haveRSA = 1; - } - #ifdef WC_RSA_PSS - else if (cert->keyOID == RSAPSSk) { - ssl->options.haveRSA = 1; - } - #endif - #endif - #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - else if (cert->keyOID == SM2k) { - ssl->options.haveECC = 1; - } - #endif - #ifdef HAVE_ED25519 - else if (cert->keyOID == ED25519k) { - ssl->options.haveECC = 1; - } - #endif - #ifdef HAVE_ED448 - else if (cert->keyOID == ED448k) { - ssl->options.haveECC = 1; - } - #endif - #ifdef HAVE_PQC - #ifdef HAVE_FALCON - else if (cert->keyOID == FALCON_LEVEL1k || - cert->keyOID == FALCON_LEVEL5k) { - ssl->options.haveFalconSig = 1; - } - #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM - else if (cert->keyOID == DILITHIUM_LEVEL2k || - cert->keyOID == DILITHIUM_LEVEL3k || - cert->keyOID == DILITHIUM_LEVEL5k) { - ssl->options.haveDilithiumSig = 1; - } - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ - #else - ssl->options.haveECC = ssl->options.haveECDSAsig; - #endif +#ifdef HAVE_FALCON +static int d2iTryFalconKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) +{ + WOLFSSL_EVP_PKEY* pkey; + int isFalcon = 0; +#ifndef WOLFSSL_SMALL_STACK + falcon_key falcon[1]; +#else + falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(falcon_key), NULL, + DYNAMIC_TYPE_FALCON); + if (falcon == NULL) { + return 0; + } +#endif + + if (wc_falcon_init(falcon) != 0) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); + #endif + return 0; + } + + /* test if Falcon key */ + if (priv) { + /* Try level 1 */ + isFalcon = ((wc_falcon_set_level(falcon, 1) == 0) && + (wc_falcon_import_private_only(mem, (word32)memSz, + falcon) == 0)); + if (!isFalcon) { + /* Try level 5 */ + isFalcon = ((wc_falcon_set_level(falcon, 5) == 0) && + (wc_falcon_import_private_only(mem, (word32)memSz, + falcon) == 0)); } - else if (ctx) { - #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) - ctx->pkCurveOID = cert->pkCurveOID; - #endif - #ifndef WC_STRICT_SIG - if (cert->keyOID == ECDSAk) { - ctx->haveECC = 1; - } - #ifndef NO_RSA - else if (cert->keyOID == RSAk) { - ctx->haveRSA = 1; - } - #ifdef WC_RSA_PSS - else if (cert->keyOID == RSAPSSk) { - ctx->haveRSA = 1; - } - #endif - #endif - #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - else if (cert->keyOID == SM2k) { - ctx->haveECC = 1; - } - #endif - #ifdef HAVE_ED25519 - else if (cert->keyOID == ED25519k) { - ctx->haveECC = 1; - } - #endif - #ifdef HAVE_ED448 - else if (cert->keyOID == ED448k) { - ctx->haveECC = 1; - } - #endif - #ifdef HAVE_PQC - #ifdef HAVE_FALCON - else if (cert->keyOID == FALCON_LEVEL1k || - cert->keyOID == FALCON_LEVEL5k) { - ctx->haveFalconSig = 1; - } - #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM - else if (cert->keyOID == DILITHIUM_LEVEL2k || - cert->keyOID == DILITHIUM_LEVEL3k || - cert->keyOID == DILITHIUM_LEVEL5k) { - ctx->haveDilithiumSig = 1; - } - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ - #else - ctx->haveECC = ctx->haveECDSAsig; - #endif + } + else { + /* Try level 1 */ + isFalcon = ((wc_falcon_set_level(falcon, 1) == 0) && + (wc_falcon_import_public(mem, (word32)memSz, falcon) == 0)); + + if (!isFalcon) { + /* Try level 5 */ + isFalcon = ((wc_falcon_set_level(falcon, 5) == 0) && + (wc_falcon_import_public(mem, (word32)memSz, + falcon) == 0)); } - #endif + } + wc_falcon_free(falcon); +#ifdef WOLFSSL_SMALL_STACK + XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); +#endif - /* check key size of cert unless specified not to */ - switch (cert->keyOID) { - #ifndef NO_RSA - #ifdef WC_RSA_PSS - case RSAPSSk: - #endif - case RSAk: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = rsa_sa_algo; - #endif - /* Determine RSA key size by parsing public key */ - idx = 0; - ret = wc_RsaPublicKeyDecode_ex(cert->publicKey, &idx, - cert->pubKeySize, NULL, (word32*)&keySz, NULL, NULL); - if (ret < 0) - break; - - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minRsaKeySz < 0 || - keySz < (int)ssl->options.minRsaKeySz || - keySz > (RSA_MAX_SIZE / 8)) { - ret = RSA_KEY_SIZE_E; - WOLFSSL_MSG("Certificate RSA key size too small"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minRsaKeySz < 0 || - keySz < (int)ctx->minRsaKeySz || - keySz > (RSA_MAX_SIZE / 8)) { - ret = RSA_KEY_SIZE_E; - WOLFSSL_MSG("Certificate RSA key size too small"); - } - } - break; - #endif /* !NO_RSA */ - #ifdef HAVE_ECC - case ECDSAk: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = ecc_dsa_sa_algo; - #endif - /* Determine ECC key size based on curve */ - #ifdef WOLFSSL_CUSTOM_CURVES - if (cert->pkCurveOID == 0 && cert->pkCurveSize != 0) { - keySz = cert->pkCurveSize * 8; - } - else - #endif - { - keySz = wc_ecc_get_curve_size_from_id( - wc_ecc_get_oid(cert->pkCurveOID, NULL, NULL)); - } - - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minEccKeySz < 0 || - keySz < (int)ssl->options.minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate ECC key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minEccKeySz < 0 || - keySz < (int)ctx->minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate ECC key size error"); - } - } - break; - #endif /* HAVE_ECC */ - #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - case SM2k: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = sm2_sa_algo; - #endif - /* Determine ECC key size based on curve */ - keySz = wc_ecc_get_curve_size_from_id( - wc_ecc_get_oid(cert->pkCurveOID, NULL, NULL)); - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minEccKeySz < 0 || - keySz < (int)ssl->options.minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Ed key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minEccKeySz < 0 || - keySz < (int)ctx->minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate ECC key size error"); - } - } - break; - #endif /* HAVE_ED25519 */ - #ifdef HAVE_ED25519 - case ED25519k: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = ed25519_sa_algo; - #endif - /* ED25519 is fixed key size */ - keySz = ED25519_KEY_SIZE; - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minEccKeySz < 0 || - keySz < (int)ssl->options.minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Ed key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minEccKeySz < 0 || - keySz < (int)ctx->minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate ECC key size error"); - } - } - break; - #endif /* HAVE_ED25519 */ - #ifdef HAVE_ED448 - case ED448k: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = ed448_sa_algo; - #endif - /* ED448 is fixed key size */ - keySz = ED448_KEY_SIZE; - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minEccKeySz < 0 || - keySz < (int)ssl->options.minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Ed key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minEccKeySz < 0 || - keySz < (int)ctx->minEccKeySz) { - ret = ECC_KEY_SIZE_E; - WOLFSSL_MSG("Certificate ECC key size error"); - } - } - break; - #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) - #if defined(HAVE_FALCON) - case FALCON_LEVEL1k: - case FALCON_LEVEL5k: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = falcon_level5_sa_algo; - #endif - /* Falcon is fixed key size */ - keySz = FALCON_MAX_KEY_SIZE; - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minFalconKeySz < 0 || - keySz < (int)ssl->options.minFalconKeySz) { - ret = FALCON_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Falcon key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minFalconKeySz < 0 || - keySz < (int)ctx->minFalconKeySz) { - ret = FALCON_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Falcon key size error"); - } - } - break; - #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) - case DILITHIUM_LEVEL2k: - case DILITHIUM_LEVEL3k: - case DILITHIUM_LEVEL5k: - #ifdef WOLF_PRIVATE_KEY_ID - keyType = dilithium_level5_sa_algo; - #endif - /* Dilithium is fixed key size */ - keySz = DILITHIUM_MAX_KEY_SIZE; - if (ssl && !ssl->options.verifyNone) { - if (ssl->options.minDilithiumKeySz < 0 || - keySz < (int)ssl->options.minDilithiumKeySz) { - ret = DILITHIUM_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Dilithium key size error"); - } - } - else if (ctx && !ctx->verifyNone) { - if (ctx->minDilithiumKeySz < 0 || - keySz < (int)ctx->minDilithiumKeySz) { - ret = DILITHIUM_KEY_SIZE_E; - WOLFSSL_MSG("Certificate Dilithium key size error"); - } - } - break; - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ - - default: - WOLFSSL_MSG("No key size check done on certificate"); - break; /* do no check if not a case for the key */ - } - - #ifdef WOLF_PRIVATE_KEY_ID - if (ssl != NULL) { - ssl->buffers.keyType = (byte)keyType; - ssl->buffers.keySz = keySz; - } - else if (ctx != NULL) { - ctx->privateKeyType = (byte)keyType; - ctx->privateKeySz = keySz; - } - #endif - - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, heap, DYNAMIC_TYPE_DCERT); - #endif - - if (ret != 0) { - done = 1; - } + if (!isFalcon) { + return -1; } - if (done == 1) { - #if !defined(NO_WOLFSSL_CM_VERIFY) && (!defined(NO_WOLFSSL_CLIENT) || \ - !defined(WOLFSSL_NO_CLIENT_AUTH)) - if ((type == CA_TYPE) || (type == CERT_TYPE)) { - /* Call to over-ride status */ - if ((ctx != NULL) && (ctx->cm != NULL) && - (ctx->cm->verifyCallback != NULL)) { - ret = CM_VerifyBuffer_ex(ctx->cm, buff, - sz, format, (ret == WOLFSSL_SUCCESS ? 0 : ret)); - } - } - #endif /* NO_WOLFSSL_CM_VERIFY */ - - return ret; + if (*out != NULL) { + pkey = *out; } - - - if (ssl && resetSuites) { - word16 havePSK = 0; - word16 haveRSA = 0; - - #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - if (ssl->options.havePSK) { - havePSK = 1; + else { + /* Create a fake Falcon EVP_PKEY. In the future, we might integrate + * Falcon into the compatibility layer. */ + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("Falcon wolfSSL_EVP_PKEY_new error"); + return 0; } - #endif - #ifndef NO_RSA - haveRSA = 1; - #endif - keySz = ssl->buffers.keySz; - - if (AllocateSuites(ssl) != 0) - return WOLFSSL_FAILURE; - /* let's reset suites */ - InitSuites(ssl->suites, ssl->version, keySz, haveRSA, - havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, - ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); } - else if (ctx && resetSuites) { - word16 havePSK = 0; - word16 haveRSA = 0; - - #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - if (ctx->havePSK) { - havePSK = 1; - } - #endif - #ifndef NO_RSA - haveRSA = 1; - #endif - keySz = ctx->privateKeySz; + pkey->type = EVP_PKEY_FALCON; + pkey->pkey.ptr = NULL; + pkey->pkey_sz = 0; - if (AllocateCtxSuites(ctx) != 0) - return WOLFSSL_FAILURE; - /* let's reset suites */ - InitSuites(ctx->suites, ctx->method->version, keySz, haveRSA, - havePSK, ctx->haveDH, ctx->haveECDSAsig, - ctx->haveECC, TRUE, ctx->haveStaticECC, - ctx->haveFalconSig, ctx->haveDilithiumSig, -#ifdef HAVE_ANON - ctx->useAnon, -#else - FALSE, -#endif - TRUE, ctx->method->side); - } + *out = pkey; + return 1; - return WOLFSSL_SUCCESS; } +#endif /* HAVE_FALCON */ - -/* CA PEM file for verification, may have multiple/chain certs to process */ -static int ProcessChainBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, - long sz, int format, int type, WOLFSSL* ssl, int verify) +#ifdef HAVE_DILITHIUM +static int d2iTryDilithiumKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, + long memSz, int priv) { - long used = 0; - int ret = 0; - int gotOne = 0; - - WOLFSSL_MSG("Processing CA PEM file"); - while (used < sz) { - long consumed = 0; + WOLFSSL_EVP_PKEY* pkey; + int isDilithium = 0; +#ifndef WOLFSSL_SMALL_STACK + dilithium_key dilithium[1]; +#else + dilithium_key *dilithium = (dilithium_key *) + XMALLOC(sizeof(dilithium_key), NULL, DYNAMIC_TYPE_DILITHIUM); + if (dilithium == NULL) { + return 0; + } +#endif - ret = ProcessBuffer(ctx, buff + used, sz - used, format, type, ssl, - &consumed, 0, verify); + if (wc_dilithium_init(dilithium) != 0) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); + #endif + return 0; + } - if (ret == MEMORY_E) { - return ret; + /* Test if Dilithium key. Try all levels. */ + if (priv) { + isDilithium = ((wc_dilithium_set_level(dilithium, 2) == 0) && + (wc_dilithium_import_private(mem, + (word32)memSz, dilithium) == 0)); + if (!isDilithium) { + isDilithium = ((wc_dilithium_set_level(dilithium, 3) == 0) && + (wc_dilithium_import_private(mem, + (word32)memSz, dilithium) == 0)); } - else if (ret < 0) { -#if defined(WOLFSSL_WPAS) && defined(HAVE_CRL) - DerBuffer* der = NULL; - EncryptedInfo info; - - WOLFSSL_MSG("Trying a CRL"); - if (PemToDer(buff + used, sz - used, CRL_TYPE, &der, NULL, &info, - NULL) == 0) { - WOLFSSL_MSG(" Processed a CRL"); - wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, der->buffer, - der->length, WOLFSSL_FILETYPE_ASN1); - FreeDer(&der); - used += info.consumed; - continue; - } -#endif - - if (consumed > 0) { /* Made progress in file */ - WOLFSSL_ERROR(ret); - WOLFSSL_MSG("CA Parse failed, with progress in file."); - WOLFSSL_MSG("Search for other certs in file"); - } - else { - WOLFSSL_MSG("CA Parse failed, no progress in file."); - WOLFSSL_MSG("Do not continue search for other certs in file"); - break; - } + if (!isDilithium) { + isDilithium = ((wc_dilithium_set_level(dilithium, 5) == 0) && + (wc_dilithium_import_private(mem, + (word32)memSz, dilithium) == 0)); } - else { - WOLFSSL_MSG(" Processed a CA"); - gotOne = 1; + } + else { + isDilithium = ((wc_dilithium_set_level(dilithium, 2) == 0) && + (wc_dilithium_import_public(mem, (word32)memSz, + dilithium) == 0)); + if (!isDilithium) { + isDilithium = ((wc_dilithium_set_level(dilithium, 3) == 0) && + (wc_dilithium_import_public(mem, (word32)memSz, + dilithium) == 0)); + } + if (!isDilithium) { + isDilithium = ((wc_dilithium_set_level(dilithium, 5) == 0) && + (wc_dilithium_import_public(mem, (word32)memSz, + dilithium) == 0)); } - used += consumed; } + wc_dilithium_free(dilithium); +#ifdef WOLFSSL_SMALL_STACK + XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif - if (gotOne) { - WOLFSSL_MSG("Processed at least one valid CA. Other stuff OK"); - return WOLFSSL_SUCCESS; + if (!isDilithium) { + return -1; } - return ret; -} - - -#ifdef HAVE_CRL - -int wolfSSL_CTX_LoadCRLBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, - long sz, int type) -{ - WOLFSSL_ENTER("wolfSSL_CTX_LoadCRLBuffer"); - if (ctx == NULL) - return BAD_FUNC_ARG; + if (*out != NULL) { + pkey = *out; + } + else { + /* Create a fake Dilithium EVP_PKEY. In the future, we might + * integrate Dilithium into the compatibility layer. */ + pkey = wolfSSL_EVP_PKEY_new(); + if (pkey == NULL) { + WOLFSSL_MSG("Dilithium wolfSSL_EVP_PKEY_new error"); + return 0; + } + } + pkey->type = EVP_PKEY_DILITHIUM; + pkey->pkey.ptr = NULL; + pkey->pkey_sz = 0; - return wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, buff, sz, type); + *out = pkey; + return 1; } +#endif /* HAVE_DILITHIUM */ - -int wolfSSL_LoadCRLBuffer(WOLFSSL* ssl, const unsigned char* buff, - long sz, int type) +static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out, + const unsigned char** in, long inSz, int priv) { - WOLFSSL_ENTER("wolfSSL_LoadCRLBuffer"); + WOLFSSL_EVP_PKEY* pkey = NULL; - if (ssl == NULL || ssl->ctx == NULL) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("d2iGenericKey"); - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerLoadCRLBuffer(SSL_CM(ssl), buff, sz, type); -} + if (in == NULL || *in == NULL || inSz < 0) { + WOLFSSL_MSG("Bad argument"); + return NULL; + } -#endif /* HAVE_CRL */ + if ((out != NULL) && (*out != NULL)) { + pkey = *out; + } -#ifdef HAVE_OCSP -int wolfSSL_EnableOCSP(WOLFSSL* ssl, int options) -{ - WOLFSSL_ENTER("wolfSSL_EnableOCSP"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerEnableOCSP(SSL_CM(ssl), options); +#if !defined(NO_RSA) + if (d2iTryRsaKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; -} - -int wolfSSL_DisableOCSP(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_DisableOCSP"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerDisableOCSP(SSL_CM(ssl)); +#endif /* NO_RSA */ +#if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) + if (d2iTryEccKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; -} - - -int wolfSSL_EnableOCSPStapling(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_EnableOCSPStapling"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerEnableOCSPStapling(SSL_CM(ssl)); +#endif /* HAVE_ECC && OPENSSL_EXTRA */ +#if !defined(NO_DSA) + if (d2iTryDsaKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; -} - -int wolfSSL_DisableOCSPStapling(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_DisableOCSPStapling"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerDisableOCSPStapling(SSL_CM(ssl)); +#endif /* NO_DSA */ +#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) + if (d2iTryDhKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; -} +#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ +#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */ -int wolfSSL_SetOCSP_OverrideURL(WOLFSSL* ssl, const char* url) -{ - WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerSetOCSPOverrideURL(SSL_CM(ssl), url); +#if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA) +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) + if (d2iTryAltDhKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; -} - +#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ +#endif /* !NO_DH && OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */ -int wolfSSL_SetOCSP_Cb(WOLFSSL* ssl, - CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx) -{ - WOLFSSL_ENTER("wolfSSL_SetOCSP_Cb"); - if (ssl) { - SSL_CM_WARNING(ssl); - ssl->ocspIOCtx = ioCbCtx; /* use SSL specific ioCbCtx */ - return wolfSSL_CertManagerSetOCSP_Cb(SSL_CM(ssl), - ioCb, respFreeCb, NULL); +#ifdef HAVE_FALCON + if (d2iTryFalconKey(&pkey, *in, inSz, priv) >= 0) { + ; } else - return BAD_FUNC_ARG; +#endif /* HAVE_FALCON */ +#ifdef HAVE_DILITHIUM + if (d2iTryDilithiumKey(&pkey, *in, inSz, priv) >= 0) { + ; + } + else +#endif /* HAVE_DILITHIUM */ + { + WOLFSSL_MSG("wolfSSL_d2i_PUBKEY couldn't determine key type"); + } + + if ((pkey != NULL) && (out != NULL)) { + *out = pkey; + } + return pkey; } +#endif /* OPENSSL_EXTRA || WPA_SMALL */ +#ifdef OPENSSL_EXTRA -int wolfSSL_CTX_EnableOCSP(WOLFSSL_CTX* ctx, int options) +WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( + WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey, const unsigned char** keyBuf, + long keyLen) { - WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSP"); - if (ctx) - return wolfSSL_CertManagerEnableOCSP(ctx->cm, options); - else - return BAD_FUNC_ARG; -} + WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL; +#ifdef WOLFSSL_PEM_TO_DER + int ret; + DerBuffer* der = NULL; + if (keyBuf == NULL || *keyBuf == NULL || keyLen <= 0) { + WOLFSSL_MSG("Bad key PEM/DER args"); + return NULL; + } -int wolfSSL_CTX_DisableOCSP(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSP"); - if (ctx) - return wolfSSL_CertManagerDisableOCSP(ctx->cm); - else - return BAD_FUNC_ARG; -} + ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &der, NULL, NULL, NULL); + if (ret < 0) { + WOLFSSL_MSG("Not PEM format"); + ret = AllocDer(&der, (word32)keyLen, PRIVATEKEY_TYPE, NULL); + if (ret == 0) { + XMEMCPY(der->buffer, *keyBuf, keyLen); + } + } + if (ret == 0) { + /* Verify this is PKCS8 Key */ + word32 inOutIdx = 0; + word32 algId; + ret = ToTraditionalInline_ex(der->buffer, &inOutIdx, der->length, + &algId); + if (ret >= 0) { + ret = 0; /* good DER */ + } + } -int wolfSSL_CTX_SetOCSP_OverrideURL(WOLFSSL_CTX* ctx, const char* url) -{ - WOLFSSL_ENTER("wolfSSL_SetOCSP_OverrideURL"); - if (ctx) - return wolfSSL_CertManagerSetOCSPOverrideURL(ctx->cm, url); - else - return BAD_FUNC_ARG; -} + if (ret == 0) { + pkcs8 = wolfSSL_EVP_PKEY_new(); + if (pkcs8 == NULL) + ret = MEMORY_E; + } + if (ret == 0) { + pkcs8->pkey.ptr = (char*)XMALLOC(der->length, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); + if (pkcs8->pkey.ptr == NULL) + ret = MEMORY_E; + } + if (ret == 0) { + XMEMCPY(pkcs8->pkey.ptr, der->buffer, der->length); + pkcs8->pkey_sz = (int)der->length; + } + FreeDer(&der); + if (ret != 0) { + wolfSSL_EVP_PKEY_free(pkcs8); + pkcs8 = NULL; + } + if (pkey != NULL) { + *pkey = pkcs8; + } -int wolfSSL_CTX_SetOCSP_Cb(WOLFSSL_CTX* ctx, CbOCSPIO ioCb, - CbOCSPRespFree respFreeCb, void* ioCbCtx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_SetOCSP_Cb"); - if (ctx) - return wolfSSL_CertManagerSetOCSP_Cb(ctx->cm, ioCb, - respFreeCb, ioCbCtx); - else - return BAD_FUNC_ARG; -} +#else + (void)bio; + (void)pkey; +#endif /* WOLFSSL_PEM_TO_DER */ -#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ - || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) -int wolfSSL_CTX_EnableOCSPStapling(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPStapling"); - if (ctx) - return wolfSSL_CertManagerEnableOCSPStapling(ctx->cm); - else - return BAD_FUNC_ARG; + return pkcs8; } -int wolfSSL_CTX_DisableOCSPStapling(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPStapling"); - if (ctx) - return wolfSSL_CertManagerDisableOCSPStapling(ctx->cm); - else - return BAD_FUNC_ARG; -} -int wolfSSL_CTX_EnableOCSPMustStaple(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_EnableOCSPMustStaple"); - if (ctx) - return wolfSSL_CertManagerEnableOCSPMustStaple(ctx->cm); - else - return BAD_FUNC_ARG; -} +#ifndef NO_BIO +/* put SSL type in extra for now, not very common */ -int wolfSSL_CTX_DisableOCSPMustStaple(WOLFSSL_CTX* ctx) +/* Converts a DER format key read from "bio" to a PKCS8 structure. + * + * bio input bio to read DER from + * pkey If not NULL then this pointer will be overwritten with a new PKCS8 + * structure. + * + * returns a WOLFSSL_PKCS8_PRIV_KEY_INFO pointer on success and NULL in fail + * case. + */ +WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY_bio(WOLFSSL_BIO* bio, + WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey) { - WOLFSSL_ENTER("wolfSSL_CTX_DisableOCSPMustStaple"); - if (ctx) - return wolfSSL_CertManagerDisableOCSPMustStaple(ctx->cm); - else - return BAD_FUNC_ARG; -} -#endif /* HAVE_CERTIFICATE_STATUS_REQUEST || HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ + WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL; +#ifdef WOLFSSL_PEM_TO_DER + unsigned char* mem = NULL; + int memSz; -#endif /* HAVE_OCSP */ + WOLFSSL_ENTER("wolfSSL_d2i_PKCS8_PKEY_bio"); -/* macro to get verify settings for AddCA */ -#define GET_VERIFY_SETTING_CTX(ctx) \ - ((ctx) && (ctx)->verifyNone ? NO_VERIFY : VERIFY) -#define GET_VERIFY_SETTING_SSL(ssl) \ - ((ssl)->options.verifyNone ? NO_VERIFY : VERIFY) + if (bio == NULL) { + return NULL; + } -#ifndef NO_FILESYSTEM + if ((memSz = wolfSSL_BIO_get_mem_data(bio, &mem)) < 0) { + return NULL; + } -/* process a file with name fname into ctx of format and type - userChain specifies a user certificate chain to pass during handshake */ -int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, - WOLFSSL* ssl, int userChain, WOLFSSL_CRL* crl, int verify) -{ -#ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force heap usage */ + pkcs8 = wolfSSL_d2i_PKCS8_PKEY(pkey, (const unsigned char**)&mem, memSz); #else - byte staticBuffer[FILE_BUFFER_SIZE]; -#endif - byte* myBuffer = staticBuffer; - int dynamic = 0; - int ret; - long sz = 0; - XFILE file; - void* heapHint = wolfSSL_CTX_GetHeap(ctx, ssl); -#ifndef NO_CODING - const char* header = NULL; - const char* footer = NULL; -#endif + (void)bio; + (void)pkey; +#endif /* WOLFSSL_PEM_TO_DER */ - (void)crl; - (void)heapHint; + return pkcs8; +} - if (fname == NULL) return WOLFSSL_BAD_FILE; - file = XFOPEN(fname, "rb"); - if (file == XBADFILE) return WOLFSSL_BAD_FILE; - if (XFSEEK(file, 0, XSEEK_END) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - sz = XFTELL(file); - if (XFSEEK(file, 0, XSEEK_SET) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; +/* expecting DER format public key + * + * bio input bio to read DER from + * out If not NULL then this pointer will be overwritten with a new + * WOLFSSL_EVP_PKEY pointer + * + * returns a WOLFSSL_EVP_PKEY pointer on success and NULL in fail case. + */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY** out) +{ + unsigned char* mem; + long memSz; + WOLFSSL_EVP_PKEY* pkey = NULL; + + WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY_bio"); + + if (bio == NULL) { + return NULL; } + (void)out; - if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { - WOLFSSL_MSG("ProcessFile file size error"); - XFCLOSE(file); - return WOLFSSL_BAD_FILE; + memSz = wolfSSL_BIO_get_len(bio); + if (memSz <= 0) { + return NULL; } - if (sz > (long)sizeof(staticBuffer)) { - WOLFSSL_MSG("Getting dynamic buffer"); - myBuffer = (byte*)XMALLOC(sz, heapHint, DYNAMIC_TYPE_FILE); - if (myBuffer == NULL) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - dynamic = 1; + mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (mem == NULL) { + return NULL; } - if ((size_t)XFREAD(myBuffer, 1, sz, file) != (size_t)sz) - ret = WOLFSSL_BAD_FILE; - else { - /* Try to detect type by parsing cert header and footer */ - if (type == DETECT_CERT_TYPE) { -#ifndef NO_CODING - if (wc_PemGetHeaderFooter(CA_TYPE, &header, &footer) == 0 && - (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) { - type = CA_TYPE; - } -#ifdef HAVE_CRL - else if (wc_PemGetHeaderFooter(CRL_TYPE, &header, &footer) == 0 && - (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) { - type = CRL_TYPE; - } -#endif - else if (wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer) == 0 && - (XSTRNSTR((char*)myBuffer, header, (int)sz) != NULL)) { - type = CERT_TYPE; - } - else -#endif - { - WOLFSSL_MSG("Failed to detect certificate type"); - if (dynamic) - XFREE(myBuffer, heapHint, DYNAMIC_TYPE_FILE); - XFCLOSE(file); - return WOLFSSL_BAD_CERTTYPE; - } - } - if ((type == CA_TYPE || type == TRUSTED_PEER_TYPE) - && format == WOLFSSL_FILETYPE_PEM) { - ret = ProcessChainBuffer(ctx, myBuffer, sz, format, type, ssl, - verify); + if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) { + pkey = wolfSSL_d2i_PUBKEY(NULL, (const unsigned char**)&mem, memSz); + if (out != NULL && pkey != NULL) { + *out = pkey; } -#ifdef HAVE_CRL - else if (type == CRL_TYPE) - ret = BufferLoadCRL(crl, myBuffer, sz, format, verify); -#endif - else - ret = ProcessBuffer(ctx, myBuffer, sz, format, type, ssl, NULL, - userChain, verify); } - XFCLOSE(file); - if (dynamic) - XFREE(myBuffer, heapHint, DYNAMIC_TYPE_FILE); - - return ret; + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + return pkey; } -/* loads file then loads each file in path, no c_rehash */ -int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, - const char* path, word32 flags) -{ - int ret = WOLFSSL_SUCCESS; -#ifndef NO_WOLFSSL_DIR - int successCount = 0; -#endif - int verify; +#endif /* !NO_BIO */ - WOLFSSL_MSG("wolfSSL_CTX_load_verify_locations_ex"); - if (ctx == NULL || (file == NULL && path == NULL)) { - return WOLFSSL_FAILURE; - } +/* Converts a DER encoded public key to a WOLFSSL_EVP_PKEY structure. + * + * out pointer to new WOLFSSL_EVP_PKEY structure. Can be NULL + * in DER buffer to convert + * inSz size of in buffer + * + * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL + * on fail + */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** out, + const unsigned char** in, long inSz) +{ + WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY"); + return d2iGenericKey(out, in, inSz, 0); +} - verify = GET_VERIFY_SETTING_CTX(ctx); - if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) - verify = VERIFY_SKIP_DATE; +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_ASN) && \ + !defined(NO_PWDBASED) - if (file) { - ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0, - NULL, verify); -#ifndef NO_WOLFSSL_DIR - if (ret == WOLFSSL_SUCCESS) - successCount++; -#endif -#if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) - ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error"); - } -#endif - } +/* helper function to get raw pointer to DER buffer from WOLFSSL_EVP_PKEY */ +static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, + unsigned char** der) +{ + int sz; + word16 pkcs8HeaderSz; - if (ret == WOLFSSL_SUCCESS && path) { -#ifndef NO_WOLFSSL_DIR - char* name = NULL; - int fileRet; - int failCount = 0; - #ifdef WOLFSSL_SMALL_STACK - ReadDirCtx* readCtx; - readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap, - DYNAMIC_TYPE_DIRCTX); - if (readCtx == NULL) - return MEMORY_E; - #else - ReadDirCtx readCtx[1]; - #endif - - /* try to load each regular file in path */ - fileRet = wc_ReadDirFirst(readCtx, path, &name); - while (fileRet == 0 && name) { - WOLFSSL_MSG(name); /* log file name */ - ret = ProcessFile(ctx, name, WOLFSSL_FILETYPE_PEM, CA_TYPE, - NULL, 0, NULL, verify); - if (ret != WOLFSSL_SUCCESS) { - /* handle flags for ignoring errors, skipping expired certs or - by PEM certificate header error */ - if ( (flags & WOLFSSL_LOAD_FLAG_IGNORE_ERR) || - ((flags & WOLFSSL_LOAD_FLAG_PEM_CA_ONLY) && - (ret == ASN_NO_PEM_HEADER))) { - /* Do not fail here if a certificate fails to load, - continue to next file */ - unsigned long err = 0; - CLEAR_ASN_NO_PEM_HEADER_ERROR(err); - #if defined(WOLFSSL_QT) - ret = WOLFSSL_SUCCESS; - #endif - } - else { - WOLFSSL_ERROR(ret); - WOLFSSL_MSG("Load CA file failed, continuing"); - failCount++; - } - } - else { - #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) - ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error. Ignoring" - "this error."); - } - #endif - successCount++; - } - fileRet = wc_ReadDirNext(readCtx, path, &name); - } - wc_ReadDirClose(readCtx); + if (!key || !key->pkey_sz) + return WOLFSSL_FATAL_ERROR; - /* pass directory read failure to response code */ - if (fileRet != WC_READDIR_NOFILE) { - ret = fileRet; - #if defined(WOLFSSL_QT) || defined(WOLFSSL_IGNORE_BAD_CERT_PATH) - if (ret == BAD_PATH_ERROR && - flags & WOLFSSL_LOAD_FLAG_IGNORE_BAD_PATH_ERR) { - /* QSslSocket always loads certs in system folder - * when it is initialized. - * Compliant with OpenSSL when flag sets. - */ - ret = WOLFSSL_SUCCESS; - } - else { - /* qssl socket wants to know errors. */ - WOLFSSL_ERROR(ret); - } - #endif - } - /* report failure if no files were loaded or there were failures */ - else if (successCount == 0 || failCount > 0) { - /* use existing error code if exists */ - #if defined(WOLFSSL_QT) - /* compliant with OpenSSL when flag sets*/ - if (!(flags & WOLFSSL_LOAD_FLAG_IGNORE_ZEROFILE)) - #endif - { - ret = WOLFSSL_FAILURE; - } + /* return the key without PKCS8 for compatibility */ + /* if pkcs8HeaderSz is invalid, use 0 and return all of pkey */ + pkcs8HeaderSz = 0; + if (key->pkey_sz > key->pkcs8HeaderSz) + pkcs8HeaderSz = key->pkcs8HeaderSz; + sz = key->pkey_sz - pkcs8HeaderSz; + if (der) { + unsigned char* pt = (unsigned char*)key->pkey.ptr; + if (*der) { + /* since this function signature has no size value passed in it is + * assumed that the user has allocated a large enough buffer */ + XMEMCPY(*der, pt + pkcs8HeaderSz, sz); + *der += sz; } else { - ret = WOLFSSL_SUCCESS; + *der = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL); + if (*der == NULL) { + return WOLFSSL_FATAL_ERROR; + } + XMEMCPY(*der, pt + pkcs8HeaderSz, sz); } - - #ifdef WOLFSSL_SMALL_STACK - XFREE(readCtx, ctx->heap, DYNAMIC_TYPE_DIRCTX); - #endif -#else - ret = NOT_COMPILED_IN; - (void)flags; -#endif } - - return ret; + return sz; } -WOLFSSL_ABI -int wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, - const char* path) +int wolfSSL_i2d_PUBKEY(const WOLFSSL_EVP_PKEY *key, unsigned char **der) { - int ret = wolfSSL_CTX_load_verify_locations_ex(ctx, file, path, - WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); - - return WS_RETURN_CODE(ret,WOLFSSL_FAILURE); + return wolfSSL_i2d_PublicKey(key, der); } -#ifdef WOLFSSL_SYS_CA_CERTS - -#ifdef USE_WINDOWS_API +#endif /* OPENSSL_EXTRA && !NO_CERTS && !NO_ASN && !NO_PWDBASED */ -static int LoadSystemCaCertsWindows(WOLFSSL_CTX* ctx, byte* loaded) +static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, + const unsigned char **in, long inSz, int priv) { - int ret = WOLFSSL_SUCCESS; - word32 i; - HANDLE handle = NULL; - PCCERT_CONTEXT certCtx = NULL; - LPCSTR storeNames[2] = {"ROOT", "CA"}; - HCRYPTPROV_LEGACY hProv = (HCRYPTPROV_LEGACY)NULL; - - if (ctx == NULL || loaded == NULL) { - ret = WOLFSSL_FAILURE; - } - - for (i = 0; ret == WOLFSSL_SUCCESS && - i < sizeof(storeNames)/sizeof(*storeNames); ++i) { - handle = CertOpenSystemStoreA(hProv, storeNames[i]); - if (handle != NULL) { - while ((certCtx = CertEnumCertificatesInStore(handle, certCtx)) - != NULL) { - if (certCtx->dwCertEncodingType == X509_ASN_ENCODING) { - if (ProcessBuffer(ctx, certCtx->pbCertEncoded, - certCtx->cbCertEncoded, WOLFSSL_FILETYPE_ASN1, - CA_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - /* - * Set "loaded" as long as we've loaded one CA - * cert. - */ - *loaded = 1; - } - } - } - } - else { - WOLFSSL_MSG_EX("Failed to open cert store %s.", storeNames[i]); - } - - if (handle != NULL && !CertCloseStore(handle, 0)) { - WOLFSSL_MSG_EX("Failed to close cert store %s.", storeNames[i]); - ret = WOLFSSL_FAILURE; - } - } - - return ret; -} - -#elif defined(__APPLE__) + int ret = 0; + word32 idx = 0, algId; + word16 pkcs8HeaderSz = 0; + WOLFSSL_EVP_PKEY* local; + int opt = 0; -#if defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) \ - && !defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) -/* - * Manually obtains certificates from the system trust store and loads them - * directly into wolfSSL "the old way". - * - * As of MacOS 14.0 we are still able to use this method to access system - * certificates. Accessibility of this API is indicated by the presence of the - * Security/SecTrustSettings.h header. In the likely event that Apple removes - * access to this API on Macs, this function should be removed and the - * DoAppleNativeCertValidation() routine should be used for all devices. - */ -static int LoadSystemCaCertsMac(WOLFSSL_CTX* ctx, byte* loaded) -{ - int ret = WOLFSSL_SUCCESS; - word32 i; - const unsigned int trustDomains[] = { - kSecTrustSettingsDomainUser, - kSecTrustSettingsDomainAdmin, - kSecTrustSettingsDomainSystem - }; - CFArrayRef certs; - OSStatus stat; - CFIndex numCerts; - CFDataRef der; - CFIndex j; + (void)opt; - if (ctx == NULL || loaded == NULL) { - ret = WOLFSSL_FAILURE; + if (in == NULL || inSz < 0) { + WOLFSSL_MSG("Bad argument"); + return NULL; } - for (i = 0; ret == WOLFSSL_SUCCESS && - i < sizeof(trustDomains)/sizeof(*trustDomains); ++i) { - stat = SecTrustSettingsCopyCertificates( - (SecTrustSettingsDomain)trustDomains[i], &certs); - if (stat == errSecSuccess) { - numCerts = CFArrayGetCount(certs); - for (j = 0; j < numCerts; ++j) { - der = SecCertificateCopyData((SecCertificateRef) - CFArrayGetValueAtIndex(certs, j)); - if (der != NULL) { - if (ProcessBuffer(ctx, CFDataGetBytePtr(der), - CFDataGetLength(der), WOLFSSL_FILETYPE_ASN1, - CA_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - /* - * Set "loaded" as long as we've loaded one CA - * cert. - */ - *loaded = 1; - } + if (priv == 1) { + /* Check if input buffer has PKCS8 header. In the case that it does not + * have a PKCS8 header then do not error out. */ + if ((ret = ToTraditionalInline_ex((const byte*)(*in), &idx, + (word32)inSz, &algId)) > 0) { + WOLFSSL_MSG("Found PKCS8 header"); + pkcs8HeaderSz = (word16)idx; - CFRelease(der); - } + if ((type == EVP_PKEY_RSA && algId != RSAk + #ifdef WC_RSA_PSS + && algId != RSAPSSk + #endif + ) || + (type == EVP_PKEY_EC && algId != ECDSAk) || + (type == EVP_PKEY_DSA && algId != DSAk) || + (type == EVP_PKEY_DH && algId != DHk)) { + WOLFSSL_MSG("PKCS8 does not match EVP key type"); + return NULL; } - CFRelease(certs); - } - else if (stat == errSecNoTrustSettings) { - WOLFSSL_MSG_EX("No trust settings for domain %d, moving to next " - "domain.", trustDomains[i]); + (void)idx; /* not used */ } else { - WOLFSSL_MSG_EX("SecTrustSettingsCopyCertificates failed with" - " status %d.", stat); - ret = WOLFSSL_FAILURE; - break; + if (ret != WC_NO_ERR_TRACE(ASN_PARSE_E)) { + WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 " + "header"); + return NULL; + } } } - return ret; -} -#endif /* defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) */ - -#else - -/* Potential system CA certs directories on Linux/Unix distros. */ -static const char* systemCaDirs[] = { -#if defined(__ANDROID__) || defined(ANDROID) - "/system/etc/security/cacerts" /* Android */ -#else - "/etc/ssl/certs", /* Debian, Ubuntu, Gentoo, others */ - "/etc/pki/ca-trust/source/anchors", /* Fedora, RHEL */ - "/etc/pki/tls/certs" /* Older RHEL */ -#endif -}; - -const char** wolfSSL_get_system_CA_dirs(word32* num) -{ - const char** ret; + if (out != NULL && *out != NULL) { + wolfSSL_EVP_PKEY_free(*out); + *out = NULL; + } + local = wolfSSL_EVP_PKEY_new(); + if (local == NULL) { + return NULL; + } - if (num == NULL) { - ret = NULL; + local->type = type; + local->pkey_sz = (int)inSz; + local->pkcs8HeaderSz = pkcs8HeaderSz; + local->pkey.ptr = (char*)XMALLOC(inSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + if (local->pkey.ptr == NULL) { + wolfSSL_EVP_PKEY_free(local); + local = NULL; + return NULL; } else { - ret = systemCaDirs; - *num = sizeof(systemCaDirs)/sizeof(*systemCaDirs); + XMEMCPY(local->pkey.ptr, *in, inSz); } - return ret; -} - -static int LoadSystemCaCertsNix(WOLFSSL_CTX* ctx, byte* loaded) { - int ret = WOLFSSL_SUCCESS; - word32 i; - - if (ctx == NULL || loaded == NULL) { - ret = WOLFSSL_FAILURE; + switch (type) { +#ifndef NO_RSA + case EVP_PKEY_RSA: + opt = priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC; + local->ownRsa = 1; + local->rsa = wolfssl_rsa_d2i(NULL, + (const unsigned char*)local->pkey.ptr, local->pkey_sz, opt); + if (local->rsa == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + break; +#endif /* NO_RSA */ +#ifdef HAVE_ECC + case EVP_PKEY_EC: + local->ownEcc = 1; + local->ecc = wolfSSL_EC_KEY_new(); + if (local->ecc == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + opt = priv ? WOLFSSL_EC_KEY_LOAD_PRIVATE : + WOLFSSL_EC_KEY_LOAD_PUBLIC; + if (wolfSSL_EC_KEY_LoadDer_ex(local->ecc, + (const unsigned char*)local->pkey.ptr, local->pkey_sz, + opt) + != WOLFSSL_SUCCESS) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + break; +#endif /* HAVE_ECC */ +#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) +#ifndef NO_DSA + case EVP_PKEY_DSA: + local->ownDsa = 1; + local->dsa = wolfSSL_DSA_new(); + if (local->dsa == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + opt = priv ? WOLFSSL_DSA_LOAD_PRIVATE : WOLFSSL_DSA_LOAD_PUBLIC; + if (wolfSSL_DSA_LoadDer_ex(local->dsa, + (const unsigned char*)local->pkey.ptr, local->pkey_sz, + opt) + != WOLFSSL_SUCCESS) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + break; +#endif /* NO_DSA */ +#ifndef NO_DH +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2)) + case EVP_PKEY_DH: + local->ownDh = 1; + local->dh = wolfSSL_DH_new(); + if (local->dh == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + if (wolfSSL_DH_LoadDer(local->dh, + (const unsigned char*)local->pkey.ptr, local->pkey_sz) + != WOLFSSL_SUCCESS) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + break; +#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ +#endif /* HAVE_DH */ +#endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH */ + default: + WOLFSSL_MSG("Unsupported key type"); + wolfSSL_EVP_PKEY_free(local); + return NULL; } - for (i = 0; ret == WOLFSSL_SUCCESS && - i < sizeof(systemCaDirs)/sizeof(*systemCaDirs); ++i) { - WOLFSSL_MSG_EX("Attempting to load system CA certs from %s.", - systemCaDirs[i]); - /* - * We want to keep trying to load more CAs even if one cert in - * the directory is bad and can't be used (e.g. if one is expired), - * so we use WOLFSSL_LOAD_FLAG_IGNORE_ERR. - */ - if (wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, systemCaDirs[i], - WOLFSSL_LOAD_FLAG_IGNORE_ERR) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG_EX("Failed to load CA certs from %s, trying " - "next possible location.", systemCaDirs[i]); + /* advance pointer with success */ + if (local != NULL) { + if (local->pkey_sz <= (int)inSz) { + *in += local->pkey_sz; } - else { - WOLFSSL_MSG_EX("Loaded CA certs from %s.", - systemCaDirs[i]); - *loaded = 1; - /* Stop searching after we've loaded one directory. */ - break; + + if (out != NULL) { + *out = local; } } - return ret; + return local; } -#endif - -int wolfSSL_CTX_load_system_CA_certs(WOLFSSL_CTX* ctx) +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, + const unsigned char **in, long inSz) { - int ret; - byte loaded = 0; - - WOLFSSL_ENTER("wolfSSL_CTX_load_system_CA_certs"); - -#ifdef USE_WINDOWS_API - - ret = LoadSystemCaCertsWindows(ctx, &loaded); - -#elif defined(__APPLE__) - -#if defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) \ - && !defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) - /* As of MacOS 14.0 we are still able to access system certificates and - * load them manually into wolfSSL "the old way". Accessibility of this API - * is indicated by the presence of the Security/SecTrustSettings.h header */ - ret = LoadSystemCaCertsMac(ctx, &loaded); -#elif defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) - /* For other Apple devices, Apple has removed the ability to obtain - * certificates from the trust store, so we can't use wolfSSL's built-in - * certificate validation mechanisms anymore. We instead must call into the - * Security Framework APIs to authenticate peer certificates when received. - * (see src/internal.c:DoAppleNativeCertValidation()). - * Thus, there is no CA "loading" required, but to keep behavior consistent - * with the current API (not using system CA certs unless this function has - * been called), we simply set a flag indicating that the new apple trust - * verification routine should be used later */ - ctx->doAppleNativeCertValidationFlag = 1; - ret = WOLFSSL_SUCCESS; - loaded = 1; - -#if FIPS_VERSION_GE(2,0) /* Gate back to cert 3389 FIPS modules */ -#warning "Cryptographic operations may occur outside the FIPS module boundary" \ - "Please review FIPS claims for cryptography on this Apple device" -#endif /* FIPS_VERSION_GE(2,0) */ + WOLFSSL_ENTER("wolfSSL_d2i_PublicKey"); -#else -/* HAVE_SECURITY_SECXXX_H macros are set by autotools or CMake when searching - * system for the required SDK headers. If building with user_settings.h, you - * will need to manually define WOLFSSL_APPLE_NATIVE_CERT_VALIDATION - * and ensure the appropriate Security.framework headers and libraries are - * visible to your compiler */ -#error "WOLFSSL_SYS_CA_CERTS on Apple devices requires Security.framework" \ - " header files to be detected, or a manual override with" \ - " WOLFSSL_APPLE_NATIVE_CERT_VALIDATION" -#endif - -#else + return _d2i_PublicKey(type, out, in, inSz, 0); +} +/* Reads in a DER format key. If PKCS8 headers are found they are stripped off. + * + * type type of key + * out newly created WOLFSSL_EVP_PKEY structure + * in pointer to input key DER + * inSz size of in buffer + * + * On success a non null pointer is returned and the pointer in is advanced the + * same number of bytes read. + */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey(int type, WOLFSSL_EVP_PKEY** out, + const unsigned char **in, long inSz) +{ + WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey"); - ret = LoadSystemCaCertsNix(ctx, &loaded); + return _d2i_PublicKey(type, out, in, inSz, 1); +} -#endif +#ifdef WOLF_PRIVATE_KEY_ID +/* Create an EVP structure for use with crypto callbacks */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out, + void* heap, int devId) +{ + WOLFSSL_EVP_PKEY* local; - if (ret == WOLFSSL_SUCCESS && !loaded) { - ret = WOLFSSL_BAD_PATH; + if (out != NULL && *out != NULL) { + wolfSSL_EVP_PKEY_free(*out); + *out = NULL; } - WOLFSSL_LEAVE("wolfSSL_CTX_load_system_CA_certs", ret); + local = wolfSSL_EVP_PKEY_new_ex(heap); + if (local == NULL) { + return NULL; + } - return ret; -} + local->type = type; + local->pkey_sz = 0; + local->pkcs8HeaderSz = 0; -#endif /* WOLFSSL_SYS_CA_CERTS */ + switch (type) { +#ifndef NO_RSA + case EVP_PKEY_RSA: + { + RsaKey* key; + local->ownRsa = 1; + local->rsa = wolfSSL_RSA_new_ex(heap, devId); + if (local->rsa == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + key = (RsaKey*)local->rsa->internal; + #ifdef WOLF_CRYPTO_CB + key->devId = devId; + #endif + (void)key; + local->rsa->inSet = 1; + break; + } +#endif /* !NO_RSA */ +#ifdef HAVE_ECC + case EVP_PKEY_EC: + { + ecc_key* key; + local->ownEcc = 1; + local->ecc = wolfSSL_EC_KEY_new_ex(heap, devId); + if (local->ecc == NULL) { + wolfSSL_EVP_PKEY_free(local); + return NULL; + } + key = (ecc_key*)local->ecc->internal; + #ifdef WOLF_CRYPTO_CB + key->devId = devId; + #endif + key->type = ECC_PRIVATEKEY; + /* key is required to have a key size / curve set, although + * actual one used is determined by devId callback function */ + wc_ecc_set_curve(key, ECDHE_SIZE, ECC_CURVE_DEF); -#ifdef WOLFSSL_TRUST_PEER_CERT -/* Used to specify a peer cert to match when connecting - ctx : the ctx structure to load in peer cert - file: the string name of cert file - type: type of format such as PEM/DER - */ -int wolfSSL_CTX_trust_peer_cert(WOLFSSL_CTX* ctx, const char* file, int type) -{ - WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_cert"); + local->ecc->inSet = 1; + break; + } +#endif /* HAVE_ECC */ + default: + WOLFSSL_MSG("Unsupported private key id type"); + wolfSSL_EVP_PKEY_free(local); + return NULL; + } - if (ctx == NULL || file == NULL) { - return WOLFSSL_FAILURE; + if (local != NULL && out != NULL) { + *out = local; } - return ProcessFile(ctx, file, type, TRUSTED_PEER_TYPE, NULL, 0, NULL, - GET_VERIFY_SETTING_CTX(ctx)); + return local; } +#endif /* WOLF_PRIVATE_KEY_ID */ + +#ifndef NO_CERTS /* // NOLINT(readability-redundant-preprocessor) */ -int wolfSSL_trust_peer_cert(WOLFSSL* ssl, const char* file, int type) +#ifndef NO_CHECK_PRIVATE_KEY +/* Check private against public in certificate for match + * + * ssl WOLFSSL structure to check private key in + * + * Returns WOLFSSL_SUCCESS on good private key + * WOLFSSL_FAILURE if mismatched. */ +int wolfSSL_check_private_key(const WOLFSSL* ssl) { - WOLFSSL_ENTER("wolfSSL_trust_peer_cert"); + int res = WOLFSSL_SUCCESS; - if (ssl == NULL || file == NULL) { + if (ssl == NULL) { return WOLFSSL_FAILURE; } +#ifdef WOLFSSL_DUAL_ALG_CERTS +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + wolfssl_priv_der_unblind(ssl->buffers.altKey, ssl->buffers.altKeyMask); +#endif + res = check_cert_key(ssl->buffers.certificate, ssl->buffers.key, + ssl->buffers.altKey, ssl->heap, ssl->buffers.keyDevId, + ssl->buffers.keyLabel, ssl->buffers.keyId, ssl->buffers.altKeyDevId, + ssl->buffers.altKeyLabel, ssl->buffers.altKeyId); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (res == WOLFSSL_SUCCESS) { + int ret; + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + (DerBuffer**)&ssl->buffers.keyMask); + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, + (DerBuffer**)&ssl->buffers.altKeyMask); + } + if (ret != 0) { + res = WOLFSSL_FAILURE; + } + } +#endif +#else +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); +#endif + res = check_cert_key(ssl->buffers.certificate, ssl->buffers.key, NULL, + ssl->heap, ssl->buffers.keyDevId, ssl->buffers.keyLabel, + ssl->buffers.keyId, INVALID_DEVID, 0, 0); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (res == WOLFSSL_SUCCESS) { + int ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + (DerBuffer**)&ssl->buffers.keyMask); + if (ret != 0) { + res = WOLFSSL_FAILURE; + } + } +#endif +#endif - return ProcessFile(NULL, file, type, TRUSTED_PEER_TYPE, ssl, 0, NULL, - GET_VERIFY_SETTING_SSL(ssl)); + return res; } -#endif /* WOLFSSL_TRUST_PEER_CERT */ +#endif /* !NO_CHECK_PRIVATE_KEY */ -#endif /* NO_FILESYSTEM */ +#endif /* !NO_CERTS */ -#ifdef HAVE_CRL +#endif /* OPENSSL_EXTRA */ -int wolfSSL_EnableCRL(WOLFSSL* ssl, int options) +#if defined(HAVE_RPK) +/* Confirm that all the byte data in the buffer is unique. + * return 1 if all the byte data in the buffer is unique, otherwise 0. + */ +static int isArrayUnique(const char* buf, size_t len) { - WOLFSSL_ENTER("wolfSSL_EnableCRL"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerEnableCRL(SSL_CM(ssl), options); + size_t i, j; + /* check the array is unique */ + for (i = 0; i < len -1; ++i) { + for (j = i+ 1; j < len; ++j) { + if (buf[i] == buf[j]) { + return 0; + } + } } - else - return BAD_FUNC_ARG; + return 1; } - -int wolfSSL_DisableCRL(WOLFSSL* ssl) +/* Set user preference for the client_cert_type exetnsion. + * Takes byte array containing cert types the caller can provide to its peer. + * Cert types are in preferred order in the array. + */ +WOLFSSL_API int wolfSSL_CTX_set_client_cert_type(WOLFSSL_CTX* ctx, + const char* buf, int bufLen) { - WOLFSSL_ENTER("wolfSSL_DisableCRL"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerDisableCRL(SSL_CM(ssl)); - } - else - return BAD_FUNC_ARG; -} + int i; -#ifndef NO_FILESYSTEM -int wolfSSL_LoadCRL(WOLFSSL* ssl, const char* path, int type, int monitor) -{ - WOLFSSL_ENTER("wolfSSL_LoadCRL"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerLoadCRL(SSL_CM(ssl), path, type, monitor); - } - else + if (ctx == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) { return BAD_FUNC_ARG; -} + } -int wolfSSL_LoadCRLFile(WOLFSSL* ssl, const char* file, int type) -{ - WOLFSSL_ENTER("wolfSSL_LoadCRLFile"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerLoadCRLFile(SSL_CM(ssl), file, type); + /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ + if (buf == NULL || bufLen == 0) { + ctx->rpkConfig.preferred_ClientCertTypeCnt = 1; + ctx->rpkConfig.preferred_ClientCertTypes[0]= WOLFSSL_CERT_TYPE_X509; + ctx->rpkConfig.preferred_ClientCertTypes[1]= WOLFSSL_CERT_TYPE_X509; + return WOLFSSL_SUCCESS; } - else + + if (!isArrayUnique(buf, (size_t)bufLen)) return BAD_FUNC_ARG; -} -#endif + for (i = 0; i < bufLen; i++){ + if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) + return BAD_FUNC_ARG; -int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb) -{ - WOLFSSL_ENTER("wolfSSL_SetCRL_Cb"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerSetCRL_Cb(SSL_CM(ssl), cb); + ctx->rpkConfig.preferred_ClientCertTypes[i] = (byte)buf[i]; } - else - return BAD_FUNC_ARG; -} + ctx->rpkConfig.preferred_ClientCertTypeCnt = bufLen; -#ifdef HAVE_CRL_IO -int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb) -{ - WOLFSSL_ENTER("wolfSSL_SetCRL_Cb"); - if (ssl) { - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerSetCRL_IOCb(SSL_CM(ssl), cb); - } - else - return BAD_FUNC_ARG; + return WOLFSSL_SUCCESS; } -#endif -int wolfSSL_CTX_EnableCRL(WOLFSSL_CTX* ctx, int options) +/* Set user preference for the server_cert_type exetnsion. + * Takes byte array containing cert types the caller can provide to its peer. + * Cert types are in preferred order in the array. + */ +WOLFSSL_API int wolfSSL_CTX_set_server_cert_type(WOLFSSL_CTX* ctx, + const char* buf, int bufLen) { - WOLFSSL_ENTER("wolfSSL_CTX_EnableCRL"); - if (ctx) - return wolfSSL_CertManagerEnableCRL(ctx->cm, options); - else + int i; + + if (ctx == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) { return BAD_FUNC_ARG; -} + } + /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ + if (buf == NULL || bufLen == 0) { + ctx->rpkConfig.preferred_ServerCertTypeCnt = 1; + ctx->rpkConfig.preferred_ServerCertTypes[0]= WOLFSSL_CERT_TYPE_X509; + ctx->rpkConfig.preferred_ServerCertTypes[1]= WOLFSSL_CERT_TYPE_X509; + return WOLFSSL_SUCCESS; + } -int wolfSSL_CTX_DisableCRL(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_DisableCRL"); - if (ctx) - return wolfSSL_CertManagerDisableCRL(ctx->cm); - else + if (!isArrayUnique(buf, (size_t)bufLen)) return BAD_FUNC_ARG; -} + for (i = 0; i < bufLen; i++){ + if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) + return BAD_FUNC_ARG; -#ifndef NO_FILESYSTEM -int wolfSSL_CTX_LoadCRL(WOLFSSL_CTX* ctx, const char* path, - int type, int monitor) -{ - WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL"); - if (ctx) - return wolfSSL_CertManagerLoadCRL(ctx->cm, path, type, monitor); - else - return BAD_FUNC_ARG; -} + ctx->rpkConfig.preferred_ServerCertTypes[i] = (byte)buf[i]; + } + ctx->rpkConfig.preferred_ServerCertTypeCnt = bufLen; -int wolfSSL_CTX_LoadCRLFile(WOLFSSL_CTX* ctx, const char* file, - int type) -{ - WOLFSSL_ENTER("wolfSSL_CTX_LoadCRL"); - if (ctx) - return wolfSSL_CertManagerLoadCRLFile(ctx->cm, file, type); - else - return BAD_FUNC_ARG; + return WOLFSSL_SUCCESS; } -#endif - -int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb) +/* Set user preference for the client_cert_type exetnsion. + * Takes byte array containing cert types the caller can provide to its peer. + * Cert types are in preferred order in the array. + */ +WOLFSSL_API int wolfSSL_set_client_cert_type(WOLFSSL* ssl, + const char* buf, int bufLen) { - WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_Cb"); - if (ctx) - return wolfSSL_CertManagerSetCRL_Cb(ctx->cm, cb); - else - return BAD_FUNC_ARG; -} + int i; -#ifdef HAVE_CRL_IO -int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb) -{ - WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_IOCb"); - if (ctx) - return wolfSSL_CertManagerSetCRL_IOCb(ctx->cm, cb); - else + if (ssl == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) { return BAD_FUNC_ARG; -} -#endif - - -#endif /* HAVE_CRL */ - - -#ifndef NO_FILESYSTEM - - -#ifdef WOLFSSL_DER_LOAD - -/* Add format parameter to allow DER load of CA files */ -int wolfSSL_CTX_der_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, - int format) -{ - WOLFSSL_ENTER("wolfSSL_CTX_der_load_verify_locations"); - if (ctx == NULL || file == NULL) - return WOLFSSL_FAILURE; + } - if (ProcessFile(ctx, file, format, CA_TYPE, NULL, 0, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { + /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ + if (buf == NULL || bufLen == 0) { + ssl->options.rpkConfig.preferred_ClientCertTypeCnt = 1; + ssl->options.rpkConfig.preferred_ClientCertTypes[0] + = WOLFSSL_CERT_TYPE_X509; + ssl->options.rpkConfig.preferred_ClientCertTypes[1] + = WOLFSSL_CERT_TYPE_X509; return WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; -} - -#endif /* WOLFSSL_DER_LOAD */ - - + if (!isArrayUnique(buf, (size_t)bufLen)) + return BAD_FUNC_ARG; -WOLFSSL_ABI -int wolfSSL_CTX_use_certificate_file(WOLFSSL_CTX* ctx, const char* file, - int format) -{ - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_file"); + for (i = 0; i < bufLen; i++){ + if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) + return BAD_FUNC_ARG; - if (ProcessFile(ctx, file, format, CERT_TYPE, NULL, 0, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; + ssl->options.rpkConfig.preferred_ClientCertTypes[i] = (byte)buf[i]; } + ssl->options.rpkConfig.preferred_ClientCertTypeCnt = bufLen; - return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } - -WOLFSSL_ABI -int wolfSSL_CTX_use_PrivateKey_file(WOLFSSL_CTX* ctx, const char* file, - int format) +/* Set user preference for the server_cert_type exetnsion. + * Takes byte array containing cert types the caller can provide to its peer. + * Cert types are in preferred order in the array. + */ +WOLFSSL_API int wolfSSL_set_server_cert_type(WOLFSSL* ssl, + const char* buf, int bufLen) { - WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_file"); + int i; - if (ProcessFile(ctx, file, format, PRIVATEKEY_TYPE, NULL, 0, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; + if (ssl == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) { + return BAD_FUNC_ARG; } - return WOLFSSL_FAILURE; -} - -#ifdef WOLFSSL_DUAL_ALG_CERTS -int wolfSSL_CTX_use_AltPrivateKey_file(WOLFSSL_CTX* ctx, const char* file, - int format) -{ - WOLFSSL_ENTER("wolfSSL_CTX_use_AltPrivateKey_file"); - - if (ProcessFile(ctx, file, format, ALT_PRIVATEKEY_TYPE, NULL, 0, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { + /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ + if (buf == NULL || bufLen == 0) { + ssl->options.rpkConfig.preferred_ServerCertTypeCnt = 1; + ssl->options.rpkConfig.preferred_ServerCertTypes[0] + = WOLFSSL_CERT_TYPE_X509; + ssl->options.rpkConfig.preferred_ServerCertTypes[1] + = WOLFSSL_CERT_TYPE_X509; return WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; -} -#endif /* WOLFSSL_DUAL_ALG_CERTS */ -#endif /* NO_FILESYSTEM */ - + if (!isArrayUnique(buf, (size_t)bufLen)) + return BAD_FUNC_ARG; -/* Sets the max chain depth when verifying a certificate chain. Default depth - * is set to MAX_CHAIN_DEPTH. - * - * ctx WOLFSSL_CTX structure to set depth in - * depth max depth - */ -void wolfSSL_CTX_set_verify_depth(WOLFSSL_CTX *ctx, int depth) { - WOLFSSL_ENTER("wolfSSL_CTX_set_verify_depth"); + for (i = 0; i < bufLen; i++){ + if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) + return BAD_FUNC_ARG; - if (ctx == NULL || depth < 0 || depth > MAX_CHAIN_DEPTH) { - WOLFSSL_MSG("Bad depth argument, too large or less than 0"); - return; + ssl->options.rpkConfig.preferred_ServerCertTypes[i] = (byte)buf[i]; } + ssl->options.rpkConfig.preferred_ServerCertTypeCnt = bufLen; - ctx->verifyDepth = (byte)depth; + return WOLFSSL_SUCCESS; } - -/* get cert chaining depth using ssl struct */ -long wolfSSL_get_verify_depth(WOLFSSL* ssl) +/* get negotiated certificate type value and return it to the second parameter. + * cert type value: + * -1: WOLFSSL_CERT_TYPE_UNKNOWN + * 0: WOLFSSL_CERT_TYPE_X509 + * 2: WOLFSSL_CERT_TYPE_RPK + * return WOLFSSL_SUCCESS on success, otherwise negative value. + * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for + * cert type. + */ +WOLFSSL_API int wolfSSL_get_negotiated_client_cert_type(WOLFSSL* ssl, int* tp) { - if(ssl == NULL) { - return BAD_FUNC_ARG; - } -#ifndef OPENSSL_EXTRA - return MAX_CHAIN_DEPTH; -#else - return ssl->options.verifyDepth; -#endif -} - + int ret = WOLFSSL_SUCCESS; -/* get cert chaining depth using ctx struct */ -long wolfSSL_CTX_get_verify_depth(WOLFSSL_CTX* ctx) -{ - if (ctx == NULL) { + if (ssl == NULL || tp == NULL) return BAD_FUNC_ARG; - } -#ifndef OPENSSL_EXTRA - return MAX_CHAIN_DEPTH; -#else - return ctx->verifyDepth; -#endif -} - -#ifndef NO_FILESYSTEM - - -WOLFSSL_ABI -int wolfSSL_CTX_use_certificate_chain_file(WOLFSSL_CTX* ctx, const char* file) -{ - /* process up to MAX_CHAIN_DEPTH plus subject cert */ - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file"); - - if (ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE, NULL, 1, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; + if (ssl->options.side == WOLFSSL_CLIENT_END) { + if (ssl->options.rpkState.received_ClientCertTypeCnt == 1) + *tp = ssl->options.rpkState.received_ClientCertTypes[0]; + else + *tp = WOLFSSL_CERT_TYPE_UNKNOWN; } - - return WOLFSSL_FAILURE; + else { + if (ssl->options.rpkState.sending_ClientCertTypeCnt == 1) + *tp = ssl->options.rpkState.sending_ClientCertTypes[0]; + else + *tp = WOLFSSL_CERT_TYPE_UNKNOWN; + } + return ret; } - -int wolfSSL_CTX_use_certificate_chain_file_format(WOLFSSL_CTX* ctx, - const char* file, int format) +/* get negotiated certificate type value and return it to the second parameter. + * cert type value: + * -1: WOLFSSL_CERT_TYPE_UNKNOWN + * 0: WOLFSSL_CERT_TYPE_X509 + * 2: WOLFSSL_CERT_TYPE_RPK + * return WOLFSSL_SUCCESS on success, otherwise negative value. + * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for + * cert type. + */ +WOLFSSL_API int wolfSSL_get_negotiated_server_cert_type(WOLFSSL* ssl, int* tp) { - /* process up to MAX_CHAIN_DEPTH plus subject cert */ - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file_format"); + int ret = WOLFSSL_SUCCESS; - if (ProcessFile(ctx, file, format, CERT_TYPE, NULL, 1, NULL, - GET_VERIFY_SETTING_CTX(ctx)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } + if (ssl == NULL || tp == NULL) + return BAD_FUNC_ARG; - return WOLFSSL_FAILURE; + if (ssl->options.side == WOLFSSL_CLIENT_END) { + if (ssl->options.rpkState.received_ServerCertTypeCnt == 1) + *tp = ssl->options.rpkState.received_ServerCertTypes[0]; + else + *tp = WOLFSSL_CERT_TYPE_UNKNOWN; + } + else { + if (ssl->options.rpkState.sending_ServerCertTypeCnt == 1) + *tp = ssl->options.rpkState.sending_ServerCertTypes[0]; + else + *tp = WOLFSSL_CERT_TYPE_UNKNOWN; + } + return ret; } +#endif /* HAVE_RPK */ -#ifndef NO_DH +#ifdef HAVE_ECC -/* server Diffie-Hellman parameters */ -static int wolfSSL_SetTmpDH_file_wrapper(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - const char* fname, int format) +/* Set Temp CTX EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */ +int wolfSSL_CTX_SetTmpEC_DHE_Sz(WOLFSSL_CTX* ctx, word16 sz) { -#ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force heap usage */ -#else - byte staticBuffer[FILE_BUFFER_SIZE]; -#endif - byte* myBuffer = staticBuffer; - int dynamic = 0; - int ret; - long sz = 0; - XFILE file; + WOLFSSL_ENTER("wolfSSL_CTX_SetTmpEC_DHE_Sz"); - if (ctx == NULL || fname == NULL) + if (ctx == NULL) return BAD_FUNC_ARG; - file = XFOPEN(fname, "rb"); - if (file == XBADFILE) return WOLFSSL_BAD_FILE; - if(XFSEEK(file, 0, XSEEK_END) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - sz = XFTELL(file); - if(XFSEEK(file, 0, XSEEK_SET) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - - if (sz > MAX_WOLFSSL_FILE_SIZE || sz <= 0) { - WOLFSSL_MSG("SetTmpDH file size error"); - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } + /* if 0 then get from loaded private key */ + if (sz == 0) { + /* applies only to ECDSA */ + if (ctx->privateKeyType != ecc_dsa_sa_algo) + return WOLFSSL_SUCCESS; - if (sz > (long)sizeof(staticBuffer)) { - WOLFSSL_MSG("Getting dynamic buffer"); - myBuffer = (byte*) XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE); - if (myBuffer == NULL) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; + if (ctx->privateKeySz == 0) { + WOLFSSL_MSG("Must set private key/cert first"); + return BAD_FUNC_ARG; } - dynamic = 1; - } - if ((size_t)XFREAD(myBuffer, 1, sz, file) != (size_t)sz) - ret = WOLFSSL_BAD_FILE; - else { - if (ssl) - ret = wolfSSL_SetTmpDH_buffer(ssl, myBuffer, sz, format); - else - ret = wolfSSL_CTX_SetTmpDH_buffer(ctx, myBuffer, sz, format); + sz = (word16)ctx->privateKeySz; } - XFCLOSE(file); - if (dynamic) - XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE); + /* check size */ +#if ECC_MIN_KEY_SZ > 0 + if (sz < ECC_MINSIZE) + return BAD_FUNC_ARG; +#endif + if (sz > ECC_MAXSIZE) + return BAD_FUNC_ARG; + + ctx->eccTempKeySz = sz; - return ret; + return WOLFSSL_SUCCESS; } -/* server Diffie-Hellman parameters */ -int wolfSSL_SetTmpDH_file(WOLFSSL* ssl, const char* fname, int format) + +/* Set Temp SSL EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */ +int wolfSSL_SetTmpEC_DHE_Sz(WOLFSSL* ssl, word16 sz) { + WOLFSSL_ENTER("wolfSSL_SetTmpEC_DHE_Sz"); + if (ssl == NULL) return BAD_FUNC_ARG; - return wolfSSL_SetTmpDH_file_wrapper(ssl->ctx, ssl, fname, format); -} + /* check size */ +#if ECC_MIN_KEY_SZ > 0 + if (sz < ECC_MINSIZE) + return BAD_FUNC_ARG; +#endif + if (sz > ECC_MAXSIZE) + return BAD_FUNC_ARG; + ssl->eccTempKeySz = sz; -/* server Diffie-Hellman parameters */ -int wolfSSL_CTX_SetTmpDH_file(WOLFSSL_CTX* ctx, const char* fname, int format) -{ - return wolfSSL_SetTmpDH_file_wrapper(ctx, NULL, fname, format); + return WOLFSSL_SUCCESS; } -#endif /* NO_DH */ - -#endif /* NO_FILESYSTEM */ +#endif /* HAVE_ECC */ -#ifndef NO_CHECK_PRIVATE_KEY -/* Check private against public in certificate for match - * - * Returns WOLFSSL_SUCCESS on good private key - * WOLFSSL_FAILURE if mismatched */ -static int check_cert_key(DerBuffer* cert, DerBuffer* key, void* heap, - int devId, int isKeyLabel, int isKeyId) -{ -#ifdef WOLFSSL_SMALL_STACK - DecodedCert* der = NULL; -#else - DecodedCert der[1]; -#endif - word32 size; - byte* buff; - int ret = WOLFSSL_FAILURE; - WOLFSSL_ENTER("check_cert_key"); +typedef struct { + byte verifyPeer:1; + byte verifyNone:1; + byte failNoCert:1; + byte failNoCertxPSK:1; + byte verifyPostHandshake:1; +} SetVerifyOptions; - if (cert == NULL || key == NULL) { - return WOLFSSL_FAILURE; - } +static SetVerifyOptions ModeToVerifyOptions(int mode) +{ + SetVerifyOptions opts; + XMEMSET(&opts, 0, sizeof(SetVerifyOptions)); -#ifdef WOLFSSL_SMALL_STACK - der = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT); - if (der == NULL) - return MEMORY_E; + if (mode != WOLFSSL_VERIFY_DEFAULT) { + opts.verifyNone = (mode == WOLFSSL_VERIFY_NONE); + if (!opts.verifyNone) { + opts.verifyPeer = + (mode & WOLFSSL_VERIFY_PEER) != 0; + opts.failNoCertxPSK = + (mode & WOLFSSL_VERIFY_FAIL_EXCEPT_PSK) != 0; + opts.failNoCert = + (mode & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0; +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) + opts.verifyPostHandshake = + (mode & WOLFSSL_VERIFY_POST_HANDSHAKE) != 0; #endif - - size = cert->length; - buff = cert->buffer; - InitDecodedCert_ex(der, buff, size, heap, devId); - if (ParseCertRelative(der, CERT_TYPE, NO_VERIFY, NULL) != 0) { - FreeDecodedCert(der); - #ifdef WOLFSSL_SMALL_STACK - XFREE(der, NULL, DYNAMIC_TYPE_DCERT); - #endif - return WOLFSSL_FAILURE; - } - - size = key->length; - buff = key->buffer; -#ifdef WOLF_PRIVATE_KEY_ID - if (devId != INVALID_DEVID) { - int type = 0; - void *pkey = NULL; - - #ifndef NO_RSA - if (der->keyOID == RSAk) { - type = DYNAMIC_TYPE_RSA; - } - #ifdef WC_RSA_PSS - if (der->keyOID == RSAPSSk) { - type = DYNAMIC_TYPE_RSA; - } - #endif - #endif - #ifdef HAVE_ECC - if (der->keyOID == ECDSAk) { - type = DYNAMIC_TYPE_ECC; - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) - if ((der->keyOID == DILITHIUM_LEVEL2k) || - (der->keyOID == DILITHIUM_LEVEL3k) || - (der->keyOID == DILITHIUM_LEVEL5k)) { - type = DYNAMIC_TYPE_DILITHIUM; - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_FALCON) - if ((der->keyOID == FALCON_LEVEL1k) || - (der->keyOID == FALCON_LEVEL5k)) { - type = DYNAMIC_TYPE_FALCON; - } - #endif - - ret = CreateDevPrivateKey(&pkey, buff, size, type, - isKeyLabel, isKeyId, heap, devId); - #ifdef WOLF_CRYPTO_CB - if (ret == 0) { - #ifndef NO_RSA - if (der->keyOID == RSAk - #ifdef WC_RSA_PSS - || der->keyOID == RSAPSSk - #endif - ) { - ret = wc_CryptoCb_RsaCheckPrivKey((RsaKey*)pkey, - der->publicKey, der->pubKeySize); - } - #endif - #ifdef HAVE_ECC - if (der->keyOID == ECDSAk) { - ret = wc_CryptoCb_EccCheckPrivKey((ecc_key*)pkey, - der->publicKey, der->pubKeySize); - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) - if ((der->keyOID == DILITHIUM_LEVEL2k) || - (der->keyOID == DILITHIUM_LEVEL3k) || - (der->keyOID == DILITHIUM_LEVEL5k)) { - ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey, - WC_PQC_SIG_TYPE_DILITHIUM, - der->publicKey, der->pubKeySize); - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_FALCON) - if ((der->keyOID == FALCON_LEVEL1k) || - (der->keyOID == FALCON_LEVEL5k)) { - ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey, - WC_PQC_SIG_TYPE_FALCON, - der->publicKey, der->pubKeySize); - } - #endif - } - #else - /* devId was set, don't check, for now */ - /* TODO: Add callback for private key check? */ - #endif - if (pkey != NULL) { - #ifndef NO_RSA - if (der->keyOID == RSAk - #ifdef WC_RSA_PSS - || der->keyOID == RSAPSSk - #endif - ) { - wc_FreeRsaKey((RsaKey*)pkey); - } - #endif - #ifdef HAVE_ECC - if (der->keyOID == ECDSAk) { - wc_ecc_free((ecc_key*)pkey); - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) - if ((der->keyOID == DILITHIUM_LEVEL2k) || - (der->keyOID == DILITHIUM_LEVEL3k) || - (der->keyOID == DILITHIUM_LEVEL5k)) { - wc_dilithium_free((dilithium_key*)pkey); - } - #endif - #if defined(HAVE_PQC) && defined(HAVE_FALCON) - if ((der->keyOID == FALCON_LEVEL1k) || - (der->keyOID == FALCON_LEVEL5k)) { - wc_falcon_free((falcon_key*)pkey); - } - #endif - XFREE(pkey, heap, type); } - if (ret != CRYPTOCB_UNAVAILABLE) { - ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; - } - } - else { - /* fall through if unavailable */ - ret = CRYPTOCB_UNAVAILABLE; - } - - if (ret == CRYPTOCB_UNAVAILABLE) -#endif /* WOLF_PRIVATE_KEY_ID */ - { - ret = wc_CheckPrivateKeyCert(buff, size, der); - ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; } - FreeDecodedCert(der); -#ifdef WOLFSSL_SMALL_STACK - XFREE(der, NULL, DYNAMIC_TYPE_DCERT); -#endif - - (void)devId; - (void)isKeyLabel; - (void)isKeyId; - - return ret; -} -/* Check private against public in certificate for match - * - * ctx WOLFSSL_CTX structure to check private key in - * - * Returns WOLFSSL_SUCCESS on good private key - * WOLFSSL_FAILURE if mismatched. */ -int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx) -{ - if (ctx == NULL) { - return WOLFSSL_FAILURE; - } - return check_cert_key(ctx->certificate, ctx->privateKey, ctx->heap, - ctx->privateKeyDevId, ctx->privateKeyLabel, ctx->privateKeyId); + return opts; } -#endif /* !NO_CHECK_PRIVATE_KEY */ -#ifdef OPENSSL_ALL -/** - * Return the private key of the WOLFSSL_CTX struct - * @return WOLFSSL_EVP_PKEY* The caller doesn *NOT*` free the returned object. - */ -WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx) +WOLFSSL_ABI +void wolfSSL_CTX_set_verify(WOLFSSL_CTX* ctx, int mode, VerifyCallback vc) { - const unsigned char *key; - int type; + SetVerifyOptions opts; - WOLFSSL_ENTER("wolfSSL_CTX_get0_privatekey"); + WOLFSSL_ENTER("wolfSSL_CTX_set_verify"); + if (ctx == NULL) + return; - if (ctx == NULL || ctx->privateKey == NULL || - ctx->privateKey->buffer == NULL) { - WOLFSSL_MSG("Bad parameter or key not set"); - return NULL; - } + opts = ModeToVerifyOptions(mode); - switch (ctx->privateKeyType) { -#ifndef NO_RSA - case rsa_sa_algo: - type = EVP_PKEY_RSA; - break; -#endif -#ifdef HAVE_ECC - case ecc_dsa_sa_algo: - type = EVP_PKEY_EC; - break; -#endif -#ifdef WOLFSSL_SM2 - case sm2_sa_algo: - type = EVP_PKEY_EC; - break; + ctx->verifyNone = opts.verifyNone; + ctx->verifyPeer = opts.verifyPeer; + ctx->failNoCert = opts.failNoCert; + ctx->failNoCertxPSK = opts.failNoCertxPSK; +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) + ctx->verifyPostHandshake = opts.verifyPostHandshake; #endif - default: - /* Other key types not supported either as ssl private keys - * or in the EVP layer */ - WOLFSSL_MSG("Unsupported key type"); - return NULL; - } - key = ctx->privateKey->buffer; + ctx->verifyCallback = vc; +} - if (ctx->privateKeyPKey != NULL) - return ctx->privateKeyPKey; - else - return wolfSSL_d2i_PrivateKey(type, - (WOLFSSL_EVP_PKEY**)&ctx->privateKeyPKey, &key, - (long)ctx->privateKey->length); +#ifdef OPENSSL_ALL +void wolfSSL_CTX_set_cert_verify_callback(WOLFSSL_CTX* ctx, + CertVerifyCallback cb, void* arg) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_cert_verify_callback"); + if (ctx == NULL) + return; + + ctx->verifyCertCb = cb; + ctx->verifyCertCbArg = arg; } #endif -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -static WOLFSSL_EVP_PKEY* d2iGenericKey(WOLFSSL_EVP_PKEY** out, - const unsigned char** in, long inSz, int priv) +void wolfSSL_set_verify(WOLFSSL* ssl, int mode, VerifyCallback vc) { + SetVerifyOptions opts; - WOLFSSL_EVP_PKEY* pkey = NULL; - const unsigned char* mem; - long memSz = inSz; + WOLFSSL_ENTER("wolfSSL_set_verify"); + if (ssl == NULL) + return; - WOLFSSL_ENTER("d2iGenericKey"); + opts = ModeToVerifyOptions(mode); - if (in == NULL || *in == NULL || inSz < 0) { - WOLFSSL_MSG("Bad argument"); - return NULL; - } - mem = *in; + ssl->options.verifyNone = opts.verifyNone; + ssl->options.verifyPeer = opts.verifyPeer; + ssl->options.failNoCert = opts.failNoCert; + ssl->options.failNoCertxPSK = opts.failNoCertxPSK; +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) + ssl->options.verifyPostHandshake = opts.verifyPostHandshake; +#endif - #if !defined(NO_RSA) - { - word32 keyIdx = 0; - int isRsaKey; - #ifdef WOLFSSL_SMALL_STACK - RsaKey *rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA); - if (rsa == NULL) - return NULL; - #else - RsaKey rsa[1]; - #endif - XMEMSET(rsa, 0, sizeof(RsaKey)); + ssl->verifyCallback = vc; +} - /* test if RSA key */ - if (priv) - isRsaKey = wc_InitRsaKey(rsa, NULL) == 0 && - wc_RsaPrivateKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0; - else - isRsaKey = wc_InitRsaKey(rsa, NULL) == 0 && - wc_RsaPublicKeyDecode(mem, &keyIdx, rsa, (word32)memSz) == 0; - wc_FreeRsaKey(rsa); - #ifdef WOLFSSL_SMALL_STACK - XFREE(rsa, NULL, DYNAMIC_TYPE_RSA); - #endif +void wolfSSL_set_verify_result(WOLFSSL *ssl, long v) +{ + WOLFSSL_ENTER("wolfSSL_set_verify_result"); - if (isRsaKey) { - pkey = wolfSSL_EVP_PKEY_new(); - if (pkey != NULL) { - pkey->pkey_sz = keyIdx; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, - priv ? DYNAMIC_TYPE_PRIVATE_KEY : - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkey->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_RSA; - if (out != NULL) { - *out = pkey; - } + if (ssl == NULL) + return; - pkey->ownRsa = 1; - pkey->rsa = wolfssl_rsa_d2i(NULL, mem, inSz, - priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC); - if (pkey->rsa == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(OPENSSL_ALL) + ssl->peerVerifyRet = (unsigned long)v; +#else + (void)v; + WOLFSSL_STUB("wolfSSL_set_verify_result"); +#endif +} - return pkey; - } - else { - WOLFSSL_MSG("RSA wolfSSL_EVP_PKEY_new error"); - } +#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ + defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) +/* For TLS v1.3 send handshake messages after handshake completes. */ +/* Returns 1=WOLFSSL_SUCCESS or 0=WOLFSSL_FAILURE */ +int wolfSSL_verify_client_post_handshake(WOLFSSL* ssl) +{ + int ret = wolfSSL_request_certificate(ssl); + if (ret != WOLFSSL_SUCCESS) { + if (!IsAtLeastTLSv1_3(ssl->version)) { + /* specific error of wrong version expected */ + WOLFSSL_ERROR(UNSUPPORTED_PROTO_VERSION); + + } + else { + WOLFSSL_ERROR(ret); /* log the error in the error queue */ } } - #endif /* NO_RSA */ - - #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) - { - word32 keyIdx = 0; - int isEccKey; - #ifdef WOLFSSL_SMALL_STACK - ecc_key *ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC); - if (ecc == NULL) - return NULL; - #else - ecc_key ecc[1]; - #endif - XMEMSET(ecc, 0, sizeof(ecc_key)); - - if (priv) - isEccKey = wc_ecc_init(ecc) == 0 && - wc_EccPrivateKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0; - else - isEccKey = wc_ecc_init(ecc) == 0 && - wc_EccPublicKeyDecode(mem, &keyIdx, ecc, (word32)memSz) == 0; - wc_ecc_free(ecc); - #ifdef WOLFSSL_SMALL_STACK - XFREE(ecc, NULL, DYNAMIC_TYPE_ECC); - #endif + return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} - if (isEccKey) { - pkey = wolfSSL_EVP_PKEY_new(); - if (pkey != NULL) { - pkey->pkey_sz = keyIdx; - pkey->pkey.ptr = (char*)XMALLOC(keyIdx, NULL, - priv ? DYNAMIC_TYPE_PRIVATE_KEY : - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkey->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_EC; - if (out != NULL) { - *out = pkey; - } +int wolfSSL_CTX_set_post_handshake_auth(WOLFSSL_CTX* ctx, int val) +{ + int ret = wolfSSL_CTX_allow_post_handshake_auth(ctx); + if (ret == 0) { + ctx->postHandshakeAuth = (val != 0); + } + return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} +int wolfSSL_set_post_handshake_auth(WOLFSSL* ssl, int val) +{ + int ret = wolfSSL_allow_post_handshake_auth(ssl); + if (ret == 0) { + ssl->options.postHandshakeAuth = (val != 0); + } + return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} +#endif /* OPENSSL_EXTRA && !NO_CERTS && WOLFSSL_TLS13 && + * WOLFSSL_POST_HANDSHAKE_AUTH */ - pkey->ownEcc = 1; - pkey->ecc = wolfSSL_EC_KEY_new(); - if (pkey->ecc == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } +/* store user ctx for verify callback */ +void wolfSSL_SetCertCbCtx(WOLFSSL* ssl, void* ctx) +{ + WOLFSSL_ENTER("wolfSSL_SetCertCbCtx"); + if (ssl) + ssl->verifyCbCtx = ctx; +} - if (wolfSSL_EC_KEY_LoadDer_ex(pkey->ecc, - (const unsigned char*)pkey->pkey.ptr, - pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE - : WOLFSSL_RSA_LOAD_PUBLIC) != 1) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - return pkey; - } - else { - WOLFSSL_MSG("ECC wolfSSL_EVP_PKEY_new error"); - } - } - } - #endif /* HAVE_ECC && OPENSSL_EXTRA */ +/* store user ctx for verify callback */ +void wolfSSL_CTX_SetCertCbCtx(WOLFSSL_CTX* ctx, void* userCtx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_SetCertCbCtx"); + if (ctx) + ctx->verifyCbCtx = userCtx; +} - #if !defined(NO_DSA) - { - word32 keyIdx = 0; - int isDsaKey; - #ifdef WOLFSSL_SMALL_STACK - DsaKey *dsa = (DsaKey*)XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA); - if (dsa == NULL) - return NULL; - #else - DsaKey dsa[1]; - #endif - XMEMSET(dsa, 0, sizeof(DsaKey)); - if (priv) - isDsaKey = wc_InitDsaKey(dsa) == 0 && - wc_DsaPrivateKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0; - else - isDsaKey = wc_InitDsaKey(dsa) == 0 && - wc_DsaPublicKeyDecode(mem, &keyIdx, dsa, (word32)memSz) == 0; - wc_FreeDsaKey(dsa); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dsa, NULL, DYNAMIC_TYPE_DSA); - #endif +/* store context CA Cache addition callback */ +void wolfSSL_CTX_SetCACb(WOLFSSL_CTX* ctx, CallbackCACache cb) +{ + if (ctx && ctx->cm) + ctx->cm->caCacheCallback = cb; +} - /* test if DSA key */ - if (isDsaKey) { - pkey = wolfSSL_EVP_PKEY_new(); - - if (pkey != NULL) { - pkey->pkey_sz = keyIdx; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, - priv ? DYNAMIC_TYPE_PRIVATE_KEY : - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkey->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_DSA; - if (out != NULL) { - *out = pkey; - } - pkey->ownDsa = 1; - pkey->dsa = wolfSSL_DSA_new(); - if (pkey->dsa == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } +#if defined(PERSIST_CERT_CACHE) - if (wolfSSL_DSA_LoadDer_ex(pkey->dsa, - (const unsigned char*)pkey->pkey.ptr, - pkey->pkey_sz, priv ? WOLFSSL_RSA_LOAD_PRIVATE - : WOLFSSL_RSA_LOAD_PUBLIC) != 1) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } +#if !defined(NO_FILESYSTEM) - return pkey; - } - else { - WOLFSSL_MSG("DSA wolfSSL_EVP_PKEY_new error"); - } - } - } - #endif /* NO_DSA */ +/* Persist cert cache to file */ +int wolfSSL_CTX_save_cert_cache(WOLFSSL_CTX* ctx, const char* fname) +{ + WOLFSSL_ENTER("wolfSSL_CTX_save_cert_cache"); - #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) - #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ - (HAVE_FIPS_VERSION > 2)) - { - int isDhKey; - word32 keyIdx = 0; - #ifdef WOLFSSL_SMALL_STACK - DhKey *dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); - if (dh == NULL) - return NULL; - #else - DhKey dh[1]; - #endif - XMEMSET(dh, 0, sizeof(DhKey)); + if (ctx == NULL || fname == NULL) + return BAD_FUNC_ARG; - isDhKey = wc_InitDhKey(dh) == 0 && - wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz) == 0; - wc_FreeDhKey(dh); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dh, NULL, DYNAMIC_TYPE_DH); - #endif + return CM_SaveCertCache(ctx->cm, fname); +} - /* test if DH key */ - if (isDhKey) { - pkey = wolfSSL_EVP_PKEY_new(); - - if (pkey != NULL) { - pkey->pkey_sz = (int)memSz; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, - priv ? DYNAMIC_TYPE_PRIVATE_KEY : - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkey->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - XMEMCPY(pkey->pkey.ptr, mem, memSz); - pkey->type = EVP_PKEY_DH; - if (out != NULL) { - *out = pkey; - } - pkey->ownDh = 1; - pkey->dh = wolfSSL_DH_new(); - if (pkey->dh == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } +/* Persist cert cache from file */ +int wolfSSL_CTX_restore_cert_cache(WOLFSSL_CTX* ctx, const char* fname) +{ + WOLFSSL_ENTER("wolfSSL_CTX_restore_cert_cache"); - if (wolfSSL_DH_LoadDer(pkey->dh, - (const unsigned char*)pkey->pkey.ptr, - pkey->pkey_sz) != WOLFSSL_SUCCESS) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } + if (ctx == NULL || fname == NULL) + return BAD_FUNC_ARG; - return pkey; - } - else { - WOLFSSL_MSG("DH wolfSSL_EVP_PKEY_new error"); - } - } - } - #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ - #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */ + return CM_RestoreCertCache(ctx->cm, fname); +} - #if !defined(NO_DH) && defined(OPENSSL_EXTRA) && defined(WOLFSSL_DH_EXTRA) - #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ - (HAVE_FIPS_VERSION > 2)) - { - word32 keyIdx = 0; - DhKey* key = NULL; - int ret; - #ifdef WOLFSSL_SMALL_STACK - DhKey* dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); - if (dh == NULL) - return NULL; - #else - DhKey dh[1]; - #endif - XMEMSET(dh, 0, sizeof(DhKey)); +#endif /* NO_FILESYSTEM */ - /* test if DH-public key */ - if (wc_InitDhKey(dh) != 0) - return NULL; +/* Persist cert cache to memory */ +int wolfSSL_CTX_memsave_cert_cache(WOLFSSL_CTX* ctx, void* mem, + int sz, int* used) +{ + WOLFSSL_ENTER("wolfSSL_CTX_memsave_cert_cache"); - ret = wc_DhKeyDecode(mem, &keyIdx, dh, (word32)memSz); - wc_FreeDhKey(dh); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dh, NULL, DYNAMIC_TYPE_DH); - #endif + if (ctx == NULL || mem == NULL || used == NULL || sz <= 0) + return BAD_FUNC_ARG; - if (ret == 0) { - pkey = wolfSSL_EVP_PKEY_new(); - if (pkey != NULL) { - pkey->type = EVP_PKEY_DH; - pkey->pkey_sz = (int)memSz; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, - priv ? DYNAMIC_TYPE_PRIVATE_KEY : - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkey->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - XMEMCPY(pkey->pkey.ptr, mem, memSz); - if (out != NULL) { - *out = pkey; - } - pkey->ownDh = 1; - pkey->dh = wolfSSL_DH_new(); - if (pkey->dh == NULL) { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } + return CM_MemSaveCertCache(ctx->cm, mem, sz, used); +} - key = (DhKey*)pkey->dh->internal; - - keyIdx = 0; - if (wc_DhKeyDecode(mem, &keyIdx, key, (word32)memSz) == 0) - { - int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q | - ELEMENT_PUB; - if (priv) - elements |= ELEMENT_PRV; - if(SetDhExternal_ex(pkey->dh, elements) - == WOLFSSL_SUCCESS ) { - return pkey; - } - } - else { - wolfSSL_EVP_PKEY_free(pkey); - return NULL; - } - } - } - } - #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ - #endif /* !NO_DH && OPENSSL_EXTRA && WOLFSSL_DH_EXTRA */ - #ifdef HAVE_PQC - #ifdef HAVE_FALCON - { - int isFalcon = 0; - #ifdef WOLFSSL_SMALL_STACK - falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(falcon_key), NULL, - DYNAMIC_TYPE_FALCON); - if (falcon == NULL) { - return NULL; - } - #else - falcon_key falcon[1]; - #endif +/* Restore cert cache from memory */ +int wolfSSL_CTX_memrestore_cert_cache(WOLFSSL_CTX* ctx, const void* mem, int sz) +{ + WOLFSSL_ENTER("wolfSSL_CTX_memrestore_cert_cache"); - if (wc_falcon_init(falcon) == 0) { - /* test if Falcon key */ - if (priv) { - /* Try level 1 */ - isFalcon = wc_falcon_set_level(falcon, 1) == 0 && - wc_falcon_import_private_only(mem, (word32)memSz, - falcon) == 0; - if (!isFalcon) { - /* Try level 5 */ - isFalcon = wc_falcon_set_level(falcon, 5) == 0 && - wc_falcon_import_private_only(mem, (word32)memSz, - falcon) == 0; - } - } else { - /* Try level 1 */ - isFalcon = wc_falcon_set_level(falcon, 1) == 0 && - wc_falcon_import_public(mem, (word32)memSz, falcon) - == 0; - - if (!isFalcon) { - /* Try level 5 */ - isFalcon = wc_falcon_set_level(falcon, 5) == 0 && - wc_falcon_import_public(mem, (word32)memSz, - falcon) == 0; - } - } - wc_falcon_free(falcon); - } + if (ctx == NULL || mem == NULL || sz <= 0) + return BAD_FUNC_ARG; - #ifdef WOLFSSL_SMALL_STACK - XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); - #endif - if (isFalcon) { - /* Create a fake Falcon EVP_PKEY. In the future, we might integrate - * Falcon into the compatibility layer. */ - pkey = wolfSSL_EVP_PKEY_new(); - if (pkey == NULL) { - WOLFSSL_MSG("Falcon wolfSSL_EVP_PKEY_new error"); - return NULL; - } - pkey->type = EVP_PKEY_FALCON; - pkey->pkey.ptr = NULL; - pkey->pkey_sz = 0; - return pkey; - } + return CM_MemRestoreCertCache(ctx->cm, mem, sz); +} - } - #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM - { - int isDilithium = 0; - #ifdef WOLFSSL_SMALL_STACK - dilithium_key *dilithium = (dilithium_key *) - XMALLOC(sizeof(dilithium_key), NULL, DYNAMIC_TYPE_DILITHIUM); - if (dilithium == NULL) { - return NULL; - } - #else - dilithium_key dilithium[1]; - #endif - if (wc_dilithium_init(dilithium) == 0) { - /* Test if Dilithium key. Try all levels. */ - if (priv) { - isDilithium = wc_dilithium_set_level(dilithium, 2) == 0 && - wc_dilithium_import_private_only(mem, - (word32)memSz, dilithium) == 0; - if (!isDilithium) { - isDilithium = wc_dilithium_set_level(dilithium, 3) == 0 && - wc_dilithium_import_private_only(mem, - (word32)memSz, dilithium) == 0; - } - if (!isDilithium) { - isDilithium = wc_dilithium_set_level(dilithium, 5) == 0 && - wc_dilithium_import_private_only(mem, - (word32)memSz, dilithium) == 0; - } - } else { - isDilithium = wc_dilithium_set_level(dilithium, 2) == 0 && - wc_dilithium_import_public(mem, (word32)memSz, - dilithium) == 0; - if (!isDilithium) { - isDilithium = wc_dilithium_set_level(dilithium, 3) == 0 && - wc_dilithium_import_public(mem, (word32)memSz, - dilithium) == 0; - } - if (!isDilithium) { - isDilithium = wc_dilithium_set_level(dilithium, 5) == 0 && - wc_dilithium_import_public(mem, (word32)memSz, - dilithium) == 0; - } - } - wc_dilithium_free(dilithium); - } +/* get how big the the cert cache save buffer needs to be */ +int wolfSSL_CTX_get_cert_cache_memsize(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_get_cert_cache_memsize"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); - #endif - if (isDilithium) { - /* Create a fake Dilithium EVP_PKEY. In the future, we might - * integrate Dilithium into the compatibility layer. */ - pkey = wolfSSL_EVP_PKEY_new(); - if (pkey == NULL) { - WOLFSSL_MSG("Dilithium wolfSSL_EVP_PKEY_new error"); - return NULL; - } - pkey->type = EVP_PKEY_DILITHIUM; - pkey->pkey.ptr = NULL; - pkey->pkey_sz = 0; - return pkey; - } + if (ctx == NULL) + return BAD_FUNC_ARG; - } - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ + return CM_GetCertCacheMemSize(ctx->cm); +} - if (pkey == NULL) { - WOLFSSL_MSG("wolfSSL_d2i_PUBKEY couldn't determine key type"); - } +#endif /* PERSIST_CERT_CACHE */ +#endif /* !NO_CERTS */ - return pkey; +void wolfSSL_load_error_strings(void) +{ + /* compatibility only */ } -#endif /* OPENSSL_EXTRA || WPA_SMALL */ -#ifdef OPENSSL_EXTRA -WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( - WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey, const unsigned char** keyBuf, long keyLen) +int wolfSSL_library_init(void) { - WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL; -#ifdef WOLFSSL_PEM_TO_DER - int ret; - DerBuffer* der = NULL; - - if (keyBuf == NULL || *keyBuf == NULL || keyLen <= 0) { - WOLFSSL_MSG("Bad key PEM/DER args"); - return NULL; - } + WOLFSSL_ENTER("wolfSSL_library_init"); + if (wolfSSL_Init() == WOLFSSL_SUCCESS) + return WOLFSSL_SUCCESS; + else + return WOLFSSL_FATAL_ERROR; +} - ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &der, NULL, NULL, NULL); - if (ret < 0) { - WOLFSSL_MSG("Not PEM format"); - ret = AllocDer(&der, (word32)keyLen, PRIVATEKEY_TYPE, NULL); - if (ret == 0) { - XMEMCPY(der->buffer, *keyBuf, keyLen); - } - } - if (ret == 0) { - /* Verify this is PKCS8 Key */ - word32 inOutIdx = 0; - word32 algId; - ret = ToTraditionalInline_ex(der->buffer, &inOutIdx, der->length, &algId); - if (ret >= 0) { - ret = 0; /* good DER */ - } - } +#ifdef HAVE_SECRET_CALLBACK - if (ret == 0) { - pkcs8 = wolfSSL_EVP_PKEY_new(); - if (pkcs8 == NULL) - ret = MEMORY_E; - } - if (ret == 0) { - pkcs8->pkey.ptr = (char*)XMALLOC(der->length, NULL, - DYNAMIC_TYPE_PUBLIC_KEY); - if (pkcs8->pkey.ptr == NULL) - ret = MEMORY_E; - } - if (ret == 0) { - XMEMCPY(pkcs8->pkey.ptr, der->buffer, der->length); - pkcs8->pkey_sz = der->length; - } +int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx) +{ + WOLFSSL_ENTER("wolfSSL_set_session_secret_cb"); + if (ssl == NULL) + return WOLFSSL_FAILURE; - FreeDer(&der); - if (ret != 0) { - wolfSSL_EVP_PKEY_free(pkcs8); - pkcs8 = NULL; - } - if (pkey != NULL) { - *pkey = pkcs8; + ssl->sessionSecretCb = cb; + ssl->sessionSecretCtx = ctx; + if (cb != NULL) { + /* If using a pre-set key, assume session resumption. */ + ssl->session->sessionIDSz = 0; + ssl->options.resuming = 1; } -#else - (void)bio; - (void)pkey; -#endif /* WOLFSSL_PEM_TO_DER */ - - return pkcs8; + return WOLFSSL_SUCCESS; } - -#ifndef NO_BIO -/* put SSL type in extra for now, not very common */ - -/* Converts a DER format key read from "bio" to a PKCS8 structure. - * - * bio input bio to read DER from - * pkey If not NULL then this pointer will be overwritten with a new PKCS8 - * structure. - * - * returns a WOLFSSL_PKCS8_PRIV_KEY_INFO pointer on success and NULL in fail - * case. - */ -WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY_bio(WOLFSSL_BIO* bio, - WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey) +int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, TicketParseCb cb, + void *ctx) { - WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL; -#ifdef WOLFSSL_PEM_TO_DER - unsigned char* mem = NULL; - int memSz; + WOLFSSL_ENTER("wolfSSL_set_session_ticket_ext_cb"); + if (ssl == NULL) + return WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_d2i_PKCS8_PKEY_bio"); + ssl->ticketParseCb = cb; + ssl->ticketParseCtx = ctx; - if (bio == NULL) { - return NULL; - } + return WOLFSSL_SUCCESS; +} - if ((memSz = wolfSSL_BIO_get_mem_data(bio, &mem)) < 0) { - return NULL; - } +int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx) +{ + WOLFSSL_ENTER("wolfSSL_set_secret_cb"); + if (ssl == NULL) + return WOLFSSL_FATAL_ERROR; - pkcs8 = wolfSSL_d2i_PKCS8_PKEY(pkey, (const unsigned char**)&mem, memSz); -#else - (void)bio; - (void)pkey; -#endif /* WOLFSSL_PEM_TO_DER */ + ssl->tlsSecretCb = cb; + ssl->tlsSecretCtx = ctx; - return pkcs8; + return WOLFSSL_SUCCESS; } - -/* expecting DER format public key - * - * bio input bio to read DER from - * out If not NULL then this pointer will be overwritten with a new - * WOLFSSL_EVP_PKEY pointer - * - * returns a WOLFSSL_EVP_PKEY pointer on success and NULL in fail case. - */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY** out) +#ifdef SHOW_SECRETS +int tlsShowSecrets(WOLFSSL* ssl, void* secret, int secretSz, + void* ctx) { - unsigned char* mem; - long memSz; - WOLFSSL_EVP_PKEY* pkey = NULL; + /* Wireshark Pre-Master-Secret Format: + * CLIENT_RANDOM + */ + const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM"; + int i, pmsPos = 0; + char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1]; + byte clientRandom[RAN_LEN]; + int clientRandomSz; - WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY_bio"); + (void)ctx; - if (bio == NULL) { - return NULL; - } - (void)out; + clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom, + sizeof(clientRandom)); - memSz = wolfSSL_BIO_get_len(bio); - if (memSz <= 0) { - return NULL; + if (clientRandomSz <= 0) { + printf("Error getting server random %d\n", clientRandomSz); + return BAD_FUNC_ARG; } - mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (mem == NULL) { - return NULL; + XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ", + CLIENT_RANDOM_LABEL); + pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1; + for (i = 0; i < clientRandomSz; i++) { + XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x", + clientRandom[i]); + pmsPos += 2; } + XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " "); + pmsPos += 1; + for (i = 0; i < secretSz; i++) { + XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x", + ((byte*)secret)[i]); + pmsPos += 2; + } + XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n"); + pmsPos += 1; - if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) { - pkey = wolfSSL_d2i_PUBKEY(NULL, (const unsigned char**)&mem, memSz); - if (out != NULL && pkey != NULL) { - *out = pkey; + /* print master secret */ + puts(pmsBuf); + + #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE) + { + FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a"); + if (f != XBADFILE) { + XFWRITE(pmsBuf, 1, pmsPos, f); + XFCLOSE(f); } } - - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - return pkey; + #endif + return 0; } +#endif /* SHOW_SECRETS */ -#endif /* !NO_BIO */ +#endif -/* Converts a DER encoded public key to a WOLFSSL_EVP_PKEY structure. - * - * out pointer to new WOLFSSL_EVP_PKEY structure. Can be NULL - * in DER buffer to convert - * inSz size of in buffer - * - * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL - * on fail +#ifdef OPENSSL_EXTRA + +/* + * check if the list has TLS13 and pre-TLS13 suites + * @param list cipher suite list that user want to set + * (caller required to check for NULL) + * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2 */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** out, - const unsigned char** in, long inSz) +static int CheckcipherList(const char* list) { - WOLFSSL_ENTER("wolfSSL_d2i_PUBKEY"); - return d2iGenericKey(out, in, inSz, 0); -} + int ret; + int findTLSv13Suites = 0; + int findbeforeSuites = 0; + byte cipherSuite0; + byte cipherSuite1; + int flags; + char* next = (char*)list; -#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && !defined(NO_ASN) && \ - !defined(NO_PWDBASED) + do { + char* current = next; + char name[MAX_SUITE_NAME + 1]; + word32 length = MAX_SUITE_NAME; + word32 current_length; -/* helper function to get raw pointer to DER buffer from WOLFSSL_EVP_PKEY */ -static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, unsigned char** der) -{ - int sz; - word16 pkcs8HeaderSz; + next = XSTRSTR(next, ":"); - if (!key || !key->pkey_sz) - return WOLFSSL_FATAL_ERROR; + current_length = (!next) ? (word32)XSTRLEN(current) + : (word32)(next - current); + if (current_length == 0) { + break; + } - /* return the key without PKCS8 for compatibility */ - /* if pkcs8HeaderSz is invalid, use 0 and return all of pkey */ - pkcs8HeaderSz = 0; - if (key->pkey_sz > key->pkcs8HeaderSz) - pkcs8HeaderSz = key->pkcs8HeaderSz; - sz = key->pkey_sz - pkcs8HeaderSz; - if (der) { - unsigned char* pt = (unsigned char*)key->pkey.ptr; - if (*der) { - /* since this function signature has no size value passed in it is - * assumed that the user has allocated a large enough buffer */ - XMEMCPY(*der, pt + pkcs8HeaderSz, sz); - *der += sz; + if (current_length < length) { + length = current_length; } - else { - *der = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL); - if (*der == NULL) { - return WOLFSSL_FATAL_ERROR; + XMEMCPY(name, current, length); + name[length] = 0; + + if (XSTRCMP(name, "ALL") == 0 || + XSTRCMP(name, "DEFAULT") == 0 || + XSTRCMP(name, "HIGH") == 0) + { + findTLSv13Suites = 1; + findbeforeSuites = 1; + break; + } + + ret = wolfSSL_get_cipher_suite_from_name(name, &cipherSuite0, + &cipherSuite1, &flags); + if (ret == 0) { + if (cipherSuite0 == TLS13_BYTE) { + /* TLSv13 suite */ + findTLSv13Suites = 1; + } + else { + findbeforeSuites = 1; } - XMEMCPY(*der, pt + pkcs8HeaderSz, sz); } - } - return sz; -} -int wolfSSL_i2d_PUBKEY(const WOLFSSL_EVP_PKEY *key, unsigned char **der) -{ - return wolfSSL_i2d_PublicKey(key, der); -} + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) + /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */ + if (ret != 0) { + char* subStr = name; + char* subStrNext; -#endif /* OPENSSL_EXTRA && !NO_CERTS && !NO_ASN && !NO_PWDBASED */ + do { + subStrNext = XSTRSTR(subStr, "+"); -static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, - const unsigned char **in, long inSz, int priv) -{ - int ret = 0; - word32 idx = 0, algId; - word16 pkcs8HeaderSz = 0; - WOLFSSL_EVP_PKEY* local; - int opt = 0; - - (void)opt; - - if (in == NULL || inSz < 0) { - WOLFSSL_MSG("Bad argument"); - return NULL; - } - - if (priv == 1) { - /* Check if input buffer has PKCS8 header. In the case that it does not - * have a PKCS8 header then do not error out. */ - if ((ret = ToTraditionalInline_ex((const byte*)(*in), &idx, - (word32)inSz, &algId)) > 0) { - WOLFSSL_MSG("Found PKCS8 header"); - pkcs8HeaderSz = (word16)idx; - - if ((type == EVP_PKEY_RSA && algId != RSAk - #ifdef WC_RSA_PSS - && algId != RSAPSSk - #endif - ) || - (type == EVP_PKEY_EC && algId != ECDSAk) || - (type == EVP_PKEY_DSA && algId != DSAk) || - (type == EVP_PKEY_DH && algId != DHk)) { - WOLFSSL_MSG("PKCS8 does not match EVP key type"); - return NULL; - } + if ((XSTRCMP(subStr, "ECDHE") == 0) || + (XSTRCMP(subStr, "RSA") == 0)) { + return 0; + } - (void)idx; /* not used */ + if (subStrNext && (XSTRLEN(subStrNext) > 0)) { + subStr = subStrNext + 1; /* +1 to skip past '+' */ + } + } while (subStrNext != NULL); } - else { - if (ret != ASN_PARSE_E) { - WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 " - "header"); - return NULL; - } + #endif + + if (findTLSv13Suites == 1 && findbeforeSuites == 1) { + /* list has mixed suites */ + return 0; } } + while (next++); /* increment to skip ':' */ - if (out != NULL && *out != NULL) { - wolfSSL_EVP_PKEY_free(*out); - *out = NULL; - } - local = wolfSSL_EVP_PKEY_new(); - if (local == NULL) { - return NULL; + if (findTLSv13Suites == 0 && findbeforeSuites == 1) { + ret = 1;/* only before TLSv13 suites */ } - - local->type = type; - local->pkey_sz = (int)inSz; - local->pkcs8HeaderSz = pkcs8HeaderSz; - local->pkey.ptr = (char*)XMALLOC(inSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - if (local->pkey.ptr == NULL) { - wolfSSL_EVP_PKEY_free(local); - local = NULL; - return NULL; + else if (findTLSv13Suites == 1 && findbeforeSuites == 0) { + ret = 2;/* only TLSv13 suties */ } else { - XMEMCPY(local->pkey.ptr, *in, inSz); - } - - switch (type) { -#ifndef NO_RSA - case EVP_PKEY_RSA: - opt = priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC; - local->ownRsa = 1; - local->rsa = wolfssl_rsa_d2i(NULL, - (const unsigned char*)local->pkey.ptr, local->pkey_sz, opt); - if (local->rsa == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - break; -#endif /* NO_RSA */ -#ifdef HAVE_ECC - case EVP_PKEY_EC: - local->ownEcc = 1; - local->ecc = wolfSSL_EC_KEY_new(); - if (local->ecc == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - opt = priv ? WOLFSSL_EC_KEY_LOAD_PRIVATE : - WOLFSSL_EC_KEY_LOAD_PUBLIC; - if (wolfSSL_EC_KEY_LoadDer_ex(local->ecc, - (const unsigned char*)local->pkey.ptr, local->pkey_sz, - opt) - != WOLFSSL_SUCCESS) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - break; -#endif /* HAVE_ECC */ -#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) -#ifndef NO_DSA - case EVP_PKEY_DSA: - local->ownDsa = 1; - local->dsa = wolfSSL_DSA_new(); - if (local->dsa == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - opt = priv ? WOLFSSL_DSA_LOAD_PRIVATE : WOLFSSL_DSA_LOAD_PUBLIC; - if (wolfSSL_DSA_LoadDer_ex(local->dsa, - (const unsigned char*)local->pkey.ptr, local->pkey_sz, - opt) - != WOLFSSL_SUCCESS) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - break; -#endif /* NO_DSA */ -#ifndef NO_DH -#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2)) - case EVP_PKEY_DH: - local->ownDh = 1; - local->dh = wolfSSL_DH_new(); - if (local->dh == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - if (wolfSSL_DH_LoadDer(local->dh, - (const unsigned char*)local->pkey.ptr, local->pkey_sz) - != WOLFSSL_SUCCESS) { - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - break; -#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */ -#endif /* HAVE_DH */ -#endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH */ - default: - WOLFSSL_MSG("Unsupported key type"); - wolfSSL_EVP_PKEY_free(local); - return NULL; - } - - /* advance pointer with success */ - if (local != NULL) { - if (local->pkey_sz <= (int)inSz) { - *in += local->pkey_sz; - } - - if (out != NULL) { - *out = local; - } + ret = 0;/* handle as mixed */ } - - return local; + return ret; } -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, - const unsigned char **in, long inSz) -{ - WOLFSSL_ENTER("wolfSSL_d2i_PublicKey"); - - return _d2i_PublicKey(type, out, in, inSz, 0); -} -/* Reads in a DER format key. If PKCS8 headers are found they are stripped off. - * - * type type of key - * out newly created WOLFSSL_EVP_PKEY structure - * in pointer to input key DER - * inSz size of in buffer +/* parse some bulk lists like !eNULL / !aNULL * - * On success a non null pointer is returned and the pointer in is advanced the - * same number of bytes read. + * returns WOLFSSL_SUCCESS on success and sets the cipher suite list */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey(int type, WOLFSSL_EVP_PKEY** out, - const unsigned char **in, long inSz) +static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + Suites* suites, const char* list) { - WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey"); + int ret = 0; + int listattribute = 0; + int tls13Only = 0; +#ifndef WOLFSSL_SMALL_STACK + byte suitesCpy[WOLFSSL_MAX_SUITE_SZ]; +#else + byte* suitesCpy = NULL; +#endif + word16 suitesCpySz = 0; + word16 i = 0; + word16 j = 0; - return _d2i_PublicKey(type, out, in, inSz, 1); -} + if (suites == NULL || list == NULL) { + WOLFSSL_MSG("NULL argument"); + return WOLFSSL_FAILURE; + } -#ifdef WOLF_PRIVATE_KEY_ID -/* Create an EVP structure for use with crypto callbacks */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out, - void* heap, int devId) -{ - WOLFSSL_EVP_PKEY* local; + listattribute = CheckcipherList(list); - if (out != NULL && *out != NULL) { - wolfSSL_EVP_PKEY_free(*out); - *out = NULL; + if (listattribute == 0) { + /* list has mixed(pre-TLSv13 and TLSv13) suites + * update cipher suites the same as before + */ + return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS : + WOLFSSL_FAILURE; + } + else if (listattribute == 1) { + /* list has only pre-TLSv13 suites. + * Only update before TLSv13 suites. + */ + tls13Only = 0; + } + else if (listattribute == 2) { + /* list has only TLSv13 suites. Only update TLv13 suites + * simulate set_ciphersuites() compatibility layer API + */ + tls13Only = 1; + if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) || + (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) { + /* Silently ignore TLS 1.3 ciphers if we don't support it. */ + return WOLFSSL_SUCCESS; + } } - local = wolfSSL_EVP_PKEY_new_ex(heap); - if (local == NULL) { - return NULL; + /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */ + if (suites->suiteSz == 0) { + WOLFSSL_MSG("Warning suites->suiteSz = 0 set to WOLFSSL_MAX_SUITE_SZ"); + suites->suiteSz = WOLFSSL_MAX_SUITE_SZ; } +#ifdef WOLFSSL_SMALL_STACK + if (suites->suiteSz > 0) { + suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (suitesCpy == NULL) { + return WOLFSSL_FAILURE; + } - local->type = type; - local->pkey_sz = 0; - local->pkcs8HeaderSz = 0; + XMEMSET(suitesCpy, 0, suites->suiteSz); + } +#else + XMEMSET(suitesCpy, 0, sizeof(suitesCpy)); +#endif - switch (type) { -#ifndef NO_RSA - case EVP_PKEY_RSA: - { - RsaKey* key; - local->ownRsa = 1; - local->rsa = wolfSSL_RSA_new_ex(heap, devId); - if (local->rsa == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; + if (suites->suiteSz > 0) + XMEMCPY(suitesCpy, suites->suites, suites->suiteSz); + suitesCpySz = suites->suiteSz; + + ret = SetCipherList_ex(ctx, ssl, suites, list); + if (ret != 1) { +#ifdef WOLFSSL_SMALL_STACK + XFREE(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return WOLFSSL_FAILURE; + } + + for (i = 0; i < suitesCpySz && + suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) { + /* Check for duplicates */ + int duplicate = 0; + for (j = 0; j < suites->suiteSz; j += 2) { + if (suitesCpy[i] == suites->suites[j] && + suitesCpy[i+1] == suites->suites[j+1]) { + duplicate = 1; + break; } - key = (RsaKey*)local->rsa->internal; - #ifdef WOLF_CRYPTO_CB - key->devId = devId; - #endif - (void)key; - local->rsa->inSet = 1; - break; } -#endif /* !NO_RSA */ -#ifdef HAVE_ECC - case EVP_PKEY_EC: - { - ecc_key* key; - local->ownEcc = 1; - local->ecc = wolfSSL_EC_KEY_new_ex(heap, devId); - if (local->ecc == NULL) { - wolfSSL_EVP_PKEY_free(local); - return NULL; + if (!duplicate) { + if (tls13Only) { + /* Updating TLS 1.3 ciphers */ + if (suitesCpy[i] != TLS13_BYTE) { + /* Only copy over <= TLS 1.2 ciphers */ + /* TLS 1.3 ciphers take precedence */ + suites->suites[suites->suiteSz++] = suitesCpy[i]; + suites->suites[suites->suiteSz++] = suitesCpy[i+1]; + } + } + else { + /* Updating <= TLS 1.2 ciphers */ + if (suitesCpy[i] == TLS13_BYTE) { + /* Only copy over TLS 1.3 ciphers */ + /* TLS 1.3 ciphers take precedence */ + XMEMMOVE(suites->suites + SUITE_LEN, suites->suites, + suites->suiteSz); + suites->suites[0] = suitesCpy[i]; + suites->suites[1] = suitesCpy[i+1]; + suites->suiteSz += 2; + } } - key = (ecc_key*)local->ecc->internal; - #ifdef WOLF_CRYPTO_CB - key->devId = devId; - #endif - key->type = ECC_PRIVATEKEY; - /* key is required to have a key size / curve set, although - * actual one used is determined by devId callback function */ - wc_ecc_set_curve(key, ECDHE_SIZE, ECC_CURVE_DEF); - - local->ecc->inSet = 1; - break; } -#endif /* HAVE_ECC */ - default: - WOLFSSL_MSG("Unsupported private key id type"); - wolfSSL_EVP_PKEY_free(local); - return NULL; } - if (local != NULL && out != NULL) { - *out = local; - } - - return local; +#ifdef WOLFSSL_SMALL_STACK + XFREE(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return ret; } -#endif /* WOLF_PRIVATE_KEY_ID */ -#ifndef NO_CERTS /* // NOLINT(readability-redundant-preprocessor) */ +#endif -#ifndef NO_CHECK_PRIVATE_KEY -/* Check private against public in certificate for match - * - * ssl WOLFSSL structure to check private key in - * - * Returns WOLFSSL_SUCCESS on good private key - * WOLFSSL_FAILURE if mismatched. */ -int wolfSSL_check_private_key(const WOLFSSL* ssl) + +int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list) { - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } - return check_cert_key(ssl->buffers.certificate, ssl->buffers.key, ssl->heap, - ssl->buffers.keyDevId, ssl->buffers.keyLabel, ssl->buffers.keyId); -} -#endif /* !NO_CHECK_PRIVATE_KEY */ + WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list"); -#endif /* !NO_CERTS */ + if (ctx == NULL) + return WOLFSSL_FAILURE; -int wolfSSL_use_PrivateKey(WOLFSSL* ssl, WOLFSSL_EVP_PKEY* pkey) -{ - WOLFSSL_ENTER("wolfSSL_use_PrivateKey"); - if (ssl == NULL || pkey == NULL ) { + if (AllocateCtxSuites(ctx) != 0) return WOLFSSL_FAILURE; - } - return wolfSSL_use_PrivateKey_buffer(ssl, (unsigned char*)pkey->pkey.ptr, - pkey->pkey_sz, WOLFSSL_FILETYPE_ASN1); +#ifdef OPENSSL_EXTRA + return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list); +#else + return (SetCipherList(ctx, ctx->suites, list)) ? + WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +#endif } - -int wolfSSL_use_PrivateKey_ASN1(int pri, WOLFSSL* ssl, const unsigned char* der, - long derSz) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES) +int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list, + const int listSz) { - WOLFSSL_ENTER("wolfSSL_use_PrivateKey_ASN1"); - if (ssl == NULL || der == NULL ) { + WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes"); + + if (ctx == NULL) return WOLFSSL_FAILURE; - } - (void)pri; /* type of private key */ - return wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, WOLFSSL_FILETYPE_ASN1); + if (AllocateCtxSuites(ctx) != 0) + return WOLFSSL_FAILURE; + + return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ? + WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } -/****************************************************************************** -* wolfSSL_CTX_use_PrivateKey_ASN1 - loads a private key buffer into the SSL ctx -* -* RETURNS: -* returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE -*/ +#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */ -int wolfSSL_CTX_use_PrivateKey_ASN1(int pri, WOLFSSL_CTX* ctx, - unsigned char* der, long derSz) +int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list) { - WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_ASN1"); - if (ctx == NULL || der == NULL ) { + WOLFSSL_ENTER("wolfSSL_set_cipher_list"); + + if (ssl == NULL || ssl->ctx == NULL) { return WOLFSSL_FAILURE; } - (void)pri; /* type of private key */ - return wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1); -} + if (AllocateSuites(ssl) != 0) + return WOLFSSL_FAILURE; +#ifdef OPENSSL_EXTRA + return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list); +#else + return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ? + WOLFSSL_SUCCESS : + WOLFSSL_FAILURE; +#endif +} -#ifndef NO_RSA -int wolfSSL_use_RSAPrivateKey_ASN1(WOLFSSL* ssl, unsigned char* der, long derSz) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES) +int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list, + const int listSz) { - WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_ASN1"); - if (ssl == NULL || der == NULL ) { + WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes"); + + if (ssl == NULL || ssl->ctx == NULL) { return WOLFSSL_FAILURE; } - return wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, WOLFSSL_FILETYPE_ASN1); + if (AllocateSuites(ssl) != 0) + return WOLFSSL_FAILURE; + + return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz)) + ? WOLFSSL_SUCCESS + : WOLFSSL_FAILURE; } -#endif +#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */ -int wolfSSL_use_certificate(WOLFSSL* ssl, WOLFSSL_X509* x509) -{ - long idx = 0; - WOLFSSL_ENTER("wolfSSL_use_certificate"); - if (x509 != NULL && ssl != NULL && x509->derCert != NULL) { - if (ProcessBuffer(NULL, x509->derCert->buffer, x509->derCert->length, - WOLFSSL_FILETYPE_ASN1, CERT_TYPE, ssl, &idx, 0, - GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } - } +#ifdef HAVE_KEYING_MATERIAL - (void)idx; - return WOLFSSL_FAILURE; -} +#define TLS_PRF_LABEL_CLIENT_FINISHED "client finished" +#define TLS_PRF_LABEL_SERVER_FINISHED "server finished" +#define TLS_PRF_LABEL_MASTER_SECRET "master secret" +#define TLS_PRF_LABEL_EXT_MASTER_SECRET "extended master secret" +#define TLS_PRF_LABEL_KEY_EXPANSION "key expansion" -#endif /* OPENSSL_EXTRA */ +static const struct ForbiddenLabels { + const char* label; + size_t labelLen; +} forbiddenLabels[] = { + {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)}, + {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)}, + {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)}, + {TLS_PRF_LABEL_EXT_MASTER_SECRET, + XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)}, + {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)}, + {NULL, 0}, +}; -#if defined(HAVE_RPK) -/* Confirm that all the byte data in the buffer is unique. - * return 1 if all the byte data in the buffer is unique, otherwise 0. +/** + * Implement RFC 5705 + * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446) + * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */ -static int isArrayUnique(const char* buf, size_t len) +int wolfSSL_export_keying_material(WOLFSSL *ssl, + unsigned char *out, size_t outLen, + const char *label, size_t labelLen, + const unsigned char *context, size_t contextLen, + int use_context) { - size_t i, j; - /* check the array is unique */ - for (i = 0; i < len -1; ++i) { - for (j = i+ 1; j < len; ++j) { - if (buf[i] == buf[j]) { - return 0; - } - } - } - return 1; -} + byte* seed = NULL; + word32 seedLen; + const struct ForbiddenLabels* fl; -/* Set user preference for the client_cert_type exetnsion. - * Takes byte array containing cert types the caller can provide to its peer. - * Cert types are in preferred order in the array. - */ -WOLFSSL_API int wolfSSL_CTX_set_client_cert_type(WOLFSSL_CTX* ctx, - const char* buf, int bufLen) -{ - int i; + WOLFSSL_ENTER("wolfSSL_export_keying_material"); - if (ctx == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) { - return BAD_FUNC_ARG; + if (ssl == NULL || out == NULL || label == NULL || + (use_context && contextLen && context == NULL)) { + WOLFSSL_MSG("Bad argument"); + return WOLFSSL_FAILURE; } - /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ - if (buf == NULL || bufLen == 0) { - ctx->rpkConfig.preferred_ClientCertTypeCnt = 1; - ctx->rpkConfig.preferred_ClientCertTypes[0]= WOLFSSL_CERT_TYPE_X509; - ctx->rpkConfig.preferred_ClientCertTypes[1]= WOLFSSL_CERT_TYPE_X509; - return WOLFSSL_SUCCESS; - } + /* clientRandom + serverRandom + * OR + * clientRandom + serverRandom + ctx len encoding + ctx */ + seedLen = !use_context ? (word32)SEED_LEN : + (word32)SEED_LEN + 2 + (word32)contextLen; - if (!isArrayUnique(buf, bufLen)) - return BAD_FUNC_ARG; + if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) { + WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake " + "data. Call wolfSSL_KeepArrays before attempting to " + "export keyid material."); + return WOLFSSL_FAILURE; + } - for (i = 0; i < bufLen; i++){ - if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) - return BAD_FUNC_ARG; - - ctx->rpkConfig.preferred_ClientCertTypes[i] = buf[i]; + /* check forbidden labels */ + for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) { + if (labelLen >= fl->labelLen && + XMEMCMP(label, fl->label, fl->labelLen) == 0) { + WOLFSSL_MSG("Forbidden label"); + return WOLFSSL_FAILURE; + } } - ctx->rpkConfig.preferred_ClientCertTypeCnt = bufLen; - - return WOLFSSL_SUCCESS; -} -/* Set user preference for the server_cert_type exetnsion. - * Takes byte array containing cert types the caller can provide to its peer. - * Cert types are in preferred order in the array. - */ -WOLFSSL_API int wolfSSL_CTX_set_server_cert_type(WOLFSSL_CTX* ctx, - const char* buf, int bufLen) -{ - int i; +#ifdef WOLFSSL_TLS13 + if (IsAtLeastTLSv1_3(ssl->version)) { + /* Path for TLS 1.3 */ + if (!use_context) { + contextLen = 0; + context = (byte*)""; /* Give valid pointer for 0 length memcpy */ + } - if (ctx == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) { - return BAD_FUNC_ARG; + if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen, + context, contextLen) != 0) { + WOLFSSL_MSG("Tls13_Exporter error"); + return WOLFSSL_FAILURE; + } + return WOLFSSL_SUCCESS; } +#endif - /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ - if (buf == NULL || bufLen == 0) { - ctx->rpkConfig.preferred_ServerCertTypeCnt = 1; - ctx->rpkConfig.preferred_ServerCertTypes[0]= WOLFSSL_CERT_TYPE_X509; - ctx->rpkConfig.preferred_ServerCertTypes[1]= WOLFSSL_CERT_TYPE_X509; - return WOLFSSL_SUCCESS; + /* Path for <=TLS 1.2 */ + seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (seed == NULL) { + WOLFSSL_MSG("malloc error"); + return WOLFSSL_FAILURE; } - if (!isArrayUnique(buf, bufLen)) - return BAD_FUNC_ARG; + XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN); + XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN); - for (i = 0; i < bufLen; i++){ - if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) - return BAD_FUNC_ARG; + if (use_context) { + /* Encode len in big endian */ + seed[SEED_LEN ] = (contextLen >> 8) & 0xFF; + seed[SEED_LEN + 1] = (contextLen) & 0xFF; + if (contextLen) { + /* 0 length context is allowed */ + XMEMCPY(seed + SEED_LEN + 2, context, contextLen); + } + } - ctx->rpkConfig.preferred_ServerCertTypes[i] = buf[i]; + PRIVATE_KEY_UNLOCK(); + if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN, + (byte*)label, (word32)labelLen, seed, seedLen, + IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap, + ssl->devId) != 0) { + WOLFSSL_MSG("wc_PRF_TLS error"); + PRIVATE_KEY_LOCK(); + XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; } - ctx->rpkConfig.preferred_ServerCertTypeCnt = bufLen; + PRIVATE_KEY_LOCK(); + XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_SUCCESS; } +#endif /* HAVE_KEYING_MATERIAL */ -/* Set user preference for the client_cert_type exetnsion. - * Takes byte array containing cert types the caller can provide to its peer. - * Cert types are in preferred order in the array. - */ -WOLFSSL_API int wolfSSL_set_client_cert_type(WOLFSSL* ssl, - const char* buf, int bufLen) +int wolfSSL_dtls_get_using_nonblock(WOLFSSL* ssl) { - int i; + int useNb = 0; - if (ssl == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) { - return BAD_FUNC_ARG; - } + if (ssl == NULL) + return WOLFSSL_FAILURE; - /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ - if (buf == NULL || bufLen == 0) { - ssl->options.rpkConfig.preferred_ClientCertTypeCnt = 1; - ssl->options.rpkConfig.preferred_ClientCertTypes[0] - = WOLFSSL_CERT_TYPE_X509; - ssl->options.rpkConfig.preferred_ClientCertTypes[1] - = WOLFSSL_CERT_TYPE_X509; - return WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_dtls_get_using_nonblock"); + if (ssl->options.dtls) { +#ifdef WOLFSSL_DTLS + useNb = ssl->options.dtlsUseNonblock; +#endif + } + else { + WOLFSSL_MSG("wolfSSL_dtls_get_using_nonblock() is " + "DEPRECATED for non-DTLS use."); } + return useNb; +} - if (!isArrayUnique(buf, bufLen)) - return BAD_FUNC_ARG; - for (i = 0; i < bufLen; i++){ - if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) - return BAD_FUNC_ARG; +#ifndef WOLFSSL_LEANPSK - ssl->options.rpkConfig.preferred_ClientCertTypes[i] = buf[i]; - } - ssl->options.rpkConfig.preferred_ClientCertTypeCnt = bufLen; +void wolfSSL_dtls_set_using_nonblock(WOLFSSL* ssl, int nonblock) +{ + (void)nonblock; - return WOLFSSL_SUCCESS; -} + WOLFSSL_ENTER("wolfSSL_dtls_set_using_nonblock"); -/* Set user preference for the server_cert_type exetnsion. - * Takes byte array containing cert types the caller can provide to its peer. - * Cert types are in preferred order in the array. - */ -WOLFSSL_API int wolfSSL_set_server_cert_type(WOLFSSL* ssl, - const char* buf, int bufLen) -{ - int i; + if (ssl == NULL) + return; - if (ssl == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) { - return BAD_FUNC_ARG; + if (ssl->options.dtls) { +#ifdef WOLFSSL_DTLS + ssl->options.dtlsUseNonblock = (nonblock != 0); +#endif } - - /* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/ - if (buf == NULL || bufLen == 0) { - ssl->options.rpkConfig.preferred_ServerCertTypeCnt = 1; - ssl->options.rpkConfig.preferred_ServerCertTypes[0] - = WOLFSSL_CERT_TYPE_X509; - ssl->options.rpkConfig.preferred_ServerCertTypes[1] - = WOLFSSL_CERT_TYPE_X509; - return WOLFSSL_SUCCESS; + else { + WOLFSSL_MSG("wolfSSL_dtls_set_using_nonblock() is " + "DEPRECATED for non-DTLS use."); } +} - if (!isArrayUnique(buf, bufLen)) - return BAD_FUNC_ARG; - for (i = 0; i < bufLen; i++){ - if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509) - return BAD_FUNC_ARG; +#ifdef WOLFSSL_DTLS - ssl->options.rpkConfig.preferred_ServerCertTypes[i] = buf[i]; - } - ssl->options.rpkConfig.preferred_ServerCertTypeCnt = bufLen; +int wolfSSL_dtls_get_current_timeout(WOLFSSL* ssl) +{ + int timeout = 0; + if (ssl) + timeout = ssl->dtls_timeout; - return WOLFSSL_SUCCESS; + WOLFSSL_LEAVE("wolfSSL_dtls_get_current_timeout", timeout); + return timeout; } -/* get negotiated certificate type value and return it to the second parameter. - * cert type value: - * -1: WOLFSSL_CERT_TYPE_UNKNOWN - * 0: WOLFSSL_CERT_TYPE_X509 - * 2: WOLFSSL_CERT_TYPE_RPK - * return WOLFSSL_SUCCESS on success, otherwise negative value. - * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for - * cert type. +#ifdef WOLFSSL_DTLS13 + +/* + * This API returns 1 when the user should set a short timeout for receiving + * data. It is recommended that it is at most 1/4 the value returned by + * wolfSSL_dtls_get_current_timeout(). */ -WOLFSSL_API int wolfSSL_get_negotiated_client_cert_type(WOLFSSL* ssl, int* tp) +int wolfSSL_dtls13_use_quick_timeout(WOLFSSL* ssl) { - int ret = WOLFSSL_SUCCESS; - - if (ssl == NULL || tp == NULL) - return BAD_FUNC_ARG; - - if (ssl->options.side == WOLFSSL_CLIENT_END) { - if (ssl->options.rpkState.received_ClientCertTypeCnt == 1) - *tp = ssl->options.rpkState.received_ClientCertTypes[0]; - else - *tp = WOLFSSL_CERT_TYPE_UNKNOWN; - } - else { - if (ssl->options.rpkState.sending_ClientCertTypeCnt == 1) - *tp = ssl->options.rpkState.sending_ClientCertTypes[0]; - else - *tp = WOLFSSL_CERT_TYPE_UNKNOWN; - } - return ret; + return ssl->dtls13FastTimeout; } -/* get negotiated certificate type value and return it to the second parameter. - * cert type value: - * -1: WOLFSSL_CERT_TYPE_UNKNOWN - * 0: WOLFSSL_CERT_TYPE_X509 - * 2: WOLFSSL_CERT_TYPE_RPK - * return WOLFSSL_SUCCESS on success, otherwise negative value. - * in case no negotiation performed, it returns WOLFSSL_SUCCESS and -1 is for - * cert type. +/* + * When this is set, a DTLS 1.3 connection will send acks immediately when a + * disruption is detected to shortcut timeouts. This results in potentially + * more traffic but may make the handshake quicker. */ -WOLFSSL_API int wolfSSL_get_negotiated_server_cert_type(WOLFSSL* ssl, int* tp) +void wolfSSL_dtls13_set_send_more_acks(WOLFSSL* ssl, int value) { - int ret = WOLFSSL_SUCCESS; - - if (ssl == NULL || tp == NULL) - return BAD_FUNC_ARG; - - if (ssl->options.side == WOLFSSL_CLIENT_END) { - if (ssl->options.rpkState.received_ServerCertTypeCnt == 1) - *tp = ssl->options.rpkState.received_ServerCertTypes[0]; - else - *tp = WOLFSSL_CERT_TYPE_UNKNOWN; - } - else { - if (ssl->options.rpkState.sending_ServerCertTypeCnt == 1) - *tp = ssl->options.rpkState.sending_ServerCertTypes[0]; - else - *tp = WOLFSSL_CERT_TYPE_UNKNOWN; - } - return ret; + if (ssl != NULL) + ssl->options.dtls13SendMoreAcks = !!value; } +#endif /* WOLFSSL_DTLS13 */ -#endif /* HAVE_RPK */ - -int wolfSSL_use_certificate_ASN1(WOLFSSL* ssl, const unsigned char* der, - int derSz) +int wolfSSL_DTLSv1_get_timeout(WOLFSSL* ssl, WOLFSSL_TIMEVAL* timeleft) { - long idx = 0; - - WOLFSSL_ENTER("wolfSSL_use_certificate_ASN1"); - if (der != NULL && ssl != NULL) { - if (ProcessBuffer(NULL, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, - ssl, &idx, 0, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } + if (ssl && timeleft) { + XMEMSET(timeleft, 0, sizeof(WOLFSSL_TIMEVAL)); + timeleft->tv_sec = ssl->dtls_timeout; } - - (void)idx; - return WOLFSSL_FAILURE; + return 0; } -#ifndef NO_FILESYSTEM - -WOLFSSL_ABI -int wolfSSL_use_certificate_file(WOLFSSL* ssl, const char* file, int format) +#ifndef NO_WOLFSSL_STUB +int wolfSSL_DTLSv1_handle_timeout(WOLFSSL* ssl) { - WOLFSSL_ENTER("wolfSSL_use_certificate_file"); + WOLFSSL_STUB("SSL_DTLSv1_handle_timeout"); + (void)ssl; + return 0; +} +#endif - if (ssl == NULL) { - return BAD_FUNC_ARG; - } - - if (ProcessFile(ssl->ctx, file, format, CERT_TYPE, - ssl, 0, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } - - return WOLFSSL_FAILURE; +#ifndef NO_WOLFSSL_STUB +void wolfSSL_DTLSv1_set_initial_timeout_duration(WOLFSSL* ssl, + word32 duration_ms) +{ + WOLFSSL_STUB("SSL_DTLSv1_set_initial_timeout_duration"); + (void)ssl; + (void)duration_ms; } +#endif - -WOLFSSL_ABI -int wolfSSL_use_PrivateKey_file(WOLFSSL* ssl, const char* file, int format) +/* user may need to alter init dtls recv timeout, WOLFSSL_SUCCESS on ok */ +int wolfSSL_dtls_set_timeout_init(WOLFSSL* ssl, int timeout) { - WOLFSSL_ENTER("wolfSSL_use_PrivateKey_file"); + if (ssl == NULL || timeout < 0) + return BAD_FUNC_ARG; - if (ssl == NULL) { + if (timeout > ssl->dtls_timeout_max) { + WOLFSSL_MSG("Can't set dtls timeout init greater than dtls timeout " + "max"); return BAD_FUNC_ARG; } - if (ProcessFile(ssl->ctx, file, format, PRIVATEKEY_TYPE, - ssl, 0, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } + ssl->dtls_timeout_init = timeout; + ssl->dtls_timeout = timeout; - return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } -WOLFSSL_ABI -int wolfSSL_use_certificate_chain_file(WOLFSSL* ssl, const char* file) +/* user may need to alter max dtls recv timeout, WOLFSSL_SUCCESS on ok */ +int wolfSSL_dtls_set_timeout_max(WOLFSSL* ssl, int timeout) { - /* process up to MAX_CHAIN_DEPTH plus subject cert */ - WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file"); + if (ssl == NULL || timeout < 0) + return BAD_FUNC_ARG; - if (ssl == NULL) { + if (timeout < ssl->dtls_timeout_init) { + WOLFSSL_MSG("Can't set dtls timeout max less than dtls timeout init"); return BAD_FUNC_ARG; } - if (ProcessFile(ssl->ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE, - ssl, 1, NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } + ssl->dtls_timeout_max = timeout; - return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } -int wolfSSL_use_certificate_chain_file_format(WOLFSSL* ssl, const char* file, - int format) + +int wolfSSL_dtls_got_timeout(WOLFSSL* ssl) { - /* process up to MAX_CHAIN_DEPTH plus subject cert */ - WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file_format"); + int result = WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_dtls_got_timeout"); - if (ssl == NULL) { - return BAD_FUNC_ARG; - } + if (ssl == NULL) + return WOLFSSL_FATAL_ERROR; + +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { + result = Dtls13RtxTimeout(ssl); + if (result < 0) { + if (result == WANT_WRITE) + ssl->dtls13SendingAckOrRtx = 1; + ssl->error = result; + WOLFSSL_ERROR(result); + return WOLFSSL_FATAL_ERROR; + } - if (ProcessFile(ssl->ctx, file, format, CERT_TYPE, ssl, 1, - NULL, GET_VERIFY_SETTING_SSL(ssl)) == WOLFSSL_SUCCESS) { return WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; -} +#endif /* WOLFSSL_DTLS13 */ -#endif /* !NO_FILESYSTEM */ + if ((IsSCR(ssl) || !ssl->options.handShakeDone)) { + if (DtlsMsgPoolTimeout(ssl) < 0){ + ssl->error = SOCKET_ERROR_E; + WOLFSSL_ERROR(ssl->error); + result = WOLFSSL_FATAL_ERROR; + } + else if ((result = DtlsMsgPoolSend(ssl, 0)) < 0) { + ssl->error = result; + WOLFSSL_ERROR(result); + result = WOLFSSL_FATAL_ERROR; + } + else { + /* Reset return value to success */ + result = WOLFSSL_SUCCESS; + } + } -#ifdef HAVE_ECC + WOLFSSL_LEAVE("wolfSSL_dtls_got_timeout", result); + return result; +} -/* Set Temp CTX EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */ -int wolfSSL_CTX_SetTmpEC_DHE_Sz(WOLFSSL_CTX* ctx, word16 sz) + +/* retransmit all the saves messages, WOLFSSL_SUCCESS on ok */ +int wolfSSL_dtls_retransmit(WOLFSSL* ssl) { - if (ctx == NULL) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wolfSSL_dtls_retransmit"); - /* if 0 then get from loaded private key */ - if (sz == 0) { - /* applies only to ECDSA */ - if (ctx->privateKeyType != ecc_dsa_sa_algo) - return WOLFSSL_SUCCESS; + if (ssl == NULL) + return WOLFSSL_FATAL_ERROR; - if (ctx->privateKeySz == 0) { - WOLFSSL_MSG("Must set private key/cert first"); - return BAD_FUNC_ARG; + if (!ssl->options.handShakeDone) { + int result = DtlsMsgPoolSend(ssl, 0); + if (result < 0) { + ssl->error = result; + WOLFSSL_ERROR(result); + return WOLFSSL_FATAL_ERROR; } - - sz = (word16)ctx->privateKeySz; } - /* check size */ -#if ECC_MIN_KEY_SZ > 0 - if (sz < ECC_MINSIZE) - return BAD_FUNC_ARG; -#endif - if (sz > ECC_MAXSIZE) - return BAD_FUNC_ARG; - - ctx->eccTempKeySz = sz; - - return WOLFSSL_SUCCESS; + return 0; } +#endif /* DTLS */ +#endif /* LEANPSK */ -/* Set Temp SSL EC-DHE size in octets, can be 14 - 66 (112 - 521 bit) */ -int wolfSSL_SetTmpEC_DHE_Sz(WOLFSSL* ssl, word16 sz) -{ - if (ssl == NULL) - return BAD_FUNC_ARG; - /* check size */ -#if ECC_MIN_KEY_SZ > 0 - if (sz < ECC_MINSIZE) - return BAD_FUNC_ARG; -#endif - if (sz > ECC_MAXSIZE) - return BAD_FUNC_ARG; +#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) - ssl->eccTempKeySz = sz; +/* Not an SSL function, return 0 for success, error code otherwise */ +/* Prereq: ssl's RNG needs to be initialized. */ +int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, + const byte* secret, word32 secretSz) +{ + int ret = 0; - return WOLFSSL_SUCCESS; -} + WOLFSSL_ENTER("wolfSSL_DTLS_SetCookieSecret"); -#endif /* HAVE_ECC */ + if (ssl == NULL) { + WOLFSSL_MSG("need a SSL object"); + return BAD_FUNC_ARG; + } + if (secret != NULL && secretSz == 0) { + WOLFSSL_MSG("can't have a new secret without a size"); + return BAD_FUNC_ARG; + } -#ifdef OPENSSL_EXTRA + /* If secretSz is 0, use the default size. */ + if (secretSz == 0) + secretSz = COOKIE_SECRET_SZ; -#ifndef NO_FILESYSTEM -int wolfSSL_CTX_use_RSAPrivateKey_file(WOLFSSL_CTX* ctx,const char* file, - int format) -{ - WOLFSSL_ENTER("wolfSSL_CTX_use_RSAPrivateKey_file"); + if (secretSz != ssl->buffers.dtlsCookieSecret.length) { + byte* newSecret; - return wolfSSL_CTX_use_PrivateKey_file(ctx, file, format); -} + if (ssl->buffers.dtlsCookieSecret.buffer != NULL) { + ForceZero(ssl->buffers.dtlsCookieSecret.buffer, + ssl->buffers.dtlsCookieSecret.length); + XFREE(ssl->buffers.dtlsCookieSecret.buffer, + ssl->heap, DYNAMIC_TYPE_COOKIE_PWD); + } + newSecret = (byte*)XMALLOC(secretSz, ssl->heap,DYNAMIC_TYPE_COOKIE_PWD); + if (newSecret == NULL) { + ssl->buffers.dtlsCookieSecret.buffer = NULL; + ssl->buffers.dtlsCookieSecret.length = 0; + WOLFSSL_MSG("couldn't allocate new cookie secret"); + return MEMORY_ERROR; + } + ssl->buffers.dtlsCookieSecret.buffer = newSecret; + ssl->buffers.dtlsCookieSecret.length = secretSz; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("wolfSSL_DTLS_SetCookieSecret secret", + ssl->buffers.dtlsCookieSecret.buffer, + ssl->buffers.dtlsCookieSecret.length); + #endif + } -int wolfSSL_use_RSAPrivateKey_file(WOLFSSL* ssl, const char* file, int format) -{ - WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_file"); + /* If the supplied secret is NULL, randomly generate a new secret. */ + if (secret == NULL) { + ret = wc_RNG_GenerateBlock(ssl->rng, + ssl->buffers.dtlsCookieSecret.buffer, secretSz); + } + else + XMEMCPY(ssl->buffers.dtlsCookieSecret.buffer, secret, secretSz); - return wolfSSL_use_PrivateKey_file(ssl, file, format); + WOLFSSL_LEAVE("wolfSSL_DTLS_SetCookieSecret", 0); + return ret; } -#endif /* NO_FILESYSTEM */ +#endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */ -/* Copies the master secret over to out buffer. If outSz is 0 returns the size - * of master secret. - * - * ses : a session from completed TLS/SSL handshake - * out : buffer to hold copy of master secret - * outSz : size of out buffer - * returns : number of bytes copied into out buffer on success - * less then or equal to 0 is considered a failure case - */ -int wolfSSL_SESSION_get_master_key(const WOLFSSL_SESSION* ses, - unsigned char* out, int outSz) -{ - int size; - - ses = ClientSessionToSession(ses); - if (outSz == 0) { - return SECRET_LEN; +/* EITHER SIDE METHODS */ +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + WOLFSSL_METHOD* wolfSSLv23_method(void) + { + return wolfSSLv23_method_ex(NULL); } + WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap) + { + WOLFSSL_METHOD* m = NULL; + WOLFSSL_ENTER("wolfSSLv23_method"); + #if !defined(NO_WOLFSSL_CLIENT) + m = wolfSSLv23_client_method_ex(heap); + #elif !defined(NO_WOLFSSL_SERVER) + m = wolfSSLv23_server_method_ex(heap); + #else + (void)heap; + #endif + if (m != NULL) { + m->side = WOLFSSL_NEITHER_END; + } - if (ses == NULL || out == NULL || outSz < 0) { - return 0; + return m; } - if (outSz > SECRET_LEN) { - size = SECRET_LEN; - } - else { - size = outSz; + #ifndef NO_OLD_TLS + #ifdef WOLFSSL_ALLOW_SSLV3 + WOLFSSL_METHOD* wolfSSLv3_method(void) + { + return wolfSSLv3_method_ex(NULL); } + WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap) + { + WOLFSSL_METHOD* m = NULL; + WOLFSSL_ENTER("wolfSSLv3_method_ex"); + #if !defined(NO_WOLFSSL_CLIENT) + m = wolfSSLv3_client_method_ex(heap); + #elif !defined(NO_WOLFSSL_SERVER) + m = wolfSSLv3_server_method_ex(heap); + #endif + if (m != NULL) { + m->side = WOLFSSL_NEITHER_END; + } - XMEMCPY(out, ses->masterSecret, size); - return size; -} - + return m; + } + #endif + #endif +#endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ -int wolfSSL_SESSION_get_master_key_length(const WOLFSSL_SESSION* ses) -{ - (void)ses; - return SECRET_LEN; -} +/* client only parts */ +#ifndef NO_WOLFSSL_CLIENT -#ifdef WOLFSSL_EARLY_DATA -unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSION *session) -{ - return session->maxEarlyDataSz; -} -#endif /* WOLFSSL_EARLY_DATA */ - -#endif /* OPENSSL_EXTRA */ + #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) + WOLFSSL_METHOD* wolfSSLv2_client_method(void) + { + WOLFSSL_STUB("wolfSSLv2_client_method"); + return NULL; + } + #endif -typedef struct { - byte verifyPeer:1; - byte verifyNone:1; - byte failNoCert:1; - byte failNoCertxPSK:1; - byte verifyPostHandshake:1; -} SetVerifyOptions; + #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) + WOLFSSL_METHOD* wolfSSLv3_client_method(void) + { + return wolfSSLv3_client_method_ex(NULL); + } + WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap) + { + WOLFSSL_METHOD* method = + (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), + heap, DYNAMIC_TYPE_METHOD); + (void)heap; + WOLFSSL_ENTER("wolfSSLv3_client_method_ex"); + if (method) + InitSSL_Method(method, MakeSSLv3()); + return method; + } + #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */ -static SetVerifyOptions ModeToVerifyOptions(int mode) -{ - SetVerifyOptions opts; - XMEMSET(&opts, 0, sizeof(SetVerifyOptions)); - if (mode != WOLFSSL_VERIFY_DEFAULT) { - opts.verifyNone = (mode == WOLFSSL_VERIFY_NONE); - if (!opts.verifyNone) { - opts.verifyPeer = - (mode & WOLFSSL_VERIFY_PEER) != 0; - opts.failNoCertxPSK = - (mode & WOLFSSL_VERIFY_FAIL_EXCEPT_PSK) != 0; - opts.failNoCert = - (mode & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0; -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - opts.verifyPostHandshake = - (mode & WOLFSSL_VERIFY_POST_HANDSHAKE) != 0; -#endif + WOLFSSL_METHOD* wolfSSLv23_client_method(void) + { + return wolfSSLv23_client_method_ex(NULL); + } + WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap) + { + WOLFSSL_METHOD* method = + (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), + heap, DYNAMIC_TYPE_METHOD); + (void)heap; + WOLFSSL_ENTER("wolfSSLv23_client_method_ex"); + if (method) { + #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \ + defined(WOLFSSL_SHA512) + #if defined(WOLFSSL_TLS13) + InitSSL_Method(method, MakeTLSv1_3()); + #elif !defined(WOLFSSL_NO_TLS12) + InitSSL_Method(method, MakeTLSv1_2()); + #elif !defined(NO_OLD_TLS) + InitSSL_Method(method, MakeTLSv1_1()); + #endif + #else + #ifndef NO_OLD_TLS + InitSSL_Method(method, MakeTLSv1_1()); + #endif + #endif + #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13) + method->downgrade = 1; + #endif } + return method; } - return opts; -} + /* please see note at top of README if you get an error from connect */ + WOLFSSL_ABI + int wolfSSL_connect(WOLFSSL* ssl) + { + #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \ + defined(WOLFSSL_TLS13)) + int neededState; + byte advanceState; + #endif + int ret = 0; -WOLFSSL_ABI -void wolfSSL_CTX_set_verify(WOLFSSL_CTX* ctx, int mode, VerifyCallback vc) -{ - SetVerifyOptions opts; + (void)ret; - WOLFSSL_ENTER("wolfSSL_CTX_set_verify"); - if (ctx == NULL) - return; + #ifdef HAVE_ERRNO_H + errno = 0; + #endif - opts = ModeToVerifyOptions(mode); + if (ssl == NULL) + return BAD_FUNC_ARG; - ctx->verifyNone = opts.verifyNone; - ctx->verifyPeer = opts.verifyPeer; - ctx->failNoCert = opts.failNoCert; - ctx->failNoCertxPSK = opts.failNoCertxPSK; -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - ctx->verifyPostHandshake = opts.verifyPostHandshake; -#endif + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (ssl->options.side == WOLFSSL_NEITHER_END) { + ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END); + if (ssl->error != WOLFSSL_SUCCESS) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->error = 0; /* expected to be zero here */ + } - ctx->verifyCallback = vc; -} + #ifdef OPENSSL_EXTRA + if (ssl->CBIS != NULL) { + ssl->CBIS(ssl, SSL_ST_CONNECT, WOLFSSL_SUCCESS); + ssl->cbmode = SSL_CB_WRITE; + } + #endif + #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ -#ifdef OPENSSL_ALL -void wolfSSL_CTX_set_cert_verify_callback(WOLFSSL_CTX* ctx, - CertVerifyCallback cb, void* arg) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_cert_verify_callback"); - if (ctx == NULL) - return; + #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \ + defined(WOLFSSL_TLS13) + return wolfSSL_connect_TLSv13(ssl); + #else + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) { + WOLFSSL_MSG("TLS 1.3"); + return wolfSSL_connect_TLSv13(ssl); + } + #endif - ctx->verifyCertCb = cb; - ctx->verifyCertCbArg = arg; -} -#endif + WOLFSSL_MSG("TLS 1.2 or lower"); + WOLFSSL_ENTER("wolfSSL_connect"); + /* make sure this wolfSSL object has arrays and rng setup. Protects + * case where the WOLFSSL object is reused via wolfSSL_clear() */ + if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { + return ret; + } -void wolfSSL_set_verify(WOLFSSL* ssl, int mode, VerifyCallback vc) -{ - SetVerifyOptions opts; +#ifdef WOLFSSL_WOLFSENTRY_HOOKS + if ((ssl->ConnectFilter != NULL) && + (ssl->options.connectState == CONNECT_BEGIN)) { + wolfSSL_netfilter_decision_t res; + if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) == + WOLFSSL_SUCCESS) && + (res == WOLFSSL_NETFILTER_REJECT)) { + ssl->error = SOCKET_FILTERED_E; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } +#endif /* WOLFSSL_WOLFSENTRY_HOOKS */ - WOLFSSL_ENTER("wolfSSL_set_verify"); - if (ssl == NULL) - return; + if (ssl->options.side != WOLFSSL_CLIENT_END) { + ssl->error = SIDE_ERROR; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } - opts = ModeToVerifyOptions(mode); + #ifdef WOLFSSL_DTLS + if (ssl->version.major == DTLS_MAJOR) { + ssl->options.dtls = 1; + ssl->options.tls = 1; + ssl->options.tls1_1 = 1; + ssl->options.dtlsStateful = 1; + } + #endif - ssl->options.verifyNone = opts.verifyNone; - ssl->options.verifyPeer = opts.verifyPeer; - ssl->options.failNoCert = opts.failNoCert; - ssl->options.failNoCertxPSK = opts.failNoCertxPSK; -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - ssl->options.verifyPostHandshake = opts.verifyPostHandshake; -#endif + /* fragOffset is non-zero when sending fragments. On the last + * fragment, fragOffset is zero again, and the state can be + * advanced. */ + advanceState = ssl->fragOffset == 0 && + (ssl->options.connectState == CONNECT_BEGIN || + ssl->options.connectState == HELLO_AGAIN || + (ssl->options.connectState >= FIRST_REPLY_DONE && + ssl->options.connectState <= FIRST_REPLY_FOURTH)); - ssl->verifyCallback = vc; -} +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) + advanceState = advanceState && !ssl->dtls13SendingAckOrRtx; +#endif /* WOLFSSL_DTLS13 */ -void wolfSSL_set_verify_result(WOLFSSL *ssl, long v) -{ - WOLFSSL_ENTER("wolfSSL_set_verify_result"); + if (ssl->buffers.outputBuffer.length > 0 + #ifdef WOLFSSL_ASYNC_CRYPT + /* do not send buffered or advance state if last error was an + async pending operation */ + && ssl->error != WC_PENDING_E + #endif + ) { + ret = SendBuffered(ssl); + if (ret == 0) { + if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) { + if (advanceState) { + ssl->options.connectState++; + WOLFSSL_MSG("connect state: Advanced from last " + "buffered fragment send"); + #ifdef WOLFSSL_ASYNC_IO + /* Cleanup async */ + FreeAsyncCtx(ssl, 0); + #endif + } + } + else { + WOLFSSL_MSG("connect state: " + "Not advanced, more fragments to send"); + } + } + else { + ssl->error = ret; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) + ssl->dtls13SendingAckOrRtx = 0; +#endif /* WOLFSSL_DTLS13 */ + } - if (ssl == NULL) - return; + ret = RetrySendAlert(ssl); + if (ret != 0) { + ssl->error = ret; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(OPENSSL_ALL) - ssl->peerVerifyRet = v; -#else - (void)v; - WOLFSSL_STUB("wolfSSL_set_verify_result"); -#endif -} + switch (ssl->options.connectState) { -#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) && \ - defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) -/* For TLS v1.3 send handshake messages after handshake completes. */ -/* Returns 1=WOLFSSL_SUCCESS or 0=WOLFSSL_FAILURE */ -int wolfSSL_verify_client_post_handshake(WOLFSSL* ssl) -{ - int ret = wolfSSL_request_certificate(ssl); - if (ret != WOLFSSL_SUCCESS) { - if (!IsAtLeastTLSv1_3(ssl->version)) { - /* specific error of wrong version expected */ - WOLFSSL_ERROR(UNSUPPORTED_PROTO_VERSION); + case CONNECT_BEGIN : + /* always send client hello first */ + if ( (ssl->error = SendClientHello(ssl)) != 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.connectState = CLIENT_HELLO_SENT; + WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT"); + FALL_THROUGH; - } - else { - WOLFSSL_ERROR(ret); /* log the error in the error queue */ - } - } - return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; -} + case CLIENT_HELLO_SENT : + neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE : + SERVER_HELLODONE_COMPLETE; + #ifdef WOLFSSL_DTLS + /* In DTLS, when resuming, we can go straight to FINISHED, + * or do a cookie exchange and then skip to FINISHED, assume + * we need the cookie exchange first. */ + if (IsDtlsNotSctpMode(ssl)) + neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE; + #endif + /* get response */ + WOLFSSL_MSG("Server state up to needed state."); + while (ssl->options.serverState < neededState) { + WOLFSSL_MSG("Progressing server state..."); + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) + return wolfSSL_connect_TLSv13(ssl); + #endif + WOLFSSL_MSG("ProcessReply..."); + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + /* if resumption failed, reset needed state */ + else if (neededState == SERVER_FINISHED_COMPLETE) { + if (!ssl->options.resuming) { + #ifdef WOLFSSL_DTLS + if (IsDtlsNotSctpMode(ssl)) + neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE; + else + #endif + neededState = SERVER_HELLODONE_COMPLETE; + } + } + WOLFSSL_MSG("ProcessReply done."); -int wolfSSL_CTX_set_post_handshake_auth(WOLFSSL_CTX* ctx, int val) -{ - int ret = wolfSSL_CTX_allow_post_handshake_auth(ctx); - if (ret == 0) { - ctx->postHandshakeAuth = (val != 0); - } - return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; -} -int wolfSSL_set_post_handshake_auth(WOLFSSL* ssl, int val) -{ - int ret = wolfSSL_allow_post_handshake_auth(ssl); - if (ret == 0) { - ssl->options.postHandshakeAuth = (val != 0); - } - return (ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; -} -#endif /* OPENSSL_EXTRA && !NO_CERTS && WOLFSSL_TLS13 && WOLFSSL_POST_HANDSHAKE_AUTH */ +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) + && ssl->dtls13Rtx.sendAcks == 1 + && ssl->options.seenUnifiedHdr) { + /* we aren't negotiated the version yet, so we aren't sure + * the other end can speak v1.3. On the other side we have + * received a unified records, assuming that the + * ServerHello got lost, we will send an empty ACK. In case + * the server is a DTLS with version less than 1.3, it + * should just ignore the message */ + ssl->dtls13Rtx.sendAcks = 0; + if ((ssl->error = SendDtls13Ack(ssl)) < 0) { + if (ssl->error == WANT_WRITE) + ssl->dtls13SendingAckOrRtx = 1; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } +#endif /* WOLFSSL_DTLS13 */ + } -/* store user ctx for verify callback */ -void wolfSSL_SetCertCbCtx(WOLFSSL* ssl, void* ctx) -{ - WOLFSSL_ENTER("wolfSSL_SetCertCbCtx"); - if (ssl) - ssl->verifyCbCtx = ctx; -} + ssl->options.connectState = HELLO_AGAIN; + WOLFSSL_MSG("connect state: HELLO_AGAIN"); + FALL_THROUGH; + case HELLO_AGAIN : -/* store user ctx for verify callback */ -void wolfSSL_CTX_SetCertCbCtx(WOLFSSL_CTX* ctx, void* userCtx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_SetCertCbCtx"); - if (ctx) - ctx->verifyCbCtx = userCtx; -} + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) + return wolfSSL_connect_TLSv13(ssl); + #endif + #ifdef WOLFSSL_DTLS + if (ssl->options.serverState == + SERVER_HELLOVERIFYREQUEST_COMPLETE) { + if (IsDtlsNotSctpMode(ssl)) { + /* re-init hashes, exclude first hello and verify request */ + if ((ssl->error = InitHandshakeHashes(ssl)) != 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + if ( (ssl->error = SendClientHello(ssl)) != 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } + } + #endif -/* store context CA Cache addition callback */ -void wolfSSL_CTX_SetCACb(WOLFSSL_CTX* ctx, CallbackCACache cb) -{ - if (ctx && ctx->cm) - ctx->cm->caCacheCallback = cb; -} + ssl->options.connectState = HELLO_AGAIN_REPLY; + WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY"); + FALL_THROUGH; + case HELLO_AGAIN_REPLY : + #ifdef WOLFSSL_DTLS + if (IsDtlsNotSctpMode(ssl)) { + neededState = ssl->options.resuming ? + SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE; -#if defined(PERSIST_CERT_CACHE) + /* get response */ + while (ssl->options.serverState < neededState) { + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + /* if resumption failed, reset needed state */ + if (neededState == SERVER_FINISHED_COMPLETE) { + if (!ssl->options.resuming) + neededState = SERVER_HELLODONE_COMPLETE; + } + } + } + #endif -#if !defined(NO_FILESYSTEM) + ssl->options.connectState = FIRST_REPLY_DONE; + WOLFSSL_MSG("connect state: FIRST_REPLY_DONE"); + FALL_THROUGH; -/* Persist cert cache to file */ -int wolfSSL_CTX_save_cert_cache(WOLFSSL_CTX* ctx, const char* fname) -{ - WOLFSSL_ENTER("wolfSSL_CTX_save_cert_cache"); + case FIRST_REPLY_DONE : + if (ssl->options.certOnly) + return WOLFSSL_SUCCESS; + #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH) + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) + return wolfSSL_connect_TLSv13(ssl); + #endif + if (ssl->options.sendVerify) { + if ( (ssl->error = SendCertificate(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + WOLFSSL_MSG("sent: certificate"); + } - if (ctx == NULL || fname == NULL) - return BAD_FUNC_ARG; + #endif + ssl->options.connectState = FIRST_REPLY_FIRST; + WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST"); + FALL_THROUGH; - return CM_SaveCertCache(ctx->cm, fname); -} + case FIRST_REPLY_FIRST : + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) + return wolfSSL_connect_TLSv13(ssl); + #endif + if (!ssl->options.resuming) { + if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif +#ifdef WOLFSSL_EXTRA_ALERTS + if (ssl->error == NO_PEER_KEY || + ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) { + SendAlert(ssl, alert_fatal, handshake_failure); + } +#endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + WOLFSSL_MSG("sent: client key exchange"); + } + ssl->options.connectState = FIRST_REPLY_SECOND; + WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND"); + FALL_THROUGH; -/* Persist cert cache from file */ -int wolfSSL_CTX_restore_cert_cache(WOLFSSL_CTX* ctx, const char* fname) -{ - WOLFSSL_ENTER("wolfSSL_CTX_restore_cert_cache"); + #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) + case FIRST_REPLY_SECOND : + /* CLIENT: Fail-safe for Server Authentication. */ + if (!ssl->options.peerAuthGood) { + WOLFSSL_MSG("Server authentication did not happen"); + ssl->error = NO_PEER_VERIFY; + return WOLFSSL_FATAL_ERROR; + } - if (ctx == NULL || fname == NULL) - return BAD_FUNC_ARG; + #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH) + if (ssl->options.sendVerify) { + if ( (ssl->error = SendCertificateVerify(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + WOLFSSL_MSG("sent: certificate verify"); + } + #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */ + ssl->options.connectState = FIRST_REPLY_THIRD; + WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD"); + FALL_THROUGH; - return CM_RestoreCertCache(ctx->cm, fname); -} - -#endif /* NO_FILESYSTEM */ - -/* Persist cert cache to memory */ -int wolfSSL_CTX_memsave_cert_cache(WOLFSSL_CTX* ctx, void* mem, - int sz, int* used) -{ - WOLFSSL_ENTER("wolfSSL_CTX_memsave_cert_cache"); - - if (ctx == NULL || mem == NULL || used == NULL || sz <= 0) - return BAD_FUNC_ARG; - - return CM_MemSaveCertCache(ctx->cm, mem, sz, used); -} - - -/* Restore cert cache from memory */ -int wolfSSL_CTX_memrestore_cert_cache(WOLFSSL_CTX* ctx, const void* mem, int sz) -{ - WOLFSSL_ENTER("wolfSSL_CTX_memrestore_cert_cache"); - - if (ctx == NULL || mem == NULL || sz <= 0) - return BAD_FUNC_ARG; - - return CM_MemRestoreCertCache(ctx->cm, mem, sz); -} - - -/* get how big the the cert cache save buffer needs to be */ -int wolfSSL_CTX_get_cert_cache_memsize(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_cert_cache_memsize"); + case FIRST_REPLY_THIRD : + if ( (ssl->error = SendChangeCipher(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + WOLFSSL_MSG("sent: change cipher spec"); + ssl->options.connectState = FIRST_REPLY_FOURTH; + WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH"); + FALL_THROUGH; - if (ctx == NULL) - return BAD_FUNC_ARG; + case FIRST_REPLY_FOURTH : + if ( (ssl->error = SendFinished(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + WOLFSSL_MSG("sent: finished"); + ssl->options.connectState = FINISHED_DONE; + WOLFSSL_MSG("connect state: FINISHED_DONE"); + FALL_THROUGH; - return CM_GetCertCacheMemSize(ctx->cm); -} +#ifdef WOLFSSL_DTLS13 + case WAIT_FINISHED_ACK: + ssl->options.connectState = FINISHED_DONE; + FALL_THROUGH; +#endif /* WOLFSSL_DTLS13 */ -#endif /* PERSIST_CERT_CACHE */ -#endif /* !NO_CERTS */ + case FINISHED_DONE : + /* get response */ + while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.connectState = SECOND_REPLY_DONE; + WOLFSSL_MSG("connect state: SECOND_REPLY_DONE"); + FALL_THROUGH; -#ifndef NO_SESSION_CACHE + case SECOND_REPLY_DONE: + #ifndef NO_HANDSHAKE_DONE_CB + if (ssl->hsDoneCb) { + int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); + if (cbret < 0) { + ssl->error = cbret; + WOLFSSL_MSG("HandShake Done Cb don't continue error"); + return WOLFSSL_FATAL_ERROR; + } + } + #endif /* NO_HANDSHAKE_DONE_CB */ -WOLFSSL_ABI -WOLFSSL_SESSION* wolfSSL_get_session(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_session"); - if (ssl) { -#ifdef NO_SESSION_CACHE_REF - return ssl->session; -#else - if (ssl->options.side == WOLFSSL_CLIENT_END) { - /* On the client side we want to return a persistent reference for - * backwards compatibility. */ -#ifndef NO_CLIENT_CACHE - if (ssl->clientSession) { - return (WOLFSSL_SESSION*)ssl->clientSession; + if (!ssl->options.dtls) { + if (!ssl->options.keepResources) { + FreeHandshakeResources(ssl); + } } + #ifdef WOLFSSL_DTLS else { - /* Try to add a ClientCache entry to associate with the current - * session. Ignore any session cache options. */ - int err; - const byte* id = ssl->session->sessionID; - byte idSz = ssl->session->sessionIDSz; - if (ssl->session->haveAltSessionID) { - id = ssl->session->altSessionID; - idSz = ID_LEN; - } - err = AddSessionToCache(ssl->ctx, ssl->session, id, idSz, - NULL, ssl->session->side, - #ifdef HAVE_SESSION_TICKET - ssl->session->ticketLen > 0, - #else - 0, - #endif - &ssl->clientSession); - if (err == 0) { - return (WOLFSSL_SESSION*)ssl->clientSession; - } + ssl->options.dtlsHsRetain = 1; } -#endif - } - else { - return ssl->session; - } -#endif - } - - return NULL; -} + #endif /* WOLFSSL_DTLS */ -/* The get1 version requires caller to call SSL_SESSION_free */ -WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl) -{ - WOLFSSL_SESSION* sess = NULL; - WOLFSSL_ENTER("wolfSSL_get1_session"); - if (ssl != NULL) { - sess = ssl->session; - if (sess != NULL) { - /* increase reference count if allocated session */ - if (sess->type == WOLFSSL_SESSION_TYPE_HEAP) { - if (wolfSSL_SESSION_up_ref(sess) != WOLFSSL_SUCCESS) - sess = NULL; + #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION) + /* This may be necessary in async so that we don't try to + * renegotiate again */ + if (ssl->secure_renegotiation && + ssl->secure_renegotiation->startScr) { + ssl->secure_renegotiation->startScr = 0; } - } - } - return sess; -} + #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */ + #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT) + /* Free the remaining async context if not using it for crypto */ + FreeAsyncCtx(ssl, 1); + #endif + ssl->error = 0; /* clear the error */ -/* - * Sets the session object to use when establishing a TLS/SSL session using - * the ssl object. Therefore, this function must be called before - * wolfSSL_connect. The session object to use can be obtained in a previous - * TLS/SSL connection using wolfSSL_get_session. - * - * This function rejects the session if it has been expired when this function - * is called. Note that this expiration check is wolfSSL specific and differs - * from OpenSSL return code behavior. - * - * By default, wolfSSL_set_session returns WOLFSSL_SUCCESS on successfully - * setting the session, WOLFSSL_FAILURE on failure due to the session cache - * being disabled, or the session has expired. - * - * To match OpenSSL return code behavior when session is expired, define - * OPENSSL_EXTRA and WOLFSSL_ERROR_CODE_OPENSSL. This behavior will return - * WOLFSSL_SUCCESS even when the session is expired and rejected. - */ -WOLFSSL_ABI -int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* session) -{ - WOLFSSL_ENTER("wolfSSL_set_session"); - if (session) - return wolfSSL_SetSession(ssl, session); + WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS); + return WOLFSSL_SUCCESS; + #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */ - return WOLFSSL_FAILURE; -} + default: + WOLFSSL_MSG("Unknown connect state ERROR"); + return WOLFSSL_FATAL_ERROR; /* unknown connect state */ + } + #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */ + } +#endif /* NO_WOLFSSL_CLIENT */ -#ifndef NO_CLIENT_CACHE -/* Associate client session with serverID, find existing or store for saving - if newSession flag on, don't reuse existing session - WOLFSSL_SUCCESS on ok */ -int wolfSSL_SetServerID(WOLFSSL* ssl, const byte* id, int len, int newSession) -{ - WOLFSSL_SESSION* session = NULL; - byte idHash[SERVER_ID_LEN]; +/* server only parts */ +#ifndef NO_WOLFSSL_SERVER - WOLFSSL_ENTER("wolfSSL_SetServerID"); + #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) + WOLFSSL_METHOD* wolfSSLv2_server_method(void) + { + WOLFSSL_STUB("wolfSSLv2_server_method"); + return 0; + } + #endif - if (ssl == NULL || id == NULL || len <= 0) - return BAD_FUNC_ARG; + #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) + WOLFSSL_METHOD* wolfSSLv3_server_method(void) + { + return wolfSSLv3_server_method_ex(NULL); + } + WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap) + { + WOLFSSL_METHOD* method = + (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), + heap, DYNAMIC_TYPE_METHOD); + (void)heap; + WOLFSSL_ENTER("wolfSSLv3_server_method_ex"); + if (method) { + InitSSL_Method(method, MakeSSLv3()); + method->side = WOLFSSL_SERVER_END; + } + return method; + } + #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */ - if (len > SERVER_ID_LEN) { -#if defined(NO_SHA) && !defined(NO_SHA256) - if (wc_Sha256Hash(id, len, idHash) != 0) - return WOLFSSL_FAILURE; -#else - if (wc_ShaHash(id, len, idHash) != 0) - return WOLFSSL_FAILURE; -#endif - id = idHash; - len = SERVER_ID_LEN; + WOLFSSL_METHOD* wolfSSLv23_server_method(void) + { + return wolfSSLv23_server_method_ex(NULL); } - if (newSession == 0) { - session = wolfSSL_GetSessionClient(ssl, id, len); - if (session) { - if (wolfSSL_SetSession(ssl, session) != WOLFSSL_SUCCESS) { - #ifdef HAVE_EXT_CACHE - wolfSSL_FreeSession(ssl->ctx, session); - #endif - WOLFSSL_MSG("wolfSSL_SetSession failed"); - session = NULL; - } + WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap) + { + WOLFSSL_METHOD* method = + (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), + heap, DYNAMIC_TYPE_METHOD); + (void)heap; + WOLFSSL_ENTER("wolfSSLv23_server_method_ex"); + if (method) { + #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \ + defined(WOLFSSL_SHA512) + #ifdef WOLFSSL_TLS13 + InitSSL_Method(method, MakeTLSv1_3()); + #elif !defined(WOLFSSL_NO_TLS12) + InitSSL_Method(method, MakeTLSv1_2()); + #elif !defined(NO_OLD_TLS) + InitSSL_Method(method, MakeTLSv1_1()); + #endif + #else + #ifndef NO_OLD_TLS + InitSSL_Method(method, MakeTLSv1_1()); + #else + #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2 + #endif + #endif + #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13) + method->downgrade = 1; + #endif + method->side = WOLFSSL_SERVER_END; } + return method; } - if (session == NULL) { - WOLFSSL_MSG("Valid ServerID not cached already"); - ssl->session->idLen = (word16)len; - XMEMCPY(ssl->session->serverID, id, len); - } -#ifdef HAVE_EXT_CACHE - else { - wolfSSL_FreeSession(ssl->ctx, session); - } + WOLFSSL_ABI + int wolfSSL_accept(WOLFSSL* ssl) + { +#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \ + defined(WOLFSSL_TLS13)) + word16 havePSK = 0; + word16 haveAnon = 0; + word16 haveMcast = 0; #endif + int ret = 0; - return WOLFSSL_SUCCESS; -} - -#endif /* !NO_CLIENT_CACHE */ + (void)ret; -/* TODO: Add SESSION_CACHE_DYNAMIC_MEM support for PERSIST_SESSION_CACHE. - * Need a count of current sessions to get an accurate memsize (totalCount is - * not decremented when sessions are removed). - * Need to determine ideal layout for mem/filesave. - * Also need mem/filesave checking to ensure not restoring non DYNAMIC_MEM cache. - */ -#if defined(PERSIST_SESSION_CACHE) && !defined(SESSION_CACHE_DYNAMIC_MEM) + if (ssl == NULL) + return WOLFSSL_FATAL_ERROR; -/* for persistence, if changes to layout need to increment and modify - save_session_cache() and restore_session_cache and memory versions too */ -#define WOLFSSL_CACHE_VERSION 2 + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) + if (ssl->options.side == WOLFSSL_NEITHER_END) { + WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side"); + ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END); + if (ssl->error != WOLFSSL_SUCCESS) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->error = 0; /* expected to be zero here */ + } + #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ -/* Session Cache Header information */ -typedef struct { - int version; /* cache layout version id */ - int rows; /* session rows */ - int columns; /* session columns */ - int sessionSz; /* sizeof WOLFSSL_SESSION */ -} cache_header_t; +#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13) + return wolfSSL_accept_TLSv13(ssl); +#else + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) + return wolfSSL_accept_TLSv13(ssl); + #endif + WOLFSSL_ENTER("wolfSSL_accept"); -/* current persistence layout is: + /* make sure this wolfSSL object has arrays and rng setup. Protects + * case where the WOLFSSL object is reused via wolfSSL_clear() */ + if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { + return ret; + } - 1) cache_header_t - 2) SessionCache - 3) ClientCache - - update WOLFSSL_CACHE_VERSION if change layout for the following - PERSISTENT_SESSION_CACHE functions -*/ - -/* get how big the the session cache save buffer needs to be */ -int wolfSSL_get_session_cache_memsize(void) -{ - int sz = (int)(sizeof(SessionCache) + sizeof(cache_header_t)); -#ifndef NO_CLIENT_CACHE - sz += (int)(sizeof(ClientCache)); -#endif - return sz; -} - - -/* Persist session cache to memory */ -int wolfSSL_memsave_session_cache(void* mem, int sz) -{ - int i; - cache_header_t cache_header; - SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header)); - - WOLFSSL_ENTER("wolfSSL_memsave_session_cache"); - - if (sz < wolfSSL_get_session_cache_memsize()) { - WOLFSSL_MSG("Memory buffer too small"); - return BUFFER_E; - } - - cache_header.version = WOLFSSL_CACHE_VERSION; - cache_header.rows = SESSION_ROWS; - cache_header.columns = SESSIONS_PER_ROW; - cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION); - XMEMCPY(mem, &cache_header, sizeof(cache_header)); - -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_RD_LOCK(row) != 0) { - WOLFSSL_MSG("Session cache mutex lock failed"); - return BAD_MUTEX_E; - } +#ifdef WOLFSSL_WOLFSENTRY_HOOKS + if ((ssl->AcceptFilter != NULL) && + ((ssl->options.acceptState == ACCEPT_BEGIN) +#ifdef HAVE_SECURE_RENEGOTIATION + || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG) #endif - for (i = 0; i < cache_header.rows; ++i) { - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) { - WOLFSSL_MSG("Session row cache mutex lock failed"); - return BAD_MUTEX_E; + )) + { + wolfSSL_netfilter_decision_t res; + if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) == + WOLFSSL_SUCCESS) && + (res == WOLFSSL_NETFILTER_REJECT)) { + ssl->error = SOCKET_FILTERED_E; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } } - #endif - - XMEMCPY(row++, &SessionCache[i], SIZEOF_SESSION_ROW); - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[i]); - #endif - } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(row); -#endif - -#ifndef NO_CLIENT_CACHE - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - return BAD_MUTEX_E; - } - XMEMCPY(row, ClientCache, sizeof(ClientCache)); - wc_UnLockMutex(&clisession_mutex); -#endif - - WOLFSSL_LEAVE("wolfSSL_memsave_session_cache", WOLFSSL_SUCCESS); +#endif /* WOLFSSL_WOLFSENTRY_HOOKS */ - return WOLFSSL_SUCCESS; -} + #ifdef HAVE_ERRNO_H + errno = 0; + #endif + #ifndef NO_PSK + havePSK = ssl->options.havePSK; + #endif + (void)havePSK; -/* Restore the persistent session cache from memory */ -int wolfSSL_memrestore_session_cache(const void* mem, int sz) -{ - int i; - cache_header_t cache_header; - SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header)); + #ifdef HAVE_ANON + haveAnon = ssl->options.useAnon; + #endif + (void)haveAnon; - WOLFSSL_ENTER("wolfSSL_memrestore_session_cache"); + #ifdef WOLFSSL_MULTICAST + haveMcast = ssl->options.haveMcast; + #endif + (void)haveMcast; - if (sz < wolfSSL_get_session_cache_memsize()) { - WOLFSSL_MSG("Memory buffer too small"); - return BUFFER_E; - } + if (ssl->options.side != WOLFSSL_SERVER_END) { + ssl->error = SIDE_ERROR; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } - XMEMCPY(&cache_header, mem, sizeof(cache_header)); - if (cache_header.version != WOLFSSL_CACHE_VERSION || - cache_header.rows != SESSION_ROWS || - cache_header.columns != SESSIONS_PER_ROW || - cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) { + #ifndef NO_CERTS + /* in case used set_accept_state after init */ + if (!havePSK && !haveAnon && !haveMcast) { + #ifdef OPENSSL_EXTRA + if (ssl->ctx->certSetupCb != NULL) { + WOLFSSL_MSG("CertSetupCb set. server cert and " + "key not checked"); + } + else + #endif + { + if (!ssl->buffers.certificate || + !ssl->buffers.certificate->buffer) { - WOLFSSL_MSG("Session cache header match failed"); - return CACHE_MATCH_ERROR; - } + WOLFSSL_MSG("accept error: server cert required"); + ssl->error = NO_PRIVATE_KEY; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) { - WOLFSSL_MSG("Session cache mutex lock failed"); - return BAD_MUTEX_E; - } -#endif - for (i = 0; i < cache_header.rows; ++i) { - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { - WOLFSSL_MSG("Session row cache mutex lock failed"); - return BAD_MUTEX_E; + if (!ssl->buffers.key || !ssl->buffers.key->buffer) { + /* allow no private key if using existing key */ + #ifdef WOLF_PRIVATE_KEY_ID + if (ssl->devId != INVALID_DEVID + #ifdef HAVE_PK_CALLBACKS + || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx) + #endif + ) { + WOLFSSL_MSG("Allowing no server private key " + "(external)"); + } + else + #endif + { + WOLFSSL_MSG("accept error: server key required"); + ssl->error = NO_PRIVATE_KEY; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } + } } #endif - XMEMCPY(&SessionCache[i], row++, SIZEOF_SESSION_ROW); - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[i]); - #endif - } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[0]); -#endif - -#ifndef NO_CLIENT_CACHE - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - return BAD_MUTEX_E; - } - XMEMCPY(ClientCache, row, sizeof(ClientCache)); - wc_UnLockMutex(&clisession_mutex); -#endif - - WOLFSSL_LEAVE("wolfSSL_memrestore_session_cache", WOLFSSL_SUCCESS); - - return WOLFSSL_SUCCESS; -} - -#if !defined(NO_FILESYSTEM) - -/* Persist session cache to file */ -/* doesn't use memsave because of additional memory use */ -int wolfSSL_save_session_cache(const char *fname) -{ - XFILE file; - int ret; - int rc = WOLFSSL_SUCCESS; - int i; - cache_header_t cache_header; - - WOLFSSL_ENTER("wolfSSL_save_session_cache"); - - file = XFOPEN(fname, "w+b"); - if (file == XBADFILE) { - WOLFSSL_MSG("Couldn't open session cache save file"); - return WOLFSSL_BAD_FILE; - } - cache_header.version = WOLFSSL_CACHE_VERSION; - cache_header.rows = SESSION_ROWS; - cache_header.columns = SESSIONS_PER_ROW; - cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION); - - /* cache header */ - ret = (int)XFWRITE(&cache_header, sizeof cache_header, 1, file); - if (ret != 1) { - WOLFSSL_MSG("Session cache header file write failed"); - XFCLOSE(file); - return FWRITE_ERROR; - } - -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_RD_LOCK(&SessionCache[0]) != 0) { - WOLFSSL_MSG("Session cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; - } -#endif - /* session cache */ - for (i = 0; i < cache_header.rows; ++i) { - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) { - WOLFSSL_MSG("Session row cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; + #ifdef WOLFSSL_DTLS + if (ssl->version.major == DTLS_MAJOR) { + ssl->options.dtls = 1; + ssl->options.tls = 1; + ssl->options.tls1_1 = 1; + if (!IsDtlsNotSctpMode(ssl) || !IsDtlsNotSrtpMode(ssl) || + IsSCR(ssl)) + ssl->options.dtlsStateful = 1; } #endif - ret = (int)XFWRITE(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file); - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[i]); - #endif - if (ret != 1) { - WOLFSSL_MSG("Session cache member file write failed"); - rc = FWRITE_ERROR; - break; + if (ssl->buffers.outputBuffer.length > 0 + #ifdef WOLFSSL_ASYNC_CRYPT + /* do not send buffered or advance state if last error was an + async pending operation */ + && ssl->error != WC_PENDING_E + #endif + ) { + ret = SendBuffered(ssl); + if (ret == 0) { + /* fragOffset is non-zero when sending fragments. On the last + * fragment, fragOffset is zero again, and the state can be + * advanced. */ + if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) { + if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE || + ssl->options.acceptState == SERVER_HELLO_SENT || + ssl->options.acceptState == CERT_SENT || + ssl->options.acceptState == CERT_STATUS_SENT || + ssl->options.acceptState == KEY_EXCHANGE_SENT || + ssl->options.acceptState == CERT_REQ_SENT || + ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE || + ssl->options.acceptState == TICKET_SENT || + ssl->options.acceptState == CHANGE_CIPHER_SENT) { + ssl->options.acceptState++; + WOLFSSL_MSG("accept state: Advanced from last " + "buffered fragment send"); + #ifdef WOLFSSL_ASYNC_IO + /* Cleanup async */ + FreeAsyncCtx(ssl, 0); + #endif + } + } + else { + WOLFSSL_MSG("accept state: " + "Not advanced, more fragments to send"); + } + } + else { + ssl->error = ret; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) + ssl->dtls13SendingAckOrRtx = 0; +#endif /* WOLFSSL_DTLS13 */ } - } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[0]); -#endif -#ifndef NO_CLIENT_CACHE - /* client cache */ - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; - } - ret = (int)XFWRITE(ClientCache, sizeof(ClientCache), 1, file); - if (ret != 1) { - WOLFSSL_MSG("Client cache member file write failed"); - rc = FWRITE_ERROR; - } - wc_UnLockMutex(&clisession_mutex); -#endif /* !NO_CLIENT_CACHE */ + ret = RetrySendAlert(ssl); + if (ret != 0) { + ssl->error = ret; + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } - XFCLOSE(file); - WOLFSSL_LEAVE("wolfSSL_save_session_cache", rc); + switch (ssl->options.acceptState) { - return rc; -} + case ACCEPT_BEGIN : +#ifdef HAVE_SECURE_RENEGOTIATION + case ACCEPT_BEGIN_RENEG: +#endif + /* get response */ + while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } +#ifdef WOLFSSL_TLS13 + ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE; + WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE"); + FALL_THROUGH; + case ACCEPT_CLIENT_HELLO_DONE : + if (ssl->options.tls1_3) { + return wolfSSL_accept_TLSv13(ssl); + } +#endif -/* Restore the persistent session cache from file */ -/* doesn't use memstore because of additional memory use */ -int wolfSSL_restore_session_cache(const char *fname) -{ - XFILE file; - int rc = WOLFSSL_SUCCESS; - int ret; - int i; - cache_header_t cache_header; + ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE; + WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE"); + FALL_THROUGH; - WOLFSSL_ENTER("wolfSSL_restore_session_cache"); + case ACCEPT_FIRST_REPLY_DONE : + if ( (ssl->error = SendServerHello(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.acceptState = SERVER_HELLO_SENT; + WOLFSSL_MSG("accept state SERVER_HELLO_SENT"); + FALL_THROUGH; - file = XFOPEN(fname, "rb"); - if (file == XBADFILE) { - WOLFSSL_MSG("Couldn't open session cache save file"); - return WOLFSSL_BAD_FILE; - } - /* cache header */ - ret = (int)XFREAD(&cache_header, sizeof(cache_header), 1, file); - if (ret != 1) { - WOLFSSL_MSG("Session cache header file read failed"); - XFCLOSE(file); - return FREAD_ERROR; - } - if (cache_header.version != WOLFSSL_CACHE_VERSION || - cache_header.rows != SESSION_ROWS || - cache_header.columns != SESSIONS_PER_ROW || - cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) { - - WOLFSSL_MSG("Session cache header match failed"); - XFCLOSE(file); - return CACHE_MATCH_ERROR; - } + case SERVER_HELLO_SENT : + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) { + return wolfSSL_accept_TLSv13(ssl); + } + #endif + #ifndef NO_CERTS + if (!ssl->options.resuming) + if ( (ssl->error = SendCertificate(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + #endif + ssl->options.acceptState = CERT_SENT; + WOLFSSL_MSG("accept state CERT_SENT"); + FALL_THROUGH; -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) { - WOLFSSL_MSG("Session cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; - } -#endif - /* session cache */ - for (i = 0; i < cache_header.rows; ++i) { - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { - WOLFSSL_MSG("Session row cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; - } - #endif + case CERT_SENT : + #ifndef NO_CERTS + if (!ssl->options.resuming) + if ( (ssl->error = SendCertificateStatus(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + #endif + ssl->options.acceptState = CERT_STATUS_SENT; + WOLFSSL_MSG("accept state CERT_STATUS_SENT"); + FALL_THROUGH; - ret = (int)XFREAD(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file); - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[i]); - #endif - if (ret != 1) { - WOLFSSL_MSG("Session cache member file read failed"); - XMEMSET(SessionCache, 0, sizeof SessionCache); - rc = FREAD_ERROR; - break; - } - } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[0]); -#endif + case CERT_STATUS_SENT : + #ifdef WOLFSSL_TLS13 + if (ssl->options.tls1_3) { + return wolfSSL_accept_TLSv13(ssl); + } + #endif + if (!ssl->options.resuming) + if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.acceptState = KEY_EXCHANGE_SENT; + WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT"); + FALL_THROUGH; -#ifndef NO_CLIENT_CACHE - /* client cache */ - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - XFCLOSE(file); - return BAD_MUTEX_E; - } - ret = (int)XFREAD(ClientCache, sizeof(ClientCache), 1, file); - if (ret != 1) { - WOLFSSL_MSG("Client cache member file read failed"); - XMEMSET(ClientCache, 0, sizeof ClientCache); - rc = FREAD_ERROR; - } - wc_UnLockMutex(&clisession_mutex); -#endif /* !NO_CLIENT_CACHE */ + case KEY_EXCHANGE_SENT : + #ifndef NO_CERTS + if (!ssl->options.resuming) { + if (ssl->options.verifyPeer) { + if ( (ssl->error = SendCertificateRequest(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + /* See if an alert was sent. */ + ProcessReplyEx(ssl, 1); + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } + else { + /* SERVER: Peer auth good if not verifying client. */ + ssl->options.peerAuthGood = 1; + } + } + #endif + ssl->options.acceptState = CERT_REQ_SENT; + WOLFSSL_MSG("accept state CERT_REQ_SENT"); + FALL_THROUGH; - XFCLOSE(file); - WOLFSSL_LEAVE("wolfSSL_restore_session_cache", rc); + case CERT_REQ_SENT : + if (!ssl->options.resuming) + if ( (ssl->error = SendServerHelloDone(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.acceptState = SERVER_HELLO_DONE; + WOLFSSL_MSG("accept state SERVER_HELLO_DONE"); + FALL_THROUGH; - return rc; -} + case SERVER_HELLO_DONE : + if (!ssl->options.resuming) { + while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } + ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE; + WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE"); + FALL_THROUGH; -#endif /* !NO_FILESYSTEM */ -#endif /* PERSIST_SESSION_CACHE && !SESSION_CACHE_DYNAMIC_MEM */ -#endif /* NO_SESSION_CACHE */ + case ACCEPT_SECOND_REPLY_DONE : + #ifndef NO_CERTS + /* SERVER: When not resuming and verifying peer but no certificate + * received and not failing when not received then peer auth good. + */ + if (!ssl->options.resuming && ssl->options.verifyPeer && + !ssl->options.havePeerCert && !ssl->options.failNoCert) { + ssl->options.peerAuthGood = 1; + } + #endif /* !NO_CERTS */ + #ifdef WOLFSSL_NO_CLIENT_AUTH + if (!ssl->options.resuming) { + ssl->options.peerAuthGood = 1; + } + #endif +#ifdef HAVE_SESSION_TICKET + if (ssl->options.createTicket && !ssl->options.noTicketTls12) { + if ( (ssl->error = SendTicket(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_MSG("Thought we need ticket but failed"); + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } +#endif /* HAVE_SESSION_TICKET */ + ssl->options.acceptState = TICKET_SENT; + WOLFSSL_MSG("accept state TICKET_SENT"); + FALL_THROUGH; -void wolfSSL_load_error_strings(void) -{ - /* compatibility only */ -} + case TICKET_SENT: + /* SERVER: Fail-safe for CLient Authentication. */ + if (!ssl->options.peerAuthGood) { + WOLFSSL_MSG("Client authentication did not happen"); + return WOLFSSL_FATAL_ERROR; + } + if ( (ssl->error = SendChangeCipher(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.acceptState = CHANGE_CIPHER_SENT; + WOLFSSL_MSG("accept state CHANGE_CIPHER_SENT"); + FALL_THROUGH; -int wolfSSL_library_init(void) -{ - WOLFSSL_ENTER("wolfSSL_library_init"); - if (wolfSSL_Init() == WOLFSSL_SUCCESS) - return WOLFSSL_SUCCESS; - else - return WOLFSSL_FATAL_ERROR; -} + case CHANGE_CIPHER_SENT : + if ( (ssl->error = SendFinished(ssl)) != 0) { + #ifdef WOLFSSL_CHECK_ALERT_ON_ERR + ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ + #endif + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + ssl->options.acceptState = ACCEPT_FINISHED_DONE; + WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE"); + FALL_THROUGH; -#ifdef HAVE_SECRET_CALLBACK + case ACCEPT_FINISHED_DONE : + if (ssl->options.resuming) { + while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) { + if ( (ssl->error = ProcessReply(ssl)) < 0) { + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } + } + ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE; + WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE"); + FALL_THROUGH; -int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx) -{ - WOLFSSL_ENTER("wolfSSL_set_session_secret_cb"); - if (ssl == NULL) - return WOLFSSL_FATAL_ERROR; + case ACCEPT_THIRD_REPLY_DONE : +#ifndef NO_HANDSHAKE_DONE_CB + if (ssl->hsDoneCb) { + int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); + if (cbret < 0) { + ssl->error = cbret; + WOLFSSL_MSG("HandShake Done Cb don't continue error"); + return WOLFSSL_FATAL_ERROR; + } + } +#endif /* NO_HANDSHAKE_DONE_CB */ - ssl->sessionSecretCb = cb; - ssl->sessionSecretCtx = ctx; - if (cb != NULL) { - /* If using a pre-set key, assume session resumption. */ - ssl->session->sessionIDSz = 0; - ssl->options.resuming = 1; - } + if (!ssl->options.dtls) { + if (!ssl->options.keepResources) { + FreeHandshakeResources(ssl); + } + } +#ifdef WOLFSSL_DTLS + else { + ssl->options.dtlsHsRetain = 1; + } +#endif /* WOLFSSL_DTLS */ - return WOLFSSL_SUCCESS; -} +#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION) + /* This may be necessary in async so that we don't try to + * renegotiate again */ + if (ssl->secure_renegotiation && + ssl->secure_renegotiation->startScr) { + ssl->secure_renegotiation->startScr = 0; + } +#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */ +#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT) + /* Free the remaining async context if not using it for crypto */ + FreeAsyncCtx(ssl, 1); +#endif +#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS) + if (ssl->dtls_export) { + if ((ssl->error = wolfSSL_send_session(ssl)) != 0) { + WOLFSSL_MSG("Export DTLS session error"); + WOLFSSL_ERROR(ssl->error); + return WOLFSSL_FATAL_ERROR; + } + } #endif + ssl->error = 0; /* clear the error */ + WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS); + return WOLFSSL_SUCCESS; -#ifndef NO_SESSION_CACHE + default : + WOLFSSL_MSG("Unknown accept state ERROR"); + return WOLFSSL_FATAL_ERROR; + } +#endif /* !WOLFSSL_NO_TLS12 */ + } -/* on by default if built in but allow user to turn off */ -WOLFSSL_ABI -long wolfSSL_CTX_set_session_cache_mode(WOLFSSL_CTX* ctx, long mode) +#endif /* NO_WOLFSSL_SERVER */ + +#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) +int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx) { - WOLFSSL_ENTER("wolfSSL_CTX_set_session_cache_mode"); + WOLFSSL_ENTER("wolfDTLS_SetChGoodCb"); - if (ctx == NULL) - return WOLFSSL_FAILURE; + if (ssl == NULL) + return BAD_FUNC_ARG; + + ssl->chGoodCb = cb; + ssl->chGoodCtx = user_ctx; - if (mode == WOLFSSL_SESS_CACHE_OFF) { - ctx->sessionCacheOff = 1; -#ifdef HAVE_EXT_CACHE - ctx->internalCacheOff = 1; - ctx->internalCacheLookupOff = 1; + return WOLFSSL_SUCCESS; +} #endif - } - if ((mode & WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR) != 0) - ctx->sessionCacheFlushOff = 1; +#ifndef NO_HANDSHAKE_DONE_CB + +int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx) +{ + WOLFSSL_ENTER("wolfSSL_SetHsDoneCb"); + + if (ssl == NULL) + return BAD_FUNC_ARG; -#ifdef HAVE_EXT_CACHE - /* WOLFSSL_SESS_CACHE_NO_INTERNAL activates both if's */ - if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE) != 0) - ctx->internalCacheOff = 1; - if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP) != 0) - ctx->internalCacheLookupOff = 1; -#endif + ssl->hsDoneCb = cb; + ssl->hsDoneCtx = user_ctx; return WOLFSSL_SUCCESS; } -#ifdef OPENSSL_EXTRA -/* Get the session cache mode for CTX - * - * ctx WOLFSSL_CTX struct to get cache mode from - * - * Returns a bit mask that has the session cache mode */ -long wolfSSL_CTX_get_session_cache_mode(WOLFSSL_CTX* ctx) +#endif /* NO_HANDSHAKE_DONE_CB */ + +WOLFSSL_ABI +int wolfSSL_Cleanup(void) { - long m = 0; + int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */ + int release = 0; +#if !defined(NO_SESSION_CACHE) + int i; + int j; +#endif - WOLFSSL_ENTER("wolfSSL_CTX_get_session_cache_mode"); + WOLFSSL_ENTER("wolfSSL_Cleanup"); - if (ctx == NULL) { - return m; +#ifndef WOLFSSL_MUTEX_INITIALIZER + if (inits_count_mutex_valid == 1) { +#endif + if (wc_LockMutex(&inits_count_mutex) != 0) { + WOLFSSL_MSG("Bad Lock Mutex count"); + return BAD_MUTEX_E; + } +#ifndef WOLFSSL_MUTEX_INITIALIZER } +#endif - if (ctx->sessionCacheOff != 1) { - m |= WOLFSSL_SESS_CACHE_SERVER; + if (initRefCount > 0) { + --initRefCount; + if (initRefCount == 0) + release = 1; } - if (ctx->sessionCacheFlushOff == 1) { - m |= WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR; +#ifndef WOLFSSL_MUTEX_INITIALIZER + if (inits_count_mutex_valid == 1) { +#endif + wc_UnLockMutex(&inits_count_mutex); +#ifndef WOLFSSL_MUTEX_INITIALIZER } +#endif -#ifdef HAVE_EXT_CACHE - if (ctx->internalCacheOff == 1) { - m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE; - } - if (ctx->internalCacheLookupOff == 1) { - m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP; - } + if (!release) + return ret; + +#ifdef OPENSSL_EXTRA + wolfSSL_BN_free_one(); #endif - return m; -} -#endif /* OPENSSL_EXTRA */ +#ifndef NO_SESSION_CACHE + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + for (i = 0; i < SESSION_ROWS; ++i) { + if ((SessionCache[i].lock_valid == 1) && + (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) { + if (ret == WOLFSSL_SUCCESS) + ret = BAD_MUTEX_E; + } + SessionCache[i].lock_valid = 0; + } + #else + if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) { + if (ret == WOLFSSL_SUCCESS) + ret = BAD_MUTEX_E; + } + session_lock_valid = 0; + #endif + for (i = 0; i < SESSION_ROWS; i++) { + for (j = 0; j < SESSIONS_PER_ROW; j++) { + #ifdef SESSION_CACHE_DYNAMIC_MEM + if (SessionCache[i].Sessions[j]) { + EvictSessionFromCache(SessionCache[i].Sessions[j]); + XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap, + DYNAMIC_TYPE_SESSION); + SessionCache[i].Sessions[j] = NULL; + } + #else + EvictSessionFromCache(&SessionCache[i].Sessions[j]); + #endif + } + } + #ifndef NO_CLIENT_CACHE + #ifndef WOLFSSL_MUTEX_INITIALIZER + if ((clisession_mutex_valid == 1) && + (wc_FreeMutex(&clisession_mutex) != 0)) { + if (ret == WOLFSSL_SUCCESS) + ret = BAD_MUTEX_E; + } + clisession_mutex_valid = 0; + #endif + #endif +#endif /* !NO_SESSION_CACHE */ -#endif /* NO_SESSION_CACHE */ +#ifndef WOLFSSL_MUTEX_INITIALIZER + if ((inits_count_mutex_valid == 1) && + (wc_FreeMutex(&inits_count_mutex) != 0)) { + if (ret == WOLFSSL_SUCCESS) + ret = BAD_MUTEX_E; + } + inits_count_mutex_valid = 0; +#endif #ifdef OPENSSL_EXTRA + wolfSSL_RAND_Cleanup(); +#endif -/* - * check if the list has TLS13 and pre-TLS13 suites - * @param list cipher suite list that user want to set - * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2 - */ -static int CheckcipherList(const char* list) -{ - int ret; - int findTLSv13Suites = 0; - int findbeforeSuites = 0; - byte cipherSuite0; - byte cipherSuite1; - int flags; - char* next = (char*)list; + if (wolfCrypt_Cleanup() != 0) { + WOLFSSL_MSG("Error with wolfCrypt_Cleanup call"); + if (ret == WOLFSSL_SUCCESS) + ret = WC_CLEANUP_E; + } - do { - char* current = next; - char name[MAX_SUITE_NAME + 1]; - word32 length = MAX_SUITE_NAME; - word32 current_length; +#if FIPS_VERSION_GE(5,1) + if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) { + if (ret == WOLFSSL_SUCCESS) + ret = WC_CLEANUP_E; + } +#endif - next = XSTRSTR(next, ":"); +#ifdef HAVE_GLOBAL_RNG +#ifndef WOLFSSL_MUTEX_INITIALIZER + if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) { + if (ret == WOLFSSL_SUCCESS) + ret = BAD_MUTEX_E; + } + globalRNGMutex_valid = 0; +#endif /* !WOLFSSL_MUTEX_INITIALIZER */ - current_length = (!next) ? (word32)XSTRLEN(current) - : (word32)(next - current); + #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG) + wolfSSL_FIPS_drbg_free(gDrbgDefCtx); + gDrbgDefCtx = NULL; + #endif +#endif - if (current_length < length) { - length = current_length; - } - XMEMCPY(name, current, length); - name[length] = 0; +#if defined(HAVE_EX_DATA) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ + defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ + defined(WOLFSSL_WPAS_SMALL) + crypto_ex_cb_free(crypto_ex_cb_ctx_session); + crypto_ex_cb_ctx_session = NULL; +#endif - if (XSTRCMP(name, "ALL") == 0 || XSTRCMP(name, "DEFAULT") == 0 || - XSTRCMP(name, "HIGH") == 0) { - findTLSv13Suites = 1; - findbeforeSuites = 1; - break; - } +#ifdef WOLFSSL_MEM_FAIL_COUNT + wc_MemFailCount_Free(); +#endif - ret = wolfSSL_get_cipher_suite_from_name(name, &cipherSuite0, - &cipherSuite1, &flags); - if (ret == 0) { - if (cipherSuite0 == TLS13_BYTE) { - /* TLSv13 suite */ - findTLSv13Suites = 1; - } - else { - findbeforeSuites = 1; - } - } + return ret; +} - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) - /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */ - if (ret != 0) { - char* subStr = name; - char* subStrNext; - do { - subStrNext = XSTRSTR(subStr, "+"); +/* call before SSL_connect, if verifying will add name check to + date check and signature check */ +WOLFSSL_ABI +int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn) +{ + WOLFSSL_ENTER("wolfSSL_check_domain_name"); - if ((XSTRCMP(subStr, "ECDHE") == 0) || - (XSTRCMP(subStr, "RSA") == 0)) { - return 0; - } + if (ssl == NULL || dn == NULL) { + WOLFSSL_MSG("Bad function argument: NULL"); + return WOLFSSL_FAILURE; + } - if (subStrNext && (XSTRLEN(subStrNext) > 0)) { - subStr = subStrNext + 1; /* +1 to skip past '+' */ - } - } while (subStrNext != NULL); - } - #endif + if (ssl->buffers.domainName.buffer) + XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN); - if (findTLSv13Suites == 1 && findbeforeSuites == 1) { - /* list has mixed suites */ - return 0; - } - } - while (next++); /* ++ needed to skip ':' */ + ssl->buffers.domainName.length = (word32)XSTRLEN(dn); + ssl->buffers.domainName.buffer = (byte*)XMALLOC( + ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN); - if (findTLSv13Suites == 0 && findbeforeSuites == 1) { - ret = 1;/* only before TLSv13 suites */ - } - else if (findTLSv13Suites == 1 && findbeforeSuites == 0) { - ret = 2;/* only TLSv13 suties */ + if (ssl->buffers.domainName.buffer) { + unsigned char* domainName = ssl->buffers.domainName.buffer; + XMEMCPY(domainName, dn, ssl->buffers.domainName.length); + domainName[ssl->buffers.domainName.length] = '\0'; + return WOLFSSL_SUCCESS; } else { - ret = 0;/* handle as mixed */ + ssl->error = MEMORY_ERROR; + return WOLFSSL_FAILURE; } - return ret; } -/* parse some bulk lists like !eNULL / !aNULL - * - * returns WOLFSSL_SUCCESS on success and sets the cipher suite list - */ -static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - Suites* suites, const char* list) + +/* turn on wolfSSL zlib compression + returns WOLFSSL_SUCCESS for success, else error (not built in) +*/ +int wolfSSL_set_compression(WOLFSSL* ssl) { - int ret = 0; - int listattribute = 0; - int tls13Only = 0; -#ifndef WOLFSSL_SMALL_STACK - byte suitesCpy[WOLFSSL_MAX_SUITE_SZ]; + WOLFSSL_ENTER("wolfSSL_set_compression"); + (void)ssl; +#ifdef HAVE_LIBZ + ssl->options.usingCompression = 1; + return WOLFSSL_SUCCESS; #else - byte* suitesCpy = NULL; + return NOT_COMPILED_IN; #endif - word16 suitesCpySz = 0; - word16 i = 0; - word16 j = 0; - - if (suites == NULL || list == NULL) { - WOLFSSL_MSG("NULL argument"); - return WOLFSSL_FAILURE; - } +} - listattribute = CheckcipherList(list); - if (listattribute == 0) { - /* list has mixed(pre-TLSv13 and TLSv13) suites - * update cipher suites the same as before - */ - return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS : - WOLFSSL_FAILURE; - } - else if (listattribute == 1) { - /* list has only pre-TLSv13 suites. - * Only update before TLSv13 suites. - */ - tls13Only = 0; - } - else if (listattribute == 2) { - /* list has only TLSv13 suites. Only update TLv13 suites - * simulate set_ciphersuites() compatibility layer API - */ - tls13Only = 1; - if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version)) || - (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) { - /* Silently ignore TLS 1.3 ciphers if we don't support it. */ - return WOLFSSL_SUCCESS; - } - } +#ifndef USE_WINDOWS_API + #ifndef NO_WRITEV - /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */ - if (suites->suiteSz == 0) { - WOLFSSL_MSG("Warning suites->suiteSz = 0 set to WOLFSSL_MAX_SUITE_SZ"); - suites->suiteSz = WOLFSSL_MAX_SUITE_SZ; - } -#ifdef WOLFSSL_SMALL_STACK - if (suites->suiteSz > 0) { - suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (suitesCpy == NULL) { - return WOLFSSL_FAILURE; - } + /* simulate writev semantics, doesn't actually do block at a time though + because of SSL_write behavior and because front adds may be small */ + int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt) + { + #ifdef WOLFSSL_SMALL_STACK + byte staticBuffer[1]; /* force heap usage */ + #else + byte staticBuffer[FILE_BUFFER_SIZE]; + #endif + byte* myBuffer = staticBuffer; + int dynamic = 0; + int sending = 0; + int idx = 0; + int i; + int ret; - XMEMSET(suitesCpy, 0, suites->suiteSz); - } -#else - XMEMSET(suitesCpy, 0, sizeof(suitesCpy)); -#endif + WOLFSSL_ENTER("wolfSSL_writev"); - if (suites->suiteSz > 0) - XMEMCPY(suitesCpy, suites->suites, suites->suiteSz); - suitesCpySz = suites->suiteSz; + for (i = 0; i < iovcnt; i++) + sending += (int)iov[i].iov_len; - ret = SetCipherList_ex(ctx, ssl, suites, list); - if (ret != 1) { -#ifdef WOLFSSL_SMALL_STACK - XFREE(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return WOLFSSL_FAILURE; - } + if (sending > (int)sizeof(staticBuffer)) { + myBuffer = (byte*)XMALLOC(sending, ssl->heap, + DYNAMIC_TYPE_WRITEV); + if (!myBuffer) + return MEMORY_ERROR; - for (i = 0; i < suitesCpySz && - suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) { - /* Check for duplicates */ - int duplicate = 0; - for (j = 0; j < suites->suiteSz; j += 2) { - if (suitesCpy[i] == suites->suites[j] && - suitesCpy[i+1] == suites->suites[j+1]) { - duplicate = 1; - break; - } - } - if (!duplicate) { - if (tls13Only) { - /* Updating TLS 1.3 ciphers */ - if (suitesCpy[i] != TLS13_BYTE) { - /* Only copy over <= TLS 1.2 ciphers */ - /* TLS 1.3 ciphers take precedence */ - suites->suites[suites->suiteSz++] = suitesCpy[i]; - suites->suites[suites->suiteSz++] = suitesCpy[i+1]; - } - } - else { - /* Updating <= TLS 1.2 ciphers */ - if (suitesCpy[i] == TLS13_BYTE) { - /* Only copy over TLS 1.3 ciphers */ - /* TLS 1.3 ciphers take precedence */ - XMEMMOVE(suites->suites + SUITE_LEN, suites->suites, - suites->suiteSz); - suites->suites[0] = suitesCpy[i]; - suites->suites[1] = suitesCpy[i+1]; - suites->suiteSz += 2; - } + dynamic = 1; } - } - } - -#ifdef WOLFSSL_SMALL_STACK - XFREE(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return ret; -} - -#endif - -int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list"); + for (i = 0; i < iovcnt; i++) { + XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len); + idx += (int)iov[i].iov_len; + } - if (ctx == NULL) - return WOLFSSL_FAILURE; + /* myBuffer may not be initialized fully, but the span up to the + * sending length will be. + */ + PRAGMA_GCC_DIAG_PUSH + PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") + ret = wolfSSL_write(ssl, myBuffer, sending); + PRAGMA_GCC_DIAG_POP - if (AllocateCtxSuites(ctx) != 0) - return WOLFSSL_FAILURE; + if (dynamic) + XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV); -#ifdef OPENSSL_EXTRA - return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list); -#else - return (SetCipherList(ctx, ctx->suites, list)) ? - WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + return ret; + } + #endif #endif -} -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES) -int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list, - const int listSz) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes"); - if (ctx == NULL) - return WOLFSSL_FAILURE; +#ifdef WOLFSSL_CALLBACKS - if (AllocateCtxSuites(ctx) != 0) - return WOLFSSL_FAILURE; + typedef struct itimerval Itimerval; - return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ? - WOLFSSL_SUCCESS : WOLFSSL_FAILURE; -} -#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */ + /* don't keep calling simple functions while setting up timer and signals + if no inlining these are the next best */ -int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list) -{ - WOLFSSL_ENTER("wolfSSL_set_cipher_list"); + #define AddTimes(a, b, c) \ + do { \ + (c).tv_sec = (a).tv_sec + (b).tv_sec; \ + (c).tv_usec = (a).tv_usec + (b).tv_usec;\ + if ((c).tv_usec >= 1000000) { \ + (c).tv_sec++; \ + (c).tv_usec -= 1000000; \ + } \ + } while (0) - if (ssl == NULL || ssl->ctx == NULL) { - return WOLFSSL_FAILURE; - } - if (AllocateSuites(ssl) != 0) - return WOLFSSL_FAILURE; + #define SubtractTimes(a, b, c) \ + do { \ + (c).tv_sec = (a).tv_sec - (b).tv_sec; \ + (c).tv_usec = (a).tv_usec - (b).tv_usec;\ + if ((c).tv_usec < 0) { \ + (c).tv_sec--; \ + (c).tv_usec += 1000000; \ + } \ + } while (0) -#ifdef OPENSSL_EXTRA - return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list); -#else - return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ? - WOLFSSL_SUCCESS : - WOLFSSL_FAILURE; -#endif -} + #define CmpTimes(a, b, cmp) \ + (((a).tv_sec == (b).tv_sec) ? \ + ((a).tv_usec cmp (b).tv_usec) : \ + ((a).tv_sec cmp (b).tv_sec)) \ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES) -int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list, - const int listSz) -{ - WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes"); - if (ssl == NULL || ssl->ctx == NULL) { - return WOLFSSL_FAILURE; + /* do nothing handler */ + static void myHandler(int signo) + { + (void)signo; + return; } - if (AllocateSuites(ssl) != 0) - return WOLFSSL_FAILURE; - return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz)) - ? WOLFSSL_SUCCESS - : WOLFSSL_FAILURE; -} -#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */ + static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb, + TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) + { + int ret = WOLFSSL_FATAL_ERROR; + int oldTimerOn = 0; /* was timer already on */ + WOLFSSL_TIMEVAL startTime; + WOLFSSL_TIMEVAL endTime; + WOLFSSL_TIMEVAL totalTime; + Itimerval myTimeout; + Itimerval oldTimeout; /* if old timer adjust from total time to reset */ + struct sigaction act, oact; + #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; } -#ifdef HAVE_KEYING_MATERIAL + if (hsCb) { + ssl->hsInfoOn = 1; + InitHandShakeInfo(&ssl->handShakeInfo, ssl); + } + if (toCb) { + ssl->toInfoOn = 1; + InitTimeoutInfo(&ssl->timeoutInfo); -#define TLS_PRF_LABEL_CLIENT_FINISHED "client finished" -#define TLS_PRF_LABEL_SERVER_FINISHED "server finished" -#define TLS_PRF_LABEL_MASTER_SECRET "master secret" -#define TLS_PRF_LABEL_EXT_MASTER_SECRET "extended master secret" -#define TLS_PRF_LABEL_KEY_EXPANSION "key expansion" + if (gettimeofday(&startTime, 0) < 0) + ERR_OUT(GETTIME_ERROR); -static const struct ForbiddenLabels { - const char* label; - size_t labelLen; -} forbiddenLabels[] = { - {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)}, - {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)}, - {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)}, - {TLS_PRF_LABEL_EXT_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)}, - {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)}, - {NULL, 0}, -}; + /* use setitimer to simulate getitimer, init 0 myTimeout */ + myTimeout.it_interval.tv_sec = 0; + myTimeout.it_interval.tv_usec = 0; + myTimeout.it_value.tv_sec = 0; + myTimeout.it_value.tv_usec = 0; + if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0) + ERR_OUT(SETITIMER_ERROR); -/** - * Implement RFC 5705 - * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446) - * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error - */ -int wolfSSL_export_keying_material(WOLFSSL *ssl, - unsigned char *out, size_t outLen, - const char *label, size_t labelLen, - const unsigned char *context, size_t contextLen, - int use_context) -{ - byte* seed = NULL; - word32 seedLen; - const struct ForbiddenLabels* fl; + if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) { + oldTimerOn = 1; - WOLFSSL_ENTER("wolfSSL_export_keying_material"); + /* is old timer going to expire before ours */ + if (CmpTimes(oldTimeout.it_value, timeout, <)) { + timeout.tv_sec = oldTimeout.it_value.tv_sec; + timeout.tv_usec = oldTimeout.it_value.tv_usec; + } + } + myTimeout.it_value.tv_sec = timeout.tv_sec; + myTimeout.it_value.tv_usec = timeout.tv_usec; - if (ssl == NULL || out == NULL || label == NULL || - (use_context && contextLen && context == NULL)) { - WOLFSSL_MSG("Bad argument"); - return WOLFSSL_FAILURE; - } + /* set up signal handler, don't restart socket send/recv */ + act.sa_handler = myHandler; + sigemptyset(&act.sa_mask); + act.sa_flags = 0; +#ifdef SA_INTERRUPT + act.sa_flags |= SA_INTERRUPT; +#endif + if (sigaction(SIGALRM, &act, &oact) < 0) + ERR_OUT(SIGACT_ERROR); - /* clientRandom + serverRandom - * OR - * clientRandom + serverRandom + ctx len encoding + ctx */ - seedLen = !use_context ? (word32)SEED_LEN : - (word32)SEED_LEN + 2 + (word32)contextLen; + if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0) + ERR_OUT(SETITIMER_ERROR); + } - if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) { - WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake " - "data. Call wolfSSL_KeepArrays before attempting to " - "export keyid material."); - return WOLFSSL_FAILURE; - } + /* do main work */ +#ifndef NO_WOLFSSL_CLIENT + if (ssl->options.side == WOLFSSL_CLIENT_END) + ret = wolfSSL_connect(ssl); +#endif +#ifndef NO_WOLFSSL_SERVER + if (ssl->options.side == WOLFSSL_SERVER_END) + ret = wolfSSL_accept(ssl); +#endif - /* check forbidden labels */ - for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) { - if (labelLen >= fl->labelLen && - XMEMCMP(label, fl->label, fl->labelLen) == 0) { - WOLFSSL_MSG("Forbidden label"); - return WOLFSSL_FAILURE; - } - } + /* do callbacks */ + if (toCb) { + if (oldTimerOn) { + if (gettimeofday(&endTime, 0) < 0) + ERR_OUT(SYSLIB_FAILED_E); + SubtractTimes(endTime, startTime, totalTime); + /* adjust old timer for elapsed time */ + if (CmpTimes(totalTime, oldTimeout.it_value, <)) + SubtractTimes(oldTimeout.it_value, totalTime, + oldTimeout.it_value); + else { + /* reset value to interval, may be off */ + oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec; + oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec; + } + /* keep iter the same whether there or not */ + } + /* restore old handler */ + if (sigaction(SIGALRM, &oact, 0) < 0) + ret = SIGACT_ERROR; /* more pressing error, stomp */ + else + /* use old settings which may turn off (expired or not there) */ + if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0) + ret = SETITIMER_ERROR; -#ifdef WOLFSSL_TLS13 - if (IsAtLeastTLSv1_3(ssl->version)) { - /* Path for TLS 1.3 */ - if (!use_context) { - contextLen = 0; - context = (byte*)""; /* Give valid pointer for 0 length memcpy */ + /* if we had a timeout call callback */ + if (ssl->timeoutInfo.timeoutName[0]) { + ssl->timeoutInfo.timeoutValue.tv_sec = timeout.tv_sec; + ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec; + (toCb)(&ssl->timeoutInfo); + } + ssl->toInfoOn = 0; } - if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen, - context, contextLen) != 0) { - WOLFSSL_MSG("Tls13_Exporter error"); - return WOLFSSL_FAILURE; + /* clean up buffers allocated by AddPacketInfo */ + FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap); + + if (hsCb) { + FinishHandShakeInfo(&ssl->handShakeInfo); + (hsCb)(&ssl->handShakeInfo); + ssl->hsInfoOn = 0; } - return WOLFSSL_SUCCESS; + return ret; } -#endif - /* Path for <=TLS 1.2 */ - seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (seed == NULL) { - WOLFSSL_MSG("malloc error"); - return WOLFSSL_FAILURE; - } - XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN); - XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN); +#ifndef NO_WOLFSSL_CLIENT - if (use_context) { - /* Encode len in big endian */ - seed[SEED_LEN ] = (contextLen >> 8) & 0xFF; - seed[SEED_LEN + 1] = (contextLen) & 0xFF; - if (contextLen) { - /* 0 length context is allowed */ - XMEMCPY(seed + SEED_LEN + 2, context, contextLen); - } + int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb, + TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) + { + WOLFSSL_ENTER("wolfSSL_connect_ex"); + return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout); } - PRIVATE_KEY_UNLOCK(); - if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN, - (byte*)label, (word32)labelLen, seed, seedLen, IsAtLeastTLSv1_2(ssl), - ssl->specs.mac_algorithm, ssl->heap, ssl->devId) != 0) { - WOLFSSL_MSG("wc_PRF_TLS error"); - PRIVATE_KEY_LOCK(); - XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_FAILURE; - } - PRIVATE_KEY_LOCK(); +#endif - XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_SUCCESS; -} -#endif /* HAVE_KEYING_MATERIAL */ -int wolfSSL_dtls_get_using_nonblock(WOLFSSL* ssl) -{ - int useNb = 0; +#ifndef NO_WOLFSSL_SERVER - if (ssl == NULL) - return WOLFSSL_FAILURE; + int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb, + TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) + { + WOLFSSL_ENTER("wolfSSL_accept_ex"); + return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout); + } - WOLFSSL_ENTER("wolfSSL_dtls_get_using_nonblock"); - if (ssl->options.dtls) { -#ifdef WOLFSSL_DTLS - useNb = ssl->options.dtlsUseNonblock; #endif - } - else { - WOLFSSL_MSG("wolfSSL_dtls_get_using_nonblock() is " - "DEPRECATED for non-DTLS use."); - } - return useNb; -} +#endif /* WOLFSSL_CALLBACKS */ -#ifndef WOLFSSL_LEANPSK -void wolfSSL_dtls_set_using_nonblock(WOLFSSL* ssl, int nonblock) -{ - (void)nonblock; +#ifndef NO_PSK - WOLFSSL_ENTER("wolfSSL_dtls_set_using_nonblock"); + void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx, + wc_psk_client_callback cb) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback"); - if (ssl == NULL) - return; + if (ctx == NULL) + return; - if (ssl->options.dtls) { -#ifdef WOLFSSL_DTLS - ssl->options.dtlsUseNonblock = (nonblock != 0); -#endif - } - else { - WOLFSSL_MSG("wolfSSL_dtls_set_using_nonblock() is " - "DEPRECATED for non-DTLS use."); + ctx->havePSK = 1; + ctx->client_psk_cb = cb; } -} + void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb) + { + byte haveRSA = 1; + int keySz = 0; -#ifdef WOLFSSL_DTLS + WOLFSSL_ENTER("wolfSSL_set_psk_client_callback"); -int wolfSSL_dtls_get_current_timeout(WOLFSSL* ssl) -{ - int timeout = 0; - if (ssl) - timeout = ssl->dtls_timeout; - - WOLFSSL_LEAVE("wolfSSL_dtls_get_current_timeout", timeout); - return timeout; -} - -#ifdef WOLFSSL_DTLS13 - -/* - * This API returns 1 when the user should set a short timeout for receiving - * data. It is recommended that it is at most 1/4 the value returned by - * wolfSSL_dtls_get_current_timeout(). - */ -int wolfSSL_dtls13_use_quick_timeout(WOLFSSL* ssl) -{ - return ssl->dtls13FastTimeout; -} + if (ssl == NULL) + return; -/* - * When this is set, a DTLS 1.3 connection will send acks immediately when a - * disruption is detected to shortcut timeouts. This results in potentially - * more traffic but may make the handshake quicker. - */ -void wolfSSL_dtls13_set_send_more_acks(WOLFSSL* ssl, int value) -{ - if (ssl != NULL) - ssl->options.dtls13SendMoreAcks = !!value; -} -#endif /* WOLFSSL_DTLS13 */ + ssl->options.havePSK = 1; + ssl->options.client_psk_cb = cb; -int wolfSSL_DTLSv1_get_timeout(WOLFSSL* ssl, WOLFSSL_TIMEVAL* timeleft) -{ - if (ssl && timeleft) { - XMEMSET(timeleft, 0, sizeof(WOLFSSL_TIMEVAL)); - timeleft->tv_sec = ssl->dtls_timeout; + #ifdef NO_RSA + haveRSA = 0; + #endif + #ifndef NO_CERTS + keySz = ssl->buffers.keySz; + #endif + if (AllocateSuites(ssl) != 0) + return; + InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, + ssl->options.haveDH, ssl->options.haveECDSAsig, + ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, + ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, + ssl->options.useAnon, TRUE, ssl->options.side); } - return 0; -} - -#ifndef NO_WOLFSSL_STUB -int wolfSSL_DTLSv1_handle_timeout(WOLFSSL* ssl) -{ - WOLFSSL_STUB("SSL_DTLSv1_handle_timeout"); - (void)ssl; - return 0; -} -#endif - -#ifndef NO_WOLFSSL_STUB -void wolfSSL_DTLSv1_set_initial_timeout_duration(WOLFSSL* ssl, word32 duration_ms) -{ - WOLFSSL_STUB("SSL_DTLSv1_set_initial_timeout_duration"); - (void)ssl; - (void)duration_ms; -} -#endif + #ifdef OPENSSL_EXTRA + /** + * set call back function for psk session use + * @param ssl a pointer to WOLFSSL structure + * @param cb a function pointer to wc_psk_use_session_cb + * @return none + */ + void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl, + wc_psk_use_session_cb_func cb) + { + WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback"); -/* user may need to alter init dtls recv timeout, WOLFSSL_SUCCESS on ok */ -int wolfSSL_dtls_set_timeout_init(WOLFSSL* ssl, int timeout) -{ - if (ssl == NULL || timeout < 0) - return BAD_FUNC_ARG; + if (ssl != NULL) { + ssl->options.havePSK = 1; + ssl->options.session_psk_cb = cb; + } - if (timeout > ssl->dtls_timeout_max) { - WOLFSSL_MSG("Can't set dtls timeout init greater than dtls timeout max"); - return BAD_FUNC_ARG; + WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS); } + #endif - ssl->dtls_timeout_init = timeout; - ssl->dtls_timeout = timeout; + void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx, + wc_psk_server_callback cb) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback"); + if (ctx == NULL) + return; + ctx->havePSK = 1; + ctx->server_psk_cb = cb; + } - return WOLFSSL_SUCCESS; -} + void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb) + { + byte haveRSA = 1; + int keySz = 0; + WOLFSSL_ENTER("wolfSSL_set_psk_server_callback"); + if (ssl == NULL) + return; -/* user may need to alter max dtls recv timeout, WOLFSSL_SUCCESS on ok */ -int wolfSSL_dtls_set_timeout_max(WOLFSSL* ssl, int timeout) -{ - if (ssl == NULL || timeout < 0) - return BAD_FUNC_ARG; + ssl->options.havePSK = 1; + ssl->options.server_psk_cb = cb; - if (timeout < ssl->dtls_timeout_init) { - WOLFSSL_MSG("Can't set dtls timeout max less than dtls timeout init"); - return BAD_FUNC_ARG; + #ifdef NO_RSA + haveRSA = 0; + #endif + #ifndef NO_CERTS + keySz = ssl->buffers.keySz; + #endif + if (AllocateSuites(ssl) != 0) + return; + InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, + ssl->options.haveDH, ssl->options.haveECDSAsig, + ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, + ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, + ssl->options.useAnon, TRUE, ssl->options.side); } - ssl->dtls_timeout_max = timeout; + const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl) + { + WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint"); - return WOLFSSL_SUCCESS; -} + if (ssl == NULL || ssl->arrays == NULL) + return NULL; + return ssl->arrays->server_hint; + } -int wolfSSL_dtls_got_timeout(WOLFSSL* ssl) -{ - int result = WOLFSSL_SUCCESS; - WOLFSSL_ENTER("wolfSSL_dtls_got_timeout"); - if (ssl == NULL) - return WOLFSSL_FATAL_ERROR; + const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl) + { + WOLFSSL_ENTER("wolfSSL_get_psk_identity"); -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { - result = Dtls13RtxTimeout(ssl); - if (result < 0) { - if (result == WANT_WRITE) - ssl->dtls13SendingAckOrRtx = 1; - ssl->error = result; - WOLFSSL_ERROR(result); - return WOLFSSL_FATAL_ERROR; - } + if (ssl == NULL || ssl->arrays == NULL) + return NULL; - return WOLFSSL_SUCCESS; + return ssl->arrays->client_identity; } -#endif /* WOLFSSL_DTLS13 */ - if ((IsSCR(ssl) || !ssl->options.handShakeDone)) { - if (DtlsMsgPoolTimeout(ssl) < 0){ - ssl->error = SOCKET_ERROR_E; - WOLFSSL_ERROR(ssl->error); - result = WOLFSSL_FATAL_ERROR; - } - else if ((result = DtlsMsgPoolSend(ssl, 0)) < 0) { - ssl->error = result; - WOLFSSL_ERROR(result); - result = WOLFSSL_FATAL_ERROR; - } + int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint) + { + WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint"); + if (hint == 0) + ctx->server_hint[0] = '\0'; else { - /* Reset return value to success */ - result = WOLFSSL_SUCCESS; + /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */ + #ifdef WOLFSSL_QT + ctx->havePSK=1; + #endif + XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN); + ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */ } + return WOLFSSL_SUCCESS; } - WOLFSSL_LEAVE("wolfSSL_dtls_got_timeout", result); - return result; -} - - -/* retransmit all the saves messages, WOLFSSL_SUCCESS on ok */ -int wolfSSL_dtls_retransmit(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_dtls_retransmit"); + int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint) + { + WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint"); - if (ssl == NULL) - return WOLFSSL_FATAL_ERROR; + if (ssl == NULL || ssl->arrays == NULL) + return WOLFSSL_FAILURE; - if (!ssl->options.handShakeDone) { - int result = DtlsMsgPoolSend(ssl, 0); - if (result < 0) { - ssl->error = result; - WOLFSSL_ERROR(result); - return WOLFSSL_FATAL_ERROR; + if (hint == 0) + ssl->arrays->server_hint[0] = 0; + else { + XSTRNCPY(ssl->arrays->server_hint, hint, + sizeof(ssl->arrays->server_hint)-1); + ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0'; } + return WOLFSSL_SUCCESS; } - return 0; -} + void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl) + { + return ssl ? ssl->options.psk_ctx : NULL; + } + void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx) + { + return ctx ? ctx->psk_ctx : NULL; + } + int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx) + { + if (ssl == NULL) + return WOLFSSL_FAILURE; + ssl->options.psk_ctx = psk_ctx; + return WOLFSSL_SUCCESS; + } + int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx) + { + if (ctx == NULL) + return WOLFSSL_FAILURE; + ctx->psk_ctx = psk_ctx; + return WOLFSSL_SUCCESS; + } +#endif /* NO_PSK */ -#endif /* DTLS */ -#endif /* LEANPSK */ +#ifdef HAVE_ANON -#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) + int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx) + { + WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher"); -/* Not an SSL function, return 0 for success, error code otherwise */ -/* Prereq: ssl's RNG needs to be initialized. */ -int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, - const byte* secret, word32 secretSz) -{ - int ret = 0; + if (ctx == NULL) + return WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_DTLS_SetCookieSecret"); + ctx->useAnon = 1; - if (ssl == NULL) { - WOLFSSL_MSG("need a SSL object"); - return BAD_FUNC_ARG; + return WOLFSSL_SUCCESS; } - if (secret != NULL && secretSz == 0) { - WOLFSSL_MSG("can't have a new secret without a size"); - return BAD_FUNC_ARG; - } +#endif /* HAVE_ANON */ - /* If secretSz is 0, use the default size. */ - if (secretSz == 0) - secretSz = COOKIE_SECRET_SZ; +#ifndef NO_CERTS - if (secretSz != ssl->buffers.dtlsCookieSecret.length) { - byte* newSecret; + /* unload any certs or keys that SSL owns, leave CTX as is + WOLFSSL_SUCCESS on ok */ + int wolfSSL_UnloadCertsKeys(WOLFSSL* ssl) + { + if (ssl == NULL) { + WOLFSSL_MSG("Null function arg"); + return BAD_FUNC_ARG; + } - if (ssl->buffers.dtlsCookieSecret.buffer != NULL) { - ForceZero(ssl->buffers.dtlsCookieSecret.buffer, - ssl->buffers.dtlsCookieSecret.length); - XFREE(ssl->buffers.dtlsCookieSecret.buffer, - ssl->heap, DYNAMIC_TYPE_COOKIE_PWD); + if (ssl->buffers.weOwnCert && !ssl->keepCert) { + WOLFSSL_MSG("Unloading cert"); + FreeDer(&ssl->buffers.certificate); + #ifdef KEEP_OUR_CERT + wolfSSL_X509_free(ssl->ourCert); + ssl->ourCert = NULL; + #endif + ssl->buffers.weOwnCert = 0; } - newSecret = (byte*)XMALLOC(secretSz, ssl->heap,DYNAMIC_TYPE_COOKIE_PWD); - if (newSecret == NULL) { - ssl->buffers.dtlsCookieSecret.buffer = NULL; - ssl->buffers.dtlsCookieSecret.length = 0; - WOLFSSL_MSG("couldn't allocate new cookie secret"); - return MEMORY_ERROR; + if (ssl->buffers.weOwnCertChain) { + WOLFSSL_MSG("Unloading cert chain"); + FreeDer(&ssl->buffers.certChain); + ssl->buffers.weOwnCertChain = 0; } - ssl->buffers.dtlsCookieSecret.buffer = newSecret; - ssl->buffers.dtlsCookieSecret.length = secretSz; - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("wolfSSL_DTLS_SetCookieSecret secret", - ssl->buffers.dtlsCookieSecret.buffer, - ssl->buffers.dtlsCookieSecret.length); - #endif - } - /* If the supplied secret is NULL, randomly generate a new secret. */ - if (secret == NULL) { - ret = wc_RNG_GenerateBlock(ssl->rng, - ssl->buffers.dtlsCookieSecret.buffer, secretSz); - } - else - XMEMCPY(ssl->buffers.dtlsCookieSecret.buffer, secret, secretSz); + if (ssl->buffers.weOwnKey) { + WOLFSSL_MSG("Unloading key"); + ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length); + FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif + ssl->buffers.weOwnKey = 0; + } - WOLFSSL_LEAVE("wolfSSL_DTLS_SetCookieSecret", 0); - return ret; -} +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->buffers.weOwnAltKey) { + WOLFSSL_MSG("Unloading alt key"); + ForceZero(ssl->buffers.altKey->buffer, ssl->buffers.altKey->length); + FreeDer(&ssl->buffers.altKey); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.altKeyMask); + #endif + ssl->buffers.weOwnAltKey = 0; + } +#endif /* WOLFSSL_DUAL_ALG_CERTS */ -#endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */ + return WOLFSSL_SUCCESS; + } -/* EITHER SIDE METHODS */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) - WOLFSSL_METHOD* wolfSSLv23_method(void) + int wolfSSL_CTX_UnloadCAs(WOLFSSL_CTX* ctx) { - return wolfSSLv23_method_ex(NULL); + WOLFSSL_ENTER("wolfSSL_CTX_UnloadCAs"); + + if (ctx == NULL) + return BAD_FUNC_ARG; + + return wolfSSL_CertManagerUnloadCAs(ctx->cm); } - WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap) + + int wolfSSL_CTX_UnloadIntermediateCerts(WOLFSSL_CTX* ctx) { - WOLFSSL_METHOD* m = NULL; - WOLFSSL_ENTER("wolfSSLv23_method"); - #if !defined(NO_WOLFSSL_CLIENT) - m = wolfSSLv23_client_method_ex(heap); - #elif !defined(NO_WOLFSSL_SERVER) - m = wolfSSLv23_server_method_ex(heap); - #else - (void)heap; - #endif - if (m != NULL) { - m->side = WOLFSSL_NEITHER_END; + WOLFSSL_ENTER("wolfSSL_CTX_UnloadIntermediateCerts"); + + if (ctx == NULL) + return BAD_FUNC_ARG; + + if (ctx->ref.count > 1) { + WOLFSSL_MSG("ctx object must have a ref count of 1 before " + "unloading intermediate certs"); + return BAD_STATE_E; } - return m; + return wolfSSL_CertManagerUnloadIntermediateCerts(ctx->cm); } - #ifdef WOLFSSL_ALLOW_SSLV3 - WOLFSSL_METHOD* wolfSSLv3_method(void) + +#ifdef WOLFSSL_TRUST_PEER_CERT + int wolfSSL_CTX_Unload_trust_peers(WOLFSSL_CTX* ctx) { - return wolfSSLv3_method_ex(NULL); + WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers"); + + if (ctx == NULL) + return BAD_FUNC_ARG; + + return wolfSSL_CertManagerUnload_trust_peers(ctx->cm); } - WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap) + +#ifdef WOLFSSL_LOCAL_X509_STORE + int wolfSSL_Unload_trust_peers(WOLFSSL* ssl) { - WOLFSSL_METHOD* m = NULL; - WOLFSSL_ENTER("wolfSSLv3_method_ex"); - #if !defined(NO_WOLFSSL_CLIENT) - m = wolfSSLv3_client_method_ex(heap); - #elif !defined(NO_WOLFSSL_SERVER) - m = wolfSSLv3_server_method_ex(heap); - #endif - if (m != NULL) { - m->side = WOLFSSL_NEITHER_END; - } + WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers"); - return m; + if (ssl == NULL) + return BAD_FUNC_ARG; + + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerUnload_trust_peers(SSL_CM(ssl)); } - #endif -#endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ +#endif /* WOLFSSL_LOCAL_X509_STORE */ +#endif /* WOLFSSL_TRUST_PEER_CERT */ +/* old NO_FILESYSTEM end */ +#endif /* !NO_CERTS */ -/* client only parts */ -#ifndef NO_WOLFSSL_CLIENT - #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) - WOLFSSL_METHOD* wolfSSLv2_client_method(void) - { - WOLFSSL_STUB("wolfSSLv2_client_method"); - return NULL; - } - #endif +#ifdef OPENSSL_EXTRA - #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) - WOLFSSL_METHOD* wolfSSLv3_client_method(void) + int wolfSSL_add_all_algorithms(void) { - return wolfSSLv3_client_method_ex(NULL); + WOLFSSL_ENTER("wolfSSL_add_all_algorithms"); + if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS) + return WOLFSSL_SUCCESS; + else + return WOLFSSL_FATAL_ERROR; } - WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap) + + int wolfSSL_OpenSSL_add_all_algorithms_noconf(void) { - WOLFSSL_METHOD* method = - (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), - heap, DYNAMIC_TYPE_METHOD); - (void)heap; - WOLFSSL_ENTER("wolfSSLv3_client_method_ex"); - if (method) - InitSSL_Method(method, MakeSSLv3()); - return method; - } - #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */ + WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf"); + if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) + return WOLFSSL_FATAL_ERROR; - WOLFSSL_METHOD* wolfSSLv23_client_method(void) - { - return wolfSSLv23_client_method_ex(NULL); + return WOLFSSL_SUCCESS; } - WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap) + + int wolfSSL_OpenSSL_add_all_algorithms_conf(void) { - WOLFSSL_METHOD* method = - (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), - heap, DYNAMIC_TYPE_METHOD); - (void)heap; - WOLFSSL_ENTER("wolfSSLv23_client_method_ex"); - if (method) { - #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) - #if defined(WOLFSSL_TLS13) - InitSSL_Method(method, MakeTLSv1_3()); - #elif !defined(WOLFSSL_NO_TLS12) - InitSSL_Method(method, MakeTLSv1_2()); - #elif !defined(NO_OLD_TLS) - InitSSL_Method(method, MakeTLSv1_1()); - #endif - #else - #ifndef NO_OLD_TLS - InitSSL_Method(method, MakeTLSv1_1()); - #endif - #endif - #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13) - method->downgrade = 1; - #endif + WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf"); + /* This function is currently the same as + wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ + the use of a wolfssl.cnf type configuration file and is only used for + OpenSSL compatibility. */ + + if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) { + return WOLFSSL_FATAL_ERROR; } - return method; + return WOLFSSL_SUCCESS; } - /* please see note at top of README if you get an error from connect */ - WOLFSSL_ABI - int wolfSSL_connect(WOLFSSL* ssl) - { - #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)) - int neededState; - byte advanceState; - #endif - int ret = 0; - - (void)ret; +#endif - #ifdef HAVE_ERRNO_H - errno = 0; - #endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) + void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown"); + if (mode) + ctx->quietShutdown = 1; + } - if (ssl == NULL) - return BAD_FUNC_ARG; - #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) - if (ssl->options.side == WOLFSSL_NEITHER_END) { - ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END); - if (ssl->error != WOLFSSL_SUCCESS) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->error = 0; /* expected to be zero here */ - } + void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode) + { + WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown"); + if (mode) + ssl->options.quietShutdown = 1; + } +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || + WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - #ifdef OPENSSL_EXTRA - if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_ST_CONNECT, WOLFSSL_SUCCESS); - ssl->cbmode = SSL_CB_WRITE; +#ifdef OPENSSL_EXTRA +#ifndef NO_BIO + void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr) + { + WOLFSSL_ENTER("wolfSSL_set_bio"); + + if (ssl == NULL) { + WOLFSSL_MSG("Bad argument, ssl was NULL"); + return; } - #endif - #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ - #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13) - return wolfSSL_connect_TLSv13(ssl); - #else - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) { - WOLFSSL_MSG("TLS 1.3"); - return wolfSSL_connect_TLSv13(ssl); + /* free any existing WOLFSSL_BIOs in use but don't free those in + * a chain */ + if (ssl->biord != NULL) { + if (ssl->biord != ssl->biowr) { + if (ssl->biowr != NULL && ssl->biowr->prev != NULL) + wolfSSL_BIO_free(ssl->biowr); + ssl->biowr = NULL; + } + if (ssl->biord->prev != NULL) + wolfSSL_BIO_free(ssl->biord); + ssl->biord = NULL; } - #endif + /* set flag obviously */ + if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ)) + rd->flags |= WOLFSSL_BIO_FLAG_READ; + if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE)) + wr->flags |= WOLFSSL_BIO_FLAG_WRITE; - WOLFSSL_MSG("TLS 1.2 or lower"); - WOLFSSL_ENTER("wolfSSL_connect"); + ssl->biord = rd; + ssl->biowr = wr; - /* make sure this wolfSSL object has arrays and rng setup. Protects - * case where the WOLFSSL object is reused via wolfSSL_clear() */ - if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { - return ret; + /* set SSL to use BIO callbacks instead */ + if (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)) { + ssl->CBIORecv = BioReceive; } - -#ifdef WOLFSSL_WOLFSENTRY_HOOKS - if ((ssl->ConnectFilter != NULL) && - (ssl->options.connectState == CONNECT_BEGIN)) { - wolfSSL_netfilter_decision_t res; - if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) == - WOLFSSL_SUCCESS) && - (res == WOLFSSL_NETFILTER_REJECT)) { - ssl->error = SOCKET_FILTERED_E; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } + if (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)) { + ssl->CBIOSend = BioSend; } -#endif /* WOLFSSL_WOLFSENTRY_HOOKS */ - if (ssl->options.side != WOLFSSL_CLIENT_END) { - ssl->error = SIDE_ERROR; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; + /* User programs should always retry reading from these BIOs */ + if (rd) { + /* User writes to rd */ + BIO_set_retry_write(rd); + } + if (wr) { + /* User reads from wr */ + BIO_set_retry_read(wr); } + } +#endif /* !NO_BIO */ +#endif /* OPENSSL_EXTRA */ - #ifdef WOLFSSL_DTLS - if (ssl->version.major == DTLS_MAJOR) { - ssl->options.dtls = 1; - ssl->options.tls = 1; - ssl->options.tls1_1 = 1; - ssl->options.dtlsStateful = 1; +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) + void wolfSSL_CTX_set_client_CA_list(WOLFSSL_CTX* ctx, + WOLF_STACK_OF(WOLFSSL_X509_NAME)* names) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_client_CA_list"); + if (ctx != NULL) { + wolfSSL_sk_X509_NAME_pop_free(ctx->client_ca_names, NULL); + ctx->client_ca_names = names; } - #endif + } - /* fragOffset is non-zero when sending fragments. On the last - * fragment, fragOffset is zero again, and the state can be - * advanced. */ - advanceState = ssl->fragOffset == 0 && - (ssl->options.connectState == CONNECT_BEGIN || - ssl->options.connectState == HELLO_AGAIN || - (ssl->options.connectState >= FIRST_REPLY_DONE && - ssl->options.connectState <= FIRST_REPLY_FOURTH)); + void wolfSSL_set_client_CA_list(WOLFSSL* ssl, + WOLF_STACK_OF(WOLFSSL_X509_NAME)* names) + { + WOLFSSL_ENTER("wolfSSL_set_client_CA_list"); + if (ssl != NULL) { + if (ssl->client_ca_names != ssl->ctx->client_ca_names) + wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL); + ssl->client_ca_names = names; + } + } -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) - advanceState = advanceState && !ssl->dtls13SendingAckOrRtx; -#endif /* WOLFSSL_DTLS13 */ + #ifdef OPENSSL_EXTRA + /* registers client cert callback, called during handshake if server + requests client auth but user has not loaded client cert/key */ + void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb"); - if (ssl->buffers.outputBuffer.length > 0 - #ifdef WOLFSSL_ASYNC_CRYPT - /* do not send buffered or advance state if last error was an - async pending operation */ - && ssl->error != WC_PENDING_E - #endif - ) { - ret = SendBuffered(ssl); - if (ret == 0) { - if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) { - if (advanceState) { - ssl->options.connectState++; - WOLFSSL_MSG("connect state: " - "Advanced from last buffered fragment send"); - #ifdef WOLFSSL_ASYNC_IO - /* Cleanup async */ - FreeAsyncCtx(ssl, 0); - #endif - } - } - else { - WOLFSSL_MSG("connect state: " - "Not advanced, more fragments to send"); - } - } - else { - ssl->error = ret; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) - ssl->dtls13SendingAckOrRtx = 0; -#endif /* WOLFSSL_DTLS13 */ + if (ctx != NULL) { + ctx->CBClientCert = cb; } + } - ret = RetrySendAlert(ssl); - if (ret != 0) { - ssl->error = ret; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } + void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx, + CertSetupCallback cb, void *arg) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb"); + if (ctx == NULL) + return; - switch (ssl->options.connectState) { + ctx->certSetupCb = cb; + ctx->certSetupCbArg = arg; + } - case CONNECT_BEGIN : - /* always send client hello first */ - if ( (ssl->error = SendClientHello(ssl)) != 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; + int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl, + const byte** suites, word16* suiteSz, + const byte** hashSigAlgo, word16* hashSigAlgoSz) + { + WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs"); + + if (suites != NULL) + *suites = NULL; + if (suiteSz != NULL) + *suiteSz = 0; + if (hashSigAlgo != NULL) + *hashSigAlgo = NULL; + if (hashSigAlgoSz != NULL) + *hashSigAlgoSz = 0; + + if (ssl != NULL && ssl->clSuites != NULL) { + if (suites != NULL && suiteSz != NULL) { + *suites = ssl->clSuites->suites; + *suiteSz = ssl->clSuites->suiteSz; } - ssl->options.connectState = CLIENT_HELLO_SENT; - WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT"); - FALL_THROUGH; + if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) { + *hashSigAlgo = ssl->clSuites->hashSigAlgo; + *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz; + } + return WOLFSSL_SUCCESS; + } + return WOLFSSL_FAILURE; + } + WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first, + byte second) + { + WOLFSSL_CIPHERSUITE_INFO info; + info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) || + CipherRequires(first, second, REQUIRES_RSA_SIG)); + info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) || + /* Static ECC ciphers may require RSA for authentication */ + (CipherRequires(first, second, REQUIRES_ECC_STATIC) && + !CipherRequires(first, second, REQUIRES_RSA_SIG))); + info.eccStatic = + (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC); + info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK); + return info; + } - case CLIENT_HELLO_SENT : - neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE : - SERVER_HELLODONE_COMPLETE; - #ifdef WOLFSSL_DTLS - /* In DTLS, when resuming, we can go straight to FINISHED, - * or do a cookie exchange and then skip to FINISHED, assume - * we need the cookie exchange first. */ - if (IsDtlsNotSctpMode(ssl)) - neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE; - #endif - /* get response */ - WOLFSSL_MSG("Server state up to needed state."); - while (ssl->options.serverState < neededState) { - WOLFSSL_MSG("Progressing server state..."); - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) - return wolfSSL_connect_TLSv13(ssl); - #endif - WOLFSSL_MSG("ProcessReply..."); - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - /* if resumption failed, reset needed state */ - else if (neededState == SERVER_FINISHED_COMPLETE) { - if (!ssl->options.resuming) { - #ifdef WOLFSSL_DTLS - if (IsDtlsNotSctpMode(ssl)) - neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE; - else - #endif - neededState = SERVER_HELLODONE_COMPLETE; - } - } - WOLFSSL_MSG("ProcessReply done."); + /** + * @param first First byte of the hash and signature algorithm + * @param second Second byte of the hash and signature algorithm + * @param hashAlgo The enum wc_HashType of the MAC algorithm + * @param sigAlgo The enum Key_Sum of the authentication algorithm + */ + int wolfSSL_get_sigalg_info(byte first, byte second, + int* hashAlgo, int* sigAlgo) + { + byte input[2]; + byte hashType; + byte sigType; -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) - && ssl->dtls13Rtx.sendAcks == 1 - && ssl->options.seenUnifiedHdr) { - /* we aren't negotiated the version yet, so we aren't sure - * the other end can speak v1.3. On the other side we have - * received a unified records, assuming that the - * ServerHello got lost, we will send an empty ACK. In case - * the server is a DTLS with version less than 1.3, it - * should just ignore the message */ - ssl->dtls13Rtx.sendAcks = 0; - if ((ssl->error = SendDtls13Ack(ssl)) < 0) { - if (ssl->error == WANT_WRITE) - ssl->dtls13SendingAckOrRtx = 1; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } -#endif /* WOLFSSL_DTLS13 */ - } + if (hashAlgo == NULL || sigAlgo == NULL) + return BAD_FUNC_ARG; - ssl->options.connectState = HELLO_AGAIN; - WOLFSSL_MSG("connect state: HELLO_AGAIN"); - FALL_THROUGH; + input[0] = first; + input[1] = second; + DecodeSigAlg(input, &hashType, &sigType); - case HELLO_AGAIN : + /* cast so that compiler reminds us of unimplemented values */ + switch ((enum SignatureAlgorithm)sigType) { + case anonymous_sa_algo: + *sigAlgo = ANONk; + break; + case rsa_sa_algo: + *sigAlgo = RSAk; + break; + case dsa_sa_algo: + *sigAlgo = DSAk; + break; + case ecc_dsa_sa_algo: + *sigAlgo = ECDSAk; + break; + case rsa_pss_sa_algo: + *sigAlgo = RSAPSSk; + break; + case ed25519_sa_algo: + *sigAlgo = ED25519k; + break; + case rsa_pss_pss_algo: + *sigAlgo = RSAPSSk; + break; + case ed448_sa_algo: + *sigAlgo = ED448k; + break; + case falcon_level1_sa_algo: + *sigAlgo = FALCON_LEVEL1k; + break; + case falcon_level5_sa_algo: + *sigAlgo = FALCON_LEVEL5k; + break; + case dilithium_level2_sa_algo: + *sigAlgo = DILITHIUM_LEVEL2k; + break; + case dilithium_level3_sa_algo: + *sigAlgo = DILITHIUM_LEVEL3k; + break; + case dilithium_level5_sa_algo: + *sigAlgo = DILITHIUM_LEVEL5k; + break; + case sm2_sa_algo: + *sigAlgo = SM2k; + break; + case invalid_sa_algo: + default: + *hashAlgo = WC_HASH_TYPE_NONE; + *sigAlgo = 0; + return BAD_FUNC_ARG; + } - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) - return wolfSSL_connect_TLSv13(ssl); - #endif + /* cast so that compiler reminds us of unimplemented values */ + switch((enum wc_MACAlgorithm)hashType) { + case no_mac: + case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */ + *hashAlgo = WC_HASH_TYPE_NONE; + break; + case md5_mac: + *hashAlgo = WC_HASH_TYPE_MD5; + break; + case sha_mac: + *hashAlgo = WC_HASH_TYPE_SHA; + break; + case sha224_mac: + *hashAlgo = WC_HASH_TYPE_SHA224; + break; + case sha256_mac: + *hashAlgo = WC_HASH_TYPE_SHA256; + break; + case sha384_mac: + *hashAlgo = WC_HASH_TYPE_SHA384; + break; + case sha512_mac: + *hashAlgo = WC_HASH_TYPE_SHA512; + break; + case blake2b_mac: + *hashAlgo = WC_HASH_TYPE_BLAKE2B; + break; + case sm3_mac: +#ifdef WOLFSSL_SM3 + *hashAlgo = WC_HASH_TYPE_SM3; +#else + *hashAlgo = WC_HASH_TYPE_NONE; +#endif + break; + default: + *hashAlgo = WC_HASH_TYPE_NONE; + *sigAlgo = 0; + return BAD_FUNC_ARG; + } + return 0; + } - #ifdef WOLFSSL_DTLS - if (ssl->options.serverState == - SERVER_HELLOVERIFYREQUEST_COMPLETE) { - if (IsDtlsNotSctpMode(ssl)) { - /* re-init hashes, exclude first hello and verify request */ - if ((ssl->error = InitHandshakeHashes(ssl)) != 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - if ( (ssl->error = SendClientHello(ssl)) != 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } + /** + * Internal wrapper for calling certSetupCb + * @param ssl The SSL/TLS Object + * @return 0 on success + */ + int CertSetupCbWrapper(WOLFSSL* ssl) + { + int ret = 0; + if (ssl->ctx->certSetupCb != NULL) { + WOLFSSL_MSG("Calling user cert setup callback"); + ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg); + if (ret == 1) { + WOLFSSL_MSG("User cert callback returned success"); + ret = 0; } - #endif + else if (ret == 0) { + SendAlert(ssl, alert_fatal, internal_error); + ret = CLIENT_CERT_CB_ERROR; + } + else if (ret < 0) { + ret = WOLFSSL_ERROR_WANT_X509_LOOKUP; + } + else { + WOLFSSL_MSG("Unexpected user callback return"); + ret = CLIENT_CERT_CB_ERROR; + } + } + return ret; + } + #endif /* OPENSSL_EXTRA */ - ssl->options.connectState = HELLO_AGAIN_REPLY; - WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY"); - FALL_THROUGH; +#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || HAVE_WEBSERVER */ - case HELLO_AGAIN_REPLY : - #ifdef WOLFSSL_DTLS - if (IsDtlsNotSctpMode(ssl)) { - neededState = ssl->options.resuming ? - SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE; +#ifndef WOLFSSL_NO_CA_NAMES + WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list( + const WOLFSSL_CTX *ctx) + { + WOLFSSL_ENTER("wolfSSL_CTX_get_client_CA_list"); - /* get response */ - while (ssl->options.serverState < neededState) { - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - /* if resumption failed, reset needed state */ - if (neededState == SERVER_FINISHED_COMPLETE) { - if (!ssl->options.resuming) - neededState = SERVER_HELLODONE_COMPLETE; - } - } - } - #endif + if (ctx == NULL) { + WOLFSSL_MSG("Bad argument passed to " + "wolfSSL_CTX_get_client_CA_list"); + return NULL; + } - ssl->options.connectState = FIRST_REPLY_DONE; - WOLFSSL_MSG("connect state: FIRST_REPLY_DONE"); - FALL_THROUGH; + return ctx->client_ca_names; + } - case FIRST_REPLY_DONE : - if (ssl->options.certOnly) - return WOLFSSL_SUCCESS; - #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH) - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) - return wolfSSL_connect_TLSv13(ssl); - #endif - if (ssl->options.sendVerify) { - if ( (ssl->error = SendCertificate(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - WOLFSSL_MSG("sent: certificate"); - } + /* returns the CA's set on server side or the CA's sent from server when + * on client side */ + WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get_client_CA_list( + const WOLFSSL* ssl) + { + WOLFSSL_ENTER("wolfSSL_get_client_CA_list"); - #endif - ssl->options.connectState = FIRST_REPLY_FIRST; - WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST"); - FALL_THROUGH; + if (ssl == NULL) { + WOLFSSL_MSG("Bad argument passed to wolfSSL_get_client_CA_list"); + return NULL; + } - case FIRST_REPLY_FIRST : - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) - return wolfSSL_connect_TLSv13(ssl); - #endif - if (!ssl->options.resuming) { - if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif -#ifdef WOLFSSL_EXTRA_ALERTS - if (ssl->error == NO_PEER_KEY || - ssl->error == PSK_KEY_ERROR) { - SendAlert(ssl, alert_fatal, handshake_failure); - } -#endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - WOLFSSL_MSG("sent: client key exchange"); - } + return SSL_CA_NAMES(ssl); + } - ssl->options.connectState = FIRST_REPLY_SECOND; - WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND"); - FALL_THROUGH; + #if !defined(NO_CERTS) + int wolfSSL_CTX_add_client_CA(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) + { + WOLFSSL_X509_NAME *nameCopy = NULL; - #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) - case FIRST_REPLY_SECOND : - /* CLIENT: Fail-safe for Server Authentication. */ - if (!ssl->options.peerAuthGood) { - WOLFSSL_MSG("Server authentication did not happen"); - ssl->error = NO_PEER_VERIFY; - return WOLFSSL_FATAL_ERROR; - } + WOLFSSL_ENTER("wolfSSL_CTX_add_client_CA"); - #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH) - if (ssl->options.sendVerify) { - if ( (ssl->error = SendCertificateVerify(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - WOLFSSL_MSG("sent: certificate verify"); - } - #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */ - ssl->options.connectState = FIRST_REPLY_THIRD; - WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD"); - FALL_THROUGH; + if (ctx == NULL || x509 == NULL){ + WOLFSSL_MSG("Bad argument"); + return WOLFSSL_FAILURE; + } - case FIRST_REPLY_THIRD : - if ( (ssl->error = SendChangeCipher(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; + if (ctx->client_ca_names == NULL) { + ctx->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL); + if (ctx->client_ca_names == NULL) { + WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error"); + return WOLFSSL_FAILURE; } - WOLFSSL_MSG("sent: change cipher spec"); - ssl->options.connectState = FIRST_REPLY_FOURTH; - WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH"); - FALL_THROUGH; + } - case FIRST_REPLY_FOURTH : - if ( (ssl->error = SendFinished(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - WOLFSSL_MSG("sent: finished"); - ssl->options.connectState = FINISHED_DONE; - WOLFSSL_MSG("connect state: FINISHED_DONE"); - FALL_THROUGH; + nameCopy = wolfSSL_X509_NAME_dup(wolfSSL_X509_get_subject_name(x509)); + if (nameCopy == NULL) { + WOLFSSL_MSG("wolfSSL_X509_NAME_dup error"); + return WOLFSSL_FAILURE; + } -#ifdef WOLFSSL_DTLS13 - case WAIT_FINISHED_ACK: - ssl->options.connectState = FINISHED_DONE; - FALL_THROUGH; -#endif /* WOLFSSL_DTLS13 */ + if (wolfSSL_sk_X509_NAME_push(ctx->client_ca_names, nameCopy) != + WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); + wolfSSL_X509_NAME_free(nameCopy); + return WOLFSSL_FAILURE; + } - case FINISHED_DONE : - /* get response */ - while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } + return WOLFSSL_SUCCESS; + } + #endif - ssl->options.connectState = SECOND_REPLY_DONE; - WOLFSSL_MSG("connect state: SECOND_REPLY_DONE"); - FALL_THROUGH; + #ifndef NO_BIO + #if !defined(NO_RSA) && !defined(NO_CERTS) + WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_load_client_CA_file( + const char* fname) + { + /* The webserver build is using this to load a CA into the server + * for client authentication as an option. Have this return NULL in + * that case. If OPENSSL_EXTRA is enabled, go ahead and include + * the function. */ + #ifdef OPENSSL_EXTRA + WOLFSSL_STACK *list = NULL; + WOLFSSL_BIO* bio = NULL; + WOLFSSL_X509 *cert = NULL; + WOLFSSL_X509_NAME *nameCopy = NULL; + unsigned long err = WOLFSSL_FAILURE; - case SECOND_REPLY_DONE: - #ifndef NO_HANDSHAKE_DONE_CB - if (ssl->hsDoneCb) { - int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); - if (cbret < 0) { - ssl->error = cbret; - WOLFSSL_MSG("HandShake Done Cb don't continue error"); - return WOLFSSL_FATAL_ERROR; - } - } - #endif /* NO_HANDSHAKE_DONE_CB */ + WOLFSSL_ENTER("wolfSSL_load_client_CA_file"); - if (!ssl->options.dtls) { - if (!ssl->options.keepResources) { - FreeHandshakeResources(ssl); - } - } - #ifdef WOLFSSL_DTLS - else { - ssl->options.dtlsHsRetain = 1; + bio = wolfSSL_BIO_new_file(fname, "rb"); + if (bio == NULL) { + WOLFSSL_MSG("wolfSSL_BIO_new_file error"); + goto cleanup; } - #endif /* WOLFSSL_DTLS */ - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION) - /* This may be necessary in async so that we don't try to - * renegotiate again */ - if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) { - ssl->secure_renegotiation->startScr = 0; + list = wolfSSL_sk_X509_NAME_new(NULL); + if (list == NULL) { + WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error"); + goto cleanup; } - #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */ - #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT) - /* Free the remaining async context if not using it for crypto */ - FreeAsyncCtx(ssl, 1); - #endif - - ssl->error = 0; /* clear the error */ - WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS); - return WOLFSSL_SUCCESS; - #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */ + /* Read each certificate in the chain out of the file. */ + while (wolfSSL_PEM_read_bio_X509(bio, &cert, NULL, NULL) != NULL) { + /* Need a persistent copy of the subject name. */ + nameCopy = wolfSSL_X509_NAME_dup( + wolfSSL_X509_get_subject_name(cert)); + if (nameCopy == NULL) { + WOLFSSL_MSG("wolfSSL_X509_NAME_dup error"); + goto cleanup; + } + /* + * Original cert will be freed so make sure not to try to access + * it in the future. + */ + nameCopy->x509 = NULL; - default: - WOLFSSL_MSG("Unknown connect state ERROR"); - return WOLFSSL_FATAL_ERROR; /* unknown connect state */ - } - #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */ - } + if (wolfSSL_sk_X509_NAME_push(list, nameCopy) != + WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); + /* Do free in loop because nameCopy is now responsibility + * of list to free and adding jumps to cleanup after this + * might result in a double free. */ + wolfSSL_X509_NAME_free(nameCopy); + goto cleanup; + } -#endif /* NO_WOLFSSL_CLIENT */ + wolfSSL_X509_free(cert); + cert = NULL; + } + CLEAR_ASN_NO_PEM_HEADER_ERROR(err); -/* server only parts */ -#ifndef NO_WOLFSSL_SERVER + err = WOLFSSL_SUCCESS; +cleanup: + wolfSSL_X509_free(cert); + wolfSSL_BIO_free(bio); + if (err != WOLFSSL_SUCCESS) { + /* We failed so return NULL */ + wolfSSL_sk_X509_NAME_pop_free(list, NULL); + list = NULL; + } + return list; + #else + (void)fname; + return NULL; + #endif + } + #endif + #endif /* !NO_BIO */ +#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA */ - #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) - WOLFSSL_METHOD* wolfSSLv2_server_method(void) - { - WOLFSSL_STUB("wolfSSLv2_server_method"); - return 0; - } - #endif +#ifdef OPENSSL_EXTRA - #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) - WOLFSSL_METHOD* wolfSSLv3_server_method(void) + #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \ + && !defined(WC_NO_RNG) + static const byte srp_N[] = { + 0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8, + 0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF, + 0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6, + 0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13, + 0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B, + 0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7, + 0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69, + 0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85, + 0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC, + 0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E, + 0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F, + 0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3 + }; + static const byte srp_g[] = { + 0x02 + }; + + int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username) { - return wolfSSLv3_server_method_ex(NULL); + int r = 0; + SrpSide srp_side = SRP_CLIENT_SIDE; + byte salt[SRP_SALT_SIZE]; + + WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username"); + if (ctx == NULL || ctx->srp == NULL || username==NULL) + return WOLFSSL_FAILURE; + + if (ctx->method->side == WOLFSSL_SERVER_END){ + srp_side = SRP_SERVER_SIDE; + } else if (ctx->method->side == WOLFSSL_CLIENT_END){ + srp_side = SRP_CLIENT_SIDE; + } else { + WOLFSSL_MSG("Init CTX failed"); + return WOLFSSL_FAILURE; + } + + if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) { + WOLFSSL_MSG("Init SRP CTX failed"); + XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP); + ctx->srp = NULL; + return WOLFSSL_FAILURE; + } + r = wc_SrpSetUsername(ctx->srp, (const byte*)username, + (word32)XSTRLEN(username)); + if (r < 0) { + WOLFSSL_MSG("fail to set srp username."); + return WOLFSSL_FAILURE; + } + + /* if wolfSSL_CTX_set_srp_password has already been called, */ + /* execute wc_SrpSetPassword here */ + if (ctx->srp_password != NULL) { + WC_RNG rng; + if (wc_InitRng(&rng) < 0){ + WOLFSSL_MSG("wc_InitRng failed"); + return WOLFSSL_FAILURE; + } + XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0])); + r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0])); + wc_FreeRng(&rng); + if (r < 0) { + WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); + return WOLFSSL_FAILURE; + } + + if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]), + srp_g, sizeof(srp_g)/sizeof(srp_g[0]), + salt, sizeof(salt)/sizeof(salt[0])) < 0) { + WOLFSSL_MSG("wc_SrpSetParam failed"); + return WOLFSSL_FAILURE; + } + r = wc_SrpSetPassword(ctx->srp, + (const byte*)ctx->srp_password, + (word32)XSTRLEN((char *)ctx->srp_password)); + if (r < 0) { + WOLFSSL_MSG("fail to set srp password."); + return WOLFSSL_FAILURE; + } + + XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); + ctx->srp_password = NULL; + } + + return WOLFSSL_SUCCESS; } - WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap) + + int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password) { - WOLFSSL_METHOD* method = - (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), - heap, DYNAMIC_TYPE_METHOD); - (void)heap; - WOLFSSL_ENTER("wolfSSLv3_server_method_ex"); - if (method) { - InitSSL_Method(method, MakeSSLv3()); - method->side = WOLFSSL_SERVER_END; + int r; + byte salt[SRP_SALT_SIZE]; + + WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password"); + if (ctx == NULL || ctx->srp == NULL || password == NULL) + return WOLFSSL_FAILURE; + + if (ctx->srp->user != NULL) { + WC_RNG rng; + if (wc_InitRng(&rng) < 0) { + WOLFSSL_MSG("wc_InitRng failed"); + return WOLFSSL_FAILURE; + } + XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0])); + r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0])); + wc_FreeRng(&rng); + if (r < 0) { + WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); + return WOLFSSL_FAILURE; + } + if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]), + srp_g, sizeof(srp_g)/sizeof(srp_g[0]), + salt, sizeof(salt)/sizeof(salt[0])) < 0){ + WOLFSSL_MSG("wc_SrpSetParam failed"); + wc_FreeRng(&rng); + return WOLFSSL_FAILURE; + } + r = wc_SrpSetPassword(ctx->srp, (const byte*)password, + (word32)XSTRLEN(password)); + if (r < 0) { + WOLFSSL_MSG("wc_SrpSetPassword failed."); + wc_FreeRng(&rng); + return WOLFSSL_FAILURE; + } + if (ctx->srp_password != NULL){ + XFREE(ctx->srp_password,NULL, + DYNAMIC_TYPE_SRP); + ctx->srp_password = NULL; + } + wc_FreeRng(&rng); + } else { + /* save password for wolfSSL_set_srp_username */ + if (ctx->srp_password != NULL) + XFREE(ctx->srp_password,ctx->heap, DYNAMIC_TYPE_SRP); + + ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap, + DYNAMIC_TYPE_SRP); + if (ctx->srp_password == NULL){ + WOLFSSL_MSG("memory allocation error"); + return WOLFSSL_FAILURE; + } + XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1); } - return method; + return WOLFSSL_SUCCESS; } - #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */ - WOLFSSL_METHOD* wolfSSLv23_server_method(void) + /** + * The modulus passed to wc_SrpSetParams in ssl.c is constant so check + * that the requested strength is less than or equal to the size of the + * static modulus size. + * @param ctx Not used + * @param strength Minimum number of bits for the modulus + * @return 1 if strength is less than or equal to static modulus + * 0 if strength is greater than static modulus + */ + int wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength) { - return wolfSSLv23_server_method_ex(NULL); + (void)ctx; + WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength"); + if (strength > (int)(sizeof(srp_N)*8)) { + WOLFSSL_MSG("Bad Parameter"); + return WOLFSSL_FAILURE; + } + return WOLFSSL_SUCCESS; } - WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap) + char* wolfSSL_get_srp_username(WOLFSSL *ssl) { - WOLFSSL_METHOD* method = - (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD), - heap, DYNAMIC_TYPE_METHOD); - (void)heap; - WOLFSSL_ENTER("wolfSSLv23_server_method_ex"); - if (method) { - #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) - #ifdef WOLFSSL_TLS13 - InitSSL_Method(method, MakeTLSv1_3()); - #elif !defined(WOLFSSL_NO_TLS12) - InitSSL_Method(method, MakeTLSv1_2()); - #elif !defined(NO_OLD_TLS) - InitSSL_Method(method, MakeTLSv1_1()); - #endif - #else - #ifndef NO_OLD_TLS - InitSSL_Method(method, MakeTLSv1_1()); - #else - #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2 - #endif - #endif - #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13) - method->downgrade = 1; - #endif - method->side = WOLFSSL_SERVER_END; + if (ssl && ssl->ctx && ssl->ctx->srp) { + return (char*) ssl->ctx->srp->user; } - return method; + return NULL; } + #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */ - - WOLFSSL_ABI - int wolfSSL_accept(WOLFSSL* ssl) + /* keyblock size in bytes or -1 */ + int wolfSSL_get_keyblock_size(WOLFSSL* ssl) { -#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)) - word16 havePSK = 0; - word16 haveAnon = 0; - word16 haveMcast = 0; -#endif - int ret = 0; - - (void)ret; - if (ssl == NULL) return WOLFSSL_FATAL_ERROR; - #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) - if (ssl->options.side == WOLFSSL_NEITHER_END) { - WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side"); - ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END); - if (ssl->error != WOLFSSL_SUCCESS) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->error = 0; /* expected to be zero here */ - } - #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ + return 2 * (ssl->specs.key_size + ssl->specs.iv_size + + ssl->specs.hash_size); + } -#if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13) - return wolfSSL_accept_TLSv13(ssl); -#else - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) - return wolfSSL_accept_TLSv13(ssl); - #endif - WOLFSSL_ENTER("wolfSSL_accept"); +#endif /* OPENSSL_EXTRA */ - /* make sure this wolfSSL object has arrays and rng setup. Protects - * case where the WOLFSSL object is reused via wolfSSL_clear() */ - if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { - return ret; - } +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \ + defined(WOLFSSL_WPAS_SMALL) -#ifdef WOLFSSL_WOLFSENTRY_HOOKS - if ((ssl->AcceptFilter != NULL) && - ((ssl->options.acceptState == ACCEPT_BEGIN) -#ifdef HAVE_SECURE_RENEGOTIATION - || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG) -#endif - )) - { - wolfSSL_netfilter_decision_t res; - if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) == - WOLFSSL_SUCCESS) && - (res == WOLFSSL_NETFILTER_REJECT)) { - ssl->error = SOCKET_FILTERED_E; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } -#endif /* WOLFSSL_WOLFSENTRY_HOOKS */ + /* store keys returns WOLFSSL_SUCCESS or -1 on error */ + int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen, + unsigned char** sr, unsigned int* srLen, + unsigned char** cr, unsigned int* crLen) + { + if (ssl == NULL || ssl->arrays == NULL) + return WOLFSSL_FATAL_ERROR; - #ifdef HAVE_ERRNO_H - errno = 0; - #endif + *ms = ssl->arrays->masterSecret; + *sr = ssl->arrays->serverRandom; + *cr = ssl->arrays->clientRandom; - #ifndef NO_PSK - havePSK = ssl->options.havePSK; - #endif - (void)havePSK; + *msLen = SECRET_LEN; + *srLen = RAN_LEN; + *crLen = RAN_LEN; - #ifdef HAVE_ANON - haveAnon = ssl->options.useAnon; - #endif - (void)haveAnon; + return WOLFSSL_SUCCESS; + } - #ifdef WOLFSSL_MULTICAST - haveMcast = ssl->options.haveMcast; - #endif - (void)haveMcast; + void wolfSSL_set_accept_state(WOLFSSL* ssl) + { + WOLFSSL_ENTER("wolfSSL_set_accept_state"); - if (ssl->options.side != WOLFSSL_SERVER_END) { - ssl->error = SIDE_ERROR; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } + if (ssl == NULL) + return; - #ifndef NO_CERTS - /* in case used set_accept_state after init */ - if (!havePSK && !haveAnon && !haveMcast) { - #ifdef OPENSSL_EXTRA - if (ssl->ctx->certSetupCb != NULL) { - WOLFSSL_MSG("CertSetupCb set. server cert and " - "key not checked"); - } - else + if (ssl->options.side == WOLFSSL_CLIENT_END) { + #ifdef HAVE_ECC + #ifdef WOLFSSL_SMALL_STACK + ecc_key* key = NULL; + #else + ecc_key key[1]; #endif - { - if (!ssl->buffers.certificate || - !ssl->buffers.certificate->buffer) { - - WOLFSSL_MSG("accept error: server cert required"); - ssl->error = NO_PRIVATE_KEY; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } + word32 idx = 0; - if (!ssl->buffers.key || !ssl->buffers.key->buffer) { - /* allow no private key if using existing key */ - #ifdef WOLF_PRIVATE_KEY_ID - if (ssl->devId != INVALID_DEVID - #ifdef HAVE_PK_CALLBACKS - || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx) - #endif - ) { - WOLFSSL_MSG("Allowing no server private key " - "(external)"); - } - else - #endif - { - WOLFSSL_MSG("accept error: server key required"); - ssl->error = NO_PRIVATE_KEY; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } + #ifdef WOLFSSL_SMALL_STACK + key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap, + DYNAMIC_TYPE_ECC); + if (key == NULL) { + WOLFSSL_MSG("Error allocating memory for ecc_key"); } - } - #endif - - #ifdef WOLFSSL_DTLS - if (ssl->version.major == DTLS_MAJOR) { - ssl->options.dtls = 1; - ssl->options.tls = 1; - ssl->options.tls1_1 = 1; - if (!IsDtlsNotSctpMode(ssl) || !IsDtlsNotSrtpMode(ssl) || - IsSCR(ssl)) - ssl->options.dtlsStateful = 1; - } - #endif - - if (ssl->buffers.outputBuffer.length > 0 - #ifdef WOLFSSL_ASYNC_CRYPT - /* do not send buffered or advance state if last error was an - async pending operation */ - && ssl->error != WC_PENDING_E #endif - ) { - ret = SendBuffered(ssl); - if (ret == 0) { - /* fragOffset is non-zero when sending fragments. On the last - * fragment, fragOffset is zero again, and the state can be - * advanced. */ - if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) { - if (ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE || - ssl->options.acceptState == SERVER_HELLO_SENT || - ssl->options.acceptState == CERT_SENT || - ssl->options.acceptState == CERT_STATUS_SENT || - ssl->options.acceptState == KEY_EXCHANGE_SENT || - ssl->options.acceptState == CERT_REQ_SENT || - ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE || - ssl->options.acceptState == TICKET_SENT || - ssl->options.acceptState == CHANGE_CIPHER_SENT) { - ssl->options.acceptState++; - WOLFSSL_MSG("accept state: " - "Advanced from last buffered fragment send"); - #ifdef WOLFSSL_ASYNC_IO - /* Cleanup async */ - FreeAsyncCtx(ssl, 0); - #endif + if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) { + if (wc_ecc_init(key) >= 0) { + if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx, + key, ssl->buffers.key->length) != 0) { + ssl->options.haveECDSAsig = 0; + ssl->options.haveECC = 0; + ssl->options.haveStaticECC = 0; } - } - else { - WOLFSSL_MSG("accept state: " - "Not advanced, more fragments to send"); + wc_ecc_free(key); } } - else { - ssl->error = ret; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; + #ifdef WOLFSSL_SMALL_STACK + XFREE(key, ssl->heap, DYNAMIC_TYPE_ECC); + #endif + #endif + + #ifndef NO_DH + if (!ssl->options.haveDH && ssl->ctx->haveDH) { + ssl->buffers.serverDH_P = ssl->ctx->serverDH_P; + ssl->buffers.serverDH_G = ssl->ctx->serverDH_G; + ssl->options.haveDH = 1; } -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) - ssl->dtls13SendingAckOrRtx = 0; -#endif /* WOLFSSL_DTLS13 */ + #endif } - ret = RetrySendAlert(ssl); - if (ret != 0) { - ssl->error = ret; - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; + if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error initializing server side"); } + } - switch (ssl->options.acceptState) { +#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - case ACCEPT_BEGIN : -#ifdef HAVE_SECURE_RENEGOTIATION - case ACCEPT_BEGIN_RENEG: -#endif - /* get response */ - while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } -#ifdef WOLFSSL_TLS13 - ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE; - WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE"); - FALL_THROUGH; + /* return true if connection established */ + int wolfSSL_is_init_finished(const WOLFSSL* ssl) + { + if (ssl == NULL) + return 0; - case ACCEPT_CLIENT_HELLO_DONE : - if (ssl->options.tls1_3) { - return wolfSSL_accept_TLSv13(ssl); - } -#endif + /* Can't use ssl->options.connectState and ssl->options.acceptState + * because they differ in meaning for TLS <=1.2 and 1.3 */ + if (ssl->options.handShakeState == HANDSHAKE_DONE) + return 1; - ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE; - WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE"); - FALL_THROUGH; + return 0; + } - case ACCEPT_FIRST_REPLY_DONE : - if ( (ssl->error = SendServerHello(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->options.acceptState = SERVER_HELLO_SENT; - WOLFSSL_MSG("accept state SERVER_HELLO_SENT"); - FALL_THROUGH; +#ifdef OPENSSL_EXTRA + void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx, + WOLFSSL_RSA*(*f)(WOLFSSL*, int, int)) + { + /* wolfSSL verifies all these internally */ + (void)ctx; + (void)f; + } - case SERVER_HELLO_SENT : - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) { - return wolfSSL_accept_TLSv13(ssl); - } - #endif - #ifndef NO_CERTS - if (!ssl->options.resuming) - if ( (ssl->error = SendCertificate(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - #endif - ssl->options.acceptState = CERT_SENT; - WOLFSSL_MSG("accept state CERT_SENT"); - FALL_THROUGH; - case CERT_SENT : - #ifndef NO_CERTS - if (!ssl->options.resuming) - if ( (ssl->error = SendCertificateStatus(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - #endif - ssl->options.acceptState = CERT_STATUS_SENT; - WOLFSSL_MSG("accept state CERT_STATUS_SENT"); - FALL_THROUGH; - - case CERT_STATUS_SENT : - #ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) { - return wolfSSL_accept_TLSv13(ssl); - } - #endif - if (!ssl->options.resuming) - if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->options.acceptState = KEY_EXCHANGE_SENT; - WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT"); - FALL_THROUGH; + void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt) + { + WOLFSSL_ENTER("wolfSSL_set_shutdown"); + if(ssl==NULL) { + WOLFSSL_MSG("Shutdown not set. ssl is null"); + return; + } - case KEY_EXCHANGE_SENT : - #ifndef NO_CERTS - if (!ssl->options.resuming) { - if (ssl->options.verifyPeer) { - if ( (ssl->error = SendCertificateRequest(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } - else { - /* SERVER: Peer auth good if not verifying client. */ - ssl->options.peerAuthGood = 1; - } - } - #endif - ssl->options.acceptState = CERT_REQ_SENT; - WOLFSSL_MSG("accept state CERT_REQ_SENT"); - FALL_THROUGH; + ssl->options.sentNotify = (opt&WOLFSSL_SENT_SHUTDOWN) > 0; + ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0; + } +#endif - case CERT_REQ_SENT : - if (!ssl->options.resuming) - if ( (ssl->error = SendServerHelloDone(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->options.acceptState = SERVER_HELLO_DONE; - WOLFSSL_MSG("accept state SERVER_HELLO_DONE"); - FALL_THROUGH; + long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx) + { + WOLFSSL_ENTER("wolfSSL_CTX_get_options"); + WOLFSSL_MSG("wolfSSL options are set through API calls and macros"); + if(ctx == NULL) + return BAD_FUNC_ARG; + return ctx->mask; + } - case SERVER_HELLO_DONE : - if (!ssl->options.resuming) { - while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } - ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE; - WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE"); - FALL_THROUGH; + /* forward declaration */ + static long wolf_set_options(long old_op, long op); - case ACCEPT_SECOND_REPLY_DONE : - #ifndef NO_CERTS - /* SERVER: When not resuming and verifying peer but no certificate - * received and not failing when not received then peer auth good. - */ - if (!ssl->options.resuming && ssl->options.verifyPeer && - !ssl->options.havePeerCert && !ssl->options.failNoCert) { - ssl->options.peerAuthGood = 1; - } - #endif /* !NO_CERTS */ - #ifdef WOLFSSL_NO_CLIENT_AUTH - if (!ssl->options.resuming) { - ssl->options.peerAuthGood = 1; - } - #endif + long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_options"); -#ifdef HAVE_SESSION_TICKET - if (ssl->options.createTicket && !ssl->options.noTicketTls12) { - if ( (ssl->error = SendTicket(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_MSG("Thought we need ticket but failed"); - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } -#endif /* HAVE_SESSION_TICKET */ - ssl->options.acceptState = TICKET_SENT; - WOLFSSL_MSG("accept state TICKET_SENT"); - FALL_THROUGH; + if (ctx == NULL) + return BAD_FUNC_ARG; - case TICKET_SENT: - /* SERVER: Fail-safe for CLient Authentication. */ - if (!ssl->options.peerAuthGood) { - WOLFSSL_MSG("Client authentication did not happen"); - return WOLFSSL_FATAL_ERROR; + ctx->mask = wolf_set_options(ctx->mask, opt); +#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \ + || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)) + if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { + ctx->noTicketTls12 = 1; + } + /* This code is here for documentation purpose. You must not turn off + * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3. + * Because we need to support both stateful and stateless tickets. + #ifdef WOLFSSL_TLS13 + if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { + ctx->noTicketTls13 = 1; } + #endif + */ +#endif + return ctx->mask; + } - if ( (ssl->error = SendChangeCipher(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - ssl->options.acceptState = CHANGE_CIPHER_SENT; - WOLFSSL_MSG("accept state CHANGE_CIPHER_SENT"); - FALL_THROUGH; + long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt) + { + WOLFSSL_ENTER("wolfSSL_CTX_clear_options"); + if(ctx == NULL) + return BAD_FUNC_ARG; + ctx->mask &= ~opt; + return ctx->mask; + } - case CHANGE_CIPHER_SENT : - if ( (ssl->error = SendFinished(ssl)) != 0) { - #ifdef WOLFSSL_CHECK_ALERT_ON_ERR - ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ - #endif - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } +#ifdef OPENSSL_EXTRA - ssl->options.acceptState = ACCEPT_FINISHED_DONE; - WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE"); - FALL_THROUGH; + int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd) + { + WOLFSSL_ENTER("wolfSSL_set_rfd"); + ssl->rfd = rfd; /* not used directly to allow IO callbacks */ - case ACCEPT_FINISHED_DONE : - if (ssl->options.resuming) { - while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) { - if ( (ssl->error = ProcessReply(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } - } - ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE; - WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE"); - FALL_THROUGH; + ssl->IOCB_ReadCtx = &ssl->rfd; - case ACCEPT_THIRD_REPLY_DONE : -#ifndef NO_HANDSHAKE_DONE_CB - if (ssl->hsDoneCb) { - int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); - if (cbret < 0) { - ssl->error = cbret; - WOLFSSL_MSG("HandShake Done Cb don't continue error"); - return WOLFSSL_FATAL_ERROR; - } - } -#endif /* NO_HANDSHAKE_DONE_CB */ + #ifdef WOLFSSL_DTLS + if (ssl->options.dtls) { + ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx; + ssl->buffers.dtlsCtx.rfd = rfd; + } + #endif - if (!ssl->options.dtls) { - if (!ssl->options.keepResources) { - FreeHandshakeResources(ssl); - } - } -#ifdef WOLFSSL_DTLS - else { - ssl->options.dtlsHsRetain = 1; - } -#endif /* WOLFSSL_DTLS */ + return WOLFSSL_SUCCESS; + } -#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION) - /* This may be necessary in async so that we don't try to - * renegotiate again */ - if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) { - ssl->secure_renegotiation->startScr = 0; - } -#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */ -#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT) - /* Free the remaining async context if not using it for crypto */ - FreeAsyncCtx(ssl, 1); -#endif -#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS) - if (ssl->dtls_export) { - if ((ssl->error = wolfSSL_send_session(ssl)) != 0) { - WOLFSSL_MSG("Export DTLS session error"); - WOLFSSL_ERROR(ssl->error); - return WOLFSSL_FATAL_ERROR; - } - } -#endif - ssl->error = 0; /* clear the error */ + int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd) + { + WOLFSSL_ENTER("wolfSSL_set_wfd"); + ssl->wfd = wfd; /* not used directly to allow IO callbacks */ - WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS); - return WOLFSSL_SUCCESS; + ssl->IOCB_WriteCtx = &ssl->wfd; - default : - WOLFSSL_MSG("Unknown accept state ERROR"); - return WOLFSSL_FATAL_ERROR; - } -#endif /* !WOLFSSL_NO_TLS12 */ + return WOLFSSL_SUCCESS; } +#endif /* OPENSSL_EXTRA */ -#endif /* NO_WOLFSSL_SERVER */ +#if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || \ + defined(WOLFSSL_WPAS_SMALL)) -#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) -int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx) -{ - WOLFSSL_ENTER("wolfDTLS_SetChGoodCb"); +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + /** + * Implemented in a similar way that ngx_ssl_ocsp_validate does it when + * SSL_get0_verified_chain is not available. + * @param ssl WOLFSSL object to extract certs from + * @return Stack of verified certs + */ + WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl) + { + WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL; + WOLFSSL_X509_STORE_CTX* storeCtx = NULL; + WOLFSSL_X509* peerCert = NULL; - if (ssl == NULL) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wolfSSL_get0_verified_chain"); - ssl->chGoodCb = cb; - ssl->chGoodCtx = user_ctx; + if (ssl == NULL || ssl->ctx == NULL) { + WOLFSSL_MSG("Bad parameter"); + return NULL; + } - return WOLFSSL_SUCCESS; -} -#endif + peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl); + if (peerCert == NULL) { + WOLFSSL_MSG("wolfSSL_get_peer_certificate error"); + return NULL; + } + /* wolfSSL_get_peer_certificate returns a copy. We want the internal + * member so that we don't have to worry about free'ing it. We call + * wolfSSL_get_peer_certificate so that we don't have to worry about + * setting up the internal pointer. */ + wolfSSL_X509_free(peerCert); + peerCert = (WOLFSSL_X509*)&ssl->peerCert; + chain = wolfSSL_get_peer_cert_chain(ssl); + if (chain == NULL) { + WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error"); + return NULL; + } + storeCtx = wolfSSL_X509_STORE_CTX_new(); + if (storeCtx == NULL) { + WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error"); + return NULL; + } + if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl), + peerCert, chain) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error"); + wolfSSL_X509_STORE_CTX_free(storeCtx); + return NULL; + } + if (wolfSSL_X509_verify_cert(storeCtx) <= 0) { + WOLFSSL_MSG("wolfSSL_X509_verify_cert error"); + wolfSSL_X509_STORE_CTX_free(storeCtx); + return NULL; + } + wolfSSL_X509_STORE_CTX_free(storeCtx); + return chain; + } +#endif /* SESSION_CERTS && OPENSSL_EXTRA */ -#ifndef NO_HANDSHAKE_DONE_CB + WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(const WOLFSSL_CTX* ctx) + { + if (ctx == NULL) { + return NULL; + } -int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx) -{ - WOLFSSL_ENTER("wolfSSL_SetHsDoneCb"); + if (ctx->x509_store_pt != NULL) + return ctx->x509_store_pt; + return &((WOLFSSL_CTX*)ctx)->x509_store; + } - if (ssl == NULL) - return BAD_FUNC_ARG; + void wolfSSL_CTX_set_cert_store(WOLFSSL_CTX* ctx, WOLFSSL_X509_STORE* str) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_cert_store"); + if (ctx == NULL || str == NULL || ctx->cm == str->cm) { + return; + } - ssl->hsDoneCb = cb; - ssl->hsDoneCtx = user_ctx; + if (wolfSSL_CertManager_up_ref(str->cm) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_CertManager_up_ref error"); + return; + } + /* free cert manager if have one */ + if (ctx->cm != NULL) { + wolfSSL_CertManagerFree(ctx->cm); + } + ctx->cm = str->cm; + ctx->x509_store.cm = str->cm; - return WOLFSSL_SUCCESS; -} + /* free existing store if it exists */ + wolfSSL_X509_STORE_free(ctx->x509_store_pt); + ctx->x509_store.cache = str->cache; + ctx->x509_store_pt = str; /* take ownership of store and free it + with CTX free */ + ctx->cm->x509_store_p = ctx->x509_store_pt;/* CTX has ownership + and free it with CTX free*/ + } -#endif /* NO_HANDSHAKE_DONE_CB */ +#ifdef OPENSSL_ALL + int wolfSSL_CTX_set1_verify_cert_store(WOLFSSL_CTX* ctx, + WOLFSSL_X509_STORE* str) + { + WOLFSSL_ENTER("wolfSSL_CTX_set1_verify_cert_store"); -WOLFSSL_ABI -int wolfSSL_Cleanup(void) -{ - int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */ - int release = 0; -#if !defined(NO_SESSION_CACHE) - int i; - int j; -#endif + if (ctx == NULL || str == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } - WOLFSSL_ENTER("wolfSSL_Cleanup"); + /* NO-OP when setting existing store */ + if (str == CTX_STORE(ctx)) + return WOLFSSL_SUCCESS; -#ifndef WOLFSSL_MUTEX_INITIALIZER - if (inits_count_mutex_valid == 1) { -#endif - if (wc_LockMutex(&inits_count_mutex) != 0) { - WOLFSSL_MSG("Bad Lock Mutex count"); - return BAD_MUTEX_E; + if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error"); + return WOLFSSL_FAILURE; } -#ifndef WOLFSSL_MUTEX_INITIALIZER + + /* free existing store if it exists */ + wolfSSL_X509_STORE_free(ctx->x509_store_pt); + ctx->x509_store_pt = str; /* take ownership of store and free it + with CTX free */ + return WOLFSSL_SUCCESS; } #endif - if (initRefCount > 0) { - --initRefCount; - if (initRefCount == 0) - release = 1; - } + int wolfSSL_set0_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str) + { + WOLFSSL_ENTER("wolfSSL_set0_verify_cert_store"); -#ifndef WOLFSSL_MUTEX_INITIALIZER - if (inits_count_mutex_valid == 1) { -#endif - wc_UnLockMutex(&inits_count_mutex); -#ifndef WOLFSSL_MUTEX_INITIALIZER + if (ssl == NULL || str == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + /* NO-OP when setting existing store */ + if (str == SSL_STORE(ssl)) + return WOLFSSL_SUCCESS; + + /* free existing store if it exists */ + wolfSSL_X509_STORE_free(ssl->x509_store_pt); + if (str == ssl->ctx->x509_store_pt) + ssl->x509_store_pt = NULL; /* if setting ctx store then just revert + to using that instead */ + else + ssl->x509_store_pt = str; /* take ownership of store and free it + with SSL free */ + return WOLFSSL_SUCCESS; } -#endif - if (!release) - return ret; -#ifdef OPENSSL_EXTRA - wolfSSL_BN_free_one(); -#endif + int wolfSSL_set1_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str) + { + WOLFSSL_ENTER("wolfSSL_set1_verify_cert_store"); -#ifndef NO_SESSION_CACHE - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - for (i = 0; i < SESSION_ROWS; ++i) { - if ((SessionCache[i].lock_valid == 1) && - (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) { - if (ret == WOLFSSL_SUCCESS) - ret = BAD_MUTEX_E; + if (ssl == NULL || str == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } - SessionCache[i].lock_valid = 0; - } - #else - if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) { - if (ret == WOLFSSL_SUCCESS) - ret = BAD_MUTEX_E; - } - session_lock_valid = 0; - #endif - for (i = 0; i < SESSION_ROWS; i++) { - for (j = 0; j < SESSIONS_PER_ROW; j++) { - #ifdef SESSION_CACHE_DYNAMIC_MEM - if (SessionCache[i].Sessions[j]) { - EvictSessionFromCache(SessionCache[i].Sessions[j]); - XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap, - DYNAMIC_TYPE_SESSION); - SessionCache[i].Sessions[j] = NULL; - } - #else - EvictSessionFromCache(&SessionCache[i].Sessions[j]); - #endif + + /* NO-OP when setting existing store */ + if (str == SSL_STORE(ssl)) + return WOLFSSL_SUCCESS; + + if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error"); + return WOLFSSL_FAILURE; } - } - #ifndef NO_CLIENT_CACHE - #ifndef WOLFSSL_MUTEX_INITIALIZER - if ((clisession_mutex_valid == 1) && - (wc_FreeMutex(&clisession_mutex) != 0)) { - if (ret == WOLFSSL_SUCCESS) - ret = BAD_MUTEX_E; - } - clisession_mutex_valid = 0; - #endif - #endif -#endif /* !NO_SESSION_CACHE */ -#ifndef WOLFSSL_MUTEX_INITIALIZER - if ((inits_count_mutex_valid == 1) && (wc_FreeMutex(&inits_count_mutex) != 0)) { - if (ret == WOLFSSL_SUCCESS) - ret = BAD_MUTEX_E; + /* free existing store if it exists */ + wolfSSL_X509_STORE_free(ssl->x509_store_pt); + if (str == ssl->ctx->x509_store_pt) + ssl->x509_store_pt = NULL; /* if setting ctx store then just revert + to using that instead */ + else + ssl->x509_store_pt = str; /* take ownership of store and free it + with SSL free */ + return WOLFSSL_SUCCESS; } - inits_count_mutex_valid = 0; -#endif +#endif /* !NO_CERTS && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */ -#ifdef OPENSSL_EXTRA - wolfSSL_RAND_Cleanup(); -#endif +#ifdef WOLFSSL_ENCRYPTED_KEYS - if (wolfCrypt_Cleanup() != 0) { - WOLFSSL_MSG("Error with wolfCrypt_Cleanup call"); - if (ret == WOLFSSL_SUCCESS) - ret = WC_CLEANUP_E; + void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx, + void* userdata) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata"); + if (ctx) + ctx->passwd_userdata = userdata; } -#if FIPS_VERSION_GE(5,1) - if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) { - if (ret == WOLFSSL_SUCCESS) - ret = WC_CLEANUP_E; - } -#endif -#ifdef HAVE_GLOBAL_RNG -#ifndef WOLFSSL_MUTEX_INITIALIZER - if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) { - if (ret == WOLFSSL_SUCCESS) - ret = BAD_MUTEX_E; + void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb* + cb) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb"); + if (ctx) + ctx->passwd_cb = cb; } - globalRNGMutex_valid = 0; -#endif /* !WOLFSSL_MUTEX_INITIALIZER */ - - #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG) - wolfSSL_FIPS_drbg_free(gDrbgDefCtx); - gDrbgDefCtx = NULL; - #endif -#endif -#if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ - defined(WOLFSSL_WPAS_SMALL) - crypto_ex_cb_free(crypto_ex_cb_ctx_session); - crypto_ex_cb_ctx_session = NULL; -#endif - -#ifdef WOLFSSL_MEM_FAIL_COUNT - wc_MemFailCount_Free(); -#endif - - return ret; -} + wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx) + { + if (ctx == NULL || ctx->passwd_cb == NULL) { + return NULL; + } -void SetupSession(WOLFSSL* ssl) -{ - WOLFSSL_SESSION* session = ssl->session; + return ctx->passwd_cb; + } - WOLFSSL_ENTER("SetupSession"); - if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) { - /* Make sure the session ID is available when the user calls any - * get_session API */ - if (!session->haveAltSessionID) { - XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN); - session->sessionIDSz = ssl->arrays->sessionIDSz; - } - else { - XMEMCPY(session->sessionID, session->altSessionID, ID_LEN); - session->sessionIDSz = ID_LEN; + void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx) + { + if (ctx == NULL) { + return NULL; } - } - session->side = (byte)ssl->options.side; - if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) - XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN); - session->haveEMS = ssl->options.haveEMS; -#ifdef WOLFSSL_SESSION_ID_CTX - /* If using compatibility layer then check for and copy over session context - * id. */ - if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) { - XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz); - session->sessionCtxSz = ssl->sessionCtxSz; - } -#endif - session->timeout = ssl->timeout; -#ifndef NO_ASN_TIME - session->bornOn = LowResTimer(); -#endif -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - session->version = ssl->version; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - session->cipherSuite0 = ssl->options.cipherSuite0; - session->cipherSuite = ssl->options.cipherSuite; -#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - session->peerVerifyRet = (byte)ssl->peerVerifyRet; -#endif - session->isSetup = 1; -} -#ifndef NO_SESSION_CACHE + return ctx->passwd_userdata; + } -WOLFSSL_ABI -void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm) -{ - /* static table now, no flushing needed */ - (void)ctx; - (void)tm; -} +#endif /* WOLFSSL_ENCRYPTED_KEYS */ -void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm) -{ - int i, j; - byte id[ID_LEN]; - (void)ctx; - XMEMSET(id, 0, ID_LEN); - WOLFSSL_ENTER("wolfSSL_flush_sessions"); - for (i = 0; i < SESSION_ROWS; ++i) { - if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { - WOLFSSL_MSG("Session cache mutex lock failed"); - return; - } - for (j = 0; j < SESSIONS_PER_ROW; j++) { -#ifdef SESSION_CACHE_DYNAMIC_MEM - WOLFSSL_SESSION* s = SessionCache[i].Sessions[j]; +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) + unsigned long wolfSSL_ERR_get_error(void) + { + WOLFSSL_ENTER("wolfSSL_ERR_get_error"); +#ifdef WOLFSSL_HAVE_ERROR_QUEUE + return wc_GetErrorNodeErr(); #else - WOLFSSL_SESSION* s = &SessionCache[i].Sessions[j]; -#endif - if ( -#ifdef SESSION_CACHE_DYNAMIC_MEM - s != NULL && -#endif - XMEMCMP(s->sessionID, id, ID_LEN) != 0 && - s->bornOn + s->timeout < (word32)tm - ) - { - EvictSessionFromCache(s); -#ifdef SESSION_CACHE_DYNAMIC_MEM - XFREE(s, s->heap, DYNAMIC_TYPE_SESSION); - SessionCache[i].Sessions[j] = NULL; + return (unsigned long)(0 - NOT_COMPILED_IN); #endif - } - } - SESSION_ROW_UNLOCK(&SessionCache[i]); } -} - - -/* set ssl session timeout in seconds */ -WOLFSSL_ABI -int wolfSSL_set_timeout(WOLFSSL* ssl, unsigned int to) -{ - if (ssl == NULL) - return BAD_FUNC_ARG; - - if (to == 0) - to = WOLFSSL_SESSION_TIMEOUT; - ssl->timeout = to; - - return WOLFSSL_SUCCESS; -} - +#endif -/** - * Sets ctx session timeout in seconds. - * The timeout value set here should be reflected in the - * "session ticket lifetime hint" if this API works in the openssl compat-layer. - * Therefore wolfSSL_CTX_set_TicketHint is called internally. - * Arguments: - * - ctx WOLFSSL_CTX object which the timeout is set to - * - to timeout value in second - * Returns: - * WOLFSSL_SUCCESS on success, BAD_FUNC_ARG on failure. - * When WOLFSSL_ERROR_CODE_OPENSSL is defined, returns previous timeout value - * on success, BAD_FUNC_ARG on failure. - */ -WOLFSSL_ABI -int wolfSSL_CTX_set_timeout(WOLFSSL_CTX* ctx, unsigned int to) -{ - #if defined(WOLFSSL_ERROR_CODE_OPENSSL) - word32 prev_timeout = 0; - #endif +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) - int ret = WOLFSSL_SUCCESS; - (void)ret; + int wolfSSL_num_locks(void) + { + return 0; + } - if (ctx == NULL) - ret = BAD_FUNC_ARG; + void wolfSSL_set_locking_callback(mutex_cb* f) + { + WOLFSSL_ENTER("wolfSSL_set_locking_callback"); - if (ret == WOLFSSL_SUCCESS) { - #if defined(WOLFSSL_ERROR_CODE_OPENSSL) - prev_timeout = ctx->timeout; - #endif - if (to == 0) { - ctx->timeout = WOLFSSL_SESSION_TIMEOUT; - } - else { - ctx->timeout = to; - } - } -#if defined(OPENSSL_EXTRA) && defined(HAVE_SESSION_TICKET) && \ - !defined(NO_WOLFSSL_SERVER) - if (ret == WOLFSSL_SUCCESS) { - if (to == 0) { - ret = wolfSSL_CTX_set_TicketHint(ctx, SESSION_TICKET_HINT_DEFAULT); - } - else { - ret = wolfSSL_CTX_set_TicketHint(ctx, to); + if (wc_SetMutexCb(f) != 0) { + WOLFSSL_MSG("Error when setting mutex call back"); } } -#endif /* OPENSSL_EXTRA && HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER */ - -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - if (ret == WOLFSSL_SUCCESS) { - return prev_timeout; - } - else { - return ret; - } -#else - return ret; -#endif /* WOLFSSL_ERROR_CODE_OPENSSL */ -} - -#ifndef NO_CLIENT_CACHE - -/* Get Session from Client cache based on id/len, return NULL on failure */ -WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len) -{ - WOLFSSL_SESSION* ret = NULL; - word32 row; - int idx; - int count; - int error = 0; - ClientSession* clSess; - - WOLFSSL_ENTER("wolfSSL_GetSessionClient"); + mutex_cb* wolfSSL_get_locking_callback(void) + { + WOLFSSL_ENTER("wolfSSL_get_locking_callback"); - if (ssl->ctx->sessionCacheOff) { - WOLFSSL_MSG("Session Cache off"); - return NULL; + return wc_GetMutexCb(); } - if (ssl->options.side == WOLFSSL_SERVER_END) - return NULL; - len = min(SERVER_ID_LEN, (word32)len); - - /* Do not access ssl->ctx->get_sess_cb from here. It is using a different - * set of ID's */ + typedef unsigned long (idCb)(void); + static idCb* inner_idCb = NULL; - row = HashObject(id, len, &error) % CLIENT_SESSION_ROWS; - if (error != 0) { - WOLFSSL_MSG("Hash session failed"); - return NULL; + unsigned long wolfSSL_thread_id(void) + { + if (inner_idCb != NULL) { + return inner_idCb(); + } + else { + return 0; + } } - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - return NULL; - } - /* start from most recently used */ - count = min((word32)ClientCache[row].totalCount, CLIENT_SESSIONS_PER_ROW); - idx = ClientCache[row].nextIdx - 1; - if (idx < 0 || idx >= CLIENT_SESSIONS_PER_ROW) { - idx = CLIENT_SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */ + void wolfSSL_set_id_callback(unsigned long (*f)(void)) + { + inner_idCb = f; } - clSess = ClientCache[row].Clients; - for (; count > 0; --count) { - WOLFSSL_SESSION* current; - SessionRow* sessRow; +#ifdef WOLFSSL_HAVE_ERROR_QUEUE +#ifndef NO_BIO + /* print out and clear all errors */ + void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio) + { + const char* file = NULL; + const char* reason = NULL; + int ret; + int line = 0; + char buf[WOLFSSL_MAX_ERROR_SZ * 2]; - if (clSess[idx].serverRow >= SESSION_ROWS) { - WOLFSSL_MSG("Client cache serverRow invalid"); - break; - } + WOLFSSL_ENTER("wolfSSL_ERR_print_errors"); - /* lock row */ - sessRow = &SessionCache[clSess[idx].serverRow]; - if (SESSION_ROW_RD_LOCK(sessRow) != 0) { - WOLFSSL_MSG("Session cache row lock failure"); - break; + if (bio == NULL) { + WOLFSSL_MSG("BIO passed in was null"); + return; } -#ifdef SESSION_CACHE_DYNAMIC_MEM - current = sessRow->Sessions[clSess[idx].serverIdx]; -#else - current = &sessRow->Sessions[clSess[idx].serverIdx]; -#endif - if (current && XMEMCMP(current->serverID, id, len) == 0) { - WOLFSSL_MSG("Found a serverid match for client"); - if (LowResTimer() < (current->bornOn + current->timeout)) { - WOLFSSL_MSG("Session valid"); - ret = current; - SESSION_ROW_UNLOCK(sessRow); - break; - } else { - WOLFSSL_MSG("Session timed out"); /* could have more for id */ + do { + ret = wc_PeekErrorNode(0, &file, &reason, &line); + if (ret >= 0) { + const char* r = wolfSSL_ERR_reason_error_string(0 - ret); + if (XSNPRINTF(buf, sizeof(buf), + "error:%d:wolfSSL library:%s:%s:%d\n", + ret, r, file, line) + >= (int)sizeof(buf)) + { + WOLFSSL_MSG("Buffer overrun formatting error message"); } - } else { - WOLFSSL_MSG("ServerID not a match from client table"); + wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf)); + wc_RemoveErrorNode(0); + } + } while (ret >= 0); + if (wolfSSL_BIO_write(bio, "", 1) != 1) { + WOLFSSL_MSG("Issue writing final string terminator"); } - SESSION_ROW_UNLOCK(sessRow); - - idx = idx > 0 ? idx - 1 : CLIENT_SESSIONS_PER_ROW - 1; } +#endif /* !NO_BIO */ +#endif /* WOLFSSL_HAVE_ERROR_QUEUE */ - wc_UnLockMutex(&clisession_mutex); - - return ret; -} - -#endif /* !NO_CLIENT_CACHE */ - -static int SslSessionCacheOff(const WOLFSSL* ssl, const WOLFSSL_SESSION* session) -{ - (void)session; - return ssl->options.sessionCacheOff - #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_FORCE_CACHE_ON_TICKET) - && session->ticketLen == 0 - #endif - ; -} +#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */ -#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ - defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) -/** - * SessionTicketNoncePrealloc() - prealloc a buffer for ticket nonces - * @output: [in] pointer to WOLFSSL_SESSION object that will soon be a - * destination of a session duplication - * @buf: [out] address of the preallocated buf - * @len: [out] len of the preallocated buf - * - * prealloc a buffer that will likely suffice to contain a ticket nonce. It's - * used when copying session under lock, when syscalls need to be avoided. If - * output already has a dynamic buffer, it's reused. +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ + defined(HAVE_SECRET_CALLBACK) +#if !defined(NO_WOLFSSL_SERVER) +/* Return the amount of random bytes copied over or error case. + * ssl : ssl struct after handshake + * out : buffer to hold random bytes + * outSz : either 0 (return max buffer sz) or size of out buffer */ -static int SessionTicketNoncePrealloc(byte** buf, byte* len, void *heap) +size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out, + size_t outSz) { - (void)heap; + size_t size; - *buf = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_NONCE_LEN, heap, - DYNAMIC_TYPE_SESSION_TICK); - if (*buf == NULL) { - WOLFSSL_MSG("Failed to preallocate ticket nonce buffer"); - *len = 0; - return 1; + /* return max size of buffer */ + if (outSz == 0) { + return RAN_LEN; } - *len = PREALLOC_SESSION_TICKET_NONCE_LEN; - return 0; -} -#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ - -static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, - WOLFSSL_SESSION* output, int avoidSysCalls, byte* ticketNonceBuf, - byte* ticketNonceLen, byte* preallocUsed); + if (ssl == NULL || out == NULL) { + return 0; + } -void TlsSessionCacheUnlockRow(word32 row) -{ - SessionRow* sessRow; + if (ssl->arrays == NULL) { + WOLFSSL_MSG("Arrays struct not saved after handshake"); + return 0; + } - sessRow = &SessionCache[row]; - (void)sessRow; - SESSION_ROW_UNLOCK(sessRow); -} - -/* Don't use this function directly. Use TlsSessionCacheGetAndRdLock and - * TlsSessionCacheGetAndWrLock to fully utilize compiler const support. */ -static int TlsSessionCacheGetAndLock(const byte *id, - const WOLFSSL_SESSION **sess, word32 *lockedRow, byte readOnly, byte side) -{ - SessionRow *sessRow; - const WOLFSSL_SESSION *s; - word32 row; - int count; - int error; - int idx; - - *sess = NULL; - row = HashObject(id, ID_LEN, &error) % SESSION_ROWS; - if (error != 0) - return error; - sessRow = &SessionCache[row]; - if (readOnly) - error = SESSION_ROW_RD_LOCK(sessRow); - else - error = SESSION_ROW_WR_LOCK(sessRow); - if (error != 0) - return FATAL_ERROR; - - /* start from most recently used */ - count = min((word32)sessRow->totalCount, SESSIONS_PER_ROW); - idx = sessRow->nextIdx - 1; - if (idx < 0 || idx >= SESSIONS_PER_ROW) { - idx = SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */ - } - for (; count > 0; --count) { -#ifdef SESSION_CACHE_DYNAMIC_MEM - s = sessRow->Sessions[idx]; -#else - s = &sessRow->Sessions[idx]; -#endif - if (s && XMEMCMP(s->sessionID, id, ID_LEN) == 0 && s->side == side) { - *sess = s; - break; - } - idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1; - } - if (*sess == NULL) { - SESSION_ROW_UNLOCK(sessRow); + if (outSz > RAN_LEN) { + size = RAN_LEN; } else { - *lockedRow = row; + size = outSz; } - return 0; + XMEMCPY(out, ssl->arrays->serverRandom, size); + return size; } +#endif /* !NO_WOLFSSL_SERVER */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */ -static int CheckSessionMatch(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess) -{ - if (ssl == NULL || sess == NULL) - return 0; #ifdef OPENSSL_EXTRA - if (ssl->sessionCtxSz > 0 && (ssl->sessionCtxSz != sess->sessionCtxSz || - XMEMCMP(ssl->sessionCtx, sess->sessionCtx, sess->sessionCtxSz) != 0)) - return 0; -#endif -#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) - if (IsAtLeastTLSv1_3(ssl->version) != IsAtLeastTLSv1_3(sess->version)) - return 0; -#endif - return 1; -} - -int TlsSessionCacheGetAndRdLock(const byte *id, const WOLFSSL_SESSION **sess, - word32 *lockedRow, byte side) -{ - return TlsSessionCacheGetAndLock(id, sess, lockedRow, 1, side); -} - -int TlsSessionCacheGetAndWrLock(const byte *id, WOLFSSL_SESSION **sess, - word32 *lockedRow, byte side) -{ - return TlsSessionCacheGetAndLock(id, (const WOLFSSL_SESSION**)sess, - lockedRow, 0, side); -} - -int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) +#if !defined(NO_WOLFSSL_SERVER) +/* Used to get the peer ephemeral public key sent during the connection + * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called + * before the ephemeral key is stored. + * return WOLFSSL_SUCCESS on success */ +int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey) { - const WOLFSSL_SESSION* sess = NULL; - const byte* id = NULL; - word32 row; - int error = 0; -#ifdef HAVE_SESSION_TICKET -#ifndef WOLFSSL_SMALL_STACK - byte tmpTicket[PREALLOC_SESSION_TICKET_LEN]; -#else - byte* tmpTicket = NULL; -#endif -#ifdef WOLFSSL_TLS13 - byte *preallocNonce = NULL; - byte preallocNonceLen = 0; - byte preallocNonceUsed = 0; -#endif /* WOLFSSL_TLS13 */ - byte tmpBufSet = 0; -#endif -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - WOLFSSL_X509* peer = NULL; -#endif - byte bogusID[ID_LEN]; - byte bogusIDSz = 0; + WOLFSSL_EVP_PKEY* ret = NULL; - WOLFSSL_ENTER("wolfSSL_GetSessionFromCache"); + WOLFSSL_ENTER("wolfSSL_get_server_tmp_key"); - if (output == NULL) { - WOLFSSL_MSG("NULL output"); + if (ssl == NULL || pkey == NULL) { + WOLFSSL_MSG("Bad argument passed in"); return WOLFSSL_FAILURE; } - if (SslSessionCacheOff(ssl, ssl->session)) - return WOLFSSL_FAILURE; - - if (ssl->options.haveSessionId == 0 && !ssl->session->haveAltSessionID) - return WOLFSSL_FAILURE; - -#ifdef HAVE_SESSION_TICKET - if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1) - return WOLFSSL_FAILURE; -#endif +#ifdef HAVE_ECC + if (ssl->peerEccKey != NULL) { + unsigned char* der; + const unsigned char* pt; + unsigned int derSz = 0; + int sz; - XMEMSET(bogusID, 0, sizeof(bogusID)); - if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL - && !ssl->session->haveAltSessionID) - id = ssl->arrays->sessionID; - else if (ssl->session->haveAltSessionID) { - id = ssl->session->altSessionID; - /* We want to restore the bogus ID for TLS compatibility */ - if (output == ssl->session) { - XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN); - bogusIDSz = ssl->session->sessionIDSz; + PRIVATE_KEY_UNLOCK(); + if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz) != + LENGTH_ONLY_E) { + WOLFSSL_MSG("get ecc der size failed"); + PRIVATE_KEY_LOCK(); + return WOLFSSL_FAILURE; } - } - else - id = ssl->session->sessionID; - - -#ifdef HAVE_EXT_CACHE - if (ssl->ctx->get_sess_cb != NULL) { - int copy = 0; - int found = 0; - WOLFSSL_SESSION* extSess; - /* Attempt to retrieve the session from the external cache. */ - WOLFSSL_MSG("Calling external session cache"); - extSess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, ©); - if ((extSess != NULL) - && CheckSessionMatch(ssl, extSess) - ) { - WOLFSSL_MSG("Session found in external cache"); - found = 1; + PRIVATE_KEY_LOCK(); - error = wolfSSL_DupSession(extSess, output, 0); -#ifdef HAVE_EX_DATA - extSess->ownExData = 1; - output->ownExData = 0; -#endif - /* We want to restore the bogus ID for TLS compatibility */ - if (ssl->session->haveAltSessionID && - output == ssl->session) { - XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN); - ssl->session->sessionIDSz = bogusIDSz; - } + derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO; + der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY); + if (der == NULL) { + WOLFSSL_MSG("Memory error"); + return WOLFSSL_FAILURE; } - /* If copy not set then free immediately */ - if (extSess != NULL && !copy) - wolfSSL_FreeSession(ssl->ctx, extSess); - if (found) - return error; - WOLFSSL_MSG("Session not found in external cache"); - } - - if (ssl->options.internalCacheLookupOff) { - WOLFSSL_MSG("Internal cache lookup turned off"); - return WOLFSSL_FAILURE; - } -#endif -#ifdef HAVE_SESSION_TICKET - if (output->ticket == NULL || - output->ticketLenAlloc < PREALLOC_SESSION_TICKET_LEN) { -#ifdef WOLFSSL_SMALL_STACK - tmpTicket = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_LEN, output->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (tmpTicket == NULL) { - WOLFSSL_MSG("tmpTicket malloc failed"); + if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) { + WOLFSSL_MSG("get ecc der failed"); + XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY); return WOLFSSL_FAILURE; } -#endif - if (output->ticketLenAlloc) - XFREE(output->ticket, output->heap, DYNAMIC_TYPE_SESSION_TICK); - output->ticket = tmpTicket; /* cppcheck-suppress autoVariables - */ - output->ticketLenAlloc = PREALLOC_SESSION_TICKET_LEN; - output->ticketLen = 0; - tmpBufSet = 1; - } -#endif - -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (output->peer != NULL) { - wolfSSL_X509_free(output->peer); - output->peer = NULL; + pt = der; /* in case pointer gets advanced */ + ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz); + XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY); } #endif -#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && \ - defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (output->ticketNonce.data != output->ticketNonce.dataStatic) { - XFREE(output->ticketNonce.data, output->heap, - DYNAMIC_TYPE_SESSION_TICK); - output->ticketNonce.data = output->ticketNonce.dataStatic; - output->ticketNonce.len = 0; - } - error = SessionTicketNoncePrealloc(&preallocNonce, &preallocNonceLen, - output->heap); - if (error != 0) { - if (tmpBufSet) { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - } -#ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); + *pkey = ret; +#ifdef HAVE_ECC + if (ret != NULL) + return WOLFSSL_SUCCESS; + else #endif return WOLFSSL_FAILURE; - } -#endif /* WOLFSSL_TLS13 && HAVE_SESSION_TICKET*/ - - /* init to avoid clang static analyzer false positive */ - row = 0; - error = TlsSessionCacheGetAndRdLock(id, &sess, &row, (byte)ssl->options.side); - error = (error == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - if (error != WOLFSSL_SUCCESS || sess == NULL) { - WOLFSSL_MSG("Get Session from cache failed"); - error = WOLFSSL_FAILURE; -#ifdef HAVE_SESSION_TICKET - if (tmpBufSet) { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - } -#ifdef WOLFSSL_TLS13 - if (preallocNonce != NULL) { - XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); - preallocNonce = NULL; - } -#endif /* WOLFSSL_TLS13 */ -#ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) { - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); - tmpTicket = NULL; - } -#endif -#endif - } - else { - if (!CheckSessionMatch(ssl, sess)) { - WOLFSSL_MSG("Invalid session: can't be used in this context"); - TlsSessionCacheUnlockRow(row); - error = WOLFSSL_FAILURE; - } - else if (LowResTimer() >= (sess->bornOn + sess->timeout)) { - WOLFSSL_SESSION* wrSess = NULL; - WOLFSSL_MSG("Invalid session: timed out"); - sess = NULL; - TlsSessionCacheUnlockRow(row); - /* Attempt to get a write lock */ - error = TlsSessionCacheGetAndWrLock(id, &wrSess, &row, - (byte)ssl->options.side); - if (error == 0 && wrSess != NULL) { - EvictSessionFromCache(wrSess); - TlsSessionCacheUnlockRow(row); - } - error = WOLFSSL_FAILURE; - } - } - - /* mollify confused cppcheck nullPointer warning. */ - if (sess == NULL) - error = WOLFSSL_FAILURE; - - if (error == WOLFSSL_SUCCESS) { -#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) - error = wolfSSL_DupSessionEx(sess, output, 1, - preallocNonce, &preallocNonceLen, &preallocNonceUsed); -#else - error = wolfSSL_DupSession(sess, output, 1); -#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ -#ifdef HAVE_EX_DATA - output->ownExData = !sess->ownExData; /* Session may own ex_data */ -#endif - TlsSessionCacheUnlockRow(row); - } - - /* We want to restore the bogus ID for TLS compatibility */ - if (ssl->session->haveAltSessionID && - output == ssl->session) { - XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN); - ssl->session->sessionIDSz = bogusIDSz; - } - -#ifdef HAVE_SESSION_TICKET - if (tmpBufSet) { - if (error == WOLFSSL_SUCCESS) { - if (output->ticketLen > SESSION_TICKET_LEN) { - output->ticket = (byte*)XMALLOC(output->ticketLen, output->heap, - DYNAMIC_TYPE_SESSION_TICK); - if (output->ticket == NULL) { - error = WOLFSSL_FAILURE; - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - output->ticketLen = 0; - } - } - else { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - } - } - else { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - output->ticketLen = 0; - } - if (error == WOLFSSL_SUCCESS) { - XMEMCPY(output->ticket, tmpTicket, output->ticketLen); - } - } -#ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (error == WOLFSSL_SUCCESS && preallocNonceUsed) { - if (preallocNonceLen < PREALLOC_SESSION_TICKET_NONCE_LEN) { - /* buffer bigger than needed */ -#ifndef XREALLOC - output->ticketNonce.data = (byte*)XMALLOC(preallocNonceLen, - output->heap, DYNAMIC_TYPE_SESSION_TICK); - if (output->ticketNonce.data != NULL) - XMEMCPY(output->ticketNonce.data, preallocNonce, - preallocNonceLen); - XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); - preallocNonce = NULL; -#else - output->ticketNonce.data = XREALLOC(preallocNonce, - preallocNonceLen, output->heap, DYNAMIC_TYPE_SESSION_TICK); - if (output->ticketNonce.data != NULL) { - /* don't free the reallocated pointer */ - preallocNonce = NULL; - } -#endif /* !XREALLOC */ - if (output->ticketNonce.data == NULL) { - output->ticketNonce.data = output->ticketNonce.dataStatic; - output->ticketNonce.len = 0; - error = WOLFSSL_FAILURE; - /* preallocNonce will be free'd after the if */ - } - } - else { - output->ticketNonce.data = preallocNonce; - output->ticketNonce.len = preallocNonceLen; - preallocNonce = NULL; - } - } - if (preallocNonce != NULL) - XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ - -#endif - -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (peer != NULL) { - wolfSSL_X509_free(peer); - } -#endif - - return error; } -WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret, - byte restoreSessionCerts) +#endif /* !NO_WOLFSSL_SERVER */ + +/** + * This function checks if any compiled in protocol versions are + * left enabled after calls to set_min or set_max API. + * @param major The SSL/TLS major version + * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no + * protocol versions are left enabled. + */ +static int CheckSslMethodVersion(byte major, unsigned long options) { - WOLFSSL_SESSION* ret = NULL; + int sanityConfirmed = 0; - (void)restoreSessionCerts; /* Kept for compatibility */ + (void)options; - if (wolfSSL_GetSessionFromCache(ssl, ssl->session) == WOLFSSL_SUCCESS) { - ret = ssl->session; + switch (major) { + #ifndef NO_TLS + case SSLv3_MAJOR: + #ifdef WOLFSSL_ALLOW_SSLV3 + if (!(options & WOLFSSL_OP_NO_SSLv3)) { + sanityConfirmed = 1; + } + #endif + #ifndef NO_OLD_TLS + if (!(options & WOLFSSL_OP_NO_TLSv1)) + sanityConfirmed = 1; + if (!(options & WOLFSSL_OP_NO_TLSv1_1)) + sanityConfirmed = 1; + #endif + #ifndef WOLFSSL_NO_TLS12 + if (!(options & WOLFSSL_OP_NO_TLSv1_2)) + sanityConfirmed = 1; + #endif + #ifdef WOLFSSL_TLS13 + if (!(options & WOLFSSL_OP_NO_TLSv1_3)) + sanityConfirmed = 1; + #endif + break; + #endif + #ifdef WOLFSSL_DTLS + case DTLS_MAJOR: + sanityConfirmed = 1; + break; + #endif + default: + WOLFSSL_MSG("Invalid major version"); + return WOLFSSL_FAILURE; } - else { - WOLFSSL_MSG("wolfSSL_GetSessionFromCache did not return a session"); + if (!sanityConfirmed) { + WOLFSSL_MSG("All compiled in TLS versions disabled"); + return WOLFSSL_FAILURE; } - - if (ret != NULL && masterSecret != NULL) - XMEMCPY(masterSecret, ret->masterSecret, SECRET_LEN); - - return ret; + return WOLFSSL_SUCCESS; } -int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) -{ - SessionRow* sessRow = NULL; - int ret = WOLFSSL_SUCCESS; +/** + * protoVerTbl holds (D)TLS version numbers in ascending order. + * Except DTLS versions, the newer version is located in the latter part of + * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and + * wolfSSL_CTX_set_max_proto_version. + */ +static const int protoVerTbl[] = { + SSL3_VERSION, + TLS1_VERSION, + TLS1_1_VERSION, + TLS1_2_VERSION, + TLS1_3_VERSION, + DTLS1_VERSION, + DTLS1_2_VERSION +}; +/* number of protocol versions listed in protoVerTbl */ +#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int)) - session = ClientSessionToSession(session); +/** + * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol + * version to use by SSL objects created from this WOLFSSL_CTX. + * This API guarantees that a version of SSL/TLS lower than specified + * here will not be allowed. If the version specified is not compiled in + * then this API sets the lowest compiled in protocol version. + * This API also accept 0 as version, to set the minimum version automatically. + * CheckSslMethodVersion() is called to check if any remaining protocol versions + * are enabled. + * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects + * @param version Any of the following + * * 0 + * * SSL3_VERSION + * * TLS1_VERSION + * * TLS1_1_VERSION + * * TLS1_2_VERSION + * * TLS1_3_VERSION + * * DTLS1_VERSION + * * DTLS1_2_VERSION + * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no + * protocol versions are left enabled. + */ +static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex"); - if (ssl == NULL || session == NULL || !session->isSetup) { - WOLFSSL_MSG("ssl or session NULL or not set up"); + if (ctx == NULL) { return WOLFSSL_FAILURE; } - /* We need to lock the session as the first step if its in the cache */ - if (session->type == WOLFSSL_SESSION_TYPE_CACHE) { - if (session->cacheRow < SESSION_ROWS) { - sessRow = &SessionCache[session->cacheRow]; - if (SESSION_ROW_RD_LOCK(sessRow) != 0) { - WOLFSSL_MSG("Session row lock failed"); - return WOLFSSL_FAILURE; - } - } - } - - if (ret == WOLFSSL_SUCCESS && ssl->options.side != WOLFSSL_NEITHER_END && - (byte)ssl->options.side != session->side) { - WOLFSSL_MSG("Setting session for wrong role"); - ret = WOLFSSL_FAILURE; - } - - if (ret == WOLFSSL_SUCCESS) { - if (ssl->session == session) { - WOLFSSL_MSG("ssl->session and session same"); - } - else if (session->type != WOLFSSL_SESSION_TYPE_CACHE) { - if (wolfSSL_SESSION_up_ref(session) == WOLFSSL_SUCCESS) { - wolfSSL_FreeSession(ssl->ctx, ssl->session); - ssl->session = session; - } - else - ret = WOLFSSL_FAILURE; - } - else { - ret = wolfSSL_DupSession(session, ssl->session, 0); - if (ret != WOLFSSL_SUCCESS) - WOLFSSL_MSG("Session duplicate failed"); - } - } - - /* Let's copy over the altSessionID for local cache purposes */ - if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID && - ssl->session != session) { - ssl->session->haveAltSessionID = 1; - XMEMCPY(ssl->session->altSessionID, session->altSessionID, ID_LEN); - } - - if (sessRow != NULL) { - SESSION_ROW_UNLOCK(sessRow); - sessRow = NULL; - } - - /* Note: the `session` variable cannot be used below, since the row is - * un-locked */ - - if (ret != WOLFSSL_SUCCESS) - return ret; - -#ifdef WOLFSSL_SESSION_ID_CTX - /* check for application context id */ - if (ssl->sessionCtxSz > 0) { - if (XMEMCMP(ssl->sessionCtx, ssl->session->sessionCtx, ssl->sessionCtxSz)) { - /* context id did not match! */ - WOLFSSL_MSG("Session context did not match"); - return WOLFSSL_FAILURE; - } - } -#endif /* WOLFSSL_SESSION_ID_CTX */ - - if (LowResTimer() >= (ssl->session->bornOn + ssl->session->timeout)) { -#if !defined(OPENSSL_EXTRA) || !defined(WOLFSSL_ERROR_CODE_OPENSSL) - return WOLFSSL_FAILURE; /* session timed out */ -#else /* defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL) */ - WOLFSSL_MSG("Session is expired but return success for " - "OpenSSL compatibility"); + switch (version) { +#ifndef NO_TLS + case SSL3_VERSION: +#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) + ctx->minDowngrade = SSLv3_MINOR; + break; #endif + case TLS1_VERSION: + #ifdef WOLFSSL_ALLOW_TLSV10 + ctx->minDowngrade = TLSv1_MINOR; + break; + #endif + case TLS1_1_VERSION: + #ifndef NO_OLD_TLS + ctx->minDowngrade = TLSv1_1_MINOR; + break; + #endif + case TLS1_2_VERSION: + #ifndef WOLFSSL_NO_TLS12 + ctx->minDowngrade = TLSv1_2_MINOR; + break; + #endif + case TLS1_3_VERSION: + #ifdef WOLFSSL_TLS13 + ctx->minDowngrade = TLSv1_3_MINOR; + break; + #endif +#endif +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + #ifndef NO_OLD_TLS + ctx->minDowngrade = DTLS_MINOR; + break; + #endif + case DTLS1_2_VERSION: + ctx->minDowngrade = DTLSv1_2_MINOR; + break; +#endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; } - ssl->options.resuming = 1; - ssl->options.haveEMS = ssl->session->haveEMS; -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - ssl->version = ssl->session->version; - if (IsAtLeastTLSv1_3(ssl->version)) - ssl->options.tls1_3 = 1; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - ssl->options.cipherSuite0 = ssl->session->cipherSuite0; - ssl->options.cipherSuite = ssl->session->cipherSuite; + switch (version) { +#ifndef NO_TLS + case TLS1_3_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2); + FALL_THROUGH; + case TLS1_2_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1); + FALL_THROUGH; + case TLS1_1_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1); + FALL_THROUGH; + case TLS1_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3); + break; + case SSL3_VERSION: + case SSL2_VERSION: + /* Nothing to do here */ + break; #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet; +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + case DTLS1_2_VERSION: + break; #endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; + } - return WOLFSSL_SUCCESS; + return CheckSslMethodVersion(ctx->method->version.major, ctx->mask); } - -#ifdef WOLFSSL_SESSION_STATS -static int get_locked_session_stats(word32* active, word32* total, - word32* peak); -#endif - -#ifndef NO_CLIENT_CACHE -ClientSession* AddSessionToClientCache(int side, int row, int idx, byte* serverID, - word16 idLen, const byte* sessionID, - word16 useTicket) +/* Sets the min protocol version allowed with WOLFSSL_CTX + * returns WOLFSSL_SUCCESS on success */ +int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version) { - int error = -1; - word32 clientRow = 0, clientIdx = 0; - ClientSession* ret = NULL; - - (void)useTicket; - if (side == WOLFSSL_CLIENT_END - && row != INVALID_SESSION_ROW - && (idLen -#ifdef HAVE_SESSION_TICKET - || useTicket == 1 -#endif - || serverID != NULL - )) { + int ret; + int proto = 0; + int maxProto = 0; + int i; + int idx = 0; - WOLFSSL_MSG("Trying to add client cache entry"); + WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version"); - if (idLen) { - clientRow = HashObject(serverID, - idLen, &error) % CLIENT_SESSION_ROWS; - } - else if (serverID != NULL) { - clientRow = HashObject(sessionID, - ID_LEN, &error) % CLIENT_SESSION_ROWS; - } - else { - error = -1; - } - if (error == 0 && wc_LockMutex(&clisession_mutex) == 0) { - clientIdx = ClientCache[clientRow].nextIdx; - if (clientIdx < CLIENT_SESSIONS_PER_ROW) { - ClientCache[clientRow].Clients[clientIdx].serverRow = - (word16)row; - ClientCache[clientRow].Clients[clientIdx].serverIdx = - (word16)idx; - if (sessionID != NULL) { - word32 sessionIDHash = HashObject(sessionID, ID_LEN, - &error); - if (error == 0) { - ClientCache[clientRow].Clients[clientIdx].sessionIDHash - = sessionIDHash; - } - } - } - else { - error = -1; - ClientCache[clientRow].nextIdx = 0; /* reset index as safety */ - WOLFSSL_MSG("Invalid client cache index! " - "Possible corrupted memory"); + if (ctx == NULL) { + return WOLFSSL_FAILURE; + } + if (version != 0) { + proto = version; + ctx->minProto = 0; /* turn min proto flag off */ + for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { + if (protoVerTbl[i] == version) { + break; } - if (error == 0) { - WOLFSSL_MSG("Adding client cache entry"); - - ret = &ClientCache[clientRow].Clients[clientIdx]; - - if (ClientCache[clientRow].totalCount < CLIENT_SESSIONS_PER_ROW) - ClientCache[clientRow].totalCount++; - ClientCache[clientRow].nextIdx++; - ClientCache[clientRow].nextIdx %= CLIENT_SESSIONS_PER_ROW; + } + } + else { + /* when 0 is specified as version, try to find out the min version */ + for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { + ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]); + if (ret == WOLFSSL_SUCCESS) { + proto = protoVerTbl[i]; + ctx->minProto = 1; /* turn min proto flag on */ + break; } - - wc_UnLockMutex(&clisession_mutex); } - else { - WOLFSSL_MSG("Hash session or lock failed"); + } + + /* check case where max > min , if so then clear the NO_* options + * i is the index into the table for proto version used, see if the max + * proto version index found is smaller */ + maxProto = wolfSSL_CTX_get_max_proto_version(ctx); + for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) { + if (protoVerTbl[idx] == maxProto) { + break; } } - else { - WOLFSSL_MSG("Skipping client cache"); + if (idx < i) { + wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 | + WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 | + WOLFSSL_OP_NO_TLSv1_3); } + ret = Set_CTX_min_proto_version(ctx, proto); return ret; } -#endif /* !NO_CLIENT_CACHE */ /** - * For backwards compatibility, this API needs to be used in *ALL* functions - * that access the WOLFSSL_SESSION members directly. - * - * This API checks if the passed in session is actually a ClientSession object - * and returns the matching session cache object. Otherwise just return the - * input. ClientSession objects only occur in the ClientCache. They are not - * allocated anywhere else. + * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol + * version to use by SSL objects created from this WOLFSSL_CTX. + * This API guarantees that a version of SSL/TLS higher than specified + * here will not be allowed. If the version specified is not compiled in + * then this API sets the highest compiled in protocol version. + * This API also accept 0 as version, to set the maximum version automatically. + * CheckSslMethodVersion() is called to check if any remaining protocol versions + * are enabled. + * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects + * @param ver Any of the following + * * 0 + * * SSL3_VERSION + * * TLS1_VERSION + * * TLS1_1_VERSION + * * TLS1_2_VERSION + * * TLS1_3_VERSION + * * DTLS1_VERSION + * * DTLS1_2_VERSION + * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no + * protocol versions are left enabled. */ -WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) -{ - WOLFSSL_ENTER("ClientSessionToSession"); -#ifdef NO_SESSION_CACHE_REF - return (WOLFSSL_SESSION*)session; -#else -#ifndef NO_CLIENT_CACHE - if (session == NULL) - return NULL; - /* Check if session points into ClientCache */ - if ((byte*)session >= (byte*)ClientCache && - /* Cast to byte* to make pointer arithmetic work per byte */ - (byte*)session < ((byte*)ClientCache) + sizeof(ClientCache)) { - ClientSession* clientSession = (ClientSession*)session; - SessionRow* sessRow = NULL; - WOLFSSL_SESSION* cacheSession = NULL; - word32 sessionIDHash = 0; - int error = 0; - session = NULL; /* Default to NULL for failure case */ - if (wc_LockMutex(&clisession_mutex) != 0) { - WOLFSSL_MSG("Client cache mutex lock failed"); - return NULL; - } - if (clientSession->serverRow >= SESSION_ROWS || - clientSession->serverIdx >= SESSIONS_PER_ROW) { - WOLFSSL_MSG("Client cache serverRow or serverIdx invalid"); - error = -1; - } - /* Prevent memory access before clientSession->serverRow and - * clientSession->serverIdx are sanitized. */ - XFENCE(); - if (error == 0) { - /* Lock row */ - sessRow = &SessionCache[clientSession->serverRow]; - error = SESSION_ROW_RD_LOCK(sessRow); - if (error != 0) { - WOLFSSL_MSG("Session cache row lock failure"); - sessRow = NULL; - } - } - if (error == 0) { -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[clientSession->serverIdx]; -#else - cacheSession = &sessRow->Sessions[clientSession->serverIdx]; -#endif - if (cacheSession && cacheSession->sessionIDSz == 0) { - cacheSession = NULL; - WOLFSSL_MSG("Session cache entry not set"); - error = -1; - } - } - if (error == 0) { - /* Calculate the hash of the session ID */ - sessionIDHash = HashObject(cacheSession->sessionID, ID_LEN, - &error); - } - if (error == 0) { - /* Check the session ID hash matches */ - error = clientSession->sessionIDHash != sessionIDHash; - if (error != 0) - WOLFSSL_MSG("session ID hash don't match"); - } - if (error == 0) { - /* Hashes match */ - session = cacheSession; - WOLFSSL_MSG("Found session cache matching client session object"); - } - if (sessRow != NULL) { - SESSION_ROW_UNLOCK(sessRow); - } - wc_UnLockMutex(&clisession_mutex); - return (WOLFSSL_SESSION*)session; - } - else { - /* Plain WOLFSSL_SESSION object */ - return (WOLFSSL_SESSION*)session; - } -#else - return (WOLFSSL_SESSION*)session; -#endif -#endif -} - -int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, - const byte* id, byte idSz, int* sessionIndex, int side, - word16 useTicket, ClientSession** clientCacheEntry) +static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver) { - WOLFSSL_SESSION* cacheSession = NULL; - SessionRow* sessRow = NULL; - word32 idx = 0; -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - WOLFSSL_X509* cachePeer = NULL; - WOLFSSL_X509* addPeer = NULL; -#endif -#ifdef HAVE_SESSION_TICKET - byte* cacheTicBuff = NULL; - byte ticBuffUsed = 0; - byte* ticBuff = NULL; - int ticLen = 0; -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - byte *preallocNonce = NULL; - byte preallocNonceLen = 0; - byte preallocNonceUsed = 0; - byte *toFree = NULL; -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC */ -#endif /* HAVE_SESSION_TICKET */ - int ret = 0; - int row; - int i; - int overwrite = 0; - (void)ctx; - (void)sessionIndex; - (void)useTicket; - (void)clientCacheEntry; - - WOLFSSL_ENTER("AddSessionToCache"); - - if (idSz == 0) { - WOLFSSL_MSG("AddSessionToCache idSz == 0"); - return BAD_FUNC_ARG; - } + int ret; + WOLFSSL_ENTER("Set_CTX_max_proto_version"); - addSession = ClientSessionToSession(addSession); - if (addSession == NULL) { - WOLFSSL_MSG("AddSessionToCache is NULL"); - return MEMORY_E; + if (!ctx || !ctx->method) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } -#ifdef HAVE_SESSION_TICKET - ticLen = addSession->ticketLen; - /* Alloc Memory here to avoid syscalls during lock */ - if (ticLen > SESSION_TICKET_LEN) { - ticBuff = (byte*)XMALLOC(ticLen, NULL, - DYNAMIC_TYPE_SESSION_TICK); - if (ticBuff == NULL) { - return MEMORY_E; - } - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (addSession->ticketNonce.data != addSession->ticketNonce.dataStatic) { - /* use the AddSession->heap even if the buffer maybe saved in - * CachedSession objects. CachedSession heap and AddSession heap should - * be the same */ - preallocNonce = (byte*)XMALLOC(addSession->ticketNonce.len, - addSession->heap, DYNAMIC_TYPE_SESSION_TICK); - if (preallocNonce == NULL) { - if (ticBuff != NULL) - XFREE(ticBuff, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); - return MEMORY_E; - } - preallocNonceLen = addSession->ticketNonce.len; + switch (ver) { + case SSL2_VERSION: + WOLFSSL_MSG("wolfSSL does not support SSLv2"); + return WOLFSSL_FAILURE; +#ifndef NO_TLS + case SSL3_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1); + FALL_THROUGH; + case TLS1_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1); + FALL_THROUGH; + case TLS1_1_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2); + FALL_THROUGH; + case TLS1_2_VERSION: + wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3); + FALL_THROUGH; + case TLS1_3_VERSION: + /* Nothing to do here */ + break; +#endif +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + case DTLS1_2_VERSION: + break; +#endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; } -#endif /* WOLFSSL_TLS13 && WOLFSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */ -#endif /* HAVE_SESSION_TICKET */ - /* Find a position for the new session in cache and use that */ - /* Use the session object in the cache for external cache if required */ - row = (int)(HashObject(id, ID_LEN, &ret) % SESSION_ROWS); - if (ret != 0) { - WOLFSSL_MSG("Hash session failed"); - #ifdef HAVE_SESSION_TICKET - XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) - XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); - #endif + ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask); + if (ret == WOLFSSL_SUCCESS) { + /* Check the major */ + switch (ver) { + #ifndef NO_TLS + case SSL3_VERSION: + case TLS1_VERSION: + case TLS1_1_VERSION: + case TLS1_2_VERSION: + case TLS1_3_VERSION: + if (ctx->method->version.major != SSLv3_MAJOR) { + WOLFSSL_MSG("Mismatched protocol version"); + return WOLFSSL_FAILURE; + } + break; #endif - return ret; - } - - sessRow = &SessionCache[row]; - if (SESSION_ROW_WR_LOCK(sessRow) != 0) { - #ifdef HAVE_SESSION_TICKET - XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) - XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + #ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + case DTLS1_2_VERSION: + if (ctx->method->version.major != DTLS_MAJOR) { + WOLFSSL_MSG("Mismatched protocol version"); + return WOLFSSL_FAILURE; + } + break; #endif + } + /* Update the method */ + switch (ver) { + case SSL2_VERSION: + WOLFSSL_MSG("wolfSSL does not support SSLv2"); + return WOLFSSL_FAILURE; + #ifndef NO_TLS + case SSL3_VERSION: + ctx->method->version.minor = SSLv3_MINOR; + break; + case TLS1_VERSION: + ctx->method->version.minor = TLSv1_MINOR; + break; + case TLS1_1_VERSION: + ctx->method->version.minor = TLSv1_1_MINOR; + break; + case TLS1_2_VERSION: + ctx->method->version.minor = TLSv1_2_MINOR; + break; + case TLS1_3_VERSION: + ctx->method->version.minor = TLSv1_3_MINOR; + break; #endif - WOLFSSL_MSG("Session row lock failed"); - return BAD_MUTEX_E; - } - - for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[i]; -#else - cacheSession = &sessRow->Sessions[i]; -#endif - if (cacheSession && XMEMCMP(id, - cacheSession->sessionID, ID_LEN) == 0 && - cacheSession->side == side) { - WOLFSSL_MSG("Session already exists. Overwriting."); - overwrite = 1; - idx = i; + #ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + ctx->method->version.minor = DTLS_MINOR; break; + case DTLS1_2_VERSION: + ctx->method->version.minor = DTLSv1_2_MINOR; + break; + #endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; } } + return ret; +} - if (!overwrite) - idx = sessRow->nextIdx; -#ifdef SESSION_INDEX - if (sessionIndex != NULL) - *sessionIndex = (row << SESSIDX_ROW_SHIFT) | idx; -#endif - -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[idx]; - if (cacheSession == NULL) { - cacheSession = (WOLFSSL_SESSION*) XMALLOC(sizeof(WOLFSSL_SESSION), - sessRow->heap, DYNAMIC_TYPE_SESSION); - if (cacheSession == NULL) { - #ifdef HAVE_SESSION_TICKET - XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) - XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); - #endif - #endif - SESSION_ROW_UNLOCK(sessRow); - return MEMORY_E; - } - XMEMSET(cacheSession, 0, sizeof(WOLFSSL_SESSION)); - sessRow->Sessions[idx] = cacheSession; - } -#else - cacheSession = &sessRow->Sessions[idx]; -#endif - -#ifdef HAVE_EX_DATA - if (overwrite) { - /* Figure out who owns the ex_data */ - if (cacheSession->ownExData) { - /* Prioritize cacheSession copy */ - XMEMCPY(&addSession->ex_data, &cacheSession->ex_data, - sizeof(WOLFSSL_CRYPTO_EX_DATA)); - } - /* else will be copied in wolfSSL_DupSession call */ - } - else if (cacheSession->ownExData) { - crypto_ex_cb_free_data(cacheSession, crypto_ex_cb_ctx_session, - &cacheSession->ex_data); - cacheSession->ownExData = 0; - } -#endif - - if (!overwrite) - EvictSessionFromCache(cacheSession); - cacheSession->type = WOLFSSL_SESSION_TYPE_CACHE; - cacheSession->cacheRow = row; +/* Sets the max protocol version allowed with WOLFSSL_CTX + * returns WOLFSSL_SUCCESS on success */ +int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version) +{ + int i; + int ret = WOLFSSL_FAILURE; + int minProto; -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - /* Save the peer field to free after unlocking the row */ - if (cacheSession->peer != NULL) - cachePeer = cacheSession->peer; - cacheSession->peer = NULL; -#endif -#ifdef HAVE_SESSION_TICKET - /* If we can reuse the existing buffer in cacheSession then we won't touch - * ticBuff at all making it a very cheap malloc/free. The page on a modern - * OS will most likely not even be allocated to the process. */ - if (ticBuff != NULL && cacheSession->ticketLenAlloc < ticLen) { - /* Save pointer only if separately allocated */ - if (cacheSession->ticket != cacheSession->staticTicket) - cacheTicBuff = cacheSession->ticket; - ticBuffUsed = 1; - cacheSession->ticket = ticBuff; - cacheSession->ticketLenAlloc = (word16) ticLen; - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - /* cache entry never used */ - if (cacheSession->ticketNonce.data == NULL) - cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic; - - if (cacheSession->ticketNonce.data != - cacheSession->ticketNonce.dataStatic) { - toFree = cacheSession->ticketNonce.data; - cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic; - cacheSession->ticketNonce.len = 0; - } -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ -#endif -#ifdef SESSION_CERTS - if (overwrite && - addSession->chain.count == 0 && - cacheSession->chain.count > 0) { - /* Copy in the certs from the session */ - addSession->chain.count = cacheSession->chain.count; - XMEMCPY(addSession->chain.certs, cacheSession->chain.certs, - sizeof(x509_buffer) * cacheSession->chain.count); - } -#endif /* SESSION_CERTS */ -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - /* Don't copy the peer cert into cache */ - addPeer = addSession->peer; - addSession->peer = NULL; -#endif - cacheSession->heap = NULL; - /* Copy data into the cache object */ -#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ - defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - ret = wolfSSL_DupSessionEx(addSession, cacheSession, 1, preallocNonce, - &preallocNonceLen, &preallocNonceUsed) == WOLFSSL_FAILURE; -#else - ret = wolfSSL_DupSession(addSession, cacheSession, 1) == WOLFSSL_FAILURE; -#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC - && FIPS_VERSION_GE(5,3)*/ -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - addSession->peer = addPeer; -#endif + WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version"); - if (ret == 0) { - if (!overwrite) { - /* Increment the totalCount and the nextIdx */ - if (sessRow->totalCount < SESSIONS_PER_ROW) - sessRow->totalCount++; - sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW; - } - if (id != addSession->sessionID) { - /* ssl->session->sessionID may contain the bogus ID or we want the - * ID from the arrays object */ - XMEMCPY(cacheSession->sessionID, id, ID_LEN); - cacheSession->sessionIDSz = ID_LEN; - } -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - if (ctx->rem_sess_cb != NULL) - cacheSession->rem_sess_cb = ctx->rem_sess_cb; -#endif -#ifdef HAVE_EX_DATA - /* The session in cache now owns the ex_data */ - addSession->ownExData = 0; - cacheSession->ownExData = 1; -#endif -#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ - defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (preallocNonce != NULL && preallocNonceUsed) { - cacheSession->ticketNonce.data = preallocNonce; - cacheSession->ticketNonce.len = preallocNonceLen; - preallocNonce = NULL; - preallocNonceLen = 0; - } -#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC - * && FIPS_VERSION_GE(5,3)*/ - } -#ifdef HAVE_SESSION_TICKET - else if (ticBuffUsed) { - /* Error occurred. Need to clean up the ticket buffer. */ - cacheSession->ticket = cacheSession->staticTicket; - cacheSession->ticketLenAlloc = 0; - cacheSession->ticketLen = 0; + if (ctx == NULL) { + return ret; } -#endif - SESSION_ROW_UNLOCK(sessRow); - cacheSession = NULL; /* Can't access after unlocked */ -#ifndef NO_CLIENT_CACHE - if (ret == 0 && clientCacheEntry != NULL) { - ClientSession* clientCache = AddSessionToClientCache(side, row, idx, - addSession->serverID, addSession->idLen, id, useTicket); - if (clientCache != NULL) - *clientCacheEntry = clientCache; + /* clear out flags and reset min protocol version */ + minProto = wolfSSL_CTX_get_min_proto_version(ctx); + wolfSSL_CTX_clear_options(ctx, + WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 | + WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3); + wolfSSL_CTX_set_min_proto_version(ctx, minProto); + if (version != 0) { + ctx->maxProto = 0; /* turn max proto flag off */ + return Set_CTX_max_proto_version(ctx, version); } -#endif - -#ifdef HAVE_SESSION_TICKET - if (ticBuff != NULL && !ticBuffUsed) - XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - XFREE(cacheTicBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); - XFREE(toFree, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ -#endif -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (cachePeer != NULL) { - wolfSSL_X509_free(cachePeer); - cachePeer = NULL; /* Make sure not use after this point */ + /* when 0 is specified as version, try to find out the min version from + * the bottom to top of the protoverTbl. + */ + for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) { + ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]); + if (ret == WOLFSSL_SUCCESS) { + ctx->maxProto = 1; /* turn max proto flag on */ + break; + } } -#endif return ret; } -void AddSession(WOLFSSL* ssl) -{ - int error = 0; - const byte* id = NULL; - byte idSz = 0; - WOLFSSL_SESSION* session = ssl->session; - - (void)error; - WOLFSSL_ENTER("AddSession"); - - if (SslSessionCacheOff(ssl, session)) { - WOLFSSL_MSG("Cache off"); - return; - } +static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver) +{ + WOLFSSL_ENTER("Set_SSL_min_proto_version"); - if (session->haveAltSessionID) { - id = session->altSessionID; - idSz = ID_LEN; - } - else { - id = session->sessionID; - idSz = session->sessionIDSz; - } - - /* Do this only for the client because if the server doesn't have an ID at - * this point, it won't on resumption. */ - if (idSz == 0 && ssl->options.side == WOLFSSL_CLIENT_END) { - WC_RNG* rng = NULL; - if (ssl->rng != NULL) - rng = ssl->rng; -#if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA) - else if (initGlobalRNG == 1 || wolfSSL_RAND_Init() == WOLFSSL_SUCCESS) { - rng = &globalRNG; - } -#endif - if (wc_RNG_GenerateBlock(rng, ssl->session->altSessionID, - ID_LEN) != 0) - return; - ssl->session->haveAltSessionID = 1; - id = ssl->session->altSessionID; - idSz = ID_LEN; + if (ssl == NULL) { + return WOLFSSL_FAILURE; } -#ifdef HAVE_EXT_CACHE - if (!ssl->options.internalCacheOff) -#endif - { - /* Try to add the session to internal cache or external cache - if a new_sess_cb is set. Its ok if we don't succeed. */ - (void)AddSessionToCache(ssl->ctx, session, id, idSz, -#ifdef SESSION_INDEX - &ssl->sessionIndex, -#else - NULL, + switch (ver) { +#ifndef NO_TLS + case SSL3_VERSION: +#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) + ssl->options.minDowngrade = SSLv3_MINOR; + break; #endif - ssl->options.side, -#ifdef HAVE_SESSION_TICKET - ssl->options.useTicket, -#else - 0, + case TLS1_VERSION: + #ifdef WOLFSSL_ALLOW_TLSV10 + ssl->options.minDowngrade = TLSv1_MINOR; + break; + #endif + case TLS1_1_VERSION: + #ifndef NO_OLD_TLS + ssl->options.minDowngrade = TLSv1_1_MINOR; + break; + #endif + case TLS1_2_VERSION: + #ifndef WOLFSSL_NO_TLS12 + ssl->options.minDowngrade = TLSv1_2_MINOR; + break; + #endif + case TLS1_3_VERSION: + #ifdef WOLFSSL_TLS13 + ssl->options.minDowngrade = TLSv1_3_MINOR; + break; + #endif #endif -#ifdef NO_SESSION_CACHE_REF - NULL -#else - (ssl->options.side == WOLFSSL_CLIENT_END) ? - &ssl->clientSession : NULL +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + #ifndef NO_OLD_TLS + ssl->options.minDowngrade = DTLS_MINOR; + break; + #endif + case DTLS1_2_VERSION: + ssl->options.minDowngrade = DTLSv1_2_MINOR; + break; #endif - ); + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; } -#ifdef HAVE_EXT_CACHE - if (error == 0 && ssl->ctx->new_sess_cb != NULL) { - int cbRet = 0; - wolfSSL_SESSION_up_ref(session); - cbRet = ssl->ctx->new_sess_cb(ssl, session); - if (cbRet == 0) - wolfSSL_FreeSession(ssl->ctx, session); - } + switch (ver) { +#ifndef NO_TLS + case TLS1_3_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2; + FALL_THROUGH; + case TLS1_2_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1; + FALL_THROUGH; + case TLS1_1_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1; + FALL_THROUGH; + case TLS1_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_SSLv3; + break; + case SSL3_VERSION: + case SSL2_VERSION: + /* Nothing to do here */ + break; #endif - -#if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS) - if (error == 0) { - word32 active = 0; - - error = get_locked_session_stats(&active, NULL, NULL); - if (error == WOLFSSL_SUCCESS) { - error = 0; /* back to this function ok */ - - if (PeakSessions < active) { - PeakSessions = active; - } - } +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + case DTLS1_2_VERSION: + break; +#endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; } -#endif /* WOLFSSL_SESSION_STATS && WOLFSSL_PEAK_SESSIONS */ - (void)error; -} - -#ifdef SESSION_INDEX - -int wolfSSL_GetSessionIndex(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_GetSessionIndex"); - WOLFSSL_LEAVE("wolfSSL_GetSessionIndex", ssl->sessionIndex); - return ssl->sessionIndex; + return CheckSslMethodVersion(ssl->version.major, ssl->options.mask); } - -int wolfSSL_GetSessionAtIndex(int idx, WOLFSSL_SESSION* session) +int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version) { - int row, col, result = WOLFSSL_FAILURE; - SessionRow* sessRow; - WOLFSSL_SESSION* cacheSession; - - WOLFSSL_ENTER("wolfSSL_GetSessionAtIndex"); - - session = ClientSessionToSession(session); + int i; + int ret = WOLFSSL_FAILURE;; - row = idx >> SESSIDX_ROW_SHIFT; - col = idx & SESSIDX_IDX_MASK; + WOLFSSL_ENTER("wolfSSL_set_min_proto_version"); - if (session == NULL || - row < 0 || row >= SESSION_ROWS || col >= SESSIONS_PER_ROW) { + if (ssl == NULL) { return WOLFSSL_FAILURE; } - - sessRow = &SessionCache[row]; - if (SESSION_ROW_RD_LOCK(sessRow) != 0) { - return BAD_MUTEX_E; + if (version != 0) { + return Set_SSL_min_proto_version(ssl, version); } -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[col]; -#else - cacheSession = &sessRow->Sessions[col]; -#endif - if (cacheSession) { - XMEMCPY(session, cacheSession, sizeof(WOLFSSL_SESSION)); - result = WOLFSSL_SUCCESS; - } - else { - result = WOLFSSL_FAILURE; + /* when 0 is specified as version, try to find out the min version */ + for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { + ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]); + if (ret == WOLFSSL_SUCCESS) + break; } - SESSION_ROW_UNLOCK(sessRow); - - WOLFSSL_LEAVE("wolfSSL_GetSessionAtIndex", result); - return result; + return ret; } -#endif /* SESSION_INDEX */ - -#if defined(SESSION_CERTS) - -WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session) +static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver) { - WOLFSSL_X509_CHAIN* chain = NULL; - WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain"); + WOLFSSL_ENTER("Set_SSL_max_proto_version"); - session = ClientSessionToSession(session); + if (!ssl) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } - if (session) - chain = &session->chain; + switch (ver) { + case SSL2_VERSION: + WOLFSSL_MSG("wolfSSL does not support SSLv2"); + return WOLFSSL_FAILURE; +#ifndef NO_TLS + case SSL3_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1; + FALL_THROUGH; + case TLS1_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1; + FALL_THROUGH; + case TLS1_1_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2; + FALL_THROUGH; + case TLS1_2_VERSION: + ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3; + FALL_THROUGH; + case TLS1_3_VERSION: + /* Nothing to do here */ + break; +#endif +#ifdef WOLFSSL_DTLS + case DTLS1_VERSION: + case DTLS1_2_VERSION: + break; +#endif + default: + WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + return WOLFSSL_FAILURE; + } - WOLFSSL_LEAVE("wolfSSL_SESSION_get_peer_chain", chain ? 1 : 0); - return chain; + return CheckSslMethodVersion(ssl->version.major, ssl->options.mask); } - -#ifdef OPENSSL_EXTRA -/* gets the peer certificate associated with the session passed in - * returns null on failure, the caller should not free the returned pointer */ -WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session) +int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version) { - WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain"); + int i; + int ret = WOLFSSL_FAILURE;; - session = ClientSessionToSession(session); - if (session) { - int count; + WOLFSSL_ENTER("wolfSSL_set_max_proto_version"); - count = wolfSSL_get_chain_count(&session->chain); - if (count < 1 || count >= MAX_CHAIN_DEPTH) { - WOLFSSL_MSG("bad count found"); - return NULL; - } + if (ssl == NULL) { + return WOLFSSL_FAILURE; + } + if (version != 0) { + return Set_SSL_max_proto_version(ssl, version); + } - if (session->peer == NULL) { - session->peer = wolfSSL_get_chain_X509(&session->chain, 0); - } - return session->peer; + /* when 0 is specified as version, try to find out the min version from + * the bottom to top of the protoverTbl. + */ + for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) { + ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]); + if (ret == WOLFSSL_SUCCESS) + break; } - WOLFSSL_MSG("No session passed in"); - return NULL; + return ret; } -#endif /* OPENSSL_EXTRA */ -#endif /* SESSION_INDEX && SESSION_CERTS */ +static int GetMinProtoVersion(int minDowngrade) +{ + int ret; + + switch (minDowngrade) { +#ifndef NO_OLD_TLS + #ifdef WOLFSSL_ALLOW_SSLV3 + case SSLv3_MINOR: + ret = SSL3_VERSION; + break; + #endif + #ifdef WOLFSSL_ALLOW_TLSV10 + case TLSv1_MINOR: + ret = TLS1_VERSION; + break; + #endif + case TLSv1_1_MINOR: + ret = TLS1_1_VERSION; + break; +#endif +#ifndef WOLFSSL_NO_TLS12 + case TLSv1_2_MINOR: + ret = TLS1_2_VERSION; + break; +#endif +#ifdef WOLFSSL_TLS13 + case TLSv1_3_MINOR: + ret = TLS1_3_VERSION; + break; +#endif + default: + ret = 0; + break; + } -#ifdef WOLFSSL_SESSION_STATS + return ret; +} -static int get_locked_session_stats(word32* active, word32* total, word32* peak) +int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx) { - int result = WOLFSSL_SUCCESS; - int i; - int count; - int idx; - word32 now = 0; - word32 seen = 0; - word32 ticks = LowResTimer(); + int ret = 0; - WOLFSSL_ENTER("get_locked_session_stats"); + WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version"); -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_RD_LOCK(&SessionCache[0]); -#endif - for (i = 0; i < SESSION_ROWS; i++) { - SessionRow* row = &SessionCache[i]; - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - if (SESSION_ROW_RD_LOCK(row) != 0) { - WOLFSSL_MSG("Session row cache mutex lock failed"); - return BAD_MUTEX_E; + if (ctx != NULL) { + if (ctx->minProto) { + ret = 0; } - #endif - - seen += row->totalCount; - - if (active == NULL) { - SESSION_ROW_UNLOCK(row); - continue; + else { + ret = GetMinProtoVersion(ctx->minDowngrade); } + } + else { + ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE); + } - count = min((word32)row->totalCount, SESSIONS_PER_ROW); - idx = row->nextIdx - 1; - if (idx < 0 || idx >= SESSIONS_PER_ROW) { - idx = SESSIONS_PER_ROW - 1; /* if back to front previous was end */ - } + WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret); - for (; count > 0; --count) { - /* if not expired then good */ -#ifdef SESSION_CACHE_DYNAMIC_MEM - if (row->Sessions[idx] && - ticks < (row->Sessions[idx]->bornOn + - row->Sessions[idx]->timeout) ) -#else - if (ticks < (row->Sessions[idx].bornOn + - row->Sessions[idx].timeout) ) -#endif - { - now++; - } + return ret; +} - idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1; - } - #ifdef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(row); +/* returns the maximum allowed protocol version given the 'options' used + * returns WOLFSSL_FATAL_ERROR on no match */ +static int GetMaxProtoVersion(long options) +{ +#ifndef NO_TLS +#ifdef WOLFSSL_TLS13 + if (!(options & WOLFSSL_OP_NO_TLSv1_3)) + return TLS1_3_VERSION; +#endif +#ifndef WOLFSSL_NO_TLS12 + if (!(options & WOLFSSL_OP_NO_TLSv1_2)) + return TLS1_2_VERSION; +#endif +#ifndef NO_OLD_TLS + if (!(options & WOLFSSL_OP_NO_TLSv1_1)) + return TLS1_1_VERSION; + #ifdef WOLFSSL_ALLOW_TLSV10 + if (!(options & WOLFSSL_OP_NO_TLSv1)) + return TLS1_VERSION; + #endif + #ifdef WOLFSSL_ALLOW_SSLV3 + if (!(options & WOLFSSL_OP_NO_SSLv3)) + return SSL3_VERSION; #endif - } -#ifndef ENABLE_SESSION_CACHE_ROW_LOCK - SESSION_ROW_UNLOCK(&SessionCache[0]); #endif +#else + (void)options; +#endif /* NO_TLS */ + return WOLFSSL_FATAL_ERROR; +} - if (active) { - *active = now; - } - if (total) { - *total = seen; + +/* returns the maximum protocol version for 'ctx' */ +int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx) +{ + int ret = 0; + long options = 0; /* default to nothing set */ + + WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version"); + + if (ctx != NULL) { + options = wolfSSL_CTX_get_options(ctx); } -#ifdef WOLFSSL_PEAK_SESSIONS - if (peak) { - *peak = PeakSessions; + if ((ctx != NULL) && ctx->maxProto) { + ret = 0; + } + else { + ret = GetMaxProtoVersion(options); } -#else - (void)peak; -#endif - WOLFSSL_LEAVE("get_locked_session_stats", result); + WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret); - return result; + if (ret == WOLFSSL_FATAL_ERROR) { + WOLFSSL_MSG("Error getting max proto version"); + ret = 0; /* setting ret to 0 to match compat return */ + } + return ret; } +#endif /* OPENSSL_EXTRA */ - -/* return WOLFSSL_SUCCESS on ok */ -int wolfSSL_get_session_stats(word32* active, word32* total, word32* peak, - word32* maxSessions) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ + defined(HAVE_SECRET_CALLBACK) +#if !defined(NO_WOLFSSL_CLIENT) +/* Return the amount of random bytes copied over or error case. + * ssl : ssl struct after handshake + * out : buffer to hold random bytes + * outSz : either 0 (return max buffer sz) or size of out buffer + */ +size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, + size_t outSz) { - int result = WOLFSSL_SUCCESS; - - WOLFSSL_ENTER("wolfSSL_get_session_stats"); - - if (maxSessions) { - *maxSessions = SESSIONS_PER_ROW * SESSION_ROWS; + size_t size; - if (active == NULL && total == NULL && peak == NULL) - return result; /* we're done */ + /* return max size of buffer */ + if (outSz == 0) { + return RAN_LEN; } - /* user must provide at least one query value */ - if (active == NULL && total == NULL && peak == NULL) { - return BAD_FUNC_ARG; + if (ssl == NULL || out == NULL) { + return 0; } - result = get_locked_session_stats(active, total, peak); + if (ssl->arrays == NULL) { + WOLFSSL_MSG("Arrays struct not saved after handshake"); + return 0; + } - WOLFSSL_LEAVE("wolfSSL_get_session_stats", result); + if (outSz > RAN_LEN) { + size = RAN_LEN; + } + else { + size = outSz; + } - return result; + XMEMCPY(out, ssl->arrays->clientRandom, size); + return size; } +#endif /* !NO_WOLFSSL_CLIENT */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */ -#endif /* WOLFSSL_SESSION_STATS */ - +#ifdef OPENSSL_EXTRA - #ifdef PRINT_SESSION_STATS + unsigned long wolfSSLeay(void) + { + return SSLEAY_VERSION_NUMBER; + } - /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_PrintSessionStats(void) + unsigned long wolfSSL_OpenSSL_version_num(void) { - word32 totalSessionsSeen = 0; - word32 totalSessionsNow = 0; - word32 peak = 0; - word32 maxSessions = 0; - int i; - int ret; - double E; /* expected freq */ - double chiSquare = 0; - - ret = wolfSSL_get_session_stats(&totalSessionsNow, &totalSessionsSeen, - &peak, &maxSessions); - if (ret != WOLFSSL_SUCCESS) - return ret; - printf("Total Sessions Seen = %u\n", totalSessionsSeen); - printf("Total Sessions Now = %u\n", totalSessionsNow); -#ifdef WOLFSSL_PEAK_SESSIONS - printf("Peak Sessions = %u\n", peak); -#endif - printf("Max Sessions = %u\n", maxSessions); - - E = (double)totalSessionsSeen / SESSION_ROWS; - - for (i = 0; i < SESSION_ROWS; i++) { - double diff = SessionCache[i].totalCount - E; - diff *= diff; /* square */ - diff /= E; /* normalize */ - - chiSquare += diff; - } - printf(" chi-square = %5.1f, d.f. = %d\n", chiSquare, - SESSION_ROWS - 1); - #if (SESSION_ROWS == 11) - printf(" .05 p value = 18.3, chi-square should be less\n"); - #elif (SESSION_ROWS == 211) - printf(".05 p value = 244.8, chi-square should be less\n"); - #elif (SESSION_ROWS == 5981) - printf(".05 p value = 6161.0, chi-square should be less\n"); - #elif (SESSION_ROWS == 3) - printf(".05 p value = 6.0, chi-square should be less\n"); - #elif (SESSION_ROWS == 2861) - printf(".05 p value = 2985.5, chi-square should be less\n"); - #endif - printf("\n"); + return OPENSSL_VERSION_NUMBER; + } - return ret; + const char* wolfSSLeay_version(int type) + { + (void)type; +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L + return wolfSSL_OpenSSL_version(type); +#else + return wolfSSL_OpenSSL_version(); +#endif } +#endif /* OPENSSL_EXTRA */ - #endif /* SESSION_STATS */ +#ifdef OPENSSL_EXTRA + void wolfSSL_ERR_free_strings(void) + { + /* handled internally */ + } -#else /* NO_SESSION_CACHE */ + void wolfSSL_cleanup_all_ex_data(void) + { + /* nothing to do here */ + } -WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) -{ - return (WOLFSSL_SESSION*)session; -} +#endif /* OPENSSL_EXTRA */ -/* No session cache version */ -WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret, - byte restoreSessionCerts) -{ - (void)ssl; - (void)masterSecret; - (void)restoreSessionCerts; +#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \ + defined(HAVE_CURL) + void wolfSSL_ERR_clear_error(void) + { + WOLFSSL_ENTER("wolfSSL_ERR_clear_error"); + #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) + wc_ClearErrorNodes(); + #endif + } +#endif - return NULL; -} +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) + int wolfSSL_clear(WOLFSSL* ssl) + { + WOLFSSL_ENTER("wolfSSL_clear"); -#endif /* NO_SESSION_CACHE */ + if (ssl == NULL) { + return WOLFSSL_FAILURE; + } + if (!ssl->options.handShakeDone) { + /* Only reset the session if we didn't complete a handshake */ + wolfSSL_FreeSession(ssl->ctx, ssl->session); + ssl->session = wolfSSL_NewSession(ssl->heap); + if (ssl->session == NULL) { + return WOLFSSL_FAILURE; + } + } -/* call before SSL_connect, if verifying will add name check to - date check and signature check */ -WOLFSSL_ABI -int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn) -{ - WOLFSSL_ENTER("wolfSSL_check_domain_name"); + /* reset error */ + ssl->error = 0; - if (ssl == NULL || dn == NULL) { - WOLFSSL_MSG("Bad function argument: NULL"); - return WOLFSSL_FAILURE; - } + /* reset option bits */ + ssl->options.isClosed = 0; + ssl->options.connReset = 0; + ssl->options.sentNotify = 0; + ssl->options.closeNotify = 0; + ssl->options.sendVerify = 0; + ssl->options.serverState = NULL_STATE; + ssl->options.clientState = NULL_STATE; + ssl->options.connectState = CONNECT_BEGIN; + ssl->options.acceptState = ACCEPT_BEGIN; + ssl->options.handShakeState = NULL_STATE; + ssl->options.handShakeDone = 0; + ssl->options.processReply = 0; /* doProcessInit */ + ssl->options.havePeerVerify = 0; + ssl->options.havePeerCert = 0; + ssl->options.peerAuthGood = 0; + ssl->options.tls1_3 = 0; + ssl->options.haveSessionId = 0; + ssl->options.tls = 0; + ssl->options.tls1_1 = 0; + #ifdef WOLFSSL_DTLS + ssl->options.dtlsStateful = 0; + #endif + #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) + ssl->options.noPskDheKe = 0; + #ifdef HAVE_SUPPORTED_CURVES + ssl->options.onlyPskDheKe = 0; + #endif + #endif + #ifdef HAVE_SESSION_TICKET + #ifdef WOLFSSL_TLS13 + ssl->options.ticketsSent = 0; + #endif + ssl->options.rejectTicket = 0; + #endif + #ifdef WOLFSSL_EARLY_DATA + ssl->earlyData = no_early_data; + ssl->earlyDataSz = 0; + #endif - if (ssl->buffers.domainName.buffer) - XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN); + #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS) + TLSX_FreeAll(ssl->extensions, ssl->heap); + ssl->extensions = NULL; + #endif - ssl->buffers.domainName.length = (word32)XSTRLEN(dn); - ssl->buffers.domainName.buffer = (byte*)XMALLOC( - ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN); + if (ssl->keys.encryptionOn) { + ForceZero(ssl->buffers.inputBuffer.buffer - + ssl->buffers.inputBuffer.offset, + ssl->buffers.inputBuffer.bufferSize); + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Check(ssl->buffers.inputBuffer.buffer - + ssl->buffers.inputBuffer.offset, + ssl->buffers.inputBuffer.bufferSize); + #endif + } + ssl->keys.encryptionOn = 0; + XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived)); - if (ssl->buffers.domainName.buffer) { - unsigned char* domainName = ssl->buffers.domainName.buffer; - XMEMCPY(domainName, dn, ssl->buffers.domainName.length); - domainName[ssl->buffers.domainName.length] = '\0'; - return WOLFSSL_SUCCESS; - } - else { - ssl->error = MEMORY_ERROR; - return WOLFSSL_FAILURE; - } -} + if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS) + return WOLFSSL_FAILURE; + if (InitHandshakeHashes(ssl) != 0) + return WOLFSSL_FAILURE; -/* turn on wolfSSL zlib compression - returns WOLFSSL_SUCCESS for success, else error (not built in) -*/ -int wolfSSL_set_compression(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_set_compression"); - (void)ssl; -#ifdef HAVE_LIBZ - ssl->options.usingCompression = 1; - return WOLFSSL_SUCCESS; -#else - return NOT_COMPILED_IN; +#ifdef KEEP_PEER_CERT + FreeX509(&ssl->peerCert); + InitX509(&ssl->peerCert, 0, ssl->heap); #endif -} +#ifdef WOLFSSL_QUIC + wolfSSL_quic_clear(ssl); +#endif -#ifndef USE_WINDOWS_API - #ifndef NO_WRITEV + return WOLFSSL_SUCCESS; + } - /* simulate writev semantics, doesn't actually do block at a time though - because of SSL_write behavior and because front adds may be small */ - int wolfSSL_writev(WOLFSSL* ssl, const struct iovec* iov, int iovcnt) - { - #ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force heap usage */ - #else - byte staticBuffer[FILE_BUFFER_SIZE]; - #endif - byte* myBuffer = staticBuffer; - int dynamic = 0; - int sending = 0; - int idx = 0; - int i; - int ret; +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - WOLFSSL_ENTER("wolfSSL_writev"); +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) + long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode) + { + /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */ - for (i = 0; i < iovcnt; i++) - sending += (int)iov[i].iov_len; + WOLFSSL_ENTER("wolfSSL_CTX_set_mode"); + switch(mode) { + case SSL_MODE_ENABLE_PARTIAL_WRITE: + ctx->partialWrite = 1; + break; + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + case SSL_MODE_RELEASE_BUFFERS: + WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); + break; + #endif + case SSL_MODE_AUTO_RETRY: + ctx->autoRetry = 1; + break; + default: + WOLFSSL_MSG("Mode Not Implemented"); + } - if (sending > (int)sizeof(staticBuffer)) { - myBuffer = (byte*)XMALLOC(sending, ssl->heap, - DYNAMIC_TYPE_WRITEV); - if (!myBuffer) - return MEMORY_ERROR; + /* SSL_MODE_AUTO_RETRY + * Should not return -1 with renegotiation on read/write */ - dynamic = 1; - } + return mode; + } - for (i = 0; i < iovcnt; i++) { - XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len); - idx += (int)iov[i].iov_len; - } + long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode) + { + /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */ - /* myBuffer may not be initialized fully, but the span up to the - * sending length will be. - */ - PRAGMA_GCC_DIAG_PUSH - PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") - ret = wolfSSL_write(ssl, myBuffer, sending); - PRAGMA_GCC_DIAG_POP + WOLFSSL_ENTER("wolfSSL_CTX_clear_mode"); + switch(mode) { + case SSL_MODE_ENABLE_PARTIAL_WRITE: + ctx->partialWrite = 0; + break; + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + case SSL_MODE_RELEASE_BUFFERS: + WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); + break; + #endif + case SSL_MODE_AUTO_RETRY: + ctx->autoRetry = 0; + break; + default: + WOLFSSL_MSG("Mode Not Implemented"); + } - if (dynamic) - XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV); + /* SSL_MODE_AUTO_RETRY + * Should not return -1 with renegotiation on read/write */ - return ret; - } - #endif + return 0; + } #endif +#ifdef OPENSSL_EXTRA -#ifdef WOLFSSL_CALLBACKS - - typedef struct itimerval Itimerval; + #ifndef NO_WOLFSSL_STUB + long wolfSSL_SSL_get_mode(WOLFSSL* ssl) + { + /* TODO: */ + (void)ssl; + WOLFSSL_STUB("SSL_get_mode"); + return 0; + } + #endif - /* don't keep calling simple functions while setting up timer and signals - if no inlining these are the next best */ - - #define AddTimes(a, b, c) \ - do { \ - (c).tv_sec = (a).tv_sec + (b).tv_sec; \ - (c).tv_usec = (a).tv_usec + (b).tv_usec;\ - if ((c).tv_usec >= 1000000) { \ - (c).tv_sec++; \ - (c).tv_usec -= 1000000; \ - } \ - } while (0) + #ifndef NO_WOLFSSL_STUB + long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx) + { + /* TODO: */ + (void)ctx; + WOLFSSL_STUB("SSL_CTX_get_mode"); + return 0; + } + #endif + #ifndef NO_WOLFSSL_STUB + void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m) + { + /* TODO: maybe? */ + (void)ctx; + (void)m; + WOLFSSL_STUB("SSL_CTX_set_default_read_ahead"); + } + #endif - #define SubtractTimes(a, b, c) \ - do { \ - (c).tv_sec = (a).tv_sec - (b).tv_sec; \ - (c).tv_usec = (a).tv_usec - (b).tv_usec;\ - if ((c).tv_usec < 0) { \ - (c).tv_sec--; \ - (c).tv_usec += 1000000; \ - } \ - } while (0) - #define CmpTimes(a, b, cmp) \ - (((a).tv_sec == (b).tv_sec) ? \ - ((a).tv_usec cmp (b).tv_usec) : \ - ((a).tv_sec cmp (b).tv_sec)) \ + /* returns the unsigned error value and increments the pointer into the + * error queue. + * + * file pointer to file name + * line gets set to line number of error when not NULL + */ + unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line) + { + #ifdef WOLFSSL_HAVE_ERROR_QUEUE + int ret = wc_PullErrorNode(file, NULL, line); + if (ret < 0) { + if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) + return 0; /* no errors in queue */ + WOLFSSL_MSG("Issue getting error node"); + WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret); + ret = 0 - ret; /* return absolute value of error */ + /* panic and try to clear out nodes */ + wc_ClearErrorNodes(); + } + return (unsigned long)ret; + #else + (void)file; + (void)line; - /* do nothing handler */ - static void myHandler(int signo) - { - (void)signo; - return; + return 0; + #endif } - static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb, - TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) - { - int ret = WOLFSSL_FATAL_ERROR; - int oldTimerOn = 0; /* was timer already on */ - WOLFSSL_TIMEVAL startTime; - WOLFSSL_TIMEVAL endTime; - WOLFSSL_TIMEVAL totalTime; - Itimerval myTimeout; - Itimerval oldTimeout; /* if old timer adjust from total time to reset */ - struct sigaction act, oact; - - #define ERR_OUT(x) { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; } +#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \ + (!defined(_WIN32) && !defined(NO_ERROR_QUEUE)) + static const char WOLFSSL_SYS_ACCEPT_T[] = "accept"; + static const char WOLFSSL_SYS_BIND_T[] = "bind"; + static const char WOLFSSL_SYS_CONNECT_T[] = "connect"; + static const char WOLFSSL_SYS_FOPEN_T[] = "fopen"; + static const char WOLFSSL_SYS_FREAD_T[] = "fread"; + static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo"; + static const char WOLFSSL_SYS_GETSOCKOPT_T[] = "getsockopt"; + static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname"; + static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname"; + static const char WOLFSSL_SYS_GETNAMEINFO_T[] = "getnameinfo"; + static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname"; + static const char WOLFSSL_SYS_IOCTLSOCKET_T[] = "ioctlsocket"; + static const char WOLFSSL_SYS_LISTEN_T[] = "listen"; + static const char WOLFSSL_SYS_OPENDIR_T[] = "opendir"; + static const char WOLFSSL_SYS_SETSOCKOPT_T[] = "setsockopt"; + static const char WOLFSSL_SYS_SOCKET_T[] = "socket"; - if (hsCb) { - ssl->hsInfoOn = 1; - InitHandShakeInfo(&ssl->handShakeInfo, ssl); + /* switch with int mapped to function name for compatibility */ + static const char* wolfSSL_ERR_sys_func(int fun) + { + switch (fun) { + case WOLFSSL_SYS_ACCEPT: return WOLFSSL_SYS_ACCEPT_T; + case WOLFSSL_SYS_BIND: return WOLFSSL_SYS_BIND_T; + case WOLFSSL_SYS_CONNECT: return WOLFSSL_SYS_CONNECT_T; + case WOLFSSL_SYS_FOPEN: return WOLFSSL_SYS_FOPEN_T; + case WOLFSSL_SYS_FREAD: return WOLFSSL_SYS_FREAD_T; + case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T; + case WOLFSSL_SYS_GETSOCKOPT: return WOLFSSL_SYS_GETSOCKOPT_T; + case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T; + case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T; + case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T; + case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T; + case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T; + case WOLFSSL_SYS_LISTEN: return WOLFSSL_SYS_LISTEN_T; + case WOLFSSL_SYS_OPENDIR: return WOLFSSL_SYS_OPENDIR_T; + case WOLFSSL_SYS_SETSOCKOPT: return WOLFSSL_SYS_SETSOCKOPT_T; + case WOLFSSL_SYS_SOCKET: return WOLFSSL_SYS_SOCKET_T; + default: + return "NULL"; } - if (toCb) { - ssl->toInfoOn = 1; - InitTimeoutInfo(&ssl->timeoutInfo); + } +#endif /* DEBUG_WOLFSSL */ - if (gettimeofday(&startTime, 0) < 0) - ERR_OUT(GETTIME_ERROR); - /* use setitimer to simulate getitimer, init 0 myTimeout */ - myTimeout.it_interval.tv_sec = 0; - myTimeout.it_interval.tv_usec = 0; - myTimeout.it_value.tv_sec = 0; - myTimeout.it_value.tv_usec = 0; - if (setitimer(ITIMER_REAL, &myTimeout, &oldTimeout) < 0) - ERR_OUT(SETITIMER_ERROR); + void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file, + int line) + { + WOLFSSL_ENTER("wolfSSL_ERR_put_error"); - if (oldTimeout.it_value.tv_sec || oldTimeout.it_value.tv_usec) { - oldTimerOn = 1; + #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA) + (void)fun; + (void)err; + (void)file; + (void)line; + WOLFSSL_MSG("Not compiled in debug mode"); + #elif defined(OPENSSL_EXTRA) && \ + (defined(_WIN32) || defined(NO_ERROR_QUEUE)) + (void)fun; + (void)file; + (void)line; + WOLFSSL_ERROR(err); + #else + WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line, + file, NULL); + #endif + (void)lib; + } - /* is old timer going to expire before ours */ - if (CmpTimes(oldTimeout.it_value, timeout, <)) { - timeout.tv_sec = oldTimeout.it_value.tv_sec; - timeout.tv_usec = oldTimeout.it_value.tv_usec; - } - } - myTimeout.it_value.tv_sec = timeout.tv_sec; - myTimeout.it_value.tv_usec = timeout.tv_usec; - /* set up signal handler, don't restart socket send/recv */ - act.sa_handler = myHandler; - sigemptyset(&act.sa_mask); - act.sa_flags = 0; -#ifdef SA_INTERRUPT - act.sa_flags |= SA_INTERRUPT; -#endif - if (sigaction(SIGALRM, &act, &oact) < 0) - ERR_OUT(SIGACT_ERROR); + /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for + * more flexibility. + * + * file output pointer to file where error happened + * line output to line number of error + * data output data. Is a string if ERR_TXT_STRING flag is used + * flags output format of output + * + * Returns the error value or 0 if no errors are in the queue + */ + unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line, + const char** data, int *flags) + { +#ifdef WOLFSSL_HAVE_ERROR_QUEUE + int ret; - if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0) - ERR_OUT(SETITIMER_ERROR); - } + WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data"); - /* do main work */ -#ifndef NO_WOLFSSL_CLIENT - if (ssl->options.side == WOLFSSL_CLIENT_END) - ret = wolfSSL_connect(ssl); -#endif -#ifndef NO_WOLFSSL_SERVER - if (ssl->options.side == WOLFSSL_SERVER_END) - ret = wolfSSL_accept(ssl); -#endif + if (flags != NULL) + *flags = ERR_TXT_STRING; /* Clear the flags */ - /* do callbacks */ - if (toCb) { - if (oldTimerOn) { - if (gettimeofday(&endTime, 0) < 0) - ERR_OUT(SYSLIB_FAILED_E); - SubtractTimes(endTime, startTime, totalTime); - /* adjust old timer for elapsed time */ - if (CmpTimes(totalTime, oldTimeout.it_value, <)) - SubtractTimes(oldTimeout.it_value, totalTime, - oldTimeout.it_value); - else { - /* reset value to interval, may be off */ - oldTimeout.it_value.tv_sec = oldTimeout.it_interval.tv_sec; - oldTimeout.it_value.tv_usec =oldTimeout.it_interval.tv_usec; - } - /* keep iter the same whether there or not */ - } - /* restore old handler */ - if (sigaction(SIGALRM, &oact, 0) < 0) - ret = SIGACT_ERROR; /* more pressing error, stomp */ - else - /* use old settings which may turn off (expired or not there) */ - if (setitimer(ITIMER_REAL, &oldTimeout, 0) < 0) - ret = SETITIMER_ERROR; + ret = wc_PullErrorNode(file, data, line); + if (ret < 0) { + if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) + return 0; /* no errors in queue */ + WOLFSSL_MSG("Error with pulling error node!"); + WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret); + ret = 0 - ret; /* return absolute value of error */ - /* if we had a timeout call callback */ - if (ssl->timeoutInfo.timeoutName[0]) { - ssl->timeoutInfo.timeoutValue.tv_sec = timeout.tv_sec; - ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec; - (toCb)(&ssl->timeoutInfo); - } - ssl->toInfoOn = 0; + /* panic and try to clear out nodes */ + wc_ClearErrorNodes(); } - /* clean up buffers allocated by AddPacketInfo */ - FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap); - - if (hsCb) { - FinishHandShakeInfo(&ssl->handShakeInfo); - (hsCb)(&ssl->handShakeInfo); - ssl->hsInfoOn = 0; - } - return ret; + return (unsigned long)ret; +#else + WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data"); + WOLFSSL_MSG("Error queue turned off, can not get error line"); + (void)file; + (void)line; + (void)data; + (void)flags; + return 0; +#endif } +#endif /* OPENSSL_EXTRA */ -#ifndef NO_WOLFSSL_CLIENT - int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb, - TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) +#if (defined(KEEP_PEER_CERT) && defined(SESSION_CERTS)) || \ + (defined(OPENSSL_EXTRA) && defined(SESSION_CERTS)) + /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object. + * + * x509 WOLFSSL_X509 object to decode into. + * in X509 DER data. + * len Length of the X509 DER data. + * returns the new certificate on success, otherwise NULL. + */ + static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len) { - WOLFSSL_ENTER("wolfSSL_connect_ex"); - return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout); - } - -#endif + int ret; + #ifdef WOLFSSL_SMALL_STACK + DecodedCert* cert; + #else + DecodedCert cert[1]; + #endif + if (x509 == NULL || in == NULL || len <= 0) + return BAD_FUNC_ARG; + #ifdef WOLFSSL_SMALL_STACK + cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, + DYNAMIC_TYPE_DCERT); + if (cert == NULL) + return MEMORY_E; + #endif -#ifndef NO_WOLFSSL_SERVER + /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object. + */ + InitDecodedCert(cert, (byte*)in, (word32)len, NULL); + if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) == 0) { + /* Check if x509 was not previously initialized by wolfSSL_X509_new() */ + if (x509->dynamicMemory != TRUE) + InitX509(x509, 0, NULL); + ret = CopyDecodedToX509(x509, cert); + } + FreeDecodedCert(cert); + #ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + #endif - int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb, - TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) - { - WOLFSSL_ENTER("wolfSSL_accept_ex"); - return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout); + return ret; } +#endif /* (KEEP_PEER_CERT & SESSION_CERTS) || (OPENSSL_EXTRA & SESSION_CERTS) */ + +#ifdef KEEP_PEER_CERT + WOLFSSL_ABI + WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl) + { + WOLFSSL_X509* ret = NULL; + WOLFSSL_ENTER("wolfSSL_get_peer_certificate"); + if (ssl != NULL) { + if (ssl->peerCert.issuer.sz) + ret = wolfSSL_X509_dup(&ssl->peerCert); +#ifdef SESSION_CERTS + else if (ssl->session->chain.count > 0) { + if (DecodeToX509(&ssl->peerCert, + ssl->session->chain.certs[0].buffer, + ssl->session->chain.certs[0].length) == 0) { + ret = wolfSSL_X509_dup(&ssl->peerCert); + } + } #endif + } + WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL); + return ret; + } -#endif /* WOLFSSL_CALLBACKS */ +#endif /* KEEP_PEER_CERT */ +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) +/* Return stack of peer certs. + * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl + * is. + */ +WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain"); -#ifndef NO_PSK + if (ssl == NULL) + return NULL; - void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx, - wc_psk_client_callback cb) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback"); + /* Try to populate if NULL or empty */ + if (ssl->peerCertChain == NULL || + wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) + wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl); + return ssl->peerCertChain; +} - if (ctx == NULL) - return; +#ifndef WOLFSSL_QT +static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, + WOLFSSL_X509 *x); +/** + * Recursively push the issuer CA chain onto the stack + * @param cm The cert manager that is queried for the issuer + * @param x This cert's issuer will be queried in cm + * @param sk The issuer is pushed onto this stack + * @return WOLFSSL_SUCCESS on success + * WOLFSSL_FAILURE on no issuer found + * WOLFSSL_FATAL_ERROR on a fatal error + */ +static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm, + WOLFSSL_X509 *x, WOLFSSL_STACK* sk) +{ + WOLFSSL_X509* issuer[MAX_CHAIN_DEPTH]; + int i; + int push = 1; + int ret = WOLFSSL_SUCCESS; - ctx->havePSK = 1; - ctx->client_psk_cb = cb; + for (i = 0; i < MAX_CHAIN_DEPTH; i++) { + if (x509GetIssuerFromCM(&issuer[i], cm, x) + != WOLFSSL_SUCCESS) + break; + x = issuer[i]; + } + if (i == 0) /* No further chain found */ + return WOLFSSL_FAILURE; + i--; + for (; i >= 0; i--) { + if (push) { + if (wolfSSL_sk_X509_push(sk, issuer[i]) != WOLFSSL_SUCCESS) { + wolfSSL_X509_free(issuer[i]); + ret = WOLFSSL_FATAL_ERROR; + push = 0; /* Free the rest of the unpushed certs */ + } + } + else { + wolfSSL_X509_free(issuer[i]); + } } + return ret; +} +#endif /* !WOLFSSL_QT */ - void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb) - { - byte haveRSA = 1; - int keySz = 0; +/* Builds up and creates a stack of peer certificates for ssl->peerCertChain + based off of the ssl session chain. Attempts to place CA certificates + at the bottom of the stack. Returns stack of WOLFSSL_X509 certs or + NULL on failure */ +WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) +{ + WOLFSSL_STACK* sk; + WOLFSSL_X509* x509; + int i = 0; + int ret; - WOLFSSL_ENTER("wolfSSL_set_psk_client_callback"); + WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain"); + if ((ssl == NULL) || (ssl->session->chain.count == 0)) + return NULL; - if (ssl == NULL) - return; + sk = wolfSSL_sk_X509_new_null(); + i = ssl->session->chain.count-1; + for (; i >= 0; i--) { + x509 = wolfSSL_X509_new_ex(ssl->heap); + if (x509 == NULL) { + WOLFSSL_MSG("Error Creating X509"); + wolfSSL_sk_X509_pop_free(sk, NULL); + return NULL; + } + ret = DecodeToX509(x509, ssl->session->chain.certs[i].buffer, + ssl->session->chain.certs[i].length); +#if !defined(WOLFSSL_QT) + if (ret == 0 && i == ssl->session->chain.count-1) { + /* On the last element in the chain try to add the CA chain + * first if we have one for this cert */ + SSL_CM_WARNING(ssl); + if (PushCAx509Chain(SSL_CM(ssl), x509, sk) + == WOLFSSL_FATAL_ERROR) { + ret = WOLFSSL_FATAL_ERROR; + } + } +#endif - ssl->options.havePSK = 1; - ssl->options.client_psk_cb = cb; + if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error decoding cert"); + wolfSSL_X509_free(x509); + wolfSSL_sk_X509_pop_free(sk, NULL); + return NULL; + } + } - #ifdef NO_RSA - haveRSA = 0; - #endif - #ifndef NO_CERTS - keySz = ssl->buffers.keySz; - #endif - if (AllocateSuites(ssl) != 0) - return; - InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, - ssl->options.haveDH, ssl->options.haveECDSAsig, - ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + if (sk == NULL) { + WOLFSSL_MSG("Null session chain"); } - #ifdef OPENSSL_EXTRA - /** - * set call back function for psk session use - * @param ssl a pointer to WOLFSSL structure - * @param cb a function pointer to wc_psk_use_session_cb - * @return none - */ - void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl, - wc_psk_use_session_cb_func cb) - { - WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback"); +#if defined(OPENSSL_ALL) + else if (ssl->options.side == WOLFSSL_SERVER_END) { + /* to be compliant with openssl + first element is kept as peer cert on server side.*/ + wolfSSL_sk_X509_pop(sk); + } +#endif + if (ssl->peerCertChain != NULL) + wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL); + /* This is Free'd when ssl is Free'd */ + ssl->peerCertChain = sk; + return sk; +} +#endif /* SESSION_CERTS && OPENSSL_EXTRA */ - if (ssl != NULL) { - ssl->options.havePSK = 1; - ssl->options.session_psk_cb = cb; - } +#ifndef NO_CERTS +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS); - } - #endif +/* create a generic wolfSSL stack node + * returns a new WOLFSSL_STACK structure on success */ +WOLFSSL_STACK* wolfSSL_sk_new_node(void* heap) +{ + WOLFSSL_STACK* sk; + WOLFSSL_ENTER("wolfSSL_sk_new_node"); - void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx, - wc_psk_server_callback cb) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback"); - if (ctx == NULL) - return; - ctx->havePSK = 1; - ctx->server_psk_cb = cb; + sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), heap, + DYNAMIC_TYPE_OPENSSL); + if (sk != NULL) { + XMEMSET(sk, 0, sizeof(*sk)); + sk->heap = heap; } - void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb) - { - byte haveRSA = 1; - int keySz = 0; - - WOLFSSL_ENTER("wolfSSL_set_psk_server_callback"); - if (ssl == NULL) - return; - - ssl->options.havePSK = 1; - ssl->options.server_psk_cb = cb; + return sk; +} - #ifdef NO_RSA - haveRSA = 0; - #endif - #ifndef NO_CERTS - keySz = ssl->buffers.keySz; - #endif - if (AllocateSuites(ssl) != 0) - return; - InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, - ssl->options.haveDH, ssl->options.haveECDSAsig, - ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); +/* free's node but does not free internal data such as in->data.x509 */ +void wolfSSL_sk_free_node(WOLFSSL_STACK* in) +{ + if (in != NULL) { + XFREE(in, in->heap, DYNAMIC_TYPE_OPENSSL); } +} - const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint"); - - if (ssl == NULL || ssl->arrays == NULL) - return NULL; +/* pushes node "in" onto "stack" and returns pointer to the new stack on success + * also handles internal "num" for number of nodes on stack + * return WOLFSSL_SUCCESS on success + */ +int wolfSSL_sk_push_node(WOLFSSL_STACK** stack, WOLFSSL_STACK* in) +{ + if (stack == NULL || in == NULL) { + return WOLFSSL_FAILURE; + } - return ssl->arrays->server_hint; + if (*stack == NULL) { + in->num = 1; + *stack = in; + return WOLFSSL_SUCCESS; } + in->num = (*stack)->num + 1; + in->next = *stack; + *stack = in; + return WOLFSSL_SUCCESS; +} - const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_get_psk_identity"); +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) +static WC_INLINE int compare_WOLFSSL_CIPHER( + WOLFSSL_CIPHER *a, + WOLFSSL_CIPHER *b) +{ + if ((a->cipherSuite0 == b->cipherSuite0) && + (a->cipherSuite == b->cipherSuite) && + (a->ssl == b->ssl) && + (XMEMCMP(a->description, b->description, sizeof a->description) == 0) && + (a->offset == b->offset) && + (a->in_stack == b->in_stack) && + (a->bits == b->bits)) + return 0; + else + return -1; +} +#endif /* OPENSSL_ALL || WOLFSSL_QT */ - if (ssl == NULL || ssl->arrays == NULL) - return NULL; - return ssl->arrays->client_identity; - } +/* return 1 on success 0 on fail */ +int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) +{ + WOLFSSL_STACK* node; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + WOLFSSL_CIPHER ciph; +#endif + WOLFSSL_ENTER("wolfSSL_sk_push"); - int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint) - { - WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint"); - if (hint == 0) - ctx->server_hint[0] = '\0'; - else { - /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */ - #ifdef WOLFSSL_QT - ctx->havePSK=1; - #endif - XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN); - ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */ - } - return WOLFSSL_SUCCESS; + if (!sk) { + return WOLFSSL_FAILURE; } - int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint) - { - WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint"); - - if (ssl == NULL || ssl->arrays == NULL) - return WOLFSSL_FAILURE; - - if (hint == 0) - ssl->arrays->server_hint[0] = 0; - else { - XSTRNCPY(ssl->arrays->server_hint, hint, - sizeof(ssl->arrays->server_hint)-1); - ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0'; - } - return WOLFSSL_SUCCESS; + /* Check if empty data */ + switch (sk->type) { + case STACK_TYPE_CIPHER: +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + /* check if entire struct is zero */ + XMEMSET(&ciph, 0, sizeof(WOLFSSL_CIPHER)); + if (compare_WOLFSSL_CIPHER(&sk->data.cipher, &ciph) == 0) { + sk->data.cipher = *(WOLFSSL_CIPHER*)data; + sk->num = 1; + if (sk->hash_fn) { + sk->hash = sk->hash_fn(&sk->data.cipher); + } + return WOLFSSL_SUCCESS; + } + break; +#endif + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + /* All other types are pointers */ + if (!sk->data.generic) { + sk->data.generic = (void*)data; + sk->num = 1; +#ifdef OPENSSL_ALL + if (sk->hash_fn) { + sk->hash = sk->hash_fn(sk->data.generic); + } +#endif + return WOLFSSL_SUCCESS; + } + break; } - void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl) - { - return ssl ? ssl->options.psk_ctx : NULL; - } - void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx) - { - return ctx ? ctx->psk_ctx : NULL; - } - int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx) - { - if (ssl == NULL) - return WOLFSSL_FAILURE; - ssl->options.psk_ctx = psk_ctx; - return WOLFSSL_SUCCESS; - } - int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx) - { - if (ctx == NULL) - return WOLFSSL_FAILURE; - ctx->psk_ctx = psk_ctx; - return WOLFSSL_SUCCESS; + /* stack already has value(s) create a new node and add more */ + node = wolfSSL_sk_new_node(sk->heap); + if (!node) { + WOLFSSL_MSG("Memory error"); + return WOLFSSL_FAILURE; } -#endif /* NO_PSK */ + /* push new x509 onto head of stack */ + node->next = sk->next; + node->type = sk->type; + sk->next = node; + sk->num += 1; -#ifdef HAVE_ANON +#ifdef OPENSSL_ALL + node->hash_fn = sk->hash_fn; + node->hash = sk->hash; + sk->hash = 0; +#endif + switch (sk->type) { + case STACK_TYPE_CIPHER: +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + node->data.cipher = sk->data.cipher; + sk->data.cipher = *(WOLFSSL_CIPHER*)data; + if (sk->hash_fn) { + sk->hash = sk->hash_fn(&sk->data.cipher); + } + break; +#endif + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + /* All other types are pointers */ + node->data.generic = sk->data.generic; + sk->data.generic = (void*)data; +#ifdef OPENSSL_ALL + if (sk->hash_fn) { + sk->hash = sk->hash_fn(sk->data.generic); + } +#endif + break; + } - int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher"); + return WOLFSSL_SUCCESS; +} - if (ctx == NULL) - return WOLFSSL_FAILURE; +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - ctx->useAnon = 1; +#ifdef OPENSSL_EXTRA - return WOLFSSL_SUCCESS; - } - -#endif /* HAVE_ANON */ +/* returns the node at index "idx", NULL if not found */ +WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx) +{ + int i; + WOLFSSL_STACK* ret = NULL; + WOLFSSL_STACK* current; + current = sk; + for (i = 0; i <= idx && current != NULL; i++) { + if (i == idx) { + ret = current; + break; + } + current = current->next; + } + return ret; +} -#ifndef NO_CERTS -/* used to be defined on NO_FILESYSTEM only, but are generally useful */ - int wolfSSL_CTX_load_verify_buffer_ex(WOLFSSL_CTX* ctx, - const unsigned char* in, - long sz, int format, int userChain, - word32 flags) - { - int verify; - int ret = WOLFSSL_FAILURE; +#endif /* OPENSSL_EXTRA */ - WOLFSSL_ENTER("wolfSSL_CTX_load_verify_buffer_ex"); +#ifdef OPENSSL_EXTRA - verify = GET_VERIFY_SETTING_CTX(ctx); - if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) - verify = VERIFY_SKIP_DATE; +#if defined(OPENSSL_ALL) - if (format == WOLFSSL_FILETYPE_PEM) - ret = ProcessChainBuffer(ctx, in, sz, format, CA_TYPE, NULL, - verify); - else - ret = ProcessBuffer(ctx, in, sz, format, CA_TYPE, NULL, NULL, - userChain, verify); -#if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) - if (ret == WOLFSSL_SUCCESS) - ret = wolfSSL_CTX_trust_peer_buffer(ctx, in, sz, format); -#endif +void *wolfSSL_lh_retrieve(WOLFSSL_STACK *sk, void *data) +{ + unsigned long hash; - WOLFSSL_LEAVE("wolfSSL_CTX_load_verify_buffer_ex", ret); - return ret; - } + WOLFSSL_ENTER("wolfSSL_lh_retrieve"); - /* wolfSSL extension allows DER files to be loaded from buffers as well */ - int wolfSSL_CTX_load_verify_buffer(WOLFSSL_CTX* ctx, - const unsigned char* in, - long sz, int format) - { - return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 0, - WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); + if (!sk || !data) { + WOLFSSL_MSG("Bad parameters"); + return NULL; } - int wolfSSL_CTX_load_verify_chain_buffer_format(WOLFSSL_CTX* ctx, - const unsigned char* in, - long sz, int format) - { - return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 1, - WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); + if (!sk->hash_fn) { + WOLFSSL_MSG("No hash function defined"); + return NULL; } + hash = sk->hash_fn(data); -#ifdef WOLFSSL_TRUST_PEER_CERT - int wolfSSL_CTX_trust_peer_buffer(WOLFSSL_CTX* ctx, - const unsigned char* in, - long sz, int format) - { - int verify; - WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_buffer"); - - /* sanity check on arguments */ - if (sz < 0 || in == NULL || ctx == NULL) { - return BAD_FUNC_ARG; + while (sk) { + /* Calc hash if not done so yet */ + if (!sk->hash) { + switch (sk->type) { + case STACK_TYPE_CIPHER: + sk->hash = sk->hash_fn(&sk->data.cipher); + break; + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + sk->hash = sk->hash_fn(sk->data.generic); + break; + } } - - #if (WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) - verify = VERIFY_SKIP_DATE; - #else - verify = GET_VERIFY_SETTING_CTX(ctx); - #endif - - if (format == WOLFSSL_FILETYPE_PEM) - return ProcessChainBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE, - NULL, verify); - else - return ProcessBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE, NULL, - NULL, 0, verify); + if (sk->hash == hash) { + switch (sk->type) { + case STACK_TYPE_CIPHER: + return &sk->data.cipher; + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + return sk->data.generic; + } + } + sk = sk->next; } -#endif /* WOLFSSL_TRUST_PEER_CERT */ - - int wolfSSL_CTX_use_certificate_buffer(WOLFSSL_CTX* ctx, - const unsigned char* in, long sz, int format) - { - int ret = WOLFSSL_FAILURE; - - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_buffer"); - ret = ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)); - WOLFSSL_LEAVE("wolfSSL_CTX_use_certificate_buffer", ret); - return ret; - } + return NULL; +} +#endif /* OPENSSL_ALL */ - int wolfSSL_CTX_use_PrivateKey_buffer(WOLFSSL_CTX* ctx, - const unsigned char* in, long sz, int format) - { - int ret = WOLFSSL_FAILURE; +#endif /* OPENSSL_EXTRA */ - WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_buffer"); - ret = ProcessBuffer(ctx, in, sz, format, PRIVATEKEY_TYPE, NULL, NULL, - 0, GET_VERIFY_SETTING_CTX(ctx)); - WOLFSSL_LEAVE("wolfSSL_CTX_use_PrivateKey_buffer", ret); - return ret; +/* OPENSSL_EXTRA is needed for wolfSSL_X509_d21 function + KEEP_OUR_CERT is to insure ability for returning ssl certificate */ +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ + defined(KEEP_OUR_CERT) +WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl) +{ + if (ssl == NULL) { + return NULL; } -#ifdef WOLF_PRIVATE_KEY_ID - int wolfSSL_CTX_use_PrivateKey_id(WOLFSSL_CTX* ctx, const unsigned char* id, - long sz, int devId, long keySz) - { - int ret = wolfSSL_CTX_use_PrivateKey_Id(ctx, id, sz, devId); - - if (ret == WOLFSSL_SUCCESS) - ctx->privateKeySz = (word32)keySz; - - return ret; + if (ssl->buffers.weOwnCert) { + if (ssl->ourCert == NULL) { + if (ssl->buffers.certificate == NULL) { + WOLFSSL_MSG("Certificate buffer not set!"); + return NULL; + } + #ifndef WOLFSSL_X509_STORE_CERTS + ssl->ourCert = wolfSSL_X509_d2i_ex(NULL, + ssl->buffers.certificate->buffer, + ssl->buffers.certificate->length, + ssl->heap); + #endif + } + return ssl->ourCert; } - - int wolfSSL_CTX_use_PrivateKey_Id(WOLFSSL_CTX* ctx, const unsigned char* id, - long sz, int devId) - { - int ret = WOLFSSL_FAILURE; - - FreeDer(&ctx->privateKey); - if (AllocDer(&ctx->privateKey, (word32)sz, PRIVATEKEY_TYPE, - ctx->heap) == 0) { - XMEMCPY(ctx->privateKey->buffer, id, sz); - ctx->privateKeyId = 1; - if (devId != INVALID_DEVID) - ctx->privateKeyDevId = devId; - else - ctx->privateKeyDevId = ctx->devId; - - ret = WOLFSSL_SUCCESS; + else { /* if cert not owned get parent ctx cert or return null */ + if (ssl->ctx) { + if (ssl->ctx->ourCert == NULL) { + if (ssl->ctx->certificate == NULL) { + WOLFSSL_MSG("Ctx Certificate buffer not set!"); + return NULL; + } + #ifndef WOLFSSL_X509_STORE_CERTS + ssl->ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, + ssl->ctx->certificate->buffer, + ssl->ctx->certificate->length, + ssl->heap); + #endif + ssl->ctx->ownOurCert = 1; + } + return ssl->ctx->ourCert; } - - return ret; } - int wolfSSL_CTX_use_PrivateKey_Label(WOLFSSL_CTX* ctx, const char* label, - int devId) - { - int ret = WOLFSSL_FAILURE; - word32 sz = (word32)XSTRLEN(label) + 1; - - FreeDer(&ctx->privateKey); - if (AllocDer(&ctx->privateKey, (word32)sz, PRIVATEKEY_TYPE, - ctx->heap) == 0) { - XMEMCPY(ctx->privateKey->buffer, label, sz); - ctx->privateKeyLabel = 1; - if (devId != INVALID_DEVID) - ctx->privateKeyDevId = devId; - else - ctx->privateKeyDevId = ctx->devId; + return NULL; +} - ret = WOLFSSL_SUCCESS; +WOLFSSL_X509* wolfSSL_CTX_get0_certificate(WOLFSSL_CTX* ctx) +{ + if (ctx) { + if (ctx->ourCert == NULL) { + if (ctx->certificate == NULL) { + WOLFSSL_MSG("Ctx Certificate buffer not set!"); + return NULL; + } + #ifndef WOLFSSL_X509_STORE_CERTS + ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, + ctx->certificate->buffer, + ctx->certificate->length, ctx->heap); + #endif + ctx->ownOurCert = 1; } - - return ret; + return ctx->ourCert; } -#endif /* WOLF_PRIVATE_KEY_ID */ + return NULL; +} +#endif /* OPENSSL_EXTRA && KEEP_OUR_CERT */ +#endif /* NO_CERTS */ - int wolfSSL_CTX_use_certificate_chain_buffer_format(WOLFSSL_CTX* ctx, - const unsigned char* in, long sz, int format) - { - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_buffer_format"); - return ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 1, - GET_VERIFY_SETTING_CTX(ctx)); +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) +void wolfSSL_set_connect_state(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_set_connect_state"); + if (ssl == NULL) { + WOLFSSL_MSG("WOLFSSL struct pointer passed in was null"); + return; } - int wolfSSL_CTX_use_certificate_chain_buffer(WOLFSSL_CTX* ctx, - const unsigned char* in, long sz) - { - return wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, in, sz, - WOLFSSL_FILETYPE_PEM); + #ifndef NO_DH + /* client creates its own DH parameters on handshake */ + if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) { + XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + } + ssl->buffers.serverDH_P.buffer = NULL; + if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) { + XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); } + ssl->buffers.serverDH_G.buffer = NULL; + #endif + if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error initializing client side"); + } +} +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -#ifndef NO_DH - /* server wrapper for ctx or ssl Diffie-Hellman parameters */ - static int wolfSSL_SetTmpDH_buffer_wrapper(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - const unsigned char* buf, - long sz, int format) - { - DerBuffer* der = NULL; - int ret = 0; - word32 pSz = MAX_DH_SIZE; - word32 gSz = MAX_DH_SIZE; - #ifdef WOLFSSL_SMALL_STACK - byte* p = NULL; - byte* g = NULL; - #else - byte p[MAX_DH_SIZE]; - byte g[MAX_DH_SIZE]; - #endif +int wolfSSL_get_shutdown(const WOLFSSL* ssl) +{ + int isShutdown = 0; - if (ctx == NULL || buf == NULL) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wolfSSL_get_shutdown"); - ret = AllocDer(&der, 0, DH_PARAM_TYPE, ctx->heap); - if (ret != 0) { - return ret; + if (ssl) { +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) + if (ssl->options.shutdownDone) { + /* The SSL object was possibly cleared with wolfSSL_clear after + * a successful shutdown. Simulate a response for a full + * bidirectional shutdown. */ + isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN; } - der->buffer = (byte*)buf; - der->length = (word32)sz; - - #ifdef WOLFSSL_SMALL_STACK - p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - - if (p == NULL || g == NULL) { - XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - return MEMORY_E; + else +#endif + { + /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent * + * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */ + if (ssl->options.sentNotify) + isShutdown |= WOLFSSL_SENT_SHUTDOWN; + if (ssl->options.closeNotify||ssl->options.connReset) + isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN; } - #endif - if (format != WOLFSSL_FILETYPE_ASN1 && format != WOLFSSL_FILETYPE_PEM) - ret = WOLFSSL_BAD_FILETYPE; - else { - if (format == WOLFSSL_FILETYPE_PEM) { -#ifdef WOLFSSL_PEM_TO_DER - FreeDer(&der); - ret = PemToDer(buf, sz, DH_PARAM_TYPE, &der, ctx->heap, - NULL, NULL); - if (ret < 0) { - /* Also try X9.42 format */ - ret = PemToDer(buf, sz, X942_PARAM_TYPE, &der, ctx->heap, - NULL, NULL); - } - #ifdef WOLFSSL_WPAS - #ifndef NO_DSA - if (ret < 0) { - ret = PemToDer(buf, sz, DSA_PARAM_TYPE, &der, ctx->heap, - NULL, NULL); - } - #endif - #endif /* WOLFSSL_WPAS */ -#else - ret = NOT_COMPILED_IN; -#endif /* WOLFSSL_PEM_TO_DER */ - } - - if (ret == 0) { - if (wc_DhParamsLoad(der->buffer, der->length, p, &pSz, g, &gSz) < 0) - ret = WOLFSSL_BAD_FILETYPE; - else if (ssl) - ret = wolfSSL_SetTmpDH(ssl, p, pSz, g, gSz); - else - ret = wolfSSL_CTX_SetTmpDH(ctx, p, pSz, g, gSz); - } - } - - FreeDer(&der); - - #ifdef WOLFSSL_SMALL_STACK - XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - #endif - - return ret; } + WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown); + return isShutdown; +} - /* server Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */ - int wolfSSL_SetTmpDH_buffer(WOLFSSL* ssl, const unsigned char* buf, long sz, - int format) - { - if (ssl == NULL) - return BAD_FUNC_ARG; - return wolfSSL_SetTmpDH_buffer_wrapper(ssl->ctx, ssl, buf, sz, format); +int wolfSSL_session_reused(WOLFSSL* ssl) +{ + int resuming = 0; + WOLFSSL_ENTER("wolfSSL_session_reused"); + if (ssl) { +#ifndef HAVE_SECURE_RENEGOTIATION + resuming = ssl->options.resuming; +#else + resuming = ssl->options.resuming || ssl->options.resumed; +#endif } + WOLFSSL_LEAVE("wolfSSL_session_reused", resuming); + return resuming; +} +/* helper function that takes in a protocol version struct and returns string */ +static const char* wolfSSL_internal_get_version(const ProtocolVersion* version) +{ + WOLFSSL_ENTER("wolfSSL_get_version"); - /* server ctx Diffie-Hellman parameters, WOLFSSL_SUCCESS on ok */ - int wolfSSL_CTX_SetTmpDH_buffer(WOLFSSL_CTX* ctx, const unsigned char* buf, - long sz, int format) - { - return wolfSSL_SetTmpDH_buffer_wrapper(ctx, NULL, buf, sz, format); + if (version == NULL) { + return "Bad arg"; } -#endif /* NO_DH */ - + if (version->major == SSLv3_MAJOR) { + switch (version->minor) { + case SSLv3_MINOR : + return "SSLv3"; + case TLSv1_MINOR : + return "TLSv1"; + case TLSv1_1_MINOR : + return "TLSv1.1"; + case TLSv1_2_MINOR : + return "TLSv1.2"; + case TLSv1_3_MINOR : + return "TLSv1.3"; + default: + return "unknown"; + } + } +#ifdef WOLFSSL_DTLS + else if (version->major == DTLS_MAJOR) { + switch (version->minor) { + case DTLS_MINOR : + return "DTLS"; + case DTLSv1_2_MINOR : + return "DTLSv1.2"; + case DTLSv1_3_MINOR : + return "DTLSv1.3"; + default: + return "unknown"; + } + } +#endif /* WOLFSSL_DTLS */ + return "unknown"; +} - int wolfSSL_use_certificate_buffer(WOLFSSL* ssl, - const unsigned char* in, long sz, int format) - { - WOLFSSL_ENTER("wolfSSL_use_certificate_buffer"); - if (ssl == NULL) - return BAD_FUNC_ARG; - return ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 0, - GET_VERIFY_SETTING_SSL(ssl)); +const char* wolfSSL_get_version(const WOLFSSL* ssl) +{ + if (ssl == NULL) { + WOLFSSL_MSG("Bad argument"); + return "unknown"; } + return wolfSSL_internal_get_version(&ssl->version); +} - int wolfSSL_use_PrivateKey_buffer(WOLFSSL* ssl, - const unsigned char* in, long sz, int format) - { - WOLFSSL_ENTER("wolfSSL_use_PrivateKey_buffer"); - if (ssl == NULL) - return BAD_FUNC_ARG; - - return ProcessBuffer(ssl->ctx, in, sz, format, PRIVATEKEY_TYPE, - ssl, NULL, 0, GET_VERIFY_SETTING_SSL(ssl)); - } -#ifdef WOLF_PRIVATE_KEY_ID - int wolfSSL_use_PrivateKey_id(WOLFSSL* ssl, const unsigned char* id, - long sz, int devId, long keySz) - { - int ret = wolfSSL_use_PrivateKey_Id(ssl, id, sz, devId); +/* current library version */ +const char* wolfSSL_lib_version(void) +{ + return LIBWOLFSSL_VERSION_STRING; +} - if (ret == WOLFSSL_SUCCESS) - ssl->buffers.keySz = (word32)keySz; +#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L +const char* wolfSSL_OpenSSL_version(int a) +{ + (void)a; + return "wolfSSL " LIBWOLFSSL_VERSION_STRING; +} +#else +const char* wolfSSL_OpenSSL_version(void) +{ + return "wolfSSL " LIBWOLFSSL_VERSION_STRING; +} +#endif /* WOLFSSL_QT */ +#endif - return ret; - } - int wolfSSL_use_PrivateKey_Id(WOLFSSL* ssl, const unsigned char* id, - long sz, int devId) - { - int ret = WOLFSSL_FAILURE; +/* current library version in hex */ +word32 wolfSSL_lib_version_hex(void) +{ + return LIBWOLFSSL_VERSION_HEX; +} - if (ssl->buffers.weOwnKey) - FreeDer(&ssl->buffers.key); - if (AllocDer(&ssl->buffers.key, (word32)sz, PRIVATEKEY_TYPE, - ssl->heap) == 0) { - XMEMCPY(ssl->buffers.key->buffer, id, sz); - ssl->buffers.weOwnKey = 1; - ssl->buffers.keyId = 1; - if (devId != INVALID_DEVID) - ssl->buffers.keyDevId = devId; - else - ssl->buffers.keyDevId = ssl->devId; - ret = WOLFSSL_SUCCESS; - } +int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite"); + if (ssl) + return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite; + return 0; +} - return ret; +WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_current_cipher"); + if (ssl) { + ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0; + ssl->cipher.cipherSuite = ssl->options.cipherSuite; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + ssl->cipher.bits = ssl->specs.key_size * 8; +#endif + return &ssl->cipher; } + else + return NULL; +} - int wolfSSL_use_PrivateKey_Label(WOLFSSL* ssl, const char* label, int devId) - { - int ret = WOLFSSL_FAILURE; - word32 sz = (word32)XSTRLEN(label) + 1; - - if (ssl->buffers.weOwnKey) - FreeDer(&ssl->buffers.key); - if (AllocDer(&ssl->buffers.key, (word32)sz, PRIVATEKEY_TYPE, - ssl->heap) == 0) { - XMEMCPY(ssl->buffers.key->buffer, label, sz); - ssl->buffers.weOwnKey = 1; - ssl->buffers.keyLabel = 1; - if (devId != INVALID_DEVID) - ssl->buffers.keyDevId = devId; - else - ssl->buffers.keyDevId = ssl->devId; - ret = WOLFSSL_SUCCESS; - } +const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher) +{ + WOLFSSL_ENTER("wolfSSL_CIPHER_get_name"); - return ret; + if (cipher == NULL) { + return NULL; } -#endif /* WOLF_PRIVATE_KEY_ID */ - int wolfSSL_use_certificate_chain_buffer_format(WOLFSSL* ssl, - const unsigned char* in, long sz, int format) - { - WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format"); - if (ssl == NULL) - return BAD_FUNC_ARG; + #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \ + !defined(WOLFSSL_QT) + return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite); + #else + return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0, + cipher->cipherSuite); + #endif +} - return ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, - ssl, NULL, 1, GET_VERIFY_SETTING_SSL(ssl)); - } +const char* wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher) +{ + WOLFSSL_ENTER("wolfSSL_CIPHER_get_version"); - int wolfSSL_use_certificate_chain_buffer(WOLFSSL* ssl, - const unsigned char* in, long sz) - { - return wolfSSL_use_certificate_chain_buffer_format(ssl, in, sz, - WOLFSSL_FILETYPE_PEM); + if (cipher == NULL || cipher->ssl == NULL) { + return NULL; } + return wolfSSL_get_version(cipher->ssl); +} - /* unload any certs or keys that SSL owns, leave CTX as is - WOLFSSL_SUCCESS on ok */ - int wolfSSL_UnloadCertsKeys(WOLFSSL* ssl) - { - if (ssl == NULL) { - WOLFSSL_MSG("Null function arg"); - return BAD_FUNC_ARG; - } +const char* wolfSSL_get_cipher(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_cipher"); + return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl)); +} - if (ssl->buffers.weOwnCert && !ssl->keepCert) { - WOLFSSL_MSG("Unloading cert"); - FreeDer(&ssl->buffers.certificate); - #ifdef KEEP_OUR_CERT - wolfSSL_X509_free(ssl->ourCert); - ssl->ourCert = NULL; - #endif - ssl->buffers.weOwnCert = 0; - } +/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */ +const char* wolfSSL_get_cipher_name(WOLFSSL* ssl) +{ + /* get access to cipher_name_idx in internal.c */ + return wolfSSL_get_cipher_name_internal(ssl); +} - if (ssl->buffers.weOwnCertChain) { - WOLFSSL_MSG("Unloading cert chain"); - FreeDer(&ssl->buffers.certChain); - ssl->buffers.weOwnCertChain = 0; - } +const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0, + byte cipherSuite) +{ + return GetCipherNameInternal(cipherSuite0, cipherSuite); +} - if (ssl->buffers.weOwnKey) { - WOLFSSL_MSG("Unloading key"); - ForceZero(ssl->buffers.key->buffer, ssl->buffers.key->length); - FreeDer(&ssl->buffers.key); - ssl->buffers.weOwnKey = 0; - } +const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0, + byte cipherSuite) +{ + return GetCipherNameIana(cipherSuite0, cipherSuite); +} -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (ssl->buffers.weOwnAltKey) { - WOLFSSL_MSG("Unloading alt key"); - ForceZero(ssl->buffers.altKey->buffer, ssl->buffers.altKey->length); - FreeDer(&ssl->buffers.altKey); - ssl->buffers.weOwnAltKey = 0; - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ +int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0, + byte* cipherSuite, int *flags) { + if ((name == NULL) || + (cipherSuite0 == NULL) || + (cipherSuite == NULL) || + (flags == NULL)) + return BAD_FUNC_ARG; + return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, flags); +} - return WOLFSSL_SUCCESS; - } +#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) +/* Creates and returns a new WOLFSSL_CIPHER stack. */ +WOLFSSL_STACK* wolfSSL_sk_new_cipher(void) +{ + WOLFSSL_STACK* sk; + WOLFSSL_ENTER("wolfSSL_sk_new_cipher"); - int wolfSSL_CTX_UnloadCAs(WOLFSSL_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_UnloadCAs"); + sk = wolfSSL_sk_new_null(); + if (sk == NULL) + return NULL; + sk->type = STACK_TYPE_CIPHER; - if (ctx == NULL) - return BAD_FUNC_ARG; + return sk; +} - return wolfSSL_CertManagerUnloadCAs(ctx->cm); - } +/* return 1 on success 0 on fail */ +int wolfSSL_sk_CIPHER_push(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, + WOLFSSL_CIPHER* cipher) +{ + return wolfSSL_sk_push(sk, cipher); +} - int wolfSSL_CTX_UnloadIntermediateCerts(WOLFSSL_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_UnloadIntermediateCerts"); +#ifndef NO_WOLFSSL_STUB +WOLFSSL_CIPHER* wolfSSL_sk_CIPHER_pop(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) +{ + WOLFSSL_STUB("wolfSSL_sk_CIPHER_pop"); + (void)sk; + return NULL; +} +#endif /* NO_WOLFSSL_STUB */ +#endif /* WOLFSSL_QT || OPENSSL_ALL */ - if (ctx == NULL) - return BAD_FUNC_ARG; +word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher) +{ + word16 cipher_id = 0; - if (ctx->ref.count > 1) { - WOLFSSL_MSG("ctx object must have a ref count of 1 before " - "unloading intermediate certs"); - return BAD_STATE_E; - } + WOLFSSL_ENTER("wolfSSL_CIPHER_get_id"); - return wolfSSL_CertManagerUnloadIntermediateCerts(ctx->cm); + if (cipher && cipher->ssl) { + cipher_id = (cipher->ssl->options.cipherSuite0 << 8) | + cipher->ssl->options.cipherSuite; } + return cipher_id; +} -#ifdef WOLFSSL_TRUST_PEER_CERT - int wolfSSL_CTX_Unload_trust_peers(WOLFSSL_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers"); - - if (ctx == NULL) - return BAD_FUNC_ARG; +const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value) +{ + const WOLFSSL_CIPHER* cipher = NULL; + byte cipherSuite0, cipherSuite; + WOLFSSL_ENTER("wolfSSL_get_cipher_by_value"); - return wolfSSL_CertManagerUnload_trust_peers(ctx->cm); - } + /* extract cipher id information */ + cipherSuite = (value & 0xFF); + cipherSuite0 = ((value >> 8) & 0xFF); -#ifdef WOLFSSL_LOCAL_X509_STORE - int wolfSSL_Unload_trust_peers(WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_CTX_Unload_trust_peers"); + /* TODO: lookup by cipherSuite0 / cipherSuite */ + (void)cipherSuite0; + (void)cipherSuite; - if (ssl == NULL) - return BAD_FUNC_ARG; + return cipher; +} - SSL_CM_WARNING(ssl); - return wolfSSL_CertManagerUnload_trust_peers(SSL_CM(ssl)); - } -#endif /* WOLFSSL_LOCAL_X509_STORE */ -#endif /* WOLFSSL_TRUST_PEER_CERT */ -/* old NO_FILESYSTEM end */ -#endif /* !NO_CERTS */ +#if defined(OPENSSL_EXTRA) +/* Free the structure for WOLFSSL_CIPHER stack + * + * sk stack to free nodes in + */ +void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) +{ + WOLFSSL_ENTER("wolfSSL_sk_CIPHER_free"); -#ifdef OPENSSL_EXTRA + wolfSSL_sk_free(sk); +} +#endif /* OPENSSL_ALL */ - int wolfSSL_add_all_algorithms(void) - { - WOLFSSL_ENTER("wolfSSL_add_all_algorithms"); - if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS) - return WOLFSSL_SUCCESS; - else - return WOLFSSL_FATAL_ERROR; +#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \ + !defined(NO_DH) +#ifdef HAVE_FFDHE +static const char* wolfssl_ffdhe_name(word16 group) +{ + const char* str = NULL; + switch (group) { + case WOLFSSL_FFDHE_2048: + str = "FFDHE_2048"; + break; + case WOLFSSL_FFDHE_3072: + str = "FFDHE_3072"; + break; + case WOLFSSL_FFDHE_4096: + str = "FFDHE_4096"; + break; + case WOLFSSL_FFDHE_6144: + str = "FFDHE_6144"; + break; + case WOLFSSL_FFDHE_8192: + str = "FFDHE_8192"; + break; + default: + break; } + return str; +} +#endif +/* Return the name of the curve used for key exchange as a printable string. + * + * ssl The SSL/TLS object. + * returns NULL if ECDH was not used, otherwise the name as a string. + */ +const char* wolfSSL_get_curve_name(WOLFSSL* ssl) +{ + const char* cName = NULL; - int wolfSSL_OpenSSL_add_all_algorithms_noconf(void) - { - WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf"); - - if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) - return WOLFSSL_FATAL_ERROR; - - return WOLFSSL_SUCCESS; - } + WOLFSSL_ENTER("wolfSSL_get_curve_name"); - int wolfSSL_OpenSSL_add_all_algorithms_conf(void) - { - WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf"); - /* This function is currently the same as - wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ - the use of a wolfssl.cnf type configuration file and is only used for - OpenSSL compatibility. */ + if (ssl == NULL) + return NULL; - if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) { - return WOLFSSL_FATAL_ERROR; +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_KYBER) + /* Check for post-quantum groups. Return now because we do not want the ECC + * check to override this result in the case of a hybrid. */ + if (IsAtLeastTLSv1_3(ssl->version)) { + switch (ssl->namedGroup) { +#ifdef HAVE_LIBOQS + case WOLFSSL_KYBER_LEVEL1: + return "KYBER_LEVEL1"; + case WOLFSSL_KYBER_LEVEL3: + return "KYBER_LEVEL3"; + case WOLFSSL_KYBER_LEVEL5: + return "KYBER_LEVEL5"; + case WOLFSSL_P256_KYBER_LEVEL1: + return "P256_KYBER_LEVEL1"; + case WOLFSSL_P384_KYBER_LEVEL3: + return "P384_KYBER_LEVEL3"; + case WOLFSSL_P521_KYBER_LEVEL5: + return "P521_KYBER_LEVEL5"; +#elif defined(HAVE_PQM4) + case WOLFSSL_KYBER_LEVEL1: + return "KYBER_LEVEL1"; +#elif defined(WOLFSSL_WC_KYBER) + #ifdef WOLFSSL_KYBER512 + case WOLFSSL_KYBER_LEVEL1: + return "KYBER_LEVEL1"; + case WOLFSSL_P256_KYBER_LEVEL1: + return "P256_KYBER_LEVEL1"; + #endif + #ifdef WOLFSSL_KYBER768 + case WOLFSSL_KYBER_LEVEL3: + return "KYBER_LEVEL3"; + case WOLFSSL_P384_KYBER_LEVEL3: + return "P384_KYBER_LEVEL3"; + #endif + #ifdef WOLFSSL_KYBER1024 + case WOLFSSL_KYBER_LEVEL5: + return "KYBER_LEVEL5"; + case WOLFSSL_P521_KYBER_LEVEL5: + return "P521_KYBER_LEVEL5"; + #endif +#endif } - return WOLFSSL_SUCCESS; } +#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_KYBER */ - /* returns previous set cache size which stays constant */ - long wolfSSL_CTX_sess_set_cache_size(WOLFSSL_CTX* ctx, long sz) - { - /* cache size fixed at compile time in wolfSSL */ - (void)ctx; - (void)sz; - WOLFSSL_MSG("session cache is set at compile time"); - #ifndef NO_SESSION_CACHE - return (long)(SESSIONS_PER_ROW * SESSION_ROWS); - #else - return 0; - #endif +#ifdef HAVE_FFDHE + if (ssl->namedGroup != 0) { + cName = wolfssl_ffdhe_name(ssl->namedGroup); } - #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown"); - if (mode) - ctx->quietShutdown = 1; +#ifdef HAVE_CURVE25519 + if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) { + cName = "X25519"; } +#endif - - void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode) - { - WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown"); - if (mode) - ssl->options.quietShutdown = 1; +#ifdef HAVE_CURVE448 + if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) { + cName = "X448"; } -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || - WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ +#endif -#ifdef OPENSSL_EXTRA -#ifndef NO_BIO - void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr) - { - WOLFSSL_ENTER("wolfSSL_set_bio"); +#ifdef HAVE_ECC + if (ssl->ecdhCurveOID != 0 && cName == NULL) { + cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, + NULL)); + } +#endif - if (ssl == NULL) { - WOLFSSL_MSG("Bad argument, ssl was NULL"); - return; - } + return cName; +} +#endif - /* free any existing WOLFSSL_BIOs in use but don't free those in - * a chain */ - if (ssl->biord != NULL) { - if (ssl->biord != ssl->biowr) { - if (ssl->biowr != NULL && ssl->biowr->prev != NULL) - wolfSSL_BIO_free(ssl->biowr); - ssl->biowr = NULL; - } - if (ssl->biord->prev != NULL) - wolfSSL_BIO_free(ssl->biord); - ssl->biord = NULL; - } - /* set flag obviously */ - if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ)) - rd->flags |= WOLFSSL_BIO_FLAG_READ; - if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE)) - wr->flags |= WOLFSSL_BIO_FLAG_WRITE; - - ssl->biord = rd; - ssl->biowr = wr; +#ifdef OPENSSL_EXTRA +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) +/* return authentication NID corresponding to cipher suite + * @param cipher a pointer to WOLFSSL_CIPHER + * return NID if found, NID_undef if not found + */ +int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) +{ + static const struct authnid { + const char* alg_name; + const int nid; + } authnid_tbl[] = { + {"RSA", NID_auth_rsa}, + {"PSK", NID_auth_psk}, + {"SRP", NID_auth_srp}, + {"ECDSA", NID_auth_ecdsa}, + {"None", NID_auth_null}, + {NULL, NID_undef} + }; - /* set SSL to use BIO callbacks instead */ - if (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)) { - ssl->CBIORecv = BioReceive; - } - if (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)) { - ssl->CBIOSend = BioSend; - } + const char* authStr; + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - /* User programs should always retry reading from these BIOs */ - if (rd) { - /* User writes to rd */ - BIO_set_retry_write(rd); - } - if (wr) { - /* User reads from wr */ - BIO_set_retry_read(wr); - } + if (GetCipherSegment(cipher, n) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return NID_undef; } -#endif /* !NO_BIO */ -#endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) - void wolfSSL_CTX_set_client_CA_list(WOLFSSL_CTX* ctx, - WOLF_STACK_OF(WOLFSSL_X509_NAME)* names) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_client_CA_list"); - if (ctx != NULL) { - wolfSSL_sk_X509_NAME_pop_free(ctx->client_ca_names, NULL); - ctx->client_ca_names = names; + authStr = GetCipherAuthStr(n); + + if (authStr != NULL) { + const struct authnid* sa; + for(sa = authnid_tbl; sa->alg_name != NULL; sa++) { + if (XSTRCMP(sa->alg_name, authStr) == 0) { + return sa->nid; + } } } - void wolfSSL_set_client_CA_list(WOLFSSL* ssl, - WOLF_STACK_OF(WOLFSSL_X509_NAME)* names) - { - WOLFSSL_ENTER("wolfSSL_set_client_CA_list"); - if (ssl != NULL) { - if (ssl->client_ca_names != ssl->ctx->client_ca_names) - wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL); - ssl->client_ca_names = names; - } + return NID_undef; +} +/* return cipher NID corresponding to cipher suite + * @param cipher a pointer to WOLFSSL_CIPHER + * return NID if found, NID_undef if not found + */ +int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) +{ + static const struct ciphernid { + const char* alg_name; + const int nid; + } ciphernid_tbl[] = { + {"AESGCM(256)", NID_aes_256_gcm}, + {"AESGCM(128)", NID_aes_128_gcm}, + {"AESCCM(128)", NID_aes_128_ccm}, + {"AES(128)", NID_aes_128_cbc}, + {"AES(256)", NID_aes_256_cbc}, + {"CAMELLIA(256)", NID_camellia_256_cbc}, + {"CAMELLIA(128)", NID_camellia_128_cbc}, + {"RC4", NID_rc4}, + {"3DES", NID_des_ede3_cbc}, + {"CHACHA20/POLY1305(256)", NID_chacha20_poly1305}, + {"None", NID_undef}, + {NULL, NID_undef} + }; + + const char* encStr; + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + + WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid"); + + if (GetCipherSegment(cipher, n) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return NID_undef; } - #ifdef OPENSSL_EXTRA - /* registers client cert callback, called during handshake if server - requests client auth but user has not loaded client cert/key */ - void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_client_cert_cb"); + encStr = GetCipherEncStr(n); - if (ctx != NULL) { - ctx->CBClientCert = cb; + if (encStr != NULL) { + const struct ciphernid* c; + for(c = ciphernid_tbl; c->alg_name != NULL; c++) { + if (XSTRCMP(c->alg_name, encStr) == 0) { + return c->nid; + } } } - void wolfSSL_CTX_set_cert_cb(WOLFSSL_CTX* ctx, - CertSetupCallback cb, void *arg) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_cert_cb"); - if (ctx == NULL) - return; + return NID_undef; +} +/* return digest NID corresponding to cipher suite + * @param cipher a pointer to WOLFSSL_CIPHER + * return NID if found, NID_undef if not found + */ +int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) +{ + static const struct macnid { + const char* alg_name; + const int nid; + } macnid_tbl[] = { + {"SHA1", NID_sha1}, + {"SHA256", NID_sha256}, + {"SHA384", NID_sha384}, + {NULL, NID_undef} + }; - ctx->certSetupCb = cb; - ctx->certSetupCbArg = arg; + const char* name; + const char* macStr; + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + (void)name; + + WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid"); + + if ((name = GetCipherSegment(cipher, n)) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return NID_undef; } - int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl, - const byte** suites, word16* suiteSz, - const byte** hashSigAlgo, word16* hashSigAlgoSz) - { - WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs"); + /* in MD5 case, NID will be NID_md5 */ + if (XSTRSTR(name, "MD5") != NULL) { + return NID_md5; + } - if (suites != NULL) - *suites = NULL; - if (suiteSz != NULL) - *suiteSz = 0; - if (hashSigAlgo != NULL) - *hashSigAlgo = NULL; - if (hashSigAlgoSz != NULL) - *hashSigAlgoSz = 0; + macStr = GetCipherMacStr(n); - if (ssl != NULL && ssl->clSuites != NULL) { - if (suites != NULL && suiteSz != NULL) { - *suites = ssl->clSuites->suites; - *suiteSz = ssl->clSuites->suiteSz; - } - if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) { - *hashSigAlgo = ssl->clSuites->hashSigAlgo; - *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz; + if (macStr != NULL) { + const struct macnid* mc; + for(mc = macnid_tbl; mc->alg_name != NULL; mc++) { + if (XSTRCMP(mc->alg_name, macStr) == 0) { + return mc->nid; } - return WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; - } - WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first, - byte second) - { - WOLFSSL_CIPHERSUITE_INFO info; - info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) || - CipherRequires(first, second, REQUIRES_RSA_SIG)); - info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) || - /* Static ECC ciphers may require RSA for authentication */ - (CipherRequires(first, second, REQUIRES_ECC_STATIC) && - !CipherRequires(first, second, REQUIRES_RSA_SIG))); - info.eccStatic = - (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC); - info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK); - return info; } - /** - * @param first First byte of the hash and signature algorithm - * @param second Second byte of the hash and signature algorithm - * @param hashAlgo The enum wc_HashType of the MAC algorithm - * @param sigAlgo The enum Key_Sum of the authentication algorithm - */ - int wolfSSL_get_sigalg_info(byte first, byte second, - int* hashAlgo, int* sigAlgo) - { - byte input[2]; - byte hashType; - byte sigType; + return NID_undef; +} +/* return key exchange NID corresponding to cipher suite + * @param cipher a pointer to WOLFSSL_CIPHER + * return NID if found, NID_undef if not found + */ +int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) +{ + static const struct kxnid { + const char* name; + const int nid; + } kxnid_table[] = { + {"ECDHEPSK", NID_kx_ecdhe_psk}, + {"ECDH", NID_kx_ecdhe}, + {"DHEPSK", NID_kx_dhe_psk}, + {"DH", NID_kx_dhe}, + {"RSAPSK", NID_kx_rsa_psk}, + {"SRP", NID_kx_srp}, + {"EDH", NID_kx_dhe}, + {"RSA", NID_kx_rsa}, + {NULL, NID_undef} + }; - if (hashAlgo == NULL || sigAlgo == NULL) - return BAD_FUNC_ARG; + const char* keaStr; + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - input[0] = first; - input[1] = second; - DecodeSigAlg(input, &hashType, &sigType); + WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid"); - /* cast so that compiler reminds us of unimplemented values */ - switch ((enum SignatureAlgorithm)sigType) { - case anonymous_sa_algo: - *sigAlgo = ANONk; - break; - case rsa_sa_algo: - *sigAlgo = RSAk; - break; - case dsa_sa_algo: - *sigAlgo = DSAk; - break; - case ecc_dsa_sa_algo: - *sigAlgo = ECDSAk; - break; - case rsa_pss_sa_algo: - *sigAlgo = RSAPSSk; - break; - case ed25519_sa_algo: - *sigAlgo = ED25519k; - break; - case rsa_pss_pss_algo: - *sigAlgo = RSAPSSk; - break; - case ed448_sa_algo: - *sigAlgo = ED448k; - break; - case falcon_level1_sa_algo: - *sigAlgo = FALCON_LEVEL1k; - break; - case falcon_level5_sa_algo: - *sigAlgo = FALCON_LEVEL5k; - break; - case dilithium_level2_sa_algo: - *sigAlgo = DILITHIUM_LEVEL2k; - break; - case dilithium_level3_sa_algo: - *sigAlgo = DILITHIUM_LEVEL3k; - break; - case dilithium_level5_sa_algo: - *sigAlgo = DILITHIUM_LEVEL5k; - break; - case sm2_sa_algo: - *sigAlgo = SM2k; - break; - case invalid_sa_algo: - default: - *hashAlgo = WC_HASH_TYPE_NONE; - *sigAlgo = 0; - return BAD_FUNC_ARG; - } - - /* cast so that compiler reminds us of unimplemented values */ - switch((enum wc_MACAlgorithm)hashType) { - case no_mac: - case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */ - *hashAlgo = WC_HASH_TYPE_NONE; - break; - case md5_mac: - *hashAlgo = WC_HASH_TYPE_MD5; - break; - case sha_mac: - *hashAlgo = WC_HASH_TYPE_SHA; - break; - case sha224_mac: - *hashAlgo = WC_HASH_TYPE_SHA224; - break; - case sha256_mac: - *hashAlgo = WC_HASH_TYPE_SHA256; - break; - case sha384_mac: - *hashAlgo = WC_HASH_TYPE_SHA384; - break; - case sha512_mac: - *hashAlgo = WC_HASH_TYPE_SHA512; - break; - case blake2b_mac: - *hashAlgo = WC_HASH_TYPE_BLAKE2B; - break; - case sm3_mac: -#ifdef WOLFSSL_SM3 - *hashAlgo = WC_HASH_TYPE_SM3; -#else - *hashAlgo = WC_HASH_TYPE_NONE; -#endif - break; - default: - *hashAlgo = WC_HASH_TYPE_NONE; - *sigAlgo = 0; - return BAD_FUNC_ARG; - } - return 0; + if (GetCipherSegment(cipher, n) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return NID_undef; } - /** - * Internal wrapper for calling certSetupCb - * @param ssl The SSL/TLS Object - * @return 0 on success - */ - int CertSetupCbWrapper(WOLFSSL* ssl) - { - int ret = 0; - if (ssl->ctx->certSetupCb != NULL) { - WOLFSSL_MSG("Calling user cert setup callback"); - ret = ssl->ctx->certSetupCb(ssl, ssl->ctx->certSetupCbArg); - if (ret == 1) { - WOLFSSL_MSG("User cert callback returned success"); - ret = 0; - } - else if (ret == 0) { - SendAlert(ssl, alert_fatal, internal_error); - ret = CLIENT_CERT_CB_ERROR; - } - else if (ret < 0) { - ret = WOLFSSL_ERROR_WANT_X509_LOOKUP; - } - else { - WOLFSSL_MSG("Unexpected user callback return"); - ret = CLIENT_CERT_CB_ERROR; - } - } - return ret; + /* in TLS 1.3 case, NID will be NID_kx_any */ + if (XSTRCMP(n[0], "TLS13") == 0) { + return NID_kx_any; } - #endif /* OPENSSL_EXTRA */ - -#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || HAVE_WEBSERVER */ -#ifndef WOLFSSL_NO_CA_NAMES - WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list( - const WOLFSSL_CTX *ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_get_client_CA_list"); + keaStr = GetCipherKeaStr(n); - if (ctx == NULL) { - WOLFSSL_MSG("Bad argument passed to wolfSSL_CTX_get_client_CA_list"); - return NULL; + if (keaStr != NULL) { + const struct kxnid* k; + for(k = kxnid_table; k->name != NULL; k++) { + if (XSTRCMP(k->name, keaStr) == 0) { + return k->nid; + } } - - return ctx->client_ca_names; } - /* returns the CA's set on server side or the CA's sent from server when - * on client side */ - WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get_client_CA_list( - const WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_get_client_CA_list"); + return NID_undef; +} +/* check if cipher suite is AEAD + * @param cipher a pointer to WOLFSSL_CIPHER + * return 1 if cipher is AEAD, 0 otherwise + */ +int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher) +{ + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - if (ssl == NULL) { - WOLFSSL_MSG("Bad argument passed to wolfSSL_get_client_CA_list"); - return NULL; - } + WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead"); - return SSL_CA_NAMES(ssl); + if (GetCipherSegment(cipher, n) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return NID_undef; } - #if !defined(NO_CERTS) - int wolfSSL_CTX_add_client_CA(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) - { - WOLFSSL_X509_NAME *nameCopy = NULL; + return IsCipherAEAD(n); +} +/* Creates cipher->description based on cipher->offset + * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added + * to a stack of ciphers. + * @param [in] cipher: A cipher from a stack of ciphers. + * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE + */ +int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher) +{ + int strLen; + unsigned long offset; + char* dp; + const char* name; + const char *keaStr, *authStr, *encStr, *macStr, *protocol; + char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + int len = MAX_DESCRIPTION_SZ-1; + const CipherSuiteInfo* cipher_names; + ProtocolVersion pv; + WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description"); - WOLFSSL_ENTER("wolfSSL_CTX_add_client_CA"); + if (cipher == NULL) + return WOLFSSL_FAILURE; - if (ctx == NULL || x509 == NULL){ - WOLFSSL_MSG("Bad argument"); - return WOLFSSL_FAILURE; - } + dp = cipher->description; + if (dp == NULL) + return WOLFSSL_FAILURE; - if (ctx->client_ca_names == NULL) { - ctx->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL); - if (ctx->client_ca_names == NULL) { - WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error"); - return WOLFSSL_FAILURE; - } - } + cipher_names = GetCipherNames(); - nameCopy = wolfSSL_X509_NAME_dup(wolfSSL_X509_get_subject_name(x509)); - if (nameCopy == NULL) { - WOLFSSL_MSG("wolfSSL_X509_NAME_dup error"); - return WOLFSSL_FAILURE; - } + offset = cipher->offset; + if (offset >= (unsigned long)GetCipherNamesSize()) + return WOLFSSL_FAILURE; + pv.major = cipher_names[offset].major; + pv.minor = cipher_names[offset].minor; + protocol = wolfSSL_internal_get_version(&pv); - if (wolfSSL_sk_X509_NAME_push(ctx->client_ca_names, nameCopy) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); - wolfSSL_X509_NAME_free(nameCopy); - return WOLFSSL_FAILURE; - } + if ((name = GetCipherSegment(cipher, n)) == NULL) { + WOLFSSL_MSG("no suitable cipher name found"); + return WOLFSSL_FAILURE; + } - return WOLFSSL_SUCCESS; + /* keaStr */ + keaStr = GetCipherKeaStr(n); + /* authStr */ + authStr = GetCipherAuthStr(n); + /* encStr */ + encStr = GetCipherEncStr(n); + if ((cipher->bits = SetCipherBits(encStr)) == WOLFSSL_FAILURE) { + WOLFSSL_MSG("Cipher Bits Not Set."); } - #endif + /* macStr */ + macStr = GetCipherMacStr(n); - #ifndef NO_BIO - #if !defined(NO_RSA) && !defined(NO_CERTS) - WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_load_client_CA_file(const char* fname) - { - /* The webserver build is using this to load a CA into the server - * for client authentication as an option. Have this return NULL in - * that case. If OPENSSL_EXTRA is enabled, go ahead and include - * the function. */ - #ifdef OPENSSL_EXTRA - WOLFSSL_STACK *list = NULL; - WOLFSSL_BIO* bio = NULL; - WOLFSSL_X509 *cert = NULL; - WOLFSSL_X509_NAME *nameCopy = NULL; - unsigned long err = WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_load_client_CA_file"); + /* Build up the string by copying onto the end. */ + XSTRNCPY(dp, name, len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; - bio = wolfSSL_BIO_new_file(fname, "rb"); - if (bio == NULL) { - WOLFSSL_MSG("wolfSSL_BIO_new_file error"); - goto cleanup; - } - - list = wolfSSL_sk_X509_NAME_new(NULL); - if (list == NULL) { - WOLFSSL_MSG("wolfSSL_sk_X509_NAME_new error"); - goto cleanup; - } + XSTRNCPY(dp, " ", len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; + XSTRNCPY(dp, protocol, len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; - /* Read each certificate in the chain out of the file. */ - while (wolfSSL_PEM_read_bio_X509(bio, &cert, NULL, NULL) != NULL) { - /* Need a persistent copy of the subject name. */ - nameCopy = wolfSSL_X509_NAME_dup( - wolfSSL_X509_get_subject_name(cert)); - if (nameCopy == NULL) { - WOLFSSL_MSG("wolfSSL_X509_NAME_dup error"); - goto cleanup; - } - /* - * Original cert will be freed so make sure not to try to access - * it in the future. - */ - nameCopy->x509 = NULL; + XSTRNCPY(dp, " Kx=", len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; + XSTRNCPY(dp, keaStr, len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; - if (wolfSSL_sk_X509_NAME_push(list, nameCopy) != - WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); - /* Do free in loop because nameCopy is now responsibility - * of list to free and adding jumps to cleanup after this - * might result in a double free. */ - wolfSSL_X509_NAME_free(nameCopy); - goto cleanup; - } + XSTRNCPY(dp, " Au=", len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; + XSTRNCPY(dp, authStr, len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; - wolfSSL_X509_free(cert); - cert = NULL; - } + XSTRNCPY(dp, " Enc=", len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; + XSTRNCPY(dp, encStr, len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; - CLEAR_ASN_NO_PEM_HEADER_ERROR(err); + XSTRNCPY(dp, " Mac=", len); + dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); + len -= strLen; dp += strLen; + XSTRNCPY(dp, macStr, len); + dp[len-1] = '\0'; - err = WOLFSSL_SUCCESS; -cleanup: - wolfSSL_X509_free(cert); - wolfSSL_BIO_free(bio); - if (err != WOLFSSL_SUCCESS) { - /* We failed so return NULL */ - wolfSSL_sk_X509_NAME_pop_free(list, NULL); - list = NULL; - } - return list; - #else - (void)fname; - return NULL; - #endif - } - #endif - #endif /* !NO_BIO */ -#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA */ + return WOLFSSL_SUCCESS; +} +#endif /* OPENSSL_ALL || WOLFSSL_QT */ -#ifdef OPENSSL_EXTRA +static WC_INLINE const char* wolfssl_kea_to_string(int kea) +{ + const char* keaStr; - #ifdef WOLFSSL_SYS_CA_CERTS - /* - * This is an OpenSSL compatibility layer function, but it doesn't mirror - * the exact functionality of its OpenSSL counterpart. We don't support the - * notion of an "OpenSSL directory". This function will attempt to load the - * environment variables SSL_CERT_DIR and SSL_CERT_FILE, if either are found, - * they will be loaded. Otherwise, it will act as a wrapper around our - * native wolfSSL_CTX_load_system_CA_certs function. This function does - * conform to OpenSSL's return value conventions. - */ - int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) - { - int ret; -#ifdef XGETENV - char* certDir; - char* certFile; - word32 flags; + switch (kea) { + case no_kea: + keaStr = "None"; + break; +#ifndef NO_RSA + case rsa_kea: + keaStr = "RSA"; + break; #endif +#ifndef NO_DH + case diffie_hellman_kea: + keaStr = "DHE"; + break; +#endif + case fortezza_kea: + keaStr = "FZ"; + break; +#ifndef NO_PSK + case psk_kea: + keaStr = "PSK"; + break; + #ifndef NO_DH + case dhe_psk_kea: + keaStr = "DHEPSK"; + break; + #endif + #ifdef HAVE_ECC + case ecdhe_psk_kea: + keaStr = "ECDHEPSK"; + break; + #endif +#endif +#ifdef HAVE_ECC + case ecc_diffie_hellman_kea: + keaStr = "ECDHE"; + break; + case ecc_static_diffie_hellman_kea: + keaStr = "ECDH"; + break; +#endif + default: + keaStr = "unknown"; + break; + } - WOLFSSL_ENTER("wolfSSL_CTX_set_default_verify_paths"); - -#ifdef XGETENV - certDir = XGETENV("SSL_CERT_DIR"); - certFile = XGETENV("SSL_CERT_FILE"); - flags = WOLFSSL_LOAD_FLAG_PEM_CA_ONLY; + return keaStr; +} - if (certDir || certFile) { - if (certDir) { - /* - * We want to keep trying to load more CAs even if one cert in - * the directory is bad and can't be used (e.g. if one is expired), - * so we use WOLFSSL_LOAD_FLAG_IGNORE_ERR. - */ - flags |= WOLFSSL_LOAD_FLAG_IGNORE_ERR; - } +static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo) +{ + const char* authStr; - ret = wolfSSL_CTX_load_verify_locations_ex(ctx, certFile, certDir, - flags); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG_EX("Failed to load CA certs from SSL_CERT_FILE: %s" - " SSL_CERT_DIR: %s. Error: %d", certFile, - certDir, ret); - return WOLFSSL_FAILURE; - } - return ret; - } + switch (sig_algo) { + case anonymous_sa_algo: + authStr = "None"; + break; +#ifndef NO_RSA + case rsa_sa_algo: + authStr = "RSA"; + break; + #ifdef WC_RSA_PSS + case rsa_pss_sa_algo: + authStr = "RSA-PSS"; + break; + #endif #endif - -#ifdef NO_FILESYSTEM - WOLFSSL_MSG("wolfSSL_CTX_set_default_verify_paths not supported" - " with NO_FILESYSTEM enabled"); - ret = WOLFSSL_FATAL_ERROR; -#else - ret = wolfSSL_CTX_load_system_CA_certs(ctx); - if (ret == WOLFSSL_BAD_PATH) { - /* - * OpenSSL doesn't treat the lack of a system CA cert directory as a - * failure. We do the same here. - */ - ret = WOLFSSL_SUCCESS; - } +#ifndef NO_DSA + case dsa_sa_algo: + authStr = "DSA"; + break; #endif - - WOLFSSL_LEAVE("wolfSSL_CTX_set_default_verify_paths", ret); - - return ret; +#ifdef HAVE_ECC + case ecc_dsa_sa_algo: + authStr = "ECDSA"; + break; +#endif +#ifdef WOLFSSL_SM2 + case sm2_sa_algo: + authStr = "SM2"; + break; +#endif +#ifdef HAVE_ED25519 + case ed25519_sa_algo: + authStr = "Ed25519"; + break; +#endif +#ifdef HAVE_ED448 + case ed448_sa_algo: + authStr = "Ed448"; + break; +#endif + default: + authStr = "unknown"; + break; } - #endif /* WOLFSSL_SYS_CA_CERTS */ - - #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \ - && !defined(WC_NO_RNG) - static const byte srp_N[] = { - 0xEE, 0xAF, 0x0A, 0xB9, 0xAD, 0xB3, 0x8D, 0xD6, 0x9C, 0x33, 0xF8, - 0x0A, 0xFA, 0x8F, 0xC5, 0xE8, 0x60, 0x72, 0x61, 0x87, 0x75, 0xFF, - 0x3C, 0x0B, 0x9E, 0xA2, 0x31, 0x4C, 0x9C, 0x25, 0x65, 0x76, 0xD6, - 0x74, 0xDF, 0x74, 0x96, 0xEA, 0x81, 0xD3, 0x38, 0x3B, 0x48, 0x13, - 0xD6, 0x92, 0xC6, 0xE0, 0xE0, 0xD5, 0xD8, 0xE2, 0x50, 0xB9, 0x8B, - 0xE4, 0x8E, 0x49, 0x5C, 0x1D, 0x60, 0x89, 0xDA, 0xD1, 0x5D, 0xC7, - 0xD7, 0xB4, 0x61, 0x54, 0xD6, 0xB6, 0xCE, 0x8E, 0xF4, 0xAD, 0x69, - 0xB1, 0x5D, 0x49, 0x82, 0x55, 0x9B, 0x29, 0x7B, 0xCF, 0x18, 0x85, - 0xC5, 0x29, 0xF5, 0x66, 0x66, 0x0E, 0x57, 0xEC, 0x68, 0xED, 0xBC, - 0x3C, 0x05, 0x72, 0x6C, 0xC0, 0x2F, 0xD4, 0xCB, 0xF4, 0x97, 0x6E, - 0xAA, 0x9A, 0xFD, 0x51, 0x38, 0xFE, 0x83, 0x76, 0x43, 0x5B, 0x9F, - 0xC6, 0x1D, 0x2F, 0xC0, 0xEB, 0x06, 0xE3 - }; - static const byte srp_g[] = { - 0x02 - }; - - int wolfSSL_CTX_set_srp_username(WOLFSSL_CTX* ctx, char* username) - { - int r = 0; - SrpSide srp_side = SRP_CLIENT_SIDE; - byte salt[SRP_SALT_SIZE]; - WOLFSSL_ENTER("wolfSSL_CTX_set_srp_username"); - if (ctx == NULL || ctx->srp == NULL || username==NULL) - return WOLFSSL_FAILURE; + return authStr; +} - if (ctx->method->side == WOLFSSL_SERVER_END){ - srp_side = SRP_SERVER_SIDE; - } else if (ctx->method->side == WOLFSSL_CLIENT_END){ - srp_side = SRP_CLIENT_SIDE; - } else { - WOLFSSL_MSG("Init CTX failed"); - return WOLFSSL_FAILURE; - } +static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size) +{ + const char* encStr; - if (wc_SrpInit(ctx->srp, SRP_TYPE_SHA256, srp_side) < 0) { - WOLFSSL_MSG("Init SRP CTX failed"); - XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP); - ctx->srp = NULL; - return WOLFSSL_FAILURE; - } - r = wc_SrpSetUsername(ctx->srp, (const byte*)username, - (word32)XSTRLEN(username)); - if (r < 0) { - WOLFSSL_MSG("fail to set srp username."); - return WOLFSSL_FAILURE; - } + (void)key_size; - /* if wolfSSL_CTX_set_srp_password has already been called, */ - /* execute wc_SrpSetPassword here */ - if (ctx->srp_password != NULL) { - WC_RNG rng; - if (wc_InitRng(&rng) < 0){ - WOLFSSL_MSG("wc_InitRng failed"); - return WOLFSSL_FAILURE; - } - XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0])); - r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0])); - wc_FreeRng(&rng); - if (r < 0) { - WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); - return WOLFSSL_FAILURE; - } + switch (cipher) { + case wolfssl_cipher_null: + encStr = "None"; + break; +#ifndef NO_RC4 + case wolfssl_rc4: + encStr = "RC4(128)"; + break; +#endif +#ifndef NO_DES3 + case wolfssl_triple_des: + encStr = "3DES(168)"; + break; +#endif +#ifndef NO_AES + case wolfssl_aes: + if (key_size == 128) + encStr = "AES(128)"; + else if (key_size == 256) + encStr = "AES(256)"; + else + encStr = "AES(?)"; + break; + #ifdef HAVE_AESGCM + case wolfssl_aes_gcm: + if (key_size == 128) + encStr = "AESGCM(128)"; + else if (key_size == 256) + encStr = "AESGCM(256)"; + else + encStr = "AESGCM(?)"; + break; + #endif + #ifdef HAVE_AESCCM + case wolfssl_aes_ccm: + if (key_size == 128) + encStr = "AESCCM(128)"; + else if (key_size == 256) + encStr = "AESCCM(256)"; + else + encStr = "AESCCM(?)"; + break; + #endif +#endif +#ifdef HAVE_CHACHA + case wolfssl_chacha: + encStr = "CHACHA20/POLY1305(256)"; + break; +#endif +#ifdef HAVE_ARIA + case wolfssl_aria_gcm: + if (key_size == 128) + encStr = "Aria(128)"; + else if (key_size == 192) + encStr = "Aria(192)"; + else if (key_size == 256) + encStr = "Aria(256)"; + else + encStr = "Aria(?)"; + break; +#endif +#ifdef HAVE_CAMELLIA + case wolfssl_camellia: + if (key_size == 128) + encStr = "Camellia(128)"; + else if (key_size == 256) + encStr = "Camellia(256)"; + else + encStr = "Camellia(?)"; + break; +#endif + default: + encStr = "unknown"; + break; + } - if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]), - srp_g, sizeof(srp_g)/sizeof(srp_g[0]), - salt, sizeof(salt)/sizeof(salt[0])) < 0) { - WOLFSSL_MSG("wc_SrpSetParam failed"); - return WOLFSSL_FAILURE; - } - r = wc_SrpSetPassword(ctx->srp, - (const byte*)ctx->srp_password, - (word32)XSTRLEN((char *)ctx->srp_password)); - if (r < 0) { - WOLFSSL_MSG("fail to set srp password."); - return WOLFSSL_FAILURE; - } + return encStr; +} - XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); - ctx->srp_password = NULL; - } +static WC_INLINE const char* wolfssl_mac_to_string(int mac) +{ + const char* macStr; - return WOLFSSL_SUCCESS; + switch (mac) { + case no_mac: + macStr = "None"; + break; +#ifndef NO_MD5 + case md5_mac: + macStr = "MD5"; + break; +#endif +#ifndef NO_SHA + case sha_mac: + macStr = "SHA1"; + break; +#endif +#ifdef HAVE_SHA224 + case sha224_mac: + macStr = "SHA224"; + break; +#endif +#ifndef NO_SHA256 + case sha256_mac: + macStr = "SHA256"; + break; +#endif +#ifdef HAVE_SHA384 + case sha384_mac: + macStr = "SHA384"; + break; +#endif +#ifdef HAVE_SHA512 + case sha512_mac: + macStr = "SHA512"; + break; +#endif + default: + macStr = "unknown"; + break; } - int wolfSSL_CTX_set_srp_password(WOLFSSL_CTX* ctx, char* password) - { - int r; - byte salt[SRP_SALT_SIZE]; - - WOLFSSL_ENTER("wolfSSL_CTX_set_srp_password"); - if (ctx == NULL || ctx->srp == NULL || password == NULL) - return WOLFSSL_FAILURE; + return macStr; +} - if (ctx->srp->user != NULL) { - WC_RNG rng; - if (wc_InitRng(&rng) < 0) { - WOLFSSL_MSG("wc_InitRng failed"); - return WOLFSSL_FAILURE; - } - XMEMSET(salt, 0, sizeof(salt)/sizeof(salt[0])); - r = wc_RNG_GenerateBlock(&rng, salt, sizeof(salt)/sizeof(salt[0])); - wc_FreeRng(&rng); - if (r < 0) { - WOLFSSL_MSG("wc_RNG_GenerateBlock failed"); - return WOLFSSL_FAILURE; - } - if (wc_SrpSetParams(ctx->srp, srp_N, sizeof(srp_N)/sizeof(srp_N[0]), - srp_g, sizeof(srp_g)/sizeof(srp_g[0]), - salt, sizeof(salt)/sizeof(salt[0])) < 0){ - WOLFSSL_MSG("wc_SrpSetParam failed"); - wc_FreeRng(&rng); - return WOLFSSL_FAILURE; - } - r = wc_SrpSetPassword(ctx->srp, (const byte*)password, - (word32)XSTRLEN(password)); - if (r < 0) { - WOLFSSL_MSG("wc_SrpSetPassword failed."); - wc_FreeRng(&rng); - return WOLFSSL_FAILURE; - } - if (ctx->srp_password != NULL){ - XFREE(ctx->srp_password,NULL, - DYNAMIC_TYPE_SRP); - ctx->srp_password = NULL; - } - wc_FreeRng(&rng); - } else { - /* save password for wolfSSL_set_srp_username */ - if (ctx->srp_password != NULL) - XFREE(ctx->srp_password,ctx->heap, DYNAMIC_TYPE_SRP); +char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, + int len) +{ + char *ret = in; + const char *keaStr, *authStr, *encStr, *macStr; + size_t strLen; + WOLFSSL_ENTER("wolfSSL_CIPHER_description"); - ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap, - DYNAMIC_TYPE_SRP); - if (ctx->srp_password == NULL){ - WOLFSSL_MSG("memory allocation error"); - return WOLFSSL_FAILURE; - } - XMEMCPY(ctx->srp_password, password, XSTRLEN(password) + 1); - } - return WOLFSSL_SUCCESS; - } + if (cipher == NULL || in == NULL) + return NULL; - /** - * The modulus passed to wc_SrpSetParams in ssl.c is constant so check - * that the requested strength is less than or equal to the size of the - * static modulus size. - * @param ctx Not used - * @param strength Minimum number of bits for the modulus - * @return 1 if strength is less than or equal to static modulus - * 0 if strength is greater than static modulus +#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) + /* if cipher is in the stack from wolfSSL_get_ciphers_compat then + * Return the description based on cipher_names[cipher->offset] */ - int wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength) - { - (void)ctx; - WOLFSSL_ENTER("wolfSSL_CTX_set_srp_strength"); - if (strength > (int)(sizeof(srp_N)*8)) { - WOLFSSL_MSG("Bad Parameter"); - return WOLFSSL_FAILURE; - } - return WOLFSSL_SUCCESS; + if (cipher->in_stack == TRUE) { + wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher); + XSTRNCPY(in,cipher->description,len); + return ret; } +#endif - char* wolfSSL_get_srp_username(WOLFSSL *ssl) - { - if (ssl && ssl->ctx && ssl->ctx->srp) { - return (char*) ssl->ctx->srp->user; - } - return NULL; - } - #endif /* WOLFCRYPT_HAVE_SRP && !NO_SHA256 && !WC_NO_RNG */ + /* Get the cipher description based on the SSL session cipher */ + keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea); + authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo); + encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm, + cipher->ssl->specs.key_size); + macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm); - /* keyblock size in bytes or -1 */ - int wolfSSL_get_keyblock_size(WOLFSSL* ssl) - { - if (ssl == NULL) - return WOLFSSL_FATAL_ERROR; - - return 2 * (ssl->specs.key_size + ssl->specs.iv_size + - ssl->specs.hash_size); - } + /* Build up the string by copying onto the end. */ + XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; -#endif /* OPENSSL_EXTRA */ + XSTRNCPY(in, " ", len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; + XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) + XSTRNCPY(in, " Kx=", len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; + XSTRNCPY(in, keaStr, len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - /* store keys returns WOLFSSL_SUCCESS or -1 on error */ - int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen, - unsigned char** sr, unsigned int* srLen, - unsigned char** cr, unsigned int* crLen) - { - if (ssl == NULL || ssl->arrays == NULL) - return WOLFSSL_FATAL_ERROR; + XSTRNCPY(in, " Au=", len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; + XSTRNCPY(in, authStr, len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - *ms = ssl->arrays->masterSecret; - *sr = ssl->arrays->serverRandom; - *cr = ssl->arrays->clientRandom; + XSTRNCPY(in, " Enc=", len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; + XSTRNCPY(in, encStr, len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - *msLen = SECRET_LEN; - *srLen = RAN_LEN; - *crLen = RAN_LEN; + XSTRNCPY(in, " Mac=", len); + in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; + XSTRNCPY(in, macStr, len); + in[len-1] = '\0'; - return WOLFSSL_SUCCESS; - } + return ret; +} - void wolfSSL_set_accept_state(WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_set_accept_state"); - if (ssl == NULL) - return; +#ifndef NO_WOLFSSL_STUB +int wolfSSL_OCSP_parse_url(char* url, char** host, char** port, char** path, + int* ssl) +{ + (void)url; + (void)host; + (void)port; + (void)path; + (void)ssl; + WOLFSSL_STUB("OCSP_parse_url"); + return 0; +} +#endif - if (ssl->options.side == WOLFSSL_CLIENT_END) { - #ifdef HAVE_ECC - #ifdef WOLFSSL_SMALL_STACK - ecc_key* key = NULL; - #else - ecc_key key[1]; - #endif - word32 idx = 0; +#ifndef NO_WOLFSSL_STUB +WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void) +{ + WOLFSSL_STUB("COMP_zlib"); + return 0; +} +#endif - #ifdef WOLFSSL_SMALL_STACK - key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap, - DYNAMIC_TYPE_ECC); - if (key == NULL) { - WOLFSSL_MSG("Error allocating memory for ecc_key"); - } - #endif - if (ssl->options.haveStaticECC && ssl->buffers.key != NULL) { - if (wc_ecc_init(key) >= 0) { - if (wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx, - key, ssl->buffers.key->length) != 0) { - ssl->options.haveECDSAsig = 0; - ssl->options.haveECC = 0; - ssl->options.haveStaticECC = 0; - } - wc_ecc_free(key); - } - } - #ifdef WOLFSSL_SMALL_STACK - XFREE(key, ssl->heap, DYNAMIC_TYPE_ECC); - #endif - #endif +#ifndef NO_WOLFSSL_STUB +WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void) +{ + WOLFSSL_STUB("COMP_rle"); + return 0; +} +#endif - #ifndef NO_DH - if (!ssl->options.haveDH && ssl->ctx->haveDH) { - ssl->buffers.serverDH_P = ssl->ctx->serverDH_P; - ssl->buffers.serverDH_G = ssl->ctx->serverDH_G; - ssl->options.haveDH = 1; - } - #endif - } +#ifndef NO_WOLFSSL_STUB +int wolfSSL_COMP_add_compression_method(int method, void* data) +{ + (void)method; + (void)data; + WOLFSSL_STUB("COMP_add_compression_method"); + return 0; +} +#endif - if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error initializing server side"); - } - } +#ifndef NO_WOLFSSL_STUB +const char* wolfSSL_COMP_get_name(const void* comp) +{ + static const char ret[] = "not supported"; -#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ + (void)comp; + WOLFSSL_STUB("wolfSSL_COMP_get_name"); + return ret; +} +#endif - /* return true if connection established */ - int wolfSSL_is_init_finished(const WOLFSSL* ssl) - { - if (ssl == NULL) - return 0; +/* wolfSSL_set_dynlock_create_callback + * CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1. + * This function exists for compatibility purposes because wolfSSL satisfies + * thread safety without relying on the callback. + */ +void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)( + const char*, int)) +{ + WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback"); + (void)f; +} +/* wolfSSL_set_dynlock_lock_callback + * CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1. + * This function exists for compatibility purposes because wolfSSL satisfies + * thread safety without relying on the callback. + */ +void wolfSSL_set_dynlock_lock_callback( + void (*f)(int, WOLFSSL_dynlock_value*, const char*, int)) +{ + WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback"); + (void)f; +} +/* wolfSSL_set_dynlock_destroy_callback + * CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1. + * This function exists for compatibility purposes because wolfSSL satisfies + * thread safety without relying on the callback. + */ +void wolfSSL_set_dynlock_destroy_callback( + void (*f)(WOLFSSL_dynlock_value*, const char*, int)) +{ + WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback"); + (void)f; +} - /* Can't use ssl->options.connectState and ssl->options.acceptState because - * they differ in meaning for TLS <=1.2 and 1.3 */ - if (ssl->options.handShakeState == HANDSHAKE_DONE) - return 1; - return 0; - } +#endif /* OPENSSL_EXTRA */ #ifdef OPENSSL_EXTRA - void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx, - WOLFSSL_RSA*(*f)(WOLFSSL*, int, int)) - { - /* wolfSSL verifies all these internally */ - (void)ctx; - (void)f; - } +#ifndef NO_CERTS +#if !defined(NO_ASN) && !defined(NO_PWDBASED) +/* Copies unencrypted DER key buffer into "der". If "der" is null then the size + * of buffer needed is returned. If *der == NULL then it allocates a buffer. + * NOTE: This also advances the "der" pointer to be at the end of buffer. + * + * Returns size of key buffer on success + */ +int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der) +{ + return wolfSSL_EVP_PKEY_get_der(key, der); +} - void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt) - { - WOLFSSL_ENTER("wolfSSL_set_shutdown"); - if(ssl==NULL) { - WOLFSSL_MSG("Shutdown not set. ssl is null"); - return; - } +int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) +{ +#if !defined(NO_RSA) || defined(HAVE_ECC) +#ifdef HAVE_ECC + unsigned char *local_der = NULL; + word32 local_derSz = 0; + unsigned char *pub_der = NULL; + ecc_key *eccKey = NULL; + word32 inOutIdx = 0; +#endif + word32 pub_derSz = 0; + int ret; + int key_type = 0; - ssl->options.sentNotify = (opt&WOLFSSL_SENT_SHUTDOWN) > 0; - ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0; + if (key == NULL) { + return WOLFSSL_FATAL_ERROR; } -#endif - long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_CTX_get_options"); - WOLFSSL_MSG("wolfSSL options are set through API calls and macros"); - if(ctx == NULL) - return BAD_FUNC_ARG; - return ctx->mask; + key_type = key->type; + if ((key_type != EVP_PKEY_EC) && (key_type != EVP_PKEY_RSA)) { + return WOLFSSL_FATAL_ERROR; } - /* forward declaration */ - static long wolf_set_options(long old_op, long op); +#ifndef NO_RSA + if (key_type == EVP_PKEY_RSA) { + return wolfSSL_i2d_RSAPublicKey(key->rsa, der); + } +#endif - long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_options"); + /* Now that RSA is taken care of, we only need to consider the ECC case. */ - if (ctx == NULL) - return BAD_FUNC_ARG; +#ifdef HAVE_ECC - ctx->mask = wolf_set_options(ctx->mask, opt); -#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \ - || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)) - if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { - ctx->noTicketTls12 = 1; - } - /* This code is here for documentation purpose. You must not turn off - * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3. - * Because we need to support both stateful and stateless tickets. - #ifdef WOLFSSL_TLS13 - if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { - ctx->noTicketTls13 = 1; - } - #endif - */ -#endif - return ctx->mask; - } - - long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt) - { - WOLFSSL_ENTER("wolfSSL_CTX_clear_options"); - if(ctx == NULL) - return BAD_FUNC_ARG; - ctx->mask &= ~opt; - return ctx->mask; + /* We need to get the DER, then convert it to a public key. But what we get + * might be a buffered private key so we need to decode it and then encode + * the public part. */ + ret = wolfSSL_EVP_PKEY_get_der(key, &local_der); + if (ret <= 0) { + /* In this case, there was no buffered DER at all. This could be the + * case where the key that was passed in was generated. So now we + * have to create the local DER. */ + local_derSz = (word32)wolfSSL_i2d_ECPrivateKey(key->ecc, &local_der); + if (local_derSz == 0) { + ret = WOLFSSL_FATAL_ERROR; + } + } else { + local_derSz = (word32)ret; + ret = 0; } -#ifdef OPENSSL_EXTRA - - int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd) - { - WOLFSSL_ENTER("wolfSSL_set_rfd"); - ssl->rfd = rfd; /* not used directly to allow IO callbacks */ - - ssl->IOCB_ReadCtx = &ssl->rfd; - - #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) { - ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx; - ssl->buffers.dtlsCtx.rfd = rfd; + if (ret == 0) { + eccKey = (ecc_key *)XMALLOC(sizeof(*eccKey), NULL, DYNAMIC_TYPE_ECC); + if (eccKey == NULL) { + WOLFSSL_MSG("Failed to allocate key buffer."); + ret = WOLFSSL_FATAL_ERROR; } - #endif - - return WOLFSSL_SUCCESS; } - - int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd) - { - WOLFSSL_ENTER("wolfSSL_set_wfd"); - ssl->wfd = wfd; /* not used directly to allow IO callbacks */ - - ssl->IOCB_WriteCtx = &ssl->wfd; - - return WOLFSSL_SUCCESS; + if (ret == 0) { + ret = wc_ecc_init(eccKey); } -#endif /* OPENSSL_EXTRA */ - -#if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) - -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - /** - * Implemented in a similar way that ngx_ssl_ocsp_validate does it when - * SSL_get0_verified_chain is not available. - * @param ssl WOLFSSL object to extract certs from - * @return Stack of verified certs - */ - WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl) - { - WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL; - WOLFSSL_X509_STORE_CTX* storeCtx = NULL; - WOLFSSL_X509* peerCert = NULL; - - WOLFSSL_ENTER("wolfSSL_get0_verified_chain"); - - if (ssl == NULL || ssl->ctx == NULL) { - WOLFSSL_MSG("Bad parameter"); - return NULL; - } - peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl); - if (peerCert == NULL) { - WOLFSSL_MSG("wolfSSL_get_peer_certificate error"); - return NULL; - } - /* wolfSSL_get_peer_certificate returns a copy. We want the internal - * member so that we don't have to worry about free'ing it. We call - * wolfSSL_get_peer_certificate so that we don't have to worry about - * setting up the internal pointer. */ - wolfSSL_X509_free(peerCert); - peerCert = (WOLFSSL_X509*)&ssl->peerCert; - chain = wolfSSL_get_peer_cert_chain(ssl); - if (chain == NULL) { - WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error"); - return NULL; - } - storeCtx = wolfSSL_X509_STORE_CTX_new(); - if (storeCtx == NULL) { - WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error"); - return NULL; - } - if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl), - peerCert, chain) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error"); - wolfSSL_X509_STORE_CTX_free(storeCtx); - return NULL; - } - if (wolfSSL_X509_verify_cert(storeCtx) <= 0) { - WOLFSSL_MSG("wolfSSL_X509_verify_cert error"); - wolfSSL_X509_STORE_CTX_free(storeCtx); - return NULL; + if (ret == 0) { + ret = wc_EccPublicKeyDecode(local_der, &inOutIdx, eccKey, local_derSz); + if (ret < 0) { + /* We now try again as x.963 [point type][x][opt y]. */ + ret = wc_ecc_import_x963(local_der, local_derSz, eccKey); } - wolfSSL_X509_STORE_CTX_free(storeCtx); - return chain; } -#endif /* SESSION_CERTS && OPENSSL_EXTRA */ - WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(WOLFSSL_CTX* ctx) - { - if (ctx == NULL) { - return NULL; + if (ret == 0) { + pub_derSz = (word32)wc_EccPublicKeyDerSize(eccKey, 0); + if ((int)pub_derSz <= 0) { + ret = WOLFSSL_FAILURE; } - - if (ctx->x509_store_pt != NULL) - return ctx->x509_store_pt; - return &ctx->x509_store; } - void wolfSSL_CTX_set_cert_store(WOLFSSL_CTX* ctx, WOLFSSL_X509_STORE* str) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_cert_store"); - if (ctx == NULL || str == NULL || ctx->cm == str->cm) { - return; + if (ret == 0) { + pub_der = (unsigned char*)XMALLOC(pub_derSz, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); + if (pub_der == NULL) { + WOLFSSL_MSG("Failed to allocate output buffer."); + ret = WOLFSSL_FATAL_ERROR; } + } - if (wolfSSL_CertManager_up_ref(str->cm) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_CertManager_up_ref error"); - return; - } - /* free cert manager if have one */ - if (ctx->cm != NULL) { - wolfSSL_CertManagerFree(ctx->cm); + if (ret == 0) { + pub_derSz = (word32)wc_EccPublicKeyToDer(eccKey, pub_der, pub_derSz, 0); + if ((int)pub_derSz <= 0) { + ret = WOLFSSL_FATAL_ERROR; } - ctx->cm = str->cm; - ctx->x509_store.cm = str->cm; - - /* free existing store if it exists */ - wolfSSL_X509_STORE_free(ctx->x509_store_pt); - ctx->x509_store.cache = str->cache; - ctx->x509_store_pt = str; /* take ownership of store and free it - with CTX free */ - ctx->cm->x509_store_p = ctx->x509_store_pt;/* CTX has ownership - and free it with CTX free*/ } -#ifdef OPENSSL_ALL - int wolfSSL_CTX_set1_verify_cert_store(WOLFSSL_CTX* ctx, WOLFSSL_X509_STORE* str) - { - WOLFSSL_ENTER("wolfSSL_CTX_set1_verify_cert_store"); + /* This block is for actually returning the DER of the public key */ + if ((ret == 0) && (der != NULL)) { + if (*der == NULL) { + *der = (unsigned char*)XMALLOC(pub_derSz, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); + if (*der == NULL) { + WOLFSSL_MSG("Failed to allocate output buffer."); + ret = WOLFSSL_FATAL_ERROR; + } - if (ctx == NULL || str == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; + if (ret == 0) { + XMEMCPY(*der, pub_der, pub_derSz); + } } - - /* NO-OP when setting existing store */ - if (str == CTX_STORE(ctx)) - return WOLFSSL_SUCCESS; - - if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error"); - return WOLFSSL_FAILURE; + else { + XMEMCPY(*der, pub_der, pub_derSz); + *der += pub_derSz; } - - /* free existing store if it exists */ - wolfSSL_X509_STORE_free(ctx->x509_store_pt); - ctx->x509_store_pt = str; /* take ownership of store and free it - with CTX free */ - return WOLFSSL_SUCCESS; } -#endif - int wolfSSL_set0_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str) - { - WOLFSSL_ENTER("wolfSSL_set0_verify_cert_store"); + XFREE(pub_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(local_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - if (ssl == NULL || str == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } + wc_ecc_free(eccKey); + XFREE(eccKey, NULL, DYNAMIC_TYPE_ECC); - /* NO-OP when setting existing store */ - if (str == SSL_STORE(ssl)) - return WOLFSSL_SUCCESS; +#else + ret = WOLFSSL_FATAL_ERROR; +#endif /* HAVE_ECC */ - /* free existing store if it exists */ - wolfSSL_X509_STORE_free(ssl->x509_store_pt); - if (str == ssl->ctx->x509_store_pt) - ssl->x509_store_pt = NULL; /* if setting ctx store then just revert - to using that instead */ - else - ssl->x509_store_pt = str; /* take ownership of store and free it - with SSL free */ - return WOLFSSL_SUCCESS; + if (ret == 0) { + return (int)pub_derSz; } + return ret; +#else + return WOLFSSL_FATAL_ERROR; +#endif /* !NO_RSA || HAVE_ECC */ +} +#endif /* !NO_ASN && !NO_PWDBASED */ - int wolfSSL_set1_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str) - { - WOLFSSL_ENTER("wolfSSL_set1_verify_cert_store"); +#endif /* !NO_CERTS */ +#endif /* OPENSSL_EXTRA */ - if (ssl == NULL || str == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } +#ifdef OPENSSL_EXTRA - /* NO-OP when setting existing store */ - if (str == SSL_STORE(ssl)) - return WOLFSSL_SUCCESS; +/* Sets the DNS hostname to name. + * Hostname is cleared if name is NULL or empty. */ +int wolfSSL_set1_host(WOLFSSL * ssl, const char* name) +{ + if (ssl == NULL) { + return WOLFSSL_FAILURE; + } - if (wolfSSL_X509_STORE_up_ref(str) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_STORE_up_ref error"); - return WOLFSSL_FAILURE; - } + return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0); +} - /* free existing store if it exists */ - wolfSSL_X509_STORE_free(ssl->x509_store_pt); - if (str == ssl->ctx->x509_store_pt) - ssl->x509_store_pt = NULL; /* if setting ctx store then just revert - to using that instead */ - else - ssl->x509_store_pt = str; /* take ownership of store and free it - with SSL free */ +/****************************************************************************** +* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters +* +* RETURNS: +* WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE +* Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL, +* same as openssl. +*/ +int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm) +{ + if (ctx == NULL || vpm == NULL) return WOLFSSL_SUCCESS; - } -#endif /* !NO_CERTS && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */ -#ifdef WOLFSSL_ENCRYPTED_KEYS + return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm); +} - void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx, - void* userdata) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata"); - if (ctx) - ctx->passwd_userdata = userdata; +/****************************************************************************** +* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters +* +* RETURNS: +* returns pointer to the SSL verification parameters on success, +* otherwise returns NULL +*/ +WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx) +{ + if (ctx == NULL) { + return NULL; } + return ctx->param; +} - void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb* - cb) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb"); - if (ctx) - ctx->passwd_cb = cb; +WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl) +{ + if (ssl == NULL) { + return NULL; } + return ssl->param; +} - wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx) - { - if (ctx == NULL || ctx->passwd_cb == NULL) { - return NULL; - } +#endif /* OPENSSL_EXTRA */ - return ctx->passwd_cb; - } +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) +/* Gets an index to store SSL structure at. + * + * Returns positive index on success and negative values on failure + */ +int wolfSSL_get_ex_data_X509_STORE_CTX_idx(void) +{ + WOLFSSL_ENTER("wolfSSL_get_ex_data_X509_STORE_CTX_idx"); + /* store SSL at index 0 */ + return 0; +} +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx) - { - if (ctx == NULL) { - return NULL; - } +#ifdef OPENSSL_EXTRA +/* Sets a function callback that will send information about the state of all + * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed + * in. + * + * ctx WOLFSSL_CTX structure to set callback function in + * f callback function to use + */ +void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx, + void (*f)(const WOLFSSL* ssl, int type, int val)) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback"); + if (ctx == NULL) { + WOLFSSL_MSG("Bad function argument"); + } + else { + ctx->CBIS = f; + } +} - return ctx->passwd_userdata; +void wolfSSL_set_info_callback(WOLFSSL* ssl, + void (*f)(const WOLFSSL* ssl, int type, int val)) +{ + WOLFSSL_ENTER("wolfSSL_set_info_callback"); + if (ssl == NULL) { + WOLFSSL_MSG("Bad function argument"); } + else { + ssl->CBIS = f; + } +} -#endif /* WOLFSSL_ENCRYPTED_KEYS */ +unsigned long wolfSSL_ERR_peek_error(void) +{ + WOLFSSL_ENTER("wolfSSL_ERR_peek_error"); -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) - unsigned long wolfSSL_ERR_get_error(void) - { - WOLFSSL_ENTER("wolfSSL_ERR_get_error"); -#ifdef WOLFSSL_HAVE_ERROR_QUEUE - return wc_GetErrorNodeErr(); -#else - return (unsigned long)(0 - NOT_COMPILED_IN); -#endif - } -#endif + return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL); +} -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) +int wolfSSL_ERR_GET_LIB(unsigned long err) +{ + unsigned long value; - int wolfSSL_num_locks(void) - { + value = (err & 0xFFFFFFL); + switch (value) { + case -WC_NO_ERR_TRACE(PARSE_ERROR): + return ERR_LIB_SSL; + case -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER): + case PEM_R_NO_START_LINE: + case PEM_R_PROBLEMS_GETTING_PASSWORD: + case PEM_R_BAD_PASSWORD_READ: + case PEM_R_BAD_DECRYPT: + return ERR_LIB_PEM; + case EVP_R_BAD_DECRYPT: + case EVP_R_BN_DECODE_ERROR: + case EVP_R_DECODE_ERROR: + case EVP_R_PRIVATE_KEY_DECODE_ERROR: + return ERR_LIB_EVP; + case ASN1_R_HEADER_TOO_LONG: + return ERR_LIB_ASN1; + default: return 0; } +} - void wolfSSL_set_locking_callback(mutex_cb* f) - { - WOLFSSL_ENTER("wolfSSL_set_locking_callback"); +/* This function is to find global error values that are the same through out + * all library version. With wolfSSL having only one set of error codes the + * return value is pretty straight forward. The only thing needed is all wolfSSL + * error values are typically negative. + * + * Returns the error reason + */ +int wolfSSL_ERR_GET_REASON(unsigned long err) +{ + int ret = (int)err; - if (wc_SetMutexCb(f) != 0) { - WOLFSSL_MSG("Error when setting mutex call back"); - } - } + WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON"); - mutex_cb* wolfSSL_get_locking_callback(void) - { - WOLFSSL_ENTER("wolfSSL_get_locking_callback"); +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + /* Nginx looks for this error to know to stop parsing certificates. + * Same for HAProxy. */ + if (err == ((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE) || + ((err & 0xFFFFFFL) == -ASN_NO_PEM_HEADER) || + ((err & 0xFFFL) == PEM_R_NO_START_LINE )) + return PEM_R_NO_START_LINE; + if (err == ((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST)) + return SSL_R_HTTP_REQUEST; +#endif +#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) + if (err == ((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG)) + return ASN1_R_HEADER_TOO_LONG; +#endif - return wc_GetMutexCb(); + /* check if error value is in range of wolfSSL errors */ + ret = 0 - ret; /* setting as negative value */ + /* wolfCrypt range is less than MAX (-100) + wolfSSL range is MIN (-300) and lower */ + if (ret < MAX_CODE_E && ret > MIN_CODE_E) { + return ret; } - - - typedef unsigned long (idCb)(void); - static idCb* inner_idCb = NULL; - - unsigned long wolfSSL_thread_id(void) - { - if (inner_idCb != NULL) { - return inner_idCb(); - } - else { - return 0; - } + else { + WOLFSSL_MSG("Not in range of typical error values"); + ret = (int)err; } + return ret; +} - void wolfSSL_set_id_callback(unsigned long (*f)(void)) - { - inner_idCb = f; - } +/* returns a string that describes the alert + * + * alertID the alert value to look up + */ +const char* wolfSSL_alert_type_string_long(int alertID) +{ + WOLFSSL_ENTER("wolfSSL_alert_type_string_long"); -#ifdef WOLFSSL_HAVE_ERROR_QUEUE -#ifndef NO_BIO - /* print out and clear all errors */ - void wolfSSL_ERR_print_errors(WOLFSSL_BIO* bio) - { - const char* file = NULL; - const char* reason = NULL; - int ret; - int line = 0; - char buf[WOLFSSL_MAX_ERROR_SZ * 2]; + return AlertTypeToString(alertID); +} - WOLFSSL_ENTER("wolfSSL_ERR_print_errors"); - if (bio == NULL) { - WOLFSSL_MSG("BIO passed in was null"); - return; - } +const char* wolfSSL_alert_desc_string_long(int alertID) +{ + WOLFSSL_ENTER("wolfSSL_alert_desc_string_long"); - do { - ret = wc_PeekErrorNode(0, &file, &reason, &line); - if (ret >= 0) { - const char* r = wolfSSL_ERR_reason_error_string(0 - ret); - if (XSNPRINTF(buf, sizeof(buf), - "error:%d:wolfSSL library:%s:%s:%d\n", - ret, r, file, line) - >= (int)sizeof(buf)) - { - WOLFSSL_MSG("Buffer overrun formatting error message"); - } - wolfSSL_BIO_write(bio, buf, (int)XSTRLEN(buf)); - wc_RemoveErrorNode(0); - } - } while (ret >= 0); - if (wolfSSL_BIO_write(bio, "", 1) != 1) { - WOLFSSL_MSG("Issue writing final string terminator"); - } + return AlertTypeToString(alertID); +} + +#define STATE_STRINGS_PROTO(s) \ + { \ + {"SSLv3 " s, \ + "SSLv3 " s, \ + "SSLv3 " s}, \ + {"TLSv1 " s, \ + "TLSv1 " s, \ + "TLSv1 " s}, \ + {"TLSv1_1 " s, \ + "TLSv1_1 " s, \ + "TLSv1_1 " s}, \ + {"TLSv1_2 " s, \ + "TLSv1_2 " s, \ + "TLSv1_2 " s}, \ + {"TLSv1_3 " s, \ + "TLSv1_3 " s, \ + "TLSv1_3 " s}, \ + {"DTLSv1 " s, \ + "DTLSv1 " s, \ + "DTLSv1 " s}, \ + {"DTLSv1_2 " s, \ + "DTLSv1_2 " s, \ + "DTLSv1_2 " s}, \ + {"DTLSv1_3 " s, \ + "DTLSv1_3 " s, \ + "DTLSv1_3 " s}, \ } -#endif /* !NO_BIO */ -#endif /* WOLFSSL_HAVE_ERROR_QUEUE */ -#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */ +#define STATE_STRINGS_PROTO_RW(s) \ + { \ + {"SSLv3 read " s, \ + "SSLv3 write " s, \ + "SSLv3 " s}, \ + {"TLSv1 read " s, \ + "TLSv1 write " s, \ + "TLSv1 " s}, \ + {"TLSv1_1 read " s, \ + "TLSv1_1 write " s, \ + "TLSv1_1 " s}, \ + {"TLSv1_2 read " s, \ + "TLSv1_2 write " s, \ + "TLSv1_2 " s}, \ + {"TLSv1_3 read " s, \ + "TLSv1_3 write " s, \ + "TLSv1_3 " s}, \ + {"DTLSv1 read " s, \ + "DTLSv1 write " s, \ + "DTLSv1 " s}, \ + {"DTLSv1_2 read " s, \ + "DTLSv1_2 write " s, \ + "DTLSv1_2 " s}, \ + {"DTLSv1_3 read " s, \ + "DTLSv1_3 write " s, \ + "DTLSv1_3 " s}, \ + } -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ - defined(HAVE_SECRET_CALLBACK) -#if !defined(NO_WOLFSSL_SERVER) -/* Return the amount of random bytes copied over or error case. - * ssl : ssl struct after handshake - * out : buffer to hold random bytes - * outSz : either 0 (return max buffer sz) or size of out buffer +/* Gets the current state of the WOLFSSL structure + * + * ssl WOLFSSL structure to get state of + * + * Returns a human readable string of the WOLFSSL structure state */ -size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out, - size_t outSz) +const char* wolfSSL_state_string_long(const WOLFSSL* ssl) { - size_t size; - /* return max size of buffer */ - if (outSz == 0) { - return RAN_LEN; - } + static const char* OUTPUT_STR[24][8][3] = { + STATE_STRINGS_PROTO("Initialization"), + STATE_STRINGS_PROTO_RW("Server Hello Request"), + STATE_STRINGS_PROTO_RW("Server Hello Verify Request"), + STATE_STRINGS_PROTO_RW("Server Hello Retry Request"), + STATE_STRINGS_PROTO_RW("Server Hello"), + STATE_STRINGS_PROTO_RW("Server Certificate Status"), + STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"), + STATE_STRINGS_PROTO_RW("Server Session Ticket"), + STATE_STRINGS_PROTO_RW("Server Certificate Request"), + STATE_STRINGS_PROTO_RW("Server Cert"), + STATE_STRINGS_PROTO_RW("Server Key Exchange"), + STATE_STRINGS_PROTO_RW("Server Hello Done"), + STATE_STRINGS_PROTO_RW("Server Change CipherSpec"), + STATE_STRINGS_PROTO_RW("Server Finished"), + STATE_STRINGS_PROTO_RW("server Key Update"), + STATE_STRINGS_PROTO_RW("Client Hello"), + STATE_STRINGS_PROTO_RW("Client Key Exchange"), + STATE_STRINGS_PROTO_RW("Client Cert"), + STATE_STRINGS_PROTO_RW("Client Change CipherSpec"), + STATE_STRINGS_PROTO_RW("Client Certificate Verify"), + STATE_STRINGS_PROTO_RW("Client End Of Early Data"), + STATE_STRINGS_PROTO_RW("Client Finished"), + STATE_STRINGS_PROTO_RW("Client Key Update"), + STATE_STRINGS_PROTO("Handshake Done"), + }; + enum ProtocolVer { + SSL_V3 = 0, + TLS_V1, + TLS_V1_1, + TLS_V1_2, + TLS_V1_3, + DTLS_V1, + DTLS_V1_2, + DTLS_V1_3, + UNKNOWN = 100 + }; - if (ssl == NULL || out == NULL) { - return 0; - } + enum IOMode { + SS_READ = 0, + SS_WRITE, + SS_NEITHER + }; - if (ssl->arrays == NULL) { - WOLFSSL_MSG("Arrays struct not saved after handshake"); - return 0; + enum SslState { + ss_null_state = 0, + ss_server_hellorequest, + ss_server_helloverify, + ss_server_helloretryrequest, + ss_server_hello, + ss_server_certificatestatus, + ss_server_encryptedextensions, + ss_server_sessionticket, + ss_server_certrequest, + ss_server_cert, + ss_server_keyexchange, + ss_server_hellodone, + ss_server_changecipherspec, + ss_server_finished, + ss_server_keyupdate, + ss_client_hello, + ss_client_keyexchange, + ss_client_cert, + ss_client_changecipherspec, + ss_client_certverify, + ss_client_endofearlydata, + ss_client_finished, + ss_client_keyupdate, + ss_handshake_done + }; + + int protocol = 0; + int cbmode = 0; + int state = 0; + + WOLFSSL_ENTER("wolfSSL_state_string_long"); + if (ssl == NULL) { + WOLFSSL_MSG("Null argument passed in"); + return NULL; } - if (outSz > RAN_LEN) { - size = RAN_LEN; + /* Get state of callback */ + if (ssl->cbmode == SSL_CB_MODE_WRITE) { + cbmode = SS_WRITE; + } + else if (ssl->cbmode == SSL_CB_MODE_READ) { + cbmode = SS_READ; } else { - size = outSz; + cbmode = SS_NEITHER; } - XMEMCPY(out, ssl->arrays->serverRandom, size); - return size; -} -#endif /* !NO_WOLFSSL_SERVER */ -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */ - -#ifdef OPENSSL_EXTRA -#if !defined(NO_WOLFSSL_SERVER) -/* Used to get the peer ephemeral public key sent during the connection - * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called - * before the ephemeral key is stored. - * return WOLFSSL_SUCCESS on success */ -int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey) -{ - WOLFSSL_EVP_PKEY* ret = NULL; - - WOLFSSL_ENTER("wolfSSL_get_server_tmp_key"); - - if (ssl == NULL || pkey == NULL) { - WOLFSSL_MSG("Bad argument passed in"); - return WOLFSSL_FAILURE; + /* Get protocol version */ + switch (ssl->version.major) { + case SSLv3_MAJOR: + switch (ssl->version.minor) { + case SSLv3_MINOR: + protocol = SSL_V3; + break; + case TLSv1_MINOR: + protocol = TLS_V1; + break; + case TLSv1_1_MINOR: + protocol = TLS_V1_1; + break; + case TLSv1_2_MINOR: + protocol = TLS_V1_2; + break; + case TLSv1_3_MINOR: + protocol = TLS_V1_3; + break; + default: + protocol = UNKNOWN; + } + break; + case DTLS_MAJOR: + switch (ssl->version.minor) { + case DTLS_MINOR: + protocol = DTLS_V1; + break; + case DTLSv1_2_MINOR: + protocol = DTLS_V1_2; + break; + case DTLSv1_3_MINOR: + protocol = DTLS_V1_3; + break; + default: + protocol = UNKNOWN; + } + break; + default: + protocol = UNKNOWN; } -#ifdef HAVE_ECC - if (ssl->peerEccKey != NULL) { - unsigned char* der; - const unsigned char* pt; - unsigned int derSz = 0; - int sz; - - PRIVATE_KEY_UNLOCK(); - if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz) != - LENGTH_ONLY_E) { - WOLFSSL_MSG("get ecc der size failed"); - PRIVATE_KEY_LOCK(); - return WOLFSSL_FAILURE; - } - PRIVATE_KEY_LOCK(); - - derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO; - der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY); - if (der == NULL) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; + /* accept process */ + if (ssl->cbmode == SSL_CB_MODE_READ) { + state = ssl->cbtype; + switch (state) { + case hello_request: + state = ss_server_hellorequest; + break; + case client_hello: + state = ss_client_hello; + break; + case server_hello: + state = ss_server_hello; + break; + case hello_verify_request: + state = ss_server_helloverify; + break; + case session_ticket: + state = ss_server_sessionticket; + break; + case end_of_early_data: + state = ss_client_endofearlydata; + break; + case hello_retry_request: + state = ss_server_helloretryrequest; + break; + case encrypted_extensions: + state = ss_server_encryptedextensions; + break; + case certificate: + if (ssl->options.side == WOLFSSL_SERVER_END) + state = ss_client_cert; + else if (ssl->options.side == WOLFSSL_CLIENT_END) + state = ss_server_cert; + else { + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; + } + break; + case server_key_exchange: + state = ss_server_keyexchange; + break; + case certificate_request: + state = ss_server_certrequest; + break; + case server_hello_done: + state = ss_server_hellodone; + break; + case certificate_verify: + state = ss_client_certverify; + break; + case client_key_exchange: + state = ss_client_keyexchange; + break; + case finished: + if (ssl->options.side == WOLFSSL_SERVER_END) + state = ss_client_finished; + else if (ssl->options.side == WOLFSSL_CLIENT_END) + state = ss_server_finished; + else { + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; + } + break; + case certificate_status: + state = ss_server_certificatestatus; + break; + case key_update: + if (ssl->options.side == WOLFSSL_SERVER_END) + state = ss_client_keyupdate; + else if (ssl->options.side == WOLFSSL_CLIENT_END) + state = ss_server_keyupdate; + else { + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; + } + break; + case change_cipher_hs: + if (ssl->options.side == WOLFSSL_SERVER_END) + state = ss_client_changecipherspec; + else if (ssl->options.side == WOLFSSL_CLIENT_END) + state = ss_server_changecipherspec; + else { + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; + } + break; + default: + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; } + } + else { + /* Send process */ + if (ssl->options.side == WOLFSSL_SERVER_END) + state = ssl->options.serverState; + else + state = ssl->options.clientState; - if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) { - WOLFSSL_MSG("get ecc der failed"); - XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY); - return WOLFSSL_FAILURE; + switch (state) { + case SERVER_HELLOVERIFYREQUEST_COMPLETE: + state = ss_server_helloverify; + break; + case SERVER_HELLO_RETRY_REQUEST_COMPLETE: + state = ss_server_helloretryrequest; + break; + case SERVER_HELLO_COMPLETE: + state = ss_server_hello; + break; + case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE: + state = ss_server_encryptedextensions; + break; + case SERVER_CERT_COMPLETE: + state = ss_server_cert; + break; + case SERVER_KEYEXCHANGE_COMPLETE: + state = ss_server_keyexchange; + break; + case SERVER_HELLODONE_COMPLETE: + state = ss_server_hellodone; + break; + case SERVER_CHANGECIPHERSPEC_COMPLETE: + state = ss_server_changecipherspec; + break; + case SERVER_FINISHED_COMPLETE: + state = ss_server_finished; + break; + case CLIENT_HELLO_RETRY: + case CLIENT_HELLO_COMPLETE: + state = ss_client_hello; + break; + case CLIENT_KEYEXCHANGE_COMPLETE: + state = ss_client_keyexchange; + break; + case CLIENT_CHANGECIPHERSPEC_COMPLETE: + state = ss_client_changecipherspec; + break; + case CLIENT_FINISHED_COMPLETE: + state = ss_client_finished; + break; + case HANDSHAKE_DONE: + state = ss_handshake_done; + break; + default: + WOLFSSL_MSG("Unknown State"); + state = ss_null_state; } - pt = der; /* in case pointer gets advanced */ - ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz); - XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY); } -#endif - *pkey = ret; -#ifdef HAVE_ECC - if (ret != NULL) - return WOLFSSL_SUCCESS; - else -#endif - return WOLFSSL_FAILURE; + if (protocol == UNKNOWN) { + WOLFSSL_MSG("Unknown protocol"); + return ""; + } + else { + return OUTPUT_STR[state][protocol][cbmode]; + } } -#endif /* !NO_WOLFSSL_SERVER */ +#endif /* OPENSSL_EXTRA */ -/** - * This function checks if any compiled in protocol versions are - * left enabled after calls to set_min or set_max API. - * @param major The SSL/TLS major version - * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no - * protocol versions are left enabled. - */ -static int CheckSslMethodVersion(byte major, unsigned long options) +static long wolf_set_options(long old_op, long op) { - int sanityConfirmed = 0; + /* if SSL_OP_ALL then turn all bug workarounds on */ + if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) { + WOLFSSL_MSG("\tSSL_OP_ALL"); + } - (void)options; + /* by default cookie exchange is on with DTLS */ + if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) { + WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default"); + } - switch (major) { - #ifndef NO_TLS - case SSLv3_MAJOR: - #ifdef WOLFSSL_ALLOW_SSLV3 - if (!(options & WOLFSSL_OP_NO_SSLv3)) { - sanityConfirmed = 1; - } - #endif - #ifndef NO_OLD_TLS - if (!(options & WOLFSSL_OP_NO_TLSv1)) - sanityConfirmed = 1; - if (!(options & WOLFSSL_OP_NO_TLSv1_1)) - sanityConfirmed = 1; - #endif - #ifndef WOLFSSL_NO_TLS12 - if (!(options & WOLFSSL_OP_NO_TLSv1_2)) - sanityConfirmed = 1; - #endif - #ifdef WOLFSSL_TLS13 - if (!(options & WOLFSSL_OP_NO_TLSv1_3)) - sanityConfirmed = 1; - #endif - break; - #endif - #ifdef WOLFSSL_DTLS - case DTLS_MAJOR: - sanityConfirmed = 1; - break; - #endif - default: - WOLFSSL_MSG("Invalid major version"); - return WOLFSSL_FAILURE; + if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) { + WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2"); } - if (!sanityConfirmed) { - WOLFSSL_MSG("All compiled in TLS versions disabled"); - return WOLFSSL_FAILURE; + +#ifdef SSL_OP_NO_TLSv1_3 + if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { + WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3"); } - return WOLFSSL_SUCCESS; -} +#endif -/** - * protoVerTbl holds (D)TLS version numbers in ascending order. - * Except DTLS versions, the newer version is located in the latter part of - * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and - * wolfSSL_CTX_set_max_proto_version. - */ -static const int protoVerTbl[] = { - SSL3_VERSION, - TLS1_VERSION, - TLS1_1_VERSION, - TLS1_2_VERSION, - TLS1_3_VERSION, - DTLS1_VERSION, - DTLS1_2_VERSION -}; -/* number of protocol versions listed in protoVerTbl */ -#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int)) + if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) { + WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2"); + } -/** - * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol - * version to use by SSL objects created from this WOLFSSL_CTX. - * This API guarantees that a version of SSL/TLS lower than specified - * here will not be allowed. If the version specified is not compiled in - * then this API sets the lowest compiled in protocol version. - * This API also accept 0 as version, to set the minimum version automatically. - * CheckSslMethodVersion() is called to check if any remaining protocol versions - * are enabled. - * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects - * @param version Any of the following - * * 0 - * * SSL3_VERSION - * * TLS1_VERSION - * * TLS1_1_VERSION - * * TLS1_2_VERSION - * * TLS1_3_VERSION - * * DTLS1_VERSION - * * DTLS1_2_VERSION - * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no - * protocol versions are left enabled. - */ -static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex"); + if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) { + WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1"); + } - if (ctx == NULL) { - return WOLFSSL_FAILURE; + if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) { + WOLFSSL_MSG("\tSSL_OP_NO_TLSv1"); } - switch (version) { -#ifndef NO_TLS - case SSL3_VERSION: -#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) - ctx->minDowngrade = SSLv3_MINOR; - break; -#endif - case TLS1_VERSION: - #ifdef WOLFSSL_ALLOW_TLSV10 - ctx->minDowngrade = TLSv1_MINOR; - break; - #endif - case TLS1_1_VERSION: - #ifndef NO_OLD_TLS - ctx->minDowngrade = TLSv1_1_MINOR; - break; - #endif - case TLS1_2_VERSION: - #ifndef WOLFSSL_NO_TLS12 - ctx->minDowngrade = TLSv1_2_MINOR; - break; - #endif - case TLS1_3_VERSION: - #ifdef WOLFSSL_TLS13 - ctx->minDowngrade = TLSv1_3_MINOR; - break; - #endif -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - #ifndef NO_OLD_TLS - ctx->minDowngrade = DTLS_MINOR; - break; - #endif - case DTLS1_2_VERSION: - ctx->minDowngrade = DTLSv1_2_MINOR; - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; + if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) { + WOLFSSL_MSG("\tSSL_OP_NO_SSLv3"); } - switch (version) { -#ifndef NO_TLS - case TLS1_3_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2); - FALL_THROUGH; - case TLS1_2_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1); - FALL_THROUGH; - case TLS1_1_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1); - FALL_THROUGH; - case TLS1_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3); - break; - case SSL3_VERSION: - case SSL2_VERSION: - /* Nothing to do here */ - break; -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - case DTLS1_2_VERSION: - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; + if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) == + WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) { + WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE"); } - return CheckSslMethodVersion(ctx->method->version.major, ctx->mask); + if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) { + #ifdef HAVE_LIBZ + WOLFSSL_MSG("SSL_OP_NO_COMPRESSION"); + #else + WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in"); + #endif + } + + return old_op | op; } -/* Sets the min protocol version allowed with WOLFSSL_CTX - * returns WOLFSSL_SUCCESS on success */ -int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version) +static int FindHashSig(const Suites* suites, byte first, byte second) { - int ret; - int proto = 0; - int maxProto = 0; - int i; - int idx = 0; + word16 i; - WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version"); - - if (ctx == NULL) { - return WOLFSSL_FAILURE; + if (suites == NULL || suites->hashSigAlgoSz == 0) { + WOLFSSL_MSG("Suites pointer error or suiteSz 0"); + return SUITES_ERROR; } - if (version != 0) { - proto = version; - ctx->minProto = 0; /* turn min proto flag off */ - for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { - if (protoVerTbl[i] == version) { - break; - } - } + + for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) { + if (suites->hashSigAlgo[i] == first && + suites->hashSigAlgo[i+1] == second ) + return i; } - else { - /* when 0 is specified as version, try to find out the min version */ - for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { - ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]); - if (ret == WOLFSSL_SUCCESS) { - proto = protoVerTbl[i]; - ctx->minProto = 1; /* turn min proto flag on */ - break; - } - } + + return MATCH_SUITE_ERROR; +} + +long wolfSSL_set_options(WOLFSSL* ssl, long op) +{ + word16 haveRSA = 1; + word16 havePSK = 0; + int keySz = 0; + + WOLFSSL_ENTER("wolfSSL_set_options"); + + if (ssl == NULL) { + return 0; } - /* check case where max > min , if so then clear the NO_* options - * i is the index into the table for proto version used, see if the max - * proto version index found is smaller */ - maxProto = wolfSSL_CTX_get_max_proto_version(ctx); - for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) { - if (protoVerTbl[idx] == maxProto) { - break; - } + ssl->options.mask = wolf_set_options(ssl->options.mask, op); + + if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { + WOLFSSL_MSG("Disabling TLS 1.3"); + if (ssl->version.minor == TLSv1_3_MINOR) + ssl->version.minor = TLSv1_2_MINOR; } - if (idx < i) { - wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 | - WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 | - WOLFSSL_OP_NO_TLSv1_3); + + if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) { + WOLFSSL_MSG("Disabling TLS 1.2"); + if (ssl->version.minor == TLSv1_2_MINOR) + ssl->version.minor = TLSv1_1_MINOR; } - ret = Set_CTX_min_proto_version(ctx, proto); - return ret; -} + if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) { + WOLFSSL_MSG("Disabling TLS 1.1"); + if (ssl->version.minor == TLSv1_1_MINOR) + ssl->version.minor = TLSv1_MINOR; + } -/** - * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol - * version to use by SSL objects created from this WOLFSSL_CTX. - * This API guarantees that a version of SSL/TLS higher than specified - * here will not be allowed. If the version specified is not compiled in - * then this API sets the highest compiled in protocol version. - * This API also accept 0 as version, to set the maximum version automatically. - * CheckSslMethodVersion() is called to check if any remaining protocol versions - * are enabled. - * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects - * @param ver Any of the following - * * 0 - * * SSL3_VERSION - * * TLS1_VERSION - * * TLS1_1_VERSION - * * TLS1_2_VERSION - * * TLS1_3_VERSION - * * DTLS1_VERSION - * * DTLS1_2_VERSION - * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no - * protocol versions are left enabled. - */ -static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver) -{ - int ret; - WOLFSSL_ENTER("Set_CTX_max_proto_version"); + if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) { + WOLFSSL_MSG("Disabling TLS 1.0"); + if (ssl->version.minor == TLSv1_MINOR) + ssl->version.minor = SSLv3_MINOR; + } - if (!ctx || !ctx->method) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; + if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION) + == WOLFSSL_OP_NO_COMPRESSION) { + #ifdef HAVE_LIBZ + ssl->options.usingCompression = 0; + #endif } - switch (ver) { - case SSL2_VERSION: - WOLFSSL_MSG("wolfSSL does not support SSLv2"); - return WOLFSSL_FAILURE; -#ifndef NO_TLS - case SSL3_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1); - FALL_THROUGH; - case TLS1_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1); - FALL_THROUGH; - case TLS1_1_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2); - FALL_THROUGH; - case TLS1_2_VERSION: - wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3); - FALL_THROUGH; - case TLS1_3_VERSION: - /* Nothing to do here */ - break; -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - case DTLS1_2_VERSION: - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; +#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \ + || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)) + if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { + ssl->options.noTicketTls12 = 1; } +#endif - ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask); - if (ret == WOLFSSL_SUCCESS) { - /* Check the major */ - switch (ver) { - #ifndef NO_TLS - case SSL3_VERSION: - case TLS1_VERSION: - case TLS1_1_VERSION: - case TLS1_2_VERSION: - case TLS1_3_VERSION: - if (ctx->method->version.major != SSLv3_MAJOR) { - WOLFSSL_MSG("Mismatched protocol version"); - return WOLFSSL_FAILURE; + + /* in the case of a version change the cipher suites should be reset */ +#ifndef NO_PSK + havePSK = ssl->options.havePSK; +#endif +#ifdef NO_RSA + haveRSA = 0; +#endif +#ifndef NO_CERTS + keySz = ssl->buffers.keySz; +#endif + + if (ssl->options.side != WOLFSSL_NEITHER_END) { + if (AllocateSuites(ssl) != 0) + return 0; + if (!ssl->suites->setSuites) { + InitSuites(ssl->suites, ssl->version, keySz, haveRSA, + havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, + ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, + ssl->options.haveFalconSig, + ssl->options.haveDilithiumSig, ssl->options.useAnon, + TRUE, ssl->options.side); + } + else { + /* Only preserve overlapping suites */ + Suites tmpSuites; + word16 in, out, haveECDSAsig = 0; + word16 haveStaticECC = ssl->options.haveStaticECC; +#ifdef NO_RSA + haveECDSAsig = 1; + haveStaticECC = 1; +#endif + XMEMSET(&tmpSuites, 0, sizeof(Suites)); + /* Get all possible ciphers and sigalgs for the version. Following + * options limit the allowed ciphers so let's try to get as many as + * possible. + * - haveStaticECC turns off haveRSA + * - haveECDSAsig turns off haveRSAsig */ + InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1, + haveStaticECC, 1, 1, 1, 1, ssl->options.side); + for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) { + if (FindSuite(&tmpSuites, ssl->suites->suites[in], + ssl->suites->suites[in+1]) >= 0) { + ssl->suites->suites[out] = ssl->suites->suites[in]; + ssl->suites->suites[out+1] = ssl->suites->suites[in+1]; + out += SUITE_LEN; + } } - break; - #endif - #ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - case DTLS1_2_VERSION: - if (ctx->method->version.major != DTLS_MAJOR) { - WOLFSSL_MSG("Mismatched protocol version"); - return WOLFSSL_FAILURE; + ssl->suites->suiteSz = out; + for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) { + if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in], + ssl->suites->hashSigAlgo[in+1]) >= 0) { + ssl->suites->hashSigAlgo[out] = + ssl->suites->hashSigAlgo[in]; + ssl->suites->hashSigAlgo[out+1] = + ssl->suites->hashSigAlgo[in+1]; + out += 2; + } } - break; - #endif - } - /* Update the method */ - switch (ver) { - case SSL2_VERSION: - WOLFSSL_MSG("wolfSSL does not support SSLv2"); - return WOLFSSL_FAILURE; - #ifndef NO_TLS - case SSL3_VERSION: - ctx->method->version.minor = SSLv3_MINOR; - break; - case TLS1_VERSION: - ctx->method->version.minor = TLSv1_MINOR; - break; - case TLS1_1_VERSION: - ctx->method->version.minor = TLSv1_1_MINOR; - break; - case TLS1_2_VERSION: - ctx->method->version.minor = TLSv1_2_MINOR; - break; - case TLS1_3_VERSION: - ctx->method->version.minor = TLSv1_3_MINOR; - break; - #endif - #ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - ctx->method->version.minor = DTLS_MINOR; - break; - case DTLS1_2_VERSION: - ctx->method->version.minor = DTLSv1_2_MINOR; - break; - #endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; + ssl->suites->hashSigAlgoSz = out; } } - return ret; + + return ssl->options.mask; } -/* Sets the max protocol version allowed with WOLFSSL_CTX - * returns WOLFSSL_SUCCESS on success */ -int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version) +long wolfSSL_get_options(const WOLFSSL* ssl) { - int i; - int ret = WOLFSSL_FAILURE; - int minProto; + WOLFSSL_ENTER("wolfSSL_get_options"); + if(ssl == NULL) + return WOLFSSL_FAILURE; + return ssl->options.mask; +} - WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version"); +#if defined(HAVE_SECURE_RENEGOTIATION) \ + || defined(HAVE_SERVER_RENEGOTIATION_INFO) +/* clears the counter for number of renegotiations done + * returns the current count before it is cleared */ +long wolfSSL_clear_num_renegotiations(WOLFSSL *s) +{ + long total; - if (ctx == NULL) { - return ret; - } + WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations"); + if (s == NULL) + return 0; - /* clear out flags and reset min protocol version */ - minProto = wolfSSL_CTX_get_min_proto_version(ctx); - wolfSSL_CTX_clear_options(ctx, - WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 | - WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3); - wolfSSL_CTX_set_min_proto_version(ctx, minProto); - if (version != 0) { - ctx->maxProto = 0; /* turn max proto flag off */ - return Set_CTX_max_proto_version(ctx, version); - } + total = s->secure_rene_count; + s->secure_rene_count = 0; + return total; +} - /* when 0 is specified as version, try to find out the min version from - * the bottom to top of the protoverTbl. - */ - for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) { - ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]); - if (ret == WOLFSSL_SUCCESS) { - ctx->maxProto = 1; /* turn max proto flag on */ - break; - } - } - return ret; +/* return the number of renegotiations since wolfSSL_new */ +long wolfSSL_total_renegotiations(WOLFSSL *s) +{ + WOLFSSL_ENTER("wolfSSL_total_renegotiations"); + return wolfSSL_num_renegotiations(s); } -static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver) +/* return the number of renegotiations since wolfSSL_new */ +long wolfSSL_num_renegotiations(WOLFSSL* s) { - WOLFSSL_ENTER("Set_SSL_min_proto_version"); - - if (ssl == NULL) { - return WOLFSSL_FAILURE; + if (s == NULL) { + return 0; } - switch (ver) { -#ifndef NO_TLS - case SSL3_VERSION: -#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) - ssl->options.minDowngrade = SSLv3_MINOR; - break; -#endif - case TLS1_VERSION: - #ifdef WOLFSSL_ALLOW_TLSV10 - ssl->options.minDowngrade = TLSv1_MINOR; - break; - #endif - case TLS1_1_VERSION: - #ifndef NO_OLD_TLS - ssl->options.minDowngrade = TLSv1_1_MINOR; - break; - #endif - case TLS1_2_VERSION: - #ifndef WOLFSSL_NO_TLS12 - ssl->options.minDowngrade = TLSv1_2_MINOR; - break; - #endif - case TLS1_3_VERSION: - #ifdef WOLFSSL_TLS13 - ssl->options.minDowngrade = TLSv1_3_MINOR; - break; - #endif -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - #ifndef NO_OLD_TLS - ssl->options.minDowngrade = DTLS_MINOR; - break; - #endif - case DTLS1_2_VERSION: - ssl->options.minDowngrade = DTLSv1_2_MINOR; - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; - } + return s->secure_rene_count; +} - switch (ver) { -#ifndef NO_TLS - case TLS1_3_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2; - FALL_THROUGH; - case TLS1_2_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1; - FALL_THROUGH; - case TLS1_1_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1; - FALL_THROUGH; - case TLS1_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_SSLv3; - break; - case SSL3_VERSION: - case SSL2_VERSION: - /* Nothing to do here */ - break; -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - case DTLS1_2_VERSION: - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); - return WOLFSSL_FAILURE; - } - return CheckSslMethodVersion(ssl->version.major, ssl->options.mask); +/* Is there a renegotiation currently in progress? */ +int wolfSSL_SSL_renegotiate_pending(WOLFSSL *s) +{ + return s && s->options.handShakeDone && + s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0; } +#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */ -int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version) -{ - int i; - int ret = WOLFSSL_FAILURE;; +#ifdef OPENSSL_EXTRA - WOLFSSL_ENTER("wolfSSL_set_min_proto_version"); +long wolfSSL_clear_options(WOLFSSL* ssl, long opt) +{ + WOLFSSL_ENTER("wolfSSL_clear_options"); + if(ssl == NULL) + return WOLFSSL_FAILURE; + ssl->options.mask &= ~opt; + return ssl->options.mask; +} +#ifdef HAVE_PK_CALLBACKS +long wolfSSL_set_tlsext_debug_arg(WOLFSSL* ssl, void *arg) +{ if (ssl == NULL) { return WOLFSSL_FAILURE; } - if (version != 0) { - return Set_SSL_min_proto_version(ssl, version); - } - - /* when 0 is specified as version, try to find out the min version */ - for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) { - ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]); - if (ret == WOLFSSL_SUCCESS) - break; - } - return ret; + ssl->loggingCtx = arg; + return WOLFSSL_SUCCESS; } +#endif /* HAVE_PK_CALLBACKS */ -static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver) +/*** TBD ***/ +#ifndef NO_WOLFSSL_STUB +int wolfSSL_sk_SSL_COMP_zero(WOLFSSL_STACK* st) { + (void)st; + WOLFSSL_STUB("wolfSSL_sk_SSL_COMP_zero"); + /* wolfSSL_set_options(ssl, SSL_OP_NO_COMPRESSION); */ + return WOLFSSL_FAILURE; +} +#endif - WOLFSSL_ENTER("Set_SSL_max_proto_version"); +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST +long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type) +{ + WOLFSSL_ENTER("wolfSSL_set_tlsext_status_type"); - if (!ssl) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; + if (s == NULL){ + return BAD_FUNC_ARG; } - switch (ver) { - case SSL2_VERSION: - WOLFSSL_MSG("wolfSSL does not support SSLv2"); - return WOLFSSL_FAILURE; -#ifndef NO_TLS - case SSL3_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1; - FALL_THROUGH; - case TLS1_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1; - FALL_THROUGH; - case TLS1_1_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2; - FALL_THROUGH; - case TLS1_2_VERSION: - ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3; - FALL_THROUGH; - case TLS1_3_VERSION: - /* Nothing to do here */ - break; -#endif -#ifdef WOLFSSL_DTLS - case DTLS1_VERSION: - case DTLS1_2_VERSION: - break; -#endif - default: - WOLFSSL_MSG("Unrecognized protocol version or not compiled in"); + if (type == TLSEXT_STATUSTYPE_ocsp){ + int r = TLSX_UseCertificateStatusRequest(&s->extensions, (byte)type, 0, + s, s->heap, s->devId); + return (long)r; + } else { + WOLFSSL_MSG( + "SSL_set_tlsext_status_type only supports TLSEXT_STATUSTYPE_ocsp type."); return WOLFSSL_FAILURE; } - return CheckSslMethodVersion(ssl->version.major, ssl->options.mask); } -int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version) +long wolfSSL_get_tlsext_status_type(WOLFSSL *s) { - int i; - int ret = WOLFSSL_FAILURE;; - - WOLFSSL_ENTER("wolfSSL_set_max_proto_version"); - - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } - if (version != 0) { - return Set_SSL_max_proto_version(ssl, version); - } + TLSX* extension; - /* when 0 is specified as version, try to find out the min version from - * the bottom to top of the protoverTbl. - */ - for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) { - ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]); - if (ret == WOLFSSL_SUCCESS) - break; - } + if (s == NULL) + return WOLFSSL_FATAL_ERROR; + extension = TLSX_Find(s->extensions, TLSX_STATUS_REQUEST); + return extension != NULL ? TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR; +} +#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */ - return ret; +#ifndef NO_WOLFSSL_STUB +long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg) +{ + (void)s; + (void)arg; + WOLFSSL_STUB("wolfSSL_get_tlsext_status_exts"); + return WOLFSSL_FAILURE; } +#endif -static int GetMinProtoVersion(int minDowngrade) +/*** TBD ***/ +#ifndef NO_WOLFSSL_STUB +long wolfSSL_set_tlsext_status_exts(WOLFSSL *s, void *arg) { - int ret; + (void)s; + (void)arg; + WOLFSSL_STUB("wolfSSL_set_tlsext_status_exts"); + return WOLFSSL_FAILURE; +} +#endif - switch (minDowngrade) { -#ifndef NO_OLD_TLS - #ifdef WOLFSSL_ALLOW_SSLV3 - case SSLv3_MINOR: - ret = SSL3_VERSION; - break; - #endif - #ifdef WOLFSSL_ALLOW_TLSV10 - case TLSv1_MINOR: - ret = TLS1_VERSION; - break; - #endif - case TLSv1_1_MINOR: - ret = TLS1_1_VERSION; - break; +/*** TBD ***/ +#ifndef NO_WOLFSSL_STUB +long wolfSSL_get_tlsext_status_ids(WOLFSSL *s, void *arg) +{ + (void)s; + (void)arg; + WOLFSSL_STUB("wolfSSL_get_tlsext_status_ids"); + return WOLFSSL_FAILURE; +} #endif -#ifndef WOLFSSL_NO_TLS12 - case TLSv1_2_MINOR: - ret = TLS1_2_VERSION; - break; + +/*** TBD ***/ +#ifndef NO_WOLFSSL_STUB +long wolfSSL_set_tlsext_status_ids(WOLFSSL *s, void *arg) +{ + (void)s; + (void)arg; + WOLFSSL_STUB("wolfSSL_set_tlsext_status_ids"); + return WOLFSSL_FAILURE; +} #endif -#ifdef WOLFSSL_TLS13 - case TLSv1_3_MINOR: - ret = TLS1_3_VERSION; - break; + +#ifndef NO_WOLFSSL_STUB +/*** TBD ***/ +WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl) +{ + (void)ssl; + WOLFSSL_STUB("SSL_get_privatekey"); + return NULL; +} #endif - default: - ret = 0; - break; - } - return ret; +#ifndef NO_WOLFSSL_STUB +/*** TBD ***/ +void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, + WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)) +{ + (void)ctx; + (void)dh; + WOLFSSL_STUB("SSL_CTX_set_tmp_dh_callback"); } +#endif -int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx) +#ifndef NO_WOLFSSL_STUB +/*** TBD ***/ +WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) { - int ret = 0; + WOLFSSL_STUB("SSL_COMP_get_compression_methods"); + return NULL; +} +#endif - WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version"); - if (ctx != NULL) { - if (ctx->minProto) { - ret = 0; - } - else { - ret = GetMinProtoVersion(ctx->minDowngrade); - } - } - else { - ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE); +int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p) +{ + WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_num"); + if (p == NULL) { + return WOLFSSL_FATAL_ERROR; } - - WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret); - - return ret; + return (int)p->num; } - -/* returns the maximum allowed protocol version given the 'options' used - * returns WOLFSSL_FATAL_ERROR on no match */ -static int GetMaxProtoVersion(long options) +WOLFSSL_CIPHER* wolfSSL_sk_SSL_CIPHER_value(WOLFSSL_STACK* sk, int i) { -#ifndef NO_TLS -#ifdef WOLFSSL_TLS13 - if (!(options & WOLFSSL_OP_NO_TLSv1_3)) - return TLS1_3_VERSION; -#endif -#ifndef WOLFSSL_NO_TLS12 - if (!(options & WOLFSSL_OP_NO_TLSv1_2)) - return TLS1_2_VERSION; -#endif -#ifndef NO_OLD_TLS - if (!(options & WOLFSSL_OP_NO_TLSv1_1)) - return TLS1_1_VERSION; - #ifdef WOLFSSL_ALLOW_TLSV10 - if (!(options & WOLFSSL_OP_NO_TLSv1)) - return TLS1_VERSION; - #endif - #ifdef WOLFSSL_ALLOW_SSLV3 - if (!(options & WOLFSSL_OP_NO_SSLv3)) - return SSL3_VERSION; - #endif -#endif -#else - (void)options; -#endif /* NO_TLS */ - return WOLFSSL_FATAL_ERROR; + WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_value"); + return (WOLFSSL_CIPHER*)wolfSSL_sk_value(sk, i); } - -/* returns the maximum protocol version for 'ctx' */ -int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx) +#if !defined(NETOS) +void ERR_load_SSL_strings(void) { - int ret = 0; - long options = 0; /* default to nothing set */ - WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version"); +} +#endif - if (ctx != NULL) { - options = wolfSSL_CTX_get_options(ctx); - } +#ifdef HAVE_OCSP +long wolfSSL_get_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char **resp) +{ + if (s == NULL || resp == NULL) + return 0; - if ((ctx != NULL) && ctx->maxProto) { - ret = 0; - } - else { - ret = GetMaxProtoVersion(options); - } + *resp = s->ocspResp; + return s->ocspRespSz; +} - WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret); +long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char *resp, + int len) +{ + if (s == NULL) + return WOLFSSL_FAILURE; - if (ret == WOLFSSL_FATAL_ERROR) { - WOLFSSL_MSG("Error getting max proto version"); - ret = 0; /* setting ret to 0 to match compat return */ - } - return ret; + s->ocspResp = resp; + s->ocspRespSz = len; + + return WOLFSSL_SUCCESS; } -#endif /* OPENSSL_EXTRA */ +#endif /* HAVE_OCSP */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ - defined(HAVE_SECRET_CALLBACK) -#if !defined(NO_WOLFSSL_CLIENT) -/* Return the amount of random bytes copied over or error case. - * ssl : ssl struct after handshake - * out : buffer to hold random bytes - * outSz : either 0 (return max buffer sz) or size of out buffer +#ifdef HAVE_MAX_FRAGMENT +#ifndef NO_WOLFSSL_CLIENT +/** + * Set max fragment tls extension + * @param c a pointer to WOLFSSL_CTX object + * @param mode maximum fragment length mode + * @return 1 on success, otherwise 0 or negative error code */ -size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, - size_t outSz) +int wolfSSL_CTX_set_tlsext_max_fragment_length(WOLFSSL_CTX *c, + unsigned char mode) { - size_t size; + if (c == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 )) + return BAD_FUNC_ARG; - /* return max size of buffer */ - if (outSz == 0) { - return RAN_LEN; - } + return wolfSSL_CTX_UseMaxFragment(c, mode); +} +/** + * Set max fragment tls extension + * @param c a pointer to WOLFSSL object + * @param mode maximum fragment length mode + * @return 1 on success, otherwise 0 or negative error code + */ +int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s, unsigned char mode) +{ + if (s == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 )) + return BAD_FUNC_ARG; - if (ssl == NULL || out == NULL) { - return 0; - } + return wolfSSL_UseMaxFragment(s, mode); +} +#endif /* NO_WOLFSSL_CLIENT */ +#endif /* HAVE_MAX_FRAGMENT */ - if (ssl->arrays == NULL) { - WOLFSSL_MSG("Arrays struct not saved after handshake"); - return 0; +#endif /* OPENSSL_EXTRA */ + +#ifdef WOLFSSL_HAVE_TLS_UNIQUE +size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count) +{ + byte len = 0; + + WOLFSSL_ENTER("wolfSSL_get_finished"); + + if (!ssl || !buf || count < TLS_FINISHED_SZ) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } - if (outSz > RAN_LEN) { - size = RAN_LEN; + if (ssl->options.side == WOLFSSL_SERVER_END) { + len = ssl->serverFinished_len; + XMEMCPY(buf, ssl->serverFinished, len); } else { - size = outSz; + len = ssl->clientFinished_len; + XMEMCPY(buf, ssl->clientFinished, len); } - - XMEMCPY(out, ssl->arrays->clientRandom, size); - return size; + return len; } -#endif /* !NO_WOLFSSL_CLIENT */ -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */ -#ifdef OPENSSL_EXTRA +size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count) +{ + byte len = 0; + WOLFSSL_ENTER("wolfSSL_get_peer_finished"); - unsigned long wolfSSLeay(void) - { - return SSLEAY_VERSION_NUMBER; + if (!ssl || !buf || count < TLS_FINISHED_SZ) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } - unsigned long wolfSSL_OpenSSL_version_num(void) - { - return OPENSSL_VERSION_NUMBER; + if (ssl->options.side == WOLFSSL_CLIENT_END) { + len = ssl->serverFinished_len; + XMEMCPY(buf, ssl->serverFinished, len); } - - const char* wolfSSLeay_version(int type) - { - (void)type; -#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L - return wolfSSL_OpenSSL_version(type); -#else - return wolfSSL_OpenSSL_version(); -#endif + else { + len = ssl->clientFinished_len; + XMEMCPY(buf, ssl->clientFinished, len); } -#endif /* OPENSSL_EXTRA */ -#ifdef OPENSSL_EXTRA - void wolfSSL_ERR_free_strings(void) - { - /* handled internally */ - } + return len; +} +#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ - void wolfSSL_cleanup_all_ex_data(void) - { - /* nothing to do here */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(OPENSSL_ALL) +long wolfSSL_get_verify_result(const WOLFSSL *ssl) +{ + if (ssl == NULL) { + return WOLFSSL_FAILURE; } -#endif /* OPENSSL_EXTRA */ + return ssl->peerVerifyRet; +} +#endif -#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \ - defined(HAVE_CURL) - void wolfSSL_ERR_clear_error(void) - { - WOLFSSL_ENTER("wolfSSL_ERR_clear_error"); - #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) - wc_ClearErrorNodes(); - #endif - } +#ifdef OPENSSL_EXTRA + +#ifndef NO_WOLFSSL_STUB +/* shows the number of accepts attempted by CTX in it's lifetime */ +long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_accept"); + (void)ctx; + return 0; +} #endif -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - int wolfSSL_clear(WOLFSSL* ssl) - { - WOLFSSL_ENTER("wolfSSL_clear"); +#ifndef NO_WOLFSSL_STUB +/* shows the number of connects attempted CTX in it's lifetime */ +long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_connect"); + (void)ctx; + return 0; +} +#endif - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } - if (!ssl->options.handShakeDone) { - /* Only reset the session if we didn't complete a handshake */ - wolfSSL_FreeSession(ssl->ctx, ssl->session); - ssl->session = wolfSSL_NewSession(ssl->heap); - if (ssl->session == NULL) { - return WOLFSSL_FAILURE; - } - } +#ifndef NO_WOLFSSL_STUB +/* shows the number of accepts completed by CTX in it's lifetime */ +long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good"); + (void)ctx; + return 0; +} +#endif - /* reset error */ - ssl->error = 0; - /* reset option bits */ - ssl->options.isClosed = 0; - ssl->options.connReset = 0; - ssl->options.sentNotify = 0; - ssl->options.closeNotify = 0; - ssl->options.sendVerify = 0; - ssl->options.serverState = NULL_STATE; - ssl->options.clientState = NULL_STATE; - ssl->options.connectState = CONNECT_BEGIN; - ssl->options.acceptState = ACCEPT_BEGIN; - ssl->options.handShakeState = NULL_STATE; - ssl->options.handShakeDone = 0; - ssl->options.processReply = 0; /* doProcessInit */ - ssl->options.havePeerVerify = 0; - ssl->options.havePeerCert = 0; - ssl->options.peerAuthGood = 0; - ssl->options.tls1_3 = 0; - ssl->options.haveSessionId = 0; - ssl->options.tls = 0; - ssl->options.tls1_1 = 0; - #ifdef WOLFSSL_DTLS - ssl->options.dtlsStateful = 0; - #endif - #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - ssl->options.noPskDheKe = 0; - #ifdef HAVE_SUPPORTED_CURVES - ssl->options.onlyPskDheKe = 0; - #endif - #endif - #ifdef HAVE_SESSION_TICKET - #ifdef WOLFSSL_TLS13 - ssl->options.ticketsSent = 0; - #endif - ssl->options.rejectTicket = 0; - #endif - #ifdef WOLFSSL_EARLY_DATA - ssl->earlyData = no_early_data; - ssl->earlyDataSz = 0; - #endif +#ifndef NO_WOLFSSL_STUB +/* shows the number of connects completed by CTX in it's lifetime */ +long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good"); + (void)ctx; + return 0; +} +#endif - #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS) - TLSX_FreeAll(ssl->extensions, ssl->heap); - ssl->extensions = NULL; - #endif - if (ssl->keys.encryptionOn) { - ForceZero(ssl->buffers.inputBuffer.buffer - - ssl->buffers.inputBuffer.offset, - ssl->buffers.inputBuffer.bufferSize); - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(ssl->buffers.inputBuffer.buffer - - ssl->buffers.inputBuffer.offset, - ssl->buffers.inputBuffer.bufferSize); - #endif - } - ssl->keys.encryptionOn = 0; - XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived)); - - if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS) - return WOLFSSL_FAILURE; +#ifndef NO_WOLFSSL_STUB +/* shows the number of renegotiation accepts attempted by CTX */ +long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate"); + (void)ctx; + return 0; +} +#endif - if (InitHandshakeHashes(ssl) != 0) - return WOLFSSL_FAILURE; -#ifdef KEEP_PEER_CERT - FreeX509(&ssl->peerCert); - InitX509(&ssl->peerCert, 0, ssl->heap); +#ifndef NO_WOLFSSL_STUB +/* shows the number of renegotiation accepts attempted by CTX */ +long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate"); + (void)ctx; + return 0; +} #endif -#ifdef WOLFSSL_QUIC - wolfSSL_quic_clear(ssl); + +#ifndef NO_WOLFSSL_STUB +long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_hits"); + (void)ctx; + return 0; +} #endif - return WOLFSSL_SUCCESS; - } -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ +#ifndef NO_WOLFSSL_STUB +long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits"); + (void)ctx; + return 0; +} +#endif -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) - long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode) - { - /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */ - WOLFSSL_ENTER("wolfSSL_CTX_set_mode"); - switch(mode) { - case SSL_MODE_ENABLE_PARTIAL_WRITE: - ctx->partialWrite = 1; - break; - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - case SSL_MODE_RELEASE_BUFFERS: - WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); - break; - #endif - case SSL_MODE_AUTO_RETRY: - ctx->autoRetry = 1; - break; - default: - WOLFSSL_MSG("Mode Not Implemented"); - } +#ifndef NO_WOLFSSL_STUB +long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full"); + (void)ctx; + return 0; +} +#endif - /* SSL_MODE_AUTO_RETRY - * Should not return -1 with renegotiation on read/write */ - return mode; - } +#ifndef NO_WOLFSSL_STUB +long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_misses"); + (void)ctx; + return 0; +} +#endif - long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode) - { - /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */ - WOLFSSL_ENTER("wolfSSL_CTX_clear_mode"); - switch(mode) { - case SSL_MODE_ENABLE_PARTIAL_WRITE: - ctx->partialWrite = 0; - break; - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - case SSL_MODE_RELEASE_BUFFERS: - WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); - break; - #endif - case SSL_MODE_AUTO_RETRY: - ctx->autoRetry = 0; - break; - default: - WOLFSSL_MSG("Mode Not Implemented"); - } +#ifndef NO_WOLFSSL_STUB +long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx) +{ + WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts"); + (void)ctx; + return 0; +} +#endif - /* SSL_MODE_AUTO_RETRY - * Should not return -1 with renegotiation on read/write */ +#ifndef NO_CERTS - return 0; +long wolfSSL_CTX_set_tlsext_status_arg(WOLFSSL_CTX* ctx, void* arg) +{ + if (ctx == NULL || ctx->cm == NULL) { + return WOLFSSL_FAILURE; } -#endif -#ifdef WOLFSSL_SESSION_ID_CTX - /* Storing app session context id, this value is inherited by WOLFSSL - * objects created from WOLFSSL_CTX. Any session that is imported with a - * different session context id will be rejected. - * - * ctx structure to set context in - * sid_ctx value of context to set - * sid_ctx_len length of sid_ctx buffer - * - * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing - */ - int wolfSSL_CTX_set_session_id_context(WOLFSSL_CTX* ctx, - const unsigned char* sid_ctx, - unsigned int sid_ctx_len) - { - WOLFSSL_ENTER("wolfSSL_CTX_set_session_id_context"); + ctx->cm->ocspIOCtx = arg; + return WOLFSSL_SUCCESS; +} - /* No application specific context needed for wolfSSL */ - if (sid_ctx_len > ID_LEN || ctx == NULL || sid_ctx == NULL) { - return WOLFSSL_FAILURE; - } - XMEMCPY(ctx->sessionCtx, sid_ctx, sid_ctx_len); - ctx->sessionCtxSz = (byte)sid_ctx_len; +#endif /* !NO_CERTS */ - return WOLFSSL_SUCCESS; +int wolfSSL_get_read_ahead(const WOLFSSL* ssl) +{ + if (ssl == NULL) { + return WOLFSSL_FAILURE; } + return ssl->readAhead; +} - /* Storing app session context id. Any session that is imported with a - * different session context id will be rejected. - * - * ssl structure to set context in - * id value of context to set - * len length of sid_ctx buffer - * - * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing - */ - int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id, - unsigned int len) - { - WOLFSSL_ENTER("wolfSSL_set_session_id_context"); - - if (len > ID_LEN || ssl == NULL || id == NULL) { - return WOLFSSL_FAILURE; - } - XMEMCPY(ssl->sessionCtx, id, len); - ssl->sessionCtxSz = (byte)len; - - return WOLFSSL_SUCCESS; +int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v) +{ + if (ssl == NULL) { + return WOLFSSL_FAILURE; } -#endif -#ifdef OPENSSL_EXTRA + ssl->readAhead = (byte)v; - #ifndef NO_WOLFSSL_STUB - long wolfSSL_SSL_get_mode(WOLFSSL* ssl) - { - /* TODO: */ - (void)ssl; - WOLFSSL_STUB("SSL_get_mode"); - return 0; - } - #endif + return WOLFSSL_SUCCESS; +} - #ifndef NO_WOLFSSL_STUB - long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx) - { - /* TODO: */ - (void)ctx; - WOLFSSL_STUB("SSL_CTX_get_mode"); - return 0; - } - #endif - #ifndef NO_WOLFSSL_STUB - void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m) - { - /* TODO: maybe? */ - (void)ctx; - (void)m; - WOLFSSL_STUB("SSL_CTX_set_default_read_ahead"); +int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx) +{ + if (ctx == NULL) { + return WOLFSSL_FAILURE; } - #endif + + return ctx->readAhead; +} - long wolfSSL_CTX_sess_get_cache_size(WOLFSSL_CTX* ctx) - { - (void)ctx; - #ifndef NO_SESSION_CACHE - return (long)(SESSIONS_PER_ROW * SESSION_ROWS); - #else - return 0; - #endif +int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v) +{ + if (ctx == NULL) { + return WOLFSSL_FAILURE; } + ctx->readAhead = (byte)v; - /* returns the unsigned error value and increments the pointer into the - * error queue. - * - * file pointer to file name - * line gets set to line number of error when not NULL - */ - unsigned long wolfSSL_ERR_get_error_line(const char** file, int* line) - { - #ifdef WOLFSSL_HAVE_ERROR_QUEUE - int ret = wc_PullErrorNode(file, NULL, line); - if (ret < 0) { - if (ret == BAD_STATE_E) return 0; /* no errors in queue */ - WOLFSSL_MSG("Issue getting error node"); - WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line", ret); - ret = 0 - ret; /* return absolute value of error */ + return WOLFSSL_SUCCESS; +} - /* panic and try to clear out nodes */ - wc_ClearErrorNodes(); - } - return (unsigned long)ret; - #else - (void)file; - (void)line; - return 0; - #endif +long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx, + void* arg) +{ + if (ctx == NULL) { + return WOLFSSL_FAILURE; } + ctx->userPRFArg = arg; + return WOLFSSL_SUCCESS; +} -#if (defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA)) && \ - (!defined(_WIN32) && !defined(NO_ERROR_QUEUE)) - static const char WOLFSSL_SYS_ACCEPT_T[] = "accept"; - static const char WOLFSSL_SYS_BIND_T[] = "bind"; - static const char WOLFSSL_SYS_CONNECT_T[] = "connect"; - static const char WOLFSSL_SYS_FOPEN_T[] = "fopen"; - static const char WOLFSSL_SYS_FREAD_T[] = "fread"; - static const char WOLFSSL_SYS_GETADDRINFO_T[] = "getaddrinfo"; - static const char WOLFSSL_SYS_GETSOCKOPT_T[] = "getsockopt"; - static const char WOLFSSL_SYS_GETSOCKNAME_T[] = "getsockname"; - static const char WOLFSSL_SYS_GETHOSTBYNAME_T[] = "gethostbyname"; - static const char WOLFSSL_SYS_GETNAMEINFO_T[] = "getnameinfo"; - static const char WOLFSSL_SYS_GETSERVBYNAME_T[] = "getservbyname"; - static const char WOLFSSL_SYS_IOCTLSOCKET_T[] = "ioctlsocket"; - static const char WOLFSSL_SYS_LISTEN_T[] = "listen"; - static const char WOLFSSL_SYS_OPENDIR_T[] = "opendir"; - static const char WOLFSSL_SYS_SETSOCKOPT_T[] = "setsockopt"; - static const char WOLFSSL_SYS_SOCKET_T[] = "socket"; +#endif /* OPENSSL_EXTRA */ - /* switch with int mapped to function name for compatibility */ - static const char* wolfSSL_ERR_sys_func(int fun) - { - switch (fun) { - case WOLFSSL_SYS_ACCEPT: return WOLFSSL_SYS_ACCEPT_T; - case WOLFSSL_SYS_BIND: return WOLFSSL_SYS_BIND_T; - case WOLFSSL_SYS_CONNECT: return WOLFSSL_SYS_CONNECT_T; - case WOLFSSL_SYS_FOPEN: return WOLFSSL_SYS_FOPEN_T; - case WOLFSSL_SYS_FREAD: return WOLFSSL_SYS_FREAD_T; - case WOLFSSL_SYS_GETADDRINFO: return WOLFSSL_SYS_GETADDRINFO_T; - case WOLFSSL_SYS_GETSOCKOPT: return WOLFSSL_SYS_GETSOCKOPT_T; - case WOLFSSL_SYS_GETSOCKNAME: return WOLFSSL_SYS_GETSOCKNAME_T; - case WOLFSSL_SYS_GETHOSTBYNAME: return WOLFSSL_SYS_GETHOSTBYNAME_T; - case WOLFSSL_SYS_GETNAMEINFO: return WOLFSSL_SYS_GETNAMEINFO_T; - case WOLFSSL_SYS_GETSERVBYNAME: return WOLFSSL_SYS_GETSERVBYNAME_T; - case WOLFSSL_SYS_IOCTLSOCKET: return WOLFSSL_SYS_IOCTLSOCKET_T; - case WOLFSSL_SYS_LISTEN: return WOLFSSL_SYS_LISTEN_T; - case WOLFSSL_SYS_OPENDIR: return WOLFSSL_SYS_OPENDIR_T; - case WOLFSSL_SYS_SETSOCKOPT: return WOLFSSL_SYS_SETSOCKOPT_T; - case WOLFSSL_SYS_SOCKET: return WOLFSSL_SYS_SOCKET_T; - default: - return "NULL"; - } - } -#endif /* DEBUG_WOLFSSL */ +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) +int wolfSSL_sk_num(const WOLFSSL_STACK* sk) +{ + WOLFSSL_ENTER("wolfSSL_sk_num"); + if (sk == NULL) + return 0; + return (int)sk->num; +} +void* wolfSSL_sk_value(const WOLFSSL_STACK* sk, int i) +{ + WOLFSSL_ENTER("wolfSSL_sk_value"); - void wolfSSL_ERR_put_error(int lib, int fun, int err, const char* file, - int line) - { - WOLFSSL_ENTER("wolfSSL_ERR_put_error"); + for (; sk != NULL && i > 0; i--) + sk = sk->next; + if (sk == NULL) + return NULL; - #if !defined(DEBUG_WOLFSSL) && !defined(OPENSSL_EXTRA) - (void)fun; - (void)err; - (void)file; - (void)line; - WOLFSSL_MSG("Not compiled in debug mode"); - #elif defined(OPENSSL_EXTRA) && \ - (defined(_WIN32) || defined(NO_ERROR_QUEUE)) - (void)fun; - (void)file; - (void)line; - WOLFSSL_ERROR(err); - #else - WOLFSSL_ERROR_LINE(err, wolfSSL_ERR_sys_func(fun), (unsigned int)line, - file, NULL); - #endif - (void)lib; + switch (sk->type) { + case STACK_TYPE_X509: + return (void*)sk->data.x509; + case STACK_TYPE_GEN_NAME: + return (void*)sk->data.gn; + case STACK_TYPE_BIO: + return (void*)sk->data.bio; + case STACK_TYPE_OBJ: + return (void*)sk->data.obj; + case STACK_TYPE_STRING: + return (void*)sk->data.string; + case STACK_TYPE_CIPHER: + return (void*)&sk->data.cipher; + case STACK_TYPE_ACCESS_DESCRIPTION: + return (void*)sk->data.access; + case STACK_TYPE_X509_EXT: + return (void*)sk->data.ext; + case STACK_TYPE_X509_REQ_ATTR: + return (void*)sk->data.generic; + case STACK_TYPE_NULL: + return (void*)sk->data.generic; + case STACK_TYPE_X509_NAME: + return (void*)sk->data.name; + case STACK_TYPE_X509_NAME_ENTRY: + return (void*)sk->data.name_entry; + case STACK_TYPE_CONF_VALUE: + #ifdef OPENSSL_EXTRA + return (void*)sk->data.conf; + #else + return NULL; + #endif + case STACK_TYPE_X509_INFO: + return (void*)sk->data.info; + case STACK_TYPE_BY_DIR_entry: + return (void*)sk->data.dir_entry; + case STACK_TYPE_BY_DIR_hash: + return (void*)sk->data.dir_hash; + case STACK_TYPE_X509_OBJ: + return (void*)sk->data.x509_obj; + case STACK_TYPE_DIST_POINT: + return (void*)sk->data.dp; + case STACK_TYPE_X509_CRL: + return (void*)sk->data.crl; + default: + return (void*)sk->data.generic; } +} +/* copies over data of "in" to "out" */ +static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out) +{ + if (in == NULL || out == NULL) + return; - /* Similar to wolfSSL_ERR_get_error_line but takes in a flags argument for - * more flexibility. - * - * file output pointer to file where error happened - * line output to line number of error - * data output data. Is a string if ERR_TXT_STRING flag is used - * flags output format of output - * - * Returns the error value or 0 if no errors are in the queue - */ - unsigned long wolfSSL_ERR_get_error_line_data(const char** file, int* line, - const char** data, int *flags) - { -#ifdef WOLFSSL_HAVE_ERROR_QUEUE - int ret; - - WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data"); - - if (flags != NULL) - *flags = ERR_TXT_STRING; /* Clear the flags */ - - ret = wc_PullErrorNode(file, data, line); - if (ret < 0) { - if (ret == BAD_STATE_E) return 0; /* no errors in queue */ - WOLFSSL_MSG("Error with pulling error node!"); - WOLFSSL_LEAVE("wolfSSL_ERR_get_error_line_data", ret); - ret = 0 - ret; /* return absolute value of error */ - - /* panic and try to clear out nodes */ - wc_ClearErrorNodes(); - } - - return (unsigned long)ret; -#else - WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data"); - WOLFSSL_MSG("Error queue turned off, can not get error line"); - (void)file; - (void)line; - (void)data; - (void)flags; - return 0; -#endif - } + *out = *in; +} -#endif /* OPENSSL_EXTRA */ +WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk) +{ + WOLFSSL_STACK* ret = NULL; + WOLFSSL_STACK* last = NULL; -#if (defined(KEEP_PEER_CERT) && defined(SESSION_CERTS)) || \ - (defined(OPENSSL_EXTRA) && defined(SESSION_CERTS)) - /* Decode the X509 DER encoded certificate into a WOLFSSL_X509 object. - * - * x509 WOLFSSL_X509 object to decode into. - * in X509 DER data. - * len Length of the X509 DER data. - * returns the new certificate on success, otherwise NULL. - */ - static int DecodeToX509(WOLFSSL_X509* x509, const byte* in, int len) - { - int ret; - #ifdef WOLFSSL_SMALL_STACK - DecodedCert* cert; - #else - DecodedCert cert[1]; - #endif - if (x509 == NULL || in == NULL || len <= 0) - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wolfSSL_sk_dup"); - #ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, - DYNAMIC_TYPE_DCERT); - if (cert == NULL) - return MEMORY_E; - #endif + while (sk) { + WOLFSSL_STACK* cur = wolfSSL_sk_new_node(sk->heap); - /* Create a DecodedCert object and copy fields into WOLFSSL_X509 object. - */ - InitDecodedCert(cert, (byte*)in, len, NULL); - if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL)) == 0) { - /* Check if x509 was not previously initialized by wolfSSL_X509_new() */ - if (x509->dynamicMemory != TRUE) - InitX509(x509, 0, NULL); - ret = CopyDecodedToX509(x509, cert); + if (!cur) { + WOLFSSL_MSG("wolfSSL_sk_new_node error"); + goto error; } - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - - return ret; - } -#endif /* (KEEP_PEER_CERT & SESSION_CERTS) || (OPENSSL_EXTRA & SESSION_CERTS) */ - -#ifdef KEEP_PEER_CERT - WOLFSSL_ABI - WOLFSSL_X509* wolfSSL_get_peer_certificate(WOLFSSL* ssl) - { - WOLFSSL_X509* ret = NULL; - WOLFSSL_ENTER("wolfSSL_get_peer_certificate"); - if (ssl != NULL) { - if (ssl->peerCert.issuer.sz) - ret = wolfSSL_X509_dup(&ssl->peerCert); -#ifdef SESSION_CERTS - else if (ssl->session->chain.count > 0) { - if (DecodeToX509(&ssl->peerCert, - ssl->session->chain.certs[0].buffer, - ssl->session->chain.certs[0].length) == 0) { - ret = wolfSSL_X509_dup(&ssl->peerCert); - } - } -#endif + if (!ret) { + /* Set first node */ + ret = cur; } - WOLFSSL_LEAVE("wolfSSL_get_peer_certificate", ret != NULL); - return ret; - } - -#endif /* KEEP_PEER_CERT */ -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) -/* Return stack of peer certs. - * Caller does not need to free return. The stack is Free'd when WOLFSSL* ssl is. - */ -WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_peer_cert_chain"); + if (last) { + last->next = cur; + } - if (ssl == NULL) - return NULL; + XMEMCPY(cur, sk, sizeof(WOLFSSL_STACK)); - /* Try to populate if NULL or empty */ - if (ssl->peerCertChain == NULL || - wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) - wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl); - return ssl->peerCertChain; -} + /* We will allocate new memory for this */ + XMEMSET(&cur->data, 0, sizeof(cur->data)); + cur->next = NULL; -#ifndef WOLFSSL_QT -static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, - WOLFSSL_X509 *x); -/** - * Recursively push the issuer CA chain onto the stack - * @param cm The cert manager that is queried for the issuer - * @param x This cert's issuer will be queried in cm - * @param sk The issuer is pushed onto this stack - * @return WOLFSSL_SUCCESS on success - * WOLFSSL_FAILURE on no issuer found - * WOLFSSL_FATAL_ERROR on a fatal error - */ -static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm, - WOLFSSL_X509 *x, WOLFSSL_STACK* sk) -{ - WOLFSSL_X509* issuer[MAX_CHAIN_DEPTH]; - int i; - int push = 1; - int ret = WOLFSSL_SUCCESS; - - for (i = 0; i < MAX_CHAIN_DEPTH; i++) { - if (x509GetIssuerFromCM(&issuer[i], cm, x) - != WOLFSSL_SUCCESS) - break; - x = issuer[i]; - } - if (i == 0) /* No further chain found */ - return WOLFSSL_FAILURE; - i--; - for (; i >= 0; i--) { - if (push) { - if (wolfSSL_sk_X509_push(sk, issuer[i]) != WOLFSSL_SUCCESS) { - wolfSSL_X509_free(issuer[i]); - ret = WOLFSSL_FATAL_ERROR; - push = 0; /* Free the rest of the unpushed certs */ - } - } - else { - wolfSSL_X509_free(issuer[i]); + switch (sk->type) { + case STACK_TYPE_X509: + if (!sk->data.x509) + break; + cur->data.x509 = wolfSSL_X509_dup(sk->data.x509); + if (!cur->data.x509) { + WOLFSSL_MSG("wolfSSL_X509_dup error"); + goto error; + } + break; + case STACK_TYPE_CIPHER: + wolfSSL_CIPHER_copy(&sk->data.cipher, &cur->data.cipher); + break; + case STACK_TYPE_GEN_NAME: + if (!sk->data.gn) + break; + cur->data.gn = wolfSSL_GENERAL_NAME_dup(sk->data.gn); + if (!cur->data.gn) { + WOLFSSL_MSG("wolfSSL_GENERAL_NAME_new error"); + goto error; + } + break; + case STACK_TYPE_OBJ: + if (!sk->data.obj) + break; + cur->data.obj = wolfSSL_ASN1_OBJECT_dup(sk->data.obj); + if (!cur->data.obj) { + WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_dup error"); + goto error; + } + break; + case STACK_TYPE_BIO: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + WOLFSSL_MSG("Unsupported stack type"); + goto error; } + + sk = sk->next; + last = cur; } return ret; + +error: + if (ret) { + wolfSSL_sk_GENERAL_NAME_free(ret); + } + return NULL; } -#endif /* !WOLFSSL_QT */ -/* Builds up and creates a stack of peer certificates for ssl->peerCertChain - based off of the ssl session chain. Attempts to place CA certificates - at the bottom of the stack. Returns stack of WOLFSSL_X509 certs or - NULL on failure */ -WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) + +WOLFSSL_STACK* wolfSSL_shallow_sk_dup(WOLFSSL_STACK* sk) { - WOLFSSL_STACK* sk; - WOLFSSL_X509* x509; - int i = 0; - int ret; - WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain"); - if ((ssl == NULL) || (ssl->session->chain.count == 0)) - return NULL; + WOLFSSL_STACK* ret = NULL; + WOLFSSL_STACK** prev = &ret; - sk = wolfSSL_sk_X509_new_null(); - i = ssl->session->chain.count-1; - for (; i >= 0; i--) { - x509 = wolfSSL_X509_new_ex(ssl->heap); - if (x509 == NULL) { - WOLFSSL_MSG("Error Creating X509"); - wolfSSL_sk_X509_pop_free(sk, NULL); - return NULL; - } - ret = DecodeToX509(x509, ssl->session->chain.certs[i].buffer, - ssl->session->chain.certs[i].length); -#if !defined(WOLFSSL_QT) - if (ret == 0 && i == ssl->session->chain.count-1) { - /* On the last element in the chain try to add the CA chain - * first if we have one for this cert */ - SSL_CM_WARNING(ssl); - if (PushCAx509Chain(SSL_CM(ssl), x509, sk) - == WOLFSSL_FATAL_ERROR) { - ret = WOLFSSL_FATAL_ERROR; - } - } -#endif + WOLFSSL_ENTER("wolfSSL_shallow_sk_dup"); - if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error decoding cert"); - wolfSSL_X509_free(x509); - wolfSSL_sk_X509_pop_free(sk, NULL); - return NULL; + for (; sk != NULL; sk = sk->next) { + WOLFSSL_STACK* cur = wolfSSL_sk_new_node(sk->heap); + + if (!cur) { + WOLFSSL_MSG("wolfSSL_sk_new_node error"); + goto error; } - } - if (sk == NULL) { - WOLFSSL_MSG("Null session chain"); + XMEMCPY(cur, sk, sizeof(WOLFSSL_STACK)); + cur->next = NULL; + + *prev = cur; + prev = &cur->next; } -#if defined(OPENSSL_ALL) - else if (ssl->options.side == WOLFSSL_SERVER_END) { - /* to be compliant with openssl - first element is kept as peer cert on server side.*/ - wolfSSL_sk_X509_pop(sk); + return ret; + +error: + if (ret) { + wolfSSL_sk_free(ret); } -#endif - if (ssl->peerCertChain != NULL) - wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL); - /* This is Free'd when ssl is Free'd */ - ssl->peerCertChain = sk; - return sk; + return NULL; } -#endif /* SESSION_CERTS && OPENSSL_EXTRA */ - -#ifndef NO_CERTS -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -/* create a generic wolfSSL stack node - * returns a new WOLFSSL_STACK structure on success */ -WOLFSSL_STACK* wolfSSL_sk_new_node(void* heap) +/* Free the just the stack structure */ +void wolfSSL_sk_free(WOLFSSL_STACK* sk) { - WOLFSSL_STACK* sk; - WOLFSSL_ENTER("wolfSSL_sk_new_node"); + WOLFSSL_ENTER("wolfSSL_sk_free"); - sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), heap, - DYNAMIC_TYPE_OPENSSL); - if (sk != NULL) { - XMEMSET(sk, 0, sizeof(*sk)); - sk->heap = heap; + while (sk != NULL) { + WOLFSSL_STACK* next = sk->next; + XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); + sk = next; } - - return sk; } -/* free's node but does not free internal data such as in->data.x509 */ -void wolfSSL_sk_free_node(WOLFSSL_STACK* in) +/* Frees each node in the stack and frees the stack. + */ +void wolfSSL_sk_GENERIC_pop_free(WOLFSSL_STACK* sk, + void (*f) (void*)) { - if (in != NULL) { - XFREE(in, in->heap, DYNAMIC_TYPE_OPENSSL); - } + WOLFSSL_ENTER("wolfSSL_sk_GENERIC_pop_free"); + wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f); } -/* pushes node "in" onto "stack" and returns pointer to the new stack on success - * also handles internal "num" for number of nodes on stack - * return WOLFSSL_SUCCESS on success - */ -int wolfSSL_sk_push_node(WOLFSSL_STACK** stack, WOLFSSL_STACK* in) +/* return 1 on success 0 on fail */ +int wolfSSL_sk_GENERIC_push(WOLFSSL_STACK* sk, void* generic) { - if (stack == NULL || in == NULL) { - return WOLFSSL_FAILURE; - } - - if (*stack == NULL) { - in->num = 1; - *stack = in; - return WOLFSSL_SUCCESS; - } + WOLFSSL_ENTER("wolfSSL_sk_GENERIC_push"); - in->num = (*stack)->num + 1; - in->next = *stack; - *stack = in; - return WOLFSSL_SUCCESS; + return wolfSSL_sk_push(sk, generic); } - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) -static WC_INLINE int compare_WOLFSSL_CIPHER( - WOLFSSL_CIPHER *a, - WOLFSSL_CIPHER *b) +void wolfSSL_sk_GENERIC_free(WOLFSSL_STACK* sk) { - if ((a->cipherSuite0 == b->cipherSuite0) && - (a->cipherSuite == b->cipherSuite) && - (a->ssl == b->ssl) && - (XMEMCMP(a->description, b->description, sizeof a->description) == 0) && - (a->offset == b->offset) && - (a->in_stack == b->in_stack) && - (a->bits == b->bits)) - return 0; - else - return -1; + wolfSSL_sk_free(sk); } -#endif /* OPENSSL_ALL || WOLFSSL_QT */ - -/* return 1 on success 0 on fail */ -int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) +/* Pop off data from the stack. Checks that the type matches the stack type. + * + * @param [in, out] sk Stack of objects. + * @param [in] type Type of stack. + * @return Object on success. + * @return NULL when stack is NULL or no nodes left in stack. + */ +void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, WOLF_STACK_TYPE type) { WOLFSSL_STACK* node; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - WOLFSSL_CIPHER ciph; -#endif - WOLFSSL_ENTER("wolfSSL_sk_push"); + void* data = NULL; - if (!sk) { - return WOLFSSL_FAILURE; - } + /* Check we have a stack passed in of the right type. */ + if ((sk != NULL) && (sk->type == type)) { + /* Get the next node to become the new first node. */ + node = sk->next; + /* Get the ASN.1 OBJECT_ID object in the first node. */ + data = sk->data.generic; - /* Check if empty data */ - switch (sk->type) { - case STACK_TYPE_CIPHER: -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - /* check if entire struct is zero */ - XMEMSET(&ciph, 0, sizeof(WOLFSSL_CIPHER)); - if (compare_WOLFSSL_CIPHER(&sk->data.cipher, &ciph) == 0) { - sk->data.cipher = *(WOLFSSL_CIPHER*)data; - sk->num = 1; - if (sk->hash_fn) { - sk->hash = sk->hash_fn(&sk->data.cipher); - } - return WOLFSSL_SUCCESS; - } - break; -#endif - case STACK_TYPE_X509: - case STACK_TYPE_GEN_NAME: - case STACK_TYPE_BIO: - case STACK_TYPE_OBJ: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - /* All other types are pointers */ - if (!sk->data.generic) { - sk->data.generic = (void*)data; - sk->num = 1; -#ifdef OPENSSL_ALL - if (sk->hash_fn) { - sk->hash = sk->hash_fn(sk->data.generic); - } -#endif - return WOLFSSL_SUCCESS; - } - break; - } + /* Check whether there is a next node. */ + if (node != NULL) { + /* Move content out of next node into current node. */ + sk->data.obj = node->data.obj; + sk->next = node->next; + /* Dispose of node. */ + XFREE(node, NULL, DYNAMIC_TYPE_ASN1); + } + else { + /* No more nodes - clear out data. */ + sk->data.obj = NULL; + } - /* stack already has value(s) create a new node and add more */ - node = wolfSSL_sk_new_node(sk->heap); - if (!node) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; + /* Decrement count as long as we thought we had nodes. */ + if (sk->num > 0) { + sk->num -= 1; + } } - /* push new x509 onto head of stack */ - node->next = sk->next; - node->type = sk->type; - sk->next = node; - sk->num += 1; + return data; +} -#ifdef OPENSSL_ALL - node->hash_fn = sk->hash_fn; - node->hash = sk->hash; - sk->hash = 0; +/* Free all nodes in a stack including the pushed objects */ +void wolfSSL_sk_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk, + wolfSSL_sk_freefunc func) +{ + WOLFSSL_ENTER("wolfSSL_sk_pop_free"); + + if (sk == NULL) { + /* pop_free can be called with NULL, do not print bad argument */ + return; + } + #if defined(WOLFSSL_QT) + /* In Qt v15.5, it calls OPENSSL_sk_free(xxx, OPENSSL_sk_free). + * By using OPENSSL_sk_free for free causes access violation. + * Therefore, switching free func to wolfSSL_ACCESS_DESCRIPTION_free + * is needed even the func isn't NULL. + */ + if (sk->type == STACK_TYPE_ACCESS_DESCRIPTION) { + func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free; + } + #endif + if (func == NULL) { + switch(sk->type) { + case STACK_TYPE_ACCESS_DESCRIPTION: + #if defined(OPENSSL_ALL) + func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free; + #endif + break; + case STACK_TYPE_X509: + func = (wolfSSL_sk_freefunc)wolfSSL_X509_free; + break; + case STACK_TYPE_X509_OBJ: + #ifdef OPENSSL_ALL + func = (wolfSSL_sk_freefunc)wolfSSL_X509_OBJECT_free; + #endif + break; + case STACK_TYPE_OBJ: + func = (wolfSSL_sk_freefunc)wolfSSL_ASN1_OBJECT_free; + break; + case STACK_TYPE_DIST_POINT: + #ifdef OPENSSL_EXTRA + func = (wolfSSL_sk_freefunc)wolfSSL_DIST_POINT_free; + #endif + break; + case STACK_TYPE_GEN_NAME: + func = (wolfSSL_sk_freefunc)wolfSSL_GENERAL_NAME_free; + break; + case STACK_TYPE_STRING: + #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ + defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) + func = (wolfSSL_sk_freefunc)wolfSSL_WOLFSSL_STRING_free; + #endif + break; + case STACK_TYPE_X509_NAME: + #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ + && !defined(WOLFCRYPT_ONLY) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_free; + #endif + break; + case STACK_TYPE_X509_NAME_ENTRY: + #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ + && !defined(WOLFCRYPT_ONLY) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_ENTRY_free; + #endif + break; + case STACK_TYPE_X509_EXT: + #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_EXTENSION_free; + #endif + break; + case STACK_TYPE_X509_REQ_ATTR: + #if defined(OPENSSL_ALL) && \ + (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_REQ)) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_ATTRIBUTE_free; + #endif + break; + case STACK_TYPE_CONF_VALUE: + #if defined(OPENSSL_ALL) + func = (wolfSSL_sk_freefunc)wolfSSL_X509V3_conf_free; + #endif + break; + case STACK_TYPE_X509_INFO: + #if defined(OPENSSL_ALL) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_INFO_free; + #endif + break; + case STACK_TYPE_BIO: +#if !defined(NO_BIO) && defined(OPENSSL_EXTRA) + func = (wolfSSL_sk_freefunc)wolfSSL_BIO_vfree; #endif - switch (sk->type) { - case STACK_TYPE_CIPHER: -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - node->data.cipher = sk->data.cipher; - sk->data.cipher = *(WOLFSSL_CIPHER*)data; - if (sk->hash_fn) { - sk->hash = sk->hash_fn(&sk->data.cipher); - } - break; + break; + case STACK_TYPE_BY_DIR_entry: +#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) + func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_entry_free; #endif - case STACK_TYPE_X509: - case STACK_TYPE_GEN_NAME: - case STACK_TYPE_BIO: - case STACK_TYPE_OBJ: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - /* All other types are pointers */ - node->data.generic = sk->data.generic; - sk->data.generic = (void*)data; -#ifdef OPENSSL_ALL - if (sk->hash_fn) { - sk->hash = sk->hash_fn(sk->data.generic); - } + break; + case STACK_TYPE_BY_DIR_hash: +#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) + func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_HASH_free; #endif - break; + break; + case STACK_TYPE_X509_CRL: +#if defined(HAVE_CRL) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) + func = (wolfSSL_sk_freefunc)wolfSSL_X509_CRL_free; +#endif + break; + case STACK_TYPE_CIPHER: + case STACK_TYPE_NULL: + default: + break; + } } - return WOLFSSL_SUCCESS; -} - -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ + while (sk != NULL) { + WOLFSSL_STACK* next = sk->next; -#ifdef OPENSSL_EXTRA + if (func != NULL) { + if (sk->type != STACK_TYPE_CIPHER) + func(sk->data.generic); + } + XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); + sk = next; + } +} -/* returns the node at index "idx", NULL if not found */ -WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx) -{ - int i; - WOLFSSL_STACK* ret = NULL; - WOLFSSL_STACK* current; +/* Creates a new stack of the requested type. + * + * @param [in] type Type of stack. + * @return Empty stack on success. + * @return NULL when dynamic memory allocation fails. + */ +WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type) +{ + WOLFSSL_STACK* sk; - current = sk; - for (i = 0; i <= idx && current != NULL; i++) { - if (i == idx) { - ret = current; - break; - } - current = current->next; + /* Allocate a new stack - first node. */ + sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, + DYNAMIC_TYPE_OPENSSL); + if (sk == NULL) { + WOLFSSL_MSG("WOLFSSL_STACK memory error"); } - return ret; + else { + /* Clear node and set type. */ + XMEMSET(sk, 0, sizeof(WOLFSSL_STACK)); + sk->type = type; + } + + return sk; +} + +/* Creates and returns a new null stack. */ +WOLFSSL_STACK* wolfSSL_sk_new_null(void) +{ + WOLFSSL_ENTER("wolfSSL_sk_new_null"); + + return wolfssl_sk_new_type(STACK_TYPE_NULL); } +int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk) +{ + if (sk == NULL) + return 0; + return (int)sk->num; +} -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #ifdef OPENSSL_EXTRA -#if defined(OPENSSL_ALL) - -void *wolfSSL_lh_retrieve(WOLFSSL_STACK *sk, void *data) +#if defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM) +int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) { - unsigned long hash; + int ret = WOLFSSL_FATAL_ERROR; - WOLFSSL_ENTER("wolfSSL_lh_retrieve"); + WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file"); + if (ssl != NULL && fname != NULL) + { + #ifdef WOLFSSL_SMALL_STACK + byte staticBuffer[1]; /* force heap usage */ + #else + byte staticBuffer[FILE_BUFFER_SIZE]; + #endif + byte* myBuffer = staticBuffer; + int dynamic = 0; + XFILE file; + long sz = 0; + WOLFSSL_CTX* ctx = ssl->ctx; + WOLFSSL_X509* peer_cert = &ssl->peerCert; + DerBuffer* fileDer = NULL; - if (!sk || !data) { - WOLFSSL_MSG("Bad parameters"); - return NULL; - } + file = XFOPEN(fname, "rb"); + if (file == XBADFILE) + return WOLFSSL_BAD_FILE; - if (!sk->hash_fn) { - WOLFSSL_MSG("No hash function defined"); - return NULL; - } + if (XFSEEK(file, 0, XSEEK_END) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } + sz = XFTELL(file); + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } - hash = sk->hash_fn(data); + if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) { + WOLFSSL_MSG("cmp_peer_cert_to_file size error"); + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } - while (sk) { - /* Calc hash if not done so yet */ - if (!sk->hash) { - switch (sk->type) { - case STACK_TYPE_CIPHER: - sk->hash = sk->hash_fn(&sk->data.cipher); - break; - case STACK_TYPE_X509: - case STACK_TYPE_GEN_NAME: - case STACK_TYPE_BIO: - case STACK_TYPE_OBJ: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - sk->hash = sk->hash_fn(sk->data.generic); - break; - } + if (sz > (long)sizeof(staticBuffer)) { + WOLFSSL_MSG("Getting dynamic buffer"); + myBuffer = (byte*)XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE); + dynamic = 1; } - if (sk->hash == hash) { - switch (sk->type) { - case STACK_TYPE_CIPHER: - return &sk->data.cipher; - case STACK_TYPE_X509: - case STACK_TYPE_GEN_NAME: - case STACK_TYPE_BIO: - case STACK_TYPE_OBJ: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - return sk->data.generic; - } + + if ((myBuffer != NULL) && + (sz > 0) && + (XFREAD(myBuffer, 1, (size_t)sz, file) == (size_t)sz) && + (PemToDer(myBuffer, (long)sz, CERT_TYPE, + &fileDer, ctx->heap, NULL, NULL) == 0) && + (fileDer->length != 0) && + (fileDer->length == peer_cert->derCert->length) && + (XMEMCMP(peer_cert->derCert->buffer, fileDer->buffer, + fileDer->length) == 0)) + { + ret = 0; } - sk = sk->next; - } - return NULL; -} + FreeDer(&fileDer); -#endif /* OPENSSL_ALL */ + if (dynamic) + XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE); + XFCLOSE(file); + } + + return ret; +} +#endif #endif /* OPENSSL_EXTRA */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +const WOLFSSL_ObjectInfo wolfssl_object_info[] = { +#ifndef NO_CERTS + /* oidCertExtType */ + { NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints", + "X509v3 Basic Constraints"}, + { NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName", + "X509v3 Subject Alternative Name"}, + { NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, + "crlDistributionPoints", "X509v3 CRL Distribution Points"}, + { NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess", + "Authority Information Access"}, + { NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType, + "authorityKeyIdentifier", "X509v3 Authority Key Identifier"}, + { NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType, + "subjectKeyIdentifier", "X509v3 Subject Key Identifier"}, + { NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage", + "X509v3 Key Usage"}, + { NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType, + "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"}, + { NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType, + "extendedKeyUsage", "X509v3 Extended Key Usage"}, + { NID_name_constraints, NAME_CONS_OID, oidCertExtType, + "nameConstraints", "X509v3 Name Constraints"}, + { NID_certificate_policies, CERT_POLICY_OID, oidCertExtType, + "certificatePolicies", "X509v3 Certificate Policies"}, -/* OPENSSL_EXTRA is needed for wolfSSL_X509_d21 function - KEEP_OUR_CERT is to insure ability for returning ssl certificate */ -#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ - defined(KEEP_OUR_CERT) -WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl) -{ - if (ssl == NULL) { - return NULL; - } + /* oidCertAuthInfoType */ + { NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP", + "OCSP"}, + { NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType, + "caIssuers", "CA Issuers"}, - if (ssl->buffers.weOwnCert) { - if (ssl->ourCert == NULL) { - if (ssl->buffers.certificate == NULL) { - WOLFSSL_MSG("Certificate buffer not set!"); - return NULL; - } - #ifndef WOLFSSL_X509_STORE_CERTS - ssl->ourCert = wolfSSL_X509_d2i_ex(NULL, - ssl->buffers.certificate->buffer, - ssl->buffers.certificate->length, - ssl->heap); - #endif - } - return ssl->ourCert; - } - else { /* if cert not owned get parent ctx cert or return null */ - if (ssl->ctx) { - if (ssl->ctx->ourCert == NULL) { - if (ssl->ctx->certificate == NULL) { - WOLFSSL_MSG("Ctx Certificate buffer not set!"); - return NULL; - } - #ifndef WOLFSSL_X509_STORE_CERTS - ssl->ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, - ssl->ctx->certificate->buffer, - ssl->ctx->certificate->length, - ssl->heap); - #endif - ssl->ctx->ownOurCert = 1; - } - return ssl->ctx->ourCert; - } - } + /* oidCertPolicyType */ + { NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy", + "X509v3 Any Policy"}, - return NULL; -} + /* oidCertAltNameType */ + { NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""}, -WOLFSSL_X509* wolfSSL_CTX_get0_certificate(WOLFSSL_CTX* ctx) -{ - if (ctx) { - if (ctx->ourCert == NULL) { - if (ctx->certificate == NULL) { - WOLFSSL_MSG("Ctx Certificate buffer not set!"); - return NULL; - } - #ifndef WOLFSSL_X509_STORE_CERTS - ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, - ctx->certificate->buffer, - ctx->certificate->length, ctx->heap); - #endif - ctx->ownOurCert = 1; - } - return ctx->ourCert; - } - return NULL; -} -#endif /* OPENSSL_EXTRA && KEEP_OUR_CERT */ -#endif /* NO_CERTS */ + /* oidCertKeyUseType */ + { NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType, + "anyExtendedKeyUsage", "Any Extended Key Usage"}, + { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType, + "serverAuth", "TLS Web Server Authentication"}, + { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType, + "clientAuth", "TLS Web Client Authentication"}, + { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType, + "OCSPSigning", "OCSP Signing"}, -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -void wolfSSL_set_connect_state(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_set_connect_state"); - if (ssl == NULL) { - WOLFSSL_MSG("WOLFSSL struct pointer passed in was null"); - return; - } + /* oidCertNameType */ + { NID_commonName, NID_commonName, oidCertNameType, "CN", "commonName"}, +#if !defined(WOLFSSL_CERT_REQ) + { NID_surname, NID_surname, oidCertNameType, "SN", "surname"}, +#endif + { NID_serialNumber, NID_serialNumber, oidCertNameType, "serialNumber", + "serialNumber"}, + { NID_userId, NID_userId, oidCertNameType, "UID", "userid"}, + { NID_countryName, NID_countryName, oidCertNameType, "C", "countryName"}, + { NID_localityName, NID_localityName, oidCertNameType, "L", "localityName"}, + { NID_stateOrProvinceName, NID_stateOrProvinceName, oidCertNameType, "ST", + "stateOrProvinceName"}, + { NID_streetAddress, NID_streetAddress, oidCertNameType, "street", + "streetAddress"}, + { NID_organizationName, NID_organizationName, oidCertNameType, "O", + "organizationName"}, + { NID_organizationalUnitName, NID_organizationalUnitName, oidCertNameType, + "OU", "organizationalUnitName"}, + { NID_emailAddress, NID_emailAddress, oidCertNameType, "emailAddress", + "emailAddress"}, + { NID_domainComponent, NID_domainComponent, oidCertNameType, "DC", + "domainComponent"}, + { NID_favouriteDrink, NID_favouriteDrink, oidCertNameType, "favouriteDrink", + "favouriteDrink"}, + { NID_businessCategory, NID_businessCategory, oidCertNameType, + "businessCategory", "businessCategory"}, + { NID_jurisdictionCountryName, NID_jurisdictionCountryName, oidCertNameType, + "jurisdictionC", "jurisdictionCountryName"}, + { NID_jurisdictionStateOrProvinceName, NID_jurisdictionStateOrProvinceName, + oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"}, + { NID_postalCode, NID_postalCode, oidCertNameType, "postalCode", + "postalCode"}, + { NID_userId, NID_userId, oidCertNameType, "UID", "userId"}, + +#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) + { NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, + oidCsrAttrType, "challengePassword", "challengePassword"}, + { NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID, + oidCsrAttrType, "contentType", "contentType" }, + { NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID, + oidCsrAttrType, "unstructuredName", "unstructuredName" }, + { NID_name, NAME_OID, oidCsrAttrType, "name", "name" }, + { NID_surname, SURNAME_OID, + oidCsrAttrType, "surname", "surname" }, + { NID_givenName, GIVEN_NAME_OID, + oidCsrAttrType, "givenName", "givenName" }, + { NID_initials, INITIALS_OID, + oidCsrAttrType, "initials", "initials" }, + { NID_dnQualifier, DNQUALIFIER_OID, + oidCsrAttrType, "dnQualifer", "dnQualifier" }, +#endif +#endif +#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */ + /* oidHashType */ + #ifdef WOLFSSL_MD2 + { NID_md2, MD2h, oidHashType, "MD2", "md2"}, + #endif + #ifdef WOLFSSL_MD5 + { NID_md5, MD5h, oidHashType, "MD5", "md5"}, + #endif + #ifndef NO_SHA + { NID_sha1, SHAh, oidHashType, "SHA1", "sha1"}, + #endif + #ifdef WOLFSSL_SHA224 + { NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"}, + #endif + #ifndef NO_SHA256 + { NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"}, + #endif + #ifdef WOLFSSL_SHA384 + { NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"}, + #endif + #ifdef WOLFSSL_SHA512 + { NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"}, + #endif + #ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + { NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"}, + #endif + #ifndef WOLFSSL_NOSHA3_256 + { NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"}, + #endif + #ifndef WOLFSSL_NOSHA3_384 + { NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"}, + #endif + #ifndef WOLFSSL_NOSHA3_512 + { NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"}, + #endif + #endif /* WOLFSSL_SHA3 */ + #ifdef WOLFSSL_SM3 + { NID_sm3, SM3h, oidHashType, "SM3", "sm3"}, + #endif + /* oidSigType */ + #ifndef NO_DSA + #ifndef NO_SHA + { NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"}, + { NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256", + "dsa_with_SHA256"}, + #endif + #endif /* NO_DSA */ + #ifndef NO_RSA + #ifdef WOLFSSL_MD2 + { NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2", + "md2WithRSAEncryption"}, + #endif + #ifndef NO_MD5 + { NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5", + "md5WithRSAEncryption"}, + #endif + #ifndef NO_SHA + { NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1", + "sha1WithRSAEncryption"}, + #endif + #ifdef WOLFSSL_SHA224 + { NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224", + "sha224WithRSAEncryption"}, + #endif + #ifndef NO_SHA256 + { NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256", + "sha256WithRSAEncryption"}, + #endif + #ifdef WOLFSSL_SHA384 + { NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384", + "sha384WithRSAEncryption"}, + #endif + #ifdef WOLFSSL_SHA512 + { NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512", + "sha512WithRSAEncryption"}, + #endif + #ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + { NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224", + "sha3-224WithRSAEncryption"}, + #endif + #ifndef WOLFSSL_NOSHA3_256 + { NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256", + "sha3-256WithRSAEncryption"}, + #endif + #ifndef WOLFSSL_NOSHA3_384 + { NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384", + "sha3-384WithRSAEncryption"}, + #endif + #ifndef WOLFSSL_NOSHA3_512 + { NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512", + "sha3-512WithRSAEncryption"}, + #endif + #endif + #ifdef WC_RSA_PSS + { NID_rsassaPss, CTC_RSASSAPSS, oidSigType, "RSASSA-PSS", "rsassaPss" }, + #endif + #endif /* NO_RSA */ + #ifdef HAVE_ECC + #ifndef NO_SHA + { NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1", + "shaWithECDSA"}, + #endif + #ifdef WOLFSSL_SHA224 + { NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType, + "ecdsa-with-SHA224","sha224WithECDSA"}, + #endif + #ifndef NO_SHA256 + { NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType, + "ecdsa-with-SHA256","sha256WithECDSA"}, + #endif + #ifdef WOLFSSL_SHA384 + { NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType, + "ecdsa-with-SHA384","sha384WithECDSA"}, + #endif + #ifdef WOLFSSL_SHA512 + { NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType, + "ecdsa-with-SHA512","sha512WithECDSA"}, + #endif + #ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + { NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType, + "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"}, + #endif + #ifndef WOLFSSL_NOSHA3_256 + { NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType, + "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"}, + #endif + #ifndef WOLFSSL_NOSHA3_384 + { NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType, + "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"}, + #endif + #ifndef WOLFSSL_NOSHA3_512 + { NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType, + "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"}, + #endif + #endif + #endif /* HAVE_ECC */ + /* oidKeyType */ + #ifndef NO_DSA + { NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"}, + #endif /* NO_DSA */ + #ifndef NO_RSA + { NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption", + "rsaEncryption"}, + #ifdef WC_RSA_PSS + { NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"}, + #endif + #endif /* NO_RSA */ + #ifdef HAVE_ECC + { NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey", + "id-ecPublicKey"}, + #endif /* HAVE_ECC */ #ifndef NO_DH - /* client creates its own DH parameters on handshake */ - if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) { - XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - } - ssl->buffers.serverDH_P.buffer = NULL; - if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) { - XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - } - ssl->buffers.serverDH_G.buffer = NULL; + { NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement", + "dhKeyAgreement"}, + #endif + #ifdef HAVE_ED448 + { NID_ED448, ED448k, oidKeyType, "ED448", "ED448"}, + #endif + #ifdef HAVE_ED25519 + { NID_ED25519, ED25519k, oidKeyType, "ED25519", "ED25519"}, #endif + #ifdef HAVE_FALCON + { CTC_FALCON_LEVEL1, FALCON_LEVEL1k, oidKeyType, "Falcon Level 1", + "Falcon Level 1"}, + { CTC_FALCON_LEVEL5, FALCON_LEVEL5k, oidKeyType, "Falcon Level 5", + "Falcon Level 5"}, + #endif /* HAVE_FALCON */ + #ifdef HAVE_DILITHIUM + { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k, oidKeyType, + "Dilithium Level 2", "Dilithium Level 2"}, + { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k, oidKeyType, + "Dilithium Level 3", "Dilithium Level 3"}, + { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k, oidKeyType, + "Dilithium Level 5", "Dilithium Level 5"}, + #endif /* HAVE_DILITHIUM */ - if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error initializing client side"); - } -} -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ + /* oidCurveType */ + #ifdef HAVE_ECC + { NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", + "prime192v1"}, + { NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", + "prime192v2"}, + { NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", + "prime192v3"}, + + { NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", + "prime239v1"}, + { NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", + "prime239v2"}, + { NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", + "prime239v3"}, + + { NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", + "prime256v1"}, + + { NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", + "secp112r1"}, + { NID_secp112r2, ECC_SECP112R2_OID, oidCurveType, "secp112r2", + "secp112r2"}, + + { NID_secp128r1, ECC_SECP128R1_OID, oidCurveType, "secp128r1", + "secp128r1"}, + { NID_secp128r2, ECC_SECP128R2_OID, oidCurveType, "secp128r2", + "secp128r2"}, + + { NID_secp160r1, ECC_SECP160R1_OID, oidCurveType, "secp160r1", + "secp160r1"}, + { NID_secp160r2, ECC_SECP160R2_OID, oidCurveType, "secp160r2", + "secp160r2"}, + + { NID_secp224r1, ECC_SECP224R1_OID, oidCurveType, "secp224r1", + "secp224r1"}, + { NID_secp384r1, ECC_SECP384R1_OID, oidCurveType, "secp384r1", + "secp384r1"}, + { NID_secp521r1, ECC_SECP521R1_OID, oidCurveType, "secp521r1", + "secp521r1"}, + + { NID_secp160k1, ECC_SECP160K1_OID, oidCurveType, "secp160k1", + "secp160k1"}, + { NID_secp192k1, ECC_SECP192K1_OID, oidCurveType, "secp192k1", + "secp192k1"}, + { NID_secp224k1, ECC_SECP224K1_OID, oidCurveType, "secp224k1", + "secp224k1"}, + { NID_secp256k1, ECC_SECP256K1_OID, oidCurveType, "secp256k1", + "secp256k1"}, + + { NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID, oidCurveType, + "brainpoolP160r1", "brainpoolP160r1"}, + { NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID, oidCurveType, + "brainpoolP192r1", "brainpoolP192r1"}, + { NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID, oidCurveType, + "brainpoolP224r1", "brainpoolP224r1"}, + { NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID, oidCurveType, + "brainpoolP256r1", "brainpoolP256r1"}, + { NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID, oidCurveType, + "brainpoolP320r1", "brainpoolP320r1"}, + { NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID, oidCurveType, + "brainpoolP384r1", "brainpoolP384r1"}, + { NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID, oidCurveType, + "brainpoolP512r1", "brainpoolP512r1"}, + #ifdef WOLFSSL_SM2 + { NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"}, + #endif + #endif /* HAVE_ECC */ -int wolfSSL_get_shutdown(const WOLFSSL* ssl) -{ - int isShutdown = 0; + /* oidBlkType */ + #ifdef WOLFSSL_AES_128 + { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"}, + #endif + #ifdef WOLFSSL_AES_192 + { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"}, + #endif + #ifdef WOLFSSL_AES_256 + { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"}, + #endif + #ifndef NO_DES3 + { NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"}, + { NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"}, + #endif /* !NO_DES3 */ + #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + { NID_chacha20_poly1305, NID_chacha20_poly1305, oidBlkType, + "ChaCha20-Poly1305", "chacha20-poly1305"}, + #endif - WOLFSSL_ENTER("wolfSSL_get_shutdown"); + /* oidOcspType */ + #ifdef HAVE_OCSP + { NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType, + "basicOCSPResponse", "Basic OCSP Response"}, + { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"}, + #endif /* HAVE_OCSP */ - if (ssl) { -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - if (ssl->options.shutdownDone) { - /* The SSL object was possibly cleared with wolfSSL_clear after - * a successful shutdown. Simulate a response for a full - * bidirectional shutdown. */ - isShutdown = WOLFSSL_SENT_SHUTDOWN | WOLFSSL_RECEIVED_SHUTDOWN; - } - else -#endif - { - /* in OpenSSL, WOLFSSL_SENT_SHUTDOWN = 1, when closeNotifySent * - * WOLFSSL_RECEIVED_SHUTDOWN = 2, from close notify or fatal err */ - if (ssl->options.sentNotify) - isShutdown |= WOLFSSL_SENT_SHUTDOWN; - if (ssl->options.closeNotify||ssl->options.connReset) - isShutdown |= WOLFSSL_RECEIVED_SHUTDOWN; - } - - } - - WOLFSSL_LEAVE("wolfSSL_get_shutdown", isShutdown); - return isShutdown; -} + #ifndef NO_PWDBASED + /* oidKdfType */ + { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"}, + /* oidPBEType */ + { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType, + "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"}, + { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES", + "pbeWithSHA1AndDES-CBC"}, + { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES", + "pbeWithSHA1And3-KeyTripleDES-CBC"}, + #endif -int wolfSSL_session_reused(WOLFSSL* ssl) -{ - int resuming = 0; - WOLFSSL_ENTER("wolfSSL_session_reused"); - if (ssl) { -#ifndef HAVE_SECURE_RENEGOTIATION - resuming = ssl->options.resuming; -#else - resuming = ssl->options.resuming || ssl->options.resumed; -#endif - } - WOLFSSL_LEAVE("wolfSSL_session_reused", resuming); - return resuming; -} + /* oidKeyWrapType */ + #ifdef WOLFSSL_AES_128 + { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap", + "aes128-wrap"}, + #endif + #ifdef WOLFSSL_AES_192 + { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap", + "aes192-wrap"}, + #endif + #ifdef WOLFSSL_AES_256 + { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap", + "aes256-wrap"}, + #endif -/* return a new malloc'd session with default settings on success */ -WOLFSSL_SESSION* wolfSSL_NewSession(void* heap) -{ - WOLFSSL_SESSION* ret = NULL; + #ifndef NO_PKCS7 + #ifndef NO_DH + /* oidCmsKeyAgreeType */ + #ifndef NO_SHA + { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme, + oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme", + "dhSinglePass-stdDH-sha1kdf-scheme"}, + #endif + #ifdef WOLFSSL_SHA224 + { dhSinglePass_stdDH_sha224kdf_scheme, + dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType, + "dhSinglePass-stdDH-sha224kdf-scheme", + "dhSinglePass-stdDH-sha224kdf-scheme"}, + #endif + #ifndef NO_SHA256 + { dhSinglePass_stdDH_sha256kdf_scheme, + dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType, + "dhSinglePass-stdDH-sha256kdf-scheme", + "dhSinglePass-stdDH-sha256kdf-scheme"}, + #endif + #ifdef WOLFSSL_SHA384 + { dhSinglePass_stdDH_sha384kdf_scheme, + dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType, + "dhSinglePass-stdDH-sha384kdf-scheme", + "dhSinglePass-stdDH-sha384kdf-scheme"}, + #endif + #ifdef WOLFSSL_SHA512 + { dhSinglePass_stdDH_sha512kdf_scheme, + dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType, + "dhSinglePass-stdDH-sha512kdf-scheme", + "dhSinglePass-stdDH-sha512kdf-scheme"}, + #endif + #endif + #endif + #if defined(WOLFSSL_APACHE_HTTPD) + /* "1.3.6.1.5.5.7.8.7" */ + { NID_id_on_dnsSRV, NID_id_on_dnsSRV, oidCertNameType, + WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV }, - WOLFSSL_ENTER("wolfSSL_NewSession"); + /* "1.3.6.1.4.1.311.20.2.3" */ + { NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN, + WOLFSSL_LN_MS_UPN }, - ret = (WOLFSSL_SESSION*)XMALLOC(sizeof(WOLFSSL_SESSION), heap, - DYNAMIC_TYPE_SESSION); - if (ret != NULL) { - int err; - XMEMSET(ret, 0, sizeof(WOLFSSL_SESSION)); - wolfSSL_RefInit(&ret->ref, &err); - #ifdef WOLFSSL_REFCNT_ERROR_RETURN - if (err != 0) { - WOLFSSL_MSG("Error setting up session reference mutex"); - XFREE(ret, ret->heap, DYNAMIC_TYPE_SESSION); - return NULL; - } - #else - (void)err; - #endif -#ifndef NO_SESSION_CACHE - ret->cacheRow = INVALID_SESSION_ROW; /* not in cache */ -#endif - ret->type = WOLFSSL_SESSION_TYPE_HEAP; - ret->heap = heap; -#ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("SESSION master secret", ret->masterSecret, SECRET_LEN); - wc_MemZero_Add("SESSION id", ret->sessionID, ID_LEN); -#endif - #ifdef HAVE_SESSION_TICKET - ret->ticket = ret->staticTicket; - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - ret->ticketNonce.data = ret->ticketNonce.dataStatic; - #endif + /* "1.3.6.1.5.5.7.1.24" */ + { NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType, + WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE }, #endif -#ifdef HAVE_EX_DATA - ret->ownExData = 1; - if (crypto_ex_cb_ctx_session != NULL) { - crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session, - &ret->ex_data); - } -#endif - } - return ret; -} +#endif /* OPENSSL_EXTRA */ +}; +#define WOLFSSL_OBJECT_INFO_SZ \ + (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info)) +const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ; +#endif -WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +/* Free the dynamically allocated data. + * + * p Pointer to dynamically allocated memory. + */ +void wolfSSL_OPENSSL_free(void* p) { - return wolfSSL_NewSession(heap); + WOLFSSL_MSG("wolfSSL_OPENSSL_free"); + + XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL); } +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#ifdef OPENSSL_EXTRA -WOLFSSL_SESSION* wolfSSL_SESSION_new(void) +void *wolfSSL_OPENSSL_malloc(size_t a) { - return wolfSSL_SESSION_new_ex(NULL); + return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL); } -/* add one to session reference count - * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */ -int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session) +int wolfSSL_OPENSSL_hexchar2int(unsigned char c) { - int ret; - - session = ClientSessionToSession(session); - - if (session == NULL || session->type != WOLFSSL_SESSION_TYPE_HEAP) - return WOLFSSL_FAILURE; - - wolfSSL_RefInc(&session->ref, &ret); -#ifdef WOLFSSL_REFCNT_ERROR_RETURN - if (ret != 0) { - WOLFSSL_MSG("Failed to lock session mutex"); - return WOLFSSL_FAILURE; - } -#else - (void)ret; -#endif - - return WOLFSSL_SUCCESS; + /* 'char' is unsigned on some platforms. */ + return (int)(signed char)HexCharToByte((char)c); } -/** - * Deep copy the contents from input to output. - * @param input The source of the copy. - * @param output The destination of the copy. - * @param avoidSysCalls If true, then system calls will be avoided or an error - * will be returned if it is not possible to proceed - * without a system call. This is useful for fetching - * sessions from cache. When a cache row is locked, we - * don't want to block other threads with long running - * system calls. - * @param ticketNonceBuf If not null and @avoidSysCalls is true, the copy of the - * ticketNonce will happen in this pre allocated buffer - * @param ticketNonceLen @ticketNonceBuf len as input, used length on output - * @param ticketNonceUsed if @ticketNonceBuf was used to copy the ticket noncet - * @return WOLFSSL_SUCCESS on success - * WOLFSSL_FAILURE on failure - */ -static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, - WOLFSSL_SESSION* output, int avoidSysCalls, byte* ticketNonceBuf, - byte* ticketNonceLen, byte* preallocUsed) +unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len) { -#ifdef HAVE_SESSION_TICKET - int ticLenAlloc = 0; - byte *ticBuff = NULL; -#endif - const size_t copyOffset = OFFSETOF(WOLFSSL_SESSION, heap) + sizeof(input->heap); - int ret = WOLFSSL_SUCCESS; - - (void)avoidSysCalls; - (void)ticketNonceBuf; - (void)ticketNonceLen; - (void)preallocUsed; - - input = ClientSessionToSession(input); - output = ClientSessionToSession(output); + unsigned char* targetBuf; + int srcDigitHigh = 0; + int srcDigitLow = 0; + size_t srcLen; + size_t srcIdx = 0; + long targetIdx = 0; - if (input == NULL || output == NULL || input == output) { - WOLFSSL_MSG("input or output are null or same"); - return WOLFSSL_FAILURE; + srcLen = XSTRLEN(str); + targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL); + if (targetBuf == NULL) { + return NULL; } -#ifdef HAVE_SESSION_TICKET - if (output->ticket != output->staticTicket) { - ticBuff = output->ticket; - ticLenAlloc = output->ticketLenAlloc; - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - /* free the data, it would be better to reuse the buffer but this - * maintain the code simpler. A smart allocator should reuse the free'd - * buffer in the next malloc without much performance penalties. */ - if (output->ticketNonce.data != output->ticketNonce.dataStatic) { - - /* Callers that avoid syscall should never calls this with - * output->tickeNonce.data being a dynamic buffer.*/ - if (avoidSysCalls) { - WOLFSSL_MSG("can't avoid syscalls with dynamic TicketNonce buffer"); - return WOLFSSL_FAILURE; + while (srcIdx < srcLen) { + if (str[srcIdx] == ':') { + srcIdx++; + continue; } - XFREE(output->ticketNonce.data, - output->heap, DYNAMIC_TYPE_SESSION_TICK); - output->ticketNonce.data = output->ticketNonce.dataStatic; - output->ticketNonce.len = 0; - } -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ -#endif /* HAVE_SESSION_TICKET */ - -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (output->peer != NULL) { - if (avoidSysCalls) { - WOLFSSL_MSG("Can't free cert when avoiding syscalls"); - return WOLFSSL_FAILURE; + srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]); + srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]); + if (srcDigitHigh < 0 || srcDigitLow < 0) { + WOLFSSL_MSG("Invalid hex character."); + XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL); + return NULL; } - wolfSSL_X509_free(output->peer); - output->peer = NULL; - } -#endif - XMEMCPY((byte*)output + copyOffset, (byte*)input + copyOffset, - sizeof(WOLFSSL_SESSION) - copyOffset); - -#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ - defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - /* fix pointer to static after the copy */ - output->ticketNonce.data = output->ticketNonce.dataStatic; -#endif - /* Set sane values for copy */ -#ifndef NO_SESSION_CACHE - if (output->type != WOLFSSL_SESSION_TYPE_CACHE) - output->cacheRow = INVALID_SESSION_ROW; -#endif -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (input->peer != NULL && input->peer->dynamicMemory) { - if (wolfSSL_X509_up_ref(input->peer) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Can't increase peer cert ref count"); - output->peer = NULL; - } - } - else if (!avoidSysCalls) - output->peer = wolfSSL_X509_dup(input->peer); - else - /* output->peer is not that important to copy */ - output->peer = NULL; -#endif -#ifdef HAVE_SESSION_TICKET - if (input->ticketLen > SESSION_TICKET_LEN) { - /* Need dynamic buffer */ - if (ticBuff == NULL || ticLenAlloc < input->ticketLen) { - /* allocate new one */ - byte* tmp; - if (avoidSysCalls) { - WOLFSSL_MSG("Failed to allocate memory for ticket when avoiding" - " syscalls"); - output->ticket = ticBuff; - output->ticketLenAlloc = (word16) ticLenAlloc; - output->ticketLen = 0; - ret = WOLFSSL_FAILURE; - } - else { -#ifdef WOLFSSL_NO_REALLOC - tmp = (byte*)XMALLOC(input->ticketLen, - output->heap, DYNAMIC_TYPE_SESSION_TICK); - XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); - ticBuff = NULL; -#else - tmp = (byte*)XREALLOC(ticBuff, input->ticketLen, - output->heap, DYNAMIC_TYPE_SESSION_TICK); -#endif /* WOLFSSL_NO_REALLOC */ - if (tmp == NULL) { - WOLFSSL_MSG("Failed to allocate memory for ticket"); -#ifndef WOLFSSL_NO_REALLOC - XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); - ticBuff = NULL; -#endif /* WOLFSSL_NO_REALLOC */ - output->ticket = NULL; - output->ticketLen = 0; - output->ticketLenAlloc = 0; - ret = WOLFSSL_FAILURE; - } - else { - ticBuff = tmp; - ticLenAlloc = input->ticketLen; - } - } - } - if (ticBuff != NULL && ret == WOLFSSL_SUCCESS) { - XMEMCPY(ticBuff, input->ticket, input->ticketLen); - output->ticket = ticBuff; - output->ticketLenAlloc = (word16) ticLenAlloc; - } - } - else { - /* Default ticket to non dynamic */ - if (avoidSysCalls) { - /* Try to use ticBuf if available. Caller can later move it to - * the static buffer. */ - if (ticBuff != NULL) { - if (ticLenAlloc >= input->ticketLen) { - output->ticket = ticBuff; - output->ticketLenAlloc = ticLenAlloc; - } - else { - WOLFSSL_MSG("ticket dynamic buffer too small but we are " - "avoiding system calls"); - ret = WOLFSSL_FAILURE; - output->ticket = ticBuff; - output->ticketLenAlloc = (word16) ticLenAlloc; - output->ticketLen = 0; - } - } - else { - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - } - } - else { - if (ticBuff != NULL) - XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); - output->ticket = output->staticTicket; - output->ticketLenAlloc = 0; - } - if (input->ticketLenAlloc > 0 && ret == WOLFSSL_SUCCESS) { - /* Shouldn't happen as session should have placed this in - * the static buffer */ - XMEMCPY(output->ticket, input->ticket, - input->ticketLen); - } - } - ticBuff = NULL; - -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (preallocUsed != NULL) - *preallocUsed = 0; - - if (input->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ && - ret == WOLFSSL_SUCCESS) { - /* TicketNonce does not fit in the static buffer */ - if (!avoidSysCalls) { - output->ticketNonce.data = (byte*)XMALLOC(input->ticketNonce.len, - output->heap, DYNAMIC_TYPE_SESSION_TICK); - - if (output->ticketNonce.data == NULL) { - WOLFSSL_MSG("Failed to allocate space for ticket nonce"); - output->ticketNonce.data = output->ticketNonce.dataStatic; - output->ticketNonce.len = 0; - ret = WOLFSSL_FAILURE; - } - else { - output->ticketNonce.len = input->ticketNonce.len; - XMEMCPY(output->ticketNonce.data, input->ticketNonce.data, - input->ticketNonce.len); - ret = WOLFSSL_SUCCESS; - } - } - /* we can't do syscalls. Use prealloc buffers if provided from the - * caller. */ - else if (ticketNonceBuf != NULL && - *ticketNonceLen >= input->ticketNonce.len) { - XMEMCPY(ticketNonceBuf, input->ticketNonce.data, - input->ticketNonce.len); - *ticketNonceLen = input->ticketNonce.len; - if (preallocUsed != NULL) - *preallocUsed = 1; - ret = WOLFSSL_SUCCESS; - } - else { - WOLFSSL_MSG("TicketNonce bigger than static buffer, and we can't " - "do syscalls"); - ret = WOLFSSL_FAILURE; - } + targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) | + srcDigitLow ); } -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ - -#endif /* HAVE_SESSION_TICKET */ -#ifdef HAVE_EX_DATA - if (input->type != WOLFSSL_SESSION_TYPE_CACHE && - output->type != WOLFSSL_SESSION_TYPE_CACHE) { - /* Not called with cache as that passes ownership of ex_data */ - ret = crypto_ex_cb_dup_data(&input->ex_data, &output->ex_data, - crypto_ex_cb_ctx_session); - } -#endif + if (len != NULL) + *len = targetIdx; - return ret; + return targetBuf; } -/** - * Deep copy the contents from input to output. - * @param input The source of the copy. - * @param output The destination of the copy. - * @param avoidSysCalls If true, then system calls will be avoided or an error - * will be returned if it is not possible to proceed - * without a system call. This is useful for fetching - * sessions from cache. When a cache row is locked, we - * don't want to block other threads with long running - * system calls. - * @return WOLFSSL_SUCCESS on success - * WOLFSSL_FAILURE on failure - */ -int wolfSSL_DupSession(const WOLFSSL_SESSION* input, WOLFSSL_SESSION* output, - int avoidSysCalls) +int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings) { - return wolfSSL_DupSessionEx(input, output, avoidSysCalls, NULL, NULL, NULL); + (void)opts; + (void)settings; + return wolfSSL_library_init(); } -WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session) +int wolfSSL_OPENSSL_init_crypto(word64 opts, + const OPENSSL_INIT_SETTINGS* settings) { - WOLFSSL_SESSION* copy; - - WOLFSSL_ENTER("wolfSSL_SESSION_dup"); + (void)opts; + (void)settings; + return wolfSSL_library_init(); +} - session = ClientSessionToSession(session); - if (session == NULL) - return NULL; +/* Colon separated list of + algorithms. + * Replaces list in context. + */ +int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list) +{ + WOLFSSL_MSG("wolfSSL_CTX_set1_sigalg_list"); -#ifdef HAVE_SESSION_TICKET - if (session->ticketLenAlloc > 0 && !session->ticket) { - WOLFSSL_MSG("Session dynamic flag is set but ticket pointer is null"); - return NULL; + if (ctx == NULL || list == NULL) { + WOLFSSL_MSG("Bad function arguments"); + return WOLFSSL_FAILURE; } -#endif - copy = wolfSSL_NewSession(session->heap); - if (copy != NULL && - wolfSSL_DupSession(session, copy, 0) != WOLFSSL_SUCCESS) { - wolfSSL_FreeSession(NULL, copy); - copy = NULL; - } - return copy; + if (AllocateCtxSuites(ctx) != 0) + return WOLFSSL_FAILURE; + + return SetSuitesHashSigAlgo(ctx->suites, list); } -void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) +/* Colon separated list of + algorithms. + * Replaces list in SSL. + */ +int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list) { - session = ClientSessionToSession(session); - if (session == NULL) - return; + WOLFSSL_MSG("wolfSSL_set1_sigalg_list"); - (void)ctx; + if (ssl == NULL || list == NULL) { + WOLFSSL_MSG("Bad function arguments"); + return WOLFSSL_FAILURE; + } - WOLFSSL_ENTER("wolfSSL_FreeSession"); + if (AllocateSuites(ssl) != 0) + return WOLFSSL_FAILURE; - if (session->ref.count > 0) { - int ret; - int isZero; - wolfSSL_RefDec(&session->ref, &isZero, &ret); - (void)ret; - if (!isZero) { - return; - } - wolfSSL_RefFree(&session->ref); - } + return SetSuitesHashSigAlgo(ssl->suites, list); +} - WOLFSSL_MSG("wolfSSL_FreeSession full free"); +static int HashToNid(byte hashAlgo, int* nid) +{ + int ret = WOLFSSL_SUCCESS; -#ifdef HAVE_EX_DATA - if (session->ownExData) { - crypto_ex_cb_free_data(session, crypto_ex_cb_ctx_session, - &session->ex_data); + /* Cast for compiler to check everything is implemented */ + switch ((enum wc_MACAlgorithm)hashAlgo) { + case no_mac: + case rmd_mac: + *nid = NID_undef; + break; + case md5_mac: + *nid = NID_md5; + break; + case sha_mac: + *nid = NID_sha1; + break; + case sha224_mac: + *nid = NID_sha224; + break; + case sha256_mac: + *nid = NID_sha256; + break; + case sha384_mac: + *nid = NID_sha384; + break; + case sha512_mac: + *nid = NID_sha512; + break; + case blake2b_mac: + *nid = NID_blake2b512; + break; + case sm3_mac: + *nid = NID_sm3; + break; + default: + ret = WOLFSSL_FAILURE; + break; } -#endif - -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS - wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data); -#endif -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (session->peer) { - wolfSSL_X509_free(session->peer); - session->peer = NULL; - } -#endif + return ret; +} -#ifdef HAVE_SESSION_TICKET - if (session->ticketLenAlloc > 0) { - XFREE(session->ticket, session->heap, DYNAMIC_TYPE_SESSION_TICK); - session->ticket = session->staticTicket; - session->ticketLen = 0; - session->ticketLenAlloc = 0; - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - if (session->ticketNonce.data != session->ticketNonce.dataStatic) { - XFREE(session->ticketNonce.data, session->heap, - DYNAMIC_TYPE_SESSION_TICK); - session->ticketNonce.data = session->ticketNonce.dataStatic; - session->ticketNonce.len = 0; - } -#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ +static int SaToNid(byte sa, int* nid) +{ + int ret = WOLFSSL_SUCCESS; + /* Cast for compiler to check everything is implemented */ + switch ((enum SignatureAlgorithm)sa) { + case anonymous_sa_algo: + *nid = NID_undef; + break; + case rsa_sa_algo: + *nid = NID_rsaEncryption; + break; + case dsa_sa_algo: + *nid = NID_dsa; + break; + case ecc_dsa_sa_algo: + *nid = NID_X9_62_id_ecPublicKey; + break; + case rsa_pss_sa_algo: + *nid = NID_rsassaPss; + break; + case ed25519_sa_algo: +#ifdef HAVE_ED25519 + *nid = NID_ED25519; +#else + ret = WOLFSSL_FAILURE; #endif - -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS - wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data); + break; + case rsa_pss_pss_algo: + *nid = NID_rsassaPss; + break; + case ed448_sa_algo: +#ifdef HAVE_ED448 + *nid = NID_ED448; +#else + ret = WOLFSSL_FAILURE; #endif - - /* Make sure masterSecret is zeroed. */ - ForceZero(session->masterSecret, SECRET_LEN); - /* Session ID is sensitive information too. */ - ForceZero(session->sessionID, ID_LEN); - - if (session->type == WOLFSSL_SESSION_TYPE_HEAP) { - XFREE(session, session->heap, DYNAMIC_TYPE_SESSION); + break; + case falcon_level1_sa_algo: + *nid = CTC_FALCON_LEVEL1; + break; + case falcon_level5_sa_algo: + *nid = CTC_FALCON_LEVEL5; + break; + case dilithium_level2_sa_algo: + *nid = CTC_DILITHIUM_LEVEL2; + break; + case dilithium_level3_sa_algo: + *nid = CTC_DILITHIUM_LEVEL3; + break; + case dilithium_level5_sa_algo: + *nid = CTC_DILITHIUM_LEVEL5; + break; + case sm2_sa_algo: + *nid = NID_sm2; + break; + case invalid_sa_algo: + default: + ret = WOLFSSL_FAILURE; + break; } + return ret; } -/* DO NOT use this API internally. Use wolfSSL_FreeSession directly instead - * and pass in the ctx parameter if possible (like from ssl->ctx). */ -void wolfSSL_SESSION_free(WOLFSSL_SESSION* session) +/* This API returns the hash selected. */ +int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid) { - session = ClientSessionToSession(session); - wolfSSL_FreeSession(NULL, session); + WOLFSSL_MSG("wolfSSL_get_signature_nid"); + + if (ssl == NULL || nid == NULL) { + WOLFSSL_MSG("Bad function arguments"); + return WOLFSSL_FAILURE; + } + + return HashToNid(ssl->options.hashAlgo, nid); } -#ifndef NO_SESSION_CACHE -int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) +/* This API returns the signature selected. */ +int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid) { - int error = 0; - const byte* id = NULL; - byte idSz = 0; - - WOLFSSL_ENTER("wolfSSL_CTX_add_session"); + WOLFSSL_MSG("wolfSSL_get_signature_type_nid"); - session = ClientSessionToSession(session); - if (session == NULL) + if (ssl == NULL || nid == NULL) { + WOLFSSL_MSG("Bad function arguments"); return WOLFSSL_FAILURE; - - /* Session cache is global */ - (void)ctx; - - if (session->haveAltSessionID) { - id = session->altSessionID; - idSz = ID_LEN; } - else { - id = session->sessionID; - idSz = session->sessionIDSz; - } - - error = AddSessionToCache(ctx, session, id, idSz, - NULL, session->side, -#ifdef HAVE_SESSION_TICKET - session->ticketLen > 0, -#else - 0, -#endif - NULL); - return error == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + return SaToNid(ssl->options.sigAlgo, nid); } -#endif -#if defined(OPENSSL_EXTRA) || defined(HAVE_EXT_CACHE) - -/** -* set cipher to WOLFSSL_SESSION from WOLFSSL_CIPHER -* @param session a pointer to WOLFSSL_SESSION structure -* @param cipher a function pointer to WOLFSSL_CIPHER -* @return WOLFSSL_SUCCESS on success, otherwise WOLFSSL_FAILURE -*/ -int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session, - const WOLFSSL_CIPHER* cipher) +int wolfSSL_get_peer_signature_nid(WOLFSSL* ssl, int* nid) { - WOLFSSL_ENTER("wolfSSL_SESSION_set_cipher"); + WOLFSSL_MSG("wolfSSL_get_peer_signature_nid"); - session = ClientSessionToSession(session); - /* sanity check */ - if (session == NULL || cipher == NULL) { - WOLFSSL_MSG("bad argument"); + if (ssl == NULL || nid == NULL) { + WOLFSSL_MSG("Bad function arguments"); return WOLFSSL_FAILURE; } - session->cipherSuite0 = cipher->cipherSuite0; - session->cipherSuite = cipher->cipherSuite; - WOLFSSL_LEAVE("wolfSSL_SESSION_set_cipher", WOLFSSL_SUCCESS); - return WOLFSSL_SUCCESS; + return HashToNid(ssl->options.peerHashAlgo, nid); } -#endif /* OPENSSL_EXTRA || HAVE_EXT_CACHE */ - -/* helper function that takes in a protocol version struct and returns string */ -static const char* wolfSSL_internal_get_version(const ProtocolVersion* version) +int wolfSSL_get_peer_signature_type_nid(const WOLFSSL* ssl, int* nid) { - WOLFSSL_ENTER("wolfSSL_get_version"); + WOLFSSL_MSG("wolfSSL_get_peer_signature_type_nid"); - if (version == NULL) { - return "Bad arg"; + if (ssl == NULL || nid == NULL) { + WOLFSSL_MSG("Bad function arguments"); + return WOLFSSL_FAILURE; } - if (version->major == SSLv3_MAJOR) { - switch (version->minor) { - case SSLv3_MINOR : - return "SSLv3"; - case TLSv1_MINOR : - return "TLSv1"; - case TLSv1_1_MINOR : - return "TLSv1.1"; - case TLSv1_2_MINOR : - return "TLSv1.2"; - case TLSv1_3_MINOR : - return "TLSv1.3"; - default: - return "unknown"; - } - } -#ifdef WOLFSSL_DTLS - else if (version->major == DTLS_MAJOR) { - switch (version->minor) { - case DTLS_MINOR : - return "DTLS"; - case DTLSv1_2_MINOR : - return "DTLSv1.2"; - case DTLSv1_3_MINOR : - return "DTLSv1.3"; - default: - return "unknown"; - } - } -#endif /* WOLFSSL_DTLS */ - return "unknown"; + return SaToNid(ssl->options.peerSigAlgo, nid); } +#ifdef HAVE_ECC -const char* wolfSSL_get_version(const WOLFSSL* ssl) +#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES) +int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list) { - if (ssl == NULL) { - WOLFSSL_MSG("Bad argument"); - return "unknown"; + if (!ctx || !list) { + return WOLFSSL_FAILURE; } - return wolfSSL_internal_get_version(&ssl->version); + return set_curves_list(NULL, ctx, list, 0); } - -/* current library version */ -const char* wolfSSL_lib_version(void) +int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list) { - return LIBWOLFSSL_VERSION_STRING; -} + if (!ssl || !list) { + return WOLFSSL_FAILURE; + } -#ifdef OPENSSL_EXTRA -#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L -const char* wolfSSL_OpenSSL_version(int a) -{ - (void)a; - return "wolfSSL " LIBWOLFSSL_VERSION_STRING; -} -#else -const char* wolfSSL_OpenSSL_version(void) -{ - return "wolfSSL " LIBWOLFSSL_VERSION_STRING; + return set_curves_list(ssl, NULL, list, 0); } -#endif /* WOLFSSL_QT */ -#endif +#endif /* WOLFSSL_TLS13 */ +#endif /* HAVE_ECC */ -/* current library version in hex */ -word32 wolfSSL_lib_version_hex(void) +#endif /* OPENSSL_EXTRA */ + +#ifdef WOLFSSL_ALT_CERT_CHAINS +int wolfSSL_is_peer_alt_cert_chain(const WOLFSSL* ssl) { - return LIBWOLFSSL_VERSION_HEX; + int isUsing = 0; + if (ssl) + isUsing = ssl->options.usingAltCertChain; + return isUsing; } +#endif /* WOLFSSL_ALT_CERT_CHAINS */ -int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl) +#ifdef SESSION_CERTS + +#ifdef WOLFSSL_ALT_CERT_CHAINS +/* Get peer's alternate certificate chain */ +WOLFSSL_X509_CHAIN* wolfSSL_get_peer_alt_chain(WOLFSSL* ssl) { - WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite"); + WOLFSSL_ENTER("wolfSSL_get_peer_alt_chain"); if (ssl) - return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite; + return &ssl->session->altChain; + return 0; } - -WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_current_cipher"); - if (ssl) { - ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0; - ssl->cipher.cipherSuite = ssl->options.cipherSuite; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - ssl->cipher.bits = ssl->specs.key_size * 8; -#endif - return &ssl->cipher; - } - else - return NULL; -} +#endif /* WOLFSSL_ALT_CERT_CHAINS */ -const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher) +/* Get peer's certificate chain */ +WOLFSSL_X509_CHAIN* wolfSSL_get_peer_chain(WOLFSSL* ssl) { - WOLFSSL_ENTER("wolfSSL_CIPHER_get_name"); - - if (cipher == NULL) { - return NULL; - } + WOLFSSL_ENTER("wolfSSL_get_peer_chain"); + if (ssl) + return &ssl->session->chain; - #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \ - !defined(WOLFSSL_QT) - return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite); - #else - return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0, - cipher->cipherSuite); - #endif + return 0; } -const char* wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher) -{ - WOLFSSL_ENTER("wolfSSL_CIPHER_get_version"); - if (cipher == NULL || cipher->ssl == NULL) { - return NULL; - } +/* Get peer's certificate chain total count */ +int wolfSSL_get_chain_count(WOLFSSL_X509_CHAIN* chain) +{ + WOLFSSL_ENTER("wolfSSL_get_chain_count"); + if (chain) + return chain->count; - return wolfSSL_get_version(cipher->ssl); + return 0; } -const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session) + +/* Get peer's ASN.1 DER certificate at index (idx) length in bytes */ +int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx) { - session = ClientSessionToSession(session); - if (session == NULL) { - return NULL; - } + WOLFSSL_ENTER("wolfSSL_get_chain_length"); + if (chain) + return chain->certs[idx].length; -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) - return GetCipherNameIana(session->cipherSuite0, session->cipherSuite); - #else - return GetCipherNameInternal(session->cipherSuite0, session->cipherSuite); - #endif -#else - return NULL; -#endif + return 0; } -const char* wolfSSL_get_cipher(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_cipher"); - return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl)); -} -/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */ -const char* wolfSSL_get_cipher_name(WOLFSSL* ssl) +/* Get peer's ASN.1 DER certificate at index (idx) */ +byte* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx) { - /* get access to cipher_name_idx in internal.c */ - return wolfSSL_get_cipher_name_internal(ssl); -} + WOLFSSL_ENTER("wolfSSL_get_chain_cert"); + if (chain) + return chain->certs[idx].buffer; -const char* wolfSSL_get_cipher_name_from_suite(const byte cipherSuite0, - const byte cipherSuite) -{ - return GetCipherNameInternal(cipherSuite0, cipherSuite); + return 0; } -const char* wolfSSL_get_cipher_name_iana_from_suite(const byte cipherSuite0, - const byte cipherSuite) + +/* Get peer's wolfSSL X509 certificate at index (idx) */ +WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx) { - return GetCipherNameIana(cipherSuite0, cipherSuite); -} + int ret = 0; + WOLFSSL_X509* x509 = NULL; +#ifdef WOLFSSL_SMALL_STACK + DecodedCert* cert = NULL; +#else + DecodedCert cert[1]; +#endif -int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0, - byte* cipherSuite, int *flags) { - if ((name == NULL) || - (cipherSuite0 == NULL) || - (cipherSuite == NULL) || - (flags == NULL)) - return BAD_FUNC_ARG; - return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, flags); -} + WOLFSSL_ENTER("wolfSSL_get_chain_X509"); + if (chain != NULL && idx < MAX_CHAIN_DEPTH) { + #ifdef WOLFSSL_SMALL_STACK + cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, + DYNAMIC_TYPE_DCERT); + if (cert != NULL) + #endif + { + InitDecodedCert(cert, chain->certs[idx].buffer, + chain->certs[idx].length, NULL); + if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) != 0) { + WOLFSSL_MSG("Failed to parse cert"); + } + else { + x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL, + DYNAMIC_TYPE_X509); + if (x509 == NULL) { + WOLFSSL_MSG("Failed alloc X509"); + } + else { + InitX509(x509, 1, NULL); -#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) -/* Creates and returns a new WOLFSSL_CIPHER stack. */ -WOLFSSL_STACK* wolfSSL_sk_new_cipher(void) -{ - WOLFSSL_STACK* sk; - WOLFSSL_ENTER("wolfSSL_sk_new_cipher"); + if ((ret = CopyDecodedToX509(x509, cert)) != 0) { + WOLFSSL_MSG("Failed to copy decoded"); + wolfSSL_X509_free(x509); + x509 = NULL; + } + } + } - sk = wolfSSL_sk_new_null(); - if (sk == NULL) - return NULL; - sk->type = STACK_TYPE_CIPHER; + FreeDecodedCert(cert); + #ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + #endif + } + } + (void)ret; - return sk; + return x509; } -/* return 1 on success 0 on fail */ -int wolfSSL_sk_CIPHER_push(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, - WOLFSSL_CIPHER* cipher) -{ - return wolfSSL_sk_push(sk, cipher); -} -#ifndef NO_WOLFSSL_STUB -WOLFSSL_CIPHER* wolfSSL_sk_CIPHER_pop(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) +/* Get peer's PEM certificate at index (idx), output to buffer if inLen big + enough else return error (-1). If buffer is NULL only calculate + outLen. Output length is in *outLen WOLFSSL_SUCCESS on ok */ +int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, + unsigned char* buf, int inLen, int* outLen) { - WOLFSSL_STUB("wolfSSL_sk_CIPHER_pop"); - (void)sk; - return NULL; -} -#endif /* NO_WOLFSSL_STUB */ -#endif /* WOLFSSL_QT || OPENSSL_ALL */ +#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) + const char* header = NULL; + const char* footer = NULL; + int headerLen; + int footerLen; + int i; + int err; + word32 szNeeded = 0; -word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher) -{ - word16 cipher_id = 0; + WOLFSSL_ENTER("wolfSSL_get_chain_cert_pem"); + if (!chain || !outLen || idx < 0 || idx >= wolfSSL_get_chain_count(chain)) + return BAD_FUNC_ARG; - WOLFSSL_ENTER("wolfSSL_CIPHER_get_id"); + err = wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer); + if (err != 0) + return err; - if (cipher && cipher->ssl) { - cipher_id = (cipher->ssl->options.cipherSuite0 << 8) | - cipher->ssl->options.cipherSuite; + headerLen = (int)XSTRLEN(header); + footerLen = (int)XSTRLEN(footer); + + /* Null output buffer return size needed in outLen */ + if(!buf) { + if(Base64_Encode(chain->certs[idx].buffer, chain->certs[idx].length, + NULL, &szNeeded) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + return WOLFSSL_FAILURE; + *outLen = szNeeded + headerLen + footerLen; + return LENGTH_ONLY_E; } - return cipher_id; -} + /* don't even try if inLen too short */ + if (inLen < headerLen + footerLen + chain->certs[idx].length) + return BAD_FUNC_ARG; -const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value) -{ - const WOLFSSL_CIPHER* cipher = NULL; - byte cipherSuite0, cipherSuite; - WOLFSSL_ENTER("wolfSSL_get_cipher_by_value"); + /* header */ + if (XMEMCPY(buf, header, headerLen) == NULL) + return WOLFSSL_FATAL_ERROR; - /* extract cipher id information */ - cipherSuite = (value & 0xFF); - cipherSuite0 = ((value >> 8) & 0xFF); + i = headerLen; - /* TODO: lookup by cipherSuite0 / cipherSuite */ - (void)cipherSuite0; - (void)cipherSuite; + /* body */ + *outLen = inLen; /* input to Base64_Encode */ + if ( (err = Base64_Encode(chain->certs[idx].buffer, + chain->certs[idx].length, buf + i, (word32*)outLen)) < 0) + return err; + i += *outLen; - return cipher; + /* footer */ + if ( (i + footerLen) > inLen) + return BAD_FUNC_ARG; + if (XMEMCPY(buf + i, footer, footerLen) == NULL) + return WOLFSSL_FATAL_ERROR; + *outLen += headerLen + footerLen; + + return WOLFSSL_SUCCESS; +#else + (void)chain; + (void)idx; + (void)buf; + (void)inLen; + (void)outLen; + return WOLFSSL_FAILURE; +#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */ } +#endif /* SESSION_CERTS */ -#if defined(OPENSSL_EXTRA) -/* Free the structure for WOLFSSL_CIPHER stack - * - * sk stack to free nodes in - */ -void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) +#ifdef HAVE_FUZZER +void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx) { - WOLFSSL_ENTER("wolfSSL_sk_CIPHER_free"); - - wolfSSL_sk_free(sk); + if (ssl) { + ssl->fuzzerCb = cbf; + ssl->fuzzerCtx = fCtx; + } } -#endif /* OPENSSL_ALL */ +#endif -#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \ - !defined(NO_DH) -#ifdef HAVE_FFDHE -static const char* wolfssl_ffdhe_name(word16 group) +#ifndef NO_CERTS +#ifdef HAVE_PK_CALLBACKS + +#ifdef HAVE_ECC +void wolfSSL_CTX_SetEccKeyGenCb(WOLFSSL_CTX* ctx, CallbackEccKeyGen cb) { - const char* str = NULL; - switch (group) { - case WOLFSSL_FFDHE_2048: - str = "FFDHE_2048"; - break; - case WOLFSSL_FFDHE_3072: - str = "FFDHE_3072"; - break; - case WOLFSSL_FFDHE_4096: - str = "FFDHE_4096"; - break; - case WOLFSSL_FFDHE_6144: - str = "FFDHE_6144"; - break; - case WOLFSSL_FFDHE_8192: - str = "FFDHE_8192"; - break; - default: - break; - } - return str; + if (ctx) + ctx->EccKeyGenCb = cb; } -#endif -/* Return the name of the curve used for key exchange as a printable string. - * - * ssl The SSL/TLS object. - * returns NULL if ECDH was not used, otherwise the name as a string. - */ -const char* wolfSSL_get_curve_name(WOLFSSL* ssl) +void wolfSSL_SetEccKeyGenCtx(WOLFSSL* ssl, void *ctx) { - const char* cName = NULL; + if (ssl) + ssl->EccKeyGenCtx = ctx; +} +void* wolfSSL_GetEccKeyGenCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->EccKeyGenCtx; - WOLFSSL_ENTER("wolfSSL_get_curve_name"); + return NULL; +} +void wolfSSL_CTX_SetEccSignCtx(WOLFSSL_CTX* ctx, void *userCtx) +{ + if (ctx) + ctx->EccSignCtx = userCtx; +} +void* wolfSSL_CTX_GetEccSignCtx(WOLFSSL_CTX* ctx) +{ + if (ctx) + return ctx->EccSignCtx; - if (ssl == NULL) - return NULL; + return NULL; +} -#if defined(WOLFSSL_TLS13) && defined(HAVE_PQC) - /* Check for post-quantum groups. Return now because we do not want the ECC - * check to override this result in the case of a hybrid. */ - if (IsAtLeastTLSv1_3(ssl->version)) { - switch (ssl->namedGroup) { -#ifdef HAVE_LIBOQS - case WOLFSSL_KYBER_LEVEL1: - return "KYBER_LEVEL1"; - case WOLFSSL_KYBER_LEVEL3: - return "KYBER_LEVEL3"; - case WOLFSSL_KYBER_LEVEL5: - return "KYBER_LEVEL5"; - case WOLFSSL_P256_KYBER_LEVEL1: - return "P256_KYBER_LEVEL1"; - case WOLFSSL_P384_KYBER_LEVEL3: - return "P384_KYBER_LEVEL3"; - case WOLFSSL_P521_KYBER_LEVEL5: - return "P521_KYBER_LEVEL5"; -#elif defined(HAVE_PQM4) - case WOLFSSL_KYBER_LEVEL1: - return "KYBER_LEVEL1"; -#elif defined(WOLFSSL_WC_KYBER) - #ifdef WOLFSSL_KYBER512 - case WOLFSSL_KYBER_LEVEL1: - return "KYBER_LEVEL1"; - #endif - #ifdef WOLFSSL_KYBER768 - case WOLFSSL_KYBER_LEVEL3: - return "KYBER_LEVEL3"; - #endif - #ifdef WOLFSSL_KYBER1024 - case WOLFSSL_KYBER_LEVEL5: - return "KYBER_LEVEL5"; - #endif -#endif - } - } +WOLFSSL_ABI +void wolfSSL_CTX_SetEccSignCb(WOLFSSL_CTX* ctx, CallbackEccSign cb) +{ + if (ctx) + ctx->EccSignCb = cb; +} +void wolfSSL_SetEccSignCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->EccSignCtx = ctx; +} +void* wolfSSL_GetEccSignCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->EccSignCtx; -#endif /* WOLFSSL_TLS13 && HAVE_PQC */ -#ifdef HAVE_FFDHE - if (ssl->namedGroup != 0) { - cName = wolfssl_ffdhe_name(ssl->namedGroup); - } -#endif + return NULL; +} -#ifdef HAVE_CURVE25519 - if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) { - cName = "X25519"; - } -#endif +void wolfSSL_CTX_SetEccVerifyCb(WOLFSSL_CTX* ctx, CallbackEccVerify cb) +{ + if (ctx) + ctx->EccVerifyCb = cb; +} +void wolfSSL_SetEccVerifyCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->EccVerifyCtx = ctx; +} +void* wolfSSL_GetEccVerifyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->EccVerifyCtx; -#ifdef HAVE_CURVE448 - if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) { - cName = "X448"; - } -#endif + return NULL; +} -#ifdef HAVE_ECC - if (ssl->ecdhCurveOID != 0 && cName == NULL) { - cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, - NULL)); - } -#endif +void wolfSSL_CTX_SetEccSharedSecretCb(WOLFSSL_CTX* ctx, + CallbackEccSharedSecret cb) +{ + if (ctx) + ctx->EccSharedSecretCb = cb; +} +void wolfSSL_SetEccSharedSecretCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->EccSharedSecretCtx = ctx; +} +void* wolfSSL_GetEccSharedSecretCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->EccSharedSecretCtx; - return cName; + return NULL; } -#endif +#endif /* HAVE_ECC */ -#ifdef OPENSSL_EXTRA -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) -/* return authentication NID corresponding to cipher suite - * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found - */ -int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) +#ifdef HAVE_ED25519 +void wolfSSL_CTX_SetEd25519SignCb(WOLFSSL_CTX* ctx, CallbackEd25519Sign cb) { - static const struct authnid { - const char* alg_name; - const int nid; - } authnid_tbl[] = { - {"RSA", NID_auth_rsa}, - {"PSK", NID_auth_psk}, - {"SRP", NID_auth_srp}, - {"ECDSA", NID_auth_ecdsa}, - {"None", NID_auth_null}, - {NULL, NID_undef} - }; - - const char* authStr; - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + if (ctx) + ctx->Ed25519SignCb = cb; +} +void wolfSSL_SetEd25519SignCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->Ed25519SignCtx = ctx; +} +void* wolfSSL_GetEd25519SignCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->Ed25519SignCtx; - if (GetCipherSegment(cipher, n) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; - } + return NULL; +} - authStr = GetCipherAuthStr(n); +void wolfSSL_CTX_SetEd25519VerifyCb(WOLFSSL_CTX* ctx, CallbackEd25519Verify cb) +{ + if (ctx) + ctx->Ed25519VerifyCb = cb; +} +void wolfSSL_SetEd25519VerifyCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->Ed25519VerifyCtx = ctx; +} +void* wolfSSL_GetEd25519VerifyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->Ed25519VerifyCtx; - if (authStr != NULL) { - const struct authnid* sa; - for(sa = authnid_tbl; sa->alg_name != NULL; sa++) { - if (XSTRCMP(sa->alg_name, authStr) == 0) { - return sa->nid; - } - } - } + return NULL; +} +#endif /* HAVE_ED25519 */ - return NID_undef; +#ifdef HAVE_CURVE25519 +void wolfSSL_CTX_SetX25519KeyGenCb(WOLFSSL_CTX* ctx, + CallbackX25519KeyGen cb) +{ + if (ctx) + ctx->X25519KeyGenCb = cb; } -/* return cipher NID corresponding to cipher suite - * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found - */ -int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) +void wolfSSL_SetX25519KeyGenCtx(WOLFSSL* ssl, void *ctx) { - static const struct ciphernid { - const char* alg_name; - const int nid; - } ciphernid_tbl[] = { - {"AESGCM(256)", NID_aes_256_gcm}, - {"AESGCM(128)", NID_aes_128_gcm}, - {"AESCCM(128)", NID_aes_128_ccm}, - {"AES(128)", NID_aes_128_cbc}, - {"AES(256)", NID_aes_256_cbc}, - {"CAMELLIA(256)", NID_camellia_256_cbc}, - {"CAMELLIA(128)", NID_camellia_128_cbc}, - {"RC4", NID_rc4}, - {"3DES", NID_des_ede3_cbc}, - {"CHACHA20/POLY1305(256)", NID_chacha20_poly1305}, - {"None", NID_undef}, - {NULL, NID_undef} - }; - - const char* encStr; - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - - WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid"); - - if (GetCipherSegment(cipher, n) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; - } - - encStr = GetCipherEncStr(n); - - if (encStr != NULL) { - const struct ciphernid* c; - for(c = ciphernid_tbl; c->alg_name != NULL; c++) { - if (XSTRCMP(c->alg_name, encStr) == 0) { - return c->nid; - } - } - } - - return NID_undef; + if (ssl) + ssl->X25519KeyGenCtx = ctx; } -/* return digest NID corresponding to cipher suite - * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found - */ -int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) +void* wolfSSL_GetX25519KeyGenCtx(WOLFSSL* ssl) { - static const struct macnid { - const char* alg_name; - const int nid; - } macnid_tbl[] = { - {"SHA1", NID_sha1}, - {"SHA256", NID_sha256}, - {"SHA384", NID_sha384}, - {NULL, NID_undef} - }; - - const char* name; - const char* macStr; - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - (void)name; + if (ssl) + return ssl->X25519KeyGenCtx; - WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid"); + return NULL; +} - if ((name = GetCipherSegment(cipher, n)) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; - } +void wolfSSL_CTX_SetX25519SharedSecretCb(WOLFSSL_CTX* ctx, + CallbackX25519SharedSecret cb) +{ + if (ctx) + ctx->X25519SharedSecretCb = cb; +} +void wolfSSL_SetX25519SharedSecretCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->X25519SharedSecretCtx = ctx; +} +void* wolfSSL_GetX25519SharedSecretCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->X25519SharedSecretCtx; - /* in MD5 case, NID will be NID_md5 */ - if (XSTRSTR(name, "MD5") != NULL) { - return NID_md5; - } + return NULL; +} +#endif /* HAVE_CURVE25519 */ - macStr = GetCipherMacStr(n); +#ifdef HAVE_ED448 +void wolfSSL_CTX_SetEd448SignCb(WOLFSSL_CTX* ctx, CallbackEd448Sign cb) +{ + if (ctx) + ctx->Ed448SignCb = cb; +} +void wolfSSL_SetEd448SignCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->Ed448SignCtx = ctx; +} +void* wolfSSL_GetEd448SignCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->Ed448SignCtx; - if (macStr != NULL) { - const struct macnid* mc; - for(mc = macnid_tbl; mc->alg_name != NULL; mc++) { - if (XSTRCMP(mc->alg_name, macStr) == 0) { - return mc->nid; - } - } - } + return NULL; +} - return NID_undef; +void wolfSSL_CTX_SetEd448VerifyCb(WOLFSSL_CTX* ctx, CallbackEd448Verify cb) +{ + if (ctx) + ctx->Ed448VerifyCb = cb; } -/* return key exchange NID corresponding to cipher suite - * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found - */ -int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) +void wolfSSL_SetEd448VerifyCtx(WOLFSSL* ssl, void *ctx) { - static const struct kxnid { - const char* name; - const int nid; - } kxnid_table[] = { - {"ECDHEPSK", NID_kx_ecdhe_psk}, - {"ECDH", NID_kx_ecdhe}, - {"DHEPSK", NID_kx_dhe_psk}, - {"DH", NID_kx_dhe}, - {"RSAPSK", NID_kx_rsa_psk}, - {"SRP", NID_kx_srp}, - {"EDH", NID_kx_dhe}, - {"RSA", NID_kx_rsa}, - {NULL, NID_undef} - }; - - const char* keaStr; - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + if (ssl) + ssl->Ed448VerifyCtx = ctx; +} +void* wolfSSL_GetEd448VerifyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->Ed448VerifyCtx; - WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid"); + return NULL; +} +#endif /* HAVE_ED448 */ - if (GetCipherSegment(cipher, n) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; - } +#ifdef HAVE_CURVE448 +void wolfSSL_CTX_SetX448KeyGenCb(WOLFSSL_CTX* ctx, + CallbackX448KeyGen cb) +{ + if (ctx) + ctx->X448KeyGenCb = cb; +} +void wolfSSL_SetX448KeyGenCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->X448KeyGenCtx = ctx; +} +void* wolfSSL_GetX448KeyGenCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->X448KeyGenCtx; - /* in TLS 1.3 case, NID will be NID_kx_any */ - if (XSTRCMP(n[0], "TLS13") == 0) { - return NID_kx_any; - } + return NULL; +} - keaStr = GetCipherKeaStr(n); +void wolfSSL_CTX_SetX448SharedSecretCb(WOLFSSL_CTX* ctx, + CallbackX448SharedSecret cb) +{ + if (ctx) + ctx->X448SharedSecretCb = cb; +} +void wolfSSL_SetX448SharedSecretCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->X448SharedSecretCtx = ctx; +} +void* wolfSSL_GetX448SharedSecretCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->X448SharedSecretCtx; - if (keaStr != NULL) { - const struct kxnid* k; - for(k = kxnid_table; k->name != NULL; k++) { - if (XSTRCMP(k->name, keaStr) == 0) { - return k->nid; - } - } - } + return NULL; +} +#endif /* HAVE_CURVE448 */ - return NID_undef; +#ifndef NO_RSA +void wolfSSL_CTX_SetRsaSignCb(WOLFSSL_CTX* ctx, CallbackRsaSign cb) +{ + if (ctx) + ctx->RsaSignCb = cb; } -/* check if cipher suite is AEAD - * @param cipher a pointer to WOLFSSL_CIPHER - * return 1 if cipher is AEAD, 0 otherwise - */ -int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher) +void wolfSSL_CTX_SetRsaSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb) { - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; + if (ctx) + ctx->RsaSignCheckCb = cb; +} +void wolfSSL_SetRsaSignCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->RsaSignCtx = ctx; +} +void* wolfSSL_GetRsaSignCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaSignCtx; - WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead"); + return NULL; +} - if (GetCipherSegment(cipher, n) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; - } - return IsCipherAEAD(n); +void wolfSSL_CTX_SetRsaVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb) +{ + if (ctx) + ctx->RsaVerifyCb = cb; } -/* Creates cipher->description based on cipher->offset - * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added - * to a stack of ciphers. - * @param [in] cipher: A cipher from a stack of ciphers. - * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE - */ -int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher) +void wolfSSL_SetRsaVerifyCtx(WOLFSSL* ssl, void *ctx) { - int strLen; - unsigned long offset; - char* dp; - const char* name; - const char *keaStr, *authStr, *encStr, *macStr, *protocol; - char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}}; - int len = MAX_DESCRIPTION_SZ-1; - const CipherSuiteInfo* cipher_names; - ProtocolVersion pv; - WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description"); - - if (cipher == NULL) - return WOLFSSL_FAILURE; + if (ssl) + ssl->RsaVerifyCtx = ctx; +} +void* wolfSSL_GetRsaVerifyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaVerifyCtx; - dp = cipher->description; - if (dp == NULL) - return WOLFSSL_FAILURE; + return NULL; +} - cipher_names = GetCipherNames(); +#ifdef WC_RSA_PSS +void wolfSSL_CTX_SetRsaPssSignCb(WOLFSSL_CTX* ctx, CallbackRsaPssSign cb) +{ + if (ctx) + ctx->RsaPssSignCb = cb; +} +void wolfSSL_CTX_SetRsaPssSignCheckCb(WOLFSSL_CTX* ctx, + CallbackRsaPssVerify cb) +{ + if (ctx) + ctx->RsaPssSignCheckCb = cb; +} +void wolfSSL_SetRsaPssSignCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->RsaPssSignCtx = ctx; +} +void* wolfSSL_GetRsaPssSignCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaPssSignCtx; - offset = cipher->offset; - if (offset >= (unsigned long)GetCipherNamesSize()) - return WOLFSSL_FAILURE; - pv.major = cipher_names[offset].major; - pv.minor = cipher_names[offset].minor; - protocol = wolfSSL_internal_get_version(&pv); + return NULL; +} - if ((name = GetCipherSegment(cipher, n)) == NULL) { - WOLFSSL_MSG("no suitable cipher name found"); - return WOLFSSL_FAILURE; - } +void wolfSSL_CTX_SetRsaPssVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb) +{ + if (ctx) + ctx->RsaPssVerifyCb = cb; +} +void wolfSSL_SetRsaPssVerifyCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->RsaPssVerifyCtx = ctx; +} +void* wolfSSL_GetRsaPssVerifyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaPssVerifyCtx; - /* keaStr */ - keaStr = GetCipherKeaStr(n); - /* authStr */ - authStr = GetCipherAuthStr(n); - /* encStr */ - encStr = GetCipherEncStr(n); - if ((cipher->bits = SetCipherBits(encStr)) == WOLFSSL_FAILURE) { - WOLFSSL_MSG("Cipher Bits Not Set."); - } - /* macStr */ - macStr = GetCipherMacStr(n); + return NULL; +} +#endif /* WC_RSA_PSS */ +void wolfSSL_CTX_SetRsaEncCb(WOLFSSL_CTX* ctx, CallbackRsaEnc cb) +{ + if (ctx) + ctx->RsaEncCb = cb; +} +void wolfSSL_SetRsaEncCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->RsaEncCtx = ctx; +} +void* wolfSSL_GetRsaEncCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaEncCtx; - /* Build up the string by copying onto the end. */ - XSTRNCPY(dp, name, len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; + return NULL; +} - XSTRNCPY(dp, " ", len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, protocol, len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; +void wolfSSL_CTX_SetRsaDecCb(WOLFSSL_CTX* ctx, CallbackRsaDec cb) +{ + if (ctx) + ctx->RsaDecCb = cb; +} +void wolfSSL_SetRsaDecCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->RsaDecCtx = ctx; +} +void* wolfSSL_GetRsaDecCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->RsaDecCtx; - XSTRNCPY(dp, " Kx=", len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, keaStr, len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; + return NULL; +} +#endif /* NO_RSA */ - XSTRNCPY(dp, " Au=", len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, authStr, len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; +/* callback for premaster secret generation */ +void wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb) +{ + if (ctx) + ctx->GenPreMasterCb = cb; +} +/* Set premaster secret generation callback context */ +void wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->GenPreMasterCtx = ctx; +} +/* Get premaster secret generation callback context */ +void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->GenPreMasterCtx; - XSTRNCPY(dp, " Enc=", len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, encStr, len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; + return NULL; +} - XSTRNCPY(dp, " Mac=", len); - dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, macStr, len); - dp[len-1] = '\0'; +/* callback for master secret generation */ +void wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx, + CallbackGenMasterSecret cb) +{ + if (ctx) + ctx->GenMasterCb = cb; +} +/* Set master secret generation callback context */ +void wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->GenMasterCtx = ctx; +} +/* Get master secret generation callback context */ +void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->GenMasterCtx; - return WOLFSSL_SUCCESS; + return NULL; } -#endif /* OPENSSL_ALL || WOLFSSL_QT */ -static WC_INLINE const char* wolfssl_kea_to_string(int kea) +/* callback for session key generation */ +void wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb) { - const char* keaStr; - - switch (kea) { - case no_kea: - keaStr = "None"; - break; -#ifndef NO_RSA - case rsa_kea: - keaStr = "RSA"; - break; -#endif -#ifndef NO_DH - case diffie_hellman_kea: - keaStr = "DHE"; - break; -#endif - case fortezza_kea: - keaStr = "FZ"; - break; -#ifndef NO_PSK - case psk_kea: - keaStr = "PSK"; - break; - #ifndef NO_DH - case dhe_psk_kea: - keaStr = "DHEPSK"; - break; - #endif - #ifdef HAVE_ECC - case ecdhe_psk_kea: - keaStr = "ECDHEPSK"; - break; - #endif -#endif -#ifdef HAVE_ECC - case ecc_diffie_hellman_kea: - keaStr = "ECDHE"; - break; - case ecc_static_diffie_hellman_kea: - keaStr = "ECDH"; - break; -#endif - default: - keaStr = "unknown"; - break; - } + if (ctx) + ctx->GenSessionKeyCb = cb; +} +/* Set session key generation callback context */ +void wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->GenSessionKeyCtx = ctx; +} +/* Get session key generation callback context */ +void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->GenSessionKeyCtx; - return keaStr; + return NULL; } -static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo) +/* callback for setting encryption keys */ +void wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb) { - const char* authStr; - - switch (sig_algo) { - case anonymous_sa_algo: - authStr = "None"; - break; -#ifndef NO_RSA - case rsa_sa_algo: - authStr = "RSA"; - break; - #ifdef WC_RSA_PSS - case rsa_pss_sa_algo: - authStr = "RSA-PSS"; - break; - #endif -#endif -#ifndef NO_DSA - case dsa_sa_algo: - authStr = "DSA"; - break; -#endif -#ifdef HAVE_ECC - case ecc_dsa_sa_algo: - authStr = "ECDSA"; - break; -#endif -#ifdef WOLFSSL_SM2 - case sm2_sa_algo: - authStr = "SM2"; - break; -#endif -#ifdef HAVE_ED25519 - case ed25519_sa_algo: - authStr = "Ed25519"; - break; -#endif -#ifdef HAVE_ED448 - case ed448_sa_algo: - authStr = "Ed448"; - break; -#endif - default: - authStr = "unknown"; - break; - } - - return authStr; + if (ctx) + ctx->EncryptKeysCb = cb; } - -static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size) +/* Set encryption keys callback context */ +void wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx) { - const char* encStr; - - (void)key_size; + if (ssl) + ssl->EncryptKeysCtx = ctx; +} +/* Get encryption keys callback context */ +void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->EncryptKeysCtx; - switch (cipher) { - case wolfssl_cipher_null: - encStr = "None"; - break; -#ifndef NO_RC4 - case wolfssl_rc4: - encStr = "RC4(128)"; - break; -#endif -#ifndef NO_DES3 - case wolfssl_triple_des: - encStr = "3DES(168)"; - break; -#endif -#ifndef NO_AES - case wolfssl_aes: - if (key_size == 128) - encStr = "AES(128)"; - else if (key_size == 256) - encStr = "AES(256)"; - else - encStr = "AES(?)"; - break; - #ifdef HAVE_AESGCM - case wolfssl_aes_gcm: - if (key_size == 128) - encStr = "AESGCM(128)"; - else if (key_size == 256) - encStr = "AESGCM(256)"; - else - encStr = "AESGCM(?)"; - break; - #endif - #ifdef HAVE_AESCCM - case wolfssl_aes_ccm: - if (key_size == 128) - encStr = "AESCCM(128)"; - else if (key_size == 256) - encStr = "AESCCM(256)"; - else - encStr = "AESCCM(?)"; - break; - #endif -#endif -#ifdef HAVE_CHACHA - case wolfssl_chacha: - encStr = "CHACHA20/POLY1305(256)"; - break; -#endif -#ifdef HAVE_ARIA - case wolfssl_aria_gcm: - if (key_size == 128) - encStr = "Aria(128)"; - else if (key_size == 192) - encStr = "Aria(192)"; - else if (key_size == 256) - encStr = "Aria(256)"; - else - encStr = "Aria(?)"; - break; -#endif -#ifdef HAVE_CAMELLIA - case wolfssl_camellia: - if (key_size == 128) - encStr = "Camellia(128)"; - else if (key_size == 256) - encStr = "Camellia(256)"; - else - encStr = "Camellia(?)"; - break; -#endif - default: - encStr = "unknown"; - break; - } + return NULL; +} - return encStr; +/* callback for Tls finished */ +/* the callback can be used to build TLS Finished message if enabled */ +void wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb) +{ + if (ctx) + ctx->TlsFinishedCb = cb; +} +/* Set Tls finished callback context */ +void wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->TlsFinishedCtx = ctx; } +/* Get Tls finished callback context */ +void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->TlsFinishedCtx; -static WC_INLINE const char* wolfssl_mac_to_string(int mac) + return NULL; +} +#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY) +/* callback for verify data */ +void wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb) { - const char* macStr; + if (ctx) + ctx->VerifyMacCb = cb; +} - switch (mac) { - case no_mac: - macStr = "None"; - break; -#ifndef NO_MD5 - case md5_mac: - macStr = "MD5"; - break; -#endif -#ifndef NO_SHA - case sha_mac: - macStr = "SHA1"; - break; -#endif -#ifdef HAVE_SHA224 - case sha224_mac: - macStr = "SHA224"; - break; -#endif -#ifndef NO_SHA256 - case sha256_mac: - macStr = "SHA256"; - break; -#endif -#ifdef HAVE_SHA384 - case sha384_mac: - macStr = "SHA384"; - break; -#endif -#ifdef HAVE_SHA512 - case sha512_mac: - macStr = "SHA512"; - break; -#endif - default: - macStr = "unknown"; - break; - } +/* Set set keys callback context */ +void wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->VerifyMacCtx = ctx; +} +/* Get set keys callback context */ +void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->VerifyMacCtx; - return macStr; + return NULL; } +#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */ -char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, - int len) +void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx, + CallbackHKDFExpandLabel cb) { - char *ret = in; - const char *keaStr, *authStr, *encStr, *macStr; - size_t strLen; - WOLFSSL_ENTER("wolfSSL_CIPHER_description"); - - if (cipher == NULL || in == NULL) - return NULL; + if (ctx) + ctx->HKDFExpandLabelCb = cb; +} +#ifdef WOLFSSL_PUBLIC_ASN +void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx, + CallbackProcessPeerCert cb) +{ + if (ctx) + ctx->ProcessPeerCertCb = cb; +} +#endif /* WOLFSSL_PUBLIC_ASN */ +void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx, + CallbackProcessServerSigKex cb) +{ + if (ctx) + ctx->ProcessServerSigKexCb = cb; +} +void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, + CallbackPerformTlsRecordProcessing cb) +{ + if (ctx) + ctx->PerformTlsRecordProcessingCb = cb; +} +#endif /* HAVE_PK_CALLBACKS */ +#endif /* NO_CERTS */ -#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - /* if cipher is in the stack from wolfSSL_get_ciphers_compat then - * Return the description based on cipher_names[cipher->offset] - */ - if (cipher->in_stack == TRUE) { - wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher); - XSTRNCPY(in,cipher->description,len); - return ret; - } -#endif - - /* Get the cipher description based on the SSL session cipher */ - keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea); - authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo); - encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm, - cipher->ssl->specs.key_size); - macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm); - - /* Build up the string by copying onto the end. */ - XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - - XSTRNCPY(in, " ", len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - - XSTRNCPY(in, " Kx=", len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, keaStr, len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - - XSTRNCPY(in, " Au=", len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, authStr, len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - - XSTRNCPY(in, " Enc=", len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, encStr, len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - - XSTRNCPY(in, " Mac=", len); - in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, macStr, len); - in[len-1] = '\0'; - - return ret; +#if defined(HAVE_PK_CALLBACKS) && !defined(NO_DH) +void wolfSSL_CTX_SetDhGenerateKeyPair(WOLFSSL_CTX* ctx, + CallbackDhGenerateKeyPair cb) { + if (ctx) + ctx->DhGenerateKeyPairCb = cb; } - - -#ifndef NO_WOLFSSL_STUB -int wolfSSL_OCSP_parse_url(char* url, char** host, char** port, char** path, - int* ssl) +void wolfSSL_CTX_SetDhAgreeCb(WOLFSSL_CTX* ctx, CallbackDhAgree cb) { - (void)url; - (void)host; - (void)port; - (void)path; - (void)ssl; - WOLFSSL_STUB("OCSP_parse_url"); - return 0; + if (ctx) + ctx->DhAgreeCb = cb; } -#endif - -#ifndef NO_WOLFSSL_STUB -void wolfSSL_RAND_screen(void) +void wolfSSL_SetDhAgreeCtx(WOLFSSL* ssl, void *ctx) { - WOLFSSL_STUB("RAND_screen"); + if (ssl) + ssl->DhAgreeCtx = ctx; } -#endif - - - -int wolfSSL_RAND_load_file(const char* fname, long len) +void* wolfSSL_GetDhAgreeCtx(WOLFSSL* ssl) { - (void)fname; - /* wolfCrypt provides enough entropy internally or will report error */ - if (len == -1) - return 1024; - else - return (int)len; -} - + if (ssl) + return ssl->DhAgreeCtx; -#ifndef NO_WOLFSSL_STUB -WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void) -{ - WOLFSSL_STUB("COMP_zlib"); - return 0; + return NULL; } -#endif +#endif /* HAVE_PK_CALLBACKS && !NO_DH */ -#ifndef NO_WOLFSSL_STUB -WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void) -{ - WOLFSSL_STUB("COMP_rle"); - return 0; -} -#endif +#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF) -#ifndef NO_WOLFSSL_STUB -int wolfSSL_COMP_add_compression_method(int method, void* data) +void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb) { - (void)method; - (void)data; - WOLFSSL_STUB("COMP_add_compression_method"); - return 0; + if (ctx) + ctx->HkdfExtractCb = cb; } -#endif -/* wolfSSL_set_dynlock_create_callback - * CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1. - * This function exists for compatibility purposes because wolfSSL satisfies - * thread safety without relying on the callback. - */ -void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)( - const char*, int)) -{ - WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback"); - (void)f; -} -/* wolfSSL_set_dynlock_lock_callback - * CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1. - * This function exists for compatibility purposes because wolfSSL satisfies - * thread safety without relying on the callback. - */ -void wolfSSL_set_dynlock_lock_callback( - void (*f)(int, WOLFSSL_dynlock_value*, const char*, int)) -{ - WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback"); - (void)f; -} -/* wolfSSL_set_dynlock_destroy_callback - * CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1. - * This function exists for compatibility purposes because wolfSSL satisfies - * thread safety without relying on the callback. - */ -void wolfSSL_set_dynlock_destroy_callback( - void (*f)(WOLFSSL_dynlock_value*, const char*, int)) +void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx) { - WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback"); - (void)f; + if (ssl) + ssl->HkdfExtractCtx = ctx; } - -#endif /* OPENSSL_EXTRA */ - -#ifdef OPENSSL_EXTRA -#ifndef NO_CERTS - -#if !defined(NO_ASN) && !defined(NO_PWDBASED) -/* Copies unencrypted DER key buffer into "der". If "der" is null then the size - * of buffer needed is returned. If *der == NULL then it allocates a buffer. - * NOTE: This also advances the "der" pointer to be at the end of buffer. - * - * Returns size of key buffer on success - */ -int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der) +void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) { - return wolfSSL_EVP_PKEY_get_der(key, der); + if (ssl) + return ssl->HkdfExtractCtx; + + return NULL; } +#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */ -int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) -{ -#if !defined(NO_RSA) || defined(HAVE_ECC) -#ifdef HAVE_ECC - unsigned char *local_der = NULL; - word32 local_derSz = 0; - unsigned char *pub_der = NULL; - ecc_key *eccKey = NULL; - word32 inOutIdx = 0; +#ifdef WOLFSSL_HAVE_WOLFSCEP + /* Used by autoconf to see if wolfSCEP is available */ + void wolfSSL_wolfSCEP(void) {} #endif - word32 pub_derSz = 0; - int ret; - int key_type = 0; - if (key == NULL) { - return WOLFSSL_FATAL_ERROR; - } - - key_type = key->type; - if ((key_type != EVP_PKEY_EC) && (key_type != EVP_PKEY_RSA)) { - return WOLFSSL_FATAL_ERROR; - } -#ifndef NO_RSA - if (key_type == EVP_PKEY_RSA) { - return wolfSSL_i2d_RSAPublicKey(key->rsa, der); - } +#ifdef WOLFSSL_HAVE_CERT_SERVICE + /* Used by autoconf to see if cert service is available */ + void wolfSSL_cert_service(void) {} #endif - /* Now that RSA is taken care of, we only need to consider the ECC case. */ +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ + !defined(WOLFCRYPT_ONLY) -#ifdef HAVE_ECC + /* NID variables are dependent on compatibility header files currently + * + * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL + * on fail + */ - /* We need to get the DER, then convert it to a public key. But what we get - * might be a buffered private key so we need to decode it and then encode - * the public part. */ - ret = wolfSSL_EVP_PKEY_get_der(key, &local_der); - if (ret <= 0) { - /* In this case, there was no buffered DER at all. This could be the - * case where the key that was passed in was generated. So now we - * have to create the local DER. */ - local_derSz = wolfSSL_i2d_ECPrivateKey(key->ecc, &local_der); - if (local_derSz == 0) { - ret = WOLFSSL_FATAL_ERROR; - } - } else { - local_derSz = ret; - ret = 0; + WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id) + { + return wolfSSL_OBJ_nid2obj_ex(id, NULL); } - if (ret == 0) { - eccKey = (ecc_key *)XMALLOC(sizeof(*eccKey), NULL, DYNAMIC_TYPE_ECC); - if (eccKey == NULL) { - WOLFSSL_MSG("Failed to allocate key buffer."); - ret = WOLFSSL_FATAL_ERROR; - } - } - if (ret == 0) { - ret = wc_ecc_init(eccKey); - } + WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id, + WOLFSSL_ASN1_OBJECT* arg_obj) + { + word32 oidSz = 0; + int nid = 0; + const byte* oid; + word32 type = 0; + WOLFSSL_ASN1_OBJECT* obj = arg_obj; + byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */ + word32 objSz = 0; + const char* sName = NULL; + int i; - if (ret == 0) { - ret = wc_EccPublicKeyDecode(local_der, &inOutIdx, eccKey, local_derSz); - if (ret < 0) { - /* We now try again as x.963 [point type][x][opt y]. */ - ret = wc_ecc_import_x963(local_der, local_derSz, eccKey); - } - } +#ifdef WOLFSSL_DEBUG_OPENSSL + WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj"); +#endif - if (ret == 0) { - pub_derSz = wc_EccPublicKeyDerSize(eccKey, 0); - if ((int)pub_derSz <= 0) { - ret = WOLFSSL_FAILURE; + for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) { + if (wolfssl_object_info[i].nid == id) { + nid = id; + id = wolfssl_object_info[i].id; + sName = wolfssl_object_info[i].sName; + type = wolfssl_object_info[i].type; + break; + } } - } - - if (ret == 0) { - pub_der = (unsigned char*)XMALLOC(pub_derSz, NULL, - DYNAMIC_TYPE_PUBLIC_KEY); - if (pub_der == NULL) { - WOLFSSL_MSG("Failed to allocate output buffer."); - ret = WOLFSSL_FATAL_ERROR; + if (i == (int)WOLFSSL_OBJECT_INFO_SZ) { + WOLFSSL_MSG("NID not in table"); + #ifdef WOLFSSL_QT + sName = NULL; + type = (word32)id; + #else + return NULL; + #endif } - } - if (ret == 0) { - pub_derSz = wc_EccPublicKeyToDer(eccKey, pub_der, pub_derSz, 0); - if ((int)pub_derSz <= 0) { - ret = WOLFSSL_FATAL_ERROR; - } - } + #ifdef HAVE_ECC + if (type == 0 && wc_ecc_get_oid((word32)id, &oid, &oidSz) > 0) { + type = oidCurveType; + } + #endif /* HAVE_ECC */ - /* This block is for actually returning the DER of the public key */ - if ((ret == 0) && (der != NULL)) { - if (*der == NULL) { - *der = (unsigned char*)XMALLOC(pub_derSz, NULL, - DYNAMIC_TYPE_PUBLIC_KEY); - if (*der == NULL) { - WOLFSSL_MSG("Failed to allocate output buffer."); - ret = WOLFSSL_FATAL_ERROR; + if (sName != NULL) { + if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) { + WOLFSSL_MSG("Attempted short name is too large"); + return NULL; } + } - if (ret == 0) { - XMEMCPY(*der, pub_der, pub_derSz); + oid = OidFromId((word32)id, type, &oidSz); + + /* set object ID to buffer */ + if (obj == NULL){ + obj = wolfSSL_ASN1_OBJECT_new(); + if (obj == NULL) { + WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); + return NULL; } } - else { - XMEMCPY(*der, pub_der, pub_derSz); - *der += pub_derSz; + obj->nid = nid; + obj->type = id; + obj->grp = (int)type; + + obj->sName[0] = '\0'; + if (sName != NULL) { + XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName)); } - } - XFREE(pub_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(local_der, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + objBuf[0] = ASN_OBJECT_ID; objSz++; + objSz += SetLength(oidSz, objBuf + 1); + if (oidSz) { + XMEMCPY(objBuf + objSz, oid, oidSz); + objSz += oidSz; + } - wc_ecc_free(eccKey); - XFREE(eccKey, NULL, DYNAMIC_TYPE_ECC); + if (obj->objSz == 0 || objSz != obj->objSz) { + obj->objSz = objSz; + if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || + (obj->obj == NULL)) { + if (obj->obj != NULL) + XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1); + obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1); + if (obj->obj == NULL) { + wolfSSL_ASN1_OBJECT_free(obj); + return NULL; + } + obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; + } + else { + obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA; + } + } + XMEMCPY((byte*)obj->obj, objBuf, obj->objSz); -#else - ret = WOLFSSL_FATAL_ERROR; -#endif /* HAVE_ECC */ + (void)type; - if (ret == 0) { - return pub_derSz; + return obj; } - return ret; -#else - return WOLFSSL_FATAL_ERROR; -#endif /* !NO_RSA || HAVE_ECC */ -} -#endif /* !NO_ASN && !NO_PWDBASED */ + static const char* oid_translate_num_to_str(const char* oid) + { + const struct oid_dict { + const char* num; + const char* desc; + } oid_dict[] = { + { "2.5.29.37.0", "Any Extended Key Usage" }, + { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" }, + { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" }, + { "1.3.6.1.5.5.7.3.3", "Code Signing" }, + { "1.3.6.1.5.5.7.3.4", "E-mail Protection" }, + { "1.3.6.1.5.5.7.3.8", "Time Stamping" }, + { "1.3.6.1.5.5.7.3.9", "OCSP Signing" }, + { NULL, NULL } + }; + const struct oid_dict* idx; -#endif /* !NO_CERTS */ -#endif /* OPENSSL_EXTRA */ + for (idx = oid_dict; idx->num != NULL; idx++) { + if (!XSTRCMP(oid, idx->num)) { + return idx->desc; + } + } + return NULL; + } -#ifdef OPENSSL_EXTRA + static int wolfssl_obj2txt_numeric(char *buf, int bufLen, + const WOLFSSL_ASN1_OBJECT *a) + { + int bufSz; + int length; + word32 idx = 0; + byte tag; -/* Sets the DNS hostname to name. - * Hostname is cleared if name is NULL or empty. */ -int wolfSSL_set1_host(WOLFSSL * ssl, const char* name) -{ - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } + if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) { + return WOLFSSL_FAILURE; + } - return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0); -} + if (tag != ASN_OBJECT_ID) { + WOLFSSL_MSG("Bad ASN1 Object"); + return WOLFSSL_FAILURE; + } -/****************************************************************************** -* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters -* -* RETURNS: -* WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE -* Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL, -* same as openssl. -*/ -int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm) -{ - if (ctx == NULL || vpm == NULL) - return WOLFSSL_SUCCESS; + if (GetLength((const byte*)a->obj, &idx, &length, + a->objSz) < 0 || length < 0) { + return ASN_PARSE_E; + } - return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm); -} + if (bufLen < MAX_OID_STRING_SZ) { + bufSz = bufLen - 1; + } + else { + bufSz = MAX_OID_STRING_SZ; + } -/****************************************************************************** -* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters -* -* RETURNS: -* returns pointer to the SSL verification parameters on success, -* otherwise returns NULL -*/ -WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx) -{ - if (ctx == NULL) { - return NULL; - } + if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx, + (word32)length)) <= 0) { + WOLFSSL_MSG("Error decoding OID"); + return WOLFSSL_FAILURE; + } - return ctx->param; -} + buf[bufSz] = '\0'; -WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl) -{ - if (ssl == NULL) { - return NULL; + return bufSz; } - return ssl->param; -} -#endif /* OPENSSL_EXTRA */ + /* If no_name is one then use numerical form, otherwise short name. + * + * Returns the buffer size on success, WOLFSSL_FAILURE on error + */ + int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a, + int no_name) + { + int bufSz; + const char* desc; + const char* name; -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -/* Gets an index to store SSL structure at. - * - * Returns positive index on success and negative values on failure - */ -int wolfSSL_get_ex_data_X509_STORE_CTX_idx(void) -{ - WOLFSSL_ENTER("wolfSSL_get_ex_data_X509_STORE_CTX_idx"); + WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt"); - /* store SSL at index 0 */ - return 0; -} -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ + if (buf == NULL || bufLen <= 1 || a == NULL) { + WOLFSSL_MSG("Bad input argument"); + return WOLFSSL_FAILURE; + } -#ifdef OPENSSL_EXTRA -/* Sets a function callback that will send information about the state of all - * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed - * in. - * - * ctx WOLFSSL_CTX structure to set callback function in - * f callback function to use - */ -void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx, - void (*f)(const WOLFSSL* ssl, int type, int val)) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback"); - if (ctx == NULL) { - WOLFSSL_MSG("Bad function argument"); - } - else { - ctx->CBIS = f; - } -} + if (no_name == 1) { + return wolfssl_obj2txt_numeric(buf, bufLen, a); + } -void wolfSSL_set_info_callback(WOLFSSL* ssl, - void (*f)(const WOLFSSL* ssl, int type, int val)) -{ - WOLFSSL_ENTER("wolfSSL_set_info_callback"); - if (ssl == NULL) { - WOLFSSL_MSG("Bad function argument"); + /* return long name unless using x509small, then return short name */ +#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA) + name = a->sName; +#else + name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a)); +#endif + + if (name == NULL) { + WOLFSSL_MSG("Name not found"); + bufSz = 0; + } + else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) { + bufSz = (int)XSTRLEN(name); + } + else { + bufSz = bufLen - 1; + } + if (bufSz) { + XMEMCPY(buf, name, bufSz); + } + else if (a->type == GEN_DNS || a->type == GEN_EMAIL || + a->type == GEN_URI) { + bufSz = (int)XSTRLEN((const char*)a->obj); + XMEMCPY(buf, a->obj, min((word32)bufSz, (word32)bufLen)); + } + else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) { + if ((desc = oid_translate_num_to_str(buf))) { + bufSz = (int)XSTRLEN(desc); + bufSz = (int)min((word32)bufSz,(word32) bufLen - 1); + XMEMCPY(buf, desc, bufSz); + } + } + else { + bufSz = 0; + } + + buf[bufSz] = '\0'; + + return bufSz; } - else { - ssl->CBIS = f; +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL) + /* Returns the long name that corresponds with an ASN1_OBJECT nid value. + * n : NID value of ASN1_OBJECT to search */ + const char* wolfSSL_OBJ_nid2ln(int n) + { + const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; + size_t i; + WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln"); + for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { + if (obj_info->nid == n) { + return obj_info->lName; + } + } + WOLFSSL_MSG("NID not found in table"); + return NULL; } -} +#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL, + WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */ +#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ + defined(WOLFSSL_HAPROXY) + /* Return the corresponding short name for the nid . + * or NULL if short name can't be found. + */ + const char * wolfSSL_OBJ_nid2sn(int n) { + const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; + size_t i; + WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn"); -unsigned long wolfSSL_ERR_peek_error(void) -{ - WOLFSSL_ENTER("wolfSSL_ERR_peek_error"); + if (n == NID_md5) { + /* NID_surname == NID_md5 and NID_surname comes before NID_md5 in + * wolfssl_object_info. As a result, the loop below will incorrectly + * return "SN" instead of "MD5." NID_surname isn't the true OpenSSL + * NID, but other functions rely on this table and modifying it to + * conform with OpenSSL's NIDs isn't trivial. */ + return "MD5"; + } + for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { + if (obj_info->nid == n) { + return obj_info->sName; + } + } + WOLFSSL_MSG_EX("SN not found (nid:%d)",n); + return NULL; + } - return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL); -} +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + int wolfSSL_OBJ_sn2nid(const char *sn) { + WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid"); + if (sn == NULL) + return NID_undef; + return wc_OBJ_sn2nid(sn); + } +#endif -int wolfSSL_ERR_GET_LIB(unsigned long err) -{ - unsigned long value; + size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o) + { + size_t ret = 0; + int err = 0; + word32 idx = 0; + int len = 0; - value = (err & 0xFFFFFFL); - switch (value) { - case -SSL_R_HTTP_REQUEST: - return ERR_LIB_SSL; - case -ASN_NO_PEM_HEADER: - case PEM_R_NO_START_LINE: - case PEM_R_PROBLEMS_GETTING_PASSWORD: - case PEM_R_BAD_PASSWORD_READ: - case PEM_R_BAD_DECRYPT: - return ERR_LIB_PEM; - case EVP_R_BAD_DECRYPT: - case EVP_R_BN_DECODE_ERROR: - case EVP_R_DECODE_ERROR: - case EVP_R_PRIVATE_KEY_DECODE_ERROR: - return ERR_LIB_EVP; - case ASN1_R_HEADER_TOO_LONG: - return ERR_LIB_ASN1; - default: - return 0; - } -} + WOLFSSL_ENTER("wolfSSL_OBJ_length"); -/* This function is to find global error values that are the same through out - * all library version. With wolfSSL having only one set of error codes the - * return value is pretty straight forward. The only thing needed is all wolfSSL - * error values are typically negative. - * - * Returns the error reason - */ -int wolfSSL_ERR_GET_REASON(unsigned long err) -{ - int ret = (int)err; + if (o == NULL || o->obj == NULL) { + WOLFSSL_MSG("Bad argument."); + err = 1; + } - WOLFSSL_ENTER("wolfSSL_ERR_GET_REASON"); + if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) { + WOLFSSL_MSG("Error parsing ASN.1 header."); + err = 1; + } + if (err == 0) { + ret = (size_t)len; + } -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - /* Nginx looks for this error to know to stop parsing certificates. - * Same for HAProxy. */ - if (err == ((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE) || - ((err & 0xFFFFFFL) == -ASN_NO_PEM_HEADER) || - ((err & 0xFFFL) == PEM_R_NO_START_LINE )) - return PEM_R_NO_START_LINE; - if (err == ((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST)) - return SSL_R_HTTP_REQUEST; -#endif -#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - if (err == ((ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG)) - return ASN1_R_HEADER_TOO_LONG; -#endif + WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret); - /* check if error value is in range of wolfSSL errors */ - ret = 0 - ret; /* setting as negative value */ - /* wolfCrypt range is less than MAX (-100) - wolfSSL range is MIN (-300) and lower */ - if (ret < MAX_CODE_E && ret > MIN_CODE_E) { return ret; } - else { - WOLFSSL_MSG("Not in range of typical error values"); - ret = (int)err; - } - return ret; -} + const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o) + { + const unsigned char* ret = NULL; + int err = 0; + word32 idx = 0; + int len = 0; -/* returns a string that describes the alert - * - * alertID the alert value to look up - */ -const char* wolfSSL_alert_type_string_long(int alertID) -{ - WOLFSSL_ENTER("wolfSSL_alert_type_string_long"); + WOLFSSL_ENTER("wolfSSL_OBJ_get0_data"); - return AlertTypeToString(alertID); -} + if (o == NULL || o->obj == NULL) { + WOLFSSL_MSG("Bad argument."); + err = 1; + } + if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) { + WOLFSSL_MSG("Error parsing ASN.1 header."); + err = 1; + } + if (err == 0) { + ret = o->obj + idx; + } -const char* wolfSSL_alert_desc_string_long(int alertID) -{ - WOLFSSL_ENTER("wolfSSL_alert_desc_string_long"); + return ret; + } - return AlertTypeToString(alertID); -} -#define STATE_STRINGS_PROTO(s) \ - { \ - {"SSLv3 " s, \ - "SSLv3 " s, \ - "SSLv3 " s}, \ - {"TLSv1 " s, \ - "TLSv1 " s, \ - "TLSv1 " s}, \ - {"TLSv1_1 " s, \ - "TLSv1_1 " s, \ - "TLSv1_1 " s}, \ - {"TLSv1_2 " s, \ - "TLSv1_2 " s, \ - "TLSv1_2 " s}, \ - {"TLSv1_3 " s, \ - "TLSv1_3 " s, \ - "TLSv1_3 " s}, \ - {"DTLSv1 " s, \ - "DTLSv1 " s, \ - "DTLSv1 " s}, \ - {"DTLSv1_2 " s, \ - "DTLSv1_2 " s, \ - "DTLSv1_2 " s}, \ - {"DTLSv1_3 " s, \ - "DTLSv1_3 " s, \ - "DTLSv1_3 " s}, \ - } + /* Gets the NID value that corresponds with the ASN1 object. + * + * o ASN1 object to get NID of + * + * Return NID on success and a negative value on failure + */ + int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o) + { + word32 oid = 0; + word32 idx = 0; + int ret; -#define STATE_STRINGS_PROTO_RW(s) \ - { \ - {"SSLv3 read " s, \ - "SSLv3 write " s, \ - "SSLv3 " s}, \ - {"TLSv1 read " s, \ - "TLSv1 write " s, \ - "TLSv1 " s}, \ - {"TLSv1_1 read " s, \ - "TLSv1_1 write " s, \ - "TLSv1_1 " s}, \ - {"TLSv1_2 read " s, \ - "TLSv1_2 write " s, \ - "TLSv1_2 " s}, \ - {"TLSv1_3 read " s, \ - "TLSv1_3 write " s, \ - "TLSv1_3 " s}, \ - {"DTLSv1 read " s, \ - "DTLSv1 write " s, \ - "DTLSv1 " s}, \ - {"DTLSv1_2 read " s, \ - "DTLSv1_2 write " s, \ - "DTLSv1_2 " s}, \ - {"DTLSv1_3 read " s, \ - "DTLSv1_3 write " s, \ - "DTLSv1_3 " s}, \ - } +#ifdef WOLFSSL_DEBUG_OPENSSL + WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid"); +#endif -/* Gets the current state of the WOLFSSL structure - * - * ssl WOLFSSL structure to get state of - * - * Returns a human readable string of the WOLFSSL structure state - */ -const char* wolfSSL_state_string_long(const WOLFSSL* ssl) -{ + if (o == NULL) { + return -1; + } - static const char* OUTPUT_STR[24][8][3] = { - STATE_STRINGS_PROTO("Initialization"), - STATE_STRINGS_PROTO_RW("Server Hello Request"), - STATE_STRINGS_PROTO_RW("Server Hello Verify Request"), - STATE_STRINGS_PROTO_RW("Server Hello Retry Request"), - STATE_STRINGS_PROTO_RW("Server Hello"), - STATE_STRINGS_PROTO_RW("Server Certificate Status"), - STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"), - STATE_STRINGS_PROTO_RW("Server Session Ticket"), - STATE_STRINGS_PROTO_RW("Server Certificate Request"), - STATE_STRINGS_PROTO_RW("Server Cert"), - STATE_STRINGS_PROTO_RW("Server Key Exchange"), - STATE_STRINGS_PROTO_RW("Server Hello Done"), - STATE_STRINGS_PROTO_RW("Server Change CipherSpec"), - STATE_STRINGS_PROTO_RW("Server Finished"), - STATE_STRINGS_PROTO_RW("server Key Update"), - STATE_STRINGS_PROTO_RW("Client Hello"), - STATE_STRINGS_PROTO_RW("Client Key Exchange"), - STATE_STRINGS_PROTO_RW("Client Cert"), - STATE_STRINGS_PROTO_RW("Client Change CipherSpec"), - STATE_STRINGS_PROTO_RW("Client Certificate Verify"), - STATE_STRINGS_PROTO_RW("Client End Of Early Data"), - STATE_STRINGS_PROTO_RW("Client Finished"), - STATE_STRINGS_PROTO_RW("Client Key Update"), - STATE_STRINGS_PROTO("Handshake Done"), - }; - enum ProtocolVer { - SSL_V3 = 0, - TLS_V1, - TLS_V1_1, - TLS_V1_2, - TLS_V1_3, - DTLS_V1, - DTLS_V1_2, - DTLS_V1_3, - UNKNOWN = 100 - }; + #ifdef WOLFSSL_QT + if (o->grp == oidCertExtType) { + /* If nid is an unknown extension, return NID_undef */ + if (wolfSSL_OBJ_nid2sn(o->nid) == NULL) + return NID_undef; + } + #endif - enum IOMode { - SS_READ = 0, - SS_WRITE, - SS_NEITHER - }; + if (o->nid > 0) + return o->nid; + if ((ret = GetObjectId(o->obj, &idx, &oid, o->grp, o->objSz)) < 0) { + if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) { + /* Put ASN object tag in front and try again */ + int len = SetObjectId(o->objSz, NULL) + o->objSz; + byte* buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (!buf) { + WOLFSSL_MSG("malloc error"); + return -1; + } + idx = SetObjectId(o->objSz, buf); + XMEMCPY(buf + idx, o->obj, o->objSz); + idx = 0; + ret = GetObjectId(buf, &idx, &oid, o->grp, len); + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (ret < 0) { + WOLFSSL_MSG("Issue getting OID of object"); + return -1; + } + } + else { + WOLFSSL_MSG("Issue getting OID of object"); + return -1; + } + } - enum SslState { - ss_null_state = 0, - ss_server_hellorequest, - ss_server_helloverify, - ss_server_helloretryrequest, - ss_server_hello, - ss_server_certificatestatus, - ss_server_encryptedextensions, - ss_server_sessionticket, - ss_server_certrequest, - ss_server_cert, - ss_server_keyexchange, - ss_server_hellodone, - ss_server_changecipherspec, - ss_server_finished, - ss_server_keyupdate, - ss_client_hello, - ss_client_keyexchange, - ss_client_cert, - ss_client_changecipherspec, - ss_client_certverify, - ss_client_endofearlydata, - ss_client_finished, - ss_client_keyupdate, - ss_handshake_done - }; + return oid2nid(oid, o->grp); + } - int protocol = 0; - int cbmode = 0; - int state = 0; + /* Return the corresponding NID for the long name + * or NID_undef if NID can't be found. + */ + int wolfSSL_OBJ_ln2nid(const char *ln) + { + const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; + size_t lnlen; + WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid"); + if (ln && (lnlen = XSTRLEN(ln)) > 0) { + /* Accept input like "/commonName=" */ + if (ln[0] == '/') { + ln++; + lnlen--; + } + if (lnlen) { + size_t i; - WOLFSSL_ENTER("wolfSSL_state_string_long"); - if (ssl == NULL) { - WOLFSSL_MSG("Null argument passed in"); - return NULL; + if (ln[lnlen-1] == '=') { + lnlen--; + } + for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { + if (lnlen == XSTRLEN(obj_info->lName) && + XSTRNCMP(ln, obj_info->lName, lnlen) == 0) { + return obj_info->nid; + } + } + } + } + return NID_undef; } - /* Get state of callback */ - if (ssl->cbmode == SSL_CB_MODE_WRITE) { - cbmode = SS_WRITE; - } - else if (ssl->cbmode == SSL_CB_MODE_READ) { - cbmode = SS_READ; - } - else { - cbmode = SS_NEITHER; - } + /* compares two objects, return 0 if equal */ + int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a, + const WOLFSSL_ASN1_OBJECT* b) + { + WOLFSSL_ENTER("wolfSSL_OBJ_cmp"); - /* Get protocol version */ - switch (ssl->version.major) { - case SSLv3_MAJOR: - switch (ssl->version.minor) { - case SSLv3_MINOR: - protocol = SSL_V3; - break; - case TLSv1_MINOR: - protocol = TLS_V1; - break; - case TLSv1_1_MINOR: - protocol = TLS_V1_1; - break; - case TLSv1_2_MINOR: - protocol = TLS_V1_2; - break; - case TLSv1_3_MINOR: - protocol = TLS_V1_3; - break; - default: - protocol = UNKNOWN; + if (a && b && a->obj && b->obj) { + if (a->objSz == b->objSz) { + return XMEMCMP(a->obj, b->obj, a->objSz); } - break; - case DTLS_MAJOR: - switch (ssl->version.minor) { - case DTLS_MINOR: - protocol = DTLS_V1; - break; - case DTLSv1_2_MINOR: - protocol = DTLS_V1_2; - break; - case DTLSv1_3_MINOR: - protocol = DTLS_V1_3; - break; - default: - protocol = UNKNOWN; + else if (a->type == EXT_KEY_USAGE_OID || + b->type == EXT_KEY_USAGE_OID) { + /* Special case for EXT_KEY_USAGE_OID so that + * cmp will be treated as a substring search */ + /* Used in libest to check for id-kp-cmcRA in + * EXT_KEY_USAGE extension */ + unsigned int idx; + const byte* s; /* shorter */ + unsigned int sLen; + const byte* l; /* longer */ + unsigned int lLen; + if (a->objSz > b->objSz) { + s = b->obj; sLen = b->objSz; + l = a->obj; lLen = a->objSz; + } + else { + s = a->obj; sLen = a->objSz; + l = b->obj; lLen = b->objSz; + } + for (idx = 0; idx <= lLen - sLen; idx++) { + if (XMEMCMP(l + idx, s, sLen) == 0) { + /* Found substring */ + return 0; + } + } } - break; - default: - protocol = UNKNOWN; - } - - /* accept process */ - if (ssl->cbmode == SSL_CB_MODE_READ) { - state = ssl->cbtype; - switch (state) { - case hello_request: - state = ss_server_hellorequest; - break; - case client_hello: - state = ss_client_hello; - break; - case server_hello: - state = ss_server_hello; - break; - case hello_verify_request: - state = ss_server_helloverify; - break; - case session_ticket: - state = ss_server_sessionticket; - break; - case end_of_early_data: - state = ss_client_endofearlydata; - break; - case hello_retry_request: - state = ss_server_helloretryrequest; - break; - case encrypted_extensions: - state = ss_server_encryptedextensions; - break; - case certificate: - if (ssl->options.side == WOLFSSL_SERVER_END) - state = ss_client_cert; - else if (ssl->options.side == WOLFSSL_CLIENT_END) - state = ss_server_cert; - else { - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; - } - break; - case server_key_exchange: - state = ss_server_keyexchange; - break; - case certificate_request: - state = ss_server_certrequest; - break; - case server_hello_done: - state = ss_server_hellodone; - break; - case certificate_verify: - state = ss_client_certverify; - break; - case client_key_exchange: - state = ss_client_keyexchange; - break; - case finished: - if (ssl->options.side == WOLFSSL_SERVER_END) - state = ss_client_finished; - else if (ssl->options.side == WOLFSSL_CLIENT_END) - state = ss_server_finished; - else { - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; - } - break; - case certificate_status: - state = ss_server_certificatestatus; - break; - case key_update: - if (ssl->options.side == WOLFSSL_SERVER_END) - state = ss_client_keyupdate; - else if (ssl->options.side == WOLFSSL_CLIENT_END) - state = ss_server_keyupdate; - else { - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; - } - break; - case change_cipher_hs: - if (ssl->options.side == WOLFSSL_SERVER_END) - state = ss_client_changecipherspec; - else if (ssl->options.side == WOLFSSL_CLIENT_END) - state = ss_server_changecipherspec; - else { - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; - } - break; - default: - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; - } - } - else { - /* Send process */ - if (ssl->options.side == WOLFSSL_SERVER_END) - state = ssl->options.serverState; - else - state = ssl->options.clientState; - - switch (state) { - case SERVER_HELLOVERIFYREQUEST_COMPLETE: - state = ss_server_helloverify; - break; - case SERVER_HELLO_RETRY_REQUEST_COMPLETE: - state = ss_server_helloretryrequest; - break; - case SERVER_HELLO_COMPLETE: - state = ss_server_hello; - break; - case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE: - state = ss_server_encryptedextensions; - break; - case SERVER_CERT_COMPLETE: - state = ss_server_cert; - break; - case SERVER_KEYEXCHANGE_COMPLETE: - state = ss_server_keyexchange; - break; - case SERVER_HELLODONE_COMPLETE: - state = ss_server_hellodone; - break; - case SERVER_CHANGECIPHERSPEC_COMPLETE: - state = ss_server_changecipherspec; - break; - case SERVER_FINISHED_COMPLETE: - state = ss_server_finished; - break; - case CLIENT_HELLO_RETRY: - case CLIENT_HELLO_COMPLETE: - state = ss_client_hello; - break; - case CLIENT_KEYEXCHANGE_COMPLETE: - state = ss_client_keyexchange; - break; - case CLIENT_CHANGECIPHERSPEC_COMPLETE: - state = ss_client_changecipherspec; - break; - case CLIENT_FINISHED_COMPLETE: - state = ss_client_finished; - break; - case HANDSHAKE_DONE: - state = ss_handshake_done; - break; - default: - WOLFSSL_MSG("Unknown State"); - state = ss_null_state; } - } - if (protocol == UNKNOWN) { - WOLFSSL_MSG("Unknown protocol"); - return ""; - } - else { - return OUTPUT_STR[state][protocol][cbmode]; + return WOLFSSL_FATAL_ERROR; } -} +#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL, + WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ + defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY) + /* Gets the NID value that is related to the OID string passed in. Example + * string would be "2.5.29.14" for subject key ID. + * + * returns NID value on success and NID_undef on error + */ + int wolfSSL_OBJ_txt2nid(const char* s) + { + unsigned int i; + #ifdef WOLFSSL_CERT_EXT + int ret; + unsigned int sum = 0; + unsigned int outSz = MAX_OID_SZ; + unsigned char out[MAX_OID_SZ]; + #endif -/* - * Sets default PEM callback password if null is passed into - * the callback parameter of a PEM_read_bio_* function. - * - * Returns callback phrase size on success or WOLFSSL_FAILURE otherwise. - */ -int wolfSSL_PEM_def_callback(char* name, int num, int w, void* key) -{ - (void)w; - WOLFSSL_ENTER("wolfSSL_PEM_def_callback"); + WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid"); - /* We assume that the user passes a default password as userdata */ - if (key) { - int sz = (int)XSTRLEN((const char*)key); - sz = (sz > num) ? num : sz; - XMEMCPY(name, key, sz); - return sz; - } else { - WOLFSSL_MSG("Error, default password cannot be created."); - return WOLFSSL_FAILURE; - } -} + if (s == NULL) { + return NID_undef; + } -#endif /* OPENSSL_EXTRA */ + #ifdef WOLFSSL_CERT_EXT + ret = EncodePolicyOID(out, &outSz, s, NULL); + if (ret == 0) { + /* sum OID */ + for (i = 0; i < outSz; i++) { + sum += out[i]; + } + } + #endif /* WOLFSSL_CERT_EXT */ -static long wolf_set_options(long old_op, long op) -{ - /* if SSL_OP_ALL then turn all bug workarounds on */ - if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) { - WOLFSSL_MSG("\tSSL_OP_ALL"); - } + /* get the group that the OID's sum is in + * @TODO possible conflict with multiples */ + for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) { + int len; + #ifdef WOLFSSL_CERT_EXT + if (ret == 0) { + if (wolfssl_object_info[i].id == (int)sum) { + return wolfssl_object_info[i].nid; + } + } + #endif - /* by default cookie exchange is on with DTLS */ - if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) { - WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default"); - } + /* try as a short name */ + len = (int)XSTRLEN(s); + if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len && + XSTRNCMP(wolfssl_object_info[i].sName, s, len) == 0) { + return wolfssl_object_info[i].nid; + } - if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) { - WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2"); - } + /* try as a long name */ + if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len && + XSTRNCMP(wolfssl_object_info[i].lName, s, len) == 0) { + return wolfssl_object_info[i].nid; + } + } -#ifdef SSL_OP_NO_TLSv1_3 - if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { - WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3"); + return NID_undef; } #endif +#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ + defined(WOLFSSL_HAPROXY) - if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) { - WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2"); - } - - if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) { - WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1"); - } - - if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) { - WOLFSSL_MSG("\tSSL_OP_NO_TLSv1"); - } - - if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) { - WOLFSSL_MSG("\tSSL_OP_NO_SSLv3"); - } - - if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) == - WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) { - WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE"); - } - - if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) { - #ifdef HAVE_LIBZ - WOLFSSL_MSG("SSL_OP_NO_COMPRESSION"); - #else - WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in"); - #endif - } - - return old_op | op; -} + /* Creates new ASN1_OBJECT from short name, long name, or text + * representation of oid. If no_name is 0, then short name, long name, and + * numerical value of oid are interpreted. If no_name is 1, then only the + * numerical value of the oid is interpreted. + * + * Returns pointer to ASN1_OBJECT on success, or NULL on error. + */ +#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN) + WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name) + { + int i, ret; + int nid = NID_undef; + unsigned int outSz = MAX_OID_SZ; + unsigned char out[MAX_OID_SZ]; + WOLFSSL_ASN1_OBJECT* obj; -long wolfSSL_set_options(WOLFSSL* ssl, long op) -{ - word16 haveRSA = 1; - word16 havePSK = 0; - int keySz = 0; + WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj"); - WOLFSSL_ENTER("wolfSSL_set_options"); + if (s == NULL) + return NULL; - if (ssl == NULL) { - return 0; - } + /* If s is numerical value, try to sum oid */ + ret = EncodePolicyOID(out, &outSz, s, NULL); + if (ret == 0 && outSz > 0) { + /* If numerical encode succeeded then just + * create object from that because sums are + * not unique and can cause confusion. */ + obj = wolfSSL_ASN1_OBJECT_new(); + if (obj == NULL) { + WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); + return NULL; + } + obj->dynamic |= WOLFSSL_ASN1_DYNAMIC; + obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL, + DYNAMIC_TYPE_ASN1); + if (obj->obj == NULL) { + wolfSSL_ASN1_OBJECT_free(obj); + return NULL; + } + obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; + i = SetObjectId((int)outSz, (byte*)obj->obj); + XMEMCPY((byte*)obj->obj + i, out, outSz); + obj->objSz = i + outSz; + return obj; + } - ssl->options.mask = wolf_set_options(ssl->options.mask, op); + /* TODO: update short names in wolfssl_object_info and check OID sums + are correct */ + for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) { + /* Short name, long name, and numerical value are interpreted */ + if (no_name == 0 && + ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) || + (XSTRCMP(s, wolfssl_object_info[i].lName) == 0))) + { + nid = wolfssl_object_info[i].nid; + } + } - if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { - if (ssl->version.minor == TLSv1_3_MINOR) - ssl->version.minor = TLSv1_2_MINOR; - } + if (nid != NID_undef) + return wolfSSL_OBJ_nid2obj(nid); - if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) { - if (ssl->version.minor == TLSv1_2_MINOR) - ssl->version.minor = TLSv1_1_MINOR; + return NULL; } +#endif - if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) { - if (ssl->version.minor == TLSv1_1_MINOR) - ssl->version.minor = TLSv1_MINOR; + /* compatibility function. Its intended use is to remove OID's from an + * internal table that have been added with OBJ_create. wolfSSL manages its + * own internal OID values and does not currently support OBJ_create. */ + void wolfSSL_OBJ_cleanup(void) + { + WOLFSSL_ENTER("wolfSSL_OBJ_cleanup"); } - if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) { - if (ssl->version.minor == TLSv1_MINOR) - ssl->version.minor = SSLv3_MINOR; + #ifndef NO_WOLFSSL_STUB + int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln) + { + (void)oid; + (void)sn; + (void)ln; + WOLFSSL_STUB("wolfSSL_OBJ_create"); + return WOLFSSL_FAILURE; } + #endif - if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION) - == WOLFSSL_OP_NO_COMPRESSION) { - #ifdef HAVE_LIBZ - ssl->options.usingCompression = 0; + void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth) + { + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_ENTER("wolfSSL_set_verify_depth"); + ssl->options.verifyDepth = (byte)depth; #endif } -#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \ - || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)) - if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { - ssl->options.noTicketTls12 = 1; - } -#endif +#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || + HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */ +#ifdef OPENSSL_EXTRA - /* in the case of a version change the cipher suites should be reset */ -#ifndef NO_PSK - havePSK = ssl->options.havePSK; -#endif -#ifdef NO_RSA - haveRSA = 0; -#endif -#ifndef NO_CERTS - keySz = ssl->buffers.keySz; -#endif +/* wolfSSL uses negative values for error states. This function returns an + * unsigned type so the value returned is the absolute value of the error. + */ +unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line) +{ + WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error"); - if (ssl->options.side != WOLFSSL_NEITHER_END) { - if (AllocateSuites(ssl) != 0) + (void)line; + (void)file; +#ifdef WOLFSSL_HAVE_ERROR_QUEUE + { + int ret; + + if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) { + WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; - InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, - ssl->options.haveDH, ssl->options.haveECDSAsig, - ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + } + #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \ + || defined(WOLFSSL_HAPROXY) + if (ret == -ASN_NO_PEM_HEADER) + return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; + #endif + #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) + if (ret == ASN1_R_HEADER_TOO_LONG) { + return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; + } + #endif + return (unsigned long)ret; } - - return ssl->options.mask; +#else + return (unsigned long)(0 - NOT_COMPILED_IN); +#endif } +#endif /* OPENSSL_EXTRA */ -long wolfSSL_get_options(const WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_options"); - if(ssl == NULL) - return WOLFSSL_FAILURE; - return ssl->options.mask; -} +#if defined(HAVE_EX_DATA) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ + defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ + defined(WOLFSSL_WPAS_SMALL) +CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL; -#if defined(HAVE_SECURE_RENEGOTIATION) \ - || defined(HAVE_SERVER_RENEGOTIATION_INFO) -/* clears the counter for number of renegotiations done - * returns the current count before it is cleared */ -long wolfSSL_clear_num_renegotiations(WOLFSSL *s) +static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr, + WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func) { - long total; - - WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations"); - if (s == NULL) - return 0; - - total = s->secure_rene_count; - s->secure_rene_count = 0; - return total; + CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC( + sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL); + if (new_ctx == NULL) + return -1; + new_ctx->ctx_l = ctx_l; + new_ctx->ctx_ptr = ctx_ptr; + new_ctx->new_func = new_func; + new_ctx->free_func = free_func; + new_ctx->dup_func = dup_func; + new_ctx->next = NULL; + /* Push to end of list */ + while (*dst != NULL) + dst = &(*dst)->next; + *dst = new_ctx; + return 0; } - -/* return the number of renegotiations since wolfSSL_new */ -long wolfSSL_total_renegotiations(WOLFSSL *s) +void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx) { - WOLFSSL_ENTER("wolfSSL_total_renegotiations"); - return wolfSSL_num_renegotiations(s); + while (cb_ctx != NULL) { + CRYPTO_EX_cb_ctx* next = cb_ctx->next; + XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL); + cb_ctx = next; + } } - -/* return the number of renegotiations since wolfSSL_new */ -long wolfSSL_num_renegotiations(WOLFSSL* s) +void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx, + WOLFSSL_CRYPTO_EX_DATA* ex_data) { - if (s == NULL) { - return 0; + int idx = 0; + for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { + if (cb_ctx->new_func != NULL) + cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l, + cb_ctx->ctx_ptr); } - - return s->secure_rene_count; } - -/* Is there a renegotiation currently in progress? */ -int wolfSSL_SSL_renegotiate_pending(WOLFSSL *s) +int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in, + WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx) { - return s && s->options.handShakeDone && - s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0; + int idx = 0; + for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { + if (cb_ctx->dup_func != NULL) { + void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx); + if (!cb_ctx->dup_func(out, in, + &ptr, idx, + cb_ctx->ctx_l, cb_ctx->ctx_ptr)) { + return WOLFSSL_FAILURE; + } + wolfSSL_CRYPTO_set_ex_data(out, idx, ptr); + } + } + return WOLFSSL_SUCCESS; } -#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */ - -#ifdef OPENSSL_EXTRA -long wolfSSL_clear_options(WOLFSSL* ssl, long opt) +void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx, + WOLFSSL_CRYPTO_EX_DATA* ex_data) { - WOLFSSL_ENTER("wolfSSL_clear_options"); - if(ssl == NULL) - return WOLFSSL_FAILURE; - ssl->options.mask &= ~opt; - return ssl->options.mask; + int idx = 0; + for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { + if (cb_ctx->free_func != NULL) + cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l, + cb_ctx->ctx_ptr); + } } -#ifdef HAVE_PK_CALLBACKS -long wolfSSL_set_tlsext_debug_arg(WOLFSSL* ssl, void *arg) +/** + * get_ex_new_index is a helper function for the following + * xx_get_ex_new_index functions: + * - wolfSSL_CRYPTO_get_ex_new_index + * - wolfSSL_CTX_get_ex_new_index + * - wolfSSL_get_ex_new_index + * Issues a unique index number for the specified class-index. + * Returns an index number greater or equal to zero on success, + * -1 on failure. + */ +int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, + WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func) { - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } + /* index counter for each class index*/ + static int ctx_idx = 0; + static int ssl_idx = 0; + static int ssl_session_idx = 0; + static int x509_idx = 0; - ssl->loggingCtx = arg; - return WOLFSSL_SUCCESS; -} -#endif /* HAVE_PK_CALLBACKS */ + int idx = -1; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) -const unsigned char *wolfSSL_SESSION_get0_id_context( - const WOLFSSL_SESSION *sess, unsigned int *sid_ctx_length) -{ - return wolfSSL_SESSION_get_id((WOLFSSL_SESSION *)sess, sid_ctx_length); -} -int wolfSSL_SESSION_set1_id(WOLFSSL_SESSION *s, - const unsigned char *sid, unsigned int sid_len) -{ - if (s == NULL) { - return WOLFSSL_FAILURE; - } - if (sid_len > ID_LEN) { - return WOLFSSL_FAILURE; - } - s->sessionIDSz = sid_len; - if (sid != s->sessionID) { - XMEMCPY(s->sessionID, sid, sid_len); + switch(class_index) { + case WOLF_CRYPTO_EX_INDEX_SSL: + WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, + dup_func, free_func); + idx = ssl_idx++; + break; + case WOLF_CRYPTO_EX_INDEX_SSL_CTX: + WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, + dup_func, free_func); + idx = ctx_idx++; + break; + case WOLF_CRYPTO_EX_INDEX_X509: + WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, + dup_func, free_func); + idx = x509_idx++; + break; + case WOLF_CRYPTO_EX_INDEX_SSL_SESSION: + if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr, + new_func, dup_func, free_func) != 0) + return -1; + idx = ssl_session_idx++; + break; + + /* following class indexes are not supoprted */ + case WOLF_CRYPTO_EX_INDEX_X509_STORE: + case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX: + case WOLF_CRYPTO_EX_INDEX_DH: + case WOLF_CRYPTO_EX_INDEX_DSA: + case WOLF_CRYPTO_EX_INDEX_EC_KEY: + case WOLF_CRYPTO_EX_INDEX_RSA: + case WOLF_CRYPTO_EX_INDEX_ENGINE: + case WOLF_CRYPTO_EX_INDEX_UI: + case WOLF_CRYPTO_EX_INDEX_BIO: + case WOLF_CRYPTO_EX_INDEX_APP: + case WOLF_CRYPTO_EX_INDEX_UI_METHOD: + case WOLF_CRYPTO_EX_INDEX_DRBG: + default: + break; } - return WOLFSSL_SUCCESS; + if (idx >= MAX_EX_DATA) + return -1; + return idx; } +#endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */ -int wolfSSL_SESSION_set1_id_context(WOLFSSL_SESSION *s, - const unsigned char *sid_ctx, unsigned int sid_ctx_len) +#if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) +void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx) { - if (s == NULL) { - return WOLFSSL_FAILURE; - } - if (sid_ctx_len > ID_LEN) { - return WOLFSSL_FAILURE; - } - s->sessionCtxSz = sid_ctx_len; - if (sid_ctx != s->sessionCtx) { - XMEMCPY(s->sessionCtx, sid_ctx, sid_ctx_len); + WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); +#ifdef HAVE_EX_DATA + if(ctx != NULL) { + return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); } - - return WOLFSSL_SUCCESS; -} - +#else + (void)ctx; + (void)idx; #endif - -/*** TBD ***/ -#ifndef NO_WOLFSSL_STUB -int wolfSSL_sk_SSL_COMP_zero(WOLFSSL_STACK* st) -{ - (void)st; - WOLFSSL_STUB("wolfSSL_sk_SSL_COMP_zero"); - /* wolfSSL_set_options(ssl, SSL_OP_NO_COMPRESSION); */ - return WOLFSSL_FAILURE; + return NULL; } -#endif -#ifdef HAVE_CERTIFICATE_STATUS_REQUEST -long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type) +int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, + WOLFSSL_CRYPTO_EX_new* new_func, + WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func) { - WOLFSSL_ENTER("wolfSSL_set_tlsext_status_type"); - - if (s == NULL){ - return BAD_FUNC_ARG; - } - if (type == TLSEXT_STATUSTYPE_ocsp){ - int r = TLSX_UseCertificateStatusRequest(&s->extensions, (byte)type, 0, s, - s->heap, s->devId); - return (long)r; - } else { - WOLFSSL_MSG( - "SSL_set_tlsext_status_type only supports TLSEXT_STATUSTYPE_ocsp type."); - return WOLFSSL_FAILURE; - } + WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index"); + return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx, arg, + new_func, dup_func, free_func); } -long wolfSSL_get_tlsext_status_type(WOLFSSL *s) +/* Return the index that can be used for the WOLFSSL structure to store + * application data. + * + */ +int wolfSSL_get_ex_new_index(long argValue, void* arg, + WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2, + WOLFSSL_CRYPTO_EX_free* cb3) { - TLSX* extension; + WOLFSSL_ENTER("wolfSSL_get_ex_new_index"); - if (s == NULL) - return WOLFSSL_FATAL_ERROR; - extension = TLSX_Find(s->extensions, TLSX_STATUS_REQUEST); - return extension != NULL ? TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR; + return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue, arg, + cb1, cb2, cb3); } -#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */ -#ifndef NO_WOLFSSL_STUB -long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg) -{ - (void)s; - (void)arg; - WOLFSSL_STUB("wolfSSL_get_tlsext_status_exts"); - return WOLFSSL_FAILURE; -} -#endif -/*** TBD ***/ -#ifndef NO_WOLFSSL_STUB -long wolfSSL_set_tlsext_status_exts(WOLFSSL *s, void *arg) +int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data) { - (void)s; - (void)arg; - WOLFSSL_STUB("wolfSSL_set_tlsext_status_exts"); + WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data"); + #ifdef HAVE_EX_DATA + if (ctx != NULL) + { + return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data); + } + #else + (void)ctx; + (void)idx; + (void)data; + #endif return WOLFSSL_FAILURE; } -#endif -/*** TBD ***/ -#ifndef NO_WOLFSSL_STUB -long wolfSSL_get_tlsext_status_ids(WOLFSSL *s, void *arg) +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +int wolfSSL_CTX_set_ex_data_with_cleanup( + WOLFSSL_CTX* ctx, + int idx, + void* data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine) { - (void)s; - (void)arg; - WOLFSSL_STUB("wolfSSL_get_tlsext_status_ids"); + WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup"); + if (ctx != NULL) + { + return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data, + cleanup_routine); + } return WOLFSSL_FAILURE; } -#endif +#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ -/*** TBD ***/ -#ifndef NO_WOLFSSL_STUB -long wolfSSL_set_tlsext_status_ids(WOLFSSL *s, void *arg) -{ - (void)s; - (void)arg; - WOLFSSL_STUB("wolfSSL_set_tlsext_status_ids"); - return WOLFSSL_FAILURE; -} -#endif +#endif /* defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) */ -#ifndef NO_WOLFSSL_STUB -/*** TBD ***/ -WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + +/* Returns char* to app data stored in ex[0]. + * + * ssl WOLFSSL structure to get app data from + */ +void* wolfSSL_get_app_data(const WOLFSSL *ssl) { - (void)ssl; - WOLFSSL_STUB("SSL_get_privatekey"); - return NULL; + /* checkout exdata stuff... */ + WOLFSSL_ENTER("wolfSSL_get_app_data"); + + return wolfSSL_get_ex_data(ssl, 0); } -#endif -#ifndef NO_WOLFSSL_STUB -/*** TBD ***/ -void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, - WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)) -{ - (void)ctx; - (void)dh; - WOLFSSL_STUB("SSL_CTX_set_tmp_dh_callback"); -} -#endif -#ifndef NO_WOLFSSL_STUB -/*** TBD ***/ -WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) -{ - WOLFSSL_STUB("SSL_COMP_get_compression_methods"); - return NULL; +/* Set ex array 0 to have app data + * + * ssl WOLFSSL struct to set app data in + * arg data to be stored + * + * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) { + WOLFSSL_ENTER("wolfSSL_set_app_data"); + + return wolfSSL_set_ex_data(ssl, 0, arg); } -#endif +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p) +#if defined(HAVE_EX_DATA) || defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_WPAS_SMALL) + +int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data) { - WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_num"); - if (p == NULL) { - return WOLFSSL_FATAL_ERROR; + WOLFSSL_ENTER("wolfSSL_set_ex_data"); +#ifdef HAVE_EX_DATA + if (ssl != NULL) + { + return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data); } - return (int)p->num; +#else + WOLFSSL_MSG("HAVE_EX_DATA macro is not defined"); + (void)ssl; + (void)idx; + (void)data; +#endif + return WOLFSSL_FAILURE; } -WOLFSSL_CIPHER* wolfSSL_sk_SSL_CIPHER_value(WOLFSSL_STACK* sk, int i) +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +int wolfSSL_set_ex_data_with_cleanup( + WOLFSSL* ssl, + int idx, + void* data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine) { - WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_value"); - return (WOLFSSL_CIPHER*)wolfSSL_sk_value(sk, i); + WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup"); + if (ssl != NULL) + { + return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data, + cleanup_routine); + } + return WOLFSSL_FAILURE; } +#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ -#if !defined(NETOS) -void ERR_load_SSL_strings(void) +void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx) { - -} + WOLFSSL_ENTER("wolfSSL_get_ex_data"); +#ifdef HAVE_EX_DATA + if (ssl != NULL) { + return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx); + } +#else + WOLFSSL_MSG("HAVE_EX_DATA macro is not defined"); + (void)ssl; + (void)idx; #endif - -#ifdef HAVE_OCSP -long wolfSSL_get_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char **resp) -{ - if (s == NULL || resp == NULL) - return 0; - - *resp = s->ocspResp; - return s->ocspRespSz; + return 0; } -long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char *resp, - int len) -{ - if (s == NULL) - return WOLFSSL_FAILURE; - - s->ocspResp = resp; - s->ocspRespSz = len; - - return WOLFSSL_SUCCESS; -} -#endif /* HAVE_OCSP */ +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */ -#ifdef HAVE_MAX_FRAGMENT -#ifndef NO_WOLFSSL_CLIENT -/** - * Set max fragment tls extension - * @param c a pointer to WOLFSSL_CTX object - * @param mode maximum fragment length mode - * @return 1 on success, otherwise 0 or negative error code - */ -int wolfSSL_CTX_set_tlsext_max_fragment_length(WOLFSSL_CTX *c, - unsigned char mode) -{ - if (c == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 )) - return BAD_FUNC_ARG; +#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \ + || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) - return wolfSSL_CTX_UseMaxFragment(c, mode); -} -/** - * Set max fragment tls extension - * @param c a pointer to WOLFSSL object - * @param mode maximum fragment length mode - * @return 1 on success, otherwise 0 or negative error code +/* returns the enum value associated with handshake state + * + * ssl the WOLFSSL structure to get state of */ -int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s, unsigned char mode) -{ - if (s == NULL || (mode < WOLFSSL_MFL_2_9 || mode > WOLFSSL_MFL_2_12 )) - return BAD_FUNC_ARG; - - return wolfSSL_UseMaxFragment(s, mode); -} -#endif /* NO_WOLFSSL_CLIENT */ -#endif /* HAVE_MAX_FRAGMENT */ - -#endif /* OPENSSL_EXTRA */ - -#ifdef WOLFSSL_HAVE_TLS_UNIQUE -size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count) +int wolfSSL_get_state(const WOLFSSL* ssl) { - byte len = 0; - - WOLFSSL_ENTER("wolfSSL_get_finished"); + WOLFSSL_ENTER("wolfSSL_get_state"); - if (!ssl || !buf || count < TLS_FINISHED_SZ) { - WOLFSSL_MSG("Bad parameter"); + if (ssl == NULL) { + WOLFSSL_MSG("Null argument passed in"); return WOLFSSL_FAILURE; } - if (ssl->options.side == WOLFSSL_SERVER_END) { - len = ssl->serverFinished_len; - XMEMCPY(buf, ssl->serverFinished, len); - } - else { - len = ssl->clientFinished_len; - XMEMCPY(buf, ssl->clientFinished, len); - } - return len; + return ssl->options.handShakeState; } +#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */ -size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count) +#ifdef OPENSSL_EXTRA +void wolfSSL_certs_clear(WOLFSSL* ssl) { - byte len = 0; - WOLFSSL_ENTER("wolfSSL_get_peer_finished"); + WOLFSSL_ENTER("wolfSSL_certs_clear"); - if (!ssl || !buf || count < TLS_FINISHED_SZ) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } + if (ssl == NULL) + return; - if (ssl->options.side == WOLFSSL_CLIENT_END) { - len = ssl->serverFinished_len; - XMEMCPY(buf, ssl->serverFinished, len); + /* ctx still owns certificate, certChain, key, dh, and cm */ + if (ssl->buffers.weOwnCert) + FreeDer(&ssl->buffers.certificate); + ssl->buffers.certificate = NULL; + if (ssl->buffers.weOwnCertChain) + FreeDer(&ssl->buffers.certChain); + ssl->buffers.certChain = NULL; +#ifdef WOLFSSL_TLS13 + ssl->buffers.certChainCnt = 0; +#endif + if (ssl->buffers.weOwnKey) { + FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif } - else { - len = ssl->clientFinished_len; - XMEMCPY(buf, ssl->clientFinished, len); + ssl->buffers.key = NULL; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.keyMask = NULL; +#endif + ssl->buffers.keyType = 0; + ssl->buffers.keyId = 0; + ssl->buffers.keyLabel = 0; + ssl->buffers.keySz = 0; + ssl->buffers.keyDevId = 0; +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->buffers.weOwnAltKey) { + FreeDer(&ssl->buffers.altKey); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.altKeyMask); + #endif } - - return len; + ssl->buffers.altKey = NULL; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.altKeyMask = NULL; +#endif +#endif /* WOLFSSL_DUAL_ALG_CERTS */ } -#endif /* WOLFSSL_HAVE_TLS_UNIQUE */ +#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(OPENSSL_ALL) -long wolfSSL_get_verify_result(const WOLFSSL *ssl) +#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ + || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) + +long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt) { - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } + WOLFSSL_ENTER("wolfSSL_ctrl"); + if (ssl == NULL) + return BAD_FUNC_ARG; - return ssl->peerVerifyRet; + switch (cmd) { + #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \ + defined(OPENSSL_ALL) + #ifdef HAVE_SNI + case SSL_CTRL_SET_TLSEXT_HOSTNAME: + WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME."); + if (pt == NULL) { + WOLFSSL_MSG("Passed in NULL Host Name."); + break; + } + return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt); + #endif /* HAVE_SNI */ + #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */ + default: + WOLFSSL_MSG("Case not implemented."); + } + (void)opt; + (void)pt; + return WOLFSSL_FAILURE; } -#endif - -#ifdef OPENSSL_EXTRA -#ifndef NO_WOLFSSL_STUB -/* shows the number of accepts attempted by CTX in it's lifetime */ -long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx) +long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt) { - WOLFSSL_STUB("wolfSSL_CTX_sess_accept"); - (void)ctx; - return 0; -} -#endif - -#ifndef NO_WOLFSSL_STUB -/* shows the number of connects attempted CTX in it's lifetime */ -long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_connect"); - (void)ctx; - return 0; -} -#endif - - -#ifndef NO_WOLFSSL_STUB -/* shows the number of accepts completed by CTX in it's lifetime */ -long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good"); - (void)ctx; - return 0; -} +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) + long ctrl_opt; #endif + long ret = WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_CTX_ctrl"); + if (ctx == NULL) + return WOLFSSL_FAILURE; -#ifndef NO_WOLFSSL_STUB -/* shows the number of connects completed by CTX in it's lifetime */ -long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good"); - (void)ctx; - return 0; -} + switch (cmd) { + case SSL_CTRL_CHAIN: +#ifdef SESSION_CERTS + { + /* + * We don't care about opt here because a copy of the certificate is + * stored anyway so increasing the reference counter is not necessary. + * Just check to make sure that it is set to one of the correct values. + */ + WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt; + WOLFSSL_X509* x509; + int i; + if (opt != 0 && opt != 1) { + ret = WOLFSSL_FAILURE; + break; + } + /* Clear certificate chain */ + FreeDer(&ctx->certChain); + if (sk) { + for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) { + x509 = wolfSSL_sk_X509_value(sk, i); + /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */ + if (wolfSSL_X509_up_ref(x509) != 1) { + WOLFSSL_MSG("Error increasing reference count"); + continue; + } + if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) != + WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error adding certificate to context"); + /* Decrease reference count on failure */ + wolfSSL_X509_free(x509); + } + } + } + /* Free previous chain */ + wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL); + ctx->x509Chain = sk; + if (sk && opt == 1) { + /* up all refs when opt == 1 */ + for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) { + x509 = wolfSSL_sk_X509_value(sk, i); + if (wolfSSL_X509_up_ref(x509) != 1) { + WOLFSSL_MSG("Error increasing reference count"); + continue; + } + } + } + } +#else + WOLFSSL_MSG("Session certificates not compiled in"); + ret = WOLFSSL_FAILURE; #endif + break; +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) + case SSL_CTRL_OPTIONS: + WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS."); + ctrl_opt = wolfSSL_CTX_set_options(ctx, opt); -#ifndef NO_WOLFSSL_STUB -/* shows the number of renegotiation accepts attempted by CTX */ -long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate"); - (void)ctx; - return 0; -} -#endif + #ifdef WOLFSSL_QT + /* Set whether to use client or server cipher preference */ + if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) + == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) { + WOLFSSL_MSG("Using Server's Cipher Preference."); + ctx->useClientOrder = FALSE; + } else { + WOLFSSL_MSG("Using Client's Cipher Preference."); + ctx->useClientOrder = TRUE; + } + #endif /* WOLFSSL_QT */ + return ctrl_opt; +#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */ + case SSL_CTRL_EXTRA_CHAIN_CERT: + WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT."); + if (pt == NULL) { + WOLFSSL_MSG("Passed in x509 pointer NULL."); + ret = WOLFSSL_FAILURE; + break; + } + return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt); -#ifndef NO_WOLFSSL_STUB -/* shows the number of renegotiation accepts attempted by CTX */ -long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate"); - (void)ctx; - return 0; -} +#ifndef NO_DH + case SSL_CTRL_SET_TMP_DH: + WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH."); + if (pt == NULL) { + WOLFSSL_MSG("Passed in DH pointer NULL."); + ret = WOLFSSL_FAILURE; + break; + } + return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt); #endif - -#ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_hits"); - (void)ctx; - return 0; -} +#ifdef HAVE_ECC + case SSL_CTRL_SET_TMP_ECDH: + WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH."); + if (pt == NULL) { + WOLFSSL_MSG("Passed in ECDH pointer NULL."); + ret = WOLFSSL_FAILURE; + break; + } + return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt); #endif + case SSL_CTRL_MODE: + wolfSSL_CTX_set_mode(ctx,opt); + break; + case SSL_CTRL_SET_MIN_PROTO_VERSION: + WOLFSSL_MSG("set min proto version"); + return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt); + case SSL_CTRL_SET_MAX_PROTO_VERSION: + WOLFSSL_MSG("set max proto version"); + return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt); + case SSL_CTRL_GET_MIN_PROTO_VERSION: + WOLFSSL_MSG("get min proto version"); + return wolfSSL_CTX_get_min_proto_version(ctx); + case SSL_CTRL_GET_MAX_PROTO_VERSION: + WOLFSSL_MSG("get max proto version"); + return wolfSSL_CTX_get_max_proto_version(ctx); + default: + WOLFSSL_MSG("CTX_ctrl cmd not implemented"); + ret = WOLFSSL_FAILURE; + break; + } - -#ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits"); (void)ctx; - return 0; + (void)cmd; + (void)opt; + (void)pt; + WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret); + return ret; } -#endif - #ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx) +long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void)) { - WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full"); - (void)ctx; - return 0; -} -#endif - + (void) ctx; + (void) cmd; + (void) fp; + WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl"); + return WOLFSSL_FAILURE; -#ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx) -{ - WOLFSSL_STUB("wolfSSL_CTX_sess_misses"); - (void)ctx; - return 0; } -#endif - +#endif /* NO_WOLFSSL_STUB */ #ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx) +long wolfSSL_CTX_clear_extra_chain_certs(WOLFSSL_CTX* ctx) { - WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts"); - (void)ctx; - return 0; + return wolfSSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0L, NULL); } #endif - -/* Return the total number of sessions */ -long wolfSSL_CTX_sess_number(WOLFSSL_CTX* ctx) +/* Returns the verifyCallback from the ssl structure if successful. +Returns NULL otherwise. */ +VerifyCallback wolfSSL_get_verify_callback(WOLFSSL* ssl) { - word32 total = 0; - - WOLFSSL_ENTER("wolfSSL_CTX_sess_number"); - (void)ctx; - -#if defined(WOLFSSL_SESSION_STATS) && !defined(NO_SESSION_CACHE) - if (wolfSSL_get_session_stats(NULL, &total, NULL, NULL) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error getting session stats"); + WOLFSSL_ENTER("wolfSSL_get_verify_callback"); + if (ssl) { + return ssl->verifyCallback; } -#else - WOLFSSL_MSG("Please use macro WOLFSSL_SESSION_STATS for session stats"); -#endif - - return (long)total; + return NULL; } - -#ifndef NO_CERTS -long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) +#ifndef NO_BIO +/* Converts EVP_PKEY data from a bio buffer to a WOLFSSL_EVP_PKEY structure. +Returns pointer to private EVP_PKEY struct upon success, NULL if there +is a failure.*/ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY** out) { - byte* chain = NULL; - int derSz; - const byte* der; - int ret; - DerBuffer *derBuffer = NULL; + unsigned char* mem = NULL; + int memSz = 0; + WOLFSSL_EVP_PKEY* key = NULL; + unsigned char* extraBioMem = NULL; - WOLFSSL_ENTER("wolfSSL_CTX_add_extra_chain_cert"); + WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_bio"); - if (ctx == NULL || x509 == NULL) { - WOLFSSL_MSG("Bad Argument"); - return WOLFSSL_FAILURE; + if (bio == NULL) { + return NULL; } + (void)out; - der = wolfSSL_X509_get_der(x509, &derSz); - if (der == NULL || derSz <= 0) { - WOLFSSL_MSG("Error getting X509 DER"); - return WOLFSSL_FAILURE; + memSz = wolfSSL_BIO_get_len(bio); + if (memSz <= 0) { + WOLFSSL_MSG("wolfSSL_BIO_get_len() failure"); + return NULL; } - if (ctx->certificate == NULL) { - WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format"); - - /* Process buffer makes first certificate the leaf. */ - ret = ProcessBuffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, - NULL, NULL, 1, GET_VERIFY_SETTING_CTX(ctx)); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret); - return WOLFSSL_FAILURE; - } + mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (mem == NULL) { + WOLFSSL_MSG("Malloc failure"); + return NULL; } - else { - long chainSz = 0; - int idx = 0; - /* TODO: Do this elsewhere. */ - ret = AllocDer(&derBuffer, derSz, CERT_TYPE, ctx->heap); - if (ret != 0) { - WOLFSSL_MSG("Memory Error"); - return WOLFSSL_FAILURE; - } - XMEMCPY(derBuffer->buffer, der, derSz); - ret = AddCA(ctx->cm, &derBuffer, WOLFSSL_USER_CA, - GET_VERIFY_SETTING_CTX(ctx)); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret); - return WOLFSSL_FAILURE; - } + if (wolfSSL_BIO_read(bio, (unsigned char*)mem, memSz) == memSz) { + int extraBioMemSz; + int derLength; - /* adding cert to existing chain */ - if (ctx->certChain != NULL && ctx->certChain->length > 0) { - chainSz += ctx->certChain->length; + /* Determines key type and returns the new private EVP_PKEY object */ + if ((key = wolfSSL_d2i_PrivateKey_EVP(NULL, &mem, (long)memSz)) == + NULL) { + WOLFSSL_MSG("wolfSSL_d2i_PrivateKey_EVP() failure"); + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + return NULL; } - chainSz += OPAQUE24_LEN + derSz; - chain = (byte*)XMALLOC(chainSz, ctx->heap, DYNAMIC_TYPE_DER); - if (chain == NULL) { - WOLFSSL_MSG("Memory Error"); - return WOLFSSL_FAILURE; - } + /* Write extra data back into bio object if necessary. */ + derLength = key->pkey_sz; + extraBioMemSz = (memSz - derLength); + if (extraBioMemSz > 0) { + int i; + int j = 0; + + extraBioMem = (unsigned char *)XMALLOC(extraBioMemSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (extraBioMem == NULL) { + WOLFSSL_MSG("Malloc failure"); + XFREE((unsigned char*)extraBioMem, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + return NULL; + } + + for (i = derLength; i < memSz; i++) { + *(extraBioMem + j) = *(mem + i); + j++; + } - if (ctx->certChain != NULL && ctx->certChain->length > 0) { - XMEMCPY(chain, ctx->certChain->buffer, ctx->certChain->length); - idx = ctx->certChain->length; + wolfSSL_BIO_write(bio, extraBioMem, extraBioMemSz); + if (wolfSSL_BIO_get_len(bio) <= 0) { + WOLFSSL_MSG("Failed to write memory to bio"); + XFREE((unsigned char*)extraBioMem, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + return NULL; + } + XFREE((unsigned char*)extraBioMem, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); } - c32to24(derSz, chain + idx); - idx += OPAQUE24_LEN; - XMEMCPY(chain + idx, der, derSz); - idx += derSz; -#ifdef WOLFSSL_TLS13 - ctx->certChainCnt++; -#endif - FreeDer(&ctx->certChain); - ret = AllocDer(&ctx->certChain, idx, CERT_TYPE, ctx->heap); - if (ret == 0) { - XMEMCPY(ctx->certChain->buffer, chain, idx); + if (out != NULL) { + *out = key; } } + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + return key; +} +#endif /* !NO_BIO */ - /* on success WOLFSSL_X509 memory is responsibility of ctx */ - wolfSSL_X509_free(x509); - if (chain != NULL) - XFREE(chain, ctx->heap, DYNAMIC_TYPE_DER); +#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */ - return WOLFSSL_SUCCESS; -} +#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_QT) || defined(WOLFSSL_WPAS_SMALL) -long wolfSSL_CTX_set_tlsext_status_arg(WOLFSSL_CTX* ctx, void* arg) +/* Converts a DER encoded private key to a WOLFSSL_EVP_PKEY structure. + * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL + * on fail */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_EVP(WOLFSSL_EVP_PKEY** out, + unsigned char** in, long inSz) { - if (ctx == NULL || ctx->cm == NULL) { - return WOLFSSL_FAILURE; - } - - ctx->cm->ocspIOCtx = arg; - return WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_EVP"); + return d2iGenericKey(out, (const unsigned char**)in, inSz, 1); } -#endif /* !NO_CERTS */ +#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT || + * WOLFSSL_WPAS_SMALL*/ -int wolfSSL_get_read_ahead(const WOLFSSL* ssl) -{ - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } - return ssl->readAhead; +/* stunnel compatibility functions*/ +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ + (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH))) +void wolfSSL_ERR_remove_thread_state(void* pid) +{ + (void) pid; + return; } - -int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v) +#ifndef NO_FILESYSTEM +/***TBD ***/ +void wolfSSL_print_all_errors_fp(XFILE fp) { - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } + (void)fp; +} +#endif /* !NO_FILESYSTEM */ - ssl->readAhead = (byte)v; +#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX || + HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */ - return WOLFSSL_SUCCESS; -} +/* Note: This is a huge section of API's - through + * wolfSSL_X509_OBJECT_get0_X509_CRL */ +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ + (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB))) +#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \ + !defined(WOLFSSL_STATIC_MEMORY) +static wolfSSL_OSSL_Malloc_cb ossl_malloc = NULL; +static wolfSSL_OSSL_Free_cb ossl_free = NULL; +static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL; -int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx) +static void* OSSL_Malloc(size_t size) { - if (ctx == NULL) { - return WOLFSSL_FAILURE; - } + if (ossl_malloc != NULL) + return ossl_malloc(size, NULL, 0); + else + return NULL; +} - return ctx->readAhead; +static void OSSL_Free(void *ptr) +{ + if (ossl_free != NULL) + ossl_free(ptr, NULL, 0); } +static void* OSSL_Realloc(void *ptr, size_t size) +{ + if (ossl_realloc != NULL) + return ossl_realloc(ptr, size, NULL, 0); + else + return NULL; +} +#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY && + * !WOLFSSL_STATIC_MEMORY */ -int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v) +int wolfSSL_CRYPTO_set_mem_functions( + wolfSSL_OSSL_Malloc_cb m, + wolfSSL_OSSL_Realloc_cb r, + wolfSSL_OSSL_Free_cb f) { - if (ctx == NULL) { - return WOLFSSL_FAILURE; +#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) +#ifdef WOLFSSL_DEBUG_MEMORY + WOLFSSL_MSG("mem functions will receive function name instead of " + "file name"); + if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f, + (wolfSSL_Realloc_cb)r) == 0) + return WOLFSSL_SUCCESS; +#else + WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem " + "functions will receive a NULL file name and 0 for the " + "line number."); + if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc, + (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) { + ossl_malloc = m; + ossl_free = f; + ossl_realloc = r; + return WOLFSSL_SUCCESS; } +#endif + else + return WOLFSSL_FAILURE; +#else + (void)m; + (void)r; + (void)f; + WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in"); + return WOLFSSL_FAILURE; +#endif +} - ctx->readAhead = (byte)v; - +int wolfSSL_ERR_load_ERR_strings(void) +{ return WOLFSSL_SUCCESS; } +void wolfSSL_ERR_load_crypto_strings(void) +{ + WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings"); + /* Do nothing */ + return; +} -long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx, - void* arg) +int wolfSSL_FIPS_mode(void) { - if (ctx == NULL) { +#ifdef HAVE_FIPS + return 1; +#else + return 0; +#endif +} + +int wolfSSL_FIPS_mode_set(int r) +{ +#ifdef HAVE_FIPS + if (r == 0) { + WOLFSSL_MSG("Cannot disable FIPS at runtime."); return WOLFSSL_FAILURE; } - - ctx->userPRFArg = arg; return WOLFSSL_SUCCESS; +#else + if (r == 0) { + return WOLFSSL_SUCCESS; + } + WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code."); + return WOLFSSL_FAILURE; +#endif } -#endif /* OPENSSL_EXTRA */ - -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -int wolfSSL_sk_num(const WOLFSSL_STACK* sk) +int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits) { - WOLFSSL_ENTER("wolfSSL_sk_num"); - if (sk == NULL) - return 0; - return (int)sk->num; + int ret = WOLFSSL_FAILURE; + WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits"); + + #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) + (void)alg_bits; + if (c!= NULL) + ret = c->bits; + #else + if (c != NULL && c->ssl != NULL) { + ret = 8 * c->ssl->specs.key_size; + if (alg_bits != NULL) { + *alg_bits = ret; + } + } + #endif + return ret; } -void* wolfSSL_sk_value(const WOLFSSL_STACK* sk, int i) +/* returns value less than 0 on fail to match + * On a successful match the priority level found is returned + */ +int wolfSSL_sk_SSL_CIPHER_find( + WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, const WOLFSSL_CIPHER* toFind) { - WOLFSSL_ENTER("wolfSSL_sk_value"); + WOLFSSL_STACK* next; + int i, sz; - for (; sk != NULL && i > 0; i--) - sk = sk->next; - if (sk == NULL) - return NULL; + if (sk == NULL || toFind == NULL) { + return WOLFSSL_FATAL_ERROR; + } - switch (sk->type) { - case STACK_TYPE_X509: - return (void*)sk->data.x509; - case STACK_TYPE_GEN_NAME: - return (void*)sk->data.gn; - case STACK_TYPE_BIO: - return (void*)sk->data.bio; - case STACK_TYPE_OBJ: - return (void*)sk->data.obj; - case STACK_TYPE_STRING: - return (void*)sk->data.string; - case STACK_TYPE_CIPHER: - return (void*)&sk->data.cipher; - case STACK_TYPE_ACCESS_DESCRIPTION: - return (void*)sk->data.access; - case STACK_TYPE_X509_EXT: - return (void*)sk->data.ext; - case STACK_TYPE_X509_REQ_ATTR: - return (void*)sk->data.generic; - case STACK_TYPE_NULL: - return (void*)sk->data.generic; - case STACK_TYPE_X509_NAME: - return (void*)sk->data.name; - case STACK_TYPE_X509_NAME_ENTRY: - return (void*)sk->data.name_entry; - case STACK_TYPE_CONF_VALUE: - #ifdef OPENSSL_EXTRA - return (void*)sk->data.conf; - #else - return NULL; - #endif - case STACK_TYPE_X509_INFO: - return (void*)sk->data.info; - case STACK_TYPE_BY_DIR_entry: - return (void*)sk->data.dir_entry; - case STACK_TYPE_BY_DIR_hash: - return (void*)sk->data.dir_hash; - case STACK_TYPE_X509_OBJ: - return (void*)sk->data.x509_obj; - case STACK_TYPE_DIST_POINT: - return (void*)sk->data.dp; - case STACK_TYPE_X509_CRL: - return (void*)sk->data.crl; - default: - return (void*)sk->data.generic; + sz = wolfSSL_sk_SSL_CIPHER_num(sk); + next = sk; + for (i = 0; i < sz && next != NULL; i++) { + if (next->data.cipher.cipherSuite0 == toFind->cipherSuite0 && + next->data.cipher.cipherSuite == toFind->cipherSuite) { + return sz - i; /* reverse because stack pushed highest on first */ + } + next = next->next; } + return WOLFSSL_FATAL_ERROR; } -/* copies over data of "in" to "out" */ -static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out) +/* free's all nodes in the stack and there data */ +void wolfSSL_sk_SSL_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) { - if (in == NULL || out == NULL) - return; - - *out = *in; + WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_free"); + wolfSSL_sk_free(sk); } -WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk) +#ifdef HAVE_SNI +int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name) { + int ret; + WOLFSSL_ENTER("wolfSSL_set_tlsext_host_name"); + ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, + host_name, (word16)XSTRLEN(host_name)); + WOLFSSL_LEAVE("wolfSSL_set_tlsext_host_name", ret); + return ret; +} - WOLFSSL_STACK* ret = NULL; - WOLFSSL_STACK* last = NULL; +/* May be called by server to get the requested accepted name and by the client + * to get the requested name. */ +const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type) +{ + void * serverName = NULL; + if (ssl == NULL) + return NULL; + TLSX_SNI_GetRequest(ssl->extensions, type, &serverName, + !wolfSSL_is_server(ssl)); + return (const char *)serverName; +} +#endif /* HAVE_SNI */ - WOLFSSL_ENTER("wolfSSL_sk_dup"); +WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) +{ + int ret; + /* This method requires some explanation. Its sibling is + * int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) + * which re-inits the WOLFSSL* with all settings in the new CTX. + * That one is the right one to use *before* a handshake is started. + * + * This method was added by OpenSSL to be used *during* the handshake, e.g. + * when a server inspects the SNI in a ClientHello callback and + * decides which set of certificates to use. + * + * Since, at the time the SNI callback is run, some decisions on + * Extensions or the ServerHello might already have been taken, this + * method is very restricted in what it does: + * - changing the server certificate(s) + * - changing the server id for session handling + * and everything else in WOLFSSL* needs to remain untouched. + */ + WOLFSSL_ENTER("wolfSSL_set_SSL_CTX"); + if (ssl == NULL || ctx == NULL) + return NULL; + if (ssl->ctx == ctx) + return ssl->ctx; - while (sk) { - WOLFSSL_STACK* cur = wolfSSL_sk_new_node(sk->heap); + if (ctx->suites == NULL) { + /* suites */ + if (AllocateCtxSuites(ctx) != 0) + return NULL; + InitSSL_CTX_Suites(ctx); + } - if (!cur) { - WOLFSSL_MSG("wolfSSL_sk_new_node error"); - goto error; - } + wolfSSL_RefInc(&ctx->ref, &ret); +#ifdef WOLFSSL_REFCNT_ERROR_RETURN + if (ret != 0) { + /* can only fail on serious stuff, like mutex not working + * or ctx refcount out of whack. */ + return NULL; + } +#else + (void)ret; +#endif + if (ssl->ctx != NULL) + wolfSSL_CTX_free(ssl->ctx); + ssl->ctx = ctx; - if (!ret) { - /* Set first node */ - ret = cur; +#ifndef NO_CERTS + /* ctx owns certificate, certChain and key */ + ssl->buffers.certificate = ctx->certificate; + ssl->buffers.certChain = ctx->certChain; +#ifdef WOLFSSL_TLS13 + ssl->buffers.certChainCnt = ctx->certChainCnt; +#endif +#ifndef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.key = ctx->privateKey; +#else + if (ctx->privateKey != NULL) { + AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ctx->privateKey->length, ctx->privateKey->type, + ctx->privateKey->heap); + /* Blind the private key for the SSL with new random mask. */ + wolfssl_priv_der_unblind(ssl->buffers.key, ctx->privateKeyMask); + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + if (ret != 0) { + return ret; } - - if (last) { - last->next = cur; + } +#endif + ssl->buffers.keyType = ctx->privateKeyType; + ssl->buffers.keyId = ctx->privateKeyId; + ssl->buffers.keyLabel = ctx->privateKeyLabel; + ssl->buffers.keySz = ctx->privateKeySz; + ssl->buffers.keyDevId = ctx->privateKeyDevId; + /* flags indicating what certs/keys are available */ + ssl->options.haveRSA = ctx->haveRSA; + ssl->options.haveDH = ctx->haveDH; + ssl->options.haveECDSAsig = ctx->haveECDSAsig; + ssl->options.haveECC = ctx->haveECC; + ssl->options.haveStaticECC = ctx->haveStaticECC; + ssl->options.haveFalconSig = ctx->haveFalconSig; + ssl->options.haveDilithiumSig = ctx->haveDilithiumSig; +#ifdef WOLFSSL_DUAL_ALG_CERTS +#ifndef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.altKey = ctx->altPrivateKey; +#else + if (ctx->altPrivateKey != NULL) { + AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, + ctx->altPrivateKey->length, ctx->altPrivateKey->type, + ctx->altPrivateKey->heap); + /* Blind the private key for the SSL with new random mask. */ + wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask); + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, + &ssl->buffers.altKeyMask); + if (ret != 0) { + return ret; } + } +#endif + ssl->buffers.altKeySz = ctx->altPrivateKeySz; + ssl->buffers.altKeyType = ctx->altPrivateKeyType; +#endif /* WOLFSSL_DUAL_ALG_CERTS */ +#endif - XMEMCPY(cur, sk, sizeof(WOLFSSL_STACK)); - - /* We will allocate new memory for this */ - XMEMSET(&cur->data, 0, sizeof(cur->data)); - cur->next = NULL; +#ifdef WOLFSSL_SESSION_ID_CTX + /* copy over application session context ID */ + ssl->sessionCtxSz = ctx->sessionCtxSz; + XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz); +#endif - switch (sk->type) { - case STACK_TYPE_X509: - if (!sk->data.x509) - break; - cur->data.x509 = wolfSSL_X509_dup(sk->data.x509); - if (!cur->data.x509) { - WOLFSSL_MSG("wolfSSL_X509_dup error"); - goto error; - } - break; - case STACK_TYPE_CIPHER: - wolfSSL_CIPHER_copy(&sk->data.cipher, &cur->data.cipher); - break; - case STACK_TYPE_GEN_NAME: - if (!sk->data.gn) - break; - cur->data.gn = wolfSSL_GENERAL_NAME_dup(sk->data.gn); - if (!cur->data.gn) { - WOLFSSL_MSG("wolfSSL_GENERAL_NAME_new error"); - goto error; - } - break; - case STACK_TYPE_OBJ: - if (!sk->data.obj) - break; - cur->data.obj = wolfSSL_ASN1_OBJECT_dup(sk->data.obj); - if (!cur->data.obj) { - WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_dup error"); - goto error; - } - break; - case STACK_TYPE_BIO: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - WOLFSSL_MSG("Unsupported stack type"); - goto error; - } + return ssl->ctx; +} - sk = sk->next; - last = cur; - } - return ret; -error: - if (ret) { - wolfSSL_sk_GENERAL_NAME_free(ret); - } +VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_get_verify_callback"); + if(ctx) + return ctx->verifyCallback; return NULL; } - -WOLFSSL_STACK* wolfSSL_shallow_sk_dup(WOLFSSL_STACK* sk) +#ifdef HAVE_SNI +/* this is a compatibily function, consider using + * wolfSSL_CTX_set_servername_callback */ +int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx, + CallbackSniRecv cb) { + WOLFSSL_ENTER("wolfSSL_CTX_set_tlsext_servername_callback"); + if (ctx) { + ctx->sniRecvCb = cb; + return WOLFSSL_SUCCESS; + } + return WOLFSSL_FAILURE; +} - WOLFSSL_STACK* ret = NULL; - WOLFSSL_STACK** prev = &ret; - - WOLFSSL_ENTER("wolfSSL_shallow_sk_dup"); +#endif /* HAVE_SNI */ - for (; sk != NULL; sk = sk->next) { - WOLFSSL_STACK* cur = wolfSSL_sk_new_node(sk->heap); - - if (!cur) { - WOLFSSL_MSG("wolfSSL_sk_new_node error"); - goto error; - } - - XMEMCPY(cur, sk, sizeof(WOLFSSL_STACK)); - cur->next = NULL; - - *prev = cur; - prev = &cur->next; - } - return ret; - -error: - if (ret) { - wolfSSL_sk_free(ret); - } - return NULL; +#ifndef NO_BIO +void wolfSSL_ERR_load_BIO_strings(void) { + WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings"); + /* do nothing */ } +#endif -/* Free the just the stack structure */ -void wolfSSL_sk_free(WOLFSSL_STACK* sk) +#ifndef NO_WOLFSSL_STUB +/* Set THREADID callback, return 1 on success, 0 on error */ +int wolfSSL_THREADID_set_callback( + void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*)) { - WOLFSSL_ENTER("wolfSSL_sk_free"); - - while (sk != NULL) { - WOLFSSL_STACK* next = sk->next; - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); - sk = next; - } + WOLFSSL_ENTER("wolfSSL_THREADID_set_callback"); + WOLFSSL_STUB("CRYPTO_THREADID_set_callback"); + (void)threadid_func; + return 1; } +#endif -/* Frees each node in the stack and frees the stack. - */ -void wolfSSL_sk_GENERIC_pop_free(WOLFSSL_STACK* sk, - void (*f) (void*)) +#ifndef NO_WOLFSSL_STUB +void wolfSSL_THREADID_set_numeric(void* id, unsigned long val) { - WOLFSSL_ENTER("wolfSSL_sk_GENERIC_pop_free"); - wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f); + WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric"); + WOLFSSL_STUB("CRYPTO_THREADID_set_numeric"); + (void)id; + (void)val; + return; } +#endif -/* return 1 on success 0 on fail */ -int wolfSSL_sk_GENERIC_push(WOLFSSL_STACK* sk, void* generic) -{ - WOLFSSL_ENTER("wolfSSL_sk_GENERIC_push"); +#endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX || + * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH || + * HAVE_SBLIM_SFCB)) */ - return wolfSSL_sk_push(sk, generic); -} -void wolfSSL_sk_GENERIC_free(WOLFSSL_STACK* sk) -{ - wolfSSL_sk_free(sk); -} +#ifdef HAVE_SNI -/* Pop off data from the stack. Checks that the type matches the stack type. - * - * @param [in, out] sk Stack of objects. - * @param [in] type Type of stack. - * @return Object on success. - * @return NULL when stack is NULL or no nodes left in stack. - */ -void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, WOLF_STACK_TYPE type) +void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb) { - WOLFSSL_STACK* node; - void* data = NULL; - - /* Check we have a stack passed in of the right type. */ - if ((sk != NULL) && (sk->type == type)) { - /* Get the next node to become the new first node. */ - node = sk->next; - /* Get the ASN.1 OBJECT_ID object in the first node. */ - data = sk->data.generic; - - /* Check whether there is a next node. */ - if (node != NULL) { - /* Move content out of next node into current node. */ - sk->data.obj = node->data.obj; - sk->next = node->next; - /* Dispose of node. */ - XFREE(node, NULL, DYNAMIC_TYPE_ASN1); - } - else { - /* No more nodes - clear out data. */ - sk->data.obj = NULL; - } - - /* Decrement count as long as we thought we had nodes. */ - if (sk->num > 0) { - sk->num -= 1; - } - } - - return data; + WOLFSSL_ENTER("wolfSSL_CTX_set_servername_callback"); + if (ctx) + ctx->sniRecvCb = cb; } -/* Free all nodes in a stack including the pushed objects */ -void wolfSSL_sk_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk, - wolfSSL_sk_freefunc func) -{ - WOLFSSL_ENTER("wolfSSL_sk_pop_free"); - - if (sk == NULL) { - /* pop_free can be called with NULL, do not print bad argument */ - return; - } - #if defined(WOLFSSL_QT) - /* In Qt v15.5, it calls OPENSSL_sk_free(xxx, OPENSSL_sk_free). - * By using OPENSSL_sk_free for free causes access violation. - * Therefore, switching free func to wolfSSL_ACCESS_DESCRIPTION_free - * is needed even the func isn't NULL. - */ - if (sk->type == STACK_TYPE_ACCESS_DESCRIPTION) { - func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free; - } - #endif - if (func == NULL) { - switch(sk->type) { - case STACK_TYPE_ACCESS_DESCRIPTION: - #if defined(OPENSSL_ALL) - func = (wolfSSL_sk_freefunc)wolfSSL_ACCESS_DESCRIPTION_free; - #endif - break; - case STACK_TYPE_X509: - func = (wolfSSL_sk_freefunc)wolfSSL_X509_free; - break; - case STACK_TYPE_X509_OBJ: - #ifdef OPENSSL_ALL - func = (wolfSSL_sk_freefunc)wolfSSL_X509_OBJECT_free; - #endif - break; - case STACK_TYPE_OBJ: - func = (wolfSSL_sk_freefunc)wolfSSL_ASN1_OBJECT_free; - break; - case STACK_TYPE_DIST_POINT: - #ifdef OPENSSL_EXTRA - func = (wolfSSL_sk_freefunc)wolfSSL_DIST_POINT_free; - #endif - break; - case STACK_TYPE_GEN_NAME: - func = (wolfSSL_sk_freefunc)wolfSSL_GENERAL_NAME_free; - break; - case STACK_TYPE_STRING: - #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ - defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) - func = (wolfSSL_sk_freefunc)wolfSSL_WOLFSSL_STRING_free; - #endif - break; - case STACK_TYPE_X509_NAME: - #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ - && !defined(WOLFCRYPT_ONLY) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_free; - #endif - break; - case STACK_TYPE_X509_NAME_ENTRY: - #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ - && !defined(WOLFCRYPT_ONLY) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_NAME_ENTRY_free; - #endif - break; - case STACK_TYPE_X509_EXT: - #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_EXTENSION_free; - #endif - break; - case STACK_TYPE_X509_REQ_ATTR: - #if defined(OPENSSL_ALL) && \ - (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_REQ)) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_ATTRIBUTE_free; - #endif - break; - case STACK_TYPE_CONF_VALUE: - #if defined(OPENSSL_ALL) - func = (wolfSSL_sk_freefunc)wolfSSL_X509V3_conf_free; - #endif - break; - case STACK_TYPE_X509_INFO: - #if defined(OPENSSL_ALL) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_INFO_free; - #endif - break; - case STACK_TYPE_BIO: -#if !defined(NO_BIO) && defined(OPENSSL_EXTRA) - func = (wolfSSL_sk_freefunc)wolfSSL_BIO_vfree; -#endif - break; - case STACK_TYPE_BY_DIR_entry: -#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) - func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_entry_free; -#endif - break; - case STACK_TYPE_BY_DIR_hash: -#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) - func = (wolfSSL_sk_freefunc)wolfSSL_BY_DIR_HASH_free; -#endif - break; - case STACK_TYPE_X509_CRL: -#if defined(HAVE_CRL) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) - func = (wolfSSL_sk_freefunc)wolfSSL_X509_CRL_free; -#endif - break; - case STACK_TYPE_CIPHER: - case STACK_TYPE_NULL: - default: - break; - } - } - - while (sk != NULL) { - WOLFSSL_STACK* next = sk->next; - if (func != NULL) { - if (sk->type != STACK_TYPE_CIPHER) - func(sk->data.generic); - } - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); - sk = next; +int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_servername_arg"); + if (ctx) { + ctx->sniRecvCbArg = arg; + return WOLFSSL_SUCCESS; } + return WOLFSSL_FAILURE; } -/* Creates a new stack of the requested type. - * - * @param [in] type Type of stack. - * @return Empty stack on success. - * @return NULL when dynamic memory allocation fails. - */ -WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type) -{ - WOLFSSL_STACK* sk; +#endif /* HAVE_SNI */ - /* Allocate a new stack - first node. */ - sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, - DYNAMIC_TYPE_OPENSSL); - if (sk == NULL) { - WOLFSSL_MSG("WOLFSSL_STACK memory error"); - } - else { - /* Clear node and set type. */ - XMEMSET(sk, 0, sizeof(WOLFSSL_STACK)); - sk->type = type; - } - - return sk; -} - -/* Creates and returns a new null stack. */ -WOLFSSL_STACK* wolfSSL_sk_new_null(void) -{ - WOLFSSL_ENTER("wolfSSL_sk_new_null"); - - return wolfssl_sk_new_type(STACK_TYPE_NULL); -} - -int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk) -{ - if (sk == NULL) - return 0; - return (int)sk->num; -} - -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - -#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \ - defined(HAVE_EXT_CACHE)) -/* stunnel 4.28 needs - * - * Callback that is called if a session tries to resume but could not find - * the session to resume it. - */ -void wolfSSL_CTX_sess_set_get_cb(WOLFSSL_CTX* ctx, - WOLFSSL_SESSION*(*f)(WOLFSSL*, const unsigned char*, int, int*)) -{ - if (ctx == NULL) - return; - -#ifdef HAVE_EXT_CACHE - ctx->get_sess_cb = f; -#else - (void)f; -#endif -} - -void wolfSSL_CTX_sess_set_new_cb(WOLFSSL_CTX* ctx, - int (*f)(WOLFSSL*, WOLFSSL_SESSION*)) -{ - if (ctx == NULL) - return; - -#ifdef HAVE_EXT_CACHE - ctx->new_sess_cb = f; -#else - (void)f; -#endif -} - -void wolfSSL_CTX_sess_set_remove_cb(WOLFSSL_CTX* ctx, void (*f)(WOLFSSL_CTX*, - WOLFSSL_SESSION*)) -{ - if (ctx == NULL) - return; - -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - ctx->rem_sess_cb = f; -#else - (void)f; -#endif -} - - -/* - * - * Note: It is expected that the importing and exporting function have been - * built with the same settings. For example if session tickets was - * enabled with the wolfSSL library exporting a session then it is - * expected to be turned on with the wolfSSL library importing the session. - */ -int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) -{ - int size = 0; -#ifdef HAVE_EXT_CACHE - int idx = 0; -#ifdef SESSION_CERTS - int i; -#endif - - WOLFSSL_ENTER("wolfSSL_i2d_SSL_SESSION"); - - sess = ClientSessionToSession(sess); - if (sess == NULL) { - return BAD_FUNC_ARG; - } - - /* side | bornOn | timeout | sessionID len | sessionID | masterSecret | - * haveEMS */ - size += OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN + - sess->sessionIDSz + SECRET_LEN + OPAQUE8_LEN; - /* altSessionID */ - size += OPAQUE8_LEN + (sess->haveAltSessionID ? ID_LEN : 0); -#ifdef SESSION_CERTS - /* Peer chain */ - size += OPAQUE8_LEN; - for (i = 0; i < sess->chain.count; i++) - size += OPAQUE16_LEN + sess->chain.certs[i].length; -#endif -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - /* Protocol version */ - size += OPAQUE16_LEN; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - /* cipher suite */ - size += OPAQUE16_LEN; -#endif -#ifndef NO_CLIENT_CACHE - /* ServerID len | ServerID */ - size += OPAQUE16_LEN + sess->idLen; -#endif -#ifdef WOLFSSL_SESSION_ID_CTX - /* session context ID len | session context ID */ - size += OPAQUE8_LEN + sess->sessionCtxSz; -#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - /* peerVerifyRet */ - size += OPAQUE8_LEN; -#endif -#ifdef WOLFSSL_TLS13 - /* namedGroup */ - size += OPAQUE16_LEN; -#endif -#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) -#ifdef WOLFSSL_TLS13 -#ifdef WOLFSSL_32BIT_MILLI_TIME - /* ticketSeen | ticketAdd */ - size += OPAQUE32_LEN + OPAQUE32_LEN; -#else - /* ticketSeen Hi 32 bits | ticketSeen Lo 32 bits | ticketAdd */ - size += OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE32_LEN; -#endif - /* ticketNonce */ - size += OPAQUE8_LEN + sess->ticketNonce.len; -#endif -#ifdef WOLFSSL_EARLY_DATA - size += OPAQUE32_LEN; -#endif -#endif -#ifdef HAVE_SESSION_TICKET - /* ticket len | ticket */ - size += OPAQUE16_LEN + sess->ticketLen; -#endif - - if (p != NULL) { - unsigned char *data; - - if (*p == NULL) - *p = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_OPENSSL); - if (*p == NULL) - return 0; - data = *p; - - data[idx++] = sess->side; - c32toa(sess->bornOn, data + idx); idx += OPAQUE32_LEN; - c32toa(sess->timeout, data + idx); idx += OPAQUE32_LEN; - data[idx++] = sess->sessionIDSz; - XMEMCPY(data + idx, sess->sessionID, sess->sessionIDSz); - idx += sess->sessionIDSz; - XMEMCPY(data + idx, sess->masterSecret, SECRET_LEN); idx += SECRET_LEN; - data[idx++] = (byte)sess->haveEMS; - data[idx++] = sess->haveAltSessionID ? ID_LEN : 0; - if (sess->haveAltSessionID) { - XMEMCPY(data + idx, sess->altSessionID, ID_LEN); - idx += ID_LEN; - } -#ifdef SESSION_CERTS - data[idx++] = (byte)sess->chain.count; - for (i = 0; i < sess->chain.count; i++) { - c16toa((word16)sess->chain.certs[i].length, data + idx); - idx += OPAQUE16_LEN; - XMEMCPY(data + idx, sess->chain.certs[i].buffer, - sess->chain.certs[i].length); - idx += sess->chain.certs[i].length; - } -#endif -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - data[idx++] = sess->version.major; - data[idx++] = sess->version.minor; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - data[idx++] = sess->cipherSuite0; - data[idx++] = sess->cipherSuite; -#endif -#ifndef NO_CLIENT_CACHE - c16toa(sess->idLen, data + idx); idx += OPAQUE16_LEN; - XMEMCPY(data + idx, sess->serverID, sess->idLen); - idx += sess->idLen; -#endif -#ifdef WOLFSSL_SESSION_ID_CTX - data[idx++] = sess->sessionCtxSz; - XMEMCPY(data + idx, sess->sessionCtx, sess->sessionCtxSz); - idx += sess->sessionCtxSz; -#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - data[idx++] = sess->peerVerifyRet; -#endif -#ifdef WOLFSSL_TLS13 - c16toa(sess->namedGroup, data + idx); - idx += OPAQUE16_LEN; -#endif -#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) -#ifdef WOLFSSL_TLS13 -#ifdef WOLFSSL_32BIT_MILLI_TIME - c32toa(sess->ticketSeen, data + idx); - idx += OPAQUE32_LEN; -#else - c32toa((word32)(sess->ticketSeen >> 32), data + idx); - idx += OPAQUE32_LEN; - c32toa((word32)sess->ticketSeen, data + idx); - idx += OPAQUE32_LEN; -#endif - c32toa(sess->ticketAdd, data + idx); - idx += OPAQUE32_LEN; - data[idx++] = sess->ticketNonce.len; - XMEMCPY(data + idx, sess->ticketNonce.data, sess->ticketNonce.len); - idx += sess->ticketNonce.len; -#endif -#ifdef WOLFSSL_EARLY_DATA - c32toa(sess->maxEarlyDataSz, data + idx); - idx += OPAQUE32_LEN; -#endif -#endif -#ifdef HAVE_SESSION_TICKET - c16toa(sess->ticketLen, data + idx); idx += OPAQUE16_LEN; - XMEMCPY(data + idx, sess->ticket, sess->ticketLen); - idx += sess->ticketLen; -#endif - } -#endif - - (void)sess; - (void)p; -#ifdef HAVE_EXT_CACHE - (void)idx; -#endif - - return size; -} - - -/* TODO: no function to free new session. - * - * Note: It is expected that the importing and exporting function have been - * built with the same settings. For example if session tickets was - * enabled with the wolfSSL library exporting a session then it is - * expected to be turned on with the wolfSSL library importing the session. - */ -WOLFSSL_SESSION* wolfSSL_d2i_SSL_SESSION(WOLFSSL_SESSION** sess, - const unsigned char** p, long i) -{ - WOLFSSL_SESSION* s = NULL; - int ret = 0; -#if defined(HAVE_EXT_CACHE) - int idx = 0; - byte* data; -#ifdef SESSION_CERTS - int j; - word16 length; -#endif -#endif /* HAVE_EXT_CACHE */ - - (void)p; - (void)i; - (void)ret; - (void)sess; - -#ifdef HAVE_EXT_CACHE - if (p == NULL || *p == NULL) - return NULL; - - s = wolfSSL_SESSION_new(); - if (s == NULL) - return NULL; - - idx = 0; - data = (byte*)*p; - - /* side | bornOn | timeout | sessionID len */ - if (i < OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->side = data[idx++]; - ato32(data + idx, &s->bornOn); idx += OPAQUE32_LEN; - ato32(data + idx, &s->timeout); idx += OPAQUE32_LEN; - s->sessionIDSz = data[idx++]; - - /* sessionID | secret | haveEMS | haveAltSessionID */ - if (i - idx < s->sessionIDSz + SECRET_LEN + OPAQUE8_LEN + OPAQUE8_LEN) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->sessionID, data + idx, s->sessionIDSz); - idx += s->sessionIDSz; - XMEMCPY(s->masterSecret, data + idx, SECRET_LEN); idx += SECRET_LEN; - s->haveEMS = data[idx++]; - if (data[idx] != ID_LEN && data[idx] != 0) { - ret = BUFFER_ERROR; - goto end; - } - s->haveAltSessionID = data[idx++] == ID_LEN; - - /* altSessionID */ - if (s->haveAltSessionID) { - if (i - idx < ID_LEN) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->altSessionID, data + idx, ID_LEN); idx += ID_LEN; - } - -#ifdef SESSION_CERTS - /* Certificate chain */ - if (i - idx == 0) { - ret = BUFFER_ERROR; - goto end; - } - s->chain.count = data[idx++]; - for (j = 0; j < s->chain.count; j++) { - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - ato16(data + idx, &length); idx += OPAQUE16_LEN; - s->chain.certs[j].length = length; - if (i - idx < length) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->chain.certs[j].buffer, data + idx, length); - idx += length; - } -#endif -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - /* Protocol Version */ - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->version.major = data[idx++]; - s->version.minor = data[idx++]; -#endif -#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) - /* Cipher suite */ - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->cipherSuite0 = data[idx++]; - s->cipherSuite = data[idx++]; -#endif -#ifndef NO_CLIENT_CACHE - /* ServerID len */ - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - ato16(data + idx, &s->idLen); idx += OPAQUE16_LEN; - - /* ServerID */ - if (i - idx < s->idLen) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->serverID, data + idx, s->idLen); idx += s->idLen; -#endif -#ifdef WOLFSSL_SESSION_ID_CTX - /* byte for length of session context ID */ - if (i - idx < OPAQUE8_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->sessionCtxSz = data[idx++]; - - /* app session context ID */ - if (i - idx < s->sessionCtxSz) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->sessionCtx, data + idx, s->sessionCtxSz); idx += s->sessionCtxSz; -#endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - /* byte for peerVerifyRet */ - if (i - idx < OPAQUE8_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->peerVerifyRet = data[idx++]; -#endif -#ifdef WOLFSSL_TLS13 - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - ato16(data + idx, &s->namedGroup); - idx += OPAQUE16_LEN; -#endif -#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) -#ifdef WOLFSSL_TLS13 - if (i - idx < (OPAQUE32_LEN * 2)) { - ret = BUFFER_ERROR; - goto end; - } -#ifdef WOLFSSL_32BIT_MILLI_TIME - ato32(data + idx, &s->ticketSeen); - idx += OPAQUE32_LEN; -#else - { - word32 seenHi, seenLo; - - ato32(data + idx, &seenHi); - idx += OPAQUE32_LEN; - ato32(data + idx, &seenLo); - idx += OPAQUE32_LEN; - s->ticketSeen = ((sword64)seenHi << 32) + seenLo; - } -#endif - ato32(data + idx, &s->ticketAdd); - idx += OPAQUE32_LEN; - if (i - idx < OPAQUE8_LEN) { - ret = BUFFER_ERROR; - goto end; - } - s->ticketNonce.len = data[idx++]; - - if (i - idx < s->ticketNonce.len) { - ret = BUFFER_ERROR; - goto end; - } -#if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - ret = SessionTicketNoncePopulate(s, data + idx, s->ticketNonce.len); - if (ret != 0) - goto end; -#else - if (s->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->ticketNonce.data, data + idx, s->ticketNonce.len); -#endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */ - - idx += s->ticketNonce.len; -#endif -#ifdef WOLFSSL_EARLY_DATA - if (i - idx < OPAQUE32_LEN) { - ret = BUFFER_ERROR; - goto end; - } - ato32(data + idx, &s->maxEarlyDataSz); - idx += OPAQUE32_LEN; -#endif -#endif -#ifdef HAVE_SESSION_TICKET - /* ticket len */ - if (i - idx < OPAQUE16_LEN) { - ret = BUFFER_ERROR; - goto end; - } - ato16(data + idx, &s->ticketLen); idx += OPAQUE16_LEN; - - /* Dispose of ol dynamic ticket and ensure space for new ticket. */ - if (s->ticketLenAlloc > 0) { - XFREE(s->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK); - } - if (s->ticketLen <= SESSION_TICKET_LEN) - s->ticket = s->staticTicket; - else { - s->ticket = (byte*)XMALLOC(s->ticketLen, NULL, - DYNAMIC_TYPE_SESSION_TICK); - if (s->ticket == NULL) { - ret = MEMORY_ERROR; - goto end; - } - s->ticketLenAlloc = (word16)s->ticketLen; - } - - /* ticket */ - if (i - idx < s->ticketLen) { - ret = BUFFER_ERROR; - goto end; - } - XMEMCPY(s->ticket, data + idx, s->ticketLen); idx += s->ticketLen; -#endif - (void)idx; - - if (sess != NULL) { - *sess = s; - } - - s->isSetup = 1; - - *p += idx; - -end: - if (ret != 0 && (sess == NULL || *sess != s)) { - wolfSSL_FreeSession(NULL, s); - s = NULL; - } -#endif /* HAVE_EXT_CACHE */ - return s; -} - -/* Check if there is a session ticket associated with this WOLFSSL_SESSION. - * - * sess - pointer to WOLFSSL_SESSION struct - * - * Returns 1 if has session ticket, otherwise 0 */ -int wolfSSL_SESSION_has_ticket(const WOLFSSL_SESSION* sess) -{ - WOLFSSL_ENTER("wolfSSL_SESSION_has_ticket"); -#ifdef HAVE_SESSION_TICKET - sess = ClientSessionToSession(sess); - if (sess) { - if ((sess->ticketLen > 0) && (sess->ticket != NULL)) { - return WOLFSSL_SUCCESS; - } - } -#else - (void)sess; -#endif - return WOLFSSL_FAILURE; -} - -unsigned long wolfSSL_SESSION_get_ticket_lifetime_hint( - const WOLFSSL_SESSION* sess) -{ - WOLFSSL_ENTER("wolfSSL_SESSION_get_ticket_lifetime_hint"); - sess = ClientSessionToSession(sess); - if (sess) { - return sess->timeout; - } - return 0; -} - -long wolfSSL_SESSION_get_timeout(const WOLFSSL_SESSION* sess) -{ - long timeout = 0; - WOLFSSL_ENTER("wolfSSL_SESSION_get_timeout"); - sess = ClientSessionToSession(sess); - if (sess) - timeout = sess->timeout; - return timeout; -} - -long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t) -{ - word32 tmptime; - - ses = ClientSessionToSession(ses); - if (ses == NULL || t < 0) { - return BAD_FUNC_ARG; - } - - tmptime = t & 0xFFFFFFFF; - ses->timeout = tmptime; - - return WOLFSSL_SUCCESS; -} - -long wolfSSL_SESSION_get_time(const WOLFSSL_SESSION* sess) -{ - long bornOn = 0; - WOLFSSL_ENTER("wolfSSL_SESSION_get_time"); - sess = ClientSessionToSession(sess); - if (sess) - bornOn = sess->bornOn; - return bornOn; -} - -long wolfSSL_SESSION_set_time(WOLFSSL_SESSION *ses, long t) -{ - - ses = ClientSessionToSession(ses); - if (ses == NULL || t < 0) { - return 0; - } - ses->bornOn = (word32)t; - return t; -} - -#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */ - -#ifdef OPENSSL_EXTRA - -#if defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM) -int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) -{ - int ret = WOLFSSL_FATAL_ERROR; - - WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file"); - if (ssl != NULL && fname != NULL) - { - #ifdef WOLFSSL_SMALL_STACK - byte staticBuffer[1]; /* force heap usage */ - #else - byte staticBuffer[FILE_BUFFER_SIZE]; - #endif - byte* myBuffer = staticBuffer; - int dynamic = 0; - XFILE file; - long sz = 0; - WOLFSSL_CTX* ctx = ssl->ctx; - WOLFSSL_X509* peer_cert = &ssl->peerCert; - DerBuffer* fileDer = NULL; - - file = XFOPEN(fname, "rb"); - if (file == XBADFILE) - return WOLFSSL_BAD_FILE; - - if (XFSEEK(file, 0, XSEEK_END) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - sz = XFTELL(file); - if (XFSEEK(file, 0, XSEEK_SET) != 0) { - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - - if (sz > MAX_WOLFSSL_FILE_SIZE || sz < 0) { - WOLFSSL_MSG("cmp_peer_cert_to_file size error"); - XFCLOSE(file); - return WOLFSSL_BAD_FILE; - } - - if (sz > (long)sizeof(staticBuffer)) { - WOLFSSL_MSG("Getting dynamic buffer"); - myBuffer = (byte*)XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE); - dynamic = 1; - } - - if ((myBuffer != NULL) && - (sz > 0) && - (XFREAD(myBuffer, 1, sz, file) == (size_t)sz) && - (PemToDer(myBuffer, (long)sz, CERT_TYPE, - &fileDer, ctx->heap, NULL, NULL) == 0) && - (fileDer->length != 0) && - (fileDer->length == peer_cert->derCert->length) && - (XMEMCMP(peer_cert->derCert->buffer, fileDer->buffer, - fileDer->length) == 0)) - { - ret = 0; - } - - FreeDer(&fileDer); - - if (dynamic) - XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE); - - XFCLOSE(file); - } - - return ret; -} -#endif -#endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -const WOLFSSL_ObjectInfo wolfssl_object_info[] = { -#ifndef NO_CERTS - /* oidCertExtType */ - { NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints", - "X509v3 Basic Constraints"}, - { NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName", - "X509v3 Subject Alternative Name"}, - { NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, "crlDistributionPoints", - "X509v3 CRL Distribution Points"}, - { NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess", - "Authority Information Access"}, - { NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType, - "authorityKeyIdentifier", "X509v3 Authority Key Identifier"}, - { NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType, - "subjectKeyIdentifier", "X509v3 Subject Key Identifier"}, - { NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage", - "X509v3 Key Usage"}, - { NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType, - "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"}, - { NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType, - "extendedKeyUsage", "X509v3 Extended Key Usage"}, - { NID_name_constraints, NAME_CONS_OID, oidCertExtType, - "nameConstraints", "X509v3 Name Constraints"}, - { NID_certificate_policies, CERT_POLICY_OID, oidCertExtType, - "certificatePolicies", "X509v3 Certificate Policies"}, - - /* oidCertAuthInfoType */ - { NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP", - "OCSP"}, - { NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType, - "caIssuers", "CA Issuers"}, - - /* oidCertPolicyType */ - { NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy", - "X509v3 Any Policy"}, - - /* oidCertAltNameType */ - { NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""}, - - /* oidCertKeyUseType */ - { NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType, - "anyExtendedKeyUsage", "Any Extended Key Usage"}, - { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType, - "serverAuth", "TLS Web Server Authentication"}, - { EKU_CLIENT_AUTH_OID, EKU_CLIENT_AUTH_OID, oidCertKeyUseType, - "clientAuth", "TLS Web Client Authentication"}, - { EKU_OCSP_SIGN_OID, EKU_OCSP_SIGN_OID, oidCertKeyUseType, - "OCSPSigning", "OCSP Signing"}, - - /* oidCertNameType */ - { NID_commonName, NID_commonName, oidCertNameType, "CN", "commonName"}, -#if !defined(WOLFSSL_CERT_REQ) - { NID_surname, NID_surname, oidCertNameType, "SN", "surname"}, -#endif - { NID_serialNumber, NID_serialNumber, oidCertNameType, "serialNumber", - "serialNumber"}, - { NID_userId, NID_userId, oidCertNameType, "UID", "userid"}, - { NID_countryName, NID_countryName, oidCertNameType, "C", "countryName"}, - { NID_localityName, NID_localityName, oidCertNameType, "L", "localityName"}, - { NID_stateOrProvinceName, NID_stateOrProvinceName, oidCertNameType, "ST", - "stateOrProvinceName"}, - { NID_streetAddress, NID_streetAddress, oidCertNameType, "street", - "streetAddress"}, - { NID_organizationName, NID_organizationName, oidCertNameType, "O", - "organizationName"}, - { NID_organizationalUnitName, NID_organizationalUnitName, oidCertNameType, - "OU", "organizationalUnitName"}, - { NID_emailAddress, NID_emailAddress, oidCertNameType, "emailAddress", - "emailAddress"}, - { NID_domainComponent, NID_domainComponent, oidCertNameType, "DC", - "domainComponent"}, - { NID_favouriteDrink, NID_favouriteDrink, oidCertNameType, "favouriteDrink", - "favouriteDrink"}, - { NID_businessCategory, NID_businessCategory, oidCertNameType, "businessCategory", - "businessCategory"}, - { NID_jurisdictionCountryName, NID_jurisdictionCountryName, oidCertNameType, "jurisdictionC", - "jurisdictionCountryName"}, - { NID_jurisdictionStateOrProvinceName, NID_jurisdictionStateOrProvinceName, - oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"}, - { NID_postalCode, NID_postalCode, oidCertNameType, "postalCode", "postalCode"}, - { NID_userId, NID_userId, oidCertNameType, "UID", "userId"}, - -#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) - { NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, - oidCsrAttrType, "challengePassword", "challengePassword"}, - { NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID, - oidCsrAttrType, "contentType", "contentType" }, - { NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID, - oidCsrAttrType, "unstructuredName", "unstructuredName" }, - { NID_name, NAME_OID, oidCsrAttrType, "name", "name" }, - { NID_surname, SURNAME_OID, - oidCsrAttrType, "surname", "surname" }, - { NID_givenName, GIVEN_NAME_OID, - oidCsrAttrType, "givenName", "givenName" }, - { NID_initials, INITIALS_OID, - oidCsrAttrType, "initials", "initials" }, - { NID_dnQualifier, DNQUALIFIER_OID, - oidCsrAttrType, "dnQualifer", "dnQualifier" }, -#endif -#endif -#ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */ - /* oidHashType */ - #ifdef WOLFSSL_MD2 - { NID_md2, MD2h, oidHashType, "MD2", "md2"}, - #endif - #ifdef WOLFSSL_MD5 - { NID_md5, MD5h, oidHashType, "MD5", "md5"}, - #endif - #ifndef NO_SHA - { NID_sha1, SHAh, oidHashType, "SHA1", "sha1"}, - #endif - #ifdef WOLFSSL_SHA224 - { NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"}, - #endif - #ifndef NO_SHA256 - { NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"}, - #endif - #ifdef WOLFSSL_SHA384 - { NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"}, - #endif - #ifdef WOLFSSL_SHA512 - { NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"}, - #endif - #ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - { NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"}, - #endif - #ifndef WOLFSSL_NOSHA3_256 - { NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"}, - #endif - #ifndef WOLFSSL_NOSHA3_384 - { NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"}, - #endif - #ifndef WOLFSSL_NOSHA3_512 - { NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"}, - #endif - #endif /* WOLFSSL_SHA3 */ - #ifdef WOLFSSL_SM3 - { NID_sm3, SM3h, oidHashType, "SM3", "sm3"}, - #endif - /* oidSigType */ - #ifndef NO_DSA - #ifndef NO_SHA - { NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"}, - { NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256", - "dsa_with_SHA256"}, - #endif - #endif /* NO_DSA */ - #ifndef NO_RSA - #ifdef WOLFSSL_MD2 - { NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2", - "md2WithRSAEncryption"}, - #endif - #ifndef NO_MD5 - { NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5", - "md5WithRSAEncryption"}, - #endif - #ifndef NO_SHA - { NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1", - "sha1WithRSAEncryption"}, - #endif - #ifdef WOLFSSL_SHA224 - { NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224", - "sha224WithRSAEncryption"}, - #endif - #ifndef NO_SHA256 - { NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256", - "sha256WithRSAEncryption"}, - #endif - #ifdef WOLFSSL_SHA384 - { NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384", - "sha384WithRSAEncryption"}, - #endif - #ifdef WOLFSSL_SHA512 - { NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512", - "sha512WithRSAEncryption"}, - #endif - #ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - { NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224", - "sha3-224WithRSAEncryption"}, - #endif - #ifndef WOLFSSL_NOSHA3_256 - { NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256", - "sha3-256WithRSAEncryption"}, - #endif - #ifndef WOLFSSL_NOSHA3_384 - { NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384", - "sha3-384WithRSAEncryption"}, - #endif - #ifndef WOLFSSL_NOSHA3_512 - { NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512", - "sha3-512WithRSAEncryption"}, - #endif - #endif - #ifdef WC_RSA_PSS - { NID_rsassaPss, CTC_RSASSAPSS, oidSigType, "RSASSA-PSS", "rsassaPss" }, - #endif - #endif /* NO_RSA */ - #ifdef HAVE_ECC - #ifndef NO_SHA - { NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1", "shaWithECDSA"}, - #endif - #ifdef WOLFSSL_SHA224 - { NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType, "ecdsa-with-SHA224","sha224WithECDSA"}, - #endif - #ifndef NO_SHA256 - { NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType, "ecdsa-with-SHA256","sha256WithECDSA"}, - #endif - #ifdef WOLFSSL_SHA384 - { NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType, "ecdsa-with-SHA384","sha384WithECDSA"}, - #endif - #ifdef WOLFSSL_SHA512 - { NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType, "ecdsa-with-SHA512","sha512WithECDSA"}, - #endif - #ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - { NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType, "id-ecdsa-with-SHA3-224", - "ecdsa_with_SHA3-224"}, - #endif - #ifndef WOLFSSL_NOSHA3_256 - { NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType, "id-ecdsa-with-SHA3-256", - "ecdsa_with_SHA3-256"}, - #endif - #ifndef WOLFSSL_NOSHA3_384 - { NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType, "id-ecdsa-with-SHA3-384", - "ecdsa_with_SHA3-384"}, - #endif - #ifndef WOLFSSL_NOSHA3_512 - { NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType, "id-ecdsa-with-SHA3-512", - "ecdsa_with_SHA3-512"}, - #endif - #endif - #endif /* HAVE_ECC */ - - /* oidKeyType */ - #ifndef NO_DSA - { NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"}, - #endif /* NO_DSA */ - #ifndef NO_RSA - { NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption", "rsaEncryption"}, - #ifdef WC_RSA_PSS - { NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"}, - #endif - #endif /* NO_RSA */ - #ifdef HAVE_ECC - { NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey", - "id-ecPublicKey"}, - #endif /* HAVE_ECC */ - #ifndef NO_DH - { NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement", "dhKeyAgreement"}, - #endif - #ifdef HAVE_ED448 - { NID_ED448, ED448k, oidKeyType, "ED448", "ED448"}, - #endif - #ifdef HAVE_ED25519 - { NID_ED25519, ED25519k, oidKeyType, "ED25519", "ED25519"}, - #endif - #ifdef HAVE_PQC - #ifdef HAVE_FALCON - { CTC_FALCON_LEVEL1, FALCON_LEVEL1k, oidKeyType, "Falcon Level 1", - "Falcon Level 1"}, - { CTC_FALCON_LEVEL5, FALCON_LEVEL5k, oidKeyType, "Falcon Level 5", - "Falcon Level 5"}, - #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM - { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k, oidKeyType, - "Dilithium Level 2", "Dilithium Level 2"}, - { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k, oidKeyType, - "Dilithium Level 3", "Dilithium Level 3"}, - { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k, oidKeyType, - "Dilithium Level 5", "Dilithium Level 5"}, - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ - - /* oidCurveType */ - #ifdef HAVE_ECC - { NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", "prime192v1"}, - { NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", "prime192v2"}, - { NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", "prime192v3"}, - - { NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", "prime239v1"}, - { NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", "prime239v2"}, - { NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", "prime239v3"}, - - { NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", "prime256v1"}, - - { NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", "secp112r1"}, - { NID_secp112r2, ECC_SECP112R2_OID, oidCurveType, "secp112r2", "secp112r2"}, - - { NID_secp128r1, ECC_SECP128R1_OID, oidCurveType, "secp128r1", "secp128r1"}, - { NID_secp128r2, ECC_SECP128R2_OID, oidCurveType, "secp128r2", "secp128r2"}, - - { NID_secp160r1, ECC_SECP160R1_OID, oidCurveType, "secp160r1", "secp160r1"}, - { NID_secp160r2, ECC_SECP160R2_OID, oidCurveType, "secp160r2", "secp160r2"}, - - { NID_secp224r1, ECC_SECP224R1_OID, oidCurveType, "secp224r1", "secp224r1"}, - { NID_secp384r1, ECC_SECP384R1_OID, oidCurveType, "secp384r1", "secp384r1"}, - { NID_secp521r1, ECC_SECP521R1_OID, oidCurveType, "secp521r1", "secp521r1"}, - - { NID_secp160k1, ECC_SECP160K1_OID, oidCurveType, "secp160k1", "secp160k1"}, - { NID_secp192k1, ECC_SECP192K1_OID, oidCurveType, "secp192k1", "secp192k1"}, - { NID_secp224k1, ECC_SECP224K1_OID, oidCurveType, "secp224k1", "secp224k1"}, - { NID_secp256k1, ECC_SECP256K1_OID, oidCurveType, "secp256k1", "secp256k1"}, - - { NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID, oidCurveType, "brainpoolP160r1", "brainpoolP160r1"}, - { NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID, oidCurveType, "brainpoolP192r1", "brainpoolP192r1"}, - { NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID, oidCurveType, "brainpoolP224r1", "brainpoolP224r1"}, - { NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID, oidCurveType, "brainpoolP256r1", "brainpoolP256r1"}, - { NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID, oidCurveType, "brainpoolP320r1", "brainpoolP320r1"}, - { NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID, oidCurveType, "brainpoolP384r1", "brainpoolP384r1"}, - { NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID, oidCurveType, "brainpoolP512r1", "brainpoolP512r1"}, - - #ifdef WOLFSSL_SM2 - { NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"}, - #endif - #endif /* HAVE_ECC */ - - /* oidBlkType */ - #ifdef WOLFSSL_AES_128 - { AES128CBCb, AES128CBCb, oidBlkType, "AES-128-CBC", "aes-128-cbc"}, - #endif - #ifdef WOLFSSL_AES_192 - { AES192CBCb, AES192CBCb, oidBlkType, "AES-192-CBC", "aes-192-cbc"}, - #endif - #ifdef WOLFSSL_AES_256 - { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"}, - #endif - #ifndef NO_DES3 - { NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"}, - { NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"}, - #endif /* !NO_DES3 */ - #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - { NID_chacha20_poly1305, NID_chacha20_poly1305, oidBlkType, "ChaCha20-Poly1305", "chacha20-poly1305"}, - #endif - - /* oidOcspType */ - #ifdef HAVE_OCSP - { NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType, "basicOCSPResponse", - "Basic OCSP Response"}, - { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", - "OCSP Nonce"}, - #endif /* HAVE_OCSP */ - - #ifndef NO_PWDBASED - /* oidKdfType */ - { PBKDF2_OID, PBKDF2_OID, oidKdfType, "PBKDFv2", "PBKDF2"}, - - /* oidPBEType */ - { PBE_SHA1_RC4_128, PBE_SHA1_RC4_128, oidPBEType, - "PBE-SHA1-RC4-128", "pbeWithSHA1And128BitRC4"}, - { PBE_SHA1_DES, PBE_SHA1_DES, oidPBEType, "PBE-SHA1-DES", - "pbeWithSHA1AndDES-CBC"}, - { PBE_SHA1_DES3, PBE_SHA1_DES3, oidPBEType, "PBE-SHA1-3DES", - "pbeWithSHA1And3-KeyTripleDES-CBC"}, - #endif - - /* oidKeyWrapType */ - #ifdef WOLFSSL_AES_128 - { AES128_WRAP, AES128_WRAP, oidKeyWrapType, "AES-128 wrap", "aes128-wrap"}, - #endif - #ifdef WOLFSSL_AES_192 - { AES192_WRAP, AES192_WRAP, oidKeyWrapType, "AES-192 wrap", "aes192-wrap"}, - #endif - #ifdef WOLFSSL_AES_256 - { AES256_WRAP, AES256_WRAP, oidKeyWrapType, "AES-256 wrap", "aes256-wrap"}, - #endif - - #ifndef NO_PKCS7 - #ifndef NO_DH - /* oidCmsKeyAgreeType */ - #ifndef NO_SHA - { dhSinglePass_stdDH_sha1kdf_scheme, dhSinglePass_stdDH_sha1kdf_scheme, - oidCmsKeyAgreeType, "dhSinglePass-stdDH-sha1kdf-scheme", "dhSinglePass-stdDH-sha1kdf-scheme"}, - #endif - #ifdef WOLFSSL_SHA224 - { dhSinglePass_stdDH_sha224kdf_scheme, - dhSinglePass_stdDH_sha224kdf_scheme, oidCmsKeyAgreeType, - "dhSinglePass-stdDH-sha224kdf-scheme", "dhSinglePass-stdDH-sha224kdf-scheme"}, - #endif - #ifndef NO_SHA256 - { dhSinglePass_stdDH_sha256kdf_scheme, - dhSinglePass_stdDH_sha256kdf_scheme, oidCmsKeyAgreeType, - "dhSinglePass-stdDH-sha256kdf-scheme", "dhSinglePass-stdDH-sha256kdf-scheme"}, - #endif - #ifdef WOLFSSL_SHA384 - { dhSinglePass_stdDH_sha384kdf_scheme, - dhSinglePass_stdDH_sha384kdf_scheme, oidCmsKeyAgreeType, - "dhSinglePass-stdDH-sha384kdf-scheme", "dhSinglePass-stdDH-sha384kdf-scheme"}, - #endif - #ifdef WOLFSSL_SHA512 - { dhSinglePass_stdDH_sha512kdf_scheme, - dhSinglePass_stdDH_sha512kdf_scheme, oidCmsKeyAgreeType, - "dhSinglePass-stdDH-sha512kdf-scheme", "dhSinglePass-stdDH-sha512kdf-scheme"}, - #endif - #endif - #endif - #if defined(WOLFSSL_APACHE_HTTPD) - /* "1.3.6.1.5.5.7.8.7" */ - { NID_id_on_dnsSRV, NID_id_on_dnsSRV, oidCertNameType, - WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV }, - - /* "1.3.6.1.4.1.311.20.2.3" */ - { NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN, - WOLFSSL_LN_MS_UPN }, - - /* "1.3.6.1.5.5.7.1.24" */ - { NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType, - WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE }, - #endif -#endif /* OPENSSL_EXTRA */ -}; - -#define WOLFSSL_OBJECT_INFO_SZ \ - (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info)) -const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ; -#endif - -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -/* Free the dynamically allocated data. - * - * p Pointer to dynamically allocated memory. - */ -void wolfSSL_OPENSSL_free(void* p) -{ - WOLFSSL_MSG("wolfSSL_OPENSSL_free"); - - XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL); -} -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ - -#ifdef OPENSSL_EXTRA - -void *wolfSSL_OPENSSL_malloc(size_t a) -{ - return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL); -} - -int wolfSSL_OPENSSL_hexchar2int(unsigned char c) -{ - /* 'char' is unsigned on some platforms. */ - return (int)(signed char)HexCharToByte((char)c); -} - -unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len) -{ - unsigned char* targetBuf; - int srcDigitHigh = 0; - int srcDigitLow = 0; - size_t srcLen; - size_t srcIdx = 0; - long targetIdx = 0; - - srcLen = XSTRLEN(str); - targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL); - if (targetBuf == NULL) { - return NULL; - } - - while (srcIdx < srcLen) { - if (str[srcIdx] == ':') { - srcIdx++; - continue; - } - - srcDigitHigh = wolfSSL_OPENSSL_hexchar2int(str[srcIdx++]); - srcDigitLow = wolfSSL_OPENSSL_hexchar2int(str[srcIdx++]); - if (srcDigitHigh < 0 || srcDigitLow < 0) { - WOLFSSL_MSG("Invalid hex character."); - XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL); - return NULL; - } - - targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) | srcDigitLow); - } - - if (len != NULL) - *len = targetIdx; - - return targetBuf; -} - -int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings) -{ - (void)opts; - (void)settings; - return wolfSSL_library_init(); -} - -int wolfSSL_OPENSSL_init_crypto(word64 opts, const OPENSSL_INIT_SETTINGS* settings) -{ - (void)opts; - (void)settings; - return wolfSSL_library_init(); -} - -#if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER) - -int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, - unsigned char* passwd, int passwdSz, byte **cipherInfo, - int maxDerSz) -{ - int ret, paddingSz; - word32 idx, cipherInfoSz; -#ifdef WOLFSSL_SMALL_STACK - EncryptedInfo* info = NULL; -#else - EncryptedInfo info[1]; -#endif - - WOLFSSL_ENTER("EncryptDerKey"); - - if (der == NULL || derSz == NULL || cipher == NULL || - passwd == NULL || cipherInfo == NULL) - return BAD_FUNC_ARG; - -#ifdef WOLFSSL_SMALL_STACK - info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL, - DYNAMIC_TYPE_ENCRYPTEDINFO); - if (info == NULL) { - WOLFSSL_MSG("malloc failed"); - return WOLFSSL_FAILURE; - } -#endif - - XMEMSET(info, 0, sizeof(EncryptedInfo)); - - /* set the cipher name on info */ - XSTRNCPY(info->name, cipher, NAME_SZ-1); - info->name[NAME_SZ-1] = '\0'; /* null term */ - - ret = wc_EncryptedInfoGet(info, info->name); - if (ret != 0) { - WOLFSSL_MSG("unsupported cipher"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); - #endif - return WOLFSSL_FAILURE; - } - - /* Generate a random salt */ - if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("generate iv failed"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); -#endif - return WOLFSSL_FAILURE; - } - - /* add the padding before encryption */ - paddingSz = ((*derSz)/info->ivSz + 1) * info->ivSz - (*derSz); - if (paddingSz == 0) - paddingSz = info->ivSz; - if (maxDerSz < *derSz + paddingSz) { - WOLFSSL_MSG("not enough DER buffer allocated"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); -#endif - return WOLFSSL_FAILURE; - } - XMEMSET(der+(*derSz), (byte)paddingSz, paddingSz); - (*derSz) += paddingSz; - - /* encrypt buffer */ - if (wc_BufferKeyEncrypt(info, der, *derSz, passwd, passwdSz, WC_MD5) != 0) { - WOLFSSL_MSG("encrypt key failed"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); -#endif - return WOLFSSL_FAILURE; - } - - /* create cipher info : 'cipher_name,Salt(hex)' */ - cipherInfoSz = (word32)(2*info->ivSz + XSTRLEN(info->name) + 2); - *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, - DYNAMIC_TYPE_STRING); - if (*cipherInfo == NULL) { - WOLFSSL_MSG("malloc failed"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); -#endif - return WOLFSSL_FAILURE; - } - XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz); - XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz); - - idx = (word32)XSTRLEN((char*)*cipherInfo); - cipherInfoSz -= idx; - ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo+idx, &cipherInfoSz); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO); -#endif - if (ret != 0) { - WOLFSSL_MSG("Base16_Encode failed"); - XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING); - return WOLFSSL_FAILURE; - } - - return WOLFSSL_SUCCESS; -} -#endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */ - -#if !defined(NO_BIO) -static int pem_write_pubkey(WOLFSSL_EVP_PKEY* key, void* heap, byte** derBuf, - int* derSz) -{ - byte* buf = NULL; - int sz = 0; - - (void)heap; - - if (key == NULL) { - WOLFSSL_MSG("Bad parameters"); - return WOLFSSL_FAILURE; - } - - switch (key->type) { -#if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: - if ((sz = wolfSSL_RSA_To_Der(key->rsa, &buf, 1, heap)) - < 0) { - WOLFSSL_MSG("wolfSSL_RSA_To_Der failed"); - break; - } - break; -#endif /* WOLFSSL_KEY_GEN && !NO_RSA */ -#if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \ - defined(WOLFSSL_CERT_GEN)) - case EVP_PKEY_DSA: - if (key->dsa == NULL) { - WOLFSSL_MSG("key->dsa is null"); - break; - } - sz = MAX_DSA_PUBKEY_SZ; - buf = (byte*)XMALLOC(sz, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (buf == NULL) { - WOLFSSL_MSG("malloc failed"); - break; - } - /* Key to DER */ - sz = wc_DsaKeyToPublicDer((DsaKey*)key->dsa->internal, buf, sz); - if (sz < 0) { - WOLFSSL_MSG("wc_DsaKeyToDer failed"); - break; - } - break; -#endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */ -#if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) - case EVP_PKEY_EC: - { - if (key->ecc == NULL) { - WOLFSSL_MSG("key->ecc is null"); - break; - } - if ((sz = wolfssl_ec_key_to_pubkey_der(key->ecc, &buf, heap)) <= - 0) { - WOLFSSL_MSG("wolfssl_ec_key_to_pubkey_der failed"); - break; - } - break; - } -#endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */ -#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) - case EVP_PKEY_DH: - WOLFSSL_MSG("Writing DH PUBKEY not supported!"); - break; -#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */ - default: - WOLFSSL_MSG("Unknown Key type!"); - break; - } - - if (buf == NULL || sz <= 0) { - if (buf != NULL) - XFREE(buf, heap, DYNAMIC_TYPE_DER); - return WOLFSSL_FAILURE; - } - - *derBuf = buf; - *derSz = sz; - return WOLFSSL_SUCCESS; -} -#endif - -#ifndef NO_BIO -static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key) -{ - int ret; - int derSz = 0; - byte* derBuf = NULL; - - ret = pem_write_pubkey(key, bio->heap, &derBuf, &derSz); - if (ret == WOLFSSL_SUCCESS) { - ret = der_write_to_bio_as_pem(derBuf, derSz, bio, PUBLICKEY_TYPE); - XFREE(derBuf, bio->heap, DYNAMIC_TYPE_DER); - } - - return ret; -} - -/* Takes a public key and writes it out to a WOLFSSL_BIO - * Returns WOLFSSL_SUCCESS or WOLFSSL_FAILURE - */ -int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key) -{ - int ret; - - WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY"); - - if ((bio == NULL) || (key == NULL)) { - ret = WOLFSSL_FAILURE; - } - else { - ret = pem_write_bio_pubkey(bio, key); - } - - return ret; -} - -/* Takes a private key and writes it out to a WOLFSSL_BIO - * Returns WOLFSSL_SUCCESS or WOLFSSL_FAILURE - */ -int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key, - const WOLFSSL_EVP_CIPHER* cipher, - unsigned char* passwd, int len, - wc_pem_password_cb* cb, void* arg) -{ - byte* keyDer; - int type; - - (void)cipher; - (void)passwd; - (void)len; - (void)cb; - (void)arg; - - WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey"); - - if (bio == NULL || key == NULL) { - WOLFSSL_MSG("Bad Function Arguments"); - return WOLFSSL_FAILURE; - } - - keyDer = (byte*)key->pkey.ptr; - - switch (key->type) { -#ifndef NO_RSA - case EVP_PKEY_RSA: - type = PRIVATEKEY_TYPE; - break; -#endif - -#ifndef NO_DSA - case EVP_PKEY_DSA: - type = DSA_PRIVATEKEY_TYPE; - break; -#endif - -#ifdef HAVE_ECC - case EVP_PKEY_EC: - type = ECC_PRIVATEKEY_TYPE; - break; -#endif - -#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) - case EVP_PKEY_DH: - type = DH_PRIVATEKEY_TYPE; - break; -#endif - - default: - WOLFSSL_MSG("Unknown Key type!"); - type = PRIVATEKEY_TYPE; - } - - return der_write_to_bio_as_pem(keyDer, key->pkey_sz, bio, type); -} -#endif /* !NO_BIO */ - -/* Colon separated list of + algorithms. - * Replaces list in context. - */ -int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list) -{ - WOLFSSL_MSG("wolfSSL_CTX_set1_sigalg_list"); - - if (ctx == NULL || list == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - if (AllocateCtxSuites(ctx) != 0) - return WOLFSSL_FAILURE; - - return SetSuitesHashSigAlgo(ctx->suites, list); -} - -/* Colon separated list of + algorithms. - * Replaces list in SSL. - */ -int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list) -{ - WOLFSSL_MSG("wolfSSL_set1_sigalg_list"); - - if (ssl == NULL || list == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - if (AllocateSuites(ssl) != 0) - return WOLFSSL_FAILURE; - - return SetSuitesHashSigAlgo(ssl->suites, list); -} - -static int HashToNid(byte hashAlgo, int* nid) -{ - int ret = WOLFSSL_SUCCESS; - - /* Cast for compiler to check everything is implemented */ - switch ((enum wc_MACAlgorithm)hashAlgo) { - case no_mac: - case rmd_mac: - *nid = NID_undef; - break; - case md5_mac: - *nid = NID_md5; - break; - case sha_mac: - *nid = NID_sha1; - break; - case sha224_mac: - *nid = NID_sha224; - break; - case sha256_mac: - *nid = NID_sha256; - break; - case sha384_mac: - *nid = NID_sha384; - break; - case sha512_mac: - *nid = NID_sha512; - break; - case blake2b_mac: - *nid = NID_blake2b512; - break; - case sm3_mac: - *nid = NID_sm3; - break; - default: - ret = WOLFSSL_FAILURE; - break; - } - - return ret; -} - -static int SaToNid(byte sa, int* nid) -{ - int ret = WOLFSSL_SUCCESS; - /* Cast for compiler to check everything is implemented */ - switch ((enum SignatureAlgorithm)sa) { - case anonymous_sa_algo: - *nid = NID_undef; - break; - case rsa_sa_algo: - *nid = NID_rsaEncryption; - break; - case dsa_sa_algo: - *nid = NID_dsa; - break; - case ecc_dsa_sa_algo: - *nid = NID_X9_62_id_ecPublicKey; - break; - case rsa_pss_sa_algo: - *nid = NID_rsassaPss; - break; - case ed25519_sa_algo: -#ifdef HAVE_ED25519 - *nid = NID_ED25519; -#else - ret = WOLFSSL_FAILURE; -#endif - break; - case rsa_pss_pss_algo: - *nid = NID_rsassaPss; - break; - case ed448_sa_algo: -#ifdef HAVE_ED448 - *nid = NID_ED448; -#else - ret = WOLFSSL_FAILURE; -#endif - break; - case falcon_level1_sa_algo: - *nid = CTC_FALCON_LEVEL1; - break; - case falcon_level5_sa_algo: - *nid = CTC_FALCON_LEVEL5; - break; - case dilithium_level2_sa_algo: - *nid = CTC_DILITHIUM_LEVEL2; - break; - case dilithium_level3_sa_algo: - *nid = CTC_DILITHIUM_LEVEL3; - break; - case dilithium_level5_sa_algo: - *nid = CTC_DILITHIUM_LEVEL5; - break; - case sm2_sa_algo: - *nid = NID_sm2; - break; - case invalid_sa_algo: - default: - ret = WOLFSSL_FAILURE; - break; - } - return ret; -} - -/* This API returns the hash selected. */ -int wolfSSL_get_signature_nid(WOLFSSL *ssl, int* nid) -{ - WOLFSSL_MSG("wolfSSL_get_signature_nid"); - - if (ssl == NULL || nid == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - return HashToNid(ssl->options.hashAlgo, nid); -} - -/* This API returns the signature selected. */ -int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid) -{ - WOLFSSL_MSG("wolfSSL_get_signature_type_nid"); - - if (ssl == NULL || nid == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - return SaToNid(ssl->options.sigAlgo, nid); -} - -int wolfSSL_get_peer_signature_nid(WOLFSSL* ssl, int* nid) -{ - WOLFSSL_MSG("wolfSSL_get_peer_signature_nid"); - - if (ssl == NULL || nid == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - return HashToNid(ssl->options.peerHashAlgo, nid); -} - -int wolfSSL_get_peer_signature_type_nid(const WOLFSSL* ssl, int* nid) -{ - WOLFSSL_MSG("wolfSSL_get_peer_signature_type_nid"); - - if (ssl == NULL || nid == NULL) { - WOLFSSL_MSG("Bad function arguments"); - return WOLFSSL_FAILURE; - } - - return SaToNid(ssl->options.peerSigAlgo, nid); -} - -#ifdef HAVE_ECC - -#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES) -static int populate_groups(int* groups, int max_count, const char *list) -{ - const char *end; - int count = 0; - const WOLF_EC_NIST_NAME* nist_name; - - if (!groups || !list) { - return -1; - } - - for (end = list; ; list = ++end) { - int len; - - if (count > max_count) { - WOLFSSL_MSG("Too many curves in list"); - return -1; - } - while (*end != ':' && *end != '\0') end++; - len = (int)(end - list); /* end points to char after end - * of curve name so no need for -1 */ - if ((len < kNistCurves_MIN_NAME_LEN) || - (len > kNistCurves_MAX_NAME_LEN)) { - WOLFSSL_MSG("Unrecognized curve name in list"); - return -1; - } - for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) { - if (len == nist_name->name_len && - XSTRNCMP(list, nist_name->name, nist_name->name_len) == 0) { - break; - } - } - if (!nist_name->name) { - WOLFSSL_MSG("Unrecognized curve name in list"); - return -1; - } - groups[count++] = nist_name->nid; - if (*end == '\0') break; - } - - return count; -} - -int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list) -{ - int groups[WOLFSSL_MAX_GROUP_COUNT]; - int count = 0; - - if (!ctx || !list) { - return WOLFSSL_FAILURE; - } - - if ((count = populate_groups(groups, - WOLFSSL_MAX_GROUP_COUNT, list)) == -1) { - return WOLFSSL_FAILURE; - } - - return wolfSSL_CTX_set1_groups(ctx, groups, count); -} - -int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list) -{ - int groups[WOLFSSL_MAX_GROUP_COUNT]; - int count = 0; - - if (!ssl || !list) { - return WOLFSSL_FAILURE; - } - - if ((count = populate_groups(groups, - WOLFSSL_MAX_GROUP_COUNT, list)) == -1) { - return WOLFSSL_FAILURE; - } - - return wolfSSL_set1_groups(ssl, groups, count); -} -#endif /* WOLFSSL_TLS13 */ - -#endif /* HAVE_ECC */ - -#ifndef NO_BIO -WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY** key, - wc_pem_password_cb* cb, - void* pass) -{ - WOLFSSL_EVP_PKEY* pkey = NULL; - DerBuffer* der = NULL; - int keyFormat = 0; - - WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey"); - - if (bio == NULL) - return pkey; - - if (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE, &keyFormat, &der) - >= 0) { - const unsigned char* ptr = der->buffer; - int type = -1; - - if (keyFormat) { - /* keyFormat is Key_Sum enum */ - if (keyFormat == RSAk) - type = EVP_PKEY_RSA; - else if (keyFormat == ECDSAk) - type = EVP_PKEY_EC; - else if (keyFormat == DSAk) - type = EVP_PKEY_DSA; - else if (keyFormat == DHk) - type = EVP_PKEY_DH; - } - else { - /* Default to RSA if format is not set */ - type = EVP_PKEY_RSA; - } - - /* handle case where reuse is attempted */ - if (key != NULL && *key != NULL) - pkey = *key; - - wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length); - if (pkey == NULL) { - WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); - } - } - - FreeDer(&der); - - if (key != NULL && pkey != NULL) - *key = pkey; - - WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", 0); - - return pkey; -} - -WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY **key, - wc_pem_password_cb *cb, - void *pass) -{ - WOLFSSL_EVP_PKEY* pkey = NULL; - DerBuffer* der = NULL; - int keyFormat = 0; - - WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY"); - - if (bio == NULL) - return pkey; - - if (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE, &keyFormat, &der) - >= 0) { - const unsigned char* ptr = der->buffer; - - /* handle case where reuse is attempted */ - if (key != NULL && *key != NULL) - pkey = *key; - - wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length); - if (pkey == NULL) { - WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); - } - } - - FreeDer(&der); - - if (key != NULL && pkey != NULL) - *key = pkey; - - WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0); - - return pkey; -} -#endif /* !NO_BIO */ - -#if !defined(NO_FILESYSTEM) -WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key, - wc_pem_password_cb *cb, void *pass) -{ - WOLFSSL_EVP_PKEY* pkey = NULL; - DerBuffer* der = NULL; - int keyFormat = 0; - - WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY"); - - if ((pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE, &keyFormat, &der) - >= 0) && (der != NULL)) { - const unsigned char* ptr = der->buffer; - - /* handle case where reuse is attempted */ - if ((key != NULL) && (*key != NULL)) { - pkey = *key; - } - - if ((wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) || - (pkey == NULL)) { - WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); - pkey = NULL; - } - } - - FreeDer(&der); - - if ((key != NULL) && (pkey != NULL)) { - *key = pkey; - } - - WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0); - - return pkey; -} -#endif /* NO_FILESYSTEM */ -#endif /* OPENSSL_EXTRA */ - -#ifdef WOLFSSL_ALT_CERT_CHAINS -int wolfSSL_is_peer_alt_cert_chain(const WOLFSSL* ssl) -{ - int isUsing = 0; - if (ssl) - isUsing = ssl->options.usingAltCertChain; - return isUsing; -} -#endif /* WOLFSSL_ALT_CERT_CHAINS */ - - -#ifdef SESSION_CERTS - -#ifdef WOLFSSL_ALT_CERT_CHAINS -/* Get peer's alternate certificate chain */ -WOLFSSL_X509_CHAIN* wolfSSL_get_peer_alt_chain(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_peer_alt_chain"); - if (ssl) - return &ssl->session->altChain; - - return 0; -} -#endif /* WOLFSSL_ALT_CERT_CHAINS */ - - -/* Get peer's certificate chain */ -WOLFSSL_X509_CHAIN* wolfSSL_get_peer_chain(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_peer_chain"); - if (ssl) - return &ssl->session->chain; - - return 0; -} - - -/* Get peer's certificate chain total count */ -int wolfSSL_get_chain_count(WOLFSSL_X509_CHAIN* chain) -{ - WOLFSSL_ENTER("wolfSSL_get_chain_count"); - if (chain) - return chain->count; - - return 0; -} - - -/* Get peer's ASN.1 DER certificate at index (idx) length in bytes */ -int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx) -{ - WOLFSSL_ENTER("wolfSSL_get_chain_length"); - if (chain) - return chain->certs[idx].length; - - return 0; -} - - -/* Get peer's ASN.1 DER certificate at index (idx) */ -byte* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx) -{ - WOLFSSL_ENTER("wolfSSL_get_chain_cert"); - if (chain) - return chain->certs[idx].buffer; - - return 0; -} - - -/* Get peer's wolfSSL X509 certificate at index (idx) */ -WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx) -{ - int ret = 0; - WOLFSSL_X509* x509 = NULL; -#ifdef WOLFSSL_SMALL_STACK - DecodedCert* cert = NULL; -#else - DecodedCert cert[1]; -#endif - - WOLFSSL_ENTER("wolfSSL_get_chain_X509"); - if (chain != NULL) { - #ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, - DYNAMIC_TYPE_DCERT); - if (cert != NULL) - #endif - { - InitDecodedCert(cert, chain->certs[idx].buffer, - chain->certs[idx].length, NULL); - - if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL)) != 0) { - WOLFSSL_MSG("Failed to parse cert"); - } - else { - x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL, - DYNAMIC_TYPE_X509); - if (x509 == NULL) { - WOLFSSL_MSG("Failed alloc X509"); - } - else { - InitX509(x509, 1, NULL); - - if ((ret = CopyDecodedToX509(x509, cert)) != 0) { - WOLFSSL_MSG("Failed to copy decoded"); - wolfSSL_X509_free(x509); - x509 = NULL; - } - } - } - - FreeDecodedCert(cert); - #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); - #endif - } - } - (void)ret; - - return x509; -} - - -/* Get peer's PEM certificate at index (idx), output to buffer if inLen big - enough else return error (-1). If buffer is NULL only calculate - outLen. Output length is in *outLen WOLFSSL_SUCCESS on ok */ -int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, - unsigned char* buf, int inLen, int* outLen) -{ -#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) - const char* header = NULL; - const char* footer = NULL; - int headerLen; - int footerLen; - int i; - int err; - word32 szNeeded = 0; - - WOLFSSL_ENTER("wolfSSL_get_chain_cert_pem"); - if (!chain || !outLen || idx < 0 || idx >= wolfSSL_get_chain_count(chain)) - return BAD_FUNC_ARG; - - err = wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer); - if (err != 0) - return err; - - headerLen = (int)XSTRLEN(header); - footerLen = (int)XSTRLEN(footer); - - /* Null output buffer return size needed in outLen */ - if(!buf) { - if(Base64_Encode(chain->certs[idx].buffer, chain->certs[idx].length, - NULL, &szNeeded) != LENGTH_ONLY_E) - return WOLFSSL_FAILURE; - *outLen = szNeeded + headerLen + footerLen; - return LENGTH_ONLY_E; - } - - /* don't even try if inLen too short */ - if (inLen < headerLen + footerLen + chain->certs[idx].length) - return BAD_FUNC_ARG; - - /* header */ - if (XMEMCPY(buf, header, headerLen) == NULL) - return WOLFSSL_FATAL_ERROR; - - i = headerLen; - - /* body */ - *outLen = inLen; /* input to Base64_Encode */ - if ( (err = Base64_Encode(chain->certs[idx].buffer, - chain->certs[idx].length, buf + i, (word32*)outLen)) < 0) - return err; - i += *outLen; - - /* footer */ - if ( (i + footerLen) > inLen) - return BAD_FUNC_ARG; - if (XMEMCPY(buf + i, footer, footerLen) == NULL) - return WOLFSSL_FATAL_ERROR; - *outLen += headerLen + footerLen; - - return WOLFSSL_SUCCESS; -#else - (void)chain; - (void)idx; - (void)buf; - (void)inLen; - (void)outLen; - return WOLFSSL_FAILURE; -#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */ -} - - -/* get session ID */ -WOLFSSL_ABI -const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session) -{ - WOLFSSL_ENTER("wolfSSL_get_sessionID"); - session = ClientSessionToSession(session); - if (session) - return session->sessionID; - - return NULL; -} - - -#endif /* SESSION_CERTS */ - -#ifdef HAVE_FUZZER -void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx) -{ - if (ssl) { - ssl->fuzzerCb = cbf; - ssl->fuzzerCtx = fCtx; - } -} -#endif - -#ifndef NO_CERTS -#ifdef HAVE_PK_CALLBACKS - -#ifdef HAVE_ECC -void wolfSSL_CTX_SetEccKeyGenCb(WOLFSSL_CTX* ctx, CallbackEccKeyGen cb) -{ - if (ctx) - ctx->EccKeyGenCb = cb; -} -void wolfSSL_SetEccKeyGenCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->EccKeyGenCtx = ctx; -} -void* wolfSSL_GetEccKeyGenCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->EccKeyGenCtx; - - return NULL; -} -void wolfSSL_CTX_SetEccSignCtx(WOLFSSL_CTX* ctx, void *userCtx) -{ - if (ctx) - ctx->EccSignCtx = userCtx; -} -void* wolfSSL_CTX_GetEccSignCtx(WOLFSSL_CTX* ctx) -{ - if (ctx) - return ctx->EccSignCtx; - - return NULL; -} - -WOLFSSL_ABI -void wolfSSL_CTX_SetEccSignCb(WOLFSSL_CTX* ctx, CallbackEccSign cb) -{ - if (ctx) - ctx->EccSignCb = cb; -} -void wolfSSL_SetEccSignCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->EccSignCtx = ctx; -} -void* wolfSSL_GetEccSignCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->EccSignCtx; - - return NULL; -} - -void wolfSSL_CTX_SetEccVerifyCb(WOLFSSL_CTX* ctx, CallbackEccVerify cb) -{ - if (ctx) - ctx->EccVerifyCb = cb; -} -void wolfSSL_SetEccVerifyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->EccVerifyCtx = ctx; -} -void* wolfSSL_GetEccVerifyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->EccVerifyCtx; - - return NULL; -} - -void wolfSSL_CTX_SetEccSharedSecretCb(WOLFSSL_CTX* ctx, CallbackEccSharedSecret cb) -{ - if (ctx) - ctx->EccSharedSecretCb = cb; -} -void wolfSSL_SetEccSharedSecretCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->EccSharedSecretCtx = ctx; -} -void* wolfSSL_GetEccSharedSecretCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->EccSharedSecretCtx; - - return NULL; -} -#endif /* HAVE_ECC */ - -#ifdef HAVE_ED25519 -void wolfSSL_CTX_SetEd25519SignCb(WOLFSSL_CTX* ctx, CallbackEd25519Sign cb) -{ - if (ctx) - ctx->Ed25519SignCb = cb; -} -void wolfSSL_SetEd25519SignCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->Ed25519SignCtx = ctx; -} -void* wolfSSL_GetEd25519SignCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->Ed25519SignCtx; - - return NULL; -} - -void wolfSSL_CTX_SetEd25519VerifyCb(WOLFSSL_CTX* ctx, CallbackEd25519Verify cb) -{ - if (ctx) - ctx->Ed25519VerifyCb = cb; -} -void wolfSSL_SetEd25519VerifyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->Ed25519VerifyCtx = ctx; -} -void* wolfSSL_GetEd25519VerifyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->Ed25519VerifyCtx; - - return NULL; -} -#endif /* HAVE_ED25519 */ - -#ifdef HAVE_CURVE25519 -void wolfSSL_CTX_SetX25519KeyGenCb(WOLFSSL_CTX* ctx, - CallbackX25519KeyGen cb) -{ - if (ctx) - ctx->X25519KeyGenCb = cb; -} -void wolfSSL_SetX25519KeyGenCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->X25519KeyGenCtx = ctx; -} -void* wolfSSL_GetX25519KeyGenCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->X25519KeyGenCtx; - - return NULL; -} - -void wolfSSL_CTX_SetX25519SharedSecretCb(WOLFSSL_CTX* ctx, - CallbackX25519SharedSecret cb) -{ - if (ctx) - ctx->X25519SharedSecretCb = cb; -} -void wolfSSL_SetX25519SharedSecretCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->X25519SharedSecretCtx = ctx; -} -void* wolfSSL_GetX25519SharedSecretCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->X25519SharedSecretCtx; - - return NULL; -} -#endif /* HAVE_CURVE25519 */ - -#ifdef HAVE_ED448 -void wolfSSL_CTX_SetEd448SignCb(WOLFSSL_CTX* ctx, CallbackEd448Sign cb) -{ - if (ctx) - ctx->Ed448SignCb = cb; -} -void wolfSSL_SetEd448SignCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->Ed448SignCtx = ctx; -} -void* wolfSSL_GetEd448SignCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->Ed448SignCtx; - - return NULL; -} - -void wolfSSL_CTX_SetEd448VerifyCb(WOLFSSL_CTX* ctx, CallbackEd448Verify cb) -{ - if (ctx) - ctx->Ed448VerifyCb = cb; -} -void wolfSSL_SetEd448VerifyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->Ed448VerifyCtx = ctx; -} -void* wolfSSL_GetEd448VerifyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->Ed448VerifyCtx; - - return NULL; -} -#endif /* HAVE_ED448 */ - -#ifdef HAVE_CURVE448 -void wolfSSL_CTX_SetX448KeyGenCb(WOLFSSL_CTX* ctx, - CallbackX448KeyGen cb) -{ - if (ctx) - ctx->X448KeyGenCb = cb; -} -void wolfSSL_SetX448KeyGenCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->X448KeyGenCtx = ctx; -} -void* wolfSSL_GetX448KeyGenCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->X448KeyGenCtx; - - return NULL; -} - -void wolfSSL_CTX_SetX448SharedSecretCb(WOLFSSL_CTX* ctx, - CallbackX448SharedSecret cb) -{ - if (ctx) - ctx->X448SharedSecretCb = cb; -} -void wolfSSL_SetX448SharedSecretCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->X448SharedSecretCtx = ctx; -} -void* wolfSSL_GetX448SharedSecretCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->X448SharedSecretCtx; - - return NULL; -} -#endif /* HAVE_CURVE448 */ - -#ifndef NO_RSA -void wolfSSL_CTX_SetRsaSignCb(WOLFSSL_CTX* ctx, CallbackRsaSign cb) -{ - if (ctx) - ctx->RsaSignCb = cb; -} -void wolfSSL_CTX_SetRsaSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb) -{ - if (ctx) - ctx->RsaSignCheckCb = cb; -} -void wolfSSL_SetRsaSignCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaSignCtx = ctx; -} -void* wolfSSL_GetRsaSignCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaSignCtx; - - return NULL; -} - - -void wolfSSL_CTX_SetRsaVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaVerify cb) -{ - if (ctx) - ctx->RsaVerifyCb = cb; -} -void wolfSSL_SetRsaVerifyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaVerifyCtx = ctx; -} -void* wolfSSL_GetRsaVerifyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaVerifyCtx; - - return NULL; -} - -#ifdef WC_RSA_PSS -void wolfSSL_CTX_SetRsaPssSignCb(WOLFSSL_CTX* ctx, CallbackRsaPssSign cb) -{ - if (ctx) - ctx->RsaPssSignCb = cb; -} -void wolfSSL_CTX_SetRsaPssSignCheckCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb) -{ - if (ctx) - ctx->RsaPssSignCheckCb = cb; -} -void wolfSSL_SetRsaPssSignCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaPssSignCtx = ctx; -} -void* wolfSSL_GetRsaPssSignCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaPssSignCtx; - - return NULL; -} - -void wolfSSL_CTX_SetRsaPssVerifyCb(WOLFSSL_CTX* ctx, CallbackRsaPssVerify cb) -{ - if (ctx) - ctx->RsaPssVerifyCb = cb; -} -void wolfSSL_SetRsaPssVerifyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaPssVerifyCtx = ctx; -} -void* wolfSSL_GetRsaPssVerifyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaPssVerifyCtx; - - return NULL; -} -#endif /* WC_RSA_PSS */ - -void wolfSSL_CTX_SetRsaEncCb(WOLFSSL_CTX* ctx, CallbackRsaEnc cb) -{ - if (ctx) - ctx->RsaEncCb = cb; -} -void wolfSSL_SetRsaEncCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaEncCtx = ctx; -} -void* wolfSSL_GetRsaEncCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaEncCtx; - - return NULL; -} - -void wolfSSL_CTX_SetRsaDecCb(WOLFSSL_CTX* ctx, CallbackRsaDec cb) -{ - if (ctx) - ctx->RsaDecCb = cb; -} -void wolfSSL_SetRsaDecCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->RsaDecCtx = ctx; -} -void* wolfSSL_GetRsaDecCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->RsaDecCtx; - - return NULL; -} -#endif /* NO_RSA */ - -/* callback for premaster secret generation */ -void wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb) -{ - if (ctx) - ctx->GenPreMasterCb = cb; -} -/* Set premaster secret generation callback context */ -void wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->GenPreMasterCtx = ctx; -} -/* Get premaster secret generation callback context */ -void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->GenPreMasterCtx; - - return NULL; -} - -/* callback for master secret generation */ -void wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx, CallbackGenMasterSecret cb) -{ - if (ctx) - ctx->GenMasterCb = cb; -} -/* Set master secret generation callback context */ -void wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->GenMasterCtx = ctx; -} -/* Get master secret generation callback context */ -void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->GenMasterCtx; - - return NULL; -} - -/* callback for session key generation */ -void wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb) -{ - if (ctx) - ctx->GenSessionKeyCb = cb; -} -/* Set session key generation callback context */ -void wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->GenSessionKeyCtx = ctx; -} -/* Get session key generation callback context */ -void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->GenSessionKeyCtx; - - return NULL; -} - -/* callback for setting encryption keys */ -void wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb) -{ - if (ctx) - ctx->EncryptKeysCb = cb; -} -/* Set encryption keys callback context */ -void wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->EncryptKeysCtx = ctx; -} -/* Get encryption keys callback context */ -void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->EncryptKeysCtx; - - return NULL; -} - -/* callback for Tls finished */ -/* the callback can be used to build TLS Finished message if enabled */ -void wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb) -{ - if (ctx) - ctx->TlsFinishedCb = cb; -} -/* Set Tls finished callback context */ -void wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->TlsFinishedCtx = ctx; -} -/* Get Tls finished callback context */ -void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->TlsFinishedCtx; - - return NULL; -} -#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY) -/* callback for verify data */ -void wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb) -{ - if (ctx) - ctx->VerifyMacCb = cb; -} - -/* Set set keys callback context */ -void wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->VerifyMacCtx = ctx; -} -/* Get set keys callback context */ -void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->VerifyMacCtx; - - return NULL; -} -#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */ - -void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx, - CallbackHKDFExpandLabel cb) -{ - if (ctx) - ctx->HKDFExpandLabelCb = cb; -} -#ifdef WOLFSSL_PUBLIC_ASN -void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx, - CallbackProcessPeerCert cb) -{ - if (ctx) - ctx->ProcessPeerCertCb = cb; -} -#endif /* WOLFSSL_PUBLIC_ASN */ -void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx, - CallbackProcessServerSigKex cb) -{ - if (ctx) - ctx->ProcessServerSigKexCb = cb; -} -void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, - CallbackPerformTlsRecordProcessing cb) -{ - if (ctx) - ctx->PerformTlsRecordProcessingCb = cb; -} -#endif /* HAVE_PK_CALLBACKS */ -#endif /* NO_CERTS */ - -#if defined(HAVE_PK_CALLBACKS) && !defined(NO_DH) -void wolfSSL_CTX_SetDhGenerateKeyPair(WOLFSSL_CTX* ctx, - CallbackDhGenerateKeyPair cb) { - if (ctx) - ctx->DhGenerateKeyPairCb = cb; -} -void wolfSSL_CTX_SetDhAgreeCb(WOLFSSL_CTX* ctx, CallbackDhAgree cb) -{ - if (ctx) - ctx->DhAgreeCb = cb; -} -void wolfSSL_SetDhAgreeCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->DhAgreeCtx = ctx; -} -void* wolfSSL_GetDhAgreeCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->DhAgreeCtx; - - return NULL; -} -#endif /* HAVE_PK_CALLBACKS && !NO_DH */ - -#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF) - -void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb) -{ - if (ctx) - ctx->HkdfExtractCb = cb; -} - -void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx) -{ - if (ssl) - ssl->HkdfExtractCtx = ctx; -} - -void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) -{ - if (ssl) - return ssl->HkdfExtractCtx; - - return NULL; -} -#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */ - -#ifdef WOLFSSL_HAVE_WOLFSCEP - /* Used by autoconf to see if wolfSCEP is available */ - void wolfSSL_wolfSCEP(void) {} -#endif - - -#ifdef WOLFSSL_HAVE_CERT_SERVICE - /* Used by autoconf to see if cert service is available */ - void wolfSSL_cert_service(void) {} -#endif - -#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ - !defined(WOLFCRYPT_ONLY) -#ifndef NO_CERTS - -#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) -#if !defined(NO_FILESYSTEM) - WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, - WOLFSSL_EVP_PKEY **key, wc_pem_password_cb *cb, void *pass) - { - WOLFSSL_EVP_PKEY* pkey = NULL; - DerBuffer* der = NULL; - int keyFormat = 0; - - WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey"); - - if (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE, &keyFormat, - &der) >= 0) { - const unsigned char* ptr = der->buffer; - int type = -1; - - if (keyFormat) { - /* keyFormat is Key_Sum enum */ - if (keyFormat == RSAk) - type = EVP_PKEY_RSA; - else if (keyFormat == ECDSAk) - type = EVP_PKEY_EC; - else if (keyFormat == DSAk) - type = EVP_PKEY_DSA; - else if (keyFormat == DHk) - type = EVP_PKEY_DH; - } - else { - /* Default to RSA if format is not set */ - type = EVP_PKEY_RSA; - } - - /* handle case where reuse is attempted */ - if (key != NULL && *key != NULL) - pkey = *key; - - wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length); - if (pkey == NULL) { - WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY"); - } - } - - FreeDer(&der); - - if (key != NULL && pkey != NULL) - *key = pkey; - - WOLFSSL_LEAVE("wolfSSL_PEM_read_PrivateKey", 0); - - return pkey; - } -#endif -#endif - -#endif /* OPENSSL_ALL || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL*/ - -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) - - #define PEM_BEGIN "-----BEGIN " - #define PEM_BEGIN_SZ 11 - #define PEM_END "-----END " - #define PEM_END_SZ 9 - #define PEM_HDR_FIN "-----" - #define PEM_HDR_FIN_SZ 5 - #define PEM_HDR_FIN_EOL_NEWLINE "-----\n" - #define PEM_HDR_FIN_EOL_NULL_TERM "-----\0" - #define PEM_HDR_FIN_EOL_SZ 6 - -#ifndef NO_BIO - - int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header, - unsigned char **data, long *len) - { - int ret = WOLFSSL_SUCCESS; - char pem[256]; - int pemLen; - char* p; - char* nameStr = NULL; - int nameLen = 0; - char* headerStr = NULL; - int headerFound = 0; - unsigned char* der = NULL; - word32 derLen = 0; - - if (bio == NULL || name == NULL || header == NULL || data == NULL || - len == NULL) { - return WOLFSSL_FAILURE; - } - - /* Find header line. */ - pem[sizeof(pem) - 1] = '\0'; - while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) { - if (XSTRNCMP(pem, PEM_BEGIN, PEM_BEGIN_SZ) == 0) - break; - } - if (pemLen <= 0) - ret = WOLFSSL_FAILURE; - /* Have a header line. */ - if (ret == WOLFSSL_SUCCESS) { - while (pem[pemLen - 1] == '\r' || pem[pemLen - 1] == '\n') - pemLen--; - pem[pemLen] = '\0'; - if (XSTRNCMP(pem + pemLen - PEM_HDR_FIN_SZ, PEM_HDR_FIN, - PEM_HDR_FIN_SZ) != 0) { - ret = WOLFSSL_FAILURE; - } - } - - /* Get out name. */ - if (ret == WOLFSSL_SUCCESS) { - nameLen = pemLen - PEM_BEGIN_SZ - PEM_HDR_FIN_SZ; - nameStr = (char*)XMALLOC(nameLen + 1, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (nameStr == NULL) - ret = WOLFSSL_FAILURE; - } - if (ret == WOLFSSL_SUCCESS) { - int headerLen; - - XSTRNCPY(nameStr, pem + PEM_BEGIN_SZ, nameLen); - nameStr[nameLen] = '\0'; - - /* Get header of PEM - encryption header. */ - headerLen = 0; - while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) { - while (pemLen > 0 && (pem[pemLen - 1] == '\r' || - pem[pemLen - 1] == '\n')) { - pemLen--; - } - pem[pemLen++] = '\n'; - pem[pemLen] = '\0'; - - /* Header separator is a blank line. */ - if (pem[0] == '\n') { - headerFound = 1; - break; - } - - /* Didn't find a blank line - no header. */ - if (XSTRNCMP(pem, PEM_END, PEM_END_SZ) == 0) { - der = (unsigned char*)headerStr; - derLen = headerLen; - /* Empty header - empty string. */ - headerStr = (char*)XMALLOC(1, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (headerStr == NULL) - ret = WOLFSSL_FAILURE; - else - headerStr[0] = '\0'; - break; - } - - p = (char*)XREALLOC(headerStr, headerLen + pemLen + 1, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (p == NULL) { - ret = WOLFSSL_FAILURE; - break; - } - - headerStr = p; - XMEMCPY(headerStr + headerLen, pem, pemLen + 1); - headerLen += pemLen; - } - if (pemLen <= 0) - ret = WOLFSSL_FAILURE; - } - - /* Get body of PEM - if there was a header */ - if (ret == WOLFSSL_SUCCESS && headerFound) { - derLen = 0; - while ((pemLen = wolfSSL_BIO_gets(bio, pem, sizeof(pem) - 1)) > 0) { - while (pemLen > 0 && (pem[pemLen - 1] == '\r' || - pem[pemLen - 1] == '\n')) { - pemLen--; - } - pem[pemLen++] = '\n'; - pem[pemLen] = '\0'; - - if (XSTRNCMP(pem, PEM_END, PEM_END_SZ) == 0) - break; - - p = (char*)XREALLOC(der, derLen + pemLen + 1, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (p == NULL) { - ret = WOLFSSL_FAILURE; - break; - } - - der = (unsigned char*)p; - XMEMCPY(der + derLen, pem, pemLen + 1); - derLen += pemLen; - } - if (pemLen <= 0) - ret = WOLFSSL_FAILURE; - } - - /* Check trailer. */ - if (ret == WOLFSSL_SUCCESS) { - if (XSTRNCMP(pem + PEM_END_SZ, nameStr, nameLen) != 0) - ret = WOLFSSL_FAILURE; - } - if (ret == WOLFSSL_SUCCESS) { - if (XSTRNCMP(pem + PEM_END_SZ + nameLen, - PEM_HDR_FIN_EOL_NEWLINE, - PEM_HDR_FIN_EOL_SZ) != 0 && - XSTRNCMP(pem + PEM_END_SZ + nameLen, - PEM_HDR_FIN_EOL_NULL_TERM, - PEM_HDR_FIN_EOL_SZ) != 0) { - ret = WOLFSSL_FAILURE; - } - } - - /* Base64 decode body. */ - if (ret == WOLFSSL_SUCCESS) { - if (Base64_Decode(der, derLen, der, &derLen) != 0) - ret = WOLFSSL_FAILURE; - } - - if (ret == WOLFSSL_SUCCESS) { - *name = nameStr; - *header = headerStr; - *data = der; - *len = derLen; - nameStr = NULL; - headerStr = NULL; - der = NULL; - } - - if (nameStr != NULL) - XFREE(nameStr, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (headerStr != NULL) - XFREE(headerStr, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (der != NULL) - XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); - - return ret; - } - - int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name, - const char *header, const unsigned char *data, - long len) - { - int err = 0; - int outSz = 0; - int nameLen; - int headerLen; - byte* pem = NULL; - word32 pemLen; - word32 derLen = (word32)len; - - if (bio == NULL || name == NULL || header == NULL || data == NULL) - return 0; - - nameLen = (int)XSTRLEN(name); - headerLen = (int)XSTRLEN(header); - - pemLen = (derLen + 2) / 3 * 4; - pemLen += (pemLen + 63) / 64; - - pem = (byte*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); - err = pem == NULL; - if (!err) - err = Base64_Encode(data, derLen, pem, &pemLen) != 0; - - if (!err) { - err = wolfSSL_BIO_write(bio, PEM_BEGIN, PEM_BEGIN_SZ) != - (int)PEM_BEGIN_SZ; - } - if (!err) - err = wolfSSL_BIO_write(bio, name, nameLen) != nameLen; - if (!err) { - err = wolfSSL_BIO_write(bio, PEM_HDR_FIN_EOL_NEWLINE, - PEM_HDR_FIN_EOL_SZ) != (int)PEM_HDR_FIN_EOL_SZ; - } - if (!err && headerLen > 0) { - err = wolfSSL_BIO_write(bio, header, headerLen) != headerLen; - /* Blank line after a header and before body. */ - if (!err) - err = wolfSSL_BIO_write(bio, "\n", 1) != 1; - headerLen++; - } - if (!err) - err = wolfSSL_BIO_write(bio, pem, pemLen) != (int)pemLen; - if (!err) - err = wolfSSL_BIO_write(bio, PEM_END, PEM_END_SZ) != - (int)PEM_END_SZ; - if (!err) - err = wolfSSL_BIO_write(bio, name, nameLen) != nameLen; - if (!err) { - err = wolfSSL_BIO_write(bio, PEM_HDR_FIN_EOL_NEWLINE, - PEM_HDR_FIN_EOL_SZ) != (int)PEM_HDR_FIN_EOL_SZ; - } - - if (!err) { - outSz = PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ + headerLen + - pemLen + PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ; - } - - if (pem != NULL) - XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); - - return outSz; - } - -#if !defined(NO_FILESYSTEM) - int wolfSSL_PEM_read(XFILE fp, char **name, char **header, - unsigned char **data, long *len) - { - int ret; - WOLFSSL_BIO* bio; - - if (name == NULL || header == NULL || data == NULL || len == NULL) - return WOLFSSL_FAILURE; - - bio = wolfSSL_BIO_new_fp(fp, BIO_NOCLOSE); - if (bio == NULL) - return 0; - - ret = wolfSSL_PEM_read_bio(bio, name, header, data, len); - - if (bio != NULL) - wolfSSL_BIO_free(bio); - - return ret; - } - - int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header, - const unsigned char *data, long len) - { - int ret; - WOLFSSL_BIO* bio; - - if (name == NULL || header == NULL || data == NULL) - return 0; - - bio = wolfSSL_BIO_new_fp(fp, BIO_NOCLOSE); - if (bio == NULL) - return 0; - - ret = wolfSSL_PEM_write_bio(bio, name, header, data, len); - - if (bio != NULL) - wolfSSL_BIO_free(bio); - - return ret; - } -#endif -#endif /* !NO_BIO */ - - int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header, - EncryptedInfo* cipher) - { - if (header == NULL || cipher == NULL) - return WOLFSSL_FAILURE; - - XMEMSET(cipher, 0, sizeof(*cipher)); - - if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0) - return WOLFSSL_FAILURE; - - return WOLFSSL_SUCCESS; - } - - int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, - long* len, wc_pem_password_cb* callback, - void* ctx) - { - int ret = WOLFSSL_SUCCESS; - char password[NAME_SZ]; - int passwordSz; - - if (cipher == NULL || data == NULL || len == NULL || callback == NULL) - return WOLFSSL_FAILURE; - - passwordSz = callback(password, sizeof(password), PEM_PASS_READ, ctx); - if (passwordSz < 0) - ret = WOLFSSL_FAILURE; - - if (ret == WOLFSSL_SUCCESS) { - if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password, - passwordSz, WC_MD5) != 0) { - ret = WOLFSSL_FAILURE; - } - } - - if (passwordSz > 0) - XMEMSET(password, 0, passwordSz); - - return ret; - } - -#ifndef NO_BIO - /* - * bp : bio to read X509 from - * x : x509 to write to - * cb : password call back for reading PEM - * u : password - * _AUX is for working with a trusted X509 certificate - */ - WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_AUX(WOLFSSL_BIO *bp, - WOLFSSL_X509 **x, wc_pem_password_cb *cb, - void *u) - { - WOLFSSL_ENTER("wolfSSL_PEM_read_bio_X509"); - - /* AUX info is; trusted/rejected uses, friendly name, private key id, - * and potentially a stack of "other" info. wolfSSL does not store - * friendly name or private key id yet in WOLFSSL_X509 for human - * readability and does not support extra trusted/rejected uses for - * root CA. */ - return wolfSSL_PEM_read_bio_X509(bp, x, cb, u); - } -#endif /* !NO_BIO */ - - -#endif /* OPENSSL_EXTRA || OPENSSL_ALL */ -#endif /* !NO_CERTS */ - - /* NID variables are dependent on compatibility header files currently - * - * returns a pointer to a new WOLFSSL_ASN1_OBJECT struct on success and NULL - * on fail - */ - - WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj(int id) - { - return wolfSSL_OBJ_nid2obj_ex(id, NULL); - } - - - WOLFSSL_LOCAL WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_nid2obj_ex(int id, - WOLFSSL_ASN1_OBJECT* arg_obj) - { - word32 oidSz = 0; - int nid = 0; - const byte* oid; - word32 type = 0; - WOLFSSL_ASN1_OBJECT* obj = arg_obj; - byte objBuf[MAX_OID_SZ + MAX_LENGTH_SZ + 1]; /* +1 for object tag */ - word32 objSz = 0; - const char* sName = NULL; - int i; - -#ifdef WOLFSSL_DEBUG_OPENSSL - WOLFSSL_ENTER("wolfSSL_OBJ_nid2obj"); -#endif - - for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) { - if (wolfssl_object_info[i].nid == id) { - nid = id; - id = wolfssl_object_info[i].id; - sName = wolfssl_object_info[i].sName; - type = wolfssl_object_info[i].type; - break; - } - } - if (i == (int)WOLFSSL_OBJECT_INFO_SZ) { - WOLFSSL_MSG("NID not in table"); - #ifdef WOLFSSL_QT - sName = NULL; - type = id; - #else - return NULL; - #endif - } - - #ifdef HAVE_ECC - if (type == 0 && wc_ecc_get_oid(id, &oid, &oidSz) > 0) { - type = oidCurveType; - } - #endif /* HAVE_ECC */ - - if (sName != NULL) { - if (XSTRLEN(sName) > WOLFSSL_MAX_SNAME - 1) { - WOLFSSL_MSG("Attempted short name is too large"); - return NULL; - } - } - - oid = OidFromId(id, type, &oidSz); - - /* set object ID to buffer */ - if (obj == NULL){ - obj = wolfSSL_ASN1_OBJECT_new(); - if (obj == NULL) { - WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); - return NULL; - } - } - obj->nid = nid; - obj->type = id; - obj->grp = type; - - obj->sName[0] = '\0'; - if (sName != NULL) { - XMEMCPY(obj->sName, (char*)sName, XSTRLEN((char*)sName)); - } - - objBuf[0] = ASN_OBJECT_ID; objSz++; - objSz += SetLength(oidSz, objBuf + 1); - if (oidSz) { - XMEMCPY(objBuf + objSz, oid, oidSz); - objSz += oidSz; - } - - if (obj->objSz == 0 || objSz != obj->objSz) { - obj->objSz = objSz; - if(((obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || - (obj->obj == NULL)) { - if (obj->obj != NULL) - XFREE((byte*)obj->obj, NULL, DYNAMIC_TYPE_ASN1); - obj->obj = (byte*)XMALLOC(obj->objSz, NULL, DYNAMIC_TYPE_ASN1); - if (obj->obj == NULL) { - wolfSSL_ASN1_OBJECT_free(obj); - return NULL; - } - obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA ; - } - else { - obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA ; - } - } - XMEMCPY((byte*)obj->obj, objBuf, obj->objSz); - - (void)type; - - return obj; - } - - static const char* oid_translate_num_to_str(const char* oid) - { - const struct oid_dict { - const char* num; - const char* desc; - } oid_dict[] = { - { "2.5.29.37.0", "Any Extended Key Usage" }, - { "1.3.6.1.5.5.7.3.1", "TLS Web Server Authentication" }, - { "1.3.6.1.5.5.7.3.2", "TLS Web Client Authentication" }, - { "1.3.6.1.5.5.7.3.3", "Code Signing" }, - { "1.3.6.1.5.5.7.3.4", "E-mail Protection" }, - { "1.3.6.1.5.5.7.3.8", "Time Stamping" }, - { "1.3.6.1.5.5.7.3.9", "OCSP Signing" }, - { NULL, NULL } - }; - const struct oid_dict* idx; - - for (idx = oid_dict; idx->num != NULL; idx++) { - if (!XSTRCMP(oid, idx->num)) { - return idx->desc; - } - } - return NULL; - } - - static int wolfssl_obj2txt_numeric(char *buf, int bufLen, - const WOLFSSL_ASN1_OBJECT *a) - { - int bufSz; - int length; - word32 idx = 0; - byte tag; - - if (GetASNTag(a->obj, &idx, &tag, a->objSz) != 0) { - return WOLFSSL_FAILURE; - } - - if (tag != ASN_OBJECT_ID) { - WOLFSSL_MSG("Bad ASN1 Object"); - return WOLFSSL_FAILURE; - } - - if (GetLength((const byte*)a->obj, &idx, &length, - a->objSz) < 0 || length < 0) { - return ASN_PARSE_E; - } - - if (bufLen < MAX_OID_STRING_SZ) { - bufSz = bufLen - 1; - } - else { - bufSz = MAX_OID_STRING_SZ; - } - - if ((bufSz = DecodePolicyOID(buf, (word32)bufSz, a->obj + idx, - (word32)length)) <= 0) { - WOLFSSL_MSG("Error decoding OID"); - return WOLFSSL_FAILURE; - } - - buf[bufSz] = '\0'; - - return bufSz; - } - - /* If no_name is one then use numerical form, otherwise short name. - * - * Returns the buffer size on success, WOLFSSL_FAILURE on error - */ - int wolfSSL_OBJ_obj2txt(char *buf, int bufLen, const WOLFSSL_ASN1_OBJECT *a, - int no_name) - { - int bufSz; - const char* desc; - const char* name; - - WOLFSSL_ENTER("wolfSSL_OBJ_obj2txt"); - - if (buf == NULL || bufLen <= 1 || a == NULL) { - WOLFSSL_MSG("Bad input argument"); - return WOLFSSL_FAILURE; - } - - if (no_name == 1) { - return wolfssl_obj2txt_numeric(buf, bufLen, a); - } - - /* return long name unless using x509small, then return short name */ -#if defined(OPENSSL_EXTRA_X509_SMALL) && !defined(OPENSSL_EXTRA) - name = a->sName; -#else - name = wolfSSL_OBJ_nid2ln(wolfSSL_OBJ_obj2nid(a)); -#endif - - if (name == NULL) { - WOLFSSL_MSG("Name not found"); - bufSz = 0; - } - else if (XSTRLEN(name) + 1 < (word32)bufLen - 1) { - bufSz = (int)XSTRLEN(name); - } - else { - bufSz = bufLen - 1; - } - if (bufSz) { - XMEMCPY(buf, name, bufSz); - } - else if (a->type == GEN_DNS || a->type == GEN_EMAIL || - a->type == GEN_URI) { - bufSz = (int)XSTRLEN((const char*)a->obj); - XMEMCPY(buf, a->obj, min(bufSz, bufLen)); - } - else if ((bufSz = wolfssl_obj2txt_numeric(buf, bufLen, a)) > 0) { - if ((desc = oid_translate_num_to_str(buf))) { - bufSz = (int)XSTRLEN(desc); - bufSz = min(bufSz, bufLen - 1); - XMEMCPY(buf, desc, bufSz); - } - } - else { - bufSz = 0; - } - - buf[bufSz] = '\0'; - - return bufSz; - } -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ - -#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS_SMALL) - /* Returns the long name that corresponds with an ASN1_OBJECT nid value. - * n : NID value of ASN1_OBJECT to search */ - const char* wolfSSL_OBJ_nid2ln(int n) - { - const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; - size_t i; - WOLFSSL_ENTER("wolfSSL_OBJ_nid2ln"); - for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { - if (obj_info->nid == n) { - return obj_info->lName; - } - } - WOLFSSL_MSG("NID not found in table"); - return NULL; - } -#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL, - WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY, WOLFSSL_WPAS_SMALL */ - -#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ - defined(WOLFSSL_HAPROXY) - char wolfSSL_CTX_use_certificate(WOLFSSL_CTX *ctx, WOLFSSL_X509 *x) - { - int ret; - - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate"); - if (!ctx || !x || !x->derCert) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } - - FreeDer(&ctx->certificate); /* Make sure previous is free'd */ - ret = AllocDer(&ctx->certificate, x->derCert->length, CERT_TYPE, - ctx->heap); - if (ret != 0) - return WOLFSSL_FAILURE; - - XMEMCPY(ctx->certificate->buffer, x->derCert->buffer, - x->derCert->length); -#ifdef KEEP_OUR_CERT - if (ctx->ourCert != NULL && ctx->ownOurCert) { - wolfSSL_X509_free(ctx->ourCert); - } - #ifndef WOLFSSL_X509_STORE_CERTS - ctx->ourCert = x; - if (wolfSSL_X509_up_ref(x) != 1) { - return WOLFSSL_FAILURE; - } - #else - ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, x->derCert->buffer, - x->derCert->length, ctx->heap); - if(ctx->ourCert == NULL){ - return WOLFSSL_FAILURE; - } - #endif - - /* We own the cert because either we up its reference counter - * or we create our own copy of the cert object. */ - ctx->ownOurCert = 1; -#endif - - /* Update the available options with public keys. */ - switch (x->pubKeyOID) { - #ifndef NO_RSA - #ifdef WC_RSA_PSS - case RSAPSSk: - #endif - case RSAk: - ctx->haveRSA = 1; - break; - #endif - #ifdef HAVE_ED25519 - case ED25519k: - #endif - #ifdef HAVE_ED448 - case ED448k: - #endif - case ECDSAk: - ctx->haveECC = 1; - #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) - ctx->pkCurveOID = x->pkCurveOID; - #endif - break; - } - - return WOLFSSL_SUCCESS; - } - - static int PushCertToDerBuffer(DerBuffer** inOutDer, int weOwn, - byte* cert, word32 certSz, void* heap) - { - int ret; - DerBuffer* inChain = NULL; - DerBuffer* der = NULL; - word32 len = 0; - if (inOutDer == NULL) - return BAD_FUNC_ARG; - inChain = *inOutDer; - if (inChain != NULL) - len = inChain->length; - ret = AllocDer(&der, len + CERT_HEADER_SZ + certSz, CERT_TYPE, - heap); - if (ret != 0) { - WOLFSSL_MSG("AllocDer error"); - return ret; - } - if (inChain != NULL) - XMEMCPY(der->buffer, inChain->buffer, len); - c32to24(certSz, der->buffer + len); - XMEMCPY(der->buffer + len + CERT_HEADER_SZ, cert, certSz); - if (weOwn) - FreeDer(inOutDer); - *inOutDer = der; - return WOLFSSL_SUCCESS; - } - - /** - * wolfSSL_CTX_add1_chain_cert makes a copy of the cert so we free it - * on success - */ - int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) - { - WOLFSSL_ENTER("wolfSSL_CTX_add0_chain_cert"); - if (wolfSSL_CTX_add1_chain_cert(ctx, x509) != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; - } - wolfSSL_X509_free(x509); - return WOLFSSL_SUCCESS; - } - - int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) - { - int ret; - WOLFSSL_ENTER("wolfSSL_CTX_add1_chain_cert"); - if (ctx == NULL || x509 == NULL || x509->derCert == NULL) { - return WOLFSSL_FAILURE; - } - - if (ctx->certificate == NULL) - ret = (int)wolfSSL_CTX_use_certificate(ctx, x509); - else { - if (wolfSSL_X509_up_ref(x509) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_up_ref error"); - return WOLFSSL_FAILURE; - } - ret = wolfSSL_CTX_load_verify_buffer(ctx, x509->derCert->buffer, - x509->derCert->length, WOLFSSL_FILETYPE_ASN1); - if (ret == WOLFSSL_SUCCESS) { - /* push to ctx->certChain */ - ret = PushCertToDerBuffer(&ctx->certChain, 1, - x509->derCert->buffer, x509->derCert->length, ctx->heap); - } - /* Store cert to free it later */ - if (ret == WOLFSSL_SUCCESS && ctx->x509Chain == NULL) { - ctx->x509Chain = wolfSSL_sk_X509_new_null(); - if (ctx->x509Chain == NULL) { - WOLFSSL_MSG("wolfSSL_sk_X509_new_null error"); - ret = WOLFSSL_FAILURE; - } - } - if (ret == WOLFSSL_SUCCESS && - wolfSSL_sk_X509_push(ctx->x509Chain, x509) - != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_sk_X509_push error"); - ret = WOLFSSL_FAILURE; - } - if (ret != WOLFSSL_SUCCESS) - wolfSSL_X509_free(x509); /* Decrease ref counter */ - } - - return (ret == WOLFSSL_SUCCESS) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - } - -#ifdef KEEP_OUR_CERT - int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) - { - int ret; - - WOLFSSL_ENTER("wolfSSL_add0_chain_cert"); - - if (ssl == NULL || ssl->ctx == NULL || x509 == NULL || - x509->derCert == NULL) - return WOLFSSL_FAILURE; - - if (ssl->buffers.certificate == NULL) { - ret = wolfSSL_use_certificate(ssl, x509); - /* Store cert to free it later */ - if (ret == WOLFSSL_SUCCESS) { - if (ssl->buffers.weOwnCert) - wolfSSL_X509_free(ssl->ourCert); - ssl->ourCert = x509; - ssl->buffers.weOwnCert = 1; - } - } - else { - ret = PushCertToDerBuffer(&ssl->buffers.certChain, - ssl->buffers.weOwnCertChain, x509->derCert->buffer, - x509->derCert->length, ssl->heap); - if (ret == WOLFSSL_SUCCESS) { - ssl->buffers.weOwnCertChain = 1; - /* Store cert to free it later */ - if (ssl->ourCertChain == NULL) { - ssl->ourCertChain = wolfSSL_sk_X509_new_null(); - if (ssl->ourCertChain == NULL) { - WOLFSSL_MSG("wolfSSL_sk_X509_new_null error"); - return WOLFSSL_FAILURE; - } - } - if (wolfSSL_sk_X509_push(ssl->ourCertChain, x509) - != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_sk_X509_push error"); - return WOLFSSL_FAILURE; - } - } - } - return ret == WOLFSSL_SUCCESS ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - } - - int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) - { - int ret; - - WOLFSSL_ENTER("wolfSSL_add1_chain_cert"); - if (ssl == NULL || ssl->ctx == NULL || x509 == NULL || - x509->derCert == NULL) - return WOLFSSL_FAILURE; - - if (wolfSSL_X509_up_ref(x509) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_up_ref error"); - return WOLFSSL_FAILURE; - } - ret = wolfSSL_add0_chain_cert(ssl, x509); - /* Decrease ref counter on error */ - if (ret != WOLFSSL_SUCCESS) - wolfSSL_X509_free(x509); - return ret; - } -#endif - - /* Return the corresponding short name for the nid . - * or NULL if short name can't be found. - */ - const char * wolfSSL_OBJ_nid2sn(int n) { - const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; - size_t i; - WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn"); - - if (n == NID_md5) { - /* NID_surname == NID_md5 and NID_surname comes before NID_md5 in - * wolfssl_object_info. As a result, the loop below will incorrectly - * return "SN" instead of "MD5." NID_surname isn't the true OpenSSL - * NID, but other functions rely on this table and modifying it to - * conform with OpenSSL's NIDs isn't trivial. */ - return "MD5"; - } - for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { - if (obj_info->nid == n) { - return obj_info->sName; - } - } - WOLFSSL_MSG_EX("SN not found (nid:%d)",n); - return NULL; - } - -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - int wolfSSL_OBJ_sn2nid(const char *sn) { - WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid"); - if (sn == NULL) - return NID_undef; - return wc_OBJ_sn2nid(sn); - } -#endif - - size_t wolfSSL_OBJ_length(const WOLFSSL_ASN1_OBJECT* o) - { - size_t ret = 0; - int err = 0; - word32 idx = 0; - int len = 0; - - WOLFSSL_ENTER("wolfSSL_OBJ_length"); - - if (o == NULL || o->obj == NULL) { - WOLFSSL_MSG("Bad argument."); - err = 1; - } - - if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) { - WOLFSSL_MSG("Error parsing ASN.1 header."); - err = 1; - } - if (err == 0) { - ret = len; - } - - WOLFSSL_LEAVE("wolfSSL_OBJ_length", (int)ret); - - return ret; - } - - const unsigned char* wolfSSL_OBJ_get0_data(const WOLFSSL_ASN1_OBJECT* o) - { - const unsigned char* ret = NULL; - int err = 0; - word32 idx = 0; - int len = 0; - - WOLFSSL_ENTER("wolfSSL_OBJ_get0_data"); - - if (o == NULL || o->obj == NULL) { - WOLFSSL_MSG("Bad argument."); - err = 1; - } - - if (err == 0 && GetASNObjectId(o->obj, &idx, &len, o->objSz)) { - WOLFSSL_MSG("Error parsing ASN.1 header."); - err = 1; - } - if (err == 0) { - ret = o->obj + idx; - } - - return ret; - } - - - /* Gets the NID value that corresponds with the ASN1 object. - * - * o ASN1 object to get NID of - * - * Return NID on success and a negative value on failure - */ - int wolfSSL_OBJ_obj2nid(const WOLFSSL_ASN1_OBJECT *o) - { - word32 oid = 0; - word32 idx = 0; - int ret; - -#ifdef WOLFSSL_DEBUG_OPENSSL - WOLFSSL_ENTER("wolfSSL_OBJ_obj2nid"); -#endif - - if (o == NULL) { - return -1; - } - - #ifdef WOLFSSL_QT - if (o->grp == oidCertExtType) { - /* If nid is an unknown extension, return NID_undef */ - if (wolfSSL_OBJ_nid2sn(o->nid) == NULL) - return NID_undef; - } - #endif - - if (o->nid > 0) - return o->nid; - if ((ret = GetObjectId(o->obj, &idx, &oid, o->grp, o->objSz)) < 0) { - if (ret == ASN_OBJECT_ID_E) { - /* Put ASN object tag in front and try again */ - int len = SetObjectId(o->objSz, NULL) + o->objSz; - byte* buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (!buf) { - WOLFSSL_MSG("malloc error"); - return -1; - } - idx = SetObjectId(o->objSz, buf); - XMEMCPY(buf + idx, o->obj, o->objSz); - idx = 0; - ret = GetObjectId(buf, &idx, &oid, o->grp, len); - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (ret < 0) { - WOLFSSL_MSG("Issue getting OID of object"); - return -1; - } - } - else { - WOLFSSL_MSG("Issue getting OID of object"); - return -1; - } - } - - return oid2nid(oid, o->grp); - } - - /* Return the corresponding NID for the long name - * or NID_undef if NID can't be found. - */ - int wolfSSL_OBJ_ln2nid(const char *ln) - { - const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; - size_t lnlen; - WOLFSSL_ENTER("wolfSSL_OBJ_ln2nid"); - if (ln && (lnlen = XSTRLEN(ln)) > 0) { - /* Accept input like "/commonName=" */ - if (ln[0] == '/') { - ln++; - lnlen--; - } - if (lnlen) { - size_t i; - - if (ln[lnlen-1] == '=') { - lnlen--; - } - for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++, obj_info++) { - if (lnlen == XSTRLEN(obj_info->lName) && - XSTRNCMP(ln, obj_info->lName, lnlen) == 0) { - return obj_info->nid; - } - } - } - } - return NID_undef; - } - - /* compares two objects, return 0 if equal */ - int wolfSSL_OBJ_cmp(const WOLFSSL_ASN1_OBJECT* a, - const WOLFSSL_ASN1_OBJECT* b) - { - WOLFSSL_ENTER("wolfSSL_OBJ_cmp"); - - if (a && b && a->obj && b->obj) { - if (a->objSz == b->objSz) { - return XMEMCMP(a->obj, b->obj, a->objSz); - } - else if (a->type == EXT_KEY_USAGE_OID || - b->type == EXT_KEY_USAGE_OID) { - /* Special case for EXT_KEY_USAGE_OID so that - * cmp will be treated as a substring search */ - /* Used in libest to check for id-kp-cmcRA in - * EXT_KEY_USAGE extension */ - unsigned int idx; - const byte* s; /* shorter */ - unsigned int sLen; - const byte* l; /* longer */ - unsigned int lLen; - if (a->objSz > b->objSz) { - s = b->obj; sLen = b->objSz; - l = a->obj; lLen = a->objSz; - } - else { - s = a->obj; sLen = a->objSz; - l = b->obj; lLen = b->objSz; - } - for (idx = 0; idx <= lLen - sLen; idx++) { - if (XMEMCMP(l + idx, s, sLen) == 0) { - /* Found substring */ - return 0; - } - } - } - } - - return WOLFSSL_FATAL_ERROR; - } -#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL, - WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */ -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ - defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_POCO_LIB) || defined(WOLFSSL_HAPROXY) - /* Gets the NID value that is related to the OID string passed in. Example - * string would be "2.5.29.14" for subject key ID. - * - * returns NID value on success and NID_undef on error - */ - int wolfSSL_OBJ_txt2nid(const char* s) - { - unsigned int i; - #ifdef WOLFSSL_CERT_EXT - int ret; - unsigned int sum = 0; - unsigned int outSz = MAX_OID_SZ; - unsigned char out[MAX_OID_SZ]; - #endif - - WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid"); - - if (s == NULL) { - return NID_undef; - } - - #ifdef WOLFSSL_CERT_EXT - ret = EncodePolicyOID(out, &outSz, s, NULL); - if (ret == 0) { - /* sum OID */ - for (i = 0; i < outSz; i++) { - sum += out[i]; - } - } - #endif /* WOLFSSL_CERT_EXT */ - - /* get the group that the OID's sum is in - * @TODO possible conflict with multiples */ - for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) { - int len; - #ifdef WOLFSSL_CERT_EXT - if (ret == 0) { - if (wolfssl_object_info[i].id == (int)sum) { - return wolfssl_object_info[i].nid; - } - } - #endif - - /* try as a short name */ - len = (int)XSTRLEN(s); - if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len && - XSTRNCMP(wolfssl_object_info[i].sName, s, len) == 0) { - return wolfssl_object_info[i].nid; - } - - /* try as a long name */ - if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len && - XSTRNCMP(wolfssl_object_info[i].lName, s, len) == 0) { - return wolfssl_object_info[i].nid; - } - } - - return NID_undef; - } -#endif -#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ - defined(WOLFSSL_HAPROXY) - - /* Creates new ASN1_OBJECT from short name, long name, or text - * representation of oid. If no_name is 0, then short name, long name, and - * numerical value of oid are interpreted. If no_name is 1, then only the - * numerical value of the oid is interpreted. - * - * Returns pointer to ASN1_OBJECT on success, or NULL on error. - */ -#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN) - WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name) - { - int i, ret; - int nid = NID_undef; - unsigned int outSz = MAX_OID_SZ; - unsigned char out[MAX_OID_SZ]; - WOLFSSL_ASN1_OBJECT* obj; - - WOLFSSL_ENTER("wolfSSL_OBJ_txt2obj"); - - if (s == NULL) - return NULL; - - /* If s is numerical value, try to sum oid */ - ret = EncodePolicyOID(out, &outSz, s, NULL); - if (ret == 0 && outSz > 0) { - /* If numerical encode succeeded then just - * create object from that because sums are - * not unique and can cause confusion. */ - obj = wolfSSL_ASN1_OBJECT_new(); - if (obj == NULL) { - WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); - return NULL; - } - obj->dynamic |= WOLFSSL_ASN1_DYNAMIC; - obj->obj = (byte*)XMALLOC(1 + MAX_LENGTH_SZ + outSz, NULL, - DYNAMIC_TYPE_ASN1); - if (obj->obj == NULL) { - wolfSSL_ASN1_OBJECT_free(obj); - return NULL; - } - obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA ; - i = SetObjectId(outSz, (byte*)obj->obj); - XMEMCPY((byte*)obj->obj + i, out, outSz); - obj->objSz = i + outSz; - return obj; - } - - /* TODO: update short names in wolfssl_object_info and check OID sums - are correct */ - for (i = 0; i < (int)WOLFSSL_OBJECT_INFO_SZ; i++) { - /* Short name, long name, and numerical value are interpreted */ - if (no_name == 0 && - ((XSTRCMP(s, wolfssl_object_info[i].sName) == 0) || - (XSTRCMP(s, wolfssl_object_info[i].lName) == 0))) - { - nid = wolfssl_object_info[i].nid; - } - } - - if (nid != NID_undef) - return wolfSSL_OBJ_nid2obj(nid); - - return NULL; - } -#endif - - /* compatibility function. Its intended use is to remove OID's from an - * internal table that have been added with OBJ_create. wolfSSL manages its - * own internal OID values and does not currently support OBJ_create. */ - void wolfSSL_OBJ_cleanup(void) - { - WOLFSSL_ENTER("wolfSSL_OBJ_cleanup"); - } - - #ifndef NO_WOLFSSL_STUB - int wolfSSL_OBJ_create(const char *oid, const char *sn, const char *ln) - { - (void)oid; - (void)sn; - (void)ln; - WOLFSSL_STUB("wolfSSL_OBJ_create"); - return WOLFSSL_FAILURE; - } - #endif - - void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth) - { - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - WOLFSSL_ENTER("wolfSSL_set_verify_depth"); - ssl->options.verifyDepth = (byte)depth; - #endif - } - -#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || - HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */ - -#ifdef OPENSSL_EXTRA - -/* wolfSSL uses negative values for error states. This function returns an - * unsigned type so the value returned is the absolute value of the error. - */ -unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line) -{ - WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error"); - - (void)line; - (void)file; -#ifdef WOLFSSL_HAVE_ERROR_QUEUE - { - int ret; - - if ((ret = wc_PeekErrorNode(-1, file, NULL, line)) < 0) { - WOLFSSL_MSG("Issue peeking at error node in queue"); - return 0; - } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \ - || defined(WOLFSSL_HAPROXY) - if (ret == -ASN_NO_PEM_HEADER) - return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; - #endif - #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - if (ret == ASN1_R_HEADER_TOO_LONG) { - return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; - } - #endif - return (unsigned long)ret; - } -#else - return (unsigned long)(0 - NOT_COMPILED_IN); -#endif -} - - -#ifndef NO_CERTS -int wolfSSL_CTX_use_PrivateKey(WOLFSSL_CTX *ctx, WOLFSSL_EVP_PKEY *pkey) -{ - WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey"); - - if (ctx == NULL || pkey == NULL) { - return WOLFSSL_FAILURE; - } - - switch (pkey->type) { -#if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: - WOLFSSL_MSG("populating RSA key"); - if (PopulateRSAEvpPkeyDer(pkey) != WOLFSSL_SUCCESS) - return WOLFSSL_FAILURE; - break; -#endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */ -#if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \ - defined(WOLFSSL_CERT_GEN)) && !defined(NO_DSA) - case EVP_PKEY_DSA: - break; -#endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) && !NO_DSA */ -#ifdef HAVE_ECC - case EVP_PKEY_EC: - WOLFSSL_MSG("populating ECC key"); - if (ECC_populate_EVP_PKEY(pkey, pkey->ecc) - != WOLFSSL_SUCCESS) - return WOLFSSL_FAILURE; - break; -#endif - default: - return WOLFSSL_FAILURE; - } - - if (pkey->pkey.ptr != NULL) { - /* ptr for WOLFSSL_EVP_PKEY struct is expected to be DER format */ - return wolfSSL_CTX_use_PrivateKey_buffer(ctx, - (const unsigned char*)pkey->pkey.ptr, - pkey->pkey_sz, SSL_FILETYPE_ASN1); - } - - WOLFSSL_MSG("wolfSSL private key not set"); - return BAD_FUNC_ARG; -} -#endif /* !NO_CERTS */ - -#endif /* OPENSSL_EXTRA */ - -#if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ - defined(WOLFSSL_WPAS_SMALL) -CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL; - -static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr, - WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func) -{ - CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC( - sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL); - if (new_ctx == NULL) - return -1; - new_ctx->ctx_l = ctx_l; - new_ctx->ctx_ptr = ctx_ptr; - new_ctx->new_func = new_func; - new_ctx->free_func = free_func; - new_ctx->dup_func = dup_func; - new_ctx->next = NULL; - /* Push to end of list */ - while (*dst != NULL) - dst = &(*dst)->next; - *dst = new_ctx; - return 0; -} - -void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx) -{ - while (cb_ctx != NULL) { - CRYPTO_EX_cb_ctx* next = cb_ctx->next; - XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL); - cb_ctx = next; - } -} - -void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx, - WOLFSSL_CRYPTO_EX_DATA* ex_data) -{ - int idx = 0; - for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { - if (cb_ctx->new_func != NULL) - cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l, - cb_ctx->ctx_ptr); - } -} - -int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in, - WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx) -{ - int idx = 0; - for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { - if (cb_ctx->dup_func != NULL) { - void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx); - if (!cb_ctx->dup_func(out, in, - &ptr, idx, - cb_ctx->ctx_l, cb_ctx->ctx_ptr)) { - return WOLFSSL_FAILURE; - } - wolfSSL_CRYPTO_set_ex_data(out, idx, ptr); - } - } - return WOLFSSL_SUCCESS; -} - -void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx, - WOLFSSL_CRYPTO_EX_DATA* ex_data) -{ - int idx = 0; - for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) { - if (cb_ctx->free_func != NULL) - cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l, - cb_ctx->ctx_ptr); - } -} - -/** - * get_ex_new_index is a helper function for the following - * xx_get_ex_new_index functions: - * - wolfSSL_CRYPTO_get_ex_new_index - * - wolfSSL_CTX_get_ex_new_index - * - wolfSSL_get_ex_new_index - * Issues a unique index number for the specified class-index. - * Returns an index number greater or equal to zero on success, - * -1 on failure. - */ -int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, - WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func) -{ - /* index counter for each class index*/ - static int ctx_idx = 0; - static int ssl_idx = 0; - static int ssl_session_idx = 0; - static int x509_idx = 0; - - int idx = -1; - - switch(class_index) { - case WOLF_CRYPTO_EX_INDEX_SSL: - WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, - dup_func, free_func); - idx = ssl_idx++; - break; - case WOLF_CRYPTO_EX_INDEX_SSL_CTX: - WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, - dup_func, free_func); - idx = ctx_idx++; - break; - case WOLF_CRYPTO_EX_INDEX_X509: - WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func, - dup_func, free_func); - idx = x509_idx++; - break; - case WOLF_CRYPTO_EX_INDEX_SSL_SESSION: - if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr, - new_func, dup_func, free_func) != 0) - return -1; - idx = ssl_session_idx++; - break; - - /* following class indexes are not supoprted */ - case WOLF_CRYPTO_EX_INDEX_X509_STORE: - case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX: - case WOLF_CRYPTO_EX_INDEX_DH: - case WOLF_CRYPTO_EX_INDEX_DSA: - case WOLF_CRYPTO_EX_INDEX_EC_KEY: - case WOLF_CRYPTO_EX_INDEX_RSA: - case WOLF_CRYPTO_EX_INDEX_ENGINE: - case WOLF_CRYPTO_EX_INDEX_UI: - case WOLF_CRYPTO_EX_INDEX_BIO: - case WOLF_CRYPTO_EX_INDEX_APP: - case WOLF_CRYPTO_EX_INDEX_UI_METHOD: - case WOLF_CRYPTO_EX_INDEX_DRBG: - default: - break; - } - if (idx >= MAX_EX_DATA) - return -1; - return idx; -} -#endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */ - -#if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) -void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); -#ifdef HAVE_EX_DATA - if(ctx != NULL) { - return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); - } -#else - (void)ctx; - (void)idx; -#endif - return NULL; -} - -int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, - WOLFSSL_CRYPTO_EX_new* new_func, - WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func) -{ - - WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index"); - - return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx, arg, - new_func, dup_func, free_func); -} - -/* Return the index that can be used for the WOLFSSL structure to store - * application data. - * - */ -int wolfSSL_get_ex_new_index(long argValue, void* arg, - WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2, - WOLFSSL_CRYPTO_EX_free* cb3) -{ - WOLFSSL_ENTER("wolfSSL_get_ex_new_index"); - - return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue, arg, - cb1, cb2, cb3); -} - - -int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data"); - #ifdef HAVE_EX_DATA - if (ctx != NULL) - { - return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data); - } - #else - (void)ctx; - (void)idx; - (void)data; - #endif - return WOLFSSL_FAILURE; -} - -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -int wolfSSL_CTX_set_ex_data_with_cleanup( - WOLFSSL_CTX* ctx, - int idx, - void* data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup"); - if (ctx != NULL) - { - return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data, - cleanup_routine); - } - return WOLFSSL_FAILURE; -} -#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - -#endif /* defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) */ - -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - -/* Returns char* to app data stored in ex[0]. - * - * ssl WOLFSSL structure to get app data from - */ -void* wolfSSL_get_app_data(const WOLFSSL *ssl) -{ - /* checkout exdata stuff... */ - WOLFSSL_ENTER("wolfSSL_get_app_data"); - - return wolfSSL_get_ex_data(ssl, 0); -} - - -/* Set ex array 0 to have app data - * - * ssl WOLFSSL struct to set app data in - * arg data to be stored - * - * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) { - WOLFSSL_ENTER("wolfSSL_set_app_data"); - - return wolfSSL_set_ex_data(ssl, 0, arg); -} - -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ - -#if defined(HAVE_EX_DATA) || defined(OPENSSL_EXTRA) || \ - defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_WPAS_SMALL) - -int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data) -{ - WOLFSSL_ENTER("wolfSSL_set_ex_data"); -#ifdef HAVE_EX_DATA - if (ssl != NULL) - { - return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data); - } -#else - WOLFSSL_MSG("HAVE_EX_DATA macro is not defined"); - (void)ssl; - (void)idx; - (void)data; -#endif - return WOLFSSL_FAILURE; -} - -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -int wolfSSL_set_ex_data_with_cleanup( - WOLFSSL* ssl, - int idx, - void* data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine) -{ - WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup"); - if (ssl != NULL) - { - return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data, - cleanup_routine); - } - return WOLFSSL_FAILURE; -} -#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - -void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx) -{ - WOLFSSL_ENTER("wolfSSL_get_ex_data"); -#ifdef HAVE_EX_DATA - if (ssl != NULL) { - return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx); - } -#else - WOLFSSL_MSG("HAVE_EX_DATA macro is not defined"); - (void)ssl; - (void)idx; -#endif - return 0; -} - -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */ - -#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \ - || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) - -#if defined(OPENSSL_EXTRA) && !defined(NO_DH) -/* Initialize ctx->dh with dh's params. Return WOLFSSL_SUCCESS on ok */ -long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh) -{ - int pSz, gSz; - byte *p, *g; - int ret=0; - - WOLFSSL_ENTER("wolfSSL_CTX_set_tmp_dh"); - - if(!ctx || !dh) - return BAD_FUNC_ARG; - - /* Get needed size for p and g */ - pSz = wolfSSL_BN_bn2bin(dh->p, NULL); - gSz = wolfSSL_BN_bn2bin(dh->g, NULL); - - if(pSz <= 0 || gSz <= 0) - return WOLFSSL_FATAL_ERROR; - - p = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if(!p) - return MEMORY_E; - - g = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if(!g) { - XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - return MEMORY_E; - } - - pSz = wolfSSL_BN_bn2bin(dh->p, p); - gSz = wolfSSL_BN_bn2bin(dh->g, g); - - if(pSz >= 0 && gSz >= 0) /* Conversion successful */ - ret = wolfSSL_CTX_SetTmpDH(ctx, p, pSz, g, gSz); - - XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(g, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - - return pSz > 0 && gSz > 0 ? ret : WOLFSSL_FATAL_ERROR; -} -#endif /* OPENSSL_EXTRA && !NO_DH */ - - -/* returns the enum value associated with handshake state - * - * ssl the WOLFSSL structure to get state of - */ -int wolfSSL_get_state(const WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_state"); - - if (ssl == NULL) { - WOLFSSL_MSG("Null argument passed in"); - return WOLFSSL_FAILURE; - } - - return ssl->options.handShakeState; -} -#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */ - -#ifdef OPENSSL_EXTRA -void wolfSSL_certs_clear(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_certs_clear"); - - if (ssl == NULL) - return; - - /* ctx still owns certificate, certChain, key, dh, and cm */ - if (ssl->buffers.weOwnCert) - FreeDer(&ssl->buffers.certificate); - ssl->buffers.certificate = NULL; - if (ssl->buffers.weOwnCertChain) - FreeDer(&ssl->buffers.certChain); - ssl->buffers.certChain = NULL; -#ifdef WOLFSSL_TLS13 - ssl->buffers.certChainCnt = 0; -#endif - if (ssl->buffers.weOwnKey) - FreeDer(&ssl->buffers.key); - ssl->buffers.key = NULL; - ssl->buffers.keyType = 0; - ssl->buffers.keyId = 0; - ssl->buffers.keyLabel = 0; - ssl->buffers.keySz = 0; - ssl->buffers.keyDevId = 0; -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (ssl->buffers.weOwnAltKey) - FreeDer(&ssl->buffers.altKey); - ssl->buffers.altKey = NULL; -#endif /* WOLFSSL_DUAL_ALG_CERTS */ -} -#endif - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ - || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) - -long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt) -{ - WOLFSSL_ENTER("wolfSSL_ctrl"); - if (ssl == NULL) - return BAD_FUNC_ARG; - - switch (cmd) { - #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - #ifdef HAVE_SNI - case SSL_CTRL_SET_TLSEXT_HOSTNAME: - WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME."); - if (pt == NULL) { - WOLFSSL_MSG("Passed in NULL Host Name."); - break; - } - return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt); - #endif /* HAVE_SNI */ - #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */ - default: - WOLFSSL_MSG("Case not implemented."); - } - (void)opt; - (void)pt; - return WOLFSSL_FAILURE; -} - -long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt) -{ -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) - long ctrl_opt; -#endif - long ret = WOLFSSL_SUCCESS; - - WOLFSSL_ENTER("wolfSSL_CTX_ctrl"); - if (ctx == NULL) - return WOLFSSL_FAILURE; - - switch (cmd) { - case SSL_CTRL_CHAIN: -#ifdef SESSION_CERTS - { - /* - * We don't care about opt here because a copy of the certificate is - * stored anyway so increasing the reference counter is not necessary. - * Just check to make sure that it is set to one of the correct values. - */ - WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt; - WOLFSSL_X509* x509; - int i; - if (opt != 0 && opt != 1) { - ret = WOLFSSL_FAILURE; - break; - } - /* Clear certificate chain */ - FreeDer(&ctx->certChain); - if (sk) { - for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) { - x509 = wolfSSL_sk_X509_value(sk, i); - /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */ - if (wolfSSL_X509_up_ref(x509) != 1) { - WOLFSSL_MSG("Error increasing reference count"); - continue; - } - if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) != - WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error adding certificate to context"); - /* Decrease reference count on failure */ - wolfSSL_X509_free(x509); - } - } - } - /* Free previous chain */ - wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL); - ctx->x509Chain = sk; - if (sk && opt == 1) { - /* up all refs when opt == 1 */ - for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) { - x509 = wolfSSL_sk_X509_value(sk, i); - if (wolfSSL_X509_up_ref(x509) != 1) { - WOLFSSL_MSG("Error increasing reference count"); - continue; - } - } - } - } -#else - WOLFSSL_MSG("Session certificates not compiled in"); - ret = WOLFSSL_FAILURE; -#endif - break; - -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) - case SSL_CTRL_OPTIONS: - WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS."); - ctrl_opt = wolfSSL_CTX_set_options(ctx, opt); - - #ifdef WOLFSSL_QT - /* Set whether to use client or server cipher preference */ - if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) - == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) { - WOLFSSL_MSG("Using Server's Cipher Preference."); - ctx->useClientOrder = FALSE; - } else { - WOLFSSL_MSG("Using Client's Cipher Preference."); - ctx->useClientOrder = TRUE; - } - #endif /* WOLFSSL_QT */ - - return ctrl_opt; -#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */ - case SSL_CTRL_EXTRA_CHAIN_CERT: - WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT."); - if (pt == NULL) { - WOLFSSL_MSG("Passed in x509 pointer NULL."); - ret = WOLFSSL_FAILURE; - break; - } - return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt); - -#ifndef NO_DH - case SSL_CTRL_SET_TMP_DH: - WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH."); - if (pt == NULL) { - WOLFSSL_MSG("Passed in DH pointer NULL."); - ret = WOLFSSL_FAILURE; - break; - } - return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt); -#endif - -#ifdef HAVE_ECC - case SSL_CTRL_SET_TMP_ECDH: - WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH."); - if (pt == NULL) { - WOLFSSL_MSG("Passed in ECDH pointer NULL."); - ret = WOLFSSL_FAILURE; - break; - } - return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt); -#endif - case SSL_CTRL_MODE: - wolfSSL_CTX_set_mode(ctx,opt); - break; - case SSL_CTRL_SET_MIN_PROTO_VERSION: - WOLFSSL_MSG("set min proto version"); - return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt); - case SSL_CTRL_SET_MAX_PROTO_VERSION: - WOLFSSL_MSG("set max proto version"); - return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt); - case SSL_CTRL_GET_MIN_PROTO_VERSION: - WOLFSSL_MSG("get min proto version"); - return wolfSSL_CTX_get_min_proto_version(ctx); - case SSL_CTRL_GET_MAX_PROTO_VERSION: - WOLFSSL_MSG("get max proto version"); - return wolfSSL_CTX_get_max_proto_version(ctx); - default: - WOLFSSL_MSG("CTX_ctrl cmd not implemented"); - ret = WOLFSSL_FAILURE; - break; - } - - (void)ctx; - (void)cmd; - (void)opt; - (void)pt; - WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret); - return ret; -} - -#ifndef WOLFSSL_NO_STUB -long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void)) -{ - (void) ctx; - (void) cmd; - (void) fp; - WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl"); - return WOLFSSL_FAILURE; - -} -#endif /* WOLFSSL_NO_STUB */ - -#ifndef NO_WOLFSSL_STUB -long wolfSSL_CTX_clear_extra_chain_certs(WOLFSSL_CTX* ctx) -{ - return wolfSSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0L, NULL); -} -#endif - -/* Returns the verifyCallback from the ssl structure if successful. -Returns NULL otherwise. */ -VerifyCallback wolfSSL_get_verify_callback(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_verify_callback"); - if (ssl) { - return ssl->verifyCallback; - } - return NULL; -} - -/* Adds the ASN1 certificate to the user ctx. -Returns WOLFSSL_SUCCESS if no error, returns WOLFSSL_FAILURE otherwise.*/ -int wolfSSL_CTX_use_certificate_ASN1(WOLFSSL_CTX *ctx, int derSz, - const unsigned char *der) -{ - WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_ASN1"); - if (der != NULL && ctx != NULL) { - if (wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz, - WOLFSSL_FILETYPE_ASN1) == WOLFSSL_SUCCESS) { - return WOLFSSL_SUCCESS; - } - - } - return WOLFSSL_FAILURE; -} - - -#if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) -/* Adds the rsa private key to the user ctx. -Returns WOLFSSL_SUCCESS if no error, returns WOLFSSL_FAILURE otherwise.*/ -int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) -{ - int ret; - int derSize; - unsigned char *maxDerBuf; - unsigned char* key = NULL; - - WOLFSSL_ENTER("wolfSSL_CTX_use_RSAPrivateKey"); - - if (ctx == NULL || rsa == NULL) { - WOLFSSL_MSG("one or more inputs were NULL"); - return BAD_FUNC_ARG; - } - maxDerBuf = (unsigned char*)XMALLOC(4096, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (maxDerBuf == NULL) { - WOLFSSL_MSG("Malloc failure"); - return MEMORY_E; - } - key = maxDerBuf; - /* convert RSA struct to der encoded buffer and get the size */ - if ((derSize = wolfSSL_i2d_RSAPrivateKey(rsa, &key)) <= 0) { - WOLFSSL_MSG("wolfSSL_i2d_RSAPrivateKey() failure"); - XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_FAILURE; - } - ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, (const unsigned char*)maxDerBuf, - derSize, SSL_FILETYPE_ASN1); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_CTX_USE_PrivateKey_buffer() failure"); - XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return WOLFSSL_FAILURE; - } - XFREE(maxDerBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return ret; -} -#endif /* WOLFSSL_KEY_GEN && !NO_RSA */ - - -#ifndef NO_BIO -/* Converts EVP_PKEY data from a bio buffer to a WOLFSSL_EVP_PKEY structure. -Returns pointer to private EVP_PKEY struct upon success, NULL if there -is a failure.*/ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY** out) -{ - unsigned char* mem = NULL; - int memSz = 0; - WOLFSSL_EVP_PKEY* key = NULL; - unsigned char* extraBioMem = NULL; - - WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_bio"); - - if (bio == NULL) { - return NULL; - } - (void)out; - - memSz = wolfSSL_BIO_get_len(bio); - if (memSz <= 0) { - WOLFSSL_MSG("wolfSSL_BIO_get_len() failure"); - return NULL; - } - - mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (mem == NULL) { - WOLFSSL_MSG("Malloc failure"); - return NULL; - } - - if (wolfSSL_BIO_read(bio, (unsigned char*)mem, memSz) == memSz) { - int extraBioMemSz; - int derLength; - - /* Determines key type and returns the new private EVP_PKEY object */ - if ((key = wolfSSL_d2i_PrivateKey_EVP(NULL, &mem, (long)memSz)) == NULL) { - WOLFSSL_MSG("wolfSSL_d2i_PrivateKey_EVP() failure"); - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - return NULL; - } - - /* Write extra data back into bio object if necessary. */ - derLength = key->pkey_sz; - extraBioMemSz = (memSz - derLength); - if (extraBioMemSz > 0) { - int i; - int j = 0; - - extraBioMem = (unsigned char *)XMALLOC(extraBioMemSz, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (extraBioMem == NULL) { - WOLFSSL_MSG("Malloc failure"); - XFREE((unsigned char*)extraBioMem, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - return NULL; - } - - for (i = derLength; i < memSz; i++) { - *(extraBioMem + j) = *(mem + i); - j++; - } - - wolfSSL_BIO_write(bio, extraBioMem, extraBioMemSz); - if (wolfSSL_BIO_get_len(bio) <= 0) { - WOLFSSL_MSG("Failed to write memory to bio"); - XFREE((unsigned char*)extraBioMem, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - return NULL; - } - XFREE((unsigned char*)extraBioMem, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - } - - if (out != NULL) { - *out = key; - } - } - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - return key; -} -#endif /* !NO_BIO */ - -#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */ - - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || defined(WOLFSSL_WPAS_SMALL) - -/* Converts a DER encoded private key to a WOLFSSL_EVP_PKEY structure. - * returns a pointer to a new WOLFSSL_EVP_PKEY structure on success and NULL - * on fail */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_EVP(WOLFSSL_EVP_PKEY** out, - unsigned char** in, long inSz) -{ - WOLFSSL_ENTER("wolfSSL_d2i_PrivateKey_EVP"); - return d2iGenericKey(out, (const unsigned char**)in, inSz, 1); -} - -#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT || WOLFSSL_WPAS_SMALL*/ - - -/* stunnel compatibility functions*/ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH))) -void wolfSSL_ERR_remove_thread_state(void* pid) -{ - (void) pid; - return; -} - -#ifndef NO_FILESYSTEM -/***TBD ***/ -void wolfSSL_print_all_errors_fp(XFILE fp) -{ - (void)fp; -} -#endif /* !NO_FILESYSTEM */ - -#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX || - HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */ - - -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ - defined(HAVE_EX_DATA) - -#if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE) -static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, - void* data, byte get, void** getRet, int* setRet) -{ - int row; - int i; - int error = 0; - SessionRow* sessRow = NULL; - const byte* id; - byte foundCache = 0; - - if (getRet != NULL) - *getRet = NULL; - if (setRet != NULL) - *setRet = WOLFSSL_FAILURE; - - id = session->sessionID; - if (session->haveAltSessionID) - id = session->altSessionID; - - row = (int)(HashObject(id, ID_LEN, &error) % SESSION_ROWS); - if (error != 0) { - WOLFSSL_MSG("Hash session failed"); - return; - } - - sessRow = &SessionCache[row]; - if (get) - error = SESSION_ROW_RD_LOCK(sessRow); - else - error = SESSION_ROW_WR_LOCK(sessRow); - if (error != 0) { - WOLFSSL_MSG("Session row lock failed"); - return; - } - - for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { - WOLFSSL_SESSION* cacheSession; -#ifdef SESSION_CACHE_DYNAMIC_MEM - cacheSession = sessRow->Sessions[i]; -#else - cacheSession = &sessRow->Sessions[i]; -#endif - if (cacheSession && - XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0 - && session->side == cacheSession->side - #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) - && (IsAtLeastTLSv1_3(session->version) == - IsAtLeastTLSv1_3(cacheSession->version)) - #endif - ) { - if (get) { - if (getRet) { - *getRet = wolfSSL_CRYPTO_get_ex_data( - &cacheSession->ex_data, idx); - } - } - else { - if (setRet) { - *setRet = wolfSSL_CRYPTO_set_ex_data( - &cacheSession->ex_data, idx, data); - } - } - foundCache = 1; - break; - } - } - SESSION_ROW_UNLOCK(sessRow); - /* If we don't have a session in cache then clear the ex_data and - * own it */ - if (!foundCache) { - XMEMSET(&session->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA)); - session->ownExData = 1; - if (!get) { - *setRet = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, - data); - } - } - -} -#endif - -int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data) -{ - int ret = WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data"); -#ifdef HAVE_EX_DATA - session = ClientSessionToSession(session); - if (session != NULL) { -#ifndef NO_SESSION_CACHE - if (!session->ownExData) { - /* Need to update in cache */ - SESSION_ex_data_cache_update(session, idx, data, 0, NULL, &ret); - } - else -#endif - { - ret = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, data); - } - } -#else - (void)session; - (void)idx; - (void)data; -#endif - return ret; -} - -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -int wolfSSL_SESSION_set_ex_data_with_cleanup( - WOLFSSL_SESSION* session, - int idx, - void* data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine) -{ - WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data_with_cleanup"); - session = ClientSessionToSession(session); - if(session != NULL) { - return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&session->ex_data, idx, - data, cleanup_routine); - } - return WOLFSSL_FAILURE; -} -#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - -void* wolfSSL_SESSION_get_ex_data(const WOLFSSL_SESSION* session, int idx) -{ - void* ret = NULL; - WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_data"); -#ifdef HAVE_EX_DATA - session = ClientSessionToSession(session); - if (session != NULL) { -#ifndef NO_SESSION_CACHE - if (!session->ownExData) { - /* Need to retrieve the data from the session cache */ - SESSION_ex_data_cache_update((WOLFSSL_SESSION*)session, idx, NULL, - 1, &ret, NULL); - } - else -#endif - { - ret = wolfSSL_CRYPTO_get_ex_data(&session->ex_data, idx); - } - } -#else - (void)session; - (void)idx; -#endif - return ret; -} -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_EX_DATA */ - -/* Note: This is a huge section of API's - through - * wolfSSL_X509_OBJECT_get0_X509_CRL */ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ - (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB))) -#ifdef HAVE_EX_DATA -int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, - WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func) -{ - WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_new_index"); - return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_SESSION, ctx_l, - ctx_ptr, new_func, dup_func, free_func); -} -#endif - -#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \ - !defined(WOLFSSL_STATIC_MEMORY) -static wolfSSL_OSSL_Malloc_cb ossl_malloc = NULL; -static wolfSSL_OSSL_Free_cb ossl_free = NULL; -static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL; - -static void* OSSL_Malloc(size_t size) -{ - if (ossl_malloc != NULL) - return ossl_malloc(size, NULL, 0); - else - return NULL; -} - -static void OSSL_Free(void *ptr) -{ - if (ossl_free != NULL) - ossl_free(ptr, NULL, 0); -} - -static void* OSSL_Realloc(void *ptr, size_t size) -{ - if (ossl_realloc != NULL) - return ossl_realloc(ptr, size, NULL, 0); - else - return NULL; -} -#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY && - * !WOLFSSL_STATIC_MEMORY */ - -int wolfSSL_CRYPTO_set_mem_functions( - wolfSSL_OSSL_Malloc_cb m, - wolfSSL_OSSL_Realloc_cb r, - wolfSSL_OSSL_Free_cb f) -{ -#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) -#ifdef WOLFSSL_DEBUG_MEMORY - WOLFSSL_MSG("mem functions will receive function name instead of " - "file name"); - if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f, - (wolfSSL_Realloc_cb)r) == 0) - return WOLFSSL_SUCCESS; -#else - WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem " - "functions will receive a NULL file name and 0 for the " - "line number."); - if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc, - (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) { - ossl_malloc = m; - ossl_free = f; - ossl_realloc = r; - return WOLFSSL_SUCCESS; - } -#endif - else - return WOLFSSL_FAILURE; -#else - (void)m; - (void)r; - (void)f; - WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in"); - return WOLFSSL_FAILURE; -#endif -} - -int wolfSSL_ERR_load_ERR_strings(void) -{ - return WOLFSSL_SUCCESS; -} - -void wolfSSL_ERR_load_crypto_strings(void) -{ - WOLFSSL_ENTER("wolfSSL_ERR_load_crypto_strings"); - /* Do nothing */ - return; -} - -int wolfSSL_FIPS_mode(void) -{ -#ifdef HAVE_FIPS - return 1; -#else - return 0; -#endif -} - -int wolfSSL_FIPS_mode_set(int r) -{ -#ifdef HAVE_FIPS - if (r == 0) { - WOLFSSL_MSG("Cannot disable FIPS at runtime."); - return WOLFSSL_FAILURE; - } - return WOLFSSL_SUCCESS; -#else - if (r == 0) { - return WOLFSSL_SUCCESS; - } - WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code."); - return WOLFSSL_FAILURE; -#endif -} - -int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits) -{ - int ret = WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits"); - - #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - (void)alg_bits; - if (c!= NULL) - ret = c->bits; - #else - if (c != NULL && c->ssl != NULL) { - ret = 8 * c->ssl->specs.key_size; - if (alg_bits != NULL) { - *alg_bits = ret; - } - } - #endif - return ret; -} - -/* returns value less than 0 on fail to match - * On a successful match the priority level found is returned - */ -int wolfSSL_sk_SSL_CIPHER_find( - WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, const WOLFSSL_CIPHER* toFind) -{ - WOLFSSL_STACK* next; - int i, sz; - - if (sk == NULL || toFind == NULL) { - return WOLFSSL_FATAL_ERROR; - } - - sz = wolfSSL_sk_SSL_CIPHER_num(sk); - next = sk; - for (i = 0; i < sz && next != NULL; i++) { - if (next->data.cipher.cipherSuite0 == toFind->cipherSuite0 && - next->data.cipher.cipherSuite == toFind->cipherSuite) { - return sz - i; /* reverse because stack pushed highest on first */ - } - next = next->next; - } - return WOLFSSL_FATAL_ERROR; -} - -/* free's all nodes in the stack and there data */ -void wolfSSL_sk_SSL_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk) -{ - WOLFSSL_ENTER("wolfSSL_sk_SSL_CIPHER_free"); - wolfSSL_sk_free(sk); -} - -#ifdef HAVE_SNI -int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name) -{ - int ret; - WOLFSSL_ENTER("wolfSSL_set_tlsext_host_name"); - ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, - host_name, (word16)XSTRLEN(host_name)); - WOLFSSL_LEAVE("wolfSSL_set_tlsext_host_name", ret); - return ret; -} - - -#ifndef NO_WOLFSSL_SERVER -const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type) -{ - void * serverName = NULL; - if (ssl == NULL) - return NULL; - TLSX_SNI_GetRequest(ssl->extensions, type, &serverName); - return (const char *)serverName; -} -#endif /* NO_WOLFSSL_SERVER */ -#endif /* HAVE_SNI */ - -WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) -{ - int ret; - /* This method requires some explanation. Its sibling is - * int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) - * which re-inits the WOLFSSL* with all settings in the new CTX. - * That one is the right one to use *before* a handshake is started. - * - * This method was added by OpenSSL to be used *during* the handshake, e.g. - * when a server inspects the SNI in a ClientHello callback and - * decides which set of certificates to use. - * - * Since, at the time the SNI callback is run, some decisions on - * Extensions or the ServerHello might already have been taken, this - * method is very restricted in what it does: - * - changing the server certificate(s) - * - changing the server id for session handling - * and everything else in WOLFSSL* needs to remain untouched. - */ - WOLFSSL_ENTER("wolfSSL_set_SSL_CTX"); - if (ssl == NULL || ctx == NULL) - return NULL; - if (ssl->ctx == ctx) - return ssl->ctx; - - wolfSSL_RefInc(&ctx->ref, &ret); -#ifdef WOLFSSL_REFCNT_ERROR_RETURN - if (ret != 0) { - /* can only fail on serious stuff, like mutex not working - * or ctx refcount out of whack. */ - return NULL; - } -#else - (void)ret; -#endif - if (ssl->ctx != NULL) - wolfSSL_CTX_free(ssl->ctx); - ssl->ctx = ctx; - -#ifndef NO_CERTS - /* ctx owns certificate, certChain and key */ - ssl->buffers.certificate = ctx->certificate; - ssl->buffers.certChain = ctx->certChain; -#ifdef WOLFSSL_TLS13 - ssl->buffers.certChainCnt = ctx->certChainCnt; -#endif - ssl->buffers.key = ctx->privateKey; - ssl->buffers.keyType = ctx->privateKeyType; - ssl->buffers.keyId = ctx->privateKeyId; - ssl->buffers.keyLabel = ctx->privateKeyLabel; - ssl->buffers.keySz = ctx->privateKeySz; - ssl->buffers.keyDevId = ctx->privateKeyDevId; - /* flags indicating what certs/keys are available */ - ssl->options.haveRSA = ctx->haveRSA; - ssl->options.haveDH = ctx->haveDH; - ssl->options.haveECDSAsig = ctx->haveECDSAsig; - ssl->options.haveECC = ctx->haveECC; - ssl->options.haveStaticECC = ctx->haveStaticECC; - ssl->options.haveFalconSig = ctx->haveFalconSig; - ssl->options.haveDilithiumSig = ctx->haveDilithiumSig; -#ifdef WOLFSSL_DUAL_ALG_CERTS - ssl->buffers.altKey = ctx->altPrivateKey; - ssl->buffers.altKeySz = ctx->altPrivateKeySz; - ssl->buffers.altKeyType = ctx->altPrivateKeyType; -#endif /* WOLFSSL_DUAL_ALG_CERTS */ -#endif - -#ifdef WOLFSSL_SESSION_ID_CTX - /* copy over application session context ID */ - ssl->sessionCtxSz = ctx->sessionCtxSz; - XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz); -#endif - - return ssl->ctx; -} - - -VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_verify_callback"); - if(ctx) - return ctx->verifyCallback; - return NULL; -} - - -#ifdef HAVE_SNI - -void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_servername_callback"); - if (ctx) - ctx->sniRecvCb = cb; -} - -int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx, - CallbackSniRecv cb) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_tlsext_servername_callback"); - if (ctx) { - ctx->sniRecvCb = cb; - return WOLFSSL_SUCCESS; - } - return WOLFSSL_FAILURE; -} - -int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_servername_arg"); - if (ctx) { - ctx->sniRecvCbArg = arg; - return WOLFSSL_SUCCESS; - } - return WOLFSSL_FAILURE; -} - -#endif /* HAVE_SNI */ - - -#ifndef NO_BIO -void wolfSSL_ERR_load_BIO_strings(void) { - WOLFSSL_ENTER("wolfSSL_ERR_load_BIO_strings"); - /* do nothing */ -} -#endif - -#ifndef NO_WOLFSSL_STUB -/* Set THREADID callback, return 1 on success, 0 on error */ -int wolfSSL_THREADID_set_callback( - void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*)) -{ - WOLFSSL_ENTER("wolfSSL_THREADID_set_callback"); - WOLFSSL_STUB("CRYPTO_THREADID_set_callback"); - (void)threadid_func; - return 1; -} -#endif - -#ifndef NO_WOLFSSL_STUB -void wolfSSL_THREADID_set_numeric(void* id, unsigned long val) -{ - WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric"); - WOLFSSL_STUB("CRYPTO_THREADID_set_numeric"); - (void)id; - (void)val; - return; -} -#endif - -#endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX || - * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH || - * HAVE_SBLIM_SFCB)) */ - - -#if defined(OPENSSL_EXTRA) - -int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size) -{ - if (!a || !b) - return 0; - return ConstantCompare((const byte*)a, (const byte*)b, (int)size); -} - -unsigned long wolfSSL_ERR_peek_last_error(void) -{ - WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error"); - -#ifdef WOLFSSL_HAVE_ERROR_QUEUE - { - int ret; - - if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) { - WOLFSSL_MSG("Issue peeking at error node in queue"); - return 0; - } - if (ret == -ASN_NO_PEM_HEADER) - return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; - #if defined(WOLFSSL_PYTHON) - if (ret == ASN1_R_HEADER_TOO_LONG) - return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; - #endif - return (unsigned long)ret; - } -#else - return (unsigned long)(0 - NOT_COMPILED_IN); -#endif -} - -#endif /* OPENSSL_EXTRA */ - -int wolfSSL_version(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_version"); - if (ssl->version.major == SSLv3_MAJOR) { - switch (ssl->version.minor) { - case SSLv3_MINOR : - return SSL3_VERSION; - case TLSv1_MINOR : - return TLS1_VERSION; - case TLSv1_1_MINOR : - return TLS1_1_VERSION; - case TLSv1_2_MINOR : - return TLS1_2_VERSION; - case TLSv1_3_MINOR : - return TLS1_3_VERSION; - default: - return WOLFSSL_FAILURE; - } - } - else if (ssl->version.major == DTLS_MAJOR) { - switch (ssl->version.minor) { - case DTLS_MINOR : - return DTLS1_VERSION; - case DTLSv1_2_MINOR : - return DTLS1_2_VERSION; - case DTLSv1_3_MINOR: - return DTLS1_3_VERSION; - default: - return WOLFSSL_FAILURE; - } - } - return WOLFSSL_FAILURE; -} - -WOLFSSL_CTX* wolfSSL_get_SSL_CTX(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_SSL_CTX"); - return ssl->ctx; -} - -#if defined(OPENSSL_ALL) || \ - defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - -const byte* wolfSSL_SESSION_get_id(const WOLFSSL_SESSION* sess, - unsigned int* idLen) -{ - WOLFSSL_ENTER("wolfSSL_SESSION_get_id"); - sess = ClientSessionToSession(sess); - if (sess == NULL || idLen == NULL) { - WOLFSSL_MSG("Bad func args. Please provide idLen"); - return NULL; - } -#ifdef HAVE_SESSION_TICKET - if (sess->haveAltSessionID) { - *idLen = ID_LEN; - return sess->altSessionID; - } -#endif - *idLen = sess->sessionIDSz; - return sess->sessionID; -} - -#if (defined(HAVE_SESSION_TICKET) || defined(SESSION_CERTS)) && \ - !defined(NO_FILESYSTEM) - -#ifndef NO_BIO - -#if defined(SESSION_CERTS) || \ - (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) -/* returns a pointer to the protocol used by the session */ -static const char* wolfSSL_SESSION_get_protocol(const WOLFSSL_SESSION* in) -{ - in = ClientSessionToSession(in); - return wolfSSL_internal_get_version((ProtocolVersion*)&in->version); -} -#endif - -/* returns true (non 0) if the session has EMS (extended master secret) */ -static int wolfSSL_SESSION_haveEMS(const WOLFSSL_SESSION* in) -{ - in = ClientSessionToSession(in); - if (in == NULL) - return 0; - return in->haveEMS; -} - -#if defined(HAVE_SESSION_TICKET) -/* prints out the ticket to bio passed in - * return WOLFSSL_SUCCESS on success - */ -static int wolfSSL_SESSION_print_ticket(WOLFSSL_BIO* bio, - const WOLFSSL_SESSION* in, const char* tab) -{ - unsigned short i, j, z, sz; - short tag = 0; - byte* pt; - - - in = ClientSessionToSession(in); - if (in == NULL || bio == NULL) { - return BAD_FUNC_ARG; - } - - sz = in->ticketLen; - pt = in->ticket; - - if (wolfSSL_BIO_printf(bio, "%s\n", (sz == 0)? " NONE": "") <= 0) - return WOLFSSL_FAILURE; - - for (i = 0; i < sz;) { - char asc[16]; - XMEMSET(asc, 0, sizeof(asc)); - - if (sz - i < 16) { - if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag + (sz - i)) <= 0) - return WOLFSSL_FAILURE; - } - else { - if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag) <= 0) - return WOLFSSL_FAILURE; - } - for (j = 0; i < sz && j < 8; j++,i++) { - asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; - if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0) - return WOLFSSL_FAILURE; - } - - if (i < sz) { - asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; - if (wolfSSL_BIO_printf(bio, "-%02X", pt[i]) <= 0) - return WOLFSSL_FAILURE; - j++; - i++; - } - - for (; i < sz && j < 16; j++,i++) { - asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; - if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0) - return WOLFSSL_FAILURE; - } - - /* pad out spacing */ - for (z = j; z < 17; z++) { - if (wolfSSL_BIO_printf(bio, " ") <= 0) - return WOLFSSL_FAILURE; - } - - for (z = 0; z < j; z++) { - if (wolfSSL_BIO_printf(bio, "%c", asc[z]) <= 0) - return WOLFSSL_FAILURE; - } - if (wolfSSL_BIO_printf(bio, "\n") <= 0) - return WOLFSSL_FAILURE; - - tag += 16; - } - return WOLFSSL_SUCCESS; -} -#endif /* HAVE_SESSION_TICKET */ - - -/* prints out the session information in human readable form - * return WOLFSSL_SUCCESS on success - */ -int wolfSSL_SESSION_print(WOLFSSL_BIO *bp, const WOLFSSL_SESSION *session) -{ - const unsigned char* pt; - unsigned char buf[SECRET_LEN]; - unsigned int sz = 0, i; - int ret; - - session = ClientSessionToSession(session); - if (session == NULL) { - return WOLFSSL_FAILURE; - } - - if (wolfSSL_BIO_printf(bp, "%s\n", "SSL-Session:") <= 0) - return WOLFSSL_FAILURE; - -#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ - defined(HAVE_SESSION_TICKET)) - if (wolfSSL_BIO_printf(bp, " Protocol : %s\n", - wolfSSL_SESSION_get_protocol(session)) <= 0) - return WOLFSSL_FAILURE; -#endif - - if (wolfSSL_BIO_printf(bp, " Cipher : %s\n", - wolfSSL_SESSION_CIPHER_get_name(session)) <= 0) - return WOLFSSL_FAILURE; - - pt = wolfSSL_SESSION_get_id(session, &sz); - if (wolfSSL_BIO_printf(bp, " Session-ID: ") <= 0) - return WOLFSSL_FAILURE; - - for (i = 0; i < sz; i++) { - if (wolfSSL_BIO_printf(bp, "%02X", pt[i]) <= 0) - return WOLFSSL_FAILURE; - } - if (wolfSSL_BIO_printf(bp, "\n") <= 0) - return WOLFSSL_FAILURE; - - if (wolfSSL_BIO_printf(bp, " Session-ID-ctx: \n") <= 0) - return WOLFSSL_FAILURE; - - ret = wolfSSL_SESSION_get_master_key(session, buf, sizeof(buf)); - if (wolfSSL_BIO_printf(bp, " Master-Key: ") <= 0) - return WOLFSSL_FAILURE; - - if (ret > 0) { - sz = (unsigned int)ret; - for (i = 0; i < sz; i++) { - if (wolfSSL_BIO_printf(bp, "%02X", buf[i]) <= 0) - return WOLFSSL_FAILURE; - } - } - if (wolfSSL_BIO_printf(bp, "\n") <= 0) - return WOLFSSL_FAILURE; - - /* @TODO PSK identity hint and SRP */ - - if (wolfSSL_BIO_printf(bp, " TLS session ticket:") <= 0) - return WOLFSSL_FAILURE; - -#ifdef HAVE_SESSION_TICKET - if (wolfSSL_SESSION_print_ticket(bp, session, " ") != WOLFSSL_SUCCESS) - return WOLFSSL_FAILURE; -#endif - -#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \ - defined(HAVE_EXT_CACHE)) - if (wolfSSL_BIO_printf(bp, " Start Time: %ld\n", - wolfSSL_SESSION_get_time(session)) <= 0) - return WOLFSSL_FAILURE; - - if (wolfSSL_BIO_printf(bp, " Timeout : %ld (sec)\n", - wolfSSL_SESSION_get_timeout(session)) <= 0) - return WOLFSSL_FAILURE; -#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */ - - /* @TODO verify return code print */ - - if (wolfSSL_BIO_printf(bp, " Extended master secret: %s\n", - (wolfSSL_SESSION_haveEMS(session) == 0)? "no" : "yes") <= 0) - return WOLFSSL_FAILURE; - - return WOLFSSL_SUCCESS; -} - -#endif /* !NO_BIO */ -#endif /* (HAVE_SESSION_TICKET || SESSION_CERTS) && !NO_FILESYSTEM */ - -#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ - -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && defined(HAVE_STUNNEL)) \ - || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) - -/* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */ -int wolfSSL_get_verify_mode(const WOLFSSL* ssl) { - int mode = 0; - WOLFSSL_ENTER("wolfSSL_get_verify_mode"); - - if (!ssl) { - return WOLFSSL_FAILURE; - } - - if (ssl->options.verifyNone) { - mode = WOLFSSL_VERIFY_NONE; - } - else { - if (ssl->options.verifyPeer) { - mode |= WOLFSSL_VERIFY_PEER; - } - if (ssl->options.failNoCert) { - mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT; - } - if (ssl->options.failNoCertxPSK) { - mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK; - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - if (ssl->options.verifyPostHandshake) { - mode |= WOLFSSL_VERIFY_POST_HANDSHAKE; - } -#endif - } - - WOLFSSL_LEAVE("wolfSSL_get_verify_mode", mode); - return mode; -} - -int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx) -{ - int mode = 0; - WOLFSSL_ENTER("wolfSSL_CTX_get_verify_mode"); - - if (!ctx) { - return WOLFSSL_FAILURE; - } - - if (ctx->verifyNone) { - mode = WOLFSSL_VERIFY_NONE; - } - else { - if (ctx->verifyPeer) { - mode |= WOLFSSL_VERIFY_PEER; - } - if (ctx->failNoCert) { - mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT; - } - if (ctx->failNoCertxPSK) { - mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK; - } -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) - if (ctx->verifyPostHandshake) { - mode |= WOLFSSL_VERIFY_POST_HANDSHAKE; - } -#endif - } - - WOLFSSL_LEAVE("wolfSSL_CTX_get_verify_mode", mode); - return mode; -} - -#endif -#if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519) -/* return 1 if success, 0 if error - * output keys are little endian format - */ -int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz, - unsigned char *pub, unsigned int *pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN */ - int ret = WOLFSSL_FAILURE; - int initTmpRng = 0; - WC_RNG *rng = NULL; -#ifdef WOLFSSL_SMALL_STACK - WC_RNG *tmpRNG = NULL; -#else - WC_RNG tmpRNG[1]; -#endif - - WOLFSSL_ENTER("wolfSSL_EC25519_generate_key"); - - if (priv == NULL || privSz == NULL || *privSz < CURVE25519_KEYSIZE || - pub == NULL || pubSz == NULL || *pubSz < CURVE25519_KEYSIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (tmpRNG == NULL) - return WOLFSSL_FAILURE; -#endif - if (wc_InitRng(tmpRNG) == 0) { - rng = tmpRNG; - initTmpRng = 1; - } - else { - WOLFSSL_MSG("Bad RNG Init, trying global"); - if (initGlobalRNG == 0) - WOLFSSL_MSG("Global RNG no Init"); - else - rng = &globalRNG; - } - - if (rng) { - curve25519_key key; - - if (wc_curve25519_init(&key) != MP_OKAY) - WOLFSSL_MSG("wc_curve25519_init failed"); - else if (wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key)!=MP_OKAY) - WOLFSSL_MSG("wc_curve25519_make_key failed"); - /* export key pair */ - else if (wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub, - pubSz, EC25519_LITTLE_ENDIAN) - != MP_OKAY) - WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_curve25519_free(&key); - } - - if (initTmpRng) - wc_FreeRng(tmpRNG); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); -#endif - - return ret; -#endif /* WOLFSSL_KEY_GEN */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - */ -int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz, - const unsigned char *priv, unsigned int privSz, - const unsigned char *pub, unsigned int pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) shared; - (void) sharedSz; - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN */ - int ret = WOLFSSL_FAILURE; - curve25519_key privkey, pubkey; - - WOLFSSL_ENTER("wolfSSL_EC25519_shared_key"); - - if (shared == NULL || sharedSz == NULL || *sharedSz < CURVE25519_KEYSIZE || - priv == NULL || privSz < CURVE25519_KEYSIZE || - pub == NULL || pubSz < CURVE25519_KEYSIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import private key */ - if (wc_curve25519_init(&privkey) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_init privkey failed"); - return ret; - } - if (wc_curve25519_import_private_ex(priv, privSz, &privkey, - EC25519_LITTLE_ENDIAN) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_import_private_ex failed"); - wc_curve25519_free(&privkey); - return ret; - } - - /* import public key */ - if (wc_curve25519_init(&pubkey) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_init pubkey failed"); - wc_curve25519_free(&privkey); - return ret; - } - if (wc_curve25519_import_public_ex(pub, pubSz, &pubkey, - EC25519_LITTLE_ENDIAN) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_import_public_ex failed"); - wc_curve25519_free(&privkey); - wc_curve25519_free(&pubkey); - return ret; - } - - if (wc_curve25519_shared_secret_ex(&privkey, &pubkey, - shared, sharedSz, - EC25519_LITTLE_ENDIAN) != MP_OKAY) - WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_curve25519_free(&privkey); - wc_curve25519_free(&pubkey); - - return ret; -#endif /* WOLFSSL_KEY_GEN */ -} -#endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */ - -#if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519) -/* return 1 if success, 0 if error - * output keys are little endian format - */ -int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz, - unsigned char *pub, unsigned int *pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#elif !defined(HAVE_ED25519_KEY_EXPORT) - WOLFSSL_MSG("No ED25519 key export built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */ - int ret = WOLFSSL_FAILURE; - int initTmpRng = 0; - WC_RNG *rng = NULL; -#ifdef WOLFSSL_SMALL_STACK - WC_RNG *tmpRNG = NULL; -#else - WC_RNG tmpRNG[1]; -#endif - - WOLFSSL_ENTER("wolfSSL_ED25519_generate_key"); - - if (priv == NULL || privSz == NULL || *privSz < ED25519_PRV_KEY_SIZE || - pub == NULL || pubSz == NULL || *pubSz < ED25519_PUB_KEY_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (tmpRNG == NULL) - return WOLFSSL_FATAL_ERROR; -#endif - if (wc_InitRng(tmpRNG) == 0) { - rng = tmpRNG; - initTmpRng = 1; - } - else { - WOLFSSL_MSG("Bad RNG Init, trying global"); - if (initGlobalRNG == 0) - WOLFSSL_MSG("Global RNG no Init"); - else - rng = &globalRNG; - } - - if (rng) { - ed25519_key key; - - if (wc_ed25519_init(&key) != MP_OKAY) - WOLFSSL_MSG("wc_ed25519_init failed"); - else if (wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key)!=MP_OKAY) - WOLFSSL_MSG("wc_ed25519_make_key failed"); - /* export private key */ - else if (wc_ed25519_export_key(&key, priv, privSz, pub, pubSz)!=MP_OKAY) - WOLFSSL_MSG("wc_ed25519_export_key failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed25519_free(&key); - } - - if (initTmpRng) - wc_FreeRng(tmpRNG); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); -#endif - - return ret; -#endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - * priv is a buffer containing private and public part of key - */ -int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz, - const unsigned char *priv, unsigned int privSz, - unsigned char *sig, unsigned int *sigSz) -{ -#if !defined(HAVE_ED25519_SIGN) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED25519_KEY_IMPORT) -#if !defined(HAVE_ED25519_SIGN) - WOLFSSL_MSG("No ED25519 sign built in"); -#elif !defined(WOLFSSL_KEY_GEN) - WOLFSSL_MSG("No Key Gen built in"); -#elif !defined(HAVE_ED25519_KEY_IMPORT) - WOLFSSL_MSG("No ED25519 Key import built in"); -#endif - (void) msg; - (void) msgSz; - (void) priv; - (void) privSz; - (void) sig; - (void) sigSz; - return WOLFSSL_FAILURE; -#else /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ - ed25519_key key; - int ret = WOLFSSL_FAILURE; - - WOLFSSL_ENTER("wolfSSL_ED25519_sign"); - - if (priv == NULL || privSz != ED25519_PRV_KEY_SIZE || - msg == NULL || sig == NULL || *sigSz < ED25519_SIG_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import key */ - if (wc_ed25519_init(&key) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_init failed"); - return ret; - } - if (wc_ed25519_import_private_key(priv, privSz/2, - priv+(privSz/2), ED25519_PUB_KEY_SIZE, - &key) != MP_OKAY){ - WOLFSSL_MSG("wc_ed25519_import_private failed"); - wc_ed25519_free(&key); - return ret; - } - - if (wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key) != MP_OKAY) - WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed25519_free(&key); - - return ret; -#endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - * pub is a buffer containing public part of key - */ -int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz, - const unsigned char *pub, unsigned int pubSz, - const unsigned char *sig, unsigned int sigSz) -{ -#if !defined(HAVE_ED25519_VERIFY) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED25519_KEY_IMPORT) -#if !defined(HAVE_ED25519_VERIFY) - WOLFSSL_MSG("No ED25519 verify built in"); -#elif !defined(WOLFSSL_KEY_GEN) - WOLFSSL_MSG("No Key Gen built in"); -#elif !defined(HAVE_ED25519_KEY_IMPORT) - WOLFSSL_MSG("No ED25519 Key import built in"); -#endif - (void) msg; - (void) msgSz; - (void) pub; - (void) pubSz; - (void) sig; - (void) sigSz; - return WOLFSSL_FAILURE; -#else /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ - ed25519_key key; - int ret = WOLFSSL_FAILURE, check = 0; - - WOLFSSL_ENTER("wolfSSL_ED25519_verify"); - - if (pub == NULL || pubSz != ED25519_PUB_KEY_SIZE || - msg == NULL || sig == NULL || sigSz != ED25519_SIG_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import key */ - if (wc_ed25519_init(&key) != MP_OKAY) { - WOLFSSL_MSG("wc_curve25519_init failed"); - return ret; - } - if (wc_ed25519_import_public(pub, pubSz, &key) != MP_OKAY){ - WOLFSSL_MSG("wc_ed25519_import_public failed"); - wc_ed25519_free(&key); - return ret; - } - - if ((ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz, - &check, &key)) != MP_OKAY) { - WOLFSSL_MSG("wc_ed25519_verify_msg failed"); - } - else if (!check) - WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed25519_free(&key); - - return ret; -#endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */ -} - -#endif /* OPENSSL_EXTRA && HAVE_ED25519 */ - -#if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448) -/* return 1 if success, 0 if error - * output keys are little endian format - */ -int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz, - unsigned char *pub, unsigned int *pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN */ - int ret = WOLFSSL_FAILURE; - int initTmpRng = 0; - WC_RNG *rng = NULL; -#ifdef WOLFSSL_SMALL_STACK - WC_RNG *tmpRNG = NULL; -#else - WC_RNG tmpRNG[1]; -#endif - - WOLFSSL_ENTER("wolfSSL_EC448_generate_key"); - - if (priv == NULL || privSz == NULL || *privSz < CURVE448_KEY_SIZE || - pub == NULL || pubSz == NULL || *pubSz < CURVE448_KEY_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (tmpRNG == NULL) - return WOLFSSL_FAILURE; -#endif - if (wc_InitRng(tmpRNG) == 0) { - rng = tmpRNG; - initTmpRng = 1; - } - else { - WOLFSSL_MSG("Bad RNG Init, trying global"); - if (initGlobalRNG == 0) - WOLFSSL_MSG("Global RNG no Init"); - else - rng = &globalRNG; - } - - if (rng) { - curve448_key key; - - if (wc_curve448_init(&key) != MP_OKAY) - WOLFSSL_MSG("wc_curve448_init failed"); - else if (wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key)!=MP_OKAY) - WOLFSSL_MSG("wc_curve448_make_key failed"); - /* export key pair */ - else if (wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz, - EC448_LITTLE_ENDIAN) - != MP_OKAY) - WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_curve448_free(&key); - } - - if (initTmpRng) - wc_FreeRng(tmpRNG); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); -#endif - - return ret; -#endif /* WOLFSSL_KEY_GEN */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - */ -int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz, - const unsigned char *priv, unsigned int privSz, - const unsigned char *pub, unsigned int pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) shared; - (void) sharedSz; - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN */ - int ret = WOLFSSL_FAILURE; - curve448_key privkey, pubkey; - - WOLFSSL_ENTER("wolfSSL_EC448_shared_key"); - - if (shared == NULL || sharedSz == NULL || *sharedSz < CURVE448_KEY_SIZE || - priv == NULL || privSz < CURVE448_KEY_SIZE || - pub == NULL || pubSz < CURVE448_KEY_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import private key */ - if (wc_curve448_init(&privkey) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_init privkey failed"); - return ret; - } - if (wc_curve448_import_private_ex(priv, privSz, &privkey, - EC448_LITTLE_ENDIAN) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_import_private_ex failed"); - wc_curve448_free(&privkey); - return ret; - } - - /* import public key */ - if (wc_curve448_init(&pubkey) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_init pubkey failed"); - wc_curve448_free(&privkey); - return ret; - } - if (wc_curve448_import_public_ex(pub, pubSz, &pubkey, - EC448_LITTLE_ENDIAN) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_import_public_ex failed"); - wc_curve448_free(&privkey); - wc_curve448_free(&pubkey); - return ret; - } - - if (wc_curve448_shared_secret_ex(&privkey, &pubkey, shared, sharedSz, - EC448_LITTLE_ENDIAN) != MP_OKAY) - WOLFSSL_MSG("wc_curve448_shared_secret_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_curve448_free(&privkey); - wc_curve448_free(&pubkey); - - return ret; -#endif /* WOLFSSL_KEY_GEN */ -} -#endif /* OPENSSL_EXTRA && HAVE_CURVE448 */ - -#if defined(OPENSSL_EXTRA) && defined(HAVE_ED448) -/* return 1 if success, 0 if error - * output keys are little endian format - */ -int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz, - unsigned char *pub, unsigned int *pubSz) -{ -#ifndef WOLFSSL_KEY_GEN - WOLFSSL_MSG("No Key Gen built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#elif !defined(HAVE_ED448_KEY_EXPORT) - WOLFSSL_MSG("No ED448 key export built in"); - (void) priv; - (void) privSz; - (void) pub; - (void) pubSz; - return WOLFSSL_FAILURE; -#else /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */ - int ret = WOLFSSL_FAILURE; - int initTmpRng = 0; - WC_RNG *rng = NULL; -#ifdef WOLFSSL_SMALL_STACK - WC_RNG *tmpRNG = NULL; -#else - WC_RNG tmpRNG[1]; -#endif - - WOLFSSL_ENTER("wolfSSL_ED448_generate_key"); - - if (priv == NULL || privSz == NULL || *privSz < ED448_PRV_KEY_SIZE || - pub == NULL || pubSz == NULL || *pubSz < ED448_PUB_KEY_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (tmpRNG == NULL) - return WOLFSSL_FATAL_ERROR; -#endif - if (wc_InitRng(tmpRNG) == 0) { - rng = tmpRNG; - initTmpRng = 1; - } - else { - WOLFSSL_MSG("Bad RNG Init, trying global"); - if (initGlobalRNG == 0) - WOLFSSL_MSG("Global RNG no Init"); - else - rng = &globalRNG; - } - - if (rng) { - ed448_key key; - - if (wc_ed448_init(&key) != MP_OKAY) - WOLFSSL_MSG("wc_ed448_init failed"); - else if (wc_ed448_make_key(rng, ED448_KEY_SIZE, &key) != MP_OKAY) - WOLFSSL_MSG("wc_ed448_make_key failed"); - /* export private key */ - else if (wc_ed448_export_key(&key, priv, privSz, pub, pubSz) != MP_OKAY) - WOLFSSL_MSG("wc_ed448_export_key failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed448_free(&key); - } - - if (initTmpRng) - wc_FreeRng(tmpRNG); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); -#endif - - return ret; -#endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - * priv is a buffer containing private and public part of key - */ -int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz, - const unsigned char *priv, unsigned int privSz, - unsigned char *sig, unsigned int *sigSz) -{ -#if !defined(HAVE_ED448_SIGN) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED448_KEY_IMPORT) -#if !defined(HAVE_ED448_SIGN) - WOLFSSL_MSG("No ED448 sign built in"); -#elif !defined(WOLFSSL_KEY_GEN) - WOLFSSL_MSG("No Key Gen built in"); -#elif !defined(HAVE_ED448_KEY_IMPORT) - WOLFSSL_MSG("No ED448 Key import built in"); -#endif - (void) msg; - (void) msgSz; - (void) priv; - (void) privSz; - (void) sig; - (void) sigSz; - return WOLFSSL_FAILURE; -#else /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */ - ed448_key key; - int ret = WOLFSSL_FAILURE; - - WOLFSSL_ENTER("wolfSSL_ED448_sign"); - - if (priv == NULL || privSz != ED448_PRV_KEY_SIZE || msg == NULL || - sig == NULL || *sigSz < ED448_SIG_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import key */ - if (wc_ed448_init(&key) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_init failed"); - return ret; - } - if (wc_ed448_import_private_key(priv, privSz/2, priv+(privSz/2), - ED448_PUB_KEY_SIZE, &key) != MP_OKAY){ - WOLFSSL_MSG("wc_ed448_import_private failed"); - wc_ed448_free(&key); - return ret; - } - - if (wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0) != MP_OKAY) - WOLFSSL_MSG("wc_curve448_shared_secret_ex failed"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed448_free(&key); - - return ret; -#endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */ -} - -/* return 1 if success, 0 if error - * input and output keys are little endian format - * pub is a buffer containing public part of key - */ -int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz, - const unsigned char *pub, unsigned int pubSz, - const unsigned char *sig, unsigned int sigSz) -{ -#if !defined(HAVE_ED448_VERIFY) || !defined(WOLFSSL_KEY_GEN) || !defined(HAVE_ED448_KEY_IMPORT) -#if !defined(HAVE_ED448_VERIFY) - WOLFSSL_MSG("No ED448 verify built in"); -#elif !defined(WOLFSSL_KEY_GEN) - WOLFSSL_MSG("No Key Gen built in"); -#elif !defined(HAVE_ED448_KEY_IMPORT) - WOLFSSL_MSG("No ED448 Key import built in"); -#endif - (void) msg; - (void) msgSz; - (void) pub; - (void) pubSz; - (void) sig; - (void) sigSz; - return WOLFSSL_FAILURE; -#else /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */ - ed448_key key; - int ret = WOLFSSL_FAILURE, check = 0; - - WOLFSSL_ENTER("wolfSSL_ED448_verify"); - - if (pub == NULL || pubSz != ED448_PUB_KEY_SIZE || msg == NULL || - sig == NULL || sigSz != ED448_SIG_SIZE) { - WOLFSSL_MSG("Bad arguments"); - return WOLFSSL_FAILURE; - } - - /* import key */ - if (wc_ed448_init(&key) != MP_OKAY) { - WOLFSSL_MSG("wc_curve448_init failed"); - return ret; - } - if (wc_ed448_import_public(pub, pubSz, &key) != MP_OKAY){ - WOLFSSL_MSG("wc_ed448_import_public failed"); - wc_ed448_free(&key); - return ret; - } - - if ((ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check, - &key, NULL, 0)) != MP_OKAY) { - WOLFSSL_MSG("wc_ed448_verify_msg failed"); - } - else if (!check) - WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)"); - else - ret = WOLFSSL_SUCCESS; - - wc_ed448_free(&key); - - return ret; -#endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN */ -} - -#endif /* OPENSSL_EXTRA && HAVE_ED448 */ - -#ifdef WOLFSSL_JNI - -int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr) -{ - WOLFSSL_ENTER("wolfSSL_set_jobject"); - if (ssl != NULL) - { - ssl->jObjectRef = objPtr; - return WOLFSSL_SUCCESS; - } - return WOLFSSL_FAILURE; -} - -void* wolfSSL_get_jobject(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_jobject"); - if (ssl != NULL) - return ssl->jObjectRef; - return NULL; -} - -#endif /* WOLFSSL_JNI */ - - -#ifdef WOLFSSL_ASYNC_CRYPT -int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents, - WOLF_EVENT_FLAG flags, int* eventCount) -{ - if (ctx == NULL) { - return BAD_FUNC_ARG; - } - - return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL, - events, maxEvents, flags, eventCount); -} - -int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags) -{ - int ret, eventCount = 0; - WOLF_EVENT* events[1]; - - if (ssl == NULL) { - return BAD_FUNC_ARG; - } - - ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl, - events, sizeof(events)/sizeof(events[0]), flags, &eventCount); - if (ret == 0) { - ret = eventCount; - } - - return ret; -} -#endif /* WOLFSSL_ASYNC_CRYPT */ - -#ifdef OPENSSL_EXTRA - -static int peek_ignore_err(int err) -{ - switch(err) { - case -WANT_READ: - case -WANT_WRITE: - case -ZERO_RETURN: - case -WOLFSSL_ERROR_ZERO_RETURN: - case -SOCKET_PEER_CLOSED_E: - case -SOCKET_ERROR_E: - return 1; - default: - return 0; - } -} - -unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line, - const char **data, int *flags) -{ - unsigned long err; - - WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data"); - err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err); - - if (err == -ASN_NO_PEM_HEADER) - return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; -#ifdef OPENSSL_ALL - /* PARSE_ERROR is returned if an HTTP request is detected. */ - else if (err == -SSL_R_HTTP_REQUEST) - return (ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST; -#endif -#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - else if (err == ASN1_R_HEADER_TOO_LONG) - return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; -#endif - return err; -} -#endif - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - -#if !defined(WOLFSSL_USER_IO) -/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280 - * example input would be "127.0.0.1" and the returned value would be 7F000001 - */ -WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa) -{ - int ipaSz = WOLFSSL_IP4_ADDR_LEN; - char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */ - int af = WOLFSSL_IP4; - WOLFSSL_ASN1_STRING *ret = NULL; - - if (ipa == NULL) - return NULL; - - if (XSTRSTR(ipa, ":") != NULL) { - af = WOLFSSL_IP6; - ipaSz = WOLFSSL_IP6_ADDR_LEN; - } - - buf[WOLFSSL_IP6_ADDR_LEN] = '\0'; - if (XINET_PTON(af, ipa, (void*)buf) != 1) { - WOLFSSL_MSG("Error parsing IP address"); - return NULL; - } - - ret = wolfSSL_ASN1_STRING_new(); - if (ret != NULL) { - if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error setting the string"); - wolfSSL_ASN1_STRING_free(ret); - ret = NULL; - } - } - - return ret; -} -#endif /* !WOLFSSL_USER_IO */ - -/* Is the specified cipher suite a fake one used an an extension proxy? */ -static WC_INLINE int SCSV_Check(byte suite0, byte suite) -{ - (void)suite0; - (void)suite; -#ifdef HAVE_RENEGOTIATION_INDICATION - if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) - return 1; -#endif - return 0; -} - -static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0, - byte suite) -{ - const CipherSuiteInfo* cipher_names = GetCipherNames(); - int cipherSz = GetCipherNamesSize(); - int i; - for (i = 0; i < cipherSz; i++) - if (cipher_names[i].cipherSuite0 == suite0 && - cipher_names[i].cipherSuite == suite) - break; - if (i == cipherSz) - return 1; - /* Check min version */ - if (cipher_names[i].minor < ssl->options.minDowngrade) { - if (ssl->options.minDowngrade <= TLSv1_2_MINOR && - cipher_names[i].minor >= TLSv1_MINOR) - /* 1.0 ciphersuites are in general available in 1.1 and - * 1.1 ciphersuites are in general available in 1.2 */ - return 0; - return 1; - } - /* Check max version */ - switch (cipher_names[i].minor) { - case SSLv3_MINOR : - return ssl->options.mask & WOLFSSL_OP_NO_SSLv3; - case TLSv1_MINOR : - return ssl->options.mask & WOLFSSL_OP_NO_TLSv1; - case TLSv1_1_MINOR : - return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1; - case TLSv1_2_MINOR : - return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2; - case TLSv1_3_MINOR : - return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3; - default: - WOLFSSL_MSG("Unrecognized minor version"); - return 1; - } -} - -/* returns a pointer to internal cipher suite list. Should not be free'd by - * caller. - */ -WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl) -{ - WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL; - const Suites* suites; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - const CipherSuiteInfo* cipher_names = GetCipherNames(); - int cipherSz = GetCipherNamesSize(); -#endif - - WOLFSSL_ENTER("wolfSSL_get_ciphers_compat"); - if (ssl == NULL) - return NULL; - - suites = WOLFSSL_SUITES(ssl); - if (suites == NULL) - return NULL; - - /* check if stack needs populated */ - if (ssl->suitesStack == NULL) { - int i; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - int j; - - /* higher priority of cipher suite will be on top of stack */ - for (i = suites->suiteSz - 2; i >=0; i-=2) { -#else - for (i = 0; i < suites->suiteSz; i+=2) { -#endif - WOLFSSL_STACK* add; - - /* A couple of suites are placeholders for special options, - * skip those. */ - if (SCSV_Check(suites->suites[i], suites->suites[i+1]) - || sslCipherMinMaxCheck(ssl, suites->suites[i], - suites->suites[i+1])) { - continue; - } - - add = wolfSSL_sk_new_node(ssl->heap); - if (add != NULL) { - add->type = STACK_TYPE_CIPHER; - add->data.cipher.cipherSuite0 = suites->suites[i]; - add->data.cipher.cipherSuite = suites->suites[i+1]; - add->data.cipher.ssl = ssl; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - for (j = 0; j < cipherSz; j++) { - if (cipher_names[j].cipherSuite0 == - add->data.cipher.cipherSuite0 && - cipher_names[j].cipherSuite == - add->data.cipher.cipherSuite) { - add->data.cipher.offset = j; - break; - } - } -#endif - #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - /* in_stack is checked in wolfSSL_CIPHER_description */ - add->data.cipher.in_stack = 1; - #endif - - add->next = ret; - if (ret != NULL) { - add->num = ret->num + 1; - } - else { - add->num = 1; - } - ret = add; - } - } - ((WOLFSSL*)ssl)->suitesStack = ret; - } - return ssl->suitesStack; -} -#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ - || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK) -long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx) -{ - WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout"); - - if (ctx == NULL) - return 0; - - return ctx->timeout; -} - - -/* returns the time in seconds of the current timeout */ -long wolfSSL_get_timeout(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_get_timeout"); - - if (ssl == NULL) - return 0; - return ssl->timeout; -} -#endif - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ - || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) - -#ifdef HAVE_ECC -int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh) -{ - WOLFSSL_ENTER("wolfSSL_SSL_CTX_set_tmp_ecdh"); - - if (ctx == NULL || ecdh == NULL) - return BAD_FUNC_ARG; - - ctx->ecdhCurveOID = ecdh->group->curve_oid; - - return WOLFSSL_SUCCESS; -} -#endif -#ifndef NO_SESSION_CACHE -int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s) -{ -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - int rem_called = FALSE; -#endif - - WOLFSSL_ENTER("wolfSSL_SSL_CTX_remove_session"); - - s = ClientSessionToSession(s); - if (ctx == NULL || s == NULL) - return BAD_FUNC_ARG; - -#ifdef HAVE_EXT_CACHE - if (!ctx->internalCacheOff) -#endif - { - const byte* id; - WOLFSSL_SESSION *sess = NULL; - word32 row = 0; - int ret; - - id = s->sessionID; - if (s->haveAltSessionID) - id = s->altSessionID; - - ret = TlsSessionCacheGetAndWrLock(id, &sess, &row, ctx->method->side); - if (ret == 0 && sess != NULL) { -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - if (sess->rem_sess_cb != NULL) { - rem_called = TRUE; - } -#endif - /* Call this before changing ownExData so that calls to ex_data - * don't try to access the SessionCache again. */ - EvictSessionFromCache(sess); -#ifdef HAVE_EX_DATA - if (sess->ownExData) { - /* Most recent version of ex data is in cache. Copy it - * over so the user can free it. */ - XMEMCPY(&s->ex_data, &sess->ex_data, - sizeof(WOLFSSL_CRYPTO_EX_DATA)); - s->ownExData = 1; - sess->ownExData = 0; - } -#endif -#ifdef SESSION_CACHE_DYNAMIC_MEM - { - /* Find and clear entry. Row is locked so we are good to go. */ - int idx; - for (idx = 0; idx < SESSIONS_PER_ROW; idx++) { - if (sess == SessionCache[row].Sessions[idx]) { - XFREE(sess, sess->heap, DYNAMIC_TYPE_SESSION); - SessionCache[row].Sessions[idx] = NULL; - break; - } - } - } -#endif - TlsSessionCacheUnlockRow(row); - } - } - -#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) - if (ctx->rem_sess_cb != NULL && !rem_called) { - ctx->rem_sess_cb(ctx, s); - } -#endif - - /* s cannot be resumed at this point */ - s->timeout = 0; - - return 0; -} -#endif /* !NO_SESSION_CACHE */ -#ifndef NO_BIO -BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) -{ - WOLFSSL_ENTER("wolfSSL_SSL_get_rbio"); - /* Nginx sets the buffer size if the read BIO is different to write BIO. - * The setting buffer size doesn't do anything so return NULL for both. - */ - if (s == NULL) - return NULL; - - return s->biord; -} -BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s) -{ - WOLFSSL_ENTER("wolfSSL_SSL_get_wbio"); - (void)s; - /* Nginx sets the buffer size if the read BIO is different to write BIO. - * The setting buffer size doesn't do anything so return NULL for both. - */ - if (s == NULL) - return NULL; - - return s->biowr; -} -#endif /* !NO_BIO */ - -int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s) -{ - WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal"); - if (s == NULL) - return WOLFSSL_FAILURE; - - if (s->options.side == WOLFSSL_CLIENT_END) { - #ifndef NO_WOLFSSL_CLIENT - return wolfSSL_connect(s); - #else - WOLFSSL_MSG("Client not compiled in"); - return WOLFSSL_FAILURE; - #endif - } - -#ifndef NO_WOLFSSL_SERVER - return wolfSSL_accept(s); -#else - WOLFSSL_MSG("Server not compiled in"); - return WOLFSSL_FAILURE; -#endif -} - -int wolfSSL_SSL_do_handshake(WOLFSSL *s) -{ - WOLFSSL_ENTER("wolfSSL_SSL_do_handshake"); -#ifdef WOLFSSL_QUIC - if (WOLFSSL_IS_QUIC(s)) { - return wolfSSL_quic_do_handshake(s); - } -#endif - return wolfSSL_SSL_do_handshake_internal(s); -} - -#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L -int wolfSSL_SSL_in_init(const WOLFSSL *ssl) -#else -int wolfSSL_SSL_in_init(WOLFSSL *ssl) -#endif -{ - WOLFSSL_ENTER("wolfSSL_SSL_in_init"); - - return !wolfSSL_is_init_finished(ssl); -} - -int wolfSSL_SSL_in_before(const WOLFSSL *ssl) -{ - WOLFSSL_ENTER("wolfSSL_SSL_in_before"); - - if (ssl == NULL) - return WOLFSSL_FAILURE; - - return ssl->options.handShakeState == NULL_STATE; -} - -int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl) -{ - WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init"); - - if (ssl == NULL) - return WOLFSSL_FAILURE; - - if (ssl->options.side == WOLFSSL_CLIENT_END) { - return ssl->options.connectState > CONNECT_BEGIN && - ssl->options.connectState < SECOND_REPLY_DONE; - } - - return ssl->options.acceptState > ACCEPT_BEGIN && - ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE; -} - -#ifndef NO_SESSION_CACHE - -WOLFSSL_SESSION *wolfSSL_SSL_get0_session(const WOLFSSL *ssl) -{ - WOLFSSL_ENTER("wolfSSL_SSL_get0_session"); - - return ssl->session; -} - -#endif /* NO_SESSION_CACHE */ - -#if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) -/* Expected return values from implementations of OpenSSL ticket key callback. - */ -#define TICKET_KEY_CB_RET_FAILURE (-1) -#define TICKET_KEY_CB_RET_NOT_FOUND 0 -#define TICKET_KEY_CB_RET_OK 1 -#define TICKET_KEY_CB_RET_RENEW 2 - -/* Implementation of session ticket encryption/decryption using OpenSSL - * callback to initialize the cipher and HMAC. - * - * ssl The SSL/TLS object. - * keyName The key name - used to identify the key to be used. - * iv The IV to use. - * mac The MAC of the encrypted data. - * enc Encrypt ticket. - * encTicket The ticket data. - * encTicketLen The length of the ticket data. - * encLen The encrypted/decrypted ticket length - output length. - * ctx Ignored. Application specific data. - * returns WOLFSSL_TICKET_RET_OK to indicate success, - * WOLFSSL_TICKET_RET_CREATE if a new ticket is required and - * WOLFSSL_TICKET_RET_FATAL on error. - */ -static int wolfSSL_TicketKeyCb(WOLFSSL* ssl, - unsigned char keyName[WOLFSSL_TICKET_NAME_SZ], - unsigned char iv[WOLFSSL_TICKET_IV_SZ], - unsigned char mac[WOLFSSL_TICKET_MAC_SZ], - int enc, unsigned char* encTicket, - int encTicketLen, int* encLen, void* ctx) -{ - byte digest[WC_MAX_DIGEST_SIZE]; -#ifdef WOLFSSL_SMALL_STACK - WOLFSSL_EVP_CIPHER_CTX *evpCtx; -#else - WOLFSSL_EVP_CIPHER_CTX evpCtx[1]; -#endif - WOLFSSL_HMAC_CTX hmacCtx; - unsigned int mdSz = 0; - int len = 0; - int ret = WOLFSSL_TICKET_RET_FATAL; - int res; - int totalSz = 0; - - (void)ctx; - - WOLFSSL_ENTER("wolfSSL_TicketKeyCb"); - - if (ssl == NULL || ssl->ctx == NULL || ssl->ctx->ticketEncWrapCb == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_TICKET_RET_FATAL; - } - -#ifdef WOLFSSL_SMALL_STACK - evpCtx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC(sizeof(*evpCtx), ssl->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (evpCtx == NULL) { - WOLFSSL_MSG("out of memory"); - return WOLFSSL_TICKET_RET_FATAL; - } -#endif - - /* Initialize the cipher and HMAC. */ - wolfSSL_EVP_CIPHER_CTX_init(evpCtx); - if (wolfSSL_HMAC_CTX_Init(&hmacCtx) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init error"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return WOLFSSL_TICKET_RET_FATAL; - } - res = ssl->ctx->ticketEncWrapCb(ssl, keyName, - iv, evpCtx, &hmacCtx, enc); - if (res != TICKET_KEY_CB_RET_OK && res != TICKET_KEY_CB_RET_RENEW) { - WOLFSSL_MSG("Ticket callback error"); - ret = WOLFSSL_TICKET_RET_FATAL; - goto end; - } - - if (wolfSSL_HMAC_size(&hmacCtx) > WOLFSSL_TICKET_MAC_SZ) { - WOLFSSL_MSG("Ticket cipher MAC size error"); - goto end; - } - - if (enc) - { - /* Encrypt in place. */ - if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len, - encTicket, encTicketLen)) - goto end; - totalSz = len; - if (totalSz > *encLen) - goto end; - if (!wolfSSL_EVP_EncryptFinal(evpCtx, &encTicket[len], &len)) - goto end; - /* Total length of encrypted data. */ - totalSz += len; - if (totalSz > *encLen) - goto end; - - /* HMAC the encrypted data into the parameter 'mac'. */ - if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, totalSz)) - goto end; - if (!wolfSSL_HMAC_Final(&hmacCtx, mac, &mdSz)) - goto end; - } - else - { - /* HMAC the encrypted data and compare it to the passed in data. */ - if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, encTicketLen)) - goto end; - if (!wolfSSL_HMAC_Final(&hmacCtx, digest, &mdSz)) - goto end; - if (XMEMCMP(mac, digest, mdSz) != 0) - goto end; - - /* Decrypt the ticket data in place. */ - if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len, - encTicket, encTicketLen)) - goto end; - totalSz = len; - if (totalSz > encTicketLen) - goto end; - if (!wolfSSL_EVP_DecryptFinal(evpCtx, &encTicket[len], &len)) - goto end; - /* Total length of decrypted data. */ - totalSz += len; - if (totalSz > encTicketLen) - goto end; - } - *encLen = totalSz; - - if (res == TICKET_KEY_CB_RET_RENEW && !IsAtLeastTLSv1_3(ssl->version) - && !enc) - ret = WOLFSSL_TICKET_RET_CREATE; - else - ret = WOLFSSL_TICKET_RET_OK; -end: - - (void)wc_HmacFree(&hmacCtx.hmac); - (void)wolfSSL_EVP_CIPHER_CTX_cleanup(evpCtx); - -#ifdef WOLFSSL_SMALL_STACK - XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - - return ret; -} - -/* Set the callback to use when encrypting/decrypting tickets. - * - * ctx The SSL/TLS context object. - * cb The OpenSSL session ticket callback. - * returns WOLFSSL_SUCCESS to indicate success. - */ -int wolfSSL_CTX_set_tlsext_ticket_key_cb(WOLFSSL_CTX *ctx, ticketCompatCb cb) -{ - - /* Set the ticket encryption callback to be a wrapper around OpenSSL - * callback. - */ - ctx->ticketEncCb = wolfSSL_TicketKeyCb; - ctx->ticketEncWrapCb = cb; - - return WOLFSSL_SUCCESS; -} - -#endif /* HAVE_SESSION_TICKET */ - -#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || - OPENSSL_EXTRA || HAVE_LIGHTY */ - -#if defined(HAVE_SESSION_TICKET) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \ - !defined(NO_WOLFSSL_SERVER) -/* Serialize the session ticket encryption keys. - * - * @param [in] ctx SSL/TLS context object. - * @param [in] keys Buffer to hold session ticket keys. - * @param [in] keylen Length of buffer. - * @return WOLFSSL_SUCCESS on success. - * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the - * correct length. - */ -long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx, - unsigned char *keys, int keylen) -{ - if (ctx == NULL || keys == NULL) { - return WOLFSSL_FAILURE; - } - if (keylen != WOLFSSL_TICKET_KEYS_SZ) { - return WOLFSSL_FAILURE; - } - - XMEMCPY(keys, ctx->ticketKeyCtx.name, WOLFSSL_TICKET_NAME_SZ); - keys += WOLFSSL_TICKET_NAME_SZ; - XMEMCPY(keys, ctx->ticketKeyCtx.key[0], WOLFSSL_TICKET_KEY_SZ); - keys += WOLFSSL_TICKET_KEY_SZ; - XMEMCPY(keys, ctx->ticketKeyCtx.key[1], WOLFSSL_TICKET_KEY_SZ); - keys += WOLFSSL_TICKET_KEY_SZ; - c32toa(ctx->ticketKeyCtx.expirary[0], keys); - keys += OPAQUE32_LEN; - c32toa(ctx->ticketKeyCtx.expirary[1], keys); - - return WOLFSSL_SUCCESS; -} - -/* Deserialize the session ticket encryption keys. - * - * @param [in] ctx SSL/TLS context object. - * @param [in] keys Session ticket keys. - * @param [in] keylen Length of data. - * @return WOLFSSL_SUCCESS on success. - * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the - * correct length. - */ -long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx, - unsigned char *keys, int keylen) -{ - if (ctx == NULL || keys == NULL) { - return WOLFSSL_FAILURE; - } - if (keylen != WOLFSSL_TICKET_KEYS_SZ) { - return WOLFSSL_FAILURE; - } - - XMEMCPY(ctx->ticketKeyCtx.name, keys, WOLFSSL_TICKET_NAME_SZ); - keys += WOLFSSL_TICKET_NAME_SZ; - XMEMCPY(ctx->ticketKeyCtx.key[0], keys, WOLFSSL_TICKET_KEY_SZ); - keys += WOLFSSL_TICKET_KEY_SZ; - XMEMCPY(ctx->ticketKeyCtx.key[1], keys, WOLFSSL_TICKET_KEY_SZ); - keys += WOLFSSL_TICKET_KEY_SZ; - ato32(keys, &ctx->ticketKeyCtx.expirary[0]); - keys += OPAQUE32_LEN; - ato32(keys, &ctx->ticketKeyCtx.expirary[1]); - - return WOLFSSL_SUCCESS; -} -#endif - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) -#ifdef HAVE_OCSP -/* Not an OpenSSL API. */ -int wolfSSL_get_ocsp_response(WOLFSSL* ssl, byte** response) -{ - *response = ssl->ocspResp; - return ssl->ocspRespSz; -} - -/* Not an OpenSSL API. */ -char* wolfSSL_get_ocsp_url(WOLFSSL* ssl) -{ - return ssl->url; -} - -/* Not an OpenSSL API. */ -int wolfSSL_set_ocsp_url(WOLFSSL* ssl, char* url) -{ - if (ssl == NULL) - return WOLFSSL_FAILURE; - - ssl->url = url; - return WOLFSSL_SUCCESS; -} -#endif /* OCSP */ -#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ - -#if defined(HAVE_OCSP) && !defined(NO_ASN_TIME) -int wolfSSL_get_ocsp_producedDate( - WOLFSSL *ssl, - byte *producedDate, - size_t producedDate_space, - int *producedDateFormat) -{ - if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) && - (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME)) - return BAD_FUNC_ARG; - - if ((producedDate == NULL) || (producedDateFormat == NULL)) - return BAD_FUNC_ARG; - - if (XSTRLEN((char *)ssl->ocspProducedDate) >= producedDate_space) - return BUFFER_E; - - XSTRNCPY((char *)producedDate, (const char *)ssl->ocspProducedDate, producedDate_space); - *producedDateFormat = ssl->ocspProducedDateFormat; - - return 0; -} - -int wolfSSL_get_ocsp_producedDate_tm(WOLFSSL *ssl, struct tm *produced_tm) { - int idx = 0; - - if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) && - (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME)) - return BAD_FUNC_ARG; - - if (produced_tm == NULL) - return BAD_FUNC_ARG; - - if (ExtractDate(ssl->ocspProducedDate, - (unsigned char)ssl->ocspProducedDateFormat, produced_tm, &idx)) - return 0; - else - return ASN_PARSE_E; -} -#endif - - -#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ - defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) -int wolfSSL_CTX_get_extra_chain_certs(WOLFSSL_CTX* ctx, WOLF_STACK_OF(X509)** chain) -{ - word32 idx; - word32 length; - WOLFSSL_STACK* node; - WOLFSSL_STACK* last = NULL; - - if (ctx == NULL || chain == NULL) { - chain = NULL; - return WOLFSSL_FAILURE; - } - if (ctx->x509Chain != NULL) { - *chain = ctx->x509Chain; - return WOLFSSL_SUCCESS; - } - - /* If there are no chains then success! */ - *chain = NULL; - if (ctx->certChain == NULL || ctx->certChain->length == 0) { - return WOLFSSL_SUCCESS; - } - - /* Create a new stack of WOLFSSL_X509 object from chain buffer. */ - for (idx = 0; idx < ctx->certChain->length; ) { - node = wolfSSL_sk_X509_new_null(); - if (node == NULL) - return WOLFSSL_FAILURE; - node->next = NULL; - - /* 3 byte length | X509 DER data */ - ato24(ctx->certChain->buffer + idx, &length); - idx += 3; - - /* Create a new X509 from DER encoded data. */ - node->data.x509 = wolfSSL_X509_d2i_ex(NULL, - ctx->certChain->buffer + idx, length, ctx->heap); - if (node->data.x509 == NULL) { - XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL); - /* Return as much of the chain as we created. */ - ctx->x509Chain = *chain; - return WOLFSSL_FAILURE; - } - idx += length; - - /* Add object to the end of the stack. */ - if (last == NULL) { - node->num = 1; - *chain = node; - } - else { - (*chain)->num++; - last->next = node; - } - - last = node; - } - - ctx->x509Chain = *chain; - - return WOLFSSL_SUCCESS; -} - -int wolfSSL_CTX_get_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb* cb) -{ - if (ctx == NULL || ctx->cm == NULL || cb == NULL) - return WOLFSSL_FAILURE; - -#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ - || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)) - if (ctx->cm->ocsp_stapling == NULL) - return WOLFSSL_FAILURE; - - *cb = ctx->cm->ocsp_stapling->statusCb; -#else - (void)cb; - *cb = NULL; -#endif - - return WOLFSSL_SUCCESS; - -} - -int wolfSSL_CTX_set_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb cb) -{ - if (ctx == NULL || ctx->cm == NULL) - return WOLFSSL_FAILURE; - -#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ - || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)) - /* Ensure stapling is on for callback to be used. */ - wolfSSL_CTX_EnableOCSPStapling(ctx); - - if (ctx->cm->ocsp_stapling == NULL) - return WOLFSSL_FAILURE; - - ctx->cm->ocsp_stapling->statusCb = cb; -#else - (void)cb; -#endif - - return WOLFSSL_SUCCESS; -} - -int wolfSSL_CTX_get0_chain_certs(WOLFSSL_CTX *ctx, - WOLF_STACK_OF(WOLFSSL_X509) **sk) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get0_chain_certs"); - if (ctx == NULL || sk == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } - - /* This function should return ctx->x509Chain if it is populated, otherwise - it should be populated from ctx->certChain. This matches the behavior of - wolfSSL_CTX_get_extra_chain_certs, so it is used directly. */ - return wolfSSL_CTX_get_extra_chain_certs(ctx, sk); -} - -#ifdef KEEP_OUR_CERT -int wolfSSL_get0_chain_certs(WOLFSSL *ssl, - WOLF_STACK_OF(WOLFSSL_X509) **sk) -{ - WOLFSSL_ENTER("wolfSSL_get0_chain_certs"); - if (ssl == NULL || sk == NULL) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } - *sk = ssl->ourCertChain; - return WOLFSSL_SUCCESS; -} -#endif - -WOLF_STACK_OF(WOLFSSL_STRING)* wolfSSL_sk_WOLFSSL_STRING_new(void) -{ - WOLF_STACK_OF(WOLFSSL_STRING)* ret = wolfSSL_sk_new_node(NULL); - - if (ret) { - ret->type = STACK_TYPE_STRING; - } - - return ret; -} - -void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s) -{ - WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free"); - - if (s != NULL) - XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); -} - -void wolfSSL_sk_WOLFSSL_STRING_free(WOLF_STACK_OF(WOLFSSL_STRING)* sk) -{ - WOLFSSL_STACK* tmp; - WOLFSSL_ENTER("wolfSSL_sk_WOLFSSL_STRING_free"); - - if (sk == NULL) - return; - - /* parse through stack freeing each node */ - while (sk) { - tmp = sk->next; - XFREE(sk->data.string, NULL, DYNAMIC_TYPE_OPENSSL); - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); - sk = tmp; - } -} - -WOLFSSL_STRING wolfSSL_sk_WOLFSSL_STRING_value(WOLF_STACK_OF(WOLFSSL_STRING)* strings, - int idx) -{ - for (; idx > 0 && strings != NULL; idx--) - strings = strings->next; - if (strings == NULL) - return NULL; - return strings->data.string; -} - -int wolfSSL_sk_WOLFSSL_STRING_num(WOLF_STACK_OF(WOLFSSL_STRING)* strings) -{ - if (strings) - return (int)strings->num; - return 0; -} - -#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */ - -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_QUIC) -#ifdef HAVE_ALPN -void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data, - unsigned int *len) -{ - word16 nameLen; - - if (ssl != NULL && data != NULL && len != NULL) { - TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen); - *len = nameLen; - } -} - -int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen, - const unsigned char *in, unsigned int inLen, - const unsigned char *clientNames, - unsigned int clientLen) -{ - unsigned int i, j; - byte lenIn, lenClient; - - if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL) - return OPENSSL_NPN_UNSUPPORTED; - - for (i = 0; i < inLen; i += lenIn) { - lenIn = in[i++]; - for (j = 0; j < clientLen; j += lenClient) { - lenClient = clientNames[j++]; - - if (lenIn != lenClient) - continue; - - if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) { - *out = (unsigned char *)(in + i); - *outLen = lenIn; - return OPENSSL_NPN_NEGOTIATED; - } - } - } - - *out = (unsigned char *)clientNames + 1; - *outLen = clientNames[0]; - return OPENSSL_NPN_NO_OVERLAP; -} - -void wolfSSL_set_alpn_select_cb(WOLFSSL *ssl, - int (*cb) (WOLFSSL *ssl, - const unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), void *arg) -{ - if (ssl != NULL) { - ssl->alpnSelect = cb; - ssl->alpnSelectArg = arg; - } -} - -void wolfSSL_CTX_set_alpn_select_cb(WOLFSSL_CTX *ctx, - int (*cb) (WOLFSSL *ssl, - const unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), void *arg) -{ - if (ctx != NULL) { - ctx->alpnSelect = cb; - ctx->alpnSelectArg = arg; - } -} - -void wolfSSL_CTX_set_next_protos_advertised_cb(WOLFSSL_CTX *s, - int (*cb) (WOLFSSL *ssl, - const unsigned char - **out, - unsigned int *outlen, - void *arg), void *arg) -{ - (void)s; - (void)cb; - (void)arg; - WOLFSSL_STUB("wolfSSL_CTX_set_next_protos_advertised_cb"); -} - -void wolfSSL_CTX_set_next_proto_select_cb(WOLFSSL_CTX *s, - int (*cb) (WOLFSSL *ssl, - unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), void *arg) -{ - (void)s; - (void)cb; - (void)arg; - WOLFSSL_STUB("wolfSSL_CTX_set_next_proto_select_cb"); -} - -void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s, const unsigned char **data, - unsigned *len) -{ - (void)s; - (void)data; - (void)len; - WOLFSSL_STUB("wolfSSL_get0_next_proto_negotiated"); -} -#endif /* HAVE_ALPN */ - -#endif /* WOLFSSL_NGINX / WOLFSSL_HAPROXY */ - -#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) -int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id) -{ - if (curve_id >= WOLFSSL_FFDHE_START) { - /* DH parameters are never disabled. */ - return 0; - } - if (curve_id > WOLFSSL_ECC_MAX_AVAIL) { - WOLFSSL_MSG("Curve id out of supported range"); - /* Disabled if not in valid range. */ - return 1; - } - if (curve_id >= 32) { - /* 0 is for invalid and 1-14 aren't used otherwise. */ - return (ssl->disabledCurves & (1U << (curve_id - 32))) != 0; - } - return (ssl->disabledCurves & (1U << curve_id)) != 0; -} - -#if (defined(HAVE_ECC) || \ - defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) -static int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names) -{ - int idx, start = 0, len, i, ret = WOLFSSL_FAILURE; - word16 curve; - word32 disabled; - char name[MAX_CURVE_NAME_SZ]; - byte groups_len = 0; -#ifdef WOLFSSL_SMALL_STACK - void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL; - int *groups; -#else - int groups[WOLFSSL_MAX_GROUP_COUNT]; -#endif - -#ifdef WOLFSSL_SMALL_STACK - groups = (int*)XMALLOC(sizeof(int)*WOLFSSL_MAX_GROUP_COUNT, - heap, DYNAMIC_TYPE_TMP_BUFFER); - if (groups == NULL) { - ret = MEMORY_E; - goto leave; - } -#endif - - for (idx = 1; names[idx-1] != '\0'; idx++) { - if (names[idx] != ':' && names[idx] != '\0') - continue; - - len = idx - start; - if (len > MAX_CURVE_NAME_SZ - 1) - goto leave; - - XMEMCPY(name, names + start, len); - name[len++] = 0; - - /* Use XSTRNCMP to avoid valgrind error. */ - if ((XSTRNCMP(name, "prime256v1", len) == 0) || - (XSTRNCMP(name, "secp256r1", len) == 0) || - (XSTRNCMP(name, "P-256", len) == 0)) - { - curve = WOLFSSL_ECC_SECP256R1; - } - else if ((XSTRNCMP(name, "secp384r1", len) == 0) || - (XSTRNCMP(name, "P-384", len) == 0)) - { - curve = WOLFSSL_ECC_SECP384R1; - } - else if ((XSTRNCMP(name, "secp521r1", len) == 0) || - (XSTRNCMP(name, "P-521", len) == 0)) - { - curve = WOLFSSL_ECC_SECP521R1; - } - #ifdef WOLFSSL_SM2 - else if ((XSTRNCMP(name, "sm2p256v1", len) == 0) || - (XSTRNCMP(name, "SM2", len) == 0)) - { - curve = WOLFSSL_ECC_SM2P256V1; - } - #endif - #ifdef HAVE_CURVE25519 - else if (XSTRNCMP(name, "X25519", len) == 0) - { - curve = WOLFSSL_ECC_X25519; - } - #endif - #ifdef HAVE_CURVE448 - else if (XSTRNCMP(name, "X448", len) == 0) - { - curve = WOLFSSL_ECC_X448; - } - #endif - else { - #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) - int nret; - const ecc_set_type *eccSet; - - nret = wc_ecc_get_curve_idx_from_name(name); - if (nret < 0) { - WOLFSSL_MSG("Could not find name in set"); - goto leave; - } - - eccSet = wc_ecc_get_curve_params(ret); - if (eccSet == NULL) { - WOLFSSL_MSG("NULL set returned"); - goto leave; - } - - curve = GetCurveByOID(eccSet->oidSum); - #else - WOLFSSL_MSG("API not present to search farther using name"); - goto leave; - #endif - } - - if (curve >= WOLFSSL_ECC_MAX_AVAIL) { - WOLFSSL_MSG("curve value is not supported"); - goto leave; - } - - for (i = 0; i < groups_len; ++i) { - if (groups[i] == curve) { - /* silently drop duplicates */ - break; - } - } - if (i >= groups_len) { - if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) { - WOLFSSL_MSG_EX("setting %d or more supported " - "curves is not permitted", groups_len); - goto leave; - } - groups[groups_len++] = (int)curve; - } - - start = idx + 1; - } - - /* Disable all curves so that only the ones the user wants are enabled. */ - disabled = 0xFFFFFFFFUL; - for (i = 0; i < groups_len; ++i) { - /* Switch the bit to off and therefore is enabled. */ - curve = (word16)groups[i]; - if (curve >= 32) { - /* 0 is for invalid and 1-14 aren't used otherwise. */ - disabled &= ~(1U << (curve - 32)); - } - else { - disabled &= ~(1U << curve); - } - #ifdef HAVE_SUPPORTED_CURVES - #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_OLD_SET_CURVES_LIST) - /* using the wolfSSL API to set the groups, this will populate - * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS. - * The order in (ssl|ctx)->groups will then be respected - * when TLSX_KEY_SHARE needs to be established */ - if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len) - != WOLFSSL_SUCCESS) - || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len) - != WOLFSSL_SUCCESS)) { - WOLFSSL_MSG("Unable to set supported curve"); - goto leave; - } - #elif !defined(NO_WOLFSSL_CLIENT) - /* set the supported curve so client TLS extension contains only the - * desired curves */ - if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS) - || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve) - != WOLFSSL_SUCCESS)) { - WOLFSSL_MSG("Unable to set supported curve"); - goto leave; - } - #endif - #endif /* HAVE_SUPPORTED_CURVES */ - } - - if (ssl) - ssl->disabledCurves = disabled; - else - ctx->disabledCurves = disabled; - ret = WOLFSSL_SUCCESS; - -leave: -#ifdef WOLFSSL_SMALL_STACK - if (groups) - XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif - return ret; -} - -int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names) -{ - if (ctx == NULL || names == NULL) { - WOLFSSL_MSG("ctx or names was NULL"); - return WOLFSSL_FAILURE; - } - return set_curves_list(NULL, ctx, names); -} - -int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names) -{ - if (ssl == NULL || names == NULL) { - WOLFSSL_MSG("ssl or names was NULL"); - return WOLFSSL_FAILURE; - } - return set_curves_list(ssl, NULL, names); -} -#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */ -#endif /* OPENSSL_EXTRA || HAVE_CURL */ - -#ifdef OPENSSL_EXTRA -/* Sets a callback for when sending and receiving protocol messages. - * This callback is copied to all WOLFSSL objects created from the ctx. - * - * ctx WOLFSSL_CTX structure to set callback in - * cb callback to use - * - * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case - */ -int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback"); - if (ctx == NULL) { - WOLFSSL_MSG("Null ctx passed in"); - return WOLFSSL_FAILURE; - } - - ctx->protoMsgCb = cb; - return WOLFSSL_SUCCESS; -} - - -/* Sets a callback for when sending and receiving protocol messages. - * - * ssl WOLFSSL structure to set callback in - * cb callback to use - * - * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case - */ -int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb) -{ - WOLFSSL_ENTER("wolfSSL_set_msg_callback"); - - if (ssl == NULL) { - return WOLFSSL_FAILURE; - } - - if (cb != NULL) { - ssl->toInfoOn = 1; - } - - ssl->protoMsgCb = cb; - return WOLFSSL_SUCCESS; -} - - -/* set the user argument to pass to the msg callback when called - * return WOLFSSL_SUCCESS on success */ -int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg"); - if (ctx == NULL) { - WOLFSSL_MSG("Null WOLFSSL_CTX passed in"); - return WOLFSSL_FAILURE; - } - - ctx->protoMsgCtx = arg; - return WOLFSSL_SUCCESS; -} - - -int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg) -{ - WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg"); - if (ssl == NULL) - return WOLFSSL_FAILURE; - - ssl->protoMsgCtx = arg; - return WOLFSSL_SUCCESS; -} - -void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file, int line) -{ - void *ret; - (void)file; - (void)line; - - if (data == NULL || siz >= INT_MAX) - return NULL; - - ret = OPENSSL_malloc(siz); - if (ret == NULL) { - return NULL; - } - return XMEMCPY(ret, data, siz); -} - -void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len) -{ - if (ptr) - ForceZero(ptr, (word32)len); -} - -int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p, - unsigned int p_len) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_alpn_protos"); - if (ctx == NULL) - return BAD_FUNC_ARG; - if (ctx->alpn_cli_protos != NULL) { - XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL); - } - - ctx->alpn_cli_protos = (const unsigned char*)XMALLOC(p_len, - ctx->heap, DYNAMIC_TYPE_OPENSSL); - if (ctx->alpn_cli_protos == NULL) { -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 1; -#else - return WOLFSSL_FAILURE; -#endif - } - XMEMCPY((void*)ctx->alpn_cli_protos, p, p_len); - ctx->alpn_cli_protos_len = p_len; - -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 0; -#else - return WOLFSSL_SUCCESS; -#endif -} - - -#ifdef HAVE_ALPN -#ifndef NO_BIO -/* Sets the ALPN extension protos - * - * example format is - * unsigned char p[] = { - * 8, 'h', 't', 't', 'p', '/', '1', '.', '1' - * }; - * - * returns WOLFSSL_SUCCESS on success */ -int wolfSSL_set_alpn_protos(WOLFSSL* ssl, - const unsigned char* p, unsigned int p_len) -{ - WOLFSSL_BIO* bio; - char* pt = NULL; - - unsigned int sz; - unsigned int idx = 0; - int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH; - WOLFSSL_ENTER("wolfSSL_set_alpn_protos"); - - if (ssl == NULL || p_len <= 1) { -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 1; -#else - return WOLFSSL_FAILURE; -#endif - } - - bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); - if (bio == NULL) { -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 1; -#else - return WOLFSSL_FAILURE; -#endif - } - - /* convert into comma separated list */ - while (idx < p_len - 1) { - unsigned int i; - - sz = p[idx++]; - if (idx + sz > p_len) { - WOLFSSL_MSG("Bad list format"); - wolfSSL_BIO_free(bio); - #if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 1; - #else - return WOLFSSL_FAILURE; - #endif - } - if (sz > 0) { - for (i = 0; i < sz; i++) { - wolfSSL_BIO_write(bio, &p[idx++], 1); - } - if (idx < p_len - 1) - wolfSSL_BIO_write(bio, ",", 1); - } - } - wolfSSL_BIO_write(bio, "\0", 1); - - /* clears out all current ALPN extensions set */ - TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap); - - if ((sz = wolfSSL_BIO_get_mem_data(bio, &pt)) > 0) { - wolfSSL_UseALPN(ssl, pt, sz, (byte) alpn_opt); - } - wolfSSL_BIO_free(bio); -#if defined(WOLFSSL_ERROR_CODE_OPENSSL) - /* 0 on success in OpenSSL, non-0 on failure in OpenSSL - * the function reverses the return value convention. - */ - return 0; -#else - return WOLFSSL_SUCCESS; -#endif -} -#endif /* !NO_BIO */ -#endif /* HAVE_ALPN */ -#endif /* OPENSSL_EXTRA */ - -#if defined(OPENSSL_EXTRA) - -#ifndef NO_BIO -#define WOLFSSL_BIO_INCLUDED -#include "src/bio.c" -#endif - -word32 nid2oid(int nid, int grp) -{ - /* get OID type */ - switch (grp) { - /* oidHashType */ - case oidHashType: - switch (nid) { - #ifdef WOLFSSL_MD2 - case NID_md2: - return MD2h; - #endif - #ifndef NO_MD5 - case NID_md5: - return MD5h; - #endif - #ifndef NO_SHA - case NID_sha1: - return SHAh; - #endif - case NID_sha224: - return SHA224h; - #ifndef NO_SHA256 - case NID_sha256: - return SHA256h; - #endif - #ifdef WOLFSSL_SHA384 - case NID_sha384: - return SHA384h; - #endif - #ifdef WOLFSSL_SHA512 - case NID_sha512: - return SHA512h; - #endif - #ifndef WOLFSSL_NOSHA3_224 - case NID_sha3_224: - return SHA3_224h; - #endif - #ifndef WOLFSSL_NOSHA3_256 - case NID_sha3_256: - return SHA3_256h; - #endif - #ifndef WOLFSSL_NOSHA3_384 - case NID_sha3_384: - return SHA3_384h; - #endif - #ifndef WOLFSSL_NOSHA3_512 - case NID_sha3_512: - return SHA3_512h; - #endif - } - break; - - /* oidSigType */ - case oidSigType: - switch (nid) { - #ifndef NO_DSA - case NID_dsaWithSHA1: - return CTC_SHAwDSA; - case NID_dsa_with_SHA256: - return CTC_SHA256wDSA; - #endif /* NO_DSA */ - #ifndef NO_RSA - case NID_md2WithRSAEncryption: - return CTC_MD2wRSA; - case NID_md5WithRSAEncryption: - return CTC_MD5wRSA; - case NID_sha1WithRSAEncryption: - return CTC_SHAwRSA; - case NID_sha224WithRSAEncryption: - return CTC_SHA224wRSA; - case NID_sha256WithRSAEncryption: - return CTC_SHA256wRSA; - case NID_sha384WithRSAEncryption: - return CTC_SHA384wRSA; - case NID_sha512WithRSAEncryption: - return CTC_SHA512wRSA; - #ifdef WOLFSSL_SHA3 - case NID_RSA_SHA3_224: - return CTC_SHA3_224wRSA; - case NID_RSA_SHA3_256: - return CTC_SHA3_256wRSA; - case NID_RSA_SHA3_384: - return CTC_SHA3_384wRSA; - case NID_RSA_SHA3_512: - return CTC_SHA3_512wRSA; - #endif - #endif /* NO_RSA */ - #ifdef HAVE_ECC - case NID_ecdsa_with_SHA1: - return CTC_SHAwECDSA; - case NID_ecdsa_with_SHA224: - return CTC_SHA224wECDSA; - case NID_ecdsa_with_SHA256: - return CTC_SHA256wECDSA; - case NID_ecdsa_with_SHA384: - return CTC_SHA384wECDSA; - case NID_ecdsa_with_SHA512: - return CTC_SHA512wECDSA; - #ifdef WOLFSSL_SHA3 - case NID_ecdsa_with_SHA3_224: - return CTC_SHA3_224wECDSA; - case NID_ecdsa_with_SHA3_256: - return CTC_SHA3_256wECDSA; - case NID_ecdsa_with_SHA3_384: - return CTC_SHA3_384wECDSA; - case NID_ecdsa_with_SHA3_512: - return CTC_SHA3_512wECDSA; - #endif - #endif /* HAVE_ECC */ - } - break; - - /* oidKeyType */ - case oidKeyType: - switch (nid) { - #ifndef NO_DSA - case NID_dsa: - return DSAk; - #endif /* NO_DSA */ - #ifndef NO_RSA - case NID_rsaEncryption: - return RSAk; - #endif /* NO_RSA */ - #ifdef HAVE_ECC - case NID_X9_62_id_ecPublicKey: - return ECDSAk; - #endif /* HAVE_ECC */ - } - break; - - - #ifdef HAVE_ECC - case oidCurveType: - switch (nid) { - case NID_X9_62_prime192v1: - return ECC_SECP192R1_OID; - case NID_X9_62_prime192v2: - return ECC_PRIME192V2_OID; - case NID_X9_62_prime192v3: - return ECC_PRIME192V3_OID; - case NID_X9_62_prime239v1: - return ECC_PRIME239V1_OID; - case NID_X9_62_prime239v2: - return ECC_PRIME239V2_OID; - case NID_X9_62_prime239v3: - return ECC_PRIME239V3_OID; - case NID_X9_62_prime256v1: - return ECC_SECP256R1_OID; - case NID_secp112r1: - return ECC_SECP112R1_OID; - case NID_secp112r2: - return ECC_SECP112R2_OID; - case NID_secp128r1: - return ECC_SECP128R1_OID; - case NID_secp128r2: - return ECC_SECP128R2_OID; - case NID_secp160r1: - return ECC_SECP160R1_OID; - case NID_secp160r2: - return ECC_SECP160R2_OID; - case NID_secp224r1: - return ECC_SECP224R1_OID; - case NID_secp384r1: - return ECC_SECP384R1_OID; - case NID_secp521r1: - return ECC_SECP521R1_OID; - case NID_secp160k1: - return ECC_SECP160K1_OID; - case NID_secp192k1: - return ECC_SECP192K1_OID; - case NID_secp224k1: - return ECC_SECP224K1_OID; - case NID_secp256k1: - return ECC_SECP256K1_OID; - case NID_brainpoolP160r1: - return ECC_BRAINPOOLP160R1_OID; - case NID_brainpoolP192r1: - return ECC_BRAINPOOLP192R1_OID; - case NID_brainpoolP224r1: - return ECC_BRAINPOOLP224R1_OID; - case NID_brainpoolP256r1: - return ECC_BRAINPOOLP256R1_OID; - case NID_brainpoolP320r1: - return ECC_BRAINPOOLP320R1_OID; - case NID_brainpoolP384r1: - return ECC_BRAINPOOLP384R1_OID; - case NID_brainpoolP512r1: - return ECC_BRAINPOOLP512R1_OID; - } - break; - #endif /* HAVE_ECC */ - - /* oidBlkType */ - case oidBlkType: - switch (nid) { - #ifdef WOLFSSL_AES_128 - case AES128CBCb: - return AES128CBCb; - #endif - #ifdef WOLFSSL_AES_192 - case AES192CBCb: - return AES192CBCb; - #endif - #ifdef WOLFSSL_AES_256 - case AES256CBCb: - return AES256CBCb; - #endif - #ifndef NO_DES3 - case NID_des: - return DESb; - case NID_des3: - return DES3b; - #endif - } - break; - - #ifdef HAVE_OCSP - case oidOcspType: - switch (nid) { - case NID_id_pkix_OCSP_basic: - return OCSP_BASIC_OID; - case OCSP_NONCE_OID: - return OCSP_NONCE_OID; - } - break; - #endif /* HAVE_OCSP */ - - /* oidCertExtType */ - case oidCertExtType: - switch (nid) { - case NID_basic_constraints: - return BASIC_CA_OID; - case NID_subject_alt_name: - return ALT_NAMES_OID; - case NID_crl_distribution_points: - return CRL_DIST_OID; - case NID_info_access: - return AUTH_INFO_OID; - case NID_authority_key_identifier: - return AUTH_KEY_OID; - case NID_subject_key_identifier: - return SUBJ_KEY_OID; - case NID_inhibit_any_policy: - return INHIBIT_ANY_OID; - case NID_key_usage: - return KEY_USAGE_OID; - case NID_name_constraints: - return NAME_CONS_OID; - case NID_certificate_policies: - return CERT_POLICY_OID; - case NID_ext_key_usage: - return EXT_KEY_USAGE_OID; - } - break; - - /* oidCertAuthInfoType */ - case oidCertAuthInfoType: - switch (nid) { - case NID_ad_OCSP: - return AIA_OCSP_OID; - case NID_ad_ca_issuers: - return AIA_CA_ISSUER_OID; - } - break; - - /* oidCertPolicyType */ - case oidCertPolicyType: - switch (nid) { - case NID_any_policy: - return CP_ANY_OID; - } - break; - - /* oidCertAltNameType */ - case oidCertAltNameType: - switch (nid) { - case NID_hw_name_oid: - return HW_NAME_OID; - } - break; - - /* oidCertKeyUseType */ - case oidCertKeyUseType: - switch (nid) { - case NID_anyExtendedKeyUsage: - return EKU_ANY_OID; - case EKU_SERVER_AUTH_OID: - return EKU_SERVER_AUTH_OID; - case EKU_CLIENT_AUTH_OID: - return EKU_CLIENT_AUTH_OID; - case EKU_OCSP_SIGN_OID: - return EKU_OCSP_SIGN_OID; - } - break; - - /* oidKdfType */ - case oidKdfType: - switch (nid) { - case PBKDF2_OID: - return PBKDF2_OID; - } - break; - - /* oidPBEType */ - case oidPBEType: - switch (nid) { - case PBE_SHA1_RC4_128: - return PBE_SHA1_RC4_128; - case PBE_SHA1_DES: - return PBE_SHA1_DES; - case PBE_SHA1_DES3: - return PBE_SHA1_DES3; - } - break; - - /* oidKeyWrapType */ - case oidKeyWrapType: - switch (nid) { - #ifdef WOLFSSL_AES_128 - case AES128_WRAP: - return AES128_WRAP; - #endif - #ifdef WOLFSSL_AES_192 - case AES192_WRAP: - return AES192_WRAP; - #endif - #ifdef WOLFSSL_AES_256 - case AES256_WRAP: - return AES256_WRAP; - #endif - } - break; - - /* oidCmsKeyAgreeType */ - case oidCmsKeyAgreeType: - switch (nid) { - #ifndef NO_SHA - case dhSinglePass_stdDH_sha1kdf_scheme: - return dhSinglePass_stdDH_sha1kdf_scheme; - #endif - #ifdef WOLFSSL_SHA224 - case dhSinglePass_stdDH_sha224kdf_scheme: - return dhSinglePass_stdDH_sha224kdf_scheme; - #endif - #ifndef NO_SHA256 - case dhSinglePass_stdDH_sha256kdf_scheme: - return dhSinglePass_stdDH_sha256kdf_scheme; - #endif - #ifdef WOLFSSL_SHA384 - case dhSinglePass_stdDH_sha384kdf_scheme: - return dhSinglePass_stdDH_sha384kdf_scheme; - #endif - #ifdef WOLFSSL_SHA512 - case dhSinglePass_stdDH_sha512kdf_scheme: - return dhSinglePass_stdDH_sha512kdf_scheme; - #endif - } - break; - - /* oidCmsKeyAgreeType */ - #ifdef WOLFSSL_CERT_REQ - case oidCsrAttrType: - switch (nid) { - case NID_pkcs9_contentType: - return PKCS9_CONTENT_TYPE_OID; - case NID_pkcs9_challengePassword: - return CHALLENGE_PASSWORD_OID; - case NID_serialNumber: - return SERIAL_NUMBER_OID; - case NID_userId: - return USER_ID_OID; - case NID_surname: - return SURNAME_OID; - } - break; - #endif - - default: - WOLFSSL_MSG("NID not in table"); - /* MSVC warns without the cast */ - return (word32)-1; - } - - /* MSVC warns without the cast */ - return (word32)-1; -} - -int oid2nid(word32 oid, int grp) -{ - size_t i; - /* get OID type */ - switch (grp) { - /* oidHashType */ - case oidHashType: - switch (oid) { - #ifdef WOLFSSL_MD2 - case MD2h: - return NID_md2; - #endif - #ifndef NO_MD5 - case MD5h: - return NID_md5; - #endif - #ifndef NO_SHA - case SHAh: - return NID_sha1; - #endif - case SHA224h: - return NID_sha224; - #ifndef NO_SHA256 - case SHA256h: - return NID_sha256; - #endif - #ifdef WOLFSSL_SHA384 - case SHA384h: - return NID_sha384; - #endif - #ifdef WOLFSSL_SHA512 - case SHA512h: - return NID_sha512; - #endif - } - break; - - /* oidSigType */ - case oidSigType: - switch (oid) { - #ifndef NO_DSA - case CTC_SHAwDSA: - return NID_dsaWithSHA1; - case CTC_SHA256wDSA: - return NID_dsa_with_SHA256; - #endif /* NO_DSA */ - #ifndef NO_RSA - case CTC_MD2wRSA: - return NID_md2WithRSAEncryption; - case CTC_MD5wRSA: - return NID_md5WithRSAEncryption; - case CTC_SHAwRSA: - return NID_sha1WithRSAEncryption; - case CTC_SHA224wRSA: - return NID_sha224WithRSAEncryption; - case CTC_SHA256wRSA: - return NID_sha256WithRSAEncryption; - case CTC_SHA384wRSA: - return NID_sha384WithRSAEncryption; - case CTC_SHA512wRSA: - return NID_sha512WithRSAEncryption; - #ifdef WOLFSSL_SHA3 - case CTC_SHA3_224wRSA: - return NID_RSA_SHA3_224; - case CTC_SHA3_256wRSA: - return NID_RSA_SHA3_256; - case CTC_SHA3_384wRSA: - return NID_RSA_SHA3_384; - case CTC_SHA3_512wRSA: - return NID_RSA_SHA3_512; - #endif - #ifdef WC_RSA_PSS - case CTC_RSASSAPSS: - return NID_rsassaPss; - #endif - #endif /* NO_RSA */ - #ifdef HAVE_ECC - case CTC_SHAwECDSA: - return NID_ecdsa_with_SHA1; - case CTC_SHA224wECDSA: - return NID_ecdsa_with_SHA224; - case CTC_SHA256wECDSA: - return NID_ecdsa_with_SHA256; - case CTC_SHA384wECDSA: - return NID_ecdsa_with_SHA384; - case CTC_SHA512wECDSA: - return NID_ecdsa_with_SHA512; - #ifdef WOLFSSL_SHA3 - case CTC_SHA3_224wECDSA: - return NID_ecdsa_with_SHA3_224; - case CTC_SHA3_256wECDSA: - return NID_ecdsa_with_SHA3_256; - case CTC_SHA3_384wECDSA: - return NID_ecdsa_with_SHA3_384; - case CTC_SHA3_512wECDSA: - return NID_ecdsa_with_SHA3_512; - #endif - #endif /* HAVE_ECC */ - } - break; - - /* oidKeyType */ - case oidKeyType: - switch (oid) { - #ifndef NO_DSA - case DSAk: - return NID_dsa; - #endif /* NO_DSA */ - #ifndef NO_RSA - case RSAk: - return NID_rsaEncryption; - #ifdef WC_RSA_PSS - case RSAPSSk: - return NID_rsassaPss; - #endif - #endif /* NO_RSA */ - #ifdef HAVE_ECC - case ECDSAk: - return NID_X9_62_id_ecPublicKey; - #endif /* HAVE_ECC */ - } - break; - - - #ifdef HAVE_ECC - case oidCurveType: - switch (oid) { - case ECC_SECP192R1_OID: - return NID_X9_62_prime192v1; - case ECC_PRIME192V2_OID: - return NID_X9_62_prime192v2; - case ECC_PRIME192V3_OID: - return NID_X9_62_prime192v3; - case ECC_PRIME239V1_OID: - return NID_X9_62_prime239v1; - case ECC_PRIME239V2_OID: - return NID_X9_62_prime239v2; - case ECC_PRIME239V3_OID: - return NID_X9_62_prime239v3; - case ECC_SECP256R1_OID: - return NID_X9_62_prime256v1; - case ECC_SECP112R1_OID: - return NID_secp112r1; - case ECC_SECP112R2_OID: - return NID_secp112r2; - case ECC_SECP128R1_OID: - return NID_secp128r1; - case ECC_SECP128R2_OID: - return NID_secp128r2; - case ECC_SECP160R1_OID: - return NID_secp160r1; - case ECC_SECP160R2_OID: - return NID_secp160r2; - case ECC_SECP224R1_OID: - return NID_secp224r1; - case ECC_SECP384R1_OID: - return NID_secp384r1; - case ECC_SECP521R1_OID: - return NID_secp521r1; - case ECC_SECP160K1_OID: - return NID_secp160k1; - case ECC_SECP192K1_OID: - return NID_secp192k1; - case ECC_SECP224K1_OID: - return NID_secp224k1; - case ECC_SECP256K1_OID: - return NID_secp256k1; - case ECC_BRAINPOOLP160R1_OID: - return NID_brainpoolP160r1; - case ECC_BRAINPOOLP192R1_OID: - return NID_brainpoolP192r1; - case ECC_BRAINPOOLP224R1_OID: - return NID_brainpoolP224r1; - case ECC_BRAINPOOLP256R1_OID: - return NID_brainpoolP256r1; - case ECC_BRAINPOOLP320R1_OID: - return NID_brainpoolP320r1; - case ECC_BRAINPOOLP384R1_OID: - return NID_brainpoolP384r1; - case ECC_BRAINPOOLP512R1_OID: - return NID_brainpoolP512r1; - } - break; - #endif /* HAVE_ECC */ - - /* oidBlkType */ - case oidBlkType: - switch (oid) { - #ifdef WOLFSSL_AES_128 - case AES128CBCb: - return AES128CBCb; - #endif - #ifdef WOLFSSL_AES_192 - case AES192CBCb: - return AES192CBCb; - #endif - #ifdef WOLFSSL_AES_256 - case AES256CBCb: - return AES256CBCb; - #endif - #ifndef NO_DES3 - case DESb: - return NID_des; - case DES3b: - return NID_des3; - #endif - } - break; - - #ifdef HAVE_OCSP - case oidOcspType: - switch (oid) { - case OCSP_BASIC_OID: - return NID_id_pkix_OCSP_basic; - case OCSP_NONCE_OID: - return OCSP_NONCE_OID; - } - break; - #endif /* HAVE_OCSP */ +#if defined(OPENSSL_EXTRA) - /* oidCertExtType */ - case oidCertExtType: - switch (oid) { - case BASIC_CA_OID: - return NID_basic_constraints; - case ALT_NAMES_OID: - return NID_subject_alt_name; - case CRL_DIST_OID: - return NID_crl_distribution_points; - case AUTH_INFO_OID: - return NID_info_access; - case AUTH_KEY_OID: - return NID_authority_key_identifier; - case SUBJ_KEY_OID: - return NID_subject_key_identifier; - case INHIBIT_ANY_OID: - return NID_inhibit_any_policy; - case KEY_USAGE_OID: - return NID_key_usage; - case NAME_CONS_OID: - return NID_name_constraints; - case CERT_POLICY_OID: - return NID_certificate_policies; - case EXT_KEY_USAGE_OID: - return NID_ext_key_usage; - } - break; +int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size) +{ + if (!a || !b) + return 0; + return ConstantCompare((const byte*)a, (const byte*)b, (int)size); +} - /* oidCertAuthInfoType */ - case oidCertAuthInfoType: - switch (oid) { - case AIA_OCSP_OID: - return NID_ad_OCSP; - case AIA_CA_ISSUER_OID: - return NID_ad_ca_issuers; - } - break; +unsigned long wolfSSL_ERR_peek_last_error(void) +{ + WOLFSSL_ENTER("wolfSSL_ERR_peek_last_error"); - /* oidCertPolicyType */ - case oidCertPolicyType: - switch (oid) { - case CP_ANY_OID: - return NID_any_policy; - } - break; +#ifdef WOLFSSL_HAVE_ERROR_QUEUE + { + int ret; - /* oidCertAltNameType */ - case oidCertAltNameType: - switch (oid) { - case HW_NAME_OID: - return NID_hw_name_oid; - } - break; + if ((ret = wc_PeekErrorNode(-1, NULL, NULL, NULL)) < 0) { + WOLFSSL_MSG("Issue peeking at error node in queue"); + return 0; + } + if (ret == -ASN_NO_PEM_HEADER) + return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; + #if defined(WOLFSSL_PYTHON) + if (ret == ASN1_R_HEADER_TOO_LONG) + return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; + #endif + return (unsigned long)ret; + } +#else + return (unsigned long)(0 - NOT_COMPILED_IN); +#endif +} - /* oidCertKeyUseType */ - case oidCertKeyUseType: - switch (oid) { - case EKU_ANY_OID: - return NID_anyExtendedKeyUsage; - case EKU_SERVER_AUTH_OID: - return EKU_SERVER_AUTH_OID; - case EKU_CLIENT_AUTH_OID: - return EKU_CLIENT_AUTH_OID; - case EKU_OCSP_SIGN_OID: - return EKU_OCSP_SIGN_OID; - } - break; +#endif /* OPENSSL_EXTRA */ - /* oidKdfType */ - case oidKdfType: - switch (oid) { - case PBKDF2_OID: - return PBKDF2_OID; - } - break; +int wolfSSL_version(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_version"); + if (ssl->version.major == SSLv3_MAJOR) { + switch (ssl->version.minor) { + case SSLv3_MINOR : + return SSL3_VERSION; + case TLSv1_MINOR : + return TLS1_VERSION; + case TLSv1_1_MINOR : + return TLS1_1_VERSION; + case TLSv1_2_MINOR : + return TLS1_2_VERSION; + case TLSv1_3_MINOR : + return TLS1_3_VERSION; + default: + return WOLFSSL_FAILURE; + } + } + else if (ssl->version.major == DTLS_MAJOR) { + switch (ssl->version.minor) { + case DTLS_MINOR : + return DTLS1_VERSION; + case DTLSv1_2_MINOR : + return DTLS1_2_VERSION; + case DTLSv1_3_MINOR: + return DTLS1_3_VERSION; + default: + return WOLFSSL_FAILURE; + } + } + return WOLFSSL_FAILURE; +} - /* oidPBEType */ - case oidPBEType: - switch (oid) { - case PBE_SHA1_RC4_128: - return PBE_SHA1_RC4_128; - case PBE_SHA1_DES: - return PBE_SHA1_DES; - case PBE_SHA1_DES3: - return PBE_SHA1_DES3; - } - break; +WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_SSL_CTX"); + return ssl->ctx; +} - /* oidKeyWrapType */ - case oidKeyWrapType: - switch (oid) { - #ifdef WOLFSSL_AES_128 - case AES128_WRAP: - return AES128_WRAP; - #endif - #ifdef WOLFSSL_AES_192 - case AES192_WRAP: - return AES192_WRAP; - #endif - #ifdef WOLFSSL_AES_256 - case AES256_WRAP: - return AES256_WRAP; - #endif - } - break; +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && defined(HAVE_STUNNEL)) \ + || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) - /* oidCmsKeyAgreeType */ - case oidCmsKeyAgreeType: - switch (oid) { - #ifndef NO_SHA - case dhSinglePass_stdDH_sha1kdf_scheme: - return dhSinglePass_stdDH_sha1kdf_scheme; - #endif - #ifdef WOLFSSL_SHA224 - case dhSinglePass_stdDH_sha224kdf_scheme: - return dhSinglePass_stdDH_sha224kdf_scheme; - #endif - #ifndef NO_SHA256 - case dhSinglePass_stdDH_sha256kdf_scheme: - return dhSinglePass_stdDH_sha256kdf_scheme; - #endif - #ifdef WOLFSSL_SHA384 - case dhSinglePass_stdDH_sha384kdf_scheme: - return dhSinglePass_stdDH_sha384kdf_scheme; - #endif - #ifdef WOLFSSL_SHA512 - case dhSinglePass_stdDH_sha512kdf_scheme: - return dhSinglePass_stdDH_sha512kdf_scheme; - #endif - } - break; +/* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */ +int wolfSSL_get_verify_mode(const WOLFSSL* ssl) { + int mode = 0; + WOLFSSL_ENTER("wolfSSL_get_verify_mode"); -#ifdef WOLFSSL_CERT_REQ - case oidCsrAttrType: - switch (oid) { - case PKCS9_CONTENT_TYPE_OID: - return NID_pkcs9_contentType; - case CHALLENGE_PASSWORD_OID: - return NID_pkcs9_challengePassword; - case SERIAL_NUMBER_OID: - return NID_serialNumber; - case USER_ID_OID: - return NID_userId; - } - break; + if (!ssl) { + return WOLFSSL_FAILURE; + } + + if (ssl->options.verifyNone) { + mode = WOLFSSL_VERIFY_NONE; + } + else { + if (ssl->options.verifyPeer) { + mode |= WOLFSSL_VERIFY_PEER; + } + if (ssl->options.failNoCert) { + mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT; + } + if (ssl->options.failNoCertxPSK) { + mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK; + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) + if (ssl->options.verifyPostHandshake) { + mode |= WOLFSSL_VERIFY_POST_HANDSHAKE; + } #endif + } - default: - WOLFSSL_MSG("OID not in table"); + WOLFSSL_LEAVE("wolfSSL_get_verify_mode", mode); + return mode; +} + +int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx) +{ + int mode = 0; + WOLFSSL_ENTER("wolfSSL_CTX_get_verify_mode"); + + if (!ctx) { + return WOLFSSL_FAILURE; } - /* If not found in above switch then try the table */ - for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) { - if (wolfssl_object_info[i].id == (int)oid) { - return wolfssl_object_info[i].nid; + + if (ctx->verifyNone) { + mode = WOLFSSL_VERIFY_NONE; + } + else { + if (ctx->verifyPeer) { + mode |= WOLFSSL_VERIFY_PEER; + } + if (ctx->failNoCert) { + mode |= WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT; + } + if (ctx->failNoCertxPSK) { + mode |= WOLFSSL_VERIFY_FAIL_EXCEPT_PSK; + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) + if (ctx->verifyPostHandshake) { + mode |= WOLFSSL_VERIFY_POST_HANDSHAKE; } +#endif } - return -1; + WOLFSSL_LEAVE("wolfSSL_CTX_get_verify_mode", mode); + return mode; +} + +#endif + +#ifdef WOLFSSL_JNI + +int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr) +{ + WOLFSSL_ENTER("wolfSSL_set_jobject"); + if (ssl != NULL) + { + ssl->jObjectRef = objPtr; + return WOLFSSL_SUCCESS; + } + return WOLFSSL_FAILURE; } -/* frees all nodes in the current threads error queue - * - * id thread id. ERR_remove_state is depreciated and id is ignored. The - * current threads queue will be free'd. - */ -void wolfSSL_ERR_remove_state(unsigned long id) +void* wolfSSL_get_jobject(WOLFSSL* ssl) { - WOLFSSL_ENTER("wolfSSL_ERR_remove_state"); - (void)id; - if (wc_ERR_remove_state() != 0) { - WOLFSSL_MSG("Error with removing the state"); - } + WOLFSSL_ENTER("wolfSSL_get_jobject"); + if (ssl != NULL) + return ssl->jObjectRef; + return NULL; } -#endif /* OPENSSL_EXTRA */ +#endif /* WOLFSSL_JNI */ -#ifdef OPENSSL_ALL -#if !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) -int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY* pkey, - const WOLFSSL_EVP_CIPHER* enc, - char* passwd, int passwdSz, - wc_pem_password_cb* cb, void* ctx) +#ifdef WOLFSSL_ASYNC_CRYPT +int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents, + WOLF_EVENT_FLAG flags, int* eventCount) { - int ret = 0; - char password[NAME_SZ]; - byte* key = NULL; - word32 keySz; - byte* pem = NULL; - int pemSz = 0; - int type = PKCS8_PRIVATEKEY_TYPE; - const byte* curveOid; - word32 oidSz; - - if (bio == NULL || pkey == NULL) - return -1; - - keySz = pkey->pkey_sz + 128; - key = (byte*)XMALLOC(keySz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (key == NULL) - ret = MEMORY_E; - - if (ret == 0 && enc != NULL && passwd == NULL) { - passwdSz = cb(password, sizeof(password), 1, ctx); - if (passwdSz < 0) - ret = WOLFSSL_FAILURE; - passwd = password; + if (ctx == NULL) { + return BAD_FUNC_ARG; } - if (ret == 0 && enc != NULL) { - WC_RNG rng; - ret = wc_InitRng(&rng); - if (ret == 0) { - int encAlgId = 0; - #ifndef NO_DES3 - if (enc == EVP_DES_CBC) - encAlgId = DESb; - else if (enc == EVP_DES_EDE3_CBC) - encAlgId = DES3b; - else - #endif - #if !defined(NO_AES) && defined(HAVE_AES_CBC) - #ifdef WOLFSSL_AES_256 - if (enc == EVP_AES_256_CBC) - encAlgId = AES256CBCb; - else - #endif - #endif - ret = -1; - if (ret == 0) { - ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz, key, - &keySz, passwd, passwdSz, PKCS5, PBES2, - encAlgId, NULL, 0, WC_PKCS12_ITT_DEFAULT, - &rng, NULL); - if (ret > 0) { - keySz = ret; - ret = 0; - } - } - wc_FreeRng(&rng); - } - type = PKCS8_ENC_PRIVATEKEY_TYPE; - } - if (ret == 0 && enc == NULL) { - int algId; - type = PKCS8_PRIVATEKEY_TYPE; - #ifdef HAVE_ECC - if (pkey->type == EVP_PKEY_EC) { - algId = ECDSAk; - ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid, - &oidSz); - } - else - #endif - { - algId = RSAk; - curveOid = NULL; - oidSz = 0; - } + return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL, + events, maxEvents, flags, eventCount); +} - #ifdef HAVE_ECC - if (ret >= 0) - #endif - { - ret = wc_CreatePKCS8Key(key, &keySz, (byte*)pkey->pkey.ptr, - pkey->pkey_sz, algId, curveOid, oidSz); - keySz = ret; - } - } +int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags) +{ + int ret, eventCount = 0; + WOLF_EVENT* events[1]; - if (password == passwd) - XMEMSET(password, 0, passwdSz); + if (ssl == NULL) { + return BAD_FUNC_ARG; + } - if (ret >= 0) { - pemSz = 2 * keySz + 2 * 64; - pem = (byte*)XMALLOC(pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (pem == NULL) - ret = MEMORY_E; + ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl, + events, sizeof(events)/sizeof(events[0]), flags, &eventCount); + if (ret == 0) { + ret = eventCount; } - if (ret >= 0) - ret = wc_DerToPemEx(key, keySz, pem, pemSz, NULL, type); + return ret; +} +#endif /* WOLFSSL_ASYNC_CRYPT */ - if (key != NULL) - XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#ifdef OPENSSL_EXTRA - if (ret >= 0) { - if (wolfSSL_BIO_write(bio, pem, ret) != ret) - ret = -1; - } +static int peek_ignore_err(int err) +{ + switch(err) { + case -WC_NO_ERR_TRACE(WANT_READ): + case -WC_NO_ERR_TRACE(WANT_WRITE): + case -WC_NO_ERR_TRACE(ZERO_RETURN): + case -WOLFSSL_ERROR_ZERO_RETURN: + case -WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E): + case -WC_NO_ERR_TRACE(SOCKET_ERROR_E): + return 1; + default: + return 0; + } +} - if (pem != NULL) - XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); +unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line, + const char **data, int *flags) +{ + unsigned long err; - return ret < 0 ? 0 : ret; + WOLFSSL_ENTER("wolfSSL_ERR_peek_error_line_data"); + err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err); + if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) + return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; +#ifdef OPENSSL_ALL + /* PARSE_ERROR is returned if an HTTP request is detected. */ + else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR)) + return (ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST; +#endif +#if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) + else if (err == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) + return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; +#endif + return err; } +#endif -#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) -int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey, - const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, - wc_pem_password_cb* cb, void* ctx) +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + +#if !defined(WOLFSSL_USER_IO) +/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280 + * example input would be "127.0.0.1" and the returned value would be 7F000001 + */ +WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa) { - int ret = WOLFSSL_SUCCESS; - BIO *b; + int ipaSz = WOLFSSL_IP4_ADDR_LEN; + char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */ + int af = WOLFSSL_IP4; + WOLFSSL_ASN1_STRING *ret = NULL; - WOLFSSL_ENTER("wolfSSL_PEM_write_PKCS8PrivateKey"); + if (ipa == NULL) + return NULL; - b = wolfSSL_BIO_new_fp(f, BIO_NOCLOSE); - if (b == NULL) { - ret = WOLFSSL_FAILURE; + if (XSTRSTR(ipa, ":") != NULL) { + af = WOLFSSL_IP6; + ipaSz = WOLFSSL_IP6_ADDR_LEN; } - if (ret == WOLFSSL_SUCCESS) { - ret = wolfSSL_PEM_write_bio_PKCS8PrivateKey(b, pkey, enc, passwd, - passwdSz, cb, ctx); + + buf[WOLFSSL_IP6_ADDR_LEN] = '\0'; + if (XINET_PTON(af, ipa, (void*)buf) != 1) { + WOLFSSL_MSG("Error parsing IP address"); + return NULL; } - wolfSSL_BIO_free(b); + ret = wolfSSL_ASN1_STRING_new(); + if (ret != NULL) { + if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error setting the string"); + wolfSSL_ASN1_STRING_free(ret); + ret = NULL; + } + } return ret; } -#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */ +#endif /* !WOLFSSL_USER_IO */ -static int bio_get_data(WOLFSSL_BIO* bio, byte** data) +/* Is the specified cipher suite a fake one used an an extension proxy? */ +static WC_INLINE int SCSV_Check(byte suite0, byte suite) { - int ret = 0; - byte* mem = NULL; + (void)suite0; + (void)suite; +#ifdef HAVE_RENEGOTIATION_INDICATION + if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) + return 1; +#endif + return 0; +} - ret = wolfSSL_BIO_get_len(bio); - if (ret > 0) { - mem = (byte*)XMALLOC(ret, bio->heap, DYNAMIC_TYPE_OPENSSL); - if (mem == NULL) { - WOLFSSL_MSG("Memory error"); - ret = MEMORY_E; - } - if (ret >= 0) { - if ((ret = wolfSSL_BIO_read(bio, mem, ret)) <= 0) { - XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL); - ret = MEMORY_E; - mem = NULL; +static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0, + byte suite) +{ + const CipherSuiteInfo* cipher_names = GetCipherNames(); + int cipherSz = GetCipherNamesSize(); + int i; + for (i = 0; i < cipherSz; i++) + if (cipher_names[i].cipherSuite0 == suite0 && + cipher_names[i].cipherSuite == suite) + break; + if (i == cipherSz) + return 1; + /* Check min version */ + if (cipher_names[i].minor < ssl->options.minDowngrade) { + if (ssl->options.minDowngrade <= TLSv1_2_MINOR && + cipher_names[i].minor >= TLSv1_MINOR) + /* 1.0 ciphersuites are in general available in 1.1 and + * 1.1 ciphersuites are in general available in 1.2 */ + return 0; + return 1; + } + /* Check max version */ + switch (cipher_names[i].minor) { + case SSLv3_MINOR : + return ssl->options.mask & WOLFSSL_OP_NO_SSLv3; + case TLSv1_MINOR : + return ssl->options.mask & WOLFSSL_OP_NO_TLSv1; + case TLSv1_1_MINOR : + return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1; + case TLSv1_2_MINOR : + return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2; + case TLSv1_3_MINOR : + return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3; + default: + WOLFSSL_MSG("Unrecognized minor version"); + return 1; + } +} + +/* returns a pointer to internal cipher suite list. Should not be free'd by + * caller. + */ +WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl) +{ + WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL; + const Suites* suites; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + const CipherSuiteInfo* cipher_names = GetCipherNames(); + int cipherSz = GetCipherNamesSize(); +#endif + + WOLFSSL_ENTER("wolfSSL_get_ciphers_compat"); + if (ssl == NULL) + return NULL; + + suites = WOLFSSL_SUITES(ssl); + if (suites == NULL) + return NULL; + + /* check if stack needs populated */ + if (ssl->suitesStack == NULL) { + int i; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + int j; + + /* higher priority of cipher suite will be on top of stack */ + for (i = suites->suiteSz - 2; i >=0; i-=2) { +#else + for (i = 0; i < suites->suiteSz; i+=2) { +#endif + WOLFSSL_STACK* add; + + /* A couple of suites are placeholders for special options, + * skip those. */ + if (SCSV_Check(suites->suites[i], suites->suites[i+1]) + || sslCipherMinMaxCheck(ssl, suites->suites[i], + suites->suites[i+1])) { + continue; + } + + add = wolfSSL_sk_new_node(ssl->heap); + if (add != NULL) { + add->type = STACK_TYPE_CIPHER; + add->data.cipher.cipherSuite0 = suites->suites[i]; + add->data.cipher.cipherSuite = suites->suites[i+1]; + add->data.cipher.ssl = ssl; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + for (j = 0; j < cipherSz; j++) { + if (cipher_names[j].cipherSuite0 == + add->data.cipher.cipherSuite0 && + cipher_names[j].cipherSuite == + add->data.cipher.cipherSuite) { + add->data.cipher.offset = (unsigned long)j; + break; + } + } +#endif + #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) + /* in_stack is checked in wolfSSL_CIPHER_description */ + add->data.cipher.in_stack = 1; + #endif + + add->next = ret; + if (ret != NULL) { + add->num = ret->num + 1; + } + else { + add->num = 1; + } + ret = add; } } + ((WOLFSSL*)ssl)->suitesStack = ret; } - - *data = mem; - - return ret; + return ssl->suitesStack; } +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ -/* DER data is PKCS#8 encrypted. */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_PKCS8PrivateKey_bio(WOLFSSL_BIO* bio, - WOLFSSL_EVP_PKEY** pkey, - wc_pem_password_cb* cb, - void* ctx) +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ + defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK) +long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx) { - int ret; - byte* der; - int len; - byte* p; - word32 algId; - WOLFSSL_EVP_PKEY* key; + WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout"); - if ((len = bio_get_data(bio, &der)) < 0) - return NULL; + if (ctx == NULL) + return 0; - if (cb != NULL) { - char password[NAME_SZ]; - int passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx); - if (passwordSz < 0) { - XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); - return NULL; - } - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("wolfSSL_d2i_PKCS8PrivateKey_bio password", password, - passwordSz); - #endif + return ctx->timeout; +} - ret = ToTraditionalEnc(der, len, password, passwordSz, &algId); - if (ret < 0) { - XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); - return NULL; - } - ForceZero(password, passwordSz); - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(password, passwordSz); - #endif - } +/* returns the time in seconds of the current timeout */ +long wolfSSL_get_timeout(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_timeout"); - p = der; - key = wolfSSL_d2i_PrivateKey_EVP(pkey, &p, len); - XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); - return key; + if (ssl == NULL) + return 0; + return ssl->timeout; } +#endif -#endif /* !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */ +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ + || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) -/* Detect which type of key it is before decoding. */ -WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, - const unsigned char** pp, - long length) +#ifdef HAVE_ECC +int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh) { - int ret; - WOLFSSL_EVP_PKEY* key = NULL; - const byte* der = *pp; - word32 idx = 0; - int len = 0; - int cnt = 0; - word32 algId; - word32 keyLen = (word32)length; + WOLFSSL_ENTER("wolfSSL_SSL_CTX_set_tmp_ecdh"); - /* Take off PKCS#8 wrapper if found. */ - if ((len = ToTraditionalInline_ex(der, &idx, keyLen, &algId)) >= 0) { - der += idx; - keyLen = len; - } - idx = 0; - len = 0; + if (ctx == NULL || ecdh == NULL) + return BAD_FUNC_ARG; - /* Use the number of elements in the outer sequence to determine key type. - */ - ret = GetSequence(der, &idx, &len, keyLen); - if (ret >= 0) { - word32 end = idx + len; - while (ret >= 0 && idx < end) { - /* Skip type */ - idx++; - /* Get length and skip over - keeping count */ - len = 0; - ret = GetLength(der, &idx, &len, keyLen); - if (ret >= 0) { - if (idx + len > end) - ret = ASN_PARSE_E; - else { - idx += len; - cnt++; - } - } - } - } + ctx->ecdhCurveOID = (word32)ecdh->group->curve_oid; - if (ret >= 0) { - int type; - /* ECC includes version, private[, curve][, public key] */ - if (cnt >= 2 && cnt <= 4) - type = EVP_PKEY_EC; - else - type = EVP_PKEY_RSA; + return WOLFSSL_SUCCESS; +} +#endif +#ifndef NO_BIO +BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) +{ + WOLFSSL_ENTER("wolfSSL_SSL_get_rbio"); + /* Nginx sets the buffer size if the read BIO is different to write BIO. + * The setting buffer size doesn't do anything so return NULL for both. + */ + if (s == NULL) + return NULL; - key = wolfSSL_d2i_PrivateKey(type, pkey, &der, keyLen); - *pp = der; - } + return s->biord; +} +BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s) +{ + WOLFSSL_ENTER("wolfSSL_SSL_get_wbio"); + (void)s; + /* Nginx sets the buffer size if the read BIO is different to write BIO. + * The setting buffer size doesn't do anything so return NULL for both. + */ + if (s == NULL) + return NULL; - return key; + return s->biowr; } -#endif /* OPENSSL_ALL */ +#endif /* !NO_BIO */ -#ifdef WOLFSSL_STATIC_EPHEMERAL -int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr) +int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s) { - int ret; - word32 idx = 0; - DerBuffer* der = NULL; + WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal"); + if (s == NULL) + return WOLFSSL_FAILURE; - if (ssl == NULL || ssl->ctx == NULL || keyPtr == NULL) { - return BAD_FUNC_ARG; + if (s->options.side == WOLFSSL_CLIENT_END) { + #ifndef NO_WOLFSSL_CLIENT + return wolfSSL_connect(s); + #else + WOLFSSL_MSG("Client not compiled in"); + return WOLFSSL_FAILURE; + #endif } -#ifndef SINGLE_THREADED - if (!ssl->ctx->staticKELockInit) { - return BUFFER_E; /* no keys set */ - } - ret = wc_LockMutex(&ssl->ctx->staticKELock); - if (ret != 0) { - return ret; - } +#ifndef NO_WOLFSSL_SERVER + return wolfSSL_accept(s); +#else + WOLFSSL_MSG("Server not compiled in"); + return WOLFSSL_FAILURE; #endif +} - ret = BUFFER_E; /* set default error */ - switch (keyAlgo) { - #ifndef NO_DH - case WC_PK_TYPE_DH: - if (ssl != NULL) - der = ssl->staticKE.dhKey; - if (der == NULL) - der = ssl->ctx->staticKE.dhKey; - if (der != NULL) { - DhKey* key = (DhKey*)keyPtr; - WOLFSSL_MSG("Using static DH key"); - ret = wc_DhKeyDecode(der->buffer, &idx, key, der->length); - } - break; - #endif - #ifdef HAVE_ECC - case WC_PK_TYPE_ECDH: - if (ssl != NULL) - der = ssl->staticKE.ecKey; - if (der == NULL) - der = ssl->ctx->staticKE.ecKey; - if (der != NULL) { - ecc_key* key = (ecc_key*)keyPtr; - WOLFSSL_MSG("Using static ECDH key"); - ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key, der->length); - } - break; - #endif - #ifdef HAVE_CURVE25519 - case WC_PK_TYPE_CURVE25519: - if (ssl != NULL) - der = ssl->staticKE.x25519Key; - if (der == NULL) - der = ssl->ctx->staticKE.x25519Key; - if (der != NULL) { - curve25519_key* key = (curve25519_key*)keyPtr; - WOLFSSL_MSG("Using static X25519 key"); - ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key, - der->length); - } - break; - #endif - #ifdef HAVE_CURVE448 - case WC_PK_TYPE_CURVE448: - if (ssl != NULL) - der = ssl->staticKE.x448Key; - if (der == NULL) - der = ssl->ctx->staticKE.x448Key; - if (der != NULL) { - curve448_key* key = (curve448_key*)keyPtr; - WOLFSSL_MSG("Using static X448 key"); - ret = wc_Curve448PrivateKeyDecode(der->buffer, &idx, key, - der->length); - } - break; - #endif - default: - /* not supported */ - ret = NOT_COMPILED_IN; - break; +int wolfSSL_SSL_do_handshake(WOLFSSL *s) +{ + WOLFSSL_ENTER("wolfSSL_SSL_do_handshake"); +#ifdef WOLFSSL_QUIC + if (WOLFSSL_IS_QUIC(s)) { + return wolfSSL_quic_do_handshake(s); } +#endif + return wolfSSL_SSL_do_handshake_internal(s); +} -#ifndef SINGLE_THREADED - wc_UnLockMutex(&ssl->ctx->staticKELock); +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L +int wolfSSL_SSL_in_init(const WOLFSSL *ssl) +#else +int wolfSSL_SSL_in_init(WOLFSSL *ssl) #endif - return ret; +{ + WOLFSSL_ENTER("wolfSSL_SSL_in_init"); + + return !wolfSSL_is_init_finished(ssl); } -static int SetStaticEphemeralKey(WOLFSSL_CTX* ctx, - StaticKeyExchangeInfo_t* staticKE, int keyAlgo, const char* key, - unsigned int keySz, int format, void* heap) +int wolfSSL_SSL_in_before(const WOLFSSL *ssl) { - int ret = 0; - DerBuffer* der = NULL; - byte* keyBuf = NULL; -#ifndef NO_FILESYSTEM - const char* keyFile = NULL; -#endif + WOLFSSL_ENTER("wolfSSL_SSL_in_before"); - /* allow empty key to free buffer */ - if (staticKE == NULL || (key == NULL && keySz > 0)) { - return BAD_FUNC_ARG; + if (ssl == NULL) + return WOLFSSL_FAILURE; + + return ssl->options.handShakeState == NULL_STATE; +} + +int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init"); + + if (ssl == NULL) + return WOLFSSL_FAILURE; + + if (ssl->options.side == WOLFSSL_CLIENT_END) { + return ssl->options.connectState > CONNECT_BEGIN && + ssl->options.connectState < SECOND_REPLY_DONE; } - WOLFSSL_ENTER("SetStaticEphemeralKey"); + return ssl->options.acceptState > ACCEPT_BEGIN && + ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE; +} - /* if just free'ing key then skip loading */ - if (key != NULL) { - #ifndef NO_FILESYSTEM - /* load file from filesystem */ - if (key != NULL && keySz == 0) { - size_t keyBufSz = 0; - keyFile = (const char*)key; - ret = wc_FileLoad(keyFile, &keyBuf, &keyBufSz, heap); - if (ret != 0) { - return ret; - } - keySz = (unsigned int)keyBufSz; - } - else - #endif - { - /* use as key buffer directly */ - keyBuf = (byte*)key; - } +#if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) +/* Expected return values from implementations of OpenSSL ticket key callback. + */ +#define TICKET_KEY_CB_RET_FAILURE (-1) +#define TICKET_KEY_CB_RET_NOT_FOUND 0 +#define TICKET_KEY_CB_RET_OK 1 +#define TICKET_KEY_CB_RET_RENEW 2 - if (format == WOLFSSL_FILETYPE_PEM) { - #ifdef WOLFSSL_PEM_TO_DER - int keyFormat = 0; - ret = PemToDer(keyBuf, keySz, PRIVATEKEY_TYPE, &der, - heap, NULL, &keyFormat); - /* auto detect key type */ - if (ret == 0 && keyAlgo == WC_PK_TYPE_NONE) { - if (keyFormat == ECDSAk) - keyAlgo = WC_PK_TYPE_ECDH; - else if (keyFormat == X25519k) - keyAlgo = WC_PK_TYPE_CURVE25519; - else - keyAlgo = WC_PK_TYPE_DH; - } - #else - ret = NOT_COMPILED_IN; - #endif - } - else { - /* Detect PK type (if required) */ - #ifdef HAVE_ECC - if (keyAlgo == WC_PK_TYPE_NONE) { - word32 idx = 0; - ecc_key eccKey; - ret = wc_ecc_init_ex(&eccKey, heap, INVALID_DEVID); - if (ret == 0) { - ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &eccKey, keySz); - if (ret == 0) - keyAlgo = WC_PK_TYPE_ECDH; - wc_ecc_free(&eccKey); - } - } - #endif - #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) - if (keyAlgo == WC_PK_TYPE_NONE) { - word32 idx = 0; - DhKey dhKey; - ret = wc_InitDhKey_ex(&dhKey, heap, INVALID_DEVID); - if (ret == 0) { - ret = wc_DhKeyDecode(keyBuf, &idx, &dhKey, keySz); - if (ret == 0) - keyAlgo = WC_PK_TYPE_DH; - wc_FreeDhKey(&dhKey); - } - } - #endif - #ifdef HAVE_CURVE25519 - if (keyAlgo == WC_PK_TYPE_NONE) { - word32 idx = 0; - curve25519_key x25519Key; - ret = wc_curve25519_init_ex(&x25519Key, heap, INVALID_DEVID); - if (ret == 0) { - ret = wc_Curve25519PrivateKeyDecode(keyBuf, &idx, &x25519Key, - keySz); - if (ret == 0) - keyAlgo = WC_PK_TYPE_CURVE25519; - wc_curve25519_free(&x25519Key); - } - } - #endif - #ifdef HAVE_CURVE448 - if (keyAlgo == WC_PK_TYPE_NONE) { - word32 idx = 0; - curve448_key x448Key; - ret = wc_curve448_init(&x448Key); - if (ret == 0) { - ret = wc_Curve448PrivateKeyDecode(keyBuf, &idx, &x448Key, - keySz); - if (ret == 0) - keyAlgo = WC_PK_TYPE_CURVE448; - wc_curve448_free(&x448Key); - } - } - #endif +/* Implementation of session ticket encryption/decryption using OpenSSL + * callback to initialize the cipher and HMAC. + * + * ssl The SSL/TLS object. + * keyName The key name - used to identify the key to be used. + * iv The IV to use. + * mac The MAC of the encrypted data. + * enc Encrypt ticket. + * encTicket The ticket data. + * encTicketLen The length of the ticket data. + * encLen The encrypted/decrypted ticket length - output length. + * ctx Ignored. Application specific data. + * returns WOLFSSL_TICKET_RET_OK to indicate success, + * WOLFSSL_TICKET_RET_CREATE if a new ticket is required and + * WOLFSSL_TICKET_RET_FATAL on error. + */ +static int wolfSSL_TicketKeyCb(WOLFSSL* ssl, + unsigned char keyName[WOLFSSL_TICKET_NAME_SZ], + unsigned char iv[WOLFSSL_TICKET_IV_SZ], + unsigned char mac[WOLFSSL_TICKET_MAC_SZ], + int enc, unsigned char* encTicket, + int encTicketLen, int* encLen, void* ctx) +{ + byte digest[WC_MAX_DIGEST_SIZE]; +#ifdef WOLFSSL_SMALL_STACK + WOLFSSL_EVP_CIPHER_CTX *evpCtx; +#else + WOLFSSL_EVP_CIPHER_CTX evpCtx[1]; +#endif + WOLFSSL_HMAC_CTX hmacCtx; + unsigned int mdSz = 0; + int len = 0; + int ret = WOLFSSL_TICKET_RET_FATAL; + int res; + int totalSz = 0; - if (keyAlgo != WC_PK_TYPE_NONE) { - ret = AllocDer(&der, keySz, PRIVATEKEY_TYPE, heap); - if (ret == 0) { - XMEMCPY(der->buffer, keyBuf, keySz); - } - } - } + (void)ctx; + + WOLFSSL_ENTER("wolfSSL_TicketKeyCb"); + + if (ssl == NULL || ssl->ctx == NULL || ssl->ctx->ticketEncWrapCb == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_TICKET_RET_FATAL; } -#ifndef NO_FILESYSTEM - /* done with keyFile buffer */ - if (keyFile && keyBuf) { - XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); +#ifdef WOLFSSL_SMALL_STACK + evpCtx = (WOLFSSL_EVP_CIPHER_CTX *)XMALLOC(sizeof(*evpCtx), ssl->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (evpCtx == NULL) { + WOLFSSL_MSG("out of memory"); + return WOLFSSL_TICKET_RET_FATAL; } #endif -#ifndef SINGLE_THREADED - if (ret == 0 && !ctx->staticKELockInit) { - ret = wc_InitMutex(&ctx->staticKELock); - if (ret == 0) { - ctx->staticKELockInit = 1; - } - } + /* Initialize the cipher and HMAC. */ + wolfSSL_EVP_CIPHER_CTX_init(evpCtx); + if (wolfSSL_HMAC_CTX_Init(&hmacCtx) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init error"); +#ifdef WOLFSSL_SMALL_STACK + XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - if (ret == 0 - #ifndef SINGLE_THREADED - && (ret = wc_LockMutex(&ctx->staticKELock)) == 0 - #endif - ) { - switch (keyAlgo) { - #ifndef NO_DH - case WC_PK_TYPE_DH: - FreeDer(&staticKE->dhKey); - staticKE->dhKey = der; der = NULL; - break; - #endif - #ifdef HAVE_ECC - case WC_PK_TYPE_ECDH: - FreeDer(&staticKE->ecKey); - staticKE->ecKey = der; der = NULL; - break; - #endif - #ifdef HAVE_CURVE25519 - case WC_PK_TYPE_CURVE25519: - FreeDer(&staticKE->x25519Key); - staticKE->x25519Key = der; der = NULL; - break; - #endif - #ifdef HAVE_CURVE448 - case WC_PK_TYPE_CURVE448: - FreeDer(&staticKE->x448Key); - staticKE->x448Key = der; der = NULL; - break; - #endif - default: - /* not supported */ - ret = NOT_COMPILED_IN; - break; - } + return WOLFSSL_TICKET_RET_FATAL; + } + res = ssl->ctx->ticketEncWrapCb(ssl, keyName, + iv, evpCtx, &hmacCtx, enc); + if (res != TICKET_KEY_CB_RET_OK && res != TICKET_KEY_CB_RET_RENEW) { + WOLFSSL_MSG("Ticket callback error"); + ret = WOLFSSL_TICKET_RET_FATAL; + goto end; + } - #ifndef SINGLE_THREADED - wc_UnLockMutex(&ctx->staticKELock); - #endif + if (wolfSSL_HMAC_size(&hmacCtx) > WOLFSSL_TICKET_MAC_SZ) { + WOLFSSL_MSG("Ticket cipher MAC size error"); + goto end; } - if (ret != 0) { - FreeDer(&der); + if (enc) + { + /* Encrypt in place. */ + if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len, + encTicket, encTicketLen)) + goto end; + totalSz = len; + if (totalSz > *encLen) + goto end; + if (!wolfSSL_EVP_EncryptFinal(evpCtx, &encTicket[len], &len)) + goto end; + /* Total length of encrypted data. */ + totalSz += len; + if (totalSz > *encLen) + goto end; + + /* HMAC the encrypted data into the parameter 'mac'. */ + if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, totalSz)) + goto end; + if (!wolfSSL_HMAC_Final(&hmacCtx, mac, &mdSz)) + goto end; } + else + { + /* HMAC the encrypted data and compare it to the passed in data. */ + if (!wolfSSL_HMAC_Update(&hmacCtx, encTicket, encTicketLen)) + goto end; + if (!wolfSSL_HMAC_Final(&hmacCtx, digest, &mdSz)) + goto end; + if (XMEMCMP(mac, digest, mdSz) != 0) + goto end; - (void)ctx; /* not used for single threaded */ + /* Decrypt the ticket data in place. */ + if (!wolfSSL_EVP_CipherUpdate(evpCtx, encTicket, &len, + encTicket, encTicketLen)) + goto end; + totalSz = len; + if (totalSz > encTicketLen) + goto end; + if (!wolfSSL_EVP_DecryptFinal(evpCtx, &encTicket[len], &len)) + goto end; + /* Total length of decrypted data. */ + totalSz += len; + if (totalSz > encTicketLen) + goto end; + } + *encLen = totalSz; - WOLFSSL_LEAVE("SetStaticEphemeralKey", ret); + if (res == TICKET_KEY_CB_RET_RENEW && !IsAtLeastTLSv1_3(ssl->version) + && !enc) + ret = WOLFSSL_TICKET_RET_CREATE; + else + ret = WOLFSSL_TICKET_RET_OK; +end: + + (void)wc_HmacFree(&hmacCtx.hmac); + (void)wolfSSL_EVP_CIPHER_CTX_cleanup(evpCtx); + +#ifdef WOLFSSL_SMALL_STACK + XFREE(evpCtx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif return ret; } -int wolfSSL_CTX_set_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo, - const char* key, unsigned int keySz, int format) +/* Set the callback to use when encrypting/decrypting tickets. + * + * ctx The SSL/TLS context object. + * cb The OpenSSL session ticket callback. + * returns WOLFSSL_SUCCESS to indicate success. + */ +int wolfSSL_CTX_set_tlsext_ticket_key_cb(WOLFSSL_CTX *ctx, ticketCompatCb cb) { - if (ctx == NULL) { - return BAD_FUNC_ARG; - } - return SetStaticEphemeralKey(ctx, &ctx->staticKE, keyAlgo, - key, keySz, format, ctx->heap); + + /* Set the ticket encryption callback to be a wrapper around OpenSSL + * callback. + */ + ctx->ticketEncCb = wolfSSL_TicketKeyCb; + ctx->ticketEncWrapCb = cb; + + return WOLFSSL_SUCCESS; } -int wolfSSL_set_ephemeral_key(WOLFSSL* ssl, int keyAlgo, - const char* key, unsigned int keySz, int format) + +#endif /* HAVE_SESSION_TICKET */ + +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || + OPENSSL_EXTRA || HAVE_LIGHTY */ + +#if defined(HAVE_SESSION_TICKET) && !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \ + !defined(NO_WOLFSSL_SERVER) +/* Serialize the session ticket encryption keys. + * + * @param [in] ctx SSL/TLS context object. + * @param [in] keys Buffer to hold session ticket keys. + * @param [in] keylen Length of buffer. + * @return WOLFSSL_SUCCESS on success. + * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the + * correct length. + */ +long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx, + unsigned char *keys, int keylen) { - if (ssl == NULL || ssl->ctx == NULL) { - return BAD_FUNC_ARG; + if (ctx == NULL || keys == NULL) { + return WOLFSSL_FAILURE; } - return SetStaticEphemeralKey(ssl->ctx, &ssl->staticKE, keyAlgo, - key, keySz, format, ssl->heap); + if (keylen != WOLFSSL_TICKET_KEYS_SZ) { + return WOLFSSL_FAILURE; + } + + XMEMCPY(keys, ctx->ticketKeyCtx.name, WOLFSSL_TICKET_NAME_SZ); + keys += WOLFSSL_TICKET_NAME_SZ; + XMEMCPY(keys, ctx->ticketKeyCtx.key[0], WOLFSSL_TICKET_KEY_SZ); + keys += WOLFSSL_TICKET_KEY_SZ; + XMEMCPY(keys, ctx->ticketKeyCtx.key[1], WOLFSSL_TICKET_KEY_SZ); + keys += WOLFSSL_TICKET_KEY_SZ; + c32toa(ctx->ticketKeyCtx.expirary[0], keys); + keys += OPAQUE32_LEN; + c32toa(ctx->ticketKeyCtx.expirary[1], keys); + + return WOLFSSL_SUCCESS; } -static int GetStaticEphemeralKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - int keyAlgo, const unsigned char** key, unsigned int* keySz) +/* Deserialize the session ticket encryption keys. + * + * @param [in] ctx SSL/TLS context object. + * @param [in] keys Session ticket keys. + * @param [in] keylen Length of data. + * @return WOLFSSL_SUCCESS on success. + * @return WOLFSSL_FAILURE when ctx is NULL, keys is NULL or keylen is not the + * correct length. + */ +long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx, + const void *keys_vp, int keylen) { - int ret = 0; - DerBuffer* der = NULL; + const byte* keys = (const byte*)keys_vp; + if (ctx == NULL || keys == NULL) { + return WOLFSSL_FAILURE; + } + if (keylen != WOLFSSL_TICKET_KEYS_SZ) { + return WOLFSSL_FAILURE; + } - if (key) *key = NULL; - if (keySz) *keySz = 0; + XMEMCPY(ctx->ticketKeyCtx.name, keys, WOLFSSL_TICKET_NAME_SZ); + keys += WOLFSSL_TICKET_NAME_SZ; + XMEMCPY(ctx->ticketKeyCtx.key[0], keys, WOLFSSL_TICKET_KEY_SZ); + keys += WOLFSSL_TICKET_KEY_SZ; + XMEMCPY(ctx->ticketKeyCtx.key[1], keys, WOLFSSL_TICKET_KEY_SZ); + keys += WOLFSSL_TICKET_KEY_SZ; + ato32(keys, &ctx->ticketKeyCtx.expirary[0]); + keys += OPAQUE32_LEN; + ato32(keys, &ctx->ticketKeyCtx.expirary[1]); -#ifndef SINGLE_THREADED - if (ctx->staticKELockInit && - (ret = wc_LockMutex(&ctx->staticKELock)) != 0) { - return ret; - } + return WOLFSSL_SUCCESS; +} #endif - switch (keyAlgo) { - #ifndef NO_DH - case WC_PK_TYPE_DH: - if (ssl != NULL) - der = ssl->staticKE.dhKey; - if (der == NULL) - der = ctx->staticKE.dhKey; - break; - #endif - #ifdef HAVE_ECC - case WC_PK_TYPE_ECDH: - if (ssl != NULL) - der = ssl->staticKE.ecKey; - if (der == NULL) - der = ctx->staticKE.ecKey; - break; - #endif - #ifdef HAVE_CURVE25519 - case WC_PK_TYPE_CURVE25519: - if (ssl != NULL) - der = ssl->staticKE.x25519Key; - if (der == NULL) - der = ctx->staticKE.x25519Key; - break; - #endif - #ifdef HAVE_CURVE448 - case WC_PK_TYPE_CURVE448: - if (ssl != NULL) - der = ssl->staticKE.x448Key; - if (der == NULL) - der = ctx->staticKE.x448Key; - break; - #endif - default: - /* not supported */ - ret = NOT_COMPILED_IN; - break; - } +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#ifdef HAVE_OCSP +/* Not an OpenSSL API. */ +int wolfSSL_get_ocsp_response(WOLFSSL* ssl, byte** response) +{ + *response = ssl->ocspResp; + return ssl->ocspRespSz; +} - if (der) { - if (key) - *key = der->buffer; - if (keySz) - *keySz = der->length; - } +/* Not an OpenSSL API. */ +char* wolfSSL_get_ocsp_url(WOLFSSL* ssl) +{ + return ssl->url; +} + +/* Not an OpenSSL API. */ +int wolfSSL_set_ocsp_url(WOLFSSL* ssl, char* url) +{ + if (ssl == NULL) + return WOLFSSL_FAILURE; + + ssl->url = url; + return WOLFSSL_SUCCESS; +} +#endif /* OCSP */ +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ + +#if defined(HAVE_OCSP) && !defined(NO_ASN_TIME) +int wolfSSL_get_ocsp_producedDate( + WOLFSSL *ssl, + byte *producedDate, + size_t producedDate_space, + int *producedDateFormat) +{ + if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) && + (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME)) + return BAD_FUNC_ARG; -#ifndef SINGLE_THREADED - wc_UnLockMutex(&ctx->staticKELock); -#endif + if ((producedDate == NULL) || (producedDateFormat == NULL)) + return BAD_FUNC_ARG; - return ret; + if (XSTRLEN((char *)ssl->ocspProducedDate) >= producedDate_space) + return BUFFER_E; + + XSTRNCPY((char *)producedDate, (const char *)ssl->ocspProducedDate, + producedDate_space); + *producedDateFormat = ssl->ocspProducedDateFormat; + + return 0; } -/* returns pointer to currently loaded static ephemeral as ASN.1 */ -/* this can be converted to PEM using wc_DerToPem */ -int wolfSSL_CTX_get_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo, - const unsigned char** key, unsigned int* keySz) -{ - if (ctx == NULL) { +int wolfSSL_get_ocsp_producedDate_tm(WOLFSSL *ssl, struct tm *produced_tm) { + int idx = 0; + + if ((ssl->ocspProducedDateFormat != ASN_UTC_TIME) && + (ssl->ocspProducedDateFormat != ASN_GENERALIZED_TIME)) return BAD_FUNC_ARG; - } - return GetStaticEphemeralKey(ctx, NULL, keyAlgo, key, keySz); -} -int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo, - const unsigned char** key, unsigned int* keySz) -{ - if (ssl == NULL || ssl->ctx == NULL) { + if (produced_tm == NULL) return BAD_FUNC_ARG; - } - return GetStaticEphemeralKey(ssl->ctx, ssl, keyAlgo, key, keySz); + if (ExtractDate(ssl->ocspProducedDate, + (unsigned char)ssl->ocspProducedDateFormat, produced_tm, &idx)) + return 0; + else + return ASN_PARSE_E; } +#endif -#endif /* WOLFSSL_STATIC_EPHEMERAL */ -#if defined(OPENSSL_EXTRA) -/* wolfSSL_THREADID_current is provided as a compat API with - * CRYPTO_THREADID_current to register current thread id into given id object. - * However, CRYPTO_THREADID_current API has been deprecated and no longer - * exists in the OpenSSL 1.0.0 or later.This API only works as a stub - * like as existing wolfSSL_THREADID_set_numeric. - */ -void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id) -{ - (void)id; - return; -} -/* wolfSSL_THREADID_hash is provided as a compatible API with - * CRYPTO_THREADID_hash which returns a hash value calculated from the - * specified thread id. However, CRYPTO_THREADID_hash API has been - * deprecated and no longer exists in the OpenSSL 1.0.0 or later. - * This API only works as a stub to returns 0. This behavior is - * equivalent to the latest OpenSSL CRYPTO_THREADID_hash. - */ -unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id) -{ - (void)id; - return 0UL; -} -/* wolfSSL_CTX_set_ecdh_auto is provided as compatible API with - * SSL_CTX_set_ecdh_auto to enable auto ecdh curve selection functionality. - * Since this functionality is enabled by default in wolfSSL, - * this API exists as a stub. - */ -int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff) +#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ + defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) +int wolfSSL_CTX_get_extra_chain_certs(WOLFSSL_CTX* ctx, + WOLF_STACK_OF(X509)** chain) { - (void)ctx; - (void)onoff; - return WOLFSSL_SUCCESS; -} + word32 idx; + word32 length; + WOLFSSL_STACK* node; + WOLFSSL_STACK* last = NULL; -/** - * set security level (wolfSSL doesn't support security level) - * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure - * @param level security level - */ -void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_security_level"); - (void)ctx; - (void)level; -} -/** - * get security level (wolfSSL doesn't support security level) - * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure - * @return always 0(level 0) - */ -int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_security_level"); - (void)ctx; - return 0; -} + if (ctx == NULL || chain == NULL) { + chain = NULL; + return WOLFSSL_FAILURE; + } + if (ctx->x509Chain != NULL) { + *chain = ctx->x509Chain; + return WOLFSSL_SUCCESS; + } + /* If there are no chains then success! */ + *chain = NULL; + if (ctx->certChain == NULL || ctx->certChain->length == 0) { + return WOLFSSL_SUCCESS; + } -/** - * Determine whether a WOLFSSL_SESSION object can be used for resumption - * @param s a pointer to WOLFSSL_SESSION structure - * @return return 1 if session is resumable, otherwise 0. - */ -int wolfSSL_SESSION_is_resumable(const WOLFSSL_SESSION *s) -{ - s = ClientSessionToSession(s); - if (s == NULL) - return 0; + /* Create a new stack of WOLFSSL_X509 object from chain buffer. */ + for (idx = 0; idx < ctx->certChain->length; ) { + node = wolfSSL_sk_X509_new_null(); + if (node == NULL) + return WOLFSSL_FAILURE; + node->next = NULL; -#ifdef HAVE_SESSION_TICKET - if (s->ticketLen > 0) - return 1; -#endif + /* 3 byte length | X509 DER data */ + ato24(ctx->certChain->buffer + idx, &length); + idx += 3; - if (s->sessionIDSz > 0) - return 1; + /* Create a new X509 from DER encoded data. */ + node->data.x509 = wolfSSL_X509_d2i_ex(NULL, + ctx->certChain->buffer + idx, (int)length, ctx->heap); + if (node->data.x509 == NULL) { + XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL); + /* Return as much of the chain as we created. */ + ctx->x509Chain = *chain; + return WOLFSSL_FAILURE; + } + idx += length; - return 0; -} + /* Add object to the end of the stack. */ + if (last == NULL) { + node->num = 1; + *chain = node; + } + else { + (*chain)->num++; + last->next = node; + } -#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) -/* - * This API accepts a user callback which puts key-log records into - * a KEY LOGFILE. The callback is stored into a CTX and propagated to - * each SSL object on its creation timing. - */ -void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx, wolfSSL_CTX_keylog_cb_func cb) -{ - WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback"); - /* stores the callback into WOLFSSL_CTX */ - if (ctx != NULL) { - ctx->keyLogCb = cb; + last = node; } -} -wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback( - const WOLFSSL_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback"); - if (ctx != NULL) - return ctx->keyLogCb; - else - return NULL; -} -#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */ -#endif /* OPENSSL_EXTRA */ + ctx->x509Chain = *chain; -#ifndef NO_CERT -#define WOLFSSL_X509_INCLUDED -#include "src/x509.c" -#endif + return WOLFSSL_SUCCESS; +} -/******************************************************************************* - * START OF standard C library wrapping APIs - ******************************************************************************/ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH))) -#ifndef NO_WOLFSSL_STUB -int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int), - void *(*r) (void *, size_t, const char *, - int), void (*f) (void *)) +int wolfSSL_CTX_get_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb* cb) { - (void) m; - (void) r; - (void) f; - WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions"); - WOLFSSL_STUB("CRYPTO_set_mem_ex_functions"); + if (ctx == NULL || ctx->cm == NULL || cb == NULL) + return WOLFSSL_FAILURE; - return WOLFSSL_FAILURE; -} -#endif +#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)) + if (ctx->cm->ocsp_stapling == NULL) + return WOLFSSL_FAILURE; + + *cb = ctx->cm->ocsp_stapling->statusCb; +#else + (void)cb; + *cb = NULL; #endif -#if defined(OPENSSL_EXTRA) + return WOLFSSL_SUCCESS; -/** - * free allocated memory resource - * @param str a pointer to resource to be freed - * @param file dummy argument - * @param line dummy argument - */ -void wolfSSL_CRYPTO_free(void *str, const char *file, int line) -{ - (void)file; - (void)line; - XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER); } -/** - * allocate memory with size of num - * @param num size of memory allocation to be malloced - * @param file dummy argument - * @param line dummy argument - * @return a pointer to allocated memory on succssesful, otherwise NULL - */ -void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line) + +int wolfSSL_CTX_set_tlsext_status_cb(WOLFSSL_CTX* ctx, tlsextStatusCb cb) { - (void)file; - (void)line; - return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER); -} + if (ctx == NULL || ctx->cm == NULL) + return WOLFSSL_FAILURE; -#endif +#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)) + /* Ensure stapling is on for callback to be used. */ + wolfSSL_CTX_EnableOCSPStapling(ctx); -/******************************************************************************* - * END OF standard C library wrapping APIs - ******************************************************************************/ + if (ctx->cm->ocsp_stapling == NULL) + return WOLFSSL_FAILURE; -/******************************************************************************* - * START OF EX_DATA APIs - ******************************************************************************/ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && (defined(HAVE_STUNNEL) || \ - defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH))) -void wolfSSL_CRYPTO_cleanup_all_ex_data(void){ - WOLFSSL_ENTER("CRYPTO_cleanup_all_ex_data"); -} + ctx->cm->ocsp_stapling->statusCb = cb; +#else + (void)cb; #endif -#ifdef HAVE_EX_DATA -void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx) + return WOLFSSL_SUCCESS; +} + +int wolfSSL_CTX_get0_chain_certs(WOLFSSL_CTX *ctx, + WOLF_STACK_OF(WOLFSSL_X509) **sk) { - WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); -#ifdef MAX_EX_DATA - if(ex_data && idx < MAX_EX_DATA && idx >= 0) { - return ex_data->ex_data[idx]; + WOLFSSL_ENTER("wolfSSL_CTX_get0_chain_certs"); + if (ctx == NULL || sk == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } -#else - (void)ex_data; - (void)idx; -#endif - return NULL; + + /* This function should return ctx->x509Chain if it is populated, otherwise + it should be populated from ctx->certChain. This matches the behavior of + wolfSSL_CTX_get_extra_chain_certs, so it is used directly. */ + return wolfSSL_CTX_get_extra_chain_certs(ctx, sk); } -int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, void *data) +#ifdef KEEP_OUR_CERT +int wolfSSL_get0_chain_certs(WOLFSSL *ssl, + WOLF_STACK_OF(WOLFSSL_X509) **sk) { - WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data"); -#ifdef MAX_EX_DATA - if (ex_data && idx < MAX_EX_DATA && idx >= 0) { -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS - if (ex_data->ex_data_cleanup_routines[idx]) { - if (ex_data->ex_data[idx]) - ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]); - ex_data->ex_data_cleanup_routines[idx] = NULL; - } -#endif - ex_data->ex_data[idx] = data; - return WOLFSSL_SUCCESS; + WOLFSSL_ENTER("wolfSSL_get0_chain_certs"); + if (ssl == NULL || sk == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } -#else - (void)ex_data; - (void)idx; - (void)data; -#endif - return WOLFSSL_FAILURE; + *sk = ssl->ourCertChain; + return WOLFSSL_SUCCESS; } +#endif -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -int wolfSSL_CRYPTO_set_ex_data_with_cleanup( - WOLFSSL_CRYPTO_EX_DATA* ex_data, - int idx, - void *data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine) +WOLF_STACK_OF(WOLFSSL_STRING)* wolfSSL_sk_WOLFSSL_STRING_new(void) { - WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup"); - if (ex_data && idx < MAX_EX_DATA && idx >= 0) { - if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx]) - ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]); - ex_data->ex_data[idx] = data; - ex_data->ex_data_cleanup_routines[idx] = cleanup_routine; - return WOLFSSL_SUCCESS; + WOLF_STACK_OF(WOLFSSL_STRING)* ret = wolfSSL_sk_new_node(NULL); + + if (ret) { + ret->type = STACK_TYPE_STRING; } - return WOLFSSL_FAILURE; + + return ret; } -#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ -/** - * Issues unique index for the class specified by class_index. - * Other parameter except class_index are ignored. - * Currently, following class_index are accepted: - * - WOLF_CRYPTO_EX_INDEX_SSL - * - WOLF_CRYPTO_EX_INDEX_SSL_CTX - * - WOLF_CRYPTO_EX_INDEX_X509 - * @param class_index index one of CRYPTO_EX_INDEX_xxx - * @param argp parameters to be saved - * @param argl parameters to be saved - * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new - * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup - * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free - * @return index value grater or equal to zero on success, -1 on failure. - */ -int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, - WOLFSSL_CRYPTO_EX_new* new_func, - WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func) +void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s) { - WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index"); + WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free"); - return wolfssl_get_ex_new_index(class_index, argl, argp, new_func, - dup_func, free_func); + if (s != NULL) + XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); } -#endif /* HAVE_EX_DATA */ -/******************************************************************************* - * END OF EX_DATA APIs - ******************************************************************************/ +void wolfSSL_sk_WOLFSSL_STRING_free(WOLF_STACK_OF(WOLFSSL_STRING)* sk) +{ + WOLFSSL_STACK* tmp; + WOLFSSL_ENTER("wolfSSL_sk_WOLFSSL_STRING_free"); -/******************************************************************************* - * START OF BUF_MEM API - ******************************************************************************/ + if (sk == NULL) + return; -#if defined(OPENSSL_EXTRA) + /* parse through stack freeing each node */ + while (sk) { + tmp = sk->next; + XFREE(sk->data.string, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); + sk = tmp; + } +} -/* Begin functions for openssl/buffer.h */ -WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void) +WOLFSSL_STRING wolfSSL_sk_WOLFSSL_STRING_value( + WOLF_STACK_OF(WOLFSSL_STRING)* strings, int idx) { - WOLFSSL_BUF_MEM* buf; - buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL, - DYNAMIC_TYPE_OPENSSL); - if (buf) { - XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM)); - } - return buf; + for (; idx > 0 && strings != NULL; idx--) + strings = strings->next; + if (strings == NULL) + return NULL; + return strings->data.string; } -/* non-compat API returns length of buffer on success */ -int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len, - char zeroFill) +int wolfSSL_sk_WOLFSSL_STRING_num(WOLF_STACK_OF(WOLFSSL_STRING)* strings) { + if (strings) + return (int)strings->num; + return 0; +} - int len_int = (int)len; - int mx; - char* tmp; +#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */ - /* verify provided arguments */ - if (buf == NULL || len_int < 0) { - return 0; /* BAD_FUNC_ARG; */ - } +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_QUIC) +#ifdef HAVE_ALPN +void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data, + unsigned int *len) +{ + word16 nameLen; - /* check to see if fits in existing length */ - if (buf->length > len) { - buf->length = len; - return len_int; + if (ssl != NULL && data != NULL && len != NULL) { + TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen); + *len = nameLen; } +} - /* check to see if fits in max buffer */ - if (buf->max >= len) { - if (buf->data != NULL && zeroFill) { - XMEMSET(&buf->data[buf->length], 0, len - buf->length); +int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen, + const unsigned char *in, unsigned int inLen, + const unsigned char *clientNames, + unsigned int clientLen) +{ + unsigned int i, j; + byte lenIn, lenClient; + + if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL) + return OPENSSL_NPN_UNSUPPORTED; + + for (i = 0; i < inLen; i += lenIn) { + lenIn = in[i++]; + for (j = 0; j < clientLen; j += lenClient) { + lenClient = clientNames[j++]; + + if (lenIn != lenClient) + continue; + + if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) { + *out = (unsigned char *)(in + i); + *outLen = lenIn; + return OPENSSL_NPN_NEGOTIATED; + } } - buf->length = len; - return len_int; } - /* expand size, to handle growth */ - mx = (len_int + 3) / 3 * 4; + *out = (unsigned char *)clientNames + 1; + *outLen = clientNames[0]; + return OPENSSL_NPN_NO_OVERLAP; +} - /* use realloc */ - tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); - if (tmp == NULL) { - return 0; /* ERR_R_MALLOC_FAILURE; */ +void wolfSSL_set_alpn_select_cb(WOLFSSL *ssl, + int (*cb) (WOLFSSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), void *arg) +{ + if (ssl != NULL) { + ssl->alpnSelect = cb; + ssl->alpnSelectArg = arg; } - buf->data = tmp; +} - buf->max = mx; - if (zeroFill) - XMEMSET(&buf->data[buf->length], 0, len - buf->length); - buf->length = len; +void wolfSSL_CTX_set_alpn_select_cb(WOLFSSL_CTX *ctx, + int (*cb) (WOLFSSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), void *arg) +{ + if (ctx != NULL) { + ctx->alpnSelect = cb; + ctx->alpnSelectArg = arg; + } +} - return len_int; +void wolfSSL_CTX_set_next_protos_advertised_cb(WOLFSSL_CTX *s, + int (*cb) (WOLFSSL *ssl, + const unsigned char + **out, + unsigned int *outlen, + void *arg), void *arg) +{ + (void)s; + (void)cb; + (void)arg; + WOLFSSL_STUB("wolfSSL_CTX_set_next_protos_advertised_cb"); +} +void wolfSSL_CTX_set_next_proto_select_cb(WOLFSSL_CTX *s, + int (*cb) (WOLFSSL *ssl, + unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), void *arg) +{ + (void)s; + (void)cb; + (void)arg; + WOLFSSL_STUB("wolfSSL_CTX_set_next_proto_select_cb"); } -/* returns length of buffer on success */ -int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len) +void wolfSSL_get0_next_proto_negotiated(const WOLFSSL *s, + const unsigned char **data, unsigned *len) { - return wolfSSL_BUF_MEM_grow_ex(buf, len, 1); + (void)s; + (void)data; + (void)len; + WOLFSSL_STUB("wolfSSL_get0_next_proto_negotiated"); } +#endif /* HAVE_ALPN */ -/* non-compat API returns length of buffer on success */ -int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len) +#endif /* WOLFSSL_NGINX / WOLFSSL_HAPROXY */ + +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) +int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id) { - char* tmp; - int mx; + int ret = 0; - /* verify provided arguments */ - if (buf == NULL || len == 0 || (int)len <= 0) { - return 0; /* BAD_FUNC_ARG; */ + WOLFSSL_ENTER("wolfSSL_curve_is_disabled"); + WOLFSSL_MSG_EX("wolfSSL_curve_is_disabled checking for %d", curve_id); + + /* (curve_id >= WOLFSSL_FFDHE_START) - DH parameters are never disabled. */ + if (curve_id < WOLFSSL_FFDHE_START) { + if (curve_id > WOLFSSL_ECC_MAX_AVAIL) { + WOLFSSL_MSG("Curve id out of supported range"); + /* Disabled if not in valid range. */ + ret = 1; + } + else if (curve_id >= 32) { + /* 0 is for invalid and 1-14 aren't used otherwise. */ + ret = (ssl->disabledCurves & (1U << (curve_id - 32))) != 0; + } + else { + ret = (ssl->disabledCurves & (1U << curve_id)) != 0; + } } - if (len == buf->length) - return (int)len; + WOLFSSL_LEAVE("wolfSSL_curve_is_disabled", ret); + return ret; +} - if (len > buf->length) - return wolfSSL_BUF_MEM_grow_ex(buf, len, 0); +#if (defined(HAVE_ECC) || \ + defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) +#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c) - /* expand size, to handle growth */ - mx = ((int)len + 3) / 3 * 4; +const WOLF_EC_NIST_NAME kNistCurves[] = { +#ifdef HAVE_ECC + {CURVE_NAME("P-160"), NID_secp160r1, WOLFSSL_ECC_SECP160R1}, + {CURVE_NAME("P-160-2"), NID_secp160r2, WOLFSSL_ECC_SECP160R2}, + {CURVE_NAME("P-192"), NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1}, + {CURVE_NAME("P-224"), NID_secp224r1, WOLFSSL_ECC_SECP224R1}, + {CURVE_NAME("P-256"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("P-384"), NID_secp384r1, WOLFSSL_ECC_SECP384R1}, + {CURVE_NAME("P-521"), NID_secp521r1, WOLFSSL_ECC_SECP521R1}, + {CURVE_NAME("K-160"), NID_secp160k1, WOLFSSL_ECC_SECP160K1}, + {CURVE_NAME("K-192"), NID_secp192k1, WOLFSSL_ECC_SECP192K1}, + {CURVE_NAME("K-224"), NID_secp224k1, WOLFSSL_ECC_SECP224R1}, + {CURVE_NAME("K-256"), NID_secp256k1, WOLFSSL_ECC_SECP256K1}, + {CURVE_NAME("B-256"), NID_brainpoolP256r1, WOLFSSL_ECC_BRAINPOOLP256R1}, + {CURVE_NAME("B-384"), NID_brainpoolP384r1, WOLFSSL_ECC_BRAINPOOLP384R1}, + {CURVE_NAME("B-512"), NID_brainpoolP512r1, WOLFSSL_ECC_BRAINPOOLP512R1}, +#endif +#ifdef HAVE_CURVE25519 + {CURVE_NAME("X25519"), NID_X25519, WOLFSSL_ECC_X25519}, +#endif +#ifdef HAVE_CURVE448 + {CURVE_NAME("X448"), NID_X448, WOLFSSL_ECC_X448}, +#endif +#ifdef WOLFSSL_HAVE_KYBER + {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1}, + {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL1}, + {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL1}, +#if (defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) + {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_P256_KYBER_LEVEL1}, + {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P256_KYBER_LEVEL1}, + {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_P256_KYBER_LEVEL1}, +#endif +#endif +#ifdef WOLFSSL_SM2 + {CURVE_NAME("SM2"), NID_sm2, WOLFSSL_ECC_SM2P256V1}, +#endif +#ifdef HAVE_ECC + /* Alternative curve names */ + {CURVE_NAME("prime256v1"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("secp256r1"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("secp384r1"), NID_secp384r1, WOLFSSL_ECC_SECP384R1}, + {CURVE_NAME("secp521r1"), NID_secp521r1, WOLFSSL_ECC_SECP521R1}, +#endif +#ifdef WOLFSSL_SM2 + {CURVE_NAME("sm2p256v1"), NID_sm2, WOLFSSL_ECC_SM2P256V1}, +#endif + {0, NULL, 0, 0}, +}; - /* We want to shrink the internal buffer */ - tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); - if (tmp == NULL) - return 0; +int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, + byte curves_only) +{ + int idx, start = 0, len, i, ret = WOLFSSL_FAILURE; + word16 curve; + word32 disabled; + char name[MAX_CURVE_NAME_SZ]; + byte groups_len = 0; +#ifdef WOLFSSL_SMALL_STACK + void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL; + int *groups; +#else + int groups[WOLFSSL_MAX_GROUP_COUNT]; +#endif + const WOLF_EC_NIST_NAME* nist_name; - buf->data = tmp; - buf->length = len; - buf->max = mx; +#ifdef WOLFSSL_SMALL_STACK + groups = (int*)XMALLOC(sizeof(int)*WOLFSSL_MAX_GROUP_COUNT, + heap, DYNAMIC_TYPE_TMP_BUFFER); + if (groups == NULL) { + ret = MEMORY_E; + goto leave; + } +#endif - return (int)len; -} + for (idx = 1; names[idx-1] != '\0'; idx++) { + if (names[idx] != ':' && names[idx] != '\0') + continue; -void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf) -{ - if (buf) { - if (buf->data) { - XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL); - buf->data = NULL; - } - buf->max = 0; - buf->length = 0; - XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL); - } -} -/* End Functions for openssl/buffer.h */ + len = idx - start; + if (len > MAX_CURVE_NAME_SZ - 1) + goto leave; -#endif /* OPENSSL_EXTRA */ + XMEMCPY(name, names + start, len); + name[len] = 0; + curve = WOLFSSL_NAMED_GROUP_INVALID; -/******************************************************************************* - * END OF BUF_MEM API - ******************************************************************************/ + for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) { + if (len == nist_name->name_len && + XSTRNCMP(name, nist_name->name, len) == 0) { + curve = nist_name->curve; + break; + } + } -#define WOLFSSL_CONF_INCLUDED -#include + if (curve == WOLFSSL_NAMED_GROUP_INVALID) { + #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC) + int nret; + const ecc_set_type *eccSet; -/******************************************************************************* - * START OF RAND API - ******************************************************************************/ + nret = wc_ecc_get_curve_idx_from_name(name); + if (nret < 0) { + WOLFSSL_MSG("Could not find name in set"); + goto leave; + } -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB) -static int wolfSSL_RAND_InitMutex(void) -{ -#ifndef WOLFSSL_MUTEX_INITIALIZER - if (gRandMethodsInit == 0) { - if (wc_InitMutex(&gRandMethodMutex) != 0) { - WOLFSSL_MSG("Bad Init Mutex rand methods"); - return BAD_MUTEX_E; + eccSet = wc_ecc_get_curve_params(ret); + if (eccSet == NULL) { + WOLFSSL_MSG("NULL set returned"); + goto leave; + } + + curve = GetCurveByOID(eccSet->oidSum); + #else + WOLFSSL_MSG("API not present to search farther using name"); + goto leave; + #endif } - gRandMethodsInit = 1; - } -#endif - return 0; -} -#endif -#ifdef OPENSSL_EXTRA + if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) || + curve == WOLFSSL_NAMED_GROUP_INVALID) { + WOLFSSL_MSG("curve value is not supported"); + goto leave; + } -/* Checks if the global RNG has been created. If not then one is created. - * - * Returns WOLFSSL_SUCCESS when no error is encountered. - */ -int wolfSSL_RAND_Init(void) -{ - int ret = WOLFSSL_FAILURE; -#ifdef HAVE_GLOBAL_RNG - if (wc_LockMutex(&globalRNGMutex) == 0) { - if (initGlobalRNG == 0) { - ret = wc_InitRng(&globalRNG); - if (ret == 0) { - initGlobalRNG = 1; - ret = WOLFSSL_SUCCESS; + for (i = 0; i < groups_len; ++i) { + if (groups[i] == curve) { + /* silently drop duplicates */ + break; } } - else { - /* GlobalRNG is already initialized */ - ret = WOLFSSL_SUCCESS; + if (i >= groups_len) { + if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) { + WOLFSSL_MSG_EX("setting %d or more supported " + "curves is not permitted", groups_len); + goto leave; + } + groups[groups_len++] = (int)curve; } - wc_UnLockMutex(&globalRNGMutex); + start = idx + 1; + } + + /* Disable all curves so that only the ones the user wants are enabled. */ + disabled = 0xFFFFFFFFUL; + for (i = 0; i < groups_len; ++i) { + /* Switch the bit to off and therefore is enabled. */ + curve = (word16)groups[i]; + if (curve >= 64) { + WC_DO_NOTHING; + } + else if (curve >= 32) { + /* 0 is for invalid and 1-14 aren't used otherwise. */ + disabled &= ~(1U << (curve - 32)); + } + else { + disabled &= ~(1U << curve); + } + #ifdef HAVE_SUPPORTED_CURVES + #if !defined(WOLFSSL_OLD_SET_CURVES_LIST) + /* using the wolfSSL API to set the groups, this will populate + * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS. + * The order in (ssl|ctx)->groups will then be respected + * when TLSX_KEY_SHARE needs to be established */ + if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len) + != WOLFSSL_SUCCESS) + || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len) + != WOLFSSL_SUCCESS)) { + WOLFSSL_MSG("Unable to set supported curve"); + goto leave; + } + #elif !defined(NO_WOLFSSL_CLIENT) + /* set the supported curve so client TLS extension contains only the + * desired curves */ + if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS) + || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve) + != WOLFSSL_SUCCESS)) { + WOLFSSL_MSG("Unable to set supported curve"); + goto leave; + } + #endif + #endif /* HAVE_SUPPORTED_CURVES */ } + + if (ssl) + ssl->disabledCurves = disabled; + else + ctx->disabledCurves = disabled; + ret = WOLFSSL_SUCCESS; + +leave: +#ifdef WOLFSSL_SMALL_STACK + if (groups) + XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } +int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set1_curves_list"); + if (ctx == NULL || names == NULL) { + WOLFSSL_MSG("ctx or names was NULL"); + return WOLFSSL_FAILURE; + } + return set_curves_list(NULL, ctx, names, 1); +} + +int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names) +{ + WOLFSSL_ENTER("wolfSSL_set1_curves_list"); + if (ssl == NULL || names == NULL) { + WOLFSSL_MSG("ssl or names was NULL"); + return WOLFSSL_FAILURE; + } + return set_curves_list(ssl, NULL, names, 1); +} +#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */ +#endif /* OPENSSL_EXTRA || HAVE_CURL */ -/* WOLFSSL_SUCCESS on ok */ -int wolfSSL_RAND_seed(const void* seed, int len) +#ifdef OPENSSL_EXTRA +/* Sets a callback for when sending and receiving protocol messages. + * This callback is copied to all WOLFSSL objects created from the ctx. + * + * ctx WOLFSSL_CTX structure to set callback in + * cb callback to use + * + * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case + */ +int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb) { -#ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->seed) { - int ret = gRandMethods->seed(seed, len); - wc_UnLockMutex(&gRandMethodMutex); - return ret; - } - wc_UnLockMutex(&gRandMethodMutex); + WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback"); + if (ctx == NULL) { + WOLFSSL_MSG("Null ctx passed in"); + return WOLFSSL_FAILURE; } -#else - (void)seed; - (void)len; -#endif - /* Make sure global shared RNG (globalRNG) is initialized */ - return wolfSSL_RAND_Init(); + ctx->protoMsgCb = cb; + return WOLFSSL_SUCCESS; } -/* Returns the path for reading seed data from. - * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd - * - * Note uses stdlib by default unless XGETENV macro is overwritten +/* Sets a callback for when sending and receiving protocol messages. * - * fname buffer to hold path - * len length of fname buffer + * ssl WOLFSSL structure to set callback in + * cb callback to use * - * Returns a pointer to fname on success and NULL on failure + * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case */ -const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) +int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb) { -#if !defined(NO_FILESYSTEM) && defined(XGETENV) - char* rt; - - WOLFSSL_ENTER("wolfSSL_RAND_file_name"); + WOLFSSL_ENTER("wolfSSL_set_msg_callback"); - if (fname == NULL) { - return NULL; + if (ssl == NULL) { + return WOLFSSL_FAILURE; } - XMEMSET(fname, 0, len); - - if ((rt = XGETENV("RANDFILE")) != NULL) { - if (len > XSTRLEN(rt)) { - XMEMCPY(fname, rt, XSTRLEN(rt)); - } - else { - WOLFSSL_MSG("RANDFILE too large for buffer"); - rt = NULL; - } + if (cb != NULL) { + ssl->toInfoOn = 1; } - /* $RANDFILE was not set or is too large, check $HOME */ - if (rt == NULL) { - const char ap[] = "/.rnd"; + ssl->protoMsgCb = cb; + return WOLFSSL_SUCCESS; +} - WOLFSSL_MSG("Environment variable RANDFILE not set"); - if ((rt = XGETENV("HOME")) == NULL) { - WOLFSSL_MSG("Environment variable HOME not set"); - return NULL; - } - if (len > XSTRLEN(rt) + XSTRLEN(ap)) { - fname[0] = '\0'; - XSTRNCAT(fname, rt, len); - XSTRNCAT(fname, ap, len - XSTRLEN(rt)); - return fname; - } - else { - WOLFSSL_MSG("HOME too large for buffer"); - return NULL; - } +/* set the user argument to pass to the msg callback when called + * return WOLFSSL_SUCCESS on success */ +int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg"); + if (ctx == NULL) { + WOLFSSL_MSG("Null WOLFSSL_CTX passed in"); + return WOLFSSL_FAILURE; } - return fname; -#else - WOLFSSL_ENTER("wolfSSL_RAND_file_name"); - WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, " - "not compiled in"); - (void)fname; - (void)len; - return NULL; -#endif + ctx->protoMsgCtx = arg; + return WOLFSSL_SUCCESS; } -/* Writes 1024 bytes from the RNG to the given file name. - * - * fname name of file to write to - * - * Returns the number of bytes written - */ -int wolfSSL_RAND_write_file(const char* fname) +int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg) { - int bytes = 0; - - WOLFSSL_ENTER("wolfSSL_RAND_write_file"); - - if (fname == NULL) { + WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg"); + if (ssl == NULL) return WOLFSSL_FAILURE; - } - -#ifndef NO_FILESYSTEM - { - #ifndef WOLFSSL_SMALL_STACK - unsigned char buf[1024]; - #else - unsigned char* buf = (unsigned char *)XMALLOC(1024, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (buf == NULL) { - WOLFSSL_MSG("malloc failed"); - return WOLFSSL_FAILURE; - } - #endif - bytes = 1024; /* default size of buf */ - if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("No RNG to use"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - #endif - return 0; - } + ssl->protoMsgCtx = arg; + return WOLFSSL_SUCCESS; +} - if (wc_RNG_GenerateBlock(&globalRNG, buf, bytes) != 0) { - WOLFSSL_MSG("Error generating random buffer"); - bytes = 0; - } - else { - XFILE f; +void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file, + int line) +{ + void *ret; + (void)file; + (void)line; - #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes); - #endif + if (data == NULL || siz >= INT_MAX) + return NULL; - f = XFOPEN(fname, "wb"); - if (f == XBADFILE) { - WOLFSSL_MSG("Error opening the file"); - bytes = 0; - } - else { - size_t bytes_written = XFWRITE(buf, 1, bytes, f); - bytes = (int)bytes_written; - XFCLOSE(f); - } - } - ForceZero(buf, bytes); - #ifdef WOLFSSL_SMALL_STACK - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - #elif defined(WOLFSSL_CHECK_MEM_ZERO) - wc_MemZero_Check(buf, sizeof(buf)); - #endif + ret = OPENSSL_malloc(siz); + if (ret == NULL) { + return NULL; } -#endif + return XMEMCPY(ret, data, siz); +} - return bytes; +void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len) +{ + if (ptr) + ForceZero(ptr, (word32)len); } -#ifndef FREERTOS_TCP +int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p, + unsigned int p_len) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_alpn_protos"); + if (ctx == NULL) + return BAD_FUNC_ARG; + if (ctx->alpn_cli_protos != NULL) { + XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL); + } -/* These constant values are protocol values made by egd */ -#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && !defined(HAVE_FIPS) && \ - defined(HAVE_HASHDRBG) && !defined(NETOS) && defined(HAVE_SYS_UN_H) - #define WOLFSSL_EGD_NBLOCK 0x01 - #include + ctx->alpn_cli_protos = (const unsigned char*)XMALLOC(p_len, + ctx->heap, DYNAMIC_TYPE_OPENSSL); + if (ctx->alpn_cli_protos == NULL) { +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 1; +#else + return WOLFSSL_FAILURE; #endif + } + XMEMCPY((void*)ctx->alpn_cli_protos, p, p_len); + ctx->alpn_cli_protos_len = p_len; -/* This collects entropy from the path nm and seeds the global PRNG with it. +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 0; +#else + return WOLFSSL_SUCCESS; +#endif +} + + +#ifdef HAVE_ALPN +#ifndef NO_BIO +/* Sets the ALPN extension protos * - * nm is the file path to the egd server + * example format is + * unsigned char p[] = { + * 8, 'h', 't', 't', 'p', '/', '1', '.', '1' + * }; * - * Returns the number of bytes read. - */ -int wolfSSL_RAND_egd(const char* nm) + * returns WOLFSSL_SUCCESS on success */ +int wolfSSL_set_alpn_protos(WOLFSSL* ssl, + const unsigned char* p, unsigned int p_len) { -#ifdef WOLFSSL_EGD_NBLOCK - struct sockaddr_un rem; - int fd; - int ret = WOLFSSL_SUCCESS; - word32 bytes = 0; - word32 idx = 0; -#ifndef WOLFSSL_SMALL_STACK - unsigned char buf[256]; + WOLFSSL_BIO* bio; + char* pt = NULL; + + unsigned int sz; + unsigned int idx = 0; + int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH; + WOLFSSL_ENTER("wolfSSL_set_alpn_protos"); + + if (ssl == NULL || p_len <= 1) { +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 1; #else - unsigned char* buf; - buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (buf == NULL) { - WOLFSSL_MSG("Not enough memory"); - return WOLFSSL_FATAL_ERROR; - } + return WOLFSSL_FAILURE; #endif + } - XMEMSET(&rem, 0, sizeof(struct sockaddr_un)); - if (nm == NULL) { - #ifdef WOLFSSL_SMALL_STACK - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - #endif - return WOLFSSL_FATAL_ERROR; + bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); + if (bio == NULL) { +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 1; +#else + return WOLFSSL_FAILURE; +#endif } - fd = socket(AF_UNIX, SOCK_STREAM, 0); - if (fd < 0) { - WOLFSSL_MSG("Error creating socket"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + /* convert into comma separated list */ + while (idx < p_len - 1) { + unsigned int i; + + sz = p[idx++]; + if (idx + sz > p_len) { + WOLFSSL_MSG("Bad list format"); + wolfSSL_BIO_free(bio); + #if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 1; + #else + return WOLFSSL_FAILURE; #endif - return WOLFSSL_FATAL_ERROR; + } + if (sz > 0) { + for (i = 0; i < sz; i++) { + wolfSSL_BIO_write(bio, &p[idx++], 1); + } + if (idx < p_len - 1) + wolfSSL_BIO_write(bio, ",", 1); + } } - rem.sun_family = AF_UNIX; - XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1); - rem.sun_path[sizeof(rem.sun_path)-1] = '\0'; + wolfSSL_BIO_write(bio, "\0", 1); - /* connect to egd server */ - if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) { - WOLFSSL_MSG("error connecting to egd server"); - ret = WOLFSSL_FATAL_ERROR; - } + /* clears out all current ALPN extensions set */ + TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap); -#ifdef WOLFSSL_CHECK_MEM_ZERO - if (ret == WOLFSSL_SUCCESS) { - wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256); + if ((sz = (unsigned int)wolfSSL_BIO_get_mem_data(bio, &pt)) > 0) { + wolfSSL_UseALPN(ssl, pt, sz, (byte) alpn_opt); } + wolfSSL_BIO_free(bio); +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + /* 0 on success in OpenSSL, non-0 on failure in OpenSSL + * the function reverses the return value convention. + */ + return 0; +#else + return WOLFSSL_SUCCESS; #endif - while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) { - buf[idx] = WOLFSSL_EGD_NBLOCK; - buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */ - ret = (int)write(fd, buf + idx, 2); - if (ret != 2) { - if (errno == EAGAIN) { - ret = WOLFSSL_SUCCESS; - continue; - } - WOLFSSL_MSG("error requesting entropy from egd server"); - ret = WOLFSSL_FATAL_ERROR; - break; - } +} +#endif /* !NO_BIO */ +#endif /* HAVE_ALPN */ +#endif /* OPENSSL_EXTRA */ - /* attempting to read */ - buf[idx] = 0; - ret = (int)read(fd, buf + idx, 256 - bytes); - if (ret == 0) { - WOLFSSL_MSG("error reading entropy from egd server"); - ret = WOLFSSL_FATAL_ERROR; - break; - } - if (ret > 0 && buf[idx] > 0) { - bytes += buf[idx]; /* egd stores amount sent in first byte */ - if (bytes + idx > 255 || buf[idx] > ret) { - WOLFSSL_MSG("Buffer error"); - ret = WOLFSSL_FATAL_ERROR; - break; - } - XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]); - idx = bytes; - ret = WOLFSSL_SUCCESS; - if (bytes >= 255) { - break; - } - } - else { - if (errno == EAGAIN || errno == EINTR) { - WOLFSSL_MSG("EGD would read"); - ret = WOLFSSL_SUCCESS; /* try again */ - } - else if (buf[idx] == 0) { - /* if egd returned 0 then there is no more entropy to be had. - Do not try more reads. */ - ret = WOLFSSL_SUCCESS; - break; - } - else { - WOLFSSL_MSG("Error with read"); - ret = WOLFSSL_FATAL_ERROR; +#if defined(OPENSSL_EXTRA) + +#ifndef NO_BIO +#define WOLFSSL_BIO_INCLUDED +#include "src/bio.c" +#endif + +word32 nid2oid(int nid, int grp) +{ + /* get OID type */ + switch (grp) { + /* oidHashType */ + case oidHashType: + switch (nid) { + #ifdef WOLFSSL_MD2 + case NID_md2: + return MD2h; + #endif + #ifndef NO_MD5 + case NID_md5: + return MD5h; + #endif + #ifndef NO_SHA + case NID_sha1: + return SHAh; + #endif + case NID_sha224: + return SHA224h; + #ifndef NO_SHA256 + case NID_sha256: + return SHA256h; + #endif + #ifdef WOLFSSL_SHA384 + case NID_sha384: + return SHA384h; + #endif + #ifdef WOLFSSL_SHA512 + case NID_sha512: + return SHA512h; + #endif + #ifndef WOLFSSL_NOSHA3_224 + case NID_sha3_224: + return SHA3_224h; + #endif + #ifndef WOLFSSL_NOSHA3_256 + case NID_sha3_256: + return SHA3_256h; + #endif + #ifndef WOLFSSL_NOSHA3_384 + case NID_sha3_384: + return SHA3_384h; + #endif + #ifndef WOLFSSL_NOSHA3_512 + case NID_sha3_512: + return SHA3_512h; + #endif } - } - } + break; - if (bytes > 0 && ret == WOLFSSL_SUCCESS) { - /* call to check global RNG is created */ - if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error with initializing global RNG structure"); - ret = WOLFSSL_FATAL_ERROR; - } - else if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes) - != 0) { - WOLFSSL_MSG("Error with reseeding DRBG structure"); - ret = WOLFSSL_FATAL_ERROR; - } - #ifdef SHOW_SECRETS - else { /* print out entropy found only when no error occurred */ - word32 i; - printf("EGD Entropy = "); - for (i = 0; i < bytes; i++) { - printf("%02X", buf[i]); + /* oidSigType */ + case oidSigType: + switch (nid) { + #ifndef NO_DSA + case NID_dsaWithSHA1: + return CTC_SHAwDSA; + case NID_dsa_with_SHA256: + return CTC_SHA256wDSA; + #endif /* NO_DSA */ + #ifndef NO_RSA + case NID_md2WithRSAEncryption: + return CTC_MD2wRSA; + case NID_md5WithRSAEncryption: + return CTC_MD5wRSA; + case NID_sha1WithRSAEncryption: + return CTC_SHAwRSA; + case NID_sha224WithRSAEncryption: + return CTC_SHA224wRSA; + case NID_sha256WithRSAEncryption: + return CTC_SHA256wRSA; + case NID_sha384WithRSAEncryption: + return CTC_SHA384wRSA; + case NID_sha512WithRSAEncryption: + return CTC_SHA512wRSA; + #ifdef WOLFSSL_SHA3 + case NID_RSA_SHA3_224: + return CTC_SHA3_224wRSA; + case NID_RSA_SHA3_256: + return CTC_SHA3_256wRSA; + case NID_RSA_SHA3_384: + return CTC_SHA3_384wRSA; + case NID_RSA_SHA3_512: + return CTC_SHA3_512wRSA; + #endif + #endif /* NO_RSA */ + #ifdef HAVE_ECC + case NID_ecdsa_with_SHA1: + return CTC_SHAwECDSA; + case NID_ecdsa_with_SHA224: + return CTC_SHA224wECDSA; + case NID_ecdsa_with_SHA256: + return CTC_SHA256wECDSA; + case NID_ecdsa_with_SHA384: + return CTC_SHA384wECDSA; + case NID_ecdsa_with_SHA512: + return CTC_SHA512wECDSA; + #ifdef WOLFSSL_SHA3 + case NID_ecdsa_with_SHA3_224: + return CTC_SHA3_224wECDSA; + case NID_ecdsa_with_SHA3_256: + return CTC_SHA3_256wECDSA; + case NID_ecdsa_with_SHA3_384: + return CTC_SHA3_384wECDSA; + case NID_ecdsa_with_SHA3_512: + return CTC_SHA3_512wECDSA; + #endif + #endif /* HAVE_ECC */ } - printf("\n"); - } - #endif - } - - ForceZero(buf, bytes); -#ifdef WOLFSSL_SMALL_STACK - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#elif defined(WOLFSSL_CHECK_MEM_ZERO) - wc_MemZero_Check(buf, 256); -#endif - close(fd); - - if (ret == WOLFSSL_SUCCESS) { - return bytes; - } - else { - return ret; - } -#else - WOLFSSL_MSG("Type of socket needed is not available"); - WOLFSSL_MSG("\tor using mode where DRBG API is not available"); - (void)nm; + break; - return WOLFSSL_FATAL_ERROR; -#endif /* WOLFSSL_EGD_NBLOCK */ -} + /* oidKeyType */ + case oidKeyType: + switch (nid) { + #ifndef NO_DSA + case NID_dsa: + return DSAk; + #endif /* NO_DSA */ + #ifndef NO_RSA + case NID_rsaEncryption: + return RSAk; + #endif /* NO_RSA */ + #ifdef HAVE_ECC + case NID_X9_62_id_ecPublicKey: + return ECDSAk; + #endif /* HAVE_ECC */ + } + break; -#endif /* !FREERTOS_TCP */ -void wolfSSL_RAND_Cleanup(void) -{ -#ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->cleanup) - gRandMethods->cleanup(); - wc_UnLockMutex(&gRandMethodMutex); - } + #ifdef HAVE_ECC + case oidCurveType: + switch (nid) { + case NID_X9_62_prime192v1: + return ECC_SECP192R1_OID; + case NID_X9_62_prime192v2: + return ECC_PRIME192V2_OID; + case NID_X9_62_prime192v3: + return ECC_PRIME192V3_OID; + case NID_X9_62_prime239v1: + return ECC_PRIME239V1_OID; + case NID_X9_62_prime239v2: + return ECC_PRIME239V2_OID; + case NID_X9_62_prime239v3: + return ECC_PRIME239V3_OID; + case NID_X9_62_prime256v1: + return ECC_SECP256R1_OID; + case NID_secp112r1: + return ECC_SECP112R1_OID; + case NID_secp112r2: + return ECC_SECP112R2_OID; + case NID_secp128r1: + return ECC_SECP128R1_OID; + case NID_secp128r2: + return ECC_SECP128R2_OID; + case NID_secp160r1: + return ECC_SECP160R1_OID; + case NID_secp160r2: + return ECC_SECP160R2_OID; + case NID_secp224r1: + return ECC_SECP224R1_OID; + case NID_secp384r1: + return ECC_SECP384R1_OID; + case NID_secp521r1: + return ECC_SECP521R1_OID; + case NID_secp160k1: + return ECC_SECP160K1_OID; + case NID_secp192k1: + return ECC_SECP192K1_OID; + case NID_secp224k1: + return ECC_SECP224K1_OID; + case NID_secp256k1: + return ECC_SECP256K1_OID; + case NID_brainpoolP160r1: + return ECC_BRAINPOOLP160R1_OID; + case NID_brainpoolP192r1: + return ECC_BRAINPOOLP192R1_OID; + case NID_brainpoolP224r1: + return ECC_BRAINPOOLP224R1_OID; + case NID_brainpoolP256r1: + return ECC_BRAINPOOLP256R1_OID; + case NID_brainpoolP320r1: + return ECC_BRAINPOOLP320R1_OID; + case NID_brainpoolP384r1: + return ECC_BRAINPOOLP384R1_OID; + case NID_brainpoolP512r1: + return ECC_BRAINPOOLP512R1_OID; + } + break; + #endif /* HAVE_ECC */ - #ifndef WOLFSSL_MUTEX_INITIALIZER - if (wc_FreeMutex(&gRandMethodMutex) == 0) - gRandMethodsInit = 0; - #endif -#endif -#ifdef HAVE_GLOBAL_RNG - if (wc_LockMutex(&globalRNGMutex) == 0) { - if (initGlobalRNG) { - wc_FreeRng(&globalRNG); - initGlobalRNG = 0; - } - wc_UnLockMutex(&globalRNGMutex); - } -#endif -} + /* oidBlkType */ + case oidBlkType: + switch (nid) { + #ifdef WOLFSSL_AES_128 + case AES128CBCb: + return AES128CBCb; + #endif + #ifdef WOLFSSL_AES_192 + case AES192CBCb: + return AES192CBCb; + #endif + #ifdef WOLFSSL_AES_256 + case AES256CBCb: + return AES256CBCb; + #endif + #ifndef NO_DES3 + case NID_des: + return DESb; + case NID_des3: + return DES3b; + #endif + } + break; -/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise WOLFSSL_FAILURE */ -int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num) -{ - int ret; - int hash; - byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */ + #ifdef HAVE_OCSP + case oidOcspType: + switch (nid) { + case NID_id_pkix_OCSP_basic: + return OCSP_BASIC_OID; + case OCSP_NONCE_OID: + return OCSP_NONCE_OID; + } + break; + #endif /* HAVE_OCSP */ -#ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->pseudorand) { - ret = gRandMethods->pseudorand(buf, num); - wc_UnLockMutex(&gRandMethodMutex); - return ret; - } - wc_UnLockMutex(&gRandMethodMutex); - } -#endif + /* oidCertExtType */ + case oidCertExtType: + switch (nid) { + case NID_basic_constraints: + return BASIC_CA_OID; + case NID_subject_alt_name: + return ALT_NAMES_OID; + case NID_crl_distribution_points: + return CRL_DIST_OID; + case NID_info_access: + return AUTH_INFO_OID; + case NID_authority_key_identifier: + return AUTH_KEY_OID; + case NID_subject_key_identifier: + return SUBJ_KEY_OID; + case NID_inhibit_any_policy: + return INHIBIT_ANY_OID; + case NID_key_usage: + return KEY_USAGE_OID; + case NID_name_constraints: + return NAME_CONS_OID; + case NID_certificate_policies: + return CERT_POLICY_OID; + case NID_ext_key_usage: + return EXT_KEY_USAGE_OID; + } + break; -#ifdef WOLFSSL_HAVE_PRF - #ifndef NO_SHA256 - hash = WC_SHA256; - #elif defined(WOLFSSL_SHA384) - hash = WC_SHA384; - #elif !defined(NO_SHA) - hash = WC_SHA; - #elif !defined(NO_MD5) - hash = WC_MD5; - #endif + /* oidCertAuthInfoType */ + case oidCertAuthInfoType: + switch (nid) { + case NID_ad_OCSP: + return AIA_OCSP_OID; + case NID_ad_ca_issuers: + return AIA_CA_ISSUER_OID; + } + break; - /* get secret value from source of entropy */ - ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN); + /* oidCertPolicyType */ + case oidCertPolicyType: + switch (nid) { + case NID_any_policy: + return CP_ANY_OID; + } + break; - /* uses input buffer to seed for pseudo random number generation, each - * thread will potentially have different results this way */ - if (ret == WOLFSSL_SUCCESS) { - PRIVATE_KEY_UNLOCK(); - ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num, - hash, NULL, INVALID_DEVID); - PRIVATE_KEY_LOCK(); - ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; - } -#else - /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */ - ret = wolfSSL_RAND_bytes(buf, num); - (void)hash; - (void)secret; -#endif - return ret; -} + /* oidCertAltNameType */ + case oidCertAltNameType: + switch (nid) { + case NID_hw_name_oid: + return HW_NAME_OID; + } + break; -/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise WOLFSSL_FAILURE */ -int wolfSSL_RAND_bytes(unsigned char* buf, int num) -{ - int ret = 0; - WC_RNG* rng = NULL; -#ifdef WOLFSSL_SMALL_STACK - WC_RNG* tmpRNG = NULL; -#else - WC_RNG tmpRNG[1]; -#endif - int initTmpRng = 0; -#ifdef HAVE_GLOBAL_RNG - int used_global = 0; -#endif + /* oidCertKeyUseType */ + case oidCertKeyUseType: + switch (nid) { + case NID_anyExtendedKeyUsage: + return EKU_ANY_OID; + case EKU_SERVER_AUTH_OID: + return EKU_SERVER_AUTH_OID; + case EKU_CLIENT_AUTH_OID: + return EKU_CLIENT_AUTH_OID; + case EKU_OCSP_SIGN_OID: + return EKU_OCSP_SIGN_OID; + } + break; - WOLFSSL_ENTER("wolfSSL_RAND_bytes"); - /* sanity check */ - if (buf == NULL || num < 0) - /* return code compliant with OpenSSL */ - return 0; + /* oidKdfType */ + case oidKdfType: + switch (nid) { + case PBKDF2_OID: + return PBKDF2_OID; + } + break; - /* if a RAND callback has been set try and use it */ -#ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->bytes) { - ret = gRandMethods->bytes(buf, num); - wc_UnLockMutex(&gRandMethodMutex); - return ret; - } - wc_UnLockMutex(&gRandMethodMutex); - } -#endif -#ifdef HAVE_GLOBAL_RNG - if (initGlobalRNG) { - if (wc_LockMutex(&globalRNGMutex) != 0) { - WOLFSSL_MSG("Bad Lock Mutex rng"); - return ret; - } + /* oidPBEType */ + case oidPBEType: + switch (nid) { + case PBE_SHA1_RC4_128: + return PBE_SHA1_RC4_128; + case PBE_SHA1_DES: + return PBE_SHA1_DES; + case PBE_SHA1_DES3: + return PBE_SHA1_DES3; + } + break; - rng = &globalRNG; - used_global = 1; - } - else -#endif - { - #ifdef WOLFSSL_SMALL_STACK - tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - if (tmpRNG == NULL) - return ret; - #endif - if (wc_InitRng(tmpRNG) == 0) { - rng = tmpRNG; - initTmpRng = 1; - } - } - if (rng) { - /* handles size greater than RNG_MAX_BLOCK_LEN */ - int blockCount = num / RNG_MAX_BLOCK_LEN; + /* oidKeyWrapType */ + case oidKeyWrapType: + switch (nid) { + #ifdef WOLFSSL_AES_128 + case AES128_WRAP: + return AES128_WRAP; + #endif + #ifdef WOLFSSL_AES_192 + case AES192_WRAP: + return AES192_WRAP; + #endif + #ifdef WOLFSSL_AES_256 + case AES256_WRAP: + return AES256_WRAP; + #endif + } + break; - while (blockCount--) { - ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN); - if (ret != 0) { - WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); - break; + /* oidCmsKeyAgreeType */ + case oidCmsKeyAgreeType: + switch (nid) { + #ifndef NO_SHA + case dhSinglePass_stdDH_sha1kdf_scheme: + return dhSinglePass_stdDH_sha1kdf_scheme; + #endif + #ifdef WOLFSSL_SHA224 + case dhSinglePass_stdDH_sha224kdf_scheme: + return dhSinglePass_stdDH_sha224kdf_scheme; + #endif + #ifndef NO_SHA256 + case dhSinglePass_stdDH_sha256kdf_scheme: + return dhSinglePass_stdDH_sha256kdf_scheme; + #endif + #ifdef WOLFSSL_SHA384 + case dhSinglePass_stdDH_sha384kdf_scheme: + return dhSinglePass_stdDH_sha384kdf_scheme; + #endif + #ifdef WOLFSSL_SHA512 + case dhSinglePass_stdDH_sha512kdf_scheme: + return dhSinglePass_stdDH_sha512kdf_scheme; + #endif } - num -= RNG_MAX_BLOCK_LEN; - buf += RNG_MAX_BLOCK_LEN; - } + break; - if (ret == 0 && num) - ret = wc_RNG_GenerateBlock(rng, buf, num); + /* oidCmsKeyAgreeType */ + #ifdef WOLFSSL_CERT_REQ + case oidCsrAttrType: + switch (nid) { + case NID_pkcs9_contentType: + return PKCS9_CONTENT_TYPE_OID; + case NID_pkcs9_challengePassword: + return CHALLENGE_PASSWORD_OID; + case NID_serialNumber: + return SERIAL_NUMBER_OID; + case NID_userId: + return USER_ID_OID; + case NID_surname: + return SURNAME_OID; + } + break; + #endif - if (ret != 0) - WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); - else - ret = WOLFSSL_SUCCESS; + default: + WOLFSSL_MSG("NID not in table"); + /* MSVC warns without the cast */ + return (word32)-1; } -#ifdef HAVE_GLOBAL_RNG - if (used_global == 1) - wc_UnLockMutex(&globalRNGMutex); -#endif - if (initTmpRng) - wc_FreeRng(tmpRNG); -#ifdef WOLFSSL_SMALL_STACK - if (tmpRNG) - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); -#endif - - return ret; + /* MSVC warns without the cast */ + return (word32)-1; } - -int wolfSSL_RAND_poll(void) +int oid2nid(word32 oid, int grp) { - byte entropy[16]; - int ret = 0; - word32 entropy_sz = 16; + size_t i; + /* get OID type */ + switch (grp) { + /* oidHashType */ + case oidHashType: + switch (oid) { + #ifdef WOLFSSL_MD2 + case MD2h: + return NID_md2; + #endif + #ifndef NO_MD5 + case MD5h: + return NID_md5; + #endif + #ifndef NO_SHA + case SHAh: + return NID_sha1; + #endif + case SHA224h: + return NID_sha224; + #ifndef NO_SHA256 + case SHA256h: + return NID_sha256; + #endif + #ifdef WOLFSSL_SHA384 + case SHA384h: + return NID_sha384; + #endif + #ifdef WOLFSSL_SHA512 + case SHA512h: + return NID_sha512; + #endif + } + break; - WOLFSSL_ENTER("wolfSSL_RAND_poll"); - if (initGlobalRNG == 0){ - WOLFSSL_MSG("Global RNG no Init"); - return WOLFSSL_FAILURE; - } - ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz); - if (ret != 0){ - WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); - ret = WOLFSSL_FAILURE; - }else - ret = WOLFSSL_SUCCESS; + /* oidSigType */ + case oidSigType: + switch (oid) { + #ifndef NO_DSA + case CTC_SHAwDSA: + return NID_dsaWithSHA1; + case CTC_SHA256wDSA: + return NID_dsa_with_SHA256; + #endif /* NO_DSA */ + #ifndef NO_RSA + case CTC_MD2wRSA: + return NID_md2WithRSAEncryption; + case CTC_MD5wRSA: + return NID_md5WithRSAEncryption; + case CTC_SHAwRSA: + return NID_sha1WithRSAEncryption; + case CTC_SHA224wRSA: + return NID_sha224WithRSAEncryption; + case CTC_SHA256wRSA: + return NID_sha256WithRSAEncryption; + case CTC_SHA384wRSA: + return NID_sha384WithRSAEncryption; + case CTC_SHA512wRSA: + return NID_sha512WithRSAEncryption; + #ifdef WOLFSSL_SHA3 + case CTC_SHA3_224wRSA: + return NID_RSA_SHA3_224; + case CTC_SHA3_256wRSA: + return NID_RSA_SHA3_256; + case CTC_SHA3_384wRSA: + return NID_RSA_SHA3_384; + case CTC_SHA3_512wRSA: + return NID_RSA_SHA3_512; + #endif + #ifdef WC_RSA_PSS + case CTC_RSASSAPSS: + return NID_rsassaPss; + #endif + #endif /* NO_RSA */ + #ifdef HAVE_ECC + case CTC_SHAwECDSA: + return NID_ecdsa_with_SHA1; + case CTC_SHA224wECDSA: + return NID_ecdsa_with_SHA224; + case CTC_SHA256wECDSA: + return NID_ecdsa_with_SHA256; + case CTC_SHA384wECDSA: + return NID_ecdsa_with_SHA384; + case CTC_SHA512wECDSA: + return NID_ecdsa_with_SHA512; + #ifdef WOLFSSL_SHA3 + case CTC_SHA3_224wECDSA: + return NID_ecdsa_with_SHA3_224; + case CTC_SHA3_256wECDSA: + return NID_ecdsa_with_SHA3_256; + case CTC_SHA3_384wECDSA: + return NID_ecdsa_with_SHA3_384; + case CTC_SHA3_512wECDSA: + return NID_ecdsa_with_SHA3_512; + #endif + #endif /* HAVE_ECC */ + } + break; - return ret; -} + /* oidKeyType */ + case oidKeyType: + switch (oid) { + #ifndef NO_DSA + case DSAk: + return NID_dsa; + #endif /* NO_DSA */ + #ifndef NO_RSA + case RSAk: + return NID_rsaEncryption; + #ifdef WC_RSA_PSS + case RSAPSSk: + return NID_rsassaPss; + #endif + #endif /* NO_RSA */ + #ifdef HAVE_ECC + case ECDSAk: + return NID_X9_62_id_ecPublicKey; + #endif /* HAVE_ECC */ + } + break; - /* If a valid struct is provided with function pointers, will override - RAND_seed, bytes, cleanup, add, pseudo_bytes and status. If a NULL - pointer is passed in, it will cancel any previous function overrides. - Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */ - int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods) - { - #ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - gRandMethods = methods; - wc_UnLockMutex(&gRandMethodMutex); - return WOLFSSL_SUCCESS; - } - #else - (void)methods; - #endif - return WOLFSSL_FAILURE; - } + #ifdef HAVE_ECC + case oidCurveType: + switch (oid) { + case ECC_SECP192R1_OID: + return NID_X9_62_prime192v1; + case ECC_PRIME192V2_OID: + return NID_X9_62_prime192v2; + case ECC_PRIME192V3_OID: + return NID_X9_62_prime192v3; + case ECC_PRIME239V1_OID: + return NID_X9_62_prime239v1; + case ECC_PRIME239V2_OID: + return NID_X9_62_prime239v2; + case ECC_PRIME239V3_OID: + return NID_X9_62_prime239v3; + case ECC_SECP256R1_OID: + return NID_X9_62_prime256v1; + case ECC_SECP112R1_OID: + return NID_secp112r1; + case ECC_SECP112R2_OID: + return NID_secp112r2; + case ECC_SECP128R1_OID: + return NID_secp128r1; + case ECC_SECP128R2_OID: + return NID_secp128r2; + case ECC_SECP160R1_OID: + return NID_secp160r1; + case ECC_SECP160R2_OID: + return NID_secp160r2; + case ECC_SECP224R1_OID: + return NID_secp224r1; + case ECC_SECP384R1_OID: + return NID_secp384r1; + case ECC_SECP521R1_OID: + return NID_secp521r1; + case ECC_SECP160K1_OID: + return NID_secp160k1; + case ECC_SECP192K1_OID: + return NID_secp192k1; + case ECC_SECP224K1_OID: + return NID_secp224k1; + case ECC_SECP256K1_OID: + return NID_secp256k1; + case ECC_BRAINPOOLP160R1_OID: + return NID_brainpoolP160r1; + case ECC_BRAINPOOLP192R1_OID: + return NID_brainpoolP192r1; + case ECC_BRAINPOOLP224R1_OID: + return NID_brainpoolP224r1; + case ECC_BRAINPOOLP256R1_OID: + return NID_brainpoolP256r1; + case ECC_BRAINPOOLP320R1_OID: + return NID_brainpoolP320r1; + case ECC_BRAINPOOLP384R1_OID: + return NID_brainpoolP384r1; + case ECC_BRAINPOOLP512R1_OID: + return NID_brainpoolP512r1; + } + break; + #endif /* HAVE_ECC */ - /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */ - int wolfSSL_RAND_status(void) - { - int ret = WOLFSSL_SUCCESS; - #ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->status) - ret = gRandMethods->status(); - wc_UnLockMutex(&gRandMethodMutex); - } - else { - ret = WOLFSSL_FAILURE; - } - #else - /* wolfCrypt provides enough seed internally, so return success */ - #endif - return ret; - } + /* oidBlkType */ + case oidBlkType: + switch (oid) { + #ifdef WOLFSSL_AES_128 + case AES128CBCb: + return AES128CBCb; + #endif + #ifdef WOLFSSL_AES_192 + case AES192CBCb: + return AES192CBCb; + #endif + #ifdef WOLFSSL_AES_256 + case AES256CBCb: + return AES256CBCb; + #endif + #ifndef NO_DES3 + case DESb: + return NID_des; + case DES3b: + return NID_des3; + #endif + } + break; - void wolfSSL_RAND_add(const void* add, int len, double entropy) - { - #ifndef WOLFSSL_NO_OPENSSL_RAND_CB - if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { - if (gRandMethods && gRandMethods->add) { - /* callback has return code, but RAND_add does not */ - (void)gRandMethods->add(add, len, entropy); + #ifdef HAVE_OCSP + case oidOcspType: + switch (oid) { + case OCSP_BASIC_OID: + return NID_id_pkix_OCSP_basic; + case OCSP_NONCE_OID: + return OCSP_NONCE_OID; } - wc_UnLockMutex(&gRandMethodMutex); - } - #else - /* wolfSSL seeds/adds internally, use explicit RNG if you want - to take control */ - (void)add; - (void)len; - (void)entropy; - #endif - } + break; + #endif /* HAVE_OCSP */ -#endif /* OPENSSL_EXTRA */ + /* oidCertExtType */ + case oidCertExtType: + switch (oid) { + case BASIC_CA_OID: + return NID_basic_constraints; + case ALT_NAMES_OID: + return NID_subject_alt_name; + case CRL_DIST_OID: + return NID_crl_distribution_points; + case AUTH_INFO_OID: + return NID_info_access; + case AUTH_KEY_OID: + return NID_authority_key_identifier; + case SUBJ_KEY_OID: + return NID_subject_key_identifier; + case INHIBIT_ANY_OID: + return NID_inhibit_any_policy; + case KEY_USAGE_OID: + return NID_key_usage; + case NAME_CONS_OID: + return NID_name_constraints; + case CERT_POLICY_OID: + return NID_certificate_policies; + case EXT_KEY_USAGE_OID: + return NID_ext_key_usage; + } + break; -/******************************************************************************* - * END OF RAND API - ******************************************************************************/ + /* oidCertAuthInfoType */ + case oidCertAuthInfoType: + switch (oid) { + case AIA_OCSP_OID: + return NID_ad_OCSP; + case AIA_CA_ISSUER_OID: + return NID_ad_ca_issuers; + } + break; -/******************************************************************************* - * START OF EVP_CIPHER API - ******************************************************************************/ + /* oidCertPolicyType */ + case oidCertPolicyType: + switch (oid) { + case CP_ANY_OID: + return NID_any_policy; + } + break; -#ifdef OPENSSL_EXTRA + /* oidCertAltNameType */ + case oidCertAltNameType: + switch (oid) { + case HW_NAME_OID: + return NID_hw_name_oid; + } + break; - /* store for external read of iv, WOLFSSL_SUCCESS on success */ - int wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_StoreExternalIV"); + /* oidCertKeyUseType */ + case oidCertKeyUseType: + switch (oid) { + case EKU_ANY_OID: + return NID_anyExtendedKeyUsage; + case EKU_SERVER_AUTH_OID: + return EKU_SERVER_AUTH_OID; + case EKU_CLIENT_AUTH_OID: + return EKU_CLIENT_AUTH_OID; + case EKU_OCSP_SIGN_OID: + return EKU_OCSP_SIGN_OID; + } + break; - if (ctx == NULL) { - WOLFSSL_MSG("Bad function argument"); - return WOLFSSL_FATAL_ERROR; - } + /* oidKdfType */ + case oidKdfType: + switch (oid) { + case PBKDF2_OID: + return PBKDF2_OID; + } + break; - switch (ctx->cipherType) { -#ifndef NO_AES -#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : - WOLFSSL_MSG("AES CBC"); - XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); - break; -#endif -#ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : - WOLFSSL_MSG("AES GCM"); - XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); - break; -#endif /* HAVE_AESGCM */ -#ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : - WOLFSSL_MSG("AES CCM"); - XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); - break; -#endif /* HAVE_AESCCM */ -#ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : - WOLFSSL_MSG("AES ECB"); - break; -#endif -#ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : - WOLFSSL_MSG("AES CTR"); - XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); - break; -#endif /* WOLFSSL_AES_COUNTER */ -#ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - WOLFSSL_MSG("AES CFB1"); - break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - WOLFSSL_MSG("AES CFB8"); - break; -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: - WOLFSSL_MSG("AES CFB128"); - break; -#endif /* WOLFSSL_AES_CFB */ -#if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: - WOLFSSL_MSG("AES OFB"); - break; -#endif /* WOLFSSL_AES_OFB */ -#ifdef WOLFSSL_AES_XTS - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: - WOLFSSL_MSG("AES XTS"); - break; -#endif /* WOLFSSL_AES_XTS */ -#endif /* NO_AES */ + /* oidPBEType */ + case oidPBEType: + switch (oid) { + case PBE_SHA1_RC4_128: + return PBE_SHA1_RC4_128; + case PBE_SHA1_DES: + return PBE_SHA1_DES; + case PBE_SHA1_DES3: + return PBE_SHA1_DES3; + } + break; -#ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : - WOLFSSL_MSG("ARIA GCM"); - XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE); - break; -#endif /* HAVE_ARIA */ + /* oidKeyWrapType */ + case oidKeyWrapType: + switch (oid) { + #ifdef WOLFSSL_AES_128 + case AES128_WRAP: + return AES128_WRAP; + #endif + #ifdef WOLFSSL_AES_192 + case AES192_WRAP: + return AES192_WRAP; + #endif + #ifdef WOLFSSL_AES_256 + case AES256_WRAP: + return AES256_WRAP; + #endif + } + break; -#ifndef NO_DES3 - case DES_CBC_TYPE : - WOLFSSL_MSG("DES CBC"); - XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE); - break; + /* oidCmsKeyAgreeType */ + case oidCmsKeyAgreeType: + switch (oid) { + #ifndef NO_SHA + case dhSinglePass_stdDH_sha1kdf_scheme: + return dhSinglePass_stdDH_sha1kdf_scheme; + #endif + #ifdef WOLFSSL_SHA224 + case dhSinglePass_stdDH_sha224kdf_scheme: + return dhSinglePass_stdDH_sha224kdf_scheme; + #endif + #ifndef NO_SHA256 + case dhSinglePass_stdDH_sha256kdf_scheme: + return dhSinglePass_stdDH_sha256kdf_scheme; + #endif + #ifdef WOLFSSL_SHA384 + case dhSinglePass_stdDH_sha384kdf_scheme: + return dhSinglePass_stdDH_sha384kdf_scheme; + #endif + #ifdef WOLFSSL_SHA512 + case dhSinglePass_stdDH_sha512kdf_scheme: + return dhSinglePass_stdDH_sha512kdf_scheme; + #endif + } + break; - case DES_EDE3_CBC_TYPE : - WOLFSSL_MSG("DES EDE3 CBC"); - XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE); - break; -#endif -#ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : - WOLFSSL_MSG("DES ECB"); - break; - case DES_EDE3_ECB_TYPE : - WOLFSSL_MSG("DES3 ECB"); - break; +#ifdef WOLFSSL_CERT_REQ + case oidCsrAttrType: + switch (oid) { + case PKCS9_CONTENT_TYPE_OID: + return NID_pkcs9_contentType; + case CHALLENGE_PASSWORD_OID: + return NID_pkcs9_challengePassword; + case SERIAL_NUMBER_OID: + return NID_serialNumber; + case USER_ID_OID: + return NID_userId; + } + break; #endif - case ARC4_TYPE : - WOLFSSL_MSG("ARC4"); - break; -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: - break; -#endif + default: + WOLFSSL_MSG("OID not in table"); + } + /* If not found in above switch then try the table */ + for (i = 0; i < WOLFSSL_OBJECT_INFO_SZ; i++) { + if (wolfssl_object_info[i].id == (int)oid) { + return wolfssl_object_info[i].nid; + } + } -#ifdef HAVE_CHACHA - case CHACHA20_TYPE: - break; -#endif + return -1; +} -#ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: - break; -#endif -#ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: - WOLFSSL_MSG("SM4 CBC"); - XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); - break; -#endif -#ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: - WOLFSSL_MSG("SM4 CTR"); - XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); - break; -#endif -#ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: - WOLFSSL_MSG("SM4 GCM"); - XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); - break; -#endif -#ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: - WOLFSSL_MSG("SM4 CCM"); - XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); - break; -#endif +/* frees all nodes in the current threads error queue + * + * id thread id. ERR_remove_state is depreciated and id is ignored. The + * current threads queue will be free'd. + */ +void wolfSSL_ERR_remove_state(unsigned long id) +{ + WOLFSSL_ENTER("wolfSSL_ERR_remove_state"); + (void)id; + if (wc_ERR_remove_state() != 0) { + WOLFSSL_MSG("Error with removing the state"); + } +} - case NULL_CIPHER_TYPE : - WOLFSSL_MSG("NULL"); - break; +#endif /* OPENSSL_EXTRA */ - default: { - WOLFSSL_MSG("bad type"); - return WOLFSSL_FATAL_ERROR; +#ifdef OPENSSL_ALL + +#if !defined(NO_BIO) && !defined(NO_PWDBASED) && defined(HAVE_PKCS8) + +static int bio_get_data(WOLFSSL_BIO* bio, byte** data) +{ + int ret = 0; + byte* mem = NULL; + + ret = wolfSSL_BIO_get_len(bio); + if (ret > 0) { + mem = (byte*)XMALLOC(ret, bio->heap, DYNAMIC_TYPE_OPENSSL); + if (mem == NULL) { + WOLFSSL_MSG("Memory error"); + ret = MEMORY_E; + } + if (ret >= 0) { + if ((ret = wolfSSL_BIO_read(bio, mem, ret)) <= 0) { + XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL); + ret = MEMORY_E; + mem = NULL; } } - return WOLFSSL_SUCCESS; } - /* set internal IV from external, WOLFSSL_SUCCESS on success */ - int wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx) - { + *data = mem; - WOLFSSL_ENTER("wolfSSL_SetInternalIV"); + return ret; +} - if (ctx == NULL) { - WOLFSSL_MSG("Bad function argument"); - return WOLFSSL_FATAL_ERROR; +/* DER data is PKCS#8 encrypted. */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_PKCS8PrivateKey_bio(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY** pkey, + wc_pem_password_cb* cb, + void* ctx) +{ + int ret; + byte* der; + int len; + byte* p; + word32 algId; + WOLFSSL_EVP_PKEY* key; + + if ((len = bio_get_data(bio, &der)) < 0) + return NULL; + + if (cb != NULL) { + char password[NAME_SZ]; + int passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx); + if (passwordSz < 0) { + XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); + return NULL; } + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("wolfSSL_d2i_PKCS8PrivateKey_bio password", password, + passwordSz); + #endif - switch (ctx->cipherType) { + ret = ToTraditionalEnc(der, (word32)len, password, passwordSz, &algId); + if (ret < 0) { + XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); + return NULL; + } -#ifndef NO_AES -#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : - WOLFSSL_MSG("AES CBC"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); - break; -#endif -#ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : - WOLFSSL_MSG("AES GCM"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); - break; -#endif -#ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : - WOLFSSL_MSG("AES ECB"); - break; -#endif -#ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : - WOLFSSL_MSG("AES CTR"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); - break; -#endif + ForceZero(password, (word32)passwordSz); + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Check(password, passwordSz); + #endif + } -#endif /* NO_AES */ + p = der; + key = wolfSSL_d2i_PrivateKey_EVP(pkey, &p, len); + XFREE(der, bio->heap, DYNAMIC_TYPE_OPENSSL); + return key; +} -#ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : - WOLFSSL_MSG("ARIA GCM"); - XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE); - break; -#endif /* HAVE_ARIA */ +#endif /* !NO_BIO && !NO_PWDBASED && HAVE_PKCS8 */ -#ifndef NO_DES3 - case DES_CBC_TYPE : - WOLFSSL_MSG("DES CBC"); - XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE); - break; +/* Detect which type of key it is before decoding. */ +WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, + const unsigned char** pp, + long length) +{ + int ret; + WOLFSSL_EVP_PKEY* key = NULL; + const byte* der = *pp; + word32 idx = 0; + int len = 0; + int cnt = 0; + word32 algId; + word32 keyLen = (word32)length; - case DES_EDE3_CBC_TYPE : - WOLFSSL_MSG("DES EDE3 CBC"); - XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE); - break; -#endif -#ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : - WOLFSSL_MSG("DES ECB"); - break; - case DES_EDE3_ECB_TYPE : - WOLFSSL_MSG("DES3 ECB"); - break; -#endif + /* Take off PKCS#8 wrapper if found. */ + if ((len = ToTraditionalInline_ex(der, &idx, keyLen, &algId)) >= 0) { + der += idx; + keyLen = (word32)len; + } + idx = 0; + len = 0; - case ARC4_TYPE : - WOLFSSL_MSG("ARC4"); - break; + /* Use the number of elements in the outer sequence to determine key type. + */ + ret = GetSequence(der, &idx, &len, keyLen); + if (ret >= 0) { + word32 end = idx + len; + while (ret >= 0 && idx < end) { + /* Skip type */ + idx++; + /* Get length and skip over - keeping count */ + len = 0; + ret = GetLength(der, &idx, &len, keyLen); + if (ret >= 0) { + if (idx + len > end) + ret = ASN_PARSE_E; + else { + idx += len; + cnt++; + } + } + } + } -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: - break; -#endif + if (ret >= 0) { + int type; + /* ECC includes version, private[, curve][, public key] */ + if (cnt >= 2 && cnt <= 4) + type = EVP_PKEY_EC; + else + type = EVP_PKEY_RSA; -#ifdef HAVE_CHACHA - case CHACHA20_TYPE: - break; -#endif + key = wolfSSL_d2i_PrivateKey(type, pkey, &der, keyLen); + *pp = der; + } -#ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: - break; -#endif -#ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: - WOLFSSL_MSG("SM4 CBC"); - XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); - break; -#endif -#ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: - WOLFSSL_MSG("SM4 CTR"); - XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); - break; -#endif -#ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: - WOLFSSL_MSG("SM4 GCM"); - XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); - break; -#endif -#ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: - WOLFSSL_MSG("SM4 CCM"); - XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); - break; -#endif + return key; +} +#endif /* OPENSSL_ALL */ - case NULL_CIPHER_TYPE : - WOLFSSL_MSG("NULL"); - break; +#ifdef WOLFSSL_STATIC_EPHEMERAL +int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr) +{ + int ret; + word32 idx = 0; + DerBuffer* der = NULL; + + if (ssl == NULL || ssl->ctx == NULL || keyPtr == NULL) { + return BAD_FUNC_ARG; + } + +#ifndef SINGLE_THREADED + if (!ssl->ctx->staticKELockInit) { + return BUFFER_E; /* no keys set */ + } + ret = wc_LockMutex(&ssl->ctx->staticKELock); + if (ret != 0) { + return ret; + } +#endif - default: { - WOLFSSL_MSG("bad type"); - return WOLFSSL_FATAL_ERROR; + ret = BUFFER_E; /* set default error */ + switch (keyAlgo) { + #ifndef NO_DH + case WC_PK_TYPE_DH: + if (ssl != NULL) + der = ssl->staticKE.dhKey; + if (der == NULL) + der = ssl->ctx->staticKE.dhKey; + if (der != NULL) { + DhKey* key = (DhKey*)keyPtr; + WOLFSSL_MSG("Using static DH key"); + ret = wc_DhKeyDecode(der->buffer, &idx, key, der->length); } - } - return WOLFSSL_SUCCESS; + break; + #endif + #ifdef HAVE_ECC + case WC_PK_TYPE_ECDH: + if (ssl != NULL) + der = ssl->staticKE.ecKey; + if (der == NULL) + der = ssl->ctx->staticKE.ecKey; + if (der != NULL) { + ecc_key* key = (ecc_key*)keyPtr; + WOLFSSL_MSG("Using static ECDH key"); + ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key, + der->length); + } + break; + #endif + #ifdef HAVE_CURVE25519 + case WC_PK_TYPE_CURVE25519: + if (ssl != NULL) + der = ssl->staticKE.x25519Key; + if (der == NULL) + der = ssl->ctx->staticKE.x25519Key; + if (der != NULL) { + curve25519_key* key = (curve25519_key*)keyPtr; + WOLFSSL_MSG("Using static X25519 key"); + ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key, + der->length); + } + break; + #endif + #ifdef HAVE_CURVE448 + case WC_PK_TYPE_CURVE448: + if (ssl != NULL) + der = ssl->staticKE.x448Key; + if (der == NULL) + der = ssl->ctx->staticKE.x448Key; + if (der != NULL) { + curve448_key* key = (curve448_key*)keyPtr; + WOLFSSL_MSG("Using static X448 key"); + ret = wc_Curve448PrivateKeyDecode(der->buffer, &idx, key, + der->length); + } + break; + #endif + default: + /* not supported */ + ret = NOT_COMPILED_IN; + break; } -#ifndef NO_DES3 +#ifndef SINGLE_THREADED + wc_UnLockMutex(&ssl->ctx->staticKELock); +#endif + return ret; +} -void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, - unsigned char* iv, int len) +static int SetStaticEphemeralKey(WOLFSSL_CTX* ctx, + StaticKeyExchangeInfo_t* staticKE, int keyAlgo, const char* key, + unsigned int keySz, int format, void* heap) { - (void)len; - - WOLFSSL_MSG("wolfSSL_3des_iv"); + int ret = 0; + DerBuffer* der = NULL; + byte* keyBuf = NULL; +#ifndef NO_FILESYSTEM + const char* keyFile = NULL; +#endif - if (ctx == NULL || iv == NULL) { - WOLFSSL_MSG("Bad function argument"); - return; + /* allow empty key to free buffer */ + if (staticKE == NULL || (key == NULL && keySz > 0)) { + return BAD_FUNC_ARG; } - if (doset) - wc_Des3_SetIV(&ctx->cipher.des3, iv); /* OpenSSL compat, no ret */ - else - XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE); -} - -#endif /* NO_DES3 */ - + WOLFSSL_ENTER("SetStaticEphemeralKey"); -#ifndef NO_AES + /* if just free'ing key then skip loading */ + if (key != NULL) { + #ifndef NO_FILESYSTEM + /* load file from filesystem */ + if (key != NULL && keySz == 0) { + size_t keyBufSz = 0; + keyFile = (const char*)key; + ret = wc_FileLoad(keyFile, &keyBuf, &keyBufSz, heap); + if (ret != 0) { + return ret; + } + keySz = (unsigned int)keyBufSz; + } + else + #endif + { + /* use as key buffer directly */ + keyBuf = (byte*)key; + } -void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, - unsigned char* iv, int len) -{ - (void)len; + if (format == WOLFSSL_FILETYPE_PEM) { + #ifdef WOLFSSL_PEM_TO_DER + int keyFormat = 0; + ret = PemToDer(keyBuf, keySz, PRIVATEKEY_TYPE, &der, + heap, NULL, &keyFormat); + /* auto detect key type */ + if (ret == 0 && keyAlgo == WC_PK_TYPE_NONE) { + if (keyFormat == ECDSAk) + keyAlgo = WC_PK_TYPE_ECDH; + else if (keyFormat == X25519k) + keyAlgo = WC_PK_TYPE_CURVE25519; + else + keyAlgo = WC_PK_TYPE_DH; + } + #else + ret = NOT_COMPILED_IN; + #endif + } + else { + /* Detect PK type (if required) */ + #ifdef HAVE_ECC + if (keyAlgo == WC_PK_TYPE_NONE) { + word32 idx = 0; + ecc_key eccKey; + ret = wc_ecc_init_ex(&eccKey, heap, INVALID_DEVID); + if (ret == 0) { + ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &eccKey, keySz); + if (ret == 0) + keyAlgo = WC_PK_TYPE_ECDH; + wc_ecc_free(&eccKey); + } + } + #endif + #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) + if (keyAlgo == WC_PK_TYPE_NONE) { + word32 idx = 0; + DhKey dhKey; + ret = wc_InitDhKey_ex(&dhKey, heap, INVALID_DEVID); + if (ret == 0) { + ret = wc_DhKeyDecode(keyBuf, &idx, &dhKey, keySz); + if (ret == 0) + keyAlgo = WC_PK_TYPE_DH; + wc_FreeDhKey(&dhKey); + } + } + #endif + #ifdef HAVE_CURVE25519 + if (keyAlgo == WC_PK_TYPE_NONE) { + word32 idx = 0; + curve25519_key x25519Key; + ret = wc_curve25519_init_ex(&x25519Key, heap, INVALID_DEVID); + if (ret == 0) { + ret = wc_Curve25519PrivateKeyDecode(keyBuf, &idx, + &x25519Key, keySz); + if (ret == 0) + keyAlgo = WC_PK_TYPE_CURVE25519; + wc_curve25519_free(&x25519Key); + } + } + #endif + #ifdef HAVE_CURVE448 + if (keyAlgo == WC_PK_TYPE_NONE) { + word32 idx = 0; + curve448_key x448Key; + ret = wc_curve448_init(&x448Key); + if (ret == 0) { + ret = wc_Curve448PrivateKeyDecode(keyBuf, &idx, &x448Key, + keySz); + if (ret == 0) + keyAlgo = WC_PK_TYPE_CURVE448; + wc_curve448_free(&x448Key); + } + } + #endif - WOLFSSL_MSG("wolfSSL_aes_ctr_iv"); + if (keyAlgo != WC_PK_TYPE_NONE) { + ret = AllocDer(&der, keySz, PRIVATEKEY_TYPE, heap); + if (ret == 0) { + XMEMCPY(der->buffer, keyBuf, keySz); + } + } + } + } - if (ctx == NULL || iv == NULL) { - WOLFSSL_MSG("Bad function argument"); - return; +#ifndef NO_FILESYSTEM + /* done with keyFile buffer */ + if (keyFile && keyBuf) { + XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); } +#endif - if (doset) - (void)wc_AesSetIV(&ctx->cipher.aes, iv); /* OpenSSL compat, no ret */ - else - XMEMCPY(iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); -} +#ifndef SINGLE_THREADED + if (ret == 0 && !ctx->staticKELockInit) { + ret = wc_InitMutex(&ctx->staticKELock); + if (ret == 0) { + ctx->staticKELockInit = 1; + } + } +#endif + if (ret == 0 + #ifndef SINGLE_THREADED + && (ret = wc_LockMutex(&ctx->staticKELock)) == 0 + #endif + ) { + switch (keyAlgo) { + #ifndef NO_DH + case WC_PK_TYPE_DH: + FreeDer(&staticKE->dhKey); + staticKE->dhKey = der; der = NULL; + break; + #endif + #ifdef HAVE_ECC + case WC_PK_TYPE_ECDH: + FreeDer(&staticKE->ecKey); + staticKE->ecKey = der; der = NULL; + break; + #endif + #ifdef HAVE_CURVE25519 + case WC_PK_TYPE_CURVE25519: + FreeDer(&staticKE->x25519Key); + staticKE->x25519Key = der; der = NULL; + break; + #endif + #ifdef HAVE_CURVE448 + case WC_PK_TYPE_CURVE448: + FreeDer(&staticKE->x448Key); + staticKE->x448Key = der; der = NULL; + break; + #endif + default: + /* not supported */ + ret = NOT_COMPILED_IN; + break; + } -#endif /* NO_AES */ + #ifndef SINGLE_THREADED + wc_UnLockMutex(&ctx->staticKELock); + #endif + } -#endif /* OPENSSL_EXTRA */ + if (ret != 0) { + FreeDer(&der); + } -/******************************************************************************* - * END OF EVP_CIPHER API - ******************************************************************************/ + (void)ctx; /* not used for single threaded */ -#ifndef NO_CERTS + WOLFSSL_LEAVE("SetStaticEphemeralKey", ret); -#define WOLFSSL_X509_STORE_INCLUDED -#include + return ret; +} -/******************************************************************************* - * START OF PKCS7 APIs - ******************************************************************************/ -#ifdef HAVE_PKCS7 +int wolfSSL_CTX_set_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo, + const char* key, unsigned int keySz, int format) +{ + if (ctx == NULL) { + return BAD_FUNC_ARG; + } + return SetStaticEphemeralKey(ctx, &ctx->staticKE, keyAlgo, + key, keySz, format, ctx->heap); +} +int wolfSSL_set_ephemeral_key(WOLFSSL* ssl, int keyAlgo, + const char* key, unsigned int keySz, int format) +{ + if (ssl == NULL || ssl->ctx == NULL) { + return BAD_FUNC_ARG; + } + return SetStaticEphemeralKey(ssl->ctx, &ssl->staticKE, keyAlgo, + key, keySz, format, ssl->heap); +} -#ifdef OPENSSL_ALL -PKCS7* wolfSSL_PKCS7_new(void) +static int GetStaticEphemeralKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + int keyAlgo, const unsigned char** key, unsigned int* keySz) { - WOLFSSL_PKCS7* pkcs7; int ret = 0; + DerBuffer* der = NULL; - pkcs7 = (WOLFSSL_PKCS7*)XMALLOC(sizeof(WOLFSSL_PKCS7), NULL, - DYNAMIC_TYPE_PKCS7); - if (pkcs7 != NULL) { - XMEMSET(pkcs7, 0, sizeof(WOLFSSL_PKCS7)); - ret = wc_PKCS7_Init(&pkcs7->pkcs7, NULL, INVALID_DEVID); + if (key) *key = NULL; + if (keySz) *keySz = 0; + +#ifndef SINGLE_THREADED + if (ctx->staticKELockInit && + (ret = wc_LockMutex(&ctx->staticKELock)) != 0) { + return ret; + } +#endif + + switch (keyAlgo) { + #ifndef NO_DH + case WC_PK_TYPE_DH: + if (ssl != NULL) + der = ssl->staticKE.dhKey; + if (der == NULL) + der = ctx->staticKE.dhKey; + break; + #endif + #ifdef HAVE_ECC + case WC_PK_TYPE_ECDH: + if (ssl != NULL) + der = ssl->staticKE.ecKey; + if (der == NULL) + der = ctx->staticKE.ecKey; + break; + #endif + #ifdef HAVE_CURVE25519 + case WC_PK_TYPE_CURVE25519: + if (ssl != NULL) + der = ssl->staticKE.x25519Key; + if (der == NULL) + der = ctx->staticKE.x25519Key; + break; + #endif + #ifdef HAVE_CURVE448 + case WC_PK_TYPE_CURVE448: + if (ssl != NULL) + der = ssl->staticKE.x448Key; + if (der == NULL) + der = ctx->staticKE.x448Key; + break; + #endif + default: + /* not supported */ + ret = NOT_COMPILED_IN; + break; } - if (ret != 0 && pkcs7 != NULL) { - XFREE(pkcs7, NULL, DYNAMIC_TYPE_PKCS7); - pkcs7 = NULL; + if (der) { + if (key) + *key = der->buffer; + if (keySz) + *keySz = der->length; } - return (PKCS7*)pkcs7; +#ifndef SINGLE_THREADED + wc_UnLockMutex(&ctx->staticKELock); +#endif + + return ret; } -/****************************************************************************** -* wolfSSL_PKCS7_SIGNED_new - allocates PKCS7 and initialize it for a signed data -* -* RETURNS: -* returns pointer to the PKCS7 structure on success, otherwise returns NULL -*/ -PKCS7_SIGNED* wolfSSL_PKCS7_SIGNED_new(void) +/* returns pointer to currently loaded static ephemeral as ASN.1 */ +/* this can be converted to PEM using wc_DerToPem */ +int wolfSSL_CTX_get_ephemeral_key(WOLFSSL_CTX* ctx, int keyAlgo, + const unsigned char** key, unsigned int* keySz) { - byte signedData[]= { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02}; - PKCS7* pkcs7 = NULL; - - if ((pkcs7 = wolfSSL_PKCS7_new()) == NULL) - return NULL; - pkcs7->contentOID = SIGNED_DATA; - if ((wc_PKCS7_SetContentType(pkcs7, signedData, sizeof(signedData))) < 0) { - if (pkcs7) { - wolfSSL_PKCS7_free(pkcs7); - return NULL; - } + if (ctx == NULL) { + return BAD_FUNC_ARG; } - return pkcs7; -} -void wolfSSL_PKCS7_free(PKCS7* pkcs7) + return GetStaticEphemeralKey(ctx, NULL, keyAlgo, key, keySz); +} +int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo, + const unsigned char** key, unsigned int* keySz) { - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; - - if (p7 != NULL) { - if (p7->data != NULL) - XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); - wc_PKCS7_Free(&p7->pkcs7); - if (p7->certs) - wolfSSL_sk_pop_free(p7->certs, NULL); - XFREE(p7, NULL, DYNAMIC_TYPE_PKCS7); + if (ssl == NULL || ssl->ctx == NULL) { + return BAD_FUNC_ARG; } + + return GetStaticEphemeralKey(ssl->ctx, ssl, keyAlgo, key, keySz); } -void wolfSSL_PKCS7_SIGNED_free(PKCS7_SIGNED* p7) +#endif /* WOLFSSL_STATIC_EPHEMERAL */ + +#if defined(OPENSSL_EXTRA) +/* wolfSSL_THREADID_current is provided as a compat API with + * CRYPTO_THREADID_current to register current thread id into given id object. + * However, CRYPTO_THREADID_current API has been deprecated and no longer + * exists in the OpenSSL 1.0.0 or later.This API only works as a stub + * like as existing wolfSSL_THREADID_set_numeric. + */ +void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id) { - wolfSSL_PKCS7_free(p7); + (void)id; return; } +/* wolfSSL_THREADID_hash is provided as a compatible API with + * CRYPTO_THREADID_hash which returns a hash value calculated from the + * specified thread id. However, CRYPTO_THREADID_hash API has been + * deprecated and no longer exists in the OpenSSL 1.0.0 or later. + * This API only works as a stub to returns 0. This behavior is + * equivalent to the latest OpenSSL CRYPTO_THREADID_hash. + */ +unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id) +{ + (void)id; + return 0UL; +} +/* wolfSSL_set_ecdh_auto is provided as compatible API with + * SSL_set_ecdh_auto to enable auto ecdh curve selection functionality. + * Since this functionality is enabled by default in wolfSSL, + * this API exists as a stub. + */ +int wolfSSL_set_ecdh_auto(WOLFSSL* ssl, int onoff) +{ + (void)ssl; + (void)onoff; + return WOLFSSL_SUCCESS; +} +/* wolfSSL_CTX_set_ecdh_auto is provided as compatible API with + * SSL_CTX_set_ecdh_auto to enable auto ecdh curve selection functionality. + * Since this functionality is enabled by default in wolfSSL, + * this API exists as a stub. + */ +int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff) +{ + (void)ctx; + (void)onoff; + return WOLFSSL_SUCCESS; +} /** - * Convert DER/ASN.1 encoded signedData structure to internal PKCS7 - * structure. Note, does not support detached content. - * - * p7 - pointer to set to address of newly created PKCS7 structure on return - * in - pointer to pointer of DER/ASN.1 data - * len - length of input data, bytes - * - * Returns newly allocated and populated PKCS7 structure or NULL on error. + * set security level (wolfSSL doesn't support security level) + * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure + * @param level security level */ -PKCS7* wolfSSL_d2i_PKCS7(PKCS7** p7, const unsigned char** in, int len) +void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level) { - return wolfSSL_d2i_PKCS7_ex(p7, in, len, NULL, 0); + WOLFSSL_ENTER("wolfSSL_CTX_set_security_level"); + (void)ctx; + (void)level; } - -/* This internal function is only decoding and setting up the PKCS7 struct. It -* does not verify the PKCS7 signature. -* -* RETURNS: -* returns pointer to a PKCS7 structure on success, otherwise returns NULL -*/ -static PKCS7* wolfSSL_d2i_PKCS7_only(PKCS7** p7, const unsigned char** in, - int len, byte* content, word32 contentSz) +/** + * get security level (wolfSSL doesn't support security level) + * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure + * @return always 0(level 0) + */ +int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX* ctx) { - WOLFSSL_PKCS7* pkcs7 = NULL; - - WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex"); - - if (in == NULL || *in == NULL || len < 0) - return NULL; - - if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL) - return NULL; - - pkcs7->len = len; - pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7); - if (pkcs7->data == NULL) { - wolfSSL_PKCS7_free((PKCS7*)pkcs7); - return NULL; - } - XMEMCPY(pkcs7->data, *in, pkcs7->len); + WOLFSSL_ENTER("wolfSSL_CTX_get_security_level"); + (void)ctx; + return 0; +} - if (content != NULL) { - pkcs7->pkcs7.content = content; - pkcs7->pkcs7.contentSz = contentSz; +#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) +/* + * This API accepts a user callback which puts key-log records into + * a KEY LOGFILE. The callback is stored into a CTX and propagated to + * each SSL object on its creation timing. + */ +void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx, + wolfSSL_CTX_keylog_cb_func cb) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback"); + /* stores the callback into WOLFSSL_CTX */ + if (ctx != NULL) { + ctx->keyLogCb = cb; } - - if (p7 != NULL) - *p7 = (PKCS7*)pkcs7; - *in += pkcs7->len; - return (PKCS7*)pkcs7; } - - -/***************************************************************************** -* wolfSSL_d2i_PKCS7_ex - Converts the given unsigned char buffer of size len -* into a PKCS7 object. Optionally, accepts a byte buffer of content which -* is stored as the PKCS7 object's content, to support detached signatures. -* @param content The content which is signed, in case the signature is -* detached. Ignored if NULL. -* @param contentSz The size of the passed in content. -* -* RETURNS: -* returns pointer to a PKCS7 structure on success, otherwise returns NULL -*/ -PKCS7* wolfSSL_d2i_PKCS7_ex(PKCS7** p7, const unsigned char** in, int len, - byte* content, word32 contentSz) +wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback( + const WOLFSSL_CTX* ctx) { - WOLFSSL_PKCS7* pkcs7 = NULL; + WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback"); + if (ctx != NULL) + return ctx->keyLogCb; + else + return NULL; +} +#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */ - WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex"); +#endif /* OPENSSL_EXTRA */ - if (in == NULL || *in == NULL || len < 0) - return NULL; +#ifndef NO_CERTS +#define WOLFSSL_X509_INCLUDED +#include "src/x509.c" +#endif - pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_d2i_PKCS7_only(p7, in, len, content, - contentSz); - if (pkcs7 != NULL) { - if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len) - != 0) { - WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed"); - wolfSSL_PKCS7_free((PKCS7*)pkcs7); - if (p7 != NULL) { - *p7 = NULL; - } - return NULL; - } - } +/******************************************************************************* + * START OF standard C library wrapping APIs + ******************************************************************************/ +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ + (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH))) +#ifndef NO_WOLFSSL_STUB +int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int), + void *(*r) (void *, size_t, const char *, + int), void (*f) (void *)) +{ + (void) m; + (void) r; + (void) f; + WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions"); + WOLFSSL_STUB("CRYPTO_set_mem_ex_functions"); - return (PKCS7*)pkcs7; + return WOLFSSL_FAILURE; } +#endif +#endif +#if defined(OPENSSL_EXTRA) /** - * This API was added as a helper function for libest. It - * extracts a stack of certificates from the pkcs7 object. - * @param pkcs7 PKCS7 parameter object - * @return WOLFSSL_STACK_OF(WOLFSSL_X509)* + * free allocated memory resource + * @param str a pointer to resource to be freed + * @param file dummy argument + * @param line dummy argument */ -WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7) +void wolfSSL_CRYPTO_free(void *str, const char *file, int line) { - int i; - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; - WOLF_STACK_OF(WOLFSSL_X509)* ret = NULL; - - WOLFSSL_ENTER("wolfSSL_PKCS7_to_stack"); - - if (!p7) { - WOLFSSL_MSG("Bad parameter"); - return NULL; - } - - if (p7->certs) - return p7->certs; - - for (i = 0; i < MAX_PKCS7_CERTS && p7->pkcs7.cert[i]; i++) { - WOLFSSL_X509* x509 = wolfSSL_X509_d2i_ex(NULL, p7->pkcs7.cert[i], - p7->pkcs7.certSz[i], pkcs7->heap); - if (!ret) - ret = wolfSSL_sk_X509_new_null(); - if (x509) { - if (wolfSSL_sk_X509_push(ret, x509) != WOLFSSL_SUCCESS) { - wolfSSL_X509_free(x509); - WOLFSSL_MSG("wolfSSL_sk_X509_push error"); - goto error; - } - } - else { - WOLFSSL_MSG("wolfSSL_X509_d2i error"); - goto error; - } - } - - /* Save stack to free later */ - if (p7->certs) - wolfSSL_sk_pop_free(p7->certs, NULL); - p7->certs = ret; - - return ret; -error: - if (ret) { - wolfSSL_sk_pop_free(ret, NULL); - } - return NULL; + (void)file; + (void)line; + XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER); } - /** - * Return stack of signers contained in PKCS7 cert. - * Notes: - * - Currently only PKCS#7 messages with a single signer cert is supported. - * - Returned WOLFSSL_STACK must be freed by caller. - * - * pkcs7 - PKCS7 struct to retrieve signer certs from. - * certs - currently unused - * flags - flags to control function behavior. - * - * Return WOLFSSL_STACK of signers on success, NULL on error. + * allocate memory with size of num + * @param num size of memory allocation to be malloced + * @param file dummy argument + * @param line dummy argument + * @return a pointer to allocated memory on succssesful, otherwise NULL */ -WOLFSSL_STACK* wolfSSL_PKCS7_get0_signers(PKCS7* pkcs7, WOLFSSL_STACK* certs, - int flags) +void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line) { - WOLFSSL_X509* x509 = NULL; - WOLFSSL_STACK* signers = NULL; - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + (void)file; + (void)line; + return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER); +} - if (p7 == NULL) - return NULL; +#endif - /* Only PKCS#7 messages with a single cert that is the verifying certificate - * is supported. - */ - if (flags & PKCS7_NOINTERN) { - WOLFSSL_MSG("PKCS7_NOINTERN flag not supported"); - return NULL; - } +/******************************************************************************* + * END OF standard C library wrapping APIs + ******************************************************************************/ - signers = wolfSSL_sk_X509_new_null(); - if (signers == NULL) - return NULL; +/******************************************************************************* + * START OF EX_DATA APIs + ******************************************************************************/ +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ + (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH))) +void wolfSSL_CRYPTO_cleanup_all_ex_data(void){ + WOLFSSL_ENTER("CRYPTO_cleanup_all_ex_data"); +} +#endif - if (wolfSSL_d2i_X509(&x509, (const byte**)&p7->pkcs7.singleCert, - p7->pkcs7.singleCertSz) == NULL) { - wolfSSL_sk_X509_pop_free(signers, NULL); - return NULL; +#ifdef HAVE_EX_DATA +void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); +#ifdef MAX_EX_DATA + if(ex_data && idx < MAX_EX_DATA && idx >= 0) { + return ex_data->ex_data[idx]; } +#else + (void)ex_data; + (void)idx; +#endif + return NULL; +} - if (wolfSSL_sk_X509_push(signers, x509) != WOLFSSL_SUCCESS) { - wolfSSL_sk_X509_pop_free(signers, NULL); - return NULL; +int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, + void *data) +{ + WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data"); +#ifdef MAX_EX_DATA + if (ex_data && idx < MAX_EX_DATA && idx >= 0) { +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS + if (ex_data->ex_data_cleanup_routines[idx]) { + if (ex_data->ex_data[idx]) + ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]); + ex_data->ex_data_cleanup_routines[idx] = NULL; + } +#endif + ex_data->ex_data[idx] = data; + return WOLFSSL_SUCCESS; } - - (void)certs; - - return signers; +#else + (void)ex_data; + (void)idx; + (void)data; +#endif + return WOLFSSL_FAILURE; } -#ifndef NO_BIO - -PKCS7* wolfSSL_d2i_PKCS7_bio(WOLFSSL_BIO* bio, PKCS7** p7) +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +int wolfSSL_CRYPTO_set_ex_data_with_cleanup( + WOLFSSL_CRYPTO_EX_DATA* ex_data, + int idx, + void *data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine) { - WOLFSSL_PKCS7* pkcs7; - int ret; + WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup"); + if (ex_data && idx < MAX_EX_DATA && idx >= 0) { + if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx]) + ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]); + ex_data->ex_data[idx] = data; + ex_data->ex_data_cleanup_routines[idx] = cleanup_routine; + return WOLFSSL_SUCCESS; + } + return WOLFSSL_FAILURE; +} +#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_bio"); +/** + * Issues unique index for the class specified by class_index. + * Other parameter except class_index are ignored. + * Currently, following class_index are accepted: + * - WOLF_CRYPTO_EX_INDEX_SSL + * - WOLF_CRYPTO_EX_INDEX_SSL_CTX + * - WOLF_CRYPTO_EX_INDEX_X509 + * @param class_index index one of CRYPTO_EX_INDEX_xxx + * @param argp parameters to be saved + * @param argl parameters to be saved + * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new + * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup + * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free + * @return index value grater or equal to zero on success, -1 on failure. + */ +int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, + WOLFSSL_CRYPTO_EX_new* new_func, + WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func) +{ + WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index"); - if (bio == NULL) - return NULL; + return wolfssl_get_ex_new_index(class_index, argl, argp, new_func, + dup_func, free_func); +} +#endif /* HAVE_EX_DATA */ - if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL) - return NULL; +/******************************************************************************* + * END OF EX_DATA APIs + ******************************************************************************/ - pkcs7->len = wolfSSL_BIO_get_len(bio); - pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7); - if (pkcs7->data == NULL) { - wolfSSL_PKCS7_free((PKCS7*)pkcs7); - return NULL; - } +/******************************************************************************* + * START OF BUF_MEM API + ******************************************************************************/ - if ((ret = wolfSSL_BIO_read(bio, pkcs7->data, pkcs7->len)) <= 0) { - wolfSSL_PKCS7_free((PKCS7*)pkcs7); - return NULL; - } - /* pkcs7->len may change if using b64 for example */ - pkcs7->len = ret; +#if defined(OPENSSL_EXTRA) - if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len) - != 0) { - WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed"); - wolfSSL_PKCS7_free((PKCS7*)pkcs7); - return NULL; +/* Begin functions for openssl/buffer.h */ +WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void) +{ + WOLFSSL_BUF_MEM* buf; + buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL, + DYNAMIC_TYPE_OPENSSL); + if (buf) { + XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM)); } - - if (p7 != NULL) - *p7 = (PKCS7*)pkcs7; - return (PKCS7*)pkcs7; + return buf; } -int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out) +/* non-compat API returns length of buffer on success */ +int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len, + char zeroFill) { - byte* output = NULL; - int localBuf = 0; - int len; - WC_RNG rng; - int ret = WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_i2d_PKCS7"); - if (!out || !p7) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } + int len_int = (int)len; + int mx; + char* tmp; - if (!p7->rng) { - if (wc_InitRng(&rng) != 0) { - WOLFSSL_MSG("wc_InitRng error"); - return WOLFSSL_FAILURE; - } - p7->rng = &rng; /* cppcheck-suppress autoVariables - */ + /* verify provided arguments */ + if (buf == NULL || len_int < 0) { + return 0; /* BAD_FUNC_ARG; */ } - if ((len = wc_PKCS7_EncodeSignedData(p7, NULL, 0)) < 0) { - WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error"); - goto cleanup; + /* check to see if fits in existing length */ + if (buf->length > len) { + buf->length = len; + return len_int; } - if (*out == NULL) { - output = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (!output) { - WOLFSSL_MSG("malloc error"); - goto cleanup; + /* check to see if fits in max buffer */ + if (buf->max >= len) { + if (buf->data != NULL && zeroFill) { + XMEMSET(&buf->data[buf->length], 0, len - buf->length); } - localBuf = 1; - } - else { - output = *out; - } - - if ((len = wc_PKCS7_EncodeSignedData(p7, output, len)) < 0) { - WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error"); - goto cleanup; + buf->length = len; + return len_int; } - ret = len; -cleanup: - if (p7->rng == &rng) { - wc_FreeRng(&rng); - p7->rng = NULL; - } - if (ret == WOLFSSL_FAILURE && localBuf && output) - XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (ret != WOLFSSL_FAILURE) - *out = output; - return ret; -} - -int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7) -{ - byte* output = NULL; - int len; - int ret = WOLFSSL_FAILURE; - WOLFSSL_ENTER("wolfSSL_i2d_PKCS7_bio"); + /* expand size, to handle growth */ + mx = (len_int + 3) / 3 * 4; - if (!bio || !p7) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; + /* use realloc */ + tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); + if (tmp == NULL) { + return 0; /* ERR_R_MALLOC_FAILURE; */ } + buf->data = tmp; - if ((len = wolfSSL_i2d_PKCS7(p7, &output)) == WOLFSSL_FAILURE) { - WOLFSSL_MSG("wolfSSL_i2d_PKCS7 error"); - goto cleanup; - } + buf->max = (size_t)mx; + if (zeroFill) + XMEMSET(&buf->data[buf->length], 0, len - buf->length); + buf->length = len; - if (wolfSSL_BIO_write(bio, output, len) <= 0) { - WOLFSSL_MSG("wolfSSL_BIO_write error"); - goto cleanup; - } + return len_int; - ret = WOLFSSL_SUCCESS; -cleanup: - if (output) - XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return ret; } -/** - * Creates and returns a PKCS7 signedData structure. - * - * Inner content type is set to DATA to match OpenSSL behavior. - * - * signer - certificate to sign bundle with - * pkey - private key matching signer - * certs - optional additional set of certificates to include - * in - input data to be signed - * flags - optional set of flags to control sign behavior - * - * PKCS7_BINARY - Do not translate input data to MIME canonical - * format (\r\n line endings), thus preventing corruption of - * binary content. - * PKCS7_TEXT - Prepend MIME headers for text/plain to content. - * PKCS7_DETACHED - Set signature detached, omit content from output bundle. - * PKCS7_STREAM - initialize PKCS7 struct for signing, do not read data. - * - * Flags not currently supported: - * PKCS7_NOCERTS - Do not include the signer cert in the output bundle. - * PKCS7_PARTIAL - Allow for PKCS7_sign() to be only partially set up, - * then signers etc to be added separately before - * calling PKCS7_final(). - * - * Returns valid PKCS7 structure pointer, or NULL if an error occurred. - */ -PKCS7* wolfSSL_PKCS7_sign(WOLFSSL_X509* signer, WOLFSSL_EVP_PKEY* pkey, - WOLFSSL_STACK* certs, WOLFSSL_BIO* in, int flags) +/* returns length of buffer on success */ +int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len) { - int err = 0; - WOLFSSL_PKCS7* p7 = NULL; - WOLFSSL_STACK* cert = certs; + return wolfSSL_BUF_MEM_grow_ex(buf, len, 1); +} - WOLFSSL_ENTER("wolfSSL_PKCS7_sign"); +/* non-compat API returns length of buffer on success */ +int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len) +{ + char* tmp; + int mx; - if (flags & PKCS7_NOCERTS) { - WOLFSSL_MSG("PKCS7_NOCERTS flag not yet supported"); - err = 1; + /* verify provided arguments */ + if (buf == NULL || len == 0 || (int)len <= 0) { + return 0; /* BAD_FUNC_ARG; */ } - if (flags & PKCS7_PARTIAL) { - WOLFSSL_MSG("PKCS7_PARTIAL flag not yet supported"); - err = 1; - } + if (len == buf->length) + return (int)len; - if ((err == 0) && (signer == NULL || signer->derCert == NULL || - signer->derCert->length == 0)) { - WOLFSSL_MSG("Bad function arg, signer is NULL or incomplete"); - err = 1; - } + if (len > buf->length) + return wolfSSL_BUF_MEM_grow_ex(buf, len, 0); - if ((err == 0) && (pkey == NULL || pkey->pkey.ptr == NULL || - pkey->pkey_sz <= 0)) { - WOLFSSL_MSG("Bad function arg, pkey is NULL or incomplete"); - err = 1; - } + /* expand size, to handle growth */ + mx = ((int)len + 3) / 3 * 4; + + /* We want to shrink the internal buffer */ + tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); + if (tmp == NULL) + return 0; - if ((err == 0) && (in == NULL) && !(flags & PKCS7_STREAM)) { - WOLFSSL_MSG("input data required unless PKCS7_STREAM used"); - err = 1; - } + buf->data = tmp; + buf->length = len; + buf->max = (size_t)mx; - if ((err == 0) && ((p7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)) { - WOLFSSL_MSG("Error allocating new WOLFSSL_PKCS7"); - err = 1; - } + return (int)len; +} - /* load signer certificate */ - if (err == 0) { - if (wc_PKCS7_InitWithCert(&p7->pkcs7, signer->derCert->buffer, - signer->derCert->length) != 0) { - WOLFSSL_MSG("Failed to load signer certificate"); - err = 1; +void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf) +{ + if (buf) { + if (buf->data) { + XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL); + buf->data = NULL; } + buf->max = 0; + buf->length = 0; + XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL); } +} +/* End Functions for openssl/buffer.h */ - /* set signer private key, data types, defaults */ - if (err == 0) { - p7->pkcs7.privateKey = (byte*)pkey->pkey.ptr; - p7->pkcs7.privateKeySz = pkey->pkey_sz; - p7->pkcs7.contentOID = DATA; /* inner content default is DATA */ - p7->pkcs7.hashOID = SHA256h; /* default to SHA-256 hash type */ - p7->type = SIGNED_DATA; /* PKCS7_final switches on type */ - } - - /* add additional chain certs if provided */ - while (cert && (err == 0)) { - if (cert->data.x509 != NULL && cert->data.x509->derCert != NULL) { - if (wc_PKCS7_AddCertificate(&p7->pkcs7, - cert->data.x509->derCert->buffer, - cert->data.x509->derCert->length) != 0) { - WOLFSSL_MSG("Error in wc_PKCS7_AddCertificate"); - err = 1; - } - } - cert = cert->next; - } +#endif /* OPENSSL_EXTRA */ - if ((err == 0) && (flags & PKCS7_DETACHED)) { - if (wc_PKCS7_SetDetached(&p7->pkcs7, 1) != 0) { - WOLFSSL_MSG("Failed to set signature detached"); - err = 1; - } - } +/******************************************************************************* + * END OF BUF_MEM API + ******************************************************************************/ - if ((err == 0) && (flags & PKCS7_STREAM)) { - /* if streaming, return before finalizing */ - return (PKCS7*)p7; - } +#define WOLFSSL_CONF_INCLUDED +#include - if ((err == 0) && (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1)) { - WOLFSSL_MSG("Error calling wolfSSL_PKCS7_final"); - err = 1; - } +/******************************************************************************* + * START OF RAND API + ******************************************************************************/ - if ((err != 0) && (p7 != NULL)) { - wolfSSL_PKCS7_free((PKCS7*)p7); - p7 = NULL; +#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB) +static int wolfSSL_RAND_InitMutex(void) +{ +#ifndef WOLFSSL_MUTEX_INITIALIZER + if (gRandMethodsInit == 0) { + if (wc_InitMutex(&gRandMethodMutex) != 0) { + WOLFSSL_MSG("Bad Init Mutex rand methods"); + return BAD_MUTEX_E; + } + gRandMethodsInit = 1; } - - return (PKCS7*)p7; +#endif + return 0; } - -#ifdef HAVE_SMIME - -#ifndef MAX_MIME_LINE_LEN - #define MAX_MIME_LINE_LEN 1024 #endif -/** - * Copy input BIO to output BIO, but convert all line endings to CRLF (\r\n), - * used by PKCS7_final(). - * - * in - input WOLFSSL_BIO to be converted - * out - output WOLFSSL_BIO to hold copy of in, with line endings adjusted +#ifdef OPENSSL_EXTRA + +/* Checks if the global RNG has been created. If not then one is created. * - * Return 0 on success, negative on error + * Returns WOLFSSL_SUCCESS when no error is encountered. */ -static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out) +int wolfSSL_RAND_Init(void) { - int ret = 0; - int lineLen = 0; - word32 canonLineLen = 0; - char* canonLine = NULL; -#ifdef WOLFSSL_SMALL_STACK - char* line = NULL; -#else - char line[MAX_MIME_LINE_LEN]; -#endif - - if (in == NULL || out == NULL) { - return BAD_FUNC_ARG; - } - -#ifdef WOLFSSL_SMALL_STACK - line = (char*)XMALLOC(MAX_MIME_LINE_LEN, in->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (line == NULL) { - return MEMORY_E; - } -#endif - XMEMSET(line, 0, MAX_MIME_LINE_LEN); - - while ((lineLen = wolfSSL_BIO_gets(in, line, MAX_MIME_LINE_LEN)) > 0) { - - if (line[lineLen - 1] == '\r' || line[lineLen - 1] == '\n') { - canonLineLen = (word32)lineLen; - if ((canonLine = wc_MIME_single_canonicalize( - line, &canonLineLen)) == NULL) { - ret = -1; - break; - } - - /* remove trailing null */ - if (canonLineLen >= 1 && canonLine[canonLineLen-1] == '\0') { - canonLineLen--; - } - - if (wolfSSL_BIO_write(out, canonLine, (int)canonLineLen) < 0) { - ret = -1; - break; + int ret = WOLFSSL_FAILURE; +#ifdef HAVE_GLOBAL_RNG + if (wc_LockMutex(&globalRNGMutex) == 0) { + if (initGlobalRNG == 0) { + ret = wc_InitRng(&globalRNG); + if (ret == 0) { + initGlobalRNG = 1; + ret = WOLFSSL_SUCCESS; } - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); - canonLine = NULL; } else { - /* no line ending in current line, write direct to out */ - if (wolfSSL_BIO_write(out, line, lineLen) < 0) { - ret = -1; - break; - } + /* GlobalRNG is already initialized */ + ret = WOLFSSL_SUCCESS; } - } - if (canonLine != NULL) { - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + wc_UnLockMutex(&globalRNGMutex); } -#ifdef WOLFSSL_SMALL_STACK - XFREE(line, in->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - return ret; } -#endif /* HAVE_SMIME */ - -/* Used by both PKCS7_final() and PKCS7_verify() */ -static const char contTypeText[] = "Content-Type: text/plain\r\n\r\n"; -/** - * Finalize PKCS7 structure, currently supports signedData only. - * - * Does not generate final bundle (ie: signedData), but finalizes - * the PKCS7 structure in preparation for a output function to be called next. - * - * pkcs7 - initialized PKCS7 structure, populated with signer, etc - * in - input data - * flags - flags to control PKCS7 behavior. Other flags except those noted - * below are ignored: - * - * PKCS7_BINARY - Do not translate input data to MIME canonical - * format (\r\n line endings), thus preventing corruption of - * binary content. - * PKCS7_TEXT - Prepend MIME headers for text/plain to content. - * - * Returns 1 on success, 0 on error - */ -int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags) +/* WOLFSSL_SUCCESS on ok */ +int wolfSSL_RAND_seed(const void* seed, int len) { - int ret = 1; - int memSz = 0; - unsigned char* mem = NULL; - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; - WOLFSSL_BIO* data = NULL; - - WOLFSSL_ENTER("wolfSSL_PKCS7_final"); - - if (p7 == NULL || in == NULL) { - WOLFSSL_MSG("Bad input args to PKCS7_final"); - ret = 0; - } - - if (ret == 1) { - if ((data = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())) == NULL) { - WOLFSSL_MSG("Error in wolfSSL_BIO_new"); - ret = 0; +#ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->seed) { + int ret = gRandMethods->seed(seed, len); + wc_UnLockMutex(&gRandMethodMutex); + return ret; } + wc_UnLockMutex(&gRandMethodMutex); } +#else + (void)seed; + (void)len; +#endif - /* prepend Content-Type header if PKCS7_TEXT */ - if ((ret == 1) && (flags & PKCS7_TEXT)) { - if (wolfSSL_BIO_write(data, contTypeText, - (int)XSTR_SIZEOF(contTypeText)) < 0) { - WOLFSSL_MSG("Error prepending Content-Type header"); - ret = 0; - } - } + /* Make sure global shared RNG (globalRNG) is initialized */ + return wolfSSL_RAND_Init(); +} - /* convert line endings to CRLF if !PKCS7_BINARY */ - if (ret == 1) { - if (flags & PKCS7_BINARY) { - /* no CRLF conversion, direct copy content */ - if ((memSz = wolfSSL_BIO_get_len(in)) <= 0) { - ret = 0; - } - if (ret == 1) { - mem = (unsigned char*)XMALLOC(memSz, in->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (mem == NULL) { - WOLFSSL_MSG("Failed to allocate memory for input data"); - ret = 0; - } - } +/* Returns the path for reading seed data from. + * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd + * + * Note uses stdlib by default unless XGETENV macro is overwritten + * + * fname buffer to hold path + * len length of fname buffer + * + * Returns a pointer to fname on success and NULL on failure + */ +const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) +{ +#if !defined(NO_FILESYSTEM) && defined(XGETENV) + char* rt; - if (ret == 1) { - if (wolfSSL_BIO_read(in, mem, memSz) != memSz) { - WOLFSSL_MSG("Error reading from input BIO"); - ret = 0; - } - else if (wolfSSL_BIO_write(data, mem, memSz) < 0) { - ret = 0; - } - } + WOLFSSL_ENTER("wolfSSL_RAND_file_name"); - if (mem != NULL) { - XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - } - else { - #ifdef HAVE_SMIME - /* convert content line endings to CRLF */ - if (wolfSSL_BIO_to_MIME_crlf(in, data) != 0) { - WOLFSSL_MSG("Error converting line endings to CRLF"); - ret = 0; - } - else { - p7->pkcs7.contentCRLF = 1; - } - #else - WOLFSSL_MSG("Without PKCS7_BINARY requires wolfSSL to be built " - "with HAVE_SMIME"); - ret = 0; - #endif - } + if (fname == NULL) { + return NULL; } - if ((ret == 1) && ((memSz = wolfSSL_BIO_get_mem_data(data, &mem)) < 0)) { - WOLFSSL_MSG("Error in wolfSSL_BIO_get_mem_data"); - ret = 0; - } + XMEMSET(fname, 0, len); - if (ret == 1) { - if (p7->data != NULL) { - XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); - } - p7->data = (byte*)XMALLOC(memSz, NULL, DYNAMIC_TYPE_PKCS7); - if (p7->data == NULL) { - ret = 0; + if ((rt = XGETENV("RANDFILE")) != NULL) { + if (len > XSTRLEN(rt)) { + XMEMCPY(fname, rt, XSTRLEN(rt)); } else { - XMEMCPY(p7->data, mem, memSz); - p7->len = memSz; + WOLFSSL_MSG("RANDFILE too large for buffer"); + rt = NULL; } } - if (ret == 1) { - p7->pkcs7.content = p7->data; - p7->pkcs7.contentSz = p7->len; - } - - if (data != NULL) { - wolfSSL_BIO_free(data); - } - - return ret; -} - -int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs, - WOLFSSL_X509_STORE* store, WOLFSSL_BIO* in, WOLFSSL_BIO* out, int flags) -{ - int i, ret = 0; - unsigned char* mem = NULL; - int memSz = 0; - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; - int contTypeLen; - WOLFSSL_X509* signer = NULL; - WOLFSSL_STACK* signers = NULL; - - WOLFSSL_ENTER("wolfSSL_PKCS7_verify"); - - if (pkcs7 == NULL) - return WOLFSSL_FAILURE; - - if (in != NULL) { - if ((memSz = wolfSSL_BIO_get_mem_data(in, &mem)) < 0) - return WOLFSSL_FAILURE; - - p7->pkcs7.content = mem; - p7->pkcs7.contentSz = memSz; - } - - /* certs is the list of certificates to find the cert with issuer/serial. */ - (void)certs; - /* store is the certificate store to use to verify signer certificate - * associated with the signers. - */ - (void)store; - - ret = wc_PKCS7_VerifySignedData(&p7->pkcs7, p7->data, p7->len); - if (ret != 0) - return WOLFSSL_FAILURE; - - if ((flags & PKCS7_NOVERIFY) != PKCS7_NOVERIFY) { - /* Verify signer certificates */ - if (store == NULL || store->cm == NULL) { - WOLFSSL_MSG("No store or store certs, but PKCS7_NOVERIFY not set"); - return WOLFSSL_FAILURE; - } + /* $RANDFILE was not set or is too large, check $HOME */ + if (rt == NULL) { + const char ap[] = "/.rnd"; - signers = wolfSSL_PKCS7_get0_signers(pkcs7, certs, flags); - if (signers == NULL) { - WOLFSSL_MSG("No signers found to verify"); - return WOLFSSL_FAILURE; - } - for (i = 0; i < wolfSSL_sk_X509_num(signers); i++) { - signer = wolfSSL_sk_X509_value(signers, i); + WOLFSSL_MSG("Environment variable RANDFILE not set"); - if (wolfSSL_CertManagerVerifyBuffer(store->cm, - signer->derCert->buffer, - signer->derCert->length, - WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Failed to verify signer certificate"); - wolfSSL_sk_X509_pop_free(signers, NULL); - return WOLFSSL_FAILURE; + if ((rt = XGETENV("HOME")) == NULL) { + #ifdef XALTHOMEVARNAME + if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) { + WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME + " not set"); + return NULL; } + #else + WOLFSSL_MSG("Environment variable HOME not set"); + return NULL; + #endif } - wolfSSL_sk_X509_pop_free(signers, NULL); - } - if (flags & PKCS7_TEXT) { - /* strip MIME header for text/plain, otherwise error */ - contTypeLen = XSTR_SIZEOF(contTypeText); - if ((p7->pkcs7.contentSz < (word32)contTypeLen) || - (XMEMCMP(p7->pkcs7.content, contTypeText, contTypeLen) != 0)) { - WOLFSSL_MSG("Error PKCS7 Content-Type not found with PKCS7_TEXT"); - return WOLFSSL_FAILURE; + if (len > XSTRLEN(rt) + XSTRLEN(ap)) { + fname[0] = '\0'; + XSTRNCAT(fname, rt, len); + XSTRNCAT(fname, ap, len - XSTRLEN(rt)); + return fname; + } + else { + WOLFSSL_MSG("Path too large for buffer"); + return NULL; } - p7->pkcs7.content += contTypeLen; - p7->pkcs7.contentSz -= contTypeLen; - } - - if (out != NULL) { - wolfSSL_BIO_write(out, p7->pkcs7.content, p7->pkcs7.contentSz); } - WOLFSSL_LEAVE("wolfSSL_PKCS7_verify", WOLFSSL_SUCCESS); - - return WOLFSSL_SUCCESS; + return fname; +#else + WOLFSSL_ENTER("wolfSSL_RAND_file_name"); + WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, " + "not compiled in"); + (void)fname; + (void)len; + return NULL; +#endif } -/** - * This API was added as a helper function for libest. It - * encodes a stack of certificates to pkcs7 format. - * @param pkcs7 PKCS7 parameter object - * @param certs WOLFSSL_STACK_OF(WOLFSSL_X509)* - * @param out Output bio - * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_PKCS7_encode_certs(PKCS7* pkcs7, WOLFSSL_STACK* certs, - WOLFSSL_BIO* out) -{ - int ret; - WOLFSSL_PKCS7* p7; - WOLFSSL_ENTER("wolfSSL_PKCS7_encode_certs"); - - if (!pkcs7 || !certs || !out) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } - p7 = (WOLFSSL_PKCS7*)pkcs7; +/* Writes 1024 bytes from the RNG to the given file name. + * + * fname name of file to write to + * + * Returns the number of bytes written + */ +int wolfSSL_RAND_write_file(const char* fname) +{ + int bytes = 0; - /* take ownership of certs */ - p7->certs = certs; - /* TODO: takes ownership even on failure below but not on above failure. */ + WOLFSSL_ENTER("wolfSSL_RAND_write_file"); - if (pkcs7->certList) { - WOLFSSL_MSG("wolfSSL_PKCS7_encode_certs called multiple times on same " - "struct"); + if (fname == NULL) { return WOLFSSL_FAILURE; } - if (certs) { - /* Save some of the values */ - int hashOID = pkcs7->hashOID; - byte version = pkcs7->version; - - if (!certs->data.x509 || !certs->data.x509->derCert) { - WOLFSSL_MSG("Missing cert"); +#ifndef NO_FILESYSTEM + { + #ifndef WOLFSSL_SMALL_STACK + unsigned char buf[1024]; + #else + unsigned char* buf = (unsigned char *)XMALLOC(1024, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (buf == NULL) { + WOLFSSL_MSG("malloc failed"); return WOLFSSL_FAILURE; } + #endif + bytes = 1024; /* default size of buf */ - if (wc_PKCS7_InitWithCert(pkcs7, certs->data.x509->derCert->buffer, - certs->data.x509->derCert->length) != 0) { - WOLFSSL_MSG("wc_PKCS7_InitWithCert error"); - return WOLFSSL_FAILURE; + if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("No RNG to use"); + #ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + return 0; } - certs = certs->next; - - pkcs7->hashOID = hashOID; - pkcs7->version = version; - } - /* Add the certs to the PKCS7 struct */ - while (certs) { - if (!certs->data.x509 || !certs->data.x509->derCert) { - WOLFSSL_MSG("Missing cert"); - return WOLFSSL_FAILURE; - } - if (wc_PKCS7_AddCertificate(pkcs7, certs->data.x509->derCert->buffer, - certs->data.x509->derCert->length) != 0) { - WOLFSSL_MSG("wc_PKCS7_AddCertificate error"); - return WOLFSSL_FAILURE; + if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) { + WOLFSSL_MSG("Error generating random buffer"); + bytes = 0; } - certs = certs->next; - } + else { + XFILE f; - if (wc_PKCS7_SetSignerIdentifierType(pkcs7, DEGENERATE_SID) != 0) { - WOLFSSL_MSG("wc_PKCS7_SetSignerIdentifierType error"); - return WOLFSSL_FAILURE; - } + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes); + #endif - ret = wolfSSL_i2d_PKCS7_bio(out, pkcs7); + f = XFOPEN(fname, "wb"); + if (f == XBADFILE) { + WOLFSSL_MSG("Error opening the file"); + bytes = 0; + } + else { + size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f); + bytes = (int)bytes_written; + XFCLOSE(f); + } + } + ForceZero(buf, (word32)bytes); + #ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #elif defined(WOLFSSL_CHECK_MEM_ZERO) + wc_MemZero_Check(buf, sizeof(buf)); + #endif + } +#endif - return ret; + return bytes; } -/****************************************************************************** -* wolfSSL_PEM_write_bio_PKCS7 - writes the PKCS7 data to BIO -* -* RETURNS: -* returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE -*/ -int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7) -{ -#ifdef WOLFSSL_SMALL_STACK - byte* outputHead; - byte* outputFoot; -#else - byte outputHead[2048]; - byte outputFoot[2048]; -#endif - word32 outputHeadSz = 2048; - word32 outputFootSz = 2048; - word32 outputSz = 0; - byte* output = NULL; - byte* pem = NULL; - int pemSz = -1; - enum wc_HashType hashType; - byte hashBuf[WC_MAX_DIGEST_SIZE]; - word32 hashSz = -1; - - WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PKCS7"); - - if (bio == NULL || p7 == NULL) - return WOLFSSL_FAILURE; - -#ifdef WOLFSSL_SMALL_STACK - outputHead = (byte*)XMALLOC(outputHeadSz, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (outputHead == NULL) - return MEMORY_E; - - outputFoot = (byte*)XMALLOC(outputFootSz, bio->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (outputFoot == NULL) - goto error; +#ifndef FREERTOS_TCP +/* These constant values are protocol values made by egd */ +#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \ + !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \ + defined(HAVE_SYS_UN_H) + #define WOLFSSL_EGD_NBLOCK 0x01 + #include #endif - XMEMSET(hashBuf, 0, WC_MAX_DIGEST_SIZE); - XMEMSET(outputHead, 0, outputHeadSz); - XMEMSET(outputFoot, 0, outputFootSz); - - hashType = wc_OidGetHash(p7->hashOID); - hashSz = wc_HashGetDigestSize(hashType); - if (hashSz > WC_MAX_DIGEST_SIZE) - goto error; - - /* only SIGNED_DATA is supported */ - switch (p7->contentOID) { - case SIGNED_DATA: - break; - default: - WOLFSSL_MSG("Unknown PKCS#7 Type"); - goto error; - }; - - if ((wc_PKCS7_EncodeSignedData_ex(p7, hashBuf, hashSz, - outputHead, &outputHeadSz, outputFoot, &outputFootSz)) != 0) - goto error; - - outputSz = outputHeadSz + p7->contentSz + outputFootSz; - output = (byte*)XMALLOC(outputSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - - if (!output) - goto error; - - XMEMSET(output, 0, outputSz); - outputSz = 0; - XMEMCPY(&output[outputSz], outputHead, outputHeadSz); - outputSz += outputHeadSz; - XMEMCPY(&output[outputSz], p7->content, p7->contentSz); - outputSz += p7->contentSz; - XMEMCPY(&output[outputSz], outputFoot, outputFootSz); - outputSz += outputFootSz; - - /* get PEM size */ - pemSz = wc_DerToPemEx(output, outputSz, NULL, 0, NULL, CERT_TYPE); - if (pemSz < 0) - goto error; - - pemSz++; /* for '\0'*/ - - /* create PEM buffer and convert from DER to PEM*/ - if ((pem = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER)) - == NULL) - goto error; - - XMEMSET(pem, 0, pemSz); - - if (wc_DerToPemEx(output, outputSz, pem, pemSz, NULL, CERT_TYPE) < 0) { - goto error; +/* This collects entropy from the path nm and seeds the global PRNG with it. + * + * nm is the file path to the egd server + * + * Returns the number of bytes read. + */ +int wolfSSL_RAND_egd(const char* nm) +{ +#ifdef WOLFSSL_EGD_NBLOCK + struct sockaddr_un rem; + int fd; + int ret = WOLFSSL_SUCCESS; + word32 bytes = 0; + word32 idx = 0; +#ifndef WOLFSSL_SMALL_STACK + unsigned char buf[256]; +#else + unsigned char* buf; + buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (buf == NULL) { + WOLFSSL_MSG("Not enough memory"); + return WOLFSSL_FATAL_ERROR; } - if ((wolfSSL_BIO_write(bio, pem, pemSz) == pemSz)) { - XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); -#ifdef WOLFSSL_SMALL_STACK - XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - return WOLFSSL_SUCCESS; - } -error: -#ifdef WOLFSSL_SMALL_STACK - if (outputHead) { - XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (outputFoot) { - XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } -#endif - if (output) { - XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (pem) { - XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XMEMSET(&rem, 0, sizeof(struct sockaddr_un)); + if (nm == NULL) { + #ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + return WOLFSSL_FATAL_ERROR; } - return WOLFSSL_FAILURE; -} -#ifdef HAVE_SMIME -/***************************************************************************** -* wolfSSL_SMIME_read_PKCS7 - Reads the given S/MIME message and parses it into -* a PKCS7 object. In case of a multipart message, stores the signed data in -* bcont. -* -* RETURNS: -* returns pointer to a PKCS7 structure on success, otherwise returns NULL -*/ -PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, - WOLFSSL_BIO** bcont) -{ - MimeHdr* allHdrs = NULL; - MimeHdr* curHdr = NULL; - MimeParam* curParam = NULL; - int inLen = 0; - byte* bcontMem = NULL; - int bcontMemSz = 0; - int sectionLen = 0; - int ret = -1; - char* section = NULL; - char* canonLine = NULL; - char* canonSection = NULL; - PKCS7* pkcs7 = NULL; - word32 outLen = 0; - word32 canonLineLen = 0; - byte* out = NULL; - byte* outHead = NULL; - - int canonPos = 0; - int lineLen = 0; - int remainLen = 0; - byte isEnd = 0; - size_t canonSize = 0; - size_t boundLen = 0; - char* boundary = NULL; - - static const char kContType[] = "Content-Type"; - static const char kCTE[] = "Content-Transfer-Encoding"; - static const char kMultSigned[] = "multipart/signed"; - static const char kAppPkcsSign[] = "application/pkcs7-signature"; - static const char kAppXPkcsSign[] = "application/x-pkcs7-signature"; - static const char kAppPkcs7Mime[] = "application/pkcs7-mime"; - static const char kAppXPkcs7Mime[] = "application/x-pkcs7-mime"; - - WOLFSSL_ENTER("wolfSSL_SMIME_read_PKCS7"); - - if (in == NULL || bcont == NULL) { - goto error; - } - inLen = wolfSSL_BIO_get_len(in); - if (inLen <= 0) { - goto error; - } - remainLen = wolfSSL_BIO_get_len(in); - if (remainLen <= 0) { - goto error; - } - - section = (char*)XMALLOC(remainLen+1, NULL, DYNAMIC_TYPE_PKCS7); - if (section == NULL) { - goto error; - } - lineLen = wolfSSL_BIO_gets(in, section, remainLen); - if (lineLen <= 0) { - goto error; - } - while (isEnd == 0 && remainLen > 0) { - sectionLen += lineLen; - remainLen -= lineLen; - lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], remainLen); - if (lineLen <= 0) { - goto error; - } - /* Line with just newline signals end of headers. */ - if ((lineLen==2 && !XSTRNCMP(§ion[sectionLen], - "\r\n", 2)) || - (lineLen==1 && (section[sectionLen] == '\r' || - section[sectionLen] == '\n'))) { - isEnd = 1; - } + fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { + WOLFSSL_MSG("Error creating socket"); + #ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + return WOLFSSL_FATAL_ERROR; } - section[sectionLen] = '\0'; - ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs); - if (ret < 0) { - WOLFSSL_MSG("Parsing MIME headers failed."); - goto error; - } - isEnd = 0; - section[0] = '\0'; - sectionLen = 0; - - curHdr = wc_MIME_find_header_name(kContType, allHdrs); - if (curHdr && !XSTRNCMP(curHdr->body, kMultSigned, - XSTR_SIZEOF(kMultSigned))) { - curParam = wc_MIME_find_param_attr("protocol", curHdr->params); - if (curParam && (!XSTRNCMP(curParam->value, kAppPkcsSign, - XSTR_SIZEOF(kAppPkcsSign)) || - !XSTRNCMP(curParam->value, kAppXPkcsSign, - XSTR_SIZEOF(kAppXPkcsSign)))) { - curParam = wc_MIME_find_param_attr("boundary", curHdr->params); - if (curParam == NULL) { - goto error; - } - - boundLen = XSTRLEN(curParam->value) + 2; - boundary = (char*)XMALLOC(boundLen+1, NULL, DYNAMIC_TYPE_PKCS7); - if (boundary == NULL) { - goto error; - } - XMEMSET(boundary, 0, (word32)(boundLen+1)); - boundary[0] = boundary[1] = '-'; - XSTRNCPY(&boundary[2], curParam->value, boundLen-2); - - /* Parse up to first boundary, ignore everything here. */ - lineLen = wolfSSL_BIO_gets(in, section, remainLen); - if (lineLen <= 0) { - goto error; - } - while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && - remainLen > 0) { - sectionLen += lineLen; - remainLen -= lineLen; - lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], - remainLen); - if (lineLen <= 0) { - goto error; - } - } - - section[0] = '\0'; - sectionLen = 0; - canonSize = remainLen + 1; - canonSection = (char*)XMALLOC(canonSize, NULL, - DYNAMIC_TYPE_PKCS7); - if (canonSection == NULL) { - goto error; - } - - lineLen = wolfSSL_BIO_gets(in, section, remainLen); - if (lineLen < 0) { - goto error; - } - while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && - remainLen > 0) { - canonLineLen = lineLen; - canonLine = wc_MIME_single_canonicalize(§ion[sectionLen], - &canonLineLen); - if (canonLine == NULL) { - goto error; - } - /* If line endings were added, the initial length may be - * exceeded. */ - if ((canonPos + canonLineLen) >= canonSize) { - canonSize = canonPos + canonLineLen; - canonSection = (char*)XREALLOC(canonSection, canonSize, - NULL, DYNAMIC_TYPE_PKCS7); - if (canonSection == NULL) { - goto error; - } - } - XMEMCPY(&canonSection[canonPos], canonLine, - (int)canonLineLen - 1); - canonPos += canonLineLen - 1; - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); - canonLine = NULL; - - sectionLen += lineLen; - remainLen -= lineLen; - - lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], - remainLen); - if (lineLen <= 0) { - goto error; - } - } - - if (canonPos > 0) { - canonPos--; - } - - /* Strip the final trailing newline. Support \r, \n or \r\n. */ - if (canonSection[canonPos] == '\n') { - if (canonPos > 0) { - canonPos--; - } - } - - if (canonSection[canonPos] == '\r') { - if (canonPos > 0) { - canonPos--; - } - } + rem.sun_family = AF_UNIX; + XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1); + rem.sun_path[sizeof(rem.sun_path)-1] = '\0'; - canonSection[canonPos+1] = '\0'; + /* connect to egd server */ + if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) { + WOLFSSL_MSG("error connecting to egd server"); + ret = WOLFSSL_FATAL_ERROR; + } - *bcont = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); - ret = wolfSSL_BIO_write(*bcont, canonSection, - canonPos + 1); - if (ret != (canonPos+1)) { - goto error; - } - if ((bcontMemSz = wolfSSL_BIO_get_mem_data(*bcont, &bcontMem)) - < 0) { - goto error; +#ifdef WOLFSSL_CHECK_MEM_ZERO + if (ret == WOLFSSL_SUCCESS) { + wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256); + } +#endif + while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) { + buf[idx] = WOLFSSL_EGD_NBLOCK; + buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */ + ret = (int)write(fd, buf + idx, 2); + if (ret != 2) { + if (errno == EAGAIN) { + ret = WOLFSSL_SUCCESS; + continue; } - XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); - canonSection = NULL; + WOLFSSL_MSG("error requesting entropy from egd server"); + ret = WOLFSSL_FATAL_ERROR; + break; + } - wc_MIME_free_hdrs(allHdrs); - allHdrs = NULL; - section[0] = '\0'; - sectionLen = 0; - lineLen = wolfSSL_BIO_gets(in, section, remainLen); - if (lineLen <= 0) { - goto error; + /* attempting to read */ + buf[idx] = 0; + ret = (int)read(fd, buf + idx, 256 - bytes); + if (ret == 0) { + WOLFSSL_MSG("error reading entropy from egd server"); + ret = WOLFSSL_FATAL_ERROR; + break; + } + if (ret > 0 && buf[idx] > 0) { + bytes += buf[idx]; /* egd stores amount sent in first byte */ + if (bytes + idx > 255 || buf[idx] > ret) { + WOLFSSL_MSG("Buffer error"); + ret = WOLFSSL_FATAL_ERROR; + break; } - while (isEnd == 0 && remainLen > 0) { - sectionLen += lineLen; - remainLen -= lineLen; - lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], - remainLen); - if (lineLen <= 0) { - goto error; - } - /* Line with just newline signals end of headers. */ - if ((lineLen==2 && !XSTRNCMP(§ion[sectionLen], - "\r\n", 2)) || - (lineLen==1 && (section[sectionLen] == '\r' || - section[sectionLen] == '\n'))) { - isEnd = 1; - } + XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]); + idx = bytes; + ret = WOLFSSL_SUCCESS; + if (bytes >= 255) { + break; } - section[sectionLen] = '\0'; - ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs); - if (ret < 0) { - WOLFSSL_MSG("Parsing MIME headers failed."); - goto error; + } + else { + if (errno == EAGAIN || errno == EINTR) { + WOLFSSL_MSG("EGD would read"); + ret = WOLFSSL_SUCCESS; /* try again */ } - curHdr = wc_MIME_find_header_name(kContType, allHdrs); - if (curHdr == NULL || (XSTRNCMP(curHdr->body, kAppPkcsSign, - XSTR_SIZEOF(kAppPkcsSign)) && - XSTRNCMP(curHdr->body, kAppXPkcsSign, - XSTR_SIZEOF(kAppXPkcsSign)))) { - WOLFSSL_MSG("S/MIME headers not found inside " - "multipart message.\n"); - goto error; + else if (buf[idx] == 0) { + /* if egd returned 0 then there is no more entropy to be had. + Do not try more reads. */ + ret = WOLFSSL_SUCCESS; + break; } - - section[0] = '\0'; - sectionLen = 0; - lineLen = wolfSSL_BIO_gets(in, section, remainLen); - while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && - remainLen > 0) { - sectionLen += lineLen; - remainLen -= lineLen; - lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], - remainLen); - if (lineLen <= 0) { - goto error; - } + else { + WOLFSSL_MSG("Error with read"); + ret = WOLFSSL_FATAL_ERROR; } - - XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7); - boundary = NULL; } } - else if (curHdr && (!XSTRNCMP(curHdr->body, kAppPkcs7Mime, - XSTR_SIZEOF(kAppPkcs7Mime)) || - !XSTRNCMP(curHdr->body, kAppXPkcs7Mime, - XSTR_SIZEOF(kAppXPkcs7Mime)))) { - sectionLen = wolfSSL_BIO_get_len(in); - if (sectionLen <= 0) { - goto error; + + if (bytes > 0 && ret == WOLFSSL_SUCCESS) { + /* call to check global RNG is created */ + if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error with initializing global RNG structure"); + ret = WOLFSSL_FATAL_ERROR; } - ret = wolfSSL_BIO_read(in, section, sectionLen); - if (ret < 0 || ret != sectionLen) { - WOLFSSL_MSG("Error reading input BIO."); - goto error; + else if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes) + != 0) { + WOLFSSL_MSG("Error with reseeding DRBG structure"); + ret = WOLFSSL_FATAL_ERROR; } - } - else { - WOLFSSL_MSG("S/MIME headers not found."); - goto error; + #ifdef SHOW_SECRETS + else { /* print out entropy found only when no error occurred */ + word32 i; + printf("EGD Entropy = "); + for (i = 0; i < bytes; i++) { + printf("%02X", buf[i]); + } + printf("\n"); + } + #endif } - curHdr = wc_MIME_find_header_name(kCTE, allHdrs); - if (curHdr == NULL) { - WOLFSSL_MSG("Content-Transfer-Encoding header not found, " - "assuming base64 encoding."); - } - else if (XSTRNCMP(curHdr->body, "base64", XSTRLEN("base64"))) { - WOLFSSL_MSG("S/MIME encodings other than base64 are not " - "currently supported.\n"); - goto error; - } + ForceZero(buf, bytes); +#ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#elif defined(WOLFSSL_CHECK_MEM_ZERO) + wc_MemZero_Check(buf, 256); +#endif + close(fd); - if (section == NULL || sectionLen <= 0) { - goto error; - } - outLen = ((sectionLen*3+3)/4)+1; - out = (byte*)XMALLOC(outLen*sizeof(byte), NULL, DYNAMIC_TYPE_PKCS7); - outHead = out; - if (outHead == NULL) { - goto error; - } - /* Strip trailing newlines. */ - while ((sectionLen > 0) && - (section[sectionLen-1] == '\r' || section[sectionLen-1] == '\n')) { - sectionLen--; + if (ret == WOLFSSL_SUCCESS) { + return (int)bytes; } - section[sectionLen] = '\0'; - ret = Base64_Decode((const byte*)section, sectionLen, out, &outLen); - if (ret < 0) { - WOLFSSL_MSG("Error base64 decoding S/MIME message."); - goto error; + else { + return ret; } - pkcs7 = wolfSSL_d2i_PKCS7_only(NULL, (const unsigned char**)&out, outLen, - bcontMem, bcontMemSz); +#else + WOLFSSL_MSG("Type of socket needed is not available"); + WOLFSSL_MSG("\tor using mode where DRBG API is not available"); + (void)nm; - wc_MIME_free_hdrs(allHdrs); - XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7); - XFREE(section, NULL, DYNAMIC_TYPE_PKCS7); + return WOLFSSL_FATAL_ERROR; +#endif /* WOLFSSL_EGD_NBLOCK */ +} - return pkcs7; +#endif /* !FREERTOS_TCP */ -error: - wc_MIME_free_hdrs(allHdrs); - XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7); - XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7); - XFREE(section, NULL, DYNAMIC_TYPE_PKCS7); - if (canonSection != NULL) - XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); - if (canonLine != NULL) - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); - if (bcont) { - wolfSSL_BIO_free(*bcont); - *bcont = NULL; /* reset 'bcount' pointer to NULL on failure */ +void wolfSSL_RAND_Cleanup(void) +{ +#ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->cleanup) + gRandMethods->cleanup(); + wc_UnLockMutex(&gRandMethodMutex); } - return NULL; -} - -/* Convert hash algo OID (from Hash_Sum in asn.h) to SMIME string equivalent. - * Returns hash algorithm string or "unknown" if not found */ -static const char* wolfSSL_SMIME_HashOIDToString(int hashOID) -{ - switch (hashOID) { - case MD5h: - return "md5"; - case SHAh: - return "sha1"; - case SHA224h: - return "sha-224"; - case SHA256h: - return "sha-256"; - case SHA384h: - return "sha-384"; - case SHA512h: - return "sha-512"; - case SHA3_224h: - return "sha3-224"; - case SHA3_384h: - return "sha3-384"; - case SHA3_512h: - return "sha3-512"; - default: - break; + #ifndef WOLFSSL_MUTEX_INITIALIZER + if (wc_FreeMutex(&gRandMethodMutex) == 0) + gRandMethodsInit = 0; + #endif +#endif +#ifdef HAVE_GLOBAL_RNG + if (wc_LockMutex(&globalRNGMutex) == 0) { + if (initGlobalRNG) { + wc_FreeRng(&globalRNG); + initGlobalRNG = 0; + } + wc_UnLockMutex(&globalRNGMutex); } - - return "unknown"; +#endif } -/* Convert PKCS#7 type (from PKCS7_TYPES in pkcs7.h) to SMIME string. - * RFC2633 only defines signed-data, enveloped-data, certs-only. - * Returns string on success, NULL on unknown type. */ -static const char* wolfSSL_SMIME_PKCS7TypeToString(int type) +/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise + * WOLFSSL_FAILURE */ +int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num) { - switch (type) { - case SIGNED_DATA: - return "signed-data"; - case ENVELOPED_DATA: - return "enveloped-data"; - default: - break; + int ret; + int hash; + byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */ + +#ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->pseudorand) { + ret = gRandMethods->pseudorand(buf, num); + wc_UnLockMutex(&gRandMethodMutex); + return ret; + } + wc_UnLockMutex(&gRandMethodMutex); } +#endif - return NULL; -} +#ifdef WOLFSSL_HAVE_PRF + #ifndef NO_SHA256 + hash = WC_SHA256; + #elif defined(WOLFSSL_SHA384) + hash = WC_SHA384; + #elif !defined(NO_SHA) + hash = WC_SHA; + #elif !defined(NO_MD5) + hash = WC_MD5; + #endif -/** - * Convert PKCS7 structure to SMIME format, adding necessary headers. - * - * Handles generation of PKCS7 bundle (ie: signedData). PKCS7 structure - * should be set up beforehand with PKCS7_sign/final/etc. Output is always - * Base64 encoded. - * - * out - output BIO for SMIME formatted data to be placed - * pkcs7 - input PKCS7 structure, initialized and set up - * in - input content to be encoded into PKCS7 - * flags - flags to control behavior of PKCS7 generation - * - * Returns 1 on success, 0 or negative on failure - */ -int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in, - int flags) -{ - int i; - int ret = 1; - WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; - byte* p7out = NULL; - int len = 0; + /* get secret value from source of entropy */ + ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN); - char boundary[33]; /* 32 chars + \0 */ - byte* sigBase64 = NULL; - word32 sigBase64Len = 0; - const char* p7TypeString = NULL; + /* uses input buffer to seed for pseudo random number generation, each + * thread will potentially have different results this way */ + if (ret == WOLFSSL_SUCCESS) { + PRIVATE_KEY_UNLOCK(); + ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num, + hash, NULL, INVALID_DEVID); + PRIVATE_KEY_LOCK(); + ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; + } +#else + /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */ + ret = wolfSSL_RAND_bytes(buf, num); + (void)hash; + (void)secret; +#endif + return ret; +} - static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise + * WOLFSSL_FAILURE */ +int wolfSSL_RAND_bytes(unsigned char* buf, int num) +{ + int ret = 0; + WC_RNG* rng = NULL; +#ifdef WOLFSSL_SMALL_STACK + WC_RNG* tmpRNG = NULL; +#else + WC_RNG tmpRNG[1]; +#endif + int initTmpRng = 0; +#ifdef HAVE_GLOBAL_RNG + int used_global = 0; +#endif - if (out == NULL || p7 == NULL) { - WOLFSSL_MSG("Bad function arguments"); + WOLFSSL_ENTER("wolfSSL_RAND_bytes"); + /* sanity check */ + if (buf == NULL || num < 0) + /* return code compliant with OpenSSL */ return 0; - } - if (in != NULL && (p7->pkcs7.content == NULL || p7->pkcs7.contentSz == 0 || - p7->pkcs7.contentCRLF == 0)) { - /* store and adjust content line endings for CRLF if needed */ - if (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1) { - ret = 0; + /* if a RAND callback has been set try and use it */ +#ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->bytes) { + ret = gRandMethods->bytes(buf, num); + wc_UnLockMutex(&gRandMethodMutex); + return ret; } + wc_UnLockMutex(&gRandMethodMutex); } - - if (ret > 0) { - /* Generate signedData bundle, DER in output (dynamic) */ - if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) == WOLFSSL_FAILURE) { - WOLFSSL_MSG("Error in wolfSSL_i2d_PKCS7"); - ret = 0; +#endif +#ifdef HAVE_GLOBAL_RNG + if (initGlobalRNG) { + if (wc_LockMutex(&globalRNGMutex) != 0) { + WOLFSSL_MSG("Bad Lock Mutex rng"); + return ret; } - } - - /* Base64 encode signedData bundle */ - if (ret > 0) { - if (Base64_Encode(p7out, len, NULL, &sigBase64Len) != LENGTH_ONLY_E) { - ret = 0; + /* the above access to initGlobalRNG is racey -- recheck it now that we + * have the lock. + */ + if (initGlobalRNG) { + rng = &globalRNG; + used_global = 1; } else { - sigBase64 = (byte*)XMALLOC(sigBase64Len, NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (sigBase64 == NULL) { - ret = 0; - } + wc_UnLockMutex(&globalRNGMutex); } } - if (ret > 0) { - XMEMSET(sigBase64, 0, sigBase64Len); - if (Base64_Encode(p7out, len, sigBase64, &sigBase64Len) < 0) { - WOLFSSL_MSG("Error in Base64_Encode of signature"); - ret = 0; + if (used_global == 0) +#endif + { + #ifdef WOLFSSL_SMALL_STACK + tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); + if (tmpRNG == NULL) + return ret; + #endif + if (wc_InitRng(tmpRNG) == 0) { + rng = tmpRNG; + initTmpRng = 1; } } + if (rng) { + /* handles size greater than RNG_MAX_BLOCK_LEN */ + int blockCount = num / RNG_MAX_BLOCK_LEN; - /* build up SMIME message */ - if (ret > 0) { - if (flags & PKCS7_DETACHED) { - - /* generate random boundary */ - if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("No RNG to use"); - ret = 0; - } - - /* no need to generate random byte for null terminator (size-1) */ - if ((ret > 0) && (wc_RNG_GenerateBlock(&globalRNG, (byte*)boundary, - sizeof(boundary) - 1 ) != 0)) { - WOLFSSL_MSG("Error in wc_RNG_GenerateBlock"); - ret = 0; - } - - if (ret > 0) { - for (i = 0; i < (int)sizeof(boundary) - 1; i++) { - boundary[i] = - alphanum[boundary[i] % XSTR_SIZEOF(alphanum)]; - } - boundary[sizeof(boundary)-1] = 0; - } - - if (ret > 0) { - /* S/MIME header beginning */ - ret = wolfSSL_BIO_printf(out, - "MIME-Version: 1.0\n" - "Content-Type: multipart/signed; " - "protocol=\"application/x-pkcs7-signature\"; " - "micalg=\"%s\"; " - "boundary=\"----%s\"\n\n" - "This is an S/MIME signed message\n\n" - "------%s\n", - wolfSSL_SMIME_HashOIDToString(p7->pkcs7.hashOID), - boundary, boundary); - } - - if (ret > 0) { - /* S/MIME content */ - ret = wolfSSL_BIO_write(out, - p7->pkcs7.content, p7->pkcs7.contentSz); - } - - if (ret > 0) { - /* S/SMIME header end boundary */ - ret = wolfSSL_BIO_printf(out, - "\n------%s\n", boundary); - } - - if (ret > 0) { - /* Signature and header */ - ret = wolfSSL_BIO_printf(out, - "Content-Type: application/x-pkcs7-signature; " - "name=\"smime.p7s\"\n" - "Content-Transfer-Encoding: base64\n" - "Content-Disposition: attachment; " - "filename=\"smime.p7s\"\n\n" - "%.*s\n" /* Base64 encoded signature */ - "------%s--\n\n", - sigBase64Len, sigBase64, - boundary); - } - } - else { - p7TypeString = wolfSSL_SMIME_PKCS7TypeToString(p7->type); - if (p7TypeString == NULL) { - WOLFSSL_MSG("Unsupported PKCS7 SMIME type"); - ret = 0; - } - - if (ret > 0) { - /* not detached */ - ret = wolfSSL_BIO_printf(out, - "MIME-Version: 1.0\n" - "Content-Disposition: attachment; " - "filename=\"smime.p7m\"\n" - "Content-Type: application/x-pkcs7-mime; " - "smime-type=%s; name=\"smime.p7m\"\n" - "Content-Transfer-Encoding: base64\n\n" - "%.*s\n" /* signature */, - p7TypeString, sigBase64Len, sigBase64); + while (blockCount--) { + ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN); + if (ret != 0) { + WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); + break; } + num -= RNG_MAX_BLOCK_LEN; + buf += RNG_MAX_BLOCK_LEN; } - } - if (p7out != NULL) { - XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } - if (sigBase64 != NULL) { - XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + if (ret == 0 && num) + ret = wc_RNG_GenerateBlock(rng, buf, (word32)num); - if (ret > 0) { - return WOLFSSL_SUCCESS; + if (ret != 0) + WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); + else + ret = WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; -} - -#endif /* HAVE_SMIME */ -#endif /* !NO_BIO */ -#endif /* OPENSSL_ALL */ - -#endif /* HAVE_PKCS7 */ -/******************************************************************************* - * END OF PKCS7 APIs - ******************************************************************************/ - -/******************************************************************************* - * START OF PKCS12 APIs - ******************************************************************************/ -#ifdef OPENSSL_EXTRA - -/* no-op function. Was initially used for adding encryption algorithms available - * for PKCS12 */ -void wolfSSL_PKCS12_PBE_add(void) -{ - WOLFSSL_ENTER("wolfSSL_PKCS12_PBE_add"); -} - -#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) -WOLFSSL_X509_PKCS12 *wolfSSL_d2i_PKCS12_fp(XFILE fp, - WOLFSSL_X509_PKCS12 **pkcs12) -{ - WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_fp"); - return (WOLFSSL_X509_PKCS12 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)pkcs12, - PKCS12_TYPE); -} -#endif /* !NO_FILESYSTEM */ - -#endif /* OPENSSL_EXTRA */ - -#if defined(HAVE_PKCS12) +#ifdef HAVE_GLOBAL_RNG + if (used_global == 1) + wc_UnLockMutex(&globalRNGMutex); +#endif + if (initTmpRng) + wc_FreeRng(tmpRNG); +#ifdef WOLFSSL_SMALL_STACK + if (tmpRNG) + XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); +#endif -#ifdef OPENSSL_EXTRA + return ret; +} -#if !defined(NO_ASN) && !defined(NO_PWDBASED) -#ifndef NO_BIO -WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12) +int wolfSSL_RAND_poll(void) { - WC_PKCS12* localPkcs12 = NULL; - unsigned char* mem = NULL; - long memSz; - int ret = -1; - - WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_bio"); + byte entropy[16]; + int ret = 0; + word32 entropy_sz = 16; - if (bio == NULL) { - WOLFSSL_MSG("Bad Function Argument bio is NULL"); - return NULL; + WOLFSSL_ENTER("wolfSSL_RAND_poll"); + if (initGlobalRNG == 0){ + WOLFSSL_MSG("Global RNG no Init"); + return WOLFSSL_FAILURE; } + ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz); + if (ret != 0){ + WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); + ret = WOLFSSL_FAILURE; + }else + ret = WOLFSSL_SUCCESS; - memSz = wolfSSL_BIO_get_len(bio); - if (memSz <= 0) { - return NULL; - } - mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (mem == NULL) { - return NULL; - } + return ret; +} - if (mem != NULL) { - localPkcs12 = wc_PKCS12_new(); - if (localPkcs12 == NULL) { - WOLFSSL_MSG("Memory error"); + /* If a valid struct is provided with function pointers, will override + RAND_seed, bytes, cleanup, add, pseudo_bytes and status. If a NULL + pointer is passed in, it will cancel any previous function overrides. + + Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */ + int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods) + { + #ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && + wc_LockMutex(&gRandMethodMutex) == 0) { + gRandMethods = methods; + wc_UnLockMutex(&gRandMethodMutex); + return WOLFSSL_SUCCESS; } + #else + (void)methods; + #endif + return WOLFSSL_FAILURE; } - if (mem != NULL && localPkcs12 != NULL) { - if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) { - ret = wc_d2i_PKCS12(mem, (word32)memSz, localPkcs12); - if (ret < 0) { - WOLFSSL_MSG("Failed to get PKCS12 sequence"); - } + /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */ + int wolfSSL_RAND_status(void) + { + int ret = WOLFSSL_SUCCESS; + #ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && + wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->status) + ret = gRandMethods->status(); + wc_UnLockMutex(&gRandMethodMutex); } else { - WOLFSSL_MSG("Failed to get data from bio struct"); + ret = WOLFSSL_FAILURE; } + #else + /* wolfCrypt provides enough seed internally, so return success */ + #endif + return ret; } - /* cleanup */ - if (mem != NULL) - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ret < 0 && localPkcs12 != NULL) { - wc_PKCS12_free(localPkcs12); - localPkcs12 = NULL; + void wolfSSL_RAND_add(const void* add, int len, double entropy) + { + #ifndef WOLFSSL_NO_OPENSSL_RAND_CB + if (wolfSSL_RAND_InitMutex() == 0 && + wc_LockMutex(&gRandMethodMutex) == 0) { + if (gRandMethods && gRandMethods->add) { + /* callback has return code, but RAND_add does not */ + (void)gRandMethods->add(add, len, entropy); + } + wc_UnLockMutex(&gRandMethodMutex); + } + #else + /* wolfSSL seeds/adds internally, use explicit RNG if you want + to take control */ + (void)add; + (void)len; + (void)entropy; + #endif } - if (pkcs12 != NULL) - *pkcs12 = localPkcs12; - return localPkcs12; + +#ifndef NO_WOLFSSL_STUB +void wolfSSL_RAND_screen(void) +{ + WOLFSSL_STUB("RAND_screen"); } +#endif -/* Converts the PKCS12 to DER format and outputs it into bio. - * - * bio is the structure to hold output DER - * pkcs12 structure to create DER from - * - * return 1 for success or 0 if an error occurs - */ -int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12) +int wolfSSL_RAND_load_file(const char* fname, long len) { - int ret = WOLFSSL_FAILURE; + (void)fname; + /* wolfCrypt provides enough entropy internally or will report error */ + if (len == -1) + return 1024; + else + return (int)len; +} - WOLFSSL_ENTER("wolfSSL_i2d_PKCS12_bio"); +#endif /* OPENSSL_EXTRA */ + +/******************************************************************************* + * END OF RAND API + ******************************************************************************/ - if ((bio != NULL) && (pkcs12 != NULL)) { - word32 certSz = 0; - byte *certDer = NULL; +/******************************************************************************* + * START OF EVP_CIPHER API + ******************************************************************************/ - certSz = wc_i2d_PKCS12(pkcs12, &certDer, NULL); - if ((certSz > 0) && (certDer != NULL)) { - if (wolfSSL_BIO_write(bio, certDer, certSz) == (int)certSz) { - ret = WOLFSSL_SUCCESS; - } - } +#ifdef OPENSSL_EXTRA - if (certDer != NULL) { - XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS); + /* store for external read of iv, WOLFSSL_SUCCESS on success */ + int wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx) + { + WOLFSSL_ENTER("wolfSSL_StoreExternalIV"); + + if (ctx == NULL) { + WOLFSSL_MSG("Bad function argument"); + return WOLFSSL_FATAL_ERROR; } - } - return ret; -} -#endif /* !NO_BIO */ + switch (ctx->cipherType) { +#ifndef NO_AES +#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + case AES_128_CBC_TYPE : + case AES_192_CBC_TYPE : + case AES_256_CBC_TYPE : + WOLFSSL_MSG("AES CBC"); + XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); + break; +#endif +#ifdef HAVE_AESGCM + case AES_128_GCM_TYPE : + case AES_192_GCM_TYPE : + case AES_256_GCM_TYPE : + WOLFSSL_MSG("AES GCM"); + XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); + break; +#endif /* HAVE_AESGCM */ +#ifdef HAVE_AESCCM + case AES_128_CCM_TYPE : + case AES_192_CCM_TYPE : + case AES_256_CCM_TYPE : + WOLFSSL_MSG("AES CCM"); + XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); + break; +#endif /* HAVE_AESCCM */ +#ifdef HAVE_AES_ECB + case AES_128_ECB_TYPE : + case AES_192_ECB_TYPE : + case AES_256_ECB_TYPE : + WOLFSSL_MSG("AES ECB"); + break; +#endif +#ifdef WOLFSSL_AES_COUNTER + case AES_128_CTR_TYPE : + case AES_192_CTR_TYPE : + case AES_256_CTR_TYPE : + WOLFSSL_MSG("AES CTR"); + XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); + break; +#endif /* WOLFSSL_AES_COUNTER */ +#ifdef WOLFSSL_AES_CFB +#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) + case AES_128_CFB1_TYPE: + case AES_192_CFB1_TYPE: + case AES_256_CFB1_TYPE: + WOLFSSL_MSG("AES CFB1"); + break; + case AES_128_CFB8_TYPE: + case AES_192_CFB8_TYPE: + case AES_256_CFB8_TYPE: + WOLFSSL_MSG("AES CFB8"); + break; +#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + case AES_128_CFB128_TYPE: + case AES_192_CFB128_TYPE: + case AES_256_CFB128_TYPE: + WOLFSSL_MSG("AES CFB128"); + break; +#endif /* WOLFSSL_AES_CFB */ +#if defined(WOLFSSL_AES_OFB) + case AES_128_OFB_TYPE: + case AES_192_OFB_TYPE: + case AES_256_OFB_TYPE: + WOLFSSL_MSG("AES OFB"); + break; +#endif /* WOLFSSL_AES_OFB */ +#ifdef WOLFSSL_AES_XTS + case AES_128_XTS_TYPE: + case AES_256_XTS_TYPE: + WOLFSSL_MSG("AES XTS"); + break; +#endif /* WOLFSSL_AES_XTS */ +#endif /* NO_AES */ -/* Creates a new WC_PKCS12 structure - * - * pass password to use - * name friendlyName to use - * pkey private key to go into PKCS12 bundle - * cert certificate to go into PKCS12 bundle - * ca extra certificates that can be added to bundle. Can be NULL - * keyNID type of encryption to use on the key (-1 means no encryption) - * certNID type of encryption to use on the certificate - * itt number of iterations with encryption - * macItt number of iterations with mac creation - * keyType flag for signature and/or encryption key - * - * returns a pointer to a new WC_PKCS12 structure on success and NULL on fail - */ -WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey, - WOLFSSL_X509* cert, WOLF_STACK_OF(WOLFSSL_X509)* ca, int keyNID, - int certNID, int itt, int macItt, int keyType) -{ - WC_PKCS12* pkcs12; - WC_DerCertList* list = NULL; - word32 passSz; - byte* keyDer = NULL; - word32 keyDerSz; - byte* certDer; - int certDerSz; - - WOLFSSL_ENTER("wolfSSL_PKCS12_create"); - - if (pass == NULL || pkey == NULL || cert == NULL) { - WOLFSSL_LEAVE("wolfSSL_PKCS12_create", BAD_FUNC_ARG); - return NULL; - } - passSz = (word32)XSTRLEN(pass); +#ifdef HAVE_ARIA + case ARIA_128_GCM_TYPE : + case ARIA_192_GCM_TYPE : + case ARIA_256_GCM_TYPE : + WOLFSSL_MSG("ARIA GCM"); + XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE); + break; +#endif /* HAVE_ARIA */ - keyDer = (byte*)pkey->pkey.ptr; - keyDerSz = pkey->pkey_sz; +#ifndef NO_DES3 + case DES_CBC_TYPE : + WOLFSSL_MSG("DES CBC"); + XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE); + break; - certDer = (byte*)wolfSSL_X509_get_der(cert, &certDerSz); - if (certDer == NULL) { - return NULL; - } + case DES_EDE3_CBC_TYPE : + WOLFSSL_MSG("DES EDE3 CBC"); + XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE); + break; +#endif +#ifdef WOLFSSL_DES_ECB + case DES_ECB_TYPE : + WOLFSSL_MSG("DES ECB"); + break; + case DES_EDE3_ECB_TYPE : + WOLFSSL_MSG("DES3 ECB"); + break; +#endif + case ARC4_TYPE : + WOLFSSL_MSG("ARC4"); + break; - if (ca != NULL) { - unsigned long numCerts = ca->num; - WOLFSSL_STACK* sk = ca; +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + case CHACHA20_POLY1305_TYPE: + break; +#endif - while (numCerts > 0 && sk != NULL) { - byte* curDer; - WC_DerCertList* cur; - int curDerSz = 0; +#ifdef HAVE_CHACHA + case CHACHA20_TYPE: + break; +#endif - cur = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList), NULL, - DYNAMIC_TYPE_PKCS); - if (cur == NULL) { - wc_FreeCertList(list, NULL); - return NULL; - } +#ifdef WOLFSSL_SM4_ECB + case SM4_ECB_TYPE: + break; +#endif +#ifdef WOLFSSL_SM4_CBC + case SM4_CBC_TYPE: + WOLFSSL_MSG("SM4 CBC"); + XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); + break; +#endif +#ifdef WOLFSSL_SM4_CTR + case SM4_CTR_TYPE: + WOLFSSL_MSG("SM4 CTR"); + XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); + break; +#endif +#ifdef WOLFSSL_SM4_GCM + case SM4_GCM_TYPE: + WOLFSSL_MSG("SM4 GCM"); + XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); + break; +#endif +#ifdef WOLFSSL_SM4_CCM + case SM4_CCM_TYPE: + WOLFSSL_MSG("SM4 CCM"); + XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); + break; +#endif - curDer = (byte*)wolfSSL_X509_get_der(sk->data.x509, &curDerSz); - if (curDer == NULL || curDerSz < 0) { - XFREE(cur, NULL, DYNAMIC_TYPE_PKCS); - wc_FreeCertList(list, NULL); - return NULL; - } + case NULL_CIPHER_TYPE : + WOLFSSL_MSG("NULL"); + break; - cur->buffer = (byte*)XMALLOC(curDerSz, NULL, DYNAMIC_TYPE_PKCS); - if (cur->buffer == NULL) { - XFREE(cur, NULL, DYNAMIC_TYPE_PKCS); - wc_FreeCertList(list, NULL); - return NULL; + default: { + WOLFSSL_MSG("bad type"); + return WOLFSSL_FATAL_ERROR; } - XMEMCPY(cur->buffer, curDer, curDerSz); - cur->bufferSz = curDerSz; - cur->next = list; - list = cur; - - sk = sk->next; - numCerts--; } + return WOLFSSL_SUCCESS; } - pkcs12 = wc_PKCS12_create(pass, passSz, name, keyDer, keyDerSz, - certDer, certDerSz, list, keyNID, certNID, itt, macItt, - keyType, NULL); + /* set internal IV from external, WOLFSSL_SUCCESS on success */ + int wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx) + { - if (ca != NULL) { - wc_FreeCertList(list, NULL); - } + WOLFSSL_ENTER("wolfSSL_SetInternalIV"); - return pkcs12; -} + if (ctx == NULL) { + WOLFSSL_MSG("Bad function argument"); + return WOLFSSL_FATAL_ERROR; + } + switch (ctx->cipherType) { -/* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure */ -int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, - WOLFSSL_EVP_PKEY** pkey, WOLFSSL_X509** cert, - WOLF_STACK_OF(WOLFSSL_X509)** ca) -{ - void* heap = NULL; - int ret; - byte* certData = NULL; - word32 certDataSz; - byte* pk = NULL; - word32 pkSz; - WC_DerCertList* certList = NULL; -#ifdef WOLFSSL_SMALL_STACK - DecodedCert *DeCert; -#else - DecodedCert DeCert[1]; +#ifndef NO_AES +#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + case AES_128_CBC_TYPE : + case AES_192_CBC_TYPE : + case AES_256_CBC_TYPE : + WOLFSSL_MSG("AES CBC"); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + break; #endif - - WOLFSSL_ENTER("wolfSSL_PKCS12_parse"); - - /* make sure we init return args */ - if (pkey) *pkey = NULL; - if (cert) *cert = NULL; - if (ca) *ca = NULL; - - if (pkcs12 == NULL || psw == NULL || pkey == NULL || cert == NULL) { - WOLFSSL_MSG("Bad argument value"); - return WOLFSSL_FAILURE; - } - - heap = wc_PKCS12_GetHeap(pkcs12); - - if (ca == NULL) { - ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz, - NULL); - } - else { - ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz, - &certList); - } - if (ret < 0) { - WOLFSSL_LEAVE("wolfSSL_PKCS12_parse", ret); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - DeCert = (DecodedCert *)XMALLOC(sizeof(*DeCert), heap, - DYNAMIC_TYPE_DCERT); - if (DeCert == NULL) { - WOLFSSL_MSG("out of memory"); - return WOLFSSL_FAILURE; - } +#ifdef HAVE_AESGCM + case AES_128_GCM_TYPE : + case AES_192_GCM_TYPE : + case AES_256_GCM_TYPE : + WOLFSSL_MSG("AES GCM"); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + break; +#endif +#ifdef HAVE_AES_ECB + case AES_128_ECB_TYPE : + case AES_192_ECB_TYPE : + case AES_256_ECB_TYPE : + WOLFSSL_MSG("AES ECB"); + break; +#endif +#ifdef WOLFSSL_AES_COUNTER + case AES_128_CTR_TYPE : + case AES_192_CTR_TYPE : + case AES_256_CTR_TYPE : + WOLFSSL_MSG("AES CTR"); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + break; #endif - /* Decode cert and place in X509 stack struct */ - if (certList != NULL) { - WC_DerCertList* current = certList; - - *ca = (WOLF_STACK_OF(WOLFSSL_X509)*)XMALLOC( - sizeof(WOLF_STACK_OF(WOLFSSL_X509)), heap, DYNAMIC_TYPE_X509); - if (*ca == NULL) { - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } - /* Free up WC_DerCertList and move on */ - while (current != NULL) { - WC_DerCertList* next = current->next; +#endif /* NO_AES */ - XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); - XFREE(current, heap, DYNAMIC_TYPE_PKCS); - current = next; - } - ret = WOLFSSL_FAILURE; - goto out; - } - XMEMSET(*ca, 0, sizeof(WOLF_STACK_OF(WOLFSSL_X509))); +#ifdef HAVE_ARIA + case ARIA_128_GCM_TYPE : + case ARIA_192_GCM_TYPE : + case ARIA_256_GCM_TYPE : + WOLFSSL_MSG("ARIA GCM"); + XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE); + break; +#endif /* HAVE_ARIA */ - /* add list of DER certs as X509's to stack */ - while (current != NULL) { - WC_DerCertList* toFree = current; - WOLFSSL_X509* x509; +#ifndef NO_DES3 + case DES_CBC_TYPE : + WOLFSSL_MSG("DES CBC"); + XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE); + break; - x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, - DYNAMIC_TYPE_X509); - InitX509(x509, 1, heap); - InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap); - if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL) != 0) { - WOLFSSL_MSG("Issue with parsing certificate"); - FreeDecodedCert(DeCert); - wolfSSL_X509_free(x509); - } - else { - if (CopyDecodedToX509(x509, DeCert) != 0) { - WOLFSSL_MSG("Failed to copy decoded cert"); - FreeDecodedCert(DeCert); - wolfSSL_X509_free(x509); - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } - /* Free up WC_DerCertList */ - while (current != NULL) { - WC_DerCertList* next = current->next; + case DES_EDE3_CBC_TYPE : + WOLFSSL_MSG("DES EDE3 CBC"); + XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE); + break; +#endif +#ifdef WOLFSSL_DES_ECB + case DES_ECB_TYPE : + WOLFSSL_MSG("DES ECB"); + break; + case DES_EDE3_ECB_TYPE : + WOLFSSL_MSG("DES3 ECB"); + break; +#endif - XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); - XFREE(current, heap, DYNAMIC_TYPE_PKCS); - current = next; - } - ret = WOLFSSL_FAILURE; - goto out; - } - FreeDecodedCert(DeCert); + case ARC4_TYPE : + WOLFSSL_MSG("ARC4"); + break; - if (wolfSSL_sk_X509_push(*ca, x509) != 1) { - WOLFSSL_MSG("Failed to push x509 onto stack"); - wolfSSL_X509_free(x509); - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + case CHACHA20_POLY1305_TYPE: + break; +#endif - /* Free up WC_DerCertList */ - while (current != NULL) { - WC_DerCertList* next = current->next; +#ifdef HAVE_CHACHA + case CHACHA20_TYPE: + break; +#endif - XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); - XFREE(current, heap, DYNAMIC_TYPE_PKCS); - current = next; - } - ret = WOLFSSL_FAILURE; - goto out; - } - } - current = current->next; - XFREE(toFree->buffer, heap, DYNAMIC_TYPE_PKCS); - XFREE(toFree, heap, DYNAMIC_TYPE_PKCS); - } - } +#ifdef WOLFSSL_SM4_ECB + case SM4_ECB_TYPE: + break; +#endif +#ifdef WOLFSSL_SM4_CBC + case SM4_CBC_TYPE: + WOLFSSL_MSG("SM4 CBC"); + XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); + break; +#endif +#ifdef WOLFSSL_SM4_CTR + case SM4_CTR_TYPE: + WOLFSSL_MSG("SM4 CTR"); + XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); + break; +#endif +#ifdef WOLFSSL_SM4_GCM + case SM4_GCM_TYPE: + WOLFSSL_MSG("SM4 GCM"); + XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); + break; +#endif +#ifdef WOLFSSL_SM4_CCM + case SM4_CCM_TYPE: + WOLFSSL_MSG("SM4 CCM"); + XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); + break; +#endif + case NULL_CIPHER_TYPE : + WOLFSSL_MSG("NULL"); + break; - /* Decode cert and place in X509 struct */ - if (certData != NULL) { - *cert = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, - DYNAMIC_TYPE_X509); - if (*cert == NULL) { - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (ca != NULL) { - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - } - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - ret = WOLFSSL_FAILURE; - goto out; - } - InitX509(*cert, 1, heap); - InitDecodedCert(DeCert, certData, certDataSz, heap); - if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL) != 0) { - WOLFSSL_MSG("Issue with parsing certificate"); - } - if (CopyDecodedToX509(*cert, DeCert) != 0) { - WOLFSSL_MSG("Failed to copy decoded cert"); - FreeDecodedCert(DeCert); - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (ca != NULL) { - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + default: { + WOLFSSL_MSG("bad type"); + return WOLFSSL_FATAL_ERROR; } - wolfSSL_X509_free(*cert); *cert = NULL; - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - ret = WOLFSSL_FAILURE; - goto out; } - FreeDecodedCert(DeCert); - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + return WOLFSSL_SUCCESS; } +#ifndef NO_DES3 - /* get key type */ - ret = BAD_STATE_E; - if (pk != NULL) { /* decode key if present */ - *pkey = wolfSSL_EVP_PKEY_new_ex(heap); - if (*pkey == NULL) { - wolfSSL_X509_free(*cert); *cert = NULL; - if (ca != NULL) { - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - } - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - ret = WOLFSSL_FAILURE; - goto out; - } - - #ifndef NO_RSA - { - const unsigned char* pt = pk; - if (wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, pkey, &pt, pkSz) != - NULL) { - ret = 0; - } - } - #endif /* NO_RSA */ +void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, + unsigned char* iv, int len) +{ + (void)len; - #ifdef HAVE_ECC - if (ret != 0) { /* if is in fail state check if ECC key */ - const unsigned char* pt = pk; - if (wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, pkey, &pt, pkSz) != - NULL) { - ret = 0; - } - } - #endif /* HAVE_ECC */ - if (pk != NULL) - XFREE(pk, heap, DYNAMIC_TYPE_PKCS); - if (ret != 0) { /* if is in fail state and no PKEY then fail */ - wolfSSL_X509_free(*cert); *cert = NULL; - if (ca != NULL) { - wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - } - wolfSSL_EVP_PKEY_free(*pkey); *pkey = NULL; - WOLFSSL_MSG("Bad PKCS12 key format"); - ret = WOLFSSL_FAILURE; - goto out; - } + WOLFSSL_MSG("wolfSSL_3des_iv"); - if (pkey != NULL && *pkey != NULL) { - (*pkey)->save_type = 0; - } + if (ctx == NULL || iv == NULL) { + WOLFSSL_MSG("Bad function argument"); + return; } - (void)ret; - (void)ca; - - ret = WOLFSSL_SUCCESS; + if (doset) + wc_Des3_SetIV(&ctx->cipher.des3, iv); /* OpenSSL compat, no ret */ + else + XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE); +} -out: +#endif /* NO_DES3 */ -#ifdef WOLFSSL_SMALL_STACK - XFREE(DeCert, heap, DYNAMIC_TYPE_DCERT); -#endif - return ret; -} +#ifndef NO_AES -int wolfSSL_PKCS12_verify_mac(WC_PKCS12 *pkcs12, const char *psw, - int pswLen) +void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, + unsigned char* iv, int len) { - WOLFSSL_ENTER("wolfSSL_PKCS12_verify_mac"); + (void)len; - if (!pkcs12) { - return WOLFSSL_FAILURE; + WOLFSSL_MSG("wolfSSL_aes_ctr_iv"); + + if (ctx == NULL || iv == NULL) { + WOLFSSL_MSG("Bad function argument"); + return; } - return wc_PKCS12_verify_ex(pkcs12, (const byte*)psw, pswLen) == 0 ? - WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + if (doset) + (void)wc_AesSetIV(&ctx->cipher.aes, iv); /* OpenSSL compat, no ret */ + else + XMEMCPY(iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); } -#endif /* !NO_ASN && !NO_PWDBASED */ +#endif /* NO_AES */ #endif /* OPENSSL_EXTRA */ -#endif /* HAVE_PKCS12 */ /******************************************************************************* - * END OF PKCS12 APIs + * END OF EVP_CIPHER API ******************************************************************************/ +#ifndef NO_CERTS + +#define WOLFSSL_X509_STORE_INCLUDED +#include + +#define WOLFSSL_SSL_P7P12_INCLUDED +#include + #endif /* !NO_CERTS */ @@ -36036,7 +24630,7 @@ int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags) if (ctx != NULL) { XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX)); ctx->type = type; - ctx->xflags = flags; + ctx->xflags = (int)flags; ctx->status = DRBG_STATUS_UNINITIALISED; ret = WOLFSSL_SUCCESS; } diff --git a/src/src/ssl_asn1.c b/src/src/ssl_asn1.c index eecf467..b93d8d5 100644 --- a/src/src/ssl_asn1.c +++ b/src/src/ssl_asn1.c @@ -247,6 +247,11 @@ static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) len = 0; } + if (len < 0) { + len = 0; /* wolfSSL_i2d_ASN1_INTEGER can return a value less than 0 + * on error */ + } + return len; } @@ -974,7 +979,8 @@ static int wolfssl_a2i_asn1_integer_clear_to_eol(char* str, int len, int* cont) nLen = 1; for (i = 0; i < len; i++) { /* Check if character is a hexadecimal character. */ - if (Base16_Decode((const byte*)str + i, 1, &num, &nLen) == ASN_INPUT_E) + if (Base16_Decode((const byte*)str + i, 1, &num, &nLen) == + WC_NO_ERR_TRACE(ASN_INPUT_E)) { /* Found end of hexadecimal characters, return count. */ len = i; @@ -2997,7 +3003,7 @@ void wolfSSL_ASN1_GENERALIZEDTIME_free(WOLFSSL_ASN1_TIME* asn1Time) { WOLFSSL_ENTER("wolfSSL_ASN1_GENERALIZEDTIME_free"); if (asn1Time != NULL) { - XMEMSET(asn1Time->data, 0, sizeof(asn1Time->data)); + XFREE(asn1Time, NULL, DYNAMIC_TYPE_OPENSSL); } } @@ -3509,14 +3515,17 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, if (ret != NULL) { /* Set the ASN.1 type and length of string. */ ret->type = V_ASN1_GENERALIZEDTIME; - ret->length = ASN_GENERALIZED_TIME_SIZE; if (t->type == V_ASN1_GENERALIZEDTIME) { + ret->length = ASN_GENERALIZED_TIME_SIZE; + /* Just copy as data already appropriately formatted. */ XMEMCPY(ret->data, t->data, ASN_GENERALIZED_TIME_SIZE); } else { /* Convert UTC TIME to GENERALIZED TIME. */ + ret->length = t->length + 2; /* Add two extra year digits */ + if (t->data[0] >= '5') { /* >= 50 is 1900s. */ ret->data[0] = '1'; ret->data[1] = '9'; @@ -3526,7 +3535,7 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, ret->data[0] = '2'; ret->data[1] = '0'; } /* Append rest of the data as it is the same. */ - XMEMCPY(&ret->data[2], t->data, ASN_UTC_TIME_SIZE); + XMEMCPY(&ret->data[2], t->data, t->length); } /* Check for pointer to return result through. */ @@ -3538,6 +3547,32 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, return ret; } +WOLFSSL_ASN1_TIME* wolfSSL_ASN1_UTCTIME_set(WOLFSSL_ASN1_TIME *s, time_t t) +{ + WOLFSSL_ASN1_TIME* ret = s; + + WOLFSSL_ENTER("wolfSSL_ASN1_UTCTIME_set"); + + if (ret == NULL) { + ret = wolfSSL_ASN1_TIME_new(); + if (ret == NULL) + return NULL; + } + + ret->length = GetFormattedTime(&t, ret->data, sizeof(ret->data)); + if (ret->length + 1 != ASN_UTC_TIME_SIZE) { + /* Either snprintf error or t can't be represented in UTC format */ + if (ret != s) + wolfSSL_ASN1_TIME_free(ret); + ret = NULL; + } + else { + ret->type = V_ASN1_UTCTIME; + } + + return ret; +} + #endif /* OPENSSL_EXTRA */ #if defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) diff --git a/src/src/ssl_bn.c b/src/src/ssl_bn.c index cbb4a92..c025755 100644 --- a/src/src/ssl_bn.c +++ b/src/src/ssl_bn.c @@ -25,7 +25,7 @@ #include - #include +#include #ifndef WC_NO_RNG #include #endif diff --git a/src/src/ssl_certman.c b/src/src/ssl_certman.c index e074996..e666059 100644 --- a/src/src/ssl_certman.c +++ b/src/src/ssl_certman.c @@ -141,14 +141,12 @@ WOLFSSL_CERT_MANAGER* wolfSSL_CertManagerNew_ex(void* heap) #ifdef HAVE_ECC cm->minEccKeySz = MIN_ECCKEY_SZ; #endif - #ifdef HAVE_PQC #ifdef HAVE_FALCON cm->minFalconKeySz = MIN_FALCONKEY_SZ; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM cm->minDilithiumKeySz = MIN_DILITHIUMKEY_SZ; #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ /* Set heap hint to use in certificate manager operations. */ cm->heap = heap; @@ -700,7 +698,7 @@ int CM_VerifyBuffer_ex(WOLFSSL_CERT_MANAGER* cm, const unsigned char* buff, /* Parse DER into decoded certificate fields and verify signature * against a known CA. */ - ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, cm); + ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, cm, NULL); } #ifdef HAVE_CRL @@ -1819,7 +1817,7 @@ int wolfSSL_CertManagerCheckCRL(WOLFSSL_CERT_MANAGER* cm, InitDecodedCert(cert, der, (word32)sz, NULL); /* Parse certificate and perform CRL checks. */ - ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_CRL, cm); + ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_CRL, cm, NULL); if (ret != 0) { WOLFSSL_MSG("ParseCert failed"); } @@ -2291,7 +2289,7 @@ int wolfSSL_CertManagerCheckOCSP(WOLFSSL_CERT_MANAGER* cm, InitDecodedCert(cert, der, (word32)sz, NULL); /* Parse certificate and perform CRL checks. */ - ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_OCSP, cm); + ret = ParseCertRelative(cert, CERT_TYPE, VERIFY_OCSP, cm, NULL); if (ret != 0) { WOLFSSL_MSG("ParseCert failed"); } diff --git a/src/src/ssl_crypto.c b/src/src/ssl_crypto.c index 3c73b88..5a05324 100644 --- a/src/src/ssl_crypto.c +++ b/src/src/ssl_crypto.c @@ -1966,7 +1966,7 @@ int wolfSSL_HMAC_cleanup(WOLFSSL_HMAC_CTX* ctx) * @return NULL on failure. */ unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, - int key_len, const unsigned char* data, int len, unsigned char* md, + int key_len, const unsigned char* data, size_t len, unsigned char* md, unsigned int* md_len) { unsigned char* ret = NULL; @@ -2000,7 +2000,7 @@ unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, #endif if (rc == 0) { /* Get the HMAC output length. */ - hmacLen = wolfssl_mac_len((unsigned char)type); + hmacLen = (int)wolfssl_mac_len((unsigned char)type); /* 0 indicates the digest is not supported. */ if (hmacLen == 0) { rc = BAD_FUNC_ARG; @@ -2009,16 +2009,16 @@ unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, /* Initialize the wolfSSL HMAC object. */ if ((rc == 0) && (wc_HmacInit(hmac, heap, INVALID_DEVID) == 0)) { /* Set the key into the wolfSSL HMAC object. */ - rc = wc_HmacSetKey(hmac, type, (const byte*)key, key_len); + rc = wc_HmacSetKey(hmac, type, (const byte*)key, (word32)key_len); if (rc == 0) { /* Update the wolfSSL HMAC object with data. */ - rc = wc_HmacUpdate(hmac, data, len); + rc = wc_HmacUpdate(hmac, data, (word32)len); } /* Finalize the wolfSSL HMAC object. */ if ((rc == 0) && (wc_HmacFinal(hmac, md) == 0)) { /* Return the length of the HMAC output if required. */ if (md_len != NULL) { - *md_len = hmacLen; + *md_len = (unsigned int)hmacLen; } /* Set the buffer to return. */ ret = md; @@ -2269,7 +2269,7 @@ int wolfSSL_CMAC_Final(WOLFSSL_CMAC_CTX* ctx, unsigned char* out, size_t* len) len32 = (word32)blockSize; /* Return size if required. */ if (len != NULL) { - *len = blockSize; + *len = (size_t)blockSize; } } } diff --git a/src/src/ssl_load.c b/src/src/ssl_load.c new file mode 100644 index 0000000..2441d48 --- /dev/null +++ b/src/src/ssl_load.c @@ -0,0 +1,5831 @@ +/* ssl_load.c + * + * Copyright (C) 2006-2023 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +/* + * WOLFSSL_SYS_CA_CERTS + * Enables ability to load system CA certs from the OS via + * wolfSSL_CTX_load_system_CA_certs. + */ + +#ifdef WOLFSSL_SYS_CA_CERTS + +#ifdef _WIN32 + #include + #include + + /* mingw gcc does not support pragma comment, and the + * linking with crypt32 is handled in configure.ac */ + #if !defined(__MINGW32__) && !defined(__MINGW64__) + #pragma comment(lib, "crypt32") + #endif +#endif + +#if defined(__APPLE__) && defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) +#include +#endif + +#endif /* WOLFSSL_SYS_CA_CERTS */ + +#if !defined(WOLFSSL_SSL_LOAD_INCLUDED) + #ifndef WOLFSSL_IGNORE_FILE_WARN + #warning ssl_load.c does not need to be compiled separately from ssl.c + #endif +#else + +#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) + /* PSK field of context when it exists. */ + #define CTX_HAVE_PSK(ctx) (ctx)->havePSK + /* PSK field of ssl when it exists. */ + #define SSL_HAVE_PSK(ssl) (ssl)->options.havePSK +#else + /* Have PSK value when no field. */ + #define CTX_HAVE_PSK(ctx) 0 + /* Have PSK value when no field. */ + #define SSL_HAVE_PSK(ssl) 0 +#endif +#ifdef NO_RSA + /* Boolean for RSA available. */ + #define WOLFSSL_HAVE_RSA 0 +#else + /* Boolean for RSA available. */ + #define WOLFSSL_HAVE_RSA 1 +#endif +#ifndef NO_CERTS + /* Private key size from ssl. */ + #define SSL_KEY_SZ(ssl) (ssl)->buffers.keySz +#else + /* Private key size not available. */ + #define SSL_KEY_SZ(ssl) 0 +#endif +#ifdef HAVE_ANON + /* Anonymous ciphersuite allowed field in context. */ + #define CTX_USE_ANON(ctx) (ctx)->useAnon +#else + /* Anonymous ciphersuite allowed field not in context. */ + #define CTX_USE_ANON(ctx) 0 +#endif + +#ifdef HAVE_PK_CALLBACKS + #define WOLFSSL_IS_PRIV_PK_SET(ctx, ssl) \ + wolfSSL_CTX_IsPrivatePkSet(((ssl) == NULL) ? (ctx) : (ssl)->ctx) +#else + #define WOLFSSL_IS_PRIV_PK_SET(ctx, ssl) 0 +#endif + +/* Get the heap from the context or the ssl depending on which is available. */ +#define WOLFSSL_HEAP(ctx, ssl) \ + (((ctx) != NULL) ? (ctx)->heap : (((ssl) != NULL) ? (ssl)->heap : NULL)) + + +#ifndef NO_CERTS + +/* Get DER encoding from data in a buffer as a DerBuffer. + * + * @param [in] buff Buffer containing data. + * @param [in] len Length of data in buffer. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @param [in] type Type of data: + * CERT_TYPE, CA_TYPE, TRUSTED_PEER_TYPE, + * PRIVATEKEY_TYPE or ALT_PRIVATEKEY_TYPE. + * @param [in, out] info Info for encryption. + * @param [in] heap Dynamic memory allocation hint. + * @param [out] der Holds DER encoded data. + * @param [out] algId Algorithm identifier for private keys. + * @return 0 on success. + * @return NOT_COMPILED_IN when format is PEM and PEM not supported. + * @return ASN_PARSE_E when format is ASN.1 and invalid DER encoding. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int DataToDerBuffer(const unsigned char* buff, word32 len, int format, + int type, EncryptedInfo* info, void* heap, DerBuffer** der, int* algId) +{ + int ret; + + info->consumed = 0; + + /* Data in buffer has PEM format - extract DER data. */ + if (format == WOLFSSL_FILETYPE_PEM) { + #ifdef WOLFSSL_PEM_TO_DER + ret = PemToDer(buff, len, type, der, heap, info, algId); + if (ret != 0) { + FreeDer(der); + } + #else + ret = NOT_COMPILED_IN; + #endif + } + /* Data in buffer is ASN.1 format - get first SEQ or OCT into der. */ + else { + int length; + word32 inOutIdx = 0; + + /* Get length of SEQ including header. */ + if ((info->consumed = wolfssl_der_length(buff, (int)len)) > 0) { + ret = 0; + } + /* Private keys may be wrapped in OCT when PKCS#8 wrapper removed. + * TODO: is this really needed? */ + else if ((type == PRIVATEKEY_TYPE) && + (GetOctetString(buff, &inOutIdx, &length, len) >= 0)) { + /* Include octet string DER header. */ + info->consumed = length + inOutIdx; + ret = 0; + } + else { + ret = ASN_PARSE_E; + } + + if (info->consumed > (int)len) { + ret = ASN_PARSE_E; + } + if (ret == 0) { + ret = AllocCopyDer(der, buff, (word32)info->consumed, type, heap); + } + } + + return ret; +} + +/* Process a user's certificate. + * + * Puts the 3-byte length before certificate data as required for TLS. + * CA certificates are added to the certificate manager. + * + * @param [in] cm Certificate manager. + * @param [in, out] pDer DER encoded data. + * @param [in] type Type of data. Valid values: + * CERT_TYPE, CA_TYPE or TRUSTED_PEER_TYPE. + * @param [in] verify How to verify certificate. + * @param [out] chainBuffer Buffer to hold chain of certificates. + * @param [in, out] pIdx On in, current index into chainBuffer. + * On out, index after certificate added. + * @param [in] bufferSz Size of buffer in bytes. + * @return 0 on success. + * @return BUFFER_E if chain buffer not big enough to hold certificate. + */ +static int ProcessUserCert(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, + int type, int verify, byte* chainBuffer, word32* pIdx, word32 bufferSz) +{ + int ret = 0; + word32 idx = *pIdx; + DerBuffer* der = *pDer; + + /* Check there is space for certificate in chainBuffer. */ + if ((ret == 0) && ((idx + der->length + CERT_HEADER_SZ) > bufferSz)) { + WOLFSSL_MSG(" Cert Chain bigger than buffer. " + "Consider increasing MAX_CHAIN_DEPTH"); + ret = BUFFER_E; + } + if (ret == 0) { + /* 3-byte length. */ + c32to24(der->length, &chainBuffer[idx]); + idx += CERT_HEADER_SZ; + /* Add complete DER encoded certificate. */ + XMEMCPY(&chainBuffer[idx], der->buffer, der->length); + idx += der->length; + + if (type == CA_TYPE) { + /* Add CA to certificate manager */ + ret = AddCA(cm, pDer, WOLFSSL_USER_CA, verify); + if (ret == 1) { + ret = 0; + } + } + } + + /* Update the index into chainBuffer. */ + *pIdx = idx; + return ret; +} + +/* Store the certificate chain buffer aganst WOLFSSL_CTX or WOLFSSL object. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] chainBuffer Buffer containing chain of certificates. + * @param [in] len Length, in bytes, of data in buffer. + * @param [in] cnt Number of certificates in chain. + * @param [in] type Type of data. Valid values: + * CERT_TYPE, CA_TYPE or CHAIN_CERT_TYPE. + * @param [in] heap Dynamic memory allocation hint. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int ProcessUserChainRetain(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const byte* chainBuffer, word32 len, int cnt, int type, void* heap) +{ + int ret = 0; + + (void)cnt; + + /* Store in SSL object if available. */ + if (ssl != NULL) { + /* Dispose of old chain if not reference to context's. */ + if (ssl->buffers.weOwnCertChain) { + FreeDer(&ssl->buffers.certChain); + } + /* Allocate and copy the buffer into SSL object. */ + ret = AllocCopyDer(&ssl->buffers.certChain, chainBuffer, len, type, + heap); + ssl->buffers.weOwnCertChain = (ret == 0); + #ifdef WOLFSSL_TLS13 + /* Update count of certificates in chain. */ + ssl->buffers.certChainCnt = cnt; + #endif + } + /* Store in SSL context object if available. */ + else if (ctx != NULL) { + /* Dispose of old chain and allocate and copy in new chain. */ + FreeDer(&ctx->certChain); + /* Allocate and copy the buffer into SSL context object. */ + ret = AllocCopyDer(&ctx->certChain, chainBuffer, len, type, heap); + #ifdef WOLFSSL_TLS13 + /* Update count of certificates in chain. */ + ctx->certChainCnt = cnt; + #endif + } + + return ret; +} + +/* Process user cert chain to pass during the TLS handshake. + * + * If not a certificate type then data is ignored. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] buff Buffer holding certificates. + * @param [in] sz Length of data in buffer. + * @param [in] format Format of the certificate: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1 + * @param [in] type Type of certificate: + * CA_TYPE, CERT_TYPE or CHAIN_CERT_TYPE + * @param [out] used Number of bytes from buff used. + * @param [in, out] info Encryption information. + * @param [in] verify How to verify certificate. + * @return 0 on success. + * @return BAD_FUNC_ARG when type is CA_TYPE and ctx is NULL. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int ProcessUserChain(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const unsigned char* buff, long sz, int format, int type, long* used, + EncryptedInfo* info, int verify) +{ + int ret = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); + + WOLFSSL_ENTER("ProcessUserChain"); + + /* Validate parameters. */ + if ((type == CA_TYPE) && (ctx == NULL)) { + WOLFSSL_MSG("Need context for CA load"); + ret = BAD_FUNC_ARG; + } + + /* Ignore non-certificate types. */ + if ((ret == 0) && (type != CERT_TYPE) && (type != CHAIN_CERT_TYPE) && + (type != CA_TYPE)) { + WOLFSSL_MSG("File type not a certificate"); + } + /* Check we haven't consumed all the data. */ + else if ((ret == 0) && (info->consumed >= sz)) { + WOLFSSL_MSG("Already consumed data"); + } + else if (ret == 0) { + #ifndef WOLFSSL_SMALL_STACK + byte stackBuffer[FILE_BUFFER_SIZE]; + #endif + StaticBuffer chain; + long consumed = info->consumed; + word32 idx = 0; + int gotOne = 0; + int cnt = 0; + /* Calculate max possible size, including max headers */ + long maxSz = (sz - consumed) + (CERT_HEADER_SZ * MAX_CHAIN_DEPTH); + + /* Setup buffer to hold chain. */ + #ifdef WOLFSSL_SMALL_STACK + static_buffer_init(&chain); + #else + static_buffer_init(&chain, stackBuffer, FILE_BUFFER_SIZE); + #endif + /* Make buffer big enough to support maximum size. */ + ret = static_buffer_set_size(&chain, (word32)maxSz, heap, + DYNAMIC_TYPE_FILE); + + WOLFSSL_MSG("Processing Cert Chain"); + /* Keep parsing certificates will data available. */ + while ((ret == 0) && (consumed < sz)) { + DerBuffer* part = NULL; + + /* Get a certificate as DER. */ + ret = DataToDerBuffer(buff + consumed, (word32)(sz - consumed), + format, type, info, heap, &part, NULL); + if (ret == 0) { + /* Process the user certificate. */ + ret = ProcessUserCert(ctx->cm, &part, type, verify, + chain.buffer, &idx, (word32)maxSz); + } + /* PEM may have trailing data that can be ignored. */ + if ((ret == WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) && gotOne) { + WOLFSSL_MSG("We got one good cert, so stuff at end ok"); + ret = 0; + break; + } + /* Certificate data handled. */ + FreeDer(&part); + + if (ret == 0) { + /* Update consumed length. */ + consumed += info->consumed; + WOLFSSL_MSG(" Consumed another Cert in Chain"); + /* Update whether we got a user certificate. */ + gotOne |= (type != CA_TYPE); + /* Update count of certificates added to chain. */ + cnt++; + } + } + if (used != NULL) { + /* Return the total consumed length. */ + *used = consumed; + } + + /* Check whether there is data in the chain buffer. */ + if ((ret == 0) && (idx > 0)) { + /* Put the chain buffer against the SSL or SSL context object. */ + ret = ProcessUserChainRetain(ctx, ssl, chain.buffer, idx, cnt, type, + heap); + } + + /* Dispose of chain buffer. */ + static_buffer_free(&chain, heap, DYNAMIC_TYPE_FILE); + } + + WOLFSSL_LEAVE("ProcessUserChain", ret); + return ret; +} + +#ifndef NO_RSA +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) +/* See if DER data is an RSA private key. + * + * Checks size meets minimum RSA key size. + * This implementation uses less dynamic memory. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an RSA key and format unknown. + * @return RSA_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, int devId, byte* keyType, int* keySize) +{ + int ret; + word32 idx; + int keySz = 0; + + (void)devId; + + /* Validate we have an RSA private key and get key size. */ + idx = 0; + ret = wc_RsaPrivateKeyValidate(der->buffer, &idx, &keySz, der->length); +#ifdef WOLF_PRIVATE_KEY_ID + /* If that didn't work then maybe a public key if device ID or callback. */ + if ((ret != 0) && ((devId != INVALID_DEVID) || + WOLFSSL_IS_PRIV_PK_SET(ctx, ssl))) { + word32 nSz; + + /* Decode as an RSA public key. */ + idx = 0; + ret = wc_RsaPublicKeyDecode_ex(der->buffer, &idx, der->length, NULL, + &nSz, NULL, NULL); + if (ret == 0) { + keySz = (int)nSz; + } + } +#endif + if (ret == 0) { + /* Get the minimum RSA key size from SSL or SSL context object. */ + int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; + + /* Format, type and size are known. */ + *keyFormat = RSAk; + *keyType = rsa_sa_algo; + *keySize = keySz; + + /* Check that the size of the RSA key is enough. */ + if (keySz < minRsaSz) { + WOLFSSL_MSG("Private Key size too small"); + ret = RSA_KEY_SIZE_E; + } + /* No static ECC key possible. */ + if ((ssl != NULL) && (ssl->options.side == WOLFSSL_SERVER_END)) { + ssl->options.haveStaticECC = 0; + } + } + /* Not an RSA key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not an RSA key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + return ret; +} +#else +/* See if DER data is an RSA private key. + * + * Checks size meets minimum RSA key size. + * This implementation uses more dynamic memory but supports older FIPS. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an RSA key and format unknown. + * @return RSA_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeRsa(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, int devId, byte* keyType, + int* keySize) +{ + int ret; + word32 idx; + /* make sure RSA key can be used */ +#ifdef WOLFSSL_SMALL_STACK + RsaKey* key; +#else + RsaKey key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate an RSA key to parse into so we can get size. */ + key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA); + if (key == NULL) + return MEMORY_E; +#endif + + /* Initialize the RSA key. */ + ret = wc_InitRsaKey_ex(key, heap, devId); + if (ret == 0) { + /* Check we have an RSA private key. */ + idx = 0; + ret = wc_RsaPrivateKeyDecode(der->buffer, &idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* If that didn't work then maybe a public key if device ID or callback. + */ + if ((ret != 0) && ((devId != INVALID_DEVID) || + WOLFSSL_IS_PRIV_PK_SET(ctx, ssl))) { + /* If that didn't work then maybe a public key if device ID or + * callback. */ + idx = 0; + ret = wc_RsaPublicKeyDecode(der->buffer, &idx, key, der->length); + } + #endif + if (ret == 0) { + /* Get the minimum RSA key size from SSL or SSL context object. */ + int minRsaSz = ssl ? ssl->options.minRsaKeySz : ctx->minRsaKeySz; + int keySz = wc_RsaEncryptSize((RsaKey*)key); + + /* Format is known. */ + *keyFormat = RSAk; + *keyType = rsa_sa_algo; + *keySize = keySz; + + /* Check that the size of the RSA key is enough. */ + if (keySz < minRsaSz) { + WOLFSSL_MSG("Private Key size too small"); + ret = RSA_KEY_SIZE_E; + } + /* No static ECC key possible. */ + if ((ssl != NULL) && (ssl->options.side == WOLFSSL_SERVER_END)) { + ssl->options.haveStaticECC = 0; + } + } + /* Not an RSA key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not an RSA key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_FreeRsaKey(key); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_RSA); +#endif + + return ret; +} +#endif +#endif /* !NO_RSA */ + +#ifdef HAVE_ECC +/* See if DER data is an ECC private key. + * + * Checks size meets minimum ECC key size. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an ECC key and format unknown. + * @return ECC_KEY_SIZE_E when ECC key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeEcc(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, int devId, byte* keyType, + int* keySize) +{ + int ret = 0; + word32 idx; + /* make sure ECC key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ecc_key* key; +#else + ecc_key key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate an ECC key to parse into. */ + key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC); + if (key == NULL) + return MEMORY_E; +#endif + + /* Initialize ECC key. */ + if (wc_ecc_init_ex(key, heap, devId) == 0) { + /* Decode as an ECC private key. */ + idx = 0; + ret = wc_EccPrivateKeyDecode(der->buffer, &idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* If that didn't work then maybe a public key if device ID or callback. + */ + if ((ret != 0) && ((devId != INVALID_DEVID) || + WOLFSSL_IS_PRIV_PK_SET(ctx, ssl))) { + /* Decode as an ECC public key. */ + idx = 0; + ret = wc_EccPublicKeyDecode(der->buffer, &idx, key, der->length); + } + #endif + #ifdef WOLFSSL_SM2 + if (*keyFormat == SM2k) { + ret = wc_ecc_set_curve(key, WOLFSSL_SM2_KEY_BITS / 8, + ECC_SM2P256V1); + } + #endif + if (ret == 0) { + /* Get the minimum ECC key size from SSL or SSL context object. */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + int keySz = wc_ecc_size(key); + + /* Format is known. */ + *keyFormat = ECDSAk; + #ifdef WOLFSSL_SM2 + if (key->dp->id == ECC_SM2P256V1) { + *keyType = sm2_sa_algo; + } + else + #endif + { + *keyType = ecc_dsa_sa_algo; + } + *keySize = keySz; + + /* Check that the size of the ECC key is enough. */ + if (keySz < minKeySz) { + WOLFSSL_MSG("ECC private key too small"); + ret = ECC_KEY_SIZE_E; + } + /* Static ECC key possible. */ + if (ssl) { + ssl->options.haveStaticECC = 1; + } + else { + ctx->haveStaticECC = 1; + } + } + /* Not an ECC key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not an ECC key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_ecc_free(key); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_ECC); +#endif + return ret; +} +#endif /* HAVE_ECC */ + +#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) +/* See if DER data is an Ed25519 private key. + * + * Checks size meets minimum ECC key size. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an Ed25519 key and format unknown. + * @return ECC_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeEd25519(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, int devId, byte* keyType, + int* keySize) +{ + int ret; + word32 idx; + /* make sure Ed25519 key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ed25519_key* key; +#else + ed25519_key key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate an Ed25519 key to parse into. */ + key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap, + DYNAMIC_TYPE_ED25519); + if (key == NULL) + return MEMORY_E; +#endif + + /* Initialize Ed25519 key. */ + ret = wc_ed25519_init_ex(key, heap, devId); + if (ret == 0) { + /* Decode as an Ed25519 private key. */ + idx = 0; + ret = wc_Ed25519PrivateKeyDecode(der->buffer, &idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* If that didn't work then maybe a public key if device ID or callback. + */ + if ((ret != 0) && ((devId != INVALID_DEVID) || + WOLFSSL_IS_PRIV_PK_SET(ctx, ssl))) { + /* Decode as an Ed25519 public key. */ + idx = 0; + ret = wc_Ed25519PublicKeyDecode(der->buffer, &idx, key, + der->length); + } + #endif + if (ret == 0) { + /* Get the minimum ECC key size from SSL or SSL context object. */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + + /* Format is known. */ + *keyFormat = ED25519k; + *keyType = ed25519_sa_algo; + *keySize = ED25519_KEY_SIZE; + + /* Check that the size of the ECC key is enough. */ + if (ED25519_KEY_SIZE < minKeySz) { + WOLFSSL_MSG("ED25519 private key too small"); + ret = ECC_KEY_SIZE_E; + } + if (ssl != NULL) { +#if !defined(WOLFSSL_NO_CLIENT_AUTH) && !defined(NO_ED25519_CLIENT_AUTH) + /* Ed25519 requires caching enabled for tracking message + * hash used in EdDSA_Update for signing */ + ssl->options.cacheMessages = 1; +#endif + } + } + /* Not an Ed25519 key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not an Ed25519 key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_ed25519_free(key); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_ED25519); +#endif + return ret; +} +#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ + +#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) +/* See if DER data is an Ed448 private key. + * + * Checks size meets minimum ECC key size. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an Ed448 key and format unknown. + * @return ECC_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeEd448(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, int devId, byte* keyType, + int* keySize) +{ + int ret; + word32 idx; + /* make sure Ed448 key can be used */ +#ifdef WOLFSSL_SMALL_STACK + ed448_key* key = NULL; +#else + ed448_key key[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate an Ed448 key to parse into. */ + key = (ed448_key*)XMALLOC(sizeof(ed448_key), heap, DYNAMIC_TYPE_ED448); + if (key == NULL) + return MEMORY_E; +#endif + + /* Initialize Ed448 key. */ + ret = wc_ed448_init_ex(key, heap, devId); + if (ret == 0) { + /* Decode as an Ed448 private key. */ + idx = 0; + ret = wc_Ed448PrivateKeyDecode(der->buffer, &idx, key, der->length); + #ifdef WOLF_PRIVATE_KEY_ID + /* If that didn't work then maybe a public key if device ID or callback. + */ + if ((ret != 0) && ((devId != INVALID_DEVID) || + WOLFSSL_IS_PRIV_PK_SET(ctx, ssl))) { + /* Decode as an Ed448 public key. */ + idx = 0; + ret = wc_Ed448PublicKeyDecode(der->buffer, &idx, key, der->length); + } + #endif + if (ret == 0) { + /* Get the minimum ECC key size from SSL or SSL context object. */ + int minKeySz = ssl ? ssl->options.minEccKeySz : ctx->minEccKeySz; + + /* Format is known. */ + *keyFormat = ED448k; + *keyType = ed448_sa_algo; + *keySize = ED448_KEY_SIZE; + + /* Check that the size of the ECC key is enough. */ + if (ED448_KEY_SIZE < minKeySz) { + WOLFSSL_MSG("ED448 private key too small"); + ret = ECC_KEY_SIZE_E; + } + if (ssl != NULL) { + /* Ed448 requires caching enabled for tracking message + * hash used in EdDSA_Update for signing */ + ssl->options.cacheMessages = 1; + } + } + /* Not an Ed448 key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not an Ed448 key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_ed448_free(key); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_ED448); +#endif + return ret; +} +#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ + +#if defined(HAVE_FALCON) +/* See if DER data is an Falcon private key. + * + * Checks size meets minimum Falcon key size. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not an Falcon key and format unknown. + * @return FALCON_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeFalcon(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, byte* keyType, int* keySize) +{ + int ret; + falcon_key* key; + + /* Allocate a Falcon key to parse into. */ + key = (falcon_key*)XMALLOC(sizeof(falcon_key), heap, DYNAMIC_TYPE_FALCON); + if (key == NULL) { + return MEMORY_E; + } + + /* Initialize Falcon key. */ + ret = wc_falcon_init(key); + if (ret == 0) { + /* Set up key to parse the format specified. */ + if (*keyFormat == FALCON_LEVEL1k) { + ret = wc_falcon_set_level(key, 1); + } + else if (*keyFormat == FALCON_LEVEL5k) { + ret = wc_falcon_set_level(key, 5); + } + else { + /* What if *keyformat is 0? We might want to do something more + * graceful here. */ + /* TODO: get the size of the private key for different formats and + * compare with DER length. */ + wc_falcon_free(key); + ret = ALGO_ID_E; + } + } + + if (ret == 0) { + /* Decode as a Falcon private key. */ + ret = wc_falcon_import_private_only(der->buffer, der->length, key); + if (ret == 0) { + /* Get the minimum Falcon key size from SSL or SSL context object. + */ + int minKeySz = ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz; + + /* Format is known. */ + if (*keyFormat == FALCON_LEVEL1k) { + *keyType = falcon_level1_sa_algo; + *keySize = FALCON_LEVEL1_KEY_SIZE; + } + else { + *keyType = falcon_level5_sa_algo; + *keySize = FALCON_LEVEL5_KEY_SIZE; + } + + /* Check that the size of the Falcon key is enough. */ + if (*keySize < minKeySz) { + WOLFSSL_MSG("Falcon private key too small"); + ret = FALCON_KEY_SIZE_E; + } + } + /* Not a Falcon key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not a Falcon key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_falcon_free(key); + } + + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_FALCON); + return ret; +} +#endif + +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_ASN1) +/* See if DER data is an Dilithium private key. + * + * Checks size meets minimum Falcon key size. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] devId Device identifier. + * @param [out] keyType Type of key. + * @param [out] keySize Size of key. + * @return 0 on success or not a Dilithium key and format unknown. + * @return DILITHIUM_KEY_SIZE_E when key size doesn't meet minimum required. + */ +static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, byte* keyType, int* keySize) +{ + int ret; + word32 idx; + dilithium_key* key; + + /* Allocate a Dilithium key to parse into. */ + key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, + DYNAMIC_TYPE_DILITHIUM); + if (key == NULL) { + return MEMORY_E; + } + + /* Initialize Dilithium key. */ + ret = wc_dilithium_init(key); + if (ret == 0) { + /* Set up key to parse the format specified. */ + if (*keyFormat == DILITHIUM_LEVEL2k) { + ret = wc_dilithium_set_level(key, 2); + } + else if (*keyFormat == DILITHIUM_LEVEL3k) { + ret = wc_dilithium_set_level(key, 3); + } + else if (*keyFormat == DILITHIUM_LEVEL5k) { + ret = wc_dilithium_set_level(key, 5); + } + else { + /* What if *keyformat is 0? We might want to do something more + * graceful here. */ + /* TODO: get the size of the private key for different formats and + * compare with DER length. */ + wc_dilithium_free(key); + ret = ALGO_ID_E; + } + } + + if (ret == 0) { + /* Decode as a Dilithium private key. */ + idx = 0; + ret = wc_Dilithium_PrivateKeyDecode(der->buffer, &idx, key, der->length); + if (ret == 0) { + /* Get the minimum Dilithium key size from SSL or SSL context + * object. */ + int minKeySz = ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz; + + /* Format is known. */ + if (*keyFormat == DILITHIUM_LEVEL2k) { + *keyType = dilithium_level2_sa_algo; + *keySize = DILITHIUM_LEVEL2_KEY_SIZE; + } + else if (*keyFormat == DILITHIUM_LEVEL3k) { + *keyType = dilithium_level3_sa_algo; + *keySize = DILITHIUM_LEVEL3_KEY_SIZE; + } + else if (*keyFormat == DILITHIUM_LEVEL5k) { + *keyType = dilithium_level5_sa_algo; + *keySize = DILITHIUM_LEVEL5_KEY_SIZE; + } + + /* Check that the size of the Dilithium key is enough. */ + if (*keySize < minKeySz) { + WOLFSSL_MSG("Dilithium private key too small"); + ret = DILITHIUM_KEY_SIZE_E; + } + } + /* Not a Dilithium key but check whether we know what it is. */ + else if (*keyFormat == 0) { + WOLFSSL_MSG("Not a Dilithium key"); + /* Format unknown so keep trying. */ + ret = 0; + } + + /* Free dynamically allocated data in key. */ + wc_dilithium_free(key); + } + + /* Dispose of allocated key. */ + XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); + return ret; +} +#endif /* HAVE_DILITHIUM */ + +/* Try to decode DER data is a known private key. + * + * Checks size meets minimum for key type. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in, out] keyFormat On in, expected format. 0 means unknown. + * @param [in] heap Dynamic memory allocation hint. + * @param [out] type Type of key: + * PRIVATEKEY_TYPE or ALT_PRIVATEKEY_TYPE. + * @return 0 on success. + * @return BAD_FUNC_ARG when der or keyFormat is NULL. + * @return BAD_FUNC_ARG when ctx and ssl are NULL. + * @return WOLFSSL_BAD_FILE when unable to identify the key format. + */ +static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int* keyFormat, void* heap, int type) +{ + int ret = 0; + int devId = wolfSSL_CTX_GetDevId(ctx, ssl); + byte* keyType = NULL; + int* keySz = NULL; + + (void)heap; + (void)devId; + (void)type; + + /* Validate parameters. */ + if ((der == NULL) || (keyFormat == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Must have an SSL context or SSL object to use. */ + if ((ret == 0) && (ctx == NULL) && (ssl == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Determine where to put key type and size in SSL or context object. */ + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (type == ALT_PRIVATEKEY_TYPE) { + if (ssl != NULL) { + keyType = &ssl->buffers.altKeyType; + keySz = &ssl->buffers.altKeySz; + } + else { + keyType = &ctx->altPrivateKeyType; + keySz = &ctx->altPrivateKeySz; + } + } + else + #endif + /* Type is PRIVATEKEY_TYPE. */ + if (ssl != NULL) { + keyType = &ssl->buffers.keyType; + keySz = &ssl->buffers.keySz; + } + else { + keyType = &ctx->privateKeyType; + keySz = &ctx->privateKeySz; + } + } + +#ifndef NO_RSA + /* Try RSA if key format is RSA or yet unknown. */ + if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == RSAk))) { +#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \ + (HAVE_FIPS_VERSION > 2)) + ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keyFormat, devId, + keyType, keySz); +#else + ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keyFormat, heap, devId, + keyType, keySz); +#endif + } +#endif +#ifdef HAVE_ECC + /* Try ECC if key format is ECDSA or SM2, or yet unknown. */ + if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == ECDSAk) + #ifdef WOLFSSL_SM2 + || (*keyFormat == SM2k) + #endif + )) { + ret = ProcessBufferTryDecodeEcc(ctx, ssl, der, keyFormat, heap, devId, + keyType, keySz); + } +#endif /* HAVE_ECC */ +#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) + /* Try Ed25519 if key format is Ed25519 or yet unknown. */ + if ((ret == 0) && ((*keyFormat == 0 || *keyFormat == ED25519k))) { + ret = ProcessBufferTryDecodeEd25519(ctx, ssl, der, keyFormat, heap, + devId, keyType, keySz); + } +#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ +#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) + /* Try Ed448 if key format is Ed448 or yet unknown. */ + if ((ret == 0) && ((*keyFormat == 0 || *keyFormat == ED448k))) { + ret = ProcessBufferTryDecodeEd448(ctx, ssl, der, keyFormat, heap, devId, + keyType, keySz); + } +#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ +#if defined(HAVE_FALCON) + /* Try Falcon if key format is Falcon level 1k or 5k or yet unknown. */ + if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == FALCON_LEVEL1k) || + (*keyFormat == FALCON_LEVEL5k))) { + ret = ProcessBufferTryDecodeFalcon(ctx, ssl, der, keyFormat, heap, + keyType, keySz); + } +#endif /* HAVE_FALCON */ +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_ASN1) + /* Try Falcon if key format is Dilithium level 2k, 3k or 5k or yet unknown. + */ + if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == DILITHIUM_LEVEL2k) || + (*keyFormat == DILITHIUM_LEVEL3k) || + (*keyFormat == DILITHIUM_LEVEL5k))) { + ret = ProcessBufferTryDecodeDilithium(ctx, ssl, der, keyFormat, heap, + keyType, keySz); + } +#endif /* HAVE_DILITHIUM */ + + /* Check we know the format. */ + if ((ret == 0) && (*keyFormat == 0)) { + WOLFSSL_MSG("Not a supported key type"); + /* Not supported key format. */ + ret = WOLFSSL_BAD_FILE; + } + + return ret; +} + +#if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) +/* Decrypt PKCS#8 private key. + * + * @param [in] info Encryption information. + * @param [in] der DER encoded data. + * @param [in] heap Dynamic memory allocation hint. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int ProcessBufferPrivPkcs8Dec(EncryptedInfo* info, DerBuffer* der, + void* heap) +{ + int ret = 0; + word32 algId; + int passwordSz = NAME_SZ; +#ifndef WOLFSSL_SMALL_STACK + char password[NAME_SZ]; +#else + char* password; +#endif + + (void)heap; +#ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for password. */ + password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING); + if (password == NULL) { + ret = MEMORY_E; + } +#endif + + if (ret == 0) { + /* Get password. */ + ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ, + info->passwd_userdata); + } + if (ret >= 0) { + /* Returned value is password size. */ + passwordSz = ret; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("ProcessBuffer password", password, passwordSz); + #endif + + /* Decrypt PKCS#8 private key inline and get algorithm id. */ + ret = ToTraditionalEnc(der->buffer, der->length, password, passwordSz, + &algId); + } + if (ret >= 0) { + /* Zero out encrypted data not overwritten. */ + ForceZero(der->buffer + ret, der->length - ret); + /* Set decrypted data length. */ + der->length = (word32)ret; + } + + /* Ensure password is zeroized. */ + ForceZero(password, (word32)passwordSz); +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of password memory. */ + XFREE(password, heap, DYNAMIC_TYPE_STRING); +#elif defined(WOLFSSL_CHECK_MEM_ZERO) + wc_MemZero_Check(password, NAME_SZ); +#endif + return ret; +} +#endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */ + +/* Put the DER into the SSL or SSL context object. + * + * Precondition: ctx or ssl is not NULL. + * Precondition: Must be a private key type. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @return 0 on success. + */ +static int ProcessBufferPrivKeyHandleDer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer** der, int type) +{ + int ret = 0; + + (void)type; + +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (type == ALT_PRIVATEKEY_TYPE) { + /* Put in alternate private key fields of objects. */ + if (ssl != NULL) { + /* Dispose of previous key if not context's. */ + if (ssl->buffers.weOwnAltKey) { + FreeDer(&ssl->buffers.altKey); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.altKeyMask); + #endif + } + ssl->buffers.altKeyId = 0; + ssl->buffers.altKeyLabel = 0; + ssl->buffers.altKeyDevId = INVALID_DEVID; + /* Store key by reference and own it. */ + ssl->buffers.altKey = *der; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("SSL Buffers key", (*der)->buffer, (*der)->length); + #endif + ssl->buffers.weOwnAltKey = 1; + } + else if (ctx != NULL) { + /* Dispose of previous key. */ + FreeDer(&ctx->altPrivateKey); + ctx->altPrivateKeyId = 0; + ctx->altPrivateKeyLabel = 0; + ctx->altPrivateKeyDevId = INVALID_DEVID; + /* Store key by reference. */ + ctx->altPrivateKey = *der; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("CTX private key", (*der)->buffer, (*der)->length); + #endif + } + } + else +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + if (ssl != NULL) { + /* Dispose of previous key if not context's. */ + if (ssl->buffers.weOwnKey) { + FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif + } + ssl->buffers.keyId = 0; + ssl->buffers.keyLabel = 0; + ssl->buffers.keyDevId = INVALID_DEVID; + /* Store key by reference and own it. */ + ssl->buffers.key = *der; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("SSL Buffers key", (*der)->buffer, (*der)->length); + #endif + ssl->buffers.weOwnKey = 1; + } + else if (ctx != NULL) { + /* Dispose of previous key. */ + FreeDer(&ctx->privateKey); + ctx->privateKeyId = 0; + ctx->privateKeyLabel = 0; + ctx->privateKeyDevId = INVALID_DEVID; + /* Store key by reference. */ + ctx->privateKey = *der; + #ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("CTX private key", (*der)->buffer, (*der)->length); + #endif + } + + return ret; +} + +/* Decode private key. + * + * Precondition: ctx or ssl is not NULL. + * Precondition: Must be a private key type. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoding. + * @param [in] format Original format of data. + * @param [in] info Encryption information. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of data: + * PRIVATEKEY_TYPE or ALT_PRIVATEKEY_TYPE. + * @param [in] algId Algorithm id of key. + * @return 0 on success. + * @return WOLFSSL_BAD_FILE when not able to decode. + */ +static int ProcessBufferPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int format, EncryptedInfo* info, void* heap, int type, + int algId) +{ + int ret; +#if (defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)) || \ + defined(HAVE_PKCS8) + word32 p8AlgId = 0; +#endif + + (void)info; + (void)format; + +#ifdef HAVE_PKCS8 + /* Try and remove PKCS8 header and get algorithm id. */ + ret = ToTraditional_ex(der->buffer, der->length, &p8AlgId); + if (ret > 0) { + /* Header stripped inline. */ + der->length = (word32)ret; + algId = p8AlgId; + } +#endif + + /* Put the data into the SSL or SSL context object. */ + ret = ProcessBufferPrivKeyHandleDer(ctx, ssl, &der, type); + if (ret == 0) { + /* Try to decode the DER data. */ + ret = ProcessBufferTryDecode(ctx, ssl, der, &algId, heap, type); + } + +#if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) + /* If private key type PKCS8 header wasn't already removed (algId == 0). */ + if (((ret != 0) || (algId == 0)) && (format != WOLFSSL_FILETYPE_PEM) && + (info->passwd_cb != NULL) && (algId == 0)) { + /* Try to decrypt DER data as a PKCS#8 private key. */ + ret = ProcessBufferPrivPkcs8Dec(info, der, heap); + if (ret >= 0) { + /* Try to decode decrypted data. */ + ret = ProcessBufferTryDecode(ctx, ssl, der, &algId, heap, type); + } + } +#endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */ + +#ifdef WOLFSSL_BLIND_PRIVATE_KEY +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (type == ALT_PRIVATEKEY_TYPE) { + if (ssl != NULL) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, + &ssl->buffers.altKeyMask); + } + else { + ret = wolfssl_priv_der_blind(NULL, ctx->altPrivateKey, + &ctx->altPrivateKeyMask); + } + } + else +#endif + if (ssl != NULL) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + } + else { + ret = wolfssl_priv_der_blind(NULL, ctx->privateKey, + &ctx->privateKeyMask); + } +#endif + + /* Check if we were able to determine algorithm id. */ + if ((ret == 0) && (algId == 0)) { + #ifdef OPENSSL_EXTRA + /* Decryption password is probably wrong. */ + if (info->passwd_cb) { + EVPerr(0, EVP_R_BAD_DECRYPT); + } + #endif + WOLFSSL_ERROR(WOLFSSL_BAD_FILE); + /* Unable to decode DER data. */ + ret = WOLFSSL_BAD_FILE; + } + + return ret; +} + +/* Use the key OID to determine have options. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] keyOID OID for public/private key. + */ +static void wolfssl_set_have_from_key_oid(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + int keyOID) +{ + /* Set which private key algorithm available based on key OID. */ + switch (keyOID) { + case ECDSAk: + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + case SM2k: + #endif + #ifdef HAVE_ED25519 + case ED25519k: + #endif + #ifdef HAVE_ED448 + case ED448k: + #endif + if (ssl != NULL) { + ssl->options.haveECC = 1; + } + else { + ctx->haveECC = 1; + } + break; + #ifndef NO_RSA + case RSAk: + #ifdef WC_RSA_PSS + case RSAPSSk: + #endif + if (ssl != NULL) { + ssl->options.haveRSA = 1; + } + else { + ctx->haveRSA = 1; + } + break; + #endif + #ifdef HAVE_FALCON + case FALCON_LEVEL1k: + case FALCON_LEVEL5k: + if (ssl != NULL) { + ssl->options.haveFalconSig = 1; + } + else { + ctx->haveFalconSig = 1; + } + break; + #endif /* HAVE_FALCON */ + #ifdef HAVE_DILITHIUM + case DILITHIUM_LEVEL2k: + case DILITHIUM_LEVEL3k: + case DILITHIUM_LEVEL5k: + if (ssl != NULL) { + ssl->options.haveDilithiumSig = 1; + } + else { + ctx->haveDilithiumSig = 1; + } + break; + #endif /* HAVE_DILITHIUM */ + default: + WOLFSSL_MSG("Cert key not supported"); + break; + } +} + +/* Set which private key algorithm we have against SSL or SSL context object. + * + * Precondition: ctx or ssl is not NULL. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] cert Decode certificate. + */ +static void ProcessBufferCertSetHave(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DecodedCert* cert) +{ + if (ssl != NULL) { + /* Reset signatures we have in SSL. */ + ssl->options.haveECDSAsig = 0; + ssl->options.haveFalconSig = 0; + ssl->options.haveDilithiumSig = 0; + } + + /* Set which signature we have based on the type in the cert. */ + switch (cert->signatureOID) { + case CTC_SHAwECDSA: + case CTC_SHA256wECDSA: + case CTC_SHA384wECDSA: + case CTC_SHA512wECDSA: + #ifdef HAVE_ED25519 + case CTC_ED25519: + #endif + #ifdef HAVE_ED448 + case CTC_ED448: + #endif + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + case CTC_SM3wSM2: + #endif + WOLFSSL_MSG("ECDSA/ED25519/ED448 cert signature"); + if (ssl) { + ssl->options.haveECDSAsig = 1; + } + else if (ctx) { + ctx->haveECDSAsig = 1; + } + break; + #ifdef HAVE_FALCON + case CTC_FALCON_LEVEL1: + case CTC_FALCON_LEVEL5: + WOLFSSL_MSG("Falcon cert signature"); + if (ssl) { + ssl->options.haveFalconSig = 1; + } + else if (ctx) { + ctx->haveFalconSig = 1; + } + break; + #endif + #ifdef HAVE_DILITHIUM + case CTC_DILITHIUM_LEVEL2: + case CTC_DILITHIUM_LEVEL3: + case CTC_DILITHIUM_LEVEL5: + WOLFSSL_MSG("Dilithium cert signature"); + if (ssl) { + ssl->options.haveDilithiumSig = 1; + } + else if (ctx) { + ctx->haveDilithiumSig = 1; + } + break; + #endif + default: + WOLFSSL_MSG("Cert signature not supported"); + break; + } + +#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ + defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || !defined(NO_RSA) + #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) + /* Set the private key curve OID. */ + if (ssl != NULL) { + ssl->pkCurveOID = cert->pkCurveOID; + } + else if (ctx) { + ctx->pkCurveOID = cert->pkCurveOID; + } + #endif +#ifndef WC_STRICT_SIG + wolfssl_set_have_from_key_oid(ctx, ssl, cert->keyOID); +#else + /* Set whether ECC is available based on signature available. */ + if (ssl != NULL) { + ssl->options.haveECC = ssl->options.haveECDSAsig; + } + else if (ctx) { + ctx->haveECC = ctx->haveECDSAsig; + } +#endif /* !WC_STRICT_SIG */ +#endif +} + +/* Check key size is valid. + * + * Precondition: ctx or ssl is not NULL. + * + * @param [in] min Minimum key size. + * @param [in] max Maximum key size. + * @param [in] keySz Key size. + * @param [in] err Error value to return when key size is invalid. + * @return 0 on success. + * @return err when verifying and min is less than 0 or key size is invalid. + */ +#define CHECK_KEY_SZ(min, max, keySz, err) \ + (((min) < 0) || ((keySz) < (min)) || ((keySz) > (max))) ? (err) : 0 + +/* Check public key in certificate. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] cert Certificate object. + * @return 0 on success. + * @return Non-zero when an error occurred. + */ +static int ProcessBufferCertPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DecodedCert* cert, int checkKeySz) +{ + int ret = 0; + byte keyType = 0; + int keySz = 0; +#ifndef NO_RSA + word32 idx; +#endif + + /* Get key size and check unless not verifying. */ + switch (cert->keyOID) { +#ifndef NO_RSA + #ifdef WC_RSA_PSS + case RSAPSSk: + #endif + case RSAk: + keyType = rsa_sa_algo; + /* Determine RSA key size by parsing public key */ + idx = 0; + ret = wc_RsaPublicKeyDecode_ex(cert->publicKey, &idx, + cert->pubKeySize, NULL, (word32*)&keySz, NULL, NULL); + if ((ret == 0) && checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minRsaKeySz : + ctx->minRsaKeySz, RSA_MAX_SIZE / 8, keySz, RSA_KEY_SIZE_E); + } + break; +#endif /* !NO_RSA */ + #ifdef HAVE_ECC + case ECDSAk: + keyType = ecc_dsa_sa_algo; + /* Determine ECC key size based on curve */ + #ifdef WOLFSSL_CUSTOM_CURVES + if ((cert->pkCurveOID == 0) && (cert->pkCurveSize != 0)) { + keySz = cert->pkCurveSize; + } + else + #endif + { + keySz = wc_ecc_get_curve_size_from_id(wc_ecc_get_oid( + cert->pkCurveOID, NULL, NULL)); + } + + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, (MAX_ECC_BITS + 7) / 8, keySz, + ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ECC */ + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + case SM2k: + keyType = sm2_sa_algo; + /* Determine ECC key size based on curve */ + keySz = WOLFSSL_SM2_KEY_BITS / 8; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, (MAX_ECC_BITS + 7) / 8, keySz, + ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED25519 */ + #ifdef HAVE_ED25519 + case ED25519k: + keyType = ed25519_sa_algo; + /* ED25519 is fixed key size */ + keySz = ED25519_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, ED25519_KEY_SIZE, keySz, ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED25519 */ + #ifdef HAVE_ED448 + case ED448k: + keyType = ed448_sa_algo; + /* ED448 is fixed key size */ + keySz = ED448_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, ED448_KEY_SIZE, keySz, ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED448 */ + #if defined(HAVE_FALCON) + case FALCON_LEVEL1k: + keyType = falcon_level1_sa_algo; + /* Falcon is fixed key size */ + keySz = FALCON_LEVEL1_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz, FALCON_MAX_KEY_SIZE, keySz, + FALCON_KEY_SIZE_E); + } + break; + case FALCON_LEVEL5k: + keyType = falcon_level5_sa_algo; + /* Falcon is fixed key size */ + keySz = FALCON_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz, FALCON_MAX_KEY_SIZE, keySz, + FALCON_KEY_SIZE_E); + } + break; + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) + case DILITHIUM_LEVEL2k: + keyType = dilithium_level2_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL2_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case DILITHIUM_LEVEL3k: + keyType = dilithium_level3_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL3_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case DILITHIUM_LEVEL5k: + keyType = dilithium_level5_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + #endif /* HAVE_DILITHIUM */ + + default: + WOLFSSL_MSG("No key size check done on public key in certificate"); + break; + } + + /* Store the type and key size as there may not be a private key set. */ + if (ssl != NULL) { + ssl->buffers.keyType = keyType; + ssl->buffers.keySz = keySz; + } + else { + ctx->privateKeyType = keyType; + ctx->privateKeySz = keySz; + } + + return ret; +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +static int ProcessBufferCertAltPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DecodedCert* cert, int checkKeySz) +{ + int ret = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); + byte keyType = 0; + int keySz = 0; +#ifndef NO_RSA + word32 idx; +#endif + + /* Check alternative key size of cert. */ + switch (cert->sapkiOID) { + /* No OID set. */ + case 0: + if (cert->sapkiLen != 0) { + /* Have the alternative key data but no OID. */ + ret = NOT_COMPILED_IN; + } + break; + +#ifndef NO_RSA + #ifdef WC_RSA_PSS + case RSAPSSk: + #endif + case RSAk: + keyType = rsa_sa_algo; + /* Determine RSA key size by parsing public key */ + idx = 0; + ret = wc_RsaPublicKeyDecode_ex(cert->sapkiDer, &idx, + cert->sapkiLen, NULL, (word32*)&keySz, NULL, NULL); + if ((ret == 0) && checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minRsaKeySz : + ctx->minRsaKeySz, RSA_MAX_SIZE / 8, keySz, RSA_KEY_SIZE_E); + } + break; +#endif /* !NO_RSA */ + #ifdef HAVE_ECC + case ECDSAk: + { + #ifdef WOLFSSL_SMALL_STACK + ecc_key* temp_key = NULL; + #else + ecc_key temp_key[1]; + #endif + keyType = ecc_dsa_sa_algo; + + #ifdef WOLFSSL_SMALL_STACK + temp_key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, + DYNAMIC_TYPE_ECC); + if (temp_key == NULL) { + ret = MEMORY_E; + } + #endif + + /* Determine ECC key size. We have to decode the sapki for + * that. */ + if (ret == 0) { + ret = wc_ecc_init_ex(temp_key, heap, INVALID_DEVID); + if (ret == 0) { + idx = 0; + ret = wc_EccPublicKeyDecode(cert->sapkiDer, &idx, temp_key, + cert->sapkiLen); + if (ret == 0) { + keySz = wc_ecc_size(temp_key); + } + wc_ecc_free(temp_key); + } + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(temp_key, heap, DYNAMIC_TYPE_ECC); + #endif + + if ((ret == 0) && checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, (MAX_ECC_BITS + 7) / 8, keySz, + ECC_KEY_SIZE_E); + } + break; + } + #endif /* HAVE_ECC */ + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + case SM2k: + keyType = sm2_sa_algo; + /* Determine ECC key size based on curve */ + keySz = WOLFSSL_SM2_KEY_BITS / 8; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, (MAX_ECC_BITS + 7) / 8, keySz, + ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED25519 */ + #ifdef HAVE_ED25519 + case ED25519k: + keyType = ed25519_sa_algo; + /* ED25519 is fixed key size */ + keySz = ED25519_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, ED25519_KEY_SIZE, keySz, ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED25519 */ + #ifdef HAVE_ED448 + case ED448k: + keyType = ed448_sa_algo; + /* ED448 is fixed key size */ + keySz = ED448_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minEccKeySz : + ctx->minEccKeySz, ED448_KEY_SIZE, keySz, ECC_KEY_SIZE_E); + } + break; + #endif /* HAVE_ED448 */ + #if defined(HAVE_FALCON) + case FALCON_LEVEL1k: + keyType = falcon_level1_sa_algo; + /* Falcon is fixed key size */ + keySz = FALCON_LEVEL1_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz, FALCON_MAX_KEY_SIZE, keySz, + FALCON_KEY_SIZE_E); + } + break; + case FALCON_LEVEL5k: + keyType = falcon_level5_sa_algo; + /* Falcon is fixed key size */ + keySz = FALCON_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minFalconKeySz : + ctx->minFalconKeySz, FALCON_MAX_KEY_SIZE, keySz, + FALCON_KEY_SIZE_E); + } + break; + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) + case DILITHIUM_LEVEL2k: + keyType = dilithium_level2_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL2_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case DILITHIUM_LEVEL3k: + keyType = dilithium_level3_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL3_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case DILITHIUM_LEVEL5k: + keyType = dilithium_level5_sa_algo; + /* Dilithium is fixed key size */ + keySz = DILITHIUM_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + #endif /* HAVE_DILITHIUM */ + + default: + /* In this case, there was an OID that we didn't recognize. + * This is an error. Use not compiled in because likely the + * given algorithm was not enabled. */ + ret = NOT_COMPILED_IN; + WOLFSSL_MSG("No alt key size check done on certificate"); + break; + } + + if (ssl != NULL) { + ssl->buffers.altKeyType = (byte)keyType; + ssl->buffers.altKeySz = keySz; + } + else if (ctx != NULL) { + ctx->altPrivateKeyType = (byte)keyType; + ctx->altPrivateKeySz = keySz; + } + + return ret; +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + +/* Parse the certificate and pull out information for TLS handshake. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoded X509 certificate. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return WOLFSSL_BAD_FILE when decoding certificate fails. + */ +static int ProcessBufferCert(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DerBuffer* der) +{ + int ret = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); +#if defined(HAVE_RPK) + RpkState* rpkState = ssl ? &ssl->options.rpkState : &ctx->rpkState; +#endif +#ifdef WOLFSSL_SMALL_STACK + DecodedCert* cert; +#else + DecodedCert cert[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for certificate to be decoded into. */ + cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap, DYNAMIC_TYPE_DCERT); + if (cert == NULL) { + ret = MEMORY_E; + } + + if (ret == 0) +#endif + { + /* Get device id from SSL context or SSL object. */ + int devId = wolfSSL_CTX_GetDevId(ctx, ssl); + + WOLFSSL_MSG("Checking cert signature type"); + /* Initialize certificate object. */ + InitDecodedCert_ex(cert, der->buffer, der->length, heap, devId); + + /* Decode up to and including public key. */ + if (DecodeToKey(cert, 0) < 0) { + WOLFSSL_MSG("Decode to key failed"); + ret = WOLFSSL_BAD_FILE; + } + if (ret == 0) { + int checkKeySz = 1; + + #if defined(HAVE_RPK) + /* Store whether the crtificate is a raw public key. */ + rpkState->isRPKLoaded = cert->isRPK; + #endif /* HAVE_RPK */ + + /* Set which private key algorithm we have. */ + ProcessBufferCertSetHave(ctx, ssl, cert); + + /* Don't check if verification is disabled for SSL. */ + if ((ssl != NULL) && ssl->options.verifyNone) { + checkKeySz = 0; + } + /* Don't check if no SSL object verification is disabled for SSL + * context. */ + else if ((ssl == NULL) && ctx->verifyNone) { + checkKeySz = 0; + } + + /* Check public key size. */ + ret = ProcessBufferCertPublicKey(ctx, ssl, cert, checkKeySz); + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ret == 0) { + ret = ProcessBufferCertAltPublicKey(ctx, ssl, cert, checkKeySz); + } + #endif + } + } + + /* Dispose of dynamic memory in certificate object. */ + FreeDecodedCert(cert); +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of certificate object. */ + XFREE(cert, heap, DYNAMIC_TYPE_DCERT); +#endif + return ret; +} + +/* Handle storing the DER encoding of the certificate. + * + * Do not free der outside of this function. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] der DER encoded certificate. + * @param [in] type Type of data: + * CERT_TYPE, CA_TYPE or TRUSTED_PEER_TYPE. + * @param [in] verify What verification to do. + * @return 0 on success. + * @return BAD_FUNC_ARG when type is CA_TYPE and ctx is NULL. + * @return WOLFSSL_BAD_CERTTYPE when data type is not supported. + */ +static int ProcessBufferCertHandleDer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + DerBuffer* der, int type, int verify) +{ + int ret = 0; + + /* CA certificate to verify with. */ + if (type == CA_TYPE) { + /* verify CA unless user set to no verify */ + ret = AddCA(ctx->cm, &der, WOLFSSL_USER_CA, verify); + if (ret == 1) { + ret = 0; + } + } +#ifdef WOLFSSL_TRUST_PEER_CERT + /* Trusted certificate to verify peer with. */ + else if (type == TRUSTED_PEER_TYPE) { + WOLFSSL_CERT_MANAGER* cm; + + /* Get certificate manager to add certificate to. */ + if (ctx != NULL) { + cm = ctx->cm; + } + else { + SSL_CM_WARNING(ssl); + cm = SSL_CM(ssl); + } + /* Add certificate as a trusted peer. */ + ret = AddTrustedPeer(cm, &der, verify); + if (ret != 1) { + WOLFSSL_MSG("Error adding trusted peer"); + } + } +#endif /* WOLFSSL_TRUST_PEER_CERT */ + /* Leaf certificate - our certificate. */ + else if (type == CERT_TYPE) { + if (ssl != NULL) { + /* Free previous certificate if we own it. */ + if (ssl->buffers.weOwnCert) { + FreeDer(&ssl->buffers.certificate); + #ifdef KEEP_OUR_CERT + /* Dispose of X509 version of certificate. */ + wolfSSL_X509_free(ssl->ourCert); + ssl->ourCert = NULL; + #endif + } + /* Store certificate as ours. */ + ssl->buffers.certificate = der; + #ifdef KEEP_OUR_CERT + ssl->keepCert = 1; /* hold cert for ssl lifetime */ + #endif + /* We have to free the certificate buffer. */ + ssl->buffers.weOwnCert = 1; + /* ourCert is created on demand. */ + } + else if (ctx != NULL) { + /* Free previous certificate. */ + FreeDer(&ctx->certificate); /* Make sure previous is free'd */ + #ifdef KEEP_OUR_CERT + /* Dispose of X509 version of certificate if we own it. */ + if (ctx->ownOurCert) { + wolfSSL_X509_free(ctx->ourCert); + } + ctx->ourCert = NULL; + #endif + /* Store certificate as ours. */ + ctx->certificate = der; + /* ourCert is created on demand. */ + } + } + else { + /* Dispose of DER buffer. */ + FreeDer(&der); + /* Not a certificate type supported. */ + ret = WOLFSSL_BAD_CERTTYPE; + } + + return ret; +} + +/* Process certificate based on type. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] buff Buffer holding original data. + * @param [in] sz Size of data in buffer. + * @param [in] der DER encoding of certificate. + * @param [in] format Format of data. + * @param [in] type Type of data: + * CERT_TYPE, CA_TYPE or TRUSTED_PEER_TYPE. + * @param [in] verify What verification to do. + * @return 0 on success. + * @return WOLFSSL_FATAL_ERROR on failure. + */ +static int ProcessBufferCertTypes(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const unsigned char* buff, long sz, DerBuffer* der, int format, int type, + int verify) +{ + int ret; + + (void)buff; + (void)sz; + (void)format; + + ret = ProcessBufferCertHandleDer(ctx, ssl, der, type, verify); + if ((ret == 0) && (type == CERT_TYPE)) { + /* Process leaf certificate. */ + ret = ProcessBufferCert(ctx, ssl, der); + } +#if !defined(NO_WOLFSSL_CM_VERIFY) && (!defined(NO_WOLFSSL_CLIENT) || \ + !defined(WOLFSSL_NO_CLIENT_AUTH)) + /* Hand bad CA or user certificate to callback. */ + if ((ret < 0) && ((type == CA_TYPE) || (type == CERT_TYPE))) { + /* Check for verification callback that may override error. */ + if ((ctx != NULL) && (ctx->cm != NULL) && + (ctx->cm->verifyCallback != NULL)) { + /* Verify and use callback. */ + ret = CM_VerifyBuffer_ex(ctx->cm, buff, sz, format, ret); + /* Convert error. */ + if (ret == 0) { + ret = WOLFSSL_FATAL_ERROR; + } + if (ret == 1) { + ret = 0; + } + } + } +#endif /* NO_WOLFSSL_CM_VERIFY */ + + return ret; +} + +/* Reset the cipher suites based on updated private key or certificate. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] type Type of certificate. + * @return 0 on success. + * @return WOLFSSL_FATAL_ERROR when allocation fails. + */ +static int ProcessBufferResetSuites(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int type) +{ + int ret = 0; + + /* Reset suites of SSL object. */ + if (ssl != NULL) { + if (ssl->options.side == WOLFSSL_SERVER_END) { + /* Allocate memory for suites. */ + if (AllocateSuites(ssl) != 0) { + ret = WOLFSSL_FATAL_ERROR; + } + else { + /* Determine cipher suites based on what we have. */ + InitSuites(ssl->suites, ssl->version, ssl->buffers.keySz, + WOLFSSL_HAVE_RSA, SSL_HAVE_PSK(ssl), ssl->options.haveDH, + ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, + ssl->options.haveStaticECC, ssl->options.haveFalconSig, + ssl->options.haveDilithiumSig, ssl->options.useAnon, TRUE, + ssl->options.side); + } + } + } + /* Reset suites of SSL context object. */ + else if ((type == CERT_TYPE) && (ctx->method->side == WOLFSSL_SERVER_END)) { + /* Allocate memory for suites. */ + if (AllocateCtxSuites(ctx) != 0) { + ret = WOLFSSL_FATAL_ERROR; + } + else { + /* Determine cipher suites based on what we have. */ + InitSuites(ctx->suites, ctx->method->version, ctx->privateKeySz, + WOLFSSL_HAVE_RSA, CTX_HAVE_PSK(ctx), ctx->haveDH, + ctx->haveECDSAsig, ctx->haveECC, TRUE, ctx->haveStaticECC, + ctx->haveFalconSig, ctx->haveDilithiumSig, CTX_USE_ANON(ctx), + TRUE, ctx->method->side); + } + } + + return ret; +} + +#ifndef WOLFSSL_DUAL_ALG_CERTS + /* Determine whether the type is for a private key. */ + #define IS_PRIVKEY_TYPE(type) ((type) == PRIVATEKEY_TYPE) +#else + /* Determine whether the type is for a private key. */ + #define IS_PRIVKEY_TYPE(type) (((type) == PRIVATEKEY_TYPE) || \ + ((type) == ALT_PRIVATEKEY_TYPE)) +#endif + +/* Process a buffer of data. + * + * Data type is a private key or a certificate. + * The format can be ASN.1 (DER) or PEM. + * + * @param [in, out] ctx SSL context object. + * @param [in] buff Buffer holding data. + * @param [in] sz Size of data in buffer. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @param [in] type Type of data: + * CERT_TYPE, CA_TYPE, TRUSTED_PEER_TYPE, + * PRIVATEKEY_TYPE or ALT_PRIVATEKEY_TYPE. + * @param [in, out] ssl SSL object. + * @param [out] used Number of bytes consumed. + * @param [in[ userChain Whether this certificate is for user's chain. + * @param [in] verify How to verify certificate. + * @return 1 on success. + * @return Less than 1 on failure. + */ +int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, + int format, int type, WOLFSSL* ssl, long* used, int userChain, int verify) +{ + DerBuffer* der = NULL; + int ret = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); +#ifdef WOLFSSL_SMALL_STACK + EncryptedInfo* info = NULL; +#else + EncryptedInfo info[1]; +#endif + int algId = 0; + + WOLFSSL_ENTER("ProcessBuffer"); + + /* Check data format is supported. */ + if ((format != WOLFSSL_FILETYPE_ASN1) && (format != WOLFSSL_FILETYPE_PEM)) { + ret = WOLFSSL_BAD_FILETYPE; + } + /* Need an object to store certificate into. */ + if ((ret == 0) && (ctx == NULL) && (ssl == NULL)) { + ret = BAD_FUNC_ARG; + } + /* CA certificates go into the SSL context object. */ + if ((ret == 0) && (ctx == NULL) && (type == CA_TYPE)) { + ret = BAD_FUNC_ARG; + } + /* This API does not handle CHAIN_CERT_TYPE */ + if ((ret == 0) && (type == CHAIN_CERT_TYPE)) { + ret = BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + if (ret == 0) { + /* Allocate memory for encryption information. */ + info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), heap, + DYNAMIC_TYPE_ENCRYPTEDINFO); + if (info == NULL) { + ret = MEMORY_E; + } + } +#endif + if (ret == 0) { + /* Initialize encryption information. */ + XMEMSET(info, 0, sizeof(EncryptedInfo)); + #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED) + if (ctx != NULL) { + info->passwd_cb = ctx->passwd_cb; + info->passwd_userdata = ctx->passwd_userdata; + } + #endif + + /* Get the DER data for a private key or certificate. */ + ret = DataToDerBuffer(buff, (word32)sz, format, type, info, heap, &der, + &algId); + if (used != NULL) { + /* Update to amount used/consumed. */ + *used = info->consumed; + } + #ifdef WOLFSSL_SMALL_STACK + if (ret != 0) { + /* Info no longer needed as loading failed. */ + XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); + } + #endif + } + + if ((ret == 0) && IS_PRIVKEY_TYPE(type)) { + /* Process the private key. */ + ret = ProcessBufferPrivateKey(ctx, ssl, der, format, info, heap, type, + algId); + #ifdef WOLFSSL_SMALL_STACK + /* Info no longer needed - keep max memory usage down. */ + XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); + #endif + } + else if (ret == 0) { + /* Processing a cerificate. */ + if (userChain) { + /* Take original buffer and add to user chain to send in TLS + * handshake. */ + ret = ProcessUserChain(ctx, ssl, buff, sz, format, type, used, info, + verify); + /* Additional chain is optional */ + if (ret == WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) { + unsigned long pemErr = 0; + CLEAR_ASN_NO_PEM_HEADER_ERROR(pemErr); + ret = 0; + } + } + + #ifdef WOLFSSL_SMALL_STACK + /* Info no longer needed - keep max memory usage down. */ + XFREE(info, heap, DYNAMIC_TYPE_ENCRYPTEDINFO); + #endif + + if (ret == 0) { + /* Process the different types of certificates. */ + ret = ProcessBufferCertTypes(ctx, ssl, buff, sz, der, format, type, + verify); + } + else { + FreeDer(&der); + } + } + + /* Reset suites if this is a private key or user certificate. */ + if ((ret == 0) && ((type == PRIVATEKEY_TYPE) || (type == CERT_TYPE))) { + ret = ProcessBufferResetSuites(ctx, ssl, type); + } + + /* Convert return code. */ + if (ret == 0) { + ret = 1; + } + else if (ret == WOLFSSL_FATAL_ERROR) { + ret = 0; + } + WOLFSSL_LEAVE("ProcessBuffer", ret); + return ret; +} + +#if defined(WOLFSSL_WPAS) && defined(HAVE_CRL) +/* Try to parse data as a PEM CRL. + * + * @param [in] ctx SSL context object. + * @param [in] buff Buffer containing potential CRL in PEM format. + * @param [in] sz Amount of data in buffer remaining. + * @param [out] consumed Number of bytes in buffer was the CRL. + * @return 0 on success. + */ +static int ProcessChainBufferCRL(WOLFSSL_CTX* ctx, const unsigned char* buff, + long sz, long* consumed) +{ + int ret; + DerBuffer* der = NULL; + EncryptedInfo info; + + WOLFSSL_MSG("Trying a CRL"); + ret = PemToDer(buff, sz, CRL_TYPE, &der, NULL, &info, NULL); + if (ret == 0) { + WOLFSSL_MSG(" Processed a CRL"); + wolfSSL_CertManagerLoadCRLBuffer(ctx->cm, der->buffer, der->length, + WOLFSSL_FILETYPE_ASN1); + FreeDer(&der); + *consumed = info.consumed; + } + + return ret; +} +#endif + +/* Process all chain certificates (and CRLs) in the PEM data. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] buff Buffer containing PEM data. + * @param [in] sz Size of data in buffer. + * @param [in] type Type of data. + * @param [in] verify How to verify certificate. + * @return 1 on success. + * @return 0 on failure. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int ProcessChainBuffer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const unsigned char* buff, long sz, int type, int verify) +{ + int ret = 0; + long used = 0; + int gotOne = 0; + + WOLFSSL_MSG("Processing CA PEM file"); + /* Keep processing file while no errors and data to parse. */ + while ((ret >= 0) && (used < sz)) { + long consumed = 0; + + /* Process the buffer. */ + ret = ProcessBuffer(ctx, buff + used, sz - used, WOLFSSL_FILETYPE_PEM, + type, ssl, &consumed, 0, verify); + /* Memory allocation failure is fatal. */ + if (ret == WC_NO_ERR_TRACE(MEMORY_E)) { + gotOne = 0; + } + /* Other error parsing. */ + else if (ret < 0) { +#if defined(WOLFSSL_WPAS) && defined(HAVE_CRL) + /* Try parsing a CRL. */ + if (ProcessChainBufferCRL(ctx, buff + used, sz - used, + &consumed) == 0) { + ret = 0; + } + else +#endif + /* Check whether we made progress. */ + if (consumed > 0) { + WOLFSSL_ERROR(ret); + WOLFSSL_MSG("CA Parse failed, with progress in file."); + WOLFSSL_MSG("Search for other certs in file"); + /* Check if we have more data to parse to recover. */ + if (used + consumed < sz) { + ret = 0; + } + } + else { + /* No progress in parsing being made - stop here. */ + WOLFSSL_MSG("CA Parse failed, no progress in file."); + WOLFSSL_MSG("Do not continue search for other certs in file"); + } + } + else { + /* Got a certificate out. */ + WOLFSSL_MSG(" Processed a CA"); + gotOne = 1; + } + /* Update used count. */ + used += consumed; + } + + /* May have other unparsable data but did we get a certificate? */ + if (gotOne) { + WOLFSSL_MSG("Processed at least one valid CA. Other stuff OK"); + ret = 1; + } + return ret; +} + + +/* Get verify settings for AddCA from SSL context. */ +#define GET_VERIFY_SETTING_CTX(ctx) \ + ((ctx) && (ctx)->verifyNone ? NO_VERIFY : VERIFY) +/* Get verify settings for AddCA from SSL. */ +#define GET_VERIFY_SETTING_SSL(ssl) \ + ((ssl)->options.verifyNone ? NO_VERIFY : VERIFY) + +#ifndef NO_FILESYSTEM + +/* Process data from a file as private keys, CRL or certificates. + * + * @param [in, out] ctx SSL context object. + * @param [in] fname Name of file to read. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @param [in] type Type of data: + * CERT_TYPE, CA_TYPE, TRUSTED_PEER_TYPE, + * PRIVATEKEY_TYPE or ALT_PRIVATEKEY_TYPE. + * @param [in, out] ssl SSL object. + * @param [in] userChain Whether file contains chain of certificates. + * @param [in, out] crl CRL object to load data into. + * @param [in] verify How to verify certificates. + * @return 1 on success. + * @return WOLFSSL_BAD_FILE when reading the file fails. + * @return WOLFSSL_BAD_CERTTYPE when unable to detect certificate type. + */ +int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, + WOLFSSL* ssl, int userChain, WOLFSSL_CRL* crl, int verify) +{ + int ret = 0; +#ifndef WOLFSSL_SMALL_STACK + byte stackBuffer[FILE_BUFFER_SIZE]; +#endif + StaticBuffer content; + long sz = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); + + (void)crl; + (void)heap; + +#ifdef WOLFSSL_SMALL_STACK + static_buffer_init(&content); +#else + static_buffer_init(&content, stackBuffer, FILE_BUFFER_SIZE); +#endif + + /* Read file into static buffer. */ + ret = wolfssl_read_file_static(fname, &content, heap, DYNAMIC_TYPE_FILE, + &sz); + if ((ret == 0) && (type == DETECT_CERT_TYPE) && + (format != WOLFSSL_FILETYPE_PEM)) { + WOLFSSL_MSG("Cannot detect certificate type when not PEM"); + ret = WOLFSSL_BAD_CERTTYPE; + } + /* Try to detect type by parsing cert header and footer. */ + if ((ret == 0) && (type == DETECT_CERT_TYPE)) { +#if !defined(NO_CODING) && !defined(WOLFSSL_NO_PEM) + const char* header = NULL; + const char* footer = NULL; + + /* Look for CA header and footer - same as CERT_TYPE. */ + if (wc_PemGetHeaderFooter(CA_TYPE, &header, &footer) == 0 && + (XSTRNSTR((char*)content.buffer, header, (word32)sz) != NULL)) { + type = CA_TYPE; + } +#ifdef HAVE_CRL + /* Look for CRL header and footer. */ + else if (wc_PemGetHeaderFooter(CRL_TYPE, &header, &footer) == 0 && + (XSTRNSTR((char*)content.buffer, header, (word32)sz) != NULL)) { + type = CRL_TYPE; + } +#endif + /* Look for cert header and footer - same as CA_TYPE. */ + else if (wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer) == 0 && + (XSTRNSTR((char*)content.buffer, header, (word32)sz) != + NULL)) { + type = CERT_TYPE; + } + else +#endif + { + /* Not a header that we support. */ + WOLFSSL_MSG("Failed to detect certificate type"); + ret = WOLFSSL_BAD_CERTTYPE; + } + } + if (ret == 0) { + /* When CA or trusted peer and PEM - process as a chain buffer. */ + if (((type == CA_TYPE) || (type == TRUSTED_PEER_TYPE)) && + (format == WOLFSSL_FILETYPE_PEM)) { + ret = ProcessChainBuffer(ctx, ssl, content.buffer, sz, type, + verify); + } +#ifdef HAVE_CRL + else if (type == CRL_TYPE) { + /* Load the CRL. */ + ret = BufferLoadCRL(crl, content.buffer, sz, format, verify); + } +#endif +#ifdef WOLFSSL_DUAL_ALG_CERTS + else if (type == PRIVATEKEY_TYPE) { + /* When support for dual algorithm certificates is enabled, the + * private key file may contain both the primary and the + * alternative private key. Hence, we have to parse both of them. + */ + long consumed = 0; + + ret = ProcessBuffer(ctx, content.buffer, sz, format, type, ssl, + &consumed, userChain, verify); + if ((ret == 1) && (consumed < sz)) { + ret = ProcessBuffer(ctx, content.buffer + consumed, + sz - consumed, format, ALT_PRIVATEKEY_TYPE, ssl, NULL, 0, + verify); + } + } +#endif + else { + /* Load all other certificate types. */ + ret = ProcessBuffer(ctx, content.buffer, sz, format, type, ssl, + NULL, userChain, verify); + } + } + + /* Dispose of dynamically allocated data. */ + static_buffer_free(&content, heap, DYNAMIC_TYPE_FILE); + return ret; +} + +#ifndef NO_WOLFSSL_DIR +/* Load file when filename is in the path. + * + * @param [in, out] ctx SSL context object. + * @param [in] name Name of file. + * @param [in] verify How to verify a certificate. + * @param [in] flags Flags representing options for loading. + * @param [in, out] failCount Number of files that failed to load. + * @param [in, out] successCount Number of files successfully loaded. + * @return 1 on success. + * @return Not 1 when loading PEM certificate failed. + */ +static int wolfssl_ctx_load_path_file(WOLFSSL_CTX* ctx, const char* name, + int verify, int flags, int* failCount, int* successCount) +{ + int ret; + + /* Attempt to load file as a CA. */ + ret = ProcessFile(ctx, name, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0, NULL, + verify); + if (ret != 1) { + /* When ignoring errors or loading PEM only and no PEM. don't fail. */ + if ((flags & WOLFSSL_LOAD_FLAG_IGNORE_ERR) || + ((flags & WOLFSSL_LOAD_FLAG_PEM_CA_ONLY) && + (ret == WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)))) { + unsigned long err = 0; + CLEAR_ASN_NO_PEM_HEADER_ERROR(err); + #if defined(WOLFSSL_QT) + ret = 1; + #endif + } + else { + WOLFSSL_ERROR(ret); + WOLFSSL_MSG("Load CA file failed, continuing"); + /* Add to fail count. */ + (*failCount)++; + } + } + else { + #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) + /* Try loading as a trusted peer certificate. */ + ret = wolfSSL_CTX_trust_peer_cert(ctx, name, WOLFSSL_FILETYPE_PEM); + if (ret != 1) { + WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error. " + "Ignoring this error."); + } + #endif + /* Add to success count. */ + (*successCount)++; + } + + return ret; +} + +/* Load PEM formatted CA files from a path. + * + * @param [in, out] ctx SSL context object. + * @param [in] path Path to directory to read. + * @param [in] flags Flags representing options for loading. + * @param [in] verify How to verify a certificate. + * @param [in] successCount Number of files successfully loaded. + * @return 1 on success. + * @return 0 on failure. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int wolfssl_ctx_load_path(WOLFSSL_CTX* ctx, const char* path, + word32 flags, int verify, int successCount) +{ + int ret = 1; + char* name = NULL; + int fileRet; + int failCount = 0; +#ifdef WOLFSSL_SMALL_STACK + ReadDirCtx* readCtx; +#else + ReadDirCtx readCtx[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for directory reading context. */ + readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap, + DYNAMIC_TYPE_DIRCTX); + if (readCtx == NULL) { + ret = MEMORY_E; + } +#endif + + if (ret == 1) { + /* Get name of first file in path. */ + fileRet = wc_ReadDirFirst(readCtx, path, &name); + /* While getting filename doesn't fail and name returned, process file. + */ + while ((fileRet == 0) && (name != NULL)) { + WOLFSSL_MSG(name); + /* Load file. */ + ret = wolfssl_ctx_load_path_file(ctx, name, verify, (int)flags, + &failCount, &successCount); + /* Get next filenmae. */ + fileRet = wc_ReadDirNext(readCtx, path, &name); + } + /* Cleanup directory reading context. */ + wc_ReadDirClose(readCtx); + + /* When not WOLFSSL_QT, ret is always overwritten. */ + (void)ret; + + /* Return real directory read failure error codes. */ + if (fileRet != WC_READDIR_NOFILE) { + ret = fileRet; + #if defined(WOLFSSL_QT) || defined(WOLFSSL_IGNORE_BAD_CERT_PATH) + /* Ignore bad path error when flag set. */ + if ((ret == WC_NO_ERR_TRACE(BAD_PATH_ERROR)) && + (flags & WOLFSSL_LOAD_FLAG_IGNORE_BAD_PATH_ERR)) { + /* QSslSocket always loads certs in system folder + * when it is initialized. + * Compliant with OpenSSL when flag set. + */ + ret = 1; + } + else { + /* qssl socket wants to know errors. */ + WOLFSSL_ERROR(ret); + } + #endif + } + /* Report failure if no files successfully loaded or there were + * failures. */ + else if ((successCount == 0) || (failCount > 0)) { + /* Use existing error code if exists. */ + #if defined(WOLFSSL_QT) + /* Compliant with OpenSSL when flag set. */ + if (!(flags & WOLFSSL_LOAD_FLAG_IGNORE_ZEROFILE)) + #endif + { + /* Return 0 when no files loaded. */ + ret = 0; + } + } + else { + /* We loaded something so it is a success. */ + ret = 1; + } + + #ifdef WOLFSSL_SMALL_STACK + /* Dispose of dynamically allocated memory. */ + XFREE(readCtx, ctx->heap, DYNAMIC_TYPE_DIRCTX); + #endif + } + + return ret; +} +#endif + +/* Load a file and/or files in path + * + * No c_rehash. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of file to load. May be NULL. + * @param [in] path Path to directory containing PEM CA files. + * May be NULL. + * @param [in] flags Flags representing options for loading. + * @return 1 on success. + * @return 0 on failure. + * @return NOT_COMPILED_IN when directory reading not supported and path is + * not NULL. + * @return Other negative on error. + */ +int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, + const char* path, word32 flags) +{ + int ret = 1; +#ifndef NO_WOLFSSL_DIR + int successCount = 0; +#endif + int verify = WOLFSSL_VERIFY_DEFAULT; + + WOLFSSL_MSG("wolfSSL_CTX_load_verify_locations_ex"); + + /* Validate parameters. */ + if ((ctx == NULL) || ((file == NULL) && (path == NULL))) { + ret = 0; + } + + if (ret == 1) { + /* Get setting on how to verify certificates. */ + verify = GET_VERIFY_SETTING_CTX(ctx); + /* Overwrite setting when flag set. */ + if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) { + verify = VERIFY_SKIP_DATE; + } + + if (file != NULL) { + /* Load the PEM formatted CA file. */ + ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0, + NULL, verify); + #ifndef NO_WOLFSSL_DIR + if (ret == 1) { + /* Include success in overall count. */ + successCount++; + } + #endif + #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) + /* Load CA as a trusted peer certificate. */ + ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM); + if (ret != 1) { + WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error"); + } + #endif + } + } + + if ((ret == 1) && (path != NULL)) { +#ifndef NO_WOLFSSL_DIR + /* Load CA files form path. */ + ret = wolfssl_ctx_load_path(ctx, path, flags, verify, successCount); +#else + /* Loading a path not supported. */ + ret = NOT_COMPILED_IN; + (void)flags; +#endif + } + + return ret; +} + +/* Load a file and/or files in path + * + * No c_rehash. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of file to load. May be NULL. + * @param [in] path Path to directory containing PEM CA files. + * May be NULL. + * @return 1 on success. + * @return 0 on failure. + */ +WOLFSSL_ABI +int wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, + const char* path) +{ + /* Load using default flags/options. */ + int ret = wolfSSL_CTX_load_verify_locations_ex(ctx, file, path, + WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); + + /* Return 1 on success or 0 on failure. */ + return WS_RETURN_CODE(ret, 0); +} + +#ifdef WOLFSSL_SYS_CA_CERTS + +#ifdef USE_WINDOWS_API + +/* Load CA certificate from Windows store. + * + * Assumes loaded is 0. + * + * @param [in, out] ctx SSL context object. + * @param [out] loaded Whether CA certificates were loaded. + * @return 1 on success. + * @return 0 on failure. + */ +static int LoadSystemCaCertsWindows(WOLFSSL_CTX* ctx, byte* loaded) +{ + int ret = 1; + word32 i; + HANDLE handle = NULL; + PCCERT_CONTEXT certCtx = NULL; + LPCSTR storeNames[2] = {"ROOT", "CA"}; + HCRYPTPROV_LEGACY hProv = (HCRYPTPROV_LEGACY)NULL; + + if ((ctx == NULL) || (loaded == NULL)) { + ret = 0; + } + + for (i = 0; (ret == 1) && (i < sizeof(storeNames)/sizeof(*storeNames)); + ++i) { + handle = CertOpenSystemStoreA(hProv, storeNames[i]); + if (handle != NULL) { + while ((certCtx = CertEnumCertificatesInStore(handle, certCtx)) + != NULL) { + if (certCtx->dwCertEncodingType == X509_ASN_ENCODING) { + if (ProcessBuffer(ctx, certCtx->pbCertEncoded, + certCtx->cbCertEncoded, WOLFSSL_FILETYPE_ASN1, + CA_TYPE, NULL, NULL, 0, + GET_VERIFY_SETTING_CTX(ctx)) == 1) { + /* + * Set "loaded" as long as we've loaded one CA + * cert. + */ + *loaded = 1; + } + } + } + } + else { + WOLFSSL_MSG_EX("Failed to open cert store %s.", storeNames[i]); + } + + if (handle != NULL && !CertCloseStore(handle, 0)) { + WOLFSSL_MSG_EX("Failed to close cert store %s.", storeNames[i]); + ret = 0; + } + } + + return ret; +} + +#elif defined(__APPLE__) + +#if defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) \ + && !defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) +/* Manually obtains certificates from the system trust store and loads them + * directly into wolfSSL "the old way". + * + * As of MacOS 14.0 we are still able to use this method to access system + * certificates. Accessibility of this API is indicated by the presence of the + * Security/SecTrustSettings.h header. In the likely event that Apple removes + * access to this API on Macs, this function should be removed and the + * DoAppleNativeCertValidation() routine should be used for all devices. + * + * Assumes loaded is 0. + * + * @param [in, out] ctx SSL context object. + * @param [out] loaded Whether CA certificates were loaded. + * @return 1 on success. + * @return 0 on failure. + */ +static int LoadSystemCaCertsMac(WOLFSSL_CTX* ctx, byte* loaded) +{ + int ret = 1; + word32 i; + const unsigned int trustDomains[] = { + kSecTrustSettingsDomainUser, + kSecTrustSettingsDomainAdmin, + kSecTrustSettingsDomainSystem + }; + CFArrayRef certs; + OSStatus stat; + CFIndex numCerts; + CFDataRef der; + CFIndex j; + + if ((ctx == NULL) || (loaded == NULL)) { + ret = 0; + } + + for (i = 0; (ret == 1) && (i < sizeof(trustDomains)/sizeof(*trustDomains)); + ++i) { + stat = SecTrustSettingsCopyCertificates( + (SecTrustSettingsDomain)trustDomains[i], &certs); + if (stat == errSecSuccess) { + numCerts = CFArrayGetCount(certs); + for (j = 0; j < numCerts; ++j) { + der = SecCertificateCopyData((SecCertificateRef) + CFArrayGetValueAtIndex(certs, j)); + if (der != NULL) { + if (ProcessBuffer(ctx, CFDataGetBytePtr(der), + CFDataGetLength(der), WOLFSSL_FILETYPE_ASN1, + CA_TYPE, NULL, NULL, 0, + GET_VERIFY_SETTING_CTX(ctx)) == 1) { + /* + * Set "loaded" as long as we've loaded one CA + * cert. + */ + *loaded = 1; + } + + CFRelease(der); + } + } + + CFRelease(certs); + } + else if (stat == errSecNoTrustSettings) { + WOLFSSL_MSG_EX("No trust settings for domain %d, moving to next " + "domain.", trustDomains[i]); + } + else { + WOLFSSL_MSG_EX("SecTrustSettingsCopyCertificates failed with" + " status %d.", stat); + ret = 0; + break; + } + } + + return ret; +} +#endif /* defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) */ + +#else + +/* Potential system CA certs directories on Linux/Unix distros. */ +static const char* systemCaDirs[] = { +#if defined(__ANDROID__) || defined(ANDROID) + "/system/etc/security/cacerts" /* Android */ +#else + "/etc/ssl/certs", /* Debian, Ubuntu, Gentoo, others */ + "/etc/pki/ca-trust/source/anchors", /* Fedora, RHEL */ + "/etc/pki/tls/certs" /* Older RHEL */ +#endif +}; + +/* Get CA directory list. + * + * @param [out] num Number of CA directories. + * @return CA directory list. + * @return NULL when num is NULL. + */ +const char** wolfSSL_get_system_CA_dirs(word32* num) +{ + const char** ret; + + /* Validate parameters. */ + if (num == NULL) { + ret = NULL; + } + else { + ret = systemCaDirs; + *num = sizeof(systemCaDirs)/sizeof(*systemCaDirs); + } + + return ret; +} + +/* Load CA certificate from default system directories. + * + * Assumes loaded is 0. + * + * @param [in, out] ctx SSL context object. + * @param [out] loaded Whether CA certificates were loaded. + * @return 1 on success. + * @return 0 on failure. + */ +static int LoadSystemCaCertsNix(WOLFSSL_CTX* ctx, byte* loaded) { + int ret = 1; + word32 i; + + if ((ctx == NULL) || (loaded == NULL)) { + ret = 0; + } + + for (i = 0; (ret == 1) && (i < sizeof(systemCaDirs)/sizeof(*systemCaDirs)); + ++i) { + WOLFSSL_MSG_EX("Attempting to load system CA certs from %s.", + systemCaDirs[i]); + /* + * We want to keep trying to load more CA certs even if one cert in + * the directory is bad and can't be used (e.g. if one is expired), + * so we use WOLFSSL_LOAD_FLAG_IGNORE_ERR. + */ + if (wolfSSL_CTX_load_verify_locations_ex(ctx, NULL, systemCaDirs[i], + WOLFSSL_LOAD_FLAG_IGNORE_ERR) != 1) { + WOLFSSL_MSG_EX("Failed to load CA certs from %s, trying " + "next possible location.", systemCaDirs[i]); + } + else { + WOLFSSL_MSG_EX("Loaded CA certs from %s.", + systemCaDirs[i]); + *loaded = 1; + /* Stop searching after we've loaded one directory. */ + break; + } + } + + return ret; +} + +#endif + +/* Load CA certificates from system defined locations. + * + * @param [in, out] ctx SSL context object. + * @return 1 on success. + * @return 0 on failure. + * @return WOLFSSL_BAD_PATH when no error but no certificates loaded. + */ +int wolfSSL_CTX_load_system_CA_certs(WOLFSSL_CTX* ctx) +{ + int ret; + byte loaded = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_load_system_CA_certs"); + +#ifdef USE_WINDOWS_API + + ret = LoadSystemCaCertsWindows(ctx, &loaded); + +#elif defined(__APPLE__) + +#if defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) \ + && !defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) + /* As of MacOS 14.0 we are still able to access system certificates and + * load them manually into wolfSSL "the old way". Accessibility of this API + * is indicated by the presence of the Security/SecTrustSettings.h header */ + ret = LoadSystemCaCertsMac(ctx, &loaded); +#elif defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) + /* For other Apple devices, Apple has removed the ability to obtain + * certificates from the trust store, so we can't use wolfSSL's built-in + * certificate validation mechanisms anymore. We instead must call into the + * Security Framework APIs to authenticate peer certificates when received. + * (see src/internal.c:DoAppleNativeCertValidation()). + * Thus, there is no CA "loading" required, but to keep behavior consistent + * with the current API (not using system CA certs unless this function has + * been called), we simply set a flag indicating that the new apple trust + * verification routine should be used later */ + ctx->doAppleNativeCertValidationFlag = 1; + ret = 1; + loaded = 1; + +#if FIPS_VERSION_GE(2,0) /* Gate back to cert 3389 FIPS modules */ +#warning "Cryptographic operations may occur outside the FIPS module boundary" \ + "Please review FIPS claims for cryptography on this Apple device" +#endif /* FIPS_VERSION_GE(2,0) */ + +#else +/* HAVE_SECURITY_SECXXX_H macros are set by autotools or CMake when searching + * system for the required SDK headers. If building with user_settings.h, you + * will need to manually define WOLFSSL_APPLE_NATIVE_CERT_VALIDATION + * and ensure the appropriate Security.framework headers and libraries are + * visible to your compiler */ +#error "WOLFSSL_SYS_CA_CERTS on Apple devices requires Security.framework" \ + " header files to be detected, or a manual override with" \ + " WOLFSSL_APPLE_NATIVE_CERT_VALIDATION" +#endif + +#else + + ret = LoadSystemCaCertsNix(ctx, &loaded); + +#endif + + /* If we didn't fail but didn't load then we error out. */ + if ((ret == 1) && (!loaded)) { + ret = WOLFSSL_BAD_PATH; + } + + WOLFSSL_LEAVE("wolfSSL_CTX_load_system_CA_certs", ret); + + return ret; +} + +#endif /* WOLFSSL_SYS_CA_CERTS */ + +#ifdef WOLFSSL_TRUST_PEER_CERT +/* Load a trusted peer certificate into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of peer certificate file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 when ctx or file is NULL. + */ +int wolfSSL_CTX_trust_peer_cert(WOLFSSL_CTX* ctx, const char* file, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_cert"); + + /* Validate parameters. */ + if ((ctx == NULL) || (file == NULL)) { + ret = 0; + } + else { + ret = ProcessFile(ctx, file, format, TRUSTED_PEER_TYPE, NULL, 0, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + } + + return ret; +} + +/* Load a trusted peer certificate into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of peer certificate file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 when ssl or file is NULL. + */ +int wolfSSL_trust_peer_cert(WOLFSSL* ssl, const char* file, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_trust_peer_cert"); + + /* Validate parameters. */ + if ((ssl == NULL) || (file == NULL)) { + ret = 0; + } + else { + ret = ProcessFile(NULL, file, format, TRUSTED_PEER_TYPE, ssl, 0, NULL, + GET_VERIFY_SETTING_SSL(ssl)); + } + + return ret; +} +#endif /* WOLFSSL_TRUST_PEER_CERT */ + + +#ifdef WOLFSSL_DER_LOAD + +/* Load a CA certificate into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of peer certificate file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_der_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, + int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_der_load_verify_locations"); + + /* Validate parameters. */ + if ((ctx == NULL) || (file == NULL)) { + ret = 0; + } + else { + ret = ProcessFile(ctx, file, format, CA_TYPE, NULL, 0, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + } + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +#endif /* WOLFSSL_DER_LOAD */ + + +/* Load a user certificate into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of user certificate file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +WOLFSSL_ABI +int wolfSSL_CTX_use_certificate_file(WOLFSSL_CTX* ctx, const char* file, + int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_file"); + + ret = ProcessFile(ctx, file, format, CERT_TYPE, NULL, 0, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + + +/* Load a private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of private key file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +WOLFSSL_ABI +int wolfSSL_CTX_use_PrivateKey_file(WOLFSSL_CTX* ctx, const char* file, + int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_file"); + + ret = ProcessFile(ctx, file, format, PRIVATEKEY_TYPE, NULL, 0, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +/* Load an alternative private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of private key file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_AltPrivateKey_file(WOLFSSL_CTX* ctx, const char* file, + int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_AltPrivateKey_file"); + + ret = ProcessFile(ctx, file, format, ALT_PRIVATEKEY_TYPE, NULL, 0, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + + +/* Load a PEM certificate chain into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of PEM certificate chain file. + * @return 1 on success. + * @return 0 on failure. + */ +WOLFSSL_ABI +int wolfSSL_CTX_use_certificate_chain_file(WOLFSSL_CTX* ctx, const char* file) +{ + int ret; + + /* process up to MAX_CHAIN_DEPTH plus subject cert */ + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file"); + + ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE, NULL, 1, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +/* Load certificate chain into SSL context. + * + * Processes up to MAX_CHAIN_DEPTH plus subject cert. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of private key file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_certificate_chain_file_format(WOLFSSL_CTX* ctx, + const char* file, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_file_format"); + + ret = ProcessFile(ctx, file, format, CERT_TYPE, NULL, 1, NULL, + GET_VERIFY_SETTING_CTX(ctx)); + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +#endif /* NO_FILESYSTEM */ + +#ifdef OPENSSL_EXTRA + +/* Load a private key into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] pkey EVP private key. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_PrivateKey(WOLFSSL* ssl, WOLFSSL_EVP_PKEY* pkey) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_PrivateKey"); + + /* Validate parameters. */ + if ((ssl == NULL) || (pkey == NULL)) { + ret = 0; + } + else { + /* Get DER encoded key data from EVP private key. */ + ret = wolfSSL_use_PrivateKey_buffer(ssl, (unsigned char*)pkey->pkey.ptr, + pkey->pkey_sz, WOLFSSL_FILETYPE_ASN1); + } + + return ret; +} + +/* Load a DER encoded private key in a buffer into SSL. + * + * @param [in] pri Indicates type of private key. Ignored. + * @param [in, out] ssl SSL object. + * @param [in] der Buffer holding DER encoded private key. + * @param [in] derSz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_PrivateKey_ASN1(int pri, WOLFSSL* ssl, const unsigned char* der, + long derSz) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_PrivateKey_ASN1"); + + (void)pri; + + /* Validate parameters. */ + if ((ssl == NULL) || (der == NULL)) { + ret = 0; + } + else { + ret = wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, + WOLFSSL_FILETYPE_ASN1); + } + + return ret; +} + +/* Load a DER encoded private key in a buffer into SSL context. + * + * @param [in] pri Indicates type of private key. Ignored. + * @param [in, out] ctx SSL context object. + * @param [in] der Buffer holding DER encoded private key. + * @param [in] derSz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_PrivateKey_ASN1(int pri, WOLFSSL_CTX* ctx, + unsigned char* der, long derSz) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_ASN1"); + + (void)pri; + + /* Validate parameters. */ + if ((ctx == NULL) || (der == NULL)) { + ret = 0; + } + else { + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, derSz, + WOLFSSL_FILETYPE_ASN1); + } + + return ret; +} + + +#ifndef NO_RSA +/* Load a DER encoded RSA private key in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] der Buffer holding DER encoded RSA private key. + * @param [in] derSz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_RSAPrivateKey_ASN1(WOLFSSL* ssl, unsigned char* der, long derSz) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_ASN1"); + + /* Validate parameters. */ + if ((ssl == NULL) || (der == NULL)) { + ret = 0; + } + else { + ret = wolfSSL_use_PrivateKey_buffer(ssl, der, derSz, + WOLFSSL_FILETYPE_ASN1); + } + + return ret; +} +#endif + +/* Load a certificate into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_certificate(WOLFSSL* ssl, WOLFSSL_X509* x509) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate"); + + /* Validate parameters. */ + if ((ssl == NULL) || (x509 == NULL) || (x509->derCert == NULL)) { + ret = 0; + } + else { + long idx = 0; + + /* Get DER encoded certificate data from X509 object. */ + ret = ProcessBuffer(NULL, x509->derCert->buffer, x509->derCert->length, + WOLFSSL_FILETYPE_ASN1, CERT_TYPE, ssl, &idx, 0, + GET_VERIFY_SETTING_SSL(ssl)); + } + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +#endif /* OPENSSL_EXTRA */ + +/* Load a DER encoded certificate in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] der Buffer holding DER encoded certificate. + * @param [in] derSz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_certificate_ASN1(WOLFSSL* ssl, const unsigned char* der, + int derSz) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate_ASN1"); + + /* Validate parameters. */ + if ((ssl == NULL) || (der == NULL)) { + ret = 0; + } + else { + long idx = 0; + + ret = ProcessBuffer(NULL, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, + ssl, &idx, 0, GET_VERIFY_SETTING_SSL(ssl)); + } + + /* Return 1 on success or 0 on failure. */ + return WS_RC(ret); +} + +#ifndef NO_FILESYSTEM + +/* Load a certificate from a file into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +WOLFSSL_ABI +int wolfSSL_use_certificate_file(WOLFSSL* ssl, const char* file, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate_file"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessFile(ssl->ctx, file, format, CERT_TYPE, ssl, 0, NULL, + GET_VERIFY_SETTING_SSL(ssl)); + /* Return 1 on success or 0 on failure. */ + ret = WS_RC(ret); + } + + return ret; +} + + +/* Load a private key from a file into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +WOLFSSL_ABI +int wolfSSL_use_PrivateKey_file(WOLFSSL* ssl, const char* file, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_PrivateKey_file"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessFile(ssl->ctx, file, format, PRIVATEKEY_TYPE, ssl, 0, NULL, + GET_VERIFY_SETTING_SSL(ssl)); + /* Return 1 on success or 0 on failure. */ + ret = WS_RC(ret); + } + + return ret; +} + + +/* Load a PEM encoded certificate chain from a file into SSL. + * + * Process up to MAX_CHAIN_DEPTH plus subject cert. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of file. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +WOLFSSL_ABI +int wolfSSL_use_certificate_chain_file(WOLFSSL* ssl, const char* file) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessFile(ssl->ctx, file, WOLFSSL_FILETYPE_PEM, CERT_TYPE, ssl, + 1, NULL, GET_VERIFY_SETTING_SSL(ssl)); + /* Return 1 on success or 0 on failure. */ + ret = WS_RC(ret); + } + + return ret; +} + +/* Load a certificate chain from a file into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +int wolfSSL_use_certificate_chain_file_format(WOLFSSL* ssl, const char* file, + int format) +{ + int ret; + + /* process up to MAX_CHAIN_DEPTH plus subject cert */ + WOLFSSL_ENTER("wolfSSL_use_certificate_chain_file_format"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessFile(ssl->ctx, file, format, CERT_TYPE, ssl, 1, NULL, + GET_VERIFY_SETTING_SSL(ssl)); + /* Return 1 on success or 0 on failure. */ + ret = WS_RC(ret); + } + + return ret; +} + +#endif /* !NO_FILESYSTEM */ + +#ifdef OPENSSL_EXTRA + +#ifndef NO_FILESYSTEM +/* Load an RSA private key from a file into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_RSAPrivateKey_file(WOLFSSL_CTX* ctx,const char* file, + int format) +{ + WOLFSSL_ENTER("wolfSSL_CTX_use_RSAPrivateKey_file"); + + return wolfSSL_CTX_use_PrivateKey_file(ctx, file, format); +} + +/* Load an RSA private key from a file into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] file Name of file. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +int wolfSSL_use_RSAPrivateKey_file(WOLFSSL* ssl, const char* file, int format) +{ + WOLFSSL_ENTER("wolfSSL_use_RSAPrivateKey_file"); + + return wolfSSL_use_PrivateKey_file(ssl, file, format); +} +#endif /* NO_FILESYSTEM */ + +#endif /* OPENSSL_EXTRA */ + +/* Load a buffer of certificate/s into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding certificate or private key. + * @param [in] sz Length of data in buffer in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @param [in] userChain Whether file contains chain of certificates. + * @param [in] flags Flags representing options for loading. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_load_verify_buffer_ex(WOLFSSL_CTX* ctx, const unsigned char* in, + long sz, int format, int userChain, word32 flags) +{ + int ret; + int verify; + + WOLFSSL_ENTER("wolfSSL_CTX_load_verify_buffer_ex"); + + /* Get setting on how to verify certificates. */ + verify = GET_VERIFY_SETTING_CTX(ctx); + /* Overwrite setting when flag set. */ + if (flags & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY) { + verify = VERIFY_SKIP_DATE; + } + + /* When PEM, treat as certificate chain of CA certificates. */ + if (format == WOLFSSL_FILETYPE_PEM) { + ret = ProcessChainBuffer(ctx, NULL, in, sz, CA_TYPE, verify); + } + /* When DER, load the CA certificate. */ + else { + ret = ProcessBuffer(ctx, in, sz, format, CA_TYPE, NULL, NULL, + userChain, verify); + } +#if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) + if (ret == 1) { + /* Load certificate/s as trusted peer certificate. */ + ret = wolfSSL_CTX_trust_peer_buffer(ctx, in, sz, format); + } +#endif + + WOLFSSL_LEAVE("wolfSSL_CTX_load_verify_buffer_ex", ret); + return ret; +} + +/* Load a buffer of certificate/s into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding certificate or private key. + * @param [in] sz Length of data in buffer in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_load_verify_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, + long sz, int format) +{ + return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 0, + WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); +} + +/* Load a buffer of certificate chain into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding certificate chain. + * @param [in] sz Length of data in buffer in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_load_verify_chain_buffer_format(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz, int format) +{ + return wolfSSL_CTX_load_verify_buffer_ex(ctx, in, sz, format, 1, + WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS); +} + + +#ifdef WOLFSSL_TRUST_PEER_CERT +/* Load a buffer of certificate/s into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding certificate/s. + * @param [in] sz Length of data in buffer in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ctx or in is NULL, or sz is less than zero. + */ +int wolfSSL_CTX_trust_peer_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, + long sz, int format) +{ + int ret; + int verify; + + WOLFSSL_ENTER("wolfSSL_CTX_trust_peer_buffer"); + + /* Validate parameters. */ + if ((ctx == NULL) || (in == NULL) || (sz < 0)) { + ret = BAD_FUNC_ARG; + } + else { + #if WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS & WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY + verify = VERIFY_SKIP_DATE; + #else + verify = GET_VERIFY_SETTING_CTX(ctx); + #endif + + /* When PEM, treat as certificate chain of trusted peer certificates. */ + if (format == WOLFSSL_FILETYPE_PEM) { + ret = ProcessChainBuffer(ctx, NULL, in, sz, TRUSTED_PEER_TYPE, + verify); + } + /* When DER, load the trusted peer certificate. */ + else { + ret = ProcessBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE, NULL, + NULL, 0, verify); + } + } + + return ret; +} +#endif /* WOLFSSL_TRUST_PEER_CERT */ + +/* Load a certificate in a buffer into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding certificate. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_use_certificate_buffer(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_buffer"); + ret = ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 0, + GET_VERIFY_SETTING_CTX(ctx)); + WOLFSSL_LEAVE("wolfSSL_CTX_use_certificate_buffer", ret); + + return ret; +} + +/* Load a private key in a buffer into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding private key. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_use_PrivateKey_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, + long sz, int format) +{ + int ret; + long consumed = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_buffer"); + + ret = ProcessBuffer(ctx, in, sz, format, PRIVATEKEY_TYPE, NULL, &consumed, + 0, GET_VERIFY_SETTING_CTX(ctx)); +#ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ret == 1) && (consumed < sz)) { + /* When support for dual algorithm certificates is enabled, the + * buffer may contain both the primary and the alternative + * private key. Hence, we have to parse both of them. + */ + ret = ProcessBuffer(ctx, in + consumed, sz - consumed, format, + ALT_PRIVATEKEY_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + } +#endif + + (void)consumed; + + WOLFSSL_LEAVE("wolfSSL_CTX_use_PrivateKey_buffer", ret); + return ret; +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +int wolfSSL_CTX_use_AltPrivateKey_buffer(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_AltPrivateKey_buffer"); + ret = ProcessBuffer(ctx, in, sz, format, ALT_PRIVATEKEY_TYPE, NULL, + NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + WOLFSSL_LEAVE("wolfSSL_CTX_use_AltPrivateKey_buffer", ret); + + return ret; +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + +#ifdef WOLF_PRIVATE_KEY_ID +/* Load the id of a private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] id Buffer holding id. + * @param [in] sz Size of data in bytes. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_PrivateKey_Id(WOLFSSL_CTX* ctx, const unsigned char* id, + long sz, int devId) +{ + int ret = 1; + + /* Dispose of old private key and allocate and copy in id. */ + FreeDer(&ctx->privateKey); + if (AllocCopyDer(&ctx->privateKey, id, (word32)sz, PRIVATEKEY_TYPE, + ctx->heap) != 0) { + ret = 0; + } + if (ret == 1) { + /* Private key is an id. */ + ctx->privateKeyId = 1; + ctx->privateKeyLabel = 0; + /* Set private key device id to be one passed in or for SSL context. */ + if (devId != INVALID_DEVID) { + ctx->privateKeyDevId = devId; + } + else { + ctx->privateKeyDevId = ctx->devId; + } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Set the ID for the alternative key, too. User can still override that + * afterwards. */ + ret = wolfSSL_CTX_use_AltPrivateKey_Id(ctx, id, sz, devId); + #endif + } + + return ret; +} + +/* Load the id of a private key into SSL context and set key size. + * + * @param [in, out] ctx SSL context object. + * @param [in] id Buffer holding id. + * @param [in] sz Size of data in bytes. + * @param [in] devId Device identifier. + * @param [in] keySz Size of key. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_PrivateKey_id(WOLFSSL_CTX* ctx, const unsigned char* id, + long sz, int devId, long keySz) +{ + int ret = wolfSSL_CTX_use_PrivateKey_Id(ctx, id, sz, devId); + if (ret == 1) { + /* Set the key size which normally is calculated during decoding. */ + ctx->privateKeySz = (int)keySz; + } + + return ret; +} + +/* Load the label name of a private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] label Buffer holding label. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_PrivateKey_Label(WOLFSSL_CTX* ctx, const char* label, + int devId) +{ + int ret = 1; + word32 sz = (word32)XSTRLEN(label) + 1; + + /* Dispose of old private key and allocate and copy in label. */ + FreeDer(&ctx->privateKey); + if (AllocCopyDer(&ctx->privateKey, (const byte*)label, (word32)sz, + PRIVATEKEY_TYPE, ctx->heap) != 0) { + ret = 0; + } + if (ret == 1) { + /* Private key is a label. */ + ctx->privateKeyId = 0; + ctx->privateKeyLabel = 1; + /* Set private key device id to be one passed in or for SSL context. */ + if (devId != INVALID_DEVID) { + ctx->privateKeyDevId = devId; + } + else { + ctx->privateKeyDevId = ctx->devId; + } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Set the ID for the alternative key, too. User can still override that + * afterwards. */ + ret = wolfSSL_CTX_use_AltPrivateKey_Label(ctx, label, devId); + #endif + } + + return ret; +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +int wolfSSL_CTX_use_AltPrivateKey_Id(WOLFSSL_CTX* ctx, const unsigned char* id, + long sz, int devId) +{ + int ret = 1; + + if ((ctx == NULL) || (id == NULL)) { + ret = 0; + } + + if (ret == 1) { + FreeDer(&ctx->altPrivateKey); + if (AllocDer(&ctx->altPrivateKey, (word32)sz, ALT_PRIVATEKEY_TYPE, + ctx->heap) != 0) { + ret = 0; + } + } + if (ret == 1) { + XMEMCPY(ctx->altPrivateKey->buffer, id, sz); + ctx->altPrivateKeyId = 1; + if (devId != INVALID_DEVID) { + ctx->altPrivateKeyDevId = devId; + } + else { + ctx->altPrivateKeyDevId = ctx->devId; + } + } + + return ret; +} + +int wolfSSL_CTX_use_AltPrivateKey_id(WOLFSSL_CTX* ctx, const unsigned char* id, + long sz, int devId, long keySz) +{ + int ret = wolfSSL_CTX_use_AltPrivateKey_Id(ctx, id, sz, devId); + if (ret == 1) { + ctx->altPrivateKeySz = (word32)keySz; + } + + return ret; +} + +int wolfSSL_CTX_use_AltPrivateKey_Label(WOLFSSL_CTX* ctx, const char* label, + int devId) +{ + int ret = 1; + word32 sz; + + if ((ctx == NULL) || (label == NULL)) { + ret = 0; + } + + if (ret == 1) { + sz = (word32)XSTRLEN(label) + 1; + FreeDer(&ctx->altPrivateKey); + if (AllocDer(&ctx->altPrivateKey, (word32)sz, ALT_PRIVATEKEY_TYPE, + ctx->heap) != 0) { + ret = 0; + } + } + if (ret == 1) { + XMEMCPY(ctx->altPrivateKey->buffer, label, sz); + ctx->altPrivateKeyLabel = 1; + if (devId != INVALID_DEVID) { + ctx->altPrivateKeyDevId = devId; + } + else { + ctx->altPrivateKeyDevId = ctx->devId; + } + } + + return ret; +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ +#endif /* WOLF_PRIVATE_KEY_ID */ + +/* Load a certificate chain in a buffer into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding DER encoded certificate chain. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_use_certificate_chain_buffer_format(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz, int format) +{ + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_buffer_format"); + return ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 1, + GET_VERIFY_SETTING_CTX(ctx)); +} + +/* Load a PEM encoded certificate chain in a buffer into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] in Buffer holding DER encoded certificate chain. + * @param [in] sz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_CTX_use_certificate_chain_buffer(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz) +{ + return wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, in, sz, + WOLFSSL_FILETYPE_PEM); +} + +/* Load a user certificate in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] in Buffer holding user certificate. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +int wolfSSL_use_certificate_buffer(WOLFSSL* ssl, const unsigned char* in, + long sz, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate_buffer"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 0, + GET_VERIFY_SETTING_SSL(ssl)); + } + + return ret; +} + +/* Load a private key in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] in Buffer holding private key. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +int wolfSSL_use_PrivateKey_buffer(WOLFSSL* ssl, const unsigned char* in, + long sz, int format) +{ + int ret; + long consumed = 0; + + WOLFSSL_ENTER("wolfSSL_use_PrivateKey_buffer"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessBuffer(ssl->ctx, in, sz, format, PRIVATEKEY_TYPE, ssl, + &consumed, 0, GET_VERIFY_SETTING_SSL(ssl)); + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ret == 1) && (consumed < sz)) { + /* When support for dual algorithm certificates is enabled, the + * buffer may contain both the primary and the alternative + * private key. Hence, we have to parse both of them. + */ + ret = ProcessBuffer(ssl->ctx, in + consumed, sz - consumed, format, + ALT_PRIVATEKEY_TYPE, ssl, NULL, 0, GET_VERIFY_SETTING_SSL(ssl)); + } + #endif + } + + return ret; +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +int wolfSSL_use_AltPrivateKey_buffer(WOLFSSL* ssl, const unsigned char* in, + long sz, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_AltPrivateKey_buffer"); + ret = ProcessBuffer(ssl->ctx, in, sz, format, ALT_PRIVATEKEY_TYPE, ssl, + NULL, 0, GET_VERIFY_SETTING_SSL(ssl)); + WOLFSSL_LEAVE("wolfSSL_use_AltPrivateKey_buffer", ret); + + return ret; +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + +#ifdef WOLF_PRIVATE_KEY_ID +/* Load the id of a private key into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] id Buffer holding id. + * @param [in] sz Size of data in bytes. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_PrivateKey_Id(WOLFSSL* ssl, const unsigned char* id, + long sz, int devId) +{ + int ret = 1; + + /* Dispose of old private key if owned and allocate and copy in id. */ + if (ssl->buffers.weOwnKey) { + FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif + } + if (AllocCopyDer(&ssl->buffers.key, id, (word32)sz, PRIVATEKEY_TYPE, + ssl->heap) != 0) { + ret = 0; + } + if (ret == 1) { + /* Buffer now ours. */ + ssl->buffers.weOwnKey = 1; + /* Private key is an id. */ + ssl->buffers.keyId = 1; + ssl->buffers.keyLabel = 0; + /* Set private key device id to be one passed in or for SSL. */ + if (devId != INVALID_DEVID) { + ssl->buffers.keyDevId = devId; + } + else { + ssl->buffers.keyDevId = ssl->devId; + } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Set the ID for the alternative key, too. User can still override that + * afterwards. */ + ret = wolfSSL_use_AltPrivateKey_Id(ssl, id, sz, devId); + #endif + } + + return ret; +} + +/* Load the id of a private key into SSL and set key size. + * + * @param [in, out] ssl SSL object. + * @param [in] id Buffer holding id. + * @param [in] sz Size of data in bytes. + * @param [in] devId Device identifier. + * @param [in] keySz Size of key. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_PrivateKey_id(WOLFSSL* ssl, const unsigned char* id, + long sz, int devId, long keySz) +{ + int ret = wolfSSL_use_PrivateKey_Id(ssl, id, sz, devId); + if (ret == 1) { + /* Set the key size which normally is calculated during decoding. */ + ssl->buffers.keySz = (int)keySz; + } + + return ret; +} + +/* Load the label name of a private key into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] label Buffer holding label. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_use_PrivateKey_Label(WOLFSSL* ssl, const char* label, int devId) +{ + int ret = 1; + word32 sz = (word32)XSTRLEN(label) + 1; + + /* Dispose of old private key if owned and allocate and copy in label. */ + if (ssl->buffers.weOwnKey) { + FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif + } + if (AllocCopyDer(&ssl->buffers.key, (const byte*)label, (word32)sz, + PRIVATEKEY_TYPE, ssl->heap) != 0) { + ret = 0; + } + if (ret == 1) { + /* Buffer now ours. */ + ssl->buffers.weOwnKey = 1; + /* Private key is a label. */ + ssl->buffers.keyId = 0; + ssl->buffers.keyLabel = 1; + /* Set private key device id to be one passed in or for SSL. */ + if (devId != INVALID_DEVID) { + ssl->buffers.keyDevId = devId; + } + else { + ssl->buffers.keyDevId = ssl->devId; + } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Set the label for the alternative key, too. User can still override + * that afterwards. */ + ret = wolfSSL_use_AltPrivateKey_Label(ssl, label, devId); + #endif + } + + return ret; +} + +#ifdef WOLFSSL_DUAL_ALG_CERTS +int wolfSSL_use_AltPrivateKey_Id(WOLFSSL* ssl, const unsigned char* id, long sz, + int devId) +{ + int ret = 1; + + if ((ssl == NULL) || (id == NULL)) { + ret = 0; + } + + if (ret == 1) { + if (ssl->buffers.weOwnAltKey) { + FreeDer(&ssl->buffers.altKey); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.altKeyMask); + #endif + } + if (AllocDer(&ssl->buffers.altKey, (word32)sz, ALT_PRIVATEKEY_TYPE, + ssl->heap) == 0) { + ret = 0; + } + } + if (ret == 1) { + XMEMCPY(ssl->buffers.altKey->buffer, id, sz); + ssl->buffers.weOwnAltKey = 1; + ssl->buffers.altKeyId = 1; + if (devId != INVALID_DEVID) { + ssl->buffers.altKeyDevId = devId; + } + else { + ssl->buffers.altKeyDevId = ssl->devId; + } + } + + return ret; +} + +int wolfSSL_use_AltPrivateKey_id(WOLFSSL* ssl, const unsigned char* id, long sz, + int devId, long keySz) +{ + int ret = wolfSSL_use_AltPrivateKey_Id(ssl, id, sz, devId); + if (ret == 1) { + ssl->buffers.altKeySz = (word32)keySz; + } + + return ret; +} + +int wolfSSL_use_AltPrivateKey_Label(WOLFSSL* ssl, const char* label, int devId) +{ + int ret = 1; + word32 sz; + + if ((ssl == NULL) || (label == NULL)) { + ret = 0; + } + + if (ret == 1) { + sz = (word32)XSTRLEN(label) + 1; + if (ssl->buffers.weOwnAltKey) { + FreeDer(&ssl->buffers.altKey); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.altKeyMask); + #endif + } + if (AllocDer(&ssl->buffers.altKey, (word32)sz, ALT_PRIVATEKEY_TYPE, + ssl->heap) == 0) { + ret = 0; + } + } + if (ret == 1) { + XMEMCPY(ssl->buffers.altKey->buffer, label, sz); + ssl->buffers.weOwnAltKey = 1; + ssl->buffers.altKeyLabel = 1; + if (devId != INVALID_DEVID) { + ssl->buffers.altKeyDevId = devId; + } + else { + ssl->buffers.altKeyDevId = ssl->devId; + } + } + + return ret; +} +#endif /* WOLFSSL_DUAL_ALG_CERTS */ +#endif /* WOLF_PRIVATE_KEY_ID */ + +/* Load a certificate chain in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] in Buffer holding DER encoded certificate chain. + * @param [in] sz Size of data in bytes. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ssl is NULL. + */ +int wolfSSL_use_certificate_chain_buffer_format(WOLFSSL* ssl, + const unsigned char* in, long sz, int format) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format"); + + /* Validate parameters. */ + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ret = ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 1, + GET_VERIFY_SETTING_SSL(ssl)); + } + + return ret; +} + +/* Load a PEM encoded certificate chain in a buffer into SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] in Buffer holding DER encoded certificate chain. + * @param [in] sz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return Negative on error. + */ +int wolfSSL_use_certificate_chain_buffer(WOLFSSL* ssl, const unsigned char* in, + long sz) +{ + return wolfSSL_use_certificate_chain_buffer_format(ssl, in, sz, + WOLFSSL_FILETYPE_PEM); +} + +#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ + defined(WOLFSSL_HAPROXY) +/* Add certificate to chain. + * + * @param [in, out] chain Buffer holding encoded certificate for TLS. + * @param [in] weOwn Indicates we need to free chain if repleced. + * @param [in] cert Buffer holding DER encoded certificate. + * @param [in] certSz Size of DER encoded certificate in bytes. + * @param [in] heap Dynamic memory allocation hint. + * @return 1 on success. + * @return 0 on failure. + */ +static int wolfssl_add_to_chain(DerBuffer** chain, int weOwn, const byte* cert, + word32 certSz, void* heap) +{ + int res = 1; + int ret; + DerBuffer* oldChain = *chain; + DerBuffer* newChain = NULL; + word32 len = 0; + + if (oldChain != NULL) { + /* Get length of previous chain. */ + len = oldChain->length; + } + /* Allocate DER buffer bug enough to hold old and new certificates. */ + ret = AllocDer(&newChain, len + CERT_HEADER_SZ + certSz, CERT_TYPE, heap); + if (ret != 0) { + WOLFSSL_MSG("AllocDer error"); + res = 0; + } + + if (res == 1) { + if (oldChain != NULL) { + /* Place old chain in new buffer. */ + XMEMCPY(newChain->buffer, oldChain->buffer, len); + } + /* Append length and DER encoded certificate. */ + c32to24(certSz, newChain->buffer + len); + XMEMCPY(newChain->buffer + len + CERT_HEADER_SZ, cert, certSz); + + /* Dispose of old chain if we own it. */ + if (weOwn) { + FreeDer(chain); + } + /* Replace chain. */ + *chain = newChain; + } + + return res; +} +#endif + +#ifdef OPENSSL_EXTRA + +/* Add a certificate to end of chain sent in TLS handshake. + * + * @param [in, out] ctx SSL context. + * @param [in] der Buffer holding DER encoded certificate. + * @param [in] derSz Size of data in buffer. + * @return 1 on success. + * @return 0 on failure. + */ +static int wolfssl_ctx_add_to_chain(WOLFSSL_CTX* ctx, const byte* der, + int derSz) +{ + int res = 1; + int ret; + DerBuffer* derBuffer = NULL; + + /* Create a DER buffer from DER encoding. */ + ret = AllocCopyDer(&derBuffer, der, (word32)derSz, CERT_TYPE, ctx->heap); + if (ret != 0) { + WOLFSSL_MSG("Memory Error"); + res = 0; + } + if (res == 1) { + /* Add a user CA certificate to the certificate manager. */ + res = AddCA(ctx->cm, &derBuffer, WOLFSSL_USER_CA, + GET_VERIFY_SETTING_CTX(ctx)); + if (res != 1) { + res = 0; + } + } + + if (res == 1) { + /* Add chain to DER buffer. */ + res = wolfssl_add_to_chain(&ctx->certChain, 1, der, (word32)derSz, ctx->heap); + #ifdef WOLFSSL_TLS13 + /* Update count of certificates. */ + ctx->certChainCnt++; + #endif + } + + return res; +} + +/* Add a certificate to chain sent in TLS handshake. + * + * @param [in, out] ctx SSL context. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) +{ + int ret = 1; + int derSz = 0; + const byte* der = NULL; + + WOLFSSL_ENTER("wolfSSL_CTX_add_extra_chain_cert"); + + /* Validate parameters. */ + if ((ctx == NULL) || (x509 == NULL)) { + WOLFSSL_MSG("Bad Argument"); + ret = 0; + } + + if (ret == 1) { + /* Get the DER encoding of the certificate from the X509 object. */ + der = wolfSSL_X509_get_der(x509, &derSz); + /* Validate buffer. */ + if ((der == NULL) || (derSz <= 0)) { + WOLFSSL_MSG("Error getting X509 DER"); + ret = 0; + } + } + + if ((ret == 1) && (ctx->certificate == NULL)) { + WOLFSSL_ENTER("wolfSSL_use_certificate_chain_buffer_format"); + + /* Process buffer makes first certificate the leaf. */ + ret = ProcessBuffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, + NULL, NULL, 1, GET_VERIFY_SETTING_CTX(ctx)); + if (ret != 1) { + ret = 0; + } + } + else if (ret == 1) { + /* Add certificate to existing chain. */ + ret = wolfssl_ctx_add_to_chain(ctx, der, derSz); + } + + if (ret == 1) { + /* On success WOLFSSL_X509 memory is responsibility of SSL context. */ + wolfSSL_X509_free(x509); + } + + WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret); + return ret; +} + +#endif /* OPENSSL_EXTRA */ + +#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \ + defined(WOLFSSL_HAPROXY) +/* Load a certificate into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_certificate(WOLFSSL_CTX *ctx, WOLFSSL_X509 *x) +{ + int res = 1; + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate"); + + /* Validate parameters. */ + if ((ctx == NULL) || (x == NULL) || (x->derCert == NULL)) { + WOLFSSL_MSG("Bad parameter"); + res = 0; + } + + if (res == 1) { + /* Replace certificate buffer with one holding the new certificate. */ + FreeDer(&ctx->certificate); + ret = AllocCopyDer(&ctx->certificate, x->derCert->buffer, + x->derCert->length, CERT_TYPE, ctx->heap); + if (ret != 0) { + res = 0; + } + } + +#ifdef KEEP_OUR_CERT + if (res == 1) { + /* Dispose of our certificate if it is ours. */ + if ((ctx->ourCert != NULL) && ctx->ownOurCert) { + wolfSSL_X509_free(ctx->ourCert); + } + #ifndef WOLFSSL_X509_STORE_CERTS + /* Keep a reference to the new certificate. */ + ctx->ourCert = x; + if (wolfSSL_X509_up_ref(x) != 1) { + res = 0; + } + #else + /* Keep a copy of the new certificate. */ + ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, x->derCert->buffer, + x->derCert->length, ctx->heap); + if (ctx->ourCert == NULL) { + res = 0; + } + #endif + /* Now own our certificate. */ + ctx->ownOurCert = 1; + } +#endif + + if (res == 1) { + /* Set have options based on public key OID. */ + wolfssl_set_have_from_key_oid(ctx, NULL, x->pubKeyOID); + } + + return res; +} + +/* Add the certificate to the chain in the SSL context and own the X509 object. + * + * @param [in, out] ctx SSL context object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_CTX_add0_chain_cert"); + + /* Add certificate to chain and copy or up reference it. */ + ret = wolfSSL_CTX_add1_chain_cert(ctx, x509); + if (ret == 1) { + /* Down reference or free original now as we own certificate. */ + wolfSSL_X509_free(x509); + } + + return ret; +} + +/* Add the certificate to the chain in the SSL context. + * + * X509 object copied or up referenced. + * + * @param [in, out] ctx SSL context object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_CTX_add1_chain_cert"); + + /* Validate parameters. */ + if ((ctx == NULL) || (x509 == NULL) || (x509->derCert == NULL)) { + ret = 0; + } + + /* Check if we already have set a certificate. */ + if ((ret == 1) && (ctx->certificate == NULL)) { + /* Use the certificate. */ + ret = wolfSSL_CTX_use_certificate(ctx, x509); + } + /* Increate reference count as we will store it. */ + else if ((ret == 1) && ((ret = wolfSSL_X509_up_ref(x509)) == 1)) { + /* Load the DER encoding. */ + ret = wolfSSL_CTX_load_verify_buffer(ctx, x509->derCert->buffer, + x509->derCert->length, WOLFSSL_FILETYPE_ASN1); + if (ret == 1) { + /* Add DER encoding to chain. */ + ret = wolfssl_add_to_chain(&ctx->certChain, 1, + x509->derCert->buffer, x509->derCert->length, ctx->heap); + } + /* Store cert in stack to free it later. */ + if ((ret == 1) && (ctx->x509Chain == NULL)) { + /* Create a stack for certificates. */ + ctx->x509Chain = wolfSSL_sk_X509_new_null(); + if (ctx->x509Chain == NULL) { + WOLFSSL_MSG("wolfSSL_sk_X509_new_null error"); + ret = 0; + } + } + if (ret == 1) { + /* Push the X509 object onto stack. */ + ret = wolfSSL_sk_X509_push(ctx->x509Chain, x509); + } + + if (ret != 1) { + /* Decrease reference count on error as we didn't store it. */ + wolfSSL_X509_free(x509); + } + } + + return WS_RC(ret); +} + +#ifdef KEEP_OUR_CERT +/* Add the certificate to the chain in the SSL and own the X509 object. + * + * @param [in, out] ssl SSL object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_add0_chain_cert"); + + /* Validate parameters. */ + if ((ssl == NULL) || (ssl->ctx == NULL) || (x509 == NULL) || + (x509->derCert == NULL)) { + ret = 0; + } + + /* Check if we already have set a certificate. */ + if ((ret == 1) && (ssl->buffers.certificate == NULL)) { + /* Use the certificate. */ + ret = wolfSSL_use_certificate(ssl, x509); + if (ret == 1) { + /* Dispose of old certificate if we own it. */ + if (ssl->buffers.weOwnCert) { + wolfSSL_X509_free(ssl->ourCert); + } + /* Store cert to free it later. */ + ssl->ourCert = x509; + ssl->buffers.weOwnCert = 1; + } + } + else if (ret == 1) { + /* Add DER encoding to chain. */ + ret = wolfssl_add_to_chain(&ssl->buffers.certChain, + ssl->buffers.weOwnCertChain, x509->derCert->buffer, + x509->derCert->length, ssl->heap); + if (ret == 1) { + /* We now own cert chain. */ + ssl->buffers.weOwnCertChain = 1; + /* Create a stack to put certificate into. */ + if (ssl->ourCertChain == NULL) { + ssl->ourCertChain = wolfSSL_sk_X509_new_null(); + if (ssl->ourCertChain == NULL) { + WOLFSSL_MSG("wolfSSL_sk_X509_new_null error"); + ret = 0; + } + } + } + if (ret == 1) { + /* Push X509 object onto stack to be freed. */ + ret = wolfSSL_sk_X509_push(ssl->ourCertChain, x509); + if (ret != 1) { + /* Free it now on error. */ + wolfSSL_X509_free(x509); + } + } + } + return WS_RC(ret); +} + +/* Add the certificate to the chain in the SSL. + * + * X509 object is up referenced. + * + * @param [in, out] ssl SSL object. + * @param [in] x509 X509 certificate object. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_add1_chain_cert"); + + /* Validate parameters. */ + if ((ssl == NULL) || (ssl->ctx == NULL) || (x509 == NULL) || + (x509->derCert == NULL)) { + ret = 0; + } + + /* Increase reference count on X509 object before adding. */ + if ((ret == 1) && ((ret == wolfSSL_X509_up_ref(x509)) == 1)) { + /* Add this to the chain. */ + if ((ret = wolfSSL_add0_chain_cert(ssl, x509)) != 1) { + /* Decrease reference count on error as not stored. */ + wolfSSL_X509_free(x509); + } + } + + return ret; +} +#endif /* KEEP_OUR_CERT */ +#endif /* OPENSSL_EXTRA, HAVE_LIGHTY, WOLFSSL_MYSQL_COMPATIBLE, HAVE_STUNNEL, + WOLFSSL_NGINX, HAVE_POCO_LIB, WOLFSSL_HAPROXY */ + +#ifdef OPENSSL_EXTRA + +/* Load a private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] pkey EVP private key. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_PrivateKey(WOLFSSL_CTX *ctx, WOLFSSL_EVP_PKEY *pkey) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey"); + + /* Validate parameters. */ + if ((ctx == NULL) || (pkey == NULL) || (pkey->pkey.ptr == NULL)) { + ret = 0; + } + + if (ret == 1) { + switch (pkey->type) { + #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) + case EVP_PKEY_RSA: + WOLFSSL_MSG("populating RSA key"); + ret = PopulateRSAEvpPkeyDer(pkey); + break; + #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */ + #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \ + defined(WOLFSSL_CERT_GEN)) && !defined(NO_DSA) + case EVP_PKEY_DSA: + break; + #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) && + * !NO_DSA */ + #ifdef HAVE_ECC + case EVP_PKEY_EC: + WOLFSSL_MSG("populating ECC key"); + ret = ECC_populate_EVP_PKEY(pkey, pkey->ecc); + break; + #endif + default: + ret = 0; + } + } + + if (ret == 1) { + /* ptr for WOLFSSL_EVP_PKEY struct is expected to be DER format */ + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, + (const unsigned char*)pkey->pkey.ptr, pkey->pkey_sz, + SSL_FILETYPE_ASN1); + } + + return ret; +} + +#endif /* OPENSSL_EXTRA */ + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) +/* Load a DER encoded certificate in a buffer into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] der Buffer holding DER encoded certificate. + * @param [in] derSz Size of data in bytes. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_certificate_ASN1(WOLFSSL_CTX *ctx, int derSz, + const unsigned char *der) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_ASN1"); + + /* Validate parameters. */ + if ((ctx == NULL) || (der == NULL)) { + ret = 0; + } + /* Load DER encoded cerificate into SSL context. */ + if ((ret == 1) && (wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz, + WOLFSSL_FILETYPE_ASN1) != 1)) { + ret = 0; + } + + return ret; +} + +#if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) +/* Load an RSA private key into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] rsa RSA private key. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ctx or rsa is NULL. + * @return MEMORY_E when dynamic memory allocation fails. + */ +int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) +{ + int ret = 1; + int derSize; + unsigned char* der = NULL; + unsigned char* p; + + WOLFSSL_ENTER("wolfSSL_CTX_use_RSAPrivateKey"); + + /* Validate parameters. */ + if ((ctx == NULL) || (rsa == NULL)) { + WOLFSSL_MSG("one or more inputs were NULL"); + ret = BAD_FUNC_ARG; + } + + /* Get DER encoding size. */ + if ((ret == 1) && ((derSize = wolfSSL_i2d_RSAPrivateKey(rsa, NULL)) <= 0)) { + ret = 0; + } + + if (ret == 1) { + /* Allocate memory to hold DER encoding.. */ + der = (unsigned char*)XMALLOC(derSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (der == NULL) { + WOLFSSL_MSG("Malloc failure"); + ret = MEMORY_E; + } + } + + if (ret == 1) { + /* Pointer passed in is modified.. */ + p = der; + /* Encode the RSA key as DER into buffer and get size. */ + if ((derSize = wolfSSL_i2d_RSAPrivateKey(rsa, &p)) <= 0) { + WOLFSSL_MSG("wolfSSL_i2d_RSAPrivateKey() failure"); + ret = 0; + } + } + + if (ret == 1) { + /* Load DER encoded cerificate into SSL context. */ + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, derSize, + SSL_FILETYPE_ASN1); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_CTX_USE_PrivateKey_buffer() failure"); + ret = 0; + } + } + + /* Dispos of dynamically allocated data. */ + XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return ret; +} +#endif /* WOLFSSL_KEY_GEN && !NO_RSA */ + +#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */ + +#endif /* !NO_CERTS */ + +#ifdef OPENSSL_EXTRA + +/* Use the default paths to look for CA certificate. + * + * This is an OpenSSL compatibility layer function, but it doesn't mirror + * the exact functionality of its OpenSSL counterpart. We don't support the + * notion of an "OpenSSL directory". This function will attempt to load the + * environment variables SSL_CERT_DIR and SSL_CERT_FILE, if either are + * found, they will be loaded. Otherwise, it will act as a wrapper around + * our native wolfSSL_CTX_load_system_CA_certs function. This function does + * conform to OpenSSL's return value conventions. + * + * @param [in] ctx SSL context object. + * @return 1 on success. + * @return 0 on failure. + * @return WOLFSSL_FATAL_ERROR when using a filesystem is not supported. + */ +int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) +{ + int ret; +#ifdef XGETENV + char* certDir; + char* certFile; + word32 flags; +#elif !defined(WOLFSSL_SYS_CA_CERTS) + (void)ctx; +#endif + + WOLFSSL_ENTER("wolfSSL_CTX_set_default_verify_paths"); + +#ifdef XGETENV + certDir = XGETENV("SSL_CERT_DIR"); + certFile = XGETENV("SSL_CERT_FILE"); + flags = WOLFSSL_LOAD_FLAG_PEM_CA_ONLY; + + if ((certDir != NULL) || (certFile != NULL)) { + if (certDir != NULL) { + /* We want to keep trying to load more CA certs even if one cert in + * the directory is bad and can't be used (e.g. if one is + * expired), so we use WOLFSSL_LOAD_FLAG_IGNORE_ERR. + */ + flags |= WOLFSSL_LOAD_FLAG_IGNORE_ERR; + } + + /* Load CA certificates from environment variable locations. */ + ret = wolfSSL_CTX_load_verify_locations_ex(ctx, certFile, certDir, + flags); + if (ret != 1) { + WOLFSSL_MSG_EX("Failed to load CA certs from SSL_CERT_FILE: %s" + " SSL_CERT_DIR: %s. Error: %d", certFile, + certDir, ret); + ret = 0; + } + } + else +#endif + + { + #ifdef NO_FILESYSTEM + WOLFSSL_MSG("wolfSSL_CTX_set_default_verify_paths not supported" + " with NO_FILESYSTEM enabled"); + ret = WOLFSSL_FATAL_ERROR; + #elif defined(WOLFSSL_SYS_CA_CERTS) + /* Load the system CA certificates. */ + ret = wolfSSL_CTX_load_system_CA_certs(ctx); + if (ret == WOLFSSL_BAD_PATH) { + /* OpenSSL doesn't treat the lack of a system CA cert directory as a + * failure. We do the same here. + */ + ret = 1; + } + #else + /* OpenSSL's implementation of this API does not require loading the + system CA cert directory. Allow skipping this without erroring out. */ + ret = 1; + #endif + } + + WOLFSSL_LEAVE("wolfSSL_CTX_set_default_verify_paths", ret); + + return ret; +} + +#endif /* OPENSSL_EXTRA */ + +#ifndef NO_DH + +/* Set the temporary DH parameters against the SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] p Buffer holding prime. + * @param [in] pSz Length of prime in bytes. + * @param [in] g Buffer holding generator. + * @param [in] gSz Length of generator in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + */ +static int wolfssl_set_tmp_dh(WOLFSSL* ssl, unsigned char* p, int pSz, + unsigned char* g, int gSz) +{ + int ret = 1; + + /* Check the size of the prime meets the requirements of the SSL. */ + if (((word16)pSz < ssl->options.minDhKeySz) || + ((word16)pSz > ssl->options.maxDhKeySz)) { + ret = DH_KEY_SIZE_E; + } + /* Only able to set DH parameters on server. */ + if ((ret == 1) && (ssl->options.side == WOLFSSL_CLIENT_END)) { + ret = SIDE_ERROR; + } + + if (ret == 1) { + #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ + !defined(HAVE_SELFTEST) + /* New DH parameters not tested for validity. */ + ssl->options.dhKeyTested = 0; + /* New DH parameters must be tested for validity before use. */ + ssl->options.dhDoKeyTest = 1; + #endif + + /* Dispose of old DH parameters if we own it. */ + if (ssl->buffers.weOwnDH) { + XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + } + + /* Assign the buffers and lengths to SSL. */ + ssl->buffers.serverDH_P.buffer = p; + ssl->buffers.serverDH_G.buffer = g; + ssl->buffers.serverDH_P.length = (unsigned int)pSz; + ssl->buffers.serverDH_G.length = (unsigned int)gSz; + /* We own the buffers. */ + ssl->buffers.weOwnDH = 1; + /* We have a DH parameters to use. */ + ssl->options.haveDH = 1; + } + + /* Allocate space for cipher suites. */ + if ((ret == 1) && (AllocateSuites(ssl) != 0)) { + ssl->buffers.serverDH_P.buffer = NULL; + ssl->buffers.serverDH_G.buffer = NULL; + ret = 0; + } + if (ret == 1) { + /* Reset the cipher suites based on having a DH parameters now. */ + InitSuites(ssl->suites, ssl->version, SSL_KEY_SZ(ssl), + WOLFSSL_HAVE_RSA, SSL_HAVE_PSK(ssl), ssl->options.haveDH, + ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, + ssl->options.haveStaticECC, ssl->options.haveFalconSig, + ssl->options.haveDilithiumSig, ssl->options.useAnon, TRUE, + ssl->options.side); + } + + return ret; +} + +/* Set the temporary DH parameters against the SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] p Buffer holding prime. + * @param [in] pSz Length of prime in bytes. + * @param [in] g Buffer holding generator. + * @param [in] gSz Length of generator in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + * @return MEMORY_E when dynamic memory allocation fails. + */ +int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz, + const unsigned char* g, int gSz) +{ + int ret = 1; + byte* pAlloc = NULL; + byte* gAlloc = NULL; + + WOLFSSL_ENTER("wolfSSL_SetTmpDH"); + + /* Validate parameters. */ + if ((ssl == NULL) || (p == NULL) || (g == NULL)) { + ret = 0; + } + + if (ret == 1) { + /* Allocate buffers for p and g to be assigned into SSL. */ + pAlloc = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + gAlloc = (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if ((pAlloc == NULL) || (gAlloc == NULL)) { + ret = MEMORY_E; + } + } + if (ret == 1) { + /* Copy p and g into allocated buffers. */ + XMEMCPY(pAlloc, p, pSz); + XMEMCPY(gAlloc, g, gSz); + /* Set the buffers into SSL. */ + ret = wolfssl_set_tmp_dh(ssl, pAlloc, pSz, gAlloc, gSz); + } + + if (ret != 1 && ssl != NULL) { + /* Free the allocated buffers if not assigned into SSL. */ + XFREE(pAlloc, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(gAlloc, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + + WOLFSSL_LEAVE("wolfSSL_SetTmpDH", ret); + return ret; +} + +#if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ + !defined(HAVE_SELFTEST) +/* Check the DH parameters is valid. + * + * @param [in] p Buffer holding prime. + * @param [in] pSz Length of prime in bytes. + * @param [in] g Buffer holding generator. + * @param [in] gSz Length of generator in bytes. + * @return 1 on success. + * @return DH_CHECK_PUB_E when p is not a prime. + * @return BAD_FUNC_ARG when p or g is NULL, or pSz or gSz is 0. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int wolfssl_check_dh_key(unsigned char* p, int pSz, unsigned char* g, + int gSz) +{ + WC_RNG rng; + int ret = 0; +#ifndef WOLFSSL_SMALL_STACK + DhKey checkKey[1]; +#else + DhKey *checkKey; +#endif + +#ifdef WOLFSSL_SMALL_STACK + checkKey = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH); + if (checkKey == NULL) { + ret = MEMORY_E; + } +#endif + /* Initialize a new random number generator. */ + if ((ret == 0) && ((ret = wc_InitRng(&rng)) == 0)) { + /* Initialize a DH object. */ + if ((ret = wc_InitDhKey(checkKey)) == 0) { + /* Check DH parameters. */ + ret = wc_DhSetCheckKey(checkKey, p, (word32)pSz, g, gSz, NULL, 0, 0, &rng); + /* Dispose of DH object. */ + wc_FreeDhKey(checkKey); + } + /* Dispose of random number generator. */ + wc_FreeRng(&rng); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of dynamically allocated data. */ + XFREE(checkKey, NULL, DYNAMIC_TYPE_DH); +#endif + /* Convert wolfCrypt return code to 1 on success and ret on failure. */ + return WC_TO_WS_RC(ret); +} +#endif + +/* Set the temporary DH parameters against the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] p Buffer holding prime. + * @param [in] pSz Length of prime in bytes. + * @param [in] g Buffer holding generator. + * @param [in] gSz Length of generator in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + * @return BAD_FUNC_ARG when ctx, p or g is NULL. + * @return DH_CHECK_PUB_E when p is not a prime. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int wolfssl_ctx_set_tmp_dh(WOLFSSL_CTX* ctx, unsigned char* p, int pSz, + unsigned char* g, int gSz) +{ + int ret = 1; + + WOLFSSL_ENTER("wolfSSL_CTX_SetTmpDH"); + + /* Check the size of the prime meets the requirements of the SSL context. */ + if (((word16)pSz < ctx->minDhKeySz) || ((word16)pSz > ctx->maxDhKeySz)) { + ret = DH_KEY_SIZE_E; + } + +#if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \ + !defined(HAVE_SELFTEST) + if (ret == 1) { + /* Test DH parameters for validity. */ + ret = wolfssl_check_dh_key(p, pSz, g, gSz); + /* Record as whether tested based on result of validity test. */ + ctx->dhKeyTested = (ret == 1); + } +#endif + + if (ret == 1) { + /* Dispose of old DH parameters. */ + XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + /* Assign the buffers and lengths to SSL context. */ + ctx->serverDH_P.buffer = p; + ctx->serverDH_G.buffer = g; + ctx->serverDH_P.length = (unsigned int)pSz; + ctx->serverDH_G.length = (unsigned int)gSz; + /* We have a DH parameters to use. */ + ctx->haveDH = 1; + } + + WOLFSSL_LEAVE("wolfSSL_CTX_SetTmpDH", 0); + return ret; +} + +/* Set the temporary DH parameters against the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] p Buffer holding prime. + * @param [in] pSz Length of prime in bytes. + * @param [in] g Buffer holding generator. + * @param [in] gSz Length of generator in bytes. + * @return 1 on success. + * @return 0 on failure. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + * @return BAD_FUNC_ARG when ctx, p or g is NULL. + * @return DH_CHECK_PUB_E when p is not a prime. + */ +int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz, + const unsigned char* g, int gSz) +{ + int ret = 1; + byte* pAlloc = NULL; + byte* gAlloc = NULL; + + /* Validate parameters. */ + if ((ctx == NULL) || (p == NULL) || (g == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 1) { + /* Allocate buffers for p and g to be assigned into SSL context. */ + pAlloc = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + gAlloc = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if ((pAlloc == NULL) || (gAlloc == NULL)) { + XFREE(pAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + pAlloc = NULL; + XFREE(gAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + gAlloc = NULL; + ret = MEMORY_E; + } + } + + if (ret == 1) { + /* Copy p and g into allocated buffers. */ + XMEMCPY(pAlloc, p, pSz); + XMEMCPY(gAlloc, g, gSz); + /* Set the buffers into SSL context. */ + ret = wolfssl_ctx_set_tmp_dh(ctx, pAlloc, pSz, gAlloc, gSz); + } + + if (ret != 1) { + /* Free the allocated buffers if not assigned into SSL context. */ + if (pAlloc) + XFREE(pAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if (gAlloc) + XFREE(gAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + return ret; +} + +#ifdef OPENSSL_EXTRA +/* Set the temporary DH parameters against the SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] dh DH object. + * @return 1 on success. + * @return 0 on failure. + * @return WOLFSSL_FATAL_ERROR on failure. + * @return BAD_FUNC_ARG when ssl or dh is NULL. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + */ +long wolfSSL_set_tmp_dh(WOLFSSL *ssl, WOLFSSL_DH *dh) +{ + int ret = 1; + byte* p = NULL; + byte* g = NULL; + int pSz = 0; + int gSz = 0; + + WOLFSSL_ENTER("wolfSSL_set_tmp_dh"); + + /* Validate parameters. */ + if ((ssl == NULL) || (dh == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 1) { + /* Get needed size for p and g. */ + pSz = wolfSSL_BN_bn2bin(dh->p, NULL); + gSz = wolfSSL_BN_bn2bin(dh->g, NULL); + /* Validate p and g size. */ + if ((pSz <= 0) || (gSz <= 0)) { + ret = WOLFSSL_FATAL_ERROR; + } + } + + if (ret == 1) { + /* Allocate buffers for p and g to be assigned into SSL. */ + p = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + g = (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if ((p == NULL) || (g == NULL)) { + ret = MEMORY_E; + } + } + if (ret == 1) { + /* Encode p and g and get sizes. */ + pSz = wolfSSL_BN_bn2bin(dh->p, p); + gSz = wolfSSL_BN_bn2bin(dh->g, g); + /* Check encoding worked. */ + if ((pSz <= 0) || (gSz <= 0)) { + ret = WOLFSSL_FATAL_ERROR; + } + } + if (ret == 1) { + /* Set the buffers into SSL. */ + ret = wolfssl_set_tmp_dh(ssl, p, pSz, g, gSz); + } + + if (ret != 1 && ssl != NULL) { + /* Free the allocated buffers if not assigned into SSL. */ + XFREE(p, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(g, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + return ret; +} + +/* Set the temporary DH parameters object against the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] dh DH object. + * @return 1 on success. + * @return 0 on failure. + * @return DH_KEY_SIZE_E when the prime is too short or long. + * @return SIDE_ERROR when the SSL is for a client. + * @return BAD_FUNC_ARG when ctx, p or g is NULL. + * @return DH_CHECK_PUB_E when p is not a prime. + */ +long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh) +{ + int ret = 1; + int pSz = 0; + int gSz = 0; + byte* p = NULL; + byte* g = NULL; + + WOLFSSL_ENTER("wolfSSL_CTX_set_tmp_dh"); + + /* Validate parameters. */ + if ((ctx == NULL) || (dh == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 1) { + /* Get needed size for p and g. */ + pSz = wolfSSL_BN_bn2bin(dh->p, NULL); + gSz = wolfSSL_BN_bn2bin(dh->g, NULL); + /* Validate p and g size. */ + if ((pSz <= 0) || (gSz <= 0)) { + ret = WOLFSSL_FATAL_ERROR; + } + } + + if (ret == 1) { + /* Allocate buffers for p and g to be assigned into SSL. */ + p = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + g = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if ((p == NULL) || (g == NULL)) { + ret = MEMORY_E; + } + } + + if (ret == 1) { + /* Encode p and g and get sizes. */ + pSz = wolfSSL_BN_bn2bin(dh->p, p); + gSz = wolfSSL_BN_bn2bin(dh->g, g); + /* Check encoding worked. */ + if ((pSz < 0) && (gSz < 0)) { + ret = WOLFSSL_FATAL_ERROR; + } + } + if (ret == 1) { + /* Set the buffers into SSL context. */ + ret = wolfssl_ctx_set_tmp_dh(ctx, p, pSz, g, gSz); + } + + if (ret != 1 && ctx != NULL) { + /* Free the allocated buffers if not assigned into SSL. */ + XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(g, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + return ret; +} + +#endif /* OPENSSL_EXTRA */ + +#ifndef NO_CERTS + +/* Set the temporary DH parameters against the SSL context or SSL. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] buf Buffer holding encoded DH parameters. + * @param [in] sz Size of encoded DH parameters. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return 0 on failure. + * @return BAD_FUNC_ARG when ctx and ssl NULL or buf is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +static int ws_ctx_ssl_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const unsigned char* buf, long sz, int format) +{ + DerBuffer* der = NULL; + int res = 1; + int ret; + /* p and g size to allocate set to maximum valid size. */ + word32 pSz = MAX_DH_SIZE; + word32 gSz = MAX_DH_SIZE; + byte* p = NULL; + byte* g = NULL; + void* heap = WOLFSSL_HEAP(ctx, ssl); + + /* Validate parameters. */ + if (((ctx == NULL) && (ssl == NULL)) || (buf == NULL)) { + res = BAD_FUNC_ARG; + } + /* Check format is supported. */ + if ((res == 1) && (format != WOLFSSL_FILETYPE_ASN1)) { + if (format != WOLFSSL_FILETYPE_PEM) { + res = WOLFSSL_BAD_FILETYPE; + } + #ifndef WOLFSSL_PEM_TO_DER + else { + res = NOT_COMPILED_IN; + } + #endif + } + + /* PemToDer allocates its own DER buffer. */ + if ((res == 1) && (format != WOLFSSL_FILETYPE_PEM)) { + /* Create an empty DER buffer. */ + ret = AllocDer(&der, 0, DH_PARAM_TYPE, heap); + if (ret == 0) { + /* Assign encoded DH parameters to DER buffer. */ + der->buffer = (byte*)buf; + der->length = (word32)sz; + } + else { + res = ret; + } + } + + if (res == 1) { + /* Allocate enough memory to p and g to support valid use cases. */ + p = (byte*)XMALLOC(pSz, heap, DYNAMIC_TYPE_PUBLIC_KEY); + g = (byte*)XMALLOC(gSz, heap, DYNAMIC_TYPE_PUBLIC_KEY); + if ((p == NULL) || (g == NULL)) { + res = MEMORY_E; + } + } + +#ifdef WOLFSSL_PEM_TO_DER + if ((res == 1) && (format == WOLFSSL_FILETYPE_PEM)) { + /* Convert from PEM to DER. */ + /* Try converting DH parameters from PEM to DER. */ + ret = PemToDer(buf, sz, DH_PARAM_TYPE, &der, heap, NULL, NULL); + if (ret < 0) { + /* Otherwise, try converting X9.43 format DH parameters. */ + ret = PemToDer(buf, sz, X942_PARAM_TYPE, &der, heap, NULL, NULL); + } + #if defined(WOLFSSL_WPAS) && !defined(NO_DSA) + if (ret < 0) { + /* Otherwise, try converting DSA parameters. */ + ret = PemToDer(buf, sz, DSA_PARAM_TYPE, &der, heap, NULL, NULL); + } + #endif /* WOLFSSL_WPAS && !NO_DSA */ + if (ret < 0) { + /* Return error from conversion. */ + res = ret; + } + } +#endif /* WOLFSSL_PEM_TO_DER */ + + if (res == 1) { + /* Get the p and g from the DER encoded parameters. */ + if (wc_DhParamsLoad(der->buffer, der->length, p, &pSz, g, &gSz) < 0) { + res = WOLFSSL_BAD_FILETYPE; + } + else if (ssl != NULL) { + /* Set p and g into SSL. */ + res = wolfssl_set_tmp_dh(ssl, p, (int)pSz, g, gSz); + } + else { + /* Set p and g into SSL context. */ + res = wolfssl_ctx_set_tmp_dh(ctx, p, (int)pSz, g, gSz); + } + } + + /* Dispose of the DER buffer. */ + FreeDer(&der); + if (res != 1) { + /* Free the allocated buffers if not assigned into SSL or context. */ + XFREE(p, heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(g, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + return res; +} + + +/* Set the temporary DH parameters against the SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] buf Buffer holding encoded DH parameters. + * @param [in] sz Size of encoded DH parameters. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return BAD_FUNC_ARG when ssl or buf is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +int wolfSSL_SetTmpDH_buffer(WOLFSSL* ssl, const unsigned char* buf, long sz, + int format) +{ + return ws_ctx_ssl_set_tmp_dh(NULL, ssl, buf, sz, format); +} + + +/* Set the temporary DH parameters against the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] buf Buffer holding encoded DH parameters. + * @param [in] sz Size of encoded DH parameters. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return BAD_FUNC_ARG when ctx or buf is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +int wolfSSL_CTX_SetTmpDH_buffer(WOLFSSL_CTX* ctx, const unsigned char* buf, + long sz, int format) +{ + return ws_ctx_ssl_set_tmp_dh(ctx, NULL, buf, sz, format); +} + +#ifndef NO_FILESYSTEM + +/* Set the temporary DH parameters file against the SSL context or SSL. + * + * @param [in, out] ctx SSL context object. + * @param [in, out] ssl SSL object. + * @param [in] fname Name of file to load. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return BAD_FUNC_ARG when ctx and ssl NULL or fname is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +static int ws_ctx_ssl_set_tmp_dh_file(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + const char* fname, int format) +{ + int res = 1; + int ret; +#ifndef WOLFSSL_SMALL_STACK + byte stackBuffer[FILE_BUFFER_SIZE]; +#endif + StaticBuffer dhFile; + long sz = 0; + void* heap = WOLFSSL_HEAP(ctx, ssl); + + /* Setup buffer to hold file contents. */ +#ifdef WOLFSSL_SMALL_STACK + static_buffer_init(&dhFile); +#else + static_buffer_init(&dhFile, stackBuffer, FILE_BUFFER_SIZE); +#endif + + /* Validate parameters. */ + if (((ctx == NULL) && (ssl == NULL)) || (fname == NULL)) { + res = BAD_FUNC_ARG; + } + + if (res == 1) { + /* Read file into static buffer. */ + ret = wolfssl_read_file_static(fname, &dhFile, heap, DYNAMIC_TYPE_FILE, + &sz); + if (ret != 0) { + res = ret; + } + } + if (res == 1) { + if (ssl != NULL) { + /* Set encoded DH parameters into SSL. */ + res = wolfSSL_SetTmpDH_buffer(ssl, dhFile.buffer, sz, format); + } + else { + /* Set encoded DH parameters into SSL context. */ + res = wolfSSL_CTX_SetTmpDH_buffer(ctx, dhFile.buffer, sz, format); + } + } + + /* Dispose of any dynamically allocated data. */ + static_buffer_free(&dhFile, heap, DYNAMIC_TYPE_FILE); + return res; +} + +/* Set the temporary DH parameters file against the SSL. + * + * @param [in, out] ssl SSL object. + * @param [in] fname Name of file to load. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return BAD_FUNC_ARG when ssl or fname is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +int wolfSSL_SetTmpDH_file(WOLFSSL* ssl, const char* fname, int format) +{ + return ws_ctx_ssl_set_tmp_dh_file(NULL, ssl, fname, format); +} + + +/* Set the temporary DH parameters file against the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] fname Name of file to load. + * @param [in] format Format of data: + * WOLFSSL_FILETYPE_PEM or WOLFSSL_FILETYPE_ASN1. + * @return 1 on success. + * @return BAD_FUNC_ARG when ctx or fname is NULL. + * @return NOT_COMPLED_IN when format is PEM but PEM is not supported. + * @return WOLFSSL_BAD_FILETYPE if format is not supported. + */ +int wolfSSL_CTX_SetTmpDH_file(WOLFSSL_CTX* ctx, const char* fname, int format) +{ + return ws_ctx_ssl_set_tmp_dh_file(ctx, NULL, fname, format); +} + +#endif /* NO_FILESYSTEM */ + +#endif /* NO_CERTS */ + +#endif /* !NO_DH */ + +#endif /* !WOLFSSL_SSL_LOAD_INCLUDED */ + diff --git a/src/src/ssl_misc.c b/src/src/ssl_misc.c index 9bc42dd..d52c2cd 100644 --- a/src/src/ssl_misc.c +++ b/src/src/ssl_misc.c @@ -24,6 +24,8 @@ #endif #include +#include +#include #if !defined(WOLFSSL_SSL_MISC_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -54,7 +56,7 @@ static int wolfssl_read_bio_file(WOLFSSL_BIO* bio, char** data) char* p; /* Allocate buffer to hold a chunk of data. */ - mem = (char*)XMALLOC(READ_BIO_FILE_CHUNK, bio->heap, DYNAMIC_TYPE_OPENSSL); + mem = (char*)XMALLOC(READ_BIO_FILE_CHUNK, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (mem == NULL) { WOLFSSL_ERROR_MSG("Memory allocation error"); ret = MEMORY_E; @@ -86,8 +88,8 @@ static int wolfssl_read_bio_file(WOLFSSL_BIO* bio, char** data) } else { /* No space left for more data to be read - add a chunk. */ - p = (char*)XREALLOC(mem, ret + READ_BIO_FILE_CHUNK, bio->heap, - DYNAMIC_TYPE_OPENSSL); + p = (char*)XREALLOC(mem, ret + READ_BIO_FILE_CHUNK, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (p == NULL) { sz = MEMORY_E; break; @@ -103,7 +105,7 @@ static int wolfssl_read_bio_file(WOLFSSL_BIO* bio, char** data) } if ((sz < 0) || (ret == 0)) { /* Dispose of memory on error or no data read. */ - XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL); + XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER); mem = NULL; /* Return error. */ ret = sz; @@ -129,14 +131,14 @@ static int wolfssl_read_bio_len(WOLFSSL_BIO* bio, int sz, char** data) char* mem; /* Allocate buffer to hold data. */ - mem = (char*)XMALLOC((size_t)sz, bio->heap, DYNAMIC_TYPE_OPENSSL); + mem = (char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (mem == NULL) { WOLFSSL_ERROR_MSG("Memory allocation error"); ret = MEMORY_E; } else if ((ret = wolfSSL_BIO_read(bio, mem, sz)) != sz) { /* Pending data not read. */ - XFREE(mem, bio->heap, DYNAMIC_TYPE_OPENSSL); + XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER); mem = NULL; ret = MEMORY_E; } @@ -206,9 +208,7 @@ static int wolfssl_read_bio(WOLFSSL_BIO* bio, char** data, int* dataSz, #endif /* OPENSSL_EXTRA && !WOLFCRYPT_ONLY */ #if (defined(OPENSSL_EXTRA) || defined(PERSIST_CERT_CACHE) || \ - (!defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \ - !defined(WOLFSSL_NO_CLIENT_AUTH)))) && !defined(WOLFCRYPT_ONLY) && \ - !defined(NO_FILESYSTEM) + !defined(NO_CERTS)) && !defined(WOLFCRYPT_ONLY) && !defined(NO_FILESYSTEM) /* Read all the data from a file. * * @param [in] fp File pointer to read with. @@ -299,5 +299,204 @@ static int wolfssl_read_file(XFILE fp, char** data, int* dataSz) } #endif /* (OPENSSL_EXTRA || PERSIST_CERT_CACHE) && !WOLFCRYPT_ONLY && * !NO_FILESYSTEM */ + +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_CERTS) + +#ifdef WOLFSSL_SMALL_STACK + +/* Buffer and size with no stack buffer. */ +typedef struct { + /* Dynamically allocated buffer. */ + byte* buffer; + /* Size of buffer in bytes. */ + word32 sz; +} StaticBuffer; + +/* Initialize static buffer. + * + * @param [in, out] sb Static buffer. + */ +static void static_buffer_init(StaticBuffer* sb) +{ + sb->buffer = NULL; + sb->sz = 0; +} + +/* Set the size of the buffer. + * + * Can only set size once. + * + * @param [in] sb Static buffer. + * @param [in] len Length required. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of dynamic memory. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int static_buffer_set_size(StaticBuffer* sb, word32 len, void* heap, + int type) +{ + int ret = 0; + + (void)heap; + (void)type; + + sb->buffer = (byte*)XMALLOC(len, heap, type); + if (sb->buffer == NULL) { + ret = MEMORY_E; + } + else { + sb->sz = len; + } + + return ret; +} + +/* Dispose of dynamically allocated buffer. + * + * @param [in] sb Static buffer. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of dynamic memory. + */ +static void static_buffer_free(StaticBuffer* sb, void* heap, int type) +{ + (void)heap; + (void)type; + XFREE(sb->buffer, heap, type); +} + +#else + +/* Buffer and size with stack buffer set and option to dynamically allocate. */ +typedef struct { + /* Stack or heap buffer. */ + byte* buffer; + /* Size of buffer in bytes. */ + word32 sz; + /* Indicates whether the buffer was dynamically allocated. */ + int dyn; +} StaticBuffer; + +/* Initialize static buffer. + * + * @param [in, out] sb Static buffer. + * @param [in] stackBuffer Buffer allocated on the stack. + * @param [in] len Length of stack buffer. + */ +static void static_buffer_init(StaticBuffer* sb, byte* stackBuffer, word32 len) +{ + sb->buffer = stackBuffer; + sb->sz = len; + sb->dyn = 0; +} + +/* Set the size of the buffer. + * + * Pre: Buffer on the stack set with its size. + * Can only set size once. + * + * @param [in] sb Static buffer. + * @param [in] len Length required. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of dynamic memory. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int static_buffer_set_size(StaticBuffer* sb, word32 len, void* heap, + int type) +{ + int ret = 0; + + (void)heap; + (void)type; + + if (len > sb->sz) { + byte* buff = (byte*)XMALLOC(len, heap, type); + if (buff == NULL) { + ret = MEMORY_E; + } + else { + sb->buffer = buff; + sb->sz = len; + sb->dyn = 1; + } + } + + return ret; +} + +/* Dispose of dynamically allocated buffer. + * + * @param [in] sb Static buffer. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of dynamic memory. + */ +static void static_buffer_free(StaticBuffer* sb, void* heap, int type) +{ + (void)heap; + (void)type; + + if (sb->dyn) { + XFREE(sb->buffer, heap, type); + } +} + +#endif /* WOLFSSL_SMALL_STACK */ + +#ifndef NO_FILESYSTEM + +/* Read all the data from a file into content. + * + * @param [in] fname File pointer to read with. + * @param [in, out] content Read data in an allocated buffer. + * @param [in] heap Dynamic memory allocation hint. + * @param [in] type Type of dynamic memory. + * @param [out] size Amount of data read in bytes. + * @return 0 on success. + * @return WOLFSSL_BAD_FILE when reading fails. + * @return MEMORY_E when memory allocation fails. + */ +static int wolfssl_read_file_static(const char* fname, StaticBuffer* content, + void* heap, int type, long* size) +{ + int ret = 0; + XFILE file = XBADFILE; + long sz = 0; + + /* Check filename is usable. */ + if (fname == NULL) { + ret = WOLFSSL_BAD_FILE; + } + /* Open file for reading. */ + if ((ret == 0) && ((file = XFOPEN(fname, "rb")) == XBADFILE)) { + ret = WOLFSSL_BAD_FILE; + } + if (ret == 0) { + /* Get length of file. */ + ret = wolfssl_file_len(file, &sz); + } + if (ret == 0) { + /* Set the buffer to be big enough to hold all data. */ + ret = static_buffer_set_size(content, (word32)sz, heap, type); + } + /* Read data from file. */ + if ((ret == 0) && ((size_t)XFREAD(content->buffer, 1, (size_t)sz, file) != + (size_t)sz)) { + ret = WOLFSSL_BAD_FILE; + } + + /* Close file if opened. */ + if (file != XBADFILE) { + XFCLOSE(file); + } + /* Return size read. */ + *size = sz; + return ret; +} + +#endif /* !NO_FILESYSTEM */ + +#endif /* !WOLFCRYPT_ONLY && !NO_CERTS */ + #endif /* !WOLFSSL_SSL_MISC_INCLUDED */ diff --git a/src/src/ssl_p7p12.c b/src/src/ssl_p7p12.c new file mode 100644 index 0000000..11b6c40 --- /dev/null +++ b/src/src/ssl_p7p12.c @@ -0,0 +1,2123 @@ +/* ssl_p7p12.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +#if defined(OPENSSL_EXTRA) && (defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) + #include +#endif +#if defined(OPENSSL_ALL) && defined(HAVE_PKCS7) + #include +#endif + +#if !defined(WOLFSSL_SSL_P7P12_INCLUDED) + #ifndef WOLFSSL_IGNORE_FILE_WARN + #warning ssl_p7p12.c does not need to be compiled separately from ssl.c + #endif +#else + +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_CERTS) + +/******************************************************************************* + * START OF PKCS7 APIs + ******************************************************************************/ +#ifdef HAVE_PKCS7 + +#ifdef OPENSSL_ALL +PKCS7* wolfSSL_PKCS7_new(void) +{ + WOLFSSL_PKCS7* pkcs7; + int ret = 0; + + pkcs7 = (WOLFSSL_PKCS7*)XMALLOC(sizeof(WOLFSSL_PKCS7), NULL, + DYNAMIC_TYPE_PKCS7); + if (pkcs7 != NULL) { + XMEMSET(pkcs7, 0, sizeof(WOLFSSL_PKCS7)); + ret = wc_PKCS7_Init(&pkcs7->pkcs7, NULL, INVALID_DEVID); + } + + if (ret != 0 && pkcs7 != NULL) { + XFREE(pkcs7, NULL, DYNAMIC_TYPE_PKCS7); + pkcs7 = NULL; + } + + return (PKCS7*)pkcs7; +} + +/****************************************************************************** +* wolfSSL_PKCS7_SIGNED_new - allocates PKCS7 and initialize it for a signed data +* +* RETURNS: +* returns pointer to the PKCS7 structure on success, otherwise returns NULL +*/ +PKCS7_SIGNED* wolfSSL_PKCS7_SIGNED_new(void) +{ + byte signedData[]= { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02}; + PKCS7* pkcs7 = NULL; + + if ((pkcs7 = wolfSSL_PKCS7_new()) == NULL) + return NULL; + pkcs7->contentOID = SIGNED_DATA; + if ((wc_PKCS7_SetContentType(pkcs7, signedData, sizeof(signedData))) < 0) { + if (pkcs7) { + wolfSSL_PKCS7_free(pkcs7); + return NULL; + } + } + return pkcs7; +} + +void wolfSSL_PKCS7_free(PKCS7* pkcs7) +{ + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + + if (p7 != NULL) { + if (p7->data != NULL) + XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); + wc_PKCS7_Free(&p7->pkcs7); + if (p7->certs) + wolfSSL_sk_pop_free(p7->certs, NULL); + XFREE(p7, NULL, DYNAMIC_TYPE_PKCS7); + } +} + +void wolfSSL_PKCS7_SIGNED_free(PKCS7_SIGNED* p7) +{ + wolfSSL_PKCS7_free(p7); + return; +} + +/** + * Convert DER/ASN.1 encoded signedData structure to internal PKCS7 + * structure. Note, does not support detached content. + * + * p7 - pointer to set to address of newly created PKCS7 structure on return + * in - pointer to pointer of DER/ASN.1 data + * len - length of input data, bytes + * + * Returns newly allocated and populated PKCS7 structure or NULL on error. + */ +PKCS7* wolfSSL_d2i_PKCS7(PKCS7** p7, const unsigned char** in, int len) +{ + return wolfSSL_d2i_PKCS7_ex(p7, in, len, NULL, 0); +} + +/* This internal function is only decoding and setting up the PKCS7 struct. It +* does not verify the PKCS7 signature. +* +* RETURNS: +* returns pointer to a PKCS7 structure on success, otherwise returns NULL +*/ +static PKCS7* wolfSSL_d2i_PKCS7_only(PKCS7** p7, const unsigned char** in, + int len, byte* content, word32 contentSz) +{ + WOLFSSL_PKCS7* pkcs7 = NULL; + + WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex"); + + if (in == NULL || *in == NULL || len < 0) + return NULL; + + if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL) + return NULL; + + pkcs7->len = len; + pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7); + if (pkcs7->data == NULL) { + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + return NULL; + } + XMEMCPY(pkcs7->data, *in, pkcs7->len); + + if (content != NULL) { + pkcs7->pkcs7.content = content; + pkcs7->pkcs7.contentSz = contentSz; + } + + if (p7 != NULL) + *p7 = (PKCS7*)pkcs7; + *in += pkcs7->len; + return (PKCS7*)pkcs7; +} + + +/***************************************************************************** +* wolfSSL_d2i_PKCS7_ex - Converts the given unsigned char buffer of size len +* into a PKCS7 object. Optionally, accepts a byte buffer of content which +* is stored as the PKCS7 object's content, to support detached signatures. +* @param content The content which is signed, in case the signature is +* detached. Ignored if NULL. +* @param contentSz The size of the passed in content. +* +* RETURNS: +* returns pointer to a PKCS7 structure on success, otherwise returns NULL +*/ +PKCS7* wolfSSL_d2i_PKCS7_ex(PKCS7** p7, const unsigned char** in, int len, + byte* content, word32 contentSz) +{ + WOLFSSL_PKCS7* pkcs7 = NULL; + + WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex"); + + if (in == NULL || *in == NULL || len < 0) + return NULL; + + pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_d2i_PKCS7_only(p7, in, len, content, + contentSz); + if (pkcs7 != NULL) { + if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len) + != 0) { + WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed"); + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + if (p7 != NULL) { + *p7 = NULL; + } + return NULL; + } + } + + return (PKCS7*)pkcs7; +} + + +/** + * This API was added as a helper function for libest. It + * extracts a stack of certificates from the pkcs7 object. + * @param pkcs7 PKCS7 parameter object + * @return WOLFSSL_STACK_OF(WOLFSSL_X509)* + */ +WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7) +{ + int i; + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + WOLF_STACK_OF(WOLFSSL_X509)* ret = NULL; + + WOLFSSL_ENTER("wolfSSL_PKCS7_to_stack"); + + if (!p7) { + WOLFSSL_MSG("Bad parameter"); + return NULL; + } + + if (p7->certs) + return p7->certs; + + for (i = 0; i < MAX_PKCS7_CERTS && p7->pkcs7.cert[i]; i++) { + WOLFSSL_X509* x509 = wolfSSL_X509_d2i_ex(NULL, p7->pkcs7.cert[i], + p7->pkcs7.certSz[i], pkcs7->heap); + if (!ret) + ret = wolfSSL_sk_X509_new_null(); + if (x509) { + if (wolfSSL_sk_X509_push(ret, x509) != WOLFSSL_SUCCESS) { + wolfSSL_X509_free(x509); + WOLFSSL_MSG("wolfSSL_sk_X509_push error"); + goto error; + } + } + else { + WOLFSSL_MSG("wolfSSL_X509_d2i error"); + goto error; + } + } + + /* Save stack to free later */ + if (p7->certs) + wolfSSL_sk_pop_free(p7->certs, NULL); + p7->certs = ret; + + return ret; +error: + if (ret) { + wolfSSL_sk_pop_free(ret, NULL); + } + return NULL; +} + +/** + * Return stack of signers contained in PKCS7 cert. + * Notes: + * - Currently only PKCS#7 messages with a single signer cert is supported. + * - Returned WOLFSSL_STACK must be freed by caller. + * + * pkcs7 - PKCS7 struct to retrieve signer certs from. + * certs - currently unused + * flags - flags to control function behavior. + * + * Return WOLFSSL_STACK of signers on success, NULL on error. + */ +WOLFSSL_STACK* wolfSSL_PKCS7_get0_signers(PKCS7* pkcs7, WOLFSSL_STACK* certs, + int flags) +{ + WOLFSSL_X509* x509 = NULL; + WOLFSSL_STACK* signers = NULL; + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + + if (p7 == NULL) + return NULL; + + /* Only PKCS#7 messages with a single cert that is the verifying certificate + * is supported. + */ + if (flags & PKCS7_NOINTERN) { + WOLFSSL_MSG("PKCS7_NOINTERN flag not supported"); + return NULL; + } + + signers = wolfSSL_sk_X509_new_null(); + if (signers == NULL) + return NULL; + + if (wolfSSL_d2i_X509(&x509, (const byte**)&p7->pkcs7.singleCert, + p7->pkcs7.singleCertSz) == NULL) { + wolfSSL_sk_X509_pop_free(signers, NULL); + return NULL; + } + + if (wolfSSL_sk_X509_push(signers, x509) != WOLFSSL_SUCCESS) { + wolfSSL_sk_X509_pop_free(signers, NULL); + return NULL; + } + + (void)certs; + + return signers; +} + +#ifndef NO_BIO + +PKCS7* wolfSSL_d2i_PKCS7_bio(WOLFSSL_BIO* bio, PKCS7** p7) +{ + WOLFSSL_PKCS7* pkcs7; + int ret; + + WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_bio"); + + if (bio == NULL) + return NULL; + + if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL) + return NULL; + + pkcs7->len = wolfSSL_BIO_get_len(bio); + pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7); + if (pkcs7->data == NULL) { + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + return NULL; + } + + if ((ret = wolfSSL_BIO_read(bio, pkcs7->data, pkcs7->len)) <= 0) { + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + return NULL; + } + /* pkcs7->len may change if using b64 for example */ + pkcs7->len = ret; + + if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len) + != 0) { + WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed"); + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + return NULL; + } + + if (p7 != NULL) + *p7 = (PKCS7*)pkcs7; + return (PKCS7*)pkcs7; +} + +int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out) +{ + byte* output = NULL; + int localBuf = 0; + int len; + WC_RNG rng; + int ret = WOLFSSL_FAILURE; + WOLFSSL_ENTER("wolfSSL_i2d_PKCS7"); + + if (!out || !p7) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + if (!p7->rng) { + if (wc_InitRng(&rng) != 0) { + WOLFSSL_MSG("wc_InitRng error"); + return WOLFSSL_FAILURE; + } + p7->rng = &rng; /* cppcheck-suppress autoVariables + */ + } + + if ((len = wc_PKCS7_EncodeSignedData(p7, NULL, 0)) < 0) { + WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error"); + goto cleanup; + } + + if (*out == NULL) { + output = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (!output) { + WOLFSSL_MSG("malloc error"); + goto cleanup; + } + localBuf = 1; + } + else { + output = *out; + } + + if ((len = wc_PKCS7_EncodeSignedData(p7, output, (word32)len)) < 0) { + WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error"); + goto cleanup; + } + + ret = len; +cleanup: + if (p7->rng == &rng) { + wc_FreeRng(&rng); + p7->rng = NULL; + } + if (ret == WOLFSSL_FAILURE && localBuf && output) + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (ret != WOLFSSL_FAILURE) + *out = output; + return ret; +} + +int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7) +{ + byte* output = NULL; + int len; + int ret = WOLFSSL_FAILURE; + WOLFSSL_ENTER("wolfSSL_i2d_PKCS7_bio"); + + if (!bio || !p7) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + if ((len = wolfSSL_i2d_PKCS7(p7, &output)) == WOLFSSL_FAILURE) { + WOLFSSL_MSG("wolfSSL_i2d_PKCS7 error"); + goto cleanup; + } + + if (wolfSSL_BIO_write(bio, output, len) <= 0) { + WOLFSSL_MSG("wolfSSL_BIO_write error"); + goto cleanup; + } + + ret = WOLFSSL_SUCCESS; +cleanup: + if (output) + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return ret; +} + +/** + * Creates and returns a PKCS7 signedData structure. + * + * Inner content type is set to DATA to match OpenSSL behavior. + * + * signer - certificate to sign bundle with + * pkey - private key matching signer + * certs - optional additional set of certificates to include + * in - input data to be signed + * flags - optional set of flags to control sign behavior + * + * PKCS7_BINARY - Do not translate input data to MIME canonical + * format (\r\n line endings), thus preventing corruption of + * binary content. + * PKCS7_TEXT - Prepend MIME headers for text/plain to content. + * PKCS7_DETACHED - Set signature detached, omit content from output bundle. + * PKCS7_STREAM - initialize PKCS7 struct for signing, do not read data. + * + * Flags not currently supported: + * PKCS7_NOCERTS - Do not include the signer cert in the output bundle. + * PKCS7_PARTIAL - Allow for PKCS7_sign() to be only partially set up, + * then signers etc to be added separately before + * calling PKCS7_final(). + * + * Returns valid PKCS7 structure pointer, or NULL if an error occurred. + */ +PKCS7* wolfSSL_PKCS7_sign(WOLFSSL_X509* signer, WOLFSSL_EVP_PKEY* pkey, + WOLFSSL_STACK* certs, WOLFSSL_BIO* in, int flags) +{ + int err = 0; + WOLFSSL_PKCS7* p7 = NULL; + WOLFSSL_STACK* cert = certs; + + WOLFSSL_ENTER("wolfSSL_PKCS7_sign"); + + if (flags & PKCS7_NOCERTS) { + WOLFSSL_MSG("PKCS7_NOCERTS flag not yet supported"); + err = 1; + } + + if (flags & PKCS7_PARTIAL) { + WOLFSSL_MSG("PKCS7_PARTIAL flag not yet supported"); + err = 1; + } + + if ((err == 0) && (signer == NULL || signer->derCert == NULL || + signer->derCert->length == 0)) { + WOLFSSL_MSG("Bad function arg, signer is NULL or incomplete"); + err = 1; + } + + if ((err == 0) && (pkey == NULL || pkey->pkey.ptr == NULL || + pkey->pkey_sz <= 0)) { + WOLFSSL_MSG("Bad function arg, pkey is NULL or incomplete"); + err = 1; + } + + if ((err == 0) && (in == NULL) && !(flags & PKCS7_STREAM)) { + WOLFSSL_MSG("input data required unless PKCS7_STREAM used"); + err = 1; + } + + if ((err == 0) && ((p7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)) { + WOLFSSL_MSG("Error allocating new WOLFSSL_PKCS7"); + err = 1; + } + + /* load signer certificate */ + if (err == 0) { + if (wc_PKCS7_InitWithCert(&p7->pkcs7, signer->derCert->buffer, + signer->derCert->length) != 0) { + WOLFSSL_MSG("Failed to load signer certificate"); + err = 1; + } + } + + /* set signer private key, data types, defaults */ + if (err == 0) { + p7->pkcs7.privateKey = (byte*)pkey->pkey.ptr; + p7->pkcs7.privateKeySz = (word32)pkey->pkey_sz; + p7->pkcs7.contentOID = DATA; /* inner content default is DATA */ + p7->pkcs7.hashOID = SHA256h; /* default to SHA-256 hash type */ + p7->type = SIGNED_DATA; /* PKCS7_final switches on type */ + } + + /* add additional chain certs if provided */ + while (cert && (err == 0)) { + if (cert->data.x509 != NULL && cert->data.x509->derCert != NULL) { + if (wc_PKCS7_AddCertificate(&p7->pkcs7, + cert->data.x509->derCert->buffer, + cert->data.x509->derCert->length) != 0) { + WOLFSSL_MSG("Error in wc_PKCS7_AddCertificate"); + err = 1; + } + } + cert = cert->next; + } + + if ((err == 0) && (flags & PKCS7_DETACHED)) { + if (wc_PKCS7_SetDetached(&p7->pkcs7, 1) != 0) { + WOLFSSL_MSG("Failed to set signature detached"); + err = 1; + } + } + + if ((err == 0) && (flags & PKCS7_STREAM)) { + /* if streaming, return before finalizing */ + return (PKCS7*)p7; + } + + if ((err == 0) && (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1)) { + WOLFSSL_MSG("Error calling wolfSSL_PKCS7_final"); + err = 1; + } + + if ((err != 0) && (p7 != NULL)) { + wolfSSL_PKCS7_free((PKCS7*)p7); + p7 = NULL; + } + + return (PKCS7*)p7; +} + +#ifdef HAVE_SMIME + +#ifndef MAX_MIME_LINE_LEN + #define MAX_MIME_LINE_LEN 1024 +#endif + +/** + * Copy input BIO to output BIO, but convert all line endings to CRLF (\r\n), + * used by PKCS7_final(). + * + * in - input WOLFSSL_BIO to be converted + * out - output WOLFSSL_BIO to hold copy of in, with line endings adjusted + * + * Return 0 on success, negative on error + */ +static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out) +{ + int ret = 0; + int lineLen = 0; + word32 canonLineLen = 0; + char* canonLine = NULL; +#ifdef WOLFSSL_SMALL_STACK + char* line = NULL; +#else + char line[MAX_MIME_LINE_LEN]; +#endif + + if (in == NULL || out == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + line = (char*)XMALLOC(MAX_MIME_LINE_LEN, in->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (line == NULL) { + return MEMORY_E; + } +#endif + XMEMSET(line, 0, MAX_MIME_LINE_LEN); + + while ((lineLen = wolfSSL_BIO_gets(in, line, MAX_MIME_LINE_LEN)) > 0) { + + if (line[lineLen - 1] == '\r' || line[lineLen - 1] == '\n') { + canonLineLen = (word32)lineLen; + if ((canonLine = wc_MIME_single_canonicalize( + line, &canonLineLen)) == NULL) { + ret = -1; + break; + } + + /* remove trailing null */ + if (canonLineLen >= 1 && canonLine[canonLineLen-1] == '\0') { + canonLineLen--; + } + + if (wolfSSL_BIO_write(out, canonLine, (int)canonLineLen) < 0) { + ret = -1; + break; + } + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + canonLine = NULL; + } + else { + /* no line ending in current line, write direct to out */ + if (wolfSSL_BIO_write(out, line, lineLen) < 0) { + ret = -1; + break; + } + } + } + + if (canonLine != NULL) { + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + } +#ifdef WOLFSSL_SMALL_STACK + XFREE(line, in->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +#endif /* HAVE_SMIME */ + +/* Used by both PKCS7_final() and PKCS7_verify() */ +static const char contTypeText[] = "Content-Type: text/plain\r\n\r\n"; + +/** + * Finalize PKCS7 structure, currently supports signedData only. + * + * Does not generate final bundle (ie: signedData), but finalizes + * the PKCS7 structure in preparation for a output function to be called next. + * + * pkcs7 - initialized PKCS7 structure, populated with signer, etc + * in - input data + * flags - flags to control PKCS7 behavior. Other flags except those noted + * below are ignored: + * + * PKCS7_BINARY - Do not translate input data to MIME canonical + * format (\r\n line endings), thus preventing corruption of + * binary content. + * PKCS7_TEXT - Prepend MIME headers for text/plain to content. + * + * Returns 1 on success, 0 on error + */ +int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags) +{ + int ret = 1; + int memSz = 0; + unsigned char* mem = NULL; + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + WOLFSSL_BIO* data = NULL; + + WOLFSSL_ENTER("wolfSSL_PKCS7_final"); + + if (p7 == NULL || in == NULL) { + WOLFSSL_MSG("Bad input args to PKCS7_final"); + ret = 0; + } + + if (ret == 1) { + if ((data = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())) == NULL) { + WOLFSSL_MSG("Error in wolfSSL_BIO_new"); + ret = 0; + } + } + + /* prepend Content-Type header if PKCS7_TEXT */ + if ((ret == 1) && (flags & PKCS7_TEXT)) { + if (wolfSSL_BIO_write(data, contTypeText, + (int)XSTR_SIZEOF(contTypeText)) < 0) { + WOLFSSL_MSG("Error prepending Content-Type header"); + ret = 0; + } + } + + /* convert line endings to CRLF if !PKCS7_BINARY */ + if (ret == 1) { + if (flags & PKCS7_BINARY) { + + /* no CRLF conversion, direct copy content */ + if ((memSz = wolfSSL_BIO_get_len(in)) <= 0) { + ret = 0; + } + if (ret == 1) { + mem = (unsigned char*)XMALLOC(memSz, in->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (mem == NULL) { + WOLFSSL_MSG("Failed to allocate memory for input data"); + ret = 0; + } + } + + if (ret == 1) { + if (wolfSSL_BIO_read(in, mem, memSz) != memSz) { + WOLFSSL_MSG("Error reading from input BIO"); + ret = 0; + } + else if (wolfSSL_BIO_write(data, mem, memSz) < 0) { + ret = 0; + } + } + + if (mem != NULL) { + XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + } + else { + #ifdef HAVE_SMIME + /* convert content line endings to CRLF */ + if (wolfSSL_BIO_to_MIME_crlf(in, data) != 0) { + WOLFSSL_MSG("Error converting line endings to CRLF"); + ret = 0; + } + else { + p7->pkcs7.contentCRLF = 1; + } + #else + WOLFSSL_MSG("Without PKCS7_BINARY requires wolfSSL to be built " + "with HAVE_SMIME"); + ret = 0; + #endif + } + } + + if ((ret == 1) && ((memSz = wolfSSL_BIO_get_mem_data(data, &mem)) < 0)) { + WOLFSSL_MSG("Error in wolfSSL_BIO_get_mem_data"); + ret = 0; + } + + if (ret == 1) { + if (p7->data != NULL) { + XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); + } + p7->data = (byte*)XMALLOC(memSz, NULL, DYNAMIC_TYPE_PKCS7); + if (p7->data == NULL) { + ret = 0; + } + else { + XMEMCPY(p7->data, mem, memSz); + p7->len = memSz; + } + } + + if (ret == 1) { + p7->pkcs7.content = p7->data; + p7->pkcs7.contentSz = (word32)p7->len; + } + + if (data != NULL) { + wolfSSL_BIO_free(data); + } + + return ret; +} + +int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs, + WOLFSSL_X509_STORE* store, WOLFSSL_BIO* in, WOLFSSL_BIO* out, int flags) +{ + int i, ret = 0; + unsigned char* mem = NULL; + int memSz = 0; + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + int contTypeLen; + WOLFSSL_X509* signer = NULL; + WOLFSSL_STACK* signers = NULL; + + WOLFSSL_ENTER("wolfSSL_PKCS7_verify"); + + if (pkcs7 == NULL) + return WOLFSSL_FAILURE; + + if (in != NULL) { + if ((memSz = wolfSSL_BIO_get_mem_data(in, &mem)) < 0) + return WOLFSSL_FAILURE; + + p7->pkcs7.content = mem; + p7->pkcs7.contentSz = (word32)memSz; + } + + /* certs is the list of certificates to find the cert with issuer/serial. */ + (void)certs; + /* store is the certificate store to use to verify signer certificate + * associated with the signers. + */ + (void)store; + + ret = wc_PKCS7_VerifySignedData(&p7->pkcs7, p7->data, p7->len); + if (ret != 0) + return WOLFSSL_FAILURE; + + if ((flags & PKCS7_NOVERIFY) != PKCS7_NOVERIFY) { + /* Verify signer certificates */ + if (store == NULL || store->cm == NULL) { + WOLFSSL_MSG("No store or store certs, but PKCS7_NOVERIFY not set"); + return WOLFSSL_FAILURE; + } + + signers = wolfSSL_PKCS7_get0_signers(pkcs7, certs, flags); + if (signers == NULL) { + WOLFSSL_MSG("No signers found to verify"); + return WOLFSSL_FAILURE; + } + for (i = 0; i < wolfSSL_sk_X509_num(signers); i++) { + signer = wolfSSL_sk_X509_value(signers, i); + + if (wolfSSL_CertManagerVerifyBuffer(store->cm, + signer->derCert->buffer, + signer->derCert->length, + WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to verify signer certificate"); + wolfSSL_sk_X509_pop_free(signers, NULL); + return WOLFSSL_FAILURE; + } + } + wolfSSL_sk_X509_pop_free(signers, NULL); + } + + if (flags & PKCS7_TEXT) { + /* strip MIME header for text/plain, otherwise error */ + contTypeLen = XSTR_SIZEOF(contTypeText); + if ((p7->pkcs7.contentSz < (word32)contTypeLen) || + (XMEMCMP(p7->pkcs7.content, contTypeText, contTypeLen) != 0)) { + WOLFSSL_MSG("Error PKCS7 Content-Type not found with PKCS7_TEXT"); + return WOLFSSL_FAILURE; + } + p7->pkcs7.content += contTypeLen; + p7->pkcs7.contentSz -= contTypeLen; + } + + if (out != NULL) { + wolfSSL_BIO_write(out, p7->pkcs7.content, p7->pkcs7.contentSz); + } + + WOLFSSL_LEAVE("wolfSSL_PKCS7_verify", WOLFSSL_SUCCESS); + + return WOLFSSL_SUCCESS; +} + +/** + * This API was added as a helper function for libest. It + * encodes a stack of certificates to pkcs7 format. + * @param pkcs7 PKCS7 parameter object + * @param certs WOLFSSL_STACK_OF(WOLFSSL_X509)* + * @param out Output bio + * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_PKCS7_encode_certs(PKCS7* pkcs7, WOLFSSL_STACK* certs, + WOLFSSL_BIO* out) +{ + int ret; + WOLFSSL_PKCS7* p7; + WOLFSSL_ENTER("wolfSSL_PKCS7_encode_certs"); + + if (!pkcs7 || !certs || !out) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + p7 = (WOLFSSL_PKCS7*)pkcs7; + + /* take ownership of certs */ + p7->certs = certs; + /* TODO: takes ownership even on failure below but not on above failure. */ + + if (pkcs7->certList) { + WOLFSSL_MSG("wolfSSL_PKCS7_encode_certs called multiple times on same " + "struct"); + return WOLFSSL_FAILURE; + } + + if (certs) { + /* Save some of the values */ + int hashOID = pkcs7->hashOID; + byte version = pkcs7->version; + + if (!certs->data.x509 || !certs->data.x509->derCert) { + WOLFSSL_MSG("Missing cert"); + return WOLFSSL_FAILURE; + } + + if (wc_PKCS7_InitWithCert(pkcs7, certs->data.x509->derCert->buffer, + certs->data.x509->derCert->length) != 0) { + WOLFSSL_MSG("wc_PKCS7_InitWithCert error"); + return WOLFSSL_FAILURE; + } + certs = certs->next; + + pkcs7->hashOID = hashOID; + pkcs7->version = version; + } + + /* Add the certs to the PKCS7 struct */ + while (certs) { + if (!certs->data.x509 || !certs->data.x509->derCert) { + WOLFSSL_MSG("Missing cert"); + return WOLFSSL_FAILURE; + } + if (wc_PKCS7_AddCertificate(pkcs7, certs->data.x509->derCert->buffer, + certs->data.x509->derCert->length) != 0) { + WOLFSSL_MSG("wc_PKCS7_AddCertificate error"); + return WOLFSSL_FAILURE; + } + certs = certs->next; + } + + if (wc_PKCS7_SetSignerIdentifierType(pkcs7, DEGENERATE_SID) != 0) { + WOLFSSL_MSG("wc_PKCS7_SetSignerIdentifierType error"); + return WOLFSSL_FAILURE; + } + + ret = wolfSSL_i2d_PKCS7_bio(out, pkcs7); + + return ret; +} + +/****************************************************************************** +* wolfSSL_PEM_write_bio_PKCS7 - writes the PKCS7 data to BIO +* +* RETURNS: +* returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE +*/ +int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7) +{ +#ifdef WOLFSSL_SMALL_STACK + byte* outputHead; + byte* outputFoot; +#else + byte outputHead[2048]; + byte outputFoot[2048]; +#endif + word32 outputHeadSz = 2048; + word32 outputFootSz = 2048; + word32 outputSz = 0; + byte* output = NULL; + byte* pem = NULL; + int pemSz = -1; + enum wc_HashType hashType; + byte hashBuf[WC_MAX_DIGEST_SIZE]; + word32 hashSz = -1; + + WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PKCS7"); + + if (bio == NULL || p7 == NULL) + return WOLFSSL_FAILURE; + +#ifdef WOLFSSL_SMALL_STACK + outputHead = (byte*)XMALLOC(outputHeadSz, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (outputHead == NULL) + return MEMORY_E; + + outputFoot = (byte*)XMALLOC(outputFootSz, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (outputFoot == NULL) + goto error; + +#endif + + XMEMSET(hashBuf, 0, WC_MAX_DIGEST_SIZE); + XMEMSET(outputHead, 0, outputHeadSz); + XMEMSET(outputFoot, 0, outputFootSz); + + hashType = wc_OidGetHash(p7->hashOID); + hashSz = (word32)wc_HashGetDigestSize(hashType); + if (hashSz > WC_MAX_DIGEST_SIZE) + goto error; + + /* only SIGNED_DATA is supported */ + switch (p7->contentOID) { + case SIGNED_DATA: + break; + default: + WOLFSSL_MSG("Unknown PKCS#7 Type"); + goto error; + }; + + if ((wc_PKCS7_EncodeSignedData_ex(p7, hashBuf, hashSz, + outputHead, &outputHeadSz, outputFoot, &outputFootSz)) != 0) + goto error; + + outputSz = outputHeadSz + p7->contentSz + outputFootSz; + output = (byte*)XMALLOC(outputSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + + if (!output) + goto error; + + XMEMSET(output, 0, outputSz); + outputSz = 0; + XMEMCPY(&output[outputSz], outputHead, outputHeadSz); + outputSz += outputHeadSz; + XMEMCPY(&output[outputSz], p7->content, p7->contentSz); + outputSz += p7->contentSz; + XMEMCPY(&output[outputSz], outputFoot, outputFootSz); + outputSz += outputFootSz; + + /* get PEM size */ + pemSz = wc_DerToPemEx(output, outputSz, NULL, 0, NULL, CERT_TYPE); + if (pemSz < 0) + goto error; + + pemSz++; /* for '\0'*/ + + /* create PEM buffer and convert from DER to PEM*/ + if ((pem = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER)) + == NULL) + goto error; + + XMEMSET(pem, 0, pemSz); + + if (wc_DerToPemEx(output, outputSz, pem, (word32)pemSz, NULL, CERT_TYPE) < 0) { + goto error; + } + if ((wolfSSL_BIO_write(bio, pem, pemSz) == pemSz)) { + XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); +#ifdef WOLFSSL_SMALL_STACK + XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return WOLFSSL_SUCCESS; + } + +error: +#ifdef WOLFSSL_SMALL_STACK + if (outputHead) { + XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + if (outputFoot) { + XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif + if (output) { + XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + if (pem) { + XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + return WOLFSSL_FAILURE; +} + +#ifdef HAVE_SMIME +/***************************************************************************** +* wolfSSL_SMIME_read_PKCS7 - Reads the given S/MIME message and parses it into +* a PKCS7 object. In case of a multipart message, stores the signed data in +* bcont. +* +* RETURNS: +* returns pointer to a PKCS7 structure on success, otherwise returns NULL +*/ +PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, + WOLFSSL_BIO** bcont) +{ + MimeHdr* allHdrs = NULL; + MimeHdr* curHdr = NULL; + MimeParam* curParam = NULL; + int inLen = 0; + byte* bcontMem = NULL; + int bcontMemSz = 0; + int sectionLen = 0; + int ret = -1; + char* section = NULL; + char* canonLine = NULL; + char* canonSection = NULL; + PKCS7* pkcs7 = NULL; + word32 outLen = 0; + word32 canonLineLen = 0; + byte* out = NULL; + byte* outHead = NULL; + + int canonPos = 0; + int lineLen = 0; + int remainLen = 0; + byte isEnd = 0; + size_t canonSize = 0; + size_t boundLen = 0; + char* boundary = NULL; + + static const char kContType[] = "Content-Type"; + static const char kCTE[] = "Content-Transfer-Encoding"; + static const char kMultSigned[] = "multipart/signed"; + static const char kAppPkcsSign[] = "application/pkcs7-signature"; + static const char kAppXPkcsSign[] = "application/x-pkcs7-signature"; + static const char kAppPkcs7Mime[] = "application/pkcs7-mime"; + static const char kAppXPkcs7Mime[] = "application/x-pkcs7-mime"; + + WOLFSSL_ENTER("wolfSSL_SMIME_read_PKCS7"); + + if (in == NULL || bcont == NULL) { + goto error; + } + inLen = wolfSSL_BIO_get_len(in); + if (inLen <= 0) { + goto error; + } + remainLen = wolfSSL_BIO_get_len(in); + if (remainLen <= 0) { + goto error; + } + + section = (char*)XMALLOC(remainLen+1, NULL, DYNAMIC_TYPE_PKCS7); + if (section == NULL) { + goto error; + } + lineLen = wolfSSL_BIO_gets(in, section, remainLen); + if (lineLen <= 0) { + goto error; + } + while (isEnd == 0 && remainLen > 0) { + sectionLen += lineLen; + remainLen -= lineLen; + lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], remainLen); + if (lineLen <= 0) { + goto error; + } + /* Line with just newline signals end of headers. */ + if ((lineLen==2 && !XSTRNCMP(§ion[sectionLen], + "\r\n", 2)) || + (lineLen==1 && (section[sectionLen] == '\r' || + section[sectionLen] == '\n'))) { + isEnd = 1; + } + } + section[sectionLen] = '\0'; + ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs); + if (ret < 0) { + WOLFSSL_MSG("Parsing MIME headers failed."); + goto error; + } + isEnd = 0; + section[0] = '\0'; + sectionLen = 0; + + curHdr = wc_MIME_find_header_name(kContType, allHdrs); + if (curHdr && !XSTRNCMP(curHdr->body, kMultSigned, + XSTR_SIZEOF(kMultSigned))) { + curParam = wc_MIME_find_param_attr("protocol", curHdr->params); + if (curParam && (!XSTRNCMP(curParam->value, kAppPkcsSign, + XSTR_SIZEOF(kAppPkcsSign)) || + !XSTRNCMP(curParam->value, kAppXPkcsSign, + XSTR_SIZEOF(kAppXPkcsSign)))) { + curParam = wc_MIME_find_param_attr("boundary", curHdr->params); + if (curParam == NULL) { + goto error; + } + + boundLen = XSTRLEN(curParam->value) + 2; + boundary = (char*)XMALLOC(boundLen+1, NULL, DYNAMIC_TYPE_PKCS7); + if (boundary == NULL) { + goto error; + } + XMEMSET(boundary, 0, (word32)(boundLen+1)); + boundary[0] = boundary[1] = '-'; + XSTRNCPY(&boundary[2], curParam->value, boundLen-2); + + /* Parse up to first boundary, ignore everything here. */ + lineLen = wolfSSL_BIO_gets(in, section, remainLen); + if (lineLen <= 0) { + goto error; + } + while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && + remainLen > 0) { + sectionLen += lineLen; + remainLen -= lineLen; + lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], + remainLen); + if (lineLen <= 0) { + goto error; + } + } + + section[0] = '\0'; + sectionLen = 0; + canonSize = (size_t)remainLen + 1; + canonSection = (char*)XMALLOC(canonSize, NULL, + DYNAMIC_TYPE_PKCS7); + if (canonSection == NULL) { + goto error; + } + + lineLen = wolfSSL_BIO_gets(in, section, remainLen); + if (lineLen < 0) { + goto error; + } + while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && + remainLen > 0) { + canonLineLen = (word32)lineLen; + canonLine = wc_MIME_single_canonicalize(§ion[sectionLen], + &canonLineLen); + if (canonLine == NULL) { + goto error; + } + /* If line endings were added, the initial length may be + * exceeded. */ + if ((canonPos + canonLineLen) >= canonSize) { + canonSize = canonPos + canonLineLen; + canonSection = (char*)XREALLOC(canonSection, canonSize, + NULL, DYNAMIC_TYPE_PKCS7); + if (canonSection == NULL) { + goto error; + } + } + XMEMCPY(&canonSection[canonPos], canonLine, + (int)canonLineLen - 1); + canonPos += canonLineLen - 1; + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + canonLine = NULL; + + sectionLen += lineLen; + remainLen -= lineLen; + + lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], + remainLen); + if (lineLen <= 0) { + goto error; + } + } + + if (canonPos > 0) { + canonPos--; + } + + /* Strip the final trailing newline. Support \r, \n or \r\n. */ + if (canonSection[canonPos] == '\n') { + if (canonPos > 0) { + canonPos--; + } + } + + if (canonSection[canonPos] == '\r') { + if (canonPos > 0) { + canonPos--; + } + } + + canonSection[canonPos+1] = '\0'; + + *bcont = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); + ret = wolfSSL_BIO_write(*bcont, canonSection, + canonPos + 1); + if (ret != (canonPos+1)) { + goto error; + } + if ((bcontMemSz = wolfSSL_BIO_get_mem_data(*bcont, &bcontMem)) + < 0) { + goto error; + } + XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); + canonSection = NULL; + + wc_MIME_free_hdrs(allHdrs); + allHdrs = NULL; + section[0] = '\0'; + sectionLen = 0; + lineLen = wolfSSL_BIO_gets(in, section, remainLen); + if (lineLen <= 0) { + goto error; + } + while (isEnd == 0 && remainLen > 0) { + sectionLen += lineLen; + remainLen -= lineLen; + lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], + remainLen); + if (lineLen <= 0) { + goto error; + } + /* Line with just newline signals end of headers. */ + if ((lineLen==2 && !XSTRNCMP(§ion[sectionLen], + "\r\n", 2)) || + (lineLen==1 && (section[sectionLen] == '\r' || + section[sectionLen] == '\n'))) { + isEnd = 1; + } + } + section[sectionLen] = '\0'; + ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs); + if (ret < 0) { + WOLFSSL_MSG("Parsing MIME headers failed."); + goto error; + } + curHdr = wc_MIME_find_header_name(kContType, allHdrs); + if (curHdr == NULL || (XSTRNCMP(curHdr->body, kAppPkcsSign, + XSTR_SIZEOF(kAppPkcsSign)) && + XSTRNCMP(curHdr->body, kAppXPkcsSign, + XSTR_SIZEOF(kAppXPkcsSign)))) { + WOLFSSL_MSG("S/MIME headers not found inside " + "multipart message.\n"); + goto error; + } + + section[0] = '\0'; + sectionLen = 0; + lineLen = wolfSSL_BIO_gets(in, section, remainLen); + while (XSTRNCMP(§ion[sectionLen], boundary, boundLen) && + remainLen > 0) { + sectionLen += lineLen; + remainLen -= lineLen; + lineLen = wolfSSL_BIO_gets(in, §ion[sectionLen], + remainLen); + if (lineLen <= 0) { + goto error; + } + } + + XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7); + boundary = NULL; + } + } + else if (curHdr && (!XSTRNCMP(curHdr->body, kAppPkcs7Mime, + XSTR_SIZEOF(kAppPkcs7Mime)) || + !XSTRNCMP(curHdr->body, kAppXPkcs7Mime, + XSTR_SIZEOF(kAppXPkcs7Mime)))) { + sectionLen = wolfSSL_BIO_get_len(in); + if (sectionLen <= 0) { + goto error; + } + ret = wolfSSL_BIO_read(in, section, sectionLen); + if (ret < 0 || ret != sectionLen) { + WOLFSSL_MSG("Error reading input BIO."); + goto error; + } + } + else { + WOLFSSL_MSG("S/MIME headers not found."); + goto error; + } + + curHdr = wc_MIME_find_header_name(kCTE, allHdrs); + if (curHdr == NULL) { + WOLFSSL_MSG("Content-Transfer-Encoding header not found, " + "assuming base64 encoding."); + } + else if (XSTRNCMP(curHdr->body, "base64", XSTRLEN("base64"))) { + WOLFSSL_MSG("S/MIME encodings other than base64 are not " + "currently supported.\n"); + goto error; + } + + if (section == NULL || sectionLen <= 0) { + goto error; + } + outLen = (word32)((sectionLen*3+3)/4)+1; + out = (byte*)XMALLOC(outLen*sizeof(byte), NULL, DYNAMIC_TYPE_PKCS7); + outHead = out; + if (outHead == NULL) { + goto error; + } + /* Strip trailing newlines. */ + while ((sectionLen > 0) && + (section[sectionLen-1] == '\r' || section[sectionLen-1] == '\n')) { + sectionLen--; + } + section[sectionLen] = '\0'; + ret = Base64_Decode((const byte*)section, (word32)sectionLen, out, &outLen); + if (ret < 0) { + WOLFSSL_MSG("Error base64 decoding S/MIME message."); + goto error; + } + pkcs7 = wolfSSL_d2i_PKCS7_only(NULL, (const unsigned char**)&out, (int)outLen, + bcontMem, (word32)bcontMemSz); + + wc_MIME_free_hdrs(allHdrs); + XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(section, NULL, DYNAMIC_TYPE_PKCS7); + + return pkcs7; + +error: + wc_MIME_free_hdrs(allHdrs); + XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(section, NULL, DYNAMIC_TYPE_PKCS7); + if (canonSection != NULL) + XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); + if (canonLine != NULL) + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + if (bcont) { + wolfSSL_BIO_free(*bcont); + *bcont = NULL; /* reset 'bcount' pointer to NULL on failure */ + } + + return NULL; +} + +/* Convert hash algo OID (from Hash_Sum in asn.h) to SMIME string equivalent. + * Returns hash algorithm string or "unknown" if not found */ +static const char* wolfSSL_SMIME_HashOIDToString(int hashOID) +{ + switch (hashOID) { + case MD5h: + return "md5"; + case SHAh: + return "sha1"; + case SHA224h: + return "sha-224"; + case SHA256h: + return "sha-256"; + case SHA384h: + return "sha-384"; + case SHA512h: + return "sha-512"; + case SHA3_224h: + return "sha3-224"; + case SHA3_384h: + return "sha3-384"; + case SHA3_512h: + return "sha3-512"; + default: + break; + } + + return "unknown"; +} + +/* Convert PKCS#7 type (from PKCS7_TYPES in pkcs7.h) to SMIME string. + * RFC2633 only defines signed-data, enveloped-data, certs-only. + * Returns string on success, NULL on unknown type. */ +static const char* wolfSSL_SMIME_PKCS7TypeToString(int type) +{ + switch (type) { + case SIGNED_DATA: + return "signed-data"; + case ENVELOPED_DATA: + return "enveloped-data"; + default: + break; + } + + return NULL; +} + +/** + * Convert PKCS7 structure to SMIME format, adding necessary headers. + * + * Handles generation of PKCS7 bundle (ie: signedData). PKCS7 structure + * should be set up beforehand with PKCS7_sign/final/etc. Output is always + * Base64 encoded. + * + * out - output BIO for SMIME formatted data to be placed + * pkcs7 - input PKCS7 structure, initialized and set up + * in - input content to be encoded into PKCS7 + * flags - flags to control behavior of PKCS7 generation + * + * Returns 1 on success, 0 or negative on failure + */ +int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in, + int flags) +{ + int i; + int ret = 1; + WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; + byte* p7out = NULL; + int len = 0; + + char boundary[33]; /* 32 chars + \0 */ + byte* sigBase64 = NULL; + word32 sigBase64Len = 0; + const char* p7TypeString = NULL; + + static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + if (out == NULL || p7 == NULL) { + WOLFSSL_MSG("Bad function arguments"); + return 0; + } + + if (in != NULL && (p7->pkcs7.content == NULL || p7->pkcs7.contentSz == 0 || + p7->pkcs7.contentCRLF == 0)) { + /* store and adjust content line endings for CRLF if needed */ + if (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1) { + ret = 0; + } + } + + if (ret > 0) { + /* Generate signedData bundle, DER in output (dynamic) */ + if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) == WOLFSSL_FAILURE) { + WOLFSSL_MSG("Error in wolfSSL_i2d_PKCS7"); + ret = 0; + } + } + + /* Base64 encode signedData bundle */ + if (ret > 0) { + if (Base64_Encode(p7out, (word32)len, NULL, &sigBase64Len) != + WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { + ret = 0; + } + else { + sigBase64 = (byte*)XMALLOC(sigBase64Len, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (sigBase64 == NULL) { + ret = 0; + } + } + } + + if (ret > 0) { + XMEMSET(sigBase64, 0, sigBase64Len); + if (Base64_Encode(p7out, (word32)len, sigBase64, &sigBase64Len) < 0) { + WOLFSSL_MSG("Error in Base64_Encode of signature"); + ret = 0; + } + } + + /* build up SMIME message */ + if (ret > 0) { + if (flags & PKCS7_DETACHED) { + + /* generate random boundary */ + if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("No RNG to use"); + ret = 0; + } + + /* no need to generate random byte for null terminator (size-1) */ + if ((ret > 0) && (wc_RNG_GenerateBlock(&globalRNG, (byte*)boundary, + sizeof(boundary) - 1 ) != 0)) { + WOLFSSL_MSG("Error in wc_RNG_GenerateBlock"); + ret = 0; + } + + if (ret > 0) { + for (i = 0; i < (int)sizeof(boundary) - 1; i++) { + boundary[i] = + alphanum[boundary[i] % XSTR_SIZEOF(alphanum)]; + } + boundary[sizeof(boundary)-1] = 0; + } + + if (ret > 0) { + /* S/MIME header beginning */ + ret = wolfSSL_BIO_printf(out, + "MIME-Version: 1.0\n" + "Content-Type: multipart/signed; " + "protocol=\"application/x-pkcs7-signature\"; " + "micalg=\"%s\"; " + "boundary=\"----%s\"\n\n" + "This is an S/MIME signed message\n\n" + "------%s\n", + wolfSSL_SMIME_HashOIDToString(p7->pkcs7.hashOID), + boundary, boundary); + } + + if (ret > 0) { + /* S/MIME content */ + ret = wolfSSL_BIO_write(out, + p7->pkcs7.content, p7->pkcs7.contentSz); + } + + if (ret > 0) { + /* S/SMIME header end boundary */ + ret = wolfSSL_BIO_printf(out, + "\n------%s\n", boundary); + } + + if (ret > 0) { + /* Signature and header */ + ret = wolfSSL_BIO_printf(out, + "Content-Type: application/x-pkcs7-signature; " + "name=\"smime.p7s\"\n" + "Content-Transfer-Encoding: base64\n" + "Content-Disposition: attachment; " + "filename=\"smime.p7s\"\n\n" + "%.*s\n" /* Base64 encoded signature */ + "------%s--\n\n", + sigBase64Len, sigBase64, + boundary); + } + } + else { + p7TypeString = wolfSSL_SMIME_PKCS7TypeToString(p7->type); + if (p7TypeString == NULL) { + WOLFSSL_MSG("Unsupported PKCS7 SMIME type"); + ret = 0; + } + + if (ret > 0) { + /* not detached */ + ret = wolfSSL_BIO_printf(out, + "MIME-Version: 1.0\n" + "Content-Disposition: attachment; " + "filename=\"smime.p7m\"\n" + "Content-Type: application/x-pkcs7-mime; " + "smime-type=%s; name=\"smime.p7m\"\n" + "Content-Transfer-Encoding: base64\n\n" + "%.*s\n" /* signature */, + p7TypeString, sigBase64Len, sigBase64); + } + } + } + + if (p7out != NULL) { + XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + if (sigBase64 != NULL) { + XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + + if (ret > 0) { + return WOLFSSL_SUCCESS; + } + + return WOLFSSL_FAILURE; +} + +#endif /* HAVE_SMIME */ +#endif /* !NO_BIO */ +#endif /* OPENSSL_ALL */ + +#endif /* HAVE_PKCS7 */ +/******************************************************************************* + * END OF PKCS7 APIs + ******************************************************************************/ + +/******************************************************************************* + * START OF PKCS12 APIs + ******************************************************************************/ +#ifdef OPENSSL_EXTRA + +/* no-op function. Was initially used for adding encryption algorithms available + * for PKCS12 */ +void wolfSSL_PKCS12_PBE_add(void) +{ + WOLFSSL_ENTER("wolfSSL_PKCS12_PBE_add"); +} + +#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) +WOLFSSL_X509_PKCS12 *wolfSSL_d2i_PKCS12_fp(XFILE fp, + WOLFSSL_X509_PKCS12 **pkcs12) +{ + WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_fp"); + return (WOLFSSL_X509_PKCS12 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)pkcs12, + PKCS12_TYPE); +} +#endif /* !NO_FILESYSTEM */ + +#endif /* OPENSSL_EXTRA */ + +#if defined(HAVE_PKCS12) + +#ifdef OPENSSL_EXTRA + +#if !defined(NO_ASN) && !defined(NO_PWDBASED) + +#ifndef NO_BIO +WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12) +{ + WC_PKCS12* localPkcs12 = NULL; + unsigned char* mem = NULL; + long memSz; + int ret = -1; + + WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_bio"); + + if (bio == NULL) { + WOLFSSL_MSG("Bad Function Argument bio is NULL"); + return NULL; + } + + memSz = wolfSSL_BIO_get_len(bio); + if (memSz <= 0) { + return NULL; + } + mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (mem == NULL) { + return NULL; + } + + if (mem != NULL) { + localPkcs12 = wc_PKCS12_new_ex(bio->heap); + if (localPkcs12 == NULL) { + WOLFSSL_MSG("Memory error"); + } + } + + if (mem != NULL && localPkcs12 != NULL) { + if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) { + ret = wc_d2i_PKCS12(mem, (word32)memSz, localPkcs12); + if (ret < 0) { + WOLFSSL_MSG("Failed to get PKCS12 sequence"); + } + } + else { + WOLFSSL_MSG("Failed to get data from bio struct"); + } + } + + /* cleanup */ + if (mem != NULL) + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ret < 0 && localPkcs12 != NULL) { + wc_PKCS12_free(localPkcs12); + localPkcs12 = NULL; + } + if (pkcs12 != NULL) + *pkcs12 = localPkcs12; + + return localPkcs12; +} + +/* Converts the PKCS12 to DER format and outputs it into bio. + * + * bio is the structure to hold output DER + * pkcs12 structure to create DER from + * + * return 1 for success or 0 if an error occurs + */ +int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12) +{ + int ret = WOLFSSL_FAILURE; + + WOLFSSL_ENTER("wolfSSL_i2d_PKCS12_bio"); + + if ((bio != NULL) && (pkcs12 != NULL)) { + word32 certSz = 0; + byte *certDer = NULL; + + certSz = (word32)wc_i2d_PKCS12(pkcs12, &certDer, NULL); + if ((certSz > 0) && (certDer != NULL)) { + if (wolfSSL_BIO_write(bio, certDer, (int)certSz) == (int)certSz) { + ret = WOLFSSL_SUCCESS; + } + } + + if (certDer != NULL) { + XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS); + } + } + + return ret; +} +#endif /* !NO_BIO */ + +/* Creates a new WC_PKCS12 structure + * + * pass password to use + * name friendlyName to use + * pkey private key to go into PKCS12 bundle + * cert certificate to go into PKCS12 bundle + * ca extra certificates that can be added to bundle. Can be NULL + * keyNID type of encryption to use on the key (-1 means no encryption) + * certNID type of encryption to use on the certificate + * itt number of iterations with encryption + * macItt number of iterations with mac creation + * keyType flag for signature and/or encryption key + * + * returns a pointer to a new WC_PKCS12 structure on success and NULL on fail + */ +WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey, + WOLFSSL_X509* cert, WOLF_STACK_OF(WOLFSSL_X509)* ca, int keyNID, + int certNID, int itt, int macItt, int keyType) +{ + WC_PKCS12* pkcs12; + WC_DerCertList* list = NULL; + word32 passSz; + byte* keyDer = NULL; + word32 keyDerSz; + byte* certDer; + int certDerSz; + + WOLFSSL_ENTER("wolfSSL_PKCS12_create"); + + if (pass == NULL || pkey == NULL || cert == NULL) { + WOLFSSL_LEAVE("wolfSSL_PKCS12_create", BAD_FUNC_ARG); + return NULL; + } + passSz = (word32)XSTRLEN(pass); + + keyDer = (byte*)pkey->pkey.ptr; + keyDerSz = (word32)pkey->pkey_sz; + + certDer = (byte*)wolfSSL_X509_get_der(cert, &certDerSz); + if (certDer == NULL) { + return NULL; + } + + if (ca != NULL) { + unsigned long numCerts = ca->num; + WOLFSSL_STACK* sk = ca; + + while (numCerts > 0 && sk != NULL) { + byte* curDer; + WC_DerCertList* cur; + int curDerSz = 0; + + cur = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList), NULL, + DYNAMIC_TYPE_PKCS); + if (cur == NULL) { + wc_FreeCertList(list, NULL); + return NULL; + } + + curDer = (byte*)wolfSSL_X509_get_der(sk->data.x509, &curDerSz); + if (curDer == NULL || curDerSz < 0) { + XFREE(cur, NULL, DYNAMIC_TYPE_PKCS); + wc_FreeCertList(list, NULL); + return NULL; + } + + cur->buffer = (byte*)XMALLOC(curDerSz, NULL, DYNAMIC_TYPE_PKCS); + if (cur->buffer == NULL) { + XFREE(cur, NULL, DYNAMIC_TYPE_PKCS); + wc_FreeCertList(list, NULL); + return NULL; + } + XMEMCPY(cur->buffer, curDer, curDerSz); + cur->bufferSz = (word32)curDerSz; + cur->next = list; + list = cur; + + sk = sk->next; + numCerts--; + } + } + + pkcs12 = wc_PKCS12_create(pass, passSz, name, keyDer, keyDerSz, + certDer, (word32)certDerSz, list, keyNID, certNID, itt, macItt, + keyType, NULL); + + if (ca != NULL) { + wc_FreeCertList(list, NULL); + } + + return pkcs12; +} + + +/* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure */ +int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, + WOLFSSL_EVP_PKEY** pkey, WOLFSSL_X509** cert, + WOLF_STACK_OF(WOLFSSL_X509)** ca) +{ + void* heap = NULL; + int ret; + byte* certData = NULL; + word32 certDataSz; + byte* pk = NULL; + word32 pkSz; + WC_DerCertList* certList = NULL; +#ifdef WOLFSSL_SMALL_STACK + DecodedCert *DeCert; +#else + DecodedCert DeCert[1]; +#endif + + WOLFSSL_ENTER("wolfSSL_PKCS12_parse"); + + /* make sure we init return args */ + if (pkey) *pkey = NULL; + if (cert) *cert = NULL; + if (ca) *ca = NULL; + + if (pkcs12 == NULL || psw == NULL || pkey == NULL || cert == NULL) { + WOLFSSL_MSG("Bad argument value"); + return WOLFSSL_FAILURE; + } + + heap = wc_PKCS12_GetHeap(pkcs12); + + if (ca == NULL) { + ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz, + NULL); + } + else { + ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz, + &certList); + } + if (ret < 0) { + WOLFSSL_LEAVE("wolfSSL_PKCS12_parse", ret); + return WOLFSSL_FAILURE; + } + +#ifdef WOLFSSL_SMALL_STACK + DeCert = (DecodedCert *)XMALLOC(sizeof(*DeCert), heap, + DYNAMIC_TYPE_DCERT); + if (DeCert == NULL) { + WOLFSSL_MSG("out of memory"); + return WOLFSSL_FAILURE; + } +#endif + + /* Decode cert and place in X509 stack struct */ + if (certList != NULL) { + WC_DerCertList* current = certList; + + *ca = (WOLF_STACK_OF(WOLFSSL_X509)*)XMALLOC( + sizeof(WOLF_STACK_OF(WOLFSSL_X509)), heap, DYNAMIC_TYPE_X509); + if (*ca == NULL) { + if (pk != NULL) { + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + if (certData != NULL) { + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + } + /* Free up WC_DerCertList and move on */ + while (current != NULL) { + WC_DerCertList* next = current->next; + + XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); + XFREE(current, heap, DYNAMIC_TYPE_PKCS); + current = next; + } + ret = WOLFSSL_FAILURE; + goto out; + } + XMEMSET(*ca, 0, sizeof(WOLF_STACK_OF(WOLFSSL_X509))); + + /* add list of DER certs as X509's to stack */ + while (current != NULL) { + WC_DerCertList* toFree = current; + WOLFSSL_X509* x509; + + x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, + DYNAMIC_TYPE_X509); + InitX509(x509, 1, heap); + InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap); + if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL) != 0) { + WOLFSSL_MSG("Issue with parsing certificate"); + FreeDecodedCert(DeCert); + wolfSSL_X509_free(x509); + } + else { + if (CopyDecodedToX509(x509, DeCert) != 0) { + WOLFSSL_MSG("Failed to copy decoded cert"); + FreeDecodedCert(DeCert); + wolfSSL_X509_free(x509); + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + if (pk != NULL) { + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + if (certData != NULL) { + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + } + /* Free up WC_DerCertList */ + while (current != NULL) { + WC_DerCertList* next = current->next; + + XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); + XFREE(current, heap, DYNAMIC_TYPE_PKCS); + current = next; + } + ret = WOLFSSL_FAILURE; + goto out; + } + FreeDecodedCert(DeCert); + + if (wolfSSL_sk_X509_push(*ca, x509) != 1) { + WOLFSSL_MSG("Failed to push x509 onto stack"); + wolfSSL_X509_free(x509); + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + if (pk != NULL) { + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + if (certData != NULL) { + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + } + + /* Free up WC_DerCertList */ + while (current != NULL) { + WC_DerCertList* next = current->next; + + XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); + XFREE(current, heap, DYNAMIC_TYPE_PKCS); + current = next; + } + ret = WOLFSSL_FAILURE; + goto out; + } + } + current = current->next; + XFREE(toFree->buffer, heap, DYNAMIC_TYPE_PKCS); + XFREE(toFree, heap, DYNAMIC_TYPE_PKCS); + } + } + + + /* Decode cert and place in X509 struct */ + if (certData != NULL) { + *cert = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, + DYNAMIC_TYPE_X509); + if (*cert == NULL) { + if (pk != NULL) { + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + if (ca != NULL) { + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + } + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + ret = WOLFSSL_FAILURE; + goto out; + } + InitX509(*cert, 1, heap); + InitDecodedCert(DeCert, certData, certDataSz, heap); + if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL) != 0) { + WOLFSSL_MSG("Issue with parsing certificate"); + } + if (CopyDecodedToX509(*cert, DeCert) != 0) { + WOLFSSL_MSG("Failed to copy decoded cert"); + FreeDecodedCert(DeCert); + if (pk != NULL) { + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + } + if (ca != NULL) { + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + } + wolfSSL_X509_free(*cert); *cert = NULL; + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + ret = WOLFSSL_FAILURE; + goto out; + } + FreeDecodedCert(DeCert); + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); + } + + + /* get key type */ + ret = BAD_STATE_E; + if (pk != NULL) { /* decode key if present */ + *pkey = wolfSSL_EVP_PKEY_new_ex(heap); + if (*pkey == NULL) { + wolfSSL_X509_free(*cert); *cert = NULL; + if (ca != NULL) { + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + ret = WOLFSSL_FAILURE; + goto out; + } + + #ifndef NO_RSA + { + const unsigned char* pt = pk; + if (wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, pkey, &pt, pkSz) != + NULL) { + ret = 0; + } + } + #endif /* NO_RSA */ + + #ifdef HAVE_ECC + if (ret != 0) { /* if is in fail state check if ECC key */ + const unsigned char* pt = pk; + if (wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, pkey, &pt, pkSz) != + NULL) { + ret = 0; + } + } + #endif /* HAVE_ECC */ + if (pk != NULL) + XFREE(pk, heap, DYNAMIC_TYPE_PKCS); + if (ret != 0) { /* if is in fail state and no PKEY then fail */ + wolfSSL_X509_free(*cert); *cert = NULL; + if (ca != NULL) { + wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; + } + wolfSSL_EVP_PKEY_free(*pkey); *pkey = NULL; + WOLFSSL_MSG("Bad PKCS12 key format"); + ret = WOLFSSL_FAILURE; + goto out; + } + + if (pkey != NULL && *pkey != NULL) { + (*pkey)->save_type = 0; + } + } + + (void)ret; + (void)ca; + + ret = WOLFSSL_SUCCESS; + +out: + +#ifdef WOLFSSL_SMALL_STACK + XFREE(DeCert, heap, DYNAMIC_TYPE_DCERT); +#endif + + return ret; +} + +int wolfSSL_PKCS12_verify_mac(WC_PKCS12 *pkcs12, const char *psw, + int pswLen) +{ + WOLFSSL_ENTER("wolfSSL_PKCS12_verify_mac"); + + if (!pkcs12) { + return WOLFSSL_FAILURE; + } + + return wc_PKCS12_verify_ex(pkcs12, (const byte*)psw, (word32)pswLen) == 0 ? + WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} + +#endif /* !NO_ASN && !NO_PWDBASED */ + +#endif /* OPENSSL_EXTRA */ + +#endif /* HAVE_PKCS12 */ +/******************************************************************************* + * END OF PKCS12 APIs + ******************************************************************************/ + +#endif /* !WOLFCRYPT_ONLY && !NO_CERTS */ + +#endif /* !WOLFSSL_SSL_P7P12_INCLUDED */ diff --git a/src/src/ssl_sess.c b/src/src/ssl_sess.c new file mode 100644 index 0000000..43ce1f5 --- /dev/null +++ b/src/src/ssl_sess.c @@ -0,0 +1,4567 @@ +/* ssl_sess.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +#if !defined(WOLFSSL_SSL_SESS_INCLUDED) + #ifndef WOLFSSL_IGNORE_FILE_WARN + #warning ssl_sess.c does not need to be compiled separately from ssl.c + #endif +#else + +#ifndef NO_SESSION_CACHE + + /* basic config gives a cache with 33 sessions, adequate for clients and + embedded servers + + TITAN_SESSION_CACHE allows just over 2 million sessions, for servers + with titanic amounts of memory with long session ID timeouts and high + levels of traffic. + + ENABLE_SESSION_CACHE_ROW_LOCK: Allows row level locking for increased + performance with large session caches + + HUGE_SESSION_CACHE yields 65,791 sessions, for servers under heavy load, + allows over 13,000 new sessions per minute or over 200 new sessions per + second + + BIG_SESSION_CACHE yields 20,027 sessions + + MEDIUM_SESSION_CACHE allows 1055 sessions, adequate for servers that + aren't under heavy load, basically allows 200 new sessions per minute + + SMALL_SESSION_CACHE only stores 6 sessions, good for embedded clients + or systems where the default of is too much RAM. + SessionCache takes about 2K, ClientCache takes about 3Kbytes + + MICRO_SESSION_CACHE only stores 1 session, good for embedded clients + or systems where memory is at a premium. + SessionCache takes about 400 bytes, ClientCache takes 576 bytes + + default SESSION_CACHE stores 33 sessions (no XXX_SESSION_CACHE defined) + SessionCache takes about 13K bytes, ClientCache takes 17K bytes + */ + #if defined(TITAN_SESSION_CACHE) + #define SESSIONS_PER_ROW 31 + #define SESSION_ROWS 64937 + #ifndef ENABLE_SESSION_CACHE_ROW_LOCK + #define ENABLE_SESSION_CACHE_ROW_LOCK + #endif + #elif defined(HUGE_SESSION_CACHE) + #define SESSIONS_PER_ROW 11 + #define SESSION_ROWS 5981 + #elif defined(BIG_SESSION_CACHE) + #define SESSIONS_PER_ROW 7 + #define SESSION_ROWS 2861 + #elif defined(MEDIUM_SESSION_CACHE) + #define SESSIONS_PER_ROW 5 + #define SESSION_ROWS 211 + #elif defined(SMALL_SESSION_CACHE) + #define SESSIONS_PER_ROW 2 + #define SESSION_ROWS 3 + #elif defined(MICRO_SESSION_CACHE) + #define SESSIONS_PER_ROW 1 + #define SESSION_ROWS 1 + #else + #define SESSIONS_PER_ROW 3 + #define SESSION_ROWS 11 + #endif + #define INVALID_SESSION_ROW (-1) + + #ifdef NO_SESSION_CACHE_ROW_LOCK + #undef ENABLE_SESSION_CACHE_ROW_LOCK + #endif + + typedef struct SessionRow { + int nextIdx; /* where to place next one */ + int totalCount; /* sessions ever on this row */ +#ifdef SESSION_CACHE_DYNAMIC_MEM + WOLFSSL_SESSION* Sessions[SESSIONS_PER_ROW]; + void* heap; +#else + WOLFSSL_SESSION Sessions[SESSIONS_PER_ROW]; +#endif + + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + /* not included in import/export */ + wolfSSL_RwLock row_lock; + int lock_valid; + #endif + } SessionRow; + #define SIZEOF_SESSION_ROW (sizeof(WOLFSSL_SESSION) + (sizeof(int) * 2)) + + static WOLFSSL_GLOBAL SessionRow SessionCache[SESSION_ROWS]; + + #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS) + static WOLFSSL_GLOBAL word32 PeakSessions; + #endif + + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + #define SESSION_ROW_RD_LOCK(row) wc_LockRwLock_Rd(&(row)->row_lock) + #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&(row)->row_lock) + #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&(row)->row_lock); + #else + static WOLFSSL_GLOBAL wolfSSL_RwLock session_lock; /* SessionCache lock */ + static WOLFSSL_GLOBAL int session_lock_valid = 0; + #define SESSION_ROW_RD_LOCK(row) wc_LockRwLock_Rd(&session_lock) + #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&session_lock) + #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&session_lock); + #endif + + #if !defined(NO_SESSION_CACHE_REF) && defined(NO_CLIENT_CACHE) + #error ClientCache is required when not using NO_SESSION_CACHE_REF + #endif + + #ifndef NO_CLIENT_CACHE + + #ifndef CLIENT_SESSIONS_MULTIPLIER + #ifdef NO_SESSION_CACHE_REF + #define CLIENT_SESSIONS_MULTIPLIER 1 + #else + /* ClientSession objects are lightweight (compared to + * WOLFSSL_SESSION) so to decrease chance that user will reuse + * the wrong session, increase the ClientCache size. This will + * make the entire ClientCache about the size of one + * WOLFSSL_SESSION object. */ + #define CLIENT_SESSIONS_MULTIPLIER 8 + #endif + #endif + #define CLIENT_SESSIONS_PER_ROW \ + (SESSIONS_PER_ROW * CLIENT_SESSIONS_MULTIPLIER) + #define CLIENT_SESSION_ROWS (SESSION_ROWS * CLIENT_SESSIONS_MULTIPLIER) + + #if CLIENT_SESSIONS_PER_ROW > 65535 + #error CLIENT_SESSIONS_PER_ROW too big + #endif + #if CLIENT_SESSION_ROWS > 65535 + #error CLIENT_SESSION_ROWS too big + #endif + + struct ClientSession { + word16 serverRow; /* SessionCache Row id */ + word16 serverIdx; /* SessionCache Idx (column) */ + word32 sessionIDHash; + }; + #ifndef WOLFSSL_CLIENT_SESSION_DEFINED + typedef struct ClientSession ClientSession; + #define WOLFSSL_CLIENT_SESSION_DEFINED + #endif + + typedef struct ClientRow { + int nextIdx; /* where to place next one */ + int totalCount; /* sessions ever on this row */ + ClientSession Clients[CLIENT_SESSIONS_PER_ROW]; + } ClientRow; + + static WOLFSSL_GLOBAL ClientRow ClientCache[CLIENT_SESSION_ROWS]; + /* Client Cache */ + /* uses session mutex */ + + /* ClientCache mutex */ + static WOLFSSL_GLOBAL wolfSSL_Mutex clisession_mutex + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(clisession_mutex); + #ifndef WOLFSSL_MUTEX_INITIALIZER + static WOLFSSL_GLOBAL int clisession_mutex_valid = 0; + #endif + #endif /* !NO_CLIENT_CACHE */ + + void EvictSessionFromCache(WOLFSSL_SESSION* session) + { +#ifdef HAVE_EX_DATA + int save_ownExData = session->ownExData; + session->ownExData = 1; /* Make sure ex_data access doesn't lead back + * into the cache. */ +#endif +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (session->rem_sess_cb != NULL) { + session->rem_sess_cb(NULL, session); + session->rem_sess_cb = NULL; + } +#endif + ForceZero(session->masterSecret, SECRET_LEN); + XMEMSET(session->sessionID, 0, ID_LEN); + session->sessionIDSz = 0; +#ifdef HAVE_SESSION_TICKET + if (session->ticketLenAlloc > 0) { + XFREE(session->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK); + session->ticket = session->staticTicket; + session->ticketLen = 0; + session->ticketLenAlloc = 0; + } +#endif +#ifdef HAVE_EX_DATA + session->ownExData = save_ownExData; +#endif + +#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if ((session->ticketNonce.data != NULL) && + (session->ticketNonce.data != session->ticketNonce.dataStatic)) + { + XFREE(session->ticketNonce.data, NULL, DYNAMIC_TYPE_SESSION_TICK); + session->ticketNonce.data = NULL; + } +#endif + } + +WOLFSSL_ABI +WOLFSSL_SESSION* wolfSSL_get_session(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_get_session"); + if (ssl) { +#ifdef NO_SESSION_CACHE_REF + return ssl->session; +#else + if (ssl->options.side == WOLFSSL_CLIENT_END) { + /* On the client side we want to return a persistent reference for + * backwards compatibility. */ +#ifndef NO_CLIENT_CACHE + if (ssl->clientSession) { + return (WOLFSSL_SESSION*)ssl->clientSession; + } + else { + /* Try to add a ClientCache entry to associate with the current + * session. Ignore any session cache options. */ + int err; + const byte* id = ssl->session->sessionID; + byte idSz = ssl->session->sessionIDSz; + if (ssl->session->haveAltSessionID) { + id = ssl->session->altSessionID; + idSz = ID_LEN; + } + err = AddSessionToCache(ssl->ctx, ssl->session, id, idSz, + NULL, ssl->session->side, + #ifdef HAVE_SESSION_TICKET + ssl->session->ticketLen > 0, + #else + 0, + #endif + &ssl->clientSession); + if (err == 0) { + return (WOLFSSL_SESSION*)ssl->clientSession; + } + } +#endif + } + else { + return ssl->session; + } +#endif + } + + return NULL; +} + +/* The get1 version requires caller to call SSL_SESSION_free */ +WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl) +{ + WOLFSSL_SESSION* sess = NULL; + WOLFSSL_ENTER("wolfSSL_get1_session"); + if (ssl != NULL) { + sess = ssl->session; + if (sess != NULL) { + /* increase reference count if allocated session */ + if (sess->type == WOLFSSL_SESSION_TYPE_HEAP) { + if (wolfSSL_SESSION_up_ref(sess) != WOLFSSL_SUCCESS) + sess = NULL; + } + } + } + return sess; +} + +/* session is a private struct, return if it is setup or not */ +WOLFSSL_API int wolfSSL_SessionIsSetup(WOLFSSL_SESSION* session) +{ + if (session != NULL) + return session->isSetup; + return 0; +} + +/* + * Sets the session object to use when establishing a TLS/SSL session using + * the ssl object. Therefore, this function must be called before + * wolfSSL_connect. The session object to use can be obtained in a previous + * TLS/SSL connection using wolfSSL_get_session. + * + * This function rejects the session if it has been expired when this function + * is called. Note that this expiration check is wolfSSL specific and differs + * from OpenSSL return code behavior. + * + * By default, wolfSSL_set_session returns WOLFSSL_SUCCESS on successfully + * setting the session, WOLFSSL_FAILURE on failure due to the session cache + * being disabled, or the session has expired. + * + * To match OpenSSL return code behavior when session is expired, define + * OPENSSL_EXTRA and WOLFSSL_ERROR_CODE_OPENSSL. This behavior will return + * WOLFSSL_SUCCESS even when the session is expired and rejected. + */ +WOLFSSL_ABI +int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* session) +{ + WOLFSSL_ENTER("wolfSSL_set_session"); + if (session) + return wolfSSL_SetSession(ssl, session); + + return WOLFSSL_FAILURE; +} + + +#ifndef NO_CLIENT_CACHE + +/* Associate client session with serverID, find existing or store for saving + if newSession flag on, don't reuse existing session + WOLFSSL_SUCCESS on ok */ +int wolfSSL_SetServerID(WOLFSSL* ssl, const byte* id, int len, int newSession) +{ + WOLFSSL_SESSION* session = NULL; + byte idHash[SERVER_ID_LEN]; + + WOLFSSL_ENTER("wolfSSL_SetServerID"); + + if (ssl == NULL || id == NULL || len <= 0) + return BAD_FUNC_ARG; + + if (len > SERVER_ID_LEN) { +#if defined(NO_SHA) && !defined(NO_SHA256) + if (wc_Sha256Hash(id, len, idHash) != 0) + return WOLFSSL_FAILURE; +#else + if (wc_ShaHash(id, (word32)len, idHash) != 0) + return WOLFSSL_FAILURE; +#endif + id = idHash; + len = SERVER_ID_LEN; + } + + if (newSession == 0) { + session = wolfSSL_GetSessionClient(ssl, id, len); + if (session) { + if (wolfSSL_SetSession(ssl, session) != WOLFSSL_SUCCESS) { + #ifdef HAVE_EXT_CACHE + wolfSSL_FreeSession(ssl->ctx, session); + #endif + WOLFSSL_MSG("wolfSSL_SetSession failed"); + session = NULL; + } + } + } + + if (session == NULL) { + WOLFSSL_MSG("Valid ServerID not cached already"); + + ssl->session->idLen = (word16)len; + XMEMCPY(ssl->session->serverID, id, len); + } +#ifdef HAVE_EXT_CACHE + else { + wolfSSL_FreeSession(ssl->ctx, session); + } +#endif + + return WOLFSSL_SUCCESS; +} + +#endif /* !NO_CLIENT_CACHE */ + +/* TODO: Add SESSION_CACHE_DYNAMIC_MEM support for PERSIST_SESSION_CACHE. + * Need a count of current sessions to get an accurate memsize (totalCount is + * not decremented when sessions are removed). + * Need to determine ideal layout for mem/filesave. + * Also need mem/filesave checking to ensure not restoring non DYNAMIC_MEM + * cache. + */ +#if defined(PERSIST_SESSION_CACHE) && !defined(SESSION_CACHE_DYNAMIC_MEM) + +/* for persistence, if changes to layout need to increment and modify + save_session_cache() and restore_session_cache and memory versions too */ +#define WOLFSSL_CACHE_VERSION 2 + +/* Session Cache Header information */ +typedef struct { + int version; /* cache layout version id */ + int rows; /* session rows */ + int columns; /* session columns */ + int sessionSz; /* sizeof WOLFSSL_SESSION */ +} cache_header_t; + +/* current persistence layout is: + + 1) cache_header_t + 2) SessionCache + 3) ClientCache + + update WOLFSSL_CACHE_VERSION if change layout for the following + PERSISTENT_SESSION_CACHE functions +*/ + +/* get how big the the session cache save buffer needs to be */ +int wolfSSL_get_session_cache_memsize(void) +{ + int sz = (int)(sizeof(SessionCache) + sizeof(cache_header_t)); +#ifndef NO_CLIENT_CACHE + sz += (int)(sizeof(ClientCache)); +#endif + return sz; +} + + +/* Persist session cache to memory */ +int wolfSSL_memsave_session_cache(void* mem, int sz) +{ + int i; + cache_header_t cache_header; + SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header)); + + WOLFSSL_ENTER("wolfSSL_memsave_session_cache"); + + if (sz < wolfSSL_get_session_cache_memsize()) { + WOLFSSL_MSG("Memory buffer too small"); + return BUFFER_E; + } + + cache_header.version = WOLFSSL_CACHE_VERSION; + cache_header.rows = SESSION_ROWS; + cache_header.columns = SESSIONS_PER_ROW; + cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION); + XMEMCPY(mem, &cache_header, sizeof(cache_header)); + +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_RD_LOCK(row) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + return BAD_MUTEX_E; + } +#endif + for (i = 0; i < cache_header.rows; ++i) { + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session row cache mutex lock failed"); + return BAD_MUTEX_E; + } + #endif + + XMEMCPY(row++, &SessionCache[i], SIZEOF_SESSION_ROW); + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[i]); + #endif + } +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(row); +#endif + +#ifndef NO_CLIENT_CACHE + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + return BAD_MUTEX_E; + } + XMEMCPY(row, ClientCache, sizeof(ClientCache)); + wc_UnLockMutex(&clisession_mutex); +#endif + + WOLFSSL_LEAVE("wolfSSL_memsave_session_cache", WOLFSSL_SUCCESS); + + return WOLFSSL_SUCCESS; +} + + +/* Restore the persistent session cache from memory */ +int wolfSSL_memrestore_session_cache(const void* mem, int sz) +{ + int i; + cache_header_t cache_header; + SessionRow* row = (SessionRow*)((byte*)mem + sizeof(cache_header)); + + WOLFSSL_ENTER("wolfSSL_memrestore_session_cache"); + + if (sz < wolfSSL_get_session_cache_memsize()) { + WOLFSSL_MSG("Memory buffer too small"); + return BUFFER_E; + } + + XMEMCPY(&cache_header, mem, sizeof(cache_header)); + if (cache_header.version != WOLFSSL_CACHE_VERSION || + cache_header.rows != SESSION_ROWS || + cache_header.columns != SESSIONS_PER_ROW || + cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) { + + WOLFSSL_MSG("Session cache header match failed"); + return CACHE_MATCH_ERROR; + } + +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + return BAD_MUTEX_E; + } +#endif + for (i = 0; i < cache_header.rows; ++i) { + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session row cache mutex lock failed"); + return BAD_MUTEX_E; + } + #endif + + XMEMCPY(&SessionCache[i], row++, SIZEOF_SESSION_ROW); + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[i]); + #endif + } +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[0]); +#endif + +#ifndef NO_CLIENT_CACHE + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + return BAD_MUTEX_E; + } + XMEMCPY(ClientCache, row, sizeof(ClientCache)); + wc_UnLockMutex(&clisession_mutex); +#endif + + WOLFSSL_LEAVE("wolfSSL_memrestore_session_cache", WOLFSSL_SUCCESS); + + return WOLFSSL_SUCCESS; +} + +#if !defined(NO_FILESYSTEM) + +/* Persist session cache to file */ +/* doesn't use memsave because of additional memory use */ +int wolfSSL_save_session_cache(const char *fname) +{ + XFILE file; + int ret; + int rc = WOLFSSL_SUCCESS; + int i; + cache_header_t cache_header; + + WOLFSSL_ENTER("wolfSSL_save_session_cache"); + + file = XFOPEN(fname, "w+b"); + if (file == XBADFILE) { + WOLFSSL_MSG("Couldn't open session cache save file"); + return WOLFSSL_BAD_FILE; + } + cache_header.version = WOLFSSL_CACHE_VERSION; + cache_header.rows = SESSION_ROWS; + cache_header.columns = SESSIONS_PER_ROW; + cache_header.sessionSz = (int)sizeof(WOLFSSL_SESSION); + + /* cache header */ + ret = (int)XFWRITE(&cache_header, sizeof cache_header, 1, file); + if (ret != 1) { + WOLFSSL_MSG("Session cache header file write failed"); + XFCLOSE(file); + return FWRITE_ERROR; + } + +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_RD_LOCK(&SessionCache[0]) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } +#endif + /* session cache */ + for (i = 0; i < cache_header.rows; ++i) { + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_RD_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session row cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } + #endif + + ret = (int)XFWRITE(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file); + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[i]); + #endif + if (ret != 1) { + WOLFSSL_MSG("Session cache member file write failed"); + rc = FWRITE_ERROR; + break; + } + } +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[0]); +#endif + +#ifndef NO_CLIENT_CACHE + /* client cache */ + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } + ret = (int)XFWRITE(ClientCache, sizeof(ClientCache), 1, file); + if (ret != 1) { + WOLFSSL_MSG("Client cache member file write failed"); + rc = FWRITE_ERROR; + } + wc_UnLockMutex(&clisession_mutex); +#endif /* !NO_CLIENT_CACHE */ + + XFCLOSE(file); + WOLFSSL_LEAVE("wolfSSL_save_session_cache", rc); + + return rc; +} + + +/* Restore the persistent session cache from file */ +/* doesn't use memstore because of additional memory use */ +int wolfSSL_restore_session_cache(const char *fname) +{ + XFILE file; + int rc = WOLFSSL_SUCCESS; + int ret; + int i; + cache_header_t cache_header; + + WOLFSSL_ENTER("wolfSSL_restore_session_cache"); + + file = XFOPEN(fname, "rb"); + if (file == XBADFILE) { + WOLFSSL_MSG("Couldn't open session cache save file"); + return WOLFSSL_BAD_FILE; + } + /* cache header */ + ret = (int)XFREAD(&cache_header, sizeof(cache_header), 1, file); + if (ret != 1) { + WOLFSSL_MSG("Session cache header file read failed"); + XFCLOSE(file); + return FREAD_ERROR; + } + if (cache_header.version != WOLFSSL_CACHE_VERSION || + cache_header.rows != SESSION_ROWS || + cache_header.columns != SESSIONS_PER_ROW || + cache_header.sessionSz != (int)sizeof(WOLFSSL_SESSION)) { + + WOLFSSL_MSG("Session cache header match failed"); + XFCLOSE(file); + return CACHE_MATCH_ERROR; + } + +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_WR_LOCK(&SessionCache[0]) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } +#endif + /* session cache */ + for (i = 0; i < cache_header.rows; ++i) { + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session row cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } + #endif + + ret = (int)XFREAD(&SessionCache[i], SIZEOF_SESSION_ROW, 1, file); + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[i]); + #endif + if (ret != 1) { + WOLFSSL_MSG("Session cache member file read failed"); + XMEMSET(SessionCache, 0, sizeof SessionCache); + rc = FREAD_ERROR; + break; + } + } +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[0]); +#endif + +#ifndef NO_CLIENT_CACHE + /* client cache */ + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + XFCLOSE(file); + return BAD_MUTEX_E; + } + ret = (int)XFREAD(ClientCache, sizeof(ClientCache), 1, file); + if (ret != 1) { + WOLFSSL_MSG("Client cache member file read failed"); + XMEMSET(ClientCache, 0, sizeof ClientCache); + rc = FREAD_ERROR; + } + wc_UnLockMutex(&clisession_mutex); +#endif /* !NO_CLIENT_CACHE */ + + XFCLOSE(file); + WOLFSSL_LEAVE("wolfSSL_restore_session_cache", rc); + + return rc; +} + +#endif /* !NO_FILESYSTEM */ +#endif /* PERSIST_SESSION_CACHE && !SESSION_CACHE_DYNAMIC_MEM */ + + +/* on by default if built in but allow user to turn off */ +WOLFSSL_ABI +long wolfSSL_CTX_set_session_cache_mode(WOLFSSL_CTX* ctx, long mode) +{ + WOLFSSL_ENTER("wolfSSL_CTX_set_session_cache_mode"); + + if (ctx == NULL) + return WOLFSSL_FAILURE; + + if (mode == WOLFSSL_SESS_CACHE_OFF) { + ctx->sessionCacheOff = 1; +#ifdef HAVE_EXT_CACHE + ctx->internalCacheOff = 1; + ctx->internalCacheLookupOff = 1; +#endif + } + + if ((mode & WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR) != 0) + ctx->sessionCacheFlushOff = 1; + +#ifdef HAVE_EXT_CACHE + /* WOLFSSL_SESS_CACHE_NO_INTERNAL activates both if's */ + if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE) != 0) + ctx->internalCacheOff = 1; + if ((mode & WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP) != 0) + ctx->internalCacheLookupOff = 1; +#endif + + return WOLFSSL_SUCCESS; +} + +#ifdef OPENSSL_EXTRA +#ifdef HAVE_MAX_FRAGMENT +/* return the max fragment size set when handshake was negotiated */ +unsigned char wolfSSL_SESSION_get_max_fragment_length(WOLFSSL_SESSION* session) +{ + session = ClientSessionToSession(session); + if (session == NULL) { + return 0; + } + + return session->mfl; +} +#endif + + +/* Get the session cache mode for CTX + * + * ctx WOLFSSL_CTX struct to get cache mode from + * + * Returns a bit mask that has the session cache mode */ +long wolfSSL_CTX_get_session_cache_mode(WOLFSSL_CTX* ctx) +{ + long m = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_get_session_cache_mode"); + + if (ctx == NULL) { + return m; + } + + if (ctx->sessionCacheOff != 1) { + m |= WOLFSSL_SESS_CACHE_SERVER; + } + + if (ctx->sessionCacheFlushOff == 1) { + m |= WOLFSSL_SESS_CACHE_NO_AUTO_CLEAR; + } + +#ifdef HAVE_EXT_CACHE + if (ctx->internalCacheOff == 1) { + m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE; + } + if (ctx->internalCacheLookupOff == 1) { + m |= WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP; + } +#endif + + return m; +} +#endif /* OPENSSL_EXTRA */ + +#endif /* !NO_SESSION_CACHE */ + +#ifndef NO_SESSION_CACHE + +WOLFSSL_ABI +void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm) +{ + /* static table now, no flushing needed */ + (void)ctx; + (void)tm; +} + +void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm) +{ + int i, j; + byte id[ID_LEN]; + + (void)ctx; + XMEMSET(id, 0, ID_LEN); + WOLFSSL_ENTER("wolfSSL_flush_sessions"); + for (i = 0; i < SESSION_ROWS; ++i) { + if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { + WOLFSSL_MSG("Session cache mutex lock failed"); + return; + } + for (j = 0; j < SESSIONS_PER_ROW; j++) { +#ifdef SESSION_CACHE_DYNAMIC_MEM + WOLFSSL_SESSION* s = SessionCache[i].Sessions[j]; +#else + WOLFSSL_SESSION* s = &SessionCache[i].Sessions[j]; +#endif + if ( +#ifdef SESSION_CACHE_DYNAMIC_MEM + s != NULL && +#endif + XMEMCMP(s->sessionID, id, ID_LEN) != 0 && + s->bornOn + s->timeout < (word32)tm + ) + { + EvictSessionFromCache(s); +#ifdef SESSION_CACHE_DYNAMIC_MEM + XFREE(s, s->heap, DYNAMIC_TYPE_SESSION); + SessionCache[i].Sessions[j] = NULL; +#endif + } + } + SESSION_ROW_UNLOCK(&SessionCache[i]); + } +} + + +/* set ssl session timeout in seconds */ +WOLFSSL_ABI +int wolfSSL_set_timeout(WOLFSSL* ssl, unsigned int to) +{ + if (ssl == NULL) + return BAD_FUNC_ARG; + + if (to == 0) + to = WOLFSSL_SESSION_TIMEOUT; + ssl->timeout = to; + + return WOLFSSL_SUCCESS; +} + + +/** + * Sets ctx session timeout in seconds. + * The timeout value set here should be reflected in the + * "session ticket lifetime hint" if this API works in the openssl compat-layer. + * Therefore wolfSSL_CTX_set_TicketHint is called internally. + * Arguments: + * - ctx WOLFSSL_CTX object which the timeout is set to + * - to timeout value in second + * Returns: + * WOLFSSL_SUCCESS on success, BAD_FUNC_ARG on failure. + * When WOLFSSL_ERROR_CODE_OPENSSL is defined, returns previous timeout value + * on success, BAD_FUNC_ARG on failure. + */ +WOLFSSL_ABI +int wolfSSL_CTX_set_timeout(WOLFSSL_CTX* ctx, unsigned int to) +{ + #if defined(WOLFSSL_ERROR_CODE_OPENSSL) + word32 prev_timeout = 0; + #endif + + int ret = WOLFSSL_SUCCESS; + (void)ret; + + if (ctx == NULL) + ret = BAD_FUNC_ARG; + + if (ret == WOLFSSL_SUCCESS) { + #if defined(WOLFSSL_ERROR_CODE_OPENSSL) + prev_timeout = ctx->timeout; + #endif + if (to == 0) { + ctx->timeout = WOLFSSL_SESSION_TIMEOUT; + } + else { + ctx->timeout = to; + } + } +#if defined(OPENSSL_EXTRA) && defined(HAVE_SESSION_TICKET) && \ + !defined(NO_WOLFSSL_SERVER) + if (ret == WOLFSSL_SUCCESS) { + if (to == 0) { + ret = wolfSSL_CTX_set_TicketHint(ctx, SESSION_TICKET_HINT_DEFAULT); + } + else { + ret = wolfSSL_CTX_set_TicketHint(ctx, (int)to); + } + } +#endif /* OPENSSL_EXTRA && HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER */ + +#if defined(WOLFSSL_ERROR_CODE_OPENSSL) + if (ret == WOLFSSL_SUCCESS) { + return (int)prev_timeout; + } + else { + return ret; + } +#else + return ret; +#endif /* WOLFSSL_ERROR_CODE_OPENSSL */ +} + + +#ifndef NO_CLIENT_CACHE + +/* Get Session from Client cache based on id/len, return NULL on failure */ +WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len) +{ + WOLFSSL_SESSION* ret = NULL; + word32 row; + int idx; + int count; + int error = 0; + ClientSession* clSess; + + WOLFSSL_ENTER("wolfSSL_GetSessionClient"); + + if (ssl->ctx->sessionCacheOff) { + WOLFSSL_MSG("Session Cache off"); + return NULL; + } + + if (ssl->options.side == WOLFSSL_SERVER_END) + return NULL; + + len = (int)min(SERVER_ID_LEN, (word32)len); + + /* Do not access ssl->ctx->get_sess_cb from here. It is using a different + * set of ID's */ + + row = HashObject(id, (word32)len, &error) % CLIENT_SESSION_ROWS; + if (error != 0) { + WOLFSSL_MSG("Hash session failed"); + return NULL; + } + + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + return NULL; + } + + /* start from most recently used */ + count = (int)min((word32)ClientCache[row].totalCount, CLIENT_SESSIONS_PER_ROW); + idx = ClientCache[row].nextIdx - 1; + if (idx < 0 || idx >= CLIENT_SESSIONS_PER_ROW) { + /* if back to front, the previous was end */ + idx = CLIENT_SESSIONS_PER_ROW - 1; + } + clSess = ClientCache[row].Clients; + + for (; count > 0; --count) { + WOLFSSL_SESSION* current; + SessionRow* sessRow; + + if (clSess[idx].serverRow >= SESSION_ROWS) { + WOLFSSL_MSG("Client cache serverRow invalid"); + break; + } + + /* lock row */ + sessRow = &SessionCache[clSess[idx].serverRow]; + if (SESSION_ROW_RD_LOCK(sessRow) != 0) { + WOLFSSL_MSG("Session cache row lock failure"); + break; + } + +#ifdef SESSION_CACHE_DYNAMIC_MEM + current = sessRow->Sessions[clSess[idx].serverIdx]; +#else + current = &sessRow->Sessions[clSess[idx].serverIdx]; +#endif + if (current && XMEMCMP(current->serverID, id, len) == 0) { + WOLFSSL_MSG("Found a serverid match for client"); + if (LowResTimer() < (current->bornOn + current->timeout)) { + WOLFSSL_MSG("Session valid"); + ret = current; + SESSION_ROW_UNLOCK(sessRow); + break; + } else { + WOLFSSL_MSG("Session timed out"); /* could have more for id */ + } + } else { + WOLFSSL_MSG("ServerID not a match from client table"); + } + SESSION_ROW_UNLOCK(sessRow); + + idx = idx > 0 ? idx - 1 : CLIENT_SESSIONS_PER_ROW - 1; + } + + wc_UnLockMutex(&clisession_mutex); + + return ret; +} + +#endif /* !NO_CLIENT_CACHE */ + +static int SslSessionCacheOff(const WOLFSSL* ssl, + const WOLFSSL_SESSION* session) +{ + (void)session; + return ssl->options.sessionCacheOff + #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_FORCE_CACHE_ON_TICKET) + && session->ticketLen == 0 + #endif + ; +} + +#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) +/** + * SessionTicketNoncePrealloc() - prealloc a buffer for ticket nonces + * @output: [in] pointer to WOLFSSL_SESSION object that will soon be a + * destination of a session duplication + * @buf: [out] address of the preallocated buf + * @len: [out] len of the preallocated buf + * + * prealloc a buffer that will likely suffice to contain a ticket nonce. It's + * used when copying session under lock, when syscalls need to be avoided. If + * output already has a dynamic buffer, it's reused. + */ +static int SessionTicketNoncePrealloc(byte** buf, byte* len, void *heap) +{ + (void)heap; + + *buf = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_NONCE_LEN, heap, + DYNAMIC_TYPE_SESSION_TICK); + if (*buf == NULL) { + WOLFSSL_MSG("Failed to preallocate ticket nonce buffer"); + *len = 0; + return 1; + } + + *len = PREALLOC_SESSION_TICKET_NONCE_LEN; + return 0; +} +#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ + +static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, + WOLFSSL_SESSION* output, int avoidSysCalls, byte* ticketNonceBuf, + byte* ticketNonceLen, byte* preallocUsed); + +void TlsSessionCacheUnlockRow(word32 row) +{ + SessionRow* sessRow; + + sessRow = &SessionCache[row]; + (void)sessRow; + SESSION_ROW_UNLOCK(sessRow); +} + +/* Don't use this function directly. Use TlsSessionCacheGetAndRdLock and + * TlsSessionCacheGetAndWrLock to fully utilize compiler const support. */ +static int TlsSessionCacheGetAndLock(const byte *id, + const WOLFSSL_SESSION **sess, word32 *lockedRow, byte readOnly, byte side) +{ + SessionRow *sessRow; + const WOLFSSL_SESSION *s; + word32 row; + int count; + int error; + int idx; + + *sess = NULL; + row = HashObject(id, ID_LEN, &error) % SESSION_ROWS; + if (error != 0) + return error; + sessRow = &SessionCache[row]; + if (readOnly) + error = SESSION_ROW_RD_LOCK(sessRow); + else + error = SESSION_ROW_WR_LOCK(sessRow); + if (error != 0) + return FATAL_ERROR; + + /* start from most recently used */ + count = (int)min((word32)sessRow->totalCount, SESSIONS_PER_ROW); + idx = sessRow->nextIdx - 1; + if (idx < 0 || idx >= SESSIONS_PER_ROW) { + idx = SESSIONS_PER_ROW - 1; /* if back to front, the previous was end */ + } + for (; count > 0; --count) { +#ifdef SESSION_CACHE_DYNAMIC_MEM + s = sessRow->Sessions[idx]; +#else + s = &sessRow->Sessions[idx]; +#endif + if (s && XMEMCMP(s->sessionID, id, ID_LEN) == 0 && s->side == side) { + *sess = s; + break; + } + idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1; + } + if (*sess == NULL) { + SESSION_ROW_UNLOCK(sessRow); + } + else { + *lockedRow = row; + } + + return 0; +} + +static int CheckSessionMatch(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess) +{ + if (ssl == NULL || sess == NULL) + return 0; +#ifdef OPENSSL_EXTRA + if (ssl->sessionCtxSz > 0 && (ssl->sessionCtxSz != sess->sessionCtxSz || + XMEMCMP(ssl->sessionCtx, sess->sessionCtx, sess->sessionCtxSz) != 0)) + return 0; +#endif +#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) + if (IsAtLeastTLSv1_3(ssl->version) != IsAtLeastTLSv1_3(sess->version)) + return 0; +#endif + return 1; +} + +int TlsSessionCacheGetAndRdLock(const byte *id, const WOLFSSL_SESSION **sess, + word32 *lockedRow, byte side) +{ + return TlsSessionCacheGetAndLock(id, sess, lockedRow, 1, side); +} + +int TlsSessionCacheGetAndWrLock(const byte *id, WOLFSSL_SESSION **sess, + word32 *lockedRow, byte side) +{ + return TlsSessionCacheGetAndLock(id, (const WOLFSSL_SESSION**)sess, + lockedRow, 0, side); +} + +int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) +{ + const WOLFSSL_SESSION* sess = NULL; + const byte* id = NULL; + word32 row; + int error = 0; +#ifdef HAVE_SESSION_TICKET +#ifndef WOLFSSL_SMALL_STACK + byte tmpTicket[PREALLOC_SESSION_TICKET_LEN]; +#else + byte* tmpTicket = NULL; +#endif +#ifdef WOLFSSL_TLS13 + byte *preallocNonce = NULL; + byte preallocNonceLen = 0; + byte preallocNonceUsed = 0; +#endif /* WOLFSSL_TLS13 */ + byte tmpBufSet = 0; +#endif +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + WOLFSSL_X509* peer = NULL; +#endif + byte bogusID[ID_LEN]; + byte bogusIDSz = 0; + + WOLFSSL_ENTER("wolfSSL_GetSessionFromCache"); + + if (output == NULL) { + WOLFSSL_MSG("NULL output"); + return WOLFSSL_FAILURE; + } + + if (SslSessionCacheOff(ssl, ssl->session)) + return WOLFSSL_FAILURE; + + if (ssl->options.haveSessionId == 0 && !ssl->session->haveAltSessionID) + return WOLFSSL_FAILURE; + +#ifdef HAVE_SESSION_TICKET + if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.useTicket == 1) + return WOLFSSL_FAILURE; +#endif + + XMEMSET(bogusID, 0, sizeof(bogusID)); + if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL + && !ssl->session->haveAltSessionID) + id = ssl->arrays->sessionID; + else if (ssl->session->haveAltSessionID) { + id = ssl->session->altSessionID; + /* We want to restore the bogus ID for TLS compatibility */ + if (output == ssl->session) { + XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN); + bogusIDSz = ssl->session->sessionIDSz; + } + } + else + id = ssl->session->sessionID; + + +#ifdef HAVE_EXT_CACHE + if (ssl->ctx->get_sess_cb != NULL) { + int copy = 0; + int found = 0; + WOLFSSL_SESSION* extSess; + /* Attempt to retrieve the session from the external cache. */ + WOLFSSL_MSG("Calling external session cache"); + extSess = ssl->ctx->get_sess_cb(ssl, (byte*)id, ID_LEN, ©); + if ((extSess != NULL) + && CheckSessionMatch(ssl, extSess) + ) { + WOLFSSL_MSG("Session found in external cache"); + found = 1; + + error = wolfSSL_DupSession(extSess, output, 0); +#ifdef HAVE_EX_DATA + extSess->ownExData = 1; + output->ownExData = 0; +#endif + /* We want to restore the bogus ID for TLS compatibility */ + if (ssl->session->haveAltSessionID && + output == ssl->session) { + XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN); + ssl->session->sessionIDSz = bogusIDSz; + } + } + /* If copy not set then free immediately */ + if (extSess != NULL && !copy) + wolfSSL_FreeSession(ssl->ctx, extSess); + if (found) + return error; + WOLFSSL_MSG("Session not found in external cache"); + } + + if (ssl->options.internalCacheLookupOff) { + WOLFSSL_MSG("Internal cache lookup turned off"); + return WOLFSSL_FAILURE; + } +#endif + +#ifdef HAVE_SESSION_TICKET + if (output->ticket == NULL || + output->ticketLenAlloc < PREALLOC_SESSION_TICKET_LEN) { +#ifdef WOLFSSL_SMALL_STACK + tmpTicket = (byte*)XMALLOC(PREALLOC_SESSION_TICKET_LEN, output->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (tmpTicket == NULL) { + WOLFSSL_MSG("tmpTicket malloc failed"); + return WOLFSSL_FAILURE; + } +#endif + if (output->ticketLenAlloc) + XFREE(output->ticket, output->heap, DYNAMIC_TYPE_SESSION_TICK); + output->ticket = tmpTicket; /* cppcheck-suppress autoVariables + */ + output->ticketLenAlloc = PREALLOC_SESSION_TICKET_LEN; + output->ticketLen = 0; + tmpBufSet = 1; + } +#endif + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (output->peer != NULL) { + wolfSSL_X509_free(output->peer); + output->peer = NULL; + } +#endif + +#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (output->ticketNonce.data != output->ticketNonce.dataStatic) { + XFREE(output->ticketNonce.data, output->heap, + DYNAMIC_TYPE_SESSION_TICK); + output->ticketNonce.data = output->ticketNonce.dataStatic; + output->ticketNonce.len = 0; + } + error = SessionTicketNoncePrealloc(&preallocNonce, &preallocNonceLen, + output->heap); + if (error != 0) { + if (tmpBufSet) { + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + } +#ifdef WOLFSSL_SMALL_STACK + if (tmpTicket != NULL) + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return WOLFSSL_FAILURE; + } +#endif /* WOLFSSL_TLS13 && HAVE_SESSION_TICKET*/ + + /* init to avoid clang static analyzer false positive */ + row = 0; + error = TlsSessionCacheGetAndRdLock(id, &sess, &row, + (byte)ssl->options.side); + error = (error == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + if (error != WOLFSSL_SUCCESS || sess == NULL) { + WOLFSSL_MSG("Get Session from cache failed"); + error = WOLFSSL_FAILURE; +#ifdef HAVE_SESSION_TICKET + if (tmpBufSet) { + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + } +#ifdef WOLFSSL_TLS13 + if (preallocNonce != NULL) { + XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); + preallocNonce = NULL; + } +#endif /* WOLFSSL_TLS13 */ +#ifdef WOLFSSL_SMALL_STACK + if (tmpTicket != NULL) { + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); + tmpTicket = NULL; + } +#endif +#endif + } + else { + if (!CheckSessionMatch(ssl, sess)) { + WOLFSSL_MSG("Invalid session: can't be used in this context"); + TlsSessionCacheUnlockRow(row); + error = WOLFSSL_FAILURE; + } + else if (LowResTimer() >= (sess->bornOn + sess->timeout)) { + WOLFSSL_SESSION* wrSess = NULL; + WOLFSSL_MSG("Invalid session: timed out"); + sess = NULL; + TlsSessionCacheUnlockRow(row); + /* Attempt to get a write lock */ + error = TlsSessionCacheGetAndWrLock(id, &wrSess, &row, + (byte)ssl->options.side); + if (error == 0 && wrSess != NULL) { + EvictSessionFromCache(wrSess); + TlsSessionCacheUnlockRow(row); + } + error = WOLFSSL_FAILURE; + } + } + + /* mollify confused cppcheck nullPointer warning. */ + if (sess == NULL) + error = WOLFSSL_FAILURE; + + if (error == WOLFSSL_SUCCESS) { +#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) + error = wolfSSL_DupSessionEx(sess, output, 1, + preallocNonce, &preallocNonceLen, &preallocNonceUsed); +#else + error = wolfSSL_DupSession(sess, output, 1); +#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 */ +#ifdef HAVE_EX_DATA + output->ownExData = !sess->ownExData; /* Session may own ex_data */ +#endif + TlsSessionCacheUnlockRow(row); + } + + /* We want to restore the bogus ID for TLS compatibility */ + if (ssl->session->haveAltSessionID && + output == ssl->session) { + XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN); + ssl->session->sessionIDSz = bogusIDSz; + } + +#ifdef HAVE_SESSION_TICKET + if (tmpBufSet) { + if (error == WOLFSSL_SUCCESS) { + if (output->ticketLen > SESSION_TICKET_LEN) { + output->ticket = (byte*)XMALLOC(output->ticketLen, output->heap, + DYNAMIC_TYPE_SESSION_TICK); + if (output->ticket == NULL) { + error = WOLFSSL_FAILURE; + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + output->ticketLen = 0; + } + } + else { + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + } + } + else { + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + output->ticketLen = 0; + } + if (error == WOLFSSL_SUCCESS) { + XMEMCPY(output->ticket, tmpTicket, output->ticketLen); + } + } +#ifdef WOLFSSL_SMALL_STACK + if (tmpTicket != NULL) + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (error == WOLFSSL_SUCCESS && preallocNonceUsed) { + if (preallocNonceLen < PREALLOC_SESSION_TICKET_NONCE_LEN) { + /* buffer bigger than needed */ +#ifndef XREALLOC + output->ticketNonce.data = (byte*)XMALLOC(preallocNonceLen, + output->heap, DYNAMIC_TYPE_SESSION_TICK); + if (output->ticketNonce.data != NULL) + XMEMCPY(output->ticketNonce.data, preallocNonce, + preallocNonceLen); + XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); + preallocNonce = NULL; +#else + output->ticketNonce.data = (byte*)XREALLOC(preallocNonce, + preallocNonceLen, output->heap, DYNAMIC_TYPE_SESSION_TICK); + if (output->ticketNonce.data != NULL) { + /* don't free the reallocated pointer */ + preallocNonce = NULL; + } +#endif /* !XREALLOC */ + if (output->ticketNonce.data == NULL) { + output->ticketNonce.data = output->ticketNonce.dataStatic; + output->ticketNonce.len = 0; + error = WOLFSSL_FAILURE; + /* preallocNonce will be free'd after the if */ + } + } + else { + output->ticketNonce.data = preallocNonce; + output->ticketNonce.len = preallocNonceLen; + preallocNonce = NULL; + } + } + if (preallocNonce != NULL) + XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ + +#endif + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (peer != NULL) { + wolfSSL_X509_free(peer); + } +#endif + + return error; +} + +WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret, + byte restoreSessionCerts) +{ + WOLFSSL_SESSION* ret = NULL; + + (void)restoreSessionCerts; /* Kept for compatibility */ + + if (wolfSSL_GetSessionFromCache(ssl, ssl->session) == WOLFSSL_SUCCESS) { + ret = ssl->session; + } + else { + WOLFSSL_MSG("wolfSSL_GetSessionFromCache did not return a session"); + } + + if (ret != NULL && masterSecret != NULL) + XMEMCPY(masterSecret, ret->masterSecret, SECRET_LEN); + + return ret; +} + +int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session) +{ + SessionRow* sessRow = NULL; + int ret = WOLFSSL_SUCCESS; + + session = ClientSessionToSession(session); + + if (ssl == NULL || session == NULL || !session->isSetup) { + WOLFSSL_MSG("ssl or session NULL or not set up"); + return WOLFSSL_FAILURE; + } + + /* We need to lock the session as the first step if its in the cache */ + if (session->type == WOLFSSL_SESSION_TYPE_CACHE) { + if (session->cacheRow < SESSION_ROWS) { + sessRow = &SessionCache[session->cacheRow]; + if (SESSION_ROW_RD_LOCK(sessRow) != 0) { + WOLFSSL_MSG("Session row lock failed"); + return WOLFSSL_FAILURE; + } + } + } + + if (ret == WOLFSSL_SUCCESS && ssl->options.side != WOLFSSL_NEITHER_END && + (byte)ssl->options.side != session->side) { + WOLFSSL_MSG("Setting session for wrong role"); + ret = WOLFSSL_FAILURE; + } + + if (ret == WOLFSSL_SUCCESS) { + if (ssl->session == session) { + WOLFSSL_MSG("ssl->session and session same"); + } + else if (session->type != WOLFSSL_SESSION_TYPE_CACHE) { + if (wolfSSL_SESSION_up_ref(session) == WOLFSSL_SUCCESS) { + wolfSSL_FreeSession(ssl->ctx, ssl->session); + ssl->session = session; + } + else + ret = WOLFSSL_FAILURE; + } + else { + ret = wolfSSL_DupSession(session, ssl->session, 0); + if (ret != WOLFSSL_SUCCESS) + WOLFSSL_MSG("Session duplicate failed"); + } + } + + /* Let's copy over the altSessionID for local cache purposes */ + if (ret == WOLFSSL_SUCCESS && session->haveAltSessionID && + ssl->session != session) { + ssl->session->haveAltSessionID = 1; + XMEMCPY(ssl->session->altSessionID, session->altSessionID, ID_LEN); + } + + if (sessRow != NULL) { + SESSION_ROW_UNLOCK(sessRow); + sessRow = NULL; + } + + /* Note: the `session` variable cannot be used below, since the row is + * un-locked */ + + if (ret != WOLFSSL_SUCCESS) + return ret; + +#ifdef WOLFSSL_SESSION_ID_CTX + /* check for application context id */ + if (ssl->sessionCtxSz > 0) { + if (XMEMCMP(ssl->sessionCtx, ssl->session->sessionCtx, + ssl->sessionCtxSz)) { + /* context id did not match! */ + WOLFSSL_MSG("Session context did not match"); + return WOLFSSL_FAILURE; + } + } +#endif /* WOLFSSL_SESSION_ID_CTX */ + + if (LowResTimer() >= (ssl->session->bornOn + ssl->session->timeout)) { +#if !defined(OPENSSL_EXTRA) || !defined(WOLFSSL_ERROR_CODE_OPENSSL) + return WOLFSSL_FAILURE; /* session timed out */ +#else /* defined(OPENSSL_EXTRA) && defined(WOLFSSL_ERROR_CODE_OPENSSL) */ + WOLFSSL_MSG("Session is expired but return success for " + "OpenSSL compatibility"); +#endif + } + ssl->options.resuming = 1; + ssl->options.haveEMS = ssl->session->haveEMS; + +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + ssl->version = ssl->session->version; + if (IsAtLeastTLSv1_3(ssl->version)) + ssl->options.tls1_3 = 1; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + ssl->options.cipherSuite0 = ssl->session->cipherSuite0; + ssl->options.cipherSuite = ssl->session->cipherSuite; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + ssl->peerVerifyRet = (unsigned long)ssl->session->peerVerifyRet; +#endif + + return WOLFSSL_SUCCESS; +} + + +#ifdef WOLFSSL_SESSION_STATS +static int get_locked_session_stats(word32* active, word32* total, + word32* peak); +#endif + +#ifndef NO_CLIENT_CACHE +ClientSession* AddSessionToClientCache(int side, int row, int idx, + byte* serverID, word16 idLen, const byte* sessionID, word16 useTicket) +{ + int error = -1; + word32 clientRow = 0, clientIdx = 0; + ClientSession* ret = NULL; + + (void)useTicket; + if (side == WOLFSSL_CLIENT_END + && row != INVALID_SESSION_ROW + && (idLen +#ifdef HAVE_SESSION_TICKET + || useTicket == 1 +#endif + || serverID != NULL + )) { + + WOLFSSL_MSG("Trying to add client cache entry"); + + if (idLen) { + clientRow = HashObject(serverID, + idLen, &error) % CLIENT_SESSION_ROWS; + } + else if (serverID != NULL) { + clientRow = HashObject(sessionID, + ID_LEN, &error) % CLIENT_SESSION_ROWS; + } + else { + error = -1; + } + if (error == 0 && wc_LockMutex(&clisession_mutex) == 0) { + clientIdx = (word32)ClientCache[clientRow].nextIdx; + if (clientIdx < CLIENT_SESSIONS_PER_ROW) { + ClientCache[clientRow].Clients[clientIdx].serverRow = + (word16)row; + ClientCache[clientRow].Clients[clientIdx].serverIdx = + (word16)idx; + if (sessionID != NULL) { + word32 sessionIDHash = HashObject(sessionID, ID_LEN, + &error); + if (error == 0) { + ClientCache[clientRow].Clients[clientIdx].sessionIDHash + = sessionIDHash; + } + } + } + else { + error = -1; + ClientCache[clientRow].nextIdx = 0; /* reset index as safety */ + WOLFSSL_MSG("Invalid client cache index! " + "Possible corrupted memory"); + } + if (error == 0) { + WOLFSSL_MSG("Adding client cache entry"); + + ret = &ClientCache[clientRow].Clients[clientIdx]; + + if (ClientCache[clientRow].totalCount < CLIENT_SESSIONS_PER_ROW) + ClientCache[clientRow].totalCount++; + ClientCache[clientRow].nextIdx++; + ClientCache[clientRow].nextIdx %= CLIENT_SESSIONS_PER_ROW; + } + + wc_UnLockMutex(&clisession_mutex); + } + else { + WOLFSSL_MSG("Hash session or lock failed"); + } + } + else { + WOLFSSL_MSG("Skipping client cache"); + } + + return ret; +} +#endif /* !NO_CLIENT_CACHE */ + +/** + * For backwards compatibility, this API needs to be used in *ALL* functions + * that access the WOLFSSL_SESSION members directly. + * + * This API checks if the passed in session is actually a ClientSession object + * and returns the matching session cache object. Otherwise just return the + * input. ClientSession objects only occur in the ClientCache. They are not + * allocated anywhere else. + */ +WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) +{ + WOLFSSL_ENTER("ClientSessionToSession"); +#ifdef NO_SESSION_CACHE_REF + return (WOLFSSL_SESSION*)session; +#else +#ifndef NO_CLIENT_CACHE + if (session == NULL) + return NULL; + /* Check if session points into ClientCache */ + if ((byte*)session >= (byte*)ClientCache && + /* Cast to byte* to make pointer arithmetic work per byte */ + (byte*)session < ((byte*)ClientCache) + sizeof(ClientCache)) { + ClientSession* clientSession = (ClientSession*)session; + SessionRow* sessRow = NULL; + WOLFSSL_SESSION* cacheSession = NULL; + word32 sessionIDHash = 0; + int error = 0; + session = NULL; /* Default to NULL for failure case */ + if (wc_LockMutex(&clisession_mutex) != 0) { + WOLFSSL_MSG("Client cache mutex lock failed"); + return NULL; + } + if (clientSession->serverRow >= SESSION_ROWS || + clientSession->serverIdx >= SESSIONS_PER_ROW) { + WOLFSSL_MSG("Client cache serverRow or serverIdx invalid"); + error = -1; + } + /* Prevent memory access before clientSession->serverRow and + * clientSession->serverIdx are sanitized. */ + XFENCE(); + if (error == 0) { + /* Lock row */ + sessRow = &SessionCache[clientSession->serverRow]; + error = SESSION_ROW_RD_LOCK(sessRow); + if (error != 0) { + WOLFSSL_MSG("Session cache row lock failure"); + sessRow = NULL; + } + } + if (error == 0) { +#ifdef SESSION_CACHE_DYNAMIC_MEM + cacheSession = sessRow->Sessions[clientSession->serverIdx]; +#else + cacheSession = &sessRow->Sessions[clientSession->serverIdx]; +#endif + if (cacheSession && cacheSession->sessionIDSz == 0) { + cacheSession = NULL; + WOLFSSL_MSG("Session cache entry not set"); + error = -1; + } + } + if (error == 0) { + /* Calculate the hash of the session ID */ + sessionIDHash = HashObject(cacheSession->sessionID, ID_LEN, + &error); + } + if (error == 0) { + /* Check the session ID hash matches */ + error = clientSession->sessionIDHash != sessionIDHash; + if (error != 0) + WOLFSSL_MSG("session ID hashes don't match"); + } + if (error == 0) { + /* Hashes match */ + session = cacheSession; + WOLFSSL_MSG("Found session cache matching client session object"); + } + if (sessRow != NULL) { + SESSION_ROW_UNLOCK(sessRow); + } + wc_UnLockMutex(&clisession_mutex); + return (WOLFSSL_SESSION*)session; + } + else { + /* Plain WOLFSSL_SESSION object */ + return (WOLFSSL_SESSION*)session; + } +#else + return (WOLFSSL_SESSION*)session; +#endif +#endif +} + +int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, + const byte* id, byte idSz, int* sessionIndex, int side, + word16 useTicket, ClientSession** clientCacheEntry) +{ + WOLFSSL_SESSION* cacheSession = NULL; + SessionRow* sessRow = NULL; + word32 idx = 0; +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + WOLFSSL_X509* cachePeer = NULL; + WOLFSSL_X509* addPeer = NULL; +#endif +#ifdef HAVE_SESSION_TICKET + byte* cacheTicBuff = NULL; + byte ticBuffUsed = 0; + byte* ticBuff = NULL; + int ticLen = 0; +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + byte *preallocNonce = NULL; + byte preallocNonceLen = 0; + byte preallocNonceUsed = 0; + byte *toFree = NULL; +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC */ +#endif /* HAVE_SESSION_TICKET */ + int ret = 0; + int row; + int i; + int overwrite = 0; + (void)ctx; + (void)sessionIndex; + (void)useTicket; + (void)clientCacheEntry; + + WOLFSSL_ENTER("AddSessionToCache"); + + if (idSz == 0) { + WOLFSSL_MSG("AddSessionToCache idSz == 0"); + return BAD_FUNC_ARG; + } + + addSession = ClientSessionToSession(addSession); + if (addSession == NULL) { + WOLFSSL_MSG("AddSessionToCache is NULL"); + return MEMORY_E; + } + +#ifdef HAVE_SESSION_TICKET + ticLen = addSession->ticketLen; + /* Alloc Memory here to avoid syscalls during lock */ + if (ticLen > SESSION_TICKET_LEN) { + ticBuff = (byte*)XMALLOC(ticLen, NULL, + DYNAMIC_TYPE_SESSION_TICK); + if (ticBuff == NULL) { + return MEMORY_E; + } + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (addSession->ticketNonce.data != addSession->ticketNonce.dataStatic) { + /* use the AddSession->heap even if the buffer maybe saved in + * CachedSession objects. CachedSession heap and AddSession heap should + * be the same */ + preallocNonce = (byte*)XMALLOC(addSession->ticketNonce.len, + addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + if (preallocNonce == NULL) { + if (ticBuff != NULL) + XFREE(ticBuff, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + return MEMORY_E; + } + preallocNonceLen = addSession->ticketNonce.len; + } +#endif /* WOLFSSL_TLS13 && WOLFSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */ +#endif /* HAVE_SESSION_TICKET */ + + /* Find a position for the new session in cache and use that */ + /* Use the session object in the cache for external cache if required */ + row = (int)(HashObject(id, ID_LEN, &ret) % SESSION_ROWS); + if (ret != 0) { + WOLFSSL_MSG("Hash session failed"); + #ifdef HAVE_SESSION_TICKET + XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + #endif + #endif + return ret; + } + + sessRow = &SessionCache[row]; + if (SESSION_ROW_WR_LOCK(sessRow) != 0) { + #ifdef HAVE_SESSION_TICKET + XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + #endif + #endif + WOLFSSL_MSG("Session row lock failed"); + return BAD_MUTEX_E; + } + + for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { +#ifdef SESSION_CACHE_DYNAMIC_MEM + cacheSession = sessRow->Sessions[i]; +#else + cacheSession = &sessRow->Sessions[i]; +#endif + if (cacheSession && XMEMCMP(id, + cacheSession->sessionID, ID_LEN) == 0 && + cacheSession->side == side) { + WOLFSSL_MSG("Session already exists. Overwriting."); + overwrite = 1; + idx = (word32)i; + break; + } + } + + if (!overwrite) + idx = (word32)sessRow->nextIdx; +#ifdef SESSION_INDEX + if (sessionIndex != NULL) + *sessionIndex = (row << SESSIDX_ROW_SHIFT) | idx; +#endif + +#ifdef SESSION_CACHE_DYNAMIC_MEM + cacheSession = sessRow->Sessions[idx]; + if (cacheSession == NULL) { + cacheSession = (WOLFSSL_SESSION*) XMALLOC(sizeof(WOLFSSL_SESSION), + sessRow->heap, DYNAMIC_TYPE_SESSION); + if (cacheSession == NULL) { + #ifdef HAVE_SESSION_TICKET + XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + #endif + #endif + SESSION_ROW_UNLOCK(sessRow); + return MEMORY_E; + } + XMEMSET(cacheSession, 0, sizeof(WOLFSSL_SESSION)); + sessRow->Sessions[idx] = cacheSession; + } +#else + cacheSession = &sessRow->Sessions[idx]; +#endif + +#ifdef HAVE_EX_DATA + if (overwrite) { + /* Figure out who owns the ex_data */ + if (cacheSession->ownExData) { + /* Prioritize cacheSession copy */ + XMEMCPY(&addSession->ex_data, &cacheSession->ex_data, + sizeof(WOLFSSL_CRYPTO_EX_DATA)); + } + /* else will be copied in wolfSSL_DupSession call */ + } + else if (cacheSession->ownExData) { + crypto_ex_cb_free_data(cacheSession, crypto_ex_cb_ctx_session, + &cacheSession->ex_data); + cacheSession->ownExData = 0; + } +#endif + + if (!overwrite) + EvictSessionFromCache(cacheSession); + + cacheSession->type = WOLFSSL_SESSION_TYPE_CACHE; + cacheSession->cacheRow = row; + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + /* Save the peer field to free after unlocking the row */ + if (cacheSession->peer != NULL) + cachePeer = cacheSession->peer; + cacheSession->peer = NULL; +#endif +#ifdef HAVE_SESSION_TICKET + /* If we can reuse the existing buffer in cacheSession then we won't touch + * ticBuff at all making it a very cheap malloc/free. The page on a modern + * OS will most likely not even be allocated to the process. */ + if (ticBuff != NULL && cacheSession->ticketLenAlloc < ticLen) { + /* Save pointer only if separately allocated */ + if (cacheSession->ticket != cacheSession->staticTicket) + cacheTicBuff = cacheSession->ticket; + ticBuffUsed = 1; + cacheSession->ticket = ticBuff; + cacheSession->ticketLenAlloc = (word16) ticLen; + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + /* cache entry never used */ + if (cacheSession->ticketNonce.data == NULL) + cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic; + + if (cacheSession->ticketNonce.data != + cacheSession->ticketNonce.dataStatic) { + toFree = cacheSession->ticketNonce.data; + cacheSession->ticketNonce.data = cacheSession->ticketNonce.dataStatic; + cacheSession->ticketNonce.len = 0; + } +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ +#endif +#ifdef SESSION_CERTS + if (overwrite && + addSession->chain.count == 0 && + cacheSession->chain.count > 0) { + /* Copy in the certs from the session */ + addSession->chain.count = cacheSession->chain.count; + XMEMCPY(addSession->chain.certs, cacheSession->chain.certs, + sizeof(x509_buffer) * cacheSession->chain.count); + } +#endif /* SESSION_CERTS */ +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + /* Don't copy the peer cert into cache */ + addPeer = addSession->peer; + addSession->peer = NULL; +#endif + cacheSession->heap = NULL; + /* Copy data into the cache object */ +#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + ret = wolfSSL_DupSessionEx(addSession, cacheSession, 1, preallocNonce, + &preallocNonceLen, &preallocNonceUsed) == WOLFSSL_FAILURE; +#else + ret = wolfSSL_DupSession(addSession, cacheSession, 1) == WOLFSSL_FAILURE; +#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC + && FIPS_VERSION_GE(5,3)*/ +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + addSession->peer = addPeer; +#endif + + if (ret == 0) { + if (!overwrite) { + /* Increment the totalCount and the nextIdx */ + if (sessRow->totalCount < SESSIONS_PER_ROW) + sessRow->totalCount++; + sessRow->nextIdx = (sessRow->nextIdx + 1) % SESSIONS_PER_ROW; + } + if (id != addSession->sessionID) { + /* ssl->session->sessionID may contain the bogus ID or we want the + * ID from the arrays object */ + XMEMCPY(cacheSession->sessionID, id, ID_LEN); + cacheSession->sessionIDSz = ID_LEN; + } +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (ctx->rem_sess_cb != NULL) + cacheSession->rem_sess_cb = ctx->rem_sess_cb; +#endif +#ifdef HAVE_EX_DATA + /* The session in cache now owns the ex_data */ + addSession->ownExData = 0; + cacheSession->ownExData = 1; +#endif +#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (preallocNonce != NULL && preallocNonceUsed) { + cacheSession->ticketNonce.data = preallocNonce; + cacheSession->ticketNonce.len = preallocNonceLen; + preallocNonce = NULL; + preallocNonceLen = 0; + } +#endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC + * && FIPS_VERSION_GE(5,3)*/ + } +#ifdef HAVE_SESSION_TICKET + else if (ticBuffUsed) { + /* Error occurred. Need to clean up the ticket buffer. */ + cacheSession->ticket = cacheSession->staticTicket; + cacheSession->ticketLenAlloc = 0; + cacheSession->ticketLen = 0; + } +#endif + SESSION_ROW_UNLOCK(sessRow); + cacheSession = NULL; /* Can't access after unlocked */ + +#ifndef NO_CLIENT_CACHE + if (ret == 0 && clientCacheEntry != NULL) { + ClientSession* clientCache = AddSessionToClientCache(side, row, (int)idx, + addSession->serverID, addSession->idLen, id, useTicket); + if (clientCache != NULL) + *clientCacheEntry = clientCache; + } +#endif + +#ifdef HAVE_SESSION_TICKET + if (ticBuff != NULL && !ticBuffUsed) + XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); + XFREE(cacheTicBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(toFree, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ +#endif + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (cachePeer != NULL) { + wolfSSL_X509_free(cachePeer); + cachePeer = NULL; /* Make sure not use after this point */ + } +#endif + + return ret; +} + +void AddSession(WOLFSSL* ssl) +{ + int error = 0; + const byte* id = NULL; + byte idSz = 0; + WOLFSSL_SESSION* session = ssl->session; + + (void)error; + + WOLFSSL_ENTER("AddSession"); + + if (SslSessionCacheOff(ssl, session)) { + WOLFSSL_MSG("Cache off"); + return; + } + + if (session->haveAltSessionID) { + id = session->altSessionID; + idSz = ID_LEN; + } + else { + id = session->sessionID; + idSz = session->sessionIDSz; + } + + /* Do this only for the client because if the server doesn't have an ID at + * this point, it won't on resumption. */ + if (idSz == 0 && ssl->options.side == WOLFSSL_CLIENT_END) { + WC_RNG* rng = NULL; + if (ssl->rng != NULL) + rng = ssl->rng; +#if defined(HAVE_GLOBAL_RNG) && defined(OPENSSL_EXTRA) + else if (initGlobalRNG == 1 || wolfSSL_RAND_Init() == WOLFSSL_SUCCESS) { + rng = &globalRNG; + } +#endif + if (wc_RNG_GenerateBlock(rng, ssl->session->altSessionID, + ID_LEN) != 0) + return; + ssl->session->haveAltSessionID = 1; + id = ssl->session->altSessionID; + idSz = ID_LEN; + } + +#ifdef HAVE_EXT_CACHE + if (!ssl->options.internalCacheOff) +#endif + { + /* Try to add the session to internal cache or external cache + if a new_sess_cb is set. Its ok if we don't succeed. */ + (void)AddSessionToCache(ssl->ctx, session, id, idSz, +#ifdef SESSION_INDEX + &ssl->sessionIndex, +#else + NULL, +#endif + ssl->options.side, +#ifdef HAVE_SESSION_TICKET + ssl->options.useTicket, +#else + 0, +#endif +#ifdef NO_SESSION_CACHE_REF + NULL +#else + (ssl->options.side == WOLFSSL_CLIENT_END) ? + &ssl->clientSession : NULL +#endif + ); + } + +#ifdef HAVE_EXT_CACHE + if (error == 0 && ssl->ctx->new_sess_cb != NULL) { + int cbRet = 0; + wolfSSL_SESSION_up_ref(session); + cbRet = ssl->ctx->new_sess_cb(ssl, session); + if (cbRet == 0) + wolfSSL_FreeSession(ssl->ctx, session); + } +#endif + +#if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS) + if (error == 0) { + word32 active = 0; + + error = get_locked_session_stats(&active, NULL, NULL); + if (error == WOLFSSL_SUCCESS) { + error = 0; /* back to this function ok */ + + if (PeakSessions < active) { + PeakSessions = active; + } + } + } +#endif /* WOLFSSL_SESSION_STATS && WOLFSSL_PEAK_SESSIONS */ + (void)error; +} + + +#ifdef SESSION_INDEX + +int wolfSSL_GetSessionIndex(WOLFSSL* ssl) +{ + WOLFSSL_ENTER("wolfSSL_GetSessionIndex"); + WOLFSSL_LEAVE("wolfSSL_GetSessionIndex", ssl->sessionIndex); + return ssl->sessionIndex; +} + + +int wolfSSL_GetSessionAtIndex(int idx, WOLFSSL_SESSION* session) +{ + int row, col, result = WOLFSSL_FAILURE; + SessionRow* sessRow; + WOLFSSL_SESSION* cacheSession; + + WOLFSSL_ENTER("wolfSSL_GetSessionAtIndex"); + + session = ClientSessionToSession(session); + + row = idx >> SESSIDX_ROW_SHIFT; + col = idx & SESSIDX_IDX_MASK; + + if (session == NULL || + row < 0 || row >= SESSION_ROWS || col >= SESSIONS_PER_ROW) { + return WOLFSSL_FAILURE; + } + + sessRow = &SessionCache[row]; + if (SESSION_ROW_RD_LOCK(sessRow) != 0) { + return BAD_MUTEX_E; + } + +#ifdef SESSION_CACHE_DYNAMIC_MEM + cacheSession = sessRow->Sessions[col]; +#else + cacheSession = &sessRow->Sessions[col]; +#endif + if (cacheSession) { + XMEMCPY(session, cacheSession, sizeof(WOLFSSL_SESSION)); + result = WOLFSSL_SUCCESS; + } + else { + result = WOLFSSL_FAILURE; + } + + SESSION_ROW_UNLOCK(sessRow); + + WOLFSSL_LEAVE("wolfSSL_GetSessionAtIndex", result); + return result; +} + +#endif /* SESSION_INDEX */ + +#if defined(SESSION_CERTS) + +WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session) +{ + WOLFSSL_X509_CHAIN* chain = NULL; + + WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain"); + + session = ClientSessionToSession(session); + + if (session) + chain = &session->chain; + + WOLFSSL_LEAVE("wolfSSL_SESSION_get_peer_chain", chain ? 1 : 0); + return chain; +} + + +#ifdef OPENSSL_EXTRA +/* gets the peer certificate associated with the session passed in + * returns null on failure, the caller should not free the returned pointer */ +WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_get_peer_chain"); + + session = ClientSessionToSession(session); + if (session) { + int count; + + count = wolfSSL_get_chain_count(&session->chain); + if (count < 1 || count >= MAX_CHAIN_DEPTH) { + WOLFSSL_MSG("bad count found"); + return NULL; + } + + if (session->peer == NULL) { + session->peer = wolfSSL_get_chain_X509(&session->chain, 0); + } + return session->peer; + } + WOLFSSL_MSG("No session passed in"); + + return NULL; +} +#endif /* OPENSSL_EXTRA */ +#endif /* SESSION_INDEX && SESSION_CERTS */ + + +#ifdef WOLFSSL_SESSION_STATS + +static int get_locked_session_stats(word32* active, word32* total, word32* peak) +{ + int result = WOLFSSL_SUCCESS; + int i; + int count; + int idx; + word32 now = 0; + word32 seen = 0; + word32 ticks = LowResTimer(); + + WOLFSSL_ENTER("get_locked_session_stats"); + +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_RD_LOCK(&SessionCache[0]); +#endif + for (i = 0; i < SESSION_ROWS; i++) { + SessionRow* row = &SessionCache[i]; + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + if (SESSION_ROW_RD_LOCK(row) != 0) { + WOLFSSL_MSG("Session row cache mutex lock failed"); + return BAD_MUTEX_E; + } + #endif + + seen += row->totalCount; + + if (active == NULL) { + SESSION_ROW_UNLOCK(row); + continue; + } + + count = min((word32)row->totalCount, SESSIONS_PER_ROW); + idx = row->nextIdx - 1; + if (idx < 0 || idx >= SESSIONS_PER_ROW) { + idx = SESSIONS_PER_ROW - 1; /* if back to front previous was end */ + } + + for (; count > 0; --count) { + /* if not expired then good */ +#ifdef SESSION_CACHE_DYNAMIC_MEM + if (row->Sessions[idx] && + ticks < (row->Sessions[idx]->bornOn + + row->Sessions[idx]->timeout) ) +#else + if (ticks < (row->Sessions[idx].bornOn + + row->Sessions[idx].timeout) ) +#endif + { + now++; + } + + idx = idx > 0 ? idx - 1 : SESSIONS_PER_ROW - 1; + } + + #ifdef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(row); + #endif + } +#ifndef ENABLE_SESSION_CACHE_ROW_LOCK + SESSION_ROW_UNLOCK(&SessionCache[0]); +#endif + + if (active) { + *active = now; + } + if (total) { + *total = seen; + } + +#ifdef WOLFSSL_PEAK_SESSIONS + if (peak) { + *peak = PeakSessions; + } +#else + (void)peak; +#endif + + WOLFSSL_LEAVE("get_locked_session_stats", result); + + return result; +} + + +/* return WOLFSSL_SUCCESS on ok */ +int wolfSSL_get_session_stats(word32* active, word32* total, word32* peak, + word32* maxSessions) +{ + int result = WOLFSSL_SUCCESS; + + WOLFSSL_ENTER("wolfSSL_get_session_stats"); + + if (maxSessions) { + *maxSessions = SESSIONS_PER_ROW * SESSION_ROWS; + + if (active == NULL && total == NULL && peak == NULL) + return result; /* we're done */ + } + + /* user must provide at least one query value */ + if (active == NULL && total == NULL && peak == NULL) { + return BAD_FUNC_ARG; + } + + result = get_locked_session_stats(active, total, peak); + + WOLFSSL_LEAVE("wolfSSL_get_session_stats", result); + + return result; +} + +#endif /* WOLFSSL_SESSION_STATS */ + + + #ifdef PRINT_SESSION_STATS + + /* WOLFSSL_SUCCESS on ok */ + int wolfSSL_PrintSessionStats(void) + { + word32 totalSessionsSeen = 0; + word32 totalSessionsNow = 0; + word32 peak = 0; + word32 maxSessions = 0; + int i; + int ret; + double E; /* expected freq */ + double chiSquare = 0; + + ret = wolfSSL_get_session_stats(&totalSessionsNow, &totalSessionsSeen, + &peak, &maxSessions); + if (ret != WOLFSSL_SUCCESS) + return ret; + printf("Total Sessions Seen = %u\n", totalSessionsSeen); + printf("Total Sessions Now = %u\n", totalSessionsNow); +#ifdef WOLFSSL_PEAK_SESSIONS + printf("Peak Sessions = %u\n", peak); +#endif + printf("Max Sessions = %u\n", maxSessions); + + E = (double)totalSessionsSeen / SESSION_ROWS; + + for (i = 0; i < SESSION_ROWS; i++) { + double diff = SessionCache[i].totalCount - E; + diff *= diff; /* square */ + diff /= E; /* normalize */ + + chiSquare += diff; + } + printf(" chi-square = %5.1f, d.f. = %d\n", chiSquare, + SESSION_ROWS - 1); + #if (SESSION_ROWS == 11) + printf(" .05 p value = 18.3, chi-square should be less\n"); + #elif (SESSION_ROWS == 211) + printf(".05 p value = 244.8, chi-square should be less\n"); + #elif (SESSION_ROWS == 5981) + printf(".05 p value = 6161.0, chi-square should be less\n"); + #elif (SESSION_ROWS == 3) + printf(".05 p value = 6.0, chi-square should be less\n"); + #elif (SESSION_ROWS == 2861) + printf(".05 p value = 2985.5, chi-square should be less\n"); + #endif + printf("\n"); + + return ret; + } + + #endif /* SESSION_STATS */ + +#else /* NO_SESSION_CACHE */ + +WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) +{ + return (WOLFSSL_SESSION*)session; +} + +/* No session cache version */ +WOLFSSL_SESSION* wolfSSL_GetSession(WOLFSSL* ssl, byte* masterSecret, + byte restoreSessionCerts) +{ + (void)ssl; + (void)masterSecret; + (void)restoreSessionCerts; + + return NULL; +} + +#endif /* NO_SESSION_CACHE */ + +#ifdef OPENSSL_EXTRA + + /* returns previous set cache size which stays constant */ + long wolfSSL_CTX_sess_set_cache_size(WOLFSSL_CTX* ctx, long sz) + { + /* cache size fixed at compile time in wolfSSL */ + (void)ctx; + (void)sz; + WOLFSSL_MSG("session cache is set at compile time"); + #ifndef NO_SESSION_CACHE + return (long)(SESSIONS_PER_ROW * SESSION_ROWS); + #else + return 0; + #endif + } + + + long wolfSSL_CTX_sess_get_cache_size(WOLFSSL_CTX* ctx) + { + (void)ctx; + #ifndef NO_SESSION_CACHE + return (long)(SESSIONS_PER_ROW * SESSION_ROWS); + #else + return 0; + #endif + } + +#endif + +#ifndef NO_SESSION_CACHE +int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) +{ + int error = 0; + const byte* id = NULL; + byte idSz = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_add_session"); + + session = ClientSessionToSession(session); + if (session == NULL) + return WOLFSSL_FAILURE; + + /* Session cache is global */ + (void)ctx; + + if (session->haveAltSessionID) { + id = session->altSessionID; + idSz = ID_LEN; + } + else { + id = session->sessionID; + idSz = session->sessionIDSz; + } + + error = AddSessionToCache(ctx, session, id, idSz, + NULL, session->side, +#ifdef HAVE_SESSION_TICKET + session->ticketLen > 0, +#else + 0, +#endif + NULL); + + return error == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} +#endif + +#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \ + defined(HAVE_EXT_CACHE)) +/* stunnel 4.28 needs + * + * Callback that is called if a session tries to resume but could not find + * the session to resume it. + */ +void wolfSSL_CTX_sess_set_get_cb(WOLFSSL_CTX* ctx, + WOLFSSL_SESSION*(*f)(WOLFSSL*, const unsigned char*, int, int*)) +{ + if (ctx == NULL) + return; + +#ifdef HAVE_EXT_CACHE + ctx->get_sess_cb = f; +#else + (void)f; +#endif +} + +void wolfSSL_CTX_sess_set_new_cb(WOLFSSL_CTX* ctx, + int (*f)(WOLFSSL*, WOLFSSL_SESSION*)) +{ + if (ctx == NULL) + return; + +#ifdef HAVE_EXT_CACHE + ctx->new_sess_cb = f; +#else + (void)f; +#endif +} + +void wolfSSL_CTX_sess_set_remove_cb(WOLFSSL_CTX* ctx, void (*f)(WOLFSSL_CTX*, + WOLFSSL_SESSION*)) +{ + if (ctx == NULL) + return; + +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + ctx->rem_sess_cb = f; +#else + (void)f; +#endif +} + + +/* + * + * Note: It is expected that the importing and exporting function have been + * built with the same settings. For example if session tickets was + * enabled with the wolfSSL library exporting a session then it is + * expected to be turned on with the wolfSSL library importing the + * session. + */ +int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) +{ + int size = 0; +#ifdef HAVE_EXT_CACHE + int idx = 0; +#ifdef SESSION_CERTS + int i; +#endif + + WOLFSSL_ENTER("wolfSSL_i2d_SSL_SESSION"); + + sess = ClientSessionToSession(sess); + if (sess == NULL) { + return BAD_FUNC_ARG; + } + + /* side | bornOn | timeout | sessionID len | sessionID | masterSecret | + * haveEMS */ + size += OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN + + sess->sessionIDSz + SECRET_LEN + OPAQUE8_LEN; + /* altSessionID */ + size += OPAQUE8_LEN + (sess->haveAltSessionID ? ID_LEN : 0); +#ifdef SESSION_CERTS + /* Peer chain */ + size += OPAQUE8_LEN; + for (i = 0; i < sess->chain.count; i++) + size += OPAQUE16_LEN + sess->chain.certs[i].length; +#endif +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + /* Protocol version */ + size += OPAQUE16_LEN; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + /* cipher suite */ + size += OPAQUE16_LEN; +#endif +#ifndef NO_CLIENT_CACHE + /* ServerID len | ServerID */ + size += OPAQUE16_LEN + sess->idLen; +#endif +#ifdef WOLFSSL_SESSION_ID_CTX + /* session context ID len | session context ID */ + size += OPAQUE8_LEN + sess->sessionCtxSz; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + /* peerVerifyRet */ + size += OPAQUE8_LEN; +#endif +#ifdef WOLFSSL_TLS13 + /* namedGroup */ + size += OPAQUE16_LEN; +#endif +#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) +#ifdef WOLFSSL_TLS13 +#ifdef WOLFSSL_32BIT_MILLI_TIME + /* ticketSeen | ticketAdd */ + size += OPAQUE32_LEN + OPAQUE32_LEN; +#else + /* ticketSeen Hi 32 bits | ticketSeen Lo 32 bits | ticketAdd */ + size += OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE32_LEN; +#endif + /* ticketNonce */ + size += OPAQUE8_LEN + sess->ticketNonce.len; +#endif +#ifdef WOLFSSL_EARLY_DATA + size += OPAQUE32_LEN; +#endif +#endif +#ifdef HAVE_SESSION_TICKET + /* ticket len | ticket */ + size += OPAQUE16_LEN + sess->ticketLen; +#endif + + if (p != NULL) { + unsigned char *data; + + if (*p == NULL) + *p = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_OPENSSL); + if (*p == NULL) + return 0; + data = *p; + + data[idx++] = sess->side; + c32toa(sess->bornOn, data + idx); idx += OPAQUE32_LEN; + c32toa(sess->timeout, data + idx); idx += OPAQUE32_LEN; + data[idx++] = sess->sessionIDSz; + XMEMCPY(data + idx, sess->sessionID, sess->sessionIDSz); + idx += sess->sessionIDSz; + XMEMCPY(data + idx, sess->masterSecret, SECRET_LEN); idx += SECRET_LEN; + data[idx++] = (byte)sess->haveEMS; + data[idx++] = sess->haveAltSessionID ? ID_LEN : 0; + if (sess->haveAltSessionID) { + XMEMCPY(data + idx, sess->altSessionID, ID_LEN); + idx += ID_LEN; + } +#ifdef SESSION_CERTS + data[idx++] = (byte)sess->chain.count; + for (i = 0; i < sess->chain.count; i++) { + c16toa((word16)sess->chain.certs[i].length, data + idx); + idx += OPAQUE16_LEN; + XMEMCPY(data + idx, sess->chain.certs[i].buffer, + sess->chain.certs[i].length); + idx += sess->chain.certs[i].length; + } +#endif +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + data[idx++] = sess->version.major; + data[idx++] = sess->version.minor; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + data[idx++] = sess->cipherSuite0; + data[idx++] = sess->cipherSuite; +#endif +#ifndef NO_CLIENT_CACHE + c16toa(sess->idLen, data + idx); idx += OPAQUE16_LEN; + XMEMCPY(data + idx, sess->serverID, sess->idLen); + idx += sess->idLen; +#endif +#ifdef WOLFSSL_SESSION_ID_CTX + data[idx++] = sess->sessionCtxSz; + XMEMCPY(data + idx, sess->sessionCtx, sess->sessionCtxSz); + idx += sess->sessionCtxSz; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + data[idx++] = sess->peerVerifyRet; +#endif +#ifdef WOLFSSL_TLS13 + c16toa(sess->namedGroup, data + idx); + idx += OPAQUE16_LEN; +#endif +#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) +#ifdef WOLFSSL_TLS13 +#ifdef WOLFSSL_32BIT_MILLI_TIME + c32toa(sess->ticketSeen, data + idx); + idx += OPAQUE32_LEN; +#else + c32toa((word32)(sess->ticketSeen >> 32), data + idx); + idx += OPAQUE32_LEN; + c32toa((word32)sess->ticketSeen, data + idx); + idx += OPAQUE32_LEN; +#endif + c32toa(sess->ticketAdd, data + idx); + idx += OPAQUE32_LEN; + data[idx++] = sess->ticketNonce.len; + XMEMCPY(data + idx, sess->ticketNonce.data, sess->ticketNonce.len); + idx += sess->ticketNonce.len; +#endif +#ifdef WOLFSSL_EARLY_DATA + c32toa(sess->maxEarlyDataSz, data + idx); + idx += OPAQUE32_LEN; +#endif +#endif +#ifdef HAVE_SESSION_TICKET + c16toa(sess->ticketLen, data + idx); idx += OPAQUE16_LEN; + XMEMCPY(data + idx, sess->ticket, sess->ticketLen); + idx += sess->ticketLen; +#endif + } +#endif + + (void)sess; + (void)p; +#ifdef HAVE_EXT_CACHE + (void)idx; +#endif + + return size; +} + + +/* TODO: no function to free new session. + * + * Note: It is expected that the importing and exporting function have been + * built with the same settings. For example if session tickets was + * enabled with the wolfSSL library exporting a session then it is + * expected to be turned on with the wolfSSL library importing the + * session. + */ +WOLFSSL_SESSION* wolfSSL_d2i_SSL_SESSION(WOLFSSL_SESSION** sess, + const unsigned char** p, long i) +{ + WOLFSSL_SESSION* s = NULL; + int ret = 0; +#if defined(HAVE_EXT_CACHE) + int idx = 0; + byte* data; +#ifdef SESSION_CERTS + int j; + word16 length; +#endif +#endif /* HAVE_EXT_CACHE */ + + (void)p; + (void)i; + (void)ret; + (void)sess; + +#ifdef HAVE_EXT_CACHE + if (p == NULL || *p == NULL) + return NULL; + + s = wolfSSL_SESSION_new(); + if (s == NULL) + return NULL; + + idx = 0; + data = (byte*)*p; + + /* side | bornOn | timeout | sessionID len */ + if (i < OPAQUE8_LEN + OPAQUE32_LEN + OPAQUE32_LEN + OPAQUE8_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->side = data[idx++]; + ato32(data + idx, &s->bornOn); idx += OPAQUE32_LEN; + ato32(data + idx, &s->timeout); idx += OPAQUE32_LEN; + s->sessionIDSz = data[idx++]; + + /* sessionID | secret | haveEMS | haveAltSessionID */ + if (i - idx < s->sessionIDSz + SECRET_LEN + OPAQUE8_LEN + OPAQUE8_LEN) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->sessionID, data + idx, s->sessionIDSz); + idx += s->sessionIDSz; + XMEMCPY(s->masterSecret, data + idx, SECRET_LEN); idx += SECRET_LEN; + s->haveEMS = data[idx++]; + if (data[idx] != ID_LEN && data[idx] != 0) { + ret = BUFFER_ERROR; + goto end; + } + s->haveAltSessionID = data[idx++] == ID_LEN; + + /* altSessionID */ + if (s->haveAltSessionID) { + if (i - idx < ID_LEN) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->altSessionID, data + idx, ID_LEN); idx += ID_LEN; + } + +#ifdef SESSION_CERTS + /* Certificate chain */ + if (i - idx == 0) { + ret = BUFFER_ERROR; + goto end; + } + s->chain.count = data[idx++]; + for (j = 0; j < s->chain.count; j++) { + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + ato16(data + idx, &length); idx += OPAQUE16_LEN; + s->chain.certs[j].length = length; + if (i - idx < length) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->chain.certs[j].buffer, data + idx, length); + idx += length; + } +#endif +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + /* Protocol Version */ + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->version.major = data[idx++]; + s->version.minor = data[idx++]; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + /* Cipher suite */ + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->cipherSuite0 = data[idx++]; + s->cipherSuite = data[idx++]; +#endif +#ifndef NO_CLIENT_CACHE + /* ServerID len */ + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + ato16(data + idx, &s->idLen); idx += OPAQUE16_LEN; + + /* ServerID */ + if (i - idx < s->idLen) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->serverID, data + idx, s->idLen); idx += s->idLen; +#endif +#ifdef WOLFSSL_SESSION_ID_CTX + /* byte for length of session context ID */ + if (i - idx < OPAQUE8_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->sessionCtxSz = data[idx++]; + + /* app session context ID */ + if (i - idx < s->sessionCtxSz) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->sessionCtx, data + idx, s->sessionCtxSz); idx += s->sessionCtxSz; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + /* byte for peerVerifyRet */ + if (i - idx < OPAQUE8_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->peerVerifyRet = data[idx++]; +#endif +#ifdef WOLFSSL_TLS13 + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + ato16(data + idx, &s->namedGroup); + idx += OPAQUE16_LEN; +#endif +#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) +#ifdef WOLFSSL_TLS13 + if (i - idx < (OPAQUE32_LEN * 2)) { + ret = BUFFER_ERROR; + goto end; + } +#ifdef WOLFSSL_32BIT_MILLI_TIME + ato32(data + idx, &s->ticketSeen); + idx += OPAQUE32_LEN; +#else + { + word32 seenHi, seenLo; + + ato32(data + idx, &seenHi); + idx += OPAQUE32_LEN; + ato32(data + idx, &seenLo); + idx += OPAQUE32_LEN; + s->ticketSeen = ((sword64)seenHi << 32) + seenLo; + } +#endif + ato32(data + idx, &s->ticketAdd); + idx += OPAQUE32_LEN; + if (i - idx < OPAQUE8_LEN) { + ret = BUFFER_ERROR; + goto end; + } + s->ticketNonce.len = data[idx++]; + + if (i - idx < s->ticketNonce.len) { + ret = BUFFER_ERROR; + goto end; + } +#if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + ret = SessionTicketNoncePopulate(s, data + idx, s->ticketNonce.len); + if (ret != 0) + goto end; +#else + if (s->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->ticketNonce.data, data + idx, s->ticketNonce.len); +#endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */ + + idx += s->ticketNonce.len; +#endif +#ifdef WOLFSSL_EARLY_DATA + if (i - idx < OPAQUE32_LEN) { + ret = BUFFER_ERROR; + goto end; + } + ato32(data + idx, &s->maxEarlyDataSz); + idx += OPAQUE32_LEN; +#endif +#endif +#ifdef HAVE_SESSION_TICKET + /* ticket len */ + if (i - idx < OPAQUE16_LEN) { + ret = BUFFER_ERROR; + goto end; + } + ato16(data + idx, &s->ticketLen); idx += OPAQUE16_LEN; + + /* Dispose of ol dynamic ticket and ensure space for new ticket. */ + if (s->ticketLenAlloc > 0) { + XFREE(s->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK); + } + if (s->ticketLen <= SESSION_TICKET_LEN) + s->ticket = s->staticTicket; + else { + s->ticket = (byte*)XMALLOC(s->ticketLen, NULL, + DYNAMIC_TYPE_SESSION_TICK); + if (s->ticket == NULL) { + ret = MEMORY_ERROR; + goto end; + } + s->ticketLenAlloc = (word16)s->ticketLen; + } + + /* ticket */ + if (i - idx < s->ticketLen) { + ret = BUFFER_ERROR; + goto end; + } + XMEMCPY(s->ticket, data + idx, s->ticketLen); idx += s->ticketLen; +#endif + (void)idx; + + if (sess != NULL) { + *sess = s; + } + + s->isSetup = 1; + + *p += idx; + +end: + if (ret != 0 && (sess == NULL || *sess != s)) { + wolfSSL_FreeSession(NULL, s); + s = NULL; + } +#endif /* HAVE_EXT_CACHE */ + return s; +} + +/* Check if there is a session ticket associated with this WOLFSSL_SESSION. + * + * sess - pointer to WOLFSSL_SESSION struct + * + * Returns 1 if has session ticket, otherwise 0 */ +int wolfSSL_SESSION_has_ticket(const WOLFSSL_SESSION* sess) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_has_ticket"); +#ifdef HAVE_SESSION_TICKET + sess = ClientSessionToSession(sess); + if (sess) { + if ((sess->ticketLen > 0) && (sess->ticket != NULL)) { + return WOLFSSL_SUCCESS; + } + } +#else + (void)sess; +#endif + return WOLFSSL_FAILURE; +} + +unsigned long wolfSSL_SESSION_get_ticket_lifetime_hint( + const WOLFSSL_SESSION* sess) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_get_ticket_lifetime_hint"); + sess = ClientSessionToSession(sess); + if (sess) { + return sess->timeout; + } + return 0; +} + +long wolfSSL_SESSION_get_timeout(const WOLFSSL_SESSION* sess) +{ + long timeout = 0; + WOLFSSL_ENTER("wolfSSL_SESSION_get_timeout"); + sess = ClientSessionToSession(sess); + if (sess) + timeout = sess->timeout; + return timeout; +} + +long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t) +{ + word32 tmptime; + + ses = ClientSessionToSession(ses); + if (ses == NULL || t < 0) { + return BAD_FUNC_ARG; + } + + tmptime = t & 0xFFFFFFFF; + ses->timeout = tmptime; + + return WOLFSSL_SUCCESS; +} + +long wolfSSL_SESSION_get_time(const WOLFSSL_SESSION* sess) +{ + long bornOn = 0; + WOLFSSL_ENTER("wolfSSL_SESSION_get_time"); + sess = ClientSessionToSession(sess); + if (sess) + bornOn = sess->bornOn; + return bornOn; +} + +long wolfSSL_SESSION_set_time(WOLFSSL_SESSION *ses, long t) +{ + + ses = ClientSessionToSession(ses); + if (ses == NULL || t < 0) { + return 0; + } + ses->bornOn = (word32)t; + return t; +} + +#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */ + +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ + defined(HAVE_EX_DATA) + +#if defined(HAVE_EX_DATA) && !defined(NO_SESSION_CACHE) +static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, + void* data, byte get, void** getRet, int* setRet) +{ + int row; + int i; + int error = 0; + SessionRow* sessRow = NULL; + const byte* id; + byte foundCache = 0; + + if (getRet != NULL) + *getRet = NULL; + if (setRet != NULL) + *setRet = WOLFSSL_FAILURE; + + id = session->sessionID; + if (session->haveAltSessionID) + id = session->altSessionID; + + row = (int)(HashObject(id, ID_LEN, &error) % SESSION_ROWS); + if (error != 0) { + WOLFSSL_MSG("Hash session failed"); + return; + } + + sessRow = &SessionCache[row]; + if (get) + error = SESSION_ROW_RD_LOCK(sessRow); + else + error = SESSION_ROW_WR_LOCK(sessRow); + if (error != 0) { + WOLFSSL_MSG("Session row lock failed"); + return; + } + + for (i = 0; i < SESSIONS_PER_ROW && i < sessRow->totalCount; i++) { + WOLFSSL_SESSION* cacheSession; +#ifdef SESSION_CACHE_DYNAMIC_MEM + cacheSession = sessRow->Sessions[i]; +#else + cacheSession = &sessRow->Sessions[i]; +#endif + if (cacheSession && + XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0 + && session->side == cacheSession->side + #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) + && (IsAtLeastTLSv1_3(session->version) == + IsAtLeastTLSv1_3(cacheSession->version)) + #endif + ) { + if (get) { + if (getRet) { + *getRet = wolfSSL_CRYPTO_get_ex_data( + &cacheSession->ex_data, idx); + } + } + else { + if (setRet) { + *setRet = wolfSSL_CRYPTO_set_ex_data( + &cacheSession->ex_data, idx, data); + } + } + foundCache = 1; + break; + } + } + SESSION_ROW_UNLOCK(sessRow); + /* If we don't have a session in cache then clear the ex_data and + * own it */ + if (!foundCache) { + XMEMSET(&session->ex_data, 0, sizeof(WOLFSSL_CRYPTO_EX_DATA)); + session->ownExData = 1; + if (!get) { + *setRet = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, + data); + } + } + +} +#endif + +#endif + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ + || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) + +#ifndef NO_SESSION_CACHE +int wolfSSL_SSL_CTX_remove_session(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *s) +{ +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + int rem_called = FALSE; +#endif + + WOLFSSL_ENTER("wolfSSL_SSL_CTX_remove_session"); + + s = ClientSessionToSession(s); + if (ctx == NULL || s == NULL) + return BAD_FUNC_ARG; + +#ifdef HAVE_EXT_CACHE + if (!ctx->internalCacheOff) +#endif + { + const byte* id; + WOLFSSL_SESSION *sess = NULL; + word32 row = 0; + int ret; + + id = s->sessionID; + if (s->haveAltSessionID) + id = s->altSessionID; + + ret = TlsSessionCacheGetAndWrLock(id, &sess, &row, ctx->method->side); + if (ret == 0 && sess != NULL) { +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (sess->rem_sess_cb != NULL) { + rem_called = TRUE; + } +#endif + /* Call this before changing ownExData so that calls to ex_data + * don't try to access the SessionCache again. */ + EvictSessionFromCache(sess); +#ifdef HAVE_EX_DATA + if (sess->ownExData) { + /* Most recent version of ex data is in cache. Copy it + * over so the user can free it. */ + XMEMCPY(&s->ex_data, &sess->ex_data, + sizeof(WOLFSSL_CRYPTO_EX_DATA)); + s->ownExData = 1; + sess->ownExData = 0; + } +#endif +#ifdef SESSION_CACHE_DYNAMIC_MEM + { + /* Find and clear entry. Row is locked so we are good to go. */ + int idx; + for (idx = 0; idx < SESSIONS_PER_ROW; idx++) { + if (sess == SessionCache[row].Sessions[idx]) { + XFREE(sess, sess->heap, DYNAMIC_TYPE_SESSION); + SessionCache[row].Sessions[idx] = NULL; + break; + } + } + } +#endif + TlsSessionCacheUnlockRow(row); + } + } + +#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA) + if (ctx->rem_sess_cb != NULL && !rem_called) { + ctx->rem_sess_cb(ctx, s); + } +#endif + + /* s cannot be resumed at this point */ + s->timeout = 0; + + return 0; +} + +WOLFSSL_SESSION *wolfSSL_SSL_get0_session(const WOLFSSL *ssl) +{ + WOLFSSL_ENTER("wolfSSL_SSL_get0_session"); + + return ssl->session; +} + +#endif /* NO_SESSION_CACHE */ + +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || + OPENSSL_EXTRA || HAVE_LIGHTY */ + +#ifdef WOLFSSL_SESSION_EXPORT +/* Used to import a serialized TLS session. + * WARNING: buf contains sensitive information about the state and is best to be + * encrypted before storing if stored. + * + * @param ssl WOLFSSL structure to import the session into + * @param buf serialized session + * @param sz size of buffer 'buf' + * @return the number of bytes read from buffer 'buf' + */ +int wolfSSL_tls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz) +{ + if (ssl == NULL || buf == NULL) { + return BAD_FUNC_ARG; + } + return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS); +} + + +/* Used to export a serialized TLS session. + * WARNING: buf contains sensitive information about the state and is best to be + * encrypted before storing if stored. + * + * @param ssl WOLFSSL structure to export the session from + * @param buf output of serialized session + * @param sz size in bytes set in 'buf' + * @return the number of bytes written into buffer 'buf' + */ +int wolfSSL_tls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz) +{ + if (ssl == NULL || sz == NULL) { + return BAD_FUNC_ARG; + } + return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_TLS); +} + +#ifdef WOLFSSL_DTLS +int wolfSSL_dtls_import(WOLFSSL* ssl, const unsigned char* buf, unsigned int sz) +{ + WOLFSSL_ENTER("wolfSSL_session_import"); + + if (ssl == NULL || buf == NULL) { + return BAD_FUNC_ARG; + } + + /* sanity checks on buffer and protocol are done in internal function */ + return wolfSSL_session_import_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS); +} + + +/* Sets the function to call for serializing the session. This function is + * called right after the handshake is completed. */ +int wolfSSL_CTX_dtls_set_export(WOLFSSL_CTX* ctx, wc_dtls_export func) +{ + + WOLFSSL_ENTER("wolfSSL_CTX_dtls_set_export"); + + /* purposefully allow func to be NULL */ + if (ctx == NULL) { + return BAD_FUNC_ARG; + } + + ctx->dtls_export = func; + + return WOLFSSL_SUCCESS; +} + +/* Sets the function in WOLFSSL struct to call for serializing the session. This + * function is called right after the handshake is completed. */ +int wolfSSL_dtls_set_export(WOLFSSL* ssl, wc_dtls_export func) +{ + + WOLFSSL_ENTER("wolfSSL_dtls_set_export"); + + /* purposefully allow func to be NULL */ + if (ssl == NULL) { + return BAD_FUNC_ARG; + } + + ssl->dtls_export = func; + + return WOLFSSL_SUCCESS; +} + + +/* This function allows for directly serializing a session rather than using + * callbacks. It has less overhead by removing a temporary buffer and gives + * control over when the session gets serialized. When using callbacks the + * session is always serialized immediately after the handshake is finished. + * + * buf is the argument to contain the serialized session + * sz is the size of the buffer passed in + * ssl is the WOLFSSL struct to serialize + * returns the size of serialized session on success, 0 on no action, and + * negative value on error */ +int wolfSSL_dtls_export(WOLFSSL* ssl, unsigned char* buf, unsigned int* sz) +{ + WOLFSSL_ENTER("wolfSSL_dtls_export"); + + if (ssl == NULL || sz == NULL) { + return BAD_FUNC_ARG; + } + + if (buf == NULL) { + *sz = MAX_EXPORT_BUFFER; + return 0; + } + + /* if not DTLS do nothing */ + if (!ssl->options.dtls) { + WOLFSSL_MSG("Currently only DTLS export is supported"); + return 0; + } + + /* copy over keys, options, and dtls state struct */ + return wolfSSL_session_export_internal(ssl, buf, sz, WOLFSSL_EXPORT_DTLS); +} + + +/* This function is similar to wolfSSL_dtls_export but only exports the portion + * of the WOLFSSL structure related to the state of the connection, i.e. peer + * sequence number, epoch, AEAD state etc. + * + * buf is the argument to contain the serialized state, if null then set "sz" to + * buffer size required + * sz is the size of the buffer passed in + * ssl is the WOLFSSL struct to serialize + * returns the size of serialized session on success, 0 on no action, and + * negative value on error */ +int wolfSSL_dtls_export_state_only(WOLFSSL* ssl, unsigned char* buf, + unsigned int* sz) +{ + WOLFSSL_ENTER("wolfSSL_dtls_export_state_only"); + + if (ssl == NULL || sz == NULL) { + return BAD_FUNC_ARG; + } + + if (buf == NULL) { + *sz = MAX_EXPORT_STATE_BUFFER; + return 0; + } + + /* if not DTLS do nothing */ + if (!ssl->options.dtls) { + WOLFSSL_MSG("Currently only DTLS export state is supported"); + return 0; + } + + /* copy over keys, options, and dtls state struct */ + return wolfSSL_dtls_export_state_internal(ssl, buf, *sz); +} + + +/* returns 0 on success */ +int wolfSSL_send_session(WOLFSSL* ssl) +{ + int ret; + byte* buf; + word32 bufSz = MAX_EXPORT_BUFFER; + + WOLFSSL_ENTER("wolfSSL_send_session"); + + if (ssl == NULL) { + return BAD_FUNC_ARG; + } + + buf = (byte*)XMALLOC(bufSz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (buf == NULL) { + return MEMORY_E; + } + + /* if not DTLS do nothing */ + if (!ssl->options.dtls) { + XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + WOLFSSL_MSG("Currently only DTLS export is supported"); + return 0; + } + + /* copy over keys, options, and dtls state struct */ + ret = wolfSSL_session_export_internal(ssl, buf, &bufSz, + WOLFSSL_EXPORT_DTLS); + if (ret < 0) { + XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + return ret; + } + + /* if no error ret has size of buffer */ + ret = ssl->dtls_export(ssl, buf, ret, NULL); + if (ret != WOLFSSL_SUCCESS) { + XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + return ret; + } + + XFREE(buf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + return 0; +} +#endif /* WOLFSSL_DTLS */ +#endif /* WOLFSSL_SESSION_EXPORT */ + +#ifdef OPENSSL_EXTRA + +/* Copies the master secret over to out buffer. If outSz is 0 returns the size + * of master secret. + * + * ses : a session from completed TLS/SSL handshake + * out : buffer to hold copy of master secret + * outSz : size of out buffer + * returns : number of bytes copied into out buffer on success + * less then or equal to 0 is considered a failure case + */ +int wolfSSL_SESSION_get_master_key(const WOLFSSL_SESSION* ses, + unsigned char* out, int outSz) +{ + int size; + + ses = ClientSessionToSession(ses); + + if (outSz == 0) { + return SECRET_LEN; + } + + if (ses == NULL || out == NULL || outSz < 0) { + return 0; + } + + if (outSz > SECRET_LEN) { + size = SECRET_LEN; + } + else { + size = outSz; + } + + XMEMCPY(out, ses->masterSecret, size); + return size; +} + + +int wolfSSL_SESSION_get_master_key_length(const WOLFSSL_SESSION* ses) +{ + (void)ses; + return SECRET_LEN; +} + +#ifdef WOLFSSL_EARLY_DATA +unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSION *session) +{ + return session->maxEarlyDataSz; +} +#endif /* WOLFSSL_EARLY_DATA */ + +#endif /* OPENSSL_EXTRA */ + +void SetupSession(WOLFSSL* ssl) +{ + WOLFSSL_SESSION* session = ssl->session; + + WOLFSSL_ENTER("SetupSession"); + + if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) { + /* Make sure the session ID is available when the user calls any + * get_session API */ + if (!session->haveAltSessionID) { + XMEMCPY(session->sessionID, ssl->arrays->sessionID, ID_LEN); + session->sessionIDSz = ssl->arrays->sessionIDSz; + } + else { + XMEMCPY(session->sessionID, session->altSessionID, ID_LEN); + session->sessionIDSz = ID_LEN; + } + } + session->side = (byte)ssl->options.side; + if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) + XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN); + session->haveEMS = ssl->options.haveEMS; +#ifdef WOLFSSL_SESSION_ID_CTX + /* If using compatibility layer then check for and copy over session context + * id. */ + if (ssl->sessionCtxSz > 0 && ssl->sessionCtxSz < ID_LEN) { + XMEMCPY(ssl->session->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz); + session->sessionCtxSz = ssl->sessionCtxSz; + } +#endif + session->timeout = ssl->timeout; +#ifndef NO_ASN_TIME + session->bornOn = LowResTimer(); +#endif +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + session->version = ssl->version; +#endif +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + session->cipherSuite0 = ssl->options.cipherSuite0; + session->cipherSuite = ssl->options.cipherSuite; +#endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + session->peerVerifyRet = (byte)ssl->peerVerifyRet; +#endif + session->isSetup = 1; +} + +#ifdef WOLFSSL_SESSION_ID_CTX + /* Storing app session context id, this value is inherited by WOLFSSL + * objects created from WOLFSSL_CTX. Any session that is imported with a + * different session context id will be rejected. + * + * ctx structure to set context in + * sid_ctx value of context to set + * sid_ctx_len length of sid_ctx buffer + * + * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing + */ + int wolfSSL_CTX_set_session_id_context(WOLFSSL_CTX* ctx, + const unsigned char* sid_ctx, + unsigned int sid_ctx_len) + { + WOLFSSL_ENTER("wolfSSL_CTX_set_session_id_context"); + + /* No application specific context needed for wolfSSL */ + if (sid_ctx_len > ID_LEN || ctx == NULL || sid_ctx == NULL) { + return WOLFSSL_FAILURE; + } + XMEMCPY(ctx->sessionCtx, sid_ctx, sid_ctx_len); + ctx->sessionCtxSz = (byte)sid_ctx_len; + + return WOLFSSL_SUCCESS; + } + + + + /* Storing app session context id. Any session that is imported with a + * different session context id will be rejected. + * + * ssl structure to set context in + * id value of context to set + * len length of sid_ctx buffer + * + * Returns WOLFSSL_SUCCESS in success case and WOLFSSL_FAILURE when failing + */ + int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id, + unsigned int len) + { + WOLFSSL_ENTER("wolfSSL_set_session_id_context"); + + if (len > ID_LEN || ssl == NULL || id == NULL) { + return WOLFSSL_FAILURE; + } + XMEMCPY(ssl->sessionCtx, id, len); + ssl->sessionCtxSz = (byte)len; + + return WOLFSSL_SUCCESS; + } +#endif + +/* return a new malloc'd session with default settings on success */ +WOLFSSL_SESSION* wolfSSL_NewSession(void* heap) +{ + WOLFSSL_SESSION* ret = NULL; + + WOLFSSL_ENTER("wolfSSL_NewSession"); + + ret = (WOLFSSL_SESSION*)XMALLOC(sizeof(WOLFSSL_SESSION), heap, + DYNAMIC_TYPE_SESSION); + if (ret != NULL) { + int err; + XMEMSET(ret, 0, sizeof(WOLFSSL_SESSION)); + wolfSSL_RefInit(&ret->ref, &err); + #ifdef WOLFSSL_REFCNT_ERROR_RETURN + if (err != 0) { + WOLFSSL_MSG("Error setting up session reference mutex"); + XFREE(ret, ret->heap, DYNAMIC_TYPE_SESSION); + return NULL; + } + #else + (void)err; + #endif +#ifndef NO_SESSION_CACHE + ret->cacheRow = INVALID_SESSION_ROW; /* not in cache */ +#endif + ret->type = WOLFSSL_SESSION_TYPE_HEAP; + ret->heap = heap; +#ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Add("SESSION master secret", ret->masterSecret, SECRET_LEN); + wc_MemZero_Add("SESSION id", ret->sessionID, ID_LEN); +#endif + #ifdef HAVE_SESSION_TICKET + ret->ticket = ret->staticTicket; + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + ret->ticketNonce.data = ret->ticketNonce.dataStatic; + #endif + #endif +#ifdef HAVE_EX_DATA + ret->ownExData = 1; + if (crypto_ex_cb_ctx_session != NULL) { + crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session, + &ret->ex_data); + } +#endif + } + return ret; +} + + +WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap) +{ + return wolfSSL_NewSession(heap); +} + +WOLFSSL_SESSION* wolfSSL_SESSION_new(void) +{ + return wolfSSL_SESSION_new_ex(NULL); +} + +/* add one to session reference count + * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */ +int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session) +{ + int ret; + + session = ClientSessionToSession(session); + + if (session == NULL || session->type != WOLFSSL_SESSION_TYPE_HEAP) + return WOLFSSL_FAILURE; + + wolfSSL_RefInc(&session->ref, &ret); +#ifdef WOLFSSL_REFCNT_ERROR_RETURN + if (ret != 0) { + WOLFSSL_MSG("Failed to lock session mutex"); + return WOLFSSL_FAILURE; + } +#else + (void)ret; +#endif + + return WOLFSSL_SUCCESS; +} + +/** + * Deep copy the contents from input to output. + * @param input The source of the copy. + * @param output The destination of the copy. + * @param avoidSysCalls If true, then system calls will be avoided or an error + * will be returned if it is not possible to proceed + * without a system call. This is useful for fetching + * sessions from cache. When a cache row is locked, we + * don't want to block other threads with long running + * system calls. + * @param ticketNonceBuf If not null and @avoidSysCalls is true, the copy of the + * ticketNonce will happen in this pre allocated buffer + * @param ticketNonceLen @ticketNonceBuf len as input, used length on output + * @param ticketNonceUsed if @ticketNonceBuf was used to copy the ticket noncet + * @return WOLFSSL_SUCCESS on success + * WOLFSSL_FAILURE on failure + */ +static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, + WOLFSSL_SESSION* output, int avoidSysCalls, byte* ticketNonceBuf, + byte* ticketNonceLen, byte* preallocUsed) +{ +#ifdef HAVE_SESSION_TICKET + int ticLenAlloc = 0; + byte *ticBuff = NULL; +#endif + const size_t copyOffset = OFFSETOF(WOLFSSL_SESSION, heap) + + sizeof(input->heap); + int ret = WOLFSSL_SUCCESS; + + (void)avoidSysCalls; + (void)ticketNonceBuf; + (void)ticketNonceLen; + (void)preallocUsed; + + input = ClientSessionToSession(input); + output = ClientSessionToSession(output); + + if (input == NULL || output == NULL || input == output) { + WOLFSSL_MSG("input or output are null or same"); + return WOLFSSL_FAILURE; + } + +#ifdef HAVE_SESSION_TICKET + if (output->ticket != output->staticTicket) { + ticBuff = output->ticket; + ticLenAlloc = output->ticketLenAlloc; + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + /* free the data, it would be better to reuse the buffer but this + * maintain the code simpler. A smart allocator should reuse the free'd + * buffer in the next malloc without much performance penalties. */ + if (output->ticketNonce.data != output->ticketNonce.dataStatic) { + + /* Callers that avoid syscall should never calls this with + * output->tickeNonce.data being a dynamic buffer.*/ + if (avoidSysCalls) { + WOLFSSL_MSG("can't avoid syscalls with dynamic TicketNonce buffer"); + return WOLFSSL_FAILURE; + } + + XFREE(output->ticketNonce.data, + output->heap, DYNAMIC_TYPE_SESSION_TICK); + output->ticketNonce.data = output->ticketNonce.dataStatic; + output->ticketNonce.len = 0; + } +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ +#endif /* HAVE_SESSION_TICKET */ + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (output->peer != NULL) { + if (avoidSysCalls) { + WOLFSSL_MSG("Can't free cert when avoiding syscalls"); + return WOLFSSL_FAILURE; + } + wolfSSL_X509_free(output->peer); + output->peer = NULL; + } +#endif + + XMEMCPY((byte*)output + copyOffset, (byte*)input + copyOffset, + sizeof(WOLFSSL_SESSION) - copyOffset); + +#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ + defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + /* fix pointer to static after the copy */ + output->ticketNonce.data = output->ticketNonce.dataStatic; +#endif + /* Set sane values for copy */ +#ifndef NO_SESSION_CACHE + if (output->type != WOLFSSL_SESSION_TYPE_CACHE) + output->cacheRow = INVALID_SESSION_ROW; +#endif +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (input->peer != NULL && input->peer->dynamicMemory) { + if (wolfSSL_X509_up_ref(input->peer) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Can't increase peer cert ref count"); + output->peer = NULL; + } + } + else if (!avoidSysCalls) + output->peer = wolfSSL_X509_dup(input->peer); + else + /* output->peer is not that important to copy */ + output->peer = NULL; +#endif +#ifdef HAVE_SESSION_TICKET + if (input->ticketLen > SESSION_TICKET_LEN) { + /* Need dynamic buffer */ + if (ticBuff == NULL || ticLenAlloc < input->ticketLen) { + /* allocate new one */ + byte* tmp; + if (avoidSysCalls) { + WOLFSSL_MSG("Failed to allocate memory for ticket when avoiding" + " syscalls"); + output->ticket = ticBuff; + output->ticketLenAlloc = (word16) ticLenAlloc; + output->ticketLen = 0; + ret = WOLFSSL_FAILURE; + } + else { +#ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC(input->ticketLen, + output->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + ticBuff = NULL; +#else + tmp = (byte*)XREALLOC(ticBuff, input->ticketLen, + output->heap, DYNAMIC_TYPE_SESSION_TICK); +#endif /* WOLFSSL_NO_REALLOC */ + if (tmp == NULL) { + WOLFSSL_MSG("Failed to allocate memory for ticket"); +#ifndef WOLFSSL_NO_REALLOC + XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + ticBuff = NULL; +#endif /* WOLFSSL_NO_REALLOC */ + output->ticket = NULL; + output->ticketLen = 0; + output->ticketLenAlloc = 0; + ret = WOLFSSL_FAILURE; + } + else { + ticBuff = tmp; + ticLenAlloc = input->ticketLen; + } + } + } + if (ticBuff != NULL && ret == WOLFSSL_SUCCESS) { + XMEMCPY(ticBuff, input->ticket, input->ticketLen); + output->ticket = ticBuff; + output->ticketLenAlloc = (word16) ticLenAlloc; + } + } + else { + /* Default ticket to non dynamic */ + if (avoidSysCalls) { + /* Try to use ticBuf if available. Caller can later move it to + * the static buffer. */ + if (ticBuff != NULL) { + if (ticLenAlloc >= input->ticketLen) { + output->ticket = ticBuff; + output->ticketLenAlloc = ticLenAlloc; + } + else { + WOLFSSL_MSG("ticket dynamic buffer too small but we are " + "avoiding system calls"); + ret = WOLFSSL_FAILURE; + output->ticket = ticBuff; + output->ticketLenAlloc = (word16) ticLenAlloc; + output->ticketLen = 0; + } + } + else { + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + } + } + else { + if (ticBuff != NULL) + XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + output->ticket = output->staticTicket; + output->ticketLenAlloc = 0; + } + if (input->ticketLenAlloc > 0 && ret == WOLFSSL_SUCCESS) { + /* Shouldn't happen as session should have placed this in + * the static buffer */ + XMEMCPY(output->ticket, input->ticket, + input->ticketLen); + } + } + ticBuff = NULL; + +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (preallocUsed != NULL) + *preallocUsed = 0; + + if (input->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ && + ret == WOLFSSL_SUCCESS) { + /* TicketNonce does not fit in the static buffer */ + if (!avoidSysCalls) { + output->ticketNonce.data = (byte*)XMALLOC(input->ticketNonce.len, + output->heap, DYNAMIC_TYPE_SESSION_TICK); + + if (output->ticketNonce.data == NULL) { + WOLFSSL_MSG("Failed to allocate space for ticket nonce"); + output->ticketNonce.data = output->ticketNonce.dataStatic; + output->ticketNonce.len = 0; + ret = WOLFSSL_FAILURE; + } + else { + output->ticketNonce.len = input->ticketNonce.len; + XMEMCPY(output->ticketNonce.data, input->ticketNonce.data, + input->ticketNonce.len); + ret = WOLFSSL_SUCCESS; + } + } + /* we can't do syscalls. Use prealloc buffers if provided from the + * caller. */ + else if (ticketNonceBuf != NULL && + *ticketNonceLen >= input->ticketNonce.len) { + XMEMCPY(ticketNonceBuf, input->ticketNonce.data, + input->ticketNonce.len); + *ticketNonceLen = input->ticketNonce.len; + if (preallocUsed != NULL) + *preallocUsed = 1; + ret = WOLFSSL_SUCCESS; + } + else { + WOLFSSL_MSG("TicketNonce bigger than static buffer, and we can't " + "do syscalls"); + ret = WOLFSSL_FAILURE; + } + } +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ + +#endif /* HAVE_SESSION_TICKET */ + +#ifdef HAVE_EX_DATA + if (input->type != WOLFSSL_SESSION_TYPE_CACHE && + output->type != WOLFSSL_SESSION_TYPE_CACHE) { + /* Not called with cache as that passes ownership of ex_data */ + ret = crypto_ex_cb_dup_data(&input->ex_data, &output->ex_data, + crypto_ex_cb_ctx_session); + } +#endif + + return ret; +} + +/** + * Deep copy the contents from input to output. + * @param input The source of the copy. + * @param output The destination of the copy. + * @param avoidSysCalls If true, then system calls will be avoided or an error + * will be returned if it is not possible to proceed + * without a system call. This is useful for fetching + * sessions from cache. When a cache row is locked, we + * don't want to block other threads with long running + * system calls. + * @return WOLFSSL_SUCCESS on success + * WOLFSSL_FAILURE on failure + */ +int wolfSSL_DupSession(const WOLFSSL_SESSION* input, WOLFSSL_SESSION* output, + int avoidSysCalls) +{ + return wolfSSL_DupSessionEx(input, output, avoidSysCalls, NULL, NULL, NULL); +} + +WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session) +{ + WOLFSSL_SESSION* copy; + + WOLFSSL_ENTER("wolfSSL_SESSION_dup"); + + session = ClientSessionToSession(session); + if (session == NULL) + return NULL; + +#ifdef HAVE_SESSION_TICKET + if (session->ticketLenAlloc > 0 && !session->ticket) { + WOLFSSL_MSG("Session dynamic flag is set but ticket pointer is null"); + return NULL; + } +#endif + + copy = wolfSSL_NewSession(session->heap); + if (copy != NULL && + wolfSSL_DupSession(session, copy, 0) != WOLFSSL_SUCCESS) { + wolfSSL_FreeSession(NULL, copy); + copy = NULL; + } + return copy; +} + +void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) +{ + session = ClientSessionToSession(session); + if (session == NULL) + return; + + (void)ctx; + + WOLFSSL_ENTER("wolfSSL_FreeSession"); + + if (session->ref.count > 0) { + int ret; + int isZero; + wolfSSL_RefDec(&session->ref, &isZero, &ret); + (void)ret; + if (!isZero) { + return; + } + wolfSSL_RefFree(&session->ref); + } + + WOLFSSL_MSG("wolfSSL_FreeSession full free"); + +#ifdef HAVE_EX_DATA + if (session->ownExData) { + crypto_ex_cb_free_data(session, crypto_ex_cb_ctx_session, + &session->ex_data); + } +#endif + +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS + wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data); +#endif + +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) + if (session->peer) { + wolfSSL_X509_free(session->peer); + session->peer = NULL; + } +#endif + +#ifdef HAVE_SESSION_TICKET + if (session->ticketLenAlloc > 0) { + XFREE(session->ticket, session->heap, DYNAMIC_TYPE_SESSION_TICK); + session->ticket = session->staticTicket; + session->ticketLen = 0; + session->ticketLenAlloc = 0; + } +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + if (session->ticketNonce.data != session->ticketNonce.dataStatic) { + XFREE(session->ticketNonce.data, session->heap, + DYNAMIC_TYPE_SESSION_TICK); + session->ticketNonce.data = session->ticketNonce.dataStatic; + session->ticketNonce.len = 0; + } +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ +#endif + +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS + wolfSSL_CRYPTO_cleanup_ex_data(&session->ex_data); +#endif + + /* Make sure masterSecret is zeroed. */ + ForceZero(session->masterSecret, SECRET_LEN); + /* Session ID is sensitive information too. */ + ForceZero(session->sessionID, ID_LEN); + + if (session->type == WOLFSSL_SESSION_TYPE_HEAP) { + XFREE(session, session->heap, DYNAMIC_TYPE_SESSION); + } +} + +/* DO NOT use this API internally. Use wolfSSL_FreeSession directly instead + * and pass in the ctx parameter if possible (like from ssl->ctx). */ +void wolfSSL_SESSION_free(WOLFSSL_SESSION* session) +{ + session = ClientSessionToSession(session); + wolfSSL_FreeSession(NULL, session); +} + +#if defined(OPENSSL_EXTRA) || defined(HAVE_EXT_CACHE) + +/** +* set cipher to WOLFSSL_SESSION from WOLFSSL_CIPHER +* @param session a pointer to WOLFSSL_SESSION structure +* @param cipher a function pointer to WOLFSSL_CIPHER +* @return WOLFSSL_SUCCESS on success, otherwise WOLFSSL_FAILURE +*/ +int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session, + const WOLFSSL_CIPHER* cipher) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_set_cipher"); + + session = ClientSessionToSession(session); + /* sanity check */ + if (session == NULL || cipher == NULL) { + WOLFSSL_MSG("bad argument"); + return WOLFSSL_FAILURE; + } + session->cipherSuite0 = cipher->cipherSuite0; + session->cipherSuite = cipher->cipherSuite; + + WOLFSSL_LEAVE("wolfSSL_SESSION_set_cipher", WOLFSSL_SUCCESS); + return WOLFSSL_SUCCESS; +} +#endif /* OPENSSL_EXTRA || HAVE_EXT_CACHE */ + +const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session) +{ + session = ClientSessionToSession(session); + if (session == NULL) { + return NULL; + } + +#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) + #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) + return GetCipherNameIana(session->cipherSuite0, session->cipherSuite); + #else + return GetCipherNameInternal(session->cipherSuite0, + session->cipherSuite); + #endif +#else + return NULL; +#endif +} + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) +const unsigned char *wolfSSL_SESSION_get0_id_context( + const WOLFSSL_SESSION *sess, unsigned int *sid_ctx_length) +{ + return wolfSSL_SESSION_get_id((WOLFSSL_SESSION *)sess, sid_ctx_length); +} +int wolfSSL_SESSION_set1_id(WOLFSSL_SESSION *s, + const unsigned char *sid, unsigned int sid_len) +{ + if (s == NULL) { + return WOLFSSL_FAILURE; + } + if (sid_len > ID_LEN) { + return WOLFSSL_FAILURE; + } + s->sessionIDSz = sid_len; + if (sid != s->sessionID) { + XMEMCPY(s->sessionID, sid, sid_len); + } + return WOLFSSL_SUCCESS; +} + +int wolfSSL_SESSION_set1_id_context(WOLFSSL_SESSION *s, + const unsigned char *sid_ctx, unsigned int sid_ctx_len) +{ + if (s == NULL) { + return WOLFSSL_FAILURE; + } + if (sid_ctx_len > ID_LEN) { + return WOLFSSL_FAILURE; + } + s->sessionCtxSz = sid_ctx_len; + if (sid_ctx != s->sessionCtx) { + XMEMCPY(s->sessionCtx, sid_ctx, sid_ctx_len); + } + + return WOLFSSL_SUCCESS; +} + +#endif + +#ifdef OPENSSL_EXTRA + +/* Return the total number of sessions */ +long wolfSSL_CTX_sess_number(WOLFSSL_CTX* ctx) +{ + word32 total = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_sess_number"); + (void)ctx; + +#if defined(WOLFSSL_SESSION_STATS) && !defined(NO_SESSION_CACHE) + if (wolfSSL_get_session_stats(NULL, &total, NULL, NULL) != + WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error getting session stats"); + } +#else + WOLFSSL_MSG("Please use macro WOLFSSL_SESSION_STATS for session stats"); +#endif + + return (long)total; +} + +#endif + +#ifdef SESSION_CERTS + +/* get session ID */ +WOLFSSL_ABI +const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session) +{ + WOLFSSL_ENTER("wolfSSL_get_sessionID"); + session = ClientSessionToSession(session); + if (session) + return session->sessionID; + + return NULL; +} + +#endif + +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ + defined(HAVE_EX_DATA) + +int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data) +{ + int ret = WOLFSSL_FAILURE; + WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data"); +#ifdef HAVE_EX_DATA + session = ClientSessionToSession(session); + if (session != NULL) { +#ifndef NO_SESSION_CACHE + if (!session->ownExData) { + /* Need to update in cache */ + SESSION_ex_data_cache_update(session, idx, data, 0, NULL, &ret); + } + else +#endif + { + ret = wolfSSL_CRYPTO_set_ex_data(&session->ex_data, idx, data); + } + } +#else + (void)session; + (void)idx; + (void)data; +#endif + return ret; +} + +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +int wolfSSL_SESSION_set_ex_data_with_cleanup( + WOLFSSL_SESSION* session, + int idx, + void* data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data_with_cleanup"); + session = ClientSessionToSession(session); + if(session != NULL) { + return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&session->ex_data, idx, + data, cleanup_routine); + } + return WOLFSSL_FAILURE; +} +#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ + +void* wolfSSL_SESSION_get_ex_data(const WOLFSSL_SESSION* session, int idx) +{ + void* ret = NULL; + WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_data"); +#ifdef HAVE_EX_DATA + session = ClientSessionToSession(session); + if (session != NULL) { +#ifndef NO_SESSION_CACHE + if (!session->ownExData) { + /* Need to retrieve the data from the session cache */ + SESSION_ex_data_cache_update((WOLFSSL_SESSION*)session, idx, NULL, + 1, &ret, NULL); + } + else +#endif + { + ret = wolfSSL_CRYPTO_get_ex_data(&session->ex_data, idx); + } + } +#else + (void)session; + (void)idx; +#endif + return ret; +} +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_EX_DATA */ + +#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ + (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB))) +#ifdef HAVE_EX_DATA +int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, + WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_get_ex_new_index"); + return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_SESSION, ctx_l, + ctx_ptr, new_func, dup_func, free_func); +} +#endif +#endif + + +#if defined(OPENSSL_ALL) || \ + defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + +const byte* wolfSSL_SESSION_get_id(const WOLFSSL_SESSION* sess, + unsigned int* idLen) +{ + WOLFSSL_ENTER("wolfSSL_SESSION_get_id"); + sess = ClientSessionToSession(sess); + if (sess == NULL || idLen == NULL) { + WOLFSSL_MSG("Bad func args. Please provide idLen"); + return NULL; + } +#ifdef HAVE_SESSION_TICKET + if (sess->haveAltSessionID) { + *idLen = ID_LEN; + return sess->altSessionID; + } +#endif + *idLen = sess->sessionIDSz; + return sess->sessionID; +} + +#if (defined(HAVE_SESSION_TICKET) || defined(SESSION_CERTS)) && \ + !defined(NO_FILESYSTEM) + +#ifndef NO_BIO + +#if defined(SESSION_CERTS) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)) +static const char* wolfSSL_internal_get_version(const ProtocolVersion* version); + +/* returns a pointer to the protocol used by the session */ +static const char* wolfSSL_SESSION_get_protocol(const WOLFSSL_SESSION* in) +{ + in = ClientSessionToSession(in); + return wolfSSL_internal_get_version((ProtocolVersion*)&in->version); +} +#endif + +/* returns true (non 0) if the session has EMS (extended master secret) */ +static int wolfSSL_SESSION_haveEMS(const WOLFSSL_SESSION* in) +{ + in = ClientSessionToSession(in); + if (in == NULL) + return 0; + return in->haveEMS; +} + +#if defined(HAVE_SESSION_TICKET) +/* prints out the ticket to bio passed in + * return WOLFSSL_SUCCESS on success + */ +static int wolfSSL_SESSION_print_ticket(WOLFSSL_BIO* bio, + const WOLFSSL_SESSION* in, const char* tab) +{ + unsigned short i, j, z, sz; + short tag = 0; + byte* pt; + + + in = ClientSessionToSession(in); + if (in == NULL || bio == NULL) { + return BAD_FUNC_ARG; + } + + sz = in->ticketLen; + pt = in->ticket; + + if (wolfSSL_BIO_printf(bio, "%s\n", (sz == 0)? " NONE": "") <= 0) + return WOLFSSL_FAILURE; + + for (i = 0; i < sz;) { + char asc[16]; + XMEMSET(asc, 0, sizeof(asc)); + + if (sz - i < 16) { + if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag + (sz - i)) <= 0) + return WOLFSSL_FAILURE; + } + else { + if (wolfSSL_BIO_printf(bio, "%s%04X -", tab, tag) <= 0) + return WOLFSSL_FAILURE; + } + for (j = 0; i < sz && j < 8; j++,i++) { + asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; + if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0) + return WOLFSSL_FAILURE; + } + + if (i < sz) { + asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; + if (wolfSSL_BIO_printf(bio, "-%02X", pt[i]) <= 0) + return WOLFSSL_FAILURE; + j++; + i++; + } + + for (; i < sz && j < 16; j++,i++) { + asc[j] = ((pt[i])&0x6f)>='A'?((pt[i])&0x6f):'.'; + if (wolfSSL_BIO_printf(bio, " %02X", pt[i]) <= 0) + return WOLFSSL_FAILURE; + } + + /* pad out spacing */ + for (z = j; z < 17; z++) { + if (wolfSSL_BIO_printf(bio, " ") <= 0) + return WOLFSSL_FAILURE; + } + + for (z = 0; z < j; z++) { + if (wolfSSL_BIO_printf(bio, "%c", asc[z]) <= 0) + return WOLFSSL_FAILURE; + } + if (wolfSSL_BIO_printf(bio, "\n") <= 0) + return WOLFSSL_FAILURE; + + tag += 16; + } + return WOLFSSL_SUCCESS; +} +#endif /* HAVE_SESSION_TICKET */ + + +/* prints out the session information in human readable form + * return WOLFSSL_SUCCESS on success + */ +int wolfSSL_SESSION_print(WOLFSSL_BIO *bp, const WOLFSSL_SESSION *session) +{ + const unsigned char* pt; + unsigned char buf[SECRET_LEN]; + unsigned int sz = 0, i; + int ret; + + session = ClientSessionToSession(session); + if (session == NULL) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_printf(bp, "%s\n", "SSL-Session:") <= 0) + return WOLFSSL_FAILURE; + +#if defined(SESSION_CERTS) || (defined(WOLFSSL_TLS13) && \ + defined(HAVE_SESSION_TICKET)) + if (wolfSSL_BIO_printf(bp, " Protocol : %s\n", + wolfSSL_SESSION_get_protocol(session)) <= 0) + return WOLFSSL_FAILURE; +#endif + + if (wolfSSL_BIO_printf(bp, " Cipher : %s\n", + wolfSSL_SESSION_CIPHER_get_name(session)) <= 0) + return WOLFSSL_FAILURE; + + pt = wolfSSL_SESSION_get_id(session, &sz); + if (wolfSSL_BIO_printf(bp, " Session-ID: ") <= 0) + return WOLFSSL_FAILURE; + + for (i = 0; i < sz; i++) { + if (wolfSSL_BIO_printf(bp, "%02X", pt[i]) <= 0) + return WOLFSSL_FAILURE; + } + if (wolfSSL_BIO_printf(bp, "\n") <= 0) + return WOLFSSL_FAILURE; + + if (wolfSSL_BIO_printf(bp, " Session-ID-ctx: \n") <= 0) + return WOLFSSL_FAILURE; + + ret = wolfSSL_SESSION_get_master_key(session, buf, sizeof(buf)); + if (wolfSSL_BIO_printf(bp, " Master-Key: ") <= 0) + return WOLFSSL_FAILURE; + + if (ret > 0) { + sz = (unsigned int)ret; + for (i = 0; i < sz; i++) { + if (wolfSSL_BIO_printf(bp, "%02X", buf[i]) <= 0) + return WOLFSSL_FAILURE; + } + } + if (wolfSSL_BIO_printf(bp, "\n") <= 0) + return WOLFSSL_FAILURE; + + /* @TODO PSK identity hint and SRP */ + + if (wolfSSL_BIO_printf(bp, " TLS session ticket:") <= 0) + return WOLFSSL_FAILURE; + +#ifdef HAVE_SESSION_TICKET + if (wolfSSL_SESSION_print_ticket(bp, session, " ") != WOLFSSL_SUCCESS) + return WOLFSSL_FAILURE; +#endif + +#if !defined(NO_SESSION_CACHE) && (defined(OPENSSL_EXTRA) || \ + defined(HAVE_EXT_CACHE)) + if (wolfSSL_BIO_printf(bp, " Start Time: %ld\n", + wolfSSL_SESSION_get_time(session)) <= 0) + return WOLFSSL_FAILURE; + + if (wolfSSL_BIO_printf(bp, " Timeout : %ld (sec)\n", + wolfSSL_SESSION_get_timeout(session)) <= 0) + return WOLFSSL_FAILURE; +#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */ + + /* @TODO verify return code print */ + + if (wolfSSL_BIO_printf(bp, " Extended master secret: %s\n", + (wolfSSL_SESSION_haveEMS(session) == 0)? "no" : "yes") <= 0) + return WOLFSSL_FAILURE; + + return WOLFSSL_SUCCESS; +} + +#endif /* !NO_BIO */ +#endif /* (HAVE_SESSION_TICKET || SESSION_CERTS) && !NO_FILESYSTEM */ + +#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX || + * WOLFSSL_HAPROXY */ + +#ifdef OPENSSL_EXTRA +/** + * Determine whether a WOLFSSL_SESSION object can be used for resumption + * @param s a pointer to WOLFSSL_SESSION structure + * @return return 1 if session is resumable, otherwise 0. + */ +int wolfSSL_SESSION_is_resumable(const WOLFSSL_SESSION *s) +{ + s = ClientSessionToSession(s); + if (s == NULL) + return 0; + +#ifdef HAVE_SESSION_TICKET + if (s->ticketLen > 0) + return 1; +#endif + + if (s->sessionIDSz > 0) + return 1; + + return 0; +} +#endif /* OPENSSL_EXTRA */ + +#endif /* !WOLFSSL_SSL_SESS_INCLUDED */ + diff --git a/src/src/tls.c b/src/src/tls.c index a28568c..6529216 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -48,7 +48,7 @@ #ifdef HAVE_CURVE448 #include #endif -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER #include #ifdef WOLFSSL_WC_KYBER #include @@ -212,7 +212,8 @@ int BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender) ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz, (byte*)hashes, ctx); } - if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->TlsFinishedCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif { PRIVATE_KEY_UNLOCK(); @@ -300,6 +301,98 @@ ProtocolVersion MakeTLSv1_3(void) } #endif +#if defined(HAVE_SUPPORTED_CURVES) +/* Sets the key exchange groups in rank order on a context. + * + * ctx SSL/TLS context object. + * groups Array of groups. + * count Number of groups in array. + * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or + * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success. + */ +int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count) +{ + int ret, i; + + WOLFSSL_ENTER("wolfSSL_CTX_set_groups"); + if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT) + return BAD_FUNC_ARG; + if (!IsTLS_ex(ctx->method->version)) + return BAD_FUNC_ARG; + + #ifdef WOLFSSL_TLS13 + ctx->numGroups = 0; + #endif + #if !defined(NO_TLS) + TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap); + #endif /* !NO_TLS */ + for (i = 0; i < count; i++) { + /* Call to wolfSSL_CTX_UseSupportedCurve also checks if input groups + * are valid */ + if ((ret = wolfSSL_CTX_UseSupportedCurve(ctx, (word16)groups[i])) + != WOLFSSL_SUCCESS) { + #if !defined(NO_TLS) + TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap); + #endif /* !NO_TLS */ + return ret; + } + #ifdef WOLFSSL_TLS13 + ctx->group[i] = (word16)groups[i]; + #endif + } + #ifdef WOLFSSL_TLS13 + ctx->numGroups = (byte)count; + #endif + + return WOLFSSL_SUCCESS; +} + +/* Sets the key exchange groups in rank order. + * + * ssl SSL/TLS object. + * groups Array of groups. + * count Number of groups in array. + * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or + * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success. + */ +int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count) +{ + int ret, i; + + WOLFSSL_ENTER("wolfSSL_set_groups"); + if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT) + return BAD_FUNC_ARG; + if (!IsTLS_ex(ssl->version)) + return BAD_FUNC_ARG; + + #ifdef WOLFSSL_TLS13 + ssl->numGroups = 0; + #endif + #if !defined(NO_TLS) + TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap); + #endif /* !NO_TLS */ + for (i = 0; i < count; i++) { + /* Call to wolfSSL_UseSupportedCurve also checks if input groups + * are valid */ + if ((ret = wolfSSL_UseSupportedCurve(ssl, (word16)groups[i])) + != WOLFSSL_SUCCESS) { + #if !defined(NO_TLS) + TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap); + #endif /* !NO_TLS */ + return ret; + } + #ifdef WOLFSSL_TLS13 + ssl->group[i] = (word16)groups[i]; + #endif + } + #ifdef WOLFSSL_TLS13 + ssl->numGroups = (byte)count; + #endif + + return WOLFSSL_SUCCESS; +} +#endif /* HAVE_SUPPORTED_CURVES */ + #ifndef WOLFSSL_NO_TLS12 #ifdef HAVE_EXTENDED_MASTER @@ -396,9 +489,10 @@ int DeriveTlsKeys(WOLFSSL* ssl) void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl); ret = ssl->ctx->GenSessionKeyCb(ssl, ctx); } - if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->GenSessionKeyCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif - ret = _DeriveTlsKeys(key_dig, key_dig_len, + ret = _DeriveTlsKeys(key_dig, (word32)key_dig_len, ssl->arrays->masterSecret, SECRET_LEN, ssl->arrays->serverRandom, ssl->arrays->clientRandom, IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, @@ -576,7 +670,8 @@ int MakeTlsMasterSecret(WOLFSSL* ssl) void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl); ret = ssl->ctx->GenMasterCb(ssl, ctx); } - if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE) + if (!ssl->ctx->GenMasterCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif { ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret, @@ -586,47 +681,13 @@ int MakeTlsMasterSecret(WOLFSSL* ssl) ssl->specs.mac_algorithm, ssl->heap, ssl->devId); } } +#ifdef HAVE_SECRET_CALLBACK + if (ret == 0 && ssl->tlsSecretCb != NULL) { + ret = ssl->tlsSecretCb(ssl, ssl->arrays->masterSecret, + SECRET_LEN, ssl->tlsSecretCtx); + } +#endif /* HAVE_SECRET_CALLBACK */ if (ret == 0) { - #ifdef SHOW_SECRETS - /* Wireshark Pre-Master-Secret Format: - * CLIENT_RANDOM - */ - const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM"; - int i, pmsPos = 0; - char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1]; - - XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ", - CLIENT_RANDOM_LABEL); - pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1; - for (i = 0; i < RAN_LEN; i++) { - XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x", - ssl->arrays->clientRandom[i]); - pmsPos += 2; - } - XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " "); - pmsPos += 1; - for (i = 0; i < SECRET_LEN; i++) { - XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x", - ssl->arrays->masterSecret[i]); - pmsPos += 2; - } - XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n"); - pmsPos += 1; - - /* print master secret */ - puts(pmsBuf); - - #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE) - { - FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a"); - if (f != XBADFILE) { - XFWRITE(pmsBuf, 1, pmsPos, f); - XFCLOSE(f); - } - } - #endif - #endif /* SHOW_SECRETS */ - ret = DeriveTlsKeys(ssl); } @@ -724,7 +785,7 @@ int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content, */ static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hmac->macType) { #ifndef NO_SHA @@ -758,6 +819,7 @@ static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz) #endif /* WOLFSSL_SM3 */ default: + ret = BAD_FUNC_ARG; break; } @@ -772,7 +834,7 @@ static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz) */ static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hmac->macType) { #ifndef NO_SHA @@ -806,6 +868,7 @@ static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash) #endif /* WOLFSSL_SM3 */ default: + ret = BAD_FUNC_ARG; break; } @@ -820,7 +883,7 @@ static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash) */ static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); wc_HashAlg hash; enum wc_HashType hashType = (enum wc_HashType)hmac->macType; int digestSz = wc_HashGetDigestSize(hashType); @@ -829,12 +892,16 @@ static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac) if ((digestSz >= 0) && (blockSz >= 0)) { ret = wc_HashInit(&hash, hashType); } + else { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad, - blockSz); + (word32)blockSz); if (ret == 0) ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash, - digestSz); + (word32)digestSz); if (ret == 0) ret = wc_HashFinal(&hash, hashType, mac); wc_HashFree(&hash, hashType); @@ -942,7 +1009,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes); c32toa(realLen << 3, lenBytes + sizeof(word32)); - ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz); + ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, (word32)blockSz); if (ret != 0) return ret; @@ -961,7 +1028,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, safeBlocks = 0; XMEMSET(digest, 0, macLen); - k = safeBlocks * blockSz; + k = (unsigned int)(safeBlocks * blockSz); for (i = safeBlocks; i < blocks; i++) { unsigned char hashBlock[WC_MAX_BLOCK_SIZE]; unsigned char isEocBlock = ctMaskEq(i, eocBlock); @@ -989,7 +1056,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, hashBlock[j] = b; } - ret = Hmac_HashUpdate(hmac, hashBlock, blockSz); + ret = Hmac_HashUpdate(hmac, hashBlock, (word32)blockSz); if (ret != 0) return ret; ret = Hmac_HashFinalRaw(hmac, hashBlock); @@ -1099,9 +1166,9 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, maxSz &= ~(0 - (maxSz >> 31)); /* Calculate #blocks processed in HMAC for max and real data. */ - blocks = maxSz >> blockBits; + blocks = (int)(maxSz >> blockBits); blocks += ((maxSz + padSz) % blockSz) < padSz; - msgBlocks = realSz >> blockBits; + msgBlocks = (int)(realSz >> blockBits); /* #Extra blocks to process. */ blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0); /* Calculate whole blocks. */ @@ -1110,8 +1177,8 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ); if (ret == 0) { /* Fill the rest of the block with any available data. */ - word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz; - currSz |= ctMaskGTE(msgSz, blockSz) & blockSz; + word32 currSz = ctMaskLT((int)msgSz, blockSz) & msgSz; + currSz |= ctMaskGTE((int)msgSz, blockSz) & blockSz; currSz -= WOLFSSL_TLS_HMAC_INNER_SZ; currSz &= ~(0 - (currSz >> 31)); ret = wc_HmacUpdate(hmac, in, currSz); @@ -2349,12 +2416,13 @@ int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size, #ifndef NO_WOLFSSL_SERVER /** Tells the SNI requested by the client. */ -word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data) +word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data, + byte ignoreStatus) { TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME); SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type); - if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) { + if (sni && (ignoreStatus || sni->status != WOLFSSL_SNI_NO_MATCH)) { switch (sni->type) { case WOLFSSL_SNI_HOST_NAME: if (data) { @@ -2929,6 +2997,9 @@ static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length, WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E); return UNKNOWN_MAX_FRAG_LEN_E; } + if (ssl->session != NULL) { + ssl->session->mfl = *input; + } #ifndef NO_WOLFSSL_SERVER if (isRequest) { @@ -3329,7 +3400,8 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); /* Let's not error out the connection if we can't verify our * cert */ - if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E) + if (ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E) || + ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E)) ret = 0; return ret; } @@ -3507,10 +3579,20 @@ int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type, #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 +static void TLSX_CSR2_FreePendingSigners(Signer *s, void* heap) +{ + Signer* next; + while(s) { + next = s->next; + FreeSigner(s, heap); + s = next; + } +} static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap) { CertificateStatusRequestItemV2* next; + TLSX_CSR2_FreePendingSigners(csr2->pendingSigners, heap); for (; csr2; csr2 = next) { next = csr2->next; @@ -3781,6 +3863,83 @@ static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length, return 0; } +static CertificateStatusRequestItemV2* TLSX_CSR2_GetMulti(TLSX *extensions) +{ + TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2); + CertificateStatusRequestItemV2* csr2 = extension ? + (CertificateStatusRequestItemV2*)extension->data : NULL; + + for (; csr2; csr2 = csr2->next) { + if (csr2->status_type == WOLFSSL_CSR2_OCSP_MULTI) + return csr2; + } + return NULL; +} + +int TLSX_CSR2_IsMulti(TLSX *extensions) +{ + return TLSX_CSR2_GetMulti(extensions) != NULL; +} + +int TLSX_CSR2_AddPendingSigner(TLSX *extensions, Signer *s) +{ + CertificateStatusRequestItemV2* csr2; + + csr2 = TLSX_CSR2_GetMulti(extensions); + if (!csr2) + return -1; + + s->next = csr2->pendingSigners; + csr2->pendingSigners = s; + return 0; +} + +Signer* TLSX_CSR2_GetPendingSigners(TLSX *extensions) +{ + CertificateStatusRequestItemV2* csr2; + + csr2 = TLSX_CSR2_GetMulti(extensions); + if (!csr2) + return NULL; + + return csr2->pendingSigners; +} + +int TLSX_CSR2_ClearPendingCA(WOLFSSL *ssl) +{ + CertificateStatusRequestItemV2* csr2; + + csr2 = TLSX_CSR2_GetMulti(ssl->extensions); + if (csr2 == NULL) + return 0; + + TLSX_CSR2_FreePendingSigners(csr2->pendingSigners, SSL_CM(ssl)->heap); + csr2->pendingSigners = NULL; + return 0; +} + +int TLSX_CSR2_MergePendingCA(WOLFSSL* ssl) +{ + CertificateStatusRequestItemV2* csr2; + Signer *s, *next; + int r = 0; + + csr2 = TLSX_CSR2_GetMulti(ssl->extensions); + if (csr2 == NULL) + return 0; + + s = csr2->pendingSigners; + while (s != NULL) { + next = s->next; + r = AddSigner(SSL_CM(ssl), s); + if (r != 0) + FreeSigner(s, SSL_CM(ssl)->heap); + s = next; + } + csr2->pendingSigners = NULL; + return r; +} + int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer, void* heap) { @@ -3862,10 +4021,10 @@ int TLSX_CSR2_ForceRequest(WOLFSSL* ssl) /* followed by */ case WOLFSSL_CSR2_OCSP_MULTI: - if (SSL_CM(ssl)->ocspEnabled) { - csr2->request.ocsp[0].ssl = ssl; + if (SSL_CM(ssl)->ocspEnabled && csr2->requests >= 1) { + csr2->request.ocsp[csr2->requests-1].ssl = ssl; return CheckOcspRequest(SSL_CM(ssl)->ocsp, - &csr2->request.ocsp[0], NULL, NULL); + &csr2->request.ocsp[csr2->requests-1], NULL, NULL); } else { WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL); @@ -3963,7 +4122,7 @@ int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type, #ifdef HAVE_SUPPORTED_CURVES #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \ - && !defined(HAVE_FFDHE) && !defined(HAVE_PQC) + && !defined(HAVE_FFDHE) && !defined(WOLFSSL_HAVE_KYBER) #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \ Use --enable-ecc and/or --enable-liboqs in the configure script or \ define HAVE_ECC. Alternatively use FFDHE for DH cipher suites. @@ -4031,7 +4190,7 @@ static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap) static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name, void* heap) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); while (list) { if (list->name == name) { @@ -4052,7 +4211,7 @@ static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name, static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); while (list) { if (list->format == format) { @@ -4339,7 +4498,7 @@ int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input, ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap); /* If it is BAD_FUNC_ARG then it is a group we do not support, but * that is fine. */ - if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) { + if (ret != WOLFSSL_SUCCESS && ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { return ret; } } @@ -4709,6 +4868,7 @@ int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second, int ephmSuite = 0; word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */ int key = 0; /* validate key */ + int foundCurve = 0; /* Found at least one supported curve */ (void)oid; @@ -4870,6 +5030,8 @@ int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second, default: continue; /* unsupported curve */ } + foundCurve = 1; + #ifdef HAVE_ECC /* Set default Oid */ if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) { @@ -5014,6 +5176,10 @@ int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second, } } + /* Check we found at least one supported curve */ + if (!foundCurve) + return 0; + *ecdhCurveOID = ssl->ecdhCurveOID; /* Choose the default if it is at the required strength. */ #ifdef HAVE_ECC @@ -5237,7 +5403,7 @@ static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data, static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte isRequest) { - int ret = SECURE_RENEGOTIATION_E; + int ret = WC_NO_ERR_TRACE(SECURE_RENEGOTIATION_E); if (length >= OPAQUE8_LEN) { if (isRequest) { @@ -5247,7 +5413,7 @@ static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input, if (ret == WOLFSSL_SUCCESS) ret = 0; } - if (ret != 0 && ret != SECURE_RENEGOTIATION_E) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(SECURE_RENEGOTIATION_E)) { } else if (ssl->secure_renegotiation == NULL) { } @@ -5317,6 +5483,12 @@ static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input, } #endif } + else { + ret = SECURE_RENEGOTIATION_E; + } + } + else { + ret = SECURE_RENEGOTIATION_E; } if (ret != 0) { @@ -5510,7 +5682,7 @@ static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input, WOLFSSL_MSG("Process client ticket rejected, not using"); ssl->options.rejectTicket = 1; ret = 0; /* not fatal */ - } else if (ret == VERSION_ERROR) { + } else if (ret == WC_NO_ERR_TRACE(VERSION_ERROR)) { WOLFSSL_MSG("Process client ticket rejected, bad TLS version"); ssl->options.rejectTicket = 1; ret = 0; /* not fatal */ @@ -5812,7 +5984,7 @@ static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap) static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte isRequest) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); word16 profile_len = 0; word16 profile_value = 0; word16 offset = 0; @@ -6120,8 +6292,12 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) { tls13minor = (byte)DTLSv1_3_MINOR; + #ifndef WOLFSSL_NO_TLS12 tls12minor = (byte)DTLSv1_2_MINOR; + #endif + #ifndef NO_OLD_TLS tls11minor = (byte)DTLS_MINOR; + #endif isDtls = 1; } #endif /* WOLFSSL_DTLS13 */ @@ -7181,7 +7357,7 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) kse->pubKey, &kse->pubKeyLen /* public */ ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -7494,7 +7670,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13GenEccKeyPair(ssl, kse); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return ret; } #endif @@ -7511,7 +7687,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) if (ret == 0) { #ifdef WOLFSSL_ASYNC_CRYPT /* Detect when private key generation is done */ - if (ssl->error == WC_PENDING_E && + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) && eccKey->type == ECC_PRIVATEKEY) { ret = 0; /* ECC Key Generation is done */ } @@ -7526,7 +7702,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) } } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif } @@ -7585,7 +7761,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) return ret; } -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER static int kyber_id2type(int id, int *type) { int ret = 0; @@ -7689,7 +7865,7 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) findEccPqc(&ecc_group, &oqs_group, kse->group); ret = kyber_id2type(oqs_group, &type); - if (ret == NOT_COMPILED_IN) { + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { WOLFSSL_MSG("Invalid Kyber algorithm specified."); ret = BAD_FUNC_ARG; } @@ -7788,7 +7964,7 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) return ret; } -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_HAVE_KYBER */ /* Generate a secret/key using the key share entry. * @@ -7805,7 +7981,7 @@ int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse) ret = TLSX_KeyShare_GenX25519Key(ssl, kse); else if (kse->group == WOLFSSL_ECC_X448) ret = TLSX_KeyShare_GenX448Key(ssl, kse); -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group)) ret = TLSX_KeyShare_GenPqcKey(ssl, kse); #endif @@ -7843,7 +8019,7 @@ static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap) wc_curve448_free((curve448_key*)current->key); #endif } -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group)) { if (current->key != NULL) { ForceZero((byte*)current->key, current->keyLen); @@ -8050,7 +8226,7 @@ static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) NULL, 0 ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -8322,7 +8498,7 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) } #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return ret; } ret = 0; @@ -8364,7 +8540,7 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) ssl->options.side ); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif } @@ -8398,7 +8574,7 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) return ret; } -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER /* Process the Kyber key share extension on the client side. * * ssl The SSL/TLS object. @@ -8437,7 +8613,7 @@ static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke, keyShareEntry->keLen); ssl->arrays->preMasterSz = keyShareEntry->keLen; - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET) + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET); keyShareEntry->ke = NULL; keyShareEntry->keLen = 0; return 0; @@ -8567,7 +8743,7 @@ static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) wc_KyberKey_Free(kem); return ret; } -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_HAVE_KYBER */ /* Process the key share extension on the client side. * @@ -8593,7 +8769,7 @@ static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry); else if (keyShareEntry->group == WOLFSSL_ECC_X448) ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry); -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group)) ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry); #endif @@ -8644,7 +8820,7 @@ static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input, if (keLen > length - offset) return BUFFER_ERROR; -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER if (WOLFSSL_NAMED_GROUP_IS_PQC(group) && ssl->options.side == WOLFSSL_SERVER_END) { /* For KEMs, the public key is not stored. Casting away const because @@ -8823,7 +8999,7 @@ int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length, /* Not in list sent if there isn't a private key. */ if (keyShareEntry == NULL || (keyShareEntry->key == NULL - #if !defined(NO_DH) || defined(HAVE_PQC) + #if !defined(NO_DH) || defined(WOLFSSL_HAVE_KYBER) && keyShareEntry->privKey == NULL #endif )) { @@ -8845,7 +9021,7 @@ int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length, #ifdef WOLFSSL_ASYNC_CRYPT /* only perform find and clear TLSX if not returning from async */ - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* Check the selected group was supported by ClientHello extensions. */ @@ -8915,7 +9091,7 @@ static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap, return 0; } -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER static int server_generate_pqc_ciphertext(WOLFSSL* ssl, KeyShareEntry* keyShareEntry, byte* data, word16 len) { @@ -9076,7 +9252,7 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, wc_KyberKey_Free(kem); return ret; } -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_HAVE_KYBER */ /* Use the data to create a new key share object in the extensions. * @@ -9125,7 +9301,7 @@ int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data, } -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER if (WOLFSSL_NAMED_GROUP_IS_PQC(group) && ssl->options.side == WOLFSSL_SERVER_END) { ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data, @@ -9292,16 +9468,19 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) break; #endif #endif - #ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: + case WOLFSSL_P256_KYBER_LEVEL1: #endif #ifdef WOLFSSL_KYBER768 case WOLFSSL_KYBER_LEVEL3: + case WOLFSSL_P384_KYBER_LEVEL3: #endif #ifdef WOLFSSL_KYBER1024 case WOLFSSL_KYBER_LEVEL5: + case WOLFSSL_P521_KYBER_LEVEL5: #endif break; #elif defined(HAVE_LIBOQS) @@ -9316,7 +9495,7 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) int id; findEccPqc(NULL, &namedGroup, namedGroup); ret = kyber_id2type(namedGroup, &id); - if (ret == NOT_COMPILED_IN) { + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { return 0; } @@ -9329,7 +9508,7 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) case WOLFSSL_KYBER_LEVEL1: break; #endif - #endif /* HAVE_PQC */ +#endif default: return 0; } @@ -9378,12 +9557,15 @@ static const word16 preferredGroup[] = { #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 WOLFSSL_KYBER_LEVEL1, + WOLFSSL_P256_KYBER_LEVEL1, #endif #ifdef WOLFSSL_KYBER768 WOLFSSL_KYBER_LEVEL3, + WOLFSSL_P384_KYBER_LEVEL3, #endif #ifdef WOLFSSL_KYBER1024 WOLFSSL_KYBER_LEVEL5, + WOLFSSL_P521_KYBER_LEVEL5, #endif #elif defined(HAVE_LIBOQS) /* These require a runtime call to TLSX_KeyShare_IsSupported to use */ @@ -9487,7 +9669,7 @@ int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions) kse = (KeyShareEntry*)extension->data; /* We should not be computing keys if we are only going to advertise * our choice here. */ - if (kse != NULL && kse->lastRet == WC_PENDING_E) { + if (kse != NULL && kse->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) { WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA); return BAD_KEY_SHARE_DATA; } @@ -9583,7 +9765,7 @@ int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length, case WOLFSSL_CKS_SIGSPEC_EXTERNAL: default: /* All other values (including external) are not. */ - return WOLFSSL_NOT_IMPLEMENTED; + return BAD_FUNC_ARG; } } @@ -9618,7 +9800,7 @@ int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length, for (j = 0; j < length; j++) { if (ssl->sigSpec[i] == input[j]) { /* Got the match, set to this one. */ - ret = wolfSSL_UseCKS(ssl, &ssl->peerSigSpec[i], 1); + ret = wolfSSL_UseCKS(ssl, &ssl->sigSpec[i], 1); if (ret == WOLFSSL_SUCCESS) { ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap); TLSX_SetResponse(ssl, TLSX_CKS); @@ -9659,16 +9841,20 @@ int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions, if (extension && extension->resp == 1) { /* Outside of the async case this path should not be taken. */ - int ret = INCOMPLETE_DATA; + int ret = WC_NO_ERR_TRACE(INCOMPLETE_DATA); #ifdef WOLFSSL_ASYNC_CRYPT /* in async case make sure key generation is finalized */ KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data; - if (serverKSE && serverKSE->lastRet == WC_PENDING_E) { + if (serverKSE && serverKSE->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) { if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) *searched = 1; ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE); } + else #endif + { + ret = INCOMPLETE_DATA; + } return ret; } @@ -9697,7 +9883,7 @@ int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions, if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) { /* Check max value supported. */ if (clientKSE->group > WOLFSSL_ECC_MAX) { -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) #endif continue; @@ -9743,7 +9929,7 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) serverKSE = (KeyShareEntry*)extension->data; if (serverKSE != NULL) { /* in async case make sure key generation is finalized */ - if (serverKSE->lastRet == WC_PENDING_E) + if (serverKSE->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE); else if (serverKSE->lastRet == 0) return 0; @@ -9762,7 +9948,7 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) return ret; if (clientKSE->key == NULL) { -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) { /* Going to need the public key (AKA ciphertext). */ serverKSE->pubKey = clientKSE->pubKey; @@ -9855,7 +10041,7 @@ int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl) #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, NULL); /* Check for error */ - if (ret != WC_NO_PENDING_E && ret < 0) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E) && ret < 0) { return ret; } #endif @@ -11212,8 +11398,10 @@ static int TLSX_ClientCertificateType_GetSize(WOLFSSL* ssl, byte msgType) ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN); } else if (msgType == server_hello || msgType == encrypted_extensions) { - /* sever side */ + /* server side */ cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;/* must be one */ + if (cnt != 1) + return SANITY_MSG_E; ret = OPAQUE8_LEN; } else { @@ -11668,7 +11856,7 @@ static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset) /* get size then write */ ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen); - if (ret != LENGTH_ONLY_E) + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen); @@ -11805,7 +11993,7 @@ static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech) /* get the size of the raw configs */ ret = GetEchConfigsEx(ech->echConfig, NULL, &size); - if (ret != LENGTH_ONLY_E) + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; } else if (ech->type == ECH_TYPE_INNER) @@ -11888,7 +12076,7 @@ static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig, if (ret == 0) ret = GetEchConfig(echConfig, NULL, &rawConfigLen); - if (ret == LENGTH_ONLY_E) + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) ret = 0; /* create info */ @@ -12130,7 +12318,7 @@ int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen) /* seal the payload */ ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey, - info, infoLen, aadCopy, aadLen, ech->innerClientHello, + info, (word32)infoLen, aadCopy, aadLen, ech->innerClientHello, ech->innerClientHelloLen - ech->hpke->Nt, ech->outerClientPayload); @@ -12984,22 +13172,31 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) #endif #endif -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1, + ssl->heap); #endif #ifdef WOLFSSL_KYBER768 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3, + ssl->heap); #endif #ifdef WOLFSSL_KYBER768 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5, + ssl->heap); #endif #elif defined(HAVE_LIBOQS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap); @@ -13021,7 +13218,7 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) #elif defined(HAVE_PQM4) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap); #endif /* HAVE_LIBOQS */ -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_HAVE_KYBER */ (void)ssl; (void)extensions; @@ -13240,7 +13437,7 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) ret = SetCipherSpecs(ssl); if (ret != 0) return ret; - now = TimeNowInMilliseconds(); + now = (word64)TimeNowInMilliseconds(); if (now == 0) return GETTIME_ERROR; #ifdef WOLFSSL_32BIT_MILLI_TIME @@ -13371,7 +13568,7 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) ssl->arrays->psk_keySz == 0 || #endif (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { #ifndef OPENSSL_EXTRA ret = PSK_KEY_ERROR; #endif @@ -13570,7 +13767,7 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, #endif /** Tells the buffered size of extensions to be sent into the client hello. */ -int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength) +int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word32* pLength) { int ret = 0; word16 length = 0; @@ -13800,7 +13997,7 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, #endif /** Writes the extensions to be sent into the client hello. */ -int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset) +int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word32* pOffset) { int ret = 0; word16 offset = 0; @@ -14294,6 +14491,143 @@ int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length, return ret; } #endif +/* Jump Table to check minimum size values for client case in TLSX_Parse */ +#ifndef NO_WOLFSSL_SERVER +static word16 TLSX_GetMinSize_Client(word16* type) +{ + switch (*type) { + case TLSXT_SERVER_NAME: + return WOLFSSL_SNI_MIN_SIZE_CLIENT; + case TLSXT_EARLY_DATA: + return WOLFSSL_EDI_MIN_SIZE_CLIENT; + case TLSXT_MAX_FRAGMENT_LENGTH: + return WOLFSSL_MFL_MIN_SIZE_CLIENT; + case TLSXT_TRUSTED_CA_KEYS: + return WOLFSSL_TCA_MIN_SIZE_CLIENT; + case TLSXT_TRUNCATED_HMAC: + return WOLFSSL_THM_MIN_SIZE_CLIENT; + case TLSXT_STATUS_REQUEST: + return WOLFSSL_CSR_MIN_SIZE_CLIENT; + case TLSXT_SUPPORTED_GROUPS: + return WOLFSSL_EC_MIN_SIZE_CLIENT; + case TLSXT_EC_POINT_FORMATS: + return WOLFSSL_PF_MIN_SIZE_CLIENT; + case TLSXT_SIGNATURE_ALGORITHMS: + return WOLFSSL_SA_MIN_SIZE_CLIENT; + case TLSXT_USE_SRTP: + return WOLFSSL_SRTP_MIN_SIZE_CLIENT; + case TLSXT_APPLICATION_LAYER_PROTOCOL: + return WOLFSSL_ALPN_MIN_SIZE_CLIENT; + case TLSXT_STATUS_REQUEST_V2: + return WOLFSSL_CSR2_MIN_SIZE_CLIENT; + case TLSXT_CLIENT_CERTIFICATE: + return WOLFSSL_CCT_MIN_SIZE_CLIENT; + case TLSXT_SERVER_CERTIFICATE: + return WOLFSSL_SCT_MIN_SIZE_CLIENT; + case TLSXT_ENCRYPT_THEN_MAC: + return WOLFSSL_ETM_MIN_SIZE_CLIENT; + case TLSXT_SESSION_TICKET: + return WOLFSSL_STK_MIN_SIZE_CLIENT; + case TLSXT_PRE_SHARED_KEY: + return WOLFSSL_PSK_MIN_SIZE_CLIENT; + case TLSXT_COOKIE: + return WOLFSSL_CKE_MIN_SIZE_CLIENT; + case TLSXT_PSK_KEY_EXCHANGE_MODES: + return WOLFSSL_PKM_MIN_SIZE_CLIENT; + case TLSXT_CERTIFICATE_AUTHORITIES: + return WOLFSSL_CAN_MIN_SIZE_CLIENT; + case TLSXT_POST_HANDSHAKE_AUTH: + return WOLFSSL_PHA_MIN_SIZE_CLIENT; + case TLSXT_SIGNATURE_ALGORITHMS_CERT: + return WOLFSSL_SA_MIN_SIZE_CLIENT; + case TLSXT_KEY_SHARE: + return WOLFSSL_KS_MIN_SIZE_CLIENT; + case TLSXT_CONNECTION_ID: + return WOLFSSL_CID_MIN_SIZE_CLIENT; + case TLSXT_RENEGOTIATION_INFO: + return WOLFSSL_SCR_MIN_SIZE_CLIENT; + case TLSXT_KEY_QUIC_TP_PARAMS_DRAFT: + return WOLFSSL_QTP_MIN_SIZE_CLIENT; + case TLSXT_ECH: + return WOLFSSL_ECH_MIN_SIZE_CLIENT; + default: + return 0; + } +} + #define TLSX_GET_MIN_SIZE_CLIENT TLSX_GetMinSize_Client +#else + #define TLSX_GET_MIN_SIZE_CLIENT(...) 0 +#endif + + +#ifndef NO_WOLFSSL_CLIENT +/* Jump Table to check minimum size values for server case in TLSX_Parse */ +static word16 TLSX_GetMinSize_Server(const word16 *type) +{ + switch (*type) { + case TLSXT_SERVER_NAME: + return WOLFSSL_SNI_MIN_SIZE_SERVER; + case TLSXT_EARLY_DATA: + return WOLFSSL_EDI_MIN_SIZE_SERVER; + case TLSXT_MAX_FRAGMENT_LENGTH: + return WOLFSSL_MFL_MIN_SIZE_SERVER; + case TLSXT_TRUSTED_CA_KEYS: + return WOLFSSL_TCA_MIN_SIZE_SERVER; + case TLSXT_TRUNCATED_HMAC: + return WOLFSSL_THM_MIN_SIZE_SERVER; + case TLSXT_STATUS_REQUEST: + return WOLFSSL_CSR_MIN_SIZE_SERVER; + case TLSXT_SUPPORTED_GROUPS: + return WOLFSSL_EC_MIN_SIZE_SERVER; + case TLSXT_EC_POINT_FORMATS: + return WOLFSSL_PF_MIN_SIZE_SERVER; + case TLSXT_SIGNATURE_ALGORITHMS: + return WOLFSSL_SA_MIN_SIZE_SERVER; + case TLSXT_USE_SRTP: + return WOLFSSL_SRTP_MIN_SIZE_SERVER; + case TLSXT_APPLICATION_LAYER_PROTOCOL: + return WOLFSSL_ALPN_MIN_SIZE_SERVER; + case TLSXT_STATUS_REQUEST_V2: + return WOLFSSL_CSR2_MIN_SIZE_SERVER; + case TLSXT_CLIENT_CERTIFICATE: + return WOLFSSL_CCT_MIN_SIZE_SERVER; + case TLSXT_SERVER_CERTIFICATE: + return WOLFSSL_SCT_MIN_SIZE_SERVER; + case TLSXT_ENCRYPT_THEN_MAC: + return WOLFSSL_ETM_MIN_SIZE_SERVER; + case TLSXT_SESSION_TICKET: + return WOLFSSL_STK_MIN_SIZE_SERVER; + case TLSXT_PRE_SHARED_KEY: + return WOLFSSL_PSK_MIN_SIZE_SERVER; + case TLSXT_COOKIE: + return WOLFSSL_CKE_MIN_SIZE_SERVER; + case TLSXT_PSK_KEY_EXCHANGE_MODES: + return WOLFSSL_PKM_MIN_SIZE_SERVER; + case TLSXT_CERTIFICATE_AUTHORITIES: + return WOLFSSL_CAN_MIN_SIZE_SERVER; + case TLSXT_POST_HANDSHAKE_AUTH: + return WOLFSSL_PHA_MIN_SIZE_SERVER; + case TLSXT_SIGNATURE_ALGORITHMS_CERT: + return WOLFSSL_SA_MIN_SIZE_SERVER; + case TLSXT_KEY_SHARE: + return WOLFSSL_KS_MIN_SIZE_SERVER; + case TLSXT_CONNECTION_ID: + return WOLFSSL_CID_MIN_SIZE_SERVER; + case TLSXT_RENEGOTIATION_INFO: + return WOLFSSL_SCR_MIN_SIZE_SERVER; + case TLSXT_KEY_QUIC_TP_PARAMS_DRAFT: + return WOLFSSL_QTP_MIN_SIZE_SERVER; + case TLSXT_ECH: + return WOLFSSL_ECH_MIN_SIZE_SERVER; + default: + return 0; + } +} + #define TLSX_GET_MIN_SIZE_SERVER TLSX_GetMinSize_Server +#else + #define TLSX_GET_MIN_SIZE_SERVER(...) 0 +#endif + /** Parses a buffer of TLS extensions. */ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, @@ -14357,6 +14691,29 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, if (length - offset < size) return BUFFER_ERROR; + /* Check minimum size required for TLSX, even if disabled */ + switch (msgType) { + #ifndef NO_WOLFSSL_SERVER + case client_hello: + if (size < TLSX_GET_MIN_SIZE_CLIENT(&type)){ + WOLFSSL_MSG("Minimum TLSX Size Requirement not Satisfied"); + return BUFFER_ERROR; + } + break; + #endif + #ifndef NO_WOLFSSL_CLIENT + case server_hello: + case hello_retry_request: + if (size < TLSX_GET_MIN_SIZE_SERVER(&type)){ + WOLFSSL_MSG("Minimum TLSX Size Requirement not Satisfied"); + return BUFFER_ERROR; + } + break; + #endif + default: + break; + } + switch (type) { #ifdef HAVE_SNI case TLSX_SERVER_NAME: @@ -14914,7 +15271,8 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, } #ifdef HAVE_EXTENDED_MASTER - if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) { + if (IsAtLeastTLSv1_3(ssl->version) && + (msgType == hello_retry_request || msgType == hello_verify_request)) { /* Don't change EMS status until server_hello received. * Second ClientHello must have same extensions. */ @@ -14922,6 +15280,12 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, else if (!isRequest && ssl->options.haveEMS && !pendingEMS) ssl->options.haveEMS = 0; #endif +#if defined(WOLFSSL_TLS13) && !defined(NO_PSK) + if (IsAtLeastTLSv1_3(ssl->version) && msgType == server_hello && + IS_OFF(seenType, TLSX_ToSemaphore(TLSX_KEY_SHARE))) { + ssl->options.noPskDheKe = 1; + } +#endif if (ret == 0) ret = SNI_VERIFY_PARSE(ssl, isRequest); diff --git a/src/src/tls13.c b/src/src/tls13.c index 9a2e240..ef37c29 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -189,7 +189,7 @@ static const byte #ifndef NO_CERTS #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \ - defined(HAVE_ED448) || defined(HAVE_PQC) + defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash); @@ -205,7 +205,7 @@ static int Tls13HKDFExpandLabel(WOLFSSL* ssl, byte* okm, word32 okmLen, const byte* info, word32 infoLen, int digest) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #if defined(HAVE_PK_CALLBACKS) if (ssl->ctx && ssl->ctx->HKDFExpandLabelCb) { @@ -216,7 +216,7 @@ static int Tls13HKDFExpandLabel(WOLFSSL* ssl, byte* okm, word32 okmLen, WOLFSSL_CLIENT_END /* ignored */); } - if (ret != NOT_COMPILED_IN) + if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) return ret; #endif (void)ssl; @@ -257,7 +257,7 @@ static int Tls13HKDFExpandKeyLabel(WOLFSSL* ssl, byte* okm, word32 okmLen, info, infoLen, digest, side); } - if (ret != NOT_COMPILED_IN) + if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) return ret; #endif @@ -308,14 +308,14 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, const byte* protocol; word32 protocolLen; int digestAlg = -1; - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hashAlgo) { #ifndef NO_WOLFSSL_SHA256 case sha256_mac: ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, ssl->devId); if (ret == 0) { - ret = wc_Sha256Update(&digest.sha256, msg, msgLen); + ret = wc_Sha256Update(&digest.sha256, msg, (word32)msgLen); if (ret == 0) ret = wc_Sha256Final(&digest.sha256, hash); wc_Sha256Free(&digest.sha256); @@ -328,7 +328,7 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, case sha384_mac: ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, ssl->devId); if (ret == 0) { - ret = wc_Sha384Update(&digest.sha384, msg, msgLen); + ret = wc_Sha384Update(&digest.sha384, msg, (word32)msgLen); if (ret == 0) ret = wc_Sha384Final(&digest.sha384, hash); wc_Sha384Free(&digest.sha384); @@ -341,7 +341,7 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, case sha512_mac: ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, ssl->devId); if (ret == 0) { - ret = wc_Sha512Update(&digest.sha512, msg, msgLen); + ret = wc_Sha512Update(&digest.sha512, msg, (word32)msgLen); if (ret == 0) ret = wc_Sha512Final(&digest.sha512, hash); wc_Sha512Free(&digest.sha512); @@ -354,7 +354,7 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, case sm3_mac: ret = wc_InitSm3(&digest.sm3, ssl->heap, ssl->devId); if (ret == 0) { - ret = wc_Sm3Update(&digest.sm3, msg, msgLen); + ret = wc_Sm3Update(&digest.sm3, msg, (word32)msgLen); if (ret == 0) ret = wc_Sm3Final(&digest.sm3, hash); wc_Sm3Free(&digest.sm3); @@ -364,6 +364,7 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, break; #endif default: + ret = BAD_FUNC_ARG; digestAlg = -1; break; } @@ -392,9 +393,9 @@ static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, return VERSION_ERROR; } if (outputLen == -1) - outputLen = hashSz; + outputLen = (int)hashSz; - ret = Tls13HKDFExpandLabel(ssl, output, outputLen, secret, hashSz, + ret = Tls13HKDFExpandLabel(ssl, output, (word32)outputLen, secret, hashSz, protocol, protocolLen, label, labelLen, hash, hashSz, digestAlg); return ret; @@ -481,7 +482,7 @@ int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen, #endif /* WOLFSSL_DTLS13 */ if (outputLen == -1) { - outputLen = hashSz; + outputLen = (int)hashSz; } if (includeMsgs) { hashOutSz = hashSz; @@ -496,7 +497,7 @@ int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen, } PRIVATE_KEY_UNLOCK(); - ret = Tls13HKDFExpandKeyLabel(ssl, output, outputLen, secret, hashSz, + ret = Tls13HKDFExpandKeyLabel(ssl, output, (word32)outputLen, secret, hashSz, protocol, protocolLen, label, labelLen, hash, hashOutSz, digestAlg, side); PRIVATE_KEY_LOCK(); @@ -973,7 +974,7 @@ int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen, { int ret; enum wc_HashType hashType = WC_HASH_TYPE_NONE; - int hashLen = 0; + word32 hashLen = 0; byte hashOut[WC_MAX_DIGEST_SIZE]; const byte* emptyHash = NULL; byte firstExpand[WC_MAX_DIGEST_SIZE]; @@ -1124,7 +1125,7 @@ static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, void *cb_ctx = ssl->HkdfExtractCtx; CallbackHKDFExtract cb = ssl->ctx->HkdfExtractCb; if (cb != NULL) { - ret = cb(prk, salt, saltLen, ikm, ikmLen, digest, cb_ctx); + ret = cb(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest, cb_ctx); } else #endif @@ -1137,7 +1138,7 @@ static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, { #if !defined(HAVE_FIPS) || \ (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) - ret = wc_Tls13_HKDF_Extract_ex(prk, salt, saltLen, ikm, ikmLen, digest, + ret = wc_Tls13_HKDF_Extract_ex(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest, ssl->heap, ssl->devId); #else ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest); @@ -1161,13 +1162,13 @@ int DeriveEarlySecret(WOLFSSL* ssl) } #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13DeriveEarlySecret(ssl); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; #endif PRIVATE_KEY_UNLOCK(); #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0, - ssl->arrays->psk_key, ssl->arrays->psk_keySz, + ssl->arrays->psk_key, (int)ssl->arrays->psk_keySz, mac2hash(ssl->specs.mac_algorithm)); #else ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0, @@ -1197,7 +1198,7 @@ int DeriveHandshakeSecret(WOLFSSL* ssl) } #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13DeriveHandshakeSecret(ssl); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; #endif @@ -1210,7 +1211,7 @@ int DeriveHandshakeSecret(WOLFSSL* ssl) PRIVATE_KEY_UNLOCK(); ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret, key, ssl->specs.hash_size, - ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz, + ssl->arrays->preMasterSecret, (int)ssl->arrays->preMasterSz, mac2hash(ssl->specs.mac_algorithm)); PRIVATE_KEY_LOCK(); @@ -1232,7 +1233,7 @@ int DeriveMasterSecret(WOLFSSL* ssl) #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13DeriveMasterSecret(ssl); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; #endif @@ -1355,7 +1356,7 @@ static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash, #endif int hashType = WC_SHA256; int hashSz = WC_SHA256_DIGEST_SIZE; - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (ssl == NULL || key == NULL || hash == NULL) { return BAD_FUNC_ARG; @@ -1392,6 +1393,7 @@ static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash, break; #endif /* WOLFSSL_SM3 */ default: + ret = BAD_FUNC_ARG; break; } if (ret != 0) @@ -1416,7 +1418,7 @@ static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash, if (ret == 0) { ret = wc_HmacSetKey(verifyHmac, hashType, key, ssl->specs.hash_size); if (ret == 0) - ret = wc_HmacUpdate(verifyHmac, hash, hashSz); + ret = wc_HmacUpdate(verifyHmac, hash, (word32)hashSz); if (ret == 0) ret = wc_HmacFinal(verifyHmac, hash); wc_HmacFree(verifyHmac); @@ -1432,7 +1434,7 @@ static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash, #endif if (pHashSz) - *pHashSz = hashSz; + *pHashSz = (word32)hashSz; return ret; } @@ -1466,7 +1468,7 @@ static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1] = "iv"; */ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) { - int ret = BAD_FUNC_ARG; /* Assume failure */ + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */ int i = 0; #ifdef WOLFSSL_SMALL_STACK byte* key_dig; @@ -1477,10 +1479,10 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13DeriveKeys(ssl, secret, side); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return ret; } - ret = BAD_FUNC_ARG; /* Assume failure */ + ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */ #endif #ifdef WOLFSSL_SMALL_STACK @@ -1553,6 +1555,7 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) break; default: + ret = BAD_FUNC_ARG; break; } @@ -1633,7 +1636,7 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) #endif /* WOLFSSL_DTLS13 */ end: - ForceZero(key_dig, i); + ForceZero(key_dig, (word32)i); #ifdef WOLFSSL_SMALL_STACK XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST); #elif defined(WOLFSSL_CHECK_MEM_ZERO) @@ -1910,10 +1913,12 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) #elif defined(WOLFSSL_ZEPHYR) word32 TimeNowInMilliseconds(void) { + int64_t t; #if defined(CONFIG_ARCH_POSIX) k_cpu_idle(); #endif - return (word32)k_uptime_get() / 1000; + t = k_uptime_get(); /* returns current uptime in milliseconds */ + return (word32)t; } #else @@ -2201,10 +2206,12 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) #elif defined(WOLFSSL_ZEPHYR) sword64 TimeNowInMilliseconds(void) { + int64_t t; #if defined(CONFIG_ARCH_POSIX) k_cpu_idle(); #endif - return (sword64)k_uptime_get() / 1000; + t = k_uptime_get(); /* returns current uptime in milliseconds */ + return (sword64)t; } #else @@ -2567,13 +2574,13 @@ static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input, (void)nonceSz; #ifdef WOLFSSL_ASYNC_CRYPT - if (ssl->error == WC_PENDING_E) { + if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->error = 0; /* clear async */ } #endif #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { if (ret > 0) { ret = 0; /* tsip_Tls13AesEncrypt returns output size */ } @@ -2646,7 +2653,7 @@ static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input, output + dataSz, macSz, aad, aadSz); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif { @@ -2688,7 +2695,7 @@ static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input, output + dataSz, macSz, aad, aadSz); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif { #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \ @@ -2750,7 +2757,7 @@ static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input, ssl->encrypt.state = CIPHER_STATE_END; #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* if async is not okay, then block */ if (!asyncOkay) { ret = wc_AsyncWait(ret, asyncDev, event_flags); @@ -2952,7 +2959,7 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13AesDecrypt(ssl, output, input, sz); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { #ifndef WOLFSSL_EARLY_DATA if (ret < 0) { ret = VERIFY_MAC_ERROR; @@ -2965,9 +2972,9 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* check for still pending */ - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; ssl->error = 0; /* clear async */ @@ -3048,7 +3055,7 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, (byte *)(input + dataSz), macSz, aad, aadSz); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif { @@ -3057,7 +3064,7 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, input + dataSz, macSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } @@ -3087,14 +3094,14 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, (byte *)(input + dataSz), macSz, aad, aadSz); } - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif { ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input, dataSz, ssl->decrypt.nonce, nonceSz, input + dataSz, macSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev); } @@ -3144,7 +3151,7 @@ int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz, #ifdef WOLFSSL_ASYNC_CRYPT /* If pending, leave now */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -3242,7 +3249,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args = (BuildMsg13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_buildmsg; @@ -3256,7 +3263,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* Reset state */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_NO_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E)) #endif { ret = 0; @@ -3269,7 +3276,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args->headerSz = Dtls13GetRlHeaderLength(ssl, 1); #endif /* WOLFSSL_DTLS13 */ - args->sz = args->headerSz + inSz; + args->sz = args->headerSz + (word32)inSz; args->idx = args->headerSz; #ifdef WOLFSSL_ASYNC_CRYPT @@ -3299,7 +3306,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args->sz += ssl->specs.aead_mac_size; if (sizeOnly) - return args->sz; + return (int)args->sz; if (args->sz > (word32)outSz) { WOLFSSL_MSG("Oops, want to write past output buffer size"); @@ -3324,8 +3331,8 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* TLS v1.3 can do in place encryption. */ if (input != output + args->idx) - XMEMCPY(output + args->idx, input, inSz); - args->idx += inSz; + XMEMCPY(output + args->idx, input, (size_t)inSz); + args->idx += (word32)inSz; ssl->options.buildMsgState = BUILD_MSG_HASH; } @@ -3334,7 +3341,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, case BUILD_MSG_HASH: { if (hashOutput) { - ret = HashOutput(ssl, output, args->headerSz + inSz, 0); + ret = HashOutput(ssl, output, (int)args->headerSz + inSz, 0); if (ret != 0) goto exit_buildmsg; } @@ -3353,8 +3360,8 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* QUIC does not use encryption of the TLS Record Layer. * Return the original length + added headers * and restore it in the record header. */ - AddTls13RecordHeader(output, inSz, type, ssl); - ret = args->headerSz + inSz; + AddTls13RecordHeader(output, (word32)inSz, (byte)type, ssl); + ret = (int)args->headerSz + inSz; goto exit_buildmsg; } #endif @@ -3364,7 +3371,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, byte* mac = output + args->idx; output += args->headerSz; - ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0, + ret = ssl->ctx->MacEncryptCb(ssl, mac, output, (unsigned int)inSz, (byte)type, 0, output, output, args->size, ssl->MacEncryptCtx); } else @@ -3376,7 +3383,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, (word16)args->headerSz, asyncOkay); if (ret != 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { /* Zeroize plaintext. */ @@ -3402,7 +3409,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, WOLFSSL_LEAVE("BuildTls13Message", ret); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -3412,7 +3419,7 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* return sz on success */ if (ret == 0) { - ret = args->sz; + ret = (int)args->sz; } else { WOLFSSL_ERROR_VERBOSE(ret); @@ -3950,7 +3957,7 @@ static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello) } if (ssl->arrays->psk_keySz == 0 || (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN && - (int)ssl->arrays->psk_keySz != USE_HW_PSK)) { + (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) { WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR); return PSK_KEY_ERROR; } @@ -4019,7 +4026,7 @@ static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx) idx - Dtls13GetRlHeaderLength(ssl, 0)); else #endif /* WOLFSSL_DTLS13 */ - ret = HashOutput(ssl, output, idx, 0); + ret = HashOutput(ssl, output, (int)idx, 0); if (ret != 0) return ret; @@ -4167,7 +4174,7 @@ static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech) /* hash the body */ if (ret == 0) { ret = HashRaw(ssl, ech->innerClientHello, - ech->innerClientHelloLen - ech->paddingLen - ech->hpke->Nt); + (int)(ech->innerClientHelloLen - ech->paddingLen - ech->hpke->Nt)); } /* swap hsHashes back */ @@ -4234,7 +4241,7 @@ typedef struct Sch13Args { byte* output; word32 idx; int sendSz; - word16 length; + word32 length; #if defined(HAVE_ECH) int clientRandomOffset; int preXLength; @@ -4312,7 +4319,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) args = (Sch13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) return ret; @@ -4419,7 +4426,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) /* set the type to inner */ args->ech->type = ECH_TYPE_INNER; - args->preXLength = args->length; + args->preXLength = (int)args->length; /* get size for inner */ ret = TLSX_GetRequestSize(ssl, client_hello, &args->length); @@ -4430,16 +4437,16 @@ int SendTls13ClientHello(WOLFSSL* ssl) args->ech->type = 0; /* set innerClientHelloLen to ClientHelloInner + padding + tag */ args->ech->paddingLen = 31 - ((args->length - 1) % 32); - args->ech->innerClientHelloLen = args->length + - args->ech->paddingLen + args->ech->hpke->Nt; + args->ech->innerClientHelloLen = (word16)(args->length + + args->ech->paddingLen + args->ech->hpke->Nt); /* set the length back to before we computed ClientHelloInner size */ - args->length = args->preXLength; + args->length = (word32)args->preXLength; } #endif { #ifdef WOLFSSL_DTLS_CH_FRAG - int maxFrag = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE); + word16 maxFrag = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE); word16 lenWithoutExts = args->length; #endif @@ -4470,7 +4477,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) } /* Total message size. */ - args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; + args->sendSz = (int)(args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ); #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) @@ -4510,7 +4517,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN); #if defined(HAVE_ECH) - args->clientRandomOffset = args->idx; + args->clientRandomOffset = (int)args->idx; #endif args->idx += RAN_LEN; @@ -4619,7 +4626,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) if (ssl->options.useEch == 1) { ret = TLSX_FinalizeEch(args->ech, args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ, - args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ)); + (word32)(args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ))); if (ret != 0) return ret; @@ -4653,7 +4660,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) /* compute the outer hash */ if (ret == 0) - ret = HashOutput(ssl, args->output, args->idx, 0); + ret = HashOutput(ssl, args->output, (int)args->idx, 0); } } if (ret != 0) @@ -4680,7 +4687,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) } #endif /* WOLFSSL_DTLS13 */ - ssl->buffers.outputBuffer.length += args->sendSz; + ssl->buffers.outputBuffer.length += (word32)args->sendSz; /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_END; @@ -4817,7 +4824,7 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, PRIVATE_KEY_UNLOCK(); #if !defined(HAVE_FIPS) || \ (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) - ret = wc_HKDF_Extract_ex(digestType, zeros, digestSize, + ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize, ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk, ssl->heap, ssl->devId); #else @@ -4831,10 +4838,10 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, PRIVATE_KEY_UNLOCK(); ret = Tls13HKDFExpandKeyLabel(ssl, acceptConfirmation, ECH_ACCEPT_CONFIRMATION_SZ, - expandLabelPrk, digestSize, + expandLabelPrk, (word32)digestSize, tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, echAcceptConfirmationLabel, ECH_ACCEPT_CONFIRMATION_LABEL_SZ, - transcriptEchConf, digestSize, digestType, WOLFSSL_SERVER_END); + transcriptEchConf, (word32)digestSize, digestType, WOLFSSL_SERVER_END); PRIVATE_KEY_LOCK(); } if (ret == 0) { @@ -4955,7 +4962,7 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, PRIVATE_KEY_UNLOCK(); #if !defined(HAVE_FIPS) || \ (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) - ret = wc_HKDF_Extract_ex(digestType, zeros, digestSize, + ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize, ssl->arrays->clientRandom, RAN_LEN, expandLabelPrk, ssl->heap, ssl->devId); #else @@ -4971,10 +4978,10 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, ret = Tls13HKDFExpandKeyLabel(ssl, output + serverRandomOffset + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ, ECH_ACCEPT_CONFIRMATION_SZ, - expandLabelPrk, digestSize, + expandLabelPrk, (word32)digestSize, tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, echAcceptConfirmationLabel, ECH_ACCEPT_CONFIRMATION_LABEL_SZ, - transcriptEchConf, digestSize, digestType, WOLFSSL_SERVER_END); + transcriptEchConf, (word32)digestSize, digestType, WOLFSSL_SERVER_END); PRIVATE_KEY_LOCK(); } @@ -5055,10 +5062,10 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, args = (Dsh13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) { - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_server_hello = 0; } @@ -5169,7 +5176,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Server random - keep for debugging. */ XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN); #if defined(HAVE_ECH) - args->serverRandomOffset = args->idx; + args->serverRandomOffset = (int)args->idx; #endif args->idx += RAN_LEN; @@ -5285,6 +5292,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } ssl->version.minor = args->pv.minor; + ssl->options.tls1_3 = 0; #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) { @@ -5318,14 +5326,15 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* restore message type */ *extMsgType = args->extMsgType; - if (args->totalExtSz > 0) { - /* Parse and handle extensions. */ + /* Parse and handle extensions, unless lower than TLS1.3. In that case, + * extensions will be parsed in DoServerHello. */ + if (args->totalExtSz > 0 && IsAtLeastTLSv1_3(ssl->version)) { ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz, *extMsgType, NULL); if (ret != 0) { #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_server_hello = 0; } @@ -5338,7 +5347,9 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->msgsReceived.got_hello_retry_request = 1; ssl->msgsReceived.got_server_hello = 0; } + } + if (args->totalExtSz > 0) { args->idx += args->totalExtSz; } @@ -5347,7 +5358,9 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, DtlsCIDOnExtensionsParsed(ssl); #endif /* WOLFSSL_DTLS_CID */ - *inOutIdx = args->idx; + if (IsAtLeastTLSv1_3(ssl->version)) { + *inOutIdx = args->idx; + } ssl->options.serverState = SERVER_HELLO_COMPLETE; @@ -5386,9 +5399,12 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } /* Force client hello version 1.2 to work for static RSA. */ - ssl->chVersion.minor = TLSv1_2_MINOR; + if (ssl->options.dtls) + ssl->chVersion.minor = DTLSv1_2_MINOR; + else + ssl->chVersion.minor = TLSv1_2_MINOR; /* Complete TLS v1.2 processing of ServerHello. */ - ret = CompleteServerHello(ssl); + ret = DoServerHello(ssl, input, inOutIdx, helloSz); #else WOLFSSL_MSG("Client using higher version, fatal error"); WOLFSSL_ERROR_VERBOSE(VERSION_ERROR); @@ -5457,7 +5473,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #if defined(HAVE_ECH) /* check for acceptConfirmation and HashInput with 8 0 bytes */ if (ssl->options.useEch == 1) { - ret = EchCheckAcceptance(ssl, input, args->serverRandomOffset, helloSz); + ret = EchCheckAcceptance(ssl, input, args->serverRandomOffset, (int)helloSz); if (ret != 0) return ret; } @@ -5724,7 +5740,7 @@ static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input, #endif ) { if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo, - peerSuites.hashSigAlgoSz) != 0) { + peerSuites.hashSigAlgoSz, 0) != 0) { WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER); return INVALID_PARAMETER; } @@ -5847,7 +5863,7 @@ int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk, byte* psk_key, } if (*found) { if (*psk_keySz > MAX_PSK_KEY_LEN && - *((int*)psk_keySz) != USE_HW_PSK) { + *((int*)psk_keySz) != WC_NO_ERR_TRACE(USE_HW_PSK)) { WOLFSSL_MSG("Key len too long in FindPsk()"); ret = PSK_KEY_ERROR; WOLFSSL_ERROR_VERBOSE(ret); @@ -6001,7 +6017,7 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz, } #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif @@ -6052,7 +6068,7 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz, return ret; /* Hash data up to binders for deriving binders in PSK extension. */ - ret = HashInput(ssl, input, inputSz); + ret = HashInput(ssl, input, (int)inputSz); if (ret < 0) return ret; @@ -6068,7 +6084,7 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz, if (ret != 0) return ret; - ret = HashInput(ssl, input, inputSz); + ret = HashInput(ssl, input, (int)inputSz); if (ret < 0) return ret; @@ -6164,7 +6180,7 @@ static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz, if (usingPSK) *usingPSK = 0; /* Hash data up to binders for deriving binders in PSK extension. */ - ret = HashInput(ssl, input, helloSz); + ret = HashInput(ssl, input, (int)helloSz); return ret; } @@ -6201,7 +6217,7 @@ static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz, if (ret != 0) { #ifdef HAVE_SESSION_TICKET #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif CleanupClientTickets((PreSharedKey*)ext->data); #endif @@ -6231,7 +6247,7 @@ static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz, else { /* No suitable PSK found, Hash the complete ClientHello, * as caller expect it after we return */ - ret = HashInput(ssl, input, helloSz); + ret = HashInput(ssl, input, (int)helloSz); } if (ret != 0) return ret; @@ -6684,7 +6700,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, args = (Dch13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) { goto exit_dch; @@ -6810,7 +6826,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, realMinor = ssl->version.minor; ssl->version.minor = args->pv.minor; - ret = HashInput(ssl, input + args->begin, helloSz); + ret = HashInput(ssl, input + args->begin, (int)helloSz); ssl->version.minor = realMinor; if (ret == 0) { ret = DoClientHello(ssl, input, inOutIdx, helloSz); @@ -7048,7 +7064,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (!args->usingPSK) { if ((ret = MatchSuite(ssl, args->clSuites)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif WOLFSSL_MSG("Unsupported cipher suite, ClientHello 1.3"); goto exit_dch; @@ -7065,7 +7081,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) ERROR_OUT(INVALID_PARAMETER, exit_dch); ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE; - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) ret = 0; /* for hello_retry return 0 */ } if (ret != 0) @@ -7087,7 +7103,8 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, TLSX* extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE); if (extension != NULL && extension->resp == 1) { KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data; - if (serverKSE != NULL && serverKSE->lastRet == WC_PENDING_E) { + if (serverKSE != NULL && + serverKSE->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = TLSX_KeyShare_GenKey(ssl, serverKSE); if (ret != 0) goto exit_dch; @@ -7220,7 +7237,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_LEAVE("DoTls13ClientHello", ret); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ssl->msgsReceived.got_client_hello = 0; return ret; } @@ -7298,7 +7315,7 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) ret = TLSX_GetResponseSize(ssl, extMsgType, &length); if (ret != 0) return ret; - sendSz = idx + length; + sendSz = (int)(idx + length); /* Check buffers are big enough and grow if needed. */ if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) @@ -7537,7 +7554,7 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) if (ret != 0) return ret; - sendSz = idx + length; + sendSz = (int)(idx + length); /* Encryption always on. */ sendSz += MAX_MSG_EXTRA; @@ -7622,13 +7639,9 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, int ret; int sendSz; word32 i; - word16 reqSz; + word32 reqSz; word16 hashSigAlgoSz = 0; SignatureAlgorithms* sa; - int haveSig = SIG_RSA | SIG_ECDSA | SIG_FALCON | SIG_DILITHIUM; -#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) - haveSig |= SIG_SM2; -#endif WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND); WOLFSSL_ENTER("SendTls13CertificateRequest"); @@ -7639,12 +7652,12 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, return SIDE_ERROR; /* Get the length of the hashSigAlgo buffer */ - InitSuitesHashSigAlgo_ex2(NULL, haveSig, 1, ssl->buffers.keySz, + InitSuitesHashSigAlgo(NULL, SIG_ALL, 1, ssl->buffers.keySz, &hashSigAlgoSz); sa = TLSX_SignatureAlgorithms_New(ssl, hashSigAlgoSz, ssl->heap); if (sa == NULL) return MEMORY_ERROR; - InitSuitesHashSigAlgo_ex2(sa->hashSigAlgo, haveSig, 1, ssl->buffers.keySz, + InitSuitesHashSigAlgo(sa->hashSigAlgo, SIG_ALL, 1, ssl->buffers.keySz, &hashSigAlgoSz); ret = TLSX_Push(&ssl->extensions, TLSX_SIGNATURE_ALGORITHMS, sa, ssl->heap); if (ret != 0) { @@ -7663,7 +7676,7 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, if (ret != 0) return ret; - sendSz = i + reqSz; + sendSz = (int)(i + reqSz); /* Always encrypted and make room for padding. */ sendSz += MAX_MSG_EXTRA; @@ -7738,7 +7751,7 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, #ifndef NO_CERTS #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \ - defined(HAVE_ED448) || defined(HAVE_PQC) + defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) /* Encode the signature algorithm into buffer. * * hashalgo The hash algorithm. @@ -7783,8 +7796,7 @@ static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) output[1] = hashAlgo; break; #endif -#ifdef HAVE_PQC - #ifdef HAVE_FALCON +#ifdef HAVE_FALCON case falcon_level1_sa_algo: output[0] = FALCON_LEVEL1_SA_MAJOR; output[1] = FALCON_LEVEL1_SA_MINOR; @@ -7793,8 +7805,8 @@ static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) output[0] = FALCON_LEVEL5_SA_MAJOR; output[1] = FALCON_LEVEL5_SA_MINOR; break; - #endif - #ifdef HAVE_DILITHIUM +#endif +#ifdef HAVE_DILITHIUM case dilithium_level2_sa_algo: output[0] = DILITHIUM_LEVEL2_SA_MAJOR; output[1] = DILITHIUM_LEVEL2_SA_MINOR; @@ -7807,7 +7819,6 @@ static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) output[0] = DILITHIUM_LEVEL5_SA_MAJOR; output[1] = DILITHIUM_LEVEL5_SA_MINOR; break; - #endif #endif default: break; @@ -7821,9 +7832,19 @@ static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) #define HYBRID_RSA3072_DILITHIUM_LEVEL2_SA_MINOR 0xA2 #define HYBRID_P384_DILITHIUM_LEVEL3_SA_MINOR 0xA4 #define HYBRID_P521_DILITHIUM_LEVEL5_SA_MINOR 0xA6 -#define HYBRID_P256_FALCON_LEVEL1_SA_MINOR 0x0C -#define HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR 0x0D -#define HYBRID_P521_FALCON_LEVEL5_SA_MINOR 0x0F +#define HYBRID_P256_FALCON_LEVEL1_SA_MINOR 0xAF +#define HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR 0xB0 +#define HYBRID_P521_FALCON_LEVEL5_SA_MINOR 0xB2 + +/* Custom defined ones for PQC first */ +#define HYBRID_DILITHIUM_LEVEL2_P256_SA_MINOR 0xD1 +#define HYBRID_DILITHIUM_LEVEL2_RSA3072_SA_MINOR 0xD2 +#define HYBRID_DILITHIUM_LEVEL3_P384_SA_MINOR 0xD3 +#define HYBRID_DILITHIUM_LEVEL5_P521_SA_MINOR 0xD4 +#define HYBRID_FALCON_LEVEL1_P256_SA_MINOR 0xD5 +#define HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR 0xD6 +#define HYBRID_FALCON_LEVEL5_P521_SA_MINOR 0xD7 + static void EncodeDualSigAlg(byte sigAlg, byte altSigAlg, byte* output) { @@ -7846,15 +7867,46 @@ static void EncodeDualSigAlg(byte sigAlg, byte altSigAlg, byte* output) altSigAlg == dilithium_level5_sa_algo) { output[1] = HYBRID_P521_DILITHIUM_LEVEL5_SA_MINOR; } - else if (sigAlg == ecc_dsa_sa_algo && altSigAlg == falcon_level1_sa_algo) { + else if (sigAlg == ecc_dsa_sa_algo && + altSigAlg == falcon_level1_sa_algo) { output[1] = HYBRID_P256_FALCON_LEVEL1_SA_MINOR; } - else if (sigAlg == rsa_pss_sa_algo && altSigAlg == falcon_level1_sa_algo) { + else if (sigAlg == rsa_pss_sa_algo && + altSigAlg == falcon_level1_sa_algo) { output[1] = HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR; } - else if (sigAlg == ecc_dsa_sa_algo && altSigAlg == falcon_level5_sa_algo) { + else if (sigAlg == ecc_dsa_sa_algo && + altSigAlg == falcon_level5_sa_algo) { output[1] = HYBRID_P521_FALCON_LEVEL5_SA_MINOR; } + else if (sigAlg == dilithium_level2_sa_algo && + altSigAlg == ecc_dsa_sa_algo) { + output[1] = HYBRID_DILITHIUM_LEVEL2_P256_SA_MINOR; + } + else if (sigAlg == dilithium_level2_sa_algo && + altSigAlg == rsa_pss_sa_algo) { + output[1] = HYBRID_DILITHIUM_LEVEL2_RSA3072_SA_MINOR; + } + else if (sigAlg == dilithium_level3_sa_algo && + altSigAlg == ecc_dsa_sa_algo) { + output[1] = HYBRID_DILITHIUM_LEVEL3_P384_SA_MINOR; + } + else if (sigAlg == dilithium_level5_sa_algo && + altSigAlg == ecc_dsa_sa_algo) { + output[1] = HYBRID_DILITHIUM_LEVEL5_P521_SA_MINOR; + } + else if (sigAlg == falcon_level1_sa_algo && + altSigAlg == ecc_dsa_sa_algo) { + output[1] = HYBRID_FALCON_LEVEL1_P256_SA_MINOR; + } + else if (sigAlg == falcon_level1_sa_algo && + altSigAlg == rsa_pss_sa_algo) { + output[1] = HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR; + } + else if (sigAlg == falcon_level5_sa_algo && + altSigAlg == ecc_dsa_sa_algo) { + output[1] = HYBRID_FALCON_LEVEL5_P521_SA_MINOR; + } if (output[1] != 0x0) { output[0] = HYBRID_SA_MAJOR; @@ -7910,7 +7962,7 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, else ret = INVALID_PARAMETER; break; -#ifdef HAVE_PQC +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) case PQC_SA_MAJOR: #if defined(HAVE_FALCON) if (input[1] == FALCON_LEVEL1_SA_MINOR) { @@ -7972,39 +8024,74 @@ static WC_INLINE int DecodeTls13HybridSigAlg(byte* input, byte* hashAlg, if (input[1] == HYBRID_P256_DILITHIUM_LEVEL2_SA_MINOR) { *sigAlg = ecc_dsa_sa_algo; - *hashAlg = 4; /* WC_HASH_TYPE_SHA? Reviewer? */ + *hashAlg = sha256_mac; *altSigAlg = dilithium_level2_sa_algo; } else if (input[1] == HYBRID_RSA3072_DILITHIUM_LEVEL2_SA_MINOR) { *sigAlg = rsa_pss_sa_algo; - *hashAlg = 4; + *hashAlg = sha256_mac; *altSigAlg = dilithium_level2_sa_algo; } else if (input[1] == HYBRID_P384_DILITHIUM_LEVEL3_SA_MINOR) { *sigAlg = ecc_dsa_sa_algo; - *hashAlg = 5; + *hashAlg = sha384_mac; *altSigAlg = dilithium_level3_sa_algo; } else if (input[1] == HYBRID_P521_DILITHIUM_LEVEL5_SA_MINOR) { *sigAlg = ecc_dsa_sa_algo; - *hashAlg = 6; + *hashAlg = sha512_mac; *altSigAlg = dilithium_level5_sa_algo; } else if (input[1] == HYBRID_P256_FALCON_LEVEL1_SA_MINOR) { *sigAlg = ecc_dsa_sa_algo; - *hashAlg = 4; + *hashAlg = sha256_mac; *altSigAlg = falcon_level1_sa_algo; } else if (input[1] == HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR) { *sigAlg = rsa_pss_sa_algo; - *hashAlg = 4; + *hashAlg = sha256_mac; *altSigAlg = falcon_level1_sa_algo; } else if (input[1] == HYBRID_P521_FALCON_LEVEL5_SA_MINOR) { *sigAlg = ecc_dsa_sa_algo; - *hashAlg = 6; + *hashAlg = sha512_mac; *altSigAlg = falcon_level5_sa_algo; } + else if (input[1] == HYBRID_DILITHIUM_LEVEL2_P256_SA_MINOR) { + *sigAlg = dilithium_level2_sa_algo; + *hashAlg = sha256_mac; + *altSigAlg = ecc_dsa_sa_algo; + } + else if (input[1] == HYBRID_DILITHIUM_LEVEL2_RSA3072_SA_MINOR) { + *sigAlg = dilithium_level2_sa_algo; + *hashAlg = sha256_mac; + *altSigAlg = rsa_pss_sa_algo; + } + else if (input[1] == HYBRID_DILITHIUM_LEVEL3_P384_SA_MINOR) { + *sigAlg = dilithium_level3_sa_algo; + *hashAlg = sha384_mac; + *altSigAlg = ecc_dsa_sa_algo; + } + else if (input[1] == HYBRID_DILITHIUM_LEVEL5_P521_SA_MINOR) { + *sigAlg = dilithium_level5_sa_algo; + *hashAlg = sha512_mac; + *altSigAlg = ecc_dsa_sa_algo; + } + else if (input[1] == HYBRID_FALCON_LEVEL1_P256_SA_MINOR) { + *sigAlg = falcon_level1_sa_algo; + *hashAlg = sha256_mac; + *altSigAlg = ecc_dsa_sa_algo; + } + else if (input[1] == HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR) { + *sigAlg = falcon_level1_sa_algo; + *hashAlg = sha256_mac; + *altSigAlg = rsa_pss_sa_algo; + } + else if (input[1] == HYBRID_FALCON_LEVEL5_P521_SA_MINOR) { + *sigAlg = falcon_level5_sa_algo; + *hashAlg = sha512_mac; + *altSigAlg = ecc_dsa_sa_algo; + } else { return INVALID_PARAMETER; } @@ -8118,7 +8205,7 @@ int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, { Digest digest; int hashSz = 0; - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); byte* hash; (void)sigAlgo; @@ -8131,7 +8218,7 @@ int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, case sha256_mac: ret = wc_InitSha256(&digest.sha256); if (ret == 0) { - ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz); + ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha256Final(&digest.sha256, hash); wc_Sha256Free(&digest.sha256); @@ -8143,7 +8230,7 @@ int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, case sha384_mac: ret = wc_InitSha384(&digest.sha384); if (ret == 0) { - ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz); + ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha384Final(&digest.sha384, hash); wc_Sha384Free(&digest.sha384); @@ -8155,7 +8242,7 @@ int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, case sha512_mac: ret = wc_InitSha512(&digest.sha512); if (ret == 0) { - ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz); + ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha512Final(&digest.sha512, hash); wc_Sha512Free(&digest.sha512); @@ -8163,6 +8250,10 @@ int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, hashSz = WC_SHA512_DIGEST_SIZE; break; #endif + default: + ret = BAD_FUNC_ARG; + break; + } if (ret != 0) @@ -8184,7 +8275,7 @@ static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) { Digest digest; int hashSz = 0; - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Digest the signature data. */ switch (hashAlgo) { @@ -8192,7 +8283,7 @@ static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) case sha256_mac: ret = wc_InitSha256(&digest.sha256); if (ret == 0) { - ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz); + ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha256Final(&digest.sha256, sigData); wc_Sha256Free(&digest.sha256); @@ -8204,7 +8295,7 @@ static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) case sha384_mac: ret = wc_InitSha384(&digest.sha384); if (ret == 0) { - ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz); + ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha384Final(&digest.sha384, sigData); wc_Sha384Free(&digest.sha384); @@ -8216,7 +8307,7 @@ static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) case sha512_mac: ret = wc_InitSha512(&digest.sha512); if (ret == 0) { - ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz); + ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz); if (ret == 0) ret = wc_Sha512Final(&digest.sha512, sigData); wc_Sha512Free(&digest.sha512); @@ -8225,6 +8316,7 @@ static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) break; #endif default: + ret = BAD_FUNC_ARG; break; } @@ -8270,7 +8362,7 @@ static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo, sigAlgo, hashAlgo); if (ret < 0) return ret; - sigSz = ret; + sigSz = (word32)ret; ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz, hashType); @@ -8420,7 +8512,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) else { if (!ssl->buffers.certificate) { WOLFSSL_MSG("Send Cert missing certificate buffer"); - return BUFFER_ERROR; + return NO_CERT_ERROR; } /* Certificate Data */ certSz = ssl->buffers.certificate->length; @@ -8468,7 +8560,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) if (ssl->fragOffset != 0) length -= (ssl->fragOffset + headerSz); - maxFragment = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE); + maxFragment = (word32)wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE); while (length > 0 && ret == 0) { byte* output = NULL; @@ -8653,7 +8745,8 @@ static int SendTls13Certificate(WOLFSSL* ssl) } #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \ - defined(HAVE_ED448) || defined(HAVE_PQC)) && \ + defined(HAVE_ED448) || defined(HAVE_FALCON) || \ + defined(HAVE_DILITHIUM)) && \ (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)) typedef struct Scv13Args { byte* output; /* not allocated */ @@ -8668,7 +8761,9 @@ typedef struct Scv13Args { word16 sigDataSz; #ifdef WOLFSSL_DUAL_ALG_CERTS byte altSigAlgo; - word16 altSigLen; /* Only used in the case of both native and alt. */ + word32 altSigLen; /* Only used in the case of both native and alt. */ + byte* altSigData; + word16 altSigDataSz; #endif } Scv13Args; @@ -8682,6 +8777,12 @@ static void FreeScv13Args(WOLFSSL* ssl, void* pArgs) XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE); args->sigData = NULL; } +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (args && args->altSigData != NULL) { + XFREE(args->altSigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE); + args->altSigData = NULL; + } +#endif } /* handle generation TLS v1.3 certificate_verify (15) */ @@ -8697,7 +8798,10 @@ static void FreeScv13Args(WOLFSSL* ssl, void* pArgs) static int SendTls13CertificateVerify(WOLFSSL* ssl) { int ret = 0; - buffer* sig = &ssl->buffers.sig; +#ifndef NO_RSA + /* Use this as a temporary buffer for RSA signature verification. */ + buffer* rsaSigBuf = &ssl->buffers.sig; +#endif #ifdef WOLFSSL_ASYNC_CRYPT Scv13Args* args = NULL; WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args); @@ -8712,11 +8816,15 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND); WOLFSSL_ENTER("SendTls13CertificateVerify"); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); +#endif + ssl->options.buildingMsg = 1; #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13SendCertVerify(ssl); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { goto exit_scv; } ret = 0; @@ -8742,7 +8850,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) args = (Scv13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_scv; @@ -8764,6 +8872,10 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) case TLS_ASYNC_BEGIN: { if (ssl->options.sendVerify == SEND_BLANK_CERT) { + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + wolfssl_priv_der_unblind(ssl->buffers.key, + ssl->buffers.keyMask); + #endif return 0; /* sent blank cert, can't verify */ } @@ -8786,9 +8898,9 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) case TLS_ASYNC_BUILD: { - int rem = ssl->buffers.outputBuffer.bufferSize + int rem = (int)(ssl->buffers.outputBuffer.bufferSize - ssl->buffers.outputBuffer.length - - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ; + - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ); /* idx is used to track verify pointer offset to output */ args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; @@ -8813,11 +8925,10 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) } else { #ifdef WOLFSSL_DUAL_ALG_CERTS - if (wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && + if (ssl->sigSpec != NULL && *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) { /* In the case of alternative, we swap in the alt. */ - if (ssl->ctx->altPrivateKey == NULL) { + if (ssl->buffers.altKey == NULL) { ERROR_OUT(NO_PRIVATE_KEY, exit_scv); } ssl->buffers.keyType = ssl->buffers.altKeyType; @@ -8825,26 +8936,29 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) /* If we own it, free key before overriding it. */ if (ssl->buffers.weOwnKey) { FreeDer(&ssl->buffers.key); + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + FreeDer(&ssl->buffers.keyMask); + #endif } - /* Transfer ownership. ssl->ctx always owns the alt private - * key. */ - ssl->buffers.key = ssl->ctx->altPrivateKey; - ssl->ctx->altPrivateKey = NULL; - ssl->buffers.weOwnKey = 1; - ssl->buffers.weOwnAltKey = 0; + /* Swap keys */ + ssl->buffers.key = ssl->buffers.altKey; + #ifdef WOLFSSL_BLIND_PRIVATE_KEY + ssl->buffers.keyMask = ssl->buffers.altKeyMask; + #endif + ssl->buffers.weOwnKey = ssl->buffers.weOwnAltKey; } #endif /* WOLFSSL_DUAL_ALG_CERTS */ - ret = DecodePrivateKey(ssl, &args->length); + ret = DecodePrivateKey(ssl, &args->sigLen); if (ret != 0) goto exit_scv; } - if (rem < 0 || args->length > rem) { + if (rem < 0 || (int)args->sigLen > rem) { ERROR_OUT(BUFFER_E, exit_scv); } - if (args->length == 0) { + if (args->sigLen == 0) { ERROR_OUT(NO_PRIVATE_KEY, exit_scv); } @@ -8872,8 +8986,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) else if (ssl->hsType == DYNAMIC_TYPE_ED448) args->sigAlgo = ed448_sa_algo; #endif - #if defined(HAVE_PQC) - #if defined(HAVE_FALCON) + #if defined(HAVE_FALCON) else if (ssl->hsType == DYNAMIC_TYPE_FALCON) { falcon_key* fkey = (falcon_key*)ssl->hsKey; byte level = 0; @@ -8890,8 +9003,8 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) ERROR_OUT(ALGO_ID_E, exit_scv); } } - #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) else if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) { dilithium_key* fkey = (dilithium_key*)ssl->hsKey; byte level = 0; @@ -8911,13 +9024,12 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) ERROR_OUT(ALGO_ID_E, exit_scv); } } - #endif /* HAVE_DILITHIUM */ - #endif /* HAVE_PQC */ + #endif /* HAVE_DILITHIUM */ else { ERROR_OUT(ALGO_ID_E, exit_scv); } -#ifdef WOLFSSL_DUAL_ALG_CERTS + #ifdef WOLFSSL_DUAL_ALG_CERTS if (ssl->peerSigSpec == NULL) { /* The peer did not respond. We didn't send CKS or they don't * support it. Either way, we do not need to handle dual @@ -8926,8 +9038,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) ssl->sigSpecSz = 0; } - if (wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && + if (ssl->sigSpec != NULL && *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { /* The native was already decoded. Now we need to do the * alternative. Note that no swap was done because this case is @@ -8936,21 +9047,27 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) ERROR_OUT(NO_PRIVATE_KEY, exit_scv); } - if (ssl->buffers.altKeyType == falcon_level1_sa_algo || + /* After this call, args->altSigLen has the length we need for + * the alternative signature. */ + ret = DecodeAltPrivateKey(ssl, &args->altSigLen); + if (ret != 0) + goto exit_scv; + + if (ssl->buffers.altKeyType == ecc_dsa_sa_algo || + ssl->buffers.altKeyType == falcon_level1_sa_algo || ssl->buffers.altKeyType == falcon_level5_sa_algo || ssl->buffers.altKeyType == dilithium_level2_sa_algo || ssl->buffers.altKeyType == dilithium_level3_sa_algo || ssl->buffers.altKeyType == dilithium_level5_sa_algo) { args->altSigAlgo = ssl->buffers.altKeyType; } + else if (ssl->buffers.altKeyType == rsa_sa_algo && + ssl->hsAltType == DYNAMIC_TYPE_RSA) { + args->altSigAlgo = rsa_pss_sa_algo; + } else { ERROR_OUT(ALGO_ID_E, exit_scv); } - /* After this call, args->altSigLen has the length we need for - * the alternative signature. */ - ret = DecodeAltPrivateKey(ssl, &args->altSigLen); - if (ret != 0) - goto exit_scv; EncodeDualSigAlg(args->sigAlgo, args->altSigAlgo, args->verify); if (args->verify[0] == 0) { @@ -8958,57 +9075,79 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) } } else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ + #endif /* WOLFSSL_DUAL_ALG_CERTS */ EncodeSigAlg(ssl->options.hashAlgo, args->sigAlgo, args->verify); if (args->sigData == NULL) { - if (ssl->hsType == DYNAMIC_TYPE_RSA) { - int sigLen = MAX_SIG_DATA_SZ; - if (args->length > MAX_SIG_DATA_SZ) - sigLen = args->length; - args->sigData = (byte*)XMALLOC(sigLen, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - } - else { - args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); + word32 sigLen = MAX_SIG_DATA_SZ; + if ((ssl->hsType == DYNAMIC_TYPE_RSA) && + (args->sigLen > MAX_SIG_DATA_SZ)) { + /* We store the RSA signature in the sigData buffer + * temporarily, hence its size must be fitting. */ + sigLen = args->sigLen; } + args->sigData = (byte*)XMALLOC(sigLen, ssl->heap, + DYNAMIC_TYPE_SIGNATURE); if (args->sigData == NULL) { ERROR_OUT(MEMORY_E, exit_scv); } } + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ssl->sigSpec != NULL) && + (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) && + (args->altSigData == NULL)) { + word32 sigLen = MAX_SIG_DATA_SZ; + if (ssl->hsAltType == DYNAMIC_TYPE_RSA && + args->altSigLen > MAX_SIG_DATA_SZ) { + /* We store the RSA signature in the sigData buffer + * temporarily, hence its size must be fitting. */ + sigLen = args->altSigLen; + } + args->altSigData = (byte*)XMALLOC(sigLen, ssl->heap, + DYNAMIC_TYPE_SIGNATURE); + if (args->altSigData == NULL) { + ERROR_OUT(MEMORY_E, exit_scv); + } + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ + /* Create the data to be signed. */ ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0); if (ret != 0) goto exit_scv; + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ssl->sigSpec != NULL) && + (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) { + XMEMCPY(args->altSigData, args->sigData, args->sigDataSz); + args->altSigDataSz = args->sigDataSz; + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ + #ifndef NO_RSA if (ssl->hsType == DYNAMIC_TYPE_RSA) { /* build encoded signature buffer */ - sig->length = WC_MAX_DIGEST_SIZE; - sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - if (sig->buffer == NULL) { + rsaSigBuf->length = WC_MAX_DIGEST_SIZE; + rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length, ssl->heap, + DYNAMIC_TYPE_SIGNATURE); + if (rsaSigBuf->buffer == NULL) { ERROR_OUT(MEMORY_E, exit_scv); } - ret = CreateRSAEncodedSig(sig->buffer, args->sigData, + ret = CreateRSAEncodedSig(rsaSigBuf->buffer, args->sigData, args->sigDataSz, args->sigAlgo, ssl->options.hashAlgo); if (ret < 0) goto exit_scv; - sig->length = ret; + rsaSigBuf->length = (unsigned int)ret; ret = 0; - - /* Maximum size of RSA Signature. */ - args->sigLen = args->length; } #endif /* !NO_RSA */ #ifdef HAVE_ECC if (ssl->hsType == DYNAMIC_TYPE_ECC) { - sig->length = args->sendSz - args->idx - HASH_SIG_SIZE - - VERIFY_HEADER; + args->sigLen = args->sendSz - args->idx - HASH_SIG_SIZE - + VERIFY_HEADER; #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->buffers.keyType != sm2_sa_algo) #endif @@ -9028,7 +9167,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) if (ret < 0) { ERROR_OUT(ret, exit_scv); } - sig->length = ED25519_SIG_SIZE; + args->sigLen = ED25519_SIG_SIZE; } #endif /* HAVE_ED25519 */ #ifdef HAVE_ED448 @@ -9037,22 +9176,57 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) if (ret < 0) { ERROR_OUT(ret, exit_scv); } - sig->length = ED448_SIG_SIZE; + args->sigLen = ED448_SIG_SIZE; } #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) - #if defined(HAVE_FALCON) + #if defined(HAVE_FALCON) if (ssl->hsType == DYNAMIC_TYPE_FALCON) { - sig->length = FALCON_MAX_SIG_SIZE; + args->sigLen = FALCON_MAX_SIG_SIZE; } - #endif - #if defined(HAVE_DILITHIUM) + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) { - sig->length = DILITHIUM_MAX_SIG_SIZE; + args->sigLen = DILITHIUM_MAX_SIG_SIZE; } - #endif - #endif /* HAVE_PQC */ + #endif /* HAVE_DILITHIUM */ + + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + + #ifndef NO_RSA + if (ssl->hsAltType == DYNAMIC_TYPE_RSA) { + /* build encoded signature buffer */ + rsaSigBuf->length = WC_MAX_DIGEST_SIZE; + rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length, + ssl->heap, + DYNAMIC_TYPE_SIGNATURE); + if (rsaSigBuf->buffer == NULL) { + ERROR_OUT(MEMORY_E, exit_scv); + } + + ret = CreateRSAEncodedSig(rsaSigBuf->buffer, + args->altSigData, args->altSigDataSz, + args->altSigAlgo, ssl->options.hashAlgo); + if (ret < 0) + goto exit_scv; + rsaSigBuf->length = ret; + ret = 0; + } + #endif /* !NO_RSA */ + #ifdef HAVE_ECC + if (ssl->hsAltType == DYNAMIC_TYPE_ECC) { + ret = CreateECCEncodedSig(args->altSigData, + args->altSigDataSz, ssl->options.hashAlgo); + if (ret < 0) + goto exit_scv; + args->altSigDataSz = (word16)ret; + ret = 0; + } + #endif /* HAVE_ECC */ + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_DO; @@ -9061,21 +9235,30 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) case TLS_ASYNC_DO: { + byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER; + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + /* As we have two signatures in the message, we store + * the length of each before the actual signature. This + * is necessary, as we could have two algorithms with + * variable length signatures. */ + sigOut += OPAQUE16_LEN; + } + #endif #ifdef HAVE_ECC if (ssl->hsType == DYNAMIC_TYPE_ECC) { #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->buffers.keyType == sm2_sa_algo) { ret = Sm2wSm3Sign(ssl, TLS13_SM2_SIG_ID, TLS13_SM2_SIG_ID_SZ, args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - (word32*)&sig->length, (ecc_key*)ssl->hsKey, NULL); + sigOut, &args->sigLen, (ecc_key*)ssl->hsKey, NULL); } else #endif { ret = EccSign(ssl, args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - (word32*)&sig->length, (ecc_key*)ssl->hsKey, + sigOut, &args->sigLen, (ecc_key*)ssl->hsKey, #ifdef HAVE_PK_CALLBACKS ssl->buffers.key #else @@ -9083,127 +9266,60 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif ); } - -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - if (ssl->hsAltType == DYNAMIC_TYPE_DILITHIUM) { - /* note the + sig->length; we are appending. */ - ret = wc_dilithium_sign_msg( - args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + - VERIFY_HEADER + sig->length, - (word32*)&args->altSigLen, - (dilithium_key*)ssl->hsAltKey, ssl->rng); - - } - else if (ssl->hsAltType == DYNAMIC_TYPE_FALCON) { - /* note the sig->length; we are appending. */ - ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + - VERIFY_HEADER + sig->length, - (word32*)&args->altSigLen, - (falcon_key*)ssl->hsAltKey, - ssl->rng); - } - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - args->length = (word16)sig->length; + args->length = (word16)args->sigLen; } #endif /* HAVE_ECC */ #ifdef HAVE_ED25519 if (ssl->hsType == DYNAMIC_TYPE_ED25519) { ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - (word32*)&sig->length, (ed25519_key*)ssl->hsKey, + sigOut, &args->sigLen, (ed25519_key*)ssl->hsKey, #ifdef HAVE_PK_CALLBACKS ssl->buffers.key #else NULL #endif ); - args->length = (word16)sig->length; + args->length = (word16)args->sigLen; } #endif #ifdef HAVE_ED448 if (ssl->hsType == DYNAMIC_TYPE_ED448) { ret = Ed448Sign(ssl, args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - (word32*)&sig->length, (ed448_key*)ssl->hsKey, + sigOut, &args->sigLen, (ed448_key*)ssl->hsKey, #ifdef HAVE_PK_CALLBACKS ssl->buffers.key #else NULL #endif ); - args->length = (word16)sig->length; + args->length = (word16)args->sigLen; } #endif - #if defined(HAVE_PQC) - #if defined(HAVE_FALCON) + #if defined(HAVE_FALCON) if (ssl->hsType == DYNAMIC_TYPE_FALCON) { ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + - VERIFY_HEADER, (word32*)&sig->length, + sigOut, &args->sigLen, (falcon_key*)ssl->hsKey, ssl->rng); - args->length = (word16)sig->length; + args->length = (word16)args->sigLen; } - #endif - #if defined(HAVE_DILITHIUM) + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) { ret = wc_dilithium_sign_msg(args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + - VERIFY_HEADER, (word32*)&sig->length, + sigOut, &args->sigLen, (dilithium_key*)ssl->hsKey, ssl->rng); - args->length = (word16)sig->length; + args->length = (word16)args->sigLen; } - #endif - #endif /* HAVE_PQC */ + #endif /* HAVE_DILITHIUM */ #ifndef NO_RSA if (ssl->hsType == DYNAMIC_TYPE_RSA) { - ret = RsaSign(ssl, sig->buffer, (word32)sig->length, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen, - args->sigAlgo, ssl->options.hashAlgo, - (RsaKey*)ssl->hsKey, - ssl->buffers.key - ); - -#ifdef WOLFSSL_DUAL_ALG_CERTS - /* In the case of RSA, we need to do the CKS both case here - * BEFORE args->sigData is overwritten!! We keep the sig - * separate and then append later so we don't interfere with the - * checks below. */ - if (wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - if (ssl->hsAltType == DYNAMIC_TYPE_DILITHIUM) { - /* note the + args->sigLen; we are appending. */ - ret = wc_dilithium_sign_msg(args->sigData, - args->sigDataSz, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER + - args->sigLen, - (word32*)&args->altSigLen, - (dilithium_key*)ssl->hsAltKey, ssl->rng); - } - else if (ssl->hsAltType == DYNAMIC_TYPE_FALCON) { - /* note the + args->sigLen; we are appending. */ - ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz, - args->verify + HASH_SIG_SIZE + - VERIFY_HEADER + args->sigLen, - (word32*)&args->altSigLen, - (falcon_key*)ssl->hsAltKey, - ssl->rng); - } - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - + ret = RsaSign(ssl, rsaSigBuf->buffer, (word32)rsaSigBuf->length, + sigOut, &args->sigLen, args->sigAlgo, + ssl->options.hashAlgo, (RsaKey*)ssl->hsKey, + ssl->buffers.key); if (ret == 0) { args->length = (word16)args->sigLen; - - XMEMCPY(args->sigData, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - args->sigLen); + XMEMCPY(args->sigData, sigOut, args->sigLen); } } #endif /* !NO_RSA */ @@ -9213,10 +9329,76 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) goto exit_scv; } -#ifdef WOLFSSL_DUAL_ALG_CERTS - /* Add in length of the alt sig which will be appended to the sig */ - args->length += args->altSigLen; -#endif /* WOLFSSL_DUAL_ALG_CERTS */ + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + /* Add signature length for the first signature. */ + c16toa((word16)args->sigLen, sigOut - OPAQUE16_LEN); + args->length += OPAQUE16_LEN; + + /* Advance our pointer to where we store the alt signature. + * We also add additional space for the length field of the + * second signature. */ + sigOut += args->sigLen + OPAQUE16_LEN; + + /* Generate the alternative signature */ + #ifdef HAVE_ECC + if (ssl->hsAltType == DYNAMIC_TYPE_ECC) { + ret = EccSign(ssl, args->altSigData, args->altSigDataSz, + sigOut, &args->altSigLen, + (ecc_key*)ssl->hsAltKey, + #ifdef HAVE_PK_CALLBACKS + ssl->buffers.altKey + #else + NULL + #endif + ); + } + #endif /* HAVE_ECC */ + #ifndef NO_RSA + if (ssl->hsAltType == DYNAMIC_TYPE_RSA) { + ret = RsaSign(ssl, rsaSigBuf->buffer, + (word32)rsaSigBuf->length, sigOut, + &args->altSigLen, args->altSigAlgo, + ssl->options.hashAlgo, (RsaKey*)ssl->hsAltKey, + ssl->buffers.altKey); + + if (ret == 0) { + XMEMCPY(args->altSigData, sigOut, args->altSigLen); + } + } + #endif /* !NO_RSA */ + #if defined(HAVE_FALCON) + if (ssl->hsAltType == DYNAMIC_TYPE_FALCON) { + ret = wc_falcon_sign_msg(args->altSigData, + args->altSigDataSz, sigOut, + &args->altSigLen, + (falcon_key*)ssl->hsAltKey, + ssl->rng); + } + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) + if (ssl->hsAltType == DYNAMIC_TYPE_DILITHIUM) { + ret = wc_dilithium_sign_msg(args->altSigData, + args->altSigDataSz, sigOut, + &args->altSigLen, + (dilithium_key*)ssl->hsAltKey, + ssl->rng); + } + #endif /* HAVE_DILITHIUM */ + + /* Check for error */ + if (ret != 0) { + goto exit_scv; + } + + /* Add signature length for the alternative signature. */ + c16toa((word16)args->altSigLen, sigOut - OPAQUE16_LEN); + + /* Add length of the alt sig to the total length */ + args->length += args->altSigLen + OPAQUE16_LEN; + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ /* Add signature length. */ c16toa(args->length, args->verify + HASH_SIG_SIZE); @@ -9232,38 +9414,72 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) if (ssl->hsType == DYNAMIC_TYPE_RSA) { /* check for signature faults */ ret = VerifyRsaSign(ssl, args->sigData, args->sigLen, - sig->buffer, (word32)sig->length, args->sigAlgo, + rsaSigBuf->buffer, (word32)rsaSigBuf->length, args->sigAlgo, ssl->options.hashAlgo, (RsaKey*)ssl->hsKey, - ssl->buffers.key - ); + ssl->buffers.key); + } + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH && + ssl->hsAltType == DYNAMIC_TYPE_RSA) { + /* check for signature faults */ + ret = VerifyRsaSign(ssl, args->altSigData, args->altSigLen, + rsaSigBuf->buffer, (word32)rsaSigBuf->length, + args->altSigAlgo, ssl->options.hashAlgo, + (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey); } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ #endif /* !NO_RSA */ #if defined(HAVE_ECC) && defined(WOLFSSL_CHECK_SIG_FAULTS) if (ssl->hsType == DYNAMIC_TYPE_ECC) { + byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER; + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + /* Add our length offset. */ + sigOut += OPAQUE16_LEN; + } + #endif #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->buffers.keyType == sm2_sa_algo) { ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID, TLS13_SM2_SIG_ID_SZ, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - sig->length, args->sigData, args->sigDataSz, + sigOut, args->sigLen, args->sigData, args->sigDataSz, (ecc_key*)ssl->hsKey, NULL); } else #endif { - ret = EccVerify(ssl, - args->verify + HASH_SIG_SIZE + VERIFY_HEADER, - sig->length, args->sigData, args->sigDataSz, - (ecc_key*)ssl->hsKey, + ret = EccVerify(ssl, sigOut, args->sigLen, + args->sigData, args->sigDataSz, + (ecc_key*)ssl->hsKey, #ifdef HAVE_PK_CALLBACKS - ssl->buffers.key + ssl->buffers.key #else - NULL + NULL #endif - ); + ); } } - #endif + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH && + ssl->hsAltType == DYNAMIC_TYPE_ECC) { + /* check for signature faults */ + byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER + + args->sigLen + OPAQUE16_LEN + OPAQUE16_LEN; + ret = EccVerify(ssl, sigOut, args->altSigLen, + args->altSigData, args->altSigDataSz, + (ecc_key*)ssl->hsAltKey, + #ifdef HAVE_PK_CALLBACKS + ssl->buffers.altKey + #else + NULL + #endif + ); + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ + #endif /* HAVE_ECC && WOLFSSL_CHECK_SIG_FAULTS */ /* Check for error */ if (ret != 0) { @@ -9282,7 +9498,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) VERIFY_HEADER, certificate_verify, ssl); args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + - args->length + HASH_SIG_SIZE + VERIFY_HEADER; + args->length + HASH_SIG_SIZE + VERIFY_HEADER; #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA; @@ -9346,13 +9562,22 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) } /* switch(ssl->options.asyncState) */ exit_scv: +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + if (ret == 0) { + ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, + &ssl->buffers.keyMask); + } + else { + wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask); + } +#endif WOLFSSL_LEAVE("SendTls13CertificateVerify", ret); WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND); #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -9442,8 +9667,8 @@ typedef struct Dcv13Args { #ifdef WOLFSSL_DUAL_ALG_CERTS byte altSigAlgo; byte* altSigData; - word16 altSigDataSz; - word16 altSignatureSz; + word32 altSigDataSz; + word32 altSignatureSz; byte altPeerAuthGood; #endif } Dcv13Args; @@ -9466,6 +9691,59 @@ static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs) } #ifdef WOLFSSL_DUAL_ALG_CERTS +#ifndef NO_RSA +/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a + * RSA public key. Convert it into a usable public key. */ +static int decodeRsaKey(WOLFSSL* ssl) +{ + int keyRet; + word32 tmpIdx = 0; + + if (ssl->peerRsaKeyPresent) + return INVALID_PARAMETER; + + keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey); + if (keyRet != 0) + return PEER_KEY_ERROR; + + ssl->peerRsaKeyPresent = 1; + keyRet = wc_RsaPublicKeyDecode(ssl->peerCert.sapkiDer, &tmpIdx, + ssl->peerRsaKey, + ssl->peerCert.sapkiLen); + if (keyRet != 0) + return PEER_KEY_ERROR; + + return 0; +} +#endif /* !NO_RSA */ + +#ifdef HAVE_ECC +/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a + * ECC public key. Convert it into a usable public key. */ +static int decodeEccKey(WOLFSSL* ssl) +{ + int keyRet; + word32 tmpIdx = 0; + + if (ssl->peerEccDsaKeyPresent) + return INVALID_PARAMETER; + + keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey); + if (keyRet != 0) + return PEER_KEY_ERROR; + + ssl->peerEccDsaKeyPresent = 1; + keyRet = wc_EccPublicKeyDecode(ssl->peerCert.sapkiDer, &tmpIdx, + ssl->peerEccDsaKey, + ssl->peerCert.sapkiLen); + if (keyRet != 0) + return PEER_KEY_ERROR; + + return 0; +} +#endif /* HAVE_ECC */ + +#ifdef HAVE_DILITHIUM /* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a * dilithium public key. Convert it into a usable public key. */ static int decodeDilithiumKey(WOLFSSL* ssl, int level) @@ -9482,10 +9760,6 @@ static int decodeDilithiumKey(WOLFSSL* ssl, int level) return PEER_KEY_ERROR; ssl->peerDilithiumKeyPresent = 1; - keyRet = wc_dilithium_init(ssl->peerDilithiumKey); - if (keyRet != 0) - return PEER_KEY_ERROR; - keyRet = wc_dilithium_set_level(ssl->peerDilithiumKey, level); if (keyRet != 0) return PEER_KEY_ERROR; @@ -9498,7 +9772,9 @@ static int decodeDilithiumKey(WOLFSSL* ssl, int level) return 0; } +#endif /* HAVE_DILITHIUM */ +#ifdef HAVE_FALCON /* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a * falcon public key. Convert it into a usable public key. */ static int decodeFalconKey(WOLFSSL* ssl, int level) @@ -9514,10 +9790,6 @@ static int decodeFalconKey(WOLFSSL* ssl, int level) return PEER_KEY_ERROR; ssl->peerFalconKeyPresent = 1; - keyRet = wc_falcon_init(ssl->peerFalconKey); - if (keyRet != 0) - return PEER_KEY_ERROR; - keyRet = wc_falcon_set_level(ssl->peerFalconKey, level); if (keyRet != 0) return PEER_KEY_ERROR; @@ -9530,7 +9802,8 @@ static int decodeFalconKey(WOLFSSL* ssl, int level) return 0; } -#endif +#endif /* HAVE_FALCON */ +#endif /* WOLFSSL_DUAL_ALG_CERTS */ /* handle processing TLS v1.3 certificate_verify (15) */ /* Parse and handle a TLS v1.3 CertificateVerify message. @@ -9547,7 +9820,11 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz) { int ret = 0; - buffer* sig = &ssl->buffers.sig; + byte* sig = NULL; +#ifndef NO_RSA + /* Use this as a temporary buffer for RSA signature verification. */ + buffer* rsaSigBuf = &ssl->buffers.sig; +#endif #ifdef WOLFSSL_ASYNC_CRYPT Dcv13Args* args = NULL; WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args); @@ -9560,7 +9837,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, #if defined(WOLFSSL_RENESAS_TSIP_TLS) ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { goto exit_dcv; } ret = 0; @@ -9577,7 +9854,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, args = (Dcv13Args*)ssl->async->args; ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) goto exit_dcv; @@ -9634,8 +9911,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, /* If no CKS extension or either native or alternative, then just * get a normal sigalgo. But if BOTH, then get the native and alt * sig algos. */ - if (wolfSSL_is_server(ssl) || - ssl->sigSpec == NULL || + if (ssl->sigSpec == NULL || *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_NATIVE || *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) { #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -9669,8 +9945,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, } #ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - (ssl->sigSpec != NULL) && + if ((ssl->sigSpec != NULL) && (*ssl->sigSpec != WOLFSSL_CKS_SIGSPEC_NATIVE)) { word16 sa; @@ -9680,6 +9955,17 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, sa = args->altSigAlgo; switch(sa) { + #ifndef NO_RSA + case rsa_pss_sa_algo: + ret = decodeRsaKey(ssl); + break; + #endif + #ifdef HAVE_ECC + case ecc_dsa_sa_algo: + ret = decodeEccKey(ssl); + break; + #endif + #ifdef HAVE_DILITHIUM case dilithium_level2_sa_algo: ret = decodeDilithiumKey(ssl, 2); break; @@ -9689,70 +9975,62 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, case dilithium_level5_sa_algo: ret = decodeDilithiumKey(ssl, 5); break; + #endif + #ifdef HAVE_FALCON case falcon_level1_sa_algo: ret = decodeFalconKey(ssl, 1); break; case falcon_level5_sa_algo: ret = decodeFalconKey(ssl, 5); break; + #endif default: ERROR_OUT(PEER_KEY_ERROR, exit_dcv); - break; } if (ret != 0) ERROR_OUT(ret, exit_dcv); if (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) { - /* Now swap in the alternative. We only support hybrid certs - * where native is RSA or ECC so check that either of those - * are present and then remove it. */ - if (ssl->peerRsaKeyPresent && - ssl->peerEccDsaKeyPresent) { - /* They shouldn't both be present. */ - ERROR_OUT(PEER_KEY_ERROR, exit_dcv); - } - else if (ssl->peerRsaKeyPresent) { + /* Now swap in the alternative by removing the native. + * sa contains the alternative signature type. */ + #ifndef NO_RSA + if (ssl->peerRsaKeyPresent && sa != rsa_pss_sa_algo) { FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey); ssl->peerRsaKeyPresent = 0; } - else if (ssl->peerEccDsaKeyPresent) { + #endif + #ifdef HAVE_ECC + else if (ssl->peerEccDsaKeyPresent && + sa != ecc_dsa_sa_algo) { FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey); ssl->peerEccDsaKeyPresent = 0; } - else { - ERROR_OUT(WOLFSSL_NOT_IMPLEMENTED, exit_dcv); + #endif + #ifdef HAVE_DILITHIUM + else if (ssl->peerDilithiumKeyPresent && + sa != dilithium_level2_sa_algo && + sa != dilithium_level3_sa_algo && + sa != dilithium_level5_sa_algo) { + FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM, + (void**)&ssl->peerDilithiumKey); + ssl->peerDilithiumKeyPresent = 0; } - } - else if (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - /* Use alternative public key to figure out the expected - * alt sig size. We only support Post-quantum key as SAPKI. - */ - switch(sa) { - case dilithium_level2_sa_algo: - case dilithium_level3_sa_algo: - case dilithium_level5_sa_algo: - ret = wc_dilithium_sig_size(ssl->peerDilithiumKey); - break; - case falcon_level1_sa_algo: - case falcon_level5_sa_algo: - ret = wc_falcon_sig_size(ssl->peerFalconKey); - break; - default: - ERROR_OUT(PEER_KEY_ERROR, exit_dcv); - break; + #endif + #ifdef HAVE_FALCON + else if (ssl->peerFalconKeyPresent && + sa != falcon_level1_sa_algo && + sa != falcon_level5_sa_algo) { + FreeKey(ssl, DYNAMIC_TYPE_FALCON, + (void**)&ssl->peerFalconKey); + ssl->peerFalconKeyPresent = 0; } - - if (ret <= 0) { + #endif + else { ERROR_OUT(PEER_KEY_ERROR, exit_dcv); } - args->altSignatureSz = ret; - ret = 0; - } - else { - ERROR_OUT(WOLFSSL_NOT_IMPLEMENTED, exit_dcv); } } #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -9788,7 +10066,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, ssl->peerEccDsaKeyPresent; } #endif - #ifdef HAVE_PQC + #ifdef HAVE_FALCON if (ssl->options.peerSigAlgo == falcon_level1_sa_algo) { WOLFSSL_MSG("Peer sent Falcon Level 1 sig"); validSigAlgo = (ssl->peerFalconKey != NULL) && @@ -9799,6 +10077,8 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, validSigAlgo = (ssl->peerFalconKey != NULL) && ssl->peerFalconKeyPresent; } + #endif + #ifdef HAVE_DILITHIUM if (ssl->options.peerSigAlgo == dilithium_level2_sa_algo) { WOLFSSL_MSG("Peer sent Dilithium Level 2 sig"); validSigAlgo = (ssl->peerDilithiumKey != NULL) && @@ -9831,61 +10111,89 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, ERROR_OUT(SIG_VERIFY_E, exit_dcv); } - sig->length = args->sz; + args->sigSz = args->sz; #ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && + if (ssl->sigSpec != NULL && *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - /* If its RSA, we only hybridize with RSA3072 which has a sig - * size of 384. For ECC, this is actually encoded as an RFC5912 - * formatted signature which means we can use the ASN APIs to - * figure out the length. Note that some post-quantum sig algs - * have variable length signatures (Falcon). That is why we - * don't do: - * sig->length -= args->altSignatureSz; */ - #define RSA3072_SIG_LEN 384 - if (ssl->options.peerSigAlgo == rsa_pss_sa_algo) { - sig->length = RSA3072_SIG_LEN; - } - else if (ssl->options.peerSigAlgo == ecc_dsa_sa_algo) { - word32 tmpIdx = args->idx; - sig->length = wc_SignatureGetSize(WC_SIGNATURE_TYPE_ECC, - ssl->peerEccDsaKey, - sizeof(*ssl->peerEccDsaKey)); - if (GetSequence(input, &tmpIdx, (int*)&sig->length, - args->sz) < 0) { - ERROR_OUT(SIG_VERIFY_E, exit_dcv); - } - /* We have to increment by the size of the header. */ - sig->length += tmpIdx - args->idx; - } - else { - ERROR_OUT(WOLFSSL_NOT_IMPLEMENTED, exit_dcv); + /* In case we received two signatures, both of them are encoded + * with their size as 16-bit integeter prior in memory. Hence, + * we can decode both lengths here now. */ + word32 tmpIdx = args->idx; + word16 tmpSz = 0; + ato16(input + tmpIdx, &tmpSz); + args->sigSz = tmpSz; + + tmpIdx += OPAQUE16_LEN + args->sigSz; + ato16(input + tmpIdx, &tmpSz); + args->altSignatureSz = tmpSz; + + if (args->sz != (args->sigSz + args->altSignatureSz + + OPAQUE16_LEN + OPAQUE16_LEN)) { + ERROR_OUT(BUFFER_ERROR, exit_dcv); } } -#endif +#endif /* WOLFSSL_DUAL_ALG_CERTS */ - sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap, + #if !defined(NO_RSA) && defined(WC_RSA_PSS) + /* In case we have to verify an RSA signature, we have to store the + * signature in the 'rsaSigBuf' structure for further processing. + */ + if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) { + word32 sigSz = args->sigSz; + sig = input + args->idx; + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Check if our alternative signature was RSA */ + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + if (ssl->options.peerSigAlgo != rsa_pss_sa_algo) { + /* We have to skip the first signature (length field + * and signature itself) and the length field of the + * alternative signature. */ + sig += OPAQUE16_LEN + OPAQUE16_LEN + args->sigSz; + sigSz = args->altSignatureSz; + } + else { + /* We have to skip the length field */ + sig += OPAQUE16_LEN; + } + } + #endif + rsaSigBuf->buffer = (byte*)XMALLOC(sigSz, ssl->heap, DYNAMIC_TYPE_SIGNATURE); + if (rsaSigBuf->buffer == NULL) { + ERROR_OUT(MEMORY_E, exit_dcv); + } + rsaSigBuf->length = sigSz; + XMEMCPY(rsaSigBuf->buffer, sig, rsaSigBuf->length); + } + #endif /* !NO_RSA && WC_RSA_PSS */ - if (sig->buffer == NULL) { + args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, + DYNAMIC_TYPE_SIGNATURE); + if (args->sigData == NULL) { ERROR_OUT(MEMORY_E, exit_dcv); } - XMEMCPY(sig->buffer, input + args->idx, sig->length); - #ifdef HAVE_ECC - if (ssl->peerEccDsaKeyPresent) { - WOLFSSL_MSG("Doing ECC peer cert verify"); + ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1); + if (ret < 0) + goto exit_dcv; - args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ssl->sigSpec != NULL) && + (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) { + args->altSigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, DYNAMIC_TYPE_SIGNATURE); - if (args->sigData == NULL) { + if (args->altSigData == NULL) { ERROR_OUT(MEMORY_E, exit_dcv); } + XMEMCPY(args->altSigData, args->sigData, args->sigDataSz); + args->altSigDataSz = args->sigDataSz; + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ - ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1); - if (ret != 0) - goto exit_dcv; + #ifdef HAVE_ECC + if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) && + (ssl->peerEccDsaKeyPresent)) { #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->options.peerSigAlgo != sm2_sa_algo) #endif @@ -9898,68 +10206,21 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, ret = 0; } } - #endif - #ifdef HAVE_ED25519 - if (ssl->peerEd25519KeyPresent) { - WOLFSSL_MSG("Doing ED25519 peer cert verify"); - - args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - if (args->sigData == NULL) { - ERROR_OUT(MEMORY_E, exit_dcv); - } - - ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1); - if (ret < 0) - goto exit_dcv; - } - #endif - #ifdef HAVE_ED448 - if (ssl->peerEd448KeyPresent) { - WOLFSSL_MSG("Doing ED448 peer cert verify"); - - args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - if (args->sigData == NULL) { - ERROR_OUT(MEMORY_E, exit_dcv); - } - - ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1); - if (ret < 0) - goto exit_dcv; - } - #endif - #ifdef HAVE_PQC - if (ssl->peerFalconKeyPresent || ssl->peerDilithiumKeyPresent) { - word16 sigDataSz; - byte *sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, - DYNAMIC_TYPE_SIGNATURE); - if (sigData == NULL) { - ERROR_OUT(MEMORY_E, exit_dcv); - } - - ret = CreateSigData(ssl, sigData, &sigDataSz, 1); - if (ret < 0) { - goto exit_dcv; - } -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - /* In this case (BOTH), the pq sig is the alternative. */ - args->altSigData = sigData; - args->altSigDataSz = sigDataSz; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - { - args->sigData = sigData; - args->sigDataSz = sigDataSz; - } - ret = 0; + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ssl->sigSpec != NULL) && + (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) && + (args->altSigAlgo == ecc_dsa_sa_algo) && + (ssl->peerEccDsaKeyPresent)) { + ret = CreateECCEncodedSig(args->altSigData, + args->altSigDataSz, ssl->options.peerHashAlgo); + if (ret < 0) + goto exit_dcv; + args->altSigDataSz = (word16)ret; + ret = 0; } - #endif + #endif /* WOLFSSL_DUAL_ALG_CERTS */ + #endif /* HAVE_ECC */ /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_DO; @@ -9968,35 +10229,52 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, case TLS_ASYNC_DO: { + sig = input + args->idx; + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + /* As we have two signatures in the message, we stored + * the length of each before the actual signature. This + * is necessary, as we could have two algorithms with + * variable length signatures. */ + sig += OPAQUE16_LEN; + } + #endif #ifndef NO_RSA - if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) { - ret = RsaVerify(ssl, sig->buffer, (word32)sig->length, &args->output, - ssl->options.peerSigAlgo, ssl->options.peerHashAlgo, ssl->peerRsaKey, + if ((ssl->options.peerSigAlgo == rsa_pss_sa_algo) && + (ssl->peerRsaKey != NULL) && (ssl->peerRsaKeyPresent != 0)) { + WOLFSSL_MSG("Doing RSA peer cert verify"); + ret = RsaVerify(ssl, rsaSigBuf->buffer, + (word32)rsaSigBuf->length, &args->output, + ssl->options.peerSigAlgo, + ssl->options.peerHashAlgo, ssl->peerRsaKey, #ifdef HAVE_PK_CALLBACKS - &ssl->buffers.peerRsaKey + &ssl->buffers.peerRsaKey #else - NULL + NULL #endif - ); + ); if (ret >= 0) { - args->sendSz = ret; + args->sendSz = (word32)ret; ret = 0; } } #endif /* !NO_RSA */ #ifdef HAVE_ECC - if (ssl->peerEccDsaKeyPresent) { + if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) && + (ssl->peerEccDsaKeyPresent)) { #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->options.peerSigAlgo == sm2_sa_algo) { ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID, - TLS13_SM2_SIG_ID_SZ, input + args->idx, args->sz, + TLS13_SM2_SIG_ID_SZ, sig, args->sigSz, args->sigData, args->sigDataSz, ssl->peerEccDsaKey, NULL); } else #endif { - ret = EccVerify(ssl, input + args->idx, sig->length, + WOLFSSL_MSG("Doing ECC peer cert verify"); + ret = EccVerify(ssl, sig, args->sigSz, args->sigData, args->sigDataSz, ssl->peerEccDsaKey, #ifdef HAVE_PK_CALLBACKS @@ -10004,21 +10282,24 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, #else NULL #endif - ); + ); } if (ret >= 0) { /* CLIENT/SERVER: data verified with public key from * certificate. */ ssl->options.peerAuthGood = 1; + FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey); ssl->peerEccDsaKeyPresent = 0; } } #endif /* HAVE_ECC */ #ifdef HAVE_ED25519 - if (ssl->peerEd25519KeyPresent) { - ret = Ed25519Verify(ssl, input + args->idx, args->sz, + if ((ssl->options.peerSigAlgo == ed25519_sa_algo) && + (ssl->peerEd25519KeyPresent)) { + WOLFSSL_MSG("Doing ED25519 peer cert verify"); + ret = Ed25519Verify(ssl, sig, args->sigSz, args->sigData, args->sigDataSz, ssl->peerEd25519Key, #ifdef HAVE_PK_CALLBACKS @@ -10026,7 +10307,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, #else NULL #endif - ); + ); if (ret >= 0) { /* CLIENT/SERVER: data verified with public key from @@ -10039,8 +10320,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, } #endif #ifdef HAVE_ED448 - if (ssl->peerEd448KeyPresent) { - ret = Ed448Verify(ssl, input + args->idx, args->sz, + if ((ssl->options.peerSigAlgo == ed448_sa_algo) && + (ssl->peerEd448KeyPresent)) { + WOLFSSL_MSG("Doing ED448 peer cert verify"); + ret = Ed448Verify(ssl, sig, args->sigSz, args->sigData, args->sigDataSz, ssl->peerEd448Key, #ifdef HAVE_PK_CALLBACKS @@ -10060,104 +10343,159 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, } } #endif - #if defined(HAVE_PQC) && defined(HAVE_FALCON) - if (ssl->peerFalconKeyPresent) { + #if defined(HAVE_FALCON) + if (((ssl->options.peerSigAlgo == falcon_level1_sa_algo) || + (ssl->options.peerSigAlgo == falcon_level5_sa_algo)) && + (ssl->peerFalconKeyPresent)) { int res = 0; - byte *sigIn = input + args->idx; - word32 sigInLen = args->sz; - byte *sigData = args->sigData; - word32 sigDataSz = args->sigDataSz; WOLFSSL_MSG("Doing Falcon peer cert verify"); -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - /* Note: + sig->length; we are skipping the native sig. */ - sigIn = input + args->idx + sig->length; - sigInLen = args->sz - sig->length; - - /* For RSA, something different was verified. */ - if (ssl->peerRsaKeyPresent) { - sigData = args->altSigData; - sigDataSz = args->altSigDataSz; - } - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - ret = wc_falcon_verify_msg(sigIn, sigInLen, - sigData, sigDataSz, + ret = wc_falcon_verify_msg(sig, args->sigSz, + args->sigData, args->sigDataSz, &res, ssl->peerFalconKey); if ((ret >= 0) && (res == 1)) { /* CLIENT/SERVER: data verified with public key from * certificate. */ -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - args->altPeerAuthGood = 1; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - ssl->options.peerAuthGood = 1; + ssl->options.peerAuthGood = 1; FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; } } - #endif /* HAVE_PQC && HAVE_FALCON */ - #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) - if (ssl->peerDilithiumKeyPresent) { + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + if (((ssl->options.peerSigAlgo == dilithium_level2_sa_algo) || + (ssl->options.peerSigAlgo == dilithium_level3_sa_algo) || + (ssl->options.peerSigAlgo == dilithium_level5_sa_algo)) && + (ssl->peerDilithiumKeyPresent)) { int res = 0; - byte *sigIn = input + args->idx; - word32 sigInLen = args->sz; - byte *sigData = args->sigData; - word32 sigDataSz = args->sigDataSz; WOLFSSL_MSG("Doing Dilithium peer cert verify"); -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - /* Go backwards from the end of the signature the size of - * the alt sig to find the beginning of the alt sig. */ - sigIn = input + args->idx + args->sz - args->altSignatureSz; - sigInLen = args->altSignatureSz; - /* For RSA, something different was verified. */ - if (ssl->peerRsaKeyPresent) { - sigData = args->altSigData; - sigDataSz = args->altSigDataSz; - } - } -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - ret = wc_dilithium_verify_msg(sigIn, sigInLen, - sigData, sigDataSz, + ret = wc_dilithium_verify_msg(sig, args->sigSz, + args->sigData, args->sigDataSz, &res, ssl->peerDilithiumKey); if ((ret >= 0) && (res == 1)) { /* CLIENT/SERVER: data verified with public key from * certificate. */ -#ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->sigSpec != NULL && - *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { - args->altPeerAuthGood = 1; - } - else -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - ssl->options.peerAuthGood = 1; + ssl->options.peerAuthGood = 1; FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM, (void**)&ssl->peerDilithiumKey); ssl->peerDilithiumKeyPresent = 0; } } - #endif /* HAVE_PQC && HAVE_DILITHIUM */ + #endif /* HAVE_DILITHIUM */ /* Check for error */ if (ret != 0) { goto exit_dcv; } + #ifdef WOLFSSL_DUAL_ALG_CERTS + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { + /* Move forward to the alternative signature. */ + sig += args->sigSz + OPAQUE16_LEN; + + /* Verify the alternative signature */ + #ifndef NO_RSA + if ((args->altSigAlgo == rsa_pss_sa_algo) && + (ssl->peerRsaKey != NULL) && + (ssl->peerRsaKeyPresent != 0)) { + WOLFSSL_MSG("Doing RSA peer cert alt verify"); + ret = RsaVerify(ssl, rsaSigBuf->buffer, + (word32)rsaSigBuf->length, + &args->output, args->altSigAlgo, + ssl->options.peerHashAlgo, ssl->peerRsaKey, + #ifdef HAVE_PK_CALLBACKS + &ssl->buffers.peerRsaKey + #else + NULL + #endif + ); + if (ret >= 0) { + args->sendSz = ret; + ret = 0; + } + } + #endif /* !NO_RSA */ + #ifdef HAVE_ECC + if ((args->altSigAlgo == ecc_dsa_sa_algo) && + (ssl->peerEccDsaKeyPresent)) { + WOLFSSL_MSG("Doing ECC peer cert alt verify"); + ret = EccVerify(ssl, sig, args->altSignatureSz, + args->altSigData, args->altSigDataSz, + ssl->peerEccDsaKey, + #ifdef HAVE_PK_CALLBACKS + &ssl->buffers.peerEccDsaKey + #else + NULL + #endif + ); + + if (ret >= 0) { + /* CLIENT/SERVER: data verified with public key from + * certificate. */ + args->altPeerAuthGood = 1; + + FreeKey(ssl, DYNAMIC_TYPE_ECC, + (void**)&ssl->peerEccDsaKey); + ssl->peerEccDsaKeyPresent = 0; + } + } + #endif /* HAVE_ECC */ + #if defined(HAVE_FALCON) + if (((args->altSigAlgo == falcon_level1_sa_algo) || + (args->altSigAlgo == falcon_level5_sa_algo)) && + (ssl->peerFalconKeyPresent)) { + int res = 0; + WOLFSSL_MSG("Doing Falcon peer cert alt verify"); + ret = wc_falcon_verify_msg(sig, args->altSignatureSz, + args->altSigData, args->altSigDataSz, + &res, ssl->peerFalconKey); + + if ((ret >= 0) && (res == 1)) { + /* CLIENT/SERVER: data verified with public key from + * certificate. */ + args->altPeerAuthGood = 1; + + FreeKey(ssl, DYNAMIC_TYPE_FALCON, + (void**)&ssl->peerFalconKey); + ssl->peerFalconKeyPresent = 0; + } + } + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + if (((args->altSigAlgo == dilithium_level2_sa_algo) || + (args->altSigAlgo == dilithium_level3_sa_algo) || + (args->altSigAlgo == dilithium_level5_sa_algo)) && + (ssl->peerDilithiumKeyPresent)) { + int res = 0; + WOLFSSL_MSG("Doing Dilithium peer cert alt verify"); + ret = wc_dilithium_verify_msg(sig, args->altSignatureSz, + args->altSigData, args->altSigDataSz, + &res, ssl->peerDilithiumKey); + + if ((ret >= 0) && (res == 1)) { + /* CLIENT/SERVER: data verified with public key from + * certificate. */ + args->altPeerAuthGood = 1; + + FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM, + (void**)&ssl->peerDilithiumKey); + ssl->peerDilithiumKeyPresent = 0; + } + } + #endif /* HAVE_DILITHIUM */ + + /* Check for error */ + if (ret != 0) { + goto exit_dcv; + } + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ + /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_VERIFY; } /* case TLS_ASYNC_DO */ @@ -10167,7 +10505,16 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, { #if !defined(NO_RSA) && defined(WC_RSA_PSS) if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) { - ret = CheckRSASignature(ssl, ssl->options.peerSigAlgo, + int sigAlgo = ssl->options.peerSigAlgo; + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Check if our alternative signature was RSA */ + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH && + ssl->options.peerSigAlgo != rsa_pss_sa_algo) { + sigAlgo = args->altSigAlgo; + } + #endif + ret = CheckRSASignature(ssl, sigAlgo, ssl->options.peerHashAlgo, args->output, args->sendSz); if (ret != 0) goto exit_dcv; @@ -10176,7 +10523,16 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, * certificate. */ ssl->peerRsaKeyPresent = 0; FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey); - ssl->options.peerAuthGood = 1; + #ifdef WOLFSSL_DUAL_ALG_CERTS + /* Check if our alternative signature was RSA */ + if (ssl->sigSpec != NULL && + *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH && + ssl->options.peerSigAlgo != rsa_pss_sa_algo) { + args->altPeerAuthGood = 1; + } + else + #endif + ssl->options.peerAuthGood = 1; } #endif /* !NO_RSA && WC_RSA_PSS */ @@ -10188,8 +10544,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, case TLS_ASYNC_FINALIZE: { #ifdef WOLFSSL_DUAL_ALG_CERTS - if (!wolfSSL_is_server(ssl) && - ssl->options.peerAuthGood && + if (ssl->options.peerAuthGood && ssl->sigSpec != NULL && *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) { ssl->options.peerAuthGood = args->altPeerAuthGood; @@ -10230,7 +10585,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, #ifdef WOLFSSL_ASYNC_CRYPT /* Handle async operation */ - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Mark message as not received so it can process again */ ssl->msgsReceived.got_certificate_verify = 0; @@ -10241,7 +10596,7 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, if (ret != 0) { WOLFSSL_ERROR_VERBOSE(ret); - if (ret != INVALID_PARAMETER) { + if (ret != WC_NO_ERR_TRACE(INVALID_PARAMETER)) { SendAlert(ssl, alert_fatal, decrypt_error); } } @@ -10315,11 +10670,11 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->options.serverState = SERVER_FINISHED_COMPLETE; return ret; } - if (ret == VERIFY_FINISHED_ERROR) { + if (ret == WC_NO_ERR_TRACE(VERIFY_FINISHED_ERROR)) { SendAlert(ssl, alert_fatal, decrypt_error); return ret; } - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { /* other errors */ return ret; } @@ -10487,12 +10842,12 @@ static int SendTls13Finished(WOLFSSL* ssl) input = output + Dtls13GetRlHeaderLength(ssl, 1); #endif /* WOLFSSL_DTLS13 */ - AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl); + AddTls13HandShakeHeader(input, (word32)finishedSz, 0, finishedSz, finished, ssl); #if defined(WOLFSSL_RENESAS_TSIP_TLS) if (ssl->options.side == WOLFSSL_CLIENT_END) { ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return ret; } ret = 0; @@ -10919,7 +11274,7 @@ static int SendTls13EndOfEarlyData(WOLFSSL* ssl) WOLFSSL_ENTER("SendTls13EndOfEarlyData"); length = 0; - sendSz = idx + length + MAX_MSG_EXTRA; + sendSz = (int)(idx + length + MAX_MSG_EXTRA); ssl->options.buildingMsg = 1; /* Check buffers are big enough and grow if needed. */ @@ -11329,7 +11684,7 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) } else #ifdef WOLFSSL_ASYNC_CRYPT - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { ssl->session->ticketNonce.data[0]++; @@ -11375,7 +11730,7 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) /* Nonce */ length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ; - sendSz = idx + length + MAX_MSG_EXTRA; + sendSz = (int)(idx + length + MAX_MSG_EXTRA); /* Check buffers are big enough and grow if needed. */ if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) @@ -12009,7 +12364,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* sanity check msg received */ if ((ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) { WOLFSSL_MSG("Sanity Check on handshake message type received failed"); - if (ret == VERSION_ERROR) + if (ret == WC_NO_ERR_TRACE(VERSION_ERROR)) SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version); else SendAlert(ssl, alert_fatal, unexpected_message); @@ -12117,7 +12472,8 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif ) { #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) - if (ret != WC_PENDING_E && ret != OCSP_WANT_READ) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) && + ret != WC_NO_ERR_TRACE(OCSP_WANT_READ)) #endif { ssl->options.cacheMessages = 0; @@ -12174,7 +12530,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \ - defined(HAVE_ED448) || defined(HAVE_PQC) + defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) case certificate_verify: WOLFSSL_MSG("processing certificate verify"); ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size); @@ -12206,7 +12562,8 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_ASYNC_IO) /* if async, offset index so this msg will be processed again */ /* NOTE: check this now before other calls can overwrite ret */ - if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) { + if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) || + ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) && *inOutIdx > 0) { /* DTLS always stores a message in a buffer when async is enable, so we * don't need to adjust for the extra bytes here (*inOutIdx is always * == 0) */ @@ -12214,13 +12571,15 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, } /* make sure async error is cleared */ - if (ret == 0 && (ssl->error == WC_PENDING_E || ssl->error == OCSP_WANT_READ)) { + if (ret == 0 && + (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) || + ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) { ssl->error = 0; } #endif if (ret == 0 && type != client_hello && type != session_ticket && type != key_update) { - ret = HashInput(ssl, input + inIdx, size); + ret = HashInput(ssl, input + inIdx, (int)size); } alertType = TranslateErrorToAlert(ret); @@ -12233,7 +12592,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, tmp = SendAlert(ssl, alert_fatal, alertType); /* propagate socket error instead of tls error to be sure the error is * not ignored by DTLS code */ - if (tmp == SOCKET_ERROR_E) + if (tmp == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) ret = SOCKET_ERROR_E; } @@ -12330,7 +12689,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) { ret = ssl->error; - if (ret != WC_PENDING_E) + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) ret = POST_HAND_AUTH_ERROR; } } @@ -12475,7 +12834,7 @@ int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ, ssl->arrays->pendingMsgSz); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* setup to process fragment again */ ssl->arrays->pendingMsgOffset -= inputLength; *inOutIdx -= inputLength + ssl->keys.padSz; @@ -12808,8 +13167,8 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) case FIRST_REPLY_THIRD: #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \ defined(HAVE_ED25519) || defined(HAVE_ED448) || \ - defined(HAVE_PQC))) && (!defined(NO_WOLFSSL_SERVER) || \ - !defined(WOLFSSL_NO_CLIENT_AUTH)) + defined(HAVE_FALCON) || defined(HAVE_DILITHIUM))) && \ + (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)) if (!ssl->options.resuming && ssl->options.sendVerify) { ssl->error = SendTls13CertificateVerify(ssl); if (ssl->error != 0) { @@ -13020,14 +13379,14 @@ int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group) #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfSSL_AsyncPop(ssl, NULL); - if (ret != WC_NO_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) { /* Check for error */ if (ret < 0) return ret; } #endif -#ifdef HAVE_PQC +#if defined(WOLFSSL_HAVE_KYBER) if (WOLFSSL_NAMED_GROUP_IS_PQC(group)) { if (ssl->ctx != NULL && ssl->ctx->method != NULL && @@ -13036,10 +13395,11 @@ int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group) } if (ssl->options.side == WOLFSSL_SERVER_END) { - /* If I am the server of a KEM connection, do not do keygen because I'm - * going to encapsulate with the client's public key. Note that I might - * be the client and ssl->option.side has not been properly set yet. In - * that case the KeyGen operation will be deferred to connection time. */ + /* If I am the server of a KEM connection, do not do keygen because + * I'm going to encapsulate with the client's public key. Note that + * I might be the client and ssl->option.side has not been properly + * set yet. In that case the KeyGen operation will be deferred to + * connection time. */ return WOLFSSL_SUCCESS; } } @@ -13389,86 +13749,6 @@ int wolfSSL_preferred_group(WOLFSSL* ssl) } #endif -#if defined(HAVE_SUPPORTED_CURVES) -/* Sets the key exchange groups in rank order on a context. - * - * ctx SSL/TLS context object. - * groups Array of groups. - * count Number of groups in array. - * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or - * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success. - */ -int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count) -{ - int ret, i; - - WOLFSSL_ENTER("wolfSSL_CTX_set_groups"); - if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT) - return BAD_FUNC_ARG; - if (!IsAtLeastTLSv1_3(ctx->method->version)) - return BAD_FUNC_ARG; - - ctx->numGroups = 0; - #if !defined(NO_TLS) - TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap); - #endif /* !NO_TLS */ - for (i = 0; i < count; i++) { - /* Call to wolfSSL_CTX_UseSupportedCurve also checks if input groups - * are valid */ - if ((ret = wolfSSL_CTX_UseSupportedCurve(ctx, (word16)groups[i])) - != WOLFSSL_SUCCESS) { - #if !defined(NO_TLS) - TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap); - #endif /* !NO_TLS */ - return ret; - } - ctx->group[i] = (word16)groups[i]; - } - ctx->numGroups = (byte)count; - - return WOLFSSL_SUCCESS; -} - -/* Sets the key exchange groups in rank order. - * - * ssl SSL/TLS object. - * groups Array of groups. - * count Number of groups in array. - * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or - * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success. - */ -int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count) -{ - int ret, i; - - WOLFSSL_ENTER("wolfSSL_set_groups"); - if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT) - return BAD_FUNC_ARG; - if (!IsAtLeastTLSv1_3(ssl->version)) - return BAD_FUNC_ARG; - - ssl->numGroups = 0; - #if !defined(NO_TLS) - TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap); - #endif /* !NO_TLS */ - for (i = 0; i < count; i++) { - /* Call to wolfSSL_UseSupportedCurve also checks if input groups - * are valid */ - if ((ret = wolfSSL_UseSupportedCurve(ssl, (word16)groups[i])) - != WOLFSSL_SUCCESS) { - #if !defined(NO_TLS) - TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap); - #endif /* !NO_TLS */ - return ret; - } - ssl->group[i] = (word16)groups[i]; - } - ssl->numGroups = (byte)count; - - return WOLFSSL_SUCCESS; -} -#endif /* HAVE_SUPPORTED_CURVES */ - #ifndef NO_PSK /* Set the PSK callback, that is passed the cipher suite, for a client to use * against context object. @@ -14030,7 +14310,8 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) case TLS13_CERT_SENT : #if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \ - defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_PQC)) + defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_FALCON) || \ + defined(HAVE_DILITHIUM)) if (!ssl->options.resuming && ssl->options.sendVerify) { if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) { WOLFSSL_ERROR(ssl->error); @@ -14314,7 +14595,7 @@ int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz) return SIDE_ERROR; if (ssl->options.handShakeState == NULL_STATE) { - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) ssl->earlyData = expecting_early_data; ret = wolfSSL_connect_TLSv13(ssl); if (ret != WOLFSSL_SUCCESS) @@ -14378,7 +14659,7 @@ int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz) return SIDE_ERROR; if (ssl->options.handShakeState == NULL_STATE) { - if (ssl->error != WC_PENDING_E) + if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) ssl->earlyData = expecting_early_data; /* this used to be: ret = wolfSSL_accept_TLSv13(ssl); * However, wolfSSL_accept_TLSv13() expects a certificate to @@ -14474,6 +14755,7 @@ int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret, if (clientRandomSz <= 0) { printf("Error getting server random %d\n", clientRandomSz); + return BAD_FUNC_ARG; } #if 0 diff --git a/src/src/wolfio.c b/src/src/wolfio.c index 041e0b7..52e61a5 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -78,11 +78,15 @@ #elif !defined(DEVKITPRO) && !defined(WOLFSSL_PICOTCP) \ && !defined(WOLFSSL_CONTIKI) && !defined(WOLFSSL_WICED) \ && !defined(WOLFSSL_GNRC) && !defined(WOLFSSL_RIOT_OS) - #include + #ifdef HAVE_NETDB_H + #include + #endif #ifdef __PPU #include #else - #include + #ifdef HAVE_SYS_IOCTL_H + #include + #endif #endif #endif #endif @@ -149,6 +153,11 @@ static WC_INLINE int TranslateReturnCode(int old, int sd) if (errno == RTCSERR_TCP_TIMED_OUT) errno = SOCKET_EAGAIN; } +#elif defined(WOLFSSL_EMNET) + if (old < 0) { /* SOCKET_ERROR */ + /* Get the real socket error */ + IP_SOCK_getsockopt(sd, SOL_SOCKET, SO_ERROR, &old, (int)sizeof(old)); + } #endif return old; @@ -162,7 +171,7 @@ static WC_INLINE int wolfSSL_LastError(int err) return WSAGetLastError(); #elif defined(EBSNET) return xn_getlasterror(); -#elif defined(WOLFSSL_LINUXKM) +#elif defined(WOLFSSL_LINUXKM) || defined(WOLFSSL_EMNET) return err; /* Return provided error value */ #elif defined(FUSION_RTOS) #include @@ -554,7 +563,7 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) start = LowResTimer(); } else { - dtls_timeout -= LowResTimer() - start; + dtls_timeout -= (int) (LowResTimer() - start); start = LowResTimer(); if (dtls_timeout < 0 || dtls_timeout > DTLS_TIMEOUT_MAX) return WOLFSSL_CBIO_ERR_TIMEOUT; @@ -604,7 +613,7 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } #endif /* !NO_ASN_TIME */ - recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, + recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, ssl->rflags, (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL); /* From the RECV(2) man page @@ -712,7 +721,7 @@ int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx) #endif } - sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, sz, ssl->wflags, + sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, (size_t)sz, ssl->wflags, (const SOCKADDR*)peer, peerSz); sent = TranslateReturnCode(sent, sd); @@ -739,7 +748,7 @@ int EmbedReceiveFromMcast(WOLFSSL *ssl, char *buf, int sz, void *ctx) WOLFSSL_ENTER("EmbedReceiveFromMcast"); - recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, NULL, NULL); + recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, ssl->rflags, NULL, NULL); recvd = TranslateReturnCode(recvd, sd); @@ -783,7 +792,7 @@ int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx) if (sz > WC_SHA256_DIGEST_SIZE) sz = WC_SHA256_DIGEST_SIZE; - XMEMCPY(buf, digest, sz); + XMEMCPY(buf, digest, (size_t)sz); return sz; } @@ -977,7 +986,7 @@ int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags) { int recvd; - recvd = (int)RECV_FUNCTION(sd, buf, sz, rdFlags); + recvd = (int)RECV_FUNCTION(sd, buf, (size_t)sz, rdFlags); recvd = TranslateReturnCode(recvd, (int)sd); return recvd; @@ -987,7 +996,7 @@ int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags) { int sent; - sent = (int)SEND_FUNCTION(sd, buf, sz, wrFlags); + sent = (int)SEND_FUNCTION(sd, buf, (size_t)sz, wrFlags); sent = TranslateReturnCode(sent, (int)sd); return sent; @@ -1079,9 +1088,9 @@ int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags) } #endif /* HAVE_IO_TIMEOUT */ -static int wolfIO_Word16ToString(char* d, word16 number) +static word32 wolfIO_Word16ToString(char* d, word16 number) { - int i = 0; + word32 i = 0; word16 order = 10000; word16 digit; @@ -1096,7 +1105,7 @@ static int wolfIO_Word16ToString(char* d, word16 number) if (i > 0 || digit != 0) d[i++] = (char)digit + '0'; if (digit != 0) - number %= digit * order; + number = (word16) (number % (digit * order)); order = (order > 1) ? order / 10 : 0; } @@ -1111,7 +1120,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) #ifdef HAVE_SOCKADDR int ret = 0; SOCKADDR_S addr; - int sockaddr_len; + socklen_t sockaddr_len; #if defined(HAVE_GETADDRINFO) /* use getaddrinfo */ ADDRINFO hints; @@ -1175,7 +1184,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) } sockaddr_len = answer->ai_addrlen; - XMEMCPY(&addr, answer->ai_addr, sockaddr_len); + XMEMCPY(&addr, answer->ai_addr, (size_t)sockaddr_len); freeaddrinfo(answer); #elif defined(WOLFSSL_USE_POPEN_HOST) && !defined(WOLFSSL_IPV6) { @@ -1338,7 +1347,7 @@ int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port) #ifdef HAVE_SOCKADDR int ret = 0; SOCKADDR_S addr; - int sockaddr_len = sizeof(SOCKADDR_IN); + socklen_t sockaddr_len = sizeof(SOCKADDR_IN); SOCKADDR_IN *sin = (SOCKADDR_IN *)&addr; if (sockfd == NULL || port < 1) { @@ -1469,7 +1478,7 @@ int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath, for (j = 0; j < i; j++) { if (port[j] < '0' || port[j] > '9') return -1; - bigPort = (bigPort * 10) + (port[j] - '0'); + bigPort = (bigPort * 10) + (word32)(port[j] - '0'); } if (outPort) *outPort = (word16)bigPort; @@ -1524,7 +1533,7 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, return MEMORY_E; } - newRecvBuf = (byte*)XMALLOC(newRecvSz, heap, dynType); + newRecvBuf = (byte*)XMALLOC((size_t)newRecvSz, heap, dynType); if (newRecvBuf == NULL) { WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf malloc failed"); return MEMORY_E; @@ -1532,7 +1541,7 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, /* if buffer already exists, then we are growing it */ if (*recvBuf) { - XMEMCPY(&newRecvBuf[pos], *recvBuf, *recvBufSz); + XMEMCPY(&newRecvBuf[pos], *recvBuf, (size_t) *recvBufSz); XFREE(*recvBuf, heap, dynType); pos += *recvBufSz; *recvBuf = NULL; @@ -1541,7 +1550,7 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, /* copy the remainder of the httpBuf into the respBuf */ if (len != 0) { if (pos + len <= newRecvSz) { - XMEMCPY(&newRecvBuf[pos], start, len); + XMEMCPY(&newRecvBuf[pos], start, (size_t)len); pos += len; } else { @@ -1603,6 +1612,11 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, /* read data if no \r\n or first time */ if ((start == NULL) || (end == NULL)) { + if (httpBufSz < len + 1) { + return BUFFER_ERROR; /* can't happen, but Coverity thinks it + * can. + */ + } result = wolfIO_Recv(sfd, (char*)httpBuf+len, httpBufSz-len-1, 0); if (result > 0) { len += result; @@ -1625,7 +1639,7 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, /* handle incomplete rx */ if (end == NULL) { if (len != 0) - XMEMMOVE(httpBuf, start, len); + XMEMMOVE(httpBuf, start, (size_t)len); start = end = NULL; } /* when start is "\r\n" */ @@ -1751,7 +1765,7 @@ int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName, return wolfIO_HttpBuildRequest_ex(reqType, domainName, path, pathLen, reqSz, contentType, "", buf, bufSize); } - int wolfIO_HttpBuildRequest_ex(const char *reqType, const char *domainName, +int wolfIO_HttpBuildRequest_ex(const char *reqType, const char *domainName, const char *path, int pathLen, int reqSz, const char *contentType, const char *exHdrs, byte *buf, int bufSize) { @@ -1793,7 +1807,7 @@ int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName, maxLen = reqTypeLen + blankStrLen + - pathLen + + (word32)pathLen + http11StrLen + hostStrLen + domainNameLen + @@ -1804,46 +1818,46 @@ int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName, singleCrLfStrLen + exHdrsLen + doubleCrLfStrLen + - 1 /* null term */; + (word32)1 /* null term */; if (maxLen > (word32)bufSize) return 0; - XSTRNCPY((char*)buf, reqType, bufSize); - buf += reqTypeLen; bufSize -= reqTypeLen; - XSTRNCPY((char*)buf, blankStr, bufSize); - buf += blankStrLen; bufSize -= blankStrLen; - XSTRNCPY((char*)buf, path, bufSize); - buf += pathLen; bufSize -= pathLen; - XSTRNCPY((char*)buf, http11Str, bufSize); - buf += http11StrLen; bufSize -= http11StrLen; + XSTRNCPY((char*)buf, reqType, (size_t)bufSize); + buf += reqTypeLen; bufSize -= (int)reqTypeLen; + XSTRNCPY((char*)buf, blankStr, (size_t)bufSize); + buf += blankStrLen; bufSize -= (int)blankStrLen; + XSTRNCPY((char*)buf, path, (size_t)bufSize); + buf += pathLen; bufSize -= (int)pathLen; + XSTRNCPY((char*)buf, http11Str, (size_t)bufSize); + buf += http11StrLen; bufSize -= (int)http11StrLen; if (domainNameLen > 0) { - XSTRNCPY((char*)buf, hostStr, bufSize); - buf += hostStrLen; bufSize -= hostStrLen; - XSTRNCPY((char*)buf, domainName, bufSize); - buf += domainNameLen; bufSize -= domainNameLen; + XSTRNCPY((char*)buf, hostStr, (size_t)bufSize); + buf += hostStrLen; bufSize -= (int)hostStrLen; + XSTRNCPY((char*)buf, domainName, (size_t)bufSize); + buf += domainNameLen; bufSize -= (int)domainNameLen; } if (reqSz > 0 && reqSzStrLen > 0) { - XSTRNCPY((char*)buf, contentLenStr, bufSize); - buf += contentLenStrLen; bufSize -= contentLenStrLen; - XSTRNCPY((char*)buf, reqSzStr, bufSize); - buf += reqSzStrLen; bufSize -= reqSzStrLen; + XSTRNCPY((char*)buf, contentLenStr, (size_t)bufSize); + buf += contentLenStrLen; bufSize -= (int)contentLenStrLen; + XSTRNCPY((char*)buf, reqSzStr, (size_t)bufSize); + buf += reqSzStrLen; bufSize -= (int)reqSzStrLen; } if (contentTypeLen > 0) { - XSTRNCPY((char*)buf, contentTypeStr, bufSize); - buf += contentTypeStrLen; bufSize -= contentTypeStrLen; - XSTRNCPY((char*)buf, contentType, bufSize); - buf += contentTypeLen; bufSize -= contentTypeLen; + XSTRNCPY((char*)buf, contentTypeStr, (size_t)bufSize); + buf += contentTypeStrLen; bufSize -= (int)contentTypeStrLen; + XSTRNCPY((char*)buf, contentType, (size_t)bufSize); + buf += contentTypeLen; bufSize -= (int)contentTypeLen; } if (exHdrsLen > 0) { - XSTRNCPY((char *)buf, singleCrLfStr, bufSize); + XSTRNCPY((char *)buf, singleCrLfStr, (size_t)bufSize); buf += singleCrLfStrLen; - bufSize -= singleCrLfStrLen; - XSTRNCPY((char *)buf, exHdrs, bufSize); + bufSize -= (int)singleCrLfStrLen; + XSTRNCPY((char *)buf, exHdrs, (size_t)bufSize); buf += exHdrsLen; - bufSize -= exHdrsLen; + bufSize -= (int)exHdrsLen; } - XSTRNCPY((char*)buf, doubleCrLfStr, bufSize); + XSTRNCPY((char*)buf, doubleCrLfStr, (size_t)bufSize); buf += doubleCrLfStrLen; #ifdef WOLFIO_DEBUG @@ -1920,7 +1934,7 @@ int EmbedOcspLookup(void* ctx, const char* url, int urlSz, /* Note, the library uses the EmbedOcspRespFree() callback to * free this buffer. */ int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE; - byte* httpBuf = (byte*)XMALLOC(httpBufSz, ctx, DYNAMIC_TYPE_OCSP); + byte* httpBuf = (byte*)XMALLOC((size_t)httpBufSz, ctx, DYNAMIC_TYPE_OCSP); if (httpBuf == NULL) { WOLFSSL_MSG("Unable to create OCSP response buffer"); @@ -2027,7 +2041,7 @@ int EmbedCrlLookup(WOLFSSL_CRL* crl, const char* url, int urlSz) } else { int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE; - byte* httpBuf = (byte*)XMALLOC(httpBufSz, crl->heap, + byte* httpBuf = (byte*)XMALLOC((size_t)httpBufSz, crl->heap, DYNAMIC_TYPE_CRL); if (httpBuf == NULL) { WOLFSSL_MSG("Unable to create CRL response buffer"); diff --git a/src/src/x509.c b/src/src/x509.c index eefa69c..72a4f37 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -177,19 +177,19 @@ int wolfSSL_X509_get_ext_count(const WOLFSSL_X509* passedCert) goto out; } - if (GetLength(input, &idx, &length, sz) < 0) { + if (GetLength(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: invalid length"); goto out; } } - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)"); goto out; } while (idx < (word32)sz) { - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE"); FreeDecodedCert(cert); return WOLFSSL_FAILURE; @@ -643,7 +643,7 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, wolfSSL_ASN1_OBJECT_free(obj); goto err; } - wolfSSL_ASN1_STRING_set(str, p, (word32)len); + wolfSSL_ASN1_STRING_set(str, p, (int)len); /* Wrap string in a WOLFSSL_ASN1_TYPE. */ type = wolfSSL_ASN1_TYPE_new(); @@ -839,7 +839,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) return NULL; } - if (GetLength(input, &idx, &length, sz) < 0) { + if (GetLength(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: invalid length"); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); @@ -850,7 +850,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } } - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)"); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); @@ -863,7 +863,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) while (idx < (word32)sz) { oid = 0; - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE"); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); @@ -874,7 +874,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } tmpIdx = idx; - ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz); + ret = GetObjectId(input, &idx, &oid, oidCertExtType, (word32)sz); if (ret < 0) { WOLFSSL_MSG("\tfail: OBJECT ID"); wolfSSL_X509_EXTENSION_free(ext); @@ -895,11 +895,11 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } /* extCount == loc. Now get the extension. */ /* Check if extension has been set */ - isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, nid); + isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, (int)nid); - if (wolfSSL_OBJ_nid2ln(nid) != NULL) { + if (wolfSSL_OBJ_nid2ln((int)nid) != NULL) { /* This is NOT an unknown OID. */ - ext->obj = wolfSSL_OBJ_nid2obj(nid); + ext->obj = wolfSSL_OBJ_nid2obj((int)nid); if (ext->obj == NULL) { WOLFSSL_MSG("\tfail: Invalid OBJECT"); wolfSSL_X509_EXTENSION_free(ext); @@ -912,7 +912,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } if (ext->obj) { - ext->obj->nid = nid; + ext->obj->nid = (int)nid; } switch (oid) { @@ -929,7 +929,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) #endif return NULL; } - a->length = x509->pathLength; + a->length = (int)x509->pathLength; /* Save ASN1_INTEGER in x509 extension */ ext->obj->pathlen = a; @@ -972,7 +972,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) return NULL; } obj->obj = (byte*)x509->authInfoCaIssuer; - obj->objSz = x509->authInfoCaIssuerSz; + obj->objSz = (unsigned int)x509->authInfoCaIssuerSz; obj->grp = oidCertAuthInfoType; obj->nid = NID_ad_ca_issuers; @@ -1007,7 +1007,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) return NULL; } obj->obj = x509->authInfo; - obj->objSz = x509->authInfoSz; + obj->objSz = (unsigned int)x509->authInfoSz; obj->grp = oidCertAuthInfoType; obj->nid = NID_ad_OCSP; @@ -1132,7 +1132,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) * parsed oid for access in later function calls */ /* Get OID from input */ - if (GetASNObjectId(input, &idx, &length, sz) != 0) { + if (GetASNObjectId(input, &idx, &length, (word32)sz) != 0) { WOLFSSL_MSG("Failed to Get ASN Object Id"); wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); @@ -1171,7 +1171,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } } - ext->obj->objSz = objSz; + ext->obj->objSz = (unsigned int)objSz; if(((ext->obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || (ext->obj->obj == NULL)) { ext->obj->obj =(byte*)XREALLOC((byte*)ext->obj->obj, @@ -1215,7 +1215,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) tmpIdx++; - if (GetLength(input, &tmpIdx, &length, sz) <= 0) { + if (GetLength(input, &tmpIdx, &length, (word32)sz) <= 0) { WOLFSSL_MSG("Error: Invalid Input Length."); wolfSSL_ASN1_OBJECT_free(ext->obj); wolfSSL_X509_EXTENSION_free(ext); @@ -1283,7 +1283,7 @@ static int asn1_string_copy_to_buffer(WOLFSSL_ASN1_STRING* str, byte** buf, WOLFSSL_MSG("malloc error"); return WOLFSSL_FAILURE; } - *len = str->length; + *len = (word32)str->length; XMEMCPY(*buf, str->data, str->length); } @@ -1418,7 +1418,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo x509->isCa = (byte)ext->obj->ca; x509->basicConstCrit = (byte)ext->crit; if (ext->obj->pathlen) - x509->pathLength = ext->obj->pathlen->length; + x509->pathLength = (word32)ext->obj->pathlen->length; x509->basicConstSet = 1; } break; @@ -1545,7 +1545,7 @@ int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, WOLFSSL_MSG("Memory error"); return rc; } - valLen = XSNPRINTF(val, len, "%*s%s", indent, "", + valLen = XSNPRINTF(val, (size_t)len, "%*s%s", indent, "", str->strData); if ((valLen < 0) || (valLen >= len) || ((tmpLen + valLen) >= tmpSz)) { @@ -2108,13 +2108,13 @@ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) goto out; } - if (GetLength(input, &idx, &length, sz) < 0) { + if (GetLength(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: invalid length"); goto out; } } - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)"); goto out; } @@ -2122,13 +2122,13 @@ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) while (idx < (word32)sz) { oid = 0; - if (GetSequence(input, &idx, &length, sz) < 0) { + if (GetSequence(input, &idx, &length, (word32)sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE"); goto out; } tmpIdx = idx; - ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz); + ret = GetObjectId(input, &idx, &oid, oidCertExtType, (word32)sz); if (ret < 0) { WOLFSSL_MSG("\tfail: OBJECT ID"); goto out; @@ -2138,7 +2138,7 @@ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) if (extCount >= loc) { /* extCount >= loc. Now check if extension has been set */ - isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, foundNID); + isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, (int)foundNID); if (isSet && ((word32)nid == foundNID)) { found = 1; @@ -2218,7 +2218,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, wolfSSL_BASIC_CONSTRAINTS_free(bc); return NULL; } - a->length = x509->pathLength; + a->length = (int)x509->pathLength; #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \ defined(WOLFSSL_APACHE_HTTPD) @@ -2395,7 +2395,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, obj->type = AUTH_INFO_OID; obj->grp = oidCertExtType; obj->obj = x509->authInfo; - obj->objSz = x509->authInfoSz; + obj->objSz = (unsigned int)x509->authInfoSz; } else { WOLFSSL_MSG("No Auth Info set"); @@ -2684,7 +2684,7 @@ int wolfSSL_X509_add_altname_ex(WOLFSSL_X509* x509, const char* name, newAltName->next = x509->altNames; newAltName->type = type; - newAltName->len = nameSz; + newAltName->len = (int)nameSz; newAltName->name = nameCopy; x509->altNames = newAltName; @@ -3296,7 +3296,7 @@ char* wolfSSL_X509_NAME_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) return NULL; } - copySz = min(sz, name->sz); + copySz = (int)min((word32)sz, (word32)name->sz); WOLFSSL_ENTER("wolfSSL_X509_NAME_oneline"); if (!name->sz) return in; @@ -3362,7 +3362,7 @@ static unsigned long X509NameHash(WOLFSSL_X509_NAME* name, ((unsigned long)digest[1] << 8) | ((unsigned long)digest[0])); } - else if (rc == HASH_TYPE_E) { + else if (rc == WC_NO_ERR_TRACE(HASH_TYPE_E)) { WOLFSSL_ERROR_MSG("Hash function not compiled in"); } else { @@ -3500,7 +3500,7 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) WOLFSSL_MSG("Memory error"); return NULL; } - if ((strLen = XSNPRINTF(str, strSz, "%s=%s, ", sn, buf)) + if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s, ", sn, buf)) >= strSz) { WOLFSSL_MSG("buffer overrun"); @@ -3518,7 +3518,7 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) WOLFSSL_MSG("Memory error"); return NULL; } - if ((strLen = XSNPRINTF(str, strSz, "%s=%s", sn, buf)) >= strSz) { + if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s", sn, buf)) >= strSz) { WOLFSSL_MSG("buffer overrun"); XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER); return NULL; @@ -3608,11 +3608,11 @@ static WOLFSSL_X509* d2i_X509orX509REQ(WOLFSSL_X509** x509, return NULL; #endif - InitDecodedCert(cert, (byte*)in, len, heap); + InitDecodedCert(cert, (byte*)in, (word32)len, heap); #ifdef WOLFSSL_CERT_REQ cert->isCSR = (byte)req; #endif - if (ParseCertRelative(cert, type, 0, NULL) == 0) { + if (ParseCertRelative(cert, type, 0, NULL, NULL) == 0) { newX509 = wolfSSL_X509_new_ex(heap); if (newX509 != NULL) { if (CopyDecodedToX509(newX509, cert) != 0) { @@ -3732,7 +3732,7 @@ int wolfSSL_X509_get_signature(WOLFSSL_X509* x509, if (buf != NULL) XMEMCPY(buf, x509->sig.buffer, x509->sig.length); - *bufSz = x509->sig.length; + *bufSz = (int)x509->sig.length; return WOLFSSL_SUCCESS; } @@ -3780,7 +3780,7 @@ int wolfSSL_X509_get_pubkey_buffer(WOLFSSL_X509* x509, der = wolfSSL_X509_get_der(x509, &derSz); if (der != NULL) { - InitDecodedCert(cert, der, derSz, NULL); + InitDecodedCert(cert, der, (word32)derSz, NULL); ret = wc_GetPubX509(cert, 0, &badDate); if (ret >= 0) { word32 idx = cert->srcIdx; @@ -3938,12 +3938,12 @@ const unsigned char* wolfSSL_X509_get_tbs(WOLFSSL_X509* x509, int* outSz) return NULL; } - if (GetSequence(der, &idx, &len, sz) < 0) { + if (GetSequence(der, &idx, &len, (word32)sz) < 0) { return NULL; } tbs = der + idx; tmpIdx = idx; - if (GetSequence(der, &idx, &len, sz) < 0) { + if (GetSequence(der, &idx, &len, (word32)sz) < 0) { return NULL; } *outSz = len + (idx - tmpIdx); @@ -5119,7 +5119,7 @@ WOLFSSL_X509* wolfSSL_X509_d2i_fp(WOLFSSL_X509** x509, XFILE file) fileBuffer = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuffer != NULL) { - int ret = (int)XFREAD(fileBuffer, 1, sz, file); + int ret = (int)XFREAD(fileBuffer, 1, (size_t)sz, file); if (ret == sz) { newX509 = wolfSSL_X509_d2i(NULL, fileBuffer, (int)sz); } @@ -5189,7 +5189,7 @@ WOLFSSL_X509* wolfSSL_X509_load_certificate_file(const char* fname, int format) dynamic = 1; } - ret = (int)XFREAD(fileBuffer, 1, sz, file); + ret = (int)XFREAD(fileBuffer, 1, (size_t)sz, file); if (ret != sz) { XFCLOSE(file); if (dynamic) @@ -5254,7 +5254,7 @@ static WOLFSSL_X509* loadX509orX509REQFromBuffer( #endif { InitDecodedCert(cert, der->buffer, der->length, NULL); - ret = ParseCertRelative(cert, type, 0, NULL); + ret = ParseCertRelative(cert, type, 0, NULL, NULL); if (ret == 0) { x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), NULL, DYNAMIC_TYPE_X509); @@ -5451,7 +5451,7 @@ int wolfSSL_X509_NAME_get_text_by_NID(WOLFSSL_X509_NAME* name, /* buf is not NULL from above */ if (text != NULL) { - textSz = min(textSz + 1, len); /* + 1 to account for null char */ + textSz = (int)min((word32)textSz + 1, (word32)len); /* + 1 to account for null char */ if (textSz > 0) { XMEMCPY(buf, text, textSz - 1); buf[textSz - 1] = '\0'; @@ -5495,7 +5495,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) return NULL; } XMEMCPY(key->pkey.ptr, x509->pubKey.buffer, x509->pubKey.length); - key->pkey_sz = x509->pubKey.length; + key->pkey_sz = (int)x509->pubKey.length; #ifdef HAVE_ECC key->pkey_curve = (int)x509->pkCurveOID; @@ -5735,8 +5735,8 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) if (x509 != NULL) { if (x509->authKeyIdSet) { - copySz = min(dstLen != NULL ? *dstLen : 0, - (int)x509->authKeyIdSz); + copySz = (int)min(dstLen != NULL ? (word32)*dstLen : 0, + x509->authKeyIdSz); id = x509->authKeyId; } @@ -5762,8 +5762,8 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) if (x509 != NULL) { if (x509->subjKeyIdSet) { - copySz = min(dstLen != NULL ? *dstLen : 0, - (int)x509->subjKeyIdSz); + copySz = (int)min(dstLen != NULL ? (word32) *dstLen : 0, + x509->subjKeyIdSz); id = x509->subjKeyId; } @@ -7079,7 +7079,7 @@ void wolfSSL_X509_get0_signature(const WOLFSSL_ASN1_BIT_STRING **psig, #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) const char* wolfSSL_X509_verify_cert_error_string(long err) { - return wolfSSL_ERR_reason_error_string(err); + return wolfSSL_ERR_reason_error_string((unsigned long)err); } #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ @@ -7526,11 +7526,24 @@ int wolfSSL_i2d_X509(WOLFSSL_X509* x509, unsigned char** out) int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { int ret = 0; WOLFSSL_X509 *x = NULL; + byte certOwnsAltNames = 0; + byte certIsCSR = 0; if ((cert == NULL) || (der == NULL) || (derSz <= 0)) { return BAD_FUNC_ARG; } + /* The call to CopyDecodedToX509() transfers ownership of the altNames in + * the DecodedCert to the temporary X509 object, causing the list to be + * freed in wolfSSL_X509_free(). As this is an unintended side-effect, we + * have to save the ownerFlag here and transfer ownership back to the + * DecodedCert prior to freeing the X509 object. */ + certOwnsAltNames = cert->weOwnAltNames; + +#ifdef WOLFSSL_CERT_REQ + certIsCSR = cert->isCSR; +#endif + x = wolfSSL_X509_new(); if (x == NULL) { ret = MEMORY_E; @@ -7539,21 +7552,27 @@ int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { ret = CopyDecodedToX509(x, cert); } + /* CopyDecodedToX509() clears cert->weOwnAltNames. Restore it. */ + cert->weOwnAltNames = certOwnsAltNames; + if (ret == 0) { /* Remove the altsigval extension. */ XFREE(x->altSigValDer, x->heap, DYNAMIC_TYPE_X509_EXT); x->altSigValDer = NULL; - x->altSigValDer = 0; + x->altSigValLen = 0; /* Remove sigOID so it won't be encoded. */ x->sigOID = 0; /* We now have a PreTBS. Encode it. */ - ret = wolfssl_x509_make_der(x, 0, der, &derSz, 0); + ret = wolfssl_x509_make_der(x, certIsCSR, der, &derSz, 0); if (ret == WOLFSSL_SUCCESS) { ret = derSz; } } if (x != NULL) { + /* Safe the altNames list from being freed unitentionally. */ + x->altNames = NULL; + wolfSSL_X509_free(x); } @@ -7683,11 +7702,11 @@ static int verifyX509orX509REQ(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, int r #ifdef WOLFSSL_CERT_REQ if (req) - ret = CheckCSRSignaturePubKey(der, derSz, x509->heap, + ret = CheckCSRSignaturePubKey(der, (word32)derSz, x509->heap, (unsigned char*)pkey->pkey.ptr, pkey->pkey_sz, type); else #endif - ret = CheckCertSignaturePubKey(der, derSz, x509->heap, + ret = CheckCertSignaturePubKey(der, (word32)derSz, x509->heap, (unsigned char*)pkey->pkey.ptr, pkey->pkey_sz, type); if (ret == 0) { return WOLFSSL_SUCCESS; @@ -7739,7 +7758,7 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) fileBuffer = (byte *)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE); if (fileBuffer != NULL) { - if ((long)XFREAD(fileBuffer, 1, sz, file) != sz) { + if ((long)XFREAD(fileBuffer, 1, (size_t)sz, file) != sz) { WOLFSSL_MSG("File read failed"); goto err_exit; } @@ -7761,7 +7780,7 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) if ((newx509 = wc_PKCS12_new()) == NULL) { goto err_exit; } - if (wc_d2i_PKCS12(fileBuffer, (int)sz, (WC_PKCS12*)newx509) < 0) { + if (wc_d2i_PKCS12(fileBuffer, (word32)sz, (WC_PKCS12*)newx509) < 0) { goto err_exit; } } @@ -8217,7 +8236,8 @@ int wolfSSL_X509_CRL_get_signature(WOLFSSL_X509_CRL* crl, { WOLFSSL_ENTER("wolfSSL_X509_CRL_get_signature"); - if (crl == NULL || crl->crlList == NULL || bufSz == NULL) + if (crl == NULL || crl->crlList == NULL || + crl->crlList->signature == NULL || bufSz == NULL) return BAD_FUNC_ARG; if (buf != NULL) @@ -8408,7 +8428,7 @@ static int X509CRLPrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509_CRL* crl, } tmp[0] = '\0'; } - if (XSNPRINTF(val, valSz, ":%02X", crl->crlList->extAuthKeyId[i]) + if (XSNPRINTF(val, (size_t)valSz, ":%02X", crl->crlList->extAuthKeyId[i]) >= valSz) { WOLFSSL_MSG("buffer overrun"); @@ -8794,7 +8814,7 @@ static int wolfSSL_X509_VERIFY_PARAM_inherit(WOLFSSL_X509_VERIFY_PARAM *to, if (isOverWrite || (from->hostName[0] != 0 && (to->hostName[0] == 0 || isDefault))) { if (!(ret = wolfSSL_X509_VERIFY_PARAM_set1_host(to, from->hostName, - (int)XSTRLEN(from->hostName)))) + (unsigned int)XSTRLEN(from->hostName)))) return ret; to->hostFlags = from->hostFlags; } @@ -9196,7 +9216,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_X509_get_serialNumber(WOLFSSL_X509* x509) wolfSSL_ASN1_INTEGER_free(a); return NULL; } - a->dataMax = x509->serialSz + 2; + a->dataMax = (unsigned int)x509->serialSz + 2; a->isDynamic = 1; } else { /* Use array instead of dynamic memory */ @@ -9722,7 +9742,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( if (ret > 0) { /* strip off sequence, this gets added on certificate creation */ - ret = GetSequence(der, &idx, &length, ret); + ret = GetSequence(der, &idx, &length, (word32)ret); } if (ret > 0) { @@ -9765,7 +9785,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( #ifdef WOLFSSL_CERT_EXT if (req->subjKeyIdSz != 0) { XMEMCPY(cert->skid, req->subjKeyId, req->subjKeyIdSz); - cert->skidSz = req->subjKeyIdSz; + cert->skidSz = (int)req->subjKeyIdSz; } if (req->keyUsageSet) cert->keyUsage = req->keyUsage; @@ -9847,7 +9867,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } out[0] = (byte) t->type; - sz = SetLength(t->length, out + 1) + 1; /* gen tag */ + sz = (int)SetLength((word32)t->length, out + 1) + 1; /* gen tag */ for (i = 0; i < t->length; i++) { out[sz + i] = t->data[i]; } @@ -10171,6 +10191,15 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( #endif #ifndef NO_DSA DsaKey* dsa = NULL; + #endif + #if defined(HAVE_FALCON) + falcon_key* falcon = NULL; + #endif + #if defined(HAVE_DILITHIUM) + dilithium_key* dilithium = NULL; + #endif + #if defined(HAVE_SPHINCS) + sphincs_key* sphincs = NULL; #endif WC_RNG rng; word32 idx = 0; @@ -10297,6 +10326,148 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } key = (void*)dsa; } + #endif + #if defined(HAVE_FALCON) + if ((x509->pubKeyOID == FALCON_LEVEL1k) || + (x509->pubKeyOID == FALCON_LEVEL5k)) { + falcon = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL, + DYNAMIC_TYPE_FALCON); + if (falcon == NULL) { + WOLFSSL_MSG("Failed to allocate memory for falcon_key"); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return WOLFSSL_FAILURE; + } + + ret = wc_falcon_init(falcon); + if (ret != 0) { + XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + + if (x509->pubKeyOID == FALCON_LEVEL1k) { + type = FALCON_LEVEL1_TYPE; + wc_falcon_set_level(falcon, 1); + } + else if (x509->pubKeyOID == FALCON_LEVEL5k) { + type = FALCON_LEVEL5_TYPE; + wc_falcon_set_level(falcon, 5); + } + + ret = wc_Falcon_PublicKeyDecode(x509->pubKey.buffer, &idx, falcon, + x509->pubKey.length); + if (ret != 0) { + WOLFSSL_ERROR_VERBOSE(ret); + wc_falcon_free(falcon); + XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + key = (void*)falcon; + } + #endif + #if defined(HAVE_DILITHIUM) + if ((x509->pubKeyOID == DILITHIUM_LEVEL2k) || + (x509->pubKeyOID == DILITHIUM_LEVEL3k) || + (x509->pubKeyOID == DILITHIUM_LEVEL5k)) { + dilithium = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL, + DYNAMIC_TYPE_DILITHIUM); + if (dilithium == NULL) { + WOLFSSL_MSG("Failed to allocate memory for dilithium_key"); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return WOLFSSL_FAILURE; + } + + ret = wc_dilithium_init(dilithium); + if (ret != 0) { + XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + + if (x509->pubKeyOID == DILITHIUM_LEVEL2k) { + type = DILITHIUM_LEVEL2_TYPE; + wc_dilithium_set_level(dilithium, 2); + } + else if (x509->pubKeyOID == DILITHIUM_LEVEL3k) { + type = DILITHIUM_LEVEL3_TYPE; + wc_dilithium_set_level(dilithium, 3); + } + else if (x509->pubKeyOID == DILITHIUM_LEVEL5k) { + type = DILITHIUM_LEVEL5_TYPE; + wc_dilithium_set_level(dilithium, 5); + } + + ret = wc_Dilithium_PublicKeyDecode(x509->pubKey.buffer, &idx, + dilithium, x509->pubKey.length); + if (ret != 0) { + WOLFSSL_ERROR_VERBOSE(ret); + wc_dilithium_free(dilithium); + XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + key = (void*)dilithium; + } + #endif + #if defined(HAVE_SPHINCS) + if ((x509->pubKeyOID == SPHINCS_FAST_LEVEL1k) || + (x509->pubKeyOID == SPHINCS_FAST_LEVEL3k) || + (x509->pubKeyOID == SPHINCS_FAST_LEVEL5k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL1k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL3k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL5k)) { + sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL, + DYNAMIC_TYPE_SPHINCS); + if (sphincs == NULL) { + WOLFSSL_MSG("Failed to allocate memory for sphincs_key"); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return WOLFSSL_FAILURE; + } + + ret = wc_sphincs_init(sphincs); + if (ret != 0) { + XFREE(sphincs, NULL, DYNAMIC_TYPE_SPHINCS); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + + if (x509->pubKeyOID == SPHINCS_FAST_LEVEL1k) { + type = SPHINCS_FAST_LEVEL1_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT); + } + else if (x509->pubKeyOID == SPHINCS_FAST_LEVEL3k) { + type = SPHINCS_FAST_LEVEL3_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT); + } + else if (x509->pubKeyOID == SPHINCS_FAST_LEVEL3k) { + type = SPHINCS_FAST_LEVEL5_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT); + } + else if (x509->pubKeyOID == SPHINCS_SMALL_LEVEL1k) { + type = SPHINCS_SMALL_LEVEL1_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT); + } + else if (x509->pubKeyOID == SPHINCS_SMALL_LEVEL3k) { + type = SPHINCS_SMALL_LEVEL3_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT); + } + else if (x509->pubKeyOID == SPHINCS_SMALL_LEVEL3k) { + type = SPHINCS_SMALL_LEVEL5_TYPE; + wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT); + } + + ret = wc_Sphincs_PublicKeyDecode(x509->pubKey.buffer, &idx, sphincs, + x509->pubKey.length); + if (ret != 0) { + WOLFSSL_ERROR_VERBOSE(ret); + wc_sphincs_free(sphincs); + XFREE(sphincs, NULL, DYNAMIC_TYPE_SPHINCS); + XFREE(cert, NULL, DYNAMIC_TYPE_CERT); + return ret; + } + key = (void*)sphincs; + } #endif if (key == NULL) { WOLFSSL_MSG("No public key found for certificate"); @@ -10397,6 +10568,32 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( wc_FreeDsaKey(dsa); XFREE(dsa, NULL, DYNAMIC_TYPE_DSA); } + #endif + #if defined(HAVE_FALCON) + if ((x509->pubKeyOID == FALCON_LEVEL1k) || + (x509->pubKeyOID == FALCON_LEVEL5k)) { + wc_falcon_free(falcon); + XFREE(falcon, NULL, DYNAMIC_TYPE_FALCON); + } + #endif + #if defined(HAVE_DILITHIUM) + if ((x509->pubKeyOID == DILITHIUM_LEVEL2k) || + (x509->pubKeyOID == DILITHIUM_LEVEL3k) || + (x509->pubKeyOID == DILITHIUM_LEVEL5k)) { + wc_dilithium_free(dilithium); + XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); + } + #endif + #if defined(HAVE_SPHINCS) + if ((x509->pubKeyOID == SPHINCS_FAST_LEVEL1k) || + (x509->pubKeyOID == SPHINCS_FAST_LEVEL3k) || + (x509->pubKeyOID == SPHINCS_FAST_LEVEL5k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL1k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL3k) || + (x509->pubKeyOID == SPHINCS_SMALL_LEVEL5k)) { + wc_sphincs_free(sphincs); + XFREE(sphincs, NULL, DYNAMIC_TYPE_SPHINCS); + } #endif XFREE(cert, NULL, DYNAMIC_TYPE_CERT); @@ -10449,7 +10646,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( ret = wc_InitRng(&rng); if (ret != 0) return ret; - ret = wc_SignCert_ex(certBodySz, sigType, der, derSz, type, key, &rng); + ret = wc_SignCert_ex(certBodySz, sigType, der, (word32)derSz, type, key, &rng); wc_FreeRng(&rng); if (ret < 0) { WOLFSSL_LEAVE("wolfSSL_X509_resign_cert", ret); @@ -10463,20 +10660,20 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( int len = 0; /* Read top level sequence */ - if (GetSequence(der, &idx, &len, derSz) < 0) { + if (GetSequence(der, &idx, &len, (word32)derSz) < 0) { WOLFSSL_MSG("GetSequence error"); return WOLFSSL_FATAL_ERROR; } /* Move idx to signature */ idx += certBodySz; /* Read signature algo sequence */ - if (GetSequence(der, &idx, &len, derSz) < 0) { + if (GetSequence(der, &idx, &len, (word32)derSz) < 0) { WOLFSSL_MSG("GetSequence error"); return WOLFSSL_FATAL_ERROR; } idx += len; /* Read signature bit string */ - if (CheckBitString(der, &idx, &len, derSz, 0, NULL) != 0) { + if (CheckBitString(der, &idx, &len, (word32)derSz, 0, NULL) != 0) { WOLFSSL_MSG("CheckBitString error"); return WOLFSSL_FATAL_ERROR; } @@ -10495,7 +10692,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( return WOLFSSL_FATAL_ERROR; } XMEMCPY(x509->sig.buffer, der + idx, len); - x509->sig.length = len; + x509->sig.length = (unsigned int)len; } /* Put in the new certificate encoding into the x509 object. */ @@ -10506,10 +10703,10 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( type = CERTREQ_TYPE; } #endif - if (AllocDer(&x509->derCert, derSz, type, NULL) != 0) + if (AllocDer(&x509->derCert, (word32)derSz, type, NULL) != 0) return WOLFSSL_FATAL_ERROR; XMEMCPY(x509->derCert->buffer, der, derSz); - x509->derCert->length = derSz; + x509->derCert->length = (word32)derSz; return ret; } @@ -10833,7 +11030,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } /* header */ - idx = SetSequence(totalBytes, temp); + idx = (int)SetSequence((word32)totalBytes, temp); if (totalBytes + idx > ASN_NAME_MAX) { #ifdef WOLFSSL_SMALL_STACK XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -10861,7 +11058,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } output = *out; - idx = SetSequence(totalBytes, output); + idx = (int)SetSequence((word32)totalBytes, output); totalBytes += idx; for (i = 0; i < MAX_NAME_ENTRIES; i++) { if (names[i].used) { @@ -10982,7 +11179,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) _x = (x->name && *x->name) ? x->name : x->staticName; _y = (y->name && *y->name) ? y->name : y->staticName; - return XSTRNCMP(_x, _y, x->sz); /* y sz is the same */ + return XSTRNCASECMP(_x, _y, x->sz); /* y sz is the same */ } #ifndef NO_BIO @@ -11085,6 +11282,27 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) return loadX509orX509REQFromPemBio(bp, x, cb, u, CERT_TYPE); } + /* + * bp : bio to read X509 from + * x : x509 to write to + * cb : password call back for reading PEM + * u : password + * _AUX is for working with a trusted X509 certificate + */ + WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_AUX(WOLFSSL_BIO *bp, + WOLFSSL_X509 **x, wc_pem_password_cb *cb, + void *u) + { + WOLFSSL_ENTER("wolfSSL_PEM_read_bio_X509"); + + /* AUX info is; trusted/rejected uses, friendly name, private key id, + * and potentially a stack of "other" info. wolfSSL does not store + * friendly name or private key id yet in WOLFSSL_X509 for human + * readability and does not support extra trusted/rejected uses for + * root CA. */ + return wolfSSL_PEM_read_bio_X509(bp, x, cb, u); + } + #ifdef WOLFSSL_CERT_REQ WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_REQ(WOLFSSL_BIO *bp, WOLFSSL_X509 **x, wc_pem_password_cb *cb, void *u) @@ -11158,7 +11376,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) if((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) { goto err; } - derSz = der->length; + derSz = (int)der->length; if((crl = wolfSSL_d2i_X509_CRL(x, der->buffer, derSz)) == NULL) { goto err; } @@ -11231,7 +11449,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) if (pem == NULL) return NULL; - if ((int)XFREAD((char *)pem, 1, pemSz, fp) != pemSz) + if ((int)XFREAD((char *)pem, 1, (size_t)pemSz, fp) != pemSz) goto err_exit; switch (type) { @@ -11244,7 +11462,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) case CRL_TYPE: if ((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) goto err_exit; - derSz = der->length; + derSz = (int)der->length; newx509 = (void*)wolfSSL_d2i_X509_CRL((WOLFSSL_X509_CRL **)x, (const unsigned char *)der->buffer, derSz); if (newx509 == NULL) @@ -11480,8 +11698,9 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) "-----BEGIN X509 CRL-----")) { /* We have a crl */ WOLFSSL_MSG("Parsing crl"); - if((PemToDer((const unsigned char*) header, footerEnd - header, - CRL_TYPE, &der, NULL, NULL, NULL)) < 0) { + if((PemToDer((const unsigned char*) header, + (long)(footerEnd - header), CRL_TYPE, &der, NULL, NULL, + NULL)) < 0) { WOLFSSL_MSG("PemToDer error"); goto err; } @@ -11895,7 +12114,6 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( static int RebuildFullName(WOLFSSL_X509_NAME* name) { int totalLen = 0, i, idx, entryCount = 0; - char* fullName; if (name == NULL) return BAD_FUNC_ARG; @@ -11915,23 +12133,26 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( } } - fullName = (char*)XMALLOC(totalLen + 1, name->heap, DYNAMIC_TYPE_X509); - if (fullName == NULL) - return MEMORY_E; + if (name->dynamicName) { + XFREE(name->name, name->heap, DYNAMIC_TYPE_X509); + name->name = name->staticName; + name->dynamicName = 0; + } + + if (totalLen >= ASN_NAME_MAX) { + name->name = (char*)XMALLOC(totalLen + 1, name->heap, + DYNAMIC_TYPE_X509); + if (name->name == NULL) + return MEMORY_E; + name->dynamicName = 1; + } idx = 0; - entryCount = AddAllEntry(name, fullName, totalLen, &idx); - if (entryCount < 0) { - XFREE(fullName, name->heap, DYNAMIC_TYPE_X509); + entryCount = AddAllEntry(name, name->name, totalLen, &idx); + if (entryCount < 0) return entryCount; - } - if (name->dynamicName) { - XFREE(name->name, name->heap, DYNAMIC_TYPE_X509); - } - fullName[idx] = '\0'; - name->name = fullName; - name->dynamicName = 1; + name->name[idx] = '\0'; name->sz = idx + 1; /* size includes null terminator */ name->entrySz = entryCount; @@ -12208,7 +12429,7 @@ int wolfSSL_PEM_write_bio_X509_REQ(WOLFSSL_BIO *bp, WOLFSSL_X509 *x) } /* get PEM size */ - pemSz = wc_DerToPemEx(der, derSz, NULL, 0, NULL, CERTREQ_TYPE); + pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, NULL, CERTREQ_TYPE); if (pemSz < 0) { return WOLFSSL_FAILURE; } @@ -12218,7 +12439,7 @@ int wolfSSL_PEM_write_bio_X509_REQ(WOLFSSL_BIO *bp, WOLFSSL_X509 *x) if (pem == NULL) { return WOLFSSL_FAILURE; } - if (wc_DerToPemEx(der, derSz, pem, pemSz, NULL, CERTREQ_TYPE) < 0) { + if (wc_DerToPemEx(der, (word32)derSz, pem, pemSz, NULL, CERTREQ_TYPE) < 0) { XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FAILURE; } @@ -12258,7 +12479,7 @@ int wolfSSL_PEM_write_bio_X509_AUX(WOLFSSL_BIO *bp, WOLFSSL_X509 *x) } /* get PEM size */ - pemSz = wc_DerToPemEx(der, derSz, NULL, 0, NULL, CERT_TYPE); + pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, NULL, CERT_TYPE); if (pemSz < 0) { return WOLFSSL_FAILURE; } @@ -12268,7 +12489,7 @@ int wolfSSL_PEM_write_bio_X509_AUX(WOLFSSL_BIO *bp, WOLFSSL_X509 *x) if (pem == NULL) { return WOLFSSL_FAILURE; } - if (wc_DerToPemEx(der, derSz, pem, pemSz, NULL, CERT_TYPE) < 0) { + if (wc_DerToPemEx(der, (word32)derSz, pem, pemSz, NULL, CERT_TYPE) < 0) { XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FAILURE; } @@ -12306,7 +12527,7 @@ int wolfSSL_PEM_write_bio_X509(WOLFSSL_BIO *bio, WOLFSSL_X509 *cert) } /* get PEM size */ - pemSz = wc_DerToPemEx(der, derSz, NULL, 0, NULL, CERT_TYPE); + pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, NULL, CERT_TYPE); if (pemSz < 0) { goto error; } @@ -12316,7 +12537,7 @@ int wolfSSL_PEM_write_bio_X509(WOLFSSL_BIO *bio, WOLFSSL_X509 *cert) if (pem == NULL) { goto error; } - if (wc_DerToPemEx(der, derSz, pem, pemSz, NULL, CERT_TYPE) < 0) { + if (wc_DerToPemEx(der, (word32)derSz, pem, pemSz, NULL, CERT_TYPE) < 0) { goto error; } @@ -12631,6 +12852,7 @@ WOLF_STACK_OF(WOLFSSL_X509_NAME) *wolfSSL_dup_CA_list( if (name == NULL || WOLFSSL_SUCCESS != wolfSSL_sk_X509_NAME_push(copy, name)) { WOLFSSL_MSG("Memory error"); wolfSSL_sk_X509_NAME_pop_free(copy, wolfSSL_X509_NAME_free); + wolfSSL_X509_NAME_free(name); return NULL; } } @@ -12752,6 +12974,14 @@ static int get_dn_attr_by_nid(int n, const char** buf) str = "UID"; len = 3; break; + case NID_serialNumber: + str = "serialNumber"; + len = 12; + break; + case NID_title: + str = "title"; + len = 5; + break; default: WOLFSSL_MSG("Attribute type not found"); str = NULL; @@ -12816,7 +13046,7 @@ static int wolfSSL_EscapeString_RFC2253(char* in, word32 inSz, } out[outIdx] = '\0'; - return outIdx; + return (int)outIdx; } /* @@ -12831,6 +13061,7 @@ static int wolfSSL_EscapeString_RFC2253(char* in, word32 inSz, * RFC22523 currently implemented. * XN_FLAG_DN_REV - print name reversed. Automatically done by * XN_FLAG_RFC2253. + * XN_FLAG_SPC_EQ - spaces before and after '=' character * * Returns WOLFSSL_SUCCESS (1) on success, WOLFSSL_FAILURE (0) on failure. */ @@ -12838,6 +13069,8 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, int indent, unsigned long flags) { int i, count = 0, nameStrSz = 0, escapeSz = 0; + int eqSpace = 0; + char eqStr[4]; char* tmp = NULL; char* nameStr = NULL; const char *buf = NULL; @@ -12850,6 +13083,15 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, if ((name == NULL) || (name->sz == 0) || (bio == NULL)) return WOLFSSL_FAILURE; + XMEMSET(eqStr, 0, sizeof(eqStr)); + if (flags & XN_FLAG_SPC_EQ) { + eqSpace = 2; + XSTRNCPY(eqStr, " = ", 4); + } + else { + XSTRNCPY(eqStr, "=", 4); + } + for (i = 0; i < indent; i++) { if (wolfSSL_BIO_write(bio, " ", 1) != 1) return WOLFSSL_FAILURE; @@ -12894,14 +13136,15 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, if (len == 0 || buf == NULL) return WOLFSSL_FAILURE; - tmpSz = nameStrSz + len + 4; /* + 4 for '=', comma space and '\0'*/ + /* + 4 for '=', comma space and '\0'*/ + tmpSz = nameStrSz + len + 4 + eqSpace; tmp = (char*)XMALLOC(tmpSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { return WOLFSSL_FAILURE; } if (i < count - 1) { - if (XSNPRINTF(tmp, tmpSz, "%s=%s, ", buf, nameStr) + if (XSNPRINTF(tmp, (size_t)tmpSz, "%s%s%s, ", buf, eqStr, nameStr) >= tmpSz) { WOLFSSL_MSG("buffer overrun"); @@ -12909,17 +13152,17 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, return WOLFSSL_FAILURE; } - tmpSz = len + nameStrSz + 3; /* 3 for '=', comma space */ + tmpSz = len + nameStrSz + 3 + eqSpace; /* 3 for '=', comma space */ } else { - if (XSNPRINTF(tmp, tmpSz, "%s=%s", buf, nameStr) + if (XSNPRINTF(tmp, (size_t)tmpSz, "%s%s%s", buf, eqStr, nameStr) >= tmpSz) { WOLFSSL_MSG("buffer overrun"); XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FAILURE; } - tmpSz = len + nameStrSz + 1; /* 1 for '=' */ + tmpSz = len + nameStrSz + 1 + eqSpace; /* 1 for '=' */ if (bio->type != WOLFSSL_BIO_FILE && bio->type != WOLFSSL_BIO_MEMORY) ++tmpSz; /* include the terminating null when not writing to a * file. @@ -13123,6 +13366,7 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, unsigned int flags, char **peername) { int ret; + size_t i; #ifdef WOLFSSL_SMALL_STACK DecodedCert *dCert; #else @@ -13159,11 +13403,27 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, #endif InitDecodedCert(dCert, x->derCert->buffer, x->derCert->length, NULL); - ret = ParseCertRelative(dCert, CERT_TYPE, 0, NULL); + ret = ParseCertRelative(dCert, CERT_TYPE, 0, NULL, NULL); if (ret != 0) { goto out; } + /* Replicate openssl behavior for checklen */ + if (chklen == 0) { + chklen = (size_t)(XSTRLEN(chk)); + } + else { + for (i = 0; i < (chklen > 1 ? chklen - 1 : chklen); i++) { + if (chk[i] == '\0') { + ret = -1; + goto out; + } + } + } + if (chklen > 1 && (chk[chklen - 1] == '\0')) { + chklen--; + } + ret = CheckHostName(dCert, (char *)chk, chklen); out: @@ -13214,7 +13474,7 @@ int wolfSSL_X509_check_ip_asc(WOLFSSL_X509 *x, const char *ipasc, if (ret == WOLFSSL_SUCCESS) { InitDecodedCert(dCert, x->derCert->buffer, x->derCert->length, NULL); - ret = ParseCertRelative(dCert, CERT_TYPE, 0, NULL); + ret = ParseCertRelative(dCert, CERT_TYPE, 0, NULL, NULL); if (ret != 0) { ret = WOLFSSL_FAILURE; } @@ -13353,7 +13613,7 @@ static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, /* Use existing CA retrieval APIs that use DecodedCert. */ InitDecodedCert(cert, x->derCert->buffer, x->derCert->length, cm->heap); - if (ParseCertRelative(cert, CERT_TYPE, 0, NULL) == 0 + if (ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL) == 0 && !cert->selfSigned) { #ifndef NO_SKID if (cert->extAuthKeyIdSet) @@ -13516,7 +13776,7 @@ int wolfSSL_X509_get_signature_nid(const WOLFSSL_X509 *x) if (x == NULL) return 0; - return oid2nid(x->sigOID, oidSigType); + return oid2nid((word32)x->sigOID, oidSigType); } #endif /* OPENSSL_EXTRA */ @@ -13700,6 +13960,16 @@ int wolfSSL_X509_set_notBefore(WOLFSSL_X509* x509, const WOLFSSL_ASN1_TIME* t) return WOLFSSL_SUCCESS; } +int wolfSSL_X509_set1_notAfter(WOLFSSL_X509* x509, const WOLFSSL_ASN1_TIME *t) +{ + return wolfSSL_X509_set_notAfter(x509, t); +} + +int wolfSSL_X509_set1_notBefore(WOLFSSL_X509* x509, const WOLFSSL_ASN1_TIME *t) +{ + return wolfSSL_X509_set_notBefore(x509, t); +} + int wolfSSL_X509_set_serialNumber(WOLFSSL_X509* x509, WOLFSSL_ASN1_INTEGER* s) { WOLFSSL_ENTER("wolfSSL_X509_set_serialNumber"); @@ -13748,7 +14018,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) if (p == NULL) return WOLFSSL_FAILURE; - if ((derSz = wc_RsaKeyToPublicDer(rsa, p, derSz)) <= 0) { + if ((derSz = wc_RsaKeyToPublicDer(rsa, p, (word32)derSz)) <= 0) { XFREE(p, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); return WOLFSSL_FAILURE; } @@ -13772,7 +14042,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) if (p == NULL) return WOLFSSL_FAILURE; - if ((derSz = wc_DsaKeyToPublicDer(dsa, p, derSz)) <= 0) { + if ((derSz = wc_DsaKeyToPublicDer(dsa, p, (word32)derSz)) <= 0) { XFREE(p, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); return WOLFSSL_FAILURE; } @@ -13797,7 +14067,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) if (p == NULL) return WOLFSSL_FAILURE; - if ((derSz = wc_EccPublicKeyToDer(ecc, p, derSz, 1)) <= 0) { + if ((derSz = wc_EccPublicKeyToDer(ecc, p, (word32)derSz, 1)) <= 0) { XFREE(p, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); return WOLFSSL_FAILURE; } @@ -13809,7 +14079,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) return WOLFSSL_FAILURE; } cert->pubKey.buffer = p; - cert->pubKey.length = derSz; + cert->pubKey.length = (unsigned int)derSz; return WOLFSSL_SUCCESS; } @@ -14014,7 +14284,7 @@ static int regenX509REQDerBuffer(WOLFSSL_X509* x509) if (wolfssl_x509_make_der(x509, 1, der, &derSz, 0) == WOLFSSL_SUCCESS) { FreeDer(&x509->derCert); - if (AllocDer(&x509->derCert, derSz, CERT_TYPE, x509->heap) == 0) { + if (AllocDer(&x509->derCert, (word32)derSz, CERT_TYPE, x509->heap) == 0) { XMEMCPY(x509->derCert->buffer, der, derSz); ret = WOLFSSL_SUCCESS; } @@ -14353,7 +14623,7 @@ void wolfSSL_X509_ATTRIBUTE_free(WOLFSSL_X509_ATTRIBUTE* attr) } #endif -#endif /* !NO_CERT */ +#endif /* !NO_CERTS */ #endif /* !WOLFCRYPT_ONLY */ diff --git a/src/src/x509_str.c b/src/src/x509_str.c index a38f93b..f5c5c2a 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -40,27 +40,59 @@ * START OF X509_STORE_CTX APIs ******************************************************************************/ -#ifdef OPENSSL_EXTRA - -WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void) +/* This API is necessary outside of OPENSSL_EXTRA because it is used in + * SetupStoreCtxCallback */ +WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new_ex(void* heap) { WOLFSSL_X509_STORE_CTX* ctx; - WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_new"); + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_new_ex"); - ctx = (WOLFSSL_X509_STORE_CTX*)XMALLOC(sizeof(WOLFSSL_X509_STORE_CTX), NULL, + ctx = (WOLFSSL_X509_STORE_CTX*)XMALLOC(sizeof(WOLFSSL_X509_STORE_CTX), heap, DYNAMIC_TYPE_X509_CTX); if (ctx != NULL) { - ctx->param = NULL; + XMEMSET(ctx, 0, sizeof(WOLFSSL_X509_STORE_CTX)); + ctx->heap = heap; +#ifdef OPENSSL_EXTRA if (wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL) != WOLFSSL_SUCCESS) { - XFREE(ctx, NULL, DYNAMIC_TYPE_X509_CTX); + XFREE(ctx, heap, DYNAMIC_TYPE_X509_CTX); ctx = NULL; } +#endif } return ctx; } +/* This API is necessary outside of OPENSSL_EXTRA because it is used in + * SetupStoreCtxCallback */ +/* free's extra data */ +void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_free"); + if (ctx != NULL) { +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS + wolfSSL_CRYPTO_cleanup_ex_data(&ctx->ex_data); +#endif + +#ifdef OPENSSL_EXTRA + if (ctx->param != NULL) { + XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); + ctx->param = NULL; + } +#endif + + XFREE(ctx, ctx->heap, DYNAMIC_TYPE_X509_CTX); + } +} + +#ifdef OPENSSL_EXTRA + +WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_new"); + return wolfSSL_X509_STORE_CTX_new_ex(NULL); +} int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509, @@ -134,11 +166,12 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, if (ctx->param == NULL) { ctx->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC( sizeof(WOLFSSL_X509_VERIFY_PARAM), - NULL, DYNAMIC_TYPE_OPENSSL); + ctx->heap, DYNAMIC_TYPE_OPENSSL); if (ctx->param == NULL){ WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init failed"); return WOLFSSL_FAILURE; } + XMEMSET(ctx->param, 0, sizeof(*ctx->param)); } return WOLFSSL_SUCCESS; @@ -146,25 +179,6 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, return WOLFSSL_FAILURE; } - -/* free's extra data */ -void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) -{ - WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_free"); - if (ctx != NULL) { -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS - wolfSSL_CRYPTO_cleanup_ex_data(&ctx->ex_data); -#endif - - if (ctx->param != NULL) { - XFREE(ctx->param, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; - } - - XFREE(ctx, NULL, DYNAMIC_TYPE_X509_CTX); - } -} - /* Its recommended to use a full free -> init cycle of all the objects * because wolfSSL_X509_STORE_CTX_init may modify the store too which doesn't * get reset here. */ @@ -173,7 +187,7 @@ void wolfSSL_X509_STORE_CTX_cleanup(WOLFSSL_X509_STORE_CTX* ctx) if (ctx != NULL) { if (ctx->param != NULL) { - XFREE(ctx->param, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); ctx->param = NULL; } @@ -194,24 +208,27 @@ void wolfSSL_X509_STORE_CTX_trusted_stack(WOLFSSL_X509_STORE_CTX *ctx, WOLF_STAC int GetX509Error(int e) { switch (e) { - case ASN_BEFORE_DATE_E: + case WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E): return WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID; - case ASN_AFTER_DATE_E: + case WC_NO_ERR_TRACE(ASN_AFTER_DATE_E): return WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED; - case ASN_NO_SIGNER_E: /* get issuer error if no CA found locally */ + case WC_NO_ERR_TRACE(ASN_NO_SIGNER_E): + /* get issuer error if no CA found locally */ return WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; - case ASN_SELF_SIGNED_E: + case WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E): return WOLFSSL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; - case ASN_PATHLEN_INV_E: - case ASN_PATHLEN_SIZE_E: + case WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E): + case WC_NO_ERR_TRACE(ASN_PATHLEN_SIZE_E): return WOLFSSL_X509_V_ERR_PATH_LENGTH_EXCEEDED; - case ASN_SIG_OID_E: - case ASN_SIG_CONFIRM_E: - case ASN_SIG_HASH_E: - case ASN_SIG_KEY_E: + case WC_NO_ERR_TRACE(ASN_SIG_OID_E): + case WC_NO_ERR_TRACE(ASN_SIG_CONFIRM_E): + case WC_NO_ERR_TRACE(ASN_SIG_HASH_E): + case WC_NO_ERR_TRACE(ASN_SIG_KEY_E): return WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE; - case CRL_CERT_REVOKED: + case WC_NO_ERR_TRACE(CRL_CERT_REVOKED): return WOLFSSL_X509_V_ERR_CERT_REVOKED; + case WC_NO_ERR_TRACE(CRL_MISSING): + return X509_V_ERR_UNABLE_TO_GET_CRL; case 0: case 1: return 0; @@ -254,7 +271,8 @@ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) SetupStoreCtxError(ctx, ret); #ifndef NO_ASN_TIME - if (ret != ASN_BEFORE_DATE_E && ret != ASN_AFTER_DATE_E) { + if (ret != WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) && + ret != WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { /* wolfSSL_CertManagerVerifyBuffer only returns ASN_AFTER_DATE_E or ASN_BEFORE_DATE_E if there are no additional errors found in the cert. Therefore, check if the cert is expired or not yet valid @@ -504,39 +522,19 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) /* if chain is null but sesChain is available then populate stack */ if (ctx->chain == NULL && ctx->sesChain != NULL) { int i; + int error = 0; WOLFSSL_X509_CHAIN* c = ctx->sesChain; - WOLFSSL_STACK* sk = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), - NULL, DYNAMIC_TYPE_X509); + WOLFSSL_STACK* sk = wolfSSL_sk_new_node(ctx->heap); - if (sk == NULL) { + if (sk == NULL) return NULL; - } - - XMEMSET(sk, 0, sizeof(WOLFSSL_STACK)); - - for (i = 0; i < c->count && i < MAX_CHAIN_DEPTH; i++) { - WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, i); - - if (x509 == NULL) { - WOLFSSL_MSG("Unable to get x509 from chain"); - wolfSSL_sk_X509_pop_free(sk, NULL); - return NULL; - } - - if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Unable to load x509 into stack"); - wolfSSL_sk_X509_pop_free(sk, NULL); - wolfSSL_X509_free(x509); - return NULL; - } - } #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) /* add CA used to verify top of chain to the list */ if (c->count > 0) { WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, c->count - 1); + WOLFSSL_X509* issuer = NULL; if (x509 != NULL) { - WOLFSSL_X509* issuer = NULL; if (wolfSSL_X509_STORE_CTX_get1_issuer(&issuer, ctx, x509) == WOLFSSL_SUCCESS) { /* check that the certificate being looked up is not self @@ -545,24 +543,47 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) &x509->subject) != 0) { if (wolfSSL_sk_X509_push(sk, issuer) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Unable to load CA x509 into stack"); - wolfSSL_sk_X509_pop_free(sk, NULL); - wolfSSL_X509_free(issuer); - return NULL; + error = 1; } } else { WOLFSSL_MSG("Certificate is self signed"); - if (issuer != NULL) - wolfSSL_X509_free(issuer); + wolfSSL_X509_free(issuer); } } else { - wolfSSL_X509_free(x509); WOLFSSL_MSG("Could not find CA for certificate"); } } + wolfSSL_X509_free(x509); + if (error) { + wolfSSL_sk_X509_pop_free(sk, NULL); + wolfSSL_X509_free(issuer); + return NULL; + } } #endif + + for (i = c->count - 1; i >= 0; i--) { + WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, i); + + if (x509 == NULL) { + WOLFSSL_MSG("Unable to get x509 from chain"); + error = 1; + break; + } + + if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Unable to load x509 into stack"); + wolfSSL_X509_free(x509); + error = 1; + break; + } + } + if (error) { + wolfSSL_sk_X509_pop_free(sk, NULL); + return NULL; + } ctx->chain = sk; } #endif /* SESSION_CERTS */ @@ -611,6 +632,14 @@ int wolfSSL_X509_STORE_get_by_subject(WOLFSSL_X509_STORE_CTX* ctx, int idx, } #endif +WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_CTX_get0_param( + WOLFSSL_X509_STORE_CTX *ctx) +{ + if (ctx == NULL) + return NULL; + + return ctx->param; +} #endif /* OPENSSL_EXTRA */ @@ -935,14 +964,33 @@ int wolfSSL_X509_STORE_set_ex_data_with_cleanup( #ifdef OPENSSL_EXTRA #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) - void wolfSSL_X509_STORE_set_verify_cb(WOLFSSL_X509_STORE *st, - WOLFSSL_X509_STORE_CTX_verify_cb verify_cb) - { - WOLFSSL_ENTER("wolfSSL_X509_STORE_set_verify_cb"); - if (st != NULL) { - st->verify_cb = verify_cb; - } +void wolfSSL_X509_STORE_set_verify_cb(WOLFSSL_X509_STORE *st, + WOLFSSL_X509_STORE_CTX_verify_cb verify_cb) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_set_verify_cb"); + if (st != NULL) { + st->verify_cb = verify_cb; } +} + +void wolfSSL_X509_STORE_set_get_crl(WOLFSSL_X509_STORE *st, + WOLFSSL_X509_STORE_CTX_get_crl_cb get_cb) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_set_get_crl"); + if (st != NULL) { + st->get_crl_cb = get_cb; + } +} + +#ifndef NO_WOLFSSL_STUB +void wolfSSL_X509_STORE_set_check_crl(WOLFSSL_X509_STORE *st, + WOLFSSL_X509_STORE_CTX_check_crl_cb check_crl) +{ + (void)st; + (void)check_crl; + WOLFSSL_STUB("wolfSSL_X509_STORE_set_check_crl (not implemented)"); +} +#endif #endif /* WOLFSSL_QT || OPENSSL_ALL */ WOLFSSL_X509_LOOKUP* wolfSSL_X509_STORE_add_lookup(WOLFSSL_X509_STORE* store, @@ -1328,6 +1376,17 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( } #endif /* OPENSSL_ALL */ +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ + defined(WOLFSSL_WPAS_SMALL) +WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_get0_param( + const WOLFSSL_X509_STORE *ctx) +{ + if (ctx == NULL) + return NULL; + return ctx->param; +} +#endif + /******************************************************************************* * END OF X509_STORE APIs ******************************************************************************/ diff --git a/src/user_settings.h b/src/user_settings.h index d102ea8..52c4e7d 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -23,7 +23,7 @@ */ /* Define a macro to display user settings version in example code: */ -#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.0" +#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.2" /* Due to limited build control, we'll ignore file warnings. */ /* See https://github.com/arduino/arduino-cli/issues/631 */ diff --git a/src/wolfcrypt/src/aes.c b/src/wolfcrypt/src/aes.c index e9716bc..8418fb0 100644 --- a/src/wolfcrypt/src/aes.c +++ b/src/wolfcrypt/src/aes.c @@ -39,15 +39,13 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits /* Tip: Locate the software cipher modes by searching for "Software AES" */ -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) - +#if FIPS_VERSION3_GE(2,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$g") - #pragma const_seg(".fipsB$g") + #pragma code_seg(".fipsA$b") + #pragma const_seg(".fipsB$b") #endif #endif @@ -97,7 +95,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #include #endif -#ifndef WOLFSSL_ARMASM +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) #ifdef WOLFSSL_IMX6_CAAM_BLOB /* case of possibly not using hardware acceleration for AES but using key @@ -114,6 +112,15 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #pragma warning(disable: 4127) #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_aes_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000002 }; + int wolfCrypt_FIPS_AES_sanity(void) + { + return 0; + } +#endif + /* Define AES implementation includes and functions */ #if defined(STM32_CRYPTO) /* STM32F2/F4/F7/L4/L5/H7/WB55 hardware AES support for ECB, CBC, CTR and GCM modes */ @@ -720,7 +727,8 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits return MEMORY_E; #endif - if (AES_set_encrypt_key_AESNI(userKey,bits,temp_key) == BAD_FUNC_ARG) { + if (AES_set_encrypt_key_AESNI(userKey,bits,temp_key) + == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { #ifdef WOLFSSL_SMALL_STACK XFREE(temp_key, aes->heap, DYNAMIC_TYPE_AES); #endif @@ -960,6 +968,9 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_AES) /* implemented in wolfcrypt/src/port/psa/psa_aes.c */ +#elif defined(WOLFSSL_RISCV_ASM) +/* implemented in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ + #else /* using wolfCrypt software implementation */ @@ -1908,6 +1919,7 @@ static word32 GetTable8_4(const byte* t, byte o0, byte o1, byte o2, byte o3) ((word32)(t)[o2] << 8) | ((word32)(t)[o3] << 0)) #endif +#ifndef HAVE_CUDA /* Encrypt a block using AES. * * @param [in] aes AES object. @@ -1922,7 +1934,7 @@ static void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, word32 t0, t1, t2, t3; const word32* rk; -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK rk = aes->key_C_fallback; #else rk = aes->key; @@ -2208,6 +2220,11 @@ static void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz) } } #endif +#else +extern void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, + word32 r); +extern void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz); +#endif /* HAVE_CUDA */ #else @@ -2703,6 +2720,7 @@ static void bs_encrypt(bs_word* state, bs_word* rk, word32 r) bs_inv_transpose(state, trans); } +#ifndef HAVE_CUDA /* Encrypt a block using AES. * * @param [in] aes AES object. @@ -2754,6 +2772,11 @@ static void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz) } } #endif +#else +extern void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, + word32 r); +extern void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz); +#endif /* HAVE_CUDA */ #endif /* !WC_AES_BITSLICED */ @@ -2926,7 +2949,7 @@ static void AesDecrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, word32 t0, t1, t2, t3; const word32* rk; -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK rk = aes->key_C_fallback; #else rk = aes->key; @@ -4066,7 +4089,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( */ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) { -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK word32* rk = aes->key_C_fallback; #else word32* rk = aes->key; @@ -4227,7 +4250,7 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) if (dir == AES_DECRYPTION) { unsigned int j; -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK rk = aes->key_C_fallback; #else rk = aes->key; @@ -4298,6 +4321,7 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) #endif /* NEED_AES_TABLES */ +#ifndef WOLFSSL_RISCV_ASM /* Software AES - SetKey */ static WARN_UNUSED_RESULT int wc_AesSetKeyLocal( Aes* aes, const byte* userKey, word32 keylen, const byte* iv, int dir, @@ -4436,11 +4460,11 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) if (ret != 0) return ret; -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK #ifdef NEED_AES_TABLES AesSetKey_C(aes, userKey, keylen, dir); #endif /* NEED_AES_TABLES */ -#endif /* WC_AES_C_DYNAMIC_FALLBACK */ +#endif /* WC_C_DYNAMIC_FALLBACK */ #ifdef WOLFSSL_AESNI aes->use_aesni = 0; @@ -4469,13 +4493,13 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) if (ret == 0) aes->use_aesni = 1; else { -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK ret = 0; #endif } return ret; } else { -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK return 0; #else return ret; @@ -4611,6 +4635,7 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) return wc_AesSetKeyLocal(aes, userKey, keylen, iv, dir, 1); } /* wc_AesSetKey() */ +#endif #if defined(WOLFSSL_AES_DIRECT) || defined(WOLFSSL_AES_COUNTER) /* AES-CTR and AES-DIRECT need to use this for key setup */ @@ -4661,7 +4686,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #ifdef WOLFSSL_AESNI -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK #define VECTOR_REGISTERS_PUSH { \ int orig_use_aesni = aes->use_aesni; \ @@ -5490,7 +5515,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #endif { int crypto_cb_ret = wc_CryptoCb_AesCbcEncrypt(aes, out, in, sz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -5659,7 +5684,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #endif { int crypto_cb_ret = wc_CryptoCb_AesCbcDecrypt(aes, out, in, sz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -6037,6 +6062,8 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) int ret = 0; word32 processed; + XMEMSET(scratch, 0, sizeof(scratch)); + if (aes == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; } @@ -6047,7 +6074,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #endif { int crypto_cb_ret = wc_CryptoCb_AesCtrEncrypt(aes, out, in, sz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -6144,13 +6171,13 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) return BAD_FUNC_ARG; } - return wc_AesSetKeyLocal(aes, key, len, iv, dir, 0); + return wc_AesSetKey(aes, key, len, iv, dir); } #endif /* NEED_AES_CTR_SOFT */ #endif /* WOLFSSL_AES_COUNTER */ -#endif /* !WOLFSSL_ARMASM */ +#endif /* !WOLFSSL_ARMASM && ! WOLFSSL_RISCV_ASM */ /* @@ -6200,6 +6227,9 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) #ifdef WOLFSSL_ARMASM /* implementation is located in wolfcrypt/src/port/arm/armv8-aes.c */ +#elif defined(WOLFSSL_RISCV_ASM) + /* implemented in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ + #elif defined(WOLFSSL_AFALG) /* implemented in wolfcrypt/src/port/afalg/afalg_aes.c */ @@ -6381,7 +6411,7 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) if (!((len == 16) || (len == 24) || (len == 32))) return BAD_FUNC_ARG; - if (aes == NULL) { + if (aes == NULL || key == NULL) { #ifdef WOLFSSL_IMX6_CAAM_BLOB ForceZero(local, sizeof(local)); #endif @@ -8295,7 +8325,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, int crypto_cb_ret = wc_CryptoCb_AesGcmEncrypt(aes, out, in, sz, iv, ivSz, authTag, authTagSz, authIn, authInSz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -8838,7 +8868,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, { int ret; #ifdef WOLFSSL_AESNI - int res = AES_GCM_AUTH_E; + int res = WC_NO_ERR_TRACE(AES_GCM_AUTH_E); #endif /* argument checks */ @@ -8859,7 +8889,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, int crypto_cb_ret = wc_CryptoCb_AesGcmDecrypt(aes, out, in, sz, iv, ivSz, authTag, authTagSz, authIn, authInSz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -10457,6 +10487,9 @@ int wc_AesCcmCheckTagSize(int sz) #ifdef WOLFSSL_ARMASM /* implementation located in wolfcrypt/src/port/arm/armv8-aes.c */ +#elif defined(WOLFSSL_RISCV_ASM) + /* implementation located in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ + #elif defined(HAVE_COLDFIRE_SEC) #error "Coldfire SEC doesn't currently support AES-CCM mode" @@ -10728,6 +10761,11 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, authTagSz > AES_BLOCK_SIZE) return BAD_FUNC_ARG; + /* Sanity check on authIn to prevent segfault in xorbuf() where + * variable 'in' is dereferenced as the mask 'm' in misc.c */ + if (authIn == NULL && authInSz > 0) + return BAD_FUNC_ARG; + /* sanity check on tag size */ if (wc_AesCcmCheckTagSize((int)authTagSz) != 0) { return BAD_FUNC_ARG; @@ -10741,7 +10779,7 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, int crypto_cb_ret = wc_CryptoCb_AesCcmEncrypt(aes, out, in, inSz, nonce, nonceSz, authTag, authTagSz, authIn, authInSz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -10870,6 +10908,11 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, authTagSz > AES_BLOCK_SIZE) return BAD_FUNC_ARG; + /* Sanity check on authIn to prevent segfault in xorbuf() where + * variable 'in' is dereferenced as the mask 'm' in misc.c */ + if (authIn == NULL && authInSz > 0) + return BAD_FUNC_ARG; + /* sanity check on tag size */ if (wc_AesCcmCheckTagSize((int)authTagSz) != 0) { return BAD_FUNC_ARG; @@ -10883,7 +10926,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, int crypto_cb_ret = wc_CryptoCb_AesCcmDecrypt(aes, out, in, inSz, nonce, nonceSz, authTag, authTagSz, authIn, authInSz); - if (crypto_cb_ret != CRYPTOCB_UNAVAILABLE) + if (crypto_cb_ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return crypto_cb_ret; /* fall-through when unavailable */ } @@ -11354,6 +11397,9 @@ int wc_AesGetKeySize(Aes* aes, word32* keySize) #elif defined(WOLFSSL_DEVCRYPTO_AES) /* implemented in wolfcrypt/src/port/devcrypt/devcrypto_aes.c */ +#elif defined(WOLFSSL_RISCV_ASM) + /* implemented in wolfcrypt/src/port/riscv/riscv-64-aes.c */ + #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES) /* Software AES - ECB */ @@ -11388,7 +11434,7 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( #endif { ret = wc_CryptoCb_AesEcbEncrypt(aes, out, in, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; ret = 0; /* fall-through when unavailable */ @@ -11428,6 +11474,7 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( return ret; } +#ifdef HAVE_AES_DECRYPT static WARN_UNUSED_RESULT int _AesEcbDecrypt( Aes* aes, byte* out, const byte* in, word32 sz) { @@ -11439,7 +11486,7 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( #endif { ret = wc_CryptoCb_AesEcbDecrypt(aes, out, in, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; ret = 0; /* fall-through when unavailable */ @@ -11478,6 +11525,7 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( return ret; } +#endif int wc_AesEcbEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { @@ -11490,6 +11538,7 @@ int wc_AesEcbEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) return _AesEcbEncrypt(aes, out, in, sz); } +#ifdef HAVE_AES_DECRYPT int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { if ((in == NULL) || (out == NULL) || (aes == NULL)) @@ -11500,6 +11549,7 @@ int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) return _AesEcbDecrypt(aes, out, in, sz); } +#endif /* HAVE_AES_DECRYPT */ #endif #endif /* HAVE_AES_ECB */ @@ -11863,7 +11913,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB1( } if (ret == 0) { - if (bit > 0 && bit < 7) { + if (bit >= 0 && bit < 7) { out[0] = cur; } } @@ -12313,12 +12363,16 @@ int wc_AesXtsSetKeyNoInit(XtsAes* aes, const byte* key, word32 len, int dir) return BAD_FUNC_ARG; } - keySz = len/2; - if (keySz != AES_128_KEY_SIZE && keySz != AES_256_KEY_SIZE) { + if ((len != (AES_128_KEY_SIZE*2)) && + (len != (AES_192_KEY_SIZE*2)) && + (len != (AES_256_KEY_SIZE*2))) + { WOLFSSL_MSG("Unsupported key size"); return WC_KEY_SIZE_E; } + keySz = len/2; + #ifdef HAVE_FIPS if (XMEMCMP(key, key + keySz, keySz) == 0) { WOLFSSL_MSG("FIPS AES-XTS main and tweak keys must differ"); @@ -12350,7 +12404,7 @@ int wc_AesXtsSetKeyNoInit(XtsAes* aes, const byte* key, word32 len, int dir) #ifdef WOLFSSL_AESNI if (ret == 0) { - /* With WC_AES_C_DYNAMIC_FALLBACK, the main and tweak keys could have + /* With WC_C_DYNAMIC_FALLBACK, the main and tweak keys could have * conflicting _aesni status, but the AES-XTS asm implementations need * them to all be AESNI. If any aren't, disable AESNI on all. */ @@ -12363,7 +12417,7 @@ int wc_AesXtsSetKeyNoInit(XtsAes* aes, const byte* key, word32 len, int dir) (dir == AES_ENCRYPTION_AND_DECRYPTION)) && (aes->aes_decrypt.use_aesni != aes->tweak.use_aesni))) { - #ifdef WC_AES_C_DYNAMIC_FALLBACK + #ifdef WC_C_DYNAMIC_FALLBACK aes->aes.use_aesni = 0; aes->aes_decrypt.use_aesni = 0; aes->tweak.use_aesni = 0; @@ -12373,7 +12427,7 @@ int wc_AesXtsSetKeyNoInit(XtsAes* aes, const byte* key, word32 len, int dir) } #else /* !WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS */ if (aes->aes.use_aesni != aes->tweak.use_aesni) { - #ifdef WC_AES_C_DYNAMIC_FALLBACK + #ifdef WC_C_DYNAMIC_FALLBACK aes->aes.use_aesni = 0; aes->tweak.use_aesni = 0; #else @@ -12502,12 +12556,28 @@ void AES_XTS_encrypt_aesni(const unsigned char *in, unsigned char *out, word32 s const unsigned char* i, const unsigned char* key, const unsigned char* key2, int nr) XASM_LINK("AES_XTS_encrypt_aesni"); +#ifdef WOLFSSL_AESXTS_STREAM +void AES_XTS_init_aesni(unsigned char* i, const unsigned char* tweak_key, + int tweak_nr) + XASM_LINK("AES_XTS_init_aesni"); +void AES_XTS_encrypt_update_aesni(const unsigned char *in, unsigned char *out, word32 sz, + const unsigned char* key, unsigned char *i, int nr) + XASM_LINK("AES_XTS_encrypt_update_aesni"); +#endif #ifdef HAVE_INTEL_AVX1 void AES_XTS_encrypt_avx1(const unsigned char *in, unsigned char *out, - word32 sz, const unsigned char* i, - const unsigned char* key, const unsigned char* key2, - int nr) - XASM_LINK("AES_XTS_encrypt_avx1"); + word32 sz, const unsigned char* i, + const unsigned char* key, const unsigned char* key2, + int nr) + XASM_LINK("AES_XTS_encrypt_avx1"); +#ifdef WOLFSSL_AESXTS_STREAM +void AES_XTS_init_avx1(unsigned char* i, const unsigned char* tweak_key, + int tweak_nr) + XASM_LINK("AES_XTS_init_avx1"); +void AES_XTS_encrypt_update_avx1(const unsigned char *in, unsigned char *out, word32 sz, + const unsigned char* key, unsigned char *i, int nr) + XASM_LINK("AES_XTS_encrypt_update_avx1"); +#endif #endif /* HAVE_INTEL_AVX1 */ #ifdef HAVE_AES_DECRYPT @@ -12515,12 +12585,22 @@ void AES_XTS_decrypt_aesni(const unsigned char *in, unsigned char *out, word32 s const unsigned char* i, const unsigned char* key, const unsigned char* key2, int nr) XASM_LINK("AES_XTS_decrypt_aesni"); +#ifdef WOLFSSL_AESXTS_STREAM +void AES_XTS_decrypt_update_aesni(const unsigned char *in, unsigned char *out, word32 sz, + const unsigned char* key, unsigned char *i, int nr) + XASM_LINK("AES_XTS_decrypt_update_aesni"); +#endif #ifdef HAVE_INTEL_AVX1 void AES_XTS_decrypt_avx1(const unsigned char *in, unsigned char *out, - word32 sz, const unsigned char* i, - const unsigned char* key, const unsigned char* key2, - int nr) - XASM_LINK("AES_XTS_decrypt_avx1"); + word32 sz, const unsigned char* i, + const unsigned char* key, const unsigned char* key2, + int nr) + XASM_LINK("AES_XTS_decrypt_avx1"); +#ifdef WOLFSSL_AESXTS_STREAM +void AES_XTS_decrypt_update_avx1(const unsigned char *in, unsigned char *out, word32 sz, + const unsigned char* key, unsigned char *i, int nr) + XASM_LINK("AES_XTS_decrypt_update_avx1"); +#endif #endif /* HAVE_INTEL_AVX1 */ #endif /* HAVE_AES_DECRYPT */ @@ -12558,16 +12638,24 @@ static WARN_UNUSED_RESULT int _AesXtsHelper( } xorbuf(out, in, totalSz); +#ifndef WOLFSSL_RISCV_ASM if (dir == AES_ENCRYPTION) { return _AesEcbEncrypt(aes, out, out, totalSz); } else { return _AesEcbDecrypt(aes, out, out, totalSz); } +#else + if (dir == AES_ENCRYPTION) { + return wc_AesEcbEncrypt(aes, out, out, totalSz); + } + else { + return wc_AesEcbDecrypt(aes, out, out, totalSz); + } +#endif } #endif /* HAVE_AES_ECB */ - /* AES with XTS mode. (XTS) XEX encryption with Tweak and cipher text Stealing. * * xaes AES keys to use for block encrypt/decrypt @@ -12579,27 +12667,63 @@ static WARN_UNUSED_RESULT int _AesXtsHelper( * returns 0 on success */ /* Software AES - XTS Encrypt */ + +static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, + word32 sz, + byte *i); static int AesXtsEncrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, const byte* i) { - int ret = 0; - word32 blocks = (sz / AES_BLOCK_SIZE); - Aes *aes = &xaes->aes; - Aes *tweak = &xaes->tweak; - byte tmp[AES_BLOCK_SIZE]; - - XMEMSET(tmp, 0, AES_BLOCK_SIZE); /* set to 0's in case of improper AES - * key setup passed to encrypt direct*/ - - ret = wc_AesEncryptDirect(tweak, tmp, i); + int ret; + byte tweak_block[AES_BLOCK_SIZE]; + ret = wc_AesEncryptDirect(&xaes->tweak, tweak_block, i); if (ret != 0) return ret; + return AesXtsEncryptUpdate_sw(xaes, out, in, sz, tweak_block); +} + +#ifdef WOLFSSL_AESXTS_STREAM + +/* Block-streaming AES-XTS tweak setup. + * + * xaes AES keys to use for block encrypt/decrypt + * i readwrite value to use for tweak + * + * returns 0 on success + */ +static int AesXtsInitTweak_sw(XtsAes* xaes, byte* i) { + return wc_AesEncryptDirect(&xaes->tweak, i, i); +} + +#endif /* WOLFSSL_AESXTS_STREAM */ + +/* Block-streaming AES-XTS. + * + * Supply block-aligned input data with successive calls. Final call need not + * be block aligned. + * + * xaes AES keys to use for block encrypt/decrypt + * out output buffer to hold cipher text + * in input plain text buffer to encrypt + * sz size of both out and in buffers + * + * returns 0 on success + */ +/* Software AES - XTS Encrypt */ +static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, + word32 sz, + byte *i) +{ + int ret = 0; + word32 blocks = (sz / AES_BLOCK_SIZE); + Aes *aes = &xaes->aes; + #ifdef HAVE_AES_ECB /* encrypt all of buffer at once when possible */ if (in != out) { /* can not handle inline */ - XMEMCPY(out, tmp, AES_BLOCK_SIZE); + XMEMCPY(out, i, AES_BLOCK_SIZE); if ((ret = _AesXtsHelper(aes, out, in, sz, AES_ENCRYPTION)) != 0) return ret; } @@ -12616,23 +12740,23 @@ static int AesXtsEncrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte buf[AES_BLOCK_SIZE]; XMEMCPY(buf, in, AES_BLOCK_SIZE); - xorbuf(buf, tmp, AES_BLOCK_SIZE); + xorbuf(buf, i, AES_BLOCK_SIZE); ret = wc_AesEncryptDirect(aes, out, buf); if (ret != 0) return ret; } - xorbuf(out, tmp, AES_BLOCK_SIZE); + xorbuf(out, i, AES_BLOCK_SIZE); /* multiply by shift left and propagate carry */ for (j = 0; j < AES_BLOCK_SIZE; j++) { byte tmpC; - tmpC = (tmp[j] >> 7) & 0x01; - tmp[j] = (byte)((tmp[j] << 1) + carry); + tmpC = (i[j] >> 7) & 0x01; + i[j] = (byte)((i[j] << 1) + carry); carry = tmpC; } if (carry) { - tmp[0] ^= GF_XTS; + i[0] ^= GF_XTS; } in += AES_BLOCK_SIZE; @@ -12661,10 +12785,10 @@ static int AesXtsEncrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, XMEMCPY(out, buf2, sz); } - xorbuf(buf, tmp, AES_BLOCK_SIZE); + xorbuf(buf, i, AES_BLOCK_SIZE); ret = wc_AesEncryptDirect(aes, out - AES_BLOCK_SIZE, buf); if (ret == 0) - xorbuf(out - AES_BLOCK_SIZE, tmp, AES_BLOCK_SIZE); + xorbuf(out - AES_BLOCK_SIZE, i, AES_BLOCK_SIZE); } return ret; @@ -12693,6 +12817,17 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, return BAD_FUNC_ARG; } +#if FIPS_VERSION3_GE(6,0,0) + /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is + * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + */ + if (sz > FIPS_AES_XTS_MAX_BYTES_PER_TWEAK) { + WOLFSSL_MSG("Request exceeds allowed bytes per SP800-38E"); + return BAD_FUNC_ARG; + } +#endif + aes = &xaes->aes; if (aes->keylen == 0) { @@ -12711,19 +12846,8 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, { #ifdef WOLFSSL_AESNI -#ifdef WC_AES_C_DYNAMIC_FALLBACK - int orig_use_aesni = aes->use_aesni; -#endif - - if (aes->use_aesni && ((ret = SAVE_VECTOR_REGISTERS2()) != 0)) { -#ifdef WC_AES_C_DYNAMIC_FALLBACK - aes->use_aesni = 0; - xaes->tweak.use_aesni = 0; -#else - return ret; -#endif - } if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); #if defined(HAVE_INTEL_AVX1) if (IS_INTEL_AVX1(intel_flags)) { AES_XTS_encrypt_avx1(in, out, sz, i, @@ -12741,28 +12865,212 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, (int)aes->rounds); ret = 0; } + RESTORE_VECTOR_REGISTERS(); } else #endif { ret = AesXtsEncrypt_sw(xaes, out, in, sz, i); } + } + + return ret; +} + +#ifdef WOLFSSL_AESXTS_STREAM + +/* Block-streaming AES-XTS. + * + * xaes AES keys to use for block encrypt/decrypt + * i readwrite value to use for tweak + * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * adds a sanity check on how the user calls the function. + * + * returns 0 on success + */ +int wc_AesXtsEncryptInit(XtsAes* xaes, const byte* i, word32 iSz, + struct XtsAesStreamData *stream) +{ + int ret; + Aes *aes; + + if ((xaes == NULL) || (i == NULL) || (stream == NULL)) { + return BAD_FUNC_ARG; + } + + if (iSz < AES_BLOCK_SIZE) { + return BAD_FUNC_ARG; + } + + aes = &xaes->aes; + + if (aes->keylen == 0) { + WOLFSSL_MSG("wc_AesXtsEncrypt called with unset encryption key."); + return BAD_FUNC_ARG; + } + + XMEMCPY(stream->tweak_block, i, AES_BLOCK_SIZE); + stream->bytes_crypted_with_this_tweak = 0; + + { #ifdef WOLFSSL_AESNI - if (aes->use_aesni) + if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + AES_XTS_init_avx1(stream->tweak_block, + (const byte*)xaes->tweak.key, + (int)xaes->tweak.rounds); + ret = 0; + } + else +#endif + { + AES_XTS_init_aesni(stream->tweak_block, + (const byte*)xaes->tweak.key, + (int)xaes->tweak.rounds); + ret = 0; + } RESTORE_VECTOR_REGISTERS(); -#ifdef WC_AES_C_DYNAMIC_FALLBACK - else if (orig_use_aesni) { - aes->use_aesni = orig_use_aesni; - xaes->tweak.use_aesni = orig_use_aesni; } + else +#endif /* WOLFSSL_AESNI */ + { + ret = AesXtsInitTweak_sw(xaes, stream->tweak_block); + } + } + + return ret; +} + +/* Block-streaming AES-XTS + * + * Note that sz must be >= AES_BLOCK_SIZE in each call, and must be a multiple + * of AES_BLOCK_SIZE in each call to wc_AesXtsEncryptUpdate(). + * wc_AesXtsEncryptFinal() can handle any length >= AES_BLOCK_SIZE. + * + * xaes AES keys to use for block encrypt/decrypt + * out output buffer to hold cipher text + * in input plain text buffer to encrypt + * sz size of both out and in buffers -- must be >= AES_BLOCK_SIZE. + * i value to use for tweak + * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * adds a sanity check on how the user calls the function. + * + * returns 0 on success + */ +static int AesXtsEncryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + int ret; + +#ifdef WOLFSSL_AESNI + Aes *aes; #endif + + if (xaes == NULL || out == NULL || in == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_AESNI + aes = &xaes->aes; #endif + + if (sz < AES_BLOCK_SIZE) { + WOLFSSL_MSG("Plain text input too small for encryption"); + return BAD_FUNC_ARG; + } + + if (stream->bytes_crypted_with_this_tweak & ((word32)AES_BLOCK_SIZE - 1U)) + { + WOLFSSL_MSG("Call to AesXtsEncryptUpdate after previous finalizing call"); + return BAD_FUNC_ARG; + } + +#ifndef WC_AESXTS_STREAM_NO_REQUEST_ACCOUNTING + (void)WC_SAFE_SUM_WORD32(stream->bytes_crypted_with_this_tweak, sz, + stream->bytes_crypted_with_this_tweak); +#endif +#if FIPS_VERSION3_GE(6,0,0) + /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is + * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + */ + if (stream->bytes_crypted_with_this_tweak > + FIPS_AES_XTS_MAX_BYTES_PER_TWEAK) + { + WOLFSSL_MSG("Request exceeds allowed bytes per SP800-38E"); + return BAD_FUNC_ARG; + } +#endif + { +#ifdef WOLFSSL_AESNI + if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + AES_XTS_encrypt_update_avx1(in, out, sz, + (const byte*)aes->key, + stream->tweak_block, + (int)aes->rounds); + ret = 0; + } + else +#endif + { + AES_XTS_encrypt_update_aesni(in, out, sz, + (const byte*)aes->key, + stream->tweak_block, + (int)aes->rounds); + ret = 0; + } + RESTORE_VECTOR_REGISTERS(); + } + else +#endif /* WOLFSSL_AESNI */ + { + ret = AesXtsEncryptUpdate_sw(xaes, out, in, sz, stream->tweak_block); + } } return ret; } +int wc_AesXtsEncryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + if (stream == NULL) + return BAD_FUNC_ARG; + if (sz & ((word32)AES_BLOCK_SIZE - 1U)) + return BAD_FUNC_ARG; + return AesXtsEncryptUpdate(xaes, out, in, sz, stream); +} + +int wc_AesXtsEncryptFinal(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + int ret; + if (stream == NULL) + return BAD_FUNC_ARG; + if (sz > 0) + ret = AesXtsEncryptUpdate(xaes, out, in, sz, stream); + else + ret = 0; + /* force the count odd, to assure error on attempt to AesXtsEncryptUpdate() + * after finalization. + */ + stream->bytes_crypted_with_this_tweak |= 1U; + ForceZero(stream->tweak_block, AES_BLOCK_SIZE); +#ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Check(stream->tweak_block, AES_BLOCK_SIZE); +#endif + return ret; +} + +#endif /* WOLFSSL_AESXTS_STREAM */ + + /* Same process as encryption but use aes_decrypt key. * * xaes AES keys to use for block encrypt/decrypt @@ -12774,8 +13082,41 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, * returns 0 on success */ /* Software AES - XTS Decrypt */ + +static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, + word32 sz, byte *i); + static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, const byte* i) +{ + int ret; + byte tweak_block[AES_BLOCK_SIZE]; + + ret = wc_AesEncryptDirect(&xaes->tweak, tweak_block, i); + if (ret != 0) + return ret; + + return AesXtsDecryptUpdate_sw(xaes, out, in, sz, tweak_block); +} + +/* Block-streaming AES-XTS. + * + * Same process as encryption but use decrypt key. + * + * Supply block-aligned input data with successive calls. Final call need not + * be block aligned. + * + * xaes AES keys to use for block encrypt/decrypt + * out output buffer to hold plain text + * in input cipher text buffer to decrypt + * sz size of both out and in buffers + * i value to use for tweak + * + * returns 0 on success + */ +/* Software AES - XTS Decrypt */ +static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, + word32 sz, byte *i) { int ret = 0; word32 blocks = (sz / AES_BLOCK_SIZE); @@ -12784,19 +13125,10 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, #else Aes *aes = &xaes->aes; #endif - Aes *tweak = &xaes->tweak; word32 j; byte carry = 0; - byte tmp[AES_BLOCK_SIZE]; byte stl = (sz % AES_BLOCK_SIZE); - XMEMSET(tmp, 0, AES_BLOCK_SIZE); /* set to 0's in case of improper AES - * key setup passed to decrypt direct*/ - - ret = wc_AesEncryptDirect(tweak, tmp, i); - if (ret != 0) - return ret; - /* if Stealing then break out of loop one block early to handle special * case */ if (stl > 0) { @@ -12806,7 +13138,7 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, #ifdef HAVE_AES_ECB /* decrypt all of buffer at once when possible */ if (in != out) { /* can not handle inline */ - XMEMCPY(out, tmp, AES_BLOCK_SIZE); + XMEMCPY(out, i, AES_BLOCK_SIZE); if ((ret = _AesXtsHelper(aes, out, in, sz, AES_DECRYPTION)) != 0) return ret; } @@ -12820,23 +13152,23 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte buf[AES_BLOCK_SIZE]; XMEMCPY(buf, in, AES_BLOCK_SIZE); - xorbuf(buf, tmp, AES_BLOCK_SIZE); + xorbuf(buf, i, AES_BLOCK_SIZE); ret = wc_AesDecryptDirect(aes, out, buf); if (ret != 0) return ret; } - xorbuf(out, tmp, AES_BLOCK_SIZE); + xorbuf(out, i, AES_BLOCK_SIZE); /* multiply by shift left and propagate carry */ for (j = 0; j < AES_BLOCK_SIZE; j++) { byte tmpC; - tmpC = (tmp[j] >> 7) & 0x01; - tmp[j] = (byte)((tmp[j] << 1) + carry); + tmpC = (i[j] >> 7) & 0x01; + i[j] = (byte)((i[j] << 1) + carry); carry = tmpC; } if (carry) { - tmp[0] ^= GF_XTS; + i[0] ^= GF_XTS; } carry = 0; @@ -12855,8 +13187,8 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, for (j = 0; j < AES_BLOCK_SIZE; j++) { byte tmpC; - tmpC = (tmp[j] >> 7) & 0x01; - tmp2[j] = (byte)((tmp[j] << 1) + carry); + tmpC = (i[j] >> 7) & 0x01; + tmp2[j] = (byte)((i[j] << 1) + carry); carry = tmpC; } if (carry) { @@ -12884,11 +13216,11 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, XMEMCPY(buf, in, sz); XMEMCPY(out, tmp2, sz); - xorbuf(buf, tmp, AES_BLOCK_SIZE); + xorbuf(buf, i, AES_BLOCK_SIZE); ret = wc_AesDecryptDirect(aes, tmp2, buf); if (ret != 0) return ret; - xorbuf(tmp2, tmp, AES_BLOCK_SIZE); + xorbuf(tmp2, i, AES_BLOCK_SIZE); XMEMCPY(out - AES_BLOCK_SIZE, tmp2, AES_BLOCK_SIZE); } @@ -12923,6 +13255,14 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, aes = &xaes->aes; #endif +/* FIPS TODO: SP800-38E - Restrict data unit to 2^20 blocks per key. A block is + * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes or + * 134,217,728-bits) Add helpful printout and message along with BAD_FUNC_ARG + * return whenever sz / AES_BLOCK_SIZE > 1,048,576 or equal to that and sz is + * not a sequence of complete blocks. + */ + if (aes->keylen == 0) { WOLFSSL_MSG("wc_AesXtsDecrypt called with unset decryption key."); return BAD_FUNC_ARG; @@ -12939,19 +13279,8 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, { #ifdef WOLFSSL_AESNI -#ifdef WC_AES_C_DYNAMIC_FALLBACK - int orig_use_aesni = aes->use_aesni; -#endif - - if (aes->use_aesni && ((ret = SAVE_VECTOR_REGISTERS2() != 0))) { -#ifdef WC_AES_C_DYNAMIC_FALLBACK - aes->use_aesni = 0; - xaes->tweak.use_aesni = 0; -#else - return ret; -#endif - } if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); #if defined(HAVE_INTEL_AVX1) if (IS_INTEL_AVX1(intel_flags)) { AES_XTS_decrypt_avx1(in, out, sz, i, @@ -12969,6 +13298,7 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, (int)aes->rounds); ret = 0; } + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -12976,20 +13306,198 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, ret = AesXtsDecrypt_sw(xaes, out, in, sz, i); } + return ret; + } +} + +#ifdef WOLFSSL_AESXTS_STREAM + +/* Same process as encryption but Aes key is AES_DECRYPTION type. + * + * xaes AES keys to use for block encrypt/decrypt + * i readwrite value to use for tweak + * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * adds a sanity check on how the user calls the function. + * + * returns 0 on success + */ +int wc_AesXtsDecryptInit(XtsAes* xaes, const byte* i, word32 iSz, + struct XtsAesStreamData *stream) +{ + int ret; + Aes *aes; + + if (xaes == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS + aes = &xaes->aes_decrypt; +#else + aes = &xaes->aes; +#endif + + if (aes->keylen == 0) { + WOLFSSL_MSG("wc_AesXtsDecrypt called with unset decryption key."); + return BAD_FUNC_ARG; + } + + if (iSz < AES_BLOCK_SIZE) { + return BAD_FUNC_ARG; + } + + XMEMCPY(stream->tweak_block, i, AES_BLOCK_SIZE); + stream->bytes_crypted_with_this_tweak = 0; + + { #ifdef WOLFSSL_AESNI - if (aes->use_aesni) + if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + AES_XTS_init_avx1(stream->tweak_block, + (const byte*)xaes->tweak.key, + (int)xaes->tweak.rounds); + ret = 0; + } + else +#endif + { + AES_XTS_init_aesni(stream->tweak_block, + (const byte*)xaes->tweak.key, + (int)xaes->tweak.rounds); + ret = 0; + } RESTORE_VECTOR_REGISTERS(); -#ifdef WC_AES_C_DYNAMIC_FALLBACK - else if (orig_use_aesni) { - aes->use_aesni = orig_use_aesni; - xaes->tweak.use_aesni = orig_use_aesni; } + else +#endif /* WOLFSSL_AESNI */ + { + ret = AesXtsInitTweak_sw(xaes, stream->tweak_block); + } + + } + + return ret; +} + +/* Block-streaming AES-XTS + * + * Note that sz must be >= AES_BLOCK_SIZE in each call, and must be a multiple + * of AES_BLOCK_SIZE in each call to wc_AesXtsDecryptUpdate(). + * wc_AesXtsDecryptFinal() can handle any length >= AES_BLOCK_SIZE. + * + * xaes AES keys to use for block encrypt/decrypt + * out output buffer to hold plain text + * in input cipher text buffer to decrypt + * sz size of both out and in buffers + * i tweak buffer of size AES_BLOCK_SIZE. + * + * returns 0 on success + */ +static int AesXtsDecryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + int ret; +#ifdef WOLFSSL_AESNI + Aes *aes; +#endif + + if (xaes == NULL || out == NULL || in == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_AESNI +#ifdef WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS + aes = &xaes->aes_decrypt; +#else + aes = &xaes->aes; #endif #endif - return ret; + if (sz < AES_BLOCK_SIZE) { + WOLFSSL_MSG("Cipher text input too small for decryption"); + return BAD_FUNC_ARG; + } + + if (stream->bytes_crypted_with_this_tweak & ((word32)AES_BLOCK_SIZE - 1U)) + { + WOLFSSL_MSG("Call to AesXtsDecryptUpdate after previous finalizing call"); + return BAD_FUNC_ARG; + } + +#ifndef WC_AESXTS_STREAM_NO_REQUEST_ACCOUNTING + (void)WC_SAFE_SUM_WORD32(stream->bytes_crypted_with_this_tweak, sz, + stream->bytes_crypted_with_this_tweak); +#endif + + { +#ifdef WOLFSSL_AESNI + if (aes->use_aesni) { + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + AES_XTS_decrypt_update_avx1(in, out, sz, + (const byte*)aes->key, + stream->tweak_block, + (int)aes->rounds); + ret = 0; + } + else +#endif + { + AES_XTS_decrypt_update_aesni(in, out, sz, + (const byte*)aes->key, + stream->tweak_block, + (int)aes->rounds); + ret = 0; + } + RESTORE_VECTOR_REGISTERS(); + } + else +#endif /* WOLFSSL_AESNI */ + { + ret = AesXtsDecryptUpdate_sw(xaes, out, in, sz, + stream->tweak_block); + } } + + return ret; +} + +int wc_AesXtsDecryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + if (stream == NULL) + return BAD_FUNC_ARG; + if (sz & ((word32)AES_BLOCK_SIZE - 1U)) + return BAD_FUNC_ARG; + return AesXtsDecryptUpdate(xaes, out, in, sz, stream); +} + +int wc_AesXtsDecryptFinal(XtsAes* xaes, byte* out, const byte* in, word32 sz, + struct XtsAesStreamData *stream) +{ + int ret; + if (stream == NULL) + return BAD_FUNC_ARG; + if (sz > 0) + ret = AesXtsDecryptUpdate(xaes, out, in, sz, stream); + else + ret = 0; + ForceZero(stream->tweak_block, AES_BLOCK_SIZE); + /* force the count odd, to assure error on attempt to AesXtsEncryptUpdate() + * after finalization. + */ + stream->bytes_crypted_with_this_tweak |= 1U; +#ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Check(stream->tweak_block, AES_BLOCK_SIZE); +#endif + return ret; } + +#endif /* WOLFSSL_AESXTS_STREAM */ + #endif /* !WOLFSSL_ARMASM || WOLFSSL_ARMASM_NO_HW_CRYPTO */ /* Same as wc_AesXtsEncryptSector but the sector gets incremented by one every diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index ac50995..778d3e7 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -166,16 +166,14 @@ ASN Options: #include #endif -#ifdef HAVE_PQC - #if defined(HAVE_FALCON) +#if defined(HAVE_FALCON) #include - #endif - #if defined(HAVE_DILITHIUM) +#endif +#if defined(HAVE_DILITHIUM) #include - #endif - #if defined(HAVE_SPHINCS) +#endif +#if defined(HAVE_SPHINCS) #include - #endif #endif #ifdef WOLFSSL_QNX_CAAM @@ -1203,14 +1201,14 @@ static int GetASN_ObjectId(const byte* input, word32 idx, int length) /* OID data must be at least 3 bytes. */ if (length < 3) { #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE - WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len); + WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", length); #else WOLFSSL_MSG("OID length less than 3"); #endif ret = ASN_PARSE_E; } - /* Last octet of a subidentifier has bit 8 clear. Last octet must be last - * of a subidentifier. Ensure last octet hasn't got top bit set indicating. + /* Last octet of a sub-identifier has bit 8 clear. Last octet must be last + * of a subidentifier. Ensure last octet hasn't got top bit set. */ else if ((input[(int)idx + length - 1] & 0x80) != 0x00) { WOLFSSL_MSG("OID last octet has top bit set"); @@ -3496,7 +3494,7 @@ int CheckBitString(const byte* input, word32* inOutIdx, int* len, #else ASNGetData dataASN[bitStringASN_Length]; int ret; - int bits; + int bits = 0; /* Parse BIT_STRING and check validity of unused bits. */ XMEMSET(dataASN, 0, sizeof(dataASN)); @@ -3534,7 +3532,7 @@ int CheckBitString(const byte* input, word32* inOutIdx, int* len, ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \ (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \ defined(OPENSSL_EXTRA))) || \ - (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \ + (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERTS)) || \ (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \ (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) @@ -4200,7 +4198,6 @@ static word32 SetBitString16Bit(word16 val, byte* output) #ifdef HAVE_ED448 static const byte sigEd448Oid[] = {43, 101, 113}; #endif /* HAVE_ED448 */ -#ifdef HAVE_PQC #ifdef HAVE_FALCON /* Falcon Level 1: 1 3 9999 3 6 */ static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 6}; @@ -4209,17 +4206,17 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 9}; #endif /* HAVE_FACON */ #ifdef HAVE_DILITHIUM - /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */ + /* Dilithium Level 2: 1.3.6.1.4.1.2.267.12.4.4 */ static const byte sigDilithium_Level2Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 4, 4}; - /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */ + /* Dilithium Level 3: 1.3.6.1.4.1.2.267.12.6.5 */ static const byte sigDilithium_Level3Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 6, 5}; - /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */ + /* Dilithium Level 5: 1.3.6.1.4.1.2.267.12.8.7 */ static const byte sigDilithium_Level5Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 8, 7}; #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */ @@ -4246,7 +4243,6 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte sigSphincsSmall_Level5Oid[] = {43, 206, 15, 6, 9, 7}; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ /* keyType */ #ifndef NO_DSA @@ -4276,7 +4272,6 @@ static word32 SetBitString16Bit(word16 val, byte* output) #ifndef NO_DH static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1}; #endif /* !NO_DH */ -#ifdef HAVE_PQC #ifdef HAVE_FALCON /* Falcon Level 1: 1 3 9999 3 6 */ static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 6}; @@ -4285,17 +4280,17 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 9}; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM - /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */ + /* Dilithium Level 2: 1.3.6.1.4.1.2.267.12.4.4 */ static const byte keyDilithium_Level2Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 4, 4}; - /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */ + /* Dilithium Level 3: 1.3.6.1.4.1.2.267.12.6.5 */ static const byte keyDilithium_Level3Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 6, 5}; - /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */ + /* Dilithium Level 5: 1.3.6.1.4.1.2.267.12.8.7 */ static const byte keyDilithium_Level5Oid[] = - {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7}; + {43, 6, 1, 4, 1, 2, 130, 11, 12, 8, 7}; #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */ @@ -4322,7 +4317,6 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte keySphincsSmall_Level5Oid[] = {43, 206, 15, 6, 9, 7}; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ /* curveType */ #ifdef HAVE_ECC @@ -4830,7 +4824,6 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(sigEd448Oid); break; #endif - #ifdef HAVE_PQC #ifdef HAVE_FALCON case CTC_FALCON_LEVEL1: oid = sigFalcon_Level1Oid; @@ -4881,7 +4874,6 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(sigSphincsSmall_Level5Oid); break; #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: break; } @@ -4943,7 +4935,6 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(keyDhOid); break; #endif /* !NO_DH */ - #ifdef HAVE_PQC #ifdef HAVE_FALCON case FALCON_LEVEL1k: oid = keyFalcon_Level1Oid; @@ -4994,7 +4985,6 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(keySphincsSmall_Level5Oid); break; #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: break; } @@ -5875,7 +5865,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, const byte* checkOid = NULL; word32 checkOidSz; #endif /* NO_VERIFY_OID */ -#ifdef HAVE_PQC +#if defined(HAVE_SPHINCS) word32 found_collision = 0; #endif (void)oidType; @@ -5887,7 +5877,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, actualOidSz = (word32)length; #endif /* NO_VERIFY_OID */ -#if defined(HAVE_PQC) && defined(HAVE_LIBOQS) && defined(HAVE_SPHINCS) +#if defined(HAVE_SPHINCS) /* Since we are summing it up, there could be collisions...and indeed there * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3. * @@ -5901,7 +5891,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, sizeof(sigSphincsFast_Level3Oid)) == 0) { found_collision = SPHINCS_FAST_LEVEL3k; } -#endif /* HAVE_PQC */ +#endif /* HAVE_SPHINCS */ /* Sum it up for now. */ while (length--) { @@ -5910,11 +5900,11 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, idx++; } -#ifdef HAVE_PQC +#ifdef HAVE_SPHINCS if (found_collision) { *oid = found_collision; } -#endif /* HAVE_PQC */ +#endif /* HAVE_SPHINCS */ /* Return the index after the OID data. */ *inOutIdx = idx; @@ -6933,7 +6923,7 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, ret = GetOctetString(input, &idx, &length, sz); if (ret < 0) { - if (ret == BUFFER_E) + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) return ASN_PARSE_E; /* Some private keys don't expect an octet string */ WOLFSSL_MSG("Couldn't find Octet string"); @@ -7227,7 +7217,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, return (int)(tmpSz + sz); #else DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length); - int sz; + int sz = 0; int ret = 0; word32 keyIdx = 0; word32 tmpAlgId = 0; @@ -7565,7 +7555,6 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, } else #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) { #ifdef WOLFSSL_SMALL_STACK @@ -7627,7 +7616,8 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, } else #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) if ((ks == DILITHIUM_LEVEL2k) || (ks == DILITHIUM_LEVEL3k) || (ks == DILITHIUM_LEVEL5k)) { @@ -7685,7 +7675,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, #endif } else - #endif /* HAVE_DILITHIUM */ +#endif /* HAVE_DILITHIUM && !WOLFSSL_DILITHIUM_VERIFY_ONLY */ #if defined(HAVE_SPHINCS) if ((ks == SPHINCS_FAST_LEVEL1k) || (ks == SPHINCS_FAST_LEVEL3k) || @@ -7757,7 +7747,6 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, } else #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ { ret = 0; } @@ -7770,17 +7759,59 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, * return 1 (true) on match * return 0 or negative value on failure/error * - * key : buffer holding DER format key - * keySz : size of key buffer - * der : a initialized and parsed DecodedCert holding a certificate */ -int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der) + * key : buffer holding DER format key + * keySz : size of key buffer + * der : a initialized and parsed DecodedCert holding a certificate + * checkAlt : indicate if we check primary or alternative key + */ +int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der, + int checkAlt) { + int ret = 0; + if (key == NULL || der == NULL) { return BAD_FUNC_ARG; } - return wc_CheckPrivateKey(key, keySz, der->publicKey, - der->pubKeySize, (enum Key_Sum) der->keyOID); +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (checkAlt && der->sapkiDer != NULL) { + /* We have to decode the public key first */ + word32 idx = 0; + /* Dilithium has the largest public key at the moment */ + word32 pubKeyLen = DILITHIUM_MAX_PUB_KEY_SIZE; + byte* decodedPubKey = (byte*)XMALLOC(pubKeyLen, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); + if (decodedPubKey == NULL) { + ret = MEMORY_E; + } + if (ret == 0) { + if (der->sapkiOID == RSAk || der->sapkiOID == ECDSAk) { + /* Simply copy the data */ + XMEMCPY(decodedPubKey, der->sapkiDer, der->sapkiLen); + pubKeyLen = der->sapkiLen; + } + else { + ret = DecodeAsymKeyPublic(der->sapkiDer, &idx, der->sapkiLen, + decodedPubKey, &pubKeyLen, + der->sapkiOID); + } + } + if (ret == 0) { + ret = wc_CheckPrivateKey(key, keySz, decodedPubKey, pubKeyLen, + (enum Key_Sum) der->sapkiOID); + } + XFREE(decodedPubKey, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + } + else +#endif + { + ret = wc_CheckPrivateKey(key, keySz, der->publicKey, + der->pubKeySize, (enum Key_Sum) der->keyOID); + } + + (void)checkAlt; + + return ret; } #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */ @@ -8060,7 +8091,6 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER); } #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */ -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) if (*algoID == 0) { falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap, @@ -8096,7 +8126,8 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER); } #endif /* HAVE_FALCON */ -#if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) if (*algoID == 0) { dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium), heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -8142,7 +8173,7 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, } XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER); } -#endif /* HAVE_DILITHIUM */ +#endif /* HAVE_DILITHIUM && !WOLFSSL_DILITHIUM_VERIFY_ONLY */ #if defined(HAVE_SPHINCS) if (*algoID == 0) { sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs), @@ -8220,7 +8251,6 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER); } #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ /* if flag is not set then this is not a key that we understand. */ if (*algoID == 0) { @@ -8605,7 +8635,7 @@ int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, if (ret == 0) { ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid, curveOidSz); - if (ret == LENGTH_ONLY_E) + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) ret = 0; } if (ret == 0) { @@ -8861,7 +8891,7 @@ int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz) DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length); int ret = 0; int id = 0; - int version; + int version = 0; word32 idx = 0; word32 pIdx = 0; word32 iterations = 0; @@ -9915,7 +9945,7 @@ int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz) #if !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)) /* If ASN_DH_KEY_E: Check if input started at beginning of key */ - if (ret == ASN_DH_KEY_E) { + if (ret == WC_NO_ERR_TRACE(ASN_DH_KEY_E)) { *inOutIdx = temp; /* the version (0) - private only (for public skip) */ @@ -10076,7 +10106,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* DH Parameters sequence with P and G */ total = 0; ret = wc_DhParamsToDer(key, NULL, &total); - if (ret != LENGTH_ONLY_E) + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; idx += total; @@ -10725,7 +10755,7 @@ int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key, } } /* An alternate pass if default certificate fails parsing */ - if (ret == ASN_PARSE_E) { + if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E)) { *inOutIdx = (word32)temp; if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) return ASN_PARSE_E; @@ -11366,6 +11396,47 @@ DNS_entry* AltNameNew(void* heap) return ret; } +DNS_entry* AltNameDup(DNS_entry* from, void* heap) +{ + DNS_entry* ret; + + ret = AltNameNew(heap); + if (ret == NULL) { + WOLFSSL_MSG("\tOut of Memory"); + return NULL; + } + + ret->type = from->type; + ret->len = from->len; + + + ret->name = CopyString(from->name, from->len, heap, DYNAMIC_TYPE_ALTNAME); +#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) + ret->ipString = CopyString(from->ipString, 0, heap, DYNAMIC_TYPE_ALTNAME); +#endif +#ifdef OPENSSL_ALL + ret->ridString = CopyString(from->ridString, 0, heap, DYNAMIC_TYPE_ALTNAME); +#endif + if (ret->name == NULL +#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) + || (from->ipString != NULL && ret->ipString == NULL) +#endif +#ifdef OPENSSL_ALL + || (from->ridString != NULL && ret->ridString == NULL) +#endif + ) { + WOLFSSL_MSG("\tOut of Memory"); + FreeAltNames(ret, heap); + return NULL; + } + +#ifdef WOLFSSL_FPKI + ret->oidSum = from->oidSum; +#endif + + return ret; +} + #ifndef IGNORE_NAME_CONSTRAINTS @@ -11471,8 +11542,8 @@ static int GetCertHeader(DecodedCert* cert) } #endif -#if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \ - defined(HAVE_LIBOQS)) +#if defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_FALCON) || \ + defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS) /* Store the key data under the BIT_STRING in dynamically allocated data. * * @param [in, out] cert Certificate object. @@ -11717,7 +11788,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, #endif PRIVATE_KEY_LOCK(); /* LENGTH_ONLY_E on success. */ - if (ret == LENGTH_ONLY_E) { + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { ret = 0; } } @@ -12545,7 +12616,6 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, ret = StoreKey(cert, source, &srcIdx, maxIdx); break; #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) && defined(HAVE_LIBOQS) #ifdef HAVE_FALCON case FALCON_LEVEL1k: cert->pkCurveOID = FALCON_LEVEL1k; @@ -12596,7 +12666,6 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, ret = StoreKey(cert, source, &srcIdx, maxIdx); break; #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ #ifndef NO_DSA case DSAk: cert->publicKey = source + pubIdx; @@ -13834,6 +13903,18 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, return ASN_PARSE_E; } + #ifndef WOLFSSL_NO_ASN_STRICT + /* RFC 5280 section 4.1.2.4 lists a DirecotryString as being + * 1..MAX in length */ + if (strLen < 1) { + WOLFSSL_MSG("Non conforming DirectoryString of length 0 was" + " found"); + WOLFSSL_MSG("Use WOLFSSL_NO_ASN_STRICT if wanting to allow" + " empty DirectoryString's"); + return ASN_PARSE_E; + } + #endif + if (id == ASN_COMMON_NAME) { if (nameType == SUBJECT) { cert->subjectCN = (char *)&input[srcIdx]; @@ -14388,7 +14469,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, DECL_ASNGETDATA(dataASN, rdnASN_Length); int ret = 0; word32 idx = 0; - int len; + int len = 0; word32 srcIdx = *inOutIdx; #ifdef WOLFSSL_X509_NAME_AVAILABLE WOLFSSL_X509_NAME* dName = NULL; @@ -14464,6 +14545,18 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, /* Get string reference. */ GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen); + #ifndef WOLFSSL_NO_ASN_STRICT + /* RFC 5280 section 4.1.2.4 lists a DirecotryString as being + * 1..MAX in length */ + if (ret == 0 && strLen < 1) { + WOLFSSL_MSG("Non conforming DirectoryString of length 0 was" + " found"); + WOLFSSL_MSG("Use WOLFSSL_NO_ASN_STRICT if wanting to allow" + " empty DirectoryString's"); + ret = ASN_PARSE_E; + } + #endif + /* Convert BER tag to a OpenSSL type. */ switch (tag) { case CTC_UTF8: @@ -15585,8 +15678,15 @@ int DecodeToKey(DecodedCert* cert, int verify) int ret; int badDate = 0; +#ifdef WOLFSSL_DUAL_ALG_CERTS + /* Call internal version and decode completely to also handle extensions. + * This is required to parse a potential alternative public key in the + * SubjectAlternativeKey extension. */ + ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 0); +#else /* Call internal version and stop after public key. */ ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1); +#endif /* Always return date errors. */ if (ret == 0) { ret = badDate; @@ -15893,7 +15993,6 @@ static WC_INLINE int IsSigAlgoECC(word32 algoOID) #ifdef HAVE_CURVE448 || (algoOID == X448k) #endif - #ifdef HAVE_PQC #ifdef HAVE_FACON || (algoOID == FALCON_LEVEL1k) || (algoOID == FALCON_LEVEL5k) @@ -15911,7 +16010,6 @@ static WC_INLINE int IsSigAlgoECC(word32 algoOID) || (algoOID == SPHINCS_SMALL_LEVEL3k) || (algoOID == SPHINCS_SMALL_LEVEL5k) #endif - #endif /* HAVE_PQC */ ); } @@ -16090,7 +16188,7 @@ word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz, #else DECL_ASNSETDATA(dataASN, digestInfoASN_Length); int ret = 0; - int sz; + int sz = 0; unsigned char dgst[WC_MAX_DIGEST_SIZE]; CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL); @@ -16229,7 +16327,6 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) sigCtx->key.ed448 = NULL; break; #endif /* HAVE_ED448 */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: case FALCON_LEVEL5k: @@ -16262,7 +16359,6 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) sigCtx->key.sphincs = NULL; break; #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: break; } /* switch (keyOID) */ @@ -16408,7 +16504,6 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, */ break; #endif - #ifdef HAVE_PQC #ifdef HAVE_FALCON case CTC_FALCON_LEVEL1: case CTC_FALCON_LEVEL5: @@ -16432,7 +16527,6 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, /* Hashes done in signing operation. */ break; #endif - #endif /* HAVE_PQC */ default: ret = HASH_TYPE_E; @@ -16812,7 +16906,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: { @@ -16869,7 +16962,9 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) + #if defined(HAVE_DILITHIUM) && \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_NO_ASN1) case DILITHIUM_LEVEL2k: { word32 idx = 0; @@ -17110,7 +17205,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: WOLFSSL_MSG("Verify Key type unknown"); ret = ASN_UNKNOWN_OID_E; @@ -17162,7 +17256,8 @@ static int ConfirmSignature(SignatureCtx* sigCtx, !defined(WOLFSSL_RENESAS_TSIP_TLS) else #else - if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE) + if (!sigCtx->pkCbRsa || + ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif /* WOLFSSL_RENESAS_FSPSM_TLS */ #endif /* HAVE_PK_CALLBACKS */ { @@ -17236,7 +17331,8 @@ static int ConfirmSignature(SignatureCtx* sigCtx, !defined(WOLFSSL_RENESAS_TSIP_TLS) else #else - if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE) + if (!sigCtx->pkCbEcc || + ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif /* WOLFSSL_RENESAS_FSPSM_TLS */ #endif /* HAVE_PK_CALLBACKS */ { @@ -17264,7 +17360,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) case FALCON_LEVEL1k: case FALCON_LEVEL5k: @@ -17275,7 +17370,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: @@ -17300,13 +17395,12 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: break; } /* switch (keyOID) */ #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { goto exit_cs; } #endif @@ -17453,7 +17547,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_ED448 */ - #ifdef HAVE_PQC #ifdef HAVE_FALCON case FALCON_LEVEL1k: { @@ -17583,7 +17676,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, break; } #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ default: break; } /* switch (keyOID) */ @@ -17605,7 +17697,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, WOLFSSL_LEAVE("ConfirmSignature", ret); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; #endif @@ -18202,6 +18294,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, } #endif /* WOLFSSL_QT || OPENSSL_ALL */ + #ifdef OPENSSL_ALL /* GeneralName choice: registeredID */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) { ret = SetDNSEntry(cert, (const char*)(input + idx), len, @@ -18210,6 +18303,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, idx += (word32)len; } } + #endif #endif /* IGNORE_NAME_CONSTRAINTS */ #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI) /* GeneralName choice: otherName */ @@ -18852,6 +18946,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) word32 idx = 0; int length = 0; int ret = 0; + word32 numNames = 0; WOLFSSL_ENTER("DecodeAltNames"); @@ -18884,6 +18979,13 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) while ((ret == 0) && (idx < sz)) { ASNGetData dataASN[altNameASN_Length]; + numNames++; + if (numNames > WOLFSSL_MAX_ALT_NAMES) { + WOLFSSL_MSG("\tToo many subject alternative names"); + ret = ASN_ALT_NAME_E; + break; + } + /* Clear dynamic data items. */ XMEMSET(dataASN, 0, sizeof(dataASN)); /* Parse GeneralName with the choices supported. */ @@ -19751,7 +19853,7 @@ static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert) while (idx < (word32)sz) { ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz); - if (ret == ASN_UNKNOWN_OID_E) + if (ret == WC_NO_ERR_TRACE(ASN_UNKNOWN_OID_E)) continue; else if (ret < 0) return ret; @@ -19831,7 +19933,7 @@ static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert) ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0, input, &idx, sz); /* Skip unknown OIDs. */ - if (ret == ASN_UNKNOWN_OID_E) { + if (ret == WC_NO_ERR_TRACE(ASN_UNKNOWN_OID_E)) { ret = 0; } else if (ret == 0) { @@ -19994,13 +20096,16 @@ static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag, * @param [in] input Buffer holding data. * @param [in] sz Size of data in buffer. * @param [in, out] head Linked list of subtree names. + * @param [in] limit If > 0, limit on number of tree + * entries to process, exceeding + * is an error. * @param [in] heap Dynamic memory hint. * @return 0 on success. * @return MEMORY_E when dynamic memory allocation fails. * @return ASN_PARSE_E when SEQUENCE is not found as expected. */ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, - void* heap) + word32 limit, void* heap) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; @@ -20078,6 +20183,7 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, DECL_ASNGETDATA(dataASN, subTreeASN_Length); word32 idx = 0; int ret = 0; + word32 cnt = 0; (void)heap; @@ -20087,6 +20193,14 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, while ((ret == 0) && (idx < (word32)sz)) { byte minVal = 0; byte maxVal = 0; + if (limit > 0) { + cnt++; + if (cnt > limit) { + WOLFSSL_MSG("too many name constraints"); + ret = ASN_NAME_INVALID_E; + break; + } + } /* Clear dynamic data and set choice for GeneralName and location to * store minimum and maximum. @@ -20185,7 +20299,7 @@ static int DecodeNameConstraints(const byte* input, word32 sz, } if (DecodeSubtree(input + idx, (word32)length, subtree, - cert->heap) < 0) { + WOLFSSL_MAX_NAME_CONSTRAINTS, cert->heap) < 0) { WOLFSSL_MSG("\terror parsing subtree"); return ASN_PARSE_E; } @@ -20212,7 +20326,8 @@ static int DecodeNameConstraints(const byte* input, word32 sz, ret = DecodeSubtree( dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data, dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length, - &cert->permittedNames, cert->heap); + &cert->permittedNames, WOLFSSL_MAX_NAME_CONSTRAINTS, + cert->heap); } } if (ret == 0) { @@ -20221,7 +20336,8 @@ static int DecodeNameConstraints(const byte* input, word32 sz, ret = DecodeSubtree( dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data, dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length, - &cert->excludedNames, cert->heap); + &cert->excludedNames, WOLFSSL_MAX_NAME_CONSTRAINTS, + cert->heap); } } @@ -21072,7 +21188,13 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, ret = ASN_PARSE_E; } #else - WOLFSSL_MSG("Certificate Policy extension not supported yet."); + WOLFSSL_MSG("Certificate Policy extension not supported."); + #ifndef WOLFSSL_NO_ASN_STRICT + if (critical) { + WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E); + ret = ASN_CRIT_EXT_E; + } + #endif #endif break; @@ -21335,7 +21457,7 @@ static int DecodeCertExtensions(DecodedCert* cert) ret = DecodeExtensionType(input + idx, (word32)length, oid, critical, cert, NULL); - if (ret == ASN_CRIT_EXT_E) { + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) { ret = 0; criticalFail = 1; } @@ -21425,7 +21547,7 @@ static int DecodeCertExtensions(DecodedCert* cert) } /* Don't fail criticality until all other extensions have been checked. */ - if (ret == ASN_CRIT_EXT_E) { + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) { criticalRet = ASN_CRIT_EXT_E; ret = 0; } @@ -21670,9 +21792,9 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, DECL_ASNGETDATA(dataASN, x509CertASN_Length); int ret = 0; int badDate = 0; - byte version; + byte version = 0; word32 idx; - word32 serialSz; + word32 serialSz = 0; const unsigned char* issuer = NULL; word32 issuerSz = 0; const unsigned char* subject = NULL; @@ -21755,6 +21877,19 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Set fields extracted from data. */ cert->version = version; cert->serialSz = (int)serialSz; + + #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_PYTHON) + /* RFC 5280 section 4.1.2.2 states that non-conforming CAs may issue + * a negative or zero serial number and should be handled gracefully. + * Since it is a non-conforming CA that issues a serial of 0 then we + * treat it as an error here. */ + if (cert->serialSz == 1 && cert->serial[0] == 0) { + WOLFSSL_MSG("Error serial number of 0, use WOLFSSL_NO_ASN_STRICT " + "if wanted"); + ret = ASN_PARSE_E; + } + #endif + cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum; cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum; cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset; @@ -21948,7 +22083,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* Decode the extension data starting at [3]. */ ret = DecodeCertExtensions(cert); if (criticalExt != NULL) { - if (ret == ASN_CRIT_EXT_E) { + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) { /* Return critical extension not recognized. */ *criticalExt = ret; ret = 0; @@ -22139,7 +22274,7 @@ static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt, /* Decode and validate extensions. */ ret = DecodeCertExtensions(cert); - if (ret == ASN_CRIT_EXT_E) { + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) { /* Return critical extension not recognized. */ *criticalExt = ret; ret = 0; @@ -22366,7 +22501,7 @@ int ParseCert(DecodedCert* cert, int type, int verify, void* cm) char* ptr; #endif - ret = ParseCertRelative(cert, type, verify, cm); + ret = ParseCertRelative(cert, type, verify, cm, NULL); if (ret < 0) return ret; @@ -23119,9 +23254,7 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, #endif /* WOLFSSL_ASN_TEMPLATE */ } -#ifdef OPENSSL_EXTRA -/* Call CheckCertSignature_ex using a public key buffer for verification - */ +/* Call CheckCertSignature_ex using a public key buffer for verification */ int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID) { @@ -23129,6 +23262,7 @@ int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap, pubKey, pubKeySz, pubKeyOID, 0); } +/* Call CheckCertSignature_ex using a public key and oid */ int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID) { @@ -23144,15 +23278,12 @@ int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap, pubKey, pubKeySz, pubKeyOID, 1); } #endif /* WOLFSSL_CERT_REQ */ -#endif /* OPENSSL_EXTRA */ -#ifdef WOLFSSL_SMALL_CERT_VERIFY -/* Call CheckCertSignature_ex using a certificate manager (cm) - */ -int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm) + +/* Call CheckCertSignature_ex using a certificate manager (cm) */ +int wc_CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm) { return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0); } -#endif /* WOLFSSL_SMALL_CERT_VERIFY */ #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */ #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \ @@ -23257,8 +23388,18 @@ int wc_CertGetPubKey(const byte* cert, word32 certSz, return ret; } #endif +Signer* findSignerByName(Signer *list, byte *hash) +{ + Signer *s; + for (s = list; s != NULL; s = s->next) { + if (XMEMCMP(s->subjectNameHash, hash, SIGNER_DIGEST_SIZE) == 0) { + return s; + } + } + return NULL; +} -int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) +int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer *extraCAList) { int ret = 0; #ifndef WOLFSSL_ASN_TEMPLATE @@ -23271,6 +23412,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) int idx = 0; #endif byte* sce_tsip_encRsaKeyIdx; + (void)extraCAList; if (cert == NULL) { return BAD_FUNC_ARG; @@ -23286,7 +23428,8 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) cert->badDate = 0; cert->criticalExt = 0; if ((ret = DecodeToKey(cert, verify)) < 0) { - if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) { + if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) || + ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { cert->badDate = ret; if (verify == VERIFY_SKIP_DATE) ret = 0; @@ -23449,7 +23592,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) cert->extensionsIdx = cert->srcIdx; /* for potential later use */ if ((ret = DecodeCertExtensions(cert)) < 0) { - if (ret == ASN_CRIT_EXT_E) { + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) { cert->criticalExt = ret; } else { @@ -23483,7 +23626,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) cert->extensionsIdx = cert->srcIdx; /* for potential later use */ if ((ret = DecodeCertExtensions(cert)) < 0) { - if (ret == ASN_CRIT_EXT_E) + if (ret == WC_NO_ERR_TRACE(ASN_CRIT_EXT_E)) cert->criticalExt = ret; else return ret; @@ -23536,7 +23679,8 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) #endif { ret = DecodeCert(cert, verify, &cert->criticalExt); - if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) { + if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) || + ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { cert->badDate = ret; if (verify == VERIFY_SKIP_DATE) ret = 0; @@ -23587,8 +23731,13 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE)) { cert->ca = NULL; +#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 + if (extraCAList != NULL) { + cert->ca = findSignerByName(extraCAList, cert->issuerHash); + } +#endif #ifndef NO_SKID - if (cert->extAuthKeyIdSet) { + if (cert->ca == NULL && cert->extAuthKeyIdSet) { cert->ca = GetCA(cm, cert->extAuthKeyId); #ifdef WOLFSSL_AKID_NAME if (cert->ca == NULL) { @@ -23733,13 +23882,19 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) if (cert->ca) { if (verify == VERIFY || verify == VERIFY_OCSP || verify == VERIFY_SKIP_DATE) { + word32 keyOID = cert->ca->keyOID; + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) + if (cert->selfSigned && (cert->signatureOID == CTC_SM3wSM2)) { + keyOID = SM2k; + } + #endif /* try to confirm/verify signature */ if ((ret = ConfirmSignature(&cert->sigCtx, cert->source + cert->certBegin, cert->sigIndex - cert->certBegin, cert->ca->publicKey, cert->ca->pubKeySize, - cert->ca->keyOID, cert->signature, - cert->sigLength, cert->signatureOID, + keyOID, cert->signature, cert->sigLength, + cert->signatureOID, #ifdef WC_RSA_PSS cert->source + cert->sigParamsIndex, cert->sigParamsLength, @@ -23747,12 +23902,50 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) NULL, 0, #endif sce_tsip_encRsaKeyIdx)) != 0) { - if (ret != WC_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) { WOLFSSL_MSG("Confirm signature failed"); } WOLFSSL_ERROR_VERBOSE(ret); return ret; } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ret == 0) && cert->extAltSigAlgSet && + cert->extAltSigValSet) { + #ifndef WOLFSSL_SMALL_STACK + byte der[MAX_CERT_VERIFY_SZ]; + #else + byte *der = (byte*)XMALLOC(MAX_CERT_VERIFY_SZ, cert->heap, + DYNAMIC_TYPE_DCERT); + if (der == NULL) { + ret = MEMORY_E; + } else + #endif /* ! WOLFSSL_SMALL_STACK */ + { + ret = wc_GeneratePreTBS(cert, der, MAX_CERT_VERIFY_SZ); + + if (ret > 0) { + ret = ConfirmSignature(&cert->sigCtx, der, ret, + cert->ca->sapkiDer, cert->ca->sapkiLen, + cert->ca->sapkiOID, cert->altSigValDer, + cert->altSigValLen, cert->altSigAlgOID, + NULL, 0, NULL); + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(der, cert->heap, DYNAMIC_TYPE_DCERT); + #endif /* WOLFSSL_SMALL_STACK */ + + if (ret != 0) { + WOLFSSL_MSG("Confirm alternative signature failed"); + WOLFSSL_ERROR_VERBOSE(ret); + return ret; + } + else { + WOLFSSL_MSG("Alt signature has been verified!"); + } + } + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ } #ifndef IGNORE_NAME_CONSTRAINTS if (verify == VERIFY || verify == VERIFY_OCSP || @@ -23769,6 +23962,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) } #ifdef WOLFSSL_CERT_REQ else if (type == CERTREQ_TYPE) { + /* try to confirm/verify signature */ if ((ret = ConfirmSignature(&cert->sigCtx, cert->source + cert->certBegin, cert->sigIndex - cert->certBegin, @@ -23781,12 +23975,50 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) NULL, 0, #endif sce_tsip_encRsaKeyIdx)) != 0) { - if (ret != WC_PENDING_E) { + if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) { WOLFSSL_MSG("Confirm signature failed"); } WOLFSSL_ERROR_VERBOSE(ret); return ret; } + + #ifdef WOLFSSL_DUAL_ALG_CERTS + if ((ret == 0) && cert->extAltSigAlgSet && + cert->extAltSigValSet) { + #ifndef WOLFSSL_SMALL_STACK + byte der[MAX_CERT_VERIFY_SZ]; + #else + byte *der = (byte*)XMALLOC(MAX_CERT_VERIFY_SZ, cert->heap, + DYNAMIC_TYPE_DCERT); + if (der == NULL) { + ret = MEMORY_E; + } else + #endif /* ! WOLFSSL_SMALL_STACK */ + { + ret = wc_GeneratePreTBS(cert, der, MAX_CERT_VERIFY_SZ); + + if (ret > 0) { + ret = ConfirmSignature(&cert->sigCtx, der, ret, + cert->sapkiDer, cert->sapkiLen, + cert->sapkiOID, cert->altSigValDer, + cert->altSigValLen, cert->altSigAlgOID, + NULL, 0, NULL); + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(der, cert->heap, DYNAMIC_TYPE_DCERT); + #endif /* WOLFSSL_SMALL_STACK */ + + if (ret != 0) { + WOLFSSL_MSG("Confirm alternative signature failed"); + WOLFSSL_ERROR_VERBOSE(ret); + return ret; + } + else { + WOLFSSL_MSG("Alt signature has been verified!"); + } + } + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ } #endif else { @@ -23824,6 +24056,89 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) return ret; } +int FillSigner(Signer* signer, DecodedCert* cert, int type, DerBuffer *der) +{ + int ret = 0; + + if (signer == NULL || cert == NULL) + return BAD_FUNC_ARG; + +#ifdef WOLFSSL_DUAL_ALG_CERTS + if (ret == 0 && signer != NULL) { + if (cert->extSapkiSet && cert->sapkiLen > 0) { + /* Allocated space for alternative public key. */ + signer->sapkiDer = (byte*)XMALLOC(cert->sapkiLen, cert->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (signer->sapkiDer == NULL) { + ret = MEMORY_E; + } + else { + XMEMCPY(signer->sapkiDer, cert->sapkiDer, cert->sapkiLen); + signer->sapkiLen = cert->sapkiLen; + signer->sapkiOID = cert->sapkiOID; + } + } + } +#endif /* WOLFSSL_DUAL_ALG_CERTS */ + +#if defined(WOLFSSL_AKID_NAME) || defined(HAVE_CRL) + if (ret == 0 && signer != NULL) + ret = CalcHashId(cert->serial, (word32)cert->serialSz, + signer->serialHash); +#endif + if (ret == 0 && signer != NULL) { + #ifdef WOLFSSL_SIGNER_DER_CERT + ret = AllocDer(&signer->derCert, der->length, der->type, NULL); + } + if (ret == 0 && signer != NULL) { + XMEMCPY(signer->derCert->buffer, der->buffer, der->length); + #else + (void)der; + #endif + signer->keyOID = cert->keyOID; + if (cert->pubKeyStored) { + signer->publicKey = cert->publicKey; + signer->pubKeySize = cert->pubKeySize; + } + + if (cert->subjectCNStored) { + signer->nameLen = cert->subjectCNLen; + signer->name = cert->subjectCN; + } + signer->maxPathLen = cert->maxPathLen; + signer->selfSigned = cert->selfSigned; + #ifndef IGNORE_NAME_CONSTRAINTS + signer->permittedNames = cert->permittedNames; + signer->excludedNames = cert->excludedNames; + #endif + #ifndef NO_SKID + XMEMCPY(signer->subjectKeyIdHash, cert->extSubjKeyId, + SIGNER_DIGEST_SIZE); + #endif + XMEMCPY(signer->subjectNameHash, cert->subjectHash, + SIGNER_DIGEST_SIZE); + #if defined(HAVE_OCSP) || defined(HAVE_CRL) + XMEMCPY(signer->issuerNameHash, cert->issuerHash, + SIGNER_DIGEST_SIZE); + #endif + #ifdef HAVE_OCSP + XMEMCPY(signer->subjectKeyHash, cert->subjectKeyHash, + KEYID_SIZE); + #endif + signer->keyUsage = cert->extKeyUsageSet ? cert->extKeyUsage + : 0xFFFF; + signer->next = NULL; /* If Key Usage not set, all uses valid. */ + cert->publicKey = 0; /* in case lock fails don't free here. */ + cert->subjectCN = 0; + #ifndef IGNORE_NAME_CONSTRAINTS + cert->permittedNames = NULL; + cert->excludedNames = NULL; + #endif + signer->type = (byte)type; + } + return ret; +} + /* Create and init an new signer */ Signer* MakeSigner(void* heap) { @@ -23852,6 +24167,9 @@ void FreeSigner(Signer* signer, void* heap) (void)heap; XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN); XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); +#ifdef WOLFSSL_DUAL_ALG_CERTS + XFREE(signer->sapkiDer, heap, DYNAMIC_TYPE_PUBLIC_KEY); +#endif #ifndef IGNORE_NAME_CONSTRAINTS if (signer->permittedNames) FreeNameSubtrees(signer->permittedNames, heap); @@ -24080,7 +24398,7 @@ int wc_GetSerialNumber(const byte* input, word32* inOutIdx, int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (pDer) { int dynType = 0; DerBuffer* der; @@ -24111,18 +24429,31 @@ int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap) der->buffer = (byte*)der + sizeof(DerBuffer); der->length = length; ret = 0; /* Success */ + } else { + ret = BAD_FUNC_ARG; } return ret; } +int AllocCopyDer(DerBuffer** pDer, const unsigned char* buff, word32 length, + int type, void* heap) +{ + int ret = AllocDer(pDer, length, type, heap); + if (ret == 0) { + XMEMCPY((*pDer)->buffer, buff, length); + } + + return ret; +} + void FreeDer(DerBuffer** pDer) { - if (pDer && *pDer) - { + if (pDer && *pDer) { DerBuffer* der = (DerBuffer*)*pDer; /* ForceZero private keys */ - if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) { + if (((der->type == PRIVATEKEY_TYPE) || + (der->type == ALT_PRIVATEKEY_TYPE)) && der->buffer != NULL) { ForceZero(der->buffer, der->length); } der->buffer = NULL; @@ -24198,7 +24529,6 @@ wcchar END_PUB_KEY = "-----END PUBLIC KEY-----"; wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----"; wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----"; #endif -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----"; wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----"; @@ -24228,7 +24558,6 @@ wcchar END_PUB_KEY = "-----END PUBLIC KEY-----"; wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----" "-----END X509 CRL-----"); @@ -24248,7 +24577,7 @@ static WC_INLINE const char* SkipEndOfLineChars(const char* line, int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (type) { case CA_TYPE: /* same as below */ @@ -24336,7 +24665,6 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) ret = 0; break; #endif -#ifdef HAVE_PQC #ifdef HAVE_FALCON case FALCON_LEVEL1_TYPE: if (header) *header = BEGIN_FALCON_LEVEL1_PRIV; @@ -24398,7 +24726,6 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) ret = 0; break; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ case PUBLICKEY_TYPE: case ECC_PUBLICKEY_TYPE: if (header) *header = BEGIN_PUB_KEY; @@ -24424,6 +24751,7 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) ret = 0; break; default: + ret = BAD_FUNC_ARG; break; } return ret; @@ -24726,7 +25054,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, #endif outLen = 0; if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen)) - != LENGTH_ONLY_E) { + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_ERROR_VERBOSE(err); return err; } @@ -25670,7 +25998,7 @@ static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType, /* returns 0 on success */ int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz) { - int ret = ALT_NAME_E; + int ret = WC_NO_ERR_TRACE(ALT_NAME_E); DNS_entry* id = NULL; do { @@ -25707,7 +26035,7 @@ int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz) /* returns 0 on success */ int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz) { - int ret = ALT_NAME_E; + int ret = WC_NO_ERR_TRACE(ALT_NAME_E); DNS_entry* id = NULL; do { @@ -25917,6 +26245,7 @@ int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen, #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA || ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN))) */ +#endif /* NO_CERTS */ #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \ defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \ @@ -25937,11 +26266,16 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) { #ifndef WOLFSSL_ASN_TEMPLATE int ret = 0, i; + int mpSz; word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0; word32 sizes[RSA_INTS]; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; + mp_int* keyInt; +#ifndef WOLFSSL_NO_MALLOC + word32 rawLen; byte* tmps[RSA_INTS]; +#endif if (key == NULL) return BAD_FUNC_ARG; @@ -25949,18 +26283,18 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) if (key->type != RSA_PRIVATE) return BAD_FUNC_ARG; +#ifndef WOLFSSL_NO_MALLOC for (i = 0; i < RSA_INTS; i++) tmps[i] = NULL; +#endif /* write all big ints from key to DER tmps */ for (i = 0; i < RSA_INTS; i++) { - mp_int* keyInt = GetRsaInt(key, i); - int mpSz; - word32 rawLen; - + keyInt = GetRsaInt(key, i); ret = mp_unsigned_bin_size(keyInt); if (ret < 0) - return ret; + break; +#ifndef WOLFSSL_NO_MALLOC rawLen = (word32)ret + 1; ret = 0; if (output != NULL) { @@ -25971,8 +26305,11 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) break; } } - mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]); +#else + ret = 0; + mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, NULL); +#endif if (mpSz < 0) { ret = mpSz; break; @@ -26004,15 +26341,33 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) j += verSz; for (i = 0; i < RSA_INTS; i++) { +/* copy from tmps if we have malloc, otherwise re-export with buffer */ +#ifndef WOLFSSL_NO_MALLOC XMEMCPY(output + j, tmps[i], sizes[i]); j += sizes[i]; +#else + keyInt = GetRsaInt(key, i); + ret = mp_unsigned_bin_size(keyInt); + if (ret < 0) + break; + ret = 0; + /* This won't overrun output due to the outLen check above */ + mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, output + j); + if (mpSz < 0) { + ret = mpSz; + break; + } + j += mpSz; +#endif } } +#ifndef WOLFSSL_NO_MALLOC for (i = 0; i < RSA_INTS; i++) { if (tmps[i]) XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA); } +#endif if (ret == 0) ret = (int)outLen; @@ -26061,6 +26416,7 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */ +#ifndef NO_CERTS #ifdef WOLFSSL_CERT_GEN @@ -26321,7 +26677,7 @@ static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz, InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz, cert->heap, devId); ret = ParseCertRelative((DecodedCert*)cert->decodedCert, - CERT_TYPE, 0, NULL); + CERT_TYPE, 0, NULL, NULL); if (ret >= 0) { cert->der = (byte*)der; } @@ -27565,6 +27921,17 @@ static int EncodeName(EncodedName* name, const char* nameStr, ret = BAD_FUNC_ARG; } +#ifdef WOLFSSL_CUSTOM_OID + if (ret == 0 && type == ASN_CUSTOM_NAME) { + if (cname == NULL || cname->custom.oidSz == 0) { + name->used = 0; + return 0; + } + } +#else + (void)cname; +#endif + CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL); if (ret == 0) { nameSz = (word32)XSTRLEN(nameStr); @@ -28164,7 +28531,8 @@ int SetName(byte* output, word32 outputSz, CertName* name) static int EncodePublicKey(int keyType, byte* output, int outLen, RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key, ed448_key* ed448Key, - DsaKey* dsaKey) + DsaKey* dsaKey, falcon_key* falconKey, + dilithium_key* dilithiumKey, sphincs_key* sphincsKey) { int ret = 0; @@ -28174,6 +28542,9 @@ static int EncodePublicKey(int keyType, byte* output, int outLen, (void)ed25519Key; (void)ed448Key; (void)dsaKey; + (void)falconKey; + (void)dilithiumKey; + (void)sphincsKey; switch (keyType) { #ifndef NO_RSA @@ -28209,6 +28580,41 @@ static int EncodePublicKey(int keyType, byte* output, int outLen, } break; #endif + #if defined(HAVE_FALCON) + case FALCON_LEVEL1_KEY: + case FALCON_LEVEL5_KEY: + ret = wc_Falcon_PublicKeyToDer(falconKey, output, + (word32)outLen, 1); + if (ret <= 0) { + ret = PUBLIC_KEY_E; + } + break; + #endif /* HAVE_FALCON */ + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) + case DILITHIUM_LEVEL2_KEY: + case DILITHIUM_LEVEL3_KEY: + case DILITHIUM_LEVEL5_KEY: + ret = wc_Dilithium_PublicKeyToDer(dilithiumKey, output, + (word32)outLen, 1); + if (ret <= 0) { + ret = PUBLIC_KEY_E; + } + break; + #endif /* HAVE_DILITHIUM */ + #if defined(HAVE_SPHINCS) + case SPHINCS_FAST_LEVEL1_KEY: + case SPHINCS_FAST_LEVEL3_KEY: + case SPHINCS_FAST_LEVEL5_KEY: + case SPHINCS_SMALL_LEVEL1_KEY: + case SPHINCS_SMALL_LEVEL3_KEY: + case SPHINCS_SMALL_LEVEL5_KEY: + ret = wc_Sphincs_PublicKeyToDer(sphincsKey, output, + (word32)outLen, 1); + if (ret <= 0) { + ret = PUBLIC_KEY_E; + } + break; + #endif /* HAVE_SPHINCS */ default: ret = PUBLIC_KEY_E; break; @@ -28997,7 +29403,6 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, } #endif -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) if ((cert->keyType == FALCON_LEVEL1_KEY) || (cert->keyType == FALCON_LEVEL5_KEY)) { @@ -29009,7 +29414,7 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, (word32)sizeof(der->publicKey), 1); } #endif /* HAVE_FALCON */ -#if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) if ((cert->keyType == DILITHIUM_LEVEL2_KEY) || (cert->keyType == DILITHIUM_LEVEL3_KEY) || (cert->keyType == DILITHIUM_LEVEL5_KEY)) { @@ -29036,7 +29441,6 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, (word32)sizeof(der->publicKey), 1); } #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ if (der->publicKeySz <= 0) return PUBLIC_KEY_E; @@ -29542,7 +29946,6 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, } #endif /* HAVE_ED448 && HAVE_ED448_SIGN */ - #if defined(HAVE_PQC) #if defined(HAVE_FALCON) if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) { word32 outSz = sigSz; @@ -29569,7 +29972,6 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, ret = outSz; } #endif /* HAVE_SPHINCS */ - #endif /* HAVE_PQC */ break; } @@ -29577,7 +29979,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, exit_ms: #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { return ret; } #endif @@ -29786,7 +30188,6 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = ED25519_KEY; else if (ed448Key) cert->keyType = ED448_KEY; -#ifdef HAVE_PQC #ifdef HAVE_FALCON else if ((falconKey != NULL) && (falconKey->level == 1)) cert->keyType = FALCON_LEVEL1_KEY; @@ -29821,7 +30222,6 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, && (sphincsKey->optim == SMALL_VARIANT)) cert->keyType = SPHINCS_SMALL_LEVEL5_KEY; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ else return BAD_FUNC_ARG; @@ -29881,7 +30281,6 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, else if (ed448Key) { cert->keyType = ED448_KEY; } -#ifdef HAVE_PQC #ifdef HAVE_FALCON else if ((falconKey != NULL) && (falconKey->level == 1)) { cert->keyType = FALCON_LEVEL1_KEY; @@ -29927,7 +30326,6 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = SPHINCS_SMALL_LEVEL5_KEY; } #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ else { ret = BAD_FUNC_ARG; } @@ -29975,7 +30373,8 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, if (ret >= 0) { /* Calculate public key encoding size. */ ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, - eccKey, ed25519Key, ed448Key, dsaKey); + eccKey, ed25519Key, ed448Key, dsaKey, falconKey, + dilithiumKey, sphincsKey); publicKeySz = (word32)ret; } if (ret >= 0) { @@ -30155,7 +30554,8 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, .data.buffer.data, (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ] .data.buffer.length, - rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); + rsaKey, eccKey, ed25519Key, ed448Key, dsaKey, + falconKey, dilithiumKey, sphincsKey); } if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) { /* Encode extensions into buffer. */ @@ -30236,6 +30636,7 @@ int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey, NULL, NULL, NULL, NULL); } + #ifdef WOLFSSL_CERT_REQ #ifndef WOLFSSL_ASN_TEMPLATE @@ -30499,7 +30900,6 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, (word32)sizeof(der->publicKey), 1); } #endif -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) if ((cert->keyType == FALCON_LEVEL1_KEY) || (cert->keyType == FALCON_LEVEL5_KEY)) { @@ -30509,7 +30909,7 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, der->publicKey, (word32)sizeof(der->publicKey), 1); } #endif -#if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) if ((cert->keyType == DILITHIUM_LEVEL2_KEY) || (cert->keyType == DILITHIUM_LEVEL3_KEY) || (cert->keyType == DILITHIUM_LEVEL5_KEY)) { @@ -30532,7 +30932,6 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, der->publicKey, (word32)sizeof(der->publicKey), 1); } #endif -#endif /* HAVE_PQC */ if (der->publicKeySz <= 0) return PUBLIC_KEY_E; @@ -30858,7 +31257,6 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = ED25519_KEY; else if (ed448Key) cert->keyType = ED448_KEY; -#ifdef HAVE_PQC #ifdef HAVE_FALCON else if ((falconKey != NULL) && (falconKey->level == 1)) cert->keyType = FALCON_LEVEL1_KEY; @@ -30893,7 +31291,6 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, && (sphincsKey->optim == SMALL_VARIANT)) cert->keyType = SPHINCS_SMALL_LEVEL5_KEY; #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ else return BAD_FUNC_ARG; @@ -30954,7 +31351,6 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, else if (ed448Key != NULL) { cert->keyType = ED448_KEY; } -#ifdef HAVE_PQC #ifdef HAVE_FALCON else if ((falconKey != NULL) && (falconKey->level == 1)) { cert->keyType = FALCON_LEVEL1_KEY; @@ -31000,7 +31396,6 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = SPHINCS_SMALL_LEVEL5_KEY; } #endif /* HAVE_SPHINCS */ -#endif /* HAVE_PQC */ else { ret = BAD_FUNC_ARG; } @@ -31022,7 +31417,8 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, if (ret >= 0) { /* Determine encode public key size. */ ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey, - eccKey, ed25519Key, ed448Key, dsaKey); + eccKey, ed25519Key, ed448Key, dsaKey, falconKey, + dilithiumKey, sphincsKey); publicKeySz = (word32)ret; } if (ret >= 0) { @@ -31136,7 +31532,8 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, ret = EncodePublicKey(cert->keyType, (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data, (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length, - rsaKey, eccKey, ed25519Key, ed448Key, dsaKey); + rsaKey, eccKey, ed25519Key, ed448Key, dsaKey, falconKey, + dilithiumKey, sphincsKey); } if ((ret >= 0 && derBuffer != NULL) && (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) { @@ -31266,7 +31663,7 @@ static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz, MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap); #ifdef WOLFSSL_ASYNC_CRYPT - if (sigSz == WC_PENDING_E) { + if (sigSz == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Not free'ing certSignCtx->sig here because it could still be in use * with async operations. */ return sigSz; @@ -31379,7 +31776,7 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap); #ifdef WOLFSSL_ASYNC_CRYPT - if (ret == WC_PENDING_E) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { /* Not free'ing certSignCtx->sig here because it could still be in use * with async operations. */ return ret; @@ -31387,6 +31784,8 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, #endif if (ret <= 0) { + XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER); + certSignCtx->sig = NULL; return ret; } @@ -31460,6 +31859,7 @@ int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz, NULL, NULL, NULL, rng); } + WOLFSSL_ABI int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz, RsaKey* key, WC_RNG* rng) @@ -31536,14 +31936,13 @@ static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey, bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0); } #endif -#if defined(HAVE_PQC) #if defined(HAVE_FALCON) if (falconKey != NULL) { bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ, 0); } #endif -#if defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) if (dilithiumKey != NULL) { bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf, MAX_PUBLIC_KEY_SZ, 0); @@ -31555,7 +31954,6 @@ static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey, MAX_PUBLIC_KEY_SZ, 0); } #endif -#endif /* HAVE_PQC */ if (bufferSz <= 0) { XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -32023,7 +32421,7 @@ static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz, #endif InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId); - ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); + ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0, NULL); if (ret < 0) { WOLFSSL_MSG("ParseCertRelative error"); @@ -32222,7 +32620,7 @@ static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId) #endif InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId); - ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0); + ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0, NULL); if (ret < 0) { WOLFSSL_MSG("ParseCertRelative error"); @@ -34075,7 +34473,7 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, PRIVATE_KEY_UNLOCK(); ret = wc_ecc_export_x963(key, NULL, &pubSz); PRIVATE_KEY_LOCK(); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { #ifndef WOLFSSL_NO_MALLOC XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -34173,7 +34571,8 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, return (int)totalSz; #else DECL_ASNSETDATA(dataASN, eccKeyASN_Length); - word32 privSz, pubSz; + word32 privSz = 0; + word32 pubSz = 0; int sz = 0; int ret = 0; int curveIdSz = 0; @@ -34198,7 +34597,7 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, PRIVATE_KEY_UNLOCK(); ret = wc_ecc_export_x963(key, NULL, &pubSz); PRIVATE_KEY_LOCK(); - if (ret == LENGTH_ONLY_E) + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) ret = 0; } } @@ -34300,7 +34699,7 @@ int wc_EccKeyDerSize(ecc_key* key, int pub) ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } return (int)sz; @@ -34367,7 +34766,7 @@ static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen, /* get pkcs8 expected output size */ ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID, curveOID, oidSz); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { #ifndef WOLFSSL_NO_MALLOC XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -34467,13 +34866,11 @@ enum { || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \ || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \ || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \ - || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \ - || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \ - || (defined(HAVE_PQC) && defined(HAVE_SPHINCS))) + || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)) -int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, - byte* privKey, word32* privKeyLen, - byte* pubKey, word32* pubKeyLen, int keyType) +int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, + const byte** privKey, word32* privKeyLen, + const byte** pubKey, word32* pubKeyLen, int keyType) { #ifndef WOLFSSL_ASN_TEMPLATE word32 oid; @@ -34528,12 +34925,9 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, endKeyIdx = (int)*inOutIdx; } - if ((word32)privSz > *privKeyLen) - return BUFFER_E; - if (endKeyIdx == (int)*inOutIdx) { *privKeyLen = (word32)privSz; - XMEMCPY(privKey, priv, *privKeyLen); + *privKey = priv; if (pubKeyLen != NULL) *pubKeyLen = 0; } @@ -34547,17 +34941,14 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, return ASN_PARSE_E; } - if ((word32)pubSz > *pubKeyLen) - return BUFFER_E; - pub = input + *inOutIdx; *inOutIdx += (word32)pubSz; *privKeyLen = (word32)privSz; - XMEMCPY(privKey, priv, *privKeyLen); + *privKey = priv; *pubKeyLen = (word32)pubSz; if (pubKey != NULL) - XMEMCPY(pubKey, pub, *pubKeyLen); + *pubKey = pub; } if (endKeyIdx != (int)*inOutIdx) return ASN_PARSE_E; @@ -34581,33 +34972,22 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, } } } - /* Check the private value length is correct. */ - if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length - > *privKeyLen) { - ret = ASN_PARSE_E; + if (ret == 0) { + /* Import private value. */ + *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length; + *privKey = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data; } if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) { - *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length; - XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data, - *privKeyLen); + /* Set public length to 0 as not seen. */ if (pubKeyLen != NULL) *pubKeyLen = 0; } - else if ((ret == 0) && - (pubKeyLen != NULL) && - (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) { - ret = ASN_PARSE_E; - } else if (ret == 0) { - /* Import private and public value. */ - *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length; - XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data, - *privKeyLen); + /* Import public value. */ if (pubKeyLen != NULL) *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length; if (pubKey != NULL && pubKeyLen != NULL) - XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data, - *pubKeyLen); + *pubKey = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data; } FREE_ASNGETDATA(dataASN, NULL); @@ -34615,8 +34995,46 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, #endif /* WOLFSSL_ASN_TEMPLATE */ } -int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, +int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, + byte* privKey, word32* privKeyLen, byte* pubKey, word32* pubKeyLen, int keyType) +{ + int ret = 0; + const byte* privKeyPtr = NULL; + const byte* pubKeyPtr = NULL; + word32 privKeyPtrLen = 0; + word32 pubKeyPtrLen = 0; + + if (privKey == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &privKeyPtr, + &privKeyPtrLen, &pubKeyPtr, &pubKeyPtrLen, keyType); + } + if ((ret == 0) && (privKeyPtrLen > *privKeyLen)) { + ret = BUFFER_E; + } + if ((ret == 0) && (pubKeyLen != NULL) && (pubKeyPtrLen > *pubKeyLen)) { + ret = BUFFER_E; + } + if ((ret == 0) && (privKeyPtr != NULL)) { + XMEMCPY(privKey, privKeyPtr, privKeyPtrLen); + *privKeyLen = privKeyPtrLen; + } + if ((ret == 0) && (pubKey != NULL) && (pubKeyPtr != NULL)) { + XMEMCPY(pubKey, pubKeyPtr, pubKeyPtrLen); + } + if ((ret == 0) && (pubKeyLen != NULL)) { + *pubKeyLen = pubKeyPtrLen; + } + + return ret; +} + +int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, + const byte** pubKey, word32* pubKeyLen, int keyType) { int ret = 0; #ifndef WOLFSSL_ASN_TEMPLATE @@ -34649,17 +35067,13 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, if (ret != 0) return ret; - /* check that the value found is not too large for pubKey buffer */ - if ((word32)length > *pubKeyLen) - return ASN_PARSE_E; - /* check that input buffer is exhausted */ if (*inOutIdx + (word32)length != inSz) return ASN_PARSE_E; /* This is the raw point data compressed or uncompressed. */ *pubKeyLen = (word32)length; - XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen); + *pubKey = input + *inOutIdx; #else len = inSz - *inOutIdx; @@ -34680,11 +35094,6 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, if (*inOutIdx != inSz) ret = ASN_PARSE_E; } - /* Check the public value length is correct. */ - if ((ret == 0) && - (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) { - ret = ASN_PARSE_E; - } /* Check that the all the buffer was used. */ if ((ret == 0) && (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) { @@ -34692,14 +35101,39 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, } if (ret == 0) { *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length; - XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data, - *pubKeyLen); + *pubKey = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data; } FREE_ASNGETDATA(dataASN, NULL); #endif /* WOLFSSL_ASN_TEMPLATE */ return ret; } + +int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, + byte* pubKey, word32* pubKeyLen, int keyType) +{ + int ret = 0; + const byte* pubKeyPtr = NULL; + word32 pubKeyPtrLen = 0; + + if (pubKey == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKeyPtr, + &pubKeyPtrLen, keyType); + } + if ((ret == 0) && (pubKeyPtrLen > *pubKeyLen)) { + ret = BUFFER_E; + } + if ((ret == 0) && (pubKeyPtr != NULL)) { + XMEMCPY(pubKey, pubKeyPtr, pubKeyPtrLen); + *pubKeyLen = pubKeyPtrLen; + } + + return ret; +} #endif #endif /* WC_ENABLE_ASYM_KEY_IMPORT */ @@ -35135,7 +35569,7 @@ int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen, byte pubKey[CURVE448_PUB_KEY_SIZE]; word32 pubKeyLen = (word32)sizeof(pubKey); - if (key == NULL || output == NULL) { + if (key == NULL) { return BAD_FUNC_ARG; } @@ -36125,7 +36559,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, /* Don't verify if we don't have access to Cert Manager. */ ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY_OCSP_CERT, - cm); + cm, resp->pendingCAs); if (ret < 0) { WOLFSSL_MSG("\tOCSP Responder certificate parsing failed"); break; @@ -36184,7 +36618,11 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, #else ca = GetCA(cm, resp->single->issuerHash); #endif - +#if defined(HAVE_CERTIFICATE_STATUS_V2) + if (ca == NULL && resp->pendingCAs != NULL) { + ca = findSignerByName(resp->pendingCAs, resp->single->issuerHash); + } +#endif if (ca) { SignatureCtx sigCtx; InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); @@ -36282,7 +36720,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, /* Parse the certificate and don't verify if we don't have access to * Cert Manager. */ ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY, - cm); + cm, resp->pendingCAs); if (ret < 0) { WOLFSSL_MSG("\tOCSP Responder certificate parsing failed"); } @@ -36321,6 +36759,13 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, #else ca = GetCA(cm, resp->single->issuerHash); #endif + + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (ca == NULL && resp->pendingCAs != NULL) { + ca = findSignerByName(resp->pendingCAs, resp->single->issuerHash); + } + #endif + if (ca) { SignatureCtx sigCtx; @@ -36378,6 +36823,7 @@ void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status, resp->source = source; resp->maxIdx = inSz; resp->heap = heap; + resp->pendingCAs = NULL; } void FreeOcspResponse(OcspResponse* resp) @@ -37413,7 +37859,7 @@ int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned, InitSignatureCtx(sigCtx, heap, INVALID_DEVID); if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey, ca->pubKeySize, ca->keyOID, signature, sigSz, - signatureOID, sigParams, sigParamsSz, NULL) != 0) { + signatureOID, sigParams, (word32)sigParamsSz, NULL) != 0) { WOLFSSL_MSG("CRL Confirm signature failed"); WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E); return ASN_CRL_CONFIRM_E; @@ -38137,7 +38583,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, buff); dcrl->sigParamsIndex = dataASN[CRLASN_IDX_SIGALGO_PARAMS].offset; - dcrl->sigParamsLength = sigParamsSz; + dcrl->sigParamsLength = (word32)sigParamsSz; } #endif @@ -39011,7 +39457,7 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) /* Get the OID value for the OBJECT_ID. */ if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType, - asn1->item.len + 2) == ASN_PARSE_E) { + asn1->item.len + 2) == WC_NO_ERR_TRACE(ASN_PARSE_E)) { known = 0; } else diff --git a/src/wolfcrypt/src/bio.c b/src/wolfcrypt/src/bio.c index 2dab43e..340cbfd 100644 --- a/src/wolfcrypt/src/bio.c +++ b/src/wolfcrypt/src/bio.c @@ -50,7 +50,7 @@ */ static int wolfSSL_BIO_BASE64_read(WOLFSSL_BIO* bio, void* buf, int len) { - word32 frmtSz = len; + word32 frmtSz = (word32)len; WOLFSSL_ENTER("wolfSSL_BIO_BASE64_read"); @@ -77,6 +77,8 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) if (buf == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nread(bio, &pt, len); if (sz1 > 0) { XMEMCPY(buf, pt, sz1); @@ -91,8 +93,10 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } } } - if (sz1 == 0) + if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY; sz1 = -1; + } return sz1; } @@ -175,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } - bio->mem_buf->length = bio->wrSz; + bio->mem_buf->length = (size_t)bio->wrSz; bio->ptr = bio->mem_buf->data; } } @@ -233,13 +237,13 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, - sz) != WOLFSSL_SUCCESS) + (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, sz) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -305,12 +309,12 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFREAD(buf, 1, len, (XFILE)bio->ptr); + ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, len); + ret = (int)XREAD(bio->num, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -399,7 +403,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, /* get the encoded length */ if (bio->flags & WOLFSSL_BIO_FLAG_BASE64_NO_NL) { if (Base64_Encode_NoNl((const byte*)data, inLen, NULL, - &sz) != LENGTH_ONLY_E) { + &sz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -448,7 +452,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, (void)heap; - return inLen; + return (int)inLen; } #endif /* WOLFSSL_BASE64_ENCODE */ @@ -502,8 +506,11 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (bio == NULL || data == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; WOLFSSL_MSG("No room left to write"); return WOLFSSL_BIO_ERROR; } @@ -521,6 +528,8 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (sz2 > 0) { XMEMCPY(buf, data, sz2); sz1 += sz2; + if (len > sz2) + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; } } @@ -591,12 +600,12 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, - len) != WOLFSSL_SUCCESS) { + (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, len) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -652,7 +661,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) if (ret > 0) { /* change so that data is formatted buffer */ data = frmt; - len = frmtSz; + len = (int)frmtSz; } #else WOLFSSL_MSG("WOLFSSL_BIO_BASE64 used without " @@ -670,12 +679,12 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFWRITE(data, 1, len, (XFILE)bio->ptr); + ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, len); + ret = (int)XWRITE(bio->num, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -972,7 +981,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { - ret = szOut; + ret = (int)szOut; } } break; @@ -1257,8 +1266,8 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) bio->rdIdx = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = bio->num; - bio->mem_buf->max = bio->num; + bio->mem_buf->length = (size_t)bio->num; + bio->mem_buf->max = (size_t)bio->num; } return WOLFSSL_SUCCESS; @@ -1608,7 +1617,12 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) XFCLOSE((XFILE)bio->ptr); } - bio->ptr = XFOPEN(name, "w"); + /* 'b' flag is ignored on POSIX targets, but on Windows it assures + * inhibition of LF<->CRLF rewriting, so that there is consistency + * between the size and contents of the representation in memory and on + * disk. + */ + bio->ptr = XFOPEN(name, "wb"); if (((XFILE)bio->ptr) == XBADFILE) { return WOLFSSL_FAILURE; } @@ -2637,7 +2651,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) len = (int)XSTRLEN((const char*)buf) + 1; } - if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, len) == 0) { + if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, (size_t)len) == 0) { wolfSSL_BIO_free(bio); return NULL; } diff --git a/src/wolfcrypt/src/chacha.c b/src/wolfcrypt/src/chacha.c index c84829b..f497560 100644 --- a/src/wolfcrypt/src/chacha.c +++ b/src/wolfcrypt/src/chacha.c @@ -72,6 +72,10 @@ Public domain. #elif defined(__clang__) && defined(NO_AVX2_SUPPORT) #undef NO_AVX2_SUPPORT #endif + #if defined(_MSC_VER) && (_MSC_VER <= 1900) + #undef NO_AVX2_SUPPORT + #define NO_AVX2_SUPPORT + #endif #ifndef NO_AVX2_SUPPORT #define HAVE_INTEL_AVX2 diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index c1edfc3..b77cc33 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -39,8 +39,8 @@ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$n") - #pragma const_seg(".fipsB$n") + #pragma code_seg(".fipsA$c") + #pragma const_seg(".fipsB$c") #endif #endif @@ -59,6 +59,15 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_cmac_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000003 }; + int wolfCrypt_FIPS_CMAC_sanity(void) + { + return 0; + } +#endif + #ifdef WOLFSSL_HASH_KEEP /* Some hardware have issues with update, this function stores the data to be * hashed into an array. Once ready, the Final operation is called on all of the @@ -125,7 +134,7 @@ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, ret = wc_CryptoCb_Cmac(cmac, key, keySz, NULL, 0, NULL, NULL, type, unused); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -193,7 +202,7 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, in, inSz, NULL, NULL, 0, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -202,7 +211,7 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) /* Clear CRYPTOCB_UNAVAILABLE return code */ ret = 0; - while (inSz != 0) { + while ((ret == 0) && (inSz != 0)) { word32 add = min(inSz, AES_BLOCK_SIZE - cmac->bufferSz); XMEMCPY(&cmac->buffer[cmac->bufferSz], in, add); @@ -261,7 +270,7 @@ int wc_CmacFinalNoFree(Cmac* cmac, byte* out, word32* outSz) #endif { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -331,7 +340,7 @@ int wc_AesCmacGenerate_ex(Cmac* cmac, ret = wc_CryptoCb_Cmac(cmac, key, keySz, in, inSz, out, outSz, WC_CMAC_AES, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* Clear CRYPTOCB_UNAVAILABLE return code */ @@ -440,10 +449,8 @@ int wc_AesCmacVerify_ex(Cmac* cmac, devId); if (ret == 0) { compareRet = ConstantCompare(check, a, (int)min(checkSz, aSz)); - } - - if (ret == 0) ret = compareRet ? 1 : 0; + } return ret; } diff --git a/src/wolfcrypt/src/coding.c b/src/wolfcrypt/src/coding.c index be5f418..2509948 100644 --- a/src/wolfcrypt/src/coding.c +++ b/src/wolfcrypt/src/coding.c @@ -181,7 +181,7 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) byte e1, e2, e3, e4; if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (ret == BUFFER_E) { + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) { /* Running out of buffer here is not an error */ break; } diff --git a/src/wolfcrypt/src/cryptocb.c b/src/wolfcrypt/src/cryptocb.c index 07b37f1..06b9ebe 100644 --- a/src/wolfcrypt/src/cryptocb.c +++ b/src/wolfcrypt/src/cryptocb.c @@ -260,9 +260,9 @@ static CryptoCb* wc_CryptoCb_FindDeviceByIndex(int startIdx) static WC_INLINE int wc_CryptoCb_TranslateErrorCode(int ret) { - if (ret == NOT_COMPILED_IN) { + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { /* backwards compatibility for older NOT_COMPILED_IN syntax */ - ret = CRYPTOCB_UNAVAILABLE; + ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); } return ret; } @@ -344,8 +344,8 @@ int wc_CryptoCb_RegisterDevice(int devId, CryptoDevCallbackFunc cb, void* ctx) /* Success. Update dev->ctx */ dev->ctx = info.cmd.ctx; } - else if ((rc == CRYPTOCB_UNAVAILABLE) || - (rc == NOT_COMPILED_IN)) { + else if ((rc == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) || + (rc == WC_NO_ERR_TRACE(NOT_COMPILED_IN))) { /* Not implemented. Return success*/ rc = 0; } @@ -391,7 +391,7 @@ void wc_CryptoCb_UnRegisterDevice(int devId) int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -421,7 +421,7 @@ int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, #ifdef WOLFSSL_KEY_GEN int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -449,7 +449,7 @@ int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) int wc_CryptoCb_RsaCheckPrivKey(RsaKey* key, const byte* pubKey, word32 pubKeySz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -474,7 +474,7 @@ int wc_CryptoCb_RsaCheckPrivKey(RsaKey* key, const byte* pubKey, int wc_CryptoCb_RsaGetSize(const RsaKey* key, int* keySize) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -500,7 +500,7 @@ int wc_CryptoCb_RsaGetSize(const RsaKey* key, int* keySize) #ifdef HAVE_ECC int wc_CryptoCb_MakeEccKey(WC_RNG* rng, int keySize, ecc_key* key, int curveId) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -527,7 +527,7 @@ int wc_CryptoCb_MakeEccKey(WC_RNG* rng, int keySize, ecc_key* key, int curveId) int wc_CryptoCb_Ecdh(ecc_key* private_key, ecc_key* public_key, byte* out, word32* outlen) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (private_key == NULL) @@ -554,7 +554,7 @@ int wc_CryptoCb_Ecdh(ecc_key* private_key, ecc_key* public_key, int wc_CryptoCb_EccSign(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -583,7 +583,7 @@ int wc_CryptoCb_EccSign(const byte* in, word32 inlen, byte* out, int wc_CryptoCb_EccVerify(const byte* sig, word32 siglen, const byte* hash, word32 hashlen, int* res, ecc_key* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -612,7 +612,7 @@ int wc_CryptoCb_EccVerify(const byte* sig, word32 siglen, int wc_CryptoCb_EccCheckPrivKey(ecc_key* key, const byte* pubKey, word32 pubKeySz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -640,7 +640,7 @@ int wc_CryptoCb_EccCheckPrivKey(ecc_key* key, const byte* pubKey, int wc_CryptoCb_Curve25519Gen(WC_RNG* rng, int keySize, curve25519_key* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -666,7 +666,7 @@ int wc_CryptoCb_Curve25519Gen(WC_RNG* rng, int keySize, int wc_CryptoCb_Curve25519(curve25519_key* private_key, curve25519_key* public_key, byte* out, word32* outlen, int endian) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (private_key == NULL) @@ -696,7 +696,7 @@ int wc_CryptoCb_Curve25519(curve25519_key* private_key, int wc_CryptoCb_Ed25519Gen(WC_RNG* rng, int keySize, ed25519_key* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -723,7 +723,7 @@ int wc_CryptoCb_Ed25519Sign(const byte* in, word32 inLen, byte* out, word32 *outLen, ed25519_key* key, byte type, const byte* context, byte contextLen) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -755,7 +755,7 @@ int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, const byte* msg, word32 msgLen, int* res, ed25519_key* key, byte type, const byte* context, byte contextLen) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (key == NULL) @@ -785,7 +785,7 @@ int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, } #endif /* HAVE_ED25519 */ -#if defined(HAVE_PQC) && defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_HAVE_KYBER) int wc_CryptoCb_PqcKemGetDevId(int type, void* key) { int devId = INVALID_DEVID; @@ -794,18 +794,16 @@ int wc_CryptoCb_PqcKemGetDevId(int type, void* key) return devId; /* get devId */ -#if defined(WOLFSSL_HAVE_KYBER) if (type == WC_PQC_KEM_TYPE_KYBER) { devId = ((KyberKey*) key)->devId; } -#endif return devId; } int wc_CryptoCb_MakePqcKemKey(WC_RNG* rng, int type, int keySize, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -839,7 +837,7 @@ int wc_CryptoCb_PqcEncapsulate(byte* ciphertext, word32 ciphertextLen, byte* sharedSecret, word32 sharedSecretLen, WC_RNG* rng, int type, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -875,7 +873,7 @@ int wc_CryptoCb_PqcEncapsulate(byte* ciphertext, word32 ciphertextLen, int wc_CryptoCb_PqcDecapsulate(const byte* ciphertext, word32 ciphertextLen, byte* sharedSecret, word32 sharedSecretLen, int type, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -906,9 +904,9 @@ int wc_CryptoCb_PqcDecapsulate(const byte* ciphertext, word32 ciphertextLen, return wc_CryptoCb_TranslateErrorCode(ret); } -#endif /* HAVE_PQC && WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_KYBER */ -#if defined(HAVE_PQC) && (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)) +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) int wc_CryptoCb_PqcSigGetDevId(int type, void* key) { int devId = INVALID_DEVID; @@ -934,7 +932,7 @@ int wc_CryptoCb_PqcSigGetDevId(int type, void* key) int wc_CryptoCb_MakePqcSignatureKey(WC_RNG* rng, int type, int keySize, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -967,7 +965,7 @@ int wc_CryptoCb_MakePqcSignatureKey(WC_RNG* rng, int type, int keySize, int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, int type, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -1003,7 +1001,7 @@ int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, word32 *outlen, int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, const byte* msg, word32 msglen, int* res, int type, void* key) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -1039,7 +1037,7 @@ int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, const byte* msg, int wc_CryptoCb_PqcSignatureCheckPrivKey(void* key, int type, const byte* pubKey, word32 pubKeySz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; CryptoCb* dev; @@ -1068,7 +1066,7 @@ int wc_CryptoCb_PqcSignatureCheckPrivKey(void* key, int type, return wc_CryptoCb_TranslateErrorCode(ret); } -#endif /* HAVE_PQC && (HAVE_FALCON || HAVE_DILITHIUM) */ +#endif /* HAVE_FALCON || HAVE_DILITHIUM */ #ifndef NO_AES #ifdef HAVE_AESGCM @@ -1078,7 +1076,7 @@ int wc_CryptoCb_AesGcmEncrypt(Aes* aes, byte* out, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1119,7 +1117,7 @@ int wc_CryptoCb_AesGcmDecrypt(Aes* aes, byte* out, const byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1162,7 +1160,7 @@ int wc_CryptoCb_AesCcmEncrypt(Aes* aes, byte* out, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1203,7 +1201,7 @@ int wc_CryptoCb_AesCcmDecrypt(Aes* aes, byte* out, const byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1243,7 +1241,7 @@ int wc_CryptoCb_AesCcmDecrypt(Aes* aes, byte* out, int wc_CryptoCb_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1275,7 +1273,7 @@ int wc_CryptoCb_AesCbcEncrypt(Aes* aes, byte* out, int wc_CryptoCb_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1308,7 +1306,7 @@ int wc_CryptoCb_AesCbcDecrypt(Aes* aes, byte* out, int wc_CryptoCb_AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1341,7 +1339,7 @@ int wc_CryptoCb_AesCtrEncrypt(Aes* aes, byte* out, int wc_CryptoCb_AesEcbEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1373,7 +1371,7 @@ int wc_CryptoCb_AesEcbEncrypt(Aes* aes, byte* out, int wc_CryptoCb_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1408,7 +1406,7 @@ int wc_CryptoCb_AesEcbDecrypt(Aes* aes, byte* out, int wc_CryptoCb_Des3Encrypt(Des3* des3, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1440,7 +1438,7 @@ int wc_CryptoCb_Des3Encrypt(Des3* des3, byte* out, int wc_CryptoCb_Des3Decrypt(Des3* des3, byte* out, const byte* in, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1474,7 +1472,7 @@ int wc_CryptoCb_Des3Decrypt(Des3* des3, byte* out, int wc_CryptoCb_ShaHash(wc_Sha* sha, const byte* in, word32 inSz, byte* digest) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1507,7 +1505,7 @@ int wc_CryptoCb_ShaHash(wc_Sha* sha, const byte* in, int wc_CryptoCb_Sha256Hash(wc_Sha256* sha256, const byte* in, word32 inSz, byte* digest) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1540,7 +1538,7 @@ int wc_CryptoCb_Sha256Hash(wc_Sha256* sha256, const byte* in, int wc_CryptoCb_Sha384Hash(wc_Sha384* sha384, const byte* in, word32 inSz, byte* digest) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1576,7 +1574,7 @@ int wc_CryptoCb_Sha384Hash(wc_Sha384* sha384, const byte* in, int wc_CryptoCb_Sha512Hash(wc_Sha512* sha512, const byte* in, word32 inSz, byte* digest) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1608,11 +1606,45 @@ int wc_CryptoCb_Sha512Hash(wc_Sha512* sha512, const byte* in, } #endif /* WOLFSSL_SHA512 */ +#if defined(WOLFSSL_SHA3) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(6, 0)) +int wc_CryptoCb_Sha3Hash(wc_Sha3* sha3, int type, const byte* in, + word32 inSz, byte* digest) +{ + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); + CryptoCb* dev; + + /* locate registered callback */ + if (sha3) { + dev = wc_CryptoCb_FindDevice(sha3->devId, WC_ALGO_TYPE_HASH); + } + else + { + /* locate first callback and try using it */ + dev = wc_CryptoCb_FindDeviceByIndex(0); + } + + if (dev && dev->cb) { + wc_CryptoInfo cryptoInfo; + XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); + cryptoInfo.algo_type = WC_ALGO_TYPE_HASH; + cryptoInfo.hash.type = type; + cryptoInfo.hash.sha3 = sha3; + cryptoInfo.hash.in = in; + cryptoInfo.hash.inSz = inSz; + cryptoInfo.hash.digest = digest; + + ret = dev->cb(dev->devId, &cryptoInfo, dev->ctx); + } + + return wc_CryptoCb_TranslateErrorCode(ret); +} +#endif /* WOLFSSL_SHA3 && (!HAVE_FIPS || FIPS_VERSION_GE(6, 0)) */ + #ifndef NO_HMAC int wc_CryptoCb_Hmac(Hmac* hmac, int macType, const byte* in, word32 inSz, byte* digest) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; if (hmac == NULL) @@ -1640,7 +1672,7 @@ int wc_CryptoCb_Hmac(Hmac* hmac, int macType, const byte* in, word32 inSz, #ifndef WC_NO_RNG int wc_CryptoCb_RandomBlock(WC_RNG* rng, byte* out, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1668,7 +1700,7 @@ int wc_CryptoCb_RandomBlock(WC_RNG* rng, byte* out, word32 sz) int wc_CryptoCb_RandomSeed(OS_Seed* os, byte* seed, word32 sz) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ @@ -1692,7 +1724,7 @@ int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, const byte* in, word32 inSz, byte* out, word32* outSz, int type, void* ctx) { - int ret = CRYPTOCB_UNAVAILABLE; + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; /* locate registered callback */ diff --git a/src/wolfcrypt/src/curve25519.c b/src/wolfcrypt/src/curve25519.c index 2c967dd..4cd29c4 100644 --- a/src/wolfcrypt/src/curve25519.c +++ b/src/wolfcrypt/src/curve25519.c @@ -238,7 +238,7 @@ int wc_curve25519_make_key(WC_RNG* rng, int keysize, curve25519_key* key) #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Curve25519Gen(rng, keysize, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -299,7 +299,7 @@ int wc_curve25519_shared_secret_ex(curve25519_key* private_key, if (private_key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Curve25519(private_key, public_key, out, outlen, endian); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } diff --git a/src/wolfcrypt/src/des3.c b/src/wolfcrypt/src/des3.c index 650c33a..e66a33d 100644 --- a/src/wolfcrypt/src/des3.c +++ b/src/wolfcrypt/src/des3.c @@ -38,8 +38,8 @@ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$i") - #pragma const_seg(".fipsB$i") + #pragma code_seg(".fipsA$d") + #pragma const_seg(".fipsB$d") #endif #endif @@ -1602,7 +1602,7 @@ #ifdef WOLF_CRYPTO_CB if (des->devId != INVALID_DEVID) { int ret = wc_CryptoCb_Des3Encrypt(des, out, in, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1653,7 +1653,7 @@ #ifdef WOLF_CRYPTO_CB if (des->devId != INVALID_DEVID) { int ret = wc_CryptoCb_Des3Decrypt(des, out, in, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } diff --git a/src/wolfcrypt/src/dh.c b/src/wolfcrypt/src/dh.c index 6b68601..28ed197 100644 --- a/src/wolfcrypt/src/dh.c +++ b/src/wolfcrypt/src/dh.c @@ -35,8 +35,8 @@ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$m") - #pragma const_seg(".fipsB$m") + #pragma code_seg(".fipsA$e") + #pragma const_seg(".fipsB$e") #endif #endif @@ -55,6 +55,15 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_dh_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000004 }; + int wolfCrypt_FIPS_DH_sanity(void) + { + return 0; + } +#endif + #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS @@ -2931,6 +2940,14 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) if (ret == 0) { /* modulus size in bytes */ modSz /= WOLFSSL_BIT_SIZE; + + if ((word32)modSz < groupSz) { + WOLFSSL_MSG("DH modSz was too small"); + ret = BAD_FUNC_ARG; + } + } + + if (ret == 0) { bufSz = (word32)modSz - groupSz; /* allocate ram */ diff --git a/src/wolfcrypt/src/dilithium.c b/src/wolfcrypt/src/dilithium.c index f8968c5..f3a6f01 100644 --- a/src/wolfcrypt/src/dilithium.c +++ b/src/wolfcrypt/src/dilithium.c @@ -19,86 +19,6568 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* Based on ed448.c and Reworked for Dilithium by Anthony Hu. */ +/* Based on ed448.c and Reworked for Dilithium by Anthony Hu. + * WolfSSL implementation by Sean Parkinson. + */ + +/* Possible Dilithium/ML-DSA options: + * + * HAVE_DILITHIUM Default: OFF + * Enables the code in this file to be compiled. + * WOLFSSL_WC_DILITHIUM Default: OFF + * Compiles the wolfSSL implementation of dilithium. + * + * WOLFSSL_NO_ML_DSA_44 Default: OFF + * Does not compile in parameter set ML-DSA-44 and any code specific to that + * parameter set. + * WOLFSSL_NO_ML_DSA_65 Default: OFF + * Does not compile in parameter set ML-DSA-65 and any code specific to that + * parameter set. + * WOLFSSL_NO_ML_DSA_87 Default: OFF + * Does not compile in parameter set ML-DSA-87 and any code specific to that + * parameter set. + * + * WOLFSSL_DILITHIUM_NO_LARGE_CODE Default: OFF + * Compiles smaller, fast code with speed trade-off. + * WOLFSSL_DILITHIUM_SMALL Default: OFF + * Compiles to small code size with a speed trade-off. + * WOLFSSL_DILITHIUM_VERIFY_ONLY Default: OFF + * Compiles in only the verification and public key operations. + * WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM Default: OFF + * Compiles verification implementation that uses smaller amounts of memory. + * WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC Default: OFF + * Only works with WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM. + * Don't allocate memory with XMALLOC. Memory is pinned against key. + * WOLFSSL_DILITHIUM_ASSIGN_KEY Default: OFF + * Key data is assigned into Dilithium key rather than copied. + * Life of key data passed in is tightly coupled to life of Dilithium key. + * Cannot be used when make key is enabled. + * WOLFSSL_DILITHIUM_SIGN_SMALL_MEM Default: OFF + * Compiles signature implementation that uses smaller amounts of memory but + * is considerably slower. + * + * WOLFSSL_DILITHIUM_ALIGNMENT Default: 8 + * Use to indicate whether loading and storing of words needs to be aligned. + * Default is to use WOLFSSL_GENERAL_ALIGNMENT - should be 4 on some ARM CPUs. + * Set this value explicitly if specific Dilithium implementation alignment is + * needed. + * + * WOLFSSL_DILITHIUM_NO_ASN1 Default: OFF + * Disables any ASN.1 encoding or decoding code. + * + * WC_DILITHIUM_CACHE_MATRIX_A Default: OFF + * Enable caching of the A matrix on import. + * Less work is required in sign and verify operations. + * WC_DILITHIUM_CACHE_PRIV_VECTORS Default: OFF + * Enable caching of private key vectors on import. + * Enables WC_DILITHIUM_CACHE_MATRIX_A. + * Less work is required in sign operations. + * WC_DILITHIUM_CACHE_PUB_VECTORS Default: OFF + * Enable caching of public key vectors on import. + * Enables WC_DILITHIUM_CACHE_MATRIX_A. + * Less work is required in sign operations. + * + * WOLFSSL_DILITHIUM_SIGN_CHECK_Y Default: OFF + * Check vector y is in required range as an early check on valid vector z. + * Falsely reports invalid in approximately 1-2% of checks. + * All valid reports are true. + * Fast fail gives faster signing times on average. + * DO NOT enable this if implementation must be conformant to FIPS 204. + * WOLFSSL_DILITHIUM_SIGN_CHECK_W0 Default: OFF + * Check vector w0 is in required range as an early check on valid vector r0. + * Falsely reports invalid in approximately 3-5% of checks. + * All valid reports are true. + * Fast fail gives faster signing times on average. + * DO NOT enable this if implementation must be conformant to FIPS 204. + * + * DILITHIUM_MUL_SLOW Default: OFF + * Define when multiplying by Q / 44 is slower than masking. + * Only applies to ML-DSA-44. + * DILITHIUM_MUL_44_SLOW Default: OFF + * Define when multiplying by 44 is slower than by 11. + * Only applies to ML-DSA-44. + * DILITHIUM_MUL_11_SLOW Default: OFF + * Define when multiplying by 11 is slower than adding and shifting. + * Only applies to ML-DSA-44. + * DILITHIUM_MUL_QINV_SLOW Default: OFF + * Define when multiplying by QINV 0x3802001 is slower than add, subtract and + * shift equivalent. + * DILITHIUM_MUL_Q_SLOW Default: OFF + * Define when multiplying by Q 0x7fe001 is slower than add, subtract and + * shift equivalent. + */ + + +#ifdef HAVE_CONFIG_H + #include +#endif + +/* in case user set HAVE_PQC there */ +#include + +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 +#include +#endif + +#if defined(HAVE_DILITHIUM) + +#ifdef HAVE_LIBOQS +#include +#endif + +#include +#include +#include +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#ifdef WOLFSSL_WC_DILITHIUM + +#ifdef DEBUG_DILITHIUM +void print_polys(const char* name, const sword32* a, int d1, int d2); +void print_polys(const char* name, const sword32* a, int d1, int d2) +{ + int i; + int j; + int k; + + fprintf(stderr, "%s\n", name); + for (i = 0; i < d1; i++) { + for (j = 0; j < d2; j++) { + for (k = 0; k < 256; k++) { + fprintf(stderr, "%9d,", a[(i*d2*256) + (j*256) + k]); + if ((k % 8) == 7) fprintf(stderr, "\n"); + } + fprintf(stderr, "\n"); + } + } +} + +void print_data(const char* name, const byte* d, int len); +void print_data(const char* name, const byte* d, int len) +{ + int i; + + fprintf(stderr, "%s\n", name); + for (i = 0; i < len; i++) { + fprintf(stderr, "0x%02x,", d[i]); + if ((i % 16) == 15) fprintf(stderr, "\n"); + } + fprintf(stderr, "\n"); +} +#endif + +#if defined(WOLFSSL_NO_ML_DSA_44) && defined(WOLFSSL_NO_ML_DSA_65) && \ + defined(WOLFSSL_NO_ML_DSA_87) + #error "No Dilithium parameters chosen" +#endif + +#if defined(WOLFSSL_DILITHIUM_ASSIGN_KEY) && \ + !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) + #error "Cannot use assign key when making keys" +#endif + + +/* Number of bytes from first block to use for sign. */ +#define DILITHIUM_SIGN_BYTES 8 + + +/* Length of seed in bytes when generating y. */ +#define DILITHIUM_Y_SEED_SZ (DILITHIUM_PRIV_RAND_SEED_SZ + 2) + + +/* Length of seed in bytes used in generating matrix a. */ +#define DILITHIUM_GEN_A_SEED_SZ (DILITHIUM_PUB_SEED_SZ + 2) +/* Length of seed in bytes used in generating vectors s1 and s2. */ +#define DILITHIUM_GEN_S_SEED_SZ (DILITHIUM_PRIV_SEED_SZ + 2) + + +/* MAX: (256 * 8 / (17 + 1)) = 576, or ((256 * 8 / (19 + 1)) = 640 + * but need blocks of 17 * 8 bytes: 5 * 17 * 8 = 680 */ +#define DILITHIUM_MAX_V_BLOCKS 5 +/* Maximum number of bytes to generate into v to make y. */ +#define DILITHIUM_MAX_V (DILITHIUM_MAX_V_BLOCKS * 8 * 17) + + +/* 2 blocks, each block 136 bytes = 272 bytes. + * ETA 2: Min req is 128 but reject rate is 2 in 16 so we need 146.3 on average. + * ETA 4: Min req is 128 but reject rate is 7 in 16 so we need 227.6 on average. + */ +#define DILITHIUM_GEN_S_NBLOCKS 2 +/* Number of bytes to generate with SHAKE-256 when generating s1 and s2. */ +#define DILITHIUM_GEN_S_BYTES \ + (DILITHIUM_GEN_S_NBLOCKS * WC_SHA3_256_COUNT * 8) +/* Number of bytes to a block of SHAKE-256 when generating s1 and s2. */ +#define DILITHIUM_GEN_S_BLOCK_BYTES (WC_SHA3_256_COUNT * 8) + + +/* The ML-DSA parameters sets. */ +static const wc_dilithium_params dilithium_params[] = { +#ifndef WOLFSSL_NO_ML_DSA_44 + { WC_ML_DSA_44, PARAMS_ML_DSA_44_K, PARAMS_ML_DSA_44_L, + PARAMS_ML_DSA_44_ETA, PARAMS_ML_DSA_44_ETA_BITS, + PARAMS_ML_DSA_44_TAU, PARAMS_ML_DSA_44_BETA, PARAMS_ML_DSA_44_OMEGA, + PARAMS_ML_DSA_44_LAMBDA, + PARAMS_ML_DSA_44_GAMMA1_BITS, PARAMS_ML_DSA_44_GAMMA2, + PARAMS_ML_DSA_44_W1_ENC_SZ, PARAMS_ML_DSA_44_A_SIZE, + PARAMS_ML_DSA_44_S1_SIZE, PARAMS_ML_DSA_44_S1_ENC_SIZE, + PARAMS_ML_DSA_44_S2_SIZE, PARAMS_ML_DSA_44_S2_ENC_SIZE, + PARAMS_ML_DSA_44_Z_ENC_SIZE, + PARAMS_ML_DSA_44_PK_SIZE, PARAMS_ML_DSA_44_SIG_SIZE }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + { WC_ML_DSA_65, PARAMS_ML_DSA_65_K, PARAMS_ML_DSA_65_L, + PARAMS_ML_DSA_65_ETA, PARAMS_ML_DSA_65_ETA_BITS, + PARAMS_ML_DSA_65_TAU, PARAMS_ML_DSA_65_BETA, PARAMS_ML_DSA_65_OMEGA, + PARAMS_ML_DSA_65_LAMBDA, + PARAMS_ML_DSA_65_GAMMA1_BITS, PARAMS_ML_DSA_65_GAMMA2, + PARAMS_ML_DSA_65_W1_ENC_SZ, PARAMS_ML_DSA_65_A_SIZE, + PARAMS_ML_DSA_65_S1_SIZE, PARAMS_ML_DSA_65_S1_ENC_SIZE, + PARAMS_ML_DSA_65_S2_SIZE, PARAMS_ML_DSA_65_S2_ENC_SIZE, + PARAMS_ML_DSA_65_Z_ENC_SIZE, + PARAMS_ML_DSA_65_PK_SIZE, PARAMS_ML_DSA_65_SIG_SIZE }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + { WC_ML_DSA_87, PARAMS_ML_DSA_87_K, PARAMS_ML_DSA_87_L, + PARAMS_ML_DSA_87_ETA, PARAMS_ML_DSA_87_ETA_BITS, + PARAMS_ML_DSA_87_TAU, PARAMS_ML_DSA_87_BETA, PARAMS_ML_DSA_87_OMEGA, + PARAMS_ML_DSA_87_LAMBDA, + PARAMS_ML_DSA_87_GAMMA1_BITS, PARAMS_ML_DSA_87_GAMMA2, + PARAMS_ML_DSA_87_W1_ENC_SZ, PARAMS_ML_DSA_87_A_SIZE, + PARAMS_ML_DSA_87_S1_SIZE, PARAMS_ML_DSA_87_S1_ENC_SIZE, + PARAMS_ML_DSA_87_S2_SIZE, PARAMS_ML_DSA_87_S2_ENC_SIZE, + PARAMS_ML_DSA_87_Z_ENC_SIZE, + PARAMS_ML_DSA_87_PK_SIZE, PARAMS_ML_DSA_87_SIG_SIZE }, +#endif +}; +/* Number of ML-DSA parameter sets compiled in. */ +#define DILITHIUM_PARAMS_CNT \ + ((unsigned int)(sizeof(dilithium_params) / sizeof(wc_dilithium_params))) + +/* Get the ML-DSA parameters that match the level. + * + * @param [in] level Level required. + * @param [out] params Parameter set. + * @return 0 on success. + * @return NOT_COMPILED_IN when parameters at level are not compiled in. + */ +static int dilithium_get_params(int level, const wc_dilithium_params** params) +{ + unsigned int i; + int ret = NOT_COMPILED_IN; + + for (i = 0; i < DILITHIUM_PARAMS_CNT; i++) { + if (dilithium_params[i].level == level) { + *params = &dilithium_params[i]; + ret = 0; + } + } + + return ret; +} + +/****************************************************************************** + * Hash operations + ******************************************************************************/ + +/* 256-bit hash using SHAKE-256. + * + * FIPS 204. 8.3: H(v,d) <- SHAKE256(v,d) + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] data Buffer holding data to hash. + * @param [in] dataLen Length of data to hash in bytes. + * @param [out] hash Buffer to hold hash result. + * @param [in] hashLen Number of bytes of hash to return. + * @return 0 on success. + * @return Negative on error. + */ +static int dilithium_shake256(wc_Shake* shake256, const byte* data, + word32 dataLen, byte* hash, word32 hashLen) +{ + int ret; + + /* Initialize SHAKE-256 operation. */ + ret = wc_InitShake256(shake256, NULL, INVALID_DEVID); + if (ret == 0) { + /* Update with data. */ + ret = wc_Shake256_Update(shake256, data, dataLen); + } + if (ret == 0) { + /* Compute hash of data. */ + ret = wc_Shake256_Final(shake256, hash, hashLen); + } + + return ret; +} + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* 256-bit hash using SHAKE-256. + * + * FIPS 204. 8.3: H(v,d) <- SHAKE256(v,d) + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] data1 First block of data to hash. + * @param [in] data1Len Length of first block in bytes. + * @param [in] data2 Second block of data to hash. + * @param [in] data2Len Length of second block in bytes. + * @param [out] hash Buffer to hold hash result. + * @param [in] hashLen Number of bytes of hash to return. + * @return 0 on success. + * @return Negative on error. + */ +static int dilithium_hash256(wc_Shake* shake256, const byte* data1, + word32 data1Len, const byte* data2, word32 data2Len, byte* hash, + word32 hashLen) +{ + int ret; + + /* Initialize SHAKE-256 operation. */ + ret = wc_InitShake256(shake256, NULL, INVALID_DEVID); + if (ret == 0) { + /* Update with first data. */ + ret = wc_Shake256_Update(shake256, data1, data1Len); + } + if (ret == 0) { + /* Update with second data. */ + ret = wc_Shake256_Update(shake256, data2, data2Len); + } + if (ret == 0) { + /* Compute hash of data. */ + ret = wc_Shake256_Final(shake256, hash, hashLen); + } + + return ret; +} +#endif + +#ifndef WOLFSSL_DILITHIUM_SMALL +/* 128-bit hash using SHAKE-128. + * + * FIPS 204. 8.3: H128(v,d) <- SHAKE128(v,d) + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] in Block of data to hash. + * @param [in] inLen Length of data in bytes. + * @param [out] out Buffer to hold hash result. + * @param [in] outLen Number of hash blocks to return. + * @return 0 on success. + * @return Negative on error. + */ +static int dilithium_squeeze128(wc_Shake* shake128, const byte* in, + word32 inLen, byte* out, word32 outBlocks) +{ + int ret; + + /* Initialize SHAKE-128 operation. */ + ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); + if (ret == 0) { + /* Absorb data - update plus final. */ + ret = wc_Shake128_Absorb(shake128, in, inLen); + } + if (ret == 0) { + /* Squeeze out hash data. */ + ret = wc_Shake128_SqueezeBlocks(shake128, out, outBlocks); + } + + return ret; +} +#endif /* WOLFSSL_DILITHIUM_SMALL */ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || \ + (!defined(WOLFSSL_DILITHIUM_SMALL) && \ + !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY)) +/* 256-bit hash using SHAKE-256. + * + * FIPS 204. 8.3: H(v,d) <- SHAKE256(v,d) + * Using SqueezeBlocks interface to get larger amounts of output. + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] in Block of data to hash. + * @param [in] inLen Length of data in bytes. + * @param [out] out Buffer to hold hash result. + * @param [in] outLen Number of hash blocks to return. + * @return 0 on success. + * @return Negative on hash error. + */ +static int dilithium_squeeze256(wc_Shake* shake256, const byte* in, + word32 inLen, byte* out, word32 outBlocks) +{ + int ret; + + /* Initialize SHAKE-256 operation. */ + ret = wc_InitShake256(shake256, NULL, INVALID_DEVID); + if (ret == 0) { + /* Absorb data - update plus final. */ + ret = wc_Shake256_Absorb(shake256, in, inLen); + } + if (ret == 0) { + /* Squeeze out hash data. */ + ret = wc_Shake256_SqueezeBlocks(shake256, out, outBlocks); + } + + return ret; +} +#endif + +/****************************************************************************** + * Encode/Decode operations + ******************************************************************************/ + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY +/* Encode vector of polynomials with range -ETA..ETA. + * + * FIPS 204. 8.2: Algorithm 18 skEncode(rho, K, tr, s1, s2, t0) + * ... + * 2: for i from 0 to l - 1 do + * 3: sk <- sk || BitPack(s1[i], eta, eta) + * 4: end for + * ... + * OR + * ... + * 5: for i from 0 to k - 1 do + * 6: sk <- sk || BitPack(s2[i], eta, eta) + * 7: end for + * ... + * + * FIPS 204. 8.2: Algorithm 11 BitPack(w, a, b) + * 1: z <- () + * 2: for i from 0 to 255 do + * 3: z <- z||IntegerToBits(b - wi, bitlen(a + b)) + * 4: end for + * 5: return BitsToBytes(z) + * + * IntegerToBits makes bit array with width specified from integer. + * BitToBytes make a byte array from a bit array. + * + * @param [in] s Vector of polynomials to encode. + * @param [in] d Dimension of vector. + * @param [in] eta Range specifier of each value. + * @param [out] p Buffer to encode into. + */ +static void dilthium_vec_encode_eta_bits(const sword32* s, byte d, byte eta, + byte* p) +{ + unsigned int i; + unsigned int j; + +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_87) + /* -2..2 */ + if (eta == DILITHIUM_ETA_2) { + /* Setp 2 or 5: For each polynomial of vector. */ + for (i = 0; i < d; i++) { + /* Step 3 or 6. + * 3 bits to encode each number. + * 8 numbers become 3 bytes. (8 * 3 bits = 3 * 8 bits) */ + for (j = 0; j < DILITHIUM_N; j += 8) { + /* Make value a positive integer. */ + byte s0 = 2 - s[j + 0]; + byte s1 = 2 - s[j + 1]; + byte s2 = 2 - s[j + 2]; + byte s3 = 2 - s[j + 3]; + byte s4 = 2 - s[j + 4]; + byte s5 = 2 - s[j + 5]; + byte s6 = 2 - s[j + 6]; + byte s7 = 2 - s[j + 7]; + + /* Pack 8 3-bit values into 3 bytes. */ + p[0] = (s0 >> 0) | (s1 << 3) | (s2 << 6); + p[1] = (s2 >> 2) | (s3 << 1) | (s4 << 4) | (s5 << 7); + p[2] = (s5 >> 1) | (s6 << 2) | (s7 << 5); + /* Move to next place to encode into. */ + p += DILITHIUM_ETA_2_BITS; + } + /* Next polynomial. */ + s += DILITHIUM_N; + } + } + else +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + /* -4..4 */ + if (eta == DILITHIUM_ETA_4) { + for (i = 0; i < d; i++) { + #ifdef WOLFSSL_DILITHIUM_SMALL + /* Step 3 or 6. + * 4 bits to encode each number. + * 2 numbers become 1 bytes. (2 * 4 bits = 1 * 8 bits) */ + for (j = 0; j < DILITHIUM_N / 2; j++) { + /* Make values positive and pack 2 4-bit values into 1 byte. */ + p[j] = (((byte)(4 - s[j * 2 + 0])) << 0) | + (((byte)(4 - s[j * 2 + 1])) << 4); + } + #else + /* Step 3 or 6. + * 4 bits to encode each number. + * 8 numbers become 4 bytes. (8 * 4 bits = 4 * 8 bits) */ + for (j = 0; j < DILITHIUM_N / 2; j += 4) { + /* Make values positive and pack 2 4-bit values into 1 byte. */ + p[j + 0] = (((byte)(4 - s[j * 2 + 0])) << 0) | + (((byte)(4 - s[j * 2 + 1])) << 4); + p[j + 1] = (((byte)(4 - s[j * 2 + 2])) << 0) | + (((byte)(4 - s[j * 2 + 3])) << 4); + p[j + 2] = (((byte)(4 - s[j * 2 + 4])) << 0) | + (((byte)(4 - s[j * 2 + 5])) << 4); + p[j + 3] = (((byte)(4 - s[j * 2 + 6])) << 0) | + (((byte)(4 - s[j * 2 + 7])) << 4); + } + #endif + /* Move to next place to encode into. */ + p += DILITHIUM_N / 2; + /* Next polynomial. */ + s += DILITHIUM_N; + } + } + else +#endif + { + } +} +#endif /* !WOLFSSL_DILITHIUM_NO_MAKE_KEY */ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || defined(WOLFSSL_DILITHIUM_CHECK_KEY) + +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Decode polynomial with range -2..2. + * + * FIPS 204. 8.2: Algorithm 19 skDecode(sk) + * ... + * 5: for i from 0 to l - 1 do + * 6: s1[i] <- BitUnpack(yi, eta, eta) + * 7: end for + * ... + * OR + * ... + * 8: for i from 0 to k - 1 do + * 9: s2[i] <- BitUnpack(zi, eta, eta) + * 10: end for + * ... + * Where y and z are arrays of bit arrays. + * + * @param [in] p Buffer of data to decode. + * @param [in] s Vector of decoded polynomials. + */ +static void dilithium_decode_eta_2_bits(const byte* p, sword32* s) +{ + unsigned int j; + + /* Step 6 or 9. + * 3 bits to encode each number. + * 8 numbers from 3 bytes. (8 * 3 bits = 3 * 8 bits) */ + for (j = 0; j < DILITHIUM_N; j += 8) { + /* Get 3 bits and put in range of -2..2. */ + s[j + 0] = 2 - ((p[0] >> 0) & 0x7 ); + s[j + 1] = 2 - ((p[0] >> 3) & 0x7 ); + s[j + 2] = 2 - ((p[0] >> 6) | ((p[1] << 2) & 0x7)); + s[j + 3] = 2 - ((p[1] >> 1) & 0x7 ); + s[j + 4] = 2 - ((p[1] >> 4) & 0x7 ); + s[j + 5] = 2 - ((p[1] >> 7) | ((p[2] << 1) & 0x7)); + s[j + 6] = 2 - ((p[2] >> 2) & 0x7 ); + s[j + 7] = 2 - ((p[2] >> 5) & 0x7 ); + /* Move to next place to decode from. */ + p += DILITHIUM_ETA_2_BITS; + } +} +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 +/* Decode polynomial with range -4..4. + * + * FIPS 204. 8.2: Algorithm 19 skDecode(sk) + * ... + * 5: for i from 0 to l - 1 do + * 6: s1[i] <- BitUnpack(yi, eta, eta) + * 7: end for + * ... + * OR + * ... + * 8: for i from 0 to k - 1 do + * 9: s2[i] <- BitUnpack(zi, eta, eta) + * 10: end for + * ... + * Where y and z are arrays of bit arrays. + * + * @param [in] p Buffer of data to decode. + * @param [in] s Vector of decoded polynomials. + */ +static void dilithium_decode_eta_4_bits(const byte* p, sword32* s) +{ + unsigned int j; + +#ifdef WOLFSSL_DILITHIUM_SMALL + /* Step 6 or 9. + * 4 bits to encode each number. + * 2 numbers from 1 bytes. (2 * 4 bits = 1 * 8 bits) */ + for (j = 0; j < DILITHIUM_N / 2; j++) { + /* Get 4 bits and put in range of -4..4. */ + s[j * 2 + 0] = 4 - (p[j] & 0xf); + s[j * 2 + 1] = 4 - (p[j] >> 4); + } +#else + /* Step 6 or 9. + * 4 bits to encode each number. + * 8 numbers from 4 bytes. (8 * 4 bits = 4 * 8 bits) */ + for (j = 0; j < DILITHIUM_N / 2; j += 4) { + /* Get 4 bits and put in range of -4..4. */ + s[j * 2 + 0] = 4 - (p[j + 0] & 0xf); + s[j * 2 + 1] = 4 - (p[j + 0] >> 4); + s[j * 2 + 2] = 4 - (p[j + 1] & 0xf); + s[j * 2 + 3] = 4 - (p[j + 1] >> 4); + s[j * 2 + 4] = 4 - (p[j + 2] & 0xf); + s[j * 2 + 5] = 4 - (p[j + 2] >> 4); + s[j * 2 + 6] = 4 - (p[j + 3] & 0xf); + s[j * 2 + 7] = 4 - (p[j + 3] >> 4); + } +#endif /* WOLFSSL_DILITHIUM_SMALL */ +} +#endif + +#if defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + (defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) || \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM))) +/* Decode vector of polynomials with range -ETA..ETA. + * + * FIPS 204. 8.2: Algorithm 19 skDecode(sk) + * ... + * 5: for i from 0 to l - 1 do + * 6: s1[i] <- BitUnpack(yi, eta, eta) + * 7: end for + * ... + * OR + * ... + * 8: for i from 0 to k - 1 do + * 9: s2[i] <- BitUnpack(zi, eta, eta) + * 10: end for + * ... + * Where y and z are arrays of bit arrays. + * + * @param [in] p Buffer of data to decode. + * @param [in] eta Range specifier of each value. + * @param [in] s Vector of decoded polynomials. + * @param [in] d Dimension of vector. + */ +static void dilithium_vec_decode_eta_bits(const byte* p, byte eta, sword32* s, + byte d) +{ + unsigned int i; + +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_87) + /* -2..2 */ + if (eta == DILITHIUM_ETA_2) { + /* Step 5 or 8: For each polynomial of vector */ + for (i = 0; i < d; i++) { + dilithium_decode_eta_2_bits(p, s); + /* Move to next place to decode from. */ + p += DILITHIUM_ETA_2_BITS * DILITHIUM_N / 8; + /* Next polynomial. */ + s += DILITHIUM_N; + } + } + else +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + /* -4..4 */ + if (eta == DILITHIUM_ETA_4) { + /* Step 5 or 8: For each polynomial of vector */ + for (i = 0; i < d; i++) { + dilithium_decode_eta_4_bits(p, s); + /* Move to next place to decode from. */ + p += DILITHIUM_N / 2; + /* Next polynomial. */ + s += DILITHIUM_N; + } + } + else +#endif + { + } +} +#endif +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN || WOLFSSL_DILITHIUM_CHECK_KEY */ + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY +/* Encode t into t0 and t1. + * + * FIPS 204. 8.4: Algorithm 29 Power2Round(r) + * 1: r+ <- r mod q + * 2: r0 <- r+ mod +/- 2^d + * 3: return ((r+ - r0) / 2^d, r0) + * + * FIPS 204. 8.2: Algorithm 18 skEncode(rho, K, tr, s1, s2, t0) + * ... + * 8: for i form 0 to k - 1 do + * 9: sk <- sk || BitPack(t0[i], s^(d-1) - 1, 2^(d-1)) + * 10: end for + * + * FIPS 204. 8.2: Algorithm 16 pkEncode(rho, t1) + * ... + * 2: for i from 0 to k - 1 do + * 3: pk <- pk || SimpleBitPack(t1[i], 2^bitlen(q-1) - d - 1) + * 4: end for + * + * @param [in] t Vector of polynomials. + * @param [in] d Dimension of vector. + * @param [out] t0 Buffer to encode bottom part of value of t into. + * @param [out] t1 Buffer to encode top part of value of t into. + */ +static void dilithium_vec_encode_t0_t1(sword32* t, byte d, byte* t0, byte* t1) +{ + unsigned int i; + unsigned int j; + + /* Alg 18, Step 8 and Alg 16, Step 2. For each polynomial of vector. */ + for (i = 0; i < d; i++) { + /* Alg 18, Step 9 and Alg 16, Step 3. + * Do all polynomial values - 8 at a time. */ + for (j = 0; j < DILITHIUM_N; j += 8) { + /* Take 8 values of t and take top bits and make positive. */ + word16 n1_0 = (t[j + 0] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_1 = (t[j + 1] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_2 = (t[j + 2] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_3 = (t[j + 3] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_4 = (t[j + 4] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_5 = (t[j + 5] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_6 = (t[j + 6] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_7 = (t[j + 7] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + /* Take 8 values of t and take bottom bits and make positive. */ + word16 n0_0 = DILITHIUM_D_MAX_HALF - + (t[j + 0] - (n1_0 << DILITHIUM_D)); + word16 n0_1 = DILITHIUM_D_MAX_HALF - + (t[j + 1] - (n1_1 << DILITHIUM_D)); + word16 n0_2 = DILITHIUM_D_MAX_HALF - + (t[j + 2] - (n1_2 << DILITHIUM_D)); + word16 n0_3 = DILITHIUM_D_MAX_HALF - + (t[j + 3] - (n1_3 << DILITHIUM_D)); + word16 n0_4 = DILITHIUM_D_MAX_HALF - + (t[j + 4] - (n1_4 << DILITHIUM_D)); + word16 n0_5 = DILITHIUM_D_MAX_HALF - + (t[j + 5] - (n1_5 << DILITHIUM_D)); + word16 n0_6 = DILITHIUM_D_MAX_HALF - + (t[j + 6] - (n1_6 << DILITHIUM_D)); + word16 n0_7 = DILITHIUM_D_MAX_HALF - + (t[j + 7] - (n1_7 << DILITHIUM_D)); + + /* 13 bits per number. + * 8 numbers become 13 bytes. (8 * 13 bits = 13 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 2) + word32* tp; + #endif + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + tp = (word32*)t0; + tp[0] = (n0_0 ) | ((word32)n0_1 << 13) | ((word32)n0_2 << 26); + tp[1] = (n0_2 >> 6) | ((word32)n0_3 << 7) | ((word32)n0_4 << 20); + tp[2] = (n0_4 >> 12) | ((word32)n0_5 << 1) | + ((word32)n0_6 << 14) | ((word32)n0_7 << 27); + #else + t0[ 0] = (n0_0 << 0); + t0[ 1] = (n0_0 >> 8) | (n0_1 << 5); + t0[ 2] = (n0_1 >> 3) ; + t0[ 3] = (n0_1 >> 11) | (n0_2 << 2); + t0[ 4] = (n0_2 >> 6) | (n0_3 << 7); + t0[ 5] = (n0_3 >> 1) ; + t0[ 6] = (n0_3 >> 9) | (n0_4 << 4); + t0[ 7] = (n0_4 >> 4) ; + t0[ 8] = (n0_4 >> 12) | (n0_5 << 1); + t0[ 9] = (n0_5 >> 7) | (n0_6 << 6); + t0[10] = (n0_6 >> 2) ; + t0[11] = (n0_6 >> 10) | (n0_7 << 3); + #endif + t0[12] = (n0_7 >> 5) ; + + /* 10 bits per number. + * 8 bytes become 10 bytes. (8 * 10 bits = 10 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 2) + tp = (word32*)t1; + tp[0] = (n1_0 ) | ((word32)n1_1 << 10) | + ((word32)n1_2 << 20) | ((word32)n1_3 << 30); + tp[1] = (n1_3 >> 2) | ((word32)n1_4 << 8) | + ((word32)n1_5 << 18) | ((word32)n1_6 << 28); + #else + t1[0] = (n1_0 << 0); + t1[1] = (n1_0 >> 8) | (n1_1 << 2); + t1[2] = (n1_1 >> 6) | (n1_2 << 4); + t1[3] = (n1_2 >> 4) | (n1_3 << 6); + t1[4] = (n1_3 >> 2) ; + t1[5] = (n1_4 << 0); + t1[6] = (n1_4 >> 8) | (n1_5 << 2); + t1[7] = (n1_5 >> 6) | (n1_6 << 4); + #endif + t1[8] = (n1_6 >> 4) | (n1_7 << 6); + t1[9] = (n1_7 >> 2) ; + + /* Move to next place to encode bottom bits to. */ + t0 += DILITHIUM_D; + /* Move to next place to encode top bits to. */ + t1 += DILITHIUM_U; + } + /* Next polynomial. */ + t += DILITHIUM_N; + } +} +#endif /* !WOLFSSL_DILITHIUM_NO_MAKE_KEY */ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || defined(WOLFSSL_DILITHIUM_CHECK_KEY) +/* Decode bottom D bits of t as t0. + * + * FIPS 204. 8.2: Algorithm 19 skDecode(sk) + * ... + * 12: t0[i] <- BitUnpack(wi, 2^(d-1) - 1, 2^(d-1) + * ... + * + * @param [in] t0 Encoded values of t0. + * @param [in] d Dimensions of vector t0. + * @param [out] t Vector of polynomials. + */ +static void dilithium_decode_t0(const byte* t0, sword32* t) +{ + unsigned int j; + + /* Step 12. Get 13 bits and convert to range (2^(d-1)-1)..2^(d-1). */ + for (j = 0; j < DILITHIUM_N; j += 8) { + /* 13 bits used per number. + * 8 numbers from 13 bytes. (8 * 13 bits = 13 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + word32 t32_2 = ((const word32*)t0)[2]; + #ifdef WC_64BIT_CPU + word64 t64 = *(const word64*)t0; + t[j + 0] = DILITHIUM_D_MAX_HALF - ( t64 & 0x1fff); + t[j + 1] = DILITHIUM_D_MAX_HALF - ((t64 >> 13) & 0x1fff); + t[j + 2] = DILITHIUM_D_MAX_HALF - ((t64 >> 26) & 0x1fff); + t[j + 3] = DILITHIUM_D_MAX_HALF - ((t64 >> 39) & 0x1fff); + t[j + 4] = DILITHIUM_D_MAX_HALF - + ((t64 >> 52) | ((t32_2 & 0x0001) << 12)); + #else + word32 t32_0 = ((const word32*)t0)[0]; + word32 t32_1 = ((const word32*)t0)[1]; + t[j + 0] = DILITHIUM_D_MAX_HALF - + ( t32_0 & 0x1fff); + t[j + 1] = DILITHIUM_D_MAX_HALF - + ((t32_0 >> 13) & 0x1fff); + t[j + 2] = DILITHIUM_D_MAX_HALF - + (( t32_0 >> 26 ) | ((t32_1 & 0x007f) << 6)); + t[j + 3] = DILITHIUM_D_MAX_HALF - + ((t32_1 >> 7) & 0x1fff); + t[j + 4] = DILITHIUM_D_MAX_HALF - + (( t32_1 >> 20 ) | ((t32_2 & 0x0001) << 12)); + #endif + t[j + 5] = DILITHIUM_D_MAX_HALF - + ((t32_2 >> 1) & 0x1fff); + t[j + 6] = DILITHIUM_D_MAX_HALF - + ((t32_2 >> 14) & 0x1fff); + t[j + 7] = DILITHIUM_D_MAX_HALF - + (( t32_2 >> 27 ) | ((word32)t0[12] ) << 5 ); +#else + t[j + 0] = DILITHIUM_D_MAX_HALF - + ((t0[ 0] ) | (((word16)(t0[ 1] & 0x1f)) << 8)); + t[j + 1] = DILITHIUM_D_MAX_HALF - + ((t0[ 1] >> 5) | (((word16)(t0[ 2] )) << 3) | + (((word16)(t0[ 3] & 0x03)) << 11)); + t[j + 2] = DILITHIUM_D_MAX_HALF - + ((t0[ 3] >> 2) | (((word16)(t0[ 4] & 0x7f)) << 6)); + t[j + 3] = DILITHIUM_D_MAX_HALF - + ((t0[ 4] >> 7) | (((word16)(t0[ 5] )) << 1) | + (((word16)(t0[ 6] & 0x0f)) << 9)); + t[j + 4] = DILITHIUM_D_MAX_HALF - + ((t0[ 6] >> 4) | (((word16)(t0[ 7] )) << 4) | + (((word16)(t0[ 8] & 0x01)) << 12)); + t[j + 5] = DILITHIUM_D_MAX_HALF - + ((t0[ 8] >> 1) | (((word16)(t0[ 9] & 0x3f)) << 7)); + t[j + 6] = DILITHIUM_D_MAX_HALF - + ((t0[ 9] >> 6) | (((word16)(t0[10] )) << 2) | + (((word16)(t0[11] & 0x07)) << 10)); + t[j + 7] = DILITHIUM_D_MAX_HALF - + ((t0[11] >> 3) | (((word16)(t0[12] )) << 5)); +#endif + /* Move to next place to decode from. */ + t0 += DILITHIUM_D; + } +} + +#if defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + (defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) || \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM))) +/* Decode bottom D bits of t as t0. + * + * FIPS 204. 8.2: Algorithm 19 skDecode(sk) + * ... + * 11: for i from 0 to k - 1 do + * 12: t0[i] <- BitUnpack(wi, 2^(d-1) - 1, 2^(d-1) + * 13: end for + * ... + * + * @param [in] t0 Encoded values of t0. + * @param [in] d Dimensions of vector t0. + * @param [out] t Vector of polynomials. + */ +static void dilithium_vec_decode_t0(const byte* t0, byte d, sword32* t) +{ + unsigned int i; + + /* Step 11. For each polynomial of vector. */ + for (i = 0; i < d; i++) { + dilithium_decode_t0(t0, t); + t0 += DILITHIUM_D * DILITHIUM_N / 8; + /* Next polynomial. */ + t += DILITHIUM_N; + } +} +#endif +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN || WOLFSSL_DILITHIUM_CHECK_KEY */ + +#if !defined(WOLFSSL_DILITHIUM_NO_VERIFY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) +/* Decode top bits of t as t1. + * + * FIPS 204. 8.2: Algorithm 17 pkDecode(pk) + * ... + * 4: t1[i] <- SimpleBitUnpack(zi, 2^(bitlen(q-1)-d) - 1) + * ... + * + * @param [in] t1 Encoded values of t1. + * @param [out] t Polynomials. + */ +static void dilithium_decode_t1(const byte* t1, sword32* t) +{ + unsigned int j; + /* Step 4. Get 10 bits as a number. */ + for (j = 0; j < DILITHIUM_N; j += 8) { + /* 10 bits used per number. + * 8 numbers from 10 bytes. (8 * 10 bits = 10 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + #ifdef WC_64BIT_CPU + word64 t64 = *(const word64*) t1; + word16 t16 = *(const word16*)(t1 + 8); + t[j+0] = (sword32)( ( t64 & 0x03ff) << DILITHIUM_D); + t[j+1] = (sword32)( ((t64 >> 10) & 0x03ff) << DILITHIUM_D); + t[j+2] = (sword32)( ((t64 >> 20) & 0x03ff) << DILITHIUM_D); + t[j+3] = (sword32)( ((t64 >> 30) & 0x03ff) << DILITHIUM_D); + t[j+4] = (sword32)( ((t64 >> 40) & 0x03ff) << DILITHIUM_D); + t[j+5] = (sword32)( ((t64 >> 50) & 0x03ff) << DILITHIUM_D); + t[j+6] = (sword32)((((t64 >> 60)| (t16 << 4)) & 0x03ff) << DILITHIUM_D); + t[j+7] = (sword32)( ((t16 >> 6) & 0x03ff) << DILITHIUM_D); + #else + word32 t32 = *((const word32*)t1); + t[j + 0] = ( t32 & 0x03ff ) << + DILITHIUM_D; + t[j + 1] = ((t32 >> 10) & 0x03ff ) << + DILITHIUM_D; + t[j + 2] = ((t32 >> 20) & 0x03ff ) << + DILITHIUM_D; + t[j + 3] = ((t32 >> 30) | (((word16)t1[4]) << 2)) << + DILITHIUM_D; + t32 = *((const word32*)(t1 + 5)); + t[j + 4] = ( t32 & 0x03ff ) << + DILITHIUM_D; + t[j + 5] = ((t32 >> 10) & 0x03ff ) << + DILITHIUM_D; + t[j + 6] = ((t32 >> 20) & 0x03ff ) << + DILITHIUM_D; + t[j + 7] = ((t32 >> 30) | (((word16)t1[9]) << 2)) << + DILITHIUM_D; + #endif +#else + t[j + 0] = (sword32)((t1[0] >> 0) | (((word16)(t1[1] & 0x03)) << 8)) + << DILITHIUM_D; + t[j + 1] = (sword32)((t1[1] >> 2) | (((word16)(t1[2] & 0x0f)) << 6)) + << DILITHIUM_D; + t[j + 2] = (sword32)((t1[2] >> 4) | (((word16)(t1[3] & 0x3f)) << 4)) + << DILITHIUM_D; + t[j + 3] = (sword32)((t1[3] >> 6) | (((word16)(t1[4] )) << 2)) + << DILITHIUM_D; + t[j + 4] = (sword32)((t1[5] >> 0) | (((word16)(t1[6] & 0x03)) << 8)) + << DILITHIUM_D; + t[j + 5] = (sword32)((t1[6] >> 2) | (((word16)(t1[7] & 0x0f)) << 6)) + << DILITHIUM_D; + t[j + 6] = (sword32)((t1[7] >> 4) | (((word16)(t1[8] & 0x3f)) << 4)) + << DILITHIUM_D; + t[j + 7] = (sword32)((t1[8] >> 6) | (((word16)(t1[9] )) << 2)) + << DILITHIUM_D; +#endif + /* Move to next place to decode from. */ + t1 += DILITHIUM_U; + } +} +#endif + +#if (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) +/* Decode top bits of t as t1. + * + * FIPS 204. 8.2: Algorithm 17 pkDecode(pk) + * ... + * 3: for i from 0 to k - 1 do + * 4: t1[i] <- SimpleBitUnpack(zi, 2^(bitlen(q-1)-d) - 1) + * 5: end for + * ... + * + * @param [in] t1 Encoded values of t1. + * @param [in] d Dimensions of vector t1. + * @param [out] t Vector of polynomials. + */ +static void dilithium_vec_decode_t1(const byte* t1, byte d, sword32* t) +{ + unsigned int i; + + /* Step 3. For each polynomial of vector. */ + for (i = 0; i < d; i++) { + dilithium_decode_t1(t1, t); + /* Next polynomial. */ + t1 += DILITHIUM_U * DILITHIUM_N / 8; + t += DILITHIUM_N; + } +} +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Encode z with range of -(GAMMA1-1)...GAMMA1 + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 3: sigma <- sigma || BitPack(z[i], GAMMA1 - 1, GAMMA1) + * ... + * + * @param [in] z Polynomial to encode. + * @param [out] s Buffer to encode into. + */ +static void dilithium_encode_gamma1_17_bits(const sword32* z, byte* s) +{ + unsigned int j; + + /* Step 3. Get 18 bits as a number. */ + for (j = 0; j < DILITHIUM_N; j += 4) { + word32 z0 = DILITHIUM_GAMMA1_17 - z[j + 0]; + word32 z1 = DILITHIUM_GAMMA1_17 - z[j + 1]; + word32 z2 = DILITHIUM_GAMMA1_17 - z[j + 2]; + word32 z3 = DILITHIUM_GAMMA1_17 - z[j + 3]; + + /* 18 bits per number. + * 8 numbers become 9 bytes. (8 * 9 bits = 9 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + #ifdef WC_64BIT_CPU + word64* s64p = (word64*)s; + s64p[0] = z0 | ((word64)z1 << 18) | + ((word64)z2 << 36) | ((word64)z3 << 54); + #else + word32* s32p = (word32*)s; + s32p[0] = z0 | (z1 << 18) ; + s32p[1] = (z1 >> 14) | (z2 << 4) | (z3 << 22); + #endif +#else + s[0] = z0 ; + s[1] = z0 >> 8 ; + s[2] = (z0 >> 16) | (z1 << 2); + s[3] = z1 >> 6 ; + s[4] = (z1 >> 14) | (z2 << 4); + s[5] = z2 >> 4 ; + s[6] = (z2 >> 12) | (z3 << 6); + s[7] = z3 >> 2 ; +#endif + s[8] = z3 >> 10 ; + /* Move to next place to encode to. */ + s += DILITHIUM_GAMMA1_17_ENC_BITS / 2; + } +} +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Encode z with range of -(GAMMA1-1)...GAMMA1 + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 3: sigma <- sigma || BitPack(z[i], GAMMA1 - 1, GAMMA1) + * ... + * + * @param [in] z Polynomial to encode. + * @param [out] s Buffer to encode into. + */ +static void dilithium_encode_gamma1_19_bits(const sword32* z, byte* s) +{ + unsigned int j; + + /* Step 3. Get 20 bits as a number. */ + for (j = 0; j < DILITHIUM_N; j += 4) { + sword32 z0 = DILITHIUM_GAMMA1_19 - z[j + 0]; + sword32 z1 = DILITHIUM_GAMMA1_19 - z[j + 1]; + sword32 z2 = DILITHIUM_GAMMA1_19 - z[j + 2]; + sword32 z3 = DILITHIUM_GAMMA1_19 - z[j + 3]; + + /* 20 bits per number. + * 4 numbers become 10 bytes. (4 * 20 bits = 10 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 2) + word16* s16p = (word16*)s; + #ifdef WC_64BIT_CPU + word64* s64p = (word64*)s; + s64p[0] = z0 | ((word64)z1 << 20) | + ((word64)z2 << 40) | ((word64)z3 << 60); + #else + word32* s32p = (word32*)s; + s32p[0] = z0 | (z1 << 20) ; + s32p[1] = (z1 >> 12) | (z2 << 8) | (z3 << 28); + #endif + s16p[4] = (z3 >> 4) ; +#else + s[0] = z0 ; + s[1] = (z0 >> 8) ; + s[2] = (z0 >> 16) | (z1 << 4); + s[3] = (z1 >> 4) ; + s[4] = (z1 >> 12) ; + s[5] = z2 ; + s[6] = (z2 >> 8) ; + s[7] = (z2 >> 16) | (z3 << 4); + s[8] = (z3 >> 4) ; + s[9] = (z3 >> 12) ; +#endif + /* Move to next place to encode to. */ + s += DILITHIUM_GAMMA1_19_ENC_BITS / 2; + } +} +#endif + +#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +/* Encode z with range of -(GAMMA1-1)...GAMMA1 + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 2: for i form 0 to l - 1 do + * 3: sigma <- sigma || BitPack(z[i], GAMMA1 - 1, GAMMA1) + * 4: end for + * ... + * + * @param [in] z Vector of polynomials to encode. + * @param [in] l Dimension of vector. + * @param [in] bits Number of bits used in encoding - GAMMA1 bits. + * @param [out] s Buffer to encode into. + */ +static void dilithium_vec_encode_gamma1(const sword32* z, byte l, int bits, + byte* s) +{ + unsigned int i; + + (void)l; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (bits == DILITHIUM_GAMMA1_BITS_17) { + /* Step 2. For each polynomial of vector. */ + for (i = 0; i < PARAMS_ML_DSA_44_L; i++) { + dilithium_encode_gamma1_17_bits(z, s); + /* Move to next place to encode to. */ + s += DILITHIUM_GAMMA1_17_ENC_BITS / 2 * DILITHIUM_N / 4; + /* Next polynomial. */ + z += DILITHIUM_N; + } + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (bits == DILITHIUM_GAMMA1_BITS_19) { + /* Step 2. For each polynomial of vector. */ + for (i = 0; i < l; i++) { + dilithium_encode_gamma1_19_bits(z, s); + /* Move to next place to encode to. */ + s += DILITHIUM_GAMMA1_19_ENC_BITS / 2 * DILITHIUM_N / 4; + /* Next polynomial. */ + z += DILITHIUM_N; + } + } + else +#endif + { + } +} +#endif /* WOLFSSL_DILITHIUM_SIGN_SMALL_MEM */ + +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* Decode polynomial with range -(GAMMA1-1)..GAMMA1. + * + * FIPS 204. 8.2: Algorithm 21 sigDecode(sigma) + * ... + * 4: z[i] <- BitUnpack(xi, GAMMA1 - 1, GAMMA1) + * ... + * + * @param [in] s Encoded values of z. + * @param [in] bits Number of bits used in encoding - GAMMA1 bits. + * @param [out] z Polynomial to fill. + */ +static void dilithium_decode_gamma1(const byte* s, int bits, sword32* z) +{ + unsigned int i; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (bits == DILITHIUM_GAMMA1_BITS_17) { +#if defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) || defined(WOLFSSL_DILITHIUM_SMALL) + /* Step 4: Get 18 bits as a number. */ + for (i = 0; i < DILITHIUM_N; i += 4) { + /* 18 bits per number. + * 4 numbers from 9 bytes. (4 * 18 bits = 9 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + #ifdef WC_64BIT_CPU + word64 s64_0 = *(const word64*)(s+0); + z[i+0] = (word32)DILITHIUM_GAMMA1_17 - + ( s64_0 & 0x3ffff ); + z[i+1] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 18) & 0x3ffff ); + z[i+2] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 36) & 0x3ffff ); + z[i+3] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 54) | (((word32)s[8]) << 10)); + #else + word32 s32_0 = ((const word32*)(s+0))[0]; + word32 s32_1 = ((const word32*)(s+0))[1]; + z[i+0] = (word32)DILITHIUM_GAMMA1_17 - + ( s32_0 & 0x3ffff ); + z[i+1] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_0 >> 18) | (((s32_1 & 0x0000f) << 14))); + z[i+2] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 4) & 0x3ffff); + z[i+3] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 22) | (((word32)s[8]) << 10 )); + #endif + #else + z[i+0] = DILITHIUM_GAMMA1_17 - + ( s[ 0] | ((sword32)(s[ 1] << 8) | + (sword32)(s[ 2] & 0x03) << 16)); + z[i+1] = DILITHIUM_GAMMA1_17 - + ((s[ 2] >> 2) | ((sword32)(s[ 3] << 6) | + (sword32)(s[ 4] & 0x0f) << 14)); + z[i+2] = DILITHIUM_GAMMA1_17 - + ((s[ 4] >> 4) | ((sword32)(s[ 5] << 4) | + (sword32)(s[ 6] & 0x3f) << 12)); + z[i+3] = DILITHIUM_GAMMA1_17 - + ((s[ 6] >> 6) | ((sword32)(s[ 7] << 2) | + (sword32)(s[ 8] ) << 10)); + #endif + /* Move to next place to decode from. */ + s += DILITHIUM_GAMMA1_17_ENC_BITS / 2; + } +#else + /* Step 4: Get 18 bits as a number. */ + for (i = 0; i < DILITHIUM_N; i += 8) { + /* 18 bits per number. + * 8 numbers from 9 bytes. (8 * 18 bits = 18 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + #ifdef WC_64BIT_CPU + word64 s64_0 = *(const word64*)(s+0); + word64 s64_1 = *(const word64*)(s+9); + z[i+0] = (word32)DILITHIUM_GAMMA1_17 - + ( s64_0 & 0x3ffff ); + z[i+1] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 18) & 0x3ffff ); + z[i+2] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 36) & 0x3ffff ); + z[i+3] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 54) | (((word32)s[8]) << 10)); + z[i+4] = (word32)DILITHIUM_GAMMA1_17 - + ( s64_1 & 0x3ffff ); + z[i+5] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 18) & 0x3ffff ); + z[i+6] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 36) & 0x3ffff ); + z[i+7] = (word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 54) | (((word32)s[17]) << 10)); + #else + word32 s32_0 = ((const word32*)(s+0))[0]; + word32 s32_1 = ((const word32*)(s+0))[1]; + word32 s32_2 = ((const word32*)(s+9))[0]; + word32 s32_3 = ((const word32*)(s+9))[1]; + z[i+0] = (word32)DILITHIUM_GAMMA1_17 - + ( s32_0 & 0x3ffff ); + z[i+1] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_0 >> 18) | (((s32_1 & 0x0000f) << 14))); + z[i+2] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 4) & 0x3ffff); + z[i+3] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 22) | (((word32)s[8]) << 10 )); + z[i+4] = (word32)DILITHIUM_GAMMA1_17 - + ( s32_2 & 0x3ffff ); + z[i+5] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_2 >> 18) | (((s32_3 & 0x0000f) << 14))); + z[i+6] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_3 >> 4) & 0x3ffff); + z[i+7] = (word32)DILITHIUM_GAMMA1_17 - + ((s32_3 >> 22) | (((word32)s[17]) << 10 )); + #endif + #else + z[i+0] = DILITHIUM_GAMMA1_17 - + ( s[ 0] | ((sword32)(s[ 1] << 8) | + (sword32)(s[ 2] & 0x03) << 16)); + z[i+1] = DILITHIUM_GAMMA1_17 - + ((s[ 2] >> 2) | ((sword32)(s[ 3] << 6) | + (sword32)(s[ 4] & 0x0f) << 14)); + z[i+2] = DILITHIUM_GAMMA1_17 - + ((s[ 4] >> 4) | ((sword32)(s[ 5] << 4) | + (sword32)(s[ 6] & 0x3f) << 12)); + z[i+3] = DILITHIUM_GAMMA1_17 - + ((s[ 6] >> 6) | ((sword32)(s[ 7] << 2) | + (sword32)(s[ 8] ) << 10)); + z[i+4] = DILITHIUM_GAMMA1_17 - + ( s[ 9] | ((sword32)(s[10] << 8) | + (sword32)(s[11] & 0x03) << 16)); + z[i+5] = DILITHIUM_GAMMA1_17 - + ((s[11] >> 2) | ((sword32)(s[12] << 6) | + (sword32)(s[13] & 0x0f) << 14)); + z[i+6] = DILITHIUM_GAMMA1_17 - + ((s[13] >> 4) | ((sword32)(s[14] << 4) | + (sword32)(s[15] & 0x3f) << 12)); + z[i+7] = DILITHIUM_GAMMA1_17 - + ((s[15] >> 6) | ((sword32)(s[16] << 2) | + (sword32)(s[17] ) << 10)); + #endif + /* Move to next place to decode from. */ + s += DILITHIUM_GAMMA1_17_ENC_BITS; + } +#endif + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (bits == DILITHIUM_GAMMA1_BITS_19) { +#if defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) || defined(WOLFSSL_DILITHIUM_SMALL) + /* Step 4: Get 20 bits as a number. */ + for (i = 0; i < DILITHIUM_N; i += 4) { + /* 20 bits per number. + * 4 numbers from 10 bytes. (4 * 20 bits = 10 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 2) + word16 s16_0 = ((const word16*)s)[4]; + #ifdef WC_64BIT_CPU + word64 s64_0 = *(const word64*)s; + z[i+0] = DILITHIUM_GAMMA1_19 - ( s64_0 & 0xfffff) ; + z[i+1] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 20) & 0xfffff) ; + z[i+2] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 40) & 0xfffff) ; + z[i+3] = DILITHIUM_GAMMA1_19 - (((s64_0 >> 60) & 0xfffff) | + ((sword32)s16_0 << 4)); + #else + word32 s32_0 = ((const word32*)s)[0]; + word32 s32_1 = ((const word32*)s)[1]; + z[i+0] = DILITHIUM_GAMMA1_19 - ( s32_0 & 0xfffff); + z[i+1] = DILITHIUM_GAMMA1_19 - (( s32_0 >> 20) | + ((s32_1 & 0x000ff) << 12)); + z[i+2] = DILITHIUM_GAMMA1_19 - ( (s32_1 >> 8) & 0xfffff); + z[i+3] = DILITHIUM_GAMMA1_19 - (( s32_1 >> 28) | + ((sword32)s16_0 << 4)); + #endif + #else + z[i+0] = DILITHIUM_GAMMA1_19 - ( s[0] | ((sword32)s[1] << 8) | + ((sword32)(s[2] & 0x0f) << 16)); + z[i+1] = DILITHIUM_GAMMA1_19 - ((s[2] >> 4) | ((sword32)s[3] << 4) | + ((sword32)(s[4] ) << 12)); + z[i+2] = DILITHIUM_GAMMA1_19 - ( s[5] | ((sword32)s[6] << 8) | + ((sword32)(s[7] & 0x0f) << 16)); + z[i+3] = DILITHIUM_GAMMA1_19 - ((s[7] >> 4) | ((sword32)s[8] << 4) | + ((sword32)(s[9] ) << 12)); + #endif + /* Move to next place to decode from. */ + s += DILITHIUM_GAMMA1_19_ENC_BITS / 2; + } +#else + /* Step 4: Get 20 bits as a number. */ + for (i = 0; i < DILITHIUM_N; i += 8) { + /* 20 bits per number. + * 8 numbers from 10 bytes. (8 * 20 bits = 20 * 8 bits) */ + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 2) + word16 s16_0 = ((const word16*)s)[4]; + word16 s16_1 = ((const word16*)s)[9]; + #ifdef WC_64BIT_CPU + word64 s64_0 = *(const word64*)(s+0); + word64 s64_1 = *(const word64*)(s+10); + z[i+0] = DILITHIUM_GAMMA1_19 - ( s64_0 & 0xfffff) ; + z[i+1] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 20) & 0xfffff) ; + z[i+2] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 40) & 0xfffff) ; + z[i+3] = DILITHIUM_GAMMA1_19 - (((s64_0 >> 60) & 0xfffff) | + ((sword32)s16_0 << 4)); + z[i+4] = DILITHIUM_GAMMA1_19 - ( s64_1 & 0xfffff) ; + z[i+5] = DILITHIUM_GAMMA1_19 - ( (s64_1 >> 20) & 0xfffff) ; + z[i+6] = DILITHIUM_GAMMA1_19 - ( (s64_1 >> 40) & 0xfffff) ; + z[i+7] = DILITHIUM_GAMMA1_19 - (((s64_1 >> 60) & 0xfffff) | + ((sword32)s16_1 << 4)); + #else + word32 s32_0 = ((const word32*)(s+ 0))[0]; + word32 s32_1 = ((const word32*)(s+ 0))[1]; + word32 s32_2 = ((const word32*)(s+10))[0]; + word32 s32_3 = ((const word32*)(s+10))[1]; + z[i+0] = DILITHIUM_GAMMA1_19 - ( s32_0 & 0xfffff); + z[i+1] = DILITHIUM_GAMMA1_19 - (( s32_0 >> 20) | + ((s32_1 & 0x000ff) << 12)); + z[i+2] = DILITHIUM_GAMMA1_19 - ( (s32_1 >> 8) & 0xfffff); + z[i+3] = DILITHIUM_GAMMA1_19 - (( s32_1 >> 28) | + ((sword32)s16_0 << 4)); + z[i+4] = DILITHIUM_GAMMA1_19 - ( s32_2 & 0xfffff); + z[i+5] = DILITHIUM_GAMMA1_19 - (( s32_2 >> 20) | + ((s32_3 & 0x000ff) << 12)); + z[i+6] = DILITHIUM_GAMMA1_19 - ( (s32_3 >> 8) & 0xfffff); + z[i+7] = DILITHIUM_GAMMA1_19 - (( s32_3 >> 28) | + ((sword32)s16_1 << 4)); + #endif + #else + z[i+0] = DILITHIUM_GAMMA1_19 - ( s[ 0] | + ((sword32)s[ 1] << 8) | + ((sword32)(s[ 2] & 0x0f) << 16)); + z[i+1] = DILITHIUM_GAMMA1_19 - ((s[ 2] >> 4) | + ((sword32) s[ 3] << 4) | + ((sword32)(s[ 4] ) << 12)); + z[i+2] = DILITHIUM_GAMMA1_19 - ( s[ 5] | + ((sword32) s[ 6] << 8) | + ((sword32)(s[ 7] & 0x0f) << 16)); + z[i+3] = DILITHIUM_GAMMA1_19 - ((s[ 7] >> 4) | + ((sword32) s[ 8] << 4) | + ((sword32)(s[ 9] ) << 12)); + z[i+4] = DILITHIUM_GAMMA1_19 - ( s[10] | + ((sword32) s[11] << 8) | + ((sword32)(s[12] & 0x0f) << 16)); + z[i+5] = DILITHIUM_GAMMA1_19 - ((s[12] >> 4) | + ((sword32) s[13] << 4) | + ((sword32)(s[14] ) << 12)); + z[i+6] = DILITHIUM_GAMMA1_19 - ( s[15] | + ((sword32) s[16] << 8) | + ((sword32)(s[17] & 0x0f) << 16)); + z[i+7] = DILITHIUM_GAMMA1_19 - ((s[17] >> 4) | + ((sword32) s[18] << 4) | + ((sword32)(s[19] ) << 12)); + #endif + /* Move to next place to decode from. */ + s += DILITHIUM_GAMMA1_19_ENC_BITS; + } +#endif + } + else +#endif + { + } +} +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* Decode polynomial with range -(GAMMA1-1)..GAMMA1. + * + * FIPS 204. 8.2: Algorithm 21 sigDecode(sigma) + * ... + * 3: for i from 0 to l - 1 do + * 4: z[i] <- BitUnpack(xi, GAMMA1 - 1, GAMMA1) + * 5: end for + * ... + * + * @param [in] x Encoded values of t0. + * @param [in] l Dimensions of vector z. + * @param [in] bits Number of bits used in encoding - GAMMA1 bits. + * @param [out] z Vector of polynomials. + */ +static void dilithium_vec_decode_gamma1(const byte* x, byte l, int bits, + sword32* z) +{ + unsigned int i; + + /* Step 3: For each polynomial of vector. */ + for (i = 0; i < l; i++) { + /* Step 4: Unpack a polynomial. */ + dilithium_decode_gamma1(x, bits, z); + /* Move pointers on to next polynomial. */ + x += DILITHIUM_N / 8 * (bits + 1); + z += DILITHIUM_N; + } +} +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Encode w1 with range of 0..((q-1)/(2*GAMMA2)-1). + * + * FIPS 204. 8.2: Algorithm 22 w1Encode(w1) + * ... + * 3: w1_tilde <- w1_tilde || + * ByteToBits(SimpleBitPack(w1[i], (q-1)/(2*GAMMA2)-1)) + * ... + * + * @param [in] w1 Vector of polynomials to encode. + * @param [in] gamma2 Maximum value in range. + * @param [out] w1e Buffer to encode into. + */ +static void dilithium_encode_w1_88(const sword32* w1, byte* w1e) +{ + unsigned int j; + + /* Step 3: Encode a polynomial values 6 bits at a time. */ + for (j = 0; j < DILITHIUM_N; j += 16) { + /* 6 bits per number. + * 16 numbers in 12 bytes. (16 * 6 bits = 12 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 4) + word32* w1e32 = (word32*)w1e; + w1e32[0] = w1[j+ 0] | (w1[j+ 1] << 6) | + (w1[j+ 2] << 12) | (w1[j+ 3] << 18) | + (w1[j+ 4] << 24) | (w1[j+ 5] << 30); + w1e32[1] = (w1[j+ 5] >> 2) | (w1[j+ 6] << 4) | + (w1[j+ 7] << 10) | (w1[j+ 8] << 16) | + (w1[j+ 9] << 22) | (w1[j+10] << 28); + w1e32[2] = (w1[j+10] >> 4) | (w1[j+11] << 2) | + (w1[j+12] << 8) | (w1[j+13] << 14) | + (w1[j+14] << 20) | (w1[j+15] << 26); +#else + w1e[ 0] = w1[j+ 0] | (w1[j+ 1] << 6); + w1e[ 1] = (w1[j+ 1] >> 2) | (w1[j+ 2] << 4); + w1e[ 2] = (w1[j+ 2] >> 4) | (w1[j+ 3] << 2); + w1e[ 3] = w1[j+ 4] | (w1[j+ 5] << 6); + w1e[ 4] = (w1[j+ 5] >> 2) | (w1[j+ 6] << 4); + w1e[ 5] = (w1[j+ 6] >> 4) | (w1[j+ 7] << 2); + w1e[ 6] = w1[j+ 8] | (w1[j+ 9] << 6); + w1e[ 7] = (w1[j+ 9] >> 2) | (w1[j+10] << 4); + w1e[ 8] = (w1[j+10] >> 4) | (w1[j+11] << 2); + w1e[ 9] = w1[j+12] | (w1[j+13] << 6); + w1e[10] = (w1[j+13] >> 2) | (w1[j+14] << 4); + w1e[11] = (w1[j+14] >> 4) | (w1[j+15] << 2); +#endif + /* Move to next place to encode to. */ + w1e += DILITHIUM_Q_HI_88_ENC_BITS * 2; + } +} +#endif /* !WOLFSSL_NO_ML_DSA_44 */ + +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Encode w1 with range of 0..((q-1)/(2*GAMMA2)-1). + * + * FIPS 204. 8.2: Algorithm 22 w1Encode(w1) + * ... + * 3: w1_tilde <- w1_tilde || + * ByteToBits(SimpleBitPack(w1[i], (q-1)/(2*GAMMA2)-1)) + * ... + * + * @param [in] w1 Vector of polynomials to encode. + * @param [in] gamma2 Maximum value in range. + * @param [out] w1e Buffer to encode into. + */ +static void dilithium_encode_w1_32(const sword32* w1, byte* w1e) +{ + unsigned int j; + + /* Step 3: Encode a polynomial values 4 bits at a time. */ + for (j = 0; j < DILITHIUM_N; j += 16) { + /* 4 bits per number. + * 16 numbers in 8 bytes. (16 * 4 bits = 8 * 8 bits) */ +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 8) + word32* w1e32 = (word32*)w1e; + w1e32[0] = (w1[j + 0] << 0) | (w1[j + 1] << 4) | + (w1[j + 2] << 8) | (w1[j + 3] << 12) | + (w1[j + 4] << 16) | (w1[j + 5] << 20) | + (w1[j + 6] << 24) | (w1[j + 7] << 28); + w1e32[1] = (w1[j + 8] << 0) | (w1[j + 9] << 4) | + (w1[j + 10] << 8) | (w1[j + 11] << 12) | + (w1[j + 12] << 16) | (w1[j + 13] << 20) | + (w1[j + 14] << 24) | (w1[j + 15] << 28); +#else + w1e[0] = w1[j + 0] | (w1[j + 1] << 4); + w1e[1] = w1[j + 2] | (w1[j + 3] << 4); + w1e[2] = w1[j + 4] | (w1[j + 5] << 4); + w1e[3] = w1[j + 6] | (w1[j + 7] << 4); + w1e[4] = w1[j + 8] | (w1[j + 9] << 4); + w1e[5] = w1[j + 10] | (w1[j + 11] << 4); + w1e[6] = w1[j + 12] | (w1[j + 13] << 4); + w1e[7] = w1[j + 14] | (w1[j + 15] << 4); +#endif + /* Move to next place to encode to. */ + w1e += DILITHIUM_Q_HI_32_ENC_BITS * 2; + } +} +#endif +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) +/* Encode w1 with range of 0..((q-1)/(2*GAMMA2)-1). + * + * FIPS 204. 8.2: Algorithm 22 w1Encode(w1) + * 1: w1_tilde = () + * 2: for i form 0 to k - 1 do + * 3: w1_tilde <- w1_tilde || + * ByteToBits(SimpleBitPack(w1[i], (q-1)/(2*GAMMA2)-1)) + * 4: end for + * 5: return w1_tilde + * + * @param [in] w1 Vector of polynomials to encode. + * @param [in] k Dimension of vector. + * @param [in] gamma2 Maximum value in range. + * @param [out] w1e Buffer to encode into. + */ +static void dilithium_vec_encode_w1(const sword32* w1, byte k, sword32 gamma2, + byte* w1e) +{ + unsigned int i; + + (void)k; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (gamma2 == DILITHIUM_Q_LOW_88) { + /* Step 2. For each polynomial of vector. */ + for (i = 0; i < PARAMS_ML_DSA_44_K; i++) { + dilithium_encode_w1_88(w1, w1e); + /* Next polynomial. */ + w1 += DILITHIUM_N; + w1e += DILITHIUM_Q_HI_88_ENC_BITS * 2 * DILITHIUM_N / 16; + } + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (gamma2 == DILITHIUM_Q_LOW_32) { + /* Step 2. For each polynomial of vector. */ + for (i = 0; i < k; i++) { + dilithium_encode_w1_32(w1, w1e); + /* Next polynomial. */ + w1 += DILITHIUM_N; + w1e += DILITHIUM_Q_HI_32_ENC_BITS * 2 * DILITHIUM_N / 16; + } + } + else +#endif + { + } +} +#endif + +/****************************************************************************** + * Expand operations + ******************************************************************************/ + +/* Generate a random polynomial by rejection. + * + * FIPS 204. 8.3: Algorithm 24 RejNTTPoly(rho) + * 1: j <- 0 + * 2: c <- 0 + * 3: while j < 256 do + * 4: a_hat[j] <- CoeffFromThreeBytes(H128(rho)[[c]], H128(rho)[[c+1]], + * H128(rho)[[c+2]]) + * 5: c <- c + 3 + * 6: if a_hat[j] != falsam then + * 7: j <- j + 1 + * 8: end if + * 9: end while + * 10: return a_hat + * + * FIPS 204. 8.1: Algorithm 8 CoeffFromThreeBytes(b0,b1,b2) + * 1: if b2 > 127 then + * 2: b2 <- b2 - 128 + * 3. end if + * 4. z <- 2^16.b2 + s^8.b1 + b0 + * 5. if z < q then return z + * 6. else return falsam + * 7. end if + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] seed Seed to hash to generate values. + * @param [out] a Polynomial. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Negative on hash error. + */ +static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, + byte* key_h) +{ +#ifdef WOLFSSL_DILITHIUM_SMALL + int ret = 0; + int j = 0; +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) + byte* h = NULL; +#else + byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; +#endif + + (void)key_h; + +#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + h = key_h; +#elif defined(WOLFSSL_SMALL_STACK) + h = (byte*)XMALLOC(DILITHIUM_REJ_NTT_POLY_H_SIZE, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (h == NULL) { + ret = MEMORY_E; + } +#endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC */ + + if (ret == 0) { + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Reading 4 bytes for 3 so need to set 1 past for last read. */ + h[DILITHIUM_GEN_A_BLOCK_BYTES] = 0; + #endif + + /* Initialize SHAKE-128 object for new hash. */ + ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); + } + if (ret == 0) { + /* Absorb the seed. */ + ret = wc_Shake128_Absorb(shake128, seed, DILITHIUM_GEN_A_SEED_SZ); + } + /* Keep generating more blocks and using triplets until we have enough. + */ + while ((ret == 0) && (j < DILITHIUM_N)) { + /* Squeeze out a block - 168 bytes = 56 values. */ + ret = wc_Shake128_SqueezeBlocks(shake128, h, 1); + if (ret == 0) { + int c; + /* Use triplets until run out or have enough for polynomial. */ + for (c = 0; c < DILITHIUM_GEN_A_BLOCK_BYTES; c += 3) { + #if defined(LITTLE_ENDIAN_ORDER) && \ + (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t = *((sword32*)(h + c)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t = (h[c] + ((sword32)h[c+1] << 8) + + ((sword32)h[c+2] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. + */ + a[j++] = t; + /* Check we whether we have enough yet. */ + if (j == DILITHIUM_N) { + break; + } + } + } + } + } + +#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) + XFREE(h, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +#else + int ret = 0; + unsigned int j = 0; + unsigned int c; +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) + byte* h = NULL; +#else + byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; +#endif + + (void)key_h; + +#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + h = key_h; +#elif defined(WOLFSSL_SMALL_STACK) + h = (byte*)XMALLOC(DILITHIUM_REJ_NTT_POLY_H_SIZE, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (h == NULL) { + ret = MEMORY_E; + } +#endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC */ + + if (ret == 0) { + /* Generate enough SHAKE-128 output blocks to give high probability of + * being able to get 256 valid 3-byte, 23-bit values from it. */ + ret = dilithium_squeeze128(shake128, seed, DILITHIUM_GEN_A_SEED_SZ, h, + DILITHIUM_GEN_A_NBLOCKS); + } + if (ret == 0) { + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Reading 4 bytes for 3 so need to set 1 past for last read. */ + h[DILITHIUM_GEN_A_BYTES] = 0; + #endif + + /* Use the first 256 triplets and know we won't exceed required. */ +#ifdef WOLFSSL_DILITHIUM_NO_LARGE_CODE + for (c = 0; c < (DILITHIUM_N - 1) * 3; c += 3) { + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t = *((sword32*)(h + c)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t = (h[c] + ((sword32)h[c+1] << 8) + + ((sword32)h[c+2] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t; + } + } + /* Use the remaining triplets, checking we have enough. */ + for (; c < DILITHIUM_GEN_A_BYTES; c += 3) { + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t = *((sword32*)(h + c)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t = (h[c] + ((sword32)h[c+1] << 8) + + ((sword32)h[c+2] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t; + /* Check we whether we have enough yet. */ + if (j == DILITHIUM_N) { + break; + } + } + } +#else + /* Do 15 bytes at a time: 255 * 3 / 15 = 51 */ + for (c = 0; c < DILITHIUM_N * 3; c += 24) { + #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t0 = *((sword32*)(h + c + 0)) & 0x7fffff; + sword32 t1 = *((sword32*)(h + c + 3)) & 0x7fffff; + sword32 t2 = *((sword32*)(h + c + 6)) & 0x7fffff; + sword32 t3 = *((sword32*)(h + c + 9)) & 0x7fffff; + sword32 t4 = *((sword32*)(h + c + 12)) & 0x7fffff; + sword32 t5 = *((sword32*)(h + c + 15)) & 0x7fffff; + sword32 t6 = *((sword32*)(h + c + 18)) & 0x7fffff; + sword32 t7 = *((sword32*)(h + c + 21)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t0 = (h[c + 0] + ((sword32)h[c + 1] << 8) + + ((sword32)h[c + 2] << 16)) & 0x7fffff; + sword32 t1 = (h[c + 3] + ((sword32)h[c + 4] << 8) + + ((sword32)h[c + 5] << 16)) & 0x7fffff; + sword32 t2 = (h[c + 6] + ((sword32)h[c + 7] << 8) + + ((sword32)h[c + 8] << 16)) & 0x7fffff; + sword32 t3 = (h[c + 9] + ((sword32)h[c + 10] << 8) + + ((sword32)h[c + 11] << 16)) & 0x7fffff; + sword32 t4 = (h[c + 12] + ((sword32)h[c + 13] << 8) + + ((sword32)h[c + 14] << 16)) & 0x7fffff; + sword32 t5 = (h[c + 15] + ((sword32)h[c + 16] << 8) + + ((sword32)h[c + 17] << 16)) & 0x7fffff; + sword32 t6 = (h[c + 18] + ((sword32)h[c + 19] << 8) + + ((sword32)h[c + 20] << 16)) & 0x7fffff; + sword32 t7 = (h[c + 21] + ((sword32)h[c + 22] << 8) + + ((sword32)h[c + 23] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t0 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t0; + } + /* Check if value is in valid range. */ + if (t1 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t1; + } + /* Check if value is in valid range. */ + if (t2 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t2; + } + /* Check if value is in valid range. */ + if (t3 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t3; + } + /* Check if value is in valid range. */ + if (t4 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t4; + } + /* Check if value is in valid range. */ + if (t5 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t5; + } + /* Check if value is in valid range. */ + if (t6 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t6; + } + /* Check if value is in valid range. */ + if (t7 < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. */ + a[j++] = t7; + } + } + if (j < DILITHIUM_N) { + /* Use the remaining triplets, checking we have enough. */ + for (; c < DILITHIUM_GEN_A_BYTES; c += 3) { + #if defined(LITTLE_ENDIAN_ORDER) && \ + (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t = *((sword32*)(h + c)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t = (h[c] + ((sword32)h[c+1] << 8) + + ((sword32)h[c+2] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. + */ + a[j++] = t; + /* Check we whether we have enough yet. */ + if (j == DILITHIUM_N) { + break; + } + } + } + } +#endif + /* Keep generating more blocks and using triplets until we have enough. + */ + while (j < DILITHIUM_N) { + /* Squeeze out a block - 168 bytes = 56 values. */ + ret = wc_Shake128_SqueezeBlocks(shake128, h, 1); + if (ret != 0) { + break; + } + /* Use triplets until run out or have enough for polynomial. */ + for (c = 0; c < DILITHIUM_GEN_A_BLOCK_BYTES; c += 3) { + #if defined(LITTLE_ENDIAN_ORDER) && \ + (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Load 32-bit value and mask out 23 bits. */ + sword32 t = *((sword32*)(h + c)) & 0x7fffff; + #else + /* Load 24-bit value and mask out 23 bits. */ + sword32 t = (h[c] + ((sword32)h[c+1] << 8) + + ((sword32)h[c+2] << 16)) & 0x7fffff; + #endif + /* Check if value is in valid range. */ + if (t < DILITHIUM_Q) { + /* Store value in polynomial and increment count of values. + */ + a[j++] = t; + /* Check we whether we have enough yet. */ + if (j == DILITHIUM_N) { + break; + } + } + } + } + } + +#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) + XFREE(h, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + (!defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) || \ + defined(WC_DILITHIUM_CACHE_MATRIX_A))) +/* Expand the seed to create matrix a. + * + * FIPS 204. 8.3: Algorithm 26 ExpandA(rho) + * 1: for r from 0 to k - 1 do + * 2: for s from 0 to l - 1 do + * 3: A_hat[r,s] <- RejNTTPoly(rho||IntegerToBits(s,8)|| + * IntegerToBits(r,8)) + * 4: end for + * 5: end for + * 6: return A_hat + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] pub_seed Seed to generate stream of data. + * @param [in] k First dimension of matrix a. + * @param [in] l Second dimension of matrix a. + * @param [out] a Matrix of polynomials. + * @return 0 on success. + * @return Negative on hash error. + */ +static int dilithium_expand_a(wc_Shake* shake128, const byte* pub_seed, byte k, + byte l, sword32* a) +{ + int ret = 0; + byte r; + byte s; + byte seed[DILITHIUM_GEN_A_SEED_SZ]; + + /* Copy the seed into a buffer that has space for s and r. */ + XMEMCPY(seed, pub_seed, DILITHIUM_PUB_SEED_SZ); + /* Step 1: Loop over first dimension of matrix. */ + for (r = 0; (ret == 0) && (r < k); r++) { + /* Put r into buffer to be hashed. */ + seed[DILITHIUM_PUB_SEED_SZ + 1] = r; + /* Step 2: Loop over second dimension of matrix. */ + for (s = 0; (ret == 0) && (s < l); s++) { + /* Put s into buffer to be hashed. */ + seed[DILITHIUM_PUB_SEED_SZ + 0] = s; + /* Step 3: Create polynomial from hashing seed. */ + ret = dilithium_rej_ntt_poly(shake128, seed, a, NULL); + /* Next polynomial. */ + a += DILITHIUM_N; + } + } + + return ret; +} +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY + +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Check random value is in valid range. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: if b < 15 + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 2 - unused. + * @return 1 when value less than 9. + * @return 0 when value greater than or equal to 9. + */ +#define DILITHIUM_COEFF_S_VALID_ETA2(b) \ + ((b) < DILITHIUM_ETA_2_MOD) + +static const byte dilithium_coeff_eta2[] = { + 2, 1, 0, -1, -2, + 2, 1, 0, -1, -2, + 2, 1, 0, -1, -2 +}; +/* Convert random value 0..15 to a value in range of -2..2. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: return 2 - (b mod 5) + * + * @param [in] b Random half-byte (nibble) value. + * @return Value in range of -2..2 on success. + */ +#define DILITHIUM_COEFF_S_ETA2(b) \ + (dilithium_coeff_eta2[b]) +#endif + +#ifndef WOLFSSL_NO_ML_DSA_65 +/* Check random value is in valid range. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 3: if b < 9 + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 4 - unused. + * @return 1 when value less than 9. + * @return 0 when value greater than or equal to 9. + */ +#define DILITHIUM_COEFF_S_VALID_ETA4(b) \ + ((b) < DILITHIUM_ETA_4_MOD) + +/* Convert random value 0..15 to a value in range of -4..4. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 3: return 4 - b + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 4 - unused. + * @return Value in range of -4..4 on success. + */ +#define DILITHIUM_COEFF_S_ETA4(b) \ + (4 - (b)) +#endif + +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_87) +#ifndef WOLFSSL_NO_ML_DSA_65 + +/* Check random value is in valid range. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: if eta = 2 and b < 15 + * 2: else + * 3: if eta = 4 and b < 9 + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. + * @return Value in range of -ETA..ETA on success. + */ +#define DILITHIUM_COEFF_S_VALID(b, eta) \ + (((eta) == DILITHIUM_ETA_2) ? DILITHIUM_COEFF_S_VALID_ETA2(b) : \ + DILITHIUM_COEFF_S_VALID_ETA4(b)) + +/* Convert random value 0..15 to a value in range of -ETA..ETA. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: if eta = 2 then return 2 - (b mod 5) + * 2: else + * 3: if eta = 4 then return 4 - b + * ... + * 6: end if + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. + * @return Value in range of -ETA..ETA on success. + */ +#define DILITHIUM_COEFF_S(b, eta) \ + (((eta) == DILITHIUM_ETA_2) ? DILITHIUM_COEFF_S_ETA2(b) \ + : DILITHIUM_COEFF_S_ETA4(b)) + +#else + +/* Check random value is in valid range. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: if b < 15 + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 2 - unused. + * @return 1 when value less than 9. + * @return 0 when value greater than or equal to 9. + */ +#define DILITHIUM_COEFF_S_VALID(b, eta) \ + DILITHIUM_COEFF_S_VALID_ETA2(b) + +/* Convert random value 0..15 to a value in range of -2..2. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 1: return 2 - (b mod 5) + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 2 - unused. + * @return Value in range of -2..2 on success. + */ +#define DILITHIUM_COEFF_S(b, eta) \ + DILITHIUM_COEFF_S_ETA2(b) + +#endif /* WOLFSSL_NO_ML_DSA_65 */ + +#else + +/* Check random value is in valid range. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 3: if b < 9 + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 4 - unused. + * @return 1 when value less than 9. + * @return 0 when value greater than or equal to 9. + */ +#define DILITHIUM_COEFF_S_VALID(b, eta) \ + DILITHIUM_COEFF_S_VALID_ETA4(b) + +/* Convert random value 0..15 to a value in range of -4..4. + * + * FIPS 204. 8.1: Algorithm 9 CoeffFromHalfByte(b) + * 3: return 4 - b + * + * @param [in] b Random half-byte (nibble) value. + * @param [in] eta Range specifier of result. Will always be 4 - unused. + * @return Value in range of -4..4 on success. + */ +#define DILITHIUM_COEFF_S(b, eta) \ + DILITHIUM_COEFF_S_ETA4(b) + +#endif /* !WOLFSSL_NO_ML_DSA_44 || !WOLFSSL_NO_ML_DSA_87 */ + +/* Extract a coefficient from a nibble of z. + * + * Breaks out of loop when we have enough coefficients. + * + * @param [in] z A random value. + * @param [in] rs Amount to shift right. + * @param [in] t Temporary result. + * @param [in] eta ETA value from parameters. + * @return Value in range -eta..eta on success. + * @return Falsam (0x10) when random value out of range. + */ +#define EXTRACT_COEFF_NIBBLE_CHECK_J(z, rs, t, eta) \ + (t) = (sword8)(((z) >> (rs)) & 0xf); \ + /* Step 7: Check we have a valid coefficient. */ \ + if (DILITHIUM_COEFF_S_VALID(t, eta)) { \ + (t) = DILITHIUM_COEFF_S(t, eta); \ + /* Step 8: Store coefficient as next polynomial value. \ + * Step 9: Increment count of polynomial values set. */ \ + s[j++] = (sword32)(t); \ + if (j == DILITHIUM_N) { \ + break; \ + } \ + } + +/* Extract a coefficient from a nibble of z. + * + * @param [in] z A random value. + * @param [in] rs Amount to shift right. + * @param [in] t Temporary result. + * @param [in] eta ETA value from parameters. + * @return Value in range -eta..eta on success. + * @return Falsam (0x10) when random value out of range. + */ +#define EXTRACT_COEFF_NIBBLE(z, rs, t, eta) \ + (t) = (sword8)(((z) >> (rs)) & 0xf); \ + /* Step 7: Check we have a valid coefficient. */ \ + if (DILITHIUM_COEFF_S_VALID(t, eta)) { \ + (t) = DILITHIUM_COEFF_S(t, eta); \ + /* Step 8: Store coefficient as next polynomial value. \ + * Step 9: Increment count of polynomial values set. */ \ + s[j++] = (sword32)(t); \ + } + + +/* Extract coefficients from hash - z. + * + * FIPS 204. 8.3: Algorithm 25 RejBoundedPoly(rho) + * 2: c <- 0 + * 5: z0 <- CoeffFromHalfByte(z mod 16, eta) + * 6: z1 <- CoeffFromHalfByte(lower(z / 16), eta) + * 7: if z0 != falsam then + * 8: aj <- z0 + * 9: j <- j + 1 + * 10: end if + * 11: if z1 != falsam then + * 12: aj <- z1 + * 13: j <- j + 1 + * 14: end if + * 15: c <- c + 1 + * + * @param [in] z Hash data to extract coefficients from. + * @param [in] zLen Length of z in bytes. + * @param [in] eta Range specifier of each value. + * @param [out] s Polynomial to fill with coefficients. + * @param [in, out] cnt Current count of coefficients in polynomial. + */ +static void dilithium_extract_coeffs(byte* z, unsigned int zLen, byte eta, + sword32* s, unsigned int* cnt) +{ +#ifdef WOLFSSL_DILITHIUM_NO_LARGE_CODE + unsigned int j = *cnt; + unsigned int c; + + (void)eta; + + /* Extract values from the squeezed data. */ + for (c = 0; c < zLen; c++) { + sword8 t; + + /* Step 5: Get coefficient from bottom nibble. */ + EXTRACT_COEFF_NIBBLE_CHECK_J(z[c], 0, t, eta); + /* Step 6: Get coefficient from top nibble. */ + EXTRACT_COEFF_NIBBLE_CHECK_J(z[c], 4, t, eta); + } + + *cnt = j; +#else + unsigned int j = *cnt; + unsigned int c; + unsigned int min = (DILITHIUM_N - j) / 2; + + (void)eta; + +#if defined(LITTLE_ENDIAN_ORDER) +#ifdef WC_64BIT_CPU + min &= ~(unsigned int)7; + /* Extract values from the squeezed data. */ + for (c = 0; c < min; c += 8) { + word64 z64 = *(word64*)(z + c); + sword8 t; + + /* Do each nibble from lowest to highest 16 at a time. */ + EXTRACT_COEFF_NIBBLE(z64, 0, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 4, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 8, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 12, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 16, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 20, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 24, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 28, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 32, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 36, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 40, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 44, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 48, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 52, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 56, t, eta); + EXTRACT_COEFF_NIBBLE(z64, 60, t, eta); + } +#else + min &= ~(unsigned int)3; + /* Extract values from the squeezed data. */ + for (c = 0; c < min; c += 4) { + word32 z32 = *(word32*)(z + c); + sword8 t; + + /* Do each nibble from lowest to highest 8 at a time. */ + EXTRACT_COEFF_NIBBLE(z32, 0, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 4, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 8, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 12, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 16, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 20, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 24, t, eta); + EXTRACT_COEFF_NIBBLE(z32, 28, t, eta); + } +#endif +#else + /* Extract values from the squeezed data. */ + for (c = 0; c < min; c++) { + sword8 t; + + /* Step 5: Get coefficient from bottom nibble. */ + EXTRACT_COEFF_NIBBLE(z[c], 0, t, eta); + EXTRACT_COEFF_NIBBLE(z[c], 4, t, eta); + } +#endif + if (j != DILITHIUM_N) { + /* Extract values from the squeezed data. */ + for (; c < zLen; c++) { + sword8 t; + + EXTRACT_COEFF_NIBBLE_CHECK_J(z[c], 0, t, eta); + EXTRACT_COEFF_NIBBLE_CHECK_J(z[c], 4, t, eta); + } + } + + *cnt = j; +#endif +} + +/* Create polynomial from hashing the seed with bounded values. + * + * FIPS 204. 8.3: Algorithm 25 RejBoundedPoly(rho) + * 1: j <- 0 + * ... + * 3: while j < 256 do + * 4: z <- H(rho)[[c]] + * ... [Extract coefficients into polynomial from z] + * 16: end while + * 17: return a + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] seed Seed, rho, to hash to generate values. + * @param [in] eta Range specifier of each value. + * @return 0 on success. + * @return Negative on hash error. + */ +static int dilithium_rej_bound_poly(wc_Shake* shake256, byte* seed, sword32* s, + byte eta) +{ +#ifdef WOLFSSL_DILITHIUM_SMALL + int ret; + unsigned int j = 0; + byte z[DILITHIUM_GEN_S_BLOCK_BYTES]; + + /* Initialize SHAKE-256 object for new hash. */ + ret = wc_InitShake256(shake256, NULL, INVALID_DEVID); + if (ret == 0) { + /* Absorb the seed. */ + ret = wc_Shake256_Absorb(shake256, seed, DILITHIUM_GEN_S_SEED_SZ); + } + if (ret == 0) { + do { + /* Squeeze out another block. */ + ret = wc_Shake256_SqueezeBlocks(shake256, z, 1); + if (ret != 0) { + break; + } + /* Extract up to the 256 valid coefficients for polynomial. */ + dilithium_extract_coeffs(z, DILITHIUM_GEN_S_BLOCK_BYTES, eta, s, + &j); + } + /* Check we got enough values to fill polynomial. */ + while (j < DILITHIUM_N); + } + + return ret; +#else + int ret; + unsigned int j = 0; + byte z[DILITHIUM_GEN_S_BYTES]; + + /* Absorb seed and squeeze out some blocks. */ + ret = dilithium_squeeze256(shake256, seed, DILITHIUM_GEN_S_SEED_SZ, z, + DILITHIUM_GEN_S_NBLOCKS); + if (ret == 0) { + /* Extract up to 256 valid coefficients for polynomial. */ + dilithium_extract_coeffs(z, DILITHIUM_GEN_S_BYTES, eta, s, &j); + /* Check we got enough values to fill polynomial. */ + while (j < DILITHIUM_N) { + /* Squeeze out another block. */ + ret = wc_Shake256_SqueezeBlocks(shake256, z, 1); + if (ret != 0) { + break; + } + /* Extract up to the 256 valid coefficients for polynomial. */ + dilithium_extract_coeffs(z, DILITHIUM_GEN_S_BLOCK_BYTES, eta, s, + &j); + } + } + + return ret; +#endif +} + +/* Expand private seed into vectors s1 and s2. + * + * FIPS 204. 8.3: Algorithm 27 ExpandS(rho) + * 1: for r from 0 to l - 1 do + * 2: s1[r] <- RejBoundedPoly(rho||IntegerToBits(r,16)) + * 3: end for + * 4: for r from 0 to k - 1 do + * 5: s2[r] <- RejBoundedPoly(rho||IntegerToBits(r + l,16)) + * 6: end for + * 7: return (s1,s2) + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] priv_seed Private seed, rho, to expand. + * @param [in] eta Range specifier of each value. + * @param [out] s1 First vector of polynomials. + * @param [in] s1Len Dimension of first vector. + * @param [out] s2 Second vector of polynomials. + * @param [in] s2Len Dimension of second vector. + * @return 0 on success. + * @return Negative on hash error. + */ +static int dilithium_expand_s(wc_Shake* shake256, byte* priv_seed, byte eta, + sword32* s1, byte s1Len, sword32* s2, byte s2Len) +{ + int ret = 0; + byte r; + byte seed[DILITHIUM_GEN_S_SEED_SZ]; + + /* Copy the seed into a buffer that has space for r. */ + XMEMCPY(seed, priv_seed, DILITHIUM_PRIV_SEED_SZ); + /* Set top 8-bits of r in buffer to 0. */ + seed[DILITHIUM_PRIV_SEED_SZ + 1] = 0; + /* Step 1: Each polynomial in s1. */ + for (r = 0; (ret == 0) && (r < s1Len); r++) { + /* Set bottom 8-bits of r into buffer - little endian. */ + seed[DILITHIUM_PRIV_SEED_SZ] = r; + + /* Step 2: Generate polynomial for s1. */ + ret = dilithium_rej_bound_poly(shake256, seed, s1, eta); + /* Next polynomial in s1. */ + s1 += DILITHIUM_N; + } + /* Step 4: Each polynomial in s2. */ + for (r = 0; (ret == 0) && (r < s2Len); r++) { + /* Set bottom 8-bits of r + l into buffer - little endian. */ + seed[DILITHIUM_PRIV_SEED_SZ] = r + s1Len; + /* Step 5: Generate polynomial for s1. */ + ret = dilithium_rej_bound_poly(shake256, seed, s2, eta); + /* Next polynomial in s2. */ + s2 += DILITHIUM_N; + } + + return ret; +} + +#endif /* !WOLFSSL_DILITHIUM_NO_MAKE_KEY */ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* Expand the private random seed into vector y. + * + * FIPS 204. 8.3: Algorithm 28 ExpandMask(rho, mu) + * 1: c <- 1 + bitlen(GAMMA1 - 1) + * 2: for r from 0 to l - 1 do + * 3: n <- IntegerToBits(mu + r, 16) + * 4: v <- (H(rho||n)[[32rc]], H(rho||n)[[32rc + 1]], ..., + * H(rho||n)[[32rc + 32c - 1]]) + * 5: s[r] <- BitUnpack(v, GAMMA-1, GAMMA1) + * 6: end for + * 7: return s + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in, out] seed Buffer containing seed to expand. + * Has space for two bytes to be appended. + * @param [in] kappa Base value to append to seed. + * @param [in] gamma1_bits Number of bits per value. + * @param [out] y Vector of polynomials. + * @param [in] l Dimension of vector. + * @return 0 on success. + * @return Negative on hash error. + */ +static int dilithium_vec_expand_mask(wc_Shake* shake256, byte* seed, + word16 kappa, byte gamma1_bits, sword32* y, byte l) +{ + int ret = 0; + byte r; + byte v[DILITHIUM_MAX_V]; + + /* Step 2: For each polynomial of vector. */ + for (r = 0; (ret == 0) && (r < l); r++) { + /* Step 3: Calculate value to append to seed. */ + word16 n = kappa + r; + + /* Step 4: Append to seed and squeeze out data. */ + seed[DILITHIUM_PRIV_RAND_SEED_SZ + 0] = n; + seed[DILITHIUM_PRIV_RAND_SEED_SZ + 1] = n >> 8; + ret = dilithium_squeeze256(shake256, seed, DILITHIUM_Y_SEED_SZ, v, + DILITHIUM_MAX_V_BLOCKS); + if (ret == 0) { + /* Decode v into polynomial. */ + dilithium_decode_gamma1(v, gamma1_bits, y); + /* Next polynomial. */ + y += DILITHIUM_N; + } + } + + return ret; +} +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* Expand commit to a polynomial. + * + * FIPS 204. 8.3: Algorithm 23 SampleInBall(rho) + * 1: c <- 0 + * 2: k <- 8 + * 3: for i from 256 - TAU to 255 do + * 4: while H(rho)[[k]] > i do + * 5: k <- k + 1 + * 6: end while + * 7: j <- H(rho)[[k]] + * 8: c[i] <- c[j] + * 9: c[j] <- (-1)^H(rho)[i+TAU-256] + * 10: k <- k + 1 + * 11: end for + * 12: return c + * + * @param [in] shake256 SHAKE-256 object. + * @param [in] seed Buffer containing seed to expand. + * @param [in] tau Number of +/- 1s in polynomial. + * @param [out] c Commit polynomial. + * @param [in] key_block Memory to use for block from key. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Negative on hash error. + */ +static int dilithium_sample_in_ball(wc_Shake* shake256, const byte* seed, + byte tau, sword32* c, byte* key_block) +{ + int ret = 0; + unsigned int k; + unsigned int i; + unsigned int s; +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) + byte* block = NULL; +#else + byte block[DILITHIUM_GEN_C_BLOCK_BYTES]; +#endif + byte signs[DILITHIUM_SIGN_BYTES]; + + (void)key_block; + +#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + block = key_block; +#elif defined(WOLFSSL_SMALL_STACK) + block = (byte*)XMALLOC(DILITHIUM_GEN_C_BLOCK_BYTES, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (block == NULL) { + ret = MEMORY_E; + } +#endif + + if (ret == 0) { + /* Set polynomial to all zeros. */ + XMEMSET(c, 0, DILITHIUM_POLY_SIZE); + + /* Generate a block of data from seed. */ + ret = dilithium_shake256(shake256, seed, DILITHIUM_SEED_SZ, block, + DILITHIUM_GEN_C_BLOCK_BYTES); + } + if (ret == 0) { + /* Copy first 8 bytes of first hash block as random sign bits. */ + XMEMCPY(signs, block, DILITHIUM_SIGN_BYTES); + /* Step 1: Initialize sign bit index. */ + s = 0; + /* Step 2: First 8 bytes are used for sign. */ + k = DILITHIUM_SIGN_BYTES; + } + + /* Step 3: Put in TAU +/- 1s. */ + for (i = DILITHIUM_N - tau; (ret == 0) && (i < DILITHIUM_N); i++) { + unsigned int j; + do { + /* Check whether block is exhausted. */ + if (k == DILITHIUM_GEN_C_BLOCK_BYTES) { + /* Generate a new block. */ + ret = wc_Shake256_SqueezeBlocks(shake256, block, 1); + /* Restart hash block index. */ + k = 0; + } + /* Step 7: Get random byte from block as index. + * Step 5 and 10: Increment hash block index. + */ + j = block[k++]; + } + /* Step 4: Get another random if random index is a future swap index. */ + while ((ret == 0) && (j > i)); + + /* Step 8: Move value from random index to current index. */ + c[i] = c[j]; + /* Step 9: Set value at random index to +/- 1. */ + c[j] = 1 - ((((signs[s >> 3]) >> (s & 0x7)) & 0x1) << 1); + /* Next sign bit index. */ + s++; + } + +#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) + XFREE(block, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +} +#endif + +/****************************************************************************** + * Decompose operations + ******************************************************************************/ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Decompose value into high and low based on GAMMA2 being ((q-1) / 88). + * + * FIPS 204. 8.4: Algorithm 30 Decompose(r) + * 1: r+ <- r mod q + * 2: r0 <- r+ mod+/- (2 * GAMMA2) + * 3: if r+ - r0 = q - 1 then + * 4: r1 <- 0 + * 5: r0 <- r0 - 1 + * 6: else r1 <- (r+ - r0) / (2 * GAMMA2) + * 7: end if + * 8: return (r1, r0) + * + * DILITHIUM_Q_LOW_88_2 = 0x2e800 = 0b101110100000000000 + * t1 * DILITHIUM_Q_LOW_88_2 = (t1 << 18) - (t1 << 16) - (t1 << 12) - (t1 << 11) + * = ((93 * t1) << 11) + * Nothing faster than straight multiply. + * + * Implementation using Barrett Reduction. + * + * @param [in] r Value to decompose. + * @param [out] r0 Low bits. + * @param [out] r1 High bits. + */ +static void dilithium_decompose_q88(sword32 r, sword32* r0, sword32* r1) +{ + sword32 t0; + sword32 t1; +#ifdef DILITHIUM_MUL_SLOW + sword32 t2; +#endif + + /* Roundup r and calculate approx high value. */ +#if !defined(DILITHIUM_MUL_44_SLOW) + t1 = ((r * 44) + ((DILITHIUM_Q_LOW_88 - 1) * 44)) >> 23; +#elif !defined(DILITHIUM_MUL_11_SLOW) + t1 = ((r * 11) + ((DILITHIUM_Q_LOW_88 - 1) * 11)) >> 21; +#else + t0 = r + DILITHIUM_Q_LOW_88 - 1; + t1 = ((t0 << 3) + (t0 << 1) + t0) >> 21; +#endif + /* Calculate approx low value. */ + t0 = r - (t1 * DILITHIUM_Q_LOW_88_2); +#ifndef DILITHIUM_MUL_SLOW + /* Calculate real high value, When t0 > modulus, +1 to approx high value. */ + t1 += ((word32)(DILITHIUM_Q_LOW_88 - t0)) >> 31; + /* Calculate real low value. */ + t0 = r - (t1 * DILITHIUM_Q_LOW_88_2); +#else + /* Calculate real high value, When t0 > modulus, +1 to approx high value. */ + t2 = ((word32)(DILITHIUM_Q_LOW_88 - t0)) >> 31; + t1 += t2; + /* Calculate real low value. */ + t0 -= (0 - t2) & DILITHIUM_Q_LOW_88_2; +#endif + /* -1 from low value if high value is 44. Was 43 but low is negative. */ + t0 -= ((word32)(43 - t1)) >> 31; + /* When high value is 44, too large, set to 0. */ + t1 &= 0 - (((word32)(t1 - 44)) >> 31); + + *r0 = t0; + *r1 = t1; +} +#endif + +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Decompose value into high and low based on GAMMA2 being ((q-1) / 32). + * + * FIPS 204. 8.4: Algorithm 30 Decompose(r) + * 1: r+ <- r mod q + * 2: r0 <- r+ mod+/- (2 * GAMMA2) + * 3: if r+ - r0 = q - 1 then + * 4: r1 <- 0 + * 5: r0 <- r0 - 1 + * 6: else r1 <- (r+ - r0) / (2 * GAMMA2) + * 7: end if + * 8: return (r1, r0) + * + * DILITHIUM_Q_LOW_32_2 = 0x7fe00 = 0b1111111111000000000 + * t1 * DILITHIUM_Q_LOW_32_2 = (t1 << 19) - (t1 << 9) + * + * Implementation using Barrett Reduction. + * + * @param [in] r Value to decompose. + * @param [out] r0 Low bits. + * @param [out] r1 High bits. + */ +static void dilithium_decompose_q32(sword32 r, sword32* r0, sword32* r1) +{ + sword32 t0; + sword32 t1; + + /* Roundup r and calculate approx high value. */ + t1 = (r + DILITHIUM_Q_LOW_32 - 1) >> 19; + /* Calculate approx low value. */ + t0 = r - (t1 << 19) + (t1 << 9); + /* Calculate real high value, When t0 > modulus, +1 to approx high value. */ + t1 += ((word32)(DILITHIUM_Q_LOW_32 - t0)) >> 31; + /* Calculate real low value. */ + t0 = r - (t1 << 19) + (t1 << 9); + /* -1 from low value if high value is 16. Was 15 but low is negative. */ + t0 -= t1 >> 4; + /* When high value is 16, too large, set to 0. */ + t1 &= 0xf; + + *r0 = t0; + *r1 = t1; +} +#endif +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +/* Decompose vector of polynomials into high and low based on GAMMA2. + * + * @param [in] r Vector of polynomials to decompose. + * @param [in] k Dimension of vector. + * @param [in] gamma2 Low-order rounding range, GAMMA2. + * @param [out] r0 Low parts in vector of polynomials. + * @param [out] r1 High parts in vector of polynomials. + */ +static void dilithium_vec_decompose(const sword32* r, byte k, sword32 gamma2, + sword32* r0, sword32* r1) +{ + unsigned int i; + unsigned int j; + + (void)k; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (gamma2 == DILITHIUM_Q_LOW_88) { + /* For each polynomial of vector. */ + for (i = 0; i < PARAMS_ML_DSA_44_K; i++) { + /* For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + /* Decompose value into two vectors. */ + dilithium_decompose_q88(r[j], &r0[j], &r1[j]); + } + /* Next polynomial of vectors. */ + r += DILITHIUM_N; + r0 += DILITHIUM_N; + r1 += DILITHIUM_N; + } + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (gamma2 == DILITHIUM_Q_LOW_32) { + /* For each polynomial of vector. */ + for (i = 0; i < k; i++) { + /* For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + /* Decompose value into two vectors. */ + dilithium_decompose_q32(r[j], &r0[j], &r1[j]); + } + /* Next polynomial of vectors. */ + r += DILITHIUM_N; + r0 += DILITHIUM_N; + r1 += DILITHIUM_N; + } + } + else +#endif + { + } +} +#endif + +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +/****************************************************************************** + * Range check operation + ******************************************************************************/ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* Check that the values of the polynomial are in range. + * + * Many places in FIPS 204. One example from Algorithm 2: + * 23: if ||z||inf >= GAMMA1 - BETA or ..., then (z, h) = falsam + * + * @param [in] a Polynomial. + * @param [in] hi Largest value in range. + */ +static int dilithium_check_low(const sword32* a, sword32 hi) +{ + int ret = 1; + unsigned int j; + /* Calculate lowest range value. */ + sword32 nhi = -hi; + + /* For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + /* Check range is -(hi-1)..(hi-1). */ + if ((a[j] <= nhi) || (a[j] >= hi)) { + /* Check failed. */ + ret = 0; + break; + } + } + + return ret; +} + +#if (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Check that the values of the vector are in range. + * + * Many places in FIPS 204. One example from Algorithm 2: + * 23: if ||z||inf >= GAMMA1 - BETA or ..., then (z, h) = falsam + * + * @param [in] a Vector of polynomials. + * @param [in] l Dimension of vector. + * @param [in] hi Largest value in range. + */ +static int dilithium_vec_check_low(const sword32* a, byte l, sword32 hi) +{ + int ret = 1; + unsigned int i; + + /* For each polynomial of vector. */ + for (i = 0; (ret == 1) && (i < l); i++) { + ret = dilithium_check_low(a, hi); + if (ret == 0) { + break; + } + /* Next polynomial. */ + a += DILITHIUM_N; + } + + return ret; +} +#endif +#endif + +/****************************************************************************** + * Hint operations + ******************************************************************************/ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Compute hints indicating whether adding ct0 to w alters high bits of w. + * + * FIPS 204. 6: Algorithm 2 ML-DSA.Sign(sk, M) + * ... + * 26: h <- MakeHint(-<>, w - <> + <>) + * 27: if ... or the number of 1's in h is greater than OMEGA, then + * (z, h) <- falsam + * ... + * 32: sigma <- sigEncode(c_tilda, z mod+/- q, h) + * ... + * + * FIPS 204. 8.4: Algorithm 33 MakeHint(z, r) + * 1: r1 <- HighBits(r) + * 2: v1 <- HightBits(r+z) + * 3: return [[r1 != v1]] + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 5: sigma <- sigma || HintBitPack(h) + * ... + * + * FIPS 204. 8.1: Algorithm 14 HintBitPack(h) + * ... + * 4: for j from 0 to 255 do + * 5: if h[i]j != 0 then + * 6: y[Index] <- j + * 7: Index <- Index + 1 + * 8: end if + * 9: end for + * ... + * + * @param [in] s Vector of polynomials that is sum of ct0 and w0. + * @param [in] w1 Vector of polynomials that is high part of w. + * @param [out] h Encoded hints. + * @param [in, out] idxp Index to write next hint into. + * return Number of hints on success. + * return Falsam of -1 when too many hints. + */ +static int dilithium_make_hint_88(const sword32* s, const sword32* w1, byte* h, + byte *idxp) +{ + unsigned int j; + byte idx = *idxp; + + /* Alg 14, Step 3: For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + /* Alg 14, Step 4: Check whether hint is required. + * Did sum end up greater than low modulus or + * sum end up less than the negative of low modulus or + * sum is the negative of the low modulus and w1 is not zero, + * then w1 will be modified. + */ + if ((s[j] > (sword32)DILITHIUM_Q_LOW_88) || + (s[j] < -(sword32)DILITHIUM_Q_LOW_88) || + ((s[j] == -(sword32)DILITHIUM_Q_LOW_88) && + (w1[j] != 0))) { + /* Alg 14, Step 6, 7: Put index as hint modifier. */ + h[idx++] = (byte)j; + /* Alg 2, Step 27: If there are too many hints, return + * falsam of -1. */ + if (idx > PARAMS_ML_DSA_44_OMEGA) { + return -1; + } + } + } + + *idxp = idx; + return 0; +} +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Compute hints indicating whether adding ct0 to w alters high bits of w. + * + * FIPS 204. 6: Algorithm 2 ML-DSA.Sign(sk, M) + * ... + * 26: h <- MakeHint(-<>, w - <> + <>) + * 27: if ... or the number of 1's in h is greater than OMEGA, then + * (z, h) <- falsam + * ... + * 32: sigma <- sigEncode(c_tilda, z mod+/- q, h) + * ... + * + * FIPS 204. 8.4: Algorithm 33 MakeHint(z, r) + * 1: r1 <- HighBits(r) + * 2: v1 <- HightBits(r+z) + * 3: return [[r1 != v1]] + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 5: sigma <- sigma || HintBitPack(h) + * ... + * + * FIPS 204. 8.1: Algorithm 14 HintBitPack(h) + * ... + * 4: for j from 0 to 255 do + * 5: if h[i]j != 0 then + * 6: y[Index] <- j + * 7: Index <- Index + 1 + * 8: end if + * 9: end for + * ... + * + * @param [in] s Vector of polynomials that is sum of ct0 and w0. + * @param [in] w1 Vector of polynomials that is high part of w. + * @param [in] omega Maximum number of hints allowed. + * @param [out] h Encoded hints. + * @param [in, out] idxp Index to write next hint into. + * return Number of hints on success. + * return Falsam of -1 when too many hints. + */ +static int dilithium_make_hint_32(const sword32* s, const sword32* w1, + byte omega, byte* h, byte *idxp) +{ + unsigned int j; + byte idx = *idxp; + + (void)omega; + + /* Alg 14, Step 3: For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + /* Alg 14, Step 4: Check whether hint is required. + * Did sum end up greater than low modulus or + * sum end up less than the negative of low modulus or + * sum is the negative of the low modulus and w1 is not zero, + * then w1 will be modified. + */ + if ((s[j] > (sword32)DILITHIUM_Q_LOW_32) || + (s[j] < -(sword32)DILITHIUM_Q_LOW_32) || + ((s[j] == -(sword32)DILITHIUM_Q_LOW_32) && + (w1[j] != 0))) { + /* Alg 14, Step 6, 7: Put index as hint modifier. */ + h[idx++] = (byte)j; + /* Alg 2, Step 27: If there are too many hints, return + * falsam of -1. */ + if (idx > omega) { + return -1; + } + } + } + + *idxp = idx; + return 0; +} +#endif + +#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +/* Compute hints indicating whether adding ct0 to w alters high bits of w. + * + * FIPS 204. 6: Algorithm 2 ML-DSA.Sign(sk, M) + * ... + * 26: h <- MakeHint(-<>, w - <> + <>) + * 27: if ... or the number of 1's in h is greater than OMEGA, then + * (z, h) <- falsam + * ... + * 32: sigma <- sigEncode(c_tilda, z mod+/- q, h) + * ... + * + * FIPS 204. 8.4: Algorithm 33 MakeHint(z, r) + * 1: r1 <- HighBits(r) + * 2: v1 <- HightBits(r+z) + * 3: return [[r1 != v1]] + * + * FIPS 204. 8.2: Algorithm 20 sigEncode(c_tilde, z, h) + * ... + * 5: sigma <- sigma || HintBitPack(h) + * ... + * + * FIPS 204. 8.1: Algorithm 14 HintBitPack(h) + * ... + * 2: Index <- 0 + * 3. for i from 0 to k - 1 do + * 4: for j from 0 to 255 do + * 5: if h[i]j != 0 then + * 6: y[Index] <- j + * 7: Index <- Index + 1 + * 8: end if + * 9: end for + * 10: y[OMEGA + i] <- Index + * 11: end for + * 12: return y + * + * @param [in] s Vector of polynomials that is sum of ct0 and w0. + * @param [in] w1 Vector of polynomials that is high part of w. + * @param [in] k Dimension of vectors. + * @param [in] gamma2 Low-order rounding range, GAMMA2. + * @param [in] omega Maximum number of hints allowed. + * @param [out] h Encoded hints. + * return Number of hints on success. + * return Falsam of -1 when too many hints. + */ +static int dilithium_make_hint(const sword32* s, const sword32* w1, byte k, + word32 gamma2, byte omega, byte* h) +{ + unsigned int i; + byte idx = 0; + + (void)k; + (void)omega; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (gamma2 == DILITHIUM_Q_LOW_88) { + /* Alg 14, Step 2: For each polynomial of vector. */ + for (i = 0; i < PARAMS_ML_DSA_44_K; i++) { + if (dilithium_make_hint_88(s, w1, h, &idx) == -1) { + return -1; + } + /* Alg 14, Step 10: Store count of hints for polynomial at end of + * list. */ + h[PARAMS_ML_DSA_44_OMEGA + i] = idx; + /* Next polynomial. */ + s += DILITHIUM_N; + w1 += DILITHIUM_N; + } + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (gamma2 == DILITHIUM_Q_LOW_32) { + /* Alg 14, Step 2: For each polynomial of vector. */ + for (i = 0; i < k; i++) { + if (dilithium_make_hint_32(s, w1, omega, h, &idx) == -1) { + return -1; + } + /* Alg 14, Step 10: Store count of hints for polynomial at end of + * list. */ + h[omega + i] = idx; + /* Next polynomial. */ + s += DILITHIUM_N; + w1 += DILITHIUM_N; + } + } + else +#endif + { + } + + /* Set remaining hints to zero. */ + XMEMSET(h + idx, 0, omega - idx); + return idx; +} +#endif /* !WOLFSSL_DILITHIUM_SIGN_SMALL_MEM */ + +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* Check that the hints are valid. + * + * @param [in] h Hints to check + * @param [in] k Dimension of vector. + * @param [in] omega Maximum number of hints. Hint counts after this index. + * @return 0 when hints valid. + * @return SIG_VERIFY_E when hints invalid. + */ +static int dilithium_check_hint(const byte* h, byte k, byte omega) +{ + int ret = 0; + unsigned int o = 0; + unsigned int i; + + /* Skip polynomial index while count is 0. */ + while ((h[omega + o] == 0) && (o < k)) { + o++; + } + /* Check all possible hints. */ + for (i = 1; i < omega; i++) { + /* Done with polynomial if index equals count of hints. */ + if (i == h[omega + o]) { + /* Next polynomial index while count is index. */ + do { + o++; + } + while ((o < k) && (i == h[omega + o])); + /* Stop if hints for all polynomials checked. */ + if (o == k) { + break; + } + } + /* Ensure the last hint is less than the current hint. */ + else if (h[i - 1] > h[i]) { + ret = SIG_VERIFY_E; + break; + } + } + if (ret == 0) { + /* Use up any sizes that are the last element. */ + while ((o < k) && (i == h[omega + o])) { + o++; + } + /* Ensure all sizes were used. */ + if (o != k) { + ret = SIG_VERIFY_E; + } + } + /* Check remaining hints are 0. */ + for (; (ret == 0) && (i < omega); i++) { + if (h[i] != 0) { + ret = SIG_VERIFY_E; + } + } + + return ret; +} + +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Use hints to modify w1. + * + * FIPS 204. 8.4: Algorithm 34 UseHint(h, r) + * 1: m <- (q - 1) / (2 * GAMMA2) + * 2: (r1, r0) <- Decompose(r) + * 3: if h == 1 and r0 > 0 return (r1 + 1) mod m + * 4: if h == 1 and r0 <= 0 return (r1 - 1) mod m + * 5: return r1 + * + * @param [in, out] w1 Vector of polynomials needing hints applied to. + * @param [in] h Hints to apply. In signature encoding. + * @param [in] i Dimension index. + * @param [in, out] op Pointer to current offset into hints. + */ +static void dilithium_use_hint_88(sword32* w1, const byte* h, unsigned int i, + byte* op) +{ + byte o = *op; + unsigned int j; + + /* For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + sword32 r; + sword32 r0; + sword32 r1; +#ifdef DILITHIUM_USE_HINT_CT + /* Hint is 1 when index is next in hint list. */ + sword32 hint = ((o < h[PARAMS_ML_DSA_44_OMEGA + i]) & + (h[o] == (byte)j)); + + /* Increment hint offset if this index has hint. */ + o += hint; + /* Convert value to positive only range. */ + r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + /* Decompose value into low and high parts. */ + dilithium_decompose_q88(r, &r0, &r1); + /* Make hint positive or negative based on sign of r0. */ + hint = (1 - (2 * (((word32)r0) >> 31))) & (0 - hint); + /* Make w1 only the top part plus the hint. */ + w1[j] = r1 + hint; + + /* Fix up w1 to not be 44 but 0. */ + w1[j] &= 0 - (((word32)(w1[j] - 44)) >> 31); + /* Hint may have reduced 0 to -1 which is actually 43. */ + w1[j] += (0 - (((word32)w1[j]) >> 31)) & 44; +#else + /* Convert value to positive only range. */ + r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + /* Decompose value into low and high parts. */ + dilithium_decompose_q88(r, &r0, &r1); + /* Check for hint. */ + if ((o < h[PARAMS_ML_DSA_44_OMEGA + i]) && (h[o] == (byte)j)) { + /* Add or subtrac hint based on sign of r0. */ + r1 += 1 - (2 * (((word32)r0) >> 31)); + /* Go to next hint offset. */ + o++; + } + /* Fix up w1 to not be 44 but 0. */ + r1 &= 0 - (((word32)(r1 - 44)) >> 31); + /* Hint may have reduced 0 to -1 which is actually 43. */ + r1 += (0 - (((word32)r1) >> 31)) & 44; + /* Make w1 only the top part plus any hint. */ + w1[j] = r1; +#endif + } + *op = o; +} +#endif /* !WOLFSSL_NO_ML_DSA_44 */ + +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) +/* Use hints to modify w1. + * + * FIPS 204. 8.4: Algorithm 34 UseHint(h, r) + * 1: m <- (q - 1) / (2 * GAMMA2) + * 2: (r1, r0) <- Decompose(r) + * 3: if h == 1 and r0 > 0 return (r1 + 1) mod m + * 4: if h == 1 and r0 <= 0 return (r1 - 1) mod m + * 5: return r1 + * + * @param [in, out] w1 Vector of polynomials needing hints applied to. + * @param [in] h Hints to apply. In signature encoding. + * @param [in] omega Max number of hints. Hint counts after this index. + * @param [in] i Dimension index. + * @param [in, out] op Pointer to current offset into hints. + */ +static void dilithium_use_hint_32(sword32* w1, const byte* h, byte omega, + unsigned int i, byte* op) +{ + byte o = *op; + unsigned int j; + + /* For each value of polynomial. */ + for (j = 0; j < DILITHIUM_N; j++) { + sword32 r; + sword32 r0; + sword32 r1; +#ifdef DILITHIUM_USE_HINT_CT + /* Hint is 1 when index is next in hint list. */ + sword32 hint = ((o < h[omega + i]) & (h[o] == (byte)j)); + + /* Increment hint offset if this index has hint. */ + o += hint; + /* Convert value to positive only range. */ + r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + /* Decompose value into low and high parts. */ + dilithium_decompose_q32(r, &r0, &r1); + /* Make hint positive or negative based on sign of r0. */ + hint = (1 - (2 * (((word32)r0) >> 31))) & (0 - hint); + /* Make w1 only the top part plus the hint. */ + w1[j] = r1 + hint; + + /* Fix up w1 not be 16 (-> 0) or -1 (-> 15). */ + w1[j] &= 0xf; +#else + /* Convert value to positive only range. */ + r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + /* Decompose value into low and high parts. */ + dilithium_decompose_q32(r, &r0, &r1); + /* Check for hint. */ + if ((o < h[omega + i]) && (h[o] == (byte)j)) { + /* Add or subtract hint based on sign of r0. */ + r1 += 1 - (2 * (((word32)r0) >> 31)); + /* Go to next hint offset. */ + o++; + } + /* Fix up w1 not be 16 (-> 0) or -1 (-> 15). */ + w1[j] = r1 & 0xf; +#endif + } + *op = o; +} +#endif + +#ifndef WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM +/* Use hints to modify w1. + * + * FIPS 204. 8.4: Algorithm 34 UseHint(h, r) + * 1: m <- (q - 1) / (2 * GAMMA2) + * 2: (r1, r0) <- Decompose(r) + * 3: if h == 1 and r0 > 0 return (r1 + 1) mod m + * 4: if h == 1 and r0 <= 0 return (r1 - 1) mod m + * 5: return r1 + * + * @param [in, out] w1 Vector of polynomials needing hints applied to. + * @param [in] k Dimension of vector. + * @param [in] gamma2 Low-order rounding range, GAMMA2. + * @param [in] omega Max number of hints. Hint counts after this index. + * @param [in] h Hints to apply. In signature encoding. + */ +static void dilithium_vec_use_hint(sword32* w1, byte k, word32 gamma2, + byte omega, const byte* h) +{ + unsigned int i; + byte o = 0; + + (void)k; + (void)omega; + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (gamma2 == DILITHIUM_Q_LOW_88) { + /* For each polynomial of vector. */ + for (i = 0; i < PARAMS_ML_DSA_44_K; i++) { + dilithium_use_hint_88(w1, h, i, &o); + w1 += DILITHIUM_N; + } + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (gamma2 == DILITHIUM_Q_LOW_32) { + /* For each polynomial of vector. */ + for (i = 0; i < k; i++) { + dilithium_use_hint_32(w1, h, omega, i, &o); + w1 += DILITHIUM_N; + } + } + else +#endif + { + } +} +#endif +#endif /* !WOLFSSL_DILITHIUM_NO_VERIFY */ + +/****************************************************************************** + * Maths operations + ******************************************************************************/ + +/* q^-1 mod 2^32 (inverse of 8380417 mod 2^32 = 58728449 = 0x3802001) */ +#define DILITHIUM_QINV 58728449 + +/* Montgomery reduce a. + * + * @param [in] a 64-bit value to be reduced. + * @return Montgomery reduction result. + */ +static sword32 dilithium_mont_red(sword64 a) +{ +#ifndef DILITHIUM_MUL_QINV_SLOW + sword64 t = (sword32)((sword32)a * (sword32)DILITHIUM_QINV); +#else + sword64 t = (sword32)((sword32)a + (sword32)((sword32)a << 13) - + (sword32)((sword32)a << 23) + (sword32)((sword32)a << 26)); +#endif +#ifndef DILITHIUM_MUL_Q_SLOW + return (sword32)((a - ((sword32)t * (sword64)DILITHIUM_Q)) >> 32); +#else + return (sword32)((a - (t << 23) + (t << 13) - t) >> 32); +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_SMALL) || !defined(WOLFSSL_DILITHIUM_NO_SIGN) + +/* Reduce 32-bit a modulo q. r = a mod q. + * + * @param [in] a 32-bit value to be reduced to range of q. + * @return Modulo result. + */ +static sword32 dilithium_red(sword32 a) +{ + sword32 t = (sword32)((a + (1 << 22)) >> 23); +#ifndef DILITHIUM_MUL_Q_SLOW + return (sword32)(a - (t * DILITHIUM_Q)); +#else + return (sword32)(a - (t << 23) + (t << 13) - t); +#endif +} + +#endif /* !WOLFSSL_DILITHIUM_SMALL || !WOLFSSL_DILITHIUM_NO_SIGN */ + +/* Zetas for NTT. */ +static const sword32 zetas[DILITHIUM_N] = { + -41978, 25847, -2608894, -518909, 237124, -777960, -876248, 466468, + 1826347, 2353451, -359251, -2091905, 3119733, -2884855, 3111497, 2680103, + 2725464, 1024112, -1079900, 3585928, -549488, -1119584, 2619752, -2108549, + -2118186, -3859737, -1399561, -3277672, 1757237, -19422, 4010497, 280005, + 2706023, 95776, 3077325, 3530437, -1661693, -3592148, -2537516, 3915439, + -3861115, -3043716, 3574422, -2867647, 3539968, -300467, 2348700, -539299, + -1699267, -1643818, 3505694, -3821735, 3507263, -2140649, -1600420, 3699596, + 811944, 531354, 954230, 3881043, 3900724, -2556880, 2071892, -2797779, + -3930395, -1528703, -3677745, -3041255, -1452451, 3475950, 2176455, -1585221, + -1257611, 1939314, -4083598, -1000202, -3190144, -3157330, -3632928, 126922, + 3412210, -983419, 2147896, 2715295, -2967645, -3693493, -411027, -2477047, + -671102, -1228525, -22981, -1308169, -381987, 1349076, 1852771, -1430430, + -3343383, 264944, 508951, 3097992, 44288, -1100098, 904516, 3958618, + -3724342, -8578, 1653064, -3249728, 2389356, -210977, 759969, -1316856, + 189548, -3553272, 3159746, -1851402, -2409325, -177440, 1315589, 1341330, + 1285669, -1584928, -812732, -1439742, -3019102, -3881060, -3628969, 3839961, + 2091667, 3407706, 2316500, 3817976, -3342478, 2244091, -2446433, -3562462, + 266997, 2434439, -1235728, 3513181, -3520352, -3759364, -1197226, -3193378, + 900702, 1859098, 909542, 819034, 495491, -1613174, -43260, -522500, + -655327, -3122442, 2031748, 3207046, -3556995, -525098, -768622, -3595838, + 342297, 286988, -2437823, 4108315, 3437287, -3342277, 1735879, 203044, + 2842341, 2691481, -2590150, 1265009, 4055324, 1247620, 2486353, 1595974, + -3767016, 1250494, 2635921, -3548272, -2994039, 1869119, 1903435, -1050970, + -1333058, 1237275, -3318210, -1430225, -451100, 1312455, 3306115, -1962642, + -1279661, 1917081, -2546312, -1374803, 1500165, 777191, 2235880, 3406031, + -542412, -2831860, -1671176, -1846953, -2584293, -3724270, 594136, -3776993, + -2013608, 2432395, 2454455, -164721, 1957272, 3369112, 185531, -1207385, + -3183426, 162844, 1616392, 3014001, 810149, 1652634, -3694233, -1799107, + -3038916, 3523897, 3866901, 269760, 2213111, -975884, 1717735, 472078, + -426683, 1723600, -1803090, 1910376, -1667432, -1104333, -260646, -3833893, + -2939036, -2235985, -420899, -2286327, 183443, -976891, 1612842, -3545687, + -554416, 3919660, -48306, -1362209, 3937738, 1400424, -846154, 1976782 +}; + +#ifndef WOLFSSL_DILITHIUM_SMALL +/* Zetas for inverse NTT. */ +static const sword32 zetas_inv[DILITHIUM_N] = { + -1976782, 846154, -1400424, -3937738, 1362209, 48306, -3919660, 554416, + 3545687, -1612842, 976891, -183443, 2286327, 420899, 2235985, 2939036, + 3833893, 260646, 1104333, 1667432, -1910376, 1803090, -1723600, 426683, + -472078, -1717735, 975884, -2213111, -269760, -3866901, -3523897, 3038916, + 1799107, 3694233, -1652634, -810149, -3014001, -1616392, -162844, 3183426, + 1207385, -185531, -3369112, -1957272, 164721, -2454455, -2432395, 2013608, + 3776993, -594136, 3724270, 2584293, 1846953, 1671176, 2831860, 542412, + -3406031, -2235880, -777191, -1500165, 1374803, 2546312, -1917081, 1279661, + 1962642, -3306115, -1312455, 451100, 1430225, 3318210, -1237275, 1333058, + 1050970, -1903435, -1869119, 2994039, 3548272, -2635921, -1250494, 3767016, + -1595974, -2486353, -1247620, -4055324, -1265009, 2590150, -2691481, -2842341, + -203044, -1735879, 3342277, -3437287, -4108315, 2437823, -286988, -342297, + 3595838, 768622, 525098, 3556995, -3207046, -2031748, 3122442, 655327, + 522500, 43260, 1613174, -495491, -819034, -909542, -1859098, -900702, + 3193378, 1197226, 3759364, 3520352, -3513181, 1235728, -2434439, -266997, + 3562462, 2446433, -2244091, 3342478, -3817976, -2316500, -3407706, -2091667, + -3839961, 3628969, 3881060, 3019102, 1439742, 812732, 1584928, -1285669, + -1341330, -1315589, 177440, 2409325, 1851402, -3159746, 3553272, -189548, + 1316856, -759969, 210977, -2389356, 3249728, -1653064, 8578, 3724342, + -3958618, -904516, 1100098, -44288, -3097992, -508951, -264944, 3343383, + 1430430, -1852771, -1349076, 381987, 1308169, 22981, 1228525, 671102, + 2477047, 411027, 3693493, 2967645, -2715295, -2147896, 983419, -3412210, + -126922, 3632928, 3157330, 3190144, 1000202, 4083598, -1939314, 1257611, + 1585221, -2176455, -3475950, 1452451, 3041255, 3677745, 1528703, 3930395, + 2797779, -2071892, 2556880, -3900724, -3881043, -954230, -531354, -811944, + -3699596, 1600420, 2140649, -3507263, 3821735, -3505694, 1643818, 1699267, + 539299, -2348700, 300467, -3539968, 2867647, -3574422, 3043716, 3861115, + -3915439, 2537516, 3592148, 1661693, -3530437, -3077325, -95776, -2706023, + -280005, -4010497, 19422, -1757237, 3277672, 1399561, 3859737, 2118186, + 2108549, -2619752, 1119584, 549488, -3585928, 1079900, -1024112, -2725464, + -2680103, -3111497, 2884855, -3119733, 2091905, 359251, -2353451, -1826347, + -466468, 876248, 777960, -237124, 518909, 2608894, -25847, 41978 +}; +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_MAKE) && defined(WOLFSSL_DILITHIUM_SMALL)) + +/* One iteration of Number-Theoretic Transform. + * + * @param [in] len Length of sequence. + */ +#define NTT(len) \ +do { \ + for (start = 0; start < DILITHIUM_N; start += 2 * (len)) { \ + zeta = zetas[++k]; \ + for (j = 0; j < (len); ++j) { \ + sword32 t = \ + dilithium_mont_red((sword64)zeta * r[start + j + (len)]); \ + sword32 rj = r[start + j]; \ + r[start + j + (len)] = rj - t; \ + r[start + j] = rj + t; \ + } \ + } \ +} \ +while (0) + +/* Number-Theoretic Transform. + * + * @param [in, out] r Polynomial to transform. + */ +static void dilithium_ntt(sword32* r) +{ +#ifdef WOLFSSL_DILITHIUM_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + + k = 0; + for (len = DILITHIUM_N / 2; len >= 1; len >>= 1) { + unsigned int start; + for (start = 0; start < DILITHIUM_N; start = j + len) { + sword32 zeta = zetas[++k]; + for (j = start; j < start + len; ++j) { + sword32 t = dilithium_mont_red((sword64)zeta * r[j + len]); + sword32 rj = r[j]; + r[j + len] = rj - t; + r[j] = rj + t; + } + } + } +#elif defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) + unsigned int j; + unsigned int k; + unsigned int start; + sword32 zeta; + + zeta = zetas[1]; + for (j = 0; j < DILITHIUM_N / 2; j++) { + sword32 t = + dilithium_mont_red((sword64)zeta * r[j + DILITHIUM_N / 2]); + sword32 rj = r[j]; + r[j + DILITHIUM_N / 2] = rj - t; + r[j] = rj + t; + } + + k = 1; + NTT(64); + NTT(32); + NTT(16); + NTT(8); + NTT(4); + NTT(2); + + for (j = 0; j < DILITHIUM_N; j += 2) { + sword32 t = dilithium_mont_red((sword64)zetas[++k] * r[j + 1]); + sword32 rj = r[j]; + r[j + 1] = rj - t; + r[j] = rj + t; + } +#elif defined(WC_32BIT_CPU) + unsigned int j; + unsigned int k; + sword32 t0; + sword32 t2; + + sword32 zeta128 = zetas[1]; + sword32 zeta640 = zetas[2]; + sword32 zeta641 = zetas[3]; + for (j = 0; j < DILITHIUM_N / 4; j++) { + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 64]; + sword32 r4 = r[j + 128]; + sword32 r6 = r[j + 192]; + + t0 = dilithium_mont_red((sword64)zeta128 * r4); + t2 = dilithium_mont_red((sword64)zeta128 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta640 * r2); + t2 = dilithium_mont_red((sword64)zeta641 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + 0] = r0; + r[j + 64] = r2; + r[j + 128] = r4; + r[j + 192] = r6; + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta32 = zetas[ 4 + j / 64 + 0]; + sword32 zeta160 = zetas[ 8 + j / 32 + 0]; + sword32 zeta161 = zetas[ 8 + j / 32 + 1]; + for (i = 0; i < 16; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 16]; + sword32 r4 = r[j + i + 32]; + sword32 r6 = r[j + i + 48]; + + t0 = dilithium_mont_red((sword64)zeta32 * r4); + t2 = dilithium_mont_red((sword64)zeta32 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta160 * r2); + t2 = dilithium_mont_red((sword64)zeta161 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + i + 0] = r0; + r[j + i + 16] = r2; + r[j + i + 32] = r4; + r[j + i + 48] = r6; + } + } + + for (j = 0; j < DILITHIUM_N; j += 16) { + int i; + sword32 zeta8 = zetas[16 + j / 16]; + sword32 zeta40 = zetas[32 + j / 8 + 0]; + sword32 zeta41 = zetas[32 + j / 8 + 1]; + for (i = 0; i < 4; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 4]; + sword32 r4 = r[j + i + 8]; + sword32 r6 = r[j + i + 12]; + + t0 = dilithium_mont_red((sword64)zeta8 * r4); + t2 = dilithium_mont_red((sword64)zeta8 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta40 * r2); + t2 = dilithium_mont_red((sword64)zeta41 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + i + 0] = r0; + r[j + i + 4] = r2; + r[j + i + 8] = r4; + r[j + i + 12] = r6; + } + } + + k = 128; + for (j = 0; j < DILITHIUM_N; j += 4) { + sword32 zeta2 = zetas[64 + j / 4]; + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 1]; + sword32 r4 = r[j + 2]; + sword32 r6 = r[j + 3]; + + t0 = dilithium_mont_red((sword64)zeta2 * r4); + t2 = dilithium_mont_red((sword64)zeta2 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zetas[k++] * r2); + t2 = dilithium_mont_red((sword64)zetas[k++] * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + 0] = r0; + r[j + 1] = r2; + r[j + 2] = r4; + r[j + 3] = r6; + } +#else + unsigned int j; + unsigned int k; + sword32 t0; + sword32 t1; + sword32 t2; + sword32 t3; + + sword32 zeta128 = zetas[1]; + sword32 zeta640 = zetas[2]; + sword32 zeta641 = zetas[3]; + for (j = 0; j < DILITHIUM_N / 8; j++) { + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 32]; + sword32 r2 = r[j + 64]; + sword32 r3 = r[j + 96]; + sword32 r4 = r[j + 128]; + sword32 r5 = r[j + 160]; + sword32 r6 = r[j + 192]; + sword32 r7 = r[j + 224]; + + t0 = dilithium_mont_red((sword64)zeta128 * r4); + t1 = dilithium_mont_red((sword64)zeta128 * r5); + t2 = dilithium_mont_red((sword64)zeta128 * r6); + t3 = dilithium_mont_red((sword64)zeta128 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta640 * r2); + t1 = dilithium_mont_red((sword64)zeta640 * r3); + t2 = dilithium_mont_red((sword64)zeta641 * r6); + t3 = dilithium_mont_red((sword64)zeta641 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta32 = zetas[ 4 + j / 64 + 0]; + sword32 zeta160 = zetas[ 8 + j / 32 + 0]; + sword32 zeta161 = zetas[ 8 + j / 32 + 1]; + sword32 zeta80 = zetas[16 + j / 16 + 0]; + sword32 zeta81 = zetas[16 + j / 16 + 1]; + sword32 zeta82 = zetas[16 + j / 16 + 2]; + sword32 zeta83 = zetas[16 + j / 16 + 3]; + for (i = 0; i < 8; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r1 = r[j + i + 8]; + sword32 r2 = r[j + i + 16]; + sword32 r3 = r[j + i + 24]; + sword32 r4 = r[j + i + 32]; + sword32 r5 = r[j + i + 40]; + sword32 r6 = r[j + i + 48]; + sword32 r7 = r[j + i + 56]; + + t0 = dilithium_mont_red((sword64)zeta32 * r4); + t1 = dilithium_mont_red((sword64)zeta32 * r5); + t2 = dilithium_mont_red((sword64)zeta32 * r6); + t3 = dilithium_mont_red((sword64)zeta32 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta160 * r2); + t1 = dilithium_mont_red((sword64)zeta160 * r3); + t2 = dilithium_mont_red((sword64)zeta161 * r6); + t3 = dilithium_mont_red((sword64)zeta161 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = dilithium_mont_red((sword64)zeta80 * r1); + t1 = dilithium_mont_red((sword64)zeta81 * r3); + t2 = dilithium_mont_red((sword64)zeta82 * r5); + t3 = dilithium_mont_red((sword64)zeta83 * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + k = 128; + for (j = 0; j < DILITHIUM_N; j += 8) { + sword32 zeta4 = zetas[32 + j / 8 + 0]; + sword32 zeta20 = zetas[64 + j / 4 + 0]; + sword32 zeta21 = zetas[64 + j / 4 + 1]; + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 1]; + sword32 r2 = r[j + 2]; + sword32 r3 = r[j + 3]; + sword32 r4 = r[j + 4]; + sword32 r5 = r[j + 5]; + sword32 r6 = r[j + 6]; + sword32 r7 = r[j + 7]; + + t0 = dilithium_mont_red((sword64)zeta4 * r4); + t1 = dilithium_mont_red((sword64)zeta4 * r5); + t2 = dilithium_mont_red((sword64)zeta4 * r6); + t3 = dilithium_mont_red((sword64)zeta4 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta20 * r2); + t1 = dilithium_mont_red((sword64)zeta20 * r3); + t2 = dilithium_mont_red((sword64)zeta21 * r6); + t3 = dilithium_mont_red((sword64)zeta21 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = dilithium_mont_red((sword64)zetas[k++] * r1); + t1 = dilithium_mont_red((sword64)zetas[k++] * r3); + t2 = dilithium_mont_red((sword64)zetas[k++] * r5); + t3 = dilithium_mont_red((sword64)zetas[k++] * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + 0] = r0; + r[j + 1] = r1; + r[j + 2] = r2; + r[j + 3] = r3; + r[j + 4] = r4; + r[j + 5] = r5; + r[j + 6] = r6; + r[j + 7] = r7; + } +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_NO_VERIFY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + (defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) || \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM))) +/* Number-Theoretic Transform. + * + * @param [in, out] r Vector of polynomials to transform. + * @param [in] l Dimension of polynomial. + */ +static void dilithium_vec_ntt(sword32* r, byte l) +{ + unsigned int i; + + for (i = 0; i < l; i++) { + dilithium_ntt(r); + r += DILITHIUM_N; + } +} +#endif +#endif + +#ifndef WOLFSSL_DILITHIUM_SMALL + +/* Number-Theoretic Transform with small initial values. + * + * @param [in, out] r Polynomial to transform. + */ +static void dilithium_ntt_small(sword32* r) +{ + unsigned int k; + unsigned int j; +#ifdef WOLFSSL_DILITHIUM_NO_LARGE_CODE + unsigned int start; + sword32 zeta; + + for (j = 0; j < DILITHIUM_N / 2; ++j) { + sword32 t = dilithium_red((sword32)-3572223 * r[j + DILITHIUM_N / 2]); + sword32 rj = r[j]; + r[j + DILITHIUM_N / 2] = rj - t; + r[j] = rj + t; + } + + k = 1; + NTT(64); + NTT(32); + NTT(16); + NTT(8); + NTT(4); + NTT(2); + + for (j = 0; j < DILITHIUM_N; j += 2) { + sword32 t = dilithium_mont_red((sword64)zetas[++k] * r[j + 1]); + sword32 rj = r[j]; + r[j + 1] = rj - t; + r[j] = rj + t; + } +#elif defined(WC_32BIT_CPU) + sword32 t0; + sword32 t2; + + sword32 zeta640 = zetas[2]; + sword32 zeta641 = zetas[3]; + for (j = 0; j < DILITHIUM_N / 4; j++) { + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 64]; + sword32 r4 = r[j + 128]; + sword32 r6 = r[j + 192]; + + t0 = dilithium_red((sword32)-3572223 * r4); + t2 = dilithium_red((sword32)-3572223 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta640 * r2); + t2 = dilithium_mont_red((sword64)zeta641 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + 0] = r0; + r[j + 64] = r2; + r[j + 128] = r4; + r[j + 192] = r6; + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta32 = zetas[ 4 + j / 64 + 0]; + sword32 zeta160 = zetas[ 8 + j / 32 + 0]; + sword32 zeta161 = zetas[ 8 + j / 32 + 1]; + for (i = 0; i < 16; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 16]; + sword32 r4 = r[j + i + 32]; + sword32 r6 = r[j + i + 48]; + + t0 = dilithium_mont_red((sword64)zeta32 * r4); + t2 = dilithium_mont_red((sword64)zeta32 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta160 * r2); + t2 = dilithium_mont_red((sword64)zeta161 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + i + 0] = r0; + r[j + i + 16] = r2; + r[j + i + 32] = r4; + r[j + i + 48] = r6; + } + } + + for (j = 0; j < DILITHIUM_N; j += 16) { + int i; + sword32 zeta8 = zetas[16 + j / 16]; + sword32 zeta40 = zetas[32 + j / 8 + 0]; + sword32 zeta41 = zetas[32 + j / 8 + 1]; + for (i = 0; i < 4; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 4]; + sword32 r4 = r[j + i + 8]; + sword32 r6 = r[j + i + 12]; + + t0 = dilithium_mont_red((sword64)zeta8 * r4); + t2 = dilithium_mont_red((sword64)zeta8 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zeta40 * r2); + t2 = dilithium_mont_red((sword64)zeta41 * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + i + 0] = r0; + r[j + i + 4] = r2; + r[j + i + 8] = r4; + r[j + i + 12] = r6; + } + } + + k = 128; + for (j = 0; j < DILITHIUM_N; j += 4) { + sword32 zeta2 = zetas[64 + j / 4]; + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 1]; + sword32 r4 = r[j + 2]; + sword32 r6 = r[j + 3]; + + t0 = dilithium_mont_red((sword64)zeta2 * r4); + t2 = dilithium_mont_red((sword64)zeta2 * r6); + r4 = r0 - t0; + r6 = r2 - t2; + r0 += t0; + r2 += t2; + + t0 = dilithium_mont_red((sword64)zetas[k++] * r2); + t2 = dilithium_mont_red((sword64)zetas[k++] * r6); + r2 = r0 - t0; + r6 = r4 - t2; + r0 += t0; + r4 += t2; + + r[j + 0] = r0; + r[j + 1] = r2; + r[j + 2] = r4; + r[j + 3] = r6; + } +#else + sword32 t0; + sword32 t1; + sword32 t2; + sword32 t3; + sword32 zeta640 = zetas[2]; + sword32 zeta641 = zetas[3]; + for (j = 0; j < DILITHIUM_N / 8; j++) { + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 32]; + sword32 r2 = r[j + 64]; + sword32 r3 = r[j + 96]; + sword32 r4 = r[j + 128]; + sword32 r5 = r[j + 160]; + sword32 r6 = r[j + 192]; + sword32 r7 = r[j + 224]; + + t0 = dilithium_red((sword32)-3572223 * r4); + t1 = dilithium_red((sword32)-3572223 * r5); + t2 = dilithium_red((sword32)-3572223 * r6); + t3 = dilithium_red((sword32)-3572223 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta640 * r2); + t1 = dilithium_mont_red((sword64)zeta640 * r3); + t2 = dilithium_mont_red((sword64)zeta641 * r6); + t3 = dilithium_mont_red((sword64)zeta641 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta32 = zetas[ 4 + j / 64 + 0]; + sword32 zeta160 = zetas[ 8 + j / 32 + 0]; + sword32 zeta161 = zetas[ 8 + j / 32 + 1]; + sword32 zeta80 = zetas[16 + j / 16 + 0]; + sword32 zeta81 = zetas[16 + j / 16 + 1]; + sword32 zeta82 = zetas[16 + j / 16 + 2]; + sword32 zeta83 = zetas[16 + j / 16 + 3]; + for (i = 0; i < 8; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r1 = r[j + i + 8]; + sword32 r2 = r[j + i + 16]; + sword32 r3 = r[j + i + 24]; + sword32 r4 = r[j + i + 32]; + sword32 r5 = r[j + i + 40]; + sword32 r6 = r[j + i + 48]; + sword32 r7 = r[j + i + 56]; + + t0 = dilithium_mont_red((sword64)zeta32 * r4); + t1 = dilithium_mont_red((sword64)zeta32 * r5); + t2 = dilithium_mont_red((sword64)zeta32 * r6); + t3 = dilithium_mont_red((sword64)zeta32 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta160 * r2); + t1 = dilithium_mont_red((sword64)zeta160 * r3); + t2 = dilithium_mont_red((sword64)zeta161 * r6); + t3 = dilithium_mont_red((sword64)zeta161 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = dilithium_mont_red((sword64)zeta80 * r1); + t1 = dilithium_mont_red((sword64)zeta81 * r3); + t2 = dilithium_mont_red((sword64)zeta82 * r5); + t3 = dilithium_mont_red((sword64)zeta83 * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + k = 128; + for (j = 0; j < DILITHIUM_N; j += 8) { + sword32 zeta4 = zetas[32 + j / 8 + 0]; + sword32 zeta20 = zetas[64 + j / 4 + 0]; + sword32 zeta21 = zetas[64 + j / 4 + 1]; + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 1]; + sword32 r2 = r[j + 2]; + sword32 r3 = r[j + 3]; + sword32 r4 = r[j + 4]; + sword32 r5 = r[j + 5]; + sword32 r6 = r[j + 6]; + sword32 r7 = r[j + 7]; + + t0 = dilithium_mont_red((sword64)zeta4 * r4); + t1 = dilithium_mont_red((sword64)zeta4 * r5); + t2 = dilithium_mont_red((sword64)zeta4 * r6); + t3 = dilithium_mont_red((sword64)zeta4 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = dilithium_mont_red((sword64)zeta20 * r2); + t1 = dilithium_mont_red((sword64)zeta20 * r3); + t2 = dilithium_mont_red((sword64)zeta21 * r6); + t3 = dilithium_mont_red((sword64)zeta21 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = dilithium_mont_red((sword64)zetas[k++] * r1); + t1 = dilithium_mont_red((sword64)zetas[k++] * r3); + t2 = dilithium_mont_red((sword64)zetas[k++] * r5); + t3 = dilithium_mont_red((sword64)zetas[k++] * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + 0] = r0; + r[j + 1] = r1; + r[j + 2] = r2; + r[j + 3] = r3; + r[j + 4] = r4; + r[j + 5] = r5; + r[j + 6] = r6; + r[j + 7] = r7; + } +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + (defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) || \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM))) +/* Number-Theoretic Transform with small initial values. + * + * @param [in, out] r Vector of polynomials to transform. + * @param [in] l Dimension of polynomial. + */ +static void dilithium_vec_ntt_small(sword32* r, byte l) +{ + unsigned int i; + + for (i = 0; i < l; i++) { + dilithium_ntt_small(r); + r += DILITHIUM_N; + } +} +#endif /* !WOLFSSL_DILITHIUM_VERIFY_ONLY */ + +#else + +/* Number-Theoretic Transform with small initial values. + * + * @param [in, out] r Polynomial to transform. + */ +#define dilithium_ntt_small dilithium_ntt +/* Number-Theoretic Transform with small initial values. + * + * @param [in, out] r Vector of polynomials to transform. + * @param [in] l Dimension of polynomial. + */ +#define dilithium_vec_ntt_small dilithium_vec_ntt + +#endif /* WOLFSSL_DILITHIUM_SMALL */ + + +/* One iteration of Inverse Number-Theoretic Transform. + * + * @param [in] len Length of sequence. + */ +#define INVNTT(len) \ +do { \ + for (start = 0; start < DILITHIUM_N; start += 2 * (len)) { \ + zeta = zetas_inv[k++]; \ + for (j = 0; j < (len); ++j) { \ + sword32 rj = r[start + j]; \ + sword32 rjl = r[start + j + (len)]; \ + sword32 t = rj + rjl; \ + r[start + j] = t; \ + rjl = rj - rjl; \ + r[start + j + (len)] = dilithium_mont_red((sword64)zeta * rjl); \ + } \ + } \ +} \ +while (0) + +/* Inverse Number-Theoretic Transform. + * + * @param [in, out] r Polynomial to transform. + */ +static void dilithium_invntt(sword32* r) +{ +#ifdef WOLFSSL_DILITHIUM_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + sword32 zeta; + + k = 256; + for (len = 1; len <= DILITHIUM_N / 2; len <<= 1) { + unsigned int start; + for (start = 0; start < DILITHIUM_N; start = j + len) { + zeta = -zetas[--k]; + for (j = start; j < start + len; ++j) { + sword32 rj = r[j]; + sword32 rjl = r[j + len]; + sword32 t = rj + rjl; + r[j] = t; + rjl = rj - rjl; + r[j + len] = dilithium_mont_red((sword64)zeta * rjl); + } + } + } + + zeta = -zetas[0]; + for (j = 0; j < DILITHIUM_N; ++j) { + r[j] = dilithium_mont_red((sword64)zeta * r[j]); + } +#elif defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) + unsigned int j; + unsigned int k = 0; + unsigned int start; + sword32 zeta; + + for (j = 0; j < DILITHIUM_N; j += 2) { + sword32 rj = r[j]; + sword32 rjl = r[j + 1]; + sword32 t = rj + rjl; + r[j] = t; + rjl = rj - rjl; + r[j + 1] = dilithium_mont_red((sword64)zetas_inv[k++] * rjl); + } + + INVNTT(2); + INVNTT(4); + INVNTT(8); + INVNTT(16); + INVNTT(32); + INVNTT(64); + INVNTT(128); + + zeta = zetas_inv[255]; + for (j = 0; j < DILITHIUM_N; ++j) { + r[j] = dilithium_mont_red((sword64)zeta * r[j]); + } +#elif defined(WC_32BIT_CPU) + unsigned int j; + unsigned int k = 0; + sword32 t0; + sword32 t2; + + sword32 zeta640; + sword32 zeta641; + sword32 zeta128; + sword32 zeta256; + for (j = 0; j < DILITHIUM_N; j += 4) { + sword32 zeta2 = zetas_inv[128 + j / 4]; + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 1]; + sword32 r4 = r[j + 2]; + sword32 r6 = r[j + 3]; + + t0 = dilithium_mont_red((sword64)zetas_inv[k++] * (r0 - r2)); + t2 = dilithium_mont_red((sword64)zetas_inv[k++] * (r4 - r6)); + r0 += r2; + r4 += r6; + r2 = t0; + r6 = t2; + + t0 = dilithium_mont_red((sword64)zeta2 * (r0 - r4)); + t2 = dilithium_mont_red((sword64)zeta2 * (r2 - r6)); + r0 += r4; + r2 += r6; + r4 = t0; + r6 = t2; + + r[j + 0] = r0; + r[j + 1] = r2; + r[j + 2] = r4; + r[j + 3] = r6; + } + + for (j = 0; j < DILITHIUM_N; j += 16) { + int i; + sword32 zeta40 = zetas_inv[192 + j / 8 + 0]; + sword32 zeta41 = zetas_inv[192 + j / 8 + 1]; + sword32 zeta8 = zetas_inv[224 + j / 16 + 0]; + for (i = 0; i < 4; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 4]; + sword32 r4 = r[j + i + 8]; + sword32 r6 = r[j + i + 12]; + + t0 = dilithium_mont_red((sword64)zeta40 * (r0 - r2)); + t2 = dilithium_mont_red((sword64)zeta41 * (r4 - r6)); + r0 += r2; + r4 += r6; + r2 = t0; + r6 = t2; + + t0 = dilithium_mont_red((sword64)zeta8 * (r0 - r4)); + t2 = dilithium_mont_red((sword64)zeta8 * (r2 - r6)); + r0 += r4; + r2 += r6; + r4 = t0; + r6 = t2; + + r[j + i + 0] = r0; + r[j + i + 4] = r2; + r[j + i + 8] = r4; + r[j + i + 12] = r6; + } + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta160 = zetas_inv[240 + j / 32 + 0]; + sword32 zeta161 = zetas_inv[240 + j / 32 + 1]; + sword32 zeta32 = zetas_inv[248 + j / 64 + 0]; + for (i = 0; i < 16; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r2 = r[j + i + 16]; + sword32 r4 = r[j + i + 32]; + sword32 r6 = r[j + i + 48]; + + t0 = dilithium_mont_red((sword64)zeta160 * (r0 - r2)); + t2 = dilithium_mont_red((sword64)zeta161 * (r4 - r6)); + r0 += r2; + r4 += r6; + r2 = t0; + r6 = t2; + + t0 = dilithium_mont_red((sword64)zeta32 * (r0 - r4)); + t2 = dilithium_mont_red((sword64)zeta32 * (r2 - r6)); + r0 += r4; + r2 += r6; + r4 = t0; + r6 = t2; + + r[j + i + 0] = r0; + r[j + i + 16] = r2; + r[j + i + 32] = r4; + r[j + i + 48] = r6; + } + } + + zeta640 = zetas_inv[252]; + zeta641 = zetas_inv[253]; + zeta128 = zetas_inv[254]; + zeta256 = zetas_inv[255]; + for (j = 0; j < DILITHIUM_N / 4; j++) { + sword32 r0 = r[j + 0]; + sword32 r2 = r[j + 64]; + sword32 r4 = r[j + 128]; + sword32 r6 = r[j + 192]; + + t0 = dilithium_mont_red((sword64)zeta640 * (r0 - r2)); + t2 = dilithium_mont_red((sword64)zeta641 * (r4 - r6)); + r0 += r2; + r4 += r6; + r2 = t0; + r6 = t2; + + t0 = dilithium_mont_red((sword64)zeta128 * (r0 - r4)); + t2 = dilithium_mont_red((sword64)zeta128 * (r2 - r6)); + r0 += r4; + r2 += r6; + r4 = t0; + r6 = t2; + + r0 = dilithium_mont_red((sword64)zeta256 * r0); + r2 = dilithium_mont_red((sword64)zeta256 * r2); + r4 = dilithium_mont_red((sword64)zeta256 * r4); + r6 = dilithium_mont_red((sword64)zeta256 * r6); + + r[j + 0] = r0; + r[j + 64] = r2; + r[j + 128] = r4; + r[j + 192] = r6; + } +#else + unsigned int j; + unsigned int k = 0; + sword32 t0; + sword32 t1; + sword32 t2; + sword32 t3; + + sword32 zeta640; + sword32 zeta641; + sword32 zeta128; + sword32 zeta256; + for (j = 0; j < DILITHIUM_N; j += 8) { + sword32 zeta20 = zetas_inv[128 + j / 4 + 0]; + sword32 zeta21 = zetas_inv[128 + j / 4 + 1]; + sword32 zeta4 = zetas_inv[192 + j / 8 + 0]; + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 1]; + sword32 r2 = r[j + 2]; + sword32 r3 = r[j + 3]; + sword32 r4 = r[j + 4]; + sword32 r5 = r[j + 5]; + sword32 r6 = r[j + 6]; + sword32 r7 = r[j + 7]; + + t0 = dilithium_mont_red((sword64)zetas_inv[k++] * (r0 - r1)); + t1 = dilithium_mont_red((sword64)zetas_inv[k++] * (r2 - r3)); + t2 = dilithium_mont_red((sword64)zetas_inv[k++] * (r4 - r5)); + t3 = dilithium_mont_red((sword64)zetas_inv[k++] * (r6 - r7)); + r0 += r1; + r2 += r3; + r4 += r5; + r6 += r7; + r1 = t0; + r3 = t1; + r5 = t2; + r7 = t3; + + t0 = dilithium_mont_red((sword64)zeta20 * (r0 - r2)); + t1 = dilithium_mont_red((sword64)zeta20 * (r1 - r3)); + t2 = dilithium_mont_red((sword64)zeta21 * (r4 - r6)); + t3 = dilithium_mont_red((sword64)zeta21 * (r5 - r7)); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + t0 = dilithium_mont_red((sword64)zeta4 * (r0 - r4)); + t1 = dilithium_mont_red((sword64)zeta4 * (r1 - r5)); + t2 = dilithium_mont_red((sword64)zeta4 * (r2 - r6)); + t3 = dilithium_mont_red((sword64)zeta4 * (r3 - r7)); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + 0] = r0; + r[j + 1] = r1; + r[j + 2] = r2; + r[j + 3] = r3; + r[j + 4] = r4; + r[j + 5] = r5; + r[j + 6] = r6; + r[j + 7] = r7; + } + + for (j = 0; j < DILITHIUM_N; j += 64) { + int i; + sword32 zeta80 = zetas_inv[224 + j / 16 + 0]; + sword32 zeta81 = zetas_inv[224 + j / 16 + 1]; + sword32 zeta82 = zetas_inv[224 + j / 16 + 2]; + sword32 zeta83 = zetas_inv[224 + j / 16 + 3]; + sword32 zeta160 = zetas_inv[240 + j / 32 + 0]; + sword32 zeta161 = zetas_inv[240 + j / 32 + 1]; + sword32 zeta32 = zetas_inv[248 + j / 64 + 0]; + for (i = 0; i < 8; i++) { + sword32 r0 = r[j + i + 0]; + sword32 r1 = r[j + i + 8]; + sword32 r2 = r[j + i + 16]; + sword32 r3 = r[j + i + 24]; + sword32 r4 = r[j + i + 32]; + sword32 r5 = r[j + i + 40]; + sword32 r6 = r[j + i + 48]; + sword32 r7 = r[j + i + 56]; + + t0 = dilithium_mont_red((sword64)zeta80 * (r0 - r1)); + t1 = dilithium_mont_red((sword64)zeta81 * (r2 - r3)); + t2 = dilithium_mont_red((sword64)zeta82 * (r4 - r5)); + t3 = dilithium_mont_red((sword64)zeta83 * (r6 - r7)); + r0 += r1; + r2 += r3; + r4 += r5; + r6 += r7; + r1 = t0; + r3 = t1; + r5 = t2; + r7 = t3; + + t0 = dilithium_mont_red((sword64)zeta160 * (r0 - r2)); + t1 = dilithium_mont_red((sword64)zeta160 * (r1 - r3)); + t2 = dilithium_mont_red((sword64)zeta161 * (r4 - r6)); + t3 = dilithium_mont_red((sword64)zeta161 * (r5 - r7)); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + t0 = dilithium_mont_red((sword64)zeta32 * (r0 - r4)); + t1 = dilithium_mont_red((sword64)zeta32 * (r1 - r5)); + t2 = dilithium_mont_red((sword64)zeta32 * (r2 - r6)); + t3 = dilithium_mont_red((sword64)zeta32 * (r3 - r7)); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + zeta640 = zetas_inv[252]; + zeta641 = zetas_inv[253]; + zeta128 = zetas_inv[254]; + zeta256 = zetas_inv[255]; + for (j = 0; j < DILITHIUM_N / 8; j++) { + sword32 r0 = r[j + 0]; + sword32 r1 = r[j + 32]; + sword32 r2 = r[j + 64]; + sword32 r3 = r[j + 96]; + sword32 r4 = r[j + 128]; + sword32 r5 = r[j + 160]; + sword32 r6 = r[j + 192]; + sword32 r7 = r[j + 224]; + + t0 = dilithium_mont_red((sword64)zeta640 * (r0 - r2)); + t1 = dilithium_mont_red((sword64)zeta640 * (r1 - r3)); + t2 = dilithium_mont_red((sword64)zeta641 * (r4 - r6)); + t3 = dilithium_mont_red((sword64)zeta641 * (r5 - r7)); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + t0 = dilithium_mont_red((sword64)zeta128 * (r0 - r4)); + t1 = dilithium_mont_red((sword64)zeta128 * (r1 - r5)); + t2 = dilithium_mont_red((sword64)zeta128 * (r2 - r6)); + t3 = dilithium_mont_red((sword64)zeta128 * (r3 - r7)); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r0 = dilithium_mont_red((sword64)zeta256 * r0); + r1 = dilithium_mont_red((sword64)zeta256 * r1); + r2 = dilithium_mont_red((sword64)zeta256 * r2); + r3 = dilithium_mont_red((sword64)zeta256 * r3); + r4 = dilithium_mont_red((sword64)zeta256 * r4); + r5 = dilithium_mont_red((sword64)zeta256 * r5); + r6 = dilithium_mont_red((sword64)zeta256 * r6); + r7 = dilithium_mont_red((sword64)zeta256 * r7); + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } +#endif +} + + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Inverse Number-Theoretic Transform. + * + * @param [in, out] r Vector of polynomials to transform. + * @param [in] l Dimension of polynomial. + */ +static void dilithium_vec_invntt(sword32* r, byte l) +{ + unsigned int i; + + for (i = 0; i < l; i++) { + dilithium_invntt(r); + r += DILITHIUM_N; + } +} +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Matrix multiplication. + * + * @param [out] r Vector of polynomials that is result. + * @param [in] m Matrix of polynomials. + * @param [in] v Vector of polynomials. + * @param [in] k First dimension of matrix and dimension of result. + * @param [in] l Second dimension of matrix and dimension of v. + */ +static void dilithium_matrix_mul(sword32* r, const sword32* m, const sword32* v, + byte k, byte l) +{ + byte i; + + for (i = 0; i < k; i++) { + byte j; + unsigned int e; + const sword32* vt = v; + +#ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + r[e] = dilithium_mont_red((sword64)m[e] * vt[e]); + } + m += DILITHIUM_N; + vt += DILITHIUM_N; + for (j = 1; j < l; j++) { + for (e = 0; e < DILITHIUM_N; e++) { + r[e] += dilithium_mont_red((sword64)m[e] * vt[e]); + } + m += DILITHIUM_N; + vt += DILITHIUM_N; + } +#elif defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) + (void)j; + if (l == 4) { + for (e = 0; e < DILITHIUM_N; e++) { + sword64 t = ((sword64)m[e + 0 * 256] * vt[e + 0 * 256]) + + ((sword64)m[e + 1 * 256] * vt[e + 1 * 256]) + + ((sword64)m[e + 2 * 256] * vt[e + 2 * 256]) + + ((sword64)m[e + 3 * 256] * vt[e + 3 * 256]); + r[e] = dilithium_mont_red(t); + } + m += DILITHIUM_N * 4; + } + else if (l == 5) { + for (e = 0; e < DILITHIUM_N; e++) { + sword64 t = ((sword64)m[e + 0 * 256] * vt[e + 0 * 256]) + + ((sword64)m[e + 1 * 256] * vt[e + 1 * 256]) + + ((sword64)m[e + 2 * 256] * vt[e + 2 * 256]) + + ((sword64)m[e + 3 * 256] * vt[e + 3 * 256]) + + ((sword64)m[e + 4 * 256] * vt[e + 4 * 256]); + r[e] = dilithium_mont_red(t); + } + m += DILITHIUM_N * 5; + } + else if (l == 7) { + for (e = 0; e < DILITHIUM_N; e++) { + sword64 t = ((sword64)m[e + 0 * 256] * vt[e + 0 * 256]) + + ((sword64)m[e + 1 * 256] * vt[e + 1 * 256]) + + ((sword64)m[e + 2 * 256] * vt[e + 2 * 256]) + + ((sword64)m[e + 3 * 256] * vt[e + 3 * 256]) + + ((sword64)m[e + 4 * 256] * vt[e + 4 * 256]) + + ((sword64)m[e + 5 * 256] * vt[e + 5 * 256]) + + ((sword64)m[e + 6 * 256] * vt[e + 6 * 256]); + r[e] = dilithium_mont_red(t); + } + m += DILITHIUM_N * 7; + } +#else + sword64 t0; + sword64 t1; +#if !defined(WOLFSSL_NO_ML_DSA_44) || !defined(WOLFSSL_NO_ML_DSA_65) + sword64 t2; + sword64 t3; +#endif + + (void)j; +#ifndef WOLFSSL_NO_ML_DSA_44 + if (l == 4) { + for (e = 0; e < DILITHIUM_N; e += 4) { + t0 = ((sword64)m[e + 0 + 0 * 256] * vt[e + 0 + 0 * 256]) + + ((sword64)m[e + 0 + 1 * 256] * vt[e + 0 + 1 * 256]) + + ((sword64)m[e + 0 + 2 * 256] * vt[e + 0 + 2 * 256]) + + ((sword64)m[e + 0 + 3 * 256] * vt[e + 0 + 3 * 256]); + t1 = ((sword64)m[e + 1 + 0 * 256] * vt[e + 1 + 0 * 256]) + + ((sword64)m[e + 1 + 1 * 256] * vt[e + 1 + 1 * 256]) + + ((sword64)m[e + 1 + 2 * 256] * vt[e + 1 + 2 * 256]) + + ((sword64)m[e + 1 + 3 * 256] * vt[e + 1 + 3 * 256]); + t2 = ((sword64)m[e + 2 + 0 * 256] * vt[e + 2 + 0 * 256]) + + ((sword64)m[e + 2 + 1 * 256] * vt[e + 2 + 1 * 256]) + + ((sword64)m[e + 2 + 2 * 256] * vt[e + 2 + 2 * 256]) + + ((sword64)m[e + 2 + 3 * 256] * vt[e + 2 + 3 * 256]); + t3 = ((sword64)m[e + 3 + 0 * 256] * vt[e + 3 + 0 * 256]) + + ((sword64)m[e + 3 + 1 * 256] * vt[e + 3 + 1 * 256]) + + ((sword64)m[e + 3 + 2 * 256] * vt[e + 3 + 2 * 256]) + + ((sword64)m[e + 3 + 3 * 256] * vt[e + 3 + 3 * 256]); + r[e + 0] = dilithium_mont_red(t0); + r[e + 1] = dilithium_mont_red(t1); + r[e + 2] = dilithium_mont_red(t2); + r[e + 3] = dilithium_mont_red(t3); + } + m += DILITHIUM_N * 4; + } + else +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + if (l == 5) { + for (e = 0; e < DILITHIUM_N; e += 4) { + t0 = ((sword64)m[e + 0 + 0 * 256] * vt[e + 0 + 0 * 256]) + + ((sword64)m[e + 0 + 1 * 256] * vt[e + 0 + 1 * 256]) + + ((sword64)m[e + 0 + 2 * 256] * vt[e + 0 + 2 * 256]) + + ((sword64)m[e + 0 + 3 * 256] * vt[e + 0 + 3 * 256]) + + ((sword64)m[e + 0 + 4 * 256] * vt[e + 0 + 4 * 256]); + t1 = ((sword64)m[e + 1 + 0 * 256] * vt[e + 1 + 0 * 256]) + + ((sword64)m[e + 1 + 1 * 256] * vt[e + 1 + 1 * 256]) + + ((sword64)m[e + 1 + 2 * 256] * vt[e + 1 + 2 * 256]) + + ((sword64)m[e + 1 + 3 * 256] * vt[e + 1 + 3 * 256]) + + ((sword64)m[e + 1 + 4 * 256] * vt[e + 1 + 4 * 256]); + t2 = ((sword64)m[e + 2 + 0 * 256] * vt[e + 2 + 0 * 256]) + + ((sword64)m[e + 2 + 1 * 256] * vt[e + 2 + 1 * 256]) + + ((sword64)m[e + 2 + 2 * 256] * vt[e + 2 + 2 * 256]) + + ((sword64)m[e + 2 + 3 * 256] * vt[e + 2 + 3 * 256]) + + ((sword64)m[e + 2 + 4 * 256] * vt[e + 2 + 4 * 256]); + t3 = ((sword64)m[e + 3 + 0 * 256] * vt[e + 3 + 0 * 256]) + + ((sword64)m[e + 3 + 1 * 256] * vt[e + 3 + 1 * 256]) + + ((sword64)m[e + 3 + 2 * 256] * vt[e + 3 + 2 * 256]) + + ((sword64)m[e + 3 + 3 * 256] * vt[e + 3 + 3 * 256]) + + ((sword64)m[e + 3 + 4 * 256] * vt[e + 3 + 4 * 256]); + r[e + 0] = dilithium_mont_red(t0); + r[e + 1] = dilithium_mont_red(t1); + r[e + 2] = dilithium_mont_red(t2); + r[e + 3] = dilithium_mont_red(t3); + } + m += DILITHIUM_N * 5; + } + else +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + if (l == 7) { + for (e = 0; e < DILITHIUM_N; e += 2) { + t0 = ((sword64)m[e + 0 + 0 * 256] * vt[e + 0 + 0 * 256]) + + ((sword64)m[e + 0 + 1 * 256] * vt[e + 0 + 1 * 256]) + + ((sword64)m[e + 0 + 2 * 256] * vt[e + 0 + 2 * 256]) + + ((sword64)m[e + 0 + 3 * 256] * vt[e + 0 + 3 * 256]) + + ((sword64)m[e + 0 + 4 * 256] * vt[e + 0 + 4 * 256]) + + ((sword64)m[e + 0 + 5 * 256] * vt[e + 0 + 5 * 256]) + + ((sword64)m[e + 0 + 6 * 256] * vt[e + 0 + 6 * 256]); + t1 = ((sword64)m[e + 1 + 0 * 256] * vt[e + 1 + 0 * 256]) + + ((sword64)m[e + 1 + 1 * 256] * vt[e + 1 + 1 * 256]) + + ((sword64)m[e + 1 + 2 * 256] * vt[e + 1 + 2 * 256]) + + ((sword64)m[e + 1 + 3 * 256] * vt[e + 1 + 3 * 256]) + + ((sword64)m[e + 1 + 4 * 256] * vt[e + 1 + 4 * 256]) + + ((sword64)m[e + 1 + 5 * 256] * vt[e + 1 + 5 * 256]) + + ((sword64)m[e + 1 + 6 * 256] * vt[e + 1 + 6 * 256]); + r[e + 0] = dilithium_mont_red(t0); + r[e + 1] = dilithium_mont_red(t1); + } + m += DILITHIUM_N * 7; + } + else +#endif + { + } +#endif + r += DILITHIUM_N; + } +} +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) +/* Polynomial multiplication. + * + * @param [out] r Polynomial result. + * @param [in] a Polynomial + * @param [in] b Polynomial. + */ +static void dilithium_mul(sword32* r, sword32* a, sword32* b) +{ + unsigned int e; +#ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + r[e] = dilithium_mont_red((sword64)a[e] * b[e]); + } +#elif defined(WOLFSSL_DILITHIUM_NO_LARGE_CODE) + for (e = 0; e < DILITHIUM_N; e += 8) { + r[e+0] = dilithium_mont_red((sword64)a[e+0] * b[e+0]); + r[e+1] = dilithium_mont_red((sword64)a[e+1] * b[e+1]); + r[e+2] = dilithium_mont_red((sword64)a[e+2] * b[e+2]); + r[e+3] = dilithium_mont_red((sword64)a[e+3] * b[e+3]); + r[e+4] = dilithium_mont_red((sword64)a[e+4] * b[e+4]); + r[e+5] = dilithium_mont_red((sword64)a[e+5] * b[e+5]); + r[e+6] = dilithium_mont_red((sword64)a[e+6] * b[e+6]); + r[e+7] = dilithium_mont_red((sword64)a[e+7] * b[e+7]); + } +#else + for (e = 0; e < DILITHIUM_N; e += 16) { + r[e+ 0] = dilithium_mont_red((sword64)a[e+ 0] * b[e+ 0]); + r[e+ 1] = dilithium_mont_red((sword64)a[e+ 1] * b[e+ 1]); + r[e+ 2] = dilithium_mont_red((sword64)a[e+ 2] * b[e+ 2]); + r[e+ 3] = dilithium_mont_red((sword64)a[e+ 3] * b[e+ 3]); + r[e+ 4] = dilithium_mont_red((sword64)a[e+ 4] * b[e+ 4]); + r[e+ 5] = dilithium_mont_red((sword64)a[e+ 5] * b[e+ 5]); + r[e+ 6] = dilithium_mont_red((sword64)a[e+ 6] * b[e+ 6]); + r[e+ 7] = dilithium_mont_red((sword64)a[e+ 7] * b[e+ 7]); + r[e+ 8] = dilithium_mont_red((sword64)a[e+ 8] * b[e+ 8]); + r[e+ 9] = dilithium_mont_red((sword64)a[e+ 9] * b[e+ 9]); + r[e+10] = dilithium_mont_red((sword64)a[e+10] * b[e+10]); + r[e+11] = dilithium_mont_red((sword64)a[e+11] * b[e+11]); + r[e+12] = dilithium_mont_red((sword64)a[e+12] * b[e+12]); + r[e+13] = dilithium_mont_red((sword64)a[e+13] * b[e+13]); + r[e+14] = dilithium_mont_red((sword64)a[e+14] * b[e+14]); + r[e+15] = dilithium_mont_red((sword64)a[e+15] * b[e+15]); + } +#endif +} + +#if (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) +/* Vector multiplication. + * + * @param [out] r Vector of polynomials that is result. + * @param [in] a Polynomials + * @param [in] b Vector of polynomials. + * @param [in] l Dimension of vectors. + */ +static void dilithium_vec_mul(sword32* r, sword32* a, sword32* b, byte l) +{ + byte i; + + for (i = 0; i < l; i++) { + dilithium_mul(r, a, b); + r += DILITHIUM_N; + b += DILITHIUM_N; + } +} +#endif +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* Modulo reduce values in polynomial. Range (-2^31)..(2^31-1). + * + * @param [in, out] a Polynomial. + */ +static void dilithium_poly_red(sword32* a) +{ + word16 j; +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + a[j] = dilithium_red(a[j]); + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + a[j+0] = dilithium_red(a[j+0]); + a[j+1] = dilithium_red(a[j+1]); + a[j+2] = dilithium_red(a[j+2]); + a[j+3] = dilithium_red(a[j+3]); + a[j+4] = dilithium_red(a[j+4]); + a[j+5] = dilithium_red(a[j+5]); + a[j+6] = dilithium_red(a[j+6]); + a[j+7] = dilithium_red(a[j+7]); + } +#endif +} + +#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +/* Modulo reduce values in polynomials of vector. Range (-2^31)..(2^31-1). + * + * @param [in, out] a Vector of polynomials. + * @param [in] l Dimension of vector. + */ +static void dilithium_vec_red(sword32* a, byte l) +{ + byte i; + + for (i = 0; i < l; i++) { + dilithium_poly_red(a); + a += DILITHIUM_N; + } +} +#endif /* WOLFSSL_DILITHIUM_SIGN_SMALL_MEM*/ +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#if (!defined(WOLFSSL_DILITHIUM_NO_SIGN) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM))) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) +/* Subtract polynomials a from r. r -= a. + * + * @param [out] r Polynomial to subtract from. + * @param [in] a Polynomial to subtract. + */ +static void dilithium_sub(sword32* r, const sword32* a) +{ + word16 j; +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + r[j] -= a[j]; + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + r[j+0] -= a[j+0]; + r[j+1] -= a[j+1]; + r[j+2] -= a[j+2]; + r[j+3] -= a[j+3]; + r[j+4] -= a[j+4]; + r[j+5] -= a[j+5]; + r[j+6] -= a[j+6]; + r[j+7] -= a[j+7]; + } +#endif +} + +#if defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Subtract vector a from r. r -= a. + * + * @param [out] r Vector of polynomials that is result. + * @param [in] a Vector of polynomials to subtract. + * @param [in] l Dimension of vectors. + */ +static void dilithium_vec_sub(sword32* r, const sword32* a, byte l) +{ + byte i; + + for (i = 0; i < l; i++) { + dilithium_sub(r, a); + r += DILITHIUM_N; + a += DILITHIUM_N; + } +} +#endif +#endif + +#ifndef WOLFSSL_DILITHIUM_VERIFY_ONLY +/* Add polynomials a to r. r += a. + * + * @param [out] r Polynomial to add to. + * @param [in] a Polynomial to add. + */ +static void dilithium_add(sword32* r, const sword32* a) +{ + word16 j; +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + r[j] += a[j]; + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + r[j+0] += a[j+0]; + r[j+1] += a[j+1]; + r[j+2] += a[j+2]; + r[j+3] += a[j+3]; + r[j+4] += a[j+4]; + r[j+5] += a[j+5]; + r[j+6] += a[j+6]; + r[j+7] += a[j+7]; + } +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Add vector a to r. r += a. + * + * @param [out] r Vector of polynomials that is result. + * @param [in] a Vector of polynomials to add. + * @param [in] l Dimension of vectors. + */ +static void dilithium_vec_add(sword32* r, const sword32* a, byte l) +{ + byte i; + + for (i = 0; i < l; i++) { + dilithium_add(r, a); + r += DILITHIUM_N; + a += DILITHIUM_N; + } +} +#endif + +/* Make values in polynomial be in positive range. + * + * @param [in, out] a Polynomial. + */ +static void dilithium_make_pos(sword32* a) +{ + word16 j; +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + a[j] += (0 - (((word32)a[j]) >> 31)) & DILITHIUM_Q; + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + a[j+0] += (0 - (((word32)a[j+0]) >> 31)) & DILITHIUM_Q; + a[j+1] += (0 - (((word32)a[j+1]) >> 31)) & DILITHIUM_Q; + a[j+2] += (0 - (((word32)a[j+2]) >> 31)) & DILITHIUM_Q; + a[j+3] += (0 - (((word32)a[j+3]) >> 31)) & DILITHIUM_Q; + a[j+4] += (0 - (((word32)a[j+4]) >> 31)) & DILITHIUM_Q; + a[j+5] += (0 - (((word32)a[j+5]) >> 31)) & DILITHIUM_Q; + a[j+6] += (0 - (((word32)a[j+6]) >> 31)) & DILITHIUM_Q; + a[j+7] += (0 - (((word32)a[j+7]) >> 31)) & DILITHIUM_Q; + } +#endif +} + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) +/* Make values in polynomials of vector be in positive range. + * + * @param [in, out] a Vector of polynomials. + * @param [in] l Dimension of vector. + */ +static void dilithium_vec_make_pos(sword32* a, byte l) +{ + byte i; + + for (i = 0; i < l; i++) { + dilithium_make_pos(a); + a += DILITHIUM_N; + } +} +#endif + +#endif /* !WOLFSSL_DILITHIUM_VERIFY_ONLY */ + +/******************************************************************************/ + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY + +/* Make a key from a random seed. + * + * xi is seed passed in. + * FIPS 204. 5: Algorithm 1 ML-DSA.KeyGen() + * ... + * 2: (rho, rho', K) E {0,1}256 x {0,1}512 x {0,1}256 <- H(xi, 1024) + * 3: A_circum <- ExpandA(rho) + * 4: (s1,s2) <- ExpandS(rho') + * 5: t <- NTT-1(A_circum o NTT(s1)) + s2 + * 6: (t1, t0) <- Power2Round(t, d) + * 7: pk <- pkEncode(rho, t1) + * 8: tr <- H(BytesToBits(pk), 512) + * 9: sk <- skEncode(rho, K, tr, s1, s2, t0) + * 10: return (pk, sk) + * + * FIPS 204. 8.2: Algorithm 16 pkEncode(rho, t1) + * 1: pk <- BitsToBytes(rho) + * 2: for i from 0 to l - 1 do + * 3: pk <- pk || SimpleBitPack(t1[i], 2^(bitlen(q-1)-d) - 1) + * 4: end for + * 5: return pk + * + * FIPS 204. 8.2: Algorithm 18 skEncode(rho, K, tr, s, s2, t0) + * 1: sk <- BitsToBytes(rho) || BitsToBytes(K) || BitsToBytes(tr) + * 2: for i from 0 to l - 1 do + * 3: sk <- sk || BitPack(s1[i], eta, eta) + * 4: end for + * 5: for i from 0 to k - 1 do + * 6: sk <- sk || BitPack(s2[i], eta, eta) + * 7: end for + * 8: for i from 0 to k - 1 do + * 9: sk <- sk || BitPack(t0[i], 2^(d-1)-1, 2^(d-1)) + * 10: end for + * 11: return sk + * + * Public and private key store in key. + * + * @param [in, out] key Dilithium key. + * @param [in] seed Seed to hash to generate values. + * @return 0 on success. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) +{ + int ret = 0; + const wc_dilithium_params* params = key->params; + sword32* a = NULL; + sword32* s1 = NULL; + sword32* s2 = NULL; + sword32* t = NULL; + byte* pub_seed = key->k; + + /* Allocate memory for large intermediates. */ +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + if (key->a == NULL) { + key->a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->a == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + a = key->a; + } +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + if ((ret == 0) && (key->s1 == NULL)) { + key->s1 = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->s1 == NULL) { + ret = MEMORY_E; + } + else { + key->s2 = key->s1 + params->s1Sz / sizeof(*s1); + key->t0 = key->s2 + params->s2Sz / sizeof(*s2); + } + } + if (ret == 0) { + s1 = key->s1; + s2 = key->s2; + t = key->t0; + } +#else + if (ret == 0) { + unsigned int allocSz; + + allocSz = params->s1Sz + params->s2Sz + params->s2Sz; +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + allocSz += params->aSz; +#endif + + /* s1, s2, t, a */ + s1 = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (s1 == NULL) { + ret = MEMORY_E; + } + else { + s2 = s1 + params->s1Sz / sizeof(*s1); + t = s2 + params->s2Sz / sizeof(*s2); +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + a = t + params->s2Sz / sizeof(*s2); +#endif + } + } +#endif + + if (ret == 0) { + /* Step 2: Create public seed, private seed and K from seed. + * Step 9; Alg 18, Step 1: Public seed is placed into private key. */ + ret = dilithium_shake256(&key->shake, seed, DILITHIUM_SEED_SZ, pub_seed, + DILITHIUM_SEEDS_SZ); + } + if (ret == 0) { + /* Step 7; Alg 16 Step 1: Copy public seed into public key. */ + XMEMCPY(key->p, pub_seed, DILITHIUM_PUB_SEED_SZ); + + /* Step 3: Expand public seed into a matrix of polynomials. */ + ret = dilithium_expand_a(&key->shake, pub_seed, params->k, params->l, + a); + } + if (ret == 0) { + byte* priv_seed = key->k + DILITHIUM_PUB_SEED_SZ; + + /* Step 4: Expand private seed into to vectors of polynomials. */ + ret = dilithium_expand_s(&key->shake, priv_seed, params->eta, s1, + params->l, s2, params->k); + } + if (ret == 0) { + byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + byte* tr = k + DILITHIUM_K_SZ; + byte* s1p = tr + DILITHIUM_TR_SZ; + byte* s2p = s1p + params->s1EncSz; + byte* t0 = s2p + params->s2EncSz; + byte* t1 = key->p + DILITHIUM_PUB_SEED_SZ; + + /* Step 9: Move k down to after public seed. */ + XMEMCPY(k, k + DILITHIUM_PRIV_SEED_SZ, DILITHIUM_K_SZ); + /* Step 9. Alg 18 Steps 2-4: Encode s1 into private key. */ + dilthium_vec_encode_eta_bits(s1, params->l, params->eta, s1p); + /* Step 9. Alg 18 Steps 5-7: Encode s2 into private key. */ + dilthium_vec_encode_eta_bits(s2, params->k, params->eta, s2p); + + /* Step 5: t <- NTT-1(A_circum o NTT(s1)) + s2 */ + dilithium_vec_ntt_small(s1, params->l); + dilithium_matrix_mul(t, a, s1, params->k, params->l); + dilithium_vec_invntt(t, params->k); + dilithium_vec_add(t, s2, params->k); + + /* Make positive for decomposing. */ + dilithium_vec_make_pos(t, params->k); + /* Step 6, Step 7, Step 9. Alg 16 Steps 2-4, Alg 18 Steps 8-10. + * Decompose t in t0 and t1 and encode into public and private key. + */ + dilithium_vec_encode_t0_t1(t, params->k, t0, t1); + /* Step 8. Alg 18, Step 1: Hash public key into private key. */ + ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if (ret == 0) { + /* Public key and private key are available. */ + key->prvKeySet = 1; + key->pubKeySet = 1; +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Matrix A is available. */ + key->aSet = 1; +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + /* Private vectors are not available as they were overwritten. */ + key->privVecsSet = 0; +#endif +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + /* Public vector, t1, is not available as it was not created. */ + key->pubVecSet = 0; +#endif + } + +#ifndef WC_DILITHIUM_CACHE_PRIV_VECTORS + XFREE(s1, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +} + +/* Make a key from a random seed. + * + * FIPS 204. 5: Algorithm 1 ML-DSA.KeyGen() + * 1: xi <- {0,1}256 [Choose random seed] + * ... + * + * @param [in, out] key Dilithium key. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_make_key(dilithium_key* key, WC_RNG* rng) +{ + int ret; + byte seed[DILITHIUM_SEED_SZ]; + + /* Generate a 256-bit random seed. */ + ret = wc_RNG_GenerateBlock(rng, seed, DILITHIUM_SEED_SZ); + if (ret == 0) { + /* Make key with random seed. */ + ret = wc_dilithium_make_key_from_seed(key, seed); + } + + return ret; +} +#endif /* !WOLFSSL_DILITHIUM_NO_MAKE_KEY */ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +#if !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) || \ + defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) +/* Decode, from private key, and NTT private key vectors s1, s2, and t0. + * + * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * 1: (rho, K, tr, s1, s2, t0) <- skDecode(sk) + * 2: s1_circum <- NTT(s1) + * 3: s2_circum <- NTT(s2) + * 4: t0_circum <- NTT(t0) + * + * @param [in, out] key Dilithium key. + * @param [out] s1 Vector of polynomials s1. + * @param [out] s2 Vector of polynomials s2. + * @param [out] t0 Vector of polynomials t0. + */ +static void dilithium_make_priv_vecs(dilithium_key* key, sword32* s1, + sword32* s2, sword32* t0) +{ + const wc_dilithium_params* params = key->params; + const byte* pubSeed = key->k; + const byte* k = pubSeed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + const byte* s1p = tr + DILITHIUM_TR_SZ; + const byte* s2p = s1p + params->s1EncSz; + const byte* t0p = s2p + params->s2EncSz; + + /* Step 1: Decode s1, s2, t0. */ + dilithium_vec_decode_eta_bits(s1p, params->eta, s1, params->l); + dilithium_vec_decode_eta_bits(s2p, params->eta, s2, params->k); + dilithium_vec_decode_t0(t0p, params->k, t0); + + /* Step 2: NTT s1. */ + dilithium_vec_ntt_small(s1, params->l); + /* Step 3: NTT s2. */ + dilithium_vec_ntt_small(s2, params->k); + /* Step 4: NTT t0. */ + dilithium_vec_ntt(t0, params->k); + +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + /* Private key vectors have been created. */ + key->privVecsSet = 1; +#endif +} +#endif + +/* Sign a message with the key and a seed. + * + * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * 1: (rho, K, tr, s1, s2, t0) <- skDecode(sk) + * 2: s1_circum <- NTT(s1) + * 3: s2_circum <- NTT(s2) + * 4: t0_circum <- NTT(t0) + * 5: A_circum <- ExpandA(rho) + * 6: mu <- H(tr||M, 512) + * 7: rnd <- {0,1}256 + * 8: rho' <- H(K||rnd||mu, 512) + * 9: kappa <- 0 + * 10: (z, h) <- falsam + * 11: while (z, h) = falsam do + * 12: y <- ExpandMask(rho', kappa) + * 13: w <- NTT-1(A_circum o NTT(y)) + * 14: w1 <- HighBits(w) + * 15: c_tilde E {0,1}2*lambda <- H(mu|w1Encode(w1), 2 * lambda) + * 16: (c1_tilde, c2_tilde) E {0,1}256 x {0,1}2*lambda-256 <- c_tilde + * 17: c < SampleInBall(c1_tilde) + * 18: c_circum <- NTT(c) + * 19: <> <- NTT-1(c_circum o s1_circum) + * 20: <> <- NTT-1(c_circum o s2_circum) + * 21: z <- y + <> + * 22: r0 <- LowBits(w - <> + * 23: if ||z||inf >= GAMMA1 - BETA or ||r0||inf GAMMA2 - BETA then + * (z, h) <- falsam + * 24: else + * 25: <> <- NTT-1(c_circum o t0_circum) + * 26: h < MakeHint(-<>, w - <> + <>) + * 27: if (||<>||inf >= GAMMMA1 or + * the number of 1's in h is greater than OMEGA, then + * (z, h) <- falsam + * 28: end if + * 29: end if + * 30: kappa <- kappa + l + * 31: end while + * 32: sigma <- sigEncode(c_tilde, z mod +/- q, h) + * 33: return sigma + * + * @param [in, out] key Dilithium key. + * @param [in, out] seed Random seed. + * @param [in] msg Message data to sign. + * @param [in] msgLen Length of message data in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, + const byte* msg, word32 msgLen, byte* sig, word32 *sigLen) +{ +#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM + int ret = 0; + const wc_dilithium_params* params = key->params; + byte* pub_seed = key->k; + byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + byte* tr = k + DILITHIUM_K_SZ; + sword32* a = NULL; + sword32* s1 = NULL; + sword32* s2 = NULL; + sword32* t0 = NULL; + sword32* y = NULL; + sword32* w0 = NULL; + sword32* w1 = NULL; + sword32* c = NULL; + sword32* z = NULL; + sword32* ct0 = NULL; + byte data[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = data + DILITHIUM_RND_SZ; + byte priv_rand_seed[DILITHIUM_Y_SEED_SZ]; + byte* h = sig + params->lambda * 2 + params->zEncSz; + + /* Check the signature buffer isn't too small. */ + if ((ret == 0) && (*sigLen < params->sigSz)) { + ret = BUFFER_E; + } + if (ret == 0) { + /* Return the size of the signature. */ + *sigLen = params->sigSz; + } + + /* Allocate memory for large intermediates. */ +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + if ((ret == 0) && (key->a == NULL)) { + a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (a == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + a = key->a; + } +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + if ((ret == 0) && (key->s1 == NULL)) { + key->s1 = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->s1 == NULL) { + ret = MEMORY_E; + } + else { + key->s2 = key->s1 + params->s1Sz / sizeof(*s1); + key->t0 = key->s2 + params->s2Sz / sizeof(*s2); + } + } + if (ret == 0) { + s1 = key->s1; + s2 = key->s2; + t0 = key->t0; + } +#endif + if (ret == 0) { + unsigned int allocSz; + + /* y-l, w0-k, w1-k, c-1, z-l, ct0-k */ + allocSz = params->s1Sz + params->s2Sz + params->s2Sz + + DILITHIUM_POLY_SIZE + params->s1Sz + params->s2Sz; +#ifndef WC_DILITHIUM_CACHE_PRIV_VECTORS + /* s1-l, s2-k, t0-k */ + allocSz += params->s1Sz + params->s2Sz + params->s2Sz; +#endif +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + /* A */ + allocSz += params->aSz; +#endif + y = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (y == NULL) { + ret = MEMORY_E; + } + else { + w0 = y + params->s1Sz / sizeof(*y); + w1 = w0 + params->s2Sz / sizeof(*w0); + c = w1 + params->s2Sz / sizeof(*w1); + z = c + DILITHIUM_N; + ct0 = z + params->s1Sz / sizeof(*z); +#ifndef WC_DILITHIUM_CACHE_PRIV_VECTORS + s1 = ct0 + params->s2Sz / sizeof(*ct0); + s2 = s1 + params->s1Sz / sizeof(*s1); + t0 = s2 + params->s2Sz / sizeof(*s2); +#endif +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + a = t0 + params->s2Sz / sizeof(*s2); +#endif + } + } + + if (ret == 0) { +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + /* Check that we haven't already cached the private vectors. */ + if (!key->privVecsSet) +#endif + { + /* Steps 1-4: Decode and NTT vectors s1, s2, and t0. */ + dilithium_make_priv_vecs(key, s1, s2, t0); + } + +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Check that we haven't already cached the matrix A. */ + if (!key->aSet) +#endif + { + /* Step 5: Create the matrix A from the public seed. */ + ret = dilithium_expand_a(&key->shake, pub_seed, params->k, + params->l, a); +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + key->aSet = (ret == 0); +#endif + } + } + if (ret == 0) { + /* Step 6: Compute the hash of tr, public key hash, and message. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + /* Step 7: Copy random into buffer for hashing. */ + XMEMCPY(data, seed, DILITHIUM_RND_SZ); + } + if (ret == 0) { + /* Step 9: Compute private random using hash. */ + ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, data, + DILITHIUM_RND_SZ + DILITHIUM_MU_SZ, priv_rand_seed, + DILITHIUM_PRIV_RAND_SEED_SZ); + } + if (ret == 0) { + word16 kappa = 0; + int valid = 0; + + /* Step 11: Start rejection sampling loop */ + do { + byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; + sword32* w = w1; + sword32* y_ntt = z; + sword32* cs2 = ct0; + byte* commit = sig; + + /* Step 12: Compute vector y from private random seed and kappa. */ + dilithium_vec_expand_mask(&key->shake, priv_rand_seed, kappa, + params->gamma1_bits, y, params->l); + #ifdef WOLFSSL_DILITHIUM_SIGN_CHECK_Y + valid = dilithium_vec_check_low(y, params->l, + (1 << params->gamma1_bits) - params->beta); + if (valid) + #endif + { + /* Step 13: NTT-1(A o NTT(y)) */ + XMEMCPY(y_ntt, y, params->s1Sz); + dilithium_vec_ntt(y_ntt, params->l); + dilithium_matrix_mul(w, a, y_ntt, params->k, params->l); + dilithium_vec_invntt(w, params->k); + /* Step 14, Step 22: Make values positive and decompose. */ + dilithium_vec_make_pos(w, params->k); + dilithium_vec_decompose(w, params->k, params->gamma2, w0, w1); + #ifdef WOLFSSL_DILITHIUM_SIGN_CHECK_W0 + valid = dilithium_vec_check_low(w0, params->k, + params->gamma2 - params->beta); + } + if (valid) { + #endif + /* Step 15: Encode w1. */ + dilithium_vec_encode_w1(w1, params->k, params->gamma2, w1e); + /* Step 15: Hash mu and encoded w1. + * Step 32: Hash is stored in signature. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, + w1e, params->w1EncSz, commit, 2 * params->lambda); + if (ret == 0) { + /* Step 17: Compute c from first 256 bits of commit. */ + ret = dilithium_sample_in_ball(&key->shake, commit, + params->tau, c, NULL); + } + if (ret == 0) { + sword32 hi; + + /* Step 18: NTT(c). */ + dilithium_ntt_small(c); + /* Step 20: cs2 = NTT-1(c o s2) */ + dilithium_vec_mul(cs2, c, s2, params->k); + dilithium_vec_invntt(cs2, params->k); + /* Step 22: w0 - cs2 */ + dilithium_vec_sub(w0, cs2, params->k); + dilithium_vec_red(w0, params->k); + /* Step 23: Check w0 - cs2 has low enough values. */ + hi = params->gamma2 - params->beta; + valid = dilithium_vec_check_low(w0, params->k, hi); + if (valid) { + /* Step 19: cs1 = NTT-1(c o s1) */ + dilithium_vec_mul(z, c, s1, params->l); + dilithium_vec_invntt(z, params->l); + /* Step 21: z = y + cs1 */ + dilithium_vec_add(z, y, params->l); + dilithium_vec_red(z, params->l); + /* Step 23: Check z has low enough values. */ + hi = (1 << params->gamma1_bits) - params->beta; + valid = dilithium_vec_check_low(z, params->l, hi); + } + if (valid) { + /* Step 25: ct0 = NTT-1(c o t0) */ + dilithium_vec_mul(ct0, c, t0, params->k); + dilithium_vec_invntt(ct0, params->k); + /* Step 27: Check ct0 has low enough values. */ + hi = params->gamma2; + valid = dilithium_vec_check_low(ct0, params->k, hi); + } + if (valid) { + /* Step 26: ct0 = ct0 + w0 */ + dilithium_vec_add(ct0, w0, params->k); + dilithium_vec_red(ct0, params->k); + /* Step 26, 27: Make hint from ct0 and w1 and check + * number of hints is valid. + * Step 32: h is encoded into signature. + */ + valid = (dilithium_make_hint(ct0, w1, params->k, + params->gamma2, params->omega, h) >= 0); + } + } + } + + if (!valid) { + /* Too many attempts - something wrong with implementation. */ + if ((kappa > (word16)(kappa + params->l))) { + ret = BAD_COND_E; + } + + /* Step 30: increment value to append to seed to unique value. + */ + kappa += params->l; + } + } + /* Step 11: Check we have a valid signature. */ + while ((ret == 0) && (!valid)); + } + if (ret == 0) { + byte* ze = sig + params->lambda * 2; + /* Step 32: Encode z into signature. + * Commit (c) and h already encoded into signature. */ + dilithium_vec_encode_gamma1(z, params->l, params->gamma1_bits, ze); + } + + XFREE(y, NULL, DYNAMIC_TYPE_DILITHIUM); + return ret; +#else + int ret = 0; + const wc_dilithium_params* params = key->params; + byte* pub_seed = key->k; + byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + byte* tr = k + DILITHIUM_K_SZ; + const byte* s1p = tr + DILITHIUM_TR_SZ; + const byte* s2p = s1p + params->s1EncSz; + const byte* t0p = s2p + params->s2EncSz; + sword32* a = NULL; + sword32* s1 = NULL; + sword32* s2 = NULL; + sword32* t0 = NULL; + sword32* y = NULL; + sword32* y_ntt = NULL; + sword32* w0 = NULL; + sword32* w1 = NULL; + sword32* c = NULL; + sword32* z = NULL; + sword32* ct0 = NULL; + byte data[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = data + DILITHIUM_RND_SZ; + byte priv_rand_seed[DILITHIUM_Y_SEED_SZ]; + byte* h = sig + params->lambda * 2 + params->zEncSz; + + /* Check the signature buffer isn't too small. */ + if ((ret == 0) && (*sigLen < params->sigSz)) { + ret = BUFFER_E; + } + if (ret == 0) { + /* Return the size of the signature. */ + *sigLen = params->sigSz; + } + + /* Allocate memory for large intermediates. */ + if (ret == 0) { + unsigned int allocSz; + + /* y-l, w0-k, w1-k, c-1, s1-1, A-1 */ + allocSz = params->s1Sz + params->s2Sz + params->s2Sz + + DILITHIUM_POLY_SIZE + DILITHIUM_POLY_SIZE + DILITHIUM_POLY_SIZE; + y = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (y == NULL) { + ret = MEMORY_E; + } + else { + w0 = y + params->s1Sz / sizeof(*y_ntt); + w1 = w0 + params->s2Sz / sizeof(*w0); + c = w1 + params->s2Sz / sizeof(*w1); + s1 = c + DILITHIUM_N; + a = s1 + DILITHIUM_N; + s2 = s1; + t0 = s1; + ct0 = s1; + z = s1; + y_ntt = s1; + } + } + + if (ret == 0) { + /* Step 7: Copy random into buffer for hashing. */ + XMEMCPY(data, seed, DILITHIUM_RND_SZ); + + /* Step 6: Compute the hash of tr, public key hash, and message. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + /* Step 9: Compute private random using hash. */ + ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, data, + DILITHIUM_RND_SZ + DILITHIUM_MU_SZ, priv_rand_seed, + DILITHIUM_PRIV_RAND_SEED_SZ); + } + if (ret == 0) { + word16 kappa = 0; + int valid; + + /* Step 11: Start rejection sampling loop */ + do { + byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; + sword32* w = w1; + byte* commit = sig; + byte r; + byte s; + byte aseed[DILITHIUM_GEN_A_SEED_SZ]; + sword32 hi; + sword32* at = a; + sword32* wt = w; + sword32* w0t = w0; + sword32* w1t = w1; + + valid = 1; + /* Step 12: Compute vector y from private random seed and kappa. */ + dilithium_vec_expand_mask(&key->shake, priv_rand_seed, kappa, + params->gamma1_bits, y, params->l); + #ifdef WOLFSSL_DILITHIUM_SIGN_CHECK_Y + valid = dilithium_vec_check_low(y, params->l, + (1 << params->gamma1_bits) - params->beta); + #endif + + /* Step 5: Create the matrix A from the public seed. */ + /* Copy the seed into a buffer that has space for s and r. */ + XMEMCPY(aseed, pub_seed, DILITHIUM_PUB_SEED_SZ); + /* Alg 26. Step 1: Loop over first dimension of matrix. */ + for (r = 0; (ret == 0) && valid && (r < params->k); r++) { + unsigned int e; + sword32* yt = y; + + /* Put r/i into buffer to be hashed. */ + aseed[DILITHIUM_PUB_SEED_SZ + 1] = r; + /* Alg 26. Step 2: Loop over second dimension of matrix. */ + for (s = 0; (ret == 0) && (s < params->l); s++) { + /* Put s into buffer to be hashed. */ + aseed[DILITHIUM_PUB_SEED_SZ + 0] = s; + /* Alg 26. Step 3: Create polynomial from hashing seed. */ + ret = dilithium_rej_ntt_poly(&key->shake, aseed, at, + NULL); + if (ret != 0) { + break; + } + XMEMCPY(y_ntt, yt, DILITHIUM_POLY_SIZE); + dilithium_ntt(y_ntt); + /* Matrix multiply. */ + if (s == 0) { + for (e = 0; e < DILITHIUM_N; e++) { + wt[e] = dilithium_mont_red((sword64)at[e] * + y_ntt[e]); + } + } + else { + for (e = 0; e < DILITHIUM_N; e++) { + wt[e] += dilithium_mont_red((sword64)at[e] * + y_ntt[e]); + } + } + /* Next polynomial. */ + yt += DILITHIUM_N; + } + dilithium_invntt(wt); + /* Step 14, Step 22: Make values positive and decompose. */ + dilithium_make_pos(wt); + #ifndef WOLFSSL_NO_ML_DSA_44 + if (params->gamma2 == DILITHIUM_Q_LOW_88) { + /* For each value of polynomial. */ + for (e = 0; e < DILITHIUM_N; e++) { + /* Decompose value into two vectors. */ + dilithium_decompose_q88(wt[e], &w0t[e], &w1t[e]); + } + } + #endif + #if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (params->gamma2 == DILITHIUM_Q_LOW_32) { + /* For each value of polynomial. */ + for (e = 0; e < DILITHIUM_N; e++) { + /* Decompose value into two vectors. */ + dilithium_decompose_q32(wt[e], &w0t[e], &w1t[e]); + } + } + #endif + #ifdef WOLFSSL_DILITHIUM_SIGN_CHECK_W0 + valid = dilithium_vec_check_low(w0t, + params->gamma2 - params->beta); + #endif + wt += DILITHIUM_N; + w0t += DILITHIUM_N; + w1t += DILITHIUM_N; + } + if ((ret == 0) && valid) { + sword32* yt = y; + const byte* s1pt = s1p; + byte* ze = sig + params->lambda * 2; + + /* Step 15: Encode w1. */ + dilithium_vec_encode_w1(w1, params->k, params->gamma2, w1e); + /* Step 15: Hash mu and encoded w1. + * Step 32: Hash is stored in signature. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, + w1e, params->w1EncSz, commit, 2 * params->lambda); + if (ret == 0) { + /* Step 17: Compute c from first 256 bits of commit. */ + ret = dilithium_sample_in_ball(&key->shake, commit, + params->tau, c, NULL); + } + if (ret == 0) { + /* Step 18: NTT(c). */ + dilithium_ntt_small(c); + } + + for (s = 0; (ret == 0) && valid && (s < params->l); s++) { + #if !defined(WOLFSSL_NO_ML_DSA_44) || \ + !defined(WOLFSSL_NO_ML_DSA_87) + /* -2..2 */ + if (params->eta == DILITHIUM_ETA_2) { + dilithium_decode_eta_2_bits(s1pt, s1); + s1pt += DILITHIUM_ETA_2_BITS * DILITHIUM_N / 8; + } + #endif + #ifndef WOLFSSL_NO_ML_DSA_65 + /* -4..4 */ + if (params->eta == DILITHIUM_ETA_4) { + dilithium_decode_eta_4_bits(s1pt, s1); + s1pt += DILITHIUM_N / 2; + } + #endif + dilithium_ntt_small(s1); + dilithium_mul(z, c, s1); + /* Step 19: cs1 = NTT-1(c o s1) */ + dilithium_invntt(z); + /* Step 21: z = y + cs1 */ + dilithium_add(z, yt); + dilithium_poly_red(z); + /* Step 23: Check z has low enough values. */ + hi = (1 << params->gamma1_bits) - params->beta; + valid = dilithium_check_low(z, hi); + if (valid) { + /* Step 32: Encode z into signature. + * Commit (c) and h already encoded into signature. */ + #if !defined(WOLFSSL_NO_ML_DSA_44) + if (params->gamma1_bits == DILITHIUM_GAMMA1_BITS_17) { + dilithium_encode_gamma1_17_bits(z, ze); + /* Move to next place to encode to. */ + ze += DILITHIUM_GAMMA1_17_ENC_BITS / 2 * + DILITHIUM_N / 4; + } + else + #endif + #if !defined(WOLFSSL_NO_ML_DSA_65) || \ + !defined(WOLFSSL_NO_ML_DSA_87) + if (params->gamma1_bits == DILITHIUM_GAMMA1_BITS_19) { + dilithium_encode_gamma1_19_bits(z, ze); + /* Move to next place to encode to. */ + ze += DILITHIUM_GAMMA1_19_ENC_BITS / 2 * + DILITHIUM_N / 4; + } + #endif + } + + yt += DILITHIUM_N; + } + } + if ((ret == 0) && valid) { + const byte* t0pt = t0p; + const byte* s2pt = s2p; + sword32* cs2 = ct0; + w0t = w0; + w1t = w1; + byte idx = 0; + + for (r = 0; valid && (r < params->k); r++) { + #if !defined(WOLFSSL_NO_ML_DSA_44) || \ + !defined(WOLFSSL_NO_ML_DSA_87) + /* -2..2 */ + if (params->eta == DILITHIUM_ETA_2) { + dilithium_decode_eta_2_bits(s2pt, s2); + s2pt += DILITHIUM_ETA_2_BITS * DILITHIUM_N / 8; + } + #endif + #ifndef WOLFSSL_NO_ML_DSA_65 + /* -4..4 */ + if (params->eta == DILITHIUM_ETA_4) { + dilithium_decode_eta_4_bits(s2pt, s2); + s2pt += DILITHIUM_N / 2; + } + #endif + dilithium_ntt_small(s2); + /* Step 20: cs2 = NTT-1(c o s2) */ + dilithium_mul(cs2, c, s2); + dilithium_invntt(cs2); + /* Step 22: w0 - cs2 */ + dilithium_sub(w0t, cs2); + dilithium_poly_red(w0t); + /* Step 23: Check w0 - cs2 has low enough values. */ + hi = params->gamma2 - params->beta; + valid = dilithium_check_low(w0t, hi); + if (valid) { + dilithium_decode_t0(t0pt, t0); + dilithium_ntt(t0); + + /* Step 25: ct0 = NTT-1(c o t0) */ + dilithium_mul(ct0, c, t0); + dilithium_invntt(ct0); + /* Step 27: Check ct0 has low enough values. */ + valid = dilithium_check_low(ct0, params->gamma2); + } + if (valid) { + /* Step 26: ct0 = ct0 + w0 */ + dilithium_add(ct0, w0t); + dilithium_poly_red(ct0); + + /* Step 26, 27: Make hint from ct0 and w1 and check + * number of hints is valid. + * Step 32: h is encoded into signature. + */ + #ifndef WOLFSSL_NO_ML_DSA_44 + if (params->gamma2 == DILITHIUM_Q_LOW_88) { + valid = (dilithium_make_hint_88(ct0, w1t, h, + &idx) == 0); + /* Alg 14, Step 10: Store count of hints for + * polynomial at end of list. */ + h[PARAMS_ML_DSA_44_OMEGA + r] = idx; + } + #endif + #if !defined(WOLFSSL_NO_ML_DSA_65) || \ + !defined(WOLFSSL_NO_ML_DSA_87) + if (params->gamma2 == DILITHIUM_Q_LOW_32) { + valid = (dilithium_make_hint_32(ct0, w1t, + params->omega, h, &idx) == 0); + /* Alg 14, Step 10: Store count of hints for + * polynomial at end of list. */ + h[params->omega + r] = idx; + } + #endif + } + + t0pt += DILITHIUM_D * DILITHIUM_N / 8; + w0t += DILITHIUM_N; + w1t += DILITHIUM_N; + } + /* Set remaining hints to zero. */ + XMEMSET(h + idx, 0, params->omega - idx); + } + + if (!valid) { + /* Too many attempts - something wrong with implementation. */ + if ((kappa > (word16)(kappa + params->l))) { + ret = BAD_COND_E; + } + + /* Step 30: increment value to append to seed to unique value. + */ + kappa += params->l; + } + } + /* Step 11: Check we have a valid signature. */ + while ((ret == 0) && (!valid)); + } + + XFREE(y, NULL, DYNAMIC_TYPE_DILITHIUM); + return ret; +#endif +} + +/* Sign a message with the key and a random number generator. + * + * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * ... + * 7: rnd <- {0,1}256 [Randomly generated.] + * ... + * + * @param [in, out] key Dilithium key. + * @param [in, out] rng Random number generator. + * @param [in] msg Message data to sign. + * @param [in] msgLen Length of message data in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_msg(dilithium_key* key, WC_RNG* rng, const byte* msg, + word32 msgLen, byte* sig, word32 *sigLen) +{ + int ret = 0; + byte rnd[DILITHIUM_RND_SZ]; + + /* Must have a random number generator. */ + if (rng == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Step 7: Generate random seed. */ + ret = wc_RNG_GenerateBlock(rng, rnd, DILITHIUM_RND_SZ); + } + if (ret == 0) { + /* Sign with random seed. */ + ret = dilithium_sign_msg_with_seed(key, rnd, msg, msgLen, sig, + sigLen); + } + + return ret; +} + +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY + +#ifndef WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM +static void dilithium_make_pub_vec(dilithium_key* key, sword32* t1) +{ + const wc_dilithium_params* params = key->params; + const byte* t1p = key->p + DILITHIUM_PUB_SEED_SZ; + + dilithium_vec_decode_t1(t1p, params->k, t1); + dilithium_vec_ntt(t1, params->k); + +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + key->pubVecSet = 1; +#endif +} +#endif + +/* Verify signature of message using public key. + * + * FIPS 204. 6: Algorithm 3 ML-DSA.Verify(pk, M, sigma) + * 1: (rho, t1) <- pkDecode(pk) + * 2: (c_tilde, z, h) <- sigDecode(sigma) + * 3: if h = falsam then return false + * 4: end if + * 5: A_circum <- ExpandS(rho) + * 6: tr <- H(BytesToBits(pk), 512) + * 7: mu <- H(tr||M, 512) + * 8: (c1_tilde, c2_tilde) E {0,1}256 x {0,1)2*lambda-256 <- c_tilde + * 9: c <- SampleInBall(c1_tilde) + * 10: w'approx <- NTT-1(A_circum o NTT(z) - NTT(c) o NTT(t1.s^d)) + * 11: w1' <- UseHint(h, w'approx) + * 12: c'_tilde < H(mu||w1Encode(w1'), 2*lambda) + * 13: return [[ ||z||inf < GAMMA1 - BETA]] and [[c_tilde = c'_tilde]] and + * [[number of 1's in h is <= OMEGA + * + * @param [in, out] key Dilithium key. + * @param [in] msg Message to verify. + * @param [in] msgLen Length of message in bytes. + * @param [in] sig Signature to verify message. + * @param [in] sigLen Length of message in bytes. + * @param [out] res Result of verification. + * @return 0 on success. + * @return SIG_VERIFY_E when hint is malformed. + * @return BUFFER_E when the length of the signature does not match + * parameters. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_verify_msg(dilithium_key* key, const byte* msg, + word32 msgLen, const byte* sig, word32 sigLen, int* res) +{ +#ifndef WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM + int ret = 0; + const wc_dilithium_params* params = key->params; + const byte* pub_seed = key->p; + const byte* commit = sig; + const byte* ze = sig + params->lambda * 2; + const byte* h = ze + params->zEncSz; + sword32* a = NULL; + sword32* t1 = NULL; + sword32* c = NULL; + sword32* z = NULL; + sword32* w = NULL; + sword32* t1c = NULL; + byte tr[DILITHIUM_TR_SZ]; + byte* mu = tr; + byte* w1e = NULL; + byte* commit_calc = tr; + int valid = 0; + sword32 hi; + + /* Ensure the signature is the right size for the parameters. */ + if (sigLen != params->sigSz) { + ret = BUFFER_E; + } + if (ret == 0) { + /* Step 13: Verify the hint is well-formed. */ + ret = dilithium_check_hint(h, params->k, params->omega); + } + + /* Allocate memory for large intermediates. */ +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + if ((ret == 0) && (key->a == NULL)) { + key->a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->a == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + a = key->a; + } +#endif +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + if ((ret == 0) && (key->t1 == NULL)) { + key->t1 = (sword32*)XMALLOC(params->s2Sz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->t1 == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + t1 = key->t1; + } +#endif + if (ret == 0) { + unsigned int allocSz; + + /* z, c, w, t1/t1c */ + allocSz = DILITHIUM_POLY_SIZE + params->s1Sz + params->s2Sz + + params->s2Sz; +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + /* a */ + allocSz += params->aSz; +#endif -#ifdef HAVE_CONFIG_H - #include + z = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (z == NULL) { + ret = MEMORY_E; + } + else { + c = z + params->s1Sz / sizeof(*z); + w = c + DILITHIUM_N; +#ifndef WC_DILITHIUM_CACHE_PUB_VECTORS + t1 = w + params->s2Sz / sizeof(*w); + t1c = t1; +#else + t1c = w + params->s2Sz / sizeof(*w); +#endif +#ifndef WC_DILITHIUM_CACHE_MATRIX_A + a = t1 + params->s2Sz / sizeof(*t1); #endif + w1e = (byte*)c; + } + } -/* in case user set HAVE_PQC there */ -#include + if (ret == 0) { + /* Step 2: Decode z from signature. */ + dilithium_vec_decode_gamma1(ze, params->l, params->gamma1_bits, z); + /* Step 13: Check z is valid - values are low enough. */ + hi = (1 << params->gamma1_bits) - params->beta; + valid = dilithium_vec_check_low(z, params->l, hi); + } + if ((ret == 0) && valid) { +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + /* Check that we haven't already cached the public vector. */ + if (!key->pubVecSet) +#endif + { + /* Step 1: Decode and NTT vector t1. */ + dilithium_make_pub_vec(key, t1); + } -#include +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Check that we haven't already cached the matrix A. */ + if (!key->aSet) +#endif + { + /* Step 5: Expand pub seed to compute matrix A. */ + ret = dilithium_expand_a(&key->shake, pub_seed, params->k, + params->l, a); +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Whether we have cached A is dependent on success of operation. */ + key->aSet = (ret == 0); +#endif + } + } + if ((ret == 0) && valid) { + /* Step 6: Hash public key. */ + ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if ((ret == 0) && valid) { + /* Step 7: Hash hash of public key and message. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if ((ret == 0) && valid) { + /* Step 9: Compute c from first 256 bits of commit. */ + ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, + NULL); + } + if ((ret == 0) && valid) { + /* Step 10: w = NTT-1(A o NTT(z) - NTT(c) o NTT(t1)) */ + dilithium_vec_ntt(z, params->l); + dilithium_matrix_mul(w, a, z, params->k, params->l); + dilithium_ntt_small(c); + dilithium_vec_mul(t1c, c, t1, params->k); + dilithium_vec_sub(w, t1c, params->k); + dilithium_vec_invntt(w, params->k); + /* Step 11: Use hint to give full w1. */ + dilithium_vec_use_hint(w, params->k, params->gamma2, params->omega, h); + /* Step 12: Encode w1. */ + dilithium_vec_encode_w1(w, params->k, params->gamma2, w1e); + /* Step 12: Hash mu and encoded w1. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, w1e, + params->w1EncSz, commit_calc, 2 * params->lambda); + } + if ((ret == 0) && valid) { + /* Step 13: Compare commit. */ + valid = (XMEMCMP(commit, commit_calc, 2 * params->lambda) == 0); + } -#if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) + *res = valid; + XFREE(z, NULL, DYNAMIC_TYPE_DILITHIUM); + return ret; +#else + int ret = 0; + const wc_dilithium_params* params = key->params; + const byte* pub_seed = key->p; + const byte* t1p = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* commit = sig; + const byte* ze = sig + params->lambda * 2; + const byte* h = ze + params->zEncSz; + sword32* t1 = NULL; + sword32* a = NULL; + sword32* c = NULL; + sword32* z = NULL; + sword32* w = NULL; + byte tr[DILITHIUM_TR_SZ]; + byte* mu = tr; + byte* w1e = NULL; + byte* commit_calc = tr; + int valid = 0; + sword32 hi; + byte i; + unsigned int j; + byte o; + byte* encW1; + byte* seed = tr; + + /* Ensure the signature is the right size for the parameters. */ + if (sigLen != params->sigSz) { + ret = BUFFER_E; + } + if (ret == 0) { + /* Step 13: Verify the hint is well-formed. */ + ret = dilithium_check_hint(h, params->k, params->omega); + } -#ifdef HAVE_LIBOQS -#include +#ifndef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + /* Allocate memory for large intermediates. */ + if (ret == 0) { + /* z, c, w, t1, w1e. */ + z = (sword32*)XMALLOC(params->s1Sz + 3 * DILITHIUM_POLY_SIZE + + DILITHIUM_MAX_W1_ENC_SZ, NULL, DYNAMIC_TYPE_DILITHIUM); + if (z == NULL) { + ret = MEMORY_E; + } + else { + c = z + params->s1Sz / sizeof(*t1); + w = c + DILITHIUM_N; + t1 = w + DILITHIUM_N; + w1e = (byte*)(t1 + DILITHIUM_N); + a = t1; + } + } +#else + if (ret == 0) { + z = key->z; + c = key->c; + w = key->w; + t1 = key->t1; + w1e = key->w1e; + a = t1; + } #endif -#include -#include -#ifdef NO_INLINE - #include + if (ret == 0) { + /* Step 2: Decode z from signature. */ + dilithium_vec_decode_gamma1(ze, params->l, params->gamma1_bits, z); + /* Step 13: Check z is valid - values are low enough. */ + hi = (1 << params->gamma1_bits) - params->beta; + valid = dilithium_vec_check_low(z, params->l, hi); + } + if ((ret == 0) && valid) { + /* Step 10: NTT(z) */ + dilithium_vec_ntt(z, params->l); + + /* Step 9: Compute c from first 256 bits of commit. */ +#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, + key->block); #else - #define WOLFSSL_MISC_INCLUDED - #include + ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, + NULL); +#endif + } + if ((ret == 0) && valid) { + dilithium_ntt_small(c); + + o = 0; + encW1 = w1e; + + /* Copy the seed into a buffer that has space for s and r. */ + XMEMCPY(seed, pub_seed, DILITHIUM_PUB_SEED_SZ); + /* Step 1: Loop over first dimension of matrix. */ + for (i = 0; (ret == 0) && (i < params->k); i++) { + byte s; + const sword32* zt = z; + + /* Step 1: Decode and NTT vector t1. */ + dilithium_decode_t1(t1p, w); + /* Next polynomial. */ + t1p += DILITHIUM_U * DILITHIUM_N / 8; + + /* Step 10: - NTT(c) o NTT(t1)) */ + dilithium_ntt(w); +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + w[j] = -dilithium_mont_red((sword64)c[j] * w[j]); + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + w[j+0] = -dilithium_mont_red((sword64)c[j+0] * w[j+0]); + w[j+1] = -dilithium_mont_red((sword64)c[j+1] * w[j+1]); + w[j+2] = -dilithium_mont_red((sword64)c[j+2] * w[j+2]); + w[j+3] = -dilithium_mont_red((sword64)c[j+3] * w[j+3]); + w[j+4] = -dilithium_mont_red((sword64)c[j+4] * w[j+4]); + w[j+5] = -dilithium_mont_red((sword64)c[j+5] * w[j+5]); + w[j+6] = -dilithium_mont_red((sword64)c[j+6] * w[j+6]); + w[j+7] = -dilithium_mont_red((sword64)c[j+7] * w[j+7]); + } #endif -/* Sign the message using the dilithium private key. - * - * in [in] Message to sign. - * inLen [in] Length of the message in bytes. - * out [in] Buffer to write signature into. - * outLen [in/out] On in, size of buffer. - * On out, the length of the signature in bytes. - * key [in] Dilithium key to use when signing - * returns BAD_FUNC_ARG when a parameter is NULL or public key not set, - * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, - * 0 otherwise. - */ -int wc_dilithium_sign_msg(const byte* in, word32 inLen, - byte* out, word32 *outLen, - dilithium_key* key, WC_RNG* rng) + /* Step 5: Expand pub seed to compute matrix A. */ + /* Put r into buffer to be hashed. */ + seed[DILITHIUM_PUB_SEED_SZ + 1] = i; + for (s = 0; (ret == 0) && (s < params->l); s++) { + /* Put s into buffer to be hashed. */ + seed[DILITHIUM_PUB_SEED_SZ + 0] = s; + /* Step 3: Create polynomial from hashing seed. */ + #ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + ret = dilithium_rej_ntt_poly(&key->shake, seed, a, key->h); + #else + ret = dilithium_rej_ntt_poly(&key->shake, seed, a, NULL); + #endif + + /* Step 10: w = A o NTT(z) - NTT(c) o NTT(t1) */ +#ifdef WOLFSSL_DILITHIUM_SMALL + for (j = 0; j < DILITHIUM_N; j++) { + w[j] += dilithium_mont_red((sword64)a[j] * zt[j]); + } +#else + for (j = 0; j < DILITHIUM_N; j += 8) { + w[j+0] += dilithium_mont_red((sword64)a[j+0] * zt[j+0]); + w[j+1] += dilithium_mont_red((sword64)a[j+1] * zt[j+1]); + w[j+2] += dilithium_mont_red((sword64)a[j+2] * zt[j+2]); + w[j+3] += dilithium_mont_red((sword64)a[j+3] * zt[j+3]); + w[j+4] += dilithium_mont_red((sword64)a[j+4] * zt[j+4]); + w[j+5] += dilithium_mont_red((sword64)a[j+5] * zt[j+5]); + w[j+6] += dilithium_mont_red((sword64)a[j+6] * zt[j+6]); + w[j+7] += dilithium_mont_red((sword64)a[j+7] * zt[j+7]); + } +#endif + /* Next polynomial. */ + zt += DILITHIUM_N; + } + + /* Step 10: w = NTT-1(A o NTT(z) - NTT(c) o NTT(t1)) */ + dilithium_invntt(w); + +#ifndef WOLFSSL_NO_ML_DSA_44 + if (params->gamma2 == DILITHIUM_Q_LOW_88) { + /* Step 11: Use hint to give full w1. */ + dilithium_use_hint_88(w, h, i, &o); + /* Step 12: Encode w1. */ + dilithium_encode_w1_88(w, encW1); + encW1 += DILITHIUM_Q_HI_88_ENC_BITS * 2 * DILITHIUM_N / 16; + } + else +#endif +#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + if (params->gamma2 == DILITHIUM_Q_LOW_32) { + /* Step 11: Use hint to give full w1. */ + dilithium_use_hint_32(w, h, params->omega, i, &o); + /* Step 12: Encode w1. */ + dilithium_encode_w1_32(w, encW1); + encW1 += DILITHIUM_Q_HI_32_ENC_BITS * 2 * DILITHIUM_N / 16; + } + else +#endif + { + } + } + } + if ((ret == 0) && valid) { + /* Step 6: Hash public key. */ + ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if ((ret == 0) && valid) { + /* Step 7: Hash hash of public key and message. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if ((ret == 0) && valid) { + /* Step 12: Hash mu and encoded w1. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, w1e, + params->w1EncSz, commit_calc, 2 * params->lambda); + } + if ((ret == 0) && valid) { + /* Step 13: Compare commit. */ + valid = (XMEMCMP(commit, commit_calc, 2 * params->lambda) == 0); + } + + *res = valid; +#ifndef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + XFREE(z, NULL, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +#endif /* !WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM */ +} + +#endif /* WOLFSSL_DILITHIUM_NO_VERIFY */ + +#elif defined(HAVE_LIBOQS) + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY +static int oqs_dilithium_make_key(dilithium_key* key, WC_RNG* rng) { int ret = 0; + OQS_SIG *oqssig = NULL; - /* sanity check on arguments */ - if ((in == NULL) || (out == NULL) || (outLen == NULL) || (key == NULL)) { - return BAD_FUNC_ARG; + if (key->level == 2) { + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); + } + else if (key->level == 3) { + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); + } + else if (key->level == 5) { + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); + } + else { + ret = SIG_TYPE_E; } -#ifdef WOLF_CRYPTO_CB - #ifndef WOLF_CRYPTO_CB_FIND - if (key->devId != INVALID_DEVID) - #endif - { - ret = wc_CryptoCb_PqcSign(in, inLen, out, outLen, rng, - WC_PQC_SIG_TYPE_DILITHIUM, key); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - ret = 0; + if (ret == 0) { + ret = wolfSSL_liboqsRngMutexLock(rng); + if (ret == 0) { + if (OQS_SIG_keypair(oqssig, key->p, key->k) != OQS_SUCCESS) { + ret = BUFFER_E; + } + } + wolfSSL_liboqsRngMutexUnlock(); + } + if (ret == 0) { + key->prvKeySet = 1; + key->pubKeySet = 1; } -#endif -#ifdef HAVE_LIBOQS + if (oqssig != NULL) { + OQS_SIG_free(oqssig); + } + + return ret; +} +#endif /* WOLFSSL_DILITHIUM_NO_MAKE_KEY */ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN +static int oqs_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, + word32 *sigLen, dilithium_key* key, WC_RNG* rng) +{ + int ret = 0; OQS_SIG *oqssig = NULL; size_t localOutLen = 0; - if ((ret == 0) && (!key->prvKeySet)) { + if (!key->prvKeySet) { ret = BAD_FUNC_ARG; } if (ret == 0) { if (key->level == 2) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_2); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); } else if (key->level == 3) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_3); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); } else if (key->level == 5) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_5); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); } else { ret = SIG_TYPE_E; @@ -111,19 +6593,19 @@ int wc_dilithium_sign_msg(const byte* in, word32 inLen, /* check and set up out length */ if (ret == 0) { - if ((key->level == 2) && (*outLen < DILITHIUM_LEVEL2_SIG_SIZE)) { - *outLen = DILITHIUM_LEVEL2_SIG_SIZE; + if ((key->level == 2) && (*sigLen < DILITHIUM_LEVEL2_SIG_SIZE)) { + *sigLen = DILITHIUM_LEVEL2_SIG_SIZE; ret = BUFFER_E; } - else if ((key->level == 3) && (*outLen < DILITHIUM_LEVEL3_SIG_SIZE)) { - *outLen = DILITHIUM_LEVEL3_SIG_SIZE; + else if ((key->level == 3) && (*sigLen < DILITHIUM_LEVEL3_SIG_SIZE)) { + *sigLen = DILITHIUM_LEVEL3_SIG_SIZE; ret = BUFFER_E; } - else if ((key->level == 5) && (*outLen < DILITHIUM_LEVEL5_SIG_SIZE)) { - *outLen = DILITHIUM_LEVEL5_SIG_SIZE; + else if ((key->level == 5) && (*sigLen < DILITHIUM_LEVEL5_SIG_SIZE)) { + *sigLen = DILITHIUM_LEVEL5_SIG_SIZE; ret = BUFFER_E; } - localOutLen = *outLen; + localOutLen = *sigLen; } if (ret == 0) { @@ -131,13 +6613,13 @@ int wc_dilithium_sign_msg(const byte* in, word32 inLen, } if ((ret == 0) && - (OQS_SIG_sign(oqssig, out, &localOutLen, in, inLen, key->k) + (OQS_SIG_sign(oqssig, sig, &localOutLen, msg, msgLen, key->k) == OQS_ERROR)) { ret = BAD_FUNC_ARG; } if (ret == 0) { - *outLen = (word32)localOutLen; + *sigLen = (word32)localOutLen; } wolfSSL_liboqsRngMutexUnlock(); @@ -145,63 +6627,30 @@ int wc_dilithium_sign_msg(const byte* in, word32 inLen, if (oqssig != NULL) { OQS_SIG_free(oqssig); } -#else - ret = NOT_COMPILED_IN; -#endif return ret; } +#endif -/* Verify the message using the dilithium public key. - * - * sig [in] Signature to verify. - * sigLen [in] Size of signature in bytes. - * msg [in] Message to verify. - * msgLen [in] Length of the message in bytes. - * res [out] *res is set to 1 on successful verification. - * key [in] Dilithium key to use to verify. - * returns BAD_FUNC_ARG when a parameter is NULL or contextLen is zero when and - * BUFFER_E when sigLen is less than DILITHIUM_LEVEL2_SIG_SIZE, - * 0 otherwise. - */ -int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, - word32 msgLen, int* res, dilithium_key* key) +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY +static int oqs_dilithium_verify_msg(const byte* sig, word32 sigLen, + const byte* msg, word32 msgLen, int* res, dilithium_key* key) { int ret = 0; - - if (key == NULL || sig == NULL || msg == NULL || res == NULL) { - return BAD_FUNC_ARG; - } - -#ifdef WOLF_CRYPTO_CB - #ifndef WOLF_CRYPTO_CB_FIND - if (key->devId != INVALID_DEVID) - #endif - { - ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, res, - WC_PQC_SIG_TYPE_DILITHIUM, key); - if (ret != CRYPTOCB_UNAVAILABLE) - return ret; - /* fall-through when unavailable */ - ret = 0; - } -#endif - -#ifdef HAVE_LIBOQS OQS_SIG *oqssig = NULL; - if ((ret == 0) && (!key->pubKeySet)) { + if (!key->pubKeySet) { ret = BAD_FUNC_ARG; } if (ret == 0) { if (key->level == 2) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_2); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); } else if (key->level == 3) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_3); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); } else if (key->level == 5) { - oqssig = OQS_SIG_new(OQS_SIG_alg_dilithium_5); + oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); } else { ret = SIG_TYPE_E; @@ -219,18 +6668,233 @@ int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, } if (ret == 0) { - *res = 1; + *res = 1; + } + + if (oqssig != NULL) { + OQS_SIG_free(oqssig); + } + return ret; +} +#endif /* WOLFSSL_DILITHIUM_NO_VERIFY */ + +#else + #error "No dilithium implementation chosen." +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY +int wc_dilithium_make_key(dilithium_key* key, WC_RNG* rng) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_MakePqcSignatureKey(rng, + WC_PQC_SIG_TYPE_DILITHIUM, key->level, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + + if (ret == 0) { +#ifdef WOLFSSL_WC_DILITHIUM + /* Check the level or parameters have been set. */ + if (key->params == NULL) { + ret = BAD_STATE_E; + } + else { + /* Make the key. */ + ret = dilithium_make_key(key, rng); + } +#elif defined(HAVE_LIBOQS) + /* Make the key. */ + ret = oqs_dilithium_make_key(key, rng); +#endif + } + + return ret; +} + +int wc_dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (seed == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { +#ifdef WOLFSSL_WC_DILITHIUM + /* Check the level or parameters have been set. */ + if (key->params == NULL) { + ret = BAD_STATE_E; + } + else { + /* Make the key. */ + ret = dilithium_make_key_from_seed(key, seed); + } +#elif defined(HAVE_LIBOQS) + /* Make the key. */ + ret = NOT_COMPILED_IN; +#endif + } + + return ret; +} +#endif + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* Sign the message using the dilithium private key. + * + * msg [in] Message to sign. + * msgLen [in] Length of the message in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL or public key not set, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, + word32 *sigLen, dilithium_key* key, WC_RNG* rng) +{ + int ret = 0; + + /* Validate parameters. */ + if ((msg == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, rng, + WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_msg(key, rng, msg, msgLen, sig, sigLen); + #elif defined(HAVE_LIBOQS) + ret = oqs_dilithium_sign_msg(msg, msgLen, sig, sigLen, key, rng); + #endif + } + + return ret; +} + +/* Sign the message using the dilithium private key. + * + * msg [in] Message to sign. + * msgLen [in] Length of the message in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL or public key not set, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_msg_with_seed(const byte* msg, word32 msgLen, byte* sig, + word32 *sigLen, dilithium_key* key, byte* seed) +{ + int ret = 0; + + /* Validate parameters. */ + if ((msg == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_msg_with_seed(key, seed, msg, msgLen, sig, sigLen); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)msgLen; + (void)seed; + #endif + } + + return ret; +} +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* Verify the message using the dilithium public key. + * + * sig [in] Signature to verify. + * sigLen [in] Size of signature in bytes. + * msg [in] Message to verify. + * msgLen [in] Length of the message in bytes. + * res [out] *res is set to 1 on successful verification. + * key [in] Dilithium key to use to verify. + * returns BAD_FUNC_ARG when a parameter is NULL or contextLen is zero when and + * BUFFER_E when sigLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, + word32 msgLen, int* res, dilithium_key* key) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (msg == NULL) || (res == NULL)) { + ret = BAD_FUNC_ARG; + } + + #ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, res, + WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } } + #endif - if (oqssig != NULL) { - OQS_SIG_free(oqssig); + if (ret == 0) { + /* Verify message with signature. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_verify_msg(key, msg, msgLen, sig, sigLen, res); + #elif defined(HAVE_LIBOQS) + ret = oqs_dilithium_verify_msg(sig, sigLen, msg, msgLen, res, key); + #endif } -#else - ret = NOT_COMPILED_IN; -#endif return ret; } +#endif /* WOLFSSL_DILITHIUM_NO_VERIFY */ /* Initialize the dilithium private/public key. * @@ -251,73 +6915,85 @@ int wc_dilithium_init(dilithium_key* key) */ int wc_dilithium_init_ex(dilithium_key* key, void* heap, int devId) { + int ret = 0; + + (void)heap; + (void)devId; + + /* Validate parameters. */ if (key == NULL) { - return BAD_FUNC_ARG; + ret = BAD_FUNC_ARG; } - ForceZero(key, sizeof(*key)); - -#ifdef WOLF_CRYPTO_CB - key->devCtx = NULL; - key->devId = devId; -#endif -#ifdef WOLF_PRIVATE_KEY_ID - key->idLen = 0; - key->labelLen = 0; -#endif + if (ret == 0) { + /* Ensure all fields reset. */ + XMEMSET(key, 0, sizeof(*key)); - (void) heap; - (void) devId; + #ifdef WOLF_CRYPTO_CB + key->devCtx = NULL; + key->devId = devId; + #endif + #ifdef WOLF_PRIVATE_KEY_ID + key->idLen = 0; + key->labelLen = 0; + #endif + } - return 0; + return ret; } #ifdef WOLF_PRIVATE_KEY_ID int wc_dilithium_init_id(dilithium_key* key, const unsigned char* id, int len, - void* heap, int devId) + void* heap, int devId) { int ret = 0; - if (key == NULL) + if (key == NULL) { ret = BAD_FUNC_ARG; - if (ret == 0 && (len < 0 || len > DILITHIUM_MAX_ID_LEN)) + } + if ((ret == 0) && ((len < 0) || (len > DILITHIUM_MAX_ID_LEN))) { ret = BUFFER_E; + } - if (ret == 0) + if (ret == 0) { ret = wc_dilithium_init_ex(key, heap, devId); - if (ret == 0 && id != NULL && len != 0) { + } + if ((ret == 0) && (id != NULL) && (len != 0)) { XMEMCPY(key->id, id, (size_t)len); key->idLen = len; } - /* Set the maxiumum level here */ + /* Set the maximum level here */ wc_dilithium_set_level(key, 5); return ret; } int wc_dilithium_init_label(dilithium_key* key, const char* label, void* heap, - int devId) + int devId) { int ret = 0; int labelLen = 0; - if (key == NULL || label == NULL) + if ((key == NULL) || (label == NULL)) { ret = BAD_FUNC_ARG; + } if (ret == 0) { labelLen = (int)XSTRLEN(label); - if (labelLen == 0 || labelLen > DILITHIUM_MAX_LABEL_LEN) + if ((labelLen == 0) || (labelLen > DILITHIUM_MAX_LABEL_LEN)) { ret = BUFFER_E; + } } - if (ret == 0) + if (ret == 0) { ret = wc_dilithium_init_ex(key, heap, devId); + } if (ret == 0) { XMEMCPY(key->label, label, (size_t)labelLen); key->labelLen = labelLen; } - /* Set the maxiumum level here */ + /* Set the maximum level here */ wc_dilithium_set_level(key, 5); return ret; @@ -332,18 +7008,49 @@ int wc_dilithium_init_label(dilithium_key* key, const char* label, void* heap, */ int wc_dilithium_set_level(dilithium_key* key, byte level) { + int ret = 0; + + /* Validate parameters. */ if (key == NULL) { - return BAD_FUNC_ARG; + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (level != 2) && (level != 3) && (level != 5)) { + ret = BAD_FUNC_ARG; } - if (level != 2 && level != 3 && level != 5) { - return BAD_FUNC_ARG; + if (ret == 0) { +#ifdef WOLFSSL_WC_DILITHIUM + /* Get the parameters for level into key. */ + ret = dilithium_get_params(level, &key->params); } + if (ret == 0) { + /* Clear any cached items. */ + #ifdef WC_DILITHIUM_CACHE_MATRIX_A + XFREE(key->a, NULL, WOLFSSL_WC_DILITHIUM); + key->a = NULL; + key->aSet = 0; + #endif + #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + XFREE(key->s1, NULL, WOLFSSL_WC_DILITHIUM); + key->s1 = NULL; + key->s2 = NULL; + key->t0 = NULL; + key->privVecsSet = 0; + #endif + #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + XFREE(key->t1, NULL, WOLFSSL_WC_DILITHIUM); + key->t1 = NULL; + key->pubVecSet = 0; + #endif +#endif /* WOLFSSL_WC_DILITHIUM */ - key->level = level; - key->pubKeySet = 0; - key->prvKeySet = 0; - return 0; + /* Store level and indicate public and private key are not set. */ + key->level = level; + key->pubKeySet = 0; + key->prvKeySet = 0; + } + + return ret; } /* Get the level of the dilithium private/public key. @@ -354,16 +7061,23 @@ int wc_dilithium_set_level(dilithium_key* key, byte level) */ int wc_dilithium_get_level(dilithium_key* key, byte* level) { - if (key == NULL || level == NULL) { - return BAD_FUNC_ARG; + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (level == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (key->level != 2) && (key->level != 3) && + (key->level != 5)) { + ret = BAD_FUNC_ARG; } - if (key->level != 2 && key->level != 3 && key->level != 5) { - return BAD_FUNC_ARG; + if (ret == 0) { + /* Return level. */ + *level = key->level; } - *level = key->level; - return 0; + return ret; } /* Clears the dilithium key data @@ -373,687 +7087,1055 @@ int wc_dilithium_get_level(dilithium_key* key, byte* level) void wc_dilithium_free(dilithium_key* key) { if (key != NULL) { +#ifdef WOLFSSL_WC_DILITHIUM + /* Dispose of cached items. */ + #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + XFREE(key->t1, NULL, WOLFSSL_WC_DILITHIUM); + #endif + #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + XFREE(key->s1, NULL, WOLFSSL_WC_DILITHIUM); + #endif + #ifdef WC_DILITHIUM_CACHE_MATRIX_A + XFREE(key->a, NULL, WOLFSSL_WC_DILITHIUM); + #endif + /* Free the SHAKE-128/256 object. */ + wc_Shake256_Free(&key->shake); +#endif + /* Ensure all private data is zeroized. */ ForceZero(key, sizeof(*key)); } } -/* Export the dilithium public key. +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY +/* Returns the size of a dilithium private key. * - * key [in] Dilithium public key. - * out [in] Array to hold public key. - * outLen [in/out] On in, the number of bytes in array. - * On out, the number bytes put into array. - * returns BAD_FUNC_ARG when a parameter is NULL, - * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_PUB_KEY_SIZE, - * 0 otherwise. + * @param [in] key Dilithium private/public key. + * @return Private key size on success for set level. + * @return BAD_FUNC_ARG when key is NULL or level not set, */ -int wc_dilithium_export_public(dilithium_key* key, - byte* out, word32* outLen) +int wc_dilithium_size(dilithium_key* key) { - /* sanity check on arguments */ - if ((key == NULL) || (out == NULL) || (outLen == NULL)) { - return BAD_FUNC_ARG; - } + int ret = BAD_FUNC_ARG; - if ((key->level != 1) && (key->level != 5)) { - return BAD_FUNC_ARG; + if (key != NULL) { + if (key->level == 2) { + ret = DILITHIUM_LEVEL2_KEY_SIZE; + } + else if (key->level == 3) { + ret = DILITHIUM_LEVEL3_KEY_SIZE; + } + else if (key->level == 5) { + ret = DILITHIUM_LEVEL5_KEY_SIZE; + } } - if (!key->pubKeySet) { - return BAD_FUNC_ARG; - } + return ret; +} - /* check and set up out length */ - if ((key->level == 2) && (*outLen < DILITHIUM_LEVEL2_PUB_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; - return BUFFER_E; - } - else if ((key->level == 3) && (*outLen < DILITHIUM_LEVEL3_PUB_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; - return BUFFER_E; - } - else if ((key->level == 5) && (*outLen < DILITHIUM_LEVEL5_PUB_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; - return BUFFER_E; - } +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY +/* Returns the size of a dilithium private plus public key. + * + * @param [in] key Dilithium private/public key. + * @return Private key size on success for set level. + * @return BAD_FUNC_ARG when key is NULL or level not set, + */ +int wc_dilithium_priv_size(dilithium_key* key) +{ + int ret = BAD_FUNC_ARG; - if (key->level == 2) { - *outLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; - XMEMCPY(out, key->p, DILITHIUM_LEVEL2_PUB_KEY_SIZE); - } - else if (key->level == 3) { - *outLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; - XMEMCPY(out, key->p, DILITHIUM_LEVEL3_PUB_KEY_SIZE); - } - else if (key->level == 5) { - *outLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; - XMEMCPY(out, key->p, DILITHIUM_LEVEL5_PUB_KEY_SIZE); + if (key != NULL) { + if (key->level == 2) { + ret = DILITHIUM_LEVEL2_PRV_KEY_SIZE; + } + else if (key->level == 3) { + ret = DILITHIUM_LEVEL3_PRV_KEY_SIZE; + } + else if (key->level == 5) { + ret = DILITHIUM_LEVEL5_PRV_KEY_SIZE; + } } - return 0; + return ret; } -/* Import a dilithium public key from a byte array. - * Public key encoded in big-endian. +/* Returns the size of a dilithium private plus public key. * - * in [in] Array holding public key. - * inLen [in] Number of bytes of data in array. - * key [in] Dilithium public key. - * returns BAD_FUNC_ARG when a parameter is NULL or key format is not supported, - * 0 otherwise. + * @param [in] key Dilithium private/public key. + * @param [out] len Private key size for set level. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or level not set, */ -int wc_dilithium_import_public(const byte* in, word32 inLen, - dilithium_key* key) +int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len) { - /* sanity check on arguments */ - if ((in == NULL) || (key == NULL)) { - return BAD_FUNC_ARG; - } - - if ((key->level != 2) && (key->level != 3) && (key->level != 5)) { - return BAD_FUNC_ARG; - } + int ret = 0; - if ((key->level == 2) && (inLen != DILITHIUM_LEVEL2_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; - } - else if ((key->level == 3) && (inLen != DILITHIUM_LEVEL3_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; + *len = wc_dilithium_priv_size(key); + if (*len < 0) { + ret = *len; } - else if ((key->level == 5) && (inLen != DILITHIUM_LEVEL5_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; - } - - XMEMCPY(key->p, in, inLen); - key->pubKeySet = 1; - return 0; + return ret; } +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ +#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ -static int parse_private_key(const byte* priv, word32 privSz, - byte** out, word32 *outSz, - dilithium_key* key) { - word32 idx = 0; - int ret = 0; - int length = 0; +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY +/* Returns the size of a dilithium public key. + * + * @param [in] key Dilithium private/public key. + * @return Public key size on success for set level. + * @return BAD_FUNC_ARG when key is NULL or level not set, + */ +int wc_dilithium_pub_size(dilithium_key* key) +{ + int ret = BAD_FUNC_ARG; - /* sanity check on arguments */ - if ((priv == NULL) || (key == NULL)) { - return BAD_FUNC_ARG; + if (key != NULL) { + if (key->level == 2) { + ret = DILITHIUM_LEVEL2_PUB_KEY_SIZE; + } + else if (key->level == 3) { + ret = DILITHIUM_LEVEL3_PUB_KEY_SIZE; + } + else if (key->level == 5) { + ret = DILITHIUM_LEVEL5_PUB_KEY_SIZE; + } } - if ((key->level != 2) && (key->level != 3) && (key->level != 5)) { - return BAD_FUNC_ARG; - } + return ret; +} - /* At this point, it is still a PKCS8 private key. */ - if ((ret = ToTraditionalInline(priv, &idx, privSz)) < 0) { - return ret; - } +/* Returns the size of a dilithium public key. + * + * @param [in] key Dilithium private/public key. + * @param [out] len Public key size for set level. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or level not set, + */ +int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len) +{ + int ret = 0; - /* Now it is a octet_string(concat(priv,pub)) */ - if ((ret = GetOctetString(priv, &idx, &length, privSz)) < 0) { - return ret; + *len = wc_dilithium_pub_size(key); + if (*len < 0) { + ret = *len; } - *out = (byte *)priv + idx; - *outSz = privSz - idx; + return ret; +} +#endif - /* And finally it is concat(priv,pub). Key size check. */ - if ((key->level == 2) && (*outSz != DILITHIUM_LEVEL2_KEY_SIZE + - DILITHIUM_LEVEL2_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; - } - else if ((key->level == 3) && (*outSz != DILITHIUM_LEVEL3_KEY_SIZE + - DILITHIUM_LEVEL3_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; - } - else if ((key->level == 5) && (*outSz != DILITHIUM_LEVEL5_KEY_SIZE + - DILITHIUM_LEVEL5_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* Returns the size of a dilithium signature. + * + * @param [in] key Dilithium private/public key. + * @return Signature size on success for set level. + * @return BAD_FUNC_ARG when key is NULL or level not set, + */ +int wc_dilithium_sig_size(dilithium_key* key) +{ + int ret = BAD_FUNC_ARG; + + if (key != NULL) { + if (key->level == 2) { + ret = DILITHIUM_LEVEL2_SIG_SIZE; + } + else if (key->level == 3) { + ret = DILITHIUM_LEVEL3_SIG_SIZE; + } + else if (key->level == 5) { + ret = DILITHIUM_LEVEL5_SIG_SIZE; + } } - return 0; + return ret; } -/* Import a dilithium private key from a byte array. +/* Returns the size of a dilithium signature. * - * priv [in] Array holding private key. - * privSz [in] Number of bytes of data in array. - * key [in] Dilithium private key. - * returns BAD_FUNC_ARG when a parameter is NULL or privSz is less than - * DILITHIUM_LEVEL2_KEY_SIZE, - * 0 otherwise. + * @param [in] key Dilithium private/public key. + * @param [out] len Signature size for set level. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or level not set, */ -int wc_dilithium_import_private_only(const byte* priv, word32 privSz, - dilithium_key* key) +int wc_MlDsaKey_GetSigLen(MlDsaKey* key, int* len) { int ret = 0; - byte *newPriv = NULL; - word32 newPrivSz = 0; - if ((ret = parse_private_key(priv, privSz, &newPriv, &newPrivSz, key)) - != 0) { - return ret; + *len = wc_dilithium_sig_size(key); + if (*len < 0) { + ret = *len; } - XMEMCPY(key->k, newPriv, newPrivSz); - key->prvKeySet = 1; - - return 0; + return ret; } +#endif -/* Import a dilithium private and public keys from byte array(s). +#ifdef WOLFSSL_DILITHIUM_CHECK_KEY +/* Check the public key of the dilithium key matches the private key. * - * priv [in] Array holding private key or private+public keys - * privSz [in] Number of bytes of data in private key array. - * pub [in] Array holding public key (or NULL). - * pubSz [in] Number of bytes of data in public key array (or 0). - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when a required parameter is NULL or an invalid - * combination of keys/lengths is supplied, 0 otherwise. + * @param [in] key Dilithium private/public key. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or no private key available, + * @return PUBLIC_KEY_E when the public key is not set or doesn't match, + * @return MEMORY_E when dynamic memory allocation fails. */ -int wc_dilithium_import_private_key(const byte* priv, word32 privSz, - const byte* pub, word32 pubSz, - dilithium_key* key) +int wc_dilithium_check_key(dilithium_key* key) { int ret = 0; - byte *newPriv = NULL; - word32 newPrivSz = 0; +#ifdef WOLFSSL_WC_DILITHIUM + const wc_dilithium_params* params; + sword32* a = NULL; + sword32* s1 = NULL; + sword32* s2 = NULL; + sword32* t = NULL; + sword32* t0 = NULL; + sword32* t1 = NULL; + + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (!key->prvKeySet)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (!key->pubKeySet)) { + ret = PUBLIC_KEY_E; + } + + /* Any value in public key are valid. + * Public seed is hashed to generate matrix A. + * t1 is the top 10 bits of a number in range of 0..(Q-1). + * Q >> 13 = 0x3ff so all encoded values are valid. + */ + + if (ret == 0) { + params = key->params; + unsigned int allocSz; + + /* s1-L, s2-K, t0-K, t-K, t1-K */ + allocSz = params->s1Sz + 4 * params->s2Sz; +#if !defined(WC_DILITHIUM_CACHE_MATRIX_A) + /* A-KxL */ + allocSz += params->aSz; +#endif + + /* Allocate memory for large intermediates. */ + s1 = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + if (s1 == NULL) { + ret = MEMORY_E; + } + else { + s2 = s1 + params->s1Sz / sizeof(*s1); + t0 = s2 + params->s2Sz / sizeof(*s2); + t = t0 + params->s2Sz / sizeof(*t0); + t1 = t + params->s2Sz / sizeof(*t); +#if !defined(WC_DILITHIUM_CACHE_MATRIX_A) + a = t1 + params->s2Sz / sizeof(*t1); +#else + a = key->a; +#endif + } + } + + if (ret == 0) { +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Check that we haven't already cached the matrix A. */ + if (!key->aSet) +#endif + { + const byte* pub_seed = key->p; + + ret = dilithium_expand_a(&key->shake, pub_seed, params->k, + params->l, a); +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + key->aSet = (ret == 0); +#endif + } + } + if (ret == 0) { + const byte* s1p = key->k + DILITHIUM_PUB_SEED_SZ + DILITHIUM_K_SZ + + DILITHIUM_TR_SZ; + const byte* s2p = s1p + params->s1EncSz; + const byte* t0p = s2p + params->s2EncSz; + const byte* t1p = key->p + DILITHIUM_PUB_SEED_SZ; + sword32* tt = t; + unsigned int i; + unsigned int j; + sword32 x = 0; + + /* Get s1, s2 and t0 from private key. */ + dilithium_vec_decode_eta_bits(s1p, params->eta, s1, params->l); + dilithium_vec_decode_eta_bits(s2p, params->eta, s2, params->k); + dilithium_vec_decode_t0(t0p, params->k, t0); + + /* Get t1 from public key. */ + dilithium_vec_decode_t1(t1p, params->k, t1); + + /* Calcaluate t = NTT-1(A o NTT(s1)) + s2 */ + dilithium_vec_ntt_small(s1, params->l); + dilithium_matrix_mul(t, a, s1, params->k, params->l); + dilithium_vec_invntt(t, params->k); + dilithium_vec_add(t, s2, params->k); + /* Subtract t0 from t. */ + dilithium_vec_sub(t, t0, params->k); + /* Make t positive to match t1. */ + dilithium_vec_make_pos(t, params->k); + + /* Check t - t0 and t1 are the same. */ + for (i = 0; i < params->k; i++) { + for (j = 0; j < DILITHIUM_N; j++) { + x |= tt[j] ^ t1[j]; + } + tt += DILITHIUM_N; + t1 += DILITHIUM_N; + } + /* Check the public seed is the same in private and public key. */ + for (i = 0; i < DILITHIUM_PUB_SEED_SZ; i++) { + x |= key->p[i] ^ key->k[i]; + } - if ((ret = parse_private_key(priv, privSz, &newPriv, &newPrivSz, key)) - != 0) { - return ret; + if ((ret == 0) && (x != 0)) { + ret = PUBLIC_KEY_E; + } + } + + /* Dispose of allocated memory. */ + XFREE(s1, NULL, DYNAMIC_TYPE_DILITHIUM); +#else + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (!key->prvKeySet)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (!key->pubKeySet)) { + ret = PUBLIC_KEY_E; } - if (pub == NULL) { - if (pubSz != 0) { - return BAD_FUNC_ARG; + if (ret == 0) { + int i; + sword32 x = 0; + + /* Check the public seed is the same in private and public key. */ + for (i = 0; i < 32; i++) { + x |= key->p[i] ^ key->k[i]; } - if ((newPrivSz != DILITHIUM_LEVEL2_PRV_KEY_SIZE) && - (newPrivSz != DILITHIUM_LEVEL3_PRV_KEY_SIZE) && - (newPrivSz != DILITHIUM_LEVEL5_PRV_KEY_SIZE)) { - return BAD_FUNC_ARG; + if (x != 0) { + ret = PUBLIC_KEY_E; } + } +#endif /* WOLFSSL_WC_DILITHIUM */ + return ret; +} +#endif /* WOLFSSL_DILITHIUM_CHECK_KEY */ + +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY + +/* Export the dilithium public key. + * + * @param [in] key Dilithium public key. + * @param [out] out Array to hold public key. + * @param [in, out] outLen On in, the number of bytes in array. + * On out, the number bytes put into array. + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BUFFER_E when outLen is less than DILITHIUM_LEVEL2_PUB_KEY_SIZE. + */ +int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen) +{ + int ret = 0; + word32 inLen; + /* Validate parameters */ + if ((key == NULL) || (out == NULL) || (outLen == NULL)) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Get length passed in for checking. */ + inLen = *outLen; if (key->level == 2) { - pub = newPriv + DILITHIUM_LEVEL2_KEY_SIZE; - pubSz = DILITHIUM_LEVEL2_PUB_KEY_SIZE; + /* Set out length. */ + *outLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < DILITHIUM_LEVEL2_PUB_KEY_SIZE) { + ret = BUFFER_E; + } } else if (key->level == 3) { - pub = newPriv + DILITHIUM_LEVEL3_KEY_SIZE; - pubSz = DILITHIUM_LEVEL3_PUB_KEY_SIZE; + /* Set out length. */ + *outLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < DILITHIUM_LEVEL3_PUB_KEY_SIZE) { + ret = BUFFER_E; + } } else if (key->level == 5) { - pub = newPriv + DILITHIUM_LEVEL5_KEY_SIZE; - pubSz = DILITHIUM_LEVEL5_PUB_KEY_SIZE; + /* Set out length. */ + *outLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < DILITHIUM_LEVEL5_PUB_KEY_SIZE) { + ret = BUFFER_E; + } + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; } - } - else if ((pubSz != DILITHIUM_LEVEL2_PUB_KEY_SIZE) && - (pubSz != DILITHIUM_LEVEL3_PUB_KEY_SIZE) && - (pubSz != DILITHIUM_LEVEL5_PUB_KEY_SIZE)) { - return BAD_FUNC_ARG; } - /* import public key */ - ret = wc_dilithium_import_public(pub, pubSz, key); + /* Check public key available. */ + if ((ret == 0) && (!key->pubKeySet)) { + ret = BAD_FUNC_ARG; + } if (ret == 0) { - /* make the private key (priv + pub) */ - XMEMCPY(key->k, newPriv, newPrivSz); - key->prvKeySet = 1; + /* Copy public key out. */ + XMEMCPY(out, key->p, *outLen); } return ret; } -/* Export the dilithium private key. +/* Import a dilithium public key from a byte array. + * + * Public key encoded in big-endian. * - * key [in] Dilithium private key. - * out [in] Array to hold private key. - * outLen [in/out] On in, the number of bytes in array. - * On out, the number bytes put into array. - * returns BAD_FUNC_ARG when a parameter is NULL, - * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_KEY_SIZE, - * 0 otherwise. + * @param [in] in Array holding public key. + * @param [in] inLen Number of bytes of data in array. + * @param [in, out] key Dilithium public key. + * @return 0 on success. + * @return BAD_FUNC_ARG when in or key is NULL or key format is not supported. */ -int wc_dilithium_export_private_only(dilithium_key* key, byte* out, - word32* outLen) +int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key) { - /* sanity checks on arguments */ - if ((key == NULL) || (out == NULL) || (outLen == NULL)) { - return BAD_FUNC_ARG; - } - - if ((key->level != 2) && (key->level != 3) && (key->level != 5)) { - return BAD_FUNC_ARG; - } + int ret = 0; - /* check and set up out length */ - if ((key->level == 2) && (*outLen < DILITHIUM_LEVEL2_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL2_KEY_SIZE; - return BUFFER_E; - } - else if ((key->level == 3) && (*outLen < DILITHIUM_LEVEL3_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL3_KEY_SIZE; - return BUFFER_E; + /* Validate parameters. */ + if ((in == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; } - else if ((key->level == 5) && (*outLen < DILITHIUM_LEVEL5_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL5_KEY_SIZE; - return BUFFER_E; + if (ret == 0) { + if (key->level == 2) { + /* Check length. */ + if (inLen != DILITHIUM_LEVEL2_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } + else if (key->level == 3) { + /* Check length. */ + if (inLen != DILITHIUM_LEVEL3_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } + else if (key->level == 5) { + /* Check length. */ + if (inLen != DILITHIUM_LEVEL5_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } } - if (key->level == 2) { - *outLen = DILITHIUM_LEVEL2_KEY_SIZE; + if (ret == 0) { + /* Copy the private key data in or copy pointer. */ + #ifndef WOLFSSL_DILITHIUM_ASSIGN_KEY + XMEMCPY(key->p, in, inLen); + #else + key->p = in; + #endif + + #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + /* Allocate t1 if required. */ + if (key->t1 == NULL) { + key->t1 = (sword32*)XMALLOC(key->params->s2Sz, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (key->t1 == NULL) { + ret = MEMORY_E; + } + } } - else if (key->level == 3) { - *outLen = DILITHIUM_LEVEL3_KEY_SIZE; + if (ret == 0) { + /* Compute t1 from public key data. */ + dilithium_make_pub_vec(key, key->t1); + #endif + #ifdef WC_DILITHIUM_CACHE_MATRIX_A + /* Allocate matrix a if required. */ + if (key->a == NULL) { + key->a = (sword32*)XMALLOC(key->params->aSz, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (key->a == NULL) { + ret = MEMORY_E; + } + } } - else if (key->level == 5) { - *outLen = DILITHIUM_LEVEL5_KEY_SIZE; + if (ret == 0) { + /* Compute matrix a from public key data. */ + ret = dilithium_expand_a(&key->shake, key->p, key->params->k, + key->params->l, key->a); + if (ret == 0) { + key->aSet = 1; + } + } + if (ret == 0) { + #endif + /* Public key is set. */ + key->pubKeySet = 1; } - XMEMCPY(out, key->k, *outLen); - - return 0; + return ret; } -/* Export the dilithium private and public key. +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ + +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY + +/* Set the private key data into key. * - * key [in] Dilithium private/public key. - * out [in] Array to hold private and public key. - * outLen [in/out] On in, the number of bytes in array. - * On out, the number bytes put into array. - * returns BAD_FUNC_ARG when a parameter is NULL, - * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_PRV_KEY_SIZE, - * 0 otherwise. + * @param [in] priv Private key data. + * @param [in] privSz Size of private key data in bytes. + * @param in, out] key Dilithium key to set into. + * @return 0 on success. + * @return BAD_FUNC_ARG when private key size is invalid. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Other negative on hash error. */ -int wc_dilithium_export_private(dilithium_key* key, byte* out, word32* outLen) +static int dilithium_set_priv_key(const byte* priv, word32 privSz, + dilithium_key* key) { - /* sanity checks on arguments */ - if ((key == NULL) || (out == NULL) || (outLen == NULL)) { - return BAD_FUNC_ARG; + int ret = 0; +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + const wc_dilithium_params* params = key->params; +#endif + + /* Validate parameters. */ + if ((privSz != DILITHIUM_LEVEL2_KEY_SIZE) && + (privSz != DILITHIUM_LEVEL3_KEY_SIZE) && + (privSz != DILITHIUM_LEVEL5_KEY_SIZE)) { + ret = BAD_FUNC_ARG; } - if ((key->level != 2) && (key->level != 3) && (key->level != 5)) { - return BAD_FUNC_ARG; + if (ret == 0) { + /* Copy the private key data in or copy pointer. */ + #ifndef WOLFSSL_DILITHIUM_ASSIGN_KEY + XMEMCPY(key->k, priv, privSz); + #else + key->k = priv; + #endif } - if ((key->level == 2) && (*outLen < DILITHIUM_LEVEL2_PRV_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL2_PRV_KEY_SIZE; - return BUFFER_E; + /* Allocate and create cached values. */ +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + if (ret == 0) { + /* Allocate matrix a if required. */ + if (key->a == NULL) { + key->a = (sword32*)XMALLOC(params->aSz, NULL, + DYNAMIC_TYPE_DILITHIUM); + if (key->a == NULL) { + ret = MEMORY_E; + } + } } - else if ((key->level == 3) && (*outLen < DILITHIUM_LEVEL3_PRV_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL3_PRV_KEY_SIZE; - return BUFFER_E; + if (ret == 0) { + /* Compute matrix a from private key data. */ + ret = dilithium_expand_a(&key->shake, key->k, params->k, params->l, + key->a); + if (ret == 0) { + key->aSet = 1; + } } - else if ((key->level == 5) && (*outLen < DILITHIUM_LEVEL5_PRV_KEY_SIZE)) { - *outLen = DILITHIUM_LEVEL5_PRV_KEY_SIZE; - return BUFFER_E; +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + if ((ret == 0) && (key->s1 == NULL)) { + /* Allocate L vector s1, K vector s2 and K vector t0 if required. */ + key->s1 = (sword32*)XMALLOC(params->s1Sz + params->s2Sz + params->s2Sz, + NULL, DYNAMIC_TYPE_DILITHIUM); + if (key->s1 == NULL) { + ret = MEMORY_E; + } } + if (ret == 0) { + /* Set pointers into allocated memory. */ + key->s2 = key->s1 + params->s1Sz / sizeof(*key->s1); + key->t0 = key->s2 + params->s2Sz / sizeof(*key->s2); - - if (key->level == 2) { - *outLen = DILITHIUM_LEVEL2_PRV_KEY_SIZE; - XMEMCPY(out, key->k, DILITHIUM_LEVEL2_KEY_SIZE); - XMEMCPY(out + DILITHIUM_LEVEL2_KEY_SIZE, key->p, - DILITHIUM_LEVEL2_PUB_KEY_SIZE); - } - else if (key->level == 3) { - *outLen = DILITHIUM_LEVEL3_PRV_KEY_SIZE; - XMEMCPY(out, key->k, DILITHIUM_LEVEL3_KEY_SIZE); - XMEMCPY(out + DILITHIUM_LEVEL3_KEY_SIZE, key->p, - DILITHIUM_LEVEL3_PUB_KEY_SIZE); + /* Compute vectors from private key. */ + dilithium_make_priv_vecs(key, key->s1, key->s2, key->t0); } - else if (key->level == 5) { - *outLen = DILITHIUM_LEVEL5_PRV_KEY_SIZE; - XMEMCPY(out, key->k, DILITHIUM_LEVEL5_KEY_SIZE); - XMEMCPY(out + DILITHIUM_LEVEL5_KEY_SIZE, key->p, - DILITHIUM_LEVEL5_PUB_KEY_SIZE); +#endif + if (ret == 0) { + /* Private key is set. */ + key->prvKeySet = 1; } - return 0; + return ret; } -/* Export the dilithium private and public key. +/* Import a dilithium private key from a byte array. * - * key [in] Dilithium private/public key. - * priv [in] Array to hold private key. - * privSz [in/out] On in, the number of bytes in private key array. - * pub [in] Array to hold public key. - * pubSz [in/out] On in, the number of bytes in public key array. - * On out, the number bytes put into array. - * returns BAD_FUNC_ARG when a parameter is NULL, - * BUFFER_E when privSz is less than DILITHIUM_LEVEL2_PRV_KEY_SIZE or pubSz is less - * than DILITHIUM_LEVEL2_PUB_KEY_SIZE, - * 0 otherwise. + * @param [in] priv Array holding private key. + * @param [in] privSz Number of bytes of data in array. + * @param [in, out] key Dilithium private key. + * @return 0 otherwise. + * @return BAD_FUNC_ARG when a parameter is NULL or privSz is less than size + * required for level, */ -int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, - byte* pub, word32 *pubSz) +int wc_dilithium_import_private(const byte* priv, word32 privSz, + dilithium_key* key) { int ret = 0; - /* export private part */ - ret = wc_dilithium_export_private(key, priv, privSz); + /* Validate parameters. */ + if ((priv == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (key->level != 2) && (key->level != 3) && + (key->level != 5)) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { - /* export public part */ - ret = wc_dilithium_export_public(key, pub, pubSz); + /* Set the private key data. */ + ret = dilithium_set_priv_key(priv, privSz, key); } return ret; } -/* Check the public key of the dilithium key matches the private key. +#if defined(WOLFSSL_DILITHIUM_PUBLIC_KEY) +/* Import a dilithium private and public keys from byte array(s). * - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * PUBLIC_KEY_E when the public key is not set or doesn't match, - * other -ve value on hash failure, - * 0 otherwise. + * @param [in] priv Array holding private key or private+public keys + * @param [in] privSz Number of bytes of data in private key array. + * @param [in] pub Array holding public key (or NULL). + * @param [in] pubSz Number of bytes of data in public key array (or 0). + * @param [in] key Dilithium private/public key. + * @return 0 on success. + * @return BAD_FUNC_ARG when a required parameter is NULL an invalid + * combination of keys/lengths is supplied. */ -int wc_dilithium_check_key(dilithium_key* key) +int wc_dilithium_import_key(const byte* priv, word32 privSz, + const byte* pub, word32 pubSz, dilithium_key* key) { - if (key == NULL) { - return BAD_FUNC_ARG; - } - int ret = 0; - /* The public key is also decoded and stored within the private key buffer - * behind the private key. Hence, we can compare both stored public keys. */ - if (key->level == 2) { - ret = XMEMCMP(key->p, key->k + DILITHIUM_LEVEL2_KEY_SIZE, - DILITHIUM_LEVEL2_PUB_KEY_SIZE); + /* Validate parameters. */ + if ((priv == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; } - else if (key->level == 3) { - ret = XMEMCMP(key->p, key->k + DILITHIUM_LEVEL3_KEY_SIZE, - DILITHIUM_LEVEL3_PUB_KEY_SIZE); + if ((pub == NULL) && (pubSz != 0)) { + ret = BAD_FUNC_ARG; } - else if (key->level == 5) { - ret = XMEMCMP(key->p, key->k + DILITHIUM_LEVEL5_KEY_SIZE, - DILITHIUM_LEVEL5_PUB_KEY_SIZE); + if ((ret == 0) && (key->level != 2) && (key->level != 3) && + (key->level != 5)) { + ret = BAD_FUNC_ARG; } - if (ret != 0) { - ret = PUBLIC_KEY_E; + if ((ret == 0) && (pub != NULL)) { + /* Import public key. */ + ret = wc_dilithium_import_public(pub, pubSz, key); + } + if (ret == 0) { + ret = dilithium_set_priv_key(priv, privSz, key); } return ret; - } +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ -/* Returns the size of a dilithium private key. +/* Export the dilithium private key. * - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * DILITHIUM_LEVEL2_KEY_SIZE otherwise. + * @param [in] key Dilithium private key. + * @param [out] out Array to hold private key. + * @param [in, out] outLen On in, the number of bytes in array. + * On out, the number bytes put into array. + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BUFFER_E when outLen is less than DILITHIUM_LEVEL2_KEY_SIZE. */ -int wc_dilithium_size(dilithium_key* key) +int wc_dilithium_export_private(dilithium_key* key, byte* out, + word32* outLen) { - if (key == NULL) { - return BAD_FUNC_ARG; - } + int ret = 0; + word32 inLen; - if (key->level == 2) { - return DILITHIUM_LEVEL2_KEY_SIZE; - } - else if (key->level == 3) { - return DILITHIUM_LEVEL3_KEY_SIZE; - } - else if (key->level == 5) { - return DILITHIUM_LEVEL5_KEY_SIZE; + /* Validate parameters. */ + if ((key == NULL) || (out == NULL) || (outLen == NULL)) { + ret = BAD_FUNC_ARG; } - return BAD_FUNC_ARG; -} - -/* Returns the size of a dilithium private plus public key. - * - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * DILITHIUM_LEVEL2_PRV_KEY_SIZE otherwise. - */ -int wc_dilithium_priv_size(dilithium_key* key) -{ - if (key == NULL) { - return BAD_FUNC_ARG; + /* Check private key available. */ + if ((ret == 0) && (!key->prvKeySet)) { + ret = BAD_FUNC_ARG; } - if (key->level == 2) { - return DILITHIUM_LEVEL2_PRV_KEY_SIZE; + if (ret == 0) { + inLen = *outLen; + /* check and set up out length */ + if (key->level == 2) { + *outLen = DILITHIUM_LEVEL2_KEY_SIZE; + } + else if (key->level == 3) { + *outLen = DILITHIUM_LEVEL3_KEY_SIZE; + } + else if (key->level == 5) { + *outLen = DILITHIUM_LEVEL5_KEY_SIZE; + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } } - else if (key->level == 3) { - return DILITHIUM_LEVEL3_PRV_KEY_SIZE; + + /* Check array length. */ + if ((ret == 0) && (inLen < *outLen)) { + ret = BUFFER_E; } - else if (key->level == 5) { - return DILITHIUM_LEVEL5_PRV_KEY_SIZE; + + if (ret == 0) { + /* Copy private key out key. */ + XMEMCPY(out, key->k, *outLen); } - return BAD_FUNC_ARG; + return ret; } -/* Returns the size of a dilithium public key. +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY +/* Export the dilithium private and public key. * - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * DILITHIUM_LEVEL2_PUB_KEY_SIZE otherwise. + * @param [in] key Dilithium private/public key. + * @param [out] priv Array to hold private key. + * @param [in, out] privSz On in, the number of bytes in private key array. + * On out, the number bytes put into private key. + * @param [out] pub Array to hold public key. + * @param [in, out] pubSz On in, the number of bytes in public key array. + * On out, the number bytes put into public key. + * @return 0 on success. + * @return BAD_FUNC_ARG when a key, priv, privSz, pub or pubSz is NULL. + * @return BUFFER_E when privSz or pubSz is less than required size. */ -int wc_dilithium_pub_size(dilithium_key* key) +int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, + byte* pub, word32 *pubSz) { - if (key == NULL) { - return BAD_FUNC_ARG; - } + int ret; - if (key->level == 2) { - return DILITHIUM_LEVEL2_PUB_KEY_SIZE; - } - else if (key->level == 3) { - return DILITHIUM_LEVEL3_PUB_KEY_SIZE; - } - else if (key->level == 5) { - return DILITHIUM_LEVEL5_PUB_KEY_SIZE; + /* Export private key only. */ + ret = wc_dilithium_export_private(key, priv, privSz); + if (ret == 0) { + /* Export public key. */ + ret = wc_dilithium_export_public(key, pub, pubSz); } - return BAD_FUNC_ARG; + return ret; } +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ -/* Returns the size of a dilithium signature. - * - * key [in] Dilithium private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * DILITHIUM_LEVEL2_SIG_SIZE otherwise. - */ -int wc_dilithium_sig_size(dilithium_key* key) -{ - if (key == NULL) { - return BAD_FUNC_ARG; - } +#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ - if (key->level == 2) { - return DILITHIUM_LEVEL2_SIG_SIZE; - } - else if (key->level == 3) { - return DILITHIUM_LEVEL3_SIG_SIZE; - } - else if (key->level == 5) { - return DILITHIUM_LEVEL5_SIG_SIZE; - } +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 - return BAD_FUNC_ARG; -} +#if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) +/* Decode the DER encoded Dilithium key. + * + * @param [in] input Array holding DER encoded data. + * @param [in, out] inOutIdx On in, index into array of start of DER encoding. + * On out, index into array after DER encoding. + * @param [in, out] key Dilithium key to store key. + * @param [in] inSz Total size of data in array. + * @return 0 on success. + * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL or inSz is 0. + * @return BAD_FUNC_ARG when level not set. + * @return Other negative on parse error. + */ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, - dilithium_key* key, word32 inSz) + dilithium_key* key, word32 inSz) { int ret = 0; - byte privKey[DILITHIUM_MAX_PRV_KEY_SIZE]; - byte pubKey[DILITHIUM_MAX_PUB_KEY_SIZE]; - word32 privKeyLen = (word32)sizeof(privKey); - word32 pubKeyLen = (word32)sizeof(pubKey); + const byte* privKey = NULL; + const byte* pubKey = NULL; + word32 privKeyLen = 0; + word32 pubKeyLen = 0; int keytype = 0; - if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) { - return BAD_FUNC_ARG; + /* Validate parameters. */ + if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) { + ret = BAD_FUNC_ARG; } - if (key->level == 2) { - keytype = DILITHIUM_LEVEL2k; - } - else if (key->level == 3) { - keytype = DILITHIUM_LEVEL3k; + if (ret == 0) { + /* Get OID sum for level. */ + if (key->level == 2) { + keytype = DILITHIUM_LEVEL2k; + } + else if (key->level == 3) { + keytype = DILITHIUM_LEVEL3k; + } + else if (key->level == 5) { + keytype = DILITHIUM_LEVEL5k; + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } } - else if (key->level == 5) { - keytype = DILITHIUM_LEVEL5k; + + if (ret == 0) { + /* Decode the asymmetric key and get out private and public key data. */ + ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &privKey, &privKeyLen, + &pubKey, &pubKeyLen, keytype); } - else { - return BAD_FUNC_ARG; + if ((ret == 0) && (pubKey == NULL) && (pubKeyLen == 0)) { + /* Check if the public key is included in the private key. */ + if ((key->level == 2) && + (privKeyLen == DILITHIUM_LEVEL2_PRV_KEY_SIZE)) { + pubKey = privKey + DILITHIUM_LEVEL2_KEY_SIZE; + pubKeyLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; + privKeyLen -= DILITHIUM_LEVEL2_PUB_KEY_SIZE; + } + else if ((key->level == 3) && + (privKeyLen == DILITHIUM_LEVEL3_PRV_KEY_SIZE)) { + pubKey = privKey + DILITHIUM_LEVEL3_KEY_SIZE; + pubKeyLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; + privKeyLen -= DILITHIUM_LEVEL3_PUB_KEY_SIZE; + } + else if ((key->level == 5) && + (privKeyLen == DILITHIUM_LEVEL5_PRV_KEY_SIZE)) { + pubKey = privKey + DILITHIUM_LEVEL5_KEY_SIZE; + pubKeyLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; + privKeyLen -= DILITHIUM_LEVEL5_PUB_KEY_SIZE; + } } - ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen, - pubKey, &pubKeyLen, keytype); if (ret == 0) { - if (pubKeyLen == 0) { - ret = wc_dilithium_import_private_only(input, inSz, key); + /* Check whether public key data was found. */ +#if defined(WOLFSSL_DILITHIUM_PUBLIC_KEY) + if (pubKeyLen == 0) +#endif + { + /* No public key data, only import private key data. */ + ret = wc_dilithium_import_private(privKey, privKeyLen, key); } +#if defined(WOLFSSL_DILITHIUM_PUBLIC_KEY) else { - ret = wc_dilithium_import_private_key(privKey, privKeyLen, - pubKey, pubKeyLen, key); + /* Import private and public key data. */ + ret = wc_dilithium_import_key(privKey, privKeyLen, pubKey, + pubKeyLen, key); } +#endif } + + (void)pubKey; + (void)pubKeyLen; + return ret; } +#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ + +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY + +/* Decode the DER encoded Dilithium public key. + * + * @param [in] input Array holding DER encoded data. + * @param [in, out] inOutIdx On in, index into array of start of DER encoding. + * On out, index into array after DER encoding. + * @param [in, out] key Dilithium key to store key. + * @param [in] inSz Total size of data in array. + * @return 0 on success. + * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL or inSz is 0. + * @return BAD_FUNC_ARG when level not set. + * @return Other negative on parse error. + */ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, - dilithium_key* key, word32 inSz) + dilithium_key* key, word32 inSz) { int ret = 0; - byte pubKey[DILITHIUM_MAX_PUB_KEY_SIZE]; - word32 pubKeyLen = (word32)sizeof(pubKey); + const byte* pubKey; + word32 pubKeyLen = 0; int keytype = 0; - if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) { - return BAD_FUNC_ARG; - } - - ret = wc_dilithium_import_public(input, inSz, key); - if (ret == 0) { - return 0; - } - - if (key->level == 2) { - keytype = DILITHIUM_LEVEL2k; - } - else if (key->level == 3) { - keytype = DILITHIUM_LEVEL3k; - } - else if (key->level == 5) { - keytype = DILITHIUM_LEVEL5k; - } - else { - return BAD_FUNC_ARG; + /* Validate parameters. */ + if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) { + ret = BAD_FUNC_ARG; } - ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, pubKey, &pubKeyLen, - keytype); if (ret == 0) { - ret = wc_dilithium_import_public(pubKey, pubKeyLen, key); + /* Try to import the key directly. */ + ret = wc_dilithium_import_public(input, inSz, key); + if (ret != 0) { + /* Start again. */ + ret = 0; + + /* Get OID sum for level. */ + if (key->level == 2) { + keytype = DILITHIUM_LEVEL2k; + } + else if (key->level == 3) { + keytype = DILITHIUM_LEVEL3k; + } + else if (key->level == 5) { + keytype = DILITHIUM_LEVEL5k; + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Decode the asymmetric key and get out public key data. */ + ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKey, + &pubKeyLen, keytype); + } + if (ret == 0) { + /* Import public key data. */ + ret = wc_dilithium_import_public(pubKey, pubKeyLen, key); + } + } } return ret; } #ifdef WC_ENABLE_ASYM_KEY_EXPORT -/* Encode the public part of an Dilithium key in DER. +/* Encode the public part of a Dilithium key in DER. * * Pass NULL for output to get the size of the encoding. * - * @param [in] key Dilithium key object. - * @param [out] output Buffer to put encoded data in. - * @param [in] outLen Size of buffer in bytes. - * @param [in] withAlg Whether to use SubjectPublicKeyInfo format. + * @param [in] key Dilithium key object. + * @param [out] output Buffer to put encoded data in. + * @param [in] len Size of buffer in bytes. + * @param [in] withAlg Whether to use SubjectPublicKeyInfo format. * @return Size of encoded data in bytes on success. * @return BAD_FUNC_ARG when key is NULL. * @return MEMORY_E when dynamic memory allocation failed. */ -int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 inLen, - int withAlg) +int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, + int withAlg) { - int ret; - byte pubKey[DILITHIUM_MAX_PUB_KEY_SIZE]; - word32 pubKeyLen = (word32)sizeof(pubKey); - int keytype = 0; - - if (key == NULL || output == NULL) { - return BAD_FUNC_ARG; - } + int ret = 0; + int keytype = 0; + int pubKeyLen = 0; - if (key->level == 2) { - keytype = DILITHIUM_LEVEL2k; - } - else if (key->level == 3) { - keytype = DILITHIUM_LEVEL3k; + /* Validate parameters. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; } - else if (key->level == 5) { - keytype = DILITHIUM_LEVEL5k; + /* Check we have a public key to encode. */ + if ((ret == 0) && (!key->pubKeySet)) { + ret = BAD_FUNC_ARG; } - else { - return BAD_FUNC_ARG; + + if (ret == 0) { + /* Get OID and length for level. */ + if (key->level == 2) { + keytype = DILITHIUM_LEVEL2k; + pubKeyLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; + } + else if (key->level == 3) { + keytype = DILITHIUM_LEVEL3k; + pubKeyLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; + } + else if (key->level == 5) { + keytype = DILITHIUM_LEVEL5k; + pubKeyLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; + } + else { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } } - ret = wc_dilithium_export_public(key, pubKey, &pubKeyLen); if (ret == 0) { - ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen, keytype, - withAlg); + ret = SetAsymKeyDerPublic(key->p, pubKeyLen, output, len, keytype, + withAlg); } return ret; } -#endif +#endif /* WC_ENABLE_ASYM_KEY_EXPORT */ + +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ -int wc_Dilithium_KeyToDer(dilithium_key* key, byte* output, word32 inLen) +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY + +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY +/* Encode the private and public data of a Dilithium key in DER. + * + * Pass NULL for output to get the size of the encoding. + * + * @param [in] key Dilithium key object. + * @param [out] output Buffer to put encoded data in. + * @param [in] len Size of buffer in bytes. + * @return Size of encoded data in bytes on success. + * @return BAD_FUNC_ARG when key is NULL. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_Dilithium_KeyToDer(dilithium_key* key, byte* output, word32 len) { - if (key == NULL) { - return BAD_FUNC_ARG; - } + int ret = BAD_FUNC_ARG; - if (key->level == 2) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, key->p, - DILITHIUM_LEVEL2_KEY_SIZE, output, inLen, - DILITHIUM_LEVEL2k); - } - else if (key->level == 3) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, key->p, - DILITHIUM_LEVEL3_KEY_SIZE, output, inLen, - DILITHIUM_LEVEL3k); - } - else if (key->level == 5) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, key->p, - DILITHIUM_LEVEL5_KEY_SIZE, output, inLen, - DILITHIUM_LEVEL5k); + /* Validate parameters and check public and private key set. */ + if ((key != NULL) && key->prvKeySet && key->pubKeySet) { + /* Create DER for level. */ + if (key->level == 2) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, key->p, + DILITHIUM_LEVEL2_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL2k); + } + else if (key->level == 3) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, key->p, + DILITHIUM_LEVEL3_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL3k); + } + else if (key->level == 5) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, key->p, + DILITHIUM_LEVEL5_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL5k); + } } - return BAD_FUNC_ARG; + return ret; } +#endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ -int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, word32 inLen) +/* Encode the private data of a Dilithium key in DER. + * + * Pass NULL for output to get the size of the encoding. + * + * @param [in] key Dilithium key object. + * @param [out] output Buffer to put encoded data in. + * @param [in] len Size of buffer in bytes. + * @return Size of encoded data in bytes on success. + * @return BAD_FUNC_ARG when key is NULL. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, word32 len) { - if (key == NULL) { - return BAD_FUNC_ARG; - } + int ret = BAD_FUNC_ARG; - if (key->level == 2) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, NULL, 0, output, - inLen, DILITHIUM_LEVEL2k); - } - else if (key->level == 3) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, NULL, 0, output, - inLen, DILITHIUM_LEVEL3k); - } - else if (key->level == 5) { - return SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, NULL, 0, output, - inLen, DILITHIUM_LEVEL5k); + /* Validate parameters and check private key set. */ + if ((key != NULL) && key->prvKeySet) { + /* Create DER for level. */ + if (key->level == 2) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, NULL, 0, + output, len, DILITHIUM_LEVEL2k); + } + else if (key->level == 3) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, NULL, 0, + output, len, DILITHIUM_LEVEL3k); + } + else if (key->level == 5) { + ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, NULL, 0, + output, len, DILITHIUM_LEVEL5k); + } } - return BAD_FUNC_ARG; + return ret; } -#endif /* HAVE_PQC && HAVE_DILITHIUM */ + +#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ + +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ + +#endif /* HAVE_DILITHIUM */ diff --git a/src/wolfcrypt/src/dsa.c b/src/wolfcrypt/src/dsa.c index 08f70db..c1606b3 100644 --- a/src/wolfcrypt/src/dsa.c +++ b/src/wolfcrypt/src/dsa.c @@ -930,33 +930,39 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, #ifdef WOLFSSL_SMALL_STACK if (k) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_forcezero(k); XFREE(k, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (kInv) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_forcezero(kInv); XFREE(kInv, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (r) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_clear(r); XFREE(r, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (s) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_clear(s); XFREE(s, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (H) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_clear(H); XFREE(H, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } #ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME if (b) { - if ((ret != MP_INIT_E) && (ret != MEMORY_E)) + if ((ret != WC_NO_ERR_TRACE(MP_INIT_E)) && + (ret != WC_NO_ERR_TRACE(MEMORY_E))) mp_forcezero(b); XFREE(b, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } @@ -966,7 +972,7 @@ int wc_DsaSign_ex(const byte* digest, word32 digestSz, byte* out, DsaKey* key, XFREE(buffer, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } #else /* !WOLFSSL_SMALL_STACK */ - if (ret != MP_INIT_E) { + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) { ForceZero(buffer, halfSz); mp_forcezero(kInv); mp_forcezero(k); @@ -1106,37 +1112,37 @@ int wc_DsaVerify_ex(const byte* digest, word32 digestSz, const byte* sig, #ifdef WOLFSSL_SMALL_STACK if (s) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(s); XFREE(s, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (r) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(r); XFREE(r, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (u1) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(u1); XFREE(u1, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (u2) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(u2); XFREE(u2, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (w) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(w); XFREE(w, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (v) { - if (ret != MP_INIT_E) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(v); XFREE(v, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } #else - if (ret != MP_INIT_E) { + if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) { mp_clear(s); mp_clear(r); mp_clear(u1); diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index 78101ed..ee1e7b7 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -98,6 +98,12 @@ Possible ECC enable options: * Use this when CPU state can be closely observed by * attacker. * default: off + * WOLFSSL_ECC_BLIND_K + * Blind the private key k by using a random mask. + * The private key is never stored unprotected but an + * unmasked copy is computed and stored each time it is + * needed. + * default: off */ /* @@ -180,6 +186,15 @@ ECC Curve Sizes: #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_ecc_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000005 }; + int wolfCrypt_FIPS_ECC_sanity(void) + { + return 0; + } +#endif + #if defined(FREESCALE_LTC_ECC) #include #endif @@ -288,6 +303,53 @@ ECC Curve Sizes: #endif +#ifdef WOLFSSL_ECC_BLIND_K +mp_int* ecc_get_k(ecc_key* key) +{ + mp_xor_ct(key->k, key->kb, key->dp->size, key->ku); + return key->ku; +} +void ecc_blind_k(ecc_key* key, mp_int* b) +{ + mp_xor_ct(key->k, b, key->dp->size, key->k); + mp_xor_ct(key->kb, b, key->dp->size, key->kb); +} +int ecc_blind_k_rng(ecc_key* key, WC_RNG* rng) +{ + int ret = 0; + WC_RNG local_rng; + +#ifdef ECC_TIMING_RESISTANT + if (rng == NULL) { + rng = key->rng; + } +#endif + if (rng == NULL) { + ret = wc_InitRng(&local_rng); + if (ret == 0) { + rng = &local_rng; + } + } + if (ret == 0) { + ret = mp_rand(key->kb, (key->dp->size + sizeof(mp_digit) - 1) / + sizeof(mp_digit), rng); + if (ret == 0) { + mp_xor_ct(key->k, key->kb, key->dp->size, key->k); + } + } + + if (rng == &local_rng) { + wc_FreeRng(&local_rng); + } + return ret; +} + +mp_int* wc_ecc_key_get_priv(ecc_key* key) +{ + return ecc_get_k(key); +} +#endif + /* forward declarations */ static int wc_ecc_new_point_ex(ecc_point** point, void* heap); static void wc_ecc_del_point_ex(ecc_point* p, void* heap); @@ -1486,7 +1548,11 @@ static int xil_mpi_import(mp_int *mpi, #ifdef ECC_CACHE_CURVE /* cache (mp_int) of the curve parameters */ + #ifdef WOLFSSL_NO_MALLOC + static ecc_curve_spec ecc_curve_spec_cache[ECC_SET_COUNT]; + #else static ecc_curve_spec* ecc_curve_spec_cache[ECC_SET_COUNT]; + #endif #ifndef SINGLE_THREADED static wolfSSL_Mutex ecc_curve_cache_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(ecc_curve_cache_mutex); #endif @@ -1666,6 +1732,9 @@ static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, } #endif +#ifdef WOLFSSL_NO_MALLOC + curve = &ecc_curve_spec_cache[x]; +#else /* make sure cache has been allocated */ if (ecc_curve_spec_cache[x] == NULL #ifdef WOLFSSL_CUSTOM_CURVES @@ -1692,6 +1761,8 @@ static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, else { curve = ecc_curve_spec_cache[x]; } +#endif /* WOLFSSL_NO_MALLOC */ + /* return new or cached curve */ *pCurve = curve; #else @@ -1771,11 +1842,16 @@ void wc_ecc_curve_cache_free(void) /* free all ECC curve caches */ for (x = 0; x < (int)ECC_SET_COUNT; x++) { + #ifdef WOLFSSL_NO_MALLOC + wc_ecc_curve_cache_free_spec(&ecc_curve_spec_cache[x]); + XMEMSET(&ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec_cache[x])); + #else if (ecc_curve_spec_cache[x]) { wc_ecc_curve_cache_free_spec(ecc_curve_spec_cache[x]); XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC); ecc_curve_spec_cache[x] = NULL; } + #endif /* WOLFSSL_NO_MALLOC */ } #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) && \ @@ -2617,6 +2693,7 @@ int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, */ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) { + int err = MP_OKAY; #if !defined(WOLFSSL_SP_MATH) DECL_MP_INT_SIZE_DYN(t1, mp_bitsused(modulus), MAX_ECC_BITS_USE); DECL_MP_INT_SIZE_DYN(t2, mp_bitsused(modulus), MAX_ECC_BITS_USE); @@ -2626,7 +2703,6 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) DECL_MP_INT_SIZE_DYN(rz, mp_bitsused(modulus), MAX_ECC_BITS_USE); #endif mp_int *x, *y, *z; - int err; (void)ct; @@ -2844,7 +2920,7 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) err = ECC_BAD_ARG_E; #endif - WOLFSSL_LEAVE("ecc_map_ex (SP Math)"); + WOLFSSL_LEAVE("ecc_map_ex (SP Math)", err); return err; #endif /* WOLFSSL_SP_MATH */ } @@ -3982,6 +4058,12 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, int wc_ecc_mulmod(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map) { + if ((k != NULL) && (R != NULL) && (mp_iszero(k))) { + mp_zero(R->x); + mp_zero(R->y); + mp_set(R->z, 1); + return MP_OKAY; + } return wc_ecc_mulmod_ex(k, G, R, a, modulus, map, NULL); } @@ -4279,8 +4361,11 @@ static int wc_ecc_cmp_param(const char* curveParam, if (param == NULL || curveParam == NULL) return BAD_FUNC_ARG; - if (encType == WC_TYPE_HEX_STR) - return XSTRNCMP(curveParam, (char*) param, paramSz); + if (encType == WC_TYPE_HEX_STR) { + if ((word32)XSTRLEN(curveParam) != paramSz) + return -1; + return (XSTRNCMP(curveParam, (char*) param, paramSz) == 0) ? 0 : -1; + } #ifdef WOLFSSL_SMALL_STACK a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC); @@ -4596,7 +4681,7 @@ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, #endif { err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen); - if (err != CRYPTOCB_UNAVAILABLE) + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return err; /* fall-through when unavailable */ } @@ -4667,7 +4752,7 @@ int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, byte* out, word32* outlen) { int err = MP_OKAY; - mp_int* k = private_key->k; + mp_int* k = ecc_get_k(private_key); #ifdef HAVE_ECC_CDH #ifdef WOLFSSL_SMALL_STACK mp_int *k_lcl = NULL; @@ -4697,7 +4782,7 @@ int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, goto errout; } /* multiply cofactor times private key "k" */ - err = mp_mul_d(private_key->k, cofactor, k); + err = mp_mul_d(ecc_get_k(private_key), cofactor, k); if (err != MP_OKAY) goto errout; } @@ -4938,7 +5023,8 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, word32 keySz = private_key->dp->size; /* sync public key x/y */ - err = wc_mp_to_bigint_sz(private_key->k, &private_key->k->raw, keySz); + err = wc_mp_to_bigint_sz(ecc_get_k(private_key), + &ecc_get_k(private_key)->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz); if (err == MP_OKAY) @@ -4952,7 +5038,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, NitroxEccGetSize(private_key)*2); if (err == MP_OKAY) err = NitroxEcdh(private_key, - &private_key->k->raw, &point->x->raw, &point->y->raw, + &ecc_get_k(private_key)->raw, &point->x->raw, &point->y->raw, private_key->e->raw.buf, &private_key->e->raw.len, &curve->prime->raw); #else @@ -4960,7 +5046,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF); if (err == MP_OKAY) err = IntelQaEcdh(&private_key->asyncDev, - &private_key->k->raw, &point->x->raw, &point->y->raw, + &ecc_get_k(private_key)->raw, &point->x->raw, &point->y->raw, out, outlen, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, private_key->dp->cofactor); @@ -4983,7 +5069,7 @@ static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen); } - if (err == WC_PENDING_E) { + if (err == WC_NO_ERR_TRACE(WC_PENDING_E)) { private_key->state++; } @@ -5076,7 +5162,7 @@ int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, RESTORE_VECTOR_REGISTERS(); /* if async pending then return and skip done cleanup below */ - if (err == WC_PENDING_E) { + if (err == WC_NO_ERR_TRACE(WC_PENDING_E)) { return err; } @@ -5098,11 +5184,33 @@ int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, err = wc_ecc_init_ex(&public_key, private_key->heap, INVALID_DEVID); if (err == MP_OKAY) { + #if FIPS_VERSION3_GE(6,0,0) + /* Since we are allowing a pass-through of ecc_make_key_ex_fips when + * both keysize == 0 and curve_id == 0 ensure we select an appropriate + * keysize here when relying on default selection */ + if (private_key->dp->size < WC_ECC_FIPS_GEN_MIN) { + if (private_key->dp->size == 0 && + (private_key->dp->id == ECC_SECP256R1 || + private_key->dp->id == ECC_SECP224R1 || + private_key->dp->id == ECC_SECP384R1 || + private_key->dp->id == ECC_SECP521R1)) { + WOLFSSL_MSG("ECC dp->size zero but dp->id sufficient for FIPS"); + err = 0; + } else { + WOLFSSL_MSG("ECC curve too small for FIPS mode"); + err = ECC_CURVE_OID_E; + } + } + if (err == 0) { /* FIPS specific check */ + #endif err = wc_ecc_set_curve(&public_key, private_key->dp->size, private_key->dp->id); if (err == MP_OKAY) { err = mp_copy(point->x, public_key.pubkey.x); } + #if FIPS_VERSION3_GE(6,0,0) + } /* end FIPS specific check */ + #endif if (err == MP_OKAY) { err = mp_copy(point->y, public_key.pubkey.y); } @@ -5323,9 +5431,9 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, key->type = ECC_PRIVATEKEY_ONLY; } - if ((err == MP_OKAY) && (mp_iszero(key->k) || mp_isneg(key->k) || - (mp_cmp(key->k, curve->order) != MP_LT))) - { + if ((err == MP_OKAY) && (mp_iszero(ecc_get_k(key)) || + mp_isneg(ecc_get_k(key)) || + (mp_cmp(ecc_get_k(key), curve->order) != MP_LT))) { err = ECC_PRIV_KEY_E; } @@ -5347,10 +5455,10 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, if (err == MP_OKAY && key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { word32 keySz = key->dp->size; /* sync private key to raw */ - err = wc_mp_to_bigint_sz(key->k, &key->k->raw, keySz); + err = wc_mp_to_bigint_sz(ecc_get_k(key), &ecc_get_k(key)->raw, keySz); if (err == MP_OKAY) { err = IntelQaEccPointMul(&key->asyncDev, - &key->k->raw, pub->x, pub->y, pub->z, + &ecc_get_k(key)->raw, pub->x, pub->y, pub->z, &curve->Gx->raw, &curve->Gy->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, key->dp->cofactor); @@ -5366,25 +5474,25 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, else #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { - err = sp_ecc_mulmod_base_256(key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_256(ecc_get_k(key), pub, 1, key->heap); } else #endif /* WOLFSSL_SP_NO_256 */ #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SP_SM2) if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SM2P256V1) { - err = sp_ecc_mulmod_base_sm2_256(key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_sm2_256(ecc_get_k(key), pub, 1, key->heap); } else #endif #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { - err = sp_ecc_mulmod_base_384(key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_384(ecc_get_k(key), pub, 1, key->heap); } else #endif #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { - err = sp_ecc_mulmod_base_521(key->k, pub, 1, key->heap); + err = sp_ecc_mulmod_base_521(ecc_get_k(key), pub, 1, key->heap); } else #endif @@ -5416,8 +5524,8 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, /* make the public key */ if (err == MP_OKAY) { /* Map in a separate call as this should be constant time */ - err = wc_ecc_mulmod_ex2(key->k, base, pub, curve->Af, curve->prime, - curve->order, rng, 0, key->heap); + err = wc_ecc_mulmod_ex2(ecc_get_k(key), base, pub, curve->Af, + curve->prime, curve->order, rng, 0, key->heap); if (err == MP_MEM) { err = MEMORY_E; } @@ -5539,11 +5647,30 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, /* make sure required variables are reset */ wc_ecc_reset(key); + #if FIPS_VERSION3_GE(6,0,0) + /* Since we are allowing a pass-through of ecc_make_key_ex_fips when + * both keysize == 0 and curve_id == 0 ensure we select an appropriate + * keysize here when relying on default selection */ + if (keysize < WC_ECC_FIPS_GEN_MIN) { + if (keysize == 0 && (curve_id == ECC_SECP256R1 || + curve_id == ECC_SECP224R1 || curve_id == ECC_SECP384R1 || + curve_id == ECC_SECP521R1)) { + WOLFSSL_MSG("ECC keysize zero but curve_id sufficient for FIPS"); + err = 0; + } else { + WOLFSSL_MSG("ECC curve too small for FIPS mode"); + err = ECC_CURVE_OID_E; + } + } + if (err == 0) { /* FIPS specific check */ + #endif err = wc_ecc_set_curve(key, keysize, curve_id); if (err != 0) { return err; } - + #if FIPS_VERSION3_GE(6,0,0) + } /* end FIPS specific check */ + #endif key->flags = (byte)flags; #ifdef WOLF_CRYPTO_CB @@ -5552,7 +5679,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #endif { err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id); - if (err != CRYPTOCB_UNAVAILABLE) + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return err; /* fall-through when unavailable */ } @@ -5653,6 +5780,11 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, if (err == SA_SILIB_RET_OK) { err = mp_read_unsigned_bin(key->k, ucompressed_key, raw_size); +#ifdef WOLFSSL_ECC_BLIND_K + if (err == MP_OKAY) { + err = ecc_blind_k_rng(key, rng); + } +#endif } #elif defined(WOLFSSL_SILABS_SE_ACCEL) @@ -5704,7 +5836,12 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, err = xil_mpi_import(key->pubkey.y, key->keyRaw + key->dp->size, key->dp->size, key->heap); if (err == 0) - err = xil_mpi_import(key->k, key->privKey, key->dp->size, key->heap); + err = xil_mpi_import(key->k, key->privKey, key->dp->size, + key->heap); +#ifdef WOLFSSL_ECC_BLIND_K + if (err == 0) + err = ecc_blind_k_rng(key, rng); +#endif if (err == 0) err = mp_set(key->pubkey.z, 1); if (err) { @@ -5886,6 +6023,11 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, err = wc_mp_to_bigint(key->pubkey.z, &key->pubkey.z->raw); #endif +#ifdef WOLFSSL_ECC_BLIND_K + if (err == MP_OKAY) + err = ecc_blind_k_rng(key, rng); +#endif + #endif /* HAVE_ECC_MAKE_PUB */ return err; @@ -6041,20 +6183,11 @@ WOLFSSL_ABI int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) { int ret = 0; -#if defined(HAVE_PKCS11) - int isPkcs11 = 0; -#endif if (key == NULL) { return BAD_FUNC_ARG; } -#if defined(HAVE_PKCS11) - if (key->isPkcs11) { - isPkcs11 = 1; - } -#endif - #ifdef ECC_DUMP_OID wc_ecc_dump_oids(); #endif @@ -6082,13 +6215,27 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) alt_fp_init(key->pubkey.z); key->k = (mp_int*)key->ka; alt_fp_init(key->k); +#ifdef WOLFSSL_ECC_BLIND_K + key->kb = (mp_int*)key->kba; + key->ku = (mp_int*)key->kia; + alt_fp_init(key->kb); + alt_fp_init(key->ku); +#endif #else ret = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, - NULL, NULL); +#ifndef WOLFSSL_ECC_BLIND_K + NULL, NULL +#else + key->kb, key->ku +#endif + ); if (ret != MP_OKAY) { return MEMORY_E; } #endif /* ALT_ECC_SIZE */ +#ifdef WOLFSSL_ECC_BLIND_K + mp_forcezero(key->kb); +#endif #endif /* WOLFSSL_ATECC508A */ #if (defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \ defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ @@ -6108,16 +6255,17 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) - #if defined(HAVE_PKCS11) - if (!isPkcs11) + #ifdef WOLF_CRYPTO_CB + /* prefer crypto callback */ + if (key->devId != INVALID_DEVID) #endif - { - /* handle as async */ - ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, - key->heap, devId); - } -#elif defined(HAVE_PKCS11) - (void)isPkcs11; + { + /* handle as async */ + ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, + key->heap, devId); + } + if (ret != 0) + return ret; #endif #if defined(WOLFSSL_DSP) @@ -6131,6 +6279,10 @@ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) #ifdef WOLFSSL_CHECK_MEM_ZERO mp_memzero_add("ECC k", key->k); +#ifdef WOLFSSL_ECC_BLIND_K + mp_memzero_add("ECC kb", key->kb); + mp_memzero_add("ECC ku", key->ku); +#endif #endif #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) @@ -6169,12 +6321,6 @@ int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap, ret = BAD_FUNC_ARG; if (ret == 0 && (len < 0 || len > ECC_MAX_ID_LEN)) ret = BUFFER_E; - -#if defined(HAVE_PKCS11) - XMEMSET(key, 0, sizeof(ecc_key)); - key->isPkcs11 = 1; -#endif - if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { @@ -6204,12 +6350,6 @@ int wc_ecc_init_label(ecc_key* key, const char* label, void* heap, int devId) if (labelLen == 0 || labelLen > ECC_MAX_LABEL_LEN) ret = BUFFER_E; } - -#if defined(HAVE_PKCS11) - XMEMSET(key, 0, sizeof(ecc_key)); - key->isPkcs11 = 1; -#endif - if (ret == 0) ret = wc_ecc_init_ex(key, heap, devId); if (ret == 0) { @@ -6551,7 +6691,7 @@ static int wc_ecc_sign_hash_async(const byte* in, word32 inlen, byte* out, } /* if async pending then return and skip done cleanup below */ - if (err == WC_PENDING_E) { + if (err == WC_NO_ERR_TRACE(WC_PENDING_E)) { key->state++; return err; } @@ -6593,7 +6733,7 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, #endif { err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key); - if (err != CRYPTOCB_UNAVAILABLE) + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return err; /* fall-through when unavailable */ } @@ -6703,7 +6843,7 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) /* currently limiting to SHA256 for auto create */ if (mp_init(key->sign_k) != MP_OKAY || wc_ecc_gen_deterministic_k(in, inlen, - WC_HASH_TYPE_SHA256, key->k, key->sign_k, + WC_HASH_TYPE_SHA256, ecc_get_k(key), key->sign_k, curve->order, key->heap) != 0) { mp_free(key->sign_k); XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC); @@ -6722,8 +6862,8 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) #else key->sign_k_set = 0; /* currently limiting to SHA256 for auto create */ - if (wc_ecc_gen_deterministic_k(in, inlen, WC_HASH_TYPE_SHA256, key->k, - key->sign_k, curve->order, key->heap) != 0) { + if (wc_ecc_gen_deterministic_k(in, inlen, WC_HASH_TYPE_SHA256, + ecc_get_k(key), key->sign_k, curve->order, key->heap) != 0) { err = ECC_PRIV_KEY_E; } else { @@ -6783,7 +6923,7 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, err = wc_ecc_gen_k(rng, key->dp->size, b, curve->order); } - while (err == MP_ZERO_E); + while (err == WC_NO_ERR_TRACE(MP_ZERO_E)); loop_check = 0; } #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -6861,15 +7001,18 @@ static int ecc_sign_hash_sw(ecc_key* key, ecc_key* pubkey, WC_RNG* rng, if (err != MP_OKAY) break; if (mp_iszero(r) == MP_NO) { - mp_int* ep = pubkey->k; - mp_int* kp = pubkey->k; - mp_int* x = key->k; + mp_int* kp = ecc_get_k(pubkey); + mp_int* ep = kp; + mp_int* x = ecc_get_k(key); + + /* Blind after getting. */ + ecc_blind_k(key, b); /* find s = (e + xr)/k = b.(e/k.b + x.r/k.b) */ /* k' = k.b */ - err = mp_mulmod(pubkey->k, b, curve->order, kp); + err = mp_mulmod(kp, b, curve->order, kp); if (err != MP_OKAY) break; /* k' = 1/k.b @@ -6948,12 +7091,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_256_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_256_nb(&nb_ctx.sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -6962,8 +7105,8 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_256(in, inlen, rng, key->k, r, s, sign_k, - key->heap); + ret = sp_ecc_sign_256(in, inlen, rng, ecc_get_k(key), r, s, + sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; } @@ -6974,8 +7117,8 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, if (ecc_sets[key->idx].id == ECC_SM2P256V1) { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_sm2_256(in, inlen, rng, key->k, r, s, sign_k, - key->heap); + ret = sp_ecc_sign_sm2_256(in, inlen, rng, ecc_get_k(key), r, s, + sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; } @@ -6988,12 +7131,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_384_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_384_nb(&nb_ctx.sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -7002,8 +7145,8 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_384(in, inlen, rng, key->k, r, s, sign_k, - key->heap); + ret = sp_ecc_sign_384(in, inlen, rng, ecc_get_k(key), r, s, + sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; } @@ -7018,12 +7161,12 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, #endif if (key->nb_ctx) { return sp_ecc_sign_521_nb(&key->nb_ctx->sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } #ifdef WC_ECC_NONBLOCK_ONLY do { /* perform blocking call to non-blocking function */ err = sp_ecc_sign_521_nb(&nb_ctx.sp_ctx, in, inlen, rng, - key->k, r, s, sign_k, key->heap); + ecc_get_k(key), r, s, sign_k, key->heap); } while (err == FP_WOULDBLOCK); return err; #endif @@ -7032,8 +7175,8 @@ static int ecc_sign_hash_sp(const byte* in, word32 inlen, WC_RNG* rng, { int ret; SAVE_VECTOR_REGISTERS(return _svr_ret;); - ret = sp_ecc_sign_521(in, inlen, rng, key->k, r, s, sign_k, - key->heap); + ret = sp_ecc_sign_521(in, inlen, rng, ecc_get_k(key), r, s, + sign_k, key->heap); RESTORE_VECTOR_REGISTERS(); return ret; } @@ -7124,7 +7267,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - defined(WOLFSSL_ASYNC_CRYPT_SW) + defined(WOLFSSL_ASYNC_CRYPT_SW) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_SIGN)) { WC_ASYNC_SW* sw = &key->asyncDev.sw; @@ -7141,7 +7284,7 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, #if defined(WOLFSSL_HAVE_SP_ECC) err = ecc_sign_hash_sp(in, inlen, rng, key, r, s); - if (err != WC_KEY_SIZE_E) { + if (err != WC_NO_ERR_TRACE(WC_KEY_SIZE_E)) { return err; } #else @@ -7256,7 +7399,8 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, if (err == MP_OKAY) err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) - err = wc_mp_to_bigint_sz(key->k, &key->k->raw, keySz); + err = wc_mp_to_bigint_sz(ecc_get_k(key), &ecc_get_k(key)->raw, + keySz); if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); if (err == MP_OKAY) @@ -7264,14 +7408,15 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, #ifdef HAVE_CAVIUM_V if (err == MP_OKAY) - err = NitroxEcdsaSign(key, &e->raw, &key->k->raw, &k->raw, - &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); + err = NitroxEcdsaSign(key, &e->raw, &ecc_get_k(key)->raw, + &k->raw, &r->raw, &s->raw, &curve->prime->raw, + &curve->order->raw); #else if (err == MP_OKAY) - err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k->raw, - &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, - &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, - &curve->Gy->raw); + err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, + &ecc_get_k(key)->raw, &k->raw, &r->raw, &s->raw, + &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, + &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw); #endif #ifndef HAVE_CAVIUM_V @@ -7773,6 +7918,16 @@ int wc_ecc_free(ecc_key* key) if (key->k) #endif mp_forcezero(key->k); +#ifdef WOLFSSL_ECC_BLIND_K +#ifdef ALT_ECC_SIZE + if (key->kb) +#endif + mp_forcezero(key->kb); +#ifdef ALT_ECC_SIZE + if (key->ku) +#endif + mp_forcezero(key->ku); +#endif #ifdef WOLFSSL_CUSTOM_CURVES if (key->deallocSet && key->dp != NULL) @@ -8317,7 +8472,7 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, #endif { err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key); - if (err != CRYPTOCB_UNAVAILABLE) + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return err; /* fall-through when unavailable */ } @@ -8425,7 +8580,7 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, #ifdef WOLFSSL_ASYNC_CRYPT /* if async pending then return and skip done cleanup below */ - if (err == WC_PENDING_E) { + if (err == WC_NO_ERR_TRACE(WC_PENDING_E)) { if (!isPrivateKeyOnly) /* do not advance state if doing make pub key */ key->state++; return err; @@ -9067,7 +9222,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, } err = ecc_verify_hash_sp(r, s, hash, hashlen, res, key); - if (err != NOT_COMPILED_IN) { + if (err != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { if (curveLoaded) { wc_ecc_curve_free(curve); FREE_CURVE_SPECS(); @@ -9845,7 +10000,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_256(key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_256(ecc_get_k(key), res, 1, key->heap); } } else @@ -9853,7 +10008,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SP_SM2) if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SM2P256V1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_sm2_256(key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_sm2_256(ecc_get_k(key), res, 1, key->heap); } } else @@ -9861,7 +10016,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_384(key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_384(ecc_get_k(key), res, 1, key->heap); } } else @@ -9869,7 +10024,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { if (err == MP_OKAY) { - err = sp_ecc_mulmod_base_521(key->k, res, 1, key->heap); + err = sp_ecc_mulmod_base_521(ecc_get_k(key), res, 1, key->heap); } } else @@ -9922,12 +10077,12 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) #else #ifdef ECC_TIMING_RESISTANT if (err == MP_OKAY) - err = wc_ecc_mulmod_ex2(key->k, base, res, a, prime, curve->order, - key->rng, 1, key->heap); + err = wc_ecc_mulmod_ex2(ecc_get_k(key), base, res, a, prime, + curve->order, key->rng, 1, key->heap); #else if (err == MP_OKAY) - err = wc_ecc_mulmod_ex2(key->k, base, res, a, prime, curve->order, - NULL, 1, key->heap); + err = wc_ecc_mulmod_ex2(ecc_get_k(key), base, res, a, prime, + curve->order, NULL, 1, key->heap); #endif #endif /* WOLFSSL_KCAPI_ECC */ } @@ -10198,31 +10353,31 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { return sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? ecc_get_k(key) : NULL, key->heap); } #endif #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SP_SM2) if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SM2P256V1) { return sp_ecc_check_key_sm2_256(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? ecc_get_k(key) : NULL, key->heap); } #endif #ifdef WOLFSSL_SP_384 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) { return sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? ecc_get_k(key) : NULL, key->heap); } #endif #ifdef WOLFSSL_SP_521 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP521R1) { return sp_ecc_check_key_521(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? ecc_get_k(key) : NULL, key->heap); } #endif #if defined(WOLFSSL_SP_1024) && defined(WOLFCRYPT_HAVE_SAKKE) if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SAKKE_1) { return sp_ecc_check_key_1024(key->pubkey.x, key->pubkey.y, - key->type == ECC_PRIVATEKEY ? key->k : NULL, key->heap); + key->type == ECC_PRIVATEKEY ? ecc_get_k(key) : NULL, key->heap); } #endif #endif @@ -10333,8 +10488,8 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) /* SP 800-56Ar3, section 5.6.2.1.2 */ /* private keys must be in the range [1, n-1] */ if ((err == MP_OKAY) && (key->type == ECC_PRIVATEKEY) && - (mp_iszero(key->k) || mp_isneg(key->k) || - (mp_cmp(key->k, curve->order) != MP_LT)) + (mp_iszero(ecc_get_k(key)) || mp_isneg(ecc_get_k(key)) || + (mp_cmp(ecc_get_k(key), curve->order) != MP_LT)) #ifdef WOLFSSL_KCAPI_ECC && key->handle == NULL #endif @@ -10419,12 +10574,26 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, alt_fp_init(key->pubkey.z); key->k = (mp_int*)key->ka; alt_fp_init(key->k); + #ifdef WOLFSSL_ECC_BLIND_K + key->kb = (mp_int*)key->kba; + key->ku = (mp_int*)key->kua; + alt_fp_init(key->kb); + alt_fp_init(key->ku); + #endif + #else + err = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, + #ifndef WOLFSSL_ECC_BLIND_K + NULL, NULL #else - err = mp_init_multi(key->k, - key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); + key->kb, key->ku + #endif + ); #endif if (err != MP_OKAY) return MEMORY_E; +#ifdef WOLFSSL_ECC_BLIND_K + mp_forcezero(key->kb); +#endif SAVE_VECTOR_REGISTERS(return _svr_ret;); @@ -10468,6 +10637,8 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, /* determine key size */ keysize = (int)(inLen>>1); + /* NOTE: FIPS v6.0.0 or greater, no restriction on imported keys, only + * on created keys or signatures */ err = wc_ecc_set_curve(key, keysize, curve_id); key->type = ECC_PUBLICKEY; } @@ -10731,7 +10902,7 @@ int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen, return BUFFER_E; } - err = wc_export_int(key->k, d, dLen, keySz + WC_CAAM_MAC_SZ, + err = wc_export_int(ecc_get_k(key), d, dLen, keySz + WC_CAAM_MAC_SZ, encType); *dLen = keySz + WC_CAAM_MAC_SZ; } @@ -10753,7 +10924,7 @@ int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen, else #endif { - err = wc_export_int(key->k, d, dLen, keySz, encType); + err = wc_export_int(ecc_get_k(key), d, dLen, keySz, encType); if (err != MP_OKAY) return err; } @@ -10862,6 +11033,8 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, wc_ecc_reset(key); /* set key size */ + /* NOTE: FIPS v6.0.0 or greater, no restriction on imported keys, only + * on created keys or signatures */ ret = wc_ecc_set_curve(key, (int)privSz, curve_id); key->type = ECC_PRIVATEKEY_ONLY; } @@ -10886,6 +11059,11 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, } ret = mp_read_unsigned_bin(key->k, priv, privSz); + #ifdef WOLFSSL_ECC_BLIND_K + if (ret == MP_OKAY) { + err = ecc_blind_k_rng(key, NULL); + } + #endif } #elif defined(WOLFSSL_QNX_CAAM) || defined(WOLFSSL_IMXRT1170_CAAM) if ((wc_ecc_size(key) + WC_CAAM_MAC_SZ) == (int)privSz) { @@ -10917,11 +11095,21 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, #else key->blackKey = CAAM_BLACK_KEY_CCM; ret = mp_read_unsigned_bin(key->k, priv, privSz); + #ifdef WOLFSSL_ECC_BLIND_K + if (ret == MP_OKAY) { + err = ecc_blind_k_rng(key, NULL); + } + #endif #endif } else { key->blackKey = 0; ret = mp_read_unsigned_bin(key->k, priv, privSz); + #ifdef WOLFSSL_ECC_BLIND_K + if (ret == MP_OKAY) { + err = ecc_blind_k_rng(key, NULL); + } + #endif /* If using AES-ECB encrypted black keys check here if key is valid, * if not valid than assume is an encrypted key. A public key is needed @@ -10950,8 +11138,8 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, ret = mp_read_unsigned_bin(key->k, priv, privSz); #ifdef HAVE_WOLF_BIGINT - if (ret == 0 && - wc_bigint_from_unsigned_bin(&key->k->raw, priv, privSz) != 0) { + if (ret == 0 && wc_bigint_from_unsigned_bin(&key->k->raw, priv, + privSz) != 0) { mp_clear(key->k); ret = ASN_GETINT_E; } @@ -10993,6 +11181,11 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, #endif } #endif /* WOLFSSL_VALIDATE_ECC_IMPORT */ +#ifdef WOLFSSL_ECC_BLIND_K + if (ret == 0) { + ret = ecc_blind_k_rng(key, NULL); + } +#endif #endif /* WOLFSSL_CRYPTOCELL */ @@ -11168,6 +11361,8 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, wc_ecc_reset(key); /* set curve type and index */ + /* NOTE: FIPS v6.0.0 or greater, no restriction on imported keys, only + * on created keys or signatures */ err = wc_ecc_set_curve(key, 0, curve_id); if (err != 0) { return err; @@ -11183,12 +11378,26 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, alt_fp_init(key->pubkey.z); key->k = (mp_int*)key->ka; alt_fp_init(key->k); +#ifdef WOLFSSL_ECC_BLIND_K + key->kb = (mp_int*)key->kba; + key->ku = (mp_int*)key->kua; + alt_fp_init(key->kb); + alt_fp_init(key->ku); +#endif #else err = mp_init_multi(key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, - NULL, NULL); +#ifndef WOLFSSL_ECC_BLIND_K + NULL, NULL +#else + key->kb, key->ku +#endif + ); #endif if (err != MP_OKAY) return MEMORY_E; +#ifdef WOLFSSL_ECC_BLIND_K + mp_forcezero(key->kb); +#endif /* read Qx */ if (err == MP_OKAY) { @@ -11335,6 +11544,11 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, err = wc_export_int(key->k, &keyRaw[0], &keySz, keySz, WC_TYPE_UNSIGNED_BIN); } + #ifdef WOLFSSL_ECC_BLIND_K + if (err == 0) { + err = ecc_blind_k_rng(key, NULL); + } + #endif if (err == MP_OKAY) { /* Create private key from external key buffer*/ @@ -11366,12 +11580,17 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, (word32)key->dp->size); } } + #ifdef WOLFSSL_ECC_BLIND_K + if (err == 0) { + err = ecc_blind_k_rng(key, NULL); + } + #endif #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) if (err == MP_OKAY) { const word32 key_size = key->dp->size; word32 buf_size = key_size; - err = wc_export_int(key->k, key->privKey, - &buf_size, key_size, WC_TYPE_UNSIGNED_BIN); + err = wc_export_int(key, key->privKey, &buf_size, key_size, + WC_TYPE_UNSIGNED_BIN); mp_reverse(key->privKey, key_size); } #endif @@ -11389,7 +11608,7 @@ static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if (err == MP_OKAY) { err = wc_ecc_check_key(key); - if (err == IS_POINT_E && (mp_iszero(key->pubkey.x) || + if (err == WC_NO_ERR_TRACE(IS_POINT_E) && (mp_iszero(key->pubkey.x) || mp_iszero(key->pubkey.y))) { err = BAD_FUNC_ARG; } @@ -13611,17 +13830,17 @@ int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt) * * @param [in, out] ctx ECIES context object. * @param [in] salt Salt to use with KDF. - * @param [in] len Length of salt in bytes. + * @param [in] sz Length of salt in bytes. * @return 0 on success. * @return BAD_FUNC_ARG when ctx is NULL or salt is NULL and len is not 0. */ -int wc_ecc_ctx_set_kdf_salt(ecEncCtx* ctx, const byte* salt, word32 len) +int wc_ecc_ctx_set_kdf_salt(ecEncCtx* ctx, const byte* salt, word32 sz) { - if (ctx == NULL || (salt == NULL && len != 0)) + if (ctx == NULL || (salt == NULL && sz != 0)) return BAD_FUNC_ARG; ctx->kdfSalt = salt; - ctx->kdfSaltSz = len; + ctx->kdfSaltSz = sz; if (ctx->protocol == REQ_RESP_CLIENT) { ctx->cliSt = ecCLI_SALT_SET; @@ -13633,9 +13852,37 @@ int wc_ecc_ctx_set_kdf_salt(ecEncCtx* ctx, const byte* salt, word32 len) return 0; } +/* Set your own salt. By default we generate a random salt for ourselves. + * This allows overriding that after init or reset. + * + * @param [in, out] ctx ECIES context object. + * @param [in] salt Salt to use for ourselves + * @param [in] sz Length of salt in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when ctx is NULL or salt is NULL and len is not 0. + */ +int wc_ecc_ctx_set_own_salt(ecEncCtx* ctx, const byte* salt, word32 sz) +{ + byte* saltBuffer; + + if (ctx == NULL || ctx->protocol == 0 || salt == NULL) + return BAD_FUNC_ARG; + + if (sz > EXCHANGE_SALT_SZ) + sz = EXCHANGE_SALT_SZ; + saltBuffer = (ctx->protocol == REQ_RESP_CLIENT) ? + ctx->clientSalt : + ctx->serverSalt; + XMEMSET(saltBuffer, 0, EXCHANGE_SALT_SZ); + XMEMCPY(saltBuffer, salt, sz); + + return 0; +} + + static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags) { - byte* saltBuffer = NULL; + byte* saltBuffer; if (ctx == NULL || flags == 0) return BAD_FUNC_ARG; @@ -13645,7 +13892,6 @@ static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags) return wc_RNG_GenerateBlock(ctx->rng, saltBuffer, EXCHANGE_SALT_SZ); } - static void ecc_ctx_init(ecEncCtx* ctx, int flags, WC_RNG* rng) { if (ctx) { @@ -13938,7 +14184,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, &sharedSz); #endif } - while (ret == WC_PENDING_E); + while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); if (ret == 0) { #ifdef WOLFSSL_ECIES_ISO18033 @@ -14357,7 +14603,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret + pubKeySz, &sharedSz); #endif - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); } if (ret == 0) { #ifdef WOLFSSL_ECIES_ISO18033 @@ -14990,57 +15236,57 @@ static int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret) #ifdef WOLFSSL_SMALL_STACK if (t1) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(t1); XFREE(t1, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (C) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(C); XFREE(C, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (Q) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(Q); XFREE(Q, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (S) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(S); XFREE(S, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (Z) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(Z); XFREE(Z, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (M) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(M); XFREE(M, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (T) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(T); XFREE(T, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (R) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(R); XFREE(R, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (N) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(N); XFREE(N, NULL, DYNAMIC_TYPE_ECC_BUFFER); } if (two) { - if (res != MP_INIT_E) + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(two); XFREE(two, NULL, DYNAMIC_TYPE_ECC_BUFFER); } #else - if (res != MP_INIT_E) { + if (res != WC_NO_ERR_TRACE(MP_INIT_E)) { mp_clear(t1); mp_clear(C); mp_clear(Q); diff --git a/src/wolfcrypt/src/eccsi.c b/src/wolfcrypt/src/eccsi.c index 0b12991..69d999b 100644 --- a/src/wolfcrypt/src/eccsi.c +++ b/src/wolfcrypt/src/eccsi.c @@ -1447,7 +1447,7 @@ static int eccsi_mulmod_point_add(EccsiKey* key, const mp_int* n, ecc_point* point, ecc_point* a, ecc_point* res, mp_digit mp, int map) { #if defined(WOLFSSL_HAVE_SP_ECC) && !defined(WOLFSSL_SP_NO_256) - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); if ((key->ecc.idx != ECC_CUSTOM_IDX) && (ecc_sets[key->ecc.idx].id == ECC_SECP256R1)) { diff --git a/src/wolfcrypt/src/ed25519.c b/src/wolfcrypt/src/ed25519.c index f59b672..381b911 100644 --- a/src/wolfcrypt/src/ed25519.c +++ b/src/wolfcrypt/src/ed25519.c @@ -36,6 +36,15 @@ #include #ifdef HAVE_ED25519 +#if FIPS_VERSION3_GE(6,0,0) + /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ + #define FIPS_NO_WRAPPERS + + #ifdef USE_WINDOWS_API + #pragma code_seg(".fipsA$f") + #pragma const_seg(".fipsB$f") + #endif +#endif #include #include @@ -48,6 +57,15 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_ed25519_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000006 }; + int wolfCrypt_FIPS_ED25519_sanity(void) + { + return 0; + } +#endif + #ifdef FREESCALE_LTC_ECC #include #endif @@ -190,6 +208,56 @@ static int ed25519_hash(ed25519_key* key, const byte* in, word32 inLen, } #ifdef HAVE_ED25519_MAKE_KEY +#if FIPS_VERSION3_GE(6,0,0) +/* Performs a Pairwise Consistency Test on an Ed25519 key pair. + * + * @param [in] key Ed25519 key to test. + * @param [in] rng Random number generator to use to create random digest. + * @return 0 on success. + * @return ECC_PCT_E when signing or verification fail. + * @return Other -ve when random number generation fails. + */ +static int ed25519_pairwise_consistency_test(ed25519_key* key, WC_RNG* rng) +{ + int err = 0; + byte digest[WC_SHA512_DIGEST_SIZE]; + word32 digestLen = WC_SHA512_DIGEST_SIZE; + byte sig[ED25519_SIG_SIZE]; + word32 sigLen = ED25519_SIG_SIZE; + int res = 0; + + /* Generate a random digest to sign. */ + err = wc_RNG_GenerateBlock(rng, digest, digestLen); + if (err == 0) { + /* Sign digest without context. */ + err = wc_ed25519_sign_msg_ex(digest, digestLen, sig, &sigLen, key, + (byte)Ed25519, NULL, 0); + if (err != 0) { + /* Any sign failure means test failed. */ + err = ECC_PCT_E; + } + } + if (err == 0) { + /* Verify digest without context. */ + err = wc_ed25519_verify_msg_ex(sig, sigLen, digest, digestLen, &res, + key, (byte)Ed25519, NULL, 0); + if (err != 0) { + /* Any verification operation failure means test failed. */ + err = ECC_PCT_E; + } + /* Check whether the signature verified. */ + else if (res == 0) { + /* Test failed. */ + err = ECC_PCT_E; + } + } + + ForceZero(sig, sigLen); + + return err; +} +#endif + int wc_ed25519_make_public(ed25519_key* key, unsigned char* pubKey, word32 pubKeySz) { @@ -252,7 +320,7 @@ int wc_ed25519_make_key(WC_RNG* rng, int keySz, ed25519_key* key) #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Ed25519Gen(rng, keySz, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -273,6 +341,13 @@ int wc_ed25519_make_key(WC_RNG* rng, int keySz, ed25519_key* key) /* put public key after private key, on the same buffer */ XMEMMOVE(key->k + ED25519_KEY_SIZE, key->p, ED25519_PUB_KEY_SIZE); +#if FIPS_VERSION3_GE(6,0,0) + ret = wc_ed25519_check_key(key); + if (ret == 0) { + ret = ed25519_pairwise_consistency_test(key, rng); + } +#endif + return ret; } #endif /* HAVE_ED25519_MAKE_KEY */ @@ -325,7 +400,7 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Ed25519Sign(in, inLen, out, outLen, key, type, context, contextLen); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -623,15 +698,14 @@ static int ed25519_verify_msg_update_with_sha(const byte* msgSegment, return ed25519_hash_update(key, sha, msgSegment, msgSegmentLen); } -/* Low part of order in big endian. */ -static const byte ed25519_low_order[] = { - 0x14, 0xde, 0xf9, 0xde, 0xa2, 0xf7, 0x9c, 0xd6, - 0x58, 0x12, 0x63, 0x1a, 0x5c, 0xf5, 0xd3, 0xed +/* ed25519 order in little endian. */ +static const byte ed25519_order[] = { + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 }; -#define ED25519_SIG_LOW_ORDER_IDX \ - ((int)(ED25519_SIG_SIZE/2 + sizeof(ed25519_low_order) - 1)) - /* sig is array of bytes containing the signature sigLen is the length of sig byte array @@ -650,6 +724,7 @@ static int ed25519_verify_msg_final_with_sha(const byte* sig, word32 sigLen, ge_p2 R; #endif int ret; + int i; /* sanity check on arguments */ if (sig == NULL || res == NULL || key == NULL) @@ -665,33 +740,19 @@ static int ed25519_verify_msg_final_with_sha(const byte* sig, word32 sigLen, * 2^252 + 0x14def9dea2f79cd65812631a5cf5d3ed * = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed */ - if (sig[ED25519_SIG_SIZE-1] > 0x10) - return BAD_FUNC_ARG; - if (sig[ED25519_SIG_SIZE-1] == 0x10) { - int i = ED25519_SIG_SIZE-1; - int j; - - /* Check high zeros. */ - for (--i; i > ED25519_SIG_LOW_ORDER_IDX; i--) { - if (sig[i] > 0x00) - break; - } - /* Did we see all zeros up to lower order index? */ - if (i == ED25519_SIG_LOW_ORDER_IDX) { - /* Check lower part. */ - for (j = 0; j < (int)sizeof(ed25519_low_order); j++, i--) { - /* Check smaller. */ - if (sig[i] < ed25519_low_order[j]) - break; - /* Check bigger. */ - if (sig[i] > ed25519_low_order[j]) - return BAD_FUNC_ARG; - } - /* Check equal - all bytes match. */ - if (i == ED25519_SIG_SIZE/2 - 1) - return BAD_FUNC_ARG; - } + + /* Check S is not larger than or equal to order. */ + for (i = (int)sizeof(ed25519_order) - 1; i >= 0; i--) { + /* Bigger than order. */ + if (sig[ED25519_SIG_SIZE/2 + i] > ed25519_order[i]) + return BAD_FUNC_ARG; + /* Less than order. */ + if (sig[ED25519_SIG_SIZE/2 + i] < ed25519_order[i]) + break; } + /* Check equal - all bytes match. */ + if (i == -1) + return BAD_FUNC_ARG; /* uncompress A (public key), test if valid, and negate it */ #ifndef FREESCALE_LTC_ECC @@ -797,7 +858,7 @@ int wc_ed25519_verify_msg_ex(const byte* sig, word32 sigLen, const byte* msg, if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Ed25519Verify(sig, sigLen, msg, msgLen, res, key, type, context, contextLen); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1059,7 +1120,7 @@ int wc_ed25519_import_public_ex(const byte* in, word32 inLen, ed25519_key* key, if (ret == 0) { key->pubKeySet = 1; - if (key->privKeySet && (!trusted)) { + if (!trusted) { ret = wc_ed25519_check_key(key); } } @@ -1260,23 +1321,84 @@ int wc_ed25519_export_key(ed25519_key* key, #endif /* HAVE_ED25519_KEY_EXPORT */ -/* check the private and public keys match */ +/* Check the public key is valid. + * + * When private key available, check the calculated public key matches. + * When no private key, check Y is in range and an X is able to be calculated. + * + * @param [in] key Ed25519 private/public key. + * @return 0 otherwise. + * @return BAD_FUNC_ARG when key is NULL. + * @return PUBLIC_KEY_E when the public key is not set, doesn't match or is + * invalid. + * @return other -ve value on hash failure. + */ int wc_ed25519_check_key(ed25519_key* key) { int ret = 0; -#ifdef HAVE_ED25519_MAKE_KEY - ALIGN16 unsigned char pubKey[ED25519_PUB_KEY_SIZE]; - if (!key->pubKeySet) + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + /* Check we have a public key to check. */ + if ((ret == 0) && (!key->pubKeySet)) { ret = PUBLIC_KEY_E; - if (ret == 0) + } + +#ifdef HAVE_ED25519_MAKE_KEY + /* If we have a private key just make the public key and compare. */ + if ((ret == 0) && (key->privKeySet)) { + ALIGN16 unsigned char pubKey[ED25519_PUB_KEY_SIZE]; + ret = wc_ed25519_make_public(key, pubKey, sizeof(pubKey)); - if (ret == 0 && XMEMCMP(pubKey, key->p, ED25519_PUB_KEY_SIZE) != 0) - ret = PUBLIC_KEY_E; + if (ret == 0 && XMEMCMP(pubKey, key->p, ED25519_PUB_KEY_SIZE) != 0) + ret = PUBLIC_KEY_E; + } #else - (void)key; + (void)key; #endif /* HAVE_ED25519_MAKE_KEY */ + /* No private key (or ability to make a public key), check Y is valid. */ + if ((ret == 0) +#ifdef HAVE_ED25519_MAKE_KEY + && (!key->privKeySet) +#endif + ) { + /* Verify that Q is not identity element 0. + * 0 has no representation for Ed25519. */ + + /* Verify that xQ and yQ are integers in the interval [0, p - 1]. + * Only have yQ so check that ordinate. p = 2^255 - 19 */ + if ((key->p[ED25519_PUB_KEY_SIZE - 1] & 0x7f) == 0x7f) { + int i; + + ret = PUBLIC_KEY_E; + /* Check up to last byte. */ + for (i = ED25519_PUB_KEY_SIZE - 2; i > 0; i--) { + if (key->p[i] != 0xff) { + ret = 0; + break; + } + } + /* Bits are all one up to last byte - check less than -19. */ + if ((ret == WC_NO_ERR_TRACE(PUBLIC_KEY_E)) && (key->p[0] < 0xed)) { + ret = 0; + } + } + + if (ret == 0) { + /* Verify that Q is on the curve. + * Uncompressing the public key will validate yQ. */ + ge_p3 A; + + if (ge_frombytes_negate_vartime(&A, key->p) != 0) { + ret = PUBLIC_KEY_E; + } + } + } + return ret; } diff --git a/src/wolfcrypt/src/ed448.c b/src/wolfcrypt/src/ed448.c index e93c212..e9e865c 100644 --- a/src/wolfcrypt/src/ed448.c +++ b/src/wolfcrypt/src/ed448.c @@ -38,6 +38,15 @@ #include #ifdef HAVE_ED448 +#if FIPS_VERSION3_GE(6,0,0) + /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ + #define FIPS_NO_WRAPPERS + + #ifdef USE_WINDOWS_API + #pragma code_seg(".fipsA$f") + #pragma const_seg(".fipsB$f") + #endif +#endif #include #include @@ -56,6 +65,14 @@ static const byte ed448Ctx[ED448CTX_SIZE+1] = "SigEd448"; #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_ed448_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000007 }; + int wolfCrypt_FIPS_ED448_sanity(void) + { + return 0; + } +#endif static int ed448_hash_init(ed448_key* key, wc_Shake *sha) { @@ -170,6 +187,56 @@ static int ed448_hash(ed448_key* key, const byte* in, word32 inLen, return ret; } +#if FIPS_VERSION3_GE(6,0,0) +/* Performs a Pairwise Consistency Test on an Ed448 key pair. + * + * @param [in] key Ed448 key to test. + * @param [in] rng Random number generator to use to create random digest. + * @return 0 on success. + * @return ECC_PCT_E when signing or verification fail. + * @return Other -ve when random number generation fails. + */ +static int ed448_pairwise_consistency_test(ed448_key* key, WC_RNG* rng) +{ + int err = 0; + byte digest[WC_SHA256_DIGEST_SIZE]; + word32 digestLen = WC_SHA256_DIGEST_SIZE; + byte sig[ED448_SIG_SIZE]; + word32 sigLen = ED448_SIG_SIZE; + int res = 0; + + /* Generate a random digest to sign. */ + err = wc_RNG_GenerateBlock(rng, digest, digestLen); + if (err == 0) { + /* Sign digest without context. */ + err = wc_ed448_sign_msg_ex(digest, digestLen, sig, &sigLen, key, Ed448, + NULL, 0); + if (err != 0) { + /* Any sign failure means test failed. */ + err = ECC_PCT_E; + } + } + if (err == 0) { + /* Verify digest without context. */ + err = wc_ed448_verify_msg_ex(sig, sigLen, digest, digestLen, &res, key, + Ed448, NULL, 0); + if (err != 0) { + /* Any verification operation failure means test failed. */ + err = ECC_PCT_E; + } + /* Check whether the signature verified. */ + else if (res == 0) { + /* Test failed. */ + err = ECC_PCT_E; + } + } + + ForceZero(sig, sigLen); + + return err; +} +#endif + /* Derive the public key for the private key. * * key [in] Ed448 key object. @@ -255,6 +322,13 @@ int wc_ed448_make_key(WC_RNG* rng, int keySz, ed448_key* key) if (ret == 0) { /* put public key after private key, on the same buffer */ XMEMMOVE(key->k + ED448_KEY_SIZE, key->p, ED448_PUB_KEY_SIZE); + + #if FIPS_VERSION3_GE(6,0,0) + ret = wc_ed448_check_key(key); + if (ret == 0) { + ret = ed448_pairwise_consistency_test(key, rng); + } + #endif } return ret; @@ -949,7 +1023,7 @@ int wc_ed448_import_public_ex(const byte* in, word32 inLen, ed448_key* key, ret = BAD_FUNC_ARG; } - if (inLen != ED448_PUB_KEY_SIZE) { + if ((inLen != ED448_PUB_KEY_SIZE) && (inLen != ED448_PUB_KEY_SIZE + 1)) { ret = BAD_FUNC_ARG; } @@ -978,7 +1052,7 @@ int wc_ed448_import_public_ex(const byte* in, word32 inLen, ed448_key* key, if (ret == 0) { key->pubKeySet = 1; - if (key->privKeySet && (!trusted)) { + if (!trusted) { /* Check untrusted public key data matches private key. */ ret = wc_ed448_check_key(key); } @@ -1226,31 +1300,91 @@ int wc_ed448_export_key(ed448_key* key, byte* priv, word32 *privSz, #endif /* HAVE_ED448_KEY_EXPORT */ -/* Check the public key of the ed448 key matches the private key. +/* Check the public key is valid. * - * key [in] Ed448 private/public key. - * returns BAD_FUNC_ARG when key is NULL, - * PUBLIC_KEY_E when the public key is not set or doesn't match, - * other -ve value on hash failure, - * 0 otherwise. + * When private key available, check the calculated public key matches. + * When no private key, check Y is in range and an X is able to be calculated. + * + * @param [in] key Ed448 private/public key. + * @return 0 otherwise. + * @return BAD_FUNC_ARG when key is NULL. + * @return PUBLIC_KEY_E when the public key is not set, doesn't match or is + * invalid. + * @return other -ve value on hash failure. */ int wc_ed448_check_key(ed448_key* key) { int ret = 0; unsigned char pubKey[ED448_PUB_KEY_SIZE]; + /* Validate parameter. */ if (key == NULL) { ret = BAD_FUNC_ARG; } + /* Check we have a public key to check. */ if (ret == 0 && !key->pubKeySet) { ret = PUBLIC_KEY_E; } - if (ret == 0) { + + /* If we have a private key just make the public key and compare. */ + if ((ret == 0) && key->privKeySet) { ret = wc_ed448_make_public(key, pubKey, sizeof(pubKey)); + if ((ret == 0) && (XMEMCMP(pubKey, key->p, ED448_PUB_KEY_SIZE) != 0)) { + ret = PUBLIC_KEY_E; + } } - if ((ret == 0) && (XMEMCMP(pubKey, key->p, ED448_PUB_KEY_SIZE) != 0)) { - ret = PUBLIC_KEY_E; + /* No private key, check Y is valid. */ + else if ((ret == 0) && (!key->privKeySet)) { + /* Verify that Q is not identity element 0. + * 0 has no representation for Ed448. */ + + /* Verify that xQ and yQ are integers in the interval [0, p - 1]. + * Only have yQ so check that ordinate. + * p = 2^448-2^224-1 = 0xff..fe..ff + */ + { + int i; + ret = PUBLIC_KEY_E; + + /* Check top part before 0xFE. */ + for (i = ED448_PUB_KEY_SIZE - 1; i > ED448_PUB_KEY_SIZE/2; i--) { + if (key->p[i] < 0xff) { + ret = 0; + break; + } + } + if (ret == WC_NO_ERR_TRACE(PUBLIC_KEY_E)) { + /* Check against 0xFE. */ + if (key->p[ED448_PUB_KEY_SIZE/2] < 0xfe) { + ret = 0; + } + else if (key->p[ED448_PUB_KEY_SIZE/2] == 0xfe) { + /* Check bottom part before last byte. */ + for (i = ED448_PUB_KEY_SIZE/2 - 1; i > 0; i--) { + if (key->p[i] != 0xff) { + ret = 0; + break; + } + } + /* Check last byte. */ + if ((ret == WC_NO_ERR_TRACE(PUBLIC_KEY_E)) && + (key->p[0] < 0xff)) { + ret = 0; + } + } + } + } + + if (ret == 0) { + /* Verify that Q is on the curve. + * Uncompressing the public key will validate yQ. */ + ge448_p2 A; + + if (ge448_from_bytes_negate_vartime(&A, key->p) != 0) { + ret = PUBLIC_KEY_E; + } + } } return ret; diff --git a/src/wolfcrypt/src/error.c b/src/wolfcrypt/src/error.c index eebd4db..2e25b60 100644 --- a/src/wolfcrypt/src/error.c +++ b/src/wolfcrypt/src/error.c @@ -34,6 +34,11 @@ #endif #ifndef NO_ERROR_STRINGS + +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H +#include +#endif + WOLFSSL_ABI const char* wc_GetErrorString(int error) { @@ -604,12 +609,37 @@ const char* wc_GetErrorString(int error) case KEY_EXHAUSTED_E: return "Key no longer usable for operation"; + case FIPS_INVALID_VER_E: + return "Invalid FIPS version defined, check length"; + + case FIPS_DATA_SZ_E: + return "FIPS Module Data too large adjust MAX_FIPS_DATA_SZ"; + + case FIPS_CODE_SZ_E: + return "FIPS Module Code too large adjust MAX_FIPS_CODE_SZ"; + + case KDF_SRTP_KAT_FIPS_E: + return "wolfCrypt FIPS SRTP-KDF Known Answer Test Failure"; + + case ED25519_KAT_FIPS_E: + return "wolfCrypt FIPS Ed25519 Known Answer Test Failure"; + + case ED448_KAT_FIPS_E: + return "wolfCrypt FIPS Ed448 Known Answer Test Failure"; + + case PBKDF2_KAT_FIPS_E: + return "wolfCrypt FIPS PBKDF2 Known Answer Test Failure"; + default: return "unknown error number"; } } +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#include +#endif + void wc_ErrorString(int error, char* buffer) { XSTRNCPY(buffer, wc_GetErrorString(error), WOLFSSL_MAX_ERROR_SZ); diff --git a/src/wolfcrypt/src/evp.c b/src/wolfcrypt/src/evp.c index a365ff6..42949fc 100644 --- a/src/wolfcrypt/src/evp.c +++ b/src/wolfcrypt/src/evp.c @@ -711,8 +711,19 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, static int wolfSSL_EVP_CipherUpdate_GCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authInSz + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)(ctx->authInSz + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -745,9 +756,19 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, /* Buffer input for one-shot API */ if (inl > 0) { byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authBufferLen + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)(ctx->authBufferLen + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -817,8 +838,19 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, static int wolfSSL_EVP_CipherUpdate_CCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authInSz + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)(ctx->authInSz + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -843,9 +875,19 @@ static int wolfSSL_EVP_CipherUpdate_CCM(WOLFSSL_EVP_CIPHER_CTX *ctx, /* Buffer input for one-shot API */ if (inl > 0) { byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authBufferLen + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)(ctx->authBufferLen + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -875,8 +917,19 @@ static int wolfSSL_EVP_CipherUpdate_AriaGCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)ctx->authInSz + inl, NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)ctx->authInSz + inl, NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -905,9 +958,18 @@ static int wolfSSL_EVP_CipherUpdate_AriaGCM(WOLFSSL_EVP_CIPHER_CTX *ctx, if (ctx->enc == 0) { /* Append extra space for the tag */ size = WC_ARIA_GCM_GET_CIPHERTEXT_SIZE(size); } - tmp = (byte*)XREALLOC(ctx->authBuffer, - (size_t)size, NULL, - DYNAMIC_TYPE_OPENSSL); + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)size, NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)size, NULL, + DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -2693,9 +2755,19 @@ int wolfSSL_EVP_PKEY_CTX_add1_hkdf_info(WOLFSSL_EVP_PKEY_CTX* ctx, if (ret == WOLFSSL_SUCCESS && info != NULL && infoSz > 0) { unsigned char* p; /* If there's already info in the buffer, append. */ + #ifdef WOLFSSL_NO_REALLOC + p = (byte*)XMALLOC((size_t)(ctx->pkey->hkdfInfoSz + (word32)infoSz), NULL, + DYNAMIC_TYPE_INFO); + if (p != NULL) { + XMEMCPY(p, ctx->pkey->hkdfInfo, (size_t)ctx->pkey->hkdfInfoSz); + XFREE(ctx->pkey->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); + ctx->pkey->hkdfInfo = NULL; + } + #else p = (byte*)XREALLOC(ctx->pkey->hkdfInfo, (size_t)(ctx->pkey->hkdfInfoSz + (word32)infoSz), NULL, DYNAMIC_TYPE_INFO); + #endif if (p == NULL) { WOLFSSL_MSG("Failed to reallocate larger HKDF info buffer."); ret = WOLFSSL_FAILURE; @@ -3211,6 +3283,8 @@ int wolfSSL_EVP_PKEY_bits(const WOLFSSL_EVP_PKEY *pkey) if (pkey == NULL) return 0; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); if ((bytes = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey)) ==0) return 0; + if (bytes < 0) + return 0; return bytes*8; } @@ -4275,23 +4349,39 @@ static int wolfssl_evp_digest_pk_final(WOLFSSL_EVP_MD_CTX *ctx, int ret; if (ctx->isHMAC) { - Hmac hmacCopy; - - if (wolfSSL_HmacCopy(&hmacCopy, &ctx->hash.hmac) != WOLFSSL_SUCCESS) +#ifdef WOLFSSL_SMALL_STACK + Hmac *hmacCopy = (Hmac *)XMALLOC(sizeof(Hmac), NULL, DYNAMIC_TYPE_OPENSSL); + if (hmacCopy == NULL) return WOLFSSL_FAILURE; - ret = wc_HmacFinal(&hmacCopy, md) == 0; - wc_HmacFree(&hmacCopy); +#else + Hmac hmacCopy[1]; +#endif + ret = wolfSSL_HmacCopy(hmacCopy, &ctx->hash.hmac); + if (ret == WOLFSSL_SUCCESS) + ret = wc_HmacFinal(hmacCopy, md) == 0; + wc_HmacFree(hmacCopy); +#ifdef WOLFSSL_SMALL_STACK + XFREE(hmacCopy, NULL, DYNAMIC_TYPE_OPENSSL); +#endif return ret; } else { - WOLFSSL_EVP_MD_CTX ctxCopy; - wolfSSL_EVP_MD_CTX_init(&ctxCopy); - - if (wolfSSL_EVP_MD_CTX_copy_ex(&ctxCopy, ctx) != WOLFSSL_SUCCESS) +#ifdef WOLFSSL_SMALL_STACK + WOLFSSL_EVP_MD_CTX *ctxCopy = (WOLFSSL_EVP_MD_CTX *)XMALLOC(sizeof(WOLFSSL_EVP_MD_CTX), NULL, DYNAMIC_TYPE_OPENSSL); + if (ctxCopy == NULL) return WOLFSSL_FAILURE; +#else + WOLFSSL_EVP_MD_CTX ctxCopy[1]; +#endif + wolfSSL_EVP_MD_CTX_init(ctxCopy); - ret = wolfSSL_EVP_DigestFinal(&ctxCopy, md, mdlen); - wolfSSL_EVP_MD_CTX_cleanup(&ctxCopy); + ret = wolfSSL_EVP_MD_CTX_copy_ex(ctxCopy, ctx); + if (ret == WOLFSSL_SUCCESS) + ret = wolfSSL_EVP_DigestFinal(ctxCopy, md, mdlen); + wolfSSL_EVP_MD_CTX_cleanup(ctxCopy); +#ifdef WOLFSSL_SMALL_STACK + XFREE(ctxCopy, NULL, DYNAMIC_TYPE_OPENSSL); +#endif return ret; } } @@ -5468,7 +5558,7 @@ void wolfSSL_EVP_init(void) #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) +#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0)) #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) { @@ -8465,7 +8555,7 @@ void wolfSSL_EVP_init(void) } if (ret < 0) { - if (ret == AES_GCM_AUTH_E) { + if (ret == WC_NO_ERR_TRACE(AES_GCM_AUTH_E)) { WOLFSSL_MSG("wolfSSL_EVP_Cipher failure: bad AES-GCM tag."); } WOLFSSL_MSG("wolfSSL_EVP_Cipher failure"); @@ -8543,7 +8633,7 @@ static int PopulateRSAEvpPkeyDer(WOLFSSL_EVP_PKEY *pkey) if (key->pkcs8HeaderSz) { ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, NULL, (word32)derSz, RSAk, NULL, 0); - if (ret == LENGTH_ONLY_E) + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) ret = 0; } #endif @@ -8917,7 +9007,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) ret = wc_DhParamsToDer(dhkey,NULL,&derSz); } - if (derSz == 0 || ret != LENGTH_ONLY_E) { + if (derSz == 0 || ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Failed to get size of DH Key"); return WOLFSSL_FAILURE; } @@ -9060,7 +9150,7 @@ static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) #ifdef HAVE_PKCS8 if (key->pkcs8HeaderSz) { /* when key has pkcs8 header the pkey should too */ - if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == LENGTH_ONLY_E) { + if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { derBuf = (byte*)XMALLOC((size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); if (derBuf) { @@ -9112,8 +9202,17 @@ static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) } else if (ecc->type == ECC_PUBLICKEY) { if ((derSz = wc_EccPublicKeyDerSize(ecc, 1)) > 0) { - derBuf = (byte*)XREALLOC(pkey->pkey.ptr, (size_t)derSz, NULL, + #ifdef WOLFSSL_NO_REALLOC + derBuf = (byte*)XMALLOC((size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + if (derBuf != NULL) { + XMEMCPY(derBuf, pkey->pkey.ptr, (size_t)pkey->pkey_sz); + XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); + pkey->pkey.ptr = NULL; + } + #else + derBuf = (byte*)XREALLOC(pkey->pkey.ptr, (size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + #endif if (derBuf != NULL) { pkey->pkey.ptr = (char*)derBuf; if ((derSz = wc_EccPublicKeyToDer(ecc, derBuf, (word32)derSz, @@ -9205,7 +9304,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); @@ -9229,6 +9328,9 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) ret = NID_sha512WithRSAEncryption; } } + else { + ret = BAD_FUNC_ARG; + } WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); @@ -12432,7 +12534,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, (word32)(BASE64_DECODE_BLOCK_SIZE - ctx->remaining), (word32)inl); for ( i = 0; cpySz > 0 && inLen > 0; i++) { - if (Base64_SkipNewline(in, &inLen, &j) == ASN_INPUT_E) { + if (Base64_SkipNewline(in, &inLen, &j) == WC_NO_ERR_TRACE(ASN_INPUT_E)) { return -1; /* detected an illegal char in input */ } c = in[j++]; @@ -12472,7 +12574,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, */ while (inLen > 3) { if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12486,7 +12588,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, } inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12497,7 +12599,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, e[1] = in[j++]; inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12508,7 +12610,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, e[2] = in[j++]; inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12615,8 +12717,10 @@ int wolfSSL_EVP_DecodeFinal(WOLFSSL_EVP_ENCODE_CTX* ctx, inLen = (word32)ctx->remaining; if ((res = Base64_SkipNewline(ctx->data, &inLen, &j)) != 0) { *outl = 0; - if (res == BUFFER_E) /* means no valid data to decode in buffer */ + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { + /* means no valid data to decode in buffer */ return 1; /* returns as success with no output */ + } else return -1; } diff --git a/src/wolfcrypt/src/ext_kyber.c b/src/wolfcrypt/src/ext_kyber.c index 0e694c0..77ab430 100644 --- a/src/wolfcrypt/src/ext_kyber.c +++ b/src/wolfcrypt/src/ext_kyber.c @@ -329,7 +329,7 @@ int wc_KyberKey_MakeKey(KyberKey* key, WC_RNG* rng) { ret = wc_CryptoCb_MakePqcKemKey(rng, WC_PQC_KEM_TYPE_KYBER, key->type, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; @@ -440,7 +440,7 @@ int wc_KyberKey_Encapsulate(KyberKey* key, unsigned char* ct, unsigned char* ss, ) { ret = wc_CryptoCb_PqcEncapsulate(ct, ctlen, ss, KYBER_SS_SZ, rng, WC_PQC_KEM_TYPE_KYBER, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; @@ -549,7 +549,7 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, ) { ret = wc_CryptoCb_PqcDecapsulate(ct, ctlen, ss, KYBER_SS_SZ, WC_PQC_KEM_TYPE_KYBER, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; @@ -608,7 +608,8 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, * @return NOT_COMPILED_IN when key type is not supported. * @return BUFFER_E when len is not the correct size. */ -int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, word32 len) +int wc_KyberKey_DecodePrivateKey(KyberKey* key, const unsigned char* in, + word32 len) { int ret = 0; word32 privLen = 0; @@ -647,7 +648,8 @@ int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, word32 len) * @return NOT_COMPILED_IN when key type is not supported. * @return BUFFER_E when len is not the correct size. */ -int wc_KyberKey_DecodePublicKey(KyberKey* key, unsigned char* in, word32 len) +int wc_KyberKey_DecodePublicKey(KyberKey* key, const unsigned char* in, + word32 len) { int ret = 0; word32 pubLen = 0; diff --git a/src/wolfcrypt/src/ext_lms.c b/src/wolfcrypt/src/ext_lms.c index a515507..7a59576 100644 --- a/src/wolfcrypt/src/ext_lms.c +++ b/src/wolfcrypt/src/ext_lms.c @@ -160,38 +160,77 @@ const char * wc_LmsKey_ParmToStr(enum wc_LmsParm lmsParm) { switch (lmsParm) { case WC_LMS_PARM_NONE: - return "LMS_NONE"; - + return "LMS/HSS NONE"; + case WC_LMS_PARM_L1_H5_W1: + return "LMS/HSS L1_H5_W1"; + case WC_LMS_PARM_L1_H5_W2: + return "LMS/HSS L1_H5_W2"; + case WC_LMS_PARM_L1_H5_W4: + return "LMS/HSS L1_H5_W4"; + case WC_LMS_PARM_L1_H5_W8: + return "LMS/HSS L1_H5_W8"; + case WC_LMS_PARM_L1_H10_W2: + return "LMS/HSS L1_H10_W2"; + case WC_LMS_PARM_L1_H10_W4: + return "LMS/HSS L1_H10_W4"; + case WC_LMS_PARM_L1_H10_W8: + return "LMS/HSS L1_H10_W8"; case WC_LMS_PARM_L1_H15_W2: return "LMS/HSS L1_H15_W2"; - case WC_LMS_PARM_L1_H15_W4: return "LMS/HSS L1_H15_W4"; - + case WC_LMS_PARM_L1_H15_W8: + return "LMS/HSS L1_H15_W8"; + case WC_LMS_PARM_L1_H20_W2: + return "LMS/HSS L1_H20_W2"; + case WC_LMS_PARM_L1_H20_W4: + return "LMS/HSS L1_H20_W4"; + case WC_LMS_PARM_L1_H20_W8: + return "LMS/HSS L1_H20_W8"; + case WC_LMS_PARM_L2_H5_W2: + return "LMS/HSS L2_H5_W2"; + case WC_LMS_PARM_L2_H5_W4: + return "LMS/HSS L2_H5_W4"; + case WC_LMS_PARM_L2_H5_W8: + return "LMS/HSS L2_H5_W8"; case WC_LMS_PARM_L2_H10_W2: return "LMS/HSS L2_H10_W2"; - case WC_LMS_PARM_L2_H10_W4: return "LMS/HSS L2_H10_W4"; - case WC_LMS_PARM_L2_H10_W8: return "LMS/HSS L2_H10_W8"; - + case WC_LMS_PARM_L2_H15_W2: + return "LMS/HSS L2_H15_W2"; + case WC_LMS_PARM_L2_H15_W4: + return "LMS/HSS L2_H15_W4"; + case WC_LMS_PARM_L2_H15_W8: + return "LMS/HSS L2_H15_W8"; + case WC_LMS_PARM_L2_H20_W2: + return "LMS/HSS L2_H20_W2"; + case WC_LMS_PARM_L2_H20_W4: + return "LMS/HSS L2_H20_W4"; + case WC_LMS_PARM_L2_H20_W8: + return "LMS/HSS L2_H20_W8"; case WC_LMS_PARM_L3_H5_W2: return "LMS/HSS L3_H5_W2"; - case WC_LMS_PARM_L3_H5_W4: return "LMS/HSS L3_H5_W4"; - case WC_LMS_PARM_L3_H5_W8: return "LMS/HSS L3_H5_W8"; - case WC_LMS_PARM_L3_H10_W4: return "LMS/HSS L3_H10_W4"; - + case WC_LMS_PARM_L3_H10_W8: + return "LMS/HSS L3_H10_W8"; + case WC_LMS_PARM_L4_H5_W2: + return "LMS/HSS L4_H5_W2"; + case WC_LMS_PARM_L4_H5_W4: + return "LMS/HSS L4_H5_W4"; case WC_LMS_PARM_L4_H5_W8: return "LMS/HSS L4_H5_W8"; - + case WC_LMS_PARM_L4_H10_W4: + return "LMS/HSS L4_H10_W4"; + case WC_LMS_PARM_L4_H10_W8: + return "LMS/HSS L4_H10_W8"; default: WOLFSSL_MSG("error: invalid LMS parameter"); break; @@ -279,36 +318,76 @@ int wc_LmsKey_SetLmsParm(LmsKey * key, enum wc_LmsParm lmsParm) /* If NONE is passed, default to the lowest predefined set. */ switch (lmsParm) { case WC_LMS_PARM_NONE: + case WC_LMS_PARM_L1_H5_W1: + return wc_LmsKey_SetParameters(key, 1, 5, 1); + case WC_LMS_PARM_L1_H5_W2: + return wc_LmsKey_SetParameters(key, 1, 5, 2); + case WC_LMS_PARM_L1_H5_W4: + return wc_LmsKey_SetParameters(key, 1, 5, 4); + case WC_LMS_PARM_L1_H5_W8: + return wc_LmsKey_SetParameters(key, 1, 5, 8); + case WC_LMS_PARM_L1_H10_W2: + return wc_LmsKey_SetParameters(key, 1, 10, 2); + case WC_LMS_PARM_L1_H10_W4: + return wc_LmsKey_SetParameters(key, 1, 10, 4); + case WC_LMS_PARM_L1_H10_W8: + return wc_LmsKey_SetParameters(key, 1, 10, 8); case WC_LMS_PARM_L1_H15_W2: return wc_LmsKey_SetParameters(key, 1, 15, 2); - case WC_LMS_PARM_L1_H15_W4: return wc_LmsKey_SetParameters(key, 1, 15, 4); - + case WC_LMS_PARM_L1_H15_W8: + return wc_LmsKey_SetParameters(key, 1, 15, 8); + case WC_LMS_PARM_L1_H20_W2: + return wc_LmsKey_SetParameters(key, 1, 20, 2); + case WC_LMS_PARM_L1_H20_W4: + return wc_LmsKey_SetParameters(key, 1, 20, 4); + case WC_LMS_PARM_L1_H20_W8: + return wc_LmsKey_SetParameters(key, 1, 20, 8); + case WC_LMS_PARM_L2_H5_W2: + return wc_LmsKey_SetParameters(key, 2, 5, 2); + case WC_LMS_PARM_L2_H5_W4: + return wc_LmsKey_SetParameters(key, 2, 5, 4); + case WC_LMS_PARM_L2_H5_W8: + return wc_LmsKey_SetParameters(key, 2, 5, 8); case WC_LMS_PARM_L2_H10_W2: return wc_LmsKey_SetParameters(key, 2, 10, 2); - case WC_LMS_PARM_L2_H10_W4: return wc_LmsKey_SetParameters(key, 2, 10, 4); - case WC_LMS_PARM_L2_H10_W8: return wc_LmsKey_SetParameters(key, 2, 10, 8); - + case WC_LMS_PARM_L2_H15_W2: + return wc_LmsKey_SetParameters(key, 2, 15, 2); + case WC_LMS_PARM_L2_H15_W4: + return wc_LmsKey_SetParameters(key, 2, 15, 4); + case WC_LMS_PARM_L2_H15_W8: + return wc_LmsKey_SetParameters(key, 2, 15, 8); + case WC_LMS_PARM_L2_H20_W2: + return wc_LmsKey_SetParameters(key, 2, 20, 2); + case WC_LMS_PARM_L2_H20_W4: + return wc_LmsKey_SetParameters(key, 2, 20, 4); + case WC_LMS_PARM_L2_H20_W8: + return wc_LmsKey_SetParameters(key, 2, 20, 8); case WC_LMS_PARM_L3_H5_W2: return wc_LmsKey_SetParameters(key, 3, 5, 2); - case WC_LMS_PARM_L3_H5_W4: return wc_LmsKey_SetParameters(key, 3, 5, 4); - case WC_LMS_PARM_L3_H5_W8: return wc_LmsKey_SetParameters(key, 3, 5, 8); - case WC_LMS_PARM_L3_H10_W4: return wc_LmsKey_SetParameters(key, 3, 10, 4); - + case WC_LMS_PARM_L3_H10_W8: + return wc_LmsKey_SetParameters(key, 3, 10, 8); + case WC_LMS_PARM_L4_H5_W2: + return wc_LmsKey_SetParameters(key, 4, 5, 2); + case WC_LMS_PARM_L4_H5_W4: + return wc_LmsKey_SetParameters(key, 4, 5, 4); case WC_LMS_PARM_L4_H5_W8: return wc_LmsKey_SetParameters(key, 4, 5, 8); - + case WC_LMS_PARM_L4_H10_W4: + return wc_LmsKey_SetParameters(key, 4, 10, 4); + case WC_LMS_PARM_L4_H10_W8: + return wc_LmsKey_SetParameters(key, 4, 10, 8); default: WOLFSSL_MSG("error: invalid LMS parameter set"); break; @@ -507,7 +586,7 @@ void wc_LmsKey_Free(LmsKey* key) * * Returns 0 on success. * */ -int wc_LmsKey_SetWriteCb(LmsKey * key, write_private_key_cb write_cb) +int wc_LmsKey_SetWriteCb(LmsKey * key, wc_lms_write_private_key_cb write_cb) { if (key == NULL || write_cb == NULL) { return BAD_FUNC_ARG; @@ -531,7 +610,7 @@ int wc_LmsKey_SetWriteCb(LmsKey * key, write_private_key_cb write_cb) * * Returns 0 on success. * */ -int wc_LmsKey_SetReadCb(LmsKey * key, read_private_key_cb read_cb) +int wc_LmsKey_SetReadCb(LmsKey * key, wc_lms_read_private_key_cb read_cb) { if (key == NULL || read_cb == NULL) { return BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/ext_xmss.c b/src/wolfcrypt/src/ext_xmss.c index 84498d9..9ce012e 100644 --- a/src/wolfcrypt/src/ext_xmss.c +++ b/src/wolfcrypt/src/ext_xmss.c @@ -307,7 +307,7 @@ void wc_XmssKey_Free(XmssKey* key) * returns BAD_FUNC_ARG when a parameter is NULL. * returns -1 on failure. * */ -int wc_XmssKey_SetWriteCb(XmssKey * key, write_private_key_cb write_cb) +int wc_XmssKey_SetWriteCb(XmssKey * key, wc_xmss_write_private_key_cb write_cb) { if (key == NULL || write_cb == NULL) { return BAD_FUNC_ARG; @@ -336,7 +336,7 @@ int wc_XmssKey_SetWriteCb(XmssKey * key, write_private_key_cb write_cb) * returns BAD_FUNC_ARG when a parameter is NULL. * returns -1 on failure. * */ -int wc_XmssKey_SetReadCb(XmssKey * key, read_private_key_cb read_cb) +int wc_XmssKey_SetReadCb(XmssKey * key, wc_xmss_read_private_key_cb read_cb) { if (key == NULL || read_cb == NULL) { return BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/falcon.c b/src/wolfcrypt/src/falcon.c index 2645db6..04309db 100644 --- a/src/wolfcrypt/src/falcon.c +++ b/src/wolfcrypt/src/falcon.c @@ -75,7 +75,7 @@ int wc_falcon_sign_msg(const byte* in, word32 inLen, { ret = wc_CryptoCb_PqcSign(in, inLen, out, outLen, rng, WC_PQC_SIG_TYPE_FALCON, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; @@ -173,7 +173,7 @@ int wc_falcon_verify_msg(const byte* sig, word32 sigLen, const byte* msg, { ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, res, WC_PQC_SIG_TYPE_FALCON, key); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; @@ -282,7 +282,7 @@ int wc_falcon_init_id(falcon_key* key, const unsigned char* id, int len, key->idLen = len; } - /* Set the maxiumum level here */ + /* Set the maximum level here */ wc_falcon_set_level(key, 5); return ret; @@ -309,7 +309,7 @@ int wc_falcon_init_label(falcon_key* key, const char* label, void* heap, key->labelLen = labelLen; } - /* Set the maxiumum level here */ + /* Set the maximum level here */ wc_falcon_set_level(key, 5); return ret; @@ -469,7 +469,8 @@ static int parse_private_key(const byte* priv, word32 privSz, /* At this point, it is still a PKCS8 private key. */ if ((ret = ToTraditionalInline(priv, &idx, privSz)) < 0) { - return ret; + /* ignore error, did not have PKCS8 header */ + (void)ret; } /* Now it is a octet_string(concat(priv,pub)) */ @@ -846,11 +847,11 @@ int wc_Falcon_PrivateKeyDecode(const byte* input, word32* inOutIdx, pubKey, &pubKeyLen, keytype); if (ret == 0) { if (pubKeyLen == 0) { - ret = wc_falcon_import_private_only(input, inSz, key); + ret = wc_falcon_import_private_key(input, inSz, NULL, 0, key); } else { - ret = wc_falcon_import_private_key(privKey, privKeyLen, - pubKey, pubKeyLen, key); + ret = wc_falcon_import_private_key(input, inSz, pubKey, + pubKeyLen, key); } } return ret; @@ -912,7 +913,7 @@ int wc_Falcon_PublicKeyToDer(falcon_key* key, byte* output, word32 inLen, word32 pubKeyLen = (word32)sizeof(pubKey); int keytype = 0; - if (key == NULL || output == NULL) { + if (key == NULL) { return BAD_FUNC_ARG; } diff --git a/src/wolfcrypt/src/fe_448.c b/src/wolfcrypt/src/fe_448.c index 73853b7..36c6096 100644 --- a/src/wolfcrypt/src/fe_448.c +++ b/src/wolfcrypt/src/fe_448.c @@ -1437,56 +1437,56 @@ void fe448_to_bytes(unsigned char* b, const sword32* a) b[ 0] = (byte)(in0 >> 0); b[ 1] = (byte)(in0 >> 8); b[ 2] = (byte)(in0 >> 16); - b[ 3] = (byte)(in0 >> 24) + ((in1 >> 0) << 4); + b[ 3] = (byte)((in0 >> 24) + ((in1 >> 0) << 4)); b[ 4] = (byte)(in1 >> 4); b[ 5] = (byte)(in1 >> 12); b[ 6] = (byte)(in1 >> 20); b[ 7] = (byte)(in2 >> 0); b[ 8] = (byte)(in2 >> 8); b[ 9] = (byte)(in2 >> 16); - b[10] = (byte)(in2 >> 24) + ((in3 >> 0) << 4); + b[10] = (byte)((in2 >> 24) + ((in3 >> 0) << 4)); b[11] = (byte)(in3 >> 4); b[12] = (byte)(in3 >> 12); b[13] = (byte)(in3 >> 20); b[14] = (byte)(in4 >> 0); b[15] = (byte)(in4 >> 8); b[16] = (byte)(in4 >> 16); - b[17] = (byte)(in4 >> 24) + ((in5 >> 0) << 4); + b[17] = (byte)((in4 >> 24) + ((in5 >> 0) << 4)); b[18] = (byte)(in5 >> 4); b[19] = (byte)(in5 >> 12); b[20] = (byte)(in5 >> 20); b[21] = (byte)(in6 >> 0); b[22] = (byte)(in6 >> 8); b[23] = (byte)(in6 >> 16); - b[24] = (byte)(in6 >> 24) + ((in7 >> 0) << 4); + b[24] = (byte)((in6 >> 24) + ((in7 >> 0) << 4)); b[25] = (byte)(in7 >> 4); b[26] = (byte)(in7 >> 12); b[27] = (byte)(in7 >> 20); b[28] = (byte)(in8 >> 0); b[29] = (byte)(in8 >> 8); b[30] = (byte)(in8 >> 16); - b[31] = (byte)(in8 >> 24) + ((in9 >> 0) << 4); + b[31] = (byte)((in8 >> 24) + ((in9 >> 0) << 4)); b[32] = (byte)(in9 >> 4); b[33] = (byte)(in9 >> 12); b[34] = (byte)(in9 >> 20); b[35] = (byte)(in10 >> 0); b[36] = (byte)(in10 >> 8); b[37] = (byte)(in10 >> 16); - b[38] = (byte)(in10 >> 24) + ((in11 >> 0) << 4); + b[38] = (byte)((in10 >> 24) + ((in11 >> 0) << 4)); b[39] = (byte)(in11 >> 4); b[40] = (byte)(in11 >> 12); b[41] = (byte)(in11 >> 20); b[42] = (byte)(in12 >> 0); b[43] = (byte)(in12 >> 8); b[44] = (byte)(in12 >> 16); - b[45] = (byte)(in12 >> 24) + ((in13 >> 0) << 4); + b[45] = (byte)((in12 >> 24) + ((in13 >> 0) << 4)); b[46] = (byte)(in13 >> 4); b[47] = (byte)(in13 >> 12); b[48] = (byte)(in13 >> 20); b[49] = (byte)(in14 >> 0); b[50] = (byte)(in14 >> 8); b[51] = (byte)(in14 >> 16); - b[52] = (byte)(in14 >> 24) + ((in15 >> 0) << 4); + b[52] = (byte)((in14 >> 24) + ((in15 >> 0) << 4)); b[53] = (byte)(in15 >> 4); b[54] = (byte)(in15 >> 12); b[55] = (byte)(in15 >> 20); @@ -1834,6 +1834,7 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b sword64 t13 = (sword64)a[ 6] * b[ 7]; sword64 t113 = (sword64)a[ 7] * b[ 6]; sword64 t14 = (sword64)a[ 7] * b[ 7]; + sword64 o, t15; t1 += t101; t2 += t102; t2 += t202; t3 += t103; t3 += t203; t3 += t303; @@ -1850,8 +1851,8 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b t11 += t111; t11 += t211; t11 += t311; t12 += t112; t12 += t212; t13 += t113; - sword64 o = t14 >> 28; - sword64 t15 = o; + o = t14 >> 28; + t15 = o; t14 -= o << 28; o = (t0 >> 28); t1 += o; t = o << 28; t0 -= t; o = (t1 >> 28); t2 += o; t = o << 28; t1 -= t; diff --git a/src/wolfcrypt/src/fe_operations.c b/src/wolfcrypt/src/fe_operations.c index 18e2b05..704b455 100644 --- a/src/wolfcrypt/src/fe_operations.c +++ b/src/wolfcrypt/src/fe_operations.c @@ -45,7 +45,7 @@ #elif defined(WOLFSSL_ARMASM) /* Assembly code in fe_armv[78]_x25519.* */ #elif defined(CURVED25519_128BIT) -#include "fe_x25519_128.i" +#include "fe_x25519_128.h" #else #if defined(HAVE_CURVE25519) || \ @@ -58,24 +58,24 @@ t[0]+2^26 t[1]+2^51 t[2]+2^77 t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on context. */ -word64 load_3(const unsigned char *in) +sword64 load_3(const unsigned char *in) { word64 result; result = (word64) in[0]; result |= ((word64) in[1]) << 8; result |= ((word64) in[2]) << 16; - return result; + return (sword64)result; } -word64 load_4(const unsigned char *in) +sword64 load_4(const unsigned char *in) { word64 result; result = (word64) in[0]; result |= ((word64) in[1]) << 8; result |= ((word64) in[2]) << 16; result |= ((word64) in[3]) << 24; - return result; + return (sword64)result; } #endif @@ -170,8 +170,8 @@ int curve25519(byte* q, const byte* n, const byte* p) #endif b &= 1; swap ^= b; - fe_cswap(x2,x3,swap); - fe_cswap(z2,z3,swap); + fe_cswap(x2,x3,(int)swap); + fe_cswap(z2,z3,(int)swap); swap = b; /* montgomery */ @@ -194,8 +194,8 @@ int curve25519(byte* q, const byte* n, const byte* p) fe_mul(z3,x1,z2); fe_mul(z2,tmp1,tmp0); } - fe_cswap(x2,x3,swap); - fe_cswap(z2,z3,swap); + fe_cswap(x2,x3,(int)swap); + fe_cswap(z2,z3,(int)swap); fe_invert(z2,z2); fe_mul(x2,x2,z2); diff --git a/src/wolfcrypt/src/ge_448.c b/src/wolfcrypt/src/ge_448.c index 5ce8ea7..d2033af 100644 --- a/src/wolfcrypt/src/ge_448.c +++ b/src/wolfcrypt/src/ge_448.c @@ -5453,56 +5453,56 @@ void sc448_reduce(byte* b) b[ 0] = (byte)(d[0 ] >> 0); b[ 1] = (byte)(d[0 ] >> 8); b[ 2] = (byte)(d[0 ] >> 16); - b[ 3] = (byte)(d[0 ] >> 24) + ((d[1 ] >> 0) << 4); + b[ 3] = (byte)((d[0 ] >> 24) + ((d[1 ] >> 0) << 4)); b[ 4] = (byte)(d[1 ] >> 4); b[ 5] = (byte)(d[1 ] >> 12); b[ 6] = (byte)(d[1 ] >> 20); b[ 7] = (byte)(d[2 ] >> 0); b[ 8] = (byte)(d[2 ] >> 8); b[ 9] = (byte)(d[2 ] >> 16); - b[10] = (byte)(d[2 ] >> 24) + ((d[3 ] >> 0) << 4); + b[10] = (byte)((d[2 ] >> 24) + ((d[3 ] >> 0) << 4)); b[11] = (byte)(d[3 ] >> 4); b[12] = (byte)(d[3 ] >> 12); b[13] = (byte)(d[3 ] >> 20); b[14] = (byte)(d[4 ] >> 0); b[15] = (byte)(d[4 ] >> 8); b[16] = (byte)(d[4 ] >> 16); - b[17] = (byte)(d[4 ] >> 24) + ((d[5 ] >> 0) << 4); + b[17] = (byte)((d[4 ] >> 24) + ((d[5 ] >> 0) << 4)); b[18] = (byte)(d[5 ] >> 4); b[19] = (byte)(d[5 ] >> 12); b[20] = (byte)(d[5 ] >> 20); b[21] = (byte)(d[6 ] >> 0); b[22] = (byte)(d[6 ] >> 8); b[23] = (byte)(d[6 ] >> 16); - b[24] = (byte)(d[6 ] >> 24) + ((d[7 ] >> 0) << 4); + b[24] = (byte)((d[6 ] >> 24) + ((d[7 ] >> 0) << 4)); b[25] = (byte)(d[7 ] >> 4); b[26] = (byte)(d[7 ] >> 12); b[27] = (byte)(d[7 ] >> 20); b[28] = (byte)(d[8 ] >> 0); b[29] = (byte)(d[8 ] >> 8); b[30] = (byte)(d[8 ] >> 16); - b[31] = (byte)(d[8 ] >> 24) + ((d[9 ] >> 0) << 4); + b[31] = (byte)((d[8 ] >> 24) + ((d[9 ] >> 0) << 4)); b[32] = (byte)(d[9 ] >> 4); b[33] = (byte)(d[9 ] >> 12); b[34] = (byte)(d[9 ] >> 20); b[35] = (byte)(d[10] >> 0); b[36] = (byte)(d[10] >> 8); b[37] = (byte)(d[10] >> 16); - b[38] = (byte)(d[10] >> 24) + ((d[11] >> 0) << 4); + b[38] = (byte)((d[10] >> 24) + ((d[11] >> 0) << 4)); b[39] = (byte)(d[11] >> 4); b[40] = (byte)(d[11] >> 12); b[41] = (byte)(d[11] >> 20); b[42] = (byte)(d[12] >> 0); b[43] = (byte)(d[12] >> 8); b[44] = (byte)(d[12] >> 16); - b[45] = (byte)(d[12] >> 24) + ((d[13] >> 0) << 4); + b[45] = (byte)((d[12] >> 24) + ((d[13] >> 0) << 4)); b[46] = (byte)(d[13] >> 4); b[47] = (byte)(d[13] >> 12); b[48] = (byte)(d[13] >> 20); b[49] = (byte)(d[14] >> 0); b[50] = (byte)(d[14] >> 8); b[51] = (byte)(d[14] >> 16); - b[52] = (byte)(d[14] >> 24) + ((d[15] >> 0) << 4); + b[52] = (byte)((d[14] >> 24) + ((d[15] >> 0) << 4)); b[53] = (byte)(d[15] >> 4); b[54] = (byte)(d[15] >> 12); b[55] = (byte)(d[15] >> 20); @@ -6206,56 +6206,56 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) r[ 0] = (byte)(rd[0 ] >> 0); r[ 1] = (byte)(rd[0 ] >> 8); r[ 2] = (byte)(rd[0 ] >> 16); - r[ 3] = (byte)(rd[0 ] >> 24) + ((rd[1 ] >> 0) << 4); + r[ 3] = (byte)((rd[0 ] >> 24) + ((rd[1 ] >> 0) << 4)); r[ 4] = (byte)(rd[1 ] >> 4); r[ 5] = (byte)(rd[1 ] >> 12); r[ 6] = (byte)(rd[1 ] >> 20); r[ 7] = (byte)(rd[2 ] >> 0); r[ 8] = (byte)(rd[2 ] >> 8); r[ 9] = (byte)(rd[2 ] >> 16); - r[10] = (byte)(rd[2 ] >> 24) + ((rd[3 ] >> 0) << 4); + r[10] = (byte)((rd[2 ] >> 24) + ((rd[3 ] >> 0) << 4)); r[11] = (byte)(rd[3 ] >> 4); r[12] = (byte)(rd[3 ] >> 12); r[13] = (byte)(rd[3 ] >> 20); r[14] = (byte)(rd[4 ] >> 0); r[15] = (byte)(rd[4 ] >> 8); r[16] = (byte)(rd[4 ] >> 16); - r[17] = (byte)(rd[4 ] >> 24) + ((rd[5 ] >> 0) << 4); + r[17] = (byte)((rd[4 ] >> 24) + ((rd[5 ] >> 0) << 4)); r[18] = (byte)(rd[5 ] >> 4); r[19] = (byte)(rd[5 ] >> 12); r[20] = (byte)(rd[5 ] >> 20); r[21] = (byte)(rd[6 ] >> 0); r[22] = (byte)(rd[6 ] >> 8); r[23] = (byte)(rd[6 ] >> 16); - r[24] = (byte)(rd[6 ] >> 24) + ((rd[7 ] >> 0) << 4); + r[24] = (byte)((rd[6 ] >> 24) + ((rd[7 ] >> 0) << 4)); r[25] = (byte)(rd[7 ] >> 4); r[26] = (byte)(rd[7 ] >> 12); r[27] = (byte)(rd[7 ] >> 20); r[28] = (byte)(rd[8 ] >> 0); r[29] = (byte)(rd[8 ] >> 8); r[30] = (byte)(rd[8 ] >> 16); - r[31] = (byte)(rd[8 ] >> 24) + ((rd[9 ] >> 0) << 4); + r[31] = (byte)((rd[8 ] >> 24) + ((rd[9 ] >> 0) << 4)); r[32] = (byte)(rd[9 ] >> 4); r[33] = (byte)(rd[9 ] >> 12); r[34] = (byte)(rd[9 ] >> 20); r[35] = (byte)(rd[10] >> 0); r[36] = (byte)(rd[10] >> 8); r[37] = (byte)(rd[10] >> 16); - r[38] = (byte)(rd[10] >> 24) + ((rd[11] >> 0) << 4); + r[38] = (byte)((rd[10] >> 24) + ((rd[11] >> 0) << 4)); r[39] = (byte)(rd[11] >> 4); r[40] = (byte)(rd[11] >> 12); r[41] = (byte)(rd[11] >> 20); r[42] = (byte)(rd[12] >> 0); r[43] = (byte)(rd[12] >> 8); r[44] = (byte)(rd[12] >> 16); - r[45] = (byte)(rd[12] >> 24) + ((rd[13] >> 0) << 4); + r[45] = (byte)((rd[12] >> 24) + ((rd[13] >> 0) << 4)); r[46] = (byte)(rd[13] >> 4); r[47] = (byte)(rd[13] >> 12); r[48] = (byte)(rd[13] >> 20); r[49] = (byte)(rd[14] >> 0); r[50] = (byte)(rd[14] >> 8); r[51] = (byte)(rd[14] >> 16); - r[52] = (byte)(rd[14] >> 24) + ((rd[15] >> 0) << 4); + r[52] = (byte)((rd[14] >> 24) + ((rd[15] >> 0) << 4)); r[53] = (byte)(rd[15] >> 4); r[54] = (byte)(rd[15] >> 12); r[55] = (byte)(rd[15] >> 20); diff --git a/src/wolfcrypt/src/hash.c b/src/wolfcrypt/src/hash.c index 9c7682f..bc69c3b 100644 --- a/src/wolfcrypt/src/hash.c +++ b/src/wolfcrypt/src/hash.c @@ -145,7 +145,7 @@ enum wc_HashType wc_HashTypeConvert(int hashType) int wc_HashGetOID(enum wc_HashType hash_type) { - int oid = HASH_TYPE_E; /* Default to hash type error */ + int oid = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ switch(hash_type) { case WC_HASH_TYPE_MD2: @@ -317,7 +317,7 @@ enum wc_HashType wc_OidGetHash(int oid) /* Get Hash digest size */ int wc_HashGetDigestSize(enum wc_HashType hash_type) { - int dig_size = HASH_TYPE_E; /* Default to hash type error */ + int dig_size = WC_NO_ERR_TRACE(HASH_TYPE_E); switch(hash_type) { case WC_HASH_TYPE_MD2: @@ -436,7 +436,7 @@ int wc_HashGetDigestSize(enum wc_HashType hash_type) /* Get Hash block size */ int wc_HashGetBlockSize(enum wc_HashType hash_type) { - int block_size = HASH_TYPE_E; /* Default to hash type error */ + int block_size = WC_NO_ERR_TRACE(HASH_TYPE_E); switch (hash_type) { case WC_HASH_TYPE_MD2: @@ -555,7 +555,7 @@ int wc_HashGetBlockSize(enum wc_HashType hash_type) int wc_Hash_ex(enum wc_HashType hash_type, const byte* data, word32 data_len, byte* hash, word32 hash_len, void* heap, int devId) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ int dig_size; /* Validate hash buffer size */ @@ -689,7 +689,7 @@ int wc_Hash(enum wc_HashType hash_type, const byte* data, int wc_HashInit_ex(wc_HashAlg* hash, enum wc_HashType type, void* heap, int devId) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL) return BAD_FUNC_ARG; @@ -801,7 +801,7 @@ int wc_HashInit(wc_HashAlg* hash, enum wc_HashType type) int wc_HashUpdate(wc_HashAlg* hash, enum wc_HashType type, const byte* data, word32 dataSz) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL || (data == NULL && dataSz > 0)) return BAD_FUNC_ARG; @@ -904,7 +904,7 @@ int wc_HashUpdate(wc_HashAlg* hash, enum wc_HashType type, const byte* data, int wc_HashFinal(wc_HashAlg* hash, enum wc_HashType type, byte* out) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL || out == NULL) return BAD_FUNC_ARG; @@ -1007,7 +1007,7 @@ int wc_HashFinal(wc_HashAlg* hash, enum wc_HashType type, byte* out) int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL) return BAD_FUNC_ARG; @@ -1124,7 +1124,7 @@ int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) #ifdef WOLFSSL_HASH_FLAGS int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, word32 flags) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL) return BAD_FUNC_ARG; @@ -1203,7 +1203,7 @@ int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, word32 flags) } int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) { - int ret = HASH_TYPE_E; /* Default to hash type error */ + int ret = WC_NO_ERR_TRACE(HASH_TYPE_E); /* Default to hash type error */ if (hash == NULL) return BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/hmac.c b/src/wolfcrypt/src/hmac.c index 9a80cb1..fb71bf3 100644 --- a/src/wolfcrypt/src/hmac.c +++ b/src/wolfcrypt/src/hmac.c @@ -30,15 +30,13 @@ #ifndef NO_HMAC -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) - +#if FIPS_VERSION3_GE(2,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$b") - #pragma const_seg(".fipsB$b") + #pragma code_seg(".fipsA$g") + #pragma const_seg(".fipsB$g") #endif #endif @@ -64,6 +62,14 @@ #define wc_HmacFinal wc_HmacFinal_Software #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_hmac_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000008 }; + int wolfCrypt_FIPS_HMAC_sanity(void) + { + return 0; + } +#endif int wc_HmacSizeByType(int type) { @@ -237,7 +243,8 @@ int _InitHmac(Hmac* hmac, int type, void* heap) } -int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) +int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, + int allowFlag) { #ifndef WOLFSSL_MAXQ108X byte* ip; @@ -259,7 +266,7 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) return BAD_FUNC_ARG; } -#ifndef HAVE_FIPS +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0) /* if set key has already been run then make sure and free existing */ /* This is for async and PIC32MZ situations, and just normally OK, provided the user calls wc_HmacInit() first. That function is not @@ -277,12 +284,40 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) if (ret != 0) return ret; -#ifdef HAVE_FIPS - if (length < HMAC_FIPS_MIN_KEY) { - WOLFSSL_ERROR_VERBOSE(HMAC_MIN_KEYLEN_E); - return HMAC_MIN_KEYLEN_E; + /* Regarding the password length: + * SP800-107r1 ss 5.3.2 states: "An HMAC key shall have a security strength + * that meets or exceeds the security strength required to protect the data + * over which the HMAC is computed" then refers to SP800-133 for HMAC keys + * generation. + * + * SP800-133r2 ss 6.2.3 states: "When a key is generated from a password, + * the entropy provided (and thus, the maximum security strength that can be + * supported by the generated key) shall be considered to be zero unless the + * password is generated using an approved RBG" + * + * wolfSSL Notes: The statement from SP800-133r2 applies to + * all password lengths. Any human generated password is considered to have + * 0 security strength regardless of length, there is no minimum length that + * is OK or will provide any amount of security strength other than 0. If + * a security strength is required users shall generate random passwords + * using a FIPS approved RBG of sufficient length that any HMAC key + * generated from that password can claim to inherit the needed security + * strength from that input. + */ + + /* In light of the above, Loosen past restriction that limited passwords to + * no less than 14-bytes to allow for shorter Passwords. + * User needs to pass true (non-zero) to override historical behavior that + * prevented use of any password less than 14-bytes. ALL non-RBG generated + * passwords shall inherit a security strength of zero + * (no security strength) + */ + if (!allowFlag) { + if (length < HMAC_FIPS_MIN_KEY) { + WOLFSSL_ERROR_VERBOSE(HMAC_MIN_KEYLEN_E); + return HMAC_MIN_KEYLEN_E; + } } -#endif #ifdef WOLF_CRYPTO_CB hmac->keyRaw = key; /* use buffer directly */ @@ -564,6 +599,16 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) #endif /* WOLFSSL_MAXQ108X */ } +int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) +{ + int allowFlag; + #if defined(HAVE_FIPS) + allowFlag = 0; /* default false for FIPS cases */ + #else + allowFlag = 1; /* default true for all non-FIPS cases */ + #endif + return wc_HmacSetKey_ex(hmac, type, key, length, allowFlag); +} static int HmacKeyInnerHash(Hmac* hmac) { @@ -666,7 +711,7 @@ int wc_HmacUpdate(Hmac* hmac, const byte* msg, word32 length) #ifdef WOLF_CRYPTO_CB if (hmac->devId != INVALID_DEVID) { ret = wc_CryptoCb_Hmac(hmac, hmac->macType, msg, length, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code */ @@ -775,7 +820,7 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) #ifdef WOLF_CRYPTO_CB if (hmac->devId != INVALID_DEVID) { ret = wc_CryptoCb_Hmac(hmac, hmac->macType, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1230,7 +1275,12 @@ int wolfSSL_GetHmacMaxSize(void) ret = wc_HmacInit(myHmac, heap, devId); if (ret == 0) { + #if FIPS_VERSION3_GE(6,0,0) + ret = wc_HmacSetKey_ex(myHmac, type, localSalt, saltSz, + FIPS_ALLOW_SHORT); + #else ret = wc_HmacSetKey(myHmac, type, localSalt, saltSz); + #endif if (ret == 0) ret = wc_HmacUpdate(myHmac, inKey, inKeySz); if (ret == 0) @@ -1311,7 +1361,12 @@ int wolfSSL_GetHmacMaxSize(void) word32 tmpSz = (n == 1) ? 0 : hashSz; word32 left = outSz - outIdx; + #if FIPS_VERSION3_GE(6,0,0) + ret = wc_HmacSetKey_ex(myHmac, type, inKey, inKeySz, + FIPS_ALLOW_SHORT); + #else ret = wc_HmacSetKey(myHmac, type, inKey, inKeySz); + #endif if (ret != 0) break; ret = wc_HmacUpdate(myHmac, tmp, tmpSz); diff --git a/src/wolfcrypt/src/kdf.c b/src/wolfcrypt/src/kdf.c index 55b7ab0..9edf3a5 100644 --- a/src/wolfcrypt/src/kdf.c +++ b/src/wolfcrypt/src/kdf.c @@ -30,15 +30,13 @@ #ifndef NO_KDF -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 5) - +#if FIPS_VERSION3_GE(5,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$m") - #pragma const_seg(".fipsB$m") + #pragma code_seg(".fipsA$h") + #pragma const_seg(".fipsB$h") #endif #endif @@ -56,6 +54,14 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_kdf_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000009 }; + int wolfCrypt_FIPS_KDF_sanity(void) + { + return 0; + } +#endif #if defined(WOLFSSL_HAVE_PRF) && !defined(NO_HMAC) @@ -300,6 +306,16 @@ int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen, { int ret = 0; +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_MSG(" secret"); + WOLFSSL_BUFFER(secret, secLen); + WOLFSSL_MSG(" label"); + WOLFSSL_BUFFER(label, labLen); + WOLFSSL_MSG(" seed"); + WOLFSSL_BUFFER(seed, seedLen); +#endif + + if (useAtLeastSha256) { #ifdef WOLFSSL_SMALL_STACK byte* labelSeed; @@ -344,6 +360,12 @@ int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen, #endif } +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_MSG(" digest"); + WOLFSSL_BUFFER(digest, digLen); + WOLFSSL_MSG_EX("hash_type %d", hash_type); +#endif + return ret; } #endif /* WOLFSSL_HAVE_PRF && !NO_HMAC */ @@ -542,14 +564,14 @@ int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen, const byte* info, word32 infoLen, int digest, void* heap) { int ret = 0; - int idx = 0; - int len; + word32 idx = 0; + size_t len; byte *data; (void)heap; /* okmLen (2) + protocol|label len (1) + info len(1) + protocollen + * labellen + infolen */ - len = 4 + protocolLen + labelLen + infoLen; + len = 4U + protocolLen + labelLen + infoLen; data = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_TMP_BUFFER); if (data == NULL) @@ -637,7 +659,7 @@ typedef union { static int _HashInit(byte hashId, _hash* hash) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hashId) { #ifndef NO_SHA @@ -662,6 +684,9 @@ int _HashInit(byte hashId, _hash* hash) ret = wc_InitSha512(&hash->sha512); break; #endif /* WOLFSSL_SHA512 */ + default: + ret = BAD_FUNC_ARG; + break; } return ret; @@ -671,7 +696,7 @@ static int _HashUpdate(byte hashId, _hash* hash, const byte* data, word32 dataSz) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hashId) { #ifndef NO_SHA @@ -696,6 +721,9 @@ int _HashUpdate(byte hashId, _hash* hash, ret = wc_Sha512Update(&hash->sha512, data, dataSz); break; #endif /* WOLFSSL_SHA512 */ + default: + ret = BAD_FUNC_ARG; + break; } return ret; @@ -704,7 +732,7 @@ int _HashUpdate(byte hashId, _hash* hash, static int _HashFinal(byte hashId, _hash* hash, byte* digest) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); switch (hashId) { #ifndef NO_SHA @@ -729,6 +757,9 @@ int _HashFinal(byte hashId, _hash* hash, byte* digest) ret = wc_Sha512Final(&hash->sha512, digest); break; #endif /* WOLFSSL_SHA512 */ + default: + ret = BAD_FUNC_ARG; + break; } return ret; @@ -936,7 +967,7 @@ static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx, * @param [in] aes AES object to encrypt with. * @return 0 on success. */ -static int wc_srtp_kdf_derive_key(byte* block, byte indexSz, byte label, +static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, byte* key, word32 keySz, Aes* aes) { int i; @@ -1093,9 +1124,9 @@ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, * @return MEMORY_E on dynamic memory allocation failure. * @return 0 on success. */ -int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, +int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, - word32 key2Sz, byte* key3, word32 key3Sz) + word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator) { int ret = 0; byte block[AES_BLOCK_SIZE]; @@ -1105,6 +1136,15 @@ int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, Aes aes[1]; #endif int aes_inited = 0; + int idxLen; + + if (idxLenIndicator == WC_SRTCP_32BIT_IDX) { + idxLen = WC_SRTCP_INDEX_LEN; + } else if (idxLenIndicator == WC_SRTCP_48BIT_IDX) { + idxLen = WC_SRTP_INDEX_LEN; + } else { + return BAD_FUNC_ARG; /* bad or invalid idxLenIndicator */ + } /* Validate parameters. */ if ((key == NULL) || (keySz > AES_256_KEY_SIZE) || (salt == NULL) || @@ -1136,23 +1176,22 @@ int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, /* Calculate first block that can be used in each derivation. */ if (ret == 0) { - wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, WC_SRTCP_INDEX_LEN, - block); + wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, idxLen, block); } /* Calculate first key if required. */ if ((ret == 0) && (key1 != NULL)) { - ret = wc_srtp_kdf_derive_key(block, WC_SRTCP_INDEX_LEN, + ret = wc_srtp_kdf_derive_key(block, idxLen, WC_SRTCP_LABEL_ENCRYPTION, key1, key1Sz, aes); } /* Calculate second key if required. */ if ((ret == 0) && (key2 != NULL)) { - ret = wc_srtp_kdf_derive_key(block, WC_SRTCP_INDEX_LEN, + ret = wc_srtp_kdf_derive_key(block, idxLen, WC_SRTCP_LABEL_MSG_AUTH, key2, key2Sz, aes); } /* Calculate third key if required. */ if ((ret == 0) && (key3 != NULL)) { - ret = wc_srtp_kdf_derive_key(block, WC_SRTCP_INDEX_LEN, + ret = wc_srtp_kdf_derive_key(block, idxLen, WC_SRTCP_LABEL_SALT, key3, key3Sz, aes); } @@ -1164,6 +1203,15 @@ int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, return ret; } +int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, + int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, + word32 key2Sz, byte* key3, word32 key3Sz) +{ + /* The default 32-bit IDX expected by many implementations */ + return wc_SRTCP_KDF_ex(key, keySz, salt, saltSz, kdrIdx, index, + key1, key1Sz, key2, key2Sz, key3, key3Sz, + WC_SRTCP_32BIT_IDX); +} /* Derive key with label using SRTP KDF algorithm. * * SP 800-135 (RFC 3711). @@ -1350,4 +1398,104 @@ int wc_SRTP_KDF_kdr_to_idx(word32 kdr) } #endif /* WC_SRTP_KDF */ +#ifdef WC_KDF_NIST_SP_800_56C +static int wc_KDA_KDF_iteration(const byte* z, word32 zSz, word32 counter, + const byte* fixedInfo, word32 fixedInfoSz, enum wc_HashType hashType, + byte* output) +{ + byte counterBuf[4]; + wc_HashAlg hash; + int ret; + + ret = wc_HashInit(&hash, hashType); + if (ret != 0) + return ret; + c32toa(counter, counterBuf); + ret = wc_HashUpdate(&hash, hashType, counterBuf, 4); + if (ret == 0) { + ret = wc_HashUpdate(&hash, hashType, z, zSz); + } + if (ret == 0 && fixedInfoSz > 0) { + ret = wc_HashUpdate(&hash, hashType, fixedInfo, fixedInfoSz); + } + if (ret == 0) { + ret = wc_HashFinal(&hash, hashType, output); + } + wc_HashFree(&hash, hashType); + return ret; +} + +/** + * \brief Performs the single-step key derivation function (KDF) as specified in + * SP800-56C option 1. + * + * \param [in] z The input keying material. + * \param [in] zSz The size of the input keying material. + * \param [in] fixedInfo The fixed information to be included in the KDF. + * \param [in] fixedInfoSz The size of the fixed information. + * \param [in] derivedSecretSz The desired size of the derived secret. + * \param [in] hashType The hash algorithm to be used in the KDF. + * \param [out] output The buffer to store the derived secret. + * \param [in] outputSz The size of the output buffer. + * + * \return 0 if the KDF operation is successful. + * \return BAD_FUNC_ARG if the input parameters are invalid. + * \return negative error code if the KDF operation fails. + */ +int wc_KDA_KDF_onestep(const byte* z, word32 zSz, const byte* fixedInfo, + word32 fixedInfoSz, word32 derivedSecretSz, enum wc_HashType hashType, + byte* output, word32 outputSz) +{ + byte hashTempBuf[WC_MAX_DIGEST_SIZE]; + word32 counter, outIdx; + int hashOutSz; + int ret; + + if (output == NULL || outputSz < derivedSecretSz) + return BAD_FUNC_ARG; + if (z == NULL || zSz == 0 || (fixedInfoSz > 0 && fixedInfo == NULL)) + return BAD_FUNC_ARG; + if (derivedSecretSz == 0) + return BAD_FUNC_ARG; + + hashOutSz = wc_HashGetDigestSize(hashType); + if (hashOutSz == WC_NO_ERR_TRACE(HASH_TYPE_E)) + return BAD_FUNC_ARG; + + /* According to SP800_56C, table 1, the max input size (max_H_inputBits) + * depends on the HASH algo. The smaller value in the table is (2**64-1)/8. + * This is larger than the possible length using word32 integers. */ + + counter = 1; + outIdx = 0; + ret = 0; + + /* According to SP800_56C the number of iterations shall not be greater than + * 2**32-1. This is not possible using word32 integers.*/ + while (outIdx + hashOutSz <= derivedSecretSz) { + ret = wc_KDA_KDF_iteration(z, zSz, counter, fixedInfo, fixedInfoSz, + hashType, output + outIdx); + if (ret != 0) + break; + counter++; + outIdx += hashOutSz; + } + + if (ret == 0 && outIdx < derivedSecretSz) { + ret = wc_KDA_KDF_iteration(z, zSz, counter, fixedInfo, fixedInfoSz, + hashType, hashTempBuf); + if (ret == 0) { + XMEMCPY(output + outIdx, hashTempBuf, derivedSecretSz - outIdx); + } + ForceZero(hashTempBuf, hashOutSz); + } + + if (ret != 0) { + ForceZero(output, derivedSecretSz); + } + + return ret; +} +#endif /* WC_KDF_NIST_SP_800_56C */ + #endif /* NO_KDF */ diff --git a/src/wolfcrypt/src/logging.c b/src/wolfcrypt/src/logging.c index 43c44a1..de87dbf 100644 --- a/src/wolfcrypt/src/logging.c +++ b/src/wolfcrypt/src/logging.c @@ -126,7 +126,10 @@ THREAD_LS_T void *StackSizeCheck_stackOffsetPointer = 0; /* Set these to default values initially. */ static wolfSSL_Logging_cb log_function = NULL; -static int loggingEnabled = 0; +#ifndef WOLFSSL_LOGGINGENABLED_DEFAULT +#define WOLFSSL_LOGGINGENABLED_DEFAULT 0 +#endif +static int loggingEnabled = WOLFSSL_LOGGINGENABLED_DEFAULT; THREAD_LS_T const char* log_prefix = NULL; #if defined(WOLFSSL_APACHE_MYNEWT) @@ -276,8 +279,11 @@ void WOLFSSL_TIME(int count) #include #endif -static void wolfssl_log(const int logLevel, const char *const logMessage) +static void wolfssl_log(const int logLevel, const char* const file_name, + int line_number, const char* const logMessage) { + (void)file_name; + (void)line_number; if (log_function) log_function(logLevel, logMessage); else { @@ -286,46 +292,103 @@ static void wolfssl_log(const int logLevel, const char *const logMessage) #elif defined(ARDUINO) wolfSSL_Arduino_Serial_Print(logMessage); #elif defined(WOLFSSL_LOG_PRINTF) - printf("%s\n", logMessage); + if (file_name != NULL) + printf("[%s L %d] %s\n", file_name, line_number, logMessage); + else + printf("%s\n", logMessage); #elif defined(THREADX) && !defined(THREADX_NO_DC_PRINTF) - dc_log_printf("%s\n", logMessage); + if (file_name != NULL) + dc_log_printf("[%s L %d] %s\n", file_name, line_number, logMessage); + else + dc_log_printf("%s\n", logMessage); #elif defined(WOLFSSL_DEOS) - printf("%s\r\n", logMessage); + if (file_name != NULL) + printf("[%s L %d] %s\r\n", file_name, line_number, logMessage); + else + printf("%s\r\n", logMessage); #elif defined(MICRIUM) - BSP_Ser_Printf("%s\r\n", logMessage); + if (file_name != NULL) + BSP_Ser_Printf("[%s L %d] %s\r\n", + file_name, line_number, logMessage); + else + BSP_Ser_Printf("%s\r\n", logMessage); #elif defined(WOLFSSL_MDK_ARM) fflush(stdout) ; - printf("%s\n", logMessage); + if (file_name != NULL) + printf("[%s L %d] %s\n", file_name, line_number, logMessage); + else + printf("%s\n", logMessage); fflush(stdout) ; #elif defined(WOLFSSL_UTASKER) fnDebugMsg((char*)logMessage); fnDebugMsg("\r\n"); #elif defined(MQX_USE_IO_OLD) - fprintf(_mqxio_stderr, "%s\n", logMessage); + if (file_name != NULL) + fprintf(_mqxio_stderr, "[%s L %d] %s\n", + file_name, line_number, logMessage); + else + fprintf(_mqxio_stderr, "%s\n", logMessage); #elif defined(WOLFSSL_APACHE_MYNEWT) - LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "%s\n", logMessage); + if (file_name != NULL) + LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "[%s L %d] %s\n", + file_name, line_number, logMessage); + else + LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "%s\n", logMessage); #elif defined(WOLFSSL_ESPIDF) - ESP_LOGI("wolfssl", "%s", logMessage); + if (file_name != NULL) + ESP_LOGI("wolfssl", "[%s L %d] %s", + file_name, line_number, logMessage); + else + ESP_LOGI("wolfssl", "%s", logMessage); #elif defined(WOLFSSL_ZEPHYR) - printk("%s\n", logMessage); + if (file_name != NULL) + printk("[%s L %d] %s\n", file_name, line_number, logMessage); + else + printk("%s\n", logMessage); #elif defined(WOLFSSL_TELIT_M2MB) - M2M_LOG_INFO("%s\n", logMessage); + if (file_name != NULL) + M2M_LOG_INFO("[%s L %d] %s\n", file_name, line_number, logMessage); + else + M2M_LOG_INFO("%s\n", logMessage); #elif defined(WOLFSSL_ANDROID_DEBUG) - __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "%s", logMessage); + if (file_name != NULL) + __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "[%s L %d] %s", + file_name, line_number, logMessage); + else + __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "%s", + logMessage); #elif defined(WOLFSSL_XILINX) - xil_printf("%s\r\n", logMessage); + if (file_name != NULL) + xil_printf("[%s L %d] %s\r\n", file_name, line_number, logMessage); + else + xil_printf("%s\r\n", logMessage); #elif defined(WOLFSSL_LINUXKM) - printk("%s\n", logMessage); + if (file_name != NULL) + printk("[%s L %d] %s\n", file_name, line_number, logMessage); + else + printk("%s\n", logMessage); #elif defined(WOLFSSL_RENESAS_RA6M4) - myprintf("%s\n", logMessage); + if (file_name != NULL) + myprintf("[%s L %d] %s\n", file_name, line_number, logMessage); + else + myprintf("%s\n", logMessage); #elif defined(STACK_SIZE_CHECKPOINT_MSG) && \ defined(HAVE_STACK_SIZE_VERBOSE) && defined(HAVE_STACK_SIZE_VERBOSE_LOG) STACK_SIZE_CHECKPOINT_MSG(logMessage); #else - if (log_prefix != NULL) - fprintf(stderr, "[%s]: %s\n", log_prefix, logMessage); - else - fprintf(stderr, "%s\n", logMessage); + if (log_prefix != NULL) { + if (file_name != NULL) + fprintf(stderr, "[%s]: [%s L %d] %s\n", + log_prefix, file_name, line_number, logMessage); + else + fprintf(stderr, "[%s]: %s\n", log_prefix, logMessage); + } else { + if (file_name != NULL) + fprintf(stderr, "[%s L %d] %s\n", + file_name, line_number, logMessage); + else + fprintf(stderr, "%s\n", logMessage); + } #endif } } @@ -337,6 +400,7 @@ static void wolfssl_log(const int logLevel, const char *const logMessage) #ifndef WOLFSSL_MSG_EX_BUF_SZ #define WOLFSSL_MSG_EX_BUF_SZ 100 #endif +#undef WOLFSSL_MSG_EX /* undo WOLFSSL_DEBUG_CODEPOINTS wrapper */ #ifdef __clang__ /* tell clang argument 1 is format */ __attribute__((__format__ (__printf__, 1, 0))) @@ -351,16 +415,42 @@ void WOLFSSL_MSG_EX(const char* fmt, ...) written = XVSNPRINTF(msg, sizeof(msg), fmt, args); va_end(args); if (written > 0) - wolfssl_log(INFO_LOG , msg); + wolfssl_log(INFO_LOG, NULL, 0, msg); + } +} + +#ifdef WOLFSSL_DEBUG_CODEPOINTS +void WOLFSSL_MSG_EX2(const char *file, int line, const char* fmt, ...) +{ + if (loggingEnabled) { + char msg[WOLFSSL_MSG_EX_BUF_SZ]; + int written; + va_list args; + va_start(args, fmt); + written = XVSNPRINTF(msg, sizeof(msg), fmt, args); + va_end(args); + if (written > 0) + wolfssl_log(INFO_LOG, file, line, msg); } } #endif +#endif + +#undef WOLFSSL_MSG /* undo WOLFSSL_DEBUG_CODEPOINTS wrapper */ void WOLFSSL_MSG(const char* msg) { if (loggingEnabled) - wolfssl_log(INFO_LOG , msg); + wolfssl_log(INFO_LOG, NULL, 0, msg); +} + +#ifdef WOLFSSL_DEBUG_CODEPOINTS +void WOLFSSL_MSG2(const char *file, int line, const char* msg) +{ + if (loggingEnabled) + wolfssl_log(INFO_LOG, file, line, msg); } +#endif #ifndef LINE_LEN #define LINE_LEN 16 @@ -375,7 +465,7 @@ void WOLFSSL_BUFFER(const byte* buffer, word32 length) } if (!buffer) { - wolfssl_log(INFO_LOG, "\tNULL"); + wolfssl_log(INFO_LOG, NULL, 0, "\tNULL"); return; } @@ -405,32 +495,66 @@ void WOLFSSL_BUFFER(const byte* buffer, word32 length) } } - wolfssl_log(INFO_LOG, line); + wolfssl_log(INFO_LOG, NULL, 0, line); buffer += LINE_LEN; buflen -= LINE_LEN; } } - +#undef WOLFSSL_ENTER /* undo WOLFSSL_DEBUG_CODEPOINTS wrapper */ void WOLFSSL_ENTER(const char* msg) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg); - wolfssl_log(ENTER_LOG , buffer); + wolfssl_log(ENTER_LOG, NULL, 0, buffer); } } +#ifdef WOLFSSL_DEBUG_CODEPOINTS +void WOLFSSL_ENTER2(const char *file, int line, const char* msg) +{ + if (loggingEnabled) { + char buffer[WOLFSSL_MAX_ERROR_SZ]; + XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg); + wolfssl_log(ENTER_LOG, file, line, buffer); + } +} +#endif +#undef WOLFSSL_LEAVE /* undo WOLFSSL_DEBUG_CODEPOINTS wrapper */ void WOLFSSL_LEAVE(const char* msg, int ret) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", msg, ret); - wolfssl_log(LEAVE_LOG , buffer); + wolfssl_log(LEAVE_LOG, NULL, 0, buffer); + } +} + +#ifdef WOLFSSL_DEBUG_CODEPOINTS +void WOLFSSL_LEAVE2(const char *file, int line, const char* msg, int ret) +{ + if (loggingEnabled) { + char buffer[WOLFSSL_MAX_ERROR_SZ]; + XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", + msg, ret); + wolfssl_log(LEAVE_LOG, file, line, buffer); } } +#endif + +#ifdef WOLFSSL_DEBUG_CODEPOINTS + /* restore the wrappers */ + #define WOLFSSL_MSG(msg) WOLFSSL_MSG2(__FILE__, __LINE__, msg) + #define WOLFSSL_ENTER(msg) WOLFSSL_ENTER2(__FILE__, __LINE__, msg) + #define WOLFSSL_LEAVE(msg, ret) WOLFSSL_LEAVE2(__FILE__, __LINE__, msg, ret) + #ifdef XVSNPRINTF + #define WOLFSSL_MSG_EX(fmt, args...) \ + WOLFSSL_MSG_EX2(__FILE__, __LINE__, fmt, ## args) + #endif +#endif WOLFSSL_API int WOLFSSL_IS_DEBUG_ON(void) { @@ -714,7 +838,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, while (1) { int ret = wc_PeekErrorNode(0, file, NULL, line); - if (ret == BAD_STATE_E) { + if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) { WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; } @@ -744,7 +868,7 @@ unsigned long wc_GetErrorNodeErr(void) ret = wc_PullErrorNode(NULL, NULL, NULL); if (ret < 0) { - if (ret == BAD_STATE_E) { + if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) { ret = 0; /* no errors in queue */ } else { @@ -1230,7 +1354,9 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, idx = getErrorNodeCurrentIdx(); while (1) { int ret = peekErrorNode(idx, file, NULL, line); - if (ret == BAD_MUTEX_E || ret == BAD_FUNC_ARG || ret == BAD_STATE_E) { + if (ret == WC_NO_ERR_TRACE(BAD_MUTEX_E) || + ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG) || + ret == WC_NO_ERR_TRACE(BAD_STATE_E)) { ERRQ_UNLOCK(); WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; @@ -1263,7 +1389,7 @@ unsigned long wc_GetErrorNodeErr(void) ret = pullErrorNode(NULL, NULL, NULL); if (ret < 0) { - if (ret == BAD_STATE_E) { + if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) { ret = 0; /* no errors in queue */ } else { @@ -1483,7 +1609,7 @@ void WOLFSSL_ERROR(int error) #endif { #ifdef WOLFSSL_ASYNC_CRYPT - if (error != WC_PENDING_E) + if (error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { char buffer[WOLFSSL_MAX_ERROR_SZ]; @@ -1501,7 +1627,8 @@ void WOLFSSL_ERROR(int error) #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) /* If running in compatibility mode do not add want read and want right to error queue */ - if (error != WANT_READ && error != WANT_WRITE) { + if (error != WC_NO_ERR_TRACE(WANT_READ) && + error != WC_NO_ERR_TRACE(WANT_WRITE)) { #endif if (error < 0) error = error - (2 * error); /* get absolute value */ @@ -1531,7 +1658,7 @@ void WOLFSSL_ERROR(int error) #ifdef DEBUG_WOLFSSL if (loggingEnabled) - wolfssl_log(ERROR_LOG , buffer); + wolfssl_log(ERROR_LOG, NULL, 0, buffer); #endif } } @@ -1540,7 +1667,7 @@ void WOLFSSL_ERROR_MSG(const char* msg) { #ifdef DEBUG_WOLFSSL if (loggingEnabled) - wolfssl_log(ERROR_LOG , msg); + wolfssl_log(ERROR_LOG, NULL, 0, msg); #else (void)msg; #endif diff --git a/src/wolfcrypt/src/memory.c b/src/wolfcrypt/src/memory.c index 4b068ce..d9958a9 100644 --- a/src/wolfcrypt/src/memory.c +++ b/src/wolfcrypt/src/memory.c @@ -38,6 +38,16 @@ Possible memory options: * NO_WOLFSSL_MEMORY: Disables wolf memory callback support. When not defined settings.h defines USE_WOLFSSL_MEMORY. * WOLFSSL_STATIC_MEMORY: Turns on the use of static memory buffers and functions. This allows for using static memory instead of dynamic. + * WOLFSSL_STATIC_MEMORY_LEAN: Requires WOLFSSL_STATIC_MEMORY be defined. + * Uses smaller type sizes for structs + * requiring that memory pool sizes be less + * then 65k and limits features available like + * IO buffers to reduce footprint size. + * WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK: + * Enables option to register a debugging + * callback function, useful for + * WOLFSSL_STATIC_MEMORY builds where XMALLOC + * and XFREE are not user defined. * WOLFSSL_STATIC_ALIGN: Define defaults to 16 to indicate static memory alignment. * HAVE_IO_POOL: Enables use of static thread safe memory pool for input/output buffers. * XMALLOC_OVERRIDE: Allows override of the XMALLOC, XFREE and XREALLOC macros. @@ -514,20 +524,39 @@ void* wolfSSL_Realloc(void *ptr, size_t size) struct wc_Memory { byte* buffer; struct wc_Memory* next; +#ifdef WOLFSSL_STATIC_MEMORY_LEAN + /* lean static memory is assumed to be under 65k */ + word16 sz; +#else word32 sz; +#endif +#ifdef WOLFSSL_DEBUG_MEMORY + word16 szUsed; +#endif }; +#ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK +static DebugMemoryCb DebugCb = NULL; + +/* Used to set a debug memory callback. Helpful in cases where + * printf is not available. */ +void wolfSSL_SetDebugMemoryCb(DebugMemoryCb cb) +{ + DebugCb = cb; +} +#endif + /* returns amount of memory used on success. On error returns negative value wc_Memory** list is the list that new buckets are prepended to */ -static int create_memory_buckets(byte* buffer, word32 bufSz, - word32 buckSz, word32 buckNum, wc_Memory** list) { - word32 i; +static int wc_create_memory_buckets(byte* buffer, word32 bufSz, + word32 buckSz, byte buckNum, wc_Memory** list) { byte* pt = buffer; int ret = 0; - word32 memSz = (word32)sizeof(wc_Memory); - word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1); + byte memSz = (byte)sizeof(wc_Memory); + word16 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1); + word16 i; /* if not enough space available for bucket size then do not try */ if (buckSz + memSz + padSz > bufSz) { @@ -542,6 +571,12 @@ static int create_memory_buckets(byte* buffer, word32 bufSz, mem->buffer = (byte*)pt + padSz + memSz; mem->next = NULL; + #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK + if (DebugCb) { + DebugCb(buckSz, buckSz, WOLFSSL_DEBUG_MEMORY_INIT, 0); + } + #endif + /* add the newly created struct to front of list */ if (*list == NULL) { *list = mem; @@ -562,41 +597,126 @@ static int create_memory_buckets(byte* buffer, word32 bufSz, return ret; } -int wolfSSL_init_memory_heap(WOLFSSL_HEAP* heap) +static int wc_partition_static_memory(byte* buffer, word32 sz, int flag, + WOLFSSL_HEAP* heap) { - word32 wc_MemSz[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS }; - word32 wc_Dist[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST }; + word32 ava = sz; + byte* pt = buffer; + int ret = 0; + byte memSz = (word32)sizeof(wc_Memory); + byte padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1); - if (heap == NULL) { - return BAD_FUNC_ARG; + WOLFSSL_ENTER("wc_partition_static_memory"); + + /* align pt */ + while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) { + *pt = 0x00; + pt++; + ava--; } +#ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "Allocated %d bytes for static memory @ %p\n", ava, pt); +#endif + + /* divide into chunks of memory and add them to available list */ + while (ava >= (word32)(heap->sizeList[0] + padSz + memSz)) { + #ifndef WOLFSSL_STATIC_MEMORY_LEAN + /* creating only IO buffers from memory passed in, max TLS is 16k */ + if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { + if ((ret = wc_create_memory_buckets(pt, ava, + WOLFMEM_IO_SZ, 1, &(heap->io))) < 0) { + WOLFSSL_LEAVE("wc_partition_static_memory", ret); + return ret; + } + + /* check if no more room left for creating IO buffers */ + if (ret == 0) { + break; + } + + /* advance pointer in buffer for next buckets and keep track + of how much memory is left available */ + pt += ret; + ava -= ret; + } + else + #endif + { + int i; + /* start at largest and move to smaller buckets */ + for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) { + if ((word32)(heap->sizeList[i] + padSz + memSz) <= ava) { + if ((ret = wc_create_memory_buckets(pt, ava, + heap->sizeList[i], heap->distList[i], + &(heap->ava[i]))) < 0) { + WOLFSSL_LEAVE("wc_partition_static_memory", ret); + return ret; + } + + /* advance pointer in buffer for next buckets and keep track + of how much memory is left available */ + pt += ret; + ava -= ret; + } + } + } + } + + (void)flag; + return 1; +} + +static int wc_init_memory_heap(WOLFSSL_HEAP* heap, unsigned int listSz, + const unsigned int* sizeList, const unsigned int* distList) +{ + unsigned int i; + XMEMSET(heap, 0, sizeof(WOLFSSL_HEAP)); - XMEMCPY(heap->sizeList, wc_MemSz, sizeof(wc_MemSz)); - XMEMCPY(heap->distList, wc_Dist, sizeof(wc_Dist)); + /* avoid XMEMCPY for LEAN static memory build */ + for (i = 0; i < listSz; i++) { + heap->sizeList[i] = sizeList[i]; + } + + for (i = 0; i < listSz; i++) { + heap->distList[i] = distList[i]; + } +#ifndef SINGLE_THREADED if (wc_InitMutex(&(heap->memory_mutex)) != 0) { WOLFSSL_MSG("Error creating heap memory mutex"); return BAD_MUTEX_E; } +#endif return 0; } -int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, - unsigned char* buf, unsigned int sz, int flag, int maxSz) +int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint, + unsigned int listSz, const unsigned int* sizeList, + const unsigned int* distList, unsigned char* buf, + unsigned int sz, int flag, int maxSz) { + WOLFSSL_HEAP* heap = NULL; + WOLFSSL_HEAP_HINT* hint = NULL; + word16 idx = 0; int ret; - WOLFSSL_HEAP* heap; - WOLFSSL_HEAP_HINT* hint; - word32 idx = 0; - if (pHint == NULL || buf == NULL) { + WOLFSSL_ENTER("wc_LoadStaticMemory_ex"); + + if (pHint == NULL || buf == NULL || sizeList == NULL || distList == NULL) { return BAD_FUNC_ARG; } + /* Cap the listSz to the actual number of items allocated in the list. */ + if (listSz > WOLFMEM_MAX_BUCKETS) { + WOLFSSL_MSG("Truncating the list of memory buckets"); + listSz = WOLFMEM_MAX_BUCKETS; + } + if ((sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT)) > sz - idx) { + WOLFSSL_MSG("Not enough memory for partition tracking"); return BUFFER_E; /* not enough memory for structures */ } @@ -607,7 +727,7 @@ int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, hint = (WOLFSSL_HEAP_HINT*)(buf + idx); idx += sizeof(WOLFSSL_HEAP_HINT); - ret = wolfSSL_init_memory_heap(heap); + ret = wc_init_memory_heap(heap, listSz, sizeList, distList); if (ret != 0) { return ret; } @@ -627,12 +747,13 @@ int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, heap = hint->memory; } - ret = wolfSSL_load_static_memory(buf + idx, sz - idx, flag, heap); + ret = wc_partition_static_memory(buf + idx, sz - idx, flag, heap); if (ret != 1) { WOLFSSL_MSG("Error partitioning memory"); - return -1; + return MEMORY_E; } +#ifndef WOLFSSL_STATIC_MEMORY_LEAN /* determine what max applies too */ if ((flag & WOLFMEM_IO_POOL) || (flag & WOLFMEM_IO_POOL_FIXED)) { heap->maxIO = maxSz; @@ -640,85 +761,44 @@ int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, else { /* general memory used in handshakes */ heap->maxHa = maxSz; } - heap->flag |= flag; +#endif *pHint = hint; (void)maxSz; - return 0; } -int wolfSSL_load_static_memory(byte* buffer, word32 sz, int flag, - WOLFSSL_HEAP* heap) +int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, + unsigned char* buf, unsigned int sz, int flag, int maxSz) { - word32 ava = sz; - byte* pt = buffer; - int ret = 0; - word32 memSz = (word32)sizeof(wc_Memory); - word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1); - - WOLFSSL_ENTER("wolfSSL_load_static_memory"); - - if (buffer == NULL) { - return BAD_FUNC_ARG; - } - - /* align pt */ - while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) { - *pt = 0x00; - pt++; - ava--; - } - -#ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Allocated %d bytes for static memory @ %p\n", ava, pt); +#ifdef WOLFSSL_LEAN_STATIC_PSK + word16 sizeList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS }; + byte distList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST }; +#else + word32 sizeList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS }; + word32 distList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST }; #endif + int ret = 0; - /* divide into chunks of memory and add them to available list */ - while (ava >= (heap->sizeList[0] + padSz + memSz)) { - /* creating only IO buffers from memory passed in, max TLS is 16k */ - if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { - if ((ret = create_memory_buckets(pt, ava, - WOLFMEM_IO_SZ, 1, &(heap->io))) < 0) { - WOLFSSL_LEAVE("wolfSSL_load_static_memory", ret); - return ret; - } + WOLFSSL_ENTER("wc_LoadStaticMemory"); + ret = wc_LoadStaticMemory_ex(pHint, + WOLFMEM_DEF_BUCKETS, sizeList, distList, + buf, sz, flag, maxSz); + WOLFSSL_LEAVE("wc_LoadStaticMemory", ret); + return ret; +} - /* check if no more room left for creating IO buffers */ - if (ret == 0) { - break; - } - /* advance pointer in buffer for next buckets and keep track - of how much memory is left available */ - pt += ret; - ava -= ret; - } - else { - int i; - /* start at largest and move to smaller buckets */ - for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) { - if ((heap->sizeList[i] + padSz + memSz) <= ava) { - if ((ret = create_memory_buckets(pt, ava, heap->sizeList[i], - heap->distList[i], &(heap->ava[i]))) < 0) { - WOLFSSL_LEAVE("wolfSSL_load_static_memory", ret); - return ret; - } - - /* advance pointer in buffer for next buckets and keep track - of how much memory is left available */ - pt += ret; - ava -= ret; - } - } - } +void wc_UnloadStaticMemory(WOLFSSL_HEAP_HINT* heap) +{ + WOLFSSL_ENTER("wc_UnloadStaticMemory"); + if (heap != NULL && heap->memory != NULL) { + wc_FreeMutex(&heap->memory->memory_mutex); } - - return 1; } - +#ifndef WOLFSSL_STATIC_MEMORY_LEAN /* returns the size of management memory needed for each bucket. * This is memory that is used to keep track of and align memory buckets. */ int wolfSSL_MemoryPaddingSz(void) @@ -731,28 +811,34 @@ int wolfSSL_MemoryPaddingSz(void) /* Used to calculate memory size for optimum use with buckets. returns the suggested size rounded down to the nearest bucket. */ -int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag) +int wolfSSL_StaticBufferSz_ex(unsigned int listSz, + const unsigned int *sizeList, const unsigned int *distList, + byte* buffer, word32 sz, int flag) { - word32 bucketSz[WOLFMEM_MAX_BUCKETS] = {WOLFMEM_BUCKETS}; - word32 distList[WOLFMEM_MAX_BUCKETS] = {WOLFMEM_DIST}; - word32 ava = sz; byte* pt = buffer; word32 memSz = (word32)sizeof(wc_Memory); word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1); - WOLFSSL_ENTER("wolfSSL_static_size"); + WOLFSSL_ENTER("wolfSSL_StaticBufferSz_ex"); - if (buffer == NULL) { + if (buffer == NULL || sizeList == NULL || distList == NULL) { return BAD_FUNC_ARG; } + /* Cap the listSz to the actual number of items allocated in the list. */ + if (listSz > WOLFMEM_MAX_BUCKETS) { + WOLFSSL_MSG("Truncating the list of memory buckets"); + listSz = WOLFMEM_MAX_BUCKETS; + } + /* align pt */ while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) { pt++; ava--; } +#ifndef WOLFSSL_STATIC_MEMORY_LEAN /* creating only IO buffers from memory passed in, max TLS is 16k */ if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { if (ava < (memSz + padSz + WOLFMEM_IO_SZ)) { @@ -761,29 +847,44 @@ int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag) ava = ava % (memSz + padSz + WOLFMEM_IO_SZ); } - else { + else +#endif + { int i, k; - if (ava < (bucketSz[0] + padSz + memSz)) { + if (ava < (sizeList[0] + padSz + memSz)) { return 0; /* not enough room for even one bucket */ } - while ((ava >= (bucketSz[0] + padSz + memSz)) && (ava > 0)) { + while ((ava >= (sizeList[0] + padSz + memSz)) && (ava > 0)) { /* start at largest and move to smaller buckets */ - for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) { + for (i = (listSz - 1); i >= 0; i--) { for (k = distList[i]; k > 0; k--) { - if ((bucketSz[i] + padSz + memSz) <= ava) { - ava -= bucketSz[i] + padSz + memSz; + if ((sizeList[i] + padSz + memSz) <= ava) { + ava -= sizeList[i] + padSz + memSz; } } } } } + WOLFSSL_LEAVE("wolfSSL_StaticBufferSz_ex", sz - ava); return sz - ava; /* round down */ } +/* Calls wolfSSL_StaticBufferSz_ex with the static memory pool config + * used by wolfSSL by default. */ +int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag) +{ + word32 bucketSz[WOLFMEM_DEF_BUCKETS] = {WOLFMEM_BUCKETS}; + word32 distList[WOLFMEM_DEF_BUCKETS] = {WOLFMEM_DIST}; + + return wolfSSL_StaticBufferSz_ex(WOLFMEM_DEF_BUCKETS, bucketSz, distList, + buffer, sz, flag); +} + + int FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io) { WOLFSSL_MSG("Freeing fixed IO buffer"); @@ -855,6 +956,32 @@ int wolfSSL_GetMemStats(WOLFSSL_HEAP* heap, WOLFSSL_MEM_STATS* stats) return 1; } +#endif /* !WOLFSSL_STATIC_MEMORY_LEAN */ + + +/* global heap hint to fall back on when no heap hint is passed to + * XMALLOC/XFREE + * NOT thread safe, should be set once before any expected XMALLOC XFREE calls + */ +static void* globalHeapHint = NULL; + + +/* Used to set a new global heap hint. Returns a pointer to the current global + * heap hint before being set. */ +void* wolfSSL_SetGlobalHeapHint(void* heap) +{ + void *oldHint = globalHeapHint; + + globalHeapHint = heap; + return oldHint; +} + + +/* returns a pointer to the current global heap hint */ +void* wolfSSL_GetGlobalHeapHint(void) +{ + return globalHeapHint; +} #ifdef WOLFSSL_DEBUG_MEMORY @@ -875,7 +1002,7 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) #endif /* if no heap hint then use dynamic memory*/ - if (heap == NULL) { + if (heap == NULL && globalHeapHint == NULL) { #ifdef WOLFSSL_HEAP_TEST /* allow using malloc for creating ctx and method */ if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD || @@ -910,13 +1037,24 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) } else { WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap; - WOLFSSL_HEAP* mem = hint->memory; + WOLFSSL_HEAP* mem; + + if (hint == NULL) { + hint = (WOLFSSL_HEAP_HINT*)globalHeapHint; + #ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "(Using global heap hint %p) ", hint); + #endif + } + mem = hint->memory; + #ifndef SINGLE_THREADED if (wc_LockMutex(&(mem->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); return NULL; } + #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* case of using fixed IO buffers */ if (mem->flag & WOLFMEM_IO_POOL_FIXED && (type == DYNAMIC_TYPE_OUT_BUFFER || @@ -928,7 +1066,10 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) pt = hint->inBuf; } } - else { + else + #endif + { + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* check if using IO pool flag */ if (mem->flag & WOLFMEM_IO_POOL && (type == DYNAMIC_TYPE_OUT_BUFFER || @@ -938,6 +1079,7 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) mem->io = pt->next; } } + #endif /* general static memory */ if (pt == NULL) { @@ -950,7 +1092,7 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) } #ifdef WOLFSSL_DEBUG_STATIC_MEMORY else { - fprintf(stderr, "Size: %ld, Empty: %d\n", size, + fprintf(stderr, "Size: %lu, Empty: %d\n", (unsigned long) size, mem->sizeList[i]); } #endif @@ -960,14 +1102,21 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) } if (pt != NULL) { - mem->inUse += pt->sz; + #ifndef WOLFSSL_STATIC_MEMORY_LEAN mem->alloc += 1; + #endif res = pt->buffer; #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Alloc: %p -> %u at %s:%d\n", pt->buffer, pt->sz, func, line); + pt->szUsed = size; + fprintf(stderr, "Alloc: %p -> %lu at %s:%d\n", pt->buffer, size, func, line); #endif - + #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK + if (DebugCb) { + DebugCb(size, pt->sz, WOLFSSL_DEBUG_MEMORY_ALLOC, type); + } + #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* keep track of connection statistics if flag is set */ if (mem->flag & WOLFMEM_TRACK_STATS) { WOLFSSL_MEM_CONN_STATS* stats = hint->stats; @@ -983,15 +1132,24 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) stats->totalAlloc++; } } + #endif } else { WOLFSSL_MSG("ERROR ran out of static memory"); + res = NULL; #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Looking for %lu bytes at %s:%d\n", size, func, line); + fprintf(stderr, "Looking for %lu bytes at %s:%d\n", (unsigned long) size, func, + line); + #endif + #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK + if (DebugCb) { + DebugCb(size, 0, WOLFSSL_DEBUG_MEMORY_FAIL, type); + } #endif } - + #ifndef SINGLE_THREADED wc_UnLockMutex(&(mem->memory_mutex)); + #endif } #ifdef WOLFSSL_MALLOC_CHECK @@ -1030,7 +1188,7 @@ void wolfSSL_Free(void *ptr, void* heap, int type) } #endif - if (heap == NULL) { + if (heap == NULL && globalHeapHint == NULL) { #ifdef WOLFSSL_HEAP_TEST /* allow using malloc for creating ctx and method */ if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD || @@ -1055,16 +1213,31 @@ void wolfSSL_Free(void *ptr, void* heap, int type) } else { WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap; - WOLFSSL_HEAP* mem = hint->memory; + WOLFSSL_HEAP* mem; word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1); + if (hint == NULL) { + hint = (WOLFSSL_HEAP_HINT*)globalHeapHint; + #ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "(Using global heap hint %p) ", hint); + #endif + } + mem = hint->memory; + if (mem == NULL) { + WOLFSSL_MSG("Bad hint pointer to memory"); + return; + } + /* get memory struct and add it to available list */ pt = (wc_Memory*)((byte*)ptr - sizeof(wc_Memory) - padSz); + #ifndef SINGLE_THREADED if (wc_LockMutex(&(mem->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); return; } + #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* case of using fixed IO buffers */ if (mem->flag & WOLFMEM_IO_POOL_FIXED && (type == DYNAMIC_TYPE_OUT_BUFFER || @@ -1078,22 +1251,38 @@ void wolfSSL_Free(void *ptr, void* heap, int type) pt->next = mem->io; mem->io = pt; } - else { /* general memory free */ + else + #endif + { /* general memory free */ for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) { if (pt->sz == mem->sizeList[i]) { pt->next = mem->ava[i]; mem->ava[i] = pt; + + #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK + if (DebugCb) { + #ifdef WOLFSSL_DEBUG_MEMORY + DebugCb(pt->szUsed, pt->sz, WOLFSSL_DEBUG_MEMORY_FREE, type); + #else + DebugCb(pt->sz, pt->sz, WOLFSSL_DEBUG_MEMORY_FREE, type); + #endif + } + #endif break; } } } + #ifndef WOLFSSL_STATIC_MEMORY_LEAN mem->inUse -= pt->sz; mem->frAlc += 1; + #endif #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Free: %p -> %u at %s:%d\n", pt->buffer, pt->sz, func, line); + fprintf (stderr, "Free: %p -> %u at %s:%d\n", pt->buffer, + pt->szUsed, func, line); #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* keep track of connection statistics if flag is set */ if (mem->flag & WOLFMEM_TRACK_STATS) { WOLFSSL_MEM_CONN_STATS* stats = hint->stats; @@ -1112,7 +1301,10 @@ void wolfSSL_Free(void *ptr, void* heap, int type) stats->totalFr++; } } + #endif + #ifndef SINGLE_THREADED wc_UnLockMutex(&(mem->memory_mutex)); + #endif } } @@ -1121,6 +1313,7 @@ void wolfSSL_Free(void *ptr, void* heap, int type) (void)type; } +#ifndef WOLFSSL_NO_REALLOC #ifdef WOLFSSL_DEBUG_MEMORY void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type, const char* func, unsigned int line) #else @@ -1138,7 +1331,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) } #endif - if (heap == NULL) { + if (heap == NULL && globalHeapHint == NULL) { #ifdef WOLFSSL_HEAP_TEST WOLFSSL_MSG("ERROR null heap hint passed in to XREALLOC"); #endif @@ -1150,9 +1343,17 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) } else { WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap; - WOLFSSL_HEAP* mem = hint->memory; + WOLFSSL_HEAP* mem; word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1); + if (hint == NULL) { + hint = (WOLFSSL_HEAP_HINT*)globalHeapHint; + #ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "(Using global heap hint %p) ", hint); + #endif + } + mem = hint->memory; + if (ptr == NULL) { #ifdef WOLFSSL_DEBUG_MEMORY return wolfSSL_Malloc(size, heap, type, func, line); @@ -1160,12 +1361,14 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) return wolfSSL_Malloc(size, heap, type); #endif } - + #ifndef SINGLE_THREADED if (wc_LockMutex(&(mem->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); return NULL; } + #endif + #ifndef WOLFSSL_STATIC_MEMORY_LEAN /* case of using fixed IO buffers or IO pool */ if (((mem->flag & WOLFMEM_IO_POOL)||(mem->flag & WOLFMEM_IO_POOL_FIXED)) && (type == DYNAMIC_TYPE_OUT_BUFFER || @@ -1178,7 +1381,9 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) } res = pt->buffer; } - else { + else + #endif + { /* general memory */ for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) { if ((word32)size <= mem->sizeList[i]) { @@ -1191,30 +1396,40 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) } if (pt != NULL && res == NULL) { + word32 prvSz; + res = pt->buffer; /* copy over original information and free ptr */ - word32 prvSz = ((wc_Memory*)((byte*)ptr - padSz - + prvSz = ((wc_Memory*)((byte*)ptr - padSz - sizeof(wc_Memory)))->sz; prvSz = (prvSz > pt->sz)? pt->sz: prvSz; XMEMCPY(pt->buffer, ptr, prvSz); + #ifndef WOLFSSL_STATIC_MEMORY_LEAN mem->inUse += pt->sz; mem->alloc += 1; + #endif /* free memory that was previously being used */ + #ifndef SINGLE_THREADED wc_UnLockMutex(&(mem->memory_mutex)); + #endif wolfSSL_Free(ptr, heap, type #ifdef WOLFSSL_DEBUG_MEMORY , func, line #endif ); + #ifndef SINGLE_THREADED if (wc_LockMutex(&(mem->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); return NULL; } + #endif } } + #ifndef SINGLE_THREADED wc_UnLockMutex(&(mem->memory_mutex)); + #endif } #ifdef WOLFSSL_MALLOC_CHECK @@ -1231,7 +1446,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) return res; } #endif /* WOLFSSL_STATIC_MEMORY */ - +#endif /* WOLFSSL_NO_REALLOC */ #endif /* USE_WOLFSSL_MEMORY */ diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index af5f09a..10f733b 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -1001,6 +1001,25 @@ WC_MISC_STATIC WC_INLINE word32 HashObject(const byte* o, word32 len, #endif /* WOLFCRYPT_ONLY && !NO_HASH_WRAPPER && * (!NO_SESSION_CACHE || HAVE_SESSION_TICKET) */ +WC_MISC_STATIC WC_INLINE char* CopyString(const char* src, int srcLen, + void* heap, int type) { + char* dst = NULL; + + if (src == NULL) + return NULL; + + if (srcLen <= 0) + srcLen = (int)XSTRLEN(src); + + dst = (char*)XMALLOC((size_t)srcLen + 1, heap, type); + if (dst != NULL) { + XMEMCPY(dst, src, (size_t)srcLen); + dst[srcLen] = '\0'; + } + + return dst; +} + #endif /* !WOLFSSL_MISC_INCLUDED && !NO_INLINE */ #endif /* WOLF_CRYPT_MISC_C */ diff --git a/src/wolfcrypt/src/pkcs12.c b/src/wolfcrypt/src/pkcs12.c index 123b2e9..ef111a6 100644 --- a/src/wolfcrypt/src/pkcs12.c +++ b/src/wolfcrypt/src/pkcs12.c @@ -130,15 +130,22 @@ typedef struct WC_PKCS12_ATTRIBUTE { WC_PKCS12* wc_PKCS12_new(void) +{ + return wc_PKCS12_new_ex(NULL); +} + + +WC_PKCS12* wc_PKCS12_new_ex(void* heap) { WC_PKCS12* pkcs12 = (WC_PKCS12*)XMALLOC(sizeof(WC_PKCS12), - NULL, DYNAMIC_TYPE_PKCS); + heap, DYNAMIC_TYPE_PKCS); if (pkcs12 == NULL) { WOLFSSL_MSG("Memory issue when creating WC_PKCS12 struct"); return NULL; } XMEMSET(pkcs12, 0, sizeof(WC_PKCS12)); + pkcs12->heap = heap; return pkcs12; } @@ -202,7 +209,7 @@ void wc_PKCS12_free(WC_PKCS12* pkcs12) } #endif - XFREE(pkcs12, NULL, DYNAMIC_TYPE_PKCS); + XFREE(pkcs12, heap, DYNAMIC_TYPE_PKCS); } @@ -290,7 +297,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, #ifdef ASN_BER_TO_DER if (pkcs12->indefinite) { if (wc_BerToDer(input, safe->dataSz, NULL, - &pkcs12->safeDersz) != LENGTH_ONLY_E) { + &pkcs12->safeDersz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Not BER sequence"); return ASN_PARSE_E; } @@ -704,7 +711,7 @@ int wc_d2i_PKCS12(const byte* der, word32 derSz, WC_PKCS12* pkcs12) #ifdef ASN_BER_TO_DER if (size == 0) { if (wc_BerToDer(der, totalSz, NULL, - (word32*)&size) != LENGTH_ONLY_E) { + (word32*)&size) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Not BER sequence"); return ASN_PARSE_E; } @@ -1119,8 +1126,8 @@ static WARN_UNUSED_RESULT int freeDecCertList(WC_DerCertList** list, while (current != NULL) { InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap); - if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL) == 0) { - if (wc_CheckPrivateKeyCert(*pkey, *pkeySz, DeCert) == 1) { + if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL) == 0) { + if (wc_CheckPrivateKeyCert(*pkey, *pkeySz, DeCert, 0) == 1) { WOLFSSL_MSG("Key Pair found"); *cert = current->buffer; *certSz = current->bufferSz; @@ -1819,7 +1826,7 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, ret = UnTraditionalEnc(key, keySz, pkcs8Key, &sz, pass, passSz, vPKCS, vAlgo, NULL, 0, itt, rng, heap); } - if (ret == LENGTH_ONLY_E) { + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { *outSz = sz + MAX_LENGTH_SZ + 1; return LENGTH_ONLY_E; } @@ -1876,7 +1883,7 @@ static int wc_PKCS12_create_key_bag(WC_PKCS12* pkcs12, WC_RNG* rng, /* get max size for shrouded key */ ret = wc_PKCS12_shroud_key(pkcs12, rng, NULL, &length, key, keySz, algo, pass, passSz, iter); - if (ret != LENGTH_ONLY_E && ret < 0) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E) && ret < 0) { return ret; } @@ -2085,7 +2092,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, encSz = contentSz; if ((ret = EncryptContent(NULL, contentSz, NULL, &encSz, pass, passSz, vPKCS, vAlgo, NULL, 0, iter, rng, heap)) < 0) { - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } } @@ -2275,7 +2282,7 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, /* get max size for key bag */ ret = wc_PKCS12_create_key_bag(pkcs12, rng, NULL, &keyBufSz, key, keySz, algo, iter, pass, (int)passSz); - if (ret != LENGTH_ONLY_E && ret < 0) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E) && ret < 0) { WOLFSSL_MSG("Error getting key bag size"); return NULL; } @@ -2312,7 +2319,7 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, #endif ret = wc_PKCS12_encrypt_content(pkcs12, rng, NULL, keyCiSz, NULL, keyBufSz, algo, pass, (int)passSz, iter, WC_PKCS12_DATA); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { XFREE(keyBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_MSG("Error getting key encrypt content size"); return NULL; @@ -2397,7 +2404,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, /* get max size of buffer needed */ ret = wc_PKCS12_create_cert_bag(pkcs12, NULL, &certBufSz, cert, certSz); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return NULL; } @@ -2409,7 +2416,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, while (current != NULL) { ret = wc_PKCS12_create_cert_bag(pkcs12, NULL, &curBufSz, current->buffer, current->bufferSz); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return NULL; } certBufSz += curBufSz; @@ -2461,7 +2468,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, /* get buffer size needed for content info */ ret = wc_PKCS12_encrypt_content(pkcs12, rng, NULL, certCiSz, NULL, certBufSz, algo, pass, (int)passSz, iter, type); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { XFREE(certBuf, heap, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_LEAVE("wc_PKCS12_create()", ret); return NULL; @@ -2517,7 +2524,7 @@ static int PKCS12_create_safe(WC_PKCS12* pkcs12, byte* certCi, word32 certCiSz, /* add Content Info structs to safe, key first then cert */ ret = wc_PKCS12_encrypt_content(pkcs12, rng, NULL, &safeDataSz, NULL, innerDataSz, 0, NULL, 0, 0, WC_PKCS12_DATA); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } @@ -2604,20 +2611,12 @@ WC_PKCS12* wc_PKCS12_create(char* pass, word32 passSz, char* name, return NULL; } - if ((pkcs12 = wc_PKCS12_new()) == NULL) { + if ((pkcs12 = wc_PKCS12_new_ex(heap)) == NULL) { wc_FreeRng(&rng); WOLFSSL_LEAVE("wc_PKCS12_create", MEMORY_E); return NULL; } - if ((ret = wc_PKCS12_SetHeap(pkcs12, heap)) != 0) { - wc_PKCS12_free(pkcs12); - wc_FreeRng(&rng); - WOLFSSL_LEAVE("wc_PKCS12_create", ret); - (void)ret; - return NULL; - } - if (iter <= 0) { iter = WC_PKCS12_ITT_DEFAULT; } diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index 997fd4f..acf7ef8 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -284,12 +284,12 @@ static int wc_PKCS7_AddDataToStream(PKCS7* pkcs7, byte* in, word32 inSz, if (rdSz >= inSz) { /* no more input to read, reset input index and request more data */ pkcs7->stream->idx = 0; - return WC_PKCS7_WANT_READ_E; + return WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E); } /* try to store input data into stream buffer */ if (inSz - rdSz > 0 && pkcs7->stream->length < expected) { - int len = min(inSz - rdSz, expected - pkcs7->stream->length); + int len = (int)min(inSz - rdSz, expected - pkcs7->stream->length); /* sanity check that the input buffer is not internal buffer */ if (in == pkcs7->stream->buffer) { @@ -324,7 +324,7 @@ static int wc_PKCS7_AddDataToStream(PKCS7* pkcs7, byte* in, word32 inSz, /* if not enough data was read in then request more */ if (pkcs7->stream->length < expected) { pkcs7->stream->idx = 0; - return WC_PKCS7_WANT_READ_E; + return WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E); } /* adjust pointer to read from stored buffer */ @@ -357,11 +357,11 @@ static int wc_PKCS7_SetMaxStream(PKCS7* pkcs7, byte* in, word32 defSz) byte* pt; if (pkcs7->stream->length > 0) { - length = pkcs7->stream->length; + length = (int)pkcs7->stream->length; pt = pkcs7->stream->buffer; } else { - length = defSz; + length = (int)defSz; pt = in; } maxIdx = (word32)length; @@ -379,8 +379,8 @@ static int wc_PKCS7_SetMaxStream(PKCS7* pkcs7, byte* in, word32 defSz) #ifdef ASN_BER_TO_DER if (length == 0 && ret == 0) { idx = 0; - if ((ret = wc_BerToDer(pt, maxIdx, NULL, - (word32*)&length)) != LENGTH_ONLY_E) { + if ((ret = wc_BerToDer(pt, maxIdx, NULL, (word32*)&length)) + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } } @@ -504,7 +504,7 @@ static void wc_PKCS7_ChangeState(PKCS7* pkcs7, int newState) pkcs7->state, wc_PKCS7_GetStateName(pkcs7->state), newState, wc_PKCS7_GetStateName(newState)); #endif - pkcs7->state = newState; + pkcs7->state = (word32)newState; } #define MAX_PKCS7_DIGEST_SZ (MAX_SEQ_SZ + MAX_ALGO_SZ + \ @@ -630,7 +630,7 @@ static int wc_SetContentType(int pkcs7TypeOID, byte* output, word32 outputSz) return BAD_FUNC_ARG; } - idSz = SetLength(typeSz, ID_Length); + idSz = (int)SetLength(typeSz, ID_Length); output[idx++] = ASN_OBJECT_ID; XMEMCPY(output + idx, ID_Length, idSz); idx += idSz; @@ -1041,9 +1041,11 @@ static int wc_PKCS7_CheckPublicKeyDer(PKCS7* pkcs7, int keyOID, /* Try to decode public key and check with wc_ecc_check_key() */ ret = wc_EccPublicKeyDecode(key, &scratch, ecc, keySz); + #if defined(WOLFSSL_VALIDATE_ECC_IMPORT) if (ret == 0) { ret = wc_ecc_check_key(ecc); } + #endif wc_ecc_free(ecc); break; @@ -1167,9 +1169,9 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) pkcs7->publicKeyOID = dCert->keyOID; XMEMCPY(pkcs7->issuerHash, dCert->issuerHash, KEYID_SIZE); pkcs7->issuer = dCert->issuerRaw; - pkcs7->issuerSz = dCert->issuerRawLen; + pkcs7->issuerSz = (word32)dCert->issuerRawLen; XMEMCPY(pkcs7->issuerSn, dCert->serial, dCert->serialSz); - pkcs7->issuerSnSz = dCert->serialSz; + pkcs7->issuerSnSz = (word32)dCert->serialSz; XMEMCPY(pkcs7->issuerSubjKeyId, dCert->extSubjKeyId, KEYID_SIZE); /* default to IssuerAndSerialNumber for SignerIdentifier */ @@ -1306,7 +1308,7 @@ static int wc_PKCS7_SignerInfoSetSID(PKCS7* pkcs7, byte* in, int inSz) return MEMORY_E; } XMEMCPY(pkcs7->signerInfo->sid, in, inSz); - pkcs7->signerInfo->sidSz = inSz; + pkcs7->signerInfo->sidSz = (word32)inSz; return 0; } @@ -1554,7 +1556,7 @@ static int EncodeAttributes(EncodedAttrib* ea, int eaSz, PKCS7Attrib* attribs, int attribsSz) { int i; - int maxSz = min(eaSz, attribsSz); + int maxSz = (int)min((word32)eaSz, attribsSz); int allAttribsSz = 0; for (i = 0; i < maxSz; i++) @@ -1564,14 +1566,14 @@ static int EncodeAttributes(EncodedAttrib* ea, int eaSz, ea[i].value = attribs[i].value; ea[i].valueSz = attribs[i].valueSz; attribSz += ea[i].valueSz; - ea[i].valueSetSz = SetSet(attribSz, ea[i].valueSet); + ea[i].valueSetSz = SetSet((word32)attribSz, ea[i].valueSet); attribSz += ea[i].valueSetSz; ea[i].oid = attribs[i].oid; ea[i].oidSz = attribs[i].oidSz; attribSz += ea[i].oidSz; - ea[i].valueSeqSz = SetSequence(attribSz, ea[i].valueSeq); + ea[i].valueSeqSz = SetSequence((word32)attribSz, ea[i].valueSeq); attribSz += ea[i].valueSeqSz; - ea[i].totalSz = attribSz; + ea[i].totalSz = (word32)attribSz; allAttribsSz += attribSz; } @@ -1614,7 +1616,7 @@ static void FreeAttribArray(PKCS7* pkcs7, FlatAttrib** arr, int rows) XFREE(arr[i], pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); } } - ForceZero(arr, rows); + ForceZero(arr, (word32)rows); XFREE(arr, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); } (void)pkcs7; @@ -1637,12 +1639,12 @@ static int SortAttribArray(FlatAttrib** arr, int rows) for (i = 0; i < rows; i++) { a = arr[i]; minSz = a->dataSz; - minIdx = i; + minIdx = (word32)i; for (j = i+1; j < rows; j++) { b = arr[j]; if (b->dataSz < minSz) { minSz = b->dataSz; - minIdx = j; + minIdx = (word32)j; } } if (minSz < a->dataSz) { @@ -1695,7 +1697,7 @@ static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, fa = derArr[i]; fa->data = output; - fa->dataSz = sz; + fa->dataSz = (word32)sz; } return 0; @@ -1715,12 +1717,12 @@ static int FlattenAttributes(PKCS7* pkcs7, byte* output, EncodedAttrib* ea, } /* create array of FlatAttrib struct pointers to hold DER attribs */ - derArr = (FlatAttrib**) XMALLOC(eaSz * sizeof(FlatAttrib*), pkcs7->heap, + derArr = (FlatAttrib**) XMALLOC((unsigned long)eaSz * sizeof(FlatAttrib*), pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (derArr == NULL) { return MEMORY_E; } - XMEMSET(derArr, 0, eaSz * sizeof(FlatAttrib*)); + XMEMSET(derArr, 0, (unsigned long)eaSz * sizeof(FlatAttrib*)); for (i = 0; i < eaSz; i++) { derArr[i] = NewAttrib(pkcs7->heap); @@ -1785,7 +1787,8 @@ static int wc_PKCS7_ImportRSA(PKCS7* pkcs7, RsaKey* privKey) #endif } #ifdef WOLF_CRYPTO_CB - else if (ret == ASN_PARSE_E && pkcs7->devId != INVALID_DEVID) { + else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) && + pkcs7->devId != INVALID_DEVID) { /* if using crypto callbacks, try public key decode */ idx = 0; ret = wc_RsaPublicKeyDecode(pkcs7->privateKey, &idx, privKey, @@ -1837,7 +1840,7 @@ static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) privKey, pkcs7->rng); } #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif } @@ -1874,7 +1877,8 @@ static int wc_PKCS7_ImportECC(PKCS7* pkcs7, ecc_key* privKey) } } #ifdef WOLF_CRYPTO_CB - else if (ret == ASN_PARSE_E && pkcs7->devId != INVALID_DEVID) { + else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) && + pkcs7->devId != INVALID_DEVID) { /* if using crypto callbacks, try public key decode */ idx = 0; ret = wc_EccPublicKeyDecode(pkcs7->privateKey, &idx, privKey, @@ -1927,7 +1931,7 @@ static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) &outSz, pkcs7->rng, privKey); } #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif if (ret == 0) ret = (int)outSz; @@ -2068,7 +2072,7 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, cannedAttribs[idx].oid = signingTimeOid; cannedAttribs[idx].oidSz = signingTimeOidSz; cannedAttribs[idx].value = signingTime; - cannedAttribs[idx].valueSz = timeSz; + cannedAttribs[idx].valueSz = (word32)timeSz; idx++; } #endif @@ -2078,13 +2082,13 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, cannedAttribs[idx].oid = messageDigestOid; cannedAttribs[idx].oidSz = messageDigestOidSz; cannedAttribs[idx].value = esd->contentDigest; - cannedAttribs[idx].valueSz = hashSz + 2; /* ASN.1 heading */ + cannedAttribs[idx].valueSz = (word32)hashSz + 2; /* ASN.1 heading */ idx++; } esd->signedAttribsCount += cannedAttribsCount; esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], - idx, cannedAttribs, cannedAttribsCount); + (int)idx, cannedAttribs, cannedAttribsCount); atrIdx += idx; } else { esd->signedAttribsCount = 0; @@ -2330,7 +2334,7 @@ static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, XMEMCPY(digestInfo + digIdx, esd->contentAttribsDigest, hashSz); digIdx += hashSz; - *digestInfoSz = digIdx; + *digestInfoSz = (word32)digIdx; return 0; } @@ -2426,7 +2430,7 @@ static int wc_PKCS7_SignedDataBuildSignature(PKCS7* pkcs7, /* CMS with ECDSA does not sign DigestInfo structure * like PKCS#7 with RSA does */ ret = wc_PKCS7_EcdsaSign(pkcs7, esd->contentAttribsDigest, - hashSz, esd); + (word32)hashSz, esd); break; #endif @@ -2468,7 +2472,7 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, Aes* aes, byte* encContentOut, byte* contentData, int contentDataSz, byte* out, word32* outIdx, ESD* esd) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); byte encContentOutOct[MAX_OCTET_STR_SZ]; word32 encContentOutOctSz = 0; @@ -2477,39 +2481,40 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, XMEMCPY(encContentOut, contentData, contentDataSz); if (esd && esd->contentDigestSet != 1) { ret = wc_HashUpdate(&esd->hash, esd->hashType, - contentData, contentDataSz); + contentData, (word32)contentDataSz); } break; #ifndef NO_AES case WC_CIPHER_AES_CBC: ret = wc_AesCbcEncrypt(aes, encContentOut, - contentData, contentDataSz); + contentData, (word32)contentDataSz); break; #endif #ifdef WOLFSSL_AESGCM_STREAM case WC_CIPHER_AES_GCM: ret = wc_AesGcmEncryptUpdate(aes, encContentOut, - contentData, contentDataSz, NULL, 0); + contentData, (word32)contentDataSz, NULL, 0); break; #endif } #ifdef WOLFSSL_ASYNC_CRYPT /* async encrypt not available here, so block till done */ - if (ret == WC_PENDING_E && cipherType != WC_CIPHER_NONE) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && + cipherType != WC_CIPHER_NONE) { ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); } #endif if (ret == 0) { - encContentOutOctSz = SetOctetString(contentDataSz, encContentOutOct); + encContentOutOctSz = SetOctetString((word32)contentDataSz, encContentOutOct); wc_PKCS7_WriteOut(pkcs7, (out)? out + *outIdx: NULL, encContentOutOct, encContentOutOctSz); *outIdx += encContentOutOctSz; wc_PKCS7_WriteOut(pkcs7, (out)? out + *outIdx : NULL, - encContentOut, contentDataSz); + encContentOut, (word32)contentDataSz); *outIdx += contentDataSz; } @@ -2517,7 +2522,7 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, } -/* Used for encoding the content, potentially one octet chunck at a time if +/* Used for encoding the content, potentially one octet chunk at a time if * in streaming mode with IO callbacks set. * Can handle the cipher types: * - WC_CIPHER_NONE, used for encoding signed bundle where no encryption is @@ -2551,7 +2556,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, if (cipherType != WC_CIPHER_NONE) { padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, - wc_PKCS7_GetOIDBlockSize(pkcs7->encryptOID)); + (word32)wc_PKCS7_GetOIDBlockSize(pkcs7->encryptOID)); } if (cipherType == WC_CIPHER_NONE && esd && esd->contentDigestSet != 1) { @@ -2633,7 +2638,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, /* copy over any remaining data */ XMEMCPY(contentData, buf + sz, contentDataRead); - idx = contentDataRead; + idx = (word32)contentDataRead; } else { /* was not on an octet boundary, copy full @@ -2661,7 +2666,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, /* encrypt and flush out remainder of content data */ ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, aes, - encContentOut, contentData, idx, out, &outIdx, esd); + encContentOut, contentData, (int)idx, out, &outIdx, esd); if (ret == 0) { if (cipherType == WC_CIPHER_NONE && esd && esd->contentDigestSet != 1) { @@ -2688,7 +2693,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, ret = wc_HashInit(&esd->hash, esd->hashType); if (ret == 0) ret = wc_HashUpdate(&esd->hash, esd->hashType, in, - inSz); + (word32)inSz); if (ret == 0) ret = wc_HashFinal(&esd->hash, esd->hashType, esd->contentDigest + 2); @@ -2698,13 +2703,13 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, #ifndef NO_AES case WC_CIPHER_AES_CBC: - ret = wc_AesCbcEncrypt(aes, out, in, inSz); + ret = wc_AesCbcEncrypt(aes, out, in, (word32)inSz); break; #endif #ifdef WOLFSSL_AESGCM_STREAM case WC_CIPHER_AES_GCM: - ret = wc_AesGcmEncryptUpdate(aes, out, in, inSz, NULL, 0); + ret = wc_AesGcmEncryptUpdate(aes, out, in, (word32)inSz, NULL, 0); break; #endif } @@ -2829,7 +2834,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, idx = ret; goto out; } - pkcs7->contentTypeSz = ret; + pkcs7->contentTypeSz = (word32)ret; } /* set signedData outer content type */ @@ -2838,7 +2843,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, idx = ret; goto out; } - signedDataOidSz = ret; + signedDataOidSz = (word32)ret; if (pkcs7->sidType != DEGENERATE_SID) { esd->hashType = wc_OidGetHash(pkcs7->hashOID); @@ -2884,7 +2889,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, /* SignerIdentifier */ if (pkcs7->sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { /* IssuerAndSerialNumber */ - esd->issuerSnSz = SetSerialNumber(pkcs7->issuerSn, pkcs7->issuerSnSz, + esd->issuerSnSz = (word32)SetSerialNumber(pkcs7->issuerSn, pkcs7->issuerSnSz, esd->issuerSn, MAX_SN_SZ, MAX_SN_SZ); signerInfoSz += esd->issuerSnSz; esd->issuerNameSz = SetSequence(pkcs7->issuerSz, esd->issuerName); @@ -2894,22 +2899,22 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, if (pkcs7->version == 3) { /* RFC 4108 version MUST be 3 for firmware package signer */ - esd->signerVersionSz = SetMyVersion(3, esd->signerVersion, 0); + esd->signerVersionSz = (word32)SetMyVersion(3, esd->signerVersion, 0); } else { /* version MUST be 1 otherwise*/ - esd->signerVersionSz = SetMyVersion(1, esd->signerVersion, 0); + esd->signerVersionSz = (word32)SetMyVersion(1, esd->signerVersion, 0); } } else if (pkcs7->sidType == CMS_SKID) { /* SubjectKeyIdentifier */ - esd->issuerSKIDSz = SetOctetString(keyIdSize, esd->issuerSKID); + esd->issuerSKIDSz = SetOctetString((word32)keyIdSize, esd->issuerSKID); esd->issuerSKIDSeqSz = SetExplicit(0, esd->issuerSKIDSz + keyIdSize, esd->issuerSKIDSeq, 0); signerInfoSz += (esd->issuerSKIDSz + esd->issuerSKIDSeqSz + keyIdSize); /* version MUST be 3 */ - esd->signerVersionSz = SetMyVersion(3, esd->signerVersion, 0); + esd->signerVersionSz = (word32)SetMyVersion(3, esd->signerVersion, 0); } else if (pkcs7->sidType == DEGENERATE_SID) { /* no signer info added */ } else { @@ -2966,7 +2971,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, } if (pkcs7->publicKeyOID != ECDSAk && hashBuf == NULL) { - ret = esd->encContentDigestSz = wc_PKCS7_GetSignSize(pkcs7); + ret = wc_PKCS7_GetSignSize(pkcs7); + esd->encContentDigestSz = (word32)ret; } else { ret = wc_PKCS7_SignedDataBuildSignature(pkcs7, flatSignedAttribs, @@ -3011,10 +3017,10 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, if (pkcs7->version == 3) { /* RFC 4108 version MUST be 3 for firmware package signer */ - esd->versionSz = SetMyVersion(3, esd->version, 0); + esd->versionSz = (word32)SetMyVersion(3, esd->version, 0); } else { - esd->versionSz = SetMyVersion(1, esd->version, 0); + esd->versionSz = (word32)SetMyVersion(1, esd->version, 0); } totalSz = esd->versionSz + esd->singleDigAlgoIdSz + esd->digAlgoIdSetSz + @@ -3096,7 +3102,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, } #endif *outputSz = totalSz; - idx = totalSz; + idx = (int)totalSz; goto out; } idx = BUFFER_E; @@ -3149,7 +3155,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, /* support returning header and footer without content */ if (output2 && output2Sz) { - *outputSz = idx; + *outputSz = (word32)idx; idx = 0; } else { @@ -3243,7 +3249,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, esd->issuerSKID, esd->issuerSKIDSz); idx += esd->issuerSKIDSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, - pkcs7->issuerSubjKeyId, keyIdSize); + pkcs7->issuerSubjKeyId, (word32)keyIdSize); idx += keyIdSize; } else if (pkcs7->sidType == DEGENERATE_SID) { /* no signer infos in degenerate case */ @@ -3341,11 +3347,11 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, #endif if (output2Sz) { - *output2Sz = idx; + *output2Sz = (word32)idx; idx = 0; /* success */ } else { - *outputSz = idx; + *outputSz = (word32)idx; } out: @@ -3517,7 +3523,7 @@ int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) wc_HashFree(&hash, hashType); } if (ret == 0) { - ret = PKCS7_EncodeSigned(pkcs7, hashBuf, hashSz, + ret = PKCS7_EncodeSigned(pkcs7, hashBuf, (word32)hashSz, output, &outputSz, NULL, NULL); } } @@ -3669,7 +3675,7 @@ int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, ret = wc_InitRng_ex(&rng, pkcs7->heap, pkcs7->devId); if (ret != 0) { - ForceZero(encrypted, encryptedSz); + ForceZero(encrypted, (word32)encryptedSz); XFREE(encrypted, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } @@ -3677,7 +3683,7 @@ int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, /* 2: build up SignedData, encapsulating EncryptedData */ pkcs7->rng = &rng; pkcs7->content = encrypted; - pkcs7->contentSz = encryptedSz; + pkcs7->contentSz = (word32)encryptedSz; pkcs7->contentOID = ENCRYPTED_DATA; pkcs7->hashOID = hashOID; pkcs7->encryptOID = signOID; @@ -3691,7 +3697,7 @@ int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, WOLFSSL_MSG("Error encoding CMS SignedData content type"); } - ForceZero(encrypted, encryptedSz); + ForceZero(encrypted, (word32)encryptedSz); XFREE(encrypted, pkcs7->heap, DYNAMIC_TYPE_PKCS7); pkcs7->rng = NULL; wc_FreeRng(&rng); @@ -4041,11 +4047,11 @@ static int wc_PKCS7_RsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) { - ret = wc_RsaSSL_Verify(sig, sigSz, digest, MAX_PKCS7_DIGEST_SZ, + ret = wc_RsaSSL_Verify(sig, (word32)sigSz, digest, MAX_PKCS7_DIGEST_SZ, key); } #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif FreeDecodedCert(dCert); wc_FreeRsaKey(key); @@ -4169,10 +4175,10 @@ static int wc_PKCS7_EcdsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) { - ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, &res, key); + ret = wc_ecc_verify_hash(sig, (word32)sigSz, hash, hashSz, &res, key); } #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif FreeDecodedCert(dCert); @@ -4248,7 +4254,7 @@ static int wc_PKCS7_BuildSignedDataDigest(PKCS7* pkcs7, byte* signedAttrib, ret = wc_HashGetDigestSize(hashType); if (ret < 0) return ret; - hashSz = ret; + hashSz = (word32)ret; if (signedAttribSz > 0) { if (signedAttrib == NULL) @@ -4329,7 +4335,7 @@ static int wc_PKCS7_BuildSignedDataDigest(PKCS7* pkcs7, byte* signedAttrib, digIdx += hashSz; XMEMCPY(pkcs7Digest, digestInfo, digIdx); - *pkcs7DigestSz = digIdx; + *pkcs7DigestSz = (word32)digIdx; /* set plain digest pointer */ *plainDigest = pkcs7Digest + digIdx - hashSz; @@ -4421,7 +4427,7 @@ static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, XMEMSET(digest, 0, MAX_PKCS7_DIGEST_SZ); content = pkcs7->content; - contentLen = pkcs7->contentSz; + contentLen = (int)pkcs7->contentSz; if (pkcs7->contentIsPkcs7Type == 1) { /* Content follows PKCS#7 RFC, which defines type as ANY. CMS @@ -4434,7 +4440,7 @@ static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, } if (GetLength_ex(content, &contentIdx, &contentLen, - contentLen, 1) < 0) { + (word32)contentLen, 1) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(digest, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -4442,7 +4448,7 @@ static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, } } - ret = wc_Hash(hashType, content + contentIdx, contentLen, digest, + ret = wc_Hash(hashType, content + contentIdx, (word32)contentLen, digest, MAX_PKCS7_DIGEST_SZ); if (ret < 0) { WOLFSSL_MSG("Error hashing PKCS7 content for verification"); @@ -4623,11 +4629,11 @@ static int wc_PKCS7_SignedDataVerifySignature(PKCS7* pkcs7, byte* sig, #ifndef NO_RSA case RSAk: - ret = wc_PKCS7_RsaVerify(pkcs7, sig, sigSz, pkcs7Digest, + ret = wc_PKCS7_RsaVerify(pkcs7, sig, (int)sigSz, pkcs7Digest, pkcs7DigestSz); if (ret < 0) { WOLFSSL_MSG("PKCS#7 verification failed, trying CMS"); - ret = wc_PKCS7_RsaVerify(pkcs7, sig, sigSz, plainDigest, + ret = wc_PKCS7_RsaVerify(pkcs7, sig, (int)sigSz, plainDigest, plainDigestSz); } break; @@ -4635,7 +4641,7 @@ static int wc_PKCS7_SignedDataVerifySignature(PKCS7* pkcs7, byte* sig, #ifdef HAVE_ECC case ECDSAk: - ret = wc_PKCS7_EcdsaVerify(pkcs7, sig, sigSz, plainDigest, + ret = wc_PKCS7_EcdsaVerify(pkcs7, sig, (int)sigSz, plainDigest, plainDigestSz); break; #endif @@ -4681,7 +4687,7 @@ static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) /* if sigOID is already RSAk */ case RSAk: - pkcs7->publicKeyOID = sigOID; + pkcs7->publicKeyOID = (word32)sigOID; break; #endif @@ -4693,7 +4699,7 @@ static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) /* if sigOID is already DSAk */ case DSAk: - pkcs7->publicKeyOID = sigOID; + pkcs7->publicKeyOID = (word32)sigOID; break; #endif @@ -4713,7 +4719,7 @@ static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) /* if sigOID is already ECDSAk */ case ECDSAk: - pkcs7->publicKeyOID = sigOID; + pkcs7->publicKeyOID = (word32)sigOID; break; #endif @@ -4757,7 +4763,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) int oidIdx; PKCS7DecodedAttrib* attrib; - if (GetSequence(in, &idx, &length, inSz) < 0) + if (GetSequence(in, &idx, &length, (word32)inSz) < 0) return ASN_PARSE_E; attrib = (PKCS7DecodedAttrib*)XMALLOC(sizeof(PKCS7DecodedAttrib), @@ -4767,8 +4773,8 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) } XMEMSET(attrib, 0, sizeof(PKCS7DecodedAttrib)); - oidIdx = idx; - if (GetObjectId(in, &idx, &oid, oidIgnoreType, inSz) + oidIdx = (int)idx; + if (GetObjectId(in, &idx, &oid, oidIgnoreType, (word32)inSz) < 0) { XFREE(attrib, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ASN_PARSE_E; @@ -4783,7 +4789,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) XMEMCPY(attrib->oid, in + oidIdx, attrib->oidSz); /* Get Set that contains the printable string value */ - if (GetSet(in, &idx, &length, inSz) < 0) { + if (GetSet(in, &idx, &length, (word32)inSz) < 0) { XFREE(attrib->oid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(attrib, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ASN_PARSE_E; @@ -4992,7 +4998,7 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, /* store public key type based on digestEncryptionAlgorithm */ if (ret == 0) { - ret = wc_PKCS7_SetPublicKeyOID(pkcs7, sigOID); + ret = wc_PKCS7_SetPublicKeyOID(pkcs7, (int)sigOID); if (ret < 0) { WOLFSSL_MSG("Failed to set public key OID from signature"); } @@ -5087,8 +5093,8 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, } /* set up for next octet string */ - pkcs7->stream->currContSz = length; - pkcs7->stream->currContRmnSz = length; + pkcs7->stream->currContSz = (word32)length; + pkcs7->stream->currContRmnSz = (word32)length; pkcs7->stream->expected = min(pkcs7->stream->currContRmnSz, MAX_PKCS7_STREAM_BUFFER); @@ -5100,7 +5106,7 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, /* check if expected data is available in stream */ ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, pkcs7->stream->expected, &msg, idx); - if (ret == WC_PKCS7_WANT_READ_E) { + if (ret == WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { break; /* ask user more input */ } @@ -5114,7 +5120,7 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, * in-definite length encoding. * number of indef is stored in pkcs7->stream->cntIdfCnt. */ - pkcs7->stream->expected = (ASN_TAG_SZ + TRAILING_ZERO) * + pkcs7->stream->expected = (word32)(ASN_TAG_SZ + TRAILING_ZERO) * pkcs7->stream->cntIdfCnt; /* dec idx by one since already consumed to get ASN_EOC */ @@ -5127,7 +5133,7 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, /* check if expected data is available in stream */ ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, pkcs7->stream->expected, &msg, idx); - if (ret == WC_PKCS7_WANT_READ_E) { + if (ret == WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { break; /* ask user more input */ } @@ -5164,7 +5170,7 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, pkcs7->stream->expected, &msg, idx); - if (ret == WC_PKCS7_WANT_READ_E) { + if (ret == WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { break; } @@ -5371,7 +5377,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, word32 len = 0; ret = wc_BerToDer(pkiMsg, pkiMsgSz, NULL, &len); - if (ret != LENGTH_ONLY_E) + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; pkcs7->der = (byte*)XMALLOC(len, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -5475,7 +5481,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, < 0) ret = ASN_PARSE_E; - pkcs7->hashOID = hashOID; + pkcs7->hashOID = (int)hashOID; /* get hash type */ hashType = wc_OidGetHash(pkcs7->hashOID); @@ -5708,8 +5714,8 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, #ifndef NO_PKCS7_STREAM pkcs7->stream->multi = multiPart; pkcs7->stream->currContIdx = localIdx; - pkcs7->stream->currContSz = length; - pkcs7->stream->currContRmnSz = length; + pkcs7->stream->currContSz = (word32)length; + pkcs7->stream->currContRmnSz = (word32)length; #endif /* reset length to outer OCTET_STRING for bundle * size check below */ @@ -5736,8 +5742,8 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, if (ret == 0) { pkcs7->stream->multi = multiPart; pkcs7->stream->currContIdx = localIdx; - pkcs7->stream->currContSz = length; - pkcs7->stream->currContRmnSz = length; + pkcs7->stream->currContSz = (word32)length; + pkcs7->stream->currContRmnSz = (word32)length; } #endif } @@ -5821,7 +5827,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &stateIdx, &idx)) != 0) { break; } - wc_PKCS7_StreamStoreVar(pkcs7, pkiMsg2Sz, localIdx, length); + wc_PKCS7_StreamStoreVar(pkcs7, pkiMsg2Sz, (int)localIdx, length); #endif /* !NO_PKCS7_STREAM */ @@ -6081,7 +6087,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } wc_PKCS7_StreamStoreVar(pkcs7, pkiMsg2Sz, 0, length); if (length > 0) { - pkcs7->stream->expected = length; + pkcs7->stream->expected = (word32)length; } else { pkcs7->stream->expected = MAX_SEQ_SZ; @@ -6119,7 +6125,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* restore content */ content = pkcs7->stream->content; - contentSz = pkcs7->stream->contentSz; + contentSz = (int)pkcs7->stream->contentSz; /* restore detached flag */ detached = pkcs7->stream->detached; @@ -6139,7 +6145,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } XMEMCPY(pkcs7->stream->tmpCert, pkiMsg2 + idx, length); pkiMsg2 = pkcs7->stream->tmpCert; - pkiMsg2Sz = length; + pkiMsg2Sz = (word32)length; idx = 0; } #else @@ -6209,7 +6215,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, pkcs7->isDynamic = isDynamic; /* This will reset PKCS7 structure and then set the * certificate */ - ret = wc_PKCS7_InitWithCert(pkcs7, cert, certSz); + ret = wc_PKCS7_InitWithCert(pkcs7, cert, (word32)certSz); /* Restore pkcs7->contentDynamic from above, will be * freed by application with wc_PKCS7_Free() */ @@ -6238,7 +6244,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, int i; pkcs7->cert[0] = cert; - pkcs7->certSz[0] = certSz; + pkcs7->certSz[0] = (word32)certSz; certIdx = idx + certSz; for (i = 1; i < MAX_PKCS7_CERTS && @@ -6411,7 +6417,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, if (in2 && in2Sz > 0 && hashBuf && hashSz > 0) { if (length > 0) { - pkcs7->stream->expected = length; + pkcs7->stream->expected = (word32)length; } else { pkcs7->stream->expected = 0; @@ -6426,10 +6432,10 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, * zero's should exist at the end of the bundle. */ if (pkcs7->stream->indefLen == 1) { - pkcs7->stream->expected = length + 3 * ASN_INDEF_END_SZ; + pkcs7->stream->expected = (word32)length + 3 * ASN_INDEF_END_SZ; } else { - pkcs7->stream->expected = length; + pkcs7->stream->expected = (word32)length; } wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_VERIFY_STAGE7); @@ -6460,7 +6466,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* restore content */ content = pkcs7->stream->content; - contentSz = pkcs7->stream->contentSz; + contentSz = (int)pkcs7->stream->contentSz; #endif ret = wc_PKCS7_ParseSignerInfo(pkcs7, pkiMsg2, pkiMsg2Sz, &idx, @@ -6489,18 +6495,18 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } pkcs7->content = content; - pkcs7->contentSz = contentSz; + pkcs7->contentSz = (word32)contentSz; if (ret == 0) { - ret = wc_PKCS7_SignedDataVerifySignature(pkcs7, sig, sigSz, - signedAttrib, signedAttribSz, + ret = wc_PKCS7_SignedDataVerifySignature(pkcs7, sig, (word32)sigSz, + signedAttrib, (word32)signedAttribSz, hashBuf, hashSz); } } #ifndef NO_PKCS7_STREAM /* make sure that terminating zero's follow */ - if ((ret == PKCS7_SIGNEEDS_CHECK || ret >= 0) && + if ((ret == WC_NO_ERR_TRACE(PKCS7_SIGNEEDS_CHECK) || ret >= 0) && pkcs7->stream->indefLen == 1) { int i; for (i = 0; i < 3 * ASN_INDEF_END_SZ; i++) { @@ -6528,7 +6534,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = BAD_FUNC_ARG; } - if (ret != 0 && ret != WC_PKCS7_WANT_READ_E) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { #ifndef NO_PKCS7_STREAM wc_PKCS7_ResetStream(pkcs7); #endif @@ -7037,7 +7043,7 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) return BAD_FUNC_ARG; /* kekOctet */ - kekOctetSz = SetOctetString(sizeof(word32), kekOctet); + kekOctetSz = (int)SetOctetString(sizeof(word32), kekOctet); sharedInfoSz += (kekOctetSz + sizeof(word32)); /* suppPubInfo */ @@ -7048,7 +7054,7 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) /* optional ukm/entityInfo */ if (kari->ukmSz > 0) { - entityUInfoOctetSz = SetOctetString(kari->ukmSz, entityUInfoOctet); + entityUInfoOctetSz = (int)SetOctetString(kari->ukmSz, entityUInfoOctet); sharedInfoSz += (entityUInfoOctetSz + kari->ukmSz); entityUInfoExplicitSz = SetExplicit(0, entityUInfoOctetSz + @@ -7058,11 +7064,11 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) } /* keyInfo */ - keyInfoSz = SetAlgoID(keyWrapOID, keyInfo, oidKeyWrapType, 0); + keyInfoSz = (int)SetAlgoID(keyWrapOID, keyInfo, oidKeyWrapType, 0); sharedInfoSz += keyInfoSz; /* sharedInfo */ - sharedInfoSeqSz = SetSequence(sharedInfoSz, sharedInfoSeq); + sharedInfoSeqSz = (int)SetSequence((word32)sharedInfoSz, sharedInfoSeq); sharedInfoSz += sharedInfoSeqSz; kari->sharedInfo = (byte*)XMALLOC(sharedInfoSz, kari->heap, @@ -7070,7 +7076,7 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) if (kari->sharedInfo == NULL) return MEMORY_E; - kari->sharedInfoSz = sharedInfoSz; + kari->sharedInfoSz = (word32)sharedInfoSz; XMEMCPY(kari->sharedInfo + idx, sharedInfoSeq, sharedInfoSeqSz); idx += sharedInfoSeqSz; @@ -7132,7 +7138,7 @@ static int wc_PKCS7_KariGenerateKEK(WC_PKCS7_KARI* kari, WC_RNG* rng, return ret; /* generate shared secret */ - secretSz = kari->senderKey->dp->size; + secretSz = (word32)kari->senderKey->dp->size; secret = (byte*)XMALLOC(secretSz, kari->heap, DYNAMIC_TYPE_PKCS7); if (secret == NULL) return MEMORY_E; @@ -7321,7 +7327,7 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, } /* generate random content encryption key, if needed */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -7420,11 +7426,11 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* Start of RecipientEncryptedKeys */ /* EncryptedKey */ - encryptedKeyOctetSz = SetOctetString(encryptedKeySz, encryptedKeyOctet); + encryptedKeyOctetSz = (int)SetOctetString(encryptedKeySz, encryptedKeyOctet); totalSz += (encryptedKeyOctetSz + encryptedKeySz); /* SubjectKeyIdentifier */ - subjKeyIdOctetSz = SetOctetString(keyIdSize, subjKeyIdOctet); + subjKeyIdOctetSz = (int)SetOctetString((word32)keyIdSize, subjKeyIdOctet); totalSz += (subjKeyIdOctetSz + keyIdSize); /* RecipientKeyIdentifier IMPLICIT [0] */ @@ -7433,17 +7439,17 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, totalSz += recipKeyIdSeqSz; /* RecipientEncryptedKey */ - recipEncKeySeqSz = SetSequence(totalSz, recipEncKeySeq); + recipEncKeySeqSz = (int)SetSequence((word32)totalSz, recipEncKeySeq); totalSz += recipEncKeySeqSz; /* RecipientEncryptedKeys */ - recipEncKeysSeqSz = SetSequence(totalSz, recipEncKeysSeq); + recipEncKeysSeqSz = (int)SetSequence((word32)totalSz, recipEncKeysSeq); totalSz += recipEncKeysSeqSz; /* Start of optional UserKeyingMaterial */ if (kari->ukmSz > 0) { - ukmOctetSz = SetOctetString(kari->ukmSz, ukmOctetStr); + ukmOctetSz = (int)SetOctetString(kari->ukmSz, ukmOctetStr); totalSz += (ukmOctetSz + kari->ukmSz); ukmExplicitSz = SetExplicit(1, ukmOctetSz + kari->ukmSz, @@ -7454,11 +7460,11 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* Start of KeyEncryptionAlgorithmIdentifier */ /* KeyWrapAlgorithm */ - keyWrapAlgSz = SetAlgoID(keyWrapOID, keyWrapAlg, oidKeyWrapType, 0); + keyWrapAlgSz = (int)SetAlgoID(keyWrapOID, keyWrapAlg, oidKeyWrapType, 0); totalSz += keyWrapAlgSz; /* KeyEncryptionAlgorithmIdentifier */ - keyEncryptAlgoIdSz = SetAlgoID(keyAgreeOID, keyEncryptAlgoId, + keyEncryptAlgoIdSz = (int)SetAlgoID(keyAgreeOID, keyEncryptAlgoId, oidCmsKeyAgreeType, keyWrapAlgSz); totalSz += keyEncryptAlgoIdSz; @@ -7467,25 +7473,25 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* recipient ECPoint, public key */ XMEMSET(origPubKeyStr, 0, sizeof(origPubKeyStr)); /* no unused bits */ origPubKeyStr[0] = ASN_BIT_STRING; - origPubKeyStrSz = SetLength(kari->senderKeyExportSz + 1, + origPubKeyStrSz = (int)SetLength(kari->senderKeyExportSz + 1, origPubKeyStr + 1) + 2; totalSz += (origPubKeyStrSz + kari->senderKeyExportSz); /* Originator AlgorithmIdentifier, params set to NULL for interop compatibility */ - origAlgIdSz = SetAlgoID(ECDSAk, origAlgId, oidKeyType, 2); + origAlgIdSz = (int)SetAlgoID(ECDSAk, origAlgId, oidKeyType, 2); origAlgId[origAlgIdSz++] = ASN_TAG_NULL; origAlgId[origAlgIdSz++] = 0; totalSz += origAlgIdSz; /* outer OriginatorPublicKey IMPLICIT [1] */ - origPubKeySeqSz = SetImplicit(ASN_SEQUENCE, 1, + origPubKeySeqSz = (int)SetImplicit(ASN_SEQUENCE, 1, origAlgIdSz + origPubKeyStrSz + kari->senderKeyExportSz, origPubKeySeq, 0); totalSz += origPubKeySeqSz; /* outer OriginatorIdentifierOrKey IMPLICIT [0] */ - origIdOrKeySeqSz = SetImplicit(ASN_SEQUENCE, 0, + origIdOrKeySeqSz = (int)SetImplicit(ASN_SEQUENCE, 0, origPubKeySeqSz + origAlgIdSz + origPubKeyStrSz + kari->senderKeyExportSz, origIdOrKeySeq, 0); @@ -7497,7 +7503,7 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, recip->recipVersion = 3; /* outer IMPLICIT [1] kari */ - kariSeqSz = SetImplicit(ASN_SEQUENCE, 1, totalSz, kariSeq, 0); + kariSeqSz = (int)SetImplicit(ASN_SEQUENCE, 1, (word32)totalSz, kariSeq, 0); totalSz += kariSeqSz; if (totalSz > MAX_RECIP_SZ) { @@ -7583,7 +7589,7 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, (void)options; - return idx; + return (int)idx; } #endif /* HAVE_ECC */ @@ -7704,7 +7710,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, } /* generate random content encryption key, if needed */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(serial, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -7757,7 +7763,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, return -1; } issuerSz = decoded->issuerRawLen; - issuerSeqSz = SetSequence(issuerSz, issuerSeq); + issuerSeqSz = (int)SetSequence((word32)issuerSz, issuerSeq); if (decoded->serialSz == 0) { WOLFSSL_MSG("DecodedCert missing serial number"); @@ -7793,7 +7799,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, verSz = SetMyVersion(2, ver, 0); recip->recipVersion = 2; - issuerSKIDSz = SetLength(keyIdSize, issuerSKID); + issuerSKIDSz = SetLength((word32)keyIdSize, issuerSKID); } else { FreeDecodedCert(decoded); #ifdef WOLFSSL_SMALL_STACK @@ -7906,7 +7912,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, encryptedKeySz, pubKey, &rng); } #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif wc_FreeRsaKey(pubKey); wc_FreeRng(&rng); @@ -7927,13 +7933,13 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - encryptedKeySz = ret; + encryptedKeySz = (word32)ret; - encKeyOctetStrSz = SetOctetString(encryptedKeySz, encKeyOctetStr); + encKeyOctetStrSz = (int)SetOctetString(encryptedKeySz, encKeyOctetStr); /* RecipientInfo */ if (sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { - recipSeqSz = SetSequence(verSz + issuerSerialSeqSz + issuerSeqSz + + recipSeqSz = (int)SetSequence(verSz + issuerSerialSeqSz + issuerSeqSz + issuerSz + snSz + keyEncAlgSz + encKeyOctetStrSz + encryptedKeySz, recipSeq); @@ -8024,7 +8030,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, lastRecip->next = recip; } - return idx; + return (int)idx; } #endif /* !NO_RSA */ @@ -8137,7 +8143,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesSetKey(aes, key, keySz, iv, AES_ENCRYPTION); + ret = wc_AesSetKey(aes, key, (word32)keySz, iv, AES_ENCRYPTION); if (ret == 0) { ret = wc_PKCS7_EncodeContentStream(pkcs7, NULL, aes, in, inSz, out, WC_CIPHER_AES_CBC); @@ -8171,7 +8177,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesGcmSetKey(aes, key, keySz); + ret = wc_AesGcmSetKey(aes, key, (word32)keySz); if (ret == 0) { #ifndef WOLFSSL_AESGCM_STREAM if (pkcs7->encodeStream) { @@ -8188,7 +8194,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif } #else - ret = wc_AesGcmEncryptInit(aes, key, keySz, iv, ivSz); + ret = wc_AesGcmEncryptInit(aes, key, (word32)keySz, iv, ivSz); if (ret == 0) { ret = wc_AesGcmEncryptUpdate(aes, NULL, NULL, 0, aad, aadSz); @@ -8238,9 +8244,9 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesCcmSetKey(aes, key, keySz); + ret = wc_AesCcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesCcmEncrypt(aes, out, in, inSz, iv, ivSz, + ret = wc_AesCcmEncrypt(aes, out, in, (word32)inSz, iv, ivSz, authTag, authTagSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async encrypt not available here, so block till done */ @@ -8268,7 +8274,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, ret = wc_Des_SetKey(&des, key, iv, DES_ENCRYPTION); if (ret == 0) - ret = wc_Des_CbcEncrypt(&des, out, in, inSz); + ret = wc_Des_CbcEncrypt(&des, out, in, (word32)inSz); break; @@ -8285,7 +8291,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, if (ret == 0) { ret = wc_Des3_SetKey(&des3, key, iv, DES_ENCRYPTION); if (ret == 0) { - ret = wc_Des3_CbcEncrypt(&des3, out, in, inSz); + ret = wc_Des3_CbcEncrypt(&des3, out, in, (word32)inSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async encrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &des3.asyncDev, WC_ASYNC_FLAG_NONE); @@ -8372,9 +8378,9 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesSetKey(aes, key, keySz, iv, AES_DECRYPTION); + ret = wc_AesSetKey(aes, key, (word32)keySz, iv, AES_DECRYPTION); if (ret == 0) { - ret = wc_AesCbcDecrypt(aes, out, in, inSz); + ret = wc_AesCbcDecrypt(aes, out, in, (word32)inSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); @@ -8409,9 +8415,9 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesGcmSetKey(aes, key, keySz); + ret = wc_AesGcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesGcmDecrypt(aes, out, in, inSz, iv, ivSz, + ret = wc_AesGcmDecrypt(aes, out, in, (word32)inSz, iv, ivSz, authTag, authTagSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ @@ -8448,9 +8454,9 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { - ret = wc_AesCcmSetKey(aes, key, keySz); + ret = wc_AesCcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesCcmDecrypt(aes, out, in, inSz, iv, ivSz, + ret = wc_AesCcmDecrypt(aes, out, in, (word32)inSz, iv, ivSz, authTag, authTagSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ @@ -8473,7 +8479,7 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, ret = wc_Des_SetKey(&des, key, iv, DES_DECRYPTION); if (ret == 0) - ret = wc_Des_CbcDecrypt(&des, out, in, inSz); + ret = wc_Des_CbcDecrypt(&des, out, in, (word32)inSz); break; case DES3b: @@ -8484,7 +8490,7 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, if (ret == 0) { ret = wc_Des3_SetKey(&des3, key, iv, DES_DECRYPTION); if (ret == 0) { - ret = wc_Des3_CbcDecrypt(&des3, out, in, inSz); + ret = wc_Des3_CbcDecrypt(&des3, out, in, (word32)inSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &des3.asyncDev, WC_ASYNC_FLAG_NONE); @@ -8628,6 +8634,8 @@ int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, return BAD_FUNC_ARG; padSz = wc_PKCS7_GetPadSize(inSz, blockSz); + if (padSz < 0) + return padSz; if (outSz < (inSz + padSz)) return BAD_FUNC_ARG; @@ -8682,7 +8690,7 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, } /* generate random content encryption key, if needed */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret < 0) { XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; @@ -8697,7 +8705,7 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, return ret; } - oriTypeLenSz = SetLength(oriTypeSz, oriTypeLen); + oriTypeLenSz = (int)SetLength(oriTypeSz, oriTypeLen); recipSeqSz = SetImplicit(ASN_SEQUENCE, 4, 1 + oriTypeLenSz + oriTypeSz + oriValueSz, recipSeq, 0); @@ -8734,7 +8742,7 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, (void)options; - return idx; + return (int)idx; } #if !defined(NO_PWDBASED) && !defined(NO_SHA) @@ -8754,8 +8762,8 @@ static int wc_PKCS7_GenerateKEK_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, case PBKDF2_OID: - ret = wc_PBKDF2(out, passwd, pLen, salt, saltSz, iterations, - outSz, prfOID); + ret = wc_PBKDF2(out, passwd, (int)pLen, salt, saltSz, iterations, + (int)outSz, prfOID); if (ret != 0) { return ret; } @@ -8806,7 +8814,7 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, /* if user set out to NULL, give back required length */ if (out == NULL) { - *outSz = outLen; + *outSz = (word32)outLen; return LENGTH_ONLY_E; } @@ -8829,21 +8837,21 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, if (ret == 0) { /* encrypt, normal */ - ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, kekSz, - (byte*)iv, ivSz, NULL, 0, NULL, 0, out, + ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, + (byte*)iv, (int)ivSz, NULL, 0, NULL, 0, out, outLen, out); } if (ret == 0) { /* encrypt again, using last ciphertext block as IV */ lastBlock = out + (((outLen / blockSz) - 1) * blockSz); - ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, kekSz, + ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, lastBlock, blockSz, NULL, 0, NULL, 0, out, outLen, out); } if (ret == 0) { - *outSz = outLen; + *outSz = (word32)outLen; } else { outLen = ret; } @@ -8899,21 +8907,21 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(PKCS7* pkcs7, const byte* kek, tmpIv = lastBlock - blockSz; /* decrypt last block */ - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, tmpIv, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, tmpIv, blockSz, NULL, 0, NULL, 0, lastBlock, blockSz, outTmp + inSz - blockSz, pkcs7->devId, pkcs7->heap); if (ret == 0) { /* using last decrypted block as IV, decrypt [0 ... n-1] blocks */ lastBlock = outTmp + inSz - blockSz; - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, lastBlock, blockSz, NULL, 0, NULL, 0, (byte*)in, inSz - blockSz, outTmp, pkcs7->devId, pkcs7->heap); } if (ret == 0) { /* decrypt using original kek and iv */ - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, (byte*)iv, ivSz, NULL, 0, NULL, 0, outTmp, inSz, outTmp, pkcs7->devId, pkcs7->heap); } @@ -9035,12 +9043,12 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, return kekBlockSz; /* generate random CEK */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, cekKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)cekKeySz); if (ret < 0) return ret; /* generate random IV */ - ret = wc_PKCS7_GenerateBlock(pkcs7, NULL, tmpIv, kekBlockSz); + ret = wc_PKCS7_GenerateBlock(pkcs7, NULL, tmpIv, (word32)kekBlockSz); if (ret != 0) return ret; @@ -9072,7 +9080,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, /* generate KEK: expand password into KEK */ ret = wc_PKCS7_GenerateKEK_PWRI(pkcs7, passwd, pLen, salt, saltSz, kdfOID, hashOID, iterations, kek, - kekKeySz); + (word32)kekKeySz); if (ret < 0) { XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -9081,23 +9089,23 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, } /* generate encrypted key: encrypt CEK with KEK */ - ret = wc_PKCS7_PwriKek_KeyWrap(pkcs7, kek, kekKeySz, pkcs7->cek, + ret = wc_PKCS7_PwriKek_KeyWrap(pkcs7, kek, (word32)kekKeySz, pkcs7->cek, pkcs7->cekSz, encryptedKey, &encryptedKeySz, - tmpIv, kekBlockSz, encryptOID); + tmpIv, (word32)kekBlockSz, encryptOID); if (ret < 0) { XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - encryptedKeySz = ret; + encryptedKeySz = (word32)ret; /* put together encrypted key OCTET STRING */ encKeyOctetStrSz = SetOctetString(encryptedKeySz, encKeyOctetStr); totalSz += (encKeyOctetStrSz + encryptedKeySz); /* put together IV OCTET STRING */ - ivOctetStringSz = SetOctetString(kekBlockSz, ivOctetString); + ivOctetStringSz = SetOctetString((word32)kekBlockSz, ivOctetString); totalSz += (ivOctetStringSz + kekBlockSz); /* set PWRIAlgorithms AlgorithmIdentifier, adding (ivOctetStringSz + @@ -9114,7 +9122,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - keyEncAlgoIdSz = ret; + keyEncAlgoIdSz = (word32)ret; totalSz += keyEncAlgoIdSz; /* KeyEncryptionAlgorithm SEQ */ @@ -9128,7 +9136,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, totalSz += (kdfSaltOctetStrSz + saltSz); /* set KDF iteration count */ - kdfIterationsSz = SetMyVersion(iterations, kdfIterations, 0); + kdfIterationsSz = (word32)SetMyVersion((word32)iterations, kdfIterations, 0); totalSz += kdfIterationsSz; /* set KDF params SEQ */ @@ -9144,7 +9152,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - kdfAlgoIdSz = ret; + kdfAlgoIdSz = (word32)ret; totalSz += kdfAlgoIdSz; /* set KeyDerivationAlgorithmIdentifier EXPLICIT [0] SEQ */ @@ -9154,7 +9162,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, totalSz += kdfAlgoIdSeqSz; /* set PasswordRecipientInfo CMSVersion, MUST be 0 */ - verSz = SetMyVersion(0, ver, 0); + verSz = (word32)SetMyVersion(0, ver, 0); totalSz += verSz; recip->recipVersion = 0; @@ -9202,7 +9210,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, XMEMCPY(recip->recip + idx, encryptedKey, encryptedKeySz); idx += encryptedKeySz; - ForceZero(kek, kekBlockSz); + ForceZero(kek, (word32)kekBlockSz); ForceZero(encryptedKey, encryptedKeySz); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -9224,7 +9232,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, (void)options; - return idx; + return (int)idx; } /* Import password and KDF settings into a PKCS7 structure. Used for setting @@ -9315,7 +9323,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, } /* generate random content encryption key, if needed */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret < 0) { XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; @@ -9340,7 +9348,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, #endif encryptedKeySz = wc_PKCS7_KeyWrap(pkcs7->cek, pkcs7->cekSz, kek, kekSz, - encryptedKey, encryptedKeySz, keyWrapOID, + encryptedKey, (word32)encryptedKeySz, keyWrapOID, direction); if (encryptedKeySz < 0) { #ifdef WOLFSSL_SMALL_STACK @@ -9358,7 +9366,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, return WC_KEY_SIZE_E; } - encKeyOctetStrSz = SetOctetString(encryptedKeySz, encKeyOctetStr); + encKeyOctetStrSz = SetOctetString((word32)encryptedKeySz, encKeyOctetStr); totalSz += (encKeyOctetStrSz + encryptedKeySz); /* KeyEncryptionAlgorithmIdentifier */ @@ -9397,7 +9405,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, totalSz += kekIdSeqSz; /* version */ - verSz = SetMyVersion(4, ver, 0); + verSz = (word32)SetMyVersion(4, ver, 0); totalSz += verSz; recip->recipVersion = 4; @@ -9464,7 +9472,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, (void)options; - return idx; + return (int)idx; } @@ -9583,7 +9591,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } /* generate random content encryption key */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret != 0) { return ret; } @@ -9626,7 +9634,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) WOLFSSL_MSG("You must add at least one CMS recipient"); return PKCS7_RECIP_E; } - recipSetSz = SetSet(recipSz, recipSet); + recipSetSz = (int)SetSet((word32)recipSz, recipSet); /* version, defined in Section 6.1 of RFC 5652 */ kariVersion = wc_PKCS7_GetCMSVersion(pkcs7, ENVELOPED_DATA); @@ -9636,7 +9644,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) return PKCS7_RECIP_E; } - verSz = SetMyVersion(kariVersion, ver, 0); + verSz = SetMyVersion((word32)kariVersion, ver, 0); ret = wc_InitRng_ex(&rng, pkcs7->heap, pkcs7->devId); if (ret != 0) { @@ -9645,7 +9653,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } /* generate IV for block cipher */ - ret = wc_PKCS7_GenerateBlock(pkcs7, &rng, tmpIv, blockSz); + ret = wc_PKCS7_GenerateBlock(pkcs7, &rng, tmpIv, (word32)blockSz); wc_FreeRng(&rng); if (ret != 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); @@ -9663,7 +9671,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) contentTypeSz = ret; /* allocate encrypted content buffer and PKCS#7 padding */ - padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, blockSz); + padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, (word32)blockSz); if (padSz < 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); return padSz; @@ -9682,7 +9690,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, - encryptedOutSz, blockSz); + (word32)encryptedOutSz, blockSz); if (ret < 0) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); @@ -9705,11 +9713,11 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } /* put together IV OCTET STRING */ - ivOctetStringSz = SetOctetString(blockSz, ivOctetString); + ivOctetStringSz = (int)SetOctetString((word32)blockSz, ivOctetString); /* build up our ContentEncryptionAlgorithmIdentifier sequence, * adding (ivOctetStringSz + blockSz) for IV OCTET STRING */ - contentEncAlgoSz = SetAlgoID(pkcs7->encryptOID, contentEncAlgo, + contentEncAlgoSz = (int)SetAlgoID(pkcs7->encryptOID, contentEncAlgo, oidBlkType, ivOctetStringSz + blockSz); if (contentEncAlgoSz == 0) { @@ -9719,9 +9727,9 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) return BAD_FUNC_ARG; } - encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0, encryptedOutSz, + encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, encContentOctet, pkcs7->encodeStream); - encContentSeqSz = SetSequenceEx(contentTypeSz + contentEncAlgoSz + + encContentSeqSz = (int)SetSequenceEx(contentTypeSz + contentEncAlgoSz + ivOctetStringSz + blockSz + encContentOctetSz + encryptedOutSz, encContentSeq, pkcs7->encodeStream); @@ -9743,10 +9751,10 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) totalSz += ASN_INDEF_END_SZ; /* account for asn1 syntax around octet strings */ - StreamOctetString(NULL, encryptedOutSz, NULL, &streamSz, &tmpIdx); + StreamOctetString(NULL, (word32)encryptedOutSz, NULL, &streamSz, &tmpIdx); totalSz += (streamSz - encryptedOutSz); - /* resize encrytped content buffer */ + /* resize encrypted content buffer */ if (encryptedContent != NULL) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); encryptedContent = (byte*)XMALLOC(streamSz, pkcs7->heap, @@ -9759,7 +9767,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } } #endif - envDataSeqSz = SetSequenceEx(totalSz, envDataSeq, pkcs7->encodeStream); + envDataSeqSz = (int)SetSequenceEx((word32)totalSz, envDataSeq, pkcs7->encodeStream); totalSz += envDataSeqSz; #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { @@ -9768,7 +9776,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) #endif /* outer content */ - outerContentSz = SetExplicit(0, totalSz, outerContent, pkcs7->encodeStream); + outerContentSz = (int)SetExplicit(0, (word32)totalSz, outerContent, pkcs7->encodeStream); #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { totalSz += ASN_INDEF_END_SZ; @@ -9779,7 +9787,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) if (pkcs7->contentOID != FIRMWARE_PKG_DATA) { /* ContentInfo */ - contentInfoSeqSz = SetSequenceEx(totalSz, contentInfoSeq, + contentInfoSeqSz = (int)SetSequenceEx((word32)totalSz, contentInfoSeq, pkcs7->encodeStream); totalSz += contentInfoSeqSz; #ifdef ASN_BER_TO_DER @@ -9804,24 +9812,24 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* begin writing out PKCS7 bundle */ if (pkcs7->contentOID != FIRMWARE_PKG_DATA) { wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - contentInfoSeq, contentInfoSeqSz); + contentInfoSeq, (word32)contentInfoSeqSz); idx += contentInfoSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - outerContentType, outerContentTypeSz); + outerContentType, (word32)outerContentTypeSz); idx += outerContentTypeSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - outerContent, outerContentSz); + outerContent, (word32)outerContentSz); idx += outerContentSz; } wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - envDataSeq, envDataSeqSz); + envDataSeq, (word32)envDataSeqSz); idx += envDataSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - ver, verSz); + ver, (word32)verSz); idx += verSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - recipSet, recipSetSz); + recipSet, (word32)recipSetSz); idx += recipSetSz; /* copy in recipients from list */ tmpRecip = pkcs7->recipList; @@ -9834,22 +9842,22 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) wc_PKCS7_FreeEncodedRecipientSet(pkcs7); wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - encContentSeq, encContentSeqSz); + encContentSeq, (word32)encContentSeqSz); idx += encContentSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - contentType, contentTypeSz); + contentType, (word32)contentTypeSz); idx += contentTypeSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - contentEncAlgo, contentEncAlgoSz); + contentEncAlgo, (word32)contentEncAlgoSz); idx += contentEncAlgoSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - ivOctetString, ivOctetStringSz); + ivOctetString, (word32)ivOctetStringSz); idx += ivOctetStringSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - tmpIv, blockSz); + tmpIv, (word32)blockSz); idx += blockSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - encContentOctet, encContentOctetSz); + encContentOctet, (word32)encContentOctetSz); idx += encContentOctetSz; /* encrypt content */ @@ -10035,7 +10043,7 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, return ret; } - pkcs7->stream->expected = sz + MAX_ALGO_SZ + ASN_TAG_SZ + + pkcs7->stream->expected = (word32)sz + MAX_ALGO_SZ + ASN_TAG_SZ + MAX_LENGTH_SZ; if (pkcs7->stream->length > 0 && pkcs7->stream->length < pkcs7->stream->expected) { @@ -10050,7 +10058,7 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, if (GetSequence(pkiMsg, idx, &length, pkiMsgSz) < 0) return ASN_PARSE_E; - if (GetNameHash_ex(pkiMsg, idx, issuerHash, pkiMsgSz, + if (GetNameHash_ex(pkiMsg, idx, issuerHash, (int)pkiMsgSz, pkcs7->publicKeyOID) < 0) return ASN_PARSE_E; @@ -10156,8 +10164,8 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, idx)) != 0) { break; } - wc_PKCS7_StreamStoreVar(pkcs7, encryptedKeySz, sidType, version); - pkcs7->stream->expected = encryptedKeySz; + wc_PKCS7_StreamStoreVar(pkcs7, (word32)encryptedKeySz, sidType, version); + pkcs7->stream->expected = (word32)encryptedKeySz; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_DECRYPT_KTRI_3); FALL_THROUGH; @@ -10168,7 +10176,7 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, pkcs7->stream->expected, &pkiMsg, idx)) != 0) { return ret; } - encryptedKeySz = pkcs7->stream->expected; + encryptedKeySz = (int)pkcs7->stream->expected; #endif /* Always allocate to ensure aligned use with RSA */ @@ -10239,12 +10247,12 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, if (encOID != RSAESOAEPk) { #endif keySz = wc_RsaPrivateDecryptInline(encryptedKey, - encryptedKeySz, &outKey, + (word32)encryptedKeySz, &outKey, privKey); #ifndef WC_NO_RSA_OAEP } else { - word32 outLen = wc_RsaEncryptSize(privKey); + word32 outLen = (word32)wc_RsaEncryptSize(privKey); outKey = (byte*)XMALLOC(outLen, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (!outKey) { @@ -10261,14 +10269,14 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, } keySz = wc_RsaPrivateDecrypt_ex(encryptedKey, - encryptedKeySz, outKey, outLen, privKey, + (word32)encryptedKeySz, outKey, outLen, privKey, WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA, WC_MGF1SHA1, NULL, 0); } #endif } #ifdef WOLFSSL_ASYNC_CRYPT - } while (keySz == WC_PENDING_E); + } while (keySz == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif #ifdef WC_RSA_BLINDING wc_FreeRng(&rng); @@ -10279,7 +10287,7 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, wc_FreeRsaKey(privKey); if (keySz <= 0 || outKey == NULL) { - ForceZero(encryptedKey, encryptedKeySz); + ForceZero(encryptedKey, (word32)encryptedKeySz); XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_WOLF_BIGINT); #ifdef WOLFSSL_SMALL_STACK XFREE(privKey, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -10293,9 +10301,9 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, #endif return keySz; } else { - *decryptedKeySz = keySz; + *decryptedKeySz = (word32)keySz; XMEMCPY(decryptedKey, outKey, keySz); - ForceZero(encryptedKey, encryptedKeySz); + ForceZero(encryptedKey, (word32)encryptedKeySz); } XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_WOLF_BIGINT); @@ -10470,7 +10478,7 @@ static int wc_PKCS7_KariGetUserKeyingMaterial(WC_PKCS7_KARI* kari, } (*idx) += length; - kari->ukmSz = length; + kari->ukmSz = (word32)length; return 0; } @@ -10603,7 +10611,7 @@ static int wc_PKCS7_KariGetIssuerAndSerialNumber(WC_PKCS7_KARI* kari, if (GetSequence(pkiMsg, idx, &length, pkiMsgSz) < 0) return ASN_PARSE_E; - if (GetNameHash_ex(pkiMsg, idx, rid, pkiMsgSz, + if (GetNameHash_ex(pkiMsg, idx, rid, (int)pkiMsgSz, kari->decoded->signatureOID) < 0) { return ASN_PARSE_E; } @@ -10994,14 +11002,14 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, return ASN_PARSE_E; } - blockSz = wc_PKCS7_GetOIDBlockSize(pwriEncAlgoId); + blockSz = wc_PKCS7_GetOIDBlockSize((int)pwriEncAlgoId); if (blockSz < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return blockSz; } /* get content-encryption key size, based on algorithm */ - kekKeySz = wc_PKCS7_GetOIDKeySize(pwriEncAlgoId); + kekKeySz = wc_PKCS7_GetOIDKeySize((int)pwriEncAlgoId); if (kekKeySz < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return kekKeySz; @@ -11049,7 +11057,7 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } /* allocate temporary space for decrypted key */ - cekSz = length; + cekSz = (word32)length; cek = (byte*)XMALLOC(cekSz, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (cek == NULL) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11065,8 +11073,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } ret = wc_PKCS7_GenerateKEK_PWRI(pkcs7, pkcs7->pass, pkcs7->passSz, - salt, saltSz, kdfAlgoId, hashOID, - iterations, kek, kekKeySz); + salt, (word32)saltSz, kdfAlgoId, hashOID, + iterations, kek, (word32)kekKeySz); if (ret < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11075,17 +11083,17 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } /* decrypt CEK with KEK */ - ret = wc_PKCS7_PwriKek_KeyUnWrap(pkcs7, kek, kekKeySz, - pkiMsg + (*idx), length, cek, - cekSz, tmpIv, blockSz, - pwriEncAlgoId); + ret = wc_PKCS7_PwriKek_KeyUnWrap(pkcs7, kek, (word32)kekKeySz, + pkiMsg + (*idx), (word32)length, cek, + cekSz, tmpIv, (word32)blockSz, + (int)pwriEncAlgoId); if (ret < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(cek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - cekSz = ret; + cekSz = (word32)ret; if (*decryptedKeySz < cekSz) { WOLFSSL_MSG("Decrypted key buffer too small for CEK"); @@ -11158,7 +11166,7 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, if (GetSequence(pkiMsg, idx, &length, pkiMsgSz) < 0) return ASN_PARSE_E; - kekIdSz = length; + kekIdSz = (word32)length; if (GetASNTag(pkiMsg, idx, &tag, pkiMsgSz) < 0) return ASN_PARSE_E; @@ -11171,14 +11179,14 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, /* save keyIdentifier and length */ keyId = pkiMsg + *idx; - keyIdSz = length; + keyIdSz = (word32)length; *idx += keyIdSz; /* may have OPTIONAL GeneralizedTime */ localIdx = *idx; if ((*idx < kekIdSz) && GetASNTag(pkiMsg, &localIdx, &tag, pkiMsgSz) == 0 && tag == ASN_GENERALIZED_TIME) { - if (wc_GetDateInfo(pkiMsg + *idx, pkiMsgSz, &datePtr, &dateFormat, + if (wc_GetDateInfo(pkiMsg + *idx, (int)pkiMsgSz, &datePtr, &dateFormat, &dateLen) != 0) { return ASN_PARSE_E; } @@ -11227,15 +11235,15 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, /* decrypt CEK with KEK */ if (pkcs7->wrapCEKCb) { - keySz = pkcs7->wrapCEKCb(pkcs7, pkiMsg + *idx, length, keyId, + keySz = pkcs7->wrapCEKCb(pkcs7, pkiMsg + *idx, (word32)length, keyId, keyIdSz, NULL, 0, decryptedKey, - *decryptedKeySz, keyWrapOID, + *decryptedKeySz, (int)keyWrapOID, (int)PKCS7_KEKRI, direction); } else { - keySz = wc_PKCS7_KeyWrap(pkiMsg + *idx, length, pkcs7->privateKey, + keySz = wc_PKCS7_KeyWrap(pkiMsg + *idx, (word32)length, pkcs7->privateKey, pkcs7->privateKeySz, decryptedKey, *decryptedKeySz, - keyWrapOID, direction); + (int)keyWrapOID, direction); } if (keySz <= 0) return keySz; @@ -11378,7 +11386,7 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, /* if user has not explicitly set keyAgreeOID, set from one in bundle */ if (pkcs7->keyAgreeOID == 0) - pkcs7->keyAgreeOID = keyAgreeOID; + pkcs7->keyAgreeOID = (int)keyAgreeOID; /* set direction based on key wrap algorithm */ switch (keyWrapOID) { @@ -11430,7 +11438,7 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, PRIVATE_KEY_UNLOCK(); ret = wc_ecc_export_x963(kari->senderKey, NULL, &tmpKeySz); PRIVATE_KEY_LOCK(); - if (ret != LENGTH_ONLY_E) { + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } @@ -11456,10 +11464,10 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, } tmpKeySz = (word32)ret; - keySz = pkcs7->wrapCEKCb(pkcs7, encryptedKey, encryptedKeySz, - rid, keyIdSize, tmpKeyDer, tmpKeySz, + keySz = pkcs7->wrapCEKCb(pkcs7, encryptedKey, (word32)encryptedKeySz, + rid, (word32)keyIdSize, tmpKeyDer, tmpKeySz, decryptedKey, *decryptedKeySz, - keyWrapOID, (int)PKCS7_KARI, direction); + (int)keyWrapOID, (int)PKCS7_KARI, direction); XFREE(tmpKeyDer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (keySz > 0) { @@ -11472,7 +11480,7 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, } else { /* create KEK */ - ret = wc_PKCS7_KariGenerateKEK(kari, pkcs7->rng, keyWrapOID, + ret = wc_PKCS7_KariGenerateKEK(kari, pkcs7->rng, (int)keyWrapOID, pkcs7->keyAgreeOID); if (ret != 0) { wc_PKCS7_KariFree(kari); @@ -11483,9 +11491,9 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, } /* decrypt CEK with KEK */ - keySz = wc_PKCS7_KeyWrap(encryptedKey, encryptedKeySz, kari->kek, + keySz = wc_PKCS7_KeyWrap(encryptedKey, (word32)encryptedKeySz, kari->kek, kari->kekSz, decryptedKey, *decryptedKeySz, - keyWrapOID, direction); + (int)keyWrapOID, direction); } if (keySz <= 0) { wc_PKCS7_KariFree(kari); @@ -11857,7 +11865,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(PKCS7* pkcs7, byte* in, len = 0; ret = wc_BerToDer(pkiMsg, pkiMsgSz, NULL, &len); - if (ret != LENGTH_ONLY_E) + if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; pkcs7->der = (byte*)XMALLOC(len, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->der == NULL) @@ -11960,7 +11968,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(PKCS7* pkcs7, byte* in, break; } - pkcs7->stream->varOne = version; + pkcs7->stream->varOne = (word32)version; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_INFOSET_END); FALL_THROUGH; @@ -11972,7 +11980,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(PKCS7* pkcs7, byte* in, return ret; } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; - version = pkcs7->stream->varOne; + version = (int)pkcs7->stream->varOne; #endif if (type == ENVELOPED_DATA) { @@ -12220,7 +12228,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, } if (ret == 0) { - pkcs7->contentOID = contentType; + pkcs7->contentOID = (int)contentType; } if (ret == 0 && GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, @@ -12228,12 +12236,12 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; } - blockKeySz = wc_PKCS7_GetOIDKeySize(encOID); + blockKeySz = wc_PKCS7_GetOIDKeySize((int)encOID); if (ret == 0 && blockKeySz < 0) { ret = blockKeySz; } - expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + expBlockSz = wc_PKCS7_GetOIDBlockSize((int)encOID); if (ret == 0 && expBlockSz < 0) { ret = expBlockSz; } @@ -12264,8 +12272,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, break; } wc_PKCS7_StreamStoreVar(pkcs7, encOID, expBlockSz, length); - pkcs7->stream->contentSz = blockKeySz; - pkcs7->stream->expected = length + MAX_LENGTH_SZ + MAX_LENGTH_SZ + + pkcs7->stream->contentSz = (word32)blockKeySz; + pkcs7->stream->expected = (word32)length + MAX_LENGTH_SZ + MAX_LENGTH_SZ + ASN_TAG_SZ + ASN_TAG_SZ; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_ENV_4); @@ -12320,7 +12328,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; } - pkcs7->stream->expected = encryptedContentTotalSz; + pkcs7->stream->expected = (word32)encryptedContentTotalSz; wc_PKCS7_StreamGetVar(pkcs7, &encOID, &expBlockSz, 0); wc_PKCS7_StreamStoreVar(pkcs7, encOID, expBlockSz, explicitOctet); #endif @@ -12337,12 +12345,12 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, wc_PKCS7_StreamGetVar(pkcs7, &encOID, &expBlockSz, &explicitOctet); tmpIv = pkcs7->stream->tmpIv; - encryptedContentTotalSz = pkcs7->stream->expected; + encryptedContentTotalSz = (int)pkcs7->stream->expected; /* restore decrypted key */ decryptedKey = pkcs7->stream->aad; decryptedKeySz = pkcs7->stream->aadSz; - blockKeySz = pkcs7->stream->contentSz; + blockKeySz = (int)pkcs7->stream->contentSz; #else ret = 0; #endif @@ -12369,7 +12377,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, if (ret == 0) { ret = PKCS7_CacheEncryptedContent(pkcs7, &pkiMsg[idx], - encryptedContentSz); + (word32)encryptedContentSz); } if (ret != 0) { @@ -12387,7 +12395,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, } else { /* cache encrypted content, no OCTET STRING */ ret = PKCS7_CacheEncryptedContent(pkcs7, &pkiMsg[idx], - encryptedContentTotalSz); + (word32)encryptedContentTotalSz); if (ret != 0) { break; } @@ -12396,10 +12404,10 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, /* use cached content */ encryptedContent = pkcs7->cachedEncryptedContent; - encryptedContentSz = pkcs7->cachedEncryptedContentSz; + encryptedContentSz = (int)pkcs7->cachedEncryptedContentSz; /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, encOID, decryptedKey, + ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, decryptedKey, blockKeySz, tmpIv, expBlockSz, NULL, 0, NULL, 0, encryptedContent, encryptedContentSz, encryptedContent, pkcs7->devId, pkcs7->heap); @@ -12442,7 +12450,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, } #ifndef NO_PKCS7_STREAM - if (ret < 0 && ret != WC_PKCS7_WANT_READ_E) { + if (ret < 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { wc_PKCS7_ResetStream(pkcs7); wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_START); if (pkcs7->cachedEncryptedContent != NULL) { @@ -12594,7 +12602,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, verSz = SetMyVersion(0, ver, 0); /* generate random content encryption key */ - ret = PKCS7_GenerateContentEncryptionKey(pkcs7, blockKeySz); + ret = PKCS7_GenerateContentEncryptionKey(pkcs7, (word32)blockKeySz); if (ret != 0) { return ret; } @@ -12637,7 +12645,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, WOLFSSL_MSG("You must add at least one CMS recipient"); return PKCS7_RECIP_E; } - recipSetSz = SetSet(recipSz, recipSet); + recipSetSz = (int)SetSet((word32)recipSz, recipSet); /* generate random nonce and IV for encryption */ switch (pkcs7->encryptOID) { @@ -12709,7 +12717,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, sizeof(contentTypeValue)); if (ret > 0) { contentTypeAttrib.value = contentTypeValue; - contentTypeAttrib.valueSz = ret; + contentTypeAttrib.valueSz = (word32)ret; /* otherwise, try to set from custom content type */ } else { @@ -12747,7 +12755,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, } ret = FlattenAttributes(pkcs7, flatAuthAttribs, authAttribs, - authAttribsCount); + (int)authAttribsCount); if (ret != 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -12799,7 +12807,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, } FlattenAttributes(pkcs7, flatUnauthAttribs, unauthAttribs, - unauthAttribsCount); + (int)unauthAttribsCount); unauthAttribsSetSz = SetImplicit(ASN_SET, 2, unauthAttribsSz, unauthAttribSet, 0); } @@ -12807,7 +12815,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* AES-GCM/CCM does NOT require padding for plaintext content or * AAD inputs RFC 5084 section 3.1 and 3.2, but we must alloc * full blocks to ensure crypto only gets full blocks */ - encryptedOutSz = pkcs7->contentSz; + encryptedOutSz = (int)pkcs7->contentSz; encryptedAllocSz = (encryptedOutSz % blockSz) ? encryptedOutSz + blockSz - (encryptedOutSz % blockSz) : @@ -12885,10 +12893,10 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, contentTypeSz = ret; /* put together nonce OCTET STRING */ - nonceOctetStringSz = SetOctetString(nonceSz, nonceOctetString); + nonceOctetStringSz = (int)SetOctetString(nonceSz, nonceOctetString); /* put together aes-ICVlen INTEGER */ - macIntSz = SetMyVersion(sizeof(authTag), macInt, 0); + macIntSz = (word32)SetMyVersion(sizeof(authTag), macInt, 0); /* add nonce and icv len into parameters string RFC5084 */ algoParamSeqSz = SetSequence(nonceOctetStringSz + nonceSz + macIntSz, @@ -12897,7 +12905,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* build up our ContentEncryptionAlgorithmIdentifier sequence, * adding (nonceOctetStringSz + blockSz + macIntSz) for nonce OCTET STRING * and tag size */ - contentEncAlgoSz = SetAlgoID(pkcs7->encryptOID, contentEncAlgo, + contentEncAlgoSz = (int)SetAlgoID(pkcs7->encryptOID, contentEncAlgo, oidBlkType, nonceOctetStringSz + nonceSz + macIntSz + algoParamSeqSz); @@ -12911,14 +12919,14 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, return BAD_FUNC_ARG; } - encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0, encryptedOutSz, + encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, encContentOctet, 0); - encContentSeqSz = SetSequence(contentTypeSz + contentEncAlgoSz + + encContentSeqSz = (int)SetSequence(contentTypeSz + contentEncAlgoSz + nonceOctetStringSz + nonceSz + macIntSz + algoParamSeqSz + encContentOctetSz + encryptedOutSz, encContentSeq); - macOctetStringSz = SetOctetString(sizeof(authTag), macOctetString); + macOctetStringSz = (int)SetOctetString(sizeof(authTag), macOctetString); /* keep track of sizes for outer wrapper layering */ totalSz = verSz + recipSetSz + recipSz + encContentSeqSz + contentTypeSz + @@ -12928,16 +12936,16 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, sizeof(authTag) + unauthAttribsSz + unauthAttribsSetSz; /* EnvelopedData */ - envDataSeqSz = SetSequence(totalSz, envDataSeq); + envDataSeqSz = (int)SetSequence((word32)totalSz, envDataSeq); totalSz += envDataSeqSz; /* outer content */ - outerContentSz = SetExplicit(0, totalSz, outerContent, 0); + outerContentSz = (int)SetExplicit(0, (word32)totalSz, outerContent, 0); totalSz += outerContentTypeSz; totalSz += outerContentSz; /* ContentInfo */ - contentInfoSeqSz = SetSequence(totalSz, contentInfoSeq); + contentInfoSeqSz = (int)SetSequence((word32)totalSz, contentInfoSeq); totalSz += contentInfoSeqSz; if (totalSz > (int)outputSz) { @@ -13183,7 +13191,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } if (ret == 0) { - pkcs7->contentOID = contentType; + pkcs7->contentOID = (int)contentType; } if (ret == 0 && GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, @@ -13192,14 +13200,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } if (ret == 0) { - blockKeySz = wc_PKCS7_GetOIDKeySize(encOID); + blockKeySz = wc_PKCS7_GetOIDKeySize((int)encOID); if (blockKeySz < 0) { ret = blockKeySz; } } if (ret == 0) { - expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + expBlockSz = wc_PKCS7_GetOIDBlockSize((int)encOID); if (expBlockSz < 0) { ret = expBlockSz; } @@ -13315,7 +13323,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* store nonce for later */ if (nonceSz > 0) { - pkcs7->stream->nonceSz = nonceSz; + pkcs7->stream->nonceSz = (word32)nonceSz; pkcs7->stream->nonce = (byte*)XMALLOC(nonceSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->stream->nonce == NULL) { @@ -13327,7 +13335,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } } - pkcs7->stream->expected = encryptedContentSz; + pkcs7->stream->expected = (word32)encryptedContentSz; wc_PKCS7_StreamStoreVar(pkcs7, encOID, blockKeySz, encryptedContentSz); #endif @@ -13344,7 +13352,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; - encryptedContentSz = pkcs7->stream->expected; + encryptedContentSz = (int)pkcs7->stream->expected; #else pkiMsgSz = inSz; #endif @@ -13356,7 +13364,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, if (encOID == 0) expBlockSz = 1; else { - expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID); + expBlockSz = wc_PKCS7_GetOIDBlockSize((int)encOID); if (expBlockSz < 0) { ret = expBlockSz; break; @@ -13397,7 +13405,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) <= 0) ret = ASN_PARSE_E; #ifndef NO_PKCS7_STREAM - pkcs7->stream->expected = length; + pkcs7->stream->expected = (word32)length; #endif encodedAttribSz = length + (idx - encodedAttribIdx); @@ -13442,7 +13450,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, return ret; } - length = pkcs7->stream->expected; + length = (int)pkcs7->stream->expected; encodedAttribs = pkcs7->stream->aad; #endif @@ -13530,7 +13538,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* store tag for later */ if (authTagSz > 0) { - pkcs7->stream->tagSz = authTagSz; + pkcs7->stream->tagSz = (word32)authTagSz; pkcs7->stream->tag = (byte*)XMALLOC(authTagSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->stream->tag == NULL) { @@ -13555,7 +13563,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* restore all variables needed */ if (pkcs7->stream->nonceSz > 0) { - nonceSz = pkcs7->stream->nonceSz; + nonceSz = (int)pkcs7->stream->nonceSz; if (nonceSz > GCM_NONCE_MID_SZ) { WOLFSSL_MSG("PKCS7 saved nonce is too large"); ret = BUFFER_E; @@ -13567,7 +13575,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } if (pkcs7->stream->tagSz > 0) { - authTagSz = pkcs7->stream->tagSz; + authTagSz = (int)pkcs7->stream->tagSz; if (authTagSz > AES_BLOCK_SIZE) { WOLFSSL_MSG("PKCS7 saved tag is too large"); ret = BUFFER_E; @@ -13592,9 +13600,9 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #endif /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, encOID, decryptedKey, + ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, decryptedKey, blockKeySz, nonce, nonceSz, encodedAttribs, encodedAttribSz, - authTag, authTagSz, encryptedContent, encryptedContentSz, + authTag, (word32)authTagSz, encryptedContent, encryptedContentSz, encryptedContent, pkcs7->devId, pkcs7->heap); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13610,7 +13618,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, XMEMCPY(output, encryptedContent, encryptedContentSz); /* free memory, zero out keys */ - ForceZero(encryptedContent, encryptedContentSz); + ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); #ifdef WOLFSSL_SMALL_STACK @@ -13632,7 +13640,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } #ifdef WOLFSSL_SMALL_STACK - if (ret != 0 && ret != WC_PKCS7_WANT_READ_E) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { if (decryptedKey != NULL) { ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); } @@ -13640,7 +13648,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } #endif #ifndef NO_PKCS7_STREAM - if (ret != 0 && ret != WC_PKCS7_WANT_READ_E) { + if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { wc_PKCS7_ResetStream(pkcs7); } #endif @@ -13739,7 +13747,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) if (blockSz < 0) return blockSz; - padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, blockSz); + padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, (word32)blockSz); if (padSz < 0) return padSz; @@ -13751,7 +13759,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) return MEMORY_E; ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, - encryptedOutSz, blockSz); + (word32)encryptedOutSz, blockSz); if (ret < 0) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; @@ -13765,11 +13773,11 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) } /* put together IV OCTET STRING */ - ivOctetStringSz = SetOctetString(blockSz, ivOctetString); + ivOctetStringSz = (int)SetOctetString((word32)blockSz, ivOctetString); /* build up ContentEncryptionAlgorithmIdentifier sequence, adding (ivOctetStringSz + blockSz) for IV OCTET STRING */ - contentEncAlgoSz = SetAlgoID(pkcs7->encryptOID, contentEncAlgo, + contentEncAlgoSz = (int)SetAlgoID(pkcs7->encryptOID, contentEncAlgo, oidBlkType, ivOctetStringSz + blockSz); if (contentEncAlgoSz == 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13779,7 +13787,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* encrypt content */ WOLFSSL_MSG("Encrypting the content"); - ret = wc_PKCS7_GenerateBlock(pkcs7, NULL, tmpIv, blockSz); + ret = wc_PKCS7_GenerateBlock(pkcs7, NULL, tmpIv, (word32)blockSz); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13795,10 +13803,10 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) return ret; } - encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0, - encryptedOutSz, encContentOctet, 0); + encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, + (word32)encryptedOutSz, encContentOctet, 0); - encContentSeqSz = SetSequence(contentTypeSz + contentEncAlgoSz + + encContentSeqSz = (int)SetSequence(contentTypeSz + contentEncAlgoSz + ivOctetStringSz + blockSz + encContentOctetSz + encryptedOutSz, encContentSeq); @@ -13834,7 +13842,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) return MEMORY_E; } - ret = FlattenAttributes(pkcs7, flatAttribs, attribs, attribsCount); + ret = FlattenAttributes(pkcs7, flatAttribs, attribs, (int)attribsCount); if (ret != 0) { XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13855,16 +13863,16 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) attribsSz + attribsSetSz; /* EncryptedData */ - encDataSeqSz = SetSequence(totalSz, encDataSeq); + encDataSeqSz = (int)SetSequence((word32)totalSz, encDataSeq); totalSz += encDataSeqSz; if (pkcs7->version != 3) { /* outer content */ - outerContentSz = SetExplicit(0, totalSz, outerContent, 0); + outerContentSz = (int)SetExplicit(0, (word32)totalSz, outerContent, 0); totalSz += outerContentTypeSz; totalSz += outerContentSz; /* ContentInfo */ - contentInfoSeqSz = SetSequence(totalSz, contentInfoSeq); + contentInfoSeqSz = (int)SetSequence((word32)totalSz, contentInfoSeq); totalSz += contentInfoSeqSz; } else { contentInfoSeqSz = 0; @@ -14101,27 +14109,27 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, ret = ASN_PARSE_E; if (ret == 0) { - pkcs7->contentOID = contentType; + pkcs7->contentOID = (int)contentType; } if (ret == 0 && (ret = GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz)) < 0) ret = ASN_PARSE_E; - if (ret == 0 && (expBlockSz = wc_PKCS7_GetOIDBlockSize(encOID)) < 0) + if (ret == 0 && (expBlockSz = wc_PKCS7_GetOIDBlockSize((int)encOID)) < 0) ret = expBlockSz; if (ret != 0) break; #ifndef NO_PKCS7_STREAM /* store expBlockSz for later */ - pkcs7->stream->varOne = expBlockSz; - pkcs7->stream->varTwo = encOID; + pkcs7->stream->varOne = (word32)expBlockSz; + pkcs7->stream->varTwo = (int)encOID; if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; } /* store version for later */ - pkcs7->stream->vers = version; + pkcs7->stream->vers = (word32)version; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_STAGE4); FALL_THROUGH; @@ -14137,7 +14145,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; /* restore saved variables */ - expBlockSz = pkcs7->stream->varOne; + expBlockSz = (int)pkcs7->stream->varOne; #endif if (ret == 0 && GetASNTag(pkiMsg, &idx, &tag, pkiMsgSz) < 0) ret = ASN_PARSE_E; @@ -14155,7 +14163,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, if (ret != 0) break; #ifndef NO_PKCS7_STREAM /* next chunk of data expected should have the IV */ - pkcs7->stream->expected = length; + pkcs7->stream->expected = (word32)length; if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; @@ -14176,7 +14184,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, /* use IV buffer from stream structure */ tmpIv = pkcs7->stream->tmpIv; - length = pkcs7->stream->expected; + length = (int)pkcs7->stream->expected; #endif XMEMCPY(tmpIv, &pkiMsg[idx], length); idx += length; @@ -14221,10 +14229,10 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; /* restore saved variables */ - expBlockSz = pkcs7->stream->varOne; - encOID = pkcs7->stream->varTwo; + expBlockSz = (int)pkcs7->stream->varOne; + encOID = (word32)pkcs7->stream->varTwo; encryptedContentSz = pkcs7->stream->varThree; - version = pkcs7->stream->vers; + version = (int)pkcs7->stream->vers; tmpIv = pkcs7->stream->tmpIv; #endif if (ret == 0 && (encryptedContent = (byte*)XMALLOC( @@ -14238,7 +14246,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, idx += encryptedContentSz; /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, encOID, + ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, pkcs7->encryptionKey, pkcs7->encryptionKeySz, tmpIv, expBlockSz, NULL, 0, NULL, 0, encryptedContent, encryptedContentSz, encryptedContent, @@ -14275,7 +14283,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, ret = wc_PKCS7_DecodeUnprotectedAttributes(pkcs7, pkiMsg, pkiMsgSz, &idx); if (ret != 0) { - ForceZero(encryptedContent, encryptedContentSz); + ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); ret = ASN_PARSE_E; } @@ -14283,7 +14291,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, } if (ret == 0) { - ForceZero(encryptedContent, encryptedContentSz); + ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); /* go back and check the version now that attribs have been processed */ diff --git a/src/wolfcrypt/src/poly1305.c b/src/wolfcrypt/src/poly1305.c index f56b3fd..cde7547 100644 --- a/src/wolfcrypt/src/poly1305.c +++ b/src/wolfcrypt/src/poly1305.c @@ -55,7 +55,7 @@ and Daniel J. Bernstein #pragma warning(disable: 4127) #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP #include #include @@ -70,6 +70,10 @@ and Daniel J. Bernstein #elif defined(__clang__) && defined(NO_AVX2_SUPPORT) #undef NO_AVX2_SUPPORT #endif + #if defined(_MSC_VER) && (_MSC_VER <= 1900) + #undef NO_AVX2_SUPPORT + #define NO_AVX2_SUPPORT + #endif #define HAVE_INTEL_AVX1 #ifndef NO_AVX2_SUPPORT @@ -77,13 +81,12 @@ and Daniel J. Bernstein #endif #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP static word32 intel_flags = 0; static word32 cpu_flags_set = 0; #endif -#if (defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP)) || \ - defined(POLY130564) +#if defined(USE_INTEL_POLY1305_SPEEDUP) || defined(POLY130564) #if defined(_MSC_VER) #define POLY1305_NOINLINE __declspec(noinline) #elif defined(__GNUC__) @@ -123,7 +126,7 @@ static word32 cpu_flags_set = 0; #endif #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP #ifdef __cplusplus extern "C" { #endif @@ -266,7 +269,7 @@ with a given ctx pointer to a Poly1305 structure. static int poly1305_blocks(Poly1305* ctx, const unsigned char *m, size_t bytes) { -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP /* AVX2 is handled in wc_Poly1305Update. */ SAVE_VECTOR_REGISTERS(return _svr_ret;); poly1305_blocks_avx(ctx, m, bytes); @@ -400,7 +403,7 @@ number of bytes is less than the block size. */ static int poly1305_block(Poly1305* ctx, const unsigned char *m) { -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP /* No call to poly1305_block when AVX2, AVX2 does 4 blocks at a time. */ SAVE_VECTOR_REGISTERS(return _svr_ret;); poly1305_block_avx(ctx, m); @@ -415,8 +418,7 @@ static int poly1305_block(Poly1305* ctx, const unsigned char *m) #if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) int wc_Poly1305SetKey(Poly1305* ctx, const byte* key, word32 keySz) { -#if defined(POLY130564) && \ - !(defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP)) +#if defined(POLY130564) && !defined(USE_INTEL_POLY1305_SPEEDUP) word64 t0,t1; #endif @@ -437,7 +439,7 @@ int wc_Poly1305SetKey(Poly1305* ctx, const byte* key, word32 keySz) if (keySz != 32 || ctx == NULL) return BAD_FUNC_ARG; -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP if (!cpu_flags_set) { intel_flags = cpuid_get_flags(); cpu_flags_set = 1; @@ -504,7 +506,7 @@ int wc_Poly1305SetKey(Poly1305* ctx, const byte* key, word32 keySz) int wc_Poly1305Final(Poly1305* ctx, byte* mac) { -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP #elif defined(POLY130564) word64 h0,h1,h2,c; @@ -523,7 +525,7 @@ int wc_Poly1305Final(Poly1305* ctx, byte* mac) if (ctx == NULL || mac == NULL) return BAD_FUNC_ARG; -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP SAVE_VECTOR_REGISTERS(return _svr_ret;); #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) @@ -709,7 +711,7 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) printf("\n"); #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); diff --git a/src/wolfcrypt/src/port/Espressif/esp32_aes.c b/src/wolfcrypt/src/port/Espressif/esp32_aes.c index 84211ee..e8c917c 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -1,6 +1,6 @@ /* esp32_aes.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -48,6 +48,9 @@ static const char* TAG = "wolf_hw_aes"; /* mutex */ static wolfSSL_Mutex aes_mutex; +/* Maximum time to wait for AES HW in FreeRTOS ticks */ +#define WOLFSSL_AES_MUTEX_WAIT 5000 + /* keep track as to whether esp aes is initialized */ static int espaes_CryptHwMutexInit = 0; @@ -86,7 +89,13 @@ static int esp_aes_hw_InUse(void) * of esp_CryptHwMutexLock(&aes_mutex ...) in code */ /* TODO - do we really want to wait? * probably not */ - ret = esp_CryptHwMutexLock(&aes_mutex, portMAX_DELAY); + ret = esp_CryptHwMutexLock(&aes_mutex, WOLFSSL_AES_MUTEX_WAIT); + if (ret == ESP_OK) { + ESP_LOGV(TAG, "esp_CryptHwMutexLock aes success"); + } + else { + ESP_LOGW(TAG, "esp_CryptHwMutexLock aes timeout! %d", ret); + } } else { ESP_LOGE(TAG, "aes engine lock failed."); @@ -597,9 +606,9 @@ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) offset += AES_BLOCK_SIZE; } /* while (blocks--) */ + esp_aes_hw_Leave(); } /* if Set Mode was successful (ret == ESP_OK) */ - esp_aes_hw_Leave(); ESP_LOGV(TAG, "leave wc_esp32AesCbcDecrypt"); return ret; } /* wc_esp32AesCbcDecrypt */ diff --git a/src/wolfcrypt/src/port/Espressif/esp32_mp.c b/src/wolfcrypt/src/port/Espressif/esp32_mp.c index 1afda2b..5c37592 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -1,6 +1,6 @@ /* esp32_mp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -23,15 +23,15 @@ * See ESP32 Technical Reference Manual - RSA Accelerator Chapter * * esp_mp_exptmod() Large Number Modular Exponentiation Z = X^Y mod M - * esp_mp_mulmod() Large Number Modular Multiplication Z = X × Y mod M - * esp_mp_mul() Large Number Multiplication Z = X × Y + * esp_mp_mulmod() Large Number Modular Multiplication Z = X * Y mod M + * esp_mp_mul() Large Number Multiplication Z = X * Y * * The ESP32 RSA Accelerator supports operand lengths of: - * N ∈ {512, 1024, 1536, 2048, 2560, 3072, 3584, 4096} bits. The bit length + * N in {512, 1024, 1536, 2048, 2560, 3072, 3584, 4096} bits. The bit length * of arguments Z, X, Y , M, and r can be any one from the N set, but all * numbers in a calculation must be of the same length. * - * The bit length of M′ is always 32. + * The bit length of M' is always 32. * * Also, beware: "we have uint32_t == unsigned long for both Xtensa and RISC-V" * see https://github.com/espressif/esp-idf/issues/9511#issuecomment-1207342464 @@ -413,7 +413,7 @@ static int esp_mp_hw_lock(void) { /* Note these names are different from those in the documentation! * - * Documenation lists the same names as the ESP32-C3: + * Documentation lists the same names as the ESP32-C3: * * DPORT_REG_SET_BIT((volatile void *)(SYSTEM_PERIP_CLK_EN1_REG), * SYSTEM_CRYPTO_RSA_CLK_EN ); @@ -1285,8 +1285,8 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) Zs = Xs + Ys; /* RSA Accelerator only supports Large Number Multiplication - * with operand length N = 32 × x, - * where x ∈ {1, 2, 3, . . . , 64} */ + * with operand length N = 32 * x, + * where x in {1, 2, 3, . . . , 64} */ if (Xs > 64 || Ys > 64) { return MP_HW_FALLBACK; /* TODO add count metric on size fallback */ } @@ -1334,7 +1334,7 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* Y (left-extend) * Accelerator supports large-number multiplication with only - * four operand lengths of N ∈ {512, 1024, 1536, 2048} */ + * four operand lengths of N in {512, 1024, 1536, 2048} */ left_pad_offset = maxWords_sz << 2; if (left_pad_offset <= 512 >> 3) { left_pad_offset = 512 >> 3; /* 64 bytes (16 words) */ @@ -1583,10 +1583,10 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) * 0 => no interrupt; 1 => interrupt on completion. */ DPORT_REG_WRITE(RSA_INT_ENA_REG, 0); /* 2. Write number of words required for result. */ - /* see 21.3.3 Write (/N16 − 1) to the RSA_MODE_REG register */ + /* see 21.3.3 Write (/N16 - 1) to the RSA_MODE_REG register */ DPORT_REG_WRITE(RSA_MODE_REG, (hwWords_sz * 2 - 1)); - /* 3. Write Xi and Yi for ∈ {0, 1, . . . , n − 1} to memory blocks + /* 3. Write Xi and Yi for {0, 1, . . . , n - 1} to memory blocks * RSA_X_MEM and RSA_Z_MEM * Maximum is 64 words (64*8*4 = 2048 bits) */ esp_mpint_to_memblock(RSA_X_MEM, @@ -1796,7 +1796,7 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) * * See 24.3.3 of the ESP32 Technical Reference Manual * - * Z = X × Y mod M */ + * Z = X * Y mod M */ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) { struct esp_mp_helper mph[1]; /* we'll save some values in this mp helper */ @@ -1839,8 +1839,12 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* do we have an even moduli? */ if ((M->dp[0] & 1) == 0) { #ifndef NO_ESP_MP_MUL_EVEN_ALT_CALC - /* Z = X × Y mod M in mixed HW & SW*/ + /* Z = X * Y mod M in mixed HW & SW */ + #if defined(NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL) + ret = mp_mul(X, Y, tmpZ); /* SW X * Y */ + #else ret = esp_mp_mul(X, Y, tmpZ); /* HW X * Y */ + #endif if (ret == MP_OKAY) { /* z = tmpZ mod M, 0 <= Z < M */ ret = mp_mod(tmpZ, M, Z); /* SW mod M */ @@ -1940,7 +1944,6 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* lock HW for use, enable peripheral clock */ if (ret == MP_OKAY) { - mulmod_lock_called = TRUE; /* Don't try to unlock unless we locked */ #ifdef WOLFSSL_HW_METRICS { /* Only track max values when using HW */ @@ -1954,6 +1957,12 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #endif ret = esp_mp_hw_lock(); + if (ret == ESP_OK) { + mulmod_lock_called = TRUE; /* Don't try to unlock unless locked */ + } + else { + ret = WC_HW_WAIT_E; + } } #if defined(CONFIG_IDF_TARGET_ESP32) @@ -1973,13 +1982,13 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) * or until the RSA_INTR interrupt is generated. * (Or until the INTER interrupt is generated.) * 6. Write 1 to RSA_INTERRUPT_REG to clear the interrupt. - * 7. Write Yi (i ∈ [0, n) ∩ N) to RSA_X_MEM + * 7. Write Yi (i in [0, n) intersect N) to RSA_X_MEM * Users need to write to the memory block only according to the length * of the number. Data beyond this length is ignored. * 8. Write 1 to RSA_MULT_START_REG * 9. Wait for the second operation to be completed. * Poll INTERRUPT_REG until it reads 1. - * 10. Read the Zi (i ∈ [0, n) ∩ N) from RSA_Z_MEM + * 10. Read the Zi (i in [0, n) intersect N) from RSA_Z_MEM * 11. Write 1 to RSA_INTERUPT_REG to clear the interrupt. * * post: Release the HW engine @@ -2441,14 +2450,14 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) esp_mp_mulmod_usage_ct); ESP_LOGI(TAG, "esp_mp_mulmod_error_ct = %lu failures", esp_mp_mulmod_error_ct); - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); esp_show_mp("HW Z", Z); /* this is the HW result */ esp_show_mp("SW Z2", Z2); /* this is the SW result */ ESP_LOGI(TAG, "esp_mp_mulmod_usage_ct = %lu tries", esp_mp_mulmod_usage_ct); ESP_LOGI(TAG, "esp_mp_mulmod_error_ct = %lu failures", esp_mp_mulmod_error_ct); - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); #ifndef NO_RECOVER_SOFTWARE_CALC @@ -2500,15 +2509,15 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) * ESP32S3, Section 20.3.1, https://www.espressif.com/sites/default/files/documentation/esp32-s3_technical_reference_manual_en.pdf * * The operation is based on Montgomery multiplication. Aside from the - * arguments X, Y , and M, two additional ones are needed —r and M′ + * arguments X, Y , and M, two additional ones are needed -r and M' .* These arguments are calculated in advance by software. .* -.* The RSA Accelerator supports operand lengths of N ∈ {512, 1024, 1536, 2048, -.* 2560, 3072, 3584, 4096} bits on the ESP32 and N ∈ [32, 4096] bits +.* The RSA Accelerator supports operand lengths of N in {512, 1024, 1536, 2048, +.* 2560, 3072, 3584, 4096} bits on the ESP32 and N in [32, 4096] bits * on the ESP32s3. .* The bit length of arguments Z, X, Y , M, and r can be any one from * the N set, but all numbers in a calculation must be of the same length. -.* The bit length of M′ is always 32. +.* The bit length of M' is always 32. .* * Z = (X ^ Y) mod M : Espressif generic notation * Y = (G ^ X) mod P : wolfSSL DH reference notation */ @@ -2991,7 +3000,7 @@ int esp_hw_show_mp_metrics(void) "NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL"); #else /* Metrics: esp_mp_mul() */ - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* mul follows */ + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* mul follows */ ESP_LOGI(TAG, "esp_mp_mul HW acceleration enabled."); ESP_LOGI(TAG, "Number of calls to esp_mp_mul: %lu", esp_mp_mul_usage_ct); @@ -3010,7 +3019,7 @@ int esp_hw_show_mp_metrics(void) "NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD"); #else /* Metrics: esp_mp_mulmod() */ - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* mulmod follows */ + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* mulmod follows */ ESP_LOGI(TAG, "esp_mp_mulmod HW acceleration enabled."); /* Metrics: esp_mp_mulmod() */ @@ -3052,7 +3061,7 @@ int esp_hw_show_mp_metrics(void) "NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD"); #else /* Metrics: sp_mp_exptmod() */ - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* exptmod follows */ + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); /* exptmod follows */ ESP_LOGI(TAG, "Number of calls to esp_mp_exptmod: %lu", esp_mp_exptmod_usage_ct); diff --git a/src/wolfcrypt/src/port/Espressif/esp32_sha.c b/src/wolfcrypt/src/port/Espressif/esp32_sha.c index 332c532..bef77b0 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -1,6 +1,6 @@ /* esp32_sha.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -43,9 +43,6 @@ #if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WC_SHA384) || \ defined(WC_SHA512) -#include "wolfssl/wolfcrypt/logging.h" - - /* this entire file content is excluded if not using HW hash acceleration */ #if defined(WOLFSSL_ESP32_CRYPT) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) @@ -58,9 +55,16 @@ #include #include +#elif defined(CONFIG_IDF_TARGET_ESP32) || \ + defined(CONFIG_IDF_TARGET_ESP32S2) || \ + defined(CONFIG_IDF_TARGET_ESP32S3) + #include #else #include /* ESP32-WROOM */ #endif + +/* wolfSSL */ +#include #include #include #include @@ -75,13 +79,18 @@ #include #endif +/* A value for an initialized, but not-yet-known SHA: */ +#define WC_UNKNOWN_SHA (-1) + +#define WC_ESP_MAX_IDLE_WAIT 10000 + static const char* TAG = "wolf_hw_sha"; #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) - /* keep track of the currently active SHA hash object for interleaving */ + /* Keep track of the currently active SHA hash object for interleaving. */ const static word32 ** _active_digest_address = 0; #endif @@ -90,7 +99,7 @@ static const char* TAG = "wolf_hw_sha"; #endif #if defined(DEBUG_WOLFSSL) - /* Only when debugging, we'll keep tracking of block numbers. */ + /* Only when debugging, we'll keep tracking of SHA block numbers. */ static int this_block_num = 0; #endif @@ -102,9 +111,12 @@ static const char* TAG = "wolf_hw_sha"; #endif #ifdef WOLFSSL_DEBUG_MUTEX - #ifndef WOLFSSL_TEST_STRAY + #ifdef WOLFSSL_TEST_STRAY + #define WOLFSSL_TEST_STRAY_INJECT (esp_sha_call_count() == 10) + #else /* unless turned on, we won't be testing for strays */ #define WOLFSSL_TEST_STRAY 0 + #define WOLFSSL_TEST_STRAY_INJECT 0 #endif #endif @@ -122,13 +134,32 @@ static const char* TAG = "wolf_hw_sha"; static unsigned long esp_byte_reversal_needed_ct = 0; #endif + static uintptr_t mutex_ctx_owner = NULLPTR; + static portMUX_TYPE sha_crit_sect = portMUX_INITIALIZER_UNLOCKED; + #if defined(ESP_MONITOR_HW_TASK_LOCK) - static void * mutex_ctx_owner = 0; - static TaskHandle_t mutex_ctx_task = 0; + #ifdef SINGLE_THREADED + uintptr_t esp_sha_mutex_ctx_owner(void) + { + return mutex_ctx_owner; + } + #else + static TaskHandle_t mutex_ctx_task = NULL; + uintptr_t esp_sha_mutex_ctx_owner(void) + { + uintptr_t ret = 0; + taskENTER_CRITICAL(&sha_crit_sect); + { + ret = mutex_ctx_owner; + } + taskEXIT_CRITICAL(&sha_crit_sect); + return ret; + }; + #endif + #ifdef WOLFSSL_DEBUG_MUTEX - static portMUX_TYPE sha_crit_sect = portMUX_INITIALIZER_UNLOCKED; WC_ESP32SHA* stray_ctx; - /* each ctx keeps track of the intializer for HW. when debugging + /* each ctx keeps track of the initializer for HW. when debugging * we'll have a global variable to indicate which has the lock. */ static int _sha_lock_count = 0; static int _sha_call_count = 0; @@ -143,40 +174,50 @@ static const char* TAG = "wolf_hw_sha"; return _sha_lock_count; } - void* esp_sha_mutex_ctx_owner(void) - { - void* ret = 0; - taskENTER_CRITICAL(&sha_crit_sect); - { - ret = mutex_ctx_owner; - } - taskEXIT_CRITICAL(&sha_crit_sect); - return ret; - }; - #else - int esp_sha_mutex_ctx_owner(void) - { - return (int)sha_mutex; - } #endif #endif +/* esp_set_hw - set hardware lock, but only if there's no other known + * current mutex owner. */ +int esp_set_hw(WC_ESP32SHA* ctx) +{ + int ret = ESP_FAIL; + if ((uintptr_t)ctx == mutex_ctx_owner || mutex_ctx_owner == NULLPTR) { + ESP_LOGV(TAG, "Initializing current mutext owner!"); + if (esp_sha_hw_islocked(ctx)) { + ESP_LOGV(TAG, "esp_set_hw already locked: 0x%x", (intptr_t)ctx); + } + ctx->mode = ESP32_SHA_HW; + mutex_ctx_owner = (uintptr_t)ctx; + ret = ESP_OK; + } + else { + ESP_LOGV(TAG, "esp_sha_init_ctx HW for non-owner 0x%x", (intptr_t)ctx); + } + return ret; +} + /* ** The wolfCrypt functions for LITTLE_ENDIAN_ORDER typically ** reverse the byte order. Except when the hardware doesn't expect it. ** +** For SoC devices with no HW (Hardware Acceleration) support: +** ctx->sha_type will be SHA_INVALID +** ctx->mode will be ESP32_SHA_SW +** ** Returns 0 (FALSE) or 1 (TRUE); see wolfSSL types.h */ int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx) { - int ret = TRUE; /* assume we'll need reversal, look for exceptions */ + int ret = 1; /* Assume we'll need reversal, look for exceptions. */ + CTX_STACK_CHECK(ctx); #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) if (ctx == NULL) { ESP_LOGE(TAG, " ctx is null"); - /* return true for bad params */ + /* Return true for bad params */ } else { #ifdef WOLFSSL_HW_METRICS @@ -186,12 +227,12 @@ int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx) #endif if (ctx->mode == ESP32_SHA_HW) { ESP_LOGV(TAG, " No reversal, ESP32_SHA_HW"); - ret = FALSE; + ret = 0; } else { - ret = TRUE; + ret = 1; ESP_LOGV(TAG, " Need byte reversal, %d", ctx->mode); - /* return true for SW; only HW C3 skips reversal at this time. */ + /* Return true for SW; only HW C3 skips reversal at this time. */ #ifdef WOLFSSL_HW_METRICS { esp_byte_reversal_needed_ct++; @@ -204,8 +245,10 @@ int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx) } } #else - /* other platforms always return true */ + /* Other platforms always return true. */ #endif + CTX_STACK_CHECK(ctx); + return ret; } @@ -218,20 +261,42 @@ int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx) ** Active HW states, such as from during a copy operation, are demoted to SW. ** For hash_type not available in HW, set SW mode. ** -** See esp_sha_init_ctx(ctx) +** For ctx, mode will be +** ESP32_SHA_INIT - For initialized, hardware-ready +** ESP32_SHA_SW - Software only +** +** See esp_sha_init_ctx(ctx) for common initialization of ctx. */ int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type) { - int ret = 0; + int ret = ESP_OK; + +#ifdef DEBUG_WOLFSSL_SHA_MUTEX + ESP_LOGV(TAG, "\n\nesp_sha_init for ctx %p\n\n", ctx); +#endif + + if (ctx == NULL) { + return ESP_FAIL; + } + +#if defined(WOLFSSL_STACK_CHECK) + ctx->first_word = 0; + ctx->last_word = 0; +#endif + CTX_STACK_CHECK(ctx); + + ret = esp_sha_init_ctx(ctx); -#if defined(CONFIG_IDF_TARGET_ESP32) || \ - defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) +#if defined(CONFIG_IDF_TARGET_ESP32) || \ + defined(CONFIG_IDF_TARGET_ESP32S2) || \ + defined(CONFIG_IDF_TARGET_ESP32S3) + + /* ESP32 Xtensa Architecture SoC. Each has different features: */ switch (hash_type) { /* check each wolfSSL hash type WC_[n] */ #ifndef NO_SHA case WC_HASH_TYPE_SHA: ctx->sha_type = SHA1; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; #endif @@ -239,7 +304,6 @@ int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type) #if defined(CONFIG_IDF_TARGET_ESP32S2) || \ defined(CONFIG_IDF_TARGET_ESP32S3) ctx->sha_type = SHA2_224; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); #else /* Don't call init, always SW as there's no HW. */ ctx->mode = ESP32_SHA_SW; @@ -248,32 +312,27 @@ int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type) case WC_HASH_TYPE_SHA256: ctx->sha_type = SHA2_256; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; #if defined(CONFIG_IDF_TARGET_ESP32S2) || \ defined(CONFIG_IDF_TARGET_ESP32S3) case WC_HASH_TYPE_SHA384: ctx->mode = ESP32_SHA_SW; - ctx->sha_type = SHA2_384; /* Espressif type, but we won't use HW */ break; #else case WC_HASH_TYPE_SHA384: ctx->sha_type = SHA2_384; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; #endif case WC_HASH_TYPE_SHA512: ctx->sha_type = SHA2_512; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; #ifndef WOLFSSL_NOSHA512_224 case WC_HASH_TYPE_SHA512_224: /* Don't call init, always SW as there's no HW. */ ctx->mode = ESP32_SHA_SW; - ctx->sha_type = SHA2_512; /* Espressif type, but we won't use HW */ break; #endif @@ -281,245 +340,84 @@ int esp_sha_init(WC_ESP32SHA* ctx, enum wc_HashType hash_type) case WC_HASH_TYPE_SHA512_256: /* Don't call init, always SW as there's no HW. */ ctx->mode = ESP32_SHA_SW; - ctx->sha_type = SHA2_512; /* Espressif type, but we won't use HW */ break; #endif default: - ret = esp_sha_init_ctx(ctx); - ESP_LOGW(TAG, "Unexpected hash_type in esp_sha_init"); - break; + ctx->mode = ESP32_SHA_SW; + ESP_LOGW(TAG, "Unexpected hash_type in esp_sha_init"); + break; } #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) + + /* ESP32 RISC-V Architecture SoC. Each has different features: */ + switch (hash_type) { /* check each wolfSSL hash type WC_[n] */ - #ifndef NO_SHA + #ifndef NO_SHA case WC_HASH_TYPE_SHA: ctx->sha_type = SHA1; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; - #endif + #endif case WC_HASH_TYPE_SHA224: ctx->sha_type = SHA2_224; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; case WC_HASH_TYPE_SHA256: ctx->sha_type = SHA2_256; /* assign Espressif SHA HW type */ - ret = esp_sha_init_ctx(ctx); break; default: /* We fall through to SW when there's no enabled HW, above. */ ctx->mode = ESP32_SHA_SW; - ret = 0; - /* If there's no HW, the ctx reference should cause build error. - ** The type should be gated away when there's no HW at all! */ - ctx->isfirstblock = true; - ctx->sha_type = hash_type; ESP_LOGW(TAG, "Unsupported hash_type = %d in esp_sha_init, " "falling back to SW", hash_type); break; } #else - /* other chipsets will be implemented here */ + /* Other chipsets will be implemented here, fallback to SW for now: */ ESP_LOGW(TAG, "SW Fallback; CONFIG_IDF_TARGET = %s", CONFIG_IDF_TARGET); ctx->mode = ESP32_SHA_SW; -#endif /* CONFIG_IDF_TARGET_ESP32 || - * CONFIG_IDF_TARGET_ESP32S2 || - * CONFIG_IDF_TARGET_ESP32S3 */ +#endif /* CONFIG_IDF_TARGET_[nnn] */ + CTX_STACK_CHECK(ctx); return ret; } -/* we'll call a separate init as there's only 1 HW acceleration */ +/* we'll call a common init for non-chip-specific settings */ int esp_sha_init_ctx(WC_ESP32SHA* ctx) { - if (ctx->initializer == NULL) { - ESP_LOGV(TAG, "regular init of blank WC_ESP32SHA ctx"); + CTX_STACK_CHECK(ctx); - /* we'll keep track of who initialized this */ - ctx->initializer = ctx; /* save our address in the initializer */ - #ifdef ESP_MONITOR_HW_TASK_LOCK - { - /* Keep track of which freeRTOS task actually locks HW */ - ctx->task_owner = xTaskGetCurrentTaskHandle(); - } - #endif - ctx->mode = ESP32_SHA_INIT; - } - else { - /* things may be more interesting when previously initialized */ - if (ctx->initializer == ctx) { - /* We're likely re-using an existing object previously initialized. - ** There's of course a non-zero probability that garbage data is - ** the same pointer value, but that's highly unlikely; We'd need - ** to discard, then re-init to same memory location for a matching - ** initializer. */ - ESP_LOGV(TAG, "re-using existing WC_ESP32SHA ctx"); - - /* we should never have an unexpected mode in a known ctx */ - switch (ctx->mode) { - case ESP32_SHA_FREED: - ESP_LOGW(TAG, "Warning: ESP32_SHA_FREED status"); + ctx->mode = ESP32_SHA_INIT; - #ifdef ESP_MONITOR_HW_TASK_LOCK - if (ctx->task_owner == xTaskGetCurrentTaskHandle()) { - esp_sha_hw_unlock(ctx); - } - else { - ESP_LOGW(TAG, "Warning: unable to unlock ctx mutex "); - } - #else - esp_sha_hw_unlock(ctx); - #endif - ctx->mode = ESP32_SHA_INIT; - /* fall through to init */ - - case ESP32_SHA_INIT: - case ESP32_SHA_SW: - /* nothing interesting here */ - break; - - case ESP32_SHA_HW: - /* This will be dealt with below: likely demote to SW */ - break; - - case ESP32_SHA_HW_COPY: - /* This is an interesting mode, caller gave HW mode hint */ - ESP_LOGI(TAG, "ALERT: ESP32_SHA_HW_COPY?"); - break; - - default: - /* This should almost never occur. We'd need to have an - ** uninitialized ctx that just happens to include the - ** breadcrumb initializer with the same address. */ - ESP_LOGW(TAG, "ALERT: unexpected WC_ESP32SHA ctx mode: " - "%d. ", ctx->mode); - ctx->mode = ESP32_SHA_INIT; - break; - } - /* We don't need to do anything here, - ** this section for diagnostics only. - ** May need to unlock HW, below. */ - } /* ctx->initializer == ctx */ - else { - /* We may end up here with either dirty memory - ** or copied SHA ctx. - ** - ** Any copy function should have already set mode = ESP32_SHA_INIT. - ** - ** In either case, initialize: */ - ctx->initializer = ctx; /* set a new address */ - #ifdef ESP_MONITOR_HW_TASK_LOCK - { - /* not HW mode, so we are not interested in task owner */ - ctx->task_owner = 0; - } - #endif - - /* Always set to ESP32_SHA_INIT, but give debug info as to why: */ - switch (ctx->mode) { - case ESP32_SHA_FREED: - ESP_LOGE(TAG, "ERROR: unexpected ESP32_SHA_FREED"); - ctx->mode = ESP32_SHA_INIT; - break; - - case ESP32_SHA_INIT: - /* if we are already in init mode, nothing to do. */ - break; - - case ESP32_SHA_SW: - /* this should rarely, if ever occur */ - ESP_LOGW(TAG, "ALERT: unexpected SW WC_ESP32SHA ctx mode. " - "Copied? Revert to ESP32_SHA_INIT."); - ctx->mode = ESP32_SHA_INIT; - break; - - case ESP32_SHA_HW: - /* this should rarely, if ever occur. */ - ESP_LOGW(TAG, "ALERT: unexpected HW WC_ESP32SHA ctx mode. " - "Copied?"); - ctx->mode = ESP32_SHA_INIT; - break; - - case ESP32_SHA_HW_COPY: - /* This is an interesting but acceptable situation: - ** an anticipated active HW copy that will demote to SW. */ - ESP_LOGV(TAG, "HW WC_ESP32SHA ctx mode = " - "ESP32_SHA_HW_COPY."); - break; - - default: - /* this will frequently occur during new init */ - ESP_LOGV(TAG, "ALERT: unexpected WC_ESP32SHA ctx mode. " - "Uninitialized?"); - ctx->mode = ESP32_SHA_INIT; - break; - } /* switch */ - } /* ctx->initializer != ctx */ - } /* ctx->initializer != NULL */ - - /* - ** After possibly changing the mode (above) handle current mode: - */ - switch (ctx->mode) { - case ESP32_SHA_INIT: - /* Likely a fresh, new SHA, as desired. */ - ESP_LOGV(TAG, "Normal ESP32_SHA_INIT"); - break; + /* This is a generic init; we don't yet know SHA type. */ + ctx->sha_type = WC_UNKNOWN_SHA; - case ESP32_SHA_HW: - /* We're already in hardware mode, so release. */ - /* Interesting, but normal. */ - ESP_LOGV(TAG, ">> HW unlock."); + /* Reminder: always start isfirstblock = 1 (true) when using HW engine. */ + /* We're always on the first block at init time. (not zero-based!) */ + ctx->isfirstblock = 1; + ctx->lockDepth = 0; /* new objects will always start with lock depth = 0 */ - /* During init is the ONLY TIME we call unlock. - ** If there's a problem, likely some undesired operation - ** outside of wolfSSL. - */ - /* TODO debug check if HW actually locked; */ +#if defined(MUTEX_DURING_INIT) + if ((uintptr_t)ctx == mutex_ctx_owner || mutex_ctx_owner == NULLPTR) { + ESP_LOGV(TAG, "Initializing current mutext owner!"); + if (esp_sha_hw_islocked(ctx)) { esp_sha_hw_unlock(ctx); - ctx->mode = ESP32_SHA_INIT; - break; - - case ESP32_SHA_HW_COPY: - /* When we init during a known active HW copy, revert to SW. */ - ESP_LOGV(TAG, "Planned revert to SW during copy."); - ctx->mode = ESP32_SHA_SW; - break; - - case ESP32_SHA_SW: - /* This is an interesting situation: likely a call when - ** another SHA in progress, but copied. */ - ESP_LOGV(TAG, ">> SW Set to init."); - ctx->mode = ESP32_SHA_INIT; - break; - - case ESP32_SHA_FAIL_NEED_UNROLL: - /* Oh, how did we get here? likely uninitialized SHA memory. - ** User code logic may need attention. */ - ESP_LOGW(TAG, "ALERT: \nESP32_SHA_FAIL_NEED_UNROLL\n"); - ctx->mode = ESP32_SHA_INIT; - break; - - default: - /* Most likely corrupted memory. */ - ESP_LOGW(TAG, "ALERT: \nunexpected mode value: " - "%d \n", ctx->mode); - ctx->mode = ESP32_SHA_INIT; - break; - } /* switch (ctx->mode) */ - - /* reminder: always start isfirstblock = 1 (true) when using HW engine */ - /* we're always on the first block at init time (not zero-based!) */ - ctx->isfirstblock = true; - ctx->lockDepth = 0; /* new objects will always start with lock depth = 0 */ + } + mutex_ctx_owner = (uintptr_t)ctx; + } + else { + ESP_LOGI(TAG, "MUTEX_DURING_INIT esp_sha_init_ctx for non-owner: " + "0x%x", (intptr_t)ctx); + } +#endif + CTX_STACK_CHECK(ctx); return ESP_OK; /* Always return success. * We assume all issues handled, above. */ } /* esp_sha_init_ctx */ @@ -542,17 +440,14 @@ int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst) /* Get a copy of the HW digest, but don't process it. */ ret = esp_sha_digest_process(dst, 0); if (ret == 0) { - /* Note we arrived here only because - * the src is already in HW mode. - * provide init hint to SW revert: */ - dst->ctx.mode = ESP32_SHA_HW_COPY; - /* initializer will be set during init */ ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA); if (ret != 0) { ESP_LOGE(TAG, "Error during esp_sha_ctx_copy " "in esp_sha_init."); } + /* As src is HW, the copy will be SW. TODO: Future interleave. */ + dst->ctx.mode = ESP32_SHA_SW; } else { ESP_LOGE(TAG, "Error during esp_sha_ctx_copy " @@ -577,7 +472,7 @@ int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst) else { /* However NOT reverting to SW is not right. ** This should never happen. */ - ESP_LOGW(TAG, "SHA Copy NOT set to SW"); + ESP_LOGW(TAG, "SHA Copy NOT set to SW from %d", dst->ctx.mode); } } /* (src->ctx.mode == ESP32_SHA_HW */ else { /* src not in HW mode, ok to copy. */ @@ -585,8 +480,8 @@ int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst) ** reminder XMEMCOPY, above: dst->ctx = src->ctx; ** No special HW init needed in SW mode. ** but we need to set our initializer breadcrumb: */ - dst->ctx.initializer = &(dst->ctx); /* assign new breadcrumb to dst */ - #ifdef ESP_MONITOR_HW_TASK_LOCK + dst->ctx.initializer = (uintptr_t)&(dst->ctx); + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { /* not HW mode for copy, so we are not interested in task owner */ dst->ctx.task_owner = 0; @@ -600,18 +495,18 @@ int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst) } /* esp_sha_ctx_copy */ #endif - /* -** internal sha224 ctx copy (no ESP HW) +** Internal sha224 ctx copy (no ESP HW) */ #ifndef NO_WOLFSSL_ESP32_CRYPT_HASH_SHA224 int esp_sha224_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) { - /* There's no 224 hardware on ESP32 */ - dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ - #ifdef ESP_MONITOR_HW_TASK_LOCK + /* There's no 224 hardware on ESP32. + * Initializer for dst is this ctx address for use as a breadcrumb. */ + dst->ctx.initializer = (uintptr_t)&dst->ctx; + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { - /* not HW mode for copy, so we are not interested in task owner */ + /* not HW mode for copy, so we are not interested in task owner: */ dst->ctx.task_owner = 0; } #endif @@ -635,14 +530,16 @@ int esp_sha256_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) ESP_LOGI(TAG, "esp_sha256_ctx_copy esp_sha512_digest_process"); } #endif - ret = esp_sha256_digest_process(dst, 0); /* TODO Use FALSE*/ - - if (ret == 0) { - /* provide init hint to possibly SW revert */ - dst->ctx.mode = ESP32_SHA_HW_COPY; + ret = esp_sha256_digest_process(dst, FALSE); + if (ret == ESP_OK) { /* initializer breadcrumb will be set during init */ - ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA256 ); + ret = esp_sha_init(&(dst->ctx), WC_HASH_TYPE_SHA256); + /* As src is HW, the copy will be SW. TODO: Future interleave. */ + dst->ctx.mode = ESP32_SHA_SW; + } + else { + ESP_LOGE(TAG, "Unexpected error during sha256 ctx copy: %d", ret); } if (dst->ctx.mode == ESP32_SHA_SW) { @@ -660,17 +557,19 @@ int esp_sha256_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) ESP_LOGV(TAG, "Confirmed wc_Sha256 Copy set to SW"); } else { - ESP_LOGW(TAG, "wc_Sha256 Copy NOT set to SW"); + ESP_LOGW(TAG, "wc_Sha256 Copy (mode = %d) set to SW", + dst->ctx.mode); + dst->ctx.mode = ESP32_SHA_SW; } } /* (src->ctx.mode == ESP32_SHA_HW) */ else { - ret = 0; + ret = ESP_OK; /* ** reminder this happened in XMEMCOPY: dst->ctx = src->ctx; ** No special HW init needed in SW mode. - ** but we need to set our initializer: */ - dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ - #ifdef ESP_MONITOR_HW_TASK_LOCK + ** but we need to set our initializer (helpful in multi-task RTOS) */ + dst->ctx.initializer = (uintptr_t)&(dst->ctx); + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { /* not HW mode, so we are not interested in task owner */ dst->ctx.task_owner = 0; @@ -705,7 +604,7 @@ int esp_sha384_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) #else if (src->ctx.mode == ESP32_SHA_HW) { /* Get a copy of the HW digest, but don't process it. */ - ESP_LOGI(TAG, "esp_sha384_ctx_copy esp_sha512_digest_process"); + ESP_LOGV(TAG, "esp_sha384_ctx_copy esp_sha512_digest_process"); ret = esp_sha512_digest_process(dst, 0); if (ret == 0) { /* provide init hint to SW revert */ @@ -734,11 +633,11 @@ int esp_sha384_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) else { ret = 0; /* - ** reminder this happened in XMEMCOPY, above: dst->ctx = src->ctx; + ** Reminder this happened in XMEMCOPY, above: dst->ctx = src->ctx; ** No special HW init needed in SW mode. - ** but we need to set our initializer: */ - dst->ctx.initializer = &dst->ctx; /* assign the initializer to dst */ - #ifdef ESP_MONITOR_HW_TASK_LOCK + ** But we need to set our initializer in dst as a breadcrumb: */ + dst->ctx.initializer = (uintptr_t)&(dst->ctx); + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { /* not HW mode for copy, so we are not interested in task owner */ dst->ctx.task_owner = 0; @@ -766,16 +665,17 @@ int esp_sha512_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) - /* there's no SHA512 HW on the RISC-V SoC so there's nothing to do. */ + /* There's no SHA512 HW on these RISC-V SoC so there's nothing to do. + * (perhaps a future one will?) */ #elif defined(CONFIG_IDF_TARGET_ESP32) || \ defined(CONFIG_IDF_TARGET_ESP32S2) || \ defined(CONFIG_IDF_TARGET_ESP32S3) if (src->ctx.mode == ESP32_SHA_HW) { /* Get a copy of the HW digest, but don't process it. */ - ESP_LOGI(TAG, "esp_sha512_ctx_copy esp_sha512_digest_process"); - ret = esp_sha512_digest_process(dst, 0); + ESP_LOGV(TAG, "esp_sha512_ctx_copy esp_sha512_digest_process"); + ret = esp_sha512_digest_process(dst, FALSE); - if (ret == 0) { + if (ret == ESP_OK) { /* provide init hint to SW revert */ dst->ctx.mode = ESP32_SHA_HW_COPY; @@ -789,27 +689,27 @@ int esp_sha512_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) ESP_LOGV(TAG, "Confirmed wc_Sha512 Copy set to SW"); } else { - ESP_LOGW(TAG, "wc_Sha512 Copy NOT set to SW"); + ESP_LOGW(TAG, "wc_Sha512 Copy set to SW"); + dst->ctx.mode = ESP32_SHA_SW; } } /* src->ctx.mode == ESP32_SHA_HW */ else { - ret = 0; + ret = ESP_OK; /* reminder this happened in XMEMCOPY, above: dst->ctx = src->ctx; ** No special HW init needed when not in active HW mode. ** but we need to set our initializer breadcrumb: */ - /* TODO: instead of what is NOT supported, gate on what IS known to be supported */ #if !defined(CONFIG_IDF_TARGET_ESP32C2) && \ !defined(CONFIG_IDF_TARGET_ESP32C3) && \ !defined(CONFIG_IDF_TARGET_ESP32C6) - dst->ctx.initializer = &dst->ctx; /*breadcrumb is this ctx address */ + dst->ctx.initializer = (uintptr_t)&(dst->ctx); #endif - #ifdef ESP_MONITOR_HW_TASK_LOCK + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { /* not HW mode for copy, so we are not interested in task owner */ dst->ctx.task_owner = 0; } - #endif - } + #endif + } /* else src->ctx.mode != ESP32_SHA_HW */ #endif return ret; @@ -821,14 +721,14 @@ int esp_sha512_ctx_copy(struct wc_Sha512* src, struct wc_Sha512* dst) ** ** See FIPS PUB 180-4, Instruction Section 1. ** -** See ESP32 shah.h for values: +** See ESP32 sha.h for values: ** ** enum SHA_TYPE { ** SHA1 = 0, ** SHA2_256, ** SHA2_384, ** SHA2_512, -** SHA_INVALID = -1, +** SHA_TYPE_MAX = -1, ** }; ** ** given the SHA_TYPE (see Espressif sha.h) return WC digest size. @@ -917,14 +817,14 @@ static word32 wc_esp_sha_digest_size(WC_ESP_SHA_TYPE type) static int wc_esp_wait_until_idle(void) { int ret = 0; /* assume success */ - int loop_ct = 10000; + int loop_ct = WC_ESP_MAX_IDLE_WAIT; #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) /* ESP32-C3 and ESP32-C6 RISC-V */ - while ((sha_ll_busy() == true) && (loop_ct > 0)) { + while ((sha_ll_busy() == 1) && (loop_ct > 0)) { loop_ct--; /* do nothing while waiting. */ } @@ -942,7 +842,7 @@ static int wc_esp_wait_until_idle(void) #endif if (loop_ct <= 0) { - ESP_LOGI(TAG, "too long to exit wc_esp_wait_until_idle"); + ESP_LOGW(TAG, "Too long to exit wc_esp_wait_until_idle"); } return ret; } /* wc_esp_wait_until_idle */ @@ -970,6 +870,7 @@ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) #if defined(CONFIG_IDF_TARGET_ESP32) word32 this_sha_mask; /* this is the bit-mask for our SHA CLK_EN_REG */ #endif + CTX_STACK_CHECK(ctx); if (ctx == NULL) { ESP_LOGE(TAG, "esp_unroll_sha_module_enable called with null ctx."); @@ -1006,7 +907,7 @@ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) periph_module_disable(PERIPH_SHA_MODULE); asm volatile("memw"); actual_unroll_count++; - ESP_LOGI(TAG, "unroll not yet successful. try #%d", + ESP_LOGW(TAG, "unroll not yet successful. try #%d", actual_unroll_count); /* we'll only try this some unreasonable number of times @@ -1025,7 +926,11 @@ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) ** This should never happen unless someone else called ** periph_module_disable() or threading not working properly. **/ - ESP_LOGW(TAG, "warning lockDepth mismatch."); + ESP_LOGW(TAG, "warning lockDepth mismatch: %d", ctx->lockDepth); + if (actual_unroll_count == 0 && ctx->lockDepth > 2) { + ESP_LOGW(TAG, "Large lockDepth discrepancy often indicates " + "stack overflow or memory corruption"); + } } ctx->lockDepth = 0; ctx->mode = ESP32_SHA_INIT; @@ -1039,16 +944,36 @@ int esp_unroll_sha_module_enable(WC_ESP32SHA* ctx) ESP_LOGI(TAG, "Setting ctx->mode = ESP32_SHA_SW"); ctx->mode = ESP32_SHA_SW; } + CTX_STACK_CHECK(ctx); return ret; } /* esp_unroll_sha_module_enable */ -int esp_sha_set_stray(WC_ESP32SHA* ctx) +/* Set and return a stray ctx value stray_ctx. Useful for multi-task debugging. + * Returns zero if not debugging. */ +uintptr_t esp_sha_set_stray(WC_ESP32SHA* ctx) { - int ret = 0; + uintptr_t ret = 0; + CTX_STACK_CHECK(ctx); + #ifdef WOLFSSL_DEBUG_MUTEX stray_ctx = ctx; - ret= (int)stray_ctx; + ret = (uintptr_t)stray_ctx; #endif + CTX_STACK_CHECK(ctx); + return ret; +} + +/* Return 1 if the SHA HW is in use, 0 otherwise. */ +int esp_sha_hw_in_use() +{ + int ret; +#ifdef SINGLE_THREADED + ret = InUse; +#else + ret = (mutex_ctx_owner != NULLPTR); + ESP_LOGV(TAG, "mutex_ctx_owner is 0x%x", mutex_ctx_owner); +#endif + ESP_LOGV(TAG, "esp_sha_hw_in_use is %d", ret); return ret; } @@ -1058,18 +983,21 @@ int esp_sha_set_stray(WC_ESP32SHA* ctx) ** When WOLFSSL_DEBUG_MUTEX is defined, additional ** debugging capabilities are available. */ -int esp_sha_hw_islocked(WC_ESP32SHA* ctx) +uintptr_t esp_sha_hw_islocked(WC_ESP32SHA* ctx) { - int ret = 0; + TaskHandle_t mutexHolder; + uintptr_t ret = 0; + CTX_STACK_CHECK(ctx); + #ifdef WOLFSSL_DEBUG_MUTEX taskENTER_CRITICAL(&sha_crit_sect); { - ret = (int)mutex_ctx_owner; + ret = (uintptr_t)mutex_ctx_owner; if (ctx == 0) { /* we are not checking if a given ctx has the lock */ } else { - if (ret == (int)ctx->initializer) { + if (ret == (uintptr_t)ctx->initializer) { /* confirmed this object is the owner */ } else { @@ -1085,7 +1013,30 @@ int esp_sha_hw_islocked(WC_ESP32SHA* ctx) } #else { - ret = (int)sha_mutex; + if (sha_mutex == NULL) { + mutexHolder = NULL; + } + else { + mutexHolder = xSemaphoreGetMutexHolder(sha_mutex); + } + + if (mutexHolder == NULL) { + /* Mutex is not in use */ + ESP_LOGV(TAG, "multi-threaded esp_mp_hw_islocked = false"); + ret = 0; + } + else { + ESP_LOGV(TAG, "multi-threaded esp_mp_hw_islocked = true"); + ret = mutex_ctx_owner; + } + + /* Verbose debug diagnostics */ + if (NULLPTR == mutex_ctx_owner) { + ESP_LOGV(TAG, "not esp_sha_hw_islocked, mutex_ctx_owner is Null"); + } + else { + ESP_LOGV(TAG, "esp_sha_hw_islocked for 0x%x", mutex_ctx_owner); + } } #endif return ret; @@ -1101,57 +1052,92 @@ int esp_sha_hw_islocked(WC_ESP32SHA* ctx) (int)esp_sha_mutex_ctx_owner()); } #endif + CTX_STACK_CHECK(ctx); return ret; } /* * The HW is typically unlocked when the SHA hash wc_Sha[nn]Final() is called. - * However, in the case of TS connections, the in progress hash may at times be + * However, in the case of TLS connections the in-progress hash may at times be * abandoned. Thus this function should be called at free time. See internal.c + * + * Returns the owner of the current lock, typically used for debugging. + * Returns zero if there was no unfinished lock found to clean up. */ -int esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) +uintptr_t esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) { - int ret = 0; + uintptr_t ret = 0; + CTX_STACK_CHECK(ctx); + ret = esp_sha_hw_islocked(ctx); /* get the owner of the current lock */ if (ret == 0) { - /* no lock */ + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG + ESP_LOGV(TAG, "No unfinished lock to clean up for ctx %p.", ctx); + #endif } else { - if (ret == (int)ctx) { + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG + ESP_LOGI(TAG, "Unfinished lock clean up: %p.", ctx); + #endif + if (ret == (uintptr_t)ctx) { /* found a match for this object */ - if (ret == (int)(ctx->initializer)) { + if (ret == ctx->initializer) { /* confirmed match*/ + ESP_LOGW(TAG, "New mutex_ctx_owner = NULL"); + #ifdef ESP_MONITOR_HW_TASK_LOCK + { + mutex_ctx_owner = NULLPTR; + } + #endif } else { - /* the only mismatch expected may be in a mullti-thread RTOS */ - ESP_LOGE(TAG, "ERROR: esp_sha_release_unfinished_lock for %x" - " but found %x", ret, (int)(ctx->initializer)); + /* the only mismatch expected may be in a multi-thread RTOS */ + ESP_LOGE(TAG, "ERROR: Release unfinished lock for %x but " + "found %x", ret, ctx->initializer); } #ifdef WOLFSSL_DEBUG_MUTEX ESP_LOGE(TAG, "\n>>>> esp_sha_release_unfinished_lock %x\n", ret); #endif - /* unlock only if this ctx is the intializer of the lock */ + + /* unlock only if this ctx is the initializer of the lock */ #ifdef SINGLE_THREADED { ret = esp_sha_hw_unlock(ctx); } #else - { - if (ctx->task_owner == xTaskGetCurrentTaskHandle()) { - ret = esp_sha_hw_unlock(ctx); - } - else { - /* We cannot free a SHA onbject locks from a different task. - * So give the ctx a hint for the other task to clean it up. */ - ctx->mode = ESP32_SHA_FREED; + #if defined(ESP_MONITOR_HW_TASK_LOCK) + { + if (ctx->task_owner == xTaskGetCurrentTaskHandle()) { + ESP_LOGV(TAG, "esp_sha_hw_unlock!"); + } + else { + /* We cannot free a SHA object lock from a different task. + * So give the ctx a hint for other task to clean it up. */ + ctx->mode = ESP32_SHA_FREED; + ESP_LOGV(TAG, "ESP32_SHA_FREED"); + } } - } - #endif + #else + /* Here we assume only 1 task, so no ESP32_SHA_FREED hint. */ + ret = esp_sha_hw_unlock(ctx); + #endif /* ESP_MONITOR_HW_TASK_LOCK */ + #endif /* SINGLE_THREADED or not */ + + } /* ret == ctx */ + } /* else not locked */ + CTX_STACK_CHECK(ctx); + if (ctx->mode != ESP32_SHA_INIT) { +#if defined(WOLFSSL_ESP32_HW_LOCK_DEBUG) + ESP_LOGW(TAG, "esp_sha_release_unfinished_lock mode = %d", ctx->mode); +#endif + if (ctx->mode == ESP32_SHA_HW) { + ESP_LOGW(TAG, "esp_sha_release_unfinished_lock HW!"); } } return ret; -} +} /* esp_sha_release_unfinished_lock */ + /* ** lock HW engine. ** this should be called before using engine. @@ -1159,9 +1145,11 @@ int esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) { int ret = 0; + CTX_STACK_CHECK(ctx); #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - ESP_LOGI(TAG, "enter esp_sha_hw_lock for %x", (int)ctx->initializer); + ESP_LOGI(TAG, "enter esp_sha_hw_lock for %x", + (uintptr_t)ctx->initializer); #endif #ifdef WOLFSSL_DEBUG_MUTEX @@ -1180,22 +1168,28 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* Init mutex * - * Note that even single thread mode may calculate hashes - * concurrently, so we still need to keep track of the - * engine being busy or not. - **/ + * Note that even single thread mode may calculate separate hashes + * concurrently, so we still need to keep track of the engine being + * busy or not. + */ #if defined(SINGLE_THREADED) if (ctx->mode == ESP32_SHA_INIT) { - if (!InUse) { - ctx->mode = ESP32_SHA_HW; - InUse = 1; + if (InUse) { + /* Revert to SW when HW is busy */ + ctx->mode = ESP32_SHA_SW; } else { - ctx->mode = ESP32_SHA_SW; + /* Set single-threaded hardware mode. */ + ctx->mode = ESP32_SHA_HW; + InUse = 1; + #ifdef WOLFSSL_DEBUG_MUTEX + ESP_LOGW(TAG, "\n\nHW in use\n\n"); + #endif } + ret = ESP_OK; } else { - /* this should not happens */ + /* this should not happen */ ESP_LOGE(TAG, "unexpected error in esp_sha_try_hw_lock."); return ESP_FAIL; } @@ -1223,21 +1217,36 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* created, but not yet locked */ ret = esp_CryptHwMutexInit(&sha_mutex); if (ret == 0) { - #ifdef WOLFSSL_DEBUG_MUTEX - ESP_LOGI(TAG, "esp_CryptHwMutexInit sha_mutex init success."); - mutex_ctx_owner = 0; - #endif - } + ESP_LOGV(TAG, "esp_CryptHwMutexInit sha_mutex init success."); + mutex_ctx_owner = NULLPTR; /* No one has the mutex yet.*/ + #ifdef WOLFSSL_DEBUG_MUTEX + { + /* Take mutex for lock/unlock test drive to ensure it works: */ + ret = esp_CryptHwMutexLock(&sha_mutex, (TickType_t)0); + if (ret == ESP_OK) { + ret = esp_CryptHwMutexUnLock(&sha_mutex); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "esp_CryptHwMutexInit fail init lock."); + } + } + else { + ESP_LOGE(TAG, "esp_CryptHwMutexInit fail init unlock."); + } + } + #endif + } /* ret == 0 for esp_CryptHwMutexInit */ else { ESP_LOGE(TAG, "esp_CryptHwMutexInit sha_mutex failed."); - sha_mutex = 0; + #ifdef WOLFSSL_DEBUG_MUTEX + { + ESP_LOGV(TAG, "Current mutext owner = %x", + (int)esp_sha_mutex_ctx_owner()); + } + #endif - ESP_LOGI(TAG, "Revert to ctx->mode = ESP32_SHA_SW."); + sha_mutex = NULL; - #ifdef WOLFSSL_DEBUG_MUTEX - ESP_LOGI(TAG, "Current mutext owner = %x", - (int)esp_sha_mutex_ctx_owner()); - #endif + ESP_LOGV(TAG, "Revert to ctx->mode = ESP32_SHA_SW."); ctx->mode = ESP32_SHA_SW; return ESP_OK; /* success, just not using HW */ @@ -1245,32 +1254,42 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } #ifdef ESP_MONITOR_HW_TASK_LOCK + /* Nothing happening here other than messages based on mutex states */ if (mutex_ctx_task == 0 || mutex_ctx_owner == 0) { /* no known stray mutex task owner */ } else { if (mutex_ctx_task == xTaskGetCurrentTaskHandle()) { - ESP_LOGI(TAG, "Found mutex_ctx_task"); + ESP_LOGV(TAG, "Found mutex_ctx_task"); if (((WC_ESP32SHA*)mutex_ctx_owner)->mode == ESP32_SHA_FREED) { ESP_LOGW(TAG, "ESP32_SHA_FREED unlocking mutex_ctx_task = %x" " for mutex_ctx_owner = %x", - (int)mutex_ctx_task, (int)mutex_ctx_owner ); - esp_CryptHwMutexUnLock(&sha_mutex); - ((WC_ESP32SHA*)mutex_ctx_owner)->mode = ESP32_SHA_INIT; - mutex_ctx_task = 0; - mutex_ctx_owner = 0; + (int)mutex_ctx_task, + (int)mutex_ctx_owner); } else { if (ctx->mode == ESP32_SHA_FREED) { - ESP_LOGW(TAG, "ESP32_SHA_FREED unlocking ctx = %x" - " for ctx.initializer = %x", - (int)ctx, (int)ctx->initializer ); - esp_CryptHwMutexUnLock(&sha_mutex); - ctx->mode = ESP32_SHA_INIT; - mutex_ctx_task = 0; - mutex_ctx_owner = 0; + ESP_LOGW(TAG, "ESP32_SHA_FREED unlocking (disabled) " + "ctx = %x for ctx.initializer = %x", + (uintptr_t)ctx, + (uintptr_t)ctx->initializer); } - } + else { + /* Not very interesting during init. */ + if (ctx->mode == ESP32_SHA_INIT) { + ESP_LOGV(TAG, "mutex_ctx_owner = 0x%x", + mutex_ctx_owner); + ESP_LOGV(TAG, "This ctx = 0x%x is ESP32_SHA_INIT", + (uintptr_t)ctx); + } + else { + ESP_LOGW(TAG, "Not Freed!"); + } + } /* ctx ESP32_SHA_FREED check */ + } /* mutex owner ESP32_SHA_FREED check */ + } /* mutex_ctx_task is current task */ + else { + ESP_LOGW(TAG, "Warning: sha mutex unlock from unexpected task"); } } #endif /* ESP_MONITOR_HW_TASK_LOCK */ @@ -1279,8 +1298,12 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) if (ctx->mode == ESP32_SHA_INIT) { /* try to lock the HW engine */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - ESP_LOGI(TAG, "ESP32_SHA_INIT for %x\n", (int)ctx->initializer); + ESP_LOGI(TAG, "ESP32_SHA_INIT for %x\n", (uintptr_t)ctx->initializer); #endif + ESP_LOGV(TAG, "Init; release unfinished ESP32_SHA_INIT lock " + "for ctx 0x%x", (uintptr_t)ctx); + esp_sha_release_unfinished_lock(ctx); + /* lock hardware; there should be exactly one instance * of esp_CryptHwMutexLock(&sha_mutex ...) in code. * @@ -1290,16 +1313,20 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) * TODO: allow for SHA interleave on chips that support it. */ - if (esp_CryptHwMutexLock(&sha_mutex, (TickType_t)0) == 0) { + if ((mutex_ctx_owner == NULLPTR) && + esp_CryptHwMutexLock(&sha_mutex, (TickType_t)0) == ESP_OK) { /* we've successfully locked */ + mutex_ctx_owner = (uintptr_t)ctx; + ESP_LOGV(TAG, "Assigned mutex_ctx_owner to 0x%x", mutex_ctx_owner); #ifdef ESP_MONITOR_HW_TASK_LOCK mutex_ctx_task = xTaskGetCurrentTaskHandle(); #endif #ifdef WOLFSSL_DEBUG_MUTEX - if (esp_sha_call_count() == 8 && WOLFSSL_TEST_STRAY) { - /* Once we've locked 10 times here, - * we'll force a fallback to SW until other thread unlocks. */ + if (WOLFSSL_TEST_STRAY_INJECT) { + ESP_LOGW(TAG, "Introducing SHA stray for testing"); + /* Once we've locked [n] times here, + * we'll force a fallback to SW until other thread unlocks. */ taskENTER_CRITICAL(&sha_crit_sect); { (void)stray_ctx; @@ -1307,8 +1334,8 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* no peek task */ } else { - stray_ctx->initializer = stray_ctx; - mutex_ctx_owner = (void*)stray_ctx->initializer; + stray_ctx->initializer = (intptr_t)stray_ctx; + mutex_ctx_owner = (intptr_t)stray_ctx->initializer; } } taskEXIT_CRITICAL(&sha_crit_sect); @@ -1318,8 +1345,8 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) "set the stay test?"); } else { - ESP_LOGI(TAG, "%x", (int)stray_ctx->initializer); - ESP_LOGI(TAG, "%x", (int)&stray_ctx); + ESP_LOGI(TAG, "%x", (uintptr_t)stray_ctx->initializer); + ESP_LOGI(TAG, "%x", (uintptr_t)&stray_ctx); ESP_LOGW(TAG, "\n\nLocking with stray\n\n" "WOLFSSL_DEBUG_MUTEX call count 8, " @@ -1335,17 +1362,22 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* check to see if we had a prior fail and need to unroll enables */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGW(TAG, "Locking for ctx %x, current mutex_ctx_owner = %x", - (int)&ctx, (int)esp_sha_mutex_ctx_owner()); + (uintptr_t)&ctx, esp_sha_mutex_ctx_owner()); + ESP_LOGI(TAG, "ctx->lockDepth = %d", ctx->lockDepth); #endif - ret = esp_unroll_sha_module_enable(ctx); + if (ctx->mode == ESP32_SHA_INIT) { + /* Set non-single-threaded hardware mode */ + esp_set_hw(ctx); + } + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGI(TAG, "Hardware Mode Active, lock depth = %d, for %x", - ctx->lockDepth, (int)ctx->initializer); + ctx->lockDepth, (uintptr_t)ctx->initializer); #endif #ifdef WOLFSSL_DEBUG_MUTEX taskENTER_CRITICAL(&sha_crit_sect); { - mutex_ctx_owner = (void*)ctx->initializer; + mutex_ctx_owner = (uintptr_t)ctx->initializer; /* let's keep track of how many times we lock this */ _sha_lock_count++; } @@ -1357,23 +1389,42 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) ** as the mutex should be gate keeping */ ESP_LOGW(TAG, "WARNING: Hardware Mode " "interesting lock depth = %d, for this %x", - ctx->lockDepth, (int)ctx->initializer); + ctx->lockDepth, (uintptr_t)ctx->initializer); } } else { - /* We should have otherwise anticipated this; how did we get here? - ** This code should rarely, ideally never be reached. */ - #ifdef WOLFSSL_DEBUG_MUTEX - ESP_LOGI(TAG, "\nHardware in use by %x; " - "Mode REVERT to ESP32_SHA_SW for %x\n", - (int)esp_sha_mutex_ctx_owner(), - (int)ctx->initializer); - ESP_LOGI(TAG, "Software Mode, lock depth = %d, for this %x", - ctx->lockDepth, (int)ctx->initializer); - ESP_LOGI(TAG, "Current mutext owner = %x", - (int)esp_sha_mutex_ctx_owner()); - #endif - ctx->mode = ESP32_SHA_SW; + /* When the lock is already in use: is it for this ctx? */ + if ((uintptr_t)ctx == esp_sha_mutex_ctx_owner()) { + ESP_LOGV(TAG, "I'm the owner! 0x%x", (uintptr_t)ctx); + ctx->mode = ESP32_SHA_SW; + } + else { + #ifdef WOLFSSL_DEBUG_MUTEX + ESP_LOGW(TAG, "\nHardware in use by %x; " + "Mode REVERT to ESP32_SHA_SW for %x\n", + esp_sha_mutex_ctx_owner(), + (uintptr_t)ctx->initializer); + ESP_LOGI(TAG, "Software Mode, lock depth = %d, for this %x", + ctx->lockDepth, (uintptr_t)ctx->initializer); + ESP_LOGI(TAG, "Current mutext owner = %x", + esp_sha_mutex_ctx_owner()); + #endif + ESP_LOGV(TAG, "I'm not owner! 0x%x; owner = 0x%x", + (uintptr_t)ctx, mutex_ctx_owner); + if (mutex_ctx_owner) { + #ifdef WOLFSSL_DEBUG_MUTEX + ESP_LOGW(TAG, "revert to SW since mutex_ctx_owner = %x" + " but we are currently ctx = %x", + mutex_ctx_owner, (intptr_t)ctx); + #endif + } + else { + /* No ctx mutex owner, so hardware must be free. */ + } + ESP_LOGV(TAG, "Set update ctx->mode = SW (from %d) for 0x%x", + ctx->mode, (uintptr_t)ctx ); + ctx->mode = ESP32_SHA_SW; + } return ESP_OK; /* success, but revert to SW */ } } /* (ctx->mode == ESP32_SHA_INIT) */ @@ -1384,33 +1435,44 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } #endif /* not defined(SINGLE_THREADED) */ -#if defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) - { - ESP_LOGV(TAG, "ets_sha_enable for RISC-V"); - ets_sha_enable(); - ctx->mode = ESP32_SHA_HW; - } -#else - if (ret == 0) { + ESP_LOGV(TAG, "ctx->mode = %d", ctx->mode); + if ((ret == ESP_OK) && (ctx->mode == ESP32_SHA_HW)) { ctx->lockDepth++; /* depth for THIS ctx (there could be others!) */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG { - printf("1) Lock depth @ %d = %d for WC_ESP32SHA @ %0x\n", - __LINE__, ctx->lockDepth, (unsigned)ctx); + ESP_LOGI(TAG, "1) Lock depth @ %d = %d for WC_ESP32SHA @ %0x\n", + __LINE__, ctx->lockDepth, (unsigned)ctx); } #endif - periph_module_enable(PERIPH_SHA_MODULE); - ctx->mode = ESP32_SHA_HW; + #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP8684) || \ + defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32C6) + { + ESP_LOGV(TAG, "ets_sha_enable for RISC-V"); + ets_sha_enable(); + } + #else + ESP_LOGV(TAG, "ets_sha_enable for Xtensa"); + periph_module_enable(PERIPH_SHA_MODULE); + #endif } else { - ESP_LOGW(TAG, ">>>> Other problem; Mode REVERT to ESP32_SHA_SW"); + /* Set to SW */ + #ifdef WOLFSSL_ESP32_CRYPT_DEBUG + if (ret == ESP_OK) { + ESP_LOGW(TAG, "Normal SHA Software fallback mode."); + } + else { + ESP_LOGW(TAG, "Warning: Unexpected Mode REVERT to ESP32_SHA_SW" + ", err = %d", ret); + } + #endif ctx->mode = ESP32_SHA_SW; } -#endif + ESP_LOGV(TAG, "leave esp_sha_hw_lock"); + CTX_STACK_CHECK(ctx); return ret; } /* esp_sha_try_hw_lock */ @@ -1422,61 +1484,80 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) int esp_sha_hw_unlock(WC_ESP32SHA* ctx) { int ret = ESP_OK; /* assume success (zero) */ + CTX_STACK_CHECK(ctx); #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGV(TAG, "enter esp_sha_hw_unlock"); #endif -#if defined(CONFIG_IDF_TARGET_ESP32C2) || \ - defined(CONFIG_IDF_TARGET_ESP8684) || \ - defined(CONFIG_IDF_TARGET_ESP32C3) || \ - defined(CONFIG_IDF_TARGET_ESP32C6) - ets_sha_disable(); /* disable also resets active, ongoing hash */ - ESP_LOGV(TAG, "ets_sha_disable in esp_sha_hw_unlock()"); -#else - /* Disable AES hardware */ - periph_module_disable(PERIPH_SHA_MODULE); -#endif /* we'll keep track of our lock depth. * in case of unexpected results, all the periph_module_disable() calls * and periph_module_disable() need to be unwound. * * see ref_counts[periph] in file: periph_ctrl.c */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - printf("2) esp_sha_hw_unlock Lock depth @ %d = %d for WC_ESP32SHA @ %0x\n", - __LINE__, ctx->lockDepth, (unsigned)ctx); + ESP_LOGI(TAG, "2) esp_sha_hw_unlock Lock depth @ %d = %d " + "for WC_ESP32SHA ctx @ %p\n", + __LINE__, ctx->lockDepth, ctx); #endif + + if (ctx->lockDepth > 0) { + #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP8684) || \ + defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32C6) + ets_sha_disable(); /* disable also resets active, ongoing hash */ + ESP_LOGV(TAG, "ets_sha_disable in esp_sha_hw_unlock()"); + #else + periph_module_disable(PERIPH_SHA_MODULE); + #endif ctx->lockDepth--; } else { + ESP_LOGW(TAG, "lockDepth <= 0; Disable SHA module skipped for %x", + (uintptr_t)ctx->initializer); ctx->lockDepth = 0; } #if defined(ESP_MONITOR_HW_TASK_LOCK) && defined(WOLFSSL_ESP32_HW_LOCK_DEBUG) - printf("3) esp_sha_hw_unlock Lock depth @ %d = %d for WC_ESP32SHA @ %0x\n", - __LINE__, ctx->lockDepth, (unsigned)ctx); + ESP_LOGI(TAG, "3) esp_sha_hw_unlock Lock depth @ %d = %d " + "for WC_ESP32SHA @ %0x\n", + __LINE__, ctx->lockDepth, (uintptr_t)ctx); #endif - if (0 == ctx->lockDepth) - { + + if (0 != ctx->lockDepth) { + /* If the lockdepth is not zero, unlock success unknown. */ + ESP_LOGE(TAG, "ERROR Non-zero lockDepth. Stray code lock?"); + ret = ESP_FAIL; + } + else { #if defined(SINGLE_THREADED) + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG + { + ESP_LOGW(TAG, "HW released, not in use."); + } + #endif InUse = 0; #else - /* unlock HW engine for next use */ + /* Hardware was unlocked above, now update semaphores. */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG { - ESP_LOGW(TAG, "Unlocking for %x, from ctx %x, & = %x, " - "mutex_ctx_owner = %x", - (int)esp_sha_mutex_ctx_owner(), - (int)ctx, - (int)&ctx, - (int)esp_sha_mutex_ctx_owner()); - ESP_LOGW(TAG, "&sha_mutex = %x", (int)&sha_mutex); + ESP_LOGW(TAG, "Unlocking for mutex_ctx_owner %x, from ctx 0x%x", + esp_sha_mutex_ctx_owner(), (uintptr_t)ctx); + ESP_LOGV(TAG, "&sha_mutex = %x", (intptr_t)&sha_mutex); } #endif /* WOLFSSL_ESP32_HW_LOCK_DEBUG */ + + /* There should be exactly 1 instance of SHA unlock, and it's here: */ esp_CryptHwMutexUnLock(&sha_mutex); + /* We don't set owner to zero here. The HW is not in use, + * but there may be a WIP hash calc (e.g. sha update). + * NO: mutex_ctx_owner = NULLPTR; */ + #ifdef ESP_MONITOR_HW_TASK_LOCK mutex_ctx_task = 0; #endif + #endif #ifdef WOLFSSL_DEBUG_MUTEX @@ -1487,14 +1568,12 @@ int esp_sha_hw_unlock(WC_ESP32SHA* ctx) taskEXIT_CRITICAL(&sha_crit_sect); #endif } - else - { - ESP_LOGE(TAG, "ERROR unlock lockDepth not zero"); - ret = ESP_FAIL; - } + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - ESP_LOGI(TAG, "leave esp_sha_hw_unlock, %x", (int)ctx->initializer); + ESP_LOGI(TAG, "leave esp_sha_hw_unlock, %x", + (uintptr_t)ctx->initializer); #endif + CTX_STACK_CHECK(ctx); return ret; } /* esp_sha_hw_unlock */ @@ -1513,7 +1592,7 @@ int esp_sha_hw_unlock(WC_ESP32SHA* ctx) /* Everything else uses esp_sha_start_process() */ static int esp_sha_start_process(WC_ESP32SHA* sha) { - int ret = 0; + int ret = ESP_OK; #if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) uint8_t HardwareAlgorithm; #endif @@ -1521,6 +1600,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) if (sha == NULL) { return BAD_FUNC_ARG; } + CTX_STACK_CHECK(sha); ESP_LOGV(TAG, " enter esp_sha_start_process"); @@ -1531,7 +1611,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) ESP_LOGV(TAG, "SHA1 SHA_START_REG"); if (sha->isfirstblock) { sha_ll_start_block(SHA2_256); - sha->isfirstblock = false; + sha->isfirstblock = 0; ESP_LOGV(TAG, " set sha->isfirstblock = 0"); @@ -1584,7 +1664,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) if (sha->isfirstblock) { REG_WRITE(SHA_START_REG, 1); - sha->isfirstblock = false; + sha->isfirstblock = 0; ESP_LOGV(TAG, " set sha->isfirstblock = 0"); @@ -1635,7 +1715,7 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) break; } - sha->isfirstblock = false; + sha->isfirstblock = 0; ESP_LOGV(TAG, " set sha->isfirstblock = 0"); #if defined(DEBUG_WOLFSSL) @@ -1687,9 +1767,10 @@ static int esp_sha_start_process(WC_ESP32SHA* sha) ESP_LOGV(TAG, " continue block #%d", this_block_num); #endif - ESP_LOGV(TAG, " leave esp_sha_start_process"); + ESP_LOGV(TAG, " leave esp_sha_start_process"); + CTX_STACK_CHECK(sha); - return ret; + return ret; } #endif /* esp_sha_start_process !CONFIG_IDF_TARGET_ESP32C3/C6 */ @@ -1705,12 +1786,22 @@ static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ #if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) word32* MessageSource; word32* AcceleratorMessage; + #define MAX_SHA_VALUE SHA_TYPE_MAX #elif CONFIG_IDF_TARGET_ESP32 int i; + /* Only values 0 .. 3 are valid for ESP32; SHA_INVALID = -1 */ + #define MAX_SHA_VALUE 4 #else - /* not used */ + /* Newer SoC devices have a different value: SHA_TYPE_MAX */ + #define MAX_SHA_VALUE SHA_TYPE_MAX #endif ESP_LOGV(TAG, " enter esp_process_block"); + + if ((ctx->sha_type < 0) || (ctx->sha_type > MAX_SHA_VALUE)) { + ESP_LOGE(TAG, "Unexpected sha_type: %d", ctx->sha_type); + } + CTX_STACK_CHECK(ctx); + if (word32_to_save > 0x31) { word32_to_save = 0x31; ESP_LOGE(TAG, " ERROR esp_process_block length exceeds 0x31 words."); @@ -1722,10 +1813,10 @@ static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ #if defined(CONFIG_IDF_TARGET_ESP32) /* load [len] words of message data into HW */ for (i = 0; i < word32_to_save; i++) { - /* by using DPORT_REG_WRITE, we avoid the need + /* By using DPORT_REG_WRITE, we avoid the need * to call __builtin_bswap32 to address endianness. * - * a useful watch array cast to watch at runtime: + * A useful watch array cast to watch at runtime: * ((word32[32]) (*(volatile word32 *)(SHA_TEXT_BASE))) * * Write value to DPORT register (does not require protecting) @@ -1733,7 +1824,7 @@ static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ DPORT_REG_WRITE(SHA_TEXT_BASE + (i*sizeof(word32)), *(data + i)); /* memw confirmed auto inserted by compiler here */ } - /* notify HW to start process + /* Notify HW to start process * see ctx->sha_type * reg data does not change until we are ready to read */ ret = esp_sha_start_process(ctx); @@ -1759,7 +1850,7 @@ static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ * ((word32[16]) (*(volatile uint32_t *)(SHA_TEXT_BASE))) */ if (&data != _active_digest_address) { - ESP_LOGV(TAG, "TODO Moving alternate ctx->for_digest"); + ESP_LOGV(TAG, "Moving alternate ctx->for_digest"); /* move last known digest into HW reg during interleave */ /* sha_ll_write_digest(ctx->sha_type, ctx->for_digest, WC_SHA256_BLOCK_SIZE); */ @@ -1838,6 +1929,7 @@ static int wc_esp_process_block(WC_ESP32SHA* ctx, /* see ctx->sha_type */ } #endif + CTX_STACK_CHECK(ctx); ESP_LOGV(TAG, " leave esp_process_block"); return ret; } /* wc_esp_process_block */ @@ -1857,6 +1949,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) #endif ESP_LOGV(TAG, "enter esp_digest_state"); + CTX_STACK_CHECK(ctx); if (ctx == NULL) { return BAD_FUNC_ARG; @@ -1871,7 +1964,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) defined(CONFIG_IDF_TARGET_ESP32S2) || \ defined(CONFIG_IDF_TARGET_ESP32S3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) - if (ctx->sha_type == SHA_TYPE_MAX) { + if (ctx->sha_type >= SHA_TYPE_MAX) { #else ESP_LOGE(TAG, "unexpected target for wc_esp_digest_state"); { @@ -1889,7 +1982,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) } #if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) - if (ctx->isfirstblock == true) { + if (ctx->isfirstblock == 1) { /* no hardware use yet. Nothing to do yet */ return ESP_OK; } @@ -1937,7 +2030,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) wc_esp_sha_digest_size(ctx->sha_type) / sizeof(word32) ); #else - /* not CONFIG_IDF_TARGET_ESP32S3 */ + /* Not CONFIG_IDF_TARGET_ESP32S3 */ /* wait until idle */ wc_esp_wait_until_idle(); @@ -1946,9 +2039,11 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) + #elif defined(CONFIG_IDF_TARGET_ESP32S2) - /* nothing here for S2 */ + #else + switch (ctx->sha_type) { case SHA1: DPORT_REG_WRITE(SHA_1_LOAD_REG, 1); @@ -1975,7 +2070,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) return ESP_FAIL; } - if (ctx->isfirstblock == true) { + if (ctx->isfirstblock == 1) { /* no hardware use yet. Nothing to do yet */ return ESP_OK; } @@ -1999,7 +2094,9 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) * example: * DPORT_SEQUENCE_REG_READ(address + i * 4); */ - + #ifdef WOLFSSL_ESP32_CRYPT_DEBUG + ESP_LOGW(TAG, "SHA HW read..."); + #endif esp_dport_access_read_buffer( #if ESP_IDF_VERSION_MAJOR >= 4 (uint32_t*)(hash), /* the result will be found in hash upon exit */ @@ -2024,6 +2121,7 @@ int wc_esp_digest_state(WC_ESP32SHA* ctx, byte* hash) } #endif /* SHA512 or SHA384*/ #endif /* not CONFIG_IDF_TARGET_ESP32S3, C3, else... */ + CTX_STACK_CHECK(ctx); ESP_LOGV(TAG, "leave esp_digest_state"); return ESP_OK; @@ -2061,13 +2159,19 @@ int esp_sha_digest_process(struct wc_Sha* sha, byte blockprocess) ret = wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); + if (blockprocess) { + ESP_LOGV(TAG, "esp_sha_digest_process NEW UNLOCK"); + esp_sha_hw_unlock(&sha->ctx); /* also unlocks mutex */ + ESP_LOGV(TAG, "sha blockprocess mutex_ctx_owner = NULLPTR"); + mutex_ctx_owner = NULLPTR; + } + ESP_LOGV(TAG, "leave esp_sha_digest_process"); return ret; } /* esp_sha_digest_process */ #endif /* NO_SHA */ - #if !defined(NO_SHA256) && !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) /* ** sha256 process @@ -2078,8 +2182,6 @@ int esp_sha256_process(struct wc_Sha256* sha, const byte* data) { int ret = 0; - ESP_LOGV(TAG, " enter esp_sha256_process"); - switch ((&sha->ctx)->sha_type) { case SHA2_256: #if defined(DEBUG_WOLFSSL_VERBOSE) @@ -2131,6 +2233,13 @@ int esp_sha256_digest_process(struct wc_Sha256* sha, byte blockprocess) } wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); + + if (blockprocess) { + ESP_LOGV(TAG, "esp_sha256_digest_process blockprocess UNLOCK"); + esp_sha_hw_unlock(&sha->ctx); /* also unlocks mutex */ + ESP_LOGV(TAG, "blockprocess mutex_ctx_owner = NULLPTR"); + mutex_ctx_owner = NULLPTR; + } #else ESP_LOGE(TAG, "Call esp_sha256_digest_process with " "NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256 "); @@ -2198,7 +2307,7 @@ int esp_sha512_block(struct wc_Sha512* sha, const word32* data, byte isfinal) */ int esp_sha512_process(struct wc_Sha512* sha) { - int ret = 0; /* assume success */ + int ret = ESP_OK; /* assume success */ word32 *data = (word32*)sha->buffer; ESP_LOGV(TAG, "enter esp_sha512_process"); @@ -2230,6 +2339,7 @@ int esp_sha512_digest_process(struct wc_Sha512* sha, byte blockproc) ret = esp_sha512_block(sha, data, 1); } + if (sha->ctx.mode == ESP32_SHA_HW) { ret = wc_esp_digest_state(&sha->ctx, (byte*)sha->digest); } @@ -2237,6 +2347,12 @@ int esp_sha512_digest_process(struct wc_Sha512* sha, byte blockproc) ESP_LOGW(TAG, "Call esp_sha512_digest_process in non-HW mode?"); } + if (blockproc) { + ESP_LOGV(TAG, "esp_sha512_digest_process NEW UNLOCK"); + esp_sha_hw_unlock(&sha->ctx); /* also unlocks mutex */ + ESP_LOGV(TAG, "mutex_ctx_owner = NULLPTR"); + mutex_ctx_owner = NULLPTR; + } ESP_LOGV(TAG, "leave esp_sha512_digest_process"); #endif return ret; @@ -2289,6 +2405,24 @@ int esp_hw_show_sha_metrics(void) return ret; } + #endif /* WOLFSSL_ESP32_CRYPT and WOLFSSL_HW_METRICS */ -#endif /* WOLFSSL_ESPIDF (exclude entire contents for non-Espressif projects */ +#if defined(WOLFSSL_STACK_CHECK) +int esp_sha_stack_check(WC_ESP32SHA* sha) { + int ret = ESP_OK; + + if (sha == NULL) { + ESP_LOGW(TAG, "esp_sha_stack_check; sha is NULL"); + } + else { + if (sha->first_word != 0 || sha->last_word != 0) { + ESP_LOGE(TAG, "esp_sha_stack_check warning"); + ret = ESP_FAIL; + } + } + return ret; +} +#endif /* WOLFSSL_STACK_CHECK */ + +#endif /* WOLFSSL_ESPIDF (exclude entire contents for non-Espressif projects. */ diff --git a/src/wolfcrypt/src/port/Espressif/esp32_util.c b/src/wolfcrypt/src/port/Espressif/esp32_util.c index 829afa4..793554a 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_util.c @@ -1,6 +1,6 @@ /* esp32_util.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -36,6 +36,7 @@ #include #if ESP_IDF_VERSION_MAJOR > 4 #include + #include #endif /* wolfSSL */ #include /* needed to print MATH_INT_T value */ @@ -76,7 +77,7 @@ static int esp_ShowMacroStatus_need_header = 0; #include #include -/* big nums can be very long, perhaps unitialized, so limit displayed words */ +/* big nums can be very long, perhaps uninitialized, so limit displayed words */ #define MAX_WORDS_ESP_SHOW_MP 32 /* @@ -118,7 +119,7 @@ int esp_CryptHwMutexLock(wolfSSL_Mutex* mutex, TickType_t block_time) { * call the ESP-IDF mutex UNlock; xSemaphoreGive * */ -int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex) { +esp_err_t esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex) { if (mutex == NULL) { WOLFSSL_ERROR_MSG("esp_CryptHwMutexLock called with null mutex"); return BAD_MUTEX_E; @@ -151,6 +152,13 @@ int esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex) { #if defined(WOLFSSL_ESPIDF) static int ShowExtendedSystemInfo_platform_espressif(void) { +#ifdef WOLFSSL_ESP_NO_WATCHDOG + ESP_LOGI(TAG, "Found WOLFSSL_ESP_NO_WATCHDOG"); +#else + ESP_LOGW(TAG, "Watchdog active; " + "missing WOLFSSL_ESP_NO_WATCHDOG definition."); +#endif + #if defined(CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ) WOLFSSL_VERSION_PRINTF("CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ: %u MHz", CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ); @@ -219,8 +227,10 @@ static int ShowExtendedSystemInfo_platform_espressif(void) /* not supported at this time */ #endif - /* check to see if we are using hardware encryption */ -#if defined(NO_ESP32_CRYPT) +/* check to see if we are using hardware encryption */ +#if defined(CONFIG_IDF_TARGET_ESP8266) + WOLFSSL_VERSION_PRINTF("No HW acceleration on ESP8266."); +#elif defined(NO_ESP32_CRYPT) WOLFSSL_VERSION_PRINTF("NO_ESP32_CRYPT defined! " "HW acceleration DISABLED."); #else @@ -246,7 +256,7 @@ static int ShowExtendedSystemInfo_platform_espressif(void) #error "ESP32_CRYPT not yet supported on this IDF TARGET" #endif - /* Even though enabled, some specifics may be disabled */ + /* Even though enabled, some specifics may be disabled */ #if defined(NO_WOLFSSL_ESP32_CRYPT_HASH) WOLFSSL_VERSION_PRINTF("NO_WOLFSSL_ESP32_CRYPT_HASH is defined!" "(disabled HW SHA)."); @@ -385,11 +395,11 @@ int esp_current_boot_count(void) /* See macro helpers above; not_defined is macro name when *not* defined */ static int show_macro(char* s, char* not_defined) { - char hd1[] = "Macro Name Defined Not Defined"; - char hd2[] = "------------------------- --------- -------------"; - char msg[] = "......................... "; - /* 012345678901234567890123456789012345678901234567890 */ - /* 1 2 3 4 5 */ + const char hd1[] = "Macro Name Defined Not Defined"; + char hd2[] = "------------------------- --------- -------------"; + char msg[] = "......................... "; + /* 012345678901234567890123456789012345678901234567890 */ + /* 1 2 3 4 5 */ size_t i = 0; #define MAX_STATUS_NAME_LENGTH 25 #define ESP_SMS_ENA_POS 30 @@ -424,7 +434,7 @@ static int show_macro(char* s, char* not_defined) } /* Show some interesting settings */ -int ShowExtendedSystemInfo_config(void) +esp_err_t ShowExtendedSystemInfo_config(void) { esp_ShowMacroStatus_need_header = 1; @@ -454,6 +464,7 @@ int ShowExtendedSystemInfo_config(void) /* Optimizations */ show_macro("RSA_LOW_MEM", STR_IFNDEF(RSA_LOW_MEM)); + show_macro("SMALL_SESSION_CACHE", STR_IFNDEF(SMALL_SESSION_CACHE)); /* Security Hardening */ show_macro("WC_NO_HARDEN", STR_IFNDEF(WC_NO_HARDEN)); @@ -473,6 +484,8 @@ int ShowExtendedSystemInfo_config(void) show_macro("WOLFSSL_AES_NO_UNROLL", STR_IFNDEF(WOLFSSL_AES_NO_UNROLL)); show_macro("TFM_TIMING_RESISTANT", STR_IFNDEF(TFM_TIMING_RESISTANT)); show_macro("ECC_TIMING_RESISTANT", STR_IFNDEF(ECC_TIMING_RESISTANT)); + + /* WC_RSA_BLINDING takes up additional space: */ show_macro("WC_RSA_BLINDING", STR_IFNDEF(WC_RSA_BLINDING)); show_macro("NO_WRITEV", STR_IFNDEF(NO_WRITEV)); @@ -482,7 +495,7 @@ int ShowExtendedSystemInfo_config(void) show_macro("WOLFSSL_NO_CURRDIR", STR_IFNDEF(WOLFSSL_NO_CURRDIR)); show_macro("WOLFSSL_LWIP", STR_IFNDEF(WOLFSSL_LWIP)); - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); #if defined(CONFIG_COMPILER_OPTIMIZATION_DEFAULT) ESP_LOGI(TAG, "Compiler Optimization: Default"); #elif defined(CONFIG_COMPILER_OPTIMIZATION_SIZE) @@ -494,7 +507,7 @@ int ShowExtendedSystemInfo_config(void) #else ESP_LOGI(TAG, "Compiler Optimization: Unknown"); #endif - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); return ESP_OK; } @@ -629,7 +642,7 @@ int ShowExtendedSystemInfo(void) #ifdef INCLUDE_uxTaskGetStackHighWaterMark ESP_LOGI(TAG, "Stack HWM: %d", uxTaskGetStackHighWaterMark(NULL)); #endif - ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); ShowExtendedSystemInfo_config(); ShowExtendedSystemInfo_git(); @@ -643,29 +656,111 @@ int ShowExtendedSystemInfo(void) return ESP_OK; } -int esp_ShowExtendedSystemInfo(void) +esp_err_t esp_ShowExtendedSystemInfo(void) { /* Someday the ShowExtendedSystemInfo may be global. * See https://github.com/wolfSSL/wolfssl/pull/6149 */ return ShowExtendedSystemInfo(); } +/* + * Disable the watchdog timer (use with caution) + */ + +esp_err_t esp_DisableWatchdog(void) +{ + esp_err_t ret = ESP_OK; +#if defined(CONFIG_IDF_TARGET_ESP8266) + /* magic bit twiddle to disable WDT on ESP8266 */ + *((volatile uint32_t*) 0x60000900) &= ~(1); +#elif CONFIG_IDF_TARGET_ESP32S3 + ESP_LOGW(TAG, "esp_DisableWatchdog TODO S3"); +#else + #if ESP_IDF_VERSION_MAJOR >= 5 + { + #if defined(CONFIG_IDF_TARGET_ESP32) + rtc_wdt_protect_off(); + rtc_wdt_disable(); + #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32C6) || \ + defined(CONFIG_IDF_TARGET_ESP32H2) + ESP_LOGW(TAG, "No known rtc_wdt_protect_off for this platform."); + #else + rtc_wdt_protect_off(); + rtc_wdt_disable(); + #endif + } + #else + ESP_LOGW(TAG, "esp_DisableWatchdog not implemented on ESP_OIDF v%d", + ESP_IDF_VERSION_MAJOR); + #endif +#endif + +#ifdef DEBUG_WOLFSSL + ESP_LOGI(TAG, "Watchdog disabled."); +#endif + + return ret; +} + +/* + * Enable the watchdog timer. + */ + +esp_err_t esp_EnabledWatchdog(void) +{ + esp_err_t ret = ESP_OK; +#if defined(CONFIG_IDF_TARGET_ESP8266) + /* magic bit twiddle to enable WDT on ESP8266 */ + *((volatile uint32_t*) 0x60000900) |= 1; +#elif CONFIG_IDF_TARGET_ESP32S3 + ESP_LOGW(TAG, "esp_EnableWatchdog TODO S3"); +#else + #if ESP_IDF_VERSION_MAJOR >= 5 + { + #if defined(CONFIG_IDF_TARGET_ESP32) + rtc_wdt_protect_on(); + rtc_wdt_enable(); + #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32C6) || \ + defined(CONFIG_IDF_TARGET_ESP32H2) + ESP_LOGW(TAG, "No known rtc_wdt_protect_off for this platform."); + #else + rtc_wdt_protect_on(); + rtc_wdt_enable(); + #endif + } + #else + ESP_LOGW(TAG, "esp_DisableWatchdog not implemented on ESP_OIDF v%d", + ESP_IDF_VERSION_MAJOR); + #endif +#endif + +#ifdef DEBUG_WOLFSSL + ESP_LOGI(TAG, "Watchdog enabled."); +#endif + + return ret; +} + /* Print a MATH_INT_T attribute list. * * Note with the right string parameters, the result can be pasted as * initialization code. */ -int esp_show_mp_attributes(char* c, MATH_INT_T* X) +esp_err_t esp_show_mp_attributes(char* c, MATH_INT_T* X) { static const char* MP_TAG = "MATH_INT_T"; - int ret = ESP_OK; + esp_err_t ret = ESP_OK; if (X == NULL) { ret = ESP_FAIL; ESP_LOGV(MP_TAG, "esp_show_mp_attributes called with X == NULL"); } else { - ESP_LOGI(MP_TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(MP_TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); ESP_LOGI(MP_TAG, "%s.used = %d;", c, X->used); #if defined(WOLFSSL_SP_INT_NEGATIVE) || defined(USE_FAST_MATH) ESP_LOGI(MP_TAG, "%s.sign = %d;", c, X->sign); @@ -679,10 +774,10 @@ int esp_show_mp_attributes(char* c, MATH_INT_T* X) * Note with the right string parameters, the result can be pasted as * initialization code. */ -int esp_show_mp(char* c, MATH_INT_T* X) +esp_err_t esp_show_mp(char* c, MATH_INT_T* X) { static const char* MP_TAG = "MATH_INT_T"; - int ret = MP_OKAY; + esp_err_t ret = ESP_OK; int words_to_show = 0; if (X == NULL) { @@ -717,16 +812,16 @@ int esp_show_mp(char* c, MATH_INT_T* X) i /* the index, again, for comment */ ); } - ESP_LOGI(MP_TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); + ESP_LOGI(MP_TAG, WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); } return ret; } /* Perform a full mp_cmp and binary compare. * (typically only used during debugging) */ -int esp_mp_cmp(char* name_A, MATH_INT_T* A, char* name_B, MATH_INT_T* B) +esp_err_t esp_mp_cmp(char* name_A, MATH_INT_T* A, char* name_B, MATH_INT_T* B) { - int ret = MP_OKAY; + esp_err_t ret = ESP_OK; int e = memcmp(A, B, sizeof(mp_int)); if (mp_cmp(A, B) == MP_EQ) { if (e == 0) { @@ -769,6 +864,7 @@ int esp_mp_cmp(char* name_A, MATH_INT_T* A, char* name_B, MATH_INT_T* B) } if (ret == MP_OKAY) { + ret = ESP_OK; ESP_LOGV(TAG, "esp_mp_cmp equal for %s and %s!", name_A, name_B); } @@ -779,7 +875,7 @@ int esp_mp_cmp(char* name_A, MATH_INT_T* A, char* name_B, MATH_INT_T* B) return ret; } -int esp_hw_show_metrics(void) +esp_err_t esp_hw_show_metrics(void) { #if defined(WOLFSSL_HW_METRICS) #if defined(WOLFSSL_ESP32_CRYPT) diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c new file mode 100644 index 0000000..8c5cd37 --- /dev/null +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c @@ -0,0 +1,280 @@ +/* esp_sdk_mem_lib.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +/* wolfSSL */ +/* Always include wolfcrypt/settings.h before any other wolfSSL file. */ +/* Reminder: settings.h pulls in user_settings.h; don't include it here. */ +#ifdef WOLFSSL_USER_SETTINGS + #include +#endif + +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ + +#if defined(WOLFSSL_USER_SETTINGS) + #include +#else + /* Define WOLFSSL_USER_SETTINGS project wide for settings.h to include */ + /* wolfSSL user settings in ./components/wolfssl/include/user_settings.h */ + #error "Missing WOLFSSL_USER_SETTINGS in CMakeLists or Makefile:\ + CFLAGS +=-DWOLFSSL_USER_SETTINGS" +#endif + +#ifndef SINGLE_THREADED + #ifdef PLATFORMIO + #include + #else + #include "semphr.h" + #endif +#endif + +/* Espressif */ +#include "sdkconfig.h" /* programmatically generated from sdkconfig */ +#include +#include + +/* wolfSSL */ +#include + +static const char* TAG = "mem lib"; +static intptr_t _starting_stack_pointer = 0; +static int _stack_used = 0; + + +/* see + * C:\SysGCC\esp8266\rtos-sdk\v3.4\components\esp8266\ld\esp8266.project.ld.in + */ +extern wc_ptr_t _data_start[]; +extern wc_ptr_t _data_end[]; +extern wc_ptr_t _rodata_start[]; +extern wc_ptr_t _rodata_end[]; +extern wc_ptr_t _bss_start[]; +extern wc_ptr_t _bss_end[]; +extern wc_ptr_t _rtc_data_start[]; +extern wc_ptr_t _rtc_data_end[]; +extern wc_ptr_t _rtc_bss_start[]; +extern wc_ptr_t _rtc_bss_end[]; +extern wc_ptr_t _iram_start[]; +extern wc_ptr_t _iram_end[]; +#if defined(CONFIG_IDF_TARGET_ESP8266) +extern wc_ptr_t _init_start[]; +extern wc_ptr_t _init_end[]; +#endif +extern wc_ptr_t _iram_text_start[]; +extern wc_ptr_t _iram_text_end[]; +extern wc_ptr_t _iram_bss_start[]; +extern wc_ptr_t _iram_bss_end[]; +extern wc_ptr_t _noinit_start[]; +extern wc_ptr_t _noinit_end[]; +extern wc_ptr_t _text_start[]; +extern wc_ptr_t _text_end[]; +extern wc_ptr_t _heap_start[]; +extern wc_ptr_t _heap_end[]; +extern wc_ptr_t _rtc_data_start[]; +extern wc_ptr_t _rtc_data_end[]; +extern void* _thread_local_start; +extern void* _thread_local_end; + +/* See https://github.com/esp8266/esp8266-wiki/wiki/Memory-Map */ +#define MEM_MAP_IO_START ((void*)(0x3FF00000)) +#define MEM_MAP_IO_END ((void*)(0x3FF0FFFF)) +#define USER_DATA_START ((void*)(0x3FFE8000)) +#define USER_DATA_END ((void*)(0x3FFE8000 + 0x14000)) +#define ETS_SYS_START ((void*)(0x3FFFC000)) +#define ETS_SYS_END ((void*)(0x3FFFC000 + 0x4000)) +#define IRAM1_START ((void*)(0x40100000)) +#define IRAM1_END ((void*)(0x40100000 + 0x8000)) +#define IRAMF1_START ((void*)(0x40108000)) +#define IRAMF1_END ((void*)(0x40108000 + 0x4000)) +#define IRAMF2_START ((void*)(0x4010C000)) +#define IRAMF2_END ((void*)(0x4010C000 + 0x4000)) + +enum sdk_memory_segment +{ + /* Ensure this list exactly matches order in sdk_memory_segment_text */ + mem_map_io = 0, + thread_local, + data, + user_data_ram, + bss, + noinit, + ets_system, + iram1, + iramf1, + iramf2, + iram, + iram_text, + iram_bss, + init, + text, + rodata, + rtc_data, + SDK_MEMORY_SEGMENT_COUNT +}; + +static void* sdk_memory_segment_start[SDK_MEMORY_SEGMENT_COUNT + 1] = {}; +static void* sdk_memory_segment_end[SDK_MEMORY_SEGMENT_COUNT + 1] = {}; +static const char* sdk_memory_segment_text[SDK_MEMORY_SEGMENT_COUNT + 1] = { + "C memory map io ", + "* thread_local ", + "C data ", + "* user data ram ", + "* bss ", + "* noinit ", + "C ets system ", + "C iram1 ", + "C iramf1 ", + "C iramf2 ", + "* iram ", + "* iram_text ", + "* iram_bss ", + "* init ", + "* text ", + "* rodata ", + "* rtc data ", + "last item", +}; + +/* Given a given memory segment [m]: assign text names, starting and ending + * addresses. See also sdk_var_whereis() that requires this initialization. */ +int sdk_log_meminfo(enum sdk_memory_segment m, void* start, void* end) +{ + const char* str; + int len = 0; + str = sdk_memory_segment_text[m]; + sdk_memory_segment_start[m] = start; + sdk_memory_segment_end[m] = end; + /* For ESP8266 See ./build/[Debug|Release]/esp8266/esp8266.project.ld */ + /* For ESP32 See ./build/VisualGDB/Debug/esp-idf/esp_system/ld/ */ + if (m == SDK_MEMORY_SEGMENT_COUNT) { + ESP_LOGI(TAG, " Linker Memory Map"); + ESP_LOGI(TAG, "-----------------------------------------------------"); + ESP_LOGI(TAG, " Start End Length"); + } + else { + len = (uint32_t)end - (uint32_t)start; + ESP_LOGI(TAG, "%s: %p ~ %p : 0x%05x (%d)", str, start, end, len, len ); + } + return ESP_OK; +} + +/* Show all known linker memory segment names, starting & ending addresses. */ +int sdk_init_meminfo(void) { + void* sample_heap_var; + int sample_stack_var = 0; + + sdk_log_meminfo(SDK_MEMORY_SEGMENT_COUNT, NULL, NULL); /* print header */ + sdk_log_meminfo(mem_map_io, MEM_MAP_IO_START, MEM_MAP_IO_END); + sdk_log_meminfo(thread_local, _thread_local_start, _thread_local_end); + sdk_log_meminfo(data, _data_start, _data_end); + sdk_log_meminfo(user_data_ram, USER_DATA_START, USER_DATA_END); + sdk_log_meminfo(bss, _bss_start, _bss_end); + sdk_log_meminfo(noinit, _noinit_start, _noinit_end); + sdk_log_meminfo(ets_system, ETS_SYS_START, ETS_SYS_END); + sdk_log_meminfo(rodata, _rodata_start, _rodata_end); + sdk_log_meminfo(iram1, IRAM1_START, IRAM1_END); + sdk_log_meminfo(iramf1, IRAMF1_START, IRAMF1_END); + sdk_log_meminfo(iramf2, IRAMF2_START, IRAMF2_END); + sdk_log_meminfo(iram, _iram_start, _iram_end); + sdk_log_meminfo(iram_text, _iram_text_start, _iram_text_end); + sdk_log_meminfo(iram_bss, _iram_bss_start, _iram_bss_end); +#if defined(CONFIG_IDF_TARGET_ESP8266) + sdk_log_meminfo(init, _init_start, _init_end); +#endif + sdk_log_meminfo(text, _text_start, _text_end); + sdk_log_meminfo(rtc_data, _rtc_data_start, _rtc_data_end); + ESP_LOGI(TAG, "-----------------------------------------------------"); + sample_heap_var = malloc(1); + if (sample_heap_var == NULL) { + ESP_LOGE(TAG, "Unable to allocate heap memory in sdk_var_whereis()."); + } + else { + sdk_var_whereis("sample_stack_var", (void*)&sample_stack_var); + sdk_var_whereis("sample_heap_var", sample_heap_var); + free(sample_heap_var); + } + return ESP_OK; +} + +/* Returns ESP_OK if found in known memory map, ESP_FAIL otherwise */ +esp_err_t sdk_var_whereis(const char* v_name, void* v) { + esp_err_t ret = ESP_FAIL; + + for (enum sdk_memory_segment m = 0 ;m < SDK_MEMORY_SEGMENT_COUNT; m++) { + if (v >= sdk_memory_segment_start[m] && + v <= sdk_memory_segment_end[m]) { + ret = ESP_OK; + ESP_LOGI(TAG, "Variable [%s] found at %p in %s", v_name, v, + sdk_memory_segment_text[m]); + if (m == user_data_ram) { + + } + } + } + + if (ret == ESP_FAIL) { + ESP_LOGW(TAG, "%s not found in known memory map: %p", v_name, v); + } + return ret; +} + +intptr_t esp_sdk_stack_pointer(void) +{ + intptr_t sp = 0; +#if defined(CONFIG_IDF_TARGET_ARCH_RISCV) + if (CONFIG_IDF_TARGET_ARCH_RISCV == 1) { + __asm volatile("mv %0, sp" : "=r" (sp)); + } +#elif defined(CONFIG_IDF_TARGET_ARCH_XTENSA) + if (CONFIG_IDF_TARGET_ARCH_XTENSA == 1) { + __asm volatile("mov %0, sp" : "=r"(sp)); + } +#endif + if (_starting_stack_pointer == 0) { + _starting_stack_pointer = sp; + } + _stack_used = _starting_stack_pointer - sp; + return sp; +} + +esp_err_t esp_sdk_mem_lib_init(void) +{ + int ret = ESP_OK; + sdk_init_meminfo(); + ESP_LOGI(TAG, "esp_sdk_mem_lib_init Ver %d", ESP_SDK_MEM_LIB_VERSION); + return ret; +} + +void* wc_debug_pvPortMalloc(size_t size, + const char* file, int line, const char* fname) { + void* ret = NULL; + ret = pvPortMalloc(size); + if (ret == NULL) { + ESP_LOGE("malloc", "%s:%d (%s)", file, line, fname); + ESP_LOGE("malloc", "Failed Allocating memory of size: %d bytes", size); + } + return ret; +} + +#endif diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c new file mode 100644 index 0000000..1ef8de4 --- /dev/null +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c @@ -0,0 +1,442 @@ +/* esp_sdk_time_lib.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +/* Reminder: user_settings.h is needed and included from settings.h + * Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +#include + +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ +#if defined(USE_WOLFSSL_ESP_SDK_TIME) +/* Espressif */ +#include "sdkconfig.h" /* programmatically generated from sdkconfig */ +#include +#include + +/* wolfSSL */ +#include + +#define ESP_SDK_TIME_LIB_VERSION 1 + +static const char* TAG = "time lib"; + +esp_err_t esp_sdk_time_lib_init(void) +{ + int ret = ESP_OK; + ESP_LOGI(TAG, "esp_sdk_time_lib_init Ver %d", ESP_SDK_TIME_LIB_VERSION); + return ret; +} + +#if defined(CONFIG_IDF_TARGET_ESP8266) + #include + +#elif defined(ESP_IDF_VERSION_MAJOR) && defined(ESP_IDF_VERSION_MINOR) + #if (ESP_IDF_VERSION_MAJOR == 5) && (ESP_IDF_VERSION_MINOR == 1) + #define HAS_ESP_NETIF_SNTP 1 + #include + #include + #elif (ESP_IDF_VERSION_MAJOR == 5) && (ESP_IDF_VERSION_MINOR > 1) + #define HAS_ESP_NETIF_SNTP 1 + #include + #include + #else + #include + #include + #endif + +#else + /* TODO Consider non ESP-IDF environments */ +#endif + +/* ESP-IDF uses a 64-bit signed integer to represent time_t + * starting from release v5.0 + * See: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#year-2036-and-2038-overflow-issues + */ + +/* see https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html */ +#ifndef TIME_ZONE + /* + * PST represents Pacific Standard Time. + * +8 specifies the offset from UTC (Coordinated Universal Time), + * indicating that Pacific Time is UTC-8 during standard time. + * PDT represents Pacific Daylight Time. + * M3.2.0 indicates that Daylight Saving Time (DST) starts on the + * second (2) Sunday (0) of March (3). + * M11.1.0 indicates that DST ends on the first (1) Sunday (0) + * of November (11) + */ + #define TIME_ZONE "PST+8PDT,M3.2.0,M11.1.0" +#endif /* not defined: TIME_ZONE, so we are setting our own */ + +#define NTP_RETRY_COUNT 10 + +/* NELEMS(x) number of elements + * To determine the number of elements in the array, we can divide the total + * size of the array by the size of the array element. + * See https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c + **/ +#define NELEMS(x) ( (int)(sizeof(x) / sizeof((x)[0])) ) + +/* See also CONFIG_LWIP_SNTP_MAX_SERVERS in sdkconfig */ +#define NTP_SERVER_LIST ( (char*[]) { \ + "pool.ntp.org", \ + "time.nist.gov", \ + "utcnist.colorado.edu" \ + } \ + ) +/* #define NTP_SERVER_COUNT using NELEMS: + * + * (int)(sizeof(NTP_SERVER_LIST) / sizeof(NTP_SERVER_LIST[0])) + */ +#define NTP_SERVER_COUNT NELEMS(NTP_SERVER_LIST) + +#ifndef CONFIG_LWIP_SNTP_MAX_SERVERS + /* We should find max value in sdkconfig, if not set it to our count:*/ + #define CONFIG_LWIP_SNTP_MAX_SERVERS NTP_SERVER_COUNT +#endif + +/* our NTP server list is global info */ +extern char* ntpServerList[NTP_SERVER_COUNT]; + +char* ntpServerList[NTP_SERVER_COUNT] = NTP_SERVER_LIST; + +/* Show the current date and time */ +int esp_show_current_datetime(void) +{ + time_t now; + char strftime_buf[64]; + struct tm timeinfo; + + time(&now); + setenv("TZ", TIME_ZONE, 1); + tzset(); + + localtime_r(&now, &timeinfo); + strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo); + ESP_LOGI(TAG, "The current date/time is: %s", strftime_buf); + return ESP_OK; +} + +/* the worst-case scenario is a hard-coded date/time */ +int set_fixed_default_time(void) +{ + /* ideally, we'd like to set time from network, + * but let's set a default time, just in case */ + struct tm timeinfo = { + .tm_year = 2024 - 1900, + .tm_mon = 1, + .tm_mday = 05, + .tm_hour = 13, + .tm_min = 01, + .tm_sec = 05 + }; + struct timeval now; + time_t interim_time; + int ret = -1; + + /* set interim static time */ + interim_time = mktime(&timeinfo); + + ESP_LOGI(TAG, "Adjusting time from fixed value"); + now = (struct timeval){ .tv_sec = interim_time }; +#if defined(CONFIG_IDF_TARGET_ESP8266) + (void)now; +#else + ret = settimeofday(&now, NULL); +#endif + ESP_LOGI(TAG, "settimeofday result = %d", ret); + return ret; +} + +/* probably_valid_time_string(s) + * + * some sanity checks on time string before calling sscanf() + * + * returns 0 == ESP_OK == Success if str is likely a valid time. + * -1 == ESP_FAIL otherwise + */ +int probably_valid_time_string(const char* str) +{ + int ret = ESP_OK; + size_t length = 0; + size_t spaces = 0; + size_t colons = 0; + + while (str[length] != '\0') { + if (str[length] == ' ') { + spaces++; + } + if (str[length] == ':') { + colons++; + } + length++; + } + + if ((length > 32) || (spaces < 4) || (spaces > 5) || (colons > 2)) { + ret = ESP_FAIL; + ESP_LOGE(TAG, "ERROR, failed time sanity check: %s", str); + } + return ret; +} + +#if defined(CONFIG_IDF_TARGET_ESP8266) +/* TODO implement time functions for ESP8266 */ +int set_time_from_string(const char* time_buffer) +{ + ESP_LOGE(TAG, "set_time_from_string not implemented for ESP8266"); + return ESP_FAIL; +} + +int set_time(void) +{ + ESP_LOGE(TAG, "set_time not implemented for ESP8266"); + return ESP_FAIL; +} + +int set_time_wait_for_ntp(void) +{ + ESP_LOGE(TAG, "set_time_wait_for_ntp not implemented for ESP8266"); + return ESP_FAIL; +} + +#else +/* ESP32 Time Helpers */ + +/* set_time_from_string(s) + * + * returns 0 = success if able to set the time from the provided string + * error for any other value, typically -1 */ +int set_time_from_string(const char* time_buffer) +{ + /* expecting github default formatting: 'Thu Aug 31 12:41:45 2023 -0700' */ + char offset[28]; /* large arrays, just in case there's still bad data */ + char day_str[28]; + char month_str[28]; + const char *format = "%3s %3s %d %d:%d:%d %d %s"; + struct tm this_timeinfo; + struct timeval now; + time_t interim_time; + int day, year, hour, minute, second; + int quote_offset = 0; + int ret = 0; + + /* perform some basic sanity checks */ + ret = probably_valid_time_string(time_buffer); + if (ret == ESP_OK) { + /* we are expecting the string to be encapsulated in single quotes */ + if (*time_buffer == 0x27) { + quote_offset = 1; + } + + ret = sscanf(time_buffer + quote_offset, + format, + day_str, month_str, + &day, &hour, &minute, &second, &year, &offset); + + if (ret == 8) { + /* we found a match for all components */ + + const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; + + for (int i = 0; i < 12; i++) { + if (strcmp(month_str, months[i]) == 0) { + this_timeinfo.tm_mon = i; + break; + } + } + + this_timeinfo.tm_mday = day; + this_timeinfo.tm_hour = hour; + this_timeinfo.tm_min = minute; + this_timeinfo.tm_sec = second; + this_timeinfo.tm_year = year - 1900; /* Years since 1900 */ + + interim_time = mktime(&this_timeinfo); + now = (struct timeval){ .tv_sec = interim_time }; + ret = settimeofday(&now, NULL); + ESP_LOGI(TAG, "Time updated to %s", time_buffer); + } + else { + ESP_LOGE(TAG, "Failed to convert \"%s\" to a tm date.", + time_buffer); + ESP_LOGI(TAG, "Trying fixed date that was hard-coded...."); + set_fixed_default_time(); + ret = ESP_FAIL; + } + } + + return ret; +} + +/* set time; returns 0 if succecssfully configured with NTP */ +int set_time(void) +{ +#ifndef NTP_SERVER_COUNT + ESP_LOGW(TAG, "Warning: no sntp server names defined. " + "Setting to empty list"); + #define NTP_SERVER_COUNT 0 + #warning "NTP not properly configured" +#endif /* not defined: NTP_SERVER_COUNT */ + +#ifdef HAS_ESP_NETIF_SNTP + #if CONFIG_LWIP_SNTP_MAX_SERVERS > 1 + esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE( + NTP_SERVER_COUNT, + ESP_SNTP_SERVER_LIST(ntpServerList[0]) + ); + #else + esp_sntp_config_t config = + ESP_NETIF_SNTP_DEFAULT_CONFIG(ntpServerList[0]); + #endif /* CONFIG_LWIP_SNTP_MAX_SERVERS > 1 */ +#endif /* HAS_ESP_NETIF_SNTP */ + + int ret = 0; + int i = 0; /* counter for time servers */ + + ESP_LOGI(TAG, "Setting the time. Startup time:"); + esp_show_current_datetime(); + +#ifdef LIBWOLFSSL_VERSION_GIT_HASH_DATE + /* initially set a default approximate time from recent git commit */ + ESP_LOGI(TAG, "Found git hash date, attempting to set system date: %s", + LIBWOLFSSL_VERSION_GIT_HASH_DATE); + set_time_from_string(LIBWOLFSSL_VERSION_GIT_HASH_DATE"\0"); + esp_show_current_datetime(); + + ret = -4; +#else + /* otherwise set a fixed time that was hard coded */ + set_fixed_default_time(); + esp_show_current_datetime(); + ret = -3; +#endif + +#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH + config.smooth_sync = true; +#endif + + if (NTP_SERVER_COUNT) { + /* next, let's setup NTP time servers + * + * see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#sntp-time-synchronization + * + * WARNING: do not set operating mode while SNTP client is running! + */ + /* TODO Consider esp_sntp_setoperatingmode(SNTP_OPMODE_POLL); */ + sntp_setoperatingmode(SNTP_OPMODE_POLL); + if (NTP_SERVER_COUNT > CONFIG_LWIP_SNTP_MAX_SERVERS) { + ESP_LOGW(TAG, "WARNING: %d NTP Servers defined, but " + "CONFIG_LWIP_SNTP_MAX_SERVERS = %d", + NTP_SERVER_COUNT,CONFIG_LWIP_SNTP_MAX_SERVERS); + } + ESP_LOGI(TAG, "sntp_setservername:"); + for (i = 0; i < CONFIG_LWIP_SNTP_MAX_SERVERS; i++) { + const char* thisServer = ntpServerList[i]; + if (strncmp(thisServer, "\x00", 1) == 0) { + /* just in case we run out of NTP servers */ + break; + } + ESP_LOGI(TAG, "%s", thisServer); + sntp_setservername(i, thisServer); + ret = ESP_OK; + } + #ifdef HAS_ESP_NETIF_SNTP + ret = esp_netif_sntp_init(&config); + #else + ESP_LOGW(TAG,"Warning: Consider upgrading ESP-IDF to take advantage " + "of updated SNTP libraries"); + #endif + if (ret == ESP_OK) { + ESP_LOGV(TAG, "Successfully called esp_netif_sntp_init"); + } + else { + ESP_LOGE(TAG, "ERROR: esp_netif_sntp_init return = %d", ret); + } + + sntp_init(); + switch (ret) { + case ESP_ERR_INVALID_STATE: + break; + default: + break; + } + ESP_LOGI(TAG, "sntp_init done."); + } + else { + ESP_LOGW(TAG, "No sntp time servers found."); + ret = -1; + } + + esp_show_current_datetime(); + ESP_LOGI(TAG, "time helper existing with result = %d", ret); + return ret; +} + +/* wait for NTP to actually set the time */ +int set_time_wait_for_ntp(void) +{ + int ret = 0; +#ifdef HAS_ESP_NETIF_SNTP + int ntp_retry = 0; + const int ntp_retry_count = NTP_RETRY_COUNT; + + ret = esp_netif_sntp_start(); + + ret = esp_netif_sntp_sync_wait(500 / portTICK_PERIOD_MS); +#else + ESP_LOGE(TAG, "HAS_ESP_NETIF_SNTP not defined"); +#endif /* HAS_ESP_NETIF_SNTP */ + esp_show_current_datetime(); + +#ifdef HAS_ESP_NETIF_SNTP + while (ret == ESP_ERR_TIMEOUT && (ntp_retry++ < ntp_retry_count)) { + ret = esp_netif_sntp_sync_wait(1000 / portTICK_PERIOD_MS); + ESP_LOGI(TAG, "Waiting for NTP to sync time... (%d/%d)", + ntp_retry, + ntp_retry_count); + esp_show_current_datetime(); + } +#endif /* HAS_ESP_NETIF_SNTP */ + +#ifdef TIME_ZONE + setenv("TZ", TIME_ZONE, 1); + tzset(); +#endif + + if (ret == ESP_OK) { + ESP_LOGI(TAG, "Successfully set time via NTP servers."); + } + else { + ESP_LOGW(TAG, "Warning: Failed to set time with NTP: " + "result = 0x%0x: %s", + ret, esp_err_to_name(ret)); + } + return ret; +} +#endif /* ESP32 or ESP8266 time helpers */ + +#endif /* USE_WOLFSSL_ESP_SDK_TIME */ +#endif /* WOLFSSL_ESPIDF*/ diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c new file mode 100644 index 0000000..06c9f81 --- /dev/null +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c @@ -0,0 +1,468 @@ +/* esp_sdk_wifi_lib.c + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +/* Reminder: user_settings.h is needed and included from settings.h + * Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +#include + +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ +#if defined(USE_WOLFSSL_ESP_SDK_WIFI) + +/* Espressif */ +#include "sdkconfig.h" /* programmatically generated from sdkconfig */ +#include +#include +#include + + +/* wolfSSL */ +#include +#include + +#define ESP_SDK_WIFI_LIB_VERSION 1 + +static const char* TAG = "wifi lib"; + +esp_err_t esp_sdk_wifi_lib_init(void) +{ + int ret = ESP_OK; + ESP_LOGI(TAG, "esp_sdk_wifi_lib_init Ver %d", ESP_SDK_WIFI_LIB_VERSION); + return ret; +} + + +/* When there's too little heap, WiFi quietly refuses to connect */ +#define WIFI_LOW_HEAP_WARNING 21132 + +#if defined(CONFIG_IDF_TARGET_ESP8266) +#elif ESP_IDF_VERSION_MAJOR >= 5 && defined(FOUND_PROTOCOL_EXAMPLES_DIR) + /* example path set in cmake file */ +#elif ESP_IDF_VERSION_MAJOR >= 4 + #include "protocol_examples_common.h" +#else + const static int CONNECTED_BIT = BIT0; + static EventGroupHandle_t wifi_event_group; +#endif + +#if defined(CONFIG_IDF_TARGET_ESP8266) + +#elif defined(ESP_IDF_VERSION_MAJOR) && defined(ESP_IDF_VERSION_MINOR) + #if ESP_IDF_VERSION_MAJOR >= 4 + /* likely using examples, see wifi_connect.h */ + #else + /* TODO - still supporting pre V4 ? */ + const static int CONNECTED_BIT = BIT0; + static EventGroupHandle_t wifi_event_group; + #endif + #if (ESP_IDF_VERSION_MAJOR == 5) + #define HAS_WPA3_FEATURES + #else + #undef HAS_WPA3_FEATURES + #endif +#else + /* TODO Consider pre IDF v5? */ +#endif + +#if defined(CONFIG_IDF_TARGET_ESP8266) +#ifndef CONFIG_ESP_MAX_STA_CONN + #define CONFIG_ESP_MAX_STA_CONN 4 +#endif +#define EXAMPLE_MAX_STA_CONN CONFIG_ESP_MAX_STA_CONN + +#define WIFI_CONNECTED_BIT BIT0 +#define WIFI_FAIL_BIT BIT1 +#ifndef CONFIG_ESP_MAXIMUM_RETRY + #define CONFIG_ESP_MAXIMUM_RETRY 5 +#endif +/* FreeRTOS event group to signal when we are connected*/ +static EventGroupHandle_t s_wifi_event_group; +static int s_retry_num = 0; + +#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY + +#if 0 +static void event_handler(void* arg, esp_event_base_t event_base, + int32_t event_id, void* event_data) +{ + if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { + esp_wifi_connect(); + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { + if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) { + esp_wifi_connect(); + s_retry_num++; + ESP_LOGI(TAG, "retry to connect to the AP"); + } else { + xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); + } + ESP_LOGI(TAG,"connect to the AP fail"); + } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { + ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; + ESP_LOGI(TAG, "got ip:%s", + ip4addr_ntoa(&event->ip_info.ip)); + s_retry_num = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + } +} +#else +static void event_handler(void* arg, esp_event_base_t event_base, + int32_t event_id, void* event_data) +{ + if (event_base == WIFI_EVENT) { + if (event_id == WIFI_EVENT_STA_START) { + esp_wifi_connect(); + ESP_LOGV(TAG, "Connect event!!"); + } + else { + if (event_id == WIFI_EVENT_STA_DISCONNECTED) { + if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) { + esp_wifi_connect(); + s_retry_num++; + ESP_LOGI(TAG, ">> Retry to connect to the AP"); + } + else { + xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); + } + ESP_LOGI(TAG, ">> Connect to the AP fail"); + } /* WIFI_EVENT_STA_DISCONNECTED */ + else if(event_id == IP_EVENT_STA_GOT_IP) { + ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; + ESP_LOGI(TAG, "got ip:%s", ip4addr_ntoa(&event->ip_info.ip)); + s_retry_num = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + } /* IP_EVENT_STA_GOT_IP */ + } /* not WIFI_EVENT_STA_START */ + } /* event_base == WIFI_EVENT */ +} /* event_handler */ + +#endif +esp_err_t esp_sdk_wifi_init_sta(void) +{ + word32 this_heap; + + s_wifi_event_group = xEventGroupCreate(); + + tcpip_adapter_init(); + + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + + ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, + &event_handler, NULL)); + ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, + &event_handler, NULL)); + + wifi_config_t wifi_config = { + .sta = { + .ssid = EXAMPLE_ESP_WIFI_SSID, + .password = EXAMPLE_ESP_WIFI_PASS + }, + }; + + /* Setting a password implies station will connect to all security modes + * including WEP/WPA. However these modes are deprecated and not advisable + * to be used. In case your Access point doesn't support WPA2, these mode + * can be enabled by commenting below line */ + if (strlen((char *)wifi_config.sta.password)) { + wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK; + } + + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); + ESP_ERROR_CHECK(esp_wifi_start() ); + + ESP_LOGI(TAG, "wifi_init_sta finished. Connecting..."); + this_heap = esp_get_free_heap_size(); + ESP_LOGI(TAG, "this heap = %d", this_heap); + if (this_heap < WIFI_LOW_HEAP_WARNING) { + ESP_LOGW(TAG, "Warning: WiFi low heap: %d", WIFI_LOW_HEAP_WARNING); + } + /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) + * or connection failed for the maximum number of re-tries (WIFI_FAIL_BIT). + * The bits are set by event_handler() + * (see above) */ + EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, + WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, + pdFALSE, + pdFALSE, + portMAX_DELAY); + + ESP_LOGI(TAG, "xEventGroupWaitBits finished."); +#if 0 + /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually + * happened. */ + if (bits & WIFI_CONNECTED_BIT) { + ESP_LOGI(TAG, "connected to ap SSID:%s", + EXAMPLE_ESP_WIFI_SSID); + } else if (bits & WIFI_FAIL_BIT) { + ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", + EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); + } else { + ESP_LOGE(TAG, "UNEXPECTED EVENT"); + } +#else + /* xEventGroupWaitBits() returns the bits before the call returned, + * hence we can test which event actually happened. */ + if (bits & WIFI_CONNECTED_BIT) { + ESP_LOGI(TAG, "Connected to AP SSID: %s", + EXAMPLE_ESP_WIFI_SSID); + } + else { + if (bits & WIFI_FAIL_BIT) { + ESP_LOGI(TAG, "Failed to connect to SSID: %s, password:%s", + EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); + } + else { + ESP_LOGE(TAG, "UNEXPECTED EVENT"); + } + } + +#endif + ESP_ERROR_CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, + &event_handler)); + ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, + &event_handler)); + vEventGroupDelete(s_wifi_event_group); + return ESP_OK; +} + +#elif ESP_IDF_VERSION_MAJOR < 4 +/* event handler for wifi events */ +static esp_err_t wifi_event_handler(void *ctx, system_event_t *event) +{ + switch (event->event_id) + { + case SYSTEM_EVENT_STA_START: + esp_wifi_connect(); + break; + case SYSTEM_EVENT_STA_GOT_IP: + #if ESP_IDF_VERSION_MAJOR >= 4 + ESP_LOGI(TAG, "got ip:" IPSTR "\n", + IP2STR(&event->event_info.got_ip.ip_info.ip)); + #else + ESP_LOGI(TAG, "got ip:%s", + ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); + #endif + /* see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/freertos_idf.html */ + xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + esp_wifi_connect(); + xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); + break; + default: + break; + } + return ESP_OK; +} +#else + +#ifdef CONFIG_ESP_MAXIMUM_RETRY + #define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY +#else + #define CONFIG_ESP_MAXIMUM_RETRY 5 +#endif + +#if CONFIG_ESP_WIFI_AUTH_OPEN +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_OPEN +#elif CONFIG_ESP_WIFI_AUTH_WEP +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WEP +#elif CONFIG_ESP_WIFI_AUTH_WPA_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_PSK +#elif CONFIG_ESP_WIFI_AUTH_WPA2_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_PSK +#elif CONFIG_ESP_WIFI_AUTH_WPA_WPA2_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_WPA2_PSK +#elif CONFIG_ESP_WIFI_AUTH_WPA3_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA3_PSK +#elif CONFIG_ESP_WIFI_AUTH_WPA2_WPA3_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_WPA3_PSK +#elif CONFIG_ESP_WIFI_AUTH_WAPI_PSK +#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WAPI_PSK +#endif + +#ifndef ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD + #define CONFIG_ESP_WIFI_AUTH_WPA2_PSK 1 + #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD CONFIG_ESP_WIFI_AUTH_WPA2_PSK +#endif + +/* FreeRTOS event group to signal when we are connected*/ +static EventGroupHandle_t s_wifi_event_group; + +/* The event group allows multiple bits for each event, + * but we only care about two events: + * - we are connected to the AP with an IP + * - we failed to connect after the maximum amount of retries */ +#define WIFI_CONNECTED_BIT BIT0 +#define WIFI_FAIL_BIT BIT1 + + +static int s_retry_num = 0; +ip_event_got_ip_t* event; + + +static void event_handler(void* arg, + esp_event_base_t event_base, + int32_t event_id, + void* event_data) +{ + if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { + esp_wifi_connect(); + } + else if (event_base == WIFI_EVENT && + event_id == WIFI_EVENT_STA_DISCONNECTED) { + if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) { + esp_wifi_connect(); + s_retry_num++; + ESP_LOGI(TAG, "retry to connect to the AP"); + } + else { + xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); + } + ESP_LOGI(TAG, "connect to the AP fail"); + } + else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { + event = (ip_event_got_ip_t*) event_data; + /* wifi_show_ip(); */ + s_retry_num = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + } +} + +esp_err_t wc_wifi_init_sta(void) +{ + esp_err_t ret = ESP_OK; + + s_wifi_event_group = xEventGroupCreate(); + + ESP_ERROR_CHECK(esp_netif_init()); + + ESP_ERROR_CHECK(esp_event_loop_create_default()); + esp_netif_create_default_wifi_sta(); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + + esp_event_handler_instance_t instance_any_id; + esp_event_handler_instance_t instance_got_ip; + ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, + ESP_EVENT_ANY_ID, + &event_handler, + NULL, + &instance_any_id)); + ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, + IP_EVENT_STA_GOT_IP, + &event_handler, + NULL, + &instance_got_ip)); + + wifi_config_t wifi_config = { + .sta = { + .ssid = EXAMPLE_ESP_WIFI_SSID, + .password = EXAMPLE_ESP_WIFI_PASS, + /* Authmode threshold resets to WPA2 as default if password matches + * WPA2 standards (password len => 8). If you want to connect the + * device to deprecated WEP/WPA networks, Please set the threshold + * value WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with + * length and format matching to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK + * standards. */ + .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD, + #ifdef HAS_WPA3_FEATURES + .sae_pwe_h2e = WPA3_SAE_PWE_BOTH, + #endif + }, + }; + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); + +#ifdef CONFIG_EXAMPLE_WIFI_SSID + if (XSTRCMP(CONFIG_EXAMPLE_WIFI_SSID, "myssid") == 0) { + ESP_LOGW(TAG, "WARNING: CONFIG_EXAMPLE_WIFI_SSID is \"myssid\"."); + ESP_LOGW(TAG, " Do you have a WiFi AP called \"myssid\", "); + ESP_LOGW(TAG, " or did you forget the ESP-IDF configuration?"); + } +#else + ESP_LOGW(TAG, "WARNING: CONFIG_EXAMPLE_WIFI_SSID not defined."); +#endif + + ESP_ERROR_CHECK(esp_wifi_start() ); + + ESP_LOGI(TAG, "wifi_init_sta finished."); + + /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) + * or connection failed for the maximum number of re-tries (WIFI_FAIL_BIT). + * The bits are set by event_handler() (see above) */ + EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, + WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, + pdFALSE, + pdFALSE, + portMAX_DELAY); + + /* xEventGroupWaitBits() returns the bits before the call returned, + * hence we can test which event actually happened. */ +#if defined(SHOW_SSID_AND_PASSWORD) + ESP_LOGW(TAG, "Undefine SHOW_SSID_AND_PASSWORD to not show SSID/password"); + if (bits & WIFI_CONNECTED_BIT) { + ESP_LOGI(TAG, "connected to ap SSID:%s password:%s", + EXAMPLE_ESP_WIFI_SSID, + EXAMPLE_ESP_WIFI_PASS); + } + else if (bits & WIFI_FAIL_BIT) { + ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", + EXAMPLE_ESP_WIFI_SSID, + EXAMPLE_ESP_WIFI_PASS); + } + else { + ESP_LOGE(TAG, "UNEXPECTED EVENT"); + } +#else + if (bits & WIFI_CONNECTED_BIT) { + ESP_LOGI(TAG, "Connected to AP"); + } + else if (bits & WIFI_FAIL_BIT) { + ESP_LOGI(TAG, "Failed to connect to AP"); + ret = -1; + } + else { + ESP_LOGE(TAG, "AP UNEXPECTED EVENT"); + ret = -2; + } +#endif + return ret; +} + +esp_err_t wc_wifi_show_ip(void) +{ + /* TODO Causes panic: ESP_LOGI(TAG, "got ip:" IPSTR, + * IP2STR(&event->ip_info.ip)); */ + return ESP_OK; +} + +#endif + + +#endif /* USE_WOLFSSL_ESP_SDK_WIFI */ +#endif /* WOLFSSL_ESPIDF */ diff --git a/src/wolfcrypt/src/port/atmel/atmel.c b/src/wolfcrypt/src/port/atmel/atmel.c index 9a404d8..b3c6b79 100644 --- a/src/wolfcrypt/src/port/atmel/atmel.c +++ b/src/wolfcrypt/src/port/atmel/atmel.c @@ -136,7 +136,7 @@ int atmel_get_random_number(uint32_t count, uint8_t* rand_out) int atmel_get_random_block(unsigned char* output, unsigned int sz) { - return atmel_get_random_number((uint32_t)sz, (uint8_t*)output); + return atmel_get_random_number((uint32_t)sz, (uint8_t*)output); } #if defined(WOLFSSL_ATMEL) && defined(WOLFSSL_ATMEL_TIME) @@ -148,12 +148,12 @@ long atmel_get_curr_time_and_date(long* tm) { long rt = 0; - /* Get current time */ + /* Get current time */ struct rtc_calendar_time rtcTime; const int monthDay[] = {0,31,59,90,120,151,181,212,243,273,304,334}; int month, year, yearLeap; - rtc_calendar_get_time(_rtc_instance[0], &rtcTime); + rtc_calendar_get_time(_rtc_instance[0], &rtcTime); /* Convert rtc_calendar_time to seconds since UTC */ month = rtcTime.month % 12; @@ -359,7 +359,7 @@ int atmel_get_enc_key_default(byte* enckey, word16 keysize) static int atmel_init_enc_key(void) { int ret; - uint8_t read_key[ATECC_KEY_SIZE]; + uint8_t read_key[ATECC_KEY_SIZE]; uint8_t writeBlock = 0; uint8_t writeOffset = 0; int slotId; @@ -388,7 +388,7 @@ static int atmel_init_enc_key(void) ForceZero(read_key, sizeof(read_key)); ret = atmel_ecc_translate_err(ret); - return ret; + return ret; } #endif @@ -497,7 +497,7 @@ int atmel_init(void) extern ATCAIfaceCfg atecc608_0_init_data; #endif #endif - + if (!mAtcaInitDone) { ATCA_STATUS status; int i; @@ -940,7 +940,7 @@ int atcatls_verify_signature_cb(WOLFSSL* ssl, const byte* sig, return ret; } -static int atcatls_set_certificates(WOLFSSL_CTX *ctx) +static int atcatls_set_certificates(WOLFSSL_CTX *ctx) { #ifndef ATCATLS_SIGNER_CERT_MAX_SIZE #define ATCATLS_SIGNER_CERT_MAX_SIZE 0x250 @@ -966,7 +966,7 @@ static int atcatls_set_certificates(WOLFSSL_CTX *ctx) uint8_t signerPubKeyBuffer[ATCATLS_PUBKEY_BUFF_MAX_SIZE]; #endif -#ifdef WOLFSSL_ATECC_TNGTLS +#ifdef WOLFSSL_ATECC_TNGTLS ret = tng_atcacert_max_signer_cert_size(&signerCertSize); if (ret != ATCACERT_E_SUCCESS) { #ifdef WOLFSSL_ATECC_DEBUG diff --git a/src/wolfcrypt/src/pwdbased.c b/src/wolfcrypt/src/pwdbased.c index 8be0c64..1aef716 100644 --- a/src/wolfcrypt/src/pwdbased.c +++ b/src/wolfcrypt/src/pwdbased.c @@ -28,6 +28,16 @@ #ifndef NO_PWDBASED +#if FIPS_VERSION3_GE(6,0,0) + /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ + #define FIPS_NO_WRAPPERS + + #ifdef USE_WINDOWS_API + #pragma code_seg(".fipsA$h") + #pragma const_seg(".fipsB$h") + #endif +#endif + #include #include #include @@ -41,6 +51,17 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + #ifdef DEBUG_WOLFSSL + #include + #endif + const unsigned int wolfCrypt_FIPS_pbkdf_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000010 }; + int wolfCrypt_FIPS_PBKDF_sanity(void) + { + return 0; + } +#endif #ifdef HAVE_PBKDF1 @@ -165,6 +186,7 @@ int wc_PBKDF1_ex(byte* key, int keyLen, byte* iv, int ivLen, int wc_PBKDF1(byte* output, const byte* passwd, int pLen, const byte* salt, int sLen, int iterations, int kLen, int hashType) { + return wc_PBKDF1_ex(output, kLen, NULL, 0, passwd, pLen, salt, sLen, iterations, hashType, NULL); } @@ -191,6 +213,24 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, return BAD_FUNC_ARG; } +#if FIPS_VERSION3_GE(6,0,0) + /* Per SP800-132 section 5 "The kLen value shall be at least 112 bits in + * length", ensure the returned bits for the derived master key are at a + * minimum 14-bytes or 112-bits after stretching and strengthening + * (iterations) */ + if (kLen < HMAC_FIPS_MIN_KEY/8) + return BAD_LENGTH_E; +#endif + +#if FIPS_VERSION3_GE(6,0,0) && defined(DEBUG_WOLFSSL) + /* SP800-132 section 5.2 recommends an iteration count of 1000 but this is + * not strictly enforceable and is listed in Appendix B Table 1 as a + * non-testable requirement. wolfCrypt will log it when appropriate but + * take no action */ + if (iterations < 1000) { + WOLFSSL_MSG("WARNING: Iteration < 1,000, see SP800-132 section 5.2"); + } +#endif if (iterations <= 0) iterations = 1; @@ -214,7 +254,17 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, if (ret == 0) { word32 i = 1; /* use int hashType here, since HMAC FIPS uses the old unique value */ + #if FIPS_VERSION3_GE(6,0,0) + { + /* Allow passwords that are less than 14-bytes for compatibility + * / interoperability, only since module v6.0.0 */ + int allowShortPasswd = 1; + ret = wc_HmacSetKey_ex(hmac, hashType, passwd, (word32)pLen, + allowShortPasswd); + } + #else ret = wc_HmacSetKey(hmac, hashType, passwd, (word32)pLen); + #endif while (ret == 0 && kLen) { int currentLen; diff --git a/src/wolfcrypt/src/random.c b/src/wolfcrypt/src/random.c index d44f2e2..89c7411 100644 --- a/src/wolfcrypt/src/random.c +++ b/src/wolfcrypt/src/random.c @@ -50,8 +50,8 @@ This library contains implementation for the random number generator. #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$c") - #pragma const_seg(".fipsB$c") + #pragma code_seg(".fipsA$i") + #pragma const_seg(".fipsB$i") #endif #endif @@ -128,6 +128,8 @@ This library contains implementation for the random number generator. #elif defined(WOLFSSL_TELIT_M2MB) #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG) #elif defined(WOLFSSL_IMXRT1170_CAAM) +#elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) + #include "cyhal_trng.h" /* Infineon/Cypress HAL RNG implementation */ #elif defined(WOLFSSL_GETRANDOM) #include #include @@ -151,6 +153,15 @@ This library contains implementation for the random number generator. #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_drbg_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000011 }; + int wolfCrypt_FIPS_DRBG_sanity(void) + { + return 0; + } +#endif + #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \ defined(HAVE_AMD_RDSEED) static word32 intel_flags = 0; @@ -611,6 +622,9 @@ static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz) } if (drbg->reseedCtr == RESEED_INTERVAL) { +#if FIPS_VERSION3_GE(6,0,0) + printf("Reseed triggered\n"); +#endif return DRBG_NEED_RESEED; } else { @@ -1456,7 +1470,7 @@ int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len) Entropy_StopThread(); #endif - if (ret != BAD_MUTEX_E) { + if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) { /* Unlock mutex now we are done. */ wc_UnLockMutex(&entropy_mutex); } @@ -1472,7 +1486,7 @@ int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len) * @return ENTROPY_RT_E or ENTROPY_APT_E on failure. * @return BAD_MUTEX_E when unable to lock mutex. */ -int wc_Entropy_OnDemandTest() +int wc_Entropy_OnDemandTest(void) { int ret = 0; @@ -1488,7 +1502,7 @@ int wc_Entropy_OnDemandTest() ret = Entropy_HealthTest_Startup(); } - if (ret != BAD_MUTEX_E) { + if (ret != WC_NO_ERR_TRACE(BAD_MUTEX_E)) { /* Unlock mutex now we are done. */ wc_UnLockMutex(&entropy_mutex); } @@ -1500,7 +1514,7 @@ int wc_Entropy_OnDemandTest() * @return 0 on success. * @return Negative on failure. */ -int Entropy_Init() +int Entropy_Init(void) { int ret = 0; @@ -1537,7 +1551,7 @@ int Entropy_Init() /* Finalize the data associated with the MemUse Entropy source. */ -void Entropy_Final() +void Entropy_Final(void) { /* Only finalize when initialized. */ if (entropy_memuse_initialized) { @@ -1854,7 +1868,7 @@ int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) #endif { ret = wc_CryptoCb_RandomBlock(rng, output, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -2662,7 +2676,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif { ret = wc_CryptoCb_RandomSeed(os, output, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -3462,7 +3476,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } /* driver could be waiting for entropy */ - if (ret != RAN_BLOCK_E && ret != 0) { + if (ret != WC_NO_ERR_TRACE(RAN_BLOCK_E) && ret != 0) { return ret; } #ifndef WOLFSSL_IMXRT1170_CAAM @@ -3717,25 +3731,33 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #elif defined(WOLFSSL_ZEPHYR) - #include + #include #if KERNEL_VERSION_NUMBER >= 0x30500 #include #else - #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #else + #include + #endif #endif #ifndef _POSIX_C_SOURCE - #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #else + #include + #endif #else #include #endif - int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) - { - sys_rand_get(output, sz); - return 0; - } + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + sys_rand_get(output, sz); + return 0; + } #elif defined(WOLFSSL_TELIT_M2MB) @@ -3832,6 +3854,40 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return ret; } +#elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) + + /* Infineon/Cypress HAL RNG implementation */ + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + cyhal_trng_t obj; + cy_rslt_t result; + uint32_t val; + word32 i = 0; + + (void)os; + + result = cyhal_trng_init(&obj); + if (result == CY_RSLT_SUCCESS) { + while (i < sz) { + /* If not aligned or there is odd/remainder add single byte */ + if( (i + sizeof(word32)) > sz || + ((wc_ptr_t)&output[i] % sizeof(word32)) != 0 + ) { + val = cyhal_trng_generate(&obj); + output[i++] = (byte)val; + } + else { + /* Use native 32 instruction */ + val = cyhal_trng_generate(&obj); + *((uint32_t*)&output[i]) = val; + i += sizeof(word32); + } + } + cyhal_trng_free(&obj); + } + return 0; + } + #elif defined(WOLFSSL_SAFERTOS) || defined(WOLFSSL_LEANPSK) || \ defined(WOLFSSL_IAR_ARM) || defined(WOLFSSL_MDK_ARM) || \ defined(WOLFSSL_uITRON4) || defined(WOLFSSL_uTKERNEL2) || \ @@ -3853,14 +3909,14 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { - int ret = WC_HW_E; + int ret = WC_NO_ERR_TRACE(WC_HW_E); #ifndef WOLF_CRYPTO_CB_FIND if (os->devId != INVALID_DEVID) #endif { ret = wc_CryptoCb_RandomSeed(os, output, sz); - if (ret == CRYPTOCB_UNAVAILABLE) { + if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { ret = WC_HW_E; } } @@ -3898,7 +3954,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif { ret = wc_CryptoCb_RandomSeed(os, output, sz); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code */ diff --git a/src/wolfcrypt/src/rsa.c b/src/wolfcrypt/src/rsa.c index 4299fd2..587e47c 100644 --- a/src/wolfcrypt/src/rsa.c +++ b/src/wolfcrypt/src/rsa.c @@ -35,15 +35,13 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. #ifndef NO_RSA -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) - +#if FIPS_VERSION3_GE(2,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$e") - #pragma const_seg(".fipsB$e") + #pragma code_seg(".fipsA$j") + #pragma const_seg(".fipsB$j") #endif #endif @@ -108,6 +106,14 @@ RSA Key Size Configuration: #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_rsa_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000012 }; + int wolfCrypt_FIPS_RSA_sanity(void) + { + return 0; + } +#endif enum { RSA_STATE_NONE = 0, @@ -121,22 +127,25 @@ enum { RSA_STATE_DECRYPT_RES }; - static void wc_RsaCleanup(RsaKey* key) { -#if !defined(WOLFSSL_RSA_VERIFY_INLINE) && !defined(WOLFSSL_NO_MALLOC) - if (key && key->data) { +#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \ + (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE))) + if (key != NULL) { + #ifndef WOLFSSL_RSA_PUBLIC_ONLY + /* if private operation zero temp buffer */ + if ((key->data != NULL && key->dataLen > 0) && + (key->type == RSA_PRIVATE_DECRYPT || + key->type == RSA_PRIVATE_ENCRYPT)) { + ForceZero(key->data, key->dataLen); + } + #endif /* make sure any allocated memory is free'd */ if (key->dataIsAlloc) { - #ifndef WOLFSSL_RSA_PUBLIC_ONLY - if (key->type == RSA_PRIVATE_DECRYPT || - key->type == RSA_PRIVATE_ENCRYPT) { - ForceZero(key->data, key->dataLen); - } - #endif XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT); key->dataIsAlloc = 0; } + key->data = NULL; key->dataLen = 0; } @@ -148,29 +157,21 @@ static void wc_RsaCleanup(RsaKey* key) int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) { int ret = 0; -#if defined(HAVE_PKCS11) - int isPkcs11 = 0; -#endif if (key == NULL) { return BAD_FUNC_ARG; } -#if defined(HAVE_PKCS11) - if (key->isPkcs11) { - isPkcs11 = 1; - } -#endif - XMEMSET(key, 0, sizeof(RsaKey)); key->type = RSA_TYPE_UNKNOWN; key->state = RSA_STATE_NONE; key->heap = heap; -#if !defined(WOLFSSL_RSA_VERIFY_INLINE) && !defined(WOLFSSL_NO_MALLOC) +#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \ + (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE))) key->dataIsAlloc = 0; - key->data = NULL; #endif + key->data = NULL; key->dataLen = 0; #ifdef WC_RSA_BLINDING key->rng = NULL; @@ -188,19 +189,18 @@ int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) #endif #ifdef WC_ASYNC_ENABLE_RSA - #if defined(HAVE_PKCS11) - if (!isPkcs11) + #ifdef WOLF_CRYPTO_CB + /* prefer crypto callback */ + if (key->devId != INVALID_DEVID) #endif - { - /* handle as async */ - ret = wolfAsync_DevCtxInit(&key->asyncDev, - WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId); - if (ret != 0) - return ret; - } + { + /* handle as async */ + ret = wolfAsync_DevCtxInit(&key->asyncDev, + WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId); + if (ret != 0) + return ret; + } #endif /* WC_ASYNC_ENABLE_RSA */ -#elif defined(HAVE_PKCS11) - (void)isPkcs11; #endif /* WOLFSSL_ASYNC_CRYPT */ #ifndef WOLFSSL_RSA_PUBLIC_ONLY @@ -273,14 +273,6 @@ int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, ret = BAD_FUNC_ARG; if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN)) ret = BUFFER_E; - -#if defined(HAVE_PKCS11) - if (ret == 0) { - XMEMSET(key, 0, sizeof(RsaKey)); - key->isPkcs11 = 1; - } -#endif - if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { @@ -310,14 +302,6 @@ int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId) if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN) ret = BUFFER_E; } - -#if defined(HAVE_PKCS11) - if (ret == 0) { - XMEMSET(key, 0, sizeof(RsaKey)); - key->isPkcs11 = 1; - } -#endif - if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0) { @@ -648,13 +632,13 @@ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) #ifdef WOLFSSL_ASYNC_CRYPT /* Do blocking async calls here, caller does not support WC_PENDING_E */ do { - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret >= 0) #endif ret = wc_RsaSSL_Sign((const byte*)msg, msgLen, sig, sigLen, key, rng); #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif if (ret > 0) { @@ -662,13 +646,13 @@ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) #ifdef WOLFSSL_ASYNC_CRYPT /* Do blocking async calls here, caller does not support WC_PENDING_E */ do { - if (ret == WC_PENDING_E) + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret >= 0) #endif ret = wc_RsaSSL_VerifyInline(sig, sigLen, &plain, key); #ifdef WOLFSSL_ASYNC_CRYPT - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif } @@ -689,13 +673,17 @@ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) int wc_CheckRsaKey(RsaKey* key) { - DECL_MP_INT_SIZE_DYN(tmp, mp_bitsused(&key->n), RSA_MAX_SIZE); #ifdef WOLFSSL_SMALL_STACK WC_RNG *rng = NULL; #else WC_RNG rng[1]; #endif int ret = 0; + DECL_MP_INT_SIZE_DYN(tmp, (key)? mp_bitsused(&key->n) : 0, RSA_MAX_SIZE); + + if (key == NULL) { + return BAD_FUNC_ARG; + } #ifdef WOLFSSL_CAAM /* can not perform these checks on an encrypted key */ @@ -727,11 +715,6 @@ int wc_CheckRsaKey(RsaKey* key) ret = MP_INIT_E; } - if (ret == 0) { - if (key == NULL) - ret = BAD_FUNC_ARG; - } - if (ret == 0) ret = _ifc_pairwise_consistency_test(key, rng); @@ -1805,7 +1788,7 @@ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, byte padValue) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); word16 i; if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) { @@ -2794,7 +2777,7 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, #ifdef WOLFSSL_HAVE_SP_RSA ret = RsaFunction_SP(in, inLen, out, outLen, type, key, rng); - if (ret != WC_KEY_SIZE_E) + if (ret != WC_NO_ERR_TRACE(WC_KEY_SIZE_E)) return ret; #endif /* WOLFSSL_HAVE_SP_RSA */ @@ -2948,7 +2931,7 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, key->dataLen = *outSz; ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng); - if (ret >= 0 || ret == WC_PENDING_E) { + if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { key->state = (type == RSA_PRIVATE_ENCRYPT || type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES: RSA_STATE_DECRYPT_RES; @@ -3146,12 +3129,12 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, { ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable and try using software */ #endif #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (ret == CRYPTOCB_UNAVAILABLE) { + if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { return NO_VALID_DEVID; } return ret; @@ -3203,7 +3186,7 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, && ret != FP_WOULDBLOCK #endif ) { - if (ret == MP_EXPTMOD_E) { + if (ret == WC_NO_ERR_TRACE(MP_EXPTMOD_E)) { /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */ WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem"); } @@ -3339,8 +3322,8 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) { /* SCE supports 1024 and 2048 bits */ ret = wc_CryptoCb_Rsa(in, inLen, out, - outLen, rsa_type, key, rng); - if (ret != CRYPTOCB_UNAVAILABLE) + &outLen, rsa_type, key, rng); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ @@ -3365,7 +3348,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key, rng); - if (ret >= 0 || ret == WC_PENDING_E) { + if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { key->state = RSA_STATE_ENCRYPT_RES; } if (ret < 0) { @@ -3425,7 +3408,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, byte* label, word32 labelSz, int saltLen, WC_RNG* rng) { - int ret = RSA_WRONG_TYPE_E; + int ret = WC_NO_ERR_TRACE(RSA_WRONG_TYPE_E); byte* pad = NULL; if (in == NULL || inLen == 0 || out == NULL || key == NULL) { @@ -3496,8 +3479,8 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Rsa(in, inLen, out, - outLen, rsa_type, key, rng); - if (ret != CRYPTOCB_UNAVAILABLE) + &outLen, rsa_type, key, rng); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ @@ -3525,6 +3508,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, break; } XMEMCPY(key->data, in, inLen); + key->dataLen = inLen; } else { key->dataIsAlloc = 0; @@ -3546,7 +3530,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, rng, pad_type != WC_RSA_OAEP_PAD); #endif - if (ret >= 0 || ret == WC_PENDING_E) { + if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { key->state = RSA_STATE_DECRYPT_UNPAD; } if (ret < 0) { @@ -3558,13 +3542,13 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, case RSA_STATE_DECRYPT_UNPAD: #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ !defined(WOLFSSL_NO_MALLOC) - ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type, - hash, mgf, label, labelSz, saltLen, - mp_count_bits(&key->n), key->heap); + ret = wc_RsaUnPad_ex(key->data, + key->dataLen, &pad, pad_value, pad_type, hash, mgf, + label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); #else - ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash, - mgf, label, labelSz, saltLen, - mp_count_bits(&key->n), key->heap); + ret = wc_RsaUnPad_ex(out, + key->dataLen, &pad, pad_value, pad_type, hash, mgf, label, + labelSz, saltLen, mp_count_bits(&key->n), key->heap); #endif if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) { ret = RSA_BUFFER_E; @@ -4033,7 +4017,10 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, /* Sig = Salt | Exp Hash */ if (ret == 0) { - if (sigSz != inSz + (word32)saltLen) { + word32 totalSz; + if ((WC_SAFE_SUM_WORD32(inSz, (word32)saltLen, totalSz) == 0) || + (sigSz != totalSz)) + { ret = PSS_SALTLEN_E; } } @@ -4259,7 +4246,7 @@ int wc_RsaEncryptSize(const RsaKey* key) #ifdef WOLF_CRYPTO_CB if (ret == 0 && key->devId != INVALID_DEVID) { - if (wc_CryptoCb_RsaGetSize(key, &ret) == CRYPTOCB_UNAVAILABLE) { + if (wc_CryptoCb_RsaGetSize(key, &ret) == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { ret = 2048/8; /* hardware handles, use 2048-bit as default */ } } @@ -4326,7 +4313,7 @@ int wc_RsaExportKey(RsaKey* key, byte* d, word32* dSz, byte* p, word32* pSz, byte* q, word32* qSz) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz) ret = 0; @@ -4531,7 +4518,8 @@ static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen, if (q != NULL) { int valid = 0; - /* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */ + /* 5.4 (186-4) 5.5 (186-5) - + * check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */ ret = wc_CompareDiffPQ(p, q, nlen, &valid); if ((ret != MP_OKAY) || (!valid)) goto notOkay; prime = q; @@ -4539,14 +4527,15 @@ static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen, else prime = p; - /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1)) + /* 4.4,5.5 (186-4) 4.4,5.4 (186-5) - + * Check that prime >= (2^(1/2))(2^((nlen/2)-1)) * This is a comparison against lowerBound */ ret = mp_read_unsigned_bin(tmp1, lower_bound, (word32)nlen/16); if (ret != MP_OKAY) goto notOkay; ret = mp_cmp(prime, tmp1); if (ret == MP_LT) goto exit; - /* 4.5,5.6 - Check that GCD(p-1, e) == 1 */ + /* 4.5,5.6 (186-4 & 186-5) - Check that GCD(p-1, e) == 1 */ ret = mp_sub_d(prime, 1, tmp1); /* tmp1 = prime-1 */ if (ret != MP_OKAY) goto notOkay; #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -4721,7 +4710,12 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #endif /* WOLFSSL_SMALL_STACK */ int i, failCount, isPrime = 0; word32 primeSz; +#ifndef WOLFSSL_NO_MALLOC byte* buf = NULL; +#else + /* RSA_MAX_SIZE is the size of n in bits. */ + byte buf[RSA_MAX_SIZE/16]; +#endif #endif /* !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 */ int err; @@ -4780,12 +4774,12 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (err != CRYPTOCB_UNAVAILABLE) + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) goto out; /* fall-through when unavailable */ #endif #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (err == CRYPTOCB_UNAVAILABLE) + if (err == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) err = NO_VALID_DEVID; goto out; } @@ -4827,12 +4821,14 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) primeSz = (word32)size / 16; /* size is the size of n in bits. primeSz is in bytes. */ +#ifndef WOLFSSL_NO_MALLOC /* allocate buffer to work with */ if (err == MP_OKAY) { buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA); if (buf == NULL) err = MEMORY_E; } +#endif SAVE_VECTOR_REGISTERS(err = _svr_ret;); @@ -4935,10 +4931,14 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) if (err == MP_OKAY && !isPrime) err = PRIME_GEN_E; +#ifndef WOLFSSL_NO_MALLOC if (buf) { ForceZero(buf, primeSz); XFREE(buf, key->heap, DYNAMIC_TYPE_RSA); } +#else + ForceZero(buf, primeSz); +#endif if (err == MP_OKAY && mp_cmp(p, q) < 0) { err = mp_copy(p, tmp1); @@ -5156,4 +5156,115 @@ int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz) #endif /* WC_RSA_NONBLOCK_TIME */ #endif /* WC_RSA_NONBLOCK */ +#ifndef WOLFSSL_RSA_PUBLIC_ONLY + +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) +/* + * Calculate y = d mod(x-1) + */ +static int CalcDX(mp_int* y, mp_int* x, mp_int* d) +{ + int err; +#ifndef WOLFSSL_SMALL_STACK + mp_int m[1]; +#else + mp_int* m = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_WOLF_BIGINT); + if (m == NULL) + return MEMORY_E; +#endif + + err = mp_init(m); + if (err == MP_OKAY) { + err = mp_sub_d(x, 1, m); + if (err == MP_OKAY) + err = mp_mod(d, m, y); + mp_forcezero(m); + } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(m, NULL, DYNAMIC_TYPE_WOLF_BIGINT); +#endif + + return err; +} +#endif + +int wc_RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz, + const byte* e, word32 eSz, const byte* d, word32 dSz, + const byte* u, word32 uSz, const byte* p, word32 pSz, + const byte* q, word32 qSz, const byte* dP, word32 dPSz, + const byte* dQ, word32 dQSz, RsaKey* key) +{ + int err = MP_OKAY; + + if (n == NULL || nSz == 0 || e == NULL || eSz == 0 + || d == NULL || dSz == 0 || p == NULL || pSz == 0 + || q == NULL || qSz == 0 || key == NULL) { + err = BAD_FUNC_ARG; + } + +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) + if (err == MP_OKAY) { + if ((u == NULL || uSz == 0) + || (dP != NULL && dPSz == 0) + || (dQ != NULL && dQSz == 0)) { + err = BAD_FUNC_ARG; + } + } +#else + (void)u; + (void)uSz; + (void)dP; + (void)dPSz; + (void)dQ; + (void)dQSz; +#endif + + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->n, n, nSz); + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->e, e, eSz); + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->d, d, dSz); + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->p, p, pSz); + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->q, q, qSz); +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) + if (err == MP_OKAY) + err = mp_read_unsigned_bin(&key->u, u, uSz); + if (err == MP_OKAY) { + if (dP != NULL) + err = mp_read_unsigned_bin(&key->dP, dP, dPSz); + else + err = CalcDX(&key->dP, &key->p, &key->d); + } + if (err == MP_OKAY) { + if (dQ != NULL) + err = mp_read_unsigned_bin(&key->dQ, dQ, dQSz); + else + err = CalcDX(&key->dQ, &key->q, &key->d); + } +#endif + + if (err == MP_OKAY) { + key->type = RSA_PRIVATE; + } + else { + mp_clear(&key->n); + mp_clear(&key->e); + mp_clear(&key->d); + mp_clear(&key->p); + mp_clear(&key->q); +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) + mp_clear(&key->u); + mp_clear(&key->dP); + mp_clear(&key->dQ); +#endif + } + + return err; +} +#endif /* WOLFSSL_RSA_PUBLIC_ONLY */ + #endif /* NO_RSA */ diff --git a/src/wolfcrypt/src/sakke.c b/src/wolfcrypt/src/sakke.c index eb0f932..c87963a 100644 --- a/src/wolfcrypt/src/sakke.c +++ b/src/wolfcrypt/src/sakke.c @@ -327,14 +327,18 @@ static int sakke_load_base_point(SakkeKey* key) static int sakke_mulmod_base(SakkeKey* key, const mp_int* n, ecc_point* res, int map) { - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SP_1024 if ((key->ecc.idx != ECC_CUSTOM_IDX) && (ecc_sets[key->ecc.idx].id == ECC_SAKKE_1)) { err = sp_ecc_mulmod_base_1024(n, res, map, key->heap); } + else #endif + { + err = NOT_COMPILED_IN; + } return err; } @@ -353,14 +357,18 @@ static int sakke_mulmod_base(SakkeKey* key, const mp_int* n, ecc_point* res, static int sakke_mulmod_base_add(SakkeKey* key, const mp_int* n, const ecc_point* a, ecc_point* res, int map) { - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SP_1024 if ((key->ecc.idx != ECC_CUSTOM_IDX) && (ecc_sets[key->ecc.idx].id == ECC_SAKKE_1)) { err = sp_ecc_mulmod_base_add_1024(n, a, 0, res, map, key->heap); } + else #endif + { + err = NOT_COMPILED_IN; + } return err; } @@ -440,7 +448,7 @@ static int sakke_mulmod_base_add(SakkeKey* key, const mp_int* n, ecc_point* a, static int sakke_mulmod_point(SakkeKey* key, const mp_int* n, const ecc_point* p, byte* table, ecc_point* res, int map) { - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SP_1024 if ((key->ecc.idx != ECC_CUSTOM_IDX) && @@ -452,7 +460,11 @@ static int sakke_mulmod_point(SakkeKey* key, const mp_int* n, err = sp_ecc_mulmod_table_1024(n, p, table, res, map, key->heap); } } + else #endif + { + err = NOT_COMPILED_IN; + } return err; } @@ -1351,7 +1363,7 @@ int wc_GenerateSakkeRskTable(const SakkeKey* key, const ecc_point* rsk, static int sakke_pairing(const SakkeKey* key, const ecc_point* p, const ecc_point* q, mp_int* r, const byte* table, word32 len) { - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SP_1024 if ((key->ecc.idx != ECC_CUSTOM_IDX) && @@ -1363,6 +1375,9 @@ static int sakke_pairing(const SakkeKey* key, const ecc_point* p, err = sp_Pairing_precomp_1024(p, q, r, table, len); } } + else { + err = NOT_COMPILED_IN; + } #else (void)key; (void)p; @@ -1370,6 +1385,7 @@ static int sakke_pairing(const SakkeKey* key, const ecc_point* p, (void)r; (void)table; (void)len; + err = NOT_COMPILED_IN; #endif return err; @@ -2523,14 +2539,18 @@ int wc_GetSakkeAuthSize(SakkeKey* key, word16* authSz) static int sakke_modexp(const SakkeKey* key, const mp_int* b, mp_int* e, mp_int* r) { - int err = NOT_COMPILED_IN; + int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SP_1024 if ((key->ecc.idx != ECC_CUSTOM_IDX) && (ecc_sets[key->ecc.idx].id == ECC_SAKKE_1)) { err = sp_ModExp_Fp_star_1024(b, e, r); } + else #endif + { + err = NOT_COMPILED_IN; + } return err; } @@ -6551,7 +6571,7 @@ int wc_SetSakkePointITable(SakkeKey* key, byte* table, word32 len) #ifdef WOLFSSL_HAVE_SP_ECC if (err == 0) { err = sp_ecc_gen_table_1024(key->i.i, NULL, &sz, NULL); - if (err == LENGTH_ONLY_E) { + if (err == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { err = 0; } } diff --git a/src/wolfcrypt/src/sha.c b/src/wolfcrypt/src/sha.c index 6999079..1892de4 100644 --- a/src/wolfcrypt/src/sha.c +++ b/src/wolfcrypt/src/sha.c @@ -36,13 +36,13 @@ #if !defined(NO_SHA) -#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$j") - #pragma const_seg(".fipsB$j") + #pragma code_seg(".fipsA$k") + #pragma const_seg(".fipsB$k") #endif #endif @@ -118,6 +118,14 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_sha_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000013 }; + int wolfCrypt_FIPS_SHA_sanity(void) + { + return 0; + } +#endif /* Hardware Acceleration */ #if defined(WOLFSSL_PIC32MZ_HASH) @@ -598,7 +606,7 @@ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) #ifdef WOLF_CRYPTO_CB if (sha->devId != INVALID_DEVID) { ret = wc_CryptoCb_ShaHash(sha, data, len, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; ret = 0; /* reset ret */ /* fall-through when unavailable */ @@ -817,7 +825,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) #ifdef WOLF_CRYPTO_CB if (sha->devId != INVALID_DEVID) { ret = wc_CryptoCb_ShaHash(sha, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } diff --git a/src/wolfcrypt/src/sha256.c b/src/wolfcrypt/src/sha256.c index 0025e85..f955dff 100644 --- a/src/wolfcrypt/src/sha256.c +++ b/src/wolfcrypt/src/sha256.c @@ -71,8 +71,8 @@ on the specific device platform. #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$d") - #pragma const_seg(".fipsB$d") + #pragma code_seg(".fipsA$l") + #pragma const_seg(".fipsB$l") #endif #endif @@ -141,6 +141,14 @@ on the specific device platform. #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_sha256_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000014 }; + int wolfCrypt_FIPS_SHA256_sanity(void) + { + return 0; + } +#endif #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) #if defined(__GNUC__) && ((__GNUC__ < 4) || \ @@ -168,8 +176,7 @@ on the specific device platform. #define HAVE_INTEL_RORX #endif - -#if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) +#if defined(LITTLE_ENDIAN_ORDER) #if ( defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP8684) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ @@ -182,20 +189,28 @@ on the specific device platform. * depending on if HW is active or not. */ #define SHA256_REV_BYTES(ctx) \ (esp_sha_need_byte_reversal(ctx)) + #elif defined(FREESCALE_MMCAU_SHA) + #define SHA256_REV_BYTES(ctx) 1 /* reverse needed on final */ #endif #endif #ifndef SHA256_REV_BYTES - #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) + #if defined(LITTLE_ENDIAN_ORDER) #define SHA256_REV_BYTES(ctx) 1 #else #define SHA256_REV_BYTES(ctx) 0 #endif #endif -#if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA) && \ +#if defined(LITTLE_ENDIAN_ORDER) && \ defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - #define SHA256_UPDATE_REV_BYTES(ctx) \ - (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA256_UPDATE_REV_BYTES(ctx) (sha256->sha_method == SHA256_C) + #else + #define SHA256_UPDATE_REV_BYTES(ctx) \ + (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif +#elif defined(FREESCALE_MMCAU_SHA) + #define SHA256_UPDATE_REV_BYTES(ctx) 0 /* reverse not needed on update */ #else #define SHA256_UPDATE_REV_BYTES(ctx) SHA256_REV_BYTES(ctx) #endif @@ -217,6 +232,15 @@ on the specific device platform. (!defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH)) && \ !defined(WOLFSSL_RENESAS_RX64_HASH) +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + #define SHA256_SETTRANSFORM_ARGS int *sha_method +#else + #define SHA256_SETTRANSFORM_ARGS void +#endif +static void Sha256_SetTransform(SHA256_SETTRANSFORM_ARGS); +#endif static int InitSha256(wc_Sha256* sha256) { @@ -242,6 +266,17 @@ static int InitSha256(wc_Sha256* sha256) sha256->used = 0; #endif +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + /* choose best Transform function under this runtime environment */ +#ifdef WC_C_DYNAMIC_FALLBACK + sha256->sha_method = 0; + Sha256_SetTransform(&sha256->sha_method); +#else + Sha256_SetTransform(); +#endif +#endif + #ifdef WOLF_CRYPTO_CB sha256->devId = wc_CryptoCb_DefaultDevID(); #endif @@ -360,25 +395,205 @@ static int InitSha256(wc_Sha256* sha256) } /* extern "C" */ #endif + static word32 intel_flags = 0; + +#if defined(WC_C_DYNAMIC_FALLBACK) && !defined(WC_NO_INTERNAL_FUNCTION_POINTERS) + #define WC_NO_INTERNAL_FUNCTION_POINTERS +#endif + +#ifdef WC_NO_INTERNAL_FUNCTION_POINTERS + + enum sha_methods { SHA256_UNSET = 0, SHA256_AVX1_SHA, SHA256_AVX2, + SHA256_AVX1_RORX, SHA256_AVX1_NOSHA, SHA256_AVX2_RORX, + SHA256_SSE2, SHA256_C }; + +#ifndef WC_C_DYNAMIC_FALLBACK + static enum sha_methods sha_method = SHA256_UNSET; +#endif + + static void Sha256_SetTransform(SHA256_SETTRANSFORM_ARGS) + { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (*sha_method) + #else + #define SHA_METHOD sha_method + #endif + if (SHA_METHOD != SHA256_UNSET) + return; + + #ifdef WC_C_DYNAMIC_FALLBACK + if (! CAN_SAVE_VECTOR_REGISTERS()) { + SHA_METHOD = SHA256_C; + return; + } + #endif + + if (intel_flags == 0) + intel_flags = cpuid_get_flags(); + + if (IS_INTEL_SHA(intel_flags)) { + #ifdef HAVE_INTEL_AVX1 + if (IS_INTEL_AVX1(intel_flags)) { + SHA_METHOD = SHA256_AVX1_SHA; + } + else + #endif + { + SHA_METHOD = SHA256_SSE2; + } + } + else + #ifdef HAVE_INTEL_AVX2 + if (IS_INTEL_AVX2(intel_flags)) { + #ifdef HAVE_INTEL_RORX + if (IS_INTEL_BMI2(intel_flags)) { + SHA_METHOD = SHA256_AVX2_RORX; + } + else + #endif + { + SHA_METHOD = SHA256_AVX2; + } + } + else + #endif + #ifdef HAVE_INTEL_AVX1 + if (IS_INTEL_AVX1(intel_flags)) { + #ifdef HAVE_INTEL_RORX + if (IS_INTEL_BMI2(intel_flags)) { + SHA_METHOD = SHA256_AVX1_RORX; + } + else + #endif + { + SHA_METHOD = SHA256_AVX1_NOSHA; + } + } + else + #endif + { + SHA_METHOD = SHA256_C; + } + #undef SHA_METHOD + } + + static WC_INLINE int inline_XTRANSFORM(wc_Sha256* S, const byte* D) { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (S->sha_method) + #else + #define SHA_METHOD sha_method + #endif + int ret; + + if (SHA_METHOD == SHA256_C) + return Transform_Sha256(S, D); + SAVE_VECTOR_REGISTERS(return _svr_ret;); + switch (SHA_METHOD) { + case SHA256_AVX2: + ret = Transform_Sha256_AVX2(S, D); + break; + case SHA256_AVX2_RORX: + ret = Transform_Sha256_AVX2_RORX(S, D); + break; + case SHA256_AVX1_SHA: + ret = Transform_Sha256_AVX1_Sha(S, D); + break; + case SHA256_AVX1_NOSHA: + ret = Transform_Sha256_AVX1(S, D); + break; + case SHA256_AVX1_RORX: + ret = Transform_Sha256_AVX1_RORX(S, D); + break; + case SHA256_SSE2: + ret = Transform_Sha256_SSE2_Sha(S, D); + break; + case SHA256_C: + case SHA256_UNSET: + default: + ret = Transform_Sha256(S, D); + break; + } + RESTORE_VECTOR_REGISTERS(); + return ret; + #undef SHA_METHOD + } +#define XTRANSFORM(...) inline_XTRANSFORM(__VA_ARGS__) + + static WC_INLINE int inline_XTRANSFORM_LEN(wc_Sha256* S, const byte* D, word32 L) { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (S->sha_method) + #else + #define SHA_METHOD sha_method + #endif + int ret; + SAVE_VECTOR_REGISTERS(return _svr_ret;); + switch (SHA_METHOD) { + case SHA256_AVX2: + ret = Transform_Sha256_AVX2_Len(S, D, L); + break; + case SHA256_AVX2_RORX: + ret = Transform_Sha256_AVX2_RORX_Len(S, D, L); + break; + case SHA256_AVX1_SHA: + ret = Transform_Sha256_AVX1_Sha_Len(S, D, L); + break; + case SHA256_AVX1_NOSHA: + ret = Transform_Sha256_AVX1_Len(S, D, L); + break; + case SHA256_AVX1_RORX: + ret = Transform_Sha256_AVX1_RORX_Len(S, D, L); + break; + case SHA256_SSE2: + ret = Transform_Sha256_SSE2_Sha_Len(S, D, L); + break; + case SHA256_C: + case SHA256_UNSET: + default: + ret = 0; + break; + } + RESTORE_VECTOR_REGISTERS(); + return ret; + #undef SHA_METHOD + } +#define XTRANSFORM_LEN(...) inline_XTRANSFORM_LEN(__VA_ARGS__) + +#else /* !WC_NO_INTERNAL_FUNCTION_POINTERS */ + static int (*Transform_Sha256_p)(wc_Sha256* sha256, const byte* data); /* = _Transform_Sha256 */ static int (*Transform_Sha256_Len_p)(wc_Sha256* sha256, const byte* data, word32 len); /* = NULL */ static int transform_check = 0; - static word32 intel_flags; static int Transform_Sha256_is_vectorized = 0; static WC_INLINE int inline_XTRANSFORM(wc_Sha256* S, const byte* D) { int ret; + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha256_is_vectorized) + SAVE_VECTOR_REGISTERS(return _svr_ret;); + #endif ret = (*Transform_Sha256_p)(S, D); + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha256_is_vectorized) + RESTORE_VECTOR_REGISTERS(); + #endif return ret; } #define XTRANSFORM(...) inline_XTRANSFORM(__VA_ARGS__) static WC_INLINE int inline_XTRANSFORM_LEN(wc_Sha256* S, const byte* D, word32 L) { int ret; + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha256_is_vectorized) + SAVE_VECTOR_REGISTERS(return _svr_ret;); + #endif ret = (*Transform_Sha256_Len_p)(S, D, L); + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha256_is_vectorized) + RESTORE_VECTOR_REGISTERS(); + #endif return ret; } #define XTRANSFORM_LEN(...) inline_XTRANSFORM_LEN(__VA_ARGS__) @@ -452,6 +667,8 @@ static int InitSha256(wc_Sha256* sha256) transform_check = 1; } +#endif /* !WC_NO_INTERNAL_FUNCTION_POINTERS */ + #if !defined(WOLFSSL_KCAPI_HASH) int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) { @@ -472,9 +689,6 @@ static int InitSha256(wc_Sha256* sha256) if (ret != 0) return ret; - /* choose best Transform function under this runtime environment */ - Sha256_SetTransform(); - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) ret = wolfAsync_DevCtxInit(&sha256->asyncDev, WOLFSSL_ASYNC_MARKER_SHA256, sha256->heap, devId); @@ -617,7 +831,14 @@ static int InitSha256(wc_Sha256* sha256) { int ret = 0; - if (sha256 == NULL || (data == NULL && len > 0)) { + if (sha256 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { return BAD_FUNC_ARG; } @@ -668,6 +889,17 @@ static int InitSha256(wc_Sha256* sha256) int wc_Sha256Update(wc_Sha256* sha256, const byte* data, word32 len) { + if (sha256 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + return se050_hash_update(&sha256->se050Ctx, data, len); } @@ -1151,7 +1383,15 @@ static int InitSha256(wc_Sha256* sha256) #ifdef XTRANSFORM_LEN #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha256->sha_method != SHA256_C) + #elif defined(WC_NO_INTERNAL_FUNCTION_POINTERS) + if (sha_method != SHA256_C) + #else if (Transform_Sha256_Len_p != NULL) + #endif + #endif { if (len >= WC_SHA256_BLOCK_SIZE) { @@ -1259,7 +1499,7 @@ static int InitSha256(wc_Sha256* sha256) #endif { int ret = wc_CryptoCb_Sha256Hash(sha256, data, len, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1387,8 +1627,12 @@ static int InitSha256(wc_Sha256* sha256) /* Kinetis requires only these bytes reversed */ #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha256->sha_method != SHA256_C) + #else if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags)) #endif + #endif { ByteReverseWords( &sha256->buffer[WC_SHA256_PAD_SIZE / sizeof(word32)], @@ -1456,7 +1700,7 @@ static int InitSha256(wc_Sha256* sha256) #endif { ret = wc_CryptoCb_Sha256Hash(sha256, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1732,11 +1976,19 @@ static int InitSha256(wc_Sha256* sha256) sha224->loLen = 0; sha224->hiLen = 0; + #ifdef WC_C_DYNAMIC_FALLBACK + sha224->sha_method = 0; + #endif + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) /* choose best Transform function under this runtime environment */ + #ifdef WC_C_DYNAMIC_FALLBACK + Sha256_SetTransform(&sha224->sha_method); + #else Sha256_SetTransform(); #endif + #endif #ifdef WOLFSSL_HASH_FLAGS sha224->flags = 0; #endif diff --git a/src/wolfcrypt/src/sha3.c b/src/wolfcrypt/src/sha3.c index 096566d..99f739b 100644 --- a/src/wolfcrypt/src/sha3.c +++ b/src/wolfcrypt/src/sha3.c @@ -29,13 +29,13 @@ #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_XILINX_CRYPT) && \ !defined(WOLFSSL_AFALG_XILINX_SHA3) -#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$l") - #pragma const_seg(".fipsB$l") + #pragma code_seg(".fipsA$n") + #pragma const_seg(".fipsB$n") #endif #endif @@ -43,6 +43,9 @@ #include #include +#ifdef WOLF_CRYPTO_CB + #include +#endif #ifdef NO_INLINE #include #else @@ -50,17 +53,33 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_sha3_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000016 }; + int wolfCrypt_FIPS_SHA3_sanity(void) + { + return 0; + } +#endif -#if !defined(WOLFSSL_ARMASM) || !defined(WOLFSSL_ARMASM_CRYPTO_SHA3) +#if !defined(WOLFSSL_ARMASM) || (!defined(__arm__) && \ + !defined(WOLFSSL_ARMASM_CRYPTO_SHA3)) #ifdef USE_INTEL_SPEEDUP #include word32 cpuid_flags; int cpuid_flags_set = 0; +#ifdef WC_C_DYNAMIC_FALLBACK + #define SHA3_BLOCK (sha3->sha3_block) + #define SHA3_BLOCK_N (sha3->sha3_block_n) +#else void (*sha3_block)(word64 *s) = NULL; void (*sha3_block_n)(word64 *s, const byte* data, word32 n, word64 c) = NULL; + #define SHA3_BLOCK sha3_block + #define SHA3_BLOCK_N sha3_block_n +#endif #endif #ifdef WOLFSSL_SHA3_SMALL @@ -614,15 +633,26 @@ static int InitSha3(wc_Sha3* sha3) if (!cpuid_flags_set) { cpuid_flags = cpuid_get_flags(); cpuid_flags_set = 1; +#ifdef WC_C_DYNAMIC_FALLBACK + } + { + if (! CAN_SAVE_VECTOR_REGISTERS()) { + SHA3_BLOCK = BlockSha3; + SHA3_BLOCK_N = NULL; + } + else +#endif if (IS_INTEL_BMI1(cpuid_flags) && IS_INTEL_BMI2(cpuid_flags)) { - sha3_block = sha3_block_bmi2; - sha3_block_n = sha3_block_n_bmi2; + SHA3_BLOCK = sha3_block_bmi2; + SHA3_BLOCK_N = sha3_block_n_bmi2; } else if (IS_INTEL_AVX2(cpuid_flags)) { - sha3_block = sha3_block_avx2; + SHA3_BLOCK = sha3_block_avx2; + SHA3_BLOCK_N = NULL; } else { - sha3_block = BlockSha3; + SHA3_BLOCK = BlockSha3; + SHA3_BLOCK_N = NULL; } } #endif @@ -643,6 +673,10 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) word32 i; word32 blocks; +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#endif if (sha3->i > 0) { byte *t; byte l = (byte)(p * 8 - sha3->i); @@ -663,7 +697,7 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); } #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(sha3->s); + (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); #endif @@ -672,8 +706,8 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) } blocks = len / (p * 8); #ifdef USE_INTEL_SPEEDUP - if ((sha3_block_n != NULL) && (blocks > 0)) { - (*sha3_block_n)(sha3->s, data, blocks, p * 8); + if ((SHA3_BLOCK_N != NULL) && (blocks > 0)) { + (*SHA3_BLOCK_N)(sha3->s, data, blocks, p * 8); len -= blocks * (p * 8); data += blocks * (p * 8); blocks = 0; @@ -684,13 +718,17 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) sha3->s[i] ^= Load64Unaligned(data + 8 * i); } #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(sha3->s); + (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); #endif len -= p * 8; data += p * 8; } +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + RESTORE_VECTOR_REGISTERS(); +#endif XMEMCPY(sha3->t, data, len); sha3->i += (byte)len; @@ -724,9 +762,15 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) for (i = 0; i < p; i++) { sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); } + +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#endif + for (j = 0; l - j >= rate; j += rate) { #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(sha3->s); + (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); #endif @@ -738,7 +782,7 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) } if (j != l) { #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(sha3->s); + (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); #endif @@ -747,6 +791,11 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) #endif XMEMCPY(hash + j, sha3->s, l - j); } +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + RESTORE_VECTOR_REGISTERS(); +#endif + return 0; } @@ -772,10 +821,12 @@ static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) ret = wolfAsync_DevCtxInit(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3, sha3->heap, devId); -#else - (void)devId; +#elif defined(WOLF_CRYPTO_CB) + sha3->devId = devId; #endif /* WOLFSSL_ASYNC_CRYPT */ + (void)devId; + return ret; } @@ -800,13 +851,32 @@ static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) return 0; } +#ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha3->devId != INVALID_DEVID) + #endif + { + int hash_type = WC_HASH_TYPE_NONE; + switch (p) { + case WC_SHA3_224_COUNT: hash_type = WC_HASH_TYPE_SHA3_224; break; + case WC_SHA3_256_COUNT: hash_type = WC_HASH_TYPE_SHA3_256; break; + case WC_SHA3_384_COUNT: hash_type = WC_HASH_TYPE_SHA3_384; break; + case WC_SHA3_512_COUNT: hash_type = WC_HASH_TYPE_SHA3_512; break; + default: return BAD_FUNC_ARG; + } + ret = wc_CryptoCb_Sha3Hash(sha3, hash_type, data, len, NULL); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + } +#endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) { #if defined(HAVE_INTEL_QA) && defined(QAT_V2) /* QAT only supports SHA3_256 */ if (p == WC_SHA3_256_COUNT) { ret = IntelQaSymSha3(&sha3->asyncDev, NULL, data, len); - if (ret != NOT_COMPILED_IN) + if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) return ret; /* fall-through when unavailable */ } @@ -835,6 +905,25 @@ static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, byte p, byte len) return BAD_FUNC_ARG; } +#ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (sha3->devId != INVALID_DEVID) + #endif + { + int hash_type = WC_HASH_TYPE_NONE; + switch (p) { + case WC_SHA3_224_COUNT: hash_type = WC_HASH_TYPE_SHA3_224; break; + case WC_SHA3_256_COUNT: hash_type = WC_HASH_TYPE_SHA3_256; break; + case WC_SHA3_384_COUNT: hash_type = WC_HASH_TYPE_SHA3_384; break; + case WC_SHA3_512_COUNT: hash_type = WC_HASH_TYPE_SHA3_512; break; + default: return BAD_FUNC_ARG; + } + ret = wc_CryptoCb_Sha3Hash(sha3, hash_type, NULL, 0, hash); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + } +#endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) { #if defined(HAVE_INTEL_QA) && defined(QAT_V2) @@ -842,7 +931,7 @@ static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, byte p, byte len) /* QAT SHA-3 only supported on v2 (8970 or later cards) */ if (len == WC_SHA3_256_DIGEST_SIZE) { ret = IntelQaSymSha3(&sha3->asyncDev, hash, NULL, len); - if (ret != NOT_COMPILED_IN) + if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) return ret; /* fall-through when unavailable */ } @@ -1311,6 +1400,13 @@ int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len) return ret; } +#ifdef WC_C_DYNAMIC_FALLBACK + #undef SHA3_BLOCK + #undef SHA3_BLOCK_N + #define SHA3_BLOCK (shake->sha3_block) + #define SHA3_BLOCK_N (shake->sha3_block_n) +#endif + /* Squeeze the state to produce pseudo-random output. * * shake wc_Shake object holding state. @@ -1320,9 +1416,13 @@ int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len) */ int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) { +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#endif for (; (blockCnt > 0); blockCnt--) { #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(shake->s); + (*SHA3_BLOCK)(shake->s); #else BlockSha3(shake->s); #endif @@ -1333,6 +1433,10 @@ int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) #endif out += WC_SHA3_128_COUNT * 8; } +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + RESTORE_VECTOR_REGISTERS(); +#endif return 0; } @@ -1450,9 +1554,13 @@ int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len) */ int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) { +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + SAVE_VECTOR_REGISTERS(return _svr_ret;); +#endif for (; (blockCnt > 0); blockCnt--) { #ifdef USE_INTEL_SPEEDUP - (*sha3_block)(shake->s); + (*SHA3_BLOCK)(shake->s); #else BlockSha3(shake->s); #endif @@ -1463,6 +1571,10 @@ int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) #endif out += WC_SHA3_256_COUNT * 8; } +#if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) + if (SHA3_BLOCK == sha3_block_avx2) + RESTORE_VECTOR_REGISTERS(); +#endif return 0; } diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index 91bf1e5..88c38f0 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -50,8 +50,8 @@ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API - #pragma code_seg(".fipsA$k") - #pragma const_seg(".fipsB$k") + #pragma code_seg(".fipsA$m") + #pragma const_seg(".fipsB$m") #endif #endif @@ -82,11 +82,20 @@ #include #endif +#if FIPS_VERSION3_GE(6,0,0) + const unsigned int wolfCrypt_FIPS_sha512_ro_sanity[2] = + { 0x1a2b3c4d, 0x00000015 }; + int wolfCrypt_FIPS_SHA512_sanity(void) + { + return 0; + } +#endif + + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) #include #endif - #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) #if defined(__GNUC__) && ((__GNUC__ < 4) || \ (__GNUC__ == 4 && __GNUC_MINOR__ <= 8)) @@ -157,6 +166,17 @@ } int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) { + if (sha512 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + return se050_hash_update(&sha512->se050Ctx, data, len); } int wc_Sha512Final(wc_Sha512* sha512, byte* hash) @@ -196,6 +216,16 @@ #ifdef WOLFSSL_SHA512 +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + #define SHA512_SETTRANSFORM_ARGS int *sha_method +#else + #define SHA512_SETTRANSFORM_ARGS void +#endif +static void Sha512_SetTransform(SHA512_SETTRANSFORM_ARGS); +#endif + static int InitSha512(wc_Sha512* sha512) { if (sha512 == NULL) @@ -214,6 +244,16 @@ static int InitSha512(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + sha512->sha_method = 0; + Sha512_SetTransform(&sha512->sha_method); +#else + Sha512_SetTransform(); +#endif +#endif + #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) @@ -255,6 +295,16 @@ static int InitSha512_224(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + sha512->sha_method = 0; + Sha512_SetTransform(&sha512->sha_method); +#else + Sha512_SetTransform(); +#endif +#endif + #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) /* HW needs to be carefully initialized, taking into account soft copy. @@ -298,6 +348,16 @@ static int InitSha512_256(wc_Sha512* sha512) sha512->loLen = 0; sha512->hiLen = 0; +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + sha512->sha_method = 0; + Sha512_SetTransform(&sha512->sha_method); +#else + Sha512_SetTransform(); +#endif +#endif + #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) /* HW needs to be carefully initialized, taking into account soft copy. @@ -415,21 +475,174 @@ static int InitSha512_256(wc_Sha512* sha512) } /* extern "C" */ #endif + static word32 intel_flags = 0; + +#if defined(WC_C_DYNAMIC_FALLBACK) && !defined(WC_NO_INTERNAL_FUNCTION_POINTERS) + #define WC_NO_INTERNAL_FUNCTION_POINTERS +#endif + static int _Transform_Sha512(wc_Sha512 *sha512); + +#ifdef WC_NO_INTERNAL_FUNCTION_POINTERS + + enum sha_methods { SHA512_UNSET = 0, SHA512_AVX1, SHA512_AVX2, + SHA512_AVX1_RORX, SHA512_AVX2_RORX, SHA512_C }; + +#ifndef WC_C_DYNAMIC_FALLBACK + static enum sha_methods sha_method = SHA512_UNSET; +#endif + + static void Sha512_SetTransform(SHA512_SETTRANSFORM_ARGS) + { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (*sha_method) + #else + #define SHA_METHOD sha_method + #endif + if (SHA_METHOD != SHA512_UNSET) + return; + + #ifdef WC_C_DYNAMIC_FALLBACK + if (! CAN_SAVE_VECTOR_REGISTERS()) { + SHA_METHOD = SHA512_C; + return; + } + #endif + + if (intel_flags == 0) + intel_flags = cpuid_get_flags(); + + #if defined(HAVE_INTEL_AVX2) + if (IS_INTEL_AVX2(intel_flags)) { + #ifdef HAVE_INTEL_RORX + if (IS_INTEL_BMI2(intel_flags)) { + SHA_METHOD = SHA512_AVX2_RORX; + } + else + #endif + { + SHA_METHOD = SHA512_AVX2; + } + } + else + #endif + #if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + #ifdef HAVE_INTEL_RORX + if (IS_INTEL_BMI2(intel_flags)) { + SHA_METHOD = SHA512_AVX1_RORX; + } + else + #endif + { + SHA_METHOD = SHA512_AVX1; + } + } + else + #endif + { + SHA_METHOD = SHA512_C; + } + #undef SHA_METHOD + } + + static WC_INLINE int Transform_Sha512(wc_Sha512 *sha512) { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (sha512->sha_method) + #else + #define SHA_METHOD sha_method + #endif + int ret; + if (SHA_METHOD == SHA512_C) + return _Transform_Sha512(sha512); + SAVE_VECTOR_REGISTERS(return _svr_ret;); + switch (SHA_METHOD) { + case SHA512_AVX2: + ret = Transform_Sha512_AVX2(sha512); + break; + case SHA512_AVX2_RORX: + ret = Transform_Sha512_AVX2_RORX(sha512); + break; + case SHA512_AVX1: + ret = Transform_Sha512_AVX1(sha512); + break; + case SHA512_AVX1_RORX: + ret = Transform_Sha512_AVX1_RORX(sha512); + break; + case SHA512_C: + case SHA512_UNSET: + default: + ret = _Transform_Sha512(sha512); + break; + } + RESTORE_VECTOR_REGISTERS(); + return ret; + #undef SHA_METHOD + } + + static WC_INLINE int Transform_Sha512_Len(wc_Sha512 *sha512, word32 len) { + #ifdef WC_C_DYNAMIC_FALLBACK + #define SHA_METHOD (sha512->sha_method) + #else + #define SHA_METHOD sha_method + #endif + int ret; + SAVE_VECTOR_REGISTERS(return _svr_ret;); + switch (SHA_METHOD) { + case SHA512_AVX2: + ret = Transform_Sha512_AVX2_Len(sha512, len); + break; + case SHA512_AVX2_RORX: + ret = Transform_Sha512_AVX2_RORX_Len(sha512, len); + break; + case SHA512_AVX1: + ret = Transform_Sha512_AVX1_Len(sha512, len); + break; + case SHA512_AVX1_RORX: + ret = Transform_Sha512_AVX1_RORX_Len(sha512, len); + break; + case SHA512_C: + case SHA512_UNSET: + default: + ret = 0; + break; + } + RESTORE_VECTOR_REGISTERS(); + return ret; + #undef SHA_METHOD + } + +#else /* !WC_NO_INTERNAL_FUNCTION_POINTERS */ + static int (*Transform_Sha512_p)(wc_Sha512* sha512) = _Transform_Sha512; static int (*Transform_Sha512_Len_p)(wc_Sha512* sha512, word32 len) = NULL; static int transform_check = 0; - static word32 intel_flags; static int Transform_Sha512_is_vectorized = 0; static WC_INLINE int Transform_Sha512(wc_Sha512 *sha512) { int ret; + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha512_is_vectorized) + SAVE_VECTOR_REGISTERS(return _svr_ret;); + #endif ret = (*Transform_Sha512_p)(sha512); + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha512_is_vectorized) + RESTORE_VECTOR_REGISTERS(); + #endif return ret; } static WC_INLINE int Transform_Sha512_Len(wc_Sha512 *sha512, word32 len) { int ret; + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha512_is_vectorized) + SAVE_VECTOR_REGISTERS(return _svr_ret;); + #endif ret = (*Transform_Sha512_Len_p)(sha512, len); + #ifdef WOLFSSL_LINUXKM + if (Transform_Sha512_is_vectorized) + RESTORE_VECTOR_REGISTERS(); + #endif return ret; } @@ -485,6 +698,8 @@ static int InitSha512_256(wc_Sha512* sha512) transform_check = 1; } +#endif /* !WC_NO_INTERNAL_FUNCTION_POINTERS */ + #else #define Transform_Sha512(sha512) _Transform_Sha512(sha512) @@ -495,7 +710,7 @@ static int InitSha512_256(wc_Sha512* sha512) static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, int (*initfp)(wc_Sha512*)) { - int ret = 0; + int ret = 0; if (sha512 == NULL) { return BAD_FUNC_ARG; @@ -516,10 +731,6 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, if (ret != 0) return ret; -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - Sha512_SetTransform(); -#endif #ifdef WOLFSSL_HASH_KEEP sha512->msg = NULL; sha512->len = 0; @@ -759,7 +970,11 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le #if defined(LITTLE_ENDIAN_ORDER) #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method == SHA512_C) + #else if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif #endif { #if !defined(WOLFSSL_ESP32_CRYPT) || \ @@ -775,15 +990,17 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) ret = Transform_Sha512(sha512); #else - if(sha512->ctx.mode == ESP32_SHA_INIT) { + if (sha512->ctx.mode == ESP32_SHA_INIT) { esp_sha_try_hw_lock(&sha512->ctx); } - ret = esp_sha512_process(sha512); - if(ret == 0 && sha512->ctx.mode == ESP32_SHA_SW){ + if (sha512->ctx.mode == ESP32_SHA_SW) { ByteReverseWords64(sha512->buffer, sha512->buffer, WC_SHA512_BLOCK_SIZE); ret = Transform_Sha512(sha512); } + else { + ret = esp_sha512_process(sha512); + } #endif if (ret == 0) sha512->buffLen = 0; @@ -794,7 +1011,16 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - if (Transform_Sha512_Len_p != NULL) { + + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method != SHA512_C) + #elif defined(WC_NO_INTERNAL_FUNCTION_POINTERS) + if (sha_method != SHA512_C) + #else + if (Transform_Sha512_Len_p != NULL) + #endif + + { word32 blocksLen = len & ~((word32)WC_SHA512_BLOCK_SIZE-1); if (blocksLen > 0) { @@ -819,7 +1045,11 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method == SHA512_C) + #else if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif { ByteReverseWords64(sha512->buffer, sha512->buffer, WC_SHA512_BLOCK_SIZE); @@ -879,7 +1109,14 @@ static WC_INLINE int Sha512Update(wc_Sha512* sha512, const byte* data, word32 le int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) { - if (sha512 == NULL || (data == NULL && len > 0)) { + if (sha512 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { return BAD_FUNC_ARG; } @@ -889,7 +1126,7 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) #endif { int ret = wc_CryptoCb_Sha512Hash(sha512, data, len, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -949,7 +1186,11 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #if defined(LITTLE_ENDIAN_ORDER) #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method == SHA512_C) + #else if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif #endif { @@ -995,7 +1236,11 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #if defined(LITTLE_ENDIAN_ORDER) #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method == SHA512_C) + #else if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif #endif #if !defined(WOLFSSL_ESP32_CRYPT) || \ defined(NO_WOLFSSL_ESP32_CRYPT_HASH) || \ @@ -1014,7 +1259,11 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha512->sha_method != SHA512_C) + #else if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags)) + #endif ByteReverseWords64(&(sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2]), &(sha512->buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64) - 2]), WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE); @@ -1109,7 +1358,7 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, { byte localHash[WC_SHA512_DIGEST_SIZE]; ret = wc_CryptoCb_Sha512Hash(sha512, NULL, 0, localHash); - if (ret != CRYPTOCB_UNAVAILABLE) { + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { XMEMCPY(hash, localHash, digestSz); return ret; } @@ -1217,15 +1466,14 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) return MEMORY_E; #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - Sha512_SetTransform(); -#endif - #if defined(LITTLE_ENDIAN_ORDER) #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) + #ifdef WC_C_DYNAMIC_FALLBACK + if (sha->sha_method == SHA512_C) + #else if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + #endif #endif { ByteReverseWords64((word64*)data, (word64*)data, @@ -1269,6 +1517,17 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) } int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) { + if (sha384 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + return se050_hash_update(&sha384->se050Ctx, data, len); } @@ -1318,6 +1577,16 @@ static int InitSha384(wc_Sha384* sha384) sha384->loLen = 0; sha384->hiLen = 0; +#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ + (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) +#ifdef WC_C_DYNAMIC_FALLBACK + sha384->sha_method = 0; + Sha512_SetTransform(&sha384->sha_method); +#else + Sha512_SetTransform(); +#endif +#endif + #if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA384) /* HW needs to be carefully initialized, taking into account soft copy. @@ -1344,7 +1613,15 @@ static int InitSha384(wc_Sha384* sha384) int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) { - if (sha384 == NULL || (data == NULL && len > 0)) { + + if (sha384 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { return BAD_FUNC_ARG; } @@ -1354,7 +1631,7 @@ int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) #endif { int ret = wc_CryptoCb_Sha384Hash(sha384, data, len, NULL); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1406,7 +1683,7 @@ int wc_Sha384Final(wc_Sha384* sha384, byte* hash) #endif { ret = wc_CryptoCb_Sha384Hash(sha384, NULL, 0, hash); - if (ret != CRYPTOCB_UNAVAILABLE) + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ } @@ -1460,11 +1737,6 @@ int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) return ret; } -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) && \ - (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)) - Sha512_SetTransform(); -#endif - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA384) ret = wolfAsync_DevCtxInit(&sha384->asyncDev, WOLFSSL_ASYNC_MARKER_SHA384, sha384->heap, devId); @@ -1614,7 +1886,8 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif -#if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) +#if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ + !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) #if defined(CONFIG_IDF_TARGET_ESP32) if (ret == 0) { ret = esp_sha512_ctx_copy(src, dst); @@ -1899,7 +2172,8 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif -#if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) +#if defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) && \ + !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA384) #if defined(CONFIG_IDF_TARGET_ESP32) esp_sha384_ctx_copy(src, dst); #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ diff --git a/src/wolfcrypt/src/signature.c b/src/wolfcrypt/src/signature.c index efcbd88..33cec70 100644 --- a/src/wolfcrypt/src/signature.c +++ b/src/wolfcrypt/src/signature.c @@ -169,7 +169,7 @@ int wc_SignatureVerifyHash( if (ret >= 0) ret = wc_ecc_verify_hash(sig, sig_len, hash_data, hash_len, &is_valid_sig, (ecc_key*)key); - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); if (ret != 0 || is_valid_sig != 1) { ret = SIG_VERIFY_E; } @@ -226,7 +226,7 @@ int wc_SignatureVerifyHash( #endif if (ret >= 0) ret = wc_RsaSSL_VerifyInline(plain_data, sig_len, &plain_ptr, (RsaKey*)key); - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); if (ret >= 0 && plain_ptr) { if ((word32)ret == hash_len && XMEMCMP(plain_ptr, hash_data, hash_len) == 0) { @@ -395,7 +395,7 @@ int wc_SignatureGenerateHash_ex( if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #else ret = SIG_TYPE_E; #endif @@ -426,7 +426,7 @@ int wc_SignatureGenerateHash_ex( if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); - } while (ret == WC_PENDING_E); + } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif /* WOLFSSL_CRYPTOCELL */ if (ret >= 0) { *sig_len = (word32)ret; diff --git a/src/wolfcrypt/src/sp_cortexm.c b/src/wolfcrypt/src/sp_cortexm.c index 07a3112..8ef1a13 100644 --- a/src/wolfcrypt/src/sp_cortexm.c +++ b/src/wolfcrypt/src/sp_cortexm.c @@ -2211,7 +2211,7 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x100\n\t" "\n" - "L_sp_2048_add_64_word:\n\t" + "L_sp_2048_add_64_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -2224,9 +2224,9 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_add_64_word\n\t" + "BNE L_sp_2048_add_64_word%=\n\t" #else - "BNE.N L_sp_2048_add_64_word\n\t" + "BNE.N L_sp_2048_add_64_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -2258,7 +2258,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x100\n\t" "\n" - "L_sp_2048_sub_in_pkace_64_word:\n\t" + "L_sp_2048_sub_in_pkace_64_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -2270,9 +2270,9 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_in_pkace_64_word\n\t" + "BNE L_sp_2048_sub_in_pkace_64_word%=\n\t" #else - "BNE.N L_sp_2048_sub_in_pkace_64_word\n\t" + "BNE.N L_sp_2048_sub_in_pkace_64_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -2312,13 +2312,13 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_mul_64_outer:\n\t" + "L_sp_2048_mul_64_outer%=:\n\t" "SUBS r3, r5, #0xfc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_mul_64_inner:\n\t" + "L_sp_2048_mul_64_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2335,14 +2335,14 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_64_inner_done\n\t" + "BGT L_sp_2048_mul_64_inner_done%=\n\t" #else - "BGT.N L_sp_2048_mul_64_inner_done\n\t" + "BGT.N L_sp_2048_mul_64_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_64_inner\n\t" + "BLT L_sp_2048_mul_64_inner%=\n\t" #else - "BLT.N L_sp_2048_mul_64_inner\n\t" + "BLT.N L_sp_2048_mul_64_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -2351,7 +2351,7 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_mul_64_inner_done:\n\t" + "L_sp_2048_mul_64_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -2359,9 +2359,9 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x1f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_mul_64_outer\n\t" + "BLE L_sp_2048_mul_64_outer%=\n\t" #else - "BLE.N L_sp_2048_mul_64_outer\n\t" + "BLE.N L_sp_2048_mul_64_outer%=\n\t" #endif "LDR lr, [%[a], #252]\n\t" "LDR r11, [%[b], #252]\n\t" @@ -2370,14 +2370,14 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_mul_64_store:\n\t" + "L_sp_2048_mul_64_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_64_store\n\t" + "BGT L_sp_2048_mul_64_store%=\n\t" #else - "BGT.N L_sp_2048_mul_64_store\n\t" + "BGT.N L_sp_2048_mul_64_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -2410,13 +2410,13 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_sqr_64_outer:\n\t" + "L_sp_2048_sqr_64_outer%=:\n\t" "SUBS r3, r5, #0xfc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_sqr_64_inner:\n\t" + "L_sp_2048_sqr_64_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2430,14 +2430,14 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_64_inner_done\n\t" + "BGT L_sp_2048_sqr_64_inner_done%=\n\t" #else - "BGT.N L_sp_2048_sqr_64_inner_done\n\t" + "BGT.N L_sp_2048_sqr_64_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_sqr_64_inner\n\t" + "BLT L_sp_2048_sqr_64_inner%=\n\t" #else - "BLT.N L_sp_2048_sqr_64_inner\n\t" + "BLT.N L_sp_2048_sqr_64_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -2445,7 +2445,7 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_sqr_64_inner_done:\n\t" + "L_sp_2048_sqr_64_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -2453,9 +2453,9 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x1f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_sqr_64_outer\n\t" + "BLE L_sp_2048_sqr_64_outer%=\n\t" #else - "BLE.N L_sp_2048_sqr_64_outer\n\t" + "BLE.N L_sp_2048_sqr_64_outer%=\n\t" #endif "LDR lr, [%[a], #252]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -2463,14 +2463,14 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_sqr_64_store:\n\t" + "L_sp_2048_sqr_64_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_64_store\n\t" + "BGT L_sp_2048_sqr_64_store%=\n\t" #else - "BGT.N L_sp_2048_sqr_64_store\n\t" + "BGT.N L_sp_2048_sqr_64_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -2520,7 +2520,7 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x80\n\t" "\n" - "L_sp_2048_add_32_word:\n\t" + "L_sp_2048_add_32_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -2533,9 +2533,9 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_add_32_word\n\t" + "BNE L_sp_2048_add_32_word%=\n\t" #else - "BNE.N L_sp_2048_add_32_word\n\t" + "BNE.N L_sp_2048_add_32_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -2567,7 +2567,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x80\n\t" "\n" - "L_sp_2048_sub_in_pkace_32_word:\n\t" + "L_sp_2048_sub_in_pkace_32_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -2579,9 +2579,9 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_in_pkace_32_word\n\t" + "BNE L_sp_2048_sub_in_pkace_32_word%=\n\t" #else - "BNE.N L_sp_2048_sub_in_pkace_32_word\n\t" + "BNE.N L_sp_2048_sub_in_pkace_32_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -2621,13 +2621,13 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_mul_32_outer:\n\t" + "L_sp_2048_mul_32_outer%=:\n\t" "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_mul_32_inner:\n\t" + "L_sp_2048_mul_32_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2644,14 +2644,14 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_32_inner_done\n\t" + "BGT L_sp_2048_mul_32_inner_done%=\n\t" #else - "BGT.N L_sp_2048_mul_32_inner_done\n\t" + "BGT.N L_sp_2048_mul_32_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_32_inner\n\t" + "BLT L_sp_2048_mul_32_inner%=\n\t" #else - "BLT.N L_sp_2048_mul_32_inner\n\t" + "BLT.N L_sp_2048_mul_32_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -2660,7 +2660,7 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_mul_32_inner_done:\n\t" + "L_sp_2048_mul_32_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -2668,9 +2668,9 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_mul_32_outer\n\t" + "BLE L_sp_2048_mul_32_outer%=\n\t" #else - "BLE.N L_sp_2048_mul_32_outer\n\t" + "BLE.N L_sp_2048_mul_32_outer%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "LDR r11, [%[b], #124]\n\t" @@ -2679,14 +2679,14 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_mul_32_store:\n\t" + "L_sp_2048_mul_32_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_32_store\n\t" + "BGT L_sp_2048_mul_32_store%=\n\t" #else - "BGT.N L_sp_2048_mul_32_store\n\t" + "BGT.N L_sp_2048_mul_32_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -2719,13 +2719,13 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_sqr_32_outer:\n\t" + "L_sp_2048_sqr_32_outer%=:\n\t" "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_sqr_32_inner:\n\t" + "L_sp_2048_sqr_32_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2739,14 +2739,14 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_32_inner_done\n\t" + "BGT L_sp_2048_sqr_32_inner_done%=\n\t" #else - "BGT.N L_sp_2048_sqr_32_inner_done\n\t" + "BGT.N L_sp_2048_sqr_32_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_sqr_32_inner\n\t" + "BLT L_sp_2048_sqr_32_inner%=\n\t" #else - "BLT.N L_sp_2048_sqr_32_inner\n\t" + "BLT.N L_sp_2048_sqr_32_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -2754,7 +2754,7 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_sqr_32_inner_done:\n\t" + "L_sp_2048_sqr_32_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -2762,9 +2762,9 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_sqr_32_outer\n\t" + "BLE L_sp_2048_sqr_32_outer%=\n\t" #else - "BLE.N L_sp_2048_sqr_32_outer\n\t" + "BLE.N L_sp_2048_sqr_32_outer%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -2772,14 +2772,14 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_sqr_32_store:\n\t" + "L_sp_2048_sqr_32_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_32_store\n\t" + "BGT L_sp_2048_sqr_32_store%=\n\t" #else - "BGT.N L_sp_2048_sqr_32_store\n\t" + "BGT.N L_sp_2048_sqr_32_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -2838,7 +2838,7 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_2048_mul_d_64_word:\n\t" + "L_sp_2048_mul_d_64_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -2852,9 +2852,9 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_d_64_word\n\t" + "BLT L_sp_2048_mul_d_64_word%=\n\t" #else - "BLT.N L_sp_2048_mul_d_64_word\n\t" + "BLT.N L_sp_2048_mul_d_64_word%=\n\t" #endif "STR r3, [%[r], #256]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -3252,7 +3252,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_2048_cond_sub_32_words:\n\t" + "L_sp_2048_cond_sub_32_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -3263,9 +3263,9 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "ADD r5, r5, #0x4\n\t" "CMP r5, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_sub_32_words\n\t" + "BLT L_sp_2048_cond_sub_32_words%=\n\t" #else - "BLT.N L_sp_2048_cond_sub_32_words\n\t" + "BLT.N L_sp_2048_cond_sub_32_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -3448,7 +3448,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_2048_mont_reduce_32_word:\n\t" + "L_sp_2048_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -3711,9 +3711,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x80\n\t" #ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_32_word\n\t" + "BLT L_sp_2048_mont_reduce_32_word%=\n\t" #else - "BLT.W L_sp_2048_mont_reduce_32_word\n\t" + "BLT.W L_sp_2048_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -3752,7 +3752,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_word:\n\t" + "L_sp_2048_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -3760,7 +3760,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_mul:\n\t" + "L_sp_2048_mont_reduce_32_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -3803,9 +3803,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_mul\n\t" + "BLT L_sp_2048_mont_reduce_32_mul%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_mul\n\t" + "BLT.N L_sp_2048_mont_reduce_32_mul%=\n\t" #endif "LDR r10, [%[a], #128]\n\t" "ADDS r4, r4, r3\n\t" @@ -3819,9 +3819,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_word\n\t" + "BLT L_sp_2048_mont_reduce_32_word%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_word\n\t" + "BLT.N L_sp_2048_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -3863,7 +3863,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_2048_mont_reduce_32_word:\n\t" + "L_sp_2048_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -4031,9 +4031,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x80\n\t" #ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_32_word\n\t" + "BLT L_sp_2048_mont_reduce_32_word%=\n\t" #else - "BLT.W L_sp_2048_mont_reduce_32_word\n\t" + "BLT.W L_sp_2048_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -4075,7 +4075,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_word:\n\t" + "L_sp_2048_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -4083,7 +4083,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_mul:\n\t" + "L_sp_2048_mont_reduce_32_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -4114,9 +4114,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_mul\n\t" + "BLT L_sp_2048_mont_reduce_32_mul%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_mul\n\t" + "BLT.N L_sp_2048_mont_reduce_32_mul%=\n\t" #endif "LDR r10, [%[a], #128]\n\t" "ADDS r4, r4, r3\n\t" @@ -4130,9 +4130,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_word\n\t" + "BLT L_sp_2048_mont_reduce_32_word%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_word\n\t" + "BLT.N L_sp_2048_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -4203,7 +4203,7 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_2048_mul_d_32_word:\n\t" + "L_sp_2048_mul_d_32_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -4217,9 +4217,9 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_d_32_word\n\t" + "BLT L_sp_2048_mul_d_32_word%=\n\t" #else - "BLT.N L_sp_2048_mul_d_32_word\n\t" + "BLT.N L_sp_2048_mul_d_32_word%=\n\t" #endif "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -4517,7 +4517,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_2048_word_32_bit:\n\t" + "L_div_2048_word_32_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -4527,7 +4527,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_2048_word_32_bit\n\t" + "bpl L_div_2048_word_32_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -4579,7 +4579,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x7c\n\t" "\n" - "L_sp_2048_cmp_32_words:\n\t" + "L_sp_2048_cmp_32_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -4592,7 +4592,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_2048_cmp_32_words\n\t" + "bcs L_sp_2048_cmp_32_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #124]\n\t" @@ -5380,7 +5380,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_2048_cond_sub_64_words:\n\t" + "L_sp_2048_cond_sub_64_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -5391,9 +5391,9 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "ADD r5, r5, #0x4\n\t" "CMP r5, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_sub_64_words\n\t" + "BLT L_sp_2048_cond_sub_64_words%=\n\t" #else - "BLT.N L_sp_2048_cond_sub_64_words\n\t" + "BLT.N L_sp_2048_cond_sub_64_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -5688,7 +5688,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_2048_mont_reduce_64_word:\n\t" + "L_sp_2048_mont_reduce_64_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -6207,9 +6207,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x100\n\t" #ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_64_word\n\t" + "BLT L_sp_2048_mont_reduce_64_word%=\n\t" #else - "BLT.W L_sp_2048_mont_reduce_64_word\n\t" + "BLT.W L_sp_2048_mont_reduce_64_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -6248,7 +6248,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_word:\n\t" + "L_sp_2048_mont_reduce_64_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -6256,7 +6256,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_mul:\n\t" + "L_sp_2048_mont_reduce_64_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -6299,9 +6299,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_mul\n\t" + "BLT L_sp_2048_mont_reduce_64_mul%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_mul\n\t" + "BLT.N L_sp_2048_mont_reduce_64_mul%=\n\t" #endif "LDR r10, [%[a], #256]\n\t" "ADDS r4, r4, r3\n\t" @@ -6315,9 +6315,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_word\n\t" + "BLT L_sp_2048_mont_reduce_64_word%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_word\n\t" + "BLT.N L_sp_2048_mont_reduce_64_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -6359,7 +6359,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_2048_mont_reduce_64_word:\n\t" + "L_sp_2048_mont_reduce_64_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -6687,9 +6687,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x100\n\t" #ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_64_word\n\t" + "BLT L_sp_2048_mont_reduce_64_word%=\n\t" #else - "BLT.W L_sp_2048_mont_reduce_64_word\n\t" + "BLT.W L_sp_2048_mont_reduce_64_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -6731,7 +6731,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_word:\n\t" + "L_sp_2048_mont_reduce_64_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -6739,7 +6739,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_mul:\n\t" + "L_sp_2048_mont_reduce_64_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -6770,9 +6770,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_mul\n\t" + "BLT L_sp_2048_mont_reduce_64_mul%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_mul\n\t" + "BLT.N L_sp_2048_mont_reduce_64_mul%=\n\t" #endif "LDR r10, [%[a], #256]\n\t" "ADDS r4, r4, r3\n\t" @@ -6786,9 +6786,9 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_word\n\t" + "BLT L_sp_2048_mont_reduce_64_word%=\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_word\n\t" + "BLT.N L_sp_2048_mont_reduce_64_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -6854,7 +6854,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x100\n\t" "\n" - "L_sp_2048_sub_64_word:\n\t" + "L_sp_2048_sub_64_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -6866,9 +6866,9 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_64_word\n\t" + "BNE L_sp_2048_sub_64_word%=\n\t" #else - "BNE.N L_sp_2048_sub_64_word\n\t" + "BNE.N L_sp_2048_sub_64_word%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -7121,7 +7121,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_2048_word_64_bit:\n\t" + "L_div_2048_word_64_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -7131,7 +7131,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_2048_word_64_bit\n\t" + "bpl L_div_2048_word_64_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -7286,7 +7286,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0xfc\n\t" "\n" - "L_sp_2048_cmp_64_words:\n\t" + "L_sp_2048_cmp_64_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -7299,7 +7299,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_2048_cmp_64_words\n\t" + "bcs L_sp_2048_cmp_64_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #252]\n\t" @@ -8562,7 +8562,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_cond_add_32_words:\n\t" + "L_sp_2048_cond_add_32_words%=:\n\t" "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -8573,9 +8573,9 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "ADD r4, r4, #0x4\n\t" "CMP r4, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_add_32_words\n\t" + "BLT L_sp_2048_cond_add_32_words%=\n\t" #else - "BLT.N L_sp_2048_cond_add_32_words\n\t" + "BLT.N L_sp_2048_cond_add_32_words%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -12948,7 +12948,7 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x180\n\t" "\n" - "L_sp_3072_add_96_word:\n\t" + "L_sp_3072_add_96_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -12961,9 +12961,9 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_add_96_word\n\t" + "BNE L_sp_3072_add_96_word%=\n\t" #else - "BNE.N L_sp_3072_add_96_word\n\t" + "BNE.N L_sp_3072_add_96_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -12995,7 +12995,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x180\n\t" "\n" - "L_sp_3072_sub_in_pkace_96_word:\n\t" + "L_sp_3072_sub_in_pkace_96_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -13007,9 +13007,9 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_in_pkace_96_word\n\t" + "BNE L_sp_3072_sub_in_pkace_96_word%=\n\t" #else - "BNE.N L_sp_3072_sub_in_pkace_96_word\n\t" + "BNE.N L_sp_3072_sub_in_pkace_96_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -13049,13 +13049,13 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_mul_96_outer:\n\t" + "L_sp_3072_mul_96_outer%=:\n\t" "SUBS r3, r5, #0x17c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_mul_96_inner:\n\t" + "L_sp_3072_mul_96_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13072,14 +13072,14 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_96_inner_done\n\t" + "BGT L_sp_3072_mul_96_inner_done%=\n\t" #else - "BGT.N L_sp_3072_mul_96_inner_done\n\t" + "BGT.N L_sp_3072_mul_96_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_96_inner\n\t" + "BLT L_sp_3072_mul_96_inner%=\n\t" #else - "BLT.N L_sp_3072_mul_96_inner\n\t" + "BLT.N L_sp_3072_mul_96_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -13088,7 +13088,7 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_mul_96_inner_done:\n\t" + "L_sp_3072_mul_96_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -13096,9 +13096,9 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x2f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_mul_96_outer\n\t" + "BLE L_sp_3072_mul_96_outer%=\n\t" #else - "BLE.N L_sp_3072_mul_96_outer\n\t" + "BLE.N L_sp_3072_mul_96_outer%=\n\t" #endif "LDR lr, [%[a], #380]\n\t" "LDR r11, [%[b], #380]\n\t" @@ -13107,14 +13107,14 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_mul_96_store:\n\t" + "L_sp_3072_mul_96_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_96_store\n\t" + "BGT L_sp_3072_mul_96_store%=\n\t" #else - "BGT.N L_sp_3072_mul_96_store\n\t" + "BGT.N L_sp_3072_mul_96_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -13147,13 +13147,13 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_sqr_96_outer:\n\t" + "L_sp_3072_sqr_96_outer%=:\n\t" "SUBS r3, r5, #0x17c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_sqr_96_inner:\n\t" + "L_sp_3072_sqr_96_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13167,14 +13167,14 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_96_inner_done\n\t" + "BGT L_sp_3072_sqr_96_inner_done%=\n\t" #else - "BGT.N L_sp_3072_sqr_96_inner_done\n\t" + "BGT.N L_sp_3072_sqr_96_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_sqr_96_inner\n\t" + "BLT L_sp_3072_sqr_96_inner%=\n\t" #else - "BLT.N L_sp_3072_sqr_96_inner\n\t" + "BLT.N L_sp_3072_sqr_96_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -13182,7 +13182,7 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_sqr_96_inner_done:\n\t" + "L_sp_3072_sqr_96_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -13190,9 +13190,9 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x2f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_sqr_96_outer\n\t" + "BLE L_sp_3072_sqr_96_outer%=\n\t" #else - "BLE.N L_sp_3072_sqr_96_outer\n\t" + "BLE.N L_sp_3072_sqr_96_outer%=\n\t" #endif "LDR lr, [%[a], #380]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -13200,14 +13200,14 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_sqr_96_store:\n\t" + "L_sp_3072_sqr_96_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_96_store\n\t" + "BGT L_sp_3072_sqr_96_store%=\n\t" #else - "BGT.N L_sp_3072_sqr_96_store\n\t" + "BGT.N L_sp_3072_sqr_96_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -13257,7 +13257,7 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0xc0\n\t" "\n" - "L_sp_3072_add_48_word:\n\t" + "L_sp_3072_add_48_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -13270,9 +13270,9 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_add_48_word\n\t" + "BNE L_sp_3072_add_48_word%=\n\t" #else - "BNE.N L_sp_3072_add_48_word\n\t" + "BNE.N L_sp_3072_add_48_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -13304,7 +13304,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0xc0\n\t" "\n" - "L_sp_3072_sub_in_pkace_48_word:\n\t" + "L_sp_3072_sub_in_pkace_48_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -13316,9 +13316,9 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_in_pkace_48_word\n\t" + "BNE L_sp_3072_sub_in_pkace_48_word%=\n\t" #else - "BNE.N L_sp_3072_sub_in_pkace_48_word\n\t" + "BNE.N L_sp_3072_sub_in_pkace_48_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -13358,13 +13358,13 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_mul_48_outer:\n\t" + "L_sp_3072_mul_48_outer%=:\n\t" "SUBS r3, r5, #0xbc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_mul_48_inner:\n\t" + "L_sp_3072_mul_48_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13381,14 +13381,14 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_48_inner_done\n\t" + "BGT L_sp_3072_mul_48_inner_done%=\n\t" #else - "BGT.N L_sp_3072_mul_48_inner_done\n\t" + "BGT.N L_sp_3072_mul_48_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_48_inner\n\t" + "BLT L_sp_3072_mul_48_inner%=\n\t" #else - "BLT.N L_sp_3072_mul_48_inner\n\t" + "BLT.N L_sp_3072_mul_48_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -13397,7 +13397,7 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_mul_48_inner_done:\n\t" + "L_sp_3072_mul_48_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -13405,9 +13405,9 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x174\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_mul_48_outer\n\t" + "BLE L_sp_3072_mul_48_outer%=\n\t" #else - "BLE.N L_sp_3072_mul_48_outer\n\t" + "BLE.N L_sp_3072_mul_48_outer%=\n\t" #endif "LDR lr, [%[a], #188]\n\t" "LDR r11, [%[b], #188]\n\t" @@ -13416,14 +13416,14 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_mul_48_store:\n\t" + "L_sp_3072_mul_48_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_48_store\n\t" + "BGT L_sp_3072_mul_48_store%=\n\t" #else - "BGT.N L_sp_3072_mul_48_store\n\t" + "BGT.N L_sp_3072_mul_48_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -13456,13 +13456,13 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_sqr_48_outer:\n\t" + "L_sp_3072_sqr_48_outer%=:\n\t" "SUBS r3, r5, #0xbc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_sqr_48_inner:\n\t" + "L_sp_3072_sqr_48_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13476,14 +13476,14 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_48_inner_done\n\t" + "BGT L_sp_3072_sqr_48_inner_done%=\n\t" #else - "BGT.N L_sp_3072_sqr_48_inner_done\n\t" + "BGT.N L_sp_3072_sqr_48_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_sqr_48_inner\n\t" + "BLT L_sp_3072_sqr_48_inner%=\n\t" #else - "BLT.N L_sp_3072_sqr_48_inner\n\t" + "BLT.N L_sp_3072_sqr_48_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -13491,7 +13491,7 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_sqr_48_inner_done:\n\t" + "L_sp_3072_sqr_48_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -13499,9 +13499,9 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x174\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_sqr_48_outer\n\t" + "BLE L_sp_3072_sqr_48_outer%=\n\t" #else - "BLE.N L_sp_3072_sqr_48_outer\n\t" + "BLE.N L_sp_3072_sqr_48_outer%=\n\t" #endif "LDR lr, [%[a], #188]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -13509,14 +13509,14 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_sqr_48_store:\n\t" + "L_sp_3072_sqr_48_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_48_store\n\t" + "BGT L_sp_3072_sqr_48_store%=\n\t" #else - "BGT.N L_sp_3072_sqr_48_store\n\t" + "BGT.N L_sp_3072_sqr_48_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -13575,7 +13575,7 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_3072_mul_d_96_word:\n\t" + "L_sp_3072_mul_d_96_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -13589,9 +13589,9 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_d_96_word\n\t" + "BLT L_sp_3072_mul_d_96_word%=\n\t" #else - "BLT.N L_sp_3072_mul_d_96_word\n\t" + "BLT.N L_sp_3072_mul_d_96_word%=\n\t" #endif "STR r3, [%[r], #384]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -14149,7 +14149,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_3072_cond_sub_48_words:\n\t" + "L_sp_3072_cond_sub_48_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -14160,9 +14160,9 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "ADD r5, r5, #0x4\n\t" "CMP r5, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_sub_48_words\n\t" + "BLT L_sp_3072_cond_sub_48_words%=\n\t" #else - "BLT.N L_sp_3072_cond_sub_48_words\n\t" + "BLT.N L_sp_3072_cond_sub_48_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -14401,7 +14401,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_3072_mont_reduce_48_word:\n\t" + "L_sp_3072_mont_reduce_48_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -14792,9 +14792,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0xc0\n\t" #ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_48_word\n\t" + "BLT L_sp_3072_mont_reduce_48_word%=\n\t" #else - "BLT.W L_sp_3072_mont_reduce_48_word\n\t" + "BLT.W L_sp_3072_mont_reduce_48_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -14833,7 +14833,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_word:\n\t" + "L_sp_3072_mont_reduce_48_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -14841,7 +14841,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_mul:\n\t" + "L_sp_3072_mont_reduce_48_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -14884,9 +14884,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_mul\n\t" + "BLT L_sp_3072_mont_reduce_48_mul%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_mul\n\t" + "BLT.N L_sp_3072_mont_reduce_48_mul%=\n\t" #endif "LDR r10, [%[a], #192]\n\t" "ADDS r4, r4, r3\n\t" @@ -14900,9 +14900,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_word\n\t" + "BLT L_sp_3072_mont_reduce_48_word%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_word\n\t" + "BLT.N L_sp_3072_mont_reduce_48_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -14944,7 +14944,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_3072_mont_reduce_48_word:\n\t" + "L_sp_3072_mont_reduce_48_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -15192,9 +15192,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0xc0\n\t" #ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_48_word\n\t" + "BLT L_sp_3072_mont_reduce_48_word%=\n\t" #else - "BLT.W L_sp_3072_mont_reduce_48_word\n\t" + "BLT.W L_sp_3072_mont_reduce_48_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -15236,7 +15236,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_word:\n\t" + "L_sp_3072_mont_reduce_48_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -15244,7 +15244,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_mul:\n\t" + "L_sp_3072_mont_reduce_48_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -15275,9 +15275,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_mul\n\t" + "BLT L_sp_3072_mont_reduce_48_mul%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_mul\n\t" + "BLT.N L_sp_3072_mont_reduce_48_mul%=\n\t" #endif "LDR r10, [%[a], #192]\n\t" "ADDS r4, r4, r3\n\t" @@ -15291,9 +15291,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_word\n\t" + "BLT L_sp_3072_mont_reduce_48_word%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_word\n\t" + "BLT.N L_sp_3072_mont_reduce_48_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -15364,7 +15364,7 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_3072_mul_d_48_word:\n\t" + "L_sp_3072_mul_d_48_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -15378,9 +15378,9 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_d_48_word\n\t" + "BLT L_sp_3072_mul_d_48_word%=\n\t" #else - "BLT.N L_sp_3072_mul_d_48_word\n\t" + "BLT.N L_sp_3072_mul_d_48_word%=\n\t" #endif "STR r3, [%[r], #192]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -15758,7 +15758,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_3072_word_48_bit:\n\t" + "L_div_3072_word_48_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -15768,7 +15768,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_3072_word_48_bit\n\t" + "bpl L_div_3072_word_48_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -15820,7 +15820,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0xbc\n\t" "\n" - "L_sp_3072_cmp_48_words:\n\t" + "L_sp_3072_cmp_48_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -15833,7 +15833,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_3072_cmp_48_words\n\t" + "bcs L_sp_3072_cmp_48_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #188]\n\t" @@ -16797,7 +16797,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_3072_cond_sub_96_words:\n\t" + "L_sp_3072_cond_sub_96_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -16808,9 +16808,9 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "ADD r5, r5, #0x4\n\t" "CMP r5, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_sub_96_words\n\t" + "BLT L_sp_3072_cond_sub_96_words%=\n\t" #else - "BLT.N L_sp_3072_cond_sub_96_words\n\t" + "BLT.N L_sp_3072_cond_sub_96_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -17217,7 +17217,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_3072_mont_reduce_96_word:\n\t" + "L_sp_3072_mont_reduce_96_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -17992,9 +17992,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x180\n\t" #ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_96_word\n\t" + "BLT L_sp_3072_mont_reduce_96_word%=\n\t" #else - "BLT.W L_sp_3072_mont_reduce_96_word\n\t" + "BLT.W L_sp_3072_mont_reduce_96_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -18033,7 +18033,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_word:\n\t" + "L_sp_3072_mont_reduce_96_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -18041,7 +18041,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_mul:\n\t" + "L_sp_3072_mont_reduce_96_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -18084,9 +18084,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_mul\n\t" + "BLT L_sp_3072_mont_reduce_96_mul%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_mul\n\t" + "BLT.N L_sp_3072_mont_reduce_96_mul%=\n\t" #endif "LDR r10, [%[a], #384]\n\t" "ADDS r4, r4, r3\n\t" @@ -18100,9 +18100,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_word\n\t" + "BLT L_sp_3072_mont_reduce_96_word%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_word\n\t" + "BLT.N L_sp_3072_mont_reduce_96_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -18144,7 +18144,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_3072_mont_reduce_96_word:\n\t" + "L_sp_3072_mont_reduce_96_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -18632,9 +18632,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x180\n\t" #ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_96_word\n\t" + "BLT L_sp_3072_mont_reduce_96_word%=\n\t" #else - "BLT.W L_sp_3072_mont_reduce_96_word\n\t" + "BLT.W L_sp_3072_mont_reduce_96_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -18676,7 +18676,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_word:\n\t" + "L_sp_3072_mont_reduce_96_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -18684,7 +18684,7 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_mul:\n\t" + "L_sp_3072_mont_reduce_96_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -18715,9 +18715,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r12, r12, #0x4\n\t" "CMP r12, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_mul\n\t" + "BLT L_sp_3072_mont_reduce_96_mul%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_mul\n\t" + "BLT.N L_sp_3072_mont_reduce_96_mul%=\n\t" #endif "LDR r10, [%[a], #384]\n\t" "ADDS r4, r4, r3\n\t" @@ -18731,9 +18731,9 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x180\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_word\n\t" + "BLT L_sp_3072_mont_reduce_96_word%=\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_word\n\t" + "BLT.N L_sp_3072_mont_reduce_96_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -18799,7 +18799,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x180\n\t" "\n" - "L_sp_3072_sub_96_word:\n\t" + "L_sp_3072_sub_96_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -18811,9 +18811,9 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_96_word\n\t" + "BNE L_sp_3072_sub_96_word%=\n\t" #else - "BNE.N L_sp_3072_sub_96_word\n\t" + "BNE.N L_sp_3072_sub_96_word%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -19122,7 +19122,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_3072_word_96_bit:\n\t" + "L_div_3072_word_96_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -19132,7 +19132,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_3072_word_96_bit\n\t" + "bpl L_div_3072_word_96_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -19287,7 +19287,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x17c\n\t" "\n" - "L_sp_3072_cmp_96_words:\n\t" + "L_sp_3072_cmp_96_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -19300,7 +19300,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_3072_cmp_96_words\n\t" + "bcs L_sp_3072_cmp_96_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #380]\n\t" @@ -20915,7 +20915,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_cond_add_48_words:\n\t" + "L_sp_3072_cond_add_48_words%=:\n\t" "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -20926,9 +20926,9 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "ADD r4, r4, #0x4\n\t" "CMP r4, #0xc0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_add_48_words\n\t" + "BLT L_sp_3072_cond_add_48_words%=\n\t" #else - "BLT.N L_sp_3072_cond_add_48_words\n\t" + "BLT.N L_sp_3072_cond_add_48_words%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -23059,7 +23059,7 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x200\n\t" "\n" - "L_sp_4096_add_128_word:\n\t" + "L_sp_4096_add_128_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -23072,9 +23072,9 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_add_128_word\n\t" + "BNE L_sp_4096_add_128_word%=\n\t" #else - "BNE.N L_sp_4096_add_128_word\n\t" + "BNE.N L_sp_4096_add_128_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -23106,7 +23106,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x200\n\t" "\n" - "L_sp_4096_sub_in_pkace_128_word:\n\t" + "L_sp_4096_sub_in_pkace_128_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -23118,9 +23118,9 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_sub_in_pkace_128_word\n\t" + "BNE L_sp_4096_sub_in_pkace_128_word%=\n\t" #else - "BNE.N L_sp_4096_sub_in_pkace_128_word\n\t" + "BNE.N L_sp_4096_sub_in_pkace_128_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -23160,13 +23160,13 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_4096_mul_128_outer:\n\t" + "L_sp_4096_mul_128_outer%=:\n\t" "SUBS r3, r5, #0x1fc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_4096_mul_128_inner:\n\t" + "L_sp_4096_mul_128_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -23183,14 +23183,14 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_mul_128_inner_done\n\t" + "BGT L_sp_4096_mul_128_inner_done%=\n\t" #else - "BGT.N L_sp_4096_mul_128_inner_done\n\t" + "BGT.N L_sp_4096_mul_128_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mul_128_inner\n\t" + "BLT L_sp_4096_mul_128_inner%=\n\t" #else - "BLT.N L_sp_4096_mul_128_inner\n\t" + "BLT.N L_sp_4096_mul_128_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -23199,7 +23199,7 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_4096_mul_128_inner_done:\n\t" + "L_sp_4096_mul_128_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -23207,9 +23207,9 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x3f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_4096_mul_128_outer\n\t" + "BLE L_sp_4096_mul_128_outer%=\n\t" #else - "BLE.N L_sp_4096_mul_128_outer\n\t" + "BLE.N L_sp_4096_mul_128_outer%=\n\t" #endif "LDR lr, [%[a], #508]\n\t" "LDR r11, [%[b], #508]\n\t" @@ -23218,14 +23218,14 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_4096_mul_128_store:\n\t" + "L_sp_4096_mul_128_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_mul_128_store\n\t" + "BGT L_sp_4096_mul_128_store%=\n\t" #else - "BGT.N L_sp_4096_mul_128_store\n\t" + "BGT.N L_sp_4096_mul_128_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -23258,13 +23258,13 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_4096_sqr_128_outer:\n\t" + "L_sp_4096_sqr_128_outer%=:\n\t" "SUBS r3, r5, #0x1fc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_4096_sqr_128_inner:\n\t" + "L_sp_4096_sqr_128_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -23278,14 +23278,14 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_sqr_128_inner_done\n\t" + "BGT L_sp_4096_sqr_128_inner_done%=\n\t" #else - "BGT.N L_sp_4096_sqr_128_inner_done\n\t" + "BGT.N L_sp_4096_sqr_128_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_sqr_128_inner\n\t" + "BLT L_sp_4096_sqr_128_inner%=\n\t" #else - "BLT.N L_sp_4096_sqr_128_inner\n\t" + "BLT.N L_sp_4096_sqr_128_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -23293,7 +23293,7 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_4096_sqr_128_inner_done:\n\t" + "L_sp_4096_sqr_128_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -23301,9 +23301,9 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x3f4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_4096_sqr_128_outer\n\t" + "BLE L_sp_4096_sqr_128_outer%=\n\t" #else - "BLE.N L_sp_4096_sqr_128_outer\n\t" + "BLE.N L_sp_4096_sqr_128_outer%=\n\t" #endif "LDR lr, [%[a], #508]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -23311,14 +23311,14 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_4096_sqr_128_store:\n\t" + "L_sp_4096_sqr_128_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_sqr_128_store\n\t" + "BGT L_sp_4096_sqr_128_store%=\n\t" #else - "BGT.N L_sp_4096_sqr_128_store\n\t" + "BGT.N L_sp_4096_sqr_128_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -23375,7 +23375,7 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_4096_mul_d_128_word:\n\t" + "L_sp_4096_mul_d_128_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -23389,9 +23389,9 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mul_d_128_word\n\t" + "BLT L_sp_4096_mul_d_128_word%=\n\t" #else - "BLT.N L_sp_4096_mul_d_128_word\n\t" + "BLT.N L_sp_4096_mul_d_128_word%=\n\t" #endif "STR r3, [%[r], #512]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -24110,7 +24110,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_4096_cond_sub_128_words:\n\t" + "L_sp_4096_cond_sub_128_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -24121,9 +24121,9 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "ADD r5, r5, #0x4\n\t" "CMP r5, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_cond_sub_128_words\n\t" + "BLT L_sp_4096_cond_sub_128_words%=\n\t" #else - "BLT.N L_sp_4096_cond_sub_128_words\n\t" + "BLT.N L_sp_4096_cond_sub_128_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -24642,7 +24642,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_4096_mont_reduce_128_word:\n\t" + "L_sp_4096_mont_reduce_128_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -25673,9 +25673,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x200\n\t" #ifdef __GNUC__ - "BLT L_sp_4096_mont_reduce_128_word\n\t" + "BLT L_sp_4096_mont_reduce_128_word%=\n\t" #else - "BLT.W L_sp_4096_mont_reduce_128_word\n\t" + "BLT.W L_sp_4096_mont_reduce_128_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -25714,7 +25714,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_word:\n\t" + "L_sp_4096_mont_reduce_128_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -25722,7 +25722,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_mul:\n\t" + "L_sp_4096_mont_reduce_128_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -25765,9 +25765,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r12, r12, #0x4\n\t" "CMP r12, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_mul\n\t" + "BLT L_sp_4096_mont_reduce_128_mul%=\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_mul\n\t" + "BLT.N L_sp_4096_mont_reduce_128_mul%=\n\t" #endif "LDR r10, [%[a], #512]\n\t" "ADDS r4, r4, r3\n\t" @@ -25781,9 +25781,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_word\n\t" + "BLT L_sp_4096_mont_reduce_128_word%=\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_word\n\t" + "BLT.N L_sp_4096_mont_reduce_128_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -25825,7 +25825,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_4096_mont_reduce_128_word:\n\t" + "L_sp_4096_mont_reduce_128_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -26473,9 +26473,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x200\n\t" #ifdef __GNUC__ - "BLT L_sp_4096_mont_reduce_128_word\n\t" + "BLT L_sp_4096_mont_reduce_128_word%=\n\t" #else - "BLT.W L_sp_4096_mont_reduce_128_word\n\t" + "BLT.W L_sp_4096_mont_reduce_128_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -26517,7 +26517,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_word:\n\t" + "L_sp_4096_mont_reduce_128_word%=:\n\t" /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -26525,7 +26525,7 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_mul:\n\t" + "L_sp_4096_mont_reduce_128_mul%=:\n\t" /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -26556,9 +26556,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r12, r12, #0x4\n\t" "CMP r12, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_mul\n\t" + "BLT L_sp_4096_mont_reduce_128_mul%=\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_mul\n\t" + "BLT.N L_sp_4096_mont_reduce_128_mul%=\n\t" #endif "LDR r10, [%[a], #512]\n\t" "ADDS r4, r4, r3\n\t" @@ -26572,9 +26572,9 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x200\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_word\n\t" + "BLT L_sp_4096_mont_reduce_128_word%=\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_word\n\t" + "BLT.N L_sp_4096_mont_reduce_128_word%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -26640,7 +26640,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x200\n\t" "\n" - "L_sp_4096_sub_128_word:\n\t" + "L_sp_4096_sub_128_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -26652,9 +26652,9 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_sub_128_word\n\t" + "BNE L_sp_4096_sub_128_word%=\n\t" #else - "BNE.N L_sp_4096_sub_128_word\n\t" + "BNE.N L_sp_4096_sub_128_word%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -27019,7 +27019,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_4096_word_128_bit:\n\t" + "L_div_4096_word_128_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -27029,7 +27029,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_4096_word_128_bit\n\t" + "bpl L_div_4096_word_128_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -27184,7 +27184,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x1fc\n\t" "\n" - "L_sp_4096_cmp_128_words:\n\t" + "L_sp_4096_cmp_128_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -27197,7 +27197,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_4096_cmp_128_words\n\t" + "bcs L_sp_4096_cmp_128_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #508]\n\t" @@ -29164,7 +29164,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_cond_add_64_words:\n\t" + "L_sp_4096_cond_add_64_words%=:\n\t" "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -29175,9 +29175,9 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "ADD r4, r4, #0x4\n\t" "CMP r4, #0x100\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_cond_add_64_words\n\t" + "BLT L_sp_4096_cond_add_64_words%=\n\t" #else - "BLT.N L_sp_4096_cond_add_64_words\n\t" + "BLT.N L_sp_4096_cond_add_64_words%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -30857,13 +30857,13 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_256_mul_8_outer:\n\t" + "L_sp_256_mul_8_outer%=:\n\t" "SUBS r3, r5, #0x1c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_256_mul_8_inner:\n\t" + "L_sp_256_mul_8_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -30880,14 +30880,14 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_mul_8_inner_done\n\t" + "BGT L_sp_256_mul_8_inner_done%=\n\t" #else - "BGT.N L_sp_256_mul_8_inner_done\n\t" + "BGT.N L_sp_256_mul_8_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_mul_8_inner\n\t" + "BLT L_sp_256_mul_8_inner%=\n\t" #else - "BLT.N L_sp_256_mul_8_inner\n\t" + "BLT.N L_sp_256_mul_8_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -30896,7 +30896,7 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_256_mul_8_inner_done:\n\t" + "L_sp_256_mul_8_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -30904,9 +30904,9 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x34\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_256_mul_8_outer\n\t" + "BLE L_sp_256_mul_8_outer%=\n\t" #else - "BLE.N L_sp_256_mul_8_outer\n\t" + "BLE.N L_sp_256_mul_8_outer%=\n\t" #endif "LDR lr, [%[a], #28]\n\t" "LDR r11, [%[b], #28]\n\t" @@ -30915,14 +30915,14 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_256_mul_8_store:\n\t" + "L_sp_256_mul_8_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_mul_8_store\n\t" + "BGT L_sp_256_mul_8_store%=\n\t" #else - "BGT.N L_sp_256_mul_8_store\n\t" + "BGT.N L_sp_256_mul_8_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -31455,13 +31455,13 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_256_sqr_8_outer:\n\t" + "L_sp_256_sqr_8_outer%=:\n\t" "SUBS r3, r5, #0x1c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_256_sqr_8_inner:\n\t" + "L_sp_256_sqr_8_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -31475,14 +31475,14 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_sqr_8_inner_done\n\t" + "BGT L_sp_256_sqr_8_inner_done%=\n\t" #else - "BGT.N L_sp_256_sqr_8_inner_done\n\t" + "BGT.N L_sp_256_sqr_8_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_sqr_8_inner\n\t" + "BLT L_sp_256_sqr_8_inner%=\n\t" #else - "BLT.N L_sp_256_sqr_8_inner\n\t" + "BLT.N L_sp_256_sqr_8_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -31490,7 +31490,7 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_256_sqr_8_inner_done:\n\t" + "L_sp_256_sqr_8_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -31498,9 +31498,9 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x34\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_256_sqr_8_outer\n\t" + "BLE L_sp_256_sqr_8_outer%=\n\t" #else - "BLE.N L_sp_256_sqr_8_outer\n\t" + "BLE.N L_sp_256_sqr_8_outer%=\n\t" #endif "LDR lr, [%[a], #28]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -31508,14 +31508,14 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_256_sqr_8_store:\n\t" + "L_sp_256_sqr_8_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_sqr_8_store\n\t" + "BGT L_sp_256_sqr_8_store%=\n\t" #else - "BGT.N L_sp_256_sqr_8_store\n\t" + "BGT.N L_sp_256_sqr_8_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -31915,7 +31915,7 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x20\n\t" "\n" - "L_sp_256_add_8_word:\n\t" + "L_sp_256_add_8_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -31928,9 +31928,9 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_add_8_word\n\t" + "BNE L_sp_256_add_8_word%=\n\t" #else - "BNE.N L_sp_256_add_8_word\n\t" + "BNE.N L_sp_256_add_8_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -33938,7 +33938,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x1c\n\t" "\n" - "L_sp_256_cmp_8_words:\n\t" + "L_sp_256_cmp_8_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -33951,7 +33951,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_256_cmp_8_words\n\t" + "bcs L_sp_256_cmp_8_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #28]\n\t" @@ -34085,7 +34085,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_256_cond_sub_8_words:\n\t" + "L_sp_256_cond_sub_8_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -34096,9 +34096,9 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "ADD r5, r5, #0x4\n\t" "CMP r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_cond_sub_8_words\n\t" + "BLT L_sp_256_cond_sub_8_words%=\n\t" #else - "BLT.N L_sp_256_cond_sub_8_words\n\t" + "BLT.N L_sp_256_cond_sub_8_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -34199,7 +34199,7 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_256_mont_reduce_8_word:\n\t" + "L_sp_256_mont_reduce_8_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -34270,9 +34270,9 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x20\n\t" #ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_8_word\n\t" + "BLT L_sp_256_mont_reduce_8_word%=\n\t" #else - "BLT.W L_sp_256_mont_reduce_8_word\n\t" + "BLT.W L_sp_256_mont_reduce_8_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -34314,7 +34314,7 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_256_mont_reduce_8_word:\n\t" + "L_sp_256_mont_reduce_8_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -34362,9 +34362,9 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x20\n\t" #ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_8_word\n\t" + "BLT L_sp_256_mont_reduce_8_word%=\n\t" #else - "BLT.W L_sp_256_mont_reduce_8_word\n\t" + "BLT.W L_sp_256_mont_reduce_8_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -34573,7 +34573,7 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_256_mont_reduce_order_8_word:\n\t" + "L_sp_256_mont_reduce_order_8_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -34644,9 +34644,9 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x20\n\t" #ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_order_8_word\n\t" + "BLT L_sp_256_mont_reduce_order_8_word%=\n\t" #else - "BLT.W L_sp_256_mont_reduce_order_8_word\n\t" + "BLT.W L_sp_256_mont_reduce_order_8_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -34688,7 +34688,7 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_256_mont_reduce_order_8_word:\n\t" + "L_sp_256_mont_reduce_order_8_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -34736,9 +34736,9 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x20\n\t" #ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_order_8_word\n\t" + "BLT L_sp_256_mont_reduce_order_8_word%=\n\t" #else - "BLT.W L_sp_256_mont_reduce_order_8_word\n\t" + "BLT.W L_sp_256_mont_reduce_order_8_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -39075,7 +39075,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x20\n\t" "\n" - "L_sp_256_sub_in_pkace_8_word:\n\t" + "L_sp_256_sub_in_pkace_8_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -39087,9 +39087,9 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_sub_in_pkace_8_word\n\t" + "BNE L_sp_256_sub_in_pkace_8_word%=\n\t" #else - "BNE.N L_sp_256_sub_in_pkace_8_word\n\t" + "BNE.N L_sp_256_sub_in_pkace_8_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -39168,7 +39168,7 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_256_mul_d_8_word:\n\t" + "L_sp_256_mul_d_8_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -39182,9 +39182,9 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_mul_d_8_word\n\t" + "BLT L_sp_256_mul_d_8_word%=\n\t" #else - "BLT.N L_sp_256_mul_d_8_word\n\t" + "BLT.N L_sp_256_mul_d_8_word%=\n\t" #endif "STR r3, [%[r], #32]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -39362,7 +39362,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_256_word_8_bit:\n\t" + "L_div_256_word_8_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -39372,7 +39372,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_256_word_8_bit\n\t" + "bpl L_div_256_word_8_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -40066,7 +40066,7 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x20\n\t" "\n" - "L_sp_256_sub_8_word:\n\t" + "L_sp_256_sub_8_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -40078,9 +40078,9 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_sub_8_word\n\t" + "BNE L_sp_256_sub_8_word%=\n\t" #else - "BNE.N L_sp_256_sub_8_word\n\t" + "BNE.N L_sp_256_sub_8_word%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -40200,9 +40200,9 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_div2_mod_8_even\n\t" + "BEQ L_sp_256_div2_mod_8_even%=\n\t" #else - "BEQ.N L_sp_256_div2_mod_8_even\n\t" + "BEQ.N L_sp_256_div2_mod_8_even%=\n\t" #endif "LDM %[a]!, {r5, r6, r7}\n\t" "LDM %[m]!, {r8, r9, r10, r11}\n\t" @@ -40219,16 +40219,16 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) "ADCS r7, r7, r11\n\t" "ADC r3, r12, r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_div2_mod_8_div2\n\t" + "B L_sp_256_div2_mod_8_div2%=\n\t" #else - "B.N L_sp_256_div2_mod_8_div2\n\t" + "B.N L_sp_256_div2_mod_8_div2%=\n\t" #endif "\n" - "L_sp_256_div2_mod_8_even:\n\t" + "L_sp_256_div2_mod_8_even%=:\n\t" "LDRD r4, r5, [%[a], #12]\n\t" "LDRD r6, r7, [%[a], #20]\n\t" "\n" - "L_sp_256_div2_mod_8_div2:\n\t" + "L_sp_256_div2_mod_8_div2%=:\n\t" "LSR r8, r4, #1\n\t" "AND r4, r4, #0x1\n\t" "LSR r9, r5, #1\n\t" @@ -40271,128 +40271,128 @@ static int sp_256_num_bits_8(const sp_digit* a) "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_7\n\t" + "BEQ L_sp_256_num_bits_8_7%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_7\n\t" + "BEQ.N L_sp_256_num_bits_8_7%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_7:\n\t" + "L_sp_256_num_bits_8_7%=:\n\t" "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_6\n\t" + "BEQ L_sp_256_num_bits_8_6%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_6\n\t" + "BEQ.N L_sp_256_num_bits_8_6%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_6:\n\t" + "L_sp_256_num_bits_8_6%=:\n\t" "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_5\n\t" + "BEQ L_sp_256_num_bits_8_5%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_5\n\t" + "BEQ.N L_sp_256_num_bits_8_5%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_5:\n\t" + "L_sp_256_num_bits_8_5%=:\n\t" "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_4\n\t" + "BEQ L_sp_256_num_bits_8_4%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_4\n\t" + "BEQ.N L_sp_256_num_bits_8_4%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_4:\n\t" + "L_sp_256_num_bits_8_4%=:\n\t" "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_3\n\t" + "BEQ L_sp_256_num_bits_8_3%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_3\n\t" + "BEQ.N L_sp_256_num_bits_8_3%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_3:\n\t" + "L_sp_256_num_bits_8_3%=:\n\t" "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_2\n\t" + "BEQ L_sp_256_num_bits_8_2%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_2\n\t" + "BEQ.N L_sp_256_num_bits_8_2%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_2:\n\t" + "L_sp_256_num_bits_8_2%=:\n\t" "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_1\n\t" + "BEQ L_sp_256_num_bits_8_1%=\n\t" #else - "BEQ.N L_sp_256_num_bits_8_1\n\t" + "BEQ.N L_sp_256_num_bits_8_1%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9\n\t" + "B L_sp_256_num_bits_8_9%=\n\t" #else - "B.N L_sp_256_num_bits_8_9\n\t" + "B.N L_sp_256_num_bits_8_9%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_1:\n\t" + "L_sp_256_num_bits_8_1%=:\n\t" "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_256_num_bits_8_9:\n\t" + "L_sp_256_num_bits_8_9%=:\n\t" "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -41515,13 +41515,13 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_384_mul_12_outer:\n\t" + "L_sp_384_mul_12_outer%=:\n\t" "SUBS r3, r5, #0x2c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_384_mul_12_inner:\n\t" + "L_sp_384_mul_12_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -41538,14 +41538,14 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_mul_12_inner_done\n\t" + "BGT L_sp_384_mul_12_inner_done%=\n\t" #else - "BGT.N L_sp_384_mul_12_inner_done\n\t" + "BGT.N L_sp_384_mul_12_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_mul_12_inner\n\t" + "BLT L_sp_384_mul_12_inner%=\n\t" #else - "BLT.N L_sp_384_mul_12_inner\n\t" + "BLT.N L_sp_384_mul_12_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -41554,7 +41554,7 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_384_mul_12_inner_done:\n\t" + "L_sp_384_mul_12_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -41562,9 +41562,9 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x54\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_384_mul_12_outer\n\t" + "BLE L_sp_384_mul_12_outer%=\n\t" #else - "BLE.N L_sp_384_mul_12_outer\n\t" + "BLE.N L_sp_384_mul_12_outer%=\n\t" #endif "LDR lr, [%[a], #44]\n\t" "LDR r11, [%[b], #44]\n\t" @@ -41573,14 +41573,14 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_384_mul_12_store:\n\t" + "L_sp_384_mul_12_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_mul_12_store\n\t" + "BGT L_sp_384_mul_12_store%=\n\t" #else - "BGT.N L_sp_384_mul_12_store\n\t" + "BGT.N L_sp_384_mul_12_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -42643,13 +42643,13 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_384_sqr_12_outer:\n\t" + "L_sp_384_sqr_12_outer%=:\n\t" "SUBS r3, r5, #0x2c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_384_sqr_12_inner:\n\t" + "L_sp_384_sqr_12_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -42663,14 +42663,14 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_sqr_12_inner_done\n\t" + "BGT L_sp_384_sqr_12_inner_done%=\n\t" #else - "BGT.N L_sp_384_sqr_12_inner_done\n\t" + "BGT.N L_sp_384_sqr_12_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_sqr_12_inner\n\t" + "BLT L_sp_384_sqr_12_inner%=\n\t" #else - "BLT.N L_sp_384_sqr_12_inner\n\t" + "BLT.N L_sp_384_sqr_12_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -42678,7 +42678,7 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_384_sqr_12_inner_done:\n\t" + "L_sp_384_sqr_12_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -42686,9 +42686,9 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x54\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_384_sqr_12_outer\n\t" + "BLE L_sp_384_sqr_12_outer%=\n\t" #else - "BLE.N L_sp_384_sqr_12_outer\n\t" + "BLE.N L_sp_384_sqr_12_outer%=\n\t" #endif "LDR lr, [%[a], #44]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -42696,14 +42696,14 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_384_sqr_12_store:\n\t" + "L_sp_384_sqr_12_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_sqr_12_store\n\t" + "BGT L_sp_384_sqr_12_store%=\n\t" #else - "BGT.N L_sp_384_sqr_12_store\n\t" + "BGT.N L_sp_384_sqr_12_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -43436,7 +43436,7 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x30\n\t" "\n" - "L_sp_384_add_12_word:\n\t" + "L_sp_384_add_12_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -43449,9 +43449,9 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_add_12_word\n\t" + "BNE L_sp_384_add_12_word%=\n\t" #else - "BNE.N L_sp_384_add_12_word\n\t" + "BNE.N L_sp_384_add_12_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -43836,7 +43836,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_384_cond_sub_12_words:\n\t" + "L_sp_384_cond_sub_12_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -43847,9 +43847,9 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "ADD r5, r5, #0x4\n\t" "CMP r5, #0x30\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_cond_sub_12_words\n\t" + "BLT L_sp_384_cond_sub_12_words%=\n\t" #else - "BLT.N L_sp_384_cond_sub_12_words\n\t" + "BLT.N L_sp_384_cond_sub_12_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -43963,7 +43963,7 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_384_mont_reduce_12_word:\n\t" + "L_sp_384_mont_reduce_12_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -44066,9 +44066,9 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x30\n\t" #ifdef __GNUC__ - "BLT L_sp_384_mont_reduce_12_word\n\t" + "BLT L_sp_384_mont_reduce_12_word%=\n\t" #else - "BLT.W L_sp_384_mont_reduce_12_word\n\t" + "BLT.W L_sp_384_mont_reduce_12_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -44110,7 +44110,7 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_384_mont_reduce_12_word:\n\t" + "L_sp_384_mont_reduce_12_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -44178,9 +44178,9 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x30\n\t" #ifdef __GNUC__ - "BLT L_sp_384_mont_reduce_12_word\n\t" + "BLT L_sp_384_mont_reduce_12_word%=\n\t" #else - "BLT.W L_sp_384_mont_reduce_12_word\n\t" + "BLT.W L_sp_384_mont_reduce_12_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -44365,7 +44365,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x2c\n\t" "\n" - "L_sp_384_cmp_12_words:\n\t" + "L_sp_384_cmp_12_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -44378,7 +44378,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_384_cmp_12_words\n\t" + "bcs L_sp_384_cmp_12_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #44]\n\t" @@ -44668,7 +44668,7 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x30\n\t" "\n" - "L_sp_384_sub_12_word:\n\t" + "L_sp_384_sub_12_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -44680,9 +44680,9 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_sub_12_word\n\t" + "BNE L_sp_384_sub_12_word%=\n\t" #else - "BNE.N L_sp_384_sub_12_word\n\t" + "BNE.N L_sp_384_sub_12_word%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -44769,7 +44769,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_384_cond_add_12_words:\n\t" + "L_sp_384_cond_add_12_words%=:\n\t" "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -44780,9 +44780,9 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "ADD r4, r4, #0x4\n\t" "CMP r4, #0x30\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_cond_add_12_words\n\t" + "BLT L_sp_384_cond_add_12_words%=\n\t" #else - "BLT.N L_sp_384_cond_add_12_words\n\t" + "BLT.N L_sp_384_cond_add_12_words%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -48974,7 +48974,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x30\n\t" "\n" - "L_sp_384_sub_in_pkace_12_word:\n\t" + "L_sp_384_sub_in_pkace_12_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -48986,9 +48986,9 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_sub_in_pkace_12_word\n\t" + "BNE L_sp_384_sub_in_pkace_12_word%=\n\t" #else - "BNE.N L_sp_384_sub_in_pkace_12_word\n\t" + "BNE.N L_sp_384_sub_in_pkace_12_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -49074,7 +49074,7 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_384_mul_d_12_word:\n\t" + "L_sp_384_mul_d_12_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -49088,9 +49088,9 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x30\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_mul_d_12_word\n\t" + "BLT L_sp_384_mul_d_12_word%=\n\t" #else - "BLT.N L_sp_384_mul_d_12_word\n\t" + "BLT.N L_sp_384_mul_d_12_word%=\n\t" #endif "STR r3, [%[r], #48]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -49288,7 +49288,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_384_word_12_bit:\n\t" + "L_div_384_word_12_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -49298,7 +49298,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_384_word_12_bit\n\t" + "bpl L_div_384_word_12_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -49962,9 +49962,9 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_div2_mod_12_even\n\t" + "BEQ L_sp_384_div2_mod_12_even%=\n\t" #else - "BEQ.N L_sp_384_div2_mod_12_even\n\t" + "BEQ.N L_sp_384_div2_mod_12_even%=\n\t" #endif "MOV r12, #0x0\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" @@ -49990,12 +49990,12 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "STM %[r]!, {r4, r5, r6, r7}\n\t" "ADC r3, r12, r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_div2_mod_12_div2\n\t" + "B L_sp_384_div2_mod_12_div2%=\n\t" #else - "B.N L_sp_384_div2_mod_12_div2\n\t" + "B.N L_sp_384_div2_mod_12_div2%=\n\t" #endif "\n" - "L_sp_384_div2_mod_12_even:\n\t" + "L_sp_384_div2_mod_12_even%=:\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" @@ -50003,7 +50003,7 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4, r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "\n" - "L_sp_384_div2_mod_12_div2:\n\t" + "L_sp_384_div2_mod_12_div2%=:\n\t" "SUB %[r], %[r], #0x30\n\t" "LDRD r8, r9, [%[r]]\n\t" "LSR r8, r8, #1\n\t" @@ -50072,196 +50072,196 @@ static int sp_384_num_bits_12(const sp_digit* a) "LDR r1, [%[a], #44]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_11\n\t" + "BEQ L_sp_384_num_bits_12_11%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_11\n\t" + "BEQ.N L_sp_384_num_bits_12_11%=\n\t" #endif "MOV r2, #0x180\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_11:\n\t" + "L_sp_384_num_bits_12_11%=:\n\t" "LDR r1, [%[a], #40]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_10\n\t" + "BEQ L_sp_384_num_bits_12_10%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_10\n\t" + "BEQ.N L_sp_384_num_bits_12_10%=\n\t" #endif "MOV r2, #0x160\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_10:\n\t" + "L_sp_384_num_bits_12_10%=:\n\t" "LDR r1, [%[a], #36]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_9\n\t" + "BEQ L_sp_384_num_bits_12_9%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_9\n\t" + "BEQ.N L_sp_384_num_bits_12_9%=\n\t" #endif "MOV r2, #0x140\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_9:\n\t" + "L_sp_384_num_bits_12_9%=:\n\t" "LDR r1, [%[a], #32]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_8\n\t" + "BEQ L_sp_384_num_bits_12_8%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_8\n\t" + "BEQ.N L_sp_384_num_bits_12_8%=\n\t" #endif "MOV r2, #0x120\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_8:\n\t" + "L_sp_384_num_bits_12_8%=:\n\t" "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_7\n\t" + "BEQ L_sp_384_num_bits_12_7%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_7\n\t" + "BEQ.N L_sp_384_num_bits_12_7%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_7:\n\t" + "L_sp_384_num_bits_12_7%=:\n\t" "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_6\n\t" + "BEQ L_sp_384_num_bits_12_6%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_6\n\t" + "BEQ.N L_sp_384_num_bits_12_6%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_6:\n\t" + "L_sp_384_num_bits_12_6%=:\n\t" "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_5\n\t" + "BEQ L_sp_384_num_bits_12_5%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_5\n\t" + "BEQ.N L_sp_384_num_bits_12_5%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_5:\n\t" + "L_sp_384_num_bits_12_5%=:\n\t" "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_4\n\t" + "BEQ L_sp_384_num_bits_12_4%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_4\n\t" + "BEQ.N L_sp_384_num_bits_12_4%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_4:\n\t" + "L_sp_384_num_bits_12_4%=:\n\t" "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_3\n\t" + "BEQ L_sp_384_num_bits_12_3%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_3\n\t" + "BEQ.N L_sp_384_num_bits_12_3%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_3:\n\t" + "L_sp_384_num_bits_12_3%=:\n\t" "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_2\n\t" + "BEQ L_sp_384_num_bits_12_2%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_2\n\t" + "BEQ.N L_sp_384_num_bits_12_2%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_2:\n\t" + "L_sp_384_num_bits_12_2%=:\n\t" "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_1\n\t" + "BEQ L_sp_384_num_bits_12_1%=\n\t" #else - "BEQ.N L_sp_384_num_bits_12_1\n\t" + "BEQ.N L_sp_384_num_bits_12_1%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13\n\t" + "B L_sp_384_num_bits_12_13%=\n\t" #else - "B.N L_sp_384_num_bits_12_13\n\t" + "B.N L_sp_384_num_bits_12_13%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_1:\n\t" + "L_sp_384_num_bits_12_1%=:\n\t" "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_384_num_bits_12_13:\n\t" + "L_sp_384_num_bits_12_13%=:\n\t" "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -51430,13 +51430,13 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_521_mul_17_outer:\n\t" + "L_sp_521_mul_17_outer%=:\n\t" "SUBS r3, r5, #0x40\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_521_mul_17_inner:\n\t" + "L_sp_521_mul_17_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -51453,14 +51453,14 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_mul_17_inner_done\n\t" + "BGT L_sp_521_mul_17_inner_done%=\n\t" #else - "BGT.N L_sp_521_mul_17_inner_done\n\t" + "BGT.N L_sp_521_mul_17_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_mul_17_inner\n\t" + "BLT L_sp_521_mul_17_inner%=\n\t" #else - "BLT.N L_sp_521_mul_17_inner\n\t" + "BLT.N L_sp_521_mul_17_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -51469,7 +51469,7 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_521_mul_17_inner_done:\n\t" + "L_sp_521_mul_17_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -51477,9 +51477,9 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x7c\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_521_mul_17_outer\n\t" + "BLE L_sp_521_mul_17_outer%=\n\t" #else - "BLE.N L_sp_521_mul_17_outer\n\t" + "BLE.N L_sp_521_mul_17_outer%=\n\t" #endif "LDR lr, [%[a], #64]\n\t" "LDR r11, [%[b], #64]\n\t" @@ -51491,14 +51491,14 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r6, r7}\n\t" "SUB r5, r5, #0x8\n\t" "\n" - "L_sp_521_mul_17_store:\n\t" + "L_sp_521_mul_17_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_mul_17_store\n\t" + "BGT L_sp_521_mul_17_store%=\n\t" #else - "BGT.N L_sp_521_mul_17_store\n\t" + "BGT.N L_sp_521_mul_17_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -53575,13 +53575,13 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_521_sqr_17_outer:\n\t" + "L_sp_521_sqr_17_outer%=:\n\t" "SUBS r3, r5, #0x40\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_521_sqr_17_inner:\n\t" + "L_sp_521_sqr_17_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -53595,14 +53595,14 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_sqr_17_inner_done\n\t" + "BGT L_sp_521_sqr_17_inner_done%=\n\t" #else - "BGT.N L_sp_521_sqr_17_inner_done\n\t" + "BGT.N L_sp_521_sqr_17_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_sqr_17_inner\n\t" + "BLT L_sp_521_sqr_17_inner%=\n\t" #else - "BLT.N L_sp_521_sqr_17_inner\n\t" + "BLT.N L_sp_521_sqr_17_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -53610,7 +53610,7 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_521_sqr_17_inner_done:\n\t" + "L_sp_521_sqr_17_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -53618,9 +53618,9 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0x7c\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_521_sqr_17_outer\n\t" + "BLE L_sp_521_sqr_17_outer%=\n\t" #else - "BLE.N L_sp_521_sqr_17_outer\n\t" + "BLE.N L_sp_521_sqr_17_outer%=\n\t" #endif "LDR lr, [%[a], #64]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -53631,14 +53631,14 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "STM %[r]!, {r6, r7}\n\t" "SUB r5, r5, #0x8\n\t" "\n" - "L_sp_521_sqr_17_store:\n\t" + "L_sp_521_sqr_17_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_sqr_17_store\n\t" + "BGT L_sp_521_sqr_17_store%=\n\t" #else - "BGT.N L_sp_521_sqr_17_store\n\t" + "BGT.N L_sp_521_sqr_17_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -54955,7 +54955,7 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x40\n\t" "\n" - "L_sp_521_add_17_word:\n\t" + "L_sp_521_add_17_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -54968,9 +54968,9 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_add_17_word\n\t" + "BNE L_sp_521_add_17_word%=\n\t" #else - "BNE.N L_sp_521_add_17_word\n\t" + "BNE.N L_sp_521_add_17_word%=\n\t" #endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a], {r4}\n\t" @@ -55288,7 +55288,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_521_cond_sub_17_words:\n\t" + "L_sp_521_cond_sub_17_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -55299,9 +55299,9 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "ADD r5, r5, #0x4\n\t" "CMP r5, #0x44\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_cond_sub_17_words\n\t" + "BLT L_sp_521_cond_sub_17_words%=\n\t" #else - "BLT.N L_sp_521_cond_sub_17_words\n\t" + "BLT.N L_sp_521_cond_sub_17_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -55568,19 +55568,19 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_521_mont_reduce_order_17_word:\n\t" + "L_sp_521_mont_reduce_order_17_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" "CMP r11, #0x40\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_mont_reduce_order_17_nomask\n\t" + "BNE L_sp_521_mont_reduce_order_17_nomask%=\n\t" #else - "BNE.N L_sp_521_mont_reduce_order_17_nomask\n\t" + "BNE.N L_sp_521_mont_reduce_order_17_nomask%=\n\t" #endif "MOV r9, #0x1ff\n\t" "AND r10, r10, r9\n\t" "\n" - "L_sp_521_mont_reduce_order_17_nomask:\n\t" + "L_sp_521_mont_reduce_order_17_nomask%=:\n\t" /* a[i+0] += m[0] * mu */ "MOV r7, #0x0\n\t" "UMLAL r4, r7, r10, lr\n\t" @@ -55722,9 +55722,9 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x44\n\t" #ifdef __GNUC__ - "BLT L_sp_521_mont_reduce_order_17_word\n\t" + "BLT L_sp_521_mont_reduce_order_17_word%=\n\t" #else - "BLT.W L_sp_521_mont_reduce_order_17_word\n\t" + "BLT.W L_sp_521_mont_reduce_order_17_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -55836,19 +55836,19 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_521_mont_reduce_order_17_word:\n\t" + "L_sp_521_mont_reduce_order_17_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" "CMP r4, #0x40\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_mont_reduce_order_17_nomask\n\t" + "BNE L_sp_521_mont_reduce_order_17_nomask%=\n\t" #else - "BNE.N L_sp_521_mont_reduce_order_17_nomask\n\t" + "BNE.N L_sp_521_mont_reduce_order_17_nomask%=\n\t" #endif "MOV r12, #0x1ff\n\t" "AND lr, lr, r12\n\t" "\n" - "L_sp_521_mont_reduce_order_17_nomask:\n\t" + "L_sp_521_mont_reduce_order_17_nomask%=:\n\t" /* a[i+0] += m[0] * mu */ "LDR r12, [%[m]]\n\t" "MOV r3, #0x0\n\t" @@ -55940,9 +55940,9 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x44\n\t" #ifdef __GNUC__ - "BLT L_sp_521_mont_reduce_order_17_word\n\t" + "BLT L_sp_521_mont_reduce_order_17_word%=\n\t" #else - "BLT.W L_sp_521_mont_reduce_order_17_word\n\t" + "BLT.W L_sp_521_mont_reduce_order_17_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -56194,7 +56194,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x40\n\t" "\n" - "L_sp_521_cmp_17_words:\n\t" + "L_sp_521_cmp_17_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -56207,7 +56207,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_521_cmp_17_words\n\t" + "bcs L_sp_521_cmp_17_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #64]\n\t" @@ -61995,7 +61995,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x40\n\t" "\n" - "L_sp_521_sub_in_pkace_17_word:\n\t" + "L_sp_521_sub_in_pkace_17_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -62007,9 +62007,9 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_sub_in_pkace_17_word\n\t" + "BNE L_sp_521_sub_in_pkace_17_word%=\n\t" #else - "BNE.N L_sp_521_sub_in_pkace_17_word\n\t" + "BNE.N L_sp_521_sub_in_pkace_17_word%=\n\t" #endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2}\n\t" @@ -62111,7 +62111,7 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_521_mul_d_17_word:\n\t" + "L_sp_521_mul_d_17_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -62125,9 +62125,9 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x44\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_mul_d_17_word\n\t" + "BLT L_sp_521_mul_d_17_word%=\n\t" #else - "BLT.N L_sp_521_mul_d_17_word\n\t" + "BLT.N L_sp_521_mul_d_17_word%=\n\t" #endif "STR r3, [%[r], #68]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -62350,7 +62350,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_521_word_17_bit:\n\t" + "L_div_521_word_17_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -62360,7 +62360,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_521_word_17_bit\n\t" + "bpl L_div_521_word_17_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -63055,7 +63055,7 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x40\n\t" "\n" - "L_sp_521_sub_17_word:\n\t" + "L_sp_521_sub_17_word%=:\n\t" "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -63067,9 +63067,9 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_sub_17_word\n\t" + "BNE L_sp_521_sub_17_word%=\n\t" #else - "BNE.N L_sp_521_sub_17_word\n\t" + "BNE.N L_sp_521_sub_17_word%=\n\t" #endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3}\n\t" @@ -63167,9 +63167,9 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_div2_mod_17_even\n\t" + "BEQ L_sp_521_div2_mod_17_even%=\n\t" #else - "BEQ.N L_sp_521_div2_mod_17_even\n\t" + "BEQ.N L_sp_521_div2_mod_17_even%=\n\t" #endif "MOV r12, #0x0\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" @@ -63206,12 +63206,12 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "STM %[r]!, {r4}\n\t" "ADC r3, r12, r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_div2_mod_17_div2\n\t" + "B L_sp_521_div2_mod_17_div2%=\n\t" #else - "B.N L_sp_521_div2_mod_17_div2\n\t" + "B.N L_sp_521_div2_mod_17_div2%=\n\t" #endif "\n" - "L_sp_521_div2_mod_17_even:\n\t" + "L_sp_521_div2_mod_17_even%=:\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" @@ -63223,7 +63223,7 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4}\n\t" "STM %[r]!, {r4}\n\t" "\n" - "L_sp_521_div2_mod_17_div2:\n\t" + "L_sp_521_div2_mod_17_div2%=:\n\t" "SUB %[r], %[r], #0x44\n\t" "LDRD r8, r9, [%[r]]\n\t" "LSR r8, r8, #1\n\t" @@ -63312,281 +63312,281 @@ static int sp_521_num_bits_17(const sp_digit* a) "LDR r1, [%[a], #64]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_16\n\t" + "BEQ L_sp_521_num_bits_17_16%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_16\n\t" + "BEQ.N L_sp_521_num_bits_17_16%=\n\t" #endif "MOV r2, #0x220\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_16:\n\t" + "L_sp_521_num_bits_17_16%=:\n\t" "LDR r1, [%[a], #60]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_15\n\t" + "BEQ L_sp_521_num_bits_17_15%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_15\n\t" + "BEQ.N L_sp_521_num_bits_17_15%=\n\t" #endif "MOV r2, #0x200\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_15:\n\t" + "L_sp_521_num_bits_17_15%=:\n\t" "LDR r1, [%[a], #56]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_14\n\t" + "BEQ L_sp_521_num_bits_17_14%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_14\n\t" + "BEQ.N L_sp_521_num_bits_17_14%=\n\t" #endif "MOV r2, #0x1e0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_14:\n\t" + "L_sp_521_num_bits_17_14%=:\n\t" "LDR r1, [%[a], #52]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_13\n\t" + "BEQ L_sp_521_num_bits_17_13%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_13\n\t" + "BEQ.N L_sp_521_num_bits_17_13%=\n\t" #endif "MOV r2, #0x1c0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_13:\n\t" + "L_sp_521_num_bits_17_13%=:\n\t" "LDR r1, [%[a], #48]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_12\n\t" + "BEQ L_sp_521_num_bits_17_12%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_12\n\t" + "BEQ.N L_sp_521_num_bits_17_12%=\n\t" #endif "MOV r2, #0x1a0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_12:\n\t" + "L_sp_521_num_bits_17_12%=:\n\t" "LDR r1, [%[a], #44]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_11\n\t" + "BEQ L_sp_521_num_bits_17_11%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_11\n\t" + "BEQ.N L_sp_521_num_bits_17_11%=\n\t" #endif "MOV r2, #0x180\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_11:\n\t" + "L_sp_521_num_bits_17_11%=:\n\t" "LDR r1, [%[a], #40]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_10\n\t" + "BEQ L_sp_521_num_bits_17_10%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_10\n\t" + "BEQ.N L_sp_521_num_bits_17_10%=\n\t" #endif "MOV r2, #0x160\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_10:\n\t" + "L_sp_521_num_bits_17_10%=:\n\t" "LDR r1, [%[a], #36]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_9\n\t" + "BEQ L_sp_521_num_bits_17_9%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_9\n\t" + "BEQ.N L_sp_521_num_bits_17_9%=\n\t" #endif "MOV r2, #0x140\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_9:\n\t" + "L_sp_521_num_bits_17_9%=:\n\t" "LDR r1, [%[a], #32]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_8\n\t" + "BEQ L_sp_521_num_bits_17_8%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_8\n\t" + "BEQ.N L_sp_521_num_bits_17_8%=\n\t" #endif "MOV r2, #0x120\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_8:\n\t" + "L_sp_521_num_bits_17_8%=:\n\t" "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_7\n\t" + "BEQ L_sp_521_num_bits_17_7%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_7\n\t" + "BEQ.N L_sp_521_num_bits_17_7%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_7:\n\t" + "L_sp_521_num_bits_17_7%=:\n\t" "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_6\n\t" + "BEQ L_sp_521_num_bits_17_6%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_6\n\t" + "BEQ.N L_sp_521_num_bits_17_6%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_6:\n\t" + "L_sp_521_num_bits_17_6%=:\n\t" "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_5\n\t" + "BEQ L_sp_521_num_bits_17_5%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_5\n\t" + "BEQ.N L_sp_521_num_bits_17_5%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_5:\n\t" + "L_sp_521_num_bits_17_5%=:\n\t" "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_4\n\t" + "BEQ L_sp_521_num_bits_17_4%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_4\n\t" + "BEQ.N L_sp_521_num_bits_17_4%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_4:\n\t" + "L_sp_521_num_bits_17_4%=:\n\t" "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_3\n\t" + "BEQ L_sp_521_num_bits_17_3%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_3\n\t" + "BEQ.N L_sp_521_num_bits_17_3%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_3:\n\t" + "L_sp_521_num_bits_17_3%=:\n\t" "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_2\n\t" + "BEQ L_sp_521_num_bits_17_2%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_2\n\t" + "BEQ.N L_sp_521_num_bits_17_2%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_2:\n\t" + "L_sp_521_num_bits_17_2%=:\n\t" "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_1\n\t" + "BEQ L_sp_521_num_bits_17_1%=\n\t" #else - "BEQ.N L_sp_521_num_bits_17_1\n\t" + "BEQ.N L_sp_521_num_bits_17_1%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18\n\t" + "B L_sp_521_num_bits_17_18%=\n\t" #else - "B.N L_sp_521_num_bits_17_18\n\t" + "B.N L_sp_521_num_bits_17_18%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_1:\n\t" + "L_sp_521_num_bits_17_1%=:\n\t" "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_521_num_bits_17_18:\n\t" + "L_sp_521_num_bits_17_18%=:\n\t" "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -67981,13 +67981,13 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_1024_mul_32_outer:\n\t" + "L_sp_1024_mul_32_outer%=:\n\t" "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_1024_mul_32_inner:\n\t" + "L_sp_1024_mul_32_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -68004,14 +68004,14 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_mul_32_inner_done\n\t" + "BGT L_sp_1024_mul_32_inner_done%=\n\t" #else - "BGT.N L_sp_1024_mul_32_inner_done\n\t" + "BGT.N L_sp_1024_mul_32_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_mul_32_inner\n\t" + "BLT L_sp_1024_mul_32_inner%=\n\t" #else - "BLT.N L_sp_1024_mul_32_inner\n\t" + "BLT.N L_sp_1024_mul_32_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -68020,7 +68020,7 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_1024_mul_32_inner_done:\n\t" + "L_sp_1024_mul_32_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -68028,9 +68028,9 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_1024_mul_32_outer\n\t" + "BLE L_sp_1024_mul_32_outer%=\n\t" #else - "BLE.N L_sp_1024_mul_32_outer\n\t" + "BLE.N L_sp_1024_mul_32_outer%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "LDR r11, [%[b], #124]\n\t" @@ -68039,14 +68039,14 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_1024_mul_32_store:\n\t" + "L_sp_1024_mul_32_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_mul_32_store\n\t" + "BGT L_sp_1024_mul_32_store%=\n\t" #else - "BGT.N L_sp_1024_mul_32_store\n\t" + "BGT.N L_sp_1024_mul_32_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -68079,13 +68079,13 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_1024_sqr_32_outer:\n\t" + "L_sp_1024_sqr_32_outer%=:\n\t" "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_1024_sqr_32_inner:\n\t" + "L_sp_1024_sqr_32_inner%=:\n\t" "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -68099,14 +68099,14 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_sqr_32_inner_done\n\t" + "BGT L_sp_1024_sqr_32_inner_done%=\n\t" #else - "BGT.N L_sp_1024_sqr_32_inner_done\n\t" + "BGT.N L_sp_1024_sqr_32_inner_done%=\n\t" #endif #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_sqr_32_inner\n\t" + "BLT L_sp_1024_sqr_32_inner%=\n\t" #else - "BLT.N L_sp_1024_sqr_32_inner\n\t" + "BLT.N L_sp_1024_sqr_32_inner%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -68114,7 +68114,7 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_1024_sqr_32_inner_done:\n\t" + "L_sp_1024_sqr_32_inner_done%=:\n\t" "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" @@ -68122,9 +68122,9 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_1024_sqr_32_outer\n\t" + "BLE L_sp_1024_sqr_32_outer%=\n\t" #else - "BLE.N L_sp_1024_sqr_32_outer\n\t" + "BLE.N L_sp_1024_sqr_32_outer%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -68132,14 +68132,14 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_1024_sqr_32_store:\n\t" + "L_sp_1024_sqr_32_store%=:\n\t" "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_sqr_32_store\n\t" + "BGT L_sp_1024_sqr_32_store%=\n\t" #else - "BGT.N L_sp_1024_sqr_32_store\n\t" + "BGT.N L_sp_1024_sqr_32_store%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -68254,7 +68254,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x80\n\t" "\n" - "L_sp_1024_sub_in_pkace_32_word:\n\t" + "L_sp_1024_sub_in_pkace_32_word%=:\n\t" "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -68266,9 +68266,9 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_1024_sub_in_pkace_32_word\n\t" + "BNE L_sp_1024_sub_in_pkace_32_word%=\n\t" #else - "BNE.N L_sp_1024_sub_in_pkace_32_word\n\t" + "BNE.N L_sp_1024_sub_in_pkace_32_word%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -68306,7 +68306,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_1024_cond_sub_32_words:\n\t" + "L_sp_1024_cond_sub_32_words%=:\n\t" "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -68317,9 +68317,9 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "ADD r5, r5, #0x4\n\t" "CMP r5, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_cond_sub_32_words\n\t" + "BLT L_sp_1024_cond_sub_32_words%=\n\t" #else - "BLT.N L_sp_1024_cond_sub_32_words\n\t" + "BLT.N L_sp_1024_cond_sub_32_words%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -68497,7 +68497,7 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x80\n\t" "\n" - "L_sp_1024_add_32_word:\n\t" + "L_sp_1024_add_32_word%=:\n\t" "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -68510,9 +68510,9 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_1024_add_32_word\n\t" + "BNE L_sp_1024_add_32_word%=\n\t" #else - "BNE.N L_sp_1024_add_32_word\n\t" + "BNE.N L_sp_1024_add_32_word%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -68551,7 +68551,7 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_1024_mul_d_32_word:\n\t" + "L_sp_1024_mul_d_32_word%=:\n\t" /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -68565,9 +68565,9 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "ADD r9, r9, #0x4\n\t" "CMP r9, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_mul_d_32_word\n\t" + "BLT L_sp_1024_mul_d_32_word%=\n\t" #else - "BLT.N L_sp_1024_mul_d_32_word\n\t" + "BLT.N L_sp_1024_mul_d_32_word%=\n\t" #endif "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -68865,7 +68865,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_1024_word_32_bit:\n\t" + "L_div_1024_word_32_bit%=:\n\t" "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -68875,7 +68875,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_1024_word_32_bit\n\t" + "bpl L_div_1024_word_32_bit%=\n\t" "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -68957,7 +68957,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x7c\n\t" "\n" - "L_sp_1024_cmp_32_words:\n\t" + "L_sp_1024_cmp_32_words%=:\n\t" "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -68970,7 +68970,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_1024_cmp_32_words\n\t" + "bcs L_sp_1024_cmp_32_words%=\n\t" "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #124]\n\t" @@ -69690,7 +69690,7 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_1024_mont_reduce_32_word:\n\t" + "L_sp_1024_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -69953,9 +69953,9 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x80\n\t" #ifdef __GNUC__ - "BLT L_sp_1024_mont_reduce_32_word\n\t" + "BLT L_sp_1024_mont_reduce_32_word%=\n\t" #else - "BLT.W L_sp_1024_mont_reduce_32_word\n\t" + "BLT.W L_sp_1024_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -70002,7 +70002,7 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_1024_mont_reduce_32_word:\n\t" + "L_sp_1024_mont_reduce_32_word%=:\n\t" /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -70170,9 +70170,9 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x80\n\t" #ifdef __GNUC__ - "BLT L_sp_1024_mont_reduce_32_word\n\t" + "BLT L_sp_1024_mont_reduce_32_word%=\n\t" #else - "BLT.W L_sp_1024_mont_reduce_32_word\n\t" + "BLT.W L_sp_1024_mont_reduce_32_word%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -71187,7 +71187,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_1024_cond_add_32_words:\n\t" + "L_sp_1024_cond_add_32_words%=:\n\t" "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -71198,9 +71198,9 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "ADD r4, r4, #0x4\n\t" "CMP r4, #0x80\n\t" #if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_cond_add_32_words\n\t" + "BLT L_sp_1024_cond_add_32_words%=\n\t" #else - "BLT.N L_sp_1024_cond_add_32_words\n\t" + "BLT.N L_sp_1024_cond_add_32_words%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) diff --git a/src/wolfcrypt/src/sp_int.c b/src/wolfcrypt/src/sp_int.c index 83a1306..3a6884a 100644 --- a/src/wolfcrypt/src/sp_int.c +++ b/src/wolfcrypt/src/sp_int.c @@ -8097,6 +8097,27 @@ int sp_submod_ct(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) } #endif /* WOLFSSL_SP_MATH_ALL && HAVE_ECC */ +#if defined(WOLFSSL_SP_MATH_ALL) && defined(HAVE_ECC) && \ + defined(WOLFSSL_ECC_BLIND_K) +void sp_xor_ct(const sp_int* a, const sp_int* b, int len, sp_int* r) +{ + if ((a != NULL) && (b != NULL) && (r != NULL)) { + unsigned int i; + + r->used = (len * 8 + SP_WORD_SIZE - 1) / SP_WORD_SIZE; + for (i = 0; i < r->used; i++) { + r->dp[i] = a->dp[i] ^ b->dp[i]; + } + i = (len * 8) % SP_WORD_SIZE; + if (i > 0) { + r->dp[r->used - 1] &= ((sp_int_digit)1 << i) - 1; + } + /* Remove leading zeros. */ + sp_clamp_ct(r); + } +} +#endif + /******************** * Shifting functoins ********************/ diff --git a/src/wolfcrypt/src/sphincs.c b/src/wolfcrypt/src/sphincs.c index a0196ce..05ba27f 100644 --- a/src/wolfcrypt/src/sphincs.c +++ b/src/wolfcrypt/src/sphincs.c @@ -431,7 +431,8 @@ static int parse_private_key(const byte* priv, word32 privSz, /* At this point, it is still a PKCS8 private key. */ if ((ret = ToTraditionalInline(priv, &idx, privSz)) < 0) { - return ret; + /* ignore error, did not have PKCS8 header */ + (void)ret; } /* Now it is a octet_string(concat(priv,pub)) */ @@ -952,7 +953,7 @@ int wc_Sphincs_PublicKeyToDer(sphincs_key* key, byte* output, word32 inLen, word32 pubKeyLen = (word32)sizeof(pubKey); int keytype = 0; - if (key == NULL || output == NULL) { + if (key == NULL) { return BAD_FUNC_ARG; } diff --git a/src/wolfcrypt/src/srp.c b/src/wolfcrypt/src/srp.c index e32c353..b914f58 100644 --- a/src/wolfcrypt/src/srp.c +++ b/src/wolfcrypt/src/srp.c @@ -908,27 +908,27 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, if (digest) XFREE(digest, srp->heap, DYNAMIC_TYPE_SRP); if (u) { - if (r != MP_INIT_E) + if (r != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(u); XFREE(u, srp->heap, DYNAMIC_TYPE_SRP); } if (s) { - if (r != MP_INIT_E) + if (r != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(s); XFREE(s, srp->heap, DYNAMIC_TYPE_SRP); } if (temp1) { - if (r != MP_INIT_E) + if (r != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(temp1); XFREE(temp1, srp->heap, DYNAMIC_TYPE_SRP); } if (temp2) { - if (r != MP_INIT_E) + if (r != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(temp2); XFREE(temp2, srp->heap, DYNAMIC_TYPE_SRP); } #else - if (r != MP_INIT_E) { + if (r != WC_NO_ERR_TRACE(MP_INIT_E)) { mp_clear(u); mp_clear(s); mp_clear(temp1); diff --git a/src/wolfcrypt/src/wc_encrypt.c b/src/wolfcrypt/src/wc_encrypt.c index 506ac11..3b6d87d 100644 --- a/src/wolfcrypt/src/wc_encrypt.c +++ b/src/wolfcrypt/src/wc_encrypt.c @@ -244,7 +244,7 @@ int wc_Des3_CbcDecryptWithKey(byte* out, const byte* in, word32 sz, int wc_BufferKeyDecrypt(EncryptedInfo* info, byte* der, word32 derSz, const byte* password, int passwordSz, int hashType) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SMALL_STACK byte* key = NULL; #else @@ -318,7 +318,7 @@ int wc_BufferKeyDecrypt(EncryptedInfo* info, byte* der, word32 derSz, int wc_BufferKeyEncrypt(EncryptedInfo* info, byte* der, word32 derSz, const byte* password, int passwordSz, int hashType) { - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifdef WOLFSSL_SMALL_STACK byte* key = NULL; #else @@ -545,9 +545,15 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, ret = wc_PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz, iterations, (int)derivedLen, typeH, 1); + if (ret < 0) + break; if (id != PBE_SHA1_RC4_128) { - ret += wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, + i = ret; + ret = wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz, iterations, 8, typeH, 2); + if (ret < 0) + break; + ret += i; } break; } @@ -658,15 +664,21 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, AES_ENCRYPTION); } else { + #ifdef HAVE_AES_DECRYPT ret = wc_AesSetKey(aes, key, derivedLen, cbcIv, AES_DECRYPTION); + #else + ret = NOT_COMPILED_IN; + #endif } } if (ret == 0) { if (enc) ret = wc_AesCbcEncrypt(aes, input, input, (word32)length); + #ifdef HAVE_AES_DECRYPT else ret = wc_AesCbcDecrypt(aes, input, input, (word32)length); + #endif } if (free_aes) wc_AesFree(aes); diff --git a/src/wolfcrypt/src/wc_kyber.c b/src/wolfcrypt/src/wc_kyber.c index b0b358f..ffa37d8 100644 --- a/src/wolfcrypt/src/wc_kyber.c +++ b/src/wolfcrypt/src/wc_kyber.c @@ -59,6 +59,11 @@ /******************************************************************************/ +/* Declare variable to make compiler not optimize code in kyber_from_msg(). */ +volatile sword16 kyber_opt_blocker = 0; + +/******************************************************************************/ + /** * Initialize the Kyber key. * @@ -203,7 +208,7 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, byte* pubSeed = buf; byte* noiseSeed = buf + KYBER_SYM_SZ; sword16* a = NULL; - sword16* e; + sword16* e = NULL; int ret = 0; int kp = 0; @@ -364,12 +369,12 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, unsigned char* ct) { int ret = 0; - sword16* sp; - sword16* ep; - sword16* k; - sword16* epp; - unsigned int kp; - unsigned int compVecSz; + sword16* sp = NULL; + sword16* ep = NULL; + sword16* k = NULL; + sword16* epp = NULL; + unsigned int kp = 0; + unsigned int compVecSz = 0; #ifndef USE_INTEL_SPEEDUP sword16* at = NULL; #else @@ -528,7 +533,9 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, byte msg[2 * KYBER_SYM_SZ]; byte kr[2 * KYBER_SYM_SZ + 1]; int ret = 0; - unsigned int ctSz; +#ifndef WOLFSSL_ML_KEM + unsigned int ctSz = 0; +#endif /* Validate parameters. */ if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rand == NULL)) { @@ -538,6 +545,7 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, ret = BUFFER_E; } +#ifndef WOLFSSL_ML_KEM if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { @@ -562,6 +570,7 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, break; } } +#endif /* If public hash (h) is not stored against key, calculate it. */ if ((ret == 0) && ((key->flags & KYBER_FLAG_H_SET) == 0)) { @@ -591,8 +600,12 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, } if (ret == 0) { +#ifndef WOLFSSL_ML_KEM /* Hash random to anonymize as seed data. */ ret = KYBER_HASH_H(rand, KYBER_SYM_SZ, msg); +#else + XMEMCPY(msg, rand, KYBER_SYM_SZ); +#endif } if (ret == 0) { /* Copy the hash of the public key into msg. */ @@ -607,6 +620,7 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, ct); } +#ifndef WOLFSSL_ML_KEM if (ret == 0) { /* Hash the cipher text after the seed. */ ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); @@ -615,6 +629,11 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, /* Derive the secret from the seed and hash of cipher text. */ ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); } +#else + if (ret == 0) { + XMEMCPY(ss, kr, KYBER_SS_SZ); + } +#endif return ret; } @@ -636,7 +655,7 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, int ret = 0; sword16* v; sword16* mp; - unsigned int kp; + unsigned int kp = 0; unsigned int compVecSz; #ifndef USE_INTEL_SPEEDUP sword16* bp = NULL; @@ -720,6 +739,39 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, return ret; } +#ifdef WOLFSSL_ML_KEM +/* Derive the secret from z and cipher text. + * + * @param [in] z Implicit rejection value. + * @param [in] ct Cipher text. + * @param [in] ctSz Length of cipher text in bytes. + * @param [out] ss Shared secret. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation failed. + * @return Other negative when a hash error occurred. + */ +static int kyber_derive_secret(const byte* z, const byte* ct, word32 ctSz, + byte* ss) +{ + int ret; + wc_Shake shake; + + ret = wc_InitShake256(&shake, NULL, INVALID_DEVID); + if (ret == 0) { + ret = wc_Shake256_Update(&shake, z, KYBER_SYM_SZ); + if (ret == 0) { + ret = wc_Shake256_Update(&shake, ct, ctSz); + } + if (ret == 0) { + ret = wc_Shake256_Final(&shake, ss, KYBER_SS_SZ); + } + wc_Shake256_Free(&shake); + } + + return ret; +} +#endif + /** * Decapsulate the cipher text to calculate the shared secret. * @@ -741,9 +793,9 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, byte msg[2 * KYBER_SYM_SZ]; byte kr[2 * KYBER_SYM_SZ + 1]; int ret = 0; - unsigned int ctSz; - unsigned int i; - int fail; + unsigned int ctSz = 0; + unsigned int i = 0; + int fail = 0; #ifndef USE_INTEL_SPEEDUP byte* cmp = NULL; #else @@ -813,6 +865,7 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, /* Compare generated cipher text with that passed in. */ fail = kyber_cmp(ct, cmp, ctSz); +#ifndef WOLFSSL_ML_KEM /* Hash the cipher text after the seed. */ ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); } @@ -824,6 +877,15 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, /* Derive the secret from the seed and hash of cipher text. */ ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); +#else + ret = kyber_derive_secret(key->z, ct, ctSz, msg); + } + if (ret == 0) { + /* Change seed to z on comparison failure. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + ss[i] = kr[i] ^ ((kr[i] ^ msg[i]) & fail); + } +#endif } #ifndef USE_INTEL_SPEEDUP @@ -849,13 +911,14 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, * @return NOT_COMPILED_IN when key type is not supported. * @return BUFFER_E when len is not the correct size. */ -int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, word32 len) +int wc_KyberKey_DecodePrivateKey(KyberKey* key, const unsigned char* in, + word32 len) { int ret = 0; word32 privLen = 0; word32 pubLen = 0; unsigned int k = 0; - unsigned char* p = in; + const unsigned char* p = in; /* Validate parameters. */ if ((key == NULL) || (in == NULL)) { @@ -933,12 +996,13 @@ int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, word32 len) * @return NOT_COMPILED_IN when key type is not supported. * @return BUFFER_E when len is not the correct size. */ -int wc_KyberKey_DecodePublicKey(KyberKey* key, unsigned char* in, word32 len) +int wc_KyberKey_DecodePublicKey(KyberKey* key, const unsigned char* in, + word32 len) { int ret = 0; word32 pubLen = 0; unsigned int k = 0; - unsigned char* p = in; + const unsigned char* p = in; if ((key == NULL) || (in == NULL)) { ret = BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/wc_kyber_poly.c b/src/wolfcrypt/src/wc_kyber_poly.c index fe140f4..aed437c 100644 --- a/src/wolfcrypt/src/wc_kyber_poly.c +++ b/src/wolfcrypt/src/wc_kyber_poly.c @@ -28,12 +28,44 @@ * polynomials. */ +/* Possible Kyber options: + * + * WOLFSSL_WC_KYBER Default: OFF + * Enables this code, wolfSSL implementation, to be built. + * + * WOLFSSL_KYBER512 Default: OFF + * Enables the KYBER512 parameter implementations. + * WOLFSSL_KYBER768 Default: OFF + * Enables the KYBER768 parameter implementations. + * WOLFSSL_KYBER1024 Default: OFF + * Enables the KYBER1024 parameter implementations. + * + * USE_INTEL_SPEEDUP Default: OFF + * Compiles in Intel x64 specific implementations that are faster. + * WOLFSSL_KYBER_NO_LARGE_CODE Default: OFF + * Compiles smaller, fast code size with a speed trade-off. + * WOLFSSL_KYBER_SMALL Default: OFF + * Compiles to small code size with a speed trade-off. + * WOLFSSL_SMALL_STACK Default: OFF + * Use less stack by dynamically allocating local variables. + * + * WOLFSSL_KYBER_NTT_UNROLL Defualt: OFF + * Enable an alternative NTT implementation that may be faster on some + * platforms and is smaller in code size. + * WOLFSSL_KYBER_INVNTT_UNROLL Default: OFF + * Enables an alternative inverse NTT implementation that may be faster on + * some platforms and is smaller in code size. + */ + #include #include #include #ifdef WOLFSSL_WC_KYBER +/* Declared in wc_kyber.c to stop compiler optimizer from simplifying. */ +extern volatile sword16 kyber_opt_blocker; + #ifdef USE_INTEL_SPEEDUP static word32 cpuid_flags = 0; #endif @@ -50,7 +82,7 @@ static word32 cpuid_flags = 0; /* Used in Barrett Reduction: * r = a mod q * => r = a - ((V * a) >> 26) * q), as V based on 2^26 - * V is the mulitplier that gets the quotient after shifting. + * V is the multiplier that gets the quotient after shifting. */ #define KYBER_V (((1U << 26) + (KYBER_Q / 2)) / KYBER_Q) @@ -161,7 +193,7 @@ static void kyber_ntt(sword16* r) for (j = 0; j < KYBER_N; ++j) { r[j] = KYBER_BARRETT_RED(r[j]); } -#else +#elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) unsigned int len; unsigned int k = 1; unsigned int j; @@ -192,6 +224,256 @@ static void kyber_ntt(sword16* r) for (j = 0; j < KYBER_N; ++j) { r[j] = KYBER_BARRETT_RED(r[j]); } +#elif defined(WOLFSSL_KYBER_NTT_UNROLL) + unsigned int k = 1; + unsigned int j; + unsigned int start; + sword16 zeta = zetas[k++]; + + for (j = 0; j < KYBER_N / 2; ++j) { + sword32 p = (sword32)zeta * r[j + KYBER_N / 2]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[j]; + r[j + KYBER_N / 2] = rj - t; + r[j] = rj + t; + } + for (start = 0; start < KYBER_N; start += 2 * 64) { + zeta = zetas[k++]; + for (j = 0; j < 64; ++j) { + sword32 p = (sword32)zeta * r[start + j + 64]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 64] = rj - t; + r[start + j] = rj + t; + } + } + for (start = 0; start < KYBER_N; start += 2 * 32) { + zeta = zetas[k++]; + for (j = 0; j < 32; ++j) { + sword32 p = (sword32)zeta * r[start + j + 32]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 32] = rj - t; + r[start + j] = rj + t; + } + } + for (start = 0; start < KYBER_N; start += 2 * 16) { + zeta = zetas[k++]; + for (j = 0; j < 16; ++j) { + sword32 p = (sword32)zeta * r[start + j + 16]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 16] = rj - t; + r[start + j] = rj + t; + } + } + for (start = 0; start < KYBER_N; start += 2 * 8) { + zeta = zetas[k++]; + for (j = 0; j < 8; ++j) { + sword32 p = (sword32)zeta * r[start + j + 8]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 8] = rj - t; + r[start + j] = rj + t; + } + } + for (start = 0; start < KYBER_N; start += 2 * 4) { + zeta = zetas[k++]; + for (j = 0; j < 4; ++j) { + sword32 p = (sword32)zeta * r[start + j + 4]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 4] = rj - t; + r[start + j] = rj + t; + } + } + for (start = 0; start < KYBER_N; start += 2 * 2) { + zeta = zetas[k++]; + for (j = 0; j < 2; ++j) { + sword32 p = (sword32)zeta * r[start + j + 2]; + sword16 t = KYBER_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 2] = rj - t; + r[start + j] = rj + t; + } + } + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < KYBER_N; ++j) { + r[j] = KYBER_BARRETT_RED(r[j]); + } +#else + unsigned int j; + sword16 t0; + sword16 t1; + sword16 t2; + sword16 t3; + + sword16 zeta128 = zetas[1]; + sword16 zeta64_0 = zetas[2]; + sword16 zeta64_1 = zetas[3]; + for (j = 0; j < KYBER_N / 8; j++) { + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 32]; + sword16 r2 = r[j + 64]; + sword16 r3 = r[j + 96]; + sword16 r4 = r[j + 128]; + sword16 r5 = r[j + 160]; + sword16 r6 = r[j + 192]; + sword16 r7 = r[j + 224]; + + t0 = KYBER_MONT_RED((sword32)zeta128 * r4); + t1 = KYBER_MONT_RED((sword32)zeta128 * r5); + t2 = KYBER_MONT_RED((sword32)zeta128 * r6); + t3 = KYBER_MONT_RED((sword32)zeta128 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = KYBER_MONT_RED((sword32)zeta64_0 * r2); + t1 = KYBER_MONT_RED((sword32)zeta64_0 * r3); + t2 = KYBER_MONT_RED((sword32)zeta64_1 * r6); + t3 = KYBER_MONT_RED((sword32)zeta64_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } + + for (j = 0; j < KYBER_N; j += 64) { + int i; + sword16 zeta32 = zetas[ 4 + j / 64 + 0]; + sword16 zeta16_0 = zetas[ 8 + j / 32 + 0]; + sword16 zeta16_1 = zetas[ 8 + j / 32 + 1]; + sword16 zeta8_0 = zetas[16 + j / 16 + 0]; + sword16 zeta8_1 = zetas[16 + j / 16 + 1]; + sword16 zeta8_2 = zetas[16 + j / 16 + 2]; + sword16 zeta8_3 = zetas[16 + j / 16 + 3]; + for (i = 0; i < 8; i++) { + sword16 r0 = r[j + i + 0]; + sword16 r1 = r[j + i + 8]; + sword16 r2 = r[j + i + 16]; + sword16 r3 = r[j + i + 24]; + sword16 r4 = r[j + i + 32]; + sword16 r5 = r[j + i + 40]; + sword16 r6 = r[j + i + 48]; + sword16 r7 = r[j + i + 56]; + + t0 = KYBER_MONT_RED((sword32)zeta32 * r4); + t1 = KYBER_MONT_RED((sword32)zeta32 * r5); + t2 = KYBER_MONT_RED((sword32)zeta32 * r6); + t3 = KYBER_MONT_RED((sword32)zeta32 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = KYBER_MONT_RED((sword32)zeta16_0 * r2); + t1 = KYBER_MONT_RED((sword32)zeta16_0 * r3); + t2 = KYBER_MONT_RED((sword32)zeta16_1 * r6); + t3 = KYBER_MONT_RED((sword32)zeta16_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = KYBER_MONT_RED((sword32)zeta8_0 * r1); + t1 = KYBER_MONT_RED((sword32)zeta8_1 * r3); + t2 = KYBER_MONT_RED((sword32)zeta8_2 * r5); + t3 = KYBER_MONT_RED((sword32)zeta8_3 * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + for (j = 0; j < KYBER_N; j += 8) { + sword16 zeta4 = zetas[32 + j / 8 + 0]; + sword16 zeta2_0 = zetas[64 + j / 4 + 0]; + sword16 zeta2_1 = zetas[64 + j / 4 + 1]; + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 1]; + sword16 r2 = r[j + 2]; + sword16 r3 = r[j + 3]; + sword16 r4 = r[j + 4]; + sword16 r5 = r[j + 5]; + sword16 r6 = r[j + 6]; + sword16 r7 = r[j + 7]; + + t0 = KYBER_MONT_RED((sword32)zeta4 * r4); + t1 = KYBER_MONT_RED((sword32)zeta4 * r5); + t2 = KYBER_MONT_RED((sword32)zeta4 * r6); + t3 = KYBER_MONT_RED((sword32)zeta4 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = KYBER_MONT_RED((sword32)zeta2_0 * r2); + t1 = KYBER_MONT_RED((sword32)zeta2_0 * r3); + t2 = KYBER_MONT_RED((sword32)zeta2_1 * r6); + t3 = KYBER_MONT_RED((sword32)zeta2_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = KYBER_BARRETT_RED(r0); + r[j + 1] = KYBER_BARRETT_RED(r1); + r[j + 2] = KYBER_BARRETT_RED(r2); + r[j + 3] = KYBER_BARRETT_RED(r3); + r[j + 4] = KYBER_BARRETT_RED(r4); + r[j + 5] = KYBER_BARRETT_RED(r5); + r[j + 6] = KYBER_BARRETT_RED(r6); + r[j + 7] = KYBER_BARRETT_RED(r7); + } #endif } @@ -230,7 +512,49 @@ static void kyber_invntt(sword16* r) sword32 p = (sword32)zeta * r[j]; r[j] = KYBER_MONT_RED(p); } -#else +#elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) + unsigned int len; + unsigned int k; + unsigned int j; + sword16 zeta; + sword16 zeta2; + + k = 0; + for (len = 2; len <= KYBER_N / 4; len <<= 1) { + unsigned int start; + for (start = 0; start < KYBER_N; start = j + len) { + zeta = zetas_inv[k++]; + for (j = start; j < start + len; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + len]; + sword16 t = rj + rjl; + r[j] = KYBER_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j + len] = KYBER_MONT_RED(p); + } + } + } + + zeta = zetas_inv[126]; + zeta2 = zetas_inv[127]; + for (j = 0; j < KYBER_N / 2; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + KYBER_N / 2]; + sword16 t = rj + rjl; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j] = t; + r[j + KYBER_N / 2] = KYBER_MONT_RED(p); + + p = (sword32)zeta2 * r[j]; + r[j] = KYBER_MONT_RED(p); + p = (sword32)zeta2 * r[j + KYBER_N / 2]; + r[j + KYBER_N / 2] = KYBER_MONT_RED(p); + } +#elif defined(WOLFSSL_KYBER_INVNTT_UNROLL) unsigned int k; unsigned int j; unsigned int start; @@ -335,6 +659,230 @@ static void kyber_invntt(sword16* r) p = (sword32)zeta2 * r[j + KYBER_N / 2]; r[j + KYBER_N / 2] = KYBER_MONT_RED(p); } +#else + unsigned int j; + sword16 t0; + sword16 t1; + sword16 t2; + sword16 t3; + sword16 zeta64_0; + sword16 zeta64_1; + sword16 zeta128; + sword16 zeta256; + sword32 p; + + for (j = 0; j < KYBER_N; j += 8) { + sword16 zeta2_0 = zetas_inv[ 0 + j / 4 + 0]; + sword16 zeta2_1 = zetas_inv[ 0 + j / 4 + 1]; + sword16 zeta4 = zetas_inv[64 + j / 8 + 0]; + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 1]; + sword16 r2 = r[j + 2]; + sword16 r3 = r[j + 3]; + sword16 r4 = r[j + 4]; + sword16 r5 = r[j + 5]; + sword16 r6 = r[j + 6]; + sword16 r7 = r[j + 7]; + + p = (sword32)zeta2_0 * (sword16)(r0 - r2); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta2_0 * (sword16)(r1 - r3); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta2_1 * (sword16)(r4 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta2_1 * (sword16)(r5 - r7); + t3 = KYBER_MONT_RED(p); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta4 * (sword16)(r0 - r4); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r1 - r5); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r2 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r3 - r7); + t3 = KYBER_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + 0] = r0; + r[j + 1] = r1; + r[j + 2] = r2; + r[j + 3] = r3; + r[j + 4] = r4; + r[j + 5] = r5; + r[j + 6] = r6; + r[j + 7] = r7; + } + + for (j = 0; j < KYBER_N; j += 64) { + int i; + sword16 zeta8_0 = zetas_inv[ 96 + j / 16 + 0]; + sword16 zeta8_1 = zetas_inv[ 96 + j / 16 + 1]; + sword16 zeta8_2 = zetas_inv[ 96 + j / 16 + 2]; + sword16 zeta8_3 = zetas_inv[ 96 + j / 16 + 3]; + sword16 zeta16_0 = zetas_inv[112 + j / 32 + 0]; + sword16 zeta16_1 = zetas_inv[112 + j / 32 + 1]; + sword16 zeta32 = zetas_inv[120 + j / 64 + 0]; + for (i = 0; i < 8; i++) { + sword16 r0 = r[j + i + 0]; + sword16 r1 = r[j + i + 8]; + sword16 r2 = r[j + i + 16]; + sword16 r3 = r[j + i + 24]; + sword16 r4 = r[j + i + 32]; + sword16 r5 = r[j + i + 40]; + sword16 r6 = r[j + i + 48]; + sword16 r7 = r[j + i + 56]; + + p = (sword32)zeta8_0 * (sword16)(r0 - r1); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta8_1 * (sword16)(r2 - r3); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta8_2 * (sword16)(r4 - r5); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta8_3 * (sword16)(r6 - r7); + t3 = KYBER_MONT_RED(p); + r0 = KYBER_BARRETT_RED(r0 + r1); + r2 = KYBER_BARRETT_RED(r2 + r3); + r4 = KYBER_BARRETT_RED(r4 + r5); + r6 = KYBER_BARRETT_RED(r6 + r7); + r1 = t0; + r3 = t1; + r5 = t2; + r7 = t3; + + p = (sword32)zeta16_0 * (sword16)(r0 - r2); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta16_0 * (sword16)(r1 - r3); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta16_1 * (sword16)(r4 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta16_1 * (sword16)(r5 - r7); + t3 = KYBER_MONT_RED(p); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta32 * (sword16)(r0 - r4); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r1 - r5); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r2 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r3 - r7); + t3 = KYBER_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + zeta64_0 = zetas_inv[124]; + zeta64_1 = zetas_inv[125]; + zeta128 = zetas_inv[126]; + zeta256 = zetas_inv[127]; + for (j = 0; j < KYBER_N / 8; j++) { + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 32]; + sword16 r2 = r[j + 64]; + sword16 r3 = r[j + 96]; + sword16 r4 = r[j + 128]; + sword16 r5 = r[j + 160]; + sword16 r6 = r[j + 192]; + sword16 r7 = r[j + 224]; + + p = (sword32)zeta64_0 * (sword16)(r0 - r2); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta64_0 * (sword16)(r1 - r3); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta64_1 * (sword16)(r4 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta64_1 * (sword16)(r5 - r7); + t3 = KYBER_MONT_RED(p); + r0 = KYBER_BARRETT_RED(r0 + r2); + r1 = KYBER_BARRETT_RED(r1 + r3); + r4 = KYBER_BARRETT_RED(r4 + r6); + r5 = KYBER_BARRETT_RED(r5 + r7); + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta128 * (sword16)(r0 - r4); + t0 = KYBER_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r1 - r5); + t1 = KYBER_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r2 - r6); + t2 = KYBER_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r3 - r7); + t3 = KYBER_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta256 * r0; + r0 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r1; + r1 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r2; + r2 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r3; + r3 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r4; + r4 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r5; + r5 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r6; + r6 = KYBER_MONT_RED(p); + p = (sword32)zeta256 * r7; + r7 = KYBER_MONT_RED(p); + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } #endif } @@ -387,13 +935,24 @@ static void kyber_basemul_mont(sword16* r, const sword16* a, const sword16* b) kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); } -#else +#elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) for (i = 0; i < KYBER_N; i += 8, zeta += 2) { kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); kyber_basemul(r + i + 4, a + i + 4, b + i + 4, zeta[1]); kyber_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); } +#else + for (i = 0; i < KYBER_N; i += 16, zeta += 4) { + kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + kyber_basemul(r + i + 4, a + i + 4, b + i + 4, zeta[1]); + kyber_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); + kyber_basemul(r + i + 8, a + i + 8, b + i + 8, zeta[2]); + kyber_basemul(r + i + 10, a + i + 10, b + i + 10, -zeta[2]); + kyber_basemul(r + i + 12, a + i + 12, b + i + 12, zeta[3]); + kyber_basemul(r + i + 14, a + i + 14, b + i + 14, -zeta[3]); + } #endif } @@ -422,7 +981,7 @@ static void kyber_basemul_mont_add(sword16* r, const sword16* a, r[i + 2] += t2[0]; r[i + 3] += t2[1]; } -#else +#elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) for (i = 0; i < KYBER_N; i += 8, zeta += 2) { sword16 t0[2]; sword16 t2[2]; @@ -443,6 +1002,43 @@ static void kyber_basemul_mont_add(sword16* r, const sword16* a, r[i + 6] += t6[0]; r[i + 7] += t6[1]; } +#else + for (i = 0; i < KYBER_N; i += 16, zeta += 4) { + sword16 t0[2]; + sword16 t2[2]; + sword16 t4[2]; + sword16 t6[2]; + sword16 t8[2]; + sword16 t10[2]; + sword16 t12[2]; + sword16 t14[2]; + + kyber_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + kyber_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + kyber_basemul(t4, a + i + 4, b + i + 4, zeta[1]); + kyber_basemul(t6, a + i + 6, b + i + 6, -zeta[1]); + kyber_basemul(t8, a + i + 8, b + i + 8, zeta[2]); + kyber_basemul(t10, a + i + 10, b + i + 10, -zeta[2]); + kyber_basemul(t12, a + i + 12, b + i + 12, zeta[3]); + kyber_basemul(t14, a + i + 14, b + i + 14, -zeta[3]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + r[i + 4] += t4[0]; + r[i + 5] += t4[1]; + r[i + 6] += t6[0]; + r[i + 7] += t6[1]; + r[i + 8] += t8[0]; + r[i + 9] += t8[1]; + r[i + 10] += t10[0]; + r[i + 11] += t10[1]; + r[i + 12] += t12[0]; + r[i + 13] += t12[1]; + r[i + 14] += t14[0]; + r[i + 15] += t14[1]; + } #endif } @@ -1460,6 +2056,8 @@ static void kyber_cbd_eta3(sword16* p, const byte* r) { unsigned int i; +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_KYBER_NO_LARGE_CODE) || \ + defined(BIG_ENDIAN_ORDER) #ifndef WORD64_AVAILABLE /* Calculate four integer coefficients at a time. */ for (i = 0; i < KYBER_N; i += 4) { @@ -1533,7 +2131,59 @@ static void kyber_cbd_eta3(sword16* p, const byte* r) /* Move over used bytes. */ r += 6; } -#endif +#endif /* WORD64_AVAILABLE */ +#else + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < KYBER_N; i += 16) { + const word32* r32 = (const word32*)r; + /* Take the next 12 bytes, little endian, as 24 bit values. */ + word32 t0 = r32[0] & 0xffffff; + word32 t1 = ((r32[0] >> 24) | (r32[1] << 8)) & 0xffffff; + word32 t2 = ((r32[1] >> 16) | (r32[2] << 16)) & 0xffffff; + word32 t3 = r32[2] >> 8 ; + word32 d0; + word32 d1; + word32 d2; + word32 d3; + + /* Add second and third bits to first. */ + d0 = (t0 >> 0) & 0x00249249; + d0 += (t0 >> 1) & 0x00249249; + d0 += (t0 >> 2) & 0x00249249; + d1 = (t1 >> 0) & 0x00249249; + d1 += (t1 >> 1) & 0x00249249; + d1 += (t1 >> 2) & 0x00249249; + d2 = (t2 >> 0) & 0x00249249; + d2 += (t2 >> 1) & 0x00249249; + d2 += (t2 >> 2) & 0x00249249; + d3 = (t3 >> 0) & 0x00249249; + d3 += (t3 >> 1) & 0x00249249; + d3 += (t3 >> 2) & 0x00249249; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + p[i + 0] = ETA3_SUB(d0, 0); + p[i + 1] = ETA3_SUB(d0, 1); + p[i + 2] = ETA3_SUB(d0, 2); + p[i + 3] = ETA3_SUB(d0, 3); + p[i + 4] = ETA3_SUB(d1, 0); + p[i + 5] = ETA3_SUB(d1, 1); + p[i + 6] = ETA3_SUB(d1, 2); + p[i + 7] = ETA3_SUB(d1, 3); + p[i + 8] = ETA3_SUB(d2, 0); + p[i + 9] = ETA3_SUB(d2, 1); + p[i + 10] = ETA3_SUB(d2, 2); + p[i + 11] = ETA3_SUB(d2, 3); + p[i + 12] = ETA3_SUB(d3, 0); + p[i + 13] = ETA3_SUB(d3, 1); + p[i + 14] = ETA3_SUB(d3, 2); + p[i + 15] = ETA3_SUB(d3, 3); + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 12; + } +#endif /* WOLFSSL_SMALL_STACK || WOLFSSL_KYBER_NO_LARGE_CODE || BIG_ENDIAN_ORDER */ } #endif @@ -2069,9 +2719,6 @@ static void kyber_vec_compress_10_c(byte* r, sword16* v, unsigned int kp) { unsigned int i; unsigned int j; -#ifdef WOLFSSL_KYBER_SMALL - unsigned int k; -#endif for (i = 0; i < kp; i++) { /* Reduce each coefficient to mod q. */ @@ -2081,9 +2728,12 @@ static void kyber_vec_compress_10_c(byte* r, sword16* v, unsigned int kp) /* Each polynomial. */ for (i = 0; i < kp; i++) { +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_KYBER_NO_LARGE_CODE) || \ + defined(BIG_ENDIAN_ORDER) /* Each 4 polynomial coefficients. */ for (j = 0; j < KYBER_N; j += 4) { #ifdef WOLFSSL_KYBER_SMALL + unsigned int k; sword16 t[4]; /* Compress four polynomial values to 10 bits each. */ for (k = 0; k < 4; k++) { @@ -2114,6 +2764,44 @@ static void kyber_vec_compress_10_c(byte* r, sword16* v, unsigned int kp) /* Move over set bytes. */ r += 5; } +#else + /* Each 16 polynomial coefficients. */ + for (j = 0; j < KYBER_N; j += 16) { + /* Compress four polynomial values to 10 bits each. */ + sword16 t0 = TO_COMP_WORD_10(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_10(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_10(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_10(v, i, j, 3); + sword16 t4 = TO_COMP_WORD_10(v, i, j, 4); + sword16 t5 = TO_COMP_WORD_10(v, i, j, 5); + sword16 t6 = TO_COMP_WORD_10(v, i, j, 6); + sword16 t7 = TO_COMP_WORD_10(v, i, j, 7); + sword16 t8 = TO_COMP_WORD_10(v, i, j, 8); + sword16 t9 = TO_COMP_WORD_10(v, i, j, 9); + sword16 t10 = TO_COMP_WORD_10(v, i, j, 10); + sword16 t11 = TO_COMP_WORD_10(v, i, j, 11); + sword16 t12 = TO_COMP_WORD_10(v, i, j, 12); + sword16 t13 = TO_COMP_WORD_10(v, i, j, 13); + sword16 t14 = TO_COMP_WORD_10(v, i, j, 14); + sword16 t15 = TO_COMP_WORD_10(v, i, j, 15); + + word32* r32 = (word32*)r; + /* Pack sixteen 10-bit values into byte array. */ + r32[0] = t0 | ((word32)t1 << 10) | ((word32)t2 << 20) | + ((word32)t3 << 30); + r32[1] = (t3 >> 2) | ((word32)t4 << 8) | ((word32)t5 << 18) | + ((word32)t6 << 28); + r32[2] = (t6 >> 4) | ((word32)t7 << 6) | ((word32)t8 << 16) | + ((word32)t9 << 26); + r32[3] = (t9 >> 6) | ((word32)t10 << 4) | ((word32)t11 << 14) | + ((word32)t12 << 24); + r32[4] = (t12 >> 8) | ((word32)t13 << 2) | ((word32)t14 << 12) | + ((word32)t15 << 22); + + /* Move over set bytes. */ + r += 20; + } +#endif } } @@ -2773,6 +3461,8 @@ void kyber_decompress_5(sword16* p, const unsigned char* b) /* Convert bit from byte to 0 or (KYBER_Q + 1) / 2. * * Constant time implementation. + * XOR in kyber_opt_blocker to ensure optimizer doesn't know what will be ANDed + * with KYBER_Q_1_HALF and can't optimize to non-constant time code. * * @param [out] p Polynomial to hold converted value. * @param [in] msg Message to get bit from byte from. @@ -2780,7 +3470,8 @@ void kyber_decompress_5(sword16* p, const unsigned char* b) * @param [in] j Index of bit in byte. */ #define FROM_MSG_BIT(p, msg, i, j) \ - p[8 * (i) + (j)] = ((sword16)0 - (sword16)(((msg)[i] >> (j)) & 1)) & KYBER_Q_1_HALF + ((p)[8 * (i) + (j)] = (((sword16)0 - (sword16)(((msg)[i] >> (j)) & 1)) ^ \ + kyber_opt_blocker) & KYBER_Q_1_HALF) /* Convert message to polynomial. * diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index cdc732f..0ef0b59 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -19,8 +19,1127 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#ifdef HAVE_CONFIG_H + #include +#endif + #include +#include +#include + +#if defined(WOLFSSL_HAVE_LMS) && defined(WOLFSSL_WC_LMS) +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + + +/* Calculate u. Appendix B. Works for w of 1, 2, 4, or 8. + * + * @param [in] w Winternitz width. + */ +#define LMS_U(w) \ + (8 * WC_SHA256_DIGEST_SIZE / (w)) +/* Calculate u. Appendix B. Works for w of 1, 2, 4, or 8. + * + * @param [in] w Winternitz width. + * @param [in] wb Winternitz width length in bits. + */ +#define LMS_V(w, wb) \ + (2 + (8 - (wb)) / (w)) +/* Calculate ls. Appendix B. Works for w of 1, 2, 4, or 8. + * + * @param [in] w Winternitz width. + * @param [in] wb Winternitz width length in bits. + */ +#define LMS_LS(w, wb) \ + (16 - LMS_V(w, wb) * (w)) +/* Calculate p. Appendix B. Works for w of 1, 2, 4, or 8. + * + * @param [in] w Winternitz width. + * @param [in] wb Winternitz width length in bits. + */ +#define LMS_P(w, wb) \ + (LMS_U(w) + LMS_V(w, wb)) +/* Calculate signature length. + * + * @param [in] l Number of levels. + * @param [in] h Height of the trees. + * @param [in] p Number of n-byte string elements in signature for a tree. + */ +#define LMS_PARAMS_SIG_LEN(l, h, p) \ + (4 + (l) * (4 + 4 + 4 + WC_SHA256_DIGEST_SIZE * (1 + (p) + (h))) + \ + ((l) - 1) * LMS_PUBKEY_LEN) + +#ifndef WOLFSSL_WC_LMS_SMALL + /* Root levels and leaf cache bits. */ + #define LMS_PARAMS_CACHE(h) \ + (((h) < LMS_ROOT_LEVELS) ? (h) : LMS_ROOT_LEVELS), \ + (((h) < LMS_CACHE_BITS ) ? (h) : LMS_CACHE_BITS ) +#else + /* Root levels and leaf cache bits aren't in structure. */ + #define LMS_PARAMS_CACHE(h) /* null expansion */ +#endif + +/* Define parameters entry for LMS. + * + * @param [in] l Number of levels. + * @param [in] h Height of the trees. + * @param [in] w Winternitz width. + * @param [in] wb Winternitz width length in bits. + * @param [in] t LMS type. + * @param [in] t2 LM-OTS type. + */ +#define LMS_PARAMS(l, h, w, wb, t, t2) \ + { l, h, w, LMS_LS(w, wb), LMS_P(w, wb), t, t2, \ + LMS_PARAMS_SIG_LEN(l, h, LMS_P(w, wb)), LMS_PARAMS_CACHE(h) } + + +/* Initialize the working state for LMS operations. + * + * @param [in, out] state LMS state. + * @param [in] params LMS parameters. + */ +static int wc_lmskey_state_init(LmsState* state, const LmsParams* params) +{ + int ret; -#ifdef WOLFSSL_HAVE_LMS - #error "Contact wolfSSL to get the implementation of this file" + /* Zero out every field. */ + XMEMSET(state, 0, sizeof(LmsState)); + + /* Keep a reference to the parameters for use in operations. */ + state->params = params; + + /* Initialize the two hash algorithms. */ + ret = wc_InitSha256(&state->hash); + if (ret == 0) { + ret = wc_InitSha256(&state->hash_k); + if (ret != 0) { + wc_Sha256Free(&state->hash); + } + } + + return ret; +} + +/* Free the working state for LMS operations. + * + * @param [in] state LMS state. + */ +static void wc_lmskey_state_free(LmsState* state) +{ + wc_Sha256Free(&state->hash_k); + wc_Sha256Free(&state->hash); +} + +/* Supported LMS parameters. */ +static const wc_LmsParamsMap wc_lms_map[] = { +#if LMS_MAX_HEIGHT >= 15 + { WC_LMS_PARM_NONE , "LMS_NONE" , + LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L1_H15_W2, "LMS/HSS L1_H15_W2", + LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L1_H15_W4, "LMS/HSS L1_H15_W4", + LMS_PARAMS(1, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4) }, +#endif +#if LMS_MAX_LEVELS >= 2 +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_L2_H10_W2, "LMS/HSS L2_H10_W2", + LMS_PARAMS(2, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L2_H10_W4, "LMS/HSS L2_H10_W4", + LMS_PARAMS(2, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L2_H10_W8, "LMS/HSS L2_H10_W8", + LMS_PARAMS(2, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, +#endif +#endif +#if LMS_MAX_LEVELS >= 3 + { WC_LMS_PARM_L3_H5_W2 , "LMS/HSS L3_H5_W2" , + LMS_PARAMS(3, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L3_H5_W4 , "LMS/HSS L3_H5_W4" , + LMS_PARAMS(3, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L3_H5_W8 , "LMS/HSS L3_H5_W8" , + LMS_PARAMS(3, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_L3_H10_W4, "LMS/HSS L3_H10_W4", + LMS_PARAMS(3, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, +#endif +#endif +#if LMS_MAX_LEVELS >= 4 + { WC_LMS_PARM_L4_H5_W8 , "LMS/HSS L4_H5_W8" , + LMS_PARAMS(4, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, +#endif + + /* For when user sets L, H, W explicitly. */ + { WC_LMS_PARM_L1_H5_W1 , "LMS/HSS_L1_H5_W1" , + LMS_PARAMS(1, 5, 1, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W1) }, + { WC_LMS_PARM_L1_H5_W2 , "LMS/HSS_L1_H5_W2" , + LMS_PARAMS(1, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L1_H5_W4 , "LMS/HSS_L1_H5_W4" , + LMS_PARAMS(1, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L1_H5_W8 , "LMS/HSS_L1_H5_W8" , + LMS_PARAMS(1, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_L1_H10_W2 , "LMS/HSS_L1_H10_W2", + LMS_PARAMS(1, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L1_H10_W4 , "LMS/HSS_L1_H10_W4", + LMS_PARAMS(1, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L1_H10_W8 , "LMS/HSS_L1_H10_W8", + LMS_PARAMS(1, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, +#endif +#if LMS_MAX_HEIGHT >= 15 + { WC_LMS_PARM_L1_H15_W8 , "LMS/HSS L1_H15_W8", + LMS_PARAMS(1, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8) }, +#endif +#if LMS_MAX_HEIGHT >= 20 + { WC_LMS_PARM_L1_H20_W2 , "LMS/HSS_L1_H20_W2", + LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L1_H20_W4 , "LMS/HSS_L1_H20_W4", + LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L1_H20_W8 , "LMS/HSS_L1_H20_W8", + LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8) }, +#endif +#if LMS_MAX_LEVELS >= 2 + { WC_LMS_PARM_L2_H5_W2 , "LMS/HSS_L2_H5_W2" , + LMS_PARAMS(2, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L2_H5_W4 , "LMS/HSS_L2_H5_W4" , + LMS_PARAMS(2, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L2_H5_W8 , "LMS/HSS_L2_H5_W8" , + LMS_PARAMS(2, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, +#if LMS_MAX_HEIGHT >= 15 + { WC_LMS_PARM_L2_H15_W2 , "LMS/HSS_L2_H15_W2", + LMS_PARAMS(2, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L2_H15_W4 , "LMS/HSS_L2_H15_W4", + LMS_PARAMS(2, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L2_H15_W8 , "LMS/HSS_L2_H15_W8", + LMS_PARAMS(2, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8) }, +#endif +#if LMS_MAX_HEIGHT >= 20 + { WC_LMS_PARM_L2_H20_W2 , "LMS/HSS_L2_H20_W2", + LMS_PARAMS(2, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L2_H20_W4 , "LMS/HSS_L2_H20_W4", + LMS_PARAMS(2, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L2_H20_W8 , "LMS/HSS_L2_H20_W8", + LMS_PARAMS(2, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8) }, +#endif +#endif +#if LMS_MAX_LEVELS >= 3 +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_L3_H10_W8 , "LMS/HSS L3_H10_W8", + LMS_PARAMS(3, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, #endif +#endif +#if LMS_MAX_LEVELS >= 4 + { WC_LMS_PARM_L4_H5_W2 , "LMS/HSS L4_H5_W2" , + LMS_PARAMS(4, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + { WC_LMS_PARM_L4_H5_W4 , "LMS/HSS L4_H5_W4" , + LMS_PARAMS(4, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_L4_H10_W4 , "LMS/HSS L4_H10_W4", + LMS_PARAMS(4, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + { WC_LMS_PARM_L4_H10_W8 , "LMS/HSS L4_H10_W8", + LMS_PARAMS(4, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, +#endif +#endif +}; +/* Number of parameter sets supported. */ +#define WC_LMS_MAP_LEN ((int)(sizeof(wc_lms_map) / sizeof(*wc_lms_map))) + +/* Initialize LMS key. + * + * Call this before setting the params of an LMS key. + * + * @param [out] key LMS key to initialize. + * @param [in] heap Heap hint. + * @param [in] devId Device identifier. + * Use INVALID_DEVID when not using a device. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL. + */ +int wc_LmsKey_Init(LmsKey* key, void* heap, int devId) +{ + int ret = 0; + + (void)heap; + (void)devId; + + /* Validate parameters. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Zeroize the key data. */ + ForceZero(key, sizeof(LmsKey)); + + #ifndef WOLFSSL_LMS_VERIFY_ONLY + /* Initialize other fields. */ + key->write_private_key = NULL; + key->read_private_key = NULL; + key->context = NULL; + key->heap = heap; + #endif + #ifdef WOLF_CRYPTO_CB + key->devId = devId; + #endif + /* Start in initialized state. */ + key->state = WC_LMS_STATE_INITED; + } + + return ret; +} + +/* Get the string representation of the LMS parameter set. + * + * @param [in] lmsParm LMS parameter set identifier. + * @return String representing LMS parameter set on success. + * @return NULL when parameter set not supported. + */ +const char* wc_LmsKey_ParmToStr(enum wc_LmsParm lmsParm) +{ + const char* str = NULL; + int i; + + /* Search through table for matching numeric identifier. */ + for (i = 0; i < WC_LMS_MAP_LEN; i++) { + if (lmsParm == wc_lms_map[i].id) { + /* Get string corresponding to numeric identifier. */ + str = wc_lms_map[i].str; + break; + } + } + + /* Return the string or NULL. */ + return str; +} + +/* Set the wc_LmsParm of an LMS key. + * + * Use this if you wish to set a key with a predefined parameter set, + * such as WC_LMS_PARM_L2_H10_W8. + * + * Key must be inited before calling this. + * + * @param [in, out] key LMS key to set parameters on. + * @param [in] lmsParm Identifier of parameters. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL. + * @return BAD_FUNC_ARG when parameters not supported. + */ +int wc_LmsKey_SetLmsParm(LmsKey* key, enum wc_LmsParm lmsParm) +{ + int ret = 0; + + /* Validate parameters. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + /* Check state is valid. */ + if ((ret == 0) && (key->state != WC_LMS_STATE_INITED)) { + WOLFSSL_MSG("error: LmsKey needs init"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + int i; + + ret = BAD_FUNC_ARG; + /* Search through table for matching numeric identifier. */ + for (i = 0; i < WC_LMS_MAP_LEN; i++) { + if (lmsParm == wc_lms_map[i].id) { + /* Set the parameters into the key. */ + key->params = &wc_lms_map[i].params; + ret = 0; + break; + } + } + } + + if (ret == 0) { + /* Move the state to params set. + * Key is ready for MakeKey or Reload. */ + key->state = WC_LMS_STATE_PARMSET; + } + + return ret; +} + +/* Set the parameters of an LMS key. + * + * Use this if you wish to set specific parameters not found in the + * wc_LmsParm predefined sets. See comments in lms.h for allowed + * parameters. + * + * Key must be inited before calling this. + * + * @param [in, out] key LMS key to set parameters on. + * @param [in] levels Number of tree levels. + * @param [in] height Height of each tree. + * @param [in] winternitz Width or Winternitz coefficient. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL. + * @return BAD_FUNC_ARG when parameters not supported. + * */ +int wc_LmsKey_SetParameters(LmsKey* key, int levels, int height, + int winternitz) +{ + int ret = 0; + + /* Validate parameters. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + /* Check state is valid. */ + if ((ret == 0) && (key->state != WC_LMS_STATE_INITED)) { + WOLFSSL_MSG("error: LmsKey needs init"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + int i; + + ret = BAD_FUNC_ARG; + /* Search through table for matching levels, height and width. */ + for (i = 0; i < WC_LMS_MAP_LEN; i++) { + if ((levels == wc_lms_map[i].params.levels) && + (height == wc_lms_map[i].params.height) && + (winternitz == wc_lms_map[i].params.width)) { + /* Set the parameters into the key. */ + key->params = &wc_lms_map[i].params; + ret = 0; + break; + } + } + } + + if (ret == 0) { + /* Move the state to params set. + * Key is ready for MakeKey or Reload. */ + key->state = WC_LMS_STATE_PARMSET; + } + + return ret; +} + +/* Get the parameters of an LMS key. + * + * Key must be inited and parameters set before calling this. + * + * @param [in] key LMS key. + * @param [out] levels Number of levels of trees. + * @param [out] height Height of the trees. + * @param [out] winternitz Winternitz width. + * Returns 0 on success. + * */ +int wc_LmsKey_GetParameters(const LmsKey* key, int* levels, int* height, + int* winternitz) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (levels == NULL) || (height == NULL) || + (winternitz == NULL)) { + ret = BAD_FUNC_ARG; + } + + /* Validate the parameters are available. */ + if ((ret == 0) && (key->params == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Set the levels, height and Winternitz width from parameters. */ + *levels = key->params->levels; + *height = key->params->height; + *winternitz = key->params->width; + } + + return ret; +} + +/* Frees the LMS key from memory. + * + * This does not affect the private key saved to non-volatile storage. + * + * @param [in, out] key LMS key to free. + */ +void wc_LmsKey_Free(LmsKey* key) +{ + if (key != NULL) { + #ifndef WOLFSSL_LMS_VERIFY_ONLY + if (key->priv_data != NULL) { + const LmsParams* params = key->params; + + ForceZero(key->priv_data, LMS_PRIV_DATA_LEN(params->levels, + params->height, params->p, params->rootLevels, + params->cacheBits)); + + XFREE(key->priv_data, key->heap, DYNAMIC_TYPE_LMS); + } + #endif + + ForceZero(key, sizeof(LmsKey)); + + key->state = WC_LMS_STATE_FREED; + } +} + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Set the write private key callback to the LMS key structure. + * + * The callback must be able to write/update the private key to + * non-volatile storage. + * + * @param [in, out] key LMS key. + * @param [in] write_cb Callback function that stores private key. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or write_cb is NULL. + * @return BAD_STATE_E when key state is invalid. + */ +int wc_LmsKey_SetWriteCb(LmsKey* key, wc_lms_write_private_key_cb write_cb) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (write_cb == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Changing the write callback of an already working key is forbidden. */ + if ((ret == 0) && (key->state == WC_LMS_STATE_OK)) { + WOLFSSL_MSG("error: wc_LmsKey_SetWriteCb: key in use"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Set the callback into the key. */ + key->write_private_key = write_cb; + } + + return ret; +} + +/* Set the read private key callback to the LMS key structure. + * + * The callback must be able to read the private key from + * non-volatile storage. + * + * @param [in, out] key LMS key. + * @param [in] read_cb Callback function that loads private key. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or read_cb is NULL. + * @return BAD_STATE_E when key state is invalid. + * */ +int wc_LmsKey_SetReadCb(LmsKey* key, wc_lms_read_private_key_cb read_cb) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (read_cb == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Changing the read callback of an already working key is forbidden. */ + if ((ret == 0) && (key->state == WC_LMS_STATE_OK)) { + WOLFSSL_MSG("error: wc_LmsKey_SetReadCb: key in use"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Set the callback into the key. */ + key->read_private_key = read_cb; + } + + return ret; +} + +/* Sets the context to be used by write and read callbacks. + * + * E.g. this could be a filename if the callbacks write/read to file. + * + * @param [in, out] key LMS key. + * @param [in] context Pointer to data for read/write callbacks. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or context is NULL. + * @return BAD_STATE_E when key state is invalid. + * */ +int wc_LmsKey_SetContext(LmsKey* key, void* context) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (context == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Setting context of an already working key is forbidden. */ + if ((ret == 0) && (key->state == WC_LMS_STATE_OK)) { + WOLFSSL_MSG("error: wc_LmsKey_SetContext: key in use"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Set the callback context into the key. */ + key->context = context; + } + + return ret; +} + +/* Make the LMS private/public key pair. The key must have its parameters + * set before calling this. + * + * Write/read callbacks, and context data, must be set prior. + * Key must have parameters set. + * + * @param [in, out] key LMS key. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rng is NULL. + * @return BAD_STATE_E when key is in an invalid state. + * @return BAD_FUNC_ARG when write callback or callback context not set. + * @return BAD_STATE_E when no more signatures can be created. + */ +int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Check state. */ + if ((ret == 0) && (key->state != WC_LMS_STATE_PARMSET)) { + WOLFSSL_MSG("error: LmsKey not ready for generation"); + ret = BAD_STATE_E; + } + /* Check write callback set. */ + if ((ret == 0) && (key->write_private_key == NULL)) { + WOLFSSL_MSG("error: LmsKey write callback is not set"); + ret = BAD_FUNC_ARG; + } + /* Check callback context set. */ + if ((ret == 0) && (key->context == NULL)) { + WOLFSSL_MSG("error: LmsKey context is not set"); + ret = BAD_FUNC_ARG; + } + + if ((ret == 0) && (key->priv_data == NULL)) { + const LmsParams* params = key->params; + + /* Allocate memory for the private key data. */ + key->priv_data = XMALLOC(LMS_PRIV_DATA_LEN(params->levels, + params->height, params->p, params->rootLevels, params->cacheBits), + key->heap, DYNAMIC_TYPE_LMS); + /* Check pointer is valid. */ + if (key->priv_data == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + LmsState* state; + #else + LmsState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for working state. */ + state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize working state for use. */ + ret = wc_lmskey_state_init(state, key->params); + if (ret == 0) { + /* Make the HSS key. */ + ret = wc_hss_make_key(state, rng, key->priv_raw, &key->priv, + key->priv_data, key->pub); + wc_lmskey_state_free(state); + } + ForceZero(state, sizeof(LmsState)); + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + if (ret == 0) { + /* Write private key to storage. */ + int rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, + key->context); + if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { + ret = IO_FAILED_E; + } + } + + /* This should not happen, but check whether signatures can be created. */ + if ((ret == 0) && (wc_LmsKey_SigsLeft(key) == 0)) { + WOLFSSL_MSG("error: generated LMS key signatures exhausted"); + key->state = WC_LMS_STATE_NOSIGS; + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Update state. */ + key->state = WC_LMS_STATE_OK; + } + + return ret; +} + +/* Reload a key that has been prepared with the appropriate params and + * data. Use this if you wish to resume signing with an existing key. + * + * Write/read callbacks, and context data, must be set prior. + * Key must have parameters set. + * + * @param [in, out] key LMS key. + * + * Returns 0 on success. */ +int wc_LmsKey_Reload(LmsKey* key) +{ + int ret = 0; + + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + /* Check state. */ + if ((ret == 0) && (key->state != WC_LMS_STATE_PARMSET)) { + WOLFSSL_MSG("error: LmsKey not ready for reload"); + ret = BAD_STATE_E; + } + /* Check read callback present. */ + if ((ret == 0) && (key->read_private_key == NULL)) { + WOLFSSL_MSG("error: LmsKey read callback is not set"); + ret = BAD_FUNC_ARG; + } + /* Check context for callback set */ + if ((ret == 0) && (key->context == NULL)) { + WOLFSSL_MSG("error: LmsKey context is not set"); + ret = BAD_FUNC_ARG; + } + + if ((ret == 0) && (key->priv_data == NULL)) { + const LmsParams* params = key->params; + + /* Allocate memory for the private key data. */ + key->priv_data = XMALLOC(LMS_PRIV_DATA_LEN(params->levels, + params->height, params->p, params->rootLevels, params->cacheBits), + key->heap, DYNAMIC_TYPE_LMS); + /* Check pointer is valid. */ + if (key->priv_data == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + /* Load private key. */ + int rv = key->read_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, + key->context); + if (rv != WC_LMS_RC_READ_TO_MEMORY) { + ret = IO_FAILED_E; + } + } + + /* Double check the key actually has signatures left. */ + if ((ret == 0) && (wc_LmsKey_SigsLeft(key) == 0)) { + WOLFSSL_MSG("error: reloaded LMS key signatures exhausted"); + key->state = WC_LMS_STATE_NOSIGS; + ret = BAD_STATE_E; + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + LmsState* state; + #else + LmsState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for working state. */ + state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize working state for use. */ + ret = wc_lmskey_state_init(state, key->params); + if (ret == 0) { + /* Reload the key ready for signing. */ + ret = wc_hss_reload_key(state, key->priv_raw, &key->priv, + key->priv_data, NULL); + } + ForceZero(state, sizeof(LmsState)); + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + + if (ret == 0) { + /* Update state. */ + key->state = WC_LMS_STATE_OK; + } + + return ret; +} + +/* Get the private key length based on parameter set of key. + * + * @param [in] key LMS key. + * @param [out] len Length of private key. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL or parameters not set. + */ +int wc_LmsKey_GetPrivLen(const LmsKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL) || (key->params == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return private key length from parameter set. */ + *len = HSS_PRIVATE_KEY_LEN; + } + + return ret; +} + +/* Sign a message. + * + * @param [in, out] key LMS key to sign with. + * @param [out] sig Signature data. Buffer must be big enough to hold + * signature data. + * @param [out] sigSz Length of signature data. + * @param [in] msg Message to sign. + * @param [in] msgSz Length of message in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, sig, sigSz or msg is NULL. + * @return BAD_FUNC_ARG when msgSz is not greater than 0. + */ +int wc_LmsKey_Sign(LmsKey* key, byte* sig, word32* sigSz, const byte* msg, + int msgSz) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (sigSz == NULL) || (msg == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (msgSz <= 0)) { + ret = BAD_FUNC_ARG; + } + /* Check state. */ + if ((ret == 0) && (key->state == WC_LMS_STATE_NOSIGS)) { + WOLFSSL_MSG("error: LMS signatures exhausted"); + ret = BAD_STATE_E; + } + if ((ret == 0) && (key->state != WC_LMS_STATE_OK)) { + /* The key had an error the last time it was used, and we + * can't guarantee its state. */ + WOLFSSL_MSG("error: can't sign, LMS key not in good state"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + LmsState* state; + #else + LmsState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for working state. */ + state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize working state for use. */ + ret = wc_lmskey_state_init(state, key->params); + if (ret == 0) { + /* Sign message. */ + ret = wc_hss_sign(state, key->priv_raw, &key->priv, + key->priv_data, msg, msgSz, sig); + wc_lmskey_state_free(state); + } + ForceZero(state, sizeof(LmsState)); + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + if (ret == 0) { + *sigSz = (word32)key->params->sig_len; + } + if (ret == 0) { + /* Write private key to storage. */ + int rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, + key->context); + if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { + ret = IO_FAILED_E; + } + } + + return ret; +} + +/* Returns whether signatures can be created with key. + * + * @param [in] key LMS key. + * + * @return 1 if there are signatures remaining. + * @return 0 if available signatures are exhausted. + */ +int wc_LmsKey_SigsLeft(LmsKey* key) +{ + int ret = 0; + + /* NULL keys have no signatures remaining. */ + if (key != NULL) { + ret = wc_hss_sigsleft(key->params, key->priv_raw); + } + + return ret; +} + +#endif /* ifndef WOLFSSL_LMS_VERIFY_ONLY*/ + +/* Get the public key length based on parameter set of key. + * + * @param [in] key LMS key. + * @param [out] len Length of public key. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL or parameters not set. + */ +int wc_LmsKey_GetPubLen(const LmsKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters */ + if ((key == NULL) || (len == NULL) || (key->params == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + *len = HSS_PUBLIC_KEY_LEN; + } + + return ret; +} + +/* Export a generated public key and parameter set from one LmsKey + * to another. Use this to prepare a signature verification LmsKey + * that is pub only. + * + * Though the public key is all that is used to verify signatures, + * the parameter set is needed to calculate the signature length + * before hand. + * + * @param [out] keyDst LMS key to copy into. + * @param [in] keySrc LMS key to copy. + * @return 0 on success. + * @return BAD_FUNC_ARG when keyDst or keySrc is NULL. + */ +int wc_LmsKey_ExportPub(LmsKey* keyDst, const LmsKey* keySrc) +{ + int ret = 0; + + if ((keyDst == NULL) || (keySrc == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ForceZero(keyDst, sizeof(LmsKey)); + + keyDst->params = keySrc->params; + XMEMCPY(keyDst->pub, keySrc->pub, sizeof(keySrc->pub)); + + /* Mark this key as verify only, to prevent misuse. */ + keyDst->state = WC_LMS_STATE_VERIFYONLY; + } + + return ret; +} + +/* Exports the raw LMS public key buffer from key to out buffer. + * The out buffer should be large enough to hold the public key, and + * outLen should indicate the size of the buffer. + * + * Call wc_LmsKey_GetPubLen beforehand to determine pubLen. + * + * @param [in] key LMS key. + * @param [out] out Buffer to hold encoded public key. + * @param [in, out] outLen On in, length of out in bytes. + * On out, the length of the public key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, out or outLen is NULL. + * @return BUFFER_E when outLen is too small to hold encoded public key. + */ +int wc_LmsKey_ExportPubRaw(const LmsKey* key, byte* out, word32* outLen) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (out == NULL) || (outLen == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Check size of out is sufficient. */ + if ((ret == 0) && (*outLen < HSS_PUBLIC_KEY_LEN)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Return encoded public key. */ + XMEMCPY(out, key->pub, HSS_PUBLIC_KEY_LEN); + *outLen = HSS_PUBLIC_KEY_LEN; + } + + return ret; +} + +/* Imports a raw public key buffer from in array to LmsKey key. + * + * The LMS parameters must be set first with wc_LmsKey_SetLmsParm or + * wc_LmsKey_SetParameters, and inLen must match the length returned + * by wc_LmsKey_GetPubLen. + * + * Call wc_LmsKey_GetPubLen beforehand to determine pubLen. + * + * @param [in, out] key LMS key to put public key in. + * @param [in] in Buffer holding encoded public key. + * @param [in] inLen Length of encoded public key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return BUFFER_E when inLen does not match public key length by parameters. + */ +int wc_LmsKey_ImportPubRaw(LmsKey* key, const byte* in, word32 inLen) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (inLen != HSS_PUBLIC_KEY_LEN)) { + /* Something inconsistent. Parameters weren't set, or input + * pub key is wrong.*/ + return BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(key->pub, in, inLen); + + key->state = WC_LMS_STATE_VERIFYONLY; + } + + return ret; +} + +/* Given a levels, height, winternitz parameter set, determine + * the signature length. + * + * Call this before wc_LmsKey_Sign so you know the length of + * the required signature buffer. + * + * @param [in] key LMS key. + * @param [out] len Length of a signature in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + */ +int wc_LmsKey_GetSigLen(const LmsKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + *len = key->params->sig_len; + } + + return ret; +} + +/* Verify the signature of the message with public key. + * + * @param [in] key LMS key. + * @param [in] sig Signature to verify. + * @param [in] sigSz Size of signature in bytes. + * @param [in] msg Message to verify. + * @param [in] msgSz Length of the message in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when a key, sig or msg is NULL. + * @return SIG_VERIFY_E when signature did not verify message. + * @return BAD_STATE_E when wrong state for operation. + * @return BUFFER_E when sigSz is invalid for parameters. + */ +int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, + const byte* msg, int msgSz) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (msg == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Check state. */ + if ((ret == 0) && (key->state != WC_LMS_STATE_OK) && + (key->state != WC_LMS_STATE_VERIFYONLY)) { + /* LMS key not ready for verification. Param str must be + * set first, and Reload() called. */ + WOLFSSL_MSG("error: LMS key not ready for verification"); + ret = BAD_STATE_E; + } + /* Check signature length. */ + if ((ret == 0) && (sigSz != key->params->sig_len)) { + ret = BUFFER_E; + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + LmsState* state; + #else + LmsState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for working state. */ + state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize working state for use. */ + ret = wc_lmskey_state_init(state, key->params); + if (ret == 0) { + /* Verify signature of message with public key. */ + ret = wc_hss_verify(state, key->pub, msg, msgSz, sig); + wc_lmskey_state_free(state); + } + ForceZero(state, sizeof(LmsState)); + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + + return ret; +} + +#endif /* WOLFSSL_HAVE_LMS && WOLFSSL_WC_LMS */ diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c index dbd5ed6..3f48420 100644 --- a/src/wolfcrypt/src/wc_lms_impl.c +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -19,8 +19,3074 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#include +/* Implementation based on: + * RFC 8554: Leighton-Micali Hash-Based Signatures + * https://datatracker.ietf.org/doc/html/rfc8554 + * Implementation by Sean Parkinson. + */ + +/* Possible LMS options: + * + * WC_LMS_FULL_HASH Default: OFF + * Performs a full hash instead of assuming internals. + * Enable when using hardware SHA-256. + * WOLFSSL_LMS_VERIFY_ONLY Default: OFF + * Only compiles in verification code. + * WOLFSSL_WC_LMS_SMALL Default: OFF + * Implementation is smaller code size with slow signing. + * Enable when memory is limited. + */ + +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#if defined(WOLFSSL_HAVE_LMS) && defined(WOLFSSL_WC_LMS) + +/* Length of R in bytes. */ +#define LMS_R_LEN 4 +/* Length of D in bytes. */ +#define LMS_D_LEN 2 +/* Length of checksum in bytes. */ +#define LMS_CKSM_LEN 2 + +/* Predefined values used in hashes to make them unique. */ +/* Fixed value for calculating x. */ +#define LMS_D_FIXED 0xff +/* D value when computing public key. */ +#define LMS_D_PBLC 0x8080 +/* D value when computing message. */ +#define LMS_D_MESG 0x8181 +/* D value when computing leaf node. */ +#define LMS_D_LEAF 0x8282 +/* D value when computing interior node. */ +#define LMS_D_INTR 0x8383 +/* D value when computing C, randomizer value. */ +#define LMS_D_C 0xfffd +/* D value when computing child SEED for private key. */ +#define LMS_D_CHILD_SEED 0xfffe +/* D value when computing child I for private key. */ +#define LMS_D_CHILD_I 0xffff + +/* Length of data to hash when computing seed: + * 16 + 4 + 2 + 32 = 54 */ +#define LMS_SEED_HASH_LEN \ + (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + LMS_MAX_NODE_LEN) + +/* Length of data to hash when computing a node: + * 16 + 4 + 2 + 32 + 32 = 86 */ +#define LMS_NODE_HASH_LEN \ + (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + 2 * LMS_MAX_NODE_LEN) + +/* Length of data to hash when computing most results: + * 16 + 4 + 2 + 1 + 32 = 55 */ +#define LMS_HASH_BUFFER_LEN \ + (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_W_LEN + LMS_MAX_NODE_LEN) + +/* Length of data to hash when computing Q: + * 16 + 4 + 2 + 32 = 54 */ +#define LMS_Q_BUFFER_LEN \ + (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_MAX_NODE_LEN) + +/* Length of preliminary data to hash when computing K: + * 16 + 4 + 2 = 22 */ +#define LMS_K_PRE_LEN (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN) + +/* Length of preliminary data to hash when computing message hash: + * 16 + 4 + 2 = 22 */ +#define LMS_MSG_PRE_LEN (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN) + + +#ifdef WC_LMS_DEBUG_PRINT_DATA +/* Print data when dubgging implementation. + * + * @param [in] name String to print before data. + * @param [in] data Array of bytes. + * @param [in] len Length of data in array. + */ +static void print_data(const char* name, const byte* data, int len) +{ + int i; + + fprintf(stderr, "%6s: ", name); + for (i = 0; i < len; i++) { + fprintf(stderr, "%02x", data[i]); + } + fprintf(stderr, "\n"); +} +#endif + +/*************************************** + * Index APIs + **************************************/ + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Zero index. + * + * @param [out] a Byte array. Big-endian encoding. + * @param [in] len Length of array in bytes. + */ +static WC_INLINE void wc_lms_idx_zero(unsigned char* a, int len) +{ + XMEMSET(a, 0, len); +} + +/* Increment big-endian value. + * + * @param [in, out] a Byte array. Big-endian encoding. + * @param [in] len Length of array in bytes. + */ +static WC_INLINE void wc_lms_idx_inc(unsigned char* a, int len) +{ + int i; + + /* Starting at least-significant byte up to most. */ + for (i = len - 1; i >= 0; i--) { + /* Add one/carry to byte. */ + if ((++a[i]) != 0) { + /* No more carry. */ + break; + } + } +} +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + +/*************************************** + * Hash APIs + **************************************/ + +/* Set hash data and length into SHA-256 digest. + * + * @param [in, out] state SHA-256 digest object. + * @param [in] data Data to add to hash. + * @param [in] len Number of bytes in data. Must be less than a block. + */ +#define LMS_SHA256_SET_DATA(sha256, data, len) \ +do { \ + XMEMCPY((sha256)->buffer, (data), (len)); \ + (sha256)->buffLen = (len); \ + (sha256)->loLen = (len); \ +} while (0) + +/* Add hash data and length into SHA-256 digest. + * + * @param [in, out] state SHA-256 digest object. + * @param [in] data Data to add to hash. + * @param [in] len Number of bytes in data. Must be less than a block. + */ +#define LMS_SHA256_ADD_DATA(sha256, data, len) \ +do { \ + XMEMCPY((byte*)(sha256)->buffer + (sha256)->buffLen, (data), (len)); \ + (sha256)->buffLen += (len); \ + (sha256)->loLen += (len); \ +} while (0) + +/* Set the length of 54 bytes in buffer as per SHA-256 final operation. + * + * @param [in, out] buffer Hash data buffer to add length to. + */ +#define LMS_SHA256_SET_LEN_54(buffer) \ +do { \ + (buffer)[54] = 0x80; \ + (buffer)[55] = 0x00; \ + (buffer)[56] = 0x00; \ + (buffer)[57] = 0x00; \ + (buffer)[58] = 0x00; \ + (buffer)[59] = 0x00; \ + (buffer)[60] = 0x00; \ + (buffer)[61] = 0x00; \ + (buffer)[62] = 0x01; \ + (buffer)[63] = 0xb0; \ +} while (0) + +/* Set the length of 55 bytes in buffer as per SHA-256 final operation. + * + * @param [in, out] buffer Hash data buffer to add length to. + */ +#define LMS_SHA256_SET_LEN_55(buffer) \ +do { \ + (buffer)[55] = 0x80; \ + (buffer)[56] = 0x00; \ + (buffer)[57] = 0x00; \ + (buffer)[58] = 0x00; \ + (buffer)[59] = 0x00; \ + (buffer)[60] = 0x00; \ + (buffer)[61] = 0x00; \ + (buffer)[62] = 0x01; \ + (buffer)[63] = 0xb8; \ +} while (0) + +#ifndef WC_LMS_FULL_HASH +/* Hash one full block of data and compute result. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_block(wc_Sha256* sha256, const byte* data, + byte* hash) +{ + /* Hash the block and reset SHA-256 state. */ + return wc_Sha256HashBlock(sha256, data, hash); +} +#endif /* !WC_LMS_FULL_HASH */ + +/* Hash data and compute result. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [in] len Length of data to hash. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash(wc_Sha256* sha256, byte* data, word32 len, + byte* hash) +{ + int ret; + +#ifndef WC_LMS_FULL_HASH + if (len < WC_SHA256_BLOCK_SIZE) { + /* Store data into SHA-256 object's buffer. */ + LMS_SHA256_SET_DATA(sha256, data, len); + ret = wc_Sha256Final(sha256, hash); + } + else if (len < WC_SHA256_BLOCK_SIZE + WC_SHA256_PAD_SIZE) { + ret = wc_Sha256HashBlock(sha256, data, NULL); + if (ret == 0) { + byte* buffer = (byte*)sha256->buffer; + int rem = len - WC_SHA256_BLOCK_SIZE; + + XMEMCPY(buffer, data + WC_SHA256_BLOCK_SIZE, rem); + buffer[rem++] = 0x80; + XMEMSET(buffer + rem, 0, WC_SHA256_BLOCK_SIZE - 2 - rem); + buffer[WC_SHA256_BLOCK_SIZE - 2] = (byte)(len >> 5); + buffer[WC_SHA256_BLOCK_SIZE - 1] = (byte)(len << 3); + ret = wc_Sha256HashBlock(sha256, buffer, hash); + } + } + else { + ret = wc_Sha256Update(sha256, data, len); + if (ret == 0) { + ret = wc_Sha256Final(sha256, hash); + } + } +#else + ret = wc_Sha256Update(sha256, data, len); + if (ret == 0) { + ret = wc_Sha256Final(sha256, hash); + } +#endif /* !WC_LMS_FULL_HASH */ + + return ret; +} + +/* Update hash with first data. + * + * Sets the data directly into SHA-256's buffer if valid. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [in] len Length of data to hash. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_first(wc_Sha256* sha256, const byte* data, + word32 len) +{ + int ret = 0; + +#ifndef WC_LMS_FULL_HASH + if (len < WC_SHA256_BLOCK_SIZE) { + /* Store data into SHA-256 object's buffer. */ + LMS_SHA256_SET_DATA(sha256, data, len); + } + else +#endif /* !WC_LMS_FULL_HASH */ + { + ret = wc_Sha256Update(sha256, data, len); + } + + return ret; +} + +/* Update hash with further data. + * + * Adds the data directly into SHA-256's buffer if valid. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [in] len Length of data to hash. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_update(wc_Sha256* sha256, const byte* data, + word32 len) +{ + int ret = 0; + +#ifndef WC_LMS_FULL_HASH + if (sha256->buffLen + len < WC_SHA256_BLOCK_SIZE) { + /* Add data to SHA-256 object's buffer. */ + LMS_SHA256_ADD_DATA(sha256, data, len); + } + else if (sha256->buffLen + len < 2 * WC_SHA256_BLOCK_SIZE) { + byte* buffer = (byte*)sha256->buffer; + + XMEMCPY(buffer + sha256->buffLen, data, + WC_SHA256_BLOCK_SIZE - sha256->buffLen); + ret = wc_Sha256HashBlock(sha256, buffer, NULL); + if (ret == 0) { + int rem = len - (WC_SHA256_BLOCK_SIZE - sha256->buffLen); + XMEMCPY(buffer, data + WC_SHA256_BLOCK_SIZE - sha256->buffLen, rem); + sha256->buffLen = rem; + sha256->loLen += len; + } + } + else { + ret = wc_Sha256Update(sha256, data, len); + } +#else + ret = wc_Sha256Update(sha256, data, len); +#endif /* !WC_LMS_FULL_HASH */ + + return ret; +} + +/* Finalize hash. + * + * @param [in] sha256 SHA-256 hash object. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_final(wc_Sha256* sha256, byte* hash) +{ +#ifndef WC_LMS_FULL_HASH + int ret = 0; + byte* buffer = (byte*)sha256->buffer; + + buffer[sha256->buffLen++] = 0x80; + if (sha256->buffLen > WC_SHA256_PAD_SIZE) { + XMEMSET(buffer + sha256->buffLen, 0, + WC_SHA256_BLOCK_SIZE - sha256->buffLen); + ret = wc_Sha256HashBlock(sha256, buffer, NULL); + sha256->buffLen = 0; + } + if (ret == 0) { + XMEMSET(buffer + sha256->buffLen, 0, + WC_SHA256_BLOCK_SIZE - 8 - sha256->buffLen); + sha256->hiLen = (sha256->hiLen << 3) + (sha256->loLen >> 29); + sha256->loLen = sha256->loLen << 3; + #ifdef LITTLE_ENDIAN_ORDER + sha256->buffer[14] = ByteReverseWord32(sha256->hiLen); + sha256->buffer[15] = ByteReverseWord32(sha256->loLen); + #else + sha256->buffer[14] = sha256->hiLen; + sha256->buffer[15] = sha256->loLen; + #endif + ret = wc_Sha256HashBlock(sha256, buffer, hash); + sha256->buffLen = 0; + sha256->hiLen = 0; + sha256->loLen = 0; + } + + return ret; +#else + return wc_Sha256Final(sha256, hash); +#endif +} + +/*************************************** + * LM-OTS APIs + **************************************/ + +/* Expand Q to and array of Winternitz width bits values plus checksum. + * + * Supported Winternitz widths: 8, 4, 2, 1. + * + * Algorithm 2: Checksum Calculation + * sum = 0 + * for ( i = 0; i < (n*8/w); i = i + 1 ) { + * sum = sum + (2^w - 1) - coef(S, i, w) + * } + * return (sum << ls) + * Section 3.1.3: Strings of w-Bit Elements + * coef(S, i, w) = (2^w - 1) AND + * ( byte(S, floor(i * w / 8)) >> + * (8 - (w * (i % (8 / w)) + w)) ) + * Combine coefficient expansion with checksum calculation. + * + * @param [in] q Q array of bytes. + * @param [in] n Number of bytes in Q. + * @param [in] w Winternitz width in bits. + * @param [in] ls Left shift of checksum. + * @param [out] qe Expanded Q with checksum. + * @return 0 on success. + * @return BAD_FUNC_ARG when Winternitz width is not supported. + */ +static WC_INLINE int wc_lmots_q_expand(byte* q, word8 n, word8 w, word8 ls, + byte* qe) +{ + int ret = 0; + word16 sum; + unsigned int i; + +#ifndef WOLFSSL_WC_LMS_SMALL + switch (w) { + /* Winternitz width of 8. */ + case 8: + /* No expansion required, just copy. */ + XMEMCPY(qe, q, n); + /* Start sum with all 2^w - 1s and subtract from that. */ + sum = 0xff * n; + /* For each byte of the hash. */ + for (i = 0; i < n; i++) { + /* Subtract coefficient from sum. */ + sum -= q[i]; + } + /* Put coefficients of checksum on the end. */ + qe[n + 0] = (word8)(sum >> 8); + qe[n + 1] = (word8)(sum ); + break; + /* Winternitz width of 4. */ + case 4: + sum = 2 * 0xf * n; + /* For each byte of the hash. */ + for (i = 0; i < n; i++) { + /* Get coefficient. */ + qe[0] = (q[i] >> 4) ; + qe[1] = (q[i] ) & 0xf; + /* Subtract coefficients from sum. */ + sum -= qe[0]; + sum -= qe[1]; + /* Move to next coefficients. */ + qe += 2; + } + /* Put coefficients of checksum on the end. */ + qe[0] = (word8)((sum >> 8) & 0xf); + qe[1] = (word8)((sum >> 4) & 0xf); + qe[2] = (word8)((sum ) & 0xf); + break; + /* Winternitz width of 2. */ + case 2: + sum = 4 * 0x3 * n; + /* For each byte of the hash. */ + for (i = 0; i < n; i++) { + /* Get coefficients. */ + qe[0] = (q[i] >> 4) ; + qe[0] = (q[i] >> 6) ; + qe[1] = (q[i] >> 4) & 0x3; + qe[2] = (q[i] >> 2) & 0x3; + qe[3] = (q[i] ) & 0x3; + /* Subtract coefficients from sum. */ + sum -= qe[0]; + sum -= qe[1]; + sum -= qe[2]; + sum -= qe[3]; + /* Move to next coefficients. */ + qe += 4; + } + /* Put coefficients of checksum on the end. */ + qe[0] = (word8)((sum >> 8) & 0x3); + qe[1] = (word8)((sum >> 6) & 0x3); + qe[2] = (word8)((sum >> 4) & 0x3); + qe[3] = (word8)((sum >> 2) & 0x3); + qe[4] = (word8)((sum ) & 0x3); + break; + /* Winternitz width of 1. */ + case 1: + sum = 8 * 0x01 * n; + /* For each byte of the hash. */ + for (i = 0; i < n; i++) { + /* Get coefficients. */ + qe[0] = (q[i] >> 4) ; + qe[0] = (q[i] >> 7) ; + qe[1] = (q[i] >> 6) & 0x1; + qe[2] = (q[i] >> 5) & 0x1; + qe[3] = (q[i] >> 4) & 0x1; + qe[4] = (q[i] >> 3) & 0x1; + qe[5] = (q[i] >> 2) & 0x1; + qe[6] = (q[i] >> 1) & 0x1; + qe[7] = (q[i] ) & 0x1; + /* Subtract coefficients from sum. */ + sum -= qe[0]; + sum -= qe[1]; + sum -= qe[2]; + sum -= qe[3]; + sum -= qe[4]; + sum -= qe[5]; + sum -= qe[6]; + sum -= qe[7]; + /* Move to next coefficients. */ + qe += 8; + } + /* Put coefficients of checksum on the end. */ + qe[0] = (word8)((sum >> 8) ); + qe[1] = (word8)((sum >> 7) & 0x1); + qe[2] = (word8)((sum >> 6) & 0x1); + qe[3] = (word8)((sum >> 5) & 0x1); + qe[4] = (word8)((sum >> 4) & 0x1); + qe[5] = (word8)((sum >> 3) & 0x1); + qe[6] = (word8)((sum >> 2) & 0x1); + qe[7] = (word8)((sum >> 1) & 0x1); + qe[8] = (word8)((sum ) & 0x1); + break; + default: + ret = BAD_FUNC_ARG; + break; + } + + (void)ls; +#else + int j; + + if ((w != 8) && (w != 4) && (w != 2) && (w != 1)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Start sum with all 2^w - 1s and subtract from that. */ + sum = ((1 << w) - 1) * ((n * 8) / w); + /* For each byte of the hash. */ + for (i = 0; i < n; i++) { + /* Get next byte. */ + byte a = *(q++); + /* For each width bits of byte. */ + for (j = 8 - w; j >= 0; j -= w) { + /* Get coefficient. */ + *qe = a >> (8 - w); + /* Subtract coefficient from sum. */ + sum -= *qe; + /* Move to next coefficient. */ + qe++; + /* Remove width bits. */ + a <<= w; + } + } + /* Shift sum up as required to pack it on the end of hash. */ + sum <<= ls; + /* For each width buts of checksum. */ + for (j = 16 - w; j >= ls; j--) { + /* Get coefficient. */ + *(qe++) = sum >> (16 - w); + /* Remove width bits. */ + sum <<= w; + } + } +#endif /* !WOLFSSL_WC_LMS_SMALL */ + + return ret; +} + +/* Calculate the hash for the message. + * + * Algorithm 3: Generating a One-Time Signature From a Private Key and a + * Message + * ... + * 5. Compute the array y as follows: + * Q = H(I || u32str(q) || u16str(D_MESG) || C || message) + * Algorithm 4b: Computing a Public Key Candidate Kc from a Signature, + * Message, Signature Typecode pubtype, and Identifiers I, q + * ... + * 3. Compute the string Kc as follows: + * Q = H(I || u32str(q) || u16str(D_MESG) || C || message) + * + * @param [in, out] state LMS state. + * @param [in] msg Message to hash. + * @param [in] msgSz Length of message in bytes. + * @param [in] c C or randomizer value. + * @param [out] q Computed Q value. + * @return 0 on success. + */ +static int wc_lmots_msg_hash(LmsState* state, const byte* msg, word32 msgSz, + const byte* c, byte* q) +{ + int ret; + byte* buffer = state->buffer; + byte* ip = buffer + LMS_I_LEN + LMS_Q_LEN; + + /* I || u32str(q) || u16str(D_MESG) */ + c16toa(LMS_D_MESG, ip); + /* H(I || u32str(q) || u16str(D_MESG) || ...) */ + ret = wc_lms_hash_first(&state->hash, buffer, LMS_MSG_PRE_LEN); + if (ret == 0) { + /* H(... || C || ...) */ + ret = wc_lms_hash_update(&state->hash, c, LMS_MAX_NODE_LEN); + } + if (ret == 0) { + /* H(... || message) */ + ret = wc_lms_hash_update(&state->hash, msg, msgSz); + } + if (ret == 0) { + /* Q = H(...) */ + ret = wc_lms_hash_final(&state->hash, q); + } + + return ret; +} + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Compute array y, intermediates of public key calculation, for signature. + * + * Verification will perform the remaining iterations of hashing. + * + * Algorithm 3: Generating a One-Time Signature From a Private Key and a + * Message + * ... + * 5. Compute the array y as follows: + * Q = H(I || u32str(q) || u16str(D_MESG) || C || message) + * for ( i = 0; i < p; i = i + 1 ) { + * a = coef(Q || Cksm(Q), i, w) + * tmp = x[i] + * for ( j = 0; j < a; j = j + 1 ) { + * tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) + * } + * y[i] = tmp + * } + * x[i] can be calculated on the fly using psueodo key generation in Appendix A. + * Appendix A, The elements of the LM-OTS private keys are computed as: + * x_q[i] = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). + * + * @param [in, out] state LMS state. + * @param [in] seed Seed to hash. + * @param [in] msg Message to sign. + * @param [in] msgSZ Length of message in bytes. + * @param [in] c C or randomizer value to hash. + * @param [out] y Calculated intermediate hashes. + * @return 0 on success. + */ +static int wc_lmots_compute_y_from_seed(LmsState* state, const byte* seed, + const byte* msg, word32 msgSz, const byte* c, byte* y) +{ + const LmsParams* params = state->params; + int ret = 0; + word16 i; + byte q[LMS_MAX_NODE_LEN + LMS_CKSM_LEN]; +#ifdef WOLFSSL_SMALL_STACK + byte* a = state->a; +#else + byte a[LMS_MAX_P]; +#endif /* WOLFSSL_SMALL_STACK */ + byte* buffer = state->buffer; + byte* ip = buffer + LMS_I_LEN + LMS_Q_LEN; + byte* jp = ip + LMS_P_LEN; + byte* tmp = jp + LMS_W_LEN; + + /* Q = H(I || u32str(q) || u16str(D_MESG) || C || message) */ + ret = wc_lmots_msg_hash(state, msg, msgSz, c, q); + if (ret == 0) { + /* Calculate checksum list all coefficients. */ + ret = wc_lmots_q_expand(q, LMS_MAX_NODE_LEN, params->width, params->ls, + a); + } + #ifndef WC_LMS_FULL_HASH + if (ret == 0) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + } + #endif /* !WC_LMS_FULL_HASH */ + + /* Compute y for each coefficient. */ + for (i = 0; (ret == 0) && (i < params->p); i++) { + unsigned int j; + + /* tmp = x[i] + * = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). */ + c16toa(i, ip); + *jp = LMS_D_FIXED; + XMEMCPY(tmp, seed, LMS_SEED_LEN); + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + + /* Apply the hash function coefficient number of times. */ + for (j = 0; (ret == 0) && (j < a[i]); j++) { + /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ + *jp = j; + /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + } + + if (ret == 0) { + /* y[i] = tmp */ + XMEMCPY(y, tmp, LMS_MAX_NODE_LEN); + y += LMS_MAX_NODE_LEN; + } + } + + return ret; +} +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + +/* Compute public key candidate K from signature. + * + * Signing performed the first coefficient number of iterations of hashing. + * + * Algorithm 4b: Computing a Public Key Candidate Kc from a Signature, + * Message, Signature Typecode pubtype, and Identifiers I, q + * ... + * 3. Compute the string Kc as follows: + * Q = H(I || u32str(q) || u16str(D_MESG) || C || message) + * for ( i = 0; i < p; i = i + 1 ) { + * a = coef(Q || Cksm(Q), i, w) + * tmp = y[i] + * for ( j = a; j < 2^w - 1; j = j + 1 ) { + * tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) + * } + * z[i] = tmp + * } + * Kc = H(I || u32str(q) || u16str(D_PBLC) || + * z[0] || z[1] || ... || z[p-1]) + * 4, Return Kc. + * + * @param [in, out] state LMS state. + * @param [in] msg Message to compute Kc for. + * @param [in] msgSz Length of message in bytes. + * @param [in] c C or randomizer value from signature. + * @param [in] sig_y Part of signature containing array y. + * @param [out] kc Kc or public key candidate K. + * @return 0 on success. + */ +static int wc_lmots_compute_kc_from_sig(LmsState* state, const byte* msg, + word32 msgSz, const byte* c, const byte* sig_y, byte* kc) +{ + const LmsParams* params = state->params; + int ret; + word16 i; + byte q[LMS_MAX_NODE_LEN + LMS_CKSM_LEN]; +#ifdef WOLFSSL_SMALL_STACK + byte* a = state->a; +#else + byte a[LMS_MAX_P]; +#endif /* WOLFSSL_SMALL_STACK */ + byte* buffer = state->buffer; + byte* ip = buffer + LMS_I_LEN + LMS_Q_LEN; + byte* jp = ip + LMS_P_LEN; + byte* tmp = jp + LMS_W_LEN; + unsigned int max = ((unsigned int)1 << params->width) - 1; + + /* I || u32str(q) || u16str(D_PBLC). */ + c16toa(LMS_D_PBLC, ip); + /* H(I || u32str(q) || u16str(D_PBLC) || ...). */ + ret = wc_lms_hash_first(&state->hash_k, buffer, LMS_K_PRE_LEN); + if (ret == 0) { + /* Q = H(I || u32str(q) || u16str(D_MESG) || C || message) */ + ret = wc_lmots_msg_hash(state, msg, msgSz, c, q); + } + if (ret == 0) { + /* Calculate checksum list all coefficients. */ + ret = wc_lmots_q_expand(q, LMS_MAX_NODE_LEN, params->width, params->ls, + a); + } + #ifndef WC_LMS_FULL_HASH + if (ret == 0) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + } + #endif /* !WC_LMS_FULL_HASH */ + + /* Compute z for each coefficient. */ + for (i = 0; (ret == 0) && (i < params->p); i++) { + unsigned int j; + + /* I || u32(str) || u16str(i) || ... */ + c16toa(i, ip); + + /* tmp = y[i]. + * I || u32(str) || u16str(i) || ... || tmp */ + XMEMCPY(tmp, sig_y, LMS_MAX_NODE_LEN); + sig_y += LMS_MAX_NODE_LEN; + + /* Finish iterations of hash from coefficient to max. */ + for (j = a[i]; (ret == 0) && (j < max); j++) { + /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ + *jp = (word8)j; + /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + } + + if (ret == 0) { + /* H(... || z[i] || ...) (for calculating Kc). */ + ret = wc_lms_hash_update(&state->hash_k, tmp, LMS_MAX_NODE_LEN); + } + } + + if (ret == 0) { + /* Kc = H(...) */ + ret = wc_lms_hash_final(&state->hash_k, kc); + } + + return ret; +} + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Generate LM-OTS public key. + * + * Caller set: state->buffer = I || u32str(q) + * + * Algorithm 1: Generating a One-Time Signature Public Key From a Private Key + * ... + * 4. Compute the string K as follows: + * for ( i = 0; i < p; i = i + 1 ) { + * tmp = x[i] + * for ( j = 0; j < 2^w - 1; j = j + 1 ) { + * tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) + * } + * y[i] = tmp + * } + * K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) + * ... + * x[i] can be calculated on the fly using psueodo key generation in Appendix A. + * Appendix A, The elements of the LM-OTS private keys are computed as: + * x_q[i] = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). + * + * @param [in, out] state LMS state. + * @param [in] seed Seed to hash. + * @param [out] k K, the public key hash, or OTS_PUB_HASH + */ +static int wc_lmots_make_public_hash(LmsState* state, const byte* seed, byte* k) +{ + const LmsParams* params = state->params; + int ret; + word16 i; + byte* buffer = state->buffer; + byte* ip = buffer + LMS_I_LEN + LMS_Q_LEN; + byte* jp = ip + LMS_P_LEN; + byte* tmp = jp + LMS_W_LEN; + unsigned int max = ((unsigned int)1 << params->width) - 1; + + /* I || u32str(q) || u16str(D_PBLC). */ + c16toa(LMS_D_PBLC, ip); + /* K = H(I || u32str(q) || u16str(D_PBLC) || ...) */ + ret = wc_lms_hash_first(&state->hash_k, buffer, LMS_K_PRE_LEN); + +#ifndef WC_LMS_FULL_HASH + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); +#endif /* !WC_LMS_FULL_HASH */ + + for (i = 0; (ret == 0) && (i < params->p); i++) { + unsigned int j; + + /* tmp = x[i] + * = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). */ + c16toa(i, ip); + *jp = LMS_D_FIXED; + XMEMCPY(tmp, seed, LMS_SEED_LEN); + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + /* Do all iterations to calculate y. */ + for (j = 0; (ret == 0) && (j < max); j++) { + /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ + *jp = (word8)j; + /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + } + if (ret == 0) { + /* K = H(... || y[i] || ...) */ + ret = wc_lms_hash_update(&state->hash_k, tmp, LMS_MAX_NODE_LEN); + } + } + if (ret == 0) { + /* K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) */ + ret = wc_lms_hash_final(&state->hash_k, k); + } + + return ret; +} + +/* Encode the LM-OTS public key. + * + * Encoded into public key and signature if more than one level. + * T[1] is already in place. Putting in: type, ostype and I. + * + * Section 4.3: + * u32str(type) || u32str(otstype) || I || T[1] + * + * @param [in] params LMS parameters. + * @param [in] priv LMS private ley. + * @param [out] pub LMS public key. + */ +static void wc_lmots_public_key_encode(const LmsParams* params, + const byte* priv, byte* pub) +{ + const byte* priv_i = priv + LMS_Q_LEN + LMS_SEED_LEN; + + /* u32str(type) || ... || T(1) */ + c32toa(params->lmsType, pub); + pub += 4; + /* u32str(type) || u32str(otstype) || ... || T(1) */ + c32toa(params->lmOtsType, pub); + pub += 4; + /* u32str(type) || u32str(otstype) || I || T(1) */ + XMEMCPY(pub, priv_i, LMS_I_LEN); +} +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + +/* Check the public key matches the parameters. + * + * @param [in] params LMS parameters. + * @param [in] pub Public key. + * @return 0 on success. + * @return PUBLIC_KEY_E when LMS or LM-OTS type doesn't match. + */ +static int wc_lmots_public_key_check(const LmsParams* params, const byte* pub) +{ + int ret = 0; + word32 type; + + /* Get message hash and height type. */ + ato32(pub, &type); + pub += 4; + /* Compare with parameters. */ + if (type != params->lmsType) { + ret = PUBLIC_KEY_E; + } + if (ret == 0) { + /* Get node hash and Winternitz width type. */ + ato32(pub, &type); + /* Compare with parameters. */ + if (type != params->lmOtsType) { + ret = PUBLIC_KEY_E; + } + } + + return ret; +} + +/* Calculate public key candidate K from signature. + * + * Algorithm 4b: Computing a Public Key Candidate Kc from a Signature, + * Message, Signature Typecode pubtype, and Identifiers I, q + * ... + * 2. Parse sigtype, C, and y from the signature as follows: + * a. sigtype = strTou32(first 4 bytes of signature) + * b. If sigtype is not equal to pubtype, return INVALID. + * ... + * d. C = next n bytes of signature + * e. y[0] = next n bytes of signature + * y[1] = next n bytes of signature + * ... + * y[p-1] = next n bytes of signature + * 3. Compute the string Kc as follows: + * ... + * + * @param [in, out] state LMS state. + * @param [in] pub LMS public key. + * @param [in] msg Message/next private key to verify. + * @param [in] msgSz Length of message in bytes. + * @param [in] sig Signature including type, C and y[0..p-1]. + * @param [out] kc Public key candidate Kc. + */ +static int wc_lmots_calc_kc(LmsState* state, const byte* pub, const byte* msg, + word32 msgSz, const byte* sig, byte* kc) +{ + int ret = 0; + + /* Check signature type. */ + if (XMEMCMP(pub, sig, LMS_TYPE_LEN) != 0) { + ret = SIG_TYPE_E; + } + if (ret == 0) { + /* Get C or randomizer value from signature. */ + const byte* c = sig + LMS_TYPE_LEN; + /* Get array y from signature. */ + const byte* y = c + LMS_MAX_NODE_LEN; + + /* Compute the public key candidate Kc from the signature. */ + ret = wc_lmots_compute_kc_from_sig(state, msg, msgSz, c, y, kc); + } + + return ret; +} + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Generate LM-OTS private key. + * + * Algorithm 5: Computing an LMS Private Key + * But use Appendix A to generate x on the fly. + * PRIV = SEED | I + * + * @param [in] rng Random number generator. + * @param [out] priv Private key data. + */ +static int wc_lmots_make_private_key(WC_RNG* rng, byte* priv) +{ + return wc_RNG_GenerateBlock(rng, priv, LMS_SEED_LEN + LMS_I_LEN); +} + +/* Generate LM-OTS signature. + * + * Algorithm 3: Generating a One-Time Signature From a Private Key and a + * Message + * ... + * 4. Set C to a uniformly random n-byte string + * 5. Compute the array y as follows: + * ... + * 6. Return u32str(type) || C || y[0] || ... || y[p-1] + * + * @param [in, out] state LMS state. + * @param [in] seed Private key seed. + * @param [in] msg Message to be signed. + * @param [in] msgSz Length of message in bytes. + * @param [out] sig Signature buffer. + * @return 0 on success. + */ +static int wc_lmots_sign(LmsState* state, const byte* seed, const byte* msg, + word32 msgSz, byte* sig) +{ + int ret; + byte* buffer = state->buffer; + byte* ip = buffer + LMS_I_LEN + LMS_Q_LEN; + byte* jp = ip + LMS_P_LEN; + byte* tmp = jp + LMS_W_LEN; + byte* sig_c = sig; + + /* I || u32str(q) || u16str(0xFFFD) || ... */ + c16toa(LMS_D_C, ip); + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || ... */ + *jp = LMS_D_FIXED; + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ + XMEMCPY(tmp, seed, LMS_SEED_LEN); + /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) + * sig = u32str(type) || C || ... */ +#ifndef WC_LMS_FULL_HASH + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, sig_c); +#else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, sig_c); +#endif /* !WC_LMS_FULL_HASH */ + + if (ret == 0) { + byte* sig_y = sig_c + LMS_MAX_NODE_LEN; + + /* Compute array y. + * sig = u32str(type) || C || y[0] || ... || y[p-1] */ + ret = wc_lmots_compute_y_from_seed(state, seed, msg, msgSz, sig_c, + sig_y); + } + + return ret; +} +#endif /* WOLFSSL_LMS_VERIFY_ONLY */ + +/*************************************** + * LMS APIs + **************************************/ + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +#ifndef WOLFSSL_WC_LMS_SMALL +/* Load the LMS private state from data. + * + * @param [in] params LMS parameters. + * @param [out] state Private key state. + * @param [in] priv_data Private key data. + */ +static void wc_lms_priv_state_load(const LmsParams* params, LmsPrivState* state, + byte* priv_data) +{ + /* Authentication path data. */ + state->auth_path = priv_data; + priv_data += params->height * LMS_MAX_NODE_LEN; + + /* Stack of nodes. */ + state->stack.stack = priv_data; + priv_data += (params->height + 1) * LMS_MAX_NODE_LEN; + ato32(priv_data, &state->stack.offset); + priv_data += 4; + + /* Cached root nodes. */ + state->root = priv_data; + priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels); + + /* Cached leaf nodes. */ + state->leaf.cache = priv_data; + priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits); + ato32(priv_data, &state->leaf.idx); + priv_data += 4; + ato32(priv_data, &state->leaf.offset); + /* priv_data += 4; */ +} + +/* Store the LMS private state into data. + * + * @param [in] params LMS parameters. + * @param [in] state Private key state. + * @param [in, out] priv_data Private key data. + */ +static void wc_lms_priv_state_store(const LmsParams* params, + LmsPrivState* state, byte* priv_data) +{ + /* Authentication path data. */ + priv_data += params->height * LMS_MAX_NODE_LEN; + + /* Stack of nodes. */ + priv_data += (params->height + 1) * LMS_MAX_NODE_LEN; + c32toa(state->stack.offset, priv_data); + priv_data += 4; + + /* Cached root nodes. */ + priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels); + + /* Cached leaf nodes. */ + priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits); + c32toa(state->leaf.idx, priv_data); + priv_data += 4; + c32toa(state->leaf.offset, priv_data); + /* priv_data += 4; */ +} + +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING +/* Copy LMS private key state. + * + * @param [in] params LMS parameters. + * @param [out] dst LMS private state destination. + * @param [in] src LMS private state source. + */ +static void wc_lms_priv_state_copy(const LmsParams* params, + LmsPrivState* dst, const LmsPrivState* src) +{ + XMEMCPY(dst->auth_path, src->auth_path, LMS_PRIV_STATE_LEN(params->height, + params->rootLevels, params->cacheBits)); + dst->stack.offset = src->stack.offset; + dst->leaf.idx = src->leaf.idx; + dst->leaf.offset = src->leaf.offset; +} +#endif /* !WOLFSSL_LMS_NO_SIGN_SMOOTHING */ +#endif /* !WOLFSSL_WC_LMS_SMALL */ + +/* Calculate the leaf node hash. + * + * Assumes buffer already contains : I + * + * Appendix C. + * ... + * temp = H(I || u32str(r)|| u16str(D_LEAF) || OTS_PUB_HASH[i]) + * ... + * Section 5.3. LMS Public Key + * ... where we denote the public + * key final hash value (namely, the K value computed in Algorithm 1) + * associated with the i-th LM-OTS private key as OTS_PUB_HASH[i], ... + * Algorithm 1: Generating a One-Time Signature Public Key From a + * Private Key + * ... + * K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) + * ... + * Therefore: + * OTS_PUB_HASH[i] = H(I || u32str(i) || u16str(D_PBLC) || + * y[0] || ... || y[p-1]) + * + * @param [in, out] state LMS state. + * @param [in] seed Private seed to generate x. + * @param [in] i Index of leaf. + * @param [in] r Leaf hash index. + * @param [out] leaf Leaf node hash. + */ +static int wc_lms_leaf_hash(LmsState* state, const byte* seed, word32 i, + word32 r, byte* leaf) +{ + int ret; + byte* buffer = state->buffer; + byte* rp = buffer + LMS_I_LEN; + byte* dp = rp + LMS_R_LEN; + byte* ots_pub_hash = dp + LMS_D_LEN; + + /* I || u32str(i) || ... */ + c32toa(i, rp); + /* OTS_PUB_HASH[i] = H(I || u32str(i) || u16str(D_PBLC) || + * y[0] || ... || y[p-1]) + */ + ret = wc_lmots_make_public_hash(state, seed, ots_pub_hash); + if (ret == 0) { + /* I || u32str(r) || ... || OTS_PUB_HASH[i] */ + c32toa(r, rp); + /* I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i] */ + c16toa(LMS_D_LEAF, dp); + /* temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) */ + #ifndef WC_LMS_FULL_HASH + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_54(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, leaf); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_SEED_HASH_LEN, leaf); + #endif /* !WC_LMS_FULL_HASH */ + } + + return ret; +} + +/* Calculate interior node hash. + * + * Appendix C. n Iterative Algorithm for Computing an LMS Public Key + * Generating an LMS Public Key from an LMS Private Key + * ... + * left_side = pop(data stack); + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + * ... + * Popping the stack is done in the caller. + * + * @param [in, out] state LMS state. + * @param [in] sp Stack pointer to left nodes. + * @param [in] r Node hash index. + * @param [out] node Interior node hash. + */ +static int wc_lms_interior_hash(LmsState* state, byte* sp, word32 r, + byte* node) +{ + byte* buffer = state->buffer; + byte* rp = buffer + LMS_I_LEN; + byte* left = rp + LMS_R_LEN + LMS_D_LEN; + + /* I || u32str(r) || u16str(D_INTR) || ... || temp */ + c32toa(r, rp); + /* left_side = pop(data stack) + * I || u32str(r) || u16str(D_INTR) || left_side || temp */ + XMEMCPY(left, sp, LMS_MAX_NODE_LEN); + /* temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ + return wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, node); +} + +#ifdef WOLFSSL_WC_LMS_SMALL +/* Computes hash of the Merkle tree and gets the authentication path for q. + * + * Appendix C: An Iterative Algorithm for Computing an LMS Public Key + * for ( i = 0; i < 2^h; i = i + 1 ) { + * r = i + num_lmots_keys; + * temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) + * j = i; + * while (j % 2 == 1) { + * r = (r - 1)/2; + * j = (j-1) / 2; + * left_side = pop(data stack); + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + * } + * push temp onto the data stack + * } + * public_key = pop(data stack) + * + * @param [in, out] state LMS state. + * @param [in] id Unique tree identifier, I. + * @param [in] seed Private seed to generate x. + * @param [in] max Count of leaf nodes to calculate. Must be greater + * than q. Must be a power of 2. + * @param [in] q Index for authentication path. + * @param [out] auth_path Authentication path for index. + * @param [out] pub LMS public key. + * @param [out] stack_d Where to store stack data. + * @return 0 on success. + */ +static int wc_lms_treehash(LmsState* state, const byte* id, const byte* seed, + word32 q, byte* auth_path, byte* pub) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte* rp = buffer + LMS_I_LEN; + byte* dp = rp + LMS_R_LEN; + byte* left = dp + LMS_D_LEN; + byte* temp = left + LMS_MAX_NODE_LEN; +#ifdef WOLFSSL_SMALL_STACK + byte* stack = NULL; +#else + byte stack[(LMS_MAX_HEIGHT + 1) * LMS_MAX_NODE_LEN]; +#endif /* WOLFSSL_SMALL_STACK */ + byte* sp; + word32 i; + + /* I || ... */ + XMEMCPY(buffer, id, LMS_I_LEN); + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate stack of left side hashes. */ + stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (stack == NULL) { + ret = MEMORY_E; + } +#endif /* WOLFSSL_SMALL_STACK */ + sp = stack; + + /* Compute all nodes requested. */ + for (i = 0; (ret == 0) && (i < ((word32)1 << params->height)); i++) { + word32 j = i; + word16 h = 0; + /* r = i + num_lmots_keys */ + word32 r = i + ((word32)1 << (params->height)); + + /* Calculate leaf node hash. */ + ret = wc_lms_leaf_hash(state, seed, i, r, temp); + + /* Store the node if on the authentication path. */ + if ((ret == 0) && (auth_path != NULL) && ((q ^ 0x1) == i)) { + XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + } + + /* I || ... || u16str(D_INTR) || ... || temp */ + c16toa(LMS_D_INTR, dp); + /* Calculate parent node is we have both left and right. */ + while ((ret == 0) && ((j & 0x1) == 1)) { + /* Get parent node index. r and j are odd. */ + r >>= 1; + j >>= 1; + h++; + + /* Calculate interior node hash. + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + */ + sp -= LMS_MAX_NODE_LEN; + ret = wc_lms_interior_hash(state, sp, r, temp); + + /* Copy out node to authentication path if on path. */ + if ((ret == 0) && (auth_path != NULL) && ((q >> h) ^ 0x1) == j) { + XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, + LMS_MAX_NODE_LEN); + } + } + /* Push temp onto the data stack. */ + XMEMCPY(sp, temp, LMS_MAX_NODE_LEN); + sp += LMS_MAX_NODE_LEN; + } + + if ((ret == 0) && (pub != NULL)) { + /* Public key, root node, is top of data stack. */ + XMEMCPY(pub, stack, LMS_MAX_NODE_LEN); + } +#ifdef WOLFSSL_SMALL_STACK + XFREE(stack, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif /* WOLFSSL_SMALL_STACK */ + return ret; +} + +/* Compute the LMS public key - root node of tree. + * + * @param [in, out] state LMS state. + * @param [in] id Unique tree identifier, I. + * @param [in] seed Private seed to generate x. + * @param [out] pub LMS public key. + * @return 0 on success. + */ +static int wc_lms_make_public_key(LmsState* state, const byte* id, + const byte* seed, byte* pub) +{ + return wc_lms_treehash(state, id, seed, 0, NULL, pub); +} + +/* Calculate the authentication path. + * + * @param [in, out] state LMS state. + * @param [in] id Public random: I. + * @param [in] seed Private random: SEED. + * @param [in] q Index of leaf. + * @param [out] sig Signature buffer to place authentication path into. + * @param [out] root Root node of tree. + * @return 0 on success. + */ +static int wc_lms_auth_path(LmsState* state, const byte* id, const byte* seed, + word32 q, byte* sig, byte* root) +{ + return wc_lms_treehash(state, id, seed, q, sig, root); +} +#else +/* Computes hash of the Merkle tree and gets the authentication path for q. + * + * Appendix C: An Iterative Algorithm for Computing an LMS Public Key + * for ( i = 0; i < 2^h; i = i + 1 ) { + * r = i + num_lmots_keys; + * temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) + * j = i; + * while (j % 2 == 1) { + * r = (r - 1)/2; + * j = (j-1) / 2; + * left_side = pop(data stack); + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + * } + * push temp onto the data stack + * } + * public_key = pop(data stack) + * + * @param [in, out] state LMS state. + * @param [in, out] privState LMS state of the private key. + * @param [in] id Unique tree identifier, I. + * @param [in] seed Private seed to generate x. + * @param [in] q Index for authentication path. + * @return 0 on success. + */ +static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, + const byte* id, const byte* seed, word32 q) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte* auth_path = privState->auth_path; + byte* root = privState->root; + HssLeafCache* leaf = &privState->leaf; + byte* rp = buffer + LMS_I_LEN; + byte* dp = rp + LMS_R_LEN; + byte* left = dp + LMS_D_LEN; + byte* temp = left + LMS_MAX_NODE_LEN; +#ifdef WOLFSSL_SMALL_STACK + byte* stack = NULL; +#else + byte stack[(LMS_MAX_HEIGHT + 1) * LMS_MAX_NODE_LEN]; +#endif /* WOLFSSL_SMALL_STACK */ + word32 spi = 0; + word32 i; + word32 max_h = (word32)1 << params->height; + word32 max_cb = (word32)1 << params->cacheBits; + + privState->stack.offset = 0; + /* Reset the cached stack. */ + leaf->offset = 0; + leaf->idx = q; + if ((q + max_cb) > max_h) { + leaf->idx = max_h - max_cb; + } + + /* I || ... */ + XMEMCPY(buffer, id, LMS_I_LEN); + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate stack of left side hashes. */ + stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (stack == NULL) { + ret = MEMORY_E; + } +#endif /* WOLFSSL_SMALL_STACK */ + + /* Compute all nodes requested. */ + for (i = 0; (ret == 0) && (i < max_h); i++) { + word32 j = i; + word16 h = 0; + /* r = i + num_lmots_keys */ + word32 r = i + max_h; + + /* Calculate leaf node hash. */ + ret = wc_lms_leaf_hash(state, seed, i, r, temp); + + /* Cache leaf node if in range. */ + if ((ret == 0) && (i >= leaf->idx) && (i < leaf->idx + max_cb)) { + XMEMCPY(leaf->cache + i * LMS_MAX_NODE_LEN, temp, LMS_MAX_NODE_LEN); + } + + /* Store the node if on the authentication path. */ + if ((ret == 0) && (auth_path != NULL) && ((q ^ 0x1) == i)) { + XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + } + + /* I || ... || u16str(D_INTR) || ... || temp */ + c16toa(LMS_D_INTR, dp); + /* Calculate parent node is we have both left and right. */ + while ((ret == 0) && ((j & 0x1) == 1)) { + /* Get parent node index. r and j are odd. */ + r >>= 1; + j >>= 1; + h++; + + /* Calculate interior node hash. + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + */ + spi -= LMS_MAX_NODE_LEN; + ret = wc_lms_interior_hash(state, stack + spi, r, temp); -#ifdef WOLFSSL_HAVE_LMS - #error "Contact wolfSSL to get the implementation of this file" + /* Copy out top root nodes. */ + if ((h > params->height - params->rootLevels) && + ((i >> (h-1)) != ((i + 1) >> (h - 1)))) { + int off = (1 << (params->height - h)) + (i >> h) - 1; + XMEMCPY(root + off * LMS_MAX_NODE_LEN, temp, LMS_MAX_NODE_LEN); + } + + /* Copy out node to authentication path if on path. */ + if ((ret == 0) && (auth_path != NULL) && ((q >> h) ^ 0x1) == j) { + XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, + LMS_MAX_NODE_LEN); + } + } + /* Push temp onto the data stack. */ + XMEMCPY(stack + spi, temp, LMS_MAX_NODE_LEN); + spi += LMS_MAX_NODE_LEN; + + if (i == q - 1) { + XMEMCPY(privState->stack.stack, stack, spi); + privState->stack.offset = spi; + } + } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(stack, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif /* WOLFSSL_SMALL_STACK */ + return ret; +} + +/* Computes hash of the Merkle tree and gets the authentication path for q. + * + * Appendix C: An Iterative Algorithm for Computing an LMS Public Key + * for ( i = 0; i < 2^h; i = i + 1 ) { + * r = i + num_lmots_keys; + * temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) + * j = i; + * while (j % 2 == 1) { + * r = (r - 1)/2; + * j = (j-1) / 2; + * left_side = pop(data stack); + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) + * } + * push temp onto the data stack + * } + * public_key = pop(data stack) + * + * @param [in, out] state LMS state. + * @param [in, out] privState LMS state of the private key. + * @param [in] id Unique tree identifier, I. + * @param [in] seed Private seed to generate x. + * @param [in] min_idx Minimum leaf index to process. + * @param [in] max_idx Maximum leaf index to process. + * @param [in] q Index for authentication path. + * @param [in] useRoot Whether to use nodes from root cache. + * @return 0 on success. + */ +static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, + const byte* id, const byte* seed, word32 min_idx, word32 max_idx, word32 q, + int useRoot) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte* auth_path = privState->auth_path; + LmsStack* stackCache = &privState->stack; + HssLeafCache* leaf = &privState->leaf; + byte* rp = buffer + LMS_I_LEN; + byte* dp = rp + LMS_R_LEN; + byte* left = dp + LMS_D_LEN; + byte* temp = left + LMS_MAX_NODE_LEN; +#ifdef WOLFSSL_SMALL_STACK + byte* stack = NULL; +#else + byte stack[(LMS_MAX_HEIGHT + 1) * LMS_MAX_NODE_LEN]; +#endif /* WOLFSSL_SMALL_STACK */ + byte* sp; + word32 max_cb = (word32)1 << params->cacheBits; + word32 i; + + /* I || ... */ + XMEMCPY(buffer, id, LMS_I_LEN); + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate stack of left side hashes. */ + stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (stack == NULL) { + ret = MEMORY_E; + } +#endif /* WOLFSSL_SMALL_STACK */ + + /* Public key, root node, is top of data stack. */ + XMEMCPY(stack, stackCache->stack, params->height * LMS_MAX_NODE_LEN); + sp = stack + stackCache->offset; + + /* Compute all nodes requested. */ + for (i = min_idx; (ret == 0) && (i <= max_idx); i++) { + word32 j = i; + word16 h = 0; + /* r = i + num_lmots_keys */ + word32 r = i + ((word32)1 << (params->height)); + + if ((i >= leaf->idx) && (i < leaf->idx + max_cb)) { + /* Calculate offset of node in cache. */ + word32 off = ((i - (leaf->idx + max_cb) + leaf->offset) % max_cb) * + LMS_MAX_NODE_LEN; + /* Copy cached node into working buffer. */ + XMEMCPY(temp, leaf->cache + off, LMS_MAX_NODE_LEN); + /* I || u32str(i) || ... */ + c32toa(i, rp); + } + else { + /* Calculate leaf node hash. */ + ret = wc_lms_leaf_hash(state, seed, i, r, temp); + + /* Check if this is at the end of the cache and not beyond q plus + * the number of leaf nodes. */ + if ((i == leaf->idx + max_cb) && (i < (q + max_cb))) { + /* Copy working node into cache over old first node. */ + XMEMCPY(leaf->cache + leaf->offset * LMS_MAX_NODE_LEN, temp, + LMS_MAX_NODE_LEN); + /* Increase start index as first node replaced. */ + leaf->idx++; + /* Update offset of first leaf node. */ + leaf->offset = (leaf->offset + 1) & (max_cb - 1); + } + } + + /* Store the node if on the authentication path. */ + if ((ret == 0) && ((q ^ 0x1) == i)) { + XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + } + + /* I || ... || u16str(D_INTR) || ... || temp */ + c16toa(LMS_D_INTR, dp); + /* Calculate parent node if we have both left and right. */ + while ((ret == 0) && ((j & 0x1) == 1)) { + /* Get parent node index. r and j are odd. */ + r >>= 1; + j >>= 1; + h++; + + sp -= LMS_MAX_NODE_LEN; + if (useRoot && (h > params->height - params->rootLevels) && + (h <= params->height)) { + /* Calculate offset of cached root node. */ + word32 off = ((word32)1U << (params->height - h)) + + (i >> h) - 1; + XMEMCPY(temp, privState->root + (off * LMS_MAX_NODE_LEN), + LMS_MAX_NODE_LEN); + } + else { + /* Calculate interior node hash. + * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || + * temp) + */ + ret = wc_lms_interior_hash(state, sp, r, temp); + } + + /* Copy out top root nodes. */ + if ((ret == 0) && (q == 0) && (!useRoot) && + (h > params->height - params->rootLevels) && + ((i >> (h-1)) != ((i + 1) >> (h - 1)))) { + int off = (1 << (params->height - h)) + (i >> h) - 1; + XMEMCPY(privState->root + off * LMS_MAX_NODE_LEN, temp, + LMS_MAX_NODE_LEN); + } + + /* Copy out node to authentication path if on path. */ + if ((ret == 0) && (((q >> h) ^ 0x1) == j)) { + XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, + LMS_MAX_NODE_LEN); + } + } + if (ret == 0) { + /* Push temp onto the data stack. */ + XMEMCPY(sp, temp, LMS_MAX_NODE_LEN); + sp += LMS_MAX_NODE_LEN; + + /* Save stack after updating first node. */ + if (i == min_idx) { + /* Copy stack back. */ + stackCache->offset = (word32)((size_t)sp - (size_t)stack); + XMEMCPY(stackCache->stack, stack, stackCache->offset); + } + } + } + + if (!useRoot) { + /* Copy stack back. */ + XMEMCPY(stackCache->stack, stack, params->height * LMS_MAX_NODE_LEN); + stackCache->offset = (word32)((size_t)sp - (size_t)stack); + } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(stack, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif /* WOLFSSL_SMALL_STACK */ + return ret; +} +#endif /* WOLFSSL_WC_LMS_SMALL */ + +/* Sign message using LMS. + * + * Appendix D. Method for Deriving Authentication Path for a Signature. + * Generating an LMS Signature + * ... + * 3. Create the LM-OTS signature for the message: + * ots_signature = lmots_sign(message, LMS_PRIV[q]) + * 4. Compute the array path as follows: + * ... + * 5. S = u32str(q) || ots_signature || u32str(type) || + * path[0] || path[1] || ... || path[h-1] + * ... + * path[] added by caller as it can come from cache. + * + * @param [in, out] state LMS state. + * @param [in] priv LMS private key. + * @param [in] msg Message/public key to sign. + * @param [in] msgSz Length of message in bytes. + * @param [out] sig LMS signature. + * @return 0 on success. + */ +static int wc_lms_sign(LmsState* state, const byte* priv, const byte* msg, + word32 msgSz, byte* sig) +{ + int ret; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte* s = sig; + const byte* priv_q = priv; + const byte* priv_seed = priv_q + LMS_Q_LEN; + const byte* priv_i = priv_seed + LMS_SEED_LEN; + + /* Setup for hashing: I || Q */ + XMEMCPY(buffer, priv_i, LMS_I_LEN); + XMEMCPY(buffer + LMS_I_LEN, priv_q, LMS_Q_LEN); + + /* Copy q from private key. + * S = u32str(q) || ... */ + XMEMCPY(s, priv_q, LMS_Q_LEN); + s += LMS_Q_LEN; + + /* ots_signature = sig = u32str(type) || ... */ + c32toa(state->params->lmOtsType, s); + s += LMS_TYPE_LEN; + /* Sign this level. + * S = u32str(q) || ots_signature || ... */ + ret = wc_lmots_sign(state, priv_seed, msg, msgSz, s); + if (ret == 0) { + /* Skip over ots_signature. */ + s += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN; + /* S = u32str(q) || ots_signature || u32str(type) || ... */ + c32toa(params->lmsType, s); + } + + return ret; +} + +#if !defined(WOLFSSL_WC_LMS_SMALL) && !defined(WOLFSSL_LMS_NO_SIG_CACHE) +/* Copy in the cached signature data. + * + * @param [in] params LMS parameters. + * @param [in] y y cache. + * @param [in] priv Private key data. + * @param [out] sig Signature data. + */ +static void wc_lms_sig_copy(const LmsParams* params, const byte* y, + const byte* priv, byte* sig) +{ + /* Put in q. */ + XMEMCPY(sig, priv, LMS_Q_LEN); + sig += LMS_Q_LEN; + /* S = u32str(q) || ... */ + c32toa(params->lmOtsType, sig); + sig += LMS_TYPE_LEN; + /* S = u32str(q) || ots_signature || ... */ + XMEMCPY(sig, y, LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN); + sig += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN; + /* S = u32str(q) || ots_signature || u32str(type) || ... */ + c32toa(params->lmsType, sig); +} +#endif /* !WOLFSSL_WC_LMS_SMALL && !WOLFSSL_LMS_NO_SIG_CACHE */ +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + +/* Compute the root node of the LMS tree. + * + * Algorithm 6a: Computing an LMS Public Key Candidate from a Signature, + * Message, Identifier, and Algorithm Typecodes + * ... + * 4. Compute the candidate LMS root value Tc as follows: + * node_num = 2^h + q + * tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc) + * i = 0 + * while (node_num > 1) { + * if (node_num is odd): + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) + * else: + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * node_num = node_num/2 + * i = i + 1 + * } + * Tc = tmp + * 5. Return Tc. + * + * @param [in, out] state LMS state. + * @param [in] q Index of node. + * @param [in] kc K candidate. + * @param [in] path Authentication path from signature. + * @param [out] tc T candidate. + * @return 0 on success. + */ +static int wc_lms_compute_root(LmsState* state, word32 q, const byte* kc, + const byte* path, byte* tc) +{ + int ret; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte* rp = buffer + LMS_I_LEN; + byte* ip = rp + LMS_Q_LEN; + byte* node = ip + LMS_P_LEN; + byte* b[2][2] = { { node, node + LMS_MAX_NODE_LEN }, + { node + LMS_MAX_NODE_LEN, node } }; + /* node_num = 2^h + q */ + word32 r = (1 << params->height) + q; + + /* tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc) */ + c32toa(r, rp); + c16toa(LMS_D_LEAF, ip); + XMEMCPY(node, kc, LMS_MAX_NODE_LEN); + /* Put tmp into offset required for first iteration. */ +#ifndef WC_LMS_FULL_HASH + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_54(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, b[r & 1][0]); +#else + ret = wc_lms_hash(&state->hash, buffer, LMS_SEED_HASH_LEN, b[r & 1][0]); +#endif /* !WC_LMS_FULL_HASH */ + + if (ret == 0) { + int i; + + /* I||...||u16str(D_INT)||... */ + c16toa(LMS_D_INTR, ip); + + /* Do all but last height. */ + for (i = 0; (ret == 0) && (i < params->height - 1); i++) { + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, LMS_MAX_NODE_LEN); + path += LMS_MAX_NODE_LEN; + + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into offset required for next iteration. */ + ret = wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, + b[r & 1][0]); + } + if (ret == 0) { + /* Last height. */ + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, LMS_MAX_NODE_LEN); + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into Tc.*/ + ret = wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, tc); + } + } + + return ret; +} + +/* LMS verify message using public key and signature. + * + * Algorithm 6a: Computing an LMS Public Key Candidate from a Signature, + * Message, Identifier, and Algorithm Typecodes + * ... + * 2. Parse sigtype, q, lmots_signature, and path from the signature + * as follows: + * a. q = strTou32(first 4 bytes of signature) + * ... + * e. lmots_signature = bytes 4 through 7 + n * (p + 1) + * of signature + * ... + * j. Set path as follows: + * path[0] = next m bytes of signature + * path[1] = next m bytes of signature + * ... + * path[h-1] = next m bytes of signature + * 3. Kc = candidate public key computed by applying Algorithm 4b + * to the signature lmots_signature, the message, and the + * identifiers I, q + * 4. Compute the candidate LMS root value Tc as follows: + * ... + * 5. Return Tc + * Algorithm 6: LMS Signature Verification + * ... + * 3. Compute the LMS Public Key Candidate Tc from the signature, + * message, identifier, pubtype, and ots_typecode, using + * Algorithm 6a. + * 4. If Tc is equal to T[1], return VALID; otherwise, return INVALID. + * + * @param [in, out] state LMS state. + * @param [in] pub LMS public key. + * @param [in] msg Message/public key to verify. + * @param [in] msgSz Length of message in bytes. + * @param [in] sig LMS signature. + */ +static int wc_lms_verify(LmsState* state, const byte* pub, const byte* msg, + word32 msgSz, const byte* sig) +{ + int ret; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + const byte* pub_i = pub + LMS_TYPE_LEN + LMS_TYPE_LEN; + const byte* pub_k = pub_i + LMS_I_LEN; + const byte* sig_q = sig; + byte tc[LMS_MAX_NODE_LEN]; + byte* kc = tc; + + /* Algorithm 6. Step 3. */ + /* Check the public key LMS type matches parameters. */ + ret = wc_lmots_public_key_check(params, pub); + if (ret == 0) { + /* Algorithm 6a. Step 2.e. */ + const byte* sig_lmots = sig + LMS_Q_LEN; + + /* Setup buffer with I || Q. */ + XMEMCPY(buffer, pub_i, LMS_I_LEN); + XMEMCPY(buffer + LMS_I_LEN, sig_q, LMS_Q_LEN); + + /* Algorithm 6a. Step 3. */ + ret = wc_lmots_calc_kc(state, pub + LMS_TYPE_LEN, msg, msgSz, + sig_lmots, kc); + } + if (ret == 0) { + /* Algorithm 6a. Step 2.j. */ + const byte* sig_path = sig + LMS_Q_LEN + LMS_TYPE_LEN + + LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN; + word32 q; + + /* Algorithm 6a. Step 2.a. */ + ato32(sig_q, &q); + + /* Algorithm 6a. Steps 4-5. */ + ret = wc_lms_compute_root(state, q, kc, sig_path, tc); + } + /* Algorithm 6. Step 4. */ + if ((ret == 0) && (XMEMCMP(pub_k, tc, LMS_MAX_NODE_LEN) != 0)) { + ret = SIG_VERIFY_E; + } + + return ret; +} + +/*************************************** + * HSS APIs + **************************************/ + +#ifndef WOLFSSL_LMS_VERIFY_ONLY +/* Derive the seed and i for child. + * + * @param [in, out] state LMS state. + * @param [in] id Parent's I. + * @param [in] seed Parent's SEED. + * @param [in] q Parent's q. + * @param [out] seed_i Derived SEED and I. + * @return 0 on success. + */ +static int wc_hss_derive_seed_i(LmsState* state, const byte* id, + const byte* seed, const byte* q, byte* seed_i) +{ + int ret = 0; + byte buffer[WC_SHA256_BLOCK_SIZE]; + byte* idp = buffer; + byte* qp = idp + LMS_I_LEN; + byte* ip = qp + LMS_Q_LEN; + byte* jp = ip + LMS_P_LEN; + byte* tmp = jp + LMS_W_LEN; + + /* parent's I || ... */ + XMEMCPY(idp, id, LMS_I_LEN); + /* parent's I || q || ... */ + XMEMCPY(qp, q, LMS_Q_LEN); + /* parent's I || q || D_CHILD_SEED || ... */ + c16toa(LMS_D_CHILD_SEED, ip); + /* parent's I || q || D_CHILD_SEED || D_FIXED || ... */ + *jp = LMS_D_FIXED; + /* parent's I || q || D_CHILD_SEED || D_FIXED || parent's SEED */ + XMEMCPY(tmp, seed, LMS_SEED_LEN); + /* SEED = H(parent's I || q || D_CHILD_SEED || D_FIXED || parent's SEED) */ +#ifndef WC_LMS_FULL_HASH + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, seed_i); +#else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, seed_i); +#endif /* !WC_LMS_FULL_HASH */ + + if (ret == 0) { + seed_i += LMS_SEED_LEN; + /* parent's I || q || D_CHILD_I || D_FIXED || parent's SEED */ + c16toa(LMS_D_CHILD_I, ip); + /* I = H(parent's I || q || D_CHILD_I || D_FIXED || parent's SEED) */ + #ifndef WC_LMS_FULL_HASH + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); + #endif /* !WC_LMS_FULL_HASH */ + /* Copy part of hash as new I into private key. */ + XMEMCPY(seed_i, tmp, LMS_I_LEN); + } + + return ret; +} + +/* Get q, index, of leaf at the specified level. */ +#define LMS_Q_AT_LEVEL(q, ls, l, h) \ + (w64GetLow32(w64ShiftRight((q), (((ls) - 1 - (l)) * (h)))) & \ + (((word32)1 << (h)) - 1)) + +/* Expand the seed and I for further levels and set q for each level. + * + * @param [in, out] state LMS state. + * @param [in, out] priv Private key for use in signing. + * @param [in] priv_raw Private key read. + * @param [in] inc Whether this is an incremental expansion. + * @return 0 on success. + */ +static int wc_hss_expand_private_key(LmsState* state, byte* priv, + const byte* priv_raw, int inc) +{ + const LmsParams* params = state->params; + int ret = 0; + w64wrapper q; + w64wrapper qm1; + word32 q32; + byte* priv_q; + byte* priv_seed_i; + int i; + + /* Get the 64-bit q value from the raw private key. */ + ato64(priv_raw, &q); + /* Step over q and parameter set. */ + priv_raw += HSS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN; + + /* Get q of highest level. */ + q32 = LMS_Q_AT_LEVEL(q, params->levels, 0, params->height); + /* Set q of highest tree. */ + c32toa(q32, priv); + + /* Incremental expansion needs q-1. */ + if (inc) { + /* Calculate q-1 for comparison. */ + qm1 = q; + w64Decrement(&qm1); + } + else { + /* Copy out SEED and I into private key. */ + XMEMCPY(priv + LMS_Q_LEN, priv_raw, LMS_SEED_I_LEN); + } + + /* Compute SEED and I for rest of levels. */ + for (i = 1; (ret == 0) && (i < params->levels); i++) { + /* Don't skip calculating SEED and I. */ + int skip = 0; + + /* Incremental means q, SEED and I already present if q unchanged. */ + if (inc) { + /* Calculate previous levels q for previous 64-bit q value. */ + word32 qm1_32 = LMS_Q_AT_LEVEL(qm1, params->levels, i - 1, + params->height); + /* Same q at previous level means no need to re-compute. */ + if (q32 == qm1_32) { + /* Do skip calculating SEED and I. */ + skip = 1; + } + } + + /* Get pointers into private q to write q and seed + I. */ + priv_q = priv; + priv += LMS_Q_LEN; + priv_seed_i = priv; + priv += LMS_SEED_I_LEN; + + /* Get q for level from 64-bit composite. */ + q32 = w64GetLow32(w64ShiftRight(q, (params->levels - 1 - i) * + params->height)) & (((word32)1 << params->height) - 1); + /* Set q of tree. */ + c32toa(q32, priv); + + if (!skip) { + /* Derive SEED and I into private key. */ + ret = wc_hss_derive_seed_i(state, priv_seed_i + LMS_SEED_LEN, + priv_seed_i, priv_q, priv + LMS_Q_LEN); + } + } + + return ret; +} + +#ifndef WOLFSSL_WC_LMS_SMALL +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING +/* Initialize the next subtree. + * + * @param [in] state LMS state. + * @param [in] privState LMS private state. + * @param [in] curr Current private key. + * @param [in] priv Next private key. + * @param [in] q q for this level. + * @return 0 on success. + */ +static int wc_lms_next_subtree_init(LmsState* state, LmsPrivState* privState, + byte* curr, byte* priv, word32 q) +{ + int ret; + const LmsParams* params = state->params; + byte* priv_q; + byte* priv_seed; + byte* priv_i; + word32 pq; + + priv_q = priv; + priv += LMS_Q_LEN; + priv_seed = curr + LMS_Q_LEN; + priv += LMS_SEED_LEN; + priv_i = curr + LMS_Q_LEN + LMS_SEED_LEN; + priv += LMS_I_LEN; + + ato32(curr, &pq); + pq = (pq + 1) & ((1 << params->height) - 1); + c32toa(pq, priv_q); + + privState->stack.offset = 0; + privState->leaf.idx = (word32)-(1 << params->cacheBits); + privState->leaf.offset = 0; + + /* Derive SEED and I for next tree. */ + ret = wc_hss_derive_seed_i(state, priv_i, priv_seed, priv_q, + priv + LMS_Q_LEN); + if (ret == 0) { + /* Update treehash for first leaf. */ + ret = wc_lms_treehash_update(state, privState, + priv + LMS_Q_LEN + LMS_SEED_LEN, priv + LMS_Q_LEN, 0, q, 0, 0); + } + + return ret; +} + +/* Increment count on next subtree. + * + * @param [in] state LMS state. + * @param [in] priv_key HSS private key. + * @param [in] q64 64-bit q for all levels. + * @return 0 on success. + */ +static int wc_hss_next_subtree_inc(LmsState* state, HssPrivKey* priv_key, + w64wrapper q64) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* curr = priv_key->priv; + byte* priv = priv_key->next_priv; + int i; + w64wrapper p64 = q64; + byte tmp_priv[LMS_PRIV_LEN]; + int use_tmp = 0; + int lastQMax = 0; + w64wrapper p64_hi; + w64wrapper q64_hi; + + /* Get previous index. */ + w64Decrement(&p64); + /* Get index of previous and current parent. */ + p64_hi = w64ShiftRight(p64, (params->levels - 1) * params->height); + q64_hi = w64ShiftRight(q64, (params->levels - 1) * params->height); + for (i = 1; (ret == 0) && (i < params->levels); i++) { + word32 qc; + w64wrapper cp64_hi; + w64wrapper cq64_hi; + + /* Get index of previous and current child. */ + cp64_hi = w64ShiftRight(p64, (params->levels - i - 1) * params->height); + cq64_hi = w64ShiftRight(q64, (params->levels - i - 1) * params->height); + /* Get the q for the child. */ + ato32(curr + LMS_PRIV_LEN, &qc); + + /* Compare index of parent node with previous value. */ + if (w64LT(p64_hi, q64_hi)) { + wc_lms_priv_state_copy(params, &priv_key->state[i], + &priv_key->next_state[i-1]); + ret = wc_lms_next_subtree_init(state, &priv_key->next_state[i - 1], + use_tmp ? tmp_priv : curr, priv, 0); + use_tmp = 0; + } + /* Check whether the child is in a new subtree. */ + else if ((qc == ((word32)1 << params->height) - 1) && + w64LT(cp64_hi, cq64_hi)) { + XMEMSET(tmp_priv, 0, LMS_Q_LEN); + /* Check whether the node at the previous level is also in a new + * subtree. */ + if (lastQMax) { + /* Calculate new SEED and I based on new subtree. */ + ret = wc_hss_derive_seed_i(state, + priv + LMS_Q_LEN + LMS_SEED_LEN, priv + LMS_Q_LEN, tmp_priv, + tmp_priv + LMS_Q_LEN); + } + else { + /* Calculate new SEED and I based on parent. */ + ret = wc_hss_derive_seed_i(state, + curr + LMS_Q_LEN + LMS_SEED_LEN, curr + LMS_Q_LEN, priv, + tmp_priv + LMS_Q_LEN); + } + /* Values not stored so note that they are in temporary. */ + use_tmp = 1; + + /* Set the the q. */ + XMEMCPY(tmp_priv, curr + LMS_PRIV_LEN, LMS_Q_LEN); + } + + lastQMax = (qc == ((word32)1 << params->height) - 1); + curr += LMS_PRIV_LEN; + priv += LMS_PRIV_LEN; + p64_hi = cp64_hi; + q64_hi = cq64_hi; + } + + return ret; +} + +/* Initialize the next subtree for each level bar the highest. + * + * @param [in, out] state LMS state. + * @param [out] priv_key Private key data. + * @return 0 on success. + */ +static int wc_hss_next_subtrees_init(LmsState* state, HssPrivKey* priv_key) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* curr = priv_key->priv; + byte* priv = priv_key->next_priv; + int i; + + XMEMCPY(priv, curr, LMS_PRIV_LEN); + wc_lms_idx_inc(priv, LMS_Q_LEN); + + for (i = 1; (ret == 0) && (i < params->levels); i++) { + word32 q; + + ato32(curr + LMS_PRIV_LEN, &q); + ret = wc_lms_next_subtree_init(state, &priv_key->next_state[i - 1], + curr, priv, q); + + curr += LMS_PRIV_LEN; + priv += LMS_PRIV_LEN; + } + + return ret; +} #endif + +/* Update the authentication path and caches. + * + * @param [in, out] state LMS state. + * @param [in, out] priv_key Private key information. + * @param [in] levels Number of level to start at. + * @param [out] pub_root Public root. + * @return 0 on success. + */ +static int wc_hss_init_auth_path(LmsState* state, HssPrivKey* priv_key, + byte* pub_root) +{ + int ret = 0; + int levels = state->params->levels; + byte* priv = priv_key->priv + LMS_PRIV_LEN * (levels - 1); + int l; + + for (l = levels - 1; (ret == 0) && (l >= 0); l--) { + word32 q; + const byte* priv_q = priv; + const byte* priv_seed = priv_q + LMS_Q_LEN; + const byte* priv_i = priv_seed + LMS_SEED_LEN; + + /* Get current q for tree at level. */ + ato32(priv_q, &q); + /* Set cache start to a value that indicates no numbers available. */ + ret = wc_lms_treehash_init(state, &priv_key->state[l], priv_i, + priv_seed, q); + + /* Move onto next level's data. */ + priv -= LMS_PRIV_LEN; + } + + if ((ret == 0) && (pub_root != NULL)) { + XMEMCPY(pub_root, priv_key->state[0].root, LMS_MAX_NODE_LEN); + } + + return ret; +} + +/* Calculate the corresponding authentication path index at that height. + * + * @param [in] i Leaf node index. + * @param [in] h Height to calculate for. + * @return Index on authentication path. + */ +#define LMS_AUTH_PATH_IDX(i, h) \ + (((i) ^ ((word32)1U << (h))) | (((word32)1U << (h)) - 1)) + +/* Update the authentication path. + * + * @param [in, out] state LMS state. + * @param [in, out] priv_key Private key information. + * @param [in] levels Number of level to start at. + * @return 0 on success. + */ +static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, + byte* priv_raw, int levels) +{ + const LmsParams* params = state->params; + int ret = 0; + byte* priv = priv_key->priv + LMS_PRIV_LEN * (levels - 1); + int i; +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + w64wrapper q64; +#endif + + (void)priv_raw; +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + ato64(priv_raw, &q64); +#endif + + for (i = levels - 1; (ret == 0) && (i >= 0); i--) { + word32 q; + const byte* priv_q = priv; + const byte* priv_seed = priv_q + LMS_Q_LEN; + const byte* priv_i = priv_seed + LMS_SEED_LEN; + LmsPrivState* privState = &priv_key->state[i]; + + /* Get q for tree at level. */ + ato32(priv_q, &q); + #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + + if ((levels > 1) && (i == levels - 1) && (q == 0)) { + /* New sub-tree. */ + ret = wc_hss_next_subtree_inc(state, priv_key, q64); + } + if ((ret == 0) && (q != 0)) + #else + if (q == 0) { + /* New sub-tree. */ + ret = wc_lms_treehash_init(state, privState, priv_i, priv_seed, 0); + } + else + #endif + { + word32 maxq = q - 1; + int h; + int maxh = params->height; + + /* Check each index at each height needed for the auth path. */ + for (h = 0; (h < maxh) && (h <= maxh - params->rootLevels); h++) { + /* Calculate the index for current q and q-1. */ + word32 qa = LMS_AUTH_PATH_IDX(q, h); + word32 qm1a = LMS_AUTH_PATH_IDX(q - 1, h); + /* If different then needs to be computed so keep highest. */ + if ((qa != qm1a) && (qa > maxq)) { + maxq = qa; + } + } + for (; h < maxh; h++) { + /* Calculate the index for current q and q-1. */ + word32 qa = LMS_AUTH_PATH_IDX(q, h); + word32 qm1a = LMS_AUTH_PATH_IDX(q - 1, h); + /* If different then copy in cached hash. */ + if ((qa != qm1a) && (qa > maxq)) { + int off = (1 << (params->height - h)) + (qa >> h) - 1; + XMEMCPY(privState->auth_path + h * LMS_MAX_NODE_LEN, + privState->root + off * LMS_MAX_NODE_LEN, + LMS_MAX_NODE_LEN); + } + } + /* Update the treehash and calculate the extra indices for + * authentication path. */ + ret = wc_lms_treehash_update(state, privState, priv_i, priv_seed, + q - 1, maxq, q, 1); + #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + if ((ret == 0) && (i > 0)) { + w64wrapper tmp64 = w64ShiftRight(q64, + (levels - i) * params->height); + w64Increment(&tmp64); + tmp64 = w64ShiftLeft(tmp64, 64 - (i * params->height)); + if (!w64IsZero(tmp64)) { + priv_seed = priv_key->next_priv + i * LMS_PRIV_LEN + + LMS_Q_LEN; + priv_i = priv_seed + LMS_SEED_LEN; + privState = &priv_key->next_state[i - 1]; + + ret = wc_lms_treehash_update(state, privState, priv_i, + priv_seed, q, q, 0, 0); + } + } + #endif + break; + } + + /* Move onto next level's data. */ + priv -= LMS_PRIV_LEN; + } + + return ret; +} + +#if !defined(WOLFSSL_LMS_NO_SIG_CACHE) && (LMS_MAX_LEVELS > 1) +/* Pre-sign for current q so that it isn't needed in signing. + * + * @param [in, out] state LMS state. + * @param [in, out] priv_key Private key. + */ +static int wc_hss_presign(LmsState* state, HssPrivKey* priv_key) +{ + int ret = 0; + const LmsParams* params = state->params; + byte* buffer = state->buffer; + byte pub[LMS_PUBKEY_LEN]; + byte* root = pub + LMS_PUBKEY_LEN - LMS_MAX_NODE_LEN; + byte* priv = priv_key->priv; + int i; + + for (i = params->levels - 2; i >= 0; i--) { + const byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + const byte* priv_q = p; + const byte* priv_seed = priv_q + LMS_Q_LEN; + const byte* priv_i = priv_seed + LMS_SEED_LEN; + + /* ... || T(1) */ + XMEMCPY(root, priv_key->state[i + 1].root, LMS_MAX_NODE_LEN); + /* u32str(type) || u32str(otstype) || I || T(1) */ + p = priv + (i + 1) * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + wc_lmots_public_key_encode(params, p, pub); + + /* Setup for hashing: I || Q || ... */ + XMEMCPY(buffer, priv_i, LMS_I_LEN); + XMEMCPY(buffer + LMS_I_LEN, priv_q, LMS_Q_LEN); + + /* LM-OTS Sign this level. */ + ret = wc_lmots_sign(state, priv_seed, pub, LMS_PUBKEY_LEN, + priv_key->y + i * LMS_PRIV_Y_TREE_LEN(params->p)); + } + + return ret; +} +#endif /* !WOLFSSL_LMS_NO_SIG_CACHE && LMS_MAX_LEVELS > 1 */ +#endif /* !WOLFSSL_WC_LMS_SMALL */ + +/* Load the private key data into HSS private key structure. + * + * @param [in] params LMS parameters. + * @param [in, out] key HSS private key. + * @param [in] priv_data Private key data. + */ +static void wc_hss_priv_data_load(const LmsParams* params, HssPrivKey* key, + byte* priv_data) +{ +#ifndef WOLFSSL_WC_LMS_SMALL + int l; +#endif + + /* Expanded private keys. */ + key->priv = priv_data; + priv_data += LMS_PRIV_KEY_LEN(params->levels); + +#ifndef WOLFSSL_WC_LMS_SMALL + for (l = 0; l < params->levels; l++) { + /* Caches for subtree. */ + wc_lms_priv_state_load(params, &key->state[l], priv_data); + priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, + params->cacheBits); + } + +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + /* Next subtree's expanded private keys. */ + key->next_priv = priv_data; + priv_data += LMS_PRIV_KEY_LEN(params->levels); + for (l = 0; l < params->levels - 1; l++) { + /* Next subtree's caches. */ + wc_lms_priv_state_load(params, &key->next_state[l], priv_data); + priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, + params->cacheBits); + } +#endif /* WOLFSSL_LMS_NO_SIGN_SMOOTHING */ + +#ifndef WOLFSSL_LMS_NO_SIG_CACHE + /* Signature cache. */ + key->y = priv_data; +#endif /* WOLFSSL_LMS_NO_SIG_CACHE */ +#endif /* WOLFSSL_WC_LMS_SMALL */ +} + +#ifndef WOLFSSL_WC_LMS_SMALL +/* Store the private key data from HSS private key structure. + * + * @param [in] params LMS parameters. + * @param [in] key HSS private key. + * @param [in, out] priv_data Private key data. + */ +static void wc_hss_priv_data_store(const LmsParams* params, HssPrivKey* key, + byte* priv_data) +{ + int l; + + (void)key; + + /* Expanded private keys. */ + priv_data += LMS_PRIV_KEY_LEN(params->levels); + + for (l = 0; l < params->levels; l++) { + /* Caches for subtrees. */ + wc_lms_priv_state_store(params, &key->state[l], priv_data); + priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, + params->cacheBits); + } +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + /* Next subtree's expanded private keys. */ + priv_data += LMS_PRIV_KEY_LEN(params->levels); + for (l = 0; l < params->levels - 1; l++) { + /* Next subtree's caches. */ + wc_lms_priv_state_store(params, &key->next_state[l], priv_data); + priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, + params->cacheBits); + } +#endif /* WOLFSSL_LMS_NO_SIGN_SMOOTHING */ + +#ifndef WOLFSSL_LMS_NO_SIG_CACHE + /* Signature cache. */ +#endif /* WOLFSSL_LMS_NO_SIG_CACHE */ +} +#endif /* WOLFSSL_WC_LMS_SMALL */ + +/* Expand private key for each level and calculating auth path.. + * + * @param [in, out] state LMS state. + * @param [in] priv_raw Raw private key bytes. + * @param [out] priv_key Private key data. + * @param [out] priv_data Private key data. + * @param [out] pub_root Public key root node. + * @return 0 on success. + */ +int wc_hss_reload_key(LmsState* state, const byte* priv_raw, + HssPrivKey* priv_key, byte* priv_data, byte* pub_root) +{ + int ret; + + (void)pub_root; + + wc_hss_priv_data_load(state->params, priv_key, priv_data); +#ifndef WOLFSSL_WC_LMS_SMALL + priv_key->inited = 0; +#endif + + /* Expand the raw private key into the private key data. */ + ret = wc_hss_expand_private_key(state, priv_key->priv, priv_raw, 0); +#ifndef WOLFSSL_WC_LMS_SMALL + if ((ret == 0) && (!priv_key->inited)) { + /* Initialize the authentication paths and caches for all trees. */ + ret = wc_hss_init_auth_path(state, priv_key, pub_root); + #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + if (ret == 0) { + ret = wc_hss_next_subtrees_init(state, priv_key); + } + #endif + #if !defined(WOLFSSL_LMS_NO_SIG_CACHE) && (LMS_MAX_LEVELS > 1) + if (ret == 0) { + /* Calculate signatures for trees not at bottom. */ + ret = wc_hss_presign(state, priv_key); + } + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + /* Set initialized flag. */ + priv_key->inited = (ret == 0); + } +#endif /* WOLFSSL_WC_LMS_SMALL */ + + return ret; +} + +/* Make an HSS key pair. + * + * @param [in, out] state LMS state. + * @param [in] rng Random number generator. + * @param [out] priv_raw Private key to write. + * @param [out] priv_key Private key. + * @param [out] priv_data Private key data. + * @param [out] pub Public key. + * @return 0 on success. + */ +int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, + HssPrivKey* priv_key, byte* priv_data, byte* pub) +{ + const LmsParams* params = state->params; + int ret = 0; + int i; + byte* p = priv_raw; + byte* pub_root = pub + LMS_L_LEN + LMS_TYPE_LEN + LMS_TYPE_LEN + LMS_I_LEN; + + /* The 64-bit q starts at 0 - set into raw private key. */ + wc_lms_idx_zero(p, HSS_Q_LEN); + p += HSS_Q_LEN; + + /* Set the LMS and LM-OTS types for each level. */ + for (i = 0; i < params->levels; i++) { + p[i] = (params->lmsType << 4) + params->lmOtsType; + } + /* Set rest of levels to an invalid value. */ + for (; i < HSS_MAX_LEVELS; i++) { + p[i] = 0xff; + } + p += HSS_PRIV_KEY_PARAM_SET_LEN; + + /* Make the private key. */ + ret = wc_lmots_make_private_key(rng, p); + + if (ret == 0) { + /* Set the levels into the public key data. */ + c32toa(params->levels, pub); + pub += LMS_L_LEN; + + ret = wc_hss_reload_key(state, priv_raw, priv_key, priv_data, pub_root); + } + #ifdef WOLFSSL_WC_LMS_SMALL + if (ret == 0) { + byte* priv_seed = priv_key->priv + LMS_Q_LEN; + byte* priv_i = priv_seed + LMS_SEED_LEN; + + /* Compute the root of the highest tree to get the root for public key. + */ + ret = wc_lms_make_public_key(state, priv_i, priv_seed, pub_root); + } + #endif /* !WOLFSSL_WC_LMS_SMALL */ + if (ret == 0) { + /* Encode the public key with remaining fields from the private key. */ + wc_lmots_public_key_encode(params, priv_key->priv, pub); + } + + return ret; +} + +#ifdef WOLFSSL_WC_LMS_SMALL +/* Sign message using HSS. + * + * Algorithm 8: Generating an HSS signature + * 1. If the message-signing key prv[L-1] is exhausted, regenerate + * that key pair, together with any parent key pairs that might + * be necessary. + * If the root key pair is exhausted, then the HSS key pair is + * exhausted and MUST NOT generate any more signatures. + * d = L + * while (prv[d-1].q == 2^(prv[d-1].h)) { + * d = d - 1 + * if (d == 0) + * return FAILURE + * } + * while (d < L) { + * create lms key pair pub[d], prv[d] + * sig[d-1] = lms_signature( pub[d], prv[d-1] ) + * d = d + 1 + * } + * 2. Sign the message. + * sig[L-1] = lms_signature( msg, prv[L-1] ) + * 3. Create the list of signed public keys. + * i = 0; + * while (i < L-1) { + * signed_pub_key[i] = sig[i] || pub[i+1] + * i = i + 1 + * } + * 4. Return u32str(L-1) || signed_pub_key[0] || ... + * || signed_pub_key[L-2] || sig[L-1] + * + * @param [in, out] state LMS state. + * @param [in, out] priv_raw Raw private key bytes. + * @param [in, out] priv_key Private key data. + * @param [in] msg Message to sign. + * @param [in] msgSz Length of message in bytes. + * @param [out] sig Signature of message. + * @return 0 on success. + */ +int wc_hss_sign(LmsState* state, byte* priv_raw, HssPrivKey* priv_key, + byte* priv_data, const byte* msg, word32 msgSz, byte* sig) +{ + const LmsParams* params = state->params; + int ret = 0; + byte* priv = priv_key->priv; + + (void)priv_data; + + /* Step 1. Part 2: Check for total key exhaustion. */ + if (!wc_hss_sigsleft(params, priv_raw)) { + ret = KEY_EXHAUSTED_E; + } + + if (ret == 0) { + /* Expand the raw private key into the private key data. */ + ret = wc_hss_expand_private_key(state, priv, priv_raw, 0); + } + if (ret == 0) { + int i; + w64wrapper q; + w64wrapper qm1; + + /* Get 64-bit q from raw private key. */ + ato64(priv_raw, &q); + /* Calculate q-1 for comparison. */ + qm1 = q; + w64Decrement(&qm1); + + /* Set number of signed public keys. */ + c32toa(params->levels - 1, sig); + sig += params->sig_len; + + /* Build from bottom up. */ + for (i = params->levels - 1; (ret == 0) && (i >= 0); i--) { + byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + byte* root = NULL; + + /* Move to start of next signature at this level. */ + sig -= LMS_SIG_LEN(params->height, params->p); + if (i != 0) { + /* Put root node into signature at this index. */ + root = sig - LMS_MAX_NODE_LEN; + } + + /* Sign using LMS for this level. */ + ret = wc_lms_sign(state, p, msg, msgSz, sig); + if (ret == 0) { + byte* s = sig + LMS_Q_LEN + LMS_TYPE_LEN + LMS_MAX_NODE_LEN + + params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN; + byte* priv_q = p; + byte* priv_seed = priv_q + LMS_Q_LEN; + byte* priv_i = priv_seed + LMS_SEED_LEN; + word32 q32; + + /* Get Q from private key as a number. */ + ato32(priv_q, &q32); + /* Calculate authentication path. */ + ret = wc_lms_auth_path(state, priv_i, priv_seed, q32, s, root); + } + if ((ret == 0) && (i != 0)) { + /* Create public data for this level if there is another. */ + sig -= LMS_PUBKEY_LEN; + msg = sig; + msgSz = LMS_PUBKEY_LEN; + wc_lmots_public_key_encode(params, p, sig); + } + } + } + if (ret == 0) { + /* Increment index of leaf node to sign with in raw data. */ + wc_lms_idx_inc(priv_raw, HSS_Q_LEN); + } + + return ret; +} +#else +/* Build signature for HSS signed message. + * + * Algorithm 8: Generating an HSS signature + * 1. ... + * while (prv[d-1].q == 2^(prv[d-1].h)) { + * d = d - 1 + * if (d == 0) + * return FAILURE + * } + * while (d < L) { + * create lms key pair pub[d], prv[d] + * sig[d-1] = lms_signature( pub[d], prv[d-1] ) + * d = d + 1 + * } + * 2. Sign the message. + * sig[L-1] = lms_signature( msg, prv[L-1] ) + * 3. Create the list of signed public keys. + * i = 0; + * while (i < L-1) { + * signed_pub_key[i] = sig[i] || pub[i+1] + * i = i + 1 + * } + * 4. Return u32str(L-1) || signed_pub_key[0] || ... + * || signed_pub_key[L-2] || sig[L-1] + * + * @param [in, out] state LMS state. + * @param [in, out] priv_raw Raw private key bytes. + * @param [in, out] priv_key Private key data. + * @param [in] msg Message to sign. + * @param [in] msgSz Length of message in bytes. + * @param [out] sig Signature of message. + * @return 0 on success. + */ +static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, + HssPrivKey* priv_key, const byte* msg, word32 msgSz, byte* sig) +{ + const LmsParams* params = state->params; + int ret = 0; + int i; + w64wrapper q; + w64wrapper qm1; + byte* priv = priv_key->priv; + + /* Get 64-bit q from raw private key. */ + ato64(priv_raw, &q); + /* Calculate q-1 for comparison. */ + qm1 = q; + w64Decrement(&qm1); + + /* Set number of signed public keys. */ + c32toa(params->levels - 1, sig); + sig += params->sig_len; + + /* Build from bottom up. */ + for (i = params->levels - 1; (ret == 0) && (i >= 0); i--) { + byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + byte* root = NULL; + #ifndef WOLFSSL_LMS_NO_SIG_CACHE + int store_p = 0; + word32 q_32 = LMS_Q_AT_LEVEL(q, params->levels, i, + params->height); + word32 qm1_32 = LMS_Q_AT_LEVEL(qm1, params->levels, i, + params->height); + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + + /* Move to start of next signature at this level. */ + sig -= LMS_SIG_LEN(params->height, params->p); + if (i != 0) { + /* Put root node into signature at this index. */ + root = sig - LMS_MAX_NODE_LEN; + } + + #ifndef WOLFSSL_LMS_NO_SIG_CACHE + /* Check if we have a cached version of C and the p hashes that we + * can reuse. */ + if ((i < params->levels - 1) && (q_32 == qm1_32)) { + wc_lms_sig_copy(params, priv_key->y + + i * LMS_PRIV_Y_TREE_LEN(params->p), p, sig); + } + else + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + { + /* Sign using LMS for this level. */ + ret = wc_lms_sign(state, p, msg, msgSz, sig); + #ifndef WOLFSSL_LMS_NO_SIG_CACHE + store_p = (i < params->levels - 1); + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + } + if (ret == 0) { + byte* s = sig + LMS_Q_LEN + LMS_TYPE_LEN; + + #ifndef WOLFSSL_LMS_NO_SIG_CACHE + /* Check if we computed new C and p hashes. */ + if (store_p) { + /* Cache the C and p hashes. */ + XMEMCPY(priv_key->y + i * LMS_PRIV_Y_TREE_LEN(params->p), s, + LMS_PRIV_Y_TREE_LEN(params->p)); + } + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + s += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + + LMS_TYPE_LEN; + + /* Copy the authentication path out of the private key. */ + XMEMCPY(s, priv_key->state[i].auth_path, + params->height * LMS_MAX_NODE_LEN); + /* Copy the root node into signature unless at top. */ + if (i != 0) { + XMEMCPY(root, priv_key->state[i].root, LMS_MAX_NODE_LEN); + } + } + if ((ret == 0) && (i != 0)) { + /* Create public data for this level if there is another. */ + sig -= LMS_PUBKEY_LEN; + msg = sig; + msgSz = LMS_PUBKEY_LEN; + wc_lmots_public_key_encode(params, p, sig); + } + } + + return ret; +} + +/* Sign message using HSS. + * + * Algorithm 8: Generating an HSS signature + * 1. If the message-signing key prv[L-1] is exhausted, regenerate + * that key pair, together with any parent key pairs that might + * be necessary. + * If the root key pair is exhausted, then the HSS key pair is + * exhausted and MUST NOT generate any more signatures. + * d = L + * while (prv[d-1].q == 2^(prv[d-1].h)) { + * d = d - 1 + * if (d == 0) + * return FAILURE + * } + * while (d < L) { + * create lms key pair pub[d], prv[d] + * sig[d-1] = lms_signature( pub[d], prv[d-1] ) + * d = d + 1 + * } + * 2. Sign the message. + * sig[L-1] = lms_signature( msg, prv[L-1] ) + * 3. Create the list of signed public keys. + * i = 0; + * while (i < L-1) { + * signed_pub_key[i] = sig[i] || pub[i+1] + * i = i + 1 + * } + * 4. Return u32str(L-1) || signed_pub_key[0] || ... + * || signed_pub_key[L-2] || sig[L-1] + * + * @param [in, out] state LMS state. + * @param [in, out] priv_raw Raw private key bytes. + * @param [in, out] priv_key Private key data. + * @param [in, out] priv_data Private key data. + * @param [in] msg Message to sign. + * @param [in] msgSz Length of message in bytes. + * @param [out] sig Signature of message. + * @return 0 on success. + */ +int wc_hss_sign(LmsState* state, byte* priv_raw, HssPrivKey* priv_key, + byte* priv_data, const byte* msg, word32 msgSz, byte* sig) +{ + const LmsParams* params = state->params; + int ret = 0; + + /* Validate fixed parameters for static code analyzers. */ + if ((params->rootLevels == 0) || (params->rootLevels > params->height)) { + ret = BAD_FUNC_ARG; + } + + /* Step 1. Part 2: Check for total key exhaustion. */ + if ((ret == 0) && (!wc_hss_sigsleft(params, priv_raw))) { + ret = KEY_EXHAUSTED_E; + } + + if ((ret == 0) && (!priv_key->inited)) { + /* Initialize the authentication paths and caches for all trees. */ + ret = wc_hss_init_auth_path(state, priv_key, NULL); + #if !defined(WOLFSSL_LMS_NO_SIG_CACHE) && (LMS_MAX_LEVELS > 1) + if (ret == 0) { + ret = wc_hss_presign(state, priv_key); + } + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ + /* Set initialized flag. */ + priv_key->inited = (ret == 0); + } + if (ret == 0) { + ret = wc_hss_sign_build_sig(state, priv_raw, priv_key, msg, msgSz, sig); + } + if (ret == 0) { + /* Increment index of leaf node to sign with in raw data. */ + wc_lms_idx_inc(priv_raw, HSS_Q_LEN); + } + /* Check we will produce another signature. */ + if ((ret == 0) && wc_hss_sigsleft(params, priv_raw)) { + /* Update the expanded private key data. */ + ret = wc_hss_expand_private_key(state, priv_key->priv, priv_raw, 1); + if (ret == 0) { + /* Update authentication path and caches for all trees. */ + ret = wc_hss_update_auth_path(state, priv_key, priv_raw, + params->levels); + } + } + if (ret == 0) { + /* Store the updated private key data. */ + wc_hss_priv_data_store(state->params, priv_key, priv_data); + } + + return ret; +} +#endif + +/* Check whether key is exhausted. + * + * First 8 bytes of raw key is the index. + * Check index is less than count of leaf nodes. + * + * @param [in] params LMS parameters. + * @param [in] priv_raw HSS raw private key. + * @return 1 when signature possible. + * @return 0 when private key exhausted. + */ +int wc_hss_sigsleft(const LmsParams* params, const byte* priv_raw) +{ + w64wrapper q; + w64wrapper cnt; + + /* Get current q - next leaf index to sign with. */ + ato64(priv_raw, &q); + /* 1 << total_height = total leaf nodes. */ + cnt = w64ShiftLeft(w64From32(0, 1), params->levels * params->height); + /* Check q is less than total leaf node count. */ + return w64LT(q, cnt); +} +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + +/* Verify message using HSS. + * + * Section 6.3. Signature Verification + * 1. Nspk = strTou32(first four bytes of S) + * 2. if Nspk+1 is not equal to the number of levels L in pub: + * 3. return INVALID + * 4. key = pub + * 5. for (i = 0; i < Nspk; i = i + 1) { + * 6. sig = siglist[i] + * 7. msg = publist[i] + * 8. if (lms_verify(msg, key, sig) != VALID): + * 9. return INVALID + * 10. key = msg + * 11. } + * 12. return lms_verify(message, key, siglist[Nspk]) + * + * @param [in, out] state LMS state. + * @param [in] pub HSS public key. + * @param [in] msg Message to rifyn. + * @param [in] msgSz Length of message in bytes. + * @param [in] sig Signature of message. + * @return 0 on success. + * @return SIG_VERFIY_E on failure. + */ +int wc_hss_verify(LmsState* state, const byte* pub, const byte* msg, + word32 msgSz, const byte* sig) +{ + const LmsParams* params = state->params; + int ret = 0; + word32 nspk; + const byte* key = pub + LMS_L_LEN; + word32 levels; + + /* Get number of levels from public key. */ + ato32(pub, &levels); + /* Line 1: Get number of signed public keys from signature. */ + ato32(sig, &nspk); + /* Line 6 (First iteration): Move to start of next signature. */ + sig += LMS_L_LEN; + + /* Line 2: Verify that pub and signature match in levels. */ + if (nspk + 1 != levels) { + /* Line 3: Return invalid signature. */ + ret = SIG_VERIFY_E; + } + if (ret == 0) { + word32 i; + + /* Line 5: For all but last LMS signature. */ + for (i = 0; (ret == 0) && (i < nspk); i++) { + /* Line 7: Get start of public key in signature. */ + const byte* pubList = sig + LMS_Q_LEN + LMS_TYPE_LEN + + LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN + + params->height * LMS_MAX_NODE_LEN; + /* Line 8: Verify the LMS signature with public key as message. */ + ret = wc_lms_verify(state, key, pubList, LMS_PUBKEY_LEN, sig); + /* Line 10: Next key is from signature. */ + key = pubList; + /* Line 6: Move to start of next signature. */ + sig = pubList + LMS_PUBKEY_LEN; + } + } + if (ret == 0) { + /* Line 12: Verify bottom tree with real message. */ + ret = wc_lms_verify(state, key, msg, msgSz, sig); + } + + return ret; +} + +#endif /* WOLFSSL_HAVE_LMS && WOLFSSL_WC_LMS */ + diff --git a/src/wolfcrypt/src/wc_pkcs11.c b/src/wolfcrypt/src/wc_pkcs11.c index 0d7bd6e..e248d8e 100644 --- a/src/wolfcrypt/src/wc_pkcs11.c +++ b/src/wolfcrypt/src/wc_pkcs11.c @@ -1355,7 +1355,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) int keyType; ret = Pkcs11HmacTypes(hmac->macType, &mechType, &keyType); - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) break; if (ret == 0) @@ -1367,7 +1367,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) (unsigned char*)hmac->id, hmac->idLen, hmac->label, hmac->labelLen, CKA_SIGN); - if (ret == WC_HW_E) { + if (ret == WC_NO_ERR_TRACE(WC_HW_E)) { ret = Pkcs11CreateSecretKey(&privKey, &session, CKK_GENERIC_SECRET, (unsigned char*)hmac->keyRaw, @@ -1414,7 +1414,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) } } #endif - if (ret == 0 || ret == NOT_COMPILED_IN) { + if (ret == 0 || ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { /* Try ECDSA mechanism next. */ ret2 = Pkcs11MechAvail(&session, CKM_ECDSA); if (ret2 == 0) { @@ -1428,7 +1428,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) } } /* OK for this to fail if set for ECDH. */ - if (ret == NOT_COMPILED_IN) + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) ret = ret2; } if (ret == 0 && clear) @@ -2514,7 +2514,7 @@ static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info) PRIVATE_KEY_UNLOCK(); ret = wc_ecc_export_x963(info->pk.ecdh.public_key, NULL, &pointLen); PRIVATE_KEY_LOCK(); - if (ret == LENGTH_ONLY_E) { + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { point = (unsigned char*)XMALLOC(pointLen, info->pk.ecdh.public_key->heap, DYNAMIC_TYPE_ECC_BUFFER); @@ -3604,7 +3604,7 @@ static int Pkcs11Hmac(Pkcs11Session* session, wc_CryptoInfo* info) ret = Pkcs11CreateSecretKey(&key, session, keyType, (unsigned char*)hmac->keyRaw, hmac->keyLen, NULL, 0, NULL, 0, CKA_SIGN); - if (ret == WC_HW_E) { + if (ret == WC_NO_ERR_TRACE(WC_HW_E)) { ret = Pkcs11CreateSecretKey(&key, session, CKK_GENERIC_SECRET, (unsigned char*)hmac->keyRaw, hmac->keyLen, NULL, 0, NULL, 0, CKA_SIGN); @@ -3614,7 +3614,7 @@ static int Pkcs11Hmac(Pkcs11Session* session, wc_CryptoInfo* info) else if (ret == 0 && hmac->labelLen != 0) { ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, keyType, session, hmac->label, hmac->labelLen); - if (ret == WC_HW_E) { + if (ret == WC_NO_ERR_TRACE(WC_HW_E)) { ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, CKK_GENERIC_SECRET, session, hmac->label, hmac->labelLen); @@ -3623,7 +3623,7 @@ static int Pkcs11Hmac(Pkcs11Session* session, wc_CryptoInfo* info) else if (ret == 0) { ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, keyType, session, hmac->id, hmac->idLen); - if (ret == WC_HW_E) { + if (ret == WC_NO_ERR_TRACE(WC_HW_E)) { ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, CKK_GENERIC_SECRET, session, hmac->id, hmac->idLen); diff --git a/src/wolfcrypt/src/wc_port.c b/src/wolfcrypt/src/wc_port.c index a21cc2b..32ffb9e 100644 --- a/src/wolfcrypt/src/wc_port.c +++ b/src/wolfcrypt/src/wc_port.c @@ -1303,9 +1303,8 @@ int wolfSSL_CryptHwMutexInit(void) } int wolfSSL_CryptHwMutexLock(void) { - int ret = BAD_MUTEX_E; /* Make sure HW Mutex has been initialized */ - ret = wolfSSL_CryptHwMutexInit(); + int ret = wolfSSL_CryptHwMutexInit(); if (ret == 0) { ret = wc_LockMutex(&wcCryptHwMutex); } @@ -1313,11 +1312,12 @@ int wolfSSL_CryptHwMutexLock(void) } int wolfSSL_CryptHwMutexUnLock(void) { - int ret = BAD_MUTEX_E; if (wcCryptHwMutexInit) { - ret = wc_UnLockMutex(&wcCryptHwMutex); + return wc_UnLockMutex(&wcCryptHwMutex); + } + else { + return BAD_MUTEX_E; } - return ret; } #endif /* WOLFSSL_CRYPT_HW_MUTEX */ @@ -1699,9 +1699,8 @@ int wolfSSL_CryptHwMutexUnLock(void) int maxq_CryptHwMutexTryLock() { - int ret = BAD_MUTEX_E; /* Make sure HW Mutex has been initialized */ - ret = wolfSSL_CryptHwMutexInit(); + int ret = wolfSSL_CryptHwMutexInit(); if (ret == 0) { ret = maxq_LockMutex(&wcCryptHwMutex, 1); } @@ -3431,7 +3430,8 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) #ifndef SINGLE_THREADED /* Environment-specific multi-thread implementation check */ -#if defined(USE_WINDOWS_API) && !defined(WOLFSSL_PTHREADS) +#if defined(USE_WINDOWS_API) && !defined(WOLFSSL_PTHREADS) && \ + !defined(_WIN32_WCE) int wolfSSL_NewThread(THREAD_TYPE* thread, THREAD_CB cb, void* arg) { @@ -3646,7 +3646,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) "wolfSSL thread", (entry_functionType)cb, (ULONG)arg, thread->threadStack, - TESTSUITE_THREAD_STACK_SZ, + WOLFSSL_NETOS_STACK_SZ, 2, 2, 1, TX_AUTO_START); if (result != TX_SUCCESS) { @@ -3668,11 +3668,13 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) #elif defined(WOLFSSL_ZEPHYR) + void* wolfsslThreadHeapHint = NULL; + int wolfSSL_NewThread(THREAD_TYPE* thread, THREAD_CB cb, void* arg) { #ifndef WOLFSSL_ZEPHYR_STACK_SZ - #define WOLFSSL_ZEPHYR_STACK_SZ (24*1024) + #define WOLFSSL_ZEPHYR_STACK_SZ (48*1024) #endif if (thread == NULL || cb == NULL) @@ -3686,10 +3688,12 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) * 0); */ thread->threadStack = (void*)XMALLOC( - Z_KERNEL_STACK_SIZE_ADJUST(WOLFSSL_ZEPHYR_STACK_SZ), 0, - DYNAMIC_TYPE_TMP_BUFFER); - if (thread->threadStack == NULL) + Z_KERNEL_STACK_SIZE_ADJUST(WOLFSSL_ZEPHYR_STACK_SZ), + wolfsslThreadHeapHint, DYNAMIC_TYPE_TMP_BUFFER); + if (thread->threadStack == NULL) { + WOLFSSL_MSG("error: XMALLOC failed"); return MEMORY_E; + } /* k_thread_create does not return any error codes */ /* Casting to k_thread_entry_t should be fine since we just ignore the @@ -3716,7 +3720,8 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) * if (err != 0) * ret = MEMORY_E; */ - XFREE(thread.threadStack, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(thread.threadStack, wolfsslThreadHeapHint, + DYNAMIC_TYPE_TMP_BUFFER); thread.threadStack = NULL; /* No thread resources to free. Everything is stored in thread.tid */ diff --git a/src/wolfcrypt/src/wc_xmss.c b/src/wolfcrypt/src/wc_xmss.c index 545b531..0e63722 100644 --- a/src/wolfcrypt/src/wc_xmss.c +++ b/src/wolfcrypt/src/wc_xmss.c @@ -19,8 +19,1654 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#ifdef HAVE_CONFIG_H + #include +#endif + #include +#include +#include #ifdef WOLFSSL_HAVE_XMSS - #error "Contact wolfSSL to get the implementation of this file" +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + + +/*************************** + * DIGEST init and free. + ***************************/ + +/* Initialize the digest algorithm to use. + * + * @param [in, out] state XMSS/MT state including digest and parameters. + * @return 0 on success. + * @return NOT_COMPILED_IN when digest algorithm not supported. + * @return Other negative when digest algorithm initialization failed. + */ +static int wc_xmss_digest_init(XmssState* state) +{ + int ret; + word8 hash = state->params->hash; + +#ifdef WC_XMSS_SHA256 + if (hash == WC_HASH_TYPE_SHA256) { + ret = wc_InitSha256(&state->digest.sha256); + } + else +#endif +#ifdef WC_XMSS_SHA512 + if (hash == WC_HASH_TYPE_SHA512) { + ret = wc_InitSha512(&state->digest.sha512); + } + else +#endif +#ifdef WC_XMSS_SHAKE128 + if (hash == WC_HASH_TYPE_SHAKE128) { + ret = wc_InitShake128(&state->digest.shake, NULL, INVALID_DEVID); + } + else +#endif +#ifdef WC_XMSS_SHAKE256 + if (hash == WC_HASH_TYPE_SHAKE256) { + ret = wc_InitShake256(&state->digest.shake, NULL, INVALID_DEVID); + } + else +#endif + { + ret = NOT_COMPILED_IN; + } + + return ret; +} +/* Free the digest algorithm. + * + * @param [in, out] state XMSS/MT state including digest and parameters. + */ +static void wc_xmss_digest_free(XmssState* state) +{ + word8 hash = state->params->hash; + +#ifdef WC_XMSS_SHA256 + if (hash == WC_HASH_TYPE_SHA256) { + wc_Sha256Free(&state->digest.sha256); + } + else +#endif +#ifdef WC_XMSS_SHA512 + if (hash == WC_HASH_TYPE_SHA512) { + wc_Sha512Free(&state->digest.sha512); + } + else +#endif +#ifdef WC_XMSS_SHAKE128 + if (hash == WC_HASH_TYPE_SHAKE128) { + wc_Shake128_Free(&state->digest.shake); + } + else +#endif +#ifdef WC_XMSS_SHAKE256 + if (hash == WC_HASH_TYPE_SHAKE256) { + wc_Shake256_Free(&state->digest.shake); + } + else +#endif + { + /* Do nothing. */ + } +} + +/* Initialize the XMSS/MT state. + * + * @param [in, out] state XMSS/MT state including digest and parameters. + * @param [in] params Parameters for key. + * @return 0 on success. + * @return NOT_COMPILED_IN when digest algorithm not supported. + * @return Other negative when digest algorithm initialization failed. + */ +static WC_INLINE int wc_xmss_state_init(XmssState* state, + const XmssParams* params) +{ + state->params = params; + state->ret = 0; + return wc_xmss_digest_init(state); +} + +/* Free the XMSS/MT state. + * + * @param [in, out] state XMSS/MT state including digest and parameters. + */ +static WC_INLINE void wc_xmss_state_free(XmssState* state) +{ + wc_xmss_digest_free(state); +} + + +/*************************** + * XMSS PARAMS + ***************************/ + +/* Map of XMSS/MT string name to OID. + */ +typedef struct wc_XmssString { + /* Name of algorithm as a string. */ + const char* str; + /* OID for algorithm. */ + word32 oid; + /* XMSS parameters. */ + XmssParams params; +} wc_XmssString; + +#ifndef WOLFSSL_WC_XMSS_SMALL + +/* Size of BDS State encoded numbers - offset=1, next=3. */ +#define XMSS_BDS_NUMS_SZ 4 +/* Size of treehash encoding - nextIdx=3, completed|used=1. */ +#define XMSS_TREEHASH_SZ 4 + +/* Calculate Secret key length. + * + * See wc_xmss_bds_state_save() and wc_xmss_bds_state_load(). + * + * SK = idx || wots_sk || SK_PRF || root || SEED || BDSs || OTHER + * BDSs = (2 * depth - 1) * BDS + * BDS = stack || height || authPath || keep || nodes || retain || + * offset || next || TREEHASHes + * TREEHASHes = (Subtree height - BDS k param) * TREEHASH + * TREEHASH = nextIdx || completed || used + * + * @param [in] n Number of bytes to hash output. + * @param [in] h Height of full tree. + * @param [in] d Depth of trees (number of subtrees). + * @param [in] s Subtree height. + * @param [in] i Length of index encoding in bytes. + * @param [in] k BDS k parameter. + * @return Secret key length in bytes. + */ +#define XMSS_SK_LEN(n, h, d, s, i, k) \ + (((i) + 4 * (n)) + \ + (2 * (d) - 1) * (((s) + 1) * (n) + \ + (s) + 1 + \ + (s) * (n) + \ + ((s) >> 1) * (n) + \ + ((s) - (k)) * XMSS_TREEHASH_SZ + \ + ((s) - (k)) * (n) + \ + XMSS_RETAIN_LEN(k, n) + \ + XMSS_BDS_NUMS_SZ) + \ + ((d) - 1) * (n) * ((n) * 2 + 3)) + +#else + +/* Calculate Secret key length. + * + * SK = idx || wots_sk || SK_PRF || root || SEED + * + * @param [in] n Number of bytes to hash output. + * @param [in] h Height of full tree. Unused. + * @param [in] d Depth of trees (number of subtrees). Unused. + * @param [in] s Subtree height. Unused. + * @param [in] i Length of index encoding in bytes. + * @param [in] k BDS k parameter. Unused. + * @return Secret key length. + */ +#define XMSS_SK_LEN(n, h, d, s, i, k) \ + ((i) + 4 * (n)) + +#endif + +#ifndef WOLFSSL_XMSS_LARGE_SECRET_KEY +/* Choose the smaller BDS K parameter. */ +#define XMSS_K(k, kl) (k) +#else +/* Choose the larger BDS K parameter. */ +#define XMSS_K(k, kl) (kl) +#endif + +/* Calculate all fixed parameter values and output an array declaration. + * + * @param [in] hash Hash algorithm to use. + * @param [in] n Number of bytes to hash output. + * @param [in] p Number of bytes of padding. + * @param [in] h Height of full tree. + * @param [in] d Depth of trees (number of subtrees). + * @param [in] i Length of index encoding in bytes. + * @param [in] k BDS k parameter. 0 or >= 2 but (h/d - k) is even. + * @param [in] kl BDS k parameter when large signatures. + * @return XMSS/XMSS^MT parameters array declaration. + */ +#define XMSS_PARAMS(hash, n, p, h, d, i, k, kl) \ + { hash, n, p, (n) * 2 + 3, (n) * ((n) * 2 + 3), h, (h) / (d), (d), (i), \ + (i) + (n) + (d) * (((n) * 2 + 3) * (n)) + (h) * (n), \ + XMSS_SK_LEN(n, h, d, ((h) / (d)), i, XMSS_K(k, kl)), (n) * 2, \ + XMSS_K(k, kl) } + /* hash, d, pad_len, wots_len, wots_sig_len, h, sub_h, d, idx_len, + * sig_len, + * sk_len, pk_len, + * bds_k */ + +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 +/* List of known XMSS algorithm strings and their OIDs. */ +static const wc_XmssString wc_xmss_alg[] = { +#ifdef WC_XMSS_SHA256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHA2_10_256", WC_XMSS_OID_SHA2_10_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHA2_16_256", WC_XMSS_OID_SHA2_16_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHA2_20_256", WC_XMSS_OID_SHA2_20_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHA256 */ +#ifdef WC_XMSS_SHA512 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 512 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 512 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHA2_10_512", WC_XMSS_OID_SHA2_10_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHA2_16_512", WC_XMSS_OID_SHA2_16_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHA2_20_512", WC_XMSS_OID_SHA2_20_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 512 */ +#endif /* WC_XMSS_SHA512 */ + +#ifdef WC_XMSS_SHAKE128 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHAKE_10_256", WC_XMSS_OID_SHAKE_10_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHAKE_16_256", WC_XMSS_OID_SHAKE_16_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHAKE_20_256", WC_XMSS_OID_SHAKE_20_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHAKE128 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 512 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 512 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHAKE_10_512", WC_XMSS_OID_SHAKE_10_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHAKE_16_512", WC_XMSS_OID_SHAKE_16_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHAKE_20_512", WC_XMSS_OID_SHAKE_20_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 512 */ +#endif /* WC_XMSS_SHAKE256 */ + +#ifdef WC_XMSS_SHA256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 192 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 192 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHA2_10_192", WC_XMSS_OID_SHA2_10_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHA2_16_192", WC_XMSS_OID_SHA2_16_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHA2_20_192", WC_XMSS_OID_SHA2_20_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 192 */ +#endif /* WC_XMSS_SHA256 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHAKE256_10_256", WC_XMSS_OID_SHAKE256_10_256, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHAKE256_16_256", WC_XMSS_OID_SHAKE256_16_256, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHAKE256_20_256", WC_XMSS_OID_SHAKE256_20_256, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHAKE256 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 192 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 192 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 10 && WOLFSSL_XMSS_MAX_HEIGHT >= 10 + { "XMSS-SHAKE256_10_192", WC_XMSS_OID_SHAKE256_10_192, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 10, 1, 4, 0, 4), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 16 && WOLFSSL_XMSS_MAX_HEIGHT >= 16 + { "XMSS-SHAKE256_16_192", WC_XMSS_OID_SHAKE256_16_192, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 16, 1, 4, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSS-SHAKE256_20_192", WC_XMSS_OID_SHAKE256_20_192, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 20, 1, 4, 0, 0), }, +#endif +#endif /* HASH_SIZE 192 */ +#endif /* WC_XMSS_SHAKE256 */ +}; +/* Length of array of known XMSS algorithms. */ +#define WC_XMSS_ALG_LEN (sizeof(wc_xmss_alg) / sizeof(*wc_xmss_alg)) +#endif + +/* Convert XMSS algorithm string to an OID - object identifier. + * + * @param [out] oid OID value corresponding to string. + * @param [in] s String to convert. + * @param [out] params XMSS/MT parameters. + * @return 0 on success. + * @return NOT_COMPILED_IN on failure. + */ +static int wc_xmss_str_to_params(const char *s, word32* oid, + const XmssParams** params) +{ + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 + unsigned int i; + + ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); + for (i = 0; i < WC_XMSS_ALG_LEN; i++) { + if (XSTRCMP(s, wc_xmss_alg[i].str) == 0) { + *oid = wc_xmss_alg[i].oid; + *params = &wc_xmss_alg[i].params; + ret = 0; + break; + } + } +#else + (void)s; + (void)oid; + (void)params; + ret = NOT_COMPILED_IN; +#endif + + return ret; +} + +#if WOLFSSL_XMSS_MAX_HEIGHT >= 20 +/* List of known XMSS^MT algorithm strings and their OIDs. */ +static const wc_XmssString wc_xmssmt_alg[] = { +#ifdef WC_XMSS_SHA256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHA2_20/2_256", WC_XMSSMT_OID_SHA2_20_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHA2_20/4_256", WC_XMSSMT_OID_SHA2_20_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHA2_40/2_256", WC_XMSSMT_OID_SHA2_40_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHA2_40/4_256", WC_XMSSMT_OID_SHA2_40_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHA2_40/8_256", WC_XMSSMT_OID_SHA2_40_8_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHA2_60/3_256", WC_XMSSMT_OID_SHA2_60_3_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHA2_60/6_256", WC_XMSSMT_OID_SHA2_60_6_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHA2_60/12_256", WC_XMSSMT_OID_SHA2_60_12_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 32, 32, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHA256 */ +#ifdef WC_XMSS_SHA512 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 512 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 512 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHA2_20/2_512", WC_XMSSMT_OID_SHA2_20_2_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHA2_20/4_512", WC_XMSSMT_OID_SHA2_20_4_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHA2_40/2_512", WC_XMSSMT_OID_SHA2_40_2_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHA2_40/4_512", WC_XMSSMT_OID_SHA2_40_4_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHA2_40/8_512", WC_XMSSMT_OID_SHA2_40_8_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHA2_60/3_512", WC_XMSSMT_OID_SHA2_60_3_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHA2_60/6_512", WC_XMSSMT_OID_SHA2_60_6_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHA2_60/12_512", WC_XMSSMT_OID_SHA2_60_12_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHA512, 64, 64, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 512 */ +#endif /* WC_XMSS_SHA512 */ + +#ifdef WC_XMSS_SHAKE128 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHAKE_20/2_256", WC_XMSSMT_OID_SHAKE_20_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHAKE_20/4_256", WC_XMSSMT_OID_SHAKE_20_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHAKE_40/2_256", WC_XMSSMT_OID_SHAKE_40_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHAKE_40/4_256", WC_XMSSMT_OID_SHAKE_40_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHAKE_40/8_256", WC_XMSSMT_OID_SHAKE_40_8_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHAKE_60/3_256", WC_XMSSMT_OID_SHAKE_60_3_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHAKE_60/6_256", WC_XMSSMT_OID_SHAKE_60_6_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHAKE_60/12_256", WC_XMSSMT_OID_SHAKE_60_12_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE128, 32, 32, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHAKE128 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 512 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 512 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHAKE_20/2_512", WC_XMSSMT_OID_SHAKE_20_2_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHAKE_20/4_512", WC_XMSSMT_OID_SHAKE_20_4_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHAKE_40/2_512", WC_XMSSMT_OID_SHAKE_40_2_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHAKE_40/4_512", WC_XMSSMT_OID_SHAKE_40_4_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHAKE_40/8_512", WC_XMSSMT_OID_SHAKE_40_8_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHAKE_60/3_512", WC_XMSSMT_OID_SHAKE_60_3_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHAKE_60/6_512", WC_XMSSMT_OID_SHAKE_60_6_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHAKE_60/12_512", WC_XMSSMT_OID_SHAKE_60_12_512 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 64, 64, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 512 */ +#endif /* WC_XMSS_SHAKE256 */ + +#ifdef WC_XMSS_SHA256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 192 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 192 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHA2_20/2_192", WC_XMSSMT_OID_SHA2_20_2_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHA2_20/4_192", WC_XMSSMT_OID_SHA2_20_4_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHA2_40/2_192", WC_XMSSMT_OID_SHA2_40_2_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHA2_40/4_192", WC_XMSSMT_OID_SHA2_40_4_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHA2_40/8_192", WC_XMSSMT_OID_SHA2_40_8_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHA2_60/3_192", WC_XMSSMT_OID_SHA2_60_3_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHA2_60/6_192", WC_XMSSMT_OID_SHA2_60_6_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHA2_60/12_192", WC_XMSSMT_OID_SHA2_60_12_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHA256, 24, 4, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 192 */ +#endif /* WC_XMSS_SHA256 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 256 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 256 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHAKE256_20/2_256", WC_XMSSMT_OID_SHAKE256_20_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHAKE256_20/4_256", WC_XMSSMT_OID_SHAKE256_20_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHAKE256_40/2_256", WC_XMSSMT_OID_SHAKE256_40_2_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHAKE256_40/4_256", WC_XMSSMT_OID_SHAKE256_40_4_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHAKE256_40/8_256", WC_XMSSMT_OID_SHAKE256_40_8_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHAKE256_60/3_256", WC_XMSSMT_OID_SHAKE256_60_3_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHAKE256_60/6_256", WC_XMSSMT_OID_SHAKE256_60_6_256 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHAKE256_60/12_256", WC_XMSSMT_OID_SHAKE256_60_12_256, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 32, 32, 60, 12, 8, 0, 0), }, +#endif +#endif /* HASH_SIZE 256 */ +#endif /* WC_XMSS_SHAKE256 */ + +#ifdef WC_XMSS_SHAKE256 +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 192 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 192 +#if WOLFSSL_XMSS_MIN_HEIGHT <= 20 && WOLFSSL_XMSS_MAX_HEIGHT >= 20 + { "XMSSMT-SHAKE256_20/2_192", WC_XMSSMT_OID_SHAKE256_20_2_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 20, 2, 3, 2, 4), }, + { "XMSSMT-SHAKE256_20/4_192", WC_XMSSMT_OID_SHAKE256_20_4_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 20, 4, 3, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 40 && WOLFSSL_XMSS_MAX_HEIGHT >= 40 + { "XMSSMT-SHAKE256_40/2_192", WC_XMSSMT_OID_SHAKE256_40_2_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 40, 2, 5, 2, 4), }, + { "XMSSMT-SHAKE256_40/4_192", WC_XMSSMT_OID_SHAKE256_40_4_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 40, 4, 5, 2, 4), }, + { "XMSSMT-SHAKE256_40/8_192", WC_XMSSMT_OID_SHAKE256_40_8_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 40, 8, 5, 0, 0), }, +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 60 && WOLFSSL_XMSS_MAX_HEIGHT >= 60 + { "XMSSMT-SHAKE256_60/3_192", WC_XMSSMT_OID_SHAKE256_60_3_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 60, 3, 8, 2, 4), }, + { "XMSSMT-SHAKE256_60/6_192", WC_XMSSMT_OID_SHAKE256_60_6_192 , + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 60, 6, 8, 2, 4), }, + { "XMSSMT-SHAKE256_60/12_192", WC_XMSSMT_OID_SHAKE256_60_12_192, + XMSS_PARAMS(WC_HASH_TYPE_SHAKE256, 24, 4, 60, 12, 8, 0, 0), }, #endif +#endif /* HASH_SIZE 192 */ +#endif /* WC_XMSS_SHAKE256 */ +}; +/* Length of array of known XMSS^MT algorithms. */ +#define WC_XMSSMT_ALG_LEN (sizeof(wc_xmssmt_alg) / sizeof(*wc_xmssmt_alg)) +#endif + +/* Convert XMSS^MT algorithm string to an OID - object identifier. + * + * @param [out] oid OID value corresponding to string. + * @param [in] s String to convert. + * @param [out] params XMSS/MT parameters. + * @return 0 on success. + * @return NOT_COMPILED_IN on failure. + */ +static int wc_xmssmt_str_to_params(const char *s, word32* oid, + const XmssParams** params) +{ + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); +#if WOLFSSL_XMSS_MAX_HEIGHT >= 20 + unsigned int i; + + ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); + for (i = 0; i < WC_XMSSMT_ALG_LEN; i++) { + if (XSTRCMP(s, wc_xmssmt_alg[i].str) == 0) { + *oid = wc_xmssmt_alg[i].oid; + *params = &wc_xmssmt_alg[i].params; + ret = 0; + break; + } + } +#else + (void)s; + (void)oid; + (void)params; + ret = NOT_COMPILED_IN; +#endif + + return ret; +} + +/*************************** + * OTHER Internal APIs + ***************************/ + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY +/* Allocates the XMSS secret key (sk) array. + * + * The XMSS/XMSS^MT secret key length is a function of the + * parameters, and can't be allocated until the param string + * has been set with SetParamStr. + * + * This is only called by MakeKey() and Reload(). + * + * Note: the XMSS sk array is force zeroed after every use. + * + * @param [in] key The XMSS key. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_FUNC_ARG when private key already allocated. + * @return MEMORY_E when allocating dynamic memory fails. + */ +static int wc_xmsskey_alloc_sk(XmssKey* key) +{ + int ret = 0; + + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + /* Ensure the private key doesn't exist. */ + else if (key->sk != NULL) { + WOLFSSL_MSG("error: XMSS secret key already exists"); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* The XMSS/XMSS^MT secret key length is a function of the + * parameters. Therefore can't allocate this until param + * string has been set. */ + ret = wc_XmssKey_GetPrivLen(key, &key->sk_len); + } + if (ret == 0) { + /* Allocate a buffer to hold secret key. */ + key->sk = (unsigned char *)XMALLOC(key->sk_len, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (key->sk == NULL) { + WOLFSSL_MSG("error: malloc XMSS key->sk failed"); + ret = MEMORY_E; + } + } + + if (ret == 0) { + /* Zeroize private key buffer. */ + ForceZero(key->sk, key->sk_len); + } + + return ret; +} + +/* Signs the message using the XMSS secret key, and + * updates the secret key on NV storage. + * + * Both operations must succeed to be considered + * successful. + * + * On success: sets key state to WC_XMSS_STATE_OK. + * On failure: sets key state to WC_XMSS_STATE_BAD + * + * If no signatures are left, sets state to WC_XMSS_STATE_NOSIGS. + * + * @return IO_FAILED_E when reading or writing private key failed. + * @return KEY_EXHAUSTED_E when no more keys in private key available. + * @return BAD_COND_E when generated signature length is invalid. + */ +static WC_INLINE int wc_xmsskey_signupdate(XmssKey* key, byte* sig, + const byte* msg, int msgLen) +{ + int ret = 0; + enum wc_XmssRc cb_rc = WC_XMSS_RC_NONE; + + /* Set the key state to bad by default. State is presumed bad unless a + * correct sign and update operation happen together. */ + key->state = WC_XMSS_STATE_BAD; + + /* Read the current secret key from NV storage.*/ + cb_rc = key->read_private_key(key->sk, key->sk_len, key->context); + if (cb_rc != WC_XMSS_RC_READ_TO_MEMORY) { + /* Read from NV storage failed. */ + WOLFSSL_MSG("error: XMSS read_private_key failed"); + ret = IO_FAILED_E; + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + XmssState* state; + #else + XmssState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize state for use in signing. */ + ret = wc_xmss_state_init(state, key->params); + if (ret == 0) { + /* Read was good. Now sign and update the secret key in memory. + */ + #ifndef WOLFSSL_WC_XMSS_SMALL + if (key->is_xmssmt) { + ret = wc_xmssmt_sign(state, msg, msgLen, key->sk, sig); + } + else { + ret = wc_xmss_sign(state, msg, msgLen, key->sk, sig); + } + #else + ret = wc_xmssmt_sign(state, msg, msgLen, key->sk, sig); + #endif + if (ret == WC_NO_ERR_TRACE(KEY_EXHAUSTED_E)) { + /* Signature space exhausted. */ + key->state = WC_XMSS_STATE_NOSIGS; + WOLFSSL_MSG("error: no XMSS signatures remaining"); + } + else if (ret != 0) { + /* Something failed or inconsistent in signature. Erase the + * signature just to be safe. */ + ForceZero(sig, key->params->sig_len); + WOLFSSL_MSG("error: XMSS sign failed"); + } + /* Free state after use. */ + wc_xmss_state_free(state); + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + + if (ret == 0) { + /* The signature succeeded. key->sk is now updated and must be + * committed to NV storage. */ + cb_rc = key->write_private_key(key->sk, key->sk_len, key->context); + if (cb_rc != WC_XMSS_RC_SAVED_TO_NV_MEMORY) { + /* Write to NV storage failed. Erase the signature from + * memory. */ + ForceZero(sig, key->params->sig_len); + WOLFSSL_MSG("error: XMSS write_private_key failed"); + ret = IO_FAILED_E; + } + } + if (ret == 0) { + /* key->sk was successfully committed to NV storage. Set the + * key state to OK, and set the sigLen. */ + key->state = WC_XMSS_STATE_OK; + } + + /* Force zero the secret key from memory always. */ + ForceZero(key->sk, key->sk_len); + + return ret; +} +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + +/*************************** + * PUBLIC API + ***************************/ + +/* Init an XMSS key. + * + * Call this before setting the parms of an XMSS key. + * + * @param [in] key The XMSS key to init. + * @param [in] heap Unused. + * @param [in] devId Unused. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + */ +int wc_XmssKey_Init(XmssKey* key, void* heap, int devId) +{ + int ret = 0; + + (void) heap; + (void) devId; + + /* Validate parameters. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Zeroize key and set state to initialized. */ + ForceZero(key, sizeof(XmssKey)); + key->state = WC_XMSS_STATE_INITED; + } + + return ret; +} + +/* Set the XMSS key parameter string. + * + * The input string must be one of the supported parm set names in + * the "Name" section from the table in wolfssl/wolfcrypt/xmss.h, + * e.g. "XMSS-SHA2_10_256" or "XMSSMT-SHA2_20/4_256". + * + * @param [in] key The XMSS key to set. + * @param [in] str The XMSS/XMSS^MT parameter string. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_FUNC_ARG when string not recognized. + * @return BAD_STATE_E when wrong state for operation. + * @return NOT_COMPILED_IN when string not supported. + */ +int wc_XmssKey_SetParamStr(XmssKey* key, const char* str) +{ + int ret = 0; + word32 oid = 0; + int is_xmssmt = 0; + + /* Validate parameters. */ + if ((key == NULL) || (str == NULL)) { + ret = BAD_FUNC_ARG; + } + + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_INITED)) { + WOLFSSL_MSG("error: XMSS key needs init"); + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Check which type of algorithm the string is for. */ + is_xmssmt = (XMEMCMP(str, "XMSS-", 5) != 0); + + /* Convert XMSS param string to OID. */ + if (is_xmssmt) { + ret = wc_xmssmt_str_to_params(str, &oid, &key->params); + } + else { + ret = wc_xmss_str_to_params(str, &oid, &key->params); + } + if (ret != 0) { + WOLFSSL_MSG("error: xmssmt_str_to_params failed"); + ret = BAD_FUNC_ARG; + } + } + + if (ret == 0) { + /* Set key info. */ + key->oid = oid; + key->is_xmssmt = is_xmssmt; + key->state = WC_XMSS_STATE_PARMSET; + } + + return ret; +} + +/* Force zeros and frees the XMSS key from memory. + * + * This does not touch the private key saved to non-volatile storage. + * + * This is the only function that frees the key->sk array. + * + * @param [in] key XMSS key. + */ +void wc_XmssKey_Free(XmssKey* key) +{ + /* Validate parameter. */ + if (key != NULL) { + #ifndef WOLFSSL_XMSS_VERIFY_ONLY + if (key->sk != NULL) { + /* Zeroize private key. */ + ForceZero(key->sk, key->sk_len); + XFREE(key->sk, NULL, DYNAMIC_TYPE_TMP_BUFFER); + key->sk = NULL; + key->sk_len = 0; + } + #endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + + /* Ensure all data is zeroized. */ + ForceZero(key, sizeof(XmssKey)); + + /* Set the state to freed. */ + key->state = WC_XMSS_STATE_FREED; + } +} + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY +/* Sets the XMSS write private key callback. + * + * The callback must be able to write/update the private key to + * non-volatile storage. + * + * @param [in] key The XMSS key. + * @param [in] write_cb The write private key callback. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + */ +int wc_XmssKey_SetWriteCb(XmssKey* key, wc_xmss_write_private_key_cb write_cb) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (write_cb == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Changing the write callback of an already working key is forbidden. */ + else if (key->state == WC_XMSS_STATE_OK) { + WOLFSSL_MSG("error: wc_XmssKey_SetWriteCb: key in use"); + ret = BAD_STATE_E; + } + else { + /* Set write callback for storing private key. */ + key->write_private_key = write_cb; + } + + return ret; +} + +/* Sets the XMSS read private key callback. + * + * The callback must be able to read the private key from + * non-volatile storage. + * + * @param [in] key The XMSS key. + * @param [in] read_cb The read private key callback. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + */ +int wc_XmssKey_SetReadCb(XmssKey* key, wc_xmss_read_private_key_cb read_cb) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (read_cb == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Changing the read callback of an already working key is forbidden. */ + else if (key->state == WC_XMSS_STATE_OK) { + WOLFSSL_MSG("error: wc_XmssKey_SetReadCb: key in use"); + ret = BAD_STATE_E; + } + else { + /* Set write callback for getting private key. */ + key->read_private_key = read_cb; + } + + return ret; +} + +/* Sets the XMSS context to be used by write and read callbacks. + * + * E.g. this could be a filename if the callbacks write/read to file. + * + * @param [in] key The XMSS key. + * @param [in] context The context pointer. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + */ +int wc_XmssKey_SetContext(XmssKey* key, void* context) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (context == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Setting context of an already working key is forbidden. */ + else if (key->state == WC_XMSS_STATE_OK) { + WOLFSSL_MSG("error: wc_XmssKey_SetContext: key in use"); + ret = BAD_STATE_E; + } + else { + /* Set read/write callback context for accessing the private key. */ + key->context = context; + } + + return ret; +} + +/* Make the XMSS/XMSS^MT private/public key pair. The key must have its + * parameters set before calling this. + * + * Write/read callbacks, and context data, must be set prior. + * Key must have parameters set. + * + * This function and Reload() are the only functions that allocate + * key->sk array. wc_XmssKey_FreeKey is the only function that + * deallocates key->sk. + * + * @param [in] key The XMSS key to make. + * @param [in] rng Initialized WC_RNG pointer. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_FUNC_ARG when a write private key is not set. + * @return BAD_FUNC_ARG when a read/write private key context is not set. + * @return BAD_FUNC_ARG when private key already allocated. + * @return MEMORY_E when allocating dynamic memory fails. + * @return BAD_STATE_E when wrong state for operation. + * @return IO_FAILED_E when writing private key failed. + * @return Other negative when random number generation failed. + */ +int wc_XmssKey_MakeKey(XmssKey* key, WC_RNG* rng) +{ + int ret = 0; + enum wc_XmssRc cb_rc = WC_XMSS_RC_NONE; +#ifdef WOLFSSL_SMALL_STACK + unsigned char* seed = NULL; +#else + unsigned char seed[3 * WC_XMSS_MAX_N]; +#endif + + /* Validate parameters */ + if ((key == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_PARMSET)) { + WOLFSSL_MSG("error: XmssKey not ready for generation"); + ret = BAD_STATE_E; + } + /* Ensure write callback available. */ + if ((ret == 0) && (key->write_private_key == NULL)) { + WOLFSSL_MSG("error: XmssKey write callback is not set"); + ret = BAD_FUNC_ARG; + } + /* Ensure read/write callback context available. */ + if ((ret == 0) && (key->context == NULL)) { + WOLFSSL_MSG("error: XmssKey context is not set"); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Allocate sk array. */ + ret = wc_xmsskey_alloc_sk(key); + } +#ifdef WOLFSSL_SMALL_STACK + if (ret == 0) { + seed = (unsigned char*)XMALLOC(3 * key->params->n, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (seed == NULL) { + ret = MEMORY_E; + } + } +#endif + + if (ret == 0) { + /* Generate three random seeds. */ + ret = wc_RNG_GenerateBlock(rng, seed, 3 * key->params->n); + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + XmssState* state; + #else + XmssState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize state for use in key generation. */ + ret = wc_xmss_state_init(state, key->params); + if (ret == 0) { + /* Finally make the private/public key pair. Immediately write + * it to NV storage and then clear from memory. */ + #ifndef WOLFSSL_WC_XMSS_SMALL + if (key->is_xmssmt) { + ret = wc_xmssmt_keygen(state, seed, key->sk, key->pk); + } + else { + ret = wc_xmss_keygen(state, seed, key->sk, key->pk); + } + #else + ret = wc_xmssmt_keygen(state, seed, key->sk, key->pk); + #endif + if (ret != 0) { + WOLFSSL_MSG("error: XMSS keygen failed"); + key->state = WC_XMSS_STATE_BAD; + } + /* Free state after use. */ + wc_xmss_state_free(state); + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + + if (ret == 0) { + /* Write out private key. */ + cb_rc = key->write_private_key(key->sk, key->sk_len, key->context); + /* Zeroize private key data whether it was saved or not. */ + ForceZero(key->sk, key->sk_len); + /* Check writing succeeded. */ + if (cb_rc != WC_XMSS_RC_SAVED_TO_NV_MEMORY) { + WOLFSSL_MSG("error: XMSS write to NV storage failed"); + key->state = WC_XMSS_STATE_BAD; + ret = IO_FAILED_E; + } + } + + if (ret == 0) { + key->state = WC_XMSS_STATE_OK; + } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return ret; +} + +/* This function allocates the secret key buffer, and does a + * quick sanity check to verify the secret key is readable + * from NV storage, and then force zeros the key from memory. + * + * On success it sets the key state to OK. + * + * Use this function to resume signing with an already existing + * XMSS key pair. + * + * Write/read callbacks, and context data, must be set prior. + * Key must have parameters set. + * + * This function and MakeKey are the only functions that allocate + * key->sk array. wc_XmssKey_FreeKey is the only function that + * deallocates key->sk. + * + * @params [in] key XMSS key to load. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_FUNC_ARG when a read or write function is not set. + * @return BAD_FUNC_ARG when a read/write function context is not set. + * @return BAD_FUNC_ARG when private key already allocated. + * @return MEMORY_E when allocating dynamic memory fails. + * @return BAD_STATE_E when wrong state for operation. + * @return IO_FAILED_E when reading private key failed. + */ +int wc_XmssKey_Reload(XmssKey* key) +{ + int ret = 0; + enum wc_XmssRc cb_rc = WC_XMSS_RC_NONE; + + /* Validate parameter. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_PARMSET)) { + WOLFSSL_MSG("error: XmssKey not ready for reload"); + ret = BAD_STATE_E; + } + /* Ensure read and write callbacks are available. */ + if ((ret == 0) && ((key->write_private_key == NULL) || + (key->read_private_key == NULL))) { + WOLFSSL_MSG("error: XmssKey write/read callbacks are not set"); + ret = BAD_FUNC_ARG; + } + /* Ensure read and write callback context is available. */ + if ((ret == 0) && (key->context == NULL)) { + WOLFSSL_MSG("error: XmssKey context is not set"); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Allocate sk array. */ + ret = wc_xmsskey_alloc_sk(key); + } + + if (ret == 0) { + /* Read the current secret key from NV storage. Force clear it + * immediately. This is just to sanity check the secret key + * is readable from permanent storage. */ + cb_rc = key->read_private_key(key->sk, key->sk_len, key->context); + ForceZero(key->sk, key->sk_len); + /* Check reading succeeded. */ + if (cb_rc != WC_XMSS_RC_READ_TO_MEMORY) { + WOLFSSL_MSG("error: XMSS read from NV storage failed"); + key->state = WC_XMSS_STATE_BAD; + ret = IO_FAILED_E; + } + } + if (ret == 0) { + key->state = WC_XMSS_STATE_OK; + } + + return ret; +} + +/* Gets the XMSS/XMSS^MT private key length. + * + * Parameters must be set before calling this, as the key size (sk_len) + * is a function of the parameters. + * + * Note: the XMSS/XMSS^MT private key format is implementation specific, + * and not standardized. Interoperability of XMSS private keys should + * not be expected. + * + * @param [in] key XMSS key. + * @param [out] len Length of the private key in bytes. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + * */ +int wc_XmssKey_GetPrivLen(const XmssKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && ((key->state != WC_XMSS_STATE_OK) && + (key->state != WC_XMSS_STATE_PARMSET))) { + /* params->sk_len not set yet. */ + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Calculate private key length: OID + private key bytes. */ + *len = XMSS_OID_LEN + (word32)key->params->sk_len; + } + + return ret; +} + +/* Sign the message using the XMSS secret key. + * + * @param [in] key XMSS key to use to sign. + * @param [in] sig Buffer to write signature into. + * @param [in, out] sigLen On in, size of buffer. + * On out, the length of the signature in bytes. + * @param [in] msg Message to sign. + * @param [in] msgLen Length of the message in bytes. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_FUNC_ARG when a write private key is not set. + * @return BAD_FUNC_ARG when a read/write private key context is not set. + * @return BAD_STATE_E when wrong state for operation. + * @return BUFFER_E when sigLen is too small. + * @return IO_FAILED_E when reading or writing private key failed. + * @return KEY_EXHAUSTED_E when no more keys in private key available. + * @return BAD_COND_E when generated signature length is invalid. + */ +int wc_XmssKey_Sign(XmssKey* key, byte* sig, word32* sigLen, const byte* msg, + int msgLen) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (sigLen == NULL) || (msg == NULL) || + (msgLen <= 0)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state == WC_XMSS_STATE_NOSIGS)) { + WOLFSSL_MSG("error: XMSS signatures exhausted"); + ret = BAD_STATE_E; + } + if ((ret == 0) && (key->state != WC_XMSS_STATE_OK)) { + /* The key had an error the last time it was used, and we + * can't guarantee its state. */ + WOLFSSL_MSG("error: can't sign, XMSS key not in good state"); + ret = BAD_STATE_E; + } + /* Check signature buffer size. */ + if ((ret == 0) && (*sigLen < key->params->sig_len)) { + /* Signature buffer too small. */ + WOLFSSL_MSG("error: XMSS sig buffer too small"); + ret = BUFFER_E; + } + /* Check read and write callbacks available. */ + if ((ret == 0) && ((key->write_private_key == NULL) || + (key->read_private_key == NULL))) { + WOLFSSL_MSG("error: XmssKey write/read callbacks are not set"); + ret = BAD_FUNC_ARG; + } + /* Check read/write callback context available. */ + if ((ret == 0) && (key->context == NULL)) { + WOLFSSL_MSG("error: XmssKey context is not set"); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + *sigLen = key->params->sig_len; + /* Finally, sign and update the secret key. */ + ret = wc_xmsskey_signupdate(key, sig, msg, msgLen); + } + + return ret; +} + +/* Check if more signatures are possible with key. + * + * @param [in] key XMSS key to check. + * @return 1 when signatures possible. + * @return 0 when key exhausted. + */ +int wc_XmssKey_SigsLeft(XmssKey* key) +{ + int ret; + + /* Validate parameter. */ + if (key == NULL) { + ret = 0; + } + /* Validate state. */ + else if (key->state == WC_XMSS_STATE_NOSIGS) { + WOLFSSL_MSG("error: XMSS signatures exhausted"); + ret = 0; + } + else if (key->state != WC_XMSS_STATE_OK) { + WOLFSSL_MSG("error: can't sign, XMSS key not in good state"); + ret = 0; + } + /* Read the current secret key from NV storage.*/ + else if (key->read_private_key(key->sk, key->sk_len, key->context) != + WC_XMSS_RC_READ_TO_MEMORY) { + WOLFSSL_MSG("error: XMSS read_private_key failed"); + ret = 0; + } + else { + /* Ask implementation to check index in private key. */ + ret = wc_xmss_sigsleft(key->params, key->sk); + } + + return ret; +} +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY*/ + +/* Get the XMSS/XMSS^MT public key length. + * + * The public key is static in size and does not depend on parameters, + * other than the choice of SHA256 as hashing function. + * + * @param [in] key XMSS key. + * @param [out] len Length of the public key. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return NOT_COMPILED_IN when a hash algorithm not supported. + */ +int wc_XmssKey_GetPubLen(const XmssKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + else { + *len = XMSS_OID_LEN + key->params->pk_len; + } + + return ret; +} + +/* Export public key and parameters from one XmssKey to another. + * + * Use this to prepare a signature verification XmssKey that is pub only. + * + * @param [out] keyDst Destination key for copy. + * @param [in] keySrc Source key for copy. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a key is NULL. + * @return Other negative when digest algorithm initialization failed. + */ +int wc_XmssKey_ExportPub(XmssKey* keyDst, const XmssKey* keySrc) +{ + int ret = 0; + + /* Validate parameters. */ + if ((keyDst == NULL) || (keySrc == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Zeroize the new key. */ + ForceZero(keyDst, sizeof(XmssKey)); + + /* Copy over the public key. */ + XMEMCPY(keyDst->pk, keySrc->pk, sizeof(keySrc->pk)); + + /* Copy over the key info. */ + keyDst->oid = keySrc->oid; + keyDst->is_xmssmt = keySrc->is_xmssmt; + keyDst->params = keySrc->params; + } + if (ret == 0) { + /* Mark keyDst as verify only, to prevent misuse. */ + keyDst->state = WC_XMSS_STATE_VERIFYONLY; + } + + return 0; +} + +/* Exports the raw XMSS public key buffer from key to out buffer. + * + * The out buffer should be large enough to hold the public key, and + * outLen should indicate the size of the buffer. + * + * @param [in] key XMSS key. + * @param [out] out Array holding public key. + * @param [in, out] outLen On in, size of buffer. + * On out, the length of the public key. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BUFFER_E if array is too small. + */ +int wc_XmssKey_ExportPubRaw(const XmssKey* key, byte* out, word32* outLen) +{ + int ret = 0; + word32 pubLen = 0; + + /* Validate parameters. */ + if ((key == NULL) || (out == NULL) || (outLen == NULL)) { + ret = BAD_FUNC_ARG; + } + + /* Get the public key length. */ + if (ret == 0) { + ret = wc_XmssKey_GetPubLen(key, &pubLen); + } + /* Check the output buffer is large enough. */ + if ((ret == 0) && (*outLen < pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + int i = 0; + /* First copy the oid into buffer. */ + for (; i < XMSS_OID_LEN; i++) { + out[XMSS_OID_LEN - i - 1] = (key->oid >> (8 * i)) & 0xFF; + } + /* Copy the public key data into buffer after oid. */ + XMEMCPY(out + XMSS_OID_LEN, key->pk, pubLen - XMSS_OID_LEN); + /* Return actual public key length. */ + *outLen = pubLen; + } + + return ret; +} + +/* Imports a raw public key buffer from in array to XmssKey key. + * + * The XMSS parameters must be set first with wc_XmssKey_SetParamStr, + * and inLen must match the length returned by wc_XmssKey_GetPubLen. + * + * @param [in, out] key XMSS key. + * @param [in] in Array holding public key. + * @param [in] inLen Length of array in bytes. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BUFFER_E if array is incorrect size. + * @return BAD_STATE_E when wrong state for operation. + * */ +int wc_XmssKey_ImportPubRaw(XmssKey* key, const byte* in, word32 inLen) +{ + int ret = 0; + word32 pubLen = 0; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_PARMSET)) { + /* XMSS key not ready for import. Param str must be set first. */ + WOLFSSL_MSG("error: XMSS key not ready for import"); + ret = BAD_STATE_E; + } + + /* Get the public key length. */ + if (ret == 0) { + ret = wc_XmssKey_GetPubLen(key, &pubLen); + } + /* Check the input buffer is the right size. */ + if ((ret == 0) && (inLen != pubLen)) { + /* Something inconsistent. Parameters weren't set, or input + * pub key is wrong.*/ + ret = BUFFER_E; + } + + if (ret == 0) { + /* Copy the public key data into key. */ + XMEMCPY(key->pk, in + XMSS_OID_LEN, pubLen - XMSS_OID_LEN); + + /* Update state to verify-only as we don't have a private key. */ + key->state = WC_XMSS_STATE_VERIFYONLY; + } + + return ret; +} + +/* Gets the XMSS/XMSS^MT signature length. + * + * Parameters must be set before calling this, as the signature size + * is a function of the parameters. + * + * Note: call this before wc_XmssKey_Sign or Verify so you know the + * length of the required signature buffer. + * + * @param [in] key XMSS key to use to sign. + * @param [out] len The length of the signature in bytes. + * + * @return 0 on success. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + * */ +int wc_XmssKey_GetSigLen(const XmssKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_OK) && + (key->state != WC_XMSS_STATE_PARMSET)) { + ret = BAD_STATE_E; + } + + if (ret == 0) { + /* Return the calculated signature length. */ + *len = key->params->sig_len; + } + + return ret; +} + +/* Verify the signature using the XMSS public key. + * + * Requires that XMSS parameters have been set with + * wc_XmssKey_SetParamStr, and that a public key is available + * from importing or MakeKey(). + * + * Call wc_XmssKey_GetSigLen() before this function to determine + * length of the signature buffer. + * + * @param [in] key XMSS key to use to verify. + * @param [in] sig Signature to verify. + * @param [in] sigLen Size of signature in bytes. + * @param [in] m Message to verify. + * @param [in] mLen Length of the message in bytes. + * + * @return 0 on success. + * @return SIG_VERIFY_E when signature did not verify message. + * @return BAD_FUNC_ARG when a parameter is NULL. + * @return BAD_STATE_E when wrong state for operation. + * @return BUFFER_E when sigLen is too small. + */ +int wc_XmssKey_Verify(XmssKey* key, const byte* sig, word32 sigLen, + const byte* m, int mLen) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (m == NULL)) { + ret = BAD_FUNC_ARG; + } + /* Validate state. */ + if ((ret == 0) && (key->state != WC_XMSS_STATE_OK) && + (key->state != WC_XMSS_STATE_VERIFYONLY)) { + /* XMSS key not ready for verification. Param str must be + * set first, and Reload() called. */ + WOLFSSL_MSG("error: XMSS key not ready for verification"); + ret = BAD_STATE_E; + } + /* Check the signature is the big enough. */ + if ((ret == 0) && (sigLen < key->params->sig_len)) { + /* Signature buffer too small. */ + ret = BUFFER_E; + } + + if (ret == 0) { + #ifdef WOLFSSL_SMALL_STACK + XmssState* state; + #else + XmssState state[1]; + #endif + + #ifdef WOLFSSL_SMALL_STACK + state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (state == NULL) { + ret = MEMORY_E; + } + if (ret == 0) + #endif + { + /* Initialize state for use in verification. */ + ret = wc_xmss_state_init(state, key->params); + if (ret == 0) { + /* Verify using either XMSS^MT function as it works for both. */ + ret = wc_xmssmt_verify(state, m, mLen, sig, key->pk); + /* Free state after use. */ + wc_xmss_state_free(state); + } + #ifdef WOLFSSL_SMALL_STACK + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + } + + return ret; +} + +#endif /* WOLFSSL_HAVE_XMSS */ diff --git a/src/wolfcrypt/src/wc_xmss_impl.c b/src/wolfcrypt/src/wc_xmss_impl.c index 4a91f99..b45bc59 100644 --- a/src/wolfcrypt/src/wc_xmss_impl.c +++ b/src/wolfcrypt/src/wc_xmss_impl.c @@ -19,8 +19,4321 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +/* Based on: + * o RFC 8391 - XMSS: eXtended Merkle Signature Scheme + * o [HDSS] "Hash-based Digital Signature Schemes", Buchmann, Dahmen and Szydlo + * from "Post Quantum Cryptography", Springer 2009. + * o [OPX] "Optimal Parameters for XMSS^MT", Hulsing, Rausch and Buchmann + * + * TODO: "Simple and Memory-efficient Signature Generation of XMSS^MT" + * (https://ece.engr.uvic.ca/~raltawy/SAC2021/9.pdf) + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + #include +#include +#include + +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#if defined(WOLFSSL_HAVE_XMSS) + +/* Indices into Hash Address. */ +#define XMSS_ADDR_LAYER 0 +#define XMSS_ADDR_TREE_HI 1 +#define XMSS_ADDR_TREE 2 +#define XMSS_ADDR_TYPE 3 +#define XMSS_ADDR_OTS 4 +#define XMSS_ADDR_LTREE 4 +#define XMSS_ADDR_TREE_ZERO 4 +#define XMSS_ADDR_CHAIN 5 +#define XMSS_ADDR_TREE_HEIGHT 5 +#define XMSS_ADDR_HASH 6 +#define XMSS_ADDR_TREE_INDEX 6 +#define XMSS_ADDR_KEY_MASK 7 + +/* Types of hash addresses. */ +#define WC_XMSS_ADDR_TYPE_OTS 0 +#define WC_XMSS_ADDR_TYPE_LTREE 1 +#define WC_XMSS_ADDR_TYPE_TREE 2 + +/* Byte to include in hash to create unique sequence. */ +#define XMSS_HASH_PADDING_F 0 +#define XMSS_HASH_PADDING_H 1 +#define XMSS_HASH_PADDING_HASH 2 +#define XMSS_HASH_PADDING_PRF 3 +#define XMSS_HASH_PADDING_PRF_KEYGEN 4 + +/* Fixed parameter values. */ +#define XMSS_WOTS_W 16 +#define XMSS_WOTS_LOG_W 4 +#define XMSS_WOTS_LEN2 3 +#define XMSS_CSUM_SHIFT 4 +#define XMSS_CSUM_LEN 2 + +/* Length of the message to the PRF. */ +#define XMSS_PRF_M_LEN 32 + +/* Length of index encoding when doing XMSS. */ +#define XMSS_IDX_LEN 4 + +/* Size of the N when using SHA-256 and 32 byte padding. */ +#define XMSS_SHA256_32_N WC_SHA256_DIGEST_SIZE +/* Size of the padding when using SHA-256 and 32 byte padding. */ +#define XMSS_SHA256_32_PAD_LEN 32 + +/* Calculate PRF data length for parameters. */ +#define XMSS_HASH_PRF_DATA_LEN(params) \ + ((params)->pad_len + (params)->n + WC_XMSS_ADDR_LEN) +/* PRF data length when using SHA-256 with 32 byte padding. */ +#define XMSS_HASH_PRF_DATA_LEN_SHA256_32 \ + (XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N + WC_XMSS_ADDR_LEN) + +/* Calculate chain hash data length for parameters. */ +#define XMSS_CHAIN_HASH_DATA_LEN(params) \ + ((params)->pad_len + 2 * (params)->n) +/* Chain hash data length when using SHA-256 with 32 byte padding. */ +#define XMSS_CHAIN_HASH_DATA_LEN_SHA256_32 \ + (XMSS_SHA256_32_PAD_LEN + 2 * XMSS_SHA256_32_N) + +/* Calculate rand hash data length for parameters. */ +#define XMSS_RAND_HASH_DATA_LEN(params) \ + ((params)->pad_len + 3 * (params)->n) +/* Rand hash data length when using SHA-256 with 32 byte padding. */ +#define XMSS_RAND_HASH_DATA_LEN_SHA256_32 \ + (XMSS_SHA256_32_PAD_LEN + 3 * XMSS_SHA256_32_N) + +/* Encode pad value into byte array. Front fill with 0s. + * + * RFC 8391: 2.4 + * + * @param [in] n Number to encode. + * @param [out] a Array to hold encoding. + * @param [in] l Length of array. + */ +#define XMSS_PAD_ENC(n, a, l) \ +do { \ + XMEMSET(a, 0, l); \ + (a)[(l) - 1] = (n); \ +} while (0) + + +/******************************************** + * Index 32/64 bits + ********************************************/ + +/* Index of 32 or 64 bits. */ +typedef union wc_Idx { +#if WOLFSSL_XMSS_MAX_HEIGHT > 32 + /* 64-bit representation. */ + w64wrapper u64; +#endif +#if WOLFSSL_XMSS_MIN_HEIGHT <= 32 + /* 32-bit representation. */ + word32 u32; +#endif +} wc_Idx; + +#if WOLFSSL_XMSS_MAX_HEIGHT > 32 +/* Set index to zero. + * + * Index is up to 64-bits. + * + * @param [out] idx 32/64-bit index to zero. + */ +#define WC_IDX_ZERO(idx) w64Zero(&(idx).u64) +#else +/* Set index to zero. + * + * Index is no more than 32-bits. + * + * @param [out] idx 32/64-bit index to zero. + */ +#define WC_IDX_ZERO(idx) idx.u32 = 0 +#endif + +#if WOLFSSL_XMSS_MAX_HEIGHT > 32 +/* Decode 64-bit index. + * + * @param [out] i Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define IDX64_DECODE(i, c, a, ret) \ + if ((c) == 5) { \ + word32 t; \ + ato32((a) + 1, &t); \ + (i) = w64From32((a)[0], t); \ + } \ + else if ((c) == 8) { \ + ato64(a, &(i)); \ + } + +/* Decode 64-bit index. + * + * @param [out] i Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define XMSS_IDX64_DECODE(i, c, a, ret) \ +do { \ + IDX64_DECODE(i, c, a, ret) \ + else { \ + (ret) = NOT_COMPILED_IN; \ + } \ +} while (0) + +/* Check whether index is valid. + * + * @param [in] i Index to check. + * @param [in] c Count of bytes i was encoded in. + * @param [in] h Full tree Height. + */ +#define IDX64_INVALID(i, c, h) \ + ((w64GetHigh32(w64Add32(i, 1, NULL)) >> ((h) - 32)) != 0) + +/* Set 64-bit index as hash address value for tree. + * + * @param [in] i Index to set. + * @param [in] c Count of bytes to encode into. + * @param [in] h Height of tree. + * @param [out] a Hash address to encode into. + * @param [out] l Index of leaf. + */ +#define IDX64_SET_ADDR_TREE(i, c, h, a, l) \ + if ((c) > 4) { \ + (l) = w64GetLow32(i) & (((word32)1 << (h)) - 1);\ + (i) = w64ShiftRight(i, h); \ + (a)[XMSS_ADDR_TREE_HI] = w64GetHigh32(i); \ + (a)[XMSS_ADDR_TREE] = w64GetLow32(i); \ + } +#endif /* WOLFSSL_XMSS_MAX_HEIGHT > 32 */ + +#if WOLFSSL_XMSS_MIN_HEIGHT <= 32 +/* Decode 32-bit index. + * + * @param [out] i Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define IDX32_DECODE(i, c, a, ret) \ + if ((c) == 4) { \ + ato32(a, &(i)); \ + } \ + else if ((c) == 3) { \ + ato24(a, &(i)); \ + } + +/* Decode 32-bit index. + * + * @param [out] i Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define XMSS_IDX32_DECODE(i, c, a, ret) \ +do { \ + IDX32_DECODE(i, c, a, ret) \ + else { \ + (ret) = NOT_COMPILED_IN; \ + } \ +} while (0) + +/* Check whether 32-bit index is valid. + * + * @param [in] i Index to check. + * @param [in] c Count of bytes i was encoded in. + * @param [in] h Full tree Height. + */ +#define IDX32_INVALID(i, c, h) \ + ((((i) + 1) >> (h)) != 0) + +/* Set 32-bit index as hash address value for tree. + * + * @param [in] i Index to set. + * @param [in] c Count of bytes to encode into. + * @param [in] h Height of tree. + * @param [out] a Hash address to encode into. + * @param [out] l Index of leaf. + */ +#define IDX32_SET_ADDR_TREE(i, c, h, a, l) \ + if ((c) <= 4) { \ + (l) = ((i) & ((1 << (h)) - 1)); \ + (i) >>= params->sub_h; \ + (a)[XMSS_ADDR_TREE] = (i); \ + } + +#endif /* WOLFSSL_XMSS_MIN_HEIGHT <= 32 */ + +#if (WOLFSSL_XMSS_MAX_HEIGHT > 32) && (WOLFSSL_XMSS_MIN_HEIGHT <= 32) + +/* Decode 32/64-bit index. + * + * @param [out] idx Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define WC_IDX_DECODE(idx, c, a, ret) \ +do { \ + IDX64_DECODE((idx).u64, c, a, ret) \ + else \ + IDX32_DECODE((idx).u32, c, a, ret) \ + else { \ + (ret) = NOT_COMPILED_IN; \ + } \ +} while (0) + +/* Check whether index is valid. + * + * @param [in] i Index to check. + * @param [in] c Count of bytes i was encoded in. + * @param [in] h Full tree Height. + */ +#define WC_IDX_INVALID(i, c, h) \ + ((((c) > 4) && IDX64_INVALID((i).u64, c, h)) || \ + (((c) <= 4) && IDX32_INVALID((i).u32, c, h))) + +/* Set 32/64-bit index as hash address value for tree. + * + * @param [in] i Index to set. + * @param [in] c Count of bytes to encode into. + * @param [in] h Height of tree. + * @param [out] a Hash address to encode into. + * @param [out] l Index of leaf. + */ +#define WC_IDX_SET_ADDR_TREE(idx, c, h, a, l) \ +do { \ + IDX64_SET_ADDR_TREE((idx).u64, c, h, a, l) \ + else \ + IDX32_SET_ADDR_TREE((idx).u32, c, h, a, l) \ +} while (0) + +#elif WOLFSSL_XMSS_MAX_HEIGHT > 32 + +/* Decode 64-bit index. + * + * @param [out] idx Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define WC_IDX_DECODE(idx, c, a, ret) \ +do { \ + IDX64_DECODE((idx).u64, c, a, ret) \ +} while (0) + +/* Check whether index is valid. + * + * @param [in] i Index to check. + * @param [in] c Count of bytes i was encoded in. + * @param [in] h Full tree Height. + */ +#define WC_IDX_INVALID(i, c, h) \ + IDX64_INVALID((i).u64, c, h) + +/* Set 64-bit index as hash address value for tree. + * + * @param [in] i Index to set. + * @param [in] c Count of bytes to encode into. + * @param [in] h Height of tree. + * @param [out] a Hash address to encode into. + * @param [out] l Index of leaf. + */ +#define WC_IDX_SET_ADDR_TREE(idx, c, h, a, l) \ +do { \ + IDX64_SET_ADDR_TREE((idx).u64, c, h, a, l) \ +} while (0) + +#else + +/* Decode 32-bit index. + * + * @param [out] idx Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + * @param [out] ret Return value. + */ +#define WC_IDX_DECODE(idx, c, a, ret) \ +do { \ + IDX32_DECODE((idx).u32, c, a, ret) \ + else { \ + (ret) = NOT_COMPILED_IN; \ + } \ +} while (0) + +/* Check whether index is valid. + * + * @param [in] i Index to check. + * @param [in] c Count of bytes i was encoded in. + * @param [in] h Full tree Height. + */ +#define WC_IDX_INVALID(i, c, h) \ + IDX32_INVALID((i).u32, c, h) + +/* Set 32-bit index as hash address value for tree. + * + * @param [in] i Index to set. + * @param [in] c Count of bytes to encode into. + * @param [in] h Height of tree. + * @param [out] a Hash address to encode into. + * @param [out] l Index of leaf. + */ +#define WC_IDX_SET_ADDR_TREE(idx, c, h, a, l) \ +do { \ + IDX32_SET_ADDR_TREE(idx.u32, c, h, a, l) \ +} while (0) + +#endif /* (WOLFSSL_XMSS_MAX_HEIGHT > 32) && (WOLFSSL_XMSS_MIN_HEIGHT <= 32) */ + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY +/* Update index by adding one to big-endian encoded value. + * + * @param [in, out] a Array index is encoded in. + * @param [in] l Length of encoded index. + */ +static void wc_idx_update(unsigned char* a, word8 l) +{ + sword8 i; + + for (i = l - 1; i >= 0; i--) { + if ((++a[i]) != 0) { + break; + } + } +} + +/* Copy index from source buffer to destination buffer. + * + * Index is put into the front of the destination buffer with the length of the + * source. + * + * @param [in] s Source buffer. + * @param [in] sl Length of index in source. + * @param [in, out] d Destination buffer. + * @param [in] dl Length of destination buffer. + */ +static void wc_idx_copy(const unsigned char* s, word8 sl, unsigned char* d, + word8 dl) +{ + XMEMCPY(d, s, sl); + XMEMSET(d + sl, 0, dl - sl); +} +#endif + +/******************************************** + * Hash Address. + ********************************************/ + +/* Set the hash address based on subtree. + * + * @param [out] a Hash address. + * @param [in] s Subtree hash address. + * @param [in] t Type of hash address. + */ +#define XMSS_ADDR_SET_SUBTREE(a, s, t) \ +do { \ + (a)[XMSS_ADDR_LAYER] = (s)[XMSS_ADDR_LAYER]; \ + (a)[XMSS_ADDR_TREE_HI] = (s)[XMSS_ADDR_TREE_HI]; \ + (a)[XMSS_ADDR_TREE] = (s)[XMSS_ADDR_TREE]; \ + (a)[XMSS_ADDR_TYPE] = (t); \ + XMEMSET((a) + 4, 0, sizeof(a) - 4 * sizeof(*(a)));\ +} while (0) + +/* Set the OTS hash address based on subtree. + * + * @param [out] a Hash address. + * @param [in] s Subtree hash address. + */ +#define XMSS_ADDR_OTS_SET_SUBTREE(a, s) \ + XMSS_ADDR_SET_SUBTREE(a, s, WC_XMSS_ADDR_TYPE_OTS) +/* Set the L-tree address based on subtree. + * + * @param [out] a Hash address. + * @param [in] s Subtree hash address. + */ +#define XMSS_ADDR_LTREE_SET_SUBTREE(a, s) \ + XMSS_ADDR_SET_SUBTREE(a, s, WC_XMSS_ADDR_TYPE_LTREE) +/* Set the hash tree address based on subtree. + * + * @param [out] a Hash address. + * @param [in] s Subtree hash address. + */ +#define XMSS_ADDR_TREE_SET_SUBTREE(a, s) \ + XMSS_ADDR_SET_SUBTREE(a, s, WC_XMSS_ADDR_TYPE_TREE) + +#ifdef LITTLE_ENDIAN_ORDER + +/* Set a byte value into a word of an encoded address. + * + * @param [in, out] a Encoded hash address. + * @param [in] i Index of word. + * @param [in] b Byte to set. + */ +#define XMSS_ADDR_SET_BYTE(a, i, b) \ + ((word32*)(a))[i] = (word32)(b) << 24 + +#else + +/* Set a byte value into a word of an encoded address. + * + * @param [in, out] a Encoded hash address. + * @param [in] i Index of word. + * @param [in] b Byte to set. + */ +#define XMSS_ADDR_SET_BYTE(a, i, b) \ + ((word32*)(a))[i] = (b) + +#endif /* LITTLE_ENDIAN_ORDER */ + +/* Convert hash address to bytes. + * + * @param [out] bytes Array to encode into. + * @param [in] addr Hash address. + */ +static void wc_xmss_addr_encode(const HashAddress addr, byte* bytes) +{ + c32toa((addr)[0], (bytes) + (0 * 4)); + c32toa((addr)[1], (bytes) + (1 * 4)); + c32toa((addr)[2], (bytes) + (2 * 4)); + c32toa((addr)[3], (bytes) + (3 * 4)); + c32toa((addr)[4], (bytes) + (4 * 4)); + c32toa((addr)[5], (bytes) + (5 * 4)); + c32toa((addr)[6], (bytes) + (6 * 4)); + c32toa((addr)[7], (bytes) + (7 * 4)); +} + +/******************************************** + * HASHING + ********************************************/ + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) && \ + !defined(WC_XMSS_FULL_HASH) + +/* Set hash data and length into SHA-256 digest. + * + * @param [in, out] state XMSS/MT state with SHA-256 digest. + * @param [in] data Data to add to hash. + * @param [in] len Number of bytes in data. + * Must be less than a block. + * @param [in] total_len Number of bytes updated so far. + */ +#define XMSS_SHA256_SET_DATA(state, data, len, total_len) \ +do { \ + XMEMCPY((state)->digest.sha256.buffer, data, len); \ + (state)->digest.sha256.buffLen = (len); \ + (state)->digest.sha256.loLen = (total_len); \ +} while (0) + +/* Save the SHA-256 state to cache. + * + * @param [in, out] state XMSS/MT state with SHA-256 digest and state cache. + */ +#define XMSS_SHA256_STATE_CACHE(state) \ + (state)->dgst_state[0] = (state)->digest.sha256.digest[0]; \ + (state)->dgst_state[1] = (state)->digest.sha256.digest[1]; \ + (state)->dgst_state[2] = (state)->digest.sha256.digest[2]; \ + (state)->dgst_state[3] = (state)->digest.sha256.digest[3]; \ + (state)->dgst_state[4] = (state)->digest.sha256.digest[4]; \ + (state)->dgst_state[5] = (state)->digest.sha256.digest[5]; \ + (state)->dgst_state[6] = (state)->digest.sha256.digest[6]; \ + (state)->dgst_state[7] = (state)->digest.sha256.digest[7]; \ + +/* Restore the SHA-256 state from cache and set length. + * + * @param [in, out] state XMSS/MT state with SHA-256 digest and state cache. + * @param [in] len Number of bytes of data hashed so far. + */ +#define XMSS_SHA256_STATE_RESTORE(state, len) \ +do { \ + (state)->digest.sha256.digest[0] = (state)->dgst_state[0]; \ + (state)->digest.sha256.digest[1] = (state)->dgst_state[1]; \ + (state)->digest.sha256.digest[2] = (state)->dgst_state[2]; \ + (state)->digest.sha256.digest[3] = (state)->dgst_state[3]; \ + (state)->digest.sha256.digest[4] = (state)->dgst_state[4]; \ + (state)->digest.sha256.digest[5] = (state)->dgst_state[5]; \ + (state)->digest.sha256.digest[6] = (state)->dgst_state[6]; \ + (state)->digest.sha256.digest[7] = (state)->dgst_state[7]; \ + (state)->digest.sha256.loLen = (len); \ +} while (0) + +/* Restore the SHA-256 state from cache and set data and length. + * + * @param [in, out] state XMSS/MT state with SHA-256 digest and cache. + * @param [in] data Data to add to hash. + * @param [in] len Number of bytes in data. + * Must be less than a block. + * @param [in] total_len Number of bytes updated so far. + */ +#define XMSS_SHA256_STATE_RESTORE_DATA(state, data, len, total_len) \ +do { \ + (state)->digest.sha256.digest[0] = (state)->dgst_state[0]; \ + (state)->digest.sha256.digest[1] = (state)->dgst_state[1]; \ + (state)->digest.sha256.digest[2] = (state)->dgst_state[2]; \ + (state)->digest.sha256.digest[3] = (state)->dgst_state[3]; \ + (state)->digest.sha256.digest[4] = (state)->dgst_state[4]; \ + (state)->digest.sha256.digest[5] = (state)->dgst_state[5]; \ + (state)->digest.sha256.digest[6] = (state)->dgst_state[6]; \ + (state)->digest.sha256.digest[7] = (state)->dgst_state[7]; \ + XMSS_SHA256_SET_DATA(state, data, len, total_len); \ +} while (0) + +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 && !WC_XMSS_FULL_HASH */ + +/* Hash the data into output buffer. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] in Data to digest. + * @param [in] inlen Length of data to digest in bytes. + * @param [out] out Buffer to put digest into. + */ +static WC_INLINE void wc_xmss_hash(XmssState* state, const byte* in, + word32 inlen, byte* out) +{ + int ret; + const XmssParams* params = state->params; -#ifdef WOLFSSL_HAVE_XMSS - #error "Contact wolfSSL to get the implementation of this file" +#ifdef WC_XMSS_SHA256 + /* Full SHA-256 digest. */ + if ((params->hash == WC_HASH_TYPE_SHA256) && + (params->n == WC_SHA256_DIGEST_SIZE)) { + ret = wc_Sha256Update(&state->digest.sha256, in, inlen); + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, out); + } + } +#if WOLFSSL_WC_XMSS_MIN_HASH_SIZE <= 192 && WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 192 + /* Partial SHA-256 digest. */ + else if (params->hash == WC_HASH_TYPE_SHA256) { + byte buf[WC_SHA256_DIGEST_SIZE]; + ret = wc_Sha256Update(&state->digest.sha256, in, inlen); + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, buf); + } + if (ret == 0) { + XMEMCPY(out, buf, params->n); + } + } #endif + else +#endif /* WC_XMSS_SHA256 */ +#ifdef WC_XMSS_SHA512 + /* Full SHA-512 digest. */ + if (params->hash == WC_HASH_TYPE_SHA512) { + ret = wc_Sha512Update(&state->digest.sha512, in, inlen); + if (ret == 0) { + ret = wc_Sha512Final(&state->digest.sha512, out); + } + } + else +#endif /* WC_XMSS_SHA512 */ +#ifdef WC_XMSS_SHAKE128 + /* Digest with SHAKE-128. */ + if (params->hash == WC_HASH_TYPE_SHAKE128) { + ret = wc_Shake128_Update(&state->digest.shake, in, inlen); + if (ret == 0) { + ret = wc_Shake128_Final(&state->digest.shake, out, params->n); + } + } + else +#endif /* WC_XMSS_SHAKE128 */ +#ifdef WC_XMSS_SHAKE256 + /* Digest with SHAKE-256. */ + if (params->hash == WC_HASH_TYPE_SHAKE256) { + ret = wc_Shake256_Update(&state->digest.shake, in, inlen); + if (ret == 0) { + ret = wc_Shake256_Final(&state->digest.shake, out, params->n); + } + } + else +#endif /* WC_XMSS_SHAKE256 */ + { + /* Unsupported digest function. */ + ret = NOT_COMPILED_IN; + } + + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +} + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) +#ifndef WC_XMSS_FULL_HASH +/* Chain hashing. + * + * RFC 8391: 3.1.2, Algorithm 2: chain - Chaining Function + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM = PRF(SEED, ADRS); + * tmp = F(KEY, tmp XOR BM); + * return tmp; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] tmp Temporary buffer holding chain data. + * @param [in] addr Hash address as a byte array. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_chain_hash_sha256_32(XmssState* state, const byte* tmp, + byte* addr, byte* hash) +{ + /* Offsets into chain hash data. */ + byte* pad = state->buf; + byte* key = pad + XMSS_SHA256_32_PAD_LEN; + byte* bm = key + XMSS_SHA256_32_N; + int ret; + + /* Calculate n-byte key - KEY. */ + ((word32*)addr)[XMSS_ADDR_KEY_MASK] = 0; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, key); + + if (ret == 0) { + /* Calculate n-byte bit mask - BM. */ + addr[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm); + } + + if (ret == 0) { + /* Function padding set in caller. */ + xorbuf(bm, tmp, XMSS_SHA256_32_N); + ret = wc_Sha256Update(&state->digest.sha256, state->buf, + XMSS_CHAIN_HASH_DATA_LEN_SHA256_32); + } + if (ret == 0) { + /* Calculate the chain hash. */ + ret = wc_Sha256Final(&state->digest.sha256, hash); + } + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +} +#else +/* Chain hashing. + * + * Padding, seed, addr for PRF set by caller into prf_buf. + * + * RFC 8391: 3.1.2, Algorithm 2: chain - Chaining Function + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM = PRF(SEED, ADRS); + * tmp = F(KEY, tmp XOR BM); + * return tmp; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] tmp Temporary buffer holding chain data. + * @param [out] out Buffer to hold hash. + */ +static void wc_xmss_chain_hash_sha256_32(XmssState* state, const byte* tmp, + byte* hash) +{ + byte* addr = state->prf_buf + XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N; + /* Offsets into chain hash data. */ + byte* pad = state->buf; + byte* key = pad + XMSS_SHA256_32_PAD_LEN; + byte* bm = key + XMSS_SHA256_32_N; + + /* Calculate n-byte key - KEY. */ + ((word32*)addr)[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, key); + /* Calculate the n-byte mask. */ + addr[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, bm); + + /* Function padding set in caller. */ + xorbuf(bm, tmp, XMSS_SHA256_32_N); + /* Calculate the chain hash. */ + wc_xmss_hash(state, state->buf, XMSS_CHAIN_HASH_DATA_LEN_SHA256_32, hash); +} +#endif /* !WC_XMSS_FULL_HASH */ +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + +/* Chain hashing. + * + * Padding, seed, addr for PRF set by caller into prf_buf. + * + * RFC 8391: 3.1.2, Algorithm 2: chain - Chaining Function + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM = PRF(SEED, ADRS); + * tmp = F(KEY, tmp XOR BM); + * return tmp; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] tmp Temporary buffer holding chain data. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_chain_hash(XmssState* state, const byte* tmp, byte* hash) +{ + const XmssParams* params = state->params; + byte* addr = state->prf_buf + params->pad_len + params->n; + /* Offsets into chain hash data. */ + byte* pad = state->buf; + byte* key = pad + params->pad_len; + byte* bm = key + params->n; + + /* Calculate n-byte key - KEY. */ + ((word32*)addr)[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN(params), key); + /* Calculate n-byte bit mask - BM. */ + addr[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN(params), bm); + + /* Function padding set in caller. */ + xorbuf(bm, tmp, params->n); + /* Calculate the chain hash. */ + wc_xmss_hash(state, state->buf, XMSS_CHAIN_HASH_DATA_LEN(params), hash); +} + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) +#ifndef WC_XMSS_FULL_HASH +/* Randomized tree hashing. + * + * RFC 8391: 4.1.4, Algorithm 7: RAND_HASH + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM_0 = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(2); + * BM_1 = PRF(SEED, ADRS); + * return H(KEY, (LEFT XOR BM_0) || (RIGHT XOR BM_1)); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] data Input data. + * @param [in] addr Hash address. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_rand_hash_sha256_32_prehash(XmssState* state, + const byte* data, HashAddress addr, byte* hash) +{ + int ret; + /* Offsets into rand hash data. */ + byte* pad = state->buf; + byte* key = pad + XMSS_SHA256_32_PAD_LEN; + byte* bm0 = key + XMSS_SHA256_32_N; + byte* bm1 = bm0 + XMSS_SHA256_32_N; + byte addr_buf[WC_XMSS_ADDR_LEN]; + + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, key); + + /* Calculate n-byte mask - BM_0. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm0); + } + + /* Calculate n-byte mask - BM_1. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm1); + } + + if (ret == 0) { + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, pad, XMSS_SHA256_32_PAD_LEN); + /* XOR into bm0 and bm1. */ + xorbuf(bm0, data, XMSS_SHA256_32_N * 2); + ret = wc_Sha256Update(&state->digest.sha256, state->buf, + XMSS_RAND_HASH_DATA_LEN_SHA256_32); + } + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, hash); + } + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +} +#endif /* !WC_XMSS_FULL_HASH */ + +/* Randomized tree hashing. + * + * RFC 8391: 4.1.4, Algorithm 7: RAND_HASH + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM_0 = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(2); + * BM_1 = PRF(SEED, ADRS); + * return H(KEY, (LEFT XOR BM_0) || (RIGHT XOR BM_1)); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] data Input data. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_rand_hash_sha256_32(XmssState* state, const byte* data, + const byte* pk_seed, HashAddress addr, byte* hash) +{ + byte* addr_buf = state->prf_buf + XMSS_SHA256_32_PAD_LEN + + XMSS_SHA256_32_N; + /* Offsets into rand hash data. */ + byte* pad = state->buf; + byte* key = pad + XMSS_SHA256_32_PAD_LEN; + byte* bm0 = key + XMSS_SHA256_32_N; + byte* bm1 = bm0 + XMSS_SHA256_32_N; +#ifndef WC_XMSS_FULL_HASH + int ret; + + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, XMSS_SHA256_32_PAD_LEN); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + XMSS_SHA256_32_PAD_LEN, pk_seed, + XMSS_SHA256_32_N); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + ret = wc_Sha256Update(&state->digest.sha256, state->prf_buf, + XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N); + if (ret == 0) { + /* Copy state after first 64 bytes. */ + XMSS_SHA256_STATE_CACHE(state); + /* Copy in remaining 32 bytes to buffer. */ + XMSS_SHA256_SET_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, key); + } + + /* Calculate n-byte mask - BM_0. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm0); + } + + /* Calculate n-byte mask - BM_1. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm1); + } + + if (ret == 0) { + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, pad, XMSS_SHA256_32_PAD_LEN); + /* XOR into bm0 and bm1. */ + xorbuf(bm0, data, 2 * XMSS_SHA256_32_N); + ret = wc_Sha256Update(&state->digest.sha256, state->buf, + XMSS_RAND_HASH_DATA_LEN_SHA256_32); + } + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, hash); + } + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +#else + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, XMSS_SHA256_32_PAD_LEN); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + XMSS_SHA256_32_PAD_LEN, pk_seed, + XMSS_SHA256_32_N); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, key); + /* Calculate n-byte mask - BM_0. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, bm0); + /* Calculate n-byte mask - BM_1. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, bm1); + + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, state->buf, XMSS_SHA256_32_PAD_LEN); + xorbuf(bm0, data, 2 * XMSS_SHA256_32_N); + wc_xmss_hash(state, state->buf, XMSS_RAND_HASH_DATA_LEN_SHA256_32, hash); +#endif /* WC_XMSS_FULL_HASH */ +} +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + +/* Randomized tree hashing. + * + * RFC 8391: 4.1.4, Algorithm 7: RAND_HASH + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM_0 = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(2); + * BM_1 = PRF(SEED, ADRS); + * return H(KEY, (LEFT XOR BM_0) || (RIGHT XOR BM_1)); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] data Input data. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_rand_hash(XmssState* state, const byte* data, + const byte* pk_seed, HashAddress addr, byte* hash) +{ + const XmssParams* params = state->params; + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + wc_xmss_rand_hash_sha256_32(state, data, pk_seed, addr, hash); + } + else +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + { + byte* addr_buf = state->prf_buf + params->pad_len + params->n; + /* Offsets into rand hash data. */ + byte* pad = state->buf; + byte* key = pad + params->pad_len; + byte* bm0 = key + params->n; + byte* bm1 = bm0 + params->n; + const word32 len = params->pad_len + params->n + WC_XMSS_ADDR_LEN; + + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, params->pad_len); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + params->pad_len, pk_seed, params->n); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + wc_xmss_hash(state, state->prf_buf, len, key); + /* Calculate n-byte mask - BM_0. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, len, bm0); + /* Calculate n-byte mask - BM_1. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + wc_xmss_hash(state, state->prf_buf, len, bm1); + + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, pad, params->pad_len); + xorbuf(bm0, data, 2 * params->n); + wc_xmss_hash(state, state->buf, params->pad_len + 3 * params->n, + hash); + } +} + +#if !defined(WOLFSSL_WC_XMSS_SMALL) || defined(WOLFSSL_XMSS_VERIFY_ONLY) +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) +/* Randomized tree hashing. + * + * RFC 8391: 4.1.4, Algorithm 7: RAND_HASH + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM_0 = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(2); + * BM_1 = PRF(SEED, ADRS); + * return H(KEY, (LEFT XOR BM_0) || (RIGHT XOR BM_1)); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] left First half of data. + * @param [in] right Second half of data. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_rand_hash_lr_sha256_32(XmssState* state, const byte* left, + const byte* right, const byte* pk_seed, HashAddress addr, byte* hash) +{ + byte* addr_buf = state->prf_buf + XMSS_SHA256_32_PAD_LEN + + XMSS_SHA256_32_N; + /* Offsets into rand hash data. */ + byte* pad = state->buf; + byte* key = pad + XMSS_SHA256_32_PAD_LEN; + byte* bm0 = key + XMSS_SHA256_32_N; + byte* bm1 = bm0 + XMSS_SHA256_32_N; +#ifndef WC_XMSS_FULL_HASH + int ret; + + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, XMSS_SHA256_32_PAD_LEN); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + XMSS_SHA256_32_PAD_LEN, pk_seed, + XMSS_SHA256_32_N); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + ret = wc_Sha256Update(&state->digest.sha256, state->prf_buf, + XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N); + if (ret == 0) { + /* Copy state after first 64 bytes. */ + XMSS_SHA256_STATE_CACHE(state); + /* Copy in remaining 32 bytes to buffer. */ + XMSS_SHA256_SET_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, key); + } + + /* Calculate n-byte mask - BM_0. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm0); + } + + /* Calculate n-byte mask - BM_1. */ + if (ret == 0) { + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + /* Copy back state after first 64 bytes. */ + XMSS_SHA256_STATE_RESTORE_DATA(state, addr_buf, WC_XMSS_ADDR_LEN, + XMSS_HASH_PRF_DATA_LEN_SHA256_32); + /* Calculate hash. */ + ret = wc_Sha256Final(&state->digest.sha256, bm1); + } + + if (ret == 0) { + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, pad, XMSS_SHA256_32_PAD_LEN); + /* XOR into bm0 and bm1. */ + XMEMCPY(state->prf_buf, left, XMSS_SHA256_32_N); + XMEMCPY(state->prf_buf + XMSS_SHA256_32_N, right, XMSS_SHA256_32_N); + xorbuf(bm0, state->prf_buf, 2 * XMSS_SHA256_32_N); + ret = wc_Sha256Update(&state->digest.sha256, state->buf, + XMSS_RAND_HASH_DATA_LEN_SHA256_32); + } + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, hash); + } + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +#else + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, XMSS_SHA256_32_PAD_LEN); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + XMSS_SHA256_32_PAD_LEN, pk_seed, XMSS_SHA256_32_N); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, key); + /* Calculate n-byte mask - BM_0. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, bm0); + /* Calculate n-byte mask - BM_1. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + wc_xmss_hash(state, state->prf_buf, XMSS_HASH_PRF_DATA_LEN_SHA256_32, bm1); + + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, state->buf, XMSS_SHA256_32_PAD_LEN); + XMEMCPY(state->prf_buf, left, XMSS_SHA256_32_N); + XMEMCPY(state->prf_buf + XMSS_SHA256_32_N, right, XMSS_SHA256_32_N); + xorbuf(bm0, state->prf_buf, 2 * XMSS_SHA256_32_N); + wc_xmss_hash(state, state->buf, XMSS_RAND_HASH_DATA_LEN_SHA256_32, hash); +#endif /* WC_XMSS_FULL_HASH */ +} +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ +/* Randomized tree hashing - left and right separate parameters. + * + * RFC 8391: 4.1.4, Algorithm 7: RAND_HASH + * ... + * ADRS.setKeyAndMask(0); + * KEY = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(1); + * BM_0 = PRF(SEED, ADRS); + * ADRS.setKeyAndMask(2); + * BM_1 = PRF(SEED, ADRS); + * return H(KEY, (LEFT XOR BM_0) || (RIGHT XOR BM_1)); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] left First half of data. + * @param [in] right Second half of data. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_rand_hash_lr(XmssState* state, const byte* left, + const byte* right, const byte* pk_seed, HashAddress addr, byte* hash) +{ + const XmssParams* params = state->params; + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + wc_xmss_rand_hash_lr_sha256_32(state, left, right, pk_seed, addr, hash); + } + else +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + { + byte* addr_buf = state->prf_buf + params->pad_len + params->n; + /* Offsets into rand hash data. */ + byte* pad = state->buf; + byte* key = pad + params->pad_len; + byte* bm0 = key + params->n; + byte* bm1 = bm0 + params->n; + const word32 len = params->pad_len + params->n + WC_XMSS_ADDR_LEN; + + /* Encode padding byte for PRF. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, state->prf_buf, params->pad_len); + /* Append public seed for PRF. */ + XMEMCPY(state->prf_buf + params->pad_len, pk_seed, params->n); + + /* Set key mask to initial value and append encoding. */ + addr[XMSS_ADDR_KEY_MASK] = 0; + wc_xmss_addr_encode(addr, addr_buf); + + /* Calculate n-byte key - KEY. */ + wc_xmss_hash(state, state->prf_buf, len, key); + /* Calculate n-byte mask - BM_0. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 1; + wc_xmss_hash(state, state->prf_buf, len, bm0); + /* Calculate n-byte mask - BM_1. */ + addr_buf[XMSS_ADDR_KEY_MASK * 4 + 3] = 2; + wc_xmss_hash(state, state->prf_buf, len, bm1); + + XMSS_PAD_ENC(XMSS_HASH_PADDING_H, pad, params->pad_len); + XMEMCPY(state->prf_buf, left, params->n); + XMEMCPY(state->prf_buf + params->n, right, params->n); + xorbuf(bm0, state->prf_buf, 2 * params->n); + wc_xmss_hash(state, state->buf, params->pad_len + 3 * params->n, + hash); + } +} +#endif /* !WOLFSSL_WC_XMSS_SMALL || WOLFSSL_XMSS_VERIFY_ONLY */ + +/* Compute message hash from the random r, root, index and message. + * + * RFC 8391: 4.1.9, Algorithm 12: XMSS_sign + * ... + * byte[n] M' = H_msg(r || getRoot(SK) || (toByte(idx_sig, n)), M); + * RFC 8391: 5.1 + * H_msg: SHA2-256(toByte(2, 32) || KEY || M) + * H_msg: SHA2-512(toByte(2, 64) || KEY || M) + * H_msg: SHAKE128(toByte(2, 32) || KEY || M, 256) + * H_msg: SHAKE256(toByte(2, 64) || KEY || M, 512) + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] random Random value of n bytes. + * @param [in] root Public root. + * @param [in] idx Buffer holding encoded index. + * @param [in] idx_len Length of encoded index in bytes. + * @param [in] m Message to hash. + * @param [in] mlen Length of message. + * @param [out] hash Buffer to hold hash. + */ +static void wc_xmss_hash_message(XmssState* state, const byte* random, + const byte* root, const byte* idx, word8 idx_len, const byte* m, + word32 mlen, byte* hash) +{ + int ret; + const XmssParams* params = state->params; + word32 padKeyLen = params->pad_len + 3 * params->n; + /* Offsets into message hash data. */ + byte* padKey = state->buf; + byte* pad = padKey; + byte* key = pad + params->pad_len; + byte* root_sk = key + params->n; + byte* idx_sig = root_sk + params->n; + + /* Set prefix data before message. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_HASH, pad, params->pad_len); + XMEMCPY(key, random, params->n); + XMEMCPY(root_sk, root, params->n); + XMEMSET(idx_sig, 0, params->n - idx_len); + XMEMCPY(idx_sig + params->n - idx_len, idx, idx_len); + + /* Hash the padding and key first. */ +#ifdef WC_XMSS_SHA256 + if (params->hash == WC_HASH_TYPE_SHA256) { + ret = wc_Sha256Update(&state->digest.sha256, padKey, padKeyLen); + } + else +#endif /* WC_XMSS_SHA256 */ +#ifdef WC_XMSS_SHA512 + if (params->hash == WC_HASH_TYPE_SHA512) { + ret = wc_Sha512Update(&state->digest.sha512, padKey, padKeyLen); + } + else +#endif /* WC_XMSS_SHA512 */ +#ifdef WC_XMSS_SHAKE128 + if (params->hash == WC_HASH_TYPE_SHAKE128) { + ret = wc_Shake128_Update(&state->digest.shake, padKey, padKeyLen); + } + else +#endif /* WC_XMSS_SHAKE128 */ +#ifdef WC_XMSS_SHAKE256 + if (params->hash == WC_HASH_TYPE_SHAKE256) { + ret = wc_Shake256_Update(&state->digest.shake, padKey, padKeyLen); + } + else +#endif /* WC_XMSS_SHAKE256 */ + { + /* Unsupported digest function. */ + ret = NOT_COMPILED_IN; + } + if (ret == 0) { + /* Generate hash of message - M'. */ + wc_xmss_hash(state, m, mlen, hash); + } + else if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +} + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + +/* Compute PRF with key and message. + * + * RFC 8391: 5.1 + * PRF: SHA2-256(toByte(3, 32) || KEY || M) + * PRF: SHA2-512(toByte(3, 64) || KEY || M) + * PRF: SHAKE128(toByte(3, 32) || KEY || M, 256) + * PRF: SHAKE256(toByte(3, 64) || KEY || M, 512) + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] key Key used to derive pseudo-random from. + * @param [in] m 32 bytes of data to derive pseudo-random from. + * @param [out] prf Buffer to hold pseudo-random data. + */ +static void wc_xmss_prf(XmssState* state, const byte* key, const byte* m, + byte* prf) +{ + const XmssParams* params = state->params; + byte* pad = state->prf_buf; + byte* key_buf = pad + params->pad_len; + byte* m_buf = key_buf + params->n; + + /* 00[0..pl-1] || 03 || key[0..n-1] || m[0..31] */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, pad, params->pad_len); + XMEMCPY(key_buf, key, params->n); + XMEMCPY(m_buf, m, XMSS_PRF_M_LEN); + + /* Hash the PRF data. */ + wc_xmss_hash(state, state->prf_buf, params->pad_len + params->n + + XMSS_PRF_M_LEN, prf); +} + +#ifdef XMSS_CALL_PRF_KEYGEN +/* Compute PRF for keygen with key and message. + * + * NIST SP 800-208: 5.1, 5.2, 5.3, 5.4 + * PRFkeygen (KEY, M): SHA-256(toByte(4, 32) || KEY || M) + * PRFkeygen (KEY, M): T192(SHA-256(toByte(4, 4) || KEY || M)) + * PRFkeygen (KEY, M): SHAKE256(toByte(4, 32) || KEY || M, 256) + * PRFkeygen (KEY, M): SHAKE256(toByte(4, 4) || KEY || M, 192) + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] key Key of n bytes used to derive pseudo-random from. + * @param [in] m n + 32 bytes of data to derive pseudo-random from. + * @param [out] prf Buffer to hold pseudo-random data. + */ +static void wc_xmss_prf_keygen(XmssState* state, const byte* key, + const byte* m, byte* prf) +{ + const XmssParams* params = state->params; + byte* pad = state->prf_buf; + byte* key_buf = pad + params->pad_len; + byte* m_buf = key_buf + params->n; + + /* 00[0..pl-1] || 04 || key[0..n-1] || m[0..n+31] */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF_KEYGEN, pad, params->pad_len); + XMEMCPY(key_buf, key, params->n); + XMEMCPY(m_buf, m, params->n + XMSS_PRF_M_LEN); + + /* Hash the PRF keygen data. */ + wc_xmss_hash(state, state->prf_buf, params->pad_len + 2 * params->n + + XMSS_PRF_M_LEN, prf); +} +#endif /* XMSS_CALL_PRF_KEYGEN */ + +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + +/******************************************** + * WOTS + ********************************************/ + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) +/* Expand private seed with PRF keygen. + * + * RFC 8391: 4.1.3 + * "the existence of a method getWOTS_SK(SK, i) is assumed" + * NIST SP 800-208: 7.2.1, Algorithm 10' + * ... + * for ( j=0; j < len; j++) { + * ADRS.setChainAddress(j); + * sk[j] = PRFkeygen(S_XMSS, SEED || ADRS); + * } + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk_seed Buffer holding private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address as a byte array. + * @param [out] gen_seed Buffer to hold seeds. + */ +static void wc_xmss_wots_get_wots_sk_sha256_32(XmssState* state, + const byte* sk_seed, const byte* pk_seed, byte* addr, byte* gen_seed) +{ + const XmssParams* params = state->params; + word32 i; + byte* pad = state->prf_buf; + byte* s_xmss = pad + XMSS_SHA256_32_PAD_LEN; + byte* seed = s_xmss + XMSS_SHA256_32_N; + byte* addr_buf = seed + XMSS_SHA256_32_N; + int ret; + + ((word32*)addr)[XMSS_ADDR_CHAIN] = 0; + ((word32*)addr)[XMSS_ADDR_HASH] = 0; + ((word32*)addr)[XMSS_ADDR_KEY_MASK] = 0; + + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF_KEYGEN, pad, XMSS_SHA256_32_PAD_LEN); + XMEMCPY(s_xmss, sk_seed, XMSS_SHA256_32_N); + XMEMCPY(seed, pk_seed, XMSS_SHA256_32_N); + XMEMCPY(addr_buf, addr, WC_XMSS_ADDR_LEN); + +#ifndef WC_XMSS_FULL_HASH + ret = wc_Sha256Update(&state->digest.sha256, pad, XMSS_SHA256_32_PAD_LEN + + XMSS_SHA256_32_N); + if (ret == 0) { + /* Copy state after first 64 bytes. */ + XMSS_SHA256_STATE_CACHE(state); + ret = wc_Sha256Update(&state->digest.sha256, seed, XMSS_SHA256_32_N + + WC_XMSS_ADDR_LEN); + } + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, gen_seed); + } + for (i = 1; (ret == 0) && (i < params->wots_len); i++) { + gen_seed += XMSS_SHA256_32_N; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + XMSS_SHA256_STATE_RESTORE(state, 64); + ret = wc_Sha256Update(&state->digest.sha256, seed, XMSS_SHA256_32_N + + WC_XMSS_ADDR_LEN); + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, gen_seed); + } + } +#else + ret = wc_Sha256Update(&state->digest.sha256, state->prf_buf, + XMSS_SHA256_32_PAD_LEN + 2 * XMSS_SHA256_32_N + WC_XMSS_ADDR_LEN); + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, gen_seed); + } + for (i = 1; (ret == 0) && i < params->wots_len; i++) { + gen_seed += XMSS_SHA256_32_N; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + ret = wc_Sha256Update(&state->digest.sha256, state->prf_buf, + XMSS_SHA256_32_PAD_LEN + 2 * XMSS_SHA256_32_N + WC_XMSS_ADDR_LEN); + if (ret == 0) { + ret = wc_Sha256Final(&state->digest.sha256, gen_seed); + } + } +#endif /* WC_XMSS_FULL_HASH*/ + + if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +} +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + +/* Expand private seed with PRF keygen. + * + * RFC 8391: 4.1.3 + * "the existence of a method getWOTS_SK(SK, i) is assumed" + * NIST SP 800-208: 7.2.1 + * Algorithm 10' + * ... + * for ( j=0; j < len; j++) { + * ADRS.setChainAddress(j); + * sk[j] = PRFkeygen(S_XMSS, SEED || ADRS); + * } + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk_seed Buffer holding private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address as a byte array. + * @param [out] gen_seed Buffer to hold seeds. + */ +static void wc_xmss_wots_get_wots_sk(XmssState* state, const byte* sk_seed, + const byte* pk_seed, byte* addr, byte* gen_seed) +{ + const XmssParams* params = state->params; + word32 i; +#ifdef XMSS_CALL_PRF_KEYGEN + byte* seed = state->buf; + byte* addr_buf = seed + params->n; +#else + byte* pad = state->prf_buf; + byte* s_xmss = pad + params->pad_len; + byte* seed = s_xmss + params->n; + byte* addr_buf = seed + params->n; + const word32 len = params->pad_len + params->n * 2 + WC_XMSS_ADDR_LEN; +#endif /* XMSS_CALL_PRF_KEYGEN */ + + /* Ensure hash address fields are 0. */ + ((word32*)addr)[XMSS_ADDR_CHAIN] = 0; + ((word32*)addr)[XMSS_ADDR_HASH] = 0; + ((word32*)addr)[XMSS_ADDR_KEY_MASK] = 0; + +#ifdef XMSS_CALL_PRF_KEYGEN + /* Copy the seed and address into PRF keygen message buffer. */ + XMEMCPY(seed, pk_seed, params->n); + XMEMCPY(addr_buf, addr, WC_XMSS_ADDR_LEN); + + wc_xmss_prf_keygen(state, sk_seed, state->buf, gen_seed); + for (i = 1; i < params->wots_len; i++) { + gen_seed += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_prf_keygen(state, sk_seed, state->buf, gen_seed); + } +#else + /* Copy the PRF keygen fields into one buffer. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF_KEYGEN, pad, params->pad_len); + XMEMCPY(s_xmss, sk_seed, params->n); + XMEMCPY(seed, pk_seed, params->n); + XMEMCPY(addr_buf, addr, WC_XMSS_ADDR_LEN); + + /* Fill output with hashes of different chain hash addresses. */ + wc_xmss_hash(state, state->prf_buf, len, gen_seed); + for (i = 1; i < params->wots_len; i++) { + gen_seed += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_hash(state, state->prf_buf, len, gen_seed); + } +#endif /* XMSS_CALL_PRF_KEYGEN */ +} + +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) +/* Chain hashing to calculate node hash. + * + * RFC 8391: 3.1.2, Algorithm 2 - recursive. + * This function is an iterative version. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] data Initial data to hash. + * @param [in] start Starting hash value in hash address. + * @param [in] steps Size of step. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address as a byte array. + * @param [out] hash Chained hash. + */ +static void wc_xmss_chain_sha256_32(XmssState* state, const byte* data, + unsigned int start, unsigned int steps, const byte* pk_seed, byte* addr, + byte* hash) +{ + if (steps > 0) { + word32 i; + byte* pad = state->prf_buf; + byte* seed = pad + XMSS_SHA256_32_PAD_LEN; +#ifndef WC_XMSS_FULL_HASH + int ret; + + /* Set data for PRF hash. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, pad, XMSS_SHA256_32_PAD_LEN); + XMEMCPY(seed, pk_seed, XMSS_SHA256_32_N); + + /* Hash first 64 bytes. */ + ret = wc_Sha256Update(&state->digest.sha256, state->prf_buf, + XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N); + if (ret == 0) { + /* Copy state after first 64 bytes. */ + XMSS_SHA256_STATE_CACHE(state); + /* Only do this once for all chain hash calls. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_F, state->buf, + state->params->pad_len); + + /* Set address. */ + XMSS_ADDR_SET_BYTE(addr, XMSS_ADDR_HASH, start); + wc_xmss_chain_hash_sha256_32(state, data, addr, hash); + /* Iterate 'steps' calls to the hash function. */ + for (i = start+1; i < (start+steps) && i < XMSS_WOTS_W; i++) { + addr[XMSS_ADDR_HASH * 4 + 3] = i; + wc_xmss_chain_hash_sha256_32(state, hash, addr, hash); + } + } + else if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } +#else + const XmssParams* params = state->params; + byte* addr_buf = seed + XMSS_SHA256_32_N; + + /* Set data for PRF hash. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, pad, XMSS_SHA256_32_PAD_LEN); + XMEMCPY(seed, pk_seed, params->n); + XMEMCPY(addr_buf, addr, WC_XMSS_ADDR_LEN); + + /* Only do this once for all chain hash calls. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_F, state->buf, params->pad_len); + + /* Set address. */ + XMSS_ADDR_SET_BYTE(addr_buf, XMSS_ADDR_HASH, start); + wc_xmss_chain_hash_sha256_32(state, data, hash); + /* Iterate 'steps' calls to the hash function. */ + for (i = start+1; i < (start+steps) && i < XMSS_WOTS_W; i++) { + addr_buf[XMSS_ADDR_HASH * 4 + 3] = i; + wc_xmss_chain_hash_sha256_32(state, hash, hash); + } +#endif /* !WC_XMSS_FULL_HASH */ + } + else if (hash != data) { + XMEMCPY(hash, data, XMSS_SHA256_32_N); + } +} +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + +/* Chain hashing to calculate node hash. + * + * RFC 8391: 3.1.2, Algorithm 2 - recursive. + * This function is an iterative version. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] data Initial data to hash. + * @param [in] start Starting hash value in hash address. + * @param [in] steps Size of step. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address as a byte array. + * @param [out] hash Chained hash. + */ +static void wc_xmss_chain(XmssState* state, const byte* data, + unsigned int start, unsigned int steps, const byte* pk_seed, byte* addr, + byte* hash) +{ + const XmssParams* params = state->params; + + if (steps > 0) { + word32 i; + byte* pad = state->prf_buf; + byte* seed = pad + params->pad_len; + byte* addr_buf = seed + params->n; + + /* Set data for PRF hash. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, pad, params->pad_len); + XMEMCPY(seed, pk_seed, params->n); + XMEMCPY(addr_buf, addr, 32); + + /* Only do this once for all chain hash calls. */ + XMSS_PAD_ENC(XMSS_HASH_PADDING_F, state->buf, params->pad_len); + + /* Set address. */ + XMSS_ADDR_SET_BYTE(addr_buf, XMSS_ADDR_HASH, start); + wc_xmss_chain_hash(state, data, hash); + /* Iterate 'steps' calls to the hash function. */ + for (i = start+1; i < (start+steps) && i < XMSS_WOTS_W; i++) { + addr_buf[XMSS_ADDR_HASH * 4 + 3] = i; + wc_xmss_chain_hash(state, hash, hash); + } + } + else if (hash != data) { + XMEMCPY(hash, data, params->n); + } +} + +/* Convert base on message and add checksum. + * + * RFC 8391:, 2.6, Algorithm 1: base_w + * int in = 0; + * int out = 0; + * unsigned int total = 0; + * int bits = 0; + * int consumed; + * + * for ( consumed = 0; consumed < out_len; consumed++ ) { + * if ( bits == 0 ) { + * total = X[in]; + * in++; + * bits += 8; + * } + * bits -= lg(w); + * basew[out] = (total >> bits) AND (w - 1); + * out++; + * } + * return basew; + * + * base_w implemented for w == 16 (lg(w) == 4). + * + * RFC 8391: 3.1.5, Algorithm 5: + * ... + * csum = 0; + * + * # Convert message to base w + * msg = base_w(M, w, len_1); + * # Compute checksum + * for ( i = 0; i < len_1; i++ ) { + * csum = csum + w - 1 - msg[i]; + * } + * + * # Convert csum to base w + * csum = csum << ( 8 - ( ( len_2 * lg(w) ) % 8 )); + * len_2_bytes = ceil( ( len_2 * lg(w) ) / 8 ); + * msg = msg || base_w(toByte(csum, len_2_bytes), w, len_2); + * + * len_1 == 8 * n / 4 = n * 2 + * Implemented for len_2 == 3 + * + * @param [in] m Message data. + * @param [in] n Number of bytes in hash. + * @param [out] msg Message in new base. + */ +static void wc_xmss_msg_convert(const byte* m, word8 n, word8* msg) +{ + word8 i; + word16 csum = 0; + + /* Split each full byte of m into two bytes of msg. */ + for (i = 0; i < n; i++) { + msg[0] = m[i] >> 4; + msg[1] = m[i] & 0xf; + csum += XMSS_WOTS_W - 1 - msg[0]; + csum += XMSS_WOTS_W - 1 - msg[1]; + msg += 2; + } + + /* Append checksum to message. (Maximum value: 1920 = 64 * 2 * 15) */ + msg[0] = (csum >> 8) ; + msg[1] = (csum >> 4) & 0x0f; + msg[2] = (csum ) & 0x0f; +} + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + +/* WOTS+ generate public key with private seed. + * + * RFC 8391: 4.1.6, Algorithm 9: + * ... + * pk = WOTS_genPK (getWOTS_SK(SK, s + i), SEED, ADRS); + * RFC 8391, 3.1.4, Algorithm 4: WOTS_genPK + * ... + * for ( i = 0; i < len; i++ ) { + * ADRS.setChainAddress(i); + * pk[i] = chain(sk[i], 0, w - 1, SEED, ADRS); + * } + * return pk; + * + * WOTS_genPK only used in Algorithm 9 and it is convenient to combine with + * getWOTS_SK due to parameter specific implementations. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk Random private seed. + * @param [in] seed Random public seed. + * @param [in] addr Hashing address. + * @param [out] pk Public key. + */ +static void wc_xmss_wots_gen_pk(XmssState* state, const byte* sk, + const byte* seed, HashAddress addr, byte* pk) +{ + const XmssParams* params = state->params; + byte* addr_buf = state->encMsg; + word32 i; + + /* Ensure chain address is 0 and encode into a buffer. */ + addr[XMSS_ADDR_CHAIN] = 0; + wc_xmss_addr_encode(addr, addr_buf); + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + /* Expand the private seed - getWOTS_SK */ + wc_xmss_wots_get_wots_sk_sha256_32(state, sk, seed, addr_buf, + pk); + + /* Calculate chain hash. */ + wc_xmss_chain_sha256_32(state, pk, 0, XMSS_WOTS_W - 1, seed, addr_buf, + pk); + for (i = 1; i < params->wots_len; i++) { + pk += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain_sha256_32(state, pk, 0, XMSS_WOTS_W - 1, seed, + addr_buf, pk); + } + } + else +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + { + /* Expand the private seed - getWOTS_SK */ + wc_xmss_wots_get_wots_sk(state, sk, seed, addr_buf, pk); + + /* Calculate chain hash. */ + wc_xmss_chain(state, pk, 0, XMSS_WOTS_W - 1, seed, addr_buf, pk); + for (i = 1; i < params->wots_len; i++) { + pk += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain(state, pk, 0, XMSS_WOTS_W - 1, seed, addr_buf, pk); + } + } +} +/* Generate a signature from a privatge key and message. + * + * RFC 8391: 4.1.9, Algorithm 11: treeSig + * sig_ots = WOTS_sign(getWOTS_SK(SK, idx_sig), + * M', getSEED(SK), ADRS); + * RFC 8391: 3.1.5, Algorithm 5: WOTS_sign + * (Convert message to base w and append checksum in base w) + * ... + * for ( i = 0; i < len; i++ ) { + * ADRS.setChainAddress(i); + * sig[i] = chain(sk[i], 0, msg[i], SEED, ADRS); + * } + * return sig; + * + * WOTS_sign only used in Algorithm 11 and convenient to do getWOTS_SK due to + * hash address reuse and parameter specific implementations. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] m Message hash to sign. + * @param [in] sk Random private seed. + * @param [in] seed Random public seed. + * @param [in] addr Hashing address. + * @param [out] sig Calculated XMSS/MT signature. + */ +static void wc_xmss_wots_sign(XmssState* state, const byte* m, + const byte* sk, const byte* seed, HashAddress addr, byte* sig) +{ + const XmssParams* params = state->params; + byte* addr_buf = state->pk; + word32 i; + + /* Convert message to base w and append checksum in base w. */ + wc_xmss_msg_convert(m, params->n, state->encMsg); + + /* Set initial chain value and encode hash address. */ + addr[XMSS_ADDR_CHAIN] = 0; + wc_xmss_addr_encode(addr, addr_buf); + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + /* Expand the private seed - getWOTS_SK */ + wc_xmss_wots_get_wots_sk_sha256_32(state, sk, seed, addr_buf, sig); + + /* Calculate chain hash. */ + wc_xmss_chain_sha256_32(state, sig, 0, state->encMsg[0], seed, addr_buf, + sig); + for (i = 1; i < params->wots_len; i++) { + sig += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain_sha256_32(state, sig, 0, state->encMsg[i], seed, + addr_buf, sig); + } + } + else +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + { + /* Expand the private seed - getWOTS_SK */ + wc_xmss_wots_get_wots_sk(state, sk, seed, addr_buf, sig); + + /* Calculate chain hash. */ + wc_xmss_chain(state, sig, 0, state->encMsg[0], seed, addr_buf, sig); + for (i = 1; i < params->wots_len; i++) { + sig += params->n; + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain(state, sig, 0, state->encMsg[i], seed, addr_buf, sig); + } + } +} + +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + +/* Compute WOTS+ public key value from signature and message. + * + * RFC 8319: 3.1.6 + * Algorithm 6: WOTS_pkFromSig + * (Convert message to base w and append checksum in base w) + * ... + * for ( i = 0; i < len; i++ ) { + * ADRS.setChainAddress(i); + * tmp_pk[i] = chain(sig[i], msg[i], w - 1 - msg[i], SEED, ADRS); + * } + * return tmp_pk; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sig XMSS/MT Signature. + * @param [in] m Message to verify. + * @param [in] seed Random public seed. + * @param [in] addr Hashing address. + * @param [out] pk Public key. + */ +static void wc_xmss_wots_pk_from_sig(XmssState* state, const byte* sig, + const byte* m, const byte* seed, HashAddress addr, byte* pk) +{ + const XmssParams* params = state->params; + byte* addr_buf = state->stack; + word32 i; + + /* Convert message to base w and append checksum in base w. */ + wc_xmss_msg_convert(m, params->n, state->encMsg); + + /* Start with address with chain value of 0. */ + addr[XMSS_ADDR_CHAIN] = 0; + wc_xmss_addr_encode(addr, addr_buf); + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + /* Calculate chain hash. */ + wc_xmss_chain_sha256_32(state, sig, state->encMsg[0], + XMSS_WOTS_W - 1 - state->encMsg[0], seed, addr_buf, pk); + for (i = 1; i < params->wots_len; i++) { + sig += params->n; + pk += params->n; + /* Update chain. */ + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain_sha256_32(state, sig, state->encMsg[i], + XMSS_WOTS_W - 1 - state->encMsg[i], seed, addr_buf, pk); + } + } + else +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 */ + { + /* Calculate chain hash. */ + wc_xmss_chain(state, sig, state->encMsg[0], + XMSS_WOTS_W - 1 - state->encMsg[0], seed, addr_buf, pk); + for (i = 1; i < params->wots_len; i++) { + sig += params->n; + pk += params->n; + /* Update chain. */ + addr_buf[XMSS_ADDR_CHAIN * 4 + 3] = i; + wc_xmss_chain(state, sig, state->encMsg[i], + XMSS_WOTS_W - 1 - state->encMsg[i], seed, addr_buf, pk); + } + } +} + +/******************************************** + * L-TREE - unbalanced binary hash tree + ********************************************/ + +/* Compute leaves of L-tree from WOTS+ public key and compress to single value. + * + * RFC 8391: 4.1.5, Algorithm 8: ltree + * unsigned int len' = len; + * ADRS.setTreeHeight(0); + * while ( len' > 1 ) { + * for ( i = 0; i < floor(len' / 2); i++ ) { + * ADRS.setTreeIndex(i); + * pk[i] = RAND_HASH(pk[2i], pk[2i + 1], SEED, ADRS); + * } + * if ( len' % 2 == 1 ) { + * pk[floor(len' / 2)] = pk[len' - 1]; + * } + * len' = ceil(len' / 2); + * ADRS.setTreeHeight(ADRS.getTreeHeight() + 1); + * } + * return pk[0]; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] pk WOTS+ public key. + * @param [in] seed Random public seed. + * @param [in] addr Hashing address. + * @param [out] pk0 N-byte compressed public key value pk[0]. + */ +static void wc_xmss_ltree(XmssState* state, byte* pk, const byte* seed, + HashAddress addr, byte* pk0) +{ + const XmssParams* params = state->params; + word8 len = params->wots_len; + word32 h = 0; + +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) && \ + !defined(WC_XMSS_FULL_HASH) + /* Precompute hash state after first 64 bytes (common to all hashes). */ + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + byte* prf_buf = state->prf_buf; + int ret; + + XMSS_PAD_ENC(XMSS_HASH_PADDING_PRF, prf_buf, XMSS_SHA256_32_PAD_LEN); + XMEMCPY(prf_buf + XMSS_SHA256_32_PAD_LEN, seed, XMSS_SHA256_32_N); + + ret = wc_Sha256Update(&state->digest.sha256, prf_buf, + XMSS_SHA256_32_PAD_LEN + XMSS_SHA256_32_N); + if (ret == 0) { + /* Copy state after first 64 bytes. */ + XMSS_SHA256_STATE_CACHE(state); + } + else if (state->ret == 0) { + /* Store any digest failures for public APIs to return. */ + state->ret = ret; + } + } +#endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 && !WC_XMSS_FULL_HASH */ + while (len > 1) { + word8 i; + word8 len2 = len >> 1; + + addr[XMSS_ADDR_TREE_HEIGHT] = h++; + + for (i = 0; i < len2; i++) { + addr[XMSS_ADDR_TREE_INDEX] = i; + #if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) && \ + !defined(WC_XMSS_FULL_HASH) + if ((params->pad_len == XMSS_SHA256_32_PAD_LEN) && + (params->n == XMSS_SHA256_32_N) && + (params->hash == WC_HASH_TYPE_SHA256)) { + wc_xmss_rand_hash_sha256_32_prehash(state, + pk + i * 2 * XMSS_SHA256_32_N, addr, + pk + i * XMSS_SHA256_32_N); + } + else + #endif /* !WOLFSSL_WC_XMSS_SMALL && WC_XMSS_SHA256 && + * !WC_XMSS_FULL_HASH */ + { + wc_xmss_rand_hash(state, pk + i * 2 * params->n, + seed, addr, pk + i * params->n); + } + } + if (len & 1) { + XMEMCPY(pk + len2 * params->n, pk + (len - 1) * params->n, + params->n); + } + len = len2 + (len & 1); + } + /* Return compressed public key value pk[0]. */ + XMEMCPY(pk0, pk, params->n); +} + +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + +#ifdef WOLFSSL_WC_XMSS_SMALL + +/******************************************** + * TREE HASH + ********************************************/ + +#ifndef WOLFSSL_SMALL_STACK +/* Compute internal nodes of Merkle tree. + * + * Implementation always starts at index 0. (s = 0) + * + * Build authentication path, if required, rather than duplicating work. + * When node is generated, copy out to authentication path array of nodes. + * + * RFC 8391: 4.1.6, Algorithm 9: treeHash + * if( s % (1 << t) != 0 ) return -1; + * for ( i = 0; i < 2^t; i++ ) { + * SEED = getSEED(SK); + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(s + i); + * pk = WOTS_genPK (getWOTS_SK(SK, s + i), SEED, ADRS); + * ADRS.setType(1); # Type = L-tree address + * ADRS.setLTreeAddress(s + i); + * node = ltree(pk, SEED, ADRS); + * ADRS.setType(2); # Type = hash tree address + * ADRS.setTreeHeight(0); + * ADRS.setTreeIndex(i + s); + * while ( Top node on Stack has same height t' as node ) { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node = RAND_HASH(Stack.pop(), node, SEED, ADRS); + * ADRS.setTreeHeight(ADRS.getTreeHeight() + 1); + * } + * Stack.push(node); + * } + * return Stack.pop(); + * RFC 8391: 4.1.9, (Example) buildAuth + * for ( j = 0; j < h; j++ ) { + * k = floor(i / (2^j)) XOR 1; + * auth[j] = treeHash(SK, k * 2^j, j, ADRS); + * } + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk_seed Random private seed. + * @param [in] pk_seed Random public seed. + * @param [in] leafIdx Index of lead node. + * @param [in] subtree_addr Address of subtree. + * @param [out] root Root node of the tree. + * @param [out] auth_path Nodes of the authentication path. + */ +static void wc_xmss_treehash(XmssState* state, const byte* sk_seed, + const byte* pk_seed, word32 leafIdx, const word32* subtree, byte* root, + byte* auth_path) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + byte* node = state->stack; + HashAddress ots; + HashAddress ltree; + HashAddress tree; + word8 height[WC_XMSS_MAX_TREE_HEIGHT + 1]; + word8 offset = 0; + word32 max = (word32)1 << params->sub_h; + word32 i; + + /* Copy hash address into one for each purpose. */ + XMSS_ADDR_OTS_SET_SUBTREE(ots, subtree); + XMSS_ADDR_LTREE_SET_SUBTREE(ltree, subtree); + XMSS_ADDR_TREE_SET_SUBTREE(tree, subtree); + + for (i = 0; i < max; i++) { + word8 h; + + /* Calculate WOTS+ public key. */ + ots[XMSS_ADDR_OTS] = i; + wc_xmss_wots_gen_pk(state, sk_seed, pk_seed, ots, state->pk); + /* Calculate public value. */ + ltree[XMSS_ADDR_LTREE] = i; + wc_xmss_ltree(state, state->pk, pk_seed, ltree, node); + + /* Initial height at this offset is 0. */ + h = height[offset] = 0; + /* Copy node, at height 0, out if on authentication path. */ + if ((auth_path != NULL) && ((leafIdx ^ 0x1) == i)) { + XMEMCPY(auth_path, node, n); + } + + /* Top node on Stack has same height t' as node. */ + while ((offset >= 1) && (h == height[offset - 1])) { + word32 tree_idx = i >> (h + 1); + + node -= n; + /* Calculate hash of node. */ + tree[XMSS_ADDR_TREE_HEIGHT] = h; + tree[XMSS_ADDR_TREE_INDEX] = tree_idx; + wc_xmss_rand_hash(state, node, pk_seed, tree, node); + + /* Update offset and height. */ + offset--; + h = ++height[offset]; + + /* Copy node out if on authentication path. */ + if ((auth_path != NULL) && (((leafIdx >> h) ^ 0x1) == tree_idx)) { + XMEMCPY(auth_path + h * n, node, n); + } + } + offset++; + node += n; + } + + /* Copy the root node. */ + XMEMCPY(root, state->stack, n); +} +#else +/* Compute internal nodes of Merkle tree. + * + * Implementation always starts at index 0. (s = 0) + * + * Build authentication path, if required, rather than duplicating work. + * When node is generated, copy out to authentication path array of nodes. + * + * RFC 8391: 4.1.6, Algorithm 9: treeHash + * if( s % (1 << t) != 0 ) return -1; + * for ( i = 0; i < 2^t; i++ ) { + * SEED = getSEED(SK); + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(s + i); + * pk = WOTS_genPK (getWOTS_SK(SK, s + i), SEED, ADRS); + * ADRS.setType(1); # Type = L-tree address + * ADRS.setLTreeAddress(s + i); + * node = ltree(pk, SEED, ADRS); + * ADRS.setType(2); # Type = hash tree address + * ADRS.setTreeHeight(0); + * ADRS.setTreeIndex(i + s); + * while ( Top node on Stack has same height t' as node ) { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node = RAND_HASH(Stack.pop(), node, SEED, ADRS); + * ADRS.setTreeHeight(ADRS.getTreeHeight() + 1); + * } + * Stack.push(node); + * } + * return Stack.pop(); + * RFC 8391: 4.1.9, (Example) buildAuth + * for ( j = 0; j < h; j++ ) { + * k = floor(i / (2^j)) XOR 1; + * auth[j] = treeHash(SK, k * 2^j, j, ADRS); + * } + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk_seed Random private seed. + * @param [in] pk_seed Random public seed. + * @param [in] leafIdx Index of lead node. + * @param [in] subtree_addr Address of subtree. + * @param [out] root Root node of the tree. + * @param [out] auth_path Nodes of the authentication path. + */ +static void wc_xmss_treehash(XmssState* state, const byte* sk_seed, + const byte* pk_seed, word32 leafIdx, const word32* subtree, byte* root, + byte* auth_path) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + byte* node = state->stack; + HashAddress addr; + word8 height[WC_XMSS_MAX_TREE_HEIGHT + 1]; + word8 offset = 0; + word32 max = (word32)1 << params->sub_h; + word32 i; + + XMSS_ADDR_SET_SUBTREE(addr, subtree, 0); + + for (i = 0; i < max; i++) { + word8 h; + + /* Calculate WOTS+ public key. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + addr[XMSS_ADDR_LTREE] = i; + wc_xmss_wots_gen_pk(state, sk_seed, pk_seed, addr, state->pk); + /* Calculate public value. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_LTREE; + wc_xmss_ltree(state, state->pk, pk_seed, addr, node); + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_TREE; + addr[XMSS_ADDR_TREE_ZERO] = 0; + + /* Initial height at this offset is 0. */ + h = height[offset] = 0; + /* Copy node out if on authentication path. */ + if ((auth_path != NULL) && ((leafIdx ^ 0x1) == i)) { + XMEMCPY(auth_path, node, n); + } + + /* Top node on Stack has same height t' as node. */ + while ((offset >= 1) && (h == height[offset - 1])) { + word32 tree_idx = i >> (h + 1); + + node -= n; + /* Calculate hash of node. */ + addr[XMSS_ADDR_TREE_HEIGHT] = h; + addr[XMSS_ADDR_TREE_INDEX] = tree_idx; + wc_xmss_rand_hash(state, node, pk_seed, addr, node); + + /* Update offset and height. */ + offset--; + h = ++height[offset]; + + /* Copy node out if on authentication path. */ + if ((auth_path != NULL) && (((leafIdx >> h) ^ 0x1) == tree_idx)) { + XMEMCPY(auth_path + h * n, node, n); + } + } + offset++; + node += n; + /* Reset hash address ready for use as OTS and LTREE. */ + addr[XMSS_ADDR_TREE_HEIGHT] = 0; + addr[XMSS_ADDR_TREE_INDEX] = 0; + } + + /* Copy the root node. */ + XMEMCPY(root, state->stack, n); +} +#endif /* !WOLFSSL_SMALL_STACK */ + +/******************************************** + * MAKE KEY + ********************************************/ + +/* Derives XMSSMT (and XMSS) key pair from seeds. + * + * RFC 8391: 4.1.7, Algorithm 10: XMSS_keyGen. + * ... + * initialize SK_PRF with a uniformly random n-byte string; + * setSK_PRF(SK, SK_PRF); + * + * # Initialization for common contents + * initialize SEED with a uniformly random n-byte string; + * setSEED(SK, SEED); + * setWOTS_SK(SK, wots_sk)); + * ADRS = toByte(0, 32); + * root = treeHash(SK, 0, h, ADRS); + * + * SK = idx || wots_sk || SK_PRF || root || SEED; + * PK = OID || root || SEED; + * return (SK || PK); + * + * wots_sk, SK_PRF and SEED passed in as seed. + * Store seed for wots_sk instead of generated wots_sk. + * OID not stored in PK this is handled in upper layer. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] seed Random seeds. + * @param [out] sk Secret/Private key. + * @param [out] pk Public key. + * @return 0 on success. + * @return <0 on digest failure. + */ +int wc_xmssmt_keygen(XmssState* state, const unsigned char* seed, + unsigned char* sk, unsigned char* pk) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + const byte* seed_priv = seed; + const byte* seed_pub = seed + 2 * n; + /* Offsets into secret/private key. */ + byte* sk_idx = sk; + byte* sk_seed = sk_idx + params->idx_len; + byte* sk_pub = sk_seed + 2 * n; + /* Offsets into public key. */ + byte* pk_root = pk; + byte* pk_seed = pk_root + n; + + /* Set first index to 0 in private key. */ + XMEMSET(sk_idx, 0, params->idx_len); + /* Set private key seed and private key for PRF in to private key. */ + XMEMCPY(sk_seed, seed_priv, 2 * n); + /* Set public key seed into public key. */ + XMEMCPY(pk_seed, seed_pub, n); + + /* Set all address values to zero. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + /* Set depth into address. */ + state->addr[XMSS_ADDR_LAYER] = params->d - 1; + /* Compute root node into public key. */ + wc_xmss_treehash(state, sk_seed, pk_seed, 0, state->addr, pk_root, NULL); + + /* Append public key (root node and public seed) to private key. */ + XMEMCPY(sk_pub, pk_root, 2 * n); + + /* Return any errors that occurred during hashing. */ + return state->ret; +} + +/******************************************** + * SIGN + ********************************************/ + +/** + * Sign message using XMSS/XMSS^MT. + * + * RFC 8391: 4.1.9, Algorithm 11: treeSig + * auth = buildAuth(SK, idx_sig, ADRS); + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(idx_sig); + * sig_ots = WOTS_sign(getWOTS_SK(SK, idx_sig), + * M', getSEED(SK), ADRS); + * Sig = sig_ots || auth; + * return Sig; + * RFC 8391: 4.2.4, Algorithm 16: XMSSMT_sign + * # Init + * ADRS = toByte(0, 32); + * SEED = getSEED(SK_MT); + * SK_PRF = getSK_PRF(SK_MT); + * idx_sig = getIdx(SK_MT); + * + * # Update SK_MT + * setIdx(SK_MT, idx_sig + 1); + * + * # Message compression + * byte[n] r = PRF(SK_PRF, toByte(idx_sig, 32)); + * byte[n] M' = H_msg(r || getRoot(SK_MT) || (toByte(idx_sig, n)), M); + * + * # Sign + * Sig_MT = idx_sig; + * unsigned int idx_tree + * = (h - h / d) most significant bits of idx_sig; + * unsigned int idx_leaf = (h / d) least significant bits of idx_sig; + * SK = idx_leaf || getXMSS_SK(SK_MT, idx_tree, 0) || SK_PRF + * || toByte(0, n) || SEED; + * ADRS.setLayerAddress(0); + * ADRS.setTreeAddress(idx_tree); + * Sig_tmp = treeSig(M', SK, idx_leaf, ADRS); + * Sig_MT = Sig_MT || r || Sig_tmp; + * for ( j = 1; j < d; j++ ) { + * root = treeHash(SK, 0, h / d, ADRS); + * idx_leaf = (h / d) least significant bits of idx_tree; + * idx_tree = (h - j * (h / d)) most significant bits of idx_tree; + * SK = idx_leaf || getXMSS_SK(SK_MT, idx_tree, j) || SK_PRF + * || toByte(0, n) || SEED; + * ADRS.setLayerAddress(j); + * ADRS.setTreeAddress(idx_tree); + * Sig_tmp = treeSig(root, SK, idx_leaf, ADRS); + * Sig_MT = Sig_MT || Sig_tmp; + * } + * return SK_MT || Sig_MT + * + * buildAuth from treeSig done inside treeHash as this is more efficient. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] m Buffer holding message. + * @param [in] mlen Length of message in buffer. + * @param [in, out] sk Secret/Private key. + * @param [out] sig Signature. + * @return 0 on success. + * @return <0 on digest failure. + */ +int wc_xmssmt_sign(XmssState* state, const unsigned char* m, word32 mlen, + unsigned char* sk, unsigned char* sig) +{ + int ret = 0; + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 hs = params->sub_h; + const word16 hsn = (word16)hs * n; + const byte* sk_seed = sk + params->idx_len; + const byte* pk_seed = sk + params->idx_len + 3 * n; + wc_Idx idx; + byte* sig_r = sig + params->idx_len; + byte root[WC_XMSS_MAX_N]; + unsigned int i; + + WC_IDX_ZERO(idx); + /* Set all address values to zero and set type to OTS. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + state->addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + + /* Copy the index into the signature data: Sig_MT = idx_sig. */ + XMEMCPY(sig, sk, params->idx_len); + + /* Read index from the secret key. */ + WC_IDX_DECODE(idx, params->idx_len, sk, ret); + /* Validate index in secret key. */ + if ((ret == 0) && (WC_IDX_INVALID(idx, params->idx_len, params->h))) { + /* Set index to maximum value to distinguish from valid value. */ + XMEMSET(sk, 0xFF, params->idx_len); + /* Zeroize the secret key. */ + ForceZero(sk + params->idx_len, params->sk_len - params->idx_len); + ret = KEY_EXHAUSTED_E; + } + + /* Update SK_MT */ + if (ret == 0) { + /* Increment the index in the secret key. */ + wc_idx_update(sk, params->idx_len); + } + + /* Message compression */ + if (ret == 0) { + const byte* sk_prf = sk + params->idx_len + n; + + /* byte[n] r = PRF(SK_PRF, toByte(idx_sig, 32)); */ + wc_idx_copy(sig, params->idx_len, state->buf, XMSS_PRF_M_LEN); + wc_xmss_prf(state, sk_prf, state->buf, sig_r); + ret = state->ret; + } + if (ret == 0) { + const byte* pub_root = sk + params->idx_len + 2 * n; + /* byte[n] M' = H_msg(r || getRoot(SK_MT) || (toByte(idx_sig, n)), M); + */ + wc_xmss_hash_message(state, sig_r, pub_root, sig, params->idx_len, m, + mlen, root); + ret = state->ret; + /* Place WOTS+ signatures after index and 'r'. */ + sig += params->idx_len + n; + } + + /* Sign. */ + for (i = 0; (ret == 0) && (i < params->d); i++) { + word32 idx_leaf = 0; + + /* Set layer, tree and OTS leaf index into hash address. */ + state->addr[XMSS_ADDR_LAYER] = i; + WC_IDX_SET_ADDR_TREE(idx, params->idx_len, hs, state->addr, idx_leaf); + /* treeSig || treeHash = sig_ots || auth */ + state->addr[XMSS_ADDR_OTS] = idx_leaf; + /* Create WOTS+ signature for tree into signature (sig_ots). */ + wc_xmss_wots_sign(state, root, sk_seed, pk_seed, state->addr, sig); + ret = state->ret; + if (ret == 0) { + sig += params->wots_sig_len; + /* Add authentication path (auth) and calc new root. */ + wc_xmss_treehash(state, sk_seed, pk_seed, idx_leaf, state->addr, + root, sig); + ret = state->ret; + sig += hsn; + } + } + + return ret; +} + +#else + +/******************************************** + * Fast C implementation + ********************************************/ + +/* Tree hash data - needs to be unpacked from binary. */ +typedef struct TreeHash { + /* Next index to update in tree - max 20 bits. */ + word32 nextIdx; + /* Number of stack entries used by tree - 0... */ + word8 used; + /* Tree is finished. */ + word8 completed; +} TreeHash; + +/* BDS state. */ +typedef struct BdsState { + /* Stack of nodes - subtree height + 1 nodes. */ + byte* stack; + /* Height of stack node - subtree height + 1 of 0... */ + byte* height; + /* Authentication path for next index - subtree height nodes. */ + byte* authPath; + /* Hashes of nodes kept - subtree height / 2 nodes. */ + byte* keep; + /* Tree hash instances - subtree height minus K instances. */ + byte* treeHash; + /* Hashes of nodes for tree hash - one for each tree hash instance. */ + byte* treeHashNode; + /* Hashes of nodes to retain - based on K parameter. */ + byte* retain; + /* Next leaf to calculate - max 20 bits. */ + word32 next; + /* Current offset into stack - 0... */ + word8 offset; +} BdsState; + +/* Index to BDS state accounting for swapping. + * + * @param [in] idx Index of node. + * @param [in] i Depth of tree. + * @param [in] hs Height of subtree. + * @param [in] d Depth/number of trees. + * @return Index of working BDS state. + */ +#define BDS_IDX(idx, i, hs, d) \ + (((((idx) >> ((hs) * ((i) + 1))) & 1) == 0) ? (i) : ((d) + (i))) +/* Index to alternate BDS state accounting for swapping. + * + * @param [in] idx Index of node. + * @param [in] i Depth of tree. + * @param [in] hs Height of subtree. + * @param [in] d Depth/number of trees. + * @return Index of alternate BDS state. + */ +#define BDS_ALT_IDX(idx, i, hs, d) \ + (((((idx) >> ((hs) * ((i) + 1))) & 1) == 0) ? ((d) + (i)) : (i)) + +/******************************************** + * Tree Hash APIs + ********************************************/ + +/* Initialize the tree hash data at specified index for the BDS state. + * + * @param [in, out] bds BDS state. + * @param [in] i Index of tree hash. + */ +static void wc_xmss_bds_state_treehash_init(BdsState* bds, int i) +{ + byte* sk = bds->treeHash + i * 4; + c32to24(0, sk); + sk[3] = 0 | (1 << 7); +} + +/* Set next index into tree hash data at specified index for the BDS state. + * + * @param [in, out] bds BDS state. + * @param [in] i Index of tree hash. + * @param [in] nextIdx Next index for tree hash. + */ +static void wc_xmss_bds_state_treehash_set_next_idx(BdsState* bds, int i, + word32 nextIdx) +{ + byte* sk = bds->treeHash + i * 4; + c32to24(nextIdx, sk); + sk[3] = 0 | (0 << 7); +} + +/* Mark tree hash, at specified index for the BDS state, as complete. + * + * @param [in, out] bds BDS state. + * @param [in] i Index of tree hash. + */ +static void wc_xmss_bds_state_treehash_complete(BdsState* bds, int i) +{ + byte* sk = bds->treeHash + i * 4; + sk[3] |= 1 << 7; +} + +/* Get the tree hash data at specified index for the BDS state. + * + * @param [in] bds BDS state. + * @param [in] i Index of tree hash. + * @param [out] treeHash Tree hash instance to fill out. + */ +static void wc_xmss_bds_state_treehash_get(BdsState* bds, int i, + TreeHash* treeHash) +{ + byte* sk = bds->treeHash + i * 4; + ato24(sk, &treeHash->nextIdx); + treeHash->used = sk[3] & 0x7f; + treeHash->completed = sk[3] >> 7; +} + +/* Set the tree hash data at specified index for the BDS state. + * + * @param [in, out] bds BDS state. + * @param [in] i Index of tree hash. + * @param [in] treeHash Tree hash data. + */ +static void wc_xmss_bds_state_treehash_set(BdsState* bds, int i, + TreeHash* treeHash) +{ + byte* sk = bds->treeHash + i * 4; + c32to24(treeHash->nextIdx, sk); + sk[3] = treeHash->used | (treeHash->completed << 7); +} + +/******************************************** + * BDS State APIs + ********************************************/ + +/* Allocate memory for BDS state. + * + * When using a static BDS state (XMSS) then pass in handle to data for bds. + * + * @param [in] params XMSS/MT parameters. + * @param [in, out] bds Handle to BDS state. May be NULL if not allocated. + * @return 0 on success. + * @return MEMORY_E on dynamic memory allocation failure. + */ +static int wc_xmss_bds_state_alloc(const XmssParams* params, BdsState** bds) +{ + const word8 cnt = 2 * params->d - 1; + int ret = 0; + + if (*bds == NULL) { + /* Allocate memory for BDS states. */ + *bds = (BdsState*)XMALLOC(sizeof(BdsState) * cnt, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (*bds == NULL) { + ret = MEMORY_E; + } + } + + return ret; +} + +/* Dispose of allocated memory associated with BDS state. + * + * @param [in] bds BDS state. + */ +static void wc_xmss_bds_state_free(BdsState* bds) +{ + /* BDS states was allocated - must free. */ + XFREE(bds, NULL, DYNAMIC_TYPE_TMP_BUFFER); +} + +/* Load the BDS state from the secret/private key. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] sk Secret/private key. + * @param [out] bds BDS states. + * @param [out] wots_sigs WOTS signatures when XMSS^MT. + */ +static void wc_xmss_bds_state_load(const XmssState* state, byte* sk, + BdsState* bds, byte** wots_sigs) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + const word8 k = params->bds_k; + const word32 retainLen = XMSS_RETAIN_LEN(k, n); + int i; + + /* Skip past standard SK = idx || wots_sk || SK_PRF || root || SEED; */ + sk += params->idx_len + 4 * n; + + for (i = 0; i < 2 * (int)params->d - 1; i++) { + /* Set pointers into SK. */ + bds[i].stack = sk; + sk += (hs + 1) * n; + bds[i].height = sk; + sk += hs + 1; + bds[i].authPath = sk; + sk += hs * n; + bds[i].keep = sk; + sk += (hs >> 1) * n; + bds[i].treeHash = sk; + sk += hsk * 4; + bds[i].treeHashNode = sk; + sk += hsk * n; + bds[i].retain = sk; + sk += retainLen; + /* Load values - big-endian encoded. */ + ato24(sk, &bds[i].next); + sk += 3; + bds[i].offset = sk[0]; + sk += 1; + } + + if (wots_sigs != NULL) { + *wots_sigs = sk; + } +} + +/* Store the BDS state into the secret/private key. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] sk Secret/private key. + * @param [in] bds BDS states. + */ +static void wc_xmss_bds_state_store(const XmssState* state, byte* sk, + BdsState* bds) +{ + int i; + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + const word8 k = params->bds_k; + const word32 skip = (hs + 1) * n + /* BdsState.stack */ + hs + 1 + /* BdsState.height */ + hs * n + /* BdsState.authPath */ + (hs >> 1) * n + /* BdsState.keep */ + hsk * 4 + /* BdsState.treeHash */ + hsk * n + /* BdsState.treeHashNode */ + XMSS_RETAIN_LEN(k, n); /* BdsState.retain */ + + /* Ignore standard SK = idx || wots_sk || SK_PRF || root || SEED; */ + sk += params->idx_len + 4 * n; + + for (i = 0; i < 2 * (int)params->d - 1; i++) { + /* Skip pointers into sk. */ + sk += skip; + /* Save values - big-endian encoded. */ + c32to24(bds[i].next, sk); + sk += 3; + sk[0] = bds[i].offset; + sk += 1; + } +} + +/******************************************** + * BDS + ********************************************/ + +/* Compute node at next index. + * + * RFC 8391: 4.1.6, Algorithm 9: treeHash + * ... + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(s + i); + * pk = WOTS_genPK (getWOTS_SK(SK, s + i), SEED, ADRS); + * ADRS.setType(1); # Type = L-tree address + * ADRS.setLTreeAddress(s + i); + * node = ltree(pk, SEED, ADRS); + * ADRS.setType(2); # Type = hash tree address + * ADRS.setTreeHeight(0); + * ADRS.setTreeIndex(i + s); + * while ( Top node on Stack has same height t' as node ) { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node = RAND_HASH(Stack.pop(), node, SEED, ADRS); + * ADRS.setTreeHeight(ADRS.getTreeHeight() + 1); + * } + * Stack.push(node); + * ... + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] bds BDS state. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] root Root node. + */ +static void wc_xmss_bds_next_idx(XmssState* state, BdsState* bds, + const byte* sk_seed, const byte* pk_seed, HashAddress addr, int i, + word8* height, word8* offset, word8** sp) +{ + const XmssParams* params = state->params; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + const word8 n = params->n; + word8 o = *offset; + word8* node = *sp; + word8 h; + + /* Calculate WOTS+ public key. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + addr[XMSS_ADDR_OTS] = i; + wc_xmss_wots_gen_pk(state, sk_seed, pk_seed, addr, state->pk); + /* Calculate public value. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_LTREE; + wc_xmss_ltree(state, state->pk, pk_seed, addr, node); + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_TREE; + addr[XMSS_ADDR_TREE_ZERO] = 0; + + /* Initial height at this offset is 0. */ + h = height[o] = 0; + /* HDSS, Section 4.5, 2: TREEHASH[h].push(v[h][3]) + * Copy right node to tree hash nodes if second right node. */ + if ((hsk > 0) && (i == 3)) { + XMEMCPY(bds->treeHashNode, node + n, n); + } + + /* Top node on Stack has same height t' as node. */ + while ((o >= 1) && (h == height[o - 1])) { + /* HDSS, Section 4.5, 1: AUTH[h] = v[h][1], h = 0,...,H-1. + * Cache left node if on authentication path. */ + if ((i >> h) == 1) { + XMEMCPY(bds->authPath + h * n, node, n); + } + /* This is a right node. */ + else if (h < hsk) { + /* HDSS, Section 4.5, 2: TREEHASH[h].push(v[h][3]) + * Copy right node to tree hash if second right node. */ + if ((i >> h) == 3) { + XMEMCPY(bds->treeHashNode + h * n, node, n); + } + } + else { + /* HDSS, Section 4.5, 3: RETAIN[h].push(v[j][2j+3] for + * h = H-K,...,H-2 and j = 2^(H-h-1)-2,...,0. + * Retain high right nodes. + */ + word32 ro = (1 << (hs - 1 - h)) + h - hs + (((i >> h) - 3) >> 1); + XMEMCPY(bds->retain + ro * n, node, n); + } + + node -= n; + /* Calculate hash of node. */ + addr[XMSS_ADDR_TREE_HEIGHT] = h; + addr[XMSS_ADDR_TREE_INDEX] = i >> (h + 1); + wc_xmss_rand_hash(state, node, pk_seed, addr, node); + + /* Update offset and height. */ + o--; + h = ++height[o]; + } + + *offset = o; + *sp = node; +} + +/* Compute initial Merkle tree and store nodes. + * + * HDSS, Section 4.5, The algorithm, Initialization. + * 1. We store the authentication path for the first leaf (s = 0): + * AUTH[h] = v[h][1], h = 0,...,H-1. + * 2. Depending on the parameter K, we store the next right authentication + * node for each height h = 0,...,H-K-1 in the treehash instances: + * TREEHASH[h].push(v[h][3]). + * 3. Finally we store the right authentication nodes clode to the root using + * the stacks RETAIN[h]: + * RETAIN[h].push(v[j][2j+3] for h = H-K,...,H-2 and j = 2^(H-h-1)-2,...,0. + * + * RFC 8391: 4.1.6, Algorithm 9: treeHash + * if( s % (1 << t) != 0 ) return -1; + * for ( i = 0; i < 2^t; i++ ) { + * SEED = getSEED(SK); + * [Compute node at next index] + * } + * return Stack.pop(); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] bds BDS state. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [out] root Root node. + */ +static void wc_xmss_bds_treehash_initial(XmssState* state, BdsState* bds, + const byte* sk_seed, const byte* pk_seed, const HashAddress addr, + byte* root) +{ + const XmssParams* params = state->params; + const word8 hsk = params->sub_h - params->bds_k; + const word8 n = params->n; + word8* node = state->stack; + HashAddress addrCopy; + word8 height[WC_XMSS_MAX_TREE_HEIGHT + 1]; + word8 offset = 0; + word32 maxIdx = (word32)1 << params->sub_h; + word32 i; + + /* First signing index will be 0 - setup BDS state. */ + bds->offset = 0; + bds->next = 0; + /* Reset the hash tree status. */ + for (i = 0; i < hsk; i++) { + wc_xmss_bds_state_treehash_init(bds, i); + } + + /* Copy hash address into local. */ + XMSS_ADDR_OTS_SET_SUBTREE(addrCopy, addr); + + /* Compute each node in tree. */ + for (i = 0; i < maxIdx; i++) { + wc_xmss_bds_next_idx(state, bds, sk_seed, pk_seed, addrCopy, i, height, + &offset, &node); + offset++; + node += n; + /* Rest the hash address for reuse. */ + addrCopy[XMSS_ADDR_TREE_HEIGHT] = 0; + addrCopy[XMSS_ADDR_TREE_INDEX] = 0; + } + + /* Copy the root node. */ + XMEMCPY(root, state->stack, n); +} + +/* Update internal nodes of Merkle tree at next index. + * + * RFC 8391: 4.1.6, Algorithm 9: treeHash + * ... + * SEED = getSEED(SK); + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(s + i); + * pk = WOTS_genPK (getWOTS_SK(SK, s + i), SEED, ADRS); + * ADRS.setType(1); # Type = L-tree address + * ADRS.setLTreeAddress(s + i); + * node = ltree(pk, SEED, ADRS); + * ADRS.setType(2); # Type = hash tree address + * ADRS.setTreeHeight(0); + * ADRS.setTreeIndex(i + s); + * while ( Top node on Stack has same height t' as node ) { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node = RAND_HASH(Stack.pop(), node, SEED, ADRS); + * ADRS.setTreeHeight(ADRS.getTreeHeight() + 1); + * } + * Stack.push(node); + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] height Height of nodes to update. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + */ +static void wc_xmss_bds_treehash_update(XmssState* state, BdsState* bds, + word8 height, const byte* sk_seed, const byte* pk_seed, + const HashAddress addr) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + HashAddress addrLocal; + TreeHash treeHash[1]; + byte* sp = bds->stack + bds->offset * n; + byte* node = state->stack + WC_XMSS_MAX_STACK_LEN - n; + word8 h; + + /* Get the tree hash data. */ + wc_xmss_bds_state_treehash_get(bds, height, treeHash); + /* Copy hash address into local as OTS type. */ + XMSS_ADDR_OTS_SET_SUBTREE(addrLocal, addr); + /* Calculate WOTS+ public key. */ + addrLocal[XMSS_ADDR_OTS] = treeHash->nextIdx; + wc_xmss_wots_gen_pk(state, sk_seed, pk_seed, addrLocal, state->pk); + /* Calculate public value. */ + addrLocal[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_LTREE; + wc_xmss_ltree(state, state->pk, pk_seed, addrLocal, node); + addrLocal[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_TREE; + addrLocal[XMSS_ADDR_TREE_ZERO] = 0; + + /* Initial height is 0. */ + h = 0; + + /* Top node on Stack has same height t' as node. */ + while ((treeHash->used > 0) && (h == bds->height[bds->offset - 1])) { + sp -= n; + /* Copy from stack to before last calculated node. */ + node -= n; + XMEMCPY(node, sp, n); + + /* Calculate hash of node. */ + addrLocal[XMSS_ADDR_TREE_HEIGHT] = h; + addrLocal[XMSS_ADDR_TREE_INDEX] = treeHash->nextIdx >> (h + 1); + wc_xmss_rand_hash(state, node, pk_seed, addrLocal, node); + + /* Update used, offset and height. */ + treeHash->used--; + bds->offset--; + h++; + } + + /* Check whether we reached the height we wanted to update. */ + if (h == height) { + /* Cache node. */ + XMEMCPY(bds->treeHashNode + height * n, node, n); + treeHash->completed = 1; + } + else { + /* Push calculated node onto stack. */ + XMEMCPY(sp, node, n); + treeHash->used++; + /* Update BDS state. */ + bds->height[bds->offset] = h; + bds->offset++; + treeHash->nextIdx++; + } + + /* Set the tree hash data back. */ + wc_xmss_bds_state_treehash_set(bds, height, treeHash); +} + +/* Updates hash trees that need it most. + * + * Algorithm 4.6: Authentication path computation, Step 5. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] updates Current number of updates. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @return Number of available updates. + */ +static word8 wc_xmss_bds_treehash_updates(XmssState* state, BdsState* bds, + word8 updates, const byte* sk_seed, const byte* pk_seed, + const HashAddress addr) +{ + const XmssParams* params = state->params; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + + while (updates > 0) { + word8 minH = hs; + word8 h = hsk; + word8 i; + + /* Step 5.a. k <- min{ h: TREEHASH(h).height() = + min[j=0..H-K-1]{TREEHASH(j.height()} } */ + for (i = 0; i < hsk; i++) { + TreeHash treeHash[1]; + + wc_xmss_bds_state_treehash_get(bds, i, treeHash); + + if (treeHash->completed) { + /* Finished - ignore. */ + } + else if (treeHash->used == 0) { + /* None used, low height. */ + if (i < minH) { + h = i; + minH = i; + } + } + /* Find the height of lowest in cache. */ + else { + word8 j; + word8 lowH = hs; + byte* height = bds->height + bds->offset - treeHash->used; + + for (j = 0; j < treeHash->used; j++) { + lowH = min(height[j], lowH); + } + if (lowH < minH) { + /* New lowest height. */ + h = i; + minH = lowH; + } + } + } + /* If none lower, then stop. */ + if (h == hsk) { + break; + } + + /* Step 5.b. TREEHASH(k).update() */ + /* Update tree to the lowest height. */ + wc_xmss_bds_treehash_update(state, bds, h, sk_seed, pk_seed, addr); + updates--; + } + return updates; +} + +/* Update BDS at next leaf. + * + * Don't do anything if processed all leaves. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + */ +static void wc_xmss_bds_update(XmssState* state, BdsState* bds, + const byte* sk_seed, const byte* pk_seed, const HashAddress addr) +{ + if (bds->next < ((word32)1 << state->params->sub_h)) { + const XmssParams* params = state->params; + byte* sp = bds->stack + bds->offset * params->n; + HashAddress addrCopy; + + XMSS_ADDR_OTS_SET_SUBTREE(addrCopy, addr); + wc_xmss_bds_next_idx(state, bds, sk_seed, pk_seed, addrCopy, bds->next, + bds->height, &bds->offset, &sp); + bds->offset++; + bds->next++; + } +} + +/* Find index of lowest zero bit. + * + * Supports max up to 31. + * + * @param [in] n Number to evaluate. + * @param [in] max Max number of bits. + * @param [out] b Next bit above first zero bit. + * @return Index of lowest bit that is zero. + */ +static word8 wc_xmss_lowest_zero_bit_index(word32 n, word8 max, word8* b) +{ + word8 i; + + /* Check each bit from lowest for a zero bit. */ + for (i = 0; i < max; i++) { + if ((n & 1) == 0) { + break; + } + n >>= 1; + } + + /* Return next bit after 0 bit. */ + *b = (n >> 1) & 1; + return i; +} + +/* Returns auth path for node leafIdx and computes for next leaf node. + * + * HDSS, Algorithm 4.6: Authentication path computation, Steps 1-4. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] leafIdx Current leaf index. + * @param [in] sk_seed Random secret/private seed. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + */ +static void wc_xmss_bds_auth_path(XmssState* state, BdsState* bds, + const word32 leafIdx, const byte* sk_seed, const byte* pk_seed, + HashAddress addr) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + word8 tau; + byte* node = state->encMsg; + word8 parent; + + /* Step 1. Find the height of first left node in authentication path. */ + tau = wc_xmss_lowest_zero_bit_index(leafIdx, hs, &parent); + if (tau == 0) { + /* Step 2. Keep node if parent is a left node. + * if s/(2^tau+1) is even and tau < H-1 then KEEP[tau] <- AUTH[tau] + */ + if (parent == 0) { + XMEMCPY(bds->keep, bds->authPath, n); + } + + /* Step 3. if tau = 0 then AUTH[0] <- LEAFCALC(s) */ + /* Calculate WOTS+ public key. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + addr[XMSS_ADDR_OTS] = leafIdx; + wc_xmss_wots_gen_pk(state, sk_seed, pk_seed, addr, state->pk); + /* Calculate public value. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_LTREE; + wc_xmss_ltree(state, state->pk, pk_seed, addr, bds->authPath); + } + else { + byte* authPath; + byte* nodes; + word8 i; + + authPath = bds->authPath + tau * n; + /* Step 4.a. = AUTH[tau-1] || KEEP[tau-1] + * Only keeping half of nodes, so need to copy out before updating. + */ + XMEMCPY(node, authPath - n, n); + XMEMCPY(node + n, bds->keep + ((tau - 1) >> 1) * n, n); + + /* Step 2. Keep node if parent is a left node. + * if s/(2^tau+1) is even and tau < H-1 then KEEP[tau] <- AUTH[tau] + */ + if ((tau < hs - 1) && (parent == 0)) { + XMEMCPY(bds->keep + (tau >> 1) * n, authPath, n); + } + + /* Step 4.a. AUTH[tau] <- g() */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_TREE; + addr[XMSS_ADDR_TREE_ZERO] = 0; + addr[XMSS_ADDR_TREE_HEIGHT] = tau - 1; + addr[XMSS_ADDR_TREE_INDEX] = leafIdx >> tau; + wc_xmss_rand_hash(state, node, pk_seed, addr, authPath); + + /* Step 4.b. */ + authPath = bds->authPath; + nodes = bds->treeHashNode; + /* for h = 0 to tau - 1 do */ + for (i = 0; i < tau; i++) { + /* if h < H - K then AUTH[h] <- TREEHASH[h].pop()*/ + if (i < hsk) { + XMEMCPY(authPath, nodes, n); + nodes += n; + } + /* if h >= H - K then AUTH[h] <- RETAIN[h].pop()*/ + else { + word32 o = (1 << (hs - 1 - i)) + i - hs + + (((leafIdx >> i) - 1) >> 1); + XMEMCPY(authPath, bds->retain + o * n, n); + } + authPath += n; + } + + /* Step 4.c. Initialize treehash instances for heights: + * 0, ..., min{tau-1, H - K - 1} */ + tau = min(tau, hsk); + for (i = 0; i < tau; i++) { + word32 startIdx = leafIdx + 1 + 3 * (1 << i); + if (startIdx < ((word32)1 << hs)) { + wc_xmss_bds_state_treehash_set_next_idx(bds, i, startIdx); + } + } + } +} + +/******************************************** + * XMSS + ********************************************/ + +/* Derives XMSS key pair from seeds. + * + * RFC 8391: 4.1.7, Algorithm 10: XMSS_keyGen. + * ... + * initialize SK_PRF with a uniformly random n-byte string; + * setSK_PRF(SK, SK_PRF); + * + * # Initialization for common contents + * initialize SEED with a uniformly random n-byte string; + * setSEED(SK, SEED); + * setWOTS_SK(SK, wots_sk)); + * ADRS = toByte(0, 32); + * root = treeHash(SK, 0, h, ADRS); + * + * SK = idx || wots_sk || SK_PRF || root || SEED; + * PK = OID || root || SEED; + * return (SK || PK); + * + * HDSS, Section 4.5, The algorithm, Initialization. + * + * wots_sk, SK_PRF and SEED passed in as seed. + * Store seed for wots_sk instead of generated wots_sk. + * OID not stored in PK this is handled in upper layer. + * BDS state is appended to SK: + * SK = idx || wots_sk || SK_PRF || root || SEED || BDS_STATE; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] seed Secret/Private and public seed. + * @param [out] sk Secret key. + * @param [out] pk Public key. + * @return 0 on success. + * @return MEMORY_E on dynamic memory allocation failure. + * @return <0 on digest failure. + */ +int wc_xmss_keygen(XmssState* state, const unsigned char* seed, + unsigned char* sk, unsigned char* pk) +{ +#if WOLFSSL_XMSS_MIN_HEIGHT <= 32 + int ret = 0; + const XmssParams* params = state->params; + const word8 n = params->n; + /* Offset of root node in public key. */ + byte* pk_root = pk; +#ifdef WOLFSSL_SMALL_STACK + BdsState* bds = NULL; +#else + BdsState bds[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for tree hash instances and put in BDS state. */ + ret = wc_xmss_bds_state_alloc(params, &bds); + if (ret == 0) +#endif + { + /* Offsets into seed. */ + const byte* seed_priv = seed; + const byte* seed_pub = seed + 2 * n; + /* Offsets into secret/private key. */ + word32* sk_idx = (word32*)sk; + byte* sk_seeds = sk + params->idx_len; + /* Offsets into public key. */ + byte* pk_seed = pk + n; + + /* Setup pointers into sk - assumes sk is initialized to zeros. */ + wc_xmss_bds_state_load(state, sk, bds, NULL); + + /* Set first index to 0 in private key. idx_len always 4. */ + *sk_idx = 0; + /* Set private key seed and private key for PRF in to private key. */ + XMEMCPY(sk_seeds, seed_priv, 2 * n); + /* Set public key seed into public key. */ + XMEMCPY(pk_seed, seed_pub, n); + + /* Set all address values to zero. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + /* Hash address layer is 0. */ + /* Compute root node into public key. */ + wc_xmss_bds_treehash_initial(state, bds, sk_seeds, pk_seed, + state->addr, pk_root); + /* Return any errors that occurred during hashing. */ + ret = state->ret; + } + if (ret == 0) { + /* Offset of root node in private key. */ + byte* sk_root = sk + params->idx_len + 2 * n; + + /* Append public key (root node and public seed) to private key. */ + XMEMCPY(sk_root, pk_root, 2 * n); + + /* Store BDS state back into secret/private key. */ + wc_xmss_bds_state_store(state, sk, bds); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated data of BDS states. */ + wc_xmss_bds_state_free(bds); +#endif + return ret; +#else + (void)state; + (void)pk; + (void)sk; + (void)seed; + + return NOT_COMPILED_IN; +#endif /* WOLFSSL_XMSS_MIN_HEIGHT <= 32 */ +} + +/* Sign a message with XMSS. + * + * RFC 8391: 4.1.9, Algorithm 11: treeSig + * ... + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(idx_sig); + * sig_ots = WOTS_sign(getWOTS_SK(SK, idx_sig), + * M', getSEED(SK), ADRS); + * Sig = sig_ots || auth; + * return Sig; + * RFC 8391: 4.1.9, Algorithm 12: XMSS_sign + * idx_sig = getIdx(SK); + * setIdx(SK, idx_sig + 1); + * ADRS = toByte(0, 32); + * byte[n] r = PRF(getSK_PRF(SK), toByte(idx_sig, 32)); + * byte[n] M' = H_msg(r || getRoot(SK) || (toByte(idx_sig, n)), M); + * Sig = idx_sig || r || treeSig(M', SK, idx_sig, ADRS); + * return (SK || Sig); + * + * HDSS, Section 4.5, The algorithm, Update and output phase. + * + * 'auth' was built at key generation or after computing previous signature. + * Build next authentication path after signature created. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] m Buffer holding message. + * @param [in] mlen Length of message in buffer. + * @param [in, out] sk Secret/Private key. + * @param [out] sm Signature and message data. + * @param [in, out] smlen On in, length of signature and message buffer. + * On out, length of signature and message data. + * @return 0 on success. + * @return <0 on digest failure. + */ +int wc_xmss_sign(XmssState* state, const unsigned char* m, word32 mlen, + unsigned char* sk, unsigned char* sig) +{ +#if WOLFSSL_XMSS_MIN_HEIGHT <= 32 + int ret = 0; + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 h = params->h; + const word8 hk = params->h - params->bds_k; + const byte* sk_seed = sk + XMSS_IDX_LEN; + const byte* pk_seed = sk + XMSS_IDX_LEN + 3 * n; + byte node[WC_XMSS_MAX_N]; + word32 idx; + byte* sig_r = sig + XMSS_IDX_LEN; +#ifdef WOLFSSL_SMALL_STACK + BdsState* bds = NULL; +#else + BdsState bds[1]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + /* Allocate memory for tree hash instances and put in BDS state. */ + ret = wc_xmss_bds_state_alloc(params, &bds); + if (ret == 0) +#endif + { + /* Load the BDS state from secret/private key. */ + wc_xmss_bds_state_load(state, sk, bds, NULL); + + /* Copy the index into the signature data: Sig = idx_sig || ... */ + *((word32*)sig) = *((word32*)sk); + /* Read index from the secret key. */ + ato32(sk, &idx); + + /* Check index is valid. */ + if (IDX32_INVALID(idx, XMSS_IDX_LEN, h)) { + /* Set index to maximum value to distinguish from valid value. */ + XMEMSET(sk, 0xFF, XMSS_IDX_LEN); + /* Zeroize the secret key. */ + ForceZero(sk + XMSS_IDX_LEN, params->sk_len - XMSS_IDX_LEN); + ret = KEY_EXHAUSTED_E; + } + } + + /* Update SK_MT */ + if (ret == 0) { + /* Increment the index in the secret key. */ + c32toa(idx + 1, sk); + } + + /* Message compression */ + if (ret == 0) { + const byte* sk_prf = sk + XMSS_IDX_LEN + n; + + /* byte[n] r = PRF(SK_PRF, toByte(idx_sig, 32)); */ + wc_idx_copy(sig, params->idx_len, state->buf, XMSS_PRF_M_LEN); + wc_xmss_prf(state, sk_prf, state->buf, sig_r); + ret = state->ret; + } + if (ret == 0) { + const byte* pub_root = sk + XMSS_IDX_LEN + 2 * n; + + /* Compute the message hash. */ + wc_xmss_hash_message(state, sig_r, pub_root, sig, XMSS_IDX_LEN, m, mlen, + node); + ret = state->ret; + /* Place new signature data after index and 'r'. */ + sig += XMSS_IDX_LEN + n; + } + + if (ret == 0) { + /* Set all address values to zero and set type to OTS. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + state->addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + /* treeSig || treeHash = sig_ots || auth */ + state->addr[XMSS_ADDR_OTS] = idx; + /* Create WOTS+ signature for tree into signature (sig_ots). */ + wc_xmss_wots_sign(state, node, sk_seed, pk_seed, state->addr, sig); + ret = state->ret; + } + if (ret == 0) { + sig += params->wots_sig_len; + /* Add authentication path (auth) and calc new root. */ + XMEMCPY(sig, bds->authPath, h * n); + ret = state->ret; + } + + if (ret == 0) { + /* Update BDS state - update authentication path for next index. */ + /* Check not last node. */ + if (idx < ((word32)1 << h) - 1) { + /* Calculate next authentication path node. */ + wc_xmss_bds_auth_path(state, bds, idx, sk_seed, pk_seed, + state->addr); + ret = state->ret; + if (ret == 0) { + /* Algorithm 4.6: Step 5. */ + wc_xmss_bds_treehash_updates(state, bds, hk >> 1, sk_seed, + pk_seed, state->addr); + ret = state->ret; + } + } + } + if (ret == 0) { + /* Store BDS state back into secret/private key. */ + wc_xmss_bds_state_store(state, sk, bds); + } + +#ifdef WOLFSSL_SMALL_STACK + /* Dispose of allocated data of BDS states. */ + wc_xmss_bds_state_free(bds); +#endif + return ret; +#else + (void)state; + (void)m; + (void)mlen; + (void)sk; + (void)sig; + + return NOT_COMPILED_IN; +#endif /* WOLFSSL_XMSS_MIN_HEIGHT <= 32 */ +} + +/******************************************** + * XMSS^MT + ********************************************/ + +/* Generate a XMSS^MT key pair from seeds. + * + * RFC 8391: 4.2.2, Algorithm 15: XMSS^MT_keyGen. + * ... + * # Example initialization + * idx_MT = 0; + * setIdx(SK_MT, idx_MT); + * initialize SK_PRF with a uniformly random n-byte string; + * setSK_PRF(SK_MT, SK_PRF); + * initialize SEED with a uniformly random n-byte string; + * setSEED(SK_MT, SEED); + * + * # Generate reduced XMSS private keys + * ADRS = toByte(0, 32); + * for ( layer = 0; layer < d; layer++ ) { + * ADRS.setLayerAddress(layer); + * for ( tree = 0; tree < + * (1 << ((d - 1 - layer) * (h / d))); + * tree++ ) { + * ADRS.setTreeAddress(tree); + * for ( i = 0; i < 2^(h / d); i++ ) { + * wots_sk[i] = WOTS_genSK(); + * } + * setXMSS_SK(SK_MT, wots_sk, tree, layer); + * } + * } + * + * SK = getXMSS_SK(SK_MT, 0, d - 1); + * setSEED(SK, SEED); + * root = treeHash(SK, 0, h / d, ADRS); + * setRoot(SK_MT, root); + * + * PK_MT = OID || root || SEED; + * return (SK_MT || PK_MT); + * + * HDSS, Section 4.5, The algorithm, Initialization. + * OPX, Section 2, Key Generation. + * + * wots_sk, SK_PRF and SEED passed in as seed. + * Store seed for wots_sk instead of generated wots_sk. + * OID not stored in PK this is handled in upper layer. + * BDS state is appended to SK: + * SK = idx || wots_sk || SK_PRF || root || SEED || BDS_STATE; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] seed Secret/Private and public seed. + * @param [out] sk Secret key. + * @param [out] pk Public key. + * @return 0 on success. + * @return MEMORY_E on dynamic memory allocation failure. + * @return <0 on digest failure. + */ +int wc_xmssmt_keygen(XmssState* state, const unsigned char* seed, + unsigned char* sk, unsigned char* pk) +{ + int ret = 0; + const XmssParams* params = state->params; + const word8 n = params->n; + unsigned char* sk_seed = sk + params->idx_len; + unsigned char* pk_root = pk; + unsigned char* pk_seed = pk + n; + word8 i; + byte* wots_sigs; + BdsState* bds = NULL; + + /* Allocate memory for BDS states and tree hash instances. */ + ret = wc_xmss_bds_state_alloc(params, &bds); + if (ret == 0) { + /* Offsets into seed. */ + const byte* seed_priv = seed; + const byte* seed_pub = seed + 2 * params->n; + + /* Load the BDS state from secret/private key. */ + wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); + + /* Set first index to 0 in private key. */ + XMEMSET(sk, 0, params->idx_len); + /* Set private key seed and private key for PRF in to private key. */ + XMEMCPY(sk_seed, seed_priv, 2 * n); + /* Set public key seed into public key. */ + XMEMCPY(pk_seed, seed_pub, n); + + /* Set all address values to zero. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + /* Hash address layer is 0 = bottom-most layer. */ + } + + /* Setup state and compute WOTS+ signatures for all but top-most subtree. */ + for (i = 0; (ret == 0) && (i < params->d - 1); i++) { + /* Compute root for subtree. */ + wc_xmss_bds_treehash_initial(state, bds + i, sk_seed, pk_seed, + state->addr, pk_root); + ret = state->ret; + if (ret == 0) { + /* Create signature for subtree for first index. */ + state->addr[XMSS_ADDR_LAYER] = i+1; + wc_xmss_wots_sign(state, pk_root, sk_seed, pk_seed, state->addr, + wots_sigs + i * params->wots_sig_len); + ret = state->ret; + } + } + if (ret == 0) { + /* Compute root for top-most subtree. */ + wc_xmss_bds_treehash_initial(state, bds + i, sk_seed, pk_seed, + state->addr, pk_root); + /* Return any errors that occurred during hashing. */ + ret = state->ret; + } + + if (ret == 0) { + /* Offset of root node in private key. */ + unsigned char* sk_root = sk_seed + 2 * n; + + /* Append public key (root node and public seed) to private key. */ + XMEMCPY(sk_root, pk_root, 2 * n); + + /* Store BDS state back into secret/private key. */ + wc_xmss_bds_state_store(state, sk, bds); + } + + /* Dispose of allocated data of BDS states. */ + wc_xmss_bds_state_free(bds); + return ret; +} + + +#if !defined(WORD64_AVAILABLE) && (WOLFSSL_XMSS_MAX_HEIGHT > 32) + #error "Support not available - use XMSS small code option" +#endif + +#if (WOLFSSL_XMSS_MAX_HEIGHT > 32) + typedef word64 XmssIdx; + #define IDX_MAX_BITS 64 +#else + typedef word32 XmssIdx; + #define IDX_MAX_BITS 32 +#endif + +/* Decode index into word. + * + * @param [out] idx Index from encoding. + * @param [in] c Count of bytes to decode to index. + * @param [in] a Array to decode from. + */ +static void xmss_idx_decode(XmssIdx* idx, word8 c, const unsigned char* a) +{ + word8 i; + XmssIdx n = 0; + + for (i = 0; i < c; i++) { + n <<= 8; + n += a[i]; + } + + *idx = n; +} + +/* Check whether index is valid. + * + * @param [in] i Index to check. + * @param [in] h Full tree Height. + */ +static int xmss_idx_invalid(XmssIdx i, word8 h) +{ + return ((i + 1) >> h) != 0; +} + +/* Get tree and leaf index from index. + * + * @param [in] i Index to split. + * @param [in] h Tree height. + * @param [out] t Tree index. + * @param [out] l Leaf index. + */ +static void xmss_idx_get_tree_leaf(XmssIdx i, word8 h, XmssIdx* t, word32* l) +{ + *l = (word32)i & (((word32)1 << h) - 1); + *t = i >> h; +} + +/* Set the index into address as the tree index. + * + * @param [in] i Tree index. + * @param [in, out] a Hash address. + */ +static void xmss_idx_set_addr_tree(XmssIdx i, HashAddress a) +{ +#if IDX_MAX_BITS == 32 + a[XMSS_ADDR_TREE_HI] = 0; + a[XMSS_ADDR_TREE] = i; +#else + a[XMSS_ADDR_TREE_HI] = (word32)(i >> 32); + a[XMSS_ADDR_TREE] = (word32)(i ); +#endif +} + +/* Sign message with XMSS^MT. + * + * RFC 8391: 4.1.9, Algorithm 11: treeSig + * ... + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(idx_sig); + * sig_ots = WOTS_sign(getWOTS_SK(SK, idx_sig), + * M', getSEED(SK), ADRS); + * Sig = sig_ots || auth; + * return Sig; + * RFC 8391: 4.2.4, Algorithm 16: XMSS^MT_sign. + * ... + * # Init + * ADRS = toByte(0, 32); + * SEED = getSEED(SK_MT); + * SK_PRF = getSK_PRF(SK_MT); + * idx_sig = getIdx(SK_MT); + * + * # Update SK_MT + * setIdx(SK_MT, idx_sig + 1); + * + * # Message compression + * byte[n] r = PRF(SK_PRF, toByte(idx_sig, 32)); + * byte[n] M' = H_msg(r || getRoot(SK_MT) || (toByte(idx_sig, n)), M); + * + * # Sign + * Sig_MT = idx_sig; + * unsigned int idx_tree + * = (h - h / d) most significant bits of idx_sig; + * unsigned int idx_leaf = (h / d) least significant bits of idx_sig; + * SK = idx_leaf || getXMSS_SK(SK_MT, idx_tree, 0) || SK_PRF + * || toByte(0, n) || SEED; + * ADRS.setLayerAddress(0); + * ADRS.setTreeAddress(idx_tree); + * Sig_tmp = treeSig(M', SK, idx_leaf, ADRS); + * Sig_MT = Sig_MT || r || Sig_tmp; + * for ( j = 1; j < d; j++ ) { + * root = treeHash(SK, 0, h / d, ADRS); + * idx_leaf = (h / d) least significant bits of idx_tree; + * idx_tree = (h - j * (h / d)) most significant bits of idx_tree; + * SK = idx_leaf || getXMSS_SK(SK_MT, idx_tree, j) || SK_PRF + * || toByte(0, n) || SEED; + * ADRS.setLayerAddress(j); + * ADRS.setTreeAddress(idx_tree); + * Sig_tmp = treeSig(root, SK, idx_leaf, ADRS); + * Sig_MT = Sig_MT || Sig_tmp; + * } + * return SK_MT || Sig_MT; + * + * 'auth' was built at key generation or after computing previous signature. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] idx Index to sign with. + * @param [in] wots_sigs Pre-computed WOTS+ signatures. + * @param [in] m Buffer holding message. + * @param [in] mlen Length of message in buffer. + * @param [in, out] sk Secret/Private key. + * @param [out] sig Signature and message data. + * @return 0 on success. + * @return <0 on digest failure. + */ +static int wc_xmssmt_sign_msg(XmssState* state, BdsState* bds, XmssIdx idx, + byte* wots_sigs, const unsigned char* m, word32 mlen, unsigned char* sk, + unsigned char* sig) +{ + int ret; + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 hs = params->sub_h; + const word8 idx_len = params->idx_len; + const byte* sk_prf = sk + idx_len + n; + byte* sig_mt = sig; + byte* sig_r = sig + idx_len; + byte node[WC_XMSS_MAX_N]; + + /* Message compression */ + /* byte[n] r = PRF(SK_PRF, toByte(idx_sig, 32)); */ + wc_idx_copy(sig_mt, idx_len, state->buf, XMSS_PRF_M_LEN); + wc_xmss_prf(state, sk_prf, state->buf, sig_r); + ret = state->ret; + if (ret == 0) { + const byte* pub_root = sk + idx_len + 2 * n; + /* byte[n] M' = H_msg(r || getRoot(SK_MT) || (toByte(idx_sig, n)), M); + */ + wc_xmss_hash_message(state, sig_r, pub_root, sig, idx_len, m, mlen, + node); + ret = state->ret; + /* Place new signature data after index and 'r'. */ + sig += idx_len + n; + } + + /* Sign */ + if (ret == 0) { + const byte* sk_seed = sk + idx_len; + const byte* pk_seed = sk + idx_len + 3 * n; + XmssIdx idx_tree; + word32 idx_leaf; + + /* Set all address values to zero and set type to OTS. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + state->addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + + /* Fist iteration - calculate signature. */ + /* Set layer, tree and OTS leaf index into hash address. */ + state->addr[XMSS_ADDR_LAYER] = 0; + xmss_idx_get_tree_leaf(idx, hs, &idx_tree, &idx_leaf); + xmss_idx_set_addr_tree(idx_tree, state->addr); + /* treeSig || treeHash = sig_ots || auth */ + state->addr[XMSS_ADDR_OTS] = idx_leaf; + /* Create WOTS+ signature for tree into signature (sig_ots). */ + wc_xmss_wots_sign(state, node, sk_seed, pk_seed, state->addr, sig); + ret = state->ret; + } + if (ret == 0) { + word8 i; + + sig += params->wots_sig_len; + /* Add authentication path. */ + XMEMCPY(sig, bds[BDS_IDX(idx, 0, hs, params->d)].authPath, hs * n); + sig += hs * n; + + /* Remaining iterations from storage. */ + for (i = 1; i < params->d; i++) { + /* Copy out precomputed signature into signature (sig_ots). */ + XMEMCPY(sig, wots_sigs + (i - 1) * params->wots_sig_len, + params->wots_sig_len); + sig += params->wots_sig_len; + /* Add authentication path (auth) and calc new root. */ + XMEMCPY(sig, bds[BDS_IDX(idx, i, hs, params->d)].authPath, hs * n); + sig += hs * n; + } + ret = state->ret; + } + + return ret; +} + +/* Compute BDS state for signing next index. + * + * HDSS, Section 4.5, The algorithm, Update and output phase. + * OPX, Section 2, Signature Generation. Para 2 and 3. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in, out] bds BDS state. + * @param [in] idx Index to sign with. + * @param [in] wots_sigs Pre-computed WOTS+ signatures. + * @param [in] m Buffer holding message. + * @param [in] mlen Length of message in buffer. + * @param [in, out] sk Secret/Private key. + * @param [out] sig Signature and message data. + * @return 0 on success. + * @return <0 on digest failure. + */ +static int wc_xmssmt_sign_next_idx(XmssState* state, BdsState* bds, XmssIdx idx, + byte* wots_sigs, unsigned char* sk) +{ + int ret = 0; + const XmssParams* params = state->params; + const word8 n = params->n; + const word8 h = params->h; + const word8 hs = params->sub_h; + const word8 hsk = params->sub_h - params->bds_k; + const byte* sk_seed = sk + params->idx_len; + const byte* pk_seed = sk + params->idx_len + 3 * n; + XmssIdx idx_tree; + int computeAuthPath = 1; + unsigned int updates; + word8 i; + + /* Update BDS state - update authentication path for next index. */ + /* HDSS, Algorithm 4.6, Step 5: repeat (H - K) / 2 times. */ + updates = hsk >> 1; + + idx_tree = (idx >> hs) + 1; + /* Check whether last tree. */ + if (idx_tree < ((XmssIdx)1 << (h - hs))) { + /* Set hash address to next tree. */ + state->addr[XMSS_ADDR_LAYER] = 0; + xmss_idx_set_addr_tree(idx_tree, state->addr); + /* Update BDS state. */ + wc_xmss_bds_update(state, &bds[BDS_ALT_IDX(idx, 0, hs, params->d)], + sk_seed, pk_seed, state->addr); + ret = state->ret; + } + + for (i = 0; (ret == 0) && (i < params->d); i++) { + word32 idx_leaf; + word8 bds_i = BDS_IDX(idx, i, hs, params->d); + word8 alt_i = BDS_ALT_IDX(idx, i, hs, params->d); + + /* Check not last at height. */ + if (((idx + 1) << (IDX_MAX_BITS - ((i + 1) * hs))) != 0) { + state->addr[XMSS_ADDR_LAYER] = i; + xmss_idx_get_tree_leaf(idx >> (hs * i), hs, &idx_tree, &idx_leaf); + xmss_idx_set_addr_tree(idx_tree, state->addr); + idx_tree++; + + if (computeAuthPath) { + /* Compute authentication path for tree. */ + wc_xmss_bds_auth_path(state, &bds[bds_i], idx_leaf, sk_seed, + pk_seed, state->addr); + ret = state->ret; + computeAuthPath = 0; + } + + if (ret == 0) { + /* HDSS, Algorithm 4.6: Step 5. */ + updates = wc_xmss_bds_treehash_updates(state, &bds[bds_i], + updates, sk_seed, pk_seed, state->addr); + ret = state->ret; + } + + /* Check tree not first, updates to do, tree not last at height and + * next leaf in alt state is not last. */ + if ((ret == 0) && (i > 0) && (updates > 0) && + (idx_tree < ((XmssIdx)1 << (h - (hs * (i + 1))))) && + (bds[alt_i].next < ((XmssIdx)1 << h))) { + xmss_idx_set_addr_tree(idx_tree, state->addr); + /* Update alternative BDS state. */ + wc_xmss_bds_update(state, &bds[alt_i], sk_seed, pk_seed, + state->addr); + ret = state->ret; + updates--; + } + } + /* Last at height. */ + else { + /* Set layer, tree and OTS leaf index into hash address. */ + state->addr[XMSS_ADDR_LAYER] = i + 1; + idx_tree = (idx + 1) >> ((i + 1) * hs); + xmss_idx_get_tree_leaf(idx_tree, hs, &idx_tree, &idx_leaf); + xmss_idx_set_addr_tree(idx_tree, state->addr); + /* Cache WOTS+ signature for new tree. */ + state->addr[XMSS_ADDR_OTS] = idx_leaf; + wc_xmss_wots_sign(state, bds[alt_i].stack, sk_seed, pk_seed, + state->addr, wots_sigs + i * params->wots_sig_len); + ret = state->ret; + + if (ret == 0) { + word8 d; + + /* Reset old BDS state. */ + bds[bds_i].offset = 0; + bds[bds_i].next = 0; + + /* Done an update. */ + updates--; + /* Need to compute authentication path in next tree up. */ + computeAuthPath = 1; + /* Mark the tree hashes as complete in new BDS state. */ + for (d = 0; d < hsk; d++) { + wc_xmss_bds_state_treehash_complete(&bds[alt_i], d); + } + } + } + } + + return ret; +} + +/* Sign a message with XMSS^MT and update BDS state for signing next index. + * + * RFC 8391: 4.2.4, Algorithm 16: XMSS^MT_sign. + * HDSS, Section 4.5, The algorithm, Update and output phase. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] m Buffer holding message. + * @param [in] mlen Length of message in buffer. + * @param [in, out] sk Secret/Private key. + * @param [out] sig Signature and message data. + * @return 0 on success. + * @return MEMORY_E on dynamic memory allocation failure. + * @return <0 on digest failure. + */ +int wc_xmssmt_sign(XmssState* state, const unsigned char* m, word32 mlen, + unsigned char* sk, unsigned char* sig) +{ + int ret = 0; + const XmssParams* params = state->params; + const word8 h = params->h; + const word8 idx_len = params->idx_len; + XmssIdx idx = 0; + byte* sig_mt = sig; + byte* wots_sigs; + BdsState* bds = NULL; + + /* Allocate memory for BDS states and tree hash instances. */ + ret = wc_xmss_bds_state_alloc(params, &bds); + if (ret == 0) { + /* Load the BDS state from secret/private key. */ + wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); + + /* Copy the index into the signature data: Sig_MT = idx_sig. */ + XMEMCPY(sig_mt, sk, idx_len); + + /* Read index from the secret key. */ + xmss_idx_decode(&idx, idx_len, sk); + } + if ((ret == 0) && xmss_idx_invalid(idx, h)) { + /* Set index to maximum value to distinguish from valid value. */ + XMEMSET(sk, 0xFF, idx_len); + /* Zeroize the secret key. */ + ForceZero(sk + idx_len, params->sk_len - idx_len); + ret = KEY_EXHAUSTED_E; + } + + if (ret == 0) { + /* Increment the index in the secret key. */ + wc_idx_update(sk, idx_len); + + /* Compute signature. */ + ret = wc_xmssmt_sign_msg(state, bds, idx, wots_sigs, m, mlen, sk, sig); + } + + /* Only update if not last index. */ + if ((ret == 0) && (idx < (((XmssIdx)1 << h) - 1))) { + /* Update BDS state for signing next index. */ + ret = wc_xmssmt_sign_next_idx(state, bds, idx, wots_sigs, sk); + } + + if (ret == 0) { + /* Store BDS state back into secret/private key. */ + wc_xmss_bds_state_store(state, sk, bds); + } + + /* Dispose of allocated data of BDS states. */ + wc_xmss_bds_state_free(bds); + return ret; +} + +#endif /* WOLFSSL_WC_XMSS_SMALL */ + +/* Check if more signatures are possible with secret/private key. + * + * @param [in] params XMSS parameters + * @param [in] sk Secret/private key. + * @return 1 when signatures possible. + * @return 0 when key exhausted. + */ + +int wc_xmss_sigsleft(const XmssParams* params, unsigned char* sk) +{ + int ret = 0; + wc_Idx idx; + + WC_IDX_ZERO(idx); + /* Read index from the secret key. */ + WC_IDX_DECODE(idx, params->idx_len, sk, ret); + /* Check validity of index. */ + if ((ret == 0) && (WC_IDX_INVALID(idx, params->idx_len, params->h))) { + ret = KEY_EXHAUSTED_E; + } + + return ret == 0; +} +#endif /* !WOLFSSL_XMSS_VERIFY_ONLY */ + +/******************************************** + * SIGN OPEN - Verify + ********************************************/ + +#if !defined(WOLFSSL_WC_XMSS_SMALL) || defined(WOLFSSL_XMSS_VERIFY_ONLY) +/* Compute root node with leaf and authentication path. + * + * RFC 8391: 4.1.10, Algorithm 13: XMSS_rootFromSig + * ... + * for ( k = 0; k < h; k++ ) { + * ADRS.setTreeHeight(k); + * if ( (floor(idx_sig / (2^k)) % 2) == 0 ) { + * ADRS.setTreeIndex(ADRS.getTreeIndex() / 2); + * node[1] = RAND_HASH(node[0], auth[k], SEED, ADRS); + * } else { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node[1] = RAND_HASH(auth[k], node[0], SEED, ADRS); + * } + * node[0] = node[1]; + * } + * return node[0]; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] idx_leaf Index of leaf node. + * @param [in] auth_path Authentication path. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [in, out] root On in, leaf node. On out, root node. + */ +static void wc_xmss_compute_root(XmssState* state, word32 idx_leaf, + const byte* auth_path, const byte* pk_seed, HashAddress addr, byte* root) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + const byte* b[2][2] = { { root, auth_path }, { auth_path, root } }; + word8 i; + + for (i = 0; i < params->sub_h; i++) { + /* Get which side the leaf is on. */ + word8 s = idx_leaf & 1; + /* Set tree height and index. */ + addr[XMSS_ADDR_TREE_HEIGHT] = i; + idx_leaf >>= 1; + addr[XMSS_ADDR_TREE_INDEX] = idx_leaf; + + /* Put the result into buffer position for next RAND_HASH. */ + wc_xmss_rand_hash_lr(state, b[s][0], b[s][1], pk_seed, addr, root); + /* Move to next auth path node. */ + b[0][1] += n; + b[1][0] += n; + } +} +#else +/* Compute root node with leaf and authentication path. + * + * RFC 8391: 4.1.10, Algorithm 13: XMSS_rootFromSig + * ... + * for ( k = 0; k < h; k++ ) { + * ADRS.setTreeHeight(k); + * if ( (floor(idx_sig / (2^k)) % 2) == 0 ) { + * ADRS.setTreeIndex(ADRS.getTreeIndex() / 2); + * node[1] = RAND_HASH(node[0], auth[k], SEED, ADRS); + * } else { + * ADRS.setTreeIndex((ADRS.getTreeIndex() - 1) / 2); + * node[1] = RAND_HASH(auth[k], node[0], SEED, ADRS); + * } + * node[0] = node[1]; + * } + * return node[0]; + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] idx_leaf Index of leaf node. + * @param [in] auth_path Authentication path. + * @param [in] pk_seed Random public seed. + * @param [in] addr Hash address. + * @param [in, out] node On in, leaf node. On out, root node. + */ +static void wc_xmss_compute_root(XmssState* state, word32 idx_leaf, + const byte* auth_path, const byte* pk_seed, HashAddress addr, byte* node) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + byte buffer[2 * WC_XMSS_MAX_N]; + byte* b[2][2] = { { buffer, buffer + n }, { buffer + n, buffer } }; + word8 i; + + /* Setup buffer for first RAND_HASH. */ + XMEMCPY(b[idx_leaf & 1][0], node, n); + XMEMCPY(b[idx_leaf & 1][1], auth_path, n); + auth_path += n; + + for (i = 0; i < params->sub_h - 1; i++) { + /* Set tree height and index. */ + addr[XMSS_ADDR_TREE_HEIGHT] = i; + idx_leaf >>= 1; + addr[XMSS_ADDR_TREE_INDEX] = idx_leaf; + + /* Put the result into buffer position for next RAND_HASH. */ + wc_xmss_rand_hash(state, buffer, pk_seed, addr, b[idx_leaf & 1][0]); + /* Put auth path node into other half of buffer. */ + XMEMCPY(b[idx_leaf & 1][1], auth_path, n); + /* Move to next auth path node. */ + auth_path += n; + } + + addr[XMSS_ADDR_TREE_HEIGHT] = i; + idx_leaf >>= 1; + addr[XMSS_ADDR_TREE_INDEX] = idx_leaf; + /* Last iteration into output node. */ + wc_xmss_rand_hash(state, buffer, pk_seed, addr, node); +} +#endif /* !WOLFSSL_WC_XMSS_SMALL || WOLFSSL_XMSS_VERIFY_ONLY */ + +/* Compute a root node from a tree signature. + * + * RFC 8391: 4.1.10, Algorithm 13: XMSS_rootFromSig + * ADRS.setType(0); # Type = OTS hash address + * ADRS.setOTSAddress(idx_sig); + * pk_ots = WOTS_pkFromSig(sig_ots, M', SEED, ADRS); + * ADRS.setType(1); # Type = L-tree address + * ADRS.setLTreeAddress(idx_sig); + * byte[n][2] node; + * node[0] = ltree(pk_ots, SEED, ADRS); + * ADRS.setType(2); # Type = hash tree address + * ADRS.setTreeIndex(idx_sig); + * [Compute root with leaf and authentication path] + * + * Computing the root from the leaf and authentication path can be implemented + * in different ways and is therefore extracted to its own function. + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] pk_seed Random public seed. + * @param [in] sig WOTS+ signature for this tree. + * @param [in] idx_sig Index of signature leaf in this tree. + * @param [in, out] addr Hash address. + * @param [in, out] node On in, previous root node. + * On out, root node of this subtree. + */ +static void wc_xmss_root_from_sig(XmssState* state, const byte* pk_seed, + const byte* sig, word32 idx_sig, HashAddress addr, byte* node) +{ + const XmssParams* params = state->params; + byte* wots_pk = state->pk; + const byte* auth_path = sig + params->wots_sig_len; + + /* Compute WOTS+ public key value from signature. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_OTS; + addr[XMSS_ADDR_OTS] = idx_sig; + wc_xmss_wots_pk_from_sig(state, sig, node, pk_seed, addr, wots_pk); + + /* Compute leaves of L-tree from WOTS+ public key. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_LTREE; + /* XMSS_ADDR_LTREE is same as XMSS_ADDR_OTS in index and value. */ + wc_xmss_ltree(state, wots_pk, pk_seed, addr, node); + + /* Compute root node from leaf and authentication path. */ + addr[XMSS_ADDR_TYPE] = WC_XMSS_ADDR_TYPE_TREE; + addr[XMSS_ADDR_TREE_ZERO] = 0; + wc_xmss_compute_root(state, idx_sig, auth_path, pk_seed, addr, node); +} + +/* Verify message with signature using XMSS/MT. + * + * RFC 8391: 4.2.5, Algorithm 17: XMSSMT_verify + * idx_sig = getIdx(Sig_MT); + * SEED = getSEED(PK_MT); + * ADRS = toByte(0, 32); + * + * byte[n] M' = H_msg(getR(Sig_MT) || getRoot(PK_MT) + * || (toByte(idx_sig, n)), M); + * + * unsigned int idx_leaf + * = (h / d) least significant bits of idx_sig; + * unsigned int idx_tree + * = (h - h / d) most significant bits of idx_sig; + * Sig' = getXMSSSignature(Sig_MT, 0); + * ADRS.setLayerAddress(0); + * ADRS.setTreeAddress(idx_tree); + * byte[n] node = XMSS_rootFromSig(idx_leaf, getSig_ots(Sig'), + * getAuth(Sig'), M', SEED, ADRS); + * for ( j = 1; j < d; j++ ) { + * idx_leaf = (h / d) least significant bits of idx_tree; + * idx_tree = (h - j * h / d) most significant bits of idx_tree; + * Sig' = getXMSSSignature(Sig_MT, j); + * ADRS.setLayerAddress(j); + * ADRS.setTreeAddress(idx_tree); + * node = XMSS_rootFromSig(idx_leaf, getSig_ots(Sig'), + * getAuth(Sig'), node, SEED, ADRS); + * } + * if ( node == getRoot(PK_MT) ) { + * return true; + * } else { + * return false; + * } + * + * @param [in] state XMSS/MT state including digest and parameters. + * @param [in] m Message buffer. + * @param [in] mlen Length of message in bytes. + * @param [in] sig Buffer holding signature. + * @param [in] pk Public key. + * @return 0 on success. + * @return MEMORY_E on dynamic memory allocation failure. + * @return SIG_VERIFY_E on verification failure. + * @return <0 on digest failure. + */ +int wc_xmssmt_verify(XmssState* state, const unsigned char* m, word32 mlen, + const unsigned char* sig, const unsigned char* pk) +{ + const XmssParams* params = state->params; + const word8 n = params->n; + int ret = 0; + const byte* pub_root = pk; + const byte* pk_seed = pk + n; + byte node[WC_XMSS_MAX_N]; + wc_Idx idx; + word32 idx_leaf = 0; + unsigned int i; + + /* Set 32/64-bit index to 0. */ + WC_IDX_ZERO(idx); + /* Set all address values to zero. */ + XMEMSET(state->addr, 0, sizeof(HashAddress)); + + if (ret == 0) { + /* Convert the index bytes from the signature to an integer. */ + WC_IDX_DECODE(idx, params->idx_len, sig, ret); + } + + if (ret == 0) { + const byte* sig_r = sig + params->idx_len; + /* byte[n] M' = H_msg(getR(Sig_MT) || getRoot(PK_MT) || + * (toByte(idx_sig, n)), M); + */ + wc_xmss_hash_message(state, sig_r, pub_root, sig, params->idx_len, m, + mlen, node); + ret = state->ret; + } + + if (ret == 0) { + /* Set tree of hash address. */ + WC_IDX_SET_ADDR_TREE(idx, params->idx_len, params->sub_h, state->addr, + idx_leaf); + + /* Skip to first WOTS+ signature and derive root. */ + sig += params->idx_len + n; + wc_xmss_root_from_sig(state, pk_seed, sig, idx_leaf, state->addr, + node); + ret = state->ret; + } + /* Calculate root of remaining subtrees up to top. */ + for (i = 1; (ret == 0) && (i < params->d); i++) { + /* Set layer and tree. */ + state->addr[XMSS_ADDR_LAYER] = i; + WC_IDX_SET_ADDR_TREE(idx, params->idx_len, params->sub_h, state->addr, + idx_leaf); + /* Skip to next WOTS+ signature and derive root. */ + sig += params->wots_sig_len + params->sub_h * n; + wc_xmss_root_from_sig(state, pk_seed, sig, idx_leaf, state->addr, + node); + ret = state->ret; + } + /* Compare calculated node with public key root. */ + if ((ret == 0) && (XMEMCMP(node, pub_root, n) != 0)) { + ret = SIG_VERIFY_E; + } + + return ret; +} +#endif /* WOLFSSL_HAVE_XMSS */ + diff --git a/src/wolfcrypt/src/wolfevent.c b/src/wolfcrypt/src/wolfevent.c index 01ddd11..4ed7b8f 100644 --- a/src/wolfcrypt/src/wolfevent.c +++ b/src/wolfcrypt/src/wolfevent.c @@ -55,7 +55,7 @@ int wolfEvent_Init(WOLF_EVENT* event, WOLF_EVENT_TYPE type, void* context) int wolfEvent_Poll(WOLF_EVENT* event, WOLF_EVENT_FLAG flags) { - int ret = BAD_COND_E; + int ret = WC_NO_ERR_TRACE(BAD_COND_E); /* Check hardware */ #ifdef WOLFSSL_ASYNC_CRYPT diff --git a/src/wolfcrypt/src/wolfmath.c b/src/wolfcrypt/src/wolfmath.c index 11e85cd..df5f0f8 100644 --- a/src/wolfcrypt/src/wolfmath.c +++ b/src/wolfcrypt/src/wolfmath.c @@ -167,7 +167,8 @@ int get_rand_digit(WC_RNG* rng, mp_digit* d) return wc_RNG_GenerateBlock(rng, (byte*)d, sizeof(mp_digit)); } -#if defined(WC_RSA_BLINDING) || defined(WOLFCRYPT_HAVE_SAKKE) +#if defined(WC_RSA_BLINDING) || defined(WOLFCRYPT_HAVE_SAKKE) || \ + defined(WOLFSSL_ECC_BLIND_K) int mp_rand(mp_int* a, int digits, WC_RNG* rng) { int ret = 0; @@ -221,7 +222,7 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) return ret; } -#endif /* WC_RSA_BLINDING || WOLFCRYPT_HAVE_SAKKE */ +#endif /* WC_RSA_BLINDING || WOLFCRYPT_HAVE_SAKKE || WOLFSSL_ECC_BLIND_K */ #endif /* !WC_NO_RNG */ #if defined(HAVE_ECC) || defined(WOLFSSL_EXPORT_INT) diff --git a/src/wolfssl/bio.c b/src/wolfssl/bio.c index 2dab43e..340cbfd 100644 --- a/src/wolfssl/bio.c +++ b/src/wolfssl/bio.c @@ -50,7 +50,7 @@ */ static int wolfSSL_BIO_BASE64_read(WOLFSSL_BIO* bio, void* buf, int len) { - word32 frmtSz = len; + word32 frmtSz = (word32)len; WOLFSSL_ENTER("wolfSSL_BIO_BASE64_read"); @@ -77,6 +77,8 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) if (buf == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nread(bio, &pt, len); if (sz1 > 0) { XMEMCPY(buf, pt, sz1); @@ -91,8 +93,10 @@ static int wolfSSL_BIO_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } } } - if (sz1 == 0) + if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_READ|WOLFSSL_BIO_FLAG_RETRY; sz1 = -1; + } return sz1; } @@ -175,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } - bio->mem_buf->length = bio->wrSz; + bio->mem_buf->length = (size_t)bio->wrSz; bio->ptr = bio->mem_buf->data; } } @@ -233,13 +237,13 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, - sz) != WOLFSSL_SUCCESS) + (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, sz) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -305,12 +309,12 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFREAD(buf, 1, len, (XFILE)bio->ptr); + ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, len); + ret = (int)XREAD(bio->num, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -399,7 +403,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, /* get the encoded length */ if (bio->flags & WOLFSSL_BIO_FLAG_BASE64_NO_NL) { if (Base64_Encode_NoNl((const byte*)data, inLen, NULL, - &sz) != LENGTH_ONLY_E) { + &sz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -448,7 +452,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, (void)heap; - return inLen; + return (int)inLen; } #endif /* WOLFSSL_BASE64_ENCODE */ @@ -502,8 +506,11 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (bio == NULL || data == NULL || len == 0) return 0; + /* default no retry */ + bio->flags &= ~(WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY); sz1 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz1 == 0) { + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; WOLFSSL_MSG("No room left to write"); return WOLFSSL_BIO_ERROR; } @@ -521,6 +528,8 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, if (sz2 > 0) { XMEMCPY(buf, data, sz2); sz1 += sz2; + if (len > sz2) + bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; } } @@ -591,12 +600,12 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, - len) != WOLFSSL_SUCCESS) { + (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, len) + if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -652,7 +661,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) if (ret > 0) { /* change so that data is formatted buffer */ data = frmt; - len = frmtSz; + len = (int)frmtSz; } #else WOLFSSL_MSG("WOLFSSL_BIO_BASE64 used without " @@ -670,12 +679,12 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM if (bio->ptr) { - ret = (int)XFWRITE(data, 1, len, (XFILE)bio->ptr); + ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); } else { - #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR) && \ + #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, len); + ret = (int)XWRITE(bio->num, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -972,7 +981,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { - ret = szOut; + ret = (int)szOut; } } break; @@ -1257,8 +1266,8 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) bio->rdIdx = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = bio->num; - bio->mem_buf->max = bio->num; + bio->mem_buf->length = (size_t)bio->num; + bio->mem_buf->max = (size_t)bio->num; } return WOLFSSL_SUCCESS; @@ -1608,7 +1617,12 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) XFCLOSE((XFILE)bio->ptr); } - bio->ptr = XFOPEN(name, "w"); + /* 'b' flag is ignored on POSIX targets, but on Windows it assures + * inhibition of LF<->CRLF rewriting, so that there is consistency + * between the size and contents of the representation in memory and on + * disk. + */ + bio->ptr = XFOPEN(name, "wb"); if (((XFILE)bio->ptr) == XBADFILE) { return WOLFSSL_FAILURE; } @@ -2637,7 +2651,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) len = (int)XSTRLEN((const char*)buf) + 1; } - if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, len) == 0) { + if (len > 0 && wolfSSL_BUF_MEM_resize(bio->mem_buf, (size_t)len) == 0) { wolfSSL_BIO_free(bio); return NULL; } diff --git a/src/wolfssl/certs_test.h b/src/wolfssl/certs_test.h index 09ed4b1..013b374 100644 --- a/src/wolfssl/certs_test.h +++ b/src/wolfssl/certs_test.h @@ -3451,7 +3451,7 @@ static const int sizeof_dh_key_der_4096 = sizeof(dh_key_der_4096); #endif /* USE_CERT_BUFFERS_4096 */ -#if defined(HAVE_PQC) && defined(HAVE_FALCON) +#if defined(HAVE_FALCON) /* certs/falcon/bench_falcon_level1_key.der */ static const unsigned char bench_falcon_level1_key[] = @@ -4099,1767 +4099,1802 @@ static const unsigned char bench_falcon_level5_key[] = }; static const int sizeof_bench_falcon_level5_key = sizeof(bench_falcon_level5_key); -#endif /* HAVE_PQC && HAVE_FALCON */ +#endif /* HAVE_FALCON */ -#if defined (HAVE_PQC) && defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) -/* certs/dilithium/bench_dilithium_level2_key.der */ -static const unsigned char bench_dilithium_level2_key[] = -{ - 0x30, 0x82, 0x0F, 0x1A, 0x02, 0x01, 0x00, 0x30, 0x0D, 0x06, - 0x0B, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0B, 0x07, - 0x04, 0x04, 0x04, 0x82, 0x0F, 0x04, 0x04, 0x82, 0x0F, 0x00, - 0xA2, 0xBD, 0x74, 0xB9, 0x8E, 0x34, 0xF0, 0xEC, 0xF7, 0x40, - 0x22, 0x33, 0xE8, 0x50, 0x43, 0x66, 0xF0, 0x25, 0x41, 0x20, - 0xD9, 0x3F, 0x8A, 0xC6, 0xAD, 0x69, 0xC6, 0x9C, 0xD9, 0xE0, - 0x0D, 0xFF, 0x77, 0x85, 0xCD, 0x88, 0x58, 0x17, 0x6B, 0x85, - 0xD2, 0x5D, 0xF0, 0x41, 0xCE, 0x6D, 0x94, 0x7F, 0xF4, 0xDB, - 0xD3, 0x60, 0x52, 0x1A, 0x83, 0x42, 0xD8, 0x7C, 0x2D, 0xD9, - 0x55, 0x7B, 0xFB, 0xB8, 0x87, 0xAA, 0xDA, 0x75, 0x42, 0x86, - 0x3E, 0x5A, 0xE4, 0xD4, 0x7D, 0xC3, 0x38, 0xA2, 0xEE, 0x0D, - 0xF5, 0xAD, 0xDA, 0x12, 0x5B, 0xD6, 0x3A, 0x89, 0x87, 0xED, - 0x57, 0xD1, 0xA9, 0xC2, 0xB3, 0xC0, 0xDC, 0x90, 0x88, 0x0C, - 0x86, 0x48, 0xD2, 0xA6, 0x60, 0x1B, 0x22, 0x8C, 0x03, 0x34, - 0x69, 0x19, 0x96, 0x24, 0x04, 0xB3, 0x65, 0x10, 0x34, 0x31, - 0x09, 0x38, 0x31, 0x5C, 0x10, 0x8C, 0x02, 0x15, 0x66, 0xD0, - 0x48, 0x50, 0x53, 0x22, 0x41, 0xC4, 0x98, 0x41, 0xE2, 0x42, - 0x62, 0x42, 0x38, 0x45, 0xC2, 0xB8, 0x08, 0x20, 0x31, 0x21, - 0x13, 0x10, 0x88, 0x00, 0xB9, 0x24, 0x93, 0x06, 0x6D, 0x44, - 0x20, 0x64, 0x98, 0x84, 0x29, 0x91, 0x12, 0x6A, 0xC9, 0x14, - 0x10, 0x11, 0x40, 0x2A, 0x24, 0xC9, 0x85, 0xCC, 0x42, 0x2A, - 0x1C, 0x44, 0x28, 0xE0, 0xB4, 0x00, 0x20, 0x99, 0x11, 0x0B, - 0x09, 0x61, 0x24, 0x14, 0x10, 0x41, 0x94, 0x20, 0xC9, 0x46, - 0x64, 0x43, 0x02, 0x6E, 0x08, 0x39, 0x71, 0x81, 0x06, 0x2D, - 0x63, 0x14, 0x71, 0x62, 0xC0, 0x11, 0x20, 0xB2, 0x61, 0xD1, - 0x30, 0x24, 0x44, 0x06, 0x89, 0x04, 0x16, 0x88, 0x10, 0x33, - 0x48, 0x51, 0xB8, 0x00, 0x4A, 0x12, 0x68, 0x14, 0x04, 0x10, - 0xD8, 0x92, 0x8D, 0x22, 0x32, 0x61, 0x0C, 0x23, 0x91, 0x10, - 0x39, 0x24, 0x51, 0x80, 0x08, 0x0B, 0x30, 0x61, 0x00, 0x89, - 0x01, 0x98, 0x34, 0x05, 0x9A, 0xA2, 0x70, 0xC4, 0x46, 0x40, - 0x52, 0x38, 0x42, 0xC0, 0x92, 0x6D, 0xCC, 0x08, 0x22, 0xD4, - 0x42, 0x4A, 0x02, 0x23, 0x40, 0x40, 0x92, 0x25, 0x12, 0x36, - 0x65, 0x42, 0x06, 0x10, 0x02, 0x10, 0x10, 0x20, 0xA3, 0x41, - 0x0A, 0x15, 0x10, 0x20, 0x23, 0x80, 0x99, 0xB6, 0x0C, 0x11, - 0x26, 0x11, 0x9B, 0xC8, 0x44, 0x1C, 0xC9, 0x05, 0xA4, 0x38, - 0x11, 0x1B, 0xB0, 0x05, 0xDC, 0x22, 0x00, 0xC8, 0x22, 0x72, - 0xA3, 0x30, 0x2E, 0xC1, 0xA8, 0x41, 0x1C, 0xA6, 0x20, 0xE2, - 0xB0, 0x21, 0x9B, 0x10, 0x01, 0x61, 0x32, 0x46, 0xC1, 0x92, - 0x61, 0x1C, 0xA4, 0x85, 0x0A, 0xB7, 0x70, 0xE4, 0x26, 0x6C, - 0x58, 0xA4, 0x00, 0x19, 0x86, 0x4C, 0xDC, 0xA6, 0x40, 0xA1, - 0x32, 0x12, 0x04, 0x81, 0x90, 0x8C, 0x04, 0x05, 0x10, 0x30, - 0x26, 0x09, 0x31, 0x2C, 0x50, 0x88, 0x89, 0x82, 0x44, 0x62, - 0x10, 0x23, 0x8A, 0x04, 0x44, 0x22, 0x0A, 0x30, 0x4E, 0xA4, - 0x34, 0x32, 0x4C, 0x18, 0x8C, 0x21, 0x21, 0x41, 0x23, 0x13, - 0x72, 0x08, 0x84, 0x24, 0x1A, 0x04, 0x24, 0x14, 0x06, 0x02, - 0xC4, 0x40, 0x70, 0xCA, 0x00, 0x6E, 0xC1, 0xC6, 0x09, 0x83, - 0x42, 0x62, 0xA0, 0x30, 0x12, 0x1B, 0x14, 0x0C, 0x08, 0x03, - 0x22, 0xCA, 0x46, 0x65, 0x64, 0x46, 0x26, 0x10, 0x39, 0x20, - 0xCA, 0x80, 0x28, 0x62, 0x14, 0x6D, 0x10, 0x26, 0x11, 0x49, - 0xA2, 0x45, 0x53, 0x98, 0x0D, 0x64, 0x40, 0x05, 0x0C, 0x31, - 0x09, 0x13, 0x11, 0x60, 0xD8, 0x02, 0x50, 0x11, 0x41, 0x41, - 0x23, 0xC1, 0x4C, 0x22, 0xC6, 0x30, 0x99, 0x06, 0x08, 0xCA, - 0x40, 0x81, 0xCC, 0x32, 0x0E, 0x11, 0xC4, 0x20, 0xD9, 0x92, - 0x41, 0xC4, 0x20, 0x08, 0xE4, 0xA0, 0x00, 0xCB, 0x88, 0x21, - 0x03, 0x03, 0x90, 0x54, 0x00, 0x49, 0x14, 0x98, 0x04, 0xC8, - 0xC0, 0x31, 0x11, 0x31, 0x69, 0x04, 0x93, 0x90, 0x00, 0xB9, - 0x21, 0x22, 0x38, 0x48, 0x00, 0x34, 0x0C, 0x61, 0x98, 0x00, - 0x01, 0xB4, 0x69, 0x60, 0x26, 0x81, 0x1C, 0xA4, 0x10, 0x22, - 0xB6, 0x10, 0x21, 0xC6, 0x20, 0x4A, 0x22, 0x26, 0xD0, 0x92, - 0x41, 0xDA, 0x84, 0x69, 0x03, 0x42, 0x2A, 0x04, 0x09, 0x02, - 0xE1, 0x24, 0x42, 0xA2, 0x46, 0x28, 0x10, 0xB1, 0x08, 0x82, - 0x86, 0x84, 0xE0, 0x24, 0x51, 0x0A, 0xC9, 0x28, 0x59, 0x86, - 0x20, 0xDB, 0xB6, 0x40, 0x13, 0xC3, 0x40, 0x1C, 0xA9, 0x09, - 0x80, 0x34, 0x50, 0xDC, 0x84, 0x2C, 0x53, 0x24, 0x08, 0xC0, - 0xB4, 0x6D, 0x88, 0x26, 0x30, 0x82, 0xC8, 0x0D, 0x62, 0x22, - 0x28, 0x64, 0xA2, 0x09, 0x10, 0x25, 0x26, 0xDB, 0x34, 0x02, - 0x4A, 0x04, 0x11, 0x53, 0xB8, 0x28, 0x82, 0x34, 0x11, 0xC2, - 0x12, 0x25, 0x20, 0xB5, 0x40, 0x19, 0xA8, 0x31, 0x80, 0x22, - 0x66, 0x21, 0xB2, 0x10, 0x0B, 0x42, 0x2A, 0x61, 0x20, 0x50, - 0x40, 0x24, 0x4C, 0x99, 0x12, 0x48, 0x21, 0xB4, 0x11, 0xD1, - 0x44, 0x48, 0x00, 0x40, 0x0C, 0x58, 0x46, 0x68, 0x04, 0x12, - 0x12, 0x93, 0x22, 0x20, 0xC2, 0x32, 0x4C, 0x01, 0xB0, 0x88, - 0xE3, 0x20, 0x8E, 0x03, 0x00, 0x6C, 0x52, 0x14, 0x30, 0xD2, - 0x44, 0x88, 0x10, 0x44, 0x4A, 0x61, 0x86, 0x29, 0x14, 0x42, - 0x24, 0x24, 0x35, 0x2E, 0x11, 0xC4, 0x0D, 0x23, 0x24, 0x66, - 0x0A, 0x90, 0x71, 0xE0, 0xC2, 0x69, 0x48, 0x38, 0x91, 0x82, - 0xC8, 0x08, 0x1C, 0x93, 0x31, 0xD9, 0x06, 0x51, 0x8A, 0xA4, - 0x6C, 0x50, 0x34, 0x68, 0x5A, 0x18, 0x89, 0x4A, 0x96, 0x85, - 0x8A, 0x18, 0x44, 0x4A, 0x34, 0x40, 0x5B, 0x36, 0x80, 0xCC, - 0x20, 0x6E, 0x09, 0x19, 0x89, 0x02, 0x38, 0x6A, 0x24, 0xA3, - 0x69, 0x58, 0x32, 0x6D, 0x21, 0x01, 0x84, 0x88, 0x86, 0x28, - 0xA3, 0x22, 0x89, 0x93, 0xA6, 0x80, 0x00, 0x88, 0x81, 0xE1, - 0x48, 0x70, 0xA2, 0x34, 0x60, 0x18, 0x02, 0x04, 0x18, 0x29, - 0x01, 0x1B, 0x31, 0x51, 0xD4, 0xA4, 0x49, 0xCC, 0x08, 0x8C, - 0xDA, 0x36, 0x11, 0x01, 0x39, 0x26, 0x42, 0x92, 0x88, 0xC8, - 0x46, 0x52, 0x8C, 0xA4, 0x08, 0x14, 0x11, 0x52, 0xCA, 0x40, - 0x66, 0x8B, 0x32, 0x8E, 0x89, 0x44, 0x02, 0x9B, 0x42, 0x02, - 0x93, 0xA4, 0x01, 0x1A, 0x00, 0x50, 0x94, 0x44, 0x42, 0x08, - 0x09, 0x8C, 0xE2, 0xA8, 0x81, 0x98, 0x00, 0x48, 0x63, 0x02, - 0x85, 0x1B, 0x05, 0x2D, 0xC1, 0xBE, 0x5F, 0xA4, 0xAC, 0xB4, - 0xF0, 0xC7, 0x94, 0xBD, 0xEC, 0xFB, 0x09, 0xAF, 0x16, 0xF1, - 0x23, 0x58, 0xAB, 0x82, 0xFA, 0x74, 0xD1, 0x84, 0x51, 0xD0, - 0x58, 0x9B, 0xFA, 0xF4, 0x11, 0xC1, 0x17, 0x2F, 0xCE, 0xD1, - 0xCA, 0xC6, 0xCE, 0x1C, 0x8F, 0x8F, 0x1B, 0x43, 0xBF, 0xB9, - 0x43, 0x41, 0x02, 0x3E, 0x5D, 0xFA, 0x24, 0x88, 0x0E, 0xA5, - 0x36, 0xA9, 0x9B, 0x25, 0x43, 0xD6, 0xEE, 0xDE, 0xAE, 0x93, - 0x54, 0xC8, 0x6C, 0x55, 0xE9, 0x5C, 0xC8, 0xC1, 0xA5, 0xD7, - 0xFC, 0xDA, 0xAF, 0xF8, 0x40, 0x1F, 0x02, 0x5C, 0x8E, 0x48, - 0x51, 0x4B, 0x3F, 0xFD, 0x76, 0x9A, 0xD0, 0x87, 0xF4, 0xD0, - 0x68, 0x9C, 0x44, 0x3B, 0xB4, 0x4A, 0xAB, 0x34, 0x2A, 0xD4, - 0x0C, 0xA4, 0x7A, 0xBB, 0x98, 0x7F, 0x8D, 0xF6, 0xA7, 0x6A, - 0x42, 0x8C, 0x7A, 0xB4, 0x32, 0xC6, 0x8A, 0xD6, 0x5E, 0x06, - 0x50, 0xC0, 0xDD, 0x3E, 0xE2, 0x44, 0x5C, 0xB9, 0x83, 0xCF, - 0x92, 0x0C, 0x3C, 0xFB, 0x53, 0x0D, 0xF0, 0xD1, 0xED, 0x77, - 0xF3, 0x02, 0x9F, 0xA6, 0xC6, 0xFA, 0x30, 0xA5, 0xC7, 0x42, - 0x06, 0x1F, 0x38, 0xE5, 0xE1, 0x56, 0x01, 0x7A, 0xD1, 0xE1, - 0xC1, 0x20, 0x44, 0x37, 0xE6, 0x18, 0x8A, 0x7E, 0x70, 0xBA, - 0x6B, 0x1C, 0x99, 0x4E, 0xFB, 0xCA, 0xCF, 0x3D, 0x29, 0x26, - 0xF4, 0x12, 0x95, 0x74, 0x11, 0x23, 0x0E, 0x2E, 0x31, 0xCF, - 0x73, 0xE6, 0x99, 0xD0, 0x72, 0x23, 0x4A, 0x46, 0x07, 0xA1, - 0x03, 0x4C, 0x3A, 0x79, 0x72, 0x3B, 0xD1, 0x79, 0x5A, 0x66, - 0x29, 0xCD, 0x34, 0xB6, 0x6A, 0xA5, 0x6A, 0x4C, 0x71, 0xE5, - 0xB3, 0xA6, 0xAC, 0x4D, 0x13, 0xDC, 0x70, 0xE4, 0x0C, 0x6A, - 0x98, 0x48, 0x1C, 0xA0, 0x6C, 0xFC, 0xDD, 0x6A, 0x3F, 0x10, - 0x3B, 0xBD, 0xC9, 0xC8, 0xEA, 0x01, 0x86, 0x5B, 0x3B, 0x19, - 0x3E, 0x6F, 0xA9, 0x4A, 0xD4, 0x38, 0x1D, 0x9C, 0x2B, 0x19, - 0xAE, 0x47, 0x54, 0xE2, 0x4E, 0xB5, 0xDF, 0xA7, 0xBD, 0x6F, - 0x01, 0x8A, 0x10, 0x5B, 0x83, 0x17, 0xB3, 0x77, 0xE1, 0x9D, - 0xBF, 0x6B, 0x25, 0xBF, 0x90, 0xC4, 0x92, 0xE1, 0x5E, 0xE1, - 0xC3, 0x0C, 0xC5, 0x05, 0x24, 0x40, 0x61, 0xA1, 0x01, 0x4A, - 0x7B, 0xE4, 0x65, 0x73, 0x1F, 0x3C, 0xA2, 0xD8, 0x54, 0xA4, - 0x64, 0xA3, 0x06, 0xDA, 0x18, 0x9A, 0xD7, 0xE4, 0x90, 0x59, - 0xAF, 0xBC, 0x1A, 0x79, 0xC4, 0x08, 0xE9, 0x87, 0x95, 0x04, - 0x48, 0x18, 0xD2, 0x33, 0x15, 0x38, 0x9C, 0x00, 0x7B, 0x72, - 0x35, 0xC1, 0x03, 0x77, 0xF1, 0x0B, 0xEC, 0x38, 0x33, 0xB7, - 0xB4, 0xBC, 0xC4, 0xBD, 0xB3, 0xBB, 0x9C, 0x34, 0x0B, 0x28, - 0x03, 0x1D, 0x99, 0x7A, 0x12, 0x0C, 0x95, 0xFE, 0x0D, 0x53, - 0x79, 0xE7, 0xE6, 0x99, 0x3F, 0xA1, 0x31, 0x9E, 0xA9, 0xB8, - 0x9B, 0xB7, 0xC0, 0x3F, 0x9C, 0x18, 0x1B, 0xA2, 0x73, 0xBC, - 0x10, 0xDB, 0x1B, 0x09, 0xE7, 0x5E, 0x67, 0x8E, 0x69, 0x92, - 0xCF, 0x99, 0xC3, 0x97, 0x58, 0xE8, 0x9A, 0x40, 0x83, 0xF2, - 0x14, 0xA3, 0x25, 0xB5, 0x51, 0x30, 0xDA, 0x91, 0x87, 0x91, - 0x1E, 0xF2, 0x5E, 0x55, 0x49, 0x68, 0x5E, 0xC9, 0x21, 0x67, - 0x03, 0xBC, 0x21, 0xE4, 0xD1, 0xFC, 0x79, 0xC7, 0xDB, 0x44, - 0xB9, 0xAB, 0x1E, 0xB4, 0x65, 0x3D, 0x63, 0xCB, 0x64, 0x76, - 0xE4, 0x1B, 0x93, 0x91, 0xB0, 0xF3, 0x4F, 0xBA, 0xD3, 0x20, - 0x47, 0x37, 0x5A, 0xCA, 0x1B, 0xDB, 0xCA, 0xA1, 0xE7, 0xED, - 0x7D, 0x8D, 0x4E, 0x7C, 0x19, 0xB2, 0x73, 0x67, 0x55, 0x11, - 0xE4, 0xA1, 0x98, 0x44, 0x5F, 0x58, 0xF7, 0xAA, 0x09, 0xFD, - 0x09, 0x4A, 0x54, 0x68, 0x32, 0xD4, 0xCA, 0xE1, 0x96, 0xFD, - 0x27, 0x05, 0x88, 0x78, 0x7B, 0x83, 0x74, 0x78, 0x6F, 0x09, - 0xC7, 0x3C, 0x66, 0xA8, 0x17, 0x3A, 0xCF, 0xB3, 0x6E, 0x5A, - 0xD7, 0x16, 0xE5, 0x2E, 0x40, 0xD7, 0x30, 0x18, 0x47, 0x5F, - 0x95, 0x19, 0x4E, 0x0F, 0x69, 0xD3, 0x11, 0xDE, 0xBB, 0x55, - 0x1B, 0xD1, 0x13, 0x71, 0x3D, 0x45, 0x3E, 0xDC, 0x72, 0x4F, - 0x89, 0x34, 0x72, 0x96, 0x77, 0xBB, 0x42, 0x29, 0x4A, 0x88, - 0x44, 0xFB, 0x05, 0x57, 0x38, 0xA6, 0xAC, 0x3E, 0x03, 0xF6, - 0xE1, 0x9D, 0xE3, 0xE9, 0x5A, 0x1B, 0x64, 0xCE, 0xC8, 0x6E, - 0x1B, 0xE8, 0xE3, 0x78, 0xF8, 0xE9, 0xF1, 0x47, 0x09, 0x0E, - 0x66, 0x50, 0x7A, 0x10, 0x51, 0xE1, 0x60, 0x73, 0x78, 0x95, - 0x00, 0x2E, 0xB8, 0x05, 0x8C, 0x22, 0x72, 0xD9, 0x88, 0xC8, - 0x8D, 0x16, 0xEF, 0x18, 0x8F, 0xC6, 0x51, 0x1E, 0xC3, 0xBA, - 0x27, 0x57, 0xB4, 0xFE, 0x74, 0x0F, 0x54, 0x45, 0x5A, 0x0B, - 0xAC, 0x6C, 0xA7, 0x46, 0x95, 0xC7, 0x35, 0x3D, 0x38, 0xBE, - 0xC5, 0x4E, 0xE0, 0x83, 0xED, 0x68, 0x8D, 0x01, 0x31, 0x7D, - 0x90, 0xA7, 0x38, 0xEE, 0x57, 0x8E, 0xD2, 0xFB, 0x87, 0x08, - 0x7A, 0x44, 0x34, 0x0B, 0x99, 0x5E, 0x2F, 0xA8, 0x4E, 0xC0, - 0x80, 0xEF, 0x62, 0xFE, 0xFB, 0x3C, 0x73, 0xF1, 0x8C, 0x56, - 0x12, 0x08, 0x8C, 0xD3, 0x9F, 0xBA, 0x44, 0x90, 0xB7, 0xDB, - 0x9C, 0xD9, 0xB4, 0x91, 0xBA, 0xFF, 0x4A, 0xB0, 0x1C, 0x91, - 0x44, 0x34, 0x52, 0xBE, 0x0D, 0xBA, 0x72, 0x33, 0x5C, 0x36, - 0xB5, 0x5E, 0x91, 0xB7, 0xE9, 0xCE, 0xD0, 0x01, 0x61, 0x19, - 0xEE, 0x2D, 0x1F, 0xBE, 0x97, 0x7C, 0x8C, 0x30, 0x91, 0x8C, - 0xB1, 0x8A, 0x04, 0xCA, 0xB8, 0x33, 0xCB, 0xA9, 0x9A, 0x2C, - 0x1B, 0x25, 0xD2, 0xDB, 0x73, 0x95, 0x3F, 0x02, 0x67, 0xEB, - 0x2C, 0xEC, 0xCC, 0x92, 0xCD, 0x1E, 0x1F, 0xC2, 0xF2, 0xA7, - 0x23, 0xAD, 0x7C, 0xA5, 0x50, 0x44, 0x76, 0x7D, 0x74, 0x13, - 0x20, 0x21, 0xF2, 0x09, 0xD9, 0x70, 0x82, 0xB0, 0x30, 0xA3, - 0x8A, 0xC0, 0x9D, 0xD2, 0x16, 0x4F, 0x65, 0xDF, 0x42, 0x37, - 0xC2, 0x63, 0xD6, 0x6C, 0xA9, 0xD1, 0x95, 0x5D, 0x84, 0xD2, - 0xB5, 0xC7, 0x7A, 0x87, 0x9B, 0x9B, 0xAF, 0x21, 0x65, 0x64, - 0xF7, 0x0B, 0x21, 0xC7, 0xF6, 0xA5, 0x27, 0xEB, 0xAA, 0x8D, - 0xF2, 0x10, 0x60, 0xFB, 0xC9, 0xB3, 0xB0, 0x32, 0x7C, 0x9F, - 0xC1, 0xDE, 0xA8, 0x77, 0x6F, 0xCC, 0x35, 0x1F, 0xBD, 0x74, - 0x0E, 0xA9, 0x84, 0x3C, 0x05, 0x9D, 0xFF, 0xBC, 0x46, 0x9A, - 0x8E, 0x43, 0xB5, 0x8B, 0x1C, 0x24, 0xB5, 0xC3, 0xB0, 0xFE, - 0x14, 0xCC, 0x3C, 0xCF, 0xF2, 0x26, 0xCE, 0x0B, 0x3A, 0x5B, - 0x5C, 0x8E, 0x59, 0xBF, 0x0D, 0xDC, 0xA6, 0xCA, 0x78, 0xE5, - 0xD9, 0xC5, 0x46, 0x56, 0x38, 0x98, 0xC4, 0xAC, 0x43, 0x64, - 0xB1, 0x78, 0x0A, 0x81, 0x34, 0x7D, 0x3D, 0xC0, 0xF5, 0x25, - 0x14, 0x66, 0xA2, 0x2A, 0x81, 0x64, 0x82, 0x62, 0x86, 0xD0, - 0x65, 0xCB, 0x2A, 0x09, 0x01, 0xF5, 0x03, 0xEC, 0xB5, 0xD1, - 0xED, 0xC7, 0x60, 0x62, 0x3D, 0x38, 0x28, 0x9C, 0x32, 0xEE, - 0x9F, 0x45, 0x72, 0x71, 0xA9, 0x6D, 0x9A, 0x54, 0x83, 0xF9, - 0xE7, 0x37, 0xC7, 0xCC, 0x28, 0xC0, 0xC2, 0x24, 0x09, 0xC3, - 0x96, 0xF6, 0xED, 0x9B, 0x60, 0xF3, 0x24, 0x4C, 0xFC, 0xAB, - 0xD0, 0x38, 0x7A, 0x1C, 0x68, 0xED, 0x63, 0x83, 0x5A, 0x28, - 0x37, 0x70, 0x31, 0xBB, 0x9D, 0xC7, 0xAA, 0x3A, 0x5B, 0xAF, - 0x88, 0x82, 0xE2, 0x30, 0xCB, 0xF5, 0xC1, 0x63, 0x9C, 0x59, - 0x41, 0xD3, 0x24, 0x92, 0xB1, 0x71, 0xA4, 0x16, 0x26, 0x0B, - 0x9C, 0x96, 0x0B, 0xE9, 0x0B, 0x69, 0xFC, 0x1F, 0xD2, 0x99, - 0xC2, 0xB6, 0x7A, 0x24, 0x28, 0x5A, 0x3D, 0x88, 0x2C, 0xF0, - 0x76, 0xFC, 0x25, 0x04, 0xBE, 0xB6, 0x19, 0x94, 0xD1, 0xBA, - 0x1A, 0x58, 0x0E, 0x9A, 0xFB, 0x4C, 0x9D, 0x21, 0x34, 0x8D, - 0x45, 0xEC, 0x50, 0xC6, 0x94, 0x1B, 0x0B, 0x87, 0x36, 0x4E, - 0xE4, 0x96, 0xF6, 0x9A, 0x34, 0xEC, 0xD8, 0x65, 0x6A, 0x46, - 0xFA, 0xC5, 0x40, 0x35, 0xD0, 0x07, 0x74, 0x02, 0xA3, 0xCF, - 0x23, 0x60, 0x15, 0xAC, 0x54, 0x98, 0x59, 0xEF, 0x94, 0x17, - 0x0A, 0xEF, 0xBB, 0xC2, 0x7B, 0x3B, 0xEF, 0xF5, 0xD1, 0x9C, - 0xB7, 0xB1, 0xDF, 0x45, 0xF5, 0x57, 0xD1, 0x18, 0x05, 0x97, - 0x8F, 0x8C, 0x30, 0x8C, 0x11, 0xF4, 0x81, 0x4D, 0x75, 0x18, - 0x97, 0x9F, 0x30, 0x64, 0xE2, 0x5B, 0x18, 0x95, 0xAC, 0x4E, - 0xDC, 0x47, 0xB5, 0x45, 0xAA, 0xD4, 0x7E, 0xF4, 0x70, 0x46, - 0x34, 0xF3, 0xB3, 0x85, 0xC2, 0x46, 0x98, 0xB5, 0xB5, 0x33, - 0x52, 0xF4, 0x36, 0x39, 0xCA, 0x23, 0xF9, 0x66, 0xB9, 0xA4, - 0x63, 0xC6, 0x3D, 0x02, 0xE7, 0x8F, 0x95, 0xF3, 0x25, 0xFD, - 0x21, 0xD0, 0x62, 0xC2, 0xEE, 0xE2, 0x2F, 0x69, 0x55, 0x31, - 0x42, 0x78, 0x2D, 0x53, 0xDC, 0x7F, 0x0E, 0x93, 0xD5, 0x4D, - 0x21, 0x64, 0x8B, 0x9E, 0x2C, 0xBE, 0xBA, 0xD3, 0x39, 0x41, - 0xE3, 0x10, 0xE5, 0x07, 0xE4, 0x0E, 0x20, 0x38, 0x63, 0xF7, - 0x02, 0xF2, 0x17, 0x99, 0xEB, 0xC6, 0xE7, 0x5F, 0xBE, 0xAE, - 0x53, 0xD1, 0x12, 0xB2, 0x9A, 0x90, 0x25, 0x6A, 0xAA, 0xFD, - 0x5D, 0x69, 0x2F, 0x32, 0x33, 0x53, 0x57, 0x1B, 0xC4, 0x24, - 0xC0, 0xC5, 0x90, 0x04, 0x04, 0x67, 0xCA, 0x85, 0x1E, 0x94, - 0x31, 0x95, 0x78, 0x76, 0x5D, 0xCF, 0x15, 0xE6, 0x06, 0x6B, - 0x1A, 0x1D, 0x0E, 0xF6, 0x64, 0x91, 0x84, 0xAE, 0xE4, 0xF0, - 0x1F, 0x0A, 0x76, 0x1C, 0x74, 0xF3, 0xC1, 0x97, 0x80, 0x5B, - 0xD9, 0xC6, 0xB6, 0x2B, 0xA8, 0xD7, 0xD8, 0xD2, 0xB5, 0x8E, - 0x05, 0xB5, 0x16, 0x6A, 0xF7, 0xCB, 0xD2, 0xFE, 0xE0, 0xA7, - 0x3E, 0x1C, 0x3E, 0x84, 0xDC, 0x89, 0x33, 0xD7, 0x2F, 0x2A, - 0x40, 0x41, 0x18, 0xB8, 0x58, 0xB6, 0x54, 0xC6, 0xC9, 0xDF, - 0x24, 0x91, 0xCD, 0x62, 0xA0, 0x9D, 0x17, 0xCC, 0xA6, 0xCF, - 0xD9, 0x25, 0xA1, 0xBC, 0x63, 0x09, 0xFB, 0xD1, 0x65, 0x5C, - 0xFC, 0xB8, 0x3A, 0x3D, 0x50, 0xEC, 0x1A, 0x26, 0x37, 0xCB, - 0x9C, 0x29, 0x9E, 0x15, 0x06, 0xC9, 0x14, 0x45, 0x41, 0x5F, - 0x6C, 0x41, 0x46, 0xEA, 0xC6, 0xF8, 0x18, 0x01, 0x7D, 0xCD, - 0x30, 0xEE, 0x5D, 0xB5, 0xA0, 0x96, 0x19, 0x80, 0x96, 0xB1, - 0x03, 0x55, 0x86, 0x57, 0xBE, 0x19, 0x13, 0x46, 0x88, 0x00, - 0xCE, 0x5E, 0xD0, 0xBE, 0xEC, 0x13, 0x2B, 0x93, 0x3C, 0xE1, - 0xEC, 0xBD, 0x15, 0x6F, 0xA5, 0xF5, 0x20, 0x59, 0x3C, 0xDD, - 0xBD, 0xFD, 0xDF, 0x9D, 0x9F, 0x07, 0x73, 0x25, 0x93, 0x42, - 0x41, 0xCF, 0x4A, 0xE5, 0x8F, 0x04, 0xAC, 0x5F, 0x6A, 0x56, - 0x87, 0x49, 0xD5, 0x64, 0x00, 0x9D, 0xF4, 0xA5, 0x6B, 0xBE, - 0x8F, 0xC8, 0xE8, 0xBC, 0xC7, 0x1C, 0x99, 0xC0, 0x2F, 0xA1, - 0xDA, 0xDF, 0x6B, 0xE5, 0x62, 0x9D, 0xC9, 0x73, 0x5B, 0x2A, - 0x3E, 0xD7, 0x8A, 0xBE, 0x0A, 0x5F, 0x2B, 0x0B, 0x61, 0xEF, - 0x4A, 0x09, 0x15, 0x70, 0xE6, 0x5C, 0xA1, 0xB6, 0xDE, 0x54, - 0x71, 0x74, 0x55, 0x63, 0x77, 0x8F, 0xC9, 0xAF, 0x22, 0x9A, - 0xFE, 0x2C, 0x09, 0x62, 0x3E, 0xA1, 0xAA, 0x89, 0xB8, 0x6B, - 0x50, 0x84, 0x20, 0x66, 0x5D, 0x8F, 0x39, 0x7F, 0xC1, 0x2D, - 0xFA, 0x78, 0x8F, 0x8E, 0xD0, 0x39, 0x33, 0xD4, 0x9A, 0x40, - 0x56, 0xBC, 0x86, 0x22, 0x07, 0xEB, 0x22, 0xB8, 0x52, 0xC0, - 0x1A, 0xD2, 0x35, 0x1F, 0x56, 0x7E, 0xDA, 0x2B, 0xC1, 0x08, - 0xD2, 0x39, 0x28, 0x46, 0x63, 0x9A, 0xAD, 0x44, 0xB3, 0xEF, - 0x1C, 0x2A, 0xD6, 0x68, 0x67, 0xE4, 0x63, 0x73, 0x78, 0x29, - 0xA7, 0xA0, 0x70, 0x2E, 0xD9, 0xB4, 0x14, 0x4D, 0x04, 0xD3, - 0x2D, 0x8A, 0x70, 0x07, 0xAD, 0x8A, 0xC0, 0xA5, 0x1D, 0xE7, - 0x17, 0xD8, 0xBB, 0xAA, 0xB5, 0xF7, 0xC8, 0x8D, 0x29, 0x8E, - 0x49, 0x32, 0xA0, 0x40, 0x34, 0xBB, 0x2E, 0x10, 0x30, 0xDD, - 0xEA, 0x3E, 0xCC, 0xC1, 0xB9, 0xF2, 0x42, 0xCC, 0x4A, 0xF2, - 0xF4, 0x93, 0x2E, 0x3F, 0x0C, 0xE8, 0xE4, 0x96, 0x1F, 0x33, - 0x2D, 0x67, 0x4F, 0x8E, 0x1B, 0x01, 0xD6, 0xE2, 0xF2, 0xFD, - 0x5D, 0xCC, 0xFD, 0x18, 0x9C, 0xD6, 0x50, 0x1F, 0xE1, 0xC5, - 0x7C, 0xBE, 0x59, 0x95, 0x7D, 0x21, 0x25, 0x3E, 0xF3, 0xBC, - 0xCE, 0x31, 0x80, 0x79, 0x34, 0x0F, 0x86, 0x78, 0x18, 0xA6, - 0x36, 0x17, 0xD9, 0x70, 0xA7, 0x22, 0xA7, 0xE8, 0xA2, 0xBD, - 0x74, 0xB9, 0x8E, 0x34, 0xF0, 0xEC, 0xF7, 0x40, 0x22, 0x33, - 0xE8, 0x50, 0x43, 0x66, 0xF0, 0x25, 0x41, 0x20, 0xD9, 0x3F, - 0x8A, 0xC6, 0xAD, 0x69, 0xC6, 0x9C, 0xD9, 0xE0, 0x0D, 0xFF, - 0x93, 0x32, 0x5D, 0x57, 0x45, 0xCC, 0xA4, 0xF9, 0x32, 0xD4, - 0x5A, 0x49, 0x17, 0x1B, 0xFB, 0x2F, 0x91, 0xAA, 0x5B, 0xC5, - 0xC8, 0xC8, 0x2B, 0x20, 0x30, 0x1B, 0xB2, 0x01, 0xC3, 0xA7, - 0x8E, 0x6C, 0xB8, 0xF7, 0xB3, 0x95, 0x4A, 0x28, 0x82, 0xAA, - 0x0C, 0x4B, 0xDA, 0x26, 0x4A, 0x34, 0x7F, 0x17, 0x55, 0x4C, - 0x5D, 0x3C, 0x0B, 0x16, 0xA2, 0xEB, 0x33, 0xFB, 0x38, 0x63, - 0xF2, 0x15, 0x7D, 0xFA, 0x52, 0xA9, 0x58, 0xDD, 0x41, 0x58, - 0xA0, 0x13, 0xD2, 0x55, 0x22, 0xF9, 0xC2, 0xF8, 0x4E, 0x3F, - 0xAC, 0xDC, 0x11, 0x0A, 0xBB, 0x7C, 0xB1, 0x2B, 0xFB, 0x60, - 0xC5, 0x08, 0xB9, 0xB0, 0xED, 0xE8, 0xB9, 0x88, 0xBD, 0x07, - 0xDE, 0x53, 0xD0, 0x6B, 0xE5, 0x6E, 0xA0, 0x17, 0x8C, 0xCF, - 0x02, 0xF0, 0x64, 0xDE, 0xCE, 0x8C, 0x91, 0xED, 0xB4, 0x4F, - 0xB0, 0xEE, 0x12, 0x26, 0xC6, 0x55, 0xA0, 0x4D, 0xCC, 0xF3, - 0x1A, 0x86, 0x5A, 0x01, 0x53, 0x01, 0xAA, 0xED, 0x6D, 0x11, - 0xCD, 0x8A, 0x4A, 0xCA, 0x85, 0x35, 0x35, 0xFA, 0x22, 0x55, - 0xF3, 0xB8, 0xFA, 0x43, 0xD6, 0x9E, 0xB5, 0x0D, 0xD3, 0x85, - 0x59, 0xC9, 0xAF, 0xCD, 0xAB, 0xFA, 0xB6, 0x65, 0x20, 0xCC, - 0x11, 0xF1, 0xDE, 0x87, 0x6F, 0x58, 0xA1, 0x41, 0xF2, 0x80, - 0x75, 0xEA, 0x26, 0x72, 0x8C, 0xE9, 0x17, 0x1C, 0x2B, 0x4D, - 0xA4, 0x9C, 0xAA, 0x32, 0xAA, 0x2C, 0x84, 0xBA, 0x87, 0xAA, - 0x81, 0x66, 0x56, 0x76, 0x0F, 0x1C, 0x58, 0xFE, 0xD1, 0x7F, - 0x33, 0x59, 0xF1, 0xF0, 0x56, 0x50, 0x00, 0x4F, 0x96, 0xF7, - 0x1C, 0x11, 0x7C, 0x36, 0xD8, 0xAD, 0x3E, 0x82, 0x15, 0x68, - 0x40, 0x83, 0xFE, 0x62, 0x94, 0xD5, 0x2A, 0x43, 0x88, 0xD8, - 0x12, 0xE2, 0x37, 0x8A, 0x3E, 0x9E, 0x24, 0x8B, 0x70, 0x3C, - 0xBD, 0x97, 0x0B, 0x59, 0xAC, 0x4B, 0x88, 0x36, 0x2D, 0x2F, - 0xE9, 0x49, 0x14, 0xC0, 0x28, 0x7F, 0x0D, 0xE8, 0x93, 0x76, - 0x22, 0xF3, 0x08, 0x17, 0x34, 0x91, 0x39, 0xA6, 0x84, 0xCA, - 0xF1, 0xD2, 0x8A, 0x9D, 0xF1, 0xD4, 0xA4, 0x85, 0xA6, 0x1E, - 0xFB, 0x6B, 0x75, 0x07, 0x80, 0x84, 0x32, 0xF5, 0x51, 0xD6, - 0x42, 0xA8, 0x69, 0x96, 0xC3, 0xBD, 0xEF, 0x2F, 0xA4, 0x23, - 0x58, 0x07, 0xBC, 0xDE, 0x45, 0xD4, 0x1E, 0x67, 0xF1, 0x00, - 0x65, 0xB5, 0x03, 0xF3, 0x83, 0x9D, 0xE8, 0xDE, 0x63, 0x42, - 0x2B, 0xB6, 0xED, 0x7F, 0x63, 0xF6, 0xCF, 0x53, 0x1B, 0xBD, - 0x9D, 0x6C, 0x26, 0xBC, 0xC2, 0xC3, 0xAF, 0x86, 0x06, 0x5F, - 0x49, 0xBF, 0x7E, 0x76, 0xF5, 0x6C, 0x5B, 0x41, 0xF7, 0xAF, - 0x02, 0x1F, 0x35, 0x43, 0x0D, 0x64, 0x65, 0xFE, 0xD7, 0x9A, - 0x3F, 0x21, 0xD5, 0x74, 0x6E, 0x8A, 0xA8, 0xAF, 0x3B, 0xCE, - 0x85, 0xBB, 0xF7, 0x7B, 0xCA, 0xF7, 0x9D, 0x02, 0x52, 0x55, - 0xE9, 0x3E, 0x4A, 0x4B, 0x62, 0x85, 0x35, 0xFA, 0xBD, 0xEB, - 0x92, 0x25, 0x24, 0x01, 0xFF, 0xEE, 0xFB, 0x94, 0xF6, 0xE6, - 0x9F, 0xE3, 0x3D, 0x93, 0xCF, 0x69, 0xEB, 0x3D, 0x8F, 0x1F, - 0xBE, 0xAE, 0x85, 0x6F, 0x8F, 0x0B, 0x22, 0x57, 0x00, 0x3D, - 0x8E, 0xF4, 0x6B, 0x4D, 0x82, 0x76, 0x91, 0x25, 0x4B, 0x2C, - 0xF1, 0xBC, 0x64, 0x96, 0x54, 0x35, 0xFD, 0xBD, 0xFC, 0x71, - 0xF7, 0x48, 0x40, 0xEB, 0x4C, 0x1C, 0xC4, 0xAB, 0x4F, 0xC9, - 0xC7, 0xB0, 0x8C, 0xBF, 0x27, 0xE2, 0x18, 0xCA, 0x78, 0xAA, - 0xA0, 0x04, 0xAB, 0x6B, 0x6D, 0xBC, 0x89, 0xCB, 0x71, 0xA7, - 0xF8, 0x81, 0x0D, 0x4F, 0x2A, 0x9A, 0x37, 0x60, 0xA0, 0x6A, - 0x14, 0xE7, 0x30, 0x2E, 0x72, 0xF9, 0xE2, 0x39, 0x27, 0xD9, - 0xC6, 0xB2, 0x9E, 0xBC, 0x3D, 0xD6, 0x2D, 0xE4, 0xCD, 0xC2, - 0x40, 0x15, 0xC5, 0x7B, 0x8A, 0x06, 0x42, 0x46, 0xF2, 0x45, - 0x14, 0x83, 0x82, 0xAB, 0x30, 0x6C, 0x73, 0x92, 0x55, 0x51, - 0xE7, 0x8B, 0x3C, 0xD1, 0x2C, 0x8A, 0xC0, 0x16, 0x79, 0xC9, - 0xFD, 0x7C, 0x78, 0x1E, 0xE9, 0xDF, 0xF4, 0x08, 0xEF, 0x38, - 0xEC, 0xCB, 0x81, 0xF1, 0x87, 0x53, 0x8A, 0x0B, 0xF3, 0x56, - 0x0C, 0xBC, 0xEE, 0x03, 0xAE, 0xBC, 0xF8, 0x43, 0x3E, 0xA2, - 0xEA, 0x84, 0x37, 0x72, 0x8A, 0x80, 0x8D, 0x61, 0x1C, 0x79, - 0x3E, 0x4A, 0x5A, 0xC2, 0x73, 0xA0, 0x95, 0xDC, 0x46, 0x2B, - 0x5E, 0x4B, 0x89, 0xE3, 0x9F, 0xD7, 0x14, 0x61, 0x8B, 0x59, - 0xD1, 0x71, 0xB0, 0x04, 0xAA, 0x4B, 0x2A, 0xCA, 0xEF, 0x8D, - 0x3B, 0x4B, 0x52, 0x8F, 0x0B, 0x76, 0xB8, 0x38, 0xF8, 0xDD, - 0xD2, 0xE6, 0x46, 0x53, 0x1C, 0xD5, 0xC8, 0x1E, 0x85, 0x54, - 0x67, 0xC0, 0x77, 0x7E, 0x28, 0x2F, 0x91, 0xC5, 0xE5, 0x28, - 0x54, 0x37, 0xF6, 0x77, 0xEC, 0x6C, 0x36, 0x1D, 0x91, 0xA9, - 0x45, 0xCC, 0x85, 0x61, 0xAB, 0x14, 0xBE, 0x81, 0x6C, 0xFF, - 0x35, 0x8C, 0x13, 0x61, 0xE7, 0x66, 0x83, 0xFF, 0x67, 0x6C, - 0x80, 0x59, 0xD5, 0x6D, 0xAB, 0x5B, 0x81, 0x76, 0x39, 0x1B, - 0xBB, 0xD2, 0xFF, 0x1B, 0x7B, 0x66, 0xD6, 0x42, 0xD0, 0x86, - 0x62, 0x4A, 0xA1, 0x4F, 0x00, 0x41, 0x7E, 0x9C, 0xE5, 0xD6, - 0x82, 0x31, 0xA7, 0x34, 0x16, 0x20, 0x62, 0xFA, 0x1F, 0x6B, - 0x21, 0xBE, 0x62, 0x19, 0xE9, 0x56, 0x7A, 0x4C, 0xF0, 0x7B, - 0xB4, 0x2E, 0x4A, 0xA7, 0x20, 0xC3, 0x5F, 0x7F, 0x5A, 0xA2, - 0xAF, 0xF5, 0xC5, 0xFD, 0x1A, 0x7C, 0xB6, 0x06, 0xCA, 0xE3, - 0x74, 0x72, 0x4E, 0x77, 0xC9, 0xDD, 0x3B, 0x44, 0x16, 0x8C, - 0x45, 0x46, 0xC5, 0xE3, 0x81, 0x1E, 0x3C, 0x4D, 0xAC, 0x1A, - 0x7F, 0xAA, 0x6D, 0xFD, 0xE1, 0x45, 0x59, 0x11, 0x44, 0x48, - 0xB5, 0x09, 0xEF, 0x7E, 0xF2, 0x75, 0x0C, 0xBF, 0xC7, 0x17, - 0xB4, 0x9E, 0x10, 0xC0, 0x11, 0xDD, 0xB2, 0x59, 0xCF, 0x25, - 0x3B, 0xA8, 0x97, 0x56, 0x08, 0xE0, 0x65, 0x27, 0xC5, 0x29, - 0x34, 0xBD, 0x38, 0xB1, 0x39, 0xAA, 0x27, 0xFC, 0x96, 0xCB, - 0x9A, 0x2B, 0x92, 0x74, 0xDF, 0x0A, 0x52, 0xE4, 0x93, 0xA8, - 0x18, 0x15, 0x2C, 0x8C, 0x61, 0xD3, 0xBC, 0xD0, 0x9E, 0x9D, - 0x40, 0x1C, 0x69, 0x95, 0x0D, 0x52, 0x76, 0x3F, 0xD7, 0xD7, - 0xC1, 0x1C, 0x34, 0xE7, 0xD4, 0xD4, 0x17, 0x2D, 0xF0, 0x6A, - 0x1C, 0xE2, 0x53, 0x18, 0x60, 0xC6, 0xA1, 0xCD, 0x4F, 0xAA, - 0x16, 0xA0, 0xC3, 0x3B, 0xCE, 0x4D, 0x73, 0x0B, 0x63, 0x02, - 0x1C, 0xEE, 0x18, 0xBF, 0xF9, 0x33, 0x24, 0xD3, 0x02, 0x34, - 0xCC, 0xB9, 0xD7, 0xC2, 0x00, 0x7F, 0xB4, 0x08, 0x4B, 0xFC, - 0x1D, 0xDF, 0x42, 0x8C, 0x75, 0xEE, 0x13, 0x90, 0x37, 0x14, - 0x0D, 0xD2, 0xE0, 0x50, 0x90, 0x6A, 0xB9, 0xEF, 0x7F, 0x70, - 0x38, 0x2E, 0xCD, 0x39, 0x2E, 0x09, 0x51, 0xDF, 0x58, 0xBE, - 0x8E, 0x82, 0x91, 0xEB, 0xBC, 0xB4, 0x6B, 0x12, 0x40, 0x4E, - 0x44, 0xB8, 0x08, 0x97, 0x57, 0xF0, 0xFE, 0x61, 0xBD, 0x77, - 0xED, 0x46, 0xDA, 0xB7, 0xA4, 0xF5, 0x4F, 0xB2, 0xA6, 0xF1, - 0x47, 0x2D, 0x11, 0x26, 0x74, 0x55, 0x81, 0xFF, 0xFB, 0xEA, - 0x00, 0x03, 0x96, 0xD8, 0xE6, 0x6B, 0xEA, 0x3F, 0x0B, 0x0C, - 0xC0, 0xE4, 0x0A, 0x3D, 0x21, 0x3C, 0x99, 0x51, 0x91, 0x11, - 0xF0, 0x91, 0x68, 0xEE, 0xEE, 0xCD, 0x71, 0x42, 0xAD, 0xBA, - 0x34, 0x68, 0x9F, 0x67, 0xB1, 0xEE, 0x1C, 0x70, 0x7A, 0xFC, - 0x1E, 0x86, 0xF8, 0x96, 0x6C, 0x13, 0xD6, 0x36, 0x57, 0x5F, - 0x11, 0x2E, 0x1B, 0x97, 0xAB, 0x8B, 0x65, 0x3E, 0x8E, 0x91, - 0x69, 0x1C, 0x76, 0xAD, 0xB5, 0x8C, 0xE6, 0x02, 0x93, 0x16, - 0xA4, 0xF5, 0x14, 0x86, 0xB5, 0x16, 0x07, 0xF5, 0x0C, 0x01, - 0xE9, 0xDC, 0xEA, 0x86, 0x58, 0x98, 0xBA, 0x2C, 0x04, 0x0A, - 0x16, 0x8A, 0xF3, 0x10, 0x25, 0x48, 0x51, 0x21, 0x77, 0x69, - 0xF1, 0x22, 0xC3, 0xF4, 0x1D, 0xD5, 0x6D, 0x59, 0x1B, 0x44, - 0x88, 0xFC, 0xE5, 0x4B, 0xE1, 0xD6, 0xF4, 0x46, 0x4C, 0x9D, - 0x45, 0x93, 0xE1, 0xB5, 0x26, 0xDF, 0x48, 0x90, 0x13, 0xA6, - 0x65, 0x7E, 0x18, 0x6A, 0x79, 0x19, 0x81, 0x10, 0x08, 0x80, - 0xA4, 0x99, 0xD3, 0x98, 0x3C, 0x9E, 0x91, 0x31, 0xE9, 0x71, - 0xA0, 0x6A, 0xF9, 0x2F, 0x61, 0xA5, 0x72, 0x13, 0x6C, 0x4C, - 0xD2, 0xAF, 0x40, 0x8B, 0x0D, 0x3D, 0xE4, 0x24, 0x7B, 0x30, - 0x9C, 0xD0, 0x62, 0x42, 0x67, 0x54, 0xC6, 0x34, 0xF2, 0x55, - 0x70, 0x95, 0xAE, 0x16, 0x9F, 0xCC, 0x6F, 0xEA, 0x0B, 0x40, - 0x38, 0xAE, 0x74, 0x89, 0xCB, 0x64, 0x79, 0xF7, 0x08, 0x68, - 0x2C, 0x1E, 0xEE, 0x28, 0xEA, 0x77, 0xA2, 0xA3, 0x8E, 0xF4, - 0xEE, 0xFE, 0x62, 0x25, 0x98, 0xB1, 0xDE, 0x4B, 0x3A, 0x62, - 0xD9, 0x12, 0xD6, 0x09, 0x32, 0x6C, 0x80, 0x27, 0x21, 0x0A, - 0xFE, 0x4D, 0xBF, 0x29, 0x90, 0xCD, 0x6C, 0xE0, 0xAF, 0x06, - 0xB3, 0xC2, 0xDF, 0xB8, 0x50, 0x59, 0xD8, 0x0A, 0xB5, 0x98, - 0xC1, 0xA8, 0x80, 0xD7, 0x61, 0xFC, 0x59, 0xDB, 0xB1, 0x2A, - 0xA5, 0xD7, 0xFA, 0x9E, 0x93, 0x60, 0xD4, 0xB0, 0x6B, 0x44, - 0xB3, 0xC3, 0x3F, 0x9B, 0xEA, 0xD4, 0x8C, 0x08, 0x4B, 0x09, - 0x97, 0xC6, 0x2B, 0xC0, 0x8A, 0x92, 0x35, 0xCA, 0x6F, 0x93, - 0xD6, 0x71, 0x1E, 0xAB, 0x0F, 0x65, 0x42, 0xC2, 0x97, 0x77, - 0x10, 0x6E, 0xD4, 0xEE, 0x2A, 0xDF, 0x54, 0x2A, 0x5F, 0xB4, - 0xD4, 0x72, 0x18, 0x90, 0x42, 0x09, 0xAA, 0xC3, 0x31, 0x89 +#ifndef WOLFSSL_DILITHIUM_NO_SIGN +static const unsigned char bench_dilithium_level2_key[] = { + 0xea, 0x05, 0x24, 0x0d, 0x80, 0x72, 0x25, 0x55, 0xf4, 0x5b, + 0xc2, 0x13, 0x8b, 0x87, 0x5d, 0x31, 0x99, 0x2f, 0x1d, 0xa9, + 0x41, 0x09, 0x05, 0x76, 0xa7, 0xb7, 0x5e, 0x8c, 0x44, 0xe2, + 0x64, 0x79, 0xd8, 0x79, 0x4c, 0xee, 0x92, 0x2b, 0x37, 0xab, + 0xb1, 0x16, 0x65, 0x72, 0xc3, 0x49, 0xc2, 0xec, 0xfd, 0x9a, + 0xe6, 0x2d, 0x1e, 0x5b, 0xe3, 0x04, 0x96, 0x16, 0xad, 0x97, + 0x5d, 0xac, 0xf2, 0xcc, 0x62, 0x2e, 0x34, 0x5d, 0x67, 0x19, + 0x47, 0xee, 0x0f, 0x8b, 0x97, 0x60, 0xb4, 0x0b, 0xeb, 0x6a, + 0x7a, 0x75, 0x14, 0x27, 0x00, 0x39, 0xd6, 0x60, 0xce, 0x39, + 0x6e, 0x69, 0x46, 0xe1, 0x0d, 0xf9, 0xa6, 0xfa, 0x8c, 0xcf, + 0x65, 0x50, 0x59, 0x1d, 0xb0, 0x26, 0xc2, 0xe2, 0xf1, 0xb9, + 0xcd, 0x09, 0x60, 0xcc, 0xbb, 0x57, 0xd6, 0xac, 0xcc, 0xf9, + 0x58, 0x73, 0xa8, 0x81, 0x61, 0x2f, 0xd2, 0xa4, 0x5b, 0x98, + 0x0d, 0x12, 0x88, 0x51, 0x63, 0x38, 0x6e, 0xa2, 0x46, 0x64, + 0x52, 0xc0, 0x71, 0xc1, 0x42, 0x68, 0xd8, 0x42, 0x32, 0x5c, + 0xb4, 0x44, 0x08, 0x95, 0x48, 0xa2, 0x46, 0x6c, 0x0b, 0x10, + 0x09, 0xc8, 0x24, 0x4d, 0x18, 0x37, 0x4c, 0x4c, 0x82, 0x05, + 0x02, 0x22, 0x10, 0x4a, 0x86, 0x30, 0x03, 0x03, 0x11, 0x44, + 0x22, 0x62, 0x01, 0xa9, 0x51, 0x13, 0x02, 0x2c, 0x19, 0x85, + 0x65, 0x51, 0x14, 0x01, 0x9c, 0xb2, 0x81, 0x0a, 0x49, 0x52, + 0xa2, 0xb2, 0x4c, 0x98, 0x34, 0x01, 0x0a, 0x07, 0x06, 0x58, + 0xb2, 0x69, 0x51, 0x24, 0x2d, 0x59, 0x12, 0x52, 0xe0, 0xb4, + 0x04, 0x14, 0x40, 0x29, 0xa2, 0xb0, 0x31, 0x54, 0xc0, 0x40, + 0x63, 0x00, 0x69, 0x18, 0x47, 0x85, 0xc8, 0x30, 0x81, 0x0b, + 0x15, 0x0a, 0xd8, 0xa0, 0x0c, 0x5c, 0x20, 0x4a, 0x11, 0x38, + 0x64, 0x04, 0x94, 0x84, 0xd3, 0x24, 0x72, 0x58, 0x38, 0x28, + 0x18, 0x37, 0x6d, 0x94, 0xc0, 0x4d, 0xa0, 0xa6, 0x0c, 0x9a, + 0x82, 0x31, 0xc2, 0x40, 0x48, 0xda, 0x46, 0x85, 0x03, 0x00, + 0x05, 0xd8, 0x02, 0x4d, 0x0b, 0x85, 0x40, 0xe2, 0x32, 0x86, + 0x4c, 0xa0, 0x65, 0x8a, 0x36, 0x65, 0x42, 0x18, 0x6e, 0x60, + 0x36, 0x0d, 0x40, 0xc0, 0x01, 0x5a, 0x44, 0x42, 0xc4, 0xa4, + 0x0d, 0xd4, 0x88, 0x8d, 0x88, 0x22, 0x52, 0x00, 0xc0, 0x0c, + 0x5b, 0x36, 0x90, 0x09, 0x20, 0x22, 0x08, 0x03, 0x12, 0x90, + 0x12, 0x42, 0x04, 0x20, 0x29, 0x8c, 0x48, 0x6d, 0x20, 0x32, + 0x08, 0x94, 0x88, 0x6c, 0x10, 0x87, 0x21, 0xc1, 0x44, 0x02, + 0x52, 0x40, 0x12, 0xdb, 0xc8, 0x24, 0x14, 0x09, 0x2c, 0x93, + 0x40, 0x09, 0x64, 0xc8, 0x4c, 0x08, 0x48, 0x70, 0xa1, 0x10, + 0x81, 0x4a, 0x80, 0x8c, 0x20, 0x03, 0x31, 0x18, 0xb3, 0x80, + 0xd3, 0x82, 0x25, 0x4c, 0x94, 0x8c, 0x1c, 0x93, 0x89, 0x1a, + 0x91, 0x51, 0xd1, 0xb6, 0x68, 0x43, 0x14, 0x25, 0x84, 0x48, + 0x61, 0x82, 0x40, 0x24, 0xdb, 0x22, 0x4d, 0x63, 0x16, 0x66, + 0x62, 0x90, 0x50, 0xa1, 0x18, 0x86, 0x49, 0x28, 0x25, 0xa0, + 0x10, 0x68, 0x8c, 0x04, 0x00, 0x08, 0x32, 0x4e, 0x22, 0x43, + 0x31, 0x42, 0x96, 0x28, 0x11, 0x23, 0x89, 0xd2, 0xc4, 0x6d, + 0x11, 0x82, 0x8d, 0x8a, 0xa8, 0x90, 0xd2, 0x06, 0x29, 0x80, + 0x82, 0x89, 0x00, 0xa8, 0x41, 0x00, 0x13, 0x6a, 0x12, 0xa8, + 0x04, 0x83, 0xc2, 0x51, 0x13, 0x09, 0x08, 0x62, 0xb4, 0x8d, + 0x94, 0xc2, 0x44, 0x5a, 0xb4, 0x08, 0x0a, 0x10, 0x48, 0xa1, + 0x28, 0x20, 0x1b, 0xb7, 0x64, 0x60, 0x24, 0x25, 0x48, 0xc0, + 0x00, 0x0a, 0x10, 0x09, 0x64, 0xb8, 0x88, 0xcb, 0x44, 0x64, + 0x54, 0x90, 0x05, 0xd2, 0xb8, 0x21, 0x49, 0x28, 0x28, 0x49, + 0x42, 0x0d, 0x63, 0xa0, 0x65, 0xcb, 0x90, 0x30, 0x51, 0x82, + 0x8d, 0x5c, 0xc6, 0x0c, 0x51, 0x06, 0x6a, 0x1a, 0x27, 0x22, + 0x01, 0xa8, 0x24, 0x61, 0xb2, 0x84, 0x23, 0x40, 0x86, 0xa3, + 0xb4, 0x48, 0x19, 0x28, 0x0c, 0x14, 0x06, 0x2e, 0xe2, 0x02, + 0x0d, 0xc4, 0x90, 0x09, 0x08, 0x06, 0x66, 0x9b, 0xc8, 0x10, + 0x5c, 0x46, 0x21, 0xca, 0xa8, 0x30, 0x83, 0x20, 0x89, 0x03, + 0x83, 0x6c, 0xa1, 0x46, 0x8c, 0x90, 0x14, 0x4c, 0x99, 0x02, + 0x81, 0x53, 0x02, 0x10, 0x8b, 0x48, 0x91, 0xe4, 0x40, 0x4a, + 0x22, 0xb1, 0x88, 0xc1, 0x06, 0x0e, 0xc3, 0xa8, 0x08, 0xc8, + 0x46, 0x92, 0x03, 0xb5, 0x4c, 0x23, 0x03, 0x0c, 0xa4, 0x06, + 0x2e, 0xdc, 0x92, 0x81, 0x0c, 0x45, 0x22, 0x40, 0x34, 0x91, + 0x90, 0x96, 0x48, 0x81, 0x82, 0x31, 0xcb, 0x16, 0x72, 0x49, + 0xc8, 0x29, 0x44, 0x86, 0x90, 0x60, 0x22, 0x4e, 0x42, 0x42, + 0x09, 0x4b, 0x82, 0x20, 0x0a, 0xb2, 0x64, 0x20, 0x86, 0x70, + 0x1a, 0xc0, 0x00, 0x1c, 0x41, 0x49, 0x89, 0x84, 0x05, 0x0c, + 0x36, 0x49, 0x19, 0x99, 0x6d, 0x00, 0x08, 0x50, 0x23, 0x96, + 0x6c, 0xe0, 0x44, 0x08, 0x98, 0x24, 0x2c, 0x0a, 0x23, 0x20, + 0x12, 0x04, 0x31, 0xc9, 0x06, 0x32, 0x14, 0x01, 0x41, 0x08, + 0x37, 0x08, 0x58, 0x00, 0x0c, 0x19, 0x04, 0x29, 0x90, 0x18, + 0x05, 0xe1, 0x88, 0x44, 0xc2, 0x20, 0x6c, 0xd1, 0x46, 0x64, + 0xd9, 0x26, 0x62, 0x09, 0x88, 0x68, 0x02, 0x29, 0x29, 0xe1, + 0x18, 0x65, 0x98, 0x04, 0x24, 0xe4, 0x34, 0x0c, 0x12, 0x85, + 0x2d, 0x20, 0x14, 0x06, 0x24, 0x15, 0x82, 0x89, 0x08, 0x91, + 0x60, 0x84, 0x28, 0x24, 0x34, 0x41, 0x1b, 0x49, 0x22, 0xd3, + 0x96, 0x64, 0x1b, 0x86, 0x4c, 0x0c, 0xb9, 0x20, 0x20, 0x39, + 0x04, 0x04, 0x34, 0x6d, 0xc1, 0x28, 0x32, 0x08, 0x14, 0x44, + 0x81, 0x18, 0x2e, 0xda, 0x38, 0x41, 0x63, 0x18, 0x26, 0xd8, + 0x48, 0x26, 0x12, 0x20, 0x21, 0x09, 0xc5, 0x25, 0x92, 0x42, + 0x0c, 0x88, 0x04, 0x64, 0x11, 0x43, 0x8a, 0x19, 0x92, 0x60, + 0x5c, 0xc6, 0x31, 0xa1, 0x24, 0x6a, 0xd8, 0xb6, 0x49, 0x1b, + 0x81, 0x90, 0xe2, 0x32, 0x4e, 0x62, 0x44, 0x21, 0x80, 0xb8, + 0x10, 0x4b, 0x90, 0x49, 0x5c, 0x06, 0x09, 0x48, 0x20, 0x49, + 0xa2, 0x92, 0x71, 0x5c, 0x48, 0x02, 0xc8, 0x08, 0x81, 0xa4, + 0x32, 0x66, 0xc9, 0x30, 0x11, 0xca, 0x92, 0x91, 0xc0, 0x00, + 0x41, 0x44, 0x98, 0x4d, 0x98, 0x12, 0x4e, 0x92, 0x46, 0x8e, + 0x49, 0xb8, 0x64, 0xdc, 0x18, 0x50, 0x51, 0xb4, 0x48, 0x08, + 0x47, 0x24, 0x08, 0x46, 0x32, 0x1b, 0x23, 0x00, 0x09, 0xb8, + 0x04, 0x0a, 0x44, 0x0c, 0x0b, 0xc7, 0x8d, 0x19, 0xa4, 0x09, + 0x11, 0x30, 0x41, 0xe3, 0x24, 0x45, 0x89, 0x1f, 0x65, 0x54, + 0xf6, 0x38, 0x04, 0x37, 0xcc, 0x89, 0xc3, 0xc5, 0xdc, 0x43, + 0xd9, 0x13, 0x56, 0x06, 0x05, 0x50, 0x29, 0x4e, 0x0f, 0xa5, + 0x5c, 0x5d, 0xd7, 0x82, 0xa1, 0x63, 0x59, 0x0d, 0x3e, 0x5b, + 0x00, 0xe6, 0x0e, 0xd8, 0x1c, 0xc7, 0xaf, 0xc0, 0x48, 0xb6, + 0x07, 0x5c, 0x65, 0x00, 0x89, 0xb3, 0x09, 0xbc, 0x4a, 0xaa, + 0xa6, 0x72, 0xbe, 0x6b, 0x9a, 0xb3, 0x5b, 0x27, 0x82, 0x65, + 0x9b, 0xc9, 0x6f, 0x19, 0x88, 0x94, 0x0b, 0x37, 0x44, 0x2f, + 0xe3, 0x9a, 0x02, 0xda, 0xff, 0x11, 0xb0, 0x48, 0x89, 0x70, + 0x8c, 0x84, 0xc2, 0xc0, 0x31, 0x4a, 0xad, 0x70, 0xe1, 0xa7, + 0x15, 0xfd, 0xb2, 0x6d, 0x93, 0xda, 0x17, 0x68, 0xc4, 0xe3, + 0xfd, 0x2c, 0x08, 0x15, 0xb9, 0xa4, 0xc5, 0x1b, 0x97, 0xc9, + 0xa3, 0xaf, 0x0d, 0x21, 0x06, 0x3d, 0xf1, 0x05, 0xd4, 0x35, + 0x80, 0x2e, 0x23, 0x99, 0xbd, 0x3a, 0x1a, 0x6c, 0xad, 0xbf, + 0x56, 0xb5, 0xd3, 0x95, 0x1b, 0x30, 0x4d, 0x56, 0xc1, 0x77, + 0xe6, 0xd6, 0xab, 0x94, 0x46, 0x68, 0xd7, 0xb8, 0xe4, 0x9d, + 0xb2, 0x8d, 0xc4, 0xd1, 0xc8, 0x92, 0xbe, 0x5d, 0x1f, 0x58, + 0x55, 0x7f, 0x11, 0x55, 0xc5, 0x2e, 0xc3, 0x9e, 0x2a, 0x29, + 0x51, 0xe8, 0x75, 0x49, 0xa7, 0xa3, 0xda, 0x0b, 0xcf, 0xf8, + 0x3f, 0x78, 0xac, 0x4c, 0x4e, 0x78, 0x6f, 0x0e, 0x67, 0xad, + 0x94, 0x59, 0x20, 0x5e, 0x37, 0x18, 0xb9, 0x09, 0x87, 0xdb, + 0xdd, 0xf0, 0xc2, 0x4d, 0x03, 0xcc, 0x98, 0x22, 0x4b, 0xe5, + 0x7d, 0x8e, 0x74, 0x7e, 0xa9, 0x1b, 0xeb, 0x7a, 0xae, 0xaf, + 0x2e, 0x7c, 0x3c, 0xc0, 0x1a, 0x30, 0x40, 0x0d, 0x79, 0x86, + 0x53, 0xcc, 0x0b, 0x2b, 0xbe, 0xa5, 0x72, 0x3b, 0xbb, 0x53, + 0x9e, 0xd5, 0xc2, 0x23, 0x1d, 0x35, 0xcd, 0x22, 0x12, 0xed, + 0x9a, 0xee, 0xc8, 0xf9, 0x05, 0x27, 0xdb, 0x46, 0x56, 0xcc, + 0x24, 0x4d, 0xee, 0xaf, 0xab, 0xa9, 0x78, 0x75, 0x75, 0xb9, + 0xd1, 0xfd, 0x39, 0x3a, 0xb2, 0xa2, 0xeb, 0x87, 0x76, 0xb2, + 0x19, 0x47, 0x88, 0xab, 0x42, 0x85, 0x4b, 0xd9, 0x76, 0x22, + 0x68, 0x4b, 0xc9, 0x88, 0x38, 0x28, 0x0a, 0x34, 0x5d, 0x12, + 0x4f, 0xf5, 0x43, 0x64, 0x44, 0x8c, 0x3c, 0xc2, 0x99, 0x91, + 0x4e, 0xfd, 0xfd, 0x9c, 0x73, 0xbf, 0x85, 0xf9, 0x9f, 0xe1, + 0x53, 0x19, 0xc8, 0x19, 0xcb, 0x7c, 0xdb, 0x9a, 0x3a, 0x2c, + 0x34, 0x55, 0x8c, 0x64, 0x6f, 0xc5, 0xb7, 0x93, 0x53, 0xb4, + 0x97, 0x7e, 0xc2, 0xf8, 0x7e, 0x8d, 0x44, 0x10, 0xca, 0x49, + 0xf5, 0x5c, 0xe8, 0xce, 0xc4, 0xcc, 0x42, 0xf0, 0x85, 0xf1, + 0xf2, 0x10, 0xa7, 0x0b, 0x37, 0x6a, 0x8e, 0x50, 0x96, 0x96, + 0x9d, 0xd9, 0x8f, 0x54, 0x45, 0x56, 0xf8, 0x64, 0x88, 0xab, + 0x51, 0x4f, 0x9f, 0x61, 0xd9, 0x12, 0x87, 0xac, 0x1d, 0xc1, + 0x23, 0xea, 0xb3, 0x5d, 0xa4, 0x6d, 0xfa, 0x58, 0x92, 0x8f, + 0x77, 0x78, 0x61, 0xe5, 0xe4, 0x33, 0xdb, 0x10, 0x2d, 0xdd, + 0xb6, 0xd7, 0xb4, 0xd0, 0x8d, 0xd1, 0xa8, 0x0b, 0x94, 0xdf, + 0xcf, 0xd7, 0xac, 0xdf, 0x47, 0x0b, 0x38, 0xe0, 0xa5, 0xf8, + 0xc3, 0xd2, 0xc3, 0xfb, 0x0f, 0x98, 0x00, 0x2b, 0x17, 0x3c, + 0x44, 0x70, 0x36, 0x47, 0x27, 0x89, 0x41, 0xcb, 0x87, 0x5a, + 0xa4, 0x2c, 0x57, 0x6d, 0x8c, 0xcb, 0xc0, 0x7d, 0x6b, 0xf5, + 0xa1, 0x17, 0x39, 0x4a, 0xb5, 0xac, 0xc6, 0x41, 0x90, 0x66, + 0x85, 0xc4, 0x4b, 0x18, 0xc6, 0xe6, 0x09, 0x6d, 0x6e, 0xbb, + 0x7f, 0x72, 0x96, 0xd3, 0x21, 0x5a, 0x96, 0xaf, 0x9e, 0xb6, + 0x0b, 0x3f, 0xe8, 0x83, 0xe5, 0x53, 0x11, 0x81, 0xc6, 0xab, + 0x40, 0xa9, 0x09, 0xb6, 0x74, 0x5e, 0xe1, 0xc3, 0x82, 0x1e, + 0xda, 0x2f, 0x24, 0xe0, 0x94, 0x8f, 0x07, 0xb7, 0x9b, 0xc6, + 0x50, 0xef, 0x3a, 0x79, 0x89, 0x4d, 0x6f, 0x16, 0x33, 0x04, + 0x24, 0x7e, 0x4a, 0xab, 0x5d, 0x03, 0x29, 0xad, 0xba, 0xa3, + 0x6c, 0xe2, 0x05, 0xab, 0x4d, 0x69, 0xb6, 0x61, 0x39, 0x9d, + 0xc3, 0x53, 0x11, 0xc0, 0xe3, 0xaa, 0x2e, 0xdc, 0x74, 0x09, + 0xbd, 0x19, 0xb5, 0xbb, 0x51, 0x1e, 0x77, 0x3e, 0xce, 0x64, + 0x13, 0xeb, 0x74, 0x03, 0xb7, 0x49, 0x99, 0xb0, 0x71, 0x99, + 0xe6, 0x17, 0x3c, 0x80, 0xe6, 0xb5, 0x51, 0xe9, 0xb3, 0xe4, + 0x2b, 0xaa, 0x52, 0x15, 0x99, 0x4e, 0x46, 0x6d, 0x67, 0x8e, + 0x79, 0xc4, 0x3c, 0xa6, 0xdc, 0x8f, 0xed, 0x87, 0xb9, 0x68, + 0x6d, 0xdc, 0x19, 0xa1, 0x52, 0x37, 0x06, 0x76, 0xad, 0xe9, + 0x61, 0x5c, 0x82, 0x16, 0x81, 0xaf, 0x3a, 0x89, 0xbf, 0x72, + 0xb0, 0xc7, 0x88, 0x3c, 0x58, 0xfe, 0xe4, 0xa5, 0x41, 0x50, + 0xfc, 0x8a, 0x15, 0xb0, 0x78, 0xd4, 0x77, 0x06, 0x4b, 0xc4, + 0x21, 0x7f, 0xaa, 0x2b, 0x88, 0x7f, 0x8c, 0x3b, 0x9b, 0xbb, + 0x2e, 0x41, 0xcf, 0x9b, 0x06, 0xd3, 0x4d, 0xcf, 0xb2, 0x9c, + 0x91, 0x46, 0x35, 0x3a, 0x5a, 0x0b, 0xe4, 0xac, 0x96, 0x7c, + 0xe0, 0xd4, 0x34, 0xe5, 0xab, 0xae, 0xa7, 0x67, 0xbf, 0x4d, + 0xab, 0x48, 0xfd, 0xcb, 0x3f, 0x5c, 0xde, 0x3f, 0x83, 0xcc, + 0x52, 0x0f, 0xdd, 0x7f, 0x20, 0x25, 0xed, 0xee, 0xd0, 0x14, + 0x38, 0xf7, 0x33, 0x4c, 0x3c, 0x5e, 0x23, 0x80, 0xa3, 0x0a, + 0xe8, 0xb0, 0xef, 0x5b, 0xca, 0xc9, 0x97, 0x13, 0x98, 0xfe, + 0x91, 0x62, 0x14, 0xa8, 0x64, 0xf6, 0x20, 0xc9, 0xc9, 0x6f, + 0x8b, 0xc0, 0xec, 0x39, 0x15, 0xa7, 0x59, 0x62, 0x68, 0x21, + 0xe1, 0x5f, 0xf6, 0xa1, 0x76, 0xb0, 0xca, 0x1b, 0x2a, 0x71, + 0xe3, 0x1a, 0x24, 0x91, 0x1f, 0x3a, 0xbb, 0xf1, 0xc9, 0x09, + 0x42, 0x48, 0x7e, 0x19, 0x1b, 0xf1, 0xf0, 0x13, 0x33, 0xf1, + 0x62, 0x31, 0x00, 0x97, 0x73, 0x9b, 0x3c, 0x26, 0xf8, 0x42, + 0xd0, 0xd4, 0x41, 0x1b, 0x9f, 0x7e, 0x43, 0x4b, 0x0b, 0x08, + 0xd7, 0xa0, 0xa8, 0x32, 0x34, 0x0a, 0xc9, 0xef, 0xb8, 0xeb, + 0xe7, 0x64, 0x3b, 0x40, 0x88, 0xe0, 0x60, 0x59, 0x07, 0xef, + 0xb9, 0x5f, 0x71, 0x92, 0x90, 0xa4, 0x5f, 0x34, 0x38, 0x93, + 0x92, 0x43, 0x87, 0xaf, 0xdd, 0x87, 0x63, 0x8c, 0x1d, 0xe5, + 0x86, 0x9e, 0xe6, 0xde, 0x94, 0xdd, 0x33, 0x5d, 0x95, 0x64, + 0xd8, 0xc4, 0x8a, 0x3c, 0xe7, 0x4b, 0xd6, 0x3f, 0xc5, 0x69, + 0x6a, 0xa8, 0x7f, 0x0f, 0x93, 0x77, 0x02, 0x46, 0x66, 0xa5, + 0xa0, 0x60, 0x8b, 0xec, 0xb1, 0xa2, 0xfc, 0x2a, 0x09, 0xb8, + 0x08, 0x1c, 0x05, 0x6b, 0x78, 0xb7, 0x7a, 0xe5, 0x60, 0xa4, + 0xaf, 0x3a, 0x9d, 0xaa, 0xf5, 0x22, 0x9b, 0x5e, 0xef, 0xc3, + 0x46, 0xed, 0x67, 0xd0, 0x8b, 0xda, 0xb4, 0xa3, 0x34, 0x32, + 0x20, 0x9d, 0x88, 0x7e, 0x43, 0x42, 0x6f, 0x02, 0xf8, 0x48, + 0x9b, 0xc5, 0x02, 0xad, 0xaa, 0xa9, 0xee, 0x19, 0x1b, 0xde, + 0x02, 0x83, 0x81, 0x10, 0xa6, 0x79, 0x4e, 0xad, 0x15, 0xf7, + 0x3e, 0x4e, 0x1e, 0x72, 0xfe, 0x52, 0x49, 0x24, 0xce, 0x82, + 0x31, 0x59, 0x72, 0xae, 0xd5, 0x34, 0x50, 0x87, 0x8b, 0xe3, + 0x8e, 0xec, 0x61, 0x35, 0x13, 0x57, 0xb1, 0xe6, 0xac, 0xfb, + 0x16, 0xc3, 0x1a, 0x98, 0x92, 0xcb, 0xcd, 0xc9, 0xf7, 0x10, + 0x6a, 0x43, 0x96, 0x33, 0x2d, 0x6f, 0x6c, 0x76, 0xb0, 0xf6, + 0x48, 0x4c, 0xae, 0x13, 0x67, 0x5d, 0x42, 0x01, 0x8e, 0x54, + 0x51, 0xcc, 0x65, 0xf1, 0x95, 0x11, 0x3c, 0x96, 0x2a, 0x5a, + 0x42, 0x3d, 0x9b, 0xbb, 0xb7, 0x7b, 0x28, 0x96, 0x09, 0xbb, + 0xed, 0x2d, 0xbc, 0xb7, 0x90, 0x62, 0xd3, 0xbe, 0xbd, 0xae, + 0x50, 0x15, 0x96, 0xc1, 0x03, 0x91, 0x14, 0x34, 0x4f, 0x21, + 0xa5, 0x6e, 0x78, 0x4a, 0x5d, 0x8b, 0xcf, 0x5b, 0x1a, 0x8a, + 0x57, 0x43, 0xb8, 0x25, 0xd3, 0xa2, 0xcd, 0x78, 0xb4, 0x93, + 0x07, 0x7a, 0x14, 0xc1, 0x0c, 0x6f, 0x5f, 0x5e, 0xcb, 0x11, + 0x17, 0x81, 0x0d, 0x7d, 0x0f, 0xda, 0xd1, 0x92, 0x43, 0x56, + 0xaf, 0x75, 0x53, 0x44, 0x1f, 0xc7, 0x9c, 0xd3, 0xc5, 0x47, + 0xe0, 0xac, 0x4a, 0x11, 0xe4, 0xfe, 0x6c, 0x80, 0x79, 0xcc, + 0x60, 0x7a, 0xd9, 0x56, 0x65, 0x83, 0x5e, 0xcf, 0x37, 0x27, + 0x55, 0xe2, 0x4d, 0xf9, 0xd6, 0x09, 0x2d, 0xee, 0xda, 0x10, + 0x6b, 0xdc, 0xd2, 0x70, 0x46, 0x94, 0xaa, 0xf5, 0x21, 0xc5, + 0xf0, 0x79, 0xdb, 0x9b, 0x8e, 0x9a, 0xdb, 0x5a, 0x56, 0x41, + 0x43, 0xe7, 0x1f, 0x8d, 0xfd, 0xda, 0x12, 0x5f, 0xf7, 0x9e, + 0x47, 0x1a, 0xf7, 0x73, 0x40, 0x67, 0xc2, 0x61, 0x07, 0x33, + 0x16, 0x78, 0x60, 0x05, 0x85, 0x5c, 0x2f, 0x2b, 0xbf, 0x2c, + 0x7a, 0x39, 0xc6, 0xed, 0xcb, 0x43, 0x66, 0x27, 0x93, 0xcd, + 0x92, 0x8d, 0x62, 0x8c, 0xaa, 0x61, 0x1c, 0x9c, 0x4c, 0x90, + 0xba, 0xba, 0x4b, 0xc1, 0xf1, 0x22, 0xde, 0xe0, 0xf9, 0x3e, + 0x04, 0xb9, 0x56, 0xa3, 0x1c, 0xe8, 0xda, 0xd6, 0x09, 0x4a, + 0x7d, 0x89, 0xbc, 0xf4, 0xe8, 0x4d, 0xa1, 0xe8, 0x34, 0x90, + 0xa5, 0x31, 0x3a, 0xec, 0x56, 0xc5, 0xd2, 0x92, 0x0b, 0xe9, + 0x58, 0xbb, 0xb2, 0x84, 0x9b, 0xa9, 0x1d, 0x19, 0xdb, 0x7a, + 0x02, 0x75, 0x79, 0x16, 0x35, 0xee, 0x3a, 0x3f, 0x4e, 0x5e, + 0x11, 0x90, 0x04, 0x03, 0xce, 0x8b, 0xa0, 0xd8, 0xc1, 0xee, + 0x52, 0x33, 0x6e, 0xd2, 0x6e, 0x06, 0x5c, 0x99, 0x24, 0x6f, + 0x16, 0xd9, 0x90, 0x28, 0xe5, 0x2d, 0x91, 0x6f, 0x1a, 0x57, + 0xf0, 0x4c, 0x7c, 0x3f, 0x7b, 0xd7, 0x30, 0xed, 0x6d, 0x21, + 0xb7, 0xf8, 0xed, 0xf3, 0x34, 0x89, 0xfa, 0xf0, 0x51, 0x6f, + 0x99, 0xa0, 0x5e, 0xf8, 0x74, 0xc7, 0x4f, 0xb5, 0x59, 0x52, + 0xbe, 0x45, 0xac, 0x3f, 0x34, 0x51, 0x87, 0x6e, 0x84, 0xea, + 0xb0, 0x40, 0xe1, 0x84, 0x16, 0x66, 0x30, 0xf1, 0x5c, 0xb2, + 0x74, 0x25, 0x03, 0xe3, 0x2e, 0x82, 0xc5, 0x60, 0x9d, 0xe4, + 0xca, 0xec, 0x49, 0x6b, 0x4e, 0x5a, 0x09, 0xa8, 0xfe, 0xff, + 0x1d, 0xa1, 0xe8, 0xec, 0x9a, 0x22, 0x3b, 0xd6, 0x72, 0x93, + 0x6f, 0x6b, 0x5a, 0xfb, 0x2d, 0x5a, 0xde, 0x01, 0x3e, 0xf6, + 0xdc, 0x77, 0x55, 0x1e, 0x32, 0x19, 0xc8, 0xa1, 0xbb, 0xcf, + 0xcb, 0x41, 0x54, 0xa2, 0xcb, 0xe6, 0x61, 0xca, 0x43, 0x63, + 0xd2, 0x2c, 0xae, 0xf4, 0xd9, 0x49, 0xb1, 0x75, 0x1a, 0x06, + 0x92, 0x13, 0x90, 0x57, 0x89, 0x8e, 0x9f, 0x26, 0xc5, 0x14, + 0xd8, 0xc7, 0x93, 0xb2, 0xaa, 0x3a, 0x9c, 0x10, 0xd5, 0x68, + 0x52, 0x28, 0x39, 0xee, 0x30, 0xdc, 0x00, 0x4b, 0x65, 0x72, + 0x59, 0x98, 0xad, 0x2e, 0x8c, 0xaf, 0x4e, 0x79, 0x0a, 0x8c, + 0x0c, 0x9d, 0xb6, 0x43, 0x26, 0x83, 0x71, 0x7b, 0x1e, 0x86, + 0x4d, 0x33, 0xd7, 0x20, 0x29, 0x6a, 0xbf, 0x2f, 0x8e, 0x4b, + 0x13, 0x35, 0x65, 0xc8, 0xec, 0xe3, 0x2c, 0xde, 0xfb, 0x30, + 0x57, 0xa9, 0x92, 0x22, 0x5d, 0x79, 0x16, 0x07, 0x73, 0x9b, + 0xe2, 0x6e, 0xd4, 0x99, 0xb4, 0x35, 0xfd, 0xa2, 0xb5, 0xd9, + 0xe5, 0x74, 0xd1, 0xb2, 0xcf, 0x32, 0xf1, 0x19, 0x69, 0xcf, + 0x1e, 0x10, 0xcc, 0x3c, 0xaf, 0xbe, 0xa4, 0x33, 0x11, 0x83, + 0x64, 0xc0, 0x39, 0xe5, 0xb0, 0x8f, 0x32, 0xf4, 0x01, 0x6a, + 0x2a, 0x11, 0x8e, 0xdd, 0x03, 0x81, 0x39, 0xe7, 0x70, 0x16, + 0x2f, 0x0e, 0x24, 0xa9, 0x12, 0x0b, 0xdb, 0xa8, 0x6c, 0xb3, + 0xf3, 0x74, 0x95, 0xca, 0x64, 0x1d, 0xee, 0x25, 0xc5, 0x27, + 0xed, 0x0f, 0x82, 0xb5, 0x7a, 0x62, 0x27, 0xb2, 0x87, 0x53, + 0x11, 0x39, 0x5e, 0xb8, 0x11, 0xca, 0x25, 0xe8, 0x17, 0x46, + 0xd3, 0x0f, 0x5d, 0x70, 0x68, 0xe1, 0x5f, 0xd1, 0xab, 0x65, + 0xe5, 0x42, 0x87, 0x1e, 0x96, 0xaf, 0x13, 0x0c, 0x9b, 0x15, + 0x75, 0x14, 0x31, 0x75, 0xcc, 0x15, 0xbf, 0x2c, 0x74, 0xab, + 0xc9, 0x9c, 0xda, 0x62, 0x1d, 0xeb, 0x19, 0x81, 0x67, 0x5e, + 0xcd, 0x54, 0x87, 0x07, 0x67, 0xba, 0xe3, 0xf6, 0x03, 0xbe, + 0x6d, 0x64, 0x2d, 0xbc, 0xec, 0x54, 0x13, 0x12, 0x5b, 0x44, + 0x90, 0x95, 0x86, 0x77, 0x8c, 0x59, 0xbd, 0x8e, 0xba, 0xb1, + 0x12, 0xea, 0xc1, 0x94, 0x37, 0xa0, 0x11, 0xff, 0xb2, 0xa4, + 0xc3, 0x61, 0xf2, 0xa3, 0x49, 0xbe, 0xe7, 0xb6, 0x96, 0x2f, }; static const int sizeof_bench_dilithium_level2_key = sizeof(bench_dilithium_level2_key); -/* certs/dilithium/bench_dilithium_level3_key.der */ -static const unsigned char bench_dilithium_level3_key[] = -{ - 0x30, 0x82, 0x17, 0x5A, 0x02, 0x01, 0x00, 0x30, 0x0D, 0x06, - 0x0B, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0B, 0x07, - 0x06, 0x05, 0x04, 0x82, 0x17, 0x44, 0x04, 0x82, 0x17, 0x40, - 0x2E, 0xFE, 0x07, 0xDF, 0x5E, 0xF9, 0x18, 0xB4, 0x0E, 0xBF, - 0x9C, 0x1C, 0xCA, 0x84, 0xBA, 0x62, 0xB9, 0xA2, 0x96, 0x76, - 0xB6, 0xB7, 0x77, 0x9C, 0xBE, 0x0C, 0xF8, 0xA5, 0xEF, 0x74, - 0xB1, 0xC2, 0x8D, 0x95, 0x6D, 0x38, 0x49, 0x01, 0xA8, 0x3D, - 0x63, 0x0B, 0xDF, 0x4B, 0x5D, 0xF4, 0xC4, 0x98, 0x27, 0x77, - 0x88, 0xA0, 0xA9, 0xF2, 0x38, 0x32, 0x62, 0x17, 0x11, 0xD6, - 0xBE, 0xA0, 0xFD, 0xEB, 0xBF, 0x4A, 0xF2, 0x6C, 0x44, 0x62, - 0x2D, 0x87, 0x3D, 0xAD, 0x0C, 0x47, 0x06, 0x00, 0x7E, 0xAF, - 0x52, 0xE7, 0xA1, 0x8E, 0x7A, 0xA7, 0x7D, 0x3C, 0xE5, 0xB2, - 0x59, 0xDA, 0x89, 0x76, 0xF7, 0xD4, 0x73, 0x16, 0x33, 0x67, - 0x88, 0x46, 0x51, 0x13, 0x12, 0x38, 0x64, 0x76, 0x73, 0x40, - 0x16, 0x55, 0x70, 0x06, 0x32, 0x84, 0x47, 0x25, 0x33, 0x44, - 0x70, 0x68, 0x36, 0x25, 0x62, 0x47, 0x76, 0x65, 0x73, 0x11, - 0x28, 0x00, 0x75, 0x33, 0x81, 0x13, 0x62, 0x51, 0x31, 0x33, - 0x11, 0x41, 0x51, 0x62, 0x55, 0x33, 0x07, 0x60, 0x14, 0x18, - 0x30, 0x58, 0x22, 0x67, 0x26, 0x86, 0x12, 0x78, 0x17, 0x47, - 0x30, 0x06, 0x05, 0x36, 0x37, 0x23, 0x08, 0x67, 0x05, 0x05, - 0x06, 0x85, 0x33, 0x83, 0x14, 0x63, 0x44, 0x35, 0x00, 0x04, - 0x56, 0x03, 0x23, 0x03, 0x33, 0x13, 0x02, 0x23, 0x25, 0x80, - 0x22, 0x00, 0x53, 0x73, 0x13, 0x70, 0x03, 0x84, 0x15, 0x50, - 0x14, 0x20, 0x06, 0x74, 0x03, 0x41, 0x26, 0x74, 0x63, 0x65, - 0x42, 0x03, 0x00, 0x72, 0x66, 0x44, 0x36, 0x88, 0x60, 0x85, - 0x76, 0x86, 0x17, 0x72, 0x16, 0x37, 0x23, 0x82, 0x15, 0x84, - 0x57, 0x14, 0x20, 0x72, 0x15, 0x55, 0x26, 0x42, 0x82, 0x66, - 0x40, 0x54, 0x03, 0x54, 0x62, 0x61, 0x83, 0x35, 0x20, 0x76, - 0x62, 0x14, 0x37, 0x35, 0x42, 0x04, 0x32, 0x72, 0x08, 0x35, - 0x42, 0x74, 0x51, 0x24, 0x54, 0x86, 0x36, 0x56, 0x11, 0x83, - 0x64, 0x44, 0x54, 0x78, 0x80, 0x50, 0x55, 0x72, 0x84, 0x16, - 0x48, 0x13, 0x04, 0x17, 0x06, 0x36, 0x25, 0x48, 0x21, 0x33, - 0x45, 0x71, 0x21, 0x54, 0x10, 0x26, 0x13, 0x72, 0x12, 0x30, - 0x03, 0x73, 0x48, 0x84, 0x16, 0x22, 0x11, 0x38, 0x26, 0x43, - 0x53, 0x36, 0x56, 0x12, 0x15, 0x70, 0x07, 0x57, 0x00, 0x65, - 0x72, 0x11, 0x73, 0x48, 0x01, 0x13, 0x31, 0x58, 0x82, 0x60, - 0x61, 0x17, 0x78, 0x44, 0x48, 0x15, 0x48, 0x26, 0x62, 0x43, - 0x72, 0x44, 0x62, 0x76, 0x40, 0x15, 0x63, 0x26, 0x10, 0x51, - 0x82, 0x21, 0x05, 0x82, 0x30, 0x56, 0x58, 0x62, 0x76, 0x48, - 0x67, 0x82, 0x86, 0x51, 0x32, 0x37, 0x78, 0x38, 0x13, 0x82, - 0x55, 0x22, 0x45, 0x22, 0x68, 0x66, 0x15, 0x30, 0x35, 0x77, - 0x04, 0x28, 0x45, 0x85, 0x72, 0x48, 0x30, 0x26, 0x06, 0x24, - 0x12, 0x75, 0x42, 0x53, 0x88, 0x14, 0x15, 0x07, 0x08, 0x86, - 0x05, 0x08, 0x01, 0x56, 0x77, 0x44, 0x38, 0x53, 0x22, 0x21, - 0x20, 0x56, 0x25, 0x15, 0x72, 0x68, 0x27, 0x03, 0x71, 0x25, - 0x64, 0x11, 0x44, 0x34, 0x77, 0x60, 0x68, 0x58, 0x44, 0x74, - 0x76, 0x63, 0x86, 0x16, 0x01, 0x40, 0x68, 0x51, 0x20, 0x12, - 0x36, 0x55, 0x01, 0x84, 0x61, 0x80, 0x46, 0x36, 0x28, 0x82, - 0x44, 0x66, 0x14, 0x80, 0x50, 0x32, 0x34, 0x46, 0x21, 0x34, - 0x63, 0x04, 0x22, 0x20, 0x17, 0x84, 0x88, 0x88, 0x47, 0x02, - 0x52, 0x60, 0x45, 0x35, 0x86, 0x72, 0x71, 0x43, 0x30, 0x58, - 0x24, 0x11, 0x11, 0x64, 0x45, 0x36, 0x25, 0x18, 0x82, 0x18, - 0x16, 0x80, 0x27, 0x76, 0x53, 0x08, 0x70, 0x87, 0x64, 0x43, - 0x68, 0x86, 0x07, 0x04, 0x34, 0x10, 0x68, 0x30, 0x21, 0x01, - 0x86, 0x66, 0x06, 0x50, 0x41, 0x72, 0x18, 0x00, 0x05, 0x40, - 0x36, 0x35, 0x60, 0x50, 0x82, 0x82, 0x24, 0x73, 0x31, 0x35, - 0x81, 0x35, 0x02, 0x50, 0x22, 0x76, 0x44, 0x52, 0x27, 0x43, - 0x82, 0x66, 0x51, 0x38, 0x86, 0x72, 0x18, 0x54, 0x20, 0x65, - 0x45, 0x26, 0x03, 0x42, 0x24, 0x25, 0x27, 0x36, 0x02, 0x04, - 0x38, 0x77, 0x18, 0x44, 0x17, 0x78, 0x46, 0x34, 0x68, 0x00, - 0x72, 0x57, 0x72, 0x67, 0x53, 0x82, 0x51, 0x06, 0x34, 0x56, - 0x71, 0x26, 0x73, 0x55, 0x58, 0x11, 0x44, 0x15, 0x26, 0x81, - 0x14, 0x88, 0x25, 0x45, 0x52, 0x84, 0x13, 0x60, 0x12, 0x26, - 0x12, 0x36, 0x11, 0x61, 0x30, 0x25, 0x32, 0x83, 0x00, 0x71, - 0x73, 0x04, 0x48, 0x40, 0x70, 0x21, 0x36, 0x54, 0x45, 0x33, - 0x43, 0x00, 0x76, 0x62, 0x63, 0x71, 0x15, 0x35, 0x27, 0x50, - 0x06, 0x16, 0x30, 0x45, 0x08, 0x12, 0x51, 0x68, 0x38, 0x21, - 0x71, 0x61, 0x61, 0x18, 0x35, 0x15, 0x25, 0x47, 0x14, 0x62, - 0x51, 0x14, 0x76, 0x12, 0x62, 0x60, 0x63, 0x16, 0x20, 0x68, - 0x62, 0x31, 0x56, 0x64, 0x05, 0x84, 0x56, 0x26, 0x40, 0x42, - 0x88, 0x05, 0x60, 0x84, 0x82, 0x10, 0x23, 0x87, 0x63, 0x33, - 0x60, 0x40, 0x58, 0x12, 0x83, 0x26, 0x03, 0x13, 0x85, 0x23, - 0x02, 0x73, 0x05, 0x27, 0x40, 0x02, 0x75, 0x85, 0x46, 0x51, - 0x83, 0x71, 0x37, 0x16, 0x05, 0x86, 0x35, 0x01, 0x45, 0x00, - 0x53, 0x68, 0x27, 0x11, 0x06, 0x08, 0x82, 0x60, 0x58, 0x28, - 0x50, 0x07, 0x32, 0x56, 0x26, 0x46, 0x78, 0x63, 0x71, 0x16, - 0x48, 0x46, 0x86, 0x41, 0x37, 0x75, 0x06, 0x01, 0x11, 0x46, - 0x45, 0x21, 0x03, 0x82, 0x42, 0x75, 0x83, 0x30, 0x66, 0x00, - 0x74, 0x74, 0x46, 0x05, 0x33, 0x82, 0x33, 0x07, 0x34, 0x53, - 0x07, 0x78, 0x53, 0x07, 0x41, 0x37, 0x78, 0x54, 0x06, 0x11, - 0x42, 0x47, 0x05, 0x02, 0x62, 0x34, 0x27, 0x17, 0x78, 0x70, - 0x70, 0x46, 0x00, 0x38, 0x75, 0x48, 0x74, 0x46, 0x83, 0x35, - 0x08, 0x46, 0x14, 0x12, 0x20, 0x68, 0x00, 0x73, 0x57, 0x81, - 0x84, 0x62, 0x43, 0x11, 0x28, 0x87, 0x13, 0x30, 0x06, 0x70, - 0x15, 0x46, 0x51, 0x14, 0x74, 0x13, 0x53, 0x26, 0x84, 0x78, - 0x86, 0x15, 0x84, 0x18, 0x70, 0x56, 0x41, 0x33, 0x61, 0x56, - 0x28, 0x11, 0x30, 0x73, 0x82, 0x00, 0x57, 0x68, 0x61, 0x44, - 0x04, 0x64, 0x78, 0x68, 0x14, 0x02, 0x83, 0x88, 0x86, 0x88, - 0x40, 0x16, 0x81, 0x20, 0x68, 0x72, 0x67, 0x05, 0x76, 0x06, - 0x54, 0x74, 0x35, 0x71, 0x02, 0x67, 0x45, 0x24, 0x73, 0x64, - 0x87, 0x31, 0x60, 0x37, 0x04, 0x11, 0x85, 0x63, 0x40, 0x71, - 0x38, 0x46, 0x65, 0x16, 0x10, 0x85, 0x06, 0x37, 0x25, 0x53, - 0x05, 0x58, 0x45, 0x87, 0x17, 0x47, 0x78, 0x10, 0x22, 0x26, - 0x24, 0x86, 0x44, 0x63, 0x45, 0x00, 0x14, 0x77, 0x60, 0x04, - 0x54, 0x45, 0x40, 0x32, 0x45, 0x03, 0x60, 0x87, 0x05, 0x02, - 0x18, 0x22, 0x20, 0x61, 0x07, 0x36, 0x72, 0x52, 0x53, 0x65, - 0x27, 0x26, 0x37, 0x54, 0x31, 0x34, 0x22, 0x54, 0x37, 0x25, - 0x83, 0x14, 0x74, 0x75, 0x17, 0x61, 0x48, 0x74, 0x24, 0x43, - 0x80, 0x81, 0x15, 0x06, 0x88, 0x23, 0x84, 0x55, 0x20, 0x11, - 0x87, 0x83, 0x64, 0x36, 0x48, 0x88, 0x32, 0x20, 0x28, 0x54, - 0x88, 0x85, 0x35, 0x61, 0x00, 0x21, 0x01, 0x31, 0x44, 0x13, - 0x71, 0x48, 0x23, 0x47, 0x31, 0x62, 0x40, 0x18, 0x21, 0x78, - 0x34, 0x12, 0x88, 0x10, 0x76, 0x46, 0x72, 0x37, 0x70, 0x84, - 0x15, 0x41, 0x84, 0x22, 0x20, 0x22, 0x27, 0x44, 0x81, 0x03, - 0x46, 0x48, 0x26, 0x16, 0x21, 0x15, 0x31, 0x85, 0x73, 0x74, - 0x73, 0x06, 0x55, 0x21, 0x12, 0x53, 0x13, 0x34, 0x01, 0x64, - 0x40, 0x83, 0x08, 0x57, 0x24, 0x04, 0x18, 0x33, 0x70, 0x18, - 0x17, 0x06, 0x14, 0x28, 0x12, 0x58, 0x00, 0x25, 0x57, 0x20, - 0x00, 0x76, 0x73, 0x45, 0x68, 0x16, 0x60, 0x22, 0x17, 0x22, - 0x37, 0x75, 0x53, 0x48, 0x40, 0x21, 0x64, 0x27, 0x52, 0x48, - 0x53, 0x61, 0x64, 0x87, 0x57, 0x61, 0x13, 0x75, 0x80, 0x08, - 0x63, 0x33, 0x60, 0x26, 0x10, 0x25, 0x61, 0x78, 0x47, 0x78, - 0x07, 0x16, 0x00, 0x52, 0x31, 0x30, 0x63, 0x66, 0x46, 0x80, - 0x07, 0x10, 0x45, 0x11, 0x13, 0x80, 0x25, 0x61, 0x25, 0x53, - 0x80, 0x71, 0x38, 0x31, 0x47, 0x55, 0x02, 0x25, 0x50, 0x87, - 0x57, 0x35, 0x74, 0x11, 0x46, 0x44, 0x53, 0x24, 0x60, 0x33, - 0x15, 0x12, 0x77, 0x20, 0x36, 0x24, 0x70, 0x04, 0x87, 0x05, - 0x71, 0x07, 0x77, 0x36, 0x47, 0x01, 0x73, 0x61, 0x32, 0x62, - 0x28, 0x81, 0x67, 0x17, 0x38, 0x45, 0x21, 0x03, 0x24, 0x72, - 0x82, 0x64, 0x84, 0x43, 0x07, 0x11, 0x20, 0x72, 0x71, 0x04, - 0x58, 0x36, 0x22, 0x21, 0x33, 0x67, 0x55, 0x48, 0x03, 0x68, - 0x32, 0x70, 0x04, 0x63, 0x11, 0x34, 0x27, 0x82, 0x42, 0x56, - 0x28, 0x74, 0x77, 0x72, 0x18, 0x27, 0x35, 0x87, 0x03, 0x18, - 0x40, 0x32, 0x78, 0x07, 0x14, 0x43, 0x73, 0x73, 0x84, 0x63, - 0x78, 0x68, 0x03, 0x22, 0x55, 0x30, 0x18, 0x88, 0x15, 0x86, - 0x18, 0x51, 0x12, 0x42, 0x13, 0x60, 0x22, 0x44, 0x61, 0x44, - 0x35, 0x73, 0x08, 0x85, 0x53, 0x02, 0x73, 0x83, 0x25, 0x85, - 0x64, 0x78, 0x16, 0x12, 0x13, 0x63, 0x48, 0x35, 0x02, 0x71, - 0x72, 0x58, 0x12, 0x10, 0x65, 0x42, 0x22, 0x54, 0x80, 0x60, - 0x57, 0x84, 0x72, 0x76, 0x67, 0x35, 0x25, 0x14, 0x73, 0x70, - 0x48, 0x03, 0x78, 0x07, 0x74, 0x48, 0x67, 0x48, 0x01, 0x62, - 0x78, 0x05, 0x37, 0x66, 0x42, 0x45, 0x33, 0x65, 0x08, 0x70, - 0x42, 0x15, 0x72, 0x53, 0x13, 0x20, 0x14, 0x38, 0x05, 0x53, - 0x00, 0x45, 0x25, 0x20, 0x80, 0x75, 0x01, 0x65, 0x80, 0x70, - 0x61, 0x50, 0x15, 0x10, 0x77, 0x23, 0x38, 0x31, 0x21, 0x51, - 0x78, 0x11, 0x88, 0x71, 0x18, 0x06, 0x45, 0x62, 0x47, 0x35, - 0x43, 0x00, 0x52, 0x34, 0x41, 0x75, 0x18, 0x13, 0x51, 0x35, - 0x72, 0x11, 0x78, 0x17, 0x30, 0x44, 0x83, 0x25, 0x64, 0x42, - 0x65, 0x23, 0x50, 0x32, 0x85, 0x30, 0x67, 0x10, 0x70, 0x01, - 0x16, 0x62, 0x36, 0x46, 0x18, 0x53, 0x53, 0x80, 0x13, 0x65, - 0x66, 0x53, 0x61, 0x55, 0x07, 0x71, 0x34, 0x56, 0x31, 0x67, - 0x64, 0x42, 0x64, 0x41, 0x22, 0x56, 0x44, 0x67, 0x25, 0x52, - 0x08, 0x17, 0x38, 0x45, 0x76, 0x83, 0x37, 0x15, 0x76, 0x31, - 0x83, 0x47, 0x30, 0x21, 0x55, 0x73, 0x37, 0x82, 0x11, 0x56, - 0x67, 0x27, 0x23, 0x44, 0x72, 0x82, 0x10, 0x80, 0x43, 0x11, - 0x16, 0x02, 0x21, 0x40, 0x42, 0x10, 0x12, 0x74, 0x58, 0x40, - 0x74, 0x00, 0x66, 0x02, 0x85, 0x76, 0x21, 0x17, 0x83, 0x78, - 0x80, 0x40, 0x46, 0x87, 0x66, 0x24, 0x35, 0x80, 0x31, 0x77, - 0x87, 0x10, 0x47, 0x02, 0x20, 0x65, 0x43, 0x73, 0x41, 0x61, - 0x72, 0x18, 0x21, 0x52, 0x32, 0x82, 0x08, 0x82, 0x00, 0x57, - 0x52, 0x41, 0x45, 0x10, 0x51, 0x41, 0x28, 0x37, 0x72, 0x45, - 0x77, 0x10, 0x56, 0x06, 0x54, 0x30, 0x03, 0x74, 0x13, 0x56, - 0x77, 0x54, 0x04, 0x86, 0x13, 0x77, 0x81, 0x77, 0x57, 0x15, - 0x76, 0x13, 0x51, 0x75, 0x4C, 0xD3, 0x8C, 0xF8, 0x0F, 0x87, - 0x37, 0xBC, 0x26, 0x1B, 0x7A, 0x1C, 0xDC, 0x05, 0xFD, 0x9B, - 0x97, 0x8C, 0x4D, 0xE5, 0x06, 0xFF, 0x57, 0x65, 0xDC, 0xFC, - 0xBF, 0x55, 0x20, 0x8F, 0xC9, 0xAB, 0x63, 0x4C, 0x37, 0x02, - 0xB5, 0x51, 0x79, 0x6B, 0xC2, 0x02, 0x74, 0xE5, 0x74, 0x72, - 0xC4, 0x3C, 0x8F, 0xD2, 0x79, 0xCB, 0x65, 0x3C, 0xBD, 0xA6, - 0xC5, 0x19, 0xDF, 0xFC, 0x24, 0xB9, 0x91, 0x81, 0x41, 0x4D, - 0xDF, 0x2E, 0x6A, 0xBD, 0x5A, 0xC4, 0x04, 0x03, 0x7F, 0x71, - 0x7D, 0x51, 0xDD, 0x2F, 0xAE, 0x4C, 0x9A, 0xF8, 0x98, 0x11, - 0xA0, 0xCE, 0xF7, 0xDE, 0xF5, 0xC6, 0x91, 0xD3, 0xDC, 0xE7, - 0xAA, 0xD0, 0x7D, 0xDF, 0x5F, 0xF2, 0x5B, 0x55, 0x9C, 0xD6, - 0x8D, 0xC9, 0x1E, 0xC7, 0x80, 0xD9, 0xC5, 0xFA, 0x15, 0xEB, - 0xCE, 0x6B, 0x99, 0x71, 0xBD, 0xED, 0x0C, 0x24, 0x1B, 0x97, - 0x52, 0xFA, 0x54, 0xF5, 0x72, 0x48, 0x97, 0x05, 0x8B, 0x04, - 0xE5, 0xAA, 0xE0, 0xDC, 0x98, 0x13, 0xD2, 0x27, 0xB0, 0x0B, - 0x49, 0x8B, 0xA0, 0xD1, 0x2C, 0x18, 0xA5, 0xFA, 0x2A, 0x80, - 0x4B, 0xF7, 0x4B, 0x8C, 0xE0, 0xA4, 0xCD, 0xD0, 0x75, 0xE9, - 0x4A, 0x75, 0x15, 0x1B, 0xB8, 0x51, 0xD8, 0x8D, 0x1E, 0xA4, - 0xD1, 0xCD, 0x0E, 0xEE, 0xD4, 0xAA, 0x55, 0x0C, 0x6A, 0xB3, - 0xC9, 0x51, 0x66, 0x72, 0x76, 0xF4, 0xF9, 0xA4, 0xC2, 0x56, - 0x9D, 0xF9, 0x7C, 0x4C, 0x91, 0x27, 0xAC, 0xB3, 0x3E, 0x6B, - 0x2D, 0x5B, 0x84, 0xF3, 0x68, 0xD7, 0x28, 0xAE, 0xB6, 0x75, - 0x41, 0x46, 0xF2, 0x50, 0xF4, 0x20, 0x04, 0x4E, 0xB3, 0x0D, - 0xC3, 0xAE, 0xA9, 0x87, 0x9E, 0xB2, 0x05, 0xAE, 0x33, 0x76, - 0x76, 0x1A, 0x7A, 0xAB, 0xFD, 0x55, 0x77, 0x64, 0xF0, 0x0A, - 0x7C, 0x4F, 0x75, 0xE7, 0xBC, 0x09, 0x2D, 0x99, 0x4B, 0x90, - 0x13, 0x42, 0x62, 0xBD, 0x70, 0x14, 0x39, 0x23, 0x3A, 0x8A, - 0x32, 0x30, 0xEA, 0x66, 0x24, 0x85, 0xAF, 0x0B, 0xD7, 0x72, - 0xC4, 0xFC, 0x89, 0xD9, 0xB6, 0x9A, 0x1D, 0xA4, 0x10, 0x50, - 0x69, 0x98, 0x8E, 0x00, 0xA1, 0xCF, 0x94, 0x6C, 0x1B, 0x79, - 0x3A, 0xB7, 0xD8, 0x86, 0x1C, 0xD1, 0x95, 0x72, 0x0A, 0x3A, - 0xDA, 0xEF, 0x26, 0x15, 0xA5, 0xE4, 0x67, 0xD6, 0x04, 0xC5, - 0x0A, 0xBA, 0x50, 0x21, 0x9C, 0xB7, 0x1A, 0xF1, 0x1F, 0x1D, - 0x90, 0x5A, 0x6E, 0x40, 0xF8, 0xC1, 0xAB, 0xBD, 0x88, 0xA7, - 0xB8, 0x25, 0xBD, 0xCB, 0x93, 0xFA, 0x79, 0xAE, 0xAF, 0x1A, - 0xBD, 0x7B, 0xC4, 0x9F, 0x89, 0x7C, 0xFF, 0xFB, 0x0E, 0x27, - 0x32, 0x20, 0x6D, 0x47, 0x6B, 0x0E, 0x0D, 0xA1, 0x6A, 0x55, - 0x7F, 0xFD, 0x73, 0x9B, 0xC5, 0x3F, 0xF8, 0x08, 0xAA, 0xFE, - 0x0F, 0x7E, 0xAD, 0xB8, 0x13, 0x50, 0x79, 0x8D, 0x58, 0xAF, - 0xB2, 0xC6, 0x66, 0x24, 0xA8, 0x19, 0xD6, 0x90, 0x81, 0x54, - 0x92, 0x7B, 0xAF, 0xA8, 0xB8, 0x3D, 0x27, 0xD0, 0xC0, 0x08, - 0xB6, 0x45, 0x3D, 0x24, 0x46, 0xA0, 0x04, 0x8A, 0x26, 0x95, - 0xCF, 0x3F, 0x3C, 0x31, 0x43, 0x5D, 0xCA, 0x7A, 0xED, 0xF7, - 0xD3, 0xB5, 0xA0, 0xEE, 0xDC, 0x97, 0x76, 0xB3, 0x2F, 0x89, - 0x18, 0x62, 0xAC, 0x4B, 0x8B, 0xFC, 0x06, 0x1E, 0x15, 0xE5, - 0x25, 0x72, 0x46, 0xB9, 0x02, 0xD9, 0x0C, 0x38, 0xCF, 0x82, - 0x13, 0x19, 0x6E, 0x18, 0x85, 0xC6, 0x76, 0xF9, 0x10, 0xF9, - 0xCD, 0x72, 0x05, 0xED, 0x5E, 0xAE, 0xBB, 0xD2, 0xAB, 0x64, - 0x13, 0x3E, 0x9F, 0x20, 0xCF, 0x8C, 0xC0, 0x37, 0x71, 0x38, - 0x22, 0x49, 0x38, 0x9C, 0x23, 0xCB, 0x0B, 0xC3, 0xE8, 0xE5, - 0xEB, 0x31, 0x61, 0x07, 0xFE, 0x2A, 0xAC, 0xDE, 0x90, 0x35, - 0x24, 0xEB, 0x6B, 0xB6, 0x34, 0x51, 0x9C, 0xE2, 0x7D, 0xD0, - 0x8B, 0x38, 0xDB, 0x81, 0x7B, 0x24, 0x7B, 0x69, 0x84, 0x1D, - 0x17, 0x9F, 0x64, 0x63, 0x6F, 0x3F, 0x43, 0xFC, 0xFE, 0x07, - 0x72, 0x66, 0x84, 0xE3, 0xCD, 0x4F, 0x25, 0x70, 0x81, 0x64, - 0x66, 0x2C, 0xA8, 0x35, 0x11, 0x1B, 0xF3, 0x03, 0x1B, 0x5B, - 0xDC, 0xFB, 0x7D, 0xAD, 0x14, 0x11, 0xC8, 0xB1, 0x0C, 0x7E, - 0x36, 0x79, 0x34, 0x79, 0x1A, 0x88, 0x8A, 0x8F, 0xF6, 0x66, - 0xB4, 0x95, 0xD4, 0xA1, 0x02, 0xF9, 0x1D, 0x26, 0x53, 0x7A, - 0x34, 0x00, 0x36, 0x0E, 0xE7, 0xFB, 0x7A, 0x60, 0xF9, 0xC3, - 0xCF, 0x30, 0xCB, 0xF0, 0x27, 0xB5, 0xD6, 0xCF, 0x15, 0x33, - 0x53, 0x88, 0x7C, 0x50, 0x07, 0xF4, 0x27, 0xE0, 0x40, 0x47, - 0xFE, 0x86, 0x0E, 0xFF, 0x07, 0x5F, 0x55, 0xB8, 0x3B, 0xAA, - 0xFB, 0xB0, 0x6B, 0x98, 0x47, 0x59, 0xB8, 0x33, 0xAA, 0x67, - 0x6B, 0x36, 0xEB, 0x76, 0x43, 0xAF, 0x31, 0x52, 0x62, 0x3D, - 0x7F, 0x64, 0x6A, 0xFC, 0x36, 0x92, 0x96, 0xF8, 0xD9, 0xE7, - 0x13, 0x77, 0x1D, 0xD0, 0xFB, 0x0D, 0x70, 0x29, 0x61, 0x52, - 0x82, 0xF4, 0xE4, 0xA7, 0x08, 0x47, 0x4C, 0x67, 0xEE, 0x36, - 0xD1, 0x1C, 0x18, 0x8B, 0xF1, 0x2D, 0xE2, 0x47, 0x16, 0x4D, - 0x1F, 0x05, 0xC6, 0x4E, 0xFB, 0x35, 0x51, 0x3A, 0x9E, 0xF9, - 0xE0, 0x1E, 0xC1, 0x64, 0x21, 0x0B, 0x8A, 0xF0, 0x1D, 0x32, - 0x78, 0x18, 0xF2, 0xB3, 0xB5, 0xBD, 0x66, 0x6B, 0xAD, 0x92, - 0x4F, 0x22, 0xDC, 0xB9, 0xCC, 0xF4, 0x98, 0x22, 0x99, 0xF6, - 0x3D, 0xC6, 0x8F, 0x28, 0x77, 0x60, 0x34, 0xD0, 0x73, 0xF5, - 0x4D, 0x9F, 0x6C, 0x5D, 0x94, 0xC2, 0x3D, 0x19, 0xCD, 0xC2, - 0x18, 0x41, 0x9B, 0x5F, 0x32, 0x2D, 0x5E, 0x3D, 0x92, 0xBE, - 0x26, 0x39, 0x85, 0x50, 0xE6, 0xE2, 0x49, 0x17, 0x19, 0xD3, - 0x57, 0xAF, 0x45, 0x85, 0x74, 0xF7, 0x16, 0x35, 0x0A, 0x94, - 0x54, 0x64, 0x45, 0xD5, 0x31, 0x51, 0x49, 0x8F, 0xA4, 0x4C, - 0x33, 0xBB, 0x62, 0x59, 0x6B, 0x08, 0xBD, 0x1C, 0xDD, 0x38, - 0x93, 0x22, 0x0B, 0xCF, 0x9B, 0x23, 0x87, 0x30, 0xA2, 0xA0, - 0x6D, 0x97, 0x2D, 0xD7, 0x2B, 0x16, 0x88, 0x72, 0x01, 0x9A, - 0x51, 0xBA, 0x56, 0xCE, 0xDC, 0xDD, 0xF9, 0x87, 0x41, 0xC8, - 0x44, 0xF1, 0xA2, 0x20, 0x9A, 0x11, 0x44, 0x13, 0xDF, 0x49, - 0x04, 0x85, 0x4C, 0x01, 0x46, 0x3E, 0xD6, 0xB8, 0xE2, 0xC2, - 0x2E, 0xED, 0xA4, 0x07, 0x29, 0x89, 0xA2, 0x46, 0x23, 0x98, - 0xA5, 0xEF, 0x59, 0x1A, 0xE7, 0x67, 0x64, 0x59, 0xF7, 0x2C, - 0x5B, 0x30, 0x29, 0x57, 0xE3, 0xDE, 0x5C, 0x84, 0x1B, 0x8F, - 0x3E, 0xB3, 0x5B, 0xF5, 0x0C, 0x6E, 0xB1, 0x4E, 0x2F, 0xB6, - 0xB6, 0x5B, 0x29, 0xCD, 0xBB, 0xB8, 0xC9, 0xF0, 0x39, 0xF9, - 0xB9, 0x11, 0x47, 0xEF, 0xF8, 0x90, 0xE0, 0x0F, 0x91, 0x70, - 0x97, 0xB4, 0xFC, 0xFD, 0xB5, 0x69, 0x8C, 0x61, 0x9A, 0x26, - 0xD2, 0xC9, 0x47, 0x67, 0xB7, 0xDB, 0x73, 0x11, 0xA3, 0xC1, - 0x3B, 0x4E, 0x5F, 0x60, 0xDA, 0x73, 0x39, 0x9B, 0xD4, 0x3D, - 0x24, 0xA6, 0x8A, 0xB5, 0x56, 0x5D, 0xBD, 0x27, 0xDE, 0x6C, - 0x67, 0xA1, 0x4A, 0x77, 0xB7, 0x44, 0x1D, 0x28, 0x44, 0xA0, - 0xA3, 0xF2, 0xEB, 0x3A, 0x9F, 0xE5, 0x5C, 0xF5, 0xE3, 0xFE, - 0xD0, 0xC3, 0xCA, 0x2A, 0x1A, 0x72, 0x86, 0xB3, 0x4E, 0x9D, - 0x25, 0x0B, 0x4C, 0xFF, 0x45, 0xB7, 0xDE, 0xE8, 0x8C, 0x0A, - 0x06, 0xED, 0x30, 0x26, 0x8F, 0xA1, 0xBF, 0x74, 0x22, 0x3D, - 0x50, 0x39, 0x17, 0xA9, 0x6B, 0x7C, 0xAC, 0xA0, 0x6A, 0xEA, - 0x14, 0x95, 0x5F, 0xAD, 0x3C, 0xB1, 0x4E, 0xE1, 0x30, 0x2F, - 0x4A, 0x77, 0x72, 0xC1, 0x1F, 0x4C, 0x91, 0x6B, 0xCF, 0x81, - 0x46, 0xAF, 0x2D, 0xEC, 0x59, 0x9E, 0x99, 0xD9, 0x60, 0x23, - 0x95, 0x08, 0x0D, 0xBB, 0xFD, 0xEC, 0x2A, 0xF7, 0x7B, 0x73, - 0x53, 0xF3, 0x88, 0xB7, 0xAF, 0x51, 0x69, 0xD5, 0x08, 0xFC, - 0xCC, 0x03, 0xD3, 0x61, 0x5C, 0xDD, 0x39, 0x56, 0x6B, 0xE4, - 0xEE, 0x1F, 0x0A, 0xD6, 0x1A, 0x84, 0x65, 0x45, 0x0C, 0x0A, - 0x34, 0xDE, 0x96, 0x24, 0xBB, 0x74, 0xF4, 0xB7, 0xE5, 0x2F, - 0xB5, 0x1F, 0x85, 0x9D, 0xD7, 0xEA, 0xB3, 0x33, 0xBE, 0xCF, - 0x19, 0x45, 0xCE, 0xF9, 0x13, 0xF5, 0xFD, 0x65, 0x5D, 0xBB, - 0xDB, 0x64, 0x94, 0xAC, 0xB8, 0x39, 0xAF, 0x9B, 0x56, 0xE4, - 0x5C, 0x95, 0x85, 0xFD, 0xB3, 0xF8, 0x3C, 0x98, 0xD3, 0x58, - 0xCE, 0xAB, 0x09, 0x0E, 0xA7, 0x42, 0x9B, 0x16, 0xA7, 0x63, - 0xEB, 0xB8, 0x7C, 0x01, 0xA2, 0xD4, 0x3C, 0x2B, 0xA7, 0xA3, - 0x52, 0x8C, 0x08, 0xA5, 0xA9, 0xAF, 0x63, 0x07, 0xDA, 0x45, - 0x86, 0x91, 0x64, 0xE6, 0x41, 0x75, 0x78, 0x46, 0x6F, 0xB9, - 0xB4, 0xEA, 0x6A, 0xDD, 0xC7, 0x1A, 0x1F, 0xC0, 0x8A, 0x00, - 0x81, 0x70, 0x74, 0x37, 0xC8, 0x84, 0x3F, 0xA8, 0xC9, 0xC1, - 0xC1, 0x60, 0x2B, 0x25, 0x9B, 0x66, 0x5F, 0x73, 0x15, 0x51, - 0xE2, 0xE4, 0x49, 0x5B, 0xEE, 0x20, 0xC8, 0x18, 0xE7, 0x65, - 0xED, 0x29, 0xEA, 0x96, 0x85, 0xB5, 0x63, 0xFB, 0xA6, 0x23, - 0x22, 0xB7, 0x4F, 0x6E, 0xE3, 0xF2, 0x9C, 0x01, 0x23, 0x7A, - 0xB9, 0x16, 0x2A, 0x93, 0xAF, 0x4F, 0xEA, 0x05, 0x15, 0x84, - 0x46, 0x32, 0x2F, 0x99, 0xB8, 0x78, 0x20, 0x78, 0x93, 0xC9, - 0x42, 0x6D, 0xBC, 0x70, 0xCE, 0x88, 0x6F, 0x12, 0x92, 0x3F, - 0xDE, 0xFB, 0xDE, 0x8E, 0xD3, 0x69, 0x09, 0x54, 0x7D, 0x0A, - 0xE1, 0x93, 0x3D, 0x10, 0x04, 0xDE, 0x66, 0x9D, 0x2D, 0xAD, - 0xA4, 0x53, 0x4C, 0xF6, 0xFC, 0x08, 0xE4, 0x58, 0x05, 0x09, - 0x78, 0x09, 0xE6, 0xF3, 0xEE, 0x83, 0xC2, 0xD0, 0xA9, 0x04, - 0xE6, 0xAC, 0x30, 0xD7, 0x34, 0x52, 0xEB, 0xCD, 0x1A, 0x7E, - 0xB9, 0xCF, 0x18, 0x68, 0x16, 0xB9, 0x9A, 0x18, 0xDA, 0xC8, - 0xE3, 0x1C, 0xF0, 0x9A, 0x2E, 0x64, 0x28, 0xBE, 0xA4, 0x9F, - 0xCB, 0xC0, 0x53, 0xE6, 0x2A, 0x88, 0xB5, 0xE7, 0xF3, 0x6F, - 0x46, 0x1C, 0xBA, 0xAD, 0x76, 0x17, 0x85, 0xAE, 0x95, 0x13, - 0x7B, 0xF9, 0xB8, 0xD3, 0x08, 0x6A, 0x38, 0x63, 0x67, 0xD8, - 0x8B, 0x51, 0x8F, 0x49, 0x44, 0xB4, 0x10, 0xB8, 0x74, 0x38, - 0xDD, 0x17, 0xEA, 0x52, 0x67, 0xB2, 0xCC, 0xC9, 0x77, 0xDD, - 0x44, 0x2E, 0xDF, 0x03, 0xC7, 0xF4, 0x87, 0xF4, 0xBC, 0x6F, - 0x94, 0x9F, 0x58, 0xDB, 0xE2, 0x09, 0xA1, 0x4C, 0xCA, 0x89, - 0x9D, 0x04, 0x5A, 0xAB, 0xDF, 0x8B, 0x82, 0x3F, 0x0E, 0xF2, - 0xE7, 0xBD, 0x9A, 0x16, 0x3A, 0xAF, 0x72, 0x18, 0xB9, 0x47, - 0xB3, 0xBC, 0xFE, 0x84, 0x43, 0x92, 0x98, 0xF4, 0x3A, 0x49, - 0x3A, 0x26, 0xB7, 0xF3, 0x37, 0x54, 0x06, 0xD8, 0x92, 0x09, - 0xE6, 0xFE, 0x9A, 0xDB, 0x68, 0x16, 0x6F, 0x5D, 0x5D, 0x8E, - 0xBB, 0xFC, 0xAC, 0x5A, 0x72, 0xFE, 0x0B, 0xEB, 0xDB, 0x90, - 0xA4, 0x6C, 0x37, 0x1A, 0x8B, 0x5A, 0xD8, 0xE9, 0xF6, 0x15, - 0xFC, 0x54, 0x1B, 0x95, 0xE3, 0xAE, 0x08, 0x46, 0xB5, 0xFB, - 0xC5, 0x66, 0xC5, 0x79, 0x17, 0x9D, 0x5C, 0x45, 0xE5, 0x4E, - 0xFF, 0xA2, 0x86, 0xD7, 0x4F, 0xD4, 0x1D, 0x17, 0xA3, 0x77, - 0x00, 0x54, 0x70, 0xDF, 0x12, 0xCA, 0xD6, 0x71, 0x05, 0x54, - 0xFA, 0x47, 0x96, 0x38, 0x2D, 0x4D, 0x70, 0x3E, 0x2E, 0x40, - 0xE7, 0x52, 0x32, 0x66, 0x4D, 0x92, 0x1B, 0x76, 0x66, 0xF1, - 0xD4, 0x38, 0x8B, 0x76, 0x47, 0xE1, 0x66, 0xDE, 0xA2, 0x06, - 0xD7, 0xA7, 0x96, 0x52, 0xED, 0xC9, 0xF3, 0xD6, 0x99, 0xDF, - 0x2F, 0x98, 0xC5, 0xBF, 0x16, 0x95, 0x80, 0x41, 0xE4, 0xEB, - 0x8B, 0x16, 0xEF, 0x6A, 0x76, 0x84, 0xE7, 0x5F, 0x6C, 0xBD, - 0x1D, 0x2A, 0x74, 0x08, 0x5B, 0x4E, 0xCA, 0xE1, 0xF5, 0xD0, - 0x42, 0x2C, 0x03, 0x9B, 0x80, 0xBD, 0x05, 0x5F, 0x87, 0xF0, - 0x84, 0x08, 0x96, 0xBE, 0xAC, 0xBF, 0xF1, 0x8F, 0x51, 0x69, - 0x9E, 0xC2, 0xE9, 0x96, 0x9D, 0x97, 0xCD, 0x56, 0x32, 0x29, - 0xC8, 0x53, 0xC2, 0x1A, 0x5A, 0xD3, 0xDA, 0x31, 0x94, 0x09, - 0x35, 0x08, 0x75, 0x27, 0x66, 0xC5, 0x10, 0x5F, 0xD1, 0x94, - 0x12, 0x03, 0x8A, 0x1B, 0x69, 0x81, 0xEB, 0xBE, 0xBC, 0x6B, - 0xE4, 0xB9, 0x84, 0x65, 0x7D, 0xE3, 0xFE, 0xFB, 0x45, 0x58, - 0x31, 0xF3, 0x66, 0x13, 0x64, 0xB2, 0xBD, 0xBC, 0xF6, 0xA5, - 0x07, 0x07, 0x8A, 0xC8, 0x43, 0xCA, 0x38, 0x94, 0x70, 0xC0, - 0x25, 0xDA, 0xC6, 0xD9, 0x74, 0x5A, 0x60, 0xE3, 0x9D, 0x74, - 0x6C, 0x72, 0xF5, 0xAF, 0xD3, 0xD7, 0xF5, 0xBD, 0x17, 0x02, - 0xE5, 0x17, 0xEC, 0xBD, 0xCB, 0x5D, 0x1A, 0x8F, 0x39, 0x31, - 0x7E, 0x4B, 0x1F, 0x1A, 0x87, 0xE2, 0x69, 0x65, 0x07, 0x42, - 0x6D, 0xD2, 0x2D, 0x04, 0x52, 0x51, 0xA7, 0xF2, 0x23, 0xC6, - 0x01, 0xD1, 0x47, 0x5F, 0x42, 0x44, 0x2A, 0x88, 0x5E, 0xBB, - 0x98, 0x5A, 0x34, 0xBB, 0x0E, 0x05, 0xA7, 0x1D, 0x7E, 0xFB, - 0x3E, 0x85, 0xD8, 0x74, 0x70, 0xE8, 0x71, 0xC2, 0x31, 0x80, - 0x37, 0xF9, 0x15, 0xA4, 0xC1, 0xFC, 0x9B, 0x68, 0x2B, 0x54, - 0x9B, 0x37, 0x9C, 0xE7, 0x62, 0x80, 0x20, 0x1E, 0x27, 0x78, - 0xBF, 0x11, 0xC4, 0x86, 0xAC, 0x7B, 0x34, 0x57, 0x76, 0x86, - 0x77, 0x15, 0x51, 0x7C, 0xDC, 0x32, 0xDF, 0x48, 0xB9, 0xC6, - 0x63, 0xC6, 0x9A, 0xDE, 0x5E, 0x9D, 0xAB, 0x4A, 0x92, 0xEE, - 0x0C, 0x10, 0x7E, 0xB5, 0x33, 0x17, 0xF6, 0x0C, 0x8D, 0x26, - 0x89, 0xCD, 0x2B, 0xB8, 0x49, 0x4A, 0x4D, 0x5D, 0x66, 0x38, - 0x86, 0x42, 0x37, 0xC5, 0x1B, 0xE7, 0x78, 0x90, 0x21, 0xAE, - 0x8F, 0xE7, 0x0C, 0x01, 0xB9, 0x31, 0x6A, 0x50, 0x1A, 0x2B, - 0xDA, 0xC2, 0x99, 0xCB, 0xEB, 0xF9, 0xAE, 0x91, 0x8B, 0xB7, - 0x08, 0x01, 0x1E, 0xCC, 0x9E, 0x20, 0x05, 0xEC, 0x45, 0x21, - 0xBE, 0xDE, 0xFE, 0x06, 0x7D, 0x92, 0x9C, 0xE7, 0x47, 0xD9, - 0x85, 0x63, 0xC3, 0xBB, 0x38, 0x15, 0x2D, 0x94, 0xCA, 0xAF, - 0xCF, 0xCA, 0x1D, 0x53, 0x1A, 0xBD, 0x23, 0xF1, 0x87, 0x99, - 0x24, 0xF3, 0x16, 0xE9, 0x7F, 0xBE, 0x00, 0x8A, 0x61, 0xA7, - 0x65, 0xF7, 0xA9, 0x53, 0x2A, 0x29, 0x20, 0x3E, 0x0B, 0xCF, - 0x12, 0x69, 0x22, 0x84, 0x27, 0x5D, 0x1C, 0xC8, 0x45, 0xA1, - 0xA5, 0x5A, 0xB0, 0xDB, 0x95, 0x5D, 0xF7, 0xCE, 0xAC, 0x98, - 0x44, 0x3B, 0xE1, 0x27, 0x9A, 0x93, 0x5D, 0x2B, 0x8A, 0x20, - 0xB1, 0x82, 0x2C, 0xDD, 0xB8, 0xCC, 0xFA, 0x77, 0x0F, 0xA7, - 0x80, 0x00, 0x87, 0x54, 0x1C, 0xCC, 0x0B, 0x1E, 0xF6, 0x52, - 0x89, 0x03, 0x65, 0x83, 0xF1, 0x97, 0x4E, 0x81, 0x99, 0xE1, - 0xDD, 0x73, 0x30, 0x31, 0xEC, 0xA7, 0xD5, 0x76, 0x28, 0xC3, - 0xCE, 0x29, 0x30, 0x7B, 0xB1, 0x27, 0x3F, 0xC4, 0x6D, 0x54, - 0xAF, 0xE2, 0x84, 0xEA, 0xF5, 0x91, 0xBD, 0xB9, 0x6C, 0x4E, - 0x98, 0x0F, 0xFB, 0xDE, 0x7C, 0x32, 0xF8, 0xED, 0xEF, 0xD0, - 0xE9, 0xA3, 0x57, 0xC0, 0x91, 0x06, 0x4C, 0x43, 0x3F, 0x32, - 0x21, 0xB5, 0xF2, 0x11, 0x5A, 0xDF, 0xFC, 0x7E, 0x91, 0x10, - 0xC0, 0x4D, 0xD4, 0x4E, 0xA8, 0x38, 0xD6, 0xE0, 0xB6, 0x27, - 0x38, 0x63, 0xF2, 0xD3, 0xFD, 0x68, 0x4C, 0xDD, 0x76, 0xA9, - 0x89, 0xCE, 0xBE, 0x7C, 0xAD, 0x45, 0x4C, 0x8C, 0x24, 0xCC, - 0x32, 0x66, 0x3A, 0x1A, 0x45, 0xDA, 0x47, 0x5C, 0x4C, 0xC6, - 0x8A, 0x9A, 0xC3, 0x99, 0xFB, 0x4C, 0x94, 0xE2, 0x20, 0xD7, - 0xE4, 0x37, 0x22, 0x99, 0x32, 0x6F, 0xFB, 0x1C, 0xE5, 0x9B, - 0xB5, 0xFC, 0xBD, 0xD2, 0xA1, 0xDD, 0x66, 0xD5, 0x47, 0x2F, - 0x6A, 0xAA, 0x50, 0xF5, 0xE8, 0x1A, 0xDC, 0x74, 0x50, 0x6A, - 0x92, 0x23, 0x93, 0xED, 0xB0, 0x58, 0x61, 0x7D, 0xB6, 0x5C, - 0x22, 0x7B, 0x54, 0x75, 0xF0, 0x69, 0xD4, 0x27, 0x0B, 0x70, - 0x3F, 0xBB, 0x76, 0x63, 0xB3, 0x1D, 0x7E, 0x33, 0x96, 0xD6, - 0x84, 0x2D, 0x28, 0x4F, 0x97, 0x65, 0xC9, 0x95, 0xCF, 0x30, - 0xBA, 0xEA, 0x08, 0xF5, 0xC6, 0x24, 0x45, 0x20, 0x85, 0x67, - 0x9F, 0x34, 0x37, 0x72, 0x44, 0x17, 0x98, 0x5F, 0xD0, 0xCE, - 0xA8, 0x6E, 0x0E, 0x50, 0x22, 0x14, 0xE1, 0x6B, 0xCB, 0xA5, - 0x12, 0x2A, 0x36, 0xF1, 0x6E, 0x81, 0x5C, 0x5A, 0x77, 0x4F, - 0xD7, 0xF9, 0xCE, 0x7A, 0xC9, 0x30, 0x2C, 0x1E, 0x7E, 0xFC, - 0x24, 0xCB, 0xE4, 0x53, 0xC3, 0x4A, 0x03, 0xED, 0xD5, 0x77, - 0xC6, 0x55, 0xEB, 0xA2, 0xB4, 0x92, 0x35, 0xE3, 0x20, 0xDA, - 0xD2, 0x58, 0xE2, 0xCC, 0xC4, 0x4E, 0xBB, 0xE3, 0x8F, 0x75, - 0xB1, 0xDB, 0x97, 0x15, 0x86, 0x43, 0xE5, 0xD4, 0x4F, 0x44, - 0x3F, 0x20, 0xE3, 0xB9, 0xA5, 0xFB, 0x3F, 0x36, 0xC9, 0x9C, - 0xEF, 0x8C, 0xD1, 0x46, 0x67, 0x16, 0xB6, 0xA6, 0x24, 0x8A, - 0xE9, 0xD7, 0x29, 0x4B, 0x5F, 0x7C, 0x06, 0xEF, 0xD7, 0xBB, - 0x88, 0xCB, 0x2C, 0xFB, 0x85, 0x19, 0x9F, 0x97, 0x74, 0xFE, - 0x76, 0x46, 0x44, 0x1E, 0xAD, 0xF3, 0x62, 0xD2, 0xAA, 0x24, - 0x37, 0xD0, 0x1E, 0xF3, 0xCB, 0x68, 0xE3, 0x17, 0xFF, 0x81, - 0x90, 0xA3, 0xD6, 0x28, 0xE6, 0xCE, 0x6D, 0x99, 0xF4, 0x2D, - 0xC6, 0xAE, 0x40, 0x52, 0x32, 0xE9, 0xC1, 0xC6, 0x79, 0x5C, - 0xF7, 0x69, 0x29, 0x0C, 0x75, 0x9F, 0x48, 0x57, 0x75, 0x1F, - 0x2F, 0x71, 0x9F, 0x24, 0x90, 0x14, 0xAE, 0xDC, 0x75, 0x2E, - 0x5E, 0xDD, 0x85, 0xE5, 0x6C, 0xC4, 0x72, 0x58, 0xF0, 0x35, - 0xDC, 0xFE, 0x03, 0xB7, 0x2F, 0xBD, 0xC3, 0x8A, 0xA3, 0x2C, - 0x62, 0xE0, 0xCD, 0x37, 0xFA, 0x9E, 0x11, 0xC0, 0x1D, 0xEF, - 0xB0, 0x58, 0x58, 0x12, 0xAF, 0x25, 0x6D, 0x75, 0x0D, 0x2F, - 0xBC, 0x89, 0xE9, 0x2E, 0x1E, 0x58, 0x64, 0x35, 0xA8, 0x90, - 0xC2, 0x61, 0x4D, 0xCE, 0x96, 0xC5, 0xF2, 0x37, 0xBD, 0xB8, - 0xDE, 0xB4, 0x0E, 0xEB, 0xDD, 0xED, 0xE6, 0x47, 0x24, 0xE6, - 0x36, 0xC9, 0x22, 0xD3, 0xE7, 0x1A, 0xEF, 0x9E, 0x16, 0x89, - 0xB9, 0x5C, 0xF4, 0x3B, 0x09, 0x7E, 0x9B, 0x87, 0x7F, 0xD6, - 0x84, 0x06, 0xCA, 0x0E, 0xA8, 0x54, 0x79, 0xCF, 0x02, 0xF6, - 0x1B, 0x57, 0x34, 0x9D, 0x97, 0x00, 0x05, 0x8B, 0x75, 0xA3, - 0x5C, 0x7C, 0xBA, 0xA7, 0x51, 0x85, 0xBC, 0xE6, 0xAC, 0xD9, - 0xD4, 0x31, 0xB3, 0x3A, 0xBD, 0x82, 0xC8, 0x60, 0x74, 0x46, - 0xA9, 0x2F, 0xC2, 0x29, 0x08, 0x59, 0x6B, 0x14, 0x19, 0x19, - 0x39, 0x7F, 0x8B, 0xA2, 0x2A, 0xFD, 0xE3, 0x09, 0x72, 0x50, - 0x74, 0x88, 0xEE, 0xC6, 0xED, 0x28, 0x37, 0xCD, 0xA9, 0xBA, - 0x2E, 0xFE, 0x07, 0xDF, 0x5E, 0xF9, 0x18, 0xB4, 0x0E, 0xBF, - 0x9C, 0x1C, 0xCA, 0x84, 0xBA, 0x62, 0xB9, 0xA2, 0x96, 0x76, - 0xB6, 0xB7, 0x77, 0x9C, 0xBE, 0x0C, 0xF8, 0xA5, 0xEF, 0x74, - 0xB1, 0xC2, 0x85, 0xCD, 0xD1, 0x25, 0xD5, 0xFC, 0xFB, 0x2C, - 0xC7, 0xD6, 0x2F, 0x30, 0x3F, 0x10, 0xEA, 0xA2, 0x99, 0xC4, - 0x22, 0x58, 0xB3, 0xC4, 0x46, 0x3C, 0x41, 0xE9, 0xE9, 0xA0, - 0x39, 0x6C, 0x09, 0x89, 0xE3, 0xAE, 0x4E, 0x35, 0xAB, 0x27, - 0x71, 0x43, 0xEB, 0xA7, 0xFA, 0x68, 0xA8, 0x42, 0x49, 0x3C, - 0x53, 0x70, 0x35, 0xCA, 0x14, 0xB7, 0x1D, 0xF8, 0x7E, 0x65, - 0x05, 0x33, 0xE3, 0x5A, 0x86, 0xCD, 0xA5, 0x18, 0x02, 0x24, - 0x23, 0xAD, 0x52, 0x6A, 0x47, 0x13, 0x14, 0x95, 0xD2, 0xF1, - 0xE1, 0x6F, 0x61, 0x70, 0x4F, 0xDC, 0x1A, 0x03, 0x0E, 0xD7, - 0x07, 0xBD, 0x84, 0x43, 0x65, 0x76, 0x9F, 0xFB, 0x1E, 0x89, - 0xEB, 0x92, 0x5E, 0xDE, 0x5B, 0xAA, 0x54, 0xEE, 0x0A, 0xF5, - 0x4A, 0x79, 0x46, 0xDA, 0xC1, 0xEC, 0x2F, 0xBC, 0xDD, 0xE5, - 0x61, 0xFA, 0xED, 0xB6, 0x97, 0x9C, 0x90, 0xD8, 0xF3, 0x2E, - 0x04, 0xCF, 0xB5, 0x89, 0x74, 0xC2, 0xD1, 0x70, 0xE0, 0x0F, - 0x53, 0x14, 0x09, 0x6A, 0x19, 0x5A, 0x65, 0xAC, 0xAA, 0x3C, - 0x25, 0x79, 0x43, 0x27, 0x47, 0x18, 0x19, 0x7A, 0x74, 0xD7, - 0x73, 0x43, 0xBD, 0x50, 0x1F, 0x68, 0xAF, 0xDF, 0x3E, 0x2A, - 0xC4, 0xDC, 0x6F, 0x85, 0x2A, 0xBC, 0x0F, 0x39, 0x4B, 0x97, - 0x6D, 0x2D, 0x87, 0x5F, 0x9A, 0x07, 0x82, 0xC7, 0x69, 0xB9, - 0xF2, 0xEF, 0xE3, 0x3C, 0x3C, 0x74, 0xB2, 0xFD, 0x81, 0x6F, - 0xC3, 0xAC, 0x93, 0x22, 0x49, 0xB5, 0x73, 0x5C, 0x58, 0x6E, - 0x5F, 0x7A, 0x6B, 0x91, 0x02, 0x25, 0x3B, 0xC8, 0x24, 0xD7, - 0xEF, 0xC8, 0x10, 0xD7, 0x54, 0xD4, 0xA7, 0xC1, 0x88, 0x77, - 0xDD, 0xCD, 0x3A, 0x92, 0xE5, 0x1D, 0xA1, 0x33, 0x10, 0xA4, - 0xF6, 0xB4, 0x43, 0xA4, 0xDB, 0x77, 0x4C, 0x91, 0x7C, 0xED, - 0xDD, 0xC7, 0xB9, 0x5A, 0xB4, 0x2A, 0x6C, 0x78, 0x54, 0xCA, - 0xBD, 0x16, 0x0C, 0x8C, 0x68, 0xE8, 0xBC, 0xDE, 0x65, 0x2F, - 0xAF, 0xEF, 0x09, 0xDC, 0x7C, 0x17, 0x7D, 0x05, 0xF7, 0xB1, - 0x8D, 0x09, 0x94, 0xDC, 0xF2, 0xAE, 0xF4, 0x21, 0x54, 0xF9, - 0x3E, 0xB0, 0x2A, 0x73, 0xFE, 0x9C, 0x51, 0xEB, 0x1E, 0x7B, - 0xFE, 0x65, 0xCB, 0x53, 0x80, 0x5B, 0xD2, 0x05, 0xA1, 0xE9, - 0xCB, 0x75, 0x60, 0x46, 0x08, 0x07, 0x83, 0x27, 0x4E, 0xD4, - 0xBF, 0x70, 0x83, 0xDE, 0xA9, 0xB4, 0x22, 0x55, 0xF1, 0x5F, - 0x91, 0x88, 0x4A, 0x43, 0xC1, 0xBF, 0x0A, 0xEF, 0xA7, 0xFF, - 0xE5, 0xA6, 0x50, 0xDD, 0xFD, 0x6E, 0x22, 0xFF, 0xC1, 0x55, - 0x82, 0x0B, 0x42, 0x86, 0x42, 0xA7, 0x91, 0xD3, 0x62, 0x69, - 0xB2, 0x8D, 0x11, 0xC5, 0xB8, 0x4F, 0xBF, 0x4D, 0xFE, 0x37, - 0x12, 0x1F, 0xBF, 0xDE, 0xA5, 0x86, 0xAD, 0xC7, 0x2C, 0x7F, - 0x27, 0x01, 0xB0, 0xA1, 0xED, 0x7D, 0xCE, 0x33, 0x68, 0x97, - 0x2E, 0xA4, 0xF4, 0xEE, 0xA4, 0x36, 0x67, 0xE3, 0xAB, 0x89, - 0xF8, 0xCE, 0xF7, 0x01, 0xB1, 0x83, 0xFB, 0x54, 0xAA, 0x69, - 0x05, 0x76, 0x24, 0xD9, 0x76, 0x9F, 0xA3, 0x9C, 0x52, 0x8C, - 0x2E, 0x27, 0xB9, 0xA3, 0x6E, 0xE2, 0xC0, 0x02, 0x09, 0xC6, - 0x18, 0xAD, 0x42, 0x88, 0x6B, 0x2F, 0x5D, 0xB4, 0xF7, 0xC6, - 0xB4, 0x18, 0xB7, 0x88, 0x0B, 0x81, 0x2C, 0x25, 0xCE, 0xC3, - 0x7E, 0x9E, 0xAE, 0xBB, 0x35, 0x3C, 0xEC, 0x78, 0x46, 0x8F, - 0x03, 0x16, 0x5E, 0x5B, 0x08, 0x63, 0xFB, 0xBC, 0x78, 0x75, - 0xAB, 0x07, 0x1A, 0xA7, 0x96, 0x41, 0xCD, 0xDC, 0x3B, 0x59, - 0xDB, 0x02, 0xBE, 0x42, 0x09, 0xF5, 0x87, 0x96, 0x5D, 0x63, - 0xC9, 0x8E, 0x06, 0xA2, 0xFF, 0xCE, 0xCD, 0xF3, 0xDE, 0x93, - 0x79, 0x63, 0x92, 0xD2, 0xB9, 0x1D, 0x76, 0x7E, 0x4F, 0x36, - 0x2A, 0x89, 0x7B, 0x93, 0xC1, 0x35, 0x0A, 0x83, 0x8B, 0xD6, - 0xF4, 0xEA, 0x2A, 0x72, 0xA9, 0xE7, 0x6A, 0x77, 0x43, 0x14, - 0x49, 0x5B, 0x01, 0xD9, 0xE7, 0x72, 0x15, 0xD9, 0x9C, 0xBE, - 0x87, 0x90, 0x2A, 0x7F, 0x68, 0x02, 0x1C, 0xB5, 0xA1, 0xC6, - 0x7B, 0x24, 0x49, 0xBF, 0x8E, 0x3D, 0xE0, 0xBA, 0x1C, 0x78, - 0x0A, 0x7C, 0x69, 0x82, 0xA1, 0x2F, 0xB6, 0x52, 0xC5, 0x25, - 0xD8, 0x9D, 0x4B, 0x38, 0xAA, 0xBA, 0xF7, 0x4C, 0xC4, 0xC2, - 0xAE, 0xED, 0x6C, 0x28, 0x1C, 0x76, 0xA9, 0x96, 0x08, 0xAB, - 0xC4, 0x15, 0xBC, 0x3E, 0xD7, 0xCC, 0xC4, 0xA2, 0xD4, 0x93, - 0xD1, 0x3A, 0xF4, 0x2F, 0x17, 0xDB, 0x1C, 0xBD, 0xCA, 0x0D, - 0x5C, 0xF9, 0x69, 0x32, 0xAF, 0xC5, 0x27, 0x37, 0xFC, 0x1B, - 0xBB, 0x8A, 0x5D, 0x41, 0xA9, 0xC7, 0xE7, 0xC5, 0x2E, 0x78, - 0xE3, 0x7A, 0x5A, 0x25, 0x49, 0x2A, 0x06, 0x3D, 0x15, 0x58, - 0x56, 0xFB, 0x66, 0xEC, 0x30, 0x7D, 0xF4, 0x02, 0xF3, 0x53, - 0x3D, 0x0D, 0xDD, 0xFE, 0xB5, 0x66, 0xB0, 0xD0, 0xAA, 0x0E, - 0x6A, 0x76, 0xA6, 0xAB, 0x87, 0x14, 0xFB, 0x47, 0xAC, 0x26, - 0x53, 0xA9, 0x2C, 0xF3, 0xD5, 0xA6, 0x4F, 0xF0, 0x3A, 0x7E, - 0x78, 0xC5, 0x69, 0x1F, 0xB7, 0xDC, 0xC4, 0xE8, 0xD7, 0x44, - 0x7B, 0xB2, 0xC4, 0x50, 0x68, 0xF4, 0x33, 0xFC, 0x65, 0x0D, - 0xDC, 0xCD, 0x71, 0xCB, 0x9C, 0x65, 0x3B, 0x72, 0xB7, 0x19, - 0x70, 0x45, 0xA7, 0x36, 0xA4, 0xCF, 0xE7, 0x6F, 0xC8, 0xF9, - 0x67, 0x52, 0x22, 0x8F, 0x8F, 0x64, 0x89, 0xD3, 0x3E, 0x50, - 0xCC, 0xBE, 0x2B, 0xF3, 0x0A, 0x22, 0x96, 0x33, 0x56, 0x30, - 0x27, 0x3F, 0x42, 0xDE, 0x69, 0xA3, 0x63, 0xDE, 0x41, 0x94, - 0x02, 0x97, 0x9D, 0x58, 0xF3, 0x27, 0xE3, 0xFE, 0x94, 0x10, - 0x20, 0x55, 0x52, 0xD2, 0x46, 0xFB, 0x5E, 0x8C, 0xDF, 0x71, - 0x9B, 0xBF, 0x33, 0x79, 0x7C, 0xF3, 0x78, 0xA3, 0x75, 0x84, - 0x6C, 0x13, 0xEF, 0xC0, 0x43, 0x82, 0xAC, 0xF0, 0x97, 0x7D, - 0x2A, 0xBC, 0xA3, 0xB7, 0xCD, 0x4C, 0x99, 0xB9, 0xB1, 0xE9, - 0x38, 0x5C, 0x97, 0xB3, 0xC0, 0x2C, 0xBD, 0x6F, 0xF7, 0x14, - 0x26, 0x3A, 0x27, 0x31, 0x52, 0x81, 0x04, 0x88, 0xE6, 0xD8, - 0x43, 0x21, 0x78, 0x87, 0x7C, 0x7E, 0x28, 0x26, 0x4F, 0x93, - 0x9D, 0x7B, 0x2D, 0x02, 0x6E, 0x91, 0x74, 0xD9, 0x2C, 0xF7, - 0x43, 0xD8, 0x66, 0x81, 0x91, 0x21, 0xA1, 0xEE, 0xBC, 0x78, - 0x71, 0x80, 0x78, 0x54, 0x16, 0x59, 0x37, 0xB8, 0x69, 0xD3, - 0x49, 0x40, 0xAB, 0x03, 0x47, 0x36, 0xFD, 0x5D, 0x60, 0x57, - 0x8F, 0xBE, 0xA8, 0xA0, 0x21, 0x38, 0x43, 0xA9, 0x5C, 0x9F, - 0xAD, 0xD8, 0xAE, 0x97, 0xA3, 0x0F, 0xFC, 0xE4, 0x4A, 0xCF, - 0x9F, 0xE9, 0x75, 0x3D, 0x60, 0x91, 0x55, 0x5C, 0x0A, 0xB9, - 0x18, 0xEF, 0xD4, 0x08, 0x58, 0x06, 0x64, 0xA1, 0x45, 0xA7, - 0x5D, 0x3F, 0x13, 0x87, 0x49, 0x76, 0x8B, 0x1B, 0x54, 0x9C, - 0x61, 0x05, 0xC6, 0x2C, 0xED, 0x24, 0x1B, 0x7F, 0x9E, 0x9B, - 0x17, 0xBB, 0x84, 0xD8, 0xE2, 0x55, 0x69, 0x0E, 0xCF, 0xB2, - 0xC3, 0x61, 0x35, 0x0D, 0x86, 0xD7, 0x81, 0x75, 0x43, 0x98, - 0x29, 0xDF, 0x19, 0x9C, 0xFB, 0xC0, 0xC0, 0x5A, 0x7E, 0xF7, - 0xC6, 0x86, 0xEF, 0x6E, 0xBA, 0x26, 0x1D, 0x07, 0xF9, 0xC0, - 0x1F, 0xC0, 0x8E, 0x41, 0x8F, 0x1A, 0xE3, 0x51, 0xE2, 0xD7, - 0xCA, 0x28, 0x7D, 0x7A, 0xA7, 0x57, 0xA3, 0x2D, 0x98, 0x56, - 0x32, 0x9D, 0xC0, 0xF8, 0x23, 0x1D, 0x2C, 0xF6, 0x64, 0x1E, - 0x70, 0x33, 0xD4, 0x8F, 0xF9, 0xB0, 0xF4, 0x57, 0x7F, 0xD1, - 0x9A, 0xD4, 0x1A, 0x7E, 0xB6, 0x07, 0xAA, 0x54, 0x19, 0x0D, - 0x5D, 0xB8, 0x26, 0x45, 0x1B, 0x38, 0x14, 0x20, 0xFB, 0xAA, - 0x09, 0x71, 0xAF, 0x96, 0xB1, 0x17, 0xF3, 0x45, 0xA3, 0xA6, - 0x90, 0x52, 0x3C, 0x3B, 0x43, 0x9A, 0x8D, 0xE3, 0xB1, 0xC5, - 0xE4, 0x32, 0x6C, 0xE0, 0x17, 0x98, 0x43, 0x34, 0x54, 0x10, - 0x17, 0x82, 0x27, 0xE8, 0x8F, 0x99, 0x88, 0x98, 0x26, 0x70, - 0x19, 0xD1, 0x2D, 0x23, 0x02, 0x5F, 0x44, 0x71, 0x2A, 0xF6, - 0x48, 0x83, 0x34, 0x3A, 0x37, 0x11, 0x9C, 0xA1, 0xCE, 0xF0, - 0xD7, 0x6E, 0xF7, 0x2B, 0xA3, 0xFC, 0x07, 0x40, 0x64, 0x1A, - 0xF1, 0xF6, 0xF8, 0x90, 0x21, 0x1C, 0x0E, 0x85, 0xAA, 0xC1, - 0xF7, 0x16, 0xF5, 0x4D, 0x27, 0x8E, 0x91, 0x4E, 0x84, 0x19, - 0xDB, 0x8C, 0xEA, 0x00, 0xEA, 0xA6, 0x86, 0x18, 0x2C, 0x8B, - 0x46, 0x5F, 0xED, 0x61, 0x38, 0x28, 0x31, 0x4A, 0x1A, 0x12, - 0x19, 0x6C, 0x2D, 0x43, 0x0E, 0xD0, 0xDD, 0x4B, 0xFA, 0xA0, - 0x39, 0xC2, 0x4B, 0x31, 0xD9, 0x56, 0xB4, 0x9E, 0xB5, 0xD1, - 0x79, 0xA3, 0x35, 0xC7, 0xAF, 0xFD, 0x0E, 0x11, 0xC7, 0x0F, - 0x55, 0x1D, 0xCA, 0x71, 0xD1, 0x37, 0x3B, 0xC2, 0x72, 0xA0, - 0xDB, 0xEE, 0xA0, 0xF2, 0x28, 0xF4, 0x77, 0x34, 0x7D, 0x9F, - 0xE8, 0x38, 0xD0, 0xF1, 0xEB, 0x51, 0x95, 0x93, 0x5D, 0x7B, - 0x4F, 0xE7, 0x1A, 0xD5, 0xA1, 0xF1, 0xF1, 0x85, 0xF7, 0x58, - 0x5C, 0x2C, 0x49, 0xAF, 0xDC, 0x93, 0xFE, 0x73, 0x0F, 0xC8, - 0xC8, 0x26, 0x1B, 0xDE, 0xD8, 0xA6, 0x8A, 0x44, 0xB4, 0x2B, - 0x67, 0xBD, 0x8E, 0xFF, 0xA5, 0x8C, 0x18, 0x95, 0xD3, 0x02, - 0x7F, 0x28, 0x93, 0xAE, 0x84, 0x1E, 0xB0, 0x5C, 0x70, 0x57, - 0x1C, 0xFF, 0x75, 0x95, 0xBF, 0xAD, 0x95, 0xF3, 0x3C, 0x19, - 0xA0, 0x7A, 0x0F, 0x62, 0x65, 0xF0, 0x0F, 0x18, 0x1E, 0x48, - 0xB3, 0x85, 0x5D, 0x11, 0x47, 0xC9, 0x95, 0x75, 0xBE, 0xFA, - 0x2D, 0x56, 0x35, 0xD0, 0x7A, 0x75, 0x68, 0xEA, 0x7D, 0x01, - 0x9E, 0xD5, 0x28, 0x9E, 0x80, 0x09, 0xE5, 0xE9, 0xF8, 0xD3, - 0x11, 0xA6, 0xC7, 0x5E, 0xD6, 0x38, 0x8B, 0x96, 0x7A, 0xFB, - 0xD8, 0x27, 0xD4, 0x47, 0x6B, 0x50, 0xAB, 0x21, 0x4E, 0xFB, - 0xC2, 0xA1, 0x8C, 0xB7, 0x50, 0xE2, 0xF7, 0xC3, 0x4C, 0x66, - 0x04, 0x28, 0x17, 0x5D, 0x6F, 0x48, 0x39, 0x9A, 0x0B, 0x4A, - 0xB0, 0x75, 0xDF, 0xA9, 0x6E, 0xE0, 0x72, 0x20, 0x68, 0xC5, - 0x9C, 0xDB, 0x41, 0xA4, 0xF9, 0xA4, 0xF5, 0x1D, 0xDD, 0x89, - 0x83, 0x11, 0xDD, 0x3A, 0xA4, 0x76, 0x38, 0x62, 0x75, 0x4C, - 0x5D, 0xC7, 0xF5, 0x99, 0x75, 0xFB, 0xB7, 0x87, 0xB8, 0x77, - 0x2B, 0x45, 0xEF, 0xC5, 0xE5, 0x10, 0xD9, 0x6B, 0x4C, 0x72, - 0x4B, 0x42, 0x13, 0x71, 0x3C, 0x9C, 0x2C, 0x2E, 0xFB, 0xA2, - 0x3A, 0xCD, 0x2B, 0x83, 0x12, 0xA7, 0xF3, 0xA5, 0xCE, 0x4B, - 0x77, 0x2B, 0xF5, 0x71, 0xA0, 0x1A, 0x40, 0x7F, 0xED, 0x97, - 0x4B, 0x0C, 0xA0, 0x55, 0x6B, 0x69, 0x73, 0x52, 0x47, 0x6A, - 0x20, 0xCB, 0xEE, 0xE0, 0xBE, 0x97, 0x8F, 0x05, 0xE0, 0x84, - 0x4A, 0x6E, 0x40, 0xCC, 0x02, 0x2C, 0xA8, 0x45, 0xD4, 0x6B, - 0xD4, 0xCD, 0x41, 0x29, 0xBE, 0x99, 0x3B, 0x51, 0x0F, 0x9C, - 0x70, 0x75, 0x83, 0x3D, 0x42, 0xCF, 0xA9, 0x02, 0xF3, 0x68, - 0x3C, 0x96, 0xE1, 0x36, 0x46, 0xB7, 0x86, 0x16, 0x03, 0x2C, - 0xBB, 0x71, 0x21, 0xBF, 0x13, 0x52, 0x03, 0x42, 0x31, 0xE3, - 0xA3, 0x26, 0xEE, 0xD7, 0x86, 0x78, 0xDA, 0x9E, 0x9A, 0x50, - 0xD1, 0x9C, 0x5B, 0xB7, 0xEB, 0xCF, 0x0A, 0x6D, 0x10, 0xA0, - 0xAB, 0x8C, 0x65, 0x4B, 0xFA, 0x9E, 0xAC, 0x0B, 0x66, 0x56, - 0xC7, 0x5D, 0x85, 0x88, 0x53, 0x1B, 0xC2, 0x37, 0xCC, 0x94, - 0x2E, 0xE1, 0xB1, 0xF7, 0xCC, 0x1F, 0x59, 0x24, 0xEC, 0x1A, - 0x27, 0xFA, 0x8D, 0xE5, 0x86, 0x9E, 0x3F, 0x21, 0xDA, 0x15, - 0xAE, 0xC7, 0x6C, 0xFB, 0x17, 0x0D, 0xF5, 0xCB, 0xE3, 0xB8, - 0x36, 0x95, 0x0F, 0xBD, 0x84, 0x19, 0x1D, 0xF5, 0x4F, 0x17, - 0xB8, 0x71, 0x9C, 0x0E, 0x3D, 0xD8, 0xFD, 0x9B, 0xD4, 0x0D, - 0x2D, 0x16, 0x5D, 0x75, 0xE7, 0x25, 0x94, 0x3D, 0xD3, 0x0C, - 0x07, 0x3D, 0x04, 0x46, 0xC8, 0x8F, 0x65, 0x06, 0xC7, 0x11, - 0xB2, 0xAB, 0x41, 0x5E, 0x96, 0x0C, 0x68, 0x76, 0x7D, 0x6D, - 0xB8, 0xB5, 0x27, 0x01, 0x2C, 0x00, 0xC2, 0xA0, 0x40, 0xB8, - 0xF7, 0xC6, 0x39, 0x56, 0xCF, 0x25, 0x56, 0xB3, 0x10, 0x04, - 0xE9, 0xC3, 0x85, 0x47, 0xE8, 0x6E, 0xC7, 0x89, 0xFE, 0x80, - 0x9A, 0x50, 0x9E, 0xBD, 0xF3, 0x2E, 0x5E, 0x96, 0x0A, 0xA8, - 0xB7, 0x6C, 0x5B, 0x9E, 0x32, 0x1E, 0x75, 0x68, 0x5E, 0x74, - 0x88, 0xFC, 0xC5, 0x3D, 0xB9, 0x21, 0x0A, 0xAD, 0x6D, 0xF6, - 0xBE, 0x2D, 0x9A, 0x8A, 0xA5, 0x2A, 0x40, 0x3C, 0xF6, 0x4C, - 0xFE, 0x18, 0xE3, 0x44, 0x7A, 0x5F, 0x31, 0x1A, 0xEE, 0x95, - 0x07, 0x96, 0xC1, 0x27, 0x7F, 0x64, 0x4E, 0xF0, 0x19, 0x2D, - 0x36, 0x33, 0x5D, 0x23, 0xC9, 0xC2, 0x36, 0x91, 0x22, 0xC9, - 0x58, 0x8C, 0xE4, 0xF1, 0x19, 0xD0, 0xBF, 0x51, 0xAA, 0x14, - 0x4C, 0x15, 0x4A, 0x93, 0xF3, 0x16, 0x6A, 0x21, 0xBE, 0xDE, - 0xA5, 0x4C, 0x84, 0xC5, 0x65, 0x06, 0xA7, 0x11, 0xDC, 0x00, - 0x5F, 0x0F, 0xF1, 0xDA, 0xA2, 0x11, 0xAB, 0x64, 0xE0, 0x1F, - 0x1A, 0x65, 0x32, 0xA7, 0x69, 0x65, 0xAF, 0x64, 0x95, 0x90, - 0xF1, 0xA5, 0xFA, 0x32, 0x4C, 0x59, 0x61, 0x87, 0x3D, 0x94, - 0x82, 0x7E, 0xE4, 0x04, 0x7B, 0x8A, 0xCD, 0x54, 0x00, 0x2A, - 0xC5, 0xC3, 0xB7, 0x2F, 0x8A, 0xA8, 0x19, 0x39, 0x93, 0x53, - 0x3E, 0xEB, 0xE7, 0x8F, 0xF7, 0xCF, 0xDA, 0x8A, 0x4E, 0xAB, - 0x91, 0x3D, 0xA3, 0x40, 0x55, 0x64, 0xE7, 0x48, 0x90, 0x03, - 0xE5, 0xE6, 0x03, 0xE8, 0x2A, 0x23, 0x78, 0x6F, 0xCA, 0xDE, - 0x7C, 0x6E, 0x56, 0x5B, 0xC8, 0x6D, 0x8C, 0x2F, 0xC8, 0x6C, - 0x7D, 0xD8, 0x60, 0x43, 0x8C, 0xF3, 0xE9, 0x9E, 0x70, 0x73, - 0xAC, 0x85, 0xB4, 0xA3, 0x29, 0x86, 0x88, 0x60, 0x6D, 0xDD, - 0x21, 0x07, 0x09, 0x8B, 0xFB, 0xA1, 0x67, 0xA5, 0xDA, 0x9D, - 0xCC, 0x2E, 0xE3, 0xBE, 0xAE, 0x06, 0x0E, 0x41, 0x4E, 0xBE, - 0x5F, 0xE4, 0x93, 0x81, 0xE8, 0x06, 0xAA, 0x2C, 0xC9, 0x1B, - 0x1C, 0x5A, 0x9E, 0x01, 0xEF, 0xFF, 0x82, 0x84, 0xD9, 0x2B, - 0x05, 0x20, 0x0D, 0xE1, 0x14, 0x6C, 0x0A, 0x85, 0x16, 0x2E, - 0x79, 0xA3, 0x64, 0xBF, 0xFC, 0x89, 0xB8, 0xFD, 0xB0, 0xC8, - 0x39, 0x9A, 0x83, 0x1B, 0x74, 0x41, 0x7C, 0xEA, 0xFD, 0x5F, - 0x83, 0x19 +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY + +static const unsigned char bench_dilithium_level2_pubkey[] = { + 0xea, 0x05, 0x24, 0x0d, 0x80, 0x72, 0x25, 0x55, 0xf4, 0x5b, + 0xc2, 0x13, 0x8b, 0x87, 0x5d, 0x31, 0x99, 0x2f, 0x1d, 0xa9, + 0x41, 0x09, 0x05, 0x76, 0xa7, 0xb7, 0x5e, 0x8c, 0x44, 0xe2, + 0x64, 0x79, 0xa0, 0xec, 0x1f, 0x24, 0xb6, 0xc8, 0x05, 0x5b, + 0xc1, 0x18, 0xb0, 0xb7, 0xcf, 0x8c, 0x60, 0x67, 0x6b, 0x81, + 0x44, 0x27, 0xb6, 0x0e, 0xfd, 0x9b, 0xc3, 0xcb, 0x52, 0x31, + 0xfa, 0xc9, 0x34, 0x8d, 0x22, 0x1e, 0x07, 0x9d, 0x96, 0x6a, + 0x63, 0x83, 0x5c, 0xd7, 0x83, 0x2d, 0x7f, 0x48, 0x64, 0x79, + 0xca, 0xb4, 0x9f, 0xa2, 0x02, 0xb7, 0x86, 0x1d, 0x0e, 0xc7, + 0xf9, 0x6c, 0x07, 0xc0, 0x35, 0x6a, 0x34, 0x79, 0x7c, 0xb8, + 0x0f, 0xed, 0x98, 0x50, 0xfb, 0x51, 0xe0, 0x36, 0x44, 0x4c, + 0xc6, 0x35, 0xa2, 0xbb, 0x55, 0xb0, 0x5c, 0x39, 0x08, 0x02, + 0x20, 0x35, 0x5c, 0x56, 0x6d, 0x2e, 0xb9, 0xef, 0x21, 0x26, + 0x87, 0x87, 0x85, 0x8a, 0x32, 0xb5, 0xa7, 0x68, 0x70, 0x3a, + 0xfd, 0x0d, 0x21, 0x48, 0x91, 0xa3, 0x29, 0xc1, 0x2a, 0x38, + 0xe5, 0x26, 0x31, 0x1f, 0x42, 0xde, 0x0b, 0x25, 0xff, 0x1d, + 0x6b, 0xb4, 0xe0, 0x5d, 0x2d, 0xcf, 0x44, 0xd5, 0x7d, 0xc4, + 0xf6, 0x95, 0xf2, 0x06, 0x4f, 0x83, 0x88, 0x9d, 0x1e, 0xeb, + 0x1c, 0x09, 0x45, 0x62, 0x67, 0x3d, 0xff, 0x51, 0x47, 0xe8, + 0xbc, 0x9b, 0x03, 0x1f, 0xc7, 0x72, 0x65, 0xce, 0xa8, 0x8c, + 0xc2, 0xa0, 0xc2, 0xbd, 0x5b, 0x7c, 0x17, 0x16, 0x8b, 0x72, + 0xfa, 0xb1, 0xbd, 0xdf, 0x49, 0xd6, 0xa1, 0x00, 0x65, 0xbe, + 0x82, 0xe7, 0x68, 0xc7, 0xe7, 0xbc, 0xc2, 0xa4, 0xdb, 0xaa, + 0xcc, 0xea, 0x41, 0x52, 0x7f, 0x56, 0xb4, 0x68, 0x1f, 0x92, + 0x96, 0x0f, 0xce, 0xd4, 0xd0, 0x87, 0x4c, 0x4a, 0x73, 0xb5, + 0x6c, 0xd4, 0x69, 0x55, 0x15, 0x47, 0xdc, 0x94, 0x7f, 0xd2, + 0x54, 0x5e, 0xb2, 0x90, 0xc2, 0x47, 0xe4, 0xf5, 0xde, 0x8b, + 0x9b, 0xc6, 0x5d, 0x50, 0x95, 0x60, 0xe0, 0xf0, 0xa7, 0x4e, + 0xe0, 0xcd, 0x41, 0x09, 0xef, 0xb3, 0x3d, 0x90, 0x5c, 0x77, + 0x54, 0xec, 0x9e, 0x5d, 0x8a, 0xe7, 0x09, 0x5c, 0xc9, 0x58, + 0x0c, 0xd0, 0x42, 0x35, 0xd2, 0x14, 0x59, 0x38, 0x69, 0xad, + 0xf9, 0xb5, 0xbf, 0x8a, 0x8e, 0x33, 0xd8, 0x5e, 0x7a, 0x55, + 0xd0, 0x53, 0x15, 0x40, 0x4e, 0xc5, 0x86, 0xd7, 0x8f, 0x5f, + 0x2f, 0x55, 0x82, 0xc2, 0x4f, 0x16, 0xe5, 0xea, 0x1c, 0xbc, + 0xff, 0x5e, 0x1f, 0x39, 0x46, 0x70, 0x54, 0x7a, 0x3a, 0x27, + 0x16, 0x1a, 0x2b, 0x6c, 0xd2, 0xb7, 0x80, 0xd3, 0xd1, 0x9d, + 0x25, 0x59, 0xed, 0xe6, 0x51, 0xb1, 0xf2, 0xad, 0x7e, 0x51, + 0x78, 0x14, 0x2b, 0x19, 0xae, 0x64, 0x72, 0x0f, 0xd8, 0x18, + 0x79, 0x8e, 0x66, 0x88, 0xd3, 0xa4, 0xa3, 0xc3, 0x76, 0x21, + 0xcb, 0xe4, 0x79, 0x5e, 0x95, 0x74, 0xe3, 0x31, 0x18, 0x79, + 0xed, 0xc7, 0xe7, 0xfb, 0x86, 0x48, 0x1b, 0x7b, 0x75, 0x5b, + 0x7f, 0x7c, 0x82, 0xc5, 0xab, 0x11, 0xb4, 0x5d, 0x59, 0x6f, + 0x78, 0xb2, 0xa5, 0x39, 0xc6, 0x63, 0x38, 0x6c, 0xeb, 0x50, + 0x06, 0x14, 0x76, 0xf0, 0xe8, 0xfb, 0x11, 0x95, 0x1f, 0x9d, + 0x9c, 0xa6, 0xe1, 0xe2, 0x0d, 0xa3, 0x66, 0xfc, 0x20, 0x83, + 0x50, 0x0e, 0x53, 0x75, 0xb5, 0x12, 0xf4, 0xdf, 0x31, 0x46, + 0x83, 0xac, 0x5b, 0xf3, 0x99, 0xa6, 0xd1, 0x7b, 0x2b, 0xc5, + 0xdc, 0x71, 0x07, 0x27, 0x33, 0x35, 0x34, 0xf5, 0x30, 0x19, + 0xc1, 0x3b, 0xba, 0x8a, 0xaf, 0x7e, 0x49, 0x93, 0x48, 0x5b, + 0x38, 0xc0, 0xbc, 0x2e, 0xc7, 0x59, 0x1b, 0xd9, 0xf5, 0xcc, + 0x86, 0xf5, 0x7b, 0x4d, 0xd7, 0x39, 0xa7, 0xa2, 0x56, 0x20, + 0x48, 0x98, 0x7d, 0x4f, 0x75, 0x56, 0x9b, 0xb8, 0x95, 0x45, + 0x17, 0xf3, 0x86, 0x3d, 0x97, 0x0a, 0x49, 0x1b, 0xca, 0xff, + 0x20, 0xc0, 0x24, 0x2c, 0x51, 0xc2, 0x0a, 0x3c, 0xbf, 0x07, + 0x60, 0x1c, 0x88, 0x85, 0x9b, 0x85, 0x2d, 0x4a, 0xfe, 0x5a, + 0x1c, 0x90, 0xf5, 0x90, 0x12, 0xd3, 0x03, 0x3c, 0x8c, 0x2e, + 0x95, 0x4a, 0x47, 0x76, 0x0f, 0x1f, 0x5d, 0x9e, 0xed, 0xc5, + 0x64, 0xc4, 0x9b, 0xbf, 0x86, 0xc5, 0x63, 0x84, 0x33, 0x00, + 0xf1, 0x26, 0x18, 0x21, 0xf3, 0x88, 0x1a, 0x08, 0x18, 0x6d, + 0x2f, 0xef, 0xd5, 0xeb, 0x2f, 0x69, 0xc8, 0x6e, 0x92, 0x34, + 0xfc, 0x72, 0x3d, 0x9a, 0xa7, 0x9e, 0x51, 0xfb, 0x56, 0xe3, + 0xdc, 0xf4, 0x8f, 0x9b, 0x6d, 0x0d, 0x2a, 0xec, 0x66, 0x12, + 0x26, 0x35, 0xbd, 0x61, 0xc2, 0x67, 0x19, 0xf5, 0x7e, 0xa1, + 0x67, 0xa2, 0x9c, 0x3b, 0x67, 0xb0, 0xc2, 0x51, 0x6a, 0x37, + 0x7c, 0x48, 0xe9, 0x4b, 0xb9, 0xa3, 0x38, 0x2f, 0xfc, 0xde, + 0xb4, 0x7c, 0xda, 0x52, 0x84, 0x0b, 0xb0, 0xd9, 0x08, 0xe9, + 0x7a, 0x4a, 0x6f, 0x79, 0x29, 0x3d, 0xc4, 0x5c, 0x78, 0xee, + 0x63, 0xb6, 0x96, 0x68, 0xd9, 0x82, 0x4e, 0xc1, 0x1b, 0x6f, + 0x52, 0xf5, 0xb3, 0xfb, 0xe8, 0xc4, 0x2a, 0x07, 0xc6, 0x3b, + 0x85, 0x0d, 0xf4, 0xbf, 0xb0, 0x6b, 0xfb, 0xce, 0x1d, 0xb4, + 0xbf, 0x63, 0x0b, 0x91, 0x67, 0xc4, 0xa3, 0x06, 0xa4, 0xaf, + 0x6c, 0xd3, 0xe5, 0x8b, 0x87, 0x4e, 0x64, 0x9c, 0xb1, 0xf3, + 0x70, 0x7c, 0x68, 0x43, 0x46, 0x13, 0x46, 0xee, 0x27, 0x75, + 0x12, 0x45, 0x42, 0xde, 0xa5, 0x8d, 0xcf, 0xf7, 0x09, 0x87, + 0xa8, 0x80, 0x3d, 0xb6, 0x45, 0xee, 0x41, 0x2d, 0x7c, 0x45, + 0x01, 0x9d, 0xaa, 0x78, 0xa8, 0x10, 0xa4, 0xfd, 0xb5, 0x5f, + 0xee, 0x0f, 0x77, 0xba, 0x73, 0xff, 0x49, 0xdc, 0xfa, 0x39, + 0xd6, 0xa3, 0x6f, 0x25, 0xb9, 0x63, 0x2c, 0x92, 0xc5, 0xdf, + 0xfb, 0xba, 0x89, 0xf9, 0xfa, 0x94, 0x5b, 0x6f, 0x5a, 0x4d, + 0x1c, 0xe4, 0xc9, 0x10, 0xf9, 0xa0, 0xe8, 0xc4, 0xcb, 0x55, + 0x1a, 0xdb, 0x56, 0x5f, 0x8e, 0x91, 0x03, 0x23, 0xca, 0xb0, + 0x1f, 0xef, 0xb8, 0x6c, 0x13, 0x5a, 0x99, 0x25, 0xf0, 0x49, + 0xa9, 0x5a, 0x45, 0xf7, 0xfd, 0x1a, 0xc2, 0x71, 0x06, 0xe3, + 0x2d, 0x25, 0x64, 0xb0, 0x52, 0x12, 0x03, 0x62, 0xc7, 0xb6, + 0xf9, 0xdc, 0x1f, 0x78, 0xff, 0x8b, 0xfa, 0xde, 0x7f, 0x71, + 0xa6, 0x35, 0x3e, 0xac, 0x20, 0x54, 0x94, 0xa7, 0x2e, 0x9d, + 0x47, 0x17, 0x4b, 0xad, 0x92, 0xb3, 0x14, 0x26, 0x8c, 0x5a, + 0xd0, 0x16, 0x4b, 0x22, 0xe9, 0x0c, 0x79, 0x6b, 0x8e, 0xac, + 0x0d, 0x12, 0xf5, 0x66, 0x8e, 0x82, 0x1a, 0x44, 0xf3, 0xe9, + 0x56, 0x5a, 0xcd, 0x1c, 0x1b, 0x81, 0x7b, 0x63, 0x59, 0xfe, + 0xc8, 0xc0, 0xe3, 0xda, 0x16, 0x6b, 0x6f, 0x0d, 0xba, 0x0e, + 0x47, 0x12, 0x86, 0x9e, 0xf0, 0x3b, 0x4d, 0x87, 0x3b, 0xf2, + 0x75, 0x73, 0x2d, 0xdf, 0xca, 0x76, 0x0b, 0xbd, 0xe7, 0xb7, + 0x74, 0x24, 0xf3, 0xc6, 0xe6, 0x75, 0x3f, 0x8b, 0x6a, 0xd9, + 0xad, 0xed, 0xc0, 0x70, 0x04, 0x1e, 0x0b, 0x8e, 0x8b, 0x7f, + 0xea, 0xbc, 0x39, 0x6b, 0x8a, 0x44, 0xa6, 0x9a, 0x2d, 0x0d, + 0x8c, 0x21, 0x60, 0x09, 0xd2, 0x4a, 0xe0, 0x62, 0xcf, 0xfa, + 0xe8, 0x9b, 0x35, 0x6f, 0x23, 0x2f, 0xb5, 0x65, 0x08, 0x60, + 0x92, 0x15, 0xd0, 0x5b, 0x63, 0xcc, 0x65, 0x05, 0xd1, 0xef, + 0x0f, 0x7e, 0x1b, 0xb3, 0x8e, 0xc6, 0x12, 0x85, 0xc9, 0x82, + 0x53, 0x79, 0x2e, 0x80, 0x5f, 0x0c, 0x7b, 0xc7, 0x1c, 0x83, + 0x41, 0x06, 0xd8, 0x41, 0xc9, 0xe7, 0xb9, 0x4b, 0xa1, 0x61, + 0xc6, 0x86, 0x67, 0xf5, 0x10, 0xf7, 0x34, 0x0d, 0x39, 0x9e, + 0x2b, 0x5f, 0x19, 0x06, 0x02, 0xa5, 0x02, 0x23, 0x71, 0xc2, + 0x12, 0x65, 0xcc, 0x81, 0x06, 0xfd, 0x8d, 0x09, 0x68, 0x37, + 0x06, 0x3b, 0xff, 0xc4, 0x24, 0xb3, 0x1f, 0xd6, 0xe6, 0x8f, + 0x9c, 0x74, 0x2c, 0x5e, 0xc5, 0xf4, 0xe9, 0xeb, 0xca, 0xd3, + 0x04, 0x5b, 0x92, 0x9e, 0x5c, 0x1a, 0x1d, 0xa1, 0xa7, 0x34, + 0xd2, 0x05, 0xae, 0xdb, 0x3d, 0x71, 0x10, 0x6e, 0x30, 0xd9, + 0xa3, 0x44, 0xa0, 0xbd, 0x9e, 0x7b, 0xb5, 0x12, 0x8a, 0x12, + 0x07, 0x60, 0xd7, 0x1f, 0x92, 0xe6, 0xfe, 0x04, 0xa9, 0x3e, + 0x62, 0x64, 0x00, 0x5f, 0x7c, 0x7b, 0x34, 0x09, 0xeb, 0x4a, + 0x18, 0x9e, 0x77, 0x72, 0x3a, 0x31, 0x1a, 0x62, 0x2a, 0xb5, + 0xcb, 0x4e, 0x53, 0xce, 0xad, 0x8b, 0x5a, 0x20, 0x4f, 0xd7, + 0x3e, 0x16, 0xf8, 0x10, 0xe2, 0xae, 0xbd, 0x3f, 0x02, 0xa9, + 0x18, 0xa0, 0x01, 0x18, 0x84, 0x95, 0x22, 0x2e, 0x93, 0x76, + 0x44, 0x4e, 0x11, 0x7b, 0x03, 0x51, 0x50, 0x19, 0x79, 0xe7, + 0xbb, 0x5c, 0x7b, 0xca, 0x74, 0xb4, 0x25, 0x26, 0xdb, 0x66, + 0xaa, 0x0b, 0x21, 0x07, 0xfb, 0x7a, 0x96, 0x10, 0x7d, 0x99, + 0xa9, 0x16, 0xcb, 0x0e, 0xba, 0x63, 0xab, 0x95, 0xfc, 0x5a, + 0xbe, 0xa6, 0x7f, 0xd8, 0xb4, 0xcd, 0x7c, 0xc5, 0xd0, 0xb1, + 0x1b, 0x48, 0x40, 0xfb, 0xe6, 0x2f, 0x2b, 0x94, 0xfe, 0x68, + 0xa2, 0xc4, 0x36, 0xd9, 0xcd, 0xc1, 0x93, 0x6d, 0xef, 0x39, + 0x5e, 0x43, 0x30, 0x5a, 0x2e, 0x66, 0xb6, 0xf2, 0xed, 0x9a, + 0x8d, 0x12, 0xdf, 0x5c, 0xae, 0xad, 0x16, 0x12, 0x7e, 0x81, + 0x82, 0x91, 0x7d, 0x2b, 0x12, 0xe9, 0x96, 0xb8, 0xb7, 0x42, + 0xcb, 0x1f, 0xf8, 0xd1, 0xfd, 0x83, 0x7a, 0xe4, 0x36, 0x1d, + 0x04, 0x27, 0x4c, 0xe5, 0xbd, 0x75, 0x24, 0xf7, 0xbd, 0xb6, + 0x6a, 0x68, 0x4e, 0x2c, 0x1b, 0x56, 0x3e, 0x60, 0xa4, 0x42, + 0xca, 0x7a, 0x54, 0xe5, 0x06, 0xe3, 0xda, 0x05, 0xf7, 0x77, + 0x36, 0x8b, 0x81, 0x26, 0x99, 0x92, 0x42, 0xda, 0x45, 0xb1, + 0xfe, 0x4b, +}; +static const int sizeof_bench_dilithium_level2_pubkey = + sizeof(bench_dilithium_level2_pubkey); + +#endif /* !WOLFSSL_DILITHIUM_NO_VERIFY */ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +static const unsigned char bench_dilithium_level3_key[] = { + 0x15, 0xc9, 0xe5, 0x53, 0x2f, 0xd8, 0x1f, 0xb4, 0xa3, 0x9f, + 0xae, 0xad, 0xb3, 0x10, 0xd0, 0x72, 0x69, 0xd3, 0x02, 0xf3, + 0xdf, 0x67, 0x5a, 0x31, 0x52, 0x19, 0xca, 0x39, 0x27, 0x77, + 0x61, 0x6d, 0x72, 0xdd, 0x85, 0x06, 0xf6, 0x94, 0x0a, 0x57, + 0x52, 0xcd, 0xac, 0x83, 0x4a, 0xe5, 0xbe, 0xa4, 0x30, 0x79, + 0x9e, 0xc6, 0xd6, 0x04, 0xc8, 0x73, 0xdc, 0x5e, 0x41, 0x75, + 0x2f, 0xac, 0x76, 0x57, 0x03, 0x08, 0x46, 0xcb, 0xaf, 0x4c, + 0x6a, 0x4f, 0x20, 0x18, 0xb3, 0x2e, 0x11, 0x54, 0xb5, 0x94, + 0xe6, 0x6f, 0x76, 0xf6, 0xb9, 0x73, 0x9a, 0x07, 0x73, 0xe8, + 0x90, 0xd1, 0x04, 0xda, 0xc5, 0x97, 0xb9, 0x52, 0x51, 0xc8, + 0xc9, 0xcc, 0x87, 0x29, 0xa1, 0xde, 0x79, 0x9b, 0xf8, 0x7f, + 0x80, 0x3f, 0xfd, 0xb3, 0x24, 0xa5, 0xba, 0xf5, 0xd6, 0xd4, + 0x07, 0xbd, 0xa7, 0x1b, 0xd0, 0xe1, 0xd0, 0x43, 0x14, 0x52, + 0x27, 0x03, 0x33, 0x76, 0x00, 0x67, 0x30, 0x23, 0x76, 0x34, + 0x72, 0x02, 0x41, 0x62, 0x12, 0x43, 0x86, 0x30, 0x18, 0x28, + 0x46, 0x27, 0x45, 0x20, 0x88, 0x33, 0x54, 0x10, 0x03, 0x81, + 0x44, 0x50, 0x06, 0x44, 0x56, 0x30, 0x37, 0x38, 0x38, 0x46, + 0x03, 0x85, 0x01, 0x86, 0x43, 0x80, 0x78, 0x28, 0x83, 0x55, + 0x37, 0x44, 0x80, 0x12, 0x17, 0x51, 0x78, 0x46, 0x22, 0x01, + 0x53, 0x54, 0x63, 0x87, 0x77, 0x38, 0x11, 0x81, 0x43, 0x30, + 0x15, 0x47, 0x66, 0x11, 0x40, 0x65, 0x70, 0x56, 0x62, 0x28, + 0x21, 0x65, 0x30, 0x45, 0x63, 0x53, 0x31, 0x80, 0x81, 0x71, + 0x23, 0x62, 0x85, 0x03, 0x07, 0x56, 0x16, 0x28, 0x18, 0x35, + 0x07, 0x38, 0x60, 0x68, 0x17, 0x30, 0x15, 0x20, 0x04, 0x13, + 0x13, 0x61, 0x51, 0x58, 0x00, 0x37, 0x51, 0x58, 0x14, 0x06, + 0x12, 0x55, 0x13, 0x46, 0x76, 0x05, 0x51, 0x87, 0x32, 0x62, + 0x50, 0x41, 0x88, 0x24, 0x50, 0x31, 0x65, 0x36, 0x31, 0x02, + 0x75, 0x35, 0x78, 0x27, 0x36, 0x08, 0x01, 0x77, 0x22, 0x77, + 0x30, 0x80, 0x11, 0x21, 0x28, 0x26, 0x68, 0x27, 0x13, 0x70, + 0x50, 0x44, 0x88, 0x20, 0x50, 0x67, 0x65, 0x74, 0x17, 0x46, + 0x50, 0x16, 0x42, 0x75, 0x35, 0x12, 0x60, 0x12, 0x17, 0x13, + 0x36, 0x72, 0x04, 0x77, 0x07, 0x55, 0x20, 0x27, 0x15, 0x02, + 0x25, 0x12, 0x57, 0x71, 0x37, 0x45, 0x43, 0x34, 0x40, 0x31, + 0x78, 0x50, 0x31, 0x28, 0x17, 0x84, 0x87, 0x43, 0x25, 0x75, + 0x58, 0x05, 0x61, 0x56, 0x41, 0x44, 0x57, 0x67, 0x85, 0x54, + 0x00, 0x88, 0x88, 0x50, 0x68, 0x11, 0x14, 0x42, 0x08, 0x74, + 0x73, 0x00, 0x38, 0x08, 0x45, 0x28, 0x62, 0x43, 0x36, 0x20, + 0x30, 0x10, 0x87, 0x83, 0x67, 0x62, 0x02, 0x48, 0x46, 0x50, + 0x08, 0x08, 0x41, 0x43, 0x78, 0x22, 0x65, 0x87, 0x43, 0x84, + 0x25, 0x36, 0x58, 0x64, 0x30, 0x10, 0x20, 0x68, 0x82, 0x47, + 0x60, 0x31, 0x76, 0x68, 0x74, 0x68, 0x75, 0x61, 0x16, 0x26, + 0x82, 0x50, 0x32, 0x61, 0x41, 0x22, 0x38, 0x20, 0x86, 0x75, + 0x74, 0x00, 0x77, 0x12, 0x81, 0x35, 0x51, 0x78, 0x88, 0x64, + 0x82, 0x00, 0x41, 0x55, 0x62, 0x87, 0x51, 0x41, 0x74, 0x51, + 0x53, 0x27, 0x33, 0x84, 0x68, 0x86, 0x57, 0x60, 0x44, 0x30, + 0x22, 0x32, 0x10, 0x52, 0x22, 0x83, 0x48, 0x53, 0x66, 0x74, + 0x14, 0x52, 0x32, 0x71, 0x41, 0x08, 0x83, 0x67, 0x41, 0x38, + 0x46, 0x80, 0x88, 0x14, 0x84, 0x30, 0x85, 0x35, 0x46, 0x20, + 0x54, 0x84, 0x56, 0x84, 0x54, 0x82, 0x14, 0x11, 0x52, 0x07, + 0x86, 0x46, 0x05, 0x82, 0x26, 0x85, 0x75, 0x07, 0x88, 0x75, + 0x51, 0x17, 0x54, 0x32, 0x68, 0x66, 0x08, 0x23, 0x66, 0x06, + 0x42, 0x28, 0x00, 0x84, 0x27, 0x27, 0x43, 0x47, 0x12, 0x27, + 0x13, 0x15, 0x17, 0x74, 0x85, 0x14, 0x12, 0x62, 0x06, 0x47, + 0x17, 0x60, 0x00, 0x10, 0x85, 0x16, 0x55, 0x64, 0x46, 0x62, + 0x77, 0x05, 0x51, 0x23, 0x52, 0x37, 0x51, 0x78, 0x35, 0x66, + 0x14, 0x15, 0x78, 0x40, 0x16, 0x54, 0x67, 0x30, 0x61, 0x24, + 0x26, 0x86, 0x56, 0x83, 0x62, 0x78, 0x88, 0x83, 0x50, 0x06, + 0x13, 0x21, 0x33, 0x73, 0x16, 0x44, 0x86, 0x77, 0x65, 0x28, + 0x12, 0x40, 0x62, 0x54, 0x55, 0x84, 0x00, 0x11, 0x77, 0x38, + 0x71, 0x51, 0x38, 0x32, 0x33, 0x67, 0x15, 0x77, 0x24, 0x33, + 0x44, 0x11, 0x05, 0x65, 0x13, 0x03, 0x72, 0x63, 0x81, 0x58, + 0x08, 0x03, 0x34, 0x23, 0x61, 0x00, 0x02, 0x63, 0x86, 0x40, + 0x03, 0x71, 0x34, 0x27, 0x45, 0x10, 0x34, 0x26, 0x83, 0x28, + 0x31, 0x35, 0x26, 0x05, 0x58, 0x41, 0x11, 0x10, 0x65, 0x35, + 0x22, 0x42, 0x28, 0x88, 0x46, 0x06, 0x57, 0x33, 0x88, 0x46, + 0x04, 0x86, 0x88, 0x88, 0x51, 0x74, 0x82, 0x27, 0x58, 0x14, + 0x11, 0x08, 0x13, 0x16, 0x61, 0x16, 0x14, 0x44, 0x83, 0x85, + 0x71, 0x44, 0x55, 0x82, 0x16, 0x62, 0x85, 0x05, 0x43, 0x41, + 0x73, 0x53, 0x60, 0x01, 0x80, 0x68, 0x33, 0x13, 0x43, 0x44, + 0x73, 0x36, 0x65, 0x35, 0x22, 0x26, 0x13, 0x31, 0x36, 0x83, + 0x30, 0x27, 0x15, 0x11, 0x54, 0x53, 0x24, 0x84, 0x75, 0x24, + 0x72, 0x78, 0x34, 0x24, 0x35, 0x80, 0x06, 0x38, 0x88, 0x11, + 0x41, 0x01, 0x34, 0x87, 0x77, 0x20, 0x14, 0x50, 0x55, 0x12, + 0x17, 0x48, 0x87, 0x74, 0x58, 0x42, 0x31, 0x46, 0x36, 0x37, + 0x26, 0x50, 0x04, 0x75, 0x77, 0x15, 0x41, 0x53, 0x04, 0x04, + 0x26, 0x61, 0x65, 0x87, 0x55, 0x56, 0x07, 0x81, 0x28, 0x21, + 0x41, 0x61, 0x41, 0x50, 0x17, 0x47, 0x25, 0x50, 0x20, 0x83, + 0x46, 0x87, 0x18, 0x45, 0x40, 0x21, 0x06, 0x08, 0x12, 0x25, + 0x71, 0x13, 0x35, 0x55, 0x54, 0x61, 0x00, 0x52, 0x74, 0x78, + 0x13, 0x84, 0x55, 0x40, 0x14, 0x40, 0x78, 0x12, 0x88, 0x43, + 0x33, 0x24, 0x66, 0x88, 0x22, 0x44, 0x15, 0x37, 0x81, 0x27, + 0x84, 0x18, 0x28, 0x11, 0x58, 0x51, 0x71, 0x21, 0x02, 0x83, + 0x70, 0x48, 0x32, 0x46, 0x00, 0x70, 0x17, 0x30, 0x63, 0x21, + 0x46, 0x60, 0x50, 0x72, 0x77, 0x45, 0x83, 0x75, 0x26, 0x31, + 0x47, 0x34, 0x47, 0x84, 0x87, 0x63, 0x22, 0x83, 0x21, 0x10, + 0x21, 0x51, 0x47, 0x46, 0x31, 0x06, 0x57, 0x82, 0x65, 0x24, + 0x61, 0x66, 0x24, 0x68, 0x14, 0x03, 0x43, 0x41, 0x04, 0x14, + 0x47, 0x61, 0x57, 0x87, 0x43, 0x83, 0x43, 0x25, 0x87, 0x36, + 0x72, 0x51, 0x38, 0x51, 0x54, 0x54, 0x84, 0x40, 0x15, 0x30, + 0x35, 0x34, 0x43, 0x61, 0x63, 0x42, 0x77, 0x31, 0x42, 0x06, + 0x61, 0x03, 0x01, 0x41, 0x08, 0x84, 0x02, 0x65, 0x04, 0x72, + 0x32, 0x00, 0x21, 0x10, 0x54, 0x73, 0x04, 0x42, 0x48, 0x11, + 0x74, 0x18, 0x63, 0x73, 0x28, 0x61, 0x36, 0x80, 0x20, 0x86, + 0x24, 0x42, 0x16, 0x11, 0x71, 0x83, 0x78, 0x38, 0x82, 0x47, + 0x67, 0x18, 0x56, 0x86, 0x85, 0x66, 0x18, 0x24, 0x50, 0x74, + 0x72, 0x02, 0x66, 0x83, 0x63, 0x08, 0x25, 0x32, 0x15, 0x78, + 0x33, 0x08, 0x34, 0x44, 0x08, 0x28, 0x10, 0x25, 0x40, 0x11, + 0x04, 0x76, 0x60, 0x16, 0x65, 0x16, 0x13, 0x30, 0x53, 0x14, + 0x77, 0x06, 0x06, 0x88, 0x64, 0x47, 0x08, 0x23, 0x11, 0x56, + 0x46, 0x61, 0x48, 0x64, 0x73, 0x66, 0x07, 0x65, 0x41, 0x24, + 0x67, 0x45, 0x42, 0x18, 0x62, 0x01, 0x70, 0x88, 0x03, 0x77, + 0x22, 0x85, 0x77, 0x02, 0x85, 0x03, 0x65, 0x15, 0x57, 0x51, + 0x28, 0x72, 0x53, 0x32, 0x05, 0x58, 0x84, 0x54, 0x03, 0x81, + 0x63, 0x23, 0x38, 0x27, 0x01, 0x85, 0x61, 0x12, 0x28, 0x62, + 0x22, 0x67, 0x56, 0x66, 0x63, 0x08, 0x74, 0x63, 0x21, 0x01, + 0x46, 0x10, 0x08, 0x18, 0x07, 0x86, 0x47, 0x70, 0x50, 0x25, + 0x45, 0x06, 0x55, 0x88, 0x46, 0x11, 0x23, 0x84, 0x70, 0x02, + 0x24, 0x88, 0x52, 0x60, 0x12, 0x72, 0x63, 0x05, 0x81, 0x21, + 0x26, 0x07, 0x64, 0x03, 0x56, 0x48, 0x27, 0x04, 0x38, 0x86, + 0x25, 0x65, 0x21, 0x25, 0x77, 0x21, 0x62, 0x28, 0x82, 0x71, + 0x85, 0x73, 0x78, 0x24, 0x78, 0x51, 0x61, 0x02, 0x81, 0x14, + 0x67, 0x61, 0x08, 0x88, 0x31, 0x77, 0x06, 0x24, 0x45, 0x13, + 0x67, 0x67, 0x54, 0x67, 0x00, 0x12, 0x62, 0x54, 0x11, 0x27, + 0x51, 0x48, 0x07, 0x33, 0x01, 0x24, 0x04, 0x64, 0x11, 0x83, + 0x18, 0x52, 0x55, 0x23, 0x24, 0x58, 0x53, 0x78, 0x30, 0x43, + 0x31, 0x76, 0x62, 0x01, 0x08, 0x73, 0x21, 0x32, 0x12, 0x78, + 0x22, 0x68, 0x33, 0x45, 0x33, 0x73, 0x02, 0x74, 0x21, 0x81, + 0x02, 0x16, 0x54, 0x31, 0x55, 0x76, 0x25, 0x76, 0x41, 0x36, + 0x75, 0x22, 0x78, 0x16, 0x60, 0x48, 0x58, 0x28, 0x83, 0x50, + 0x88, 0x66, 0x72, 0x70, 0x21, 0x21, 0x24, 0x16, 0x62, 0x57, + 0x20, 0x13, 0x80, 0x61, 0x15, 0x45, 0x42, 0x86, 0x00, 0x25, + 0x77, 0x58, 0x84, 0x01, 0x66, 0x16, 0x46, 0x56, 0x68, 0x57, + 0x12, 0x20, 0x75, 0x60, 0x41, 0x85, 0x02, 0x88, 0x12, 0x68, + 0x20, 0x02, 0x41, 0x18, 0x87, 0x13, 0x17, 0x33, 0x74, 0x11, + 0x08, 0x37, 0x47, 0x08, 0x31, 0x67, 0x08, 0x50, 0x61, 0x54, + 0x56, 0x71, 0x63, 0x26, 0x85, 0x22, 0x07, 0x87, 0x71, 0x28, + 0x20, 0x47, 0x48, 0x66, 0x54, 0x38, 0x03, 0x41, 0x38, 0x21, + 0x70, 0x50, 0x66, 0x53, 0x56, 0x70, 0x74, 0x55, 0x70, 0x28, + 0x52, 0x01, 0x42, 0x65, 0x53, 0x73, 0x32, 0x33, 0x67, 0x42, + 0x67, 0x85, 0x18, 0x45, 0x12, 0x37, 0x58, 0x82, 0x13, 0x73, + 0x78, 0x77, 0x03, 0x42, 0x04, 0x65, 0x55, 0x66, 0x07, 0x25, + 0x07, 0x37, 0x40, 0x78, 0x66, 0x71, 0x11, 0x21, 0x43, 0x25, + 0x87, 0x40, 0x58, 0x63, 0x33, 0x43, 0x52, 0x10, 0x31, 0x53, + 0x56, 0x48, 0x05, 0x55, 0x77, 0x77, 0x26, 0x87, 0x28, 0x43, + 0x61, 0x46, 0x11, 0x76, 0x82, 0x50, 0x42, 0x04, 0x32, 0x88, + 0x18, 0x66, 0x16, 0x36, 0x64, 0x41, 0x38, 0x17, 0x55, 0x43, + 0x06, 0x25, 0x80, 0x27, 0x21, 0x16, 0x81, 0x22, 0x64, 0x60, + 0x38, 0x16, 0x82, 0x40, 0x72, 0x34, 0x73, 0x52, 0x61, 0x85, + 0x11, 0x16, 0x00, 0x25, 0x03, 0x30, 0x06, 0x80, 0x21, 0x56, + 0x64, 0x52, 0x23, 0x26, 0x37, 0x75, 0x73, 0x65, 0x53, 0x27, + 0x37, 0x47, 0x56, 0x76, 0x80, 0x38, 0x53, 0x62, 0x14, 0x24, + 0x64, 0x03, 0x66, 0x21, 0x72, 0x16, 0x36, 0x34, 0x11, 0x65, + 0x61, 0x62, 0x86, 0x02, 0x83, 0x27, 0x80, 0x82, 0x70, 0x72, + 0x52, 0x60, 0x20, 0x87, 0x58, 0x58, 0x14, 0x38, 0x47, 0x03, + 0x10, 0x72, 0x60, 0x48, 0x02, 0x01, 0x17, 0x21, 0x61, 0x62, + 0x38, 0x64, 0x27, 0x53, 0x57, 0x13, 0x68, 0x18, 0x26, 0x62, + 0x43, 0x42, 0x21, 0x85, 0x70, 0x23, 0x58, 0x13, 0x72, 0x04, + 0x04, 0x08, 0x05, 0x82, 0x26, 0x18, 0x82, 0x47, 0x87, 0x71, + 0x32, 0x28, 0x68, 0x25, 0x87, 0x24, 0x06, 0x74, 0x41, 0x44, + 0x08, 0x64, 0x68, 0x30, 0x24, 0x44, 0x21, 0x73, 0x03, 0x45, + 0x70, 0x41, 0x06, 0x78, 0x38, 0x33, 0x88, 0x13, 0x31, 0x14, + 0x18, 0x17, 0x45, 0x06, 0x26, 0x67, 0x66, 0x73, 0x82, 0x56, + 0x66, 0x88, 0x70, 0x22, 0x55, 0x47, 0x27, 0x50, 0x86, 0x55, + 0x53, 0x00, 0x28, 0x55, 0x40, 0x62, 0xe9, 0x37, 0x65, 0xe1, + 0x30, 0x48, 0x6b, 0x35, 0x76, 0x96, 0x05, 0x21, 0xce, 0xed, + 0x46, 0xae, 0x7e, 0x6d, 0xc9, 0xf1, 0xc9, 0xb3, 0x7a, 0xa7, + 0xde, 0xa7, 0x62, 0x18, 0x11, 0xc0, 0xd8, 0xd0, 0x17, 0x0f, + 0x38, 0xaf, 0x0e, 0x3d, 0xaf, 0xe6, 0x63, 0xb0, 0xc4, 0x68, + 0x4e, 0x29, 0xa4, 0xf4, 0x20, 0x22, 0xbc, 0x82, 0x15, 0x1d, + 0x08, 0x39, 0x18, 0xfe, 0x69, 0x55, 0x06, 0x3d, 0xf4, 0xa3, + 0xe7, 0x29, 0x23, 0xa4, 0xd9, 0xa4, 0x22, 0x06, 0x2d, 0x5f, + 0x22, 0xb3, 0x9b, 0x1c, 0xb6, 0x3e, 0xf3, 0xf4, 0x8a, 0xb3, + 0x35, 0x18, 0x4c, 0x1f, 0xaf, 0xd4, 0xcf, 0x5b, 0x9b, 0xa7, + 0xf8, 0xd2, 0x86, 0x71, 0x8e, 0x64, 0x96, 0xd1, 0x6e, 0xad, + 0xd2, 0x7e, 0x16, 0x5b, 0x38, 0x91, 0x0e, 0x40, 0xaa, 0x07, + 0x6a, 0x63, 0x2a, 0xc0, 0x5b, 0x14, 0x79, 0x52, 0xcb, 0x23, + 0x6e, 0x76, 0x95, 0xd0, 0x90, 0x6c, 0x18, 0xe7, 0x89, 0xee, + 0xb9, 0x7f, 0x33, 0x08, 0x35, 0x8f, 0xa3, 0xaa, 0xaa, 0x10, + 0x2f, 0x8b, 0xc9, 0x6c, 0x1d, 0x95, 0xb5, 0xb8, 0x54, 0x0d, + 0x67, 0x86, 0xd4, 0x5d, 0xae, 0x8f, 0x33, 0x20, 0xe2, 0x35, + 0xda, 0x71, 0x53, 0x24, 0xad, 0x16, 0x84, 0x2e, 0x98, 0xcd, + 0x00, 0xa2, 0x69, 0x6a, 0x12, 0x9a, 0x86, 0xf3, 0x9f, 0x18, + 0x6c, 0x9f, 0x24, 0xbe, 0xb3, 0xf4, 0x90, 0xb3, 0xc4, 0xa4, + 0x8b, 0xce, 0x88, 0x60, 0xa0, 0x91, 0xb8, 0x9a, 0x52, 0xe5, + 0xfe, 0x16, 0x6d, 0xff, 0xb3, 0xdc, 0x50, 0x79, 0xfe, 0x31, + 0x24, 0xd4, 0x59, 0x5f, 0xf9, 0xb4, 0x70, 0x0b, 0x15, 0x93, + 0xd9, 0xe9, 0x92, 0xb6, 0xf5, 0x80, 0x34, 0x63, 0x66, 0x78, + 0xcf, 0xa9, 0xce, 0x48, 0xbf, 0xbe, 0x9e, 0xfa, 0xdd, 0x7d, + 0xf4, 0x16, 0xe2, 0xd2, 0x98, 0x13, 0xe2, 0x76, 0xdd, 0x0a, + 0xc7, 0x2d, 0xe8, 0x88, 0x8e, 0x1a, 0xc0, 0xfc, 0xe8, 0x35, + 0xaf, 0x5d, 0xe2, 0x4c, 0x96, 0x82, 0x4c, 0xe5, 0x89, 0x14, + 0xb8, 0x27, 0x39, 0xb5, 0x55, 0xc5, 0xa5, 0x8a, 0x01, 0xcc, + 0xfd, 0xbd, 0xa9, 0xec, 0xae, 0xc0, 0xe7, 0xd7, 0xf8, 0x11, + 0x84, 0x35, 0x99, 0x26, 0xb6, 0xc6, 0xf7, 0x35, 0xe0, 0x93, + 0xd8, 0xd7, 0xbf, 0xc0, 0xc8, 0x44, 0xfd, 0x46, 0xf5, 0xb7, + 0xc5, 0x5a, 0x75, 0xd3, 0xc7, 0xfa, 0xf4, 0xe1, 0xc0, 0x84, + 0x5e, 0x31, 0xfe, 0x69, 0x80, 0x5a, 0xe5, 0x4b, 0x9b, 0x5b, + 0xa4, 0x5c, 0x23, 0xaa, 0x85, 0xc9, 0x9a, 0xbd, 0x71, 0x49, + 0x11, 0x30, 0x8b, 0x81, 0xa1, 0xdd, 0xf8, 0xb8, 0x74, 0x91, + 0xe7, 0xf7, 0x82, 0x42, 0x70, 0x22, 0x95, 0xf0, 0xcc, 0x9f, + 0x02, 0x33, 0x0f, 0x08, 0x3b, 0x04, 0x31, 0xd7, 0x4f, 0x86, + 0x78, 0x49, 0xb9, 0x90, 0xf5, 0x8f, 0xec, 0x12, 0x84, 0x52, + 0x03, 0x1f, 0x64, 0x5e, 0xf0, 0x2a, 0xeb, 0x87, 0xa5, 0xec, + 0x95, 0x25, 0x64, 0x25, 0x49, 0x3b, 0x3c, 0x30, 0xed, 0x3b, + 0xe9, 0x36, 0xfd, 0xae, 0xa6, 0x26, 0xd3, 0x45, 0xbc, 0x1b, + 0x78, 0x5f, 0xce, 0x27, 0x45, 0x1c, 0xd5, 0xf9, 0xa7, 0xda, + 0x62, 0xe6, 0x7e, 0xd3, 0xbb, 0xd8, 0x0a, 0xfd, 0xf5, 0xa5, + 0x31, 0x09, 0x6e, 0x40, 0xe8, 0xcf, 0xc1, 0x42, 0x8e, 0x2e, + 0x75, 0x65, 0xaa, 0x91, 0x6f, 0xc7, 0x75, 0x3a, 0x1e, 0x40, + 0x99, 0x71, 0x5e, 0x00, 0xae, 0x07, 0xad, 0x43, 0x49, 0xdd, + 0x6d, 0x36, 0xe3, 0xa8, 0xdf, 0x2c, 0x39, 0xa2, 0x57, 0xd7, + 0x93, 0xa1, 0x16, 0x80, 0x89, 0xa6, 0x56, 0x69, 0x75, 0xea, + 0xb8, 0xb2, 0x43, 0x0c, 0xdf, 0x46, 0x05, 0x9a, 0x39, 0x08, + 0x3b, 0xb6, 0x76, 0xe3, 0x5b, 0x98, 0x5b, 0x48, 0xc0, 0x11, + 0x14, 0x6f, 0xcd, 0xb7, 0xaa, 0x08, 0x1e, 0x53, 0x9b, 0x94, + 0x9d, 0xa2, 0xe6, 0x99, 0xcb, 0x1c, 0xb4, 0xbf, 0x55, 0x84, + 0x12, 0xc9, 0xf1, 0xf0, 0x94, 0xd9, 0x7d, 0x61, 0xa9, 0xe7, + 0xe6, 0xc1, 0xe2, 0xca, 0x6b, 0x36, 0x80, 0x72, 0x31, 0x79, + 0xbf, 0xe7, 0x3e, 0x99, 0x9e, 0xd5, 0x59, 0xd4, 0x97, 0x14, + 0xd5, 0xfa, 0x93, 0x37, 0x8a, 0x65, 0xa5, 0xb6, 0x4e, 0xba, + 0xb3, 0x84, 0xf2, 0xc1, 0x55, 0xb6, 0x94, 0x31, 0x30, 0xe7, + 0xb2, 0x71, 0x4e, 0xc6, 0x21, 0x50, 0xf3, 0xcf, 0x7c, 0xbc, + 0x26, 0xb7, 0x20, 0xcb, 0x2d, 0x9e, 0x55, 0x23, 0x7c, 0xf0, + 0x97, 0x16, 0x57, 0x5b, 0xcc, 0xc5, 0x48, 0xc9, 0xc8, 0xee, + 0x1e, 0x11, 0x6b, 0x72, 0x3b, 0x29, 0x71, 0xa4, 0xed, 0x08, + 0x6c, 0x38, 0xc6, 0x2e, 0x64, 0x3b, 0x16, 0xd8, 0x4d, 0x19, + 0xe8, 0x94, 0xd3, 0xd5, 0xb4, 0x18, 0xb4, 0x03, 0x24, 0x62, + 0xe7, 0x44, 0x5e, 0x09, 0x60, 0xc6, 0xa9, 0xa6, 0xca, 0xbe, + 0x83, 0xe5, 0xf1, 0xbd, 0x04, 0x22, 0x4b, 0x1b, 0x08, 0x0b, + 0xa6, 0x20, 0x95, 0xf2, 0x78, 0x8c, 0x3e, 0x73, 0x03, 0x7b, + 0x75, 0x2c, 0xe5, 0x72, 0xec, 0xc9, 0x25, 0x06, 0x6b, 0x3a, + 0x5e, 0x0e, 0x96, 0xd0, 0xe3, 0x85, 0xb0, 0xb5, 0x6a, 0x83, + 0x40, 0x41, 0x94, 0xce, 0xa1, 0x07, 0x79, 0x07, 0xe2, 0x50, + 0xa4, 0xde, 0x7d, 0x64, 0x2f, 0x7e, 0x43, 0xd5, 0x72, 0xd1, + 0xa7, 0xb9, 0x76, 0xa3, 0xfc, 0x25, 0x33, 0xd7, 0x95, 0xb5, + 0xd9, 0x94, 0x93, 0x55, 0xaf, 0x04, 0x86, 0x4a, 0xfc, 0x2f, + 0x5f, 0x3d, 0x34, 0x86, 0xf2, 0x9a, 0x31, 0x4c, 0xc9, 0xad, + 0x08, 0xa5, 0x03, 0x91, 0x8a, 0x7e, 0x46, 0xc9, 0x44, 0x61, + 0x11, 0x59, 0x4f, 0xbb, 0x70, 0xf9, 0x9d, 0x3e, 0x6d, 0x53, + 0xb4, 0x16, 0x28, 0xd3, 0x67, 0x52, 0x14, 0xad, 0xba, 0xb1, + 0x21, 0xaf, 0x84, 0x18, 0xc9, 0x37, 0x78, 0xb3, 0x78, 0x92, + 0x95, 0xad, 0x1b, 0xc0, 0x70, 0xe7, 0xe9, 0x06, 0x02, 0xed, + 0x6c, 0x99, 0x4e, 0x43, 0xc0, 0xa4, 0x6f, 0x23, 0xa8, 0x02, + 0xc4, 0xbd, 0xc0, 0x16, 0xc4, 0xed, 0xe0, 0xe1, 0x56, 0x06, + 0x3f, 0xf4, 0x77, 0x12, 0x72, 0x52, 0x04, 0xe8, 0xe4, 0x26, + 0xe5, 0x01, 0x47, 0x5b, 0x8a, 0xca, 0x07, 0x3b, 0xc9, 0xb1, + 0x42, 0x8f, 0x7d, 0x64, 0x7d, 0x5d, 0x6a, 0x95, 0xde, 0x4d, + 0x4b, 0xd3, 0xfa, 0xcf, 0xf0, 0x25, 0x27, 0x96, 0x48, 0xb6, + 0xcc, 0x68, 0x29, 0x37, 0x95, 0xcd, 0x36, 0xb7, 0xb0, 0xd6, + 0xf1, 0xfc, 0x4f, 0xe9, 0xa8, 0x6b, 0x9d, 0x75, 0xc7, 0x9b, + 0x19, 0xaf, 0xbb, 0x8a, 0xaf, 0x4b, 0xb8, 0xe2, 0xeb, 0x8d, + 0xd9, 0xf5, 0x75, 0xc5, 0xc8, 0x0b, 0xf2, 0x1c, 0xf9, 0x9e, + 0xc7, 0x4d, 0x7c, 0x71, 0x47, 0xbd, 0x57, 0x7e, 0xe6, 0x59, + 0xca, 0x8c, 0xf2, 0x0c, 0x47, 0x4a, 0x90, 0xa7, 0xf5, 0xb8, + 0xb2, 0x43, 0x97, 0xdb, 0xbe, 0x76, 0x37, 0x29, 0x36, 0x40, + 0xaa, 0x7a, 0x81, 0xf0, 0xa0, 0xd0, 0x81, 0x39, 0x88, 0xf0, + 0x23, 0xb0, 0xa4, 0xbe, 0x5e, 0xd8, 0x33, 0x98, 0x5d, 0x9d, + 0xb5, 0xd4, 0x1c, 0x00, 0xe2, 0x30, 0xb8, 0x68, 0x58, 0x65, + 0x30, 0x94, 0x3d, 0xf2, 0x75, 0x0c, 0x8e, 0x3b, 0xee, 0x9b, + 0xce, 0x6c, 0x67, 0x68, 0x54, 0x86, 0x7d, 0x27, 0x2a, 0x2f, + 0xf7, 0x25, 0xff, 0x22, 0x1e, 0x74, 0xbd, 0x72, 0x11, 0xf4, + 0x47, 0x8e, 0x2f, 0x0d, 0xb9, 0x31, 0xac, 0x5c, 0x1d, 0xa0, + 0x11, 0xea, 0x16, 0x24, 0x86, 0x76, 0xbd, 0xa3, 0x41, 0x7f, + 0x00, 0xe6, 0xe2, 0x86, 0x93, 0xff, 0x02, 0x07, 0xce, 0x49, + 0xe4, 0xaf, 0x00, 0x9b, 0x15, 0xa6, 0x05, 0xf7, 0x54, 0xd1, + 0xbb, 0xa7, 0x09, 0x67, 0xe6, 0x99, 0xf9, 0x23, 0xe6, 0xaa, + 0x6f, 0xcb, 0xe1, 0xc1, 0xac, 0x7b, 0x98, 0xa9, 0x14, 0x43, + 0x55, 0x22, 0x2c, 0x7a, 0x4a, 0x4a, 0x63, 0xc1, 0xfe, 0x5c, + 0xca, 0xf4, 0x91, 0x3b, 0x6f, 0xf8, 0x7e, 0x2a, 0xa1, 0x4a, + 0xc3, 0x16, 0x1c, 0x1d, 0x53, 0x7d, 0x0e, 0x77, 0x0d, 0x72, + 0x07, 0x78, 0xea, 0xce, 0xe4, 0x0c, 0xf7, 0xce, 0xa0, 0xef, + 0xa1, 0xdb, 0x6b, 0x5f, 0xfd, 0xeb, 0x68, 0xc7, 0x76, 0xfd, + 0x35, 0xd2, 0xcb, 0xa4, 0xf6, 0xe6, 0x6b, 0xdb, 0xe9, 0xd5, + 0x1e, 0x05, 0x8a, 0xba, 0xed, 0x77, 0x94, 0x36, 0x6c, 0x3c, + 0xe2, 0x23, 0xf8, 0x84, 0xa1, 0xe3, 0xcd, 0xfa, 0x1d, 0x31, + 0x52, 0x4d, 0xbc, 0x16, 0x31, 0x92, 0xd7, 0xbe, 0x2e, 0xd6, + 0x6d, 0x1d, 0x58, 0x4e, 0xd8, 0x06, 0x8f, 0xb3, 0xe6, 0x79, + 0x60, 0x92, 0x71, 0x1f, 0x72, 0x84, 0x55, 0x7b, 0xfa, 0xc8, + 0xcf, 0x20, 0x16, 0x2f, 0xc7, 0x13, 0x17, 0xd1, 0x2d, 0xd1, + 0x0d, 0x84, 0x48, 0x08, 0x69, 0xd1, 0x55, 0xb1, 0x08, 0xb6, + 0x17, 0x8c, 0x38, 0x31, 0xa4, 0x77, 0x73, 0xc0, 0xe9, 0xfc, + 0x5f, 0x8e, 0xb3, 0x74, 0x1f, 0xab, 0xcf, 0xf5, 0x26, 0x26, + 0x20, 0x80, 0xd8, 0x13, 0x42, 0xcf, 0xc7, 0x9d, 0xd6, 0x5b, + 0x1a, 0xfd, 0x46, 0x83, 0xba, 0xc1, 0xe5, 0x92, 0xe9, 0x27, + 0xa8, 0xa0, 0x36, 0xd5, 0x31, 0x75, 0x7b, 0x8f, 0x53, 0xf6, + 0xbd, 0x08, 0x1a, 0x86, 0x81, 0x83, 0x85, 0x07, 0x44, 0x3e, + 0xf9, 0x72, 0x47, 0xe0, 0xf1, 0xbe, 0x43, 0x6a, 0xc3, 0x00, + 0x94, 0xd3, 0x19, 0x81, 0xde, 0xf3, 0xfd, 0x57, 0x98, 0xdc, + 0x57, 0xfe, 0x9f, 0x4b, 0x38, 0x23, 0xad, 0xa8, 0xd4, 0x07, + 0x07, 0x5c, 0xca, 0x25, 0xb8, 0x77, 0x7e, 0x45, 0x01, 0x9b, + 0xd4, 0x45, 0x5b, 0x94, 0x47, 0x18, 0x35, 0x66, 0xad, 0x0a, + 0x97, 0x06, 0xc6, 0xa7, 0xaa, 0x50, 0xbf, 0x07, 0x90, 0xfe, + 0x50, 0x8d, 0xd9, 0x1f, 0xdd, 0x33, 0xa4, 0xa7, 0x23, 0x48, + 0xa3, 0xd6, 0x5d, 0xb8, 0x9e, 0x97, 0x22, 0x32, 0xd3, 0x8a, + 0xb0, 0x5e, 0xb3, 0xc9, 0x0b, 0x24, 0x09, 0x66, 0x2e, 0xea, + 0x94, 0x9c, 0x90, 0x4f, 0x3e, 0x93, 0xcf, 0x30, 0x3f, 0xb4, + 0xbe, 0x5e, 0x6c, 0xaf, 0x1a, 0xff, 0x00, 0xc7, 0x74, 0x2e, + 0x8b, 0x08, 0xe9, 0x22, 0x61, 0xc5, 0xd1, 0x21, 0x15, 0xa1, + 0xba, 0x37, 0xd2, 0x24, 0xfd, 0xa5, 0x63, 0x9a, 0x97, 0xfa, + 0xfe, 0xb2, 0xa5, 0x1b, 0x3b, 0xbd, 0xb7, 0xb3, 0x2f, 0x3d, + 0xf1, 0x5a, 0xf2, 0xf6, 0xe4, 0x12, 0xe4, 0x3a, 0x26, 0x3c, + 0x21, 0x5c, 0xd6, 0x83, 0x65, 0x26, 0x86, 0xcc, 0x47, 0x84, + 0xd7, 0x26, 0x31, 0x31, 0xcf, 0x1d, 0xd6, 0xc4, 0xa4, 0xf2, + 0xd4, 0x25, 0x54, 0x2b, 0x81, 0x00, 0x1d, 0xd8, 0xdf, 0x04, + 0xb8, 0x4b, 0xcf, 0xe5, 0x16, 0xf4, 0x4a, 0x17, 0xc5, 0xd8, + 0xd3, 0xdf, 0xe4, 0xb7, 0xd3, 0x98, 0xb6, 0x73, 0xa0, 0x37, + 0x67, 0xbb, 0x8b, 0xc3, 0xfc, 0xac, 0x6e, 0x6c, 0x0e, 0x5d, + 0x44, 0xb0, 0x9d, 0xf8, 0xae, 0x17, 0x9b, 0xf9, 0xcb, 0xe8, + 0xfe, 0xc1, 0x7b, 0x78, 0x16, 0xf6, 0x74, 0x04, 0x7d, 0x38, + 0x17, 0x36, 0x09, 0xe3, 0x73, 0xa1, 0x76, 0x78, 0x7c, 0x14, + 0xb3, 0x83, 0x91, 0x59, 0x27, 0xea, 0x8c, 0x69, 0xe6, 0xa5, + 0x21, 0xcd, 0x78, 0xc7, 0x26, 0xa2, 0xfb, 0xd4, 0xf3, 0xaf, + 0x3f, 0xcf, 0x51, 0x10, 0xcc, 0x4b, 0xdd, 0x14, 0xf4, 0xf3, + 0xb8, 0xea, 0x07, 0xa7, 0x76, 0xe7, 0xbe, 0xec, 0x01, 0xb5, + 0x1e, 0xdc, 0xc3, 0x55, 0x19, 0xb1, 0x16, 0x3f, 0xfe, 0xd4, + 0x15, 0x49, 0xaf, 0x04, 0x9d, 0x38, 0xdd, 0x86, 0x53, 0x2a, + 0x80, 0x62, 0x42, 0xb7, 0x98, 0x42, 0x38, 0xaf, 0x9d, 0x87, + 0xe2, 0x3f, 0xea, 0x7e, 0x0a, 0x35, 0xb8, 0xee, 0xa5, 0x48, + 0x09, 0x08, 0xc5, 0x0d, 0xae, 0x01, 0xd5, 0xec, 0x43, 0x29, + 0x3b, 0xfb, 0x78, 0xc4, 0x96, 0x01, 0x1c, 0x21, 0xf2, 0xc9, + 0x44, 0x68, 0x24, 0x66, 0x86, 0x96, 0xb8, 0xc8, 0xe9, 0xd0, + 0x38, 0x0e, 0x96, 0x4d, 0xcc, 0x45, 0xab, 0xe1, 0xca, 0x50, + 0x10, 0x20, 0x01, 0xbe, 0x89, 0xc0, 0x43, 0x84, 0xd8, 0x38, + 0x52, 0xc0, 0xaf, 0x4d, 0x6b, 0x99, 0x0b, 0xc0, 0xc2, 0x99, + 0x07, 0xc6, 0x78, 0xa8, 0xf7, 0x32, 0x84, 0x86, 0xc5, 0x1a, + 0x95, 0x81, 0xa6, 0x6a, 0x05, 0xa7, 0x9d, 0x81, 0x0e, 0x32, + 0x18, 0x11, 0x4a, 0x0f, 0xfc, 0x17, 0x9e, 0xf7, 0xbf, 0x54, + 0x82, 0xed, 0xba, 0x6f, 0xbd, 0x41, 0xc1, 0xca, 0x55, 0x6c, + 0xff, 0x32, 0x6b, 0xa2, 0x59, 0xae, 0xae, 0x92, 0xc1, 0xb5, + 0xa6, 0xfc, 0xaf, 0x09, 0x48, 0x57, 0xd6, 0xee, 0x38, 0x99, + 0xb4, 0xe3, 0x8f, 0xb7, 0xfc, 0x6a, 0x0a, 0x3b, 0x08, 0xe1, + 0x81, 0x46, 0x11, 0xeb, 0x4a, 0x98, 0x43, 0x16, 0x16, 0x1f, + 0x68, 0xdb, 0xb9, 0x71, 0x19, 0xfe, 0x8b, 0xe6, 0xb7, 0x8b, + 0xc1, 0x3b, 0x90, 0xc5, 0x89, 0x1d, 0xca, 0xd9, 0x19, 0x6c, + 0xe8, 0x01, 0xf4, 0x19, 0x50, 0x3e, 0x93, 0x84, 0xbf, 0xaa, + 0x9a, 0x3d, 0x20, 0x4c, 0x4e, 0x79, 0x83, 0xec, 0x46, 0x83, + 0x09, 0x00, 0xc3, 0x8a, 0xad, 0xd5, 0x2b, 0x08, 0xd1, 0x47, + 0xac, 0x96, 0x0e, 0x34, 0xf0, 0x89, 0x1a, 0x0f, 0xf2, 0x51, + 0x8d, 0x2c, 0xb5, 0xf2, 0xfe, 0x8c, 0xdc, 0xed, 0x41, 0x51, + 0x8c, 0x71, 0x12, 0x05, 0xec, 0x68, 0x21, 0x86, 0x94, 0xf4, + 0xfb, 0xfc, 0xaa, 0xc7, 0xc7, 0xbb, 0x74, 0xa2, 0x8b, 0x76, + 0x62, 0x1c, 0x64, 0x11, 0xa0, 0xd0, 0x5f, 0x46, 0x64, 0xd4, + 0x47, 0xbc, 0x8a, 0x5b, 0x2b, 0xc2, 0xc1, 0x88, 0xb2, 0x30, + 0xbd, 0x02, 0x17, 0x18, 0x0a, 0xd7, 0x9b, 0x3d, 0x91, 0xb9, + 0x2c, 0x83, 0x24, 0xb4, 0x8b, 0x9d, 0x02, 0xaf, 0xb2, 0x4e, + 0x57, 0xe1, 0xb0, 0xa2, 0xf3, 0x7c, 0xde, 0x15, 0xba, 0x60, + 0xbd, 0x80, 0xbe, 0x6d, 0x6f, 0x16, 0xb3, 0xb9, 0xb8, 0x6a, + 0x55, 0xb4, 0xad, 0xf1, 0x01, 0x63, 0x40, 0x01, 0xba, 0x5b, + 0x5d, 0x9a, 0xbc, 0xf0, 0x58, 0xa8, 0xf7, 0xbb, 0x8e, 0x91, + 0xa0, 0xfd, 0x8c, 0x49, 0x8f, 0x1a, 0xbb, 0x2a, 0x28, 0x0d, + 0x7a, 0xa6, 0xc2, 0xd7, 0x41, 0x16, 0xed, 0x61, 0x5d, 0xc4, + 0xe7, 0xcf, 0x2b, 0xb4, 0xb9, 0x10, 0x6f, 0x38, 0x42, 0x88, + 0x94, 0x6e, 0x75, 0x2c, 0x89, 0xac, 0xa0, 0xe9, 0x81, 0xec, + 0x2d, 0x62, 0xa3, 0xba, 0x3c, 0x40, 0xdb, 0x65, 0x56, 0x8e, + 0xc7, 0xd8, 0xb0, 0xd4, 0xf9, 0x04, 0x2b, 0x4c, 0x83, 0x20, + 0xbe, 0xad, 0xb8, 0x66, 0x1c, 0x20, 0x32, 0xb3, 0xf6, 0xf1, + 0xac, 0xa5, 0x8a, 0x72, 0x9a, 0x41, 0x1d, 0x6e, 0xa0, 0x16, + 0xe0, 0x0c, 0x39, 0xb6, 0x06, 0x96, 0x55, 0xb7, 0xda, 0x1c, + 0x54, 0x08, 0xf6, 0x30, 0x1b, 0xb6, 0x57, 0xca, 0x7d, 0xb0, + 0xdc, 0x9e, 0xfa, 0x5c, 0x38, 0x7f, 0xac, 0x37, 0x80, 0x26, + 0xba, 0xdc, 0x7a, 0x95, 0xe5, 0x7b, 0x90, 0xf3, 0x1a, 0xc7, + 0x31, 0x8e, 0x97, 0x07, 0x9a, 0xb8, 0xbe, 0xae, 0x16, 0x11, + 0x44, 0xb0, 0x01, 0xf5, 0xe8, 0x37, 0x1a, 0x67, 0xfe, 0x00, + 0x8f, 0xa1, 0xf5, 0x03, 0x7c, 0xed, 0xbf, 0x42, 0xf4, 0x78, + 0x2b, 0xfb, 0x9f, 0x8c, 0xb3, 0x63, 0x0b, 0x42, 0xbf, 0xae, + 0x8e, 0xf7, 0x6f, 0xb4, 0xb1, 0xe8, 0x75, 0x8c, 0xdf, 0x69, + 0xc6, 0xe1, 0x3a, 0x26, 0x05, 0x47, 0x03, 0x61, 0xfc, 0xc5, + 0xa9, 0xc1, 0x4f, 0x70, 0xce, 0x18, 0xbb, 0x01, 0xe6, 0x11, + 0xc9, 0xa7, 0x7e, 0x65, 0xb8, 0xdc, 0x61, 0x3d, 0x9b, 0x47, + 0x2e, 0x34, 0x16, 0xa1, 0x73, 0x61, 0x91, 0xed, 0x45, 0xe3, + 0x01, 0x26, 0xee, 0x16, 0x76, 0x0e, 0xb7, 0xa1, 0xc0, 0xb3, + 0xac, 0xf0, 0xa5, 0x3b, 0xf6, 0x64, 0x1b, 0x93, 0x94, 0x5c, + 0x8f, 0x4c, 0x25, 0x89, 0xa1, 0x92, 0x32, 0x50, 0x28, 0x03, + 0x8b, 0xff, 0xc4, 0xf6, 0x2a, 0xe8, 0xda, 0x8d, 0xfe, 0x49, + 0xb5, 0x33, 0x01, 0xca, 0x2d, 0x2d, 0x60, 0x33, 0xd6, 0x30, + 0x38, 0x8a, 0x1e, 0x38, 0x3d, 0x78, 0x11, 0xff, 0xef, 0x1c, + 0x82, 0x33, 0xbb, 0xfc, 0x95, 0xef, 0x79, 0xb0, 0x59, 0xbd, + 0x2c, 0xfd, 0x1c, 0x3f, 0x42, 0xda, 0xdf, 0xbd, 0x56, 0xf2, + 0xd6, 0xae, 0x2d, 0x23, 0x36, 0xed, 0xb1, 0x8d, 0x62, 0x58, + 0x71, 0x66, 0x21, 0xe0, 0x4d, 0xee, 0xf4, 0x16, 0x48, 0xa6, + 0xcf, 0x1a, 0x8a, 0xf0, 0x8a, 0xd1, 0x53, 0xf6, 0xe5, 0x4e, + 0x98, 0x9d, 0x7d, 0x6c, 0xd2, 0xdf, 0xb8, 0x2d, 0xa6, 0xe5, + 0x8a, 0xd6, 0xb5, 0xae, 0x61, 0x96, 0xfa, 0x6b, 0xca, 0x7f, + 0x08, 0xc2, 0x2b, 0x67, 0x30, 0x5e, 0x21, 0x3b, 0xa4, 0x84, + 0x95, 0xc6, 0x2f, 0x2c, 0x1f, 0xe2, 0x0e, 0x1a, 0xc3, 0x89, + 0x6a, 0x6a, 0xe7, 0x08, 0xf9, 0x74, 0xee, 0x4f, 0xcd, 0x5e, + 0xe8, 0xce, 0x55, 0x4d, 0x38, 0xed, 0x62, 0x35, 0xee, 0xfc, + 0x14, 0x56, 0xb9, 0xf0, 0xce, 0x29, 0x1c, 0x21, 0x40, 0x51, + 0xe4, 0x76, 0xe3, 0xa6, 0xd8, 0x3d, 0x54, 0x58, 0x51, 0xe5, + 0xf0, 0xdc, 0x50, 0x39, 0x43, 0x67, 0x44, 0x14, 0xcc, 0x6e, + 0x5a, 0xb1, 0x15, 0xec, 0xb4, 0x3e, 0x0e, 0xef, 0x8e, 0x72, + 0x6a, 0xdf, 0xba, 0x37, 0x27, 0x15, 0x62, 0xc3, 0xbd, 0xee, + 0x1d, 0xb1, 0x24, 0x2f, 0x57, 0x51, 0xf1, 0x8f, 0xfb, 0xd1, + 0x10, 0x6f, 0x11, 0xb9, 0x94, 0x5c, 0x9c, 0x12, 0x26, 0x46, + 0x46, 0x7b, 0x31, 0x0e, 0xad, 0x93, 0xe4, 0x4f, 0x09, 0xe3, + 0xbf, 0xc5, 0xe3, 0x11, 0xa4, 0x25, 0x8d, 0x9b, 0x8e, 0x26, + 0x02, 0xaa, 0x72, 0x18, 0xce, 0x89, 0x67, 0xfc, 0x1c, 0x28, + 0xab, 0x11, 0x5a, 0x84, 0x23, 0x7c, 0x91, 0xac, 0x6b, 0x48, + 0x9c, 0x39, 0x14, 0xa3, 0xac, 0xc6, 0x30, 0xbc, 0x1e, 0x0c, + 0xd3, 0x34, 0x19, 0xa9, 0x2b, 0xe7, 0xa4, 0xf8, 0xc1, 0xf0, + 0x3c, 0x60, 0xa2, 0xf7, 0x51, 0x86, 0xcf, 0x42, 0xad, 0x34, + 0x81, 0xa6, 0x93, 0x0b, 0x88, 0x4c, 0xbf, 0xd2, 0x4f, 0xe0, + 0xdb, 0xb2, 0x1d, 0x6d, 0xb2, 0x5c, 0xac, 0xd8, 0x64, 0x85, + 0xc3, 0x35, 0x6e, 0x5d, 0xaf, 0x63, 0x3e, 0x47, 0xb7, 0x5d, + 0x39, 0x21, 0x36, 0xa6, 0xd4, 0xef, 0x9e, 0x1c, 0x1f, 0xd6, + 0xa4, 0xe0, 0xe4, 0x22, 0x75, 0x1e, 0xeb, 0x15, 0xb4, 0xee, + 0x43, 0x37, 0x06, 0xf9, 0x77, 0xbf, 0x68, 0x9b, 0x9a, 0x7f, + 0x38, 0x30, 0x87, 0xde, 0x0c, 0x6a, 0x39, 0x41, 0xe1, 0xed, + 0xf4, 0x18, 0x6e, 0x29, 0x44, 0xf0, 0xfc, 0xb6, 0x09, 0x5b, + 0xb3, 0x30, 0xc9, 0x0a, 0x8c, 0x41, 0x6f, 0x1e, 0x95, 0xbe, + 0x93, 0x3c, 0x11, 0x9b, 0x24, 0xf7, 0x57, 0xb8, 0xc5, 0x9b, + 0x08, 0xaa, 0xcd, 0x24, 0x86, 0x98, 0x59, 0x0f, 0xc6, 0x0e, + 0xd2, 0x71, 0xb2, 0x5e, 0xae, 0x72, 0xc9, 0x69, 0x3b, 0x80, + 0xc2, 0x27, }; static const int sizeof_bench_dilithium_level3_key = sizeof(bench_dilithium_level3_key); -/* certs/dilithium/bench_dilithium_level5_key.der */ -static const unsigned char bench_dilithium_level5_key[] = -{ - 0x30, 0x82, 0x1D, 0x3A, 0x02, 0x01, 0x00, 0x30, 0x0D, 0x06, - 0x0B, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0B, 0x07, - 0x08, 0x07, 0x04, 0x82, 0x1D, 0x24, 0x04, 0x82, 0x1D, 0x20, - 0x0A, 0xDB, 0x85, 0x3A, 0x41, 0x2C, 0x30, 0x56, 0x65, 0x04, - 0x0A, 0x20, 0x31, 0x2A, 0xF3, 0x88, 0x4C, 0x38, 0x64, 0x86, - 0x14, 0x06, 0xF5, 0xF0, 0x7F, 0x63, 0xC1, 0x87, 0x24, 0x39, - 0xFB, 0xC0, 0x28, 0x0C, 0xBE, 0x81, 0xF7, 0xCD, 0x25, 0x8B, - 0x86, 0x42, 0xAD, 0x74, 0x54, 0xCB, 0xA4, 0xDA, 0xC7, 0x94, - 0x70, 0xA3, 0x41, 0xDA, 0x1F, 0xD8, 0x4F, 0x94, 0x5C, 0x0B, - 0xA5, 0x35, 0x60, 0xB2, 0x8C, 0x50, 0xED, 0x0B, 0xCB, 0x75, - 0x6F, 0x14, 0x64, 0x48, 0x86, 0x21, 0xBC, 0x4A, 0x4C, 0xC5, - 0x22, 0xBC, 0x2D, 0x28, 0x32, 0x39, 0x13, 0x57, 0xC9, 0xE5, - 0x74, 0xF4, 0xE6, 0x3A, 0xC2, 0xE2, 0x49, 0x24, 0x31, 0x88, - 0x82, 0x08, 0x03, 0x89, 0x6C, 0x8B, 0x84, 0x08, 0x81, 0xC2, - 0x08, 0xDB, 0x44, 0x60, 0xA0, 0xB2, 0x91, 0x88, 0x36, 0x28, - 0x12, 0x89, 0x89, 0x4B, 0xA4, 0x01, 0x62, 0x12, 0x4C, 0x08, - 0x02, 0x44, 0x19, 0x15, 0x64, 0x8B, 0x04, 0x65, 0xE4, 0x14, - 0x06, 0x08, 0xC7, 0x04, 0x5B, 0x28, 0x81, 0x89, 0xC2, 0x70, - 0xD0, 0xB4, 0x71, 0x4C, 0x24, 0x80, 0xA1, 0x28, 0x86, 0xD1, - 0x06, 0x25, 0x13, 0x03, 0x84, 0x8C, 0x18, 0x41, 0x49, 0x34, - 0x09, 0xCB, 0x22, 0x71, 0x0C, 0xA3, 0x90, 0x22, 0x94, 0x51, - 0x58, 0x02, 0x2D, 0x53, 0x30, 0x00, 0xC2, 0x06, 0x42, 0x48, - 0xC4, 0x70, 0x8A, 0x32, 0x89, 0x80, 0x16, 0x06, 0x90, 0x44, - 0x91, 0xCB, 0xC8, 0x71, 0xA2, 0xB6, 0x64, 0xD0, 0x26, 0x0A, - 0x21, 0x05, 0x88, 0x0C, 0xB0, 0x6C, 0x03, 0x49, 0x24, 0x80, - 0x02, 0x11, 0xD1, 0x36, 0x06, 0x84, 0x32, 0x11, 0x81, 0x44, - 0x91, 0x9B, 0xB0, 0x01, 0x91, 0x02, 0x25, 0x44, 0x92, 0x69, - 0x5A, 0x08, 0x6C, 0x90, 0x00, 0x0D, 0x09, 0x17, 0x64, 0x89, - 0xB2, 0x2D, 0x02, 0x06, 0x2C, 0xDC, 0x92, 0x45, 0xE1, 0x34, - 0x31, 0x11, 0x03, 0x2D, 0x00, 0x94, 0x29, 0xCA, 0x34, 0x89, - 0xA3, 0x40, 0x22, 0xC4, 0x30, 0x08, 0x02, 0x33, 0x6E, 0x1C, - 0x85, 0x10, 0xE4, 0x92, 0x30, 0xC4, 0x46, 0x84, 0xE0, 0x26, - 0x28, 0xC3, 0x10, 0x65, 0x51, 0x06, 0x4A, 0x03, 0xC1, 0x11, - 0x48, 0x32, 0x4E, 0x9A, 0xC4, 0x6C, 0x91, 0x38, 0x40, 0xC0, - 0x92, 0x64, 0xE3, 0xA4, 0x85, 0x22, 0x32, 0x52, 0x92, 0x08, - 0x20, 0x82, 0x22, 0x12, 0x49, 0x20, 0x6C, 0x91, 0x06, 0x01, - 0x1B, 0x30, 0x06, 0x12, 0xC3, 0x41, 0x4B, 0x40, 0x42, 0x0B, - 0xA7, 0x01, 0x60, 0x12, 0x89, 0x24, 0x98, 0x30, 0x99, 0xA6, - 0x64, 0x61, 0x26, 0x6A, 0x91, 0xB0, 0x11, 0x03, 0xC2, 0x2D, - 0x41, 0xC8, 0x6D, 0xD8, 0x38, 0x28, 0x4B, 0x98, 0x04, 0x98, - 0x18, 0x09, 0x18, 0xA6, 0x65, 0x81, 0x38, 0x69, 0x5B, 0xC4, - 0x6D, 0x98, 0x26, 0x0D, 0x62, 0xC6, 0x71, 0xC3, 0xC6, 0x4C, - 0xC2, 0x02, 0x46, 0x5B, 0x94, 0x65, 0x09, 0x29, 0x0E, 0xA2, - 0xA2, 0x41, 0xE4, 0x02, 0x69, 0xA3, 0x90, 0x4D, 0x8B, 0xA6, - 0x70, 0xA3, 0x40, 0x85, 0x5C, 0x36, 0x48, 0x22, 0xC5, 0x84, - 0x19, 0x91, 0x25, 0x00, 0xC2, 0x65, 0xC4, 0x46, 0x2E, 0xDC, - 0xB0, 0x51, 0x94, 0x28, 0x01, 0x9B, 0x22, 0x66, 0x01, 0xA8, - 0x90, 0x9A, 0xC4, 0x08, 0xD1, 0x22, 0x41, 0x42, 0x34, 0x62, - 0x60, 0x40, 0x92, 0x93, 0xC8, 0x45, 0xD8, 0x04, 0x20, 0x8A, - 0x30, 0x25, 0xE1, 0x14, 0x40, 0x11, 0x13, 0x00, 0x54, 0x22, - 0x62, 0x50, 0x10, 0x22, 0x03, 0xA9, 0x85, 0x9B, 0x42, 0x4D, - 0x50, 0xB2, 0x41, 0x10, 0x13, 0x48, 0x63, 0x38, 0x68, 0xA1, - 0xB0, 0x0D, 0x1B, 0x88, 0x84, 0x8A, 0x28, 0x51, 0xD4, 0x38, - 0x2A, 0x12, 0x43, 0x61, 0x80, 0x38, 0x32, 0x18, 0xC6, 0x29, - 0x22, 0xB5, 0x21, 0x02, 0x99, 0x28, 0xCC, 0x18, 0x85, 0x83, - 0xB4, 0x8C, 0x81, 0x24, 0x51, 0x10, 0x83, 0x68, 0x1C, 0x47, - 0x71, 0x8C, 0x40, 0x6C, 0x00, 0xB6, 0x0D, 0x88, 0x22, 0x90, - 0x0C, 0xC7, 0x49, 0xC0, 0x82, 0x89, 0xDA, 0x22, 0x4A, 0xC8, - 0x18, 0x08, 0xD1, 0x00, 0x2C, 0xDA, 0x30, 0x49, 0x49, 0xC8, - 0x91, 0x5A, 0x96, 0x64, 0x11, 0x96, 0x20, 0xD2, 0xC4, 0x60, - 0xE0, 0x46, 0x6A, 0x02, 0xB5, 0x21, 0x19, 0xB9, 0x81, 0x23, - 0x00, 0x22, 0x11, 0x37, 0x32, 0x19, 0xA4, 0x0D, 0x51, 0x96, - 0x89, 0x1B, 0x11, 0x11, 0xC3, 0x14, 0x88, 0x4C, 0x96, 0x0C, - 0x01, 0x13, 0x72, 0x83, 0x16, 0x12, 0x24, 0x38, 0x51, 0x40, - 0x34, 0x89, 0xD9, 0x26, 0x01, 0x54, 0x42, 0x8D, 0x00, 0xC1, - 0x85, 0x13, 0x14, 0x84, 0x82, 0x16, 0x25, 0x88, 0xB0, 0x51, - 0x11, 0x80, 0x30, 0x23, 0x25, 0x46, 0x04, 0x27, 0x66, 0x11, - 0x28, 0x30, 0xD4, 0x94, 0x84, 0x10, 0xA0, 0x8C, 0xC1, 0x36, - 0x0C, 0x14, 0x98, 0x28, 0x5B, 0x02, 0x90, 0xD9, 0x90, 0x31, - 0xD3, 0x28, 0x68, 0x23, 0x90, 0x80, 0x24, 0xC7, 0x84, 0xA1, - 0x00, 0x09, 0xC1, 0x36, 0x84, 0x58, 0xB6, 0x28, 0x4A, 0xB0, - 0x69, 0x08, 0x10, 0x51, 0x1C, 0xB6, 0x84, 0x83, 0x84, 0x81, - 0x03, 0x39, 0x90, 0x81, 0x42, 0x12, 0x13, 0xB4, 0x49, 0x0A, - 0x20, 0x09, 0x93, 0x22, 0x42, 0xD4, 0x26, 0x21, 0xA3, 0x32, - 0x89, 0x89, 0x84, 0x81, 0x0B, 0x02, 0x21, 0x64, 0x28, 0x90, - 0x89, 0xB2, 0x29, 0xE1, 0x36, 0x2C, 0x11, 0x30, 0x51, 0x21, - 0x83, 0x2C, 0x04, 0x36, 0x26, 0x61, 0x12, 0x8C, 0x19, 0x43, - 0x52, 0x89, 0x90, 0x88, 0x43, 0xB8, 0x71, 0x0C, 0x43, 0x09, - 0x84, 0x26, 0x6A, 0x50, 0x36, 0x20, 0x00, 0xC3, 0x68, 0x91, - 0x38, 0x0E, 0x12, 0x12, 0x52, 0x82, 0xC4, 0x4D, 0x64, 0x90, - 0x4D, 0x8C, 0x30, 0x22, 0x14, 0x26, 0x6E, 0x10, 0x46, 0x8E, - 0x58, 0x34, 0x46, 0x22, 0x97, 0x68, 0x02, 0x43, 0x61, 0x41, - 0x06, 0x01, 0x88, 0x42, 0x40, 0x08, 0x06, 0x6D, 0x80, 0x42, - 0x22, 0x84, 0x48, 0x89, 0xDB, 0x84, 0x90, 0xC0, 0x22, 0x71, - 0x43, 0x96, 0x45, 0x0A, 0xA3, 0x30, 0x12, 0x28, 0x44, 0x51, - 0x00, 0x52, 0x99, 0xA0, 0x8D, 0xC2, 0x28, 0x00, 0xC8, 0x18, - 0x6E, 0xA2, 0x40, 0x8E, 0x03, 0x47, 0x31, 0x61, 0x22, 0x41, - 0xD3, 0xB4, 0x01, 0x48, 0x14, 0x40, 0x4C, 0x06, 0x0C, 0x41, - 0x06, 0x2A, 0x5B, 0x90, 0x25, 0xCC, 0xC6, 0x41, 0xC3, 0x86, - 0x28, 0x99, 0x26, 0x50, 0x11, 0xC4, 0x8D, 0x8C, 0x30, 0x68, - 0x8C, 0x08, 0x0C, 0x50, 0x38, 0x86, 0xDC, 0x10, 0x92, 0xD4, - 0x18, 0x72, 0x02, 0xA8, 0x2C, 0x42, 0x82, 0x44, 0x53, 0x36, - 0x0E, 0x90, 0x32, 0x49, 0x84, 0x24, 0x09, 0x12, 0xA2, 0x41, - 0x82, 0x10, 0x4D, 0x01, 0xA0, 0x8C, 0x11, 0xB2, 0x80, 0x21, - 0x89, 0x69, 0x24, 0x21, 0x28, 0x02, 0x03, 0x6E, 0x49, 0x32, - 0x0C, 0x08, 0x88, 0x84, 0x91, 0x80, 0x10, 0x0C, 0x33, 0x12, - 0x43, 0x24, 0x8A, 0x82, 0x26, 0x10, 0x60, 0xC6, 0x60, 0x48, - 0xA2, 0x10, 0x12, 0x83, 0x24, 0x0B, 0x03, 0x40, 0xCA, 0x08, - 0x20, 0x99, 0x36, 0x86, 0x5B, 0x24, 0x41, 0x10, 0x87, 0x04, - 0x0C, 0x15, 0x04, 0x14, 0xB2, 0x68, 0x0B, 0x89, 0x29, 0x99, - 0x16, 0x8D, 0x00, 0x42, 0x00, 0x9B, 0x48, 0x44, 0x12, 0x45, - 0x6C, 0x0A, 0x25, 0x92, 0xC0, 0xC4, 0x00, 0x1A, 0xC8, 0x31, - 0x21, 0x26, 0x8A, 0x81, 0xA0, 0x2C, 0x11, 0x85, 0x65, 0x9A, - 0x08, 0x61, 0xD9, 0x22, 0x12, 0xCB, 0x36, 0x71, 0xA2, 0x08, - 0x0A, 0xE4, 0x06, 0x32, 0x19, 0x19, 0x4A, 0x1B, 0x34, 0x45, - 0x51, 0x06, 0x6E, 0x48, 0x02, 0x68, 0x13, 0xB7, 0x10, 0x44, - 0xC8, 0x85, 0x13, 0x81, 0x2C, 0xC4, 0x40, 0x45, 0x42, 0x98, - 0x21, 0x62, 0x18, 0x92, 0x9B, 0x44, 0x25, 0xA1, 0x06, 0x28, - 0x52, 0x82, 0x11, 0x44, 0x24, 0x32, 0x02, 0xC6, 0x80, 0x10, - 0x45, 0x4E, 0x22, 0x93, 0x0D, 0x44, 0x02, 0x68, 0x4A, 0x30, - 0x81, 0xC9, 0x94, 0x85, 0x08, 0x07, 0x08, 0x24, 0x39, 0x64, - 0xD2, 0x08, 0x22, 0xD0, 0xA0, 0x41, 0x81, 0x92, 0x91, 0x8C, - 0x24, 0x6A, 0xCA, 0x36, 0x32, 0x1C, 0x12, 0x45, 0x92, 0x94, - 0x80, 0x82, 0x86, 0x4C, 0xDA, 0xA2, 0x84, 0x98, 0x24, 0x49, - 0x0A, 0x13, 0x90, 0x1B, 0xC3, 0x01, 0x49, 0x28, 0x60, 0x08, - 0x21, 0x92, 0x0B, 0xB0, 0x20, 0x52, 0x90, 0x84, 0x8A, 0x32, - 0x11, 0x50, 0x28, 0x8C, 0x5B, 0x38, 0x2E, 0xDC, 0xB4, 0x08, - 0x12, 0x20, 0x84, 0xD1, 0x12, 0x22, 0x99, 0x08, 0x11, 0x19, - 0x95, 0x10, 0x80, 0x44, 0x6A, 0xE1, 0x12, 0x85, 0xCC, 0xB0, - 0x24, 0x23, 0x15, 0x4C, 0x63, 0x34, 0x68, 0x5C, 0xB6, 0x65, - 0x42, 0xC2, 0x4D, 0x20, 0x95, 0x84, 0x8A, 0x42, 0x00, 0x4C, - 0x24, 0x50, 0x98, 0x02, 0x6C, 0x21, 0x44, 0x84, 0x20, 0x85, - 0x21, 0x80, 0x48, 0x6C, 0x9C, 0x14, 0x86, 0x81, 0x86, 0x91, - 0x1C, 0x09, 0x04, 0xDC, 0xC6, 0x28, 0x09, 0x27, 0x30, 0x4B, - 0x02, 0x64, 0x44, 0x46, 0x30, 0x9C, 0xA2, 0x8C, 0x20, 0x11, - 0x68, 0x11, 0x24, 0x51, 0x0B, 0x02, 0x00, 0xD2, 0x82, 0x4D, - 0xC3, 0x80, 0x71, 0xE0, 0x48, 0x2C, 0x4A, 0x88, 0x50, 0xA0, - 0x20, 0x49, 0x4B, 0xB4, 0x31, 0x08, 0x12, 0x71, 0x90, 0xA2, - 0x89, 0xCA, 0x46, 0x85, 0x91, 0x96, 0x91, 0x8A, 0x30, 0x31, - 0x0B, 0xC2, 0x21, 0x61, 0x10, 0x49, 0x10, 0x99, 0x81, 0x53, - 0x36, 0x0C, 0x23, 0x81, 0x88, 0x62, 0x28, 0x0A, 0x12, 0x43, - 0x70, 0x02, 0xC7, 0x51, 0x14, 0x34, 0x88, 0x23, 0x84, 0x49, - 0x23, 0x86, 0x08, 0x0C, 0x28, 0x28, 0x94, 0xA0, 0x8D, 0x11, - 0x33, 0x60, 0xA3, 0x38, 0x6E, 0xC0, 0x42, 0x2E, 0x52, 0xB4, - 0x40, 0x0A, 0x25, 0x4D, 0x1C, 0x10, 0x2A, 0x9A, 0x96, 0x64, - 0x10, 0xC1, 0x60, 0x8C, 0x46, 0x60, 0x5A, 0x24, 0x89, 0x42, - 0x40, 0x86, 0xD0, 0x34, 0x89, 0x5C, 0x02, 0x02, 0x00, 0x34, - 0x21, 0x00, 0x24, 0x00, 0xA0, 0x20, 0x60, 0x03, 0xA6, 0x40, - 0xDC, 0x30, 0x80, 0x4B, 0xA8, 0x20, 0x0B, 0xA2, 0x24, 0xE2, - 0xB0, 0x89, 0xA2, 0xB2, 0x65, 0xD4, 0xA6, 0x68, 0x20, 0xA3, - 0x04, 0x4C, 0xC2, 0x11, 0x4A, 0x38, 0x24, 0x08, 0x17, 0x4D, - 0xE2, 0xA2, 0x00, 0x02, 0xC8, 0x00, 0x08, 0x00, 0x30, 0xA4, - 0xB6, 0x25, 0x5A, 0x30, 0x01, 0x40, 0x92, 0x4C, 0xC8, 0x44, - 0x92, 0x43, 0xC8, 0x60, 0xA3, 0x86, 0x84, 0x18, 0x04, 0x70, - 0x53, 0xB2, 0x40, 0x4C, 0x04, 0x84, 0x09, 0xC8, 0x48, 0x21, - 0x13, 0x31, 0x04, 0xA5, 0x0D, 0x90, 0x92, 0x88, 0xC1, 0x10, - 0x8D, 0xE0, 0x88, 0x28, 0x0B, 0x06, 0x84, 0x23, 0x22, 0x6C, - 0xDB, 0xB2, 0x05, 0xC8, 0x08, 0x6E, 0x93, 0x86, 0x4C, 0x0C, - 0x37, 0x86, 0xDA, 0x16, 0x51, 0x9B, 0x08, 0x32, 0x00, 0x91, - 0x45, 0xA4, 0x00, 0x2D, 0x14, 0x02, 0x0E, 0x60, 0x90, 0x4C, - 0x23, 0xB4, 0x09, 0x00, 0xA5, 0x81, 0x19, 0x21, 0x32, 0xC2, - 0x00, 0x02, 0x18, 0x10, 0x50, 0x08, 0xA2, 0x6D, 0x20, 0x31, - 0x6A, 0x90, 0x46, 0x90, 0x8B, 0x94, 0x30, 0x21, 0x44, 0x52, - 0x10, 0x19, 0x51, 0x94, 0xC0, 0x29, 0xC8, 0x20, 0x4E, 0x48, - 0xA6, 0x4C, 0x11, 0xC4, 0x64, 0xDC, 0x34, 0x10, 0x48, 0xC4, - 0x84, 0xCA, 0x46, 0x0C, 0x58, 0x12, 0x49, 0x0B, 0x16, 0x00, - 0x20, 0x42, 0x50, 0x04, 0x00, 0x46, 0xF8, 0x68, 0xB1, 0xA7, - 0x5E, 0xA7, 0xE6, 0xCE, 0xF5, 0x88, 0x8A, 0x5F, 0x79, 0xC9, - 0x3A, 0x5F, 0xF2, 0x7F, 0x5A, 0xED, 0xB4, 0xB4, 0x25, 0x44, - 0xD2, 0x7E, 0xED, 0xCE, 0x46, 0x40, 0xAC, 0xC2, 0x53, 0xD0, - 0xD3, 0xE7, 0xF6, 0x1C, 0xFA, 0x23, 0x4A, 0xB0, 0xEA, 0x32, - 0x91, 0xB7, 0xDA, 0x8B, 0x72, 0x35, 0xB7, 0x74, 0xD5, 0x9A, - 0x9B, 0x22, 0x3D, 0x49, 0x08, 0xBA, 0xD1, 0x7D, 0x9F, 0x64, - 0xD5, 0xAD, 0x7A, 0x37, 0xBD, 0x11, 0xD0, 0xA0, 0x7C, 0x53, - 0x05, 0x1A, 0x66, 0x6C, 0x5D, 0x42, 0x45, 0x55, 0x34, 0xC0, - 0x1F, 0xCA, 0xDB, 0x0D, 0x4F, 0x75, 0x95, 0x9F, 0x10, 0x9A, - 0x8D, 0x54, 0xCE, 0xC2, 0x5C, 0xF0, 0xCE, 0xBD, 0x39, 0x70, - 0xB0, 0x52, 0x2E, 0x4B, 0x11, 0x0D, 0x25, 0xD7, 0xE5, 0x4B, - 0xF1, 0xE3, 0x4F, 0xBE, 0xF2, 0x73, 0xA6, 0xDE, 0xB6, 0xC4, - 0x61, 0x71, 0xCC, 0x5C, 0xFE, 0x55, 0xF0, 0x50, 0xBA, 0x9C, - 0x18, 0x44, 0x13, 0xDD, 0xCB, 0x7A, 0xD2, 0xA2, 0xDC, 0xBF, - 0xF2, 0xC8, 0x84, 0xFF, 0x5B, 0xA7, 0xFA, 0x8D, 0x18, 0xF2, - 0x55, 0xD0, 0x3C, 0x4E, 0xB3, 0x77, 0x7C, 0x95, 0x91, 0x98, - 0x52, 0xF2, 0xB6, 0xCF, 0xFC, 0x45, 0xF4, 0x71, 0x62, 0x24, - 0xE2, 0x7B, 0xF7, 0x85, 0x08, 0x17, 0x6A, 0x62, 0xB4, 0xE9, - 0x08, 0x3E, 0xA1, 0xC6, 0x27, 0x8E, 0xB3, 0x26, 0xA5, 0x95, - 0x91, 0x84, 0xD0, 0xA0, 0xCD, 0xBF, 0x45, 0xD0, 0xE2, 0x26, - 0x65, 0x74, 0xD6, 0x49, 0x50, 0xF2, 0x6B, 0xAE, 0xF1, 0x8A, - 0x2A, 0x18, 0xDA, 0xF0, 0xAD, 0xE7, 0xF3, 0x0A, 0x0E, 0x33, - 0xA5, 0xCA, 0x11, 0x16, 0xCC, 0xD6, 0x81, 0x89, 0x83, 0x27, - 0x32, 0x97, 0x61, 0x48, 0x0D, 0x89, 0x3E, 0xB7, 0x7E, 0x02, - 0xC8, 0x96, 0x93, 0xFA, 0xD0, 0x1D, 0x76, 0xB4, 0xA4, 0x38, - 0x4C, 0xE3, 0xB4, 0x6F, 0xCE, 0x66, 0x90, 0x53, 0xDC, 0xCE, - 0xD6, 0x10, 0x16, 0x3E, 0xB8, 0xBD, 0xD9, 0x8C, 0xA9, 0x90, - 0x54, 0xAF, 0x86, 0x07, 0xB3, 0xC1, 0x82, 0xFB, 0x41, 0x61, - 0xB8, 0x6D, 0x8E, 0xA5, 0xA8, 0xEB, 0xE3, 0xC0, 0xCF, 0x51, - 0xAA, 0x94, 0x7A, 0x7F, 0x9C, 0x48, 0xA3, 0x40, 0x83, 0x33, - 0x22, 0x41, 0x61, 0x4C, 0xD4, 0x62, 0xD7, 0xC6, 0xC6, 0x5B, - 0xF3, 0x48, 0x42, 0xA7, 0x18, 0xD5, 0xAF, 0x05, 0xF6, 0x7A, - 0xF6, 0x6D, 0x82, 0xFF, 0x89, 0x68, 0x21, 0x13, 0x62, 0xA5, - 0x7E, 0xC9, 0x43, 0x03, 0x73, 0xF7, 0xD1, 0x01, 0x7D, 0xD9, - 0x13, 0x03, 0x9C, 0x99, 0x74, 0xD4, 0x92, 0x2E, 0xD1, 0xD3, - 0xCB, 0x53, 0x6C, 0xF9, 0xFE, 0xB4, 0x3D, 0x51, 0xF1, 0x63, - 0x42, 0x5B, 0xB2, 0x5D, 0x70, 0x03, 0xE5, 0x46, 0x5B, 0xC1, - 0xEB, 0x27, 0x11, 0x22, 0x15, 0x73, 0x6C, 0xF8, 0x51, 0x0A, - 0xFF, 0xD8, 0xFE, 0xB6, 0xE1, 0xBD, 0x42, 0xC0, 0x4C, 0xEB, - 0xCD, 0x1E, 0x3C, 0xD5, 0x7C, 0xEA, 0xC6, 0xD4, 0x34, 0xD2, - 0x8D, 0x99, 0xC4, 0x99, 0xA8, 0x8E, 0x9F, 0x60, 0xA8, 0xE8, - 0x7B, 0x1E, 0x7E, 0x50, 0x14, 0xAD, 0xFC, 0xDB, 0xA6, 0x00, - 0xE9, 0x00, 0x7A, 0x5A, 0xCD, 0x01, 0x26, 0xBB, 0x4E, 0x00, - 0x9E, 0xCC, 0xD3, 0x2D, 0x49, 0x1B, 0xB8, 0x60, 0x2C, 0x59, - 0x2A, 0x95, 0x8C, 0x92, 0x4D, 0x1A, 0x57, 0x3B, 0xEF, 0x6E, - 0xC4, 0x91, 0xE4, 0x99, 0x5E, 0xAE, 0x1B, 0xAF, 0x1E, 0x14, - 0x51, 0x38, 0x19, 0xBC, 0x33, 0x5C, 0x21, 0x4D, 0xAD, 0xA1, - 0x12, 0x17, 0xE6, 0xF5, 0x37, 0x98, 0xF6, 0xE6, 0x38, 0x4D, - 0x07, 0x80, 0x1D, 0xD8, 0x5E, 0xCC, 0x58, 0xDB, 0x7E, 0x3A, - 0x8F, 0x90, 0xDF, 0x9E, 0x80, 0xFB, 0xFC, 0x10, 0xEC, 0x7E, - 0x81, 0x53, 0x37, 0xC1, 0x66, 0xEE, 0xD7, 0x80, 0x0F, 0x0C, - 0xEB, 0xE8, 0x85, 0x2E, 0x37, 0x61, 0x8B, 0x9C, 0x63, 0xF6, - 0x27, 0x77, 0x16, 0x44, 0x61, 0x66, 0xC9, 0x79, 0x31, 0xDD, - 0xB4, 0x94, 0x9D, 0x8C, 0x8B, 0x1D, 0x28, 0xC2, 0x84, 0xC9, - 0x30, 0x71, 0xF4, 0x9E, 0xEF, 0x00, 0x2B, 0xA2, 0x9F, 0x38, - 0x65, 0xE6, 0xD1, 0x80, 0x26, 0x9B, 0xC4, 0xE8, 0x83, 0xCE, - 0x64, 0xD0, 0x8A, 0x9A, 0x1E, 0xEF, 0xA3, 0xB6, 0xD2, 0x0B, - 0x9C, 0x14, 0xF3, 0x08, 0xF1, 0x73, 0xD1, 0x34, 0xAE, 0x83, - 0xE7, 0x97, 0x5B, 0x97, 0x35, 0x0E, 0x35, 0xDC, 0x22, 0xD5, - 0xAA, 0xD1, 0xBC, 0xC7, 0x40, 0x20, 0xAD, 0x43, 0x36, 0x24, - 0x66, 0x7A, 0xB7, 0x1F, 0xF9, 0x1A, 0x1F, 0x37, 0xCE, 0xC2, - 0xFC, 0x98, 0xB1, 0x6A, 0x9A, 0x81, 0xD9, 0x4B, 0x53, 0x68, - 0xC5, 0xF3, 0xE6, 0x69, 0x76, 0xA6, 0x8B, 0x98, 0xFB, 0x84, - 0x2E, 0xD3, 0x4F, 0x77, 0xF9, 0x24, 0xF9, 0x13, 0x89, 0x8D, - 0xF6, 0x80, 0x2E, 0x0E, 0xA1, 0xCD, 0x90, 0x58, 0xCE, 0x63, - 0x36, 0x95, 0x8C, 0xF6, 0x68, 0xC3, 0x84, 0xF8, 0xB4, 0x5E, - 0x9E, 0x6C, 0x19, 0x32, 0x90, 0xA7, 0xD0, 0x2D, 0x47, 0x6B, - 0xCB, 0xAF, 0x85, 0x65, 0x92, 0x83, 0x11, 0x8E, 0xCC, 0x88, - 0xB1, 0x0B, 0xB8, 0x1E, 0x55, 0x4F, 0x18, 0x2A, 0xC4, 0x02, - 0xA8, 0x45, 0x6A, 0xCD, 0x75, 0x58, 0x6A, 0xAF, 0x83, 0x94, - 0x38, 0x1D, 0xA9, 0x09, 0x29, 0x1E, 0x0E, 0x43, 0xA9, 0x04, - 0x26, 0xF6, 0x1C, 0xC7, 0xCB, 0xC1, 0x10, 0xB9, 0x86, 0xC1, - 0xA2, 0xEC, 0x03, 0xDE, 0xF7, 0x53, 0x67, 0x2B, 0xDF, 0xEE, - 0xAF, 0xD2, 0xF2, 0xA8, 0xBD, 0xD9, 0x21, 0xCC, 0x8C, 0x72, - 0x02, 0x44, 0xF5, 0xA5, 0xED, 0x88, 0x5B, 0xAC, 0x5F, 0x5A, - 0x15, 0x81, 0xCC, 0x95, 0x15, 0x2E, 0x34, 0x72, 0x59, 0x6C, - 0x03, 0x36, 0x5E, 0x22, 0x7E, 0x3F, 0x65, 0xA6, 0x8C, 0x4F, - 0x89, 0xC1, 0xE7, 0x63, 0xB6, 0x1B, 0xE5, 0x41, 0xC7, 0xF8, - 0x96, 0xA4, 0x8F, 0x4F, 0x47, 0x59, 0x3E, 0x9D, 0x45, 0xCE, - 0xE4, 0x1B, 0xF1, 0x69, 0x0C, 0x39, 0x34, 0x16, 0x77, 0x6A, - 0xF5, 0xB5, 0x9E, 0x8B, 0x63, 0x86, 0x35, 0xFD, 0x4F, 0x2A, - 0x4B, 0x49, 0x21, 0x7C, 0xE3, 0xEA, 0x5C, 0xDE, 0x98, 0xE4, - 0x58, 0x32, 0x67, 0x98, 0xFC, 0x8F, 0xAB, 0x01, 0x0E, 0xA4, - 0x8B, 0x39, 0xA3, 0x55, 0x4C, 0x8E, 0x98, 0xBA, 0xCD, 0x3B, - 0xDB, 0x91, 0x8D, 0x94, 0x98, 0xBE, 0x37, 0x7B, 0xDB, 0x58, - 0xFC, 0xC1, 0x88, 0x7D, 0xD3, 0xBC, 0x8F, 0xB4, 0x7C, 0xB2, - 0xFE, 0x3E, 0x26, 0x36, 0x95, 0x7E, 0xDB, 0xD1, 0x38, 0x29, - 0xD9, 0xCF, 0x5D, 0x0E, 0xD1, 0xDF, 0x7F, 0xD1, 0x68, 0x04, - 0x70, 0x6F, 0x61, 0x39, 0x49, 0x44, 0xD2, 0x5C, 0x0C, 0xC3, - 0xD6, 0xF8, 0x1E, 0x96, 0x36, 0x43, 0x79, 0xB2, 0xE5, 0x1A, - 0xF1, 0x32, 0x03, 0xE1, 0x22, 0x45, 0x20, 0x1B, 0x36, 0x6A, - 0xB8, 0x62, 0xA5, 0xC5, 0x85, 0x8B, 0xED, 0x42, 0x69, 0xC6, - 0x30, 0x36, 0xA1, 0xF6, 0x22, 0x8D, 0x37, 0xD8, 0xE4, 0xBD, - 0x26, 0x8B, 0x89, 0xC2, 0xA9, 0x10, 0x82, 0xDD, 0x0C, 0x2D, - 0x04, 0x39, 0xB7, 0x59, 0x0B, 0x30, 0x2A, 0x6D, 0x84, 0x4A, - 0x74, 0xB9, 0x3F, 0xEA, 0xA5, 0x34, 0x76, 0xFA, 0xAD, 0x99, - 0xB0, 0xEF, 0xA0, 0xF1, 0x85, 0x3D, 0x00, 0x76, 0x00, 0xF8, - 0xFA, 0x1B, 0xAA, 0xB7, 0x5A, 0x62, 0x0E, 0xFD, 0xDC, 0x7A, - 0xCA, 0x18, 0x43, 0x32, 0x02, 0xB7, 0x20, 0x38, 0x0B, 0x50, - 0x4E, 0x57, 0xBF, 0x88, 0xBA, 0x09, 0xD3, 0x9D, 0x8B, 0x3A, - 0x88, 0x82, 0xD9, 0xC3, 0x60, 0x89, 0x10, 0xF5, 0x09, 0x61, - 0x72, 0x41, 0x83, 0xCB, 0x29, 0x38, 0xB3, 0x75, 0xD8, 0xBB, - 0x7E, 0x3F, 0x4A, 0x3C, 0x6B, 0xE5, 0xAE, 0xB7, 0x18, 0xC1, - 0x52, 0x3C, 0x8D, 0x8B, 0xF3, 0x8B, 0x84, 0x98, 0x3E, 0xE3, - 0x5F, 0x5B, 0x89, 0xB7, 0x07, 0x58, 0xD3, 0x7B, 0x84, 0x38, - 0x57, 0x3B, 0xF7, 0x59, 0x22, 0x6B, 0xA7, 0x31, 0x1D, 0xAF, - 0xBF, 0xFA, 0x15, 0x8B, 0xE0, 0x72, 0xFA, 0xCA, 0xB6, 0xC2, - 0xD6, 0x42, 0x43, 0x27, 0xF6, 0xAA, 0x3E, 0x5B, 0x07, 0x12, - 0x5C, 0xEF, 0xED, 0xCB, 0xDF, 0xAA, 0x5F, 0xF8, 0x77, 0xD0, - 0x8E, 0xC7, 0x03, 0x1E, 0x23, 0x5A, 0xF1, 0x3A, 0xA9, 0x10, - 0x6F, 0x05, 0x46, 0x04, 0x72, 0x63, 0xAC, 0xAE, 0x4B, 0x3D, - 0x1E, 0x2D, 0xC2, 0xE9, 0x38, 0x6A, 0xA9, 0x11, 0x1E, 0xE0, - 0xCA, 0x06, 0x7A, 0x5A, 0x45, 0xB2, 0x82, 0x0C, 0x10, 0xEB, - 0x0D, 0x10, 0x26, 0x74, 0xA5, 0x07, 0x1B, 0xBA, 0x61, 0xFD, - 0x8C, 0x73, 0xCB, 0x96, 0xFC, 0xF8, 0x98, 0x2D, 0x83, 0x12, - 0x0B, 0x6A, 0x9C, 0xA4, 0x70, 0x95, 0x4B, 0xD8, 0x11, 0x71, - 0x8F, 0x22, 0x89, 0xA2, 0x6A, 0x0A, 0xB0, 0x17, 0x93, 0x46, - 0x89, 0x60, 0x58, 0x2E, 0x1F, 0x3B, 0xE1, 0x6F, 0x49, 0x47, - 0xBC, 0x93, 0xD2, 0x14, 0x3D, 0xF2, 0x21, 0xA4, 0xFA, 0x1F, - 0x9D, 0x3F, 0x08, 0x40, 0x17, 0x77, 0x58, 0x7F, 0x65, 0xB4, - 0xFD, 0x01, 0x67, 0xF1, 0x62, 0x77, 0xD8, 0x6D, 0x46, 0x42, - 0x30, 0x52, 0x64, 0x4C, 0x76, 0x64, 0x7E, 0x09, 0xDD, 0x57, - 0x04, 0xB8, 0x4A, 0x7F, 0x8A, 0x68, 0xC3, 0x0D, 0xD9, 0xBE, - 0xF6, 0x61, 0x1C, 0x4D, 0x30, 0x80, 0x18, 0x83, 0xD6, 0x3F, - 0xB9, 0x58, 0x52, 0x20, 0xB9, 0x60, 0xEA, 0x22, 0xD0, 0xD0, - 0x61, 0x1A, 0x3B, 0x32, 0x69, 0x35, 0x8B, 0x22, 0x6E, 0x27, - 0x2E, 0xE2, 0x6D, 0xBA, 0xC7, 0x17, 0x02, 0xDA, 0x83, 0x22, - 0x5C, 0x31, 0x60, 0xD6, 0x78, 0x78, 0xBF, 0x0B, 0xEE, 0xD4, - 0x68, 0x32, 0xAE, 0x17, 0x80, 0x04, 0x7F, 0xD9, 0xA9, 0xA0, - 0xC9, 0xB7, 0x98, 0xEE, 0x9C, 0x8C, 0x61, 0x70, 0xBB, 0x2F, - 0x10, 0x39, 0x3E, 0xCC, 0x6E, 0xC8, 0x0A, 0x0F, 0xA2, 0x1E, - 0x31, 0x01, 0x75, 0x1E, 0x41, 0x9E, 0x63, 0x14, 0xC2, 0x3A, - 0xD9, 0x1A, 0x8B, 0x52, 0x0D, 0xFD, 0xDC, 0xE6, 0x23, 0x35, - 0xF1, 0x17, 0xE4, 0xA6, 0xDB, 0xAC, 0x3F, 0x67, 0x59, 0x02, - 0x8E, 0x20, 0x6F, 0x55, 0x69, 0xF8, 0x16, 0xFC, 0x33, 0x53, - 0xCA, 0xE8, 0x4E, 0x3F, 0xA4, 0x5C, 0xA6, 0xA4, 0x95, 0xCD, - 0xB7, 0x9D, 0x14, 0x79, 0xAE, 0x82, 0xF8, 0x2F, 0xE2, 0x13, - 0x0D, 0xDE, 0x75, 0x19, 0xA4, 0x0C, 0x32, 0x83, 0xD0, 0x14, - 0x35, 0xE7, 0x77, 0xD0, 0x18, 0x9C, 0xEF, 0xCC, 0xD5, 0xDA, - 0x39, 0x3B, 0xFF, 0x11, 0x39, 0x20, 0x3D, 0x5A, 0xB1, 0x16, - 0x2A, 0x57, 0x6B, 0x27, 0xC1, 0xB6, 0x69, 0xB5, 0x9B, 0x78, - 0x6F, 0x6B, 0x8A, 0xEF, 0x3F, 0x8F, 0xB8, 0x37, 0xBF, 0xCA, - 0x2D, 0x27, 0x25, 0x12, 0xC9, 0x81, 0x3A, 0x4C, 0x1A, 0x94, - 0xDF, 0x6D, 0x27, 0xF8, 0x85, 0x26, 0xA0, 0x88, 0x56, 0x7B, - 0x62, 0x5E, 0x84, 0xCF, 0x84, 0xAB, 0x81, 0xA3, 0xD4, 0xEB, - 0xE9, 0x85, 0x96, 0xED, 0x27, 0x42, 0xF6, 0x86, 0x28, 0xF1, - 0x8C, 0x69, 0x81, 0xD9, 0xAC, 0x1E, 0x9F, 0x12, 0xA4, 0x9E, - 0x78, 0xC5, 0x2E, 0x07, 0x66, 0xFF, 0x2F, 0xED, 0x93, 0xD2, - 0x62, 0x30, 0x30, 0x81, 0xE5, 0x76, 0x7A, 0x2A, 0x8E, 0xF3, - 0xC0, 0x21, 0x9C, 0xE8, 0xE3, 0x51, 0x4F, 0xDA, 0x96, 0xCF, - 0x6A, 0x0A, 0xC9, 0x90, 0x64, 0x93, 0x70, 0xE2, 0xAD, 0x6E, - 0x17, 0x06, 0x5E, 0xBD, 0x5C, 0x40, 0x4B, 0x43, 0x78, 0x1F, - 0x40, 0x55, 0x36, 0xBD, 0x2B, 0xD6, 0x92, 0x88, 0x02, 0xAA, - 0x3E, 0xDF, 0x3B, 0xC9, 0x90, 0x69, 0x28, 0xE6, 0xE1, 0x7D, - 0xBD, 0x2A, 0xC1, 0x6F, 0x70, 0x6D, 0xB8, 0x1A, 0xAD, 0x66, - 0x4F, 0x78, 0xF7, 0x00, 0x57, 0xED, 0xA8, 0xC3, 0x87, 0x8A, - 0x27, 0x2E, 0xFC, 0xC4, 0x37, 0xB9, 0xED, 0xAE, 0x06, 0x05, - 0x19, 0x60, 0x53, 0x85, 0x54, 0x83, 0x52, 0xEC, 0xBF, 0xA5, - 0x79, 0xFC, 0x18, 0xC3, 0xD8, 0x98, 0xC5, 0xD8, 0x81, 0x78, - 0x4F, 0xDA, 0x24, 0xAD, 0x6F, 0xF4, 0x78, 0x56, 0x79, 0x9F, - 0x5D, 0xE3, 0x6D, 0x35, 0x93, 0xEA, 0xA8, 0xB5, 0x44, 0x1A, - 0xDA, 0x87, 0xBD, 0x06, 0x4D, 0xFF, 0x35, 0x2A, 0x76, 0x51, - 0xD3, 0xC2, 0x73, 0x20, 0x93, 0x33, 0xC0, 0xEA, 0x88, 0xA0, - 0xCD, 0xE1, 0xEA, 0x79, 0x86, 0x32, 0xA7, 0xCE, 0xBA, 0x73, - 0xE9, 0x82, 0x32, 0x64, 0x88, 0x44, 0x66, 0x8A, 0x8C, 0xCB, - 0xF1, 0xDB, 0x42, 0x91, 0x3E, 0x78, 0x3A, 0x77, 0xEB, 0x4C, - 0xFD, 0xFE, 0x43, 0xD8, 0xEA, 0x9E, 0xED, 0x19, 0xAD, 0xA8, - 0x64, 0x1A, 0x12, 0xC3, 0x81, 0x75, 0xA0, 0x61, 0xAF, 0x4F, - 0x71, 0x25, 0x94, 0x76, 0x31, 0x9A, 0xF6, 0x14, 0x3F, 0x6D, - 0x36, 0xC0, 0x2F, 0x52, 0x3B, 0x4B, 0xCB, 0x2B, 0xCF, 0xB8, - 0x70, 0x19, 0x0D, 0x15, 0x1A, 0xF9, 0x48, 0xA8, 0x3A, 0x55, - 0xAF, 0x18, 0x66, 0x50, 0xC8, 0x32, 0x97, 0x43, 0x1E, 0x9F, - 0x8B, 0x66, 0xC1, 0x2E, 0x37, 0x69, 0xB8, 0x97, 0xF9, 0x6A, - 0x1E, 0x69, 0xBA, 0x5C, 0xEC, 0x6F, 0xFD, 0x99, 0x71, 0xB8, - 0xC4, 0x05, 0xB9, 0xB9, 0xE6, 0x4D, 0xA7, 0x01, 0x2D, 0xEB, - 0x26, 0x23, 0x40, 0x4D, 0x79, 0x1B, 0xE4, 0xD9, 0xAB, 0x9F, - 0xE9, 0x9B, 0x35, 0x78, 0xC0, 0x32, 0x8E, 0xF7, 0x5F, 0x7E, - 0xB5, 0x56, 0xD2, 0xA1, 0x35, 0x81, 0x72, 0xD2, 0x6A, 0x0A, - 0xC9, 0x6D, 0x0D, 0xDB, 0x2B, 0xA4, 0x02, 0x92, 0x76, 0x26, - 0xAF, 0x36, 0x27, 0x01, 0xDF, 0xA5, 0x5B, 0x09, 0x97, 0x06, - 0x5E, 0x80, 0xB0, 0x32, 0xFC, 0x1F, 0x72, 0x4E, 0x93, 0x2F, - 0x12, 0xF3, 0xA2, 0x60, 0x19, 0x74, 0x69, 0x03, 0x8B, 0x7D, - 0x6B, 0x2C, 0xE9, 0x54, 0x91, 0xF1, 0x3F, 0x2B, 0xF1, 0x65, - 0x71, 0x0B, 0x24, 0xEF, 0xCC, 0xB8, 0x79, 0x8E, 0x9B, 0x03, - 0xC1, 0xFF, 0xAC, 0xF0, 0x04, 0xEA, 0x92, 0xA3, 0x86, 0x64, - 0x6B, 0x63, 0x43, 0xA6, 0xC3, 0xCB, 0x43, 0xBE, 0xB0, 0xA9, - 0x11, 0x1B, 0x74, 0xC0, 0x87, 0x61, 0x5C, 0xDB, 0xF4, 0xA3, - 0x0E, 0xA6, 0x36, 0xEE, 0x41, 0x7F, 0xA8, 0xA6, 0xDF, 0x1B, - 0x05, 0xAE, 0x77, 0x90, 0x6A, 0xD4, 0x5B, 0x8E, 0x27, 0xE2, - 0xC0, 0x3E, 0x99, 0xAB, 0xFD, 0xFE, 0x6B, 0x71, 0xB4, 0x22, - 0x77, 0x7A, 0xB0, 0x43, 0x8B, 0x81, 0x33, 0x4D, 0x51, 0xD4, - 0xAB, 0xD9, 0xA0, 0x7C, 0xA7, 0x8A, 0x39, 0x92, 0x45, 0x39, - 0xAC, 0x54, 0x13, 0x6E, 0xA5, 0x22, 0x28, 0xC8, 0xAD, 0x3D, - 0xB1, 0xB2, 0xF3, 0x6B, 0xF6, 0x51, 0x17, 0xA3, 0x37, 0xE9, - 0xC9, 0x94, 0x54, 0xD7, 0x64, 0xC6, 0x04, 0xE7, 0xFA, 0x93, - 0xC1, 0xFA, 0xBA, 0xCA, 0x21, 0x1B, 0xF0, 0x6C, 0x99, 0x22, - 0x52, 0x53, 0xEF, 0xC2, 0xA2, 0x19, 0xB3, 0xCA, 0xF5, 0x30, - 0xC1, 0xD1, 0x24, 0x7F, 0x3A, 0x28, 0x8F, 0xAA, 0x70, 0xD2, - 0xBB, 0x7A, 0xF5, 0x8A, 0x23, 0x57, 0xE9, 0x79, 0x00, 0xF4, - 0x1C, 0x1D, 0xB1, 0x42, 0x0C, 0x53, 0x99, 0x7B, 0x99, 0x68, - 0x6E, 0x71, 0xD9, 0xD4, 0xE9, 0xC1, 0xA7, 0x5B, 0x05, 0xA7, - 0x6F, 0xF2, 0xE7, 0x11, 0x3B, 0x70, 0x5F, 0x11, 0x98, 0xBE, - 0xB5, 0xF8, 0x78, 0x5F, 0x5C, 0x19, 0xAC, 0x92, 0x4D, 0x18, - 0x0D, 0x7B, 0x6F, 0x8C, 0x90, 0xAB, 0x6B, 0x32, 0x3D, 0x51, - 0x11, 0xBC, 0x80, 0xC4, 0xCF, 0x4A, 0xF4, 0x7F, 0xCC, 0x68, - 0x92, 0x76, 0xF7, 0x9D, 0xF7, 0x07, 0x44, 0x8C, 0xB5, 0x4D, - 0x53, 0x7E, 0xE2, 0x58, 0x42, 0xB5, 0x8E, 0xB3, 0xC7, 0x0C, - 0x2F, 0xCA, 0x77, 0x2D, 0x56, 0x84, 0xCA, 0x98, 0x05, 0x09, - 0x43, 0xA9, 0x0E, 0x92, 0x4B, 0x57, 0x27, 0x46, 0x31, 0xF0, - 0xE3, 0xA4, 0x48, 0xD9, 0x42, 0x51, 0x32, 0xF0, 0x70, 0xA1, - 0x72, 0xA9, 0x2B, 0x1D, 0xB1, 0x2A, 0x09, 0x96, 0xAE, 0x3E, - 0x83, 0x41, 0x7B, 0x9B, 0x28, 0x6E, 0x85, 0xB7, 0xAD, 0x7F, - 0x10, 0xA3, 0x54, 0xBF, 0x24, 0xB6, 0xFB, 0x6D, 0xA5, 0x9F, - 0xE6, 0xBB, 0x33, 0x8A, 0x04, 0x83, 0x53, 0xFB, 0xB9, 0x79, - 0xF7, 0x76, 0xC9, 0x43, 0xC7, 0xE4, 0xB5, 0xE7, 0x19, 0x56, - 0x72, 0x55, 0xAC, 0x1D, 0xA8, 0xE4, 0xD8, 0x0C, 0x66, 0x15, - 0x7F, 0x17, 0x08, 0xB9, 0x33, 0x4B, 0x9C, 0x84, 0xDA, 0x49, - 0x9F, 0x1B, 0x42, 0x85, 0x0F, 0x4B, 0xC0, 0x70, 0x35, 0x23, - 0x34, 0xD9, 0x3C, 0x76, 0xF9, 0x22, 0x5C, 0x1A, 0xE9, 0x81, - 0xE5, 0x31, 0xA3, 0xF1, 0xB7, 0x7F, 0xE2, 0x75, 0x42, 0x27, - 0x82, 0xC7, 0xBA, 0x68, 0x20, 0x0E, 0xAC, 0xD0, 0x32, 0x28, - 0xB5, 0x99, 0x71, 0xBA, 0x48, 0x2C, 0x95, 0xA5, 0xC8, 0x65, - 0x2E, 0x19, 0x70, 0xAD, 0x12, 0x3A, 0xAD, 0x83, 0x87, 0x15, - 0xA7, 0xEA, 0x9D, 0x6E, 0x11, 0x94, 0x95, 0x23, 0x51, 0xDA, - 0x5F, 0x67, 0xBD, 0xDD, 0xA7, 0xF9, 0xF8, 0x76, 0xE4, 0x3C, - 0x83, 0x0A, 0xAB, 0xBE, 0x6A, 0xB0, 0xC5, 0xA8, 0xBE, 0xD9, - 0xDD, 0xBC, 0x4E, 0xA6, 0xCF, 0x91, 0xB3, 0x42, 0x30, 0x96, - 0x8E, 0x45, 0xC6, 0x1F, 0x55, 0x6B, 0x2C, 0x0A, 0xBC, 0x9F, - 0x69, 0x65, 0x98, 0x34, 0x95, 0x6A, 0x1E, 0x86, 0x78, 0x8B, - 0x26, 0x4F, 0x05, 0x76, 0x03, 0x22, 0xCB, 0x72, 0xF1, 0xD0, - 0x1A, 0x64, 0x19, 0xC7, 0x21, 0x5C, 0x51, 0xD0, 0x6C, 0x0B, - 0xDA, 0xB9, 0x67, 0x7A, 0x83, 0xC3, 0x1E, 0x16, 0x27, 0x4A, - 0x00, 0x5F, 0xBA, 0x0E, 0x45, 0x81, 0x6E, 0xE7, 0x5B, 0x5A, - 0x8F, 0x0D, 0x6D, 0x47, 0xB1, 0x30, 0xA7, 0x42, 0x1E, 0xA9, - 0x8A, 0x27, 0x4A, 0xB0, 0x60, 0x2F, 0xA9, 0x12, 0x42, 0xD6, - 0x7F, 0x10, 0x01, 0xF3, 0x59, 0xD2, 0x40, 0x11, 0x19, 0x92, - 0xFE, 0x80, 0x25, 0x1B, 0x60, 0xDC, 0x02, 0x7B, 0x10, 0x45, - 0x17, 0x66, 0x70, 0xB9, 0x64, 0x4A, 0xBA, 0xAD, 0xBF, 0x55, - 0x7C, 0xB3, 0xD8, 0x18, 0x6D, 0x16, 0x53, 0xED, 0x89, 0xE5, - 0xD2, 0x50, 0xFA, 0xA8, 0xFE, 0x74, 0x67, 0xC4, 0x35, 0x4C, - 0xC4, 0xBE, 0x52, 0x9A, 0x8E, 0xBB, 0xB6, 0xE0, 0xAF, 0x52, - 0x57, 0x3D, 0x99, 0x79, 0x10, 0xB8, 0xE6, 0xAB, 0x24, 0x9E, - 0x75, 0xC2, 0x2A, 0xFB, 0xDB, 0xF8, 0xE0, 0x02, 0xCB, 0x49, - 0x56, 0x52, 0x6B, 0x8C, 0xFA, 0x8E, 0xCF, 0xFA, 0x18, 0x50, - 0xDD, 0x98, 0x49, 0xEC, 0xA8, 0x08, 0x6C, 0x60, 0xC0, 0x68, - 0xBF, 0x7B, 0x49, 0xB4, 0xE6, 0x49, 0x59, 0x6E, 0x65, 0x0E, - 0x41, 0xEA, 0x64, 0xC8, 0xD3, 0x1A, 0x9F, 0x39, 0xAE, 0xEB, - 0x3C, 0x88, 0xFB, 0x40, 0xDC, 0xB8, 0x07, 0x82, 0x56, 0x01, - 0xAC, 0x04, 0x0B, 0x6B, 0x0B, 0x15, 0xAA, 0x4F, 0xD2, 0x04, - 0xF3, 0x65, 0xCD, 0xF7, 0x32, 0xB1, 0x95, 0xC4, 0x91, 0xB8, - 0x63, 0x02, 0x26, 0x47, 0x1D, 0x6E, 0x6D, 0xCF, 0x3D, 0x39, - 0x3D, 0xDC, 0x18, 0x33, 0xD8, 0xF5, 0x8C, 0xB0, 0x69, 0x53, - 0x48, 0x86, 0x14, 0x50, 0xA3, 0x65, 0xEE, 0x2C, 0x2F, 0x72, - 0xF7, 0x43, 0xE7, 0xEA, 0xA0, 0x3E, 0x3C, 0x30, 0x33, 0xD9, - 0x1D, 0x6E, 0x5D, 0xCB, 0xE1, 0xE0, 0x8D, 0x95, 0xD2, 0x58, - 0x8D, 0xD5, 0xB3, 0x1C, 0x22, 0x28, 0x6A, 0xBB, 0xB3, 0x09, - 0xB1, 0x91, 0x60, 0xE2, 0xC6, 0x48, 0x11, 0xF0, 0x49, 0xB6, - 0xE9, 0xEF, 0x4B, 0xC6, 0xDB, 0xB1, 0xBF, 0x6C, 0xB2, 0x92, - 0x5C, 0x65, 0x91, 0x67, 0x81, 0x9C, 0x71, 0x5A, 0x2C, 0xFE, - 0xC8, 0xF9, 0xF5, 0x96, 0x7D, 0x3E, 0xBB, 0x7F, 0xEF, 0xF7, - 0xBF, 0xF8, 0xAC, 0xCF, 0xA6, 0x6F, 0x28, 0x9C, 0x09, 0x65, - 0x8F, 0xF7, 0xDC, 0xEF, 0x3E, 0x4B, 0xCD, 0x6D, 0x97, 0xD3, - 0xCC, 0x9C, 0xF7, 0xF2, 0x4C, 0xE6, 0x64, 0x31, 0xE8, 0x1E, - 0xDE, 0x56, 0xAE, 0xA6, 0x04, 0xFB, 0xED, 0x2E, 0x3F, 0x23, - 0x7D, 0xBC, 0x6D, 0xCC, 0x4B, 0xD4, 0x9E, 0x06, 0x83, 0xE1, - 0x95, 0xAE, 0xC4, 0xAA, 0x6E, 0xFF, 0x9E, 0x1C, 0xB9, 0x07, - 0x60, 0x6D, 0xD5, 0x09, 0x06, 0x30, 0x0C, 0x3F, 0xB5, 0xE8, - 0x8B, 0x01, 0x94, 0x1B, 0x84, 0xE9, 0xB7, 0x37, 0x03, 0xA7, - 0xAF, 0x4B, 0x63, 0x3F, 0xD2, 0x57, 0xBB, 0xB8, 0xBF, 0xE2, - 0x53, 0x4F, 0xA1, 0x9E, 0xC7, 0x4C, 0xDA, 0x89, 0x25, 0x0E, - 0x7E, 0xC9, 0x44, 0x7F, 0x4C, 0x02, 0x7F, 0xA4, 0x08, 0xEC, - 0x7F, 0x44, 0xEA, 0xF7, 0xCF, 0x1B, 0x19, 0xFA, 0x6A, 0x0A, - 0x3E, 0xE1, 0xF4, 0x78, 0xDF, 0x93, 0xAB, 0x86, 0x9E, 0xE1, - 0x31, 0xBF, 0x70, 0x20, 0x8B, 0x87, 0xCE, 0xFC, 0x84, 0x03, - 0x8D, 0xF1, 0x25, 0xE6, 0x88, 0x30, 0x79, 0x63, 0xAF, 0x5C, - 0x3B, 0x84, 0xA9, 0xB8, 0x89, 0xB4, 0x23, 0x58, 0x78, 0xF9, - 0xAB, 0x76, 0x1B, 0x20, 0x56, 0xDB, 0x9E, 0xFE, 0x59, 0x29, - 0xB9, 0x8C, 0xD7, 0x4E, 0xA4, 0x5C, 0x7F, 0x40, 0xA8, 0xEB, - 0x0D, 0x90, 0xBA, 0x30, 0x68, 0x5E, 0x9C, 0x90, 0xBE, 0xD4, - 0x43, 0x4B, 0x67, 0x27, 0xE7, 0x7D, 0x06, 0xB8, 0xF0, 0x96, - 0xEF, 0xF4, 0x47, 0x5F, 0x8E, 0xCA, 0x46, 0x85, 0x3C, 0x94, - 0x9E, 0xDE, 0x09, 0x40, 0x45, 0xB3, 0x69, 0xF1, 0x8F, 0x90, - 0xF5, 0x5C, 0x22, 0x69, 0xBF, 0x5F, 0x11, 0x66, 0xD9, 0xDC, - 0x37, 0x6A, 0x2C, 0xAF, 0x72, 0x66, 0xC8, 0x28, 0xEA, 0x59, - 0x71, 0xB1, 0x7F, 0x10, 0xA5, 0xBC, 0x42, 0x99, 0xF6, 0xD6, - 0xB4, 0xC4, 0x18, 0x49, 0x72, 0x37, 0xF3, 0xCD, 0x01, 0xD6, - 0xAB, 0x2A, 0xFE, 0x1A, 0xBC, 0x52, 0x15, 0x38, 0x30, 0xF2, - 0x4F, 0xC0, 0xD3, 0x5B, 0x91, 0x5A, 0x55, 0xD1, 0x82, 0x5A, - 0x50, 0xE8, 0x16, 0x8C, 0x3D, 0xC8, 0x97, 0x3D, 0x2A, 0xA9, - 0xF3, 0xEA, 0x48, 0x57, 0x51, 0x29, 0xB0, 0x81, 0x4D, 0x6B, - 0x69, 0xFE, 0xF8, 0xA8, 0xE0, 0x5F, 0xF4, 0x98, 0xBE, 0x3D, - 0x39, 0xB6, 0x10, 0x3E, 0x70, 0x16, 0x60, 0x46, 0xA1, 0x74, - 0x5C, 0xF5, 0x53, 0x24, 0xF4, 0x56, 0x33, 0x97, 0x18, 0xB6, - 0x4A, 0x91, 0xE1, 0xF4, 0x36, 0x11, 0x80, 0xCF, 0xDE, 0xE3, - 0x7C, 0x8C, 0x27, 0xC9, 0x29, 0xA6, 0xCC, 0xA2, 0xE3, 0x61, - 0xED, 0x46, 0x10, 0x0D, 0x43, 0x1D, 0x63, 0xB2, 0x4B, 0xC0, - 0xFF, 0x79, 0x2D, 0x6D, 0xD1, 0x0E, 0xD4, 0x73, 0x24, 0xE2, - 0xFE, 0x07, 0x15, 0xC4, 0xB3, 0xFC, 0xDA, 0x14, 0x44, 0x81, - 0x89, 0xA9, 0x16, 0xEF, 0x8C, 0x60, 0xEE, 0x2D, 0xBC, 0x81, - 0xF1, 0xD8, 0xE1, 0x37, 0x5D, 0xC0, 0xD2, 0xA5, 0x8C, 0xF9, - 0xAF, 0xAA, 0xBE, 0xF6, 0x46, 0x65, 0xEB, 0x53, 0x97, 0x2F, - 0xDA, 0x28, 0x66, 0x29, 0x67, 0x1F, 0x1F, 0x0A, 0x61, 0x61, - 0x66, 0x61, 0xF2, 0xA7, 0x1F, 0x1C, 0x30, 0x1F, 0xDD, 0xDE, - 0xAB, 0xC7, 0x6C, 0x1C, 0xED, 0xC8, 0xDC, 0x09, 0xBA, 0xF9, - 0x93, 0x76, 0x4C, 0xCC, 0xAE, 0xF5, 0x2D, 0xA4, 0xAB, 0x3F, - 0xA0, 0x42, 0x4E, 0x8F, 0x28, 0x87, 0xE1, 0x64, 0xCA, 0xF4, - 0xB6, 0xAC, 0x39, 0x1E, 0x1C, 0xF2, 0x69, 0xFF, 0x30, 0x3B, - 0x2F, 0x5C, 0xB2, 0x82, 0xD8, 0x28, 0x2D, 0xA8, 0x2C, 0xDA, - 0x6D, 0x76, 0x38, 0xFC, 0x50, 0x6F, 0xA4, 0xB9, 0x52, 0x9F, - 0xD5, 0xFA, 0x94, 0xDC, 0x54, 0xED, 0xD9, 0x10, 0x6F, 0xDA, - 0x7E, 0x5E, 0x8A, 0xFB, 0xB3, 0x68, 0xD0, 0xD1, 0x25, 0x77, - 0x7E, 0x8B, 0x91, 0x68, 0x4E, 0xF4, 0x74, 0x99, 0x77, 0xB8, - 0x5C, 0xCE, 0xCC, 0x3D, 0x54, 0xA8, 0xD8, 0x4F, 0x01, 0x30, - 0x37, 0xB0, 0x82, 0x42, 0xB9, 0xB1, 0xBF, 0x83, 0xC8, 0xB6, - 0x40, 0x7F, 0xF2, 0xD8, 0x3C, 0xBD, 0x63, 0xCB, 0x23, 0x34, - 0xA4, 0xFB, 0x4C, 0xE0, 0x8B, 0x85, 0xA4, 0xA9, 0x7B, 0xA4, - 0x78, 0x86, 0xD4, 0xE9, 0x68, 0xA4, 0x40, 0x8D, 0xBC, 0x56, - 0x44, 0x8B, 0x24, 0x80, 0x6B, 0xC1, 0x84, 0xEC, 0xB3, 0x70, - 0x01, 0x0A, 0xFE, 0xED, 0x7D, 0xD9, 0x7E, 0xAB, 0x89, 0xDB, - 0xE3, 0x90, 0x5C, 0x6A, 0x75, 0x8E, 0x16, 0xF2, 0x0A, 0xFE, - 0x9E, 0x08, 0xC8, 0xB2, 0x35, 0x3C, 0xC3, 0x20, 0x29, 0xD4, - 0x8A, 0xA6, 0x58, 0x25, 0x43, 0x9B, 0x27, 0xAE, 0xBF, 0xC7, - 0x50, 0x82, 0x9F, 0x04, 0x88, 0x4C, 0xB0, 0x4E, 0x38, 0xA5, - 0x84, 0xC1, 0xBA, 0x6A, 0xA7, 0x16, 0x85, 0x76, 0xF5, 0x21, - 0x15, 0x3F, 0x00, 0x2C, 0x0A, 0xBD, 0x18, 0x66, 0x0C, 0xD1, - 0x46, 0x33, 0x1A, 0xF3, 0x85, 0x34, 0x68, 0x49, 0x05, 0x10, - 0x85, 0xF9, 0x61, 0xD6, 0xB6, 0x97, 0xFC, 0xAA, 0x2C, 0xBC, - 0xF1, 0x75, 0xF3, 0xFC, 0x57, 0x20, 0x54, 0xF2, 0x02, 0x5E, - 0xAB, 0xDD, 0x19, 0x31, 0xAB, 0x97, 0x5F, 0x11, 0x4F, 0xCE, - 0x4F, 0xB9, 0xBB, 0xA2, 0x01, 0x51, 0x48, 0x5A, 0x2C, 0x52, - 0xAD, 0x58, 0x00, 0x22, 0x41, 0x4D, 0x24, 0x68, 0x9F, 0xD9, - 0x13, 0x5C, 0x55, 0x0A, 0x62, 0xAD, 0x3E, 0x29, 0x86, 0x34, - 0x3B, 0x2D, 0x34, 0xBE, 0x0A, 0xDB, 0x85, 0x3A, 0x41, 0x2C, - 0x30, 0x56, 0x65, 0x04, 0x0A, 0x20, 0x31, 0x2A, 0xF3, 0x88, - 0x4C, 0x38, 0x64, 0x86, 0x14, 0x06, 0xF5, 0xF0, 0x7F, 0x63, - 0xC1, 0x87, 0x24, 0x39, 0xFB, 0xC0, 0xC2, 0x6B, 0x57, 0xB3, - 0xA9, 0x7C, 0x21, 0xD7, 0x17, 0xB5, 0x23, 0x89, 0x8B, 0x9A, - 0x53, 0xC6, 0x26, 0xD6, 0xC1, 0xD8, 0x3B, 0xD2, 0x30, 0x0B, - 0x30, 0x76, 0xB3, 0x21, 0x2B, 0xCF, 0x64, 0xB8, 0xCD, 0x8C, - 0xB9, 0x33, 0x73, 0xA5, 0x19, 0x5C, 0xBB, 0x4A, 0x6F, 0x9E, - 0xA7, 0x62, 0x61, 0x1C, 0x32, 0xBB, 0x3E, 0x1B, 0x8A, 0xAC, - 0xE5, 0xE1, 0xA9, 0xDD, 0x50, 0xFB, 0x3B, 0xCF, 0xB6, 0x49, - 0x7B, 0xED, 0x1A, 0x7E, 0x8E, 0x73, 0xAE, 0x8B, 0x31, 0x06, - 0x11, 0xC4, 0x84, 0x4C, 0xCA, 0x6D, 0x5A, 0x79, 0x50, 0x2E, - 0x66, 0x90, 0x0A, 0x13, 0x86, 0x15, 0x78, 0x06, 0xAD, 0x5D, - 0x8C, 0x5E, 0xC8, 0x73, 0xB0, 0x82, 0xFB, 0x03, 0xE6, 0x30, - 0xE7, 0x0B, 0x99, 0xF0, 0xD9, 0x8C, 0x2C, 0xFA, 0x34, 0xAB, - 0x8B, 0xDD, 0x06, 0x2F, 0x39, 0xE0, 0x53, 0x37, 0x61, 0x3D, - 0xC3, 0x77, 0x4C, 0x9F, 0x66, 0x95, 0x81, 0x94, 0x0A, 0xE5, - 0xCE, 0x59, 0xA1, 0x83, 0x5C, 0x77, 0xBD, 0xF5, 0xAD, 0xE2, - 0x9C, 0x10, 0x64, 0x22, 0xAD, 0x99, 0x02, 0x3F, 0x6A, 0xB2, - 0x96, 0x2C, 0xF3, 0x21, 0xEB, 0x5A, 0x7D, 0xFC, 0x02, 0x9B, - 0x53, 0x94, 0xB1, 0x88, 0x3E, 0x07, 0x78, 0x31, 0x8F, 0xDF, - 0xDA, 0xAF, 0xB7, 0x55, 0xC9, 0x30, 0x74, 0x61, 0xD1, 0x75, - 0x15, 0xF1, 0x29, 0xB0, 0x8B, 0xD9, 0x19, 0xB3, 0x2E, 0x8C, - 0x3C, 0x4C, 0xED, 0x22, 0x0B, 0x07, 0xEC, 0xA8, 0x2B, 0x26, - 0xBA, 0x2A, 0xE3, 0xEB, 0x91, 0x2C, 0xDF, 0x28, 0xFD, 0xE3, - 0x12, 0x6D, 0xA8, 0x8C, 0xA9, 0xA0, 0x18, 0xAE, 0x18, 0xC4, - 0x05, 0x53, 0xF6, 0xF7, 0x69, 0xEF, 0xBB, 0xF8, 0xFF, 0x55, - 0xD9, 0x4E, 0xA0, 0xC9, 0x58, 0x38, 0x67, 0x31, 0xE7, 0x5C, - 0x46, 0x41, 0x58, 0x26, 0x48, 0x8C, 0x82, 0x91, 0xE4, 0x46, - 0x91, 0xE0, 0xA4, 0x4F, 0xA5, 0xFD, 0x28, 0x14, 0xC8, 0x07, - 0x73, 0xB9, 0x20, 0x7D, 0x94, 0xAF, 0xDC, 0xBF, 0x4A, 0x55, - 0xA8, 0x82, 0xBF, 0x6D, 0x22, 0xD2, 0xFF, 0x18, 0x5E, 0xFB, - 0xC4, 0xDE, 0x8B, 0x12, 0x58, 0x1E, 0x05, 0x51, 0x4A, 0x31, - 0x54, 0x26, 0xA5, 0xFD, 0x36, 0xED, 0x14, 0x80, 0x4E, 0x3F, - 0xB2, 0x4F, 0x43, 0x70, 0xAF, 0x63, 0x77, 0x86, 0x68, 0xF4, - 0x35, 0xC2, 0x4E, 0x57, 0x43, 0x63, 0x06, 0x07, 0x21, 0xCE, - 0x61, 0xDD, 0x5D, 0x1D, 0xA3, 0xF7, 0x24, 0x72, 0xED, 0x73, - 0x6A, 0xA0, 0xE6, 0x9C, 0x1A, 0xA3, 0xCF, 0x98, 0x47, 0xC2, - 0xE1, 0x29, 0x22, 0x1B, 0x7C, 0x14, 0x0E, 0xE2, 0x6B, 0x58, - 0x54, 0xA7, 0x3E, 0x0F, 0x07, 0x1D, 0xAB, 0xFD, 0x1C, 0x1E, - 0xE0, 0x24, 0xCB, 0x2B, 0xC8, 0x7D, 0x90, 0x83, 0x8D, 0x46, - 0x43, 0xB4, 0x30, 0x39, 0x26, 0x29, 0xEE, 0xAF, 0x67, 0x61, - 0x4C, 0x16, 0xF1, 0xF4, 0x01, 0x55, 0x71, 0x30, 0x1B, 0x18, - 0xC2, 0xF3, 0x8A, 0x26, 0x52, 0x63, 0xD0, 0xEA, 0x66, 0x04, - 0xD7, 0xCC, 0x09, 0xF1, 0x66, 0x62, 0xD1, 0x29, 0xFD, 0xCE, - 0x0A, 0x85, 0xD5, 0x2C, 0x5B, 0x0D, 0xC3, 0x53, 0x8F, 0x45, - 0xA1, 0x95, 0xEE, 0xAF, 0xC3, 0xC5, 0xEE, 0xE6, 0xCE, 0x4A, - 0x33, 0xDB, 0x8B, 0x29, 0x79, 0xBC, 0xF7, 0xC5, 0x33, 0xCD, - 0xC1, 0x74, 0x25, 0x69, 0xEC, 0x75, 0xA4, 0x05, 0x1D, 0x6D, - 0x6E, 0xEC, 0x77, 0xDC, 0xF9, 0x08, 0xB1, 0xFA, 0x38, 0x7F, - 0x8E, 0xDF, 0x74, 0x10, 0x27, 0x19, 0x52, 0xAB, 0x6B, 0x08, - 0xEB, 0x51, 0x22, 0xE7, 0x79, 0xDA, 0x9F, 0xC0, 0xD2, 0x5E, - 0x5C, 0x2A, 0xC7, 0xF8, 0x6B, 0xB6, 0x63, 0x06, 0x49, 0xB4, - 0xDD, 0xEB, 0x20, 0x6F, 0x5A, 0x5E, 0x78, 0x79, 0xA5, 0xAF, - 0x35, 0x6D, 0x36, 0xBA, 0xA4, 0x38, 0x98, 0x38, 0xD9, 0x59, - 0x81, 0x16, 0x8C, 0xCE, 0x78, 0xCA, 0xD1, 0x86, 0x8B, 0x3A, - 0xD9, 0xA5, 0x5B, 0x7C, 0x53, 0x24, 0xB8, 0xD2, 0x2B, 0x09, - 0x73, 0x04, 0x87, 0x3E, 0x39, 0x64, 0x42, 0x5A, 0xE1, 0xC8, - 0x72, 0xD5, 0x00, 0x06, 0x06, 0x81, 0x91, 0x7A, 0x12, 0xA1, - 0x91, 0xEC, 0xBF, 0xD6, 0xBC, 0xFD, 0x82, 0xDA, 0xEE, 0x3A, - 0xB7, 0xF1, 0x54, 0xE3, 0xBD, 0xE5, 0xC0, 0x18, 0xE9, 0x5C, - 0x49, 0x0C, 0xFA, 0x64, 0x80, 0x98, 0x5C, 0x44, 0x9B, 0x4A, - 0x48, 0x3E, 0x0C, 0xBE, 0x5E, 0xBB, 0x68, 0xDA, 0x09, 0xD7, - 0x00, 0x51, 0x5B, 0x13, 0x96, 0xC2, 0x8A, 0xCE, 0xB0, 0x8F, - 0xDF, 0x84, 0x77, 0x70, 0x4B, 0x0F, 0x6E, 0xC7, 0x62, 0x47, - 0xFA, 0xA8, 0x35, 0x18, 0x43, 0x93, 0x4C, 0x83, 0x13, 0x45, - 0x74, 0x76, 0x19, 0xA7, 0x71, 0x98, 0x8C, 0x2E, 0xFC, 0xA9, - 0x83, 0x64, 0xD1, 0xA3, 0x95, 0x33, 0x31, 0xDB, 0xA8, 0xC3, - 0xB9, 0x72, 0x80, 0x58, 0xEC, 0xEB, 0xFC, 0xF3, 0x03, 0x44, - 0xDC, 0x11, 0x06, 0x3A, 0x95, 0x81, 0x28, 0xDB, 0xAB, 0x36, - 0xC4, 0x37, 0x0C, 0xD4, 0x6B, 0xAF, 0x04, 0xD0, 0x23, 0x3F, - 0xDD, 0x08, 0x88, 0x06, 0x23, 0x39, 0xCF, 0xB2, 0xCF, 0x13, - 0x27, 0xE1, 0x4E, 0x21, 0xDA, 0x81, 0x58, 0x29, 0x70, 0x2B, - 0x26, 0xB7, 0xA7, 0x69, 0xA1, 0x86, 0xBC, 0xD9, 0x88, 0xED, - 0x70, 0x61, 0x94, 0x2D, 0xCD, 0x47, 0x57, 0xD0, 0xBD, 0x07, - 0x05, 0x7E, 0xA5, 0x35, 0x29, 0x15, 0xFA, 0x62, 0x7E, 0xB7, - 0x2A, 0xEB, 0x4F, 0xC4, 0x0D, 0x6D, 0x2E, 0x6D, 0x8F, 0x53, - 0x7C, 0x0B, 0x62, 0x72, 0xA5, 0x01, 0x5D, 0xD9, 0x52, 0xAF, - 0x60, 0x22, 0x90, 0xD0, 0xE6, 0x37, 0x25, 0x57, 0x73, 0x66, - 0xD5, 0x96, 0x6A, 0x23, 0x75, 0x43, 0xF7, 0x6A, 0xC8, 0x3E, - 0xAC, 0x20, 0xC8, 0x8A, 0xE3, 0xD1, 0xB4, 0x07, 0x87, 0x8E, - 0x3A, 0xEB, 0x43, 0x10, 0x91, 0x7F, 0x17, 0x96, 0x4B, 0x7A, - 0x31, 0x2A, 0x84, 0xFC, 0xFE, 0xB1, 0x26, 0x67, 0xD6, 0xAD, - 0xB8, 0xB7, 0x3D, 0x3A, 0x2F, 0xEE, 0x94, 0x2F, 0x05, 0xF1, - 0xD8, 0x8E, 0xD4, 0x97, 0xAF, 0x36, 0xCE, 0x01, 0x18, 0x0B, - 0x68, 0x41, 0x26, 0xEB, 0x38, 0x2B, 0xF6, 0xD2, 0x8A, 0x5A, - 0x79, 0x02, 0xA1, 0xE4, 0x49, 0x48, 0xCF, 0x55, 0x2B, 0x74, - 0x16, 0x63, 0x27, 0x9D, 0x25, 0xAA, 0x7F, 0x8A, 0x5D, 0x96, - 0x68, 0xF3, 0x58, 0x7C, 0x10, 0xCF, 0x6A, 0xE3, 0xE2, 0x80, - 0x90, 0xD3, 0x39, 0xF5, 0x62, 0x01, 0x33, 0x5F, 0xC2, 0xFD, - 0xAD, 0xE6, 0x2A, 0xB2, 0x3D, 0x89, 0x99, 0x7B, 0x17, 0x35, - 0xE4, 0x5C, 0x62, 0x10, 0x69, 0x10, 0x93, 0x57, 0x92, 0x15, - 0x53, 0xEC, 0x82, 0x17, 0x00, 0xFC, 0x13, 0x49, 0x58, 0x79, - 0x90, 0x36, 0x0D, 0x50, 0xA5, 0xFE, 0xAE, 0xE1, 0xB3, 0xAF, - 0x40, 0x98, 0x3C, 0xB7, 0xAB, 0xC9, 0x0B, 0x2B, 0xE8, 0x31, - 0x71, 0x0D, 0x47, 0xE1, 0xE0, 0x3D, 0xCB, 0xB0, 0x3E, 0x44, - 0x00, 0x18, 0x66, 0xD5, 0x44, 0xEF, 0x58, 0x6A, 0xC3, 0x98, - 0x86, 0x19, 0xBA, 0xCE, 0x24, 0xF0, 0x9A, 0xED, 0x55, 0xA9, - 0x1F, 0x52, 0xB2, 0xBA, 0x1A, 0x2C, 0x71, 0x9F, 0xD7, 0xE6, - 0xA1, 0x01, 0x64, 0x8B, 0x22, 0x22, 0x23, 0xC8, 0x2A, 0xBA, - 0x13, 0x5A, 0xDD, 0xC4, 0x0C, 0x1A, 0x3C, 0x4F, 0x1E, 0x0B, - 0x5B, 0xB5, 0x45, 0xA3, 0xDD, 0x4D, 0xE9, 0x00, 0x06, 0x60, - 0x59, 0xFC, 0x48, 0xB2, 0x3E, 0x32, 0xBF, 0xF8, 0x74, 0x4E, - 0x65, 0x9F, 0x89, 0x8D, 0xE4, 0x0C, 0xC1, 0x89, 0xCF, 0x19, - 0xF0, 0xBC, 0x75, 0xDC, 0xE4, 0xEA, 0x23, 0x18, 0x23, 0xC2, - 0xD2, 0xA4, 0x96, 0xA6, 0xC2, 0x73, 0x41, 0x1E, 0xD8, 0x9D, - 0x02, 0x02, 0x35, 0x16, 0x61, 0x9B, 0x6F, 0xCC, 0x16, 0x80, - 0x2B, 0xA5, 0xE2, 0x9B, 0x63, 0x9B, 0x4E, 0x75, 0xBD, 0xBD, - 0xF3, 0x36, 0x16, 0x53, 0x6B, 0x34, 0x33, 0xF4, 0xBC, 0x05, - 0x79, 0x8A, 0x1F, 0x23, 0xD8, 0x36, 0xCC, 0xDB, 0x37, 0x5A, - 0x1E, 0xCE, 0x6D, 0x27, 0x7B, 0x6C, 0x66, 0x11, 0xE3, 0x96, - 0xAD, 0xC3, 0xF9, 0x57, 0xF9, 0xA7, 0x4C, 0x4F, 0x8E, 0x97, - 0x70, 0xB1, 0x70, 0xE9, 0x77, 0xF0, 0xC2, 0xD0, 0x79, 0x12, - 0x79, 0x3F, 0xDB, 0x71, 0x66, 0x48, 0xDB, 0x5A, 0xFC, 0xA7, - 0x8E, 0xE4, 0x1A, 0x93, 0xFE, 0x49, 0xF5, 0x7D, 0xEF, 0xC4, - 0x4B, 0xC1, 0x10, 0x2A, 0xD6, 0xF0, 0x5D, 0xC4, 0x80, 0x8B, - 0x9C, 0x2E, 0x44, 0xFB, 0x71, 0xD3, 0xA3, 0x80, 0xFB, 0x77, - 0x60, 0x16, 0xAD, 0x0B, 0xEC, 0x75, 0x9A, 0x58, 0x4B, 0x6E, - 0xD8, 0xFD, 0xE9, 0x41, 0x46, 0x85, 0x43, 0xFD, 0x82, 0x53, - 0x51, 0x65, 0xF8, 0xD0, 0x26, 0x2B, 0xF2, 0xF9, 0xE9, 0x26, - 0xD7, 0x15, 0x84, 0x31, 0x80, 0xAE, 0xFD, 0xA5, 0x30, 0x65, - 0xEE, 0x52, 0xCA, 0x3C, 0x76, 0x16, 0x91, 0x5A, 0x26, 0x49, - 0x1A, 0x28, 0xC7, 0x81, 0x10, 0x95, 0xB8, 0x96, 0x09, 0x50, - 0x6D, 0xB1, 0x64, 0xA2, 0x87, 0xCF, 0x38, 0x3C, 0x3C, 0x6E, - 0x0B, 0x96, 0x97, 0xFC, 0x81, 0xBD, 0x7D, 0xE7, 0xCC, 0xB6, - 0xF7, 0xE8, 0x15, 0x05, 0xAF, 0xDE, 0x1C, 0x68, 0xC0, 0xCF, - 0xF8, 0x68, 0x94, 0x90, 0x7B, 0x7D, 0x98, 0x57, 0xDC, 0x86, - 0x6D, 0x69, 0xD6, 0x98, 0x62, 0x0F, 0x38, 0x99, 0x93, 0x99, - 0x55, 0xD6, 0xA5, 0x8C, 0x94, 0x62, 0xCB, 0xD9, 0xE8, 0xA4, - 0x7C, 0xDF, 0x21, 0xF4, 0x36, 0x65, 0xCF, 0x3F, 0xE4, 0x10, - 0xA5, 0xB4, 0x71, 0x08, 0x65, 0x98, 0x59, 0x70, 0x19, 0x7E, - 0x27, 0x13, 0x71, 0x3F, 0xD2, 0x91, 0x20, 0xFF, 0x53, 0xDB, - 0xD2, 0xD4, 0x07, 0x3A, 0x49, 0x72, 0x05, 0x66, 0xED, 0x7D, - 0xBC, 0x61, 0x70, 0x7F, 0x64, 0x41, 0xDD, 0xB3, 0x1B, 0x03, - 0xB8, 0x20, 0xE1, 0x5D, 0x07, 0x39, 0xFC, 0xD2, 0x30, 0x72, - 0xE8, 0x0F, 0xA7, 0xA2, 0x71, 0xE8, 0x3D, 0xD9, 0x2B, 0x5B, - 0xB4, 0x97, 0x2B, 0xC3, 0x58, 0xE1, 0x2B, 0x0F, 0xAA, 0x8C, - 0x5A, 0x72, 0xC7, 0xBB, 0xB6, 0x59, 0x2B, 0x73, 0x39, 0x9A, - 0x20, 0xE5, 0x9A, 0x70, 0x30, 0x7B, 0x28, 0xBE, 0xD6, 0x6A, - 0x04, 0x18, 0x41, 0xEF, 0x18, 0xCD, 0xB5, 0x69, 0xB6, 0x00, - 0x50, 0xEE, 0xF9, 0x45, 0x2F, 0x86, 0xEE, 0x04, 0xBE, 0xF8, - 0x88, 0x9E, 0x0D, 0xAC, 0x1B, 0xA9, 0xD1, 0xC1, 0xA5, 0x3E, - 0xF6, 0xD9, 0x78, 0x99, 0x9D, 0x2E, 0x26, 0x6C, 0xCA, 0x7C, - 0x4C, 0xC7, 0xAF, 0xAB, 0xF0, 0xBB, 0x93, 0x32, 0x03, 0x22, - 0xAF, 0x27, 0x6A, 0x9F, 0x53, 0x77, 0xA9, 0x6C, 0x83, 0xA2, - 0x46, 0x15, 0x61, 0x6C, 0xB3, 0x08, 0x6F, 0x5B, 0x85, 0x73, - 0x8A, 0xCD, 0x8A, 0xB0, 0x70, 0xAC, 0xA5, 0x22, 0x18, 0x87, - 0x54, 0x91, 0x6B, 0x34, 0x7F, 0x0B, 0x4E, 0xCA, 0x44, 0xB3, - 0xBE, 0xB0, 0x77, 0x28, 0x85, 0x73, 0xDD, 0x29, 0x70, 0x53, - 0xD9, 0xA2, 0x4F, 0x12, 0xCB, 0x41, 0xFD, 0x99, 0x27, 0xC7, - 0xA9, 0xCF, 0xB7, 0x5B, 0xFB, 0xCC, 0x77, 0xBA, 0x12, 0xE1, - 0xD6, 0xF6, 0x7C, 0x22, 0xB4, 0xED, 0xB0, 0xA0, 0x71, 0x59, - 0xD2, 0xF3, 0x14, 0xB2, 0x7C, 0x4A, 0x0A, 0xD6, 0x43, 0x10, - 0xA0, 0xF6, 0xC0, 0x6F, 0xB4, 0x31, 0x8F, 0x7B, 0xF8, 0x5A, - 0xC9, 0x91, 0x0F, 0x7A, 0xE5, 0xDF, 0x29, 0x11, 0x66, 0xFF, - 0x4C, 0x73, 0xA6, 0xC7, 0xA0, 0xCC, 0x7B, 0x73, 0x79, 0x36, - 0x1D, 0x5E, 0x7C, 0xE2, 0xC9, 0xF7, 0x56, 0xC4, 0x88, 0x71, - 0xC1, 0x03, 0xEE, 0xE7, 0xE0, 0xEE, 0x12, 0xD7, 0x3D, 0x3A, - 0xB2, 0x91, 0x51, 0xE1, 0x18, 0xFE, 0x66, 0x22, 0x84, 0xA6, - 0xC3, 0xD2, 0x54, 0xE9, 0xE5, 0xF8, 0xDB, 0xF1, 0xF9, 0x6A, - 0x01, 0x61, 0xCF, 0x3D, 0xDA, 0x89, 0x5B, 0xED, 0x89, 0x10, - 0xBA, 0x18, 0xB8, 0xBA, 0x66, 0x38, 0x0D, 0x37, 0xEC, 0x1E, - 0xF7, 0x06, 0xD6, 0xC0, 0x84, 0x06, 0x2F, 0x43, 0xBD, 0x50, - 0xA0, 0x05, 0x9B, 0x50, 0xCD, 0xBB, 0xB7, 0x93, 0xF0, 0x70, - 0x50, 0xB7, 0x03, 0x0F, 0x27, 0x70, 0x47, 0x8E, 0xEB, 0x14, - 0xE0, 0x81, 0xBC, 0x7F, 0xA5, 0x60, 0xB0, 0x09, 0xCA, 0x38, - 0xCB, 0x59, 0x85, 0x49, 0xB3, 0xD4, 0x29, 0x50, 0xE1, 0x04, - 0xBD, 0x9F, 0x6C, 0xA5, 0x76, 0xCB, 0xE6, 0x79, 0xED, 0xDD, - 0xB8, 0x98, 0xA9, 0x94, 0xDD, 0xD3, 0x2E, 0xE0, 0xEA, 0xCD, - 0xD3, 0x34, 0xDA, 0x78, 0xBE, 0x7A, 0xC9, 0x8C, 0xD6, 0x12, - 0x5B, 0xD0, 0x36, 0x11, 0x79, 0x52, 0xCA, 0xA1, 0xCC, 0x3D, - 0x5B, 0x1F, 0x35, 0x80, 0xCC, 0x56, 0xDA, 0xC9, 0x88, 0xB7, - 0xD3, 0x28, 0x86, 0x6F, 0x4E, 0x20, 0x56, 0x56, 0x62, 0x12, - 0x79, 0xDA, 0x3F, 0x75, 0xEC, 0x89, 0xDC, 0x90, 0x44, 0xAE, - 0xB8, 0x0E, 0x34, 0x76, 0xF9, 0xAE, 0xDF, 0x2C, 0x28, 0x0F, - 0xCF, 0x28, 0x0B, 0x7B, 0x8A, 0xC4, 0x9B, 0x0B, 0x3C, 0x3E, - 0xC2, 0x70, 0x88, 0x71, 0xED, 0x3B, 0x3D, 0x61, 0x73, 0xDC, - 0x1B, 0x1A, 0x89, 0x16, 0xE2, 0x36, 0x50, 0x96, 0x38, 0x44, - 0xB1, 0xB6, 0x23, 0xB1, 0x83, 0x51, 0x43, 0x7C, 0x37, 0x9C, - 0x83, 0xDB, 0x63, 0x3E, 0x02, 0x42, 0xFA, 0xE9, 0x0B, 0x22, - 0xCB, 0xA5, 0x1F, 0x09, 0x03, 0x1C, 0xD0, 0xAD, 0xCB, 0xEE, - 0xB5, 0x3F, 0xFC, 0xCD, 0x80, 0x04, 0x63, 0x44, 0x4F, 0x3F, - 0x2B, 0x17, 0x66, 0xE0, 0xA7, 0x1E, 0xA2, 0xB5, 0xE3, 0xD3, - 0x23, 0x76, 0xF9, 0x75, 0x7C, 0x39, 0x5C, 0x6A, 0x64, 0xF8, - 0x61, 0xDE, 0x66, 0x3F, 0xCD, 0x4F, 0x06, 0xEF, 0x9C, 0xCA, - 0x43, 0xA9, 0x32, 0x30, 0xDC, 0xB8, 0xA2, 0xE0, 0xAA, 0xEB, - 0x4D, 0x30, 0x8D, 0x0C, 0xD1, 0x5E, 0x04, 0xEE, 0xED, 0x46, - 0x07, 0x9C, 0xF4, 0xD8, 0xD5, 0x78, 0x9A, 0x51, 0x93, 0xC6, - 0x95, 0x5C, 0x12, 0x48, 0x2B, 0x92, 0x7A, 0xE4, 0x57, 0x3D, - 0x37, 0xEC, 0xA0, 0x19, 0xEC, 0x0A, 0x45, 0x0B, 0xFE, 0x9F, - 0x5F, 0xA0, 0xB3, 0x05, 0xEE, 0xF9, 0x87, 0x76, 0x5C, 0xC1, - 0xAD, 0x92, 0x79, 0x50, 0xAC, 0x70, 0xB6, 0xE8, 0xBB, 0x7C, - 0xCA, 0xC2, 0x49, 0xAD, 0xB0, 0xDA, 0xD0, 0x28, 0x90, 0xC2, - 0xEE, 0x3D, 0x4C, 0xCD, 0xC8, 0x41, 0x89, 0x5C, 0x65, 0xB9, - 0x1C, 0xCA, 0x67, 0x7B, 0xEF, 0x0D, 0x7B, 0x69, 0x4B, 0x8E, - 0x51, 0x0D, 0xF7, 0x70, 0xB7, 0xB3, 0x4E, 0xC8, 0x87, 0x8D, - 0xD1, 0xDD, 0x20, 0x11, 0x3C, 0x34, 0xA3, 0x3B, 0x6F, 0xDD, - 0xF5, 0xB2, 0xB1, 0x21, 0x9A, 0xE0, 0x4A, 0xF0, 0xB9, 0xEB, - 0x64, 0xDB, 0xC6, 0xD6, 0x64, 0x8F, 0x1A, 0x2C, 0x40, 0x0A, - 0x24, 0xF4, 0x0C, 0x0F, 0x60, 0x04, 0xBA, 0x9D, 0x3A, 0xE7, - 0x05, 0x58, 0xB5, 0x29, 0xD4, 0xD3, 0x64, 0xED, 0xCE, 0x47, - 0x7B, 0xB0, 0x6E, 0xCC, 0x2F, 0x46, 0x3A, 0xFE, 0x11, 0xC6, - 0x6B, 0x91, 0x51, 0x6A, 0x17, 0xCD, 0x03, 0x35, 0x0E, 0x1C, - 0x0E, 0x8B, 0xDD, 0x46, 0x4F, 0x5D, 0x9A, 0x5C, 0xE1, 0x14, - 0x99, 0xE8, 0xF2, 0xA4, 0xED, 0xCF, 0x6F, 0xC6, 0xC1, 0x67, - 0x36, 0x49, 0x1F, 0x1E, 0x42, 0x92, 0x4D, 0x32, 0x05, 0x4E, - 0xA6, 0xD7, 0xC0, 0xEC, 0xB0, 0x3E, 0xFD, 0xA1, 0xA7, 0x08, - 0x6B, 0xE8, 0x7F, 0xCD, 0xF8, 0x3C, 0x53, 0x58, 0x4C, 0x97, - 0xE6, 0x8D, 0xFE, 0xA9, 0x49, 0x61, 0xD1, 0xF0, 0xA0, 0xC7, - 0xB4, 0x4F, 0xBE, 0xDD, 0x90, 0x92, 0x0B, 0xA0, 0x5E, 0x69, - 0xAC, 0xDA, 0x26, 0x99, 0xF8, 0xE3, 0x07, 0xB5, 0xB9, 0xB7, - 0x48, 0xC7, 0xA3, 0x64, 0x3E, 0xA0, 0xB6, 0xC1, 0xF8, 0x6E, - 0x23, 0xA3, 0x11, 0x52, 0xA8, 0x26, 0xBD, 0x1C, 0xAD, 0xEB, - 0xF7, 0xDF, 0xC6, 0x35, 0xB4, 0x92, 0xE5, 0xB0, 0x5B, 0x53, - 0x55, 0xAA, 0x6E, 0xAD, 0x36, 0x4B, 0xF0, 0xE5, 0x9E, 0x32, - 0xB6, 0xFF, 0x1C, 0x01, 0x35, 0x20, 0x5E, 0xAD, 0x3E, 0xA3, - 0x01, 0x5D, 0xA0, 0xC5, 0x1B, 0xC8, 0x69, 0xB8, 0xF2, 0x2B, - 0x2B, 0x69, 0xC4, 0x4E, 0xA3, 0xC6, 0x1C, 0xFE, 0xCC, 0x0C, - 0x79, 0x6E, 0xDD, 0xD4, 0x59, 0x93, 0x51, 0xA2, 0x41, 0x3A, - 0x7A, 0x7D, 0x19, 0x5C, 0x1A, 0x91, 0x3C, 0x68, 0x00, 0x42, - 0x58, 0x51, 0x26, 0x11, 0x1A, 0x1E, 0xDE, 0x3B, 0x64, 0x16, - 0xBC, 0xDC, 0x5A, 0xF7, 0x7E, 0x80, 0x04, 0x63, 0xED, 0xDB, - 0x68, 0x74, 0xC2, 0x6B, 0x36, 0x67, 0xFC, 0x81, 0xB3, 0x64, - 0xBC, 0xAC, 0xA4, 0x56, 0x55, 0x77, 0x86, 0x74, 0xE2, 0x68, - 0x02, 0xD5, 0x5A, 0x84, 0x8F, 0x0E, 0x7F, 0xA1, 0xE9, 0xA5, - 0x30, 0xEB, 0xB4, 0x3E, 0x31, 0x09, 0x7F, 0xE2, 0x21, 0x35, - 0x4F, 0xFA, 0x61, 0xD2, 0x42, 0xB5, 0xCC, 0x31, 0xDE, 0x9C, - 0xDD, 0x39, 0x71, 0x90, 0x69, 0x9C, 0xF3, 0x7B, 0x91, 0xB1, - 0x65, 0x44, 0x10, 0xEC, 0x5C, 0x31, 0xF5, 0xA5, 0x37, 0xFF, - 0x52, 0xDF, 0x21, 0x85, 0x8A, 0x08, 0x77, 0xD7, 0xEE, 0xCC, - 0xD8, 0x58, 0xEF, 0x5B, 0xDD, 0x12, 0xC0, 0x4E, 0xC2, 0x20, - 0xAD, 0x5E, 0x74, 0x37, 0xE0, 0x70, 0x1B, 0xBA, 0xA3, 0x84, - 0x39, 0x2C, 0x4F, 0x63, 0x77, 0x69, 0x6C, 0x60, 0x69, 0x00, - 0xF0, 0xCE, 0x19, 0x29, 0x62, 0xDA, 0x10, 0xD9, 0x15, 0x79, - 0xC5, 0x2B, 0xB0, 0xB3, 0x97, 0x8C, 0x98, 0x83, 0x9F, 0x25, - 0x3F, 0x56, 0x1F, 0x2C, 0x63, 0x77, 0xFA, 0xDB, 0x27, 0xDF, - 0x94, 0xAE, 0x08, 0x44, 0x75, 0x8A, 0xE8, 0x91, 0x72, 0xB0, - 0xD0, 0x93, 0xC5, 0x7B, 0xB1, 0xD0, 0xEB, 0xD8, 0xDD, 0x88, - 0x29, 0xF8, 0x36, 0xE7, 0x7C, 0xFD, 0x88, 0xFE, 0xA1, 0xEE, - 0x12, 0x9A, 0x0E, 0x84, 0x75, 0x15, 0xA8, 0xA0, 0xD7, 0xBC, - 0x72, 0x75, 0x7D, 0x4E, 0xDF, 0xEE, 0x30, 0x30, 0x23, 0x6D, - 0xCC, 0xE5, 0xD7, 0xFD, 0x11, 0xE0, 0x87, 0x65, 0xDE, 0xAA, - 0xF4, 0x2C, 0x64, 0x74, 0x1A, 0x0C, 0x7A, 0x0A, 0x5B, 0x85, - 0xF3, 0x35, 0xB8, 0x41, 0x27, 0x14, 0xFC, 0x2A, 0x8D, 0x28, - 0xD0, 0xA7, 0xDB, 0xB0, 0xD9, 0x5A, 0xA9, 0x0F, 0x0B, 0x2F, - 0xE0, 0x8E, 0x37, 0x82, 0x5E, 0x8E, 0x1E, 0x2F, 0xC2, 0xA6, - 0xF5, 0x89, 0x54, 0x77, 0x49, 0x49, 0xDC, 0xF4, 0x03, 0xF2, - 0x04, 0xD6, 0xC0, 0x43, 0xB1, 0x13, 0x2B, 0x0C, 0xC2, 0x14, - 0x93, 0x5A, 0x90, 0x20, 0x87, 0xA0, 0x4A, 0xB2, 0xD7, 0x25, - 0x81, 0x79, 0x3C, 0x9C, 0xF6, 0x92, 0xBB, 0x26, 0xB0, 0x25, - 0x93, 0x05, 0x60, 0xEC, 0x56, 0x3C, 0x92, 0x41, 0x63, 0x52, - 0x0F, 0x95, 0x06, 0x7D, 0xE8, 0x46, 0x90, 0x39, 0x69, 0xEA, - 0x6B, 0xA6, 0x64, 0x09, 0x7B, 0x2F, 0x34, 0xE0, 0x21, 0x29, - 0xDA, 0xE3, 0xCF, 0xFE, 0xA7, 0x8E, 0x14, 0x3A, 0xD7, 0x53, - 0x26, 0xD7, 0x82, 0x0E, 0x2A, 0x00, 0x43, 0xEB, 0x6A, 0x23, - 0x75, 0x28, 0xD0, 0x9B, 0x85, 0xE0, 0xFB, 0x14, 0x19, 0xF3, - 0x6A, 0x73, 0x6C, 0x97, 0x0E, 0x21, 0xFC, 0x0F, 0x26, 0xC5, - 0xCE, 0xB7, 0xC6, 0x59, 0xA2, 0xE6, 0x4C, 0xF4, 0xC7, 0xBB, - 0x9B, 0xA8, 0xFA, 0x12, 0xC7, 0xDA, 0x33, 0x26, 0x69, 0x83, - 0x49, 0xA8, 0x0A, 0x3E, 0xF0, 0xD4 +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY + +static const unsigned char bench_dilithium_level3_pubkey[] = { + 0x15, 0xc9, 0xe5, 0x53, 0x2f, 0xd8, 0x1f, 0xb4, 0xa3, 0x9f, + 0xae, 0xad, 0xb3, 0x10, 0xd0, 0x72, 0x69, 0xd3, 0x02, 0xf3, + 0xdf, 0x67, 0x5a, 0x31, 0x52, 0x19, 0xca, 0x39, 0x27, 0x77, + 0x61, 0x6d, 0x0f, 0xc1, 0x33, 0x26, 0x09, 0xf0, 0xf9, 0x4d, + 0x12, 0x7a, 0xef, 0xf7, 0x21, 0x26, 0x2c, 0xe0, 0xe2, 0x92, + 0x1f, 0x9d, 0xd1, 0xaa, 0xaf, 0x08, 0x14, 0xf2, 0xaa, 0x24, + 0x99, 0x0f, 0x20, 0x57, 0x35, 0x04, 0x32, 0x96, 0x8e, 0x6e, + 0x10, 0x64, 0xe3, 0xe3, 0x57, 0x26, 0x33, 0x32, 0x7b, 0xe4, + 0x18, 0x41, 0x77, 0xd3, 0x24, 0x63, 0x3d, 0x11, 0xea, 0xdc, + 0xbe, 0x59, 0xff, 0x8d, 0xc2, 0xe4, 0xc7, 0x04, 0xf3, 0xd4, + 0xe0, 0x1d, 0x5e, 0x09, 0x46, 0xbf, 0x02, 0x05, 0xc7, 0xa6, + 0xb7, 0x82, 0x40, 0x1f, 0x55, 0xe9, 0x77, 0x82, 0xc0, 0xcc, + 0x86, 0x99, 0x19, 0x99, 0xa2, 0xc9, 0x1b, 0x4f, 0xdd, 0x49, + 0x4c, 0x78, 0x0a, 0x58, 0xb8, 0xf0, 0x23, 0xac, 0x1a, 0x71, + 0x57, 0x6d, 0xd6, 0x3a, 0x3a, 0x6f, 0x93, 0xb3, 0x2b, 0x09, + 0xbe, 0xec, 0x7b, 0x5b, 0xf7, 0x3a, 0xed, 0xf9, 0xd0, 0xb1, + 0xfe, 0x9f, 0x9b, 0xec, 0x11, 0xb6, 0x6b, 0xd1, 0xb6, 0x00, + 0x72, 0x7f, 0x68, 0x9a, 0x61, 0xa5, 0xf5, 0x6e, 0xe9, 0x46, + 0xa4, 0x82, 0x08, 0x9f, 0x50, 0x4c, 0x75, 0xc3, 0x48, 0x85, + 0x76, 0x39, 0xea, 0x0c, 0xf2, 0xe8, 0x7e, 0x48, 0x69, 0xd9, + 0x6f, 0x9a, 0x89, 0x7d, 0x98, 0xc1, 0x16, 0xdc, 0x2f, 0xc7, + 0x0a, 0x11, 0xa8, 0xbb, 0xe7, 0x91, 0xb1, 0x0f, 0x0e, 0xf0, + 0xb4, 0xc8, 0x41, 0x7e, 0x62, 0x9e, 0x3c, 0x30, 0x4c, 0xbc, + 0x4c, 0xeb, 0x37, 0xaf, 0x48, 0x72, 0x59, 0x64, 0x8e, 0xfb, + 0x77, 0x11, 0x28, 0xdd, 0x30, 0x52, 0x8e, 0x69, 0x8c, 0x9f, + 0x3d, 0xec, 0xdf, 0xa7, 0x5f, 0x42, 0x18, 0xda, 0xba, 0x1a, + 0x96, 0x91, 0x7d, 0x62, 0xd5, 0x52, 0xff, 0x44, 0xc9, 0x1d, + 0x29, 0xa6, 0xb9, 0x03, 0x9a, 0x26, 0x26, 0xcf, 0x57, 0x40, + 0x70, 0x7e, 0x2b, 0xbd, 0xf0, 0x81, 0x71, 0x0f, 0x0b, 0x2e, + 0x9b, 0x03, 0xba, 0x31, 0x41, 0x68, 0x37, 0xc8, 0xff, 0xea, + 0xc4, 0x73, 0xa5, 0xf9, 0xc2, 0x92, 0x78, 0x0c, 0xe7, 0xfd, + 0x5d, 0xb2, 0x01, 0xb5, 0x8d, 0xeb, 0x64, 0xd4, 0x14, 0xea, + 0x7a, 0xd1, 0x42, 0xc8, 0x99, 0xe4, 0x7d, 0x5b, 0x7e, 0x3b, + 0x8f, 0xab, 0x82, 0x12, 0xdf, 0xbb, 0xa1, 0x45, 0x30, 0xc9, + 0x0f, 0xb9, 0xe5, 0xba, 0xe6, 0x8a, 0xf3, 0x78, 0x61, 0xcc, + 0x9f, 0xe1, 0x46, 0x2a, 0x9a, 0x18, 0x0e, 0x2a, 0x57, 0xf3, + 0xe5, 0x56, 0xd1, 0x42, 0x48, 0xe1, 0x5a, 0x8e, 0x33, 0xce, + 0x19, 0xe5, 0x3e, 0x7f, 0x00, 0x70, 0x9c, 0x4c, 0xd3, 0xe1, + 0x0c, 0xa1, 0x7e, 0xd4, 0xa9, 0x9e, 0x8b, 0xe2, 0xf0, 0xac, + 0xdb, 0xa6, 0x72, 0x75, 0x67, 0xa6, 0x57, 0xed, 0x79, 0x2e, + 0xca, 0x8d, 0xeb, 0x9b, 0x9e, 0xb7, 0xbf, 0x30, 0x02, 0x2b, + 0xb3, 0x43, 0x89, 0x9b, 0xa8, 0x88, 0xa5, 0xbb, 0x33, 0xd9, + 0x99, 0x30, 0x7c, 0xc7, 0xd4, 0x28, 0x5e, 0x5e, 0x3f, 0x9d, + 0x6d, 0x35, 0x75, 0x33, 0x8e, 0xff, 0x84, 0x2e, 0x2d, 0xda, + 0xf0, 0xff, 0x70, 0xe5, 0xb5, 0x62, 0x96, 0x33, 0x3a, 0xd9, + 0xb5, 0x82, 0x25, 0x81, 0x81, 0x40, 0x5d, 0x4f, 0x11, 0x86, + 0x63, 0x1a, 0x06, 0xc1, 0x67, 0xc7, 0x49, 0x03, 0xc7, 0xe4, + 0x6f, 0xb4, 0x13, 0x3e, 0x57, 0x62, 0xfd, 0x8a, 0xc6, 0x2b, + 0x65, 0x5b, 0xa4, 0x29, 0x57, 0x8d, 0xde, 0xa5, 0xee, 0x32, + 0xc2, 0x76, 0x03, 0xca, 0xce, 0xc1, 0x48, 0xec, 0x45, 0xcf, + 0x30, 0x21, 0x28, 0x7f, 0x10, 0x47, 0xd2, 0xdb, 0xee, 0xca, + 0x5b, 0x0f, 0xd5, 0x39, 0x3a, 0xc3, 0xa6, 0x78, 0xb2, 0x15, + 0xaf, 0x82, 0x3c, 0x2f, 0xc4, 0x51, 0x5c, 0x52, 0xad, 0xf2, + 0x89, 0x92, 0x8e, 0xf3, 0x50, 0x38, 0xed, 0xf8, 0xc9, 0x14, + 0x4c, 0xe4, 0xa3, 0x9a, 0xaf, 0xc4, 0x5c, 0xf3, 0x9f, 0xc3, + 0xa3, 0xc0, 0xbe, 0x45, 0x1b, 0x21, 0x63, 0xfa, 0xe0, 0xe0, + 0x91, 0x2b, 0x42, 0xca, 0x91, 0xfb, 0x5e, 0x97, 0x9a, 0x0a, + 0xd4, 0x88, 0xba, 0xb8, 0x22, 0xc6, 0xbf, 0x56, 0x58, 0x1e, + 0x92, 0xa9, 0x9d, 0xa7, 0xed, 0xc9, 0xab, 0x54, 0x4f, 0x75, + 0x8d, 0x42, 0xc1, 0xe1, 0x61, 0xd0, 0x91, 0x9a, 0x3a, 0x40, + 0x9a, 0xa3, 0xfb, 0x7b, 0x4e, 0xf0, 0x85, 0xf0, 0xdc, 0x40, + 0x72, 0x9f, 0x05, 0xa8, 0xbe, 0x95, 0x5a, 0x7f, 0xba, 0x75, + 0x00, 0x6e, 0x95, 0x76, 0xbd, 0xb2, 0x40, 0xf5, 0xb0, 0x64, + 0x0a, 0x2f, 0x06, 0x3d, 0x9f, 0xac, 0x6a, 0xa5, 0x46, 0x5a, + 0x85, 0xa4, 0x6f, 0xee, 0x27, 0xa0, 0xeb, 0x5f, 0x1f, 0x91, + 0xbd, 0x2b, 0x02, 0x16, 0xdf, 0x74, 0x97, 0x2c, 0xd0, 0xa8, + 0x9f, 0x3a, 0x7b, 0xdf, 0x3e, 0x98, 0x4a, 0x91, 0xdc, 0x19, + 0x96, 0x88, 0x75, 0x21, 0x1a, 0x6a, 0xa8, 0x4b, 0x1f, 0x35, + 0xd1, 0x92, 0xf5, 0x76, 0xf4, 0x72, 0x55, 0x13, 0xdb, 0x5d, + 0x07, 0x8d, 0xd9, 0x72, 0xe4, 0x75, 0xde, 0x80, 0xbc, 0xe9, + 0x9c, 0xf0, 0x5c, 0x6a, 0x8a, 0x0e, 0x34, 0xf6, 0x3f, 0x5c, + 0xef, 0x0e, 0xcc, 0x52, 0x38, 0x2d, 0x7b, 0xc2, 0x1b, 0x69, + 0x9f, 0xe5, 0xed, 0x14, 0xb0, 0x91, 0x0b, 0xe9, 0x4d, 0x34, + 0xd5, 0xaa, 0xd4, 0xd2, 0x46, 0x39, 0x45, 0x7e, 0x85, 0x2f, + 0xdb, 0x89, 0xf4, 0xff, 0x05, 0x74, 0x51, 0xba, 0xdd, 0xee, + 0xf6, 0xc2, 0xc1, 0x0a, 0x8f, 0xd9, 0xeb, 0xc7, 0x61, 0x30, + 0x8f, 0x86, 0x8b, 0x1f, 0x82, 0xc1, 0x22, 0xfd, 0x83, 0xf4, + 0x5d, 0xc5, 0x94, 0xf5, 0xd7, 0x17, 0xc7, 0x7b, 0x71, 0xf5, + 0x5e, 0x15, 0x49, 0x70, 0xb2, 0x57, 0xa0, 0xc0, 0x57, 0x63, + 0x53, 0x35, 0xb6, 0x52, 0x20, 0x7b, 0x83, 0xd4, 0x57, 0x63, + 0x25, 0x8e, 0x83, 0xb3, 0x8e, 0x26, 0x1f, 0x09, 0xde, 0x14, + 0xd6, 0xa6, 0xfc, 0xe5, 0x93, 0x3c, 0x88, 0x8e, 0xf5, 0x10, + 0x57, 0xb9, 0xc9, 0x9b, 0xff, 0x72, 0x9d, 0x3d, 0x3f, 0x97, + 0xd9, 0x3c, 0x20, 0xe2, 0x57, 0xfd, 0x2a, 0x5c, 0x17, 0x12, + 0xe6, 0x08, 0xaf, 0xe4, 0x26, 0x96, 0xb9, 0x6d, 0xc3, 0xac, + 0x22, 0xf3, 0x8b, 0x89, 0xde, 0xc7, 0x8a, 0x93, 0x06, 0xf7, + 0x1d, 0x08, 0x21, 0x36, 0x16, 0x74, 0x2b, 0x97, 0x23, 0xe4, + 0x79, 0x31, 0x08, 0x23, 0x62, 0x30, 0x67, 0xe2, 0xed, 0x30, + 0x9b, 0x0c, 0xf9, 0x08, 0x7a, 0x29, 0x73, 0xc6, 0x77, 0x8a, + 0xbb, 0x2a, 0x1c, 0x66, 0xd0, 0xdd, 0x9e, 0xa3, 0xe9, 0x62, + 0xcc, 0xb7, 0x88, 0x25, 0x4a, 0x5f, 0xbc, 0xaa, 0xe3, 0xe4, + 0x4f, 0xec, 0xa6, 0x8e, 0xa6, 0xa4, 0x1b, 0x22, 0x2b, 0x2c, + 0x8f, 0x57, 0x7f, 0xb7, 0x33, 0xfe, 0x16, 0x43, 0x85, 0xc5, + 0xd2, 0x95, 0xe6, 0xb9, 0x21, 0x68, 0x88, 0x98, 0x33, 0x8c, + 0x1d, 0x15, 0x9c, 0x4d, 0x62, 0x1f, 0x6b, 0xe8, 0x7a, 0x2d, + 0x6b, 0x0e, 0xc3, 0xde, 0x1a, 0xa8, 0xed, 0x67, 0xb3, 0xb3, + 0x36, 0x5b, 0x4b, 0xcb, 0xe8, 0xa8, 0x5c, 0x0b, 0x2f, 0xca, + 0xd7, 0x71, 0xe8, 0x85, 0xe7, 0x4d, 0xe5, 0x7b, 0x45, 0xed, + 0xb2, 0x4c, 0x69, 0x04, 0x7e, 0x4f, 0xc0, 0xef, 0x1a, 0xca, + 0x0d, 0xa6, 0xc4, 0x79, 0x15, 0x78, 0x9c, 0xd2, 0x91, 0x3c, + 0x32, 0x55, 0x40, 0xe7, 0xcb, 0x7e, 0xde, 0x07, 0xa6, 0x97, + 0x00, 0x2d, 0x70, 0xf6, 0x3d, 0x15, 0xdf, 0x29, 0x8e, 0xa3, + 0x96, 0x6d, 0xf2, 0xbb, 0xa5, 0x1b, 0x7b, 0x58, 0x30, 0xf6, + 0x17, 0xbd, 0xda, 0x13, 0xf7, 0x33, 0xc2, 0x62, 0x32, 0xd4, + 0x1c, 0x2e, 0x31, 0x74, 0x92, 0xad, 0x99, 0x8c, 0x0e, 0x7c, + 0x50, 0x21, 0xcd, 0xff, 0x41, 0xeb, 0xd1, 0xca, 0x14, 0xb7, + 0xb2, 0x31, 0x2f, 0xbe, 0x16, 0xce, 0x4f, 0x26, 0x16, 0x04, + 0xc2, 0xaf, 0xbe, 0x0d, 0x24, 0xab, 0x9a, 0x21, 0x37, 0x06, + 0xac, 0x50, 0x23, 0xf1, 0xbe, 0x5c, 0xbb, 0x64, 0xf3, 0xd3, + 0x66, 0xa3, 0xb8, 0xbe, 0x8b, 0x49, 0x8d, 0xf6, 0xc7, 0xb9, + 0x8f, 0x4e, 0x31, 0x06, 0x51, 0xe5, 0xf3, 0x0e, 0x56, 0xc4, + 0x24, 0x30, 0xf5, 0xe9, 0x36, 0x71, 0xbc, 0xc9, 0x70, 0x2c, + 0x6c, 0x4c, 0x15, 0x43, 0x44, 0xa4, 0xfc, 0xf1, 0xd2, 0x71, + 0x6c, 0x4c, 0xce, 0x30, 0x6c, 0x05, 0x7d, 0x2e, 0xb7, 0xbc, + 0xe4, 0x65, 0x76, 0x24, 0x75, 0x36, 0xdf, 0x28, 0xfc, 0xcd, + 0x9a, 0xba, 0xc2, 0xcd, 0xb0, 0x30, 0xdb, 0xe7, 0x2e, 0x3c, + 0x92, 0x63, 0x1d, 0x30, 0x23, 0x74, 0xb1, 0xb8, 0xcc, 0xd7, + 0xb6, 0x90, 0x65, 0x73, 0xa2, 0x2a, 0x6e, 0x49, 0x95, 0x0d, + 0xab, 0x24, 0xdf, 0x2d, 0xbf, 0x76, 0x46, 0x01, 0x44, 0xe4, + 0x18, 0x8e, 0xd5, 0x9a, 0x76, 0xc9, 0xc6, 0xbc, 0xdb, 0x7f, + 0x80, 0x52, 0xc6, 0x40, 0x41, 0x12, 0x36, 0x7c, 0x80, 0x69, + 0xce, 0x7b, 0xe1, 0xa0, 0x53, 0xa2, 0xd6, 0x8f, 0x3f, 0xf7, + 0xd7, 0x61, 0x09, 0x70, 0xa2, 0xa0, 0xc6, 0xaf, 0xa0, 0xd0, + 0xfa, 0x13, 0xbf, 0xc0, 0x69, 0x15, 0xce, 0x15, 0xec, 0x24, + 0x4b, 0x6b, 0xdc, 0x93, 0x51, 0xc6, 0x82, 0x19, 0x92, 0x84, + 0x5d, 0x99, 0xb0, 0x90, 0x2c, 0xcc, 0x2a, 0x81, 0x6b, 0x22, + 0x64, 0x0a, 0xcb, 0x51, 0x25, 0x82, 0x50, 0x02, 0x2d, 0x3e, + 0xd4, 0x72, 0xb3, 0x0c, 0x15, 0x77, 0xd2, 0xca, 0x98, 0x2f, + 0x41, 0x93, 0x14, 0xb2, 0x7f, 0xa1, 0x97, 0xa3, 0xb8, 0x8a, + 0x56, 0x24, 0x38, 0xa7, 0x36, 0xc5, 0x01, 0xc0, 0x9f, 0x3f, + 0x3e, 0x9a, 0xf6, 0xe9, 0x16, 0x82, 0x01, 0x58, 0x70, 0x0e, + 0x0d, 0xbc, 0xfa, 0x03, 0x57, 0x65, 0xa8, 0x5a, 0x3d, 0x57, + 0x81, 0x23, 0xbe, 0x6e, 0xa9, 0xe8, 0x22, 0xdf, 0x2f, 0x70, + 0xeb, 0x0a, 0x03, 0x96, 0x6b, 0xef, 0x20, 0x9f, 0xf2, 0x62, + 0xe7, 0xb2, 0x6e, 0x3a, 0x1e, 0x40, 0x1f, 0xd2, 0x97, 0x48, + 0xd1, 0x18, 0xf0, 0xeb, 0x52, 0x58, 0x02, 0x26, 0xce, 0x75, + 0xb1, 0x3a, 0x9d, 0x5b, 0x52, 0x94, 0xb2, 0x6e, 0x0e, 0x3f, + 0x39, 0xb6, 0xd9, 0x8a, 0x9d, 0xe8, 0x7c, 0x83, 0x32, 0xcc, + 0x43, 0x35, 0x9b, 0x7a, 0xed, 0xb2, 0x1e, 0x51, 0x37, 0x6c, + 0x14, 0xd8, 0xb8, 0x55, 0xb3, 0x91, 0xef, 0x0c, 0x3a, 0xe5, + 0x77, 0xd0, 0xbd, 0xb0, 0x7d, 0x38, 0x84, 0x2a, 0x47, 0xb2, + 0xb6, 0xda, 0xd7, 0x75, 0xd6, 0x2e, 0x60, 0xc7, 0x10, 0x52, + 0xf7, 0xdd, 0x09, 0x15, 0x6f, 0x04, 0x31, 0xc3, 0x5a, 0x6b, + 0x0c, 0x60, 0x10, 0xa8, 0x6e, 0x20, 0xa9, 0xdd, 0xb7, 0x72, + 0xc3, 0x9e, 0x85, 0xd2, 0x8f, 0x16, 0x7e, 0x3d, 0xe0, 0x63, + 0x81, 0x32, 0xfd, 0xca, 0xbc, 0x0f, 0xef, 0x3e, 0x74, 0x6a, + 0xb1, 0x60, 0xc1, 0x10, 0x50, 0x7c, 0x67, 0xa4, 0x19, 0xa7, + 0xb8, 0xed, 0xe6, 0xf5, 0x4e, 0x41, 0x53, 0xa6, 0x72, 0x1b, + 0x2c, 0x33, 0x6a, 0x37, 0xf1, 0xb5, 0x1c, 0x01, 0x7d, 0xa2, + 0x1f, 0x2c, 0x4e, 0x0a, 0xbf, 0xd4, 0x2c, 0x24, 0x91, 0x58, + 0x62, 0xfb, 0xf8, 0x63, 0xd9, 0xf8, 0x78, 0xf5, 0xc7, 0x78, + 0x32, 0xda, 0x99, 0xeb, 0x58, 0x20, 0x25, 0x19, 0xb1, 0x06, + 0x7f, 0x6a, 0x29, 0x20, 0xdb, 0xc8, 0x22, 0x48, 0xa9, 0x7f, + 0x24, 0x54, 0x8d, 0x7d, 0x8d, 0xb1, 0x69, 0xb2, 0xa3, 0x98, + 0x14, 0x0f, 0xba, 0xfa, 0xb6, 0x15, 0xe8, 0x28, 0x99, 0x3f, + 0x30, 0x04, 0x50, 0xab, 0x5a, 0x3c, 0xf1, 0x97, 0xe1, 0xc8, + 0x0f, 0x0e, 0xb4, 0x11, 0x63, 0x5a, 0x79, 0x08, 0x48, 0x75, + 0xaf, 0x9b, 0xca, 0xd9, 0x13, 0x18, 0xcc, 0xb1, 0xb3, 0xee, + 0xdd, 0x63, 0xdd, 0xf4, 0x21, 0x98, 0x76, 0xe2, 0x3e, 0xd5, + 0x86, 0x23, 0x33, 0x7e, 0xc7, 0xb4, 0x35, 0x4b, 0xc2, 0x2d, + 0xe1, 0xe2, 0xb0, 0x6c, 0x8b, 0x9b, 0x20, 0x3d, 0x48, 0x24, + 0x7c, 0xea, 0xa1, 0x75, 0x27, 0xe5, 0xf4, 0x70, 0xeb, 0x3b, + 0xc7, 0x26, 0x37, 0x04, 0xff, 0x8a, 0x7a, 0xd0, 0xc2, 0xb7, + 0x84, 0xb7, 0x29, 0xfb, 0x0e, 0xa3, 0xa8, 0x71, 0xcd, 0x58, + 0x06, 0x36, 0xe2, 0xf2, 0x77, 0xcc, 0x0f, 0x78, 0x08, 0x2b, + 0xbb, 0xe3, 0x53, 0x05, 0x71, 0xdc, 0x6c, 0x37, 0x32, 0x91, + 0x46, 0x42, 0x4f, 0x21, 0xe0, 0x34, 0xad, 0x3f, 0x30, 0x5a, + 0xc7, 0x0d, 0x17, 0x19, 0x39, 0x31, 0x58, 0x69, 0x3c, 0x8c, + 0xbe, 0xe7, 0xa6, 0x3b, 0xad, 0xfb, 0x46, 0x89, 0x06, 0xc1, + 0x8c, 0x16, 0x9a, 0x06, 0x3a, 0xd0, 0x7e, 0xd6, 0xb0, 0x7b, + 0x7d, 0xf8, 0x91, 0x7c, 0xfa, 0xd9, 0x66, 0x39, 0xfa, 0xbc, + 0x57, 0xa7, 0x78, 0x8b, 0x36, 0x78, 0xc0, 0x1c, 0x0e, 0x23, + 0x05, 0x0e, 0x04, 0x61, 0x16, 0x34, 0xf9, 0xc6, 0x63, 0x58, + 0xdf, 0xf4, 0x52, 0xce, 0xd0, 0x0f, 0x0c, 0xec, 0xb1, 0x82, + 0xf4, 0x72, 0x73, 0x72, 0x3f, 0x02, 0xbe, 0xe3, 0x9c, 0x63, + 0x73, 0xc8, 0x21, 0x65, 0xba, 0x57, 0x52, 0xa9, 0x19, 0xac, + 0x68, 0x50, 0xbd, 0x2d, 0x72, 0x5b, 0x93, 0x0f, 0x1c, 0x81, + 0x77, 0xd7, 0x2e, 0xc3, 0x93, 0x52, 0x6e, 0xdc, 0x79, 0x52, + 0x9f, 0xe3, 0xde, 0xe1, 0xba, 0x58, 0x55, 0xab, 0x8a, 0xf2, + 0x35, 0x6a, 0xcf, 0x94, 0x1f, 0x17, 0xa4, 0x23, 0x2e, 0x8e, + 0x18, 0x21, 0xbe, 0x14, 0xfa, 0xe7, 0x59, 0xc5, 0x44, 0x34, + 0xce, 0x03, 0xf4, 0xb7, 0x75, 0xd3, 0x51, 0x55, 0xdf, 0xff, + 0xcf, 0x4f, 0x44, 0xee, 0x13, 0x9b, 0xcb, 0x12, 0xae, 0xe5, + 0x5b, 0x44, 0x65, 0x28, 0xcb, 0x6a, 0x9c, 0x24, 0x1d, 0xea, + 0x2d, 0x5e, 0xa5, 0xc3, 0x78, 0xad, 0xed, 0x0c, 0x05, 0xa6, + 0xaf, 0x95, 0x04, 0xd2, 0xb5, 0x91, 0x0e, 0xa0, 0x06, 0x77, + 0xc5, 0x82, 0xf6, 0xdd, 0x72, 0x83, 0x04, 0xcc, 0xb0, 0xab, + 0x7a, 0xf0, 0xb4, 0x4d, 0x36, 0x71, 0x72, 0x1a, 0x9a, 0x0d, + 0xcd, 0xa3, 0x11, 0xa8, 0x0d, 0x7d, 0x49, 0xce, 0x9c, 0x09, + 0x1d, 0x08, 0xa4, 0x39, 0x2e, 0x03, 0xdf, 0x3a, 0xc8, 0xfe, + 0x6a, 0x2b, 0x0b, 0x07, 0x80, 0x55, 0x8a, 0xa8, 0xe6, 0x0e, + 0xc9, 0x7e, 0x83, 0xce, 0x3a, 0x98, 0x98, 0x4e, 0x3e, 0x08, + 0x20, 0x8f, 0x10, 0xfc, 0xc1, 0xc4, 0xcf, 0x37, 0x8d, 0x69, + 0xd8, 0x57, 0x9d, 0x48, 0x80, 0x6a, 0xef, 0x0c, 0xdd, 0x27, + 0x99, 0xf9, 0xe7, 0xd0, 0xd2, 0x36, 0xd8, 0xed, 0x41, 0x14, + 0x1b, 0x10, +}; +static const int sizeof_bench_dilithium_level3_pubkey = + sizeof(bench_dilithium_level3_pubkey); + +#endif /* !WOLFSSL_DILITHIUM_NO_VERIFY */ + +#ifndef WOLFSSL_DILITHIUM_NO_SIGN + +static const unsigned char bench_dilithium_level5_key[] = { + 0xef, 0x49, 0x79, 0x47, 0x15, 0xc4, 0x8a, 0xa9, 0x74, 0x2a, + 0xf0, 0x36, 0x94, 0x5c, 0x91, 0x1c, 0x5d, 0xff, 0x2c, 0x83, + 0xf2, 0x8b, 0x04, 0xfc, 0x5d, 0x64, 0xbd, 0x49, 0x73, 0xcd, + 0xcc, 0x99, 0xfd, 0x0f, 0x8f, 0x6e, 0xad, 0x75, 0x9b, 0xc9, + 0xb1, 0xb9, 0x90, 0x93, 0xbf, 0xce, 0x02, 0x2d, 0x12, 0x0c, + 0x54, 0x2e, 0xe2, 0x3e, 0x52, 0xff, 0xe0, 0x7a, 0xca, 0x2d, + 0x81, 0x84, 0xea, 0x16, 0x1f, 0x10, 0xc4, 0xc9, 0xde, 0xcd, + 0xf6, 0xbd, 0x60, 0xc9, 0xb3, 0xd0, 0x0f, 0x57, 0xeb, 0x71, + 0x78, 0x9b, 0xb5, 0x72, 0x2a, 0x65, 0x11, 0x14, 0xff, 0x63, + 0x8d, 0x38, 0xcf, 0xa4, 0xf4, 0xad, 0xd0, 0x68, 0x84, 0x97, + 0xfe, 0xd3, 0x91, 0xa0, 0xe4, 0xc3, 0x74, 0xcf, 0x20, 0x87, + 0x89, 0x84, 0x1f, 0x75, 0x91, 0xe3, 0xb3, 0x47, 0x8b, 0xfe, + 0x76, 0xb7, 0x2d, 0x30, 0x89, 0x02, 0x04, 0xc9, 0x93, 0xa8, + 0x31, 0xd3, 0x84, 0x2d, 0xe4, 0x26, 0x12, 0xdb, 0x94, 0x08, + 0x12, 0x45, 0x45, 0xca, 0x44, 0x89, 0x52, 0xc4, 0x28, 0x41, + 0x46, 0x01, 0x1c, 0x93, 0x20, 0x8b, 0x40, 0x6d, 0x09, 0x36, + 0x65, 0x4c, 0xa2, 0x40, 0x62, 0xb8, 0x2c, 0x1b, 0x00, 0x20, + 0x61, 0x42, 0x8c, 0x24, 0xa7, 0x10, 0x19, 0x27, 0x25, 0x22, + 0x14, 0x31, 0x13, 0x33, 0x46, 0x0c, 0x22, 0x22, 0x18, 0xa7, + 0x91, 0x0c, 0x24, 0x61, 0xd9, 0x32, 0x46, 0xc8, 0x96, 0x49, + 0x5c, 0x90, 0x89, 0x9b, 0x84, 0x01, 0x5c, 0x08, 0x42, 0x64, + 0x84, 0x85, 0x0c, 0x42, 0x21, 0x20, 0x48, 0x21, 0x92, 0x00, + 0x28, 0x83, 0x20, 0x4c, 0x08, 0xc7, 0x51, 0x99, 0x06, 0x66, + 0x01, 0x18, 0x51, 0x13, 0x48, 0x0a, 0x0b, 0x42, 0x90, 0x4c, + 0x14, 0x08, 0x83, 0x14, 0x6d, 0x10, 0x10, 0x91, 0xe2, 0xc4, + 0x8d, 0xe1, 0x12, 0x11, 0x10, 0x40, 0x29, 0x99, 0x92, 0x30, + 0x12, 0x39, 0x6c, 0x91, 0x86, 0x68, 0x08, 0x83, 0x0c, 0x54, + 0x80, 0x80, 0xa2, 0x08, 0x52, 0x09, 0x30, 0x71, 0x0c, 0x10, + 0x04, 0x53, 0x00, 0x65, 0x91, 0x12, 0x2d, 0x0c, 0xa2, 0x8c, + 0x18, 0x14, 0x45, 0xd8, 0x14, 0x06, 0xe4, 0x36, 0x72, 0x93, + 0x10, 0x68, 0x09, 0xc2, 0x08, 0x51, 0x14, 0x8c, 0x13, 0x39, + 0x11, 0xd8, 0x44, 0x02, 0x18, 0x39, 0x29, 0x98, 0x16, 0x71, + 0x82, 0x40, 0x70, 0x01, 0x10, 0x8c, 0x1a, 0x30, 0x08, 0x02, + 0x03, 0x41, 0x5a, 0x00, 0x40, 0xa4, 0x16, 0x90, 0x20, 0x26, + 0x32, 0x00, 0x49, 0x61, 0x20, 0x20, 0x0c, 0x1a, 0xb0, 0x10, + 0x63, 0x10, 0x11, 0x58, 0x30, 0x0d, 0x59, 0x80, 0x68, 0x90, + 0x46, 0x2a, 0x91, 0xa8, 0x71, 0x98, 0x20, 0x40, 0x21, 0x83, + 0x6c, 0xc0, 0x48, 0x0d, 0x8b, 0x90, 0x11, 0x08, 0x09, 0x31, + 0x8c, 0x00, 0x12, 0x10, 0x14, 0x6e, 0xc2, 0x06, 0x32, 0x1a, + 0x26, 0x10, 0x0a, 0x91, 0x44, 0x08, 0x99, 0x8d, 0x60, 0x86, + 0x28, 0x11, 0x20, 0x6d, 0xa3, 0x12, 0x81, 0x8b, 0xc6, 0x51, + 0xcb, 0xa0, 0x61, 0x09, 0x97, 0x61, 0x48, 0xb6, 0x0d, 0x21, + 0x49, 0x51, 0x08, 0x13, 0x0c, 0x0a, 0x34, 0x86, 0x49, 0x80, + 0x65, 0x14, 0x39, 0x04, 0x21, 0x01, 0x81, 0x9a, 0xb8, 0x4d, + 0x04, 0x41, 0x48, 0x03, 0x92, 0x81, 0x62, 0x14, 0x6c, 0x10, + 0x16, 0x11, 0xe2, 0xa2, 0x49, 0xe3, 0x30, 0x65, 0x04, 0x93, + 0x8d, 0x1c, 0x33, 0x70, 0x1b, 0x15, 0x50, 0xe4, 0x38, 0x80, + 0x21, 0x37, 0x06, 0x20, 0xc6, 0x24, 0xc8, 0x22, 0x88, 0x4a, + 0x44, 0x80, 0x14, 0x43, 0x88, 0x54, 0x44, 0x42, 0x11, 0x49, + 0x41, 0x19, 0xb9, 0x2d, 0xcc, 0x04, 0x0d, 0x19, 0xc1, 0x65, + 0x5b, 0xa0, 0x11, 0x94, 0x00, 0x84, 0xe4, 0xb6, 0x41, 0xc2, + 0x18, 0x72, 0x5c, 0x02, 0x69, 0x11, 0x85, 0x24, 0x13, 0x35, + 0x00, 0x62, 0x34, 0x04, 0x58, 0x40, 0x21, 0x00, 0xc4, 0x28, + 0x0c, 0x17, 0x30, 0x10, 0x47, 0x60, 0x4b, 0xc2, 0x61, 0x9c, + 0x80, 0x2c, 0x20, 0x94, 0x31, 0x58, 0x92, 0x09, 0xcc, 0x00, + 0x02, 0x42, 0x94, 0x69, 0x99, 0x28, 0x06, 0x98, 0x02, 0x52, + 0x90, 0x32, 0x6e, 0x8a, 0x18, 0x2e, 0x54, 0x94, 0x81, 0x03, + 0xc6, 0x89, 0x03, 0xa1, 0x84, 0x48, 0x82, 0x48, 0x52, 0xc4, + 0x00, 0x91, 0x30, 0x24, 0x20, 0x12, 0x0d, 0x83, 0x80, 0x05, + 0x92, 0x48, 0x61, 0x98, 0x46, 0x92, 0xe1, 0xa6, 0x25, 0x20, + 0x93, 0x4d, 0x1c, 0x37, 0x2c, 0x9b, 0x94, 0x8d, 0xc8, 0x88, + 0x80, 0xa2, 0x18, 0x72, 0x0c, 0x09, 0x70, 0x81, 0x36, 0x90, + 0x24, 0x45, 0x69, 0x53, 0x36, 0x6c, 0xd2, 0x20, 0x51, 0x23, + 0xc1, 0x8c, 0x62, 0xb0, 0x70, 0x11, 0xb2, 0x70, 0xcb, 0x84, + 0x69, 0x4b, 0x32, 0x89, 0x01, 0x21, 0x81, 0x02, 0x38, 0x66, + 0xa3, 0x26, 0x12, 0x24, 0xa3, 0x30, 0x22, 0x24, 0x84, 0x18, + 0xb9, 0x84, 0x40, 0x16, 0x50, 0x22, 0x44, 0x31, 0x1b, 0x13, + 0x8d, 0x53, 0x02, 0x89, 0x4a, 0x22, 0x10, 0x53, 0x18, 0x01, + 0x58, 0x30, 0x2d, 0x00, 0x05, 0x08, 0x13, 0x80, 0x84, 0xc2, + 0x22, 0x0e, 0x88, 0x26, 0x2a, 0x04, 0xc4, 0x4c, 0x19, 0x43, + 0x01, 0xc8, 0x38, 0x4c, 0xd1, 0xb2, 0x90, 0x13, 0x29, 0x10, + 0x12, 0x48, 0x22, 0x01, 0xa8, 0x51, 0xd1, 0x92, 0x40, 0x11, + 0x27, 0x62, 0x10, 0x01, 0x0c, 0x0c, 0xc6, 0x28, 0xe3, 0x46, + 0x60, 0x24, 0x01, 0x8d, 0x14, 0xb6, 0x10, 0x50, 0xb6, 0x25, + 0x44, 0x38, 0x40, 0x44, 0xc2, 0x0c, 0x19, 0xc0, 0x64, 0x9c, + 0x44, 0x02, 0x21, 0x25, 0x65, 0x02, 0x23, 0x86, 0x1a, 0x12, + 0x70, 0x51, 0x24, 0x91, 0x09, 0x08, 0x44, 0x09, 0x35, 0x66, + 0x91, 0x04, 0x12, 0x43, 0x42, 0x8d, 0x22, 0xa0, 0x70, 0x14, + 0x91, 0x25, 0xa0, 0x00, 0x80, 0xe4, 0x00, 0x90, 0x44, 0xb2, + 0x61, 0x14, 0x20, 0x6e, 0xca, 0x14, 0x0d, 0x23, 0x85, 0x68, + 0xda, 0x40, 0x92, 0x0b, 0xb1, 0x20, 0x92, 0x04, 0x46, 0xc0, + 0x08, 0x8a, 0x40, 0xc4, 0x4d, 0x0c, 0x17, 0x45, 0xd3, 0x18, + 0x52, 0x1b, 0x46, 0x24, 0xc2, 0x24, 0x71, 0x83, 0x10, 0x80, + 0xc8, 0x82, 0x68, 0xc2, 0x96, 0x81, 0x0a, 0x01, 0x92, 0x60, + 0xb4, 0x84, 0x09, 0xc6, 0x00, 0x04, 0x37, 0x90, 0x0b, 0xa0, + 0x28, 0x12, 0x27, 0x09, 0x94, 0x80, 0x50, 0xd8, 0x04, 0x86, + 0x08, 0x13, 0x8a, 0x4a, 0x06, 0x89, 0x9b, 0xc4, 0x60, 0xe3, + 0xa2, 0x20, 0xe0, 0x38, 0x21, 0x22, 0xb4, 0x68, 0x0a, 0xa1, + 0x0c, 0x01, 0x24, 0x32, 0x4c, 0x48, 0x30, 0xa2, 0x80, 0x8d, + 0x58, 0x44, 0x10, 0xc8, 0x94, 0x6d, 0x21, 0xc3, 0x61, 0xcb, + 0x98, 0x24, 0xdc, 0x38, 0x11, 0xc9, 0x18, 0x11, 0x20, 0x01, + 0x50, 0x1c, 0x34, 0x8d, 0x02, 0x03, 0x09, 0x0a, 0x40, 0x61, + 0xd4, 0xb8, 0x84, 0x9c, 0xc2, 0x09, 0x04, 0xb1, 0x89, 0x83, + 0x86, 0x84, 0x19, 0x83, 0x0c, 0x5a, 0x86, 0x89, 0x10, 0x21, + 0x0d, 0xd1, 0xc2, 0x80, 0x18, 0x29, 0x2a, 0x0c, 0x01, 0x50, + 0x89, 0x88, 0x48, 0x03, 0xa7, 0x85, 0x21, 0x92, 0x64, 0xc4, + 0x16, 0x81, 0x94, 0x06, 0x6c, 0x53, 0x26, 0x12, 0x90, 0xb6, + 0x21, 0x0b, 0xa8, 0x64, 0x43, 0x96, 0x84, 0x41, 0x88, 0x70, + 0xe3, 0xa6, 0x44, 0x12, 0xc0, 0x09, 0x01, 0xc7, 0x60, 0xc3, + 0x20, 0x42, 0xc3, 0x40, 0x68, 0x10, 0xa6, 0x51, 0xa4, 0xa0, + 0x71, 0x54, 0x98, 0x04, 0x88, 0xb2, 0x00, 0x54, 0x18, 0x6a, + 0x48, 0x98, 0x20, 0x21, 0xb2, 0x8d, 0x82, 0x20, 0x81, 0x99, + 0x16, 0x81, 0x0a, 0xc5, 0x88, 0x0a, 0x23, 0x11, 0x8a, 0x16, + 0x44, 0x24, 0xc9, 0x29, 0x59, 0x08, 0x91, 0x1c, 0x29, 0x05, + 0x14, 0xc9, 0x44, 0xe3, 0x20, 0x10, 0x1b, 0xa1, 0x64, 0x82, + 0xa2, 0x90, 0x00, 0x00, 0x82, 0x98, 0xb2, 0x85, 0xc8, 0x04, + 0x28, 0xc8, 0xb2, 0x65, 0xc9, 0xc6, 0x88, 0xcc, 0x08, 0x91, + 0x84, 0x08, 0x30, 0x94, 0x94, 0x8d, 0xc0, 0x18, 0x46, 0x82, + 0x36, 0x4c, 0x83, 0x10, 0x72, 0x23, 0xb1, 0x88, 0x81, 0x20, + 0x8e, 0x19, 0x03, 0x8a, 0x94, 0x46, 0x22, 0x21, 0x35, 0x8e, + 0x04, 0xc0, 0x88, 0x5b, 0xb6, 0x09, 0x0a, 0x18, 0x44, 0x21, + 0x90, 0x65, 0x03, 0xb2, 0x21, 0xc4, 0x10, 0x50, 0xc1, 0x80, + 0x0c, 0x09, 0x40, 0x49, 0xe4, 0xa8, 0x8c, 0xa4, 0x36, 0x61, + 0x59, 0x12, 0x86, 0x20, 0x08, 0x2d, 0x10, 0x19, 0x85, 0xe4, + 0x34, 0x60, 0xc4, 0xb6, 0x60, 0x00, 0x18, 0x06, 0x8c, 0xb8, + 0x45, 0x19, 0x13, 0x4a, 0x53, 0xc4, 0x40, 0xc9, 0x38, 0x71, + 0xd9, 0x48, 0x10, 0x59, 0x08, 0x02, 0x02, 0x10, 0x69, 0x53, + 0x28, 0x80, 0x22, 0x81, 0x4c, 0xc9, 0x16, 0x26, 0xa1, 0x48, + 0x64, 0x19, 0x21, 0x11, 0x1c, 0x37, 0x88, 0x4b, 0x94, 0x2c, + 0x48, 0xc8, 0x6c, 0x63, 0x88, 0x65, 0x81, 0x40, 0x61, 0xa1, + 0x44, 0x31, 0x82, 0x18, 0x08, 0x80, 0x00, 0x26, 0x50, 0x14, + 0x49, 0xa1, 0x32, 0x50, 0x02, 0xc8, 0x45, 0x0c, 0x07, 0x24, + 0x13, 0x01, 0x6d, 0x0a, 0xb3, 0x90, 0x64, 0x30, 0x85, 0x21, + 0x09, 0x61, 0x44, 0x44, 0x72, 0x08, 0x32, 0x06, 0xe1, 0xa2, + 0x21, 0xdb, 0xa4, 0x09, 0x5a, 0xb4, 0x71, 0x43, 0xb2, 0x09, + 0x82, 0xc4, 0x64, 0x88, 0xa0, 0x91, 0xca, 0x14, 0x90, 0xa4, + 0xa8, 0x41, 0xc1, 0x38, 0x85, 0x12, 0x32, 0x60, 0x1a, 0x11, + 0x72, 0x53, 0x32, 0x2c, 0xe3, 0x08, 0x4d, 0x24, 0xc6, 0x28, + 0x0a, 0x03, 0x8c, 0x88, 0x06, 0x05, 0xa0, 0xa8, 0x05, 0x84, + 0xa2, 0x4c, 0x80, 0x40, 0x62, 0xda, 0x24, 0x81, 0x9a, 0x16, + 0x91, 0x24, 0x81, 0x04, 0xa4, 0x46, 0x51, 0xc2, 0xa8, 0x25, + 0x20, 0x28, 0x42, 0x13, 0x46, 0x2c, 0x63, 0x42, 0x72, 0x03, + 0x88, 0x28, 0xa3, 0x22, 0x24, 0x1a, 0x02, 0x26, 0x42, 0xa2, + 0x11, 0x11, 0xb0, 0x51, 0x92, 0xb4, 0x6c, 0xe2, 0x32, 0x85, + 0x10, 0xc2, 0x41, 0xc1, 0x40, 0x46, 0x4c, 0x26, 0x01, 0x1c, + 0x35, 0x02, 0x0c, 0x14, 0x0c, 0x18, 0x81, 0x00, 0x10, 0x26, + 0x02, 0xc8, 0x32, 0x8c, 0xe4, 0x02, 0x68, 0xcc, 0x14, 0x2e, + 0x89, 0x38, 0x60, 0x10, 0x12, 0x24, 0x93, 0x42, 0x65, 0xe3, + 0x24, 0x29, 0x08, 0x80, 0x41, 0x09, 0x29, 0x46, 0x5b, 0x26, + 0x49, 0x5b, 0x30, 0x80, 0x03, 0xc1, 0x2c, 0x04, 0x09, 0x82, + 0x4c, 0x48, 0x2d, 0x1c, 0x36, 0x4d, 0xdb, 0x02, 0x86, 0x21, + 0xb5, 0x51, 0x81, 0x80, 0x2d, 0xcb, 0x20, 0x81, 0x5b, 0x34, + 0x41, 0x89, 0x36, 0x48, 0x44, 0xa0, 0x05, 0x59, 0xb6, 0x64, + 0x12, 0x45, 0x21, 0x20, 0x31, 0x51, 0x0a, 0xc3, 0x8c, 0x14, + 0x48, 0x71, 0x18, 0x35, 0x24, 0x20, 0x45, 0x05, 0x88, 0x20, + 0x09, 0x08, 0xb1, 0x29, 0x18, 0xa0, 0x09, 0x4a, 0x00, 0x8a, + 0xe2, 0xb8, 0x45, 0x02, 0x27, 0x89, 0xd8, 0x10, 0x25, 0x51, + 0x82, 0x8c, 0x13, 0x92, 0x30, 0x1c, 0x24, 0x8e, 0x1c, 0x93, + 0x4d, 0xa3, 0x48, 0x51, 0x93, 0xa8, 0x69, 0xe2, 0x04, 0x89, + 0x13, 0x13, 0x61, 0xcb, 0x98, 0x8c, 0x09, 0x21, 0x62, 0x4b, + 0x14, 0x4e, 0x11, 0xa3, 0x09, 0x98, 0x40, 0x42, 0x91, 0x12, + 0x08, 0x80, 0x84, 0x2d, 0xc0, 0x12, 0x60, 0x03, 0xa4, 0x29, + 0x18, 0x80, 0x01, 0x94, 0x44, 0x8a, 0x12, 0x11, 0x72, 0xc4, + 0x22, 0x32, 0x9a, 0x46, 0x88, 0x1b, 0x16, 0x4d, 0x4b, 0x08, + 0x11, 0x02, 0x48, 0x45, 0x81, 0xa4, 0x64, 0xe1, 0x88, 0x0c, + 0x63, 0x10, 0x70, 0x48, 0x98, 0x05, 0x9b, 0xb8, 0x84, 0x03, + 0x14, 0x05, 0x44, 0x86, 0x0c, 0x20, 0x11, 0x68, 0xbe, 0x71, + 0x83, 0xc2, 0x69, 0xde, 0x49, 0xad, 0xb4, 0xdb, 0x93, 0xcb, + 0x20, 0x2b, 0xbd, 0x95, 0x97, 0x57, 0x7e, 0xcb, 0xbc, 0x73, + 0xb6, 0x3d, 0x16, 0x4a, 0x0e, 0xe4, 0x9c, 0x81, 0xb1, 0x5d, + 0x27, 0x64, 0xa2, 0x14, 0x12, 0x1b, 0x8e, 0xd0, 0xd8, 0x38, + 0xf6, 0xc7, 0xbb, 0x9f, 0x77, 0x3c, 0x62, 0x04, 0x92, 0xe1, + 0x97, 0xaf, 0x24, 0xa7, 0xf9, 0xf0, 0x8d, 0x3a, 0xbf, 0x5d, + 0xab, 0x5c, 0x97, 0x0f, 0xfc, 0x35, 0xbc, 0x62, 0xd8, 0x42, + 0xfd, 0xc7, 0x8b, 0xf7, 0x80, 0xd1, 0x38, 0x68, 0x14, 0x5e, + 0x4f, 0x99, 0x31, 0xc7, 0xaf, 0xbd, 0x27, 0xce, 0x1c, 0x5b, + 0x09, 0x1b, 0xcf, 0xbb, 0xfb, 0xf9, 0xf4, 0x90, 0x4c, 0xc1, + 0xa2, 0x12, 0xf9, 0xd0, 0xa5, 0x2c, 0xfd, 0x7b, 0x55, 0xb0, + 0xb1, 0xc6, 0x42, 0xe6, 0xeb, 0x10, 0x5e, 0xe9, 0x00, 0xe8, + 0x46, 0xe4, 0xe0, 0x8b, 0x21, 0xbc, 0xb1, 0xa9, 0x9e, 0x75, + 0x66, 0xf0, 0xb8, 0x87, 0xb9, 0x11, 0x7e, 0x28, 0x6c, 0x4d, + 0x58, 0xcd, 0x54, 0x71, 0x0c, 0x6a, 0xcc, 0xfb, 0x52, 0xc2, + 0x5b, 0xcc, 0x19, 0x67, 0x4f, 0xc2, 0x2f, 0x09, 0x62, 0x51, + 0x82, 0xeb, 0x9b, 0x94, 0x11, 0xb4, 0x5a, 0x67, 0x7f, 0x58, + 0x18, 0xb2, 0x3f, 0x37, 0x1f, 0x94, 0x44, 0x73, 0x6a, 0x02, + 0xf5, 0xfb, 0x5b, 0x03, 0xac, 0x5d, 0xc6, 0xa9, 0x79, 0x8f, + 0x0f, 0x50, 0xa0, 0x57, 0x46, 0x05, 0x6d, 0x58, 0xde, 0x6e, + 0x8d, 0x9c, 0x0e, 0x6a, 0xb5, 0x9b, 0x1b, 0x22, 0x74, 0xad, + 0x00, 0x55, 0x27, 0x46, 0xce, 0xbb, 0x82, 0x77, 0x4e, 0x6e, + 0x59, 0x38, 0x26, 0xb3, 0xc7, 0xbc, 0x97, 0x54, 0x83, 0x69, + 0x1f, 0x3e, 0xbd, 0x0f, 0xff, 0x2f, 0xca, 0xb9, 0xea, 0x91, + 0x26, 0x8e, 0x0a, 0x78, 0x25, 0xf6, 0x6b, 0x11, 0x30, 0xd7, + 0xe2, 0xf4, 0x2b, 0xda, 0xcf, 0xe1, 0x4a, 0x47, 0xab, 0x5f, + 0x54, 0x34, 0x38, 0xac, 0xd1, 0xbf, 0x45, 0xad, 0x4b, 0x52, + 0x0f, 0x4c, 0xa2, 0xac, 0x22, 0x7c, 0xb6, 0xed, 0x7f, 0xd5, + 0x63, 0x3b, 0x1a, 0x3b, 0xf2, 0x3d, 0x9b, 0x96, 0x92, 0x08, + 0xb9, 0x95, 0x13, 0xaf, 0x20, 0x26, 0x8b, 0x15, 0x97, 0x89, + 0xa5, 0x88, 0x8f, 0x78, 0xb4, 0x57, 0x9d, 0x51, 0x96, 0x9c, + 0x98, 0x93, 0xd5, 0x83, 0xf9, 0xff, 0x94, 0x29, 0x1e, 0xa5, + 0x28, 0xa4, 0x0c, 0x22, 0xab, 0xbc, 0x70, 0x48, 0xa2, 0x16, + 0x1c, 0xa4, 0xba, 0x8b, 0xfe, 0xb2, 0xa9, 0x03, 0x96, 0x5f, + 0xb4, 0x84, 0x8e, 0xb4, 0xbb, 0x7b, 0x11, 0xc5, 0xc2, 0xdb, + 0xe3, 0x88, 0xb5, 0xd3, 0xac, 0x07, 0x33, 0x53, 0xe8, 0x10, + 0x9e, 0xc5, 0x81, 0xb0, 0x77, 0x2f, 0x4f, 0x6d, 0x0d, 0x89, + 0xb4, 0x04, 0x98, 0x05, 0xe6, 0xd3, 0x36, 0x97, 0xcd, 0x3e, + 0x4d, 0xc6, 0x21, 0xe4, 0x0b, 0xcf, 0xed, 0xa7, 0x4d, 0xd9, + 0xd3, 0x25, 0xec, 0xec, 0x47, 0xfd, 0x06, 0x92, 0x77, 0x25, + 0x3c, 0x44, 0xe6, 0x5d, 0xb4, 0x35, 0x2b, 0x5d, 0x05, 0x65, + 0x63, 0x0b, 0xd9, 0xb8, 0x28, 0xdf, 0xdd, 0xfd, 0x64, 0x18, + 0x42, 0x19, 0x7f, 0x12, 0x78, 0xdd, 0xf0, 0x64, 0xd6, 0x99, + 0xb8, 0x74, 0x81, 0xe2, 0xb9, 0xc8, 0x67, 0x6d, 0x31, 0x22, + 0xa5, 0x68, 0xa1, 0x8d, 0x3e, 0x49, 0xbe, 0x10, 0x68, 0xa8, + 0x74, 0x1d, 0x18, 0xcf, 0x00, 0xe1, 0x4f, 0x77, 0xd8, 0xc6, + 0xe3, 0x08, 0xbb, 0x4c, 0xed, 0xff, 0xd9, 0x9b, 0xb0, 0xd1, + 0x50, 0xbb, 0x8b, 0x91, 0xcd, 0x5f, 0x2a, 0xfb, 0x8f, 0x4d, + 0x3c, 0x98, 0xba, 0xd7, 0x98, 0x99, 0xa7, 0x22, 0x14, 0xd7, + 0x94, 0xb5, 0xb8, 0xa4, 0x52, 0x31, 0xa7, 0xa1, 0xa4, 0x28, + 0xee, 0x31, 0xb5, 0xd0, 0xc1, 0x07, 0x05, 0x16, 0x1d, 0x53, + 0x45, 0x62, 0x23, 0x05, 0x44, 0xb6, 0x4f, 0x92, 0x03, 0x53, + 0x9a, 0x71, 0x56, 0xae, 0x16, 0x81, 0xb4, 0xc9, 0x98, 0xf4, + 0x7f, 0x11, 0x37, 0xc2, 0xc8, 0xf2, 0xe4, 0x48, 0xe3, 0xcc, + 0xf1, 0xe3, 0x3d, 0x8e, 0x13, 0x5b, 0x25, 0xad, 0xce, 0x6f, + 0xed, 0x60, 0x4f, 0x7d, 0x51, 0xe1, 0xd0, 0x74, 0xf4, 0xed, + 0xf3, 0x84, 0xa6, 0x0e, 0xba, 0xb4, 0x8e, 0x5a, 0xb9, 0x12, + 0x70, 0x43, 0x4c, 0xb5, 0xa5, 0x1e, 0x86, 0xa5, 0xe3, 0x4d, + 0x76, 0x95, 0xce, 0x2c, 0x53, 0x3a, 0x4e, 0x3f, 0x47, 0x73, + 0x85, 0x88, 0xd9, 0x39, 0x21, 0x83, 0x24, 0x68, 0x6a, 0x1e, + 0x77, 0xdf, 0x59, 0xc5, 0x1b, 0xe2, 0xb1, 0x47, 0x9d, 0xee, + 0x45, 0x1e, 0xc6, 0xd4, 0x43, 0xe2, 0xc7, 0x1c, 0x98, 0x84, + 0xe0, 0x39, 0xe9, 0x9f, 0xa0, 0xa2, 0x24, 0x4a, 0x88, 0x46, + 0xf3, 0x50, 0x52, 0xb5, 0xae, 0x37, 0x5c, 0xa1, 0x7d, 0xad, + 0x7c, 0x30, 0x3e, 0xcd, 0x80, 0x1c, 0xac, 0xf4, 0xe6, 0xb5, + 0x9f, 0x22, 0xb6, 0xfb, 0x0e, 0x6d, 0x80, 0x10, 0xf7, 0x3f, + 0xdd, 0x5b, 0xd9, 0xd4, 0x03, 0x14, 0x41, 0x90, 0x88, 0xa8, + 0xcf, 0x50, 0xa2, 0xf2, 0x7e, 0xf0, 0x0a, 0x7f, 0xed, 0x77, + 0x09, 0x48, 0x32, 0x55, 0xe9, 0x93, 0xe7, 0x27, 0x18, 0x46, + 0x17, 0x03, 0x25, 0x8e, 0x17, 0x5d, 0xe8, 0x9e, 0xb1, 0xb4, + 0x9d, 0x1a, 0x5e, 0xbe, 0xa8, 0xb8, 0x45, 0x30, 0xc6, 0xa5, + 0xb4, 0xaf, 0xf3, 0x0d, 0x91, 0x9c, 0xa9, 0x5b, 0x4c, 0xbb, + 0x19, 0x19, 0x39, 0x51, 0x36, 0x80, 0xf7, 0x10, 0xf7, 0x73, + 0x49, 0x17, 0xec, 0xbc, 0x92, 0x08, 0x21, 0xb1, 0x0c, 0x23, + 0xc4, 0xd6, 0xd2, 0xb3, 0xfd, 0xae, 0xe7, 0x71, 0xf3, 0x50, + 0x11, 0x27, 0x1a, 0x85, 0xf0, 0xab, 0xd8, 0x16, 0x64, 0xcb, + 0xad, 0xbb, 0xae, 0x54, 0x37, 0xa3, 0xa8, 0xf4, 0x09, 0x67, + 0x54, 0x61, 0x86, 0x0f, 0x0e, 0x25, 0x0d, 0xda, 0x4a, 0xc7, + 0xe7, 0x02, 0x80, 0x6b, 0x59, 0xd2, 0xc8, 0x88, 0x4d, 0x7d, + 0xfd, 0x3d, 0x48, 0x04, 0x6d, 0x95, 0xdf, 0xc2, 0x8b, 0x23, + 0x70, 0x4a, 0xf5, 0xdc, 0xc9, 0x24, 0x8d, 0x7e, 0x52, 0x22, + 0x7e, 0x9c, 0x5c, 0x32, 0xa5, 0xd5, 0xf2, 0x11, 0x08, 0xa0, + 0xd4, 0xa2, 0xd8, 0xdb, 0x1d, 0x9f, 0x1b, 0x54, 0x8f, 0xb5, + 0xf6, 0x71, 0x71, 0x49, 0xbc, 0x38, 0x09, 0xb6, 0x24, 0x94, + 0x80, 0x1f, 0x2d, 0x0c, 0xc7, 0xe4, 0xd6, 0xcd, 0xab, 0x53, + 0x79, 0x28, 0xed, 0x48, 0x23, 0x14, 0x2f, 0x0b, 0x3a, 0xd0, + 0xa7, 0x08, 0xe1, 0xfd, 0x1e, 0xb6, 0xdd, 0x12, 0x93, 0x2d, + 0x95, 0x06, 0xba, 0x95, 0xcb, 0x1a, 0xed, 0xfb, 0x60, 0xe7, + 0xf1, 0x1c, 0xad, 0xc3, 0xea, 0x8d, 0x3c, 0x53, 0x32, 0xb5, + 0x38, 0x26, 0xdd, 0x39, 0xf0, 0x39, 0x4e, 0x6f, 0x3e, 0xa9, + 0xea, 0x25, 0x29, 0xb8, 0x6c, 0x7d, 0x0a, 0x91, 0xd4, 0xb9, + 0x7b, 0x67, 0xe4, 0xe5, 0x63, 0xd7, 0x6b, 0x03, 0xa5, 0xd7, + 0xe8, 0xd2, 0xc0, 0x34, 0x53, 0xa6, 0x16, 0x21, 0x2a, 0x2a, + 0x09, 0xd3, 0xad, 0xa1, 0x2c, 0x6a, 0x88, 0x2d, 0x90, 0x06, + 0xba, 0x0b, 0xaa, 0xd1, 0xdb, 0xa4, 0xd0, 0x49, 0x0f, 0x42, + 0xe1, 0xca, 0xf0, 0x69, 0x15, 0x63, 0xcb, 0x0b, 0x4c, 0x2e, + 0x99, 0x20, 0x44, 0xe3, 0x6e, 0x32, 0x8a, 0xa1, 0x5c, 0x5b, + 0x03, 0xeb, 0xb5, 0x05, 0xff, 0x1a, 0x76, 0x38, 0x1c, 0xb0, + 0x74, 0xf1, 0x5a, 0x0d, 0x8a, 0xd2, 0x4e, 0x38, 0x11, 0x86, + 0xb0, 0x2d, 0xd3, 0x88, 0xe2, 0x0f, 0x51, 0x68, 0xb9, 0x79, + 0x96, 0x50, 0x95, 0xdc, 0x69, 0xcb, 0xa6, 0x25, 0x4a, 0xdf, + 0xa1, 0x39, 0x13, 0x47, 0x0a, 0xf0, 0xeb, 0xcb, 0x14, 0x01, + 0x28, 0x9c, 0x0f, 0xe2, 0x62, 0xca, 0xb5, 0x40, 0x51, 0x45, + 0x8e, 0x18, 0x88, 0xc9, 0x58, 0xaf, 0xb3, 0x48, 0xd5, 0x20, + 0xe8, 0xd8, 0x5b, 0xa2, 0x98, 0x74, 0x25, 0xfa, 0x25, 0x19, + 0x82, 0x22, 0xfa, 0x82, 0x7c, 0x38, 0x8d, 0x62, 0x86, 0x01, + 0x63, 0x20, 0x36, 0x8e, 0xaf, 0x15, 0x8a, 0x74, 0x1e, 0xfd, + 0x7f, 0xbe, 0x60, 0xc3, 0x65, 0x31, 0xce, 0xdb, 0x92, 0xb9, + 0x13, 0x2a, 0x78, 0xa9, 0xfc, 0x6a, 0x7b, 0x18, 0xec, 0x0c, + 0x7b, 0x4c, 0x86, 0xaf, 0xea, 0x6d, 0x52, 0x09, 0x76, 0x52, + 0x87, 0x8a, 0x0b, 0x2a, 0xf3, 0x93, 0x35, 0x92, 0x8b, 0x60, + 0x42, 0x2e, 0x12, 0xa9, 0xf7, 0x7c, 0x61, 0x5c, 0x8f, 0xc0, + 0xaa, 0x6e, 0x6a, 0xf6, 0x48, 0x48, 0xc6, 0x3e, 0xe0, 0x1d, + 0xb4, 0xfb, 0xc4, 0xd8, 0x01, 0xb8, 0xf2, 0xf4, 0xdf, 0xc1, + 0xba, 0xb5, 0xf2, 0x27, 0x3f, 0xdb, 0x78, 0x62, 0x1c, 0x0a, + 0xbe, 0xdb, 0xdd, 0x3c, 0x0c, 0x29, 0x85, 0xf1, 0x44, 0x5f, + 0x2b, 0x43, 0x80, 0x57, 0xa7, 0x5a, 0x4d, 0x1b, 0xbe, 0x03, + 0xe7, 0x55, 0x7b, 0x91, 0x9d, 0x4c, 0x8b, 0xd7, 0xfd, 0xde, + 0x65, 0x7e, 0xa8, 0x48, 0xbb, 0xa9, 0x96, 0x06, 0x7f, 0xc0, + 0x6c, 0xed, 0x87, 0x53, 0x77, 0xb4, 0x5a, 0x7c, 0xbb, 0xce, + 0xcf, 0x01, 0x08, 0x45, 0x61, 0xc1, 0x28, 0xb6, 0xf2, 0xb4, + 0x5b, 0x6b, 0x84, 0xfe, 0x18, 0x09, 0x39, 0xc1, 0xc8, 0x96, + 0x36, 0x6e, 0xba, 0x7e, 0x48, 0x12, 0xe6, 0xdc, 0x22, 0x48, + 0x17, 0x0b, 0xbd, 0x92, 0x64, 0xfa, 0xc9, 0x9b, 0x07, 0xda, + 0xed, 0x04, 0x68, 0x42, 0x15, 0x8c, 0xf9, 0xd8, 0xc3, 0x0d, + 0x21, 0x9d, 0x96, 0xbc, 0xc3, 0x07, 0x1a, 0x2c, 0x59, 0x3f, + 0x1a, 0x83, 0x43, 0xf0, 0xe0, 0xde, 0xe3, 0x40, 0x8e, 0x04, + 0x66, 0x3c, 0x87, 0x1e, 0xfa, 0x7b, 0x8a, 0x7b, 0xd2, 0x9e, + 0x15, 0xf5, 0xec, 0x3c, 0x72, 0x7e, 0x2d, 0x19, 0xf8, 0xfd, + 0xf0, 0x28, 0x71, 0x8a, 0xf5, 0xcb, 0x4c, 0x61, 0x5f, 0x85, + 0xe0, 0x6f, 0xb8, 0xf3, 0x17, 0x10, 0xcb, 0x44, 0x45, 0x8c, + 0x96, 0x08, 0xa1, 0xf1, 0x48, 0xa4, 0x1d, 0xea, 0x35, 0x2f, + 0x82, 0x2b, 0xc2, 0x0b, 0xef, 0x73, 0xe1, 0xc2, 0x35, 0xdb, + 0xe7, 0x68, 0xfd, 0xb0, 0xe8, 0x7b, 0x2d, 0x0f, 0xfd, 0x53, + 0x1b, 0xb8, 0x36, 0x54, 0xd6, 0x43, 0x30, 0xcf, 0x83, 0xb0, + 0x18, 0xda, 0x9b, 0x86, 0x82, 0xfa, 0xe6, 0x37, 0x5b, 0x9e, + 0xa4, 0xdb, 0x7c, 0x59, 0x25, 0x59, 0xc6, 0x46, 0x36, 0x72, + 0xc5, 0x72, 0xd8, 0x2f, 0x26, 0xe2, 0xee, 0xe3, 0xcb, 0xe5, + 0x33, 0x1f, 0x18, 0x2e, 0x16, 0xce, 0xd2, 0x9c, 0x89, 0x6e, + 0xd5, 0x21, 0xfa, 0x58, 0x83, 0xa9, 0x4c, 0x69, 0x97, 0x7d, + 0xae, 0x1f, 0x65, 0xd5, 0xdb, 0xf0, 0xfe, 0xd5, 0x32, 0xb1, + 0x50, 0x72, 0xdf, 0x2b, 0xe2, 0xc1, 0xe6, 0x2e, 0x8b, 0x87, + 0xa8, 0x4e, 0x84, 0xbe, 0xc9, 0x27, 0xb5, 0x74, 0x7e, 0x13, + 0x17, 0x57, 0x9c, 0xc6, 0xd3, 0x9f, 0xcd, 0x86, 0x50, 0x4b, + 0x6c, 0x50, 0xa2, 0xba, 0xfe, 0xf6, 0xd5, 0x85, 0x68, 0x31, + 0x89, 0xfb, 0xeb, 0xfe, 0x92, 0xb0, 0xd0, 0x4c, 0xbc, 0x65, + 0x4b, 0x62, 0xe2, 0xdf, 0x88, 0x7e, 0x90, 0xe0, 0xb3, 0xec, + 0x13, 0x69, 0x33, 0xea, 0x53, 0x69, 0x9a, 0x0b, 0x27, 0xfb, + 0xca, 0x9f, 0x9e, 0x1f, 0xcf, 0xb1, 0xeb, 0xf4, 0x8f, 0xe2, + 0x53, 0xc8, 0xe6, 0x51, 0x75, 0xee, 0xb1, 0x34, 0x3e, 0x37, + 0xdd, 0x2d, 0x3a, 0x72, 0x76, 0x33, 0xc1, 0x27, 0xe7, 0xbd, + 0xc1, 0x7f, 0xcb, 0x53, 0x5d, 0xdf, 0xc4, 0x1f, 0x36, 0xdb, + 0x6a, 0x91, 0x1f, 0x6a, 0xa5, 0xc6, 0xe2, 0x37, 0x68, 0x1a, + 0x7d, 0xf7, 0xed, 0x2a, 0xc7, 0x99, 0x5e, 0xbd, 0x59, 0x57, + 0x09, 0x22, 0x7e, 0x9c, 0xbd, 0x8e, 0xad, 0xbe, 0xee, 0xa5, + 0x2a, 0xe3, 0x9f, 0xff, 0x14, 0xda, 0xba, 0x90, 0x37, 0xba, + 0x3a, 0x42, 0xcd, 0x4a, 0x28, 0x47, 0x27, 0x58, 0x7a, 0x33, + 0x93, 0x77, 0x83, 0x29, 0xab, 0x47, 0x19, 0x43, 0x00, 0x6f, + 0xe7, 0x77, 0xc1, 0xaa, 0xd6, 0xbc, 0xc0, 0x1b, 0xd0, 0xdf, + 0xf9, 0x40, 0x4d, 0xb2, 0x60, 0xce, 0x59, 0x17, 0x0a, 0xa9, + 0x14, 0x4e, 0x6a, 0x30, 0x1b, 0x26, 0x68, 0x55, 0x12, 0x19, + 0x62, 0x85, 0x5d, 0xa6, 0xb4, 0x48, 0x4a, 0xe9, 0xe1, 0x57, + 0xb1, 0x48, 0xf3, 0x86, 0xd1, 0x50, 0x2e, 0x1d, 0x57, 0xbe, + 0x09, 0xf8, 0x53, 0x40, 0xd9, 0x55, 0xd9, 0x71, 0x4c, 0xa7, + 0xdb, 0x61, 0x82, 0x4e, 0x00, 0x58, 0xe4, 0x89, 0xae, 0xa6, + 0x1a, 0x4b, 0xe3, 0x9d, 0xec, 0x65, 0xee, 0xe1, 0x7b, 0xdb, + 0x4f, 0x8d, 0xf3, 0xd9, 0x89, 0xaa, 0xd1, 0x31, 0x30, 0xde, + 0xc3, 0x5c, 0xbc, 0xb9, 0x60, 0x0a, 0xe0, 0x13, 0x14, 0x85, + 0x08, 0x60, 0xc5, 0x1c, 0xc2, 0x9d, 0x8b, 0x6e, 0xb8, 0x94, + 0x11, 0x6f, 0xd3, 0xee, 0xfb, 0xf8, 0x15, 0xd8, 0xa4, 0x0b, + 0x92, 0xdf, 0x7c, 0x9a, 0xa2, 0xec, 0xa3, 0x3d, 0xbc, 0xcd, + 0xe8, 0xb5, 0xb3, 0xf5, 0xe8, 0xee, 0x2a, 0x57, 0xf7, 0x58, + 0xc4, 0xaa, 0xeb, 0x33, 0x44, 0x5f, 0x62, 0xbe, 0x90, 0x48, + 0xe5, 0xcb, 0x6a, 0xcb, 0x55, 0x94, 0x6d, 0xe6, 0x22, 0x03, + 0xeb, 0xcb, 0x05, 0xb8, 0xb4, 0xa5, 0xbe, 0xec, 0x79, 0x21, + 0x0d, 0xb3, 0x5c, 0x74, 0x11, 0xcb, 0xb3, 0xa6, 0x06, 0x2f, + 0x73, 0xd1, 0x14, 0xd9, 0x70, 0x4e, 0xc5, 0xf5, 0xff, 0xfd, + 0x49, 0x3b, 0xa9, 0x22, 0x80, 0x2a, 0x5e, 0xf9, 0xae, 0xa5, + 0xd4, 0x3c, 0x74, 0xd7, 0x5a, 0x5d, 0x88, 0x6f, 0x99, 0xe2, + 0x4c, 0xa3, 0x9b, 0x15, 0xb8, 0xfd, 0x0b, 0x0d, 0x57, 0x03, + 0xe8, 0xda, 0x78, 0xc4, 0x63, 0x49, 0x48, 0x7a, 0x39, 0xcd, + 0xfa, 0xad, 0x92, 0x55, 0x4a, 0x0e, 0x68, 0x08, 0xb9, 0x34, + 0xe0, 0x14, 0x6e, 0x19, 0xed, 0x69, 0x14, 0x7f, 0xc1, 0x7d, + 0x12, 0xac, 0x5d, 0xf7, 0x62, 0x6f, 0x77, 0x65, 0xa3, 0xc2, + 0xf9, 0xda, 0x43, 0x9e, 0x6b, 0x82, 0xd9, 0x14, 0x57, 0x02, + 0x09, 0x9f, 0xa7, 0x15, 0x27, 0xe8, 0xad, 0xa1, 0x73, 0xc7, + 0xb6, 0x11, 0x4c, 0x5e, 0xf4, 0x1a, 0x0a, 0x97, 0x98, 0x5e, + 0x29, 0x8a, 0x8b, 0xa5, 0xbd, 0x86, 0x7f, 0x6d, 0x31, 0x72, + 0x6d, 0xe5, 0xcf, 0x13, 0xff, 0xb9, 0x4e, 0x69, 0x66, 0x37, + 0x1b, 0xfb, 0xe8, 0xb7, 0x60, 0xfe, 0xbf, 0xaa, 0x06, 0x88, + 0xa4, 0xa2, 0x0b, 0x33, 0x55, 0xac, 0x61, 0x77, 0x0a, 0x6f, + 0x1f, 0xaf, 0xd8, 0x9b, 0xc7, 0x26, 0x13, 0xf6, 0xc4, 0xef, + 0xce, 0x0f, 0x16, 0x86, 0x64, 0x1b, 0xc0, 0x71, 0x35, 0xf9, + 0x1f, 0xaf, 0xc4, 0x7a, 0xa3, 0x3b, 0x89, 0x40, 0xcb, 0x09, + 0x11, 0x7b, 0x01, 0x54, 0xd5, 0xd2, 0x2a, 0xc8, 0xfe, 0x0e, + 0xef, 0x8c, 0xfb, 0x2b, 0x08, 0x12, 0x6d, 0xbb, 0xa8, 0x2e, + 0x7a, 0x2b, 0xc2, 0x91, 0x2a, 0x76, 0x0b, 0x31, 0x30, 0x4a, + 0x5b, 0xca, 0x96, 0xc9, 0x89, 0xa0, 0x12, 0x40, 0x76, 0xbe, + 0xcd, 0x59, 0x5f, 0xc2, 0x7b, 0xaf, 0xf6, 0x29, 0xde, 0xe9, + 0x24, 0x61, 0x3f, 0x46, 0x78, 0xa7, 0xda, 0x65, 0xb0, 0xb3, + 0xae, 0xf3, 0x72, 0x6e, 0x37, 0x6e, 0xae, 0xb1, 0x3b, 0xf6, + 0x60, 0xa1, 0x92, 0x86, 0x9e, 0x97, 0x4f, 0x5e, 0x86, 0x88, + 0x32, 0x06, 0x7c, 0xe3, 0x37, 0x7e, 0xb1, 0x83, 0xf5, 0x83, + 0x05, 0x43, 0xb3, 0xe3, 0xa1, 0x68, 0xe5, 0x4c, 0x92, 0x9c, + 0x61, 0xa3, 0x5d, 0xcf, 0x23, 0xe7, 0xce, 0xf5, 0x7f, 0xbb, + 0xf7, 0x89, 0x5e, 0xa8, 0xf0, 0xa1, 0xff, 0x1a, 0xaf, 0x15, + 0xc8, 0x3d, 0x8b, 0xce, 0x06, 0xa4, 0x60, 0xd6, 0x40, 0x19, + 0x48, 0x33, 0x53, 0x34, 0x9e, 0xd8, 0x75, 0xfc, 0x45, 0x73, + 0x35, 0x8f, 0x70, 0x04, 0x80, 0xa1, 0xe5, 0xfc, 0x98, 0xb0, + 0x52, 0x63, 0x41, 0x84, 0x57, 0xa2, 0x85, 0x4e, 0x68, 0x13, + 0x2d, 0x3e, 0x4b, 0x68, 0x7f, 0x43, 0x04, 0x05, 0x02, 0x5a, + 0x16, 0x67, 0x5a, 0xc5, 0xea, 0xac, 0x25, 0x61, 0xd4, 0xa4, + 0xe7, 0xbe, 0x13, 0x95, 0xbd, 0x03, 0xb4, 0x26, 0xe3, 0xbf, + 0x7e, 0xe5, 0x0b, 0x34, 0xeb, 0x59, 0x5d, 0xd7, 0xdb, 0x1e, + 0x07, 0xfc, 0x63, 0xab, 0xbb, 0xc6, 0x7a, 0x51, 0x50, 0x59, + 0x13, 0x4b, 0x27, 0x88, 0x98, 0xdc, 0x01, 0x37, 0xeb, 0x58, + 0x75, 0xde, 0x5a, 0xa4, 0x6b, 0xdd, 0xba, 0x01, 0x40, 0xf7, + 0x1c, 0x0a, 0xf3, 0x02, 0x3d, 0x54, 0x64, 0xf2, 0x85, 0x43, + 0x90, 0xc0, 0x69, 0x18, 0x94, 0x95, 0x6e, 0x57, 0x14, 0xda, + 0x27, 0x0a, 0x42, 0xb2, 0x5a, 0x78, 0xe4, 0xf1, 0x45, 0x85, + 0x54, 0xec, 0x44, 0xa0, 0xcb, 0xf4, 0xd1, 0x3a, 0x85, 0x74, + 0x0f, 0x04, 0x67, 0xf4, 0x42, 0x01, 0xc4, 0x04, 0x66, 0x48, + 0x6c, 0xbe, 0x84, 0x38, 0x6e, 0xda, 0x23, 0xd0, 0xd1, 0x26, + 0x94, 0x11, 0x65, 0x2e, 0xc6, 0xd8, 0x6e, 0x25, 0x17, 0x43, + 0x9f, 0x55, 0x2d, 0x1d, 0x55, 0xa9, 0xdd, 0x3b, 0xc7, 0x09, + 0xde, 0x26, 0x64, 0xd4, 0x85, 0x21, 0x15, 0x0d, 0x4a, 0x45, + 0x4d, 0xba, 0x13, 0x9e, 0x3b, 0x5e, 0xc2, 0xf7, 0xc1, 0x34, + 0xc5, 0x74, 0xd4, 0x95, 0x19, 0x3d, 0x69, 0x9c, 0xae, 0xef, + 0x13, 0x95, 0x2c, 0x77, 0xdd, 0x64, 0x2c, 0x12, 0x31, 0x7d, + 0xb5, 0x55, 0xde, 0x69, 0x35, 0x3f, 0x77, 0x72, 0xc6, 0x21, + 0x22, 0x23, 0x7a, 0x05, 0xbf, 0x92, 0xae, 0x49, 0x7f, 0x74, + 0x17, 0x97, 0x5f, 0x5b, 0x4d, 0x7d, 0x86, 0x23, 0x04, 0xe0, + 0xff, 0x10, 0x06, 0xc3, 0xd3, 0x05, 0xde, 0xc4, 0xae, 0xaf, + 0x3d, 0x2d, 0xaf, 0x3c, 0xaf, 0xd3, 0xd5, 0xfd, 0x84, 0xd8, + 0x3b, 0x6c, 0x8e, 0x8b, 0x23, 0x8b, 0x16, 0xaa, 0x67, 0xf1, + 0xde, 0xa4, 0x4b, 0x5a, 0x39, 0x60, 0x73, 0xd2, 0x9f, 0x1f, + 0x8c, 0xcf, 0xbc, 0xaa, 0x74, 0x9e, 0x8d, 0xfd, 0xc3, 0xb7, + 0x86, 0xe5, 0xbb, 0x5a, 0x4d, 0x3d, 0xe2, 0xc3, 0x28, 0x78, + 0x26, 0xd4, 0xb3, 0x45, 0x94, 0xd3, 0x2d, 0xbf, 0x8c, 0x92, + 0x56, 0x3c, 0x6e, 0xea, 0x53, 0x38, 0x7f, 0x22, 0x67, 0xc9, + 0xa7, 0x14, 0x20, 0xb9, 0x13, 0xc4, 0xa0, 0x44, 0x83, 0xc4, + 0x19, 0xca, 0x98, 0x71, 0xc7, 0x13, 0x70, 0x3a, 0xa7, 0xfb, + 0x9e, 0xc4, 0x94, 0x8c, 0xfd, 0x21, 0x36, 0x88, 0xea, 0x23, + 0xc7, 0x43, 0x52, 0x9f, 0xf4, 0x9e, 0xb1, 0xb4, 0xd3, 0x20, + 0x65, 0xd8, 0x18, 0x25, 0x80, 0xb7, 0xe4, 0x5c, 0x96, 0x3a, + 0xa3, 0xb5, 0x40, 0x63, 0xac, 0x02, 0x34, 0x51, 0xf7, 0x12, + 0xea, 0x97, 0x9d, 0x3e, 0xe7, 0xcb, 0x88, 0x15, 0xaa, 0xe3, + 0xfe, 0xe5, 0x42, 0xe5, 0x48, 0xcf, 0xc6, 0x8e, 0x0e, 0xc6, + 0x48, 0xdb, 0xe5, 0x1e, 0x79, 0x99, 0xed, 0x78, 0xa6, 0x37, + 0xdd, 0xe3, 0x7b, 0x01, 0xdd, 0x20, 0x63, 0x45, 0x57, 0xd1, + 0x0f, 0x05, 0x5d, 0x29, 0xad, 0x99, 0x6c, 0x27, 0xa3, 0x0c, + 0x72, 0x81, 0xb1, 0x26, 0x16, 0xaf, 0x11, 0x65, 0xba, 0x79, + 0xbc, 0xb8, 0xfe, 0xe7, 0xc5, 0xe6, 0x4c, 0xfa, 0x37, 0xc5, + 0xe0, 0x2e, 0x4e, 0xef, 0x75, 0xe4, 0x04, 0xaf, 0xfa, 0x41, + 0x7f, 0x58, 0x2e, 0x8f, 0x95, 0x5f, 0x15, 0x5c, 0x15, 0x23, + 0x81, 0xb7, 0x2c, 0x81, 0x70, 0xf5, 0xcc, 0x60, 0x09, 0x7e, + 0xf1, 0x0d, 0x9c, 0x9d, 0xcc, 0xa0, 0x30, 0xa8, 0x82, 0x23, + 0x5f, 0x94, 0xcb, 0x18, 0xc4, 0x32, 0xe6, 0xab, 0xcd, 0x96, + 0x9e, 0xab, 0xcd, 0x68, 0x6f, 0x88, 0xb7, 0x72, 0x65, 0xbc, + 0x1e, 0x05, 0x60, 0xfe, 0x6b, 0x77, 0x2a, 0x11, 0x63, 0x59, + 0x29, 0xdb, 0xba, 0xe0, 0x50, 0xd5, 0x51, 0x77, 0x16, 0xb8, + 0xb7, 0xf4, 0xa9, 0xbe, 0xf0, 0xa5, 0xaa, 0x20, 0x50, 0x2e, + 0x73, 0x21, 0xee, 0x77, 0xa3, 0xc8, 0xbc, 0x0c, 0x16, 0x0f, + 0x83, 0x7b, 0xaf, 0xbb, 0x91, 0x95, 0xd3, 0x6e, 0xe7, 0x28, + 0x77, 0x00, 0xbc, 0x83, 0x46, 0xa5, 0x0a, 0x19, 0xe8, 0x10, + 0xfb, 0x24, 0xeb, 0x27, 0xc2, 0xa3, 0xdd, 0xb8, 0x5b, 0x27, + 0xb9, 0xbb, 0x49, 0xd9, 0xd0, 0x32, 0x94, 0x48, 0x1b, 0xb8, + 0xf8, 0xb2, 0x30, 0xf4, 0x1f, 0x3d, 0xbf, 0xe6, 0xf3, 0x34, + 0xd3, 0x32, 0x85, 0x67, 0x85, 0x13, 0x3e, 0x20, 0xb7, 0xfa, + 0x74, 0x27, 0x74, 0x8f, 0x55, 0x47, 0x15, 0x91, 0x0b, 0x3f, + 0xb1, 0x18, 0xe7, 0x11, 0x1e, 0x52, 0xd8, 0xd1, 0x3f, 0xb9, + 0x5d, 0x4f, 0x88, 0xb9, 0x1e, 0x5a, 0xb6, 0x90, 0x64, 0xad, + 0x6f, 0x8d, 0x33, 0xb3, 0x57, 0xde, 0x3e, 0x13, 0xb3, 0x9f, + 0x2d, 0x00, 0xb1, 0x79, 0x84, 0x60, 0x6d, 0x3c, 0x5f, 0xc0, + 0x34, 0x08, 0x4b, 0x58, 0x33, 0x59, 0xfe, 0xe5, 0xed, 0xd3, + 0x10, 0xd8, 0xd8, 0x85, 0xc3, 0xc9, 0x71, 0xcf, 0x40, 0x96, + 0xc0, 0xd5, 0x5e, 0x62, 0xe7, 0xcb, 0x33, 0xee, 0x72, 0xb5, + 0xb8, 0x6e, 0xea, 0x13, 0xde, 0xeb, 0x82, 0x03, 0x8e, 0x6c, + 0xb3, 0x67, 0xb1, 0x5f, 0xd4, 0xe1, 0xd9, 0xc2, 0x7a, 0x97, + 0xbb, 0xd4, 0x5e, 0x0b, 0xfe, 0xc1, 0xb3, 0x1f, 0x2b, 0x1a, + 0x37, 0x98, 0x26, 0x27, 0xb1, 0xaf, 0x4c, 0x55, 0xe1, 0xae, + 0x4c, 0x86, 0x80, 0x4b, 0xc5, 0xf2, 0x35, 0x48, 0x81, 0xf7, + 0x83, 0x75, 0x63, 0x08, 0x0d, 0x77, 0x41, 0x14, 0xbc, 0xf3, + 0x6e, 0x46, 0xbd, 0x9c, 0x5a, 0x4f, 0x5c, 0x89, 0x26, 0xb6, + 0x6c, 0xde, 0x0d, 0x15, 0x31, 0xec, 0x7e, 0x13, 0xf2, 0x99, + 0x74, 0x40, 0x3c, 0xe1, 0xea, 0xa0, 0xc9, 0x99, 0x0a, 0x4b, + 0x17, 0x74, 0xff, 0x47, 0x15, 0x76, 0x5e, 0x44, 0xa2, 0x1c, + 0x93, 0xd3, 0xe6, 0xa2, 0x82, 0x0f, 0x7f, 0x55, 0xa8, 0xf3, + 0x79, 0xc3, 0xa8, 0x9f, 0x37, 0x2b, 0x97, 0x7e, 0x90, 0x71, + 0xfc, 0xa7, 0xff, 0xc6, 0xc7, 0x93, 0x5c, 0xc9, 0xed, 0x20, + 0x60, 0xbd, 0x5c, 0x36, 0x05, 0x55, 0x51, 0x55, 0x51, 0x15, + 0x36, 0x01, 0x17, 0xa9, 0x56, 0x27, 0x44, 0x66, 0xc9, 0x3a, + 0xb9, 0xbb, 0xee, 0x04, 0xb6, 0x2a, 0xfd, 0x10, 0x9a, 0x46, + 0xdd, 0x5d, 0x6d, 0xad, 0x21, 0x86, 0x6d, 0x62, 0x8a, 0x4a, + 0xbc, 0x73, 0xf0, 0x9d, 0x93, 0x0d, 0xf1, 0x62, 0xfa, 0x58, + 0x64, 0x37, 0x4f, 0x0b, 0xa3, 0xa1, 0x52, 0xce, 0x03, 0xce, + 0x0f, 0x77, 0x29, 0xad, 0x47, 0x38, 0xca, 0xbc, 0x61, 0xe6, + 0xad, 0xe4, 0x8b, 0xf1, 0x82, 0xa8, 0xd5, 0xe3, 0x8c, 0xd3, + 0xa0, 0xc4, 0xc0, 0x5e, 0x3b, 0xa1, 0x66, 0x2a, 0x6e, 0x88, + 0x24, 0x56, 0xe4, 0x84, 0x0a, 0x36, 0x72, 0xf3, 0x5c, 0x11, + 0xd9, 0x66, 0xd8, 0x45, 0x5c, 0x83, 0x9e, 0x1c, 0x8c, 0xc6, + 0xf6, 0x6e, 0x6a, 0xb1, 0x52, 0xed, 0x6c, 0x6a, 0x6d, 0x23, + 0xb9, 0x0b, 0x66, 0x26, 0x5a, 0x16, 0x16, 0x90, 0x43, 0xb9, + 0xc3, 0x02, 0xc1, 0x43, 0x93, 0x13, 0x94, 0xfe, 0xc3, 0x59, + 0x49, 0xbe, 0x1e, 0x26, 0x1b, 0x9d, 0x8e, 0xba, 0xc4, 0x29, + 0x51, 0x05, 0x28, 0x1f, 0x55, 0x59, 0x1c, 0x3e, 0x25, 0x86, + 0xcc, 0xc7, 0xd9, 0xd3, 0xa8, 0xe7, 0x10, 0xa0, 0xb6, 0x23, + 0xb9, 0xaf, 0x00, 0x8b, 0x7d, 0xf1, 0x5b, 0xd6, 0xb7, 0x56, + 0x44, 0x9b, 0x0a, 0xec, 0xa6, 0x2b, 0xb4, 0x4e, 0x1d, 0x4f, + 0xc5, 0x0b, 0x45, 0xd2, 0x3a, 0xc5, 0xc0, 0xbf, 0xb9, 0xdd, + 0x59, 0x21, 0xf2, 0x67, 0x25, 0x88, 0x9b, 0xb6, 0x66, 0x83, + 0xbf, 0x62, 0xfe, 0x7c, 0xfa, 0x9e, 0x50, 0xed, 0x15, 0x93, + 0xb6, 0x7a, 0xb0, 0xc4, 0xbe, 0xcf, 0x2a, 0x70, 0x4e, 0x52, + 0x20, 0xc1, 0x24, 0x08, 0x49, 0xd9, 0x05, 0x04, 0x53, 0x73, + 0xf3, 0xcf, 0x14, 0x70, 0xac, 0x3c, 0x45, 0x0f, 0x08, 0xa3, + 0xae, 0x43, 0xe7, 0x7f, 0x1f, 0xe2, 0x14, 0xf1, 0xbb, 0x25, + 0x20, 0xfd, 0xe4, 0xaf, 0x44, 0x9e, 0x77, 0x88, 0x4d, 0x26, + 0x09, 0xb1, 0xb0, 0x12, 0xf5, 0xdf, 0x3c, 0x53, 0x48, 0x78, + 0xb9, 0x60, 0x41, 0xd3, 0x8f, 0x8d, 0x11, 0x63, 0x60, 0x28, + 0x30, 0x07, 0xa2, 0x14, 0x3b, 0x8c, 0x50, 0xe2, 0xee, 0x73, + 0x39, 0x66, 0xd1, 0x51, 0x87, 0xac, 0x90, 0x9b, 0x2c, 0x6d, + 0x8d, 0xd5, 0x75, 0x3f, 0xc6, 0xf1, 0x8f, 0xdf, 0xdb, 0x45, + 0x38, 0xf8, 0xd6, 0x7e, 0xc7, 0x7c, 0x44, 0x08, 0x4a, 0x14, + 0xa0, 0x84, 0x7c, 0x8b, 0x88, 0x40, 0x93, 0x89, 0xae, 0x2c, + 0x20, 0x07, 0x80, 0xec, 0xce, 0x4c, 0x2c, 0x4e, 0x49, 0x79, + 0x53, 0xe7, 0xde, 0xa2, 0x9e, 0x67, 0x21, 0x53, 0x7c, 0x85, + 0xe7, 0x6f, 0xbd, 0x93, 0xab, 0x63, 0xba, 0xf0, 0xbd, 0xea, + 0x39, 0x16, 0x47, 0xbf, 0xe6, 0x0c, 0xcb, 0x63, 0xc7, 0xc5, + 0xf1, 0xdc, 0x5a, 0x52, 0xcd, 0x4c, 0x53, 0x8b, 0x7e, 0xb1, + 0xc3, 0x4e, 0xe7, 0x61, 0x25, 0x01, 0xec, 0xae, 0x06, 0x74, + 0x9f, 0xbc, 0xbb, 0x2a, 0x47, 0x46, 0xe8, 0xae, 0xf2, 0xab, + 0x15, 0xed, 0xa6, 0x86, 0x8f, 0x2f, 0xe5, 0x67, 0x0f, 0xdd, + 0xbf, 0x70, 0x53, 0xaa, 0x9b, 0x74, }; static const int sizeof_bench_dilithium_level5_key = sizeof(bench_dilithium_level5_key); -#endif /* HAVE_PQC && HAVE_DILITHIUM */ +#endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ + +#ifndef WOLFSSL_DILITHIUM_NO_VERIFY + +static const unsigned char bench_dilithium_level5_pubkey[] = { + 0xef, 0x49, 0x79, 0x47, 0x15, 0xc4, 0x8a, 0xa9, 0x74, 0x2a, + 0xf0, 0x36, 0x94, 0x5c, 0x91, 0x1c, 0x5d, 0xff, 0x2c, 0x83, + 0xf2, 0x8b, 0x04, 0xfc, 0x5d, 0x64, 0xbd, 0x49, 0x73, 0xcd, + 0xcc, 0x99, 0x50, 0x5f, 0x2b, 0x16, 0x3a, 0xbb, 0x98, 0xc0, + 0xa7, 0x69, 0x0e, 0x95, 0x99, 0x0b, 0xa2, 0x6c, 0xfe, 0x6c, + 0xdb, 0xc8, 0xa7, 0x09, 0x46, 0x6c, 0x90, 0x50, 0xa4, 0x75, + 0x30, 0xf7, 0x90, 0xac, 0x31, 0xb6, 0xdd, 0x21, 0xaf, 0xc6, + 0xf9, 0xfe, 0xee, 0xc6, 0x5b, 0xa8, 0x8f, 0x0a, 0x2e, 0xd0, + 0x42, 0xab, 0xa8, 0x3c, 0x8d, 0xbf, 0xf7, 0x44, 0xbd, 0x0d, + 0xcf, 0xf4, 0x68, 0xfc, 0x16, 0x67, 0xf7, 0x39, 0x48, 0x5f, + 0x56, 0xd1, 0xe7, 0x1f, 0x49, 0x80, 0x50, 0xbe, 0x54, 0xd1, + 0xb7, 0xc9, 0xd2, 0x32, 0xc7, 0x08, 0x8c, 0xde, 0x2c, 0x31, + 0xf6, 0x1d, 0xc7, 0xac, 0xb3, 0x79, 0xd7, 0x4b, 0x1b, 0x23, + 0x89, 0x0a, 0xdc, 0x8e, 0x44, 0x41, 0x14, 0x28, 0x99, 0x13, + 0xb3, 0x26, 0xa6, 0x0e, 0x83, 0x60, 0xaa, 0x8d, 0x7c, 0x23, + 0x13, 0xba, 0x6c, 0x28, 0x90, 0x56, 0x84, 0xa1, 0x23, 0x8b, + 0x81, 0x20, 0x97, 0x7c, 0x66, 0x3f, 0xed, 0x5d, 0xd0, 0xe4, + 0x5d, 0xee, 0x46, 0xbc, 0x4b, 0x3c, 0x03, 0xb5, 0xbc, 0x4d, + 0x8d, 0x37, 0xa3, 0x56, 0x4b, 0x33, 0xad, 0xef, 0xd4, 0xb6, + 0xec, 0xdb, 0x04, 0x9a, 0x19, 0x58, 0x57, 0xd8, 0x00, 0x3a, + 0x92, 0x61, 0x0c, 0x0b, 0xc8, 0x52, 0xe5, 0x04, 0x02, 0x9a, + 0x00, 0x7e, 0xec, 0x7e, 0x94, 0xaa, 0xef, 0x2d, 0x7f, 0xb6, + 0x2e, 0x7c, 0xb0, 0x73, 0xa2, 0x20, 0xc0, 0x07, 0x30, 0x41, + 0x50, 0x20, 0x14, 0x18, 0x21, 0x5e, 0x2a, 0x6f, 0x70, 0x21, + 0xd6, 0x97, 0x13, 0xb9, 0xc1, 0x9e, 0x90, 0x67, 0xcc, 0x55, + 0x8a, 0xec, 0xec, 0x0a, 0x1e, 0x90, 0xdc, 0x3f, 0xb0, 0x4d, + 0xd1, 0x18, 0xea, 0x4f, 0xcb, 0x5d, 0x15, 0x4c, 0xb8, 0x35, + 0x9b, 0x34, 0x24, 0x30, 0x06, 0x53, 0x17, 0xf0, 0xbe, 0x27, + 0x36, 0xb3, 0x04, 0x6a, 0xbd, 0xbf, 0xa7, 0x39, 0xee, 0xa9, + 0x8f, 0x0e, 0x98, 0xc5, 0xf5, 0x9f, 0x46, 0x25, 0x93, 0xc9, + 0xf2, 0xf6, 0x2b, 0x8e, 0x92, 0x06, 0x01, 0x3d, 0x81, 0x18, + 0xf2, 0xec, 0xf1, 0x05, 0x4c, 0xad, 0x4b, 0xcb, 0x98, 0xa4, + 0xb5, 0x61, 0x20, 0xda, 0x81, 0xa1, 0xfb, 0x92, 0x4c, 0xaf, + 0x87, 0x6f, 0x6e, 0xd2, 0x57, 0xec, 0xcd, 0x94, 0xb3, 0x79, + 0xbf, 0x59, 0x88, 0x17, 0x81, 0xce, 0x8a, 0x57, 0xce, 0x57, + 0xae, 0x3e, 0x82, 0x81, 0x2f, 0x83, 0x61, 0xd8, 0xf9, 0x68, + 0x21, 0xe7, 0x72, 0x5b, 0xd6, 0x80, 0x55, 0x68, 0x5d, 0x67, + 0x15, 0x0c, 0x8b, 0xdc, 0x4f, 0xc3, 0x89, 0x36, 0x3c, 0xac, + 0xaf, 0x16, 0x5e, 0x1c, 0xfa, 0x68, 0x74, 0x6a, 0xab, 0x68, + 0xd8, 0x59, 0x96, 0x2d, 0x33, 0x62, 0xe4, 0xbd, 0xb3, 0xb7, + 0x4d, 0x88, 0x35, 0xb8, 0xed, 0xb2, 0x16, 0x85, 0x97, 0x08, + 0x71, 0x71, 0x39, 0x7e, 0x0c, 0x53, 0x16, 0xda, 0x38, 0xe5, + 0x28, 0x09, 0x9c, 0xd9, 0x46, 0xec, 0x68, 0xda, 0x8d, 0xd0, + 0xad, 0xb2, 0x79, 0x28, 0x3b, 0x1e, 0x12, 0xc9, 0xdf, 0xa9, + 0x6d, 0x3d, 0x29, 0x99, 0x2f, 0x53, 0xc2, 0xd0, 0xf9, 0x88, + 0x26, 0x94, 0x47, 0xaf, 0xf6, 0x96, 0xf3, 0xe1, 0x11, 0xa6, + 0x82, 0x3d, 0x43, 0x3f, 0x1f, 0xbc, 0xf6, 0x98, 0xbe, 0xff, + 0x06, 0x86, 0x61, 0x27, 0xdc, 0x91, 0x54, 0xd4, 0xfc, 0x68, + 0x83, 0xe8, 0x35, 0x3e, 0xee, 0x94, 0x59, 0x28, 0x2f, 0xde, + 0xdd, 0x03, 0x60, 0x66, 0xc1, 0x49, 0x57, 0xdd, 0xbc, 0xd5, + 0x0a, 0x67, 0x34, 0xf1, 0xa6, 0x0a, 0x57, 0x94, 0x65, 0x02, + 0x2c, 0x52, 0x43, 0x70, 0x3b, 0xc1, 0x9a, 0xff, 0xda, 0x6f, + 0xb9, 0x54, 0x47, 0x01, 0xda, 0x27, 0xe4, 0x48, 0x4a, 0x90, + 0x9f, 0xb5, 0xc3, 0xee, 0x0e, 0x09, 0x57, 0xfe, 0x48, 0x51, + 0x08, 0x34, 0x5e, 0x8f, 0x16, 0xc9, 0x0b, 0x74, 0xd9, 0x7d, + 0x22, 0x3f, 0xd6, 0xb7, 0x5d, 0xd6, 0x76, 0x00, 0x8d, 0x4e, + 0x78, 0x73, 0x86, 0xd6, 0xdb, 0x2a, 0x65, 0xab, 0xdf, 0xb0, + 0xea, 0x11, 0xad, 0xdf, 0xba, 0x43, 0xdb, 0xa8, 0x0a, 0xfb, + 0x04, 0x38, 0x81, 0x2b, 0xa3, 0x29, 0xfc, 0x95, 0x73, 0x9a, + 0x0c, 0x6c, 0x9e, 0xcd, 0xdc, 0xcf, 0x0a, 0x0c, 0x18, 0x41, + 0x6f, 0x1d, 0xa3, 0xf6, 0x12, 0x4c, 0x13, 0xf2, 0x02, 0xc6, + 0x50, 0x99, 0x86, 0x73, 0xa7, 0xf9, 0x7e, 0x84, 0x7f, 0x4c, + 0x00, 0xce, 0x2e, 0x21, 0x76, 0x8e, 0x17, 0x7a, 0x87, 0x6f, + 0x81, 0xe6, 0xc0, 0x52, 0xa5, 0xa0, 0x3c, 0x54, 0x3c, 0xec, + 0xb0, 0x9d, 0x1c, 0x3b, 0xec, 0xe5, 0x4e, 0x4a, 0x37, 0xe7, + 0xd5, 0xa9, 0x07, 0x87, 0x23, 0x28, 0x5d, 0x3d, 0x22, 0x02, + 0x79, 0x40, 0x3f, 0x2d, 0x40, 0xc9, 0xe5, 0xa6, 0x9b, 0xa8, + 0xb8, 0x76, 0xf6, 0x77, 0x5b, 0x8d, 0x72, 0x96, 0x3e, 0x13, + 0xbf, 0x76, 0xfa, 0x7b, 0xb7, 0x82, 0x5f, 0xe7, 0x9d, 0x54, + 0x0e, 0x05, 0x1a, 0x9f, 0xa4, 0x42, 0xa5, 0xb4, 0x93, 0x23, + 0x06, 0x59, 0x43, 0xa8, 0xe8, 0x5c, 0xfc, 0x18, 0x97, 0xdb, + 0xad, 0x9a, 0x80, 0x0a, 0xf2, 0x20, 0x50, 0xac, 0xc1, 0x13, + 0x3e, 0x98, 0x09, 0xde, 0xf2, 0x70, 0x9e, 0x14, 0xc2, 0x5c, + 0xec, 0x65, 0x07, 0x0b, 0xfa, 0x02, 0x5c, 0xf8, 0x71, 0xaa, + 0x9b, 0x45, 0x62, 0xe2, 0x27, 0xaf, 0x77, 0xf8, 0xe3, 0xeb, + 0x7b, 0x24, 0x7b, 0x3c, 0x67, 0xc2, 0x6d, 0x6e, 0x17, 0xae, + 0x6e, 0x86, 0x6f, 0x98, 0xc9, 0xac, 0x13, 0x9f, 0x87, 0x64, + 0x3d, 0x4d, 0x6f, 0xa0, 0xb3, 0x39, 0xc6, 0x68, 0x1b, 0xa7, + 0xeb, 0x3e, 0x0f, 0x6b, 0xc7, 0xa4, 0xe2, 0x20, 0x27, 0x75, + 0x3f, 0x09, 0x16, 0xff, 0x1a, 0xcc, 0xa7, 0xc4, 0x6d, 0xc2, + 0xfc, 0xc3, 0x0b, 0x37, 0x63, 0xff, 0x9b, 0x10, 0xe6, 0x00, + 0xf7, 0x18, 0x43, 0x9f, 0x07, 0x50, 0x31, 0x51, 0xd4, 0xfd, + 0xad, 0xa2, 0x0f, 0x77, 0xda, 0x41, 0xc1, 0x0a, 0x6f, 0x86, + 0xd7, 0xdc, 0x8a, 0x52, 0xd6, 0xa1, 0x27, 0xdb, 0x14, 0x67, + 0x26, 0x91, 0xb3, 0xcd, 0x01, 0x5f, 0x60, 0xa1, 0x7f, 0x43, + 0x15, 0x1a, 0x82, 0x0f, 0xd3, 0x66, 0x5f, 0x60, 0x57, 0x2f, + 0xb2, 0x8c, 0x27, 0x2a, 0x9d, 0x1b, 0xf9, 0xf2, 0x59, 0x20, + 0x39, 0xd9, 0xc5, 0xaf, 0xf2, 0x36, 0x8c, 0x58, 0x00, 0x1b, + 0xd0, 0xc5, 0x8e, 0x1a, 0x49, 0xa8, 0x60, 0xbe, 0xd1, 0xd7, + 0x2a, 0xb0, 0xc2, 0xab, 0x58, 0x8a, 0x7a, 0xa9, 0x41, 0x68, + 0x70, 0xbd, 0xea, 0x73, 0xa5, 0x03, 0x11, 0xb2, 0x27, 0xd9, + 0xcd, 0xf5, 0x09, 0xe8, 0x1c, 0xe2, 0x4f, 0x50, 0x6a, 0x84, + 0x34, 0x62, 0x2e, 0x36, 0xaa, 0x4c, 0xc1, 0x83, 0x78, 0x98, + 0x35, 0x7a, 0x27, 0x7e, 0xfe, 0xf1, 0x6f, 0x59, 0x27, 0x35, + 0x73, 0xce, 0x74, 0xaa, 0xb4, 0x72, 0x82, 0xa8, 0xe2, 0x81, + 0x7a, 0x6b, 0xca, 0x33, 0xa5, 0xda, 0xa2, 0x63, 0xca, 0x2e, + 0x90, 0x03, 0x32, 0xec, 0x63, 0xdb, 0x52, 0x7b, 0x16, 0xfc, + 0x01, 0x2d, 0x30, 0x12, 0x1e, 0xf9, 0xa3, 0x72, 0x21, 0x3c, + 0x75, 0x0c, 0x61, 0x9c, 0x7e, 0x73, 0x04, 0x71, 0x41, 0x45, + 0x5d, 0x7f, 0x49, 0x1c, 0x09, 0x08, 0xa4, 0xec, 0x2f, 0xfd, + 0xc4, 0xfb, 0x59, 0x6a, 0x27, 0x7a, 0xd4, 0xfc, 0x5f, 0x20, + 0x04, 0x34, 0x7d, 0x08, 0xed, 0x82, 0x5a, 0x90, 0xe1, 0xab, + 0xfd, 0x35, 0x3a, 0x8d, 0xbb, 0x0a, 0x9d, 0x73, 0xff, 0x69, + 0xe5, 0xe9, 0x09, 0x55, 0x14, 0xd9, 0x7b, 0x6f, 0x0d, 0x99, + 0xd2, 0x7e, 0x71, 0xf8, 0x4f, 0x72, 0x2f, 0xbb, 0xc6, 0xc4, + 0x36, 0xc9, 0x01, 0xd3, 0x9b, 0x94, 0xab, 0x41, 0x0f, 0x4a, + 0x61, 0x5c, 0x68, 0xe5, 0xd7, 0x0d, 0x94, 0xaa, 0xee, 0xba, + 0x95, 0xcb, 0x8c, 0x0e, 0x85, 0x3a, 0x02, 0x6b, 0x95, 0x50, + 0xfd, 0x02, 0xfd, 0xa4, 0x58, 0x29, 0x78, 0x4f, 0xd0, 0xae, + 0x66, 0xd6, 0x5c, 0xe7, 0x45, 0xfe, 0x98, 0xb0, 0xa3, 0xe2, + 0x87, 0xc0, 0xd2, 0x81, 0x08, 0xf1, 0xf1, 0xe7, 0xda, 0x62, + 0x9e, 0xa0, 0x34, 0x86, 0xeb, 0xa1, 0x6e, 0x4a, 0x26, 0x8e, + 0x39, 0x0c, 0x51, 0x10, 0x33, 0x11, 0x87, 0xf8, 0x79, 0x3c, + 0x49, 0x7a, 0x8b, 0xce, 0xc1, 0x0a, 0x0e, 0xe1, 0xd5, 0x2a, + 0xac, 0xf0, 0x3a, 0x1d, 0x6a, 0x6a, 0xe5, 0xe1, 0x81, 0x70, + 0xad, 0xaf, 0x15, 0x4c, 0x2a, 0x70, 0x2a, 0x6b, 0x22, 0x0d, + 0x30, 0xe7, 0x56, 0xed, 0x2d, 0x4b, 0x85, 0x17, 0x49, 0x72, + 0x3a, 0x1b, 0x6f, 0x57, 0x1c, 0xf7, 0x72, 0x9e, 0x20, 0xdb, + 0x57, 0x1c, 0xfb, 0x36, 0x50, 0x52, 0xec, 0x5b, 0xd6, 0x6a, + 0x1b, 0xf8, 0x74, 0xad, 0xe6, 0x00, 0x74, 0x04, 0xc5, 0x99, + 0x83, 0xe4, 0x5a, 0x0c, 0xc3, 0xe8, 0x6d, 0x3a, 0xd7, 0x3c, + 0x3c, 0xc0, 0x1a, 0x28, 0xb3, 0x29, 0x7a, 0x10, 0x9e, 0x39, + 0x66, 0x5b, 0xc1, 0x38, 0xac, 0x21, 0x4e, 0xcd, 0x01, 0xf2, + 0xf6, 0x30, 0x2c, 0x2b, 0xb6, 0xbf, 0xf5, 0xea, 0x61, 0xaf, + 0x0c, 0xa6, 0x01, 0x11, 0x15, 0x19, 0x09, 0x8c, 0x7e, 0x69, + 0xdf, 0x3b, 0xea, 0xd3, 0x0a, 0x3a, 0xd7, 0xbd, 0xe1, 0x17, + 0xaf, 0x92, 0x3c, 0xf5, 0xfe, 0x35, 0xd6, 0xcf, 0x07, 0xa6, + 0xf7, 0xe9, 0xc1, 0x99, 0xed, 0x80, 0xe3, 0x12, 0xd5, 0x4b, + 0xb9, 0xdf, 0xaf, 0x4e, 0x52, 0xad, 0x8e, 0x66, 0x87, 0xe5, + 0x2c, 0xd0, 0x45, 0x70, 0xd9, 0x78, 0x8f, 0x4b, 0xf4, 0xe1, + 0xf1, 0x22, 0xf2, 0xe3, 0xed, 0x1f, 0xeb, 0xe9, 0x70, 0x31, + 0x4c, 0x65, 0x5f, 0x55, 0xee, 0x5d, 0xaa, 0x83, 0x87, 0x76, + 0xbe, 0x11, 0xae, 0xd7, 0xf2, 0xfb, 0x43, 0xe7, 0x17, 0x81, + 0x33, 0x15, 0x47, 0xa0, 0xf3, 0x8e, 0x84, 0x57, 0xff, 0x35, + 0x9e, 0x4a, 0x8a, 0xab, 0x50, 0x3a, 0x45, 0xe0, 0xc3, 0x73, + 0xca, 0x77, 0x61, 0x68, 0x38, 0xd0, 0xa3, 0x5f, 0x03, 0x8d, + 0x41, 0xc2, 0xd3, 0x4a, 0x17, 0xe0, 0xa8, 0xaa, 0x00, 0xf3, + 0xf2, 0x5b, 0xa8, 0xe1, 0x06, 0xa6, 0x2b, 0xdb, 0xe1, 0x74, + 0xbd, 0xc4, 0xd2, 0x2b, 0x55, 0x9a, 0xb0, 0xf8, 0x35, 0xd8, + 0x6b, 0xec, 0xdb, 0xc5, 0xf4, 0x6c, 0x40, 0x90, 0x6a, 0x68, + 0xc9, 0xb5, 0xcb, 0xbb, 0xd0, 0xb0, 0xbc, 0x9f, 0xb9, 0xaa, + 0x50, 0x14, 0x93, 0x3b, 0x9f, 0x25, 0xcb, 0x40, 0xb8, 0x08, + 0xcc, 0x13, 0xe5, 0xdc, 0x3f, 0x84, 0x96, 0xe0, 0x73, 0x7b, + 0x7d, 0x9e, 0x41, 0x92, 0x5d, 0xcc, 0xa4, 0xea, 0x4f, 0x93, + 0x0c, 0x40, 0x2e, 0x42, 0x8a, 0xe9, 0xb9, 0x12, 0x74, 0xbb, + 0x79, 0x7c, 0xb0, 0x37, 0x20, 0xb6, 0xaf, 0x43, 0x3a, 0x88, + 0x59, 0x7c, 0x68, 0x28, 0x5f, 0x98, 0xc2, 0xf0, 0x2a, 0xbc, + 0xa1, 0x61, 0x88, 0x1f, 0x43, 0xbc, 0x42, 0x8f, 0x43, 0xf3, + 0x7e, 0x16, 0x96, 0xfa, 0x92, 0x70, 0xaf, 0x3c, 0x9f, 0x4b, + 0xd9, 0x60, 0xe9, 0xf6, 0x2e, 0x84, 0xda, 0x88, 0x31, 0x34, + 0xa6, 0x85, 0x10, 0x05, 0xef, 0x40, 0xa8, 0xa5, 0x4f, 0x92, + 0x59, 0xf7, 0xe0, 0xc4, 0x2b, 0x12, 0x17, 0x71, 0xbe, 0x8c, + 0x4a, 0x02, 0xfe, 0x12, 0xb6, 0x3b, 0x85, 0x75, 0x37, 0xf3, + 0x73, 0x2d, 0x9c, 0x00, 0x5d, 0x80, 0xad, 0x20, 0x2f, 0x5a, + 0x0b, 0x17, 0x7e, 0x67, 0x72, 0x24, 0x5a, 0xb9, 0xf3, 0xb1, + 0x33, 0xa4, 0x57, 0x1d, 0x49, 0x72, 0x2c, 0x7f, 0x47, 0x15, + 0x07, 0xe0, 0x45, 0x14, 0xdd, 0x77, 0x86, 0x6d, 0x03, 0xbe, + 0x57, 0xd0, 0xaa, 0x18, 0xa6, 0xdd, 0x94, 0x18, 0x3f, 0x8a, + 0xf3, 0xb5, 0xd7, 0x5a, 0xec, 0xc8, 0x79, 0x7f, 0x51, 0x61, + 0x3c, 0x9b, 0xb2, 0x9b, 0xf3, 0xb4, 0x35, 0xd1, 0x38, 0xbf, + 0x37, 0xce, 0x54, 0xd1, 0xf8, 0xb6, 0x45, 0xeb, 0x52, 0x0d, + 0x9a, 0x09, 0x58, 0x0d, 0x2c, 0x0b, 0xb1, 0xf2, 0x30, 0x3a, + 0x95, 0xc1, 0x13, 0x91, 0xd2, 0x9f, 0x8d, 0x8d, 0xd0, 0x38, + 0x3e, 0x4c, 0xae, 0x4a, 0x55, 0xa7, 0x42, 0x11, 0x83, 0xc4, + 0x70, 0xf0, 0x2b, 0x68, 0x9e, 0x07, 0xad, 0xb7, 0x83, 0xc6, + 0x53, 0x3c, 0xfb, 0x0a, 0x5d, 0x24, 0xdc, 0xe1, 0x55, 0x72, + 0xcf, 0xce, 0x3e, 0xc8, 0xd0, 0x57, 0x8a, 0x82, 0x5e, 0x78, + 0x2b, 0x80, 0xc5, 0xb9, 0x09, 0x46, 0xf8, 0x90, 0x39, 0x52, + 0xa9, 0xce, 0x3f, 0x3d, 0x41, 0x3b, 0x28, 0x45, 0xa3, 0xb3, + 0x21, 0xc2, 0xcd, 0x14, 0x49, 0x41, 0x6c, 0x38, 0xda, 0x1b, + 0x5f, 0x16, 0x49, 0xf9, 0x65, 0x00, 0x4e, 0xb4, 0x20, 0x55, + 0x70, 0xe8, 0x58, 0x1a, 0x18, 0xbf, 0x41, 0xef, 0x31, 0xb1, + 0xe7, 0x8d, 0x89, 0xc1, 0x48, 0xe8, 0xf5, 0x57, 0x35, 0xfa, + 0xc1, 0x79, 0xee, 0x2c, 0xe8, 0x7d, 0xb6, 0x03, 0xcc, 0x66, + 0x09, 0x6f, 0x52, 0x84, 0x0a, 0x34, 0x18, 0x2c, 0x01, 0x45, + 0x81, 0x00, 0xe5, 0x5e, 0x8d, 0xae, 0x1c, 0x96, 0x8b, 0x45, + 0x73, 0x00, 0x0a, 0xb5, 0xcf, 0x8d, 0x0e, 0x35, 0x5d, 0x1a, + 0x0e, 0xbf, 0x64, 0x9a, 0x52, 0x20, 0x48, 0xc6, 0xb9, 0x40, + 0xd3, 0x2c, 0x52, 0xca, 0x93, 0xcf, 0xbb, 0x94, 0x06, 0xf3, + 0x97, 0xee, 0xcc, 0x5d, 0xa3, 0xea, 0xf8, 0x5a, 0x39, 0x77, + 0x34, 0xd7, 0xf6, 0x4e, 0xbe, 0x8a, 0x07, 0x5f, 0x51, 0x53, + 0xc5, 0x1b, 0x8c, 0x47, 0x8f, 0x34, 0x0e, 0x60, 0x0a, 0x90, + 0xe2, 0xda, 0x7b, 0xef, 0xd6, 0xf5, 0x5d, 0xe5, 0x32, 0x37, + 0x75, 0x99, 0x81, 0x4a, 0x2a, 0x78, 0x71, 0xdc, 0xf4, 0xe5, + 0xca, 0xd8, 0x6b, 0x3b, 0x90, 0x68, 0x2e, 0x93, 0xc5, 0x10, + 0x42, 0x5d, 0x38, 0x90, 0x32, 0x46, 0xea, 0x87, 0xe0, 0xbc, + 0xb8, 0x9a, 0x18, 0x20, 0x68, 0x85, 0x6d, 0x9b, 0xc9, 0x8f, + 0x9b, 0xd2, 0xbe, 0x15, 0x12, 0x68, 0xd0, 0xb0, 0x16, 0x5f, + 0xe2, 0x69, 0x1d, 0x04, 0x00, 0xfc, 0x63, 0x33, 0xcd, 0x1f, + 0x89, 0xcd, 0x52, 0xff, 0xec, 0x19, 0x69, 0x74, 0xa3, 0xce, + 0x4d, 0xab, 0x93, 0xe4, 0xc6, 0x13, 0x56, 0x27, 0xc9, 0x25, + 0x5a, 0x01, 0xb2, 0x36, 0x8b, 0x61, 0xe5, 0x8b, 0x98, 0xac, + 0xe4, 0x2a, 0xb6, 0x40, 0x9f, 0x42, 0xe4, 0x1b, 0x52, 0xf7, + 0xfd, 0xd8, 0x30, 0x07, 0x33, 0xf9, 0x47, 0xcb, 0x3c, 0xad, + 0x12, 0xc1, 0xcc, 0x29, 0x62, 0x49, 0x04, 0x0c, 0x23, 0x97, + 0x5a, 0xa4, 0x84, 0x67, 0xde, 0x5a, 0xe5, 0x36, 0xd2, 0x88, + 0xf1, 0xd4, 0xeb, 0x13, 0x81, 0x54, 0x51, 0x11, 0xe3, 0xba, + 0xbc, 0xee, 0xdd, 0x6c, 0xcd, 0xe6, 0xb4, 0xa1, 0x8b, 0x0b, + 0x66, 0xfb, 0x8e, 0x50, 0xa0, 0xda, 0x69, 0x8d, 0xcc, 0x2d, + 0xe4, 0x2c, 0xc4, 0x37, 0xdf, 0x61, 0xc0, 0x03, 0xbd, 0x8b, + 0x28, 0xca, 0xd2, 0x8c, 0x1c, 0xf1, 0xa4, 0x26, 0x69, 0xe5, + 0xcf, 0x45, 0xdb, 0x5a, 0x47, 0x79, 0xed, 0x9f, 0xf7, 0xd2, + 0xdb, 0xba, 0x46, 0x53, 0x4f, 0xce, 0xa8, 0xbe, 0x8f, 0x4a, + 0xd6, 0xdf, 0x2e, 0x06, 0xe6, 0x4c, 0x9a, 0xc1, 0xb6, 0x49, + 0xed, 0xc4, 0xeb, 0xaa, 0xa4, 0x29, 0x6d, 0xd4, 0xcc, 0x8c, + 0xb6, 0x40, 0x11, 0x39, 0x69, 0xf7, 0x75, 0xcd, 0xb1, 0x99, + 0x46, 0x4e, 0xde, 0xcb, 0xf6, 0x9d, 0x32, 0xf3, 0xc9, 0x47, + 0x47, 0x7a, 0xcb, 0xfb, 0xa3, 0x0c, 0x3b, 0xdf, 0xb7, 0xde, + 0xec, 0x99, 0xde, 0xb0, 0x26, 0x04, 0x34, 0xae, 0x6b, 0xfc, + 0x99, 0xbc, 0xde, 0xd5, 0xbe, 0xe7, 0xeb, 0xf9, 0xe7, 0xa6, + 0x01, 0x9a, 0x0c, 0x5e, 0x66, 0xe6, 0x53, 0xe4, 0xd1, 0x58, + 0xac, 0xda, 0x69, 0x77, 0x7b, 0x68, 0xd6, 0x30, 0x2a, 0x9c, + 0x6b, 0xbe, 0x9f, 0x3d, 0x71, 0xd6, 0x54, 0xcd, 0x59, 0x4e, + 0x1f, 0xe3, 0x83, 0x4e, 0xd1, 0x8e, 0xaf, 0x97, 0xa8, 0xe5, + 0xb6, 0x59, 0x77, 0xa8, 0x02, 0x20, 0xe4, 0xeb, 0x44, 0x71, + 0xbc, 0x07, 0x14, 0x79, 0x4f, 0x0c, 0x27, 0x06, 0x39, 0xcf, + 0x7c, 0xef, 0x2b, 0x9b, 0x5e, 0xc4, 0x6d, 0x79, 0x13, 0x00, + 0x43, 0x6f, 0x51, 0x77, 0xb5, 0xc3, 0x72, 0xad, 0x13, 0xa9, + 0xe5, 0x9a, 0x5b, 0x1a, 0x99, 0x74, 0xc0, 0x7a, 0xf9, 0xc5, + 0xb0, 0x58, 0x35, 0x1c, 0xa5, 0x51, 0xdb, 0xa1, 0x14, 0xcd, + 0x26, 0x71, 0xb1, 0xe7, 0xaa, 0x14, 0xa7, 0x46, 0x93, 0xd3, + 0x5c, 0x8c, 0x1a, 0x91, 0x77, 0x46, 0x2e, 0x15, 0xaa, 0x9e, + 0xf7, 0x2b, 0x79, 0x41, 0x76, 0xf7, 0x22, 0x53, 0x7d, 0x51, + 0xdb, 0x98, 0x3d, 0x5b, 0x78, 0x5f, 0xc3, 0xc9, 0x29, 0xa3, + 0xff, 0x75, 0x82, 0x06, 0x9a, 0x16, 0x5e, 0xa4, 0x79, 0x0d, + 0xd1, 0x6d, 0x08, 0xff, 0x43, 0xef, 0x9c, 0xf3, 0x1b, 0x7a, + 0x3f, 0x34, 0xbe, 0x19, 0x15, 0x06, 0x33, 0xdb, 0xa5, 0x71, + 0xcb, 0x5f, 0x6b, 0x8d, 0xbd, 0x5b, 0x32, 0x91, 0xb2, 0x37, + 0x3d, 0xb4, 0x40, 0x9e, 0x02, 0x9b, 0xb7, 0x68, 0x20, 0x58, + 0x5c, 0xab, 0xcb, 0xc8, 0x23, 0x2d, 0x77, 0xcc, 0x0b, 0xf6, + 0x78, 0x6b, 0x80, 0x06, 0x91, 0xa9, 0xfd, 0x7e, 0xfa, 0x25, + 0x98, 0x9f, 0xcc, 0x79, 0x0a, 0x1a, 0x54, 0x83, 0xac, 0x64, + 0x16, 0x90, 0xe5, 0xd9, 0xa7, 0xd7, 0x1b, 0x86, 0x0d, 0xe6, + 0xe6, 0x22, 0x2b, 0x1f, 0x44, 0x49, 0x98, 0x9c, 0x51, 0x6f, + 0xcf, 0x58, 0x4a, 0xfa, 0xfa, 0x84, 0x12, 0xa5, 0x10, 0xf4, + 0xca, 0xf0, 0x98, 0x2b, 0xc9, 0x03, 0x71, 0x37, 0xe7, 0xdc, + 0xc2, 0xb1, 0x4e, 0x64, 0xde, 0x4f, 0x46, 0x0d, 0x6b, 0x25, + 0x88, 0x5d, 0xd6, 0xff, 0x23, 0x46, 0x57, 0x36, 0x14, 0x18, + 0xa7, 0xcb, 0xb8, 0xbd, 0xf0, 0xc5, 0x37, 0x36, 0xee, 0xe1, + 0xed, 0x9f, 0x4d, 0xd4, 0x39, 0xe5, 0x92, 0xcf, 0x95, 0x4d, + 0x66, 0x36, 0x5d, 0xd0, 0xcc, 0x07, 0xcf, 0x15, 0x5a, 0xce, + 0x14, 0xb8, 0xda, 0x0d, 0x3d, 0x1b, 0x45, 0xc5, 0x2e, 0x34, + 0x43, 0x25, 0x02, 0x3a, 0xcd, 0x14, 0x45, 0xfb, 0x3e, 0xf9, + 0x88, 0x5d, 0x0d, 0x29, 0x31, 0xb9, 0xa1, 0xe6, 0x31, 0x18, + 0x52, 0x46, 0x3f, 0x22, 0x4f, 0x9f, 0x7a, 0x65, 0x36, 0x88, + 0xa3, 0x1c, 0x3e, 0x6f, 0x50, 0x7a, 0x36, 0xbe, 0x56, 0x7e, + 0x50, 0xcb, 0x7a, 0x10, 0xa0, 0xec, 0xf6, 0x82, 0xd6, 0x30, + 0x1c, 0xe8, 0x4c, 0x50, 0xf9, 0x3e, 0xdb, 0xac, 0xbe, 0x4f, + 0x90, 0xb1, 0xd5, 0x1b, 0x12, 0x95, 0xfb, 0xe8, 0x08, 0x64, + 0x56, 0x7c, 0x96, 0xcc, 0x90, 0xb1, 0xbc, 0xa0, 0xf5, 0x32, + 0x69, 0xb3, 0x5f, 0x27, 0x0f, 0xbe, 0xc9, 0xbd, 0xeb, 0xfa, + 0x4b, 0x5c, 0xc5, 0x99, 0x9e, 0x5a, 0x04, 0xcc, 0xd0, 0x4d, + 0x29, 0xe8, 0x84, 0x55, 0x8c, 0xd7, 0xc4, 0x06, 0x13, 0x4d, + 0x92, 0xe5, 0x98, 0x9c, 0x4c, 0xc1, 0xf7, 0xaf, 0x7b, 0xd5, + 0x2b, 0x92, 0x68, 0x68, 0x19, 0x70, 0x4c, 0x9e, 0x46, 0xb8, + 0x34, 0xeb, 0x01, 0x47, 0xbe, 0x59, 0xab, 0x0b, 0x22, 0x25, + 0xe7, 0x56, 0xa8, 0xb4, 0x93, 0x3c, 0xd5, 0x98, 0x9f, 0x61, + 0x2e, 0xfa, 0xcb, 0x5f, 0x5b, 0xd8, 0x09, 0x83, 0xe9, 0x40, + 0xe9, 0x0e, 0x42, 0xdd, 0x17, 0xd7, 0x6e, 0x19, 0x8d, 0x95, + 0x0a, 0x93, +}; +static const int sizeof_bench_dilithium_level5_pubkey = + sizeof(bench_dilithium_level5_pubkey); + +#endif /* !WOLFSSL_DILITHIUM_NO_VERIFY */ + +#endif /* HAVE_DILITHIUM */ -#if defined(HAVE_PQC) && defined(HAVE_SPHINCS) +#if defined(HAVE_SPHINCS) /* certs/sphincs/bench_sphincs_fast_level1_key.der */ static const unsigned char bench_sphincs_fast_level1_key[] = @@ -5999,7 +6034,7 @@ static const unsigned char bench_sphincs_small_level5_key[] = }; static const int sizeof_bench_sphincs_small_level5_key = sizeof(bench_sphincs_small_level5_key); -#endif /* HAVE_PQC && HAVE_SPHINCS */ +#endif /* HAVE_SPHINCS */ #if defined(HAVE_ECC) && defined(USE_CERT_BUFFERS_256) diff --git a/src/wolfssl/error-ssl.h b/src/wolfssl/error-ssl.h index e579bfb..724d7de 100644 --- a/src/wolfssl/error-ssl.h +++ b/src/wolfssl/error-ssl.h @@ -30,6 +30,10 @@ extern "C" { #endif +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H + #include +#endif + enum wolfSSL_ErrorCodes { INPUT_CASE_ERROR = -301, /* process input state error */ PREFIX_ERROR = -302, /* bad index to key rounds */ @@ -211,6 +215,9 @@ enum wolfSSL_ErrorCodes { WOLFSSL_LOCAL void SetErrorString(int err, char* buff); +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES + #include +#endif #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/evp.c b/src/wolfssl/evp.c index a365ff6..42949fc 100644 --- a/src/wolfssl/evp.c +++ b/src/wolfssl/evp.c @@ -711,8 +711,19 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, static int wolfSSL_EVP_CipherUpdate_GCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authInSz + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)(ctx->authInSz + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -745,9 +756,19 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, /* Buffer input for one-shot API */ if (inl > 0) { byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authBufferLen + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)(ctx->authBufferLen + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -817,8 +838,19 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, static int wolfSSL_EVP_CipherUpdate_CCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authInSz + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)(ctx->authInSz + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -843,9 +875,19 @@ static int wolfSSL_EVP_CipherUpdate_CCM(WOLFSSL_EVP_CIPHER_CTX *ctx, /* Buffer input for one-shot API */ if (inl > 0) { byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)(ctx->authBufferLen + inl), NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)(ctx->authBufferLen + inl), NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -875,8 +917,19 @@ static int wolfSSL_EVP_CipherUpdate_AriaGCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx, const unsigned char *in, int inl) { if (in && inl > 0) { - byte* tmp = (byte*)XREALLOC(ctx->authIn, + byte* tmp; + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)ctx->authInSz + inl, NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authIn, (size_t)ctx->authInSz); + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authIn, (size_t)ctx->authInSz + inl, NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { ctx->authIn = tmp; XMEMCPY(ctx->authIn + ctx->authInSz, in, (size_t)inl); @@ -905,9 +958,18 @@ static int wolfSSL_EVP_CipherUpdate_AriaGCM(WOLFSSL_EVP_CIPHER_CTX *ctx, if (ctx->enc == 0) { /* Append extra space for the tag */ size = WC_ARIA_GCM_GET_CIPHERTEXT_SIZE(size); } - tmp = (byte*)XREALLOC(ctx->authBuffer, - (size_t)size, NULL, - DYNAMIC_TYPE_OPENSSL); + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)size, NULL, + DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL) { + XMEMCPY(tmp, ctx->authBuffer, (size_t)ctx->authBufferLen); + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; + } + #else + tmp = (byte*)XREALLOC(ctx->authBuffer, (size_t)size, NULL, + DYNAMIC_TYPE_OPENSSL); + #endif if (tmp) { XMEMCPY(tmp + ctx->authBufferLen, in, (size_t)inl); ctx->authBufferLen += inl; @@ -2693,9 +2755,19 @@ int wolfSSL_EVP_PKEY_CTX_add1_hkdf_info(WOLFSSL_EVP_PKEY_CTX* ctx, if (ret == WOLFSSL_SUCCESS && info != NULL && infoSz > 0) { unsigned char* p; /* If there's already info in the buffer, append. */ + #ifdef WOLFSSL_NO_REALLOC + p = (byte*)XMALLOC((size_t)(ctx->pkey->hkdfInfoSz + (word32)infoSz), NULL, + DYNAMIC_TYPE_INFO); + if (p != NULL) { + XMEMCPY(p, ctx->pkey->hkdfInfo, (size_t)ctx->pkey->hkdfInfoSz); + XFREE(ctx->pkey->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); + ctx->pkey->hkdfInfo = NULL; + } + #else p = (byte*)XREALLOC(ctx->pkey->hkdfInfo, (size_t)(ctx->pkey->hkdfInfoSz + (word32)infoSz), NULL, DYNAMIC_TYPE_INFO); + #endif if (p == NULL) { WOLFSSL_MSG("Failed to reallocate larger HKDF info buffer."); ret = WOLFSSL_FAILURE; @@ -3211,6 +3283,8 @@ int wolfSSL_EVP_PKEY_bits(const WOLFSSL_EVP_PKEY *pkey) if (pkey == NULL) return 0; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); if ((bytes = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey)) ==0) return 0; + if (bytes < 0) + return 0; return bytes*8; } @@ -4275,23 +4349,39 @@ static int wolfssl_evp_digest_pk_final(WOLFSSL_EVP_MD_CTX *ctx, int ret; if (ctx->isHMAC) { - Hmac hmacCopy; - - if (wolfSSL_HmacCopy(&hmacCopy, &ctx->hash.hmac) != WOLFSSL_SUCCESS) +#ifdef WOLFSSL_SMALL_STACK + Hmac *hmacCopy = (Hmac *)XMALLOC(sizeof(Hmac), NULL, DYNAMIC_TYPE_OPENSSL); + if (hmacCopy == NULL) return WOLFSSL_FAILURE; - ret = wc_HmacFinal(&hmacCopy, md) == 0; - wc_HmacFree(&hmacCopy); +#else + Hmac hmacCopy[1]; +#endif + ret = wolfSSL_HmacCopy(hmacCopy, &ctx->hash.hmac); + if (ret == WOLFSSL_SUCCESS) + ret = wc_HmacFinal(hmacCopy, md) == 0; + wc_HmacFree(hmacCopy); +#ifdef WOLFSSL_SMALL_STACK + XFREE(hmacCopy, NULL, DYNAMIC_TYPE_OPENSSL); +#endif return ret; } else { - WOLFSSL_EVP_MD_CTX ctxCopy; - wolfSSL_EVP_MD_CTX_init(&ctxCopy); - - if (wolfSSL_EVP_MD_CTX_copy_ex(&ctxCopy, ctx) != WOLFSSL_SUCCESS) +#ifdef WOLFSSL_SMALL_STACK + WOLFSSL_EVP_MD_CTX *ctxCopy = (WOLFSSL_EVP_MD_CTX *)XMALLOC(sizeof(WOLFSSL_EVP_MD_CTX), NULL, DYNAMIC_TYPE_OPENSSL); + if (ctxCopy == NULL) return WOLFSSL_FAILURE; +#else + WOLFSSL_EVP_MD_CTX ctxCopy[1]; +#endif + wolfSSL_EVP_MD_CTX_init(ctxCopy); - ret = wolfSSL_EVP_DigestFinal(&ctxCopy, md, mdlen); - wolfSSL_EVP_MD_CTX_cleanup(&ctxCopy); + ret = wolfSSL_EVP_MD_CTX_copy_ex(ctxCopy, ctx); + if (ret == WOLFSSL_SUCCESS) + ret = wolfSSL_EVP_DigestFinal(ctxCopy, md, mdlen); + wolfSSL_EVP_MD_CTX_cleanup(ctxCopy); +#ifdef WOLFSSL_SMALL_STACK + XFREE(ctxCopy, NULL, DYNAMIC_TYPE_OPENSSL); +#endif return ret; } } @@ -5468,7 +5558,7 @@ void wolfSSL_EVP_init(void) #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) +#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0)) #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) { @@ -8465,7 +8555,7 @@ void wolfSSL_EVP_init(void) } if (ret < 0) { - if (ret == AES_GCM_AUTH_E) { + if (ret == WC_NO_ERR_TRACE(AES_GCM_AUTH_E)) { WOLFSSL_MSG("wolfSSL_EVP_Cipher failure: bad AES-GCM tag."); } WOLFSSL_MSG("wolfSSL_EVP_Cipher failure"); @@ -8543,7 +8633,7 @@ static int PopulateRSAEvpPkeyDer(WOLFSSL_EVP_PKEY *pkey) if (key->pkcs8HeaderSz) { ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, NULL, (word32)derSz, RSAk, NULL, 0); - if (ret == LENGTH_ONLY_E) + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) ret = 0; } #endif @@ -8917,7 +9007,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) ret = wc_DhParamsToDer(dhkey,NULL,&derSz); } - if (derSz == 0 || ret != LENGTH_ONLY_E) { + if (derSz == 0 || ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Failed to get size of DH Key"); return WOLFSSL_FAILURE; } @@ -9060,7 +9150,7 @@ static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) #ifdef HAVE_PKCS8 if (key->pkcs8HeaderSz) { /* when key has pkcs8 header the pkey should too */ - if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == LENGTH_ONLY_E) { + if (wc_EccKeyToPKCS8(ecc, NULL, (word32*)&derSz) == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { derBuf = (byte*)XMALLOC((size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); if (derBuf) { @@ -9112,8 +9202,17 @@ static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) } else if (ecc->type == ECC_PUBLICKEY) { if ((derSz = wc_EccPublicKeyDerSize(ecc, 1)) > 0) { - derBuf = (byte*)XREALLOC(pkey->pkey.ptr, (size_t)derSz, NULL, + #ifdef WOLFSSL_NO_REALLOC + derBuf = (byte*)XMALLOC((size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + if (derBuf != NULL) { + XMEMCPY(derBuf, pkey->pkey.ptr, (size_t)pkey->pkey_sz); + XFREE(pkey->pkey.ptr, pkey->heap, DYNAMIC_TYPE_OPENSSL); + pkey->pkey.ptr = NULL; + } + #else + derBuf = (byte*)XREALLOC(pkey->pkey.ptr, (size_t)derSz, pkey->heap, DYNAMIC_TYPE_OPENSSL); + #endif if (derBuf != NULL) { pkey->pkey.ptr = (char*)derBuf; if ((derSz = wc_EccPublicKeyToDer(ecc, derBuf, (word32)derSz, @@ -9205,7 +9304,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); @@ -9229,6 +9328,9 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) ret = NID_sha512WithRSAEncryption; } } + else { + ret = BAD_FUNC_ARG; + } WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); @@ -12432,7 +12534,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, (word32)(BASE64_DECODE_BLOCK_SIZE - ctx->remaining), (word32)inl); for ( i = 0; cpySz > 0 && inLen > 0; i++) { - if (Base64_SkipNewline(in, &inLen, &j) == ASN_INPUT_E) { + if (Base64_SkipNewline(in, &inLen, &j) == WC_NO_ERR_TRACE(ASN_INPUT_E)) { return -1; /* detected an illegal char in input */ } c = in[j++]; @@ -12472,7 +12574,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, */ while (inLen > 3) { if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12486,7 +12588,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, } inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12497,7 +12599,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, e[1] = in[j++]; inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12508,7 +12610,7 @@ int wolfSSL_EVP_DecodeUpdate(WOLFSSL_EVP_ENCODE_CTX* ctx, e[2] = in[j++]; inLen--; if ((res = Base64_SkipNewline(in, &inLen, &j)) != 0) { - if (res == BUFFER_E) { + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { break; } else { @@ -12615,8 +12717,10 @@ int wolfSSL_EVP_DecodeFinal(WOLFSSL_EVP_ENCODE_CTX* ctx, inLen = (word32)ctx->remaining; if ((res = Base64_SkipNewline(ctx->data, &inLen, &j)) != 0) { *outl = 0; - if (res == BUFFER_E) /* means no valid data to decode in buffer */ + if (res == WC_NO_ERR_TRACE(BUFFER_E)) { + /* means no valid data to decode in buffer */ return 1; /* returns as success with no output */ + } else return -1; } diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index 258cb03..390b21b 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -122,8 +122,10 @@ #ifdef HAVE_CURVE448 #include #endif -#ifdef HAVE_PQC +#ifdef HAVE_FALCON #include +#endif +#ifdef HAVE_DILITHIUM #include #endif #ifdef HAVE_HKDF @@ -206,7 +208,12 @@ #endif #elif defined(WOLFSSL_ZEPHYR) #ifndef SINGLE_THREADED - #include + #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #else + #include + #endif #endif #elif defined(WOLFSSL_TELIT_M2MB) /* do nothing */ @@ -343,7 +350,7 @@ #endif #endif - #if !defined(NO_RSA) && !defined(NO_DES3) + #if !defined(NO_RSA) && !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES) #if !defined(NO_SHA) #if defined(WOLFSSL_STATIC_RSA) #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA @@ -500,7 +507,7 @@ #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC) #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA #endif - #if !defined(NO_DES3) + #if !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES) #define BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA #endif #endif @@ -686,7 +693,8 @@ #endif #endif #if !defined(NO_DES3) && !(defined(WSSL_HARDEN_TLS) && \ - WSSL_HARDEN_TLS > 112) + WSSL_HARDEN_TLS > 112) && \ + !defined(NO_DES3_TLS_SUITES) /* 3DES offers only 112 bits of security. * Using guidance from section 5.6.1 * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */ @@ -1548,7 +1556,7 @@ enum Misc { MAXEARLYDATASZ_LEN = 4, /* maxEarlyDataSz size in ticket */ #endif #endif -#ifdef HAVE_PQC +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) ENCRYPT_LEN = 5120, /* Allow 5k byte buffer for dilithium and * hybridization with other algs. */ #else @@ -1560,7 +1568,6 @@ enum Misc { #endif SIZEOF_SENDER = 4, /* clnt or srvr */ FINISHED_SZ = 36, /* WC_MD5_DIGEST_SIZE + WC_SHA_DIGEST_SIZE */ - MAX_RECORD_SIZE = 16384, /* 2^14, max size by standard */ MAX_PLAINTEXT_SZ = (1 << 14), /* Max plaintext sz */ MAX_TLS_CIPHER_SZ = (1 << 14) + 2048, /* Max TLS encrypted data sz */ #ifdef WOLFSSL_TLS13 @@ -1726,10 +1733,12 @@ enum Misc { AEAD_LEN_OFFSET = 11, /* Auth Data: Length */ AEAD_AUTH_DATA_SZ = 13, /* Size of the data to authenticate */ AEAD_NONCE_SZ = 12, - AESGCM_IMP_IV_SZ = 4, /* Size of GCM/CCM AEAD implicit IV */ + AESGCM_IMP_IV_SZ = 4, /* Size of GCM AEAD implicit IV */ + AESCCM_IMP_IV_SZ = 4, /* Size of CCM AEAD implicit IV */ AESGCM_EXP_IV_SZ = 8, /* Size of GCM/CCM AEAD explicit IV */ AESGCM_NONCE_SZ = AESGCM_EXP_IV_SZ + AESGCM_IMP_IV_SZ, - GCM_IMP_IV_SZ = 4, /* Size of GCM/CCM AEAD implicit IV */ + GCM_IMP_IV_SZ = 4, /* Size of GCM AEAD implicit IV */ + CCM_IMP_IV_SZ = 4, /* Size of CCM AEAD implicit IV */ GCM_EXP_IV_SZ = 8, /* Size of GCM/CCM AEAD explicit IV */ GCM_NONCE_SZ = GCM_EXP_IV_SZ + GCM_IMP_IV_SZ, @@ -1768,7 +1777,7 @@ enum Misc { ECDHE_SIZE = 32, /* ECDHE server size defaults to 256 bit */ #endif MAX_EXPORT_ECC_SZ = 256, /* Export ANSI X9.62 max future size */ - MAX_CURVE_NAME_SZ = 16, /* Maximum size of curve name string */ + MAX_CURVE_NAME_SZ = 18, /* Maximum size of curve name string */ NEW_SA_MAJOR = 8, /* Most significant byte used with new sig algos */ ED25519_SA_MAJOR = 8, /* Most significant byte for ED25519 */ @@ -1787,16 +1796,16 @@ enum Misc { FALCON_LEVEL5_SA_MINOR = 0xB1, DILITHIUM_LEVEL2_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL2_SA_MINOR = 0xA0, + DILITHIUM_LEVEL2_SA_MINOR = 0xD0, DILITHIUM_LEVEL3_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL3_SA_MINOR = 0xA3, + DILITHIUM_LEVEL3_SA_MINOR = 0xD1, DILITHIUM_LEVEL5_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL5_SA_MINOR = 0xA5, + DILITHIUM_LEVEL5_SA_MINOR = 0xD2, MIN_RSA_SHA512_PSS_BITS = 512 * 2 + 8 * 8, /* Min key size */ MIN_RSA_SHA384_PSS_BITS = 384 * 2 + 8 * 8, /* Min key size */ -#if defined(HAVE_PQC) +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) MAX_CERT_VERIFY_SZ = 6000, /* For Dilithium */ #elif defined(WOLFSSL_CERT_EXT) MAX_CERT_VERIFY_SZ = 2048, /* For larger extensions */ @@ -1848,13 +1857,13 @@ enum Misc { #define WOLFSSL_NAMED_GROUP_IS_FFHDE(group) \ (MIN_FFHDE_GROUP <= (group) && (group) <= MAX_FFHDE_GROUP) -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER #define WOLFSSL_NAMED_GROUP_IS_PQC(group) \ ((WOLFSSL_PQC_SIMPLE_MIN <= (group) && (group) <= WOLFSSL_PQC_SIMPLE_MAX) || \ (WOLFSSL_PQC_HYBRID_MIN <= (group) && (group) <= WOLFSSL_PQC_HYBRID_MAX)) #else #define WOLFSSL_NAMED_GROUP_IS_PQC(group) ((void)(group), 0) -#endif /* HAVE_PQC */ +#endif /* WOLFSSL_HAVE_KYBER */ /* minimum Downgrade Minor version */ #ifndef WOLFSSL_MIN_DOWNGRADE @@ -1884,7 +1893,7 @@ enum Misc { /* number of items in the signature algo list */ #ifndef WOLFSSL_MAX_SIGALGO -#ifdef HAVE_PQC +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) /* If we are building with post-quantum algorithms, we likely want to * inter-op with OQS's OpenSSL and they send a lot more sigalgs. */ @@ -1913,12 +1922,14 @@ enum Misc { #endif #define MIN_ECCKEY_SZ (WOLFSSL_MIN_ECC_BITS / 8) -#ifdef HAVE_PQC +#ifdef HAVE_FALCON #ifndef MIN_FALCONKEY_SZ - #define MIN_FALCONKEY_SZ 897 + #define MIN_FALCONKEY_SZ 1281 +#endif #endif +#ifdef HAVE_DILITHIUM #ifndef MIN_DILITHIUMKEY_SZ - #define MIN_DILITHIUMKEY_SZ 1312 + #define MIN_DILITHIUMKEY_SZ 2528 #endif #endif @@ -1961,7 +1972,7 @@ enum Misc { #endif #ifndef MAX_X509_SIZE - #if defined(HAVE_PQC) + #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) #define MAX_X509_SIZE (8*1024) /* max static x509 buffer size; dilithium is big */ #elif defined(WOLFSSL_HAPROXY) #define MAX_X509_SIZE 3072 /* max static x509 buffer size */ @@ -2169,17 +2180,22 @@ WOLFSSL_LOCAL int DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutI WOLFSSL_LOCAL int CompleteServerHello(WOLFSSL *ssl); WOLFSSL_LOCAL int CheckVersion(WOLFSSL *ssl, ProtocolVersion pv); WOLFSSL_LOCAL int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, - word32 hashSigAlgoSz); + word32 hashSigAlgoSz, int matchSuites); #if defined(WOLF_PRIVATE_KEY_ID) && !defined(NO_CHECK_PRIVATE_KEY) WOLFSSL_LOCAL int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType, int label, int id, void* heap, int devId); #endif -WOLFSSL_LOCAL int DecodePrivateKey(WOLFSSL *ssl, word16* length); +#ifdef WOLFSSL_BLIND_PRIVATE_KEY +WOLFSSL_LOCAL int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key, + DerBuffer** mask); +WOLFSSL_LOCAL void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask); +#endif +WOLFSSL_LOCAL int DecodePrivateKey(WOLFSSL *ssl, word32* length); #ifdef WOLFSSL_DUAL_ALG_CERTS -WOLFSSL_LOCAL int DecodeAltPrivateKey(WOLFSSL *ssl, word16* length); +WOLFSSL_LOCAL int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length); #endif -#ifdef WOLF_PRIVATE_KEY_ID +#if defined(WOLF_PRIVATE_KEY_ID) || defined(HAVE_PK_CALLBACKS) WOLFSSL_LOCAL int GetPrivateKeySigSize(WOLFSSL* ssl); #ifndef NO_ASN WOLFSSL_LOCAL int InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx); @@ -2195,9 +2211,9 @@ WOLFSSL_LOCAL void FreeAsyncCtx(WOLFSSL* ssl, byte freeAsync); WOLFSSL_LOCAL void FreeKeyExchange(WOLFSSL* ssl); WOLFSSL_LOCAL void FreeSuites(WOLFSSL* ssl); WOLFSSL_LOCAL int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz); -WOLFSSL_LOCAL int MatchDomainName(const char* pattern, int len, const char* str); +WOLFSSL_LOCAL int MatchDomainName(const char* pattern, int len, const char* str, word32 strLen); #ifndef NO_CERTS -WOLFSSL_LOCAL int CheckForAltNames(DecodedCert* dCert, const char* domain, int* checkCN); +WOLFSSL_LOCAL int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, int* checkCN); WOLFSSL_LOCAL int CheckIPAddr(DecodedCert* dCert, const char* ipasc); WOLFSSL_LOCAL void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType); #endif @@ -2273,6 +2289,8 @@ enum { /* determine maximum record size */ +#define MAX_RECORD_SIZE 16384 /* 2^14, max size by standard */ + #ifdef RECORD_SIZE /* user supplied value */ #if RECORD_SIZE < 128 || RECORD_SIZE > MAX_RECORD_SIZE @@ -2353,16 +2371,8 @@ typedef struct CipherSuite { #endif } CipherSuite; -WOLFSSL_LOCAL void InitSuitesHashSigAlgo(Suites* suites, int haveECDSAsig, - int haveRSAsig, int haveFalconSig, - int haveDilithiumSig, int haveAnon, - int tls1_2, int keySz); -WOLFSSL_LOCAL void InitSuitesHashSigAlgo_ex(byte* hashSigAlgo, int haveECDSAsig, - int haveRSAsig, int haveFalconSig, - int haveDilithiumSig, int haveAnon, - int tls1_2, int keySz, word16* len); /* use wolfSSL_API visibility to be able to test in tests/api.c */ -WOLFSSL_API void InitSuitesHashSigAlgo_ex2(byte* hashSigAlgo, int have, +WOLFSSL_API void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have, int tls1_2, int keySz, word16* len); WOLFSSL_LOCAL int AllocateCtxSuites(WOLFSSL_CTX* ctx); @@ -2631,8 +2641,10 @@ struct WOLFSSL_CERT_MANAGER { /* with CTX free. */ #endif wolfSSL_Ref ref; -#ifdef HAVE_PQC +#ifdef HAVE_FALCON short minFalconKeySz; /* minimum allowed Falcon key size */ +#endif +#ifdef HAVE_DILITHIUM short minDilithiumKeySz; /* minimum allowed Dilithium key size */ #endif #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ @@ -2683,6 +2695,14 @@ typedef struct ProcPeerCertArgs { } ProcPeerCertArgs; WOLFSSL_LOCAL int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret, ProcPeerCertArgs* args); +WOLFSSL_LOCAL void DoCrlCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, + ProcPeerCertArgs* args, int* outRet); + +WOLFSSL_LOCAL int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, + WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args, + int cert_err, void* heap, int* x509Free); +WOLFSSL_LOCAL void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store, + WOLFSSL* ssl, void* heap, int x509Free); #endif /* !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) */ #endif /* !defined NO_CERTS */ @@ -2806,74 +2826,108 @@ typedef struct Options Options; /** TLS Extensions - RFC 6066 */ #ifdef HAVE_TLS_EXTENSIONS +#define TLSXT_SERVER_NAME 0x0000 /* a.k.a. SNI */ +#define TLSXT_MAX_FRAGMENT_LENGTH 0x0001 +#define TLSXT_TRUSTED_CA_KEYS 0x0003 +#define TLSXT_TRUNCATED_HMAC 0x0004 +#define TLSXT_STATUS_REQUEST 0x0005 /* a.k.a. OCSP stapling */ +#define TLSXT_SUPPORTED_GROUPS 0x000a /* a.k.a. Supported Curves */ +#define TLSXT_EC_POINT_FORMATS 0x000b +#define TLSXT_SIGNATURE_ALGORITHMS 0x000d /* HELLO_EXT_SIG_ALGO */ +#define TLSXT_USE_SRTP 0x000e /* 14 */ +#define TLSXT_APPLICATION_LAYER_PROTOCOL 0x0010 /* a.k.a. ALPN */ +#define TLSXT_STATUS_REQUEST_V2 0x0011 /* a.k.a. OCSP stapling v2 */ +#define TLSXT_CLIENT_CERTIFICATE 0x0013 /* RFC8446 */ +#define TLSXT_SERVER_CERTIFICATE 0x0014 /* RFC8446 */ +#define TLSXT_ENCRYPT_THEN_MAC 0x0016 /* RFC 7366 */ +#define TLSXT_EXTENDED_MASTER_SECRET 0x0017 /* HELLO_EXT_EXTMS */ +#define TLSXT_SESSION_TICKET 0x0023 +#define TLSXT_PRE_SHARED_KEY 0x0029 +#define TLSXT_EARLY_DATA 0x002a +#define TLSXT_SUPPORTED_VERSIONS 0x002b +#define TLSXT_COOKIE 0x002c +#define TLSXT_PSK_KEY_EXCHANGE_MODES 0x002d +#define TLSXT_CERTIFICATE_AUTHORITIES 0x002f +#define TLSXT_POST_HANDSHAKE_AUTH 0x0031 +#define TLSXT_SIGNATURE_ALGORITHMS_CERT 0x0032 +#define TLSXT_KEY_SHARE 0x0033 +#define TLSXT_CONNECTION_ID 0x0036 +#define TLSXT_KEY_QUIC_TP_PARAMS 0x0039 /* RFC 9001, ch. 8.2 */ +#define TLSXT_ECH 0xfe0d /* from */ + /* draft-ietf-tls-esni-13 */ +/* The 0xFF section is experimental/custom/personal use */ +#define TLSXT_CKS 0xff92 /* X9.146 */ +#define TLSXT_RENEGOTIATION_INFO 0xff01 +#define TLSXT_KEY_QUIC_TP_PARAMS_DRAFT 0xffa5 /* from */ + /* draft-ietf-quic-tls-27 */ + typedef enum { #ifdef HAVE_SNI - TLSX_SERVER_NAME = 0x0000, /* a.k.a. SNI */ -#endif - TLSX_MAX_FRAGMENT_LENGTH = 0x0001, - TLSX_TRUSTED_CA_KEYS = 0x0003, - TLSX_TRUNCATED_HMAC = 0x0004, - TLSX_STATUS_REQUEST = 0x0005, /* a.k.a. OCSP stapling */ - TLSX_SUPPORTED_GROUPS = 0x000a, /* a.k.a. Supported Curves */ - TLSX_EC_POINT_FORMATS = 0x000b, + TLSX_SERVER_NAME = TLSXT_SERVER_NAME, +#endif + TLSX_MAX_FRAGMENT_LENGTH = TLSXT_MAX_FRAGMENT_LENGTH, + TLSX_TRUSTED_CA_KEYS = TLSXT_TRUSTED_CA_KEYS, + TLSX_TRUNCATED_HMAC = TLSXT_TRUNCATED_HMAC, + TLSX_STATUS_REQUEST = TLSXT_STATUS_REQUEST, + TLSX_SUPPORTED_GROUPS = TLSXT_SUPPORTED_GROUPS, + TLSX_EC_POINT_FORMATS = TLSXT_EC_POINT_FORMATS, #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) - TLSX_SIGNATURE_ALGORITHMS = 0x000d, /* HELLO_EXT_SIG_ALGO */ + TLSX_SIGNATURE_ALGORITHMS = TLSXT_SIGNATURE_ALGORITHMS, #endif #ifdef WOLFSSL_SRTP - TLSX_USE_SRTP = 0x000e, /* 14 */ + TLSX_USE_SRTP = TLSXT_USE_SRTP, #endif - TLSX_APPLICATION_LAYER_PROTOCOL = 0x0010, /* a.k.a. ALPN */ - TLSX_STATUS_REQUEST_V2 = 0x0011, /* a.k.a. OCSP stapling v2 */ + TLSX_APPLICATION_LAYER_PROTOCOL = TLSXT_APPLICATION_LAYER_PROTOCOL, + TLSX_STATUS_REQUEST_V2 = TLSXT_STATUS_REQUEST_V2, #ifdef HAVE_RPK - TLSX_CLIENT_CERTIFICATE_TYPE = 0x0013, /* RFC8446 */ - TLSX_SERVER_CERTIFICATE_TYPE = 0x0014, /* RFC8446 */ + TLSX_CLIENT_CERTIFICATE_TYPE = TLSXT_CLIENT_CERTIFICATE, + TLSX_SERVER_CERTIFICATE_TYPE = TLSXT_SERVER_CERTIFICATE, #endif #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - TLSX_ENCRYPT_THEN_MAC = 0x0016, /* RFC 7366 */ + TLSX_ENCRYPT_THEN_MAC = TLSXT_ENCRYPT_THEN_MAC, #endif - TLSX_EXTENDED_MASTER_SECRET = 0x0017, /* HELLO_EXT_EXTMS */ - TLSX_SESSION_TICKET = 0x0023, + TLSX_EXTENDED_MASTER_SECRET = TLSXT_EXTENDED_MASTER_SECRET, + TLSX_SESSION_TICKET = TLSXT_SESSION_TICKET, #ifdef WOLFSSL_TLS13 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - TLSX_PRE_SHARED_KEY = 0x0029, + TLSX_PRE_SHARED_KEY = TLSXT_PRE_SHARED_KEY, #endif #ifdef WOLFSSL_EARLY_DATA - TLSX_EARLY_DATA = 0x002a, + TLSX_EARLY_DATA = TLSXT_EARLY_DATA, #endif - TLSX_SUPPORTED_VERSIONS = 0x002b, + TLSX_SUPPORTED_VERSIONS = TLSXT_SUPPORTED_VERSIONS, #ifdef WOLFSSL_SEND_HRR_COOKIE - TLSX_COOKIE = 0x002c, + TLSX_COOKIE = TLSXT_COOKIE, #endif #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - TLSX_PSK_KEY_EXCHANGE_MODES = 0x002d, + TLSX_PSK_KEY_EXCHANGE_MODES = TLSXT_PSK_KEY_EXCHANGE_MODES, #endif #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) - TLSX_CERTIFICATE_AUTHORITIES = 0x002f, + TLSX_CERTIFICATE_AUTHORITIES = TLSXT_CERTIFICATE_AUTHORITIES, #endif #ifdef WOLFSSL_POST_HANDSHAKE_AUTH - TLSX_POST_HANDSHAKE_AUTH = 0x0031, + TLSX_POST_HANDSHAKE_AUTH = TLSXT_POST_HANDSHAKE_AUTH, #endif #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) - TLSX_SIGNATURE_ALGORITHMS_CERT = 0x0032, + TLSX_SIGNATURE_ALGORITHMS_CERT = TLSXT_SIGNATURE_ALGORITHMS_CERT, #endif - TLSX_KEY_SHARE = 0x0033, + TLSX_KEY_SHARE = TLSXT_KEY_SHARE, #if defined(WOLFSSL_DTLS_CID) - TLSX_CONNECTION_ID = 0x0036, + TLSX_CONNECTION_ID = TLSXT_CONNECTION_ID, #endif /* defined(WOLFSSL_DTLS_CID) */ #ifdef WOLFSSL_QUIC - TLSX_KEY_QUIC_TP_PARAMS = 0x0039, /* RFC 9001, ch. 8.2 */ + TLSX_KEY_QUIC_TP_PARAMS = TLSXT_KEY_QUIC_TP_PARAMS, #endif - #ifdef WOLFSSL_DUAL_ALG_CERTS - TLSX_CKS = 0xff92, /* X9.146; ff indcates personal - * use and 92 is hex for 146. */ + #ifdef HAVE_ECH + TLSX_ECH = TLSXT_ECH, #endif #endif - TLSX_RENEGOTIATION_INFO = 0xff01, -#ifdef WOLFSSL_QUIC - TLSX_KEY_QUIC_TP_PARAMS_DRAFT = 0xffa5, /* from draft-ietf-quic-tls-27 */ +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_DUAL_ALG_CERTS) + TLSX_CKS = TLSXT_CKS, #endif -#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) - TLSX_ECH = 0xfe0d, /* from draft-ietf-tls-esni-13 */ + TLSX_RENEGOTIATION_INFO = TLSXT_RENEGOTIATION_INFO, +#ifdef WOLFSSL_QUIC + TLSX_KEY_QUIC_TP_PARAMS_DRAFT = TLSXT_KEY_QUIC_TP_PARAMS_DRAFT, #endif } TLSX_Type; @@ -2986,9 +3040,9 @@ WOLFSSL_LOCAL int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isRequest); #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT) WOLFSSL_LOCAL int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, - word16* pLength); + word32* pLength); WOLFSSL_LOCAL int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, - byte msgType, word16* pOffset); + byte msgType, word32* pOffset); #endif #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER) @@ -3044,7 +3098,7 @@ WOLFSSL_LOCAL int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size, void* heap); WOLFSSL_LOCAL byte TLSX_SNI_Status(TLSX* extensions, byte type); WOLFSSL_LOCAL word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, - void** data); + void** data, byte ignoreStatus); #ifndef NO_WOLFSSL_SERVER WOLFSSL_LOCAL void TLSX_SNI_SetOptions(TLSX* extensions, byte type, @@ -3140,11 +3194,17 @@ typedef struct CSRIv2 { OcspRequest ocsp[1 + MAX_CHAIN_DEPTH]; } request; struct CSRIv2* next; + Signer *pendingSigners; } CertificateStatusRequestItemV2; WOLFSSL_LOCAL int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type, byte options, void* heap, int devId); #ifndef NO_CERTS +WOLFSSL_LOCAL int TLSX_CSR2_IsMulti(TLSX *extensions); +WOLFSSL_LOCAL int TLSX_CSR2_AddPendingSigner(TLSX *extensions, Signer *s); +WOLFSSL_LOCAL Signer* TLSX_CSR2_GetPendingSigners(TLSX *extensions); +WOLFSSL_LOCAL int TLSX_CSR2_ClearPendingCA(WOLFSSL *ssl); +WOLFSSL_LOCAL int TLSX_CSR2_MergePendingCA(WOLFSSL* ssl); WOLFSSL_LOCAL int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer, void* heap); #endif @@ -3369,7 +3429,7 @@ typedef struct KeyShareEntry { word32 keyLen; /* Key size (bytes) */ byte* pubKey; /* Public key */ word32 pubKeyLen; /* Public key length */ -#if !defined(NO_DH) || defined(HAVE_PQC) +#if !defined(NO_DH) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) byte* privKey; /* Private key - DH and PQ KEMs only */ word32 privKeyLen;/* Only for PQ KEMs. */ #endif @@ -3575,7 +3635,10 @@ struct WOLFSSL_CTX { int certChainCnt; #endif DerBuffer* privateKey; - byte privateKeyType:6; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + DerBuffer* privateKeyMask; /* Mask of private key DER. */ +#endif + byte privateKeyType; byte privateKeyId:1; byte privateKeyLabel:1; int privateKeySz; @@ -3583,8 +3646,14 @@ struct WOLFSSL_CTX { #ifdef WOLFSSL_DUAL_ALG_CERTS DerBuffer* altPrivateKey; +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + DerBuffer* altPrivateKeyMask; /* Mask of alt private key DER. */ +#endif byte altPrivateKeyType; + byte altPrivateKeyId:1; + byte altPrivateKeyLabel:1; int altPrivateKeySz; + int altPrivateKeyDevId; #endif /* WOLFSSL_DUAL_ALG_CERTS */ #ifdef OPENSSL_ALL WOLFSSL_EVP_PKEY* privateKeyPKey; @@ -3693,8 +3762,10 @@ struct WOLFSSL_CTX { #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) short minEccKeySz; /* minimum ECC key size */ #endif -#ifdef HAVE_PQC +#ifdef HAVE_FALCON short minFalconKeySz; /* minimum Falcon key size */ +#endif +#ifdef HAVE_DILITHIUM short minDilithiumKeySz;/* minimum Dilithium key size */ #endif unsigned long mask; /* store SSL_OP_ flags */ @@ -3989,6 +4060,7 @@ int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 inSz, word16 sz); #ifndef NO_CERTS + WOLFSSL_LOCAL int AddSigner(WOLFSSL_CERT_MANAGER* cm, Signer *s); WOLFSSL_LOCAL int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify); WOLFSSL_LOCAL @@ -4035,13 +4107,16 @@ enum KeyExchangeAlgorithm { ecc_static_diffie_hellman_kea /* for verify suite only */ }; -/* Used with InitSuitesHashSigAlgo_ex2 */ +/* Used with InitSuitesHashSigAlgo */ #define SIG_ECDSA 0x01 #define SIG_RSA 0x02 #define SIG_SM2 0x04 #define SIG_FALCON 0x08 #define SIG_DILITHIUM 0x10 #define SIG_ANON 0x20 +/* SIG_ANON is omitted by default */ +#define SIG_ALL (SIG_ECDSA | SIG_RSA | SIG_SM2 | SIG_FALCON | \ + SIG_DILITHIUM) /* Supported Authentication Schemes */ enum SignatureAlgorithm { @@ -4406,6 +4481,10 @@ struct WOLFSSL_SESSION { #endif #ifdef HAVE_EX_DATA WOLFSSL_CRYPTO_EX_DATA ex_data; +#endif +#ifdef HAVE_MAX_FRAGMENT + byte mfl; /* max fragment length negotiated i.e. + * WOLFSSL_MFL_2_8 (6) */ #endif byte isSetup:1; }; @@ -4548,15 +4627,24 @@ typedef struct Buffers { #ifndef NO_CERTS DerBuffer* certificate; /* WOLFSSL_CTX owns, unless we own */ DerBuffer* key; /* WOLFSSL_CTX owns, unless we own */ - byte keyType:6; /* Type of key: RSA, ECC, Ed25519 */ +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + DerBuffer* keyMask; /* Mask of private key DER. */ +#endif + byte keyType; /* Type of key */ byte keyId:1; /* Key data is an id not data */ byte keyLabel:1; /* Key data is a label not data */ int keySz; /* Size of RSA key */ int keyDevId; /* Device Id for key */ #ifdef WOLFSSL_DUAL_ALG_CERTS DerBuffer* altKey; /* WOLFSSL_CTX owns, unless we own */ - byte altKeyType; /* Type of key: dilithium, falcon */ - int altKeySz; /* Size of key */ +#ifdef WOLFSSL_BLIND_PRIVATE_KEY + DerBuffer* altKeyMask; /* Mask of alt private key DER. */ +#endif + byte altKeyType; /* Type of alt key */ + byte altKeyId:1; /* Key data is an id not data */ + byte altKeyLabel:1; /* Key data is a label not data */ + int altKeySz; /* Size of alt key */ + int altKeyDevId; /* Device Id for alt key */ #endif DerBuffer* certChain; /* WOLFSSL_CTX owns, unless we own */ /* chain after self, in DER, with leading size for each cert */ @@ -4841,8 +4929,10 @@ struct Options { #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) short minEccKeySz; /* minimum ECC key size */ #endif -#if defined(HAVE_PQC) +#if defined(HAVE_FALCON) short minFalconKeySz; /* minimum Falcon key size */ +#endif +#if defined(HAVE_DILITHIUM) short minDilithiumKeySz;/* minimum Dilithium key size */ #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) @@ -5036,9 +5126,9 @@ struct WOLFSSL_X509 { int pubKeyOID; DNS_entry* altNamesNext; /* hint for retrieval */ #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ - defined(HAVE_PQC) + defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) word32 pkCurveOID; -#endif /* HAVE_ECC || HAVE_PQC */ +#endif #ifndef NO_CERTS DerBuffer* derCert; /* may need */ #endif @@ -5631,9 +5721,11 @@ struct WOLFSSL { curve448_key* peerX448Key; byte peerX448KeyPresent; #endif -#ifdef HAVE_PQC +#ifdef HAVE_FALCON falcon_key* peerFalconKey; byte peerFalconKeyPresent; +#endif +#ifdef HAVE_DILITHIUM dilithium_key* peerDilithiumKey; byte peerDilithiumKeyPresent; #endif @@ -5861,6 +5953,10 @@ struct WOLFSSL { #ifdef HAVE_SECRET_CALLBACK SessionSecretCb sessionSecretCb; void* sessionSecretCtx; + TicketParseCb ticketParseCb; + void* ticketParseCtx; + TlsSecretCb tlsSecretCb; + void* tlsSecretCtx; #ifdef WOLFSSL_TLS13 Tls13SecretCb tls13SecretCb; void* tls13SecretCtx; @@ -6110,16 +6206,11 @@ typedef struct { int name_len; const char *name; int nid; + word16 curve; } WOLF_EC_NIST_NAME; extern const WOLF_EC_NIST_NAME kNistCurves[]; -/* This is the longest and shortest curve name in the kNistCurves list. Note we - * also have quantum-safe group names as well. */ -#define kNistCurves_MIN_NAME_LEN 5 -#ifdef HAVE_PQC -#define kNistCurves_MAX_NAME_LEN 32 -#else -#define kNistCurves_MAX_NAME_LEN 7 -#endif +WOLFSSL_LOCAL int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, + const char* names, byte curves_only); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ /* internal functions */ @@ -6179,6 +6270,7 @@ WOLFSSL_LOCAL int DeriveKeys(WOLFSSL* ssl); WOLFSSL_LOCAL int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side); WOLFSSL_LOCAL int IsTLS(const WOLFSSL* ssl); +WOLFSSL_LOCAL int IsTLS_ex(const ProtocolVersion pv); WOLFSSL_LOCAL int IsAtLeastTLSv1_2(const WOLFSSL* ssl); WOLFSSL_LOCAL int IsAtLeastTLSv1_3(ProtocolVersion pv); WOLFSSL_LOCAL int IsEncryptionOn(const WOLFSSL* ssl, int isSend); @@ -6407,6 +6499,7 @@ WOLFSSL_LOCAL int cipherExtraData(WOLFSSL* ssl); WOLFSSL_LOCAL word32 LowResTimer(void); WOLFSSL_LOCAL int FindSuiteSSL(const WOLFSSL* ssl, byte* suite); +WOLFSSL_LOCAL int FindSuite(const Suites* suites, byte first, byte second); WOLFSSL_LOCAL void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType); @@ -6741,6 +6834,11 @@ WOLFSSL_LOCAL int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* se int secretSz, void* ctx); #endif +#if defined(SHOW_SECRETS) +WOLFSSL_LOCAL int tlsShowSecrets(WOLFSSL* ssl, void* secret, + int secretSz, void* ctx); +#endif + /* Optional Pre-Master-Secret logging for Wireshark */ #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE) #ifndef WOLFSSL_SSLKEYLOGFILE_OUTPUT diff --git a/src/wolfssl/openssl/bn.h b/src/wolfssl/openssl/bn.h index 973b855..d5ad52b 100644 --- a/src/wolfssl/openssl/bn.h +++ b/src/wolfssl/openssl/bn.h @@ -40,7 +40,9 @@ typedef struct WOLFSSL_BIGNUM { int neg; /* openssh deference */ void *internal; /* our big num */ +#if !defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH) mp_int mpi; +#endif } WOLFSSL_BIGNUM; #define WOLFSSL_BN_ULONG unsigned long diff --git a/src/wolfssl/openssl/ec.h b/src/wolfssl/openssl/ec.h index 23ef5e9..da988c6 100644 --- a/src/wolfssl/openssl/ec.h +++ b/src/wolfssl/openssl/ec.h @@ -74,9 +74,15 @@ enum { #ifdef HAVE_ED448 NID_ED448 = ED448k, #endif +#ifdef HAVE_CURVE448 + NID_X448 = X448k, +#endif #ifdef HAVE_ED25519 NID_ED25519 = ED25519k, #endif +#ifdef HAVE_CURVE25519 + NID_X25519 = X25519k, +#endif OPENSSL_EC_EXPLICIT_CURVE = 0x000, OPENSSL_EC_NAMED_CURVE = 0x001, @@ -138,6 +144,12 @@ struct WOLFSSL_EC_BUILTIN_CURVE { typedef int point_conversion_form_t; +typedef struct WOLFSSL_EC_KEY_METHOD { + /* Not implemented */ + /* Just here so that some C compilers don't complain. To be removed. */ + void* dummy_member; +} WOLFSSL_EC_KEY_METHOD; + WOLFSSL_API size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *r,size_t nitems); @@ -306,12 +318,29 @@ WOLFSSL_API int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group, const WOLFSSL_EC_POINT *a); -#ifndef HAVE_SELFTEST WOLFSSL_API char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx); -#endif +WOLFSSL_API +WOLFSSL_EC_POINT *wolfSSL_EC_POINT_hex2point + (const WOLFSSL_EC_GROUP *group, const char *hex, + WOLFSSL_EC_POINT *p, WOLFSSL_BN_CTX *ctx); + +WOLFSSL_API const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_OpenSSL(void); +WOLFSSL_API WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_METHOD_new( + const WOLFSSL_EC_KEY_METHOD *meth); +WOLFSSL_API void wolfSSL_EC_KEY_METHOD_free(WOLFSSL_EC_KEY_METHOD *meth); +/* TODO when implementing change the types to the real callback signatures + * and use real parameter names */ +WOLFSSL_API void wolfSSL_EC_KEY_METHOD_set_init(WOLFSSL_EC_KEY_METHOD *meth, + void* a1, void* a2, void* a3, void* a4, void* a5, void* a6); +WOLFSSL_API void wolfSSL_EC_KEY_METHOD_set_sign(WOLFSSL_EC_KEY_METHOD *meth, + void* a1, void* a2, void* a3); +WOLFSSL_API const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_get_method( + const WOLFSSL_EC_KEY *key); +WOLFSSL_API int wolfSSL_EC_KEY_set_method(WOLFSSL_EC_KEY *key, + const WOLFSSL_EC_KEY_METHOD *meth); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) @@ -320,6 +349,7 @@ typedef WOLFSSL_EC_GROUP EC_GROUP; typedef WOLFSSL_EC_GROUP EC_METHOD; typedef WOLFSSL_EC_POINT EC_POINT; typedef WOLFSSL_EC_BUILTIN_CURVE EC_builtin_curve; +typedef WOLFSSL_EC_KEY_METHOD EC_KEY_METHOD; #ifndef HAVE_ECC #define OPENSSL_NO_EC @@ -395,9 +425,8 @@ typedef WOLFSSL_EC_BUILTIN_CURVE EC_builtin_curve; #define EC_KEY_set_conv_form wolfSSL_EC_KEY_set_conv_form #define EC_KEY_get_conv_form wolfSSL_EC_KEY_get_conv_form -#ifndef HAVE_SELFTEST - #define EC_POINT_point2hex wolfSSL_EC_POINT_point2hex -#endif +#define EC_POINT_point2hex wolfSSL_EC_POINT_point2hex +#define EC_POINT_hex2point wolfSSL_EC_POINT_hex2point #define EC_POINT_dump wolfSSL_EC_POINT_dump #define EC_get_builtin_curves wolfSSL_EC_get_builtin_curves @@ -405,6 +434,14 @@ typedef WOLFSSL_EC_BUILTIN_CURVE EC_builtin_curve; #define EC_curve_nid2nist wolfSSL_EC_curve_nid2nist #define EC_curve_nist2nid wolfSSL_EC_curve_nist2nid +#define EC_KEY_OpenSSL wolfSSL_EC_KEY_OpenSSL +#define EC_KEY_METHOD_new wolfSSL_EC_KEY_METHOD_new +#define EC_KEY_METHOD_free wolfSSL_EC_KEY_METHOD_free +#define EC_KEY_METHOD_set_init wolfSSL_EC_KEY_METHOD_set_init +#define EC_KEY_METHOD_set_sign wolfSSL_EC_KEY_METHOD_set_sign +#define EC_KEY_get_method wolfSSL_EC_KEY_get_method +#define EC_KEY_set_method wolfSSL_EC_KEY_set_method + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/evp.h b/src/wolfssl/openssl/evp.h index bdeabf2..346cefc 100644 --- a/src/wolfssl/openssl/evp.h +++ b/src/wolfssl/openssl/evp.h @@ -401,6 +401,7 @@ typedef union { #define NID_X9_62_id_ecPublicKey EVP_PKEY_EC #define NID_rsaEncryption EVP_PKEY_RSA +#define NID_rsa EVP_PKEY_RSA #define NID_dsa EVP_PKEY_DSA #define EVP_PKEY_OP_SIGN (1 << 3) diff --git a/src/wolfssl/openssl/hmac.h b/src/wolfssl/openssl/hmac.h index 427a3d6..818c860 100644 --- a/src/wolfssl/openssl/hmac.h +++ b/src/wolfssl/openssl/hmac.h @@ -45,7 +45,7 @@ WOLFSSL_API unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, int key_len, - const unsigned char* d, int n, unsigned char* md, + const unsigned char* d, size_t n, unsigned char* md, unsigned int* md_len); WOLFSSL_API WOLFSSL_HMAC_CTX* wolfSSL_HMAC_CTX_new(void); @@ -69,7 +69,7 @@ WOLFSSL_API const WOLFSSL_EVP_MD *wolfSSL_HMAC_CTX_get_md(const WOLFSSL_HMAC_CTX typedef struct WOLFSSL_HMAC_CTX HMAC_CTX; -#define HMAC(a,b,c,d,e,f,g) wolfSSL_HMAC((a),(b),(c),(d),(e),(f),(g)) +#define HMAC wolfSSL_HMAC #define HMAC_CTX_new wolfSSL_HMAC_CTX_new #define HMAC_CTX_init wolfSSL_HMAC_CTX_Init diff --git a/src/wolfssl/openssl/opensslv.h b/src/wolfssl/openssl/opensslv.h index 57404c9..f68b6ca 100644 --- a/src/wolfssl/openssl/opensslv.h +++ b/src/wolfssl/openssl/opensslv.h @@ -25,6 +25,7 @@ #define WOLFSSL_OPENSSLV_H_ #include +#include #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) diff --git a/src/wolfssl/openssl/sha.h b/src/wolfssl/openssl/sha.h index c364414..ab38c5c 100644 --- a/src/wolfssl/openssl/sha.h +++ b/src/wolfssl/openssl/sha.h @@ -27,7 +27,7 @@ #include #include - +#include #ifdef WOLFSSL_PREFIX #include "prefix_sha.h" #endif @@ -151,7 +151,7 @@ typedef WOLFSSL_SHA224_CTX SHA224_CTX; * to Sha256, is expected to also be 16 byte aligned addresses. */ typedef struct WOLFSSL_SHA256_CTX { /* big enough to hold wolfcrypt Sha256, but check on init */ - ALIGN16 void* holder[(274 + CTX_SHA_HW_ADDER + WC_ASYNC_DEV_SIZE) / + ALIGN16 void* holder[sizeof(wc_Sha256) / sizeof(void*)]; #if defined(WOLFSSL_DEVCRYPTO_HASH) || defined(WOLFSSL_HASH_KEEP) ALIGN16 void* keephash_holder[sizeof(void*) + (2 * sizeof(unsigned int))]; diff --git a/src/wolfssl/openssl/sha3.h b/src/wolfssl/openssl/sha3.h index 1b0d63b..4407bca 100644 --- a/src/wolfssl/openssl/sha3.h +++ b/src/wolfssl/openssl/sha3.h @@ -27,6 +27,7 @@ #include #include +#include #ifdef WOLFSSL_PREFIX #include "prefix_sha.h" @@ -41,7 +42,11 @@ * to Sha3 is expected to also be 16 byte aligned addresses. */ struct WOLFSSL_SHA3_CTX { /* big enough to hold wolfcrypt Sha3, but check on init */ +#ifdef WOLFSSL_SHA3 + ALIGN16 void* holder[sizeof(wc_Sha3)]; +#else ALIGN16 void* holder[(424 + WC_ASYNC_DEV_SIZE) / sizeof(void*)]; +#endif }; #ifndef WOLFSSL_NOSHA3_224 diff --git a/src/wolfssl/openssl/ssl.h b/src/wolfssl/openssl/ssl.h index 5cd96e2..0fbf621 100644 --- a/src/wolfssl/openssl/ssl.h +++ b/src/wolfssl/openssl/ssl.h @@ -210,6 +210,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define i2d_PKCS8PrivateKey_bio wolfSSL_PEM_write_bio_PKCS8PrivateKey #define PKCS8_PRIV_KEY_INFO_free wolfSSL_EVP_PKEY_free #define d2i_PKCS12_fp wolfSSL_d2i_PKCS12_fp +#define SSL_set_ecdh_auto wolfSSL_set_ecdh_auto #define SSL_CTX_set_ecdh_auto wolfSSL_CTX_set_ecdh_auto #define i2d_PUBKEY wolfSSL_i2d_PUBKEY @@ -366,6 +367,8 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_SESSION_dup wolfSSL_SESSION_dup #define SSL_SESSION_free wolfSSL_SESSION_free #define SSL_SESSION_set_cipher wolfSSL_SESSION_set_cipher +#define SSL_SESSION_get_max_fragment_length \ + wolfSSL_SESSION_get_max_fragment_length #define SSL_is_init_finished wolfSSL_is_init_finished #define SSL_SESSION_set1_id wolfSSL_SESSION_set1_id @@ -500,6 +503,8 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define X509_set_pubkey wolfSSL_X509_set_pubkey #define X509_set_notAfter wolfSSL_X509_set_notAfter #define X509_set_notBefore wolfSSL_X509_set_notBefore +#define X509_set1_notAfter wolfSSL_X509_set1_notAfter +#define X509_set1_notBefore wolfSSL_X509_set1_notBefore #define X509_set_serialNumber wolfSSL_X509_set_serialNumber #define X509_set_version wolfSSL_X509_set_version #define X509_REQ_set_version wolfSSL_X509_set_version @@ -634,6 +639,9 @@ typedef WOLFSSL_X509_NAME_ENTRY X509_NAME_ENTRY; #define X509_V_FLAG_CRL_CHECK WOLFSSL_CRL_CHECK #define X509_V_FLAG_CRL_CHECK_ALL WOLFSSL_CRL_CHECKALL +#define X509_V_FLAG_PARTIAL_CHAIN 0 +#define X509_V_FLAG_TRUSTED_FIRST 0 + #define X509_V_FLAG_USE_CHECK_TIME WOLFSSL_USE_CHECK_TIME #define X509_V_FLAG_NO_CHECK_TIME WOLFSSL_NO_CHECK_TIME #define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT WOLFSSL_ALWAYS_CHECK_SUBJECT @@ -674,10 +682,13 @@ typedef WOLFSSL_X509_NAME_ENTRY X509_NAME_ENTRY; wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_CTX_verify_cb)(c)) #define X509_STORE_set_verify_cb_func(s, c) \ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_CTX_verify_cb)(c)) +#define X509_STORE_set_get_crl wolfSSL_X509_STORE_set_get_crl +#define X509_STORE_set_check_crl wolfSSL_X509_STORE_set_check_crl #define X509_STORE_new wolfSSL_X509_STORE_new #define X509_STORE_free wolfSSL_X509_STORE_free +#define X509_STORE_up_ref wolfSSL_X509_STORE_up_ref #define X509_STORE_add_lookup wolfSSL_X509_STORE_add_lookup #define X509_STORE_add_cert wolfSSL_X509_STORE_add_cert #define X509_STORE_add_crl wolfSSL_X509_STORE_add_crl @@ -686,8 +697,10 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_STORE_get_by_subject wolfSSL_X509_STORE_get_by_subject #define X509_STORE_set_ex_data wolfSSL_X509_STORE_set_ex_data #define X509_STORE_get_ex_data wolfSSL_X509_STORE_get_ex_data +#define X509_STORE_get0_param wolfSSL_X509_STORE_get0_param #define X509_STORE_CTX_get1_issuer wolfSSL_X509_STORE_CTX_get1_issuer #define X509_STORE_CTX_set_time wolfSSL_X509_STORE_CTX_set_time +#define X509_STORE_CTX_get0_param wolfSSL_X509_STORE_CTX_get0_param #define X509_VERIFY_PARAM_new wolfSSL_X509_VERIFY_PARAM_new #define X509_VERIFY_PARAM_free wolfSSL_X509_VERIFY_PARAM_free #define X509_VERIFY_PARAM_set_flags wolfSSL_X509_VERIFY_PARAM_set_flags @@ -711,6 +724,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define d2i_X509_CRL_fp wolfSSL_d2i_X509_CRL_fp #define PEM_read_X509_CRL wolfSSL_PEM_read_X509_CRL +#define X509_CRL_dup wolfSSL_X509_CRL_dup #define X509_CRL_free wolfSSL_X509_CRL_free #define X509_CRL_get_lastUpdate wolfSSL_X509_CRL_get_lastUpdate #define X509_CRL_get0_lastUpdate wolfSSL_X509_CRL_get_lastUpdate @@ -822,6 +836,10 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define COMP_rle wolfSSL_COMP_rle #define SSL_COMP_add_compression_method wolfSSL_COMP_add_compression_method +#define SSL_get_current_compression(ssl) 0 +#define SSL_get_current_expansion(ssl) 0 +#define SSL_COMP_get_name wolfSSL_COMP_get_name + #define SSL_get_ex_new_index wolfSSL_get_ex_new_index #define RSA_get_ex_new_index wolfSSL_get_ex_new_index @@ -835,18 +853,21 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #ifndef NO_ASN_TIME #define ASN1_TIME_new wolfSSL_ASN1_TIME_new #define ASN1_UTCTIME_new wolfSSL_ASN1_TIME_new +#define ASN1_GENERALIZEDTIME_new wolfSSL_ASN1_TIME_new #define ASN1_TIME_free wolfSSL_ASN1_TIME_free #define ASN1_UTCTIME_free wolfSSL_ASN1_TIME_free +#define ASN1_GENERALIZEDTIME_free wolfSSL_ASN1_TIME_free #define ASN1_TIME_adj wolfSSL_ASN1_TIME_adj #define ASN1_TIME_print wolfSSL_ASN1_TIME_print #define ASN1_TIME_to_string wolfSSL_ASN1_TIME_to_string #define ASN1_TIME_to_tm wolfSSL_ASN1_TIME_to_tm #define ASN1_TIME_to_generalizedtime wolfSSL_ASN1_TIME_to_generalizedtime +#define ASN1_UTCTIME_set wolfSSL_ASN1_UTCTIME_set #endif #define ASN1_TIME_set wolfSSL_ASN1_TIME_set #define ASN1_TIME_set_string wolfSSL_ASN1_TIME_set_string +#define ASN1_GENERALIZEDTIME_set_string wolfSSL_ASN1_TIME_set_string #define ASN1_GENERALIZEDTIME_print wolfSSL_ASN1_GENERALIZEDTIME_print -#define ASN1_GENERALIZEDTIME_free wolfSSL_ASN1_GENERALIZEDTIME_free #define ASN1_tag2str wolfSSL_ASN1_tag2str @@ -916,7 +937,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #endif #define SSL_set0_verify_cert_store wolfSSL_set0_verify_cert_store #define SSL_set1_verify_cert_store wolfSSL_set1_verify_cert_store -#define SSL_CTX_get_cert_store(x) wolfSSL_CTX_get_cert_store ((WOLFSSL_CTX*) (x)) +#define SSL_CTX_get_cert_store(x) wolfSSL_CTX_get_cert_store ((x)) #define SSL_get_client_CA_list wolfSSL_get_client_CA_list #define SSL_set_client_CA_list wolfSSL_set_client_CA_list #define SSL_get_ex_data_X509_STORE_CTX_idx wolfSSL_get_ex_data_X509_STORE_CTX_idx @@ -937,7 +958,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define SSL_alert_type_string wolfSSL_alert_type_string #define SSL_alert_desc_string wolfSSL_alert_desc_string -#define SSL_state_string wolfSSL_state_string +#define SSL_state_string wolfSSL_state_string_long #define RSA_free wolfSSL_RSA_free #define RSA_generate_key wolfSSL_RSA_generate_key @@ -1212,6 +1233,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define TLSEXT_STATUSTYPE_ocsp 1 +#define TLSEXT_max_fragment_length_DISABLED WOLFSSL_MFL_DISABLED #define TLSEXT_max_fragment_length_512 WOLFSSL_MFL_2_9 #define TLSEXT_max_fragment_length_1024 WOLFSSL_MFL_2_10 #define TLSEXT_max_fragment_length_2048 WOLFSSL_MFL_2_11 @@ -1337,6 +1359,10 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL_CONF_TYPE_FILE WOLFSSL_CONF_TYPE_FILE #define SSL_CONF_TYPE_DIR WOLFSSL_CONF_TYPE_DIR +#define OPENSSL_INIT_new wolfSSL_OPENSSL_INIT_new +#define OPENSSL_INIT_free wolfSSL_OPENSSL_INIT_free +#define OPENSSL_INIT_set_config_appname wolfSSL_OPENSSL_INIT_set_config_appname + #if defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) @@ -1511,7 +1537,8 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define OPENSSL_STRING WOLFSSL_STRING #define OPENSSL_CSTRING WOLFSSL_STRING -#define TLSEXT_TYPE_application_layer_protocol_negotiation 16 +#define TLSEXT_TYPE_application_layer_protocol_negotiation \ + TLSXT_APPLICATION_LAYER_PROTOCOL #define OPENSSL_NPN_UNSUPPORTED 0 #define OPENSSL_NPN_NEGOTIATED 1 diff --git a/src/wolfssl/openssl/tls1.h b/src/wolfssl/openssl/tls1.h index dc4a27c..843696a 100644 --- a/src/wolfssl/openssl/tls1.h +++ b/src/wolfssl/openssl/tls1.h @@ -45,8 +45,10 @@ #ifdef WOLFSSL_QUIC /* from rfc9001 */ -#define TLSEXT_TYPE_quic_transport_parameters_draft 0xffa5 -#define TLSEXT_TYPE_quic_transport_parameters 0x0039 +#define TLSEXT_TYPE_quic_transport_parameters_draft \ + TLSXT_KEY_QUIC_TP_PARAMS_DRAFT +#define TLSEXT_TYPE_quic_transport_parameters \ + TLSXT_KEY_QUIC_TP_PARAMS #endif #endif /* WOLFSSL_OPENSSL_TLS1_H_ */ diff --git a/src/wolfssl/openssl/x509.h b/src/wolfssl/openssl/x509.h index a603ce6..9afb8e0 100644 --- a/src/wolfssl/openssl/x509.h +++ b/src/wolfssl/openssl/x509.h @@ -50,7 +50,6 @@ #define X509_FLAG_NO_IDS (1UL << 12) #define XN_FLAG_FN_SN 0 -#define XN_FLAG_ONELINE 0 #define XN_FLAG_COMPAT 0 #define XN_FLAG_RFC2253 1 #define XN_FLAG_SEP_COMMA_PLUS (1 << 16) @@ -68,6 +67,7 @@ #define XN_FLAG_FN_ALIGN (1 << 25) #define XN_FLAG_MULTILINE 0xFFFF +#define XN_FLAG_ONELINE (XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_SPC_EQ | XN_FLAG_FN_SN) /* * All of these aren't actually used in wolfSSL. Some are included to diff --git a/src/wolfssl/openssl/x509v3.h b/src/wolfssl/openssl/x509v3.h index c9c9ad8..51b4e65 100644 --- a/src/wolfssl/openssl/x509v3.h +++ b/src/wolfssl/openssl/x509v3.h @@ -145,7 +145,7 @@ WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); #define BASIC_CONSTRAINTS_free wolfSSL_BASIC_CONSTRAINTS_free #define AUTHORITY_KEYID_free wolfSSL_AUTHORITY_KEYID_free -#define SSL_CTX_get_cert_store(x) wolfSSL_CTX_get_cert_store ((WOLFSSL_CTX*) (x)) +#define SSL_CTX_get_cert_store(x) wolfSSL_CTX_get_cert_store ((x)) #define ASN1_INTEGER WOLFSSL_ASN1_INTEGER #define ASN1_OCTET_STRING WOLFSSL_ASN1_STRING #define X509V3_EXT_get wolfSSL_X509V3_EXT_get diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index 804ec44..d1a88bd 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -37,6 +37,7 @@ #include #include #include +#include /* For the types */ #include @@ -152,8 +153,6 @@ typedef struct WOLFSSL_SOCKADDR WOLFSSL_SOCKADDR; typedef struct WOLFSSL_CRL WOLFSSL_CRL; typedef struct WOLFSSL_X509_STORE_CTX WOLFSSL_X509_STORE_CTX; -typedef int (*WOLFSSL_X509_STORE_CTX_verify_cb)(int, WOLFSSL_X509_STORE_CTX *); - typedef struct WOLFSSL_BY_DIR_HASH WOLFSSL_BY_DIR_HASH; typedef struct WOLFSSL_BY_DIR_entry WOLFSSL_BY_DIR_entry; typedef struct WOLFSSL_BY_DIR WOLFSSL_BY_DIR; @@ -228,6 +227,12 @@ typedef struct WOLFSSL_DIST_POINT WOLFSSL_DIST_POINT; typedef struct WOLFSSL_CONF_CTX WOLFSSL_CONF_CTX; +typedef int (*WOLFSSL_X509_STORE_CTX_verify_cb)(int, WOLFSSL_X509_STORE_CTX *); +typedef int (*WOLFSSL_X509_STORE_CTX_get_crl_cb)(WOLFSSL_X509_STORE_CTX *, + WOLFSSL_X509_CRL **, WOLFSSL_X509 *); +typedef int (*WOLFSSL_X509_STORE_CTX_check_crl_cb)(WOLFSSL_X509_STORE_CTX *, + WOLFSSL_X509_CRL *); + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || defined(HAVE_CURL) struct WOLFSSL_OBJ_NAME { @@ -603,6 +608,7 @@ struct WOLFSSL_X509_STORE { #endif #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) WOLFSSL_X509_STORE_CTX_verify_cb verify_cb; + WOLFSSL_X509_STORE_CTX_get_crl_cb get_crl_cb; #endif #ifdef HAVE_EX_DATA WOLFSSL_CRYPTO_EX_DATA ex_data; @@ -704,6 +710,7 @@ struct WOLFSSL_X509_STORE_CTX { int totalCerts; /* number of peer cert buffers */ WOLFSSL_BUFFER_INFO* certs; /* peer certs */ WOLFSSL_X509_STORE_CTX_verify_cb verify_cb; /* verify callback */ + void* heap; }; typedef char* WOLFSSL_STRING; @@ -793,9 +800,9 @@ enum SNICbReturn { * functions should use this macro to fill this gap. Users who want them * to return the same return value as OpenSSL can define * WOLFSSL_ERR_CODE_OPENSSL. - * Give item1 a variable that contains the potentially negative + * Give rc a variable that contains the potentially negative * wolfSSL-defined return value or the return value itself, and - * give item2 the openSSL-defined return value. + * give fail_rc the openSSL-defined return value. * Note that this macro replaces only negative return values with the * specified value. * Since wolfSSL 4.7.0, the following functions use this macro: @@ -804,11 +811,15 @@ enum SNICbReturn { * - wolfSSL_EVP_PKEY_cmp */ #if defined(WOLFSSL_ERROR_CODE_OPENSSL) - #define WS_RETURN_CODE(item1,item2) \ - (((item1) < 0) ? (int)(item2) : (int)(item1)) + #define WS_RETURN_CODE(rc, fail_rc) \ + (((rc) < 0) ? (int)(fail_rc) : (int)(rc)) #else - #define WS_RETURN_CODE(item1,item2) (item1) + #define WS_RETURN_CODE(rc, fail_rc) (rc) #endif +#define WS_RC(rc) \ + (((rc) == 1) ? 1 : 0) +#define WC_TO_WS_RC(ret) \ + (((ret) == 0) ? 1 : (ret)) /* Maximum master key length (SECRET_LEN) */ #define WOLFSSL_MAX_MASTER_KEY_LENGTH 48 @@ -1130,6 +1141,7 @@ WOLFSSL_API WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap); WOLFSSL_ABI WOLFSSL_API WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method); WOLFSSL_API int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx); #ifdef OPENSSL_EXTRA +WOLFSSL_API int wolfSSL_set_ecdh_auto(WOLFSSL* ssl, int onoff); WOLFSSL_API int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff); WOLFSSL_API int wolfSSL_get_signature_nid(WOLFSSL* ssl, int* nid); WOLFSSL_API int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid); @@ -1141,7 +1153,7 @@ WOLFSSL_API int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, WOLFSSL_API int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list); #endif WOLFSSL_ABI WOLFSSL_API WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx); -WOLFSSL_API WOLFSSL_CTX* wolfSSL_get_SSL_CTX(WOLFSSL* ssl); +WOLFSSL_API WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm); @@ -1177,6 +1189,21 @@ WOLFSSL_API int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz); WOLFSSL_ABI WOLFSSL_API int wolfSSL_accept(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_CTX_mutual_auth(WOLFSSL_CTX* ctx, int req); WOLFSSL_API int wolfSSL_mutual_auth(WOLFSSL* ssl, int req); + +WOLFSSL_API int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, + int count); +WOLFSSL_API int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count); +#if defined(OPENSSL_EXTRA) && defined(HAVE_SUPPORTED_CURVES) +WOLFSSL_API int wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups, + int count); +WOLFSSL_API int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count); + +#ifdef HAVE_ECC +WOLFSSL_API int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list); +WOLFSSL_API int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list); +#endif +#endif + #ifdef WOLFSSL_TLS13 WOLFSSL_API int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret, unsigned int secretSz); @@ -1194,20 +1221,6 @@ WOLFSSL_API int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_request_certificate(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_preferred_group(WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, - int count); -WOLFSSL_API int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count); - -#if defined(OPENSSL_EXTRA) && defined(HAVE_SUPPORTED_CURVES) -WOLFSSL_API int wolfSSL_CTX_set1_groups(WOLFSSL_CTX* ctx, int* groups, - int count); -WOLFSSL_API int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count); - -#ifdef HAVE_ECC -WOLFSSL_API int wolfSSL_CTX_set1_groups_list(WOLFSSL_CTX *ctx, const char *list); -WOLFSSL_API int wolfSSL_set1_groups_list(WOLFSSL *ssl, const char *list); -#endif -#endif WOLFSSL_API int wolfSSL_connect_TLSv13(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_accept_TLSv13(WOLFSSL* ssl); @@ -1236,6 +1249,7 @@ WOLFSSL_API unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSIO WOLFSSL_ABI WOLFSSL_API void wolfSSL_CTX_free(WOLFSSL_CTX* ctx); WOLFSSL_ABI WOLFSSL_API void wolfSSL_free(WOLFSSL* ssl); WOLFSSL_ABI WOLFSSL_API int wolfSSL_shutdown(WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_SendUserCanceled(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_send(WOLFSSL* ssl, const void* data, int sz, int flags); WOLFSSL_API int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags); @@ -1361,8 +1375,17 @@ WOLFSSL_ABI WOLFSSL_API long wolfSSL_CTX_set_session_cache_mode(WOLFSSL_CTX* ctx #ifdef HAVE_SECRET_CALLBACK typedef int (*SessionSecretCb)(WOLFSSL* ssl, void* secret, int* secretSz, void* ctx); -WOLFSSL_API int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb, - void*); +/* This callback is used to set the master secret during resumption */ +WOLFSSL_API int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, + void* ctx); +typedef int (*TicketParseCb)(WOLFSSL *ssl, const unsigned char *data, + int len, void *ctx); +WOLFSSL_API int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, + TicketParseCb cb, void *ctx); +typedef int (*TlsSecretCb)(WOLFSSL* ssl, void* secret, int secretSz, + void* ctx); +/* This callback is used to log the secret for TLS <= 1.2 */ +WOLFSSL_API int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx); #ifdef WOLFSSL_TLS13 typedef int (*Tls13SecretCb)(WOLFSSL* ssl, int id, const unsigned char* secret, int secretSz, void* ctx); @@ -1659,6 +1682,11 @@ WOLFSSL_API int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned cha WOLFSSL_API void wolfSSL_set_connect_state(WOLFSSL* ssl); WOLFSSL_API void wolfSSL_set_accept_state(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_session_reused(WOLFSSL* ssl); +#ifdef OPENSSL_EXTRA +/* using unsigned char instead of uint8_t here to avoid stdint include */ +WOLFSSL_API unsigned char wolfSSL_SESSION_get_max_fragment_length( + WOLFSSL_SESSION* session); +#endif WOLFSSL_API int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session); WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session); WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_new(void); @@ -1687,6 +1715,7 @@ WOLFSSL_API const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* WOLFSSL_API const char* wolfSSL_get_cipher(WOLFSSL* ssl); WOLFSSL_API void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk); WOLFSSL_API WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_SessionIsSetup(WOLFSSL_SESSION* session); WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new(void); WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new_ex(void* heap); @@ -1866,6 +1895,10 @@ WOLFSSL_API void wolfSSL_X509_STORE_CTX_set_verify_cb(WOLFSSL_X509_STORE_CTX *c WOLFSSL_X509_STORE_CTX_verify_cb verify_cb); WOLFSSL_API void wolfSSL_X509_STORE_set_verify_cb(WOLFSSL_X509_STORE *st, WOLFSSL_X509_STORE_CTX_verify_cb verify_cb); +WOLFSSL_API void wolfSSL_X509_STORE_set_get_crl(WOLFSSL_X509_STORE *st, + WOLFSSL_X509_STORE_CTX_get_crl_cb get_cb); +WOLFSSL_API void wolfSSL_X509_STORE_set_check_crl(WOLFSSL_X509_STORE *st, + WOLFSSL_X509_STORE_CTX_check_crl_cb check_crl); WOLFSSL_API int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* n, unsigned char** out); WOLFSSL_API int wolfSSL_i2d_X509_NAME_canon(WOLFSSL_X509_NAME* name, @@ -1927,8 +1960,12 @@ WOLFSSL_API int wolfSSL_X509_set_issuer_name(WOLFSSL_X509* cert, WOLFSSL_API int wolfSSL_X509_set_pubkey(WOLFSSL_X509* cert, WOLFSSL_EVP_PKEY* pkey); WOLFSSL_API int wolfSSL_X509_set_notAfter(WOLFSSL_X509* x509, const WOLFSSL_ASN1_TIME* t); +WOLFSSL_API int wolfSSL_X509_set1_notAfter(WOLFSSL_X509* x509, + const WOLFSSL_ASN1_TIME *t); WOLFSSL_API int wolfSSL_X509_set_notBefore(WOLFSSL_X509* x509, const WOLFSSL_ASN1_TIME* t); +WOLFSSL_API int wolfSSL_X509_set1_notBefore(WOLFSSL_X509* x509, + const WOLFSSL_ASN1_TIME *t); WOLFSSL_API WOLFSSL_ASN1_TIME* wolfSSL_X509_get_notBefore(const WOLFSSL_X509* x509); WOLFSSL_API WOLFSSL_ASN1_TIME* wolfSSL_X509_get_notAfter(const WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_X509_set_serialNumber(WOLFSSL_X509* x509, @@ -1985,6 +2022,8 @@ WOLFSSL_API void wolfSSL_X509_STORE_free(WOLFSSL_X509_STORE* store); WOLFSSL_API int wolfSSL_X509_STORE_up_ref(WOLFSSL_X509_STORE* store); WOLFSSL_API int wolfSSL_X509_STORE_add_cert( WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509); +WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_get0_param( + const WOLFSSL_X509_STORE *ctx); WOLFSSL_API WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain( WOLFSSL_X509_STORE_CTX* ctx); WOLFSSL_API WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get1_chain( @@ -1996,7 +2035,10 @@ WOLFSSL_API int wolfSSL_X509_STORE_set_flags(WOLFSSL_X509_STORE* store, WOLFSSL_API int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE* store); WOLFSSL_API int wolfSSL_X509_STORE_get_by_subject(WOLFSSL_X509_STORE_CTX* ctx, int idx, WOLFSSL_X509_NAME* name, WOLFSSL_X509_OBJECT* obj); +WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_CTX_get0_param( + WOLFSSL_X509_STORE_CTX *ctx); WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void); +WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new_ex(void* heap); WOLFSSL_API int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509, WOLF_STACK_OF(WOLFSSL_X509)*); WOLFSSL_API void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx); @@ -2540,7 +2582,8 @@ enum { /* ssl Constants */ WOLFSSL_FAILURE = 0, /* for some functions */ WOLFSSL_SUCCESS = 1, -/* WOLFSSL_SHUTDOWN_NOT_DONE is returned by wolfSSL_shutdown when the other end +/* WOLFSSL_SHUTDOWN_NOT_DONE is returned by wolfSSL_shutdown and + * wolfSSL_SendUserCanceled when the other end * of the connection has yet to send its close notify alert as part of the * bidirectional shutdown. To complete the shutdown, either keep calling * wolfSSL_shutdown until it returns WOLFSSL_SUCCESS or call wolfSSL_read until @@ -2924,6 +2967,7 @@ WOLFSSL_API int wolfSSL_X509_REVOKED_get_serial_number(RevokedCert* rev, byte* in, int* inOutSz); #endif #if defined(HAVE_CRL) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) +WOLFSSL_API WOLFSSL_X509_CRL* wolfSSL_X509_CRL_dup(const WOLFSSL_X509_CRL* crl); WOLFSSL_API void wolfSSL_X509_CRL_free(WOLFSSL_X509_CRL *crl); #endif @@ -2964,7 +3008,6 @@ WOLFSSL_API int wolfSSL_connect_cert(WOLFSSL* ssl); /* PKCS12 compatibility */ -typedef struct WC_PKCS12 WC_PKCS12; WOLFSSL_API WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12); WOLFSSL_API int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12); @@ -3096,6 +3139,17 @@ WOLFSSL_API int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* key, unsigned int len, const unsigned char* in, long sz, int format); WOLFSSL_API int wolfSSL_CTX_use_certificate_chain_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, long sz); +#ifdef WOLFSSL_DUAL_ALG_CERTS + WOLFSSL_API int wolfSSL_CTX_use_AltPrivateKey_buffer(WOLFSSL_CTX* ctx, + const unsigned char* in, long sz, int format); + WOLFSSL_API int wolfSSL_CTX_use_AltPrivateKey_id(WOLFSSL_CTX* ctx, + const unsigned char* id, long sz, + int devId, long keySz); + WOLFSSL_API int wolfSSL_CTX_use_AltPrivateKey_Id(WOLFSSL_CTX* ctx, + const unsigned char* id, long sz, int devId); + WOLFSSL_API int wolfSSL_CTX_use_AltPrivateKey_Label(WOLFSSL_CTX* ctx, + const char* label, int devId); +#endif /* SSL versions */ WOLFSSL_API int wolfSSL_use_certificate_buffer(WOLFSSL* ssl, const unsigned char* in, @@ -3114,6 +3168,17 @@ WOLFSSL_API int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* key, unsigned int len, WOLFSSL_API int wolfSSL_use_certificate_chain_buffer(WOLFSSL* ssl, const unsigned char* in, long sz); WOLFSSL_API int wolfSSL_UnloadCertsKeys(WOLFSSL* ssl); +#ifdef WOLFSSL_DUAL_ALG_CERTS + WOLFSSL_API int wolfSSL_use_AltPrivateKey_buffer(WOLFSSL* ssl, + const unsigned char* in, long sz, int format); + WOLFSSL_API int wolfSSL_use_AltPrivateKey_id(WOLFSSL* ssl, + const unsigned char* id, long sz, + int devId, long keySz); + WOLFSSL_API int wolfSSL_use_AltPrivateKey_Id(WOLFSSL* ssl, + const unsigned char* id, long sz, int devId); + WOLFSSL_API int wolfSSL_use_AltPrivateKey_Label(WOLFSSL* ssl, + const char* label, int devId); +#endif #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ defined(KEEP_OUR_CERT) @@ -3753,7 +3818,6 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); /* SNI types */ enum { WOLFSSL_SNI_HOST_NAME = 0, - WOLFSSL_SNI_HOST_NAME_OUTER = 0, }; WOLFSSL_ABI WOLFSSL_API int wolfSSL_UseSNI(WOLFSSL* ssl, unsigned char type, @@ -3858,6 +3922,7 @@ WOLFSSL_API int wolfSSL_ALPN_FreePeerProtocol(WOLFSSL* ssl, char **list); /* Fragment lengths */ enum { + WOLFSSL_MFL_DISABLED = 0, WOLFSSL_MFL_2_9 = 1, /* 512 bytes */ WOLFSSL_MFL_2_10 = 2, /* 1024 bytes */ WOLFSSL_MFL_2_11 = 3, /* 2048 bytes */ @@ -4435,7 +4500,7 @@ WOLFSSL_API int wolfSSL_set0_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str); WOLFSSL_API int wolfSSL_set1_verify_cert_store(WOLFSSL *ssl, WOLFSSL_X509_STORE* str); -WOLFSSL_API WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(WOLFSSL_CTX* ctx); +WOLFSSL_API WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(const WOLFSSL_CTX* ctx); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ defined(HAVE_SECRET_CALLBACK) @@ -4531,7 +4596,7 @@ WOLFSSL_API WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_get_entry(WOLFSSL_X509_NA WOLFSSL_API void wolfSSL_X509_NAME_ENTRY_free(WOLFSSL_X509_NAME_ENTRY* ne); WOLFSSL_API WOLFSSL_X509_NAME_ENTRY* wolfSSL_X509_NAME_ENTRY_new(void); WOLFSSL_API void wolfSSL_X509_NAME_free(WOLFSSL_X509_NAME* name); -WOLFSSL_API char wolfSSL_CTX_use_certificate(WOLFSSL_CTX* ctx, WOLFSSL_X509* x); +WOLFSSL_API int wolfSSL_CTX_use_certificate(WOLFSSL_CTX* ctx, WOLFSSL_X509* x); WOLFSSL_API int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509); @@ -4815,14 +4880,17 @@ typedef int (*CallbackSniRecv)(WOLFSSL *ssl, int *ret, void* exArg); WOLFSSL_API void wolfSSL_CTX_set_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb); -WOLFSSL_API int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx, - CallbackSniRecv cb); WOLFSSL_API int wolfSSL_CTX_set_servername_arg(WOLFSSL_CTX* ctx, void* arg); #endif -#if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) \ - || defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) +#if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) + +#ifdef HAVE_SNI +WOLFSSL_API int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx, + CallbackSniRecv cb); +#endif WOLFSSL_API void wolfSSL_ERR_remove_thread_state(void* pid); @@ -4858,10 +4926,11 @@ WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_X509_OBJECT_get0_X509_CRL(WOLFSSL_X509_OBJ WOLFSSL_API void wolfSSL_sk_X509_pop_free(WOLF_STACK_OF(WOLFSSL_X509)* sk, void (*f) (WOLFSSL_X509*)); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) && defined(HAVE_ECC) +#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) && (defined(HAVE_ECC) || \ + defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) WOLFSSL_API int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names); WOLFSSL_API int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names); -#endif /* (OPENSSL_EXTRA || HAVE_CURL) && HAVE_ECC */ +#endif #if defined(OPENSSL_ALL) || \ defined(HAVE_STUNNEL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ @@ -4985,6 +5054,10 @@ WOLFSSL_API int wolfSSL_SSL_do_handshake(WOLFSSL *s); #ifdef OPENSSL_EXTRA WOLFSSL_API int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings); +WOLFSSL_API OPENSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void); +WOLFSSL_API void wolfSSL_OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS* init); +WOLFSSL_API int wolfSSL_OPENSSL_INIT_set_config_appname( + OPENSSL_INIT_SETTINGS* init, char* appname); #endif #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L WOLFSSL_API int wolfSSL_SSL_in_init(const WOLFSSL* ssl); @@ -5051,7 +5124,7 @@ WOLFSSL_API int PEM_write_bio_WOLFSSL_X509(WOLFSSL_BIO *bio, WOLFSSL_API long wolfSSL_CTX_get_tlsext_ticket_keys(WOLFSSL_CTX *ctx, unsigned char *keys, int keylen); WOLFSSL_API long wolfSSL_CTX_set_tlsext_ticket_keys(WOLFSSL_CTX *ctx, - unsigned char *keys, int keylen); + const void *keys_vp, int keylen); #endif WOLFSSL_API void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, @@ -5134,6 +5207,7 @@ WOLFSSL_API int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) WOLFSSL_API int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp); WOLFSSL_API void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)); WOLFSSL_API WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); +WOLFSSL_API const char* wolfSSL_COMP_get_name(const void* comp); WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, const char *file, const char *dir); WOLFSSL_API int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *ctx, WOLFSSL_X509_CRL *x); WOLFSSL_API int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p); @@ -5153,6 +5227,7 @@ WOLFSSL_API int wolfSSL_ASN1_TIME_get_length(const WOLFSSL_ASN1_TIME *t); WOLFSSL_API unsigned char* wolfSSL_ASN1_TIME_get_data(const WOLFSSL_ASN1_TIME *t); WOLFSSL_API WOLFSSL_ASN1_TIME *wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, WOLFSSL_ASN1_TIME **out); +WOLFSSL_API WOLFSSL_ASN1_TIME* wolfSSL_ASN1_UTCTIME_set(WOLFSSL_ASN1_TIME *s, time_t t); WOLFSSL_API int wolfSSL_i2c_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER *a, unsigned char **pp); WOLFSSL_API int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, char *buf, int size); @@ -5303,6 +5378,247 @@ WOLFSSL_API int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buffer, #define DTLS1_2_VERSION 0xFEFD #define DTLS1_3_VERSION 0xFEFC +/* These minimums where determined whilst referencing their RFC specs. The + * values represent the minimum sizes of the data types in the required struct + * for the `extension_data` field. A length of 0 was assumed when necassary. + * + * Documents Used for the respective extension: + * - https://datatracker.ietf.org/doc/html/rfc6066 + * - Server Name Indication (SNI) + * - Maximum Fragment Length Negotiation (MFL) + * - Trusted CA Indication (TCA) + * - Certificate Status Request (CSR) + * - Truncate HMAC (THM) + * - https://datatracker.ietf.org/doc/html/rfc8446 + * - Early Data Indication (EDI) + * - Pre-Shared Key (PSK) + * - Pre-Shared Key Exchange Modes (PKM) + * - Key Share (KS) + * - Post-Handshake Authentication (PHA) + * - Signature Algorithms (SA) + * - Signature Algorithms Certificate (SAC) + * - Support Groups (EC) + * - Cookie (CKE) + * - Supported Versions (SV) + * - Certificate Authorities (CAN) + * - https://datatracker.ietf.org/doc/html/rfc6961 + * - Certificate Status Request v2 (CSR2) + * - https://datatracker.ietf.org/doc/rfc9146/ + * - Connection Identifier (CID) + * - https://datatracker.ietf.org/doc/rfc7301/ + * - Application-Layer Protocol Negotiation (ALPN) + * - https://datatracker.ietf.org/doc/html/rfc3711 + * - Secure Real-time Transport Protocol (SRTP) + * - https://datatracker.ietf.org/doc/html/rfc7366 + * - Encrypt Then Mac (ETM) + * - https://datatracker.ietf.org/doc/html/rfc7250 + * - Client Certificate Type (CCT) + * - Server Certificate Type (SCT) + * - https://datatracker.ietf.org/doc/draft-ietf-tls-esni/ + * - Encrypted Client Hello (ECH) + * - https://datatracker.ietf.org/doc/html/rfc5746 + * - Secure Renegotiation (SCR) + * - https://datatracker.ietf.org/doc/rfc4492/ + * - Point Frame (PF) + * - https://datatracker.ietf.org/doc/rfc9000/ + * - QUIC (QTP) + * - https://datatracker.ietf.org/doc/html/rfc5077 + * - Session Ticket (STK) + * Example: + * For `WOLFSSL_CSR_MIN_SIZE_CLIENT = 5`, 5 was determined by looking at the + * struct below defined in its respective RFC. + * The below struct for `CertificateStatusRequest` is made up of the types: + * `CertificateStatusType` is an enum with a max value of 255, thus its + * length is 1 byte. + * `OCSPStatusRequest` is a struct of the following: + * - `responder_id_list`: which is 2 bytes + * - `request_extensions`: which is 2 bytes + * This then gives the minimum size/length of 5 bytes for this extension + * for the client + * struct { + * CertificateStatusType status_type; + * select (status_type) { + * case ocsp: OCSPStatusRequest; + * } request; + * } CertificateStatusRequest; + * enum { ocsp(1), (255) } CertificateStatusType; + * struct { + * ResponderID responder_id_list<0..2^16-1>; + * Extensions request_extensions; + * } OCSPStatusRequest; + * opaque ResponderID<1..2^16-1>; + * opaque Extensions<0..2^16-1>; + */ + +#ifndef WOLFSSL_SNI_MIN_SIZE_CLIENT + #define WOLFSSL_SNI_MIN_SIZE_CLIENT 4 +#endif +#ifndef WOLFSSL_SNI_MIN_SIZE_SERVER + #define WOLFSSL_SNI_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_EDI_MIN_SIZE_CLIENT + #define WOLFSSL_EDI_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_EDI_MIN_SIZE_SERVER + #define WOLFSSL_EDI_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_TCA_MIN_SIZE_CLIENT + #define WOLFSSL_TCA_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_TCA_MIN_SIZE_SERVER + #define WOLFSSL_TCA_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_CSR_MIN_SIZE_CLIENT + #define WOLFSSL_CSR_MIN_SIZE_CLIENT 5 +#endif +#ifndef WOLFSSL_CSR_MIN_SIZE_SERVER + #define WOLFSSL_CSR_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_PKM_MIN_SIZE_CLIENT + #define WOLFSSL_PKM_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_PKM_MIN_SIZE_SERVER + #define WOLFSSL_PKM_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_CSR2_MIN_SIZE_CLIENT + #define WOLFSSL_CSR2_MIN_SIZE_CLIENT 7 +#endif +#ifndef WOLFSSL_CSR2_MIN_SIZE_SERVER + #define WOLFSSL_CSR2_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_CID_MIN_SIZE_CLIENT + #define WOLFSSL_CID_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_CID_MIN_SIZE_SERVER + #define WOLFSSL_CID_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_ALPN_MIN_SIZE_CLIENT + #define WOLFSSL_ALPN_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_ALPN_MIN_SIZE_SERVER + #define WOLFSSL_ALPN_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_SRTP_MIN_SIZE_CLIENT + #define WOLFSSL_SRTP_MIN_SIZE_CLIENT 3 +#endif +#ifndef WOLFSSL_SRTP_MIN_SIZE_SERVER + #define WOLFSSL_SRTP_MIN_SIZE_SERVER 3 +#endif +#ifndef WOLFSSL_KS_MIN_SIZE_CLIENT + #define WOLFSSL_KS_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_KS_MIN_SIZE_SERVER + #define WOLFSSL_KS_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_ETM_MIN_SIZE_CLIENT + #define WOLFSSL_ETM_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_ETM_MIN_SIZE_SERVER + #define WOLFSSL_ETM_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_PSK_MIN_SIZE_CLIENT + #define WOLFSSL_PSK_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_PSK_MIN_SIZE_SERVER + #define WOLFSSL_PSK_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_CCT_MIN_SIZE_CLIENT + #define WOLFSSL_CCT_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_CCT_MIN_SIZE_SERVER + #define WOLFSSL_CCT_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_SCT_MIN_SIZE_CLIENT + #define WOLFSSL_SCT_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_SCT_MIN_SIZE_SERVER + #define WOLFSSL_SCT_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_PHA_MIN_SIZE_CLIENT + #define WOLFSSL_PHA_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_PHA_MIN_SIZE_SERVER + #define WOLFSSL_PHA_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_THM_MIN_SIZE_CLIENT + #define WOLFSSL_THM_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_THM_MIN_SIZE_SERVER + #define WOLFSSL_THM_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_SA_MIN_SIZE_CLIENT + #define WOLFSSL_SA_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_SA_MIN_SIZE_SERVER + #define WOLFSSL_SA_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_SAC_MIN_SIZE_CLIENT + #define WOLFSSL_SAC_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_SAC_MIN_SIZE_SERVER + #define WOLFSSL_SAC_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_EC_MIN_SIZE_CLIENT + #define WOLFSSL_EC_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_EC_MIN_SIZE_SERVER + #define WOLFSSL_EC_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_ECH_MIN_SIZE_CLIENT + #define WOLFSSL_ECH_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_ECH_MIN_SIZE_SERVER + #define WOLFSSL_ECH_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_MFL_MIN_SIZE_CLIENT + #define WOLFSSL_MFL_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_MFL_MIN_SIZE_SERVER + #define WOLFSSL_MFL_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_CKE_MIN_SIZE_CLIENT + #define WOLFSSL_CKE_MIN_SIZE_CLIENT 3 +#endif +#ifndef WOLFSSL_CKE_MIN_SIZE_SERVER + #define WOLFSSL_CKE_MIN_SIZE_SERVER 3 +#endif +#ifndef WOLFSSL_SV_MIN_SIZE_CLIENT + #define WOLFSSL_SV_MIN_SIZE_CLIENT 2 +#endif +#ifndef WOLFSSL_SV_MIN_SIZE_SERVER + #define WOLFSSL_SV_MIN_SIZE_SERVER 2 +#endif +#ifndef WOLFSSL_SCR_MIN_SIZE_CLIENT + #define WOLFSSL_SCR_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_SCR_MIN_SIZE_SERVER + #define WOLFSSL_SCR_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_PF_MIN_SIZE_CLIENT + #define WOLFSSL_PF_MIN_SIZE_CLIENT 1 +#endif +#ifndef WOLFSSL_PF_MIN_SIZE_SERVER + #define WOLFSSL_PF_MIN_SIZE_SERVER 1 +#endif +#ifndef WOLFSSL_CAN_MIN_SIZE_CLIENT + #define WOLFSSL_CAN_MIN_SIZE_CLIENT 3 +#endif +#ifndef WOLFSSL_CAN_MIN_SIZE_SERVER + #define WOLFSSL_CAN_MIN_SIZE_SERVER 3 +#endif +#ifndef WOLFSSL_QTP_MIN_SIZE_CLIENT + #define WOLFSSL_QTP_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_QTP_MIN_SIZE_SERVER + #define WOLFSSL_QTP_MIN_SIZE_SERVER 0 +#endif +#ifndef WOLFSSL_STK_MIN_SIZE_CLIENT + #define WOLFSSL_STK_MIN_SIZE_CLIENT 0 +#endif +#ifndef WOLFSSL_STK_MIN_SIZE_SERVER + #define WOLFSSL_STK_MIN_SIZE_SERVER 0 +#endif + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index 47abb74..4dd6320 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -143,9 +143,26 @@ #include #define SOCKET_T int #elif defined(WOLFSSL_ZEPHYR) + #include #include #include - #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #ifdef CONFIG_POSIX_API + #include + #include + #include + #include + #endif + #else + #include + #ifdef CONFIG_POSIX_API + #include + #include + #include + #include + #endif + #endif #define SOCKET_T int #define SOL_SOCKET 1 #define WOLFSSL_USE_GETADDRINFO @@ -985,11 +1002,11 @@ static WC_INLINE int PasswordCallBack(char* passwd, int sz, int rw, void* userda (void)rw; (void)userdata; if (userdata != NULL) { - strncpy(passwd, (char*)userdata, sz); + strncpy(passwd, (char*)userdata, (size_t) sz); return (int)XSTRLEN((char*)userdata); } else { - strncpy(passwd, "yassl123", sz); + strncpy(passwd, "yassl123", (size_t) sz); return 8; } } @@ -1312,7 +1329,7 @@ static WC_INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer, if (entry) { XMEMCPY(&addr->sin_addr.s_addr, entry->h_addr_list[0], - entry->h_length); + (size_t) entry->h_length); useLookup = 1; } #else @@ -1850,7 +1867,7 @@ static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - key[i] = b; + key[i] = (unsigned char) b; } ret = 32; /* length of key in octets or 0 for error */ @@ -1894,7 +1911,7 @@ static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identit for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - key[i] = b; + key[i] = (unsigned char) b; } ret = 32; /* length of key in octets or 0 for error */ @@ -1927,7 +1944,7 @@ static WC_INLINE unsigned int my_psk_client_tls13_cb(WOLFSSL* ssl, for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - key[i] = b; + key[i] = (unsigned char) b; } *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; @@ -1950,7 +1967,7 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, unsigned int ret; int i; int b = 0x01; - int kIdLen = (int)XSTRLEN(kIdentityStr); + size_t kIdLen = XSTRLEN(kIdentityStr); const char* userCipher = (const char*)wolfSSL_get_psk_callback_ctx(ssl); (void)ssl; @@ -1966,7 +1983,7 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - key[i] = b; + key[i] = (unsigned char) b; } *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; @@ -2029,7 +2046,7 @@ static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - local_psk[i] = b; + local_psk[i] = (unsigned char) b; } *id = local_psk; @@ -2082,7 +2099,7 @@ static WC_INLINE unsigned int my_psk_client_cs_cb(WOLFSSL* ssl, for (i = 0; i < 32; i++, b += 0x22) { if (b >= 0x100) b = 0x01; - key[i] = b; + key[i] = (unsigned char) b; } return 32; /* length of key in octets or 0 for error */ @@ -2416,7 +2433,7 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) */ fprintf(stderr, "In verification callback, error = %d, %s\n", store->error, - wolfSSL_ERR_error_string(store->error, buffer)); + wolfSSL_ERR_error_string((unsigned long) store->error, buffer)); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) peer = store->current_cert; if (peer) { @@ -2707,7 +2724,7 @@ static WC_INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut, if (ret != 0) return ret; ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl), - wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl)); + wolfSSL_GetMacSecret(ssl, macVerify), (word32) wolfSSL_GetHmacSize(ssl)); if (ret != 0) return ret; ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner)); @@ -2741,7 +2758,7 @@ static WC_INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut, fprintf(stderr, "AesInit failed in myMacEncryptCb\n"); return ret; } - ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION); + ret = wc_AesSetKey(&encCtx->aes, key, (word32) keyLen, iv, AES_ENCRYPTION); if (ret != 0) { fprintf(stderr, "AesSetKey failed in myMacEncryptCb\n"); return ret; @@ -2760,7 +2777,7 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, { AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx; int ret = 0; - int macInSz = 0; + unsigned int macInSz = 0; int ivExtra = 0; int digestSz = wolfSSL_GetHmacSize(ssl); unsigned int pad = 0; @@ -2802,7 +2819,7 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, fprintf(stderr, "AesInit failed in myDecryptVerifyCb\n"); return ret; } - ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION); + ret = wc_AesSetKey(&decCtx->aes, key, (word32) keyLen, iv, AES_DECRYPTION); if (ret != 0) { fprintf(stderr, "AesSetKey failed in myDecryptVerifyCb\n"); return ret; @@ -2816,7 +2833,7 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, return ret; if (wolfSSL_GetCipherType(ssl) == WOLFSSL_AEAD_TYPE) { - *padSz = wolfSSL_GetAeadMacSize(ssl); + *padSz = (unsigned int)wolfSSL_GetAeadMacSize(ssl); return 0; /* hmac, not needed if aead mode */ } @@ -2827,8 +2844,8 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, ivExtra = wolfSSL_GetCipherBlockSize(ssl); } - *padSz = wolfSSL_GetHmacSize(ssl) + pad + padByte; - macInSz = decSz - ivExtra - digestSz - pad - padByte; + *padSz = (unsigned int)wolfSSL_GetHmacSize(ssl) + pad + padByte; + macInSz = decSz - (unsigned int)ivExtra - (unsigned int)digestSz - pad - padByte; wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify); @@ -2836,7 +2853,7 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, if (ret != 0) return ret; ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl), - wolfSSL_GetMacSecret(ssl, macVerify), digestSz); + wolfSSL_GetMacSecret(ssl, macVerify), (unsigned int) digestSz); if (ret != 0) return ret; ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner)); @@ -2850,7 +2867,7 @@ static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl, return ret; if (XMEMCMP(verify, decOut + decSz - digestSz - pad - padByte, - digestSz) != 0) { + (size_t) digestSz) != 0) { printf("myDecryptVerify verify failed\n"); return -1; } @@ -2901,7 +2918,7 @@ static WC_INLINE int myEncryptMacCb(WOLFSSL* ssl, unsigned char* macOut, fprintf(stderr, "AesInit failed in myMacEncryptCb\n"); return ret; } - ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION); + ret = wc_AesSetKey(&encCtx->aes, key, (word32) keyLen, iv, AES_ENCRYPTION); if (ret != 0) { fprintf(stderr, "AesSetKey failed in myMacEncryptCb\n"); return ret; @@ -2921,7 +2938,7 @@ static WC_INLINE int myEncryptMacCb(WOLFSSL* ssl, unsigned char* macOut, if (ret != 0) return ret; ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl), - wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl)); + wolfSSL_GetMacSecret(ssl, macVerify), (word32) wolfSSL_GetHmacSize(ssl)); if (ret != 0) return ret; ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner)); @@ -2965,7 +2982,7 @@ static WC_INLINE int myVerifyDecryptCb(WOLFSSL* ssl, if (ret != 0) return ret; ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl), - wolfSSL_GetMacSecret(ssl, macVerify), digestSz); + wolfSSL_GetMacSecret(ssl, macVerify), (word32) digestSz); if (ret != 0) return ret; ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner)); @@ -2978,7 +2995,7 @@ static WC_INLINE int myVerifyDecryptCb(WOLFSSL* ssl, if (ret != 0) return ret; - if (XMEMCMP(verify, decOut + decSz, digestSz) != 0) { + if (XMEMCMP(verify, decOut + decSz, (size_t) digestSz) != 0) { printf("myDecryptVerify verify failed\n"); return -1; } @@ -3004,7 +3021,7 @@ static WC_INLINE int myVerifyDecryptCb(WOLFSSL* ssl, fprintf(stderr, "AesInit failed in myDecryptVerifyCb\n"); return ret; } - ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION); + ret = wc_AesSetKey(&decCtx->aes, key, (word32) keyLen, iv, AES_DECRYPTION); if (ret != 0) { fprintf(stderr, "AesSetKey failed in myDecryptVerifyCb\n"); return ret; @@ -3085,7 +3102,7 @@ static WC_INLINE void FreeAtomicUser(WOLFSSL* ssl) #endif /* ATOMIC_USER */ -#ifdef WOLFSSL_STATIC_MEMORY +#if defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY_LEAN) static WC_INLINE int wolfSSL_PrintStats(WOLFSSL_MEM_STATS* stats) { word16 i; @@ -3167,7 +3184,7 @@ static WC_INLINE int myEccKeyGen(WOLFSSL* ssl, ecc_key* key, word32 keySz, WC_RNG *rng = wolfSSL_GetRNG(ssl); /* create new key */ - ret = wc_ecc_make_key_ex(rng, keySz, new_key, ecc_curve); + ret = wc_ecc_make_key_ex(rng, (int) keySz, new_key, ecc_curve); #ifdef TEST_PK_PRIVKEY if (ret == 0 && new_key != key) { @@ -3363,7 +3380,7 @@ static WC_INLINE int myHkdfExtract(byte* prk, const byte* salt, word32 saltLen, byte* ikm, word32 ikmLen, int digest, void* ctx) { int ret; - int len = 0; + word32 len = 0; switch (digest) { #ifndef NO_SHA256 @@ -3494,7 +3511,7 @@ static WC_INLINE int myX25519KeyGen(WOLFSSL* ssl, curve25519_key* key, if (ret != 0) return ret; - ret = wc_curve25519_make_key(&rng, keySz, key); + ret = wc_curve25519_make_key(&rng, (int) keySz, key); wc_FreeRng(&rng); @@ -3665,7 +3682,7 @@ static WC_INLINE int myX448KeyGen(WOLFSSL* ssl, curve448_key* key, if (ret != 0) return ret; - ret = wc_curve448_make_key(&rng, keySz, key); + ret = wc_curve448_make_key(&rng, (int) keySz, key); wc_FreeRng(&rng); @@ -3798,7 +3815,7 @@ static WC_INLINE int myRsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, if (ret == 0) ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, &myKey, &rng); if (ret > 0) { /* save and convert to 0 success */ - *outSz = ret; + *outSz = (word32) ret; ret = 0; } wc_FreeRsaKey(&myKey); @@ -3932,7 +3949,7 @@ static WC_INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz, &rng); } if (ret > 0) { /* save and convert to 0 success */ - *outSz = ret; + *outSz = (word32) ret; ret = 0; } wc_FreeRsaKey(&myKey); @@ -4083,7 +4100,7 @@ static WC_INLINE int myRsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, if (ret == 0) { ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, &myKey, &rng); if (ret > 0) { - *outSz = ret; + *outSz = (word32) ret; ret = 0; /* reset to success */ } } diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index d6193c4..2da6e5e 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.7.0" -#define LIBWOLFSSL_VERSION_HEX 0x05007000 +#define LIBWOLFSSL_VERSION_STRING "5.7.2" +#define LIBWOLFSSL_VERSION_HEX 0x05007002 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/aes.h b/src/wolfssl/wolfcrypt/aes.h index 1c369ce..46687da 100644 --- a/src/wolfssl/wolfcrypt/aes.h +++ b/src/wolfssl/wolfcrypt/aes.h @@ -55,6 +55,11 @@ typedef struct Gcm { #endif /* GCM_TABLE */ } Gcm; +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_aes_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_AES_sanity(void); +#endif + WOLFSSL_LOCAL void GenerateM0(Gcm* gcm); #ifdef WOLFSSL_ARMASM WOLFSSL_LOCAL void GMULT(byte* X, byte* Y); @@ -256,7 +261,7 @@ struct Aes { ALIGN16 bs_word bs_key[15 * AES_BLOCK_SIZE * BS_WORD_SIZE]; #endif word32 rounds; -#ifdef WC_AES_C_DYNAMIC_FALLBACK +#ifdef WC_C_DYNAMIC_FALLBACK word32 key_C_fallback[60]; #endif int keylen; @@ -400,15 +405,37 @@ struct Aes { #endif #ifdef WOLFSSL_AES_XTS -typedef struct XtsAes { - Aes aes; -#ifdef WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS - Aes aes_decrypt; -#endif - Aes tweak; -} XtsAes; + #if FIPS_VERSION3_GE(6,0,0) + /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is + * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + */ + #define FIPS_AES_XTS_MAX_BYTES_PER_TWEAK 16777216 + #endif + struct XtsAes { + Aes aes; + #ifdef WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS + Aes aes_decrypt; + #endif + Aes tweak; + }; + + #ifdef WOLFSSL_AESXTS_STREAM + struct XtsAesStreamData { + byte tweak_block[AES_BLOCK_SIZE]; + word32 bytes_crypted_with_this_tweak; + }; + #endif + + #ifndef WC_AESXTS_TYPE_DEFINED + typedef struct XtsAes XtsAes; + typedef struct XtsAesStreamData XtsAesStreamData; + #define WC_AESXTS_TYPE_DEFINED + #endif + #endif + #if (!defined(WC_AESFREE_IS_MANDATORY)) && \ (defined(WC_DEBUG_CIPHER_LIFECYCLE) || \ (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)) || \ @@ -430,9 +457,15 @@ typedef struct XtsAes { #endif #ifdef HAVE_AESGCM -typedef struct Gmac { +struct Gmac { Aes aes; -} Gmac; +}; + +#ifndef WC_AESGCM_TYPE_DEFINED + typedef struct Gmac Gmac; + #define WC_AESGCM_TYPE_DEFINED +#endif + #endif /* HAVE_AESGCM */ #endif /* HAVE_FIPS */ @@ -658,6 +691,28 @@ WOLFSSL_API int wc_AesXtsDecryptConsecutiveSectors(XtsAes* aes, byte* out, const byte* in, word32 sz, word64 sector, word32 sectorSz); +#ifdef WOLFSSL_AESXTS_STREAM + +WOLFSSL_API int wc_AesXtsEncryptInit(XtsAes* aes, const byte* i, word32 iSz, + struct XtsAesStreamData *stream); + +WOLFSSL_API int wc_AesXtsDecryptInit(XtsAes* aes, const byte* i, word32 iSz, + struct XtsAesStreamData *stream); + +WOLFSSL_API int wc_AesXtsEncryptUpdate(XtsAes* aes, byte* out, + const byte* in, word32 sz, struct XtsAesStreamData *stream); + +WOLFSSL_API int wc_AesXtsDecryptUpdate(XtsAes* aes, byte* out, + const byte* in, word32 sz, struct XtsAesStreamData *stream); + +WOLFSSL_API int wc_AesXtsEncryptFinal(XtsAes* aes, byte* out, + const byte* in, word32 sz, struct XtsAesStreamData *stream); + +WOLFSSL_API int wc_AesXtsDecryptFinal(XtsAes* aes, byte* out, + const byte* in, word32 sz, struct XtsAesStreamData *stream); + +#endif /* WOLFSSL_AESXTS_STREAM */ + WOLFSSL_API int wc_AesXtsFree(XtsAes* aes); #endif diff --git a/src/wolfssl/wolfcrypt/asn.h b/src/wolfssl/wolfcrypt/asn.h index 01eb03c..503c985 100644 --- a/src/wolfssl/wolfcrypt/asn.h +++ b/src/wolfssl/wolfcrypt/asn.h @@ -780,6 +780,20 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WOLFSSL_TLS_FEATURE_SUM 92 #endif +/* Maximum number of allowed subject alternative names in a certificate. + * Any certificate containing more than this number of subject + * alternative names will cause an error when attempting to parse. */ +#ifndef WOLFSSL_MAX_ALT_NAMES +#define WOLFSSL_MAX_ALT_NAMES 128 +#endif + +/* Maximum number of allowed name constraints in a certificate. + * Any certificate containing more than this number of name constraints + * will cause an error when attempting to parse. */ +#ifndef WOLFSSL_MAX_NAME_CONSTRAINTS +#define WOLFSSL_MAX_NAME_CONSTRAINTS 128 +#endif + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* NIDs */ #define NID_undef 0 @@ -934,7 +948,7 @@ enum Misc_ASN { ASN_GEN_TIME_SZ = 15, /* 7 numbers * 2 + Zulu tag */ #ifdef HAVE_SPHINCS MAX_ENCODED_SIG_SZ = 51200, -#elif defined(HAVE_PQC) +#elif defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) MAX_ENCODED_SIG_SZ = 5120, #elif !defined(NO_RSA) #ifdef WOLFSSL_HAPROXY @@ -969,6 +983,9 @@ enum Misc_ASN { MAX_DSA_PRIVKEY_SZ = (DSA_INTS * MAX_DSA_INT_SZ) + MAX_SEQ_SZ + MAX_VERSION_SZ, /* Maximum size of a DSA Private key taken from DsaKeyIntsToDer. */ +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + MAX_PQC_PUBLIC_KEY_SZ = 2592, /* Maximum size of a Dilithium public key. */ +#endif MAX_RSA_E_SZ = 16, /* Max RSA public e size */ MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */ MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */ @@ -1015,7 +1032,11 @@ enum Misc_ASN { OCSP_NONCE_EXT_SZ = 35, /* OCSP Nonce Extension size */ MAX_OCSP_EXT_SZ = 58, /* Max OCSP Extension length */ MAX_OCSP_NONCE_SZ = 16, /* OCSP Nonce size */ +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + MAX_PUBLIC_KEY_SZ = MAX_PQC_PUBLIC_KEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, +#else MAX_PUBLIC_KEY_SZ = MAX_DSA_PUBKEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, +#endif #ifdef WOLFSSL_ENCRYPTED_KEYS HEADER_ENCRYPTED_KEY_SIZE = 88,/* Extra header size for encrypted key */ #else @@ -1143,9 +1164,9 @@ enum Key_Sum { DHk = 647, /* dhKeyAgreement OID: 1.2.840.113549.1.3.1 */ FALCON_LEVEL1k = 273, /* 1.3.9999.3.6 */ FALCON_LEVEL5k = 276, /* 1.3.9999.3.9 */ - DILITHIUM_LEVEL2k = 213, /* 1.3.6.1.4.1.2.267.7.4.4 */ - DILITHIUM_LEVEL3k = 216, /* 1.3.6.1.4.1.2.267.7.6.5 */ - DILITHIUM_LEVEL5k = 220, /* 1.3.6.1.4.1.2.267.7.8.7 */ + DILITHIUM_LEVEL2k = 218, /* 1.3.6.1.4.1.2.267.12.4.4 */ + DILITHIUM_LEVEL3k = 221, /* 1.3.6.1.4.1.2.267.12.6.5 */ + DILITHIUM_LEVEL5k = 225, /* 1.3.6.1.4.1.2.267.12.8.7 */ SPHINCS_FAST_LEVEL1k = 281, /* 1 3 9999 6 7 4 */ SPHINCS_FAST_LEVEL3k = 283, /* 1 3 9999 6 8 3 + 2 (See GetOID() in asn.c) */ SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ @@ -1476,9 +1497,13 @@ struct SignatureCtx { #ifdef HAVE_ED448 struct ed448_key* ed448; #endif - #ifdef HAVE_PQC + #if defined(HAVE_FALCON) struct falcon_key* falcon; + #endif + #if defined(HAVE_DILITHIUM) struct dilithium_key* dilithium; + #endif + #if defined(HAVE_SPHINCS) struct sphincs_key* sphincs; #endif void* ptr; @@ -2017,10 +2042,9 @@ struct Signer { word32 cm_idx; #endif #ifdef WOLFSSL_DUAL_ALG_CERTS - /* The Subject Alternative Public Key Info (SAPKI) will NOT be cached. - * Caching of it is NOT SUPPORTED yet. */ - byte *sapkiDer; - int sapkiLen; + word32 sapkiOID; /* key type */ + byte* sapkiDer; + int sapkiLen; #endif /* WOLFSSL_DUAL_ALG_CERTS */ byte type; @@ -2107,6 +2131,7 @@ WOLFSSL_LOCAL int StreamOctetString(const byte* inBuf, word32 inBufSz, WOLFSSL_ASN_API void FreeAltNames(DNS_entry* altNames, void* heap); WOLFSSL_ASN_API DNS_entry* AltNameNew(void* heap); +WOLFSSL_ASN_API DNS_entry* AltNameDup(DNS_entry* from, void* heap); #ifndef IGNORE_NAME_CONSTRAINTS WOLFSSL_ASN_API void FreeNameSubtrees(Base_entry* names, void* heap); #endif /* IGNORE_NAME_CONSTRAINTS */ @@ -2128,14 +2153,20 @@ WOLFSSL_LOCAL int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz); WOLFSSL_LOCAL int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap); -WOLFSSL_API int CheckCertSignature(const byte*,word32,void*,void* cm); WOLFSSL_LOCAL int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID); -#ifdef OPENSSL_EXTRA -WOLFSSL_API int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, - void* heap, const byte* pubKey, - word32 pubKeySz, int pubKeyOID); -#endif +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SMALL_CERT_VERIFY) + WOLFSSL_API int wc_CheckCertSignature(const byte* cert, word32 certSz, + void* heap, void* cm); + /* Depricated public API name kept for backwards build compatibility */ + #define CheckCertSignature(cert, certSz, heap, cm) \ + wc_CheckCertSignature(cert, certSz, heap, cm) + + WOLFSSL_API int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, + void* heap, const byte* pubKey, + word32 pubKeySz, int pubKeyOID); +#endif /* OPENSSL_EXTRA || WOLFSSL_SMALL_CERT_VERIFY */ + #ifdef WOLFSSL_DUAL_ALG_CERTS WOLFSSL_LOCAL int wc_ConfirmAltSignature( const byte* buf, word32 bufSz, @@ -2156,7 +2187,7 @@ WOLFSSL_LOCAL int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, WOLFSSL_ASN_API int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, int sigAlgoType); WOLFSSL_LOCAL int ParseCertRelative(DecodedCert* cert, int type, int verify, - void* cm); + void* cm, Signer *extraCa); WOLFSSL_LOCAL int DecodeToKey(DecodedCert* cert, int verify); #ifdef WOLFSSL_ASN_TEMPLATE WOLFSSL_LOCAL int DecodeCert(DecodedCert* cert, int verify, int* criticalExt); @@ -2165,6 +2196,8 @@ WOLFSSL_LOCAL int TryDecodeRPKToKey(DecodedCert* cert); WOLFSSL_LOCAL int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate); WOLFSSL_LOCAL const byte* OidFromId(word32 id, word32 type, word32* oidSz); +WOLFSSL_LOCAL Signer* findSignerByName(Signer *list, byte *hash); +WOLFSSL_LOCAL int FillSigner(Signer* signer, DecodedCert* cert, int type, DerBuffer *der); WOLFSSL_LOCAL Signer* MakeSigner(void* heap); WOLFSSL_LOCAL void FreeSigner(Signer* signer, void* heap); WOLFSSL_LOCAL void FreeSignerTable(Signer** table, int rows, void* heap); @@ -2308,7 +2341,8 @@ WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx); WOLFSSL_LOCAL int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx, word32 sigOID); -WOLFSSL_LOCAL int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der); +WOLFSSL_LOCAL int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, + DecodedCert* der, int checkAlt); WOLFSSL_LOCAL int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, const byte* pubKey, word32 pubKeySz, enum Key_Sum ks); WOLFSSL_LOCAL int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g); @@ -2347,8 +2381,11 @@ WOLFSSL_LOCAL void FreeSignatureCtx(SignatureCtx* sigCtx); WOLFSSL_LOCAL int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, byte* output, word32 outLen, int keyType, int withHeader); -WOLFSSL_LOCAL int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, - byte* pubKey, word32* pubKeyLen, int keyType); +WOLFSSL_LOCAL int DecodeAsymKeyPublic_Assign(const byte* input, + word32* inOutIdx, word32 inSz, const byte** pubKey, word32* pubKeyLen, + int keyType); +WOLFSSL_LOCAL int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, + word32 inSz, byte* pubKey, word32* pubKeyLen, int keyType); #ifndef NO_CERTS @@ -2358,7 +2395,10 @@ WOLFSSL_LOCAL int wc_EncryptedInfoParse(EncryptedInfo* info, WOLFSSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type, DerBuffer** pDer, void* heap, EncryptedInfo* info, int* eccKey); -WOLFSSL_LOCAL int AllocDer(DerBuffer** der, word32 length, int type, void* heap); +WOLFSSL_LOCAL int AllocDer(DerBuffer** der, word32 length, int type, + void* heap); +WOLFSSL_LOCAL int AllocCopyDer(DerBuffer** der, const unsigned char* buff, + word32 length, int type, void* heap); WOLFSSL_LOCAL void FreeDer(DerBuffer** der); #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \ @@ -2527,7 +2567,7 @@ struct OcspResponse { byte* source; /* pointer to source buffer, not owned */ word32 maxIdx; /* max offset based on init size */ - + Signer* pendingCAs; #ifdef OPENSSL_EXTRA int verifyError; #endif @@ -2652,9 +2692,10 @@ WOLFSSL_LOCAL void FreeDecodedCRL(DecodedCRL* dcrl); || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \ || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \ || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \ - || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \ - || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \ - || (defined(HAVE_PQC) && defined(HAVE_SPHINCS))) + || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)) +WOLFSSL_LOCAL int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, + word32 inSz, const byte** privKey, word32* privKeyLen, const byte** pubKey, + word32* pubKeyLen, int keyType); WOLFSSL_LOCAL int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, byte* privKey, word32* privKeyLen, byte* pubKey, word32* pubKeyLen, int keyType); diff --git a/src/wolfssl/wolfcrypt/asn_public.h b/src/wolfssl/wolfcrypt/asn_public.h index 0f58152..f233004 100644 --- a/src/wolfssl/wolfcrypt/asn_public.h +++ b/src/wolfssl/wolfcrypt/asn_public.h @@ -218,9 +218,9 @@ enum Ctc_SigType { CTC_FALCON_LEVEL1 = 273, CTC_FALCON_LEVEL5 = 276, - CTC_DILITHIUM_LEVEL2 = 213, - CTC_DILITHIUM_LEVEL3 = 216, - CTC_DILITHIUM_LEVEL5 = 220, + CTC_DILITHIUM_LEVEL2 = 218, + CTC_DILITHIUM_LEVEL3 = 221, + CTC_DILITHIUM_LEVEL5 = 225, CTC_SPHINCS_FAST_LEVEL1 = 281, CTC_SPHINCS_FAST_LEVEL3 = 283, @@ -516,7 +516,7 @@ typedef struct Cert { #endif #ifdef WOLFSSL_DUAL_ALG_CERTS /* These will not point to managed buffers. They will point to buffers that - * are managed by others. No cleanup neccessary. */ + * are managed by others. No cleanup necessary. */ /* Subject Alternative Public Key Info */ byte *sapkiDer; int sapkiLen; @@ -799,8 +799,7 @@ WOLFSSL_API int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz); (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)) || \ (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)) || \ (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)) || \ - (defined(HAVE_PQC) && (defined(HAVE_FALCON) || \ - defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)))) + (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS))) #define WC_ENABLE_ASYM_KEY_EXPORT #endif @@ -809,8 +808,7 @@ WOLFSSL_API int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz); (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) || \ (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) || \ (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) || \ - (defined(HAVE_PQC) && (defined(HAVE_FALCON) || \ - defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)))) + (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS))) #define WC_ENABLE_ASYM_KEY_IMPORT #endif diff --git a/src/wolfssl/wolfcrypt/chacha.h b/src/wolfssl/wolfcrypt/chacha.h index 848edf6..6c9577b 100644 --- a/src/wolfssl/wolfcrypt/chacha.h +++ b/src/wolfssl/wolfcrypt/chacha.h @@ -77,7 +77,7 @@ enum { typedef struct ChaCha { word32 X[CHACHA_CHUNK_WORDS]; /* state of cipher */ -#ifdef HAVE_INTEL_AVX1 +#if defined(USE_INTEL_CHACHA_SPEEDUP) /* vpshufd reads 16 bytes but we only use bottom 4. */ byte extra[12]; #endif diff --git a/src/wolfssl/wolfcrypt/cmac.h b/src/wolfssl/wolfcrypt/cmac.h index e59df28..a92e832 100644 --- a/src/wolfssl/wolfcrypt/cmac.h +++ b/src/wolfssl/wolfcrypt/cmac.h @@ -38,8 +38,7 @@ #endif /* avoid redefinition of structs */ -#if !defined(HAVE_FIPS) || \ - (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(2,0,0) #ifndef WC_CMAC_TYPE_DEFINED typedef struct Cmac Cmac; @@ -82,6 +81,11 @@ typedef enum CmacType { #define WC_CMAC_TAG_MAX_SZ AES_BLOCK_SIZE #define WC_CMAC_TAG_MIN_SZ (AES_BLOCK_SIZE/4) +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_cmac_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_CMAC_sanity(void); +#endif + #endif /* HAVE_FIPS */ WOLFSSL_API diff --git a/src/wolfssl/wolfcrypt/cryptocb.h b/src/wolfssl/wolfcrypt/cryptocb.h index 8f66777..29580ea 100644 --- a/src/wolfssl/wolfcrypt/cryptocb.h +++ b/src/wolfssl/wolfcrypt/cryptocb.h @@ -71,7 +71,7 @@ #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) #include #endif -#ifdef HAVE_PQC +#ifdef WOLFSSL_HAVE_KYBER #include #ifdef WOLFSSL_WC_KYBER #include @@ -79,10 +79,10 @@ #include #endif #endif -#if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) #include #endif -#if defined(HAVE_PQC) && defined(HAVE_FALCON) +#if defined(HAVE_FALCON) #include #endif @@ -216,7 +216,7 @@ typedef struct wc_CryptoInfo { byte contextLen; } ed25519verify; #endif - #if defined(HAVE_PQC) && defined(WOLFSSL_HAVE_KYBER) + #if defined(WOLFSSL_HAVE_KYBER) struct { WC_RNG* rng; int size; @@ -241,8 +241,7 @@ typedef struct wc_CryptoInfo { int type; /* enum wc_PqcKemType */ } pqc_decaps; #endif - #if defined(HAVE_PQC) && \ - (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)) + #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) struct { WC_RNG* rng; int size; @@ -399,6 +398,9 @@ typedef struct wc_CryptoInfo { #endif #ifdef WOLFSSL_SHA512 wc_Sha512* sha512; + #endif + #ifdef WOLFSSL_SHA3 + wc_Sha3* sha3; #endif void* ctx; #if HAVE_ANONYMOUS_INLINE_AGGREGATES @@ -525,7 +527,7 @@ WOLFSSL_LOCAL int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, const byte* context, byte contextLen); #endif /* HAVE_ED25519 */ -#if defined(HAVE_PQC) && defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_HAVE_KYBER) WOLFSSL_LOCAL int wc_CryptoCb_PqcKemGetDevId(int type, void* key); WOLFSSL_LOCAL int wc_CryptoCb_MakePqcKemKey(WC_RNG* rng, int type, @@ -538,9 +540,9 @@ WOLFSSL_LOCAL int wc_CryptoCb_PqcEncapsulate(byte* ciphertext, WOLFSSL_LOCAL int wc_CryptoCb_PqcDecapsulate(const byte* ciphertext, word32 ciphertextLen, byte* sharedSecret, word32 sharedSecretLen, int type, void* key); -#endif /* HAVE_PQC && WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_KYBER */ -#if defined(HAVE_PQC) && (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)) +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) WOLFSSL_LOCAL int wc_CryptoCb_PqcSigGetDevId(int type, void* key); WOLFSSL_LOCAL int wc_CryptoCb_MakePqcSignatureKey(WC_RNG* rng, int type, @@ -554,7 +556,7 @@ WOLFSSL_LOCAL int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, WOLFSSL_LOCAL int wc_CryptoCb_PqcSignatureCheckPrivKey(void* key, int type, const byte* pubKey, word32 pubKeySz); -#endif /* HAVE_PQC && (HAVE_FALCON || HAVE_DILITHIUM) */ +#endif /* HAVE_FALCON || HAVE_DILITHIUM */ #ifndef NO_AES #ifdef HAVE_AESGCM @@ -623,6 +625,11 @@ WOLFSSL_LOCAL int wc_CryptoCb_Sha512Hash(wc_Sha512* sha512, const byte* in, word32 inSz, byte* digest); #endif +#ifdef WOLFSSL_SHA3 +WOLFSSL_LOCAL int wc_CryptoCb_Sha3Hash(wc_Sha3* sha3, int type, const byte* in, + word32 inSz, byte* digest); +#endif + #ifndef NO_HMAC WOLFSSL_LOCAL int wc_CryptoCb_Hmac(Hmac* hmac, int macType, const byte* in, word32 inSz, byte* digest); diff --git a/src/wolfssl/wolfcrypt/dh.h b/src/wolfssl/wolfcrypt/dh.h index e94cb59..93e8475 100644 --- a/src/wolfssl/wolfcrypt/dh.h +++ b/src/wolfssl/wolfcrypt/dh.h @@ -30,8 +30,7 @@ #ifndef NO_DH -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -120,6 +119,11 @@ enum { #endif #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_dh_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_DH_sanity(void); +#endif + #ifdef HAVE_PUBLIC_FFDHE #ifdef HAVE_FFDHE_2048 WOLFSSL_API const DhParams* wc_Dh_ffdhe2048_Get(void); diff --git a/src/wolfssl/wolfcrypt/dilithium.h b/src/wolfssl/wolfcrypt/dilithium.h index 5472d09..8b336cf 100644 --- a/src/wolfssl/wolfcrypt/dilithium.h +++ b/src/wolfssl/wolfcrypt/dilithium.h @@ -35,34 +35,458 @@ #include #endif -#if defined(HAVE_PQC) && defined(HAVE_DILITHIUM) +#if defined(HAVE_DILITHIUM) #ifdef HAVE_LIBOQS #include #include #endif +#if defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) && \ + defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_ONLY) + #define WOLFSSL_DILITHIUM_VERIFY_ONLY +#endif +#ifdef WOLFSSL_DILITHIUM_VERIFY_ONLY + #ifndef WOLFSSL_DILITHIUM_NO_MAKE_KEY + #define WOLFSSL_DILITHIUM_NO_MAKE_KEY + #endif + #ifndef WOLFSSL_DILITHIUM_NO_SIGN + #define WOLFSSL_DILITHIUM_NO_SIGN + #endif +#endif + +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + #define WOLFSSL_DILITHIUM_PUBLIC_KEY +#endif +#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ + !defined(WOLFSSL_DILITHIUM_NO_SIGN) + #define WOLFSSL_DILITHIUM_PRIVATE_KEY +#endif + +#if defined(WOLFSSL_DILITHIUM_PUBLIC_KEY) && \ + defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) && \ + !defined(WOLFSSL_DILITHIUM_NO_CHECK_KEY) && \ + !defined(WOLFSSL_DILITHIUM_CHECK_KEY) + #define WOLFSSL_DILITHIUM_CHECK_KEY +#endif + +#ifdef WOLFSSL_WC_DILITHIUM + #include +#ifndef WOLFSSL_DILITHIUM_VERIFY_ONLY + #include +#endif +#endif + +#if defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) && \ + !defined(WC_DILITHIUM_CACHE_MATRIX_A) + #define WC_DILITHIUM_CACHE_MATRIX_A +#endif +#if defined(WC_DILITHIUM_CACHE_PUB_VECTORS) && \ + !defined(WC_DILITHIUM_CACHE_MATRIX_A) + #define WC_DILITHIUM_CACHE_MATRIX_A +#endif + #ifdef __cplusplus extern "C" { #endif /* Macros Definitions */ -#ifdef HAVE_LIBOQS -#define DILITHIUM_LEVEL2_KEY_SIZE OQS_SIG_dilithium_2_length_secret_key -#define DILITHIUM_LEVEL2_SIG_SIZE OQS_SIG_dilithium_2_length_signature -#define DILITHIUM_LEVEL2_PUB_KEY_SIZE OQS_SIG_dilithium_2_length_public_key -#define DILITHIUM_LEVEL2_PRV_KEY_SIZE (DILITHIUM_LEVEL2_PUB_KEY_SIZE+DILITHIUM_LEVEL2_KEY_SIZE) +#ifdef WOLFSSL_WC_DILITHIUM + +#ifndef WOLFSSL_DILITHIUM_ALIGNMENT + #if defined(__arch64__) + #define WOLFSSL_DILITHIUM_ALIGNMENT 8 + #elif defined(__arm__) + #define WOLFSSL_DILITHIUM_ALIGNMENT 4 + #elif !defined(WOLFSSL_AESNI) && defined(WOLFSSL_GENERAL_ALIGNMENT) + #define WOLFSSL_DILITHIUM_ALIGNMENT WOLFSSL_GENERAL_ALIGNMENT + #else + #define WOLFSSL_DILITHIUM_ALIGNMENT 8 + #endif +#endif /* WOLFSSL_DILITHIUM_ALIGNMENT */ + +#define DILITHIUM_LEVEL2_KEY_SIZE 2560 +#define DILITHIUM_LEVEL2_SIG_SIZE 2420 +#define DILITHIUM_LEVEL2_PUB_KEY_SIZE 1312 +#define DILITHIUM_LEVEL2_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL2_PUB_KEY_SIZE + DILITHIUM_LEVEL2_KEY_SIZE) + +#define DILITHIUM_LEVEL3_KEY_SIZE 4032 +#define DILITHIUM_LEVEL3_SIG_SIZE 3309 +#define DILITHIUM_LEVEL3_PUB_KEY_SIZE 1952 +#define DILITHIUM_LEVEL3_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL3_PUB_KEY_SIZE + DILITHIUM_LEVEL3_KEY_SIZE) + +#define DILITHIUM_LEVEL5_KEY_SIZE 4896 +#define DILITHIUM_LEVEL5_SIG_SIZE 4627 +#define DILITHIUM_LEVEL5_PUB_KEY_SIZE 2592 +#define DILITHIUM_LEVEL5_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL5_PUB_KEY_SIZE + DILITHIUM_LEVEL5_KEY_SIZE) + + +/* Modulus. */ +#define DILITHIUM_Q 0x7fe001 +/* Number of bits in modulus. */ +#define DILITHIUM_Q_BITS 23 +/* Number of elements in polynomial. */ +#define DILITHIUM_N 256 + +/* Number of dropped bits. */ +#define DILITHIUM_D 13 +/* Maximum value of dropped bits. */ +#define DILITHIUM_D_MAX (1 << DILITHIUM_D) +/* Half maximum value. */ +#define DILITHIUM_D_MAX_HALF (1 << (DILITHIUM_D - 1)) +/* Number of undropped bits. */ +#define DILITHIUM_U (DILITHIUM_Q_BITS - DILITHIUM_D) + +/* Bits in coefficient range of y, GAMMA1, of 2^17 is 17. */ +#define DILITHIUM_GAMMA1_BITS_17 17 +/* Coefficient range of y, GAMMA1, of 2^17. */ +#define DILITHIUM_GAMMA1_17 (1 << 17) +/* # encoding bits of y is GAMMA1 + 1. */ +#define DILITHIUM_GAMMA1_17_ENC_BITS 18 +/* Coefficient range of y, GAMMA1, of 2^17. */ +/* Bits in coefficient range of y, GAMMA1, of 2^19 is 19. */ +#define DILITHIUM_GAMMA1_BITS_19 19 +/* Coefficient range of y, GAMMA1, of 2^19. */ +#define DILITHIUM_GAMMA1_19 (1 << 19) +/* # encoding bits of y is GAMMA1 + 1. */ +#define DILITHIUM_GAMMA1_19_ENC_BITS 20 + +/* Low-order rounding range, GAMMA2, is Q divided by 88. */ +#define DILITHIUM_Q_LOW_88 ((DILITHIUM_Q - 1) / 88) +/* Absolute low-order rounding range, GAMMA2, is Q divided by 88. */ +#define DILITHIUM_Q_LOW_88_2 (((DILITHIUM_Q - 1) / 88) * 2) +/* # encoding bits of w1 when range is 88. */ +#define DILITHIUM_Q_HI_88_ENC_BITS 6 +/* Low-order rounding range, GAMMA2, is Q divided by 32. */ +#define DILITHIUM_Q_LOW_32 ((DILITHIUM_Q - 1) / 32) +/* Absolute low-order rounding range, GAMMA2, is Q divided by 32. */ +#define DILITHIUM_Q_LOW_32_2 (((DILITHIUM_Q - 1) / 32) * 2) +/* # encoding bits of w1 when range is 32. */ +#define DILITHIUM_Q_HI_32_ENC_BITS 4 + +/* Private key range, eta, of 2. */ +#define DILITHIUM_ETA_2 2 +/* Bits needed to encode values in range -2..2 as a positive number. */ +#define DILITHIUM_ETA_2_BITS 3 +/* Extract count of valid values. */ +#define DILITHIUM_ETA_2_MOD 15 +/* Private key range, eta, of 4. */ +#define DILITHIUM_ETA_4 4 +/* Bits needed to encode values in range -4..4 as a positive number. */ +#define DILITHIUM_ETA_4_BITS 4 +/* Extract count of valid values. */ +#define DILITHIUM_ETA_4_MOD 9 + +/* Number of bytes in a polynomial in memory. */ +#define DILITHIUM_POLY_SIZE (DILITHIUM_N * sizeof(sword32)) + +#ifndef WOLFSSL_NO_ML_DSA_44 + +/* Fist dimension of A, k, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_K 4 +/* Second dimension of A, l, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_L 4 +/* Private key range, ETA, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_ETA DILITHIUM_ETA_2 +/* Number of bits in private key for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_ETA_BITS DILITHIUM_ETA_2_BITS +/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_LAMBDA 16 +/* # +/-1's in polynomial c, TAU, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_TAU 39 +/* BETA = TAU * ETA for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_BETA \ + (PARAMS_ML_DSA_44_TAU * PARAMS_ML_DSA_44_ETA) +/* Max # 1's in the hint h, OMEGA, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_OMEGA 80 +/* Bits in coefficient range of y, GAMMA1, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_GAMMA1_BITS DILITHIUM_GAMMA1_BITS_17 +/* Ccoefficient range of y, GAMMA1, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_GAMMA1 (1 << PARAMS_ML_DSA_44_GAMMA1_BITS) +/* Low-order rounding range, GAMMA2, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_GAMMA2 DILITHIUM_Q_LOW_88 +/* Bits in high-order rounding range, GAMMA2, for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_GAMMA2_HI_BITS 6 +/* Encoding size of w1 in bytes for ML-DSA-44. + * K * N / 8 * 6 - 6 bits as max value is 43 in high bits. */ +#define PARAMS_ML_DSA_44_W1_ENC_SZ \ + (PARAMS_ML_DSA_44_K * DILITHIUM_N / 8 * PARAMS_ML_DSA_44_GAMMA2_HI_BITS) +/* Size of memory used for matrix a in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_A_SIZE \ + (PARAMS_ML_DSA_44_K * PARAMS_ML_DSA_44_L * DILITHIUM_POLY_SIZE) +/* Size of memory used for vector s1 in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_S1_SIZE \ + (PARAMS_ML_DSA_44_L * DILITHIUM_POLY_SIZE) +/* Encoding size of s1 in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_S1_ENC_SIZE \ + (PARAMS_ML_DSA_44_S1_SIZE / sizeof(sword32) * PARAMS_ML_DSA_44_ETA_BITS / 8) +/* Size of memory used for vector s2 in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_S2_SIZE \ + (PARAMS_ML_DSA_44_K * DILITHIUM_POLY_SIZE) +/* Encoding size of s2 in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_S2_ENC_SIZE \ + (PARAMS_ML_DSA_44_S2_SIZE / sizeof(sword32) * PARAMS_ML_DSA_44_ETA_BITS / 8) +/* Encoding size of z in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_Z_ENC_SIZE \ + (PARAMS_ML_DSA_44_S1_SIZE / sizeof(sword32) / 8 * \ + (PARAMS_ML_DSA_44_GAMMA1_BITS + 1)) +/* Encoding size of public key in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_PK_SIZE \ + (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_44_K * DILITHIUM_N * DILITHIUM_U / 8) +/* Encoding size of signature in bytes for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_SIG_SIZE \ + ((PARAMS_ML_DSA_44_LAMBDA * 2) + \ + PARAMS_ML_DSA_44_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_44_GAMMA1_BITS + 1) + \ + PARAMS_ML_DSA_44_OMEGA + PARAMS_ML_DSA_44_K) + +#endif /* WOLFSSL_NO_ML_DSA_44 */ + +#ifndef WOLFSSL_NO_ML_DSA_65 + +/* Fist dimension of A, k, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_K 6 +/* Second dimension of A, l, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_L 5 +/* Private key range, ETA, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_ETA DILITHIUM_ETA_4 +/* Number of bits in private key for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_ETA_BITS DILITHIUM_ETA_4_BITS +/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_LAMBDA 24 +/* # +/-1's in polynomial c, TAU, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_TAU 49 +/* BETA = TAU * ETA for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_BETA \ + (PARAMS_ML_DSA_65_TAU * PARAMS_ML_DSA_65_ETA) +/* Max # 1's in the hint h, OMEGA, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_OMEGA 55 +/* Bits in coefficient range of y, GAMMA1, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_GAMMA1_BITS DILITHIUM_GAMMA1_BITS_19 +/* Ccoefficient range of y, GAMMA1, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_GAMMA1 (1 << PARAMS_ML_DSA_65_GAMMA1_BITS) +/* Low-order rounding range, GAMMA2, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_GAMMA2 DILITHIUM_Q_LOW_32 +/* Bits in high-order rounding range, GAMMA2, for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_GAMMA2_HI_BITS 4 +/* Encoding size of w1 in bytes for ML-DSA-65. + * K * N / 8 * 4 - 4 bits as max value is 15 in high bits. */ +#define PARAMS_ML_DSA_65_W1_ENC_SZ \ + (PARAMS_ML_DSA_65_K * DILITHIUM_N / 8 * PARAMS_ML_DSA_65_GAMMA2_HI_BITS) +/* Size of memory used for matrix a in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_A_SIZE \ + (PARAMS_ML_DSA_65_K * PARAMS_ML_DSA_65_L * DILITHIUM_POLY_SIZE) +/* Size of memory used for vector s1 in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_S1_SIZE \ + (PARAMS_ML_DSA_65_L * DILITHIUM_POLY_SIZE) +/* Encoding size of s1 in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_S1_ENC_SIZE \ + (PARAMS_ML_DSA_65_S1_SIZE / sizeof(sword32) * PARAMS_ML_DSA_65_ETA_BITS / 8) +/* Size of memory used for vector s2 in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_S2_SIZE \ + (PARAMS_ML_DSA_65_K * DILITHIUM_POLY_SIZE) +/* Encoding size of s2 in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_S2_ENC_SIZE \ + (PARAMS_ML_DSA_65_S2_SIZE / sizeof(sword32) * PARAMS_ML_DSA_65_ETA_BITS / 8) +/* Encoding size of z in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_Z_ENC_SIZE \ + (PARAMS_ML_DSA_65_S1_SIZE / sizeof(sword32) / 8 * \ + (PARAMS_ML_DSA_65_GAMMA1_BITS + 1)) +/* Encoding size of public key in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_PK_SIZE \ + (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_65_K * DILITHIUM_N * DILITHIUM_U / 8) +/* Encoding size of signature in bytes for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_SIG_SIZE \ + ((PARAMS_ML_DSA_65_LAMBDA * 2) + \ + PARAMS_ML_DSA_65_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_65_GAMMA1_BITS + 1) + \ + PARAMS_ML_DSA_65_OMEGA + PARAMS_ML_DSA_65_K) + +#endif /* WOLFSSL_NO_ML_DSA_65 */ + +#ifndef WOLFSSL_NO_ML_DSA_87 + +/* Fist dimension of A, k, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_K 8 +/* Second dimension of A, l, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_L 7 +/* Private key range, ETA, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_ETA DILITHIUM_ETA_2 +/* Number of bits in private key for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_ETA_BITS DILITHIUM_ETA_2_BITS +/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_LAMBDA 32 +/* # +/-1's in polynomial c, TAU, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_TAU 60 +/* BETA = TAU * ETA for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_BETA \ + (PARAMS_ML_DSA_87_TAU * PARAMS_ML_DSA_87_ETA) +/* Max # 1's in the hint h, OMEGA, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_OMEGA 75 +/* Bits in coefficient range of y, GAMMA1, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_GAMMA1_BITS DILITHIUM_GAMMA1_BITS_19 +/* Ccoefficient range of y, GAMMA1, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_GAMMA1 (1 << PARAMS_ML_DSA_87_GAMMA1_BITS) +/* Low-order rounding range, GAMMA2, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_GAMMA2 DILITHIUM_Q_LOW_32 +/* Bits in high-order rounding range, GAMMA2, for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_GAMMA2_HI_BITS 4 +/* Encoding size of w1 in bytes for ML-DSA-87. + * K * N / 8 * 4 - 4 bits as max value is 15 in high bits. */ +#define PARAMS_ML_DSA_87_W1_ENC_SZ \ + (PARAMS_ML_DSA_87_K * DILITHIUM_N / 8 * PARAMS_ML_DSA_87_GAMMA2_HI_BITS) +/* Size of memory used for matrix A in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_A_SIZE \ + (PARAMS_ML_DSA_87_K * PARAMS_ML_DSA_87_L * DILITHIUM_POLY_SIZE) +#define PARAMS_ML_DSA_87_S_SIZE 4 +/* Size of memory used for vector s1 in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_S1_SIZE \ + (PARAMS_ML_DSA_87_L * DILITHIUM_POLY_SIZE) +/* Encoding size of s1 in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_S1_ENC_SIZE \ + (PARAMS_ML_DSA_87_S1_SIZE / sizeof(sword32) * PARAMS_ML_DSA_87_ETA_BITS / 8) +/* Size of memory used for vector s2 in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_S2_SIZE \ + (PARAMS_ML_DSA_87_K * DILITHIUM_POLY_SIZE) +/* Encoding size of s2 in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_S2_ENC_SIZE \ + (PARAMS_ML_DSA_87_S2_SIZE / sizeof(sword32) * PARAMS_ML_DSA_87_ETA_BITS / 8) +/* Encoding size of z in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_Z_ENC_SIZE \ + (PARAMS_ML_DSA_87_S1_SIZE / sizeof(sword32) / 8 * \ + (PARAMS_ML_DSA_87_GAMMA1_BITS + 1)) +/* Encoding size of public key in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_PK_SIZE \ + (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_87_K * DILITHIUM_N * DILITHIUM_U / 8) +/* Encoding size of signature in bytes for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_SIG_SIZE \ + ((PARAMS_ML_DSA_87_LAMBDA * 2) + \ + PARAMS_ML_DSA_87_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_87_GAMMA1_BITS + 1) + \ + PARAMS_ML_DSA_87_OMEGA + PARAMS_ML_DSA_87_K) + +#endif /* WOLFSSL_NO_ML_DSA_87 */ + + +#ifndef WOLFSSL_NO_ML_DSA_87 + +#define DILITHIUM_MAX_W1_ENC_SZ PARAMS_ML_DSA_87_W1_ENC_SZ +/* Maximum collision strength of c-tilde in bytes. */ +#define DILITHIUM_MAX_LAMBDA PARAMS_ML_DSA_87_LAMBDA + +/* Maximum count of elements of a vector with dimension K. */ +#define DILITHIUM_MAX_K_VECTOR_COUNT \ + (PARAMS_ML_DSA_87_K * DILITHIUM_N) +/* Maximum count of elements of a vector with dimension L. */ +#define DILITHIUM_MAX_L_VECTOR_COUNT \ + (PARAMS_ML_DSA_87_L * DILITHIUM_N) + +#elif !defined(WOLFSSL_NO_ML_DSA_65) + +/* Maximum w1 encoding size in bytes. */ +#define DILITHIUM_MAX_W1_ENC_SZ PARAMS_ML_DSA_65_W1_ENC_SZ +/* Maximum collision strength of c-tilde in bytes. */ +#define DILITHIUM_MAX_LAMBDA PARAMS_ML_DSA_65_LAMBDA + +/* Maximum count of elements of a vector with dimension K. */ +#define DILITHIUM_MAX_K_VECTOR_COUNT \ + (PARAMS_ML_DSA_65_K * DILITHIUM_N) +/* Maximum count of elements of a vector with dimension L. */ +#define DILITHIUM_MAX_L_VECTOR_COUNT \ + (PARAMS_ML_DSA_65_L * DILITHIUM_N) + +#else + +/* Maximum w1 encoding size in bytes. */ +#define DILITHIUM_MAX_W1_ENC_SZ PARAMS_ML_DSA_44_W1_ENC_SZ +/* Maximum collision strength of c-tilde in bytes. */ +#define DILITHIUM_MAX_LAMBDA PARAMS_ML_DSA_44_LAMBDA + +/* Maximum count of elements of a vector with dimension K. */ +#define DILITHIUM_MAX_K_VECTOR_COUNT \ + (PARAMS_ML_DSA_44_K * DILITHIUM_N) +/* Maximum count of elements of a vector with dimension L. */ +#define DILITHIUM_MAX_L_VECTOR_COUNT \ + (PARAMS_ML_DSA_44_L * DILITHIUM_N) -#define DILITHIUM_LEVEL3_KEY_SIZE OQS_SIG_dilithium_3_length_secret_key -#define DILITHIUM_LEVEL3_SIG_SIZE OQS_SIG_dilithium_3_length_signature -#define DILITHIUM_LEVEL3_PUB_KEY_SIZE OQS_SIG_dilithium_3_length_public_key -#define DILITHIUM_LEVEL3_PRV_KEY_SIZE (DILITHIUM_LEVEL3_PUB_KEY_SIZE+DILITHIUM_LEVEL3_KEY_SIZE) +#endif + +/* Length of K in bytes. */ +#define DILITHIUM_K_SZ 32 +/* Length of TR in bytes. */ +#define DILITHIUM_TR_SZ 64 +/* Length of public key seed in bytes when expanding a. */ +#define DILITHIUM_PUB_SEED_SZ 32 +/* Length of private key seed in bytes when generating a key. */ +#define DILITHIUM_PRIV_SEED_SZ 64 + +/* Length of seed when creating vector c. */ +#define DILITHIUM_SEED_SZ 32 +/* Length of seeds created when making a key. */ +#define DILITHIUM_SEEDS_SZ 128 + +/* Length of MU in bytes. */ +#define DILITHIUM_MU_SZ 64 +/* Length of random in bytes when generating a signature. */ +#define DILITHIUM_RND_SZ 32 +/* Length of private random in bytes when generating a signature. */ +#define DILITHIUM_PRIV_RAND_SEED_SZ 64 + +/* 5 blocks, each block 21 * 8 bytes = 840 bytes. + * Minimum required is 256 * 3 = 768. */ +#define DILITHIUM_GEN_A_NBLOCKS 5 +/* Number of bytes to generate with Shake128 when generating A. */ +#define DILITHIUM_GEN_A_BYTES \ + (DILITHIUM_GEN_A_NBLOCKS * WC_SHA3_128_COUNT * 8) +/* Number of bytes to a block of SHAKE-128 when generating A. */ +#define DILITHIUM_GEN_A_BLOCK_BYTES (WC_SHA3_128_COUNT * 8) + +/* Number of bytes to a block of SHAKE-256 when generating c. */ +#define DILITHIUM_GEN_C_BLOCK_BYTES (WC_SHA3_256_COUNT * 8) + + +#ifndef WOLFSSL_DILITHIUM_SMALL +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* A block SHAKE-128 output plus one for reading 4 bytes at a time. */ + #define DILITHIUM_REJ_NTT_POLY_H_SIZE (DILITHIUM_GEN_A_BYTES + 1) +#else + /* A block SHAKE-128 output. */ + #define DILITHIUM_REJ_NTT_POLY_H_SIZE DILITHIUM_GEN_A_BYTES +#endif /* LITTLE_ENDIAN_ORDER && WOLFSSL_DILITHIUM_ALIGNMENT == 0 */ +#else +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* A block SHAKE-128 output plus one for reading 4 bytes at a time. */ + #define DILITHIUM_REJ_NTT_POLY_H_SIZE (DILITHIUM_GEN_A_BLOCK_BYTES + 1) +#else + /* A block SHAKE-128 output. */ + #define DILITHIUM_REJ_NTT_POLY_H_SIZE DILITHIUM_GEN_A_BLOCK_BYTES +#endif /* LITTLE_ENDIAN_ORDER && WOLFSSL_DILITHIUM_ALIGNMENT == 0 */ +#endif + +#elif defined(HAVE_LIBOQS) + +#define DILITHIUM_LEVEL2_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_secret_key +#define DILITHIUM_LEVEL2_SIG_SIZE OQS_SIG_ml_dsa_44_ipd_length_signature +#define DILITHIUM_LEVEL2_PUB_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_public_key +#define DILITHIUM_LEVEL2_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL2_PUB_KEY_SIZE+DILITHIUM_LEVEL2_KEY_SIZE) + +#define DILITHIUM_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key +#define DILITHIUM_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature +#define DILITHIUM_LEVEL3_PUB_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_public_key +#define DILITHIUM_LEVEL3_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL3_PUB_KEY_SIZE+DILITHIUM_LEVEL3_KEY_SIZE) + +#define DILITHIUM_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key +#define DILITHIUM_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature +#define DILITHIUM_LEVEL5_PUB_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_public_key +#define DILITHIUM_LEVEL5_PRV_KEY_SIZE \ + (DILITHIUM_LEVEL5_PUB_KEY_SIZE+DILITHIUM_LEVEL5_KEY_SIZE) -#define DILITHIUM_LEVEL5_KEY_SIZE OQS_SIG_dilithium_5_length_secret_key -#define DILITHIUM_LEVEL5_SIG_SIZE OQS_SIG_dilithium_5_length_signature -#define DILITHIUM_LEVEL5_PUB_KEY_SIZE OQS_SIG_dilithium_5_length_public_key -#define DILITHIUM_LEVEL5_PRV_KEY_SIZE (DILITHIUM_LEVEL5_PUB_KEY_SIZE+DILITHIUM_LEVEL5_KEY_SIZE) #endif #define DILITHIUM_MAX_KEY_SIZE DILITHIUM_LEVEL5_KEY_SIZE @@ -77,9 +501,34 @@ /* Structs */ +#ifdef WOLFSSL_WC_DILITHIUM +typedef struct wc_dilithium_params { + byte level; + byte k; + byte l; + byte eta; + byte eta_bits; + byte tau; + byte beta; + byte omega; + byte lambda; + byte gamma1_bits; + word32 gamma2; + word32 w1EncSz; + word16 aSz; + word16 s1Sz; + word16 s1EncSz; + word16 s2Sz; + word16 s2EncSz; + word16 zEncSz; + word16 pkSz; + word16 sigSz; +} wc_dilithium_params; +#endif + struct dilithium_key { - bool pubKeySet; - bool prvKeySet; + byte pubKeySet; + byte prvKeySet; byte level; /* 2,3 or 5 */ #ifdef WOLF_CRYPTO_CB @@ -93,8 +542,43 @@ struct dilithium_key { int labelLen; #endif +#ifndef WOLFSSL_DILITHIUM_ASSIGN_KEY byte p[DILITHIUM_MAX_PUB_KEY_SIZE]; - byte k[DILITHIUM_MAX_PRV_KEY_SIZE]; + byte k[DILITHIUM_MAX_KEY_SIZE]; +#else + const byte* p; + const byte* k; +#endif + +#ifdef WOLFSSL_WC_DILITHIUM + const wc_dilithium_params* params; + wc_Shake shake; +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + sword32* a; + byte aSet; +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + sword32* s1; + sword32* s2; + sword32* t0; + byte privVecsSet; +#endif +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + sword32* t1; + byte pubVecSet; +#endif +#if defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && \ + defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) + sword32 z[DILITHIUM_MAX_L_VECTOR_COUNT]; + sword32 c[DILITHIUM_N]; + sword32 w[DILITHIUM_N]; + sword32 t1[DILITHIUM_N]; + byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; + byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; + byte block[DILITHIUM_GEN_C_BLOCK_BYTES]; +#endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC && + * WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM */ +#endif /* WOLFSSL_WC_DILITHIUM */ }; #ifndef WC_DILITHIUMKEY_TYPE_DEFINED @@ -104,12 +588,22 @@ struct dilithium_key { /* Functions */ +#ifndef WOLFSSL_DILITHIUM_VERIFY_ONLY +WOLFSSL_API +int wc_dilithium_make_key(dilithium_key* key, WC_RNG* rng); WOLFSSL_API -int wc_dilithium_sign_msg(const byte* in, word32 inLen, byte* out, word32 *outLen, - dilithium_key* key, WC_RNG* rng); +int wc_dilithium_make_key_from_seed(dilithium_key* key, const byte* seed); + +WOLFSSL_API +int wc_dilithium_sign_msg(const byte* in, word32 inLen, byte* out, + word32 *outLen, dilithium_key* key, WC_RNG* rng); +WOLFSSL_API +int wc_dilithium_sign_msg_with_seed(const byte* in, word32 inLen, byte* out, + word32 *outLen, dilithium_key* key, byte* seed); +#endif WOLFSSL_API int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, - word32 msgLen, int* res, dilithium_key* key); + word32 msgLen, int* res, dilithium_key* key); WOLFSSL_API int wc_dilithium_init(dilithium_key* key); @@ -120,10 +614,10 @@ int wc_dilithium_init_ex(dilithium_key* key, void* heap, int devId); #ifdef WOLF_PRIVATE_KEY_ID WOLFSSL_API int wc_dilithium_init_id(dilithium_key* key, const unsigned char* id, int len, - void* heap, int devId); + void* heap, int devId); WOLFSSL_API int wc_dilithium_init_label(dilithium_key* key, const char* label, void* heap, - int devId); + int devId); #endif WOLFSSL_API @@ -133,54 +627,140 @@ int wc_dilithium_get_level(dilithium_key* key, byte* level); WOLFSSL_API void wc_dilithium_free(dilithium_key* key); +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY WOLFSSL_API -int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key); -WOLFSSL_API -int wc_dilithium_import_private_only(const byte* priv, word32 privSz, - dilithium_key* key); -WOLFSSL_API -int wc_dilithium_import_private_key(const byte* priv, word32 privSz, - const byte* pub, word32 pubSz, - dilithium_key* key); - -WOLFSSL_API -int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen); +int wc_dilithium_size(dilithium_key* key); +#endif +#if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) && \ + defined(WOLFSSL_DILITHIUM_PUBLIC_KEY) WOLFSSL_API -int wc_dilithium_export_private_only(dilithium_key* key, byte* out, word32* outLen); +int wc_dilithium_priv_size(dilithium_key* key); +#endif +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY WOLFSSL_API -int wc_dilithium_export_private(dilithium_key* key, byte* out, word32* outLen); +int wc_dilithium_pub_size(dilithium_key* key); +#endif +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) WOLFSSL_API -int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, - byte* pub, word32 *pubSz); +int wc_dilithium_sig_size(dilithium_key* key); +#endif +#ifdef WOLFSSL_DILITHIUM_CHECK_KEY WOLFSSL_API int wc_dilithium_check_key(dilithium_key* key); +#endif +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY WOLFSSL_API -int wc_dilithium_size(dilithium_key* key); +int wc_dilithium_import_public(const byte* in, word32 inLen, + dilithium_key* key); +#endif +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY WOLFSSL_API -int wc_dilithium_priv_size(dilithium_key* key); +int wc_dilithium_import_private(const byte* priv, word32 privSz, + dilithium_key* key); +#define wc_dilithium_import_private_only wc_dilithium_import_private WOLFSSL_API -int wc_dilithium_pub_size(dilithium_key* key); +int wc_dilithium_import_key(const byte* priv, word32 privSz, + const byte* pub, word32 pubSz, dilithium_key* key); +#endif + +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY WOLFSSL_API -int wc_dilithium_sig_size(dilithium_key* key); +int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen); +#endif +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY +WOLFSSL_API +int wc_dilithium_export_private(dilithium_key* key, byte* out, word32* outLen); +#endif +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY +WOLFSSL_API +int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, + byte* pub, word32 *pubSz); +#endif +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 +#if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) WOLFSSL_API int wc_Dilithium_PrivateKeyDecode(const byte* input, - word32* inOutIdx, - dilithium_key* key, word32 inSz); + word32* inOutIdx, dilithium_key* key, word32 inSz); +#endif +#ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY WOLFSSL_API int wc_Dilithium_PublicKeyDecode(const byte* input, - word32* inOutIdx, - dilithium_key* key, word32 inSz); + word32* inOutIdx, dilithium_key* key, word32 inSz); +#endif + +#ifdef WC_ENABLE_ASYM_KEY_EXPORT +WOLFSSL_API int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, + word32 inLen, int withAlg); +#endif +#if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) WOLFSSL_API int wc_Dilithium_KeyToDer(dilithium_key* key, byte* output, - word32 inLen); + word32 inLen); +#endif +#ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, - word32 inLen); -WOLFSSL_API int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, - word32 inLen, int withAlg); + word32 inLen); +#endif +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ + + + +#define WC_ML_DSA_44 2 +#define WC_ML_DSA_65 3 +#define WC_ML_DSA_87 5 + +#define DILITHIUM_ML_DSA_44_KEY_SIZE 2560 +#define DILITHIUM_ML_DSA_44_SIG_SIZE 2420 +#define DILITHIUM_ML_DSA_44_PUB_KEY_SIZE 1312 +#define DILITHIUM_ML_DSA_44_PRV_KEY_SIZE \ + (DILITHIUM_ML_DSA_44_PUB_KEY_SIZE + DILITHIUM_ML_DSA_44_KEY_SIZE) + +#define DILITHIUM_ML_DSA_65_KEY_SIZE 4032 +#define DILITHIUM_ML_DSA_65_SIG_SIZE 3309 +#define DILITHIUM_ML_DSA_65_PUB_KEY_SIZE 1952 +#define DILITHIUM_ML_DSA_65_PRV_KEY_SIZE \ + (DILITHIUM_ML_DSA_65_PUB_KEY_SIZE + DILITHIUM_ML_DSA_65_KEY_SIZE) + +#define DILITHIUM_ML_DSA_87_KEY_SIZE 4896 +#define DILITHIUM_ML_DSA_87_SIG_SIZE 4627 +#define DILITHIUM_ML_DSA_87_PUB_KEY_SIZE 2592 +#define DILITHIUM_ML_DSA_87_PRV_KEY_SIZE \ + (DILITHIUM_ML_DSA_87_PUB_KEY_SIZE + DILITHIUM_ML_DSA_87_KEY_SIZE) + + +#define MlDsaKey dilithium_key + + +#define wc_MlDsaKey_Init(key, heap, devId) \ + wc_dilithium_init_ex(key, heap, devId) +#define wc_MlDsaKey_SetParams(key, id) \ + wc_dilithium_set_level(key, id) +#define wc_MlDsaKey_GetParams(key, id) \ + wc_dilithium_get_level(key, id) +#define wc_MlDsaKey_MakeKey(key, rng) \ + wc_dilithium_make_key(key, rng) +#define wc_MlDsaKey_ExportPrivRaw(key, out, outLen) \ + wc_dilithium_export_private_only(key, out, outLen) +#define wc_MlDsaKey_ImportPrivRaw(key, in, inLen) \ + wc_dilithium_import_private_only(out, outLen, key) +#define wc_MlDsaKey_Sign(key, sig, sigSz, msg, msgSz, rng) \ + wc_dilithium_sign_msg(msg, msgSz, sig, sigSz, key, rng) +#define wc_MlDsaKey_Free(key) \ + wc_dilithium_free(key) +#define wc_MlDsaKey_ExportPubRaw(key, out, outLen) \ + wc_dilithium_export_public(key, out, outLen) +#define wc_MlDsaKey_ImportPubRaw(key, in, inLen) \ + wc_dilithium_import_public(out, outLen, key) +#define wc_MlDsaKey_Verify(key, sig, sigSz, msg, msgSz, res) \ + wc_dilithium_verify_msg(sig, sigSz, msg, msgSz, res, key) + +int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len); +int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len); +int wc_MlDsaKey_GetSigLen(MlDsaKey* key, int* len); #ifdef __cplusplus } /* extern "C" */ #endif -#endif /* HAVE_PQC && HAVE_DILITHIUM */ +#endif /* HAVE_DILITHIUM */ #endif /* WOLF_CRYPT_DILITHIUM_H */ diff --git a/src/wolfssl/wolfcrypt/ecc.h b/src/wolfssl/wolfcrypt/ecc.h index 2d7ee32..4a198a6 100644 --- a/src/wolfssl/wolfcrypt/ecc.h +++ b/src/wolfssl/wolfcrypt/ecc.h @@ -31,8 +31,7 @@ #ifdef HAVE_ECC -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -83,6 +82,10 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_ecc_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_ECC_sanity(void); +#endif /* Enable curve B parameter if needed */ #if defined(HAVE_COMP_KEY) || defined(ECC_CACHE_CURVE) @@ -131,6 +134,14 @@ #endif #endif +#if FIPS_VERSION3_GE(6,0,0) + #define WC_ECC_FIPS_SIG_MIN 224 + #define WC_ECC_FIPS_GEN_MIN (WC_ECC_FIPS_SIG_MIN/8) +#endif + +#ifdef WOLFSSL_SM2 + #define WOLFSSL_SM2_KEY_BITS 256 +#endif /* calculate max ECC bytes */ #if ((MAX_ECC_BITS * 2) % 8) == 0 @@ -209,13 +220,13 @@ typedef enum ecc_curve_id { ECC_CURVE_DEF = 0, /* NIST or SECP */ /* NIST Prime Curves */ - ECC_SECP192R1, + ECC_SECP192R1, /* 1 */ ECC_PRIME192V2, ECC_PRIME192V3, ECC_PRIME239V1, ECC_PRIME239V2, ECC_PRIME239V3, - ECC_SECP256R1, + ECC_SECP256R1, /* 7 */ /* SECP Curves */ ECC_SECP112R1, @@ -224,9 +235,9 @@ typedef enum ecc_curve_id { ECC_SECP128R2, ECC_SECP160R1, ECC_SECP160R2, - ECC_SECP224R1, - ECC_SECP384R1, - ECC_SECP521R1, + ECC_SECP224R1, /* 14 */ + ECC_SECP384R1, /* 15 */ + ECC_SECP521R1, /* 16 */ /* Koblitz */ ECC_SECP160K1, @@ -286,7 +297,7 @@ typedef byte ecc_oid_t; /* ECC set type defined a GF(p) curve */ #ifndef WOLFSSL_ECC_CURVE_STATIC -typedef struct ecc_set_type { +struct ecc_set_type { int size; /* The size of the curve in octets */ int id; /* id of this curve */ const char* name; /* name of this curve */ @@ -300,13 +311,13 @@ typedef struct ecc_set_type { word32 oidSz; word32 oidSum; /* sum of encoded OID bytes */ int cofactor; -} ecc_set_type; +}; #else #define MAX_ECC_NAME 16 #define MAX_ECC_STRING ((MAX_ECC_BYTES * 2) + 2) /* The values are stored as text strings. */ -typedef struct ecc_set_type { +struct ecc_set_type { int size; /* The size of the curve in octets */ int id; /* id of this curve */ char name[MAX_ECC_NAME]; /* name of this curve */ @@ -320,7 +331,7 @@ typedef struct ecc_set_type { word32 oidSz; word32 oidSum; /* sum of encoded OID bytes */ int cofactor; -} ecc_set_type; +}; #endif @@ -430,10 +441,19 @@ typedef struct alt_fp_int { #define WC_ECCKEY_TYPE_DEFINED #endif +#ifndef WC_ECCPOINT_TYPE_DEFINED + typedef struct ecc_point ecc_point; + #define WC_ECCPOINT_TYPE_DEFINED +#endif + +#ifndef WC_ECCSET_TYPE_DEFINED + typedef struct ecc_set_type ecc_set_type; + #define WC_ECCSET_TYPE_DEFINED +#endif /* A point on an ECC curve, stored in Jacobian format such that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */ -typedef struct { +struct ecc_point { #ifndef ALT_ECC_SIZE mp_int x[1]; /* The x coordinate */ mp_int y[1]; /* The y coordinate */ @@ -447,7 +467,7 @@ typedef struct { #if defined(WOLFSSL_SMALL_STACK_CACHE) && !defined(WOLFSSL_ECC_NO_SMALL_STACK) ecc_key* key; #endif -} ecc_point; +}; /* ECC Flags */ enum { @@ -490,6 +510,17 @@ struct ecc_key { mp_int* k; alt_fp_int ka[1]; #endif +#ifdef WOLFSSL_ECC_BLIND_K +#ifndef ALT_ECC_SIZE + mp_int kb[1]; + mp_int ku[1]; +#else + mp_int* kb; + mp_int* ku; + alt_fp_int kba[1]; + alt_fp_int kua[1]; +#endif +#endif #ifdef WOLFSSL_CAAM word32 blackKey; /* address of key encrypted and in secure memory */ @@ -508,9 +539,6 @@ struct ecc_key { void* devCtx; int devId; #endif -#if defined(HAVE_PKCS11) - byte isPkcs11 : 1; /* indicate if PKCS11 is preferred */ -#endif #ifdef WOLFSSL_SILABS_SE_ACCEL sl_se_command_context_t cmd_ctx; sl_se_key_descriptor_t key; @@ -590,7 +618,20 @@ struct ecc_key { #endif }; -#define wc_ecc_key_get_priv(key) ((key)->k) +#ifndef WOLFSSL_ECC_BLIND_K +#define ecc_get_k(key) (key)->k +#define ecc_blind_k(key, b) (void)b +#define ecc_blind_k_rng(key, rng) 0 + +#define wc_ecc_key_get_priv(key) (key)->k +#else +mp_int* ecc_get_k(ecc_key* key); +void ecc_blind_k(ecc_key* key, mp_int* b); +int ecc_blind_k_rng(ecc_key* key, WC_RNG* rng); + +WOLFSSL_API mp_int* wc_ecc_key_get_priv(ecc_key* key); +#endif + #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV @@ -946,6 +987,8 @@ const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx); WOLFSSL_API int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt); WOLFSSL_API +int wc_ecc_ctx_set_own_salt(ecEncCtx* ctx, const byte* salt, word32 sz); +WOLFSSL_API int wc_ecc_ctx_set_kdf_salt(ecEncCtx* ctx, const byte* salt, word32 sz); WOLFSSL_API int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz); diff --git a/src/wolfssl/wolfcrypt/ed25519.h b/src/wolfssl/wolfcrypt/ed25519.h index 9748d6d..efba650 100644 --- a/src/wolfssl/wolfcrypt/ed25519.h +++ b/src/wolfssl/wolfcrypt/ed25519.h @@ -45,6 +45,10 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_ed25519_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_ED25519_sanity(void); +#endif /* info about EdDSA curve specifically ed25519, defined as an elliptic curve over GF(p) */ @@ -70,11 +74,6 @@ enum { Ed25519ph = 1 }; -#ifndef WC_ED25519KEY_TYPE_DEFINED - typedef struct ed25519_key ed25519_key; - #define WC_ED25519KEY_TYPE_DEFINED -#endif - /* ED25519 Flags */ enum { WC_ED25519_FLAG_NONE = 0x00, @@ -111,6 +110,11 @@ struct ed25519_key { #endif }; +#ifndef WC_ED25519KEY_TYPE_DEFINED + typedef struct ed25519_key ed25519_key; + #define WC_ED25519KEY_TYPE_DEFINED +#endif + WOLFSSL_API int wc_ed25519_make_public(ed25519_key* key, unsigned char* pubKey, diff --git a/src/wolfssl/wolfcrypt/ed448.h b/src/wolfssl/wolfcrypt/ed448.h index 48011fc..5884bda 100644 --- a/src/wolfssl/wolfcrypt/ed448.h +++ b/src/wolfssl/wolfcrypt/ed448.h @@ -47,6 +47,10 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_ed448_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_ED448_sanity(void); +#endif /* info about EdDSA curve specifically ed448, defined as an elliptic curve * over GF(p) @@ -72,11 +76,6 @@ enum { Ed448ph = 1 }; -#ifndef WC_ED448KEY_TYPE_DEFINED - typedef struct ed448_key ed448_key; - #define WC_ED448KEY_TYPE_DEFINED -#endif - /* An ED448 Key */ struct ed448_key { byte p[ED448_PUB_KEY_SIZE]; /* compressed public key */ @@ -102,6 +101,10 @@ struct ed448_key { #endif }; +#ifndef WC_ED448KEY_TYPE_DEFINED + typedef struct ed448_key ed448_key; + #define WC_ED448KEY_TYPE_DEFINED +#endif WOLFSSL_API int wc_ed448_make_public(ed448_key* key, unsigned char* pubKey, diff --git a/src/wolfssl/wolfcrypt/error-crypt.h b/src/wolfssl/wolfcrypt/error-crypt.h index 99afb96..dbe0553 100644 --- a/src/wolfssl/wolfcrypt/error-crypt.h +++ b/src/wolfssl/wolfcrypt/error-crypt.h @@ -73,8 +73,8 @@ enum { VAR_STATE_CHANGE_E = -126, /* var state modified by different thread */ FIPS_DEGRADED_E = -127, /* FIPS Module in degraded mode */ - /* -128 unused. */ - /* -129 unused. */ + FIPS_CODE_SZ_E = -128, /* Module CODE too big */ + FIPS_DATA_SZ_E = -129, /* Module DATA too big */ RSA_WRONG_TYPE_E = -130, /* RSA wrong block type for RSA function */ RSA_BUFFER_E = -131, /* RSA buffer error, output too small or @@ -107,12 +107,14 @@ enum { ASN_SIG_HASH_E = -156, /* ASN sig error, unsupported hash type */ ASN_SIG_KEY_E = -157, /* ASN sig error, unsupported key type */ ASN_DH_KEY_E = -158, /* ASN key init error, invalid input */ - /* -159 unused. */ + KDF_SRTP_KAT_FIPS_E = -159, /* SRTP-KDF Known Answer Test Failure */ ASN_CRIT_EXT_E = -160, /* ASN unsupported critical extension */ ASN_ALT_NAME_E = -161, /* ASN alternate name error */ ASN_NO_PEM_HEADER = -162, /* ASN no PEM header found */ - - /* -163..-169 unused. */ + ED25519_KAT_FIPS_E = -163, /* Ed25519 Known answer test failure */ + ED448_KAT_FIPS_E = -164, /* Ed448 Known answer test failure */ + PBKDF2_KAT_FIPS_E = -165, /* PBKDF2 Known answer test failure */ + /* -166..-169 unused. */ ECC_BAD_ARG_E = -170, /* ECC input argument of wrong type */ ASN_ECC_KEY_E = -171, /* ASN ECC bad input */ @@ -188,10 +190,11 @@ enum { WC_INIT_E = -228, /* wolfcrypt failed to initialize */ SIG_VERIFY_E = -229, /* wolfcrypt signature verify error */ BAD_COND_E = -230, /* Bad condition variable operation */ - SIG_TYPE_E = -231, /* Signature Type not enabled/available */ + SIG_TYPE_E = -231, /* Signature Type not enabled/available + * NOTE: 1024-bit sign disabled in FIPS mode */ HASH_TYPE_E = -232, /* Hash Type not enabled/available */ - /* -233 unused. */ + FIPS_INVALID_VER_E = -233, /* Invalid FIPS Version defined */ WC_KEY_SIZE_E = -234, /* Key size error, either too small or large */ ASN_COUNTRY_SIZE_E = -235, /* ASN Cert Gen, invalid country code size */ @@ -291,6 +294,22 @@ WOLFSSL_API void wc_ErrorString(int err, char* buff); WOLFSSL_ABI WOLFSSL_API const char* wc_GetErrorString(int error); #endif +#if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && !defined(BUILDING_WOLFSSL) + #undef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#endif +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES + #define WC_NO_ERR_TRACE(label) (CONST_NUM_ERR_ ## label) + #ifndef WC_ERR_TRACE + #define WC_ERR_TRACE(label) \ + ( fprintf(stderr, \ + "ERR TRACE: %s L %d " #label " (%d)\n", \ + __FILE__, __LINE__, label), label) + #endif + #include +#else + #define WC_NO_ERR_TRACE(label) (label) +#endif + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/ext_lms.h b/src/wolfssl/wolfcrypt/ext_lms.h index ccdfdcb..fae812f 100644 --- a/src/wolfssl/wolfcrypt/ext_lms.h +++ b/src/wolfssl/wolfcrypt/ext_lms.h @@ -53,8 +53,8 @@ struct LmsKey { unsigned char pub[HSS_MAX_PUBLIC_KEY_LEN]; #ifndef WOLFSSL_LMS_VERIFY_ONLY hss_working_key * working_key; - write_private_key_cb write_private_key; /* Callback to write/update key. */ - read_private_key_cb read_private_key; /* Callback to read key. */ + wc_lms_write_private_key_cb write_private_key; /* Callback to write/update key. */ + wc_lms_read_private_key_cb read_private_key; /* Callback to read key. */ void * context; /* Context arg passed to callbacks. */ hss_extra_info info; #endif /* ifndef WOLFSSL_LMS_VERIFY_ONLY */ diff --git a/src/wolfssl/wolfcrypt/ext_xmss.h b/src/wolfssl/wolfcrypt/ext_xmss.h index 9abf158..5f51bf5 100644 --- a/src/wolfssl/wolfcrypt/ext_xmss.h +++ b/src/wolfssl/wolfcrypt/ext_xmss.h @@ -45,8 +45,8 @@ struct XmssKey { /* The secret key length is a function of xmss_params. */ unsigned char * sk; word32 sk_len; - write_private_key_cb write_private_key; /* Callback to write/update key. */ - read_private_key_cb read_private_key; /* Callback to read key. */ + wc_xmss_write_private_key_cb write_private_key; /* Callback to write/update key. */ + wc_xmss_read_private_key_cb read_private_key; /* Callback to read key. */ void * context; /* Context arg passed to callbacks. */ #endif /* ifndef WOLFSSL_XMSS_VERIFY_ONLY */ enum wc_XmssState state; diff --git a/src/wolfssl/wolfcrypt/fe_operations.h b/src/wolfssl/wolfcrypt/fe_operations.h index cdd27db..8a1cab7 100644 --- a/src/wolfssl/wolfcrypt/fe_operations.h +++ b/src/wolfssl/wolfcrypt/fe_operations.h @@ -116,8 +116,8 @@ WOLFSSL_LOCAL void fe_cmov(fe f, const fe g, int b); WOLFSSL_LOCAL void fe_pow22523(fe out,const fe z); /* 64 type needed for SHA512 */ -WOLFSSL_LOCAL word64 load_3(const unsigned char *in); -WOLFSSL_LOCAL word64 load_4(const unsigned char *in); +WOLFSSL_LOCAL sword64 load_3(const unsigned char *in); +WOLFSSL_LOCAL sword64 load_4(const unsigned char *in); #ifdef CURVED25519_ASM WOLFSSL_LOCAL void fe_cmov_table(fe* r, fe* base, signed char b); diff --git a/src/wolfssl/wolfcrypt/fips_test.h b/src/wolfssl/wolfcrypt/fips_test.h index dc37477..452e651 100644 --- a/src/wolfssl/wolfcrypt/fips_test.h +++ b/src/wolfssl/wolfcrypt/fips_test.h @@ -51,39 +51,44 @@ enum FipsCastId { - FIPS_CAST_AES_CBC, - FIPS_CAST_AES_GCM, - FIPS_CAST_HMAC_SHA1, - FIPS_CAST_HMAC_SHA2_256, - FIPS_CAST_HMAC_SHA2_512, - FIPS_CAST_HMAC_SHA3_256, - FIPS_CAST_DRBG, - FIPS_CAST_RSA_SIGN_PKCS1v15, - FIPS_CAST_ECC_CDH, - FIPS_CAST_ECC_PRIMITIVE_Z, - FIPS_CAST_DH_PRIMITIVE_Z, - FIPS_CAST_ECDSA, - FIPS_CAST_KDF_TLS12, - FIPS_CAST_KDF_TLS13, - FIPS_CAST_KDF_SSH, - FIPS_CAST_COUNT + /* v5.2.0 & v5.2.1 + */ + FIPS_CAST_AES_CBC = 0, + FIPS_CAST_AES_GCM = 1, + FIPS_CAST_HMAC_SHA1 = 2, + FIPS_CAST_HMAC_SHA2_256 = 3, + FIPS_CAST_HMAC_SHA2_512 = 4, + FIPS_CAST_HMAC_SHA3_256 = 5, + FIPS_CAST_DRBG = 6, + FIPS_CAST_RSA_SIGN_PKCS1v15 = 7, + FIPS_CAST_ECC_CDH = 8, + FIPS_CAST_ECC_PRIMITIVE_Z = 9, + FIPS_CAST_DH_PRIMITIVE_Z = 10, + FIPS_CAST_ECDSA = 11, + FIPS_CAST_KDF_TLS12 = 12, + FIPS_CAST_KDF_TLS13 = 13, + FIPS_CAST_KDF_SSH = 14, + /* v6.0.0 + */ + FIPS_CAST_KDF_SRTP = 15, + FIPS_CAST_ED25519 = 16, + FIPS_CAST_ED448 = 17, + FIPS_CAST_PBKDF2 = 18, + FIPS_CAST_COUNT = 19 }; enum FipsCastStateId { - FIPS_CAST_STATE_INIT, - FIPS_CAST_STATE_PROCESSING, - FIPS_CAST_STATE_SUCCESS, - FIPS_CAST_STATE_FAILURE + FIPS_CAST_STATE_INIT = 0, + FIPS_CAST_STATE_PROCESSING = 1, + FIPS_CAST_STATE_SUCCESS = 2, + FIPS_CAST_STATE_FAILURE = 3 }; enum FipsModeId { - FIPS_MODE_INIT = 0, - FIPS_MODE_NORMAL = 1, - FIPS_MODE_DEGRADED = 2, - FIPS_MODE_FAILED = 3 + FIPS_MODE_INIT = 0, + FIPS_MODE_NORMAL = 1, + FIPS_MODE_DEGRADED = 2, + FIPS_MODE_FAILED = 3 }; - /* FIPS failure callback */ typedef void(*wolfCrypt_fips_cb)(int ok, int err, const char* hash); @@ -94,6 +99,7 @@ WOLFSSL_API int wolfCrypt_SetCb_fips(wolfCrypt_fips_cb cbf); WOLFSSL_API int wolfCrypt_GetStatus_fips(void); WOLFSSL_API int wolfCrypt_GetMode_fips(void); WOLFSSL_API const char* wolfCrypt_GetCoreHash_fips(void); +WOLFSSL_API const char* wolfCrypt_GetRawComputedHash_fips(void); #ifdef HAVE_FORCE_FIPS_FAILURE /* Public function to force failure mode for operational testing */ diff --git a/src/wolfssl/wolfcrypt/hmac.h b/src/wolfssl/wolfcrypt/hmac.h index 929d8b2..0d0844e 100644 --- a/src/wolfssl/wolfcrypt/hmac.h +++ b/src/wolfssl/wolfcrypt/hmac.h @@ -30,8 +30,7 @@ #ifndef NO_HMAC -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif @@ -39,9 +38,17 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_hmac_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_HMAC_sanity(void); +#endif + +#if FIPS_VERSION3_GE(6,0,0) + #define FIPS_ALLOW_SHORT 1 +#endif + /* avoid redefinition of structs */ -#if !defined(HAVE_FIPS) || \ - (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(2,0,0) #ifdef WOLFSSL_ASYNC_CRYPT #include @@ -184,7 +191,10 @@ struct Hmac { #endif /* HAVE_FIPS */ /* does init */ -WOLFSSL_API int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 keySz); +WOLFSSL_API int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, + word32 keySz); +WOLFSSL_API int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, + word32 length, int allowFlag); WOLFSSL_API int wc_HmacUpdate(Hmac* hmac, const byte* in, word32 sz); WOLFSSL_API int wc_HmacFinal(Hmac* hmac, byte* out); #ifdef WOLFSSL_KCAPI_HMAC diff --git a/src/wolfssl/wolfcrypt/kdf.h b/src/wolfssl/wolfcrypt/kdf.h index 7fa3c7e..ad107e5 100644 --- a/src/wolfssl/wolfcrypt/kdf.h +++ b/src/wolfssl/wolfcrypt/kdf.h @@ -39,6 +39,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_kdf_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_KDF_sanity(void); +#endif + enum max_prf { #ifdef HAVE_FFDHE_8192 MAX_PRF_HALF = 516, /* Maximum half secret len */ @@ -132,6 +137,12 @@ WOLFSSL_API int wc_SSH_KDF(byte hashId, byte keyId, /* Length of index for SRTCP KDF. */ #define WC_SRTCP_INDEX_LEN 4 +/* Indicators */ +enum { + WC_SRTCP_32BIT_IDX = 0, + WC_SRTCP_48BIT_IDX = 1, +}; + /* Maximum length of salt that can be used with SRTP/SRTCP. */ #define WC_SRTP_MAX_SALT 14 @@ -141,6 +152,9 @@ WOLFSSL_API int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, WOLFSSL_API int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz); +WOLFSSL_API int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, + word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, + byte* key2, word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator); WOLFSSL_API int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, word32 saltSz, int kdrIdx, const byte* index, byte label, byte* outKey, word32 outKeySz); @@ -152,6 +166,11 @@ WOLFSSL_API int wc_SRTP_KDF_kdr_to_idx(word32 kdr); #endif /* WC_SRTP_KDF */ +#ifdef WC_KDF_NIST_SP_800_56C +WOLFSSL_API int wc_KDA_KDF_onestep(const byte* z, word32 zSz, + const byte* fixedInfo, word32 fixedInfoSz, word32 derivedSecretSz, + enum wc_HashType hashType, byte* output, word32 outputSz); +#endif #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/kyber.h b/src/wolfssl/wolfcrypt/kyber.h index 5132e12..8e9a7b3 100644 --- a/src/wolfssl/wolfcrypt/kyber.h +++ b/src/wolfssl/wolfcrypt/kyber.h @@ -201,10 +201,10 @@ WOLFSSL_API int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, WOLFSSL_API int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, const unsigned char* ct, word32 len); -WOLFSSL_API int wc_KyberKey_DecodePrivateKey(KyberKey* key, unsigned char* in, - word32 len); -WOLFSSL_API int wc_KyberKey_DecodePublicKey(KyberKey* key, unsigned char* in, - word32 len); +WOLFSSL_API int wc_KyberKey_DecodePrivateKey(KyberKey* key, + const unsigned char* in, word32 len); +WOLFSSL_API int wc_KyberKey_DecodePublicKey(KyberKey* key, + const unsigned char* in, word32 len); WOLFSSL_API int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len); WOLFSSL_API int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len); diff --git a/src/wolfssl/wolfcrypt/lms.h b/src/wolfssl/wolfcrypt/lms.h index 483f349..fe87388 100644 --- a/src/wolfssl/wolfcrypt/lms.h +++ b/src/wolfssl/wolfcrypt/lms.h @@ -34,8 +34,8 @@ typedef struct LmsKey LmsKey; /* Private key write and read callbacks. */ -typedef int (*write_private_key_cb)(const byte * priv, word32 privSz, void *context); -typedef int (*read_private_key_cb)(byte * priv, word32 privSz, void *context); +typedef int (*wc_lms_write_private_key_cb)(const byte * priv, word32 privSz, void *context); +typedef int (*wc_lms_read_private_key_cb)(byte * priv, word32 privSz, void *context); /* Return codes returned by private key callbacks. */ enum wc_LmsRc { @@ -75,20 +75,45 @@ enum wc_LmsRc { /* Predefined LMS/HSS parameter sets for convenience. * - * Not predefining a set with Winternitz=1, because the signatures + * Not predefining many sets with Winternitz=1, because the signatures * will be large. */ enum wc_LmsParm { - WC_LMS_PARM_NONE = 0, - WC_LMS_PARM_L1_H15_W2 = 1, /* 1 level Merkle tree of 15 height. */ - WC_LMS_PARM_L1_H15_W4 = 2, - WC_LMS_PARM_L2_H10_W2 = 3, /* 2 level Merkle tree of 10 height. */ - WC_LMS_PARM_L2_H10_W4 = 4, - WC_LMS_PARM_L2_H10_W8 = 5, - WC_LMS_PARM_L3_H5_W2 = 6, /* 3 level Merkle tree of 5 height. */ - WC_LMS_PARM_L3_H5_W4 = 7, - WC_LMS_PARM_L3_H5_W8 = 8, - WC_LMS_PARM_L3_H10_W4 = 9, /* 3 level Merkle tree of 10 height. */ - WC_LMS_PARM_L4_H5_W8 = 10, /* 4 level Merkle tree of 5 height. */ + WC_LMS_PARM_NONE = 0, + WC_LMS_PARM_L1_H5_W1 = 1, + WC_LMS_PARM_L1_H5_W2 = 2, + WC_LMS_PARM_L1_H5_W4 = 3, + WC_LMS_PARM_L1_H5_W8 = 4, + WC_LMS_PARM_L1_H10_W2 = 5, + WC_LMS_PARM_L1_H10_W4 = 6, + WC_LMS_PARM_L1_H10_W8 = 7, + WC_LMS_PARM_L1_H15_W2 = 8, + WC_LMS_PARM_L1_H15_W4 = 9, + WC_LMS_PARM_L1_H15_W8 = 10, + WC_LMS_PARM_L1_H20_W2 = 11, + WC_LMS_PARM_L1_H20_W4 = 12, + WC_LMS_PARM_L1_H20_W8 = 13, + WC_LMS_PARM_L2_H5_W2 = 14, + WC_LMS_PARM_L2_H5_W4 = 15, + WC_LMS_PARM_L2_H5_W8 = 16, + WC_LMS_PARM_L2_H10_W2 = 17, + WC_LMS_PARM_L2_H10_W4 = 18, + WC_LMS_PARM_L2_H10_W8 = 19, + WC_LMS_PARM_L2_H15_W2 = 20, + WC_LMS_PARM_L2_H15_W4 = 21, + WC_LMS_PARM_L2_H15_W8 = 22, + WC_LMS_PARM_L2_H20_W2 = 23, + WC_LMS_PARM_L2_H20_W4 = 24, + WC_LMS_PARM_L2_H20_W8 = 25, + WC_LMS_PARM_L3_H5_W2 = 26, + WC_LMS_PARM_L3_H5_W4 = 27, + WC_LMS_PARM_L3_H5_W8 = 28, + WC_LMS_PARM_L3_H10_W4 = 29, + WC_LMS_PARM_L3_H10_W8 = 30, + WC_LMS_PARM_L4_H5_W2 = 31, + WC_LMS_PARM_L4_H5_W4 = 32, + WC_LMS_PARM_L4_H5_W8 = 33, + WC_LMS_PARM_L4_H10_W4 = 34, + WC_LMS_PARM_L4_H10_W8 = 35, }; /* enum wc_LmsState is to help track the state of an LMS/HSS Key. */ @@ -113,9 +138,9 @@ WOLFSSL_API int wc_LmsKey_GetParameters(const LmsKey * key, int * levels, int * height, int * winternitz); #ifndef WOLFSSL_LMS_VERIFY_ONLY WOLFSSL_API int wc_LmsKey_SetWriteCb(LmsKey * key, - write_private_key_cb write_cb); + wc_lms_write_private_key_cb write_cb); WOLFSSL_API int wc_LmsKey_SetReadCb(LmsKey * key, - read_private_key_cb read_cb); + wc_lms_read_private_key_cb read_cb); WOLFSSL_API int wc_LmsKey_SetContext(LmsKey * key, void * context); WOLFSSL_API int wc_LmsKey_MakeKey(LmsKey * key, WC_RNG * rng); WOLFSSL_API int wc_LmsKey_Reload(LmsKey * key); diff --git a/src/wolfssl/wolfcrypt/logging.h b/src/wolfssl/wolfcrypt/logging.h index 4eee1fa..d17f834 100644 --- a/src/wolfssl/wolfcrypt/logging.h +++ b/src/wolfssl/wolfcrypt/logging.h @@ -181,6 +181,25 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); #define WOLFSSL_MSG_EX(...) WC_DO_NOTHING #endif WOLFSSL_API void WOLFSSL_MSG(const char* msg); +#ifdef WOLFSSL_DEBUG_CODEPOINTS + WOLFSSL_API void WOLFSSL_MSG2( + const char *file, int line, const char* msg); + WOLFSSL_API void WOLFSSL_ENTER2( + const char *file, int line, const char* msg); + WOLFSSL_API void WOLFSSL_LEAVE2( + const char *file, int line, const char* msg, int ret); + #define WOLFSSL_MSG(msg) WOLFSSL_MSG2(__FILE__, __LINE__, msg) + #define WOLFSSL_ENTER(msg) WOLFSSL_ENTER2(__FILE__, __LINE__, msg) + #define WOLFSSL_LEAVE(msg, ret) WOLFSSL_LEAVE2(__FILE__, __LINE__, msg, ret) + #ifdef XVSNPRINTF + WOLFSSL_API void WOLFSSL_MSG_EX2( + const char *file, int line, const char* fmt, ...); + #define WOLFSSL_MSG_EX(fmt, args...) \ + WOLFSSL_MSG_EX2(__FILE__, __LINE__, fmt, ## args) + #else + #define WOLFSSL_MSG_EX2(...) WC_DO_NOTHING + #endif +#endif WOLFSSL_API void WOLFSSL_BUFFER(const byte* buffer, word32 length); #else diff --git a/src/wolfssl/wolfcrypt/mem_track.h b/src/wolfssl/wolfcrypt/mem_track.h index 5857564..c6d8163 100644 --- a/src/wolfssl/wolfcrypt/mem_track.h +++ b/src/wolfssl/wolfcrypt/mem_track.h @@ -177,30 +177,34 @@ static WC_INLINE void* TrackMalloc(size_t sz) (void)line; #endif #endif +#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) + if (pthread_mutex_lock(&memLock) == 0) + { +#endif #ifdef DO_MEM_STATS - ourMemStats.totalAllocs++; - ourMemStats.totalBytes += sz; - ourMemStats.currentBytes += sz; -#ifdef WOLFSSL_TRACK_MEMORY_VERBOSE - if (ourMemStats.peakAllocsTripOdometer < ourMemStats.totalAllocs - - ourMemStats.totalDeallocs) { - ourMemStats.peakAllocsTripOdometer = ourMemStats.totalAllocs - - ourMemStats.totalDeallocs; - } - if (ourMemStats.peakBytesTripOdometer < ourMemStats.currentBytes) -#endif - { + ourMemStats.totalAllocs++; + ourMemStats.totalBytes += sz; + ourMemStats.currentBytes += sz; #ifdef WOLFSSL_TRACK_MEMORY_VERBOSE - ourMemStats.peakBytesTripOdometer = ourMemStats.currentBytes; + if (ourMemStats.peakAllocsTripOdometer < ourMemStats.totalAllocs - + ourMemStats.totalDeallocs) { + ourMemStats.peakAllocsTripOdometer = ourMemStats.totalAllocs - + ourMemStats.totalDeallocs; + } + if (ourMemStats.peakBytesTripOdometer < ourMemStats.currentBytes) #endif - if (ourMemStats.currentBytes > ourMemStats.peakBytes) - ourMemStats.peakBytes = ourMemStats.currentBytes; - } + { + #ifdef WOLFSSL_TRACK_MEMORY_VERBOSE + ourMemStats.peakBytesTripOdometer = ourMemStats.currentBytes; + #endif + if (ourMemStats.currentBytes > ourMemStats.peakBytes) + ourMemStats.peakBytes = ourMemStats.currentBytes; + } + #endif /* DO_MEM_STATS */ #ifdef DO_MEM_LIST - if (pthread_mutex_lock(&memLock) == 0) { #ifdef WOLFSSL_DEBUG_MEMORY header->func = func; header->line = line; @@ -218,7 +222,8 @@ static WC_INLINE void* TrackMalloc(size_t sz) } ourMemList.tail = header; /* add to the end either way */ ourMemList.count++; - +#endif +#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) pthread_mutex_unlock(&memLock); } #endif /* DO_MEM_LIST */ @@ -245,7 +250,7 @@ static WC_INLINE void TrackFree(void* ptr) header = &mt->u.hint; sz = header->thisSize; -#ifdef DO_MEM_LIST +#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) if (pthread_mutex_lock(&memLock) == 0) { #endif @@ -277,7 +282,9 @@ static WC_INLINE void TrackFree(void* ptr) prev->next = next; } ourMemList.count--; +#endif +#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) pthread_mutex_unlock(&memLock); } #endif diff --git a/src/wolfssl/wolfcrypt/memory.h b/src/wolfssl/wolfcrypt/memory.h index 9a1d7b0..31b6a28 100644 --- a/src/wolfssl/wolfcrypt/memory.h +++ b/src/wolfssl/wolfcrypt/memory.h @@ -101,48 +101,72 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, #ifndef WOLFSSL_STATIC_ALIGN #define WOLFSSL_STATIC_ALIGN 16 #endif +/* WOLFMEM_BUCKETS - list of the sizes of buckets in the pool + * WOLFMEM_DIST - list of quantities of buffers in the buckets + * WOLFMEM_DEF_BUCKETS - number of values in WOLFMEM_BUCKETS and WOLFMEM_DIST + * WOLFMEM_MAX_BUCKETS - size of the arrays used to store the buckets and + * dists in the memory pool; defaults to WOLFMEM_DEF_BUCKETS + * + * The following defines provide a reasonable set of buckets in the memory + * pool for running wolfSSL on a Linux box. The bucket and dist lists below + * have nine items each, so WOLFMEM_DEF_BUCKETS is set to 9. + * + * If WOLFMEM_DEF_BUCKETS is less then WOLFMEM_MAX_BUCKETS, the unused values + * are set to zero and ignored. If WOLFMEM_MAX_BUCKETS is less than + * WOLFMEM_DEF_BUCKETS, not all the buckets will be created in the pool. + */ + #ifndef WOLFMEM_DEF_BUCKETS + #define WOLFMEM_DEF_BUCKETS 9 /* number of default memory blocks */ + #endif + #ifndef WOLFMEM_MAX_BUCKETS - #define WOLFMEM_MAX_BUCKETS 9 + #define WOLFMEM_MAX_BUCKETS WOLFMEM_DEF_BUCKETS #endif - #define WOLFMEM_DEF_BUCKETS 9 /* number of default memory blocks */ + + #if WOLFMEM_MAX_BUCKETS < WOLFMEM_DEF_BUCKETS + #warning "ignoring excess buckets, MAX_BUCKETS less than DEF_BUCKETS" + #endif + #ifndef WOLFMEM_IO_SZ #define WOLFMEM_IO_SZ 16992 /* 16 byte aligned */ #endif + + #ifndef LARGEST_MEM_BUCKET + #ifndef SESSION_CERTS + #define LARGEST_MEM_BUCKET 16128 + #elif defined(OPENSSL_EXTRA) + #ifdef WOLFSSL_TLS13 + #define LARGEST_MEM_BUCKET 30400 + #else + #define LARGEST_MEM_BUCKET 25600 + #endif + #elif defined(WOLFSSL_CERT_EXT) + /* certificate extensions requires 24k for the SSL struct */ + #define LARGEST_MEM_BUCKET 24576 + #else + /* increase 23k for object member of WOLFSSL_X509_NAME_ENTRY */ + #define LARGEST_MEM_BUCKET 23440 + #endif + #endif + #ifndef WOLFMEM_BUCKETS #ifndef SESSION_CERTS /* default size of chunks of memory to separate into */ - #ifndef LARGEST_MEM_BUCKET - #define LARGEST_MEM_BUCKET 16128 - #endif #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3456,4544,\ LARGEST_MEM_BUCKET - #elif defined (OPENSSL_EXTRA) + #elif defined(OPENSSL_EXTRA) /* extra storage in structs for multiple attributes and order */ - #ifndef LARGEST_MEM_BUCKET - #ifdef WOLFSSL_TLS13 - #define LARGEST_MEM_BUCKET 30400 - #else - #define LARGEST_MEM_BUCKET 25600 - #endif - #endif #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3360,4480,\ LARGEST_MEM_BUCKET - #elif defined (WOLFSSL_CERT_EXT) - /* certificate extensions requires 24k for the SSL struct */ - #ifndef LARGEST_MEM_BUCKET - #define LARGEST_MEM_BUCKET 24576 - #endif + #elif defined(WOLFSSL_CERT_EXT) #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3456,4544,\ LARGEST_MEM_BUCKET #else - /* increase 23k for object member of WOLFSSL_X509_NAME_ENTRY */ - #ifndef LARGEST_MEM_BUCKET - #define LARGEST_MEM_BUCKET 23440 - #endif #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3456,4544,\ LARGEST_MEM_BUCKET #endif #endif + #ifndef WOLFMEM_DIST #ifndef WOLFSSL_STATIC_MEMORY_SMALL #define WOLFMEM_DIST 49,10,6,14,5,6,9,1,1 @@ -190,7 +214,14 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, typedef struct wc_Memory wc_Memory; /* internal structure for mem bucket */ typedef struct WOLFSSL_HEAP { wc_Memory* ava[WOLFMEM_MAX_BUCKETS]; + #ifndef WOLFSSL_STATIC_MEMORY_LEAN wc_Memory* io; /* list of buffers to use for IO */ + #endif + + #ifdef WOLFSSL_STATIC_MEMORY_LEAN + word16 sizeList[WOLFMEM_MAX_BUCKETS];/* memory sizes in ava list */ + byte distList[WOLFMEM_MAX_BUCKETS];/* general distribution */ + #else word32 maxHa; /* max concurrent handshakes */ word32 curHa; word32 maxIO; /* max concurrent IO connections */ @@ -199,10 +230,16 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, word32 distList[WOLFMEM_MAX_BUCKETS];/* general distribution */ word32 inUse; /* amount of memory currently in use */ word32 ioUse; + #endif + + #ifndef WOLFSSL_STATIC_MEMORY_LEAN word32 alloc; /* total number of allocs */ word32 frAlc; /* total number of frees */ int flag; + #endif + #ifndef SINGLE_THREADED wolfSSL_Mutex memory_mutex; + #endif } WOLFSSL_HEAP; /* structure passed into XMALLOC as heap hint @@ -211,22 +248,41 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, typedef struct WOLFSSL_HEAP_HINT { WOLFSSL_HEAP* memory; WOLFSSL_MEM_CONN_STATS* stats; /* hold individual connection stats */ + #ifndef WOLFSSL_STATIC_MEMORY_LEAN wc_Memory* outBuf; /* set if using fixed io buffers */ wc_Memory* inBuf; byte haFlag; /* flag used for checking handshake count */ + #endif } WOLFSSL_HEAP_HINT; + WOLFSSL_API void* wolfSSL_SetGlobalHeapHint(void* heap); + WOLFSSL_API void* wolfSSL_GetGlobalHeapHint(void); + WOLFSSL_API int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint, + unsigned int listSz, const unsigned int *sizeList, + const unsigned int *distList, unsigned char* buf, unsigned int sz, + int flag, int max); +#ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK + #define WOLFSSL_DEBUG_MEMORY_ALLOC 0 + #define WOLFSSL_DEBUG_MEMORY_FAIL 1 + #define WOLFSSL_DEBUG_MEMORY_FREE 2 + #define WOLFSSL_DEBUG_MEMORY_INIT 3 + + + typedef void (*DebugMemoryCb)(size_t sz, int bucketSz, byte st, int type); + WOLFSSL_API void wolfSSL_SetDebugMemoryCb(DebugMemoryCb cb); +#endif WOLFSSL_API int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, unsigned char* buf, unsigned int sz, int flag, int max); + WOLFSSL_API void wc_UnloadStaticMemory(WOLFSSL_HEAP_HINT* heap); - WOLFSSL_LOCAL int wolfSSL_init_memory_heap(WOLFSSL_HEAP* heap); - WOLFSSL_LOCAL int wolfSSL_load_static_memory(byte* buffer, word32 sz, - int flag, WOLFSSL_HEAP* heap); - WOLFSSL_LOCAL int wolfSSL_GetMemStats(WOLFSSL_HEAP* heap, + WOLFSSL_API int wolfSSL_GetMemStats(WOLFSSL_HEAP* heap, WOLFSSL_MEM_STATS* stats); WOLFSSL_LOCAL int SetFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io); WOLFSSL_LOCAL int FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io); + WOLFSSL_API int wolfSSL_StaticBufferSz_ex(unsigned int listSz, + const unsigned int *sizeList, const unsigned int *distList, + byte* buffer, word32 sz, int flag); WOLFSSL_API int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag); WOLFSSL_API int wolfSSL_MemoryPaddingSz(void); #endif /* WOLFSSL_STATIC_MEMORY */ @@ -272,6 +328,9 @@ WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(void **CipherLifecycleTag, #ifndef WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED #define WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED 0 #endif + #ifndef CAN_SAVE_VECTOR_REGISTERS + #define CAN_SAVE_VECTOR_REGISTERS() (SAVE_VECTOR_REGISTERS2_fuzzer() == 0) + #endif #endif #ifdef DEBUG_VECTOR_REGISTER_ACCESS diff --git a/src/wolfssl/wolfcrypt/misc.h b/src/wolfssl/wolfcrypt/misc.h index 2685c6c..9761d68 100644 --- a/src/wolfssl/wolfcrypt/misc.h +++ b/src/wolfssl/wolfcrypt/misc.h @@ -135,6 +135,8 @@ WOLFSSL_LOCAL byte ctSetLTE(int a, int b); WOLFSSL_LOCAL void ctMaskCopy(byte mask, byte* dst, byte* src, word16 size); WOLFSSL_LOCAL word32 MakeWordFromHash(const byte* hashID); WOLFSSL_LOCAL word32 HashObject(const byte* o, word32 len, int* error); +WOLFSSL_LOCAL char* CopyString(const char* src, int srcLen, void* heap, + int type); WOLFSSL_LOCAL void w64Increment(w64wrapper *n); WOLFSSL_LOCAL void w64Decrement(w64wrapper *n); diff --git a/src/wolfssl/wolfcrypt/pkcs12.h b/src/wolfssl/wolfcrypt/pkcs12.h index f302354..dc06c9d 100644 --- a/src/wolfssl/wolfcrypt/pkcs12.h +++ b/src/wolfssl/wolfcrypt/pkcs12.h @@ -29,9 +29,7 @@ extern "C" { #endif -#ifndef WOLFSSL_TYPES_DEFINED /* do not redeclare from ssl.h */ - typedef struct WC_PKCS12 WC_PKCS12; -#endif +typedef struct WC_PKCS12 WC_PKCS12; typedef struct WC_DerCertList { /* dereferenced in ssl.c */ byte* buffer; @@ -47,6 +45,7 @@ enum { }; WOLFSSL_API WC_PKCS12* wc_PKCS12_new(void); +WOLFSSL_API WC_PKCS12* wc_PKCS12_new_ex(void* heap); WOLFSSL_API void wc_PKCS12_free(WC_PKCS12* pkcs12); WOLFSSL_API int wc_d2i_PKCS12(const byte* der, word32 derSz, WC_PKCS12* pkcs12); #ifndef NO_FILESYSTEM @@ -67,7 +66,7 @@ WOLFSSL_API WC_PKCS12* wc_PKCS12_create(char* pass, word32 passSz, WOLFSSL_LOCAL int wc_PKCS12_SetHeap(WC_PKCS12* pkcs12, void* heap); WOLFSSL_LOCAL void* wc_PKCS12_GetHeap(WC_PKCS12* pkcs12); -WOLFSSL_LOCAL void wc_FreeCertList(WC_DerCertList* list, void* heap); +WOLFSSL_API void wc_FreeCertList(WC_DerCertList* list, void* heap); #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/poly1305.h b/src/wolfssl/wolfcrypt/poly1305.h index c0a5b8d..cc31254 100644 --- a/src/wolfssl/wolfcrypt/poly1305.h +++ b/src/wolfssl/wolfcrypt/poly1305.h @@ -48,7 +48,14 @@ #define WC_HAS_GCC_4_4_64BIT #endif -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef WOLFSSL_X86_64_BUILD +#if defined(USE_INTEL_SPEEDUP) && !defined(NO_POLY1305_ASM) + #define USE_INTEL_POLY1305_SPEEDUP + #define HAVE_INTEL_AVX1 +#endif +#endif + +#if defined(USE_INTEL_POLY1305_SPEEDUP) #elif (defined(WC_HAS_SIZEOF_INT128_64BIT) || defined(WC_HAS_MSVC_64BIT) || \ defined(WC_HAS_GCC_4_4_64BIT)) #define POLY130564 @@ -67,7 +74,7 @@ enum { /* Poly1305 state */ typedef struct Poly1305 { -#if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) +#ifdef USE_INTEL_POLY1305_SPEEDUP word64 r[3]; word64 h[3]; word64 pad[2]; diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h new file mode 100644 index 0000000..55ff661 --- /dev/null +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h @@ -0,0 +1,229 @@ +/* esp-sdk-lib.h + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ +#ifndef __ESP_SDK_LIB_H__ + +#define __ESP_SDK_LIB_H__ + +/* Always include wolfcrypt/settings.h before any other wolfSSL file. */ +/* Reminder: settings.h pulls in user_settings.h; don't include it here. */ +#include + +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ + +/* WOLFSSL_USER_SETTINGS must be defined, typically in the CMakeLists.txt: */ +/* set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DWOLFSSL_USER_SETTINGS") */ +#ifndef WOLFSSL_USER_SETTINGS + #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targts" +#endif + +/* FreeRTOS */ +#include +#include +#include + +/* Espressif */ +#include "sdkconfig.h" /* ensure ESP-IDF settings are available everywhere */ +#include +#include + +#define ESP_SDK_MEM_LIB_VERSION 1 + +/** + ****************************************************************************** + ****************************************************************************** + ** USER APPLICATION SETTINGS BEGIN + ****************************************************************************** + ****************************************************************************** + **/ + +/* when using a private config with plain text passwords, + * file my_private_config.h should be excluded from git updates */ +/* #define USE_MY_PRIVATE_CONFIG */ + +/* Note that IntelliSense may not work properly in the next section for the + * Espressif SDK 3.4 on the ESP8266. Macros should still be defined. + * See the project-level Makefile. Example found in: + * https://github.com/wolfSSL/wolfssl/tree/master/IDE/Espressif/ESP-IDF/examples/template + * + * The USE_MY_PRIVATE_[OS]_CONFIG is typically an environment variable that + * triggers the make (not cmake) to add compiler defines. + */ +#if defined(USE_MY_PRIVATE_WINDOWS_CONFIG) + #include "/workspace/my_private_config.h" +#elif defined(USE_MY_PRIVATE_WSL_CONFIG) + #include "/mnt/c/workspace/my_private_config.h" +#elif defined(USE_MY_PRIVATE_LINUX_CONFIG) + #include "~/workspace/my_private_config.h" +#elif defined(USE_MY_PRIVATE_MAC_CONFIG) + #include "~/Documents/my_private_config.h" +#elif defined(USE_MY_PRIVATE_CONFIG) + /* This section works best with cmake & non-environment variable setting */ + #if defined(WOLFSSL_CMAKE_SYSTEM_NAME_WINDOWS) + #define WOLFSSL_CMAKE + #include "/workspace/my_private_config.h" + #elif defined(WOLFSSL_MAKE_SYSTEM_NAME_WINDOWS) + #define WOLFSSL_MAKE + #include "/workspace/my_private_config.h" + #elif defined(WOLFSSL_CMAKE_SYSTEM_NAME_WSL) + #define WOLFSSL_CMAKE + #include "/mnt/c/workspace/my_private_config.h" + #elif defined(WOLFSSL_MAKE_SYSTEM_NAME_WSL) + #define WOLFSSL_MAKE + #include "/mnt/c/workspace/my_private_config.h" + #elif defined(WOLFSSL_CMAKE_SYSTEM_NAME_LINUX) + #define WOLFSSL_CMAKE + #include "~/workspace/my_private_config.h" + #elif defined(WOLFSSL_MAKE_SYSTEM_NAME_LINUX) + #define WOLFSSL_MAKE + #include "~/workspace/my_private_config.h" + #elif defined(WOLFSSL_CMAKE_SYSTEM_NAME_APPLE) + #include "~/Documents/my_private_config.h" + #elif defined(WOLFSSL_MAKE_SYSTEM_NAME_APPLE) + #define WOLFSSL_MAKE + #include "~/Documents/my_private_config.h" + #elif defined(OS_WINDOWS) + #include "/workspace/my_private_config.h" + #else + /* Edit as needed for your private config: */ + #warning "default private config using /workspace/my_private_config.h" + #include "/workspace/my_private_config.h" + #endif +#else + + /* + ** The examples use WiFi configuration that you can set via project + ** configuration menu + ** + ** If you'd rather not, just change the below entries to strings with + ** the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" + */ + #if defined(CONFIG_ESP_WIFI_SSID) + /* tyically from ESP32 with ESP-IDF v4 ot v5 */ + #define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID + #elif defined(CONFIG_EXAMPLE_WIFI_SSID) + /* typically from ESP8266 rtos-sdk/v3.4 */ + #undef EXAMPLE_ESP_WIFI_SSID + #define EXAMPLE_ESP_WIFI_SSID CONFIG_EXAMPLE_WIFI_SSID + #else + #define EXAMPLE_ESP_WIFI_SSID "MYSSID_WIFI_CONNECT" + #endif + + #if defined(CONFIG_ESP_WIFI_PASSWORD) + /* tyically from ESP32 with ESP-IDF v4 or v5 */ + #define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD + #elif defined(CONFIG_EXAMPLE_WIFI_SSID) + /* typically from ESP8266 rtos-sdk/v3.4 */ + #undef EXAMPLE_ESP_WIFI_PASS + #define EXAMPLE_ESP_WIFI_PASS CONFIG_EXAMPLE_WIFI_PASSWORD + #else + #define EXAMPLE_ESP_WIFI_PASS "MYPASSWORD_WIFI_CONNECT" + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +WOLFSSL_LOCAL esp_err_t esp_sdk_time_mem_init(void); + +WOLFSSL_LOCAL esp_err_t sdk_var_whereis(const char* v_name, void* v); + +WOLFSSL_LOCAL intptr_t esp_sdk_stack_pointer(void); + +/****************************************************************************** +* Time helpers +******************************************************************************/ +WOLFSSL_LOCAL esp_err_t esp_sdk_time_lib_init(void); + +/* a function to show the current data and time */ +WOLFSSL_LOCAL esp_err_t esp_show_current_datetime(void); + +/* worst case, if GitHub time not available, used fixed time */ +WOLFSSL_LOCAL esp_err_t set_fixed_default_time(void); + +/* set time from string (e.g. GitHub commit time) */ +WOLFSSL_LOCAL esp_err_t set_time_from_string(const char* time_buffer); + +/* set time from NTP servers, + * also initially calls set_fixed_default_time or set_time_from_string */ +WOLFSSL_LOCAL esp_err_t set_time(void); + +/* wait NTP_RETRY_COUNT seconds before giving up on NTP time */ +WOLFSSL_LOCAL esp_err_t set_time_wait_for_ntp(void); + +#ifndef NO_ESP_SDK_WIFI + +/****************************************************************************** +* WiFi helpers +******************************************************************************/ +/* ESP lwip */ +#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY + +#define TLS_SMP_WIFI_SSID CONFIG_WIFI_SSID +#define TLS_SMP_WIFI_PASS CONFIG_WIFI_PASSWORD + +/* Optionally enable WiFi. Typically not used for wolfcrypt tests */ +/* #define USE_WIFI_EXAMPLE */ +#ifdef USE_WIFI_EXAMPLE + #include "esp_netif.h" + #if defined(CONFIG_IDF_TARGET_ESP8266) + /* TODO find and implement ESP8266 example include */ + #else + #include "protocol_examples_common.h" /* see project CMakeLists.txt */ + #endif +#endif + + +/* ESP lwip */ +#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY + +WOLFSSL_LOCAL esp_err_t esp_sdk_wifi_lib_init(void); + +WOLFSSL_LOCAL esp_err_t esp_sdk_wifi_init_sta(void); + +WOLFSSL_LOCAL esp_err_t esp_sdk_wifi_show_ip(void); + +#endif /* !NO_ESP_SDK_WIFI */ + + +/****************************************************************************** +* Debug helpers +******************************************************************************/ +WOLFSSL_LOCAL esp_err_t sdk_init_meminfo(void); +WOLFSSL_LOCAL void* wc_debug_pvPortMalloc(size_t size, + const char* file, int line, const char* fname); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* Check for traps */ +#if defined(CONFIG_IDF_TARGET_ESP8266) + #if !defined(NO_SESSION_CACHE) && \ + !defined(MICRO_SESSION_CACHE) && \ + !defined(SMALL_SESSION_CACHE) + #warning "Limited DRAM/IRAM on ESP8266. Check session cache settings" + #endif +#endif + +#endif /* WOLFSSL_ESPIDF */ + +#endif /* __ESP_SDK_LIB_H__ */ diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index 72905c9..9a33bf5 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -1,6 +1,6 @@ /* esp32-crypt.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -44,6 +44,18 @@ #include #include +#ifndef _INTPTR_T_DECLARED + #define intptr_t (void*) +#endif + +#ifndef _UINTPTR_T_DECLARED + #define uintptr_t (void*) +#endif + +#ifndef NULLPTR + #define NULLPTR ((uintptr_t)NULL) +#endif + #if ESP_IDF_VERSION_MAJOR >= 4 #define WOLFSSL_ESPIDF_BLANKLINE_MESSAGE "" #else @@ -51,13 +63,34 @@ #define WOLFSSL_ESPIDF_BLANKLINE_MESSAGE "." #endif +#if defined(WOLFSSL_STACK_CHECK) + #define CTX_STACK_CHECK(ctx) esp_sha_stack_check(ctx) +#else + #define CTX_STACK_CHECK(ctx) {} +#endif + +#if defined(CONFIG_IDF_TARGET) + #define FOUND_CONFIG_IDF_TARGET CONFIG_IDF_TARGET +#else + #define FOUND_CONFIG_IDF_TARGET "(unknown device)" +#endif + /* Optional exit message. * The WOLFSSL_COMPLETE keyword exits wolfSSL test harness script. */ #define WOLFSSL_ESPIDF_EXIT_MESSAGE \ + "\n\nDevice: " FOUND_CONFIG_IDF_TARGET \ "\n\nDone!" \ "\n\nWOLFSSL_COMPLETE" \ "\n\nIf running from idf.py monitor, press twice: Ctrl+]" +#define WOLFSSL_ESPIDF_VERBOSE_EXIT_MESSAGE(s, err) \ + "\n\nDevice: " FOUND_CONFIG_IDF_TARGET \ + "\n\nExit code: %d " \ + "\n\n"s \ + "\n\nWOLFSSL_COMPLETE" \ + "\n\nIf running from idf.py monitor, press twice: Ctrl+]", \ + (err) + /* exit codes to be used in tfm.c, sp_int.c, integer.c, etc. * * see wolfssl/wolfcrypt/error-crypt.h @@ -200,7 +233,7 @@ enum { ** Even if HW is enabled, do not run HW math tests. See HW_MATH_ENABLED. ** ** NO_ESP_MP_MUL_EVEN_ALT_CALC -** Used during Z = X × Y mod M +** Used during Z = X * Y mod M ** By default, even moduli use a two step HW esp_mp_mul with SW mp_mod. ** Enable this to instead fall back to pure software mp_mulmod. ** @@ -306,11 +339,16 @@ enum { /* #define NO_ESP32_CRYPT */ /* #define NO_WOLFSSL_ESP32_CRYPT_HASH */ - #define NO_WOLFSSL_ESP32_CRYPT_AES /* No AES HW */ - #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI /* No RSA HW*/ - #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL /* No RSA, so no mp_mul */ - #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD /* No RSA, so no mp_mulmod */ - #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD /* No RSA, no mp_exptmod */ + /* No AES HW */ + #define NO_WOLFSSL_ESP32_CRYPT_AES + /* No RSA HW: */ + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI + /* No RSA, so no mp_mul: */ + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL + /* No RSA, so no mp_mulmod: */ + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + /* No RSA, no mp_exptmod: */ + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD #include #include @@ -419,6 +457,11 @@ enum { #define NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512 /***** END CONFIG_IDF_TARGET_ESP32C6 *****/ +#elif defined(CONFIG_IDF_TARGET_ESP32H2) + /* wolfSSL Hardware Acceleration not yet implemented. Note: no WiFi. */ + #define NO_ESP32_CRYPT + /***** END CONFIG_IDF_TARGET_ESP32H2 *****/ + #elif defined(CONFIG_IDF_TARGET_ESP32S2) #include "soc/dport_reg.h" #include @@ -439,9 +482,26 @@ enum { #include #endif #define ESP_PROHIBIT_SMALL_X 0 - + /***** END CONFIG_IDF_TARGET_ESP32S3 *****/ #else - /* not yet supported. no HW */ + /* Unknown: Not yet supported. Assume no HW. */ + #define NO_ESP32_CRYPT + /***** END CONFIG_IDF_TARGET_[x] config unknown *****/ + +#endif /* CONFIG_IDF_TARGET target check */ + +#ifdef NO_ESP32_CRYPT + /* There's no hardware acceleration, so ensure everything is disabled: */ + #undef NO_WOLFSSL_ESP32_CRYPT_HASH + #define NO_WOLFSSL_ESP32_CRYPT_HASH + #undef NO_WOLFSSL_ESP32_CRYPT_AES + #define NO_WOLFSSL_ESP32_CRYPT_AES + #undef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI +#endif + +#ifdef NO_WOLFSSL_ESP32_CRYPT_HASH + /* There's no SHA hardware acceleration, so ensure all are disabled: */ #undef NO_WOLFSSL_ESP32_CRYPT_HASH_SHA #define NO_WOLFSSL_ESP32_CRYPT_HASH_SHA #undef NO_WOLFSSL_ESP32_CRYPT_HASH_SHA224 @@ -456,7 +516,15 @@ enum { #endif /* CONFIG_IDF_TARGET target check */ -#ifndef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI +#ifdef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI + /* With RSA disabled (or not available), explicitly disable each: */ + #undef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL + #undef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + #undef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD +#else #if defined(NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL) && \ defined(NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD) && \ defined(NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD) @@ -482,6 +550,19 @@ enum { #endif #endif +/* Resulting settings review for syntax highlighter review only: */ +#if defined(NO_ESP32_CRYPT) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_AES) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_RSA_PRI) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA224) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA384) || \ + defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) || \ + defined(WOLFSSL_ESP32_CRYPT_DEBUG) +#endif + #ifdef __cplusplus extern "C" { @@ -495,6 +576,10 @@ extern "C" WOLFSSL_LOCAL int esp_ShowExtendedSystemInfo(void); + WOLFSSL_LOCAL esp_err_t esp_DisableWatchdog(void); + + WOLFSSL_LOCAL esp_err_t esp_EnableWatchdog(void); + /* Compare MATH_INT_T A to MATH_INT_T B * During debug, the strings name_A and name_B can help * identify variable name. */ @@ -620,6 +705,8 @@ extern "C" #include "rom/sha.h" #define WC_ESP_SHA_TYPE SHA_TYPE #endif + #elif defined(CONFIG_IDF_TARGET_ESP8266) + /* there's no HW to include */ #else #include "rom/sha.h" #endif @@ -638,11 +725,14 @@ extern "C" typedef struct { - /* pointer to object the initialized HW; to track copies */ - void* initializer; -#if !defined(SINGLE_THREADED) || defined(ESP_MONITOR_HW_TASK_LOCK) - void* task_owner; -#endif + #if defined(WOLFSSL_STACK_CHECK) + word32 first_word; + #endif + /* Pointer to object that initialized HW, to track copies: */ + uintptr_t initializer; + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) + TaskHandle_t task_owner; + #endif /* an ESP32_MODE value; typically: ** 0 init, @@ -666,6 +756,9 @@ extern "C" /* 0 (false) this is NOT first block. ** 1 (true ) this is first block. */ byte isfirstblock : 1; /* 1 bit only for true / false */ + #if defined(WOLFSSL_STACK_CHECK) + word32 last_word; + #endif } WC_ESP32SHA; WOLFSSL_LOCAL int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx); @@ -676,20 +769,25 @@ extern "C" WOLFSSL_LOCAL int esp_sha_hw_unlock(WC_ESP32SHA* ctx); /* esp_sha_hw_islocked: returns 0 if not locked, otherwise owner address */ - WOLFSSL_LOCAL int esp_sha_hw_islocked(WC_ESP32SHA* ctx); - WOLFSSL_LOCAL int esp_sha_call_count(); - WOLFSSL_LOCAL int esp_sha_lock_count(); - WOLFSSL_LOCAL int esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx); - WOLFSSL_LOCAL int esp_sha_set_stray(WC_ESP32SHA* ctx); + WOLFSSL_LOCAL uintptr_t esp_sha_hw_islocked(WC_ESP32SHA* ctx); + + /* esp_sha_hw_in_use returns 1 (true) if SHA HW in use, otherwise 0 */ + WOLFSSL_LOCAL int esp_sha_hw_in_use(void); + WOLFSSL_LOCAL int esp_sha_call_count(void); + WOLFSSL_LOCAL int esp_sha_lock_count(void); + WOLFSSL_LOCAL uintptr_t esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx); + WOLFSSL_LOCAL uintptr_t esp_sha_set_stray(WC_ESP32SHA* ctx); +#ifndef NO_SHA struct wc_Sha; WOLFSSL_LOCAL int esp_sha_ctx_copy(struct wc_Sha* src, struct wc_Sha* dst); WOLFSSL_LOCAL int esp_sha_digest_process(struct wc_Sha* sha, byte blockprocess); WOLFSSL_LOCAL int esp_sha_process(struct wc_Sha* sha, const byte* data); +#endif /* NO_SHA */ #ifdef WOLFSSL_DEBUG_MUTEX - /* testing HW release in task that did not lock */ + /* Testing HW release in task that did not lock: */ extern WC_ESP32SHA* stray_ctx; #endif @@ -788,7 +886,7 @@ extern "C" #define WOLFSSL_HAS_METRICS /* Allow sha256 code to keep track of SW fallback during active HW */ - WOLFSSL_LOCAL int esp_sw_sha256_count_add(); + WOLFSSL_LOCAL int esp_sw_sha256_count_add(void); /* show MP HW Metrics*/ WOLFSSL_LOCAL int esp_hw_show_mp_metrics(void); @@ -800,6 +898,13 @@ extern "C" WOLFSSL_LOCAL int esp_hw_show_metrics(void); #endif + +#if defined(WOLFSSL_STACK_CHECK) + +WOLFSSL_LOCAL int esp_sha_stack_check(WC_ESP32SHA* sha); + +#endif /* WOLFSSL_STACK_CHECK */ + /* * Errata Mitigation. See * https://www.espressif.com/sites/default/files/documentation/esp32_errata_en.pdf @@ -820,8 +925,8 @@ extern "C" /* Non-FIFO read may not be needed in chip revision v3.0. */ #define ESP_EM__READ_NON_FIFO_REG {DPORT_SEQUENCE_REG_READ(0x3FF40078);} - /* When the CPU frequency is 160 MHz, add six �nop� between two consecutive - ** FIFO reads. When the CPU frequency is 240 MHz, add seven �nop� between + /* When the CPU frequency is 160 MHz, add six nops between two consecutive + ** FIFO reads. When the CPU frequency is 240 MHz, add seven nops between ** two consecutive FIFO reads. See 3.16 */ #if defined(CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80) #define ESP_EM__3_16 { \ @@ -881,16 +986,6 @@ extern "C" } #endif -/* Compatibility checks */ -#if defined(DEBUG_WOLFSSH) || defined(ESP_ENABLE_WOLFSSH) || \ - defined(WOLFSSH_TERM) || defined(WOLFSSH_TEST_SERVER) - #ifndef NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256 - /* need to add this line to wolfssl component user_settings.h - * #define NO_WOLFSSL_ESP32_CRYPT_HASH_SHA256 */ - #error "ESP32_CRYPT_HASH_SHA256 not supported on wolfSSL at this time" - #endif -#endif /* SSH SHA256 HW check */ - #endif /* WOLFSSL_ESPIDF (entire contents excluded when not Espressif ESP-IDF) */ #endif /* __ESP32_CRYPT_H__ */ diff --git a/src/wolfssl/wolfcrypt/pwdbased.h b/src/wolfssl/wolfcrypt/pwdbased.h index fb75f44..bcf0939 100644 --- a/src/wolfssl/wolfcrypt/pwdbased.h +++ b/src/wolfssl/wolfcrypt/pwdbased.h @@ -35,6 +35,10 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_pbkdf_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_PBKDF_sanity(void); +#endif /* * hashType renamed to typeH to avoid shadowing global declaration here: * wolfssl/wolfcrypt/asn.h line 173 in enum Oid_Types diff --git a/src/wolfssl/wolfcrypt/random.h b/src/wolfssl/wolfcrypt/random.h index d4ab8e3..9dd6163 100644 --- a/src/wolfssl/wolfcrypt/random.h +++ b/src/wolfssl/wolfcrypt/random.h @@ -30,8 +30,7 @@ #include -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -39,6 +38,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_drbg_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_DRBG_sanity(void); +#endif + /* Maximum generate block length */ #ifndef RNG_MAX_BLOCK_LEN #ifdef HAVE_INTEL_QA @@ -242,8 +246,8 @@ WOLFSSL_API int wc_FreeRng(WC_RNG* rng); #endif #ifdef HAVE_HASHDRBG - WOLFSSL_LOCAL int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* entropy, - word32 entropySz); + WOLFSSL_API int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* entropy, + word32 entropySz); WOLFSSL_API int wc_RNG_TestSeed(const byte* seed, word32 seedSz); WOLFSSL_API int wc_RNG_HealthTest(int reseed, const byte* entropyA, word32 entropyASz, diff --git a/src/wolfssl/wolfcrypt/rsa.h b/src/wolfssl/wolfcrypt/rsa.h index 3daa02c..f73974d 100644 --- a/src/wolfssl/wolfcrypt/rsa.h +++ b/src/wolfssl/wolfcrypt/rsa.h @@ -97,6 +97,11 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_rsa_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_RSA_sanity(void); +#endif + #ifndef RSA_MIN_SIZE #define RSA_MIN_SIZE 512 #endif @@ -136,6 +141,11 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. #endif #endif +#if FIPS_VERSION3_GE(6,0,0) + #define WC_RSA_FIPS_GEN_MIN 2048 + #define WC_RSA_FIPS_SIG_MIN (WC_RSA_FIPS_GEN_MIN/8) +#endif + enum { RSA_PUBLIC = 0, RSA_PRIVATE = 1, @@ -207,9 +217,6 @@ struct RsaKey { void* devCtx; int devId; #endif -#if defined(HAVE_PKCS11) - byte isPkcs11 : 1; /* indicate if PKCS11 is preferred */ -#endif #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #ifdef WOLFSSL_CERT_GEN @@ -235,8 +242,8 @@ struct RsaKey { char label[RSA_MAX_LABEL_LEN]; int labelLen; #endif -#if defined(WOLFSSL_ASYNC_CRYPT) || !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ - !defined(WOLFSSL_NO_MALLOC) +#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \ + (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE))) byte dataIsAlloc; #endif #ifdef WC_RSA_NONBLOCK @@ -434,19 +441,24 @@ WOLFSSL_API int wc_RsaExportKey(RsaKey* key, int nlen, int* isPrime); #endif -WOLFSSL_LOCAL int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock, - word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType, - enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, - int saltLen, int bits, void* heap); -WOLFSSL_LOCAL int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out, - byte padValue, int padType, enum wc_HashType hType, - int mgf, byte* optLabel, word32 labelLen, int saltLen, - int bits, void* heap); +WOLFSSL_API int wc_RsaPad_ex(const byte* input, word32 inputLen, + byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, + WC_RNG* rng, int padType, enum wc_HashType hType, int mgf, + byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap); +WOLFSSL_API int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, + byte** out, byte padValue, int padType, enum wc_HashType hType, int mgf, + byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap); WOLFSSL_LOCAL int wc_hash2mgf(enum wc_HashType hType); WOLFSSL_LOCAL int RsaFunctionCheckIn(const byte* in, word32 inLen, RsaKey* key, int checkSmallCt); +WOLFSSL_API int wc_RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz, + const byte* e, word32 eSz, const byte* d, word32 dSz, + const byte* u, word32 uSz, const byte* p, word32 pSz, + const byte* q, word32 qSz, const byte* dP, word32 dPSz, + const byte* dQ, word32 dQSz, RsaKey* key); + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index bc544c7..a4302c7 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -1,6 +1,6 @@ /* settings.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -265,6 +265,23 @@ /* Uncomment next line if using MAXQ108x */ /* #define WOLFSSL_MAXQ108X */ +/* Check PLATFORMIO first, as it may define other known environments. */ +#ifdef PLATFORMIO + #ifdef ESP_PLATFORM + /* Turn on the wolfSSL ESPIDF flag for the PlatformIO ESP-IDF detect */ + #define WOLFSSL_ESPIDF + #endif /* ESP_PLATFORM */ + + /* Ensure all PlatformIO boards have the wolfSSL user_setting.h enabled. */ + #ifndef WOLFSSL_USER_SETTINGS + #define WOLFSSL_USER_SETTINGS + #endif /* WOLFSSL_USER_SETTINGS */ + + /* Similar to Arduino we have limited build control, so suppress warning */ + #undef WOLFSSL_IGNORE_FILE_WARN + #define WOLFSSL_IGNORE_FILE_WARN +#endif + #if defined(ARDUINO) /* Due to limited build control, we'll ignore file warnings. */ /* See https://github.com/arduino/arduino-cli/issues/631 */ @@ -306,22 +323,61 @@ #include -#define WOLFSSL_MAKE_FIPS_VERSION(major, minor) (((major) * 256) + (minor)) +/*------------------------------------------------------------*/ +#define WOLFSSL_MAKE_FIPS_VERSION3(major, minor, patch) \ + (((major) * 65536) + ((minor) * 256) + (patch)) +#define WOLFSSL_MAKE_FIPS_VERSION(major, minor) \ + WOLFSSL_MAKE_FIPS_VERSION3(major, minor, 0) + #if !defined(HAVE_FIPS) - #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION(0,0) + #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION3(0,0,0) + #define WOLFSSL_FIPS_VERSION2_CODE WOLFSSL_FIPS_VERSION_CODE #elif !defined(HAVE_FIPS_VERSION) - #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION(1,0) + #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION3(1,0,0) + #define WOLFSSL_FIPS_VERSION2_CODE WOLFSSL_FIPS_VERSION_CODE #elif !defined(HAVE_FIPS_VERSION_MINOR) - #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION(HAVE_FIPS_VERSION,0) + #define WOLFSSL_FIPS_VERSION_CODE \ + WOLFSSL_MAKE_FIPS_VERSION3(HAVE_FIPS_VERSION,0,0) + #define WOLFSSL_FIPS_VERSION2_CODE WOLFSSL_FIPS_VERSION_CODE +#elif !defined(HAVE_FIPS_VERSION_PATCH) + #define WOLFSSL_FIPS_VERSION_CODE \ + WOLFSSL_MAKE_FIPS_VERSION3(HAVE_FIPS_VERSION, \ + HAVE_FIPS_VERSION_MINOR, 0) + #define WOLFSSL_FIPS_VERSION2_CODE WOLFSSL_FIPS_VERSION_CODE #else - #define WOLFSSL_FIPS_VERSION_CODE WOLFSSL_MAKE_FIPS_VERSION(HAVE_FIPS_VERSION,HAVE_FIPS_VERSION_MINOR) -#endif + #define WOLFSSL_FIPS_VERSION_CODE \ + WOLFSSL_MAKE_FIPS_VERSION3(HAVE_FIPS_VERSION,\ + HAVE_FIPS_VERSION_MINOR, \ + HAVE_FIPS_VERSION_PATCH) + #define WOLFSSL_FIPS_VERSION2_CODE \ + WOLFSSL_MAKE_FIPS_VERSION3(HAVE_FIPS_VERSION,\ + HAVE_FIPS_VERSION_MINOR, \ + 0) +#endif + +#define FIPS_VERSION_LT(major,minor) \ + (WOLFSSL_FIPS_VERSION2_CODE < WOLFSSL_MAKE_FIPS_VERSION(major,minor)) +#define FIPS_VERSION_LE(major,minor) \ + (WOLFSSL_FIPS_VERSION2_CODE <= WOLFSSL_MAKE_FIPS_VERSION(major,minor)) +#define FIPS_VERSION_EQ(major,minor) \ + (WOLFSSL_FIPS_VERSION2_CODE == WOLFSSL_MAKE_FIPS_VERSION(major,minor)) +#define FIPS_VERSION_GE(major,minor) \ + (WOLFSSL_FIPS_VERSION2_CODE >= WOLFSSL_MAKE_FIPS_VERSION(major,minor)) +#define FIPS_VERSION_GT(major,minor) \ + (WOLFSSL_FIPS_VERSION2_CODE > WOLFSSL_MAKE_FIPS_VERSION(major,minor)) + +#define FIPS_VERSION3_LT(major,minor,patch) \ + (WOLFSSL_FIPS_VERSION_CODE < WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch)) +#define FIPS_VERSION3_LE(major,minor,patch) \ + (WOLFSSL_FIPS_VERSION_CODE <= WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch)) +#define FIPS_VERSION3_EQ(major,minor,patch) \ + (WOLFSSL_FIPS_VERSION_CODE == WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch)) +#define FIPS_VERSION3_GE(major,minor,patch) \ + (WOLFSSL_FIPS_VERSION_CODE >= WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch)) +#define FIPS_VERSION3_GT(major,minor,patch) \ + (WOLFSSL_FIPS_VERSION_CODE > WOLFSSL_MAKE_FIPS_VERSION3(major,minor,patch)) +/*------------------------------------------------------------*/ -#define FIPS_VERSION_LT(major,minor) (WOLFSSL_FIPS_VERSION_CODE < WOLFSSL_MAKE_FIPS_VERSION(major,minor)) -#define FIPS_VERSION_LE(major,minor) (WOLFSSL_FIPS_VERSION_CODE <= WOLFSSL_MAKE_FIPS_VERSION(major,minor)) -#define FIPS_VERSION_EQ(major,minor) (WOLFSSL_FIPS_VERSION_CODE == WOLFSSL_MAKE_FIPS_VERSION(major,minor)) -#define FIPS_VERSION_GE(major,minor) (WOLFSSL_FIPS_VERSION_CODE >= WOLFSSL_MAKE_FIPS_VERSION(major,minor)) -#define FIPS_VERSION_GT(major,minor) (WOLFSSL_FIPS_VERSION_CODE > WOLFSSL_MAKE_FIPS_VERSION(major,minor)) /* make sure old RNG name is used with CTaoCrypt FIPS */ #ifdef HAVE_FIPS @@ -332,7 +388,7 @@ * system or other set of headers included by wolfSSL already defines * RNG. Examples are: * wolfEngine, wolfProvider and potentially other use-cases */ - #ifndef RNG + #if !defined(RNG) && !defined(NO_OLD_RNGNAME) #define RNG WC_RNG #endif #endif @@ -452,6 +508,9 @@ /* WC_RSA_BLINDING takes up extra space! */ #define WC_RSA_BLINDING + + /* Cache Resistant features are on by default, but has performance + * penalty on embedded systems. May not be needed here. Disabled: */ #define WC_NO_CACHE_RESISTANT #endif /* !WOLFSSL_ESPIDF_NO_DEFAULT */ @@ -977,7 +1036,7 @@ extern void uITRON4_free(void *p) ; #if defined(WOLFSSL_LEANPSK) && !defined(XMALLOC_USER) && \ - !defined(NO_WOLFSSL_MEMORY) + !defined(NO_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) #include #define XMALLOC(s, h, type) ((void)(h), (void)(type), malloc((s))) #define XFREE(p, h, type) ((void)(h), (void)(type), free((p))) @@ -995,22 +1054,45 @@ extern void uITRON4_free(void *p) ; #ifdef FREERTOS - #include "FreeRTOS.h" - #include + + #ifdef PLATFORMIO + #include + #include + #else + #include "FreeRTOS.h" + #include + #endif #if !defined(XMALLOC_USER) && !defined(NO_WOLFSSL_MEMORY) && \ !defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_TRACK_MEMORY) - #define XMALLOC(s, h, type) ((void)(h), (void)(type), pvPortMalloc((s))) + + /* XMALLOC */ + #if defined(WOLFSSL_ESPIDF) && \ + (defined(DEBUG_WOLFSSL) || defined(DEBUG_WOLFSSL_MALLOC)) + #include + #define XMALLOC(s, h, type) \ + ((void)(h), (void)(type), wc_debug_pvPortMalloc( \ + (s), (__FILE__), (__LINE__), (__FUNCTION__) )) + #else + #define XMALLOC(s, h, type) \ + ((void)(h), (void)(type), pvPortMalloc((s))) + #endif + + /* XFREE */ #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) + + /* XREALLOC */ #if defined(WOLFSSL_ESPIDF) - /* In IDF, realloc(p, n) is equivalent to - * heap_caps_realloc(p, s, MALLOC_CAP_8BIT) - * there's no pvPortRealloc available */ - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) - /* FreeRTOS pvPortRealloc() implementation can be found here: - * https://github.com/wolfSSL/wolfssl-freertos/pull/3/files */ + /* In the Espressif EDP-IDF, realloc(p, n) is equivalent to + * heap_caps_realloc(p, s, MALLOC_CAP_8BIT) + * There's no pvPortRealloc available: */ + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) #elif defined(USE_INTEGER_HEAP_MATH) || defined(OPENSSL_EXTRA) - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), pvPortRealloc((p), (n))) + /* FreeRTOS pvPortRealloc() implementation can be found here: + * https://github.com/wolfSSL/wolfssl-freertos/pull/3/files */ + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), pvPortRealloc((p), (n))) + #else + /* no XREALLOC available */ #endif #endif @@ -1034,7 +1116,11 @@ extern void uITRON4_free(void *p) ; #endif #ifndef SINGLE_THREADED - #include "semphr.h" + #ifdef PLATFORMIO + #include + #else + #include "semphr.h" + #endif #endif #endif @@ -1241,8 +1327,10 @@ extern void uITRON4_free(void *p) ; /* Copy data out of flash memory and into SRAM */ #define XMEMCPY_P(pdest, psrc, size) memcpy_P((pdest), (psrc), (size)) #else +#ifndef FLASH_QUALIFIER #define FLASH_QUALIFIER #endif +#endif #ifdef FREESCALE_MQX_5_0 /* use normal Freescale MQX port, but with minor changes for 5.0 */ @@ -2000,14 +2088,22 @@ extern void uITRON4_free(void *p) ; #endif /*(WOLFSSL_APACHE_MYNEWT)*/ #ifdef WOLFSSL_ZEPHYR + #include +#if KERNEL_VERSION_NUMBER >= 0x30100 #include #include #include +#else + #include + #include + #include +#endif #include #define WOLFSSL_DH_CONST #define WOLFSSL_HAVE_MAX #define NO_WRITEV + #define NO_STDLIB_ISASCII #define USE_FLAT_BENCHMARK_H #define USE_FLAT_TEST_H @@ -2692,7 +2788,9 @@ extern void uITRON4_free(void *p) ; #endif /* Enable ECC_CACHE_CURVE for ASYNC */ - #if !defined(ECC_CACHE_CURVE) + #if !defined(ECC_CACHE_CURVE) && !defined(NO_ECC_CACHE_CURVE) + /* Enabled by default for increased async performance, + * but not required */ #define ECC_CACHE_CURVE #endif #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -2719,9 +2817,6 @@ extern void uITRON4_free(void *p) ; !defined(WOLFSSL_SP_MATH) && !defined(NO_BIG_INT) #error The static memory option is only supported for fast math or SP Math #endif - #ifdef WOLFSSL_SMALL_STACK - #error static memory does not support small stack please undefine - #endif #endif /* WOLFSSL_STATIC_MEMORY */ #ifdef HAVE_AES_KEYWRAP @@ -2833,6 +2928,9 @@ extern void uITRON4_free(void *p) ; #ifndef WOLFSSL_SP_DIV_WORD_HALF #define WOLFSSL_SP_DIV_WORD_HALF #endif + #ifdef __PIE__ + #define WC_NO_INTERNAL_FUNCTION_POINTERS + #endif #endif @@ -2865,6 +2963,9 @@ extern void uITRON4_free(void *p) ; #ifndef HAVE_SNI #define HAVE_SNI #endif + #ifndef WOLFSSL_RSA_KEY_CHECK + #define WOLFSSL_RSA_KEY_CHECK + #endif #endif /* Make sure setting OPENSSL_ALL also sets OPENSSL_EXTRA. */ @@ -3159,8 +3260,10 @@ extern void uITRON4_free(void *p) ; /* Do not allow using small stack with no malloc */ #if defined(WOLFSSL_NO_MALLOC) && \ - (defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) - #error Small stack cannot be used with no malloc (WOLFSSL_NO_MALLOC) + (defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ + !defined(WOLFSSL_STATIC_MEMORY) + #error Small stack cannot be used with no malloc (WOLFSSL_NO_MALLOC) and \ + without staticmemory (WOLFSSL_STATIC_MEMORY) #endif /* If malloc is disabled make sure it is also disabled in SP math */ @@ -3194,6 +3297,13 @@ extern void uITRON4_free(void *p) ; #define HAVE_ONE_TIME_AUTH #endif +/* This is checked for in configure.ac, so might want to do it in here as well. + */ +#if defined(HAVE_SECURE_RENEGOTIATION) && defined(HAVE_RENEGOTIATION_INDICATION) + #error HAVE_RENEGOTIATION_INDICATION cannot be defined together with \ + HAVE_SECURE_RENEGOTIATION +#endif + /* Check for insecure build combination: * secure renegotiation [enabled] * extended master secret [disabled] @@ -3242,7 +3352,9 @@ extern void uITRON4_free(void *p) ; #ifdef HAVE_LIBOQS #define HAVE_PQC #define HAVE_FALCON -#define HAVE_DILITHIUM +#ifndef HAVE_DILITHIUM + #define HAVE_DILITHIUM +#endif #ifndef WOLFSSL_NO_SPHINCS #define HAVE_SPHINCS #endif @@ -3264,6 +3376,7 @@ extern void uITRON4_free(void *p) ; #if (defined(HAVE_LIBOQS) || \ defined(WOLFSSL_WC_KYBER) || \ + defined(WOLFSSL_WC_DILITHIUM) || \ defined(HAVE_LIBXMSS) || \ defined(HAVE_LIBLMS) || \ defined(WOLFSSL_DUAL_ALG_CERTS)) && \ @@ -3294,6 +3407,11 @@ extern void uITRON4_free(void *p) ; #error The SRTP extension requires DTLS #endif +/* FIPS v5 and older doesn't support WOLF_PRIVATE_KEY_ID with PK callbacks */ +#if defined(HAVE_FIPS) && FIPS_VERSION_LT(5,3) && defined(HAVE_PK_CALLBACKS) + #define NO_WOLF_PRIVATE_KEY_ID +#endif + /* Are we using an external private key store like: * PKCS11 / HSM / crypto callback / PK callback */ #if !defined(WOLF_PRIVATE_KEY_ID) && !defined(NO_WOLF_PRIVATE_KEY_ID) && \ @@ -3312,11 +3430,19 @@ extern void uITRON4_free(void *p) ; /* (D)TLS v1.3 requires 64-bit number wrappers as does XMSS and LMS. */ #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS_DROP_STATS) || \ - defined(WOLFSSL_WC_XMSS) || defined(WOLFSSL_WC_LMS) + (defined(WOLFSSL_WC_XMSS) && (!defined(WOLFSSL_XMSS_MAX_HEIGHT) || \ + WOLFSSL_XMSS_MAX_HEIGHT > 32)) || (defined(WOLFSSL_WC_LMS) && \ + !defined(WOLFSSL_LMS_VERIFY_ONLY)) #undef WOLFSSL_W64_WRAPPER #define WOLFSSL_W64_WRAPPER #endif +/* wc_xmss and wc_lms require these misc.c functions. */ +#if defined(WOLFSSL_WC_XMSS) || defined(WOLFSSL_WC_LMS) + #undef WOLFSSL_NO_INT_ENCODE + #undef WOLFSSL_NO_INT_DECODE +#endif + /* DTLS v1.3 requires AES ECB if using AES */ #if defined(WOLFSSL_DTLS13) && !defined(NO_AES) && \ !defined(WOLFSSL_AES_DIRECT) @@ -3434,10 +3560,32 @@ extern void uITRON4_free(void *p) ; #endif /* Some final sanity checks */ +#ifdef WOLFSSL_APPLE_HOMEKIT + #ifndef WOLFCRYPT_HAVE_SRP + #error "WOLFCRYPT_HAVE_SRP is required for Apple Homekit" + #endif + #ifndef HAVE_CHACHA + #error "HAVE_CHACHA is required for Apple Homekit" + #endif + #ifdef USE_FAST_MATH + #ifdef FP_MAX_BITS + #if FP_MAX_BITS < (8192 * 2) + #error "HomeKit FP_MAX_BITS must at least (8192 * 2)" + #endif + #else + #error "HomeKit FP_MAX_BITS must be assigned a value (8192 * 2)" + #endif + #endif +#endif + #if defined(WOLFSSL_ESPIDF) && defined(ARDUINO) #error "Found both ESPIDF and ARDUINO. Pick one." #endif +#if defined(HAVE_FIPS) && defined(HAVE_PKCS11) + #error "PKCS11 not allowed with FIPS enabled (Crypto outside boundary)" +#endif + #if defined(WOLFSSL_CAAM_BLOB) #ifndef WOLFSSL_CAAM #error "WOLFSSL_CAAM_BLOB requires WOLFSSL_CAAM" @@ -3450,6 +3598,29 @@ extern void uITRON4_free(void *p) ; #endif #endif +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ + defined(OPENSSL_COEXIST) + #error "OPENSSL_EXTRA can not be defined with OPENSSL_COEXIST" +#endif + +#if !defined(NO_DSA) && defined(NO_SHA) + #error "Please disable DSA if disabling SHA-1" +#endif + +/* if configure.ac turned on this feature, HAVE_ENTROPY_MEMUSE will be set, + * also define HAVE_WOLFENTROPY */ +#ifdef HAVE_ENTROPY_MEMUSE + #ifndef HAVE_WOLFENTROPY + #define HAVE_WOLFENTROPY + #endif +#elif defined(HAVE_WOLFENTROPY) + /* else if user_settings.h only defined HAVE_WOLFENTROPY + * also define HAVE_ENTROPY_MEMUSE */ + #ifndef HAVE_ENTROPY_MEMUSE + #define HAVE_ENTROPY_MEMUSE + #endif +#endif /* HAVE_ENTROPY_MEMUSE */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/sha.h b/src/wolfssl/wolfcrypt/sha.h index e8bcc9b..eb599ab 100644 --- a/src/wolfssl/wolfcrypt/sha.h +++ b/src/wolfssl/wolfcrypt/sha.h @@ -31,8 +31,7 @@ #ifndef NO_SHA -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -53,6 +52,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_sha_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_SHA_sanity(void); +#endif + /* avoid redefinition of structs */ #if !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) diff --git a/src/wolfssl/wolfcrypt/sha256.h b/src/wolfssl/wolfcrypt/sha256.h index 323c53a..a6c4ea4 100644 --- a/src/wolfssl/wolfcrypt/sha256.h +++ b/src/wolfssl/wolfcrypt/sha256.h @@ -32,8 +32,7 @@ #ifndef NO_SHA256 -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -61,6 +60,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_sha256_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_SHA256_sanity(void); +#endif + /* avoid redefinition of structs */ #if !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) @@ -175,13 +179,23 @@ struct wc_Sha256 { #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_HASH) psa_hash_operation_t psa_ctx; #else +#ifdef WC_64BIT_CPU /* alignment on digest and buffer speeds up ARMv8 crypto operations */ ALIGN16 word32 digest[WC_SHA256_DIGEST_SIZE / sizeof(word32)]; ALIGN16 word32 buffer[WC_SHA256_BLOCK_SIZE / sizeof(word32)]; +#else + word32 digest[WC_SHA256_DIGEST_SIZE / sizeof(word32)]; + word32 buffer[WC_SHA256_BLOCK_SIZE / sizeof(word32)]; +#endif word32 buffLen; /* in bytes */ word32 loLen; /* length in bytes */ word32 hiLen; /* length in bytes */ void* heap; + +#ifdef WC_C_DYNAMIC_FALLBACK + int sha_method; +#endif + #endif #ifdef WOLFSSL_PIC32MZ_HASH hashUpdCache cache; /* cache for updates */ diff --git a/src/wolfssl/wolfcrypt/sha3.h b/src/wolfssl/wolfcrypt/sha3.h index 2b9283a..e1ce33a 100644 --- a/src/wolfssl/wolfcrypt/sha3.h +++ b/src/wolfssl/wolfcrypt/sha3.h @@ -36,6 +36,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_sha3_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_SHA3_sanity(void); +#endif + #ifdef WOLFSSL_ASYNC_CRYPT #include #endif @@ -119,6 +124,16 @@ struct wc_Sha3 { void* heap; +#ifdef WOLF_CRYPTO_CB + int devId; +#endif + +#ifdef WC_C_DYNAMIC_FALLBACK + void (*sha3_block)(word64 *s); + void (*sha3_block_n)(word64 *s, const byte* data, word32 n, + word64 c); +#endif + #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -135,7 +150,10 @@ struct wc_Sha3 { #endif #if defined(WOLFSSL_SHAKE128) || defined(WOLFSSL_SHAKE256) -typedef wc_Sha3 wc_Shake; + #ifndef WC_SHAKE_TYPE_DEFINED + typedef wc_Sha3 wc_Shake; + #define WC_SHAKE_TYPE_DEFINED + #endif #endif WOLFSSL_API int wc_InitSha3_224(wc_Sha3* sha3, void* heap, int devId); @@ -202,7 +220,8 @@ WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); WOLFSSL_LOCAL void sha3_block_avx2(word64* s); WOLFSSL_LOCAL void BlockSha3(word64 *s); #endif -#if defined(WOLFSSL_ARMASM) && defined(WOLFSSL_ARMASM_CRYPTO_SHA3) +#if defined(WOLFSSL_ARMASM) && (defined(__arm__) || \ + defined(WOLFSSL_ARMASM_CRYPTO_SHA3)) WOLFSSL_LOCAL void BlockSha3(word64 *s); #endif diff --git a/src/wolfssl/wolfcrypt/sha512.h b/src/wolfssl/wolfcrypt/sha512.h index 7592c46..bf3cff6 100644 --- a/src/wolfssl/wolfcrypt/sha512.h +++ b/src/wolfssl/wolfcrypt/sha512.h @@ -32,8 +32,7 @@ #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) -#if defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) +#if FIPS_VERSION3_GE(2,0,0) #include #endif /* HAVE_FIPS_VERSION >= 2 */ @@ -41,6 +40,11 @@ extern "C" { #endif +#if FIPS_VERSION3_GE(6,0,0) + extern const unsigned int wolfCrypt_FIPS_sha512_ro_sanity[2]; + WOLFSSL_LOCAL int wolfCrypt_FIPS_SHA512_sanity(void); +#endif + /* avoid redefinition of structs */ #if !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) @@ -147,15 +151,20 @@ struct wc_Sha512 { #ifdef USE_INTEL_SPEEDUP const byte* data; #endif +#ifdef WC_C_DYNAMIC_FALLBACK + int sha_method; +#endif #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_SMALL_STACK_CACHE word64* W; #endif + #if defined(WOLFSSL_ESP32_CRYPT) && \ !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) && \ - !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) + (!defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA512) || \ + !defined(NO_WOLFSSL_ESP32_CRYPT_HASH_SHA384)) WC_ESP32SHA ctx; #endif #if defined(WOLFSSL_SILABS_SE_ACCEL) diff --git a/src/wolfssl/wolfcrypt/sp_int.h b/src/wolfssl/wolfcrypt/sp_int.h index cf7b8f2..ba16895 100644 --- a/src/wolfssl/wolfcrypt/sp_int.h +++ b/src/wolfssl/wolfcrypt/sp_int.h @@ -695,9 +695,11 @@ typedef struct sp_ecc_ctx { #define sp_clamp(a) \ do { \ int ii; \ - for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + if ((a)->used > 0) { \ + for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + } \ + (a)->used = (unsigned int)ii + 1; \ } \ - (a)->used = (unsigned int)ii + 1; \ } while (0) /* Check the compiled and linked math implementation are the same. @@ -996,6 +998,9 @@ MP_API int sp_submod_ct(const sp_int* a, const sp_int* b, const sp_int* m, MP_API int sp_addmod_ct(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r); #endif +#if defined(WOLFSSL_SP_MATH_ALL) && defined(HAVE_ECC) +MP_API void sp_xor_ct(const sp_int* a, const sp_int* b, int len, sp_int* r); +#endif MP_API int sp_lshd(sp_int* a, int s); #ifdef WOLFSSL_SP_MATH_ALL @@ -1144,6 +1149,7 @@ WOLFSSL_LOCAL void sp_memzero_check(sp_int* sp); #define mp_submod sp_submod #define mp_addmod_ct sp_addmod_ct #define mp_submod_ct sp_submod_ct +#define mp_xor_ct sp_xor_ct #define mp_lshd sp_lshd #define mp_rshd sp_rshd #define mp_div sp_div diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index 01ed929..9dd2f75 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -303,7 +303,8 @@ typedef struct w64wrapper { #ifndef WARN_UNUSED_RESULT #if defined(WOLFSSL_LINUXKM) && defined(__must_check) #define WARN_UNUSED_RESULT __must_check - #elif defined(__GNUC__) && (__GNUC__ >= 4) + #elif (defined(__GNUC__) && (__GNUC__ >= 4)) || \ + (defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001)) #define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else #define WARN_UNUSED_RESULT @@ -311,7 +312,7 @@ typedef struct w64wrapper { #endif /* WARN_UNUSED_RESULT */ #ifndef WC_MAYBE_UNUSED - #if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) + #if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) #define WC_MAYBE_UNUSED __attribute__((unused)) #else #define WC_MAYBE_UNUSED @@ -430,6 +431,9 @@ typedef struct w64wrapper { #define XELEM_CNT(x) (sizeof((x))/sizeof(*(x))) + #define WC_SAFE_SUM_WORD32(in1, in2, out) ((in2) <= 0xffffffffU - (in1) ? \ + ((out) = (in1) + (in2), 1) : ((out) = 0xffffffffU, 0)) + /* idea to add global alloc override by Moises Guimaraes */ /* default to libc stuff */ /* XREALLOC is used once in normal math lib, not in fast math lib */ @@ -589,7 +593,7 @@ typedef struct w64wrapper { #endif #define WC_DECLARE_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - VAR_TYPE* VAR_NAME[VAR_ITEMS]; \ + VAR_TYPE* VAR_NAME[VAR_ITEMS] = { NULL, }; \ int idx##VAR_NAME = 0, inner_idx_##VAR_NAME #define WC_HEAP_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ VAR_TYPE* VAR_NAME[VAR_ITEMS] @@ -766,7 +770,7 @@ typedef struct w64wrapper { defined(WOLFSSL_ZEPHYR) || defined(MICROCHIP_PIC24) /* XC32 version < 1.0 does not support strncasecmp. */ #define USE_WOLF_STRNCASECMP - #define XSTRNCASECMP(s1,s2) wc_strncasecmp(s1,s2) + #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp((s1),(s2),(n)) #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) #define XSTRNCASECMP(s1,s2,n) _strnicmp((s1),(s2),(n)) #else @@ -820,6 +824,10 @@ typedef struct w64wrapper { return ret; } #define XSNPRINTF _xsnprintf_ + #elif defined(FREESCALE_MQX) + /* see wc_port.h for fio.h and nio.h includes. MQX does not + have stdio.h available, so it needs its own section. */ + #define XSNPRINTF snprintf #elif defined(WOLF_C89) #include #define XSPRINTF sprintf @@ -1208,14 +1216,14 @@ typedef struct w64wrapper { WC_PK_TYPE_CURVE25519_KEYGEN = 16, WC_PK_TYPE_RSA_GET_SIZE = 17, #define _WC_PK_TYPE_MAX WC_PK_TYPE_RSA_GET_SIZE - #if defined(HAVE_PQC) && defined(WOLFSSL_HAVE_KYBER) + #if defined(WOLFSSL_HAVE_KYBER) WC_PK_TYPE_PQC_KEM_KEYGEN = 18, WC_PK_TYPE_PQC_KEM_ENCAPS = 19, WC_PK_TYPE_PQC_KEM_DECAPS = 20, #undef _WC_PK_TYPE_MAX #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_KEM_DECAPS #endif - #if defined(HAVE_PQC) && (defined(HAVE_DILITHIUM) || defined(HAVE_FALCON)) + #if defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) WC_PK_TYPE_PQC_SIG_KEYGEN = 21, WC_PK_TYPE_PQC_SIG_SIGN = 22, WC_PK_TYPE_PQC_SIG_VERIFY = 23, @@ -1226,7 +1234,7 @@ typedef struct w64wrapper { WC_PK_TYPE_MAX = _WC_PK_TYPE_MAX }; - #if defined(HAVE_PQC) +#if defined(WOLFSSL_HAVE_KYBER) /* Post quantum KEM algorithms */ enum wc_PqcKemType { WC_PQC_KEM_TYPE_NONE = 0, @@ -1238,7 +1246,9 @@ typedef struct w64wrapper { #endif WC_PQC_KEM_TYPE_MAX = _WC_PQC_KEM_TYPE_MAX }; +#endif +#if defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) /* Post quantum signature algorithms */ enum wc_PqcSignatureType { WC_PQC_SIG_TYPE_NONE = 0, @@ -1255,7 +1265,7 @@ typedef struct w64wrapper { #endif WC_PQC_SIG_TYPE_MAX = _WC_PQC_SIG_TYPE_MAX }; - #endif +#endif /* settings detection for compile vs runtime math incompatibilities */ enum { @@ -1397,6 +1407,20 @@ typedef struct w64wrapper { #endif typedef void* THREAD_TYPE; #define WOLFSSL_THREAD + #elif defined(WOLFSSL_USER_THREADING) + /* User can define user specific threading types + * THREAD_RETURN + * TREAD_TYPE + * WOLFSSL_THREAD + * e.g. + * typedef unsigned int THREAD_RETURN; + * typedef size_t THREAD_TYPE; + * #define WOLFSSL_THREAD void + * + * User can also implement their own wolfSSL_NewThread(), + * wolfSSL_JoinThread() and wolfSSL_Cond signaling if they want. + * Otherwise, those functions are omitted. + */ #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) || \ defined(FREESCALE_MQX) typedef unsigned int THREAD_RETURN; @@ -1419,6 +1443,7 @@ typedef struct w64wrapper { k_thread_stack_t* threadStack; } THREAD_TYPE; #define WOLFSSL_THREAD + extern void* wolfsslThreadHeapHint; #elif defined(NETOS) typedef UINT THREAD_RETURN; typedef struct { @@ -1633,6 +1658,9 @@ typedef struct w64wrapper { #ifndef SAVE_VECTOR_REGISTERS2 #define SAVE_VECTOR_REGISTERS2() 0 #endif + #ifndef CAN_SAVE_VECTOR_REGISTERS + #define CAN_SAVE_VECTOR_REGISTERS() 1 + #endif #ifndef WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL #define WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL(x) WC_DO_NOTHING #endif diff --git a/src/wolfssl/wolfcrypt/wc_kyber.h b/src/wolfssl/wolfcrypt/wc_kyber.h index 61fe8b2..5491285 100644 --- a/src/wolfssl/wolfcrypt/wc_kyber.h +++ b/src/wolfssl/wolfcrypt/wc_kyber.h @@ -34,7 +34,9 @@ #ifdef WOLFSSL_HAVE_KYBER -#if defined(_MSC_VER) +#ifdef noinline + #define KYBER_NOINLINE noinline +#elif defined(_MSC_VER) #define KYBER_NOINLINE __declspec(noinline) #elif defined(__GNUC__) #define KYBER_NOINLINE __attribute__((noinline)) diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index f51dad7..6f90eaa 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -19,5 +19,452 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#error "Contact wolfSSL to get the implementation of this file" +/* Implementation based on: + * RFC 8554: Leighton-Micali Hash-Based Signatures + * https://datatracker.ietf.org/doc/html/rfc8554 + * Implementation by Sean Parkinson. + */ + +/* Possible LMS options: + * + * WOLFSSL_LMS_LARGE_CACHES Default: OFF + * Authentication path caches are large and signing faster. + * WOLFSSL_LMS_ROOT_LEVELS Default: 5 (Large: 7) + * Number of levels of interior nodes from the to to cached. + * Valid value are: 1..height of subtree. + * The bigger the number, the larger the LmsKey but faster signing. + * Only applies when !WOLFSSL_WC_LMS_SMALL. + * WOLFSSL_LMS_CACHE_BITS Default: 5 (Large: 7) + * 2 to the power of the value is the number of leaf nodes to cache. + * Maximum valid value is height of subtree. + * Valid value are: 0..height of subtree. + * The bigger the number, the larger the LmsKey but faster signing. + * Only applies when !WOLFSSL_WC_LMS_SMALL. + * + * Memory/Level | R/C | Approx. Time (% of 5/5) + * (Bytes) | | H=10 | H=15 | H=20 + * -------------+--------------+--------+-------- + * 2016 | 5/5 | 100.0% | 100.0% | 100.0% + * 3040 | 5/6 | 75.5% | 89.2% | + * 4064 | 6/6 | 75.3% | 78.8% | + * 4576 | 4/7 | 72.4% | 87.6% | + * 6112 | 6/7 | 72.1% | 67.5% | + * 8160 | 7/7 | 72.2% | 56.8% | + * 8416 | 3/8 | 66.4% | 84.9% | + * 12256 | 7/8 | 66.5% | 45.9% | + * 16352 | 8/8 | 66.0% | 35.0% | + * 16416 | 1/9 | 54.1% | 79.5% | + * R = Root levels + * C = Cache bits + * To mimic the dynamic memory usage of XMSS, use 3/3. + * + * WOLFSSL_LMS_NO_SIGN SMOOTHING Default: OFF + * Disable precalculation of next subtree. + * Use less dynamic memory. + * At certain indexes, signing will take a long time compared to the mean. + * When OFF, the private key holds a second copy of caches. + * + * WOLFSSL_LMS_NO_SIG_CACHE Default: OFF + * Signature cache is disabled. + * This will use less dynamic memory and make signing slower when multiple + * levels. + * + * Sig cache holds the C and y hashes for a tree that is not the lowest. + * Sig cache size = (levels - 1) * (1 + p) * 32 bytes + * p is the number of y terms based on Winternitz width. + * + * w | p | l | Bytes + * ---+----+---+------ + * 4 | 67 | 2 | 2176 + * 4 | 67 | 3 | 4353 + * 4 | 67 | 4 | 6528 + * 8 | 34 | 2 | 1120 + * 8 | 34 | 3 | 2240 + * 8 | 34 | 4 | 3360 + * w = Winternitz width + * l = #levels + */ + +#ifndef WC_LMS_H +#define WC_LMS_H + +#if defined(WOLFSSL_HAVE_LMS) && defined(WOLFSSL_WC_LMS) + +#include +#include + +#ifdef WOLFSSL_LMS_MAX_LEVELS + /* Maximum number of levels of trees supported by implementation. */ + #define LMS_MAX_LEVELS WOLFSSL_LMS_MAX_LEVELS +#else + /* Maximum number of levels of trees supported by implementation. */ + #define LMS_MAX_LEVELS 4 +#endif +#if (LMS_MAX_LEVELS < 1) || (LMS_MAX_LEVELS > 4) + #error "LMS parameters only support heights 1-4." +#endif + +/* Smoothing is only used when there are 2 or more levels. */ +#if LMS_MAX_LEVELS == 1 && !defined(WOLFSSL_LMS_NO_SIGN_SMOOTHING) + #define WOLFSSL_LMS_NO_SIGN_SMOOTHING +#endif + +#ifdef WOLFSSL_LMS_MAX_HEIGHT + /* Maximum height of a tree supported by implementation. */ + #define LMS_MAX_HEIGHT WOLFSSL_LMS_MAX_HEIGHT +#else + /* Maximum height of a tree supported by implementation. */ + #define LMS_MAX_HEIGHT 20 +#endif +#if (LMS_MAX_HEIGHT < 5) || (LMS_MAX_HEIGHT > 20) + #error "LMS parameters only support heights 5-20." +#endif + +/* Length of I in bytes. */ +#define LMS_I_LEN 16 +/* Length of L in bytes. */ +#define LMS_L_LEN 4 +/* Length of Q for a level. */ +#define LMS_Q_LEN 4 +/* Length of P in bytes. */ +#define LMS_P_LEN 2 +/* Length of W in bytes. */ +#define LMS_W_LEN 1 + +/* Length of numeric types when encoding. */ +#define LMS_TYPE_LEN 4 + +/* Maximum size of a node hash. */ +#define LMS_MAX_NODE_LEN WC_SHA256_DIGEST_SIZE +/* Maximum size of SEED (produced by hash). */ +#define LMS_SEED_LEN WC_SHA256_DIGEST_SIZE +/* Maximum number of P, number of n-byte string elements in LM-OTS signature. + * Value of P when N=32 and W=1. + */ +#define LMS_MAX_P 265 +/* Length of SEED and I in bytes. */ +#define LMS_SEED_I_LEN (LMS_SEED_LEN + LMS_I_LEN) + + +#ifndef WOLFSSL_LMS_ROOT_LEVELS + #ifdef WOLFSSL_LMS_LARGE_CACHES + /* Number of root levels of interior nodes to store. */ + #define LMS_ROOT_LEVELS 7 + #else + /* Number of root levels of interior nodes to store. */ + #define LMS_ROOT_LEVELS 5 + #endif +#else + #define LMS_ROOT_LEVELS WOLFSSL_LMS_ROOT_LEVELS +#endif +#if LMS_ROOT_LEVELS <= 0 + #error "LMS_ROOT_LEVELS must be greater than 0." +#endif +/* Count of root nodes to store per level. */ +#define LMS_ROOT_COUNT ((1 << (LMS_ROOT_LEVELS)) - 1) + +#ifndef WOLFSSL_LMS_CACHE_BITS + #ifdef WOLFSSL_LMS_LARGE_CACHES + /* 2 to the power of the value is the number of leaf nodes to cache. */ + #define LMS_CACHE_BITS 7 + #else + /* 2 to the power of the value is the number of leaf nodes to cache. */ + #define LMS_CACHE_BITS 5 + #endif +#else + #define LMS_CACHE_BITS WOLFSSL_LMS_CACHE_BITS +#endif +#if LMS_CACHE_BITS < 0 + #error "LMS_CACHE_BITS must be greater than or equal to 0." +#endif +/* Number of leaf nodes to cache. */ +#define LMS_LEAF_CACHE (1 << LMS_CACHE_BITS) + +/* Maximum number of levels of trees described in private key. */ +#define HSS_MAX_LEVELS 8 +/* Length of full Q in bytes. Q from all levels combined. */ +#define HSS_Q_LEN 8 + +/* Compressed parameter set length in bytes. */ +#define HSS_COMPRESS_PARAM_SET_LEN 1 +/* Total compressed parameter set length for private key in bytes. */ +#define HSS_PRIV_KEY_PARAM_SET_LEN \ + (HSS_COMPRESS_PARAM_SET_LEN * HSS_MAX_LEVELS) + +/* Private key length for one level. */ +#define LMS_PRIV_LEN \ + (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN) +/* Public key length in signature. */ +#define LMS_PUBKEY_LEN \ + (LMS_TYPE_LEN + LMS_TYPE_LEN + LMS_I_LEN + LMS_MAX_NODE_LEN) + +/* LMS signature data length. */ +#define LMS_SIG_LEN(h, p) \ + (LMS_Q_LEN + LMS_TYPE_LEN + LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN + \ + LMS_TYPE_LEN + (h) * LMS_MAX_NODE_LEN) + +/* Length of public key. */ +#define HSS_PUBLIC_KEY_LEN (LMS_L_LEN + LMS_PUBKEY_LEN) +/* Length of private key. */ +#define HSS_PRIVATE_KEY_LEN \ + (HSS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN + LMS_SEED_LEN + LMS_I_LEN) +/* Maximum public key length - length is constant for all parameters. */ +#define HSS_MAX_PRIVATE_KEY_LEN HSS_PRIVATE_KEY_LEN +/* Maximum private key length - length is constant for all parameters. */ +#define HSS_MAX_PUBLIC_KEY_LEN HSS_PUBLIC_KEY_LEN +/* Maximum signature length. */ +#define HSS_MAX_SIG_LEN \ + (LMS_TYPE_LEN + \ + LMS_MAX_LEVELS * (LMS_Q_LEN + LMS_TYPE_LEN + LMS_TYPE_LEN + \ + LMS_MAX_NODE_LEN * (1 + LMS_MAX_P + LMS_MAX_HEIGHT)) + \ + (LMS_MAX_LEVELS - 1) * LMS_PUBKEY_LEN \ + ) + +/* Maximum buffer length required for use when hashing. */ +#define LMS_MAX_BUFFER_LEN \ + (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_W_LEN + 2 * LMS_MAX_NODE_LEN) + + +/* Private key data length. + * + * HSSPrivKey.priv + */ +#define LMS_PRIV_KEY_LEN(l) \ + ((l) * LMS_PRIV_LEN) + +/* Stack of nodes. */ +#define LMS_STACK_CACHE_LEN(h) \ + (((h) + 1) * LMS_MAX_NODE_LEN) + +/* Root cache length. */ +#define LMS_ROOT_CACHE_LEN(rl) \ + (((1 << (rl)) - 1) * LMS_MAX_NODE_LEN) + +/* Leaf cache length. */ +#define LMS_LEAF_CACHE_LEN(cb) \ + ((1 << (cb)) * LMS_MAX_NODE_LEN) + +/* Length of LMS private key state. + * + * LmsPrivState + * auth_path + + * root + + * stack.stack + stack.offset + + * cache.leaf + cache.index + cache.offset + */ +#define LMS_PRIV_STATE_LEN(h, rl, cb) \ + (((h) * LMS_MAX_NODE_LEN) + \ + LMS_STACK_CACHE_LEN(h) + 4 + \ + LMS_ROOT_CACHE_LEN(rl) + \ + LMS_LEAF_CACHE_LEN(cb) + 4 + 4) + +#ifndef WOLFSSL_WC_LMS_SMALL + /* Private key data state for all levels. */ + #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) \ + ((l) * LMS_PRIV_STATE_LEN(h, rl, cb)) +#else + /* Private key data state for all levels. */ + #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) 0 +#endif + +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + /* Extra private key data for smoothing. */ + #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) \ + (LMS_PRIV_KEY_LEN(l) + \ + ((l) - 1) * LMS_PRIV_STATE_LEN(h, rl, cb)) +#else + /* Extra private key data for smoothing. */ + #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) 0 +#endif + +#ifndef WOLFSSL_LMS_NO_SIG_CACHE + #define LMS_PRIV_Y_TREE_LEN(p) \ + (LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN) + /* Length of the y data cached in private key data. */ + #define LMS_PRIV_Y_LEN(l, p) \ + (((l) - 1) * (LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN)) +#else + /* Length of the y data cached in private key data. */ + #define LMS_PRIV_Y_LEN(l, p) 0 +#endif + +#ifndef WOLFSSL_WC_LMS_SMALL +/* Length of private key data. */ +#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb) \ + (LMS_PRIV_KEY_LEN(l) + \ + LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) + \ + LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) + \ + LMS_PRIV_Y_LEN(l, p)) +#else +#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb) \ + LMS_PRIV_KEY_LEN(l) +#endif + + +/* LMS Parameters. */ +/* SHA-256 hash, 32-bytes of hash used, tree height of 5. */ +#define LMS_SHA256_M32_H5 5 +/* SHA-256 hash, 32-bytes of hash used, tree height of 10. */ +#define LMS_SHA256_M32_H10 6 +/* SHA-256 hash, 32-bytes of hash used, tree height of 15. */ +#define LMS_SHA256_M32_H15 7 +/* SHA-256 hash, 32-bytes of hash used, tree height of 20. */ +#define LMS_SHA256_M32_H20 8 +/* SHA-256 hash, 32-bytes of hash used, tree height of 25. */ +#define LMS_SHA256_M32_H25 9 + +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 1 bit. */ +#define LMOTS_SHA256_N32_W1 1 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 2 bits. */ +#define LMOTS_SHA256_N32_W2 2 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 4 bits. */ +#define LMOTS_SHA256_N32_W4 3 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 8 bits. */ +#define LMOTS_SHA256_N32_W8 4 + +typedef struct LmsParams { + /* Number of tree levels. */ + word8 levels; + /* Height of each tree. */ + word8 height; + /* Width or Winternitz coefficient. */ + word8 width; + /* Number of left-shift bits used in checksum calculation. */ + word8 ls; + /* Number of n-byte string elements in LM-OTS signature. */ + word16 p; + /* LMS type. */ + word16 lmsType; + /* LMOTS type. */ + word16 lmOtsType; + /* Length of LM-OTS signature. */ + word16 sig_len; +#ifndef WOLFSSL_WC_LMS_SMALL + /* Number of root levels of interior nodes to store. */ + word8 rootLevels; + /* 2 to the power of the value is the number of leaf nodes to cache. */ + word8 cacheBits; +#endif +} LmsParams; + +/* Mapping of id and string to parameters. */ +typedef struct wc_LmsParamsMap { + /* Identifier of parameters. */ + enum wc_LmsParm id; + /* String representation of identifier of parameters. */ + const char* str; + /* LMS parameter set. */ + LmsParams params; +} wc_LmsParamsMap; + +typedef struct LmsState { + /* Buffer to hold data to hash. */ + ALIGN16 byte buffer[LMS_MAX_BUFFER_LEN]; +#ifdef WOLFSSL_SMALL_STACK + /* Buffer to hold expanded Q coefficients. */ + ALIGN16 byte a[LMS_MAX_P]; +#endif + /* LMS parameters. */ + const LmsParams* params; + /* Hash algorithm. */ + wc_Sha256 hash; + /* Hash algorithm for calculating K. */ + wc_Sha256 hash_k; +} LmsState; + +#ifndef WOLFSSL_WC_LMS_SMALL +/* Stack of interior node hashes. */ +typedef struct LmsStack { + /* Stack nodes. */ + byte* stack; + /* Top of stack offset. */ + word32 offset; +} LmsStack; + +/* Cache of leaf hashes. */ +typedef struct HssLeafCache { + /* Cache of leaf nodes. Circular queue. */ + byte* cache; + /* Start index of cached leaf nodes. */ + word32 idx; + /* Index into cache of first leaf node. */ + word32 offset; +} HssLeafCache; + +typedef struct LmsPrivState { + /* Authentication path for current index. */ + byte* auth_path; + /* Stack nodes. */ + LmsStack stack; + /* Root nodes. */ + byte* root; + /* Cache of leaf nodes. */ + HssLeafCache leaf; +} LmsPrivState; +#endif /* WOLFSSL_WC_LMS_SMALL */ + +typedef struct HssPrivKey { + /* Private key. */ + byte* priv; +#ifndef WOLFSSL_WC_LMS_SMALL + /* Per level state of the private key. */ + LmsPrivState state[LMS_MAX_LEVELS]; +#ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + /* Next private key. */ + byte* next_priv; + /* Next private state. */ + LmsPrivState next_state[LMS_MAX_LEVELS - 1]; +#endif +#ifndef WOLFSSL_LMS_NO_SIG_CACHE + /* Per level state of the private key. */ + byte* y; +#endif + /* Indicates the key has all levels initialized. */ + word8 inited:1; +#endif +} HssPrivKey; + +struct LmsKey { + /* Public key. */ + ALIGN16 byte pub[HSS_PUBLIC_KEY_LEN]; +#ifndef WOLFSSL_LMS_VERIFY_ONLY + /* Encoded private key. */ + ALIGN16 byte priv_raw[HSS_PRIVATE_KEY_LEN]; + + /* Packed private key data. */ + byte* priv_data; + /* HSS Private key. */ + HssPrivKey priv; + + /* Callback to write/update key. */ + wc_lms_write_private_key_cb write_private_key; + /* Callback to read key. */ + wc_lms_read_private_key_cb read_private_key; + /* Context arg passed to callbacks. */ + void* context; + /* Dynamic memory hint. */ + void* heap; +#endif /* !WOLFSSL_LMS_VERIFY_ONLY */ + /* Parameters of key. */ + const LmsParams* params; + /* Current state of key. */ + enum wc_LmsState state; +#ifdef WOLF_CRYPTO_CB + /* Device Identifier. */ + int devId; +#endif +}; + +int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, + HssPrivKey* priv_key, byte* priv_data, byte* pub); +int wc_hss_reload_key(LmsState* state, const byte* priv_raw, + HssPrivKey* priv_key, byte* priv_data, byte* pub_root); +int wc_hss_sign(LmsState* state, byte* priv_raw, HssPrivKey* priv_key, + byte* priv_data, const byte* msg, word32 msgSz, byte* sig); +int wc_hss_sigsleft(const LmsParams* params, const byte* priv_raw); +int wc_hss_verify(LmsState* state, const byte* pub, const byte* msg, + word32 msgSz, const byte* sig); + +#endif /* WOLFSSL_HAVE_LMS && WOLFSSL_WC_LMS */ +#endif /* WC_LMS_H */ diff --git a/src/wolfssl/wolfcrypt/wc_port.h b/src/wolfssl/wolfcrypt/wc_port.h index bf5ef6b..23110b9 100644 --- a/src/wolfssl/wolfcrypt/wc_port.h +++ b/src/wolfssl/wolfcrypt/wc_port.h @@ -80,7 +80,7 @@ #endif #endif /* WOLFSSL_SGX */ #endif - #ifndef SINGLE_THREADED + #if !defined(SINGLE_THREADED) && !defined(_WIN32_WCE) #include #endif #elif defined(THREADX) @@ -145,13 +145,20 @@ #elif defined(WOLFSSL_APACHE_MYNEWT) /* do nothing */ #elif defined(WOLFSSL_ZEPHYR) + #include #ifndef SINGLE_THREADED #ifndef CONFIG_PTHREAD_IPC #error "Need CONFIG_PTHREAD_IPC for threading" #endif + #if KERNEL_VERSION_NUMBER >= 0x30100 #include #include #include + #else + #include + #include + #include + #endif #endif #elif defined(WOLFSSL_TELIT_M2MB) @@ -335,7 +342,11 @@ #endif #elif defined(_MSC_VER) /* Use MSVC compiler intrinsics for atomic ops */ - #include + #ifdef _WIN32_WCE + #include + #else + #include + #endif typedef volatile long wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_OPS #endif @@ -702,16 +713,23 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFGETS fgets #define XFPRINTF fprintf #define XFFLUSH fflush + #define XFEOF(fp) feof(fp) + #define XFERROR(fp) ferror(fp) + #define XCLEARERR(fp) clearerr(fp) #if !defined(NO_WOLFSSL_DIR)\ && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) #if defined(USE_WINDOWS_API) + #include #include #ifndef XSTAT #define XSTAT _stat #endif #define XS_ISREG(s) (s & _S_IFREG) #define SEPARATOR_CHAR ';' + #define XWRITE _write + #define XREAD _read + #define XALTHOMEVARNAME "USERPROFILE" #elif defined(ARDUINO) #ifndef XSTAT @@ -766,6 +784,15 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #ifndef MAX_PATH #define MAX_PATH (260 + 1) #endif + #ifndef XFEOF + #define XFEOF(fp) 0 + #endif + #ifndef XFERROR + #define XFERROR(fp) 0 + #endif + #ifndef XCLEARERR + #define XCLEARERR(fp) WC_DO_NOTHING + #endif WOLFSSL_LOCAL int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen, void* heap); @@ -999,8 +1026,13 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define USE_WOLF_TIME_T #elif defined(WOLFSSL_ZEPHYR) + #include #ifndef _POSIX_C_SOURCE - #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #else + #include + #endif #else #include #endif diff --git a/src/wolfssl/wolfcrypt/wc_xmss.h b/src/wolfssl/wolfcrypt/wc_xmss.h index 96274d7..9d88fbf 100644 --- a/src/wolfssl/wolfcrypt/wc_xmss.h +++ b/src/wolfssl/wolfcrypt/wc_xmss.h @@ -19,5 +19,267 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#error "Contact wolfSSL to get the implementation of this file" +/* Based on: + * o RFC 8391 - XMSS: eXtended Merkle Signature Scheme + * o [HDSS] "Hash-based Digital Signature Schemes", Buchmann, Dahmen and Szydlo + * from "Post Quantum Cryptography", Springer 2009. + */ + +#ifndef WC_XMSS_H +#define WC_XMSS_H + +#ifdef WOLFSSL_HAVE_XMSS +#include +#include +#include +#include + +#if !defined(WOLFSSL_WC_XMSS) + #error "This code is incompatible with external implementation of XMSS." +#endif + +#if (defined(WC_XMSS_SHA512) || defined(WC_XMSS_SHAKE256)) && \ + (WOLFSSL_WC_XMSS_MAX_HASH_SIZE >= 512) + #define WC_XMSS_MAX_N 64 + #define WC_XMSS_MAX_PADDING_LEN 64 +#else + #define WC_XMSS_MAX_N 32 + #define WC_XMSS_MAX_PADDING_LEN 32 +#endif +#define WC_XMSS_MAX_MSG_PRE_LEN \ + (WC_XMSS_MAX_PADDING_LEN + 3 * WC_XMSS_MAX_N) +#define WC_XMSS_MAX_TREE_HEIGHT 20 +#define WC_XMSS_MAX_CSUM_BYTES 4 +#define WC_XMSS_MAX_WOTS_LEN (8 * WC_XMSS_MAX_N / 4 + 3) +#define WC_XMSS_MAX_WOTS_SIG_LEN (WC_XMSS_MAX_WOTS_LEN * WC_XMSS_MAX_N) +#define WC_XMSS_MAX_STACK_LEN \ + ((WC_XMSS_MAX_TREE_HEIGHT + 1) * WC_XMSS_MAX_N) +#define WC_XMSS_MAX_D 12 +#define WC_XMSS_MAX_BDS_STATES (2 * WC_XMSS_MAX_D - 1) +#define WC_XMSS_MAX_TREE_HASH \ + ((2 * WC_XMSS_MAX_D - 1) * WC_XMSS_MAX_TREE_HEIGHT) +#define WC_XMSS_MAX_BDS_K 0 + +#define WC_XMSS_ADDR_LEN 32 + +#define WC_XMSS_HASH_PRF_MAX_DATA_LEN \ + (WC_XMSS_MAX_PADDING_LEN + 2 * WC_XMSS_MAX_N + WC_XMSS_ADDR_LEN) +#define WC_XMSS_HASH_MAX_DATA_LEN \ + (WC_XMSS_MAX_PADDING_LEN + 3 * WC_XMSS_MAX_N) + + +#define WC_XMSS_SHA256_N 32 +#define WC_XMSS_SHA256_PADDING_LEN 32 +#define WC_XMSS_SHA256_WOTS_LEN 67 + +#define XMSS_OID_LEN 4 + +#define XMSS_MAX_HASH_LEN WC_SHA256_DIGEST_SIZE + +#define XMSS_RETAIN_LEN(k, n) ((!!(k)) * ((1 << (k)) - (k) - 1) * (n)) + +/* XMMS Algorithm OIDs + * Note: values are used in mathematical calculations in OID to parames. */ +#define WC_XMSS_OID_SHA2_10_256 0x01 +#define WC_XMSS_OID_SHA2_16_256 0x02 +#define WC_XMSS_OID_SHA2_20_256 0x03 +#define WC_XMSS_OID_SHA2_10_512 0x04 +#define WC_XMSS_OID_SHA2_16_512 0x05 +#define WC_XMSS_OID_SHA2_20_512 0x06 +#define WC_XMSS_OID_SHAKE_10_256 0x07 +#define WC_XMSS_OID_SHAKE_16_256 0x08 +#define WC_XMSS_OID_SHAKE_20_256 0x09 +#define WC_XMSS_OID_SHAKE_10_512 0x0a +#define WC_XMSS_OID_SHAKE_16_512 0x0b +#define WC_XMSS_OID_SHAKE_20_512 0x0c +#define WC_XMSS_OID_SHA2_10_192 0x0d +#define WC_XMSS_OID_SHA2_16_192 0x0e +#define WC_XMSS_OID_SHA2_20_192 0x0f +#define WC_XMSS_OID_SHAKE256_10_256 0x10 +#define WC_XMSS_OID_SHAKE256_16_256 0x11 +#define WC_XMSS_OID_SHAKE256_20_256 0x12 +#define WC_XMSS_OID_SHAKE256_10_192 0x13 +#define WC_XMSS_OID_SHAKE256_16_192 0x14 +#define WC_XMSS_OID_SHAKE256_20_192 0x15 +#define WC_XMSS_OID_FIRST WC_XMSS_OID_SHA2_10_256 +#define WC_XMSS_OID_LAST WC_XMSS_OID_SHAKE256_20_192 + +/* XMMS^MT Algorithm OIDs + * Note: values are used in mathematical calculations in OID to parames. */ +#define WC_XMSSMT_OID_SHA2_20_2_256 0x01 +#define WC_XMSSMT_OID_SHA2_20_4_256 0x02 +#define WC_XMSSMT_OID_SHA2_40_2_256 0x03 +#define WC_XMSSMT_OID_SHA2_40_4_256 0x04 +#define WC_XMSSMT_OID_SHA2_40_8_256 0x05 +#define WC_XMSSMT_OID_SHA2_60_3_256 0x06 +#define WC_XMSSMT_OID_SHA2_60_6_256 0x07 +#define WC_XMSSMT_OID_SHA2_60_12_256 0x08 +#define WC_XMSSMT_OID_SHA2_20_2_512 0x09 +#define WC_XMSSMT_OID_SHA2_20_4_512 0x0a +#define WC_XMSSMT_OID_SHA2_40_2_512 0x0b +#define WC_XMSSMT_OID_SHA2_40_4_512 0x0c +#define WC_XMSSMT_OID_SHA2_40_8_512 0x0d +#define WC_XMSSMT_OID_SHA2_60_3_512 0x0e +#define WC_XMSSMT_OID_SHA2_60_6_512 0x0f +#define WC_XMSSMT_OID_SHA2_60_12_512 0x10 +#define WC_XMSSMT_OID_SHAKE_20_2_256 0x11 +#define WC_XMSSMT_OID_SHAKE_20_4_256 0x12 +#define WC_XMSSMT_OID_SHAKE_40_2_256 0x13 +#define WC_XMSSMT_OID_SHAKE_40_4_256 0x14 +#define WC_XMSSMT_OID_SHAKE_40_8_256 0x15 +#define WC_XMSSMT_OID_SHAKE_60_3_256 0x16 +#define WC_XMSSMT_OID_SHAKE_60_6_256 0x17 +#define WC_XMSSMT_OID_SHAKE_60_12_256 0x18 +#define WC_XMSSMT_OID_SHAKE_20_2_512 0x19 +#define WC_XMSSMT_OID_SHAKE_20_4_512 0x1a +#define WC_XMSSMT_OID_SHAKE_40_2_512 0x1b +#define WC_XMSSMT_OID_SHAKE_40_4_512 0x1c +#define WC_XMSSMT_OID_SHAKE_40_8_512 0x1d +#define WC_XMSSMT_OID_SHAKE_60_3_512 0x1e +#define WC_XMSSMT_OID_SHAKE_60_6_512 0x1f +#define WC_XMSSMT_OID_SHAKE_60_12_512 0x20 +#define WC_XMSSMT_OID_SHA2_20_2_192 0x21 +#define WC_XMSSMT_OID_SHA2_20_4_192 0x22 +#define WC_XMSSMT_OID_SHA2_40_2_192 0x23 +#define WC_XMSSMT_OID_SHA2_40_4_192 0x24 +#define WC_XMSSMT_OID_SHA2_40_8_192 0x25 +#define WC_XMSSMT_OID_SHA2_60_3_192 0x26 +#define WC_XMSSMT_OID_SHA2_60_6_192 0x27 +#define WC_XMSSMT_OID_SHA2_60_12_192 0x28 +#define WC_XMSSMT_OID_SHAKE256_20_2_256 0x29 +#define WC_XMSSMT_OID_SHAKE256_20_4_256 0x2a +#define WC_XMSSMT_OID_SHAKE256_40_2_256 0x2b +#define WC_XMSSMT_OID_SHAKE256_40_4_256 0x2c +#define WC_XMSSMT_OID_SHAKE256_40_8_256 0x2d +#define WC_XMSSMT_OID_SHAKE256_60_3_256 0x2e +#define WC_XMSSMT_OID_SHAKE256_60_6_256 0x2f +#define WC_XMSSMT_OID_SHAKE256_60_12_256 0x30 +#define WC_XMSSMT_OID_SHAKE256_20_2_192 0x31 +#define WC_XMSSMT_OID_SHAKE256_20_4_192 0x32 +#define WC_XMSSMT_OID_SHAKE256_40_2_192 0x33 +#define WC_XMSSMT_OID_SHAKE256_40_4_192 0x34 +#define WC_XMSSMT_OID_SHAKE256_40_8_192 0x35 +#define WC_XMSSMT_OID_SHAKE256_60_3_192 0x36 +#define WC_XMSSMT_OID_SHAKE256_60_6_192 0x37 +#define WC_XMSSMT_OID_SHAKE256_60_12_192 0x38 +#define WC_XMSSMT_OID_FIRST WC_XMSSMT_OID_SHA2_20_2_256 +#define WC_XMSSMT_OID_LAST WC_XMSSMT_OID_SHAKE256_60_12_192 + + +/* Type for hash address. */ +typedef word32 HashAddress[8]; + +/* XMSS/XMSS^MT fixed parameters. */ +typedef struct XmssParams { + /* Hash algorithm to use. */ + word8 hash; + /* Size of hash output. */ + word8 n; + /* Number of bytes of padding before rest of hash data. */ + word8 pad_len; + /* Number of values to chain = 2 * n + 3. */ + word8 wots_len; + /* Number of bytes in each WOTS+ signature. */ + word16 wots_sig_len; + /* Full height of tree. */ + word8 h; + /* Height of tree each subtree. */ + word8 sub_h; + /* Number of subtrees = h / sub_h. */ + word8 d; + /* Number of bytes to encode index into in private/secret key. */ + word8 idx_len; + /* Number of bytes in a signature. */ + word32 sig_len; + /* Number of bytes in a secret/private key. */ + word32 sk_len; + /* Number of bytes in a public key. */ + word8 pk_len; + /* BDS parameter for fast C implementation. */ + word8 bds_k; +} XmssParams; + +struct XmssKey { + /* Public key. */ + unsigned char pk[2 * WC_XMSS_MAX_N]; + /* OID that identifies parameters. */ + word32 oid; + /* Indicates whether the parameters are for XMSS^MT. */ + int is_xmssmt; + /* XMSS/XMSS^MT parameters. */ + const XmssParams* params; +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + /* Secret/private key. */ + unsigned char* sk; + /* Length of secret key. */ + word32 sk_len; + /* Callback to write/update key. */ + wc_xmss_write_private_key_cb write_private_key; + /* Callback to read key. */ + wc_xmss_read_private_key_cb read_private_key; + /* Context arg passed to callbacks. */ + void* context; +#endif /* ifndef WOLFSSL_XMSS_VERIFY_ONLY */ + /* State of key. */ + enum wc_XmssState state; +}; + +typedef struct XmssState { + const XmssParams* params; + + /* Digest is assumed to be at the end. */ + union { + #ifdef WC_XMSS_SHA256 + wc_Sha256 sha256; + #endif + #ifdef WC_XMSS_SHA512 + wc_Sha512 sha512; + #endif + #if defined(WC_XMSS_SHAKE128) || defined(WC_XMSS_SHAKE256) + wc_Shake shake; + #endif + } digest; +#if !defined(WOLFSSL_WC_XMSS_SMALL) && defined(WC_XMSS_SHA256) && \ + !defined(WC_XMSS_FULL_HASH) + ALIGN16 word32 dgst_state[WC_SHA256_DIGEST_SIZE / sizeof(word32)]; +#endif + ALIGN16 byte prf_buf[WC_XMSS_HASH_PRF_MAX_DATA_LEN]; + ALIGN16 byte buf[WC_XMSS_HASH_MAX_DATA_LEN]; + ALIGN16 byte pk[WC_XMSS_MAX_WOTS_SIG_LEN]; +#ifndef WOLFSSL_XMSS_VERIFY_ONLY + ALIGN16 byte stack[WC_XMSS_MAX_STACK_LEN]; +#else + ALIGN16 byte stack[WC_XMSS_ADDR_LEN]; +#endif + byte encMsg[WC_XMSS_MAX_WOTS_LEN]; + HashAddress addr; + + int ret; +} XmssState; + +#ifdef __cplusplus + extern "C" { +#endif + +WOLFSSL_LOCAL int wc_xmssmt_keygen(XmssState *state, const unsigned char* seed, + unsigned char *sk, unsigned char *pk); +WOLFSSL_LOCAL int wc_xmss_keygen(XmssState *state, const unsigned char* seed, + unsigned char *sk, unsigned char *pk); + +WOLFSSL_LOCAL int wc_xmssmt_sign(XmssState *state, const unsigned char *m, + word32 mlen, unsigned char *sk, unsigned char *sm); +WOLFSSL_LOCAL int wc_xmss_sign(XmssState *state, const unsigned char *m, + word32 mlen, unsigned char *sk, unsigned char *sm); + +WOLFSSL_LOCAL int wc_xmss_sigsleft(const XmssParams* params, unsigned char* sk); + +WOLFSSL_LOCAL int wc_xmssmt_verify(XmssState *state, const unsigned char *m, + word32 mlen, const unsigned char *sm, const unsigned char *pk); + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* WOLFSSL_HAVE_XMSS */ +#endif /* WC_XMSS_H */ diff --git a/src/wolfssl/wolfcrypt/xmss.h b/src/wolfssl/wolfcrypt/xmss.h index 7f19aee..37aab34 100644 --- a/src/wolfssl/wolfcrypt/xmss.h +++ b/src/wolfssl/wolfcrypt/xmss.h @@ -160,9 +160,9 @@ enum wc_XmssState { }; /* Private key write and read callbacks. */ -typedef enum wc_XmssRc (*write_private_key_cb)(const byte* priv, word32 privSz, +typedef enum wc_XmssRc (*wc_xmss_write_private_key_cb)(const byte* priv, word32 privSz, void* context); -typedef enum wc_XmssRc (*read_private_key_cb)(byte* priv, word32 privSz, +typedef enum wc_XmssRc (*wc_xmss_read_private_key_cb)(byte* priv, word32 privSz, void* context); #ifdef __cplusplus @@ -173,9 +173,9 @@ WOLFSSL_API int wc_XmssKey_Init(XmssKey* key, void* heap, int devId); WOLFSSL_API int wc_XmssKey_SetParamStr(XmssKey* key, const char* str); #ifndef WOLFSSL_XMSS_VERIFY_ONLY WOLFSSL_API int wc_XmssKey_SetWriteCb(XmssKey* key, - write_private_key_cb write_cb); + wc_xmss_write_private_key_cb write_cb); WOLFSSL_API int wc_XmssKey_SetReadCb(XmssKey* key, - read_private_key_cb read_cb); + wc_xmss_read_private_key_cb read_cb); WOLFSSL_API int wc_XmssKey_SetContext(XmssKey* key, void* context); WOLFSSL_API int wc_XmssKey_MakeKey(XmssKey* key, WC_RNG* rng); WOLFSSL_API int wc_XmssKey_Reload(XmssKey* key); diff --git a/src/wolfssl/wolfio.h b/src/wolfssl/wolfio.h index 48646a5..e2a1c88 100644 --- a/src/wolfssl/wolfio.h +++ b/src/wolfssl/wolfio.h @@ -129,7 +129,18 @@ #include #include #elif defined(WOLFSSL_ZEPHYR) - #include + #include + #if KERNEL_VERSION_NUMBER >= 0x30100 + #include + #ifdef CONFIG_POSIX_API + #include + #endif + #else + #include + #ifdef CONFIG_POSIX_API + #include + #endif + #endif #elif defined(MICROCHIP_PIC32) #include #elif defined(HAVE_NETX) @@ -139,6 +150,8 @@ #include #include #include + #elif defined(WOLFSSL_EMNET) + #include #elif !defined(WOLFSSL_NO_SOCK) #include #include @@ -206,7 +219,8 @@ #define SOCKET_ECONNREFUSED SYS_NET_ECONNREFUSED #define SOCKET_ECONNABORTED SYS_NET_ECONNABORTED #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) - #if MQX_USE_IO_OLD + #if (defined(MQX_USE_IO_OLD) && MQX_USE_IO_OLD) || \ + defined(FREESCALE_MQX_5_0) /* RTCS old I/O doesn't have an EWOULDBLOCK */ #define SOCKET_EWOULDBLOCK EAGAIN #define SOCKET_EAGAIN EAGAIN @@ -293,7 +307,7 @@ #define SOCKET_ECONNREFUSED ERR_CONN #define SOCKET_ECONNABORTED ERR_ABRT #elif defined(WOLFSSL_EMNET) - #include + #define XSOCKLENT int #define SOCKET_EWOULDBLOCK IP_ERR_WOULD_BLOCK #define SOCKET_EAGAIN IP_ERR_WOULD_BLOCK #define SOCKET_ECONNRESET IP_ERR_CONN_RESET From 6e15746cf5866d697a6af7c24e0cb51f5bf649d8 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Sat, 23 Nov 2024 12:44:28 -0800 Subject: [PATCH 05/13] wolfssl 5.7.4 Release for Arduino --- ChangeLog.md | 226 +- README | 264 +- README.md | 276 +- examples/wolfssl_client/wolfssl_client.ino | 2 +- examples/wolfssl_server/README.md | 4 +- examples/wolfssl_server/wolfssl_server.ino | 2 +- library.json.pio | 4 +- library.properties | 2 +- library.properties.pio | 2 +- src/src/bio.c | 551 ++- src/src/conf.c | 32 +- src/src/crl.c | 66 +- src/src/dtls.c | 120 +- src/src/dtls13.c | 240 +- src/src/internal.c | 2869 +++++++----- src/src/keys.c | 30 +- src/src/ocsp.c | 425 +- src/src/pk.c | 806 +++- src/src/quic.c | 12 +- src/src/sniffer.c | 273 +- src/src/ssl.c | 1064 +++-- src/src/ssl_asn1.c | 1247 +++-- src/src/ssl_bn.c | 126 +- src/src/ssl_certman.c | 59 +- src/src/ssl_crypto.c | 49 +- src/src/ssl_load.c | 200 +- src/src/ssl_misc.c | 12 +- src/src/ssl_p7p12.c | 123 +- src/src/ssl_sess.c | 66 +- src/src/tls.c | 780 ++-- src/src/tls13.c | 388 +- src/src/wolfio.c | 469 +- src/src/x509.c | 2054 ++++++--- src/src/x509_str.c | 778 +++- src/user_settings.h | 4 +- src/wolfcrypt/src/aes.c | 516 ++- src/wolfcrypt/src/arc4.c | 2 +- src/wolfcrypt/src/asm.c | 52 +- src/wolfcrypt/src/asn.c | 3154 +++++++++---- src/wolfcrypt/src/bio.c | 551 ++- src/wolfcrypt/src/blake2b.c | 2 +- src/wolfcrypt/src/blake2s.c | 2 +- src/wolfcrypt/src/camellia.c | 2 +- src/wolfcrypt/src/chacha.c | 245 +- src/wolfcrypt/src/chacha20_poly1305.c | 2 +- src/wolfcrypt/src/cmac.c | 211 +- src/wolfcrypt/src/coding.c | 4 +- src/wolfcrypt/src/compress.c | 8 +- src/wolfcrypt/src/cpuid.c | 2 +- src/wolfcrypt/src/cryptocb.c | 91 +- src/wolfcrypt/src/curve25519.c | 43 +- src/wolfcrypt/src/curve448.c | 2 +- src/wolfcrypt/src/des3.c | 165 +- src/wolfcrypt/src/dh.c | 123 +- src/wolfcrypt/src/dilithium.c | 2901 ++++++++++-- src/wolfcrypt/src/dsa.c | 6 +- src/wolfcrypt/src/ecc.c | 395 +- src/wolfcrypt/src/eccsi.c | 14 +- src/wolfcrypt/src/ed25519.c | 35 +- src/wolfcrypt/src/ed448.c | 2 +- src/wolfcrypt/src/error.c | 24 +- src/wolfcrypt/src/evp.c | 331 +- src/wolfcrypt/src/ext_kyber.c | 54 +- src/wolfcrypt/src/ext_lms.c | 7 +- src/wolfcrypt/src/ext_xmss.c | 7 +- src/wolfcrypt/src/falcon.c | 2 +- src/wolfcrypt/src/fe_448.c | 2 +- src/wolfcrypt/src/fe_low_mem.c | 2 +- src/wolfcrypt/src/fe_operations.c | 2 +- src/wolfcrypt/src/ge_448.c | 18 +- src/wolfcrypt/src/ge_low_mem.c | 2 +- src/wolfcrypt/src/ge_operations.c | 20 +- src/wolfcrypt/src/hash.c | 206 +- src/wolfcrypt/src/hmac.c | 2 +- src/wolfcrypt/src/hpke.c | 2 +- src/wolfcrypt/src/integer.c | 2 +- src/wolfcrypt/src/kdf.c | 61 +- src/wolfcrypt/src/logging.c | 211 +- src/wolfcrypt/src/md2.c | 4 +- src/wolfcrypt/src/md4.c | 2 +- src/wolfcrypt/src/md5.c | 2 +- src/wolfcrypt/src/memory.c | 10 +- src/wolfcrypt/src/misc.c | 117 +- src/wolfcrypt/src/pkcs12.c | 59 +- src/wolfcrypt/src/pkcs7.c | 1292 +++--- src/wolfcrypt/src/poly1305.c | 122 +- src/wolfcrypt/src/port/Espressif/esp32_aes.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 340 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 16 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 149 +- .../src/port/Espressif/esp_sdk_mem_lib.c | 51 +- .../src/port/Espressif/esp_sdk_time_lib.c | 62 +- .../src/port/Espressif/esp_sdk_wifi_lib.c | 15 +- src/wolfcrypt/src/port/atmel/atmel.c | 2 +- src/wolfcrypt/src/pwdbased.c | 28 +- src/wolfcrypt/src/random.c | 55 +- src/wolfcrypt/src/rc2.c | 2 +- src/wolfcrypt/src/ripemd.c | 2 +- src/wolfcrypt/src/rsa.c | 156 +- src/wolfcrypt/src/sakke.c | 18 +- src/wolfcrypt/src/sha.c | 37 +- src/wolfcrypt/src/sha256.c | 60 +- src/wolfcrypt/src/sha3.c | 11 +- src/wolfcrypt/src/sha512.c | 76 +- src/wolfcrypt/src/signature.c | 4 +- src/wolfcrypt/src/siphash.c | 36 +- src/wolfcrypt/src/sm2.c | 2 +- src/wolfcrypt/src/sm3.c | 2 +- src/wolfcrypt/src/sm4.c | 2 +- src/wolfcrypt/src/sp_arm32.c | 1497 +++--- src/wolfcrypt/src/sp_arm64.c | 666 ++- src/wolfcrypt/src/sp_armthumb.c | 670 ++- src/wolfcrypt/src/sp_c32.c | 3437 +++++++------- src/wolfcrypt/src/sp_c64.c | 2622 +++++------ src/wolfcrypt/src/sp_cortexm.c | 4024 +++++++++++------ src/wolfcrypt/src/sp_dsp32.c | 37 +- src/wolfcrypt/src/sp_int.c | 712 ++- src/wolfcrypt/src/sp_sm2_arm32.c | 2 +- src/wolfcrypt/src/sp_sm2_arm64.c | 2 +- src/wolfcrypt/src/sp_sm2_armthumb.c | 2 +- src/wolfcrypt/src/sp_sm2_c32.c | 2 +- src/wolfcrypt/src/sp_sm2_c64.c | 2 +- src/wolfcrypt/src/sp_sm2_cortexm.c | 2 +- src/wolfcrypt/src/sp_sm2_x86_64.c | 2 +- src/wolfcrypt/src/sp_x86_64.c | 1514 ++++--- src/wolfcrypt/src/sphincs.c | 2 +- src/wolfcrypt/src/srp.c | 10 +- src/wolfcrypt/src/tfm.c | 20 +- src/wolfcrypt/src/wc_dsp.c | 2 +- src/wolfcrypt/src/wc_encrypt.c | 2 +- src/wolfcrypt/src/wc_kyber.c | 103 +- src/wolfcrypt/src/wc_kyber_poly.c | 937 +++- src/wolfcrypt/src/wc_lms.c | 251 +- src/wolfcrypt/src/wc_lms_impl.c | 1153 +++-- src/wolfcrypt/src/wc_pkcs11.c | 303 +- src/wolfcrypt/src/wc_port.c | 383 +- src/wolfcrypt/src/wc_xmss.c | 2 +- src/wolfcrypt/src/wc_xmss_impl.c | 2 +- src/wolfcrypt/src/wolfevent.c | 2 +- src/wolfcrypt/src/wolfmath.c | 12 +- src/wolfssl/bio.c | 551 ++- src/wolfssl/callbacks.h | 2 +- src/wolfssl/crl.h | 2 +- src/wolfssl/error-ssl.h | 53 +- src/wolfssl/evp.c | 331 +- src/wolfssl/internal.h | 371 +- src/wolfssl/ocsp.h | 43 +- src/wolfssl/openssl/aes.h | 2 +- src/wolfssl/openssl/asn1.h | 189 +- src/wolfssl/openssl/asn1t.h | 2 +- src/wolfssl/openssl/bio.h | 8 +- src/wolfssl/openssl/bn.h | 4 +- src/wolfssl/openssl/buffer.h | 2 +- src/wolfssl/openssl/camellia.h | 2 +- src/wolfssl/openssl/cmac.h | 2 +- src/wolfssl/openssl/cms.h | 2 +- src/wolfssl/openssl/compat_types.h | 4 +- src/wolfssl/openssl/conf.h | 2 +- src/wolfssl/openssl/crypto.h | 2 +- src/wolfssl/openssl/des.h | 2 +- src/wolfssl/openssl/dh.h | 9 +- src/wolfssl/openssl/dsa.h | 5 +- src/wolfssl/openssl/ec.h | 11 +- src/wolfssl/openssl/ec25519.h | 2 +- src/wolfssl/openssl/ec448.h | 2 +- src/wolfssl/openssl/ecdh.h | 2 +- src/wolfssl/openssl/ecdsa.h | 2 +- src/wolfssl/openssl/ed25519.h | 2 +- src/wolfssl/openssl/ed448.h | 2 +- src/wolfssl/openssl/err.h | 2 +- src/wolfssl/openssl/evp.h | 5 +- src/wolfssl/openssl/fips_rand.h | 2 +- src/wolfssl/openssl/hmac.h | 2 +- src/wolfssl/openssl/include.am | 1 + src/wolfssl/openssl/kdf.h | 2 +- src/wolfssl/openssl/lhash.h | 2 +- src/wolfssl/openssl/md4.h | 2 +- src/wolfssl/openssl/md5.h | 2 +- src/wolfssl/openssl/modes.h | 2 +- src/wolfssl/openssl/obj_mac.h | 2 +- src/wolfssl/openssl/objects.h | 2 +- src/wolfssl/openssl/ocsp.h | 27 +- src/wolfssl/openssl/opensslv.h | 37 +- src/wolfssl/openssl/ossl_typ.h | 2 +- src/wolfssl/openssl/pem.h | 21 +- src/wolfssl/openssl/pkcs12.h | 2 +- src/wolfssl/openssl/pkcs7.h | 2 +- src/wolfssl/openssl/rand.h | 2 +- src/wolfssl/openssl/rc4.h | 2 +- src/wolfssl/openssl/ripemd.h | 2 +- src/wolfssl/openssl/rsa.h | 9 +- src/wolfssl/openssl/safestack.h | 40 + src/wolfssl/openssl/sha.h | 2 +- src/wolfssl/openssl/sha3.h | 2 +- src/wolfssl/openssl/srp.h | 2 +- src/wolfssl/openssl/ssl.h | 95 +- src/wolfssl/openssl/stack.h | 2 +- src/wolfssl/openssl/tls1.h | 2 +- src/wolfssl/openssl/txt_db.h | 2 +- src/wolfssl/openssl/x509.h | 2 +- src/wolfssl/openssl/x509_vfy.h | 5 +- src/wolfssl/openssl/x509v3.h | 20 +- src/wolfssl/quic.h | 2 +- src/wolfssl/sniffer.h | 2 +- src/wolfssl/sniffer_error.h | 2 +- src/wolfssl/ssl.h | 353 +- src/wolfssl/test.h | 76 +- src/wolfssl/version.h | 6 +- src/wolfssl/wolfcrypt/aes.h | 29 +- src/wolfssl/wolfcrypt/arc4.h | 2 +- src/wolfssl/wolfcrypt/asn.h | 330 +- src/wolfssl/wolfcrypt/asn_public.h | 59 +- src/wolfssl/wolfcrypt/blake2-impl.h | 2 +- src/wolfssl/wolfcrypt/blake2-int.h | 2 +- src/wolfssl/wolfcrypt/blake2.h | 2 +- src/wolfssl/wolfcrypt/camellia.h | 2 +- src/wolfssl/wolfcrypt/chacha.h | 25 +- src/wolfssl/wolfcrypt/chacha20_poly1305.h | 4 +- src/wolfssl/wolfcrypt/cmac.h | 31 +- src/wolfssl/wolfcrypt/coding.h | 2 +- src/wolfssl/wolfcrypt/compress.h | 2 +- src/wolfssl/wolfcrypt/cpuid.h | 2 +- src/wolfssl/wolfcrypt/cryptocb.h | 12 +- src/wolfssl/wolfcrypt/curve25519.h | 15 +- src/wolfssl/wolfcrypt/curve448.h | 6 +- src/wolfssl/wolfcrypt/des3.h | 9 +- src/wolfssl/wolfcrypt/dh.h | 5 +- src/wolfssl/wolfcrypt/dilithium.h | 134 +- src/wolfssl/wolfcrypt/dsa.h | 2 +- src/wolfssl/wolfcrypt/ecc.h | 29 +- src/wolfssl/wolfcrypt/eccsi.h | 14 +- src/wolfssl/wolfcrypt/ed25519.h | 17 +- src/wolfssl/wolfcrypt/ed448.h | 8 +- src/wolfssl/wolfcrypt/error-crypt.h | 55 +- src/wolfssl/wolfcrypt/ext_kyber.h | 15 +- src/wolfssl/wolfcrypt/ext_lms.h | 9 +- src/wolfssl/wolfcrypt/ext_xmss.h | 9 +- src/wolfssl/wolfcrypt/falcon.h | 2 +- src/wolfssl/wolfcrypt/fe_448.h | 2 +- src/wolfssl/wolfcrypt/fe_operations.h | 2 +- src/wolfssl/wolfcrypt/fips_test.h | 9 +- src/wolfssl/wolfcrypt/ge_448.h | 2 +- src/wolfssl/wolfcrypt/ge_operations.h | 4 +- src/wolfssl/wolfcrypt/hash.h | 68 +- src/wolfssl/wolfcrypt/hmac.h | 31 +- src/wolfssl/wolfcrypt/hpke.h | 2 +- src/wolfssl/wolfcrypt/integer.h | 10 +- src/wolfssl/wolfcrypt/kdf.h | 4 +- src/wolfssl/wolfcrypt/kyber.h | 54 +- src/wolfssl/wolfcrypt/lms.h | 24 +- src/wolfssl/wolfcrypt/logging.h | 2 +- src/wolfssl/wolfcrypt/md2.h | 2 +- src/wolfssl/wolfcrypt/md4.h | 2 +- src/wolfssl/wolfcrypt/md5.h | 2 +- src/wolfssl/wolfcrypt/mem_track.h | 2 +- src/wolfssl/wolfcrypt/memory.h | 2 +- src/wolfssl/wolfcrypt/misc.h | 12 +- src/wolfssl/wolfcrypt/mpi_class.h | 2 +- src/wolfssl/wolfcrypt/mpi_superclass.h | 2 +- src/wolfssl/wolfcrypt/pkcs11.h | 47 +- src/wolfssl/wolfcrypt/pkcs12.h | 2 +- src/wolfssl/wolfcrypt/pkcs7.h | 35 +- src/wolfssl/wolfcrypt/poly1305.h | 73 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 12 +- .../wolfcrypt/port/Espressif/esp32-crypt.h | 135 +- .../wolfcrypt/port/Espressif/esp_crt_bundle.h | 242 + src/wolfssl/wolfcrypt/port/atmel/atmel.h | 2 +- src/wolfssl/wolfcrypt/pwdbased.h | 2 +- src/wolfssl/wolfcrypt/random.h | 2 +- src/wolfssl/wolfcrypt/rc2.h | 2 +- src/wolfssl/wolfcrypt/ripemd.h | 2 +- src/wolfssl/wolfcrypt/rsa.h | 27 +- src/wolfssl/wolfcrypt/sakke.h | 18 +- src/wolfssl/wolfcrypt/selftest.h | 2 +- src/wolfssl/wolfcrypt/settings.h | 745 ++- src/wolfssl/wolfcrypt/sha.h | 10 +- src/wolfssl/wolfcrypt/sha256.h | 11 +- src/wolfssl/wolfcrypt/sha3.h | 5 +- src/wolfssl/wolfcrypt/sha512.h | 9 +- src/wolfssl/wolfcrypt/signature.h | 2 +- src/wolfssl/wolfcrypt/siphash.h | 2 +- src/wolfssl/wolfcrypt/sm2.h | 2 +- src/wolfssl/wolfcrypt/sm3.h | 2 +- src/wolfssl/wolfcrypt/sm4.h | 2 +- src/wolfssl/wolfcrypt/sp.h | 2 +- src/wolfssl/wolfcrypt/sp_int.h | 95 +- src/wolfssl/wolfcrypt/sphincs.h | 2 +- src/wolfssl/wolfcrypt/srp.h | 2 +- src/wolfssl/wolfcrypt/tfm.h | 18 +- src/wolfssl/wolfcrypt/types.h | 178 +- src/wolfssl/wolfcrypt/visibility.h | 2 +- src/wolfssl/wolfcrypt/wc_encrypt.h | 2 +- src/wolfssl/wolfcrypt/wc_kyber.h | 73 +- src/wolfssl/wolfcrypt/wc_lms.h | 148 +- src/wolfssl/wolfcrypt/wc_pkcs11.h | 6 +- src/wolfssl/wolfcrypt/wc_port.h | 166 +- src/wolfssl/wolfcrypt/wc_xmss.h | 2 +- src/wolfssl/wolfcrypt/wolfevent.h | 2 +- src/wolfssl/wolfcrypt/wolfmath.h | 28 +- src/wolfssl/wolfcrypt/xmss.h | 2 +- src/wolfssl/wolfio.h | 99 +- 301 files changed, 33650 insertions(+), 16228 deletions(-) create mode 100644 src/wolfssl/openssl/safestack.h create mode 100644 src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h diff --git a/ChangeLog.md b/ChangeLog.md index 01fca46..a0585b3 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,196 @@ +# wolfSSL Release 5.7.4 (Oct 24, 2024) + +Release 5.7.4 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 + +PR stands for Pull Request, and PR references a GitHub pull request + number where the code change was added. + + +## Vulnerabilities +* [Low] When the OpenSSL compatibility layer is enabled, certificate + verification behaved differently in wolfSSL than OpenSSL, in the + X509_STORE_add_cert() and X509_STORE_load_locations() implementations. + Previously, in cases where an application explicitly loaded an intermediate + certificate, wolfSSL was verifying only up to that intermediate certificate, + rather than verifying up to the root CA. This only affects use cases where the + API is called directly, and does not affect TLS connections. Users that call + the API X509_STORE_add_cert() or X509_STORE_load_locations() directly in their + applications are recommended to update the version of wolfSSL used or to have + additional sanity checks on certificates loaded into the X509_STORE when + verifying a certificate. (https://github.com/wolfSSL/wolfssl/pull/8087) + + +## PQC TLS Experimental Build Fix +* When using TLS with post quantum algorithms enabled, the connection uses a + smaller EC curve than agreed on. Users building with --enable-experimental and + enabling PQC cipher suites with TLS connections are recommended to update the + version of wolfSSL used. Thanks to Daniel Correa for the report. + (https://github.com/wolfSSL/wolfssl/pull/8084) + + +## New Feature Additions +* RISC-V 64 new assembly optimizations added for SHA-256, SHA-512, ChaCha20, + Poly1305, and SHA-3 (PR 7758,7833,7818,7873,7916) +* Implement support for Connection ID (CID) with DTLS 1.2 (PR 7995) +* Add support for (DevkitPro)libnds (PR 7990) +* Add port for Mosquitto OSP (Open Source Project) (PR 6460) +* Add port for init sssd (PR 7781) +* Add port for eXosip2 (PR 7648) +* Add support for STM32G4 (PR 7997) +* Add support for MAX32665 and MAX32666 TPU HW and ARM ASM Crypto Callback + Support (PR 7777) +* Add support for building wolfSSL to be used in libspdm (PR 7869) +* Add port for use with Nucleus Plus 2.3 (PR 7732) +* Initial support for RFC5755 x509 attribute certificates (acerts). Enabled with + --enable-acert (PR 7926) +* PKCS#11 RSA Padding offload allows tokens to perform CKM_RSA_PKCS + (sign/encrypt), CKM_RSA_PKCS_PSS (sign), and CKM_RSA_PKCS_OAEP (encrypt). + (PR 7750) +* Added “new” and “delete” style functions for heap/pool allocation and freeing + of low level crypto structures (PR 3166 and 8089) + + +## Enhancements and Optimizations +* Increase default max alt. names from 128 to 1024 (PR 7762) +* Added new constant time DH agree function wc_DhAgree_ct (PR 7802) +* Expanded compatibility layer with the API EVP_PKEY_is_a (PR 7804) +* Add option to disable cryptocb test software test using + --disable-cryptocb-sw-test (PR 7862) +* Add a call to certificate verify callback before checking certificate dates + (PR 7895) +* Expanded algorithms supported with the wolfCrypt CSharp wrapper. Adding + support for RNG, ECC(ECIES and ECDHE), RSA, ED25519/Curve25519, AES-GCM, and + Hashing (PR 3166) +* Expand MMCAU support for use with DES ECB (PR 7960) +* Update AES SIV to handle multiple associated data inputs (PR 7911) +* Remove HAVE_NULL_CIPHER from --enable-openssh (PR 7811) +* Removed duplicate if(NULL) checks when calling XFREE (macro does) (PR 7839) +* Set RSA_MIN_SIZE default to 2048 bits (PR 7923) +* Added support for wolfSSL to be used as the default TLS in the zephyr kernel + (PR 7731) +* Add enable provider build using --enable-wolfprovider with autotools (PR 7550) +* Renesas RX TSIP ECDSA support (PR 7685) +* Support DTLS1.3 downgrade when the server supports CID (PR 7841) +* Server-side checks OCSP even if it uses v2 multi (PR 7828) +* Add handling of absent hash params in PKCS7 bundle parsing and creation + (PR 7845) +* Add the use of w64wrapper for Poly1305, enabling Poly1305 to be used in + environments that do not have a word64 type (PR 7759) +* Update to the maxq10xx support (PR 7824) +* Add support for parsing over optional PKCS8 attributes (PR 7944) +* Add support for either side method with DTLS 1.3 (PR 8012) +* Added PKCS7 PEM support for parsing PEM data with BEGIN/END PKCS7 (PR 7704) +* Add CMake support for WOLFSSL_CUSTOM_CURVES (PR 7962) +* Add left-most wildcard matching support to X509_check_host() (PR 7966) +* Add option to set custom SKID with PKCS7 bundle creation (PR 7954) +* Building wolfSSL as a library with Ada and corrections to Alire manifest + (PR 7303,7940) +* Renesas RX72N support updated (PR 7849) +* New option WOLFSSL_COPY_KEY added to always copy the key to the SSL object + (PR 8005) +* Add the new option WOLFSSL_COPY_CERT to always copy the cert buffer for each + SSL object (PR 7867) +* Add an option to use AES-CBC with HMAC for default session ticket enc/dec. + Defaults to AES-128-CBC with HMAC-SHA256 (PR 7703) +* Memory usage improvements in wc_PRF, sha256 (for small code when many + registers are available) and sp_int objects (PR 7901) +* Change in the configure script to work around ">>" with no command. In older + /bin/sh it can be ambiguous, as used in OS’s such as FreeBSD 9.2 (PR 7876) +* Don't attempt to include system headers when not required (PR 7813) +* Certificates: DER encoding of ECC signature algorithm parameter is now + allowed to be NULL with a define (PR 7903) +* SP x86_64 asm: check for AVX2 support for VMs (PR 7979) +* Update rx64n support on gr-rose (PR 7889) +* Update FSP version to v5.4.0 for RA6M4 (PR 7994) +* Update TSIP driver version to v1.21 for RX65N RSK (PR 7993) +* Add a new crypto callback for RSA with padding (PR 7907) +* Replaced the use of pqm4 with wolfSSL implementations of Kyber/MLDSA + (PR 7924) +* Modernized memory fence support for C11 and clang (PR 7938) +* Add a CRL error override callback (PR 7986) +* Extend the X509 unknown extension callback for use with a user context + (PR 7730) +* Additional debug error tracing added with TLS (PR 7917) +* Added runtime support for library call stack traces with + –enable-debug-trace-errcodes=backtrace, using libbacktrace (PR 7846) +* Expanded C89 conformance (PR 8077) +* Expanded support for WOLFSSL_NO_MALLOC (PR 8065) +* Added support for cross-compilation of Linux kernel module (PR 7746) +* Updated Linux kernel module with support for kernel 6.11 and 6.12 (PR 7826) +* Introduce WOLFSSL_ASN_ALLOW_0_SERIAL to allow parsing of certificates with a + serial number of 0 (PR 7893) +* Add conditional repository_owner to all wolfSSL GitHub workflows (PR 7871) + +### Espressif / Arduino Updates +* Update wolfcrypt settings.h for Espressif ESP-IDF, template update (PR 7953) +* Update Espressif sha, util, mem, time helpers (PR 7955) +* Espressif _thread_local_start and _thread_local_end fix (PR 8030) +* Improve benchmark for Espressif devices (PR 8037) +* Introduce Espressif common CONFIG_WOLFSSL_EXAMPLE_NAME, Kconfig (PR 7866) +* Add wolfSSL esp-tls and Certificate Bundle Support for Espressif ESP-IDF + (PR 7936) +* Update wolfssl Release for Arduino (PR 7775) + +### Post Quantum Crypto Updates +* Dilithium: support fixed size arrays in dilithium_key (PR 7727) +* Dilithium: add option to use precalc with small sign (PR 7744) +* Allow Kyber to be built with FIPS (PR 7788) +* Allow Kyber asm to be used in the Linux kernel module (PR 7872) +* Dilithium, Kyber: Update to final specification (PR 7877) +* Dilithium: Support FIPS 204 Draft and Final Draft (PR 7909,8016) + +### ARM Assembly Optimizations +* ARM32 assembly optimizations added for ChaCha20 and Poly1305 (PR 8020) +* Poly1305 assembly optimizations improvements for Aarch64 (PR 7859) +* Poly1305 assembly optimizations added for Thumb-2 (PR 7939) +* Adding ARM ASM build option to STM32CubePack (PR 7747) +* Add ARM64 to Visual Studio Project (PR 8010) +* Kyber assembly optimizations for ARM32 and Aarch64 (PR 8040,7998) +* Kyber assembly optimizations for ARMv7E-M/ARMv7-M (PR 7706) + + +## Fixes +* ECC key load: fixes for certificates with parameters that are not default for + size (PR 7751) +* Fixes for building x86 in Visual Studio for non-windows OS (PR 7884) +* Fix for TLS v1.2 secret callback, incorrectly detecting bad master secret + (PR 7812) +* Fixes for PowerPC assembly use with Darwin and SP math all (PR 7931) +* Fix for detecting older versions of Mac OS when trying to link with + libdispatch (PR 7932) +* Fix for DTLS1.3 downgrade to DTLS1.2 when the server sends multiple handshake + packets combined into a single transmission. (PR 7840) +* Fix for OCSP to save the request if it was stored in ssl->ctx->certOcspRequest + (PR 7779) +* Fix to OCSP for searching for CA by key hash instead of ext. key id (PR 7934) +* Fix for staticmemory and singlethreaded build (PR 7737) +* Fix to not allow Shake128/256 with Xilinx AFALG (PR 7708) +* Fix to support PKCS11 without RSA key generation (PR 7738) +* Fix not calling the signing callback when using PK callbacks + TLS 1.3 + (PR 7761) +* Cortex-M/Thumb2 ASM fix label for IAR compiler (PR 7753) +* Fix with PKCS11 to iterate correctly over slotId (PR 7736) +* Stop stripping out the sequence header on the AltSigAlg extension (PR 7710) +* Fix ParseCRL_AuthKeyIdExt with ASN template to set extAuthKeyIdSet value + (PR 7742) +* Use max key length for PSK encrypt buffer size (PR 7707) +* DTLS 1.3 fix for size check to include headers and CID fixes (PR 7912,7951) +* Fix STM32 Hash FIFO and add support for STM32U5A9xx (PR 7787) +* Fix CMake build error for curl builds (PR 8021) +* SP Maths: PowerPC ASM fix to use XOR instead of LI (PR 8038) +* SSL loading of keys/certs: testing and fixes (PR 7789) +* Misc. fixes for Dilithium and Kyber (PR 7721,7765,7803,8027,7904) +* Fixes for building wolfBoot sources for PQ LMS/XMSS (PR 7868) +* Fixes for building with Kyber enabled using CMake and zephyr port (PR 7773) +* Fix for edge cases with session resumption with TLS 1.2 (PR 8097) +* Fix issue with ARM ASM with AES CFB/OFB not initializing the "left" member + (PR 8099) + + # wolfSSL Release 5.7.2 (July 08, 2024) Release 5.7.2 has been developed according to wolfSSL's development and QA @@ -89,6 +282,7 @@ Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 * Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) ## Fixes +* Fixed Kyber control-flow timing leak. Thanks to Antoon Purnal from PQShield for the report * Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) * Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) * Fixed use of %rip with SHA-256 x64 assembly (PR 7409) @@ -219,7 +413,7 @@ fixed this omission in several PRs for this release. * [Low] CVE-2023-6936: A potential heap overflow read is possible in servers connecting over TLS 1.3 when the optional `WOLFSSL_CALLBACKS` has been defined. The out of bounds read can occur when a server receives a malicious malformed ClientHello. Users should either discontinue use of `WOLFSSL_CALLBACKS` on the server side or update versions of wolfSSL to 5.6.6. Thanks to the tlspuffin fuzzer team for the report which was designed and developed by; Lucca Hirschi (Inria, LORIA), Steve Kremer (Inria, LORIA), and Max Ammann (Trail of Bits). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6949. -* [Low] A side channel vulnerability with AES T-Tables is possible in a very controlled environment where precision sub-cache-line inspection can happen, such as inside an Intel SGX enclave. This can lead to recovery of the AES key. To prevent this type of attack, wolfSSL added an AES bitsliced implementation which can be enabled with the “`--enable-aes-bitsliced`” configure option. Thanks to Florian Sieck, Zhiyuan Zhang, Sebastian Berndt, Chitchanok Chuengsatiansup, Thomas Eisenbarth, and Yuval Yarom for the report (Universities of Lübeck, Melbourne, Adelaide and Bochum). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6854. +* [Low] CVE-2024-1543: A side channel vulnerability with AES T-Tables is possible in a very controlled environment where precision sub-cache-line inspection can happen, such as inside an Intel SGX enclave. This can lead to recovery of the AES key. To prevent this type of attack, wolfSSL added an AES bitsliced implementation which can be enabled with the “`--enable-aes-bitsliced`” configure option. Thanks to Florian Sieck, Zhiyuan Zhang, Sebastian Berndt, Chitchanok Chuengsatiansup, Thomas Eisenbarth, and Yuval Yarom for the report (Universities of Lübeck, Melbourne, Adelaide and Bochum). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/6854. * [Low] CVE-2023-6937: wolfSSL prior to 5.6.6 did not check that messages in a single (D)TLS record do not span key boundaries. As a result, it was possible to combine (D)TLS messages using different keys into one (D)TLS record. The most extreme edge case is that, in (D)TLS 1.3, it was possible that an unencrypted (D)TLS 1.3 record from the server containing first a ServerHello message and then the rest of the first server flight would be accepted by a wolfSSL client. In (D)TLS 1.3 the handshake is encrypted after the ServerHello but a wolfSSL client would accept an unencrypted flight from the server. This does not compromise key negotiation and authentication so it is assigned a low severity rating. Thanks to Johannes Wilson for the report (Sectra Communications and Linköping University). The fix for this issue is located in the following GitHub Pull Request: https://github.com/wolfSSL/wolfssl/pull/7029. @@ -873,9 +1067,9 @@ Release 5.5.1 of wolfSSL embedded TLS has bug fixes and new features including: ## Enhancements * DTLSv1.3: Do HRR Cookie exchange by default -* Add wolfSSL_EVP_PKEY_new_CMAC_key to OpenSSL compatible API -* Update ide win10 build files to add missing sp source files -* Improve Workbench docs +* Add wolfSSL_EVP_PKEY_new_CMAC_key to OpenSSL compatible API +* Update ide win10 build files to add missing sp source files +* Improve Workbench docs * Improve EVP support for CHACHA20_POLY1305 * Improve `wc_SetCustomExtension` documentation * RSA-PSS with OCSP and add simple OCSP response DER verify test case @@ -883,23 +1077,23 @@ Release 5.5.1 of wolfSSL embedded TLS has bug fixes and new features including: * Don't over-allocate memory for DTLS fragments * Add WOLFSSL_ATECC_TFLXTLS for Atmel port * SHA-3 performance improvements with x86_64 assembly -* Add code to fallback to S/W if TSIP cannot handle +* Add code to fallback to S/W if TSIP cannot handle * Improves entropy with VxWorks * Make time in milliseconds 64-bits for longer session ticket lives * Support for setting cipher list with bytes * wolfSSL_set1_curves_list(), wolfSSL_CTX_set1_curves_list() improvements * Add to RSAES-OAEP key parsing for pkcs7 * Add missing DN nid to work with PrintName() -* SP int: default to 16 bit word size when NO_64BIT defined +* SP int: default to 16 bit word size when NO_64BIT defined * Limit the amount of fragments we store per a DTLS connection and error out when max limit is reached * Detect when certificate's RSA public key size is too big and fail on loading of certificate ## Fixes * Fix for async with OCSP non-blocking in `ProcessPeerCerts` * Fixes for building with 32-bit and socket size sign/unsigned mismatch -* Fix Windows CMakeList compiler options -* TLS 1.3 Middle-Box compat: fix missing brace -* Configuration consistency fixes for RSA keys and way to force disable of private keys +* Fix Windows CMakeList compiler options +* TLS 1.3 Middle-Box compat: fix missing brace +* Configuration consistency fixes for RSA keys and way to force disable of private keys * Fix for Aarch64 Mac M1 SP use * Fix build errors and warnings for MSVC with DTLS 1.3 * Fix HMAC compat layer function for SHA-1 @@ -907,9 +1101,9 @@ Release 5.5.1 of wolfSSL embedded TLS has bug fixes and new features including: * Check return from call to wc_Time * SP math: fix build configuration with opensslall * Fix for async session tickets -* SP int mp_init_size fixes when SP_WORD_SIZE == 8 +* SP int mp_init_size fixes when SP_WORD_SIZE == 8 * Ed. function to make public key now checks for if the private key flag is set -* Fix HashRaw WC_SHA256_DIGEST_SIZE for wc_Sha256GetHash +* Fix HashRaw WC_SHA256_DIGEST_SIZE for wc_Sha256GetHash * Fix for building with PSK only * Set correct types in wolfSSL_sk_*_new functions * Sanity check that size passed to mp_init_size() is no more than SP_INT_DIGITS @@ -1023,7 +1217,7 @@ CVE-2020-12966 https://www.amd.com/en/corporate/product-security/bulletin/amd-sb * Update SP math all to not use sp_int_word when SQR_MUL_ASM is available ### SP Math Fixes * Fixes for constant time with div function -* Fix casting warnings for Windows builds and assembly changes to support XMM6-15 being non-volatile +* Fix casting warnings for Windows builds and assembly changes to support XMM6-15 being non-volatile * Fix for div_word when not using div function * Fixes for user settings with SP ASM and ED/Curve25519 small * Additional Wycheproof tests ran and fixes @@ -1203,7 +1397,7 @@ Release 5.3.0 of wolfSSL embedded TLS has bug fixes and new features including: ### Math Library Fixes * Sanity check with SP math that ECC points ordinates are not greater than modulus length * Additional sanity checks that _sp_add_d does not error due to overflow -* Wycheproof fixes, testing integration, and fixes for AVX / AArch64 ASM edge case tests +* Wycheproof fixes, testing integration, and fixes for AVX / AArch64 ASM edge case tests * TFM fp_div_2_ct rework to avoid potential overflow ### Misc. @@ -1444,7 +1638,7 @@ Release 5.1.0 of wolfSSL embedded TLS has bug fixes and new features including: ###### PORT Fixes * Building with Android wpa_supplicant and KeyStore * Setting initial value of CA certificate with TSIP enabled -* Cryptocell ECC build fix and fix with RSA disabled +* Cryptocell ECC build fix and fix with RSA disabled * IoT-SAFE improvement for Key/File slot ID size, fix for C++ compile, and fixes for retrieving the public key after key generation ###### Math Library Fixes @@ -1583,7 +1777,7 @@ Release 5.0.0 of wolfSSL embedded TLS has bug fixes and new features including: - SSL_SESSION_has_ticket() - SSL_SESSION_get_ticket_lifetime_hint() - DIST_POINT_new - - DIST_POINT_free + - DIST_POINT_free - DIST_POINTS_free - CRL_DIST_POINTS_free - sk_DIST_POINT_push @@ -1746,7 +1940,7 @@ Release 4.8.0 of wolfSSL embedded TLS has bug fixes and new features including: ### Vulnerabilities * [Low] CVE-2021-37155: OCSP request/response verification issue. In the case that the serial number in the OCSP request differs from the serial number in the OCSP response the error from the comparison was not resulting in a failed verification. We recommend users that have wolfSSL version 4.6.0 and 4.7.0 with OCSP enabled update their version of wolfSSL. Version 4.5.0 and earlier are not affected by this report. Thanks to Rainer Mueller-Amersdorffer, Roee Yankelevsky, Barak Gutman, Hila Cohen and Shoshi Berko (from CYMOTIVE Technologies and CARIAD) for the report. -* [Low] CVE-2021-24116: Side-Channel cache look up vulnerability in base64 PEM decoding for versions of wolfSSL 4.5.0 and earlier. Versions 4.6.0 and up contain a fix and do not need to be updated for this report. If decoding a PEM format private key using version 4.5.0 and older of wolfSSL then we recommend updating the version of wolfSSL used. Thanks to Florian Sieck, Jan Wichelmann, Sebastian Berndt and Thomas Eisenbarth for the report. +* [Low] CVE-2021-24116: Side-Channel cache look up vulnerability in base64 PEM decoding for versions of wolfSSL 4.5.0 and earlier. Versions 4.6.0 and up contain a fix and do not need to be updated for this report. If decoding a PEM format private key using version 4.5.0 and older of wolfSSL then we recommend updating the version of wolfSSL used. Thanks to Florian Sieck, Jan Wichelmann, Sebastian Berndt and Thomas Eisenbarth for the report. ### New Feature Additions ###### New Product diff --git a/README b/README index 3fa99a5..2b462bc 100644 --- a/README +++ b/README @@ -70,111 +70,197 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.7.2 (July 08, 2024) +# wolfSSL Release 5.7.4 (Oct 24, 2024) -Release 5.7.2 has been developed according to wolfSSL's development and QA +Release 5.7.4 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -## Vulnerabilities -* [Medium] CVE-2024-1544 -Potential ECDSA nonce side channel attack in versions of wolfSSL before 5.6.6 with wc_ecc_sign_hash calls. Generating the ECDSA nonce k samples a random number r and then truncates this randomness with a modular reduction mod n where n is the order of the elliptic curve. Analyzing the division through a control-flow revealing side-channel reveals a bias in the most significant bits of k. Depending on the curve this is either a negligible bias or a significant bias large enough to reconstruct k with lattice reduction methods. Thanks to Luca Wilke, Florian Sieck and Thomas Eisenbarth (University of Lübeck) for reporting the vulnerability. Details will appear in the proceedings of CCS 24. -Fixed https://github.com/wolfSSL/wolfssl/pull/7020 - - -* [Medium] CVE-2024-5288 -A private key blinding operation, enabled by defining the macro WOLFSSL_BLIND_PRIVATE_KEY, was added to mitigate a potential row hammer attack on ECC operations. If performing ECC private key operations in an environment where a malicious user could gain fine control over the device and perform row hammer style attacks it is recommended to update the version of wolfSSL used and to build with WOLFSSL_BLIND_PRIVATE_KEY defined. Thanks to Kemal Derya, M. Caner Tol, Berk Sunar for the report (Vernam Applied Cryptography and Cybersecurity Lab at Worcester Polytechnic Institute) -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7416 - - -* [Low] When parsing a provided maliciously crafted certificate directly using wolfSSL API, outside of a TLS connection, a certificate with an excessively large number of extensions could lead to a potential DoS. There are existing sanity checks during a TLS handshake with wolfSSL which mitigate this issue. Thanks to Bing Shi for the report. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7597 +PR stands for Pull Request, and PR references a GitHub pull request + number where the code change was added. -* [Low] CVE-2024-5991 -In the function MatchDomainName(), input param str is treated as a NULL terminated string despite being user provided and unchecked. Specifically, the Openssl compatibility function X509_check_host() takes in a pointer and length to check against, with no requirements that it be NULL terminated. While calling without a NULL terminated string is very uncommon, it is still technically allowed. If a caller was attempting to do a name check on a non*NULL terminated buffer, the code would read beyond the bounds of the input array until it found a NULL terminator. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7604 -* [Medium] CVE-2024-5814 -A malicious TLS1.2 server can force a TLS1.3 client with downgrade capability to use a ciphersuite that it did not agree to and achieve a successful connection. This is because, aside from the extensions, the client was skipping fully parsing the server hello when downgrading from TLS 1.3. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7619 - -* [Medium] OCSP stapling version 2 response verification bypass issue when a crafted response of length 0 is received. Found with internal testing. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 - -* [Medium] OCSP stapling version 2 revocation bypass with a retry of a TLS connection attempt. A revoked CA certificate could incorrectly be loaded into the trusted signers list and used in a repeat connection attempt. Found with internal testing. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 +## Vulnerabilities +* [Low] When the OpenSSL compatibility layer is enabled, certificate + verification behaved differently in wolfSSL than OpenSSL, in the + X509_STORE_add_cert() and X509_STORE_load_locations() implementations. + Previously, in cases where an application explicitly loaded an intermediate + certificate, wolfSSL was verifying only up to that intermediate certificate, + rather than verifying up to the root CA. This only affects use cases where the + API is called directly, and does not affect TLS connections. Users that call + the API X509_STORE_add_cert() or X509_STORE_load_locations() directly in their + applications are recommended to update the version of wolfSSL used or to have + additional sanity checks on certificates loaded into the X509_STORE when + verifying a certificate. (https://github.com/wolfSSL/wolfssl/pull/8087) + + +## PQC TLS Experimental Build Fix +* When using TLS with post quantum algorithms enabled, the connection uses a + smaller EC curve than agreed on. Users building with --enable-experimental and + enabling PQC cipher suites with TLS connections are recommended to update the + version of wolfSSL used. Thanks to Daniel Correa for the report. + (https://github.com/wolfSSL/wolfssl/pull/8084) ## New Feature Additions -* Added Dilithium/ML-DSA: Implementation of ML-DSA-44/65/87 (PR 7622) -* AES RISC-V 64-bit ASM: ECB/CBC/CTR/GCM/CCM (PR 7569) -* Added CUDA support for AES encryption (PR 7436) -* Added support for gRPC (PR 7445) -* Added function wc_RsaPrivateKeyDecodeRaw to import raw RSA private keys (PR 7608) -* Added crypto callback for SHA-3 (PR 7670) -* Support for Infineon Modus Toolbox with wolfSSL (PR 7369) -* Allow user to send a user_canceled alert by calling wolfSSL_SendUserCanceled (PR 7590) -* C# wrapper SNI support added (PR 7610) -* Quantum-safe algorithm support added to the Linux kernel module (PR 7574) -* Support for NIST 800-56C Option 1 KDF, using the macro WC_KDF_NIST_SP_800_56C added (PR 7589) -* AES-XTS streaming mode added, along with hardware acceleration and kernel module use (PR 7522, 7560, 7424) -* PlatformIO FreeRTOS with ESP build and addition of benchmark and test example applications (PR 7528, 7413, 7559, 7542) +* RISC-V 64 new assembly optimizations added for SHA-256, SHA-512, ChaCha20, + Poly1305, and SHA-3 (PR 7758,7833,7818,7873,7916) +* Implement support for Connection ID (CID) with DTLS 1.2 (PR 7995) +* Add support for (DevkitPro)libnds (PR 7990) +* Add port for Mosquitto OSP (Open Source Project) (PR 6460) +* Add port for init sssd (PR 7781) +* Add port for eXosip2 (PR 7648) +* Add support for STM32G4 (PR 7997) +* Add support for MAX32665 and MAX32666 TPU HW and ARM ASM Crypto Callback + Support (PR 7777) +* Add support for building wolfSSL to be used in libspdm (PR 7869) +* Add port for use with Nucleus Plus 2.3 (PR 7732) +* Initial support for RFC5755 x509 attribute certificates (acerts). Enabled with + --enable-acert (PR 7926) +* PKCS#11 RSA Padding offload allows tokens to perform CKM_RSA_PKCS + (sign/encrypt), CKM_RSA_PKCS_PSS (sign), and CKM_RSA_PKCS_OAEP (encrypt). + (PR 7750) +* Added “new” and “delete” style functions for heap/pool allocation and freeing + of low level crypto structures (PR 3166 and 8089) ## Enhancements and Optimizations -* Expanded STM32 AES hardware acceleration support for use with STM32H5 (PR 7578) -* Adjusted wc_xmss and wc_lms settings to support use with wolfBoot (PR 7393) -* Added the --enable-rpk option to autotools build for using raw public key support (PR 7379) -* SHA-3 Thumb2, ARM32 assembly implementation added (PR 7667) -* Improvements to RSA padding to expose Pad/Unpad APIs (PR 7612) -* Updates and API additions for supporting socat version 1.8.0.0 (PR 7594) -* cmake build improvements, expanding build options with SINGLE_THREADED and post-quantum algorithms, adjusting the generation of options.h file and using “yes;no” boolean instead of strings (PR 7611, 7546, 7479, 7480, 7380) -* Improvements for Renesas RZ support (PR 7474) -* Improvements to dual algorithm certificates for post-quantum keys (PR 7286) -* Added wolfSSL_SessionIsSetup so the user can check if a session ticket has been sent by the server (PR 7430) -* hostap updates: Implement PACs for EAP-FAST and filter cipher list on TLS version change (PR 7446) -* Changed subject name comparison to match different upper and lower cases (PR 7420) -* Support for DTLS 1.3 downgrade when using PSK (PR 7367) -* Update to static memory build for more generic memory pools used (PR 7418) -* Improved performance of Kyber C implementation (PR 7654) -* Support for ECC_CACHE_CURVE with no malloc (PR 7490) -* Added the configure option --enable-debug-trace-errcodes (macro WOLFSSL_DEBUG_TRACE_ERROR_CODES) which enables more debug tracking of error code values (PR 7634) -* Enhanced wc_MakeRsaKey and wc_RsaKeyToDer to work with WOLFSSL_NO_MALLOC (PR 7362) -* Improvements to assembly implementations of ChaCha20 and Poly1305 ASM for use with MSVC (PR 7319) -* Cortex-M inline assembly labels with unique number appended (PR 7649) -* Added secret logging callback to TLS <= 1.2, enabled with the macro HAVE_SECRET_CALLBACK (PR 7372) -* Made wc_RNG_DRBG_Reseed() a public wolfCrypt API (PR 7386) -* Enabled DES3 support without the DES3 ciphers. To re-enable DES3 cipher suites, use the configure flag --enable-des3-tls-suites (PR 7315) -* Added stubs required for latest nginx (1.25.5) (PR 7449) -* Added option for using a custom salt with the function wc_ecc_ctx_set_own_salt (PR 7552) -* Added PQ files for Windows (PR 7419) -* Enhancements to static memory feature, adding the option for a global heap hint (PR 7478) and build options for a lean or debug setting, enabled with --enable-staticmemory=small or --enable-staticmemory=debug (PR 7597) -* Updated --enable-jni to define SESSION_CERTS for wolfJSSE (PR 7557) -* Exposed DTLS in Ada wrapper and updated examples (PR 7397) -* Added additional minimum TLS extension size sanity checks (PR 7602) -* ESP improvements: updating the examples and libraries, updates for Apple HomeKit SHA/SRP, and fix for endianness with SHA512 software fallback (PR 7607, 7392, 7505, 7535) -* Made the wc_CheckCertSigPubKey API publicly available with the define of the macro WOLFSSL_SMALL_CERT_VERIFY (PR 7599) -* Added an alpha/preview of additional FIPS 140-3 full submission, bringing additional algorithms such as SRTP-KDF, AES-XTS, GCM streaming, AES-CFB, ED25519, and ED448 into the FIPS module boundary (PR 7295) -* XCODE support for v5.2.3 of the FIPS module (PR 7140) -* Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) +* Increase default max alt. names from 128 to 1024 (PR 7762) +* Added new constant time DH agree function wc_DhAgree_ct (PR 7802) +* Expanded compatibility layer with the API EVP_PKEY_is_a (PR 7804) +* Add option to disable cryptocb test software test using + --disable-cryptocb-sw-test (PR 7862) +* Add a call to certificate verify callback before checking certificate dates + (PR 7895) +* Expanded algorithms supported with the wolfCrypt CSharp wrapper. Adding + support for RNG, ECC(ECIES and ECDHE), RSA, ED25519/Curve25519, AES-GCM, and + Hashing (PR 3166) +* Expand MMCAU support for use with DES ECB (PR 7960) +* Update AES SIV to handle multiple associated data inputs (PR 7911) +* Remove HAVE_NULL_CIPHER from --enable-openssh (PR 7811) +* Removed duplicate if(NULL) checks when calling XFREE (macro does) (PR 7839) +* Set RSA_MIN_SIZE default to 2048 bits (PR 7923) +* Added support for wolfSSL to be used as the default TLS in the zephyr kernel + (PR 7731) +* Add enable provider build using --enable-wolfprovider with autotools (PR 7550) +* Renesas RX TSIP ECDSA support (PR 7685) +* Support DTLS1.3 downgrade when the server supports CID (PR 7841) +* Server-side checks OCSP even if it uses v2 multi (PR 7828) +* Add handling of absent hash params in PKCS7 bundle parsing and creation + (PR 7845) +* Add the use of w64wrapper for Poly1305, enabling Poly1305 to be used in + environments that do not have a word64 type (PR 7759) +* Update to the maxq10xx support (PR 7824) +* Add support for parsing over optional PKCS8 attributes (PR 7944) +* Add support for either side method with DTLS 1.3 (PR 8012) +* Added PKCS7 PEM support for parsing PEM data with BEGIN/END PKCS7 (PR 7704) +* Add CMake support for WOLFSSL_CUSTOM_CURVES (PR 7962) +* Add left-most wildcard matching support to X509_check_host() (PR 7966) +* Add option to set custom SKID with PKCS7 bundle creation (PR 7954) +* Building wolfSSL as a library with Ada and corrections to Alire manifest + (PR 7303,7940) +* Renesas RX72N support updated (PR 7849) +* New option WOLFSSL_COPY_KEY added to always copy the key to the SSL object + (PR 8005) +* Add the new option WOLFSSL_COPY_CERT to always copy the cert buffer for each + SSL object (PR 7867) +* Add an option to use AES-CBC with HMAC for default session ticket enc/dec. + Defaults to AES-128-CBC with HMAC-SHA256 (PR 7703) +* Memory usage improvements in wc_PRF, sha256 (for small code when many + registers are available) and sp_int objects (PR 7901) +* Change in the configure script to work around ">>" with no command. In older + /bin/sh it can be ambiguous, as used in OS’s such as FreeBSD 9.2 (PR 7876) +* Don't attempt to include system headers when not required (PR 7813) +* Certificates: DER encoding of ECC signature algorithm parameter is now + allowed to be NULL with a define (PR 7903) +* SP x86_64 asm: check for AVX2 support for VMs (PR 7979) +* Update rx64n support on gr-rose (PR 7889) +* Update FSP version to v5.4.0 for RA6M4 (PR 7994) +* Update TSIP driver version to v1.21 for RX65N RSK (PR 7993) +* Add a new crypto callback for RSA with padding (PR 7907) +* Replaced the use of pqm4 with wolfSSL implementations of Kyber/MLDSA + (PR 7924) +* Modernized memory fence support for C11 and clang (PR 7938) +* Add a CRL error override callback (PR 7986) +* Extend the X509 unknown extension callback for use with a user context + (PR 7730) +* Additional debug error tracing added with TLS (PR 7917) +* Added runtime support for library call stack traces with + –enable-debug-trace-errcodes=backtrace, using libbacktrace (PR 7846) +* Expanded C89 conformance (PR 8077) +* Expanded support for WOLFSSL_NO_MALLOC (PR 8065) +* Added support for cross-compilation of Linux kernel module (PR 7746) +* Updated Linux kernel module with support for kernel 6.11 and 6.12 (PR 7826) +* Introduce WOLFSSL_ASN_ALLOW_0_SERIAL to allow parsing of certificates with a + serial number of 0 (PR 7893) +* Add conditional repository_owner to all wolfSSL GitHub workflows (PR 7871) + +### Espressif / Arduino Updates +* Update wolfcrypt settings.h for Espressif ESP-IDF, template update (PR 7953) +* Update Espressif sha, util, mem, time helpers (PR 7955) +* Espressif _thread_local_start and _thread_local_end fix (PR 8030) +* Improve benchmark for Espressif devices (PR 8037) +* Introduce Espressif common CONFIG_WOLFSSL_EXAMPLE_NAME, Kconfig (PR 7866) +* Add wolfSSL esp-tls and Certificate Bundle Support for Espressif ESP-IDF + (PR 7936) +* Update wolfssl Release for Arduino (PR 7775) + +### Post Quantum Crypto Updates +* Dilithium: support fixed size arrays in dilithium_key (PR 7727) +* Dilithium: add option to use precalc with small sign (PR 7744) +* Allow Kyber to be built with FIPS (PR 7788) +* Allow Kyber asm to be used in the Linux kernel module (PR 7872) +* Dilithium, Kyber: Update to final specification (PR 7877) +* Dilithium: Support FIPS 204 Draft and Final Draft (PR 7909,8016) + +### ARM Assembly Optimizations +* ARM32 assembly optimizations added for ChaCha20 and Poly1305 (PR 8020) +* Poly1305 assembly optimizations improvements for Aarch64 (PR 7859) +* Poly1305 assembly optimizations added for Thumb-2 (PR 7939) +* Adding ARM ASM build option to STM32CubePack (PR 7747) +* Add ARM64 to Visual Studio Project (PR 8010) +* Kyber assembly optimizations for ARM32 and Aarch64 (PR 8040,7998) +* Kyber assembly optimizations for ARMv7E-M/ARMv7-M (PR 7706) + ## Fixes -* Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) -* Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) -* Fixed use of %rip with SHA-256 x64 assembly (PR 7409) -* Fixed OCSP response message build for DTLS (PR 7671) -* Handled edge case in wc_ecc_mulmod() with zero (PR 7532) -* Fixed RPK (Raw Public Key) to follow certificate use correctly (PR 7375) -* Added sanity check on record header with QUIC use (PR 7638) -* Added sanity check for empty directory strings in X.509 when parsing (PR 7669) -* Added sanity check on non-conforming serial number of 0 in certificates being parsed (PR 7625) -* Fixed wolfSSL_CTX_set1_sigalgs_list() to make the TLS connection conform to the selected sig hash algorithm (PR 7693) -* Various fixes for dual algorithm certificates including small stack use and support for Certificate Signing Requests (PR 7577) -* Added sanity check for critical policy extension when wolfSSL is built without policy extension support enabled (PR 7388) -* Added sanity check that the ed25519 signature is smaller than the order (PR 7513) -* Fixed Segger emNet to handle non-blocking want read/want write (PR 7581) +* ECC key load: fixes for certificates with parameters that are not default for + size (PR 7751) +* Fixes for building x86 in Visual Studio for non-windows OS (PR 7884) +* Fix for TLS v1.2 secret callback, incorrectly detecting bad master secret + (PR 7812) +* Fixes for PowerPC assembly use with Darwin and SP math all (PR 7931) +* Fix for detecting older versions of Mac OS when trying to link with + libdispatch (PR 7932) +* Fix for DTLS1.3 downgrade to DTLS1.2 when the server sends multiple handshake + packets combined into a single transmission. (PR 7840) +* Fix for OCSP to save the request if it was stored in ssl->ctx->certOcspRequest + (PR 7779) +* Fix to OCSP for searching for CA by key hash instead of ext. key id (PR 7934) +* Fix for staticmemory and singlethreaded build (PR 7737) +* Fix to not allow Shake128/256 with Xilinx AFALG (PR 7708) +* Fix to support PKCS11 without RSA key generation (PR 7738) +* Fix not calling the signing callback when using PK callbacks + TLS 1.3 + (PR 7761) +* Cortex-M/Thumb2 ASM fix label for IAR compiler (PR 7753) +* Fix with PKCS11 to iterate correctly over slotId (PR 7736) +* Stop stripping out the sequence header on the AltSigAlg extension (PR 7710) +* Fix ParseCRL_AuthKeyIdExt with ASN template to set extAuthKeyIdSet value + (PR 7742) +* Use max key length for PSK encrypt buffer size (PR 7707) +* DTLS 1.3 fix for size check to include headers and CID fixes (PR 7912,7951) +* Fix STM32 Hash FIFO and add support for STM32U5A9xx (PR 7787) +* Fix CMake build error for curl builds (PR 8021) +* SP Maths: PowerPC ASM fix to use XOR instead of LI (PR 8038) +* SSL loading of keys/certs: testing and fixes (PR 7789) +* Misc. fixes for Dilithium and Kyber (PR 7721,7765,7803,8027,7904) +* Fixes for building wolfBoot sources for PQ LMS/XMSS (PR 7868) +* Fixes for building with Kyber enabled using CMake and zephyr port (PR 7773) +* Fix for edge cases with session resumption with TLS 1.2 (PR 8097) +* Fix issue with ARM ASM with AES CFB/OFB not initializing the "left" member + (PR 8099) diff --git a/README.md b/README.md index f6b00c3..2deaa8c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.2 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.4 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -8,14 +8,18 @@ See the [Arduino-wolfSSL logs](https://downloads.arduino.cc/libraries/logs/githu ## Arduino Releases -The first Official wolfSSL Arduino Library is `5.6.6-Arduino.1`: a slightly modified, post [release 5.6.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.6.6-stable) version update. +This release of wolfSSL is version [5.7.4](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.4-stable). -The next Official wolfSSL Arduino Library is [5.7.0](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.0-stable) +Version [5.7.2](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.2-stable) of the Arduino wolfSSL was published August 3, 2024. + +The next Official wolfSSL Arduino Library was [5.7.0](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.0-stable) + +The first Official wolfSSL Arduino Library was `5.6.6-Arduino.1`: a slightly modified, post [release 5.6.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.6.6-stable) version update. See other [wolfSSL releases versions](https://github.com/wolfSSL/wolfssl/releases). The `./wolfssl-arduino.sh INSTALL` [script](https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO) can be used to install specific GitHub versions as needed. # wolfSSL Embedded SSL/TLS Library -The [wolfSSL embedded SSL library](https://www.wolfssl.com/products/wolfssl/) +The [wolfSSL embedded SSL library](https://www.wolfssl.com/products/wolfssl/) (formerly CyaSSL) is a lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments - primarily because of its small size, speed, and feature set. It is commonly used in @@ -90,111 +94,197 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.7.2 (July 08, 2024) +# wolfSSL Release 5.7.4 (Oct 24, 2024) -Release 5.7.2 has been developed according to wolfSSL's development and QA +Release 5.7.4 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -## Vulnerabilities -* [Medium] CVE-2024-1544 -Potential ECDSA nonce side channel attack in versions of wolfSSL before 5.6.6 with wc_ecc_sign_hash calls. Generating the ECDSA nonce k samples a random number r and then truncates this randomness with a modular reduction mod n where n is the order of the elliptic curve. Analyzing the division through a control-flow revealing side-channel reveals a bias in the most significant bits of k. Depending on the curve this is either a negligible bias or a significant bias large enough to reconstruct k with lattice reduction methods. Thanks to Luca Wilke, Florian Sieck and Thomas Eisenbarth (University of Lübeck) for reporting the vulnerability. Details will appear in the proceedings of CCS 24. -Fixed https://github.com/wolfSSL/wolfssl/pull/7020 - - -* [Medium] CVE-2024-5288 -A private key blinding operation, enabled by defining the macro WOLFSSL_BLIND_PRIVATE_KEY, was added to mitigate a potential row hammer attack on ECC operations. If performing ECC private key operations in an environment where a malicious user could gain fine control over the device and perform row hammer style attacks it is recommended to update the version of wolfSSL used and to build with WOLFSSL_BLIND_PRIVATE_KEY defined. Thanks to Kemal Derya, M. Caner Tol, Berk Sunar for the report (Vernam Applied Cryptography and Cybersecurity Lab at Worcester Polytechnic Institute) -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7416 - +PR stands for Pull Request, and PR references a GitHub pull request + number where the code change was added. -* [Low] When parsing a provided maliciously crafted certificate directly using wolfSSL API, outside of a TLS connection, a certificate with an excessively large number of extensions could lead to a potential DoS. There are existing sanity checks during a TLS handshake with wolfSSL which mitigate this issue. Thanks to Bing Shi for the report. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7597 -* [Low] CVE-2024-5991 -In the function MatchDomainName(), input param str is treated as a NULL terminated string despite being user provided and unchecked. Specifically, the Openssl compatibility function X509_check_host() takes in a pointer and length to check against, with no requirements that it be NULL terminated. While calling without a NULL terminated string is very uncommon, it is still technically allowed. If a caller was attempting to do a name check on a non*NULL terminated buffer, the code would read beyond the bounds of the input array until it found a NULL terminator. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7604 - -* [Medium] CVE-2024-5814 -A malicious TLS1.2 server can force a TLS1.3 client with downgrade capability to use a ciphersuite that it did not agree to and achieve a successful connection. This is because, aside from the extensions, the client was skipping fully parsing the server hello when downgrading from TLS 1.3. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7619 - -* [Medium] OCSP stapling version 2 response verification bypass issue when a crafted response of length 0 is received. Found with internal testing. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 - -* [Medium] OCSP stapling version 2 revocation bypass with a retry of a TLS connection attempt. A revoked CA certificate could incorrectly be loaded into the trusted signers list and used in a repeat connection attempt. Found with internal testing. -Fixed in github pull request https://github.com/wolfSSL/wolfssl/pull/7702 +## Vulnerabilities +* [Low] When the OpenSSL compatibility layer is enabled, certificate + verification behaved differently in wolfSSL than OpenSSL, in the + X509_STORE_add_cert() and X509_STORE_load_locations() implementations. + Previously, in cases where an application explicitly loaded an intermediate + certificate, wolfSSL was verifying only up to that intermediate certificate, + rather than verifying up to the root CA. This only affects use cases where the + API is called directly, and does not affect TLS connections. Users that call + the API X509_STORE_add_cert() or X509_STORE_load_locations() directly in their + applications are recommended to update the version of wolfSSL used or to have + additional sanity checks on certificates loaded into the X509_STORE when + verifying a certificate. (https://github.com/wolfSSL/wolfssl/pull/8087) + + +## PQC TLS Experimental Build Fix +* When using TLS with post quantum algorithms enabled, the connection uses a + smaller EC curve than agreed on. Users building with --enable-experimental and + enabling PQC cipher suites with TLS connections are recommended to update the + version of wolfSSL used. Thanks to Daniel Correa for the report. + (https://github.com/wolfSSL/wolfssl/pull/8084) ## New Feature Additions -* Added Dilithium/ML-DSA: Implementation of ML-DSA-44/65/87 (PR 7622) -* AES RISC-V 64-bit ASM: ECB/CBC/CTR/GCM/CCM (PR 7569) -* Added CUDA support for AES encryption (PR 7436) -* Added support for gRPC (PR 7445) -* Added function wc_RsaPrivateKeyDecodeRaw to import raw RSA private keys (PR 7608) -* Added crypto callback for SHA-3 (PR 7670) -* Support for Infineon Modus Toolbox with wolfSSL (PR 7369) -* Allow user to send a user_canceled alert by calling wolfSSL_SendUserCanceled (PR 7590) -* C# wrapper SNI support added (PR 7610) -* Quantum-safe algorithm support added to the Linux kernel module (PR 7574) -* Support for NIST 800-56C Option 1 KDF, using the macro WC_KDF_NIST_SP_800_56C added (PR 7589) -* AES-XTS streaming mode added, along with hardware acceleration and kernel module use (PR 7522, 7560, 7424) -* PlatformIO FreeRTOS with ESP build and addition of benchmark and test example applications (PR 7528, 7413, 7559, 7542) +* RISC-V 64 new assembly optimizations added for SHA-256, SHA-512, ChaCha20, + Poly1305, and SHA-3 (PR 7758,7833,7818,7873,7916) +* Implement support for Connection ID (CID) with DTLS 1.2 (PR 7995) +* Add support for (DevkitPro)libnds (PR 7990) +* Add port for Mosquitto OSP (Open Source Project) (PR 6460) +* Add port for init sssd (PR 7781) +* Add port for eXosip2 (PR 7648) +* Add support for STM32G4 (PR 7997) +* Add support for MAX32665 and MAX32666 TPU HW and ARM ASM Crypto Callback + Support (PR 7777) +* Add support for building wolfSSL to be used in libspdm (PR 7869) +* Add port for use with Nucleus Plus 2.3 (PR 7732) +* Initial support for RFC5755 x509 attribute certificates (acerts). Enabled with + --enable-acert (PR 7926) +* PKCS#11 RSA Padding offload allows tokens to perform CKM_RSA_PKCS + (sign/encrypt), CKM_RSA_PKCS_PSS (sign), and CKM_RSA_PKCS_OAEP (encrypt). + (PR 7750) +* Added “new” and “delete” style functions for heap/pool allocation and freeing + of low level crypto structures (PR 3166 and 8089) ## Enhancements and Optimizations -* Expanded STM32 AES hardware acceleration support for use with STM32H5 (PR 7578) -* Adjusted wc_xmss and wc_lms settings to support use with wolfBoot (PR 7393) -* Added the --enable-rpk option to autotools build for using raw public key support (PR 7379) -* SHA-3 Thumb2, ARM32 assembly implementation added (PR 7667) -* Improvements to RSA padding to expose Pad/Unpad APIs (PR 7612) -* Updates and API additions for supporting socat version 1.8.0.0 (PR 7594) -* cmake build improvements, expanding build options with SINGLE_THREADED and post-quantum algorithms, adjusting the generation of options.h file and using “yes;no” boolean instead of strings (PR 7611, 7546, 7479, 7480, 7380) -* Improvements for Renesas RZ support (PR 7474) -* Improvements to dual algorithm certificates for post-quantum keys (PR 7286) -* Added wolfSSL_SessionIsSetup so the user can check if a session ticket has been sent by the server (PR 7430) -* hostap updates: Implement PACs for EAP-FAST and filter cipher list on TLS version change (PR 7446) -* Changed subject name comparison to match different upper and lower cases (PR 7420) -* Support for DTLS 1.3 downgrade when using PSK (PR 7367) -* Update to static memory build for more generic memory pools used (PR 7418) -* Improved performance of Kyber C implementation (PR 7654) -* Support for ECC_CACHE_CURVE with no malloc (PR 7490) -* Added the configure option --enable-debug-trace-errcodes (macro WOLFSSL_DEBUG_TRACE_ERROR_CODES) which enables more debug tracking of error code values (PR 7634) -* Enhanced wc_MakeRsaKey and wc_RsaKeyToDer to work with WOLFSSL_NO_MALLOC (PR 7362) -* Improvements to assembly implementations of ChaCha20 and Poly1305 ASM for use with MSVC (PR 7319) -* Cortex-M inline assembly labels with unique number appended (PR 7649) -* Added secret logging callback to TLS <= 1.2, enabled with the macro HAVE_SECRET_CALLBACK (PR 7372) -* Made wc_RNG_DRBG_Reseed() a public wolfCrypt API (PR 7386) -* Enabled DES3 support without the DES3 ciphers. To re-enable DES3 cipher suites, use the configure flag --enable-des3-tls-suites (PR 7315) -* Added stubs required for latest nginx (1.25.5) (PR 7449) -* Added option for using a custom salt with the function wc_ecc_ctx_set_own_salt (PR 7552) -* Added PQ files for Windows (PR 7419) -* Enhancements to static memory feature, adding the option for a global heap hint (PR 7478) and build options for a lean or debug setting, enabled with --enable-staticmemory=small or --enable-staticmemory=debug (PR 7597) -* Updated --enable-jni to define SESSION_CERTS for wolfJSSE (PR 7557) -* Exposed DTLS in Ada wrapper and updated examples (PR 7397) -* Added additional minimum TLS extension size sanity checks (PR 7602) -* ESP improvements: updating the examples and libraries, updates for Apple HomeKit SHA/SRP, and fix for endianness with SHA512 software fallback (PR 7607, 7392, 7505, 7535) -* Made the wc_CheckCertSigPubKey API publicly available with the define of the macro WOLFSSL_SMALL_CERT_VERIFY (PR 7599) -* Added an alpha/preview of additional FIPS 140-3 full submission, bringing additional algorithms such as SRTP-KDF, AES-XTS, GCM streaming, AES-CFB, ED25519, and ED448 into the FIPS module boundary (PR 7295) -* XCODE support for v5.2.3 of the FIPS module (PR 7140) -* Expanded OpenSSL compatibility layer and added EC_POINT_hex2point (PR 7191) +* Increase default max alt. names from 128 to 1024 (PR 7762) +* Added new constant time DH agree function wc_DhAgree_ct (PR 7802) +* Expanded compatibility layer with the API EVP_PKEY_is_a (PR 7804) +* Add option to disable cryptocb test software test using + --disable-cryptocb-sw-test (PR 7862) +* Add a call to certificate verify callback before checking certificate dates + (PR 7895) +* Expanded algorithms supported with the wolfCrypt CSharp wrapper. Adding + support for RNG, ECC(ECIES and ECDHE), RSA, ED25519/Curve25519, AES-GCM, and + Hashing (PR 3166) +* Expand MMCAU support for use with DES ECB (PR 7960) +* Update AES SIV to handle multiple associated data inputs (PR 7911) +* Remove HAVE_NULL_CIPHER from --enable-openssh (PR 7811) +* Removed duplicate if(NULL) checks when calling XFREE (macro does) (PR 7839) +* Set RSA_MIN_SIZE default to 2048 bits (PR 7923) +* Added support for wolfSSL to be used as the default TLS in the zephyr kernel + (PR 7731) +* Add enable provider build using --enable-wolfprovider with autotools (PR 7550) +* Renesas RX TSIP ECDSA support (PR 7685) +* Support DTLS1.3 downgrade when the server supports CID (PR 7841) +* Server-side checks OCSP even if it uses v2 multi (PR 7828) +* Add handling of absent hash params in PKCS7 bundle parsing and creation + (PR 7845) +* Add the use of w64wrapper for Poly1305, enabling Poly1305 to be used in + environments that do not have a word64 type (PR 7759) +* Update to the maxq10xx support (PR 7824) +* Add support for parsing over optional PKCS8 attributes (PR 7944) +* Add support for either side method with DTLS 1.3 (PR 8012) +* Added PKCS7 PEM support for parsing PEM data with BEGIN/END PKCS7 (PR 7704) +* Add CMake support for WOLFSSL_CUSTOM_CURVES (PR 7962) +* Add left-most wildcard matching support to X509_check_host() (PR 7966) +* Add option to set custom SKID with PKCS7 bundle creation (PR 7954) +* Building wolfSSL as a library with Ada and corrections to Alire manifest + (PR 7303,7940) +* Renesas RX72N support updated (PR 7849) +* New option WOLFSSL_COPY_KEY added to always copy the key to the SSL object + (PR 8005) +* Add the new option WOLFSSL_COPY_CERT to always copy the cert buffer for each + SSL object (PR 7867) +* Add an option to use AES-CBC with HMAC for default session ticket enc/dec. + Defaults to AES-128-CBC with HMAC-SHA256 (PR 7703) +* Memory usage improvements in wc_PRF, sha256 (for small code when many + registers are available) and sp_int objects (PR 7901) +* Change in the configure script to work around ">>" with no command. In older + /bin/sh it can be ambiguous, as used in OS’s such as FreeBSD 9.2 (PR 7876) +* Don't attempt to include system headers when not required (PR 7813) +* Certificates: DER encoding of ECC signature algorithm parameter is now + allowed to be NULL with a define (PR 7903) +* SP x86_64 asm: check for AVX2 support for VMs (PR 7979) +* Update rx64n support on gr-rose (PR 7889) +* Update FSP version to v5.4.0 for RA6M4 (PR 7994) +* Update TSIP driver version to v1.21 for RX65N RSK (PR 7993) +* Add a new crypto callback for RSA with padding (PR 7907) +* Replaced the use of pqm4 with wolfSSL implementations of Kyber/MLDSA + (PR 7924) +* Modernized memory fence support for C11 and clang (PR 7938) +* Add a CRL error override callback (PR 7986) +* Extend the X509 unknown extension callback for use with a user context + (PR 7730) +* Additional debug error tracing added with TLS (PR 7917) +* Added runtime support for library call stack traces with + –enable-debug-trace-errcodes=backtrace, using libbacktrace (PR 7846) +* Expanded C89 conformance (PR 8077) +* Expanded support for WOLFSSL_NO_MALLOC (PR 8065) +* Added support for cross-compilation of Linux kernel module (PR 7746) +* Updated Linux kernel module with support for kernel 6.11 and 6.12 (PR 7826) +* Introduce WOLFSSL_ASN_ALLOW_0_SERIAL to allow parsing of certificates with a + serial number of 0 (PR 7893) +* Add conditional repository_owner to all wolfSSL GitHub workflows (PR 7871) + +### Espressif / Arduino Updates +* Update wolfcrypt settings.h for Espressif ESP-IDF, template update (PR 7953) +* Update Espressif sha, util, mem, time helpers (PR 7955) +* Espressif _thread_local_start and _thread_local_end fix (PR 8030) +* Improve benchmark for Espressif devices (PR 8037) +* Introduce Espressif common CONFIG_WOLFSSL_EXAMPLE_NAME, Kconfig (PR 7866) +* Add wolfSSL esp-tls and Certificate Bundle Support for Espressif ESP-IDF + (PR 7936) +* Update wolfssl Release for Arduino (PR 7775) + +### Post Quantum Crypto Updates +* Dilithium: support fixed size arrays in dilithium_key (PR 7727) +* Dilithium: add option to use precalc with small sign (PR 7744) +* Allow Kyber to be built with FIPS (PR 7788) +* Allow Kyber asm to be used in the Linux kernel module (PR 7872) +* Dilithium, Kyber: Update to final specification (PR 7877) +* Dilithium: Support FIPS 204 Draft and Final Draft (PR 7909,8016) + +### ARM Assembly Optimizations +* ARM32 assembly optimizations added for ChaCha20 and Poly1305 (PR 8020) +* Poly1305 assembly optimizations improvements for Aarch64 (PR 7859) +* Poly1305 assembly optimizations added for Thumb-2 (PR 7939) +* Adding ARM ASM build option to STM32CubePack (PR 7747) +* Add ARM64 to Visual Studio Project (PR 8010) +* Kyber assembly optimizations for ARM32 and Aarch64 (PR 8040,7998) +* Kyber assembly optimizations for ARMv7E-M/ARMv7-M (PR 7706) + ## Fixes -* Fixed the NXP MMCAU HW acceleration for SHA-256 (PR 7389) -* Fixed AES-CFB1 encrypt/decrypt on size (8*x-1) bits (PR 7431) -* Fixed use of %rip with SHA-256 x64 assembly (PR 7409) -* Fixed OCSP response message build for DTLS (PR 7671) -* Handled edge case in wc_ecc_mulmod() with zero (PR 7532) -* Fixed RPK (Raw Public Key) to follow certificate use correctly (PR 7375) -* Added sanity check on record header with QUIC use (PR 7638) -* Added sanity check for empty directory strings in X.509 when parsing (PR 7669) -* Added sanity check on non-conforming serial number of 0 in certificates being parsed (PR 7625) -* Fixed wolfSSL_CTX_set1_sigalgs_list() to make the TLS connection conform to the selected sig hash algorithm (PR 7693) -* Various fixes for dual algorithm certificates including small stack use and support for Certificate Signing Requests (PR 7577) -* Added sanity check for critical policy extension when wolfSSL is built without policy extension support enabled (PR 7388) -* Added sanity check that the ed25519 signature is smaller than the order (PR 7513) -* Fixed Segger emNet to handle non-blocking want read/want write (PR 7581) +* ECC key load: fixes for certificates with parameters that are not default for + size (PR 7751) +* Fixes for building x86 in Visual Studio for non-windows OS (PR 7884) +* Fix for TLS v1.2 secret callback, incorrectly detecting bad master secret + (PR 7812) +* Fixes for PowerPC assembly use with Darwin and SP math all (PR 7931) +* Fix for detecting older versions of Mac OS when trying to link with + libdispatch (PR 7932) +* Fix for DTLS1.3 downgrade to DTLS1.2 when the server sends multiple handshake + packets combined into a single transmission. (PR 7840) +* Fix for OCSP to save the request if it was stored in ssl->ctx->certOcspRequest + (PR 7779) +* Fix to OCSP for searching for CA by key hash instead of ext. key id (PR 7934) +* Fix for staticmemory and singlethreaded build (PR 7737) +* Fix to not allow Shake128/256 with Xilinx AFALG (PR 7708) +* Fix to support PKCS11 without RSA key generation (PR 7738) +* Fix not calling the signing callback when using PK callbacks + TLS 1.3 + (PR 7761) +* Cortex-M/Thumb2 ASM fix label for IAR compiler (PR 7753) +* Fix with PKCS11 to iterate correctly over slotId (PR 7736) +* Stop stripping out the sequence header on the AltSigAlg extension (PR 7710) +* Fix ParseCRL_AuthKeyIdExt with ASN template to set extAuthKeyIdSet value + (PR 7742) +* Use max key length for PSK encrypt buffer size (PR 7707) +* DTLS 1.3 fix for size check to include headers and CID fixes (PR 7912,7951) +* Fix STM32 Hash FIFO and add support for STM32U5A9xx (PR 7787) +* Fix CMake build error for curl builds (PR 8021) +* SP Maths: PowerPC ASM fix to use XOR instead of LI (PR 8038) +* SSL loading of keys/certs: testing and fixes (PR 7789) +* Misc. fixes for Dilithium and Kyber (PR 7721,7765,7803,8027,7904) +* Fixes for building wolfBoot sources for PQ LMS/XMSS (PR 7868) +* Fixes for building with Kyber enabled using CMake and zephyr port (PR 7773) +* Fix for edge cases with session resumption with TLS 1.2 (PR 8097) +* Fix issue with ARM ASM with AES CFB/OFB not initializing the "left" member + (PR 8099) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/examples/wolfssl_client/wolfssl_client.ino b/examples/wolfssl_client/wolfssl_client.ino index 21a84de..e4727dc 100644 --- a/examples/wolfssl_client/wolfssl_client.ino +++ b/examples/wolfssl_client/wolfssl_client.ino @@ -1,6 +1,6 @@ /* wolfssl_client.ino * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/examples/wolfssl_server/README.md b/examples/wolfssl_server/README.md index 523eb08..a707357 100644 --- a/examples/wolfssl_server/README.md +++ b/examples/wolfssl_server/README.md @@ -13,7 +13,7 @@ Additional examples can be found on [wolfSSL/wolfssl-examples](https://github.co ## Connect with an Arduino Sketch -See the companion [Arduino Sketch Client](../wolfssl_client/wolfssl_client.ino). +See the companion [Arduino Sketch Client](../wolfssl_client/wolfssl_client.ino). ## Connect with Linux Client @@ -35,7 +35,7 @@ press the reset button or power cycle the Arduino before making a connection. Here's one possible script to test the server from a command-line client: ```bash -#!/bin/bash +#!/usr/bin/env bash echo "client log " > client_log.txt counter=1 THIS_ERR=0 diff --git a/examples/wolfssl_server/wolfssl_server.ino b/examples/wolfssl_server/wolfssl_server.ino index 3a89432..387052c 100644 --- a/examples/wolfssl_server/wolfssl_server.ino +++ b/examples/wolfssl_server/wolfssl_server.ino @@ -1,6 +1,6 @@ /* wolfssl_server.ino * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/library.json.pio b/library.json.pio index b5f5981..220b438 100644 --- a/library.json.pio +++ b/library.json.pio @@ -1,7 +1,7 @@ { "name": "Arduino-wolfSSL", - "version": "5.7.2", - "description": "5.7.2 (Arduino-wolfSSL for PlatformIO) A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments.", + "version": "5.7.4", + "description": "5.7.4 (Arduino-wolfSSL for PlatformIO) A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments.", "keywords": "FIPS, DO-178, TLS, DTLS, DSA, PSK, X.509, RSA, ECC, AES, GCM, PQ, SHA, SHA256, 3DES, SHA512, MD5, ASN, CMAC, Blake, camellia, ChaCha, ChaCha20, DH, OCSP, ALPN, SNI, CRL, dilithium, ed25519, ed448, kdf, pkcs7, pkcs12, poly1305, Curve25519, sakke, SM, SM2, SM3, SM4, TFM, PKI, SRP, wolfcrypt, wolfssl, Post-quantum cryptography, Certificate management, SSL-TLS handshake, Session caching, Hash, Secure hashing, Public key infrastructure, Cryptanalysis, Lightweight cryptography, Hardware-based security", "repository": { "type": "git", diff --git a/library.properties b/library.properties index 5f7d802..d90b539 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.7.2 +version=5.7.4 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/library.properties.pio b/library.properties.pio index 9d1ac56..f772f1f 100644 --- a/library.properties.pio +++ b/library.properties.pio @@ -1,5 +1,5 @@ name=Arduino-wolfSSL -version=5.7.2 +version=5.7.4 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index 340cbfd..ac4eb03 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,10 +24,9 @@ #endif #include -#if defined(OPENSSL_EXTRA) && !defined(_WIN32) +#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ - #undef _GNU_SOURCE - #define _GNU_SOURCE + #define _GNU_SOURCE 1 #endif #if !defined(WOLFSSL_BIO_INCLUDED) @@ -161,7 +160,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->wrSz = 0; bio->mem_buf->length = 0; } - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { @@ -180,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } bio->mem_buf->length = (size_t)bio->wrSz; - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } } else { @@ -217,11 +216,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return WOLFSSL_FATAL_ERROR; bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_read((WOLFSSL*)bio->ptr, buf, len); + ret = wolfSSL_read(bio->ptr.ssl, buf, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -235,15 +234,15 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -290,6 +289,9 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom read */ if (bio->method && bio->method->readCb) { ret = bio->method->readCb(bio, (char*)buf, len); @@ -302,19 +304,22 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) break; case WOLFSSL_BIO_BIO: /* read BIOs */ ret = wolfSSL_BIO_BIO_read(bio, buf, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_read(bio, buf, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFREAD(buf, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, (size_t)len); + ret = (int)XREAD(bio->num.fd, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -345,14 +350,52 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Recv(bio->num, (char*)buf, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + else { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + ret = wolfIO_RecvFrom(bio->num.fd, &bio->peer_addr, + (char*)buf, len, 0); + } + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (!inhibit_flow_increment)) { + bio->bytes_read += (word32)ret; + } +#endif + /* case where front of list is done */ if (bio == front) { break; /* at front of list so be done */ @@ -409,8 +452,9 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } } else { - if (Base64_Encode((const byte*)data, inLen, NULL, &sz) != - LENGTH_ONLY_E) { + if (Base64_Encode((const byte*)data, inLen, NULL, &sz) + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -468,16 +512,16 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_ENTER("wolfSSL_BIO_SSL_write"); - if (bio->ptr == NULL) { + if (bio->ptr.ssl == NULL) { return BAD_FUNC_ARG; } bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_write((WOLFSSL*)bio->ptr, data, len); + ret = wolfSSL_write(bio->ptr.ssl, data, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -576,8 +620,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, } XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); - bio->ptr = bio->mem_buf->data; - bio->num = (int)bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; bio->wrSz += len; bio->wrIdx += len; @@ -598,14 +642,14 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -647,6 +691,9 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom write */ if (bio->method && bio->method->writeCb) { ret = bio->method->writeCb(bio, (const char*)data, len); @@ -672,19 +719,22 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } case WOLFSSL_BIO_BIO: /* write bios */ ret = wolfSSL_BIO_BIO_write(bio, data, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_write(bio, data, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFWRITE(data, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, (size_t)len); + ret = (int)XWRITE(bio->num.fd, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -725,14 +775,50 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Send(bio->num, (char*)data, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + else if (bio->peer_addr.sa.sa_family == AF_UNSPEC) + ret = SOCKET_ERROR_E; + else + ret = wolfIO_SendTo(bio->num.fd, &bio->peer_addr, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (! inhibit_flow_increment)) + bio->bytes_written += (word32)ret; +#endif + /* advance to the next bio in list */ bio = bio->next; } @@ -748,7 +834,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) (const char*)data, len, 0, ret); } - if (frmt != NULL) { + if (front != NULL) { XFREE(frmt, front->heap, DYNAMIC_TYPE_TMP_BUFFER); } @@ -793,6 +879,49 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) case BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; + +#ifdef WOLFSSL_HAVE_BIO_ADDR + case BIO_CTRL_DGRAM_CONNECT: + case BIO_CTRL_DGRAM_SET_PEER: + { + socklen_t addr_size; + if (parg == NULL) { + ret = WOLFSSL_FAILURE; + break; + } + addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + ret = WOLFSSL_SUCCESS; + break; + } + + case BIO_CTRL_DGRAM_SET_CONNECTED: + if (parg == NULL) { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + bio->connected = 0; + } + else { + socklen_t addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + bio->connected = 1; + } + ret = WOLFSSL_SUCCESS; + break; + + case BIO_CTRL_DGRAM_QUERY_MTU: + ret = 0; /* not implemented */ + break; + +#endif /* WOLFSSL_HAVE_BIO_ADDR */ + default: WOLFSSL_MSG("CMD not yet implemented"); ret = WOLFSSL_FAILURE; @@ -826,8 +955,51 @@ int wolfSSL_BIO_up_ref(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } + +#ifdef WOLFSSL_HAVE_BIO_ADDR +WOLFSSL_BIO_ADDR *wolfSSL_BIO_ADDR_new(void) { + WOLFSSL_BIO_ADDR *addr = + (WOLFSSL_BIO_ADDR *)XMALLOC(sizeof(*addr), NULL, DYNAMIC_TYPE_BIO); + if (addr) + addr->sa.sa_family = AF_UNSPEC; + return addr; +} + +void wolfSSL_BIO_ADDR_free(WOLFSSL_BIO_ADDR *addr) { + XFREE(addr, NULL, DYNAMIC_TYPE_BIO); +} + +void wolfSSL_BIO_ADDR_clear(WOLFSSL_BIO_ADDR *addr) { + if (addr == NULL) + return; + XMEMSET(addr, 0, sizeof(*addr)); + addr->sa.sa_family = AF_UNSPEC; +} + +socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr) { + switch (addr->sa.sa_family) { +#ifndef WOLFSSL_NO_BIO_ADDR_IN + case AF_INET: + return sizeof(addr->sa_in); +#endif +#ifdef WOLFSSL_IPV6 + case AF_INET6: + return sizeof(addr->sa_in6); #endif +#if defined(HAVE_SYS_UN_H) && !defined(WOLFSSL_NO_SOCKADDR_UN) + case AF_UNIX: + return sizeof(addr->sa_un); +#endif + default: + /* must return zero if length can't be determined, to avoid buffer + * overruns in callers. + */ + return 0; + } +} +#endif /* WOLFSSL_HAVE_BIO_ADDR */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ /* helper function for wolfSSL_BIO_gets * size till a newline is hit @@ -888,15 +1060,15 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (((XFILE)bio->ptr) == XBADFILE) { + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_BIO_ERROR; } #if defined(MICRIUM) || defined(LSR_FS) || defined(EBSNET) WOLFSSL_MSG("XFGETS not ported for this system yet"); - ret = XFGETS(buf, sz, (XFILE)bio->ptr); + ret = XFGETS(buf, sz, bio->ptr.fh); #else - if (XFGETS(buf, sz, (XFILE)bio->ptr) != NULL) { + if (XFGETS(buf, sz, bio->ptr.fh) != NULL) { ret = (int)XSTRLEN(buf); } else { @@ -972,13 +1144,13 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) #ifndef WOLFCRYPT_ONLY /* call final on hash */ case WOLFSSL_BIO_MD: - if (wolfSSL_EVP_MD_CTX_size((WOLFSSL_EVP_MD_CTX*)bio->ptr) > sz) { + if (wolfSSL_EVP_MD_CTX_size(bio->ptr.md_ctx) > sz) { WOLFSSL_MSG("Output buffer was too small for digest"); ret = WOLFSSL_FAILURE; } else { unsigned int szOut = 0; - ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, + ret = wolfSSL_EVP_DigestFinal(bio->ptr.md_ctx, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { ret = (int)szOut; @@ -1133,8 +1305,8 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) } #ifndef WOLFCRYPT_ONLY - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr != NULL) { - return (long)wolfSSL_pending((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { + return (long)wolfSSL_pending(bio->ptr.ssl); } #endif @@ -1162,7 +1334,7 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) { WOLFSSL_BIO* front = bio; - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_get_mem_ptr"); @@ -1188,7 +1360,10 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio = bio->prev; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } #ifdef OPENSSL_ALL @@ -1208,8 +1383,8 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; - bio->num = (int)bio->mem_buf->max; - bio->ptr = bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->wrIdx = 0; bio->rdIdx = 0; @@ -1242,15 +1417,16 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } - if (bio->ptr != NULL) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data != NULL) { + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr = (byte*)XMALLOC(size, bio->heap, DYNAMIC_TYPE_OPENSSL); - if (bio->ptr == NULL) { + bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); bio->wrSz = 0; - bio->num = 0; + bio->num.length = 0; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1261,13 +1437,13 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num = (int)size; + bio->num.length = size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { - bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = (size_t)bio->num; - bio->mem_buf->max = (size_t)bio->num; + bio->mem_buf->data = (char*)bio->ptr.mem_buf_data; + bio->mem_buf->length = bio->num.length; + bio->mem_buf->max = bio->num.length; } return WOLFSSL_SUCCESS; @@ -1295,12 +1471,12 @@ int wolfSSL_BIO_make_bio_pair(WOLFSSL_BIO *b1, WOLFSSL_BIO *b2) } /* set default write size if not already set */ - if (b1->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b1, + if (b1->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b1, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - if (b2->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b2, + if (b2->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b2, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -1341,7 +1517,7 @@ int wolfSSL_BIO_nread0(WOLFSSL_BIO *bio, char **buf) WOLFSSL_BIO* pair = bio->pair; /* case where have wrapped around write buffer */ - *buf = (char*)pair->ptr + pair->rdIdx; + *buf = (char*)pair->ptr.mem_buf_data + pair->rdIdx; if (pair->wrIdx > 0 && pair->rdIdx >= pair->wrIdx) { return pair->wrSz - pair->rdIdx; } @@ -1373,7 +1549,7 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { /* special case if asking to read 0 bytes */ if (num == 0) { - *buf = (char*)bio->pair->ptr + bio->pair->rdIdx; + *buf = (char*)bio->pair->ptr.mem_buf_data + bio->pair->rdIdx; return 0; } @@ -1387,6 +1563,9 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) sz = num; } bio->pair->rdIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->pair->bytes_read += (word32)sz; +#endif /* check if have read to the end of the buffer and need to reset */ if (bio->pair->rdIdx == bio->pair->wrSz) { @@ -1424,7 +1603,7 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { if (num == 0) { - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; return 0; } @@ -1463,8 +1642,11 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (num < sz) { sz = num; } - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; bio->wrIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->bytes_written += (word32)sz; +#endif /* if at the end of the buffer and space for wrap around then set * write index back to 0 */ @@ -1476,6 +1658,37 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) return sz; } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS +word64 wolfSSL_BIO_number_read(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_read; + bio = bio->next; + } + + return ret; +} + +word64 wolfSSL_BIO_number_written(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_written; + bio = bio->next; + } + + return ret; +} +#endif /* WOLFSSL_BIO_HAVE_FLOW_STATS */ /* Reset BIO to initial state */ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) @@ -1491,16 +1704,16 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (XFSEEK((XFILE)bio->ptr, 0, XSEEK_SET) != 0) + if (XFSEEK(bio->ptr.fh, 0, XSEEK_SET) != 0) return WOLFSSL_BIO_ERROR; else - return 0; + return WOLFSSL_SUCCESS; #endif case WOLFSSL_BIO_BIO: bio->rdIdx = 0; bio->wrIdx = 0; - return 0; + return WOLFSSL_SUCCESS; case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; @@ -1510,27 +1723,27 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) } else { bio->wrSz = 0; - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; - bio->num = 0; + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; + bio->num.length = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = NULL; bio->mem_buf->length = 0; bio->mem_buf->max = 0; } } - return 0; + return WOLFSSL_SUCCESS; #ifndef WOLFCRYPT_ONLY case WOLFSSL_BIO_MD: - if (bio->ptr != NULL) { + if (bio->ptr.md_ctx != NULL) { const WOLFSSL_EVP_MD* md = - wolfSSL_EVP_MD_CTX_md((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_cleanup((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_init((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_DigestInit((WOLFSSL_EVP_MD_CTX*)bio->ptr, md); + wolfSSL_EVP_MD_CTX_md(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_cleanup(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_init(bio->ptr.md_ctx); + wolfSSL_EVP_DigestInit(bio->ptr.md_ctx, md); } - return 0; + return WOLFSSL_SUCCESS; #endif /* WOLFCRYPT_ONLY */ default: @@ -1580,7 +1793,7 @@ long wolfSSL_BIO_set_fp(WOLFSSL_BIO *bio, XFILE fp, int c) } bio->shutdown = (byte)c; - bio->ptr = (XFILE)fp; + bio->ptr.fh = fp; return WOLFSSL_SUCCESS; } @@ -1598,7 +1811,7 @@ long wolfSSL_BIO_get_fp(WOLFSSL_BIO *bio, XFILE* fp) return WOLFSSL_FAILURE; } - *fp = (XFILE)bio->ptr; + *fp = bio->ptr.fh; return WOLFSSL_SUCCESS; } @@ -1613,8 +1826,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (((XFILE)bio->ptr) != XBADFILE && bio->shutdown == BIO_CLOSE) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + XFCLOSE(bio->ptr.fh); } /* 'b' flag is ignored on POSIX targets, but on Windows it assures @@ -1622,8 +1835,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) * between the size and contents of the representation in memory and on * disk. */ - bio->ptr = XFOPEN(name, "wb"); - if (((XFILE)bio->ptr) == XBADFILE) { + bio->ptr.fh = XFOPEN(name, "wb"); + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } bio->shutdown = BIO_CLOSE; @@ -1640,13 +1853,13 @@ int wolfSSL_BIO_seek(WOLFSSL_BIO *bio, int ofs) WOLFSSL_ENTER("wolfSSL_BIO_seek"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } /* offset ofs from beginning of file */ if (bio->type == WOLFSSL_BIO_FILE && - XFSEEK((XFILE)bio->ptr, ofs, SEEK_SET) < 0) { - return -1; + XFSEEK(bio->ptr.fh, ofs, SEEK_SET) < 0) { + return WOLFSSL_FATAL_ERROR; } return 0; @@ -1663,16 +1876,16 @@ int wolfSSL_BIO_tell(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_tell"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (bio->type != WOLFSSL_BIO_FILE) { return 0; } - pos = (int)XFTELL((XFILE)bio->ptr); + pos = (int)XFTELL(bio->ptr.fh); if (pos < 0) - return -1; + return WOLFSSL_FATAL_ERROR; else return pos; } @@ -1799,15 +2012,16 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) if (bio) { switch (bio->type) { case WOLFSSL_BIO_SOCKET: + case WOLFSSL_BIO_DGRAM: #ifdef XFCNTL { int ret; - int flag = XFCNTL(bio->num, F_GETFL, 0); + int flag = XFCNTL(bio->num.fd, F_GETFL, 0); if (on) { - ret = XFCNTL(bio->num, F_SETFL, flag | O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag | O_NONBLOCK); } else { - ret = XFCNTL(bio->num, F_SETFL, flag & ~O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag & ~O_NONBLOCK); } if (ret == -1) { @@ -1818,7 +2032,7 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) break; case WOLFSSL_BIO_SSL: #ifdef WOLFSSL_DTLS - wolfSSL_dtls_set_using_nonblock((WOLFSSL*)bio->ptr, (int)on); + wolfSSL_dtls_set_using_nonblock(bio->ptr.ssl, (int)on); #endif break; @@ -1966,7 +2180,7 @@ int wolfSSL_BIO_get_mem_data(WOLFSSL_BIO* bio, void* p) } if (p) { - *(byte**)p = (byte*)mem_bio->ptr + mem_bio->rdIdx; + *(byte**)p = mem_bio->ptr.mem_buf_data + mem_bio->rdIdx; } return mem_bio->wrSz - mem_bio->rdIdx; @@ -1991,7 +2205,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) - if (XFFLUSH((FILE *)bio->ptr) != 0) + if (XFFLUSH(bio->ptr.fh) != 0) return WOLFSSL_FAILURE; #endif /* !NO_FILESYSTEM && XFFLUSH */ @@ -2015,14 +2229,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) /* return the context and initialize the BIO state */ int wolfSSL_BIO_get_md_ctx(WOLFSSL_BIO *bio, WOLFSSL_EVP_MD_CTX **mdcp) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if ((bio != NULL) && (mdcp != NULL)) { - *mdcp = (WOLFSSL_EVP_MD_CTX*)bio->ptr; + *mdcp = bio->ptr.md_ctx; ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } WOLFSSL_BIO_METHOD* wolfSSL_BIO_f_buffer(void) @@ -2110,11 +2327,39 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio) { bio->type = WOLFSSL_BIO_SOCKET; bio->shutdown = (byte)closeF; - bio->num = sfd; + bio->num.fd = (SOCKET_T)sfd; } return bio; } + +#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_datagram(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_DGRAM); + + WOLFSSL_ENTER("wolfSSL_BIO_s_datagram"); + + return &meth; + } + + + WOLFSSL_BIO* wolfSSL_BIO_new_dgram(int fd, int closeF) + { + WOLFSSL_BIO* bio = wolfSSL_BIO_new(wolfSSL_BIO_s_datagram()); + + WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); + if (bio) { + bio->type = WOLFSSL_BIO_DGRAM; + bio->shutdown = (byte)closeF; + bio->num.fd = (SOCKET_T)fd; + } + return bio; + } +#endif + + /** * Create new socket BIO object. This is a pure TCP connection with * no SSL or TLS protection. @@ -2231,7 +2476,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2255,17 +2500,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - if (b->num == WOLFSSL_BIO_ERROR) { + if (b->num.fd == SOCKET_INVALID) { if (wolfIO_TcpBind(&sfd, b->port) < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; - int newfd = wolfIO_TcpAccept(b->num, NULL, NULL); + int newfd = wolfIO_TcpAccept(b->num.fd, NULL, NULL); if (newfd < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; @@ -2322,8 +2567,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } - if (b->type == WOLFSSL_BIO_SSL && b->ptr != NULL) { - return wolfSSL_negotiate((WOLFSSL*)b->ptr); + if (b->type == WOLFSSL_BIO_SSL && b->ptr.ssl != NULL) { + return wolfSSL_negotiate(b->ptr.ssl); } else { WOLFSSL_MSG("Not SSL BIO or no SSL object set"); @@ -2348,12 +2593,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return; } - if (b->ptr != NULL) { - int rc = wolfSSL_shutdown((WOLFSSL*)b->ptr); + if (b->ptr.ssl != NULL) { + int rc = wolfSSL_shutdown(b->ptr.ssl); if (rc == SSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ - wolfSSL_shutdown((WOLFSSL*)b->ptr); + wolfSSL_shutdown(b->ptr.ssl); } } else { @@ -2363,12 +2608,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_set_ssl"); if (b != NULL) { - b->ptr = ssl; + b->ptr.ssl = ssl; b->shutdown = (byte)closeF; if (b->next != NULL) wolfSSL_set_bio(ssl, b->next, b->next); @@ -2376,7 +2621,10 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } long wolfSSL_BIO_get_ssl(WOLFSSL_BIO* bio, WOLFSSL** ssl) @@ -2396,7 +2644,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - *ssl = (WOLFSSL*)bio->ptr; + *ssl = bio->ptr.ssl; return WOLFSSL_SUCCESS; } @@ -2540,7 +2788,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_set_fd"); if (b != NULL) { - b->num = fd; + b->num.fd = (SOCKET_T)fd; b->shutdown = (byte)closeF; } @@ -2584,7 +2832,14 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->method = method; #endif bio->shutdown = BIO_CLOSE; /* default to close things */ - bio->num = WOLFSSL_BIO_ERROR; + + if ((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) + { + bio->num.fd = SOCKET_INVALID; + } else { + bio->num.length = 0; + } bio->init = 1; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) @@ -2616,8 +2871,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (method->type == WOLFSSL_BIO_MD) { - bio->ptr = wolfSSL_EVP_MD_CTX_new(); - if (bio->ptr == NULL) { + bio->ptr.md_ctx = wolfSSL_EVP_MD_CTX_new(); + if (bio->ptr.md_ctx == NULL) { WOLFSSL_MSG("Memory error"); wolfSSL_BIO_free(bio); return NULL; @@ -2656,11 +2911,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return NULL; } - bio->num = (int)bio->mem_buf->max; + bio->num.length = bio->mem_buf->max; bio->wrSz = len; - bio->ptr = bio->mem_buf->data; - if (len > 0 && bio->ptr != NULL) { - XMEMCPY(bio->ptr, buf, len); + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + if (len > 0 && bio->ptr.mem_buf_data != NULL) { + XMEMCPY(bio->ptr.mem_buf_data, buf, len); bio->flags |= BIO_FLAGS_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2723,44 +2978,51 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->pair->pair = NULL; } - if (bio->ip != NULL) { - XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); - } + XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->shutdown) { - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr) - wolfSSL_free((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl) + wolfSSL_free(bio->ptr.ssl); #ifdef CloseSocket - if ((bio->type == WOLFSSL_BIO_SOCKET) && (bio->num > 0)) - CloseSocket(bio->num); + if (((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) && + (bio->num.fd != SOCKET_INVALID)) + { + CloseSocket(bio->num.fd); + } #endif } #ifndef NO_FILESYSTEM if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { - if (bio->ptr) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh) { + XFCLOSE(bio->ptr.fh); } #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR)\ && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - else if (bio->num != WOLFSSL_BIO_ERROR) { - XCLOSE(bio->num); + else if (bio->num.fd != SOCKET_INVALID) { + XCLOSE(bio->num.fd); } #endif } #endif if (bio->shutdown != BIO_NOCLOSE) { - if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr != NULL) { + if (bio->type == WOLFSSL_BIO_MEMORY && + bio->ptr.mem_buf_data != NULL) + { if (bio->mem_buf != NULL) { - if (bio->mem_buf->data != (char*)bio->ptr) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + if ((byte *)bio->mem_buf->data != bio->ptr.mem_buf_data) + { + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } else { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } if (bio->mem_buf != NULL) { @@ -2770,7 +3032,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (bio->type == WOLFSSL_BIO_MD) { - wolfSSL_EVP_MD_CTX_free((WOLFSSL_EVP_MD_CTX*)bio->ptr); + wolfSSL_EVP_MD_CTX_free(bio->ptr.md_ctx); } XFREE(bio, 0, DYNAMIC_TYPE_OPENSSL); @@ -2809,8 +3071,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } /* SSL BIO's should use the next object in the chain for IO */ - if (top->type == WOLFSSL_BIO_SSL && top->ptr) - wolfSSL_set_bio((WOLFSSL*)top->ptr, append, append); + if (top->type == WOLFSSL_BIO_SSL && top->ptr.ssl) + wolfSSL_set_bio(top->ptr.ssl, append, append); return top; } @@ -2914,9 +3176,11 @@ int wolfSSL_BIO_get_fd(WOLFSSL_BIO *bio, int* fd) WOLFSSL_ENTER("wolfSSL_BIO_get_fd"); if (bio != NULL) { + if (bio->num.fd == SOCKET_INVALID) + return WOLFSSL_BIO_ERROR; if (fd != NULL) - *fd = bio->num; - return bio->num; + *fd = (int)bio->num.fd; + return (int)bio->num.fd; } return WOLFSSL_BIO_ERROR; @@ -2991,10 +3255,10 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) switch (bio->type) { #if !defined(NO_FILESYSTEM) case WOLFSSL_BIO_FILE: - if (bio->ptr == NULL) { - return -1; + if (bio->ptr.fh == XBADFILE) { + return WOLFSSL_FATAL_ERROR; } - ret = XVFPRINTF((XFILE)bio->ptr, format, args); + ret = XVFPRINTF(bio->ptr.fh, format, args); break; #endif @@ -3088,21 +3352,22 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) return wolfSSL_BIO_write(bio, "\tNULL", 5); } - XSPRINTF(line, "%04x - ", lineOffset); + (void)XSNPRINTF(line, sizeof(line), "%04x - ", lineOffset); o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - XSPRINTF(line + o,"%02x ", (unsigned char)buf[i]); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + "%02x ", (unsigned char)buf[i]); else - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); if (i == 7) - XSPRINTF(line + o + 2, "-"); + (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); o += 3; } - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - XSPRINTF(line + o, "%c", + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/src/conf.c b/src/src/conf.c index d177da5..c9a35c1 100644 --- a/src/src/conf.c +++ b/src/src/conf.c @@ -1,6 +1,6 @@ /* conf.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -133,7 +133,7 @@ WOLFSSL_TXT_DB *wolfSSL_TXT_DB_read(WOLFSSL_BIO *in, int num) XFREE(strBuf, NULL, DYNAMIC_TYPE_OPENSSL); goto error; } - if (wolfSSL_sk_push(ret->data, strBuf) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_push(ret->data, strBuf) <= 0) { WOLFSSL_MSG("wolfSSL_sk_push error"); XFREE(strBuf, NULL, DYNAMIC_TYPE_OPENSSL); goto error; @@ -146,9 +146,7 @@ WOLFSSL_TXT_DB *wolfSSL_TXT_DB_read(WOLFSSL_BIO *in, int num) wolfSSL_TXT_DB_free(ret); ret = NULL; } - if (buf) { - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -228,7 +226,7 @@ int wolfSSL_TXT_DB_insert(WOLFSSL_TXT_DB *db, WOLFSSL_STRING *row) return WOLFSSL_FAILURE; } - if (wolfSSL_sk_push(db->data, row) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_push(db->data, row) <= 0) { WOLFSSL_MSG("wolfSSL_sk_push error"); return WOLFSSL_FAILURE; } @@ -452,11 +450,11 @@ int wolfSSL_CONF_add_string(WOLFSSL_CONF *conf, sk = (WOLF_STACK_OF(WOLFSSL_CONF_VALUE) *)section->value; value->section = section->section; - if (wolfSSL_sk_CONF_VALUE_push(sk, value) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_CONF_VALUE_push(sk, value) <= 0) { WOLFSSL_MSG("wolfSSL_sk_CONF_VALUE_push error"); return WOLFSSL_FAILURE; } - if (wolfSSL_sk_CONF_VALUE_push(conf->data, value) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_CONF_VALUE_push(conf->data, value) <= 0) { WOLFSSL_MSG("wolfSSL_sk_CONF_VALUE_push error"); wolfssl_sk_pop_type(sk, STACK_TYPE_CONF_VALUE); return WOLFSSL_FAILURE; @@ -499,7 +497,7 @@ WOLFSSL_CONF_VALUE *wolfSSL_CONF_new_section(WOLFSSL_CONF *conf, ret->value = (char*)sk; - if (wolfSSL_sk_CONF_VALUE_push(conf->data, ret) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_CONF_VALUE_push(conf->data, ret) <= 0) { WOLFSSL_MSG("wolfSSL_sk_CONF_VALUE_push error"); goto error; } @@ -793,8 +791,7 @@ static char* expandValue(WOLFSSL_CONF *conf, const char* section, return ret ? ret : str; expand_cleanup: - if (ret) - XFREE(ret, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(ret, NULL, DYNAMIC_TYPE_OPENSSL); return NULL; } @@ -803,7 +800,7 @@ static char* expandValue(WOLFSSL_CONF *conf, const char* section, {(idx)++;} int wolfSSL_NCONF_load(WOLFSSL_CONF *conf, const char *file, long *eline) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_BIO *in = NULL; char* buf = NULL; char* idx = NULL; @@ -961,8 +958,7 @@ int wolfSSL_NCONF_load(WOLFSSL_CONF *conf, const char *file, long *eline) cleanup: if (in) wolfSSL_BIO_free(in); - if (buf) - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (eline) *eline = line; return ret; @@ -986,13 +982,11 @@ void wolfSSL_X509V3_conf_free(WOLFSSL_CONF_VALUE *val) if (val->name) { /* Not a section. Don't free section as it is a shared pointer. */ XFREE(val->name, NULL, DYNAMIC_TYPE_OPENSSL); - if (val->value) - XFREE(val->value, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(val->value, NULL, DYNAMIC_TYPE_OPENSSL); } else { /* Section so val->value is a stack */ - if (val->section) - XFREE(val->section, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(val->section, NULL, DYNAMIC_TYPE_OPENSSL); /* Only free the stack structures. The contained conf values * will be freed in wolfSSL_NCONF_free */ sk = (WOLF_STACK_OF(WOLFSSL_CONF_VALUE)*)val->value; @@ -1545,7 +1539,7 @@ static const conf_cmd_tbl* wolfssl_conf_find_cmd(WOLFSSL_CONF_CTX* cctx, */ int wolfSSL_CONF_cmd(WOLFSSL_CONF_CTX* cctx, const char* cmd, const char* value) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); const conf_cmd_tbl* confcmd = NULL; WOLFSSL_ENTER("wolfSSL_CONF_cmd"); diff --git a/src/src/crl.c b/src/src/crl.c index 706c1f6..5e359c7 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -1,6 +1,6 @@ /* crl.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -121,7 +121,7 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, wolfSSL_d2i_X509_NAME(&crle->issuer, (unsigned char**)&dcrl->issuer, dcrl->issuerSz); if (crle->issuer == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } #endif #ifdef CRL_STATIC_REVOKED_LIST @@ -141,13 +141,13 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, crle->toBeSigned = (byte*)XMALLOC(crle->tbsSz, heap, DYNAMIC_TYPE_CRL_ENTRY); if (crle->toBeSigned == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; crle->signature = (byte*)XMALLOC(crle->signatureSz, heap, DYNAMIC_TYPE_CRL_ENTRY); if (crle->signature == NULL) { XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY); crle->toBeSigned = NULL; - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WC_RSA_PSS @@ -160,7 +160,7 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, crle->toBeSigned = NULL; XFREE(crle->signature, heap, DYNAMIC_TYPE_CRL_ENTRY); crle->signature = NULL; - return -1; + return WOLFSSL_FATAL_ERROR; } XMEMCPY(crle->sigParams, buff + dcrl->sigParamsIndex, crle->sigParamsSz); @@ -219,13 +219,10 @@ static void CRL_Entry_free(CRL_Entry* crle, void* heap) tmp = next; } #endif - if (crle->signature != NULL) - XFREE(crle->signature, heap, DYNAMIC_TYPE_CRL_ENTRY); - if (crle->toBeSigned != NULL) - XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY); + XFREE(crle->signature, heap, DYNAMIC_TYPE_CRL_ENTRY); + XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY); #ifdef WC_RSA_PSS - if (crle->sigParams != NULL) - XFREE(crle->sigParams, heap, DYNAMIC_TYPE_CRL_ENTRY); + XFREE(crle->sigParams, heap, DYNAMIC_TYPE_CRL_ENTRY); #endif #if defined(OPENSSL_EXTRA) if (crle->issuer != NULL) { @@ -426,7 +423,7 @@ static int CheckCertCRLList(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, #endif { #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK) - if (!XVALIDATE_DATE(crle->nextDate,crle->nextDateFormat, AFTER)) { + if (!XVALIDATE_DATE(crle->nextDate,crle->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL next date is no longer valid"); nextDateValid = 0; } @@ -440,7 +437,7 @@ static int CheckCertCRLList(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, break; } else if (foundEntry == 0) { - ret = ASN_AFTER_DATE_E; + ret = CRL_CERT_DATE_ERR; } } } @@ -481,8 +478,9 @@ int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, if (foundEntry == 0) { /* perform embedded lookup */ if (crl->crlIOCb) { - ret = crl->crlIOCb(crl, (const char*)extCrlInfo, extCrlInfoSz); - if (ret == WOLFSSL_CBIO_ERR_WANT_READ) { + int cbRet = crl->crlIOCb(crl, (const char*)extCrlInfo, + extCrlInfoSz); + if (cbRet == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { ret = OCSP_WANT_READ; } else if (ret >= 0) { @@ -505,9 +503,9 @@ int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, /* When not set the folder or not use hash_dir, do nothing. */ if ((foundEntry == 0) && (ret != WC_NO_ERR_TRACE(OCSP_WANT_READ))) { if (crl->cm != NULL && crl->cm->x509_store_p != NULL) { - ret = LoadCertByIssuer(crl->cm->x509_store_p, + int loadRet = LoadCertByIssuer(crl->cm->x509_store_p, (WOLFSSL_X509_NAME*)issuerName, X509_LU_CRL); - if (ret == WOLFSSL_SUCCESS) { + if (loadRet == WOLFSSL_SUCCESS) { /* try again */ ret = CheckCertCRLList(crl, issuerHash, serial, serialSz, serialHash, &foundEntry); @@ -538,6 +536,13 @@ int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, crl->cm->cbMissingCRL(url); } + + if (crl->cm != NULL && crl->cm->crlCb && + crl->cm->crlCb(ret, crl, crl->cm, crl->cm->crlCbCtx)) { + if (ret != 0) + WOLFSSL_MSG("Overriding CRL error"); + ret = 0; + } } return ret; @@ -565,7 +570,7 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, WOLFSSL_ENTER("AddCRL"); if (crl == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; crle = crl->currentEntry; @@ -580,7 +585,7 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, if (InitCRL_Entry(crle, dcrl, buff, verified, crl->heap) < 0) { WOLFSSL_MSG("Init CRL Entry failed"); CRL_Entry_free(crle, crl->heap); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wc_LockRwLock_Wr(&crl->crlLock) != 0) { @@ -627,7 +632,7 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, else { WOLFSSL_MSG("Pem to Der failed"); FreeDer(&der); - return -1; + return WOLFSSL_FATAL_ERROR; } #else ret = NOT_COMPILED_IN; @@ -779,7 +784,8 @@ static CRL_Entry* DupCRL_Entry(const CRL_Entry* ent, void* heap) #endif if (dupl->toBeSigned == NULL || dupl->signature == NULL #ifdef WC_RSA_PSS - || dupl->sigParams == NULL + /* allow sigParamsSz is zero and malloc(0) to return NULL */ + || (dupl->sigParams == NULL && dupl->sigParamsSz != 0) #endif ) { CRL_Entry_free(dupl, heap); @@ -1020,7 +1026,7 @@ static int SwapLists(WOLFSSL_CRL* crl) #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif - return -1; + return WOLFSSL_FATAL_ERROR; } if (crl->monitors[0].path) { @@ -1031,7 +1037,7 @@ static int SwapLists(WOLFSSL_CRL* crl) #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -1043,7 +1049,7 @@ static int SwapLists(WOLFSSL_CRL* crl) #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -1053,7 +1059,7 @@ static int SwapLists(WOLFSSL_CRL* crl) #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif - return -1; + return WOLFSSL_FATAL_ERROR; } newList = tmp->crlList; @@ -1102,10 +1108,14 @@ static int StopMonitor(wolfSSL_CRL_mfd_t mfd) struct kevent change; /* trigger custom shutdown */ +#if defined(NOTE_TRIGGER) EV_SET(&change, CRL_CUSTOM_FD, EVFILT_USER, 0, NOTE_TRIGGER, 0, NULL); +#elif defined(EV_TRIGGER) + EV_SET(&change, CRL_CUSTOM_FD, EVFILT_USER, EV_TRIGGER, 0, 0, NULL); +#endif if (kevent(mfd, &change, 1, NULL, 0, NULL) < 0) { WOLFSSL_MSG("kevent trigger customer event failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } return 0; @@ -1237,7 +1247,7 @@ static int StopMonitor(wolfSSL_CRL_mfd_t mfd) /* write to our custom event */ if (write(mfd, &w64, sizeof(w64)) < 0) { WOLFSSL_MSG("StopMonitor write failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } return 0; @@ -1380,7 +1390,7 @@ static int StopMonitor(wolfSSL_CRL_mfd_t mfd) { if (SetEvent(mfd) == 0) { WOLFSSL_MSG("SetEvent custom event trigger failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } return 0; } diff --git a/src/src/dtls.c b/src/src/dtls.c index 52ace7e..5b2356a 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -1,6 +1,6 @@ /* dtls.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -953,8 +953,13 @@ int DoClientHelloStateless(WOLFSSL* ssl, const byte* input, word32 helloSz, int tlsxFound; ret = FindExtByType(&ch.cookieExt, TLSX_COOKIE, ch.extension, &tlsxFound); - if (ret != 0) + if (ret != 0) { + if (isFirstCHFrag) { + WOLFSSL_MSG("\t\tCookie probably missing from first " + "fragment. Dropping."); + } return ret; + } } } #endif @@ -1033,22 +1038,6 @@ int DoClientHelloStateless(WOLFSSL* ssl, const byte* input, word32 helloSz, #if defined(WOLFSSL_DTLS_CID) -typedef struct ConnectionID { - byte length; -/* Ignore "nonstandard extension used : zero-sized array in struct/union" - * MSVC warning */ -#ifdef _MSC_VER -#pragma warning(disable: 4200) -#endif - byte id[]; -} ConnectionID; - -typedef struct CIDInfo { - ConnectionID* tx; - ConnectionID* rx; - byte negotiated : 1; -} CIDInfo; - static ConnectionID* DtlsCidNew(const byte* cid, byte size, void* heap) { ConnectionID* ret; @@ -1150,10 +1139,8 @@ void TLSX_ConnectionID_Free(byte* ext, void* heap) info = DtlsCidGetInfoFromExt(ext); if (info == NULL) return; - if (info->rx != NULL) - XFREE(info->rx, heap, DYNAMIC_TYPE_TLSX); - if (info->tx != NULL) - XFREE(info->tx, heap, DYNAMIC_TYPE_TLSX); + XFREE(info->rx, heap, DYNAMIC_TYPE_TLSX); + XFREE(info->tx, heap, DYNAMIC_TYPE_TLSX); XFREE(info, heap, DYNAMIC_TYPE_TLSX); DtlsCidUnsetInfoFromExt(ext); XFREE(ext, heap, DYNAMIC_TYPE_TLSX); @@ -1228,9 +1215,8 @@ int TLSX_ConnectionID_Use(WOLFSSL* ssl) int TLSX_ConnectionID_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte isRequest) { - ConnectionID* id; CIDInfo* info; - byte cidSize; + byte cidSz; TLSX* ext; ext = TLSX_Find(ssl->extensions, TLSX_CONNECTION_ID); @@ -1246,35 +1232,41 @@ int TLSX_ConnectionID_Parse(WOLFSSL* ssl, const byte* input, word16 length, } } + if (length < OPAQUE8_LEN) + return BUFFER_ERROR; + + cidSz = *input; + if (cidSz + OPAQUE8_LEN > length) + return BUFFER_ERROR; + info = DtlsCidGetInfo(ssl); if (info == NULL) return BAD_STATE_E; /* it may happen if we process two ClientHello because the server sent an - * HRR request */ - if (info->tx != NULL) { + * HRR/HVR request */ + if (info->tx != NULL || info->negotiated) { if (ssl->options.side != WOLFSSL_SERVER_END && - ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE) + ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE && + !IsSCR(ssl)) return BAD_STATE_E; - XFREE(info->tx, ssl->heap, DYNAMIC_TYPE_TLSX); - info->tx = NULL; - } - - if (length < OPAQUE8_LEN) - return BUFFER_ERROR; - - cidSize = *input; - if (cidSize + OPAQUE8_LEN > length) - return BUFFER_ERROR; + /* Should not be null if negotiated */ + if (info->tx == NULL) + return BAD_STATE_E; - if (cidSize > 0) { - id = (ConnectionID*)XMALLOC(sizeof(*id) + cidSize, ssl->heap, - DYNAMIC_TYPE_TLSX); + /* For now we don't support changing the CID on a rehandshake */ + if (cidSz != info->tx->length || + XMEMCMP(info->tx->id, input + OPAQUE8_LEN, cidSz) != 0) + return DTLS_CID_ERROR; + } + else if (cidSz > 0) { + ConnectionID* id = (ConnectionID*)XMALLOC(sizeof(*id) + cidSz, + ssl->heap, DYNAMIC_TYPE_TLSX); if (id == NULL) return MEMORY_ERROR; - XMEMCPY(id->id, input + OPAQUE8_LEN, cidSize); - id->length = cidSize; + XMEMCPY(id->id, input + OPAQUE8_LEN, cidSz); + id->length = cidSz; info->tx = id; } @@ -1314,10 +1306,6 @@ int wolfSSL_dtls_cid_use(WOLFSSL* ssl) { int ret; - /* CID is supported on DTLSv1.3 only */ - if (!IsAtLeastTLSv1_3(ssl->version)) - return WOLFSSL_FAILURE; - ssl->options.useDtlsCID = 1; ret = TLSX_ConnectionID_Use(ssl); if (ret != 0) @@ -1343,8 +1331,9 @@ int wolfSSL_dtls_cid_set(WOLFSSL* ssl, unsigned char* cid, unsigned int size) return WOLFSSL_FAILURE; if (cidInfo->rx != NULL) { - XFREE(cidInfo->rx, ssl->heap, DYNAMIC_TYPE_TLSX); - cidInfo->rx = NULL; + WOLFSSL_MSG("wolfSSL doesn't support changing the CID during a " + "connection"); + return WOLFSSL_FAILURE; } /* empty CID */ @@ -1383,7 +1372,42 @@ int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buf, return DtlsCidGet(ssl, buf, bufferSz, 0); } +int wolfSSL_dtls_cid_max_size(void) +{ + return DTLS_CID_MAX_SIZE; +} #endif /* WOLFSSL_DTLS_CID */ + +byte DtlsGetCidTxSize(WOLFSSL* ssl) +{ +#ifdef WOLFSSL_DTLS_CID + unsigned int cidSz; + int ret; + ret = wolfSSL_dtls_cid_get_tx_size(ssl, &cidSz); + if (ret != WOLFSSL_SUCCESS) + return 0; + return (byte)cidSz; +#else + (void)ssl; + return 0; +#endif +} + +byte DtlsGetCidRxSize(WOLFSSL* ssl) +{ +#ifdef WOLFSSL_DTLS_CID + unsigned int cidSz; + int ret; + ret = wolfSSL_dtls_cid_get_rx_size(ssl, &cidSz); + if (ret != WOLFSSL_SUCCESS) + return 0; + return (byte)cidSz; +#else + (void)ssl; + return 0; +#endif +} + #endif /* WOLFSSL_DTLS */ #endif /* WOLFCRYPT_ONLY */ diff --git a/src/src/dtls13.c b/src/src/dtls13.c index 0284ffe..6f2f014 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -1,6 +1,6 @@ /* dtls13.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -71,6 +71,8 @@ typedef struct Dtls13HandshakeHeader { byte fragmentLength[3]; } Dtls13HandshakeHeader; +wc_static_assert(sizeof(Dtls13HandshakeHeader) == DTLS13_HANDSHAKE_HEADER_SZ); + /** * struct Dtls13Recordplaintextheader: represent header of unprotected DTLSv1.3 * record @@ -339,9 +341,17 @@ static void Dtls13MsgWasProcessed(WOLFSSL* ssl, enum HandShakeType hs) if (ssl->options.dtlsStateful) ssl->keys.dtls_expected_peer_handshake_number++; - /* we need to send ACKs on the last message of a flight that needs explicit - acknowledgment */ - ssl->dtls13Rtx.sendAcks = Dtls13RtxMsgNeedsAck(ssl, hs); +#ifdef WOLFSSL_RW_THREADED + if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0) +#endif + { + /* we need to send ACKs on the last message of a flight that needs + * explicit acknowledgment */ + ssl->dtls13Rtx.sendAcks = Dtls13RtxMsgNeedsAck(ssl, hs); + #ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); + #endif + } } int Dtls13ProcessBufferedMessages(WOLFSSL* ssl) @@ -395,7 +405,8 @@ int Dtls13ProcessBufferedMessages(WOLFSSL* ssl) * from there, the message can be considered processed successfully. * WANT_WRITE means that we are done with processing the msg and we are * waiting to flush the output buffer. */ - if ((ret == 0 || ret == WANT_WRITE) || (msg->type == certificate_request && + if ((ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) || + (msg->type == certificate_request && ssl->options.handShakeDone && ret == WC_NO_ERR_TRACE(WC_PENDING_E))) { if (IsAtLeastTLSv1_3(ssl->version)) @@ -484,22 +495,25 @@ int Dtls13HashClientHello(const WOLFSSL* ssl, byte* hash, int* hashSz, wc_HashAlg hashCtx; int type = wolfSSL_GetHmacType_ex(specs); + if (type < 0) + return type; + header[0] = (byte)client_hello; c32to24(length, header + 1); - ret = wc_HashInit_ex(&hashCtx, type, ssl->heap, ssl->devId); + ret = wc_HashInit_ex(&hashCtx, (enum wc_HashType)type, ssl->heap, ssl->devId); if (ret == 0) { - ret = wc_HashUpdate(&hashCtx, type, header, OPAQUE32_LEN); + ret = wc_HashUpdate(&hashCtx, (enum wc_HashType)type, header, OPAQUE32_LEN); if (ret == 0) - ret = wc_HashUpdate(&hashCtx, type, body, length); + ret = wc_HashUpdate(&hashCtx, (enum wc_HashType)type, body, length); if (ret == 0) - ret = wc_HashFinal(&hashCtx, type, hash); + ret = wc_HashFinal(&hashCtx, (enum wc_HashType)type, hash); if (ret == 0) { - *hashSz = wc_HashGetDigestSize(type); + *hashSz = wc_HashGetDigestSize((enum wc_HashType)type); if (*hashSz < 0) ret = *hashSz; } - wc_HashFree(&hashCtx, type); + wc_HashFree(&hashCtx, (enum wc_HashType)type); } return ret; } @@ -557,9 +571,6 @@ static int Dtls13SendFragment(WOLFSSL* ssl, byte* output, word16 output_size, else { msg = output + recordHeaderLength; - if (length <= recordHeaderLength) - return BUFFER_ERROR; - if (hashOutput) { ret = Dtls13HashHandshake(ssl, msg, recordLength); if (ret != 0) @@ -651,8 +662,17 @@ static void Dtls13RtxRecordUnlink(WOLFSSL* ssl, Dtls13RtxRecord** prevNext, Dtls13RtxRecord* r) { /* if r was at the tail of the list, update the tail pointer */ - if (r->next == NULL) - ssl->dtls13Rtx.rtxRecordTailPtr = prevNext; + if (r->next == NULL) { + #ifdef WOLFSSL_RW_THREADED + if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0) + #endif + { + ssl->dtls13Rtx.rtxRecordTailPtr = prevNext; + #ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); + #endif + } + } /* unlink */ *prevNext = r->next; @@ -709,12 +729,20 @@ static int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq) WOLFSSL_ENTER("Dtls13RtxAddAck"); - rn = Dtls13NewRecordNumber(epoch, seq, ssl->heap); - if (rn == NULL) - return MEMORY_E; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0) +#endif + { + rn = Dtls13NewRecordNumber(epoch, seq, ssl->heap); + if (rn == NULL) + return MEMORY_E; - rn->next = ssl->dtls13Rtx.seenRecords; - ssl->dtls13Rtx.seenRecords = rn; + rn->next = ssl->dtls13Rtx.seenRecords; + ssl->dtls13Rtx.seenRecords = rn; + #ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); + #endif + } return 0; } @@ -727,15 +755,23 @@ static void Dtls13RtxFlushAcks(WOLFSSL* ssl) WOLFSSL_ENTER("Dtls13RtxFlushAcks"); - list = ssl->dtls13Rtx.seenRecords; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0) +#endif + { + list = ssl->dtls13Rtx.seenRecords; - while (list != NULL) { - rn = list; - list = rn->next; - XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG); - } + while (list != NULL) { + rn = list; + list = rn->next; + XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG); + } - ssl->dtls13Rtx.seenRecords = NULL; + ssl->dtls13Rtx.seenRecords = NULL; + #ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); + #endif + } } static int Dtls13DetectDisruption(WOLFSSL* ssl, word32 fragOffset) @@ -811,9 +847,7 @@ static void Dtls13MaybeSaveClientHello(WOLFSSL* ssl) while (r != NULL) { if (r->handshakeType == client_hello) { Dtls13RtxRecordUnlink(ssl, prev_next, r); - if (ssl->dtls13ClientHello != NULL) - XFREE(ssl->dtls13ClientHello, ssl->heap, - DYNAMIC_TYPE_DTLS_MSG); + XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG); ssl->dtls13ClientHello = r->data; ssl->dtls13ClientHelloSz = r->length; r->data = NULL; @@ -921,7 +955,7 @@ static int Dtls13SendOneFragmentRtx(WOLFSSL* ssl, handshakeType, hashOutput, Dtls13SendNow(ssl, handshakeType)); if (rtxRecord != NULL) { - if (ret == 0 || ret == WANT_WRITE) + if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) Dtls13RtxAddRecord(&ssl->dtls13Rtx, rtxRecord); else Dtls13FreeRtxBufferRecord(ssl, rtxRecord); @@ -981,7 +1015,7 @@ static int Dtls13SendFragmentedInternal(WOLFSSL* ssl) ret = Dtls13SendOneFragmentRtx(ssl, (enum HandShakeType)ssl->dtls13FragHandshakeType, (word16)recordLength + MAX_MSG_EXTRA, output, (word32)recordLength, 0); - if (ret == WANT_WRITE) { + if (ret == WC_NO_ERR_TRACE(WANT_WRITE)) { ssl->dtls13FragOffset += fragLength; return ret; } @@ -1053,45 +1087,26 @@ static WC_INLINE word8 Dtls13GetEpochBits(w64wrapper epoch) } #ifdef WOLFSSL_DTLS_CID -static byte Dtls13GetCidTxSize(WOLFSSL* ssl) -{ - unsigned int cidSz; - int ret; - ret = wolfSSL_dtls_cid_get_tx_size(ssl, &cidSz); - if (ret != WOLFSSL_SUCCESS) - return 0; - return (byte)cidSz; -} - -static byte Dtls13GetCidRxSize(WOLFSSL* ssl) -{ - unsigned int cidSz; - int ret; - ret = wolfSSL_dtls_cid_get_rx_size(ssl, &cidSz); - if (ret != WOLFSSL_SUCCESS) - return 0; - return (byte)cidSz; -} static int Dtls13AddCID(WOLFSSL* ssl, byte* flags, byte* out, word16* idx) { - byte cidSize; + byte cidSz; int ret; if (!wolfSSL_dtls_cid_is_enabled(ssl)) return 0; - cidSize = Dtls13GetCidTxSize(ssl); + cidSz = DtlsGetCidTxSize(ssl); /* no cid */ - if (cidSize == 0) + if (cidSz == 0) return 0; *flags |= DTLS13_CID_BIT; - /* we know that we have at least cidSize of space */ - ret = wolfSSL_dtls_cid_get_tx(ssl, out + *idx, cidSize); + /* we know that we have at least cidSz of space */ + ret = wolfSSL_dtls_cid_get_tx(ssl, out + *idx, cidSz); if (ret != WOLFSSL_SUCCESS) return ret; - *idx += cidSize; + *idx += cidSz; return 0; } @@ -1137,8 +1152,6 @@ static int Dtls13UnifiedHeaderParseCID(WOLFSSL* ssl, byte flags, #else #define Dtls13AddCID(a, b, c, d) 0 -#define Dtls13GetCidRxSize(a) 0 -#define Dtls13GetCidTxSize(a) 0 #define Dtls13UnifiedHeaderParseCID(a, b, c, d, e) 0 #endif /* WOLFSSL_DTLS_CID */ @@ -1210,6 +1223,11 @@ int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output, return 0; } +int Dtls13MinimumRecordLength(WOLFSSL* ssl) +{ + return Dtls13GetRlHeaderLength(ssl, 1) + DTLS13_MIN_CIPHERTEXT; +} + /** * Dtls13EncryptRecordNumber() - encrypt record number in the header * @ssl: ssl object @@ -1226,14 +1244,20 @@ int Dtls13EncryptRecordNumber(WOLFSSL* ssl, byte* hdr, word16 recordLength) if (ssl == NULL || hdr == NULL) return BAD_FUNC_ARG; +#ifdef HAVE_NULL_CIPHER + /* Do not encrypt record numbers with null cipher. See RFC 9150 Sec 9 */ + if (ssl->specs.bulk_cipher_algorithm == wolfssl_cipher_null) + return 0; +#endif /*HAVE_NULL_CIPHER */ + /* we need at least a 16 bytes of ciphertext to encrypt record number see 4.2.3*/ - if (recordLength < Dtls13GetRlHeaderLength(ssl, 1) + DTLS13_MIN_CIPHERTEXT) + if (recordLength < Dtls13MinimumRecordLength(ssl)) return BUFFER_ERROR; seqLength = (*hdr & DTLS13_LEN_BIT) ? DTLS13_SEQ_16_LEN : DTLS13_SEQ_8_LEN; - cidSz = Dtls13GetCidTxSize(ssl); + cidSz = DtlsGetCidTxSize(ssl); /* header flags + seq number + CID size*/ hdrLength = OPAQUE8_LEN + seqLength + cidSz; @@ -1264,7 +1288,7 @@ word16 Dtls13GetRlHeaderLength(WOLFSSL* ssl, byte isEncrypted) if (!isEncrypted) return DTLS_RECORD_HEADER_SZ; - return DTLS13_UNIFIED_HEADER_SIZE + Dtls13GetCidTxSize(ssl); + return DTLS13_UNIFIED_HEADER_SIZE + DtlsGetCidTxSize(ssl); } /** @@ -1391,7 +1415,7 @@ int Dtls13GetUnifiedHeaderSize(WOLFSSL* ssl, const byte input, word16* size) return BAD_FUNC_ARG; /* flags (1) + CID + seq 8bit (1) */ - *size = OPAQUE8_LEN + Dtls13GetCidRxSize(ssl) + OPAQUE8_LEN; + *size = OPAQUE8_LEN + DtlsGetCidRxSize(ssl) + OPAQUE8_LEN; if (input & DTLS13_SEQ_LEN_BIT) *size += OPAQUE8_LEN; if (input & DTLS13_LEN_BIT) @@ -1454,17 +1478,22 @@ int Dtls13ParseUnifiedRecordLayer(WOLFSSL* ssl, const byte* input, hdrInfo->recordLength = inputSize - idx; } - /* minimum size for a dtls1.3 packet is 16 bytes (to have enough ciphertext - to create record number xor mask). (draft 43 - Sec 4.2.3) */ - if (hdrInfo->recordLength < DTLS13_RN_MASK_SIZE) - return LENGTH_ERROR; - if (inputSize < idx + DTLS13_RN_MASK_SIZE) - return BUFFER_ERROR; + /* Do not encrypt record numbers with null cipher. See RFC 9150 Sec 9 */ + if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) + { + /* minimum size for a dtls1.3 packet is 16 bytes (to have enough + * ciphertext to create record number xor mask). + * (draft 43 - Sec 4.2.3) */ + if (hdrInfo->recordLength < DTLS13_RN_MASK_SIZE) + return LENGTH_ERROR; + if (inputSize < idx + DTLS13_RN_MASK_SIZE) + return BUFFER_ERROR; - ret = Dtls13EncryptDecryptRecordNumber(ssl, seqNum, seqLen, input + idx, - DEPROTECT); - if (ret != 0) - return ret; + ret = Dtls13EncryptDecryptRecordNumber(ssl, seqNum, seqLen, input + idx, + DEPROTECT); + if (ret != 0) + return ret; + } if (seqLen == DTLS13_SEQ_16_LEN) { hdrInfo->seqHiPresent = 1; @@ -1563,7 +1592,7 @@ static int Dtls13RtxSendBuffered(WOLFSSL* ssl) ret = Dtls13SendFragment(ssl, output, (word16)sendSz, r->length + headerLength, (enum HandShakeType)r->handshakeType, 0, isLast || !ssl->options.groupMessages); - if (ret != 0 && ret != WANT_WRITE) + if (ret != 0 && ret != WC_NO_ERR_TRACE(WANT_WRITE)) return ret; if (r->rnIdx >= DTLS13_RETRANS_RN_SIZE) @@ -1577,7 +1606,7 @@ static int Dtls13RtxSendBuffered(WOLFSSL* ssl) r->seq[r->rnIdx] = seq; r->rnIdx++; - if (ret == WANT_WRITE) { + if (ret == WC_NO_ERR_TRACE(WANT_WRITE)) { /* this fragment will be sent eventually. Move it to the end of the list so next time we start with a new one. */ Dtls13RtxMoveToEndOfList(ssl, prevNext, r); @@ -1684,7 +1713,7 @@ static int _Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32 size, isFirst = fragOff == 0; isComplete = isFirst && fragLength == messageLength; - if (!isComplete && !Dtls13AcceptFragmented(ssl, handshakeType)) { + if (!isComplete && !Dtls13AcceptFragmented(ssl, (enum HandShakeType)handshakeType)) { #ifdef WOLFSSL_DTLS_CH_FRAG byte tls13 = 0; /* check if the first CH fragment contains a valid cookie */ @@ -1876,7 +1905,7 @@ int Dtls13HandshakeSend(WOLFSSL* ssl, byte* message, word16 outputSize, if (maxLen < maxFrag) { ret = Dtls13SendOneFragmentRtx(ssl, handshakeType, outputSize, message, length, hashOutput); - if (ret == 0 || ret == WANT_WRITE) + if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) ssl->keys.dtls_handshake_number++; } else { @@ -2523,13 +2552,25 @@ static void Dtls13RtxRemoveRecord(WOLFSSL* ssl, w64wrapper epoch, int Dtls13DoScheduledWork(WOLFSSL* ssl) { int ret; + int sendAcks; WOLFSSL_ENTER("Dtls13DoScheduledWork"); ssl->dtls13SendingAckOrRtx = 1; - if (ssl->dtls13Rtx.sendAcks) { +#ifdef WOLFSSL_RW_THREADED + ret = wc_LockMutex(&ssl->dtls13Rtx.mutex); + if (ret < 0) + return ret; +#endif + sendAcks = ssl->dtls13Rtx.sendAcks; + if (sendAcks) { ssl->dtls13Rtx.sendAcks = 0; + } +#ifdef WOLFSSL_RW_THREADED + ret = wc_UnLockMutex(&ssl->dtls13Rtx.mutex); +#endif + if (sendAcks) { ret = SendDtls13Ack(ssl); if (ret != 0) return ret; @@ -2586,7 +2627,7 @@ int Dtls13RtxTimeout(WOLFSSL* ssl) /* Increase timeout on long timeout */ if (DtlsMsgPoolTimeout(ssl) != 0) - return -1; + return WOLFSSL_FATAL_ERROR; return Dtls13RtxSendBuffered(ssl); } @@ -2605,13 +2646,28 @@ static int Dtls13RtxHasKeyUpdateBuffered(WOLFSSL* ssl) return 0; } +int DoDtls13KeyUpdateAck(WOLFSSL* ssl) +{ + int ret = 0; + + if (!Dtls13RtxHasKeyUpdateBuffered(ssl)) { + /* we removed the KeyUpdate message because it was ACKed */ + ssl->dtls13WaitKeyUpdateAck = 0; + ret = Dtls13KeyUpdateAckReceived(ssl); + } + + return ret; +} + int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize, word32* processedSize) { const byte* ackMessage; w64wrapper epoch, seq; word16 length; +#ifndef WOLFSSL_RW_THREADED int ret; +#endif int i; if (inputSize < OPAQUE16_LEN) @@ -2643,15 +2699,13 @@ int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize, ssl->options.serverState = SERVER_FINISHED_ACKED; } +#ifndef WOLFSSL_RW_THREADED if (ssl->dtls13WaitKeyUpdateAck) { - if (!Dtls13RtxHasKeyUpdateBuffered(ssl)) { - /* we removed the KeyUpdate message because it was ACKed */ - ssl->dtls13WaitKeyUpdateAck = 0; - ret = Dtls13KeyUpdateAckReceived(ssl); - if (ret != 0) - return ret; - } + ret = DoDtls13KeyUpdateAck(ssl); + if (ret != 0) + return ret; } +#endif *processedSize = length + OPAQUE16_LEN; @@ -2702,9 +2756,17 @@ int SendDtls13Ack(WOLFSSL* ssl) if (ret != 0) return ret; - ret = Dtls13WriteAckMessage(ssl, ssl->dtls13Rtx.seenRecords, &length); - if (ret != 0) +#ifdef WOLFSSL_RW_THREADED + ret = wc_LockMutex(&ssl->dtls13Rtx.mutex); + if (ret < 0) return ret; +#endif + ret = Dtls13WriteAckMessage(ssl, ssl->dtls13Rtx.seenRecords, &length); +#ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); +#endif + if (ret != 0) + return ret; output = GetOutputBuffer(ssl); diff --git a/src/src/internal.c b/src/src/internal.c index 6bbd38f..a152022 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -1,6 +1,6 @@ /* internal.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,8 +19,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - #ifdef HAVE_CONFIG_H #include #endif @@ -212,6 +210,8 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS #endif #endif +int writeAeadAuthData(WOLFSSL* ssl, word16 sz, byte type, byte* additional, + byte dec, byte** seq, int verifyOrder); #ifdef WOLFSSL_DTLS static int _DtlsCheckWindow(WOLFSSL* ssl); @@ -344,7 +344,7 @@ void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) { wolfSSL_CTX_keylog_cb_func logCb = NULL; int msSz; - int hasVal; + int invalidCount; int i; const char* label = SSC_CR; int labelSz = sizeof(SSC_CR); @@ -355,32 +355,34 @@ void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) int ret; (void)ctx; - if (ssl == NULL || secret == NULL || *secretSz == 0) + if (ssl == NULL || secret == NULL || secretSz == NULL || *secretSz == 0) return BAD_FUNC_ARG; if (ssl->arrays == NULL) return BAD_FUNC_ARG; - /* get the user-callback func from CTX*/ + /* get the user-callback func from CTX */ logCb = ssl->ctx->keyLogCb; - if (logCb == NULL) - return 0; + if (logCb == NULL) { + return 0; /* no logging callback */ + } - /* need to make sure the given master-secret has a meaningful value */ + /* make sure the given master-secret has a meaningful value */ msSz = *secretSz; - hasVal = 0; + invalidCount = 0; for (i = 0; i < msSz; i++) { - if (*((byte*)secret) != 0) { - hasVal = 1; - break; + if (((byte*)secret)[i] == 0) { + invalidCount++; } } - if (hasVal == 0) - return 0; /* master-secret looks invalid */ + if (invalidCount == *secretSz) { + WOLFSSL_MSG("master-secret is not valid"); + return 0; /* ignore error */ + } /* build up a hex-decoded keylog string - "CLIENT_RANDOM " - note that each keylog string does not have CR/LF. - */ + * "CLIENT_RANDOM " + * note that each keylog string does not have CR/LF. + */ buffSz = labelSz + (RAN_LEN * 2) + 1 + ((*secretSz) * 2) + 1; log = XMALLOC(buffSz, ssl->heap, DYNAMIC_TYPE_SECRET); if (log == NULL) @@ -410,8 +412,9 @@ void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) ret = 0; } } - else - ret = MEMORY_E; + else { + ret = BUFFER_E; + } } /* Zero out Base16 encoded secret and other data. */ ForceZero(log, buffSz); @@ -2107,7 +2110,7 @@ int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf, word32* sz, if (type == WOLFSSL_EXPORT_TLS) { *sz += AES_BLOCK_SIZE*2; } - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (ret == 0) { @@ -2562,7 +2565,7 @@ void wolfSSL_CRYPTO_cleanup_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data) #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) /* free all ech configs in the list */ -static void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap) +void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap) { WOLFSSL_EchConfig* working_config = configs; WOLFSSL_EchConfig* next_config; @@ -2573,8 +2576,7 @@ static void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap) XFREE(working_config->cipherSuites, heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(working_config->publicName, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (working_config->raw != NULL) - XFREE(working_config->raw, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(working_config->raw, heap, DYNAMIC_TYPE_TMP_BUFFER); if (working_config->receiverPrivkey != NULL) { wc_HpkeFreeKey(NULL, working_config->kemId, @@ -2621,10 +2623,8 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) XFREE(ctx->method, heapAtCTXInit, DYNAMIC_TYPE_METHOD); ctx->method = NULL; - if (ctx->suites) { - XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES); - ctx->suites = NULL; - } + XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES); + ctx->suites = NULL; #ifndef NO_DH XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -2723,10 +2723,8 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL); ctx->alpn_cli_protos = NULL; } - if (ctx->param) { - XFREE(ctx->param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; - } + XFREE(ctx->param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL); + ctx->param = NULL; if (ctx->x509_store.param) { XFREE(ctx->x509_store.param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL); @@ -2774,6 +2772,7 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) #ifdef WOLFSSL_STATIC_MEMORY static void SSL_CtxResourceFreeStaticMem(void* heap) { +#ifndef SINGLE_THREADED if (heap != NULL #ifdef WOLFSSL_HEAP_TEST /* avoid dereferencing a test value */ @@ -2784,6 +2783,9 @@ static void SSL_CtxResourceFreeStaticMem(void* heap) WOLFSSL_HEAP* mem = hint->memory; wc_FreeMutex(&mem->memory_mutex); } +#else + (void)heap; +#endif } #endif /* WOLFSSL_STATIC_MEMORY */ @@ -2883,100 +2885,92 @@ void InitCiphers(WOLFSSL* ssl) } - -/* Free ciphers */ -void FreeCiphers(WOLFSSL* ssl) +static void FreeCiphersSide(Ciphers *cipher, void* heap) { - (void)ssl; #ifdef BUILD_ARC4 - wc_Arc4Free(ssl->encrypt.arc4); - wc_Arc4Free(ssl->decrypt.arc4); - XFREE(ssl->encrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER); + wc_Arc4Free(cipher->arc4); + XFREE(cipher->arc4, heap, DYNAMIC_TYPE_CIPHER); + cipher->arc4 = NULL; #endif #ifdef BUILD_DES3 - wc_Des3Free(ssl->encrypt.des3); - wc_Des3Free(ssl->decrypt.des3); - XFREE(ssl->encrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER); + wc_Des3Free(cipher->des3); + XFREE(cipher->des3, heap, DYNAMIC_TYPE_CIPHER); + cipher->des3 = NULL; #endif #if defined(BUILD_AES) || defined(BUILD_AESGCM) || defined(HAVE_ARIA) - /* See: InitKeys() in keys.c on addition of BUILD_AESGCM check (enc->aes, dec->aes) */ - wc_AesFree(ssl->encrypt.aes); - wc_AesFree(ssl->decrypt.aes); - XFREE(ssl->encrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); + /* See: InitKeys() in keys.c on addition of BUILD_AESGCM check (enc->aes, + * dec->aes) */ + wc_AesFree(cipher->aes); + XFREE(cipher->aes, heap, DYNAMIC_TYPE_CIPHER); + cipher->aes = NULL; #endif #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) - wc_Sm4Free(ssl->encrypt.sm4); - wc_Sm4Free(ssl->decrypt.sm4); - XFREE(ssl->encrypt.sm4, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.sm4, ssl->heap, DYNAMIC_TYPE_CIPHER); + wc_Sm4Free(cipher->sm4); + XFREE(cipher->sm4, heap, DYNAMIC_TYPE_CIPHER); + cipher->sm4 = NULL; #endif #if (defined(BUILD_AESGCM) || defined(BUILD_AESCCM) || defined(HAVE_ARIA)) && \ !defined(WOLFSSL_NO_TLS12) - XFREE(ssl->decrypt.additional, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->encrypt.additional, ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(cipher->additional, heap, DYNAMIC_TYPE_CIPHER); + cipher->additional = NULL; #endif #ifdef CIPHER_NONCE - XFREE(ssl->decrypt.nonce, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->encrypt.nonce, ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(cipher->nonce, heap, DYNAMIC_TYPE_CIPHER); + cipher->nonce = NULL; #endif #ifdef HAVE_ARIA - wc_AriaFreeCrypt(ssl->encrypt.aria); - wc_AriaFreeCrypt(ssl->decrypt.aria); - XFREE(ssl->encrypt.aria, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.aria, ssl->heap, DYNAMIC_TYPE_CIPHER); + wc_AriaFreeCrypt(cipher->aria); + XFREE(cipher->aria, heap, DYNAMIC_TYPE_CIPHER); + cipher->aria = NULL; #endif #ifdef HAVE_CAMELLIA - XFREE(ssl->encrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(cipher->cam, heap, DYNAMIC_TYPE_CIPHER); + cipher->cam = NULL; #endif #ifdef HAVE_CHACHA - if (ssl->encrypt.chacha) - ForceZero(ssl->encrypt.chacha, sizeof(ChaCha)); - if (ssl->decrypt.chacha) - ForceZero(ssl->decrypt.chacha, sizeof(ChaCha)); - XFREE(ssl->encrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER); + if (cipher->chacha) + ForceZero(cipher->chacha, sizeof(ChaCha)); + XFREE(cipher->chacha, heap, DYNAMIC_TYPE_CIPHER); + cipher->chacha = NULL; #endif +#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) + wc_HmacFree(cipher->hmac); + XFREE(cipher->hmac, heap, DYNAMIC_TYPE_CIPHER); + cipher->hmac = NULL; +#endif +} + +/* Free ciphers */ +void FreeCiphers(WOLFSSL* ssl) +{ + FreeCiphersSide(&ssl->encrypt, ssl->heap); + FreeCiphersSide(&ssl->decrypt, ssl->heap); + #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH) if (ssl->auth.poly1305) ForceZero(ssl->auth.poly1305, sizeof(Poly1305)); XFREE(ssl->auth.poly1305, ssl->heap, DYNAMIC_TYPE_CIPHER); -#endif -#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) - wc_HmacFree(ssl->encrypt.hmac); - wc_HmacFree(ssl->decrypt.hmac); - XFREE(ssl->encrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->decrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER); + ssl->auth.poly1305 = NULL; #endif #ifdef WOLFSSL_DTLS13 #ifdef BUILD_AES - if (ssl->dtlsRecordNumberEncrypt.aes != NULL) { - wc_AesFree(ssl->dtlsRecordNumberEncrypt.aes); - XFREE(ssl->dtlsRecordNumberEncrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); - ssl->dtlsRecordNumberEncrypt.aes = NULL; - } - if (ssl->dtlsRecordNumberDecrypt.aes != NULL) { - wc_AesFree(ssl->dtlsRecordNumberDecrypt.aes); - XFREE(ssl->dtlsRecordNumberDecrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); - ssl->dtlsRecordNumberDecrypt.aes = NULL; - } + wc_AesFree(ssl->dtlsRecordNumberEncrypt.aes); + wc_AesFree(ssl->dtlsRecordNumberDecrypt.aes); + XFREE(ssl->dtlsRecordNumberEncrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(ssl->dtlsRecordNumberDecrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER); + ssl->dtlsRecordNumberEncrypt.aes = NULL; + ssl->dtlsRecordNumberDecrypt.aes = NULL; #endif /* BUILD_AES */ #ifdef HAVE_CHACHA - XFREE(ssl->dtlsRecordNumberEncrypt.chacha, - ssl->heap, DYNAMIC_TYPE_CIPHER); - XFREE(ssl->dtlsRecordNumberDecrypt.chacha, - ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(ssl->dtlsRecordNumberEncrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER); + XFREE(ssl->dtlsRecordNumberDecrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER); ssl->dtlsRecordNumberEncrypt.chacha = NULL; ssl->dtlsRecordNumberDecrypt.chacha = NULL; #endif /* HAVE_CHACHA */ #endif /* WOLFSSL_DTLS13 */ } - void InitCipherSpecs(CipherSpecs* cs) { XMEMSET(cs, 0, sizeof(CipherSpecs)); @@ -3268,9 +3262,13 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, int haveRSAsig = 1; #ifdef WOLFSSL_DTLS - /* If DTLS v1.2 or later than set tls1_2 flag */ - if (pv.major == DTLS_MAJOR && pv.minor <= DTLSv1_2_MINOR) { - tls1_2 = 1; + if (pv.major == DTLS_MAJOR) { + dtls = 1; + tls = 1; + /* May be dead assignments dependent upon configuration */ + (void) dtls; + (void) tls; + tls1_2 = pv.minor <= DTLSv1_2_MINOR; } #endif @@ -3381,17 +3379,6 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, haveRSAsig = 0; /* can't have RSA sig if don't have RSA */ #endif -#ifdef WOLFSSL_DTLS - if (pv.major == DTLS_MAJOR) { - dtls = 1; - tls = 1; - /* May be dead assignments dependent upon configuration */ - (void) dtls; - (void) tls; - tls1_2 = pv.minor <= DTLSv1_2_MINOR; - } -#endif - #ifdef HAVE_RENEGOTIATION_INDICATION if (side == WOLFSSL_CLIENT_END) { suites->suites[idx++] = CIPHER_BYTE; @@ -4568,23 +4555,17 @@ void FreeX509(WOLFSSL_X509* x509) x509->authKeyId = NULL; XFREE(x509->subjKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT); x509->subjKeyId = NULL; - if (x509->authInfo != NULL) { - XFREE(x509->authInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); - x509->authInfo = NULL; - } - if (x509->rawCRLInfo != NULL) { - XFREE(x509->rawCRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); - x509->rawCRLInfo = NULL; - } - if (x509->CRLInfo != NULL) { - XFREE(x509->CRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); - x509->CRLInfo = NULL; - } + wolfSSL_ASN1_STRING_free(x509->subjKeyIdStr); + x509->subjKeyIdStr = NULL; + XFREE(x509->authInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); + x509->authInfo = NULL; + XFREE(x509->rawCRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); + x509->rawCRLInfo = NULL; + XFREE(x509->CRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT); + x509->CRLInfo = NULL; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ defined(WOLFSSL_QT) - if (x509->authInfoCaIssuer != NULL) { - XFREE(x509->authInfoCaIssuer, x509->heap, DYNAMIC_TYPE_X509_EXT); - } + XFREE(x509->authInfoCaIssuer, x509->heap, DYNAMIC_TYPE_X509_EXT); if (x509->ext_sk != NULL) { wolfSSL_sk_X509_EXTENSION_pop_free(x509->ext_sk, NULL); } @@ -4639,11 +4620,16 @@ void FreeX509(WOLFSSL_X509* x509) x509->altNames = NULL; } -#ifdef WOLFSSL_DUAL_ALG_CERTS + #ifdef WOLFSSL_DUAL_ALG_CERTS XFREE(x509->sapkiDer, x509->heap, DYNAMIC_TYPE_X509_EXT); + x509->sapkiDer = NULL; XFREE(x509->altSigAlgDer, x509->heap, DYNAMIC_TYPE_X509_EXT); - XFREE(x509->altSigValDer, x509->heap, DYNAMIC_TYPE_X509_EXT); -#endif /* WOLFSSL_DUAL_ALG_CERTS */ + x509->altSigAlgDer = NULL; + if (x509->altSigValDer) { + XFREE(x509->altSigValDer, x509->heap, DYNAMIC_TYPE_X509_EXT); + x509->altSigValDer= NULL; + } + #endif /* WOLFSSL_DUAL_ALG_CERTS */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) wolfSSL_RefFree(&x509->ref); @@ -4758,8 +4744,7 @@ static void SetDigest(WOLFSSL* ssl, int hashAlgo) #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */ #endif /* !NO_CERTS */ -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) -static word32 MacSize(const WOLFSSL* ssl) +word32 MacSize(const WOLFSSL* ssl) { #ifdef HAVE_TRUNCATED_HMAC word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ @@ -4770,7 +4755,6 @@ static word32 MacSize(const WOLFSSL* ssl) return digestSz; } -#endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */ #ifndef NO_RSA #if !defined(WOLFSSL_NO_TLS12) || \ @@ -6804,19 +6788,67 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #endif /* HAVE_RPK */ #ifndef NO_CERTS +#ifdef WOLFSSL_COPY_CERT + /* If WOLFSSL_COPY_CERT is defined, always copy the cert */ + if (ctx->certificate != NULL) { + ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer, + ctx->certificate->length, ctx->certificate->type, + ctx->certificate->heap); + if (ret != 0) { + return ret; + } + + ssl->buffers.weOwnCert = 1; + ret = WOLFSSL_SUCCESS; + } + if (ctx->certChain != NULL) { + ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer, + ctx->certChain->length, ctx->certChain->type, + ctx->certChain->heap); + if (ret != 0) { + return ret; + } + + ssl->buffers.weOwnCertChain = 1; + ret = WOLFSSL_SUCCESS; + } +#else /* ctx still owns certificate, certChain, key, dh, and cm */ ssl->buffers.certificate = ctx->certificate; ssl->buffers.certChain = ctx->certChain; +#endif #ifdef WOLFSSL_TLS13 ssl->buffers.certChainCnt = ctx->certChainCnt; #endif #ifndef WOLFSSL_BLIND_PRIVATE_KEY +#ifdef WOLFSSL_COPY_KEY + if (ctx->privateKey != NULL) { + if (ssl->buffers.key != NULL) { + FreeDer(&ssl->buffers.key); + } + ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ctx->privateKey->length, ctx->privateKey->type, + ctx->privateKey->heap); + if (ret != 0) { + return ret; + } + ssl->buffers.weOwnKey = 1; + ret = WOLFSSL_SUCCESS; + } + else { + ssl->buffers.key = ctx->privateKey; + } +#else ssl->buffers.key = ctx->privateKey; +#endif #else if (ctx->privateKey != NULL) { - AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, ctx->privateKey->length, ctx->privateKey->type, ctx->privateKey->heap); + if (ret != 0) { + return ret; + } ssl->buffers.weOwnKey = 1; /* Blind the private key for the SSL with new random mask. */ wolfssl_priv_der_unblind(ssl->buffers.key, ctx->privateKeyMask); @@ -6837,9 +6869,12 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->buffers.altKey = ctx->altPrivateKey; #else if (ctx->altPrivateKey != NULL) { - AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, + ret = AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, ctx->altPrivateKey->length, ctx->altPrivateKey->type, ctx->altPrivateKey->heap); + if (ret != 0) { + return ret; + } /* Blind the private key for the SSL with new random mask. */ wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask); ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, @@ -6847,6 +6882,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) if (ret != 0) { return ret; } + ret = WOLFSSL_SUCCESS; } #endif ssl->buffers.altKeyType = ctx->altPrivateKeyType; @@ -6893,7 +6929,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) } } /* writeDup check */ - if (ctx->mask != 0 && wolfSSL_set_options(ssl, ctx->mask) == 0) { + if (ctx->mask != 0 && wolfSSL_set_options(ssl, (long)ctx->mask) == 0) { WOLFSSL_MSG("wolfSSL_set_options error"); return BAD_FUNC_ARG; } @@ -6916,12 +6952,12 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #endif #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) /* Don't change recv callback if currently using BIO's */ - if (ssl->CBIORecv != BioReceive) + if (ssl->CBIORecv != SslBioReceive) #endif ssl->CBIORecv = ctx->CBIORecv; #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) /* Don't change send callback if currently using BIO's */ - if (ssl->CBIOSend != BioSend) + if (ssl->CBIOSend != SslBioSend) #endif ssl->CBIOSend = ctx->CBIOSend; ssl->verifyDepth = ctx->verifyDepth; @@ -7235,6 +7271,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl_hint->memory = ctx_hint->memory; #ifndef WOLFSSL_STATIC_MEMORY_LEAN + #ifndef SINGLE_THREADED /* lock and check IO count / handshake count */ if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); @@ -7243,10 +7280,13 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E); return BAD_MUTEX_E; } + #endif if (ctx_hint->memory->maxHa > 0 && ctx_hint->memory->maxHa <= ctx_hint->memory->curHa) { WOLFSSL_MSG("At max number of handshakes for static memory"); + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL); ssl->heap = NULL; /* free and set to NULL for IO counter */ return MEMORY_E; @@ -7255,7 +7295,9 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) if (ctx_hint->memory->maxIO > 0 && ctx_hint->memory->maxIO <= ctx_hint->memory->curIO) { WOLFSSL_MSG("At max number of IO allowed for static memory"); + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL); ssl->heap = NULL; /* free and set to NULL for IO counter */ return MEMORY_E; @@ -7263,7 +7305,9 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ctx_hint->memory->curIO++; ctx_hint->memory->curHa++; ssl_hint->haFlag = 1; + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif /* check if tracking stats */ if (ctx_hint->memory->flag & WOLFMEM_TRACK_STATS) { @@ -7277,25 +7321,35 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) /* check if using fixed IO buffers */ if (ctx_hint->memory->flag & WOLFMEM_IO_POOL_FIXED) { + #ifndef SINGLE_THREADED if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) { WOLFSSL_MSG("Bad memory_mutex lock"); WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E); return BAD_MUTEX_E; } + #endif if (SetFixedIO(ctx_hint->memory, &(ssl_hint->inBuf)) != 1) { + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif return MEMORY_E; } if (SetFixedIO(ctx_hint->memory, &(ssl_hint->outBuf)) != 1) { + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif return MEMORY_E; } if (ssl_hint->outBuf == NULL || ssl_hint->inBuf == NULL) { WOLFSSL_MSG("Not enough memory to create fixed IO buffers"); + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif return MEMORY_E; } + #ifndef SINGLE_THREADED wc_UnLockMutex(&(ctx_hint->memory->memory_mutex)); + #endif } #endif /* !WOLFSSL_STATIC_MEMORY_LEAN */ #ifdef WOLFSSL_HEAP_TEST @@ -7315,6 +7369,15 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer; ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN; +#ifdef WOLFSSL_THREADED_CRYPT + { + int i; + for (i = 0; i < WOLFSSL_THREADED_CRYPT_CNT; i++) { + ssl->buffers.encrypt[i].avail = 1; + } + } +#endif + #ifdef KEEP_PEER_CERT InitX509(&ssl->peerCert, 0, ssl->heap); #endif @@ -7469,6 +7532,9 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) ssl->options.disallowEncThenMac = ctx->disallowEncThenMac; #endif +#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) + ssl->options.disableECH = ctx->disableECH; +#endif /* default alert state (none) */ ssl->alert_history.last_rx.code = -1; @@ -7532,7 +7598,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) /* requires valid arrays and suites unless writeDup ing */ if ((ret = SetSSL_CTX(ssl, ctx, writeDup)) != WOLFSSL_SUCCESS #ifdef WOLFSSL_NO_INIT_CTX_KEY - && ret != NO_PRIVATE_KEY + && ret != WC_NO_ERR_TRACE(NO_PRIVATE_KEY) #endif ) { WOLFSSL_MSG_EX("SetSSL_CTX failed. err = %d", ret); @@ -7649,6 +7715,13 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->dtls13DecryptEpoch = &ssl->dtls13Epochs[0]; ssl->options.dtls13SendMoreAcks = WOLFSSL_DTLS13_SEND_MOREACK_DEFAULT; ssl->dtls13Rtx.rtxRecordTailPtr = &ssl->dtls13Rtx.rtxRecords; + +#ifdef WOLFSSL_RW_THREADED + ret = wc_InitMutex(&ssl->dtls13Rtx.mutex); + if (ret < 0) { + return ret; + } +#endif #endif /* WOLFSSL_DTLS13 */ #ifdef WOLFSSL_QUIC @@ -7676,6 +7749,11 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->sigSpec = ctx->sigSpec; ssl->sigSpecSz = ctx->sigSpecSz; #endif /* WOLFSSL_DUAL_ALG_CERTS */ +#ifdef HAVE_OCSP +#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) + ssl->response_idx = 0; +#endif +#endif /* Returns 0 on success, not WOLFSSL_SUCCESS (1) */ WOLFSSL_MSG_EX("InitSSL done. return 0 (success)"); return 0; @@ -7774,7 +7852,7 @@ void FreeKey(WOLFSSL* ssl, int type, void** pKey) int AllocKey(WOLFSSL* ssl, int type, void** pKey) { int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); - int sz = 0; + size_t sz = 0; #ifdef HAVE_ECC ecc_key* eccKey; #endif /* HAVE_ECC */ @@ -8056,7 +8134,7 @@ void FreeKeyExchange(WOLFSSL* ssl) } /* Free handshake key */ - FreeKey(ssl, ssl->hsType, &ssl->hsKey); + FreeKey(ssl, (int)ssl->hsType, &ssl->hsKey); #ifdef WOLFSSL_DUAL_ALG_CERTS FreeKey(ssl, ssl->hsAltType, &ssl->hsAltKey); #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -8174,6 +8252,25 @@ void SSL_ResourceFree(WOLFSSL* ssl) ShrinkInputBuffer(ssl, FORCED_FREE); if (ssl->buffers.outputBuffer.dynamicFlag) ShrinkOutputBuffer(ssl); +#ifdef WOLFSSL_THREADED_CRYPT + { + int i; + for (i = 0; i < WOLFSSL_THREADED_CRYPT_CNT; i++) { + bufferStatic* buff = &ssl->buffers.encrypt[i].buffer; + + ssl->buffers.encrypt[i].stop = 1; + FreeCiphersSide(&ssl->buffers.encrypt[i].encrypt, ssl->heap); + if (buff->dynamicFlag) { + XFREE(buff->buffer - buff->offset, ssl->heap, + DYNAMIC_TYPE_OUT_BUFFER); + buff->buffer = buff->staticBuffer; + buff->bufferSize = STATIC_BUFFER_LEN; + buff->offset = 0; + buff->dynamicFlag = 0; + } + } + } +#endif #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER) if (ssl->buffers.tls13CookieSecret.buffer != NULL) { ForceZero(ssl->buffers.tls13CookieSecret.buffer, @@ -8342,9 +8439,7 @@ void SSL_ResourceFree(WOLFSSL* ssl) } #endif #ifdef OPENSSL_EXTRA - if (ssl->param) { - XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL); - } + XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL); #endif #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) while (ssl->certReqCtx != NULL) { @@ -8428,6 +8523,10 @@ void SSL_ResourceFree(WOLFSSL* ssl) #endif #ifdef WOLFSSL_DTLS13 Dtls13FreeFsmResources(ssl); + +#ifdef WOLFSSL_RW_THREADED + wc_FreeMutex(&ssl->dtls13Rtx.mutex); +#endif #endif /* WOLFSSL_DTLS13 */ #ifdef WOLFSSL_QUIC wolfSSL_quic_free(ssl); @@ -8887,8 +8986,7 @@ void DtlsMsgDelete(DtlsMsg* item, void* heap) DtlsMsgDestroyFragBucket(item->fragBucketList, heap); item->fragBucketList = next; } - if (item->raw != NULL) - XFREE(item->raw, heap, DYNAMIC_TYPE_DTLS_FRAG); + XFREE(item->raw, heap, DYNAMIC_TYPE_DTLS_FRAG); XFREE(item, heap, DYNAMIC_TYPE_DTLS_MSG); } } @@ -9892,7 +9990,7 @@ ProtocolVersion MakeDTLSv1_3(void) word32 LowResTimer(void) { int64_t t; - #if defined(CONFIG_ARCH_POSIX) + #if defined(CONFIG_ARCH_POSIX) && !defined(CONFIG_BOARD_NATIVE_POSIX) k_cpu_idle(); #endif t = k_uptime_get(); /* returns current uptime in milliseconds */ @@ -10083,6 +10181,13 @@ int HashOutput(WOLFSSL* ssl, const byte* output, int sz, int ivSz) sz -= dtls_record_extra; #endif /* WOLFSSL_DTLS13 */ } else { +#ifdef WOLFSSL_DTLS_CID + byte cidSz = DtlsGetCidTxSize(ssl); + if (IsEncryptionOn(ssl, 1) && cidSz > 0) { + adj += cidSz; + sz -= cidSz + 1; /* +1 to not hash the real content type */ + } +#endif adj += DTLS_RECORD_EXTRA; sz -= DTLS_RECORD_EXTRA; } @@ -10123,7 +10228,8 @@ int HashInput(WOLFSSL* ssl, const byte* input, int sz) /* add record layer header for message */ -static void AddRecordHeader(byte* output, word32 length, byte type, WOLFSSL* ssl, int epochOrder) +static void AddRecordHeader(byte* output, word32 length, byte type, + WOLFSSL* ssl, int epochOrder) { RecordLayerHeader* rl; @@ -10162,12 +10268,18 @@ static void AddRecordHeader(byte* output, word32 length, byte type, WOLFSSL* ssl } else { #ifdef WOLFSSL_DTLS - DtlsRecordLayerHeader* dtls; - /* dtls record layer header extensions */ - dtls = (DtlsRecordLayerHeader*)output; + DtlsRecordLayerHeader* dtls = (DtlsRecordLayerHeader*)output; +#ifdef WOLFSSL_DTLS_CID + byte cidSz = 0; + if (type == dtls12_cid && (cidSz = DtlsGetCidTxSize(ssl)) > 0) { + wolfSSL_dtls_cid_get_tx(ssl, output + DTLS12_CID_OFFSET, cidSz); + c16toa((word16)length, output + DTLS12_CID_OFFSET + cidSz); + } + else +#endif + c16toa((word16)length, dtls->length); WriteSEQ(ssl, epochOrder, dtls->sequence_number); - c16toa((word16)length, dtls->length); #endif } } @@ -10269,6 +10381,8 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, int maxFrag; int ret = 0; int headerSz; + int rHdrSz = 0; /* record header size */ + int hsHdrSz = 0; /* handshake header size */ WOLFSSL_ENTER("SendHandshakeMsg"); (void)type; @@ -10277,8 +10391,10 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, if (ssl == NULL || input == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) - headerSz = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ; + if (ssl->options.dtls) { + rHdrSz = DTLS_RECORD_HEADER_SZ; + hsHdrSz = DTLS_HANDSHAKE_HEADER_SZ; + } else #endif { @@ -10286,7 +10402,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, * per fragment like in DTLS. The handshake header should * already be in the input buffer. */ inputSz += HANDSHAKE_HEADER_SZ; - headerSz = RECORD_HEADER_SZ; + rHdrSz = RECORD_HEADER_SZ; } maxFrag = wolfSSL_GetMaxFragSize(ssl, (int)inputSz); @@ -10301,7 +10417,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, if (!ssl->options.buildingMsg) { /* Hash it before the loop as we modify the input with * encryption on */ - ret = HashOutput(ssl, input, headerSz + (int)inputSz, 0); + ret = HashRaw(ssl, input + rHdrSz, inputSz + hsHdrSz); if (ret != 0) return ret; #ifdef WOLFSSL_DTLS @@ -10311,6 +10427,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, ssl->keys.dtls_handshake_number--; #endif } + headerSz = rHdrSz + hsHdrSz; while (ssl->fragOffset < inputSz) { byte* output; int outputSz; @@ -10323,7 +10440,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, fragSz = inputSz - ssl->fragOffset; /* check for available size */ - outputSz = headerSz + fragSz; + outputSz = headerSz + (int)fragSz; if (IsEncryptionOn(ssl, 1)) outputSz += cipherExtraData(ssl); if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) @@ -10381,7 +10498,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, } #endif } - ssl->buffers.outputBuffer.length += outputSz; + ssl->buffers.outputBuffer.length += (word32)outputSz; #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) if (ssl->hsInfoOn) { AddPacketName(ssl, packetName); @@ -10431,14 +10548,14 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) if (ssl->CBIORecv == NULL) { WOLFSSL_MSG("Your IO Recv callback is null, please set"); - return -1; + return WOLFSSL_FATAL_ERROR; } retry: recvd = ssl->CBIORecv(ssl, (char *)buf, (int)sz, ssl->IOCB_ReadCtx); if (recvd < 0) { switch (recvd) { - case WOLFSSL_CBIO_ERR_GENERAL: /* general/unknown error */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_GENERAL): #ifdef WOLFSSL_APACHE_HTTPD #ifndef NO_BIO if (ssl->biord) { @@ -10450,26 +10567,26 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) } #endif #endif - return -1; + return WOLFSSL_FATAL_ERROR; - case WOLFSSL_CBIO_ERR_WANT_READ: /* want read, would block */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ): if (retryLimit > 0 && ssl->ctx->autoRetry && !ssl->options.handShakeDone && !ssl->options.dtls) { retryLimit--; goto retry; } - return WANT_READ; + return WC_NO_ERR_TRACE(WANT_READ); - case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_RST): #ifdef USE_WINDOWS_API if (ssl->options.dtls) { goto retry; } #endif ssl->options.connReset = 1; - return -1; + return WOLFSSL_FATAL_ERROR; - case WOLFSSL_CBIO_ERR_ISR: /* interrupt */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_ISR): /* interrupt */ /* see if we got our timeout */ #ifdef WOLFSSL_CALLBACKS if (ssl->toInfoOn) { @@ -10489,11 +10606,11 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) #endif goto retry; - case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* peer closed connection */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE): ssl->options.isClosed = 1; - return -1; + return WOLFSSL_FATAL_ERROR; - case WOLFSSL_CBIO_ERR_TIMEOUT: + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_TIMEOUT): #ifdef WOLFSSL_DTLS #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { @@ -10501,7 +10618,7 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) if (Dtls13RtxTimeout(ssl) < 0) { WOLFSSL_MSG( "Error trying to retransmit DTLS buffered message"); - return -1; + return WOLFSSL_FATAL_ERROR; } goto retry; } @@ -10516,7 +10633,7 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) goto retry; } #endif - return -1; + return WOLFSSL_FATAL_ERROR; default: WOLFSSL_MSG("Unexpected recv return code"); @@ -10549,8 +10666,8 @@ void ShrinkOutputBuffer(WOLFSSL* ssl) * calls ShrinkInputBuffer itself when it is safe to do so. Don't overuse it. */ void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree) { - int usedLength = ssl->buffers.inputBuffer.length - - ssl->buffers.inputBuffer.idx; + int usedLength = (int)(ssl->buffers.inputBuffer.length - + ssl->buffers.inputBuffer.idx); if (!forcedFree && (usedLength > STATIC_BUFFER_LEN || ssl->buffers.clearOutputBuffer.length > 0)) return; @@ -10609,19 +10726,19 @@ int SendBuffered(WOLFSSL* ssl) if (sent < 0) { switch (sent) { - case WOLFSSL_CBIO_ERR_WANT_WRITE: /* would block */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE): if (retryLimit > 0 && ssl->ctx->autoRetry && !ssl->options.handShakeDone && !ssl->options.dtls) { retryLimit--; goto retry; } - return WANT_WRITE; + return WC_NO_ERR_TRACE(WANT_WRITE); - case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_RST): ssl->options.connReset = 1; break; - case WOLFSSL_CBIO_ERR_ISR: /* interrupt */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_ISR): /* interrupt */ /* see if we got our timeout */ #ifdef WOLFSSL_CALLBACKS if (ssl->toInfoOn) { @@ -10641,7 +10758,7 @@ int SendBuffered(WOLFSSL* ssl) #endif continue; - case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* epipe / conn closed */ + case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE): /* epipe */ ssl->options.connReset = 1; /* treat same as reset */ break; @@ -10657,8 +10774,8 @@ int SendBuffered(WOLFSSL* ssl) return SEND_OOB_READ_E; } - ssl->buffers.outputBuffer.idx += sent; - ssl->buffers.outputBuffer.length -= sent; + ssl->buffers.outputBuffer.idx += (word32)sent; + ssl->buffers.outputBuffer.length -= (word32)sent; } ssl->buffers.outputBuffer.idx = 0; @@ -10669,6 +10786,69 @@ int SendBuffered(WOLFSSL* ssl) return 0; } +#ifdef WOLFSSL_THREADED_CRYPT +static WC_INLINE int GrowAnOutputBuffer(WOLFSSL* ssl, + bufferStatic* outputBuffer, int size) +{ + byte* tmp; +#if WOLFSSL_GENERAL_ALIGNMENT > 0 + byte hdrSz = ssl->options.dtls ? DTLS_RECORD_HEADER_SZ : + RECORD_HEADER_SZ; + byte align = WOLFSSL_GENERAL_ALIGNMENT; +#else + const byte align = WOLFSSL_GENERAL_ALIGNMENT; +#endif + +#if WOLFSSL_GENERAL_ALIGNMENT > 0 + /* the encrypted data will be offset from the front of the buffer by + the header, if the user wants encrypted alignment they need + to define their alignment requirement */ + + while (align < hdrSz) + align *= 2; +#endif + + tmp = (byte*)XMALLOC(size + outputBuffer->length + align, + ssl->heap, DYNAMIC_TYPE_OUT_BUFFER); + WOLFSSL_MSG("growing output buffer"); + + if (tmp == NULL) + return MEMORY_E; + +#if WOLFSSL_GENERAL_ALIGNMENT > 0 + if (align) + tmp += align - hdrSz; +#endif + +#ifdef WOLFSSL_STATIC_MEMORY + /* can be from IO memory pool which does not need copy if same buffer */ + if (outputBuffer->length && tmp == outputBuffer->buffer) { + outputBuffer->bufferSize = size + outputBuffer->length; + return 0; + } +#endif + + if (outputBuffer->length) + XMEMCPY(tmp, outputBuffer->buffer, outputBuffer->length); + + if (outputBuffer->dynamicFlag) { + XFREE(outputBuffer->buffer - outputBuffer->offset, ssl->heap, + DYNAMIC_TYPE_OUT_BUFFER); + } + +#if WOLFSSL_GENERAL_ALIGNMENT > 0 + if (align) + outputBuffer->offset = align - hdrSz; + else +#endif + outputBuffer->offset = 0; + + outputBuffer->buffer = tmp; + outputBuffer->dynamicFlag = 1; + outputBuffer->bufferSize = size + outputBuffer->length; + return 0; +} +#endif /* returns the current location in the output buffer to start writing to */ byte* GetOutputBuffer(WOLFSSL* ssl) @@ -10781,7 +10961,7 @@ int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength) return BAD_FUNC_ARG; } - tmp = (byte*)XMALLOC(size + usedLength + align, + tmp = (byte*)XMALLOC((size_t)(size + usedLength + align), ssl->heap, DYNAMIC_TYPE_IN_BUFFER); WOLFSSL_MSG("growing input buffer"); @@ -10825,7 +11005,7 @@ int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength) ssl->buffers.inputBuffer.offset = 0; ssl->buffers.inputBuffer.buffer = tmp; - ssl->buffers.inputBuffer.bufferSize = size + usedLength; + ssl->buffers.inputBuffer.bufferSize = (word32)(size + usedLength); ssl->buffers.inputBuffer.idx = 0; ssl->buffers.inputBuffer.length = (word32)usedLength; @@ -10992,13 +11172,8 @@ int MsgCheckEncryption(WOLFSSL* ssl, byte type, byte encrypted) static WC_INLINE int isLastMsg(const WOLFSSL* ssl, word32 msgSz) { word32 extra = 0; - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) extra = ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - extra += MacSize(ssl); -#endif - } return (ssl->buffers.inputBuffer.idx - ssl->curStartIdx) + msgSz + extra == ssl->curSize; } @@ -11219,6 +11394,11 @@ static int GetDtls13RecordHeader(WOLFSSL* ssl, word32* inOutIdx, if (ret != 0) return ret; + if (ssl->dtls13CurRlLength > sizeof(ssl->dtls13CurRL)) { + WOLFSSL_MSG("Record header too long"); + return SEQUENCE_ERROR; + } + if (readSize < ssl->dtls13CurRlLength + DTLS13_RN_MASK_SIZE) { /* when using DTLS over a medium that does not guarantee that a full * message is received in a single read, we may end up without the full @@ -11271,6 +11451,9 @@ static int GetDtls13RecordHeader(WOLFSSL* ssl, word32* inOutIdx, static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, RecordLayerHeader* rh, word16* size) { +#ifdef WOLFSSL_DTLS_CID + byte cidSz = 0; +#endif #ifdef HAVE_FUZZER if (ssl->fuzzerCb) @@ -11288,8 +11471,8 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, if (ssl->options.tls1_3) { ret = GetDtls13RecordHeader(ssl, inOutIdx, rh, size); if (ret == 0 || - ret != WC_NO_ERR_TRACE(SEQUENCE_ERROR) || - ret != WC_NO_ERR_TRACE(DTLS_CID_ERROR)) + ((ret != WC_NO_ERR_TRACE(SEQUENCE_ERROR)) && + (ret != WC_NO_ERR_TRACE(DTLS_CID_ERROR)))) return ret; } @@ -11324,6 +11507,11 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, *inOutIdx += ENUM_LEN + VERSION_SZ; ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curEpoch); +#ifdef WOLFSSL_DTLS_CID + if (rh->type == dtls12_cid && (cidSz = DtlsGetCidRxSize(ssl)) == 0) + return DTLS_CID_ERROR; +#endif + #ifdef WOLFSSL_DTLS13 /* only non protected message can use the DTLSPlaintext record header */ if (IsAtLeastTLSv1_3(ssl->version)) { @@ -11355,6 +11543,21 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, ssl->keys.curSeq = w64From32(ssl->keys.curSeq_hi, ssl->keys.curSeq_lo); #endif /* WOLFSSL_DTLS13 */ +#ifdef WOLFSSL_DTLS_CID + if (rh->type == dtls12_cid) { + byte cid[DTLS_CID_MAX_SIZE]; + if (ssl->buffers.inputBuffer.length - *inOutIdx < + (word32)cidSz + LENGTH_SZ) + return LENGTH_ERROR; + if (cidSz > DTLS_CID_MAX_SIZE || + wolfSSL_dtls_cid_get_rx(ssl, cid, cidSz) != WOLFSSL_SUCCESS) + return DTLS_CID_ERROR; + if (XMEMCMP(ssl->buffers.inputBuffer.buffer + *inOutIdx, + cid, cidSz) != 0) + return DTLS_CID_ERROR; + *inOutIdx += cidSz; + } +#endif ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, size); *inOutIdx += LENGTH_SZ; @@ -11402,8 +11605,12 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, /* DTLSv1.3 MUST check window after deprotecting to avoid timing channel (RFC9147 Section 4.5.1) */ if (IsDtlsNotSctpMode(ssl) && !IsAtLeastTLSv1_3(ssl->version)) { + byte needsEnc = rh->type == application_data; /* can't be epoch 0 */ +#ifdef WOLFSSL_DTLS_CID + needsEnc = needsEnc || rh->type == dtls12_cid; +#endif if (!_DtlsCheckWindow(ssl) || - (rh->type == application_data && ssl->keys.curEpoch == 0) || + (needsEnc && ssl->keys.curEpoch == 0) || (rh->type == alert && ssl->options.handShakeDone && ssl->keys.curEpoch == 0 && ssl->keys.dtls_epoch != 0)) { WOLFSSL_LEAVE("GetRecordHeader()", SEQUENCE_ERROR); @@ -11450,7 +11657,7 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, } #endif /* WOLFSSL_DTLS13 */ /* Don't care about protocol version being lower than expected on alerts - * sent back before version negotitation. */ + * sent back before version negotiation. */ else if (!(ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.connectState == CLIENT_HELLO_SENT && rh->type == alert && @@ -11494,6 +11701,9 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, case change_cipher_spec: case application_data: case alert: +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + case dtls12_cid: +#endif #ifdef WOLFSSL_DTLS13 case ack: #endif /* WOLFSSL_DTLS13 */ @@ -12393,16 +12603,20 @@ int CipherRequires(byte first, byte second, int requirement) #ifndef NO_CERTS - /* Match names with wildcards, each wildcard can represent a single name component or fragment but not multiple names, i.e., *.z.com matches y.z.com but not x.y.z.com + If flags contains WOLFSSL_LEFT_MOST_WILDCARD_ONLY, wildcard only applies + to left-most name component, compatible with RFC 2830 identity checking. + return 1 on success */ int MatchDomainName(const char* pattern, int patternLen, const char* str, - word32 strLen) + word32 strLen, unsigned int flags) { int ret = 0; + byte wildcardEligible = 1; + byte leftWildcardOnly = flags & WOLFSSL_LEFT_MOST_WILDCARD_ONLY; if (pattern == NULL || str == NULL || patternLen <= 0 || strLen == 0) return 0; @@ -12415,11 +12629,16 @@ int MatchDomainName(const char* pattern, int patternLen, const char* str, pattern++; - if (p == '*') { + if ((p == '*') && wildcardEligible) { char s; /* We will always match '*' */ patternLen--; + /* Only single wildcard allowed with strict left only */ + if (leftWildcardOnly) { + wildcardEligible = 0; + } + /* Consume any extra '*' chars until the next non '*' char. */ while (patternLen > 0) { p = (char)XTOLOWER((unsigned char)*pattern); @@ -12428,6 +12647,10 @@ int MatchDomainName(const char* pattern, int patternLen, const char* str, return 0; if (p != '*') break; + if (leftWildcardOnly && (p == '*')) { + /* RFC2830 only allows single left-most wildcard */ + return 0; + } patternLen--; } @@ -12459,6 +12682,11 @@ int MatchDomainName(const char* pattern, int patternLen, const char* str, } } else { + /* Past left-most wildcard location, not eligible if flag set*/ + if (leftWildcardOnly && wildcardEligible) { + wildcardEligible = 0; + } + /* Simple case, pattern match exactly */ if (p != (char)XTOLOWER((unsigned char) *str)) return 0; @@ -12490,7 +12718,7 @@ int MatchDomainName(const char* pattern, int patternLen, const char* str, * -1 : No matches and wild pattern match failed. */ int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, - int* checkCN) + int* checkCN, unsigned int flags) { int match = 0; DNS_entry* altName = NULL; @@ -12509,19 +12737,19 @@ int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, while (altName) { WOLFSSL_MSG("\tindividual AltName check"); -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME if (altName->type == ASN_IP_TYPE) { buf = altName->ipString; len = (word32)XSTRLEN(buf); } else -#endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ +#endif /* WOLFSSL_IP_ALT_NAME */ { buf = altName->name; len = (word32)altName->len; } - if (MatchDomainName(buf, (int)len, domain, domainLen)) { + if (MatchDomainName(buf, (int)len, domain, domainLen, flags)) { match = 1; if (checkCN != NULL) { *checkCN = 0; @@ -12550,13 +12778,14 @@ int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, * domainNameLen The length of the domain name. * returns DOMAIN_NAME_MISMATCH when no match found and 0 on success. */ -int CheckHostName(DecodedCert* dCert, const char *domainName, size_t domainNameLen) +int CheckHostName(DecodedCert* dCert, const char *domainName, + size_t domainNameLen, unsigned int flags) { int checkCN; int ret = WC_NO_ERR_TRACE(DOMAIN_NAME_MISMATCH); if (CheckForAltNames(dCert, domainName, (word32)domainNameLen, - &checkCN) != 1) { + &checkCN, flags) != 1) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_MSG("DomainName match on alt names failed"); } @@ -12567,7 +12796,7 @@ int CheckHostName(DecodedCert* dCert, const char *domainName, size_t domainNameL #ifndef WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY if (checkCN == 1) { if (MatchDomainName(dCert->subjectCN, dCert->subjectCNLen, - domainName, (word32)domainNameLen) == 1) { + domainName, (word32)domainNameLen, flags) == 1) { ret = 0; } else { @@ -12584,7 +12813,7 @@ int CheckIPAddr(DecodedCert* dCert, const char* ipasc) { WOLFSSL_MSG("Checking IPAddr"); - return CheckHostName(dCert, ipasc, (size_t)XSTRLEN(ipasc)); + return CheckHostName(dCert, ipasc, (size_t)XSTRLEN(ipasc), 0); } @@ -12605,40 +12834,9 @@ static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain, #endif #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \ - defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType) -{ - if (name->dynamicName) { - XFREE(name->name, name->heap, DYNAMIC_TYPE_X509); - name->name = name->staticName; - name->dynamicName = 0; - } - - if (nameType == SUBJECT) { - XSTRNCPY(name->name, dCert->subject, ASN_NAME_MAX); - name->name[ASN_NAME_MAX - 1] = '\0'; - name->sz = (int)XSTRLEN(name->name) + 1; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) - name->rawLen = min(dCert->subjectRawLen, ASN_NAME_MAX); - if (name->rawLen > 0) - XMEMCPY(name->raw, dCert->subjectRaw, name->rawLen); -#endif - } - else { - XSTRNCPY(name->name, dCert->issuer, ASN_NAME_MAX); - name->name[ASN_NAME_MAX - 1] = '\0'; - name->sz = (int)XSTRLEN(name->name) + 1; -#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) \ - && (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)) - name->rawLen = min(dCert->issuerRawLen, ASN_NAME_MAX); - if (name->rawLen > 0) { - XMEMCPY(name->raw, dCert->issuerRaw, name->rawLen); - } -#endif - } -} - -static int CopyAltNames(DNS_entry** to, DNS_entry* from, int type, void* heap) + defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_ACERT) + static int CopyAltNames(DNS_entry** to, DNS_entry* from, int type, void* heap) { /* Copy from to the beginning of to */ DNS_entry** prev_next = to; @@ -12669,6 +12867,44 @@ static int CopyAltNames(DNS_entry** to, DNS_entry* from, int type, void* heap) return 0; } +#endif /* KEEP_PEER_CERT || SESSION_CERTS || + * OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || + * WOLFSSL_ACERT */ + + +#if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \ + defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType) +{ + if (name->dynamicName) { + XFREE(name->name, name->heap, DYNAMIC_TYPE_X509); + name->name = name->staticName; + name->dynamicName = 0; + } + + if (nameType == ASN_SUBJECT) { + XSTRNCPY(name->name, dCert->subject, ASN_NAME_MAX); + name->name[ASN_NAME_MAX - 1] = '\0'; + name->sz = (int)XSTRLEN(name->name) + 1; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) + name->rawLen = min(dCert->subjectRawLen, ASN_NAME_MAX); + if (name->rawLen > 0) + XMEMCPY(name->raw, dCert->subjectRaw, name->rawLen); +#endif + } + else { + XSTRNCPY(name->name, dCert->issuer, ASN_NAME_MAX); + name->name[ASN_NAME_MAX - 1] = '\0'; + name->sz = (int)XSTRLEN(name->name) + 1; +#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) \ + && (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)) + name->rawLen = min(dCert->issuerRawLen, ASN_NAME_MAX); + if (name->rawLen > 0) { + XMEMCPY(name->raw, dCert->issuerRaw, name->rawLen); + } +#endif + } +} #ifdef WOLFSSL_CERT_REQ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) @@ -12786,6 +13022,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) { int ret = 0; + int minSz; if (x509 == NULL || dCert == NULL || dCert->subjectCNLen < 0) @@ -12799,7 +13036,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) x509->version = dCert->version + 1; - CopyDecodedName(&x509->issuer, dCert, ISSUER); + CopyDecodedName(&x509->issuer, dCert, ASN_ISSUER); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) if (dCert->issuerName != NULL) { wolfSSL_X509_set_issuer_name(x509, @@ -12807,7 +13044,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) x509->issuer.x509 = x509; } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ - CopyDecodedName(&x509->subject, dCert, SUBJECT); + CopyDecodedName(&x509->subject, dCert, ASN_SUBJECT); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) if (dCert->subjectName != NULL) { wolfSSL_X509_set_subject_name(x509, @@ -12835,49 +13072,45 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) #endif /* WOLFSSL_CERT_REQ */ #ifdef WOLFSSL_SEP - { - int minSz = min(dCert->deviceTypeSz, EXTERNAL_SERIAL_SIZE); - if (minSz > 0) { - x509->deviceTypeSz = minSz; - XMEMCPY(x509->deviceType, dCert->deviceType, minSz); - } - else - x509->deviceTypeSz = 0; - minSz = min(dCert->hwTypeSz, EXTERNAL_SERIAL_SIZE); - if (minSz > 0) { - x509->hwTypeSz = minSz; - XMEMCPY(x509->hwType, dCert->hwType, minSz); - } - else - x509->hwTypeSz = 0; - minSz = min(dCert->hwSerialNumSz, EXTERNAL_SERIAL_SIZE); - if (minSz > 0) { - x509->hwSerialNumSz = minSz; - XMEMCPY(x509->hwSerialNum, dCert->hwSerialNum, minSz); - } - else - x509->hwSerialNumSz = 0; + minSz = min(dCert->deviceTypeSz, EXTERNAL_SERIAL_SIZE); + if (minSz > 0) { + x509->deviceTypeSz = minSz; + XMEMCPY(x509->deviceType, dCert->deviceType, minSz); } + else + x509->deviceTypeSz = 0; + minSz = min(dCert->hwTypeSz, EXTERNAL_SERIAL_SIZE); + if (minSz > 0) { + x509->hwTypeSz = minSz; + XMEMCPY(x509->hwType, dCert->hwType, minSz); + } + else + x509->hwTypeSz = 0; + minSz = min(dCert->hwSerialNumSz, EXTERNAL_SERIAL_SIZE); + if (minSz > 0) { + x509->hwSerialNumSz = minSz; + XMEMCPY(x509->hwSerialNum, dCert->hwSerialNum, minSz); + } + else + x509->hwSerialNumSz = 0; #endif /* WOLFSSL_SEP */ - { - int minSz; - if (dCert->beforeDateLen > 0) { - minSz = (int)min(dCert->beforeDate[1], MAX_DATE_SZ); - x509->notBefore.type = dCert->beforeDate[0]; - x509->notBefore.length = minSz; - XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz); - } - else - x509->notBefore.length = 0; - if (dCert->afterDateLen > 0) { - minSz = (int)min(dCert->afterDate[1], MAX_DATE_SZ); - x509->notAfter.type = dCert->afterDate[0]; - x509->notAfter.length = minSz; - XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz); - } - else - x509->notAfter.length = 0; + + if (dCert->beforeDateLen > 0) { + minSz = (int)min(dCert->beforeDate[1], MAX_DATE_SZ); + x509->notBefore.type = dCert->beforeDate[0]; + x509->notBefore.length = minSz; + XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz); + } + else + x509->notBefore.length = 0; + if (dCert->afterDateLen > 0) { + minSz = (int)min(dCert->afterDate[1], MAX_DATE_SZ); + x509->notAfter.type = dCert->afterDate[0]; + x509->notAfter.length = minSz; + XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz); } + else + x509->notAfter.length = 0; if (dCert->publicKey != NULL && dCert->pubKeySize != 0) { x509->pubKey.buffer = (byte*)XMALLOC( @@ -13016,7 +13249,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) ret = MEMORY_E; } } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + #ifdef WOLFSSL_ASN_CA_ISSUER if (dCert->extAuthInfoCaIssuer != NULL && dCert->extAuthInfoCaIssuerSz > 0) { x509->authInfoCaIssuer = (byte*)XMALLOC(dCert->extAuthInfoCaIssuerSz, x509->heap, DYNAMIC_TYPE_X509_EXT); @@ -13102,10 +13335,10 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) #ifndef IGNORE_NETSCAPE_CERT_TYPE x509->nsCertType = dCert->nsCertType; #endif - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) + #ifdef WOLFSSL_SEP x509->certPolicySet = dCert->extCertPolicySet; x509->certPolicyCrit = dCert->extCertPolicyCrit; - #endif /* WOLFSSL_SEP || WOLFSSL_QT */ + #endif #ifdef WOLFSSL_CERT_EXT { int i; @@ -13179,14 +13412,135 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) #endif /* KEEP_PEER_CERT || SESSION_CERTS */ +#if defined(WOLFSSL_ACERT) +/* Copy a DecodedAcert structure to an X509_ACERT. + * + * @param [out] x509 the dst X509 acert structure + * @param [in] dAcert the src decoded acert structure + * + * @return 0 on success + * @return < 0 on error + * */ +int CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509, DecodedAcert* dAcert) +{ + int ret = 0; + + if (x509 == NULL || dAcert == NULL) { + return BAD_FUNC_ARG; + } + + /* Copy version and serial number. */ + x509->version = dAcert->version + 1; + + XMEMCPY(x509->serial, dAcert->serial, EXTERNAL_SERIAL_SIZE); + x509->serialSz = dAcert->serialSz; + + if (dAcert->holderSerialSz > 0) { + /* This ACERT Holder field had a serial number. Copy it. */ + XMEMCPY(x509->holderSerial, dAcert->holderSerial, + dAcert->holderSerialSz); + x509->holderSerialSz = dAcert->holderSerialSz; + } + + /* Copy before and after dates. */ + { + int minSz = 0; + + if (dAcert->beforeDateLen > 0) { + minSz = (int)min(dAcert->beforeDate[1], MAX_DATE_SZ); + x509->notBefore.type = dAcert->beforeDate[0]; + x509->notBefore.length = minSz; + XMEMCPY(x509->notBefore.data, &dAcert->beforeDate[2], minSz); + } + else { + x509->notBefore.length = 0; + } + + if (dAcert->afterDateLen > 0) { + minSz = (int)min(dAcert->afterDate[1], MAX_DATE_SZ); + x509->notAfter.type = dAcert->afterDate[0]; + x509->notAfter.length = minSz; + XMEMCPY(x509->notAfter.data, &dAcert->afterDate[2], minSz); + } + else { + x509->notAfter.length = 0; + } + } + + /* Copy the signature. */ + if (dAcert->signature != NULL && dAcert->sigLength != 0 && + dAcert->sigLength <= MAX_ENCODED_SIG_SZ) { + x509->sig.buffer = (byte*)XMALLOC( + dAcert->sigLength, x509->heap, DYNAMIC_TYPE_SIGNATURE); + if (x509->sig.buffer == NULL) { + ret = MEMORY_E; + } + else { + XMEMCPY(x509->sig.buffer, dAcert->signature, dAcert->sigLength); + x509->sig.length = dAcert->sigLength; + x509->sigOID = (int)dAcert->signatureOID; + } + } + + /* if der contains original source buffer then store for potential + * retrieval */ + if (dAcert->source != NULL && dAcert->maxIdx > 0) { + if (AllocDer(&x509->derCert, dAcert->maxIdx, CERT_TYPE, x509->heap) + == 0) { + XMEMCPY(x509->derCert->buffer, dAcert->source, dAcert->maxIdx); + } + else { + ret = MEMORY_E; + } + } + + /* Copy holder and att cert issuer names if present. */ + if (CopyAltNames(&x509->holderIssuerName, dAcert->holderIssuerName, + ASN_DIR_TYPE, x509->heap) != 0) { + return MEMORY_E; + } + + if (CopyAltNames(&x509->holderEntityName, dAcert->holderEntityName, + ASN_DIR_TYPE, x509->heap) != 0) { + return MEMORY_E; + } + + if (CopyAltNames(&x509->AttCertIssuerName, dAcert->AttCertIssuerName, + ASN_DIR_TYPE, x509->heap) != 0) { + return MEMORY_E; + } + + if (dAcert->rawAttr && dAcert->rawAttrLen > 0) { + /* Allocate space for the raw Attributes field, then copy it in. */ + x509->rawAttr = (byte*)XMALLOC(dAcert->rawAttrLen, x509->heap, + DYNAMIC_TYPE_X509_EXT); + if (x509->rawAttr != NULL) { + XMEMCPY(x509->rawAttr, dAcert->rawAttr, dAcert->rawAttrLen); + x509->rawAttrLen = dAcert->rawAttrLen; + } + else { + ret = MEMORY_E; + } + } + + return ret; +} +#endif /* WOLFSSL_ACERT */ + + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ (defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && !defined(WOLFSSL_NO_TLS12)) -static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, - word32 status_length) +static int ProcessCSR_ex(WOLFSSL* ssl, byte* input, word32* inOutIdx, + word32 status_length, int idx) { int ret = 0; OcspRequest* request; - +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) + TLSX* ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); + CertificateStatusRequest* csr; +#else + (void)idx; +#endif #ifdef WOLFSSL_SMALL_STACK CertStatus* status; OcspEntry* single; @@ -13198,11 +13552,19 @@ static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif WOLFSSL_ENTER("ProcessCSR"); - +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) + if (ext) { + /* status request */ + csr = (CertificateStatusRequest*)ext->data; + if (csr && !csr->ssl) + csr->ssl = ssl; + } +#endif do { #ifdef HAVE_CERTIFICATE_STATUS_REQUEST if (ssl->status_request) { - request = (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions); + request = (OcspRequest*)TLSX_CSR_GetRequest_ex(ssl->extensions, + idx); ssl->status_request = 0; break; } @@ -13225,24 +13587,28 @@ static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, #ifdef WOLFSSL_SMALL_STACK status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap, - DYNAMIC_TYPE_OCSP_STATUS); + DYNAMIC_TYPE_OCSP_STATUS); single = (OcspEntry*)XMALLOC(sizeof(OcspEntry), ssl->heap, - DYNAMIC_TYPE_OCSP_ENTRY); + DYNAMIC_TYPE_OCSP_ENTRY); response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap, - DYNAMIC_TYPE_OCSP_REQUEST); + DYNAMIC_TYPE_OCSP_REQUEST); if (status == NULL || single == NULL || response == NULL) { - if (status) + if (status != NULL) { XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS); - if (single) + } + if (single != NULL) { XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY); - if (response) + } + if (response != NULL) { XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); + } return MEMORY_ERROR; } #endif + /* InitOcspResponse sets single and status to response struct. */ InitOcspResponse(response, single, status, input +*inOutIdx, status_length, ssl->heap); if (OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, 0) != 0) @@ -13263,17 +13629,25 @@ static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, *inOutIdx += status_length; + /* FreeOcspResponse frees status and single only if + * single->isDynamic is set. */ FreeOcspResponse(response); #ifdef WOLFSSL_SMALL_STACK - XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS); - XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY); - XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); + XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS); + XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY); + XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); #endif WOLFSSL_LEAVE("ProcessCSR", ret); return ret; } + +static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx, + word32 status_length) +{ + return ProcessCSR_ex(ssl, input, inOutIdx, status_length, 0); +} #endif @@ -13526,8 +13900,7 @@ int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, if (x509 != NULL) wolfSSL_X509_free(x509); #endif - if (domain != NULL) - XFREE(domain, heap, DYNAMIC_TYPE_STRING); + XFREE(domain, heap, DYNAMIC_TYPE_STRING); return MEMORY_E; } @@ -13612,7 +13985,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int cert_err, /* If altNames names is present, then subject common name is ignored */ if (args->dCert->altNames != NULL) { if (CheckForAltNames(args->dCert, ssl->param->hostName, - (word32)XSTRLEN(ssl->param->hostName), NULL) != 1) { + (word32)XSTRLEN(ssl->param->hostName), NULL, 0) != 1) { if (cert_err == 0) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); @@ -13626,7 +13999,7 @@ int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int cert_err, args->dCert->subjectCN, args->dCert->subjectCNLen, ssl->param->hostName, - (word32)XSTRLEN(ssl->param->hostName)) == 0) { + (word32)XSTRLEN(ssl->param->hostName), 0) == 0) { if (cert_err == 0) { ret = DOMAIN_NAME_MISMATCH; WOLFSSL_ERROR_VERBOSE(ret); @@ -13806,15 +14179,11 @@ static void FreeProcPeerCertArgs(WOLFSSL* ssl, void* pArgs) (void)ssl; - if (args->certs) { - XFREE(args->certs, ssl->heap, DYNAMIC_TYPE_DER); - args->certs = NULL; - } + XFREE(args->certs, ssl->heap, DYNAMIC_TYPE_DER); + args->certs = NULL; #ifdef WOLFSSL_TLS13 - if (args->exts) { - XFREE(args->exts, ssl->heap, DYNAMIC_TYPE_CERT_EXT); - args->exts = NULL; - } + XFREE(args->exts, ssl->heap, DYNAMIC_TYPE_CERT_EXT); + args->exts = NULL; #endif if (args->dCert) { if (args->dCertInit) { @@ -13924,9 +14293,7 @@ int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type) /* / .(r)N\0 */ /*|1| 8 |1|1|1|1| => 13 */ len = (int)XSTRLEN(entry->dir_name) + 13; - if (filename != NULL) { - XFREE(filename, NULL, DYNAMIC_TYPE_OPENSSL); - } + XFREE(filename, NULL, DYNAMIC_TYPE_OPENSSL); filename = (char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL); if (filename == NULL) { @@ -14001,7 +14368,8 @@ int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type) ph->hash_value = hash; ph->last_suffix = suffix; - ret = wolfSSL_sk_BY_DIR_HASH_push(entry->hashes, ph); + ret = wolfSSL_sk_BY_DIR_HASH_push(entry->hashes, ph) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } } wc_UnLockMutex(&lookup->dirs->lock); @@ -14336,6 +14704,52 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) return ret; } +#if defined(HAVE_OCSP) && defined(WOLFSSL_TLS13) \ + && defined(HAVE_CERTIFICATE_STATUS_REQUEST) +static int ProcessPeerCertsChainOCSPStatusCheck(WOLFSSL* ssl) +{ + int ret = 0; + word32 i; + word32 idx = 0; + TLSX* ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); + CertificateStatusRequest* csr; + + if (ext) { + csr = (CertificateStatusRequest*)ext->data; + if (csr == NULL) { + return 0; + } + } else + return 0; + + /* error when leaf cert doesn't have certificate status */ + if (csr->requests < 1 || csr->responses[0].length == 0) { + WOLFSSL_MSG("Leaf cert doesn't have certificate status."); + return BAD_CERTIFICATE_STATUS_ERROR; + } + + for (i = 0; i < csr->requests; i++) { + if (csr->responses[i].length != 0) { + ssl->status_request = 1; + idx = 0; + ret = ProcessCSR_ex(ssl, + csr->responses[i].buffer, + &idx, csr->responses[i].length, i); + if (ret < 0) { + WOLFSSL_ERROR_VERBOSE(ret); + break; + } + } + else { + WOLFSSL_MSG("Intermediate cert doesn't have certificate status."); + } + } + + return ret; +} + +#endif + #ifdef HAVE_CRL static int ProcessPeerCertsChainCRLCheck(WOLFSSL* ssl, ProcPeerCertArgs* args) { @@ -14618,8 +15032,11 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, args->idx += extSz; listSz -= extSz + OPAQUE16_LEN; WOLFSSL_MSG_EX("\tParsing %d bytes of cert extensions", - args->exts[args->totalCerts].length); + args->exts[args->totalCerts].length); #if !defined(NO_TLS) + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) + ssl->response_idx = args->totalCerts; + #endif ret = TLSX_Parse(ssl, args->exts[args->totalCerts].buffer, (word16)args->exts[args->totalCerts].length, certificate, NULL); @@ -14805,13 +15222,22 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, #ifdef HAVE_OCSP #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 addToPendingCAs = 0; - if (ssl->status_request_v2 && TLSX_CSR2_IsMulti(ssl->extensions)) { + if (ssl->options.side == WOLFSSL_CLIENT_END && + ssl->status_request_v2 && + TLSX_CSR2_IsMulti(ssl->extensions)) { ret = TLSX_CSR2_InitRequests(ssl->extensions, args->dCert, 0, ssl->heap); addToPendingCAs = 1; } else /* skips OCSP and force CRL check */ #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) + if (IsAtLeastTLSv1_3(ssl->version)) { + ret = TLSX_CSR_InitRequest_ex(ssl->extensions, + args->dCert, ssl->heap, args->certIdx); + } + else + #endif if (SSL_CM(ssl)->ocspEnabled && SSL_CM(ssl)->ocspCheckAll) { WOLFSSL_MSG("Doing Non Leaf OCSP check"); @@ -15007,8 +15433,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (dCertAdd_inited) FreeDecodedCert(dCertAdd); #ifdef WOLFSSL_SMALL_STACK - if (dCertAdd) - XFREE(dCertAdd, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(dCertAdd, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif if (ret != 0) goto exit_ppc; @@ -15293,24 +15718,17 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ssl->options.side == WOLFSSL_CLIENT_END) { #ifdef HAVE_CERTIFICATE_STATUS_REQUEST if (ssl->status_request) { - args->fatal = (TLSX_CSR_InitRequest(ssl->extensions, - args->dCert, ssl->heap) != 0); + args->fatal = (TLSX_CSR_InitRequest_ex( + ssl->extensions, args->dCert, + ssl->heap, args->certIdx) != 0); doLookup = 0; WOLFSSL_MSG("\tHave status request"); #if defined(WOLFSSL_TLS13) if (ssl->options.tls1_3) { - TLSX* ext = TLSX_Find(ssl->extensions, - TLSX_STATUS_REQUEST); - if (ext != NULL) { - word32 idx = 0; - CertificateStatusRequest* csr = - (CertificateStatusRequest*)ext->data; - ret = ProcessCSR(ssl, csr->response.buffer, - &idx, csr->response.length); - if (ret < 0) { - WOLFSSL_ERROR_VERBOSE(ret); - goto exit_ppc; - } + ret = ProcessPeerCertsChainOCSPStatusCheck(ssl); + if (ret < 0) { + WOLFSSL_ERROR_VERBOSE(ret); + goto exit_ppc; } } #endif @@ -15350,9 +15768,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ssl->peerVerifyRet == 0) { /* Return first cert error here */ ssl->peerVerifyRet = - ret == OCSP_CERT_REVOKED - ? WOLFSSL_X509_V_ERR_CERT_REVOKED - : WOLFSSL_X509_V_ERR_CERT_REJECTED; + ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) + ? WOLFSSL_X509_V_ERR_CERT_REVOKED + : WOLFSSL_X509_V_ERR_CERT_REJECTED; } #endif } @@ -15381,7 +15799,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ssl->peerVerifyRet == 0) { /* Return first cert error here */ ssl->peerVerifyRet = - ret == CRL_CERT_REVOKED + ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED) ? WOLFSSL_X509_V_ERR_CERT_REVOKED : WOLFSSL_X509_V_ERR_CERT_REJECTED; } @@ -15520,7 +15938,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, (ssl->buffers.domainName.buffer == NULL ? 0 : (word32)XSTRLEN( (const char *)ssl->buffers.domainName.buffer)), - NULL) != 1) { + NULL, 0) != 1) { WOLFSSL_MSG("DomainName match on alt names failed"); /* try to get peer key still */ ret = DOMAIN_NAME_MISMATCH; @@ -15535,7 +15953,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, (ssl->buffers.domainName.buffer == NULL ? 0 : (word32)XSTRLEN( (const char *)ssl->buffers.domainName.buffer) - )) == 0) + ), 0) == 0) { WOLFSSL_MSG("DomainName match on common name failed"); ret = DOMAIN_NAME_MISMATCH; @@ -15548,14 +15966,14 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, args->dCert->subjectCNLen, (char*)ssl->buffers.domainName.buffer, (ssl->buffers.domainName.buffer == NULL ? 0 : - (word32)XSTRLEN(ssl->buffers.domainName.buffer))) == 0) + (word32)XSTRLEN(ssl->buffers.domainName.buffer)), 0) == 0) { WOLFSSL_MSG("DomainName match on common name failed"); if (CheckForAltNames(args->dCert, (char*)ssl->buffers.domainName.buffer, (ssl->buffers.domainName.buffer == NULL ? 0 : (word32)XSTRLEN(ssl->buffers.domainName.buffer)), - NULL) != 1) { + NULL, 0) != 1) { WOLFSSL_MSG( "DomainName match on alt names failed too"); /* try to get peer key still */ @@ -16025,13 +16443,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->options.serverState = SERVER_CERT_COMPLETE; } - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) args->idx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - args->idx += MacSize(ssl); - #endif - } /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_END; @@ -16196,12 +16609,9 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, DYNAMIC_TYPE_OCSP_REQUEST); if (status == NULL || single == NULL || response == NULL) { - if (status) - XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS); - if (single) - XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY); - if (response) - XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); + XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS); + XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY); + XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); return MEMORY_ERROR; } @@ -16294,20 +16704,9 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, } if (IsEncryptionOn(ssl, 0)) { - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + ssl->keys.padSz + digestSz > size) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz + digestSz; - } - else - #endif - { - if (*inOutIdx + ssl->keys.padSz > size) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz; - } + if (*inOutIdx + ssl->keys.padSz > size) + return BUFFER_E; + *inOutIdx += ssl->keys.padSz; } WOLFSSL_LEAVE("DoCertificateStatus", ret); @@ -16338,24 +16737,12 @@ static int DoHelloRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (IsEncryptionOn(ssl, 0)) { /* If size == totalSz then we are in DtlsMsgDrain so no need to worry * about padding */ - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - if (size != totalSz && - *inOutIdx + ssl->keys.padSz + digestSz > totalSz) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz + digestSz; - } - else - #endif - { - /* access beyond input + size should be checked against totalSz */ - if (size != totalSz && - *inOutIdx + ssl->keys.padSz > totalSz) - return BUFFER_E; + /* access beyond input + size should be checked against totalSz */ + if (size != totalSz && + *inOutIdx + ssl->keys.padSz > totalSz) + return BUFFER_E; - *inOutIdx += ssl->keys.padSz; - } + *inOutIdx += ssl->keys.padSz; } if (ssl->options.side == WOLFSSL_SERVER_END) { @@ -16392,17 +16779,8 @@ int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, * If size == totalSz then we are in DtlsMsgDrain so no need to worry about * padding */ if (size != totalSz) { - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - if (*inOutIdx + size + ssl->keys.padSz + MacSize(ssl) > totalSz) - return BUFFER_E; - } - else - #endif - { - if (*inOutIdx + size + ssl->keys.padSz > totalSz) - return BUFFER_E; - } + if (*inOutIdx + size + ssl->keys.padSz > totalSz) + return BUFFER_E; } #ifdef WOLFSSL_CALLBACKS @@ -16445,10 +16823,6 @@ int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, /* force input exhaustion at ProcessReply consuming padSz */ *inOutIdx += size + ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - *inOutIdx += MacSize(ssl); -#endif if (ssl->options.side == WOLFSSL_CLIENT_END) { ssl->options.serverState = SERVER_FINISHED_COMPLETE; @@ -16995,10 +17369,6 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, expectedIdx = *inOutIdx + size + (ssl->keys.encryptionOn ? ssl->keys.padSz : 0); -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead && ssl->keys.encryptionOn) - expectedIdx += MacSize(ssl); -#endif #if !defined(NO_WOLFSSL_SERVER) && \ defined(HAVE_SECURE_RENEGOTIATION) && \ @@ -17081,10 +17451,10 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* hello_request not hashed */ if (type != hello_request #ifdef WOLFSSL_ASYNC_CRYPT - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif #ifdef WOLFSSL_NONBLOCK_OCSP - && ssl->error != OCSP_WANT_READ + && ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ) #endif ) { ret = HashInput(ssl, input + *inOutIdx, (int)size); @@ -17101,6 +17471,18 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, case certificate_request: case server_hello_done: if (ssl->options.resuming) { + /* Client requested resumption, but server is doing a + * full handshake */ + + /* The server's decision to resume isn't known until after the + * "server_hello". If subsequent handshake messages like + * "certificate" or "server_key_exchange" are recevied then we + * are doing a full handshake */ + + /* If the server included a session id then we + * treat this as a fatal error, since the server said it was + * doing resumption, but did not. */ + /* https://www.rfc-editor.org/rfc/rfc5077.html#section-3.4 * Alternatively, the client MAY include an empty Session ID * in the ClientHello. In this case, the client ignores the @@ -17109,7 +17491,7 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, * messages. */ #ifndef WOLFSSL_WPAS - if (ssl->session->sessionIDSz != 0) { + if (ssl->arrays->sessionIDSz != 0) { /* Fatal error. Only try to send an alert. RFC 5246 does not * allow for reverting back to a full handshake after the * server has indicated the intention to do a resumption. */ @@ -17149,23 +17531,12 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, WOLFSSL_MSG("processing hello verify request"); ret = DoHelloVerifyRequest(ssl, input,inOutIdx, size); if (IsEncryptionOn(ssl, 0)) { - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz + digestSz; - } - else - #endif - { - /* access beyond input + size should be checked against totalSz - */ - if (*inOutIdx + ssl->keys.padSz > totalSz) - return BUFFER_E; + /* access beyond input + size should be checked against totalSz + */ + if (*inOutIdx + ssl->keys.padSz > totalSz) + return BUFFER_E; - *inOutIdx += ssl->keys.padSz; - } + *inOutIdx += ssl->keys.padSz; } break; @@ -17238,13 +17609,8 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, AddLateName("ServerHelloDone", &ssl->timeoutInfo); #endif ssl->options.serverState = SERVER_HELLODONE_COMPLETE; - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) *inOutIdx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - *inOutIdx += MacSize(ssl); - #endif - } break; case finished: @@ -17279,24 +17645,12 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* If size == totalSz then we are in DtlsMsgDrain so no need to worry * about padding */ if (IsEncryptionOn(ssl, 0)) { - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - if (size != totalSz && - *inOutIdx + ssl->keys.padSz + digestSz > totalSz) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz + digestSz; - } - else - #endif - { - /* access beyond input + size should be checked against totalSz - */ - if (size != totalSz && - *inOutIdx + ssl->keys.padSz > totalSz) - return BUFFER_E; - *inOutIdx += ssl->keys.padSz; - } + /* access beyond input + size should be checked against totalSz + */ + if (size != totalSz && + *inOutIdx + ssl->keys.padSz > totalSz) + return BUFFER_E; + *inOutIdx += ssl->keys.padSz; } break; @@ -18159,22 +18513,9 @@ static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, input + *inOutIdx, size, type, fragOffset, fragSz, ssl->heap); *inOutIdx += fragSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; - } - *inOutIdx += digestSz; - } - else - #endif - { - if (*inOutIdx + ssl->keys.padSz > totalSz) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; - } + if (*inOutIdx + ssl->keys.padSz > totalSz) { + WOLFSSL_ERROR(BUFFER_E); + return BUFFER_E; } *inOutIdx += ssl->keys.padSz; ret = 0; @@ -18215,22 +18556,9 @@ static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* Already saw this message and processed it. It can be ignored. */ WOLFSSL_MSG("Already saw this message and processed it"); *inOutIdx += fragSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; - } - *inOutIdx += digestSz; - } - else - #endif - { - if (*inOutIdx + ssl->keys.padSz > totalSz) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; - } + if (*inOutIdx + ssl->keys.padSz > totalSz) { + WOLFSSL_ERROR(BUFFER_E); + return BUFFER_E; } #ifndef WOLFSSL_DTLS_RESEND_ONLY_TIMEOUT if (IsDtlsNotSctpMode(ssl) && @@ -18263,17 +18591,11 @@ static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, input + *inOutIdx, size, type, fragOffset, fragSz, ssl->heap); *inOutIdx += fragSz; - *inOutIdx += ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + digestSz > totalSz) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; - } - *inOutIdx += digestSz; + if (*inOutIdx + ssl->keys.padSz > totalSz) { + WOLFSSL_ERROR(BUFFER_E); + return BUFFER_E; } -#endif + *inOutIdx += ssl->keys.padSz; ret = 0; if (ssl->dtls_rx_msg_list != NULL && ssl->dtls_rx_msg_list->ready) ret = DtlsMsgDrain(ssl); @@ -18293,14 +18615,6 @@ static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (idx + fragSz + ssl->keys.padSz > totalSz) return BUFFER_E; *inOutIdx = idx + fragSz + ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) { - word32 digestSz = MacSize(ssl); - if (*inOutIdx + digestSz > totalSz) - return BUFFER_E; - *inOutIdx += digestSz; - } -#endif /* In async mode always store the message and process it with * DtlsMsgDrain because in case of a WC_PENDING_E it will be * easier this way. */ @@ -18357,8 +18671,8 @@ static WC_INLINE void AeadIncrementExpIV(WOLFSSL* ssl) #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_CHAPOL_AEAD) /* Used for the older version of creating AEAD tags with Poly1305 */ -static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out, - byte* cipher, word16 sz, byte* tag) +static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, int additionalSz, + const byte* out, byte* cipher, word16 sz, byte* tag) { int ret = 0; int msglen = (sz - ssl->specs.aead_mac_size); @@ -18376,12 +18690,12 @@ static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out, return ret; if ((ret = wc_Poly1305Update(ssl->auth.poly1305, additional, - AEAD_AUTH_DATA_SZ)) != 0) + additionalSz)) != 0) return ret; /* length of additional input plus padding */ XMEMSET(padding, 0, sizeof(padding)); - padding[0] = AEAD_AUTH_DATA_SZ; + padding[0] = additionalSz; if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding, sizeof(padding))) != 0) return ret; @@ -18424,19 +18738,21 @@ static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out, * Return 0 on success negative values in error case */ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, - word16 sz) + word16 sz, byte type) { - const byte* additionalSrc = input - RECORD_HEADER_SZ; int ret = 0; word32 msgLen = (sz - ssl->specs.aead_mac_size); byte tag[POLY1305_AUTH_SZ]; byte add[AEAD_AUTH_DATA_SZ]; + int addSz = 0; byte nonce[CHACHA20_NONCE_SZ]; byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for poly1305 */ #ifdef CHACHA_AEAD_TEST int i; #endif Keys* keys = &ssl->keys; + byte* seq = NULL; + int verifyOrder = CUR_ORDER; XMEMSET(tag, 0, sizeof(tag)); XMEMSET(nonce, 0, sizeof(nonce)); @@ -18454,36 +18770,22 @@ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, /* opaque SEQ number stored for AD */ if (ssl->options.dtls && DtlsSCRKeysSet(ssl)) { if (ssl->keys.dtls_epoch == - ssl->secure_renegotiation->tmp_keys.dtls_epoch) { + ssl->secure_renegotiation->tmp_keys.dtls_epoch) keys = &ssl->secure_renegotiation->tmp_keys; - WriteSEQ(ssl, CUR_ORDER, add); - } else - WriteSEQ(ssl, PREV_ORDER, add); + verifyOrder = PREV_ORDER; } - else #endif - WriteSEQ(ssl, CUR_ORDER, add); + + addSz = writeAeadAuthData(ssl, msgLen, type, add, 0, &seq, verifyOrder); + if (addSz < 0) + return addSz; if (ssl->options.oldPoly != 0) { /* get nonce. SEQ should not be incremented again here */ - XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2); + XMEMCPY(nonce + CHACHA20_OLD_OFFSET, seq, SEQ_SZ); } - /* Store the type, version. Unfortunately, they are in - * the input buffer ahead of the plaintext. */ - #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) { - additionalSrc -= DTLS_HANDSHAKE_EXTRA; - } - #endif - - /* add TLS message size to additional data */ - add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff; - add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff; - - XMEMCPY(add + AEAD_TYPE_OFFSET, additionalSrc, 3); - #ifdef CHACHA_AEAD_TEST printf("Encrypt Additional : "); for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) { @@ -18502,15 +18804,8 @@ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, if (ssl->options.oldPoly == 0) { /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte * record sequence number XORed with client_write_IV/server_write_IV */ - XMEMCPY(nonce, keys->aead_enc_imp_IV, CHACHA20_IMP_IV_SZ); - nonce[4] ^= add[0]; - nonce[5] ^= add[1]; - nonce[6] ^= add[2]; - nonce[7] ^= add[3]; - nonce[8] ^= add[4]; - nonce[9] ^= add[5]; - nonce[10] ^= add[6]; - nonce[11] ^= add[7]; + XMEMCPY(nonce + CHACHA20_OFFSET, seq, SEQ_SZ); + xorbuf(nonce, keys->aead_enc_imp_IV, CHACHA20_IMP_IV_SZ); } #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("ChachaAEADEncrypt nonce", nonce, CHACHA20_NONCE_SZ); @@ -18565,7 +18860,7 @@ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, /* get the poly1305 tag using either old padding scheme or more recent */ if (ssl->options.oldPoly != 0) { - if ((ret = Poly1305TagOld(ssl, add, (const byte* )out, + if ((ret = Poly1305TagOld(ssl, add, addSz, (const byte* )out, poly, sz, tag)) != 0) { ForceZero(poly, sizeof(poly)); #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -18583,8 +18878,8 @@ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, #endif return ret; } - if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add, - sizeof(add), out, msgLen, tag, sizeof(tag))) != 0) { + if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add, addSz, out, msgLen, + tag, sizeof(tag))) != 0) { ForceZero(poly, sizeof(poly)); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE); @@ -18640,12 +18935,14 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, word16 sz) { byte add[AEAD_AUTH_DATA_SZ]; + int addSz = 0; byte nonce[CHACHA20_NONCE_SZ]; byte tag[POLY1305_AUTH_SZ]; byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */ int ret = 0; int msgLen = (sz - ssl->specs.aead_mac_size); Keys* keys = &ssl->keys; + byte* seq = NULL; #ifdef CHACHA_AEAD_TEST int i; @@ -18674,24 +18971,16 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, keys = &ssl->secure_renegotiation->tmp_keys; #endif - /* sequence number field is 64-bits */ - WriteSEQ(ssl, PEER_ORDER, add); + + addSz = writeAeadAuthData(ssl, msgLen, no_type, add, 1, &seq, PEER_ORDER); + if (addSz < 0) + return addSz; if (ssl->options.oldPoly != 0) { /* get nonce, SEQ should not be incremented again here */ - XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2); + XMEMCPY(nonce + CHACHA20_OLD_OFFSET, seq, SEQ_SZ); } - /* get AD info */ - /* Store the type, version. */ - add[AEAD_TYPE_OFFSET] = ssl->curRL.type; - add[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor; - add[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor; - - /* add TLS message size to additional data */ - add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff; - add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff; - #ifdef CHACHA_AEAD_TEST printf("Decrypt Additional : "); for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) { @@ -18703,15 +18992,8 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, if (ssl->options.oldPoly == 0) { /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte * record sequence number XORed with client_write_IV/server_write_IV */ - XMEMCPY(nonce, keys->aead_dec_imp_IV, CHACHA20_IMP_IV_SZ); - nonce[4] ^= add[0]; - nonce[5] ^= add[1]; - nonce[6] ^= add[2]; - nonce[7] ^= add[3]; - nonce[8] ^= add[4]; - nonce[9] ^= add[5]; - nonce[10] ^= add[6]; - nonce[11] ^= add[7]; + XMEMCPY(nonce + CHACHA20_OFFSET, seq, SEQ_SZ); + xorbuf(nonce, keys->aead_dec_imp_IV, CHACHA20_IMP_IV_SZ); } #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("ChachaAEADEncrypt nonce", nonce, CHACHA20_NONCE_SZ); @@ -18756,7 +19038,8 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, /* get the tag using Poly1305 */ if (ssl->options.oldPoly != 0) { - if ((ret = Poly1305TagOld(ssl, add, input, poly, sz, tag)) != 0) { + if ((ret = Poly1305TagOld(ssl, add, addSz, input, poly, sz, tag)) + != 0) { ForceZero(poly, sizeof(poly)); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE); @@ -18773,8 +19056,8 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, #endif return ret; } - if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add, - sizeof(add), input, (word32)msgLen, tag, sizeof(tag))) != 0) { + if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add, addSz, input, + (word32)msgLen, tag, sizeof(tag))) != 0) { ForceZero(poly, sizeof(poly)); #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE); @@ -18858,9 +19141,74 @@ typedef int (*Sm4AuthDecryptFunc)(wc_Sm4* sm4, byte* out, const byte* in, #endif +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#define TLS_AEAD_CID_SZ(s, dec) \ + ((dec) ? DtlsGetCidRxSize((s)) \ + : DtlsGetCidTxSize((s))) +#define TLS_AEAD_CID(s, dec, b, c) \ + ((dec) ? wolfSSL_dtls_cid_get_rx((s), (b), (c)) \ + : wolfSSL_dtls_cid_get_tx((s), (b), (c))) +#endif +/** + * + * @param ssl WOLFSSL object + * @param sz Length of fragment + * @param type Record content type + * @param additional AAD output buffer. Assumed AEAD_AUTH_DATA_SZ length. + * @param dec Are we decrypting + * @return >= 0 length of auth data + * < 0 error + */ +int writeAeadAuthData(WOLFSSL* ssl, word16 sz, byte type, + byte* additional, byte dec, byte** seq, int verifyOrder) +{ + word32 idx = 0; +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + byte cidSz = 0; + if (ssl->options.dtls && (cidSz = TLS_AEAD_CID_SZ(ssl, dec)) > 0) { + if (cidSz > DTLS_CID_MAX_SIZE) { + WOLFSSL_MSG("DTLS CID too large"); + return DTLS_CID_ERROR; + } + + XMEMSET(additional + idx, 0xFF, SEQ_SZ); + idx += SEQ_SZ; + additional[idx++] = dtls12_cid; + additional[idx++] = cidSz; + additional[idx++] = dtls12_cid; + additional[idx++] = dec ? ssl->curRL.pvMajor : ssl->version.major; + additional[idx++] = dec ? ssl->curRL.pvMinor : ssl->version.minor; + WriteSEQ(ssl, verifyOrder, additional + idx); + if (seq != NULL) + *seq = additional + idx; + idx += SEQ_SZ; + if (TLS_AEAD_CID(ssl, dec, additional + idx, (unsigned int)cidSz) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + WOLFSSL_MSG("DTLS CID write failed"); + return DTLS_CID_ERROR; + } + idx += cidSz; + c16toa(sz, additional + idx); + idx += LENGTH_SZ; + + return (int)idx; + } +#endif + if (seq != NULL) + *seq = additional + idx; + WriteSEQ(ssl, verifyOrder, additional + idx); + idx += SEQ_SZ; + additional[idx++] = dec ? ssl->curRL.type : type; + additional[idx++] = dec ? ssl->curRL.pvMajor : ssl->version.major; + additional[idx++] = dec ? ssl->curRL.pvMinor : ssl->version.minor; + c16toa(sz, additional + idx); + idx += LENGTH_SZ; + + return (int)idx; +} static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, - word16 sz, int asyncOkay) + word16 sz, int asyncOkay, byte type) { int ret = 0; #ifdef WOLFSSL_ASYNC_CRYPT @@ -18927,7 +19275,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, case wolfssl_aes_ccm:/* GCM AEAD macros use same size as CCM */ { AES_AUTH_ENCRYPT_FUNC aes_auth_fn; - const byte* additionalSrc; + int additionalSz; #ifdef WOLFSSL_ASYNC_CRYPT /* initialize event */ @@ -18945,27 +19293,17 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #else aes_auth_fn = AES_CCM_ENCRYPT; #endif - additionalSrc = input - 5; - - XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ); - /* sequence number field is 64-bits */ - WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional); - - /* Store the type, version. Unfortunately, they are in - * the input buffer ahead of the plaintext. */ - #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) { - additionalSrc -= DTLS_HANDSHAKE_EXTRA; + additionalSz = writeAeadAuthData(ssl, + /* Length of the plain text minus the explicit + * IV length minus the authentication tag size. */ + sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, type, + ssl->encrypt.additional, 0, NULL, CUR_ORDER); + if (additionalSz < 0) { + ret = additionalSz; + break; } - #endif - XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET, - additionalSrc, 3); - /* Store the length of the plain text minus the explicit - * IV length minus the authentication tag size. */ - c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->encrypt.additional + AEAD_LEN_OFFSET); #if !defined(NO_PUBLIC_GCM_SET_IV) && \ ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))) @@ -18983,7 +19321,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ssl->encrypt.nonce, AESGCM_NONCE_SZ, out + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size, - ssl->encrypt.additional, AEAD_AUTH_DATA_SZ); + ssl->encrypt.additional, additionalSz); } if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) @@ -18995,7 +19333,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ssl->encrypt.nonce, AESGCM_NONCE_SZ, out + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size, - ssl->encrypt.additional, AEAD_AUTH_DATA_SZ); + ssl->encrypt.additional, additionalSz); } #ifdef WOLFSSL_ASYNC_CRYPT @@ -19016,27 +19354,18 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #ifdef HAVE_ARIA case wolfssl_aria_gcm: { - const byte* additionalSrc = input - RECORD_HEADER_SZ; + int additionalSz; byte *outBuf = NULL; - XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ); - /* sequence number field is 64-bits */ - WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional); - - /* Store the type, version. Unfortunately, they are in - * the input buffer ahead of the plaintext. */ - #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) { - additionalSrc -= DTLS_HANDSHAKE_EXTRA; - } - #endif - XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET, - additionalSrc, 3); + additionalSz = ret = writeAeadAuthData(ssl, + /* Length of the plain text minus the explicit + * IV length minus the authentication tag size. */ + sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, type, + ssl->encrypt.additional, 0, NULL, CUR_ORDER); + if (ret < 0) + break; + ret = 0; - /* Store the length of the plain text minus the explicit - * IV length minus the authentication tag size. */ - c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->encrypt.additional + AEAD_LEN_OFFSET); XMEMCPY(ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ); XMEMCPY(ssl->encrypt.nonce + AESGCM_IMP_IV_SZ, @@ -19051,7 +19380,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, (byte*) input + AESGCM_EXP_IV_SZ, sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, ssl->encrypt.nonce, AESGCM_NONCE_SZ, - ssl->encrypt.additional, AEAD_AUTH_DATA_SZ, + ssl->encrypt.additional, additionalSz, out + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size ); @@ -19074,7 +19403,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \ !defined(NO_CHAPOL_AEAD) case wolfssl_chacha: - ret = ChachaAEADEncrypt(ssl, out, input, sz); + ret = ChachaAEADEncrypt(ssl, out, input, sz, type); break; #endif @@ -19192,7 +19521,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, } static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, - word16 sz, int asyncOkay) + word16 sz, int asyncOkay, byte type) { int ret = 0; @@ -19283,7 +19612,7 @@ static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, case CIPHER_STATE_DO: { - ret = EncryptDo(ssl, out, input, sz, asyncOkay); + ret = EncryptDo(ssl, out, input, sz, asyncOkay, type); /* Advance state */ ssl->encrypt.state = CIPHER_STATE_END; @@ -19416,6 +19745,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */ { wc_AesAuthDecryptFunc aes_auth_fn; + int additionalSz; #ifdef WOLFSSL_ASYNC_CRYPT /* initialize event */ @@ -19434,17 +19764,13 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, aes_auth_fn = wc_AesCcmDecrypt; #endif - XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ); - - /* sequence number field is 64-bits */ - WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional); - - ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type; - ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor; - ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor; - - c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->decrypt.additional + AEAD_LEN_OFFSET); + additionalSz = writeAeadAuthData(ssl, + sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, no_type, + ssl->decrypt.additional, 1, NULL, PEER_ORDER); + if (additionalSz < 0) { + ret = additionalSz; + break; + } #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION) if (ssl->options.dtls && IsDtlsMsgSCRKeys(ssl)) @@ -19467,7 +19793,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->decrypt.nonce, AESGCM_NONCE_SZ, (byte *)(input + sz - ssl->specs.aead_mac_size), ssl->specs.aead_mac_size, - ssl->decrypt.additional, AEAD_AUTH_DATA_SZ); + ssl->decrypt.additional, additionalSz); } if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) @@ -19480,7 +19806,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ssl->decrypt.nonce, AESGCM_NONCE_SZ, input + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size, - ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) { + ssl->decrypt.additional, additionalSz)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, @@ -19497,17 +19823,14 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, case wolfssl_aria_gcm: { byte *outBuf = NULL; - XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ); - - /* sequence number field is 64-bits */ - WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional); - - ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type; - ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor; - ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor; + int additionalSz; - c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->decrypt.additional + AEAD_LEN_OFFSET); + additionalSz = ret = writeAeadAuthData(ssl, + sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, no_type, + ssl->decrypt.additional, 1, NULL, PEER_ORDER); + if (ret < 0) + break; + ret = 0; #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION) if (ssl->options.dtls && IsDtlsMsgSCRKeys(ssl)) @@ -19530,7 +19853,7 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, (byte *)input + AESGCM_EXP_IV_SZ, sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, ssl->decrypt.nonce, AESGCM_NONCE_SZ, - ssl->decrypt.additional, AEAD_AUTH_DATA_SZ, + ssl->decrypt.additional, additionalSz, (byte *)input + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size ); @@ -19853,12 +20176,7 @@ static WC_INLINE int CipherHasExpIV(WOLFSSL *ssl) /* check cipher text size for sanity */ static int SanityCheckCipherText(WOLFSSL* ssl, word32 encryptSz) { -#ifdef HAVE_TRUNCATED_HMAC - word32 minLength = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ - : ssl->specs.hash_size; -#else - word32 minLength = ssl->specs.hash_size; /* covers stream */ -#endif + word32 minLength = MacSize(ssl); #ifndef WOLFSSL_AEAD_ONLY if (ssl->specs.cipher_type == block) { @@ -20290,7 +20608,7 @@ int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz, /* 4th argument has potential to underflow, ssl->hmac function should * either increment the size by (macSz + padLen + 1) before use or check on * the size to make sure is valid. */ - ret = ssl->hmac(ssl, verify, input, pLen - macSz - padLen - 1, padLen, + ret = ssl->hmac(ssl, verify, input, (word32)(pLen - macSz - padLen - 1), padLen, content, 1, PEER_ORDER); good |= MaskMac(input, pLen, ssl->specs.hash_size, verify); @@ -20316,10 +20634,9 @@ int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz, int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) { - word32 msgSz = WOLFSSL_IS_QUIC(ssl)? ssl->curSize : ssl->keys.encryptSz; + word32 msgSz = ssl->curSize; word32 idx = *inOutIdx; int dataSz; - int ivExtra = 0; byte* rawData = input + idx; /* keep current for hmac */ #ifdef HAVE_LIBZ byte decomp[MAX_RECORD_SIZE + MAX_COMP_EXTRA]; @@ -20380,23 +20697,7 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) } #endif -#ifndef WOLFSSL_AEAD_ONLY - if (ssl->specs.cipher_type == block) { - if (ssl->options.tls1_1) - ivExtra = ssl->specs.block_size; - } - else -#endif - if (ssl->specs.cipher_type == aead) { - if (CipherHasExpIV(ssl)) - ivExtra = AESGCM_EXP_IV_SZ; - } - - dataSz = msgSz - ivExtra - ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - dataSz -= MacSize(ssl); -#endif + dataSz = msgSz - ssl->keys.padSz; if (dataSz < 0) { WOLFSSL_MSG("App data buffer error, malicious input?"); if (sniff == NO_SNIFF) { @@ -20428,17 +20729,13 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) if (dataSz < 0) return dataSz; } #endif - idx += rawSz; + idx += (word32)rawSz; ssl->buffers.clearOutputBuffer.buffer = rawData; ssl->buffers.clearOutputBuffer.length = (unsigned int)dataSz; } idx += ssl->keys.padSz; -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - idx += MacSize(ssl); -#endif #ifdef HAVE_LIBZ /* decompress could be bigger, overwrite after verify */ @@ -20654,7 +20951,11 @@ static void LogAlert(int type) typeStr = AlertTypeToString(type); if (typeStr != NULL) { char buff[60]; - XSNPRINTF(buff, sizeof(buff), "Alert type: %s", typeStr); + if (XSNPRINTF(buff, sizeof(buff), "Alert type: %s", typeStr) + >= (int)sizeof(buff)) + { + buff[sizeof(buff) - 1] = 0; + } WOLFSSL_MSG(buff); } #else @@ -20684,26 +20985,8 @@ static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type) } #endif - if (IsEncryptionOn(ssl, 0)) { - int ivExtra = 0; -#ifndef WOLFSSL_AEAD_ONLY - if (ssl->specs.cipher_type == block) { - if (ssl->options.tls1_1) - ivExtra = ssl->specs.block_size; - } - else -#endif - if (ssl->specs.cipher_type == aead) { - if (CipherHasExpIV(ssl)) - ivExtra = AESGCM_EXP_IV_SZ; - } - dataSz -= ivExtra; + if (IsEncryptionOn(ssl, 0)) dataSz -= ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - dataSz -= MacSize(ssl); - #endif - } /* make sure can read the message */ if (dataSz != ALERT_SIZE) { @@ -20746,10 +21029,6 @@ static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type) if (IsEncryptionOn(ssl, 0)) { *inOutIdx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - *inOutIdx += MacSize(ssl); - #endif } return level; @@ -20764,9 +21043,9 @@ static int GetInputData(WOLFSSL *ssl, word32 size) /* check max input length */ - usedLength = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx; - maxLength = ssl->buffers.inputBuffer.bufferSize - usedLength; - inSz = (int)(size - usedLength); /* from last partial read */ + usedLength = (int)(ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx); + maxLength = (int)(ssl->buffers.inputBuffer.bufferSize - (word32)usedLength); + inSz = (int)(size - (word32)usedLength); /* from last partial read */ #ifdef WOLFSSL_DTLS if (ssl->options.dtls && IsDtlsNotSctpMode(ssl)) { @@ -20788,7 +21067,7 @@ static int GetInputData(WOLFSSL *ssl, word32 size) } if (inSz > maxLength) { - if (GrowInputBuffer(ssl, size + dtlsExtra, usedLength) < 0) + if (GrowInputBuffer(ssl, (int)(size + (word32)dtlsExtra), usedLength) < 0) return MEMORY_E; } @@ -20808,8 +21087,8 @@ static int GetInputData(WOLFSSL *ssl, word32 size) ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.length, (word32)inSz); - if (in == WANT_READ) - return WANT_READ; + if (in == WC_NO_ERR_TRACE(WANT_READ)) + return WC_NO_ERR_TRACE(WANT_READ); if (in < 0) { WOLFSSL_ERROR_VERBOSE(SOCKET_ERROR_E); @@ -20821,7 +21100,7 @@ static int GetInputData(WOLFSSL *ssl, word32 size) return RECV_OVERFLOW_E; } - ssl->buffers.inputBuffer.length += in; + ssl->buffers.inputBuffer.length += (word32)in; inSz -= in; } while (ssl->buffers.inputBuffer.length < size); @@ -20875,20 +21154,12 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, int ret; word32 pad = 0; word32 padByte = 0; -#ifdef HAVE_TRUNCATED_HMAC - word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ - : ssl->specs.hash_size; -#else - word32 digestSz = ssl->specs.hash_size; -#endif + word32 digestSz = MacSize(ssl); byte verify[WC_MAX_DIGEST_SIZE]; if (ssl->specs.cipher_type == block) { - int ivExtra = 0; - if (ssl->options.tls1_1) - ivExtra = ssl->specs.block_size; - pad = *(input + msgSz - ivExtra - 1); + pad = input[msgSz - 1]; padByte = 1; if (ssl->options.tls) { @@ -20897,8 +21168,8 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, if(ssl->ctx->VerifyMacCb) { void* ctx = wolfSSL_GetVerifyMacCtx(ssl); ret = ssl->ctx->VerifyMacCb(ssl, input, - (msgSz - ivExtra) - digestSz - pad - 1, - digestSz, (word32)content, ctx); + msgSz - digestSz - pad - 1, + digestSz, (word32)content, ctx); if (ret != 0 && ret != WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) { return ret; @@ -20907,8 +21178,8 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, if (!ssl->ctx->VerifyMacCb || ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) #endif - ret = TimingPadVerify(ssl, input, pad, digestSz, msgSz - ivExtra, - content); + ret = TimingPadVerify(ssl, input, (int)pad, (int)digestSz, + (int)msgSz, content); if (ret != 0) return ret; } @@ -20957,7 +21228,7 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, } #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY) else { - *padSz = digestSz + pad + padByte; + *padSz = pad + padByte; } #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */ @@ -21026,6 +21297,38 @@ static int DtlsShouldDrop(WOLFSSL* ssl, int retcode) } #endif /* WOLFSSL_DTLS */ +#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +static int removeMsgInnerPadding(WOLFSSL* ssl) +{ + word32 i = ssl->buffers.inputBuffer.idx + + ssl->curSize; + if (ssl->specs.cipher_type == aead) + i -= ssl->specs.aead_mac_size; + else + i -= ssl->keys.padSz + MacSize(ssl); + + /* check that the end of the logical length doesn't extend + * past the real buffer */ + if (i > ssl->buffers.inputBuffer.length || i == 0) { + WOLFSSL_ERROR(BUFFER_ERROR); + return BUFFER_ERROR; + } + + /* Remove padding from end of plain text. */ + for (--i; i > ssl->buffers.inputBuffer.idx; i--) { + if (ssl->buffers.inputBuffer.buffer[i] != 0) + break; + } + + /* Get the real content type from the end of the data. */ + ssl->curRL.type = ssl->buffers.inputBuffer.buffer[i]; + /* consider both contentType byte and MAC as padding */ + ssl->keys.padSz = ssl->buffers.inputBuffer.idx + + ssl->curSize - i; + return 0; +} +#endif + int ProcessReply(WOLFSSL* ssl) { return ProcessReplyEx(ssl, 0); @@ -21048,15 +21351,17 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) atomicUser = 1; #endif - if (ssl->error != 0 && ssl->error != WANT_READ && ssl->error != WANT_WRITE + if (ssl->error != 0 && + ssl->error != WC_NO_ERR_TRACE(WANT_READ) && + ssl->error != WC_NO_ERR_TRACE(WANT_WRITE) #if defined(HAVE_SECURE_RENEGOTIATION) || defined(WOLFSSL_DTLS13) - && ssl->error != APP_DATA_READY + && ssl->error != WC_NO_ERR_TRACE(APP_DATA_READY) #endif #ifdef WOLFSSL_ASYNC_CRYPT - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif #ifdef WOLFSSL_NONBLOCK_OCSP - && ssl->error != OCSP_WANT_READ + && ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ) #endif && (allowSocketErr != 1 || ssl->error != WC_NO_ERR_TRACE(SOCKET_ERROR_E)) @@ -21290,7 +21595,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) if (!ssl->options.dtls) { if ((ret = GetInputData(ssl, ssl->curSize)) < 0) { #ifdef WOLFSSL_EXTRA_ALERTS - if (ret != WANT_READ) + if (ret != WC_NO_ERR_TRACE(WANT_READ)) SendAlert(ssl, alert_fatal, bad_record_mac); #endif return ret; @@ -21334,8 +21639,6 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->keys.padSz = 0; ssl->options.processReply = verifyEncryptedMessage; - /* in case > 1 msg per record */ - ssl->curStartIdx = ssl->buffers.inputBuffer.idx; FALL_THROUGH; /* verify digest of encrypted message */ @@ -21439,13 +21742,14 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* Mask on indicates this is expected to be a * padding byte. */ - padding &= ctMaskLTE(i, ssl->keys.padSz); + padding &= ctMaskLTE((int)i, + (int)ssl->keys.padSz); /* When this is a padding byte and not equal * to length then mask is set. */ invalid |= padding & ctMaskNotEq(in->buffer[off - i], - ssl->keys.padSz); + (int)ssl->keys.padSz); } /* If mask is set then there was an error. */ if (invalid) { @@ -21502,12 +21806,17 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #ifndef WOLFSSL_NO_TLS12 /* handle success */ #ifndef WOLFSSL_AEAD_ONLY - if (ssl->options.tls1_1 && ssl->specs.cipher_type == block) + if (ssl->options.tls1_1 && + ssl->specs.cipher_type == block) { ssl->buffers.inputBuffer.idx += ssl->specs.block_size; + ssl->curSize -= ssl->specs.block_size; + } #endif /* go past TLSv1.1 IV */ - if (CipherHasExpIV(ssl)) + if (CipherHasExpIV(ssl)) { ssl->buffers.inputBuffer.idx += AESGCM_EXP_IV_SZ; + ssl->curSize -= AESGCM_EXP_IV_SZ; + } #endif } else { @@ -21604,32 +21913,49 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->keys.encryptSz = ssl->curSize; ssl->keys.decryptedCur = 1; -#ifdef WOLFSSL_TLS13 - if (ssl->options.tls1_3) { - word32 i = (ssl->buffers.inputBuffer.idx + - ssl->curSize - ssl->specs.aead_mac_size); - /* check that the end of the logical length doesn't extend - * past the real buffer */ - if (i > ssl->buffers.inputBuffer.length || i == 0) { - WOLFSSL_ERROR(BUFFER_ERROR); - return BUFFER_ERROR; - } - - /* Remove padding from end of plain text. */ - for (--i; i > ssl->buffers.inputBuffer.idx; i--) { - if (ssl->buffers.inputBuffer.buffer[i] != 0) - break; - } + } - /* Get the real content type from the end of the data. */ - ssl->curRL.type = ssl->buffers.inputBuffer.buffer[i]; - /* consider both contentType byte and MAC as padding */ - ssl->keys.padSz = ssl->buffers.inputBuffer.idx - + ssl->curSize - i; + if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 1) { +#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + int removePadding = 0; + if (ssl->options.tls1_3) + removePadding = 1; +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (!ssl->options.tls1_3 && ssl->options.dtls && + ssl->curRL.type == dtls12_cid) + removePadding = 1; +#endif + if (removePadding) { + ret = removeMsgInnerPadding(ssl); + if (ret != 0) + return ret; } + else #endif + { + /* With atomicUser the callback should have already included + * the mac in the padding size. The ETM callback doesn't do + * this for some reason. */ + if (ssl->specs.cipher_type != aead +#ifdef ATOMIC_USER + && (!atomicUser +#ifdef HAVE_ENCRYPT_THEN_MAC + || ssl->options.startedETMRead +#endif /* HAVE_ENCRYPT_THEN_MAC */ + ) +#endif /* !ATOMIC_USER */ + ) + { + /* consider MAC as padding */ + ssl->keys.padSz += MacSize(ssl); + } + } + } + /* in case > 1 msg per record */ + ssl->curStartIdx = ssl->buffers.inputBuffer.idx; + ssl->options.processReply = runProcessingOneRecord; FALL_THROUGH; @@ -21676,11 +22002,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) if (IsEncryptionOn(ssl, 0) && ssl->options.startedETMRead) { - /* For TLS v1.1 the block size and explicit IV are added to idx, - * so it needs to be included in this limit check */ - if ((ssl->curSize - ssl->keys.padSz - - (ssl->buffers.inputBuffer.idx - ssl->curStartIdx) - - MacSize(ssl) > MAX_PLAINTEXT_SZ) + if ((ssl->curSize - ssl->keys.padSz > MAX_PLAINTEXT_SZ) #ifdef WOLFSSL_ASYNC_CRYPT && ssl->buffers.inputBuffer.length != ssl->buffers.inputBuffer.idx @@ -21697,12 +22019,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) else #endif /* TLS13 plaintext limit is checked earlier before decryption */ - /* For TLS v1.1 the block size and explicit IV are added to idx, - * so it needs to be included in this limit check */ if (!IsAtLeastTLSv1_3(ssl->version) - && ssl->curSize - ssl->keys.padSz - - (ssl->buffers.inputBuffer.idx - ssl->curStartIdx) - > MAX_PLAINTEXT_SZ + && ssl->curSize - ssl->keys.padSz > MAX_PLAINTEXT_SZ #ifdef WOLFSSL_ASYNC_CRYPT && ssl->buffers.inputBuffer.length != ssl->buffers.inputBuffer.idx @@ -21813,7 +22131,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) * calling DtlsMsgPoolSend. This msg is done * processing so let's move on. */ && (!ssl->options.dtls - || ret != WANT_WRITE) + || ret != WC_NO_ERR_TRACE(WANT_WRITE)) #ifdef WOLFSSL_ASYNC_CRYPT /* In async case, on pending, move onto next message. * Current message should have been DtlsMsgStore'ed and @@ -21890,28 +22208,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } if (IsEncryptionOn(ssl, 0) && ssl->options.handShakeDone) { -#ifdef HAVE_AEAD - if (ssl->specs.cipher_type == aead) { - if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha) - ssl->curSize -= AESGCM_EXP_IV_SZ; - ssl->buffers.inputBuffer.idx += ssl->specs.aead_mac_size; - ssl->curSize -= ssl->specs.aead_mac_size; - } - else -#endif - { - ssl->buffers.inputBuffer.idx += ssl->keys.padSz; - ssl->curSize -= (word16)ssl->keys.padSz; - ssl->curSize -= ssl->specs.iv_size; - } - - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - ssl->buffers.inputBuffer.idx += digestSz; - ssl->curSize -= (word16)digestSz; - } - #endif + ssl->buffers.inputBuffer.idx += ssl->keys.padSz; + ssl->curSize -= (word16)ssl->keys.padSz; } if (ssl->curSize != 1) { @@ -22012,6 +22310,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) #endif } #endif + #ifndef WOLFSSL_RW_THREADED #ifdef WOLFSSL_TLS13 if (ssl->keys.keyUpdateRespond) { WOLFSSL_MSG("No KeyUpdate from peer seen"); @@ -22019,6 +22318,7 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) return SANITY_MSG_E; } #endif + #endif if ((ret = DoApplicationData(ssl, ssl->buffers.inputBuffer.buffer, &ssl->buffers.inputBuffer.idx, @@ -22115,32 +22415,17 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->options.processReply = runProcessingOneMessage; if (IsEncryptionOn(ssl, 0)) { - WOLFSSL_MSG("Bundled encrypted messages, remove middle pad"); - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - if (ssl->buffers.inputBuffer.idx >= - ssl->keys.padSz + digestSz) { - ssl->buffers.inputBuffer.idx -= - ssl->keys.padSz + digestSz; - } - else { - WOLFSSL_MSG("\tmiddle padding error"); - WOLFSSL_ERROR_VERBOSE(FATAL_ERROR); - return FATAL_ERROR; - } + /* With encryption on, we advance the index by the value + * of ssl->keys.padSz. Since padding only appears once, we + * only can do this at the end of record parsing. We have to + * reset the index to the start of the next message here. */ + if (ssl->buffers.inputBuffer.idx >= ssl->keys.padSz) { + ssl->buffers.inputBuffer.idx -= ssl->keys.padSz; } - else - #endif - { - if (ssl->buffers.inputBuffer.idx >= ssl->keys.padSz) { - ssl->buffers.inputBuffer.idx -= ssl->keys.padSz; - } - else { - WOLFSSL_MSG("\tmiddle padding error"); - WOLFSSL_ERROR_VERBOSE(FATAL_ERROR); - return FATAL_ERROR; - } + else { + WOLFSSL_MSG("\tBuffer advanced not enough error"); + WOLFSSL_ERROR_VERBOSE(FATAL_ERROR); + return FATAL_ERROR; } } } @@ -22259,7 +22544,7 @@ int SendChangeCipher(WOLFSSL* ssl) return ret; } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; #ifdef WOLFSSL_TLS13 if (!ssl->options.tls1_3) @@ -22675,9 +22960,10 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, ssl->options.buildMsgState = BUILD_MSG_BEGIN; XMEMSET(args, 0, sizeof(BuildMsgArgs)); - args->sz = RECORD_HEADER_SZ + inSz; + args->sz = RECORD_HEADER_SZ + (word32)inSz; args->idx = RECORD_HEADER_SZ; args->headerSz = RECORD_HEADER_SZ; + args->type = (byte)type; } switch (ssl->options.buildMsgState) { @@ -22743,6 +23029,17 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args->sz += DTLS_RECORD_EXTRA; args->idx += DTLS_RECORD_EXTRA; args->headerSz += DTLS_RECORD_EXTRA; + #ifdef WOLFSSL_DTLS_CID + if (ssl->options.dtls) { + byte cidSz = 0; + if ((cidSz = DtlsGetCidTxSize(ssl)) > 0) { + args->sz += cidSz; + args->idx += cidSz; + args->headerSz += cidSz; + args->sz++; /* real_type. no padding. */ + } + } + #endif } #endif @@ -22824,7 +23121,12 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif args->size = (word16)(args->sz - args->headerSz); /* include mac and digest */ - AddRecordHeader(output, args->size, (byte)type, ssl, epochOrder); + +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls && DtlsGetCidTxSize(ssl) > 0) + args->type = dtls12_cid; +#endif + AddRecordHeader(output, args->size, args->type, ssl, epochOrder); /* write to output */ if (args->ivSz > 0) { @@ -22833,7 +23135,16 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args->idx += min(args->ivSz, MAX_IV_SZ); } XMEMCPY(output + args->idx, input, inSz); - args->idx += inSz; + args->idx += (word32)inSz; +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls && DtlsGetCidTxSize(ssl) > 0) { + output[args->idx++] = (byte)type; /* type goes after input */ + inSz++; + } +#endif + /* Make sure we don't access input anymore as inSz may have been + * incremented */ + input = NULL; ssl->options.buildMsgState = BUILD_MSG_HASH; } @@ -22845,7 +23156,8 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, goto exit_buildmsg; if (type == handshake && hashOutput) { - ret = HashOutput(ssl, output, args->headerSz + inSz, args->ivSz); + ret = HashOutput(ssl, output, + (int)(args->headerSz + (word32)inSz), (int)args->ivSz); if (ret != 0) goto exit_buildmsg; } @@ -22881,7 +23193,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, if (ssl->options.startedETMWrite) { if (ssl->ctx->EncryptMacCb) { ret = ssl->ctx->EncryptMacCb(ssl, output + args->idx + - args->pad + 1, type, 0, + args->pad + 1, args->type, 0, output + args->headerSz, output + args->headerSz, args->size - args->digestSz, @@ -22894,8 +23206,9 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, { if (ssl->ctx->MacEncryptCb) { ret = ssl->ctx->MacEncryptCb(ssl, output + args->idx, - output + args->headerSz + args->ivSz, (unsigned int)inSz, - type, 0, output + args->headerSz, + output + args->headerSz + args->ivSz, + (unsigned int)inSz, args->type, 0, + output + args->headerSz, output + args->headerSz, args->size, ssl->MacEncryptCtx); goto exit_buildmsg; @@ -22926,8 +23239,9 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif ret = ssl->hmac(ssl, hmac, - output + args->headerSz + args->ivSz, (word32)inSz, - -1, type, 0, epochOrder); + output + args->headerSz + args->ivSz, + (word32)inSz, -1, args->type, 0, + epochOrder); XMEMCPY(output + args->idx, hmac, args->digestSz); #ifdef WOLFSSL_SMALL_STACK @@ -22938,7 +23252,8 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif { ret = ssl->hmac(ssl, output + args->idx, output + - args->headerSz + args->ivSz, (word32)inSz, -1, type, 0, epochOrder); + args->headerSz + args->ivSz, (word32)inSz, -1, + args->type, 0, epochOrder); } } #endif /* WOLFSSL_AEAD_ONLY */ @@ -22974,18 +23289,42 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, ssl->keys.dtls_prev_sequence_number_lo; } #endif + +#ifdef WOLFSSL_THREADED_CRYPT + if (asyncOkay) { + WOLFSSL_MSG("Not encrypting\n"); + /* make sure build message state is reset */ + ssl->options.buildMsgState = BUILD_MSG_BEGIN; + + /* return sz on success */ + if (ret == 0) { + ret = args->sz; + } + else { + WOLFSSL_ERROR_VERBOSE(ret); + } + + /* Final cleanup */ + FreeBuildMsgArgs(ssl, args); + + return ret; + } + else +#endif + { #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) if (ssl->options.startedETMWrite) { ret = Encrypt(ssl, output + args->headerSz, output + args->headerSz, (word16)(args->size - args->digestSz), - asyncOkay); + asyncOkay, args->type); } else #endif { ret = Encrypt(ssl, output + args->headerSz, - output + args->headerSz, args->size, asyncOkay); + output + args->headerSz, args->size, asyncOkay, + args->type); } #if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS) /* Restore sequence numbers */ @@ -22995,6 +23334,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, ssl->keys.dtls_sequence_number_lo = dtls_sequence_number_lo; } #endif + } } if (ret != 0) { @@ -23046,8 +23386,8 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #endif ret = ssl->hmac(ssl, hmac, output + args->headerSz, - args->ivSz + inSz + args->pad + 1, -1, type, - 0, epochOrder); + args->ivSz + inSz + args->pad + 1, -1, + args->type, 0, epochOrder); XMEMCPY(output + args->idx + args->pad + 1, hmac, args->digestSz); @@ -23060,8 +23400,8 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, { ret = ssl->hmac(ssl, output + args->idx + args->pad + 1, output + args->headerSz, - args->ivSz + inSz + args->pad + 1, -1, type, - 0, epochOrder); + args->ivSz + (word32)inSz + args->pad + 1, + -1, args->type, 0, epochOrder); } } #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */ @@ -23132,6 +23472,13 @@ int SendFinished(WOLFSSL* ssl) /* check for available size */ outputSz = sizeof(input) + MAX_MSG_EXTRA; +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls) { + byte cidSz = 0; + if ((cidSz = DtlsGetCidTxSize(ssl)) > 0) + outputSz += cidSz + 1; /* +1 for inner content type */ + } +#endif /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state * is not advanced yet */ @@ -23155,7 +23502,8 @@ int SendFinished(WOLFSSL* ssl) /* get output buffer */ output = GetOutputBuffer(ssl); - AddHandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl); + AddHandShakeHeader(input, (word32)finishedSz, 0, + (word32)finishedSz, finished, ssl); /* make finished hashes */ hashes = (Hashes*)&input[headerSz]; @@ -23195,6 +23543,7 @@ int SendFinished(WOLFSSL* ssl) } #endif + ssl->keys.encryptionOn = 1; sendSz = BuildMessage(ssl, output, outputSz, input, headerSz + finishedSz, handshake, 1, 0, 0, CUR_ORDER); if (sendSz < 0) @@ -23245,7 +23594,7 @@ int SendFinished(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ret = SendBuffered(ssl); @@ -23278,14 +23627,18 @@ int SendFinished(WOLFSSL* ssl) * * Returns 0 on success */ -static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, - DecodedCert* cert, byte* certData, word32 length) +int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, + DecodedCert* cert, byte* certData, word32 length, + byte *ctxOwnsRequest) { int ret; if (request != NULL) XMEMSET(request, 0, sizeof(OcspRequest)); + if (ctxOwnsRequest!= NULL) + *ctxOwnsRequest = 0; + InitDecodedCert(cert, certData, length, ssl->heap); /* TODO: Setup async support here */ ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, SSL_CM(ssl), NULL); @@ -23299,8 +23652,11 @@ static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, if (!ssl->buffers.weOwnCert) { wolfSSL_Mutex* ocspLock = &SSL_CM(ssl)->ocsp_stapling->ocspLock; if (wc_LockMutex(ocspLock) == 0) { - if (ssl->ctx->certOcspRequest == NULL) + if (ssl->ctx->certOcspRequest == NULL) { ssl->ctx->certOcspRequest = request; + if (ctxOwnsRequest!= NULL) + *ctxOwnsRequest = 1; + } wc_UnLockMutex(ocspLock); } } @@ -23329,6 +23685,7 @@ int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest, int ret = 0; OcspRequest* request = NULL; byte createdRequest = 0; + byte ctxOwnsRequest = 0; if (ssl == NULL || ocspRequest == NULL || response == NULL) return BAD_FUNC_ARG; @@ -23366,7 +23723,7 @@ int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest, createdRequest = 1; if (ret == 0) { ret = CreateOcspRequest(ssl, request, cert, der->buffer, - der->length); + der->length, &ctxOwnsRequest); } if (ret != 0) { @@ -23393,7 +23750,7 @@ int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest, } /* free request up if error case found otherwise return it */ - if (ret != 0 && createdRequest) { + if (ret != 0 && createdRequest && !ctxOwnsRequest) { FreeOcspRequest(request); XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); } @@ -23425,6 +23782,14 @@ int cipherExtraData(WOLFSSL* ssl) cipherExtra = ssl->specs.iv_size + ssl->specs.block_size + ssl->specs.hash_size; } + /* Add space needed for the CID */ +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls) { + byte cidSz = 0; + if ((cidSz = DtlsGetCidTxSize(ssl)) > 0) + cipherExtra += cidSz + 1; /* +1 for inner content type */ + } +#endif /* Sanity check so we don't ever return negative. */ return cipherExtra > 0 ? cipherExtra : 0; } @@ -23669,7 +24034,7 @@ int SendCertificate(WOLFSSL* ssl) } if (inputSz > 0) { /* clang thinks could be zero, let's help */ - input = (byte*)XMALLOC(inputSz, ssl->heap, + input = (byte*)XMALLOC((size_t)inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; @@ -23722,12 +24087,12 @@ int SendCertificate(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; if (!ssl->options.groupMessages) ret = SendBuffered(ssl); } - if (ret != WANT_WRITE) { + if (ret != WC_NO_ERR_TRACE(WANT_WRITE)) { /* Clean up the fragment offset. */ ssl->options.buildingMsg = 0; ssl->fragOffset = 0; @@ -23895,14 +24260,16 @@ int SendCertificateRequest(WOLFSSL* ssl) return BUFFER_E; } - input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + input = (byte*)XMALLOC((size_t)inputSz, ssl->heap, + DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, certificate_request)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, + certificate_request)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -23917,7 +24284,8 @@ int SendCertificateRequest(WOLFSSL* ssl) sendSz = (int)i; #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl)) { - if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, certificate_request)) != 0) + if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, + certificate_request)) != 0) return ret; } if (ssl->options.dtls) @@ -23938,7 +24306,7 @@ int SendCertificateRequest(WOLFSSL* ssl) return ret; } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; if (ssl->options.groupMessages) ret = 0; else @@ -24088,6 +24456,7 @@ int SendCertificateStatus(WOLFSSL* ssl) { OcspRequest* request = ssl->ctx->certOcspRequest; buffer responses[1 + MAX_CHAIN_DEPTH]; + byte ctxOwnsRequest = 0; int i = 0; XMEMSET(responses, 0, sizeof(responses)); @@ -24144,9 +24513,8 @@ int SendCertificateStatus(WOLFSSL* ssl) if (idx > chain->length) break; - ret = CreateOcspRequest(ssl, request, cert, der.buffer, - der.length); + der.length, &ctxOwnsRequest); if (ret == 0) { request->ssl = ssl; ret = CheckOcspRequest(SSL_CM(ssl)->ocsp_stapling, @@ -24161,12 +24529,13 @@ int SendCertificateStatus(WOLFSSL* ssl) i++; - FreeOcspRequest(request); + if (!ctxOwnsRequest) + FreeOcspRequest(request); } } } - - XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); + if (!ctxOwnsRequest) + XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); #ifdef WOLFSSL_SMALL_STACK XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); #endif @@ -24393,6 +24762,50 @@ static int CheckTLS13AEADSendLimit(WOLFSSL* ssl) } #endif /* WOLFSSL_TLS13 && !WOLFSSL_TLS13_IGNORE_AEAD_LIMITS */ +#ifdef WOLFSSL_THREADED_CRYPT +int SendAsyncData(WOLFSSL* ssl) +{ + int i; + + for (i = 0; i < WOLFSSL_THREADED_CRYPT_CNT; i++) { + ThreadCrypt* encrypt = &ssl->buffers.encrypt[i]; + + if (encrypt->done) { + int error; + + GrowOutputBuffer(ssl, encrypt->buffer.length); + XMEMCPY(ssl->buffers.outputBuffer.buffer, encrypt->buffer.buffer, + encrypt->buffer.length); + ssl->buffers.outputBuffer.length = encrypt->buffer.length; + ssl->buffers.outputBuffer.idx = 0; + encrypt->done = 0; + encrypt->avail = 1; + if ((error = SendBuffered(ssl)) < 0) { + ssl->error = error; + WOLFSSL_ERROR(ssl->error); + /* store for next call if WANT_WRITE or user embedSend() that + doesn't present like WANT_WRITE */ + ssl->buffers.plainSz = encrypt->buffer.length; + ssl->buffers.prevSent = encrypt->buffer.length; + if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && + (ssl->options.connReset || ssl->options.isClosed)) { + return SOCKET_PEER_CLOSED_E; /* peer reset or closed */ + } + return ssl->error; + } + + /* only one message per attempt */ + if (ssl->options.partialWrite == 1) { + WOLFSSL_MSG("Partial Write on, only sending one record"); + break; + } + } + } + + return 0; +} +#endif + /** * ssl_in_handshake(): * Invoked in wolfSSL_read/wolfSSL_write to check if wolfSSL_negotiate() is @@ -24447,18 +24860,20 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_EARLY_DATA_GROUP) int groupMsgs = 0; #endif + int error = ssl->error; - if (ssl->error == WANT_WRITE + if (error == WC_NO_ERR_TRACE(WANT_WRITE) #ifdef WOLFSSL_ASYNC_CRYPT - || ssl->error == WC_PENDING_E + || error == WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { + error = 0; ssl->error = 0; } /* don't allow write after decrypt or mac error */ - if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || - ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR)) { + if (error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || + error == WC_NO_ERR_TRACE(DECRYPT_ERROR)) { /* For DTLS allow these possible errors and allow the session to continue despite them */ if (ssl->options.dtls) { @@ -24501,10 +24916,33 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) return WOLFSSL_CBIO_ERR_WANT_WRITE; } #endif - return err; + return err; } } +#ifdef WOLFSSL_RW_THREADED +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) { + /* Dtls13DoScheduledWork(ssl) may return WANT_WRITE */ + if ((error = Dtls13DoScheduledWork(ssl)) < 0) { + ssl->error = error; + WOLFSSL_ERROR(error); + return error; + } + } +#endif /* WOLFSSL_DTLS13 */ +#ifdef WOLFSSL_TLS13 + if (ssl->options.sendKeyUpdate) { + ssl->options.sendKeyUpdate = 0; + ret = SendTls13KeyUpdate(ssl); + if (ret != 0) { + ssl->error = BUILD_MSG_ERROR; + return WOLFSSL_FATAL_ERROR; + } + } +#endif +#endif + /* last time system socket output buffer was full, try again to send */ if (ssl->buffers.outputBuffer.length > 0 #if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_EARLY_DATA_GROUP) @@ -24512,15 +24950,16 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #endif ) { WOLFSSL_MSG("output buffer was full, trying to send again"); - if ( (ssl->error = SendBuffered(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && - (ssl->options.connReset || ssl->options.isClosed)) { - ssl->error = SOCKET_PEER_CLOSED_E; - WOLFSSL_ERROR(ssl->error); + if ( (error = SendBuffered(ssl)) < 0) { + WOLFSSL_ERROR(error); + if (error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && + (ssl->options.connReset || ssl->options.isClosed)) { + error = SOCKET_PEER_CLOSED_E; + ssl->error = error; + WOLFSSL_ERROR(error); return 0; /* peer reset or closed */ } - return ssl->error; + return (ssl->error = error); } else { /* advance sent to previous sent + plain size just sent */ @@ -24529,7 +24968,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) if (sent > sz) { WOLFSSL_MSG("error: write() after WANT_WRITE with short size"); - return ssl->error = BAD_FUNC_ARG; + return (ssl->error = BAD_FUNC_ARG); } } } @@ -24540,6 +24979,19 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) return WOLFSSL_FATAL_ERROR; } +#ifdef WOLFSSL_THREADED_CRYPT + ret = SendAsyncData(ssl); + if (ret != 0) { + ssl->error = ret; + return WOLFSSL_FATAL_ERROR; + } + if (ssl->dtls13WaitKeyUpdateAck) { + ret = DoDtls13KeyUpdateAck(ssl); + if (ret != 0) + return ret; + } +#endif + for (;;) { byte* out; byte* sendBuffer = (byte*)data + sent; /* may switch on comp */ @@ -24548,6 +25000,10 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #ifdef HAVE_LIBZ byte comp[MAX_RECORD_SIZE + MAX_COMP_EXTRA]; #endif +#ifdef WOLFSSL_THREADED_CRYPT + int i; + ThreadCrypt* encrypt = NULL; +#endif #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS) if (IsAtLeastTLSv1_3(ssl->version)) { @@ -24612,21 +25068,53 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_DTLS_SIZE_CHECK) if (ssl->options.dtls && (buffSz < sz - sent)) { - ssl->error = DTLS_SIZE_ERROR; - WOLFSSL_ERROR(ssl->error); - return ssl->error; + error = DTLS_SIZE_ERROR; + ssl->error = error; + WOLFSSL_ERROR(error); + return error; } #endif outputSz = buffSz + COMP_EXTRA + DTLS_RECORD_HEADER_SZ; if (IsEncryptionOn(ssl, 1) || ssl->options.tls1_3) outputSz += cipherExtraData(ssl); +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls) { + byte cidSz = 0; + if ((cidSz = DtlsGetCidTxSize(ssl)) > 0) + outputSz += cidSz + 1; /* +1 for inner content type */ + } +#endif + /* check for available size */ if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) - return ssl->error = ret; + return (ssl->error = ret); /* get output buffer */ +#ifndef WOLFSSL_THREADED_CRYPT out = GetOutputBuffer(ssl); +#else + do { + for (i = 0; i < WOLFSSL_THREADED_CRYPT_CNT; i++) { + if (ssl->buffers.encrypt[i].avail) { + encrypt = &ssl->buffers.encrypt[i]; + break; + } + } + if (encrypt == NULL) { + ret = SendAsyncData(ssl); + if (ret != 0) { + ssl->error = ret; + return WOLFSSL_FATAL_ERROR; + } + } + } + while (encrypt == NULL); + encrypt->done = 0; + encrypt->avail = 0; + GrowAnOutputBuffer(ssl, &encrypt->buffer, outputSz); + out = encrypt->buffer.buffer; +#endif #ifdef HAVE_LIBZ if (ssl->options.usingCompression) { @@ -24670,21 +25158,70 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #ifdef WOLFSSL_ASYNC_CRYPT FreeAsyncCtx(ssl, 0); #endif - ssl->buffers.outputBuffer.length += sendSz; +#ifdef WOLFSSL_THREADED_CRYPT + if (!encrypt->init) { + SetKeys(&encrypt->encrypt, NULL, &ssl->keys, &ssl->specs, + ssl->options.side, ssl->heap, ssl->devId, ssl->rng, + ssl->options.tls1_3); + encrypt->init = 1; + } + encrypt->buffer.length = sendSz; + encrypt->offset = RECORD_HEADER_SZ; + if (ssl->options.dtls) { + encrypt->offset += DTLS_RECORD_EXTRA; + } + encrypt->cryptLen = outputSz - encrypt->offset; + #ifdef HAVE_TRUNCATED_HMAC + if (ssl->truncated_hmac) { + encrypt->cryptLen -= min(TRUNCATED_HMAC_SZ, ssl->specs.hash_size); + } + else + #endif + { + encrypt->cryptLen -= ssl->specs.hash_size; + } - if ( (ssl->error = SendBuffered(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); +#if !defined(NO_PUBLIC_GCM_SET_IV) && \ + ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \ + (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))) + XMEMCPY(encrypt->nonce, ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ); + XMEMCPY(encrypt->nonce + AESGCM_IMP_IV_SZ, ssl->keys.aead_exp_IV, + AESGCM_EXP_IV_SZ); +#endif + XMEMSET(encrypt->additional, 0, AEAD_AUTH_DATA_SZ); + WriteSEQ(ssl, CUR_ORDER, encrypt->additional); + XMEMCPY(encrypt->additional + AEAD_TYPE_OFFSET, encrypt->buffer.buffer, + 3); + c16toa(sendSz - encrypt->offset - AESGCM_EXP_IV_SZ - + ssl->specs.aead_mac_size, encrypt->additional + AEAD_LEN_OFFSET); + + #ifdef WOLFSSL_DTLS + if (ssl->options.dtls) + DtlsSEQIncrement(ssl, CUR_ORDER); + #endif + + if (encrypt->signal != NULL) { + encrypt->signal(encrypt->signalCtx, ssl); + } + return sendSz; +#else + ssl->buffers.outputBuffer.length += (word32)sendSz; + + if ( (error = SendBuffered(ssl)) < 0) { + ssl->error = error; + WOLFSSL_ERROR(error); /* store for next call if WANT_WRITE or user embedSend() that doesn't present like WANT_WRITE */ ssl->buffers.plainSz = buffSz; ssl->buffers.prevSent = sent; - if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && - (ssl->options.connReset || ssl->options.isClosed)) { + if (error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && + (ssl->options.connReset || ssl->options.isClosed)) { + error = SOCKET_PEER_CLOSED_E; ssl->error = SOCKET_PEER_CLOSED_E; - WOLFSSL_ERROR(ssl->error); + WOLFSSL_ERROR(error); return 0; /* peer reset or closed */ } - return ssl->error; + return error; } sent += buffSz; @@ -24694,6 +25231,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) WOLFSSL_MSG("Partial Write on, only sending one record"); break; } +#endif } return sent; @@ -24703,11 +25241,14 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) { int size; + int error = ssl->error; WOLFSSL_ENTER("ReceiveData"); /* reset error state */ - if (ssl->error == WANT_READ || ssl->error == WOLFSSL_ERROR_WANT_READ) { + if (error == WC_NO_ERR_TRACE(WANT_READ) || + error == WOLFSSL_ERROR_WANT_READ) { + error = 0; ssl->error = 0; } @@ -24715,25 +25256,26 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) if (ssl->options.dtls) { /* In DTLS mode, we forgive some errors and allow the session * to continue despite them. */ - if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || - ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR) || - ssl->error == WC_NO_ERR_TRACE(DTLS_SIZE_ERROR)) { + if (error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) || + error == WC_NO_ERR_TRACE(DECRYPT_ERROR) || + error == WC_NO_ERR_TRACE(DTLS_SIZE_ERROR)) { + error = 0; ssl->error = 0; } } #endif /* WOLFSSL_DTLS */ - if (ssl->error != 0 && ssl->error != WANT_WRITE + if (error != 0 && error != WC_NO_ERR_TRACE(WANT_WRITE) #ifdef WOLFSSL_ASYNC_CRYPT - && ssl->error != WC_PENDING_E + && error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif #if defined(HAVE_SECURE_RENEGOTIATION) || defined(WOLFSSL_DTLS13) - && ssl->error != APP_DATA_READY + && error != WC_NO_ERR_TRACE(APP_DATA_READY) #endif ) { WOLFSSL_MSG("User calling wolfSSL_read in error state, not allowed"); - return ssl->error; + return error; } #ifdef WOLFSSL_EARLY_DATA @@ -24771,32 +25313,39 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) #endif while (ssl->buffers.clearOutputBuffer.length == 0) { - if ( (ssl->error = ProcessReply(ssl)) < 0) { - if (ssl->error == ZERO_RETURN) { + if ( (error = ProcessReply(ssl)) < 0) { + if (error == WC_NO_ERR_TRACE(ZERO_RETURN)) { + ssl->error = error; WOLFSSL_MSG("Zero return, no more data coming"); return 0; /* no more data coming */ } - if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) { + if (error == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) { if (ssl->options.connReset || ssl->options.isClosed) { WOLFSSL_MSG("Peer reset or closed, connection done"); - ssl->error = SOCKET_PEER_CLOSED_E; - WOLFSSL_ERROR(ssl->error); + error = SOCKET_PEER_CLOSED_E; + ssl->error = error; + WOLFSSL_ERROR(error); return 0; /* peer reset or closed */ } } - WOLFSSL_ERROR(ssl->error); - return ssl->error; + ssl->error = error; + WOLFSSL_ERROR(error); + return error; } -#ifdef WOLFSSL_DTLS13 +#ifndef WOLFSSL_RW_THREADED + #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) { /* Dtls13DoScheduledWork(ssl) may return WANT_WRITE */ - if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) { - WOLFSSL_ERROR(ssl->error); - return ssl->error; + if ((error = Dtls13DoScheduledWork(ssl)) < 0) { + ssl->error = error; + WOLFSSL_ERROR(error); + return error; } } -#endif /* WOLFSSL_DTLS13 */ + #endif /* WOLFSSL_DTLS13 */ +#endif + #ifdef HAVE_SECURE_RENEGOTIATION if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) { @@ -24845,12 +25394,12 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) #endif } - size = min(sz, (int)ssl->buffers.clearOutputBuffer.length); + size = (int)min((word32)sz, ssl->buffers.clearOutputBuffer.length); XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, size); if (peek == 0) { - ssl->buffers.clearOutputBuffer.length -= size; + ssl->buffers.clearOutputBuffer.length -= (word32)size; ssl->buffers.clearOutputBuffer.buffer += size; } @@ -24924,7 +25473,7 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) /* If CheckAvailableSize returned WANT_WRITE due to a blocking write * then discard pending output and just send the alert. */ if (ssl->options.dtls) { - if (ret != WANT_WRITE || severity != alert_fatal) + if (ret != WC_NO_ERR_TRACE(WANT_WRITE) || severity != alert_fatal) return ret; ShrinkOutputBuffer(ssl); if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) { @@ -25021,7 +25570,21 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) } #endif - ssl->buffers.outputBuffer.length += sendSz; + /* + * We check if we are trying to send a + * CLOSE_NOTIFY alert. + * */ + if (type == close_notify) { + if (!ssl->options.sentNotify) { + ssl->options.sentNotify = 1; + } + else { + /* CLOSE_NOTIFY already sent */ + return 0; + } + } + + ssl->buffers.outputBuffer.length += (word32)sendSz; ret = SendBuffered(ssl); @@ -25103,16 +25666,19 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) } /* pass to wolfCrypt */ - if (error < MAX_CODE_E && error > MIN_CODE_E) { + if (error <= WC_FIRST_E && error >= WC_LAST_E) { return wc_GetErrorString(error); } - switch (error) { - + if (error == 0) { #ifdef OPENSSL_EXTRA - case 0 : return "ok"; +#else + return "unknown error number"; #endif + } + + switch ((enum wolfSSL_ErrorCodes)error) { case UNSUPPORTED_SUITE : return "unsupported cipher suite"; @@ -25222,9 +25788,6 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case -WOLFSSL_ERROR_WANT_X509_LOOKUP: return "application client cert callback asked to be called again"; - case -WOLFSSL_ERROR_SSL: - return "fatal TLS protocol error"; - case BUFFER_ERROR : return "malformed buffer input error"; @@ -25320,6 +25883,9 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case MAX_CHAIN_ERROR: return "Maximum Chain Depth Exceeded"; + case MAX_CERT_EXTENSIONS_ERR: + return "Maximum Cert Extension Exceeded"; + case COOKIE_ERROR: return "DTLS Cookie Error"; @@ -25380,6 +25946,9 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case SESSION_TICKET_EXPECT_E: return "Session Ticket Error"; + case SCR_DIFFERENT_CERT_E: + return "SCR Different cert error"; + case SESSION_SECRET_CB_E: return "Session Secret Callback Error"; @@ -25545,81 +26114,133 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case UNSUPPORTED_CERTIFICATE: return "Unsupported certificate type"; -#ifdef HAVE_HTTP_CLIENT case HTTP_TIMEOUT: return "HTTP timeout for OCSP or CRL req"; + case HTTP_RECV_ERR: return "HTTP Receive error"; + case HTTP_HEADER_ERR: return "HTTP Header error"; + case HTTP_PROTO_ERR: return "HTTP Protocol error"; + case HTTP_STATUS_ERR: return "HTTP Status error"; + case HTTP_VERSION_ERR: return "HTTP Version error"; + case HTTP_APPSTR_ERR: return "HTTP Application string error"; -#endif -#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) + + case UNSUPPORTED_PROTO_VERSION: + #ifdef OPENSSL_EXTRA + return "WRONG_SSL_VERSION"; + #else + return "bad/unsupported protocol version"; + #endif + + case FALCON_KEY_SIZE_E: + return "Wrong key size for Falcon."; + + case DILITHIUM_KEY_SIZE_E: + return "Wrong key size for Dilithium."; + + case QUIC_TP_MISSING_E: + return "QUIC transport parameter not set"; + + case QUIC_WRONG_ENC_LEVEL: + return "QUIC data received at wrong encryption level"; + + case DTLS_CID_ERROR: + return "DTLS ConnectionID mismatch or missing"; + + case DTLS_TOO_MANY_FRAGMENTS_E: + return "Received too many fragmented messages from peer error"; + + case DUPLICATE_TLS_EXT_E: + return "Duplicate TLS extension in message."; + + case WOLFSSL_ALPN_NOT_FOUND: + return "TLS extension not found"; + + case WOLFSSL_BAD_CERTTYPE: + return "Certificate type not supported"; + + case WOLFSSL_BAD_STAT: + return "bad status"; + + case WOLFSSL_BAD_PATH: + return "No certificates found at designated path"; + + case WOLFSSL_BAD_FILETYPE: + return "Data format not supported"; + + case WOLFSSL_BAD_FILE: + return "Input/output error on file"; + + case WOLFSSL_NOT_IMPLEMENTED: + return "Function not implemented"; + + case WOLFSSL_UNKNOWN: + return "Unknown algorithm (EVP)"; + + case WOLFSSL_FATAL_ERROR: + return "fatal error"; + } + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) + + switch (error) { /* TODO: -WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE. Conflicts with - * -WOLFSSL_ERROR_WANT_CONNECT. */ + * -WOLFSSL_ERROR_WANT_CONNECT. + */ + case -WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID: return "certificate not yet valid"; + case -WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED: return "certificate has expired"; + case -WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: return "certificate signature failure"; + case -WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: return "format error in certificate's notAfter field"; + case -WOLFSSL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: return "self-signed certificate in certificate chain"; + case -WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: return "unable to get local issuer certificate"; + case -WOLFSSL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: return "unable to verify the first certificate"; + case -WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG: return "certificate chain too long"; + case -WOLFSSL_X509_V_ERR_CERT_REVOKED: return "certificate revoked"; + case -WOLFSSL_X509_V_ERR_INVALID_CA: return "invalid CA certificate"; + case -WOLFSSL_X509_V_ERR_PATH_LENGTH_EXCEEDED: return "path length constraint exceeded"; + case -WOLFSSL_X509_V_ERR_CERT_REJECTED: return "certificate rejected"; + case -WOLFSSL_X509_V_ERR_SUBJECT_ISSUER_MISMATCH: return "subject issuer mismatch"; -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || HAVE_WEBSERVER */ - case UNSUPPORTED_PROTO_VERSION: - #ifdef OPENSSL_EXTRA - return "WRONG_SSL_VERSION"; - #else - return "bad/unsupported protocol version"; - #endif - - case FALCON_KEY_SIZE_E: - return "Wrong key size for Falcon."; - case DILITHIUM_KEY_SIZE_E: - return "Wrong key size for Dilithium."; - -#ifdef WOLFSSL_QUIC - case QUIC_TP_MISSING_E: - return "QUIC transport parameter not set"; - case QUIC_WRONG_ENC_LEVEL: - return "QUIC data received at wrong encryption level"; -#endif - case DTLS_CID_ERROR: - return "DTLS ConnectionID mismatch or missing"; - case DTLS_TOO_MANY_FRAGMENTS_E: - return "Received too many fragmented messages from peer error"; - - case DUPLICATE_TLS_EXT_E: - return "Duplicate TLS extension in message."; - - default : - return "unknown error number"; } +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || HAVE_WEBSERVER || HAVE_MEMCACHED */ + + return "unknown error number"; #endif /* NO_ERROR_STRINGS */ } @@ -25696,7 +26317,7 @@ void SetErrorString(int error, char* str) */ #ifndef NO_ERROR_STRINGS - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \ + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \ defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE} #define SUITE_ALIAS(x,z,w,v,u) {(x),"",(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS}, @@ -25705,7 +26326,7 @@ void SetErrorString(int error, char* str) #define SUITE_ALIAS(x,z,w,v,u) {(x),"",(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS}, #endif #else - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \ + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \ defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE} #define SUITE_ALIAS(x,z,w,v,u) {(x),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS}, @@ -26499,7 +27120,7 @@ const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]) { /* Returns the number of bits based on the cipher enc string, or 0 on failure */ int SetCipherBits(const char* enc) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if ((XSTRCMP(enc,"AESGCM(256)") == 0) || (XSTRCMP(enc,"AES(256)") == 0) || @@ -26567,13 +27188,16 @@ const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl) } int GetCipherSuiteFromName(const char* name, byte* cipherSuite0, - byte* cipherSuite, int* flags) + byte* cipherSuite, byte* major, byte* minor, int* flags) { int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); int i; unsigned long len; const char* nameDelim; + (void)major; + (void)minor; + /* Support trailing : */ nameDelim = XSTRSTR(name, ":"); if (nameDelim) @@ -26591,9 +27215,19 @@ int GetCipherSuiteFromName(const char* name, byte* cipherSuite0, #endif if (found) { - *cipherSuite0 = cipher_names[i].cipherSuite0; - *cipherSuite = cipher_names[i].cipherSuite; - *flags = cipher_names[i].flags; + if (cipherSuite0 != NULL) + *cipherSuite0 = cipher_names[i].cipherSuite0; + if (cipherSuite != NULL) + *cipherSuite = cipher_names[i].cipherSuite; +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) + if (major != NULL) + *major = cipher_names[i].major; + if (minor != NULL) + *minor = cipher_names[i].minor; +#endif + if (flags != NULL) + *flags = cipher_names[i].flags; ret = 0; break; } @@ -27464,7 +28098,7 @@ static int CmpEccStrength(int hashAlgo, int curveSz) { int dgstSz = GetMacDigestSize((byte)hashAlgo); if (dgstSz <= 0) - return -1; + return WOLFSSL_FATAL_ERROR; return dgstSz - (curveSz & (~0x3)); } #endif @@ -28263,7 +28897,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) #ifndef NO_RSA if (ssl->buffers.keyType == rsa_sa_algo || ssl->buffers.keyType == 0) { ssl->hsType = DYNAMIC_TYPE_RSA; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey); if (ret != 0) { goto exit_dpk; } @@ -28312,7 +28946,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) #ifdef HAVE_ECC #ifndef NO_RSA - FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey); + FreeKey(ssl, (int)ssl->hsType, (void**)&ssl->hsKey); #endif /* !NO_RSA */ if (ssl->buffers.keyType == ecc_dsa_sa_algo || ssl->buffers.keyType == 0 @@ -28321,7 +28955,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) #endif ) { ssl->hsType = DYNAMIC_TYPE_ECC; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey); if (ret != 0) { goto exit_dpk; } @@ -29474,14 +30108,16 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (ssl->options.dtls) recordHeaderSz += DTLS_RECORD_EXTRA; inputSz -= recordHeaderSz; - input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + input = (byte*)XMALLOC((size_t)inputSz, ssl->heap, + DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; XMEMCPY(input, output + recordHeaderSz, inputSz); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && - (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, client_hello)) != 0) { + (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, + client_hello)) != 0) { XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); return ret; } @@ -29525,7 +30161,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->options.buildingMsg = 0; - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ret = SendBuffered(ssl); @@ -29550,9 +30186,8 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #endif #ifdef WOLFSSL_DTLS - if (ssl->options.dtls) { + if (ssl->options.dtls) DtlsMsgPoolReset(ssl); - } #endif if (OPAQUE16_LEN + OPAQUE8_LEN > size) @@ -30006,15 +30641,8 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->options.serverState = SERVER_HELLO_COMPLETE; - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) *inOutIdx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMWrite && - ssl->specs.cipher_type == block) { - *inOutIdx += MacSize(ssl); - } - #endif - } #ifdef HAVE_SECRET_CALLBACK if (ssl->sessionSecretCb != NULL @@ -30264,7 +30892,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, InitDecodedCert(cert, input + *inOutIdx, dnSz, ssl->heap); - ret = GetName(cert, SUBJECT, dnSz); + ret = GetName(cert, ASN_SUBJECT, dnSz); if (ret == 0) { if ((name = wolfSSL_X509_NAME_new_ex(cert->heap)) == NULL) @@ -30272,12 +30900,12 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } if (ret == 0) { - CopyDecodedName(name, cert, SUBJECT); + CopyDecodedName(name, cert, ASN_SUBJECT); } if (ret == 0) { if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name) - == WOLFSSL_FAILURE) + <= 0) { ret = MEMORY_ERROR; } @@ -30346,13 +30974,8 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->options.sendVerify = SEND_BLANK_CERT; } - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) *inOutIdx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - *inOutIdx += MacSize(ssl); - #endif - } WOLFSSL_LEAVE("DoCertificateRequest", 0); WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO); @@ -30472,10 +31095,8 @@ static void FreeDskeArgs(WOLFSSL* ssl, void* pArgs) #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ defined(HAVE_CURVE448) - if (args->verifySig) { - XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); - args->verifySig = NULL; - } + XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); + args->verifySig = NULL; #endif } @@ -31742,13 +32363,8 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, case TLS_ASYNC_FINALIZE: { - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) args->idx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - args->idx += MacSize(ssl); - #endif - } /* Advance state and proceed */ ssl->options.asyncState = TLS_ASYNC_END; @@ -31811,14 +32427,10 @@ static void FreeSckeArgs(WOLFSSL* ssl, void* pArgs) (void)ssl; - if (args->encSecret) { - XFREE(args->encSecret, ssl->heap, DYNAMIC_TYPE_SECRET); - args->encSecret = NULL; - } - if (args->input) { - XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); - args->input = NULL; - } + XFREE(args->encSecret, ssl->heap, DYNAMIC_TYPE_SECRET); + args->encSecret = NULL; + XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + args->input = NULL; } /* handle generation client_key_exchange (16) */ @@ -32101,7 +32713,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) /* create ephemeral private key */ ssl->hsType = DYNAMIC_TYPE_ECC; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey); if (ret != 0) { goto exit_scke; } @@ -32620,7 +33232,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) ); if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, @@ -32641,7 +33253,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) ); if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { FreeKey(ssl, DYNAMIC_TYPE_CURVE448, @@ -32688,7 +33300,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) ); if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, @@ -32709,7 +33321,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) ); if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { FreeKey(ssl, DYNAMIC_TYPE_CURVE448, @@ -32732,7 +33344,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif && !ssl->options.keepResources) { FreeKey(ssl, DYNAMIC_TYPE_ECC, @@ -32925,8 +33537,8 @@ int SendClientKeyExchange(WOLFSSL* ssl) if (ssl->options.dtls) recordHeaderSz += DTLS_RECORD_EXTRA; - args->inputSz = idx - recordHeaderSz; /* buildmsg adds rechdr */ - args->input = (byte*)XMALLOC(args->inputSz, ssl->heap, + args->inputSz = (int)idx - recordHeaderSz; /* buildmsg adds rechdr */ + args->input = (byte*)XMALLOC((size_t)args->inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); if (args->input == NULL) { ERROR_OUT(MEMORY_E, exit_scke); @@ -32989,12 +33601,12 @@ int SendClientKeyExchange(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += args->sendSz; + ssl->buffers.outputBuffer.length += (word32)args->sendSz; if (!ssl->options.groupMessages) { ret = SendBuffered(ssl); } - if (ret == 0 || ret == WANT_WRITE) { + if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) { int tmpRet = MakeMasterSecret(ssl); if (tmpRet != 0) { ret = tmpRet; /* save WANT_WRITE unless more serious */ @@ -33024,7 +33636,9 @@ int SendClientKeyExchange(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_IO /* Handle async operation */ - if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) || ret == WANT_WRITE) { + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) || + ret == WC_NO_ERR_TRACE(WANT_WRITE)) + { if (ssl->options.buildingMsg) return ret; /* If we have completed all states then we will not enter this function @@ -33083,15 +33697,11 @@ static void FreeScvArgs(WOLFSSL* ssl, void* pArgs) (void)ssl; #ifndef NO_RSA - if (args->verifySig) { - XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); - args->verifySig = NULL; - } + XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); + args->verifySig = NULL; #endif - if (args->input) { - XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); - args->input = NULL; - } + XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + args->input = NULL; } /* handle generation of certificate_verify (15) */ @@ -33171,7 +33781,7 @@ int SendCertificateVerify(WOLFSSL* ssl) } /* Use tmp buffer */ - args->input = (byte*)XMALLOC(args->sendSz, + args->input = (byte*)XMALLOC((size_t)args->sendSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); if (args->input == NULL) ERROR_OUT(MEMORY_E, exit_scv); @@ -33581,9 +34191,9 @@ int SendCertificateVerify(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_IO /* Handle async operation */ - if (ret == WANT_WRITE + if (ret == WC_NO_ERR_TRACE(WANT_WRITE) #ifdef WOLFSSL_ASYNC_CRYPT - || ret == WC_PENDING_E + || ret == WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) return ret; @@ -33717,13 +34327,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif } - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) *inOutIdx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - *inOutIdx += MacSize(ssl); - #endif - } ssl->expect_session_ticket = 0; @@ -33917,6 +34522,29 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifndef WOLFSSL_NO_TLS12 + static int getSessionID(WOLFSSL* ssl) + { + int sessIdSz = 0; + (void)ssl; +#ifndef NO_SESSION_CACHE + /* if no session cache don't send a session ID */ + if (!ssl->options.sessionCacheOff) + sessIdSz = ID_LEN; +#endif +#ifdef HAVE_SESSION_TICKET + /* we may be echoing an ID as part of session tickets */ + if (ssl->options.useTicket) { + /* echo session id sz can be 0,32 or bogus len in between */ + sessIdSz = ssl->arrays->sessionIDSz; + if (sessIdSz > ID_LEN) { + WOLFSSL_MSG("Bad bogus session id len"); + return BUFFER_ERROR; + } + } +#endif /* HAVE_SESSION_TICKET */ + return sessIdSz; + } + /* handle generation of server_hello (2) */ int SendServerHello(WOLFSSL* ssl) { @@ -33925,17 +34553,18 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word16 length; word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; int sendSz; - byte sessIdSz = ID_LEN; - #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SESSION_TICKET) - byte echoId = 0; /* ticket echo id flag */ - #endif - byte cacheOff = 0; /* session cache off flag */ + byte sessIdSz; WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND); WOLFSSL_ENTER("SendServerHello"); + ret = getSessionID(ssl); + if (ret < 0) + return ret; + sessIdSz = (byte)ret; + length = VERSION_SZ + RAN_LEN - + ID_LEN + ENUM_LEN + + ENUM_LEN + sessIdSz + SUITE_LEN + ENUM_LEN; @@ -33943,45 +34572,12 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ret = TLSX_GetResponseSize(ssl, server_hello, &length); if (ret != 0) return ret; - #ifdef HAVE_SESSION_TICKET - if (ssl->options.useTicket) { - /* echo session id sz can be 0,32 or bogus len in between */ - sessIdSz = ssl->arrays->sessionIDSz; - if (sessIdSz > ID_LEN) { - WOLFSSL_MSG("Bad bogus session id len"); - return BUFFER_ERROR; - } - if (!IsAtLeastTLSv1_3(ssl->version)) - length -= (ID_LEN - sessIdSz); /* adjust ID_LEN assumption */ - echoId = 1; - } - #endif /* HAVE_SESSION_TICKET */ #else if (ssl->options.haveEMS) { length += HELLO_EXT_SZ_SZ + HELLO_EXT_SZ; } #endif - /* is the session cache off at build or runtime */ -#ifdef NO_SESSION_CACHE - cacheOff = 1; -#else - if (ssl->options.sessionCacheOff == 1) { - cacheOff = 1; - } -#endif - - /* if no session cache don't send a session ID unless we're echoing - * an ID as part of session tickets */ - if (cacheOff == 1 - #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SESSION_TICKET) - && echoId == 0 - #endif - ) { - length -= ID_LEN; /* adjust ID_LEN assumption */ - sessIdSz = 0; - } - sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { @@ -34012,11 +34608,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* then random and session id */ if (!ssl->options.resuming) { - /* generate random part and session id */ - ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, - RAN_LEN + sizeof(sessIdSz) + sessIdSz); - if (ret != 0) - return ret; + word32 genRanLen = RAN_LEN; #ifdef WOLFSSL_TLS13 if (TLSv1_3_Capable(ssl)) { @@ -34024,6 +34616,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1), tls13Downgrade, TLS13_DOWNGRADE_SZ); output[idx + RAN_LEN - 1] = (byte)IsAtLeastTLSv1_2(ssl); + genRanLen -= TLS13_DOWNGRADE_SZ + 1; } else #endif @@ -34035,12 +34628,21 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1), tls13Downgrade, TLS13_DOWNGRADE_SZ); output[idx + RAN_LEN - 1] = 0; + genRanLen -= TLS13_DOWNGRADE_SZ + 1; } - /* store info in SSL for later */ + /* generate random part */ + ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, genRanLen); + if (ret != 0) + return ret; XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN); idx += RAN_LEN; + + /* generate session id */ output[idx++] = sessIdSz; + ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, sessIdSz); + if (ret != 0) + return ret; XMEMCPY(ssl->arrays->sessionID, output + idx, sessIdSz); ssl->arrays->sessionIDSz = sessIdSz; } @@ -34106,7 +34708,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->options.dtls) recordHeaderSz += DTLS_RECORD_EXTRA; inputSz -= recordHeaderSz; - input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + input = (byte*)XMALLOC((size_t)inputSz, ssl->heap, + DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; @@ -34151,7 +34754,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->options.serverState = SERVER_HELLO_COMPLETE; ssl->options.buildingMsg = 0; - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; if (ssl->options.groupMessages) ret = 0; @@ -34174,7 +34777,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return 0; } - return (byte)GetCurveByOID(key->dp->oidSum); + return (byte)GetCurveByOID((int)key->dp->oidSum); } #endif /* HAVE_ECC */ @@ -34210,16 +34813,12 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, (void)ssl; #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) - if (args->exportBuf) { - XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER); - args->exportBuf = NULL; - } + XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER); + args->exportBuf = NULL; #endif #ifndef NO_RSA - if (args->verifySig) { - XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); - args->verifySig = NULL; - } + XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); + args->verifySig = NULL; #endif (void)args; } @@ -35816,9 +36415,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef WOLFSSL_ASYNC_IO /* Handle async operation */ - if (ret == WANT_WRITE + if (ret == WC_NO_ERR_TRACE(WANT_WRITE) #ifdef WOLFSSL_ASYNC_CRYPT - || ret == WC_PENDING_E + || ret == WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) return ret; @@ -37116,8 +37715,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->clSuites = NULL; #endif #ifdef WOLFSSL_SMALL_STACK - if (clSuites != NULL) - XFREE(clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); + XFREE(clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); #endif WOLFSSL_LEAVE("DoClientHello", ret); WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO); @@ -37533,13 +38131,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, case TLS_ASYNC_FINALIZE: { - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) args->idx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - args->idx += MacSize(ssl); - #endif - } ssl->options.havePeerVerify = 1; @@ -37652,7 +38245,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, inputSz += DTLS_HANDSHAKE_EXTRA; } - input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + input = (byte*)XMALLOC((size_t)inputSz, ssl->heap, + DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; @@ -37697,7 +38291,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->options.serverState = SERVER_HELLODONE_COMPLETE; ssl->options.buildingMsg = 0; - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ret = SendBuffered(ssl); @@ -37888,7 +38482,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, itHash = HashObject((byte*)it, sizeof(*it), &error); if (error == 0) { ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv, et->mac, - 1, et->enc_ticket, sizeof(InternalTicket), &encLen, + 1, et->enc_ticket, WOLFSSL_INTERNAL_TICKET_LEN, &encLen, SSL_TICKET_CTX(ssl)); } else { @@ -37903,7 +38497,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif goto error; } - if (encLen < (int)sizeof(InternalTicket) || + if (encLen < (int)WOLFSSL_INTERNAL_TICKET_LEN || encLen > (int)WOLFSSL_TICKET_ENC_SZ) { WOLFSSL_MSG("Bad user ticket encrypt size"); ret = BAD_TICKET_KEY_CB_SZ; @@ -37979,7 +38573,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_ENTER("DoDecryptTicket"); if (len > SESSION_TICKET_LEN || - len < (word32)(sizeof(InternalTicket) + WOLFSSL_TICKET_FIXED_SZ)) { + len < (word32)(WOLFSSL_INTERNAL_TICKET_LEN + + WOLFSSL_TICKET_FIXED_SZ)) { WOLFSSL_ERROR_VERBOSE(BAD_TICKET_MSG_SZ); return WOLFSSL_TICKET_RET_REJECT; } @@ -38027,7 +38622,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return WOLFSSL_TICKET_RET_REJECT; } } - if (outLen > (int)inLen || outLen < (int)sizeof(InternalTicket)) { + if (outLen > (int)inLen || outLen < (int)WOLFSSL_INTERNAL_TICKET_LEN) { WOLFSSL_MSG("Bad user ticket decrypt len"); WOLFSSL_ERROR_VERBOSE(BAD_TICKET_KEY_CB_SZ); return BAD_TICKET_KEY_CB_SZ; @@ -38095,7 +38690,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, diff -= ticketSeen; if (diff > timeout * 1000 || diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) - return -1; + return WOLFSSL_FATAL_ERROR; #else sword64 diff; sword64 ticketSeen; /* Time ticket seen (ms) */ @@ -38113,7 +38708,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, diff -= ticketSeen; if (diff > timeout * 1000 || diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) - return -1; + return WOLFSSL_FATAL_ERROR; #endif ato32(psk->it->ageAdd, &ticketAdd); /* Subtract client's ticket age and unobfuscate. */ @@ -38123,7 +38718,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, * Allow +/- 1000 milliseconds on ticket age. */ if (diff < -1000 || diff - MAX_TICKET_AGE_DIFF * 1000 > 1000) - return -1; + return WOLFSSL_FATAL_ERROR; #if !defined(WOLFSSL_PSK_ONE_ID) && !defined(WOLFSSL_PRIORITIZE_PSK) /* Check whether resumption is possible based on suites in SSL and @@ -38131,18 +38726,18 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, */ (void)ssl; if (XMEMCMP(suite, psk->it->suite, SUITE_LEN) != 0) - return -1; + return WOLFSSL_FATAL_ERROR; #else (void)suite; if (!FindSuiteSSL(ssl, psk->it->suite)) - return -1; + return WOLFSSL_FATAL_ERROR; #endif #ifdef OPENSSL_EXTRA if (ssl->sessionCtxSz > 0 && (psk->it->sessionCtxSz != ssl->sessionCtxSz || XMEMCMP(psk->it->sessionCtx, ssl->sessionCtx, ssl->sessionCtxSz) != 0)) - return -1; + return WOLFSSL_FATAL_ERROR; #endif return 0; } @@ -38721,7 +39316,123 @@ static void TicketEncCbCtx_Free(TicketEncCbCtx* keyCtx) wc_FreeRng(&keyCtx->rng); } -#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \ +#ifdef WOLFSSL_TICKET_ENC_CBC_HMAC +/* Ticket encryption/decryption implementation. + * + * @param [in] key Key for encryption/decryption and HMAC. + * @param [in] keyLen Length of key in bytes. + * @param [in] iv IV/Nonce for encryption/decryption. + * @param [in] aad Additional authentication data. + * @param [in] aadSz Length of additional authentication data. + * @param [in] in Data to encrypt/decrypt. + * @param [in] inLen Length of encrypted data. + * @param [out] out Resulting data from encrypt/decrypt. + * @param [out] outLen Size of resulting data. + * @param [in] tag Authentication tag for encrypted data. + * @param [in] heap Dynamic memory allocation data hint. + * @param [in] enc 1 when encrypting, 0 when decrypting. + * @return 0 on success. + * @return Other value when encryption/decryption fails. + */ +static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz, + byte* in, int inLen, byte* out, int* outLen, byte* tag, + void* heap, int enc) +{ + int ret; +#ifdef WOLFSSL_SMALL_STACK + Aes* aes; + Hmac* hmac; +#else + Aes aes[1]; + Hmac hmac[1]; +#endif + + (void)heap; + +#ifdef WOLFSSL_SMALL_STACK + aes = (Aes*)XMALLOC(sizeof(Aes), heap, DYNAMIC_TYPE_TMP_BUFFER); + if (aes == NULL) + return MEMORY_E; + hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_TMP_BUFFER); + if (hmac == NULL) { + XFREE(aes, heap, DYNAMIC_TYPE_TMP_BUFFER); + return MEMORY_E; + } +#endif + + XMEMSET(aes, 0, sizeof(Aes)); + XMEMSET(hmac, 0, sizeof(Hmac)); + + ret = wc_HmacInit(hmac, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ret == 0) { + ret = wc_HmacSetKey(hmac, WOLFSSL_TICKET_ENC_HMAC, key + keyLen - + WOLFSSL_TICKET_HMAC_KEY_SZ, WOLFSSL_TICKET_HMAC_KEY_SZ); + } + if (ret == 0) { + ret = wc_HmacUpdate(hmac, aad, aadSz); + } + + if (ret == 0) { + if (enc) { + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret == 0) { + ret = wc_AesSetKey(aes, key, + keyLen - WOLFSSL_TICKET_HMAC_KEY_SZ, iv, AES_ENCRYPTION); + } + if (ret == 0) { + ret = wc_HmacUpdate(hmac, in, inLen); + } + if (ret == 0) { + ret = wc_AesCbcEncrypt(aes, in, out, inLen); + } + if (ret == 0) { + XMEMSET(tag, 0, WOLFSSL_TICKET_MAC_SZ); + ret = wc_HmacFinal(hmac, tag); + } + wc_AesFree(aes); + } + else { + unsigned char calcTag[WOLFSSL_TICKET_MAC_SZ]; + + ret = wc_AesInit(aes, NULL, INVALID_DEVID); + if (ret == 0) { + ret = wc_AesSetKey(aes, key, + keyLen - WOLFSSL_TICKET_HMAC_KEY_SZ, iv, AES_DECRYPTION); + } + if (ret == 0) { + ret = wc_AesCbcDecrypt(aes, in, out, inLen); + } + if (ret == 0) { + ret = wc_HmacUpdate(hmac, out, inLen); + } + if (ret == 0) { + XMEMSET(calcTag, 0, WOLFSSL_TICKET_MAC_SZ); + ret = wc_HmacFinal(hmac, calcTag); + } + if (ret == 0) { + int i; + calcTag[0] ^= tag[0]; + for (i = 1; i < WOLFSSL_TICKET_MAC_SZ; i++) { + calcTag[0] |= calcTag[i] ^ tag[i]; + } + /* Return a negative value when no match. */ + ret = -calcTag[0]; + } + wc_AesFree(aes); + } + } + wc_HmacFree(hmac); + +#ifdef WOLFSSL_SMALL_STACK + XFREE(hmac, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(aes, heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + *outLen = inLen; + + return ret; +} +#elif defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \ !defined(WOLFSSL_TICKET_ENC_AES128_GCM) && \ !defined(WOLFSSL_TICKET_ENC_AES256_GCM) /* Ticket encryption/decryption implementation. @@ -39016,7 +39727,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_ENTER("DefTicketEncCb"); - if ((!enc) && (inLen != sizeof(InternalTicket))) { + if ((!enc) && (inLen != WOLFSSL_INTERNAL_TICKET_LEN)) { return BUFFER_E; } @@ -40142,7 +40853,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], lenErrMask = 0 - (SECRET_LEN != args->sigSz); args->lastErr = (ret & (~lenErrMask)) | - (RSA_PAD_E & lenErrMask); + (WC_NO_ERR_TRACE(RSA_PAD_E) & lenErrMask); ret = 0; break; } /* rsa_kea */ @@ -40297,7 +41008,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], ); if (!ssl->specs.static_ecdh #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { FreeKey(ssl, DYNAMIC_TYPE_ECC, @@ -40500,13 +41211,8 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], case TLS_ASYNC_FINALIZE: { - if (IsEncryptionOn(ssl, 0)) { + if (IsEncryptionOn(ssl, 0)) args->idx += ssl->keys.padSz; - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) - args->idx += MacSize(ssl); - #endif - } ret = MakeMasterSecret(ssl); @@ -40858,7 +41564,7 @@ int wolfSSL_sk_BY_DIR_HASH_find( } next = next->next; } - return -1; + return WOLFSSL_FATAL_ERROR; } /* return a number of WOLFSSL_BY_DIR_HASH in stack */ int wolfSSL_sk_BY_DIR_HASH_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk) @@ -40866,7 +41572,7 @@ int wolfSSL_sk_BY_DIR_HASH_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk) WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_num"); if (sk == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; return (int)sk->num; } /* return WOLFSSL_BY_DIR_HASH instance at i */ @@ -41027,9 +41733,7 @@ void wolfSSL_BY_DIR_entry_free(WOLFSSL_BY_DIR_entry* entry) wolfSSL_sk_BY_DIR_HASH_free(entry->hashes); } - if (entry->dir_name != NULL) { - XFREE(entry->dir_name, NULL, DYNAMIC_TYPE_OPENSSL); - } + XFREE(entry->dir_name, NULL, DYNAMIC_TYPE_OPENSSL); XFREE(entry, NULL, DYNAMIC_TYPE_OPENSSL); } @@ -41051,7 +41755,7 @@ int wolfSSL_sk_BY_DIR_entry_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk) WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_num"); if (sk == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; return (int)sk->num; } /* return WOLFSSL_BY_DIR_entry instance at i */ @@ -41269,7 +41973,8 @@ static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, } for (i = 0; i < totalCerts; i++) { - secCert = ConvertToSecCertificateRef(certs[i].buffer, certs[i].length); + secCert = ConvertToSecCertificateRef(certs[i].buffer, + (int)certs[i].length); if (!secCert) { WOLFSSL_MSG("Error: can't convert DER cert to SecCertificateRef"); ret = 0; diff --git a/src/src/keys.c b/src/src/keys.c index f9f9e85..b5b982c 100644 --- a/src/src/keys.c +++ b/src/src/keys.c @@ -1,6 +1,6 @@ /* keys.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -2371,7 +2371,7 @@ static int SetPrefix(byte* sha_input, int idx) #endif -static int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, CipherSpecs* specs, +int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, CipherSpecs* specs, int side, void* heap, int devId, WC_RNG* rng, int tls13) { (void)rng; @@ -3318,9 +3318,7 @@ static int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, CipherSpecs* specs, DYNAMIC_TYPE_CIPHER); if (enc->hmac == NULL) return MEMORY_E; - } - if (enc) { if (wc_HmacInit(enc->hmac, heap, devId) != 0) { WOLFSSL_MSG("HmacInit failed in SetKeys"); XFREE(enc->hmac, heap, DYNAMIC_TYPE_CIPHER); @@ -3334,9 +3332,7 @@ static int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, CipherSpecs* specs, DYNAMIC_TYPE_CIPHER); if (dec->hmac == NULL) return MEMORY_E; - } - if (dec) { if (wc_HmacInit(dec->hmac, heap, devId) != 0) { WOLFSSL_MSG("HmacInit failed in SetKeys"); XFREE(dec->hmac, heap, DYNAMIC_TYPE_CIPHER); @@ -3876,12 +3872,12 @@ int DeriveKeys(WOLFSSL* ssl) if (shaOutput == NULL || md5Input == NULL || shaInput == NULL || keyData == NULL || md5 == NULL || sha == NULL) { - if (shaOutput) XFREE(shaOutput, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (md5Input) XFREE(md5Input, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (shaInput) XFREE(shaInput, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (keyData) XFREE(keyData, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (md5) XFREE(md5, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (sha) XFREE(sha, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(shaOutput, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(md5Input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(shaInput, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(keyData, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(md5, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(sha, NULL, DYNAMIC_TYPE_TMP_BUFFER); return MEMORY_E; } @@ -4013,11 +4009,11 @@ static int MakeSslMasterSecret(WOLFSSL* ssl) if (shaOutput == NULL || md5Input == NULL || shaInput == NULL || md5 == NULL || sha == NULL) { - if (shaOutput) XFREE(shaOutput, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (md5Input) XFREE(md5Input, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (shaInput) XFREE(shaInput, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (md5) XFREE(md5, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (sha) XFREE(sha, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(shaOutput, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(md5Input, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(shaInput, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(md5, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(sha, NULL, DYNAMIC_TYPE_TMP_BUFFER); return MEMORY_E; } diff --git a/src/src/ocsp.c b/src/src/ocsp.c index 4760c50..493d826 100644 --- a/src/src/ocsp.c +++ b/src/src/ocsp.c @@ -1,6 +1,6 @@ /* ocsp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -90,8 +90,7 @@ static void FreeOcspEntry(OcspEntry* entry, void* heap) for (status = entry->status; status; status = next) { next = status->next; - if (status->rawOcspResponse) - XFREE(status->rawOcspResponse, heap, DYNAMIC_TYPE_OCSP_STATUS); + XFREE(status->rawOcspResponse, heap, DYNAMIC_TYPE_OCSP_STATUS); #ifdef OPENSSL_EXTRA if (status->serialInt) { @@ -251,10 +250,10 @@ static int GetOcspStatus(WOLFSSL_OCSP* ocsp, OcspRequest* request, else if (*status) { #ifndef NO_ASN_TIME if (XVALIDATE_DATE((*status)->thisDate, - (*status)->thisDateFormat, BEFORE) + (*status)->thisDateFormat, ASN_BEFORE) && ((*status)->nextDate[0] != 0) && XVALIDATE_DATE((*status)->nextDate, - (*status)->nextDateFormat, AFTER)) + (*status)->nextDateFormat, ASN_AFTER)) #endif { ret = xstat2err((*status)->status); @@ -284,7 +283,7 @@ static int GetOcspStatus(WOLFSSL_OCSP* ocsp, OcspRequest* request, * ocsp Context object for OCSP status. * response OCSP response message data. * responseSz Length of OCSP response message data. - * reponseBuffer Buffer object to return the response with. + * responseBuffer Buffer object to return the response with. * status The certificate status object. * entry The OCSP entry for this certificate. * ocspRequest Request corresponding to response. @@ -318,9 +317,9 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, DYNAMIC_TYPE_OCSP_REQUEST); if (newStatus == NULL || newSingle == NULL || ocspResponse == NULL) { - if (newStatus) XFREE(newStatus, NULL, DYNAMIC_TYPE_OCSP_STATUS); - if (newSingle) XFREE(newSingle, NULL, DYNAMIC_TYPE_OCSP_ENTRY); - if (ocspResponse) XFREE(ocspResponse, NULL, DYNAMIC_TYPE_OCSP_REQUEST); + XFREE(newStatus, NULL, DYNAMIC_TYPE_OCSP_STATUS); + XFREE(newSingle, NULL, DYNAMIC_TYPE_OCSP_ENTRY); + XFREE(ocspResponse, NULL, DYNAMIC_TYPE_OCSP_REQUEST); WOLFSSL_LEAVE("CheckCertOCSP", MEMORY_ERROR); return MEMORY_E; @@ -375,10 +374,7 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, } if (status != NULL) { - if (status->rawOcspResponse) { - XFREE(status->rawOcspResponse, ocsp->cm->heap, - DYNAMIC_TYPE_OCSP_STATUS); - } + XFREE(status->rawOcspResponse, ocsp->cm->heap, DYNAMIC_TYPE_OCSP_STATUS); /* Replace existing certificate entry with updated */ ocspResponse->single->status->next = status->next; @@ -493,8 +489,7 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, ret = wolfSSL_get_ocsp_response(ssl, &response); ret = CheckOcspResponse(ocsp, response, ret, responseBuffer, status, entry, NULL, heap); - if (response != NULL) - XFREE(response, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(response, NULL, DYNAMIC_TYPE_OPENSSL); break; case SSL_TLSEXT_ERR_NOACK: ret = OCSP_LOOKUP_FAIL; @@ -538,9 +533,12 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, responseSz = ocsp->cm->ocspIOCb(ioCtx, url, urlSz, request, requestSz, &response); } - if (responseSz == WOLFSSL_CBIO_ERR_WANT_READ) { + if (responseSz == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { ret = OCSP_WANT_READ; } + else if (responseSz == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_TIMEOUT)){ + ret = HTTP_TIMEOUT; + } XFREE(request, ocsp->cm->heap, DYNAMIC_TYPE_OCSP); @@ -668,8 +666,9 @@ int CheckOcspResponder(OcspResponse *bs, DecodedCert *cert, void* vp) return ret; } -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_APACHE_HTTPD) || defined(HAVE_LIGHTY) + +/* compatibility layer OCSP functions */ +#ifdef OPENSSL_EXTRA int wolfSSL_OCSP_resp_find_status(WOLFSSL_OCSP_BASICRESP *bs, WOLFSSL_OCSP_CERTID* id, int* status, int* reason, WOLFSSL_ASN1_TIME** revtime, WOLFSSL_ASN1_TIME** thisupd, @@ -695,10 +694,17 @@ int wolfSSL_OCSP_resp_find_status(WOLFSSL_OCSP_BASICRESP *bs, if (status != NULL) *status = single->status->status; +#ifdef WOLFSSL_OCSP_PARSE_STATUS if (thisupd != NULL) *thisupd = &single->status->thisDateParsed; if (nextupd != NULL) *nextupd = &single->status->nextDateParsed; +#else + if (thisupd != NULL) + *thisupd = NULL; + if (nextupd != NULL) + *nextupd = NULL; +#endif /* TODO: Not needed for Nginx or httpd */ if (reason != NULL) @@ -821,16 +827,15 @@ WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_cert_to_id( if (ret != 0) { if (derCert != NULL) FreeDer(&derCert); - if (certId != NULL) { + if (cm != NULL) { XFREE(certId, cm->heap, DYNAMIC_TYPE_OPENSSL); certId = NULL; - } - if (certStatus) XFREE(certStatus, cm->heap, DYNAMIC_TYPE_OPENSSL); + } } #ifdef WOLFSSL_SMALL_STACK - if (cert != NULL) + if (cm != NULL) XFREE(cert, cm->heap, DYNAMIC_TYPE_DCERT); #endif @@ -850,7 +855,7 @@ void wolfSSL_OCSP_BASICRESP_free(WOLFSSL_OCSP_BASICRESP* basicResponse) int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, WOLF_STACK_OF(WOLFSSL_X509) *certs, WOLFSSL_X509_STORE *st, unsigned long flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifdef WOLFSSL_SMALL_STACK DecodedCert *cert; #else @@ -872,10 +877,8 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, return WOLFSSL_FAILURE; #endif -#ifdef OPENSSL_EXTRA if (bs->verifyError != OCSP_VERIFY_ERROR_NONE) goto out; -#endif if (flags & OCSP_TRUSTOTHER) { for (idx = 0; idx < wolfSSL_sk_X509_num(certs); idx++) { @@ -922,8 +925,7 @@ void wolfSSL_OCSP_RESPONSE_free(OcspResponse* response) XFREE(response->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); } - if (response->source != NULL) - XFREE(response->source, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(response->source, NULL, DYNAMIC_TYPE_TMP_BUFFER); XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST); } @@ -952,18 +954,18 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE_bio(WOLFSSL_BIO* bio, long fcur; long flen; - if (bio->ptr == NULL) + if (bio->ptr.fh == NULL) return NULL; - fcur = XFTELL((XFILE)bio->ptr); + fcur = XFTELL(bio->ptr.fh); if (fcur < 0) return NULL; - if(XFSEEK((XFILE)bio->ptr, 0, SEEK_END) != 0) + if(XFSEEK(bio->ptr.fh, 0, SEEK_END) != 0) return NULL; - flen = XFTELL((XFILE)bio->ptr); + flen = XFTELL(bio->ptr.fh); if (flen < 0) return NULL; - if (XFSEEK((XFILE)bio->ptr, fcur, SEEK_SET) != 0) + if (XFSEEK(bio->ptr.fh, fcur, SEEK_SET) != 0) return NULL; /* check calculated length */ @@ -1054,6 +1056,9 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE(OcspResponse** response, if (GetSequence(*data, &idx, &length, (word32)len) >= 0) (*data) += (unsigned char) ((int)idx + length); + if (response != NULL && *response == NULL) + *response = resp; + return resp; } @@ -1106,10 +1111,8 @@ WOLFSSL_OCSP_BASICRESP* wolfSSL_OCSP_response_get1_basic(OcspResponse* response) DYNAMIC_TYPE_OCSP_ENTRY); bs->source = (byte*)XMALLOC(bs->maxIdx, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (bs->single == NULL || bs->source == NULL) { - if (bs->single) { - XFREE(bs->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); - bs->single = NULL; - } + XFREE(bs->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); + bs->single = NULL; wolfSSL_OCSP_RESPONSE_free(bs); bs = NULL; } @@ -1143,6 +1146,9 @@ int wolfSSL_i2d_OCSP_REQUEST(OcspRequest* request, unsigned char** data) { int size; + if (request == NULL) + return BAD_FUNC_ARG; + size = EncodeOcspRequest(request, NULL, 0); if (size <= 0 || data == NULL) return size; @@ -1164,8 +1170,7 @@ WOLFSSL_OCSP_ONEREQ* wolfSSL_OCSP_request_add0_id(OcspRequest *req, XMEMCPY(req->issuerHash, cid->issuerHash, KEYID_SIZE); XMEMCPY(req->issuerKeyHash, cid->issuerKeyHash, KEYID_SIZE); if (cid->status->serialSz > req->serialSz) { - if (req->serial != NULL) - XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP); + XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP); req->serial = (byte*)XMALLOC((size_t)cid->status->serialSz, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); if (req->serial == NULL) @@ -1191,9 +1196,7 @@ WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_CERTID_dup(WOLFSSL_OCSP_CERTID* id) } return certId; } -#endif -#if defined(OPENSSL_ALL) || defined(APACHE_HTTPD) || defined(WOLFSSL_HAPROXY) #ifndef NO_BIO int wolfSSL_i2d_OCSP_REQUEST_bio(WOLFSSL_BIO* out, WOLFSSL_OCSP_REQUEST *req) @@ -1295,7 +1298,8 @@ WOLFSSL_OCSP_CERTID* wolfSSL_d2i_OCSP_CERTID(WOLFSSL_OCSP_CERTID** cidOut, return NULL; } -const WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_SINGLERESP_get0_id(const WOLFSSL_OCSP_SINGLERESP *single) +const WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_SINGLERESP_get0_id( + const WOLFSSL_OCSP_SINGLERESP *single) { return single; } @@ -1343,11 +1347,17 @@ int wolfSSL_OCSP_single_get0_status(WOLFSSL_OCSP_SINGLERESP *single, if (single == NULL) return WOLFSSL_FAILURE; +#ifdef WOLFSSL_OCSP_PARSE_STATUS if (thisupd != NULL) *thisupd = &single->status->thisDateParsed; if (nextupd != NULL) *nextupd = &single->status->nextDateParsed; - +#else + if (thisupd != NULL) + *thisupd = NULL; + if (nextupd != NULL) + *nextupd = NULL; +#endif if (reason != NULL) *reason = 0; if (revtime != NULL) @@ -1392,9 +1402,325 @@ WOLFSSL_OCSP_SINGLERESP* wolfSSL_OCSP_resp_get0(WOLFSSL_OCSP_BASICRESP *bs, int return single; } -#endif /* OPENSSL_ALL || APACHE_HTTPD || WOLFSSL_HAPROXY */ +#endif /* OPENSSL_EXTRA */ + +#ifdef OPENSSL_ALL + +/******************************************************************************* + * START OF WOLFSSL_OCSP_REQ_CTX API + ******************************************************************************/ + +enum ocspReqStates { + ORS_INVALID = 0, + ORS_HEADER_ADDED, + ORS_REQ_DONE +}; + +enum ocspReqIOStates { + ORIOS_INVALID = 0, + ORIOS_WRITE, + ORIOS_READ +}; + +WOLFSSL_OCSP_REQ_CTX* wolfSSL_OCSP_REQ_CTX_new(WOLFSSL_BIO *bio, int maxline) +{ + WOLFSSL_OCSP_REQ_CTX* ret = NULL; + + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_new"); + + if (maxline <= 0) + maxline = OCSP_MAX_REQUEST_SZ; + + ret = (WOLFSSL_OCSP_REQ_CTX*)XMALLOC(sizeof(*ret), NULL, + DYNAMIC_TYPE_OPENSSL); + if (ret != NULL) { + XMEMSET(ret, 0, sizeof(*ret)); + ret->buf = (byte*)XMALLOC((word32)maxline, NULL, DYNAMIC_TYPE_OPENSSL); + if (ret->buf == NULL) + goto error; + ret->reqResp = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); + ret->bufLen = maxline; + ret->bio = bio; + ret->ioState = ORIOS_WRITE; + } + + return ret; +error: + wolfSSL_OCSP_REQ_CTX_free(ret); + return NULL; +} + +void wolfSSL_OCSP_REQ_CTX_free(WOLFSSL_OCSP_REQ_CTX *ctx) +{ + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_free"); + if (ctx != NULL) { + if (ctx->buf != NULL) + XFREE(ctx->buf, NULL, DYNAMIC_TYPE_OPENSSL); + if (ctx->reqResp != NULL) + wolfSSL_BIO_free(ctx->reqResp); + XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL); + } +} + +WOLFSSL_OCSP_REQ_CTX* wolfSSL_OCSP_sendreq_new(WOLFSSL_BIO *bio, + const char *path, OcspRequest *req, int maxline) +{ + WOLFSSL_OCSP_REQ_CTX* ret = NULL; + + WOLFSSL_ENTER("wolfSSL_OCSP_sendreq_new"); + + ret = wolfSSL_OCSP_REQ_CTX_new(bio, maxline); + if (ret == NULL) + return NULL; + + if (wolfSSL_OCSP_REQ_CTX_http(ret, "POST", path) != WOLFSSL_SUCCESS) + goto error; + + if (req != NULL && + wolfSSL_OCSP_REQ_CTX_set1_req(ret, req) != WOLFSSL_SUCCESS) + goto error; + + return ret; +error: + wolfSSL_OCSP_REQ_CTX_free(ret); + return NULL; +} + +int wolfSSL_OCSP_REQ_CTX_add1_header(WOLFSSL_OCSP_REQ_CTX *ctx, + const char *name, const char *value) +{ + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_add1_header"); + + if (name == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + if (wolfSSL_BIO_puts(ctx->reqResp, name) <= 0) { + WOLFSSL_MSG("wolfSSL_BIO_puts error"); + return WOLFSSL_FAILURE; + } + if (value != NULL) { + if (wolfSSL_BIO_write(ctx->reqResp, ": ", 2) != 2) { + WOLFSSL_MSG("wolfSSL_BIO_write error"); + return WOLFSSL_FAILURE; + } + if (wolfSSL_BIO_puts(ctx->reqResp, value) <= 0) { + WOLFSSL_MSG("wolfSSL_BIO_puts error"); + return WOLFSSL_FAILURE; + } + } + if (wolfSSL_BIO_write(ctx->reqResp, "\r\n", 2) != 2) { + WOLFSSL_MSG("wolfSSL_BIO_write error"); + return WOLFSSL_FAILURE; + } + + ctx->state = ORS_HEADER_ADDED; + + return WOLFSSL_SUCCESS; +} + +int wolfSSL_OCSP_REQ_CTX_http(WOLFSSL_OCSP_REQ_CTX *ctx, const char *op, + const char *path) +{ + static const char http_hdr[] = "%s %s HTTP/1.0\r\n"; + + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_http"); + + if (ctx == NULL || op == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + if (path == NULL) + path = "/"; + + if (wolfSSL_BIO_printf(ctx->reqResp, http_hdr, op, path) <= 0) { + WOLFSSL_MSG("WOLFSSL_OCSP_REQ_CTX: wolfSSL_BIO_printf error"); + return WOLFSSL_FAILURE; + } + + ctx->state = ORS_HEADER_ADDED; + + return WOLFSSL_SUCCESS; +} + +int wolfSSL_OCSP_REQ_CTX_set1_req(WOLFSSL_OCSP_REQ_CTX *ctx, OcspRequest *req) +{ + static const char req_hdr[] = + "Content-Type: application/ocsp-request\r\n" + "Content-Length: %d\r\n\r\n"; + /* Should be enough to hold Content-Length */ + char req_hdr_buf[sizeof(req_hdr) + 10]; + int req_hdr_buf_len; + int req_len = wolfSSL_i2d_OCSP_REQUEST(req, NULL); + + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_set1_req"); + + if (ctx == NULL || req == NULL) { + WOLFSSL_MSG("Bad parameters"); + return WOLFSSL_FAILURE; + } + + if (req_len <= 0) { + WOLFSSL_MSG("wolfSSL_OCSP_REQ_CTX_set1_req: request len error"); + return WOLFSSL_FAILURE; + } + + req_hdr_buf_len = + XSNPRINTF(req_hdr_buf, sizeof(req_hdr_buf), req_hdr, req_len); + if (req_hdr_buf_len >= (int)sizeof(req_hdr_buf)) { + WOLFSSL_MSG("wolfSSL_OCSP_REQ_CTX_set1_req: request too long"); + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(ctx->reqResp, req_hdr_buf, req_hdr_buf_len) <= 0) { + WOLFSSL_MSG("wolfSSL_OCSP_REQ_CTX_set1_req: wolfSSL_BIO_write error"); + return WOLFSSL_FAILURE; + } + + if (wolfSSL_i2d_OCSP_REQUEST_bio(ctx->reqResp, req) <= 0) { + WOLFSSL_MSG("wolfSSL_OCSP_REQ_CTX_set1_req: request i2d error"); + return WOLFSSL_FAILURE; + } + + ctx->state = ORS_REQ_DONE; + + return WOLFSSL_SUCCESS; +} + +static int OCSP_REQ_CTX_bio_cb(char *buf, int sz, void *ctx) +{ + return BioReceiveInternal((WOLFSSL_BIO*)ctx, NULL, buf, sz); +} + +int wolfSSL_OCSP_REQ_CTX_nbio(WOLFSSL_OCSP_REQ_CTX *ctx) +{ + WOLFSSL_ENTER("wolfSSL_OCSP_REQ_CTX_nbio"); + + if (ctx == NULL) { + WOLFSSL_MSG("Bad parameters"); + return WOLFSSL_FAILURE; + } + + switch ((enum ocspReqIOStates)ctx->ioState) { + case ORIOS_WRITE: + case ORIOS_READ: + break; + case ORIOS_INVALID: + default: + WOLFSSL_MSG("Invalid ctx->ioState state"); + return WOLFSSL_FAILURE; + } + + if (ctx->ioState == ORIOS_WRITE) { + switch ((enum ocspReqStates)ctx->state) { + case ORS_HEADER_ADDED: + /* Write final new line to complete http header */ + if (wolfSSL_BIO_write(ctx->reqResp, "\r\n", 2) != 2) { + WOLFSSL_MSG("wolfSSL_BIO_write error"); + return WOLFSSL_FAILURE; + } + break; + case ORS_REQ_DONE: + break; + case ORS_INVALID: + default: + WOLFSSL_MSG("Invalid WOLFSSL_OCSP_REQ_CTX state"); + return WOLFSSL_FAILURE; + } + } + + switch ((enum ocspReqIOStates)ctx->ioState) { + case ORIOS_WRITE: + { + const unsigned char *req; + int reqLen = wolfSSL_BIO_get_mem_data(ctx->reqResp, &req); + if (reqLen <= 0) { + WOLFSSL_MSG("wolfSSL_BIO_get_mem_data error"); + return WOLFSSL_FAILURE; + } + while (ctx->sent < reqLen) { + int sent = wolfSSL_BIO_write(ctx->bio, req + ctx->sent, + reqLen - ctx->sent); + if (sent <= 0) { + if (wolfSSL_BIO_should_retry(ctx->bio)) + return WOLFSSL_FATAL_ERROR; + WOLFSSL_MSG("wolfSSL_BIO_write error"); + ctx->ioState = ORIOS_INVALID; + return 0; + } + ctx->sent += sent; + } + ctx->sent = 0; + ctx->ioState = ORIOS_READ; + (void)wolfSSL_BIO_reset(ctx->reqResp); + FALL_THROUGH; + } + case ORIOS_READ: + { + byte* resp = NULL; + int respLen; + int ret; + + if (ctx->buf == NULL) /* Should be allocated in new call */ + return WOLFSSL_FAILURE; + + ret = wolfIO_HttpProcessResponseOcspGenericIO(OCSP_REQ_CTX_bio_cb, + ctx->bio, &resp, ctx->buf, ctx->bufLen, NULL); + if (ret <= 0) { + if (resp != NULL) + XFREE(resp, NULL, DYNAMIC_TYPE_OCSP); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ) || + ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) + { + return WOLFSSL_FATAL_ERROR; + } + return WOLFSSL_FAILURE; + } + respLen = ret; + ret = wolfSSL_BIO_write(ctx->reqResp, resp, respLen); + XFREE(resp, NULL, DYNAMIC_TYPE_OCSP); + if (ret != respLen) { + WOLFSSL_MSG("wolfSSL_BIO_write error"); + return WOLFSSL_FAILURE; + } + break; + } + case ORIOS_INVALID: + default: + WOLFSSL_MSG("Invalid ctx->ioState state"); + return WOLFSSL_FAILURE; + } + + return WOLFSSL_SUCCESS; +} + +int wolfSSL_OCSP_sendreq_nbio(OcspResponse **presp, WOLFSSL_OCSP_REQ_CTX *ctx) +{ + int ret; + int len; + const unsigned char *resp = NULL; + + WOLFSSL_ENTER("wolfSSL_OCSP_sendreq_nbio"); + + if (presp == NULL) + return WOLFSSL_FAILURE; + + ret = wolfSSL_OCSP_REQ_CTX_nbio(ctx); + if (ret != WOLFSSL_SUCCESS) + return ret; + + len = wolfSSL_BIO_get_mem_data(ctx->reqResp, &resp); + if (len <= 0) + return WOLFSSL_FAILURE; + return wolfSSL_d2i_OCSP_RESPONSE(presp, &resp, len) != NULL + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} + +/******************************************************************************* + * END OF WOLFSSL_OCSP_REQ_CTX API + ******************************************************************************/ -#ifdef OPENSSL_EXTRA #ifndef NO_WOLFSSL_STUB int wolfSSL_OCSP_REQUEST_add_ext(OcspRequest* req, WOLFSSL_X509_EXTENSION* ext, int idx) @@ -1467,12 +1793,14 @@ int wolfSSL_OCSP_id_get0_info(WOLFSSL_ASN1_STRING **name, #if defined(WOLFSSL_QT) || defined(WOLFSSL_HAPROXY) /* Serial number starts at 0 index of ser->data */ - XMEMCPY(&ser->data[i], cid->status->serial, (size_t)cid->status->serialSz); + XMEMCPY(&ser->data[i], cid->status->serial, + (size_t)cid->status->serialSz); ser->length = cid->status->serialSz; #else ser->data[i++] = ASN_INTEGER; i += SetLength(cid->status->serialSz, ser->data + i); - XMEMCPY(&ser->data[i], cid->status->serial, (size_t)cid->status->serialSz); + XMEMCPY(&ser->data[i], cid->status->serial, + (size_t)cid->status->serialSz); ser->length = i + cid->status->serialSz; #endif @@ -1573,7 +1901,7 @@ int wolfSSL_OCSP_check_nonce(OcspRequest* req, WOLFSSL_OCSP_BASICRESP* bs) /* nonce present in req only */ if (reqNonce != NULL && rspNonce == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; /* nonces are present and equal, return 1. Extra NULL check for fixing scan-build warning. */ @@ -1585,7 +1913,8 @@ int wolfSSL_OCSP_check_nonce(OcspRequest* req, WOLFSSL_OCSP_BASICRESP* bs) /* nonces are present but not equal */ return 0; } -#endif /* OPENSSL_EXTRA */ + +#endif /* OPENSSL_ALL */ #else /* HAVE_OCSP */ diff --git a/src/src/pk.c b/src/src/pk.c index db281f6..42468bf 100644 --- a/src/src/pk.c +++ b/src/src/pk.c @@ -1,6 +1,6 @@ /* pk.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -354,7 +354,7 @@ int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, int ret = 0; int paddingSz = 0; word32 idx; - word32 cipherInfoSz; + word32 cipherInfoSz = 0; #ifdef WOLFSSL_SMALL_STACK EncryptedInfo* info = NULL; #else @@ -376,7 +376,7 @@ int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, DYNAMIC_TYPE_ENCRYPTEDINFO); if (info == NULL) { WOLFSSL_MSG("malloc failed"); - ret = 0; + ret = MEMORY_E; } } #endif @@ -397,7 +397,7 @@ int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, /* Generate a random salt. */ if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) { WOLFSSL_MSG("generate iv failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -417,7 +417,8 @@ int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, (*derSz) += (int)paddingSz; /* Encrypt DER buffer. */ - ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz, WC_MD5); + ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz, + WC_MD5); if (ret != 0) { WOLFSSL_MSG("encrypt key failed"); } @@ -1789,7 +1790,7 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) || (derSz <= 0)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -1808,7 +1809,7 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, /* Something went wrong while decoding. */ WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 " "header"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { @@ -1830,13 +1831,13 @@ int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf, WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed"); } WOLFSSL_ERROR_VERBOSE(res); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { /* Set external RSA key data from wolfCrypt key. */ if (SetRsaExternal(rsa) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { rsa->inSet = 1; @@ -2051,6 +2052,32 @@ WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, } return rsa; } + +WOLFSSL_RSA *wolfSSL_d2i_RSA_PUBKEY_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out) +{ + char* data = NULL; + int dataSz = 0; + int memAlloced = 0; + WOLFSSL_RSA* rsa = NULL; + + WOLFSSL_ENTER("wolfSSL_d2i_RSA_PUBKEY_bio"); + + if (bio == NULL) + return NULL; + + if (wolfssl_read_bio(bio, &data, &dataSz, &memAlloced) != 0) { + if (memAlloced) + XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return NULL; + } + + rsa = wolfssl_rsa_d2i(out, (const unsigned char*)data, dataSz, + WOLFSSL_RSA_LOAD_PUBLIC); + if (memAlloced) + XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + return rsa; +} #endif /* !NO_BIO */ #ifndef NO_FILESYSTEM @@ -2451,7 +2478,7 @@ int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent) /* Validate parameters. */ if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -2551,7 +2578,7 @@ int SetRsaExternal(WOLFSSL_RSA* rsa) /* Validate parameters. */ if ((rsa == NULL) || (rsa->internal == NULL)) { WOLFSSL_ERROR_MSG("rsa key NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -2571,6 +2598,7 @@ int SetRsaExternal(WOLFSSL_RSA* rsa) } if (key->type == RSA_PRIVATE) { + #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (ret == 1) { /* Copy private exponent. */ ret = wolfssl_bn_set_value(&rsa->d, &key->d); @@ -2592,7 +2620,8 @@ int SetRsaExternal(WOLFSSL_RSA* rsa) WOLFSSL_ERROR_MSG("rsa q error"); } } - #ifndef RSA_LOW_MEM + #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \ + !defined(RSA_LOW_MEM) if (ret == 1) { /* Copy d mod p-1. */ ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP); @@ -2614,7 +2643,11 @@ int SetRsaExternal(WOLFSSL_RSA* rsa) WOLFSSL_ERROR_MSG("rsa u error"); } } - #endif /* !RSA_LOW_MEM */ + #endif + #else + WOLFSSL_ERROR_MSG("rsa private key not compiled in "); + ret = 0; + #endif /* !WOLFSSL_RSA_PUBLIC_ONLY */ } } if (ret == 1) { @@ -2647,7 +2680,7 @@ int SetRsaInternal(WOLFSSL_RSA* rsa) /* Validate parameters. */ if ((rsa == NULL) || (rsa->internal == NULL)) { WOLFSSL_ERROR_MSG("rsa key NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -2656,24 +2689,25 @@ int SetRsaInternal(WOLFSSL_RSA* rsa) /* Copy down modulus if available. */ if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) { WOLFSSL_ERROR_MSG("rsa n key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy down public exponent if available. */ if ((ret == 1) && (rsa->e != NULL) && (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) { WOLFSSL_ERROR_MSG("rsa e key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Enough numbers for public key */ key->type = RSA_PUBLIC; +#ifndef WOLFSSL_RSA_PUBLIC_ONLY /* Copy down private exponent if available. */ if ((ret == 1) && (rsa->d != NULL)) { if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) { WOLFSSL_ERROR_MSG("rsa d key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { /* Enough numbers for private key */ @@ -2685,38 +2719,39 @@ int SetRsaInternal(WOLFSSL_RSA* rsa) if ((ret == 1) && (rsa->p != NULL) && (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) { WOLFSSL_ERROR_MSG("rsa p key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy down second prime if available. */ if ((ret == 1) && (rsa->q != NULL) && (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) { WOLFSSL_ERROR_MSG("rsa q key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } - #ifndef RSA_LOW_MEM +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) /* Copy down d mod p-1 if available. */ if ((ret == 1) && (rsa->dmp1 != NULL) && (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) { WOLFSSL_ERROR_MSG("rsa dP key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy down d mod q-1 if available. */ if ((ret == 1) && (rsa->dmq1 != NULL) && (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) { WOLFSSL_ERROR_MSG("rsa dQ key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy down 1/q mod p if available. */ if ((ret == 1) && (rsa->iqmp != NULL) && (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) { WOLFSSL_ERROR_MSG("rsa u key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } - #endif /* !RSA_LOW_MEM */ +#endif +#endif if (ret == 1) { /* All available numbers have been set down. */ @@ -3273,6 +3308,7 @@ static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits, #endif int initTmpRng = 0; WC_RNG* rng = NULL; + long en = 0; #endif (void)cb; @@ -3286,10 +3322,12 @@ static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits, /* Something went wrong so return memory error. */ ret = MEMORY_E; } + if ((ret == 0) && ((en = (long)wolfSSL_BN_get_word(e)) <= 0)) { + ret = BAD_FUNC_ARG; + } if (ret == 0) { /* Generate an RSA key. */ - ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits, - (long)wolfSSL_BN_get_word(e), rng); + ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits, en, rng); if (ret != MP_OKAY) { WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed"); } @@ -3493,12 +3531,15 @@ int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e, * @param [out] em Encoded message. * @param [in[ mHash Message hash. * @param [in] hashAlg Hash algorithm. + * @param [in] mgf1Hash MGF algorithm. * @param [in] saltLen Length of salt to generate. * @return 1 on success. * @return 0 on failure. */ -int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, - const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen) + +int wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, unsigned char *em, + const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, + const WOLFSSL_EVP_MD *mgf1Hash, int saltLen) { int ret = 1; enum wc_HashType hashType; @@ -3521,6 +3562,9 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, ret = 0; } + if (mgf1Hash == NULL) + mgf1Hash = hashAlg; + if (ret == 1) { /* Get/create an RNG. */ rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng); @@ -3546,7 +3590,7 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, } if (ret == 1) { /* Get the wolfCrypt MGF algorithm from hash algorithm. */ - mgf = wc_hash2mgf(hashType); + mgf = wc_hash2mgf(EvpMd2MacType(mgf1Hash)); if (mgf == WC_MGF1NONE) { WOLFSSL_ERROR_MSG("wc_hash2mgf error"); ret = 0; @@ -3617,6 +3661,13 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, return ret; } +int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, + const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen) +{ + return wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1(rsa, em, mHash, hashAlg, NULL, + saltLen); +} + /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message. * * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram. @@ -3624,14 +3675,15 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em, * @param [in] rsa RSA key. * @param [in[ mHash Message hash. * @param [in] hashAlg Hash algorithm. + * @param [in] mgf1Hash MGF algorithm. * @param [in] em Encoded message. * @param [in] saltLen Length of salt to generate. * @return 1 on success. * @return 0 on failure. */ -int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, - const WOLFSSL_EVP_MD *hashAlg, - const unsigned char *em, int saltLen) +int wolfSSL_RSA_verify_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, + const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, + const WOLFSSL_EVP_MD *mgf1Hash, const unsigned char *em, int saltLen) { int ret = 1; int hashLen = 0; @@ -3649,6 +3701,9 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, ret = 0; } + if (mgf1Hash == NULL) + mgf1Hash = hashAlg; + /* TODO: use wolfCrypt RSA key to get emLen and bits? */ /* Set the external data from the wolfCrypt RSA key if not done. */ if ((ret == 1) && (!rsa->exSet)) { @@ -3711,7 +3766,7 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, if (ret == 1) { /* Get the wolfCrypt MGF algorithm from hash algorithm. */ - if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) { + if ((mgf = wc_hash2mgf(EvpMd2MacType(mgf1Hash))) == WC_MGF1NONE) { WOLFSSL_ERROR_MSG("wc_hash2mgf error"); ret = 0; } @@ -3754,6 +3809,14 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; } + +int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, + const WOLFSSL_EVP_MD *hashAlg, + const unsigned char *em, int saltLen) +{ + return wolfSSL_RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, hashAlg, NULL, em, + saltLen); +} #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */ #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || * WOLFSSL_NGINX) */ @@ -4235,7 +4298,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) || (from == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4256,7 +4319,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, default: WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding " "scheme"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #else /* Check for supported padding schemes in FIPS. */ @@ -4264,14 +4327,14 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, if (padding != RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in " "FIPS"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #endif } /* Set wolfCrypt RSA key data from external if not already done. */ if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4279,7 +4342,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, outLen = wolfSSL_RSA_size(rsa); if (outLen == 0) { WOLFSSL_ERROR_MSG("Bad RSA size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4287,7 +4350,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, /* Get an RNG. */ rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng); if (rng == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4313,7 +4376,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, /* wolfCrypt error means return -1. */ if (ret <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret); return ret; @@ -4348,7 +4411,7 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) || (from == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4367,7 +4430,7 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, break; default: WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #else /* Check for supported padding schemes in FIPS. */ @@ -4375,14 +4438,14 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, if (padding != RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in " "FIPS"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #endif } /* Set wolfCrypt RSA key data from external if not already done. */ if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4390,7 +4453,7 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, outLen = wolfSSL_RSA_size(rsa); if (outLen == 0) { WOLFSSL_ERROR_MSG("Bad RSA size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4408,7 +4471,7 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, /* wolfCrypt error means return -1. */ if (ret <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret); return ret; @@ -4439,7 +4502,7 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) || (from == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4454,20 +4517,20 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, /* TODO: RSA_X931_PADDING not supported */ default: WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #else if (padding != RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in " "FIPS"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #endif } /* Set wolfCrypt RSA key data from external if not already done. */ if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4475,7 +4538,7 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, outLen = wolfSSL_RSA_size(rsa); if (outLen == 0) { WOLFSSL_ERROR_MSG("Bad RSA size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4494,7 +4557,7 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, /* wolfCrypt error means return -1. */ if (ret <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret); return ret; @@ -4531,7 +4594,7 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) || (from == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { @@ -4544,20 +4607,20 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, /* TODO: RSA_X931_PADDING not supported */ default: WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* Set wolfCrypt RSA key data from external if not already done. */ if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { /* Get an RNG. */ rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng); if (rng == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4590,7 +4653,7 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, /* wolfCrypt error means return -1. */ if (ret <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret); return ret; @@ -4625,7 +4688,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) || (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) { WOLFSSL_ERROR_MSG("rsa no init error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_SMALL_STACK @@ -4634,7 +4697,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { WOLFSSL_ERROR_MSG("Memory allocation failure"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #endif @@ -4643,7 +4706,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) /* Initialize temp MP integer. */ if (mp_init(tmp) != MP_OKAY) { WOLFSSL_ERROR_MSG("mp_init error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -4654,7 +4717,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp); if (err != MP_OKAY) { WOLFSSL_ERROR_MSG("mp_sub_d error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { @@ -4663,7 +4726,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) (mp_int*)rsa->dmp1->internal); if (err != MP_OKAY) { WOLFSSL_ERROR_MSG("mp_mod error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { @@ -4671,7 +4734,7 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp); if (err != MP_OKAY) { WOLFSSL_ERROR_MSG("mp_sub_d error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { @@ -4680,15 +4743,16 @@ int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa) (mp_int*)rsa->dmq1->internal); if (err != MP_OKAY) { WOLFSSL_ERROR_MSG("mp_mod error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } mp_clear(t); #ifdef WOLFSSL_SMALL_STACK - if (tmp != NULL) + if (rsa != NULL) { XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER); + } #endif return ret; @@ -4861,34 +4925,34 @@ int SetDsaExternal(WOLFSSL_DSA* dsa) if (dsa == NULL || dsa->internal == NULL) { WOLFSSL_MSG("dsa key NULL error"); - return -1; + return WOLFSSL_FATAL_ERROR; } key = (DsaKey*)dsa->internal; if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) { WOLFSSL_MSG("dsa p key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) { WOLFSSL_MSG("dsa q key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) { WOLFSSL_MSG("dsa g key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) { WOLFSSL_MSG("dsa y key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) { WOLFSSL_MSG("dsa x key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } dsa->exSet = 1; @@ -4906,7 +4970,7 @@ int SetDsaInternal(WOLFSSL_DSA* dsa) if (dsa == NULL || dsa->internal == NULL) { WOLFSSL_MSG("dsa key NULL error"); - return -1; + return WOLFSSL_FATAL_ERROR; } key = (DsaKey*)dsa->internal; @@ -4914,25 +4978,25 @@ int SetDsaInternal(WOLFSSL_DSA* dsa) if (dsa->p != NULL && wolfssl_bn_get_value(dsa->p, &key->p) != 1) { WOLFSSL_MSG("rsa p key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (dsa->q != NULL && wolfssl_bn_get_value(dsa->q, &key->q) != 1) { WOLFSSL_MSG("rsa q key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (dsa->g != NULL && wolfssl_bn_get_value(dsa->g, &key->g) != 1) { WOLFSSL_MSG("rsa g key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (dsa->pub_key != NULL) { if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) { WOLFSSL_MSG("rsa pub_key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } /* public key */ @@ -4942,7 +5006,7 @@ int SetDsaInternal(WOLFSSL_DSA* dsa) if (dsa->priv_key != NULL) { if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) { WOLFSSL_MSG("rsa priv_key error"); - return -1; + return WOLFSSL_FATAL_ERROR; } /* private key */ @@ -4990,7 +5054,7 @@ int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa) #ifdef WOLFSSL_SMALL_STACK tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); if (tmpRng == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; #endif if (wc_InitRng(tmpRng) == 0) { rng = tmpRng; @@ -5094,7 +5158,7 @@ int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits, #ifdef WOLFSSL_SMALL_STACK tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); if (tmpRng == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; #endif if (wc_InitRng(tmpRng) == 0) { rng = tmpRng; @@ -5266,20 +5330,20 @@ int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out) if (sig == NULL || sig->r == NULL || sig->s == NULL || out == NULL) { WOLFSSL_MSG("Bad function arguments"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (StoreECC_DSA_Sig(buf, &bufLen, (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) { WOLFSSL_MSG("StoreECC_DSA_Sig error"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out == NULL) { byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1); if (tmp == NULL) { WOLFSSL_MSG("malloc error"); - return -1; + return WOLFSSL_FATAL_ERROR; } *out = tmp; } @@ -5403,13 +5467,13 @@ WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig, return ret; } -#endif /* HAVE_SELFTEST */ -/* return 1 on success, < 0 otherwise */ -int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet, - WOLFSSL_DSA* dsa) +#endif /* !HAVE_SELFTEST */ + +static int dsa_do_sign(const unsigned char* d, int dLen, unsigned char* sigRet, + WOLFSSL_DSA* dsa) { - int ret = -1; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); int initTmpRng = 0; WC_RNG* rng = NULL; #ifdef WOLFSSL_SMALL_STACK @@ -5418,25 +5482,23 @@ int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet, WC_RNG tmpRng[1]; #endif - WOLFSSL_ENTER("wolfSSL_DSA_do_sign"); - if (d == NULL || sigRet == NULL || dsa == NULL) { WOLFSSL_MSG("Bad function arguments"); - return ret; + return WOLFSSL_FATAL_ERROR; } if (dsa->inSet == 0) { WOLFSSL_MSG("No DSA internal set, do it"); if (SetDsaInternal(dsa) != 1) { WOLFSSL_MSG("SetDsaInternal failed"); - return ret; + return WOLFSSL_FATAL_ERROR; } } #ifdef WOLFSSL_SMALL_STACK tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); if (tmpRng == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; #endif if (wc_InitRng(tmpRng) == 0) { @@ -5445,14 +5507,30 @@ int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet, } else { WOLFSSL_MSG("Bad RNG Init, trying global"); +#ifdef WOLFSSL_SMALL_STACK + XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG); + tmpRng = NULL; +#endif rng = wolfssl_get_global_rng(); + if (! rng) + return WOLFSSL_FATAL_ERROR; } if (rng) { - if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0) - WOLFSSL_MSG("DsaSign failed"); +#ifdef HAVE_SELFTEST + if (dLen != WC_SHA_DIGEST_SIZE || + wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0) { + WOLFSSL_MSG("wc_DsaSign failed or dLen wrong length"); + ret = WOLFSSL_FATAL_ERROR; + } +#else + if (wc_DsaSign_ex(d, dLen, sigRet, (DsaKey*)dsa->internal, rng) < 0) { + WOLFSSL_MSG("wc_DsaSign_ex failed"); + ret = WOLFSSL_FATAL_ERROR; + } +#endif else - ret = 1; + ret = WOLFSSL_SUCCESS; } if (initTmpRng) @@ -5464,6 +5542,15 @@ int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet, return ret; } +/* return 1 on success, < 0 otherwise */ +int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet, + WOLFSSL_DSA* dsa) +{ + WOLFSSL_ENTER("wolfSSL_DSA_do_sign"); + + return dsa_do_sign(d, WC_SHA_DIGEST_SIZE, sigRet, dsa); +} + #ifndef HAVE_SELFTEST WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest, int inLen, WOLFSSL_DSA* dsa) @@ -5474,12 +5561,12 @@ WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest, WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex"); - if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) { + if (!digest || !dsa) { WOLFSSL_MSG("Bad function arguments"); return NULL; } - if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) { + if (dsa_do_sign(digest, inLen, sigBin, dsa) != 1) { WOLFSSL_MSG("wolfSSL_DSA_do_sign error"); return NULL; } @@ -5498,18 +5585,16 @@ WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest, /* 2 * sigLen for the two points r and s */ return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen); } -#endif /* !HAVE_SELFTEST */ +#endif -int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig, +static int dsa_do_verify(const unsigned char* d, int dLen, unsigned char* sig, WOLFSSL_DSA* dsa, int *dsacheck) { - int ret = -1; - - WOLFSSL_ENTER("wolfSSL_DSA_do_verify"); + int ret; if (d == NULL || sig == NULL || dsa == NULL) { WOLFSSL_MSG("Bad function arguments"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (dsa->inSet == 0) { @@ -5517,17 +5602,34 @@ int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig, if (SetDsaInternal(dsa) != 1) { WOLFSSL_MSG("SetDsaInternal failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } } - ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck); - if (ret != 0 || *dsacheck != 1) { +#ifdef HAVE_SELFTEST + ret = dLen == WC_SHA_DIGEST_SIZE ? + wc_DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck) : BAD_FUNC_ARG; +#else + ret = wc_DsaVerify_ex(d, dLen, sig, (DsaKey*)dsa->internal, dsacheck); +#endif + if (ret != 0) { WOLFSSL_MSG("DsaVerify failed"); - return ret; + return WOLFSSL_FATAL_ERROR; + } + if (*dsacheck != 1) { + WOLFSSL_MSG("DsaVerify sig failed"); + return WOLFSSL_FAILURE; } - return 1; + return WOLFSSL_SUCCESS; +} + +int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig, + WOLFSSL_DSA* dsa, int *dsacheck) +{ + WOLFSSL_ENTER("wolfSSL_DSA_do_verify"); + + return dsa_do_verify(d, WC_SHA_DIGEST_SIZE, sig, dsa, dsacheck); } @@ -5552,7 +5654,7 @@ int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len, WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex"); - if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) { + if (!digest || !sig || !dsa) { WOLFSSL_MSG("Bad function arguments"); return 0; } @@ -5604,14 +5706,14 @@ int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len, if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1) return 0; - if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck) + if ((dsa_do_verify(digest, digest_len, sigBin, dsa, &dsacheck) != 1) || dsacheck != 1) { return 0; } return 1; } -#endif /* !HAVE_SELFTEST */ +#endif int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa, unsigned char** out) @@ -5910,8 +6012,7 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, if (tmp == NULL) { WOLFSSL_MSG("malloc failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); - if (cipherInfo != NULL) - XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); + XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); return 0; } @@ -5922,13 +6023,11 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, WOLFSSL_MSG("wc_DerToPemEx failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); XFREE(tmp, NULL, DYNAMIC_TYPE_PEM); - if (cipherInfo != NULL) - XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); + XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); return 0; } XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); - if (cipherInfo != NULL) - XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); + XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING); *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY); if (*pem == NULL) { @@ -6104,19 +6203,19 @@ int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) { WOLFSSL_MSG("Bad function arguments"); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, (word32)derSz); if (ret < 0) { WOLFSSL_MSG("DsaPrivateKeyDecode failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (SetDsaExternal(dsa) != 1) { WOLFSSL_MSG("SetDsaExternal failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } dsa->inSet = 1; @@ -6136,7 +6235,7 @@ int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf, if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) { WOLFSSL_MSG("Bad function arguments"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (opt == WOLFSSL_DSA_LOAD_PRIVATE) { @@ -6151,17 +6250,17 @@ int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf, if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) { WOLFSSL_ERROR_VERBOSE(ret); WOLFSSL_MSG("DsaPrivateKeyDecode failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) { WOLFSSL_ERROR_VERBOSE(ret); WOLFSSL_MSG("DsaPublicKeyDecode failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (SetDsaExternal(dsa) != 1) { WOLFSSL_MSG("SetDsaExternal failed"); - return -1; + return WOLFSSL_FATAL_ERROR; } dsa->inSet = 1; @@ -7279,7 +7378,7 @@ WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn) #ifndef NO_CERTS -/* Load the DER encoded DH parameters/key into DH key. +/* Load the DER encoded DH parameters into DH key. * * @param [in, out] dh DH key to load parameters into. * @param [in] der Buffer holding DER encoded parameters data. @@ -7290,7 +7389,7 @@ WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn) * @return 0 on success. * @return 1 when decoding DER or setting the external key fails. */ -static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der, +static int wolfssl_dh_load_params(WOLFSSL_DH* dh, const unsigned char* der, word32* idx, word32 derSz) { int err = 0; @@ -7403,7 +7502,7 @@ WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp, WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed"); err = 1; } - if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx, + if ((!err) && (wolfssl_dh_load_params(newDh, *pp, &idx, (word32)length) != 0)) { WOLFSSL_ERROR_MSG("Loading DH parameters failed"); err = 1; @@ -7560,13 +7659,13 @@ int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz) if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) || (derSz <= 0)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } - if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx, + if ((ret == 1) && (wolfssl_dh_load_params(dh, derBuf, &idx, (word32)derSz) != 0)) { WOLFSSL_ERROR_MSG("DH key decode failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } return ret; @@ -7754,7 +7853,7 @@ WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh, static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out, void* heap) { - int ret = -1; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); int err = 0; byte* der = NULL; word32 derSz; @@ -7798,9 +7897,7 @@ static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out, *out = der; der = NULL; } - if (der != NULL) { - XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -7885,7 +7982,7 @@ int SetDhExternal_ex(WOLFSSL_DH *dh, int elm) /* Validate parameters. */ if ((dh == NULL) || (dh->internal == NULL)) { WOLFSSL_ERROR_MSG("dh key NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -7897,21 +7994,21 @@ int SetDhExternal_ex(WOLFSSL_DH *dh, int elm) /* Set the prime. */ if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) { WOLFSSL_ERROR_MSG("dh param p error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if ((ret == 1) && (elm & ELEMENT_G)) { /* Set the generator. */ if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) { WOLFSSL_ERROR_MSG("dh param g error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if ((ret == 1) && (elm & ELEMENT_Q)) { /* Set the order. */ if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) { WOLFSSL_ERROR_MSG("dh param q error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #ifdef WOLFSSL_DH_EXTRA @@ -7919,14 +8016,14 @@ int SetDhExternal_ex(WOLFSSL_DH *dh, int elm) /* Set the private key. */ if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) { WOLFSSL_ERROR_MSG("No DH Private Key"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if ((ret == 1) && (elm & ELEMENT_PUB)) { /* Set the public key. */ if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) { WOLFSSL_ERROR_MSG("No DH Public Key"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #endif /* WOLFSSL_DH_EXTRA */ @@ -7971,7 +8068,7 @@ int SetDhInternal(WOLFSSL_DH* dh) /* Validate parameters. */ if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { /* Get the wolfSSL DH key. */ @@ -7980,26 +8077,26 @@ int SetDhInternal(WOLFSSL_DH* dh) /* Clear out key and initialize. */ wc_FreeDhKey(key); if (wc_InitDhKey(key) != 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { /* Transfer prime. */ if (wolfssl_bn_get_value(dh->p, &key->p) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 1) { /* Transfer generator. */ if (wolfssl_bn_get_value(dh->g, &key->g) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #ifdef HAVE_FFDHE_Q /* Transfer order if available. */ if ((ret == 1) && (dh->q != NULL)) { if (wolfssl_bn_get_value(dh->q, &key->q) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #endif @@ -8008,14 +8105,14 @@ int SetDhInternal(WOLFSSL_DH* dh) if ((ret == 1) && (dh->priv_key != NULL) && (!wolfSSL_BN_is_zero(dh->priv_key))) { if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* Transfer public key if available. */ if ((ret == 1) && (dh->pub_key != NULL) && (!wolfSSL_BN_is_zero(dh->pub_key))) { if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #endif /* WOLFSSL_DH_EXTRA */ @@ -8038,17 +8135,14 @@ int SetDhInternal(WOLFSSL_DH* dh) */ int wolfSSL_DH_size(WOLFSSL_DH* dh) { - int ret = -1; - WOLFSSL_ENTER("wolfSSL_DH_size"); - /* Validate parameter. */ - if (dh != NULL) { - /* Size of key is size of prime in bytes. */ - ret = wolfSSL_BN_num_bytes(dh->p); - } + if (dh == NULL) + return WOLFSSL_FATAL_ERROR; - return ret; + /* Validate parameter. */ + /* Size of key is size of prime in bytes. */ + return wolfSSL_BN_num_bytes(dh->p); } /** @@ -8575,6 +8669,10 @@ int wolfSSL_DH_generate_key(WOLFSSL_DH* dh) /* Private key size can be as much as the size of the prime. */ if (dh->length) { privSz = (word32)(dh->length / 8); /* to bytes */ + /* Special case where priv key is larger than dh->length / 8 + * See GeneratePrivateDh */ + if (dh->length == 128) + privSz = 21; } else { privSz = pubSz; @@ -8641,20 +8739,8 @@ int wolfSSL_DH_generate_key(WOLFSSL_DH* dh) } -/* Compute the shared key from the private key and peer's public key. - * - * Return code compliant with OpenSSL. - * OpenSSL returns 0 when number of bits in p are smaller than minimum - * supported. - * - * @param [out] key Buffer to place shared key. - * @param [in] otherPub Peer's public key. - * @param [in] dh DH key containing private key. - * @return -1 on error. - * @return Size of shared secret in bytes on success. - */ -int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, - WOLFSSL_DH* dh) +static int _DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, + WOLFSSL_DH* dh, int ct) { int ret = 0; word32 keySz = 0; @@ -8674,19 +8760,19 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, /* Validate parameters. */ if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) { WOLFSSL_ERROR_MSG("Bad function arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Get the maximum size of computed DH key. */ if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) { WOLFSSL_ERROR_MSG("Bad DH_size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { /* Validate the size of the private key. */ sz = wolfSSL_BN_num_bytes(dh->priv_key); if (sz > (int)privSz) { WOLFSSL_ERROR_MSG("Bad priv internal size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { @@ -8699,7 +8785,7 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, sz = wolfSSL_BN_num_bytes(otherPub); if (sz > pubSz) { WOLFSSL_ERROR_MSG("Bad otherPub size"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -8709,14 +8795,14 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, pub = (unsigned char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); if (pub == NULL) - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { /* Allocate memory for the private key array. */ priv = (unsigned char*)XMALLOC((size_t)privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY); if (priv == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { @@ -8724,28 +8810,58 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, /* Get the private key into the array. */ privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv); if (privSz <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { /* Get the public key into the array. */ pubSz = wolfSSL_BN_bn2bin(otherPub, pub); if (pubSz <= 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* Synchronize the external into the internal parameters. */ if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) { WOLFSSL_ERROR_MSG("Bad DH set internal"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } PRIVATE_KEY_UNLOCK(); /* Calculate shared secret from private and public keys. */ - if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv, - (word32)privSz, pub, (word32)pubSz) < 0)) { - WOLFSSL_ERROR_MSG("wc_DhAgree failed"); - ret = -1; + if (ret == 0) { + word32 padded_keySz = keySz; +#if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(7,0)) && !defined(HAVE_SELFTEST) + if (ct) { + if (wc_DhAgree_ct((DhKey*)dh->internal, key, &keySz, priv, + (word32)privSz, pub, (word32)pubSz) < 0) { + WOLFSSL_ERROR_MSG("wc_DhAgree_ct failed"); + ret = WOLFSSL_FATAL_ERROR; + } + } + else +#endif /* (!HAVE_FIPS || FIPS_VERSION_GE(7,0)) && !HAVE_SELFTEST */ + { + if (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv, + (word32)privSz, pub, (word32)pubSz) < 0) { + WOLFSSL_ERROR_MSG("wc_DhAgree failed"); + ret = WOLFSSL_FATAL_ERROR; + } + } + + if ((ret == 0) && ct) { + /* Arrange for correct fixed-length, right-justified key, even if + * the crypto back end doesn't support it. With some crypto back + * ends this forgoes formal constant-timeness on the key agreement, + * but assured that wolfSSL_DH_compute_key_padded() functions + * correctly. + */ + if (keySz < padded_keySz) { + XMEMMOVE(key, key + (padded_keySz - keySz), + padded_keySz - keySz); + XMEMSET(key, 0, padded_keySz - keySz); + keySz = padded_keySz; + } + } } if (ret == 0) { /* Return actual length. */ @@ -8769,6 +8885,45 @@ int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, return ret; } + +/* Compute the shared key from the private key and peer's public key. + * + * Return code compliant with OpenSSL. + * OpenSSL returns 0 when number of bits in p are smaller than minimum + * supported. + * + * @param [out] key Buffer to place shared key. + * @param [in] otherPub Peer's public key. + * @param [in] dh DH key containing private key. + * @return -1 on error. + * @return Size of shared secret in bytes on success. + */ +int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, + WOLFSSL_DH* dh) +{ + return _DH_compute_key(key, otherPub, dh, 0); +} + +/* Compute the shared key from the private key and peer's public key as in + * wolfSSL_DH_compute_key, but using constant time processing, with an output + * key length fixed at the nominal DH key size. Leading zeros are retained. + * + * Return code compliant with OpenSSL. + * OpenSSL returns 0 when number of bits in p are smaller than minimum + * supported. + * + * @param [out] key Buffer to place shared key. + * @param [in] otherPub Peer's public key. + * @param [in] dh DH key containing private key. + * @return -1 on error. + * @return Size of shared secret in bytes on success. + */ +int wolfSSL_DH_compute_key_padded(unsigned char* key, + const WOLFSSL_BIGNUM* otherPub, WOLFSSL_DH* dh) +{ + return _DH_compute_key(key, otherPub, dh, 1); +} + #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) || * HAVE_FIPS_VERSION > 2 */ @@ -8956,7 +9111,7 @@ int EccEnumToNID(int n) #endif default: WOLFSSL_MSG("NID not found"); - return -1; + return WOLFSSL_FATAL_ERROR; } } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ @@ -8972,8 +9127,7 @@ int EccEnumToNID(int n) */ int NIDToEccEnum(int nid) { - /* -1 on error. */ - int id = -1; + int id; WOLFSSL_ENTER("NIDToEccEnum"); @@ -9061,6 +9215,8 @@ int NIDToEccEnum(int nid) break; default: WOLFSSL_MSG("NID not found"); + /* -1 on error. */ + id = WOLFSSL_FATAL_ERROR; } return id; @@ -9172,13 +9328,19 @@ void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group) * @return NULL on error. */ static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group, - const unsigned char* in, long inSz) + const unsigned char** in_pp, long inSz) { int err = 0; WOLFSSL_EC_GROUP* ret = NULL; word32 idx = 0; word32 oid = 0; int id = 0; + const unsigned char* in; + + if (in_pp == NULL || *in_pp == NULL) + return NULL; + + in = *in_pp; /* Use the group passed in. */ if ((group != NULL) && (*group != NULL)) { @@ -9227,6 +9389,9 @@ static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group, } ret = NULL; } + else { + *in_pp += idx; + } return ret; } @@ -9258,7 +9423,8 @@ WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio, } if (!err) { /* Create EC group from DER encoding. */ - ret = wolfssl_ec_group_d2i(group, der->buffer, der->length); + const byte** p = (const byte**)&der->buffer; + ret = wolfssl_ec_group_d2i(group, p, der->length); if (ret == NULL) { WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP"); } @@ -9269,6 +9435,52 @@ WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio, return ret; } +WOLFSSL_EC_GROUP *wolfSSL_d2i_ECPKParameters(WOLFSSL_EC_GROUP **out, + const unsigned char **in, long len) +{ + return wolfssl_ec_group_d2i(out, in, len); +} + +int wolfSSL_i2d_ECPKParameters(const WOLFSSL_EC_GROUP* grp, unsigned char** pp) +{ + unsigned char* out = NULL; + int len = 0; + int idx; + const byte* oid = NULL; + word32 oidSz = 0; + + if (grp == NULL || !wc_ecc_is_valid_idx(grp->curve_idx) || + grp->curve_idx < 0) + return WOLFSSL_FATAL_ERROR; + + /* Get the actual DER encoding of the OID. ecc_sets[grp->curve_idx].oid + * is just the numerical representation. */ + if (wc_ecc_get_oid(grp->curve_oid, &oid, &oidSz) < 0) + return WOLFSSL_FATAL_ERROR; + + len = SetObjectId(oidSz, NULL) + oidSz; + + if (pp == NULL) + return len; + + if (*pp == NULL) { + out = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + if (out == NULL) + return WOLFSSL_FATAL_ERROR; + } + else { + out = *pp; + } + + idx = SetObjectId(oidSz, out); + XMEMCPY(out + idx, oid, oidSz); + if (*pp == NULL) + *pp = out; + else + *pp += len; + + return len; +} #endif /* !NO_BIO */ #if defined(OPENSSL_ALL) && !defined(NO_CERTS) @@ -9337,7 +9549,7 @@ int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b, if ((a == NULL) || (b == NULL)) { WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments"); /* Return error value. */ - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Compare NID and wolfSSL curve index. */ else { @@ -9488,7 +9700,7 @@ int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group) /* Validate parameter. */ if ((group == NULL) || (group->curve_idx < 0)) { WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_SMALL_STACK @@ -9497,7 +9709,7 @@ int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group) order = (mp_int *)XMALLOC(sizeof(*order), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (order == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } #endif @@ -9559,6 +9771,12 @@ int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group, ret = 0; } + if (ret == 1 && + (group->curve_idx < 0 || !wc_ecc_is_valid_idx(group->curve_idx))) { + WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order Bad group idx"); + ret = 0; + } + if (ret == 1) { mp = (mp_int*)order->internal; } @@ -9604,7 +9822,7 @@ static int ec_point_internal_set(WOLFSSL_EC_POINT *p) /* Validate parameter. */ if ((p == NULL) || (p->internal == NULL)) { WOLFSSL_MSG("ECPoint NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { /* Get internal point as a wolfCrypt EC point. */ @@ -9613,19 +9831,19 @@ static int ec_point_internal_set(WOLFSSL_EC_POINT *p) /* Set X ordinate if available. */ if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) { WOLFSSL_MSG("ecc point X error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Set Y ordinate if available. */ if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y, point->y) != 1)) { WOLFSSL_MSG("ecc point Y error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Set Z ordinate if available. */ if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z, point->z) != 1)) { WOLFSSL_MSG("ecc point Z error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Internal values set when operations succeeded. */ p->inSet = (ret == 1); @@ -9651,7 +9869,7 @@ static int ec_point_external_set(WOLFSSL_EC_POINT *p) /* Validate parameter. */ if ((p == NULL) || (p->internal == NULL)) { WOLFSSL_MSG("ECPoint NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { /* Get internal point as a wolfCrypt EC point. */ @@ -9660,17 +9878,17 @@ static int ec_point_external_set(WOLFSSL_EC_POINT *p) /* Set X ordinate. */ if (wolfssl_bn_set_value(&p->X, point->x) != 1) { WOLFSSL_MSG("ecc point X error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Set Y ordinate. */ if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) { WOLFSSL_MSG("ecc point Y error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Set Z ordinate. */ if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) { WOLFSSL_MSG("ecc point Z error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* External values set when operations succeeded. */ p->exSet = (ret == 1); @@ -10316,7 +10534,7 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, /* Check return. When buf is NULL, return will be length only * error. */ - if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) { + if (ret != ((buf != NULL) ? MP_OKAY : WC_NO_ERR_TRACE(LENGTH_ONLY_E))) { err = 1; } } @@ -11350,43 +11568,43 @@ static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group, /* Check that the big numbers were allocated. */ if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) || (mod == NULL)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Get the modulus for the curve. */ if ((ret == 0) && (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 0) { /* bt = Bx * (Az ^ 2). When Az is one then just copy. */ if (BN_is_one(a->Z)) { if (BN_copy(bt, b->X) == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* az = Az ^ 2 */ else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* bt = Bx * az = Bx * (Az ^ 2) */ else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */ if (BN_is_one(b->Z)) { if (BN_copy(at, a->X) == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* bz = Bz ^ 2 */ else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* at = Ax * bz = Ax * (Bz ^ 2) */ else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* Compare x-ordinates. */ @@ -11397,32 +11615,32 @@ static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group, /* bt = By * (Az ^ 3). When Az is one then just copy. */ if (BN_is_one(a->Z)) { if (BN_copy(bt, b->Y) == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* az = az * Az = Az ^ 3 */ else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* bt = By * az = By * (Az ^ 3) */ else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */ if (BN_is_one(b->Z)) { if (BN_copy(at, a->Y) == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* bz = bz * Bz = Bz ^ 3 */ else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* at = Ay * bz = Ay * (Bz ^ 3) */ else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } /* Compare y-ordinates. */ @@ -11462,7 +11680,7 @@ int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group, if ((group == NULL) || (a == NULL) || (a->internal == NULL) || (b == NULL) || (b->internal == NULL)) { WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret != -1) { #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN @@ -12239,11 +12457,11 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) || (derSz <= 0)) { WOLFSSL_MSG("Bad function arguments"); - res = -1; + res = WOLFSSL_FATAL_ERROR; } if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) && (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) { - res = -1; + res = WOLFSSL_FATAL_ERROR; } if (res == 1) { @@ -12262,7 +12480,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, /* Error out on parsing error. */ else if (ret != WC_NO_ERR_TRACE(ASN_PARSE_E)) { WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header"); - res = -1; + res = WOLFSSL_FATAL_ERROR; } } @@ -12279,7 +12497,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key), ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC); if (tmp == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { /* We now try again as x.963 [point type][x][opt y]. */ @@ -12311,7 +12529,7 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, else { WOLFSSL_MSG("wc_EccPublicKeyDecode failed"); } - res = -1; + res = WOLFSSL_FATAL_ERROR; } /* Internal key updated - update whether it is a valid key. */ @@ -12321,12 +12539,62 @@ int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf, /* Set the external EC key based on value in internal. */ if ((res == 1) && (SetECKeyExternal(key) != 1)) { WOLFSSL_MSG("SetECKeyExternal failed"); - res = -1; + res = WOLFSSL_FATAL_ERROR; } return res; } + +#ifndef NO_BIO + +WOLFSSL_EC_KEY *wolfSSL_d2i_EC_PUBKEY_bio(WOLFSSL_BIO *bio, + WOLFSSL_EC_KEY **out) +{ + char* data = NULL; + int dataSz = 0; + int memAlloced = 0; + WOLFSSL_EC_KEY* ec = NULL; + int err = 0; + + WOLFSSL_ENTER("wolfSSL_d2i_EC_PUBKEY_bio"); + + if (bio == NULL) + return NULL; + + if (err == 0 && wolfssl_read_bio(bio, &data, &dataSz, &memAlloced) != 0) { + WOLFSSL_ERROR_MSG("wolfssl_read_bio failed"); + err = 1; + } + + if (err == 0 && (ec = wolfSSL_EC_KEY_new()) == NULL) { + WOLFSSL_ERROR_MSG("wolfSSL_EC_KEY_new failed"); + err = 1; + } + + /* Load the EC key with the public key from the DER encoding. */ + if (err == 0 && wolfSSL_EC_KEY_LoadDer_ex(ec, (const unsigned char*)data, + dataSz, WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1) { + WOLFSSL_ERROR_MSG("wolfSSL_EC_KEY_LoadDer_ex failed"); + err = 1; + } + + if (memAlloced) + XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (err) { /* on error */ + wolfSSL_EC_KEY_free(ec); + ec = NULL; + } + else { /* on success */ + if (out != NULL) + *out = ec; + } + + return ec; +} + +#endif /* !NO_BIO */ + /* * EC key PEM APIs */ @@ -12915,7 +13183,7 @@ int SetECKeyExternal(WOLFSSL_EC_KEY* eckey) /* Validate parameter. */ if ((eckey == NULL) || (eckey->internal == NULL)) { WOLFSSL_MSG("ec key NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { ecc_key* key = (ecc_key*)eckey->internal; @@ -12930,13 +13198,13 @@ int SetECKeyExternal(WOLFSSL_EC_KEY* eckey) if (wc_ecc_copy_point(&key->pubkey, (ecc_point*)eckey->pub_key->internal) != MP_OKAY) { WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Set external public key from internal wolfCrypt, public key. */ if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) { WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -12945,7 +13213,7 @@ int SetECKeyExternal(WOLFSSL_EC_KEY* eckey) (wolfssl_bn_set_value(&eckey->priv_key, wc_ecc_key_get_priv(key)) != 1)) { WOLFSSL_MSG("ec priv key error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* External values set when operations succeeded. */ @@ -12973,7 +13241,7 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) if ((eckey == NULL) || (eckey->internal == NULL) || (eckey->group == NULL)) { WOLFSSL_MSG("ec key NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { ecc_key* key = (ecc_key*)eckey->internal; @@ -12983,7 +13251,7 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) if ((eckey->group->curve_idx < 0) || (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) { WOLFSSL_MSG("invalid curve idx"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -12996,14 +13264,14 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) if ((ret == 1) && pubSet) { if (ec_point_internal_set(eckey->pub_key) != 1) { WOLFSSL_MSG("ec key pub error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy public point to key. */ if ((ret == 1) && (wc_ecc_copy_point( (ecc_point*)eckey->pub_key->internal, &key->pubkey) != MP_OKAY)) { WOLFSSL_MSG("wc_ecc_copy_point error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (ret == 1) { @@ -13017,7 +13285,7 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) if (wolfssl_bn_get_value(eckey->priv_key, wc_ecc_key_get_priv(key)) != 1) { WOLFSSL_MSG("ec key priv error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* private key */ if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) { @@ -13045,13 +13313,9 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) */ point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key) { - int ret = -1; - - if (key != NULL) { - ret = key->form; - } - - return ret; + if (key == NULL) + return WOLFSSL_FATAL_ERROR; + return key->form; } /* Set point conversion format into EC key. @@ -13902,7 +14166,7 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, if ((dgst == NULL) || (sig == NULL) || (key == NULL) || (key->internal == NULL)) { WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Ensure internal EC key is set from external. */ @@ -13911,7 +14175,7 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, if (SetECKeyInternal(key) != 1) { WOLFSSL_MSG("SetECKeyInternal failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -13922,7 +14186,7 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified, (ecc_key *)key->internal) != MP_OKAY) { WOLFSSL_MSG("wc_ecc_verify_hash failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else if (verified == 0) { WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected"); @@ -13936,7 +14200,7 @@ int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen, (word32)dLen, &verified, (ecc_key*)key->internal); if (ret != MP_OKAY) { WOLFSSL_MSG("wc_ecc_verify_hash failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else if (verified == 0) { WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected"); @@ -15448,7 +15712,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, if (!err) { const unsigned char* ptr = der->buffer; - int type = -1; + int type; /* Set key type based on format returned. */ switch (keyFormat) { @@ -15467,6 +15731,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, type = EVP_PKEY_DH; break; default: + type = WOLFSSL_FATAL_ERROR; break; } @@ -15494,6 +15759,13 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, return pkey; } + + +PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, + PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, void* arg) +{ + return wolfSSL_PEM_read_bio_PrivateKey(bio, key, cb, arg); +} #endif /* !NO_BIO */ #if !defined(NO_FILESYSTEM) @@ -15586,7 +15858,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key, if (!err) { const unsigned char* ptr = der->buffer; - int type = -1; + int type; /* Set key type based on format returned. */ switch (keyFormat) { @@ -15605,6 +15877,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key, type = EVP_PKEY_DH; break; default: + type = WOLFSSL_FATAL_ERROR; break; } @@ -16126,8 +16399,6 @@ int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len, #ifdef OPENSSL_ALL #if !defined(NO_PWDBASED) && defined(HAVE_PKCS8) -#if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \ - !defined(NO_STDIO_FILESYSTEM)) /* Encrypt the key into a buffer using PKCS$8 and a password. * * @param [in] pkey Private key to encrypt. @@ -16140,7 +16411,7 @@ int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len, * @return 0 on success. * @return BAD_FUNC_ARG when EVP cipher not supported. */ -static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, +int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key, word32* keySz) { @@ -16204,7 +16475,7 @@ static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, * @param On out, size of encoded key in bytes. * @return 0 on success. */ -static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) +int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) { int ret = 0; int algId; @@ -16227,6 +16498,34 @@ static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) curveOid = NULL; oidSz = 0; } + else if (pkey->type == EVP_PKEY_DSA) { + /* DSA has no curve information. */ + algId = DSAk; + curveOid = NULL; + oidSz = 0; + } + else if (pkey->type == EVP_PKEY_DH) { + if (pkey->dh == NULL) + return BAD_FUNC_ARG; + + if (pkey->dh->priv_key != NULL || pkey->dh->pub_key != NULL) { + /* Special case. DH buffer is always in PKCS8 format */ + if (keySz == NULL) + return BAD_FUNC_ARG; + + *keySz = pkey->pkey_sz; + if (key == NULL) + return LENGTH_ONLY_E; + + XMEMCPY(key, pkey->pkey.ptr, pkey->pkey_sz); + return pkey->pkey_sz; + } + + /* DH has no curve information. */ + algId = DHk; + curveOid = NULL; + oidSz = 0; + } else { ret = NOT_COMPILED_IN; } @@ -16240,6 +16539,8 @@ static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) return ret; } +#if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \ + !defined(NO_STDIO_FILESYSTEM)) /* Write PEM encoded, PKCS#8 formatted private key to BIO. * * @param [out] pem Buffer holding PEM encoding. @@ -16272,7 +16573,7 @@ static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz, if (res == 1) { /* Guestimate key size and PEM size. */ - if (pem_pkcs8_encode(pkey, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { + if (pkcs8_encode(pkey, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { res = 0; } } @@ -16320,7 +16621,7 @@ static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz, if (res == 1) { /* Encrypt the private key. */ - ret = pem_pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz); + ret = pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz); if (ret <= 0) { res = 0; } @@ -16336,7 +16637,7 @@ static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz, type = PKCS8_PRIVATEKEY_TYPE; /* Encode private key in PKCS#8 format. */ - ret = pem_pkcs8_encode(pkey, key, &keySz); + ret = pkcs8_encode(pkey, key, &keySz); if (ret < 0) { res = 0; } @@ -16402,6 +16703,13 @@ int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); return res; } + +int wolfSSL_PEM_write_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, + PKCS8_PRIV_KEY_INFO* keyInfo) +{ + return wolfSSL_PEM_write_bio_PKCS8PrivateKey(bio, keyInfo, NULL, NULL, 0, + NULL, NULL); +} #endif /* !NO_BIO */ #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) diff --git a/src/src/quic.c b/src/src/quic.c index 117bb43..f709ea6 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -1,6 +1,6 @@ /* quic.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -200,7 +200,7 @@ static sword32 quic_record_transfer(QuicRecord* qr, byte* buf, word32 sz) /* We check if the buf is at least RECORD_HEADER_SZ */ if (sz < RECORD_HEADER_SZ) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (qr->rec_hdr_remain == 0) { @@ -614,7 +614,7 @@ int wolfSSL_quic_do_handshake(WOLFSSL* ssl) else { ret = wolfSSL_read_early_data(ssl, tmpbuffer, sizeof(tmpbuffer), &len); - if (ret < 0 && ssl->error == ZERO_RETURN) { + if (ret < 0 && ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN)) { /* this is expected, since QUIC handles the actual early * data separately. */ ret = WOLFSSL_SUCCESS; @@ -634,7 +634,9 @@ int wolfSSL_quic_do_handshake(WOLFSSL* ssl) cleanup: if (ret <= 0 && ssl->options.handShakeState == HANDSHAKE_DONE - && (ssl->error == ZERO_RETURN || ssl->error == WANT_READ)) { + && (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) || + ssl->error == WC_NO_ERR_TRACE(WANT_READ))) + { ret = WOLFSSL_SUCCESS; } if (ret == WOLFSSL_SUCCESS) { @@ -783,7 +785,7 @@ int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz) /* record too small to be fit into a RecordLayerHeader struct. */ if (n == -1) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (quic_record_done(ssl->quic.input_head)) { QuicRecord* qr = ssl->quic.input_head; diff --git a/src/src/sniffer.c b/src/src/sniffer.c index 94b2a9f..758e7be 100644 --- a/src/src/sniffer.c +++ b/src/src/sniffer.c @@ -1,6 +1,6 @@ /* sniffer.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -851,14 +851,11 @@ static void FreeSnifferSession(SnifferSession* session) XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES); #endif #ifdef WOLFSSL_TLS13 - if (session->cliKeyShare) - XFREE(session->cliKeyShare, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(session->cliKeyShare, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif #ifdef HAVE_MAX_FRAGMENT - if (session->tlsFragBuf) { - XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - session->tlsFragBuf = NULL; - } + XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + session->tlsFragBuf = NULL; #endif } XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION); @@ -1659,31 +1656,31 @@ static int LoadKeyFile(byte** keyBuf, word32* keyBufSz, int ret = -1; if (keyBuf == NULL || keyBufSz == NULL || keyFile == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (keySz == 0) { /* load from file */ file = XFOPEN(keyFile, "rb"); - if (file == XBADFILE) return -1; + if (file == XBADFILE) return WOLFSSL_FATAL_ERROR; if(XFSEEK(file, 0, XSEEK_END) != 0) { XFCLOSE(file); - return -1; + return WOLFSSL_FATAL_ERROR; } fileSz = XFTELL(file); if (fileSz > MAX_WOLFSSL_FILE_SIZE || fileSz < 0) { XFCLOSE(file); - return -1; + return WOLFSSL_FATAL_ERROR; } if(XFSEEK(file, 0, XSEEK_SET) != 0) { XFCLOSE(file); - return -1; + return WOLFSSL_FATAL_ERROR; } loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE); if (loadBuf == NULL) { XFCLOSE(file); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = (int)XFREAD(loadBuf, 1, fileSz, file); @@ -1691,14 +1688,14 @@ static int LoadKeyFile(byte** keyBuf, word32* keyBufSz, if (ret != fileSz) { XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE); - return -1; + return WOLFSSL_FATAL_ERROR; } } else { /* use buffer directly */ loadBuf = (byte*)XMALLOC(keySz, NULL, DYNAMIC_TYPE_FILE); if (loadBuf == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } fileSz = keySz; XMEMCPY(loadBuf, keyFile, fileSz); @@ -1735,7 +1732,7 @@ static int LoadKeyFile(byte** keyBuf, word32* keyBufSz, } if (ret < 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } return ret; @@ -1754,14 +1751,14 @@ static int CreateWatchSnifferServer(char* error) DYNAMIC_TYPE_SNIFFER_SERVER); if (sniffer == NULL) { SetError(MEMORY_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } InitSnifferServer(sniffer); sniffer->ctx = wolfSSL_CTX_new(wolfSSLv23_client_method()); if (!sniffer->ctx) { SetError(MEMORY_STR, error, NULL, 0); FreeSnifferServer(sniffer); - return -1; + return WOLFSSL_FATAL_ERROR; } #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT) if (CryptoDeviceId != INVALID_DEVID) @@ -1803,7 +1800,7 @@ static int SetNamedPrivateKey(const char* name, const char* address, int port, NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY); if (namedKey == NULL) { SetError(MEMORY_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } XMEMSET(namedKey, 0, sizeof(NamedKey)); @@ -1818,7 +1815,7 @@ static int SetNamedPrivateKey(const char* name, const char* address, int port, if (ret < 0) { SetError(KEY_FILE_STR, error, NULL, 0); FreeNamedKey(namedKey); - return -1; + return WOLFSSL_FATAL_ERROR; } } #endif @@ -1852,7 +1849,7 @@ static int SetNamedPrivateKey(const char* name, const char* address, int port, #ifdef HAVE_SNI FreeNamedKey(namedKey); #endif - return -1; + return WOLFSSL_FATAL_ERROR; } InitSnifferServer(sniffer); @@ -1868,7 +1865,7 @@ static int SetNamedPrivateKey(const char* name, const char* address, int port, FreeNamedKey(namedKey); #endif FreeSnifferServer(sniffer); - return -1; + return WOLFSSL_FATAL_ERROR; } #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT) if (CryptoDeviceId != INVALID_DEVID) @@ -1909,7 +1906,7 @@ static int SetNamedPrivateKey(const char* name, const char* address, int port, SetError(KEY_FILE_STR, error, NULL, 0); if (isNew) FreeSnifferServer(sniffer); - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WOLF_CRYPTO_CB wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId); @@ -2127,7 +2124,7 @@ static int CheckIp6Hdr(Ip6Hdr* iphdr, IpInfo* info, int length, char* error) if (version != IPV6) { SetError(BAD_IPVER_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } /* Here, we need to move onto next header if not TCP. */ @@ -2137,7 +2134,7 @@ static int CheckIp6Hdr(Ip6Hdr* iphdr, IpInfo* info, int length, char* error) int hdrsz = (exthdr->length + 1) * 8; if (hdrsz > length - exthdrsz) { SetError(PACKET_HDR_SHORT_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } exthdrsz += hdrsz; exthdr = (Ip6ExtHdr*)((byte*)exthdr + hdrsz); @@ -2149,7 +2146,7 @@ static int CheckIp6Hdr(Ip6Hdr* iphdr, IpInfo* info, int length, char* error) #ifndef WOLFSSL_SNIFFER_WATCH if (!IsServerRegistered6(iphdr->src) && !IsServerRegistered6(iphdr->dst)) { SetError(SERVER_NOT_REG_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -2183,12 +2180,12 @@ static int CheckIpHdr(IpHdr* iphdr, IpInfo* info, int length, char* error, if (version != IPV4) { SetError(BAD_IPVER_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } if (iphdr->protocol != TCP_PROTOCOL) { SetError(BAD_PROTO_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } info->length = IP_HL(iphdr); @@ -2580,7 +2577,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, if (args->length > *sslBytes) { SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -2803,7 +2800,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, if (args->length > *sslBytes) { SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* if curve not provided in key share data, then use private @@ -2896,7 +2893,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, if (args->length > *sslBytes) { SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { @@ -2979,7 +2976,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, if (args->length > *sslBytes) { SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret == 0) { @@ -3165,13 +3162,13 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, if (SetCipherSpecs(session->sslServer) != 0) { SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - ret = -1; break; + ret = WOLFSSL_FATAL_ERROR; break; } if (SetCipherSpecs(session->sslClient) != 0) { SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - ret = -1; break; + ret = WOLFSSL_FATAL_ERROR; break; } #ifdef WOLFSSL_TLS13 @@ -3203,7 +3200,7 @@ static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session, } if (ret != 0) { SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE); - ret = -1; break; + ret = WOLFSSL_FATAL_ERROR; break; } #ifdef SHOW_SECRETS @@ -3263,7 +3260,7 @@ static int ProcessClientKeyExchange(const byte* input, int* sslBytes, session->sslServer->buffers.key->length == 0) { SetError(RSA_KEY_MISSING_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -3291,7 +3288,7 @@ static int ProcessKeyShare(KeyShareInfo* info, const byte* input, int len, info->key_len = (word16)((input[index] << 8) | input[index+1]); index += OPAQUE16_LEN; if (info->key_len == 0 || info->key_len > len - index) { - return -1; + return WOLFSSL_FATAL_ERROR; } info->key = &input[index]; index += info->key_len; @@ -3395,7 +3392,7 @@ static int ProcessServerKeyShare(SnifferSession* session, const byte* input, int } if (ret != 0) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } return ret; @@ -3420,7 +3417,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* make sure can read through hint len */ if (TICKET_HINT_LEN > *sslBytes) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } input += TICKET_HINT_LEN; /* skip over hint len */ *sslBytes -= TICKET_HINT_LEN; @@ -3431,7 +3428,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* make sure can read through hint age and nonce len */ if (TICKET_HINT_AGE_LEN + 1 > *sslBytes) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } input += TICKET_HINT_AGE_LEN; /* skip over hint age */ *sslBytes -= TICKET_HINT_AGE_LEN; @@ -3440,7 +3437,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, len = input[0]; if (len > MAX_TICKET_NONCE_STATIC_SZ) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } input += OPAQUE8_LEN; *sslBytes -= OPAQUE8_LEN; @@ -3458,7 +3455,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* make sure can read through len */ if (OPAQUE16_LEN > *sslBytes) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } len = (word16)((input[0] << 8) | input[1]); @@ -3468,7 +3465,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* make sure can read through ticket */ if (len > *sslBytes) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_TLS13 @@ -3478,7 +3475,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, #ifdef HAVE_SESSION_TICKET if (SetTicket(session->sslServer, input, len) != 0) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* set haveSessionId to use the wolfSession cache */ @@ -3505,7 +3502,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* capture last part of sessionID as macID (32 bytes) */ if (len < ID_LEN) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* store session with macID as sessionID */ session->sslServer->options.haveSessionId = 1; @@ -3549,7 +3546,7 @@ static int DoResume(SnifferSession* session, char* error) INC_STAT(SnifferStats.sslResumeMisses); #endif SetError(BAD_SESSION_RESUME_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -3574,13 +3571,13 @@ static int DoResume(SnifferSession* session, char* error) if (SetCipherSpecs(session->sslServer) != 0) { SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - return -1; + return WOLFSSL_FATAL_ERROR; } if (SetCipherSpecs(session->sslClient) != 0) { SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_TLS13 @@ -3619,7 +3616,7 @@ static int DoResume(SnifferSession* session, char* error) if (ret != 0) { SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } return ret; @@ -3648,7 +3645,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, /* make sure can read through session len */ if (toRead > *sslBytes) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } XMEMCPY(&pv, input, VERSION_SZ); @@ -3673,7 +3670,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, /* make sure can read through compression */ if ( (b + SUITE_LEN + ENUM_LEN) > *sslBytes) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } if (b) { #ifdef WOLFSSL_TLS13 @@ -3721,7 +3718,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, if (b) { SetError(BAD_COMPRESSION_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* extensions */ @@ -3732,7 +3729,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, /* make sure can read len */ if (SUITE_LEN > *sslBytes) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } len = (word16)((input[0] << 8) | input[1]); input += SUITE_LEN; @@ -3740,7 +3737,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, /* make sure can read through all extensions */ if (len > *sslBytes) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } while (len >= EXT_TYPE_SZ + LENGTH_SZ) { @@ -3759,7 +3756,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, if (extLen > *sslBytes) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef DEBUG_SNIFFER printf("\tserver_hello ext: 0x%02x (len %d)\n", extType, extLen); @@ -3772,7 +3769,7 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, if (ret != 0) { SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } break; #endif @@ -3838,14 +3835,14 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, #ifndef WOLFSSL_TLS13 SetError(UNSUPPORTED_TLS_VER_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - return -1; + return WOLFSSL_FATAL_ERROR; #endif } else { #ifdef WOLFSSL_NO_TLS12 SetError(UNSUPPORTED_TLS_VER_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - return -1; + return WOLFSSL_FATAL_ERROR; #endif } @@ -4010,7 +4007,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read up to session len */ if (toRead > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* skip, get negotiated one from server hello */ @@ -4032,7 +4029,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, if (bLen) { if (ID_LEN > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } Trace(CLIENT_RESUME_TRY_STR); #ifdef WOLFSSL_TLS13 @@ -4058,7 +4055,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read len */ if (SUITE_LEN > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } len = (word16)((input[0] << 8) | input[1]); input += SUITE_LEN; @@ -4066,7 +4063,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read suites + comp len */ if (len + ENUM_LEN > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } input += len; *sslBytes -= len; @@ -4077,7 +4074,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read len */ if (bLen > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } input += bLen; *sslBytes -= bLen; @@ -4091,7 +4088,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read len */ if (SUITE_LEN > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } len = (word16)((input[0] << 8) | input[1]); input += SUITE_LEN; @@ -4099,7 +4096,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read through all extensions */ if (len > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } while (len >= EXT_TYPE_SZ + LENGTH_SZ) { @@ -4117,7 +4114,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, /* make sure can read through individual extension */ if (extLen > *sslBytes) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef DEBUG_SNIFFER @@ -4166,7 +4163,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, word16 ksLen = (word16)((input[0] << 8) | input[1]); if (ksLen + OPAQUE16_LEN > extLen) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* cache key share data till server_hello */ session->cliKeyShareSz = ksLen; @@ -4190,7 +4187,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, idsLen = (word16)((input[idx] << 8) | input[idx+1]); if (idsLen + OPAQUE16_LEN + idx > extLen) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } idx += OPAQUE16_LEN; @@ -4198,7 +4195,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, idLen = (word16)((input[idx] << 8) | input[idx+1]); if (idLen + OPAQUE16_LEN + idx > extLen) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } idx += OPAQUE16_LEN; identity = &input[idx]; @@ -4214,7 +4211,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, bindersLen = (word16)((input[idx] << 8) | input[idx+1]); if (bindersLen + OPAQUE16_LEN + idx > extLen) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } idx += OPAQUE16_LEN; binders = &input[idx]; @@ -4249,7 +4246,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, if (extLen && extLen < ID_LEN) { SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } if (extLen) { if (session->ticketID == NULL) { @@ -4258,7 +4255,7 @@ static int ProcessClientHello(const byte* input, int* sslBytes, if (session->ticketID == 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -4300,7 +4297,7 @@ static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz, if (WatchCb == NULL) { SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = wc_InitSha256(&sha); @@ -4310,7 +4307,7 @@ static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz, ret = wc_Sha256Final(&sha, digest); if (ret != 0) { SetError(WATCH_HASH_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = WatchCb((void*)session, digest, sizeof(digest), @@ -4320,7 +4317,7 @@ static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz, INC_STAT(SnifferStats.sslKeysUnmatched); #endif SetError(WATCH_FAIL_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { #ifdef WOLFSSL_SNIFFER_STATS @@ -4344,7 +4341,7 @@ static int ProcessCertificate(const byte* input, int* sslBytes, if (*sslBytes < CERT_HEADER_SZ) { SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_TLS13 @@ -4361,14 +4358,14 @@ static int ProcessCertificate(const byte* input, int* sslBytes, if (*sslBytes < (int)certChainSz) { SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } ato24(input, &certSz); input += OPAQUE24_LEN; if (*sslBytes < (int)certSz) { SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } *sslBytes -= certChainSz; @@ -4446,7 +4443,7 @@ static int ProcessFinished(const byte* input, int size, int* sslBytes, if (ret != 0) { SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } session->flags.gotFinished = 1; @@ -4482,7 +4479,7 @@ static int ProcessFinished(const byte* input, int size, int* sslBytes, if (ret != 0) { SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } #endif @@ -4532,7 +4529,7 @@ static int DoHandShake(const byte* input, int* sslBytes, if (*sslBytes < HANDSHAKE_HEADER_SZ) { SetError(HANDSHAKE_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } type = input[0]; size = (input[1] << 16) | (input[2] << 8) | input[3]; @@ -4598,7 +4595,7 @@ static int DoHandShake(const byte* input, int* sslBytes, if (HashUpdate(session->hash, input, size) != 0) { SetError(EXTENDED_MASTER_HASH_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; goto exit; } } @@ -4632,7 +4629,7 @@ static int DoHandShake(const byte* input, int* sslBytes, /* can't know temp key passively */ SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE); session->verboseErr = 1; - ret = -1; + ret = WOLFSSL_FATAL_ERROR; #if defined(WOLFSSL_SNIFFER_STATS) INC_STAT(SnifferStats.sslEphemeralMisses); @@ -4683,7 +4680,7 @@ static int DoHandShake(const byte* input, int* sslBytes, else { SetError(EXTENDED_MASTER_HASH_STR, error, session, FATAL_ERROR_STATE); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } XMEMSET(session->hash, 0, sizeof(HsHashes)); XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES); @@ -4715,7 +4712,7 @@ static int DoHandShake(const byte* input, int* sslBytes, break; default: SetError(GOT_UNKNOWN_HANDSHAKE_STR, error, session, 0); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } @@ -4723,10 +4720,8 @@ static int DoHandShake(const byte* input, int* sslBytes, exit: #endif #ifdef HAVE_MAX_FRAGMENT - if (session->tlsFragBuf) { - XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - session->tlsFragBuf = NULL; - } + XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + session->tlsFragBuf = NULL; #endif *sslBytes = startBytes - size; /* actual bytes of full process */ @@ -5011,6 +5006,7 @@ static const byte* DecryptMessage(WOLFSSL* ssl, const byte* input, word32 sz, return NULL; } + ssl->curSize = sz; ssl->keys.encryptSz = sz; if (ssl->options.tls1_1 && ssl->specs.cipher_type == block) { output += ssl->specs.block_size; /* go past TLSv1.1 IV */ @@ -5251,14 +5247,14 @@ static int DoOldHello(SnifferSession* session, const byte* sslFrame, if (*rhSize > *sslBytes) { SetError(OLD_CLIENT_INPUT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = ProcessOldClientHello(session->sslServer, input, &idx, *sslBytes, (word16)*rhSize); if (ret < 0 && ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) { SetError(BAD_OLD_CLIENT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } Trace(OLD_CLIENT_OK_STR); @@ -5324,7 +5320,7 @@ static int TcpChecksum(IpInfo* ipInfo, TcpInfo* tcpInfo, int dataLen, /* field, but tcp checksum offloading could negate calculation */ if (checksum == 0) return 0; - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -5347,7 +5343,7 @@ static int CheckHeaders(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte* packet, /* ip header */ if (length < IP_HDR_SZ) { SetError(PACKET_HDR_SHORT_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } version = IP_V(iphdr); @@ -5361,31 +5357,31 @@ static int CheckHeaders(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte* packet, } if (CheckIpHdr(iphdr, ipInfo, length, error, trace) != 0) - return -1; + return WOLFSSL_FATAL_ERROR; #ifndef WOLFSSL_SNIFFER_WATCH if (checkReg && !IsServerRegistered(iphdr->src) && !IsServerRegistered(iphdr->dst)) { SetError(SERVER_NOT_REG_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif /* tcp header */ if (length < (ipInfo->length + TCP_HDR_SZ)) { SetError(PACKET_HDR_SHORT_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } tcphdr = (TcpHdr*)(packet + ipInfo->length); if (CheckTcpHdr(tcphdr, tcpInfo, error, trace) != 0) - return -1; + return WOLFSSL_FATAL_ERROR; #ifndef WOLFSSL_SNIFFER_WATCH if (checkReg && !IsPortRegistered(tcpInfo->srcPort) && !IsPortRegistered(tcpInfo->dstPort)) { SetError(SERVER_PORT_NOT_REG_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -5393,7 +5389,7 @@ static int CheckHeaders(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte* packet, *sslFrame = packet + ipInfo->length + tcpInfo->length; if (*sslFrame > packet + length) { SetError(PACKET_HDR_SHORT_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } /* We only care about the data in the TCP/IP record. There may be extra @@ -5435,7 +5431,7 @@ static int CheckSession(IpInfo* ipInfo, TcpInfo* tcpInfo, int sslBytes, return 1; SetError(MEMORY_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } return 1; } @@ -5458,7 +5454,7 @@ static int CheckSession(IpInfo* ipInfo, TcpInfo* tcpInfo, int sslBytes, #endif SetError(BAD_SESSION_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } } return 0; @@ -5519,12 +5515,12 @@ static int AddToReassembly(byte from, word32 seq, const byte* sslFrame, if (MaxRecoveryMemory != -1 && (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) { SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } add = CreateBuffer(&seq, seq + sslBytes - 1, sslFrame, &bytesLeft); if (add == NULL) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } *front = add; *reassemblyMemory += sslBytes; @@ -5541,12 +5537,12 @@ static int AddToReassembly(byte from, word32 seq, const byte* sslFrame, if (MaxRecoveryMemory -1 && (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) { SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } add = CreateBuffer(&seq, end, sslFrame, &bytesLeft); if (add == NULL) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } add->next = curr; *front = add; @@ -5583,13 +5579,13 @@ static int AddToReassembly(byte from, word32 seq, const byte* sslFrame, if (MaxRecoveryMemory != -1 && (int)(*reassemblyMemory + added) > MaxRecoveryMemory) { SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } add = CreateBuffer(&seq, seq + added - 1, &sslFrame[seq - startSeq], &bytesLeft); if (add == NULL) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } add->next = prev->next; prev->next = add; @@ -5859,7 +5855,7 @@ static int FindNextRecordInAssembly(SnifferSession* session, if ( *sslBytes > (int)ssl->buffers.inputBuffer.bufferSize) { if (GrowInputBuffer(ssl, *sslBytes, 0) < 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -5951,7 +5947,7 @@ static int CheckAck(TcpInfo* tcpInfo, SnifferSession* session) TraceAck(real, expected); if (real > expected) - return -1; /* we missed a packet, ACKing data we never saw */ + return WOLFSSL_FATAL_ERROR; /* we missed a packet, ACKing data we never saw */ } return 0; } @@ -6000,7 +5996,7 @@ static int CheckSequence(IpInfo* ipInfo, TcpInfo* tcpInfo, UpdateMissedDataSessions(); #endif SetError(ACK_MISSED_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } else { SetError(ACK_MISSED_STR, error, session, 0); @@ -6071,13 +6067,13 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, if (session->flags.fatalError == FATAL_ERROR_STATE) { SetError(FATAL_ERROR_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } if (skipPartial) { if (FindNextRecordInAssembly(session, sslFrame, sslBytes, end, error) < 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -6095,7 +6091,7 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) { if (GrowInputBuffer(ssl, *sslBytes, length) < 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } if (vChain == NULL) { @@ -6118,7 +6114,7 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) { if (GrowInputBuffer(ssl, *sslBytes, length) < 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -6156,7 +6152,7 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, #ifdef OLD_HELLO_ALLOWED int ret = DoOldHello(session, *sslFrame, &rhSize, sslBytes, error); if (ret < 0) - return -1; /* error already set */ + return WOLFSSL_FATAL_ERROR; /* error already set */ if (*sslBytes <= 0) return 1; #endif @@ -6267,7 +6263,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, rhSize = 0; if (sslBytes < 0) { SetError(PACKET_HDR_SHORT_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } if (sslBytes >= RECORD_HEADER_SZ) { if (GetRecordHeader(sslFrame, &rh, &rhSize) != 0) { @@ -6289,7 +6285,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, if (sslBytes > (int)ssl->buffers.inputBuffer.bufferSize) { if (GrowInputBuffer(ssl, sslBytes, 0) < 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } } XMEMMOVE(ssl->buffers.inputBuffer.buffer, sslFrame, sslBytes); @@ -6327,11 +6323,11 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, } if (ssl->decrypt.setup != 1) { SetError(DECRYPT_KEYS_NOT_SETUP, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } if (CheckAvailableSize(ssl, rhSize) < 0) { SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } sslFrame = DecryptMessage(ssl, sslFrame, rhSize, @@ -6355,7 +6351,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, if (errCode != 0) { if ((enum ContentType)rh.type == application_data) { SetError(BAD_DECRYPT, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* do not end session for failures on handshake packets */ return 0; @@ -6380,7 +6376,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, if (session->flags.fatalError == 0) SetError(BAD_HANDSHAKE_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* DoHandShake now fully decrements sslBytes to remaining */ @@ -6434,7 +6430,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, *data = NULL; SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } *data = tmpData; XMEMCPY(*data + decoded, @@ -6454,7 +6450,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, stored = StoreDataCb(buf, bufSz, offset, ctx); if (stored <= 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } offset += stored; } while (offset < bufSz); @@ -6462,13 +6458,13 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, else { SetError(STORE_DATA_CB_MISSING_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } #else (void)ctx; SetError(NO_DATA_DEST_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; #endif } TraceAddedData(ret, decoded); @@ -6479,7 +6475,7 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, else { /* set error, but do not treat fatal */ SetError(BAD_APP_DATA_STR, error,session, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } if (ssl->buffers.outputBuffer.dynamicFlag) ShrinkOutputBuffer(ssl); @@ -6500,10 +6496,11 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, case ack: /* TODO */ #endif /* WOLFSSL_DTLS13 */ + case dtls12_cid: case no_type: default: SetError(GOT_UNKNOWN_RECORD_STR, error, session, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } /* do we have another msg in record ? */ @@ -6851,7 +6848,7 @@ int ssl_FreeZeroDecodeBuffer(byte** data, int sz, char* error) (void)error; if (sz < 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (data != NULL) { @@ -6874,7 +6871,7 @@ int ssl_Trace(const char* traceFile, char* error) TraceFile = XFOPEN(traceFile, "a"); if (!TraceFile) { SetError(BAD_TRACE_FILE_STR, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } TraceOn = 1; } @@ -6944,7 +6941,7 @@ int ssl_GetSessionStats(unsigned int* active, unsigned int* total, return 0; else { SetError(BAD_SESSION_STATS, error, NULL, 0); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -6985,7 +6982,7 @@ int ssl_ResetStatistics(void) int ssl_ReadStatistics(SSLStats* stats) { if (stats == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; LOCK_STAT(); XMEMCPY(stats, &SnifferStats, sizeof(SSLStats)); @@ -6999,7 +6996,7 @@ int ssl_ReadStatistics(SSLStats* stats) int ssl_ReadResetStatistics(SSLStats* stats) { if (stats == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; LOCK_STAT(); XMEMCPY(stats, &SnifferStats, sizeof(SSLStats)); @@ -7045,10 +7042,10 @@ int ssl_SetWatchKey_buffer(void* vSniffer, const byte* key, word32 keySz, int ret; if (vSniffer == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (key == NULL || keySz == 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } sniffer = (SnifferSession*)vSniffer; @@ -7077,7 +7074,7 @@ int ssl_SetWatchKey_buffer(void* vSniffer, const byte* key, word32 keySz, if (ret != WOLFSSL_SUCCESS) { SetError(KEY_FILE_STR, error, sniffer, FATAL_ERROR_STATE); - return -1; + return WOLFSSL_FATAL_ERROR; } return 0; @@ -7091,10 +7088,10 @@ int ssl_SetWatchKey_file(void* vSniffer, const char* keyFile, int keyType, int ret; if (vSniffer == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (keyFile == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } /* Remap the keyType from what the user can use to @@ -7106,7 +7103,7 @@ int ssl_SetWatchKey_file(void* vSniffer, const char* keyFile, int keyType, if (ret < 0) { SetError(KEY_FILE_STR, error, NULL, 0); XFREE(keyBuf, NULL, DYNAMIC_TYPE_X509); - return -1; + return WOLFSSL_FATAL_ERROR; } ret = ssl_SetWatchKey_buffer(vSniffer, keyBuf, keyBufSz, FILETYPE_DER, diff --git a/src/src/ssl.c b/src/src/ssl.c index 9ba891d..fe81193 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -1,6 +1,6 @@ /* ssl.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -25,10 +25,9 @@ #endif #include -#if defined(OPENSSL_EXTRA) && !defined(_WIN32) +#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XISASCII */ - #undef _GNU_SOURCE - #define _GNU_SOURCE + #define _GNU_SOURCE 1 #endif #if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \ @@ -553,6 +552,18 @@ int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output, return GetEchConfigsEx(ctx->echConfigs, output, outputLen); } +void wolfSSL_CTX_SetEchEnable(WOLFSSL_CTX* ctx, byte enable) +{ + if (ctx != NULL) { + ctx->disableECH = !enable; + if (ctx->disableECH) { + TLSX_Remove(&ctx->extensions, TLSX_ECH, ctx->heap); + FreeEchConfigs(ctx->echConfigs, ctx->heap); + ctx->echConfigs = NULL; + } + } +} + /* set the ech config from base64 for our client ssl object, base64 is the * format ech configs are sent using dns records */ int wolfSSL_SetEchConfigsBase64(WOLFSSL* ssl, char* echConfigs64, @@ -841,7 +852,7 @@ int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, word32* outputLen) if (output == NULL) { *outputLen = totalLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (totalLen > *outputLen) { @@ -942,6 +953,18 @@ int wolfSSL_GetEchConfigs(WOLFSSL* ssl, byte* output, word32* outputLen) return GetEchConfigsEx(ssl->echConfigs, output, outputLen); } +void wolfSSL_SetEchEnable(WOLFSSL* ssl, byte enable) +{ + if (ssl != NULL) { + ssl->options.disableECH = !enable; + if (ssl->options.disableECH) { + TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap); + FreeEchConfigs(ssl->echConfigs, ssl->heap); + ssl->echConfigs = NULL; + } + } +} + /* get the raw ech configs from our linked list of ech config structs */ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) { @@ -986,7 +1009,7 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) if (output == NULL) { *outputLen = totalLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (totalLen > *outputLen) { @@ -1034,9 +1057,7 @@ WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap) if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_Init failed"); WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0); - if (method != NULL) { - XFREE(method, heap, DYNAMIC_TYPE_METHOD); - } + XFREE(method, heap, DYNAMIC_TYPE_METHOD); return NULL; } } @@ -1132,10 +1153,8 @@ void wolfSSL_CTX_free(WOLFSSL_CTX* ctx) #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \ && !defined(NO_SHA256) && !defined(WC_NO_RNG) if (ctx->srp != NULL) { - if (ctx->srp_password != NULL){ - XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); - ctx->srp_password = NULL; - } + XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); + ctx->srp_password = NULL; wc_SrpTerm(ctx->srp); XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP); ctx->srp = NULL; @@ -1688,7 +1707,7 @@ const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len) return NULL; cipher = wolfSSL_get_cipher_name_iana(ssl); - len = (int)min((word32)len, (int)(XSTRLEN(cipher) + 1)); + len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1)); XMEMCPY(buf, cipher, len); return buf; } @@ -1954,6 +1973,15 @@ int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu) return WOLFSSL_SUCCESS; } +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) +int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu) { + if (wolfSSL_dtls_set_mtu(ssl, mtu) == 0) + return SSL_SUCCESS; + else + return SSL_FAILURE; +} +#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ + #endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */ #ifdef WOLFSSL_SRTP @@ -2041,7 +2069,7 @@ static int DtlsSrtpSelProfiles(word16* id, const char* profile_str) int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL) { ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str); } @@ -2049,7 +2077,7 @@ int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str) } int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ssl != NULL) { ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str); } @@ -2094,7 +2122,7 @@ int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl, } if (out == NULL) { *olen = (size_t)profile->kdfBits; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*olen < (size_t)profile->kdfBits) { @@ -2303,7 +2331,7 @@ int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub) } else { WOLFSSL_MSG("No room in peer list."); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } else { @@ -2394,7 +2422,7 @@ int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx) /* return underlying connect or accept, WOLFSSL_SUCCESS on ok */ int wolfSSL_negotiate(WOLFSSL* ssl) { - int err = WOLFSSL_FATAL_ERROR; + int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); WOLFSSL_ENTER("wolfSSL_negotiate"); @@ -2876,8 +2904,9 @@ static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek) /* make sure bidirectional TLS shutdown completes */ if (ssl->error == WOLFSSL_ERROR_SYSCALL || ssl->options.shutdownDone) { /* ask the underlying transport the connection is closed */ - if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx) == - WOLFSSL_CBIO_ERR_CONN_CLOSE) { + if (ssl->CBIORecv(ssl, (char*)data, 0, ssl->IOCB_ReadCtx) + == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE)) + { ssl->options.isClosed = 1; ssl->error = WOLFSSL_ERROR_ZERO_RETURN; } @@ -2900,9 +2929,9 @@ static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek) #ifdef HAVE_WRITE_DUP if (ssl->dupWrite) { - if (ssl->error != 0 && ssl->error != WANT_READ + if (ssl->error != 0 && ssl->error != WC_NO_ERR_TRACE(WANT_READ) #ifdef WOLFSSL_ASYNC_CRYPT - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { int notifyErr; @@ -3395,7 +3424,7 @@ int wolfSSL_UseALPN(WOLFSSL* ssl, char *protocol_name_list, char *list, *ptr, **token; word16 len; int idx = 0; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_UseALPN"); @@ -3623,7 +3652,7 @@ static int _Rehandshake(WOLFSSL* ssl) ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED; -#if !defined(NO_WOLFSSL_SERVER) +#if !defined(NO_WOLFSSL_SERVER) && !defined(WOLFSSL_NO_TLS12) if (ssl->options.side == WOLFSSL_SERVER_END) { ret = SendHelloRequest(ssl); if (ret != 0) { @@ -3631,7 +3660,7 @@ static int _Rehandshake(WOLFSSL* ssl) return WOLFSSL_FATAL_ERROR; } } -#endif /* !NO_WOLFSSL_SERVER */ +#endif /* !NO_WOLFSSL_SERVER && !WOLFSSL_NO_TLS12 */ ret = InitHandshakeHashes(ssl); if (ret != 0) { @@ -3975,7 +4004,7 @@ int wolfSSL_recv(WOLFSSL* ssl, void* data, int sz, int flags) int wolfSSL_SendUserCanceled(WOLFSSL* ssl) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_recv"); if (ssl != NULL) { @@ -3997,7 +4026,7 @@ int wolfSSL_SendUserCanceled(WOLFSSL* ssl) WOLFSSL_ABI int wolfSSL_shutdown(WOLFSSL* ssl) { - int ret = WOLFSSL_FATAL_ERROR; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); WOLFSSL_ENTER("wolfSSL_shutdown"); if (ssl == NULL) @@ -4039,7 +4068,7 @@ int wolfSSL_shutdown(WOLFSSL* ssl) /* call wolfSSL_shutdown again for bidirectional shutdown */ if (ssl->options.sentNotify && !ssl->options.closeNotify) { ret = ProcessReply(ssl); - if ((ret == ZERO_RETURN) || + if ((ret == WC_NO_ERR_TRACE(ZERO_RETURN)) || (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))) { /* simulate OpenSSL behavior */ ssl->options.shutdownDone = 1; @@ -4097,13 +4126,16 @@ int wolfSSL_get_error(WOLFSSL* ssl, int ret) WOLFSSL_LEAVE("wolfSSL_get_error", ssl->error); /* make sure converted types are handled in SetErrorString() too */ - if (ssl->error == WANT_READ) + if (ssl->error == WC_NO_ERR_TRACE(WANT_READ)) return WOLFSSL_ERROR_WANT_READ; /* convert to OpenSSL type */ - else if (ssl->error == WANT_WRITE) + else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) return WOLFSSL_ERROR_WANT_WRITE; /* convert to OpenSSL type */ - else if (ssl->error == ZERO_RETURN || ssl->options.shutdownDone) + else if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) || + ssl->options.shutdownDone) return WOLFSSL_ERROR_ZERO_RETURN; /* convert to OpenSSL type */ #ifdef OPENSSL_EXTRA + else if (ssl->error == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) + return WOLFSSL_ERROR_SYSCALL; /* convert to OpenSSL type */ else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E)) return WOLFSSL_ERROR_SYSCALL; /* convert to OpenSSL type */ #endif @@ -4126,9 +4158,9 @@ int wolfSSL_want(WOLFSSL* ssl) { int rw_state = SSL_NOTHING; if (ssl) { - if (ssl->error == WANT_READ) + if (ssl->error == WC_NO_ERR_TRACE(WANT_READ)) rw_state = SSL_READING; - else if (ssl->error == WANT_WRITE) + else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) rw_state = SSL_WRITING; } return rw_state; @@ -4139,7 +4171,7 @@ int wolfSSL_want(WOLFSSL* ssl) int wolfSSL_want_read(WOLFSSL* ssl) { WOLFSSL_ENTER("wolfSSL_want_read"); - if (ssl->error == WANT_READ) + if (ssl->error == WC_NO_ERR_TRACE(WANT_READ)) return 1; return 0; @@ -4150,7 +4182,7 @@ int wolfSSL_want_read(WOLFSSL* ssl) int wolfSSL_want_write(WOLFSSL* ssl) { WOLFSSL_ENTER("wolfSSL_want_write"); - if (ssl->error == WANT_WRITE) + if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) return 1; return 0; @@ -4549,7 +4581,7 @@ int wolfSSL_GetCipherType(WOLFSSL* ssl) if (ssl->specs.cipher_type == aead) return WOLFSSL_AEAD_TYPE; - return -1; + return WOLFSSL_FATAL_ERROR; } @@ -4665,7 +4697,7 @@ int wolfSSL_pending(WOLFSSL* ssl) if (ssl == NULL) return WOLFSSL_FAILURE; - return ssl->buffers.clearOutputBuffer.length; + return (int)ssl->buffers.clearOutputBuffer.length; } int wolfSSL_has_pending(const WOLFSSL* ssl) @@ -4834,6 +4866,20 @@ int wolfSSL_GetVersion(const WOLFSSL* ssl) break; } } +#ifdef WOLFSSL_DTLS + if (ssl->version.major == DTLS_MAJOR) { + switch (ssl->version.minor) { + case DTLS_MINOR : + return WOLFSSL_DTLSV1; + case DTLSv1_2_MINOR : + return WOLFSSL_DTLSV1_2; + case DTLSv1_3_MINOR : + return WOLFSSL_DTLSV1_3; + default: + break; + } + } +#endif /* WOLFSSL_DTLS */ return VERSION_ERROR; } @@ -5094,6 +5140,42 @@ Signer* GetCA(void* vp, byte* hash) return ret; } +#if defined(HAVE_OCSP) +Signer* GetCAByKeyHash(void* vp, const byte* keyHash) +{ + WOLFSSL_CERT_MANAGER* cm = (WOLFSSL_CERT_MANAGER*)vp; + Signer* ret = NULL; + Signer* signers; + int row; + + if (cm == NULL || keyHash == NULL) + return NULL; + + /* try lookup using keyHash as subjKeyID first */ + ret = GetCA(vp, (byte*)keyHash); + if (ret != NULL && XMEMCMP(ret->subjectKeyHash, keyHash, KEYID_SIZE) == 0) { + return ret; + } + + /* if we can't find the cert, we have to scan the full table */ + if (wc_LockMutex(&cm->caLock) != 0) + return NULL; + + /* Unfortunately we need to look through the entire table */ + for (row = 0; row < CA_TABLE_SIZE && ret == NULL; row++) { + for (signers = cm->caTable[row]; signers != NULL; + signers = signers->next) { + if (XMEMCMP(signers->subjectKeyHash, keyHash, KEYID_SIZE) == 0) { + ret = signers; + break; + } + } + } + + wc_UnLockMutex(&cm->caLock); + return ret; +} +#endif #ifdef WOLFSSL_AKID_NAME Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz, const byte* serial, word32 serialSz) @@ -5349,6 +5431,13 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) #endif InitDecodedCert(cert, der->buffer, der->length, cm->heap); + +#ifdef WC_ASN_UNKNOWN_EXT_CB + if (cm->unknownExtCallback != NULL) { + wc_SetUnknownExtCallback(cert, cm->unknownExtCallback); + } +#endif + ret = ParseCert(cert, CA_TYPE, verify, cm); WOLFSSL_MSG("\tParsed new CA"); @@ -5446,13 +5535,15 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) } } - if (ret == 0 && cert->isCA == 0 && type != WOLFSSL_USER_CA) { + if (ret == 0 && cert->isCA == 0 && type != WOLFSSL_USER_CA && + type != WOLFSSL_TEMP_CA) { WOLFSSL_MSG("\tCan't add as CA if not actually one"); ret = NOT_CA_ERROR; } #ifndef ALLOW_INVALID_CERTSIGN else if (ret == 0 && cert->isCA == 1 && type != WOLFSSL_USER_CA && - !cert->selfSigned && (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0) { + type != WOLFSSL_TEMP_CA && !cert->selfSigned && + (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0) { /* Intermediate CA certs are required to have the keyCertSign * extension set. User loaded root certs are not. */ WOLFSSL_MSG("\tDoesn't have key usage certificate signing"); @@ -5932,6 +6023,17 @@ int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb) return BAD_FUNC_ARG; } +int wolfSSL_SetCRL_ErrorCb(WOLFSSL* ssl, crlErrorCb cb, void* ctx) +{ + WOLFSSL_ENTER("wolfSSL_SetCRL_Cb"); + if (ssl) { + SSL_CM_WARNING(ssl); + return wolfSSL_CertManagerSetCRL_ErrorCb(SSL_CM(ssl), cb, ctx); + } + else + return BAD_FUNC_ARG; +} + #ifdef HAVE_CRL_IO int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb) { @@ -5997,6 +6099,15 @@ int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb) return BAD_FUNC_ARG; } +int wolfSSL_CTX_SetCRL_ErrorCb(WOLFSSL_CTX* ctx, crlErrorCb cb, void* cbCtx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_SetCRL_ErrorCb"); + if (ctx) + return wolfSSL_CertManagerSetCRL_ErrorCb(ctx->cm, cb, cbCtx); + else + return BAD_FUNC_ARG; +} + #ifdef HAVE_CRL_IO int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb) { @@ -6194,7 +6305,7 @@ static int check_cert_key(DerBuffer* cert, DerBuffer* key, DerBuffer* altKey, #endif word32 size; byte* buff; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("check_cert_key"); @@ -6238,7 +6349,7 @@ static int check_cert_key(DerBuffer* cert, DerBuffer* key, DerBuffer* altKey, if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif /* WOLF_PRIVATE_KEY_ID */ { - ret = wc_CheckPrivateKeyCert(buff, size, der, 0); + ret = wc_CheckPrivateKeyCert(buff, size, der, 0, heap); ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; } @@ -6298,7 +6409,7 @@ static int check_cert_key(DerBuffer* cert, DerBuffer* key, DerBuffer* altKey, if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) #endif /* WOLF_PRIVATE_KEY_ID */ { - ret = wc_CheckPrivateKeyCert(buff, size, der, 1); + ret = wc_CheckPrivateKeyCert(buff, size, der, 1, heap); ret = (ret == 1) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE; } } @@ -6482,7 +6593,7 @@ static int d2iTryRsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, #endif if (!isRsaKey) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -6566,7 +6677,7 @@ static int d2iTryEccKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, #endif if (!isEccKey) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -6654,7 +6765,7 @@ static int d2iTryDsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, /* test if DSA key */ if (!isDsaKey) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -6738,7 +6849,7 @@ static int d2iTryDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, /* test if DH key */ if (!isDhKey) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -6822,7 +6933,7 @@ static int d2iTryAltDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, #endif if (ret != 0) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -6937,7 +7048,7 @@ static int d2iTryFalconKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, #endif if (!isFalcon) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -7022,7 +7133,7 @@ static int d2iTryDilithiumKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, #endif if (!isDilithium) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (*out != NULL) { @@ -7132,29 +7243,51 @@ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( WOLFSSL_PKCS8_PRIV_KEY_INFO* pkcs8 = NULL; #ifdef WOLFSSL_PEM_TO_DER int ret; - DerBuffer* der = NULL; + DerBuffer* pkcs8Der = NULL; + DerBuffer rawDer; + EncryptedInfo info; + int advanceLen = 0; + + XMEMSET(&info, 0, sizeof(info)); + XMEMSET(&rawDer, 0, sizeof(rawDer)); if (keyBuf == NULL || *keyBuf == NULL || keyLen <= 0) { WOLFSSL_MSG("Bad key PEM/DER args"); return NULL; } - ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &der, NULL, NULL, NULL); + ret = PemToDer(*keyBuf, keyLen, PRIVATEKEY_TYPE, &pkcs8Der, NULL, &info, + NULL); if (ret < 0) { WOLFSSL_MSG("Not PEM format"); - ret = AllocDer(&der, (word32)keyLen, PRIVATEKEY_TYPE, NULL); + ret = AllocDer(&pkcs8Der, (word32)keyLen, PRIVATEKEY_TYPE, NULL); if (ret == 0) { - XMEMCPY(der->buffer, *keyBuf, keyLen); + XMEMCPY(pkcs8Der->buffer, *keyBuf, keyLen); } } + else { + advanceLen = (int)info.consumed; + } if (ret == 0) { /* Verify this is PKCS8 Key */ word32 inOutIdx = 0; word32 algId; - ret = ToTraditionalInline_ex(der->buffer, &inOutIdx, der->length, - &algId); + ret = ToTraditionalInline_ex(pkcs8Der->buffer, &inOutIdx, + pkcs8Der->length, &algId); if (ret >= 0) { + if (advanceLen == 0) /* Set only if not PEM */ + advanceLen = inOutIdx + ret; + if (algId == DHk) { + /* Special case for DH as we expect the DER buffer to be always + * be in PKCS8 format */ + rawDer.buffer = pkcs8Der->buffer; + rawDer.length = inOutIdx + ret; + } + else { + rawDer.buffer = pkcs8Der->buffer + inOutIdx; + rawDer.length = ret; + } ret = 0; /* good DER */ } } @@ -7165,21 +7298,24 @@ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( ret = MEMORY_E; } if (ret == 0) { - pkcs8->pkey.ptr = (char*)XMALLOC(der->length, NULL, + pkcs8->pkey.ptr = (char*)XMALLOC(rawDer.length, NULL, DYNAMIC_TYPE_PUBLIC_KEY); if (pkcs8->pkey.ptr == NULL) ret = MEMORY_E; } if (ret == 0) { - XMEMCPY(pkcs8->pkey.ptr, der->buffer, der->length); - pkcs8->pkey_sz = (int)der->length; + XMEMCPY(pkcs8->pkey.ptr, rawDer.buffer, rawDer.length); + pkcs8->pkey_sz = (int)rawDer.length; } - FreeDer(&der); + FreeDer(&pkcs8Der); if (ret != 0) { wolfSSL_EVP_PKEY_free(pkcs8); pkcs8 = NULL; } + else { + *keyBuf += advanceLen; + } if (pkey != NULL) { *pkey = pkcs8; } @@ -7192,6 +7328,48 @@ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( return pkcs8; } +#ifdef OPENSSL_ALL +int wolfSSL_i2d_PKCS8_PKEY(WOLFSSL_PKCS8_PRIV_KEY_INFO* key, unsigned char** pp) +{ + word32 keySz = 0; + unsigned char* out; + int len; + + WOLFSSL_ENTER("wolfSSL_i2d_PKCS8_PKEY"); + + if (key == NULL) + return WOLFSSL_FATAL_ERROR; + + if (pkcs8_encode(key, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + return WOLFSSL_FATAL_ERROR; + len = (int)keySz; + + if (pp == NULL) + return len; + + if (*pp == NULL) { + out = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + if (out == NULL) + return WOLFSSL_FATAL_ERROR; + } + else { + out = *pp; + } + + if (pkcs8_encode(key, out, &keySz) != len) { + if (*pp == NULL) + XFREE(out, NULL, DYNAMIC_TYPE_ASN1); + return WOLFSSL_FATAL_ERROR; + } + + if (*pp == NULL) + *pp = out; + else + *pp += len; + + return len; +} +#endif #ifndef NO_BIO /* put SSL type in extra for now, not very common */ @@ -8337,6 +8515,8 @@ static int CheckcipherList(const char* list) char name[MAX_SUITE_NAME + 1]; word32 length = MAX_SUITE_NAME; word32 current_length; + byte major = INVALID_BYTE; + byte minor = INVALID_BYTE; next = XSTRSTR(next, ":"); @@ -8361,10 +8541,10 @@ static int CheckcipherList(const char* list) break; } - ret = wolfSSL_get_cipher_suite_from_name(name, &cipherSuite0, - &cipherSuite1, &flags); + ret = GetCipherSuiteFromName(name, &cipherSuite0, + &cipherSuite1, &major, &minor, &flags); if (ret == 0) { - if (cipherSuite0 == TLS13_BYTE) { + if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) { /* TLSv13 suite */ findTLSv13Suites = 1; } @@ -8465,10 +8645,6 @@ static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl, } /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */ - if (suites->suiteSz == 0) { - WOLFSSL_MSG("Warning suites->suiteSz = 0 set to WOLFSSL_MAX_SUITE_SZ"); - suites->suiteSz = WOLFSSL_MAX_SUITE_SZ; - } #ifdef WOLFSSL_SMALL_STACK if (suites->suiteSz > 0) { suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL, @@ -8495,6 +8671,12 @@ static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl, return WOLFSSL_FAILURE; } + /* The idea in this section is that OpenSSL has two API to set ciphersuites. + * - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites + * - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites + * Since we direct both API here we attempt to provide API compatibility. If + * we only get suites from <= 1.2 or == 1.3 then we will only update those + * suites and keep the suites from the other group. */ for (i = 0; i < suitesCpySz && suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) { /* Check for duplicates */ @@ -8884,14 +9066,14 @@ int wolfSSL_dtls_got_timeout(WOLFSSL* ssl) int result = WOLFSSL_SUCCESS; WOLFSSL_ENTER("wolfSSL_dtls_got_timeout"); - if (ssl == NULL) + if (ssl == NULL || !ssl->options.dtls) return WOLFSSL_FATAL_ERROR; #ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { + if (IsAtLeastTLSv1_3(ssl->version)) { result = Dtls13RtxTimeout(ssl); if (result < 0) { - if (result == WANT_WRITE) + if (result == WC_NO_ERR_TRACE(WANT_WRITE)) ssl->dtls13SendingAckOrRtx = 1; ssl->error = result; WOLFSSL_ERROR(result); @@ -8902,7 +9084,8 @@ int wolfSSL_dtls_got_timeout(WOLFSSL* ssl) } #endif /* WOLFSSL_DTLS13 */ - if ((IsSCR(ssl) || !ssl->options.handShakeDone)) { + /* Do we have any 1.2 messages stored? */ + if (ssl->dtls_tx_msg_list != NULL || ssl->dtls_tx_msg != NULL) { if (DtlsMsgPoolTimeout(ssl) < 0){ ssl->error = SOCKET_ERROR_E; WOLFSSL_ERROR(ssl->error); @@ -9231,7 +9414,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifdef WOLFSSL_ASYNC_CRYPT /* do not send buffered or advance state if last error was an async pending operation */ - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { ret = SendBuffered(ssl); @@ -9330,7 +9513,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, * should just ignore the message */ ssl->dtls13Rtx.sendAcks = 0; if ((ssl->error = SendDtls13Ack(ssl)) < 0) { - if (ssl->error == WANT_WRITE) + if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) ssl->dtls13SendingAckOrRtx = 1; WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; @@ -9431,7 +9614,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, ProcessReplyEx(ssl, 1); /* See if an alert was sent. */ #endif #ifdef WOLFSSL_EXTRA_ALERTS - if (ssl->error == NO_PEER_KEY || + if (ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY) || ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR)) { SendAlert(ssl, alert_fatal, handshake_failure); } @@ -9782,7 +9965,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifdef WOLFSSL_ASYNC_CRYPT /* do not send buffered or advance state if last error was an async pending operation */ - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { ret = SendBuffered(ssl); @@ -10098,7 +10281,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS); return WOLFSSL_SUCCESS; - default : + default: WOLFSSL_MSG("Unknown accept state ERROR"); return WOLFSSL_FATAL_ERROR; } @@ -10315,6 +10498,25 @@ int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn) } } +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) +const char *wolfSSL_get0_peername(WOLFSSL *ssl) { + if (ssl == NULL) { + return NULL; + } + + if (ssl->buffers.domainName.buffer) + return (const char *)ssl->buffers.domainName.buffer; + else if (ssl->session && ssl->session->peer) + return ssl->session->peer->subjectCN; + else if (ssl->peerCert.subjectCN[0]) + return ssl->peerCert.subjectCN; + else { + ssl->error = NO_PEER_CERT; + return NULL; + } +} + +#endif /* SESSION_CERTS && OPENSSL_EXTRA */ /* turn on wolfSSL zlib compression returns WOLFSSL_SUCCESS for success, else error (not built in) @@ -10357,7 +10559,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) sending += (int)iov[i].iov_len; if (sending > (int)sizeof(staticBuffer)) { - myBuffer = (byte*)XMALLOC(sending, ssl->heap, + myBuffer = (byte*)XMALLOC((size_t)sending, ssl->heap, DYNAMIC_TYPE_WRITEV); if (!myBuffer) return MEMORY_ERROR; @@ -10432,7 +10634,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb, TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout) { - int ret = WOLFSSL_FATAL_ERROR; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); int oldTimerOn = 0; /* was timer already on */ WOLFSSL_TIMEVAL startTime; WOLFSSL_TIMEVAL endTime; @@ -10887,8 +11089,11 @@ int wolfSSL_set_compression(WOLFSSL* ssl) { WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf"); - if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) + if (wolfSSL_add_all_algorithms() == + WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) + { return WOLFSSL_FATAL_ERROR; + } return WOLFSSL_SUCCESS; } @@ -10901,7 +11106,9 @@ int wolfSSL_set_compression(WOLFSSL* ssl) the use of a wolfssl.cnf type configuration file and is only used for OpenSSL compatibility. */ - if (wolfSSL_add_all_algorithms() == WOLFSSL_FATAL_ERROR) { + if (wolfSSL_add_all_algorithms() == + WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) + { return WOLFSSL_FATAL_ERROR; } return WOLFSSL_SUCCESS; @@ -10930,7 +11137,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #ifdef OPENSSL_EXTRA #ifndef NO_BIO - void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr) + static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags) { WOLFSSL_ENTER("wolfSSL_set_bio"); @@ -10941,8 +11148,8 @@ int wolfSSL_set_compression(WOLFSSL* ssl) /* free any existing WOLFSSL_BIOs in use but don't free those in * a chain */ - if (ssl->biord != NULL) { - if (ssl->biord != ssl->biowr) { + if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) { + if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) { if (ssl->biowr != NULL && ssl->biowr->prev != NULL) wolfSSL_BIO_free(ssl->biowr); ssl->biowr = NULL; @@ -10951,21 +11158,33 @@ int wolfSSL_set_compression(WOLFSSL* ssl) wolfSSL_BIO_free(ssl->biord); ssl->biord = NULL; } + else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) { + if (ssl->biowr->prev != NULL) + wolfSSL_BIO_free(ssl->biowr); + ssl->biowr = NULL; + } + /* set flag obviously */ if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ)) rd->flags |= WOLFSSL_BIO_FLAG_READ; if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE)) wr->flags |= WOLFSSL_BIO_FLAG_WRITE; - ssl->biord = rd; - ssl->biowr = wr; + if (flags & WOLFSSL_BIO_FLAG_READ) + ssl->biord = rd; + if (flags & WOLFSSL_BIO_FLAG_WRITE) + ssl->biowr = wr; /* set SSL to use BIO callbacks instead */ - if (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)) { - ssl->CBIORecv = BioReceive; + if ((flags & WOLFSSL_BIO_FLAG_READ) && + (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0))) + { + ssl->CBIORecv = SslBioReceive; } - if (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)) { - ssl->CBIOSend = BioSend; + if ((flags & WOLFSSL_BIO_FLAG_WRITE) && + (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0))) + { + ssl->CBIOSend = SslBioSend; } /* User programs should always retry reading from these BIOs */ @@ -10978,6 +11197,22 @@ int wolfSSL_set_compression(WOLFSSL* ssl) BIO_set_retry_read(wr); } } + + void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr) + { + ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE); + } + + void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd) + { + ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ); + } + + void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr) + { + ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE); + } + #endif /* !NO_BIO */ #endif /* OPENSSL_EXTRA */ @@ -11272,8 +11507,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) return WOLFSSL_FAILURE; } - if (wolfSSL_sk_X509_NAME_push(ctx->client_ca_names, nameCopy) != - WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_NAME_push(ctx->client_ca_names, nameCopy) <= 0) { WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); wolfSSL_X509_NAME_free(nameCopy); return WOLFSSL_FAILURE; @@ -11297,7 +11531,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_BIO* bio = NULL; WOLFSSL_X509 *cert = NULL; WOLFSSL_X509_NAME *nameCopy = NULL; - unsigned long err = WOLFSSL_FAILURE; + unsigned long err = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_load_client_CA_file"); @@ -11328,8 +11562,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) */ nameCopy->x509 = NULL; - if (wolfSSL_sk_X509_NAME_push(list, nameCopy) != - WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_NAME_push(list, nameCopy) <= 0) { WOLFSSL_MSG("wolfSSL_sk_X509_NAME_push error"); /* Do free in loop because nameCopy is now responsibility * of list to free and adding jumps to cleanup after this @@ -11490,16 +11723,12 @@ int wolfSSL_set_compression(WOLFSSL* ssl) wc_FreeRng(&rng); return WOLFSSL_FAILURE; } - if (ctx->srp_password != NULL){ - XFREE(ctx->srp_password,NULL, - DYNAMIC_TYPE_SRP); - ctx->srp_password = NULL; - } + XFREE(ctx->srp_password, NULL, DYNAMIC_TYPE_SRP); + ctx->srp_password = NULL; wc_FreeRng(&rng); } else { /* save password for wolfSSL_set_srp_username */ - if (ctx->srp_password != NULL) - XFREE(ctx->srp_password,ctx->heap, DYNAMIC_TYPE_SRP); + XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); ctx->srp_password = (byte*)XMALLOC(XSTRLEN(password) + 1, ctx->heap, DYNAMIC_TYPE_SRP); @@ -11673,7 +11902,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_MSG("wolfSSL options are set through API calls and macros"); if(ctx == NULL) return BAD_FUNC_ARG; - return ctx->mask; + return (long)ctx->mask; } /* forward declaration */ @@ -11686,7 +11915,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) if (ctx == NULL) return BAD_FUNC_ARG; - ctx->mask = wolf_set_options(ctx->mask, opt); + ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt); #if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \ || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)) if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) { @@ -11702,7 +11931,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #endif */ #endif - return ctx->mask; + return (long)ctx->mask; } long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt) @@ -11710,8 +11939,8 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_CTX_clear_options"); if(ctx == NULL) return BAD_FUNC_ARG; - ctx->mask &= ~opt; - return ctx->mask; + ctx->mask &= (unsigned long)~opt; + return (long)ctx->mask; } #ifdef OPENSSL_EXTRA @@ -12129,8 +12358,9 @@ int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey) int sz; PRIVATE_KEY_UNLOCK(); - if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz) != - LENGTH_ONLY_E) { + if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz) + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + { WOLFSSL_MSG("get ecc der size failed"); PRIVATE_KEY_LOCK(); return WOLFSSL_FAILURE; @@ -12530,7 +12760,7 @@ static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver) int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version) { int i; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int minProto; WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version"); @@ -12651,7 +12881,7 @@ static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver) int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version) { int i; - int ret = WOLFSSL_FAILURE;; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);; WOLFSSL_ENTER("wolfSSL_set_min_proto_version"); @@ -12719,7 +12949,7 @@ static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver) int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version) { int i; - int ret = WOLFSSL_FAILURE;; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);; WOLFSSL_ENTER("wolfSSL_set_max_proto_version"); @@ -12857,7 +13087,7 @@ int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx) WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret); - if (ret == WOLFSSL_FATAL_ERROR) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { WOLFSSL_MSG("Error getting max proto version"); ret = 0; /* setting ret to 0 to match compat return */ } @@ -13031,6 +13261,10 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, ssl->keys.encryptionOn = 0; XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived)); + FreeCiphers(ssl); + InitCiphers(ssl); + InitCipherSpecs(&ssl->specs); + if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS) return WOLFSSL_FAILURE; @@ -13045,7 +13279,11 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, #ifdef WOLFSSL_QUIC wolfSSL_quic_clear(ssl); #endif - +#ifdef HAVE_OCSP +#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) + ssl->response_idx = 0; +#endif +#endif return WOLFSSL_SUCCESS; } @@ -13074,7 +13312,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, } /* SSL_MODE_AUTO_RETRY - * Should not return -1 with renegotiation on read/write */ + * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */ return mode; } @@ -13101,7 +13339,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, } /* SSL_MODE_AUTO_RETRY - * Should not return -1 with renegotiation on read/write */ + * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */ return 0; } @@ -13410,7 +13648,7 @@ static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm, i--; for (; i >= 0; i--) { if (push) { - if (wolfSSL_sk_X509_push(sk, issuer[i]) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(sk, issuer[i]) <= 0) { wolfSSL_X509_free(issuer[i]); ret = WOLFSSL_FATAL_ERROR; push = 0; /* Free the rest of the unpushed certs */ @@ -13456,13 +13694,13 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) * first if we have one for this cert */ SSL_CM_WARNING(ssl); if (PushCAx509Chain(SSL_CM(ssl), x509, sk) - == WOLFSSL_FATAL_ERROR) { + == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { ret = WOLFSSL_FATAL_ERROR; } } #endif - if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) <= 0) { WOLFSSL_MSG("Error decoding cert"); wolfSSL_X509_free(x509); wolfSSL_sk_X509_pop_free(sk, NULL); @@ -13552,71 +13790,85 @@ static WC_INLINE int compare_WOLFSSL_CIPHER( (a->bits == b->bits)) return 0; else - return -1; + return WOLFSSL_FATAL_ERROR; } #endif /* OPENSSL_ALL || WOLFSSL_QT */ -/* return 1 on success 0 on fail */ +/* return number of elements on success 0 on fail */ int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) +{ + WOLFSSL_ENTER("wolfSSL_sk_push"); + + return wolfSSL_sk_insert(sk, data, 0); +} + +/* return number of elements on success 0 on fail */ +int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx) { WOLFSSL_STACK* node; #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) WOLFSSL_CIPHER ciph; #endif - WOLFSSL_ENTER("wolfSSL_sk_push"); + WOLFSSL_ENTER("wolfSSL_sk_insert"); - if (!sk) { + if (!sk) + return WOLFSSL_FATAL_ERROR; + if (!data) return WOLFSSL_FAILURE; - } - /* Check if empty data */ - switch (sk->type) { - case STACK_TYPE_CIPHER: + if (idx == 0 || sk->num == 0) { + /* Check if empty data */ + switch (sk->type) { + case STACK_TYPE_CIPHER: #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - /* check if entire struct is zero */ - XMEMSET(&ciph, 0, sizeof(WOLFSSL_CIPHER)); - if (compare_WOLFSSL_CIPHER(&sk->data.cipher, &ciph) == 0) { - sk->data.cipher = *(WOLFSSL_CIPHER*)data; - sk->num = 1; - if (sk->hash_fn) { - sk->hash = sk->hash_fn(&sk->data.cipher); + /* check if entire struct is zero */ + XMEMSET(&ciph, 0, sizeof(WOLFSSL_CIPHER)); + if (compare_WOLFSSL_CIPHER(&sk->data.cipher, &ciph) == 0) { + sk->data.cipher = *(WOLFSSL_CIPHER*)data; + sk->num = 1; + if (sk->hash_fn) { + sk->hash = sk->hash_fn(&sk->data.cipher); + } + return (int)sk->num; } - return WOLFSSL_SUCCESS; - } - break; + if (sk->num == 0) + sk->num = 1; /* confirmed at least one element */ + break; #endif - case STACK_TYPE_X509: - case STACK_TYPE_GEN_NAME: - case STACK_TYPE_BIO: - case STACK_TYPE_OBJ: - case STACK_TYPE_STRING: - case STACK_TYPE_ACCESS_DESCRIPTION: - case STACK_TYPE_X509_EXT: - case STACK_TYPE_X509_REQ_ATTR: - case STACK_TYPE_NULL: - case STACK_TYPE_X509_NAME: - case STACK_TYPE_X509_NAME_ENTRY: - case STACK_TYPE_CONF_VALUE: - case STACK_TYPE_X509_INFO: - case STACK_TYPE_BY_DIR_entry: - case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: - case STACK_TYPE_DIST_POINT: - case STACK_TYPE_X509_CRL: - default: - /* All other types are pointers */ - if (!sk->data.generic) { - sk->data.generic = (void*)data; - sk->num = 1; + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + /* All other types are pointers */ + if (!sk->data.generic) { + sk->data.generic = (void*)data; + sk->num = 1; #ifdef OPENSSL_ALL - if (sk->hash_fn) { - sk->hash = sk->hash_fn(sk->data.generic); - } + if (sk->hash_fn) + sk->hash = sk->hash_fn(sk->data.generic); #endif - return WOLFSSL_SUCCESS; - } - break; + return (int)sk->num; + } + if (sk->num == 0) + sk->num = 1; /* confirmed at least one element */ + break; + } } /* stack already has value(s) create a new node and add more */ @@ -13625,26 +13877,71 @@ int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) WOLFSSL_MSG("Memory error"); return WOLFSSL_FAILURE; } - - /* push new x509 onto head of stack */ - node->next = sk->next; node->type = sk->type; - sk->next = node; sk->num += 1; - #ifdef OPENSSL_ALL node->hash_fn = sk->hash_fn; - node->hash = sk->hash; - sk->hash = 0; #endif + + if (idx == 0) { + /* Special case where we need to change the values in the head element + * to avoid changing the initial pointer. */ + /* push new item onto head of stack */ + node->next = sk->next; + sk->next = node; +#ifdef OPENSSL_ALL + node->hash = sk->hash; + sk->hash = 0; +#endif + switch (sk->type) { + case STACK_TYPE_CIPHER: +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + node->data.cipher = sk->data.cipher; + sk->data.cipher = *(WOLFSSL_CIPHER*)data; + if (sk->hash_fn) { + sk->hash = sk->hash_fn(&sk->data.cipher); + } + break; +#endif + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + /* All other types are pointers */ + node->data.generic = sk->data.generic; + sk->data.generic = (void*)data; +#ifdef OPENSSL_ALL + if (sk->hash_fn) + sk->hash = sk->hash_fn(sk->data.generic); +#endif + break; + } + + return (int)sk->num; + } + + /* populate node */ switch (sk->type) { case STACK_TYPE_CIPHER: #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - node->data.cipher = sk->data.cipher; - sk->data.cipher = *(WOLFSSL_CIPHER*)data; - if (sk->hash_fn) { - sk->hash = sk->hash_fn(&sk->data.cipher); - } + node->data.cipher = *(WOLFSSL_CIPHER*)data; + if (node->hash_fn) + node->hash = node->hash_fn(&node->data.cipher); break; #endif case STACK_TYPE_X509: @@ -13667,17 +13964,25 @@ int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) case STACK_TYPE_X509_CRL: default: /* All other types are pointers */ - node->data.generic = sk->data.generic; - sk->data.generic = (void*)data; + node->data.generic = (void*)data; #ifdef OPENSSL_ALL - if (sk->hash_fn) { - sk->hash = sk->hash_fn(sk->data.generic); - } + if (node->hash_fn) + node->hash = node->hash_fn(node->data.generic); #endif break; } + { + /* insert node into stack. not using sk since we return sk->num after */ + WOLFSSL_STACK* prev_node = sk; + while (idx != 0 && prev_node->next != NULL) { + prev_node = prev_node->next; + idx--; + } + node->next = prev_node->next; + prev_node->next = node; + } - return WOLFSSL_SUCCESS; + return (int)sk->num; } #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ @@ -14106,7 +14411,8 @@ int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0, (cipherSuite == NULL) || (flags == NULL)) return BAD_FUNC_ARG; - return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, flags); + return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL, + flags); } @@ -14149,7 +14455,7 @@ word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher) WOLFSSL_ENTER("wolfSSL_CIPHER_get_id"); if (cipher && cipher->ssl) { - cipher_id = (cipher->ssl->options.cipherSuite0 << 8) | + cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) | cipher->ssl->options.cipherSuite; } @@ -14247,9 +14553,6 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) return "P384_KYBER_LEVEL3"; case WOLFSSL_P521_KYBER_LEVEL5: return "P521_KYBER_LEVEL5"; -#elif defined(HAVE_PQM4) - case WOLFSSL_KYBER_LEVEL1: - return "KYBER_LEVEL1"; #elif defined(WOLFSSL_WC_KYBER) #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: @@ -14549,7 +14852,9 @@ int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher) authStr = GetCipherAuthStr(n); /* encStr */ encStr = GetCipherEncStr(n); - if ((cipher->bits = SetCipherBits(encStr)) == WOLFSSL_FAILURE) { + if ((cipher->bits = SetCipherBits(encStr)) == + WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { WOLFSSL_MSG("Cipher Bits Not Set."); } /* macStr */ @@ -14805,7 +15110,7 @@ static WC_INLINE const char* wolfssl_mac_to_string(int mac) macStr = "SHA1"; break; #endif -#ifdef HAVE_SHA224 +#ifdef WOLFSSL_SHA224 case sha224_mac: macStr = "SHA224"; break; @@ -14815,12 +15120,12 @@ static WC_INLINE const char* wolfssl_mac_to_string(int mac) macStr = "SHA256"; break; #endif -#ifdef HAVE_SHA384 +#ifdef WOLFSSL_SHA384 case sha384_mac: macStr = "SHA384"; break; #endif -#ifdef HAVE_SHA512 +#ifdef WOLFSSL_SHA512 case sha512_mac: macStr = "SHA512"; break; @@ -14894,20 +15199,80 @@ char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, return ret; } - -#ifndef NO_WOLFSSL_STUB -int wolfSSL_OCSP_parse_url(char* url, char** host, char** port, char** path, - int* ssl) +int wolfSSL_OCSP_parse_url(const char* url, char** host, char** port, + char** path, int* ssl) { - (void)url; - (void)host; - (void)port; - (void)path; - (void)ssl; - WOLFSSL_STUB("OCSP_parse_url"); - return 0; + const char* u = url; + const char* upath; /* path in u */ + const char* uport; /* port in u */ + const char* hostEnd; + + WOLFSSL_ENTER("OCSP_parse_url"); + + *host = NULL; + *port = NULL; + *path = NULL; + *ssl = 0; + + if (*(u++) != 'h') goto err; + if (*(u++) != 't') goto err; + if (*(u++) != 't') goto err; + if (*(u++) != 'p') goto err; + if (*u == 's') { + *ssl = 1; + u++; + *port = CopyString("443", -1, NULL, DYNAMIC_TYPE_OPENSSL); + } + else if (*u == ':') { + *ssl = 0; + *port = CopyString("80", -1, NULL, DYNAMIC_TYPE_OPENSSL); + } + else + goto err; + if (*port == NULL) + goto err; + if (*(u++) != ':') goto err; + if (*(u++) != '/') goto err; + if (*(u++) != '/') goto err; + + /* Look for path */ + upath = XSTRSTR(u, "/"); + *path = CopyString(upath == NULL ? "/" : upath, -1, NULL, + DYNAMIC_TYPE_OPENSSL); + + /* Look for port */ + uport = XSTRSTR(u, ":"); + if (uport != NULL) { + if (*(++uport) == '\0') + goto err; + /* port must be before path */ + if (upath != NULL && uport >= upath) + goto err; + XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL); + *port = CopyString(uport, upath != NULL ? (int)(upath - uport) : -1, + NULL, DYNAMIC_TYPE_OPENSSL); + if (*port == NULL) + goto err; + hostEnd = uport - 1; + } + else + hostEnd = upath; + + *host = CopyString(u, hostEnd != NULL ? (int)(hostEnd - u) : -1, NULL, + DYNAMIC_TYPE_OPENSSL); + if (*host == NULL) + goto err; + + return WOLFSSL_SUCCESS; +err: + XFREE(*host, NULL, DYNAMIC_TYPE_OPENSSL); + *host = NULL; + XFREE(*port, NULL, DYNAMIC_TYPE_OPENSSL); + *port = NULL; + XFREE(*path, NULL, DYNAMIC_TYPE_OPENSSL); + *path = NULL; + return WOLFSSL_FAILURE; } -#endif #ifndef NO_WOLFSSL_STUB WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void) @@ -14915,17 +15280,13 @@ WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void) WOLFSSL_STUB("COMP_zlib"); return 0; } -#endif -#ifndef NO_WOLFSSL_STUB WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void) { WOLFSSL_STUB("COMP_rle"); return 0; } -#endif -#ifndef NO_WOLFSSL_STUB int wolfSSL_COMP_add_compression_method(int method, void* data) { (void)method; @@ -14933,10 +15294,18 @@ int wolfSSL_COMP_add_compression_method(int method, void* data) WOLFSSL_STUB("COMP_add_compression_method"); return 0; } -#endif -#ifndef NO_WOLFSSL_STUB -const char* wolfSSL_COMP_get_name(const void* comp) +const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) { + (void)ssl; + return NULL; +} + +const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) { + (void)ssl; + return NULL; +} + +const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp) { static const char ret[] = "not supported"; @@ -15287,7 +15656,7 @@ int wolfSSL_ERR_GET_REASON(unsigned long err) /* Nginx looks for this error to know to stop parsing certificates. * Same for HAProxy. */ if (err == ((ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE) || - ((err & 0xFFFFFFL) == -ASN_NO_PEM_HEADER) || + ((err & 0xFFFFFFL) == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) || ((err & 0xFFFL) == PEM_R_NO_START_LINE )) return PEM_R_NO_START_LINE; if (err == ((ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST)) @@ -15302,7 +15671,9 @@ int wolfSSL_ERR_GET_REASON(unsigned long err) ret = 0 - ret; /* setting as negative value */ /* wolfCrypt range is less than MAX (-100) wolfSSL range is MIN (-300) and lower */ - if (ret < MAX_CODE_E && ret > MIN_CODE_E) { + if ((ret <= WC_FIRST_E && ret >= WC_LAST_E) || + (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E)) + { return ret; } else { @@ -15774,7 +16145,7 @@ long wolfSSL_set_options(WOLFSSL* ssl, long op) return 0; } - ssl->options.mask = wolf_set_options(ssl->options.mask, op); + ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op); if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { WOLFSSL_MSG("Disabling TLS 1.3"); @@ -15840,11 +16211,14 @@ long wolfSSL_set_options(WOLFSSL* ssl, long op) else { /* Only preserve overlapping suites */ Suites tmpSuites; - word16 in, out, haveECDSAsig = 0; - word16 haveStaticECC = ssl->options.haveStaticECC; + word16 in, out; + word16 haveECDSAsig, haveStaticECC; #ifdef NO_RSA haveECDSAsig = 1; haveStaticECC = 1; +#else + haveECDSAsig = 0; + haveStaticECC = ssl->options.haveStaticECC; #endif XMEMSET(&tmpSuites, 0, sizeof(Suites)); /* Get all possible ciphers and sigalgs for the version. Following @@ -15877,7 +16251,7 @@ long wolfSSL_set_options(WOLFSSL* ssl, long op) } } - return ssl->options.mask; + return (long)ssl->options.mask; } @@ -15886,7 +16260,7 @@ long wolfSSL_get_options(const WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_get_options"); if(ssl == NULL) return WOLFSSL_FAILURE; - return ssl->options.mask; + return (long)ssl->options.mask; } #if defined(HAVE_SECURE_RENEGOTIATION) \ @@ -16844,7 +17218,7 @@ int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk) #if defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM) int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) { - int ret = WOLFSSL_FATAL_ERROR; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); WOLFSSL_ENTER("wolfSSL_cmp_peer_cert_to_file"); if (ssl != NULL && fname != NULL) @@ -17826,7 +18200,7 @@ int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, NULL, &szNeeded) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return WOLFSSL_FAILURE; *outLen = szNeeded + headerLen + footerLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* don't even try if inLen too short */ @@ -18838,7 +19212,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) #endif if (o == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef WOLFSSL_QT @@ -18858,7 +19232,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) byte* buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (!buf) { WOLFSSL_MSG("malloc error"); - return -1; + return WOLFSSL_FATAL_ERROR; } idx = SetObjectId(o->objSz, buf); XMEMCPY(buf + idx, o->obj, o->objSz); @@ -18867,12 +19241,12 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (ret < 0) { WOLFSSL_MSG("Issue getting OID of object"); - return -1; + return WOLFSSL_FATAL_ERROR; } } else { WOLFSSL_MSG("Issue getting OID of object"); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -19137,11 +19511,11 @@ unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line) } #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \ || defined(WOLFSSL_HAPROXY) - if (ret == -ASN_NO_PEM_HEADER) + if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; #endif #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - if (ret == ASN1_R_HEADER_TOO_LONG) { + if (ret == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) { return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; } #endif @@ -19168,7 +19542,7 @@ static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr, CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC( sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL); if (new_ctx == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; new_ctx->ctx_l = ctx_l; new_ctx->ctx_ptr = ctx_ptr; new_ctx->new_func = new_func; @@ -19272,7 +19646,7 @@ int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, case WOLF_CRYPTO_EX_INDEX_SSL_SESSION: if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr, new_func, dup_func, free_func) != 0) - return -1; + return WOLFSSL_FATAL_ERROR; idx = ssl_session_idx++; break; @@ -19293,7 +19667,7 @@ int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, break; } if (idx >= MAX_EX_DATA) - return -1; + return WOLFSSL_FATAL_ERROR; return idx; } #endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */ @@ -19488,11 +19862,15 @@ void wolfSSL_certs_clear(WOLFSSL* ssl) return; /* ctx still owns certificate, certChain, key, dh, and cm */ - if (ssl->buffers.weOwnCert) + if (ssl->buffers.weOwnCert) { FreeDer(&ssl->buffers.certificate); + ssl->buffers.weOwnCert = 0; + } ssl->buffers.certificate = NULL; - if (ssl->buffers.weOwnCertChain) + if (ssl->buffers.weOwnCertChain) { FreeDer(&ssl->buffers.certChain); + ssl->buffers.weOwnCertChain = 0; + } ssl->buffers.certChain = NULL; #ifdef WOLFSSL_TLS13 ssl->buffers.certChainCnt = 0; @@ -19502,6 +19880,7 @@ void wolfSSL_certs_clear(WOLFSSL* ssl) #ifdef WOLFSSL_BLIND_PRIVATE_KEY FreeDer(&ssl->buffers.keyMask); #endif + ssl->buffers.weOwnKey = 0; } ssl->buffers.key = NULL; #ifdef WOLFSSL_BLIND_PRIVATE_KEY @@ -19518,6 +19897,7 @@ void wolfSSL_certs_clear(WOLFSSL* ssl) #ifdef WOLFSSL_BLIND_PRIVATE_KEY FreeDer(&ssl->buffers.altKeyMask); #endif + ssl->buffers.weOwnAltKey = 0; } ssl->buffers.altKey = NULL; #ifdef WOLFSSL_BLIND_PRIVATE_KEY @@ -19971,7 +20351,7 @@ int wolfSSL_FIPS_mode_set(int r) int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits"); #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) @@ -20092,25 +20472,82 @@ WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) ssl->ctx = ctx; #ifndef NO_CERTS +#ifdef WOLFSSL_COPY_CERT + /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */ + if (ctx->certificate != NULL) { + if (ssl->buffers.certificate != NULL) { + FreeDer(&ssl->buffers.certificate); + ssl->buffers.certificate = NULL; + } + ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer, + ctx->certificate->length, ctx->certificate->type, + ctx->certificate->heap); + if (ret != 0) { + ssl->buffers.weOwnCert = 0; + return NULL; + } + + ssl->buffers.weOwnCert = 1; + } + if (ctx->certChain != NULL) { + if (ssl->buffers.certChain != NULL) { + FreeDer(&ssl->buffers.certChain); + ssl->buffers.certChain = NULL; + } + ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer, + ctx->certChain->length, ctx->certChain->type, + ctx->certChain->heap); + if (ret != 0) { + ssl->buffers.weOwnCertChain = 0; + return NULL; + } + + ssl->buffers.weOwnCertChain = 1; + } +#else /* ctx owns certificate, certChain and key */ ssl->buffers.certificate = ctx->certificate; ssl->buffers.certChain = ctx->certChain; +#endif #ifdef WOLFSSL_TLS13 ssl->buffers.certChainCnt = ctx->certChainCnt; #endif #ifndef WOLFSSL_BLIND_PRIVATE_KEY +#ifdef WOLFSSL_COPY_KEY + if (ctx->privateKey != NULL) { + if (ssl->buffers.key != NULL) { + FreeDer(&ssl->buffers.key); + ssl->buffers.key = NULL; + } + ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ctx->privateKey->length, ctx->privateKey->type, + ctx->privateKey->heap); + if (ret != 0) { + ssl->buffers.weOwnKey = 0; + return NULL; + } + ssl->buffers.weOwnKey = 1; + } + else { + ssl->buffers.key = ctx->privateKey; + } +#else ssl->buffers.key = ctx->privateKey; +#endif #else if (ctx->privateKey != NULL) { - AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, + ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer, ctx->privateKey->length, ctx->privateKey->type, ctx->privateKey->heap); + if (ret != 0) { + return NULL; + } /* Blind the private key for the SSL with new random mask. */ wolfssl_priv_der_unblind(ssl->buffers.key, ctx->privateKeyMask); ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key, &ssl->buffers.keyMask); if (ret != 0) { - return ret; + return NULL; } } #endif @@ -20132,15 +20569,18 @@ WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) ssl->buffers.altKey = ctx->altPrivateKey; #else if (ctx->altPrivateKey != NULL) { - AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, + ret = AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer, ctx->altPrivateKey->length, ctx->altPrivateKey->type, ctx->altPrivateKey->heap); + if (ret != 0) { + return NULL; + } /* Blind the private key for the SSL with new random mask. */ wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask); ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey, &ssl->buffers.altKeyMask); if (ret != 0) { - return ret; + return NULL; } } #endif @@ -20168,7 +20608,7 @@ VerifyCallback wolfSSL_CTX_get_verify_callback(WOLFSSL_CTX* ctx) } #ifdef HAVE_SNI -/* this is a compatibily function, consider using +/* this is a compatibility function, consider using * wolfSSL_CTX_set_servername_callback */ int wolfSSL_CTX_set_tlsext_servername_callback(WOLFSSL_CTX* ctx, CallbackSniRecv cb) @@ -20260,10 +20700,10 @@ unsigned long wolfSSL_ERR_peek_last_error(void) WOLFSSL_MSG("Issue peeking at error node in queue"); return 0; } - if (ret == -ASN_NO_PEM_HEADER) + if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; #if defined(WOLFSSL_PYTHON) - if (ret == ASN1_R_HEADER_TOO_LONG) + if (ret == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; #endif return (unsigned long)ret; @@ -21249,8 +21689,7 @@ void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s) { WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free"); - if (s != NULL) - XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL); } void wolfSSL_sk_WOLFSSL_STRING_free(WOLF_STACK_OF(WOLFSSL_STRING)* sk) @@ -21460,12 +21899,12 @@ const WOLF_EC_NIST_NAME kNistCurves[] = { #endif #ifdef WOLFSSL_HAVE_KYBER {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1}, - {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL1}, - {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL1}, + {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3}, + {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5}, #if (defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_P256_KYBER_LEVEL1}, - {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P256_KYBER_LEVEL1}, - {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_P256_KYBER_LEVEL1}, + {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P384_KYBER_LEVEL3}, + {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_P521_KYBER_LEVEL5}, #endif #endif #ifdef WOLFSSL_SM2 @@ -21618,9 +22057,9 @@ int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, #endif /* HAVE_SUPPORTED_CURVES */ } - if (ssl) + if (ssl != NULL) ssl->disabledCurves = disabled; - else + else if (ctx != NULL) ctx->disabledCurves = disabled; ret = WOLFSSL_SUCCESS; @@ -22646,7 +23085,7 @@ int oid2nid(word32 oid, int grp) } } - return -1; + return WOLFSSL_FATAL_ERROR; } /* frees all nodes in the current threads error queue @@ -22663,7 +23102,7 @@ void wolfSSL_ERR_remove_state(unsigned long id) } } -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA */ #ifdef OPENSSL_ALL @@ -23240,6 +23679,18 @@ int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff) return WOLFSSL_SUCCESS; } +/* wolfSSL_CTX_set_dh_auto is provided as compatible API with + * SSL_CTX_set_dh_auto to enable auto dh selection functionality. + * Since this functionality is enabled by default in wolfSSL, + * this API exists as a stub. + */ +int wolfSSL_CTX_set_dh_auto(WOLFSSL_CTX* ctx, int onoff) +{ + (void)ctx; + (void)onoff; + return WOLFSSL_SUCCESS; +} + /** * set security level (wolfSSL doesn't support security level) * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure @@ -23273,7 +23724,7 @@ void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx, wolfSSL_CTX_keylog_cb_func cb) { WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback"); - /* stores the callback into WOLFSSL_CTX */ + /* stores the callback into WOLFSSL_CTX */ if (ctx != NULL) { ctx->keyLogCb = cb; } @@ -23284,14 +23735,92 @@ wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback( WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback"); if (ctx != NULL) return ctx->keyLogCb; - else - return NULL; + return NULL; } #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */ #endif /* OPENSSL_EXTRA */ -#ifndef NO_CERTS +#ifdef WOLFSSL_THREADED_CRYPT +int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx) +{ + ThreadCrypt* encrypt; + + if (ssl == NULL) { + return 0; + } + + encrypt = &ssl->buffers.encrypt[idx]; + return (encrypt->avail == 0) && (encrypt->done == 0); +} + +int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx) +{ + ThreadCrypt* encrypt; + + if (ssl == NULL) { + return 1; + } + + encrypt = &ssl->buffers.encrypt[idx]; + return encrypt->stop; +} + +int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx) +{ + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); + ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx]; + + if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) { + unsigned char* out = encrypt->buffer.buffer + encrypt->offset; + unsigned char* input = encrypt->buffer.buffer + encrypt->offset; + word32 encSz = encrypt->buffer.length - encrypt->offset; + + ret = +#if !defined(NO_GCM_ENCRYPT_EXTRA) && \ + ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))) + wc_AesGcmEncrypt_ex +#else + wc_AesGcmEncrypt +#endif + (encrypt->encrypt.aes, + out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ, + encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, + encrypt->nonce, AESGCM_NONCE_SZ, + out + encSz - ssl->specs.aead_mac_size, + ssl->specs.aead_mac_size, + encrypt->additional, AEAD_AUTH_DATA_SZ); +#if !defined(NO_PUBLIC_GCM_SET_IV) && \ + ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ + (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))) + XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ); +#endif + encrypt->done = 1; + } + + return ret; +} + +int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx, + WOLFSSL_THREAD_SIGNAL signal, void* ctx) +{ + int ret = 0; + + if (ssl == NULL) { + ret = BAD_FUNC_ARG; + } + else { + ssl->buffers.encrypt[idx].signal = signal; + ssl->buffers.encrypt[idx].signalCtx = ctx; + } + + return ret; +} +#endif + + +#ifndef NO_CERT #define WOLFSSL_X509_INCLUDED #include "src/x509.c" #endif @@ -23561,10 +24090,8 @@ int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len) void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf) { if (buf) { - if (buf->data) { - XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL); - buf->data = NULL; - } + XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL); + buf->data = NULL; buf->max = 0; buf->length = 0; XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL); @@ -23609,7 +24136,7 @@ static int wolfSSL_RAND_InitMutex(void) */ int wolfSSL_RAND_Init(void) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifdef HAVE_GLOBAL_RNG if (wc_LockMutex(&globalRNGMutex) == 0) { if (initGlobalRNG == 0) { @@ -23665,7 +24192,7 @@ int wolfSSL_RAND_seed(const void* seed, int len) */ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) { -#if !defined(NO_FILESYSTEM) && defined(XGETENV) +#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV) char* rt; WOLFSSL_ENTER("wolfSSL_RAND_file_name"); @@ -23676,6 +24203,7 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) XMEMSET(fname, 0, len); +/* // NOLINTBEGIN(concurrency-mt-unsafe) */ if ((rt = XGETENV("RANDFILE")) != NULL) { if (len > XSTRLEN(rt)) { XMEMCPY(fname, rt, XSTRLEN(rt)); @@ -23685,6 +24213,7 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) rt = NULL; } } +/* // NOLINTEND(concurrency-mt-unsafe) */ /* $RANDFILE was not set or is too large, check $HOME */ if (rt == NULL) { @@ -23692,6 +24221,7 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) WOLFSSL_MSG("Environment variable RANDFILE not set"); +/* // NOLINTBEGIN(concurrency-mt-unsafe) */ if ((rt = XGETENV("HOME")) == NULL) { #ifdef XALTHOMEVARNAME if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) { @@ -23704,6 +24234,7 @@ const char* wolfSSL_RAND_file_name(char* fname, unsigned long len) return NULL; #endif } +/* // NOLINTEND(concurrency-mt-unsafe) */ if (len > XSTRLEN(rt) + XSTRLEN(ap)) { fname[0] = '\0'; @@ -24139,8 +24670,7 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num) if (initTmpRng) wc_FreeRng(tmpRNG); #ifdef WOLFSSL_SMALL_STACK - if (tmpRNG) - XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); + XFREE(tmpRNG, NULL, DYNAMIC_TYPE_RNG); #endif return ret; @@ -24626,7 +25156,7 @@ void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, #if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG) int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL) { XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX)); ctx->type = type; @@ -24638,7 +25168,7 @@ int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags) } WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX), NULL, DYNAMIC_TYPE_OPENSSL); ret = wolfSSL_FIPS_drbg_init(ctx, type, flags); @@ -24655,7 +25185,7 @@ WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags) int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx, const unsigned char* pers, size_t perslen) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL && ctx->rng == NULL) { #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \ (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0))) @@ -24689,7 +25219,7 @@ int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx, size_t entropy_blocklen, drbg_nonce_get none_get, drbg_nonce_clean nonce_clean) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL) { ctx->entropy_get = entropy_get; ctx->entropy_clean = entropy_clean; @@ -24710,7 +25240,7 @@ void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy) int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin, size_t adinlen) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL && ctx->rng != NULL) { #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \ (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0))) @@ -24729,7 +25259,7 @@ int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out, size_t outlen, int prediction_resistance, const unsigned char* adin, size_t adinlen) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL && ctx->rng != NULL) { ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen); if (ret == 0) { diff --git a/src/src/ssl_asn1.c b/src/src/ssl_asn1.c index b93d8d5..95f9cca 100644 --- a/src/src/ssl_asn1.c +++ b/src/src/ssl_asn1.c @@ -1,6 +1,6 @@ /* ssl_asn1.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -46,212 +46,197 @@ #ifdef OPENSSL_ALL -/* Create an ASN1 item of the specified type. - * - * @param [out] item Pointer to location to place new ASN1 item. - * @param [in] type Type of ASN1 item to create. - * @return 0 on success. - * @return 1 when item type not supported. - * @return 1 when item type allocation fails. - */ -static int wolfssl_asn1_item_new(void** item, int type) +/* Provides access to the member of the obj offset by offset */ +#define asn1Mem(obj, offset) (*(void**)(((byte*)(obj)) + (offset))) +#define asn1Type(obj, offset) (*(int*)(((byte*)(obj)) + (offset))) + +static void* asn1_new_tpl(const WOLFSSL_ASN1_TEMPLATE *mem) { - int err = 0; + if (mem->sequence) + return wolfSSL_sk_new_null(); + else + return mem->new_func(); +} - switch (type) { - case WOLFSSL_X509_ALGOR_ASN1: - *(WOLFSSL_X509_ALGOR**)item = wolfSSL_X509_ALGOR_new(); +static void* asn1_item_alloc(const WOLFSSL_ASN1_ITEM* item) +{ + void* ret = NULL; + + /* allocation */ + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + case WOLFSSL_ASN1_CHOICE: + ret = (void *)XMALLOC(item->size, NULL, DYNAMIC_TYPE_OPENSSL); + if (ret != NULL) + XMEMSET(ret, 0, item->size); break; - case WOLFSSL_ASN1_BIT_STRING_ASN1: - *(WOLFSSL_ASN1_BIT_STRING**)item = wolfSSL_ASN1_BIT_STRING_new(); + case WOLFSSL_ASN1_OBJECT_TYPE: + if (item->mcount != 1 || item->members->offset) { + WOLFSSL_MSG("incorrect member count or offset"); + return NULL; + } + ret = asn1_new_tpl(item->members); break; - case WOLFSSL_ASN1_INTEGER_ASN1: - *(WOLFSSL_ASN1_INTEGER**)item = wolfSSL_ASN1_INTEGER_new(); - break; default: - WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_new"); - *(void**)item = NULL; + WOLFSSL_MSG("ASN1 type not implemented"); + return NULL; } - /* Check whether an item was put in. */ - if (*(void**)item == NULL) { - err = 1; + + return ret; +} + +static int asn1_item_init(void* obj, const WOLFSSL_ASN1_ITEM* item) +{ + const WOLFSSL_ASN1_TEMPLATE *mem = NULL; + size_t i; + int ret = 0; + + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) { + asn1Mem(obj, mem->offset) = asn1_new_tpl(mem); + if (asn1Mem(obj, mem->offset) == NULL) { + ret = WOLFSSL_FATAL_ERROR; + break; + } + } + break; + case WOLFSSL_ASN1_OBJECT_TYPE: + /* Initialized by new_func. Nothing to do. */ + break; + case WOLFSSL_ASN1_CHOICE: + asn1Type(obj, item->toffset) = -1; + /* We don't know what to initialize. Nothing to do. */ + break; + default: + WOLFSSL_MSG("ASN1 type not implemented"); + ret = WOLFSSL_FATAL_ERROR; + break; } - return err; + return ret; } /* Create a new ASN1 item based on a template. * - * @param [in] tpl Template of ASN1 items. + * @param [in] item Info about ASN1 items. * @return A new ASN1 item on success. - * @return NULL when tpl is NULL, dynamic memory allocation fails or ASN1 + * @return NULL when item is NULL, dynamic memory allocation fails or ASN1 * item type not supported. */ -void* wolfSSL_ASN1_item_new(const WOLFSSL_ASN1_ITEM* tpl) +void* wolfSSL_ASN1_item_new(const WOLFSSL_ASN1_ITEM* item) { - int err = 0; void* ret = NULL; - const WOLFSSL_ASN1_TEMPLATE *mem = NULL; - size_t i; WOLFSSL_ENTER("wolfSSL_ASN1_item_new"); - if (tpl != NULL) { - ret = (void *)XMALLOC(tpl->size, NULL, DYNAMIC_TYPE_OPENSSL); - } + if (item == NULL) + return NULL; - if (ret != NULL) { - XMEMSET(ret, 0, tpl->size); - for (mem = tpl->members, i = 0; i < tpl->mcount; mem++, i++) { - if ((err = wolfssl_asn1_item_new( - (void**)(((byte*)ret) + mem->offset), mem->type))) { - break; - } - } - } + /* allocation */ + ret = asn1_item_alloc(item); + if (ret == NULL) + return NULL; - if (err) { - wolfSSL_ASN1_item_free(ret, tpl); + /* initialization */ + if (asn1_item_init(ret, item) != 0) { + wolfSSL_ASN1_item_free(ret, item); ret = NULL; } + return ret; } -/* Dispose of an ASN1 item of the specified type. - * - * @param [in, out] item Pointer to an anonymized ASN1 item to free. - * @param [in] type Type of ASN1 item to free. - */ -static void wolfssl_asn1_item_free(void** item, int type) +static void asn1_free_tpl(void *obj, const WOLFSSL_ASN1_TEMPLATE *mem) { - switch (type) { - case WOLFSSL_X509_ALGOR_ASN1: - wolfSSL_X509_ALGOR_free(*(WOLFSSL_X509_ALGOR**)item); - break; - case WOLFSSL_ASN1_BIT_STRING_ASN1: - wolfSSL_ASN1_BIT_STRING_free(*(WOLFSSL_ASN1_BIT_STRING**)item); - break; - case WOLFSSL_ASN1_INTEGER_ASN1: - wolfSSL_ASN1_INTEGER_free(*(WOLFSSL_ASN1_INTEGER**)item); - break; - default: - WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_free"); + if (obj != NULL) { + if (mem->sequence) + wolfSSL_sk_pop_free((WOLFSSL_STACK *)obj, mem->free_func); + else + mem->free_func(obj); } } /* Dispose of ASN1 item based on a template. * * @param [in, out] val ASN item to free. - * @param [in, tpl Template of ASN1 items. + * @param [in, item Info about ASN1 items. */ -void wolfSSL_ASN1_item_free(void *items, const WOLFSSL_ASN1_ITEM *tpl) +void wolfSSL_ASN1_item_free(void *obj, const WOLFSSL_ASN1_ITEM *item) { const WOLFSSL_ASN1_TEMPLATE *mem = NULL; size_t i; WOLFSSL_ENTER("wolfSSL_ASN1_item_free"); - if (items != NULL) { - for (mem = tpl->members, i = 0; i < tpl->mcount; mem++, i++) { - wolfssl_asn1_item_free((void**)(((byte*)items) + mem->offset), - mem->type); + if (obj != NULL) { + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) + asn1_free_tpl(asn1Mem(obj, mem->offset), mem); + XFREE(obj, NULL, DYNAMIC_TYPE_OPENSSL); + break; + case WOLFSSL_ASN1_CHOICE: + if (asn1Type(obj, item->toffset) < 0) + break; /* type not set */ + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) { + if (asn1Type(obj, item->toffset) == mem->tag) { + asn1_free_tpl(asn1Mem(obj, mem->offset), mem); + break; + } + } + XFREE(obj, NULL, DYNAMIC_TYPE_OPENSSL); + break; + case WOLFSSL_ASN1_OBJECT_TYPE: + asn1_free_tpl(obj, item->members); + break; + default: + WOLFSSL_MSG("ASN1 type not implemented"); + break; } } - XFREE(items, NULL, DYNAMIC_TYPE_OPENSSL); -} - -/* Offset buf if not NULL or NULL. */ -#define bufLenOrNull(buf, len) (((buf) != NULL) ? ((buf) + (len)) : NULL) - -/* Encode X509 algorithm as DER. - * - * @param [in] algor X509 algorithm object. - * @param [in, out] buf Buffer to encode into. May be NULL. - * @return Length of DER encoding on success. - * @return 0 on failure. - */ -static int wolfSSL_i2d_X509_ALGOR(const WOLFSSL_X509_ALGOR* algor, byte* buf) -{ - int ret; - word32 oid = 0; - word32 idx = 0; - - if (algor->algorithm == 0) { - WOLFSSL_MSG("X509_ALGOR algorithm not set"); - ret = 0; - } - else if (GetObjectId(algor->algorithm->obj, &idx, &oid, - (word32)algor->algorithm->grp, algor->algorithm->objSz) < 0) { - WOLFSSL_MSG("Issue getting OID of object"); - ret = 0; - } - else { - ret = (int)SetAlgoID((int)oid, buf, algor->algorithm->grp, 0); - } - - return ret; } -/* Encode ASN.1 BIT_STRING as DER. - * - * @param [in] bit_str BIT_STRING object. - * @param [in, out] buf Buffer to encode into. May be NULL. - * @return Length of DER encoding on success. - */ -static int wolfSSL_i2d_ASN1_BIT_STRING(const WOLFSSL_ASN1_BIT_STRING* bit_str, - byte* buf) +static int i2d_asn1_items(const void* obj, byte** buf, + const WOLFSSL_ASN1_TEMPLATE* mem) { - int len; - - len = (int)SetBitString((word32)bit_str->length, 0, buf); - if ((buf != NULL) && (bit_str->data != NULL)) { - XMEMCPY(buf + len, bit_str->data, (size_t)bit_str->length); - } - - return len + bit_str->length; -} - -/* Encode ASN item as DER. - * - * @param [in] item Pointer to anonymized ASN item. - * @param [in, out] buf Buffer to encode into. May be NULL. - * @return Length of DER encoding on success. - * @return 0 on failure. - */ -static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) -{ - int len; - - switch (type) { - case WOLFSSL_X509_ALGOR_ASN1: - len = wolfSSL_i2d_X509_ALGOR(*(const WOLFSSL_X509_ALGOR**)item, - buf); - break; - case WOLFSSL_ASN1_BIT_STRING_ASN1: - len = wolfSSL_i2d_ASN1_BIT_STRING( - *(const WOLFSSL_ASN1_BIT_STRING**)item, buf); - break; - case WOLFSSL_ASN1_INTEGER_ASN1: - { - byte *tmp_buf = buf; - len = wolfSSL_i2d_ASN1_INTEGER( - *(const WOLFSSL_ASN1_INTEGER**)item, &tmp_buf); - if ((buf == NULL) && (tmp_buf != NULL)) { - XFREE(tmp_buf, NULL, DYNAMIC_TYPE_ASN1); - tmp_buf = NULL; + int len = 0; + int ret = 0; + if (mem->sequence) { + const WOLFSSL_STACK* sk = (WOLFSSL_STACK *)asn1Mem(obj, mem->offset); + int ski; /* stack index */ + int innerLen = 0; + /* Figure out the inner length first */ + for (ski = 0; ski < wolfSSL_sk_num(sk); ski++) { + ret = mem->i2d_func(wolfSSL_sk_value(sk, ski), NULL); + if (ret <= 0) + break; + innerLen += ret; + } + if (ret <= 0) + return 0; + if (buf != NULL && *buf != NULL) { + /* Now write it out */ + int writeLen = 0; + *buf += SetSequence((word32)innerLen, *buf); + for (ski = 0; ski < wolfSSL_sk_num(sk); ski++) { + ret = mem->i2d_func(wolfSSL_sk_value(sk, ski), buf); + if (ret <= 0) + break; + writeLen += ret; } + if (ret <= 0 || writeLen != innerLen) + return 0; } - break; - default: - WOLFSSL_MSG("Type not support in processMembers"); - len = 0; + len = (int)SetSequence((word32)innerLen, NULL) + innerLen; } - - if (len < 0) { - len = 0; /* wolfSSL_i2d_ASN1_INTEGER can return a value less than 0 - * on error */ + else { + ret = mem->i2d_func(asn1Mem(obj, mem->offset), + buf != NULL && *buf != NULL ? buf : NULL); + if (ret <= 0) + return 0; + len = ret; } - return len; } @@ -264,7 +249,7 @@ static int wolfssl_i2d_asn1_item(void** item, int type, byte* buf) * @return Length of DER encoding on success. * @return 0 on failure. */ -static int wolfssl_i2d_asn1_items(const void* src, byte*buf, +static int wolfssl_i2d_asn1_items(const void* obj, byte* buf, const WOLFSSL_ASN1_TEMPLATE* members, size_t mcount) { const WOLFSSL_ASN1_TEMPLATE* mem = NULL; @@ -275,12 +260,34 @@ static int wolfssl_i2d_asn1_items(const void* src, byte*buf, WOLFSSL_ENTER("wolfssl_i2d_asn1_items"); for (mem = members, i = 0; i < mcount; mem++, i++) { - ret = wolfssl_i2d_asn1_item((void**)(((byte*)src) + mem->offset), - mem->type, bufLenOrNull(buf, len)); - if (ret == 0) { + byte* tmp = buf; + if (mem->ex && mem->tag >= 0) { + /* Figure out the inner length */ + int innerLen = 0; + int hdrLen = 0; + ret = i2d_asn1_items(obj, NULL, mem); + if (ret <= 0) { + len = 0; + break; + } + innerLen = ret; + hdrLen = SetExplicit((byte)mem->tag, (word32)innerLen, buf, 0); + len += hdrLen; + if (buf != NULL) + buf += hdrLen; + } + + ret = i2d_asn1_items(obj, &buf, mem); + if (ret <= 0) { len = 0; break; } + if (buf != NULL && tmp != NULL && !mem->ex && mem->tag >= 0) { + /* Encode the implicit tag */ + byte imp[ASN_TAG_SZ + MAX_LENGTH_SZ]; + SetImplicit(tmp[0], mem->tag, 0, imp, 0); + tmp[0] = imp[0]; + } len += ret; } @@ -297,25 +304,55 @@ static int wolfssl_i2d_asn1_items(const void* src, byte*buf, * @return Length of DER encoding on success. * @return 0 on failure. */ -static int i2d_ASN_SEQUENCE(const void* src, byte* buf, - const WOLFSSL_ASN1_ITEM* tpl) +static int i2d_ASN_SEQUENCE(const void* obj, byte* buf, + const WOLFSSL_ASN1_ITEM* item) { word32 seq_len; word32 len = 0; - seq_len = (word32)wolfssl_i2d_asn1_items(src, NULL, tpl->members, - tpl->mcount); + seq_len = (word32)wolfssl_i2d_asn1_items(obj, NULL, item->members, + item->mcount); if (seq_len != 0) { len = SetSequence(seq_len, buf); if (buf != NULL) { - wolfssl_i2d_asn1_items(src, buf + len, tpl->members, tpl->mcount); + if (wolfssl_i2d_asn1_items(obj, buf + len, item->members, + item->mcount) > 0) + len += seq_len; /* success */ + else + len = 0; /* error */ } - len += seq_len; + else + len += seq_len; } return (int)len; } +static int i2d_ASN_CHOICE(const void* obj, byte* buf, + const WOLFSSL_ASN1_ITEM* item) +{ + const WOLFSSL_ASN1_TEMPLATE* mem = NULL; + size_t i; + + if (asn1Type(obj, item->toffset) < 0) + return 0; /* type not set */ + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) { + if (asn1Type(obj, item->toffset) == mem->tag) { + return wolfssl_i2d_asn1_items(obj, buf, mem, 1); + } + } + return 0; +} + +static int i2d_ASN_OBJECT_TYPE(const void* obj, byte* buf, + const WOLFSSL_ASN1_ITEM* item) +{ + /* To be able to use wolfssl_i2d_asn1_items without any modifications, + * pass in a pointer to obj so that asn1Mem uses the correct pointer. */ + const void ** obj_pp = &obj; + return wolfssl_i2d_asn1_items(obj_pp, buf, item->members, item->mcount); +} + /* Encode ASN1 template item. * * @param [in] src ASN1 items to encode. @@ -324,14 +361,20 @@ static int i2d_ASN_SEQUENCE(const void* src, byte* buf, * @return Length of DER encoding on success. * @return 0 on failure. */ -static int wolfssl_asn1_item_encode(const void* src, byte* buf, - const WOLFSSL_ASN1_ITEM* tpl) +static int wolfssl_asn1_item_encode(const void* obj, byte* buf, + const WOLFSSL_ASN1_ITEM* item) { int len; - switch (tpl->type) { - case ASN_SEQUENCE: - len = i2d_ASN_SEQUENCE(src, buf, tpl); + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + len = i2d_ASN_SEQUENCE(obj, buf, item); + break; + case WOLFSSL_ASN1_OBJECT_TYPE: + len = i2d_ASN_OBJECT_TYPE(obj, buf, item); + break; + case WOLFSSL_ASN1_CHOICE: + len = i2d_ASN_CHOICE(obj, buf, item); break; default: WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_i2d"); @@ -347,10 +390,10 @@ static int wolfssl_asn1_item_encode(const void* src, byte* buf, * @param [in, out] dest Pointer to buffer to encode into. May be NULL. * @param [in] tpl Template of ASN1 items. * @return Length of DER encoding on success. - * @return 0 on failure. + * @return WOLFSSL_FATAL_ERROR on failure. */ -int wolfSSL_ASN1_item_i2d(const void* src, byte** dest, - const WOLFSSL_ASN1_ITEM* tpl) +int wolfSSL_ASN1_item_i2d(const void* obj, byte** dest, + const WOLFSSL_ASN1_ITEM* item) { int ret = 1; int len = 0; @@ -359,35 +402,320 @@ int wolfSSL_ASN1_item_i2d(const void* src, byte** dest, WOLFSSL_ENTER("wolfSSL_ASN1_item_i2d"); /* Validate parameters. */ - if ((src == NULL) || (tpl == NULL)) { + if ((obj == NULL) || (item == NULL)) { ret = 0; } - if ((ret == 1) && ((len = wolfssl_asn1_item_encode(src, NULL, tpl)) == 0)) { + if ((ret == 1) && ((len = wolfssl_asn1_item_encode(obj, NULL, item)) == 0)) ret = 0; - } if ((ret == 1) && (dest != NULL)) { if (*dest == NULL) { buf = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); if (buf == NULL) ret = 0; - *dest = buf; + } + else + buf = *dest; + + if (ret == 1) { + len = wolfssl_asn1_item_encode(obj, buf, item); + if (len <= 0) + ret = 0; } if (ret == 1) { - len = wolfssl_asn1_item_encode(src, *dest, tpl); + if (*dest == NULL) + *dest = buf; + else + *dest += len; } } if (ret == 0) { - XFREE(buf, NULL, DYNAMIC_TYPE_ASN1); - len = 0; + if (*dest == NULL) + XFREE(buf, NULL, DYNAMIC_TYPE_ASN1); + len = WOLFSSL_FATAL_ERROR; } WOLFSSL_LEAVE("wolfSSL_ASN1_item_i2d", len); return len; } +static void* d2i_obj(const WOLFSSL_ASN1_TEMPLATE* mem, const byte** src, + long* len) +{ + void* ret; + const byte* tmp = *src; + ret = mem->d2i_func(NULL, &tmp, *len); + if (ret == NULL) { + WOLFSSL_MSG("d2i error"); + return NULL; + } + if (tmp <= *src) { + WOLFSSL_MSG("ptr not advanced"); + mem->free_func(ret); /* never a stack so we can call this directly */ + return NULL; + } + *len -= (tmp - *src); + *src = tmp; + return ret; +} + +static void* d2i_generic_obj(const WOLFSSL_ASN1_TEMPLATE* mem, const byte** src, + long* len) +{ + void* ret = NULL; + if (mem->sequence) { + long skl = 0; + int slen = 0; + WOLFSSL_STACK* sk = NULL; + word32 idx = 0; + const byte* tmp = *src; + if (GetSequence(tmp, &idx, &slen, (word32)*len) < 0) + goto error; + skl = (long)slen; + tmp += idx; + ret = sk = wolfSSL_sk_new_null(); + while (skl > 0) { + void* new_obj = d2i_obj(mem, &tmp, &skl); + if (new_obj == NULL) { + WOLFSSL_MSG("d2i_obj failed"); + goto error; + } + if (wolfSSL_sk_insert(sk, new_obj, -1) <= 0) { + mem->free_func(new_obj); + WOLFSSL_MSG("push failed"); + goto error; + } + } + if (skl != 0) { + WOLFSSL_MSG("l not zero after sequence"); + goto error; + } + *len -= (long)slen; + *src = tmp; + } + else { + ret = d2i_obj(mem, src, len); + } + return ret; +error: + asn1_free_tpl(ret, mem); + return NULL; +} + +static int d2i_handle_tags(const WOLFSSL_ASN1_TEMPLATE* mem, const byte** src, + long* len, byte** impBuf, int* asnLen) +{ + if (mem->tag >= 0) { + byte tag = 0; + word32 idx = 0; + if (mem->ex) { + if (GetASNTag(*src, &idx, &tag, (word32)*len) < 0 || + (byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | mem->tag) + != tag || + GetLength(*src, &idx, asnLen, (word32)*len) < 0) { + WOLFSSL_MSG("asn tag error"); + return WOLFSSL_FATAL_ERROR; + } + *len -= idx; + *src += idx; + } + else { + /* Underlying d2i functions won't be able to handle the implicit + * tag so we substitute it for the expected tag. */ + if (mem->first_byte == 0) { + WOLFSSL_MSG("first byte not set"); + return WOLFSSL_FATAL_ERROR; + } + if (GetASNTag(*src, &idx, &tag, (word32)*len) < 0 || + (byte)mem->tag != (tag & ASN_TYPE_MASK) || + GetLength(*src, &idx, asnLen, (word32)*len) < 0) { + WOLFSSL_MSG("asn tag error"); + return WOLFSSL_FATAL_ERROR; + } + *asnLen += idx; /* total buffer length */ + *impBuf = (byte*)XMALLOC(*asnLen, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (*impBuf == NULL) { + WOLFSSL_MSG("malloc error"); + return WOLFSSL_FATAL_ERROR; + } + XMEMCPY(*impBuf, *src, *asnLen); + (*impBuf)[0] = mem->first_byte; + } + } + return 0; +} + +static void* d2i_generic(const WOLFSSL_ASN1_TEMPLATE* mem, + const byte** src, long* len) +{ + int asnLen = -1; + const byte *tmp = NULL; + void* ret = NULL; + byte* impBuf = NULL; + long l; + + if (*len <= 0) { + WOLFSSL_MSG("buffer too short"); + return NULL; + } + + if (d2i_handle_tags(mem, src, len, &impBuf, &asnLen) != 0) { + WOLFSSL_MSG("tags error"); + goto error; + } + + if (impBuf != NULL) + tmp = impBuf; + else + tmp = *src; + l = (long)(asnLen >= 0 ? asnLen : *len); + ret = d2i_generic_obj(mem, &tmp, &l); + if (l < 0) { + WOLFSSL_MSG("ptr advanced too far"); + goto error; + } + if (impBuf != NULL) { + tmp = *src + (tmp - impBuf); /* for the next calculation */ + XFREE(impBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + impBuf = NULL; + } + if (asnLen >= 0 && (int)(tmp - *src) != asnLen) { + WOLFSSL_MSG("ptr not advanced enough"); + goto error; + } + *len -= tmp - *src; + *src = tmp; + return ret; +error: + asn1_free_tpl(ret, mem); + if (impBuf != NULL) + XFREE(impBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return NULL; +} + +static int d2i_ASN_SEQUENCE(void* obj, const byte **src, long len, + const WOLFSSL_ASN1_ITEM* item) +{ + const WOLFSSL_ASN1_TEMPLATE* mem = NULL; + int err; + word32 idx = 0; + int slen = 0; + size_t i; + const byte* s = *src; + + err = GetSequence(s, &idx, &slen, (word32)len); + if (err <= 0) { + WOLFSSL_MSG("GetSequence error"); + return WOLFSSL_FATAL_ERROR; + } + s += idx; + len -= idx; + + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) { + asn1Mem(obj, mem->offset) = d2i_generic(mem, &s, &len); + if (asn1Mem(obj, mem->offset) == NULL) { + WOLFSSL_MSG("d2i error"); + return WOLFSSL_FATAL_ERROR; + } + } + *src = s; + return 0; +} + +static int d2i_ASN_CHOICE(void* obj, const byte **src, long len, + const WOLFSSL_ASN1_ITEM* item) +{ + const WOLFSSL_ASN1_TEMPLATE* mem = NULL; + size_t i; + + for (mem = item->members, i = 0; i < item->mcount; mem++, i++) { + asn1Mem(obj, mem->offset) = d2i_generic(mem, src, &len); + if (asn1Mem(obj, mem->offset) != NULL) { + asn1Type(obj, item->toffset) = mem->tag; + return 0; + } + } + WOLFSSL_MSG("der does not decode with any CHOICE"); + return WOLFSSL_FATAL_ERROR; +} + +static void* d2i_ASN_OBJECT_TYPE(const byte **src, long len, + const WOLFSSL_ASN1_ITEM* item) +{ + return d2i_generic(item->members, src, &len); +} + +void* wolfSSL_ASN1_item_d2i(void** dst, const byte **src, long len, + const WOLFSSL_ASN1_ITEM* item) +{ + void* obj = NULL; + int err = 0; + const byte *tmp; + + WOLFSSL_ENTER("wolfSSL_ASN1_item_d2i"); + + if (src == NULL || *src == NULL || len <= 0 || item == NULL) { + WOLFSSL_LEAVE("wolfSSL_ASN1_item_d2i", 0); + return NULL; + } + + tmp = *src; + + /* Create an empty object. */ + + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + case WOLFSSL_ASN1_CHOICE: + obj = asn1_item_alloc(item); + if (obj == NULL) + return NULL; + break; + case WOLFSSL_ASN1_OBJECT_TYPE: + /* allocated later */ + break; + default: + WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_d2i"); + return NULL; + } + + switch (item->type) { + case WOLFSSL_ASN1_SEQUENCE: + err = d2i_ASN_SEQUENCE(obj, &tmp, len, item); + break; + case WOLFSSL_ASN1_CHOICE: + err = d2i_ASN_CHOICE(obj, &tmp, len, item); + break; + case WOLFSSL_ASN1_OBJECT_TYPE: + obj = d2i_ASN_OBJECT_TYPE(&tmp, len, item); + if (obj == NULL) + err = WOLFSSL_FATAL_ERROR; + break; + default: + WOLFSSL_MSG("Type not supported in wolfSSL_ASN1_item_d2i"); + err = WOLFSSL_FATAL_ERROR; + break; + } + + if (err == 0) + *src = tmp; + else { + wolfSSL_ASN1_item_free(obj, item); + obj = NULL; + } + + if (dst != NULL && obj != NULL) { + if (*dst != NULL) + wolfSSL_ASN1_item_free(*dst, item); + *dst = obj; + } + + WOLFSSL_LEAVE("wolfSSL_ASN1_item_d2i", obj != NULL); + return obj; +} + #endif /* OPENSSL_ALL */ #endif /* OPENSSL_EXTRA */ @@ -453,9 +781,6 @@ int wolfSSL_ASN1_BIT_STRING_get_bit(const WOLFSSL_ASN1_BIT_STRING* bitStr, return bit; } -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ - -#if defined(OPENSSL_ALL) && !defined(NO_CERTS) /* Grow data to require length. * @@ -478,7 +803,8 @@ static int wolfssl_asn1_bit_string_grow(WOLFSSL_ASN1_BIT_STRING* bitStr, } else { /* Clear out new, top bytes. */ - XMEMSET(tmp + bitStr->length, 0, (size_t)(len - bitStr->length)); + if (len > bitStr->length) + XMEMSET(tmp + bitStr->length, 0, (size_t)(len - bitStr->length)); bitStr->data = tmp; bitStr->length = len; } @@ -527,7 +853,99 @@ int wolfSSL_ASN1_BIT_STRING_set_bit(WOLFSSL_ASN1_BIT_STRING* bitStr, int idx, return ret; } -#endif /* OPENSSL_ALL && !NO_CERTS */ +/* Serialize object to DER encoding + * + * @param bstr Object to serialize + * @param pp Output + * @return Length on success + * Negative number on failure + */ +int wolfSSL_i2d_ASN1_BIT_STRING(const WOLFSSL_ASN1_BIT_STRING* bstr, + unsigned char** pp) +{ + int len; + unsigned char* buf; + + if (bstr == NULL || (bstr->data == NULL && bstr->length != 0)) + return WOLFSSL_FATAL_ERROR; + + len = (int)SetBitString((word32)bstr->length, 0, NULL) + bstr->length; + if (pp != NULL) { + word32 idx; + + if (*pp != NULL) + buf = *pp; + else { + buf = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); + if (buf == NULL) + return WOLFSSL_FATAL_ERROR; + } + + idx = SetBitString((word32)bstr->length, 0, buf); + if (bstr->length > 0) + XMEMCPY(buf + idx, bstr->data, (size_t)bstr->length); + + if (*pp != NULL) + *pp += len; + else + *pp = buf; + } + + return len; +} + +WOLFSSL_ASN1_BIT_STRING* wolfSSL_d2i_ASN1_BIT_STRING( + WOLFSSL_ASN1_BIT_STRING** out, const byte** src, long len) +{ + WOLFSSL_ASN1_BIT_STRING* ret = NULL; +#ifdef WOLFSSL_ASN_TEMPLATE + word32 idx = 0; + byte tag = 0; + int length = 0; + + WOLFSSL_ENTER("wolfSSL_d2i_ASN1_BIT_STRING"); + + if (src == NULL || *src == NULL || len == 0) + return NULL; + + if (GetASNTag(*src, &idx, &tag, (word32)len) < 0) + return NULL; + if (tag != ASN_BIT_STRING) + return NULL; + if (GetLength(*src, &idx, &length, (word32)len) < 0) + return NULL; + if (GetASN_BitString(*src, idx, length) != 0) + return NULL; + idx++; /* step over unused bits */ + length--; + + ret = wolfSSL_ASN1_BIT_STRING_new(); + if (ret == NULL) + return NULL; + + if (wolfssl_asn1_bit_string_grow(ret, length) != 1) { + wolfSSL_ASN1_BIT_STRING_free(ret); + return NULL; + } + + XMEMCPY(ret->data, *src + idx, length); + *src += idx + (word32)length; + + if (out != NULL) { + if (*out != NULL) + wolfSSL_ASN1_BIT_STRING_free(*out); + *out = ret; + } +#else + WOLFSSL_MSG("d2i_ASN1_BIT_STRING needs --enable-asn=template"); + (void)out; + (void)src; + (void)len; +#endif + return ret; +} + +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ /******************************************************************************* * ASN1_INTEGER APIs @@ -706,7 +1124,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_dup(const WOLFSSL_ASN1_INTEGER* src) * @return Negative value when a is less than b. * @return 0 when a equals b. * @return Positive value when a is greater than b. - * @return -1 when a or b is NULL. + * @return WOLFSSL_FATAL_ERROR when a or b is NULL. */ int wolfSSL_ASN1_INTEGER_cmp(const WOLFSSL_ASN1_INTEGER* a, const WOLFSSL_ASN1_INTEGER* b) @@ -718,11 +1136,11 @@ int wolfSSL_ASN1_INTEGER_cmp(const WOLFSSL_ASN1_INTEGER* a, /* Validate parameters. */ if ((a == NULL) || (b == NULL)) { WOLFSSL_MSG("Bad parameter."); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Negative value < Positive value */ else if (a->negative && !b->negative) { - ret = -1; + ret = -2; /* avoid collision with WOLFSSL_FATAL_ERROR */ } /* Positive value > Negative value */ else if (!a->negative && b->negative) { @@ -772,7 +1190,7 @@ static void wolfssl_twos_compl(byte* data, int length) /* Calculate 2's complement of DER encoding. * - * @param [in] data Array that is number. + * @param [in|out] data Array that is number. * @param [in] length Number of bytes in array. * @param [out] neg When NULL, 2's complement data. * When not NULL, check for negative first and return. @@ -787,7 +1205,7 @@ static int wolfssl_asn1_int_twos_compl(byte* data, int length, byte* neg) /* Get length from DER header. */ if (GetLength(data, &idx, &len, (word32)length) < 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { if (neg != NULL) { @@ -811,60 +1229,48 @@ static int wolfssl_asn1_int_twos_compl(byte* data, int length, byte* neg) * @return -1 when a is NULL or no data, out is NULL, dynamic memory allocation * fails or encoding length fails. */ -int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** out) +int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, unsigned char** pp) { - int ret = 0; - byte* buf = NULL; - WOLFSSL_ENTER("wolfSSL_i2d_ASN1_INTEGER"); /* Validate parameters. */ - if ((a == NULL) || (a->data == NULL) || (a->length <= 0) || (out == NULL)) { + if (a == NULL || a->data == NULL || a->length <= 0) { WOLFSSL_MSG("Bad parameter."); - ret = -1; + return WOLFSSL_FATAL_ERROR; } - if ((ret == 0) && (*out == NULL)) { - /* Allocate buffer to hold encoding. */ - buf = (unsigned char*)XMALLOC((size_t)a->length, NULL, - DYNAMIC_TYPE_ASN1); - if (buf == NULL) { - WOLFSSL_MSG("Failed to allocate output buffer."); - ret = -1; + if (pp != NULL) { + byte* buf; + + if (*pp != NULL) + buf = *pp; + else { + buf = (byte*)XMALLOC((size_t)a->length, NULL, DYNAMIC_TYPE_ASN1); + if (buf == NULL) + return WOLFSSL_FATAL_ERROR; } - /* Return any allocated buffer. */ - *out = buf; - } - if (ret == 0) { + /* Copy the data (including tag and length) into output buffer. */ - XMEMCPY(*out, a->data, (size_t)a->length); + XMEMCPY(buf, a->data, (size_t)a->length); /* Only magnitude of the number stored (i.e. the sign isn't encoded). * The "negative" field is 1 if the value must be interpreted as * negative and we need to output the 2's complement of the value in * the DER output. */ - if (a->negative) { - ret = wolfssl_asn1_int_twos_compl(*out, a->length, NULL); - } - } - if (ret == 0) { - ret = a->length; - /* Move pointer on passed encoding when buffer passed in. */ - if (buf == NULL) { - *out += a->length; + if (a->negative && + wolfssl_asn1_int_twos_compl(buf, a->length, NULL) != 0) { + if (*pp == NULL) + XFREE(buf, NULL, DYNAMIC_TYPE_ASN1); + return WOLFSSL_FATAL_ERROR; } - } - /* Dispose of any dynamically allocated data on error. */ - else if (buf != NULL) { - /* Dispose of buffer allocated locally on error. */ - XFREE(buf, NULL, DYNAMIC_TYPE_ASN1); - /* Don't return freed buffer. */ - *out = NULL; - } - WOLFSSL_LEAVE("wolfSSL_i2d_ASN1_INTEGER", ret); + if (*pp != NULL) + *pp += a->length; + else + *pp = buf; + } - return ret; + return a->length; } /* Decode DER encoding of ASN.1 INTEGER. @@ -1427,7 +1833,7 @@ long wolfSSL_ASN1_INTEGER_get(const WOLFSSL_ASN1_INTEGER* a) /* Create a big number from the DER encoding. */ bn = wolfSSL_ASN1_INTEGER_to_BN(a, NULL); if (bn == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } if (ret > 0) { @@ -1700,6 +2106,36 @@ int wolfSSL_ASN1_get_object(const unsigned char **in, long *len, int *tag, return ret; } +int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj, const byte* der, word32 len, + int addHdr) +{ + word32 idx = 0; + + if (obj == NULL || der == NULL || len == 0) + return WOLFSSL_FAILURE; + + if (addHdr) + idx = SetHeader(ASN_OBJECT_ID, (word32)len, NULL, 0); + + if (obj->obj != NULL) { + XFREE((void*)obj->obj, obj->heap, DYNAMIC_TYPE_ASN1); + obj->obj = NULL; + obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA; + } + + obj->obj =(unsigned char*)XMALLOC(idx + len, obj->heap, DYNAMIC_TYPE_ASN1); + if (obj->obj == NULL) + return WOLFSSL_FAILURE; + + if (addHdr) + SetHeader(ASN_OBJECT_ID, (word32)len, (byte*)obj->obj, 0); + + XMEMCPY((byte*)obj->obj + idx, der, len); + obj->objSz = (unsigned int)(idx + len); + obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; + return WOLFSSL_SUCCESS; +} + /* Creates and ASN.1 OBJECT_ID object from DER encoding. * * @param [out] a Pointer to return new ASN.1 OBJECT_ID through. @@ -1714,38 +2150,43 @@ WOLFSSL_ASN1_OBJECT *wolfSSL_d2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a, const unsigned char **der, long length) { WOLFSSL_ASN1_OBJECT* ret = NULL; - int err = 0; - const unsigned char *d; - long len = 0; - int tag = 0; - int cls; + int len = 0; + word32 idx = 0; WOLFSSL_ENTER("wolfSSL_d2i_ASN1_OBJECT"); /* Validate parameters. */ if ((der == NULL) || (*der == NULL) || (length <= 0)) { WOLFSSL_MSG("Bad parameter"); - err = 1; + return NULL; } - if (!err) { - /* Get pointer to be modified along the way. */ - d = *der; - /* Move d to value and get length and tag. */ - if (wolfSSL_ASN1_get_object(&d, &len, &tag, &cls, length) & 0x80) { - WOLFSSL_MSG("wolfSSL_ASN1_get_object error"); - err = 1; - } + if (GetASNHeader(*der, ASN_OBJECT_ID, &idx, &len, (word32)length) < 0) { + WOLFSSL_MSG("error getting tag"); + return NULL; } - /* Check it DER encoding is of an OBJECT_ID. */ - if ((!err) && (tag != ASN_OBJECT_ID)) { - WOLFSSL_MSG("Not an ASN object"); - err = 1; + + if (len <= 0) { + WOLFSSL_MSG("zero length"); + return NULL; } - /* Create an ASN.1 OBJECT_ID_object from value. TODO: not DER encoding? */ - if ((!err) && ((ret = wolfSSL_c2i_ASN1_OBJECT(a, &d, len)) != NULL)) { - /* Update pointer to after decoded bytes. */ - *der = d; + + ret = wolfSSL_ASN1_OBJECT_new(); + if (ret == NULL) { + WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_new error"); + return NULL; + } + + if (wolfssl_asn1_obj_set(ret, *der, idx + len, 0) != WOLFSSL_SUCCESS) { + wolfSSL_ASN1_OBJECT_free(ret); + return NULL; + } + + *der += idx + len; + if (a != NULL) { + if (*a != NULL) + wolfSSL_ASN1_OBJECT_free(*a); + *a = ret; } return ret; @@ -1821,7 +2262,6 @@ int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp) WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a, const unsigned char **pp, long len) { - int err = 0; WOLFSSL_ASN1_OBJECT* ret = NULL; WOLFSSL_ENTER("wolfSSL_c2i_ASN1_OBJECT"); @@ -1829,40 +2269,29 @@ WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a, /* Validate parameters. */ if ((pp == NULL) || (*pp == NULL) || (len <= 0)) { WOLFSSL_MSG("Bad parameter"); - err = 1; + return NULL; } /* Create a new ASN.1 OBJECT_ID object. */ - if ((!err) && ((ret = wolfSSL_ASN1_OBJECT_new()) == NULL)) { + ret = wolfSSL_ASN1_OBJECT_new(); + if (ret == NULL) { WOLFSSL_MSG("wolfSSL_ASN1_OBJECT_new error"); - err = 1; + return NULL; } - if (!err) { - /* Allocate memory for content octets. */ - ret->obj = (const unsigned char*)XMALLOC((size_t)len, NULL, - DYNAMIC_TYPE_ASN1); - if (ret->obj == NULL) { - WOLFSSL_MSG("error allocating asn data memory"); - wolfSSL_ASN1_OBJECT_free(ret); - ret = NULL; - err = 1; - } + if (wolfssl_asn1_obj_set(ret, *pp, (word32)len, 1) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfssl_asn1_obj_set error"); + wolfSSL_ASN1_OBJECT_free(ret); + return NULL; } - if (!err) { - /* Content octets buffer was dynamically allocated. */ - ret->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; - /* Copy in content octets and set size. */ - XMEMCPY((byte*)ret->obj, *pp, (size_t)len); - ret->objSz = (unsigned int)len; - - /* Move pointer to after data copied out. */ - *pp += len; - /* Return ASN.1 OBJECT_ID object through a if required. */ - if (a != NULL) { - *a = ret; - } + /* Move pointer to after data copied out. */ + *pp += len; + /* Return ASN.1 OBJECT_ID object through a if required. */ + if (a != NULL) { + if (*a != NULL) + wolfSSL_ASN1_OBJECT_free(*a); + *a = ret; } return ret; @@ -1992,16 +2421,9 @@ void wolfSSL_sk_ASN1_OBJECT_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk, int wolfSSL_sk_ASN1_OBJECT_push(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk, WOLFSSL_ASN1_OBJECT* obj) { - int ret = 0; - WOLFSSL_ENTER("wolfSSL_sk_ASN1_OBJECT_push"); - /* Push on when we have a stack and object to work with. */ - if ((sk != NULL) && (obj != NULL)) { - ret = wolfSSL_sk_push(sk, obj); - } - - return ret; + return wolfSSL_sk_push(sk, obj); } /* Pop off a WOLFSSL_ASN1_OBJECT from the stack. @@ -2163,7 +2585,7 @@ WOLFSSL_ASN1_STRING* wolfSSL_ASN1_STRING_dup(WOLFSSL_ASN1_STRING* asn1) * @return Negative value when a is less than b. * @return 0 when a equals b. * @return Positive value when a is greater than b. - * @return -1 when a or b is NULL. + * @return WOLFSSL_FATAL_ERROR when a or b is NULL. */ int wolfSSL_ASN1_STRING_cmp(const WOLFSSL_ASN1_STRING *a, const WOLFSSL_ASN1_STRING *b) @@ -2173,7 +2595,7 @@ int wolfSSL_ASN1_STRING_cmp(const WOLFSSL_ASN1_STRING *a, /* Validate parameters. */ if ((a == NULL) || (b == NULL)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Compare length of data. */ else if (a->length != b->length) { @@ -2296,7 +2718,7 @@ int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_STRING *asn1) len = wolfSSL_ASN1_STRING_length(asn1); /* Check data and length are usable. */ if ((data == NULL) || (len < 0)) { - len = -1; + len = WOLFSSL_FATAL_ERROR; } } if (len != -1) { @@ -2304,7 +2726,7 @@ int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_STRING *asn1) buf = (unsigned char*)XMALLOC((size_t)(len + 1), NULL, DYNAMIC_TYPE_OPENSSL); if (buf == NULL) { - len = -1; + len = WOLFSSL_FATAL_ERROR; } } if (len != -1) { @@ -2318,7 +2740,7 @@ int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_STRING *asn1) } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#if defined(OPENSSL_EXTRA) +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) /* Encode ASN.1 STRING data as hex digits separated by colon. * @@ -2397,7 +2819,155 @@ char* wolfSSL_i2s_ASN1_STRING(WOLFSSL_v3_ext_method *method, return ret; } -#endif /* OPENSSL_EXTRA */ + +static int i2d_ASN1_STRING(WOLFSSL_ASN1_STRING* s, + unsigned char **pp, byte tag) +{ + int idx; + int len; + unsigned char* out; + + if (s == NULL || s->data == NULL || s->length == 0) + return WOLFSSL_FATAL_ERROR; + + len = SetHeader(tag, s->length, NULL, 0) + s->length; + + if (pp == NULL) + return len; + + if (*pp == NULL) { + out = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + if (out == NULL) + return WOLFSSL_FATAL_ERROR; + } + else { + out = *pp; + } + + idx = (int)SetHeader(tag, s->length, out, 0); + XMEMCPY(out + idx, s->data, s->length); + if (*pp == NULL) + *pp = out; + else + *pp += len; + + return len; +} + +int wolfSSL_i2d_ASN1_GENERALSTRING(WOLFSSL_ASN1_STRING* s, unsigned char **pp) +{ + WOLFSSL_ENTER("wolfSSL_i2d_ASN1_GENERALSTRING"); + + return i2d_ASN1_STRING(s, pp, ASN_GENERALSTRING); +} + +int wolfSSL_i2d_ASN1_OCTET_STRING(WOLFSSL_ASN1_STRING* s, unsigned char **pp) +{ + WOLFSSL_ENTER("wolfSSL_i2d_ASN1_OCTET_STRING"); + + return i2d_ASN1_STRING(s, pp, ASN_OCTET_STRING); +} + +int wolfSSL_i2d_ASN1_UTF8STRING(WOLFSSL_ASN1_STRING* s, unsigned char **pp) +{ + WOLFSSL_ENTER("wolfSSL_i2d_ASN1_UTF8STRING"); + + return i2d_ASN1_STRING(s, pp, ASN_UTF8STRING); +} + +int wolfSSL_i2d_ASN1_SEQUENCE(WOLFSSL_ASN1_STRING* s, + unsigned char **pp) +{ + unsigned char* out; + + if (s == NULL || s->data == NULL || s->length == 0) + return WOLFSSL_FATAL_ERROR; + + if (pp == NULL) + return s->length; + + if (*pp == NULL) { + out = (unsigned char*)XMALLOC(s->length, NULL, DYNAMIC_TYPE_ASN1); + if (out == NULL) + return WOLFSSL_FATAL_ERROR; + } + else { + out = *pp; + } + + XMEMCPY(out, s->data, s->length); + if (*pp == NULL) + *pp = out; + else + *pp += s->length; + + return s->length; +} + +static WOLFSSL_ASN1_STRING* d2i_ASN1_STRING(WOLFSSL_ASN1_STRING** out, + const byte** src, long len, byte expTag) +{ + WOLFSSL_ASN1_STRING* ret = NULL; + word32 idx = 0; + byte tag = 0; + int length = 0; + + WOLFSSL_ENTER("d2i_ASN1_GENERALSTRING"); + + if (src == NULL || *src == NULL || len == 0) + return NULL; + + if (GetASNTag(*src, &idx, &tag, (word32)len) < 0) + return NULL; + if (tag != expTag) + return NULL; + if (GetLength(*src, &idx, &length, (word32)len) < 0) + return NULL; + + ret = wolfSSL_ASN1_STRING_new(); + if (ret == NULL) + return NULL; + + if (wolfSSL_ASN1_STRING_set(ret, *src + idx, length) != 1) { + wolfSSL_ASN1_STRING_free(ret); + return NULL; + } + + if (out != NULL) { + if (*out != NULL) + wolfSSL_ASN1_STRING_free(*out); + *out = ret; + } + *src += idx + length; + + return ret; +} + +WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_GENERALSTRING(WOLFSSL_ASN1_STRING** out, + const byte** src, long len) +{ + WOLFSSL_ENTER("wolfSSL_d2i_ASN1_GENERALSTRING"); + + return d2i_ASN1_STRING(out, src, len, ASN_GENERALSTRING); +} + +WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_OCTET_STRING(WOLFSSL_ASN1_STRING** out, + const byte** src, long len) +{ + WOLFSSL_ENTER("wolfSSL_d2i_ASN1_OCTET_STRING"); + + return d2i_ASN1_STRING(out, src, len, ASN_OCTET_STRING); +} + +WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_UTF8STRING(WOLFSSL_ASN1_STRING** out, + const byte** src, long len) +{ + WOLFSSL_ENTER("wolfSSL_d2i_ASN1_UTF8STRING"); + + return d2i_ASN1_STRING(out, src, len, ASN_UTF8STRING); +} + +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #endif /* NO_ASN */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) @@ -2470,7 +3040,7 @@ unsigned char* wolfSSL_ASN1_STRING_data(WOLFSSL_ASN1_STRING* asn) * @return String length on success. * @return 0 when asn is NULL or no data set. */ -int wolfSSL_ASN1_STRING_length(WOLFSSL_ASN1_STRING* asn) +int wolfSSL_ASN1_STRING_length(const WOLFSSL_ASN1_STRING* asn) { int len = 0; @@ -2820,7 +3390,7 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, /* Write out hash character to indicate hex string. */ if (wolfSSL_BIO_write(bio, hash, 1) != 1) { - str_len = -1; + str_len = WOLFSSL_FATAL_ERROR; } else { /* Check if we are to write out DER header. */ @@ -2832,7 +3402,7 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, str_len += 4; /* Write out tag and length as hex digits. */ if (wolfSSL_BIO_write(bio, hex_tmp, 4) != 4) { - str_len = -1; + str_len = WOLFSSL_FATAL_ERROR; } } } @@ -2850,7 +3420,7 @@ static int wolfssl_asn1_string_dump_hex(WOLFSSL_BIO *bio, str_len += 2; /* Write out character as hex digites. */ if (wolfSSL_BIO_write(bio, hex_tmp, 2) != 2) { - str_len = -1; + str_len = WOLFSSL_FATAL_ERROR; break; } } @@ -2905,7 +3475,7 @@ static int wolfssl_asn1_string_print_esc_2253(WOLFSSL_BIO *bio, str_len++; /* Write out escaping character. */ if (wolfSSL_BIO_write(bio,"\\", 1) != 1) { - str_len = -1; + str_len = WOLFSSL_FATAL_ERROR; break; } } @@ -2913,7 +3483,7 @@ static int wolfssl_asn1_string_print_esc_2253(WOLFSSL_BIO *bio, str_len++; /* Write out character. */ if (wolfSSL_BIO_write(bio, p, 1) != 1) { - str_len = -1; + str_len = WOLFSSL_FATAL_ERROR; break; } } @@ -3002,9 +3572,7 @@ int wolfSSL_ASN1_STRING_print_ex(WOLFSSL_BIO *bio, WOLFSSL_ASN1_STRING *str, void wolfSSL_ASN1_GENERALIZEDTIME_free(WOLFSSL_ASN1_TIME* asn1Time) { WOLFSSL_ENTER("wolfSSL_ASN1_GENERALIZEDTIME_free"); - if (asn1Time != NULL) { - XFREE(asn1Time, NULL, DYNAMIC_TYPE_OPENSSL); - } + XFREE(asn1Time, NULL, DYNAMIC_TYPE_OPENSSL); } #ifndef NO_BIO @@ -3419,7 +3987,7 @@ unsigned char* wolfSSL_ASN1_TIME_get_data(const WOLFSSL_ASN1_TIME *t) */ int wolfSSL_ASN1_TIME_check(const WOLFSSL_ASN1_TIME* a) { - int ret = 1; + int ret = WOLFSSL_SUCCESS; char buf[MAX_TIME_STRING_SZ]; WOLFSSL_ENTER("wolfSSL_ASN1_TIME_check"); @@ -3427,7 +3995,7 @@ int wolfSSL_ASN1_TIME_check(const WOLFSSL_ASN1_TIME* a) /* If can convert to human readable then format good. */ if (wolfSSL_ASN1_TIME_to_string((WOLFSSL_ASN1_TIME*)a, buf, MAX_TIME_STRING_SZ) == NULL) { - ret = 0; + ret = WOLFSSL_FAILURE; } return ret; @@ -3445,7 +4013,7 @@ int wolfSSL_ASN1_TIME_check(const WOLFSSL_ASN1_TIME* a) */ int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *t, const char *str) { - int ret = 1; + int ret = WOLFSSL_SUCCESS; int slen = 0; WOLFSSL_ENTER("wolfSSL_ASN1_TIME_set_string"); @@ -3454,15 +4022,15 @@ int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *t, const char *str) WOLFSSL_MSG("Bad parameter"); ret = 0; } - if (ret == 1) { + if (ret == WOLFSSL_SUCCESS) { /* Get length of string including NUL terminator. */ slen = (int)XSTRLEN(str) + 1; if (slen > CTC_DATE_SIZE) { WOLFSSL_MSG("Date string too long"); - ret = 0; + ret = WOLFSSL_FAILURE; } } - if ((ret == 1) && (t != NULL)) { + if ((ret == WOLFSSL_SUCCESS) && (t != NULL)) { /* Copy in string including NUL terminator. */ XMEMCPY(t->data, str, (size_t)slen); /* Do not include NUL terminator in length. */ @@ -3475,6 +4043,21 @@ int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *t, const char *str) return ret; } +int wolfSSL_ASN1_TIME_set_string_X509(WOLFSSL_ASN1_TIME *t, const char *str) +{ + int ret = WOLFSSL_SUCCESS; + + WOLFSSL_ENTER("wolfSSL_ASN1_TIME_set_string_X509"); + + if (t == NULL) + ret = WOLFSSL_FAILURE; + if (ret == WOLFSSL_SUCCESS) + ret = wolfSSL_ASN1_TIME_set_string(t, str); + if (ret == WOLFSSL_SUCCESS) + ret = wolfSSL_ASN1_TIME_check(t); + return ret; +} + /* Convert ASN.1 TIME object to ASN.1 GENERALIZED TIME object. * * @param [in] t ASN.1 TIME object. @@ -3547,6 +4130,7 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, return ret; } +#if !defined(USER_TIME) && !defined(TIME_OVERRIDES) WOLFSSL_ASN1_TIME* wolfSSL_ASN1_UTCTIME_set(WOLFSSL_ASN1_TIME *s, time_t t) { WOLFSSL_ASN1_TIME* ret = s; @@ -3572,7 +4156,7 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_UTCTIME_set(WOLFSSL_ASN1_TIME *s, time_t t) return ret; } - +#endif /* !USER_TIME && !TIME_OVERRIDES */ #endif /* OPENSSL_EXTRA */ #if defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) @@ -4006,6 +4590,7 @@ static void wolfssl_asn1_type_free_value(WOLFSSL_ASN1_TYPE* at) #endif break; case V_ASN1_UTF8STRING: + case V_ASN1_OCTET_STRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_IA5STRING: @@ -4033,6 +4618,41 @@ void wolfSSL_ASN1_TYPE_free(WOLFSSL_ASN1_TYPE* at) XFREE(at, NULL, DYNAMIC_TYPE_OPENSSL); } +int wolfSSL_i2d_ASN1_TYPE(WOLFSSL_ASN1_TYPE* at, unsigned char** pp) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); + + if (at == NULL) + return WOLFSSL_FATAL_ERROR; + + switch (at->type) { + case V_ASN1_NULL: + break; + case V_ASN1_OBJECT: + ret = wolfSSL_i2d_ASN1_OBJECT(at->value.object, pp); + break; + case V_ASN1_UTF8STRING: + ret = wolfSSL_i2d_ASN1_UTF8STRING(at->value.utf8string, pp); + break; + case V_ASN1_GENERALIZEDTIME: + ret = wolfSSL_i2d_ASN1_GENERALSTRING(at->value.utf8string, pp); + break; + case V_ASN1_SEQUENCE: + ret = wolfSSL_i2d_ASN1_SEQUENCE(at->value.sequence, pp); + break; + case V_ASN1_UTCTIME: + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_IA5STRING: + case V_ASN1_UNIVERSALSTRING: + default: + WOLFSSL_MSG("asn1 i2d type not supported"); + break; + } + + return ret; +} + #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS) || \ @@ -4070,6 +4690,7 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_UTF8STRING: + case V_ASN1_OCTET_STRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_IA5STRING: @@ -4089,6 +4710,14 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) } } +int wolfSSL_ASN1_TYPE_get(const WOLFSSL_ASN1_TYPE *a) +{ + if (a != NULL && (a->type == V_ASN1_BOOLEAN || a->type == V_ASN1_NULL + || a->value.ptr != NULL)) + return a->type; + return 0; +} + #endif /* OPENSSL_ALL || OPENSSL_EXTRA || WOLFSSL_WPAS */ #endif /* !NO_ASN */ diff --git a/src/src/ssl_bn.c b/src/src/ssl_bn.c index c025755..227fc71 100644 --- a/src/src/ssl_bn.c +++ b/src/src/ssl_bn.c @@ -1,6 +1,6 @@ /* ssl_bn.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -64,7 +64,7 @@ static int wolfssl_bn_set_neg(WOLFSSL_BIGNUM* bn, int neg) if (BN_IS_NULL(bn)) { WOLFSSL_MSG("bn NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } #if !defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_INT_NEGATIVE) else if (neg) { @@ -102,17 +102,17 @@ int wolfssl_bn_get_value(WOLFSSL_BIGNUM* bn, mp_int* mpi) /* Validate parameters. */ if (BN_IS_NULL(bn)) { WOLFSSL_MSG("bn NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else if (mpi == NULL) { WOLFSSL_MSG("mpi NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Copy the internal representation into MP integer. */ if ((ret == 1) && mp_copy((mp_int*)bn->internal, mpi) != MP_OKAY) { WOLFSSL_MSG("mp_copy error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } return ret; @@ -145,7 +145,7 @@ int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi) /* Validate parameters. */ if ((bn == NULL) || (mpi == NULL)) { WOLFSSL_MSG("mpi or bn NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Allocate a new big number if one not passed in. */ @@ -153,7 +153,7 @@ int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi) a = wolfSSL_BN_new(); if (a == NULL) { WOLFSSL_MSG("wolfssl_bn_set_value alloc failed"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } *bn = a; } @@ -161,7 +161,7 @@ int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi) /* Copy MP integer value into internal representation of big number. */ if ((ret == 1) && (mp_copy(mpi, (mp_int*)((*bn)->internal)) != MP_OKAY)) { WOLFSSL_MSG("mp_copy error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Dispose of any allocated big number on error. */ @@ -455,7 +455,7 @@ int wolfSSL_BN_bn2bin(const WOLFSSL_BIGNUM* bn, unsigned char* r) /* Validate parameters. */ if (BN_IS_NULL(bn)) { WOLFSSL_MSG("NULL bn error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } else { /* Get the length of the encoding. */ @@ -464,7 +464,7 @@ int wolfSSL_BN_bn2bin(const WOLFSSL_BIGNUM* bn, unsigned char* r) if ((r != NULL) && (mp_to_unsigned_bin((mp_int*)bn->internal, r) != MP_OKAY)) { WOLFSSL_MSG("mp_to_unsigned_bin error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } } @@ -492,7 +492,7 @@ WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* data, int len, WOLFSSL_ENTER("wolfSSL_BN_bin2bn"); /* Validate parameters. */ - if ((data == NULL) || (len < 0)) { + if (len < 0) { ret = NULL; } /* Allocate a new big number when ret is NULL. */ @@ -507,7 +507,7 @@ WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* data, int len, if (ret->internal == NULL) { ret = NULL; } - else { + else if (data != NULL) { /* Decode into big number. */ if (mp_read_unsigned_bin((mp_int*)ret->internal, data, (word32)len) != 0) { @@ -516,10 +516,15 @@ WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* data, int len, ret = NULL; } else { - /* Don't free bn as we may be returning it. */ + /* Don't free bn as we are returning it. */ bn = NULL; } } + else if (data == NULL) { + wolfSSL_BN_zero(ret); + /* Don't free bn as we are returning it. */ + bn = NULL; + } } /* Dispose of allocated BN not being returned. */ @@ -1129,8 +1134,7 @@ int wolfSSL_BN_cmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b) ret = 0; } else { - /* NULL less than not NULL. */ - ret = -1; + ret = -1; /* NULL less than not NULL. */ } } else if (bIsNull) { @@ -1147,9 +1151,12 @@ int wolfSSL_BN_cmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b) else if (ret == MP_GT) { ret = 1; } - else { + else if (ret == MP_LT) { ret = -1; } + else { + ret = WOLFSSL_FATAL_ERROR; /* also -1 */ + } } return ret; @@ -1305,7 +1312,7 @@ static int wolfssl_bn_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, #endif /* Validate parameters. */ - if (BN_IS_NULL(bn)) { + if (ret == 1 && BN_IS_NULL(bn)) { WOLFSSL_MSG("bn NULL error"); ret = 0; } @@ -1412,6 +1419,85 @@ int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w) return ret; } +int wolfSSL_BN_mul_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) +{ + int ret = 1; +#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) +#ifdef WOLFSSL_SMALL_STACK + mp_int* w_mp = NULL; +#else + mp_int w_mp[1]; +#endif /* WOLFSSL_SMALL_STACK */ +#endif + + WOLFSSL_ENTER("wolfSSL_BN_mul_word"); + +#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) +#ifdef WOLFSSL_SMALL_STACK + /* Allocate temporary MP integer. */ + w_mp = (mp_int*)XMALLOC(sizeof(*w_mp), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (w_mp == NULL) { + ret = 0; + } + else +#endif /* WOLFSSL_SMALL_STACK */ + { + /* Clear out MP integer so it can be freed. */ + XMEMSET(w_mp, 0, sizeof(*w_mp)); + } +#endif + + /* Validate parameters. */ + if (ret == 1 && BN_IS_NULL(bn)) { + WOLFSSL_MSG("bn NULL error"); + ret = 0; + } + + if (ret == 1) { + int rc = 0; +#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) + if (w > (WOLFSSL_BN_ULONG)MP_MASK) { + /* Initialize temporary MP integer. */ + if (mp_init(w_mp) != MP_OKAY) { + ret = 0; + } + /* Set value into temporary MP integer. */ + if ((ret == 1) && (mp_set_int(w_mp, w) != MP_OKAY)) { + ret = 0; + } + if (ret == 1) { + rc = mp_mul((mp_int*)bn->internal, w_mp, + (mp_int*)bn->internal); + if (rc != MP_OKAY) { + WOLFSSL_MSG("mp_mul error"); + ret = 0; + } + } + } + else +#endif + { + rc = mp_mul_d((mp_int*)bn->internal, (mp_digit)w, + (mp_int*)bn->internal); + if (rc != MP_OKAY) { + WOLFSSL_MSG("mp_mul_d error"); + ret = 0; + } + } + } + +#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) + mp_free(w_mp); +#ifdef WOLFSSL_SMALL_STACK + XFREE(w_mp, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif /* WOLFSSL_SMALL_STACK */ +#endif + + WOLFSSL_LEAVE("wolfSSL_BN_mul_word", ret); + + return ret; +} + #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_RSA) || !defined(NO_DH) || \ !defined(NO_DSA)) /* Calculate bn modulo word w. bn % w @@ -2268,18 +2354,18 @@ int wolfSSL_BN_is_prime_ex(const WOLFSSL_BIGNUM *bn, int checks, if (BN_IS_NULL(bn)) { WOLFSSL_MSG("bn NULL error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Create a new RNG or use global. */ if ((ret == 1) && ((rng = wolfssl_make_rng(tmpRng, &localRng)) == NULL)) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if ((ret == 1) && (mp_prime_is_prime_ex((mp_int*)bn->internal, checks, &res, rng) != MP_OKAY)) { WOLFSSL_MSG("mp_prime_is_prime_ex error"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } if (localRng) { diff --git a/src/src/ssl_certman.c b/src/src/ssl_certman.c index e666059..346904e 100644 --- a/src/src/ssl_certman.c +++ b/src/src/ssl_certman.c @@ -1,6 +1,6 @@ /* ssl_certman.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -398,7 +398,7 @@ WOLFSSL_STACK* wolfSSL_CertManagerGetCerts(WOLFSSL_CERT_MANAGER* cm) } /* Decode certificate. */ - if ((!err) && (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS)) { + if ((!err) && (wolfSSL_sk_X509_push(sk, x509) <= 0)) { wolfSSL_X509_free(x509); err = 1; } @@ -455,11 +455,12 @@ int wolfSSL_CertManagerUnloadCAs(WOLFSSL_CERT_MANAGER* cm) return ret; } -int wolfSSL_CertManagerUnloadIntermediateCerts(WOLFSSL_CERT_MANAGER* cm) +static int wolfSSL_CertManagerUnloadIntermediateCertsEx( + WOLFSSL_CERT_MANAGER* cm, byte type) { int ret = WOLFSSL_SUCCESS; - WOLFSSL_ENTER("wolfSSL_CertManagerUnloadIntermediateCerts"); + WOLFSSL_ENTER("wolfSSL_CertManagerUnloadIntermediateCertsEx"); /* Validate parameter. */ if (cm == NULL) { @@ -471,7 +472,7 @@ int wolfSSL_CertManagerUnloadIntermediateCerts(WOLFSSL_CERT_MANAGER* cm) } if (ret == WOLFSSL_SUCCESS) { /* Dispose of CA table. */ - FreeSignerTableType(cm->caTable, CA_TABLE_SIZE, WOLFSSL_CHAIN_CA, + FreeSignerTableType(cm->caTable, CA_TABLE_SIZE, type, cm->heap); /* Unlock CA table. */ @@ -481,6 +482,22 @@ int wolfSSL_CertManagerUnloadIntermediateCerts(WOLFSSL_CERT_MANAGER* cm) return ret; } +#if defined(OPENSSL_EXTRA) +static int wolfSSL_CertManagerUnloadTempIntermediateCerts( + WOLFSSL_CERT_MANAGER* cm) +{ + WOLFSSL_ENTER("wolfSSL_CertManagerUnloadTempIntermediateCerts"); + return wolfSSL_CertManagerUnloadIntermediateCertsEx(cm, WOLFSSL_TEMP_CA); +} +#endif + +int wolfSSL_CertManagerUnloadIntermediateCerts( + WOLFSSL_CERT_MANAGER* cm) +{ + WOLFSSL_ENTER("wolfSSL_CertManagerUnloadIntermediateCerts"); + return wolfSSL_CertManagerUnloadIntermediateCertsEx(cm, WOLFSSL_CHAIN_CA); +} + #ifdef WOLFSSL_TRUST_PEER_CERT /* Unload the trusted peers table. * @@ -609,8 +626,7 @@ void wolfSSL_CertManagerSetVerify(WOLFSSL_CERT_MANAGER* cm, VerifyCallback vc) } #endif /* NO_WOLFSSL_CM_VERIFY */ -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB void wolfSSL_CertManagerSetUnknownExtCallback(WOLFSSL_CERT_MANAGER* cm, wc_UnknownExtCallback cb) { @@ -620,7 +636,7 @@ void wolfSSL_CertManagerSetUnknownExtCallback(WOLFSSL_CERT_MANAGER* cm, } } -#endif /* WOLFSSL_CUSTOM_OID && WOLFSSL_ASN_TEMPLATE && HAVE_OID_DECODING */ +#endif /* WC_ASN_UNKNOWN_EXT_CB */ #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) /* Verify the certificate. @@ -690,8 +706,7 @@ int CM_VerifyBuffer_ex(WOLFSSL_CERT_MANAGER* cm, const unsigned char* buff, /* Create a decoded certificate with DER buffer. */ InitDecodedCert(cert, buff, (word32)sz, cm->heap); -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB if (cm->unknownExtCallback != NULL) wc_SetUnknownExtCallback(cert, cm->unknownExtCallback); #endif @@ -1384,9 +1399,7 @@ int CM_SaveCertCache(WOLFSSL_CERT_MANAGER* cm, const char* fname) ret = FWRITE_ERROR; } } - if (mem != NULL) { - XFREE(mem, cm->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(mem, cm->heap, DYNAMIC_TYPE_TMP_BUFFER); /* Unlock CA table. */ wc_UnLockMutex(&cm->caLock); @@ -1862,6 +1875,26 @@ int wolfSSL_CertManagerSetCRL_Cb(WOLFSSL_CERT_MANAGER* cm, CbMissingCRL cb) return ret; } +int wolfSSL_CertManagerSetCRL_ErrorCb(WOLFSSL_CERT_MANAGER* cm, crlErrorCb cb, + void* ctx) +{ + int ret = WOLFSSL_SUCCESS; + + WOLFSSL_ENTER("wolfSSL_CertManagerSetCRL_Cb"); + + /* Validate parameters. */ + if (cm == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == WOLFSSL_SUCCESS) { + /* Store callback. */ + cm->crlCb = cb; + cm->crlCbCtx = ctx; + } + + return ret; +} + #ifdef HAVE_CRL_IO /* Set the CRL I/O callback. * diff --git a/src/src/ssl_crypto.c b/src/src/ssl_crypto.c index 5a05324..0730c45 100644 --- a/src/src/ssl_crypto.c +++ b/src/src/ssl_crypto.c @@ -1,6 +1,6 @@ /* ssl_crypto.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -45,8 +45,7 @@ void wolfSSL_MD4_Init(WOLFSSL_MD4_CTX* md4) { /* Ensure WOLFSSL_MD4_CTX is big enough for wolfCrypt Md4. */ - typedef char ok[sizeof(md4->buffer) >= sizeof(Md4) ? 1 : -1]; - (void)sizeof(ok); + WOLFSSL_ASSERT_SIZEOF_GE(md4->buffer, Md4); WOLFSSL_ENTER("MD4_Init"); @@ -97,8 +96,7 @@ void wolfSSL_MD4_Final(unsigned char* digest, WOLFSSL_MD4_CTX* md4) int wolfSSL_MD5_Init(WOLFSSL_MD5_CTX* md5) { /* Ensure WOLFSSL_MD5_CTX is big enough for wolfCrypt wc_Md5. */ - typedef char md5_test[sizeof(WOLFSSL_MD5_CTX) >= sizeof(wc_Md5) ? 1 : -1]; - (void)sizeof(md5_test); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_MD5_CTX, wc_Md5); WOLFSSL_ENTER("MD5_Init"); @@ -212,8 +210,7 @@ unsigned char* wolfSSL_MD5(const unsigned char* data, size_t len, int wolfSSL_SHA_Init(WOLFSSL_SHA_CTX* sha) { /* Ensure WOLFSSL_SHA_CTX is big enough for wolfCrypt wc_Sha. */ - typedef char sha_test[sizeof(WOLFSSL_SHA_CTX) >= sizeof(wc_Sha) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA_CTX, wc_Sha); WOLFSSL_ENTER("SHA_Init"); @@ -362,8 +359,7 @@ int wolfSSL_SHA1_Transform(WOLFSSL_SHA_CTX* sha, const unsigned char* data) int wolfSSL_SHA224_Init(WOLFSSL_SHA224_CTX* sha224) { /* Ensure WOLFSSL_SHA224_CTX is big enough for wolfCrypt wc_Sha224. */ - typedef char sha_test[sizeof(SHA224_CTX) >= sizeof(wc_Sha224) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA224_CTX, wc_Sha224); WOLFSSL_ENTER("SHA224_Init"); @@ -422,8 +418,7 @@ int wolfSSL_SHA224_Final(byte* output, WOLFSSL_SHA224_CTX* sha224) int wolfSSL_SHA256_Init(WOLFSSL_SHA256_CTX* sha256) { /* Ensure WOLFSSL_SHA256_CTX is big enough for wolfCrypt wc_Sha256. */ - typedef char sha_test[sizeof(SHA256_CTX) >= sizeof(wc_Sha256) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA256_CTX, wc_Sha256); WOLFSSL_ENTER("SHA256_Init"); @@ -512,8 +507,7 @@ int wolfSSL_SHA256_Transform(WOLFSSL_SHA256_CTX* sha256, int wolfSSL_SHA384_Init(WOLFSSL_SHA384_CTX* sha384) { /* Ensure WOLFSSL_SHA384_CTX is big enough for wolfCrypt wc_Sha384. */ - typedef char sha_test[sizeof(SHA384_CTX) >= sizeof(wc_Sha384) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA384_CTX, wc_Sha384); WOLFSSL_ENTER("SHA384_Init"); @@ -572,8 +566,7 @@ int wolfSSL_SHA384_Final(byte* output, WOLFSSL_SHA384_CTX* sha384) int wolfSSL_SHA512_Init(WOLFSSL_SHA512_CTX* sha512) { /* Ensure WOLFSSL_SHA512_CTX is big enough for wolfCrypt wc_Sha512. */ - typedef char sha_test[sizeof(SHA512_CTX) >= sizeof(wc_Sha512) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA512_CTX, wc_Sha512); WOLFSSL_ENTER("SHA512_Init"); @@ -809,8 +802,7 @@ int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512, int wolfSSL_SHA3_224_Init(WOLFSSL_SHA3_224_CTX* sha3_224) { /* Ensure WOLFSSL_SHA3_224_CTX is big enough for wolfCrypt wc_Sha3. */ - typedef char sha_test[sizeof(SHA3_224_CTX) >= sizeof(wc_Sha3) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA3_224_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_224_Init"); @@ -869,8 +861,7 @@ int wolfSSL_SHA3_224_Final(byte* output, WOLFSSL_SHA3_224_CTX* sha3) int wolfSSL_SHA3_256_Init(WOLFSSL_SHA3_256_CTX* sha3_256) { /* Ensure WOLFSSL_SHA3_256_CTX is big enough for wolfCrypt wc_Sha3. */ - typedef char sha_test[sizeof(SHA3_256_CTX) >= sizeof(wc_Sha3) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA3_256_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_256_Init"); @@ -929,8 +920,7 @@ int wolfSSL_SHA3_256_Final(byte* output, WOLFSSL_SHA3_256_CTX* sha3) int wolfSSL_SHA3_384_Init(WOLFSSL_SHA3_384_CTX* sha3_384) { /* Ensure WOLFSSL_SHA3_384_CTX is big enough for wolfCrypt wc_Sha3. */ - typedef char sha_test[sizeof(SHA3_384_CTX) >= sizeof(wc_Sha3) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA3_384_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_384_Init"); @@ -989,8 +979,7 @@ int wolfSSL_SHA3_384_Final(byte* output, WOLFSSL_SHA3_384_CTX* sha3) int wolfSSL_SHA3_512_Init(WOLFSSL_SHA3_512_CTX* sha3_512) { /* Ensure WOLFSSL_SHA3_512_CTX is big enough for wolfCrypt wc_Sha3. */ - typedef char sha_test[sizeof(SHA3_512_CTX) >= sizeof(wc_Sha3) ? 1 : -1]; - (void)sizeof(sha_test); + WOLFSSL_ASSERT_SIZEOF_GE(SHA3_512_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_512_Init"); @@ -2442,7 +2431,7 @@ int wolfSSL_DES_set_key_checked(WOLFSSL_const_DES_cblock* key, /* Check key parity is odd. */ if ((ret == 0) && (!wolfSSL_DES_check_key_parity(key))) { WOLFSSL_MSG("Odd parity test fail"); - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } /* Check whether key is weak. */ if ((ret == 0) && wolfSSL_DES_is_weak_key(key)) { @@ -2934,25 +2923,24 @@ void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* in, WOLFSSL_DES_cblock* out, static int wolfssl_aes_set_key(const unsigned char *key, const int bits, AES_KEY *aes, int enc) { - typedef char aes_test[sizeof(AES_KEY) >= sizeof(Aes) ? 1 : -1]; - (void)sizeof(aes_test); + wc_static_assert(sizeof(AES_KEY) >= sizeof(Aes)); /* Validate parameters. */ if ((key == NULL) || (aes == NULL)) { WOLFSSL_MSG("Null argument passed in"); - return -1; + return WOLFSSL_FATAL_ERROR; } XMEMSET(aes, 0, sizeof(AES_KEY)); if (wc_AesInit((Aes*)aes, NULL, INVALID_DEVID) != 0) { WOLFSSL_MSG("Error in initting AES key"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (wc_AesSetKey((Aes*)aes, key, ((bits)/8), NULL, enc) != 0) { WOLFSSL_MSG("Error in setting AES key"); - return -1; + return WOLFSSL_FATAL_ERROR; } return 0; } @@ -3449,8 +3437,7 @@ size_t wolfSSL_CRYPTO_cts128_decrypt(const unsigned char *in, void wolfSSL_RC4_set_key(WOLFSSL_RC4_KEY* key, int len, const unsigned char* data) { - typedef char rc4_test[sizeof(WOLFSSL_RC4_KEY) >= sizeof(Arc4) ? 1 : -1]; - (void)sizeof(rc4_test); + wc_static_assert(sizeof(WOLFSSL_RC4_KEY) >= sizeof(Arc4)); WOLFSSL_ENTER("wolfSSL_RC4_set_key"); diff --git a/src/src/ssl_load.c b/src/src/ssl_load.c index 2441d48..0361edb 100644 --- a/src/src/ssl_load.c +++ b/src/src/ssl_load.c @@ -1,6 +1,6 @@ /* ssl_load.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -137,26 +137,16 @@ static int DataToDerBuffer(const unsigned char* buff, word32 len, int format, FreeDer(der); } #else + (void)algId; ret = NOT_COMPILED_IN; #endif } /* Data in buffer is ASN.1 format - get first SEQ or OCT into der. */ else { - int length; - word32 inOutIdx = 0; - /* Get length of SEQ including header. */ if ((info->consumed = wolfssl_der_length(buff, (int)len)) > 0) { ret = 0; } - /* Private keys may be wrapped in OCT when PKCS#8 wrapper removed. - * TODO: is this really needed? */ - else if ((type == PRIVATEKEY_TYPE) && - (GetOctetString(buff, &inOutIdx, &length, len) >= 0)) { - /* Include octet string DER header. */ - info->consumed = length + inOutIdx; - ret = 0; - } else { ret = ASN_PARSE_E; } @@ -302,22 +292,11 @@ static int ProcessUserChain(WOLFSSL_CTX* ctx, WOLFSSL* ssl, WOLFSSL_ENTER("ProcessUserChain"); - /* Validate parameters. */ - if ((type == CA_TYPE) && (ctx == NULL)) { - WOLFSSL_MSG("Need context for CA load"); - ret = BAD_FUNC_ARG; - } - - /* Ignore non-certificate types. */ - if ((ret == 0) && (type != CERT_TYPE) && (type != CHAIN_CERT_TYPE) && - (type != CA_TYPE)) { - WOLFSSL_MSG("File type not a certificate"); - } /* Check we haven't consumed all the data. */ - else if ((ret == 0) && (info->consumed >= sz)) { + if (info->consumed >= sz) { WOLFSSL_MSG("Already consumed data"); } - else if (ret == 0) { + else { #ifndef WOLFSSL_SMALL_STACK byte stackBuffer[FILE_BUFFER_SIZE]; #endif @@ -884,17 +863,17 @@ static int ProcessBufferTryDecodeFalcon(WOLFSSL_CTX* ctx, WOLFSSL* ssl, ret = wc_falcon_init(key); if (ret == 0) { /* Set up key to parse the format specified. */ - if (*keyFormat == FALCON_LEVEL1k) { + if ((*keyFormat == FALCON_LEVEL1k) || ((*keyFormat == 0) && + ((der->length == FALCON_LEVEL1_KEY_SIZE) || + (der->length == FALCON_LEVEL1_PRV_KEY_SIZE)))) { ret = wc_falcon_set_level(key, 1); } - else if (*keyFormat == FALCON_LEVEL5k) { + else if ((*keyFormat == FALCON_LEVEL5k) || ((*keyFormat == 0) && + ((der->length == FALCON_LEVEL5_KEY_SIZE) || + (der->length == FALCON_LEVEL5_PRV_KEY_SIZE)))) { ret = wc_falcon_set_level(key, 5); } else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - /* TODO: get the size of the private key for different formats and - * compare with DER length. */ wc_falcon_free(key); ret = ALGO_ID_E; } @@ -935,6 +914,11 @@ static int ProcessBufferTryDecodeFalcon(WOLFSSL_CTX* ctx, WOLFSSL* ssl, /* Free dynamically allocated data in key. */ wc_falcon_free(key); } + else if ((ret == WC_NO_ERR_TRACE(ALGO_ID_E)) && (*keyFormat == 0)) { + WOLFSSL_MSG("Not a Falcon key"); + /* Format unknown so keep trying. */ + ret = 0; + } /* Dispose of allocated key. */ XFREE(key, heap, DYNAMIC_TYPE_FALCON); @@ -977,20 +961,22 @@ static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, ret = wc_dilithium_init(key); if (ret == 0) { /* Set up key to parse the format specified. */ - if (*keyFormat == DILITHIUM_LEVEL2k) { + if ((*keyFormat == DILITHIUM_LEVEL2k) || ((*keyFormat == 0) && + ((der->length == DILITHIUM_LEVEL2_KEY_SIZE) || + (der->length == DILITHIUM_LEVEL2_PRV_KEY_SIZE)))) { ret = wc_dilithium_set_level(key, 2); } - else if (*keyFormat == DILITHIUM_LEVEL3k) { + else if ((*keyFormat == DILITHIUM_LEVEL3k) || ((*keyFormat == 0) && + ((der->length == DILITHIUM_LEVEL3_KEY_SIZE) || + (der->length == DILITHIUM_LEVEL3_PRV_KEY_SIZE)))) { ret = wc_dilithium_set_level(key, 3); } - else if (*keyFormat == DILITHIUM_LEVEL5k) { + else if ((*keyFormat == DILITHIUM_LEVEL5k) || ((*keyFormat == 0) && + ((der->length == DILITHIUM_LEVEL5_KEY_SIZE) || + (der->length == DILITHIUM_LEVEL5_PRV_KEY_SIZE)))) { ret = wc_dilithium_set_level(key, 5); } else { - /* What if *keyformat is 0? We might want to do something more - * graceful here. */ - /* TODO: get the size of the private key for different formats and - * compare with DER length. */ wc_dilithium_free(key); ret = ALGO_ID_E; } @@ -1036,6 +1022,11 @@ static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, /* Free dynamically allocated data in key. */ wc_dilithium_free(key); } + else if ((ret == WC_NO_ERR_TRACE(ALGO_ID_E)) && (*keyFormat == 0)) { + WOLFSSL_MSG("Not a Dilithium key"); + /* Format unknown so keep trying. */ + ret = 0; + } /* Dispose of allocated key. */ XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); @@ -1227,8 +1218,13 @@ static int ProcessBufferPrivPkcs8Dec(EncryptedInfo* info, DerBuffer* der, der->length = (word32)ret; } - /* Ensure password is zeroized. */ - ForceZero(password, (word32)passwordSz); +#ifdef WOLFSSL_SMALL_STACK + if (password != NULL) +#endif + { + /* Ensure password is zeroized. */ + ForceZero(password, (word32)passwordSz); + } #ifdef WOLFSSL_SMALL_STACK /* Dispose of password memory. */ XFREE(password, heap, DYNAMIC_TYPE_STRING); @@ -1348,24 +1344,10 @@ static int ProcessBufferPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int algId) { int ret; -#if (defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)) || \ - defined(HAVE_PKCS8) - word32 p8AlgId = 0; -#endif (void)info; (void)format; -#ifdef HAVE_PKCS8 - /* Try and remove PKCS8 header and get algorithm id. */ - ret = ToTraditional_ex(der->buffer, der->length, &p8AlgId); - if (ret > 0) { - /* Header stripped inline. */ - der->length = (word32)ret; - algId = p8AlgId; - } -#endif - /* Put the data into the SSL or SSL context object. */ ret = ProcessBufferPrivKeyHandleDer(ctx, ssl, &der, type); if (ret == 0) { @@ -1579,7 +1561,9 @@ static void ProcessBufferCertSetHave(WOLFSSL_CTX* ctx, WOLFSSL* ssl, } #endif #ifndef WC_STRICT_SIG - wolfssl_set_have_from_key_oid(ctx, ssl, cert->keyOID); + if ((ctx != NULL) || (ssl != NULL)) { + wolfssl_set_have_from_key_oid(ctx, ssl, (int)cert->keyOID); + } #else /* Set whether ECC is available based on signature available. */ if (ssl != NULL) { @@ -2386,7 +2370,7 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, if (ret == 0) { ret = 1; } - else if (ret == WOLFSSL_FATAL_ERROR) { + else if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { ret = 0; } WOLFSSL_LEAVE("ProcessBuffer", ret); @@ -2875,6 +2859,41 @@ int wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, return WS_RETURN_CODE(ret, 0); } +/* Load a file and/or files in path, with OpenSSL-compatible semantics. + * + * No c_rehash. + * + * @param [in, out] ctx SSL context object. + * @param [in] file Name of file to load. May be NULL. + * @param [in] path Path to directory containing PEM CA files. + * May be NULL. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_load_verify_locations_compat(WOLFSSL_CTX* ctx, const char* file, + const char* path) +{ + /* We want to keep trying to load more CA certs even if one cert in the + * directory is bad and can't be used (e.g. if one is expired), and we + * want to return success if any were successfully loaded (mimicking + * OpenSSL SSL_CTX_load_verify_locations() semantics), so we use + * WOLFSSL_LOAD_FLAG_IGNORE_ERR. OpenSSL (as of v3.3.2) actually + * returns success even if no certs are loaded (e.g. because the + * supplied "path" doesn't exist or access is prohibited), and only + * returns failure if the "file" is non-null and fails to load. + * + * Note that if a file is supplied and can't be successfully loaded, the + * overall call fails and the path is never even evaluated. This is + * consistent with OpenSSL behavior. + */ + + int ret = wolfSSL_CTX_load_verify_locations_ex(ctx, file, path, + WOLFSSL_LOAD_VERIFY_DEFAULT_FLAGS | WOLFSSL_LOAD_FLAG_IGNORE_ERR); + + /* Return 1 on success or 0 on failure. */ + return WS_RETURN_CODE(ret, 0); +} + #ifdef WOLFSSL_SYS_CA_CERTS #ifdef USE_WINDOWS_API @@ -4793,7 +4812,8 @@ int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) } if (ret == 1) { /* Push the X509 object onto stack. */ - ret = wolfSSL_sk_X509_push(ctx->x509Chain, x509); + ret = wolfSSL_sk_X509_push(ctx->x509Chain, x509) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } if (ret != 1) { @@ -4820,8 +4840,7 @@ int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) WOLFSSL_ENTER("wolfSSL_add0_chain_cert"); /* Validate parameters. */ - if ((ssl == NULL) || (ssl->ctx == NULL) || (x509 == NULL) || - (x509->derCert == NULL)) { + if ((ssl == NULL) || (x509 == NULL) || (x509->derCert == NULL)) { ret = 0; } @@ -4858,7 +4877,8 @@ int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) } if (ret == 1) { /* Push X509 object onto stack to be freed. */ - ret = wolfSSL_sk_X509_push(ssl->ourCertChain, x509); + ret = wolfSSL_sk_X509_push(ssl->ourCertChain, x509) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (ret != 1) { /* Free it now on error. */ wolfSSL_X509_free(x509); @@ -4884,8 +4904,7 @@ int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) WOLFSSL_ENTER("wolfSSL_add1_chain_cert"); /* Validate parameters. */ - if ((ssl == NULL) || (ssl->ctx == NULL) || (x509 == NULL) || - (x509->derCert == NULL)) { + if ((ssl == NULL) || (x509 == NULL) || (x509->derCert == NULL)) { ret = 0; } @@ -5080,19 +5099,20 @@ int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) { int ret; -#ifdef XGETENV - char* certDir; - char* certFile; - word32 flags; +#if defined(XGETENV) && !defined(NO_GETENV) + char* certDir = NULL; + char* certFile = NULL; + word32 flags = 0; #elif !defined(WOLFSSL_SYS_CA_CERTS) (void)ctx; #endif WOLFSSL_ENTER("wolfSSL_CTX_set_default_verify_paths"); -#ifdef XGETENV - certDir = XGETENV("SSL_CERT_DIR"); - certFile = XGETENV("SSL_CERT_FILE"); +#if defined(XGETENV) && !defined(NO_GETENV) + /* // NOLINTBEGIN(concurrency-mt-unsafe) */ + certDir = wc_strdup_ex(XGETENV("SSL_CERT_DIR"), DYNAMIC_TYPE_TMP_BUFFER); + certFile = wc_strdup_ex(XGETENV("SSL_CERT_FILE"), DYNAMIC_TYPE_TMP_BUFFER); flags = WOLFSSL_LOAD_FLAG_PEM_CA_ONLY; if ((certDir != NULL) || (certFile != NULL)) { @@ -5114,6 +5134,7 @@ int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) ret = 0; } } + /* // NOLINTEND(concurrency-mt-unsafe) */ else #endif @@ -5125,7 +5146,7 @@ int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) #elif defined(WOLFSSL_SYS_CA_CERTS) /* Load the system CA certificates. */ ret = wolfSSL_CTX_load_system_CA_certs(ctx); - if (ret == WOLFSSL_BAD_PATH) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_BAD_PATH)) { /* OpenSSL doesn't treat the lack of a system CA cert directory as a * failure. We do the same here. */ @@ -5138,6 +5159,10 @@ int wolfSSL_CTX_set_default_verify_paths(WOLFSSL_CTX* ctx) #endif } +#if defined(XGETENV) && !defined(NO_GETENV) + XFREE(certFile, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(certDir, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif WOLFSSL_LEAVE("wolfSSL_CTX_set_default_verify_paths", ret); return ret; @@ -5250,9 +5275,10 @@ int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz, if (ret == 1) { /* Allocate buffers for p and g to be assigned into SSL. */ - pAlloc = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - gAlloc = (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + pAlloc = (byte*)XMALLOC((size_t)pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + gAlloc = (byte*)XMALLOC((size_t)gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); if ((pAlloc == NULL) || (gAlloc == NULL)) { + /* Memory will be freed below in the (ret != 1) block */ ret = MEMORY_E; } } @@ -5309,7 +5335,7 @@ static int wolfssl_check_dh_key(unsigned char* p, int pSz, unsigned char* g, /* Initialize a DH object. */ if ((ret = wc_InitDhKey(checkKey)) == 0) { /* Check DH parameters. */ - ret = wc_DhSetCheckKey(checkKey, p, (word32)pSz, g, gSz, NULL, 0, 0, &rng); + ret = wc_DhSetCheckKey(checkKey, p, (word32)pSz, g, (word32)gSz, NULL, 0, 0, &rng); /* Dispose of DH object. */ wc_FreeDhKey(checkKey); } @@ -5408,13 +5434,9 @@ int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz, if (ret == 1) { /* Allocate buffers for p and g to be assigned into SSL context. */ - pAlloc = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - gAlloc = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + pAlloc = (byte*)XMALLOC((size_t)pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + gAlloc = (byte*)XMALLOC((size_t)gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); if ((pAlloc == NULL) || (gAlloc == NULL)) { - XFREE(pAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - pAlloc = NULL; - XFREE(gAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - gAlloc = NULL; ret = MEMORY_E; } } @@ -5427,12 +5449,10 @@ int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz, ret = wolfssl_ctx_set_tmp_dh(ctx, pAlloc, pSz, gAlloc, gSz); } - if (ret != 1) { + if ((ret != 1) && (ctx != NULL)) { /* Free the allocated buffers if not assigned into SSL context. */ - if (pAlloc) - XFREE(pAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (gAlloc) - XFREE(gAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(pAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(gAlloc, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); } return ret; } @@ -5465,7 +5485,7 @@ long wolfSSL_set_tmp_dh(WOLFSSL *ssl, WOLFSSL_DH *dh) } if (ret == 1) { - /* Get needed size for p and g. */ + /* Get sizes of p and g. */ pSz = wolfSSL_BN_bn2bin(dh->p, NULL); gSz = wolfSSL_BN_bn2bin(dh->g, NULL); /* Validate p and g size. */ @@ -5496,7 +5516,7 @@ long wolfSSL_set_tmp_dh(WOLFSSL *ssl, WOLFSSL_DH *dh) ret = wolfssl_set_tmp_dh(ssl, p, pSz, g, gSz); } - if (ret != 1 && ssl != NULL) { + if ((ret != 1) && (ssl != NULL)) { /* Free the allocated buffers if not assigned into SSL. */ XFREE(p, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); XFREE(g, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -5531,7 +5551,7 @@ long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh) } if (ret == 1) { - /* Get needed size for p and g. */ + /* Get sizes of p and g. */ pSz = wolfSSL_BN_bn2bin(dh->p, NULL); gSz = wolfSSL_BN_bn2bin(dh->g, NULL); /* Validate p and g size. */ @@ -5563,7 +5583,7 @@ long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh) ret = wolfssl_ctx_set_tmp_dh(ctx, p, pSz, g, gSz); } - if (ret != 1 && ctx != NULL) { + if ((ret != 1) && (ctx != NULL)) { /* Free the allocated buffers if not assigned into SSL. */ XFREE(p, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); XFREE(g, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -5670,11 +5690,11 @@ static int ws_ctx_ssl_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL* ssl, } else if (ssl != NULL) { /* Set p and g into SSL. */ - res = wolfssl_set_tmp_dh(ssl, p, (int)pSz, g, gSz); + res = wolfssl_set_tmp_dh(ssl, p, (int)pSz, g, (int)gSz); } else { /* Set p and g into SSL context. */ - res = wolfssl_ctx_set_tmp_dh(ctx, p, (int)pSz, g, gSz); + res = wolfssl_ctx_set_tmp_dh(ctx, p, (int)pSz, g, (int)gSz); } } diff --git a/src/src/ssl_misc.c b/src/src/ssl_misc.c index d52c2cd..9a5f4b0 100644 --- a/src/src/ssl_misc.c +++ b/src/src/ssl_misc.c @@ -1,6 +1,6 @@ /* ssl_misc.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -165,7 +165,15 @@ static int wolfssl_read_bio(WOLFSSL_BIO* bio, char** data, int* dataSz, if (bio->type == WOLFSSL_BIO_MEMORY) { ret = wolfSSL_BIO_get_mem_data(bio, data); if (ret > 0) { - bio->rdIdx += ret; + /* Advance the write index in the memory bio */ + WOLFSSL_BIO* mem_bio = bio; + for (; mem_bio != NULL; mem_bio = mem_bio->next) { + if (mem_bio->type == WOLFSSL_BIO_MEMORY) + break; + } + if (mem_bio == NULL) + mem_bio = bio; /* Default to input */ + mem_bio->rdIdx += ret; } *memAlloced = 0; } diff --git a/src/src/ssl_p7p12.c b/src/src/ssl_p7p12.c index 11b6c40..fba2767 100644 --- a/src/src/ssl_p7p12.c +++ b/src/src/ssl_p7p12.c @@ -94,8 +94,7 @@ void wolfSSL_PKCS7_free(PKCS7* pkcs7) WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7; if (p7 != NULL) { - if (p7->data != NULL) - XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); wc_PKCS7_Free(&p7->pkcs7); if (p7->certs) wolfSSL_sk_pop_free(p7->certs, NULL); @@ -230,7 +229,7 @@ WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7) if (!ret) ret = wolfSSL_sk_X509_new_null(); if (x509) { - if (wolfSSL_sk_X509_push(ret, x509) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(ret, x509) <= 0) { wolfSSL_X509_free(x509); WOLFSSL_MSG("wolfSSL_sk_X509_push error"); goto error; @@ -295,7 +294,7 @@ WOLFSSL_STACK* wolfSSL_PKCS7_get0_signers(PKCS7* pkcs7, WOLFSSL_STACK* certs, return NULL; } - if (wolfSSL_sk_X509_push(signers, x509) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(signers, x509) <= 0) { wolfSSL_sk_X509_pop_free(signers, NULL); return NULL; } @@ -352,7 +351,7 @@ int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out) int localBuf = 0; int len; WC_RNG rng; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_i2d_PKCS7"); if (!out || !p7) { @@ -397,9 +396,9 @@ int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out) wc_FreeRng(&rng); p7->rng = NULL; } - if (ret == WOLFSSL_FAILURE && localBuf && output) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE) && localBuf) XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (ret != WOLFSSL_FAILURE) + if (ret != WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) *out = output; return ret; } @@ -408,7 +407,7 @@ int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7) { byte* output = NULL; int len; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_i2d_PKCS7_bio"); if (!bio || !p7) { @@ -416,7 +415,9 @@ int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7) return WOLFSSL_FAILURE; } - if ((len = wolfSSL_i2d_PKCS7(p7, &output)) == WOLFSSL_FAILURE) { + if ((len = wolfSSL_i2d_PKCS7(p7, &output)) == + WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { WOLFSSL_MSG("wolfSSL_i2d_PKCS7 error"); goto cleanup; } @@ -428,8 +429,7 @@ int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7) ret = WOLFSSL_SUCCESS; cleanup: - if (output) - XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -602,7 +602,7 @@ static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out) canonLineLen = (word32)lineLen; if ((canonLine = wc_MIME_single_canonicalize( line, &canonLineLen)) == NULL) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } @@ -612,7 +612,7 @@ static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out) } if (wolfSSL_BIO_write(out, canonLine, (int)canonLineLen) < 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); @@ -621,15 +621,13 @@ static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out) else { /* no line ending in current line, write direct to out */ if (wolfSSL_BIO_write(out, line, lineLen) < 0) { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } } } - if (canonLine != NULL) { - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); - } + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); #ifdef WOLFSSL_SMALL_STACK XFREE(line, in->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -718,9 +716,7 @@ int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags) } } - if (mem != NULL) { - XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER); } else { #ifdef HAVE_SMIME @@ -746,9 +742,7 @@ int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags) } if (ret == 1) { - if (p7->data != NULL) { - XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); - } + XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7); p7->data = (byte*)XMALLOC(memSz, NULL, DYNAMIC_TYPE_PKCS7); if (p7->data == NULL) { ret = 0; @@ -1040,19 +1034,11 @@ int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7) error: #ifdef WOLFSSL_SMALL_STACK - if (outputHead) { - XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (outputFoot) { - XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - if (output) { - XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (pem) { - XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FAILURE; } @@ -1168,7 +1154,8 @@ PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, } XMEMSET(boundary, 0, (word32)(boundLen+1)); boundary[0] = boundary[1] = '-'; - XSTRNCPY(&boundary[2], curParam->value, boundLen-2); + /* analyzers have issues with using strncpy and strcpy here */ + XMEMCPY(&boundary[2], curParam->value, boundLen - 2); /* Parse up to first boundary, ignore everything here. */ lineLen = wolfSSL_BIO_gets(in, section, remainLen); @@ -1387,10 +1374,8 @@ PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7); XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7); XFREE(section, NULL, DYNAMIC_TYPE_PKCS7); - if (canonSection != NULL) - XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); - if (canonLine != NULL) - XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7); if (bcont) { wolfSSL_BIO_free(*bcont); *bcont = NULL; /* reset 'bcount' pointer to NULL on failure */ @@ -1491,7 +1476,9 @@ int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in, if (ret > 0) { /* Generate signedData bundle, DER in output (dynamic) */ - if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) == WOLFSSL_FAILURE) { + if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) == + WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { WOLFSSL_MSG("Error in wolfSSL_i2d_PKCS7"); ret = 0; } @@ -1607,12 +1594,8 @@ int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in, } } - if (p7out != NULL) { - XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } - if (sigBase64 != NULL) { - XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (ret > 0) { return WOLFSSL_SUCCESS; @@ -1704,8 +1687,7 @@ WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12) } /* cleanup */ - if (mem != NULL) - XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); if (ret < 0 && localPkcs12 != NULL) { wc_PKCS12_free(localPkcs12); localPkcs12 = NULL; @@ -1725,7 +1707,7 @@ WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12) */ int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_i2d_PKCS12_bio"); @@ -1740,9 +1722,7 @@ int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12) } } - if (certDer != NULL) { - XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS); - } + XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS); } return ret; @@ -1904,12 +1884,8 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, *ca = (WOLF_STACK_OF(WOLFSSL_X509)*)XMALLOC( sizeof(WOLF_STACK_OF(WOLFSSL_X509)), heap, DYNAMIC_TYPE_X509); if (*ca == NULL) { - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); /* Free up WC_DerCertList and move on */ while (current != NULL) { WC_DerCertList* next = current->next; @@ -1943,12 +1919,8 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, FreeDecodedCert(DeCert); wolfSSL_X509_free(x509); wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); /* Free up WC_DerCertList */ while (current != NULL) { WC_DerCertList* next = current->next; @@ -1962,16 +1934,12 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, } FreeDecodedCert(DeCert); - if (wolfSSL_sk_X509_push(*ca, x509) != 1) { + if (wolfSSL_sk_X509_push(*ca, x509) <= 0) { WOLFSSL_MSG("Failed to push x509 onto stack"); wolfSSL_X509_free(x509); wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } - if (certData != NULL) { - XFREE(certData, heap, DYNAMIC_TYPE_PKCS); - } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(certData, heap, DYNAMIC_TYPE_PKCS); /* Free up WC_DerCertList */ while (current != NULL) { @@ -1997,9 +1965,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, *cert = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap, DYNAMIC_TYPE_X509); if (*cert == NULL) { - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); if (ca != NULL) { wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; } @@ -2015,9 +1981,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, if (CopyDecodedToX509(*cert, DeCert) != 0) { WOLFSSL_MSG("Failed to copy decoded cert"); FreeDecodedCert(DeCert); - if (pk != NULL) { - XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); - } + XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); if (ca != NULL) { wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; } @@ -2064,8 +2028,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, } } #endif /* HAVE_ECC */ - if (pk != NULL) - XFREE(pk, heap, DYNAMIC_TYPE_PKCS); + XFREE(pk, heap, DYNAMIC_TYPE_PKCS); if (ret != 0) { /* if is in fail state and no PKEY then fail */ wolfSSL_X509_free(*cert); *cert = NULL; if (ca != NULL) { diff --git a/src/src/ssl_sess.c b/src/src/ssl_sess.c index 43ce1f5..91f2c84 100644 --- a/src/src/ssl_sess.c +++ b/src/src/ssl_sess.c @@ -1004,7 +1004,7 @@ WOLFSSL_SESSION* wolfSSL_GetSessionClient(WOLFSSL* ssl, const byte* id, int len) #else current = &sessRow->Sessions[clSess[idx].serverIdx]; #endif - if (current && XMEMCMP(current->serverID, id, len) == 0) { + if (current && XMEMCMP(current->serverID, id, (unsigned long)len) == 0) { WOLFSSL_MSG("Found a serverid match for client"); if (LowResTimer() < (current->bornOn + current->timeout)) { WOLFSSL_MSG("Session valid"); @@ -1309,8 +1309,7 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) output->ticketLenAlloc = 0; } #ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif return WOLFSSL_FAILURE; } @@ -1330,16 +1329,12 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) output->ticketLenAlloc = 0; } #ifdef WOLFSSL_TLS13 - if (preallocNonce != NULL) { - XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); - preallocNonce = NULL; - } + XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); + preallocNonce = NULL; #endif /* WOLFSSL_TLS13 */ #ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) { - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); - tmpTicket = NULL; - } + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); + tmpTicket = NULL; #endif #endif } @@ -1413,12 +1408,11 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) output->ticketLen = 0; } if (error == WOLFSSL_SUCCESS) { - XMEMCPY(output->ticket, tmpTicket, output->ticketLen); + XMEMCPY(output->ticket, tmpTicket, output->ticketLen); /* cppcheck-suppress uninitvar */ } } #ifdef WOLFSSL_SMALL_STACK - if (tmpTicket != NULL) - XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(tmpTicket, output->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ @@ -1455,8 +1449,7 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) preallocNonce = NULL; } } - if (preallocNonce != NULL) - XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); #endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ #endif @@ -1632,7 +1625,7 @@ ClientSession* AddSessionToClientCache(int side, int row, int idx, ID_LEN, &error) % CLIENT_SESSION_ROWS; } else { - error = -1; + error = WOLFSSL_FATAL_ERROR; } if (error == 0 && wc_LockMutex(&clisession_mutex) == 0) { clientIdx = (word32)ClientCache[clientRow].nextIdx; @@ -1651,7 +1644,7 @@ ClientSession* AddSessionToClientCache(int side, int row, int idx, } } else { - error = -1; + error = WOLFSSL_FATAL_ERROR; ClientCache[clientRow].nextIdx = 0; /* reset index as safety */ WOLFSSL_MSG("Invalid client cache index! " "Possible corrupted memory"); @@ -1716,14 +1709,14 @@ WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) if (clientSession->serverRow >= SESSION_ROWS || clientSession->serverIdx >= SESSIONS_PER_ROW) { WOLFSSL_MSG("Client cache serverRow or serverIdx invalid"); - error = -1; + error = WOLFSSL_FATAL_ERROR; } - /* Prevent memory access before clientSession->serverRow and - * clientSession->serverIdx are sanitized. */ - XFENCE(); if (error == 0) { /* Lock row */ sessRow = &SessionCache[clientSession->serverRow]; + /* Prevent memory access before clientSession->serverRow and + * clientSession->serverIdx are sanitized. */ + XFENCE(); error = SESSION_ROW_RD_LOCK(sessRow); if (error != 0) { WOLFSSL_MSG("Session cache row lock failure"); @@ -1736,10 +1729,12 @@ WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session) #else cacheSession = &sessRow->Sessions[clientSession->serverIdx]; #endif + /* Prevent memory access */ + XFENCE(); if (cacheSession && cacheSession->sessionIDSz == 0) { cacheSession = NULL; WOLFSSL_MSG("Session cache entry not set"); - error = -1; + error = WOLFSSL_FATAL_ERROR; } } if (error == 0) { @@ -1839,8 +1834,7 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, preallocNonce = (byte*)XMALLOC(addSession->ticketNonce.len, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); if (preallocNonce == NULL) { - if (ticBuff != NULL) - XFREE(ticBuff, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(ticBuff, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); return MEMORY_E; } preallocNonceLen = addSession->ticketNonce.len; @@ -1855,7 +1849,8 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, WOLFSSL_MSG("Hash session failed"); #ifdef HAVE_SESSION_TICKET XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); #endif #endif @@ -1866,7 +1861,8 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, if (SESSION_ROW_WR_LOCK(sessRow) != 0) { #ifdef HAVE_SESSION_TICKET XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); #endif #endif @@ -1905,7 +1901,8 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, if (cacheSession == NULL) { #ifdef HAVE_SESSION_TICKET XFREE(ticBuff, NULL, DYNAMIC_TYPE_SESSION_TICK); - #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) + #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) XFREE(preallocNonce, addSession->heap, DYNAMIC_TYPE_SESSION_TICK); #endif #endif @@ -1994,10 +1991,12 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13) && \ defined(WOLFSSL_TICKET_NONCE_MALLOC) && \ (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) - ret = wolfSSL_DupSessionEx(addSession, cacheSession, 1, preallocNonce, - &preallocNonceLen, &preallocNonceUsed) == WOLFSSL_FAILURE; + ret = (wolfSSL_DupSessionEx(addSession, cacheSession, 1, preallocNonce, + &preallocNonceLen, &preallocNonceUsed) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)); #else - ret = wolfSSL_DupSession(addSession, cacheSession, 1) == WOLFSSL_FAILURE; + ret = (wolfSSL_DupSession(addSession, cacheSession, 1) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)); #endif /* HAVE_SESSION_TICKET && WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) @@ -3906,8 +3905,7 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, } } else { - if (ticBuff != NULL) - XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); + XFREE(ticBuff, output->heap, DYNAMIC_TYPE_SESSION_TICK); output->ticket = output->staticTicket; output->ticketLenAlloc = 0; } @@ -4237,7 +4235,7 @@ const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session) int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_SESSION_set_ex_data"); #ifdef HAVE_EX_DATA session = ClientSessionToSession(session); diff --git a/src/src/tls.c b/src/src/tls.c index 6529216..8441acf 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -1,6 +1,6 @@ /* tls.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -52,7 +52,7 @@ #include #ifdef WOLFSSL_WC_KYBER #include -#elif defined(HAVE_LIBOQS) || defined(HAVE_PQM4) +#elif defined(HAVE_LIBOQS) #include #endif #endif @@ -760,6 +760,15 @@ int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content, if (ssl == NULL || inner == NULL) return BAD_FUNC_ARG; + if (content == dtls12_cid +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + || (ssl->options.dtls && DtlsGetCidTxSize(ssl) > 0) +#endif + ) { + WOLFSSL_MSG("wolfSSL_SetTlsHmacInner doesn't support CID"); + return BAD_FUNC_ARG; + } + XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ); WriteSEQ(ssl, verify, inner); @@ -918,10 +927,11 @@ static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac) * in Message data. * sz Size of the message data. * header Constructed record header with length of handshake data. + * headerSz Length of header * returns 0 on success, otherwise failure. */ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, - word32 sz, int macLen, byte* header) + word32 sz, int macLen, byte* header, word32 headerSz) { byte lenBytes[8]; int i, j; @@ -929,7 +939,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, int blockBits, blockMask; int lastBlockLen, extraLen, eocIndex; int blocks, safeBlocks, lenBlock, eocBlock; - unsigned int maxLen; + word32 maxLen; int blockSz, padSz; int ret; word32 realLen; @@ -982,29 +992,30 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, blockMask = blockSz - 1; /* Size of data to HMAC if padding length byte is zero. */ - maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen; + maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - (word32)macLen; + /* Complete data (including padding) has block for EOC and/or length. */ - extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz); + extraBlock = ctSetLTE(((int)maxLen + padSz) & blockMask, padSz); /* Total number of blocks for data including padding. */ - blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock; + blocks = ((int)(maxLen + (word32)blockSz - 1) >> blockBits) + extraBlock; /* Up to last 6 blocks can be hashed safely. */ safeBlocks = blocks - 6; /* Length of message data. */ realLen = maxLen - in[sz - 1]; /* Number of message bytes in last block. */ - lastBlockLen = realLen & blockMask; + lastBlockLen = (int)realLen & blockMask; /* Number of padding bytes in last block. */ extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1; /* Number of blocks to create for hash. */ - lenBlock = (realLen + extraLen) >> blockBits; + lenBlock = ((int)realLen + extraLen) >> blockBits; /* Block containing EOC byte. */ - eocBlock = realLen >> blockBits; + eocBlock = (int)(realLen >> (word32)blockBits); /* Index of EOC byte in block. */ - eocIndex = realLen & blockMask; + eocIndex = (int)(realLen & (word32)blockMask); /* Add length of hmac's ipad to total length. */ - realLen += blockSz; + realLen += (word32)blockSz; /* Length as bits - 8 bytes bigendian. */ c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes); c32toa(realLen << 3, lenBytes + sizeof(word32)); @@ -1016,11 +1027,12 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, XMEMSET(hmac->innerHash, 0, macLen); if (safeBlocks > 0) { - ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ); + ret = Hmac_HashUpdate(hmac, header, headerSz); if (ret != 0) return ret; - ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz - - WOLFSSL_TLS_HMAC_INNER_SZ); + ret = Hmac_HashUpdate(hmac, in, (word32)(safeBlocks * blockSz - + WOLFSSL_TLS_HMAC_INNER_SZ)); + if (ret != 0) return ret; } @@ -1039,10 +1051,10 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock; unsigned char b = 0; - if (k < WOLFSSL_TLS_HMAC_INNER_SZ) + if (k < headerSz) b = header[k]; else if (k < maxLen) - b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ]; + b = in[k - headerSz]; k++; b = ctMaskSel(atEoc, 0x80, b); @@ -1056,7 +1068,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, hashBlock[j] = b; } - ret = Hmac_HashUpdate(hmac, hashBlock, (word32)blockSz); + ret = Hmac_HashUpdate(hmac, hashBlock, (word32)blockSz); /* cppcheck-suppress uninitvar */ if (ret != 0) return ret; ret = Hmac_HashFinalRaw(hmac, hashBlock); @@ -1085,10 +1097,11 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, * in Message data. * sz Size of the message data. * header Constructed record header with length of handshake data. + * headerSz Length of header * returns 0 on success, otherwise failure. */ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, - word32 sz, byte* header) + word32 sz, byte* header, word32 headerSz) { byte dummy[WC_MAX_BLOCK_SIZE] = {0}; int ret = 0; @@ -1174,7 +1187,7 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, /* Calculate whole blocks. */ msgBlocks--; - ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ); + ret = wc_HmacUpdate(hmac, header, headerSz); if (ret == 0) { /* Fill the rest of the block with any available data. */ word32 currSz = ctMaskLT((int)msgSz, blockSz) & msgSz; @@ -1210,11 +1223,66 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, #endif +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#define TLS_HMAC_CID_SZ(s, v) \ + ((v) ? DtlsGetCidRxSize((s)) \ + : DtlsGetCidTxSize((s))) +#define TLS_HMAC_CID(s, v, b, c) \ + ((v) ? wolfSSL_dtls_cid_get_rx((s), (b), (c)) \ + : wolfSSL_dtls_cid_get_tx((s), (b), (c))) +#endif + +static int TLS_hmac_SetInner(WOLFSSL* ssl, byte* inner, word32* innerSz, + word32 sz, int content, int verify, int epochOrder) +{ +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + unsigned int cidSz = 0; + if (ssl->options.dtls && (cidSz = TLS_HMAC_CID_SZ(ssl, verify)) > 0) { + word32 idx = 0; + if (cidSz > DTLS_CID_MAX_SIZE) { + WOLFSSL_MSG("DTLS CID too large"); + return DTLS_CID_ERROR; + } + + XMEMSET(inner + idx, 0xFF, SEQ_SZ); + idx += SEQ_SZ; + inner[idx++] = dtls12_cid; + inner[idx++] = (byte)cidSz; + inner[idx++] = dtls12_cid; + inner[idx++] = ssl->version.major; + inner[idx++] = ssl->version.minor; + WriteSEQ(ssl, epochOrder, inner + idx); + idx += SEQ_SZ; + if (TLS_HMAC_CID(ssl, verify, inner + idx, cidSz) == + WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + WOLFSSL_MSG("DTLS CID write failed"); + return DTLS_CID_ERROR; + } + idx += cidSz; + c16toa((word16)sz, inner + idx); + idx += LENGTH_SZ; + + *innerSz = idx; + return 0; + } +#endif + *innerSz = WOLFSSL_TLS_HMAC_INNER_SZ; + return wolfSSL_SetTlsHmacInner(ssl, inner, sz, content, + !ssl->options.dtls ? verify : epochOrder); +} + +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#define TLS_HMAC_INNER_SZ WOLFSSL_TLS_HMAC_CID_INNER_SZ +#else +#define TLS_HMAC_INNER_SZ WOLFSSL_TLS_HMAC_INNER_SZ +#endif + int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, int content, int verify, int epochOrder) { Hmac hmac; - byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ]; + byte myInner[TLS_HMAC_INNER_SZ]; + word32 innerSz = TLS_HMAC_INNER_SZ; int ret = 0; const byte* macSecret = NULL; word32 hashSz = 0; @@ -1242,10 +1310,10 @@ int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, } #endif - if (!ssl->options.dtls) - wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify); - else - wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder); + ret = TLS_hmac_SetInner(ssl, myInner, &innerSz, sz, content, verify, + epochOrder); + if (ret != 0) + return ret; ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId); if (ret != 0) @@ -1256,10 +1324,8 @@ int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, if (ssl->options.dtls) macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder); else - macSecret = wolfSSL_GetMacSecret(ssl, verify); -#else - macSecret = wolfSSL_GetMacSecret(ssl, verify); #endif + macSecret = wolfSSL_GetMacSecret(ssl, verify); ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl), macSecret, ssl->specs.hash_size); @@ -1272,21 +1338,23 @@ int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, #ifdef HAVE_BLAKE2 if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) { ret = Hmac_UpdateFinal(&hmac, digest, in, - sz + hashSz + padSz + 1, myInner); + sz + hashSz + padSz + 1, myInner, innerSz); } else #endif { ret = Hmac_UpdateFinal_CT(&hmac, digest, in, - sz + hashSz + padSz + 1, hashSz, myInner); + (sz + hashSz + (word32)padSz + 1), + (int)hashSz, myInner, innerSz); + } #else ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1, - myInner); + myInner, innerSz); #endif } else { - ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner)); + ret = wc_HmacUpdate(&hmac, myInner, innerSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, in, sz); /* content */ if (ret == 0) @@ -1830,7 +1898,7 @@ static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length, byte isRequest) { word16 size = 0, offset = 0, wlen; - int r = BUFFER_ERROR; + int r = WC_NO_ERR_TRACE(BUFFER_ERROR); const byte *s; if (OPAQUE16_LEN > length) @@ -2682,8 +2750,7 @@ static void TLSX_TCA_Free(TCA* tca, void* heap) (void)heap; if (tca) { - if (tca->id) - XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX); + XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX); XFREE(tca, heap, DYNAMIC_TYPE_TLSX); } } @@ -3117,51 +3184,64 @@ int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap) static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap) { + int i; + switch (csr->status_type) { case WOLFSSL_CSR_OCSP: - FreeOcspRequest(&csr->request.ocsp); + for (i = 0; i <= csr->requests; i++) { + FreeOcspRequest(&csr->request.ocsp[i]); + } break; } - #ifdef WOLFSSL_TLS13 - if (csr->response.buffer != NULL) { - XFREE(csr->response.buffer, csr->ssl->heap, + for (i = 0; i < MAX_CERT_EXTENSIONS; i++) { + if (csr->responses[i].buffer != NULL) { + XFREE(csr->responses[i].buffer, heap, DYNAMIC_TYPE_TMP_BUFFER); + } } #endif XFREE(csr, heap, DYNAMIC_TYPE_TLSX); (void)heap; } -static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest) +word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr, byte isRequest, + int idx) { word16 size = 0; /* shut up compiler warnings */ (void) csr; (void) isRequest; - #ifndef NO_WOLFSSL_CLIENT if (isRequest) { switch (csr->status_type) { case WOLFSSL_CSR_OCSP: size += ENUM_LEN + 2 * OPAQUE16_LEN; - if (csr->request.ocsp.nonceSz) + if (csr->request.ocsp[0].nonceSz) size += OCSP_NONCE_EXT_SZ; break; } } #endif #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) - if (!isRequest && csr->ssl->options.tls1_3) - return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length; + if (!isRequest && IsAtLeastTLSv1_3(csr->ssl->version)) { + return (word16)(OPAQUE8_LEN + OPAQUE24_LEN + + csr->responses[idx].length); + } +#else + (void)idx; #endif - return size; } -static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, - byte isRequest) +static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest) +{ + return TLSX_CSR_GetSize_ex(csr, isRequest, 0); +} + +int TLSX_CSR_Write_ex(CertificateStatusRequest* csr, byte* output, + byte isRequest, int idx) { /* shut up compiler warnings */ (void) csr; (void) output; (void) isRequest; @@ -3182,8 +3262,8 @@ static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, offset += OPAQUE16_LEN; /* request extensions */ - if (csr->request.ocsp.nonceSz) { - ret = (int)EncodeOcspRequestExtensions(&csr->request.ocsp, + if (csr->request.ocsp[0].nonceSz) { + ret = (int)EncodeOcspRequestExtensions(&csr->request.ocsp[0], output + offset + OPAQUE16_LEN, OCSP_NONCE_EXT_SZ); @@ -3205,20 +3285,112 @@ static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, } #endif #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) - if (!isRequest && csr->ssl->options.tls1_3) { + if (!isRequest && IsAtLeastTLSv1_3(csr->ssl->version)) { word16 offset = 0; output[offset++] = csr->status_type; - c32to24(csr->response.length, output + offset); + c32to24(csr->responses[idx].length, output + offset); offset += OPAQUE24_LEN; - XMEMCPY(output + offset, csr->response.buffer, csr->response.length); - offset += csr->response.length; + XMEMCPY(output + offset, csr->responses[idx].buffer, + csr->responses[idx].length); + offset += (word16)csr->responses[idx].length; return offset; } +#else + (void)idx; #endif return 0; } +static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output, + byte isRequest) +{ + return TLSX_CSR_Write_ex(csr, output, isRequest, 0); +} + +#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_TLS13) && \ + defined(WOLFSSL_TLS_OCSP_MULTI) +/* Process OCSP request certificate chain + * + * ssl SSL/TLS object. + * returns 0 on success, otherwise failure. + */ +static int ProcessChainOCSPRequest(WOLFSSL* ssl) +{ + DecodedCert* cert; + OcspRequest* request; + TLSX* extension; + CertificateStatusRequest* csr; + DerBuffer* chain; + word32 pos = 0; + buffer der; + int i = 1; + int ret = 0; + byte ctxOwnsRequest = 0; + + /* use certChain if available, otherwise use peer certificate */ + chain = ssl->buffers.certChain; + if (chain == NULL) { + chain = ssl->buffers.certificate; + } + + extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); + csr = extension ? + (CertificateStatusRequest*)extension->data : NULL; + if (csr == NULL) + return MEMORY_ERROR; + + cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap, + DYNAMIC_TYPE_DCERT); + if (cert == NULL) { + return MEMORY_E; + } + + if (chain && chain->buffer) { + while (ret == 0 && pos + OPAQUE24_LEN < chain->length) { + c24to32(chain->buffer + pos, &der.length); + pos += OPAQUE24_LEN; + der.buffer = chain->buffer + pos; + pos += der.length; + + if (pos > chain->length) + break; + request = &csr->request.ocsp[i]; + if (ret == 0) { + ret = CreateOcspRequest(ssl, request, cert, + der.buffer, der.length, &ctxOwnsRequest); + if (ctxOwnsRequest) { + wolfSSL_Mutex* ocspLock = + &SSL_CM(ssl)->ocsp_stapling->ocspLock; + if (wc_LockMutex(ocspLock) == 0) { + /* the request is ours */ + ssl->ctx->certOcspRequest = NULL; + } + wc_UnLockMutex(ocspLock); + } + } + + if (ret == 0) { + request->ssl = ssl; + ret = CheckOcspRequest(SSL_CM(ssl)->ocsp_stapling, + request, &csr->responses[i], ssl->heap); + /* Suppressing, not critical */ + if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) || + ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) || + ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) { + ret = 0; + } + i++; + csr->requests++; + } + } + } + XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); + + return ret; +} +#endif + static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte isRequest) { @@ -3273,14 +3445,14 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, switch (csr->status_type) { case WOLFSSL_CSR_OCSP: /* propagate nonce */ - if (csr->request.ocsp.nonceSz) { + if (csr->request.ocsp[0].nonceSz) { request = (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions); if (request) { - XMEMCPY(request->nonce, csr->request.ocsp.nonce, - csr->request.ocsp.nonceSz); - request->nonceSz = csr->request.ocsp.nonceSz; + XMEMCPY(request->nonce, csr->request.ocsp[0].nonce, + csr->request.ocsp[0].nonceSz); + request->nonceSz = csr->request.ocsp[0].nonceSz; } } break; @@ -3311,14 +3483,21 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, ret = BUFFER_ERROR; } if (ret == 0) { - csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap, + if (ssl->response_idx < (1 + MAX_CHAIN_DEPTH)) + csr->responses[ssl->response_idx].buffer = + (byte*)XMALLOC(resp_length, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (csr->response.buffer == NULL) + else + ret = BAD_FUNC_ARG; + + if (ret == 0 && + csr->responses[ssl->response_idx].buffer == NULL) ret = MEMORY_ERROR; } if (ret == 0) { - XMEMCPY(csr->response.buffer, input + offset, resp_length); - csr->response.length = resp_length; + XMEMCPY(csr->responses[ssl->response_idx].buffer, + input + offset, resp_length); + csr->responses[ssl->response_idx].length = resp_length; } return ret; @@ -3383,6 +3562,7 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, #if defined(WOLFSSL_TLS13) if (ssl->options.tls1_3) { + if (ssl->buffers.certificate == NULL) { WOLFSSL_MSG("Certificate buffer not set!"); return BUFFER_ERROR; @@ -3413,19 +3593,33 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, } FreeDecodedCert(cert); XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT); - extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); csr = extension ? (CertificateStatusRequest*)extension->data : NULL; if (csr == NULL) return MEMORY_ERROR; - request = &csr->request.ocsp; - ret = CreateOcspResponse(ssl, &request, &csr->response); + request = &csr->request.ocsp[0]; + ret = CreateOcspResponse(ssl, &request, &csr->responses[0]); + if (request != &csr->request.ocsp[0] && + ssl->buffers.weOwnCert) { + /* request will be allocated in CreateOcspResponse() */ + FreeOcspRequest(request); + XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST); + } if (ret != 0) return ret; - if (csr->response.buffer) + + if (csr->responses[0].buffer) TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST); + #if defined(WOLFSSL_TLS_OCSP_MULTI) + /* process OCSP request in certificate chain */ + if ((ret = ProcessChainOCSPRequest(ssl)) != 0) { + WOLFSSL_MSG("Process Cert Chain OCSP request failed"); + WOLFSSL_ERROR_VERBOSE(ret); + return ret; + } + #endif } else #endif @@ -3437,9 +3631,10 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, return 0; } -int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap) +int TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert, + void* heap, int idx) { - TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST); + TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST); CertificateStatusRequest* csr = extension ? (CertificateStatusRequest*)extension->data : NULL; int ret = 0; @@ -3448,18 +3643,33 @@ int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap) switch (csr->status_type) { case WOLFSSL_CSR_OCSP: { byte nonce[MAX_OCSP_NONCE_SZ]; - int nonceSz = csr->request.ocsp.nonceSz; - + int req_cnt = idx == -1 ? csr->requests : idx; + int nonceSz = csr->request.ocsp[0].nonceSz; + OcspRequest* request; + + request = &csr->request.ocsp[req_cnt]; + if (request->serial != NULL) { + /* clear request contents before re-use */ + FreeOcspRequest(request); + if (csr->requests > 0) + csr->requests--; + } /* preserve nonce */ - XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz); + XMEMCPY(nonce, request->nonce, nonceSz); - if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap)) - != 0) - return ret; + if (req_cnt < MAX_CERT_EXTENSIONS) { + if ((ret = InitOcspRequest(request, cert, 0, heap)) != 0) + return ret; - /* restore nonce */ - XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz); - csr->request.ocsp.nonceSz = nonceSz; + /* restore nonce */ + XMEMCPY(request->nonce, nonce, nonceSz); + request->nonceSz = nonceSz; + csr->requests++; + } + else { + WOLFSSL_ERROR_VERBOSE(MAX_CERT_EXTENSIONS_ERR); + return MAX_CERT_EXTENSIONS_ERR; + } } break; } @@ -3468,22 +3678,37 @@ int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap) return ret; } -void* TLSX_CSR_GetRequest(TLSX* extensions) +int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap) +{ + return TLSX_CSR_InitRequest_ex(extensions, cert, heap, -1); +} + +void* TLSX_CSR_GetRequest_ex(TLSX* extensions, int idx) { TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST); CertificateStatusRequest* csr = extension ? (CertificateStatusRequest*)extension->data : NULL; - if (csr) { + if (csr && csr->ssl) { switch (csr->status_type) { case WOLFSSL_CSR_OCSP: - return &csr->request.ocsp; + if (IsAtLeastTLSv1_3(csr->ssl->version)) { + return idx < csr->requests ? &csr->request.ocsp[idx] : NULL; + } + else { + return idx == 0 ? &csr->request.ocsp[0] : NULL; + } } } return NULL; } +void* TLSX_CSR_GetRequest(TLSX* extensions) +{ + return TLSX_CSR_GetRequest_ex(extensions, 0); +} + int TLSX_CSR_ForceRequest(WOLFSSL* ssl) { TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); @@ -3494,9 +3719,9 @@ int TLSX_CSR_ForceRequest(WOLFSSL* ssl) switch (csr->status_type) { case WOLFSSL_CSR_OCSP: if (SSL_CM(ssl)->ocspEnabled) { - csr->request.ocsp.ssl = ssl; + csr->request.ocsp[0].ssl = ssl; return CheckOcspRequest(SSL_CM(ssl)->ocsp, - &csr->request.ocsp, NULL, NULL); + &csr->request.ocsp[0], NULL, NULL); } else { WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL); @@ -3524,7 +3749,9 @@ int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type, return MEMORY_E; ForceZero(csr, sizeof(CertificateStatusRequest)); - +#if defined(WOLFSSL_TLS13) + XMEMSET(csr->responses, 0, sizeof(csr->responses)); +#endif csr->status_type = status_type; csr->options = options; csr->ssl = ssl; @@ -3541,9 +3768,9 @@ int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type, (void)devId; #endif if (ret == 0) { - if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce, + if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp[0].nonce, MAX_OCSP_NONCE_SZ) == 0) - csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ; + csr->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ; wc_FreeRng(&rng); } @@ -3887,7 +4114,7 @@ int TLSX_CSR2_AddPendingSigner(TLSX *extensions, Signer *s) csr2 = TLSX_CSR2_GetMulti(extensions); if (!csr2) - return -1; + return WOLFSSL_FATAL_ERROR; s->next = csr2->pendingSigners; csr2->pendingSigners = s; @@ -5678,14 +5905,25 @@ static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input, /* SERVER: ticket is peer auth. */ ssl->options.peerAuthGood = 1; } - } else if (ret == WOLFSSL_TICKET_RET_REJECT) { + } else if (ret == WOLFSSL_TICKET_RET_REJECT || + ret == WC_NO_ERR_TRACE(VERSION_ERROR)) { WOLFSSL_MSG("Process client ticket rejected, not using"); - ssl->options.rejectTicket = 1; + if (ret == WC_NO_ERR_TRACE(VERSION_ERROR)) + WOLFSSL_MSG("\tbad TLS version"); ret = 0; /* not fatal */ - } else if (ret == WC_NO_ERR_TRACE(VERSION_ERROR)) { - WOLFSSL_MSG("Process client ticket rejected, bad TLS version"); + ssl->options.rejectTicket = 1; - ret = 0; /* not fatal */ + /* If we have session tickets enabled then send a new ticket */ + if (!TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET)) { + ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + TLSX_SetResponse(ssl, TLSX_SESSION_TICKET); + ssl->options.createTicket = 1; + ssl->options.useTicket = 1; + } + } } else if (ret == WOLFSSL_TICKET_RET_FATAL) { WOLFSSL_MSG("Process client ticket fatal error, not using"); } else if (ret < 0) { @@ -5975,9 +6213,7 @@ static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap) static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap) { - if (srtp != NULL) { - XFREE(srtp, heap, DYNAMIC_TYPE_TLSX); - } + XFREE(srtp, heap, DYNAMIC_TYPE_TLSX); (void)heap; } @@ -6594,8 +6830,7 @@ static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap) { (void)heap; - if (cookie != NULL) - XFREE(cookie, heap, DYNAMIC_TYPE_TLSX); + XFREE(cookie, heap, DYNAMIC_TYPE_TLSX); } /* Get the size of the encoded Cookie extension. @@ -6748,8 +6983,7 @@ int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac, if (mac != NULL) XMEMCPY(cookie->data + len, mac, macSz); - if (extension->data != NULL) - XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX); + XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX); extension->data = (void*)cookie; extension->resp = (byte)resp; @@ -6907,16 +7141,15 @@ static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input, InitDecodedCert(cert, input + idx, extLen, ssl->heap); didInit = TRUE; idx += extLen; - ret = GetName(cert, SUBJECT, extLen); + ret = GetName(cert, ASN_SUBJECT, extLen); } if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL) ret = MEMORY_ERROR; if (ret == 0) { - CopyDecodedName(name, cert, SUBJECT); - if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name) - == WOLFSSL_FAILURE) + CopyDecodedName(name, cert, ASN_SUBJECT); + if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name) <= 0) ret = MEMORY_ERROR; } @@ -7392,21 +7625,15 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */ if (dhKey != NULL) wc_FreeDhKey(dhKey); - if (kse->key != NULL) { - XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH); - kse->key = NULL; - } + XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH); + kse->key = NULL; if (ret != 0) { /* Cleanup on error, otherwise data owned by key share entry */ - if (kse->privKey != NULL) { - XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - kse->privKey = NULL; - } - if (kse->pubKey != NULL) { - XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - kse->pubKey = NULL; - } + XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->privKey = NULL; + XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + kse->pubKey = NULL; } #else (void)ssl; @@ -7488,16 +7715,12 @@ static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse) if (ret != 0) { /* Data owned by key share entry otherwise. */ - if (kse->pubKey != NULL) { - XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - kse->pubKey = NULL; - } + XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + kse->pubKey = NULL; if (key != NULL) wc_curve25519_free(key); - if (kse->key != NULL) { - XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - kse->key = NULL; - } + XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->key = NULL; } #else (void)ssl; @@ -7576,16 +7799,12 @@ static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse) if (ret != 0) { /* Data owned by key share entry otherwise. */ - if (kse->pubKey != NULL) { - XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - kse->pubKey = NULL; - } + XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + kse->pubKey = NULL; if (key != NULL) wc_curve448_free(key); - if (kse->key != NULL) { - XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - kse->key = NULL; - } + XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->key = NULL; } #else (void)ssl; @@ -7683,7 +7902,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) #endif { /* set curve info for EccMakeKey "peer" info */ - ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId); + ret = wc_ecc_set_curve(eccKey, (int)kse->keyLen, curveId); if (ret == 0) { #ifdef WOLFSSL_ASYNC_CRYPT /* Detect when private key generation is done */ @@ -7739,16 +7958,12 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) if (ret != 0) { /* Cleanup on error, otherwise data owned by key share entry */ - if (kse->pubKey != NULL) { - XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - kse->pubKey = NULL; - } + XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + kse->pubKey = NULL; if (eccKey != NULL) wc_ecc_free(eccKey); - if (kse->key != NULL) { - XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - kse->key = NULL; - } + XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->key = NULL; } #else (void)ssl; @@ -7957,10 +8172,8 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) wc_KyberKey_Free(kem); TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); - if (pubKey != NULL) - XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - if (privKey != NULL) - XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); return ret; } @@ -8024,10 +8237,8 @@ static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap) if (current->key != NULL) { ForceZero((byte*)current->key, current->keyLen); } - if (current->pubKey != NULL) { - XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); - current->pubKey = NULL; - } + XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); + current->pubKey = NULL; if (current->privKey != NULL) { ForceZero(current->privKey, current->privKeyLen); XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY); @@ -8246,18 +8457,12 @@ static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) /* done with key share, release resources */ if (dhKey) wc_FreeDhKey(dhKey); - if (keyShareEntry->key) { - XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH); - keyShareEntry->key = NULL; - } - if (keyShareEntry->privKey != NULL) { - XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - keyShareEntry->privKey = NULL; - } - if (keyShareEntry->pubKey != NULL) { - XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - keyShareEntry->pubKey = NULL; - } + XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH); + keyShareEntry->key = NULL; + XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->privKey = NULL; + XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + keyShareEntry->pubKey = NULL; XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); keyShareEntry->ke = NULL; #else @@ -8335,10 +8540,8 @@ static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, wc_curve25519_free(peerX25519Key); XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX); wc_curve25519_free((curve25519_key*)keyShareEntry->key); - if (keyShareEntry->key != NULL) { - XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - keyShareEntry->key = NULL; - } + XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->key = NULL; #else (void)ssl; (void)keyShareEntry; @@ -8415,10 +8618,8 @@ static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) wc_curve448_free(peerX448Key); XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX); wc_curve448_free((curve448_key*)keyShareEntry->key); - if (keyShareEntry->key != NULL) { - XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - keyShareEntry->key = NULL; - } + XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->key = NULL; #else (void)ssl; (void)keyShareEntry; @@ -8705,7 +8906,7 @@ static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ !defined(HAVE_SELFTEST) if (ret == 0) { - ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng); + ret = wc_ecc_set_rng((ecc_key *)keyShareEntry->key, ssl->rng); if (ret != 0) { WOLFSSL_MSG("Failure to set the ECC private key RNG."); } @@ -8714,8 +8915,8 @@ static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) if (ret == 0) { PRIVATE_KEY_UNLOCK(); - ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey, - sharedSecret, &outlen); + ret = wc_ecc_shared_secret((ecc_key *)keyShareEntry->key, + &eccpubkey, sharedSecret, &outlen); PRIVATE_KEY_LOCK(); if (outlen != sharedSecretLen - ssSz) { WOLFSSL_MSG("ECC shared secret derivation error."); @@ -8735,9 +8936,7 @@ static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) ssl->arrays->preMasterSz = (word32) sharedSecretLen; } - if (sharedSecret != NULL) { - XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); - } + XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); wc_ecc_free(&eccpubkey); wc_KyberKey_Free(kem); @@ -9193,14 +9392,14 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ !defined(HAVE_SELFTEST) if (ret == 0) { - ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng); + ret = wc_ecc_set_rng((ecc_key *)ecc_kse->key, ssl->rng); } #endif if (ret == 0) { outlen = ecc_kse->keyLen; PRIVATE_KEY_UNLOCK(); - ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey, + ret = wc_ecc_shared_secret((ecc_key *)ecc_kse->key, &eccpubkey, sharedSecret, &outlen); PRIVATE_KEY_LOCK(); @@ -9224,9 +9423,7 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, } if (ret == 0) { - if (keyShareEntry->ke != NULL) { - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - } + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); keyShareEntry->ke = sharedSecret; keyShareEntry->keLen = outlen + ssSz; @@ -9244,10 +9441,8 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, } TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); - if (sharedSecret != NULL) - XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); - if (ciphertext != NULL) - XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); + XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); + XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); wc_ecc_free(&eccpubkey); wc_KyberKey_Free(kem); return ret; @@ -9312,9 +9507,7 @@ int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data, else #endif if (data != NULL) { - if (keyShareEntry->ke != NULL) { - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - } + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); keyShareEntry->ke = data; keyShareEntry->keLen = len; } @@ -9504,9 +9697,6 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) } break; } - #elif defined(HAVE_PQM4) - case WOLFSSL_KYBER_LEVEL1: - break; #endif #endif default: @@ -9575,8 +9765,6 @@ static const word16 preferredGroup[] = { WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P521_KYBER_LEVEL5, -#elif defined(HAVE_PQM4) - WOLFSSL_KYBER_LEVEL1, #endif WOLFSSL_NAMED_GROUP_INVALID }; @@ -9610,14 +9798,14 @@ static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group) #ifdef HAVE_LIBOQS if (!TLSX_KeyShare_IsSupported(group)) - return -1; + return WOLFSSL_FATAL_ERROR; #endif for (i = 0; i < numGroups; i++) if (groups[i] == (word16)group) return i; - return -1; + return WOLFSSL_FATAL_ERROR; } /* Set a key share that is supported by the client into extensions. @@ -9965,7 +10153,7 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) /* for async do setup of serverKSE below, but return WC_PENDING_E */ if (ret != 0 #ifdef WOLFSSL_ASYNC_CRYPT - && ret != WC_PENDING_E + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { TLSX_KeyShare_FreeAll(list, ssl->heap); @@ -12106,8 +12294,7 @@ static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig, ech->hpke = NULL; } - if (info != NULL) - XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -12130,6 +12317,11 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, if (size == 0) return BAD_FUNC_ARG; + if (ssl->options.disableECH) { + WOLFSSL_MSG("TLSX_ECH_Parse: ECH disabled. Ignoring."); + return 0; + } + if (msgType == encrypted_extensions) { ret = wolfSSL_SetEchConfigs(ssl, readBuf, size); @@ -12263,13 +12455,11 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, /* free the ech struct and the dynamic buffer it uses */ static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap) { - if (ech->innerClientHello != NULL) - XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER); if (ech->ephemeralKey != NULL) wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey, ech->hpke->heap); - if (ech->hpke != NULL) - XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER); (void)heap; @@ -12436,27 +12626,36 @@ void TLSX_FreeAll(TLSX* list, void* heap) WOLFSSL_MSG("Encrypt-Then-Mac extension free"); break; #endif -#ifdef WOLFSSL_TLS13 - case TLSX_SUPPORTED_VERSIONS: - WOLFSSL_MSG("Supported Versions extension free"); - break; - - #ifdef WOLFSSL_SEND_HRR_COOKIE - case TLSX_COOKIE: - WOLFSSL_MSG("Cookie extension free"); - CKE_FREE_ALL((Cookie*)extension->data, heap); - break; - #endif +#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) case TLSX_PRE_SHARED_KEY: WOLFSSL_MSG("Pre-Shared Key extension free"); PSK_FREE_ALL((PreSharedKey*)extension->data, heap); break; + #ifdef WOLFSSL_TLS13 case TLSX_PSK_KEY_EXCHANGE_MODES: WOLFSSL_MSG("PSK Key Exchange Modes extension free"); break; + #endif + #endif + + case TLSX_KEY_SHARE: + WOLFSSL_MSG("Key Share extension free"); + KS_FREE_ALL((KeyShareEntry*)extension->data, heap); + break; +#endif +#ifdef WOLFSSL_TLS13 + case TLSX_SUPPORTED_VERSIONS: + WOLFSSL_MSG("Supported Versions extension free"); + break; + + #ifdef WOLFSSL_SEND_HRR_COOKIE + case TLSX_COOKIE: + WOLFSSL_MSG("Cookie extension free"); + CKE_FREE_ALL((Cookie*)extension->data, heap); + break; #endif #ifdef WOLFSSL_EARLY_DATA @@ -12476,11 +12675,6 @@ void TLSX_FreeAll(TLSX* list, void* heap) WOLFSSL_MSG("Signature Algorithms extension free"); break; #endif - - case TLSX_KEY_SHARE: - WOLFSSL_MSG("Key Share extension free"); - KS_FREE_ALL((KeyShareEntry*)extension->data, heap); - break; #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) case TLSX_CERTIFICATE_AUTHORITIES: WOLFSSL_MSG("Certificate Authorities extension free"); @@ -12554,7 +12748,7 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, continue; /* skip! */ /* ssl level extensions are expected to override ctx level ones. */ - if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type))) + if (!IS_OFF(semaphore, TLSX_ToSemaphore((word16)extension->type))) continue; /* skip! */ /* extension type + extension data length. */ @@ -12631,26 +12825,33 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, ret = ETM_GET_SIZE(msgType, &length); break; #endif /* HAVE_ENCRYPT_THEN_MAC */ -#ifdef WOLFSSL_TLS13 - case TLSX_SUPPORTED_VERSIONS: - ret = SV_GET_SIZE(extension->data, msgType, &length); - break; - - #ifdef WOLFSSL_SEND_HRR_COOKIE - case TLSX_COOKIE: - ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length); - break; - #endif +#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) case TLSX_PRE_SHARED_KEY: ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType, &length); break; - + #ifdef WOLFSSL_TLS13 case TLSX_PSK_KEY_EXCHANGE_MODES: ret = PKM_GET_SIZE((byte)extension->val, msgType, &length); break; + #endif + #endif + case TLSX_KEY_SHARE: + length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType); + break; +#endif + +#ifdef WOLFSSL_TLS13 + case TLSX_SUPPORTED_VERSIONS: + ret = SV_GET_SIZE(extension->data, msgType, &length); + break; + + #ifdef WOLFSSL_SEND_HRR_COOKIE + case TLSX_COOKIE: + ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length); + break; #endif #ifdef WOLFSSL_EARLY_DATA @@ -12671,9 +12872,6 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, break; #endif - case TLSX_KEY_SHARE: - length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType); - break; #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) case TLSX_CERTIFICATE_AUTHORITIES: length += CAN_GET_SIZE(extension->data); @@ -12719,7 +12917,7 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, /* marks the extension as processed so ctx level */ /* extensions don't overlap with ssl level ones. */ - TURN_ON(semaphore, TLSX_ToSemaphore(extension->type)); + TURN_ON(semaphore, TLSX_ToSemaphore((word16)extension->type)); } *pLength += length; @@ -12746,11 +12944,11 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, continue; /* skip! */ /* ssl level extensions are expected to override ctx level ones. */ - if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type))) + if (!IS_OFF(semaphore, TLSX_ToSemaphore((word16)extension->type))) continue; /* skip! */ /* writes extension type. */ - c16toa(extension->type, output + offset); + c16toa((word16)extension->type, output + offset); offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN; length_offset = offset; @@ -12855,20 +13053,8 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, ret = ETM_WRITE(extension->data, output, msgType, &offset); break; #endif /* HAVE_ENCRYPT_THEN_MAC */ -#ifdef WOLFSSL_TLS13 - case TLSX_SUPPORTED_VERSIONS: - WOLFSSL_MSG("Supported Versions extension to write"); - ret = SV_WRITE(extension->data, output + offset, msgType, &offset); - break; - - #ifdef WOLFSSL_SEND_HRR_COOKIE - case TLSX_COOKIE: - WOLFSSL_MSG("Cookie extension to write"); - ret = CKE_WRITE((Cookie*)extension->data, output + offset, - msgType, &offset); - break; - #endif +#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) case TLSX_PRE_SHARED_KEY: WOLFSSL_MSG("Pre-Shared Key extension to write"); @@ -12876,11 +13062,33 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, msgType, &offset); break; + #ifdef WOLFSSL_TLS13 case TLSX_PSK_KEY_EXCHANGE_MODES: WOLFSSL_MSG("PSK Key Exchange Modes extension to write"); ret = PKM_WRITE((byte)extension->val, output + offset, msgType, &offset); break; + #endif + #endif + case TLSX_KEY_SHARE: + WOLFSSL_MSG("Key Share extension to write"); + offset += KS_WRITE((KeyShareEntry*)extension->data, + output + offset, msgType); + break; +#endif +#ifdef WOLFSSL_TLS13 + case TLSX_SUPPORTED_VERSIONS: + WOLFSSL_MSG("Supported Versions extension to write"); + ret = SV_WRITE(extension->data, output + offset, msgType, + &offset); + break; + + #ifdef WOLFSSL_SEND_HRR_COOKIE + case TLSX_COOKIE: + WOLFSSL_MSG("Cookie extension to write"); + ret = CKE_WRITE((Cookie*)extension->data, output + offset, + msgType, &offset); + break; #endif #ifdef WOLFSSL_EARLY_DATA @@ -12905,11 +13113,6 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, break; #endif - case TLSX_KEY_SHARE: - WOLFSSL_MSG("Key Share extension to write"); - offset += KS_WRITE((KeyShareEntry*)extension->data, - output + offset, msgType); - break; #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) case TLSX_CERTIFICATE_AUTHORITIES: WOLFSSL_MSG("Certificate Authorities extension to write"); @@ -12968,7 +13171,7 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, /* marks the extension as processed so ctx level */ /* extensions don't overlap with ssl level ones. */ - TURN_ON(semaphore, TLSX_ToSemaphore(extension->type)); + TURN_ON(semaphore, TLSX_ToSemaphore((word16)extension->type)); /* if we encountered an error propagate it */ if (ret != 0) @@ -13190,7 +13393,7 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3, ssl->heap); #endif -#ifdef WOLFSSL_KYBER768 +#ifdef WOLFSSL_KYBER1024 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5, ssl->heap); @@ -13215,8 +13418,6 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5, ssl->heap); -#elif defined(HAVE_PQM4) - ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap); #endif /* HAVE_LIBOQS */ #endif /* WOLFSSL_HAVE_KYBER */ @@ -13551,7 +13752,7 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) ssl->arrays->client_identity, MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName); if (GetCipherSuiteFromName(cipherName, &cipherSuite0, - &cipherSuite, &cipherSuiteFlags) != 0) { + &cipherSuite, NULL, NULL, &cipherSuiteFlags) != 0) { return PSK_KEY_ERROR; } } @@ -13637,18 +13838,21 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) #endif #if defined(HAVE_ECH) /* GREASE ECH */ - if (ssl->echConfigs == NULL) { - ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng); - } - else if (ssl->echConfigs != NULL) { - ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap, - ssl->rng); + if (!ssl->options.disableECH) { + if (ssl->echConfigs == NULL) { + ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, + ssl->rng); + } + else if (ssl->echConfigs != NULL) { + ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), + ssl->heap, ssl->rng); + } } #endif } #if defined(HAVE_ECH) else if (IsAtLeastTLSv1_3(ssl->version)) { - if (ssl->ctx->echConfigs != NULL) { + if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) { ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap, ssl->ctx->echConfigs); @@ -13838,7 +14042,8 @@ int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word32* pLength) } #endif #if defined(HAVE_ECH) - if (ssl->options.useEch == 1 && msgType == client_hello) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH + && msgType == client_hello) { ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length); if (ret != 0) return ret; @@ -14083,7 +14288,8 @@ int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word32* pOffset) #endif #endif #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) - if (ssl->options.useEch == 1 && msgType == client_hello) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH + && msgType == client_hello) { ret = TLSX_WriteWithEch(ssl, output, semaphore, msgType, &offset); if (ret != 0) @@ -14169,9 +14375,6 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif - #ifdef WOLFSSL_DTLS_CID - TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); - #endif } #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) else { @@ -14183,6 +14386,9 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) #endif } #endif + #ifdef WOLFSSL_DTLS_CID + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); + #endif #endif /* WOLFSSL_TLS13 */ break; @@ -14296,7 +14502,7 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset #ifndef NO_WOLFSSL_SERVER case server_hello: PF_VALIDATE_RESPONSE(ssl, semaphore); - #ifdef WOLFSSL_TLS13 + #ifdef WOLFSSL_TLS13 if (IsAtLeastTLSv1_3(ssl->version)) { XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE); TURN_OFF(semaphore, @@ -14313,21 +14519,23 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif - #ifdef WOLFSSL_DTLS_CID - TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); - #endif /* WOLFSSL_DTLS_CID */ } + else + #endif /* WOLFSSL_TLS13 */ + { #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) - else { #ifdef HAVE_SUPPORTED_CURVES TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE)); #endif #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY)); #endif - } #endif - #endif + WC_DO_NOTHING; /* avoid empty brackets */ + } + #ifdef WOLFSSL_DTLS_CID + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID)); + #endif /* WOLFSSL_DTLS_CID */ break; #ifdef WOLFSSL_TLS13 @@ -15233,10 +15441,6 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #endif /* WOLFSSL_QUIC */ #if defined(WOLFSSL_DTLS_CID) case TLSX_CONNECTION_ID: - /* connection ID not supported in DTLSv1.2 */ - if (!IsAtLeastTLSv1_3(ssl->version)) - break; - if (msgType != client_hello && msgType != server_hello) return EXT_NOT_ALLOWED; @@ -15652,6 +15856,26 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, return m; } #endif /* !WOLFSSL_NO_TLS12 */ + #ifdef WOLFSSL_DTLS13 + WOLFSSL_METHOD* wolfDTLSv1_3_method(void) + { + return wolfDTLSv1_3_method_ex(NULL); + } + WOLFSSL_METHOD* wolfDTLSv1_3_method_ex(void* heap) + { + WOLFSSL_METHOD* m; + WOLFSSL_ENTER("DTLSv1_3_method"); + #ifndef NO_WOLFSSL_CLIENT + m = wolfDTLSv1_3_client_method_ex(heap); + #else + m = wolfDTLSv1_3_server_method_ex(heap); + #endif + if (m != NULL) { + m->side = WOLFSSL_NEITHER_END; + } + return m; + } + #endif /* WOLFSSL_DTLS13 */ #endif /* WOLFSSL_DTLS */ #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ diff --git a/src/src/tls13.c b/src/src/tls13.c index ef37c29..e826893 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -1,6 +1,6 @@ /* tls13.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -221,7 +221,7 @@ static int Tls13HKDFExpandLabel(WOLFSSL* ssl, byte* okm, word32 okmLen, #endif (void)ssl; PRIVATE_KEY_UNLOCK(); -#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) +#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0)) ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen, protocol, protocolLen, label, labelLen, @@ -261,7 +261,7 @@ static int Tls13HKDFExpandKeyLabel(WOLFSSL* ssl, byte* okm, word32 okmLen, return ret; #endif -#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) +#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0)) ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen, protocol, protocolLen, label, labelLen, @@ -1137,7 +1137,7 @@ static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, #endif { #if !defined(HAVE_FIPS) || \ - (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) + (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0)) ret = wc_Tls13_HKDF_Extract_ex(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest, ssl->heap, ssl->devId); #else @@ -2534,7 +2534,6 @@ static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output, /* Copy the input to output if not the same buffer */ if (ret == 0 && output != input) XMEMCPY(output, input, sz); - return ret; } #endif @@ -2930,7 +2929,6 @@ static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output, /* Copy the input to output if not the same buffer */ if (ret == 0 && output != input) XMEMCPY(output, input, sz); - return ret; } #endif @@ -3199,6 +3197,7 @@ typedef struct BuildMsg13Args { word32 idx; word32 headerSz; word16 size; + word32 paddingSz; } BuildMsg13Args; static void FreeBuildMsg13Args(WOLFSSL* ssl, void* pArgs) @@ -3304,7 +3303,14 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, args->sz++; /* Authentication data at the end. */ args->sz += ssl->specs.aead_mac_size; - +#ifdef WOLFSSL_DTLS13 + /* Pad to minimum length */ + if (ssl->options.dtls && + args->sz < (word32)Dtls13MinimumRecordLength(ssl)) { + args->paddingSz = Dtls13MinimumRecordLength(ssl) - args->sz; + args->sz = Dtls13MinimumRecordLength(ssl); + } +#endif if (sizeOnly) return (int)args->sz; @@ -3348,6 +3354,9 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* The real record content type goes at the end of the data. */ output[args->idx++] = (byte)type; + /* Double check that any necessary padding is zero'd out */ + XMEMSET(output + args->idx, 0, args->paddingSz); + args->idx += args->paddingSz; ssl->options.buildMsgState = BUILD_MSG_ENCRYPT; } @@ -3393,7 +3402,8 @@ int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, #ifdef WOLFSSL_DTLS13 if (ret == 0 && ssl->options.dtls) { /* AAD points to the header. Reuse the variable */ - ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad, (word16)args->sz); + ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad, + (word16)args->sz); } #endif /* WOLFSSL_DTLS13 */ } @@ -3600,7 +3610,7 @@ int CreateCookieExt(const WOLFSSL* ssl, byte* hash, word16 hashSz, macSz = WC_SHA256_DIGEST_SIZE; #endif /* NO_SHA256 */ - ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID); + ret = wc_HmacInit(&cookieHmac, ssl->heap, ssl->devId); if (ret == 0) { ret = wc_HmacSetKey(&cookieHmac, cookieType, ssl->buffers.tls13CookieSecret.buffer, @@ -3940,7 +3950,7 @@ static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello) MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName); if (GetCipherSuiteFromName(cipherName, &cipherSuite0, - &cipherSuite, &cipherSuiteFlags) != 0) { + &cipherSuite, NULL, NULL, &cipherSuiteFlags) != 0) { WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR); return PSK_KEY_ERROR; } @@ -4145,7 +4155,7 @@ int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config) return i; } - return -1; + return WOLFSSL_FATAL_ERROR; } /* returns status after we hash the ech inner */ @@ -4153,7 +4163,11 @@ static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech) { int ret; HS_Hashes* tmpHashes; +#ifdef WOLFSSL_DTLS13 + byte falseHeader[DTLS13_HANDSHAKE_HEADER_SZ]; +#else byte falseHeader[HANDSHAKE_HEADER_SZ]; +#endif if (ssl == NULL || ech == NULL) return BAD_FUNC_ARG; @@ -4415,14 +4429,14 @@ int SendTls13ClientHello(WOLFSSL* ssl) /* find length of outer and inner */ #if defined(HAVE_ECH) - if (ssl->options.useEch == 1) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH) { TLSX* echX = TLSX_Find(ssl->extensions, TLSX_ECH); if (echX == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; args->ech = (WOLFSSL_ECH*)echX->data; if (args->ech == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; /* set the type to inner */ args->ech->type = ECH_TYPE_INNER; @@ -4455,8 +4469,17 @@ int SendTls13ClientHello(WOLFSSL* ssl) if (ret != 0) return ret; + /* Total message size. */ + args->sendSz = + (int)(args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ); + +#ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) + args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA; +#endif /* WOLFSSL_DTLS13 */ + #ifdef WOLFSSL_DTLS_CH_FRAG - if (ssl->options.dtls && args->length > maxFrag && + if (ssl->options.dtls && args->sendSz > maxFrag && TLSX_Find(ssl->extensions, TLSX_COOKIE) == NULL) { /* Try again with an empty key share if we would be fragmenting * without a cookie */ @@ -4467,7 +4490,9 @@ int SendTls13ClientHello(WOLFSSL* ssl) ret = TLSX_GetRequestSize(ssl, client_hello, &args->length); if (ret != 0) return ret; - if (args->length > maxFrag) { + args->sendSz = (int)(args->length + + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ); + if (args->sendSz > maxFrag) { WOLFSSL_MSG("Can't fit first CH in one fragment."); return BUFFER_ERROR; } @@ -4476,14 +4501,6 @@ int SendTls13ClientHello(WOLFSSL* ssl) #endif } - /* Total message size. */ - args->sendSz = (int)(args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ); - -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) - args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA; -#endif /* WOLFSSL_DTLS13 */ - /* Check buffers are big enough and grow if needed. */ if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) return ret; @@ -4563,7 +4580,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) #if defined(HAVE_ECH) /* write inner then outer */ - if (ssl->options.useEch == 1) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH) { /* set the type to inner */ args->ech->type = ECH_TYPE_INNER; @@ -4623,7 +4640,7 @@ int SendTls13ClientHello(WOLFSSL* ssl) #if defined(HAVE_ECH) /* encrypt and pack the ech innerClientHello */ - if (ssl->options.useEch == 1) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH) { ret = TLSX_FinalizeEch(args->ech, args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ, (word32)(args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ))); @@ -4653,11 +4670,9 @@ int SendTls13ClientHello(WOLFSSL* ssl) { #if defined(HAVE_ECH) /* compute the inner hash */ - if (ssl->options.useEch == 1) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH) ret = EchHashHelloInner(ssl, args->ech); - } #endif - /* compute the outer hash */ if (ret == 0) ret = HashOutput(ssl, args->output, (int)args->idx, 0); @@ -4815,7 +4830,7 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, break; #endif /* WOLFSSL_SM3 */ default: - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } } @@ -4823,7 +4838,7 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, if (ret == 0) { PRIVATE_KEY_UNLOCK(); #if !defined(HAVE_FIPS) || \ - (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) + (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0)) ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize, ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk, ssl->heap, ssl->devId); @@ -4953,7 +4968,7 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, break; #endif /* WOLFSSL_SM3 */ default: - ret = -1; + ret = WOLFSSL_FATAL_ERROR; break; } @@ -4961,7 +4976,7 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, if (ret == 0) { PRIVATE_KEY_UNLOCK(); #if !defined(HAVE_FIPS) || \ - (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) + (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0)) ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize, ssl->arrays->clientRandom, RAN_LEN, expandLabelPrk, ssl->heap, ssl->devId); @@ -5472,7 +5487,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #if defined(HAVE_ECH) /* check for acceptConfirmation and HashInput with 8 0 bytes */ - if (ssl->options.useEch == 1) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH) { ret = EchCheckAcceptance(ssl, input, args->serverRandomOffset, (int)helloSz); if (ret != 0) return ret; @@ -5851,7 +5866,7 @@ int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk, byte* psk_key, if (*psk_keySz != 0) { int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE; *found = (GetCipherSuiteFromName(cipherName, &cipherSuite0, - &cipherSuite, &cipherSuiteFlags) == 0); + &cipherSuite, NULL, NULL, &cipherSuiteFlags) == 0); (void)cipherSuiteFlags; } } @@ -6377,7 +6392,7 @@ int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie, word16 cookieSz) return HRR_COOKIE_ERROR; cookieSz -= macSz; - ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID); + ret = wc_HmacInit(&cookieHmac, ssl->heap, ssl->devId); if (ret == 0) { ret = wc_HmacSetKey(&cookieHmac, cookieType, ssl->buffers.tls13CookieSecret.buffer, @@ -6932,12 +6947,12 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, goto exit_dch; #if defined(HAVE_ECH) - if (ssl->ctx->echConfigs != NULL) { + if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) { /* save the start of the buffer so we can use it when parsing ech */ echX = TLSX_Find(ssl->extensions, TLSX_ECH); if (echX == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; ((WOLFSSL_ECH*)echX->data)->aad = input + HANDSHAKE_HEADER_SZ; ((WOLFSSL_ECH*)echX->data)->aadLen = helloSz; @@ -7011,7 +7026,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ret != 0) goto exit_dch; #else - if ((ret = HashInput(ssl, input + args->begin, helloSz)) != 0) + if ((ret = HashInput(ssl, input + args->begin, (int)helloSz)) != 0) goto exit_dch; #endif @@ -7404,11 +7419,11 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) #endif /* WOLFSSL_DTLS13 */ { #if defined(HAVE_ECH) - if (ssl->ctx->echConfigs != NULL) { + if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) { echX = TLSX_Find(ssl->extensions, TLSX_ECH); if (echX == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; /* replace the last 8 bytes of server random with the accept */ if (((WOLFSSL_ECH*)echX->data)->state == ECH_PARSED_INTERNAL) { @@ -7455,7 +7470,7 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) } #endif /* WOLFSSL_DTLS13 */ - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; if (!ssl->options.groupMessages || extMsgType != server_hello) ret = SendBuffered(ssl); @@ -7603,11 +7618,12 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) /* This handshake message is always encrypted. */ sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, - idx - RECORD_HEADER_SZ, handshake, 1, 0, 0); + (int)(idx - RECORD_HEADER_SZ), + handshake, 1, 0, 0); if (sendSz < 0) return sendSz; - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ssl->options.buildingMsg = 0; ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE; @@ -7633,7 +7649,7 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) * returns 0 on success, otherwise failure. */ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, - int reqCtxLen) + word32 reqCtxLen) { byte* output; int ret; @@ -7721,7 +7737,7 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, /* Always encrypted. */ sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, - i - RECORD_HEADER_SZ, handshake, 1, 0, 0); + (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0); if (sendSz < 0) return sendSz; @@ -7736,7 +7752,7 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ssl->options.buildingMsg = 0; if (!ssl->options.groupMessages) ret = SendBuffered(ssl); @@ -8403,6 +8419,75 @@ static word32 NextCert(byte* data, word32 length, word32* idx) return len; } +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER) +/* Write certificate status request into certificate to buffer. + * + * ssl SSL/TLS object. + * certExts DerBuffer array. buffers written + * extSz word32 array. + * Length of the certificate status request data for the certificate. + * extSz_num number of the CSR written + * extIdx The index number of certificate status request data + * for the certificate. + * offset index offset + * returns Total number of bytes written. + */ +static word32 WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts, + word16* extSz, word16 extSz_num) +{ + int ret = 0; + TLSX* ext; + CertificateStatusRequest* csr; + word32 ex_offset = HELLO_EXT_TYPE_SZ + OPAQUE16_LEN /* extension type */ + + OPAQUE16_LEN /* extension length */; + word32 totalSz = 0; + word32 tmpSz; + word32 extIdx; + DerBuffer* der; + + ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); + csr = ext ? (CertificateStatusRequest*)ext->data : NULL; + + if (csr) { + for (extIdx = 0; extIdx < (word16)(extSz_num); extIdx++) { + tmpSz = TLSX_CSR_GetSize_ex(csr, 0, extIdx); + + if (tmpSz > (OPAQUE8_LEN + OPAQUE24_LEN) && + certExts[extIdx] == NULL) { + /* csr extension is not zero */ + extSz[extIdx] = tmpSz; + + ret = AllocDer(&certExts[extIdx], extSz[extIdx] + ex_offset, + CERT_TYPE, ssl->heap); + if (ret < 0) + return ret; + der = certExts[extIdx]; + + /* write extension type */ + c16toa(ext->type, der->buffer + + OPAQUE16_LEN); + /* writes extension data length. */ + c16toa(extSz[extIdx], der->buffer + + HELLO_EXT_TYPE_SZ + OPAQUE16_LEN); + /* write extension data */ + extSz[extIdx] = (word16)TLSX_CSR_Write_ex(csr, + der->buffer + ex_offset, 0, extIdx); + /* add extension offset */ + extSz[extIdx] += (word16)ex_offset; + /* extension length */ + c16toa(extSz[extIdx] - OPAQUE16_LEN, + der->buffer); + } + totalSz += extSz[extIdx]; + } + } + else { + /* chain cert empty extension size */ + totalSz += OPAQUE16_LEN * extSz_num; + } + return totalSz; +} +#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */ /* Add certificate data and empty extension to output up to the fragment size. * * ssl SSL/TLS object. @@ -8412,10 +8497,11 @@ static word32 NextCert(byte* data, word32 length, word32* idx) * idx The start of the certificate data to write out. * fragSz The maximum size of this fragment. * output The buffer to write to. + * extIdx The index number of the extension data with the certificate * returns the number of bytes written. */ static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz, - word32 idx, word32 fragSz, byte* output) + word32 idx, word32 fragSz, byte* output, word16 extIdx) { word32 i = 0; word32 copySz = min(len - idx, fragSz); @@ -8436,7 +8522,7 @@ static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz, } } else { - byte* certExts = ssl->buffers.certExts->buffer + idx + i - len; + byte* certExts = ssl->buffers.certExts[extIdx]->buffer + idx + i - len; /* Put out as much of the extensions' data as will fit in fragment. */ if (copySz > fragSz - i) copySz = fragSz - i; @@ -8458,13 +8544,16 @@ static int SendTls13Certificate(WOLFSSL* ssl) { int ret = 0; word32 certSz, certChainSz, headerSz, listSz, payloadSz; - word16 extSz = 0; - word32 length, maxFragment; + word16 extSz[MAX_CERT_EXTENSIONS]; + word16 extIdx = 0; + word32 maxFragment; + word32 totalextSz = 0; word32 len = 0; word32 idx = 0; word32 offset = OPAQUE16_LEN; byte* p = NULL; byte certReqCtxLen = 0; + sword32 length; #ifdef WOLFSSL_POST_HANDSHAKE_AUTH byte* certReqCtx = NULL; #endif @@ -8477,6 +8566,8 @@ static int SendTls13Certificate(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND); WOLFSSL_ENTER("SendTls13Certificate"); + XMEMSET(extSz, 0, sizeof(extSz)); + ssl->options.buildingMsg = 1; #ifdef WOLFSSL_POST_HANDSHAKE_AUTH @@ -8506,11 +8597,11 @@ static int SendTls13Certificate(WOLFSSL* ssl) certSz = 0; certChainSz = 0; headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ; - length = headerSz; + length = (sword32)headerSz; listSz = 0; } else { - if (!ssl->buffers.certificate) { + if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) { WOLFSSL_MSG("Send Cert missing certificate buffer"); return NO_CERT_ERROR; } @@ -8519,35 +8610,42 @@ static int SendTls13Certificate(WOLFSSL* ssl) /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */ headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ + CERT_HEADER_SZ; - - ret = TLSX_GetResponseSize(ssl, certificate, &extSz); - if (ret < 0) - return ret; - - /* Create extensions' data if none already present. */ - if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) { - ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap); - if (ret < 0) - return ret; - - extSz = 0; - ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer, - certificate, &extSz); + /* set empty extension as default */ + for (extIdx = 0; extIdx < (word16)XELEM_CNT(extSz); extIdx++) + extSz[extIdx] = OPAQUE16_LEN; + + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER) + /* We only send CSR on the server side. On client side, the CSR data + * is populated with the server response. We would be sending the server + * its own stapling data. */ + if (ssl->options.side == WOLFSSL_SERVER_END) { + ret = WriteCSRToBuffer(ssl, &ssl->buffers.certExts[0], &extSz[0], + 1 /* +1 for leaf */ + ssl->buffers.certChainCnt); if (ret < 0) return ret; + totalextSz += ret; + ret = 0; /* Clear to signal no error */ + } + else + #endif + { + /* Leaf cert empty extension size */ + totalextSz += OPAQUE16_LEN; + /* chain cert empty extension size */ + totalextSz += OPAQUE16_LEN * ssl->buffers.certChainCnt; } /* Length of message data with one certificate and extensions. */ - length = headerSz + certSz + extSz; + length = (sword32)(headerSz + certSz + totalextSz); /* Length of list data with one certificate and extensions. */ - listSz = CERT_HEADER_SZ + certSz + extSz; + listSz = CERT_HEADER_SZ + certSz + totalextSz; /* Send rest of chain if sending cert (chain has leading size/s). */ if (certSz > 0 && ssl->buffers.certChainCnt > 0) { p = ssl->buffers.certChain->buffer; /* Chain length including extensions. */ - certChainSz = ssl->buffers.certChain->length + - OPAQUE16_LEN * ssl->buffers.certChainCnt; + certChainSz = ssl->buffers.certChain->length; + length += certChainSz; listSz += certChainSz; } @@ -8555,13 +8653,15 @@ static int SendTls13Certificate(WOLFSSL* ssl) certChainSz = 0; } - payloadSz = length; + payloadSz = (word32)length; if (ssl->fragOffset != 0) length -= (ssl->fragOffset + headerSz); maxFragment = (word32)wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE); + extIdx = 0; + while (length > 0 && ret == 0) { byte* output = NULL; word32 fragSz = 0; @@ -8576,15 +8676,15 @@ static int SendTls13Certificate(WOLFSSL* ssl) #endif /* WOLFSSL_DTLS13 */ if (ssl->fragOffset == 0) { - if (headerSz + certSz + extSz + certChainSz <= + if (headerSz + certSz + totalextSz + certChainSz <= maxFragment - HANDSHAKE_HEADER_SZ) { - fragSz = headerSz + certSz + extSz + certChainSz; + fragSz = headerSz + certSz + totalextSz + certChainSz; } #ifdef WOLFSSL_DTLS13 else if (ssl->options.dtls){ /* short-circuit the fragmentation logic here. DTLS fragmentation will be done in dtls13HandshakeSend() */ - fragSz = headerSz + certSz + extSz + certChainSz; + fragSz = headerSz + certSz + totalextSz + certChainSz; } #endif /* WOLFSSL_DTLS13 */ else { @@ -8601,7 +8701,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) #endif /* WOLFSSL_DTLS13 */ } else { - fragSz = min(length, maxFragment); + fragSz = min((word32)length, maxFragment); sendSz += fragSz; } @@ -8643,20 +8743,23 @@ static int SendTls13Certificate(WOLFSSL* ssl) else AddTls13RecordHeader(output, fragSz, handshake, ssl); - if (certSz > 0 && ssl->fragOffset < certSz + extSz) { - /* Put in the leaf certificate with extensions. */ - word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer, - certSz, extSz, ssl->fragOffset, fragSz, output + i); - i += copySz; - ssl->fragOffset += copySz; - length -= copySz; - fragSz -= copySz; - if (ssl->fragOffset == certSz + extSz) - FreeDer(&ssl->buffers.certExts); + if (extIdx == 0) { + if (certSz > 0 && ssl->fragOffset < certSz + extSz[0]) { + /* Put in the leaf certificate with extensions. */ + word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer, + certSz, extSz[0], ssl->fragOffset, fragSz, + output + i, 0); + i += copySz; + ssl->fragOffset += copySz; + length -= copySz; + fragSz -= copySz; + if (ssl->fragOffset == certSz + extSz[0]) + FreeDer(&ssl->buffers.certExts[0]); + } } if (certChainSz > 0 && fragSz > 0) { - /* Put in the CA certificates with empty extensions. */ - while (fragSz > 0) { + /* Put in the CA certificates with extensions. */ + while (fragSz > 0) { word32 l; if (offset == len + OPAQUE16_LEN) { @@ -8665,19 +8768,30 @@ static int SendTls13Certificate(WOLFSSL* ssl) /* Point to the start of current cert in chain buffer. */ p = ssl->buffers.certChain->buffer + idx; len = NextCert(ssl->buffers.certChain->buffer, - ssl->buffers.certChain->length, &idx); + ssl->buffers.certChain->length, &idx); if (len == 0) break; + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \ + !defined(NO_WOLFSSL_SERVER) + if (MAX_CERT_EXTENSIONS > extIdx) + extIdx++; + #endif } - - /* Write out certificate and empty extension. */ - l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz, - output + i); + /* Write out certificate and extension. */ + l = AddCertExt(ssl, p, len, extSz[extIdx], offset, fragSz, + output + i, extIdx); i += l; ssl->fragOffset += l; length -= l; fragSz -= l; offset += l; + + if (extIdx != 0 && extIdx < MAX_CERT_EXTENSIONS && + ssl->buffers.certExts[extIdx] != NULL && + offset == len + extSz[extIdx]) + FreeDer(&ssl->buffers.certExts[extIdx]); + /* for next chain cert */ + len += extSz[extIdx] - OPAQUE16_LEN; } } @@ -8699,7 +8813,8 @@ static int SendTls13Certificate(WOLFSSL* ssl) { /* This message is always encrypted. */ sendSz = BuildTls13Message(ssl, output, sendSz, - output + RECORD_HEADER_SZ, i - RECORD_HEADER_SZ, handshake, 1, + output + RECORD_HEADER_SZ, (int)(i - RECORD_HEADER_SZ), + handshake, 1, 0, 0); if (sendSz < 0) return sendSz; @@ -8715,14 +8830,14 @@ static int SendTls13Certificate(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ssl->options.buildingMsg = 0; if (!ssl->options.groupMessages) ret = SendBuffered(ssl); } } - if (ret != WANT_WRITE) { + if (ret != WC_NO_ERR_TRACE(WANT_WRITE)) { /* Clean up the fragment offset. */ ssl->options.buildingMsg = 0; ssl->fragOffset = 0; @@ -8759,6 +8874,10 @@ typedef struct Scv13Args { byte sigAlgo; byte* sigData; word16 sigDataSz; +#ifndef NO_RSA + byte* toSign; /* not allocated */ + word32 toSignSz; +#endif #ifdef WOLFSSL_DUAL_ALG_CERTS byte altSigAlgo; word32 altSigLen; /* Only used in the case of both native and alt. */ @@ -8918,7 +9037,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) if (ssl->buffers.key == NULL) { #ifdef HAVE_PK_CALLBACKS if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) - args->length = (word16)GetPrivateKeySigSize(ssl); + args->sigLen = (word16)GetPrivateKeySigSize(ssl); else #endif ERROR_OUT(NO_PRIVATE_KEY, exit_scv); @@ -9146,7 +9265,8 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif /* !NO_RSA */ #ifdef HAVE_ECC if (ssl->hsType == DYNAMIC_TYPE_ECC) { - args->sigLen = args->sendSz - args->idx - HASH_SIG_SIZE - + args->sigLen = (word32)args->sendSz - args->idx - + HASH_SIG_SIZE - VERIFY_HEADER; #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->buffers.keyType != sm2_sa_algo) @@ -9313,7 +9433,17 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif /* HAVE_DILITHIUM */ #ifndef NO_RSA if (ssl->hsType == DYNAMIC_TYPE_RSA) { - ret = RsaSign(ssl, rsaSigBuf->buffer, (word32)rsaSigBuf->length, + args->toSign = rsaSigBuf->buffer; + args->toSignSz = (word32)rsaSigBuf->length; + #if defined(HAVE_PK_CALLBACKS) && \ + defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH) + /* Pass full data to sign (args->sigData), not hash of */ + if (ssl->ctx->RsaPssSignCb) { + args->toSign = args->sigData; + args->toSignSz = args->sigDataSz; + } + #endif + ret = RsaSign(ssl, (const byte*)args->toSign, args->toSignSz, sigOut, &args->sigLen, args->sigAlgo, ssl->options.hashAlgo, (RsaKey*)ssl->hsKey, ssl->buffers.key); @@ -9357,10 +9487,20 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif /* HAVE_ECC */ #ifndef NO_RSA if (ssl->hsAltType == DYNAMIC_TYPE_RSA) { - ret = RsaSign(ssl, rsaSigBuf->buffer, - (word32)rsaSigBuf->length, sigOut, - &args->altSigLen, args->altSigAlgo, - ssl->options.hashAlgo, (RsaKey*)ssl->hsAltKey, + args->toSign = rsaSigBuf->buffer; + args->toSignSz = (word32)rsaSigBuf->length; + #if defined(HAVE_PK_CALLBACKS) && \ + defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH) + /* Pass full data to sign (args->altSigData), not hash of */ + if (ssl->ctx->RsaPssSignCb) { + args->toSign = args->altSigData; + args->toSignSz = (word32)args->altSigDataSz; + } + #endif + ret = RsaSign(ssl, (const byte*)args->toSign, + args->toSignSz, sigOut, &args->altSigLen, + args->altSigAlgo, ssl->options.hashAlgo, + (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey); if (ret == 0) { @@ -9551,7 +9691,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += args->sendSz; + ssl->buffers.outputBuffer.length += (word32)args->sendSz; ssl->options.buildingMsg = 0; if (!ssl->options.groupMessages) ret = SendBuffered(ssl); @@ -10842,7 +10982,8 @@ static int SendTls13Finished(WOLFSSL* ssl) input = output + Dtls13GetRlHeaderLength(ssl, 1); #endif /* WOLFSSL_DTLS13 */ - AddTls13HandShakeHeader(input, (word32)finishedSz, 0, finishedSz, finished, ssl); + AddTls13HandShakeHeader(input, (word32)finishedSz, 0, (word32)finishedSz, + finished, ssl); #if defined(WOLFSSL_RENESAS_TSIP_TLS) if (ssl->options.side == WOLFSSL_CLIENT_END) { @@ -10903,7 +11044,7 @@ static int SendTls13Finished(WOLFSSL* ssl) dtlsRet = Dtls13HandshakeSend(ssl, output, (word16)outputSz, (word16)(Dtls13GetRlHeaderLength(ssl, 1) + headerSz + finishedSz), finished, 1); - if (dtlsRet != 0 && dtlsRet != WANT_WRITE) + if (dtlsRet != 0 && dtlsRet != WC_NO_ERR_TRACE(WANT_WRITE)) return ret; } else @@ -10927,7 +11068,7 @@ static int SendTls13Finished(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ssl->options.buildingMsg = 0; } @@ -11067,7 +11208,7 @@ static int SendTls13Finished(WOLFSSL* ssl) * ssl The SSL/TLS object. * returns 0 on success, otherwise failure. */ -static int SendTls13KeyUpdate(WOLFSSL* ssl) +int SendTls13KeyUpdate(WOLFSSL* ssl) { byte* input; byte* output; @@ -11136,12 +11277,12 @@ static int SendTls13KeyUpdate(WOLFSSL* ssl) } #endif - ssl->buffers.outputBuffer.length += sendSz; + ssl->buffers.outputBuffer.length += (word32)sendSz; ret = SendBuffered(ssl); - if (ret != 0 && ret != WANT_WRITE) + if (ret != 0 && ret != WC_NO_ERR_TRACE(WANT_WRITE)) return ret; } @@ -11244,7 +11385,12 @@ static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* WOLFSSL_DTLS13 */ +#ifndef WOLFSSL_RW_THREADED return SendTls13KeyUpdate(ssl); +#else + ssl->options.sendKeyUpdate = 1; + return 0; +#endif } WOLFSSL_LEAVE("DoTls13KeyUpdate", ret); @@ -12347,7 +12493,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, { int ret = 0, tmp; word32 inIdx = *inOutIdx; - int alertType = invalid_alert; + int alertType; #if defined(HAVE_ECH) TLSX* echX = NULL; word32 echInOutIdx; @@ -12932,7 +13078,7 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_CRYPT /* do not send buffered or advance state if last error was an async pending operation */ - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { if ((ret = SendBuffered(ssl)) == 0) { @@ -13086,6 +13232,14 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) case HELLO_AGAIN_REPLY: /* Get the response/s from the server. */ while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) { +#ifdef WOLFSSL_DTLS13 + if (!IsAtLeastTLSv1_3(ssl->version)) { + #ifndef WOLFSSL_NO_TLS12 + if (ssl->options.downgrade) + return wolfSSL_connect(ssl); + #endif + } +#endif /* WOLFSSL_DTLS13 */ if ((ssl->error = ProcessReply(ssl)) < 0) { WOLFSSL_ERROR(ssl->error); return WOLFSSL_FATAL_ERROR; @@ -13606,7 +13760,7 @@ int wolfSSL_update_keys(WOLFSSL* ssl) { int ret; ret = Tls13UpdateKeys(ssl); - if (ret == WANT_WRITE) + if (ret == WC_NO_ERR_TRACE(WANT_WRITE)) ret = WOLFSSL_ERROR_WANT_WRITE; else if (ret == 0) ret = WOLFSSL_SUCCESS; @@ -13707,7 +13861,7 @@ int wolfSSL_request_certificate(WOLFSSL* ssl) ssl->msgsReceived.got_finished = 0; ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len); - if (ret == WANT_WRITE) + if (ret == WC_NO_ERR_TRACE(WANT_WRITE)) ret = WOLFSSL_ERROR_WANT_WRITE; else if (ret == 0) ret = WOLFSSL_SUCCESS; @@ -14062,7 +14216,7 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) #ifdef WOLFSSL_ASYNC_CRYPT /* do not send buffered or advance state if last error was an async pending operation */ - && ssl->error != WC_PENDING_E + && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { @@ -14440,7 +14594,7 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS); return WOLFSSL_SUCCESS; - default : + default: WOLFSSL_MSG("Unknown accept state ERROR"); return WOLFSSL_FATAL_ERROR; } @@ -14674,7 +14828,7 @@ int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz) ret = ReceiveData(ssl, (byte*)data, sz, FALSE); if (ret > 0) *outSz = ret; - if (ssl->error == ZERO_RETURN) { + if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN)) { ssl->error = WOLFSSL_ERROR_NONE; #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) { diff --git a/src/src/wolfio.c b/src/src/wolfio.c index 52e61a5..a632ff8 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -1,6 +1,6 @@ /* wolfio.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -41,6 +41,11 @@ #include #include +#ifdef NUCLEUS_PLUS_2_3 +/* Holds last Nucleus networking error number */ +int Nucleus_Net_Errno; +#endif + #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) #ifndef USE_WINDOWS_API #if defined(WOLFSSL_LWIP) && !defined(WOLFSSL_APACHE_MYNEWT) @@ -131,68 +136,65 @@ Possible IO enable options: #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) -/* Translates return codes returned from - * send() and recv() if need be. - */ -static WC_INLINE int TranslateReturnCode(int old, int sd) +static WC_INLINE int wolfSSL_LastError(int err, SOCKET_T sd) { (void)sd; -#if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) - if (old == 0) { - errno = SOCKET_EWOULDBLOCK; - return -1; /* convert to BSD style wouldblock as error */ - } - - if (old < 0) { - errno = RTCS_geterror(sd); - if (errno == RTCSERR_TCP_CONN_CLOSING) - return 0; /* convert to BSD style closing */ - if (errno == RTCSERR_TCP_CONN_RLSD) - errno = SOCKET_ECONNRESET; - if (errno == RTCSERR_TCP_TIMED_OUT) - errno = SOCKET_EAGAIN; - } -#elif defined(WOLFSSL_EMNET) - if (old < 0) { /* SOCKET_ERROR */ - /* Get the real socket error */ - IP_SOCK_getsockopt(sd, SOL_SOCKET, SO_ERROR, &old, (int)sizeof(old)); - } -#endif - - return old; -} - -static WC_INLINE int wolfSSL_LastError(int err) -{ - (void)err; /* Suppress unused arg */ + if (err > 0) + return 0; #ifdef USE_WINDOWS_API return WSAGetLastError(); #elif defined(EBSNET) return xn_getlasterror(); #elif defined(WOLFSSL_LINUXKM) || defined(WOLFSSL_EMNET) - return err; /* Return provided error value */ + return -err; /* Return provided error value with corrected sign. */ #elif defined(FUSION_RTOS) #include return FCL_GET_ERRNO; +#elif defined(NUCLEUS_PLUS_2_3) + return Nucleus_Net_Errno; +#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) + if ((err == 0) || (err == -SOCKET_EWOULDBLOCK)) { + return SOCKET_EWOULDBLOCK; /* convert to BSD style wouldblock */ + } else { + err = RTCS_geterror(sd); + if ((err == RTCSERR_TCP_CONN_CLOSING) || + (err == RTCSERR_TCP_CONN_RLSD)) + { + err = SOCKET_ECONNRESET; + } + return err; + } +#elif defined(WOLFSSL_EMNET) + /* Get the real socket error */ + IP_SOCK_getsockopt(sd, SOL_SOCKET, SO_ERROR, &err, (int)sizeof(old)); + return err; #else return errno; #endif } -static int TranslateIoError(int err) +/* Translates return codes returned from + * send(), recv(), and other network I/O calls. + */ +static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) { #ifdef _WIN32 size_t errstr_offset; char errstr[WOLFSSL_STRERROR_BUFFER_SIZE]; #endif /* _WIN32 */ - +#if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) if (err > 0) return err; +#else + if (err >= 0) + return err; +#endif + + err = wolfSSL_LastError(err, sd); - err = wolfSSL_LastError(err); #if SOCKET_EWOULDBLOCK != SOCKET_EAGAIN if ((err == SOCKET_EWOULDBLOCK) || (err == SOCKET_EAGAIN)) #else @@ -200,8 +202,26 @@ static int TranslateIoError(int err) #endif { WOLFSSL_MSG("\tWould block"); - return WOLFSSL_CBIO_ERR_WANT_READ; + if (direction == SOCKET_SENDING) + return WOLFSSL_CBIO_ERR_WANT_WRITE; + else if (direction == SOCKET_RECEIVING) + return WOLFSSL_CBIO_ERR_WANT_READ; + else + return WOLFSSL_CBIO_ERR_GENERAL; } + +#ifdef SOCKET_ETIMEDOUT + else if (err == SOCKET_ETIMEDOUT) { + WOLFSSL_MSG("\tTimed out"); + if (direction == SOCKET_SENDING) + return WOLFSSL_CBIO_ERR_WANT_WRITE; + else if (direction == SOCKET_RECEIVING) + return WOLFSSL_CBIO_ERR_WANT_READ; + else + return WOLFSSL_CBIO_ERR_TIMEOUT; + } +#endif + else if (err == SOCKET_ECONNRESET) { WOLFSSL_MSG("\tConnection reset"); return WOLFSSL_CBIO_ERR_CONN_RST; @@ -239,56 +259,58 @@ static int TranslateIoError(int err) #ifdef OPENSSL_EXTRA #ifndef NO_BIO -/* Use the WOLFSSL read BIO for receiving data. This is set by the function - * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIORecv. - * - * ssl WOLFSSL struct passed in that has this function set as the receive - * callback. - * buf buffer to fill with data read - * sz size of buf buffer - * ctx a user set context - * - * returns the amount of data read or want read. See WOLFSSL_CBIO_ERR_* values. - */ + +int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) +{ + return SslBioSend(ssl, buf, sz, ctx); +} + int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) { - int recvd = WOLFSSL_CBIO_ERR_GENERAL; + return SslBioReceive(ssl, buf, sz, ctx); +} + +int BioReceiveInternal(WOLFSSL_BIO* biord, WOLFSSL_BIO* biowr, char* buf, + int sz) +{ + int recvd = WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_GENERAL); - WOLFSSL_ENTER("BioReceive"); + WOLFSSL_ENTER("SslBioReceive"); - if (ssl->biord == NULL) { + if (biord == NULL) { WOLFSSL_MSG("WOLFSSL biord not set"); return WOLFSSL_CBIO_ERR_GENERAL; } - recvd = wolfSSL_BIO_read(ssl->biord, buf, sz); + recvd = wolfSSL_BIO_read(biord, buf, sz); if (recvd <= 0) { if (/* ssl->biowr->wrIdx is checked for Bind9 */ - wolfSSL_BIO_method_type(ssl->biowr) == WOLFSSL_BIO_BIO && - wolfSSL_BIO_wpending(ssl->biowr) != 0 && + wolfSSL_BIO_method_type(biowr) == WOLFSSL_BIO_BIO && + wolfSSL_BIO_wpending(biowr) != 0 && /* Not sure this pending check is necessary but let's double * check that the read BIO is empty before we signal a write * need */ - wolfSSL_BIO_supports_pending(ssl->biord) && - wolfSSL_BIO_ctrl_pending(ssl->biord) == 0) { + wolfSSL_BIO_supports_pending(biord) && + wolfSSL_BIO_ctrl_pending(biord) == 0) { /* Let's signal to the app layer that we have * data pending that needs to be sent. */ return WOLFSSL_CBIO_ERR_WANT_WRITE; } - else if (ssl->biord->type == WOLFSSL_BIO_SOCKET) { + else if (biord->type == WOLFSSL_BIO_SOCKET) { if (recvd == 0) { - WOLFSSL_MSG("BioReceive connection closed"); + WOLFSSL_MSG("SslBioReceive connection closed"); return WOLFSSL_CBIO_ERR_CONN_CLOSE; } #ifdef USE_WOLFSSL_IO - recvd = TranslateIoError(recvd); + recvd = TranslateIoReturnCode(recvd, biord->num.fd, + SOCKET_RECEIVING); #endif return recvd; } /* If retry and read flags are set, return WANT_READ */ - if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) && - (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) { + if ((biord->flags & WOLFSSL_BIO_FLAG_READ) && + (biord->flags & WOLFSSL_BIO_FLAG_RETRY)) { return WOLFSSL_CBIO_ERR_WANT_READ; } @@ -296,10 +318,27 @@ int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) return WOLFSSL_CBIO_ERR_GENERAL; } - (void)ctx; return recvd; } +/* Use the WOLFSSL read BIO for receiving data. This is set by the function + * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIORecv. + * + * ssl WOLFSSL struct passed in that has this function set as the receive + * callback. + * buf buffer to fill with data read + * sz size of buf buffer + * ctx a user set context + * + * returns the amount of data read or want read. See WOLFSSL_CBIO_ERR_* values. + */ +int SslBioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) +{ + WOLFSSL_ENTER("SslBioReceive"); + (void)ctx; + return BioReceiveInternal(ssl->biord, ssl->biowr, buf, sz); +} + /* Use the WOLFSSL write BIO for sending data. This is set by the function * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIOSend. @@ -311,11 +350,11 @@ int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) * * returns the amount of data sent or want send. See WOLFSSL_CBIO_ERR_* values. */ -int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) +int SslBioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) { - int sent = WOLFSSL_CBIO_ERR_GENERAL; + int sent = WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_GENERAL); - WOLFSSL_ENTER("BioSend"); + WOLFSSL_ENTER("SslBioSend"); if (ssl->biowr == NULL) { WOLFSSL_MSG("WOLFSSL biowr not set"); @@ -326,7 +365,8 @@ int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) if (sent <= 0) { if (ssl->biowr->type == WOLFSSL_BIO_SOCKET) { #ifdef USE_WOLFSSL_IO - sent = TranslateIoError(sent); + sent = TranslateIoReturnCode(sent, ssl->biowr->num.fd, + SOCKET_SENDING); #endif return sent; } @@ -370,7 +410,6 @@ int EmbedReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx) recvd = wolfIO_Recv(sd, buf, sz, ssl->rflags); if (recvd < 0) { WOLFSSL_MSG("Embed Receive error"); - return TranslateIoError(recvd); } else if (recvd == 0) { WOLFSSL_MSG("Embed receive connection closed"); @@ -400,7 +439,6 @@ int EmbedSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) sent = wolfIO_Send(sd, buf, sz, ssl->wflags); if (sent < 0) { WOLFSSL_MSG("Embed Send error"); - return TranslateIoError(sent); } return sent; @@ -411,6 +449,110 @@ int EmbedSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) #include +#if defined(NUCLEUS_PLUS_2_3) +STATIC INT32 nucyassl_recv(INT sd, CHAR *buf, UINT16 sz, INT16 flags) +{ + int recvd; + + /* Read data from socket */ + recvd = NU_Recv(sd, buf, sz, flags); + if (recvd < 0) { + if (recvd == NU_NOT_CONNECTED) { + recvd = 0; + } else { + Nucleus_Net_Errno = recvd; + recvd = WOLFSSL_FATAL_ERROR; + } + } else { + Nucleus_Net_Errno = 0; + } + + return (recvd); +} + + +STATIC int nucyassl_send(INT sd, CHAR *buf, UINT16 sz, INT16 flags) +{ + int sent; + + /* Write data to socket */ + sent = NU_Send(sd, buf, sz, flags); + + if (sent < 0) { + Nucleus_Net_Errno = sent; + sent = WOLFSSL_FATAL_ERROR; + } else { + Nucleus_Net_Errno = 0; + } + + return sent; +} + +#define SELECT_FUNCTION nucyassl_select + +int nucyassl_select(INT sd, UINT32 timeout) +{ + FD_SET readfs; + STATUS status; + + /* Init fs data for socket */ + NU_FD_Init(&readfs); + NU_FD_Set(sd, &readfs); + + /* Wait for data to arrive */ + status = NU_Select((sd + 1), &readfs, NU_NULL, NU_NULL, + (timeout * NU_TICKS_PER_SECOND)); + + if (status < 0) { + Nucleus_Net_Errno = status; + status = WOLFSSL_FATAL_ERROR; + } + + return status; +} + +#define sockaddr_storage addr_struct +#define sockaddr addr_struct + +STATIC INT32 nucyassl_recvfrom(INT sd, CHAR *buf, UINT16 sz, INT16 flags, + SOCKADDR *peer, XSOCKLENT *peersz) +{ + int recvd; + + memset(peer, 0, sizeof(struct addr_struct)); + + recvd = NU_Recv_From(sd, buf, sz, flags, (struct addr_struct *) peer, + (INT16*) peersz); + if (recvd < 0) { + Nucleus_Net_Errno = recvd; + recvd = WOLFSSL_FATAL_ERROR; + } else { + Nucleus_Net_Errno = 0; + } + + return recvd; + +} + +STATIC int nucyassl_sendto(INT sd, CHAR *buf, UINT16 sz, INT16 flags, + const SOCKADDR *peer, INT16 peersz) +{ + int sent; + + sent = NU_Send_To(sd, buf, sz, flags, (const struct addr_struct *) peer, + peersz); + + if (sent < 0) { + Nucleus_Net_Errno = sent; + sent = WOLFSSL_FATAL_ERROR; + } else { + Nucleus_Net_Errno = 0; + } + + return sent; +} +#endif /* NUCLEUS_PLUS_2_3 */ + #ifndef DTLS_SENDTO_FUNCTION #define DTLS_SENDTO_FUNCTION sendto #endif @@ -508,6 +650,7 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) #elif !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) word32 invalidPeerPackets = 0; #endif + int newPeer = 0; WOLFSSL_ENTER("EmbedReceiveFrom"); @@ -535,8 +678,13 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) dtlsCtx->peer.bufSz = sizeof(SOCKADDR_S); else dtlsCtx->peer.bufSz = 0; + newPeer = 1; + peer = (SOCKADDR_S*)dtlsCtx->peer.sa; + } + else { + peer = &lclPeer; + XMEMCPY(peer, (SOCKADDR_S*)dtlsCtx->peer.sa, sizeof(lclPeer)); } - peer = (SOCKADDR_S*)dtlsCtx->peer.sa; peerSz = dtlsCtx->peer.bufSz; } @@ -546,9 +694,20 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { - doDtlsTimeout = - doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL || + doDtlsTimeout = doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL; +#ifdef WOLFSSL_RW_THREADED + { + int ret = wc_LockMutex(&ssl->dtls13Rtx.mutex); + if (ret < 0) { + return ret; + } + } +#endif + doDtlsTimeout = doDtlsTimeout || (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL); +#ifdef WOLFSSL_RW_THREADED + wc_UnLockMutex(&ssl->dtls13Rtx.mutex); +#endif } #endif /* WOLFSSL_DTLS13 */ @@ -635,12 +794,11 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) peerSz = (XSOCKLENT)dtlsCtx->peer.bufSz; } - recvd = TranslateReturnCode(recvd, sd); + recvd = TranslateIoReturnCode(recvd, sd, SOCKET_RECEIVING); if (recvd < 0) { WOLFSSL_MSG("Embed Receive From error"); - recvd = TranslateIoError(recvd); - if (recvd == WOLFSSL_CBIO_ERR_WANT_READ && + if (recvd == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ) && !wolfSSL_dtls_get_using_nonblock(ssl)) { recvd = WOLFSSL_CBIO_ERR_TIMEOUT; } @@ -681,8 +839,16 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } } else { - /* Store size of saved address */ - dtlsCtx->peer.sz = peerSz; + if (newPeer) { + /* Store size of saved address */ + dtlsCtx->peer.sz = peerSz; + } +#ifndef WOLFSSL_PEER_ADDRESS_CHANGES + else if ((dtlsCtx->peer.sz != (unsigned int)peerSz) || + (XMEMCMP(peer, dtlsCtx->peer.sa, peerSz) != 0)) { + return WOLFSSL_CBIO_ERR_GENERAL; + } +#endif } #ifndef NO_ASN_TIME ssl->dtls_start_timeout = 0; @@ -724,11 +890,10 @@ int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx) sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, (size_t)sz, ssl->wflags, (const SOCKADDR*)peer, peerSz); - sent = TranslateReturnCode(sent, sd); + sent = TranslateIoReturnCode(sent, sd, SOCKET_SENDING); if (sent < 0) { WOLFSSL_MSG("Embed Send To error"); - return TranslateIoError(sent); } return sent; @@ -750,16 +915,14 @@ int EmbedReceiveFromMcast(WOLFSSL *ssl, char *buf, int sz, void *ctx) recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, ssl->rflags, NULL, NULL); - recvd = TranslateReturnCode(recvd, sd); + recvd = TranslateIoReturnCode(recvd, sd, SOCKET_RECEIVING); if (recvd < 0) { WOLFSSL_MSG("Embed Receive From error"); - recvd = TranslateIoError(recvd); - if (recvd == WOLFSSL_CBIO_ERR_WANT_READ && + if (recvd == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ) && !wolfSSL_dtls_get_using_nonblock(ssl)) { recvd = WOLFSSL_CBIO_ERR_TIMEOUT; } - return recvd; } return recvd; @@ -987,7 +1150,7 @@ int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags) int recvd; recvd = (int)RECV_FUNCTION(sd, buf, (size_t)sz, rdFlags); - recvd = TranslateReturnCode(recvd, (int)sd); + recvd = TranslateIoReturnCode(recvd, sd, SOCKET_RECEIVING); return recvd; } @@ -997,11 +1160,41 @@ int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags) int sent; sent = (int)SEND_FUNCTION(sd, buf, (size_t)sz, wrFlags); - sent = TranslateReturnCode(sent, (int)sd); + sent = TranslateIoReturnCode(sent, sd, SOCKET_SENDING); return sent; } +#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && defined(OPENSSL_EXTRA) + +int wolfIO_RecvFrom(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int rdFlags) +{ + int recvd; + socklen_t addr_len = (socklen_t)sizeof(*addr); + + recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, rdFlags, + addr ? &addr->sa : NULL, + addr ? &addr_len : 0); + recvd = TranslateIoReturnCode(recvd, sd, SOCKET_RECEIVING); + + return recvd; +} + +int wolfIO_SendTo(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int wrFlags) +{ + int sent; + socklen_t addr_len = addr ? wolfSSL_BIO_ADDR_size(addr) : 0; + + sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, (size_t)sz, wrFlags, + addr ? &addr->sa : NULL, + addr_len); + sent = TranslateIoReturnCode(sent, sd, SOCKET_SENDING); + + return sent; +} + +#endif /* WOLFSSL_HAVE_BIO_ADDR && WOLFSSL_DTLS && OPENSSL_EXTRA */ + #endif /* USE_WOLFSSL_IO */ @@ -1030,7 +1223,7 @@ int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags) unsigned long blocking = non_blocking; ret = ioctlsocket(sockfd, FIONBIO, &blocking); if (ret == SOCKET_ERROR) - ret = -1; + ret = WOLFSSL_FATAL_ERROR; #else ret = fcntl(sockfd, F_GETFL, 0); if (ret >= 0) { @@ -1060,7 +1253,7 @@ int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags) if ((sockfd < 0) || (sockfd >= FD_SETSIZE)) { WOLFSSL_MSG("socket fd out of FDSET range"); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -1146,7 +1339,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) #endif /* HAVE_SOCKADDR */ if (sockfd == NULL || ip == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } #if !defined(HAVE_GETADDRINFO) @@ -1175,12 +1368,12 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) if (wolfIO_Word16ToString(strPort, port) == 0) { WOLFSSL_MSG("invalid port number for responder"); - return -1; + return WOLFSSL_FATAL_ERROR; } if (getaddrinfo(ip, strPort, &hints, &answer) < 0 || answer == NULL) { WOLFSSL_MSG("no addr info for responder"); - return -1; + return WOLFSSL_FATAL_ERROR; } sockaddr_len = answer->ai_addrlen; @@ -1244,7 +1437,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) } else { WOLFSSL_MSG("no addr info for responder"); - return -1; + return WOLFSSL_FATAL_ERROR; } } #else @@ -1284,7 +1477,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) if (entry == NULL) { WOLFSSL_MSG("no addr info for responder"); - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -1297,7 +1490,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) { WOLFSSL_MSG("bad socket fd, out of fds?"); *sockfd = SOCKET_INVALID; - return -1; + return WOLFSSL_FATAL_ERROR; } #ifdef HAVE_IO_TIMEOUT @@ -1313,7 +1506,8 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) #ifdef HAVE_IO_TIMEOUT if ((ret != 0) && (to_sec > 0)) { #ifdef USE_WINDOWS_API - if ((ret == SOCKET_ERROR) && (wolfSSL_LastError(ret) == WSAEWOULDBLOCK)) + if ((ret == SOCKET_ERROR) && + (wolfSSL_LastError(ret, *sockfd) == SOCKET_EWOULDBLOCK)) #else if (errno == EINPROGRESS) #endif @@ -1330,7 +1524,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) WOLFSSL_MSG("Responder tcp connect failed"); CloseSocket(*sockfd); *sockfd = SOCKET_INVALID; - return -1; + return WOLFSSL_FATAL_ERROR; } return ret; #else @@ -1338,7 +1532,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) (void)ip; (void)port; (void)to_sec; - return -1; + return WOLFSSL_FATAL_ERROR; #endif /* HAVE_SOCKADDR */ } @@ -1351,7 +1545,7 @@ int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port) SOCKADDR_IN *sin = (SOCKADDR_IN *)&addr; if (sockfd == NULL || port < 1) { - return -1; + return WOLFSSL_FATAL_ERROR; } XMEMSET(&addr, 0, sizeof(addr)); @@ -1369,7 +1563,7 @@ int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port) { WOLFSSL_MSG("socket failed"); *sockfd = SOCKET_INVALID; - return -1; + return WOLFSSL_FATAL_ERROR; } #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\ @@ -1390,14 +1584,14 @@ int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port) WOLFSSL_MSG("wolfIO_TcpBind failed"); CloseSocket(*sockfd); *sockfd = SOCKET_INVALID; - ret = -1; + ret = WOLFSSL_FATAL_ERROR; } return ret; #else (void)sockfd; (void)port; - return -1; + return WOLFSSL_FATAL_ERROR; #endif /* HAVE_SOCKADDR */ } @@ -1477,7 +1671,7 @@ int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath, } for (j = 0; j < i; j++) { - if (port[j] < '0' || port[j] > '9') return -1; + if (port[j] < '0' || port[j] > '9') return WOLFSSL_FATAL_ERROR; bigPort = (bigPort * 10) + (word32)(port[j] - '0'); } if (outPort) @@ -1508,8 +1702,9 @@ int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath, return result; } -static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, - int* recvBufSz, int chunkSz, char* start, int len, int dynType, void* heap) +static int wolfIO_HttpProcessResponseBuf(WolfSSLGenericIORecvCb ioCb, + void* ioCbCtx, byte **recvBuf, int* recvBufSz, int chunkSz, char* start, + int len, int dynType, void* heap) { byte* newRecvBuf = NULL; int newRecvSz = *recvBufSz + chunkSz; @@ -1556,13 +1751,13 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, else { WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf bad size"); XFREE(newRecvBuf, heap, dynType); - return -1; + return WOLFSSL_FATAL_ERROR; } } /* receive the remainder of chunk */ while (len < chunkSz) { - int rxSz = wolfIO_Recv(sfd, (char*)&newRecvBuf[pos], chunkSz-len, 0); + int rxSz = ioCb((char*)&newRecvBuf[pos], chunkSz-len, ioCbCtx); if (rxSz > 0) { len += rxSz; pos += rxSz; @@ -1570,7 +1765,7 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, else { WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf recv failed"); XFREE(newRecvBuf, heap, dynType); - return -1; + return WOLFSSL_FATAL_ERROR; } } @@ -1580,8 +1775,9 @@ static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf, return 0; } -int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, - byte** respBuf, byte* httpBuf, int httpBufSz, int dynType, void* heap) +int wolfIO_HttpProcessResponseGenericIO(WolfSSLGenericIORecvCb ioCb, + void* ioCbCtx, const char** appStrList, unsigned char** respBuf, + unsigned char* httpBuf, int httpBufSz, int dynType, void* heap) { static const char HTTP_PROTO[] = "HTTP/1."; static const char HTTP_STATUS_200[] = "200"; @@ -1602,8 +1798,8 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, do { if (state == phr_get_chunk_data) { /* get chunk of data */ - result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz, - chunkSz, start, len, dynType, heap); + result = wolfIO_HttpProcessResponseBuf(ioCb, ioCbCtx, respBuf, + &respBufSz, chunkSz, start, len, dynType, heap); state = (result != 0) ? phr_http_end : phr_get_chunk_len; end = NULL; @@ -1617,16 +1813,14 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, * can. */ } - result = wolfIO_Recv(sfd, (char*)httpBuf+len, httpBufSz-len-1, 0); + result = ioCb((char*)httpBuf+len, httpBufSz-len-1, ioCbCtx); if (result > 0) { len += result; start = (char*)httpBuf; start[len] = 0; } else { - result = TranslateReturnCode(result, sfd); - result = wolfSSL_LastError(result); - if (result == SOCKET_EWOULDBLOCK || result == SOCKET_EAGAIN) { + if (result == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { return OCSP_WANT_READ; } @@ -1745,8 +1939,8 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, } while (state != phr_http_end); if (!isChunked) { - result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz, chunkSz, - start, len, dynType, heap); + result = wolfIO_HttpProcessResponseBuf(ioCb, ioCbCtx, respBuf, + &respBufSz, chunkSz, start, len, dynType, heap); } if (result >= 0) { @@ -1758,6 +1952,22 @@ int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, return result; } + +static int httpResponseIoCb(char* buf, int sz, void* ctx) +{ + /* Double cast to silence the compiler int/pointer width msg */ + return wolfIO_Recv((SOCKET_T)(uintptr_t)ctx, buf, sz, 0); +} + +int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, + byte** respBuf, byte* httpBuf, int httpBufSz, int dynType, void* heap) +{ + return wolfIO_HttpProcessResponseGenericIO(httpResponseIoCb, + /* Double cast to silence the compiler int/pointer width msg */ + (void*)(uintptr_t)sfd, appStrList, respBuf, httpBuf, httpBufSz, + dynType, heap); +} + int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName, const char *path, int pathLen, int reqSz, const char *contentType, byte *buf, int bufSize) @@ -1879,17 +2089,25 @@ int wolfIO_HttpBuildRequestOcsp(const char* domainName, const char* path, ocspReqSz, "application/ocsp-request", cacheCtl, buf, bufSize); } +static const char* ocspAppStrList[] = { + "application/ocsp-response", + NULL +}; + +WOLFSSL_API int wolfIO_HttpProcessResponseOcspGenericIO( + WolfSSLGenericIORecvCb ioCb, void* ioCbCtx, unsigned char** respBuf, + unsigned char* httpBuf, int httpBufSz, void* heap) +{ + return wolfIO_HttpProcessResponseGenericIO(ioCb, ioCbCtx, + ocspAppStrList, respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_OCSP, heap); +} + /* return: >0 OCSP Response Size * -1 error */ int wolfIO_HttpProcessResponseOcsp(int sfd, byte** respBuf, byte* httpBuf, int httpBufSz, void* heap) { - const char* appStrList[] = { - "application/ocsp-response", - NULL - }; - - return wolfIO_HttpProcessResponse(sfd, appStrList, + return wolfIO_HttpProcessResponse(sfd, ocspAppStrList, respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_OCSP, heap); } @@ -1976,8 +2194,7 @@ int EmbedOcspLookup(void* ctx, const char* url, int urlSz, /* in default callback ctx is heap hint */ void EmbedOcspRespFree(void* ctx, byte *resp) { - if (resp) - XFREE(resp, ctx, DYNAMIC_TYPE_OCSP); + XFREE(resp, ctx, DYNAMIC_TYPE_OCSP); (void)ctx; } @@ -2862,7 +3079,7 @@ int uIPReceive(WOLFSSL *ssl, char *buf, int sz, void *_ctx) { uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx; if (!ctx || !ctx->ssl_rx_databuf) - return -1; + return WOLFSSL_FATAL_ERROR; (void)ssl; if (ctx->ssl_rb_len > 0) { if (sz > ctx->ssl_rb_len - ctx->ssl_rb_off) @@ -3014,7 +3231,7 @@ int LwIPNativeSend(WOLFSSL* ssl, char* buf, int sz, void* ctx) ret = tcp_write(nlwip->pcb, buf, sz, TCP_WRITE_FLAG_COPY); if (ret != ERR_OK) { - sz = -1; + sz = WOLFSSL_FATAL_ERROR; } return sz; diff --git a/src/src/x509.c b/src/src/x509.c index 72a4f37..18feff0 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -1,6 +1,6 @@ /* x509.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -362,71 +362,9 @@ WOLFSSL_STACK* wolfSSL_sk_new_x509_ext(void) * OpenSSL. */ int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk,WOLFSSL_X509_EXTENSION* ext) { - WOLFSSL_STACK* node; - WOLFSSL_ENTER("wolfSSL_sk_X509_EXTENSION_push"); - if (sk == NULL || ext == NULL) { - return WOLFSSL_FAILURE; - } - - /* no previous values in stack */ - if (sk->data.ext == NULL) { - sk->data.ext = ext; - sk->num += 1; - return (int)sk->num; - } - - /* stack already has value(s) create a new node and add more */ - node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, - DYNAMIC_TYPE_X509); - if (node == NULL) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; - } - XMEMSET(node, 0, sizeof(WOLFSSL_STACK)); - - /* push new obj onto head of stack */ - node->data.ext = sk->data.ext; - node->next = sk->next; - node->type = sk->type; - sk->next = node; - sk->data.ext = ext; - sk->num += 1; - - return (int)sk->num; -} - -/* Free the structure for X509_EXTENSION stack - * - * sk stack to free nodes in - */ -void wolfSSL_sk_X509_EXTENSION_free(WOLFSSL_STACK* sk) -{ - WOLFSSL_STACK* node; - - WOLFSSL_ENTER("wolfSSL_sk_X509_EXTENSION_free"); - - if (sk == NULL) { - return; - } - - /* parse through stack freeing each node */ - node = sk->next; - while ((node != NULL) && (sk->num > 1)) { - WOLFSSL_STACK* tmp = node; - node = node->next; - - wolfSSL_X509_EXTENSION_free(tmp->data.ext); - XFREE(tmp, NULL, DYNAMIC_TYPE_X509); - sk->num -= 1; - } - - /* free head of stack */ - if (sk->num == 1) { - wolfSSL_X509_EXTENSION_free(sk->data.ext); - } - XFREE(sk, NULL, DYNAMIC_TYPE_X509); + return wolfSSL_sk_push(sk, ext); } static WOLFSSL_STACK* generateExtStack(const WOLFSSL_X509 *x) @@ -523,22 +461,22 @@ int wolfSSL_X509_get_ext_by_OBJ(const WOLFSSL_X509 *x, if (!x || !obj) { WOLFSSL_MSG("Bad parameter"); - return -1; + return WOLFSSL_FATAL_ERROR; } sk = wolfSSL_X509_get0_extensions(x); if (!sk) { WOLFSSL_MSG("No extensions"); - return -1; + return WOLFSSL_FATAL_ERROR; } lastpos++; if (lastpos < 0) lastpos = 0; for (; lastpos < wolfSSL_sk_num(sk); lastpos++) - if (wolfSSL_OBJ_cmp((WOLFSSL_ASN1_OBJECT*)wolfSSL_sk_value(sk, - lastpos), obj) == 0) + if (wolfSSL_OBJ_cmp(wolfSSL_sk_X509_EXTENSION_value(sk, + lastpos)->obj, obj) == 0) return lastpos; - return -1; + return WOLFSSL_FATAL_ERROR; } #endif /* OPENSSL_ALL || OPENSSL_EXTRA */ @@ -556,10 +494,10 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, WOLFSSL_GENERAL_NAME* gn) { int ret = 0; - WOLFSSL_ASN1_OBJECT* obj; - WOLFSSL_ASN1_TYPE* type; - WOLFSSL_ASN1_STRING* str; - byte tag; + WOLFSSL_ASN1_OBJECT* obj = NULL; + WOLFSSL_ASN1_TYPE* type = NULL; + WOLFSSL_ASN1_STRING* str = NULL; + byte tag = 0; unsigned char* p = (unsigned char *)dns->name; long len = dns->len; @@ -594,7 +532,7 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, goto err; } - tag = ASN_UTF8STRING; + tag = V_ASN1_UTF8STRING; } else #endif @@ -604,54 +542,34 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, /* Create an object id for general name from DER encoding. */ obj = wolfSSL_d2i_ASN1_OBJECT(NULL, (const unsigned char**)&p, len); - if (obj == NULL) { + if (obj == NULL) goto err; - } /* Pointer moved on and now update length of remaining data. */ len -= (long)((size_t)p - (size_t)dns->name); - /* Next is: [0]. Check tag and length. */ - if (GetASNTag(p, &idx, &tag, (word32)len) < 0) { - wolfSSL_ASN1_OBJECT_free(obj); - goto err; - } - if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)) { - wolfSSL_ASN1_OBJECT_free(obj); - goto err; - } - if (GetLength(p, &idx, &nameLen, (word32)len) <= 1) { - wolfSSL_ASN1_OBJECT_free(obj); - goto err; - } - - /* Next is a string of some type. */ - if (GetASNTag(p, &idx, &tag, (word32)len) < 0) { - wolfSSL_ASN1_OBJECT_free(obj); + /* Next is "value [0] EXPLICIT ANY DEFINED BY type-id" */ + if (GetASNHeader(p, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0, + &idx, &nameLen, (word32)len) < 0) goto err; - } - if (GetLength(p, &idx, &nameLen, (word32)len) <= 0) { - wolfSSL_ASN1_OBJECT_free(obj); - goto err; - } p += idx; len -= idx; + + /* Set the tag to object so that it gets output in raw form */ + tag = V_ASN1_SEQUENCE; } + /* Create a WOLFSSL_ASN1_STRING from the DER. */ str = wolfSSL_ASN1_STRING_type_new(tag); if (str == NULL) { - wolfSSL_ASN1_OBJECT_free(obj); goto err; } wolfSSL_ASN1_STRING_set(str, p, (int)len); /* Wrap string in a WOLFSSL_ASN1_TYPE. */ type = wolfSSL_ASN1_TYPE_new(); - if (type == NULL) { - wolfSSL_ASN1_OBJECT_free(obj); - wolfSSL_ASN1_STRING_free(str); + if (type == NULL) goto err; - } wolfSSL_ASN1_TYPE_set(type, tag, str); /* Store the object and string in general name. */ @@ -660,6 +578,10 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, ret = 1; err: + if (ret != 1) { + wolfSSL_ASN1_OBJECT_free(obj); + wolfSSL_ASN1_STRING_free(str); + } return ret; } #endif /* OPENSSL_ALL || WOLFSSL_WPAS_SMALL */ @@ -722,7 +644,7 @@ static int wolfssl_x509_alt_names_to_gn(WOLFSSL_X509* x509, } } - if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) <= 0) { WOLFSSL_MSG("Error pushing onto stack"); wolfSSL_GENERAL_NAME_free(gn); wolfSSL_sk_pop_free(sk, NULL); @@ -917,11 +839,37 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) switch (oid) { case BASIC_CA_OID: + { + word32 dataIdx = idx; + word32 dummyOid; + int dataLen = 0; + if (!isSet) break; /* Set pathlength */ a = wolfSSL_ASN1_INTEGER_new(); - if (a == NULL) { + + /* Set the data */ + ret = GetObjectId(input, &dataIdx, &dummyOid, oidCertExtType, + (word32)sz) == 0; + if (ret && dataIdx < (word32)sz) { + /* Skip the critical information */ + if (input[dataIdx] == ASN_BOOLEAN) { + dataIdx++; + ret = GetLength(input, &dataIdx, &dataLen, sz) >= 0; + dataIdx += dataLen; + } + } + if (ret) { + ret = GetOctetString(input, &dataIdx, &dataLen, + (word32)sz) > 0; + } + if (ret) { + ret = wolfSSL_ASN1_STRING_set(&ext->value, input + dataIdx, + dataLen) == 1; + } + + if (a == NULL || !ret) { wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); #ifdef WOLFSSL_SMALL_STACK @@ -937,7 +885,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) ext->obj->ca = x509->isCa; ext->crit = x509->basicConstCrit; break; - + } case AUTH_INFO_OID: if (!isSet) break; @@ -976,7 +924,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) obj->grp = oidCertAuthInfoType; obj->nid = NID_ad_ca_issuers; - ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj); + ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Error pushing ASN1 object onto stack"); wolfSSL_ASN1_OBJECT_free(obj); @@ -1011,7 +960,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) obj->grp = oidCertAuthInfoType; obj->nid = NID_ad_OCSP; - ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj); + ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Error pushing ASN1 object onto stack"); wolfSSL_ASN1_OBJECT_free(obj); @@ -1067,7 +1017,9 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) case CERT_POLICY_OID: if (!isSet) break; + #ifdef WOLFSSL_SEP ext->crit = x509->certPolicyCrit; + #endif break; case KEY_USAGE_OID: @@ -1249,7 +1201,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) */ if (x509->ext_sk == NULL) x509->ext_sk = wolfSSL_sk_new_x509_ext(); - if (wolfSSL_sk_X509_EXTENSION_push(x509->ext_sk, ext) == WOLFSSL_FAILURE) { + if (wolfSSL_sk_insert(x509->ext_sk, ext, -1) <= 0) { wolfSSL_X509_EXTENSION_free(ext); ext = NULL; } @@ -1338,7 +1290,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo word32 len = 0; len = SetOthername(gn->d.otherName, NULL); - if (len == WOLFSSL_FAILURE) { + if (len == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { return WOLFSSL_FAILURE; } @@ -1354,7 +1306,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo ret = wolfSSL_X509_add_altname_ex(x509, buf, len, ASN_OTHER_TYPE); XFREE(buf, x509->heap, DYNAMIC_TYPE_X509_EXT); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("wolfSSL_X509_add_altname_ex() failed"); return WOLFSSL_FAILURE; } @@ -1424,6 +1376,11 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo break; default: #ifdef WOLFSSL_CUSTOM_OID + { + char *oid = NULL; + byte *val = NULL; + int err = 0; + if ((ext->obj == NULL) || (ext->value.length == 0)) { WOLFSSL_MSG("Extension has insufficient information."); return WOLFSSL_FAILURE; @@ -1436,12 +1393,10 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } /* This is a viable custom extension. */ - char *oid = XMALLOC(MAX_OID_STRING_SZ, x509->heap, - DYNAMIC_TYPE_X509_EXT); - byte *val = XMALLOC(ext->value.length, x509->heap, - DYNAMIC_TYPE_X509_EXT); - int err = 0; - + oid = (char*)XMALLOC(MAX_OID_STRING_SZ, x509->heap, + DYNAMIC_TYPE_X509_EXT); + val = (byte*)XMALLOC(ext->value.length, x509->heap, + DYNAMIC_TYPE_X509_EXT); if ((oid == NULL) || (val == NULL)) { WOLFSSL_MSG("Memory allocation failure.\n"); err = 1; @@ -1466,12 +1421,13 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo x509->custom_exts[x509->customExtCount].val = val; x509->custom_exts[x509->customExtCount].valSz = ext->value.length; x509->customExtCount++; + break; + } #else WOLFSSL_MSG("Unsupported extension to add"); return WOLFSSL_FAILURE; #endif /* WOLFSSL_CUSTOM_OID */ - break; - } + } /* switch (nid) */ return WOLFSSL_SUCCESS; } @@ -1485,7 +1441,7 @@ int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, ASN1_OBJECT* obj; ASN1_STRING* str; int nid; - int rc = WOLFSSL_FAILURE; + int rc = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); char tmp[CTC_NAME_SIZE*2 + 1]; const int tmpSz = sizeof(tmp); int tmpLen = 0; @@ -1807,7 +1763,8 @@ static WOLFSSL_AUTHORITY_INFO_ACCESS* wolfssl_x509v3_ext_aia_d2i( break; } /* Push onto AUTHORITY_INFO_ACCESS stack. */ - ret = wolfSSL_sk_ACCESS_DESCRIPTION_push(aia, ad); + ret = wolfSSL_sk_ACCESS_DESCRIPTION_push(aia, ad) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Error pushing ASN1 AD onto stack"); err = 1; @@ -2035,7 +1992,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) * lastPos : Start search from extension after lastPos. * Set to -1 to search from index 0. * return >= 0 If successful the extension index is returned. - * return -1 If extension is not found or error is encountered. + * return WOLFSSL_FATAL_ERROR If extension is not found or error is encountered. */ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) { @@ -2305,8 +2262,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } dns = dns->next; - if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) != - WOLFSSL_SUCCESS) { + if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) <= 0) { WOLFSSL_MSG("Error pushing ASN1 object onto stack"); goto err; } @@ -2361,13 +2317,13 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, /* push GENERAL_NAME onto fullname stack */ if (wolfSSL_sk_GENERAL_NAME_push(dp->distpoint->name.fullname, - gn) != WOLFSSL_SUCCESS) { + gn) <= 0) { WOLFSSL_MSG("wolfSSL_sk_GENERAL_NAME_push error"); goto err; } /* push DIST_POINT onto stack */ - if (wolfSSL_sk_DIST_POINT_push(sk, dp) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_DIST_POINT_push(sk, dp) <= 0) { WOLFSSL_MSG("Error pushing DIST_POINT onto stack"); goto err; } @@ -2482,14 +2438,14 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, obj->grp = oidCertExtType; obj->obj = (byte*)(x509->certPolicies[i]); obj->objSz = MAX_CERTPOL_SZ; - if (wolfSSL_sk_ASN1_OBJECT_push(sk, obj) - != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_ASN1_OBJECT_push(sk, obj) <= 0) { WOLFSSL_MSG("Error pushing ASN1 object onto stack"); wolfSSL_ASN1_OBJECT_free(obj); wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); sk = NULL; } } + obj = wolfSSL_ASN1_OBJECT_new(); if (obj == NULL) { WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); @@ -2500,11 +2456,21 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, obj->grp = oidCertExtType; obj->obj = (byte*)(x509->certPolicies[i]); obj->objSz = MAX_CERTPOL_SZ; + + if (wolfSSL_sk_ASN1_OBJECT_push(sk, obj) <= 0) { + WOLFSSL_MSG("Error pushing ASN1 object onto stack"); + wolfSSL_ASN1_OBJECT_free(obj); + wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); + sk = NULL; + } + + obj = NULL; } else { WOLFSSL_MSG("No Cert Policy set"); } - #elif defined(WOLFSSL_SEP) + #endif /* WOLFSSL_CERT_EXT */ + #ifdef WOLFSSL_SEP if (x509->certPolicySet) { if (c != NULL) { *c = x509->certPolicyCrit; @@ -2520,8 +2486,6 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, else { WOLFSSL_MSG("No Cert Policy set"); } - #else - WOLFSSL_MSG("wolfSSL not built with WOLFSSL_SEP or WOLFSSL_CERT_EXT"); #endif break; } @@ -2560,6 +2524,44 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, case EXT_KEY_USAGE_OID: if (x509->extKeyUsageSrc != NULL) { + const byte* ekuSrc = x509->extKeyUsageSrc; + word32 i; + + sk = wolfSSL_sk_new_asn1_obj(); + if (sk == NULL) { + WOLFSSL_MSG("Issue creating stack"); + return NULL; + } + + for (i = 0; i < x509->extKeyUsageCount; i++) { + long ekuSrcLen = (long)(x509->extKeyUsageSz - + (word32)(ekuSrc - x509->extKeyUsageSrc)); + WOLFSSL_ASN1_OBJECT* ekuObj = wolfSSL_d2i_ASN1_OBJECT(NULL, + &ekuSrc, ekuSrcLen); + if (ekuObj == NULL) { + wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); + WOLFSSL_MSG("d2i obj error"); + return NULL; + } + ekuObj->type = EXT_KEY_USAGE_OID; + ekuObj->grp = oidCertExtType; + /* Push to end to maintain order */ + if (wolfSSL_sk_insert(sk, ekuObj, -1) <= 0) { + wolfSSL_ASN1_OBJECT_free(ekuObj); + wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); + WOLFSSL_MSG("d2i obj error"); + return NULL; + } + } + + if ((word32)(ekuSrc - x509->extKeyUsageSrc) + != x509->extKeyUsageSz || + i != x509->extKeyUsageCount) { + wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); + WOLFSSL_MSG("incorrect eku count or buffer not exhausted"); + return NULL; + } + if (c != NULL) { if (x509->extKeyUsageCount > 1) { *c = -2; @@ -2568,15 +2570,6 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, *c = x509->extKeyUsageCrit; } } - obj = wolfSSL_ASN1_OBJECT_new(); - if (obj == NULL) { - WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); - return NULL; - } - obj->type = EXT_KEY_USAGE_OID; - obj->grp = oidCertExtType; - obj->obj = x509->extKeyUsageSrc; - obj->objSz = x509->extKeyUsageSz; } else { WOLFSSL_MSG("No Extended Key Usage set"); @@ -2623,7 +2616,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } } if (obj) { - if (wolfSSL_sk_ASN1_OBJECT_push(sk, obj) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_ASN1_OBJECT_push(sk, obj) <= 0) { WOLFSSL_MSG("Error pushing ASN1_OBJECT object onto " "stack."); goto err; @@ -2796,7 +2789,7 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) WOLFSSL_MSG("wolfSSL_GENERAL_NAME_new error"); goto err_cleanup; } - if (wolfSSL_sk_GENERAL_NAME_push(gns, gn) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_GENERAL_NAME_push(gns, gn) <= 0) { WOLFSSL_MSG("wolfSSL_sk_GENERAL_NAME_push error"); wolfSSL_GENERAL_NAME_free(gn); goto err_cleanup; @@ -3550,7 +3543,7 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) } } - XMEMCPY(in, tmpBuf, totalLen); + XMEMCPY(in, tmpBuf, totalLen); /* cppcheck-suppress uninitvar */ in[totalLen] = '\0'; return in; @@ -3664,6 +3657,24 @@ WOLFSSL_X509* wolfSSL_X509_REQ_d2i(WOLFSSL_X509** x509, { return d2i_X509orX509REQ(x509, in, len, 1, NULL); } + +WOLFSSL_X509* wolfSSL_d2i_X509_REQ_INFO(WOLFSSL_X509** req, + const unsigned char** in, int len) +{ + WOLFSSL_X509* ret = NULL; + WOLFSSL_ENTER("wolfSSL_d2i_X509_REQ_INFO"); + + if (in == NULL) { + WOLFSSL_MSG("NULL input for wolfSSL_d2i_X509"); + return NULL; + } + + ret = wolfSSL_X509_REQ_d2i(req, *in, len); + if (ret != NULL) { + *in += ret->derCert->length; + } + return ret; +} #endif #endif /* KEEP_PEER_CERT || SESSION_CERTS || OPENSSL_EXTRA || @@ -3711,7 +3722,7 @@ char* wolfSSL_X509_get_next_altname(WOLFSSL_X509* cert) } ret = cert->altNamesNext->name; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME /* return the IP address as a string */ if (cert->altNamesNext->type == ASN_IP_TYPE) { ret = cert->altNamesNext->ipString; @@ -4459,39 +4470,9 @@ int wolfSSL_GENERAL_NAME_set0_othername(WOLFSSL_GENERAL_NAME* gen, int wolfSSL_sk_GENERAL_NAME_push(WOLFSSL_GENERAL_NAMES* sk, WOLFSSL_GENERAL_NAME* gn) { - WOLFSSL_STACK* node; WOLFSSL_ENTER("wolfSSL_sk_GENERAL_NAME_push"); - if (sk == NULL || gn == NULL) { - return WOLFSSL_FAILURE; - } - - /* no previous values in stack */ - if (sk->data.gn == NULL) { - sk->data.gn = gn; - sk->num += 1; - - return WOLFSSL_SUCCESS; - } - - /* stack already has value(s) create a new node and add more */ - node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, - DYNAMIC_TYPE_ASN1); - if (node == NULL) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; - } - XMEMSET(node, 0, sizeof(WOLFSSL_STACK)); - - /* push new obj onto head of stack */ - node->type = STACK_TYPE_GEN_NAME; - node->data.gn = sk->data.gn; - node->next = sk->next; - sk->next = node; - sk->data.gn = gn; - sk->num += 1; - - return WOLFSSL_SUCCESS; + return wolfSSL_sk_push(sk, gn); } #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ @@ -4531,7 +4512,7 @@ int wolfSSL_sk_GENERAL_NAME_num(WOLFSSL_STACK* sk) WOLFSSL_ENTER("wolfSSL_sk_GENERAL_NAME_num"); if (sk == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } return (int)sk->num; @@ -4702,7 +4683,7 @@ int wolfSSL_sk_DIST_POINT_num(WOLFSSL_STACK* sk) WOLFSSL_ENTER("wolfSSL_sk_DIST_POINT_num"); if (sk == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } return wolfSSL_sk_num(sk); @@ -5040,7 +5021,7 @@ int wolfSSL_GENERAL_NAME_print(WOLFSSL_BIO* out, WOLFSSL_GENERAL_NAME* gen) break; } - if (ret == WOLFSSL_FAILURE) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) return WOLFSSL_FAILURE; else return WOLFSSL_SUCCESS; @@ -5069,19 +5050,9 @@ int wolfSSL_sk_X509_EXTENSION_num(WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk) /* returns null on failure and pointer to internal value on success */ WOLFSSL_X509_EXTENSION* wolfSSL_sk_X509_EXTENSION_value( - WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int idx) + const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int idx) { - WOLFSSL_STACK* ret; - - if (sk == NULL) { - return NULL; - } - - ret = wolfSSL_sk_get_node(sk, idx); - if (ret != NULL) { - return ret->data.ext; - } - return NULL; + return (WOLFSSL_X509_EXTENSION*)wolfSSL_sk_value(sk, idx); } /* frees all of the nodes and the values in stack */ @@ -5092,6 +5063,11 @@ void wolfSSL_sk_X509_EXTENSION_pop_free( wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f); } +void wolfSSL_sk_X509_EXTENSION_free(WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk) +{ + wolfSSL_sk_pop_free(sk, NULL); +} + #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) @@ -5368,7 +5344,7 @@ int wolfSSL_X509_NAME_get_sz(WOLFSSL_X509_NAME* name) { WOLFSSL_ENTER("wolfSSL_X509_NAME_get_sz"); if (!name) - return -1; + return WOLFSSL_FATAL_ERROR; return name->sz; } @@ -5583,7 +5559,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) * size of this subset and its memory usage */ #endif /* OPENSSL_EXTRA_X509_SMALL || KEEP_PEER_CERT || SESSION_CERTS */ -#if defined(OPENSSL_ALL) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) /* * Converts a and b to DER and then does an XMEMCMP to check if they match. * Returns 0 when certificates match and WOLFSSL_FATAL_ERROR when they don't. @@ -5668,9 +5644,9 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) case NID_key_usage: crit = x509->keyUsageCrit; break; case NID_crl_distribution_points: crit= x509->CRLdistCrit; break; case NID_ext_key_usage: crit= x509->extKeyUsageCrit; break; - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) - case NID_certificate_policies: crit = x509->certPolicyCrit; break; - #endif /* WOLFSSL_SEP || WOLFSSL_QT */ + #ifdef WOLFSSL_SEP + case NID_certificate_policies: crit = x509->certPolicyCrit; break; + #endif /* WOLFSSL_SEP */ } } @@ -5778,6 +5754,37 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) return id; } + + const WOLFSSL_ASN1_STRING *wolfSSL_X509_get0_subject_key_id( + WOLFSSL_X509 *x509) + { + WOLFSSL_ASN1_STRING* ret = NULL; + + WOLFSSL_ENTER("wolfSSL_X509_get0_subject_key_id"); + + if (x509 != NULL && x509->subjKeyIdSet) { + if (x509->subjKeyIdStr == NULL) { + x509->subjKeyIdStr = wolfSSL_ASN1_STRING_new(); + if (x509->subjKeyIdStr != NULL) { + if (wolfSSL_ASN1_STRING_set(x509->subjKeyIdStr, + x509->subjKeyId, x509->subjKeyIdSz) == 1) { + ret = x509->subjKeyIdStr; + } + else { + wolfSSL_ASN1_STRING_free(x509->subjKeyIdStr); + x509->subjKeyIdStr = NULL; + } + } + } + else { + ret = x509->subjKeyIdStr; + } + } + + WOLFSSL_LEAVE("wolfSSL_X509_get0_subject_key_id", ret != NULL); + + return ret; + } #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ @@ -5830,81 +5837,304 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) #define MAX_WIDTH 80 #endif -static int X509PrintSubjAltName(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, - int indent) +#if defined(WOLFSSL_ACERT) +#define ACERT_NUM_DIR_TAGS 4 + +/* Convenience struct and function for printing the Holder sub fields + * of an X509 Attribute struct. */ +struct acert_dir_print_t { + const char * pfx; + const byte tag[3]; +}; + +static struct acert_dir_print_t acert_dir_print[ACERT_NUM_DIR_TAGS] = { - int ret = WOLFSSL_SUCCESS; - DNS_entry* entry; + { "C=", {0x55, 0x04, ASN_COUNTRY_NAME} }, + { "O=", {0x55, 0x04, ASN_ORG_NAME} }, + { "OU=", {0x55, 0x04, ASN_ORGUNIT_NAME} }, + { "CN=", {0x55, 0x04, ASN_COMMON_NAME} }, +}; - if (bio == NULL || x509 == NULL) { - ret = WOLFSSL_FAILURE; - } +/* Print an entry of ASN_DIR_TYPE into dst of length max_len. + * + * Returns total_len of str on success. + * Returns < 0 on failure. + * */ +static int X509PrintDirType(char * dst, int max_len, const DNS_entry * entry) +{ + word32 k = 0; + word32 i = 0; + const char * src = entry->name; + word32 src_len = (word32)XSTRLEN(src); + int total_len = 0; + int bytes_left = max_len; + int fld_len = 0; + int match_found = 0; + + XMEMSET(dst, 0, max_len); + + /* loop over printable DIR tags. */ + for (k = 0; k < ACERT_NUM_DIR_TAGS; ++k) { + const char * pfx = acert_dir_print[k].pfx; + const byte * tag = acert_dir_print[k].tag; + byte asn_tag; + + /* walk through entry looking for matches. */ + for (i = 0; i < src_len - 5; ++i) { + if (XMEMCMP(tag, &src[i], 3) == 0) { + if (bytes_left < 5) { + /* Not enough space left for name oid + tag + len. */ + break; + } - if (ret == WOLFSSL_SUCCESS && x509->subjAltNameSet && - x509->altNames != NULL) { - char scratch[MAX_WIDTH]; - int len; + if (match_found) { + /* append a {',', ' '} before doing anything else. */ + *dst++ = ','; + *dst++ = ' '; + total_len += 2; + bytes_left -= 2; + } - len = XSNPRINTF(scratch, MAX_WIDTH, "%*s", indent, ""); - if (len >= MAX_WIDTH) - ret = WOLFSSL_FAILURE; - if (ret == WOLFSSL_SUCCESS) { - if (wolfSSL_BIO_write(bio, scratch, (int)XSTRLEN(scratch)) <= 0) { - ret = WOLFSSL_FAILURE; - } - } - if (ret == WOLFSSL_SUCCESS) { - int nameCount = 0; + i += 3; - entry = x509->altNames; - while (entry != NULL) { - ++nameCount; - if (nameCount > 1) { - if (wolfSSL_BIO_write(bio, ", ", 2) <= 0) { - ret = WOLFSSL_FAILURE; - break; - } + /* Get the ASN Tag. */ + if (GetASNTag((const byte *)src, &i, &asn_tag, src_len) < 0) { + WOLFSSL_MSG("error: GetASNTag failed"); + break; } - if (entry->type == ASN_DNS_TYPE) { - len = XSNPRINTF(scratch, MAX_WIDTH, "DNS:%s", entry->name); - if (len >= MAX_WIDTH) { - ret = WOLFSSL_FAILURE; - break; - } + /* Check it is printable. */ + if ((asn_tag != ASN_PRINTABLE_STRING) && + (asn_tag != ASN_IA5_STRING) && + (asn_tag != ASN_UTF8STRING)) { + /* Don't know what this is but we can't print it. */ + WOLFSSL_MSG("error: asn tag not printable string"); + break; } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) - else if (entry->type == ASN_IP_TYPE) { - len = XSNPRINTF(scratch, MAX_WIDTH, "IP Address:%s", - entry->ipString); - if (len >= MAX_WIDTH) { - ret = WOLFSSL_FAILURE; - break; - } + + /* Now get the length of the printable string. */ + if (GetLength((const byte *)src, &i, &fld_len, src_len) < 0) { + break; } - #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ - else if (entry->type == ASN_RFC822_TYPE) { - len = XSNPRINTF(scratch, MAX_WIDTH, "email:%s", - entry->name); - if (len >= MAX_WIDTH) { - ret = WOLFSSL_FAILURE; - break; - } + + /* Make sure we have space to fit it. */ + if ((int) XSTRLEN(pfx) > bytes_left) { + /* Not enough space left. */ + break; } - else if (entry->type == ASN_DIR_TYPE) { - /* @TODO entry->name in ASN1 syntax */ - len = XSNPRINTF(scratch, MAX_WIDTH, - "DirName:"); - if (len >= MAX_WIDTH) { - ret = WOLFSSL_FAILURE; - break; - } + + /* Copy it in, decrement available space. */ + XSTRNCPY(dst, pfx, bytes_left); + dst += XSTRLEN(pfx); + total_len += XSTRLEN(pfx); + bytes_left -= XSTRLEN(pfx); + + if (fld_len > bytes_left) { + /* Not enough space left. */ + break; } - else if (entry->type == ASN_URI_TYPE) { - len = XSNPRINTF(scratch, MAX_WIDTH, "URI:%s", - entry->name); - if (len >= MAX_WIDTH) { - ret = WOLFSSL_FAILURE; + + XMEMCPY(dst, &src[i], fld_len); + i += fld_len; + dst += fld_len; + total_len += fld_len; + bytes_left -= fld_len; + + match_found = 1; + } + } + } + + return total_len; +} + +static int X509_ACERT_print_name_entry(WOLFSSL_BIO* bio, + const DNS_entry* entry, int indent) +{ + int ret = WOLFSSL_SUCCESS; + int nameCount = 0; + char scratch[MAX_WIDTH]; + int len; + + if (bio == NULL || entry == NULL) { + return WOLFSSL_FAILURE; + } + + len = XSNPRINTF(scratch, MAX_WIDTH, "%*s", indent, ""); + if (len >= MAX_WIDTH) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, scratch, (int)XSTRLEN(scratch)) <= 0) { + return WOLFSSL_FAILURE; + } + + while (entry != NULL) { + ++nameCount; + if (nameCount > 1) { + if (wolfSSL_BIO_write(bio, ", ", 2) <= 0) { + ret = WOLFSSL_FAILURE; + break; + } + } + + if (entry->type == ASN_DNS_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "DNS:%s", entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) + else if (entry->type == ASN_IP_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "IP Address:%s", + entry->ipString); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ + else if (entry->type == ASN_RFC822_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "email:%s", + entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + else if (entry->type == ASN_DIR_TYPE) { + len = X509PrintDirType(scratch, MAX_WIDTH, entry); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + else if (entry->type == ASN_URI_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "URI:%s", + entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #if defined(OPENSSL_ALL) + else if (entry->type == ASN_RID_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "Registered ID:%s", + entry->ridString); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #endif + else if (entry->type == ASN_OTHER_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, + "othername "); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + else { + WOLFSSL_MSG("Bad alt name type."); + ret = WOLFSSL_FAILURE; + break; + } + + if (wolfSSL_BIO_write(bio, scratch, (int)XSTRLEN(scratch)) + <= 0) { + ret = WOLFSSL_FAILURE; + break; + } + + entry = entry->next; + } + + if (ret == WOLFSSL_SUCCESS && wolfSSL_BIO_write(bio, "\n", 1) <= 0) { + ret = WOLFSSL_FAILURE; + } + + return ret; +} + +#endif /* if WOLFSSL_ACERT*/ + +static int X509PrintSubjAltName(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, + int indent) +{ + int ret = WOLFSSL_SUCCESS; + DNS_entry* entry; + + if (bio == NULL || x509 == NULL) { + ret = WOLFSSL_FAILURE; + } + + if (ret == WOLFSSL_SUCCESS && x509->subjAltNameSet && + x509->altNames != NULL) { + char scratch[MAX_WIDTH]; + int len; + + len = XSNPRINTF(scratch, MAX_WIDTH, "%*s", indent, ""); + if (len >= MAX_WIDTH) + ret = WOLFSSL_FAILURE; + if (ret == WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_write(bio, scratch, (int)XSTRLEN(scratch)) <= 0) { + ret = WOLFSSL_FAILURE; + } + } + if (ret == WOLFSSL_SUCCESS) { + int nameCount = 0; + + entry = x509->altNames; + while (entry != NULL) { + ++nameCount; + if (nameCount > 1) { + if (wolfSSL_BIO_write(bio, ", ", 2) <= 0) { + ret = WOLFSSL_FAILURE; + break; + } + } + + if (entry->type == ASN_DNS_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "DNS:%s", entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #ifdef WOLFSSL_IP_ALT_NAME + else if (entry->type == ASN_IP_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "IP Address:%s", + entry->ipString); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ + else if (entry->type == ASN_RFC822_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "email:%s", + entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + else if (entry->type == ASN_DIR_TYPE) { + /* @TODO entry->name in ASN1 syntax */ + len = XSNPRINTF(scratch, MAX_WIDTH, + "DirName:"); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; + break; + } + } + else if (entry->type == ASN_URI_TYPE) { + len = XSNPRINTF(scratch, MAX_WIDTH, "URI:%s", + entry->name); + if (len >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; break; } } @@ -6158,6 +6388,70 @@ static int X509PrintSerial(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) return WOLFSSL_SUCCESS; } +#ifndef NO_ASN_TIME +static int X509PrintValidity(WOLFSSL_BIO* bio, WOLFSSL_ASN1_TIME * notBefore, + WOLFSSL_ASN1_TIME * notAfter, int indent) +{ + char tmp[80]; + (void) indent; + + if (wolfSSL_BIO_write(bio, " Validity\n", + (int)XSTRLEN(" Validity\n")) <= 0) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, " Not Before: ", + (int)XSTRLEN(" Not Before: ")) <= 0) { + return WOLFSSL_FAILURE; + } + if (notBefore->length > 0) { + if (GetTimeString(notBefore->data, ASN_UTC_TIME, + tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { + if (GetTimeString(notBefore->data, ASN_GENERALIZED_TIME, + tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error getting not before date"); + return WOLFSSL_FAILURE; + } + } + } + else { + XSTRNCPY(tmp, "Not Set", sizeof(tmp)-1); + } + tmp[sizeof(tmp) - 1] = '\0'; /* make sure null terminated */ + if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, "\n Not After : ", + (int)XSTRLEN("\n Not After : ")) <= 0) { + return WOLFSSL_FAILURE; + } + if (notAfter->length > 0) { + if (GetTimeString(notAfter->data, ASN_UTC_TIME, + tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { + if (GetTimeString(notAfter->data, ASN_GENERALIZED_TIME, + tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Error getting not after date"); + return WOLFSSL_FAILURE; + } + } + } + else { + XSTRNCPY(tmp, "Not Set", sizeof(tmp)-1); + } + tmp[sizeof(tmp) - 1] = '\0'; /* make sure null terminated */ + if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, "\n\0", (int)XSTRLEN("\n\0")) <= 0) { + return WOLFSSL_FAILURE; + } + + return WOLFSSL_SUCCESS; +} +#endif /* ifndef NO_ASN_TIME */ + /* iterate through certificate extensions printing them out in human readable * form * return WOLFSSL_SUCCESS on success @@ -6200,7 +6494,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) return WOLFSSL_FAILURE; } - for (i = 0; (i < count) && (ret != WOLFSSL_FAILURE); i++) { + for (i = 0; (i < count) && (ret != WC_NO_ERR_TRACE(WOLFSSL_FAILURE)); i++) { WOLFSSL_X509_EXTENSION* ext; ext = wolfSSL_X509_get_ext(x509, i); @@ -6217,7 +6511,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) break; } if (wolfSSL_OBJ_obj2txt(buf, MAX_WIDTH, obj, 0) - == WOLFSSL_FAILURE) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { ret = WOLFSSL_FAILURE; break; @@ -6280,7 +6574,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) XMEMCPY(scratch + scratchLen, val, valLen); scratchLen += valLen; } - if (ret == WOLFSSL_FAILURE) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) break; if (wolfSSL_BIO_write(bio, scratch, scratchLen) <= 0) { @@ -6329,7 +6623,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) XMEMCPY(scratch + scratchLen, val, valLen); scratchLen += valLen; } - if (ret == WOLFSSL_FAILURE) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) break; if (wolfSSL_BIO_write(bio, scratch, scratchLen) <= 0) { @@ -6386,9 +6680,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) } } - if (buf != NULL) { - XFREE(buf, x509->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(buf, x509->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -6429,7 +6721,7 @@ static int X509PrintSignature_ex(WOLFSSL_BIO* bio, byte* sig, } if (ret == WOLFSSL_SUCCESS) { if (wolfSSL_OBJ_obj2txt(scratch, MAX_WIDTH, obj, 0) - == WOLFSSL_FAILURE) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { ret = WOLFSSL_FAILURE; } @@ -6568,9 +6860,7 @@ static int X509PrintSignature(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, return WOLFSSL_FAILURE; } - if (sig != NULL) { - XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); } @@ -6726,7 +7016,7 @@ static int X509PrintReqAttributes(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, const byte* data; if (wolfSSL_OBJ_obj2txt(lName, lNameSz, attr->object, 0) - == WOLFSSL_FAILURE) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { return WOLFSSL_FAILURE; } @@ -6820,142 +7110,289 @@ int wolfSSL_X509_REQ_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509) return WOLFSSL_SUCCESS; } -#endif /* WOLFSSL_CERT_REQ */ +#endif /* WOLFSSL_CERT_REQ */ + + +/* Writes the human readable form of x509 to bio. + * + * bio WOLFSSL_BIO to write to. + * x509 Certificate to write. + * + * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_X509_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, + unsigned long nmflags, unsigned long cflag) +{ + char issuType[] = "Issuer:"; + char subjType[] = "Subject:"; + + WOLFSSL_ENTER("wolfSSL_X509_print_ex"); + + /* flags currently not supported */ + (void)nmflags; + (void)cflag; + + if (bio == NULL || x509 == NULL) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, "Certificate:\n", + (int)XSTRLEN("Certificate:\n")) <= 0) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, " Data:\n", + (int)XSTRLEN(" Data:\n")) <= 0) { + return WOLFSSL_FAILURE; + } + + /* print version of cert */ + if (X509PrintVersion(bio, wolfSSL_X509_version(x509), 8) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* print serial number out */ + if (X509PrintSerial(bio, x509, 8) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* print out signature algo*/ + if (X509PrintSignature(bio, x509, 1, 8) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* print issuer */ + if (X509PrintName(bio, wolfSSL_X509_get_issuer_name(x509), issuType, 8) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + #ifndef NO_ASN_TIME + /* print validity */ + if (X509PrintValidity(bio, &x509->notBefore, &x509->notAfter, 8) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + #endif /* NO_ASN_TIME */ + + /* print subject */ + if (X509PrintName(bio, wolfSSL_X509_get_subject_name(x509), subjType, 8) + != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* get and print public key */ + if (X509PrintPubKey(bio, x509, 8) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* print out extensions */ + if (X509PrintExtensions(bio, x509, 8) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* print out signature */ + if (X509PrintSignature(bio, x509, 0, 4) != WOLFSSL_SUCCESS) { + return WOLFSSL_FAILURE; + } + + /* done with print out */ + if (wolfSSL_BIO_write(bio, "\n\0", (int)XSTRLEN("\n\0")) <= 0) { + return WOLFSSL_FAILURE; + } + + return WOLFSSL_SUCCESS; +} +int wolfSSL_X509_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509) +{ + return wolfSSL_X509_print_ex(bio, x509, 0, 0); +} + +#if defined(WOLFSSL_ACERT) +/* Retrieve sig NID from an ACERT. + * + * returns NID on success + * returns 0 on failure + */ +int wolfSSL_X509_ACERT_get_signature_nid(const WOLFSSL_X509_ACERT *x509) +{ + if (x509 == NULL) { + return 0; + } + + return oid2nid((word32)x509->sigOID, oidSigType); +} + +static int X509AcertPrintSignature(WOLFSSL_BIO* bio, WOLFSSL_X509_ACERT* x509, + int algOnly, int indent) +{ + int sigSz = 0; + if (wolfSSL_X509_ACERT_get_signature(x509, NULL, &sigSz) <= 0) { + return WOLFSSL_FAILURE; + } + + if (sigSz > 0) { + unsigned char* sig; + int sigNid; + + sigNid = wolfSSL_X509_ACERT_get_signature_nid(x509); + if (sigNid <= 0) { + return WOLFSSL_FAILURE; + } + + sig = (unsigned char*)XMALLOC(sigSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (sig == NULL) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_X509_ACERT_get_signature(x509, sig, &sigSz) <= 0) { + XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; + } + + if (X509PrintSignature_ex(bio, sig, sigSz, sigNid, algOnly, indent) + != WOLFSSL_SUCCESS) { + XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_FAILURE; + } + + if (sig != NULL) { + XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + + } + + return WOLFSSL_SUCCESS; +} + +static int X509AcertPrintSerial(WOLFSSL_BIO* bio, WOLFSSL_X509_ACERT* x509, + int indent) +{ + unsigned char serial[32]; + int sz = sizeof(serial); + + XMEMSET(serial, 0, sz); + if (wolfSSL_X509_ACERT_get_serial_number(x509, serial, &sz) + == WOLFSSL_SUCCESS) { + X509PrintSerial_ex(bio, serial, sz, 1, indent); + } + return WOLFSSL_SUCCESS; +} - -/* Writes the human readable form of x509 to bio. - * - * bio WOLFSSL_BIO to write to. - * x509 Certificate to write. - * - * returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure - */ -int wolfSSL_X509_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, - unsigned long nmflags, unsigned long cflag) +int wolfSSL_X509_ACERT_print(WOLFSSL_BIO* bio, WOLFSSL_X509_ACERT* x509) { - char issuType[] = "Issuer:"; - char subjType[] = "Subject:"; - - WOLFSSL_ENTER("wolfSSL_X509_print_ex"); - - /* flags currently not supported */ - (void)nmflags; - (void)cflag; + const char * hdr = "Attribute Certificate:\n"; + const char * data_hdr = " Data:\n"; + const char * holder_hdr = " Holder:\n"; + const char * holder_issuer_hdr = " Issuer:"; + const char * holder_name_hdr = " Name:"; + const char * attcert_issuer_hdr = " Issuer:"; if (bio == NULL || x509 == NULL) { return WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, "Certificate:\n", - (int)XSTRLEN("Certificate:\n")) <= 0) { - return WOLFSSL_FAILURE; + /* print acert header */ + if (wolfSSL_BIO_write(bio, hdr, (int)XSTRLEN(hdr)) <= 0) { + return WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, " Data:\n", - (int)XSTRLEN(" Data:\n")) <= 0) { - return WOLFSSL_FAILURE; + /* print data header */ + if (wolfSSL_BIO_write(bio, data_hdr, (int)XSTRLEN(data_hdr)) <= 0) { + return WOLFSSL_FAILURE; } /* print version of cert */ - if (X509PrintVersion(bio, wolfSSL_X509_version(x509), 8) + if (X509PrintVersion(bio, wolfSSL_X509_ACERT_version(x509), 8) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } /* print serial number out */ - if (X509PrintSerial(bio, x509, 8) != WOLFSSL_SUCCESS) { + if (X509AcertPrintSerial(bio, x509, 8) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - /* print out signature algo*/ - if (X509PrintSignature(bio, x509, 1, 8) != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; - } - - /* print issuer */ - if (X509PrintName(bio, wolfSSL_X509_get_issuer_name(x509), issuType, 8) - != WOLFSSL_SUCCESS) { + /* print holder field */ + if (wolfSSL_BIO_write(bio, holder_hdr, (int)XSTRLEN(holder_hdr)) <= 0) { return WOLFSSL_FAILURE; } -#ifndef NO_ASN_TIME - /* print validity */ - { - char tmp[80]; - - if (wolfSSL_BIO_write(bio, " Validity\n", - (int)XSTRLEN(" Validity\n")) <= 0) { + if (x509->holderEntityName != NULL) { + /* print issuer header */ + if (wolfSSL_BIO_write(bio, holder_name_hdr, + (int)XSTRLEN(holder_name_hdr)) <= 0) { return WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, " Not Before: ", - (int)XSTRLEN(" Not Before: ")) <= 0) { + if (X509_ACERT_print_name_entry(bio, x509->holderEntityName, 1) + != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - if (x509->notBefore.length > 0) { - if (GetTimeString(x509->notBefore.data, ASN_UTC_TIME, - tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { - if (GetTimeString(x509->notBefore.data, ASN_GENERALIZED_TIME, - tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error getting not before date"); - return WOLFSSL_FAILURE; - } - } - } - else { - XSTRNCPY(tmp, "Not Set", sizeof(tmp)-1); - } - tmp[sizeof(tmp) - 1] = '\0'; /* make sure null terminated */ - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + } + + if (x509->holderIssuerName != NULL) { + /* print issuer header */ + if (wolfSSL_BIO_write(bio, holder_issuer_hdr, + (int)XSTRLEN(holder_issuer_hdr)) <= 0) { return WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, "\n Not After : ", - (int)XSTRLEN("\n Not After : ")) <= 0) { + if (X509_ACERT_print_name_entry(bio, x509->holderIssuerName, 1) + != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - if (x509->notAfter.length > 0) { - if (GetTimeString(x509->notAfter.data, ASN_UTC_TIME, - tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { - if (GetTimeString(x509->notAfter.data, ASN_GENERALIZED_TIME, - tmp, sizeof(tmp)) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Error getting not after date"); - return WOLFSSL_FAILURE; - } - } - } - else { - XSTRNCPY(tmp, "Not Set", sizeof(tmp)-1); - } - tmp[sizeof(tmp) - 1] = '\0'; /* make sure null terminated */ - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + } + + if (x509->holderSerialSz > 0) { + X509PrintSerial_ex(bio, x509->holderSerial, x509->holderSerialSz, + 1, 12); + } + + /* print issuer header */ + if (wolfSSL_BIO_write(bio, attcert_issuer_hdr, + (int)XSTRLEN(attcert_issuer_hdr)) <= 0) { + return WOLFSSL_FAILURE; + } + + if (x509->AttCertIssuerName != NULL) { + if (X509_ACERT_print_name_entry(bio, x509->AttCertIssuerName, 1) + != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - - if (wolfSSL_BIO_write(bio, "\n\0", (int)XSTRLEN("\n\0")) <= 0) { + } + else { + const char * msg = " Issuer type not supported.\n"; + if (wolfSSL_BIO_write(bio, msg, (int)XSTRLEN(msg)) <= 0) { return WOLFSSL_FAILURE; } } - #endif - /* print subject */ - if (X509PrintName(bio, wolfSSL_X509_get_subject_name(x509), subjType, 8) - != WOLFSSL_SUCCESS) { + #ifndef NO_ASN_TIME + /* print validity */ + if (X509PrintValidity(bio, &x509->notBefore, &x509->notAfter, 8) + != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } + #endif /* NO_ASN_TIME */ - /* get and print public key */ - if (X509PrintPubKey(bio, x509, 8) != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; - } + /* print raw attributes */ + if (x509->rawAttr && x509->rawAttrLen > 0) { + char attr_hdr[128]; /* buffer for XSNPRINTF */ - /* print out extensions */ - if (X509PrintExtensions(bio, x509, 8) != WOLFSSL_SUCCESS) { - return WOLFSSL_FAILURE; + if (XSNPRINTF(attr_hdr, 128, "%*s%s: %d bytes\n", 8, "", + "Attributes", x509->rawAttrLen) >= 128) { + return WOLFSSL_FAILURE; + } + + if (wolfSSL_BIO_write(bio, attr_hdr, (int)XSTRLEN(attr_hdr)) <= 0) { + return WOLFSSL_FAILURE; + } } - /* print out signature */ - if (X509PrintSignature(bio, x509, 0, 4) != WOLFSSL_SUCCESS) { + /* print out sig algo and signature */ + if (X509AcertPrintSignature(bio, x509, 0, 8) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -6966,10 +7403,7 @@ int wolfSSL_X509_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, return WOLFSSL_SUCCESS; } -int wolfSSL_X509_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509) -{ - return wolfSSL_X509_print_ex(bio, x509, 0, 0); -} +#endif /* WOLFSSL_ACERT */ #ifndef NO_FILESYSTEM int wolfSSL_X509_print_fp(XFILE fp, WOLFSSL_X509 *x509) @@ -7040,7 +7474,6 @@ int wolfSSL_X509_signature_print(WOLFSSL_BIO *bp, for (i = 0; i < length; ++i) { char hex_digits[4]; -#ifdef XSNPRINTF if (XSNPRINTF(hex_digits, sizeof(hex_digits), "%c%02X", i>0 ? ':' : ' ', (unsigned int)sigalg->algorithm->obj[idx+i]) >= (int)sizeof(hex_digits)) @@ -7048,10 +7481,6 @@ int wolfSSL_X509_signature_print(WOLFSSL_BIO *bp, WOLFSSL_MSG("buffer overrun"); return WOLFSSL_FAILURE; } -#else - XSPRINTF(hex_digits, "%c%02X", i>0 ? ':' : ' ', - (unsigned int)sigalg->algorithm->obj[idx+i]); -#endif if (wolfSSL_BIO_puts(bp, hex_digits) <= 0) return WOLFSSL_FAILURE; } @@ -7101,13 +7530,12 @@ int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, { #if !defined(NO_FILESYSTEM) && \ (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); XFILE fp; long sz; byte* pem = NULL; byte* curr = NULL; byte* prev = NULL; - WOLFSSL_X509* x509; const char* header = NULL; const char* footer = NULL; @@ -7168,12 +7596,8 @@ int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, } else if (wc_PemGetHeaderFooter(CERT_TYPE, &header, &footer) == 0 && XSTRNSTR((char*)curr, header, (unsigned int)sz) != NULL) { - x509 = wolfSSL_X509_load_certificate_buffer(curr, (int)sz, - WOLFSSL_FILETYPE_PEM); - if (x509 == NULL) - goto end; - ret = wolfSSL_X509_STORE_add_cert(lookup->store, x509); - wolfSSL_X509_free(x509); + ret = X509StoreLoadCertBuffer(lookup->store, curr, + (word32)sz, WOLFSSL_FILETYPE_PEM); if (ret != WOLFSSL_SUCCESS) goto end; curr = (byte*)XSTRNSTR((char*)curr, footer, (unsigned int)sz); @@ -7191,8 +7615,7 @@ int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, while (ret == WOLFSSL_SUCCESS); end: - if (pem != NULL) - XFREE(pem, 0, DYNAMIC_TYPE_PEM); + XFREE(pem, 0, DYNAMIC_TYPE_PEM); XFCLOSE(fp); return WS_RETURN_CODE(ret, (int)WOLFSSL_FAILURE); #else @@ -7310,8 +7733,7 @@ static int x509AddCertDir(WOLFSSL_BY_DIR *ctx, const char *argc, long argl) XSTRNCPY(entry->dir_name, buf, pathLen); entry->dir_name[pathLen] = '\0'; - if (wolfSSL_sk_BY_DIR_entry_push(ctx->dir_entry, entry) - != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_BY_DIR_entry_push(ctx->dir_entry, entry) <= 0) { wolfSSL_BY_DIR_entry_free(entry); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, 0, DYNAMIC_TYPE_OPENSSL); @@ -7357,7 +7779,7 @@ static int x509AddCertDir(WOLFSSL_BY_DIR *ctx, const char *argc, long argl) int wolfSSL_X509_LOOKUP_ctrl(WOLFSSL_X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret) { - int lret = WOLFSSL_FAILURE; + int lret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_X509_LOOKUP_ctrl"); #if !defined(NO_FILESYSTEM) @@ -7416,7 +7838,7 @@ static int wolfssl_x509_make_der(WOLFSSL_X509* x509, int req, */ static int loadX509orX509REQFromBio(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int req) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); /* Get large buffer to hold cert der */ int derSz = X509_BUFFER_SZ; #ifdef WOLFSSL_SMALL_STACK @@ -7526,20 +7948,12 @@ int wolfSSL_i2d_X509(WOLFSSL_X509* x509, unsigned char** out) int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { int ret = 0; WOLFSSL_X509 *x = NULL; - byte certOwnsAltNames = 0; byte certIsCSR = 0; if ((cert == NULL) || (der == NULL) || (derSz <= 0)) { return BAD_FUNC_ARG; } - /* The call to CopyDecodedToX509() transfers ownership of the altNames in - * the DecodedCert to the temporary X509 object, causing the list to be - * freed in wolfSSL_X509_free(). As this is an unintended side-effect, we - * have to save the ownerFlag here and transfer ownership back to the - * DecodedCert prior to freeing the X509 object. */ - certOwnsAltNames = cert->weOwnAltNames; - #ifdef WOLFSSL_CERT_REQ certIsCSR = cert->isCSR; #endif @@ -7552,9 +7966,6 @@ int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { ret = CopyDecodedToX509(x, cert); } - /* CopyDecodedToX509() clears cert->weOwnAltNames. Restore it. */ - cert->weOwnAltNames = certOwnsAltNames; - if (ret == 0) { /* Remove the altsigval extension. */ XFREE(x->altSigValDer, x->heap, DYNAMIC_TYPE_X509_EXT); @@ -7570,9 +7981,6 @@ int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { } if (x != NULL) { - /* Safe the altNames list from being freed unitentionally. */ - x->altNames = NULL; - wolfSSL_X509_free(x); } @@ -7807,8 +8215,7 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) } #endif _exit: - if (fileBuffer != NULL) - XFREE(fileBuffer, NULL, DYNAMIC_TYPE_FILE); + XFREE(fileBuffer, NULL, DYNAMIC_TYPE_FILE); return newx509; } @@ -7983,9 +8390,7 @@ WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_bio(WOLFSSL_BIO *bp, } } - if (der != NULL) { - XFREE(der, 0, DYNAMIC_TYPE_DER); - } + XFREE(der, 0, DYNAMIC_TYPE_DER); return crl; } @@ -8007,7 +8412,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, const char *file, int type) { #ifndef NO_BIO - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int count = 0; WOLFSSL_BIO *bio = NULL; WOLFSSL_X509_CRL *crl = NULL; @@ -8041,7 +8446,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, } ret = wolfSSL_X509_STORE_add_crl(ctx->store, crl); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Adding crl failed"); break; } @@ -8058,7 +8463,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, WOLFSSL_MSG("Load crl failed"); } else { ret = wolfSSL_X509_STORE_add_crl(ctx->store, crl); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Adding crl failed"); } else { ret = 1;/* handled a file */ @@ -8074,7 +8479,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, WOLFSSL_LEAVE("wolfSSL_X509_load_crl_file", ret); return ret; #else - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int count = 0; XFILE fp; WOLFSSL_X509_CRL *crl = NULL; @@ -8098,7 +8503,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, } ret = wolfSSL_X509_STORE_add_crl(ctx->store, crl); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Adding crl failed"); break; } @@ -8117,7 +8522,7 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, } else { ret = wolfSSL_X509_STORE_add_crl(ctx->store, crl); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Adding crl failed"); } else { @@ -8346,9 +8751,7 @@ static int X509CRLPrintSignature(WOLFSSL_BIO* bio, WOLFSSL_X509_CRL* crl, return WOLFSSL_FAILURE; } - if (sig != NULL) { - XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(sig, NULL, DYNAMIC_TYPE_TMP_BUFFER); } @@ -8724,8 +9127,7 @@ WOLFSSL_X509_VERIFY_PARAM* wolfSSL_X509_VERIFY_PARAM_new(void) void wolfSSL_X509_VERIFY_PARAM_free(WOLFSSL_X509_VERIFY_PARAM *param) { - if (param != NULL) - XFREE(param, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(param, NULL, DYNAMIC_TYPE_OPENSSL); } @@ -8733,7 +9135,7 @@ void wolfSSL_X509_VERIFY_PARAM_free(WOLFSSL_X509_VERIFY_PARAM *param) int wolfSSL_X509_VERIFY_PARAM_set_flags(WOLFSSL_X509_VERIFY_PARAM *param, unsigned long flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (param != NULL) { param->flags |= flags; @@ -8759,7 +9161,7 @@ int wolfSSL_X509_VERIFY_PARAM_get_flags(WOLFSSL_X509_VERIFY_PARAM *param) int wolfSSL_X509_VERIFY_PARAM_clear_flags(WOLFSSL_X509_VERIFY_PARAM *param, unsigned long flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (param != NULL) { param->flags &= ~flags; @@ -8769,6 +9171,41 @@ int wolfSSL_X509_VERIFY_PARAM_clear_flags(WOLFSSL_X509_VERIFY_PARAM *param, return ret; } +/* note WOLFSSL_X509_VERIFY_PARAM does not record purpose, trust, depth, or + * auth_level. + */ +static const WOLFSSL_X509_VERIFY_PARAM x509_verify_param_builtins[] = { + { + "ssl_client", /* name */ + 0, /* check_time */ + 0, /* inherit_flags */ + 0, /* flags */ + "", /* hostname */ + 0, /* hostFlags */ + "" /* ipasc */ + }, + { + "ssl_server", /* name */ + 0, /* check_time */ + 0, /* inherit_flags */ + 0, /* flags */ + "", /* hostname */ + 0, /* hostFlags */ + "" /* ipasc */ + } +}; + +const WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_VERIFY_PARAM_lookup(const char *name) +{ + const WOLFSSL_X509_VERIFY_PARAM *param = &x509_verify_param_builtins[0], + *param_end = &x509_verify_param_builtins[XELEM_CNT(x509_verify_param_builtins)]; + while (param < param_end) { + if (XSTRCMP(name, param->name) == 0) + return param; + ++param; + } + return NULL; +} /* inherits properties of param "to" to param "from" * @@ -8779,10 +9216,10 @@ int wolfSSL_X509_VERIFY_PARAM_clear_flags(WOLFSSL_X509_VERIFY_PARAM *param, * WOLFSSL_VPARAM_LOCKED don't copy any values * WOLFSSL_VPARAM_ONCE the current inherit_flags is zerroed */ -static int wolfSSL_X509_VERIFY_PARAM_inherit(WOLFSSL_X509_VERIFY_PARAM *to, +int wolfSSL_X509_VERIFY_PARAM_inherit(WOLFSSL_X509_VERIFY_PARAM *to, const WOLFSSL_X509_VERIFY_PARAM *from) { - int ret = WOLFSSL_FAILURE; + int ret = WOLFSSL_SUCCESS; int isOverWrite = 0; int isDefault = 0; unsigned int flags; @@ -8884,7 +9321,7 @@ int wolfSSL_X509_VERIFY_PARAM_set1_host(WOLFSSL_X509_VERIFY_PARAM* pParam, int wolfSSL_X509_VERIFY_PARAM_set1(WOLFSSL_X509_VERIFY_PARAM *to, const WOLFSSL_X509_VERIFY_PARAM *from) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); unsigned int _inherit_flags; if (!to) { @@ -8926,7 +9363,7 @@ void wolfSSL_X509_VERIFY_PARAM_set_hostflags(WOLFSSL_X509_VERIFY_PARAM* param, int wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(WOLFSSL_X509_VERIFY_PARAM *param, const char *ipasc) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (param != NULL) { if (ipasc == NULL) { @@ -8951,7 +9388,7 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(WOLFSSL_X509_VERIFY_PARAM *param, int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, const unsigned char* ip, size_t iplen) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifndef NO_FILESYSTEM char* buf = NULL; char* p = NULL; @@ -8970,14 +9407,13 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, if (iplen == 4) { /* ipv4 www.xxx.yyy.zzz max 15 length + Null termination */ buf = (char*)XMALLOC(16, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (!buf) { WOLFSSL_MSG("failed malloc"); return ret; } - XSPRINTF(buf, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); - buf[15] = '\0'; + (void)XSNPRINTF(buf, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + buf[15] = '\0'; /* null terminate */ } else if (iplen == 16) { /* ipv6 normal address scheme @@ -9006,47 +9442,46 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, * to re-construct IP address in ascii. */ buf = (char*)XMALLOC(max_ipv6_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (!buf) { WOLFSSL_MSG("failed malloc"); return ret; } p = buf; for (i = 0; i < 16; i += 2) { - val = (((word32)(ip[i]<<8)) | (ip[i+1])) & 0xFFFF; - if (val == 0){ - if (!write_zero) { + val = (((word32)(ip[i]<<8)) | (ip[i+1])) & 0xFFFF; + if (val == 0){ + if (!write_zero) { *p = ':'; - } - p++; - *p = '\0'; - write_zero = 1; - } - else { - if (i != 0) - *p++ = ':'; - XSPRINTF(p, "%x", val); - } - /* sanity check */ - if (XSTRLEN(buf) > max_ipv6_len) { - WOLFSSL_MSG("The target ip address exceeds buffer length(40)"); - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - buf = NULL; - break; - } - /* move the pointer to the last */ - /* XSTRLEN includes NULL because of XSPRINTF use */ - p = buf + (XSTRLEN(buf)); + } + p++; + *p = '\0'; + write_zero = 1; + } + else { + if (i != 0) { + *p++ = ':'; + } + (void)XSNPRINTF(p, max_ipv6_len - (size_t)(p - buf), "%x", val); + } + /* sanity check */ + if (XSTRLEN(buf) > max_ipv6_len) { + WOLFSSL_MSG("The target ip address exceeds buffer length(40)"); + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + buf = NULL; + break; + } + /* move the pointer to the last */ + /* XSTRLEN includes NULL because of XSPRINTF use */ + p = buf + (XSTRLEN(buf)); } /* termination */ - if(i == 16 && buf) { + if (i == 16 && buf) { p--; if ((*p) == ':') { - /* when the last character is :, the following segments are zero - * Therefore, adding : and null termination - */ - p++; - *p++ = ':'; + /* when the last character is :, the following segments are zero + * Therefore, adding : and null termination */ + p++; + *p++ = ':'; *p = '\0'; } } @@ -9057,7 +9492,7 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, } if (buf) { - /* set address to ip asc */ + /* set address to ip asc */ ret = wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(param, buf); XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); } @@ -9084,12 +9519,12 @@ int wolfSSL_X509_cmp_current_time(const WOLFSSL_ASN1_TIME* asnTime) return wolfSSL_X509_cmp_time(asnTime, NULL); } -/* return -1 if asnTime is earlier than or equal to cmpTime, and 1 otherwise +/* return WOLFSSL_FATAL_ERROR if asnTime is earlier than or equal to cmpTime, and 1 otherwise * return 0 on error */ int wolfSSL_X509_cmp_time(const WOLFSSL_ASN1_TIME* asnTime, time_t* cmpTime) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); time_t tmpTime, *pTime = &tmpTime; struct tm ts, *tmpTs, *ct; #if defined(NEED_TMP_TIME) @@ -9336,6 +9771,110 @@ int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, WOLFSSL_ASN1_OBJECT *aobj return WOLFSSL_SUCCESS; } +/** + * Serialize object to DER encoding + * + * @param alg Object to serialize + * @param pp Output + * @return Length on success + * Negative number on failure + */ +int wolfSSL_i2d_X509_ALGOR(const WOLFSSL_X509_ALGOR* alg, + unsigned char** pp) +{ + int len; + word32 oid = 0; + word32 idx = 0; + unsigned char* buf = NULL; + + if (alg == NULL || alg->algorithm == 0) { + WOLFSSL_MSG("alg is NULL or algorithm not set"); + return WOLFSSL_FATAL_ERROR; + } + + if (GetObjectId(alg->algorithm->obj, &idx, &oid, + (word32)alg->algorithm->grp, alg->algorithm->objSz) < 0) { + WOLFSSL_MSG("Issue getting OID of object"); + return WOLFSSL_FATAL_ERROR; + } + + len = (int)SetAlgoID((int)oid, NULL, alg->algorithm->grp, 0); + if (len == 0) { + WOLFSSL_MSG("SetAlgoID error"); + return WOLFSSL_FATAL_ERROR; + } + + if (pp != NULL) { + if (*pp != NULL) + buf = *pp; + else { + buf = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); + if (buf == NULL) + return WOLFSSL_FATAL_ERROR; + } + + len = (int)SetAlgoID((int)oid, buf, alg->algorithm->grp, 0); + if (len == 0) { + WOLFSSL_MSG("SetAlgoID error"); + if (*pp == NULL) + XFREE(buf, NULL, DYNAMIC_TYPE_ASN1); + return WOLFSSL_FATAL_ERROR; + } + + if (*pp != NULL) + *pp += len; + else + *pp = buf; + } + + return len; +} + +WOLFSSL_X509_ALGOR* wolfSSL_d2i_X509_ALGOR(WOLFSSL_X509_ALGOR** out, + const byte** src, long len) +{ + WOLFSSL_X509_ALGOR* ret = NULL; + word32 idx = 0; + word32 oid = 0; + int grp; + + WOLFSSL_ENTER("wolfSSL_d2i_X509_ALGOR"); + + if (src == NULL || *src == NULL || len == 0) + return NULL; + + if (GetAlgoId(*src, &idx, &oid, oidIgnoreType, (word32)len) != 0) + return NULL; + + /* Try to guess the type */ + for (grp = 0; grp < oidIgnoreType; grp++) { + word32 oidSz; + if (OidFromId(oid, (word32)grp, &oidSz) != NULL) + break; + } + if (grp == oidIgnoreType) + return NULL; + + ret = wolfSSL_X509_ALGOR_new(); + if (ret == NULL) + return NULL; + + ret->algorithm = wolfSSL_OBJ_nid2obj(oid2nid(oid, grp)); + if (ret->algorithm == NULL) { + wolfSSL_X509_ALGOR_free(ret); + return NULL; + } + *src += idx; + + if (out != NULL) { + if (*out != NULL) + wolfSSL_X509_ALGOR_free(*out); + *out = ret; + } + + return ret; +} + /** * Allocate a new WOLFSSL_X509_PUBKEY object. * @@ -9557,6 +10096,17 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) #endif /* OPENSSL_ALL || WOLFSSL_APACHE_HTTPD || WOLFSSL_HAPROXY || WOLFSSL_WPAS */ +#if !defined(NO_CERTS) && !defined(NO_ASN) && !defined(NO_PWDBASED) + +int wolfSSL_i2d_X509_PUBKEY(WOLFSSL_X509_PUBKEY* x509_PubKey, unsigned char** der) +{ + if (x509_PubKey == NULL) + return WOLFSSL_FATAL_ERROR; + return wolfSSL_i2d_PublicKey(x509_PubKey->pkey, der); +} + +#endif /* !NO_CERTS && !NO_ASN && !NO_PWDBASED */ + #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) @@ -9731,7 +10281,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( static int CopyX509NameToCert(WOLFSSL_X509_NAME* n, byte* out) { unsigned char* der = NULL; - int length = BAD_FUNC_ARG, ret; + int length = WC_NO_ERR_TRACE(BAD_FUNC_ARG), ret; word32 idx = 0; ret = wolfSSL_i2d_X509_NAME(n, &der); @@ -9749,8 +10299,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( XMEMCPY(out, der + idx, length); } - if (der != NULL) - XFREE(der, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(der, NULL, DYNAMIC_TYPE_OPENSSL); return length; } @@ -9799,7 +10348,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( #if defined(OPENSSL_ALL) idx = wolfSSL_X509_REQ_get_attr_by_NID(req, NID_pkcs9_unstructuredName, -1); - if (idx != WOLFSSL_FATAL_ERROR) { + if (idx != WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { WOLFSSL_X509_ATTRIBUTE *attr; attr = wolfSSL_X509_REQ_get_attr(req, idx); if (attr != NULL) { @@ -10083,7 +10632,9 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( int sigType = WOLFSSL_FAILURE; /* Convert key type and hash algorithm to a signature algorithm */ - if (wolfSSL_EVP_get_hashinfo(md, &hashType, NULL) == WOLFSSL_FAILURE) { + if (wolfSSL_EVP_get_hashinfo(md, &hashType, NULL) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { return WOLFSSL_FAILURE; } @@ -10178,7 +10729,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( static int wolfssl_x509_make_der(WOLFSSL_X509* x509, int req, unsigned char* der, int* derSz, int includeSig) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int totalLen; Cert* cert = NULL; void* key = NULL; @@ -10622,7 +11173,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( WOLFSSL_ENTER("wolfSSL_X509_resign_cert"); sigType = wolfSSL_sigTypeFromPKEY(md, pkey); - if (sigType == WOLFSSL_FAILURE) { + if (sigType == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Error getting signature type from pkey"); return WOLFSSL_FATAL_ERROR; } @@ -10752,8 +11303,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } out: - if (der) - XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -10809,7 +11359,7 @@ static int ConvertNIDToWolfSSL(int nid) case NID_favouriteDrink: return ASN_FAVOURITE_DRINK; default: WOLFSSL_MSG("Attribute NID not found"); - return -1; + return WOLFSSL_FATAL_ERROR; } } #endif /* OPENSSL_ALL || OPENSSL_EXTRA || @@ -11113,7 +11663,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) InitDecodedCert(cert, *in, (word32)length, NULL); /* Parse the X509 subject name */ - if (GetName(cert, SUBJECT, (int)length) != 0) { + if (GetName(cert, ASN_SUBJECT, (int)length) != 0) { WOLFSSL_MSG("WOLFSSL_X509_NAME parse error"); goto cleanup; } @@ -11276,6 +11826,63 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } +#if defined(WOLFSSL_ACERT) + WOLFSSL_X509_ACERT *wolfSSL_PEM_read_bio_X509_ACERT(WOLFSSL_BIO *bp, + WOLFSSL_X509_ACERT **x, + wc_pem_password_cb *cb, + void *u) + { + WOLFSSL_X509_ACERT* x509 = NULL; +#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) + unsigned char * pem = NULL; + int pemSz; + + WOLFSSL_ENTER("wolfSSL_PEM_read_bio_X509_ACERT"); + + if (bp == NULL) { + WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_X509_ACERT", BAD_FUNC_ARG); + return NULL; + } + + if ((pemSz = wolfSSL_BIO_get_len(bp)) <= 0) { + /* No certificate in buffer */ + WOLFSSL_ERROR(ASN_NO_PEM_HEADER); + return NULL; + } + + pem = (unsigned char*)XMALLOC(pemSz, 0, DYNAMIC_TYPE_PEM); + + if (pem == NULL) { + return NULL; + } + + XMEMSET(pem, 0, pemSz); + + if (wolfSSL_BIO_read(bp, pem, pemSz) != pemSz) { + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + return NULL; + } + + x509 = wolfSSL_X509_ACERT_load_certificate_buffer(pem, pemSz, + WOLFSSL_FILETYPE_PEM); + + if (x != NULL) { + *x = x509; + } + + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + +#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */ + (void)bp; + (void)x; + (void)cb; + (void)u; + + return x509; + + } +#endif /* WOLFSSL_ACERT */ + WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509(WOLFSSL_BIO *bp, WOLFSSL_X509 **x, wc_pem_password_cb *cb, void *u) { @@ -11382,9 +11989,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } err: - if(pem != NULL) { - XFREE(pem, 0, DYNAMIC_TYPE_PEM); - } + XFREE(pem, 0, DYNAMIC_TYPE_PEM); if(der != NULL) { FreeDer(&der); } @@ -11481,8 +12086,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) return newx509; err_exit: - if (pem != NULL) - XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); if (der != NULL) FreeDer(&der); @@ -11747,8 +12351,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) #endif return WOLFSSL_SUCCESS; err: - if (pem) - XFREE(pem, 0, DYNAMIC_TYPE_PEM); + XFREE(pem, 0, DYNAMIC_TYPE_PEM); #ifdef HAVE_CRL if (der) FreeDer(&der); @@ -11838,8 +12441,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) ret = MEMORY_E; break; } - if (wolfSSL_sk_X509_INFO_push(localSk, current) != - WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_INFO_push(localSk, current) <= 0) { wolfSSL_X509_INFO_free(current); current = NULL; ret = WOLFSSL_FAILURE; @@ -12216,8 +12818,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( if (name->entries == NULL) { name->entries = wolfSSL_sk_X509_NAME_new(NULL); } - if (wolfSSL_sk_X509_NAME_ENTRY_push(name->entries, current - ) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_NAME_ENTRY_push(name->entries, current) <= 0) { ret = WOLFSSL_FAILURE; } #endif @@ -12245,7 +12846,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( const unsigned char *bytes, int len, int loc, int set) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int nid; WOLFSSL_X509_NAME_ENTRY* entry; @@ -12315,7 +12916,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( int idx) { if (!name || idx >= MAX_NAME_ENTRIES || !obj || !obj->obj) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (idx < 0) { @@ -12332,7 +12933,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( } } } - return -1; + return WOLFSSL_FATAL_ERROR; } #endif @@ -12388,7 +12989,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( #ifndef NO_CHECK_PRIVATE_KEY return wc_CheckPrivateKey((byte*)key->pkey.ptr, key->pkey_sz, x509->pubKey.buffer, x509->pubKey.length, - (enum Key_Sum)x509->pubKeyOID) == 1 ? + (enum Key_Sum)x509->pubKeyOID, key->heap) == 1 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; #else /* not compiled in */ @@ -12549,8 +13150,7 @@ int wolfSSL_PEM_write_bio_X509(WOLFSSL_BIO *bio, WOLFSSL_X509 *cert) return WOLFSSL_SUCCESS; error: - if (pem) - XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FAILURE; } #endif /* WOLFSSL_CERT_GEN */ @@ -12669,7 +13269,7 @@ int wolfSSL_sk_X509_NAME_find(const WOLF_STACK_OF(WOLFSSL_X509_NAME) *sk, return i; } } - return -1; + return WOLFSSL_FATAL_ERROR; } /* Name Entry */ @@ -12849,7 +13449,7 @@ WOLF_STACK_OF(WOLFSSL_X509_NAME) *wolfSSL_dup_CA_list( for (i = 0; i < num; i++) { name = wolfSSL_X509_NAME_dup(wolfSSL_sk_X509_NAME_value(sk, i)); - if (name == NULL || WOLFSSL_SUCCESS != wolfSSL_sk_X509_NAME_push(copy, name)) { + if (name == NULL || wolfSSL_sk_X509_NAME_push(copy, name) <= 0) { WOLFSSL_MSG("Memory error"); wolfSSL_sk_X509_NAME_pop_free(copy, wolfSSL_X509_NAME_free); wolfSSL_X509_NAME_free(name); @@ -13247,6 +13847,28 @@ void wolfSSL_X509_OBJECT_free(WOLFSSL_X509_OBJECT *obj) XFREE(obj, NULL, DYNAMIC_TYPE_OPENSSL); } } + +WOLFSSL_X509_OBJECT *wolfSSL_X509_OBJECT_retrieve_by_subject( + WOLF_STACK_OF(WOLFSSL_X509_OBJECT) *sk, + WOLFSSL_X509_LOOKUP_TYPE type, + WOLFSSL_X509_NAME *name) +{ + int i; + + WOLFSSL_ENTER("wolfSSL_X509_OBJECT_retrieve_by_subject"); + + if (sk == NULL || name == NULL) + return NULL; + + for (i = 0; i < wolfSSL_sk_X509_OBJECT_num(sk); i++) { + WOLFSSL_X509_OBJECT* obj = (WOLFSSL_X509_OBJECT *)wolfSSL_sk_X509_OBJECT_value(sk, i); + if (obj != NULL && obj->type == type && + wolfSSL_X509_NAME_cmp( + wolfSSL_X509_get_subject_name(obj->data.x509), name) == 0) + return obj; + } + return NULL; +} #endif /* OPENSSL_ALL */ #ifndef NO_WOLFSSL_STUB @@ -13287,7 +13909,7 @@ int wolfSSL_sk_X509_num(const WOLF_STACK_OF(WOLFSSL_X509) *s) WOLFSSL_ENTER("wolfSSL_sk_X509_num"); if (s == NULL) - return -1; + return WOLFSSL_FATAL_ERROR; return (int)s->num; } @@ -13376,7 +13998,6 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, WOLFSSL_ENTER("wolfSSL_X509_check_host"); /* flags and peername not needed for Nginx. */ - (void)flags; (void)peername; if ((x == NULL) || (chk == NULL)) { @@ -13384,11 +14005,15 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, return WOLFSSL_FAILURE; } - if (flags == WOLFSSL_NO_WILDCARDS) { + if (flags & WOLFSSL_NO_WILDCARDS) { WOLFSSL_MSG("X509_CHECK_FLAG_NO_WILDCARDS not yet implemented"); return WOLFSSL_FAILURE; } - if (flags == WOLFSSL_NO_PARTIAL_WILDCARDS) { + if (flags & WOLFSSL_NO_PARTIAL_WILDCARDS) { + WOLFSSL_MSG("X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS not yet implemented"); + return WOLFSSL_FAILURE; + } + if (flags & WOLFSSL_MULTI_LABEL_WILDCARDS) { WOLFSSL_MSG("X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS not yet implemented"); return WOLFSSL_FAILURE; } @@ -13415,7 +14040,7 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, else { for (i = 0; i < (chklen > 1 ? chklen - 1 : chklen); i++) { if (chk[i] == '\0') { - ret = -1; + ret = WOLFSSL_FATAL_ERROR; goto out; } } @@ -13424,7 +14049,7 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, chklen--; } - ret = CheckHostName(dCert, (char *)chk, chklen); + ret = CheckHostName(dCert, (char *)chk, chklen, flags); out: @@ -13442,7 +14067,7 @@ int wolfSSL_X509_check_host(WOLFSSL_X509 *x, const char *chk, size_t chklen, int wolfSSL_X509_check_ip_asc(WOLFSSL_X509 *x, const char *ipasc, unsigned int flags) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifdef WOLFSSL_SMALL_STACK DecodedCert *dCert = NULL; #else @@ -13491,8 +14116,9 @@ int wolfSSL_X509_check_ip_asc(WOLFSSL_X509 *x, const char *ipasc, } #ifdef WOLFSSL_SMALL_STACK - if (dCert != NULL) + if (x != NULL) { XFREE(dCert, x->heap, DYNAMIC_TYPE_DCERT); + } #endif return ret; @@ -13579,6 +14205,9 @@ int wolfSSL_X509_NAME_digest(const WOLFSSL_X509_NAME *name, #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) +#if defined(OPENSSL_EXTRA) && \ + ((defined(SESSION_CERTS) && !defined(WOLFSSL_QT)) || \ + defined(WOLFSSL_SIGNER_DER_CERT)) /** * Find the issuing cert of the input cert. On a self-signed cert this @@ -13649,6 +14278,8 @@ static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, return WOLFSSL_SUCCESS; } +#endif /* if defined(OPENSSL_EXTRA) && (defined(SESSION_CERTS) || \ + defined(WOLFSSL_SIGNER_DER_CERT)) */ void wolfSSL_X509_email_free(WOLF_STACK_OF(WOLFSSL_STRING) *sk) { @@ -14097,7 +14728,7 @@ int wolfSSL_X509_set_version(WOLFSSL_X509* x509, long v) #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) && WOLFSSL_CERT_GEN */ -#if defined(OPENSSL_ALL) && \ +#if (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)) && \ defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_REQ) void wolfSSL_X509V3_set_ctx(WOLFSSL_X509V3_CTX* ctx, WOLFSSL_X509* issuer, @@ -14158,7 +14789,7 @@ void wolfSSL_X509V3_set_ctx(WOLFSSL_X509V3_CTX* ctx, WOLFSSL_X509* issuer, int wolfSSL_i2d_X509_REQ(WOLFSSL_X509* req, unsigned char** out) { int derSz = 0; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_BIO* bio = NULL; WOLFSSL_ENTER("wolfSSL_i2d_X509_REQ"); @@ -14270,7 +14901,7 @@ int wolfSSL_X509_REQ_sign_ctx(WOLFSSL_X509 *req, static int regenX509REQDerBuffer(WOLFSSL_X509* x509) { int derSz = X509_BUFFER_SZ; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifdef WOLFSSL_SMALL_STACK byte* der; der = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -14467,11 +15098,16 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, req->reqAttributes->type = STACK_TYPE_X509_REQ_ATTR; } } - ret = wolfSSL_sk_push(req->reqAttributes, attr); - if ((ret != WOLFSSL_SUCCESS) || (req->reqAttributes->type == STACK_TYPE_CIPHER)) { - /* CIPHER type makes a copy */ - wolfSSL_X509_ATTRIBUTE_free(attr); + if ((req->reqAttributes != NULL) && + (req->reqAttributes->type == STACK_TYPE_X509_REQ_ATTR)) { + ret = wolfSSL_sk_push(req->reqAttributes, attr) > 0 + ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + } + else { + ret = WOLFSSL_FAILURE; } + if (ret != WOLFSSL_SUCCESS) + wolfSSL_X509_ATTRIBUTE_free(attr); } return ret; @@ -14621,7 +15257,417 @@ void wolfSSL_X509_ATTRIBUTE_free(WOLFSSL_X509_ATTRIBUTE* attr) XFREE(attr, NULL, DYNAMIC_TYPE_OPENSSL); } } -#endif +#endif /* (OPENSSL_ALL || OPENSSL_EXTRA) && + (WOLFSSL_CERT_GEN || WOLFSSL_CERT_REQ) */ + +#if defined(WOLFSSL_ACERT) && \ + (defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA)) + +/* Allocate and return a new WOLFSSL_X509_ACERT struct pointer. + * + * @param [in] heap heap hint + * + * @return pointer on success + * @return NULL on error + * */ +WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new_ex(void* heap) +{ + WOLFSSL_X509_ACERT* x509; + + x509 = (WOLFSSL_X509_ACERT*) XMALLOC(sizeof(WOLFSSL_X509_ACERT), heap, + DYNAMIC_TYPE_X509_ACERT); + + if (x509 != NULL) { + wolfSSL_X509_ACERT_init(x509, 1, heap); + } + + return x509; +} + +WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new(void) +{ + return wolfSSL_X509_ACERT_new_ex(NULL); +} + +/* Initialize a WOLFSSL_X509_ACERT struct. + * + * If dynamic == 1, then the x509 pointer will be freed + * in wolfSSL_X509_ACERT_free. + * + * @param [in] x509 x509 acert pointer + * @param [in] dynamic dynamic mem flag + * @param [in] heap heap hint + * + * @return void + * */ +void wolfSSL_X509_ACERT_init(WOLFSSL_X509_ACERT * x509, int dynamic, void* heap) +{ + if (x509 == NULL) { + WOLFSSL_MSG("error: InitX509Acert: null parameter"); + return; + } + + XMEMSET(x509, 0, sizeof(*x509)); + + x509->heap = heap; + x509->dynamic = dynamic; +} + +/* Free a WOLFSSL_X509_ACERT struct and its sub-fields. + * + * If this ACERT was initialized with dynamic == 1, then + * the x509 pointer itself will be freed as well. + * + * @param [in] x509 x509 acert pointer + * + * @return void + * */ +void wolfSSL_X509_ACERT_free(WOLFSSL_X509_ACERT * x509) +{ + int dynamic = 0; + void * heap = NULL; + + if (x509 == NULL) { + WOLFSSL_MSG("error: wolfSSL_X509_ACERT_free: null parameter"); + return; + } + + dynamic = x509->dynamic; + heap = x509->heap; + + /* Free holder and att cert issuer structures. */ + if (x509->holderIssuerName) { + FreeAltNames(x509->holderIssuerName, heap); + x509->holderIssuerName = NULL; + } + + if (x509->AttCertIssuerName) { + FreeAltNames(x509->AttCertIssuerName, heap); + x509->AttCertIssuerName = NULL; + } + + if (x509->rawAttr != NULL) { + XFREE(x509->rawAttr, heap, DYNAMIC_TYPE_X509_EXT); + x509->rawAttr = NULL; + x509->rawAttrLen = 0; + } + + /* Free derCert source and signature buffer. */ + FreeDer(&x509->derCert); + + if (x509->sig.buffer != NULL) { + XFREE(x509->sig.buffer, heap, DYNAMIC_TYPE_SIGNATURE); + x509->sig.buffer = NULL; + } + + /* Finally memset and free x509 acert structure. */ + XMEMSET(x509, 0, sizeof(*x509)); + + if (dynamic == 1) { + XFREE(x509, heap, DYNAMIC_TYPE_X509_ACERT); + } + + return; +} + +#if defined(OPENSSL_EXTRA) +long wolfSSL_X509_ACERT_get_version(const WOLFSSL_X509_ACERT* x509) +{ + int version = 0; + + if (x509 == NULL) { + return 0L; + } + + version = x509->version; + + return version != 0 ? (long)version - 1L : 0L; +} +#endif /* OPENSSL_EXTRA */ + +int wolfSSL_X509_ACERT_version(WOLFSSL_X509_ACERT* x509) +{ + if (x509 == NULL) { + return 0; + } + + return x509->version; +} + +/* Retrieve the serial number from an ACERT. + * + * @param [in] x509 the x509 attribute certificate + * @param [in, out] buf the serial number buffer pointer + * @param [in, out] bufSz the serial number buffer size pointer + * + * buf may be null, but bufSz is required. On success, sets + * bufSz pointer to signature length, and copies signature + * to buf if provided. + * + * Returns WWOLFSSL_FATAL_ERROR if bufSz is null or too small. + * Returns WOLFSSL_SUCCESS on success. + */ +int wolfSSL_X509_ACERT_get_serial_number(WOLFSSL_X509_ACERT* x509, + byte* buf, int* bufSz) +{ + WOLFSSL_ENTER("wolfSSL_X509_ACERT_get_serial_number"); + + if (x509 == NULL || bufSz == NULL) { + WOLFSSL_MSG("error: null argument passed in"); + return BAD_FUNC_ARG; + } + + if (buf != NULL) { + if (*bufSz < x509->serialSz) { + WOLFSSL_MSG("error: serial buffer too small"); + return BUFFER_E; + } + + XMEMCPY(buf, x509->serial, x509->serialSz); + } + + *bufSz = x509->serialSz; + + return WOLFSSL_SUCCESS; +} + +/* Sets buf pointer and len to raw Attribute buffer and buffer len + * in X509 struct. + * + * Returns WOLFSSL_SUCCESS on success. + * Returns BAD_FUNC_ARG if input pointers are null. + * */ +WOLFSSL_API int wolfSSL_X509_ACERT_get_attr_buf(const WOLFSSL_X509_ACERT* x509, + const byte ** rawAttr, + word32 * rawAttrLen) +{ + if (x509 == NULL || rawAttr == NULL || rawAttrLen == NULL) { + return BAD_FUNC_ARG; + } + + *rawAttr = x509->rawAttr; + *rawAttrLen = x509->rawAttrLen; + + return WOLFSSL_SUCCESS; +} + +#ifndef NO_WOLFSSL_STUB +WOLFSSL_API int wolfSSL_X509_ACERT_sign(WOLFSSL_X509_ACERT * x509, + WOLFSSL_EVP_PKEY * pkey, + const WOLFSSL_EVP_MD * md) +{ + WOLFSSL_STUB("X509_ACERT_sign"); + (void) x509; + (void) pkey; + (void) md; + return WOLFSSL_NOT_IMPLEMENTED; +} +#endif /* NO_WOLFSSL_STUB */ + +/* Helper function for ACERT_verify. + * + * @param [in] x509 the x509 attribute certificate + * @param [in, out] outSz the x509 der length + * + * @return der buffer on success + * @return NULL on error + * */ +static const byte* acert_get_der(WOLFSSL_X509_ACERT * x509, int* outSz) +{ + if (x509 == NULL || x509->derCert == NULL || outSz == NULL) { + return NULL; + } + + *outSz = (int)x509->derCert->length; + return x509->derCert->buffer; +} + +/* Given an X509_ACERT and EVP_PKEY, verify the acert's signature. + * + * @param [in] x509 the x509 attribute certificate + * @param [in] pkey the evp_pkey + * + * @return WOLFSSL_SUCCESS on verify success + * @return < 0 on error + * */ +int wolfSSL_X509_ACERT_verify(WOLFSSL_X509_ACERT* x509, WOLFSSL_EVP_PKEY* pkey) +{ + int ret = 0; + const byte * der = NULL; + int derSz = 0; + int pkey_type; + + if (x509 == NULL || pkey == NULL) { + WOLFSSL_MSG("error: wolfSSL_X509_ACERT_verify: bad arg"); + return WOLFSSL_FATAL_ERROR; + } + + WOLFSSL_ENTER("wolfSSL_X509_ACERT_verify"); + + der = acert_get_der(x509, &derSz); + + if (der == NULL || derSz <= 0) { + WOLFSSL_MSG("error: wolfSSL_X509_ACERT_verify: get der failed"); + return WOLFSSL_FATAL_ERROR; + } + + switch (pkey->type) { + case EVP_PKEY_RSA: + pkey_type = RSAk; + break; + + case EVP_PKEY_EC: + pkey_type = ECDSAk; + break; + + case EVP_PKEY_DSA: + pkey_type = DSAk; + break; + + default: + WOLFSSL_MSG("error: wolfSSL_X509_ACERT_verify: unknown pkey type"); + return WOLFSSL_FATAL_ERROR; + } + + + ret = VerifyX509Acert(der, (word32)derSz, + (const byte *)pkey->pkey.ptr, pkey->pkey_sz, + pkey_type, x509->heap); + + return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} + +WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer_ex( + const unsigned char* buf, int sz, int format, void * heap) +{ + int ret = 0; + WOLFSSL_X509_ACERT * x509 = NULL; + DerBuffer * der = NULL; + #ifdef WOLFSSL_SMALL_STACK + DecodedAcert * acert = NULL; + #else + DecodedAcert acert[1]; + #endif + + WOLFSSL_ENTER("wolfSSL_X509_ACERT_load_certificate_buffer"); + + if (format == WOLFSSL_FILETYPE_PEM) { + #ifdef WOLFSSL_PEM_TO_DER + ret = PemToDer(buf, sz, ACERT_TYPE, &der, heap, NULL, NULL); + + if (ret != 0 || der == NULL || der->buffer == NULL) { + WOLFSSL_ERROR(ret); + + if (der != NULL) { + FreeDer(&der); + } + + return NULL; + } + #else + WOLFSSL_ERROR(NOT_COMPILED_IN); + return NULL; + #endif + } + else { + ret = AllocDer(&der, (word32)sz, ACERT_TYPE, heap); + + if (ret != 0 || der == NULL || der->buffer == NULL) { + WOLFSSL_ERROR(ret); + return NULL; + } + + XMEMCPY(der->buffer, buf, sz); + } + + #ifdef WOLFSSL_SMALL_STACK + acert = (DecodedAcert*)XMALLOC(sizeof(DecodedAcert), heap, + DYNAMIC_TYPE_DCERT); + if (acert == NULL) { + WOLFSSL_ERROR(MEMORY_ERROR); + FreeDer(&der); + return NULL; + } + #endif + + InitDecodedAcert(acert, der->buffer, der->length, heap); + + ret = ParseX509Acert(acert, VERIFY_SKIP_DATE); + + if (ret == 0) { + x509 = wolfSSL_X509_ACERT_new_ex(heap); + + if (x509 != NULL) { + ret = CopyDecodedAcertToX509(x509, acert); + + if (ret != 0) { + wolfSSL_X509_ACERT_free(x509); + x509 = NULL; + } + } + else { + ret = MEMORY_ERROR; + } + } + + FreeDecodedAcert(acert); + + #ifdef WOLFSSL_SMALL_STACK + XFREE(acert, heap, DYNAMIC_TYPE_DCERT); + #endif + + FreeDer(&der); + + if (ret != 0) { + WOLFSSL_ERROR(ret); + } + + return x509; +} + +WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer( + const unsigned char* buf, int sz, int format) +{ + return wolfSSL_X509_ACERT_load_certificate_buffer_ex(buf, sz, format, NULL); +} + +/* Retrieve the signature from an ACERT. + * + * @param [in] x509 the x509 attribute certificate + * @param [in, out] buf the signature buffer pointer + * @param [in, out] bufSz the signature buffer size pointer + * + * buf may be null, but bufSz is required. On success, sets + * bufSz pointer to signature length, and copies signature + * to buf if provided. + * + * Returns WWOLFSSL_FATAL_ERROR if bufSz is null or too small. + * Returns WOLFSSL_SUCCESS on success. + */ +int wolfSSL_X509_ACERT_get_signature(WOLFSSL_X509_ACERT* x509, + unsigned char* buf, int* bufSz) +{ + WOLFSSL_ENTER("wolfSSL_X509_ACERT_get_signature"); + + if (x509 == NULL || bufSz == NULL) { + return WOLFSSL_FATAL_ERROR; + } + + /* If buf array is provided, it must be long enough. */ + if (buf != NULL && *bufSz < (int)x509->sig.length) { + return WOLFSSL_FATAL_ERROR; + } + + if (buf != NULL) { + /* Copy in buffer if provided. */ + XMEMCPY(buf, x509->sig.buffer, x509->sig.length); + } + + *bufSz = (int)x509->sig.length; + + return WOLFSSL_SUCCESS; +} +#endif /* WOLFSSL_ACERT && (OPENSSL_EXTRA_X509_SMALL || OPENSSL_EXTRA) */ #endif /* !NO_CERTS */ diff --git a/src/src/x509_str.c b/src/src/x509_str.c index f5c5c2a..c3d33b8 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -1,6 +1,6 @@ /* x509_str.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -36,9 +36,21 @@ #ifndef NO_CERTS -/******************************************************************************* +#ifdef OPENSSL_EXTRA +static int X509StoreGetIssuerEx(WOLFSSL_X509 **issuer, + WOLFSSL_STACK *certs, WOLFSSL_X509 *x); +static int X509StoreAddCa(WOLFSSL_X509_STORE* store, + WOLFSSL_X509* x509, int type); +#endif + +/* Based on OpenSSL default max depth */ +#ifndef WOLFSSL_X509_STORE_DEFAULT_MAX_DEPTH +#define WOLFSSL_X509_STORE_DEFAULT_MAX_DEPTH 100 +#endif + +/****************************************************************************** * START OF X509_STORE_CTX APIs - ******************************************************************************/ + *****************************************************************************/ /* This API is necessary outside of OPENSSL_EXTRA because it is used in * SetupStoreCtxCallback */ @@ -53,11 +65,16 @@ WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new_ex(void* heap) XMEMSET(ctx, 0, sizeof(WOLFSSL_X509_STORE_CTX)); ctx->heap = heap; #ifdef OPENSSL_EXTRA - if (wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL) != - WOLFSSL_SUCCESS) { + if ((ctx->owned = wolfSSL_sk_X509_new_null()) == NULL) { XFREE(ctx, heap, DYNAMIC_TYPE_X509_CTX); ctx = NULL; } + if (ctx != NULL && + wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL) != + WOLFSSL_SUCCESS) { + wolfSSL_X509_STORE_CTX_free(ctx); + ctx = NULL; + } #endif } @@ -76,9 +93,18 @@ void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) #endif #ifdef OPENSSL_EXTRA - if (ctx->param != NULL) { - XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; + XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); + ctx->param = NULL; + + if (ctx->chain != NULL) { + wolfSSL_sk_X509_free(ctx->chain); + } + if (ctx->owned != NULL) { + wolfSSL_sk_X509_pop_free(ctx->owned, NULL); + } + + if (ctx->current_issuer != NULL) { + wolfSSL_X509_free(ctx->current_issuer); } #endif @@ -98,8 +124,6 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509, WOLF_STACK_OF(WOLFSSL_X509)* sk) { - int ret = 0; - (void)sk; WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_init"); if (ctx != NULL) { @@ -108,51 +132,21 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, ctx->current_cert = x509; #else if(x509 != NULL){ - ctx->current_cert = wolfSSL_X509_d2i_ex(NULL, x509->derCert->buffer, - x509->derCert->length, x509->heap); + ctx->current_cert = wolfSSL_X509_d2i_ex(NULL, + x509->derCert->buffer, + x509->derCert->length, + x509->heap); if(ctx->current_cert == NULL) return WOLFSSL_FAILURE; } else ctx->current_cert = NULL; #endif - ctx->chain = sk; - /* Add intermediate certs, that verify to a loaded CA, to the store */ - if (sk != NULL) { - byte addedAtLeastOne = 1; - WOLF_STACK_OF(WOLFSSL_X509)* head = wolfSSL_shallow_sk_dup(sk); - if (head == NULL) - return WOLFSSL_FAILURE; - while (addedAtLeastOne) { - WOLF_STACK_OF(WOLFSSL_X509)* cur = head; - WOLF_STACK_OF(WOLFSSL_X509)** prev = &head; - addedAtLeastOne = 0; - while (cur) { - WOLFSSL_X509* cert = cur->data.x509; - if (cert != NULL && cert->derCert != NULL && - wolfSSL_CertManagerVerifyBuffer(store->cm, - cert->derCert->buffer, - cert->derCert->length, - WOLFSSL_FILETYPE_ASN1) == WOLFSSL_SUCCESS) { - ret = wolfSSL_X509_STORE_add_cert(store, cert); - if (ret < 0) { - wolfSSL_sk_free(head); - return WOLFSSL_FAILURE; - } - addedAtLeastOne = 1; - *prev = cur->next; - wolfSSL_sk_free_node(cur); - cur = *prev; - } - else { - prev = &cur->next; - cur = cur->next; - } - } - } - wolfSSL_sk_free(head); + ctx->ctxIntermediates = sk; + if (ctx->chain != NULL) { + wolfSSL_sk_X509_free(ctx->chain); + ctx->chain = NULL; } - ctx->sesChain = NULL; ctx->domain = NULL; #ifdef HAVE_EX_DATA @@ -186,20 +180,19 @@ void wolfSSL_X509_STORE_CTX_cleanup(WOLFSSL_X509_STORE_CTX* ctx) { if (ctx != NULL) { - if (ctx->param != NULL) { - XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); - ctx->param = NULL; - } + XFREE(ctx->param, ctx->heap, DYNAMIC_TYPE_OPENSSL); + ctx->param = NULL; wolfSSL_X509_STORE_CTX_init(ctx, NULL, NULL, NULL); } } -void wolfSSL_X509_STORE_CTX_trusted_stack(WOLFSSL_X509_STORE_CTX *ctx, WOLF_STACK_OF(WOLFSSL_X509) *sk) +void wolfSSL_X509_STORE_CTX_trusted_stack(WOLFSSL_X509_STORE_CTX *ctx, + WOLF_STACK_OF(WOLFSSL_X509) *sk) { if (ctx != NULL) { - ctx->chain = sk; + ctx->setTrustedSk = sk; } } @@ -225,6 +218,10 @@ int GetX509Error(int e) case WC_NO_ERR_TRACE(ASN_SIG_HASH_E): case WC_NO_ERR_TRACE(ASN_SIG_KEY_E): return WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE; + /* We can't disambiguate if its the before or after date that caused + * the error. Assume expired. */ + case WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR): + return X509_V_ERR_CRL_HAS_EXPIRED; case WC_NO_ERR_TRACE(CRL_CERT_REVOKED): return WOLFSSL_X509_V_ERR_CERT_REVOKED; case WC_NO_ERR_TRACE(CRL_MISSING): @@ -255,58 +252,239 @@ static void SetupStoreCtxError(WOLFSSL_X509_STORE_CTX* ctx, int ret) wolfSSL_X509_STORE_CTX_set_error_depth(ctx, depth); } -/* Verifies certificate chain using WOLFSSL_X509_STORE_CTX - * returns 0 on success or < 0 on failure. - */ -int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) +static int X509StoreVerifyCert(WOLFSSL_X509_STORE_CTX* ctx) { - WOLFSSL_ENTER("wolfSSL_X509_verify_cert"); - - if (ctx != NULL && ctx->store != NULL && ctx->store->cm != NULL - && ctx->current_cert != NULL && ctx->current_cert->derCert != NULL) { - int ret = wolfSSL_CertManagerVerifyBuffer(ctx->store->cm, - ctx->current_cert->derCert->buffer, - ctx->current_cert->derCert->length, - WOLFSSL_FILETYPE_ASN1); + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + WOLFSSL_ENTER("X509StoreVerifyCert"); + + if (ctx->current_cert != NULL && ctx->current_cert->derCert != NULL) { + ret = wolfSSL_CertManagerVerifyBuffer(ctx->store->cm, + ctx->current_cert->derCert->buffer, + ctx->current_cert->derCert->length, + WOLFSSL_FILETYPE_ASN1); SetupStoreCtxError(ctx, ret); + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + if (ctx->store->verify_cb) + ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, ctx) == 1 ? 0 : ret; + #endif #ifndef NO_ASN_TIME if (ret != WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) && ret != WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { /* wolfSSL_CertManagerVerifyBuffer only returns ASN_AFTER_DATE_E or - ASN_BEFORE_DATE_E if there are no additional errors found in the - cert. Therefore, check if the cert is expired or not yet valid - in order to return the correct expected error. */ + * ASN_BEFORE_DATE_E if there are no additional errors found in the + * cert. Therefore, check if the cert is expired or not yet valid + * in order to return the correct expected error. */ byte *afterDate = ctx->current_cert->notAfter.data; byte *beforeDate = ctx->current_cert->notBefore.data; if (XVALIDATE_DATE(afterDate, - (byte)ctx->current_cert->notAfter.type, AFTER) < 1) { + (byte)ctx->current_cert->notAfter.type, ASN_AFTER) < 1) { ret = ASN_AFTER_DATE_E; } else if (XVALIDATE_DATE(beforeDate, - (byte)ctx->current_cert->notBefore.type, BEFORE) < 1) { + (byte)ctx->current_cert->notBefore.type, ASN_BEFORE) < 1) { ret = ASN_BEFORE_DATE_E; } SetupStoreCtxError(ctx, ret); + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + if (ctx->store->verify_cb) + ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, + ctx) == 1 ? 0 : -1; + #endif } #endif + } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - if (ctx->store && ctx->store->verify_cb) - ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, ctx) == 1 ? 0 : -1; + return ret; +} + +static int addAllButSelfSigned(WOLF_STACK_OF(WOLFSSL_X509)*to, + WOLF_STACK_OF(WOLFSSL_X509)*from, int *numAdded) +{ + int ret = WOLFSSL_SUCCESS; + int i = 0; + int cnt = 0; + WOLFSSL_X509 *x = NULL; + + for (i = 0; i < wolfSSL_sk_X509_num(from); i++) { + x = wolfSSL_sk_X509_value(from, i); + if (wolfSSL_X509_NAME_cmp(&x->issuer, &x->subject) != 0) { + if (wolfSSL_sk_X509_push(to, x) <= 0) { + ret = WOLFSSL_FAILURE; + goto exit; + } + cnt++; + } + } + +exit: + if (numAdded != NULL) { + *numAdded = cnt; + } + return ret; +} + +/* Verifies certificate chain using WOLFSSL_X509_STORE_CTX + * returns 0 on success or < 0 on failure. + */ +int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + int done = 0; + int added = 0; + int i = 0; + int numInterAdd = 0; + int depth = 0; + WOLFSSL_X509 *issuer = NULL; + WOLFSSL_X509 *orig = NULL; + WOLF_STACK_OF(WOLFSSL_X509)* certs = NULL; + WOLF_STACK_OF(WOLFSSL_X509)* certsToUse = NULL; + WOLFSSL_ENTER("wolfSSL_X509_verify_cert"); + + if (ctx == NULL || ctx->store == NULL || ctx->store->cm == NULL + || ctx->current_cert == NULL || ctx->current_cert->derCert == NULL) { + return WOLFSSL_FATAL_ERROR; + } + + certs = ctx->store->certs; + if (ctx->setTrustedSk != NULL) { + certs = ctx->setTrustedSk; + } + + if (certs == NULL && + wolfSSL_sk_X509_num(ctx->ctxIntermediates) > 0) { + certsToUse = wolfSSL_sk_X509_new_null(); + ret = addAllButSelfSigned(certsToUse, ctx->ctxIntermediates, NULL); + } + else { + /* Add the intermediates provided on init to the list of untrusted + * intermediates to be used */ + ret = addAllButSelfSigned(certs, ctx->ctxIntermediates, &numInterAdd); + } + if (ret != WOLFSSL_SUCCESS) { + goto exit; + } + + if (ctx->chain != NULL) { + wolfSSL_sk_X509_free(ctx->chain); + } + ctx->chain = wolfSSL_sk_X509_new_null(); + + if (ctx->depth > 0) { + depth = ctx->depth + 1; + } + else { + depth = WOLFSSL_X509_STORE_DEFAULT_MAX_DEPTH + 1; + } + + orig = ctx->current_cert; + while(done == 0 && depth > 0) { + issuer = NULL; + + /* Try to find an untrusted issuer first */ + ret = X509StoreGetIssuerEx(&issuer, certs, + ctx->current_cert); + if (ret == WOLFSSL_SUCCESS) { + if (ctx->current_cert == issuer) { + wolfSSL_sk_X509_push(ctx->chain, ctx->current_cert); + break; + } + + /* We found our issuer in the non-trusted cert list, add it + * to the CM and verify the current cert against it */ + ret = X509StoreAddCa(ctx->store, issuer, + WOLFSSL_TEMP_CA); + if (ret != WOLFSSL_SUCCESS) { + goto exit; + } + + added = 1; + + ret = X509StoreVerifyCert(ctx); + if (ret != WOLFSSL_SUCCESS) { + goto exit; + } + + /* Add it to the current chain and look at the issuer cert next */ + wolfSSL_sk_X509_push(ctx->chain, ctx->current_cert); + ctx->current_cert = issuer; + } + else if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + /* Could not find in untrusted list, only place left is + * a trusted CA in the CM */ + ret = X509StoreVerifyCert(ctx); + if (ret != WOLFSSL_SUCCESS) { + if (((ctx->flags & WOLFSSL_PARTIAL_CHAIN) || + (ctx->store->param->flags & WOLFSSL_PARTIAL_CHAIN)) && + (added == 1)) { + wolfSSL_sk_X509_push(ctx->chain, ctx->current_cert); + ret = WOLFSSL_SUCCESS; + } + goto exit; + } + + /* Cert verified, finish building the chain */ + wolfSSL_sk_X509_push(ctx->chain, ctx->current_cert); + issuer = NULL; + #ifdef WOLFSSL_SIGNER_DER_CERT + x509GetIssuerFromCM(&issuer, ctx->store->cm, ctx->current_cert); + if (issuer != NULL && ctx->owned != NULL) { + wolfSSL_sk_X509_push(ctx->owned, issuer); + } + #else + if (ctx->setTrustedSk == NULL) { + X509StoreGetIssuerEx(&issuer, + ctx->store->trusted, ctx->current_cert); + } + else { + X509StoreGetIssuerEx(&issuer, + ctx->setTrustedSk, ctx->current_cert); + } #endif + if (issuer != NULL) { + wolfSSL_sk_X509_push(ctx->chain, issuer); + } - return ret >= 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; + done = 1; + } + else { + goto exit; + } + + depth--; } - return WOLFSSL_FATAL_ERROR; + +exit: + /* Remove additional intermediates from init from the store */ + if (ctx != NULL && numInterAdd > 0) { + for (i = 0; i < numInterAdd; i++) { + wolfSSL_sk_X509_pop(ctx->store->certs); + } + } + /* Remove intermediates that were added to CM */ + if (ctx != NULL) { + if (ctx->store != NULL) { + if (added == 1) { + wolfSSL_CertManagerUnloadTempIntermediateCerts(ctx->store->cm); + } + } + if (orig != NULL) { + ctx->current_cert = orig; + } + } + if (certsToUse != NULL) { + wolfSSL_sk_X509_free(certsToUse); + } + + return ret == WOLFSSL_SUCCESS ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } #endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) WOLFSSL_X509* wolfSSL_X509_STORE_CTX_get_current_cert( - WOLFSSL_X509_STORE_CTX* ctx) + WOLFSSL_X509_STORE_CTX* ctx) { WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_current_cert"); if (ctx) @@ -404,14 +582,6 @@ int wolfSSL_X509_STORE_CTX_set_purpose(WOLFSSL_X509_STORE_CTX *ctx, WOLFSSL_STUB("wolfSSL_X509_STORE_CTX_set_purpose (not implemented)"); return 0; } - -void wolfSSL_X509_STORE_CTX_set_flags(WOLFSSL_X509_STORE_CTX *ctx, - unsigned long flags) -{ - (void)ctx; - (void)flags; - WOLFSSL_STUB("wolfSSL_X509_STORE_CTX_set_flags (not implemented)"); -} #endif /* !NO_WOLFSSL_STUB */ #endif /* WOLFSSL_QT || OPENSSL_ALL */ @@ -419,6 +589,14 @@ void wolfSSL_X509_STORE_CTX_set_flags(WOLFSSL_X509_STORE_CTX *ctx, #ifdef OPENSSL_EXTRA +void wolfSSL_X509_STORE_CTX_set_flags(WOLFSSL_X509_STORE_CTX *ctx, + unsigned long flags) +{ + if ((ctx != NULL) && (flags & WOLFSSL_PARTIAL_CHAIN)){ + ctx->flags |= WOLFSSL_PARTIAL_CHAIN; + } +} + /* set X509_STORE_CTX ex_data, max idx is MAX_EX_DATA. Return WOLFSSL_SUCCESS * on success, WOLFSSL_FAILURE on error. */ int wolfSSL_X509_STORE_CTX_set_ex_data(WOLFSSL_X509_STORE_CTX* ctx, int idx, @@ -450,8 +628,8 @@ int wolfSSL_X509_STORE_CTX_set_ex_data_with_cleanup( WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_set_ex_data_with_cleanup"); if (ctx != NULL) { - return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data, - cleanup_routine); + return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, + data, cleanup_routine); } return WOLFSSL_FAILURE; } @@ -466,22 +644,24 @@ void wolfSSL_X509_STORE_CTX_set_depth(WOLFSSL_X509_STORE_CTX* ctx, int depth) } #endif - WOLFSSL_X509* wolfSSL_X509_STORE_CTX_get0_current_issuer( WOLFSSL_X509_STORE_CTX* ctx) { - int ret; - WOLFSSL_X509* issuer; - + WOLFSSL_STACK* node; WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get0_current_issuer"); - if (ctx == NULL) { + if (ctx == NULL) return NULL; - } - ret = wolfSSL_X509_STORE_CTX_get1_issuer(&issuer, ctx, ctx->current_cert); - if (ret == WOLFSSL_SUCCESS) { - return issuer; + /* get0 only checks currently built chain */ + if (ctx->chain != NULL) { + for (node = ctx->chain; node != NULL; node = node->next) { + if (wolfSSL_X509_check_issued(node->data.x509, + ctx->current_cert) == + WOLFSSL_X509_V_OK) { + return node->data.x509; + } + } } return NULL; @@ -501,7 +681,7 @@ void wolfSSL_X509_STORE_CTX_set_error(WOLFSSL_X509_STORE_CTX* ctx, int er) /* Set the error depth in the X509 STORE CTX */ void wolfSSL_X509_STORE_CTX_set_error_depth(WOLFSSL_X509_STORE_CTX* ctx, - int depth) + int depth) { WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_set_error_depth"); @@ -529,7 +709,8 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) if (sk == NULL) return NULL; -#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) +#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ + defined(OPENSSL_EXTRA) /* add CA used to verify top of chain to the list */ if (c->count > 0) { WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, c->count - 1); @@ -541,7 +722,7 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) * signed and that a issuer was found */ if (issuer != NULL && wolfSSL_X509_NAME_cmp(&x509->issuer, &x509->subject) != 0) { - if (wolfSSL_sk_X509_push(sk, issuer) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(sk, issuer) <= 0) { WOLFSSL_MSG("Unable to load CA x509 into stack"); error = 1; } @@ -573,7 +754,7 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) break; } - if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(sk, x509) <= 0) { WOLFSSL_MSG("Unable to load x509 into stack"); wolfSSL_X509_free(x509); error = 1; @@ -692,13 +873,13 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_STORE_get1_certs( if (certToFilterName != NULL) { if (wolfSSL_X509_NAME_cmp(certToFilterName, name) == 0) { filteredCert = wolfSSL_X509_dup(certToFilter->data.x509); - if (filteredCert == NULL) { + if (filteredCert == NULL || + wolfSSL_sk_X509_push(filteredCerts, filteredCert) + <= 0) { err = 1; + wolfSSL_X509_free(filteredCert); break; } - else { - wolfSSL_sk_X509_push(filteredCerts, filteredCert); - } } } certToFilter = certToFilter->next; @@ -730,34 +911,63 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_STORE_get1_certs( int wolfSSL_X509_STORE_CTX_get1_issuer(WOLFSSL_X509 **issuer, WOLFSSL_X509_STORE_CTX *ctx, WOLFSSL_X509 *x) { - WOLFSSL_STACK* node; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get1_issuer"); if (issuer == NULL || ctx == NULL || x == NULL) return WOLFSSL_FATAL_ERROR; - if (ctx->chain != NULL) { - for (node = ctx->chain; node != NULL; node = node->next) { - if (wolfSSL_X509_check_issued(node->data.x509, x) == - WOLFSSL_X509_V_OK) { - *issuer = x; + ret = X509StoreGetIssuerEx(issuer, ctx->store->certs, x); + if ((ret == WOLFSSL_SUCCESS) && (*issuer != NULL)) { + return wolfSSL_X509_up_ref(*issuer); + } + +#ifdef WOLFSSL_SIGNER_DER_CERT + ret = x509GetIssuerFromCM(issuer, ctx->store->cm, x); +#else + ret = X509StoreGetIssuerEx(issuer, ctx->store->trusted, x); + if ((ret == WOLFSSL_SUCCESS) && (*issuer != NULL)) { + return wolfSSL_X509_up_ref(*issuer); + } +#endif + + return ret; +} +#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */ + +#ifdef OPENSSL_EXTRA + +static int X509StoreGetIssuerEx(WOLFSSL_X509 **issuer, + WOLFSSL_STACK * certs, WOLFSSL_X509 *x) +{ + int i; + + if (issuer == NULL || x == NULL) + return WOLFSSL_FATAL_ERROR; + + if (certs != NULL) { + for (i = 0; i < wolfSSL_sk_X509_num(certs); i++) { + if (wolfSSL_X509_check_issued( + wolfSSL_sk_X509_value(certs, i), x) == + WOLFSSL_X509_V_OK) { + *issuer = wolfSSL_sk_X509_value(certs, i); return WOLFSSL_SUCCESS; } } } - /* Result is ignored when passed to wolfSSL_OCSP_cert_to_id(). */ - - return x509GetIssuerFromCM(issuer, ctx->store->cm, x); + return WOLFSSL_FAILURE; } -#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */ -/******************************************************************************* +#endif + +/****************************************************************************** * END OF X509_STORE_CTX APIs - ******************************************************************************/ + *****************************************************************************/ -/******************************************************************************* +/****************************************************************************** * START OF X509_STORE APIs - ******************************************************************************/ + *****************************************************************************/ #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) @@ -785,10 +995,25 @@ WOLFSSL_X509_STORE* wolfSSL_X509_STORE_new(void) if ((store->cm = wolfSSL_CertManagerNew()) == NULL) goto err_exit; +#ifdef OPENSSL_EXTRA + if ((store->certs = wolfSSL_sk_X509_new_null()) == NULL) + goto err_exit; + + if ((store->owned = wolfSSL_sk_X509_new_null()) == NULL) + goto err_exit; + +#if !defined(WOLFSSL_SIGNER_DER_CERT) + if ((store->trusted = wolfSSL_sk_X509_new_null()) == NULL) + goto err_exit; +#endif +#endif + #ifdef HAVE_CRL store->crl = store->cm->crl; #endif + store->numAdded = 0; + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) /* Link store's new Certificate Manager to self by default */ @@ -823,6 +1048,30 @@ WOLFSSL_X509_STORE* wolfSSL_X509_STORE_new(void) return NULL; } +#ifdef OPENSSL_ALL +static void X509StoreFreeObjList(WOLFSSL_X509_STORE* store, + WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* objs) +{ + int i; + WOLFSSL_X509_OBJECT *obj = NULL; + int cnt = store->numAdded; + + i = wolfSSL_sk_X509_OBJECT_num(objs) - 1; + while (cnt > 0 && i > 0) { + /* The inner X509 is owned by somebody else, NULL out the reference */ + obj = (WOLFSSL_X509_OBJECT *)wolfSSL_sk_X509_OBJECT_value(objs, i); + if (obj != NULL) { + obj->type = (WOLFSSL_X509_LOOKUP_TYPE)0; + obj->data.ptr = NULL; + } + cnt--; + i--; + } + + wolfSSL_sk_X509_OBJECT_pop_free(objs, NULL); +} +#endif + void wolfSSL_X509_STORE_free(WOLFSSL_X509_STORE* store) { int doFree = 0; @@ -845,21 +1094,36 @@ void wolfSSL_X509_STORE_free(WOLFSSL_X509_STORE* store) wolfSSL_CertManagerFree(store->cm); store->cm = NULL; } +#if defined(OPENSSL_EXTRA) + if (store->certs != NULL) { + wolfSSL_sk_X509_free(store->certs); + store->certs = NULL; + } + if (store->owned != NULL) { + wolfSSL_sk_X509_pop_free(store->owned, wolfSSL_X509_free); + store->owned = NULL; + } +#if !defined(WOLFSSL_SIGNER_DER_CERT) + if (store->trusted != NULL) { + wolfSSL_sk_X509_free(store->trusted); + store->trusted = NULL; + } +#endif +#endif #ifdef OPENSSL_ALL if (store->objs != NULL) { - wolfSSL_sk_X509_OBJECT_pop_free(store->objs, NULL); + X509StoreFreeObjList(store, store->objs); } #endif #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - if (store->param != NULL) { - XFREE(store->param, NULL, DYNAMIC_TYPE_OPENSSL); - store->param = NULL; - } + XFREE(store->param, NULL, DYNAMIC_TYPE_OPENSSL); + store->param = NULL; if (store->lookup.dirs != NULL) { #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) if (store->lookup.dirs->dir_entry) { - wolfSSL_sk_BY_DIR_entry_free(store->lookup.dirs->dir_entry); + wolfSSL_sk_BY_DIR_entry_free( + store->lookup.dirs->dir_entry); } #endif wc_FreeMutex(&store->lookup.dirs->lock); @@ -867,6 +1131,7 @@ void wolfSSL_X509_STORE_free(WOLFSSL_X509_STORE* store) store->lookup.dirs = NULL; } #endif + wolfSSL_RefFree(&store->ref); XFREE(store, NULL, DYNAMIC_TYPE_X509_STORE); } } @@ -920,7 +1185,7 @@ int wolfSSL_X509_STORE_up_ref(WOLFSSL_X509_STORE* store) * @return WOLFSSL_SUCCESS on success or WOLFSSL_FAILURE on failure */ int wolfSSL_X509_STORE_set_ex_data(WOLFSSL_X509_STORE* store, int idx, - void *data) + void *data) { WOLFSSL_ENTER("wolfSSL_X509_STORE_set_ex_data"); #ifdef HAVE_EX_DATA @@ -1007,22 +1272,68 @@ WOLFSSL_X509_LOOKUP* wolfSSL_X509_STORE_add_lookup(WOLFSSL_X509_STORE* store, return &store->lookup; } -int wolfSSL_X509_STORE_add_cert(WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509) +static int X509StoreAddCa(WOLFSSL_X509_STORE* store, + WOLFSSL_X509* x509, int type) { - int result = WOLFSSL_FATAL_ERROR; - - WOLFSSL_ENTER("wolfSSL_X509_STORE_add_cert"); - if (store != NULL && store->cm != NULL && x509 != NULL - && x509->derCert != NULL) { - DerBuffer* derCert = NULL; + int result = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); + DerBuffer* derCert = NULL; + WOLFSSL_ENTER("X509StoreAddCa"); + if (store != NULL && x509 != NULL && x509->derCert != NULL) { result = AllocDer(&derCert, x509->derCert->length, x509->derCert->type, NULL); if (result == 0) { /* AddCA() frees the buffer. */ XMEMCPY(derCert->buffer, x509->derCert->buffer, x509->derCert->length); - result = AddCA(store->cm, &derCert, WOLFSSL_USER_CA, VERIFY); + result = AddCA(store->cm, &derCert, type, VERIFY); + } + } + + return result; +} + + +int wolfSSL_X509_STORE_add_cert(WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509) +{ + int result = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); + + WOLFSSL_ENTER("wolfSSL_X509_STORE_add_cert"); + if (store != NULL && store->cm != NULL && x509 != NULL + && x509->derCert != NULL) { + /* Mimic the openssl behavior, must be self signed to be considered + * trusted, addCA() internals will do additional checks for + * CA=TRUE */ + if (wolfSSL_X509_NAME_cmp(&x509->issuer, &x509->subject) == 0) { + result = X509StoreAddCa(store, x509, WOLFSSL_USER_CA); + #if !defined(WOLFSSL_SIGNER_DER_CERT) + if (result == WOLFSSL_SUCCESS && store->trusted != NULL) { + result = wolfSSL_sk_X509_push(store->trusted, x509); + if (result > 0) { + result = WOLFSSL_SUCCESS; + } + else { + result = WOLFSSL_FATAL_ERROR; + } + } + #endif + } + else { + if (store->certs != NULL) { + result = wolfSSL_sk_X509_push(store->certs, x509); + if (result > 0) { + result = WOLFSSL_SUCCESS; + } + else { + result = WOLFSSL_FATAL_ERROR; + } + } + else { + /* If store->certs is NULL, this is an X509_STORE managed by an + * SSL_CTX, preserve behavior and always add as USER_CA */ + result = X509StoreAddCa( + store, x509, WOLFSSL_USER_CA); + } } } @@ -1052,6 +1363,9 @@ int wolfSSL_X509_STORE_set_flags(WOLFSSL_X509_STORE* store, unsigned long flag) ret = wolfSSL_CertManagerDisableCRL(store->cm); } #endif + if (flag & WOLFSSL_PARTIAL_CHAIN) { + store->param->flags |= WOLFSSL_PARTIAL_CHAIN; + } return ret; } @@ -1062,13 +1376,107 @@ int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE* store) return WOLFSSL_SUCCESS; } +int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, + byte *buf, word32 bufLen, int type) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + WOLFSSL_X509 *x509 = NULL; + + if (str == NULL || buf == NULL) { + return WOLFSSL_FAILURE; + } + + /* OpenSSL X509_STORE_load_file fails on DER file, we will as well */ + x509 = wolfSSL_X509_load_certificate_buffer(buf, bufLen, type); + if (str->owned != NULL) { + wolfSSL_sk_X509_push(str->owned, x509); + } + ret = wolfSSL_X509_STORE_add_cert(str, x509); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to load file"); + ret = WOLFSSL_FAILURE; + } + if (str->owned == NULL) { + wolfSSL_X509_free(x509); + } + + return ret; +} + #if !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) + +static int X509StoreReadFile(const char *fname, + StaticBuffer *content, word32 *bytesRead, int *type) +{ + int ret = -1; + long sz = 0; +#ifdef HAVE_CRL + const char* header = NULL; + const char* footer = NULL; +#endif + + ret = wolfssl_read_file_static(fname, content, NULL, DYNAMIC_TYPE_FILE, + &sz); + if (ret == 0) { + *type = CERT_TYPE; + *bytesRead = (word32)sz; +#ifdef HAVE_CRL + /* Look for CRL header and footer. */ + if (wc_PemGetHeaderFooter(CRL_TYPE, &header, &footer) == 0 && + (XSTRNSTR((char*)content->buffer, header, (word32)sz) != + NULL)) { + *type = CRL_TYPE; + } +#endif + } + + return (ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE); +} + +static int X509StoreLoadFile(WOLFSSL_X509_STORE *str, + const char *fname) +{ + int ret = WOLFSSL_SUCCESS; + int type = 0; +#ifndef WOLFSSL_SMALL_STACK + byte stackBuffer[FILE_BUFFER_SIZE]; +#endif + StaticBuffer content; + word32 contentLen = 0; + +#ifdef WOLFSSL_SMALL_STACK + static_buffer_init(&content); +#else + static_buffer_init(&content, stackBuffer, FILE_BUFFER_SIZE); +#endif + + ret = X509StoreReadFile(fname, &content, &contentLen, &type); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to load file"); + ret = WOLFSSL_FAILURE; + } + + if ((ret == WOLFSSL_SUCCESS) && (type == CERT_TYPE)) { + ret = X509StoreLoadCertBuffer(str, content.buffer, + contentLen, WOLFSSL_FILETYPE_PEM); + } +#ifdef HAVE_CRL + else if ((ret == WOLFSSL_SUCCESS) && (type == CRL_TYPE)) { + ret = BufferLoadCRL(str->cm->crl, content.buffer, contentLen, + WOLFSSL_FILETYPE_PEM, 0); + } +#endif + + static_buffer_free(&content, NULL, DYNAMIC_TYPE_FILE); + return ret; +} + /* Loads certificate(s) files in pem format into X509_STORE struct from either * a file or directory. * Returns WOLFSSL_SUCCESS on success or WOLFSSL_FAILURE if an error occurs. */ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, - const char *file, const char *dir) + const char *file, const char *dir) { WOLFSSL_CTX* ctx; char *name = NULL; @@ -1108,10 +1516,7 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, /* Load individual file */ if (file) { - /* Try to process file with type DETECT_CERT_TYPE to parse the - correct certificate header and footer type */ - ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, DETECT_CERT_TYPE, - NULL, 0, str->cm->crl, 0); + ret = X509StoreLoadFile(str, file); if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to load file"); ret = WOLFSSL_FAILURE; @@ -1124,7 +1529,7 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, #ifdef WOLFSSL_SMALL_STACK readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), ctx->heap, - DYNAMIC_TYPE_TMP_BUFFER); + DYNAMIC_TYPE_TMP_BUFFER); if (readCtx == NULL) { WOLFSSL_MSG("Memory error"); wolfSSL_CTX_free(ctx); @@ -1136,10 +1541,8 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, ret = wc_ReadDirFirst(readCtx, dir, &name); while (ret == 0 && name) { WOLFSSL_MSG(name); - /* Try to process file with type DETECT_CERT_TYPE to parse the - correct certificate header and footer type */ - ret = ProcessFile(ctx, name, WOLFSSL_FILETYPE_PEM, DETECT_CERT_TYPE, - NULL, 0, str->cm->crl, 0); + + ret = X509StoreLoadFile(str, name); /* Not failing on load errors */ if (ret != WOLFSSL_SUCCESS) WOLFSSL_MSG("Failed to load file in path, continuing"); @@ -1182,17 +1585,23 @@ int wolfSSL_X509_CA_num(WOLFSSL_X509_STORE* store) } table = store->cm->caTable; - if (table){ + if (table || (store->certs != NULL)){ if (wc_LockMutex(&store->cm->caLock) == 0){ - int i = 0; - for (i = 0; i < CA_TABLE_SIZE; i++) { - Signer* signer = table[i]; - while (signer) { - Signer* next = signer->next; - cnt_ret++; - signer = next; + if (table) { + int i = 0; + for (i = 0; i < CA_TABLE_SIZE; i++) { + Signer* signer = table[i]; + while (signer) { + Signer* next = signer->next; + cnt_ret++; + signer = next; + } } } + + if (store->certs != NULL) { + cnt_ret += wolfSSL_sk_X509_num(store->certs); + } wc_UnLockMutex(&store->cm->caLock); } } @@ -1201,7 +1610,8 @@ int wolfSSL_X509_CA_num(WOLFSSL_X509_STORE* store) } /****************************************************************************** -* wolfSSL_X509_STORE_GetCerts - retrieve stack of X509 in a certificate store ctx +* wolfSSL_X509_STORE_GetCerts - retrieve stack of X509 in a certificate +* store ctx * * This API can be used in SSL verify callback function to view cert chain * See examples/client/client.c and myVerify() function in test.h @@ -1232,7 +1642,8 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_GetCerts(WOLFSSL_X509_STORE_CTX* s) /* get certificate buffer */ cert = &s->certs[certIdx]; - dCert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT); + dCert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, + DYNAMIC_TYPE_DCERT); if (dCert == NULL) { goto error; @@ -1254,7 +1665,7 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_GetCerts(WOLFSSL_X509_STORE_CTX* s) if (CopyDecodedToX509(x509, dCert) == 0) { - if (wolfSSL_sk_X509_push(sk, x509) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_push(sk, x509) <= 0) { WOLFSSL_MSG("Unable to load x509 into stack"); wolfSSL_X509_free(x509); goto error; @@ -1295,7 +1706,14 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( { WOLFSSL_STACK* ret = NULL; WOLFSSL_STACK* cert_stack = NULL; +#if ((defined(WOLFSSL_SIGNER_DER_CERT) && !defined(NO_FILESYSTEM)) || \ + (defined(HAVE_CRL))) + WOLFSSL_X509_OBJECT* obj = NULL; +#endif +#if defined(WOLFSSL_SIGNER_DER_CERT) && !defined(NO_FILESYSTEM) WOLFSSL_X509* x509 = NULL; + int i = 0; +#endif WOLFSSL_ENTER("wolfSSL_X509_STORE_get0_objects"); if (store == NULL || store->cm == NULL) { @@ -1306,7 +1724,7 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( if (store->objs != NULL) { #if defined(WOLFSSL_SIGNER_DER_CERT) && !defined(NO_FILESYSTEM) /* want to update objs stack by cm stack again before returning it*/ - wolfSSL_sk_X509_OBJECT_pop_free(store->objs, NULL); + X509StoreFreeObjList(store, store->objs); store->objs = NULL; #else if (wolfSSL_sk_X509_OBJECT_num(store->objs) == 0) { @@ -1326,32 +1744,43 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( #if defined(WOLFSSL_SIGNER_DER_CERT) && !defined(NO_FILESYSTEM) cert_stack = wolfSSL_CertManagerGetCerts(store->cm); - /* wolfSSL_sk_X509_pop checks for NULL */ - while ((x509 = wolfSSL_sk_X509_pop(cert_stack)) != NULL) { - WOLFSSL_X509_OBJECT* obj = wolfSSL_X509_OBJECT_new(); + store->numAdded = 0; + for (i = 0; i < wolfSSL_sk_X509_num(store->certs); i++) { + wolfSSL_sk_X509_push(cert_stack, + wolfSSL_sk_X509_value(store->certs, i)); + store->numAdded++; + } + /* Do not modify stack until after we guarantee success to + * simplify cleanup logic handling cert merging above */ + for (i = 0; i < wolfSSL_sk_X509_num(cert_stack); i++) { + x509 = (WOLFSSL_X509 *)wolfSSL_sk_value(cert_stack, i); + obj = wolfSSL_X509_OBJECT_new(); if (obj == NULL) { WOLFSSL_MSG("wolfSSL_X509_OBJECT_new error"); goto err_cleanup; } - if (wolfSSL_sk_X509_OBJECT_push(ret, obj) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_OBJECT_push(ret, obj) <= 0) { WOLFSSL_MSG("wolfSSL_sk_X509_OBJECT_push error"); wolfSSL_X509_OBJECT_free(obj); goto err_cleanup; } obj->type = WOLFSSL_X509_LU_X509; obj->data.x509 = x509; - x509 = NULL; + } + + while (wolfSSL_sk_X509_num(cert_stack) > 0) { + wolfSSL_sk_X509_pop(cert_stack); } #endif #ifdef HAVE_CRL if (store->cm->crl != NULL) { - WOLFSSL_X509_OBJECT* obj = wolfSSL_X509_OBJECT_new(); + obj = wolfSSL_X509_OBJECT_new(); if (obj == NULL) { WOLFSSL_MSG("wolfSSL_X509_OBJECT_new error"); goto err_cleanup; } - if (wolfSSL_sk_X509_OBJECT_push(ret, obj) != WOLFSSL_SUCCESS) { + if (wolfSSL_sk_X509_OBJECT_push(ret, obj) <= 0) { WOLFSSL_MSG("wolfSSL_sk_X509_OBJECT_push error"); wolfSSL_X509_OBJECT_free(obj); goto err_cleanup; @@ -1367,11 +1796,14 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( return ret; err_cleanup: if (ret != NULL) - wolfSSL_sk_X509_OBJECT_pop_free(ret, NULL); - if (cert_stack != NULL) + X509StoreFreeObjList(store, ret); + if (cert_stack != NULL) { + while (store->numAdded > 0) { + wolfSSL_sk_X509_pop(cert_stack); + store->numAdded--; + } wolfSSL_sk_X509_pop_free(cert_stack, NULL); - if (x509 != NULL) - wolfSSL_X509_free(x509); + } return NULL; } #endif /* OPENSSL_ALL */ @@ -1385,11 +1817,21 @@ WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_get0_param( return NULL; return ctx->param; } + +#ifdef OPENSSL_EXTRA +int wolfSSL_X509_STORE_set1_param(WOLFSSL_X509_STORE *ctx, + WOLFSSL_X509_VERIFY_PARAM *param) +{ + if (ctx == NULL) + return WOLFSSL_FAILURE; + return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, param); +} +#endif #endif -/******************************************************************************* +/****************************************************************************** * END OF X509_STORE APIs - ******************************************************************************/ + *****************************************************************************/ #endif /* NO_CERTS */ diff --git a/src/user_settings.h b/src/user_settings.h index 52c4e7d..15bc03b 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -1,6 +1,6 @@ /* examples/configs/user_settings_arduino.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -23,7 +23,7 @@ */ /* Define a macro to display user settings version in example code: */ -#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.2" +#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.4" /* Due to limited build control, we'll ignore file warnings. */ /* See https://github.com/arduino/arduino-cli/issues/631 */ diff --git a/src/wolfcrypt/src/aes.c b/src/wolfcrypt/src/aes.c index 8418fb0..1cb9843 100644 --- a/src/wolfcrypt/src/aes.c +++ b/src/wolfcrypt/src/aes.c @@ -1,6 +1,6 @@ /* aes.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -82,6 +82,17 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #include #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include +#ifdef MAX3266X_CB + /* Revert back to SW so HW CB works */ + /* HW only works for AES: ECB, CBC, and partial via ECB for other modes */ + #include + /* Turn off MAX3266X_AES in the context of this file when using CB */ + #undef MAX3266X_AES +#endif +#endif + #if defined(WOLFSSL_TI_CRYPT) #include #else @@ -613,6 +624,10 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #define AESNI_ALIGN 16 #endif + /* note that all write access to these static variables must be idempotent, + * as arranged by Check_CPU_support_AES(), else they will be susceptible to + * data races. + */ static int checkedAESNI = 0; static int haveAESNI = 0; static word32 intel_flags = 0; @@ -2201,7 +2216,8 @@ static void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, } #if defined(HAVE_AES_ECB) && !(defined(WOLFSSL_IMX6_CAAM) && \ - !defined(NO_IMX6_CAAM_AES) && !defined(WOLFSSL_QNX_CAAM)) + !defined(NO_IMX6_CAAM_AES) && !defined(WOLFSSL_QNX_CAAM)) && \ + !defined(MAX3266X_AES) /* Encrypt a number of blocks using AES. * * @param [in] aes AES object. @@ -2785,6 +2801,12 @@ extern void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz); static WARN_UNUSED_RESULT int wc_AesEncrypt( Aes* aes, const byte* inBlock, byte* outBlock) { +#if defined(MAX3266X_AES) + word32 keySize; +#endif +#if defined(MAX3266X_CB) + int ret_cb; +#endif word32 r; if (aes == NULL) { @@ -2888,6 +2910,26 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( } #endif +#if defined(MAX3266X_AES) + if (wc_AesGetKeySize(aes, &keySize) == 0) { + return wc_MXC_TPU_AesEncrypt(inBlock, (byte*)aes->reg, (byte*)aes->key, + MXC_TPU_MODE_ECB, AES_BLOCK_SIZE, + outBlock, (unsigned int)keySize); + } +#endif +#if defined(MAX3266X_CB) && defined(HAVE_AES_ECB) /* Can do a basic ECB block */ + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif + { + ret_cb = wc_CryptoCb_AesEcbEncrypt(aes, outBlock, inBlock, + AES_BLOCK_SIZE); + if (ret_cb != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret_cb; + /* fall-through when unavailable */ + } +#endif + AesEncrypt_C(aes, inBlock, outBlock, r); return 0; @@ -3168,7 +3210,8 @@ static void AesDecrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, } #if defined(HAVE_AES_ECB) && !(defined(WOLFSSL_IMX6_CAAM) && \ - !defined(NO_IMX6_CAAM_AES) && !defined(WOLFSSL_QNX_CAAM)) + !defined(NO_IMX6_CAAM_AES) && !defined(WOLFSSL_QNX_CAAM)) && \ + !defined(MAX3266X_AES) /* Decrypt a number of blocks using AES. * * @param [in] aes AES object. @@ -3535,6 +3578,12 @@ static void AesDecryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz) static WARN_UNUSED_RESULT int wc_AesDecrypt( Aes* aes, const byte* inBlock, byte* outBlock) { +#if defined(MAX3266X_AES) + word32 keySize; +#endif +#if defined(MAX3266X_CB) + int ret_cb; +#endif word32 r; if (aes == NULL) { @@ -3611,6 +3660,27 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( } /* else !wc_esp32AesSupportedKeyLen for ESP32 */ #endif +#if defined(MAX3266X_AES) + if (wc_AesGetKeySize(aes, &keySize) == 0) { + return wc_MXC_TPU_AesDecrypt(inBlock, (byte*)aes->reg, (byte*)aes->key, + MXC_TPU_MODE_ECB, AES_BLOCK_SIZE, + outBlock, (unsigned int)keySize); + } +#endif + +#if defined(MAX3266X_CB) && defined(HAVE_AES_ECB) /* Can do a basic ECB block */ + #ifndef WOLF_CRYPTO_CB_FIND + if (aes->devId != INVALID_DEVID) + #endif + { + ret_cb = wc_CryptoCb_AesEcbDecrypt(aes, outBlock, inBlock, + AES_BLOCK_SIZE); + if (ret_cb != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret_cb; + /* fall-through when unavailable */ + } +#endif + AesDecrypt_C(aes, inBlock, outBlock, r); return 0; @@ -3656,8 +3726,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( #if !defined(WOLFSSL_STM32_CUBEMX) || defined(STM32_HAL_V2) ByteReverseWords(rk, rk, keylen); #endif - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif return wc_AesSetIV(aes, iv); @@ -3737,8 +3807,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( if (iv) XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif @@ -3768,8 +3838,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( aes->rounds = keylen/4 + 6; XMEMCPY(aes->key, userKey, keylen); - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif @@ -3820,8 +3890,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( if (rk == NULL) return BAD_FUNC_ARG; - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif @@ -3901,8 +3971,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( XMEMCPY(aes->key, userKey, keylen); ret = nrf51_aes_set_key(userKey); - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif @@ -3958,7 +4028,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( aes->rounds = keylen/4 + 6; XMEMCPY(aes->key, userKey, keylen); - #if defined(WOLFSSL_AES_COUNTER) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif return wc_AesSetIV(aes, iv); @@ -4099,7 +4170,8 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) XMEMCPY(rk, key, keySz); #if defined(LITTLE_ENDIAN_ORDER) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \ - (!defined(WOLFSSL_ESP32_CRYPT) || defined(NO_WOLFSSL_ESP32_CRYPT_AES)) + (!defined(WOLFSSL_ESP32_CRYPT) || defined(NO_WOLFSSL_ESP32_CRYPT_AES)) && \ + !defined(MAX3266X_AES) /* Always reverse words when using only SW */ { ByteReverseWords(rk, rk, keySz); @@ -4246,7 +4318,7 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) } /* switch */ ForceZero(&temp, sizeof(temp)); -#if defined(HAVE_AES_DECRYPT) +#if defined(HAVE_AES_DECRYPT) && !defined(MAX3266X_AES) if (dir == AES_DECRYPTION) { unsigned int j; @@ -4449,8 +4521,8 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) #endif } - #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \ - defined(WOLFSSL_AES_OFB) + #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) aes->left = 0; #endif @@ -4542,8 +4614,8 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) #ifndef WC_AES_BITSLICED #if defined(LITTLE_ENDIAN_ORDER) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \ - (!defined(WOLFSSL_ESP32_CRYPT) || \ - defined(NO_WOLFSSL_ESP32_CRYPT_AES)) + (!defined(WOLFSSL_ESP32_CRYPT) || defined(NO_WOLFSSL_ESP32_CRYPT_AES)) \ + && !defined(MAX3266X_AES) /* software */ ByteReverseWords(aes->key, aes->key, keylen); @@ -4688,7 +4760,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #ifdef WC_C_DYNAMIC_FALLBACK -#define VECTOR_REGISTERS_PUSH { \ +#define VECTOR_REGISTERS_PUSH { \ int orig_use_aesni = aes->use_aesni; \ if (aes->use_aesni && (SAVE_VECTOR_REGISTERS2() != 0)) { \ aes->use_aesni = 0; \ @@ -4703,6 +4775,15 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } \ WC_DO_NOTHING +#elif defined(SAVE_VECTOR_REGISTERS2_DOES_NOTHING) + +#define VECTOR_REGISTERS_PUSH { \ + WC_DO_NOTHING + +#define VECTOR_REGISTERS_POP \ + } \ + WC_DO_NOTHING + #else #define VECTOR_REGISTERS_PUSH { \ @@ -5374,6 +5455,91 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } #endif /* HAVE_AES_DECRYPT */ +#elif defined(MAX3266X_AES) + int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) + { + word32 keySize; + int status; + byte *iv; + + if ((in == NULL) || (out == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + /* Always enforce a length check */ + if (sz % AES_BLOCK_SIZE) { + #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS + return BAD_LENGTH_E; + #else + return BAD_FUNC_ARG; + #endif + } + if (sz == 0) { + return 0; + } + + iv = (byte*)aes->reg; + status = wc_AesGetKeySize(aes, &keySize); + if (status != 0) { + return status; + } + + status = wc_MXC_TPU_AesEncrypt(in, iv, (byte*)aes->key, + MXC_TPU_MODE_CBC, sz, out, + (unsigned int)keySize); + /* store iv for next call */ + if (status == 0) { + XMEMCPY(iv, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + } + return (status == 0) ? 0 : -1; + } + + #ifdef HAVE_AES_DECRYPT + int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) + { + word32 keySize; + int status; + byte *iv; + byte temp_block[AES_BLOCK_SIZE]; + + if ((in == NULL) || (out == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + /* Always enforce a length check */ + if (sz % AES_BLOCK_SIZE) { + #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS + return BAD_LENGTH_E; + #else + return BAD_FUNC_ARG; + #endif + } + if (sz == 0) { + return 0; + } + + iv = (byte*)aes->reg; + status = wc_AesGetKeySize(aes, &keySize); + if (status != 0) { + return status; + } + + /* get IV for next call */ + XMEMCPY(temp_block, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + status = wc_MXC_TPU_AesDecrypt(in, iv, (byte*)aes->key, + MXC_TPU_MODE_CBC, sz, out, + keySize); + + /* store iv for next call */ + if (status == 0) { + XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + } + return (status == 0) ? 0 : -1; + } + #endif /* HAVE_AES_DECRYPT */ + + + #elif defined(WOLFSSL_PIC32MZ_CRYPT) int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) @@ -7897,6 +8063,8 @@ static void GHASH_FINAL(Aes* aes, byte* s, word32 sSz) GHASH_LEN_BLOCK(aes); /* Copy the result into s. */ XMEMCPY(s, AES_TAG(aes), sSz); + /* reset aes->gcm.H in case of re-use */ + GHASH_INIT_EXTRA(aes); } #endif /* WOLFSSL_AESGCM_STREAM */ @@ -8308,7 +8476,10 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, int ret; /* argument checks */ - if (aes == NULL || authTagSz > AES_BLOCK_SIZE || ivSz == 0) { + if (aes == NULL || authTagSz > AES_BLOCK_SIZE || ivSz == 0 || + ((authTagSz > 0) && (authTag == NULL)) || + ((authInSz > 0) && (authIn == NULL))) + { return BAD_FUNC_ARG; } @@ -8437,8 +8608,8 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, * in and out are don't cares, as this is is the GMAC case. */ if (aes == NULL || iv == NULL || (sz != 0 && (in == NULL || out == NULL)) || authTag == NULL || authTagSz > AES_BLOCK_SIZE || authTagSz == 0 || - ivSz == 0) { - + ivSz == 0 || ((authInSz > 0) && (authIn == NULL))) + { return BAD_FUNC_ARG; } @@ -8855,7 +9026,7 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( /* now use res as a mask for constant time return of ret, unless tag * mismatch, whereupon AES_GCM_AUTH_E is returned. */ - ret = (ret & ~res) | (res & AES_GCM_AUTH_E); + ret = (ret & ~res) | (res & WC_NO_ERR_TRACE(AES_GCM_AUTH_E)); #endif return ret; } @@ -9637,7 +9808,7 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( ASSERT_SAVED_VECTOR_REGISTERS(); /* Hash in A, the Authentication Data */ - ret = AesGcmAadUpdate_aesni(aes, a, aSz, (cSz > 0) && (c != NULL)); + ret = AesGcmAadUpdate_aesni(aes, a, aSz, cSz > 0); if (ret != 0) return ret; @@ -9858,7 +10029,8 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_AESNI) if ((ret == 0) && (aes->streamData == NULL)) { /* Allocate buffers for streaming. */ - aes->streamData = (byte*)XMALLOC(5 * AES_BLOCK_SIZE, aes->heap, + aes->streamData_sz = 5 * AES_BLOCK_SIZE; + aes->streamData = (byte*)XMALLOC(aes->streamData_sz, aes->heap, DYNAMIC_TYPE_AES); if (aes->streamData == NULL) { ret = MEMORY_E; @@ -10345,7 +10517,7 @@ int wc_Gmac(const byte* key, word32 keySz, byte* iv, word32 ivSz, byte* authTag, word32 authTagSz, WC_RNG* rng) { #ifdef WOLFSSL_SMALL_STACK - Aes *aes = NULL; + Aes *aes; #else Aes aes[1]; #endif @@ -10358,24 +10530,24 @@ int wc_Gmac(const byte* key, word32 keySz, byte* iv, word32 ivSz, } #ifdef WOLFSSL_SMALL_STACK - if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, - DYNAMIC_TYPE_AES)) == NULL) - return MEMORY_E; + aes = wc_AesNew(NULL, INVALID_DEVID, &ret); +#else + ret = wc_AesInit(aes, NULL, INVALID_DEVID); #endif + if (ret != 0) + return ret; - ret = wc_AesInit(aes, NULL, INVALID_DEVID); - if (ret == 0) { - ret = wc_AesGcmSetKey(aes, key, keySz); - if (ret == 0) - ret = wc_AesGcmSetIV(aes, ivSz, NULL, 0, rng); - if (ret == 0) - ret = wc_AesGcmEncrypt_ex(aes, NULL, NULL, 0, iv, ivSz, + ret = wc_AesGcmSetKey(aes, key, keySz); + if (ret == 0) + ret = wc_AesGcmSetIV(aes, ivSz, NULL, 0, rng); + if (ret == 0) + ret = wc_AesGcmEncrypt_ex(aes, NULL, NULL, 0, iv, ivSz, authTag, authTagSz, authIn, authInSz); - wc_AesFree(aes); - } - ForceZero(aes, sizeof *aes); + #ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); + wc_AesDelete(aes, NULL); +#else + wc_AesFree(aes); #endif return ret; @@ -10401,22 +10573,21 @@ int wc_GmacVerify(const byte* key, word32 keySz, } #ifdef WOLFSSL_SMALL_STACK - if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, - DYNAMIC_TYPE_AES)) == NULL) - return MEMORY_E; -#endif - + aes = wc_AesNew(NULL, INVALID_DEVID, &ret); +#else ret = wc_AesInit(aes, NULL, INVALID_DEVID); +#endif if (ret == 0) { ret = wc_AesGcmSetKey(aes, key, keySz); if (ret == 0) ret = wc_AesGcmDecrypt(aes, NULL, NULL, 0, iv, ivSz, authTag, authTagSz, authIn, authInSz); - wc_AesFree(aes); + } - ForceZero(aes, sizeof *aes); #ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); + wc_AesDelete(aes, NULL); +#else + wc_AesFree(aes); #endif #else (void)key; @@ -11128,8 +11299,41 @@ int wc_AesCcmEncrypt_ex(Aes* aes, byte* out, const byte* in, word32 sz, #endif /* HAVE_AESCCM */ +#ifndef WC_NO_CONSTRUCTORS +Aes* wc_AesNew(void* heap, int devId, int *result_code) +{ + int ret; + Aes* aes = (Aes*)XMALLOC(sizeof(Aes), heap, DYNAMIC_TYPE_AES); + if (aes == NULL) { + ret = MEMORY_E; + } + else { + ret = wc_AesInit(aes, heap, devId); + if (ret != 0) { + XFREE(aes, heap, DYNAMIC_TYPE_AES); + aes = NULL; + } + } + + if (result_code != NULL) + *result_code = ret; -/* Initialize Aes for use with async hardware */ + return aes; +} + +int wc_AesDelete(Aes *aes, Aes** aes_p) +{ + if (aes == NULL) + return BAD_FUNC_ARG; + wc_AesFree(aes); + XFREE(aes, aes->heap, DYNAMIC_TYPE_AES); + if (aes_p != NULL) + *aes_p = NULL; + return 0; +} +#endif /* !WC_NO_CONSTRUCTORS */ + +/* Initialize Aes */ int wc_AesInit(Aes* aes, void* heap, int devId) { int ret = 0; @@ -11137,17 +11341,12 @@ int wc_AesInit(Aes* aes, void* heap, int devId) if (aes == NULL) return BAD_FUNC_ARG; - aes->heap = heap; - aes->rounds = 0; + XMEMSET(aes, 0, sizeof(*aes)); -#ifdef WOLFSSL_AESNI - /* clear here for the benefit of wc_AesGcmInit(). */ - aes->use_aesni = 0; -#endif + aes->heap = heap; #ifdef WOLF_CRYPTO_CB aes->devId = devId; - aes->devCtx = NULL; #else (void)devId; #endif @@ -11160,51 +11359,18 @@ int wc_AesInit(Aes* aes, void* heap, int devId) aes->alFd = WC_SOCK_NOTSET; aes->rdFd = WC_SOCK_NOTSET; #endif -#ifdef WOLFSSL_KCAPI_AES - aes->handle = NULL; - aes->init = 0; -#endif #if defined(WOLFSSL_DEVCRYPTO) && \ (defined(WOLFSSL_DEVCRYPTO_AES) || defined(WOLFSSL_DEVCRYPTO_CBC)) aes->ctx.cfd = -1; #endif -#if defined(WOLFSSL_CRYPTOCELL) && defined(WOLFSSL_CRYPTOCELL_AES) - XMEMSET(&aes->ctx, 0, sizeof(aes->ctx)); -#endif #if defined(WOLFSSL_IMXRT_DCP) DCPAesInit(aes); #endif -#ifdef WOLFSSL_MAXQ10XX_CRYPTO - XMEMSET(&aes->maxq_ctx, 0, sizeof(aes->maxq_ctx)); -#endif - -#ifdef HAVE_AESGCM -#ifdef OPENSSL_EXTRA - XMEMSET(aes->gcm.aadH, 0, sizeof(aes->gcm.aadH)); - aes->gcm.aadLen = 0; -#endif -#endif - -#ifdef WOLFSSL_AESGCM_STREAM -#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_AESNI) - aes->streamData = NULL; -#endif - aes->keylen = 0; - aes->nonceSz = 0; - aes->gcmKeySet = 0; - aes->nonceSet = 0; - aes->ctrSet = 0; -#endif - #if defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_AES) ret = wc_psa_aes_init(aes); #endif -#if defined(WOLFSSL_RENESAS_FSPSM) - XMEMSET(&aes->ctx, 0, sizeof(aes->ctx)); -#endif - #ifdef WC_DEBUG_CIPHER_LIFECYCLE if (ret == 0) ret = wc_debug_CipherLifecycleInit(&aes->CipherLifecycleTag, aes->heap); @@ -11259,11 +11425,12 @@ int wc_AesInit_Label(Aes* aes, const char* label, void* heap, int devId) } #endif -/* Free Aes from use with async hardware */ +/* Free Aes resources */ void wc_AesFree(Aes* aes) { - if (aes == NULL) + if (aes == NULL) { return; + } #ifdef WC_DEBUG_CIPHER_LIFECYCLE (void)wc_debug_CipherLifecycleFree(&aes->CipherLifecycleTag, aes->heap, 1); @@ -11305,6 +11472,7 @@ void wc_AesFree(Aes* aes) #if defined(WOLFSSL_AESGCM_STREAM) && defined(WOLFSSL_SMALL_STACK) && \ !defined(WOLFSSL_AESNI) if (aes->streamData != NULL) { + ForceZero(aes->streamData, aes->streamData_sz); XFREE(aes->streamData, aes->heap, DYNAMIC_TYPE_AES); aes->streamData = NULL; } @@ -11330,6 +11498,8 @@ void wc_AesFree(Aes* aes) wc_fspsm_Aesfree(aes); #endif + ForceZero(aes, sizeof(Aes)); + #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(aes, sizeof(Aes)); #endif @@ -11400,6 +11570,48 @@ int wc_AesGetKeySize(Aes* aes, word32* keySize) #elif defined(WOLFSSL_RISCV_ASM) /* implemented in wolfcrypt/src/port/riscv/riscv-64-aes.c */ +#elif defined(MAX3266X_AES) + +int wc_AesEcbEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) +{ + int status; + word32 keySize; + + if ((in == NULL) || (out == NULL) || (aes == NULL)) + return BAD_FUNC_ARG; + + status = wc_AesGetKeySize(aes, &keySize); + if (status != 0) { + return status; + } + + status = wc_MXC_TPU_AesEncrypt(in, (byte*)aes->reg, (byte*)aes->key, + MXC_TPU_MODE_ECB, sz, out, keySize); + + return status; +} + +#ifdef HAVE_AES_DECRYPT +int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) +{ + int status; + word32 keySize; + + if ((in == NULL) || (out == NULL) || (aes == NULL)) + return BAD_FUNC_ARG; + + status = wc_AesGetKeySize(aes, &keySize); + if (status != 0) { + return status; + } + + status = wc_MXC_TPU_AesDecrypt(in, (byte*)aes->reg, (byte*)aes->key, + MXC_TPU_MODE_ECB, sz, out, keySize); + + return status; +} +#endif /* HAVE_AES_DECRYPT */ + #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES) /* Software AES - ECB */ @@ -12167,8 +12379,7 @@ int wc_AesKeyWrap(const byte* key, word32 keySz, const byte* in, word32 inSz, out: #ifdef WOLFSSL_SMALL_STACK - if (aes != NULL) - XFREE(aes, NULL, DYNAMIC_TYPE_AES); + XFREE(aes, NULL, DYNAMIC_TYPE_AES); #endif return ret; @@ -12286,8 +12497,7 @@ int wc_AesKeyUnWrap(const byte* key, word32 keySz, const byte* in, word32 inSz, out: #ifdef WOLFSSL_SMALL_STACK - if (aes) - XFREE(aes, NULL, DYNAMIC_TYPE_AES); + XFREE(aes, NULL, DYNAMIC_TYPE_AES); #endif return ret; @@ -13606,7 +13816,7 @@ int wc_AesXtsDecryptConsecutiveSectors(XtsAes* aes, byte* out, const byte* in, * See RFC 5297 Section 2.4. */ static WARN_UNUSED_RESULT int S2V( - const byte* key, word32 keySz, const byte* assoc, word32 assocSz, + const byte* key, word32 keySz, const AesSivAssoc* assoc, word32 numAssoc, const byte* nonce, word32 nonceSz, const byte* data, word32 dataSz, byte* out) { @@ -13620,6 +13830,8 @@ static WARN_UNUSED_RESULT int S2V( #endif word32 macSz = AES_BLOCK_SIZE; int ret = 0; + byte tmpi = 0; + word32 ai; word32 zeroBytes; #ifdef WOLFSSL_SMALL_STACK @@ -13632,32 +13844,48 @@ static WARN_UNUSED_RESULT int S2V( } if (ret == 0) #endif - { + + if ((numAssoc > 126) || ((nonceSz > 0) && (numAssoc > 125))) { + /* See RFC 5297 Section 7. */ + WOLFSSL_MSG("Maximum number of ADs (including the nonce) for AES SIV is" + " 126."); + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { XMEMSET(tmp[1], 0, AES_BLOCK_SIZE); XMEMSET(tmp[2], 0, AES_BLOCK_SIZE); ret = wc_AesCmacGenerate(tmp[0], &macSz, tmp[1], AES_BLOCK_SIZE, key, keySz); - if (ret == 0) { - ShiftAndXorRb(tmp[1], tmp[0]); - ret = wc_AesCmacGenerate(tmp[0], &macSz, assoc, assocSz, key, - keySz); - if (ret == 0) { - xorbuf(tmp[1], tmp[0], AES_BLOCK_SIZE); - } - } } if (ret == 0) { - if (nonceSz > 0) { - ShiftAndXorRb(tmp[0], tmp[1]); - ret = wc_AesCmacGenerate(tmp[1], &macSz, nonce, nonceSz, key, - keySz); + /* Loop over authenticated associated data AD1..ADn */ + for (ai = 0; ai < numAssoc; ++ai) { + ShiftAndXorRb(tmp[1-tmpi], tmp[tmpi]); + ret = wc_AesCmacGenerate(tmp[tmpi], &macSz, assoc[ai].assoc, + assoc[ai].assocSz, key, keySz); + if (ret != 0) + break; + xorbuf(tmp[1-tmpi], tmp[tmpi], AES_BLOCK_SIZE); + tmpi = 1 - tmpi; + } + + /* Add nonce as final AD. See RFC 5297 Section 3. */ + if ((ret == 0) && (nonceSz > 0)) { + ShiftAndXorRb(tmp[1-tmpi], tmp[tmpi]); + ret = wc_AesCmacGenerate(tmp[tmpi], &macSz, nonce, + nonceSz, key, keySz); if (ret == 0) { - xorbuf(tmp[0], tmp[1], AES_BLOCK_SIZE); + xorbuf(tmp[1-tmpi], tmp[tmpi], AES_BLOCK_SIZE); } + tmpi = 1 - tmpi; } - else { + + /* For simplicity of the remaining code, make sure the "final" result + is always in tmp[0]. */ + if (tmpi == 1) { XMEMCPY(tmp[0], tmp[1], AES_BLOCK_SIZE); } } @@ -13693,9 +13921,7 @@ static WARN_UNUSED_RESULT int S2V( } } #ifdef WOLFSSL_SMALL_STACK - if (cmac != NULL) { - XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); - } + XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); #elif defined(WOLFSSL_CHECK_MEM_ZERO) wc_MemZero_Check(cmac, sizeof(Cmac)); #endif @@ -13726,8 +13952,8 @@ static WARN_UNUSED_RESULT int S2V( } static WARN_UNUSED_RESULT int AesSivCipher( - const byte* key, word32 keySz, const byte* assoc, - word32 assocSz, const byte* nonce, word32 nonceSz, + const byte* key, word32 keySz, const AesSivAssoc* assoc, + word32 numAssoc, const byte* nonce, word32 nonceSz, const byte* data, word32 dataSz, byte* siv, byte* out, int enc) { @@ -13751,7 +13977,7 @@ static WARN_UNUSED_RESULT int AesSivCipher( if (ret == 0) { if (enc == 1) { - ret = S2V(key, keySz / 2, assoc, assocSz, nonce, nonceSz, data, + ret = S2V(key, keySz / 2, assoc, numAssoc, nonce, nonceSz, data, dataSz, sivTmp); if (ret != 0) { WOLFSSL_MSG("S2V failed."); @@ -13765,17 +13991,12 @@ static WARN_UNUSED_RESULT int AesSivCipher( } } -#ifdef WOLFSSL_SMALL_STACK - if (ret == 0) { - aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_AES); - if (aes == NULL) { - ret = MEMORY_E; - } - } -#endif - if (ret == 0) { +#ifdef WOLFSSL_SMALL_STACK + aes = wc_AesNew(NULL, INVALID_DEVID, &ret); +#else ret = wc_AesInit(aes, NULL, INVALID_DEVID); +#endif if (ret != 0) { WOLFSSL_MSG("Failed to initialized AES object."); } @@ -13798,7 +14019,7 @@ static WARN_UNUSED_RESULT int AesSivCipher( } if (ret == 0 && enc == 0) { - ret = S2V(key, keySz / 2, assoc, assocSz, nonce, nonceSz, out, dataSz, + ret = S2V(key, keySz / 2, assoc, numAssoc, nonce, nonceSz, out, dataSz, sivTmp); if (ret != 0) { WOLFSSL_MSG("S2V failed."); @@ -13810,9 +14031,10 @@ static WARN_UNUSED_RESULT int AesSivCipher( } } - wc_AesFree(aes); #ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); + wc_AesDelete(aes, NULL); +#else + wc_AesFree(aes); #endif return ret; @@ -13825,7 +14047,10 @@ int wc_AesSivEncrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out) { - return AesSivCipher(key, keySz, assoc, assocSz, nonce, nonceSz, in, inSz, + AesSivAssoc ad; + ad.assoc = assoc; + ad.assocSz = assocSz; + return AesSivCipher(key, keySz, &ad, 1U, nonce, nonceSz, in, inSz, siv, out, 1); } @@ -13836,7 +14061,32 @@ int wc_AesSivDecrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out) { - return AesSivCipher(key, keySz, assoc, assocSz, nonce, nonceSz, in, inSz, + AesSivAssoc ad; + ad.assoc = assoc; + ad.assocSz = assocSz; + return AesSivCipher(key, keySz, &ad, 1U, nonce, nonceSz, in, inSz, + siv, out, 0); +} + +/* + * See RFC 5297 Section 2.6. + */ +int wc_AesSivEncrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, + word32 numAssoc, const byte* nonce, word32 nonceSz, + const byte* in, word32 inSz, byte* siv, byte* out) +{ + return AesSivCipher(key, keySz, assoc, numAssoc, nonce, nonceSz, in, inSz, + siv, out, 1); +} + +/* + * See RFC 5297 Section 2.7. + */ +int wc_AesSivDecrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, + word32 numAssoc, const byte* nonce, word32 nonceSz, + const byte* in, word32 inSz, byte* siv, byte* out) +{ + return AesSivCipher(key, keySz, assoc, numAssoc, nonce, nonceSz, in, inSz, siv, out, 0); } diff --git a/src/wolfcrypt/src/arc4.c b/src/wolfcrypt/src/arc4.c index af298a0..649d52f 100644 --- a/src/wolfcrypt/src/arc4.c +++ b/src/wolfcrypt/src/arc4.c @@ -1,6 +1,6 @@ /* arc4.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/asm.c b/src/wolfcrypt/src/asm.c index c735ebf..2096ae9 100644 --- a/src/wolfcrypt/src/asm.c +++ b/src/wolfcrypt/src/asm.c @@ -1,6 +1,6 @@ /* asm.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -529,6 +529,27 @@ __asm__( \ #define LOOP_START \ mu = c[x] * mp +#ifdef __APPLE__ + +#define INNERMUL \ +__asm__( \ + " mullw r16,%3,%4 \n\t" \ + " mulhwu r17,%3,%4 \n\t" \ + " addc r16,r16,%2 \n\t" \ + " addze r17,r17 \n\t" \ + " addc %1,r16,%5 \n\t" \ + " addze %0,r17 \n\t" \ +:"=r"(cy),"=r"(_c[0]):"0"(cy),"r"(mu),"r"(tmpm[0]),"1"(_c[0]):"r16", "r17", "cc"); ++tmpm; + +#define PROPCARRY \ +__asm__( \ + " addc %1,%3,%2 \n\t" \ + " xor %0,%2,%2 \n\t" \ + " addze %0,%2 \n\t" \ +:"=r"(cy),"=r"(_c[0]):"0"(cy),"1"(_c[0]):"cc"); + +#else + #define INNERMUL \ __asm__( \ " mullw 16,%3,%4 \n\t" \ @@ -546,6 +567,8 @@ __asm__( \ " addze %0,%2 \n\t" \ :"=r"(cy),"=r"(_c[0]):"0"(cy),"1"(_c[0]):"cc"); +#endif + #elif defined(TFM_PPC64) /* PPC64 */ @@ -555,6 +578,8 @@ __asm__( \ #define LOOP_START \ mu = c[x] * mp +#ifdef __APPLE__ + #define INNERMUL \ __asm__( \ " mulld r16,%3,%4 \n\t" \ @@ -576,6 +601,31 @@ __asm__( \ " addze %0,%0 \n\t" \ :"=r"(cy),"=m"(_c[0]):"0"(cy),"1"(_c[0]):"r16","cc"); +#else + +#define INNERMUL \ +__asm__( \ + " mulld 16,%3,%4 \n\t" \ + " mulhdu 17,%3,%4 \n\t" \ + " addc 16,16,%0 \n\t" \ + " addze 17,17 \n\t" \ + " ldx 18,0,%1 \n\t" \ + " addc 16,16,18 \n\t" \ + " addze %0,17 \n\t" \ + " sdx 16,0,%1 \n\t" \ +:"=r"(cy),"=m"(_c[0]):"0"(cy),"r"(mu),"r"(tmpm[0]),"1"(_c[0]):"16", "17", "18","cc"); ++tmpm; + +#define PROPCARRY \ +__asm__( \ + " ldx 16,0,%1 \n\t" \ + " addc 16,16,%0 \n\t" \ + " sdx 16,0,%1 \n\t" \ + " xor %0,%0,%0 \n\t" \ + " addze %0,%0 \n\t" \ +:"=r"(cy),"=m"(_c[0]):"0"(cy),"1"(_c[0]):"16","cc"); + +#endif + /******************************************************************/ #elif defined(TFM_AVR32) diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index 778d3e7..0c52002 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -1,6 +1,6 @@ /* asn.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -56,6 +56,8 @@ ASN Options: * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to restore 3.13.0 behavior. + * WOLFSSL_ASN_ALLOW_0_SERIAL: Even if WOLFSSL_NO_ASN_STRICT is not defined, + allow a length=1, but zero value serial number. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer must still be trusted) * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert @@ -100,6 +102,9 @@ ASN Options: * which is discouraged by X.690 specification - default values shall not * be encoded. * NO_TIME_SIGNEDNESS_CHECK: Disabled the time_t signedness check. + * WOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED: Allows the ECDSA/EdDSA signature + * algorithms in certificates to have NULL parameter instead of empty. + * DO NOT enable this unless required for interoperability. */ #include @@ -1092,7 +1097,7 @@ static int GetASN_Integer(const byte* input, word32 idx, int length, * @return 0 on success. * @return ASN_PARSE_E when unused bits is invalid. */ -static int GetASN_BitString(const byte* input, word32 idx, int length) +int GetASN_BitString(const byte* input, word32 idx, int length) { #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)) @@ -1210,7 +1215,7 @@ static int GetASN_ObjectId(const byte* input, word32 idx, int length) /* Last octet of a sub-identifier has bit 8 clear. Last octet must be last * of a subidentifier. Ensure last octet hasn't got top bit set. */ - else if ((input[(int)idx + length - 1] & 0x80) != 0x00) { + else if ((input[(int)idx + length - 1] & 0x80) == 0x80) { WOLFSSL_MSG("OID last octet has top bit set"); ret = ASN_PARSE_E; } @@ -1498,6 +1503,8 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, int minDepth; /* Integer had a zero prepended. */ int zeroPadded; + word32 tmpW32Val; + signed char tmpScharVal; #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE WOLFSSL_ENTER("GetASN_Items"); @@ -1536,14 +1543,18 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, /* Check if first of numbered choice. */ if (choice == 0 && asn[i].optional > 1) { choice = asn[i].optional; - if (choiceMet[choice - 2] == -1) { + tmpScharVal = choiceMet[choice - 2]; + XFENCE(); /* Prevent memory access */ + if (tmpScharVal == -1) { /* Choice seen but not found a match yet. */ choiceMet[choice - 2] = 0; } } /* Check for end of data or not a choice and tag not matching. */ - if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE && + tmpW32Val = endIdx[depth]; + XFENCE(); /* Prevent memory access */ + if (idx == tmpW32Val || (data[i].dataType != ASN_DATA_TYPE_CHOICE && (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) { if (asn[i].optional) { /* Skip over ASN.1 items underneath this optional item. */ @@ -1611,6 +1622,7 @@ int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete, /* Store found tag in data. */ data[i].tag = input[idx]; + XFENCE(); /* Prevent memory access */ if (data[i].dataType != ASN_DATA_TYPE_CHOICE) { int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED; /* Check constructed match expected for non-choice ASN.1 item. */ @@ -2285,7 +2297,7 @@ int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, /* Bottom 7 bits are the number of bytes to calculate length with. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length. */ - word32 bytes = (word32)b & 0x7FU; + int bytes = (int)(b & 0x7F); int minLen; /* Calculate minimum length to be encoded with bytes. */ @@ -2297,15 +2309,16 @@ int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, minLen = 0x80; } /* Only support up to the number of bytes that fit into return var. */ - else if (bytes > sizeof(length)) { + else if (bytes > (int)sizeof(length)) { WOLFSSL_MSG("GetLength - overlong data length spec"); return ASN_PARSE_E; - } else { + } + else { minLen = 1 << ((bytes - 1) * 8); } /* Check the number of bytes required are available. */ - if ((idx + bytes) > maxIdx) { + if ((idx + (word32)bytes) > maxIdx) { WOLFSSL_MSG("GetLength - bad long length"); return BUFFER_E; } @@ -2429,6 +2442,19 @@ static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx, if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) { ret = ASN_PARSE_E; } + if (ret == 0 && tag == ASN_OBJECT_ID) { + if (length < 3) { + /* OID data must be at least 3 bytes. */ + WOLFSSL_MSG("OID length less than 3"); + ret = ASN_PARSE_E; + } + else if ((input[(int)idx + length - 1] & 0x80) == 0x80) { + /* Last octet of a sub-identifier has bit 8 clear. Last octet must be + * last of a subidentifier. Ensure last octet hasn't got top bit set. */ + WOLFSSL_MSG("OID last octet has top bit set"); + ret = ASN_PARSE_E; + } + } if (ret == 0) { /* Return the length of data and index after header. */ *len = length; @@ -2457,7 +2483,7 @@ static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx, * @return BUFFER_E when there is not enough data to parse. * @return ASN_PARSE_E when the expected tag is not found or length is invalid. */ -static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len, +int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len, word32 maxIdx) { return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1); @@ -2690,14 +2716,15 @@ int GetASNInt(const byte* input, word32* inOutIdx, int* len, return ret; if (*len > 0) { - #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY /* check for invalid padding on negative integer. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1 */ if (*len > 1) { - if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80)) - return ASN_PARSE_E; + if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80)) { + WOLFSSL_MSG("Bad INTEGER encoding of negative"); + return ASN_EXPECT_0_E; + } } #endif @@ -2707,8 +2734,10 @@ int GetASNInt(const byte* input, word32* inOutIdx, int* len, (*len)--; #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY - if (*len > 0 && (input[*inOutIdx] & 0x80) == 0) - return ASN_PARSE_E; + if (*len > 0 && (input[*inOutIdx] & 0x80) == 0) { + WOLFSSL_MSG("INTEGER is negative"); + return ASN_EXPECT_0_E; + } #endif } } @@ -3473,7 +3502,7 @@ int CheckBitString(const byte* input, word32* inOutIdx, int* len, } b = input[idx]; - if (zeroBits && b != 0x00) + if (zeroBits && (b != 0x00)) return ASN_EXPECT_0_E; if (b >= 0x08) return ASN_PARSE_E; @@ -3636,14 +3665,14 @@ int StreamOctetString(const byte* inBuf, word32 inBufSz, byte* out, word32* outS } else { *outSz = outIdx; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } } /* Convert BER to DER */ -/* Pull informtation from the ASN.1 BER encoded item header */ +/* Pull information from the ASN.1 BER encoded item header */ static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx, byte* pTag, word32* pLen, int* indef) { @@ -4004,13 +4033,11 @@ int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz) /* Return the length of the DER encoded ASN.1 */ *derSz = j; if (der == NULL) { - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } end: #ifdef WOLFSSL_SMALL_STACK - if (indefItems != NULL) { - XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } @@ -4206,6 +4233,7 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 9}; #endif /* HAVE_FACON */ #ifdef HAVE_DILITHIUM +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT /* Dilithium Level 2: 1.3.6.1.4.1.2.267.12.4.4 */ static const byte sigDilithium_Level2Oid[] = {43, 6, 1, 4, 1, 2, 130, 11, 12, 4, 4}; @@ -4217,6 +4245,19 @@ static word32 SetBitString16Bit(word16 val, byte* output) /* Dilithium Level 5: 1.3.6.1.4.1.2.267.12.8.7 */ static const byte sigDilithium_Level5Oid[] = {43, 6, 1, 4, 1, 2, 130, 11, 12, 8, 7}; +#endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + + /* ML-DSA Level 2: 2.16.840.1.101.3.4.3.17 */ + static const byte sigMlDsa_Level2Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 17}; + + /* ML-DSA Level 3: 2.16.840.1.101.3.4.3.18 */ + static const byte sigMlDsa_Level3Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 18}; + + /* ML-DSA Level 5: 2.16.840.1.101.3.4.3.19 */ + static const byte sigMlDsa_Level5Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 19}; #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */ @@ -4280,6 +4321,7 @@ static word32 SetBitString16Bit(word16 val, byte* output) static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 9}; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT /* Dilithium Level 2: 1.3.6.1.4.1.2.267.12.4.4 */ static const byte keyDilithium_Level2Oid[] = {43, 6, 1, 4, 1, 2, 130, 11, 12, 4, 4}; @@ -4291,6 +4333,19 @@ static word32 SetBitString16Bit(word16 val, byte* output) /* Dilithium Level 5: 1.3.6.1.4.1.2.267.12.8.7 */ static const byte keyDilithium_Level5Oid[] = {43, 6, 1, 4, 1, 2, 130, 11, 12, 8, 7}; +#endif + + /* ML-DSA Level 2: 2.16.840.1.101.3.4.3.17 */ + static const byte keyMlDsa_Level2Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 17}; + + /* ML-DSA Level 3: 2.16.840.1.101.3.4.3.18 */ + static const byte keyMlDsa_Level3Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 18}; + + /* ML-DSA Level 5: 2.16.840.1.101.3.4.3.19 */ + static const byte keyMlDsa_Level5Oid[] = + {96, 134, 72, 1, 101, 3, 4, 3, 19}; #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */ @@ -4834,7 +4889,8 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(sigFalcon_Level5Oid); break; #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM + #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case CTC_DILITHIUM_LEVEL2: oid = sigDilithium_Level2Oid; *oidSz = sizeof(sigDilithium_Level2Oid); @@ -4847,7 +4903,20 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) oid = sigDilithium_Level5Oid; *oidSz = sizeof(sigDilithium_Level5Oid); break; - #endif /* HAVE_DILITHIUM */ + #endif + case CTC_ML_DSA_LEVEL2: + oid = sigMlDsa_Level2Oid; + *oidSz = sizeof(sigMlDsa_Level2Oid); + break; + case CTC_ML_DSA_LEVEL3: + oid = sigMlDsa_Level3Oid; + *oidSz = sizeof(sigMlDsa_Level3Oid); + break; + case CTC_ML_DSA_LEVEL5: + oid = sigMlDsa_Level5Oid; + *oidSz = sizeof(sigMlDsa_Level5Oid); + break; + #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS case CTC_SPHINCS_FAST_LEVEL1: oid = sigSphincsFast_Level1Oid; @@ -4945,7 +5014,8 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) *oidSz = sizeof(keyFalcon_Level5Oid); break; #endif /* HAVE_FALCON */ - #ifdef HAVE_DILITHIUM + #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: oid = keyDilithium_Level2Oid; *oidSz = sizeof(keyDilithium_Level2Oid); @@ -4958,7 +5028,20 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) oid = keyDilithium_Level5Oid; *oidSz = sizeof(keyDilithium_Level5Oid); break; - #endif /* HAVE_DILITHIUM */ + #endif + case ML_DSA_LEVEL2k: + oid = keyMlDsa_Level2Oid; + *oidSz = sizeof(keyMlDsa_Level2Oid); + break; + case ML_DSA_LEVEL3k: + oid = keyMlDsa_Level3Oid; + *oidSz = sizeof(keyMlDsa_Level3Oid); + break; + case ML_DSA_LEVEL5k: + oid = keyMlDsa_Level5Oid; + *oidSz = sizeof(keyMlDsa_Level5Oid); + break; + #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS case SPHINCS_FAST_LEVEL1k: oid = keySphincsFast_Level1Oid; @@ -5625,7 +5708,7 @@ int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz) } /* compute length of encoded OID */ - d = (in[0] * 40) + in[1]; + d = ((word32)in[0] * 40) + in[1]; len = 0; for (i = 1; i < (int)inSz; i++) { x = 0; @@ -5648,7 +5731,7 @@ int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz) } /* calc first byte */ - d = (in[0] * 40) + in[1]; + d = ((word32)in[0] * 40) + in[1]; /* encode bytes */ x = 0; @@ -5683,14 +5766,13 @@ int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz) } /* return length */ - *outSz = len; + *outSz = (word32)len; return 0; } #endif /* HAVE_OID_ENCODING */ -#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) || \ - defined(OPENSSL_ALL) +#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) /* Encode dotted form of OID into byte array version. * * @param [in] in Byte array containing OID. @@ -5737,7 +5819,7 @@ int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz) return 0; } -#endif /* HAVE_OID_DECODING || WOLFSSL_ASN_PRINT || OPENSSL_ALL */ +#endif /* HAVE_OID_DECODING || WOLFSSL_ASN_PRINT */ /* Decode the header of a BER/DER encoded OBJECT ID. * @@ -6047,22 +6129,8 @@ enum { #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem)) #endif -/* Get the OID id/sum from the BER encoding of an algorithm identifier. - * - * NULL tag is skipped if present. - * - * @param [in] input Buffer holding BER encoded data. - * @param [in, out] inOutIdx On in, start of algorithm identifier. - * On out, start of ASN.1 item after algorithm id. - * @param [out] oid Id of OID in algorithm identifier data. - * @param [in] oidType Type of OID to expect. - * @param [in] maxIdx Maximum index of data in buffer. - * @return 0 on success. - * @return ASN_PARSE_E when encoding is invalid. - * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. - */ -int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, - word32 oidType, word32 maxIdx) +static int GetAlgoIdImpl(const byte* input, word32* inOutIdx, word32* oid, + word32 oidType, word32 maxIdx, byte *absentParams) { #ifndef WOLFSSL_ASN_TEMPLATE int length; @@ -6088,6 +6156,10 @@ int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, ret = GetASNNull(input, &idx, maxIdx); if (ret != 0) return ret; + + if (absentParams != NULL) { + *absentParams = FALSE; + } } } } @@ -6112,6 +6184,11 @@ int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, if (ret == 0) { /* Return the OID id/sum. */ *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum; + + if ((absentParams != NULL) && + (dataASN[ALGOIDASN_IDX_NULL].tag == ASN_TAG_NULL)) { + *absentParams = FALSE; + } } FREE_ASNGETDATA(dataASN, NULL); @@ -6119,6 +6196,37 @@ int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, #endif /* WOLFSSL_ASN_TEMPLATE */ } +/* Get the OID id/sum from the BER encoding of an algorithm identifier. + * + * NULL tag is skipped if present. + * + * @param [in] input Buffer holding BER encoded data. + * @param [in, out] inOutIdx On in, start of algorithm identifier. + * On out, start of ASN.1 item after algorithm id. + * @param [out] oid Id of OID in algorithm identifier data. + * @param [in] oidType Type of OID to expect. + * @param [in] maxIdx Maximum index of data in buffer. + * @return 0 on success. + * @return ASN_PARSE_E when encoding is invalid. + * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. + */ +int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, + word32 oidType, word32 maxIdx) +{ + return GetAlgoIdImpl(input, inOutIdx, oid, oidType, maxIdx, NULL); +} + +int GetAlgoIdEx(const byte* input, word32* inOutIdx, word32* oid, + word32 oidType, word32 maxIdx, byte *absentParams) +{ + /* Assume absent until proven otherwise */ + if (absentParams != NULL) { + *absentParams = TRUE; + } + + return GetAlgoIdImpl(input, inOutIdx, oid, oidType, maxIdx, absentParams); +} + #ifndef NO_RSA #ifdef WC_RSA_PSS @@ -6210,7 +6318,8 @@ static int RsaPssHashOidToMgf1(word32 oid, int* mgf) return ret; } -#ifndef NO_CERTS +#if !defined(NO_CERTS) && !defined(NO_ASN_CRYPT) + /* Convert a hash OID to a fake signature OID. * * @param [in] oid Hash OID. @@ -6261,7 +6370,7 @@ static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid) #endif #ifdef WOLFSSL_ASN_TEMPLATE -/* ASN tag for hashAlgorigthm. */ +/* ASN tag for hashAlgorithm. */ #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0) /* ASN tag for maskGenAlgorithm. */ #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1) @@ -6309,7 +6418,7 @@ enum { /* Number of items in ASN.1 template for an algorithm identifier. */ #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem)) #else -/* ASN tag for hashAlgorigthm. */ +/* ASN tag for hashAlgorithm. */ #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0) /* ASN tag for maskGenAlgorithm. */ #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) @@ -6829,8 +6938,9 @@ static const ASNItem pkcs8KeyASN[] = { /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 }, #endif /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 }, - /* attributes [0] Attributes OPTIONAL */ - /* [[2: publicKey [1] PublicKey OPTIONAL ]] */ +/* OPTIONAL Attributes IMPLICIT [0] */ + { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 }, +/* [[2: publicKey [1] PublicKey OPTIONAL ]] */ }; enum { PKCS8KEYASN_IDX_SEQ = 0, @@ -6843,6 +6953,7 @@ enum { PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ, #endif PKCS8KEYASN_IDX_PKEY_DATA, + PKCS8KEYASN_IDX_PKEY_ATTRIBUTES, WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX) }; @@ -6857,6 +6968,7 @@ enum { * On out, start of encoded key. * @param [in] sz Size of data in buffer. * @param [out] algId Key's algorithm id from PKCS #8 header. + * @param [out] eccOid ECC curve OID. * @return Length of key data on success. * @return BAD_FUNC_ARG when input or inOutIdx is NULL. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or @@ -6866,8 +6978,8 @@ enum { * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a * non-zero length. */ -int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, - word32* algId) +int ToTraditionalInline_ex2(const byte* input, word32* inOutIdx, word32 sz, + word32* algId, word32* eccOid) { #ifndef WOLFSSL_ASN_TEMPLATE word32 idx; @@ -6917,8 +7029,14 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, #endif /* WC_RSA_PSS && !NO_RSA */ if (tag == ASN_OBJECT_ID) { - if (SkipObjectId(input, &idx, sz) < 0) - return ASN_PARSE_E; + if ((*algId == ECDSAk) && (eccOid != NULL)) { + if (GetObjectId(input, &idx, eccOid, oidCurveType, sz) < 0) + return ASN_PARSE_E; + } + else { + if (SkipObjectId(input, &idx, sz) < 0) + return ASN_PARSE_E; + } } ret = GetOctetString(input, &idx, &length, sz); @@ -6939,6 +7057,8 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, byte version = 0; word32 idx; + (void)eccOid; + /* Check validity of parameters. */ if (input == NULL || inOutIdx == NULL) { return BAD_FUNC_ARG; @@ -7012,6 +7132,11 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) { ret = ASN_PARSE_E; } + if (eccOid != NULL) { + ASNGetData* oidCurve = + &dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE]; + *eccOid = oidCurve->data.oid.sum; + } break; #endif #ifdef HAVE_ED25519 @@ -7049,6 +7174,15 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, ret = ASN_PARSE_E; } break; + #endif + #ifndef NO_DH + case DHk: + /* Neither NULL item nor OBJECT_ID item allowed. */ + if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) || + (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) { + ret = ASN_PARSE_E; + } + break; #endif /* DSAk not supported. */ /* Falcon, Dilithium and Sphincs not supported. */ @@ -7071,6 +7205,29 @@ int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, #endif } +/* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448. + * + * @param [in] input Buffer holding BER data. + * @param [in, out] inOutIdx On in, start of PKCS #8 encoding. + * On out, start of encoded key. + * @param [in] sz Size of data in buffer. + * @param [out] algId Key's algorithm id from PKCS #8 header. + * @return Length of key data on success. + * @return BAD_FUNC_ARG when input or inOutIdx is NULL. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found. + * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a + * non-zero length. + */ +int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz, + word32* algId) +{ + return ToTraditionalInline_ex2(input, inOutIdx, sz, algId, NULL); +} + + /* TODO: test case */ int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz) { @@ -7146,7 +7303,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, WOLFSSL_MSG("Checking size of PKCS8"); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } WOLFSSL_ENTER("wc_CreatePKCS8Key"); @@ -7216,7 +7373,9 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, *outSz = tmpSz + sz; return (int)(tmpSz + sz); #else - DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length); + /* pkcs8KeyASN_Length-1, the -1 is because we are not adding the optional + * set of attributes */ + DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length-1); int sz = 0; int ret = 0; word32 keyIdx = 0; @@ -7237,7 +7396,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, ret = ASN_PARSE_E; } - CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL); + CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length-1, ret, NULL); if (ret == 0) { /* Only support default PKCS #8 format - v0. */ @@ -7263,7 +7422,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz); /* Get the size of the DER encoding. */ - ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz); + ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length-1, &sz); } if (ret == 0) { /* Always return the calculated size. */ @@ -7272,11 +7431,11 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, /* Check for buffer to encoded into. */ if ((ret == 0) && (out == NULL)) { WOLFSSL_MSG("Checking size of PKCS8"); - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (ret == 0) { /* Encode PKCS #8 key into buffer. */ - SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out); + SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length-1, out); ret = sz; } @@ -7296,9 +7455,11 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, * privKeySz : size of private key buffer * pubKey : buffer holding DER format public key * pubKeySz : size of public key buffer - * ks : type of key */ + * ks : type of key + * heap : heap hint to use */ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, - const byte* pubKey, word32 pubKeySz, enum Key_Sum ks) + const byte* pubKey, word32 pubKeySz, enum Key_Sum ks, + void* heap) { int ret; (void)privKeySz; @@ -7335,14 +7496,14 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, } #endif - if ((ret = wc_InitRsaKey(a, NULL)) < 0) { + if ((ret = wc_InitRsaKey(a, heap)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(b, NULL, DYNAMIC_TYPE_RSA); XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return ret; } - if ((ret = wc_InitRsaKey(b, NULL)) < 0) { + if ((ret = wc_InitRsaKey(b, heap)) < 0) { wc_FreeRsaKey(a); #ifdef WOLFSSL_SMALL_STACK XFREE(b, NULL, DYNAMIC_TYPE_RSA); @@ -7403,7 +7564,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, } #endif - if ((ret = wc_ecc_init(key_pair)) < 0) { + if ((ret = wc_ecc_init_ex(key_pair, heap, INVALID_DEVID)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER); XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC); @@ -7421,7 +7582,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz); #endif wc_ecc_free(key_pair); - ret = wc_ecc_init(key_pair); + ret = wc_ecc_init_ex(key_pair, heap, INVALID_DEVID); if (ret == 0) { ret = wc_ecc_import_private_key(privDer, privSz, pubKey, @@ -7472,7 +7633,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, return MEMORY_E; #endif - if ((ret = wc_ed25519_init(key_pair)) < 0) { + if ((ret = wc_ed25519_init_ex(key_pair, heap, INVALID_DEVID)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519); #endif @@ -7522,7 +7683,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, return MEMORY_E; #endif - if ((ret = wc_ed448_init(key_pair)) < 0) { + if ((ret = wc_ed448_init_ex(key_pair, heap, INVALID_DEVID)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448); #endif @@ -7618,9 +7779,15 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) - if ((ks == DILITHIUM_LEVEL2k) || - (ks == DILITHIUM_LEVEL3k) || - (ks == DILITHIUM_LEVEL5k)) { + if ((ks == ML_DSA_LEVEL2k) || + (ks == ML_DSA_LEVEL3k) || + (ks == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (ks == DILITHIUM_LEVEL2k) + || (ks == DILITHIUM_LEVEL3k) + || (ks == DILITHIUM_LEVEL5k) + #endif + ) { #ifdef WOLFSSL_SMALL_STACK dilithium_key* key_pair = NULL; #else @@ -7642,15 +7809,27 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, return ret; } - if (ks == DILITHIUM_LEVEL2k) { - ret = wc_dilithium_set_level(key_pair, 2); + + if (ks == ML_DSA_LEVEL2k) { + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_44); + } + else if (ks == ML_DSA_LEVEL3k) { + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_65); + } + else if (ks == ML_DSA_LEVEL5k) { + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_87); + } + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if (ks == DILITHIUM_LEVEL2k) { + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_44_DRAFT); } else if (ks == DILITHIUM_LEVEL3k) { - ret = wc_dilithium_set_level(key_pair, 3); + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_65_DRAFT); } else if (ks == DILITHIUM_LEVEL5k) { - ret = wc_dilithium_set_level(key_pair, 5); + ret = wc_dilithium_set_level(key_pair, WC_ML_DSA_87_DRAFT); } + #endif if (ret < 0) { #ifdef WOLFSSL_SMALL_STACK @@ -7751,6 +7930,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, ret = 0; } (void)ks; + (void)heap; return ret; } @@ -7765,7 +7945,7 @@ int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, * checkAlt : indicate if we check primary or alternative key */ int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der, - int checkAlt) + int checkAlt, void* heap) { int ret = 0; @@ -7779,7 +7959,7 @@ int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der, word32 idx = 0; /* Dilithium has the largest public key at the moment */ word32 pubKeyLen = DILITHIUM_MAX_PUB_KEY_SIZE; - byte* decodedPubKey = (byte*)XMALLOC(pubKeyLen, NULL, + byte* decodedPubKey = (byte*)XMALLOC(pubKeyLen, heap, DYNAMIC_TYPE_PUBLIC_KEY); if (decodedPubKey == NULL) { ret = MEMORY_E; @@ -7798,15 +7978,15 @@ int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der, } if (ret == 0) { ret = wc_CheckPrivateKey(key, keySz, decodedPubKey, pubKeyLen, - (enum Key_Sum) der->sapkiOID); + (enum Key_Sum) der->sapkiOID, heap); } - XFREE(decodedPubKey, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + XFREE(decodedPubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); } else #endif { ret = wc_CheckPrivateKey(key, keySz, der->publicKey, - der->pubKeySize, (enum Key_Sum) der->keyOID); + der->pubKeySize, (enum Key_Sum) der->keyOID, heap); } (void)checkAlt; @@ -8136,31 +8316,28 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, if (wc_dilithium_init(dilithium) != 0) { tmpIdx = 0; - if (wc_dilithium_set_level(dilithium, 2) - == 0) { + if (wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) { if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, - keySz) == 0) { - *algoID = DILITHIUM_LEVEL2k; + keySz) == 0) { + *algoID = ML_DSA_LEVEL2k; } else { WOLFSSL_MSG("Not Dilithium Level 2 DER key"); } } - else if (wc_dilithium_set_level(dilithium, 3) - == 0) { + else if (wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) { if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, - keySz) == 0) { - *algoID = DILITHIUM_LEVEL3k; + keySz) == 0) { + *algoID = ML_DSA_LEVEL3k; } else { WOLFSSL_MSG("Not Dilithium Level 3 DER key"); } } - else if (wc_dilithium_set_level(dilithium, 5) - == 0) { + else if (wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) { if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, - keySz) == 0) { - *algoID = DILITHIUM_LEVEL5k; + keySz) == 0) { + *algoID = ML_DSA_LEVEL5k; } else { WOLFSSL_MSG("Not Dilithium Level 5 DER key"); @@ -8479,7 +8656,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, if (out == NULL) { /* Sequence tag, length */ *outSz = 1 + SetLength(outerLen, NULL) + outerLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } SetOctetString(keySz + padSz, out); @@ -8562,9 +8739,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, } #ifdef WOLFSSL_SMALL_STACK - if (saltTmp != NULL) { - XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); #endif WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret); @@ -9064,7 +9239,7 @@ static const ASNItem p8EncPbes1ASN[] = { /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 }, /* Iteration Count */ /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 }, -/* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 }, +/* ENCDATA */ { 1, (ASN_CONTEXT_SPECIFIC | 0), 0, 0, 0 }, }; enum { P8ENCPBES1ASN_IDX_SEQ = 0, @@ -9123,7 +9298,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, word32 seqSz; word32 innerSz; int ret; - int version, id, blockSz = 0; + int version, id = PBE_NONE, blockSz = 0; #ifdef WOLFSSL_SMALL_STACK byte* saltTmp = NULL; byte* cbcIv = NULL; @@ -9195,7 +9370,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, if (out == NULL) { *outSz = totalSz; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } inOutIdx = 0; @@ -9351,7 +9526,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, /* Return size when no output buffer. */ if ((ret == 0) && (out == NULL)) { *outSz = (word32)sz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* Check output buffer is big enough for encoded data. */ if ((ret == 0) && (sz > (int)*outSz)) { @@ -9398,6 +9573,42 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, #endif /* NO_PWDBASED */ #ifndef NO_RSA +#ifdef WOLFSSL_ASN_TEMPLATE +/* ASN.1 template for an RSA public key. + * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo + * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey + */ +static const ASNItem rsaPublicKeyASN[] = { +/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, +/* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, +/* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 }, +#ifdef WC_RSA_PSS +/* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 }, +#endif +/* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 }, + /* RSAPublicKey */ +/* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, +/* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 }, +/* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 }, +}; +enum { + RSAPUBLICKEYASN_IDX_SEQ = 0, + RSAPUBLICKEYASN_IDX_ALGOID_SEQ, + RSAPUBLICKEYASN_IDX_ALGOID_OID, + RSAPUBLICKEYASN_IDX_ALGOID_NULL, +#ifdef WC_RSA_PSS + RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ, +#endif + RSAPUBLICKEYASN_IDX_PUBKEY, + RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ, + RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N, + RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E +}; + +/* Number of items in ASN.1 template for an RSA public key. */ +#define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem)) +#endif #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) /* This function is to retrieve key position information in a cert.* @@ -9408,9 +9619,10 @@ static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx, word32* key_n_len, word32* key_e, word32* key_e_len) { - +#ifndef WOLFSSL_ASN_TEMPLATE int ret = 0; int length = 0; + #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA) byte b; #endif @@ -9473,48 +9685,31 @@ static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx, } if (key_e_len) *key_e_len = length; - return ret; -} -#endif /* WOLFSSL_RENESAS_TSIP */ - -#ifdef WOLFSSL_ASN_TEMPLATE -/* ASN.1 template for an RSA public key. - * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo - * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey - */ -static const ASNItem rsaPublicKeyASN[] = { -/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, -/* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, -/* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 }, -/* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 }, -#ifdef WC_RSA_PSS -/* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 }, -#endif -/* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 }, - /* RSAPublicKey */ -/* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, -/* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 }, -/* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 }, -}; -enum { - RSAPUBLICKEYASN_IDX_SEQ = 0, - RSAPUBLICKEYASN_IDX_ALGOID_SEQ, - RSAPUBLICKEYASN_IDX_ALGOID_OID, - RSAPUBLICKEYASN_IDX_ALGOID_NULL, -#ifdef WC_RSA_PSS - RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ, -#endif - RSAPUBLICKEYASN_IDX_PUBKEY, - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ, - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N, - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E -}; +#else + int ret = 0; + const byte* n = NULL; + const byte* e = NULL; /* pointer to modulus/exponent */ + word32 rawIndex = 0; -/* Number of items in ASN.1 template for an RSA public key. */ -#define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem)) + ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, (word32)inSz, + &n, key_n_len, &e, key_e_len); + if (ret == 0) { + /* convert pointer to offset */ + if (key_n != NULL) { + rawIndex = n - input; + *key_n += rawIndex; + } + if (key_e != NULL) { + rawIndex = e - input; + *key_e += rawIndex; + } + } + return ret; #endif +} +#endif /* WOLFSSL_RENESAS_TSIP */ /* Decode RSA public key. * * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo @@ -10126,7 +10321,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) /* if no output, then just getting size */ if (output == NULL) { *outSz = total; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* make sure output fits in buffer */ @@ -10201,7 +10396,7 @@ int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv) ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz); if (output == NULL) { *outSz = (word32)sz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* Check buffer is big enough for encoding. */ if ((ret == 0) && ((int)*outSz < sz)) { @@ -10265,7 +10460,7 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) if (output == NULL) { *outSz = idx; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* make sure output fits in buffer */ if (idx > *outSz) { @@ -10313,7 +10508,7 @@ int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz) } if ((ret == 0) && (output == NULL)) { *outSz = (word32)sz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* Check buffer is big enough for encoding. */ if ((ret == 0) && (*outSz < (word32)sz)) { @@ -11164,7 +11359,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, *inLen = outLen; if (output == NULL) { FreeTmpDsas(tmps, key->heap, ints); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (outLen > *inLen) { FreeTmpDsas(tmps, key->heap, ints); @@ -11226,7 +11421,7 @@ static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen, } if ((ret == 0) && (output == NULL)) { *inLen = (word32)sz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* Check buffer is big enough for encoding. */ if ((ret == 0) && (sz > (int)*inLen)) { @@ -11277,7 +11472,7 @@ int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen) } /* This version of the function allows output to be NULL. In that case, the - DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer + DsaKeyIntsToDer will return WC_NO_ERR_TRACE(LENGTH_ONLY_E) and the required output buffer size will be pointed to by inLen. */ int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen) { @@ -11373,10 +11568,10 @@ void FreeAltNames(DNS_entry* altNames, void* heap) DNS_entry* tmp = altNames->next; XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME); - #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) + #ifdef WOLFSSL_IP_ALT_NAME XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME); #endif - #if defined(OPENSSL_ALL) + #ifdef WOLFSSL_RID_ALT_NAME XFREE(altNames->ridString, heap, DYNAMIC_TYPE_ALTNAME); #endif XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME); @@ -11411,17 +11606,17 @@ DNS_entry* AltNameDup(DNS_entry* from, void* heap) ret->name = CopyString(from->name, from->len, heap, DYNAMIC_TYPE_ALTNAME); -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME ret->ipString = CopyString(from->ipString, 0, heap, DYNAMIC_TYPE_ALTNAME); #endif -#ifdef OPENSSL_ALL +#ifdef WOLFSSL_RID_ALT_NAME ret->ridString = CopyString(from->ridString, 0, heap, DYNAMIC_TYPE_ALTNAME); #endif if (ret->name == NULL -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME || (from->ipString != NULL && ret->ipString == NULL) #endif -#ifdef OPENSSL_ALL +#ifdef WOLFSSL_RID_ALT_NAME || (from->ridString != NULL && ret->ridString == NULL) #endif ) { @@ -11500,8 +11695,7 @@ void FreeDecodedCert(DecodedCert* cert) wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName); #endif /* WOLFSSL_X509_NAME_AVAILABLE */ #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) - if (cert->sce_tsip_encRsaKeyIdx != NULL) - XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA); + XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA); #endif FreeSignatureCtx(&cert->sigCtx); } @@ -11534,9 +11728,11 @@ static int GetCertHeader(DecodedCert* cert) cert->sigIndex) < 0) return ASN_PARSE_E; - if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial, - &cert->serialSz, cert->sigIndex) < 0) - return ASN_PARSE_E; + ret = wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial, + &cert->serialSz, cert->sigIndex); + if (ret < 0) { + return ret; + } return ret; } @@ -11782,7 +11978,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, pubSz = 1 + pubSz; else pubSz = 1 + 2 * pubSz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); #else ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp); #endif @@ -11902,34 +12098,38 @@ int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve) #ifdef WOLFSSL_ASN_TEMPLATE #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT) -/* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo). +/* ASN.1 template for the SubjectPublicKeyInfo of a general asymmetric key. + * Used with Ed448/Ed25519, Curve448/Curve25519, SPHINCS+, falcon, dilithium, + * etc. + * + * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo * RFC 8410, 4 - Subject Public Key Fields */ -static const ASNItem edPubKeyASN[] = { +static const ASNItem publicKeyASN[] = { /* SubjectPublicKeyInfo */ /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* AlgorithmIdentifier */ /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, - /* Ed25519/Ed448 OID */ + /* Ed25519/Ed448 OID, etc. */ /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 }, /* Public key stream */ /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 }, }; enum { - EDPUBKEYASN_IDX_SEQ = 0, - EDPUBKEYASN_IDX_ALGOID_SEQ, - EDPUBKEYASN_IDX_ALGOID_OID, - EDPUBKEYASN_IDX_PUBKEY + PUBKEYASN_IDX_SEQ = 0, + PUBKEYASN_IDX_ALGOID_SEQ, + PUBKEYASN_IDX_ALGOID_OID, + PUBKEYASN_IDX_PUBKEY }; -/* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */ -#define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem)) +/* Number of items in ASN.1 template for public key SubjectPublicKeyInfo. */ +#define publicKeyASN_Length (sizeof(publicKeyASN) / sizeof(ASNItem)) #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */ #endif /* WOLFSSL_ASN_TEMPLATE */ #ifdef WC_ENABLE_ASYM_KEY_EXPORT -/* Build ASN.1 formatted public key based on RFC 8410 +/* Build ASN.1 formatted public key based on RFC 5280 and RFC 8410 * * Pass NULL for output to get the size of the encoding. * @@ -11953,12 +12153,16 @@ int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, word32 sz; #else int sz = 0; - DECL_ASNSETDATA(dataASN, edPubKeyASN_Length); + DECL_ASNSETDATA(dataASN, publicKeyASN_Length); #endif - if (pubKey == NULL) { + /* validate parameters */ + if (pubKey == NULL){ return BAD_FUNC_ARG; } + if (output != NULL && outLen == 0) { + return BUFFER_E; + } #ifndef WOLFSSL_ASN_TEMPLATE /* calculate size */ @@ -12001,25 +12205,26 @@ int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, } #else if (withHeader) { - CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL); + CALLOC_ASNSETDATA(dataASN, publicKeyASN_Length, ret, NULL); if (ret == 0) { /* Set the OID. */ - SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType, + SetASN_OID(&dataASN[PUBKEYASN_IDX_ALGOID_OID], (word32)keyType, oidKeyType); /* Leave space for public point. */ - SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen); + SetASN_Buffer(&dataASN[PUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen); /* Calculate size of public key encoding. */ - ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz); + ret = SizeASN_Items(publicKeyASN, dataASN, publicKeyASN_Length, + &sz); } if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) { ret = BUFFER_E; } if ((ret == 0) && (output != NULL)) { /* Encode public key. */ - SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output); + SetASN_Items(publicKeyASN, dataASN, publicKeyASN_Length, output); /* Set location to encode public point. */ - output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data; + output = (byte*)dataASN[PUBKEYASN_IDX_PUBKEY].data.buffer.data; } FREE_ASNSETDATA(dataASN, NULL); @@ -12627,16 +12832,15 @@ static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx, break; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: - cert->pkCurveOID = DILITHIUM_LEVEL2k; - ret = StoreKey(cert, source, &srcIdx, maxIdx); - break; case DILITHIUM_LEVEL3k: - cert->pkCurveOID = DILITHIUM_LEVEL3k; - ret = StoreKey(cert, source, &srcIdx, maxIdx); - break; case DILITHIUM_LEVEL5k: - cert->pkCurveOID = DILITHIUM_LEVEL5k; + #endif + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: + cert->pkCurveOID = cert->keyOID; ret = StoreKey(cert, source, &srcIdx, maxIdx); break; #endif /* HAVE_DILITHIUM */ @@ -13264,7 +13468,7 @@ static const byte rdnChoice[] = { }; #endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME /* used to set the human readable string for the IP address with a ASN_IP_TYPE * DNS entry * return 0 on success @@ -13273,7 +13477,7 @@ static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap) { int ret = 0; size_t nameSz = 0; - char tmpName[WOLFSSL_MAX_IPSTR] = {0}; + char tmpName[WOLFSSL_MAX_IPSTR]; unsigned char* ip; if (entry == NULL || entry->type != ASN_IP_TYPE) { @@ -13287,6 +13491,8 @@ static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap) } ip = (unsigned char*)entry->name; + XMEMSET(tmpName, 0, sizeof(tmpName)); + /* store IP addresses as a string */ if (entry->len == WOLFSSL_IP4_ADDR_LEN) { if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0], @@ -13328,9 +13534,9 @@ static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap) return ret; } -#endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ +#endif /* WOLFSSL_IP_ALT_NAME */ -#if defined(OPENSSL_ALL) +#ifdef WOLFSSL_RID_ALT_NAME /* used to set the human readable string for the registeredID with an * ASN_RID_TYPE DNS entry * return 0 on success @@ -13339,7 +13545,9 @@ static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) { int i, j, ret = 0; int nameSz = 0; +#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) int nid = 0; +#endif int tmpSize = MAX_OID_SZ; word32 oid = 0; word32 idx = 0; @@ -13359,47 +13567,53 @@ static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) ret = GetOID((const byte*)entry->name, &idx, &oid, oidIgnoreType, entry->len); + if (ret == 0) { + #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) + if ((nid = oid2nid(oid, oidCsrAttrType)) > 0) { + /* OID has known string value */ + finalName = (char*)wolfSSL_OBJ_nid2ln(nid); + } + else + #endif + { + /* Decode OBJECT_ID into dotted form array. */ + ret = DecodeObjectId((const byte*)(entry->name),(word32)entry->len, + tmpName, (word32*)&tmpSize); - if (ret == 0 && (nid = oid2nid(oid, oidCsrAttrType)) > 0) { - /* OID has known string value */ - finalName = (char*)wolfSSL_OBJ_nid2ln(nid); - } - else { - /* Decode OBJECT_ID into dotted form array. */ - ret = DecodeObjectId((const byte*)(entry->name),(word32)entry->len, - tmpName, (word32*)&tmpSize); - - if (ret == 0) { - j = 0; - /* Append each number of dotted form. */ - for (i = 0; i < tmpSize; i++) { - if (j >= MAX_OID_SZ) { - return BUFFER_E; - } + if (ret == 0) { + j = 0; + /* Append each number of dotted form. */ + for (i = 0; i < tmpSize; i++) { + if (j >= MAX_OID_SZ) { + return BUFFER_E; + } - if (i < tmpSize - 1) { - ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d.", tmpName[i]); - } - else { - ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d", tmpName[i]); - } + if (i < tmpSize - 1) { + ret = XSNPRINTF(oidName + j, (word32)(MAX_OID_SZ - j), + "%d.", tmpName[i]); + } + else { + ret = XSNPRINTF(oidName + j, (word32)(MAX_OID_SZ - j), + "%d", tmpName[i]); + } - if (ret >= 0) { - j += ret; - } - else { - return BUFFER_E; + if (ret >= 0) { + j += ret; + } + else { + return BUFFER_E; + } } + ret = 0; + finalName = oidName; } - ret = 0; - finalName = oidName; } } if (ret == 0) { nameSz = (int)XSTRLEN((const char*)finalName); - entry->ridString = (char*)XMALLOC(nameSz + 1, heap, + entry->ridString = (char*)XMALLOC((word32)(nameSz + 1), heap, DYNAMIC_TYPE_ALTNAME); if (entry->ridString == NULL) { @@ -13407,13 +13621,13 @@ static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) } if (ret == 0) { - XMEMCPY(entry->ridString, finalName, nameSz + 1); + XMEMCPY(entry->ridString, finalName, (word32)(nameSz + 1)); } } return ret; } -#endif /* OPENSSL_ALL && WOLFSSL_ASN_TEMPLATE */ +#endif /* WOLFSSL_RID_ALT_NAME */ #ifdef WOLFSSL_ASN_TEMPLATE @@ -13454,7 +13668,7 @@ static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry) /* Allocate a DNS entry and set the fields. * - * @param [in] cert Certificate object. + * @param [in] heap Heap hint. * @param [in] str DNS name string. * @param [in] strLen Length of DNS name string. * @param [in] type Type of DNS name string. @@ -13462,27 +13676,23 @@ static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry) * @return 0 on success. * @return MEMORY_E when dynamic memory allocation fails. */ -static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, +static int SetDNSEntry(void* heap, const char* str, int strLen, int type, DNS_entry** entries) { DNS_entry* dnsEntry; int ret = 0; - /* Only used for heap. */ - (void)cert; - /* TODO: consider one malloc. */ /* Allocate DNS Entry object. */ - dnsEntry = AltNameNew(cert->heap); + dnsEntry = AltNameNew(heap); if (dnsEntry == NULL) { ret = MEMORY_E; } if (ret == 0) { /* Allocate DNS Entry name - length of string plus 1 for NUL. */ - dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap, + dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, heap, DYNAMIC_TYPE_ALTNAME); if (dnsEntry->name == NULL) { - XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); ret = MEMORY_E; } } @@ -13493,29 +13703,27 @@ static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen, XMEMCPY(dnsEntry->name, str, (size_t)strLen); dnsEntry->name[strLen] = '\0'; -#if defined(OPENSSL_ALL) +#ifdef WOLFSSL_RID_ALT_NAME /* store registeredID as a string */ - if (type == ASN_RID_TYPE) { - if ((ret = GenerateDNSEntryRIDString(dnsEntry, cert->heap)) != 0) { - XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME); - XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); - } - } + if (type == ASN_RID_TYPE) + ret = GenerateDNSEntryRIDString(dnsEntry, heap); #endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) - /* store IP addresses as a string */ - if (type == ASN_IP_TYPE) { - if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) { - XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME); - XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME); - } - } } - if (ret == 0) { +#ifdef WOLFSSL_IP_ALT_NAME + /* store IP addresses as a string */ + if (ret == 0 && type == ASN_IP_TYPE) + ret = GenerateDNSEntryIPString(dnsEntry, heap); #endif + if (ret == 0) { ret = AddDNSEntryToList(entries, dnsEntry); } + /* failure cleanup */ + if (ret != 0 && dnsEntry != NULL) { + XFREE(dnsEntry->name, heap, DYNAMIC_TYPE_ALTNAME); + XFREE(dnsEntry, heap, DYNAMIC_TYPE_ALTNAME); + } + return ret; } #endif @@ -13774,7 +13982,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, * @param [in, out] cert Decoded certificate object. * @param [out] full Buffer to hold full name as a string. * @param [out] hash Buffer to hold hash of name. - * @param [in] nameType ISSUER or SUBJECT. + * @param [in] nameType ASN_ISSUER or ASN_SUBJECT. * @param [in] input Buffer holding certificate name. * @param [in, out] inOutIdx On in, start of certificate name. * On out, start of ASN.1 item after cert name. @@ -13829,13 +14037,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT) /* store pointer to raw issuer */ - if (nameType == ISSUER) { + if (nameType == ASN_ISSUER) { cert->issuerRaw = &input[srcIdx]; cert->issuerRawLen = length; } #endif #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectRaw = &input[srcIdx]; cert->subjectRawLen = length; } @@ -13904,26 +14112,30 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, } #ifndef WOLFSSL_NO_ASN_STRICT - /* RFC 5280 section 4.1.2.4 lists a DirecotryString as being + /* RFC 5280 section 4.1.2.4 lists a DirectoryString as being * 1..MAX in length */ if (strLen < 1) { WOLFSSL_MSG("Non conforming DirectoryString of length 0 was" " found"); WOLFSSL_MSG("Use WOLFSSL_NO_ASN_STRICT if wanting to allow" " empty DirectoryString's"); + #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ + !defined(WOLFCRYPT_ONLY) + wolfSSL_X509_NAME_free(dName); + #endif /* OPENSSL_EXTRA */ return ASN_PARSE_E; } #endif if (id == ASN_COMMON_NAME) { - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectCN = (char *)&input[srcIdx]; cert->subjectCNLen = strLen; cert->subjectCNEnc = (char)b; } #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \ defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerCN = (char*)&input[srcIdx]; cert->issuerCNLen = strLen; cert->issuerCNEnc = (char)b; @@ -13942,7 +14154,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_NAME; copyLen = sizeof(WOLFSSL_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectN = (char*)&input[srcIdx]; cert->subjectNLen = strLen; cert->subjectNEnc = b; @@ -13958,7 +14170,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_INITIALS; copyLen = sizeof(WOLFSSL_INITIALS) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectI = (char*)&input[srcIdx]; cert->subjectILen = strLen; cert->subjectIEnc = b; @@ -13974,7 +14186,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_GIVEN_NAME; copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectGN = (char*)&input[srcIdx]; cert->subjectGNLen = strLen; cert->subjectGNEnc = b; @@ -13990,7 +14202,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_DNQUALIFIER; copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectDNQ = (char*)&input[srcIdx]; cert->subjectDNQLen = strLen; cert->subjectDNQEnc = b; @@ -14007,13 +14219,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_SUR_NAME; copyLen = sizeof(WOLFSSL_SUR_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectSN = (char*)&input[srcIdx]; cert->subjectSNLen = strLen; cert->subjectSNEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerSN = (char*)&input[srcIdx]; cert->issuerSNLen = strLen; cert->issuerSNEnc = (char)b; @@ -14030,13 +14242,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_COUNTRY_NAME; copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectC = (char*)&input[srcIdx]; cert->subjectCLen = strLen; cert->subjectCEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerC = (char*)&input[srcIdx]; cert->issuerCLen = strLen; cert->issuerCEnc = (char)b; @@ -14053,13 +14265,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_LOCALITY_NAME; copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectL = (char*)&input[srcIdx]; cert->subjectLLen = strLen; cert->subjectLEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerL = (char*)&input[srcIdx]; cert->issuerLLen = strLen; cert->issuerLEnc = (char)b; @@ -14076,13 +14288,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_STATE_NAME; copyLen = sizeof(WOLFSSL_STATE_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectST = (char*)&input[srcIdx]; cert->subjectSTLen = strLen; cert->subjectSTEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerST = (char*)&input[srcIdx]; cert->issuerSTLen = strLen; cert->issuerSTEnc = (char)b; @@ -14099,13 +14311,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_ORG_NAME; copyLen = sizeof(WOLFSSL_ORG_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectO = (char*)&input[srcIdx]; cert->subjectOLen = strLen; cert->subjectOEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerO = (char*)&input[srcIdx]; cert->issuerOLen = strLen; cert->issuerOEnc = (char)b; @@ -14122,13 +14334,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_ORGUNIT_NAME; copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectOU = (char*)&input[srcIdx]; cert->subjectOULen = strLen; cert->subjectOUEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerOU = (char*)&input[srcIdx]; cert->issuerOULen = strLen; cert->issuerOUEnc = (char)b; @@ -14145,13 +14357,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_SERIAL_NUMBER; copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectSND = (char*)&input[srcIdx]; cert->subjectSNDLen = strLen; cert->subjectSNDEnc = (char)b; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerSND = (char*)&input[srcIdx]; cert->issuerSNDLen = strLen; cert->issuerSNDEnc = (char)b; @@ -14168,7 +14380,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_USER_ID; copyLen = sizeof(WOLFSSL_USER_ID) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectUID = (char*)&input[srcIdx]; cert->subjectUIDLen = strLen; cert->subjectUIDEnc = (char)b; @@ -14185,7 +14397,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_STREET_ADDR_NAME; copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectStreet = (char*)&input[srcIdx]; cert->subjectStreetLen = strLen; cert->subjectStreetEnc = (char)b; @@ -14201,7 +14413,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_BUS_CAT; copyLen = sizeof(WOLFSSL_BUS_CAT) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectBC = (char*)&input[srcIdx]; cert->subjectBCLen = strLen; cert->subjectBCEnc = (char)b; @@ -14216,7 +14428,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_POSTAL_NAME; copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectPC = (char*)&input[srcIdx]; cert->subjectPCLen = strLen; cert->subjectPCEnc = (char)b; @@ -14255,7 +14467,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_JOI_C; copyLen = sizeof(WOLFSSL_JOI_C) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectJC = (char*)&input[srcIdx]; cert->subjectJCLen = strLen; cert->subjectJCEnc = (char)b; @@ -14273,7 +14485,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copy = WOLFSSL_JOI_ST; copyLen = sizeof(WOLFSSL_JOI_ST) - 1; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectJS = (char*)&input[srcIdx]; cert->subjectJSLen = strLen; cert->subjectJSEnc = (char)b; @@ -14337,13 +14549,13 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if !defined(IGNORE_NAME_CONSTRAINTS) || \ defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectEmail = (char*)&input[srcIdx]; cert->subjectEmailLen = strLen; } #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \ (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) - else if (nameType == ISSUER) { + else if (nameType == ASN_ISSUER) { cert->issuerEmail = (char*)&input[srcIdx]; cert->issuerEmailLen = strLen; } @@ -14445,8 +14657,8 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \ !defined(WOLFCRYPT_ONLY) - if (nameType == ISSUER) { -#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \ + if (nameType == ASN_ISSUER) { +#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) &&\ (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)) dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX); XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen); @@ -14504,14 +14716,14 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, if (ret == 0) { #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT) /* Store pointer and length to raw issuer. */ - if (nameType == ISSUER) { + if (nameType == ASN_ISSUER) { cert->issuerRaw = &input[srcIdx]; cert->issuerRawLen = len; } #endif #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT) /* Store pointer and length to raw subject. */ - if (nameType == SUBJECT) { + if (nameType == ASN_SUBJECT) { cert->subjectRaw = &input[srcIdx]; cert->subjectRawLen = len; } @@ -14530,7 +14742,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, &srcIdx, maxIdx); if (ret == 0) { /* Put RDN data into certificate. */ - ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT, + ret = GetRDN(cert, full, &idx, &nid, nameType == ASN_SUBJECT, dataASN); } #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -14546,7 +14758,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen); #ifndef WOLFSSL_NO_ASN_STRICT - /* RFC 5280 section 4.1.2.4 lists a DirecotryString as being + /* RFC 5280 section 4.1.2.4 lists a DirectoryString as being * 1..MAX in length */ if (ret == 0 && strLen < 1) { WOLFSSL_MSG("Non conforming DirectoryString of length 0 was" @@ -14588,7 +14800,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #ifdef WOLFSSL_X509_NAME_AVAILABLE /* Store X509_NAME in certificate. */ - if (nameType == ISSUER) { + if (nameType == ASN_ISSUER) { #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ defined(HAVE_LIGHTY)) && \ (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)) @@ -14638,7 +14850,7 @@ enum { * Either the issuer or subject name. * * @param [in, out] cert Decoded certificate object. - * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT. + * @param [in] nameType Type being decoded: ASN_ISSUER or ASN_SUBJECT. * @param [in] maxIdx Index of next item after certificate name. * @return 0 on success. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or @@ -14659,7 +14871,7 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) WOLFSSL_MSG("Getting Name"); - if (nameType == ISSUER) { + if (nameType == ASN_ISSUER) { full = cert->issuer; hash = cert->issuerHash; } @@ -14717,7 +14929,7 @@ int GetName(DecodedCert* cert, int nameType, int maxIdx) cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset; /* Get fields to fill in based on name type. */ - if (nameType == ISSUER) { + if (nameType == ASN_ISSUER) { full = cert->issuer; hash = cert->issuerHash; } @@ -14774,18 +14986,23 @@ static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx) } #endif +/* Extract certTime from date string parameter. + * Reminder: idx is incremented in each call to GetTime() + * Return 0 on failure, 1 for success. */ int ExtractDate(const unsigned char* date, unsigned char format, - struct tm* certTime, int* idx) + struct tm* certTime, int* idx) { XMEMSET(certTime, 0, sizeof(struct tm)); + /* Get the first two bytes of the year (century) */ if (format == ASN_UTC_TIME) { if (btoi(date[*idx]) >= 5) certTime->tm_year = 1900; else certTime->tm_year = 2000; } - else { /* format == GENERALIZED_TIME */ + else { + /* format == GENERALIZED_TIME */ #ifdef WOLFSSL_LINUXKM if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0; #else @@ -14805,11 +15022,7 @@ int ExtractDate(const unsigned char* date, unsigned char format, int tm_min = certTime->tm_min; int tm_sec = certTime->tm_sec; -#ifdef WOLFSSL_LINUXKM - if (GetTime_Long(&tm_year, date, idx) != 0) return 0; -#else if (GetTime(&tm_year, date, idx) != 0) return 0; -#endif if (GetTime(&tm_mon , date, idx) != 0) return 0; if (GetTime(&tm_mday, date, idx) != 0) return 0; if (GetTime(&tm_hour, date, idx) != 0) return 0; @@ -14823,28 +15036,30 @@ int ExtractDate(const unsigned char* date, unsigned char format, certTime->tm_hour = tm_hour; certTime->tm_min = tm_min; certTime->tm_sec = tm_sec; -#else - /* adjust tm_year, tm_mon */ -#ifdef WOLFSSL_LINUXKM - if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0; -#else - if (GetTime(&certTime->tm_year, date, idx) != 0) return 0; -#endif +#else /* !AVR */ + /* Get the next two bytes of the year. */ + #ifdef WOLFSSL_LINUXKM + if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0; + #else + if (GetTime(&certTime->tm_year, date, idx) != 0) return 0; + #endif certTime->tm_year -= 1900; + + /* The next fields are expected in specific order in [date] string: */ if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0; certTime->tm_mon -= 1; if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0; if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0; if (GetTime(&certTime->tm_min , date, idx) != 0) return 0; if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0; -#endif + +#endif /* !AVR */ return 1; } -#if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ - defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#ifdef WOLFSSL_ASN_TIME_STRING int GetTimeString(byte* date, int format, char* buf, int len) { struct tm t; @@ -14890,7 +15105,7 @@ int GetTimeString(byte* date, int format, char* buf, int len) return 1; } -#endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ +#endif /* WOLFSSL_ASN_TIME_STRING */ /* Check time struct for valid values. Returns 0 for success */ static int ValidateGmtime(struct tm* inTime) @@ -15006,19 +15221,13 @@ int GetFormattedTime(void* currTime, byte* buf, word32 len) hour = ts->tm_hour; mini = ts->tm_min; sec = ts->tm_sec; - #if defined(WOLF_C89) if (len < ASN_UTC_TIME_SIZE) { WOLFSSL_MSG("buffer for GetFormattedTime is too short."); return BUFFER_E; } - ret = XSPRINTF((char*)buf, - "%02d%02d%02d%02d%02d%02dZ", year, mon, day, - hour, mini, sec); - #else ret = XSNPRINTF((char*)buf, len, "%02d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec); - #endif } else { /* GeneralizedTime */ @@ -15028,19 +15237,13 @@ int GetFormattedTime(void* currTime, byte* buf, word32 len) hour = ts->tm_hour; mini = ts->tm_min; sec = ts->tm_sec; - #if defined(WOLF_C89) if (len < ASN_GENERALIZED_TIME_SIZE) { WOLFSSL_MSG("buffer for GetFormattedTime is too short."); return BUFFER_E; } - ret = XSPRINTF((char*)buf, - "%4d%02d%02d%02d%02d%02dZ", year, mon, day, - hour, mini, sec); - #else ret = XSNPRINTF((char*)buf, len, "%4d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec); - #endif } return ret; @@ -15091,7 +15294,7 @@ static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b) /* Make sure before and after dates are valid */ /* date = ASN.1 raw */ /* format = ASN_UTC_TIME or ASN_GENERALIZED_TIME */ -/* dateType = AFTER or BEFORE */ +/* dateType = ASN_AFTER or ASN_BEFORE */ int wc_ValidateDate(const byte* date, byte format, int dateType) { time_t ltime; @@ -15121,14 +15324,14 @@ int wc_ValidateDate(const byte* date, byte format, int dateType) #endif #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW - if (dateType == BEFORE) { + if (dateType == ASN_BEFORE) { WOLFSSL_MSG("Skewing local time for before date check"); ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW; } #endif #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW - if (dateType == AFTER) { + if (dateType == ASN_AFTER) { WOLFSSL_MSG("Skewing local time for after date check"); ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW; } @@ -15162,13 +15365,13 @@ int wc_ValidateDate(const byte* date, byte format, int dateType) return 0; } - if (dateType == BEFORE) { + if (dateType == ASN_BEFORE) { if (DateLessThan(localTime, &certTime)) { WOLFSSL_MSG("Date BEFORE check failed"); return 0; } } - else { /* dateType == AFTER */ + else { /* dateType == ASN_AFTER */ if (DateGreaterThan(localTime, &certTime)) { WOLFSSL_MSG("Date AFTER check failed"); return 0; @@ -15334,7 +15537,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) byte format; word32 startIdx = 0; - if (dateType == BEFORE) + if (dateType == ASN_BEFORE) cert->beforeDate = &cert->source[cert->srcIdx]; else cert->afterDate = &cert->source[cert->srcIdx]; @@ -15348,7 +15551,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) XMEMSET(date, 0, MAX_DATE_SIZE); XMEMCPY(date, datePtr, (size_t)length); - if (dateType == BEFORE) + if (dateType == ASN_BEFORE) cert->beforeDateLen = (int)(cert->srcIdx - startIdx); else cert->afterDateLen = (int)(cert->srcIdx - startIdx); @@ -15356,7 +15559,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) #ifndef NO_ASN_TIME_CHECK if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE && !XVALIDATE_DATE(date, format, dateType)) { - if (dateType == BEFORE) { + if (dateType == ASN_BEFORE) { WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E); return ASN_BEFORE_DATE_E; } @@ -15382,10 +15585,10 @@ static int GetValidity(DecodedCert* cert, int verify, int maxIdx) maxIdx = (int)cert->srcIdx + length; - if (GetDate(cert, BEFORE, verify, maxIdx) < 0) + if (GetDate(cert, ASN_BEFORE, verify, maxIdx) < 0) badDate = ASN_BEFORE_DATE_E; /* continue parsing */ - if (GetDate(cert, AFTER, verify, maxIdx) < 0) + if (GetDate(cert, ASN_AFTER, verify, maxIdx) < 0) return ASN_AFTER_DATE_E; if (badDate != 0) @@ -15585,7 +15788,7 @@ int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate) WOLFSSL_MSG("Got Algo ID"); - if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0) + if ( (ret = GetName(cert, ASN_ISSUER, (int)cert->sigIndex)) < 0) return ret; if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0) @@ -15594,7 +15797,7 @@ int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate) } #endif - if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0) + if ( (ret = GetName(cert, ASN_SUBJECT, (int)cert->sigIndex)) < 0) return ret; WOLFSSL_MSG("Got Subject Name"); @@ -15621,8 +15824,8 @@ int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate) * @return 0 on success. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time. * @return ASN_DATE_SZ_E when time data is not supported. - * @return ASN_BEFORE_DATE_E when BEFORE date is invalid. - * @return ASN_AFTER_DATE_E when AFTER date is invalid. + * @return ASN_BEFORE_DATE_E when ASN_BEFORE date is invalid. + * @return ASN_AFTER_DATE_E when ASN_AFTER date is invalid. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or * is invalid. * @return BUFFER_E when data in buffer is too small. @@ -15800,7 +16003,7 @@ word32 SetLengthEx(word32 length, byte* output, byte isIndef) * @param [out] output Buffer to encode into. * @return Number of bytes encoded. */ -static word32 SetHeader(byte tag, word32 len, byte* output, byte isIndef) +word32 SetHeader(byte tag, word32 len, byte* output, byte isIndef) { if (output) { /* Encode tag first. */ @@ -15998,9 +16201,14 @@ static WC_INLINE int IsSigAlgoECC(word32 algoOID) || (algoOID == FALCON_LEVEL5k) #endif #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT || (algoOID == DILITHIUM_LEVEL2k) || (algoOID == DILITHIUM_LEVEL3k) || (algoOID == DILITHIUM_LEVEL5k) + #endif + || (algoOID == ML_DSA_LEVEL2k) + || (algoOID == ML_DSA_LEVEL3k) + || (algoOID == ML_DSA_LEVEL5k) #endif #ifdef HAVE_SPHINCS || (algoOID == SPHINCS_FAST_LEVEL1k) @@ -16024,7 +16232,7 @@ static WC_INLINE int IsSigAlgoECC(word32 algoOID) * @return Encoded data size on success. * @return 0 when dynamic memory allocation fails. */ -word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) +static word32 SetAlgoIDImpl(int algoOID, byte* output, int type, int curveSz, byte absentParams) { #ifndef WOLFSSL_ASN_TEMPLATE word32 tagSz, idSz, seqSz, algoSz = 0; @@ -16033,9 +16241,10 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */ word32 length = 0; - tagSz = (type == oidHashType || + tagSz = ((type == oidHashType || (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) || - (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U; + (type == oidKeyType && algoOID == RSAk)) && + (absentParams == FALSE)) ? 2U : 0U; algoName = OidFromId((word32)algoOID, (word32)type, &algoSz); if (algoName == NULL) { WOLFSSL_MSG("Unknown Algorithm"); @@ -16091,6 +16300,10 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) /* Don't put out NULL DER item. */ dataASN[ALGOIDASN_IDX_NULL].noOut = 1; } + /* Override for absent (not NULL) params */ + if (TRUE == absentParams) { + dataASN[ALGOIDASN_IDX_NULL].noOut = 1; + } if (algoOID == DSAk) { /* Don't include SEQUENCE for DSA keys. */ o = 1; @@ -16133,6 +16346,27 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) #endif /* WOLFSSL_ASN_TEMPLATE */ } +/* Encode an algorithm identifier. + * + * [algoOID, type] is unique. + * + * @param [in] algoOID Algorithm identifier. + * @param [out] output Buffer to hold encoding. + * @param [in] type Type of OID being encoded. + * @param [in] curveSz Add extra space for curve data. + * @return Encoded data size on success. + * @return 0 when dynamic memory allocation fails. + */ +word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) +{ + return SetAlgoIDImpl(algoOID, output, type, curveSz, FALSE); +} + +word32 SetAlgoIDEx(int algoOID, byte* output, int type, int curveSz, byte absentParams) +{ + return SetAlgoIDImpl(algoOID, output, type, curveSz, absentParams); +} + #ifdef WOLFSSL_ASN_TEMPLATE /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */ /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature. @@ -16265,15 +16499,11 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) if (sigCtx == NULL) return; - if (sigCtx->digest) { - XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST); - sigCtx->digest = NULL; - } + XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST); + sigCtx->digest = NULL; #if !(defined(NO_RSA) && defined(NO_DSA)) - if (sigCtx->sigCpy) { - XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE); - sigCtx->sigCpy = NULL; - } + XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE); + sigCtx->sigCpy = NULL; #endif #ifndef NO_ASN_CRYPT if (sigCtx->key.ptr) { @@ -16337,9 +16567,14 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: + #endif + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: wc_dilithium_free(sigCtx->key.dilithium); XFREE(sigCtx->key.dilithium, sigCtx->heap, DYNAMIC_TYPE_DILITHIUM); @@ -16511,9 +16746,14 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, break; #endif #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case CTC_DILITHIUM_LEVEL2: case CTC_DILITHIUM_LEVEL3: case CTC_DILITHIUM_LEVEL5: + #endif + case CTC_ML_DSA_LEVEL2: + case CTC_ML_DSA_LEVEL3: + case CTC_ML_DSA_LEVEL5: /* Hashes done in signing operation. */ break; #endif @@ -16553,7 +16793,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, const byte* sigParams, word32 sigParamsSz, byte* rsaKeyIdx) { - int ret = 0; + int ret = WC_NO_ERR_TRACE(ASN_SIG_CONFIRM_E); /* default to failure */ #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) CertAttribute* certatt = NULL; #endif @@ -16965,83 +17205,55 @@ static int ConfirmSignature(SignatureCtx* sigCtx, #if defined(HAVE_DILITHIUM) && \ !defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ !defined(WOLFSSL_DILITHIUM_NO_ASN1) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: + case DILITHIUM_LEVEL3k: + case DILITHIUM_LEVEL5k: + #endif + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: { word32 idx = 0; - sigCtx->verify = 0; - sigCtx->key.dilithium = - (dilithium_key*)XMALLOC(sizeof(dilithium_key), - sigCtx->heap, - DYNAMIC_TYPE_DILITHIUM); - if (sigCtx->key.dilithium == NULL) { - ERROR_OUT(MEMORY_E, exit_cs); - } - if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium, - sigCtx->heap, sigCtx->devId)) < 0) { - goto exit_cs; + int level; + if (keyOID == ML_DSA_LEVEL2k) { + level = WC_ML_DSA_44; } - if ((ret = wc_dilithium_set_level( - sigCtx->key.dilithium, 2)) - < 0) { - goto exit_cs; - } - if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx, - sigCtx->key.dilithium, keySz)) < 0) { - WOLFSSL_MSG("ASN Key import error Dilithium Level 2"); - goto exit_cs; + else if (keyOID == ML_DSA_LEVEL3k) { + level = WC_ML_DSA_65; } - break; - } - case DILITHIUM_LEVEL3k: - { - word32 idx = 0; - sigCtx->verify = 0; - sigCtx->key.dilithium = - (dilithium_key*)XMALLOC(sizeof(dilithium_key), - sigCtx->heap, - DYNAMIC_TYPE_DILITHIUM); - if (sigCtx->key.dilithium == NULL) { - ERROR_OUT(MEMORY_E, exit_cs); + else if (keyOID == ML_DSA_LEVEL5k) { + level = WC_ML_DSA_87; } - if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium, - sigCtx->heap, sigCtx->devId)) < 0) { - goto exit_cs; + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if (keyOID == DILITHIUM_LEVEL2k) { + level = WC_ML_DSA_44_DRAFT; } - if ((ret = wc_dilithium_set_level( - sigCtx->key.dilithium, 3)) - < 0) { - goto exit_cs; + else if (keyOID == DILITHIUM_LEVEL3k) { + level = WC_ML_DSA_65_DRAFT; } - if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx, - sigCtx->key.dilithium, keySz)) < 0) { - WOLFSSL_MSG("ASN Key import error Dilithium Level 3"); - goto exit_cs; + else if (keyOID == DILITHIUM_LEVEL5k) { + level = WC_ML_DSA_87_DRAFT; } - break; - } - case DILITHIUM_LEVEL5k: - { - word32 idx = 0; + #endif sigCtx->verify = 0; - sigCtx->key.dilithium = - (dilithium_key*)XMALLOC(sizeof(dilithium_key), - sigCtx->heap, - DYNAMIC_TYPE_DILITHIUM); + sigCtx->key.dilithium = (dilithium_key*)XMALLOC( + sizeof(dilithium_key), sigCtx->heap, + DYNAMIC_TYPE_DILITHIUM); if (sigCtx->key.dilithium == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium, - sigCtx->heap, sigCtx->devId)) < 0) { + sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; } - if ((ret = wc_dilithium_set_level( - sigCtx->key.dilithium, 5)) - < 0) { + if ((ret = wc_dilithium_set_level(sigCtx->key.dilithium, + level)) < 0) { goto exit_cs; } if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx, sigCtx->key.dilithium, keySz)) < 0) { - WOLFSSL_MSG("ASN Key import error Dilithium Level 5"); + WOLFSSL_MSG("ASN Key import error Dilithium"); goto exit_cs; } break; @@ -17371,6 +17583,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: @@ -17380,6 +17593,15 @@ static int ConfirmSignature(SignatureCtx* sigCtx, sigCtx->key.dilithium); break; } + #endif + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: + { + ret = wc_dilithium_verify_ctx_msg(sig, sigSz, NULL, 0, buf, + bufSz, &sigCtx->verify, sigCtx->key.dilithium); + break; + } #endif /* HAVE_DILITHIUM */ #if defined(HAVE_SPHINCS) case SPHINCS_FAST_LEVEL1k: @@ -17574,39 +17796,22 @@ static int ConfirmSignature(SignatureCtx* sigCtx, } #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: - { - if (sigCtx->verify == 1) { - ret = 0; - } - else { - WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match"); - ret = ASN_SIG_CONFIRM_E; - } - break; - } case DILITHIUM_LEVEL3k: - { - if (sigCtx->verify == 1) { - ret = 0; - } - else { - WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match"); - ret = ASN_SIG_CONFIRM_E; - } - break; - } case DILITHIUM_LEVEL5k: - { + #endif + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: if (sigCtx->verify == 1) { ret = 0; } else { - WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match"); + WOLFSSL_MSG("DILITHIUM Verify didn't match"); ret = ASN_SIG_CONFIRM_E; } break; - } #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS case SPHINCS_FAST_LEVEL1k: @@ -17689,6 +17894,9 @@ static int ConfirmSignature(SignatureCtx* sigCtx, exit_cs: +#else + /* For NO_ASN_CRYPT return "not compiled in" */ + ret = NOT_COMPILED_IN; #endif /* !NO_ASN_CRYPT */ (void)keyOID; @@ -17735,8 +17943,7 @@ int wc_ConfirmAltSignature( } #ifdef WOLFSSL_SMALL_STACK - if (sigCtx != NULL) - XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); + XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); #endif return ret; } @@ -17987,7 +18194,9 @@ static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert) #ifndef WOLFSSL_ASN_TEMPLATE static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry) { -#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV) +#if (defined(WOLFSSL_ASN_ALL) || defined(OPENSSL_EXTRA)) && \ + !defined(WOLFSSL_ALT_NAMES_NO_REV) + /* logic to add alt name to end of list */ dnsEntry->next = NULL; if (cert->altNames == NULL) { /* First on list */ @@ -18110,7 +18319,7 @@ static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid) } if (ret == 0) { - ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry); + ret = SetDNSEntry(cert->heap, buf, (int)bufLen, ASN_OTHER_TYPE, &entry); if (ret == 0) { #ifdef WOLFSSL_FPKI entry->oidSum = oid; @@ -18137,10 +18346,12 @@ static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid) * @return BUFFER_E when data in buffer is too small. */ static int DecodeOtherName(DecodedCert* cert, const byte* input, - word32* inOutIdx, word32 maxIdx) + word32* inOutIdx, int len) { DECL_ASNGETDATA(dataASN, otherNameASN_Length); int ret = 0; + word32 maxIdx = *inOutIdx + (word32)len; + const char* name = (const char*)input + *inOutIdx; CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap); @@ -18169,7 +18380,9 @@ static int DecodeOtherName(DecodedCert* cert, const byte* input, (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum); break; default: - WOLFSSL_MSG("\tunsupported OID skipping"); + WOLFSSL_MSG("\tadding unsupported OID"); + ret = SetDNSEntry(cert->heap, name, len, ASN_OTHER_TYPE, + &cert->altNames); break; } } @@ -18201,8 +18414,8 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, /* GeneralName choice: dnsName */ if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) { - ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE, - &cert->altNames); + ret = SetDNSEntry(cert->heap, (const char*)(input + idx), len, + ASN_DNS_TYPE, &cert->altNames); if (ret == 0) { idx += (word32)len; } @@ -18220,7 +18433,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, return ASN_PARSE_E; } - ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen, + ret = SetDNSEntry(cert->heap, (const char*)(input + idxDir), strLen, ASN_DIR_TYPE, &cert->altDirNames); if (ret == 0) { idx += (word32)len; @@ -18228,7 +18441,7 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, } /* GeneralName choice: rfc822Name */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) { - ret = SetDNSEntry(cert, (const char*)(input + idx), len, + ret = SetDNSEntry(cert->heap, (const char*)(input + idx), len, ASN_RFC822_TYPE, &cert->altEmailNames); if (ret == 0) { idx += (word32)len; @@ -18276,40 +18489,38 @@ static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag, } #endif - ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE, - &cert->altNames); + ret = SetDNSEntry(cert->heap, (const char*)(input + idx), len, + ASN_URI_TYPE, &cert->altNames); if (ret == 0) { idx += (word32)len; } } - #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \ - defined(WOLFSSL_IP_ALT_NAME) + #ifdef WOLFSSL_IP_ALT_NAME /* GeneralName choice: iPAddress */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) { - ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE, - &cert->altNames); + ret = SetDNSEntry(cert->heap, (const char*)(input + idx), len, + ASN_IP_TYPE, &cert->altNames); if (ret == 0) { idx += (word32)len; } } - #endif /* WOLFSSL_QT || OPENSSL_ALL */ - - #ifdef OPENSSL_ALL + #endif /* WOLFSSL_IP_ALT_NAME */ + #ifdef WOLFSSL_RID_ALT_NAME /* GeneralName choice: registeredID */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) { - ret = SetDNSEntry(cert, (const char*)(input + idx), len, + ret = SetDNSEntry(cert->heap, (const char*)(input + idx), len, ASN_RID_TYPE, &cert->altNames); if (ret == 0) { idx += (word32)len; } } - #endif + #endif /* WOLFSSL_RID_ALT_NAME */ #endif /* IGNORE_NAME_CONSTRAINTS */ #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI) /* GeneralName choice: otherName */ else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) { /* TODO: test data for code path */ - ret = DecodeOtherName(cert, input, &idx, idx + (word32)len); + ret = DecodeOtherName(cert, input, &idx, len); } #endif /* GeneralName choice: dNSName, x400Address, ediPartyName */ @@ -18547,6 +18758,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; int length = 0; + word32 numNames = 0; WOLFSSL_ENTER("DecodeAltNames"); @@ -18579,8 +18791,13 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) return BUFFER_E; } - current_byte = input[idx++]; + numNames++; + if (numNames > WOLFSSL_MAX_ALT_NAMES) { + WOLFSSL_MSG("\tToo many subject alternative names"); + return ASN_ALT_NAME_E; + } + current_byte = input[idx++]; length--; /* Save DNS Type names in the altNames list. */ @@ -18774,7 +18991,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) length -= strLen; idx += (word32)strLen; } -#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) { DNS_entry* ipAddr; int strLen; @@ -18809,21 +19026,19 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) XMEMCPY(ipAddr->name, &input[idx], strLen); ipAddr->name[strLen] = '\0'; - #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) { WOLFSSL_MSG("\tOut of Memory for IP string"); XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME); XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME); return MEMORY_E; } - #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ AddAltName(cert, ipAddr); length -= strLen; idx += (word32)strLen; } -#endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */ -#if defined(OPENSSL_ALL) +#endif /* WOLFSSL_IP_ALT_NAME */ +#ifdef WOLFSSL_RID_ALT_NAME else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) { DNS_entry* rid; int strLen; @@ -18870,7 +19085,7 @@ static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert) length -= strLen; idx += (word32)strLen; } -#endif /* OPENSSL_ALL */ +#endif /* WOLFSSL_RID_ALT_NAME */ #endif /* IGNORE_NAME_CONSTRAINTS */ else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) { @@ -19472,15 +19687,11 @@ static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) /* Set ocsp entry */ if (b == GENERALNAME_URI && oid == AIA_OCSP_OID && - cert->extAuthInfo == NULL) - { + cert->extAuthInfo == NULL) { cert->extAuthInfoSz = length; cert->extAuthInfo = input + idx; - #if !defined(OPENSSL_ALL) && !defined(WOLFSSL_QT) - break; - #endif } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + #ifdef WOLFSSL_ASN_CA_ISSUER /* Set CaIssuers entry */ else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID && cert->extAuthInfoCaIssuer == NULL) @@ -19488,7 +19699,7 @@ static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) cert->extAuthInfoCaIssuerSz = length; cert->extAuthInfoCaIssuer = input + idx; } - #endif + #endif idx += (word32)length; } @@ -19526,11 +19737,8 @@ static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC], &cert->extAuthInfo, &sz32); cert->extAuthInfoSz = (int)sz32; - #if !defined(OPENSSL_ALL) && !defined(WOLFSSL_QT) - break; - #endif } - #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + #ifdef WOLFSSL_ASN_CA_ISSUER /* Check we have CA Issuer and URI. */ else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_CA_ISSUER_OID) && @@ -19541,7 +19749,7 @@ static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert) &cert->extAuthInfoCaIssuer, &sz32); cert->extAuthInfoCaIssuerSz = (int)sz32; } - #endif + #endif /* Otherwise skip. */ } } @@ -19617,13 +19825,14 @@ static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert) return ASN_PARSE_E; } + cert->extAuthKeyIdSz = length; + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #ifdef WOLFSSL_AKID_NAME cert->extRawAuthKeyIdSrc = input; cert->extRawAuthKeyIdSz = sz; #endif cert->extAuthKeyIdSrc = &input[idx]; - cert->extAuthKeyIdSz = length; #endif /* OPENSSL_EXTRA */ return GetHashId(input + idx, length, cert->extAuthKeyId, @@ -19719,9 +19928,9 @@ static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert) ret = GetOctetString(input, &idx, &length, sz); if (ret > 0) { + cert->extSubjKeyIdSz = (word32)length; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) cert->extSubjKeyIdSrc = &input[idx]; - cert->extSubjKeyIdSz = (word32)length; #endif /* OPENSSL_EXTRA */ /* Get the hash or hash of the hash if wrong size. */ @@ -20110,6 +20319,7 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, #ifndef WOLFSSL_ASN_TEMPLATE word32 idx = 0; int ret = 0; + word32 cnt = 0; (void)heap; @@ -20118,6 +20328,14 @@ static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head, word32 nameIdx; byte b, bType; + if (limit > 0) { + cnt++; + if (cnt > limit) { + WOLFSSL_MSG("too many name constraints"); + return ASN_NAME_INVALID_E; + } + } + if (GetSequence(input, &idx, &seqLength, sz) < 0) { WOLFSSL_MSG("\tfail: should be a SEQUENCE"); return ASN_PARSE_E; @@ -20348,7 +20566,7 @@ static int DecodeNameConstraints(const byte* input, word32 sz, } #endif /* IGNORE_NAME_CONSTRAINTS */ -#if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \ +#if defined(WOLFSSL_CERT_EXT) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* Decode ITU-T X.690 OID format to a string representation @@ -20401,10 +20619,10 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) exit: return w; } -#endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */ +#endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT) - #ifdef WOLFSSL_ASN_TEMPLATE +#if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) +#ifdef WOLFSSL_ASN_TEMPLATE /* ASN.1 template for PolicyInformation. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies. */ @@ -20423,230 +20641,221 @@ int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz) /* Number of items in ASN.1 template for PolicyInformation. */ #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem)) - #endif +#endif - /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */ - static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert) - { - #ifndef WOLFSSL_ASN_TEMPLATE - word32 idx = 0; - word32 oldIdx; - int policy_length = 0; - int ret; - int total_length = 0; - #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \ - !defined(WOLFSSL_DUP_CERTPOL) - int i; - #endif +/* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */ +static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert) +{ +#ifndef WOLFSSL_ASN_TEMPLATE + word32 idx = 0; + word32 oldIdx; + int policy_length = 0; + int ret; + int total_length = 0; +#if defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_DUP_CERTPOL) + int i; +#endif - WOLFSSL_ENTER("DecodeCertPolicy"); + WOLFSSL_ENTER("DecodeCertPolicy"); - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) - /* Check if cert is null before dereferencing below */ - if (cert == NULL) - return BAD_FUNC_ARG; - #else - (void)cert; - #endif + /* Check if cert is null before dereferencing below */ + if (cert == NULL) + return BAD_FUNC_ARG; - #if defined(WOLFSSL_CERT_EXT) - cert->extCertPoliciesNb = 0; - #endif +#if defined(WOLFSSL_CERT_EXT) + cert->extCertPoliciesNb = 0; +#endif - if (GetSequence(input, &idx, &total_length, sz) < 0) { - WOLFSSL_MSG("\tGet CertPolicy total seq failed"); - return ASN_PARSE_E; - } + if (GetSequence(input, &idx, &total_length, sz) < 0) { + WOLFSSL_MSG("\tGet CertPolicy total seq failed"); + return ASN_PARSE_E; + } + + /* Validate total length */ + if (total_length > (int)(sz - idx)) { + WOLFSSL_MSG("\tCertPolicy length mismatch"); + return ASN_PARSE_E; + } + + /* Unwrap certificatePolicies */ + do { + int length = 0; - /* Validate total length */ - if (total_length > (int)(sz - idx)) { - WOLFSSL_MSG("\tCertPolicy length mismatch"); + if (GetSequence(input, &idx, &policy_length, sz) < 0) { + WOLFSSL_MSG("\tGet CertPolicy seq failed"); return ASN_PARSE_E; } - /* Unwrap certificatePolicies */ - do { - int length = 0; + oldIdx = idx; + ret = GetASNObjectId(input, &idx, &length, sz); + if (ret != 0) + return ret; + policy_length -= (int)(idx - oldIdx); - if (GetSequence(input, &idx, &policy_length, sz) < 0) { - WOLFSSL_MSG("\tGet CertPolicy seq failed"); + if (length > 0) { + /* Verify length won't overrun buffer */ + if (length > (int)(sz - idx)) { + WOLFSSL_MSG("\tCertPolicy length exceeds input buffer"); return ASN_PARSE_E; } - oldIdx = idx; - ret = GetASNObjectId(input, &idx, &length, sz); - if (ret != 0) - return ret; - policy_length -= (int)(idx - oldIdx); - - if (length > 0) { - /* Verify length won't overrun buffer */ - if (length > (int)(sz - idx)) { - WOLFSSL_MSG("\tCertPolicy length exceeds input buffer"); - return ASN_PARSE_E; - } - - #if defined(WOLFSSL_SEP) + #ifdef WOLFSSL_SEP + if (cert->deviceType == NULL) { cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap, - DYNAMIC_TYPE_X509_EXT); + DYNAMIC_TYPE_X509_EXT); if (cert->deviceType == NULL) { WOLFSSL_MSG("\tCouldn't alloc memory for deviceType"); return MEMORY_E; } cert->deviceTypeSz = length; XMEMCPY(cert->deviceType, input + idx, (size_t)length); - break; - #elif defined(WOLFSSL_CERT_EXT) - /* decode cert policy */ - if (DecodePolicyOID(cert->extCertPolicies[ - cert->extCertPoliciesNb], MAX_CERTPOL_SZ, - input + idx, length) <= 0) { - WOLFSSL_MSG("\tCouldn't decode CertPolicy"); - WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); - return ASN_PARSE_E; - } - #ifndef WOLFSSL_DUP_CERTPOL - /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST - * NOT appear more than once in a certificate policies - * extension". This is a sanity check for duplicates. - * extCertPolicies should only have OID values, additional - * qualifiers need to be stored in a separate array. */ - for (i = 0; i < cert->extCertPoliciesNb; i++) { - if (XMEMCMP(cert->extCertPolicies[i], + } + #endif + + #ifdef WOLFSSL_CERT_EXT + /* decode cert policy */ + if (DecodePolicyOID(cert->extCertPolicies[ + cert->extCertPoliciesNb], MAX_CERTPOL_SZ, + input + idx, length) <= 0) { + WOLFSSL_MSG("\tCouldn't decode CertPolicy"); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + #ifndef WOLFSSL_DUP_CERTPOL + /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST + * NOT appear more than once in a certificate policies + * extension". This is a sanity check for duplicates. + * extCertPolicies should only have OID values, additional + * qualifiers need to be stored in a separate array. */ + for (i = 0; i < cert->extCertPoliciesNb; i++) { + if (XMEMCMP(cert->extCertPolicies[i], cert->extCertPolicies[cert->extCertPoliciesNb], MAX_CERTPOL_SZ) == 0) { - WOLFSSL_MSG("Duplicate policy OIDs not allowed"); - WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted"); - WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E); - return CERTPOLICIES_E; - } + WOLFSSL_MSG("Duplicate policy OIDs not allowed"); + WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted"); + WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E); + return CERTPOLICIES_E; } - #endif /* !WOLFSSL_DUP_CERTPOL */ - cert->extCertPoliciesNb++; - #else - WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0); - return 0; - #endif } - idx += (word32)policy_length; - } while((int)idx < total_length - #if defined(WOLFSSL_CERT_EXT) - && cert->extCertPoliciesNb < MAX_CERTPOL_NB + #endif /* !WOLFSSL_DUP_CERTPOL */ + cert->extCertPoliciesNb++; #endif - ); - - WOLFSSL_LEAVE("DecodeCertPolicy", 0); - return 0; - #else /* WOLFSSL_ASN_TEMPLATE */ - word32 idx = 0; - int ret = 0; - int total_length = 0; - #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \ - !defined(WOLFSSL_DUP_CERTPOL) - int i; + } + idx += (word32)policy_length; + } while((int)idx < total_length + #ifdef WOLFSSL_CERT_EXT + && cert->extCertPoliciesNb < MAX_CERTPOL_NB #endif + ); - WOLFSSL_ENTER("DecodeCertPolicy"); - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) - /* Check if cert is null before dereferencing below */ - if (cert == NULL) - ret = BAD_FUNC_ARG; - #endif + WOLFSSL_LEAVE("DecodeCertPolicy", 0); + return 0; +#else /* WOLFSSL_ASN_TEMPLATE */ + word32 idx = 0; + int ret = 0; + int total_length = 0; +#if defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_DUP_CERTPOL) + int i; +#endif - if (ret == 0) { - #if defined(WOLFSSL_CERT_EXT) - cert->extCertPoliciesNb = 0; - #endif + WOLFSSL_ENTER("DecodeCertPolicy"); - /* Strip SEQUENCE OF and check using all data. */ - if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0) - { - ret = ASN_PARSE_E; - } + /* Check if cert is null before dereferencing below */ + if (cert == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + #if defined(WOLFSSL_CERT_EXT) + cert->extCertPoliciesNb = 0; + #endif + + /* Strip SEQUENCE OF and check using all data. */ + if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0) + { + ret = ASN_PARSE_E; } + } - /* Unwrap certificatePolicies */ - while ((ret == 0) && ((int)idx < total_length) - #if defined(WOLFSSL_CERT_EXT) - && (cert->extCertPoliciesNb < MAX_CERTPOL_NB) - #endif - ) { - ASNGetData dataASN[policyInfoASN_Length]; - byte* data = NULL; - word32 length = 0; + /* Unwrap certificatePolicies */ + while ((ret == 0) && ((int)idx < total_length) + #if defined(WOLFSSL_CERT_EXT) + && (cert->extCertPoliciesNb < MAX_CERTPOL_NB) + #endif + ) { + ASNGetData dataASN[policyInfoASN_Length]; + byte* data = NULL; + word32 length = 0; - /* Clear dynamic data and check OID is a cert policy type. */ - XMEMSET(dataASN, 0, sizeof(dataASN)); - GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType); - ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1, - input, &idx, (word32)sz); - if (ret == 0) { - /* Get the OID. */ - GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length); - if (length == 0) { - ret = ASN_PARSE_E; - } - } - #if defined(WOLFSSL_SEP) - /* Store OID in device type. */ - if (ret == 0) { - cert->deviceType = (byte*)XMALLOC(length, cert->heap, - DYNAMIC_TYPE_X509_EXT); - if (cert->deviceType == NULL) { - WOLFSSL_MSG("\tCouldn't alloc memory for deviceType"); - ret = MEMORY_E; - } + /* Clear dynamic data and check OID is a cert policy type. */ + XMEMSET(dataASN, 0, sizeof(dataASN)); + GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType); + ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1, + input, &idx, (word32)sz); + if (ret == 0) { + /* Get the OID. */ + GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length); + if (length == 0) { + ret = ASN_PARSE_E; } - if (ret == 0) { + } + #ifdef WOLFSSL_SEP + /* Store OID in device type. */ + if (ret == 0 && cert->deviceType == NULL) { + cert->deviceType = (byte*)XMALLOC(length, cert->heap, + DYNAMIC_TYPE_X509_EXT); + if (cert->deviceType != NULL) { /* Store device type data and length. */ cert->deviceTypeSz = (int)length; XMEMCPY(cert->deviceType, data, length); - break; } - #elif defined(WOLFSSL_CERT_EXT) - if (ret == 0) { - /* Decode cert policy. */ - if (DecodePolicyOID( - cert->extCertPolicies[cert->extCertPoliciesNb], - MAX_CERTPOL_SZ, data, length) <= 0) { - WOLFSSL_MSG("\tCouldn't decode CertPolicy"); - WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); - ret = ASN_PARSE_E; - } + else { + WOLFSSL_MSG("\tCouldn't alloc memory for deviceType"); + ret = MEMORY_E; } - #ifndef WOLFSSL_DUP_CERTPOL - /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST - * NOT appear more than once in a certificate policies - * extension". This is a sanity check for duplicates. - * extCertPolicies should only have OID values, additional - * qualifiers need to be stored in a separate array. */ - for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) { - if (XMEMCMP(cert->extCertPolicies[i], - cert->extCertPolicies[cert->extCertPoliciesNb], - MAX_CERTPOL_SZ) == 0) { - WOLFSSL_MSG("Duplicate policy OIDs not allowed"); - WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted"); - WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E); - ret = CERTPOLICIES_E; - } + } + #endif /* WOLFSSL_SEP */ + + #ifdef WOLFSSL_CERT_EXT + if (ret == 0) { + /* Decode cert policy. */ + if (DecodePolicyOID( + cert->extCertPolicies[cert->extCertPoliciesNb], + MAX_CERTPOL_SZ, data, length) <= 0) { + WOLFSSL_MSG("\tCouldn't decode CertPolicy"); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + ret = ASN_PARSE_E; } - #endif /* !defined(WOLFSSL_DUP_CERTPOL) */ - if (ret == 0) { - /* Keep count of policies seen. */ - cert->extCertPoliciesNb++; + } + #ifndef WOLFSSL_DUP_CERTPOL + /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST + * NOT appear more than once in a certificate policies + * extension". This is a sanity check for duplicates. + * extCertPolicies should only have OID values, additional + * qualifiers need to be stored in a separate array. */ + for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) { + if (XMEMCMP(cert->extCertPolicies[i], + cert->extCertPolicies[cert->extCertPoliciesNb], + MAX_CERTPOL_SZ) == 0) { + WOLFSSL_MSG("Duplicate policy OIDs not allowed"); + WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted"); + WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E); + ret = CERTPOLICIES_E; } - #else - (void)data; - WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0); - break; - #endif } - - WOLFSSL_LEAVE("DecodeCertPolicy", 0); - return ret; - #endif /* WOLFSSL_ASN_TEMPLATE */ + #endif /* !WOLFSSL_DUP_CERTPOL */ + if (ret == 0) { + /* Keep count of policies seen. */ + cert->extCertPoliciesNb++; + } + #endif /* WOLFSSL_CERT_EXT */ } -#endif /* WOLFSSL_SEP */ + + WOLFSSL_LEAVE("DecodeCertPolicy", 0); + return ret; +#endif /* WOLFSSL_ASN_TEMPLATE */ +} +#endif /* WOLFSSL_SEP || WOLFSSL_CERT_EXT */ #ifdef WOLFSSL_SUBJ_DIR_ATTR #ifdef WOLFSSL_ASN_TEMPLATE @@ -20661,7 +20870,7 @@ static const ASNItem subjDirAttrASN[] = { enum { SUBJDIRATTRASN_IDX_SEQ = 0, SUBJDIRATTRASN_IDX_OID, - SUBJDIRATTRASN_IDX_SET, + SUBJDIRATTRASN_IDX_SET }; /* Number of items in ASN.1 template for BasicConstraints. */ @@ -20746,6 +20955,11 @@ static int DecodeSubjDirAttr(const byte* input, word32 sz, DecodedCert* cert) WOLFSSL_ENTER("DecodeSubjDirAttr"); +#ifdef OPENSSL_ALL + cert->extSubjDirAttrSrc = input; + cert->extSubjDirAttrSz = sz; +#endif /* OPENSSL_ALL */ + CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap); /* Strip outer SEQUENCE. */ @@ -20983,6 +21197,7 @@ static int DecodeAltSigAlg(const byte* input, int sz, DecodedCert* cert) (void)cert; } + /* We do this to make sure the format of the extension is correct. */ if (ret == 0) { GetASN_OID(&dataASN[ALTSIG_ALGOID_OID], oidSigType); @@ -20992,8 +21207,8 @@ static int DecodeAltSigAlg(const byte* input, int sz, DecodedCert* cert) } if (ret == 0) { - cert->altSigAlgDer = dataASN[ALTSIG_ALGOID_SEQ].data.u8; - cert->altSigAlgLen = dataASN[ALTSIG_ALGOID_SEQ].length; + cert->altSigAlgDer = (byte *)input; + cert->altSigAlgLen = sz; cert->altSigAlgOID = dataASN[ALTSIG_ALGOID_OID].data.oid.sum; } @@ -21175,15 +21390,11 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, /* Certificate policies. */ case CERT_POLICY_OID: - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) + #ifdef WOLFSSL_SEP VERIFY_AND_SET_OID(cert->extCertPolicySet); - #if defined(OPENSSL_EXTRA) || \ - defined(OPENSSL_EXTRA_X509_SMALL) - cert->extCertPolicyCrit = critical ? 1 : 0; - #endif + cert->extCertPolicyCrit = critical ? 1 : 0; #endif - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \ - defined(WOLFSSL_QT) + #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) if (DecodeCertPolicy(input, length, cert) < 0) { ret = ASN_PARSE_E; } @@ -21355,8 +21566,7 @@ enum { #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem)) #endif -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB int wc_SetUnknownExtCallback(DecodedCert* cert, wc_UnknownExtCallback cb) { if (cert == NULL) { @@ -21366,7 +21576,18 @@ int wc_SetUnknownExtCallback(DecodedCert* cert, cert->unknownExtCallback = cb; return 0; } -#endif + +int wc_SetUnknownExtCallbackEx(DecodedCert* cert, + wc_UnknownExtCallbackEx cb, void *ctx) { + if (cert == NULL) { + return BAD_FUNC_ARG; + } + + cert->unknownExtCallbackEx = cb; + cert->unknownExtCallbackExCtx = ctx; + return 0; +} +#endif /* WC_ASN_UNKNOWN_EXT_CB */ /* * Processing the Certificate Extensions. This does not modify the current @@ -21520,8 +21741,9 @@ static int DecodeCertExtensions(DecodedCert* cert) /* Decode the extension by type. */ ret = DecodeExtensionType(input + idx, length, oid, critical, cert, &isUnknownExt); -#if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING) - if (isUnknownExt && (cert->unknownExtCallback != NULL)) { +#ifdef WC_ASN_UNKNOWN_EXT_CB + if (isUnknownExt && (cert->unknownExtCallback != NULL || + cert->unknownExtCallbackEx != NULL)) { word16 decOid[MAX_OID_SZ]; word32 decOidSz = sizeof(decOid); ret = DecodeObjectId( @@ -21535,12 +21757,22 @@ static int DecodeCertExtensions(DecodedCert* cert) WOLFSSL_ERROR(ret); } - ret = cert->unknownExtCallback(decOid, decOidSz, critical, - dataASN[CERTEXTASN_IDX_VAL].data.buffer.data, - dataASN[CERTEXTASN_IDX_VAL].length); + if ((ret == 0) && (cert->unknownExtCallback != NULL)) { + ret = cert->unknownExtCallback(decOid, decOidSz, critical, + dataASN[CERTEXTASN_IDX_VAL].data.buffer.data, + dataASN[CERTEXTASN_IDX_VAL].length); + } + + if ((ret == 0) && (cert->unknownExtCallbackEx != NULL)) { + ret = cert->unknownExtCallbackEx(decOid, decOidSz, critical, + dataASN[CERTEXTASN_IDX_VAL].data.buffer.data, + dataASN[CERTEXTASN_IDX_VAL].length, + cert->unknownExtCallbackExCtx); + } } -#endif +#else (void)isUnknownExt; +#endif /* Move index on to next extension. */ idx += length; @@ -21723,12 +21955,12 @@ enum { /* Check the data data. * * @param [in] dataASN ASN template dynamic data item. - * @param [in] dataType BEFORE or AFTER date. + * @param [in] dataType ASN_BEFORE or ASN_AFTER date. * @return 0 on success. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time. * @return ASN_DATE_SZ_E when time data is not supported. - * @return ASN_BEFORE_DATE_E when BEFORE date is invalid. - * @return ASN_AFTER_DATE_E when AFTER date is invalid. + * @return ASN_BEFORE_DATE_E when ASN_BEFORE date is invalid. + * @return ASN_AFTER_DATE_E when ASN_AFTER date is invalid. */ static int CheckDate(ASNGetData *dataASN, int dateType) { @@ -21746,14 +21978,18 @@ static int CheckDate(ASNGetData *dataASN, int dateType) } #ifndef NO_ASN_TIME_CHECK - /* Check date is a valid string and BEFORE or AFTER now. */ - if ((ret == 0) && - (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) { - if (dateType == BEFORE) { - ret = ASN_BEFORE_DATE_E; - } - else { - ret = ASN_AFTER_DATE_E; + /* Check date is a valid string and ASN_BEFORE or ASN_AFTER now. */ + if (ret == 0) { + if (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType)) { + if (dateType == ASN_BEFORE) { + ret = ASN_BEFORE_DATE_E; + } + else if (dateType == ASN_AFTER) { + ret = ASN_AFTER_DATE_E; + } + else { + ret = ASN_TIME_E; + } } } #endif @@ -21768,14 +22004,14 @@ static int CheckDate(ASNGetData *dataASN, int dateType) * @param [in] verify Whether to verify dates before and after now. * @param [out] criticalExt Critical extension return code. * @param [out] badDateRet Bad date return code. - * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo. - * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo. + * @param [in] stopAtPubKey Stop parsing before subjectPublicKeyInfo. + * @param [in] stopAfterPubKey Stop parsing after subjectPublicKeyInfo. * @return 0 on success. * @return ASN_CRIT_EXT_E when a critical extension was not recognized. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time. * @return ASN_DATE_SZ_E when time data is not supported. - * @return ASN_BEFORE_DATE_E when BEFORE date is invalid. - * @return ASN_AFTER_DATE_E when AFTER date is invalid. + * @return ASN_BEFORE_DATE_E when ASN_BEFORE date is invalid. + * @return ASN_AFTER_DATE_E when ASN_AFTER date is invalid. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or * is invalid. * @return BUFFER_E when data in buffer is too small. @@ -21878,7 +22114,8 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, cert->version = version; cert->serialSz = (int)serialSz; - #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_PYTHON) + #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_PYTHON) && \ + !defined(WOLFSSL_ASN_ALLOW_0_SERIAL) /* RFC 5280 section 4.1.2.2 states that non-conforming CAs may issue * a negative or zero serial number and should be handled gracefully. * Since it is a non-conforming CA that issues a serial of 0 then we @@ -21889,6 +22126,11 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, ret = ASN_PARSE_E; } #endif + if (cert->serialSz == 0) { + WOLFSSL_MSG("Error serial size is zero. Should be at least one " + "even with no serial number."); + ret = ASN_PARSE_E; + } cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum; cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum; @@ -21896,27 +22138,27 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, /* No bad date error - don't always care. */ badDate = 0; - /* Find the item with the BEFORE date and check it. */ + /* Find the item with the ASN_BEFORE date and check it. */ i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0) ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT; - if ((CheckDate(&dataASN[i], BEFORE) < 0) && (verify != NO_VERIFY) && + if ((CheckDate(&dataASN[i], ASN_BEFORE) < 0) && (verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { badDate = ASN_BEFORE_DATE_E; } - /* Store reference to BEFOREdate. */ + /* Store reference to ASN_BEFORE date. */ cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source); cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source); - /* Find the item with the AFTER date and check it. */ + /* Find the item with the ASN_AFTER date and check it. */ i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0) ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT; - if ((CheckDate(&dataASN[i], AFTER) < 0) && (verify != NO_VERIFY) && + if ((CheckDate(&dataASN[i], ASN_AFTER) < 0) && (verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { badDate = ASN_AFTER_DATE_E; } - /* Store reference to AFTER date. */ + /* Store reference to ASN_AFTER date. */ cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source); cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source); @@ -21954,16 +22196,20 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, } /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */ else if (IsSigAlgoECC(cert->signatureOID)) { - if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0) - #ifdef WC_RSA_PSS - || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) + #ifndef WOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED + if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0) { + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + ret = ASN_PARSE_E; + } #endif - ) { + #ifdef WC_RSA_PSS + if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) { WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); ret = ASN_PARSE_E; } + #endif } - #ifdef WC_RSA_PSS + #ifdef WC_RSA_PSS /* Check parameters starting with a SEQUENCE. */ else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) { word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum; @@ -22005,7 +22251,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, cert->sigParamsLength = sigAlgParamsSz; } } - #endif + #endif } if ((ret == 0) && (!done)) { pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset; @@ -22047,13 +22293,13 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, if ((ret == 0) && (issuer != NULL)) { idx = 0; /* Put issuer into cert and calculate hash. */ - ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer, + ret = GetCertName(cert, cert->issuer, cert->issuerHash, ASN_ISSUER, issuer, &idx, issuerSz); } if ((ret == 0) && (subject != NULL)) { idx = 0; /* Put subject into cert and calculate hash. */ - ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT, + ret = GetCertName(cert, cert->subject, cert->subjectHash, ASN_SUBJECT, subject, &idx, subjectSz); } if (ret == 0) { @@ -22115,8 +22361,8 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, * @return ASN_CRIT_EXT_E when a critical extension was not recognized. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time. * @return ASN_DATE_SZ_E when time data is not supported. - * @return ASN_BEFORE_DATE_E when BEFORE date is invalid. - * @return ASN_AFTER_DATE_E when AFTER date is invalid. + * @return ASN_BEFORE_DATE_E when ASN_BEFORE date is invalid. + * @return ASN_AFTER_DATE_E when ASN_AFTER date is invalid. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or * is invalid. * @return BUFFER_E when data in buffer is too small. @@ -22425,7 +22671,7 @@ static int DecodeCertReq(DecodedCert* cert, int* criticalExt) { DECL_ASNGETDATA(dataASN, certReqASN_Length); int ret = 0; - byte version; + byte version = 0; word32 idx; CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap); @@ -22461,7 +22707,7 @@ static int DecodeCertReq(DecodedCert* cert, int* criticalExt) /* Parse the subject name. */ idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset; - ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT, + ret = GetCertName(cert, cert->subject, cert->subjectHash, ASN_SUBJECT, cert->source, &idx, dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset); } @@ -23034,8 +23280,7 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, FreeSignatureCtx(sigCtx); #ifdef WOLFSSL_SMALL_STACK - if (sigCtx != NULL) - XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); + XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); #endif return ret; #else /* WOLFSSL_ASN_TEMPLATE */ @@ -23293,9 +23538,9 @@ typedef struct DecodeInstr { /* Tag expected. */ byte tag; /* Operation to perform: step in or go over */ - byte op:1; + WC_BITFIELD op:1; /* ASN.1 item is optional. */ - byte optional:1; + WC_BITFIELD optional:1; } DecodeInstr; /* Step into ASN.1 item. */ @@ -23319,7 +23564,7 @@ int wc_CertGetPubKey(const byte* cert, word32 certSz, const unsigned char** pubKey, word32* pubKeySz) { int ret = 0; - int l; + int l = 0; word32 o = 0; int i; static DecodeInstr ops[] = { @@ -24024,8 +24269,10 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer else { /* no signer */ WOLFSSL_MSG("No CA signer to verify with"); + /* If you end up here with error -188, + * consider using WOLFSSL_ALT_CERT_CHAINS. */ #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) - /* ret needs to be self-signer error for Qt compat */ + /* ret needs to be self-signer error for openssl compatibility */ if (cert->selfSigned) { WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E); return ASN_SELF_SIGNED_E; @@ -24241,13 +24488,9 @@ void FreeTrustedPeer(TrustedPeerCert* tp, void* heap) return; } - if (tp->name) { - XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN); - } + XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN); - if (tp->sig) { - XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE); - } + XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE); #ifndef IGNORE_NAME_CONSTRAINTS if (tp->permittedNames) FreeNameSubtrees(tp->permittedNames, heap); @@ -24485,6 +24728,10 @@ wcchar END_CERT = "-----END CERTIFICATE-----"; wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----"; wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----"; #endif +#if defined(WOLFSSL_ACERT) + wcchar BEGIN_ACERT = "-----BEGIN ATTRIBUTE CERTIFICATE-----"; + wcchar END_ACERT = "-----END ATTRIBUTE CERTIFICATE-----"; +#endif /* WOLFSSL_ACERT */ #ifndef NO_DH wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----"; wcchar END_DH_PARAM = "-----END DH PARAMETERS-----"; @@ -24513,6 +24760,10 @@ wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----"; wcchar END_EC_PARAM = "-----END EC PARAMETERS-----"; #endif #endif +#ifdef HAVE_PKCS7 +wcchar BEGIN_PKCS7 = "-----BEGIN PKCS7-----"; +wcchar END_PKCS7 = "-----END PKCS7-----"; +#endif #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ !defined(NO_DSA) wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----"; @@ -24536,12 +24787,20 @@ wcchar END_PUB_KEY = "-----END PUBLIC KEY-----"; wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----"; wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----"; wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----"; wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----"; wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----"; wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----"; + #endif + wcchar BEGIN_ML_DSA_LEVEL2_PRIV = "-----BEGIN ML_DSA_LEVEL2 PRIVATE KEY-----"; + wcchar END_ML_DSA_LEVEL2_PRIV = "-----END ML_DSA_LEVEL2 PRIVATE KEY-----"; + wcchar BEGIN_ML_DSA_LEVEL3_PRIV = "-----BEGIN ML_DSA_LEVEL3 PRIVATE KEY-----"; + wcchar END_ML_DSA_LEVEL3_PRIV = "-----END ML_DSA_LEVEL3 PRIVATE KEY-----"; + wcchar BEGIN_ML_DSA_LEVEL5_PRIV = "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----"; + wcchar END_ML_DSA_LEVEL5_PRIV = "-----END ML_DSA_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_DILITHIUM */ #if defined(HAVE_SPHINCS) wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----"; @@ -24620,6 +24879,20 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) ret = 0; break; #endif + #ifdef HAVE_PKCS7 + case PKCS7_TYPE: + if (header) *header = BEGIN_PKCS7; + if (footer) *footer = END_PKCS7; + ret = 0; + break; + #endif + #if defined(WOLFSSL_ACERT) + case ACERT_TYPE: + if (header) *header = BEGIN_ACERT; + if (footer) *footer = END_ACERT; + ret = 0; + break; + #endif /* WOLFSSL_ACERT */ #ifndef NO_DSA case DSA_TYPE: case DSA_PRIVATEKEY_TYPE: @@ -24678,6 +24951,7 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) break; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2_TYPE: if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV; if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV; @@ -24693,6 +24967,22 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV; ret = 0; break; + #endif + case ML_DSA_LEVEL2_TYPE: + if (header) *header = BEGIN_ML_DSA_LEVEL2_PRIV; + if (footer) *footer = END_ML_DSA_LEVEL2_PRIV; + ret = 0; + break; + case ML_DSA_LEVEL3_TYPE: + if (header) *header = BEGIN_ML_DSA_LEVEL3_PRIV; + if (footer) *footer = END_ML_DSA_LEVEL3_PRIV; + ret = 0; + break; + case ML_DSA_LEVEL5_TYPE: + if (header) *header = BEGIN_ML_DSA_LEVEL5_PRIV; + if (footer) *footer = END_ML_DSA_LEVEL5_PRIV; + ret = 0; + break; #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS case SPHINCS_FAST_LEVEL1_TYPE: @@ -25124,9 +25414,9 @@ int PemToDer(const unsigned char* buff, long longSz, int type, { const char* header = NULL; const char* footer = NULL; - const char* headerEnd; - const char* footerEnd; - const char* consumedEnd; + const char* headerEnd = NULL; + const char* footerEnd = NULL; + const char* consumedEnd = NULL; const char* bufferEnd = (const char*)(buff + longSz); long neededSz; int ret = 0; @@ -25657,7 +25947,7 @@ int wc_CertPemToDer(const unsigned char* pem, int pemSz, } if (type != CERT_TYPE && type != CHAIN_CERT_TYPE && type != CA_TYPE && - type != CERTREQ_TYPE) { + type != CERTREQ_TYPE && type != PKCS7_TYPE) { WOLFSSL_MSG("Bad cert type"); return BAD_FUNC_ARG; } @@ -25948,7 +26238,7 @@ int wc_GetPubKeyDerFromCert(struct DecodedCert* cert, /* if derKey is NULL, return required output buffer size in derKeySz */ if (derKey == NULL) { *derKeySz = cert->pubKeySize; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (ret == 0) { @@ -26015,7 +26305,7 @@ int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz) if (uuid == NULL) { *uuidSz = (word32)id->len; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((int)*uuidSz < id->len) { @@ -26043,7 +26333,7 @@ int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz) if (id != NULL && id->oidSum == FASCN_OID) { if (fascn == NULL) { *fascnSz = (word32)id->len; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((int)*fascnSz < id->len) { @@ -27409,12 +27699,8 @@ static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input) } /* Dispose of allocated data. */ - if (extKuASN != NULL) { - XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (dataASN != NULL) { - XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; #endif @@ -27567,7 +27853,7 @@ static int SetCertificatePolicies(byte *output, byte oid[MAX_OID_SZ]; word32 oidSz; word32 sz = 0; - int piSz; + int piSz = 0; if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) { ret = BAD_FUNC_ARG; @@ -27964,9 +28250,9 @@ static int EncodeName(EncodedName* name, const char* nameStr, break; #ifdef WOLFSSL_CUSTOM_OID case ASN_CUSTOM_NAME: - nameSz = cname->custom.valSz; + nameSz = (word32)cname->custom.valSz; oid = cname->custom.oid; - oidSz = cname->custom.oidSz; + oidSz = (word32)cname->custom.oidSz; break; #endif #ifdef WOLFSSL_CERT_REQ @@ -28033,8 +28319,7 @@ int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr, } #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \ - (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)) +#ifdef WOLFSSL_ASN_PARSE_KEYUSAGE /* Convert key usage string (comma delimited, null terminated) to word16 * Returns 0 on success, negative on error */ @@ -28157,7 +28442,7 @@ int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage, void* heap) return ret; } -#endif /* (CERT_GEN && CERT_EXT) || (OPENSSL_ALL || OPENSSL_EXTRA) */ +#endif /* WOLFSSL_ASN_PARSE_KEYUSAGE */ #ifdef WOLFSSL_CERT_GEN /* Encodes one attribute of the name (issuer/subject) @@ -28291,8 +28576,8 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, else if (type == ASN_CUSTOM_NAME) { #ifdef WOLFSSL_CUSTOM_OID SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid, - name->custom.oidSz, name->custom.enc, - name->custom.val, name->custom.valSz); + (word32)name->custom.oidSz, (byte)name->custom.enc, + name->custom.val, (word32)name->custom.valSz); #endif } else { @@ -28514,10 +28799,8 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) } } - if (namesASN != NULL) - XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (dataASN != NULL) - XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER); (void)heap; return ret; #endif @@ -28591,9 +28874,14 @@ static int EncodePublicKey(int keyType, byte* output, int outLen, break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2_KEY: case DILITHIUM_LEVEL3_KEY: case DILITHIUM_LEVEL5_KEY: + #endif + case ML_DSA_LEVEL2_KEY: + case ML_DSA_LEVEL3_KEY: + case ML_DSA_LEVEL5_KEY: ret = wc_Dilithium_PublicKeyToDer(dilithiumKey, output, (word32)outLen, 1); if (ret <= 0) { @@ -29415,9 +29703,15 @@ static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) - if ((cert->keyType == DILITHIUM_LEVEL2_KEY) || - (cert->keyType == DILITHIUM_LEVEL3_KEY) || - (cert->keyType == DILITHIUM_LEVEL5_KEY)) { + if ((cert->keyType == ML_DSA_LEVEL2_KEY) || + (cert->keyType == ML_DSA_LEVEL3_KEY) || + (cert->keyType == ML_DSA_LEVEL5_KEY) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (cert->keyType == DILITHIUM_LEVEL2_KEY) + || (cert->keyType == DILITHIUM_LEVEL3_KEY) + || (cert->keyType == DILITHIUM_LEVEL5_KEY) + #endif + ) { if (dilithiumKey == NULL) return PUBLIC_KEY_E; @@ -29904,7 +30198,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, case CERTSIGN_STATE_DO: certSignCtx->state = CERTSIGN_STATE_DO; - ret = ALGO_ID_E; /* default to error */ + ret = -1; /* default to error, reassigned to ALGO_ID_E below. */ #ifndef NO_RSA if (rsaKey) { @@ -29958,9 +30252,23 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey && dilithiumKey) { word32 outSz = sigSz; - ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey, rng); - if (ret == 0) - ret = outSz; + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + if ((dilithiumKey->params->level == WC_ML_DSA_44_DRAFT) || + (dilithiumKey->params->level == WC_ML_DSA_65_DRAFT) || + (dilithiumKey->params->level == WC_ML_DSA_87_DRAFT)) { + ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey, + rng); + if (ret == 0) + ret = outSz; + } + else + #endif + { + ret = wc_dilithium_sign_ctx_msg(NULL, 0, buf, sz, sig, + &outSz, dilithiumKey, rng); + if (ret == 0) + ret = outSz; + } } #endif /* HAVE_DILITHIUM */ #if defined(HAVE_SPHINCS) @@ -29973,6 +30281,9 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, } #endif /* HAVE_SPHINCS */ + if (ret == -1) + ret = ALGO_ID_E; + break; } @@ -30103,8 +30414,8 @@ int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz, return (int)(idx + seqSz); #else DECL_ASNSETDATA(dataASN, sigASN_Length); - word32 seqSz; - int sz; + word32 seqSz = 0; + int sz = 0; int ret = 0; CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL); @@ -30195,12 +30506,32 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = FALCON_LEVEL5_KEY; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44_DRAFT)) { cert->keyType = DILITHIUM_LEVEL2_KEY; - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65_DRAFT)) { cert->keyType = DILITHIUM_LEVEL3_KEY; - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87_DRAFT)) { cert->keyType = DILITHIUM_LEVEL5_KEY; + } + #endif + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44)) { + cert->keyType = ML_DSA_LEVEL2_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65)) { + cert->keyType = ML_DSA_LEVEL3_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87)) { + cert->keyType = ML_DSA_LEVEL5_KEY; + } #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS else if ((sphincsKey != NULL) && (sphincsKey->level == 1) @@ -30290,15 +30621,32 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, } #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) { + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44_DRAFT)) { cert->keyType = DILITHIUM_LEVEL2_KEY; } - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) { + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65_DRAFT)) { cert->keyType = DILITHIUM_LEVEL3_KEY; } - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) { + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87_DRAFT)) { cert->keyType = DILITHIUM_LEVEL5_KEY; } + #endif + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_44)) { + cert->keyType = ML_DSA_LEVEL2_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_65)) { + cert->keyType = ML_DSA_LEVEL3_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_87)) { + cert->keyType = ML_DSA_LEVEL5_KEY; + } #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS else if ((sphincsKey != NULL) && (sphincsKey->level == 1) @@ -30603,12 +30951,20 @@ int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType, falconKey = (falcon_key*)key; else if (keyType == FALCON_LEVEL5_TYPE) falconKey = (falcon_key*)key; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT else if (keyType == DILITHIUM_LEVEL2_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL3_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL5_TYPE) dilithiumKey = (dilithium_key*)key; +#endif + else if (keyType == ML_DSA_LEVEL2_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL3_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL5_TYPE) + dilithiumKey = (dilithium_key*)key; else if (keyType == SPHINCS_FAST_LEVEL1_TYPE) sphincsKey = (sphincs_key*)key; else if (keyType == SPHINCS_FAST_LEVEL3_TYPE) @@ -30910,9 +31266,15 @@ static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey, } #endif #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_ASN1) - if ((cert->keyType == DILITHIUM_LEVEL2_KEY) || - (cert->keyType == DILITHIUM_LEVEL3_KEY) || - (cert->keyType == DILITHIUM_LEVEL5_KEY)) { + if ((cert->keyType == ML_DSA_LEVEL2_KEY) || + (cert->keyType == ML_DSA_LEVEL3_KEY) || + (cert->keyType == ML_DSA_LEVEL5_KEY) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (cert->keyType == DILITHIUM_LEVEL2_KEY) + || (cert->keyType == DILITHIUM_LEVEL3_KEY) + || (cert->keyType == DILITHIUM_LEVEL5_KEY) + #endif + ) { if (dilithiumKey == NULL) return PUBLIC_KEY_E; der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey, @@ -31264,12 +31626,32 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, cert->keyType = FALCON_LEVEL5_KEY; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44_DRAFT)) { cert->keyType = DILITHIUM_LEVEL2_KEY; - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65_DRAFT)) { cert->keyType = DILITHIUM_LEVEL3_KEY; - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87_DRAFT)) { cert->keyType = DILITHIUM_LEVEL5_KEY; + } + #endif + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44)) { + cert->keyType = ML_DSA_LEVEL2_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65)) { + cert->keyType = ML_DSA_LEVEL3_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87)) { + cert->keyType = ML_DSA_LEVEL5_KEY; + } #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS else if ((sphincsKey != NULL) && (sphincsKey->level == 1) @@ -31360,15 +31742,32 @@ static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, } #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) { + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_44_DRAFT)) { cert->keyType = DILITHIUM_LEVEL2_KEY; } - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) { + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_65_DRAFT)) { cert->keyType = DILITHIUM_LEVEL3_KEY; } - else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) { + else if ((dilithiumKey != NULL) && + (dilithiumKey->params->level == WC_ML_DSA_87_DRAFT)) { cert->keyType = DILITHIUM_LEVEL5_KEY; } + #endif + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_44)) { + cert->keyType = ML_DSA_LEVEL2_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_65)) { + cert->keyType = ML_DSA_LEVEL3_KEY; + } + else if ((dilithiumKey != NULL) && + (dilithiumKey->level == WC_ML_DSA_87)) { + cert->keyType = ML_DSA_LEVEL5_KEY; + } #endif /* HAVE_DILITHIUM */ #ifdef HAVE_SPHINCS else if ((sphincsKey != NULL) && (sphincsKey->level == 1) @@ -31580,12 +31979,20 @@ int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType, falconKey = (falcon_key*)key; else if (keyType == FALCON_LEVEL5_TYPE) falconKey = (falcon_key*)key; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT else if (keyType == DILITHIUM_LEVEL2_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL3_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL5_TYPE) dilithiumKey = (dilithium_key*)key; +#endif + else if (keyType == ML_DSA_LEVEL2_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL3_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL5_TYPE) + dilithiumKey = (dilithium_key*)key; else if (keyType == SPHINCS_FAST_LEVEL1_TYPE) sphincsKey = (sphincs_key*)key; else if (keyType == SPHINCS_FAST_LEVEL3_TYPE) @@ -31726,9 +32133,14 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, case FALCON_LEVEL5_TYPE: falconKey = (falcon_key*)key; break; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2_TYPE: case DILITHIUM_LEVEL3_TYPE: case DILITHIUM_LEVEL5_TYPE: +#endif + case ML_DSA_LEVEL2_TYPE: + case ML_DSA_LEVEL3_TYPE: + case ML_DSA_LEVEL5_TYPE: dilithiumKey = (dilithium_key*)key; break; case SPHINCS_FAST_LEVEL1_TYPE: @@ -31829,12 +32241,20 @@ int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz, falconKey = (falcon_key*)key; else if (keyType == FALCON_LEVEL5_TYPE) falconKey = (falcon_key*)key; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT else if (keyType == DILITHIUM_LEVEL2_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL3_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL5_TYPE) dilithiumKey = (dilithium_key*)key; +#endif + else if (keyType == ML_DSA_LEVEL2_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL3_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL5_TYPE) + dilithiumKey = (dilithium_key*)key; else if (keyType == SPHINCS_FAST_LEVEL1_TYPE) sphincsKey = (sphincs_key*)key; else if (keyType == SPHINCS_FAST_LEVEL3_TYPE) @@ -31882,7 +32302,7 @@ int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz, WOLFSSL_ABI int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert) { - int rc = BAD_FUNC_ARG; + int rc = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if ((subjectRaw != NULL) && (cert != NULL)) { *subjectRaw = cert->sbjRaw; rc = 0; @@ -32008,12 +32428,20 @@ int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key) falconKey = (falcon_key*)key; else if (keyType == FALCON_LEVEL5_TYPE) falconKey = (falcon_key*)key; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT else if (keyType == DILITHIUM_LEVEL2_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL3_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL5_TYPE) dilithiumKey = (dilithium_key*)key; +#endif + else if (keyType == ML_DSA_LEVEL2_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL3_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL5_TYPE) + dilithiumKey = (dilithium_key*)key; else if (keyType == SPHINCS_FAST_LEVEL1_TYPE) sphincsKey = (sphincs_key*)key; else if (keyType == SPHINCS_FAST_LEVEL3_TYPE) @@ -32061,12 +32489,20 @@ int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key) falconKey = (falcon_key*)key; else if (keyType == FALCON_LEVEL5_TYPE) falconKey = (falcon_key*)key; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT else if (keyType == DILITHIUM_LEVEL2_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL3_TYPE) dilithiumKey = (dilithium_key*)key; else if (keyType == DILITHIUM_LEVEL5_TYPE) dilithiumKey = (dilithium_key*)key; +#endif + else if (keyType == ML_DSA_LEVEL2_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL3_TYPE) + dilithiumKey = (dilithium_key*)key; + else if (keyType == ML_DSA_LEVEL5_TYPE) + dilithiumKey = (dilithium_key*)key; else if (keyType == SPHINCS_FAST_LEVEL1_TYPE) sphincsKey = (sphincs_key*)key; else if (keyType == SPHINCS_FAST_LEVEL3_TYPE) @@ -32332,7 +32768,7 @@ int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx, } XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz); - cert->extKeyUsageOIDSz[idx] = oidSz; + cert->extKeyUsageOIDSz[idx] = (byte)oidSz; cert->extKeyUsage |= EXTKEYUSE_USER; return 0; @@ -32368,7 +32804,7 @@ int wc_SetCustomExtension(Cert *cert, int critical, const char *oid, ext->oid = (char*)oid; ext->crit = (critical == 0) ? 0 : 1; ext->val = (byte*)der; - ext->valSz = derSz; + ext->valSz = (int)derSz; cert->customCertExtCount++; return 0; @@ -33659,9 +34095,9 @@ static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz, #else if (ret == 0) { /* Base X-ordinate */ - DataToHexString(base + 1, curve->size, curve->Gx); + DataToHexString(base + 1, (word32)curve->size, curve->Gx); /* Base Y-ordinate */ - DataToHexString(base + 1 + curve->size, curve->size, curve->Gy); + DataToHexString(base + 1 + curve->size, (word32)curve->size, curve->Gy); /* Prime */ DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data, dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length, @@ -33886,6 +34322,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, int curve_id = ECC_CURVE_DEF; #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2) word32 algId = 0; + word32 eccOid = 0; #endif /* Validate parameters. */ @@ -33895,11 +34332,11 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2) /* if has pkcs8 header skip it */ - if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) { + if (ToTraditionalInline_ex2(input, inOutIdx, inSz, &algId, &eccOid) < 0) { /* ignore error, did not have pkcs8 header */ } else { - curve_id = wc_ecc_get_oid(algId, NULL, NULL); + curve_id = wc_ecc_get_oid(eccOid, NULL, NULL); } #endif @@ -34392,7 +34829,7 @@ int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx, #endif /* WOLFSSL_ASN_TEMPLATE */ } -#if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT) +#ifdef HAVE_ECC_KEY_EXPORT /* build DER formatted ECC key, include optional public key if requested, * return length on success, negative on error */ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, @@ -34527,7 +34964,7 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } #endif - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (inLen != NULL && totalSz > *inLen) { #ifndef WOLFSSL_NO_MALLOC @@ -34639,7 +35076,7 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, /* Return the size if no buffer. */ if ((ret == 0) && (output == NULL)) { *inLen = (word32)sz; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* Check the buffer is big enough. */ if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) { @@ -34684,6 +35121,7 @@ int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen, /* Write a Private ecc key, including public to DER format, * length on success else < 0 */ +/* Note: use wc_EccKeyDerSize to get length only */ WOLFSSL_ABI int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen) { @@ -34695,10 +35133,7 @@ int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen) int wc_EccKeyDerSize(ecc_key* key, int pub) { word32 sz = 0; - int ret; - - ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1); - + int ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1); if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } @@ -34709,7 +35144,11 @@ int wc_EccKeyDerSize(ecc_key* key, int pub) * length on success else < 0 */ int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen) { - return wc_BuildEccKeyDer(key, output, &inLen, 0, 1); + int ret = wc_BuildEccKeyDer(key, output, &inLen, 0, 1); + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { + return (int)inLen; + } + return ret; } #ifdef HAVE_PKCS8 @@ -34778,7 +35217,7 @@ static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen, XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif *outLen = pkcs8Sz; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*outLen < pkcs8Sz) { @@ -34823,7 +35262,7 @@ int wc_EccKeyToPKCS8(ecc_key* key, byte* output, return eccToPKCS8(key, output, outLen, 1); } #endif /* HAVE_PKCS8 */ -#endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */ +#endif /* HAVE_ECC_KEY_EXPORT */ #endif /* HAVE_ECC */ #ifdef WC_ENABLE_ASYM_KEY_IMPORT @@ -35042,7 +35481,7 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, word32 oid; #else word32 len; - DECL_ASNGETDATA(dataASN, edPubKeyASN_Length); + DECL_ASNGETDATA(dataASN, publicKeyASN_Length); #endif if (input == NULL || inSz == 0 || inOutIdx == NULL || @@ -35077,17 +35516,17 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, #else len = inSz - *inOutIdx; - CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL); + CALLOC_ASNGETDATA(dataASN, publicKeyASN_Length, ret, NULL); if (ret == 0) { /* Require OID. */ word32 oidSz; const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz); - GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz); + GetASN_ExpBuffer(&dataASN[PUBKEYASN_IDX_ALGOID_OID], oid, oidSz); /* Decode Ed25519 private key. */ - ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input, - inOutIdx, inSz); + ret = GetASN_Items(publicKeyASN, dataASN, publicKeyASN_Length, 1, + input, inOutIdx, inSz); if (ret != 0) ret = ASN_PARSE_E; /* check that input buffer is exhausted */ @@ -35096,12 +35535,12 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, } /* Check that the all the buffer was used. */ if ((ret == 0) && - (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) { + (GetASNItem_Length(dataASN[PUBKEYASN_IDX_SEQ], input) != len)) { ret = ASN_PARSE_E; } if (ret == 0) { - *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length; - *pubKey = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data; + *pubKeyLen = dataASN[PUBKEYASN_IDX_PUBKEY].data.ref.length; + *pubKey = dataASN[PUBKEYASN_IDX_PUBKEY].data.ref.data; } FREE_ASNGETDATA(dataASN, NULL); @@ -35251,13 +35690,16 @@ int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz; #else DECL_ASNSETDATA(dataASN, edKeyASN_Length); - int sz; + int sz = 0; #endif - /* Validate parameters. */ - if (privKey == NULL || outLen == 0) { + /* validate parameters */ + if (privKey == NULL) { return BAD_FUNC_ARG; } + if (output != NULL && outLen == 0) { + return BUFFER_E; + } #ifndef WOLFSSL_ASN_TEMPLATE /* calculate size */ @@ -35415,7 +35857,7 @@ int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen, byte pubKey[CURVE25519_PUB_KEY_SIZE]; word32 pubKeyLen = (word32)sizeof(pubKey); - if (key == NULL || output == NULL) { + if (key == NULL) { return BAD_FUNC_ARG; } @@ -35788,7 +36230,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, if (idx >= size) return BUFFER_E; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#ifdef WOLFSSL_OCSP_PARSE_STATUS single->status->thisDateAsn = source + idx; localIdx = 0; if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL, @@ -35809,7 +36251,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, #ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK - if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE)) + if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, ASN_BEFORE)) return ASN_BEFORE_DATE_E; #endif #endif @@ -35824,7 +36266,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, idx++; if (GetLength(source, &idx, &length, size) < 0) return ASN_PARSE_E; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#ifdef WOLFSSL_OCSP_PARSE_STATUS single->status->nextDateAsn = source + idx; localIdx = 0; if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL, @@ -35845,7 +36287,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, #ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK - if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER)) + if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, ASN_AFTER)) return ASN_AFTER_DATE_E; #endif #endif @@ -35866,7 +36308,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, *ioIndex = idx; return 0; -#else +#else /* WOLFSSL_ASN_TEMPLATE */ DECL_ASNGETDATA(dataASN, singleResponseASN_Length); int ret = 0; word32 ocspDigestSize = OCSP_DIGEST_SIZE; @@ -35876,10 +36318,6 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, word32 issuerKeyHashLen; word32 thisDateLen; word32 nextDateLen; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) - WOLFSSL_ASN1_TIME *at; -#endif (void)wrapperSz; @@ -35953,48 +36391,49 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, /* Store the thisDate format - only one possible. */ cs->thisDateFormat = ASN_GENERALIZED_TIME; #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) - /* Check date is a valid string and BEFORE now. */ - if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) { + /* Check date is a valid string and ASN_BEFORE now. */ + if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, ASN_BEFORE)) { ret = ASN_BEFORE_DATE_E; } + #endif /* !NO_ASN_TIME_CHECK && !WOLFSSL_NO_OCSP_DATE_CHECK */ } +#ifdef WOLFSSL_OCSP_PARSE_STATUS if (ret == 0) { - #endif - #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) /* Store ASN.1 version of thisDate. */ + WOLFSSL_ASN1_TIME *at; cs->thisDateAsn = GetASNItem_Addr( dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source); at = &cs->thisDateParsed; at->type = ASN_GENERALIZED_TIME; XMEMCPY(at->data, cs->thisDate, thisDateLen); at->length = (int)thisDateLen; - #endif } +#endif if ((ret == 0) && (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) { /* Store the nextDate format - only one possible. */ cs->nextDateFormat = ASN_GENERALIZED_TIME; #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) - /* Check date is a valid string and AFTER now. */ - if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) { + /* Check date is a valid string and ASN_AFTER now. */ + if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, ASN_AFTER)) { ret = ASN_AFTER_DATE_E; } + #endif /* !NO_ASN_TIME_CHECK && !WOLFSSL_NO_OCSP_DATE_CHECK */ } +#ifdef WOLFSSL_OCSP_PARSE_STATUS if ((ret == 0) && - (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) { - #endif - #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) + (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) + { /* Store ASN.1 version of thisDate. */ + WOLFSSL_ASN1_TIME *at; cs->nextDateAsn = GetASNItem_Addr( dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source); at = &cs->nextDateParsed; at->type = ASN_GENERALIZED_TIME; XMEMCPY(at->data, cs->nextDate, nextDateLen); at->length = (int)nextDateLen; - #endif } +#endif if (ret == 0) { /* OcspEntry now used. */ single->used = 1; @@ -36002,7 +36441,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, FREE_ASNGETDATA(dataASN, NULL); return ret; -#endif +#endif /* WOLFSSL_ASN_TEMPLATE */ } #ifdef WOLFSSL_ASN_TEMPLATE @@ -36614,7 +37053,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, int sigValid = -1; #ifndef NO_SKID - ca = GetCA(cm, resp->single->issuerKeyHash); + ca = GetCAByKeyHash(cm, resp->single->issuerKeyHash); #else ca = GetCA(cm, resp->single->issuerHash); #endif @@ -36755,7 +37194,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, /* Response didn't have a certificate - lookup CA. */ #ifndef NO_SKID - ca = GetCA(cm, resp->single->issuerKeyHash); + ca = GetCAByKeyHash(cm, resp->single->issuerKeyHash); #else ca = GetCA(cm, resp->single->issuerHash); #endif @@ -37392,8 +37831,7 @@ void FreeOcspRequest(OcspRequest* req) WOLFSSL_ENTER("FreeOcspRequest"); if (req) { - if (req->serial) - XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); + XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); req->serial = NULL; #ifdef OPENSSL_EXTRA @@ -37406,13 +37844,10 @@ void FreeOcspRequest(OcspRequest* req) req->serialInt = NULL; #endif - if (req->url) - XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); + XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST); req->url = NULL; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \ - defined(HAVE_LIGHTY) +#ifdef OPENSSL_EXTRA if (req->cid != NULL) wolfSSL_OCSP_CERTID_free((WOLFSSL_OCSP_CERTID*)req->cid); req->cid = NULL; @@ -37630,8 +38065,7 @@ void FreeDecodedCRL(DecodedCRL* dcrl) tmp = next; } #ifdef OPENSSL_EXTRA - if (dcrl->issuer != NULL) - XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL); #endif } @@ -38009,7 +38443,7 @@ static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl, { #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK) if (verify != NO_VERIFY && - !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) { + !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL after date is no longer valid"); WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR); return CRL_CERT_DATE_ERR; @@ -38072,6 +38506,7 @@ static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl) } dcrl->extAuthKeyIdSet = 1; + /* Get the hash or hash of the hash if wrong size. */ ret = GetHashId(input + idx, length, dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID)); @@ -38097,6 +38532,8 @@ static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl) WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available"); } else { + dcrl->extAuthKeyIdSet = 1; + /* Get the hash or hash of the hash if wrong size. */ ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data, (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length, @@ -38570,7 +39007,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, tbsParams = GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_SIGALGO_PARAMS], buff); - tbsParamsSz = + tbsParamsSz =(int) GetASNItem_Length(dataASN[CRLASN_IDX_TBS_SIGALGO_PARAMS], buff); } @@ -38578,7 +39015,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, sigParams = GetASNItem_Addr(dataASN[CRLASN_IDX_SIGALGO_PARAMS], buff); - sigParamsSz = + sigParamsSz = (int) GetASNItem_Length(dataASN[CRLASN_IDX_SIGALGO_PARAMS], buff); dcrl->sigParamsIndex = @@ -38605,7 +39042,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, ret = ASN_PARSE_E; } else if ((tbsParamsSz > 0) && - (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) { + (XMEMCMP(tbsParams, sigParams, (word32)tbsParamsSz) != 0)) { WOLFSSL_MSG("CRL TBS and signature parameter mismatch"); ret = ASN_PARSE_E; } @@ -38622,7 +39059,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, if (dcrl->nextDateFormat != 0) { /* Next date was set, so validate it. */ if (verify != NO_VERIFY && - !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) { + !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL after date is no longer valid"); ret = CRL_CERT_DATE_ERR; WOLFSSL_ERROR_VERBOSE(ret); @@ -38934,10 +39371,8 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) mimeType == MIME_PARAM)) && pos >= 1) { mimeStatus = MIME_BODYVAL; end = pos-1; - if (nameAttr != NULL) { - XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7); - nameAttr = NULL; - } + XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7); + nameAttr = NULL; ret = wc_MIME_header_strip(curLine, &nameAttr, start, end); if (ret) { goto error; @@ -38946,10 +39381,8 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) } else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) { end = pos-1; - if (bodyVal != NULL) { - XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7); - bodyVal = NULL; - } + XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7); + bodyVal = NULL; ret = wc_MIME_header_strip(curLine, &bodyVal, start, end); if (ret) { goto error; @@ -39042,12 +39475,9 @@ int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers) if (ret != 0) wc_MIME_free_hdrs(curHdr); wc_MIME_free_hdrs(nextHdr); - if (nameAttr != NULL) - XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7); - if (bodyVal != NULL) - XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7); - if (nextParam != NULL) - XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7); + XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7); return ret; } @@ -40029,6 +40459,1032 @@ int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e, } #endif /* !NO_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */ +#if defined(WOLFSSL_ACERT) && defined(WOLFSSL_ASN_TEMPLATE) +/* Initialize decoded certificate object with buffer of DER encoding. + * + * @param [in, out] cert Decoded certificate object. + * @param [in] source Buffer containing DER encoded certificate. + * @param [in] inSz Size of DER data in buffer in bytes. + * @param [in] heap Dynamic memory hint. + */ +void InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, + void* heap) +{ + if (acert == NULL) { + return; + } + + WOLFSSL_MSG("InitDecodedAcert"); + + XMEMSET(acert, 0, sizeof(DecodedAcert)); + acert->heap = heap; + acert->source = source; /* don't own */ + acert->maxIdx = inSz; /* can't go over this index */ + acert->heap = heap; + + InitSignatureCtx(&acert->sigCtx, heap, INVALID_DEVID); + + return; +} + +/* Free the decoded attribute cert object's dynamic data. + * + * @param [in, out] acert Attribute Decoded certificate object. + */ +void FreeDecodedAcert(DecodedAcert * acert) +{ + if (acert == NULL) { + return; + } + + WOLFSSL_MSG("FreeDecodedAcert"); + + if (acert->holderIssuerName) { + FreeAltNames(acert->holderIssuerName, acert->heap); + acert->holderIssuerName = NULL; + } + + if (acert->holderEntityName) { + FreeAltNames(acert->holderEntityName, acert->heap); + acert->holderEntityName = NULL; + } + + if (acert->AttCertIssuerName) { + FreeAltNames(acert->AttCertIssuerName, acert->heap); + acert->AttCertIssuerName = NULL; + } + + FreeSignatureCtx(&acert->sigCtx); + + XMEMSET(acert, 0, sizeof(DecodedAcert)); + return; +} + +/* Decode an Attribute Cert GeneralName field. + * + * @param [in] input Buffer containing encoded OtherName. + * @param [in, out] inOutIdx On in, the index of the start of the OtherName. + * On out, index after OtherName. + * @param [in] len Length of data in buffer. + * @param [in] cert Decoded attribute certificate object. + * @param [in, out] entries Linked list of DNS name entries. + * + * @return 0 on success. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int DecodeAcertGeneralName(const byte* input, word32* inOutIdx, + byte tag, int len, DecodedAcert* acert, + DNS_entry** entries) +{ + int ret = 0; + word32 idx = *inOutIdx; + + /* GeneralName choice: dnsName */ + if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) { + ret = SetDNSEntry(acert->heap, (const char*)(input + idx), len, + ASN_DNS_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } +#ifndef IGNORE_NAME_CONSTRAINTS + /* GeneralName choice: directoryName */ + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) { + int strLen = 0; + word32 idxDir = idx; + + /* Expecting a SEQUENCE using up all data. */ + if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0) + { + WOLFSSL_MSG("\tfail: seq length"); + return ASN_PARSE_E; + } + + ret = SetDNSEntry(acert->heap, (const char*)(input + idxDir), strLen, + ASN_DIR_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } + /* GeneralName choice: rfc822Name */ + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) { + ret = SetDNSEntry(acert->heap, (const char*)(input + idx), len, + ASN_RFC822_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } + /* GeneralName choice: uniformResourceIdentifier */ + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) { + WOLFSSL_MSG("\tPutting URI into list but not using"); + + #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI) + /* Verify RFC 5280 Sec 4.2.1.6 rule: + "The name MUST NOT be a relative URI" + As per RFC 3986 Sec 4.3, an absolute URI is only required to contain + a scheme and hier-part. So the only strict requirement is a ':' + being present after the scheme. If a '/' is present as part of the + hier-part, it must come after the ':' (see RFC 3986 Sec 3). */ + { + int i = 0; + + /* skip past scheme (i.e http,ftp,...) finding first ':' char */ + for (i = 0; i < len; i++) { + if (input[idx + (word32)i] == ':') { + break; + } + if (input[idx + (word32)i] == '/') { + i = len; /* error, found relative path since '/' was + * encountered before ':'. Returning error + * value in next if statement. */ + } + } + + /* test hier-part is empty */ + if (i == 0 || i == len) { + WOLFSSL_MSG("\tEmpty or malformed URI"); + WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E); + return ASN_ALT_NAME_E; + } + + /* test if scheme is missing */ + if (input[idx + (word32)i] != ':') { + WOLFSSL_MSG("\tAlt Name must be absolute URI"); + WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E); + return ASN_ALT_NAME_E; + } + } + #endif + + ret = SetDNSEntry(acert->heap, (const char*)(input + idx), len, + ASN_URI_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } + #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \ + defined(WOLFSSL_IP_ALT_NAME) + /* GeneralName choice: iPAddress */ + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) { + ret = SetDNSEntry(acert->heap, (const char*)(input + idx), len, + ASN_IP_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } + #endif /* WOLFSSL_QT || OPENSSL_ALL */ + + #ifdef OPENSSL_ALL + /* GeneralName choice: registeredID */ + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) { + ret = SetDNSEntry(acert->heap, (const char*)(input + idx), len, + ASN_RID_TYPE, entries); + if (ret == 0) { + idx += (word32)len; + } + } + #endif +#endif /* IGNORE_NAME_CONSTRAINTS */ + /* GeneralName choice: dNSName, x400Address, ediPartyName */ + else { + WOLFSSL_MSG("\tUnsupported name type, skipping"); + idx += (word32)len; + } + + if (ret == 0) { + /* Return index of next encoded byte. */ + *inOutIdx = idx; + } + return ret; +} + +/* Decode General Names from an ACERT input. + * + * @param [in] input Buffer holding encoded data. + * @param [in] sz Size of encoded data in bytes. + * @param [in, out] cert Decoded certificate object. + * @param [in, out] entries Linked list of DNS name entries. + * + * @return 0 on success. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int DecodeAcertGeneralNames(const byte* input, word32 sz, + DecodedAcert* acert, + DNS_entry** entries) +{ + word32 idx = 0; + int length = 0; + int ret = 0; + word32 numNames = 0; + + /* Get SEQUENCE and expect all data to be accounted for. */ + if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) { + WOLFSSL_MSG("\tBad Sequence"); + return ASN_PARSE_E; + } + + if (length == 0) { + /* There is supposed to be a non-empty sequence here. */ + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + + if ((word32)length + idx != sz) { + return ASN_PARSE_E; + } + + while ((ret == 0) && (idx < sz)) { + ASNGetData dataASN[altNameASN_Length]; + + numNames++; + if (numNames > WOLFSSL_MAX_ALT_NAMES) { + WOLFSSL_MSG("error: acert: too many subject alternative names"); + ret = ASN_ALT_NAME_E; + break; + } + + /* Clear dynamic data items. */ + XMEMSET(dataASN, 0, sizeof(dataASN)); + /* Parse GeneralName with the choices supported. */ + GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice); + /* Decode a GeneralName choice. */ + ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input, + &idx, sz); + + if (ret != 0) { + break; + } + + ret = DecodeAcertGeneralName(input, &idx, + dataASN[ALTNAMEASN_IDX_GN].tag, + (int)dataASN[ALTNAMEASN_IDX_GN].length, + acert, entries); + } + + return ret; +} + +/* Holder has three potential forms: + * Holder ::= SEQUENCE { + * baseCertificateID [0] IssuerSerial OPTIONAL, + * -- the issuer and serial number of + * -- the holder's Public Key Certificate + * entityName [1] GeneralNames OPTIONAL, + * -- the name of the claimant or role + * objectDigestInfo [2] ObjectDigestInfo OPTIONAL + * -- used to directly authenticate the holder, + * -- for example, an executable + * } + * + * where IssuerSerial is: + * IssuerSerial ::= SEQUENCE { + * issuer GeneralNames, + * serial CertificateSerialNumber, + * issuerUID UniqueIdentifier OPTIONAL + * } + * + * Note: + * - Holder Option 2 objectDigestInfo is not mandatory + * for the spec and is not implemented here yet. + * + * - issuerUniqueID not supported yet. + * */ +static const ASNItem HolderASN[] = +{ + /* Holder root sequence. */ +/* HOLDER_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, + /* Holder Option 0:*/ +/* ISSUERSERIAL_SEQ */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 2 }, + /* issuer GeneralNames, */ +/* GN_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 }, + /* serial CertificateSerialNumber */ +/* SERIAL_INT */ { 2, ASN_INTEGER, 0, 0, 0 }, + /* Holder Option 1:*/ +/* GN_SEQ */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 }, +}; + +enum { + HOLDER_IDX_SEQ = 0, + HOLDER_IDX_ISSUERSERIAL_SEQ, + HOLDER_IDX_GN_SEQ, + HOLDER_IDX_SERIAL_INT, + HOLDER_IDX_GN_SEQ_OPT1 +}; + +/* Number of items in ASN template for an X509 Acert. */ +#define HolderASN_Length (sizeof(HolderASN) / sizeof(ASNItem)) + +/* Decode the Holder field of an x509 attribute certificate. + * + * + * @param [in] input Buffer containing encoded Holder field. + * @param [in] len Length of Holder field. + * @param [in] cert Decoded certificate object. + * + * @return 0 on success. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. + * @return MEMORY_E when dynamic memory allocation fails. + * */ +static int DecodeHolder(const byte* input, word32 len, DecodedAcert* acert) +{ + DECL_ASNGETDATA(dataASN, HolderASN_Length); + int ret = 0; + word32 idx = 0; + word32 holderSerialSz = 0; + + if (input == NULL || len <= 0 || acert == NULL) { + return BUFFER_E; + } + + CALLOC_ASNGETDATA(dataASN, HolderASN_Length, ret, acert->heap); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, acert->heap); + return MEMORY_E; + } + + holderSerialSz = EXTERNAL_SERIAL_SIZE; + + GetASN_Buffer(&dataASN[HOLDER_IDX_SERIAL_INT], acert->holderSerial, + &holderSerialSz); + + ret = GetASN_Items(HolderASN, dataASN, HolderASN_Length, 0, input, + &idx, len); + + if (ret != 0) { + WOLFSSL_MSG("error: Holder: GetASN_Items failed"); + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; + } + + if (dataASN[HOLDER_IDX_SERIAL_INT].tag != 0) { + acert->holderSerialSz = (int)holderSerialSz; + } + else { + acert->holderSerialSz = 0; + } + + { + /* Now parse the GeneralNames field. + * Use the HOLDER_IDX_GN_SEQ offset for input. */ + const byte * gn_input = NULL; + word32 gn_len = 0; + word32 holder_index = HOLDER_IDX_GN_SEQ; + + /* Determine which tag was seen. */ + if (dataASN[HOLDER_IDX_GN_SEQ].tag != 0) { + gn_input = input + dataASN[holder_index].offset; + gn_len = dataASN[holder_index].length + 2; + } + else { + gn_input = input; + gn_len = len; + } + + ret = DecodeAcertGeneralNames(gn_input, gn_len, acert, + &acert->holderIssuerName); + + if (ret != 0) { + WOLFSSL_MSG("error: Holder: DecodeAcertGeneralNames failed"); + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; + } + } + + FREE_ASNGETDATA(dataASN, acert->heap); + return 0; +} + +/* From RFC 5755. + * 4.2.3. Issuer + * + * ACs conforming to this profile MUST use the v2Form choice, which MUST + * contain one and only one GeneralName in the issuerName, which MUST + * contain a non-empty distinguished name in the directoryName field. + * This means that all AC issuers MUST have non-empty distinguished + * names. ACs conforming to this profile MUST omit the + * baseCertificateID and objectDigestInfo fields. + * + * 4.1. X.509 Attribute Certificate Definition + * + * AttCertIssuer ::= CHOICE { + * v1Form GeneralNames, -- MUST NOT be used in this + * -- profile + * v2Form [0] V2Form -- v2 only + * } + * + * V2Form ::= SEQUENCE { + * issuerName GeneralNames OPTIONAL, + * baseCertificateID [0] IssuerSerial OPTIONAL, + * objectDigestInfo [1] ObjectDigestInfo OPTIONAL + * -- issuerName MUST be present in this profile + * -- baseCertificateID and objectDigestInfo MUST + * -- NOT be present in this profile + * } + * */ +static const ASNItem AttCertIssuerASN[] = +{ + /* V2Form ::= SEQUENCE { */ +/* AttCertIssuer_GN_SEQ */ { 0, ASN_SEQUENCE, 1, 0, 0 }, +}; + +enum { + ATTCERTISSUER_IDX_GN_SEQ +}; + +/* Number of items in ASN template for an X509 Acert. */ +#define AttCertIssuerASN_Length (sizeof(AttCertIssuerASN) / sizeof(ASNItem)) + +/* Decode the AttCertIssuer Field of an x509 attribute certificate. + * + * + * @param [in] input Buffer containing encoded AttCertIssuer field. + * @param [in] len Length of Holder field. + * @param [in] cert Decoded certificate object. + * + * @return 0 on success. + * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or + * is invalid. + * @return BUFFER_E when data in buffer is too small. + * @return ASN_UNKNOWN_OID_E when the OID cannot be verified. + * @return MEMORY_E when dynamic memory allocation fails. + * */ +static int DecodeAttCertIssuer(const byte* input, word32 len, + DecodedAcert* cert) +{ + DECL_ASNGETDATA(dataASN, AttCertIssuerASN_Length); + int ret = 0; + word32 idx = 0; + const byte * gn_input = NULL; + word32 gn_len = 0; + + if (input == NULL || len <= 0 || cert == NULL) { + return BUFFER_E; + } + + CALLOC_ASNGETDATA(dataASN, AttCertIssuerASN_Length, ret, cert->heap); + + if (ret != 0) { + return MEMORY_E; + } + + ret = GetASN_Items(AttCertIssuerASN, dataASN, AttCertIssuerASN_Length, + 0, input, &idx, len); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, cert->heap); + WOLFSSL_MSG("error: AttCertIssuer: GetASN_Items failed"); + return ret; + } + + /* Now parse the GeneralNames field. + * Use the HOLDER_IDX_GN_SEQ offset for input. */ + gn_input = input + dataASN[ATTCERTISSUER_IDX_GN_SEQ].offset; + gn_len = dataASN[ATTCERTISSUER_IDX_GN_SEQ].length + 2; + + ret = DecodeAcertGeneralNames(gn_input, gn_len, cert, + &cert->AttCertIssuerName); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, cert->heap); + WOLFSSL_MSG("error: AttCertIssuer: DecodeAcertGeneralNames failed"); + return ret; + } + + FREE_ASNGETDATA(dataASN, cert->heap); + return 0; +} + + +/* ASN template for an X509 Attribute Certificate, + * from RFC 5755 + */ +static const ASNItem AcertASN[] = +{ + /* AttributeCertificate ::= SEQUENCE */ +/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, + /* AttributeCertificateInfo ::= SEQUENCE */ +/* ACINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, + /* AttCertVersion ::= INTEGER { v2(1) } */ +/* ACINFO_VER_INT */ { 2, ASN_INTEGER, 0, 0, 0 }, + /* holder Holder */ +/* ACINFO_HOLDER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 }, + /* issuer AttCertIssuer */ +/* ACINFO_CHOICE_SEQ */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 2 }, +/* ACINFO_ISSUER_SEQ */ { 2, ASN_SEQUENCE | 0, 1, 0, 2 }, + /* signature AlgorithmIdentifier */ + /* AlgorithmIdentifier ::= SEQUENCE */ +/* ACINFO_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, + /* Algorithm OBJECT IDENTIFIER */ +/* ACINFO_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 }, + /* parameters */ +/* ACINFO_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 }, +#ifdef WC_RSA_PSS +/* ACINFO_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 }, +#endif + /* CertificateSerialNumber ::= INTEGER */ +/* ACINFO_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 }, + /* Validity ::= SEQUENCE */ +/* ACINFO_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, + /* notBeforeTime GeneralizedTime, */ +/* ACINFO_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 }, + /* notAfterTime GeneralizedTime */ +/* ACINFO_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 }, + /* attributes SEQUENCE OF Attribute */ +/* ACINFO_ATTRIBUTES_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 }, + /* issuerUniqueID OPTIONAL, */ +/* ACINFO_UNIQUE_ID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 }, + /* extensions OPTIONAL */ +/* ACINFO_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 1, 1 }, +/* ACINFO_EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 }, + /* signature AlgorithmIdentifier */ + /* AlgorithmIdentifier ::= SEQUENCE */ +/* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, + /* Algorithm OBJECT IDENTIFIER */ +/* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 }, + /* parameters */ +/* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 }, +#ifdef WC_RSA_PSS +/* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 }, +#endif + /* signature BIT STRING */ +/* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 }, +}; + +enum { + ACERT_IDX_SEQ = 0, + ACERT_IDX_ACINFO_SEQ, + ACERT_IDX_ACINFO_VER_INT, + /* ACINFO holder and issuer */ + ACERT_IDX_ACINFO_HOLDER_SEQ, + ACERT_IDX_ACINFO_CHOICE_SEQ, + ACERT_IDX_ACINFO_ISSUER_SEQ, + /* ACINFO sig alg*/ + ACERT_IDX_ACINFO_ALGOID_SEQ, + ACERT_IDX_ACINFO_ALGOID_OID, + ACERT_IDX_ACINFO_ALGOID_PARAMS_NULL, +#ifdef WC_RSA_PSS + /* Additional RSA-PSS params. */ + ACERT_IDX_ACINFO_ALGOID_PARAMS, +#endif + /* serial number */ + ACERT_IDX_ACINFO_SERIAL, + /* validity time */ + ACERT_IDX_ACINFO_VALIDITY_SEQ, + ACERT_IDX_ACINFO_VALIDITY_NOTB_GT, + ACERT_IDX_ACINFO_VALIDITY_NOTA_GT, + /* attributes */ + ACERT_IDX_ACINFO_ATTRIBUTES_SEQ, + /* unique identifier */ + ACERT_IDX_ACINFO_UNIQUE_ID, + /* extensions */ + ACERT_ACINFO_EXT, + ACERT_ACINFO_EXT_SEQ, + /* sig alg */ + ACERT_IDX_SIGALGO_SEQ, + ACERT_IDX_SIGALGO_OID, + ACERT_IDX_SIGALGO_PARAMS_NULL, +#ifdef WC_RSA_PSS + /* Additional RSA-PSS params. */ + ACERT_IDX_SIGALGO_PARAMS, +#endif + /* signature */ + ACERT_IDX_SIGNATURE, + WOLF_ENUM_DUMMY_LAST_ELEMENT(ACERT_IDX) +}; + +/* Number of items in ASN template for an X509 Acert. */ +#define AcertASN_Length (sizeof(AcertASN) / sizeof(ASNItem)) + +/* Initial implementation for parsing and verifying an + * X509 Attribute Certificate (RFC 5755). + * + * At present these fields are NOT parsed: + * - issuerUniqueID + * - extensions + * - attributes + * + * Returns 0 on success. + * Returns negative error code on error/failure. + * */ +int ParseX509Acert(DecodedAcert* acert, int verify) +{ + DECL_ASNGETDATA(dataASN, AcertASN_Length); + int ret = 0; + word32 idx = 0; + int badDate = 0; + byte version = 0; + word32 serialSz = EXTERNAL_SERIAL_SIZE; + + if (acert == NULL) { + return BAD_FUNC_ARG; + } + + CALLOC_ASNGETDATA(dataASN, AcertASN_Length, ret, acert->heap); + + if (ret != 0) { + return MEMORY_E; + } + + /* Get the version and put the serial number into the buffer. */ + GetASN_Int8Bit(&dataASN[ACERT_IDX_ACINFO_VER_INT], &version); + + GetASN_Buffer(&dataASN[ACERT_IDX_ACINFO_SERIAL], acert->serial, + &serialSz); + + /* Check OID types for signature algorithm. */ + GetASN_OID(&dataASN[ACERT_IDX_ACINFO_ALGOID_OID], oidSigType); + GetASN_OID(&dataASN[ACERT_IDX_SIGALGO_OID], oidSigType); + + /* Parse the X509 certificate. */ + ret = GetASN_Items(AcertASN, dataASN, AcertASN_Length, 1, + acert->source, &acert->srcIdx, acert->maxIdx); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; + } + + /* Check version is valid/supported - can't be negative. */ + if (version > MAX_X509_VERSION) { + FREE_ASNGETDATA(dataASN, acert->heap); + WOLFSSL_MSG("Unexpected attribute certificate version"); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + + acert->version = version; + acert->serialSz = (int)serialSz; + + acert->signatureOID = dataASN[ACERT_IDX_ACINFO_ALGOID_OID].data.oid.sum; + acert->certBegin = dataASN[ACERT_IDX_ACINFO_SEQ].offset; + + /* check BEFORE date. */ + idx = ACERT_IDX_ACINFO_VALIDITY_NOTB_GT; + if (CheckDate(&dataASN[idx], BEFORE) < 0) { + if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { + badDate = ASN_BEFORE_DATE_E; + } + } + + /* Store reference to BEFORE date. */ + acert->beforeDate = GetASNItem_Addr(dataASN[idx], acert->source); + acert->beforeDateLen = (int)GetASNItem_Length(dataASN[idx], acert->source); + + /* check AFTER date. */ + idx = ACERT_IDX_ACINFO_VALIDITY_NOTA_GT; + if (CheckDate(&dataASN[idx], AFTER) < 0) { + if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { + badDate = ASN_BEFORE_DATE_E; + } + } + + /* Store reference to AFTER date. */ + acert->afterDate = GetASNItem_Addr(dataASN[idx], acert->source); + acert->afterDateLen = (int)GetASNItem_Length(dataASN[idx], acert->source); + + /* Store the signature information. */ + acert->sigIndex = dataASN[ACERT_IDX_SIGALGO_SEQ].offset; + GetASN_GetConstRef(&dataASN[ACERT_IDX_SIGNATURE], + &acert->signature, &acert->sigLength); + + /* Make sure 'signature' and 'signatureAlgorithm' are the same. */ + if (dataASN[ACERT_IDX_SIGALGO_OID].data.oid.sum != acert->signatureOID) { + FREE_ASNGETDATA(dataASN, acert->heap); + WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E); + return ASN_SIG_OID_E; + } + + /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */ + if (IsSigAlgoECC(acert->signatureOID)) { + if ((dataASN[ACERT_IDX_SIGALGO_PARAMS_NULL].tag != 0) + #ifdef WC_RSA_PSS + || (dataASN[ACERT_IDX_SIGALGO_PARAMS].tag != 0) + #endif + ) { + FREE_ASNGETDATA(dataASN, acert->heap); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + } + + #ifdef WC_RSA_PSS + /* Check parameters starting with a SEQUENCE. */ + if (dataASN[ACERT_IDX_SIGALGO_PARAMS].tag != 0) { + word32 oid = dataASN[ACERT_IDX_SIGALGO_OID].data.oid.sum; + word32 sigAlgParamsSz = 0; + const byte * acParams = NULL; + word32 acParamsSz = 0; + const byte * sigAlgParams = NULL; + + /* Parameters only with RSA PSS. */ + if (oid != CTC_RSASSAPSS) { + FREE_ASNGETDATA(dataASN, acert->heap); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + + /* Check RSA PSS parameters are the same. */ + acParams = GetASNItem_Addr(dataASN[ACERT_IDX_ACINFO_ALGOID_PARAMS], + acert->source); + acParamsSz = GetASNItem_Length(dataASN[ACERT_IDX_ACINFO_ALGOID_PARAMS], + acert->source); + sigAlgParams = GetASNItem_Addr(dataASN[ACERT_IDX_SIGALGO_PARAMS], + acert->source); + sigAlgParamsSz = GetASNItem_Length(dataASN[ACERT_IDX_SIGALGO_PARAMS], + acert->source); + + if ((acParamsSz != sigAlgParamsSz) || + (XMEMCMP(acParams, sigAlgParams, acParamsSz) != 0)) { + + FREE_ASNGETDATA(dataASN, acert->heap); + WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + return ASN_PARSE_E; + } + + /* Store RSA PSS parameters for use in signature verification. */ + acert->sigParamsIndex = dataASN[ACERT_IDX_SIGALGO_PARAMS].offset; + acert->sigParamsLength = sigAlgParamsSz; + } + #endif + + /* Store the raw Attributes field. */ + GetASN_GetConstRef(&dataASN[ACERT_IDX_ACINFO_ATTRIBUTES_SEQ], + &acert->rawAttr, &acert->rawAttrLen); + + { + /* Now parse the Holder and AttCertIssuer fields. + * Use the ACINFO holder and issuer sequence offset for input. */ + const byte * holder_input = NULL; + word32 holder_len = 0; + const byte * issuer_input = NULL; + word32 issuer_len = 0; + word32 i_holder = ACERT_IDX_ACINFO_HOLDER_SEQ; + word32 i_issuer = 0; + + /* Determine which issuer tag was seen. We need this to determine + * the holder_input. */ + i_issuer = (dataASN[ACERT_IDX_ACINFO_CHOICE_SEQ].tag != 0) ? + ACERT_IDX_ACINFO_CHOICE_SEQ : ACERT_IDX_ACINFO_ISSUER_SEQ; + + holder_input = acert->source + dataASN[i_holder].offset; + holder_len = dataASN[i_issuer].offset - dataASN[i_holder].offset; + + ret = DecodeHolder(holder_input, holder_len, acert); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; + } + + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + printf("debug: parse acert:issuer index: %d\n", i_issuer); + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ + + GetASN_GetConstRef(&dataASN[i_issuer], &issuer_input, &issuer_len); + + if (i_issuer == ACERT_IDX_ACINFO_CHOICE_SEQ && issuer_len > 0) { + /* Try to decode the AttCertIssuer as well. */ + ret = DecodeAttCertIssuer(issuer_input, issuer_len, acert); + + if (ret != 0) { + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; + } + } + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + else { + printf("debug: parse acert: unsupported issuer format: %d, %d\n", + i_issuer, issuer_len); + } + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ + } + + if (badDate) { + if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { + ret = badDate; + } + } + + FREE_ASNGETDATA(dataASN, acert->heap); + return ret; +} + +/* Given the parsed attribute cert info, verify the signature. + * + * The sigCtx is alloced and freed here. + * + * @param [in] acinfo the parsed acinfo sequence + * @param [in] acinfoSz the parsed acinfo sequence length + * @param [in] pubKey public key + * @param [in] pubKeySz public key length + * @param [in] pubKeyOID public key oid + * @param [in] sig the parsed signature + * @param [in] sigSz the parsed signature length + * @param [in] sigOID the parsed signature OID + * @param [in] sigParams the parsed signature RSA-PSS params + * @param [in] sigParamsSz the parsed signature RSA-PSS params length + * @param [in] heap heap hint + * + * @return 0 on verify success + * @return < 0 on error + * */ +static int acert_sig_verify(const byte * acinfo, word32 acinfoSz, + const byte * pubKey, word32 pubKeySz, + int pubKeyOID, const byte * sig, word32 sigSz, + word32 sigOID, const byte * sigParams, + word32 sigParamsSz, void * heap) +{ +#ifndef WOLFSSL_SMALL_STACK + SignatureCtx sigCtx[1]; +#else + SignatureCtx * sigCtx = NULL; +#endif + int ret = 0; + + #ifdef WOLFSSL_SMALL_STACK + sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, + DYNAMIC_TYPE_SIGNATURE); + if (sigCtx == NULL) { + WOLFSSL_MSG("error: VerifyX509Acert: malloc sigCtx failed"); + return MEMORY_E; + } + #endif + + InitSignatureCtx(sigCtx, heap, INVALID_DEVID); + + /* Check x509 acert signature. */ + ret = ConfirmSignature(sigCtx, acinfo, acinfoSz, pubKey, pubKeySz, + (word32)pubKeyOID, sig, sigSz, sigOID, + sigParams, sigParamsSz, NULL); + + if (ret == WC_NO_ERR_TRACE(ASN_SIG_CONFIRM_E)) { + WOLFSSL_MSG("info: VerifyX509Acert: confirm signature failed"); + } + + FreeSignatureCtx(sigCtx); + #ifdef WOLFSSL_SMALL_STACK + XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); + sigCtx = NULL; + #endif + + return ret; +} + +/* Verify the X509 ACERT signature, using the given pubkey. + * + * @param [in] der input acert in der format + * @param [in] derSz acert length + * @param [in] pubKey public key + * @param [in] pubKeySz public key length + * @param [in] pubKeyOID public key oid + * @param [in] heap heap hint + * + * @return 0 on success + * @return < 0 on error + * */ +int VerifyX509Acert(const byte* der, word32 derSz, + const byte* pubKey, word32 pubKeySz, int pubKeyOID, + void * heap) +{ + DECL_ASNGETDATA(dataASN, AcertASN_Length); + word32 idx = 0; + int ret = 0; + const byte * acinfo = NULL; /* The acinfo sequence. */ + word32 acinfoSz = 0; /* The acinfo sequence length. */ +#ifdef WC_RSA_PSS + const byte * acParams = NULL; + word32 acParamsSz = 0; +#endif + const byte * sig = NULL; + word32 sigSz = 0; + word32 sigOID = 0; + const byte * sigParams = NULL; + word32 sigParamsSz = 0; + + if (der == NULL || pubKey == NULL || derSz == 0 || pubKeySz == 0) { + WOLFSSL_MSG("error: VerifyX509Acert: bad args"); + return BAD_FUNC_ARG; + } + + CALLOC_ASNGETDATA(dataASN, AcertASN_Length, ret, heap); + + if (ret != 0) { + WOLFSSL_MSG("error: VerifyX509Acert: calloc dataASN failed"); + return MEMORY_E; + } + + /* Check OID types for signature algorithm. */ + GetASN_OID(&dataASN[ACERT_IDX_ACINFO_ALGOID_OID], oidSigType); + GetASN_OID(&dataASN[ACERT_IDX_SIGALGO_OID], oidSigType); + + /* Parse the X509 certificate. */ + ret = GetASN_Items(AcertASN, dataASN, AcertASN_Length, 1, + der, &idx, derSz); + + if (ret != 0) { + WOLFSSL_MSG("error: VerifyX509Acert: GetASN_Items failed"); + FREE_ASNGETDATA(dataASN, heap); + return ret; + } + + /* Check signature OIDs match. */ + if (dataASN[ACERT_IDX_ACINFO_ALGOID_OID].data.oid.sum + != dataASN[ACERT_IDX_SIGALGO_OID].data.oid.sum) { + WOLFSSL_MSG("error: VerifyX509Acert: sig OID mismatch"); + FREE_ASNGETDATA(dataASN, heap); + return ASN_SIG_OID_E; + } + + /* Get the attribute certificate info. */ + acinfo = GetASNItem_Addr(dataASN[ACERT_IDX_ACINFO_SEQ], der); + acinfoSz = GetASNItem_Length(dataASN[ACERT_IDX_ACINFO_SEQ], der); + + if (acinfo == NULL || acinfoSz == 0) { + WOLFSSL_MSG("error: VerifyX509Acert: empty acinfo"); + FREE_ASNGETDATA(dataASN, heap); + return ASN_PARSE_E; + } + + /* Get acert signature and sig info. */ + sigOID = dataASN[ACERT_IDX_ACINFO_ALGOID_OID].data.oid.sum; + #ifdef WC_RSA_PSS + if (dataASN[ACERT_IDX_ACINFO_ALGOID_PARAMS].tag != 0) { + acParams = GetASNItem_Addr(dataASN[ACERT_IDX_ACINFO_ALGOID_PARAMS], + der); + acParamsSz = GetASNItem_Length(dataASN[ACERT_IDX_ACINFO_ALGOID_PARAMS], + der); + } + if (dataASN[ACERT_IDX_SIGALGO_PARAMS].tag != 0) { + sigParams = GetASNItem_Addr(dataASN[ACERT_IDX_SIGALGO_PARAMS], der); + sigParamsSz = GetASNItem_Length(dataASN[ACERT_IDX_SIGALGO_PARAMS], + der); + } + #endif + + GetASN_GetConstRef(&dataASN[ACERT_IDX_SIGNATURE], &sig, &sigSz); + + #ifdef WC_RSA_PSS + if (acParamsSz != sigParamsSz) { + ret = ASN_PARSE_E; + } + else if ((acParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) { + ret = ASN_PARSE_E; + } + else if ((acParamsSz > 0) && + (XMEMCMP(acParams, sigParams, acParamsSz) != 0)) { + ret = ASN_PARSE_E; + } + #endif + + if (ret == 0) { + /* Finally, do the verification. */ + ret = acert_sig_verify(acinfo, acinfoSz, + pubKey, pubKeySz, pubKeyOID, + sig, sigSz, sigOID, sigParams, sigParamsSz, + heap); + } + + FREE_ASNGETDATA(dataASN, heap); + return ret; +} + +void wc_InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, + void* heap) +{ + InitDecodedAcert(acert, source, inSz, heap); +} + +void wc_FreeDecodedAcert(DecodedAcert * acert) +{ + FreeDecodedAcert(acert); +} + +int wc_ParseX509Acert(DecodedAcert* acert, int verify) +{ + return ParseX509Acert(acert, verify); +} + +int wc_VerifyX509Acert(const byte* acert, word32 acertSz, + const byte* pubKey, word32 pubKeySz, + int pubKeyOID, void * heap) +{ + return VerifyX509Acert(acert, acertSz, pubKey, pubKeySz, + pubKeyOID, heap); +} + +#endif /* WOLFSSL_ACERT && WOLFSSL_ASN_TEMPLATE */ #ifdef WOLFSSL_SEP diff --git a/src/wolfcrypt/src/bio.c b/src/wolfcrypt/src/bio.c index 340cbfd..ac4eb03 100644 --- a/src/wolfcrypt/src/bio.c +++ b/src/wolfcrypt/src/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,10 +24,9 @@ #endif #include -#if defined(OPENSSL_EXTRA) && !defined(_WIN32) +#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ - #undef _GNU_SOURCE - #define _GNU_SOURCE + #define _GNU_SOURCE 1 #endif #if !defined(WOLFSSL_BIO_INCLUDED) @@ -161,7 +160,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->wrSz = 0; bio->mem_buf->length = 0; } - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { @@ -180,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } bio->mem_buf->length = (size_t)bio->wrSz; - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } } else { @@ -217,11 +216,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return WOLFSSL_FATAL_ERROR; bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_read((WOLFSSL*)bio->ptr, buf, len); + ret = wolfSSL_read(bio->ptr.ssl, buf, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -235,15 +234,15 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -290,6 +289,9 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom read */ if (bio->method && bio->method->readCb) { ret = bio->method->readCb(bio, (char*)buf, len); @@ -302,19 +304,22 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) break; case WOLFSSL_BIO_BIO: /* read BIOs */ ret = wolfSSL_BIO_BIO_read(bio, buf, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_read(bio, buf, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFREAD(buf, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, (size_t)len); + ret = (int)XREAD(bio->num.fd, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -345,14 +350,52 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Recv(bio->num, (char*)buf, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + else { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + ret = wolfIO_RecvFrom(bio->num.fd, &bio->peer_addr, + (char*)buf, len, 0); + } + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (!inhibit_flow_increment)) { + bio->bytes_read += (word32)ret; + } +#endif + /* case where front of list is done */ if (bio == front) { break; /* at front of list so be done */ @@ -409,8 +452,9 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } } else { - if (Base64_Encode((const byte*)data, inLen, NULL, &sz) != - LENGTH_ONLY_E) { + if (Base64_Encode((const byte*)data, inLen, NULL, &sz) + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -468,16 +512,16 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_ENTER("wolfSSL_BIO_SSL_write"); - if (bio->ptr == NULL) { + if (bio->ptr.ssl == NULL) { return BAD_FUNC_ARG; } bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_write((WOLFSSL*)bio->ptr, data, len); + ret = wolfSSL_write(bio->ptr.ssl, data, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -576,8 +620,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, } XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); - bio->ptr = bio->mem_buf->data; - bio->num = (int)bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; bio->wrSz += len; bio->wrIdx += len; @@ -598,14 +642,14 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -647,6 +691,9 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom write */ if (bio->method && bio->method->writeCb) { ret = bio->method->writeCb(bio, (const char*)data, len); @@ -672,19 +719,22 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } case WOLFSSL_BIO_BIO: /* write bios */ ret = wolfSSL_BIO_BIO_write(bio, data, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_write(bio, data, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFWRITE(data, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, (size_t)len); + ret = (int)XWRITE(bio->num.fd, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -725,14 +775,50 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Send(bio->num, (char*)data, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + else if (bio->peer_addr.sa.sa_family == AF_UNSPEC) + ret = SOCKET_ERROR_E; + else + ret = wolfIO_SendTo(bio->num.fd, &bio->peer_addr, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (! inhibit_flow_increment)) + bio->bytes_written += (word32)ret; +#endif + /* advance to the next bio in list */ bio = bio->next; } @@ -748,7 +834,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) (const char*)data, len, 0, ret); } - if (frmt != NULL) { + if (front != NULL) { XFREE(frmt, front->heap, DYNAMIC_TYPE_TMP_BUFFER); } @@ -793,6 +879,49 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) case BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; + +#ifdef WOLFSSL_HAVE_BIO_ADDR + case BIO_CTRL_DGRAM_CONNECT: + case BIO_CTRL_DGRAM_SET_PEER: + { + socklen_t addr_size; + if (parg == NULL) { + ret = WOLFSSL_FAILURE; + break; + } + addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + ret = WOLFSSL_SUCCESS; + break; + } + + case BIO_CTRL_DGRAM_SET_CONNECTED: + if (parg == NULL) { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + bio->connected = 0; + } + else { + socklen_t addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + bio->connected = 1; + } + ret = WOLFSSL_SUCCESS; + break; + + case BIO_CTRL_DGRAM_QUERY_MTU: + ret = 0; /* not implemented */ + break; + +#endif /* WOLFSSL_HAVE_BIO_ADDR */ + default: WOLFSSL_MSG("CMD not yet implemented"); ret = WOLFSSL_FAILURE; @@ -826,8 +955,51 @@ int wolfSSL_BIO_up_ref(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } + +#ifdef WOLFSSL_HAVE_BIO_ADDR +WOLFSSL_BIO_ADDR *wolfSSL_BIO_ADDR_new(void) { + WOLFSSL_BIO_ADDR *addr = + (WOLFSSL_BIO_ADDR *)XMALLOC(sizeof(*addr), NULL, DYNAMIC_TYPE_BIO); + if (addr) + addr->sa.sa_family = AF_UNSPEC; + return addr; +} + +void wolfSSL_BIO_ADDR_free(WOLFSSL_BIO_ADDR *addr) { + XFREE(addr, NULL, DYNAMIC_TYPE_BIO); +} + +void wolfSSL_BIO_ADDR_clear(WOLFSSL_BIO_ADDR *addr) { + if (addr == NULL) + return; + XMEMSET(addr, 0, sizeof(*addr)); + addr->sa.sa_family = AF_UNSPEC; +} + +socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr) { + switch (addr->sa.sa_family) { +#ifndef WOLFSSL_NO_BIO_ADDR_IN + case AF_INET: + return sizeof(addr->sa_in); +#endif +#ifdef WOLFSSL_IPV6 + case AF_INET6: + return sizeof(addr->sa_in6); #endif +#if defined(HAVE_SYS_UN_H) && !defined(WOLFSSL_NO_SOCKADDR_UN) + case AF_UNIX: + return sizeof(addr->sa_un); +#endif + default: + /* must return zero if length can't be determined, to avoid buffer + * overruns in callers. + */ + return 0; + } +} +#endif /* WOLFSSL_HAVE_BIO_ADDR */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ /* helper function for wolfSSL_BIO_gets * size till a newline is hit @@ -888,15 +1060,15 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (((XFILE)bio->ptr) == XBADFILE) { + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_BIO_ERROR; } #if defined(MICRIUM) || defined(LSR_FS) || defined(EBSNET) WOLFSSL_MSG("XFGETS not ported for this system yet"); - ret = XFGETS(buf, sz, (XFILE)bio->ptr); + ret = XFGETS(buf, sz, bio->ptr.fh); #else - if (XFGETS(buf, sz, (XFILE)bio->ptr) != NULL) { + if (XFGETS(buf, sz, bio->ptr.fh) != NULL) { ret = (int)XSTRLEN(buf); } else { @@ -972,13 +1144,13 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) #ifndef WOLFCRYPT_ONLY /* call final on hash */ case WOLFSSL_BIO_MD: - if (wolfSSL_EVP_MD_CTX_size((WOLFSSL_EVP_MD_CTX*)bio->ptr) > sz) { + if (wolfSSL_EVP_MD_CTX_size(bio->ptr.md_ctx) > sz) { WOLFSSL_MSG("Output buffer was too small for digest"); ret = WOLFSSL_FAILURE; } else { unsigned int szOut = 0; - ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, + ret = wolfSSL_EVP_DigestFinal(bio->ptr.md_ctx, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { ret = (int)szOut; @@ -1133,8 +1305,8 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) } #ifndef WOLFCRYPT_ONLY - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr != NULL) { - return (long)wolfSSL_pending((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { + return (long)wolfSSL_pending(bio->ptr.ssl); } #endif @@ -1162,7 +1334,7 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) { WOLFSSL_BIO* front = bio; - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_get_mem_ptr"); @@ -1188,7 +1360,10 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio = bio->prev; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } #ifdef OPENSSL_ALL @@ -1208,8 +1383,8 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; - bio->num = (int)bio->mem_buf->max; - bio->ptr = bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->wrIdx = 0; bio->rdIdx = 0; @@ -1242,15 +1417,16 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } - if (bio->ptr != NULL) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data != NULL) { + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr = (byte*)XMALLOC(size, bio->heap, DYNAMIC_TYPE_OPENSSL); - if (bio->ptr == NULL) { + bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); bio->wrSz = 0; - bio->num = 0; + bio->num.length = 0; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1261,13 +1437,13 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num = (int)size; + bio->num.length = size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { - bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = (size_t)bio->num; - bio->mem_buf->max = (size_t)bio->num; + bio->mem_buf->data = (char*)bio->ptr.mem_buf_data; + bio->mem_buf->length = bio->num.length; + bio->mem_buf->max = bio->num.length; } return WOLFSSL_SUCCESS; @@ -1295,12 +1471,12 @@ int wolfSSL_BIO_make_bio_pair(WOLFSSL_BIO *b1, WOLFSSL_BIO *b2) } /* set default write size if not already set */ - if (b1->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b1, + if (b1->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b1, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - if (b2->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b2, + if (b2->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b2, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -1341,7 +1517,7 @@ int wolfSSL_BIO_nread0(WOLFSSL_BIO *bio, char **buf) WOLFSSL_BIO* pair = bio->pair; /* case where have wrapped around write buffer */ - *buf = (char*)pair->ptr + pair->rdIdx; + *buf = (char*)pair->ptr.mem_buf_data + pair->rdIdx; if (pair->wrIdx > 0 && pair->rdIdx >= pair->wrIdx) { return pair->wrSz - pair->rdIdx; } @@ -1373,7 +1549,7 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { /* special case if asking to read 0 bytes */ if (num == 0) { - *buf = (char*)bio->pair->ptr + bio->pair->rdIdx; + *buf = (char*)bio->pair->ptr.mem_buf_data + bio->pair->rdIdx; return 0; } @@ -1387,6 +1563,9 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) sz = num; } bio->pair->rdIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->pair->bytes_read += (word32)sz; +#endif /* check if have read to the end of the buffer and need to reset */ if (bio->pair->rdIdx == bio->pair->wrSz) { @@ -1424,7 +1603,7 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { if (num == 0) { - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; return 0; } @@ -1463,8 +1642,11 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (num < sz) { sz = num; } - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; bio->wrIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->bytes_written += (word32)sz; +#endif /* if at the end of the buffer and space for wrap around then set * write index back to 0 */ @@ -1476,6 +1658,37 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) return sz; } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS +word64 wolfSSL_BIO_number_read(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_read; + bio = bio->next; + } + + return ret; +} + +word64 wolfSSL_BIO_number_written(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_written; + bio = bio->next; + } + + return ret; +} +#endif /* WOLFSSL_BIO_HAVE_FLOW_STATS */ /* Reset BIO to initial state */ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) @@ -1491,16 +1704,16 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (XFSEEK((XFILE)bio->ptr, 0, XSEEK_SET) != 0) + if (XFSEEK(bio->ptr.fh, 0, XSEEK_SET) != 0) return WOLFSSL_BIO_ERROR; else - return 0; + return WOLFSSL_SUCCESS; #endif case WOLFSSL_BIO_BIO: bio->rdIdx = 0; bio->wrIdx = 0; - return 0; + return WOLFSSL_SUCCESS; case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; @@ -1510,27 +1723,27 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) } else { bio->wrSz = 0; - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; - bio->num = 0; + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; + bio->num.length = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = NULL; bio->mem_buf->length = 0; bio->mem_buf->max = 0; } } - return 0; + return WOLFSSL_SUCCESS; #ifndef WOLFCRYPT_ONLY case WOLFSSL_BIO_MD: - if (bio->ptr != NULL) { + if (bio->ptr.md_ctx != NULL) { const WOLFSSL_EVP_MD* md = - wolfSSL_EVP_MD_CTX_md((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_cleanup((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_init((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_DigestInit((WOLFSSL_EVP_MD_CTX*)bio->ptr, md); + wolfSSL_EVP_MD_CTX_md(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_cleanup(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_init(bio->ptr.md_ctx); + wolfSSL_EVP_DigestInit(bio->ptr.md_ctx, md); } - return 0; + return WOLFSSL_SUCCESS; #endif /* WOLFCRYPT_ONLY */ default: @@ -1580,7 +1793,7 @@ long wolfSSL_BIO_set_fp(WOLFSSL_BIO *bio, XFILE fp, int c) } bio->shutdown = (byte)c; - bio->ptr = (XFILE)fp; + bio->ptr.fh = fp; return WOLFSSL_SUCCESS; } @@ -1598,7 +1811,7 @@ long wolfSSL_BIO_get_fp(WOLFSSL_BIO *bio, XFILE* fp) return WOLFSSL_FAILURE; } - *fp = (XFILE)bio->ptr; + *fp = bio->ptr.fh; return WOLFSSL_SUCCESS; } @@ -1613,8 +1826,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (((XFILE)bio->ptr) != XBADFILE && bio->shutdown == BIO_CLOSE) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + XFCLOSE(bio->ptr.fh); } /* 'b' flag is ignored on POSIX targets, but on Windows it assures @@ -1622,8 +1835,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) * between the size and contents of the representation in memory and on * disk. */ - bio->ptr = XFOPEN(name, "wb"); - if (((XFILE)bio->ptr) == XBADFILE) { + bio->ptr.fh = XFOPEN(name, "wb"); + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } bio->shutdown = BIO_CLOSE; @@ -1640,13 +1853,13 @@ int wolfSSL_BIO_seek(WOLFSSL_BIO *bio, int ofs) WOLFSSL_ENTER("wolfSSL_BIO_seek"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } /* offset ofs from beginning of file */ if (bio->type == WOLFSSL_BIO_FILE && - XFSEEK((XFILE)bio->ptr, ofs, SEEK_SET) < 0) { - return -1; + XFSEEK(bio->ptr.fh, ofs, SEEK_SET) < 0) { + return WOLFSSL_FATAL_ERROR; } return 0; @@ -1663,16 +1876,16 @@ int wolfSSL_BIO_tell(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_tell"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (bio->type != WOLFSSL_BIO_FILE) { return 0; } - pos = (int)XFTELL((XFILE)bio->ptr); + pos = (int)XFTELL(bio->ptr.fh); if (pos < 0) - return -1; + return WOLFSSL_FATAL_ERROR; else return pos; } @@ -1799,15 +2012,16 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) if (bio) { switch (bio->type) { case WOLFSSL_BIO_SOCKET: + case WOLFSSL_BIO_DGRAM: #ifdef XFCNTL { int ret; - int flag = XFCNTL(bio->num, F_GETFL, 0); + int flag = XFCNTL(bio->num.fd, F_GETFL, 0); if (on) { - ret = XFCNTL(bio->num, F_SETFL, flag | O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag | O_NONBLOCK); } else { - ret = XFCNTL(bio->num, F_SETFL, flag & ~O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag & ~O_NONBLOCK); } if (ret == -1) { @@ -1818,7 +2032,7 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) break; case WOLFSSL_BIO_SSL: #ifdef WOLFSSL_DTLS - wolfSSL_dtls_set_using_nonblock((WOLFSSL*)bio->ptr, (int)on); + wolfSSL_dtls_set_using_nonblock(bio->ptr.ssl, (int)on); #endif break; @@ -1966,7 +2180,7 @@ int wolfSSL_BIO_get_mem_data(WOLFSSL_BIO* bio, void* p) } if (p) { - *(byte**)p = (byte*)mem_bio->ptr + mem_bio->rdIdx; + *(byte**)p = mem_bio->ptr.mem_buf_data + mem_bio->rdIdx; } return mem_bio->wrSz - mem_bio->rdIdx; @@ -1991,7 +2205,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) - if (XFFLUSH((FILE *)bio->ptr) != 0) + if (XFFLUSH(bio->ptr.fh) != 0) return WOLFSSL_FAILURE; #endif /* !NO_FILESYSTEM && XFFLUSH */ @@ -2015,14 +2229,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) /* return the context and initialize the BIO state */ int wolfSSL_BIO_get_md_ctx(WOLFSSL_BIO *bio, WOLFSSL_EVP_MD_CTX **mdcp) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if ((bio != NULL) && (mdcp != NULL)) { - *mdcp = (WOLFSSL_EVP_MD_CTX*)bio->ptr; + *mdcp = bio->ptr.md_ctx; ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } WOLFSSL_BIO_METHOD* wolfSSL_BIO_f_buffer(void) @@ -2110,11 +2327,39 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio) { bio->type = WOLFSSL_BIO_SOCKET; bio->shutdown = (byte)closeF; - bio->num = sfd; + bio->num.fd = (SOCKET_T)sfd; } return bio; } + +#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_datagram(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_DGRAM); + + WOLFSSL_ENTER("wolfSSL_BIO_s_datagram"); + + return &meth; + } + + + WOLFSSL_BIO* wolfSSL_BIO_new_dgram(int fd, int closeF) + { + WOLFSSL_BIO* bio = wolfSSL_BIO_new(wolfSSL_BIO_s_datagram()); + + WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); + if (bio) { + bio->type = WOLFSSL_BIO_DGRAM; + bio->shutdown = (byte)closeF; + bio->num.fd = (SOCKET_T)fd; + } + return bio; + } +#endif + + /** * Create new socket BIO object. This is a pure TCP connection with * no SSL or TLS protection. @@ -2231,7 +2476,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2255,17 +2500,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - if (b->num == WOLFSSL_BIO_ERROR) { + if (b->num.fd == SOCKET_INVALID) { if (wolfIO_TcpBind(&sfd, b->port) < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; - int newfd = wolfIO_TcpAccept(b->num, NULL, NULL); + int newfd = wolfIO_TcpAccept(b->num.fd, NULL, NULL); if (newfd < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; @@ -2322,8 +2567,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } - if (b->type == WOLFSSL_BIO_SSL && b->ptr != NULL) { - return wolfSSL_negotiate((WOLFSSL*)b->ptr); + if (b->type == WOLFSSL_BIO_SSL && b->ptr.ssl != NULL) { + return wolfSSL_negotiate(b->ptr.ssl); } else { WOLFSSL_MSG("Not SSL BIO or no SSL object set"); @@ -2348,12 +2593,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return; } - if (b->ptr != NULL) { - int rc = wolfSSL_shutdown((WOLFSSL*)b->ptr); + if (b->ptr.ssl != NULL) { + int rc = wolfSSL_shutdown(b->ptr.ssl); if (rc == SSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ - wolfSSL_shutdown((WOLFSSL*)b->ptr); + wolfSSL_shutdown(b->ptr.ssl); } } else { @@ -2363,12 +2608,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_set_ssl"); if (b != NULL) { - b->ptr = ssl; + b->ptr.ssl = ssl; b->shutdown = (byte)closeF; if (b->next != NULL) wolfSSL_set_bio(ssl, b->next, b->next); @@ -2376,7 +2621,10 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } long wolfSSL_BIO_get_ssl(WOLFSSL_BIO* bio, WOLFSSL** ssl) @@ -2396,7 +2644,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - *ssl = (WOLFSSL*)bio->ptr; + *ssl = bio->ptr.ssl; return WOLFSSL_SUCCESS; } @@ -2540,7 +2788,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_set_fd"); if (b != NULL) { - b->num = fd; + b->num.fd = (SOCKET_T)fd; b->shutdown = (byte)closeF; } @@ -2584,7 +2832,14 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->method = method; #endif bio->shutdown = BIO_CLOSE; /* default to close things */ - bio->num = WOLFSSL_BIO_ERROR; + + if ((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) + { + bio->num.fd = SOCKET_INVALID; + } else { + bio->num.length = 0; + } bio->init = 1; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) @@ -2616,8 +2871,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (method->type == WOLFSSL_BIO_MD) { - bio->ptr = wolfSSL_EVP_MD_CTX_new(); - if (bio->ptr == NULL) { + bio->ptr.md_ctx = wolfSSL_EVP_MD_CTX_new(); + if (bio->ptr.md_ctx == NULL) { WOLFSSL_MSG("Memory error"); wolfSSL_BIO_free(bio); return NULL; @@ -2656,11 +2911,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return NULL; } - bio->num = (int)bio->mem_buf->max; + bio->num.length = bio->mem_buf->max; bio->wrSz = len; - bio->ptr = bio->mem_buf->data; - if (len > 0 && bio->ptr != NULL) { - XMEMCPY(bio->ptr, buf, len); + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + if (len > 0 && bio->ptr.mem_buf_data != NULL) { + XMEMCPY(bio->ptr.mem_buf_data, buf, len); bio->flags |= BIO_FLAGS_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2723,44 +2978,51 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->pair->pair = NULL; } - if (bio->ip != NULL) { - XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); - } + XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->shutdown) { - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr) - wolfSSL_free((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl) + wolfSSL_free(bio->ptr.ssl); #ifdef CloseSocket - if ((bio->type == WOLFSSL_BIO_SOCKET) && (bio->num > 0)) - CloseSocket(bio->num); + if (((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) && + (bio->num.fd != SOCKET_INVALID)) + { + CloseSocket(bio->num.fd); + } #endif } #ifndef NO_FILESYSTEM if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { - if (bio->ptr) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh) { + XFCLOSE(bio->ptr.fh); } #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR)\ && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - else if (bio->num != WOLFSSL_BIO_ERROR) { - XCLOSE(bio->num); + else if (bio->num.fd != SOCKET_INVALID) { + XCLOSE(bio->num.fd); } #endif } #endif if (bio->shutdown != BIO_NOCLOSE) { - if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr != NULL) { + if (bio->type == WOLFSSL_BIO_MEMORY && + bio->ptr.mem_buf_data != NULL) + { if (bio->mem_buf != NULL) { - if (bio->mem_buf->data != (char*)bio->ptr) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + if ((byte *)bio->mem_buf->data != bio->ptr.mem_buf_data) + { + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } else { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } if (bio->mem_buf != NULL) { @@ -2770,7 +3032,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (bio->type == WOLFSSL_BIO_MD) { - wolfSSL_EVP_MD_CTX_free((WOLFSSL_EVP_MD_CTX*)bio->ptr); + wolfSSL_EVP_MD_CTX_free(bio->ptr.md_ctx); } XFREE(bio, 0, DYNAMIC_TYPE_OPENSSL); @@ -2809,8 +3071,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } /* SSL BIO's should use the next object in the chain for IO */ - if (top->type == WOLFSSL_BIO_SSL && top->ptr) - wolfSSL_set_bio((WOLFSSL*)top->ptr, append, append); + if (top->type == WOLFSSL_BIO_SSL && top->ptr.ssl) + wolfSSL_set_bio(top->ptr.ssl, append, append); return top; } @@ -2914,9 +3176,11 @@ int wolfSSL_BIO_get_fd(WOLFSSL_BIO *bio, int* fd) WOLFSSL_ENTER("wolfSSL_BIO_get_fd"); if (bio != NULL) { + if (bio->num.fd == SOCKET_INVALID) + return WOLFSSL_BIO_ERROR; if (fd != NULL) - *fd = bio->num; - return bio->num; + *fd = (int)bio->num.fd; + return (int)bio->num.fd; } return WOLFSSL_BIO_ERROR; @@ -2991,10 +3255,10 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) switch (bio->type) { #if !defined(NO_FILESYSTEM) case WOLFSSL_BIO_FILE: - if (bio->ptr == NULL) { - return -1; + if (bio->ptr.fh == XBADFILE) { + return WOLFSSL_FATAL_ERROR; } - ret = XVFPRINTF((XFILE)bio->ptr, format, args); + ret = XVFPRINTF(bio->ptr.fh, format, args); break; #endif @@ -3088,21 +3352,22 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) return wolfSSL_BIO_write(bio, "\tNULL", 5); } - XSPRINTF(line, "%04x - ", lineOffset); + (void)XSNPRINTF(line, sizeof(line), "%04x - ", lineOffset); o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - XSPRINTF(line + o,"%02x ", (unsigned char)buf[i]); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + "%02x ", (unsigned char)buf[i]); else - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); if (i == 7) - XSPRINTF(line + o + 2, "-"); + (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); o += 3; } - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - XSPRINTF(line + o, "%c", + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/wolfcrypt/src/blake2b.c b/src/wolfcrypt/src/blake2b.c index adc6034..bce74b3 100644 --- a/src/wolfcrypt/src/blake2b.c +++ b/src/wolfcrypt/src/blake2b.c @@ -12,7 +12,7 @@ */ /* blake2b.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/blake2s.c b/src/wolfcrypt/src/blake2s.c index 9efa84f..7e36d6e 100644 --- a/src/wolfcrypt/src/blake2s.c +++ b/src/wolfcrypt/src/blake2s.c @@ -12,7 +12,7 @@ */ /* blake2s.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/camellia.c b/src/wolfcrypt/src/camellia.c index 9f2897f..3425177 100644 --- a/src/wolfcrypt/src/camellia.c +++ b/src/wolfcrypt/src/camellia.c @@ -27,7 +27,7 @@ /* camellia.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/chacha.c b/src/wolfcrypt/src/chacha.c index f497560..84b26eb 100644 --- a/src/wolfcrypt/src/chacha.c +++ b/src/wolfcrypt/src/chacha.c @@ -1,6 +1,6 @@ /* chacha.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -35,22 +35,56 @@ Public domain. #include -#if defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_ARMASM_NO_NEON) +#ifdef HAVE_CHACHA + #include + #include + + #ifdef NO_INLINE + #include + #else + #define WOLFSSL_MISC_INCLUDED + #include + #endif + + #ifdef BIG_ENDIAN_ORDER + #define LITTLE32(x) ByteReverseWord32(x) + #else + #define LITTLE32(x) (x) + #endif + + /* Number of rounds */ + #define ROUNDS 20 + + #define U32C(v) (v##U) + #define U32V(v) ((word32)(v) & U32C(0xFFFFFFFF)) + #define U8TO32_LITTLE(p) LITTLE32(((word32*)(p))[0]) + + #define ROTATE(v,c) rotlFixed(v, c) + #define XOR(v,w) ((v) ^ (w)) + #define PLUS(v,w) (U32V((v) + (w))) + #define PLUSONE(v) (PLUS((v),1)) + + #define QUARTERROUND(a,b,c,d) \ + x[a] = PLUS(x[a],x[b]); x[d] = ROTATE(XOR(x[d],x[a]),16); \ + x[c] = PLUS(x[c],x[d]); x[b] = ROTATE(XOR(x[b],x[c]),12); \ + x[a] = PLUS(x[a],x[b]); x[d] = ROTATE(XOR(x[d],x[a]), 8); \ + x[c] = PLUS(x[c],x[d]); x[b] = ROTATE(XOR(x[b],x[c]), 7); +#endif /* HAVE_CHACHA */ + + +#if defined(WOLFSSL_ARMASM) /* implementation is located in wolfcrypt/src/port/arm/armv8-chacha.c */ +#elif defined(WOLFSSL_RISCV_ASM) + /* implementation located in wolfcrypt/src/port/rsicv/riscv-64-chacha.c */ + #else + +/* BEGIN ChaCha C implementation */ #if defined(HAVE_CHACHA) -#include -#include #include #include -#ifdef NO_INLINE - #include -#else - #define WOLFSSL_MISC_INCLUDED - #include -#endif #ifdef CHACHA_AEAD_TEST #include @@ -85,31 +119,6 @@ Public domain. static word32 cpuidFlags = 0; #endif -#ifdef BIG_ENDIAN_ORDER - #define LITTLE32(x) ByteReverseWord32(x) -#else - #define LITTLE32(x) (x) -#endif - -/* Number of rounds */ -#define ROUNDS 20 - -#define U32C(v) (v##U) -#define U32V(v) ((word32)(v) & U32C(0xFFFFFFFF)) -#define U8TO32_LITTLE(p) LITTLE32(((word32*)(p))[0]) - -#define ROTATE(v,c) rotlFixed(v, c) -#define XOR(v,w) ((v) ^ (w)) -#define PLUS(v,w) (U32V((v) + (w))) -#define PLUSONE(v) (PLUS((v),1)) - -#define QUARTERROUND(a,b,c,d) \ - x[a] = PLUS(x[a],x[b]); x[d] = ROTATE(XOR(x[d],x[a]),16); \ - x[c] = PLUS(x[c],x[d]); x[b] = ROTATE(XOR(x[b],x[c]),12); \ - x[a] = PLUS(x[a],x[b]); x[d] = ROTATE(XOR(x[d],x[a]), 8); \ - x[c] = PLUS(x[c],x[d]); x[b] = ROTATE(XOR(x[b],x[c]), 7); - - /** * Set up iv(nonce). Earlier versions used 64 bits instead of 96, this version * uses the typical AEAD 96 bit nonce and can do record sizes of 256 GB. @@ -235,86 +244,6 @@ static WC_INLINE void wc_Chacha_wordtobyte(word32 x[CHACHA_CHUNK_WORDS], } #endif /* !USE_INTEL_CHACHA_SPEEDUP */ - -#ifdef HAVE_XCHACHA - -/* - * wc_HChacha_block - half a ChaCha block, for XChaCha - * - * see https://tools.ietf.org/html/draft-arciszewski-xchacha-03 - */ -static WC_INLINE void wc_HChacha_block(ChaCha* ctx, word32 stream[CHACHA_CHUNK_WORDS/2], word32 nrounds) -{ - word32 x[CHACHA_CHUNK_WORDS]; - word32 i; - - for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { - x[i] = ctx->X[i]; - } - - for (i = nrounds; i > 0; i -= 2) { - QUARTERROUND(0, 4, 8, 12) - QUARTERROUND(1, 5, 9, 13) - QUARTERROUND(2, 6, 10, 14) - QUARTERROUND(3, 7, 11, 15) - QUARTERROUND(0, 5, 10, 15) - QUARTERROUND(1, 6, 11, 12) - QUARTERROUND(2, 7, 8, 13) - QUARTERROUND(3, 4, 9, 14) - } - - for (i = 0; i < CHACHA_CHUNK_WORDS/4; ++i) - stream[i] = x[i]; - for (i = CHACHA_CHUNK_WORDS/4; i < CHACHA_CHUNK_WORDS/2; ++i) - stream[i] = x[i + CHACHA_CHUNK_WORDS/2]; -} - -/* XChaCha -- https://tools.ietf.org/html/draft-arciszewski-xchacha-03 */ -int wc_XChacha_SetKey(ChaCha *ctx, - const byte *key, word32 keySz, - const byte *nonce, word32 nonceSz, - word32 counter) { - word32 k[CHACHA_MAX_KEY_SZ]; - byte iv[CHACHA_IV_BYTES]; - int ret; - - if (nonceSz != XCHACHA_NONCE_BYTES) - return BAD_FUNC_ARG; - - if ((ret = wc_Chacha_SetKey(ctx, key, keySz)) < 0) - return ret; - - /* form a first chacha IV from the first 16 bytes of the nonce. - * the first word is supplied in the "counter" arg, and - * the result is a full 128 bit nonceful IV for the one-time block - * crypto op that follows. - */ - if ((ret = wc_Chacha_SetIV(ctx, nonce + 4, U8TO32_LITTLE(nonce))) < 0) - return ret; - - wc_HChacha_block(ctx, k, 20); /* 20 rounds, but keeping half the output. */ - - /* the HChacha output is used as a 256 bit key for the main cipher. */ - XMEMCPY(&ctx->X[4], k, 8 * sizeof(word32)); - - /* use 8 bytes from the end of the 24 byte nonce, padded up to 12 bytes, - * to form the IV for the main cipher. - */ - XMEMSET(iv, 0, 4); - XMEMCPY(iv + 4, nonce + 16, 8); - - if ((ret = wc_Chacha_SetIV(ctx, iv, counter)) < 0) - return ret; - - ForceZero(k, sizeof k); - ForceZero(iv, sizeof iv); - - return 0; -} - -#endif /* HAVE_XCHACHA */ - - #ifdef __cplusplus extern "C" { #endif @@ -438,7 +367,13 @@ int wc_Chacha_Process(ChaCha* ctx, byte* output, const byte* input, #endif } -void wc_Chacha_purge_current_block(ChaCha* ctx) { +#endif /* HAVE_CHACHA */ +#endif /* END ChaCha C implementation */ + +#if defined(HAVE_CHACHA) && defined(HAVE_XCHACHA) + +void wc_Chacha_purge_current_block(ChaCha* ctx) +{ if (ctx->left > 0) { byte scratch[CHACHA_CHUNK_BYTES]; XMEMSET(scratch, 0, sizeof(scratch)); @@ -446,6 +381,80 @@ void wc_Chacha_purge_current_block(ChaCha* ctx) { } } -#endif /* HAVE_CHACHA */ +/* + * wc_HChacha_block - half a ChaCha block, for XChaCha + * + * see https://tools.ietf.org/html/draft-arciszewski-xchacha-03 + */ +static WC_INLINE void wc_HChacha_block(ChaCha* ctx, + word32 stream[CHACHA_CHUNK_WORDS/2], word32 nrounds) +{ + word32 x[CHACHA_CHUNK_WORDS]; + word32 i; + + for (i = 0; i < CHACHA_CHUNK_WORDS; i++) { + x[i] = ctx->X[i]; + } + + for (i = nrounds; i > 0; i -= 2) { + QUARTERROUND(0, 4, 8, 12) + QUARTERROUND(1, 5, 9, 13) + QUARTERROUND(2, 6, 10, 14) + QUARTERROUND(3, 7, 11, 15) + QUARTERROUND(0, 5, 10, 15) + QUARTERROUND(1, 6, 11, 12) + QUARTERROUND(2, 7, 8, 13) + QUARTERROUND(3, 4, 9, 14) + } + + for (i = 0; i < CHACHA_CHUNK_WORDS/4; ++i) + stream[i] = x[i]; + for (i = CHACHA_CHUNK_WORDS/4; i < CHACHA_CHUNK_WORDS/2; ++i) + stream[i] = x[i + CHACHA_CHUNK_WORDS/2]; +} + +/* XChaCha -- https://tools.ietf.org/html/draft-arciszewski-xchacha-03 */ +int wc_XChacha_SetKey(ChaCha *ctx, + const byte *key, word32 keySz, + const byte *nonce, word32 nonceSz, + word32 counter) +{ + int ret; + word32 k[CHACHA_MAX_KEY_SZ]; + byte iv[CHACHA_IV_BYTES]; + + if (nonceSz != XCHACHA_NONCE_BYTES) + return BAD_FUNC_ARG; + + if ((ret = wc_Chacha_SetKey(ctx, key, keySz)) < 0) + return ret; + + /* form a first chacha IV from the first 16 bytes of the nonce. + * the first word is supplied in the "counter" arg, and + * the result is a full 128 bit nonceful IV for the one-time block + * crypto op that follows. + */ + if ((ret = wc_Chacha_SetIV(ctx, nonce + 4, U8TO32_LITTLE(nonce))) < 0) + return ret; + + wc_HChacha_block(ctx, k, 20); /* 20 rounds, but keeping half the output. */ + + /* the HChacha output is used as a 256 bit key for the main cipher. */ + XMEMCPY(&ctx->X[4], k, 8 * sizeof(word32)); + + /* use 8 bytes from the end of the 24 byte nonce, padded up to 12 bytes, + * to form the IV for the main cipher. + */ + XMEMSET(iv, 0, 4); + XMEMCPY(iv + 4, nonce + 16, 8); + + if ((ret = wc_Chacha_SetIV(ctx, iv, counter)) < 0) + return ret; + + ForceZero(k, sizeof k); + ForceZero(iv, sizeof iv); + + return 0; +} -#endif /* WOLFSSL_ARMASM && !WOLFSSL_ARMASM_NO_NEON */ +#endif /* HAVE_CHACHA && HAVE_XCHACHA */ diff --git a/src/wolfcrypt/src/chacha20_poly1305.c b/src/wolfcrypt/src/chacha20_poly1305.c index df4147c..a29a18f 100644 --- a/src/wolfcrypt/src/chacha20_poly1305.c +++ b/src/wolfcrypt/src/chacha20_poly1305.c @@ -1,6 +1,6 @@ /* chacha.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index b77cc33..52c1d2d 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -1,6 +1,6 @@ /* cmac.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -32,7 +32,7 @@ #include #endif -#if defined(WOLFSSL_CMAC) && !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) +#if defined(WOLFSSL_CMAC) #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ @@ -80,7 +80,7 @@ int wc_CMAC_Grow(Cmac* cmac, const byte* in, int inSz) } #endif /* WOLFSSL_HASH_KEEP */ - +#if !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) /* Used by AES-SIV. See aes.c. */ void ShiftAndXorRb(byte* out, byte* in) { @@ -100,6 +100,7 @@ void ShiftAndXorRb(byte* out, byte* in) } } } +#endif /* !NO_AES && WOLFSSL_AES_DIRECT */ /* returns 0 on success */ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, @@ -146,30 +147,40 @@ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, return BAD_FUNC_ARG; } - ret = wc_AesInit(&cmac->aes, heap, devId); + switch (type) { +#if !defined (NO_AES) && defined(WOLFSSL_AES_DIRECT) + case WC_CMAC_AES: + cmac->type = WC_CMAC_AES; + ret = wc_AesInit(&cmac->aes, heap, devId); -#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) - cmac->useSWCrypt = useSW; - if (cmac->useSWCrypt == 1) { - cmac->aes.useSWCrypt = 1; - } -#endif - - if (ret == 0) { - ret = wc_AesSetKey(&cmac->aes, key, keySz, NULL, AES_ENCRYPTION); - } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + cmac->useSWCrypt = useSW; + if (cmac->useSWCrypt == 1) { + cmac->aes.useSWCrypt = 1; + } + #endif - if (ret == 0) { - byte l[AES_BLOCK_SIZE]; + if (ret == 0) { + ret = wc_AesSetKey(&cmac->aes, key, keySz, NULL, AES_ENCRYPTION); + } - XMEMSET(l, 0, AES_BLOCK_SIZE); - ret = wc_AesEncryptDirect(&cmac->aes, l, l); if (ret == 0) { - ShiftAndXorRb(cmac->k1, l); - ShiftAndXorRb(cmac->k2, cmac->k1); - ForceZero(l, AES_BLOCK_SIZE); + byte l[AES_BLOCK_SIZE]; + + XMEMSET(l, 0, AES_BLOCK_SIZE); + ret = wc_AesEncryptDirect(&cmac->aes, l, l); + if (ret == 0) { + ShiftAndXorRb(cmac->k1, l); + ShiftAndXorRb(cmac->k2, cmac->k1); + ForceZero(l, AES_BLOCK_SIZE); + } } + break; +#endif /* !NO_AES && WOLFSSL_AES_DIRECT */ + default: + return BAD_FUNC_ARG; } + return ret; } @@ -201,7 +212,7 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) #endif { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, in, inSz, - NULL, NULL, 0, NULL); + NULL, NULL, cmac->type, NULL); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -211,26 +222,35 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) /* Clear CRYPTOCB_UNAVAILABLE return code */ ret = 0; - while ((ret == 0) && (inSz != 0)) { - word32 add = min(inSz, AES_BLOCK_SIZE - cmac->bufferSz); - XMEMCPY(&cmac->buffer[cmac->bufferSz], in, add); - - cmac->bufferSz += add; - in += add; - inSz -= add; - - if (cmac->bufferSz == AES_BLOCK_SIZE && inSz != 0) { - if (cmac->totalSz != 0) { - xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); - } - ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, cmac->buffer); - if (ret == 0) { - cmac->totalSz += AES_BLOCK_SIZE; - cmac->bufferSz = 0; + switch (cmac->type) { +#if !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) + case WC_CMAC_AES: + { + while ((ret == 0) && (inSz != 0)) { + word32 add = min(inSz, AES_BLOCK_SIZE - cmac->bufferSz); + XMEMCPY(&cmac->buffer[cmac->bufferSz], in, add); + + cmac->bufferSz += add; + in += add; + inSz -= add; + + if (cmac->bufferSz == AES_BLOCK_SIZE && inSz != 0) { + if (cmac->totalSz != 0) { + xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); + } + ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, + cmac->buffer); + if (ret == 0) { + cmac->totalSz += AES_BLOCK_SIZE; + cmac->bufferSz = 0; + } } } + }; break; +#endif /* !NO_AES && WOLFSSL_AES_DIRECT */ + default: + ret = BAD_FUNC_ARG; } - return ret; } @@ -242,11 +262,18 @@ int wc_CmacFree(Cmac* cmac) /* TODO: msg is leaked if wc_CmacFinal() is not called * e.g. when multiple calls to wc_CmacUpdate() and one fails but * wc_CmacFinal() not called. */ - if (cmac->msg != NULL) { - XFREE(cmac->msg, cmac->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(cmac->msg, cmac->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - wc_AesFree(&cmac->aes); + switch (cmac->type) { +#if !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) + case WC_CMAC_AES: + wc_AesFree(&cmac->aes); + break; +#endif /* !NO_AES && WOLFSSL_AES_DIRECT */ + default: + /* Nothing to do */ + (void)cmac; + } ForceZero(cmac, sizeof(Cmac)); return 0; } @@ -254,8 +281,6 @@ int wc_CmacFree(Cmac* cmac) int wc_CmacFinalNoFree(Cmac* cmac, byte* out, word32* outSz) { int ret = 0; - const byte* subKey; - word32 remainder; if (cmac == NULL || out == NULL || outSz == NULL) { return BAD_FUNC_ARG; @@ -269,44 +294,64 @@ int wc_CmacFinalNoFree(Cmac* cmac, byte* out, word32* outSz) if (cmac->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, 0, NULL); + ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, cmac->type, + NULL); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; - /* fall-through when unavailable */ - } -#endif - if (cmac->bufferSz == AES_BLOCK_SIZE) { - subKey = cmac->k1; - } - else { - /* ensure we will have a valid remainder value */ - if (cmac->bufferSz > AES_BLOCK_SIZE) { - return BAD_STATE_E; - } - remainder = AES_BLOCK_SIZE - cmac->bufferSz; + /* Clear CRYPTOCB_UNAVAILABLE return code */ + ret = 0; - if (remainder == 0) { - remainder = AES_BLOCK_SIZE; - } - if (remainder > 1) { - XMEMSET(cmac->buffer + AES_BLOCK_SIZE - remainder, 0, remainder); - } - - cmac->buffer[AES_BLOCK_SIZE - remainder] = 0x80; - subKey = cmac->k2; + /* fall-through when unavailable */ } - xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); - xorbuf(cmac->buffer, subKey, AES_BLOCK_SIZE); - ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, cmac->buffer); +#endif if (ret == 0) { - XMEMCPY(out, cmac->digest, *outSz); + switch (cmac->type) { + #if !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) + case WC_CMAC_AES: + { + const byte* subKey; + word32 remainder; + + if (cmac->bufferSz == AES_BLOCK_SIZE) { + subKey = cmac->k1; + } + else { + /* ensure we will have a valid remainder value */ + if (cmac->bufferSz > AES_BLOCK_SIZE) { + ret = BAD_STATE_E; + break; + } + remainder = AES_BLOCK_SIZE - cmac->bufferSz; + + if (remainder == 0) { + remainder = AES_BLOCK_SIZE; + } + if (remainder > 1) { + XMEMSET(cmac->buffer + AES_BLOCK_SIZE - remainder, 0, + remainder); + } + + cmac->buffer[AES_BLOCK_SIZE - remainder] = 0x80; + subKey = cmac->k2; + } + xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); + xorbuf(cmac->buffer, subKey, AES_BLOCK_SIZE); + ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, cmac->buffer); + if (ret == 0) { + XMEMCPY(out, cmac->digest, *outSz); + } + }; break; + #endif /* !NO_AES && WOLFSSL_AES_DIRECT */ + default: + ret = BAD_FUNC_ARG; + } } - - return 0; + return ret; } -int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) { +int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) +{ int ret = 0; if (cmac == NULL) @@ -316,7 +361,7 @@ int wc_CmacFinal(Cmac* cmac, byte* out, word32* outSz) { return ret; } - +#if !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) int wc_AesCmacGenerate_ex(Cmac* cmac, byte* out, word32* outSz, const byte* in, word32 inSz, @@ -336,8 +381,6 @@ int wc_AesCmacGenerate_ex(Cmac* cmac, if (devId != INVALID_DEVID) #endif { - cmac->devCtx = NULL; - ret = wc_CryptoCb_Cmac(cmac, key, keySz, in, inSz, out, outSz, WC_CMAC_AES, NULL); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) @@ -414,9 +457,7 @@ int wc_AesCmacGenerate(byte* out, word32* outSz, #ifdef WOLFSSL_SMALL_STACK - if (cmac) { - XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); - } + XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); #elif defined(WOLFSSL_CHECK_MEM_ZERO) wc_MemZero_Check(cmac, sizeof(Cmac)); #endif @@ -436,7 +477,8 @@ int wc_AesCmacVerify_ex(Cmac* cmac, word32 aSz = sizeof(a); int compareRet; - if (cmac == NULL || check == NULL || checkSz == 0 || (in == NULL && inSz != 0)) { + if (cmac == NULL || check == NULL || checkSz == 0 || + (in == NULL && inSz != 0)) { return BAD_FUNC_ARG; } @@ -495,14 +537,13 @@ int wc_AesCmacVerify(const byte* check, word32 checkSz, INVALID_DEVID); #ifdef WOLFSSL_SMALL_STACK - if (cmac) { - XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); - } + XFREE(cmac, NULL, DYNAMIC_TYPE_CMAC); #elif defined(WOLFSSL_CHECK_MEM_ZERO) wc_MemZero_Check(cmac, sizeof(Cmac)); #endif return ret; } +#endif /* !NO_AES && WOLFSSL_AES_DIRECT */ -#endif /* WOLFSSL_CMAC && NO_AES && WOLFSSL_AES_DIRECT */ +#endif /* WOLFSSL_CMAC */ diff --git a/src/wolfcrypt/src/coding.c b/src/wolfcrypt/src/coding.c index 2509948..aa87ae7 100644 --- a/src/wolfcrypt/src/coding.c +++ b/src/wolfcrypt/src/coding.c @@ -1,6 +1,6 @@ /* coding.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -458,7 +458,7 @@ static int DoBase64_Encode(const byte* in, word32 inLen, byte* out, *outLen = i; if (ret == 0) - return getSzOnly ? LENGTH_ONLY_E : 0; + return getSzOnly ? WC_NO_ERR_TRACE(LENGTH_ONLY_E) : 0; return ret; } diff --git a/src/wolfcrypt/src/compress.c b/src/wolfcrypt/src/compress.c index 58c154c..941596e 100644 --- a/src/wolfcrypt/src/compress.c +++ b/src/wolfcrypt/src/compress.c @@ -1,6 +1,6 @@ /* compress.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -310,10 +310,8 @@ int wc_DeCompressDynamic(byte** out, int maxSz, int memoryType, if (inflateEnd(&stream) != Z_OK) result = DECOMPRESS_E; - if (tmp != NULL) { - XFREE(tmp, heap, memoryType); - tmp = NULL; - } + XFREE(tmp, heap, memoryType); + tmp = NULL; return result; } diff --git a/src/wolfcrypt/src/cpuid.c b/src/wolfcrypt/src/cpuid.c index fa7ee43..6722386 100644 --- a/src/wolfcrypt/src/cpuid.c +++ b/src/wolfcrypt/src/cpuid.c @@ -1,6 +1,6 @@ /* cpuid.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/cryptocb.c b/src/wolfcrypt/src/cryptocb.c index 06b9ebe..4b903dd 100644 --- a/src/wolfcrypt/src/cryptocb.c +++ b/src/wolfcrypt/src/cryptocb.c @@ -1,6 +1,6 @@ /* cryptocb.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -55,7 +55,6 @@ #ifdef WOLFSSL_CAAM #include #endif - /* TODO: Consider linked list with mutex */ #ifndef MAX_CRYPTO_DEVID_CALLBACKS #define MAX_CRYPTO_DEVID_CALLBACKS 8 @@ -85,6 +84,7 @@ static const char* GetAlgoTypeStr(int algo) case WC_ALGO_TYPE_RNG: return "RNG"; case WC_ALGO_TYPE_SEED: return "Seed"; case WC_ALGO_TYPE_HMAC: return "HMAC"; + case WC_ALGO_TYPE_CMAC: return "CMAC"; } return NULL; } @@ -104,6 +104,7 @@ static const char* GetPkTypeStr(int pk) } return NULL; } +#if !defined(NO_AES) || !defined(NO_DES3) static const char* GetCipherTypeStr(int cipher) { switch (cipher) { @@ -119,6 +120,7 @@ static const char* GetCipherTypeStr(int cipher) } return NULL; } +#endif /* !NO_AES || !NO_DES3 */ static const char* GetHashTypeStr(int hash) { switch (hash) { @@ -141,6 +143,16 @@ static const char* GetHashTypeStr(int hash) return NULL; } +#ifdef WOLFSSL_CMAC +static const char* GetCmacTypeStr(int type) +{ + switch (type) { + case WC_CMAC_AES: return "AES"; + } + return NULL; +} +#endif /* WOLFSSL_CMAC */ + #ifndef NO_RSA static const char* GetRsaType(int type) { @@ -186,12 +198,14 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) GetPkTypeStr(info->pk.type), info->pk.type); } } +#if !defined(NO_AES) || !defined(NO_DES3) else if (info->algo_type == WC_ALGO_TYPE_CIPHER) { printf("Crypto CB: %s %s (%d) (%p ctx)\n", GetAlgoTypeStr(info->algo_type), GetCipherTypeStr(info->cipher.type), info->cipher.type, info->cipher.ctx); } +#endif /* !NO_AES || !NO_DES3 */ else if (info->algo_type == WC_ALGO_TYPE_HASH) { printf("Crypto CB: %s %s (%d) (%p ctx) %s\n", GetAlgoTypeStr(info->algo_type), @@ -206,6 +220,17 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) info->hmac.macType, info->hmac.hmac, (info->hmac.in != NULL) ? "Update" : "Final"); } +#ifdef WOLFSSL_CMAC + else if (info->algo_type == WC_ALGO_TYPE_CMAC) { + printf("Crypto CB: %s %s (%d) (%p ctx) %s %s %s\n", + GetAlgoTypeStr(info->algo_type), + GetCmacTypeStr(info->cmac.type), + info->cmac.type, info->cmac.cmac, + (info->cmac.key != NULL) ? "Init " : "", + (info->cmac.in != NULL) ? "Update " : "", + (info->cmac.out != NULL) ? "Final" : ""); + } +#endif #ifdef WOLF_CRYPTO_CB_CMD else if (info->algo_type == WC_ALGO_TYPE_NONE) { printf("Crypto CB: %s %s (%d)\n", @@ -418,6 +443,62 @@ int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, return wc_CryptoCb_TranslateErrorCode(ret); } +#ifdef WOLF_CRYPTO_CB_RSA_PAD +int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, + word32* outLen, int type, RsaKey* key, WC_RNG* rng, + RsaPadding *padding) +{ + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); + CryptoCb* dev; + int pk_type; + + if (key == NULL) + return ret; + + /* locate registered callback */ + dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); + + if (padding) { + switch(padding->pad_type) { +#ifndef NO_PKCS11_RSA_PKCS + case WC_RSA_PKCSV15_PAD: + pk_type = WC_PK_TYPE_RSA_PKCS; + break; + case WC_RSA_PSS_PAD: + pk_type = WC_PK_TYPE_RSA_PSS; + break; + case WC_RSA_OAEP_PAD: + pk_type = WC_PK_TYPE_RSA_OAEP; + break; +#endif /* NO_PKCS11_RSA_PKCS */ + default: + pk_type = WC_PK_TYPE_RSA; + } + } else { + pk_type = WC_PK_TYPE_RSA; + } + + if (dev && dev->cb) { + wc_CryptoInfo cryptoInfo; + XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); + cryptoInfo.algo_type = WC_ALGO_TYPE_PK; + cryptoInfo.pk.type = pk_type; + cryptoInfo.pk.rsa.in = in; + cryptoInfo.pk.rsa.inLen = inLen; + cryptoInfo.pk.rsa.out = out; + cryptoInfo.pk.rsa.outLen = outLen; + cryptoInfo.pk.rsa.type = type; + cryptoInfo.pk.rsa.key = key; + cryptoInfo.pk.rsa.rng = rng; + cryptoInfo.pk.rsa.padding = padding; + + ret = dev->cb(dev->devId, &cryptoInfo, dev->ctx); + } + + return wc_CryptoCb_TranslateErrorCode(ret); +} +#endif + #ifdef WOLFSSL_KEY_GEN int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { @@ -1719,7 +1800,8 @@ int wc_CryptoCb_RandomSeed(OS_Seed* os, byte* seed, word32 sz) return wc_CryptoCb_TranslateErrorCode(ret); } #endif /* !WC_NO_RNG */ -#ifdef WOLFSSL_CMAC + +#if defined(WOLFSSL_CMAC) int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, const byte* in, word32 inSz, byte* out, word32* outSz, int type, void* ctx) @@ -1735,7 +1817,6 @@ int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, /* locate first callback and try using it */ dev = wc_CryptoCb_FindDeviceByIndex(0); } - if (dev && dev->cb) { wc_CryptoInfo cryptoInfo; XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); @@ -1756,7 +1837,7 @@ int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, return wc_CryptoCb_TranslateErrorCode(ret); } -#endif +#endif /* WOLFSSL_CMAC */ /* returns the default dev id for the current build */ int wc_CryptoCb_DefaultDevID(void) diff --git a/src/wolfcrypt/src/curve25519.c b/src/wolfcrypt/src/curve25519.c index 4cd29c4..7641055 100644 --- a/src/wolfcrypt/src/curve25519.c +++ b/src/wolfcrypt/src/curve25519.c @@ -1,6 +1,6 @@ /* curve25519.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -655,6 +655,40 @@ int wc_curve25519_import_private_ex(const byte* priv, word32 privSz, #endif /* HAVE_CURVE25519_KEY_IMPORT */ +#ifndef WC_NO_CONSTRUCTORS +curve25519_key* wc_curve25519_new(void* heap, int devId, int *result_code) +{ + int ret; + curve25519_key* key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), heap, + DYNAMIC_TYPE_CURVE25519); + if (key == NULL) { + ret = MEMORY_E; + } + else { + ret = wc_curve25519_init_ex(key, heap, devId); + if (ret != 0) { + XFREE(key, heap, DYNAMIC_TYPE_CURVE25519); + key = NULL; + } + } + + if (result_code != NULL) + *result_code = ret; + + return key; +} + +int wc_curve25519_delete(curve25519_key* key, curve25519_key** key_p) { + if (key == NULL) + return BAD_FUNC_ARG; + wc_curve25519_free(key); + XFREE(key, key->heap, DYNAMIC_TYPE_CURVE25519); + if (key_p != NULL) + *key_p = NULL; + return 0; +} +#endif /* !WC_NO_CONSTRUCTORS */ + int wc_curve25519_init_ex(curve25519_key* key, void* heap, int devId) { if (key == NULL) @@ -698,11 +732,8 @@ void wc_curve25519_free(curve25519_key* key) se050_curve25519_free_key(key); #endif - key->dp = NULL; - ForceZero(key->k, sizeof(key->k)); - XMEMSET(&key->p, 0, sizeof(key->p)); - key->pubSet = 0; - key->privSet = 0; + ForceZero(key, sizeof(*key)); + #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Check(key, sizeof(curve25519_key)); #endif diff --git a/src/wolfcrypt/src/curve448.c b/src/wolfcrypt/src/curve448.c index dd320a8..3cbf577 100644 --- a/src/wolfcrypt/src/curve448.c +++ b/src/wolfcrypt/src/curve448.c @@ -1,6 +1,6 @@ /* curve448.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/des3.c b/src/wolfcrypt/src/des3.c index e66a33d..93bdde2 100644 --- a/src/wolfcrypt/src/des3.c +++ b/src/wolfcrypt/src/des3.c @@ -1,6 +1,6 @@ /* des3.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -1031,6 +1031,169 @@ } +#ifdef WOLFSSL_DES_ECB + /* One block, compatibility only */ + int wc_Des_EcbEncrypt(Des* des, byte* out, const byte* in, word32 sz) + { + int offset = 0; + int len = sz; + int ret = 0; + byte temp_block[DES_BLOCK_SIZE]; + + + #ifdef FREESCALE_MMCAU_CLASSIC + if ((wc_ptr_t)out % WOLFSSL_MMCAU_ALIGNMENT) { + WOLFSSL_MSG("Bad cau_des_encrypt alignment"); + return BAD_ALIGN_E; + } + #endif + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + ret = wolfSSL_CryptHwMutexLock(); + if (ret != 0) { + return ret; + } + #ifdef FREESCALE_MMCAU_CLASSIC + cau_des_encrypt(temp_block, (byte*)des->key, out + offset); + #else + MMCAU_DES_EncryptEcb(temp_block, (byte*)des->key, out + offset); + #endif + wolfSSL_CryptHwMutexUnLock(); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + + } + return ret; + + } + + int wc_Des_EcbDecrypt(Des* des, byte* out, const byte* in, word32 sz) + { + int offset = 0; + int len = sz; + int ret = 0; + byte temp_block[DES_BLOCK_SIZE]; + + #ifdef FREESCALE_MMCAU_CLASSIC + if ((wc_ptr_t)out % WOLFSSL_MMCAU_ALIGNMENT) { + WOLFSSL_MSG("Bad cau_des_decrypt alignment"); + return BAD_ALIGN_E; + } + #endif + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + ret = wolfSSL_CryptHwMutexLock(); + if (ret != 0) { + return ret; + } + + #ifdef FREESCALE_MMCAU_CLASSIC + cau_des_decrypt(in + offset, (byte*)des->key, out + offset); + #else + MMCAU_DES_DecryptEcb(in + offset, (byte*)des->key, out + offset); + #endif + wolfSSL_CryptHwMutexUnLock(); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + } + + return ret; + } + + int wc_Des3_EcbEncrypt(Des3* des, byte* out, const byte* in, word32 sz) + { + int offset = 0; + int len = sz; + int ret = 0; + + byte temp_block[DES_BLOCK_SIZE]; + + + #ifdef FREESCALE_MMCAU_CLASSIC + if ((wc_ptr_t)out % WOLFSSL_MMCAU_ALIGNMENT) { + WOLFSSL_MSG("Bad 3ede cau_des_encrypt alignment"); + return BAD_ALIGN_E; + } + #endif + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + ret = wolfSSL_CryptHwMutexLock(); + if (ret != 0) { + return ret; + } + #ifdef FREESCALE_MMCAU_CLASSIC + cau_des_encrypt(temp_block, (byte*)des->key[0], out + offset); + cau_des_decrypt(out + offset, (byte*)des->key[1], out + offset); + cau_des_encrypt(out + offset, (byte*)des->key[2], out + offset); + #else + MMCAU_DES_EncryptEcb(temp_block , (byte*)des->key[0], out + offset); + MMCAU_DES_DecryptEcb(out + offset, (byte*)des->key[1], out + offset); + MMCAU_DES_EncryptEcb(out + offset, (byte*)des->key[2], out + offset); + #endif + wolfSSL_CryptHwMutexUnLock(); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + + } + + return ret; + } + + int wc_Des3_EcbDecrypt(Des3* des, byte* out, const byte* in, word32 sz) + { + int offset = 0; + int len = sz; + int ret = 0; + + byte temp_block[DES_BLOCK_SIZE]; + + #ifdef FREESCALE_MMCAU_CLASSIC + if ((wc_ptr_t)out % WOLFSSL_MMCAU_ALIGNMENT) { + WOLFSSL_MSG("Bad 3ede cau_des_decrypt alignment"); + return BAD_ALIGN_E; + } + #endif + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + ret = wolfSSL_CryptHwMutexLock(); + if (ret != 0) { + return ret; + } + #ifdef FREESCALE_MMCAU_CLASSIC + cau_des_decrypt(in + offset, (byte*)des->key[2], out + offset); + cau_des_encrypt(out + offset, (byte*)des->key[1], out + offset); + cau_des_decrypt(out + offset, (byte*)des->key[0], out + offset); + #else + MMCAU_DES_DecryptEcb(in + offset , (byte*)des->key[2], out + offset); + MMCAU_DES_EncryptEcb(out + offset, (byte*)des->key[1], out + offset); + MMCAU_DES_DecryptEcb(out + offset, (byte*)des->key[0], out + offset); + #endif + wolfSSL_CryptHwMutexUnLock(); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + } + + return ret; + } +#endif /* WOLFSSL_DES_ECB */ + + #elif defined(WOLFSSL_PIC32MZ_CRYPT) /* PIC32MZ DES hardware requires size multiple of block size */ diff --git a/src/wolfcrypt/src/dh.c b/src/wolfcrypt/src/dh.c index 28ed197..610b4b6 100644 --- a/src/wolfcrypt/src/dh.c +++ b/src/wolfcrypt/src/dh.c @@ -1,6 +1,6 @@ /* dh.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -1028,7 +1028,7 @@ static int _ffc_pairwise_consistency_test(DhKey* key, if (n < 5) return 0; else - return (word32)(2.4 * XPOW((double)n, 1.0/3.0) * + return (word32)((double)2.4 * XPOW((double)n, 1.0/3.0) * XPOW(XLOG((double)n), 2.0/3.0) - 5); } #endif /* WOLFSSL_DH_CONST*/ @@ -1153,7 +1153,7 @@ static int GeneratePrivateDh186(DhKey* key, WC_RNG* rng, byte* priv, } #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Add("GeneratePrivateDh186 cBuf", cBuf, cSz); + wc_MemZero_Add("GeneratePrivateDh186 cBuf", cBuf, cSz); /* cppcheck-suppress uninitvar */ mp_memzero_add("GeneratePrivateDh186 tmpX", tmpX); #endif do { @@ -1981,7 +1981,7 @@ int wc_DhGenerateKeyPair(DhKey* key, WC_RNG* rng, #ifndef WOLFSSL_KCAPI_DH static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, - const byte* priv, word32 privSz, const byte* otherPub, word32 pubSz) + const byte* priv, word32 privSz, const byte* otherPub, word32 pubSz, int ct) { int ret = 0; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) @@ -2138,6 +2138,13 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #endif #if !defined(WOLFSSL_SP_MATH) + if (ct) { + /* for the constant-time variant, we will probably use more bits in x for + * the modexp than we read from the private key, and those extra bits need + * to be zeroed. + */ + XMEMSET(x, 0, sizeof *x); + } if (mp_init_multi(x, y, z, 0, 0, 0) != MP_OKAY) { #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(z, key->heap, DYNAMIC_TYPE_DH); @@ -2159,8 +2166,17 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) ret = MP_READ_E; - if (ret == 0 && mp_exptmod(y, x, &key->p, z) != MP_OKAY) - ret = MP_EXPTMOD_E; + if (ret == 0) { + if (ct) + ret = mp_exptmod_ex(y, x, + ((int)*agreeSz + DIGIT_BIT - 1) / DIGIT_BIT, + &key->p, z); + else + ret = mp_exptmod(y, x, &key->p, z); + if (ret != MP_OKAY) + ret = MP_EXPTMOD_E; + } + #ifdef WOLFSSL_CHECK_MEM_ZERO if (ret == 0) mp_memzero_add("wc_DhAgree_Sync z", z); @@ -2170,11 +2186,16 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, if (ret == 0 && (mp_cmp_d(z, 1) == MP_EQ)) ret = MP_VAL; - if (ret == 0 && mp_to_unsigned_bin(z, agree) != MP_OKAY) - ret = MP_TO_E; - - if (ret == 0) - *agreeSz = (word32)mp_unsigned_bin_size(z); + if (ret == 0) { + if (ct) { + ret = mp_to_unsigned_bin_len_ct(z, agree, (int)*agreeSz); + } + else { + ret = mp_to_unsigned_bin(z, agree); + if (ret == MP_OKAY) + *agreeSz = (word32)mp_unsigned_bin_size(z); + } + } mp_forcezero(z); mp_clear(y); @@ -2183,6 +2204,7 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, RESTORE_VECTOR_REGISTERS(); #else + (void)ct; ret = WC_KEY_SIZE_E; #endif @@ -2238,7 +2260,8 @@ static int wc_DhAgree_Async(DhKey* key, byte* agree, word32* agreeSz, #endif /* otherwise use software DH */ - ret = wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz); + ret = wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz, + 0); return ret; } @@ -2267,13 +2290,69 @@ int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv, else #endif { - ret = wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz); + ret = wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, + pubSz, 0); } #endif /* WOLFSSL_KCAPI_DH */ return ret; } +int wc_DhAgree_ct(DhKey* key, byte* agree, word32 *agreeSz, const byte* priv, + word32 privSz, const byte* otherPub, word32 pubSz) +{ + int ret; + word32 requested_agreeSz; +#ifndef WOLFSSL_NO_MALLOC + byte *agree_buffer = NULL; +#else + byte agree_buffer[DH_MAX_SIZE / 8]; +#endif + + if (key == NULL || agree == NULL || agreeSz == NULL || priv == NULL || + otherPub == NULL) { + return BAD_FUNC_ARG; + } + + requested_agreeSz = *agreeSz; + +#ifndef WOLFSSL_NO_MALLOC + agree_buffer = (byte *)XMALLOC(requested_agreeSz, key->heap, + DYNAMIC_TYPE_DH); + if (agree_buffer == NULL) + return MEMORY_E; +#endif + + XMEMSET(agree_buffer, 0, requested_agreeSz); + + ret = wc_DhAgree_Sync(key, agree_buffer, agreeSz, priv, privSz, otherPub, + pubSz, 1); + + if (ret == 0) { + /* Arrange for correct fixed-length, right-justified key, even if the + * crypto back end doesn't support it. This assures that the key is + * unconditionally agreed correctly. With some crypto back ends, + * e.g. heapmath, there are no provisions for actual constant time, but + * with others the key computation and clamping is constant time, and + * the unclamping here is also constant time. + */ + byte *agree_src = agree_buffer + *agreeSz - 1, + *agree_dst = agree + requested_agreeSz - 1; + while (agree_dst >= agree) { + word32 mask = (agree_src >= agree_buffer) - 1U; + agree_src += (mask & requested_agreeSz); + *agree_dst-- = *agree_src--; + } + *agreeSz = requested_agreeSz; + } + +#ifndef WOLFSSL_NO_MALLOC + XFREE(agree_buffer, key->heap, DYNAMIC_TYPE_DH); +#endif + + return ret; +} + #ifdef WOLFSSL_DH_EXTRA WOLFSSL_LOCAL int wc_DhKeyCopy(DhKey* src, DhKey* dst) { @@ -2900,7 +2979,11 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) primeCheckCount = 0; int primeCheck = MP_NO, ret = 0; +#ifdef WOLFSSL_NO_MALLOC + unsigned char buf[DH_MAX_SIZE / WOLFSSL_BIT_SIZE]; +#else unsigned char *buf = NULL; +#endif #if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC) XMEMSET(tmp, 0, sizeof(tmp)); @@ -2950,11 +3033,16 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) if (ret == 0) { bufSz = (word32)modSz - groupSz; +#ifdef WOLFSSL_NO_MALLOC + if (bufSz > sizeof(buf)) + ret = MEMORY_E; +#else /* allocate ram */ buf = (unsigned char *)XMALLOC(bufSz, dh->heap, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) ret = MEMORY_E; +#endif } /* make a random string that will be multiplied against q */ @@ -3088,11 +3176,16 @@ int wc_DhGenerateParams(WC_RNG *rng, int modSz, DhKey *dh) RESTORE_VECTOR_REGISTERS(); - if (buf != NULL) { +#ifndef WOLFSSL_NO_MALLOC + if (buf != NULL) +#endif + { ForceZero(buf, bufSz); +#ifndef WOLFSSL_NO_MALLOC if (dh != NULL) { XFREE(buf, dh->heap, DYNAMIC_TYPE_TMP_BUFFER); } +#endif } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) @@ -3149,7 +3242,7 @@ int wc_DhExportParamsRaw(DhKey* dh, byte* p, word32* pSz, *pSz = pLen; *qSz = qLen; *gSz = gLen; - ret = LENGTH_ONLY_E; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } } diff --git a/src/wolfcrypt/src/dilithium.c b/src/wolfcrypt/src/dilithium.c index f3a6f01..ce01042 100644 --- a/src/wolfcrypt/src/dilithium.c +++ b/src/wolfcrypt/src/dilithium.c @@ -1,6 +1,6 @@ /* dilithium.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -58,6 +58,19 @@ * WOLFSSL_DILITHIUM_SIGN_SMALL_MEM Default: OFF * Compiles signature implementation that uses smaller amounts of memory but * is considerably slower. + * WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC Default: OFF + * Compiles signature implementation that uses smaller amounts of memory but + * is considerably slower. Allocates vectors and decodes private key data + * into them upfront. + * WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A Default: OFF + * Compiles signature implementation that uses smaller amounts of memory but + * is slower. Allocates matrix A and calculates it upfront. + * WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM Default: OFF + * Compiles key generation implementation that uses smaller amounts of memory + * but is slower. + * WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 Default: OFF + * Compiles the small memory implementations to use a 64-bit polynomial. + * Uses 2KB of memory but is slightly quicker (2.75-7%). * * WOLFSSL_DILITHIUM_ALIGNMENT Default: 8 * Use to indicate whether loading and storing of words needs to be aligned. @@ -67,6 +80,9 @@ * * WOLFSSL_DILITHIUM_NO_ASN1 Default: OFF * Disables any ASN.1 encoding or decoding code. + * WOLFSSL_DILITHIUM_REVERSE_HASH_OID Default: OFF + * Reverse the DER encoded hash oid when signing and verifying a pre-hashed + * message. * * WC_DILITHIUM_CACHE_MATRIX_A Default: OFF * Enable caching of the A matrix on import. @@ -79,6 +95,10 @@ * Enable caching of public key vectors on import. * Enables WC_DILITHIUM_CACHE_MATRIX_A. * Less work is required in sign operations. + * WC_DILITHIUM_FIXED_ARRAY Default: OFF + * Make the matrix and vectors of cached data fixed arrays that have + * maximumal sizes for the configured parameters. + * Useful in low dynamic memory situations. * * WOLFSSL_DILITHIUM_SIGN_CHECK_Y Default: OFF * Check vector y is in required range as an early check on valid vector z. @@ -129,6 +149,7 @@ #endif #include +#include #include #include #ifdef NO_INLINE @@ -138,6 +159,18 @@ #include #endif +#if defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) + #define WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +#endif +#if defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) + #define WOLFSSL_DILITHIUM_SIGN_SMALL_MEM + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC + #error "PRECALC and PRECALC_A is equivalent to non small mem" + #endif +#endif + #ifdef WOLFSSL_WC_DILITHIUM #ifdef DEBUG_DILITHIUM @@ -217,6 +250,9 @@ void print_data(const char* name, const byte* d, int len) /* Number of bytes to a block of SHAKE-256 when generating s1 and s2. */ #define DILITHIUM_GEN_S_BLOCK_BYTES (WC_SHA3_256_COUNT * 8) +/* Length of the hash OID to include in pre-hash message. */ +#define DILITHIUM_HASH_OID_LEN 11 + /* The ML-DSA parameters sets. */ static const wc_dilithium_params dilithium_params[] = { @@ -256,6 +292,44 @@ static const wc_dilithium_params dilithium_params[] = { PARAMS_ML_DSA_87_Z_ENC_SIZE, PARAMS_ML_DSA_87_PK_SIZE, PARAMS_ML_DSA_87_SIG_SIZE }, #endif +#if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) +#ifndef WOLFSSL_NO_ML_DSA_44 + { WC_ML_DSA_44_DRAFT, PARAMS_ML_DSA_44_K, PARAMS_ML_DSA_44_L, + PARAMS_ML_DSA_44_ETA, PARAMS_ML_DSA_44_ETA_BITS, + PARAMS_ML_DSA_44_TAU, PARAMS_ML_DSA_44_BETA, PARAMS_ML_DSA_44_OMEGA, + PARAMS_ML_DSA_44_LAMBDA, + PARAMS_ML_DSA_44_GAMMA1_BITS, PARAMS_ML_DSA_44_GAMMA2, + PARAMS_ML_DSA_44_W1_ENC_SZ, PARAMS_ML_DSA_44_A_SIZE, + PARAMS_ML_DSA_44_S1_SIZE, PARAMS_ML_DSA_44_S1_ENC_SIZE, + PARAMS_ML_DSA_44_S2_SIZE, PARAMS_ML_DSA_44_S2_ENC_SIZE, + PARAMS_ML_DSA_44_Z_ENC_SIZE, + PARAMS_ML_DSA_44_PK_SIZE, PARAMS_ML_DSA_44_SIG_SIZE }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + { WC_ML_DSA_65_DRAFT, PARAMS_ML_DSA_65_K, PARAMS_ML_DSA_65_L, + PARAMS_ML_DSA_65_ETA, PARAMS_ML_DSA_65_ETA_BITS, + PARAMS_ML_DSA_65_TAU, PARAMS_ML_DSA_65_BETA, PARAMS_ML_DSA_65_OMEGA, + PARAMS_ML_DSA_65_LAMBDA, + PARAMS_ML_DSA_65_GAMMA1_BITS, PARAMS_ML_DSA_65_GAMMA2, + PARAMS_ML_DSA_65_W1_ENC_SZ, PARAMS_ML_DSA_65_A_SIZE, + PARAMS_ML_DSA_65_S1_SIZE, PARAMS_ML_DSA_65_S1_ENC_SIZE, + PARAMS_ML_DSA_65_S2_SIZE, PARAMS_ML_DSA_65_S2_ENC_SIZE, + PARAMS_ML_DSA_65_Z_ENC_SIZE, + PARAMS_ML_DSA_65_PK_SIZE, PARAMS_ML_DSA_65_SIG_SIZE }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + { WC_ML_DSA_87_DRAFT, PARAMS_ML_DSA_87_K, PARAMS_ML_DSA_87_L, + PARAMS_ML_DSA_87_ETA, PARAMS_ML_DSA_87_ETA_BITS, + PARAMS_ML_DSA_87_TAU, PARAMS_ML_DSA_87_BETA, PARAMS_ML_DSA_87_OMEGA, + PARAMS_ML_DSA_87_LAMBDA, + PARAMS_ML_DSA_87_GAMMA1_BITS, PARAMS_ML_DSA_87_GAMMA2, + PARAMS_ML_DSA_87_W1_ENC_SZ, PARAMS_ML_DSA_87_A_SIZE, + PARAMS_ML_DSA_87_S1_SIZE, PARAMS_ML_DSA_87_S1_ENC_SIZE, + PARAMS_ML_DSA_87_S2_SIZE, PARAMS_ML_DSA_87_S2_ENC_SIZE, + PARAMS_ML_DSA_87_Z_ENC_SIZE, + PARAMS_ML_DSA_87_PK_SIZE, PARAMS_ML_DSA_87_SIG_SIZE }, +#endif +#endif }; /* Number of ML-DSA parameter sets compiled in. */ #define DILITHIUM_PARAMS_CNT \ @@ -271,7 +345,7 @@ static const wc_dilithium_params dilithium_params[] = { static int dilithium_get_params(int level, const wc_dilithium_params** params) { unsigned int i; - int ret = NOT_COMPILED_IN; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); for (i = 0; i < DILITHIUM_PARAMS_CNT; i++) { if (dilithium_params[i].level == level) { @@ -318,7 +392,6 @@ static int dilithium_shake256(wc_Shake* shake256, const byte* data, return ret; } -#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) /* 256-bit hash using SHAKE-256. * * FIPS 204. 8.3: H(v,d) <- SHAKE256(v,d) @@ -356,6 +429,195 @@ static int dilithium_hash256(wc_Shake* shake256, const byte* data1, return ret; } + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +/* 256-bit hash of context and message using SHAKE-256. + * + * FIPS 204. 5.2: Algorithm 2 ML-DSA.Sign(sk, M, ctx) + * ... + * 10: M' <- BytesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx) || M + * ... + * + * FIPS 204. 6.2: Algorithm 7 ML-DSA.Sign_internal(sk, M', rnd) + * ... + * 6: mu <- H(BytesToBits(tr)||M', 64)) + * ... + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] tr Public key hash. + * @param [in] trLen Length of public key hash in bytes. + * @param [in] preHash 0 when message was not hashed, + * 1 when message was hashed. + * @param [in] ctx Context of signature. + * @param [in] ctxLen Length of context of signature in bytes. + * @param [in] ctx Message to sign. + * @param [in] ctxLen Length of message to sign in bytes. + * @param [out] hash Buffer to hold hash result. + * @param [in] hashLen Number of bytes of hash to return. + * @return 0 on success. + * @return Negative on error. + */ +static int dilithium_hash256_ctx_msg(wc_Shake* shake256, const byte* tr, + byte trLen, byte preHash, const byte* ctx, byte ctxLen, const byte* msg, + word32 msgLen, byte* hash, word32 hashLen) +{ + int ret; + byte prefix[2]; + + prefix[0] = preHash; + prefix[1] = ctxLen; + + /* Initialize SHAKE-256 operation. */ + ret = wc_InitShake256(shake256, NULL, INVALID_DEVID); + if (ret == 0) { + /* Update with public key hash. */ + ret = wc_Shake256_Update(shake256, tr, trLen); + } + if (ret == 0) { + /* Update with context prefix - 0 | ctxLen. */ + ret = wc_Shake256_Update(shake256, prefix, (word32)sizeof(prefix)); + } + if (ret == 0) { + /* Update with context. */ + ret = wc_Shake256_Update(shake256, ctx, ctxLen); + } + if (ret == 0) { + /* Update with message. */ + ret = wc_Shake256_Update(shake256, msg, msgLen); + } + if (ret == 0) { + /* Compute hash of data. */ + ret = wc_Shake256_Final(shake256, hash, hashLen); + } + + return ret; +} + +/* Get the OID for the digest hash. + * + * @param [in] hash Hash algorithm. + * @param [out] oidBuffer Buffer to hold OID. + * @param [out] oidLen Length of OID in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG if hash algorithm not known. + */ +static int dilithium_get_hash_oid(int hash, byte* oidBuffer, word32* oidLen) +{ + int ret = 0; + const byte* oid; + +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 + + oid = OidFromId(wc_HashGetOID((enum wc_HashType)hash), oidHashType, oidLen); + if ((oid != NULL) && (*oidLen <= DILITHIUM_HASH_OID_LEN - 2)) { +#ifndef WOLFSSL_DILITHIUM_REVERSE_HASH_OID + oidBuffer[0] = 0x06; /* ObjectID */ + oidBuffer[1] = *oidLen; /* ObjectID */ + oidBuffer += 2; + XMEMCPY(oidBuffer, oid, *oidLen); +#else + int i; + for (i = (int)*oidLen - 1; i >= 0; i--) { + *(oidBuffer++) = oid[i]; + } + *(oidBuffer++) = *oidLen; /* ObjectID */ + * oidBuffer = 0x06; /* ObjectID */ +#endif + *oidLen += 2; + } + else { + ret = BAD_FUNC_ARG; + } + +#else + + *oidLen = DILITHIUM_HASH_OID_LEN; +#ifndef NO_SHA256 + if (hash == WC_HASH_TYPE_SHA256) { + static byte sha256Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01 + }; + oid = sha256Oid; + } + else +#endif +#ifdef WOLFSSL_SHA384 + if (hash == WC_HASH_TYPE_SHA384) { + static byte sha384Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02 + }; + oid = sha384Oid; + } + else +#endif +#ifdef WOLFSSL_SHA512 + if (hash == WC_HASH_TYPE_SHA512) { + static byte sha512Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03 + }; + oid = sha512Oid; + } + else +#ifndef WOLFSSL_NOSHA512_256 + if (hash == WC_HASH_TYPE_SHA512_256) { + static byte sha512_256Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06 + }; + oid = sha512_256Oid; + } + else +#endif +#endif + if (hash == WC_HASH_TYPE_SHAKE128) { + static byte shake128Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0B + }; + oid = shake128Oid; + } + else if (hash == WC_HASH_TYPE_SHAKE256) { + static byte shake256Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0C + }; + oid = shake256Oid; + } + else if (hash == WC_HASH_TYPE_SHA3_256) { + static byte sha3_256Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08 + }; + oid = sha3_256Oid; + } + else if (hash == WC_HASH_TYPE_SHA3_384) { + static byte sha3_384Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x09 + }; + oid = sha3_384Oid; + } + else if (hash == WC_HASH_TYPE_SHA3_512) { + static byte sha3_512Oid[DILITHIUM_HASH_OID_LEN] = { + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0A + }; + oid = sha3_512Oid; + } + else { + oid = NULL; + ret = BAD_FUNC_ARG; + } + + if ((oid != NULL) && (*oidLen <= DILITHIUM_HASH_OID_LEN)) { +#ifndef WOLFSSL_DILITHIUM_REVERSE_HASH_OID + XMEMCPY(oidBuffer, oid, *oidLen); +#else + int i; + for (i = (int)*oidLen - 1; i >= 0; i--) { + *(oidBuffer++) = oid[i]; + } +#endif + } +#endif + + return ret; +} #endif #ifndef WOLFSSL_DILITHIUM_SMALL @@ -710,13 +972,13 @@ static void dilithium_vec_decode_eta_bits(const byte* p, byte eta, sword32* s, * 2: r0 <- r+ mod +/- 2^d * 3: return ((r+ - r0) / 2^d, r0) * - * FIPS 204. 8.2: Algorithm 18 skEncode(rho, K, tr, s1, s2, t0) + * FIPS 204. 7.2: Algorithm 24 skEncode(rho, K, tr, s1, s2, t0) * ... * 8: for i form 0 to k - 1 do * 9: sk <- sk || BitPack(t0[i], s^(d-1) - 1, 2^(d-1)) * 10: end for * - * FIPS 204. 8.2: Algorithm 16 pkEncode(rho, t1) + * FIPS 204. 7.2: Algorithm 22 pkEncode(rho, t1) * ... * 2: for i from 0 to k - 1 do * 3: pk <- pk || SimpleBitPack(t1[i], 2^bitlen(q-1) - d - 1) @@ -732,9 +994,9 @@ static void dilithium_vec_encode_t0_t1(sword32* t, byte d, byte* t0, byte* t1) unsigned int i; unsigned int j; - /* Alg 18, Step 8 and Alg 16, Step 2. For each polynomial of vector. */ + /* Alg 24, Step 8 and Alg 22, Step 2. For each polynomial of vector. */ for (i = 0; i < d; i++) { - /* Alg 18, Step 9 and Alg 16, Step 3. + /* Alg 24, Step 9 and Alg 22, Step 3. * Do all polynomial values - 8 at a time. */ for (j = 0; j < DILITHIUM_N; j += 8) { /* Take 8 values of t and take top bits and make positive. */ @@ -1674,43 +1936,24 @@ static void dilithium_vec_encode_w1(const sword32* w1, byte k, sword32 gamma2, * @param [in, out] shake128 SHAKE-128 object. * @param [in] seed Seed to hash to generate values. * @param [out] a Polynomial. + * @param [in] h Buffer to hold hashes. * @return 0 on success. - * @return MEMORY_E when dynamic memory allocation fails. * @return Negative on hash error. */ -static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, - byte* key_h) +static int dilithium_rej_ntt_poly_ex(wc_Shake* shake128, byte* seed, sword32* a, + byte* h) { -#ifdef WOLFSSL_DILITHIUM_SMALL int ret = 0; +#ifdef WOLFSSL_DILITHIUM_SMALL int j = 0; -#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) - byte* h = NULL; -#else - byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; -#endif - - (void)key_h; - -#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - h = key_h; -#elif defined(WOLFSSL_SMALL_STACK) - h = (byte*)XMALLOC(DILITHIUM_REJ_NTT_POLY_H_SIZE, NULL, - DYNAMIC_TYPE_DILITHIUM); - if (h == NULL) { - ret = MEMORY_E; - } -#endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC */ - if (ret == 0) { - #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) - /* Reading 4 bytes for 3 so need to set 1 past for last read. */ - h[DILITHIUM_GEN_A_BLOCK_BYTES] = 0; - #endif +#if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) + /* Reading 4 bytes for 3 so need to set 1 past for last read. */ + h[DILITHIUM_GEN_A_BLOCK_BYTES] = 0; +#endif - /* Initialize SHAKE-128 object for new hash. */ - ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); - } + /* Initialize SHAKE-128 object for new hash. */ + ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); if (ret == 0) { /* Absorb the seed. */ ret = wc_Shake128_Absorb(shake128, seed, DILITHIUM_GEN_A_SEED_SZ); @@ -1746,39 +1989,14 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, } } } - -#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) - XFREE(h, NULL, DYNAMIC_TYPE_DILITHIUM); -#endif - return ret; #else - int ret = 0; unsigned int j = 0; unsigned int c; -#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) - byte* h = NULL; -#else - byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; -#endif - - (void)key_h; - -#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - h = key_h; -#elif defined(WOLFSSL_SMALL_STACK) - h = (byte*)XMALLOC(DILITHIUM_REJ_NTT_POLY_H_SIZE, NULL, - DYNAMIC_TYPE_DILITHIUM); - if (h == NULL) { - ret = MEMORY_E; - } -#endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC */ - if (ret == 0) { - /* Generate enough SHAKE-128 output blocks to give high probability of - * being able to get 256 valid 3-byte, 23-bit values from it. */ - ret = dilithium_squeeze128(shake128, seed, DILITHIUM_GEN_A_SEED_SZ, h, - DILITHIUM_GEN_A_NBLOCKS); - } + /* Generate enough SHAKE-128 output blocks to give high probability of + * being able to get 256 valid 3-byte, 23-bit values from it. */ + ret = dilithium_squeeze128(shake128, seed, DILITHIUM_GEN_A_SEED_SZ, h, + DILITHIUM_GEN_A_NBLOCKS); if (ret == 0) { #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) /* Reading 4 bytes for 3 so need to set 1 past for last read. */ @@ -1786,7 +2004,7 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, #endif /* Use the first 256 triplets and know we won't exceed required. */ -#ifdef WOLFSSL_DILITHIUM_NO_LARGE_CODE + #ifdef WOLFSSL_DILITHIUM_NO_LARGE_CODE for (c = 0; c < (DILITHIUM_N - 1) * 3; c += 3) { #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) /* Load 32-bit value and mask out 23 bits. */ @@ -1822,7 +2040,7 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, } } } -#else + #else /* Do 15 bytes at a time: 255 * 3 / 15 = 51 */ for (c = 0; c < DILITHIUM_N * 3; c += 24) { #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT == 0) @@ -1919,7 +2137,7 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, } } } -#endif + #endif /* Keep generating more blocks and using triplets until we have enough. */ while (j < DILITHIUM_N) { @@ -1952,15 +2170,60 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, } } } - -#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) - XFREE(h, NULL, DYNAMIC_TYPE_DILITHIUM); #endif + return ret; +} + +#if (!defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) && \ + !defined(WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM)) || \ + defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ + (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) +/* Generate a random polynomial by rejection. + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] seed Seed to hash to generate values. + * @param [out] a Polynomial. + * @param [in] heap Dynamic memory hint. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Negative on hash error. + */ +static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, + void* heap) +{ + int ret; +#if defined(WOLFSSL_SMALL_STACK) + byte* h = NULL; +#else + byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; #endif + + (void)heap; + +#if defined(WOLFSSL_SMALL_STACK) + h = (byte*)XMALLOC(DILITHIUM_REJ_NTT_POLY_H_SIZE, heap, + DYNAMIC_TYPE_DILITHIUM); + if (h == NULL) { + ret = MEMORY_E; + } +#endif + + ret = dilithium_rej_ntt_poly_ex(shake128, seed, a, h); + +#if defined(WOLFSSL_SMALL_STACK) + XFREE(h, heap, DYNAMIC_TYPE_DILITHIUM); +#endif + + return ret; } +#endif -#if !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) || \ +#if (!defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY) && \ + !defined(WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM)) || \ defined(WOLFSSL_DILITHIUM_CHECK_KEY) || \ (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ @@ -1983,11 +2246,12 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, * @param [in] k First dimension of matrix a. * @param [in] l Second dimension of matrix a. * @param [out] a Matrix of polynomials. + * @param [in] heap Dynamic memory hint. * @return 0 on success. * @return Negative on hash error. */ static int dilithium_expand_a(wc_Shake* shake128, const byte* pub_seed, byte k, - byte l, sword32* a) + byte l, sword32* a, void* heap) { int ret = 0; byte r; @@ -2005,7 +2269,7 @@ static int dilithium_expand_a(wc_Shake* shake128, const byte* pub_seed, byte k, /* Put s into buffer to be hashed. */ seed[DILITHIUM_PUB_SEED_SZ + 0] = s; /* Step 3: Create polynomial from hashing seed. */ - ret = dilithium_rej_ntt_poly(shake128, seed, a, NULL); + ret = dilithium_rej_ntt_poly(shake128, seed, a, heap); /* Next polynomial. */ a += DILITHIUM_N; } @@ -2031,7 +2295,7 @@ static int dilithium_expand_a(wc_Shake* shake128, const byte* pub_seed, byte k, #define DILITHIUM_COEFF_S_VALID_ETA2(b) \ ((b) < DILITHIUM_ETA_2_MOD) -static const byte dilithium_coeff_eta2[] = { +static const char dilithium_coeff_eta2[] = { 2, 1, 0, -1, -2, 2, 1, 0, -1, -2, 2, 1, 0, -1, -2 @@ -2514,6 +2778,7 @@ static int dilithium_vec_expand_mask(wc_Shake* shake256, byte* seed, #endif #if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + /* Expand commit to a polynomial. * * FIPS 204. 8.3: Algorithm 23 SampleInBall(rho) @@ -2530,48 +2795,41 @@ static int dilithium_vec_expand_mask(wc_Shake* shake256, byte* seed, * 11: end for * 12: return c * - * @param [in] shake256 SHAKE-256 object. - * @param [in] seed Buffer containing seed to expand. - * @param [in] tau Number of +/- 1s in polynomial. - * @param [out] c Commit polynomial. - * @param [in] key_block Memory to use for block from key. + * @param [in] shake256 SHAKE-256 object. + * @param [in] seed Buffer containing seed to expand. + * @param [in] seedLen Length of seed in bytes. + * @param [in] tau Number of +/- 1s in polynomial. + * @param [out] c Commit polynomial. + * @param [in] block Memory to use for block from key. * @return 0 on success. - * @return MEMORY_E when dynamic memory allocation fails. * @return Negative on hash error. */ -static int dilithium_sample_in_ball(wc_Shake* shake256, const byte* seed, - byte tau, sword32* c, byte* key_block) +static int dilithium_sample_in_ball_ex(int level, wc_Shake* shake256, + const byte* seed, word32 seedLen, byte tau, sword32* c, byte* block) { int ret = 0; unsigned int k; unsigned int i; unsigned int s; -#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) - byte* block = NULL; -#else - byte block[DILITHIUM_GEN_C_BLOCK_BYTES]; -#endif byte signs[DILITHIUM_SIGN_BYTES]; - (void)key_block; - -#ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - block = key_block; -#elif defined(WOLFSSL_SMALL_STACK) - block = (byte*)XMALLOC(DILITHIUM_GEN_C_BLOCK_BYTES, NULL, - DYNAMIC_TYPE_DILITHIUM); - if (block == NULL) { - ret = MEMORY_E; - } -#endif - if (ret == 0) { /* Set polynomial to all zeros. */ XMEMSET(c, 0, DILITHIUM_POLY_SIZE); /* Generate a block of data from seed. */ - ret = dilithium_shake256(shake256, seed, DILITHIUM_SEED_SZ, block, - DILITHIUM_GEN_C_BLOCK_BYTES); +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + if (level >= WC_ML_DSA_DRAFT) { + ret = dilithium_shake256(shake256, seed, DILITHIUM_SEED_SZ, block, + DILITHIUM_GEN_C_BLOCK_BYTES); + } + else +#endif + { + (void)level; + ret = dilithium_shake256(shake256, seed, seedLen, block, + DILITHIUM_GEN_C_BLOCK_BYTES); + } } if (ret == 0) { /* Copy first 8 bytes of first hash block as random sign bits. */ @@ -2609,26 +2867,72 @@ static int dilithium_sample_in_ball(wc_Shake* shake256, const byte* seed, s++; } -#if !defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && defined(WOLFSSL_SMALL_STACK) - XFREE(block, NULL, DYNAMIC_TYPE_DILITHIUM); -#endif return ret; } + +#if (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ + !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) || \ + (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ + !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) +/* Expand commit to a polynomial. + * + * @param [in] shake256 SHAKE-256 object. + * @param [in] seed Buffer containing seed to expand. + * @param [in] seedLen Length of seed in bytes. + * @param [in] tau Number of +/- 1s in polynomial. + * @param [out] c Commit polynomial. + * @param [in] heap Dynamic memory hint. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Negative on hash error. + */ +static int dilithium_sample_in_ball(int level, wc_Shake* shake256, + const byte* seed, word32 seedLen, byte tau, sword32* c, void* heap) +{ + int ret = 0; +#if defined(WOLFSSL_SMALL_STACK) + byte* block = NULL; +#else + byte block[DILITHIUM_GEN_C_BLOCK_BYTES]; #endif -/****************************************************************************** - * Decompose operations - ******************************************************************************/ + (void)heap; -#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) -#ifndef WOLFSSL_NO_ML_DSA_44 -/* Decompose value into high and low based on GAMMA2 being ((q-1) / 88). - * - * FIPS 204. 8.4: Algorithm 30 Decompose(r) - * 1: r+ <- r mod q - * 2: r0 <- r+ mod+/- (2 * GAMMA2) - * 3: if r+ - r0 = q - 1 then - * 4: r1 <- 0 +#if defined(WOLFSSL_SMALL_STACK) + block = (byte*)XMALLOC(DILITHIUM_GEN_C_BLOCK_BYTES, heap, + DYNAMIC_TYPE_DILITHIUM); + if (block == NULL) { + ret = MEMORY_E; + } +#endif + + if (ret == 0) { + ret = dilithium_sample_in_ball_ex(level, shake256, seed, seedLen, tau, + c, block); + } + +#if defined(WOLFSSL_SMALL_STACK) + XFREE(block, heap, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +} +#endif + +#endif + +/****************************************************************************** + * Decompose operations + ******************************************************************************/ + +#if !defined(WOLFSSL_DILITHIUM_NO_SIGN) || !defined(WOLFSSL_DILITHIUM_NO_VERIFY) +#ifndef WOLFSSL_NO_ML_DSA_44 +/* Decompose value into high and low based on GAMMA2 being ((q-1) / 88). + * + * FIPS 204. 8.4: Algorithm 30 Decompose(r) + * 1: r+ <- r mod q + * 2: r0 <- r+ mod+/- (2 * GAMMA2) + * 3: if r+ - r0 = q - 1 then + * 4: r1 <- 0 * 5: r0 <- r0 - 1 * 6: else r1 <- (r+ - r0) / (2 * GAMMA2) * 7: end if @@ -2734,7 +3038,8 @@ static void dilithium_decompose_q32(sword32 r, sword32* r0, sword32* r1) #ifndef WOLFSSL_DILITHIUM_NO_SIGN -#ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM +#if !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) || \ + defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A) /* Decompose vector of polynomials into high and low based on GAMMA2. * * @param [in] r Vector of polynomials to decompose. @@ -2825,8 +3130,7 @@ static int dilithium_check_low(const sword32* a, sword32 hi) return ret; } -#if (!defined(WOLFSSL_DILITHIUM_NO_VERIFY) && \ - !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM)) || \ +#if !defined(WOLFSSL_DILITHIUM_NO_VERIFY) || \ (!defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM)) /* Check that the values of the vector are in range. @@ -3125,11 +3429,11 @@ static int dilithium_check_hint(const byte* h, byte k, byte omega) unsigned int i; /* Skip polynomial index while count is 0. */ - while ((h[omega + o] == 0) && (o < k)) { + while ((o < k) && (h[omega + o] == 0)) { o++; } /* Check all possible hints. */ - for (i = 1; i < omega; i++) { + for (i = 1; (o < k) && (i < omega); i++) { /* Done with polynomial if index equals count of hints. */ if (i == h[omega + o]) { /* Next polynomial index while count is index. */ @@ -3143,7 +3447,7 @@ static int dilithium_check_hint(const byte* h, byte k, byte omega) } } /* Ensure the last hint is less than the current hint. */ - else if (h[i - 1] > h[i]) { + else if (h[i - 1] >= h[i]) { ret = SIG_VERIFY_E; break; } @@ -5160,27 +5464,27 @@ static void dilithium_vec_make_pos(sword32* a, byte l) /* Make a key from a random seed. * * xi is seed passed in. - * FIPS 204. 5: Algorithm 1 ML-DSA.KeyGen() - * ... - * 2: (rho, rho', K) E {0,1}256 x {0,1}512 x {0,1}256 <- H(xi, 1024) + * FIPS 204. 6.1: Algorithm 6 ML-DSA.KeyGen_internal(xi) + * 1: (rho, rho', K) E B32 x B64 x B32 <- H(xi||k||l, 1024) + * 2: * 3: A_circum <- ExpandA(rho) * 4: (s1,s2) <- ExpandS(rho') * 5: t <- NTT-1(A_circum o NTT(s1)) + s2 * 6: (t1, t0) <- Power2Round(t, d) * 7: pk <- pkEncode(rho, t1) - * 8: tr <- H(BytesToBits(pk), 512) + * 8: tr <- H(pk, 64) * 9: sk <- skEncode(rho, K, tr, s1, s2, t0) * 10: return (pk, sk) * - * FIPS 204. 8.2: Algorithm 16 pkEncode(rho, t1) - * 1: pk <- BitsToBytes(rho) - * 2: for i from 0 to l - 1 do + * FIPS 204. 7.2: Algorithm 22 pkEncode(rho, t1) + * 1: pk <- rho + * 2: for i from 0 to k - 1 do * 3: pk <- pk || SimpleBitPack(t1[i], 2^(bitlen(q-1)-d) - 1) * 4: end for * 5: return pk * - * FIPS 204. 8.2: Algorithm 18 skEncode(rho, K, tr, s, s2, t0) - * 1: sk <- BitsToBytes(rho) || BitsToBytes(K) || BitsToBytes(tr) + * FIPS 204. 7.2: Algorithm 24 skEncode(rho, K, tr, s, s2, t0) + * 1: sk <- rho || K || tr * 2: for i from 0 to l - 1 do * 3: sk <- sk || BitPack(s1[i], eta, eta) * 4: end for @@ -5202,6 +5506,7 @@ static void dilithium_vec_make_pos(sword32* a, byte l) */ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) { +#ifndef WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM int ret = 0; const wc_dilithium_params* params = key->params; sword32* a = NULL; @@ -5209,22 +5514,28 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) sword32* s2 = NULL; sword32* t = NULL; byte* pub_seed = key->k; + byte kl[2]; /* Allocate memory for large intermediates. */ #ifdef WC_DILITHIUM_CACHE_MATRIX_A +#ifndef WC_DILITHIUM_FIXED_ARRAY if (key->a == NULL) { - key->a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + key->a = (sword32*)XMALLOC(params->aSz, key->heap, + DYNAMIC_TYPE_DILITHIUM); if (key->a == NULL) { ret = MEMORY_E; } } +#endif if (ret == 0) { a = key->a; } #endif #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->s1 == NULL)) { - key->s1 = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + key->s1 = (sword32*)XMALLOC(params->aSz, key->heap, + DYNAMIC_TYPE_DILITHIUM); if (key->s1 == NULL) { ret = MEMORY_E; } @@ -5233,6 +5544,7 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) key->t0 = key->s2 + params->s2Sz / sizeof(*s2); } } +#endif if (ret == 0) { s1 = key->s1; s2 = key->s2; @@ -5248,7 +5560,7 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) #endif /* s1, s2, t, a */ - s1 = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + s1 = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (s1 == NULL) { ret = MEMORY_E; } @@ -5256,25 +5568,40 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) s2 = s1 + params->s1Sz / sizeof(*s1); t = s2 + params->s2Sz / sizeof(*s2); #ifndef WC_DILITHIUM_CACHE_MATRIX_A - a = t + params->s2Sz / sizeof(*s2); + a = t + params->s2Sz / sizeof(*t); #endif } } #endif if (ret == 0) { - /* Step 2: Create public seed, private seed and K from seed. - * Step 9; Alg 18, Step 1: Public seed is placed into private key. */ - ret = dilithium_shake256(&key->shake, seed, DILITHIUM_SEED_SZ, pub_seed, - DILITHIUM_SEEDS_SZ); +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + if (key->params->level >= WC_ML_DSA_DRAFT) { + /* Step 2: Create public seed, private seed and K from seed. + * Step 9; Alg 18, Step 1: Public seed is placed into private key. + */ + ret = dilithium_shake256(&key->shake, seed, DILITHIUM_SEED_SZ, + pub_seed, DILITHIUM_SEEDS_SZ); + } + else +#endif + { + kl[0] = params->k; + kl[1] = params->l; + /* Step 1: Create public seed, private seed and K from seed. + * Step 9; Alg 24, Step 1: Public seed is placed into private key. + */ + ret = dilithium_hash256(&key->shake, seed, DILITHIUM_SEED_SZ, kl, 2, + pub_seed, DILITHIUM_SEEDS_SZ); + } } if (ret == 0) { - /* Step 7; Alg 16 Step 1: Copy public seed into public key. */ + /* Step 7; Alg 22 Step 1: Copy public seed into public key. */ XMEMCPY(key->p, pub_seed, DILITHIUM_PUB_SEED_SZ); /* Step 3: Expand public seed into a matrix of polynomials. */ ret = dilithium_expand_a(&key->shake, pub_seed, params->k, params->l, - a); + a, key->heap); } if (ret == 0) { byte* priv_seed = key->k + DILITHIUM_PUB_SEED_SZ; @@ -5293,9 +5620,9 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) /* Step 9: Move k down to after public seed. */ XMEMCPY(k, k + DILITHIUM_PRIV_SEED_SZ, DILITHIUM_K_SZ); - /* Step 9. Alg 18 Steps 2-4: Encode s1 into private key. */ + /* Step 9. Alg 24 Steps 2-4: Encode s1 into private key. */ dilthium_vec_encode_eta_bits(s1, params->l, params->eta, s1p); - /* Step 9. Alg 18 Steps 5-7: Encode s2 into private key. */ + /* Step 9. Alg 24 Steps 5-7: Encode s2 into private key. */ dilthium_vec_encode_eta_bits(s2, params->k, params->eta, s2p); /* Step 5: t <- NTT-1(A_circum o NTT(s1)) + s2 */ @@ -5306,11 +5633,11 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) /* Make positive for decomposing. */ dilithium_vec_make_pos(t, params->k); - /* Step 6, Step 7, Step 9. Alg 16 Steps 2-4, Alg 18 Steps 8-10. + /* Step 6, Step 7, Step 9. Alg 22 Steps 2-4, Alg 24 Steps 8-10. * Decompose t in t0 and t1 and encode into public and private key. */ dilithium_vec_encode_t0_t1(t, params->k, t0, t1); - /* Step 8. Alg 18, Step 1: Hash public key into private key. */ + /* Step 8. Alg 24, Step 1: Hash public key into private key. */ ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, DILITHIUM_TR_SZ); } @@ -5333,16 +5660,239 @@ static int dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) } #ifndef WC_DILITHIUM_CACHE_PRIV_VECTORS - XFREE(s1, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(s1, key->heap, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +#else + int ret = 0; + const wc_dilithium_params* params = key->params; + sword32* a = NULL; + sword32* s1 = NULL; + sword32* s2 = NULL; + sword32* t = NULL; +#ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + sword64* t64 = NULL; +#endif + byte* h = NULL; + byte* pub_seed = key->k; + unsigned int r; + unsigned int s; + byte kl[2]; + + /* Allocate memory for large intermediates. */ + if (ret == 0) { + unsigned int allocSz; + + /* s1-l, s2-k, t-k, a-1 */ + allocSz = params->s1Sz + params->s2Sz + params->s2Sz + + DILITHIUM_REJ_NTT_POLY_H_SIZE + DILITHIUM_POLY_SIZE; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + /* t64 */ + allocSz += DILITHIUM_POLY_SIZE * 2; + #endif + s1 = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); + if (s1 == NULL) { + ret = MEMORY_E; + } + else { + s2 = s1 + params->s1Sz / sizeof(*s1); + t = s2 + params->s2Sz / sizeof(*s2); + h = (byte*)(t + params->s2Sz / sizeof(*t)); + a = (sword32*)(h + DILITHIUM_REJ_NTT_POLY_H_SIZE); + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = (sword64*)(a + DILITHIUM_N); + #endif + } + } + + if (ret == 0) { +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + if (key->params->level >= WC_ML_DSA_DRAFT) { + /* Step 2: Create public seed, private seed and K from seed. + * Step 9; Alg 18, Step 1: Public seed is placed into private key. + */ + ret = dilithium_shake256(&key->shake, seed, DILITHIUM_SEED_SZ, + pub_seed, DILITHIUM_SEEDS_SZ); + } + else #endif + { + kl[0] = params->k; + kl[1] = params->l; + /* Step 1: Create public seed, private seed and K from seed. + * Step 9; Alg 24, Step 1: Public seed is placed into private key. + */ + ret = dilithium_hash256(&key->shake, seed, DILITHIUM_SEED_SZ, kl, 2, + pub_seed, DILITHIUM_SEEDS_SZ); + } + } + if (ret == 0) { + byte* priv_seed = key->k + DILITHIUM_PUB_SEED_SZ; + + /* Step 7; Alg 22 Step 1: Copy public seed into public key. */ + XMEMCPY(key->p, pub_seed, DILITHIUM_PUB_SEED_SZ); + + /* Step 4: Expand private seed into to vectors of polynomials. */ + ret = dilithium_expand_s(&key->shake, priv_seed, params->eta, s1, + params->l, s2, params->k); + } + if (ret == 0) { + byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + byte* tr = k + DILITHIUM_K_SZ; + byte* s1p = tr + DILITHIUM_TR_SZ; + byte* s2p = s1p + params->s1EncSz; + byte* t0 = s2p + params->s2EncSz; + byte* t1 = key->p + DILITHIUM_PUB_SEED_SZ; + byte aseed[DILITHIUM_GEN_A_SEED_SZ]; + sword32* s2t = s2; + sword32* tt = t; + + /* Step 9: Move k down to after public seed. */ + XMEMCPY(k, k + DILITHIUM_PRIV_SEED_SZ, DILITHIUM_K_SZ); + /* Step 9. Alg 24 Steps 2-4: Encode s1 into private key. */ + dilthium_vec_encode_eta_bits(s1, params->l, params->eta, s1p); + /* Step 9. Alg 24 Steps 5-7: Encode s2 into private key. */ + dilthium_vec_encode_eta_bits(s2, params->k, params->eta, s2p); + + /* Step 5: NTT(s1) */ + dilithium_vec_ntt_small(s1, params->l); + /* Step 5: t <- NTT-1(A_circum o NTT(s1)) + s2 */ + XMEMCPY(aseed, pub_seed, DILITHIUM_PUB_SEED_SZ); + for (r = 0; (ret == 0) && (r < params->k); r++) { + sword32* s1t = s1; + unsigned int e; + + /* Put r/i into buffer to be hashed. */ + aseed[DILITHIUM_PUB_SEED_SZ + 1] = r; + for (s = 0; (ret == 0) && (s < params->l); s++) { + + /* Put s into buffer to be hashed. */ + aseed[DILITHIUM_PUB_SEED_SZ + 0] = s; + /* Step 3: Expand public seed into a matrix of polynomials. */ + ret = dilithium_rej_ntt_poly_ex(&key->shake, aseed, a, h); + if (ret != 0) { + break; + } + /* Matrix multiply. */ + #ifndef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + if (s == 0) { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + tt[e] = dilithium_mont_red((sword64)a[e] * s1t[e]); + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + tt[e+0] = dilithium_mont_red((sword64)a[e+0]*s1t[e+0]); + tt[e+1] = dilithium_mont_red((sword64)a[e+1]*s1t[e+1]); + tt[e+2] = dilithium_mont_red((sword64)a[e+2]*s1t[e+2]); + tt[e+3] = dilithium_mont_red((sword64)a[e+3]*s1t[e+3]); + tt[e+4] = dilithium_mont_red((sword64)a[e+4]*s1t[e+4]); + tt[e+5] = dilithium_mont_red((sword64)a[e+5]*s1t[e+5]); + tt[e+6] = dilithium_mont_red((sword64)a[e+6]*s1t[e+6]); + tt[e+7] = dilithium_mont_red((sword64)a[e+7]*s1t[e+7]); + } + #endif + } + else { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + tt[e] += dilithium_mont_red((sword64)a[e] * s1t[e]); + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + tt[e+0] += dilithium_mont_red((sword64)a[e+0]*s1t[e+0]); + tt[e+1] += dilithium_mont_red((sword64)a[e+1]*s1t[e+1]); + tt[e+2] += dilithium_mont_red((sword64)a[e+2]*s1t[e+2]); + tt[e+3] += dilithium_mont_red((sword64)a[e+3]*s1t[e+3]); + tt[e+4] += dilithium_mont_red((sword64)a[e+4]*s1t[e+4]); + tt[e+5] += dilithium_mont_red((sword64)a[e+5]*s1t[e+5]); + tt[e+6] += dilithium_mont_red((sword64)a[e+6]*s1t[e+6]); + tt[e+7] += dilithium_mont_red((sword64)a[e+7]*s1t[e+7]); + } + #endif + } + #else + if (s == 0) { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] = (sword64)a[e] * s1t[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] = (sword64)a[e+0] * s1t[e+0]; + t64[e+1] = (sword64)a[e+1] * s1t[e+1]; + t64[e+2] = (sword64)a[e+2] * s1t[e+2]; + t64[e+3] = (sword64)a[e+3] * s1t[e+3]; + t64[e+4] = (sword64)a[e+4] * s1t[e+4]; + t64[e+5] = (sword64)a[e+5] * s1t[e+5]; + t64[e+6] = (sword64)a[e+6] * s1t[e+6]; + t64[e+7] = (sword64)a[e+7] * s1t[e+7]; + } + #endif + } + else { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] += (sword64)a[e] * s1t[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] += (sword64)a[e+0] * s1t[e+0]; + t64[e+1] += (sword64)a[e+1] * s1t[e+1]; + t64[e+2] += (sword64)a[e+2] * s1t[e+2]; + t64[e+3] += (sword64)a[e+3] * s1t[e+3]; + t64[e+4] += (sword64)a[e+4] * s1t[e+4]; + t64[e+5] += (sword64)a[e+5] * s1t[e+5]; + t64[e+6] += (sword64)a[e+6] * s1t[e+6]; + t64[e+7] += (sword64)a[e+7] * s1t[e+7]; + } + #endif + } + #endif + /* Next polynomial. */ + s1t += DILITHIUM_N; + } + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + for (e = 0; e < DILITHIUM_N; e++) { + tt[e] = dilithium_mont_red(t64[e]); + } + #endif + dilithium_invntt(tt); + dilithium_add(tt, s2t); + /* Make positive for decomposing. */ + dilithium_make_pos(tt); + + tt += DILITHIUM_N; + s2t += DILITHIUM_N; + } + + /* Step 6, Step 7, Step 9. Alg 22 Steps 2-4, Alg 24 Steps 8-10. + * Decompose t in t0 and t1 and encode into public and private key. + */ + dilithium_vec_encode_t0_t1(t, params->k, t0, t1); + /* Step 8. Alg 24, Step 1: Hash public key into private key. */ + ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if (ret == 0) { + /* Public key and private key are available. */ + key->prvKeySet = 1; + key->pubKeySet = 1; + } + + XFREE(s1, key->heap, DYNAMIC_TYPE_DILITHIUM); return ret; +#endif } /* Make a key from a random seed. * - * FIPS 204. 5: Algorithm 1 ML-DSA.KeyGen() - * 1: xi <- {0,1}256 [Choose random seed] - * ... + * FIPS 204. 5.1: Algorithm 1 ML-DSA.KeyGen() + * 1: xi <- B32 [Choose random seed] + * 2: if xi = NULL then + * 3: return falsam + * 4: end if + * 5: return ML-DSA.KeyGen_internal(xi) * * @param [in, out] key Dilithium key. * @param [in] rng Random number generator. @@ -5355,10 +5905,11 @@ static int dilithium_make_key(dilithium_key* key, WC_RNG* rng) int ret; byte seed[DILITHIUM_SEED_SZ]; - /* Generate a 256-bit random seed. */ + /* Step 1: Generate a 32 byte random seed. */ ret = wc_RNG_GenerateBlock(rng, seed, DILITHIUM_SEED_SZ); + /* Step 2: Check for error. */ if (ret == 0) { - /* Make key with random seed. */ + /* Step 5: Make key with random seed. */ ret = wc_dilithium_make_key_from_seed(key, seed); } @@ -5369,10 +5920,11 @@ static int dilithium_make_key(dilithium_key* key, WC_RNG* rng) #ifndef WOLFSSL_DILITHIUM_NO_SIGN #if !defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) || \ + defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC) || \ defined(WC_DILITHIUM_CACHE_PRIV_VECTORS) /* Decode, from private key, and NTT private key vectors s1, s2, and t0. * - * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * FIPS 204. 6: Algorithm 2 ML-DSA.Sign(sk, M) * 1: (rho, K, tr, s1, s2, t0) <- skDecode(sk) * 2: s1_circum <- NTT(s1) * 3: s2_circum <- NTT(s2) @@ -5415,7 +5967,13 @@ static void dilithium_make_priv_vecs(dilithium_key* key, sword32* s1, /* Sign a message with the key and a seed. * - * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * FIPS 204. 5.2: Algorithm 2 ML-DSA.sign(sk, M, ctx) + * ... + * 10: M' <- ByyesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx) || M + * ... + * + * FIPS 204. 6: Algorithm 2 ML-DSA.Sign(sk, M) * 1: (rho, K, tr, s1, s2, t0) <- skDecode(sk) * 2: s1_circum <- NTT(s1) * 3: s2_circum <- NTT(s2) @@ -5454,26 +6012,25 @@ static void dilithium_make_priv_vecs(dilithium_key* key, sword32* s1, * 33: return sigma * * @param [in, out] key Dilithium key. - * @param [in, out] seed Random seed. - * @param [in] msg Message data to sign. - * @param [in] msgLen Length of message data in bytes. + * @param [in] seedMu Random seed || mu. * @param [out] sig Buffer to hold signature. * @param [in, out] sigLen On in, length of buffer in bytes. * On out, the length of the signature in bytes. * @return 0 on success. + * @return BAD_FUNC_ARG when context length is greater than 255. * @return BUFFER_E when the signature buffer is too small. * @return MEMORY_E when memory allocation fails. * @return Other negative when an error occurs. */ -static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, - const byte* msg, word32 msgLen, byte* sig, word32 *sigLen) +static int dilithium_sign_with_seed_mu(dilithium_key* key, + const byte* seedMu, byte* sig, word32 *sigLen) { #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM int ret = 0; const wc_dilithium_params* params = key->params; - byte* pub_seed = key->k; - byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; - byte* tr = k + DILITHIUM_K_SZ; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* mu = seedMu + DILITHIUM_RND_SZ; sword32* a = NULL; sword32* s1 = NULL; sword32* s2 = NULL; @@ -5484,13 +6041,11 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, sword32* c = NULL; sword32* z = NULL; sword32* ct0 = NULL; - byte data[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; - byte* mu = data + DILITHIUM_RND_SZ; byte priv_rand_seed[DILITHIUM_Y_SEED_SZ]; - byte* h = sig + params->lambda * 2 + params->zEncSz; + byte* h = sig + params->lambda / 4 + params->zEncSz; /* Check the signature buffer isn't too small. */ - if ((ret == 0) && (*sigLen < params->sigSz)) { + if (*sigLen < params->sigSz) { ret = BUFFER_E; } if (ret == 0) { @@ -5500,19 +6055,23 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, /* Allocate memory for large intermediates. */ #ifdef WC_DILITHIUM_CACHE_MATRIX_A +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->a == NULL)) { - a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (a == NULL) { ret = MEMORY_E; } } +#endif if (ret == 0) { a = key->a; } #endif #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->s1 == NULL)) { - key->s1 = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + key->s1 = (sword32*)XMALLOC(params->aSz, key->heap, + DYNAMIC_TYPE_DILITHIUM); if (key->s1 == NULL) { ret = MEMORY_E; } @@ -5521,6 +6080,7 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, key->t0 = key->s2 + params->s2Sz / sizeof(*s2); } } +#endif if (ret == 0) { s1 = key->s1; s2 = key->s2; @@ -5541,7 +6101,7 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, /* A */ allocSz += params->aSz; #endif - y = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + y = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (y == NULL) { ret = MEMORY_E; } @@ -5579,24 +6139,15 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, { /* Step 5: Create the matrix A from the public seed. */ ret = dilithium_expand_a(&key->shake, pub_seed, params->k, - params->l, a); + params->l, a, key->heap); #ifdef WC_DILITHIUM_CACHE_MATRIX_A key->aSet = (ret == 0); #endif } } - if (ret == 0) { - /* Step 6: Compute the hash of tr, public key hash, and message. */ - ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, - mu, DILITHIUM_MU_SZ); - } - if (ret == 0) { - /* Step 7: Copy random into buffer for hashing. */ - XMEMCPY(data, seed, DILITHIUM_RND_SZ); - } if (ret == 0) { /* Step 9: Compute private random using hash. */ - ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, data, + ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, seedMu, DILITHIUM_RND_SZ + DILITHIUM_MU_SZ, priv_rand_seed, DILITHIUM_PRIV_RAND_SEED_SZ); } @@ -5640,11 +6191,11 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, /* Step 15: Hash mu and encoded w1. * Step 32: Hash is stored in signature. */ ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, - w1e, params->w1EncSz, commit, 2 * params->lambda); + w1e, params->w1EncSz, commit, params->lambda / 4); if (ret == 0) { /* Step 17: Compute c from first 256 bits of commit. */ - ret = dilithium_sample_in_ball(&key->shake, commit, - params->tau, c, NULL); + ret = dilithium_sample_in_ball(params->level, &key->shake, + commit, params->lambda / 4, params->tau, c, key->heap); } if (ret == 0) { sword32 hi; @@ -5708,23 +6259,24 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, while ((ret == 0) && (!valid)); } if (ret == 0) { - byte* ze = sig + params->lambda * 2; + byte* ze = sig + params->lambda / 4; /* Step 32: Encode z into signature. * Commit (c) and h already encoded into signature. */ dilithium_vec_encode_gamma1(z, params->l, params->gamma1_bits, ze); } - XFREE(y, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(y, key->heap, DYNAMIC_TYPE_DILITHIUM); return ret; #else int ret = 0; const wc_dilithium_params* params = key->params; - byte* pub_seed = key->k; - byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; - byte* tr = k + DILITHIUM_K_SZ; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; const byte* s1p = tr + DILITHIUM_TR_SZ; const byte* s2p = s1p + params->s1EncSz; const byte* t0p = s2p + params->s2EncSz; + const byte* mu = seedMu + DILITHIUM_RND_SZ; sword32* a = NULL; sword32* s1 = NULL; sword32* s2 = NULL; @@ -5736,10 +6288,16 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, sword32* c = NULL; sword32* z = NULL; sword32* ct0 = NULL; - byte data[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; - byte* mu = data + DILITHIUM_RND_SZ; +#ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + sword64* t64 = NULL; +#endif + byte* blocks = NULL; byte priv_rand_seed[DILITHIUM_Y_SEED_SZ]; - byte* h = sig + params->lambda * 2 + params->zEncSz; + byte* h = sig + params->lambda / 4 + params->zEncSz; +#ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + byte maxK = (byte)min(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A, + params->k); +#endif /* Check the signature buffer isn't too small. */ if ((ret == 0) && (*sigLen < params->sigSz)) { @@ -5754,58 +6312,101 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, if (ret == 0) { unsigned int allocSz; - /* y-l, w0-k, w1-k, c-1, s1-1, A-1 */ - allocSz = params->s1Sz + params->s2Sz + params->s2Sz + + /* y-l, w0-k, w1-k, blocks, c-1, z-1, A-1 */ + allocSz = params->s1Sz + params->s2Sz + params->s2Sz + + DILITHIUM_REJ_NTT_POLY_H_SIZE + DILITHIUM_POLY_SIZE + DILITHIUM_POLY_SIZE + DILITHIUM_POLY_SIZE; - y = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC + allocSz += params->s1Sz + params->s2Sz + params->s2Sz; + #elif defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A) + allocSz += maxK * params->l * DILITHIUM_POLY_SIZE; + #endif + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + allocSz += DILITHIUM_POLY_SIZE * 2; + #endif + y = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (y == NULL) { ret = MEMORY_E; } else { - w0 = y + params->s1Sz / sizeof(*y_ntt); - w1 = w0 + params->s2Sz / sizeof(*w0); - c = w1 + params->s2Sz / sizeof(*w1); - s1 = c + DILITHIUM_N; - a = s1 + DILITHIUM_N; - s2 = s1; - t0 = s1; - ct0 = s1; - z = s1; - y_ntt = s1; + w0 = y + params->s1Sz / sizeof(*y_ntt); + w1 = w0 + params->s2Sz / sizeof(*w0); + blocks = (byte*)(w1 + params->s2Sz / sizeof(*w1)); + c = (sword32*)(blocks + DILITHIUM_REJ_NTT_POLY_H_SIZE); + z = c + DILITHIUM_N; + a = z + DILITHIUM_N; + ct0 = z; + #if defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A) + y_ntt = w0; + s1 = z; + s2 = z; + t0 = z; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = (sword64*)(a + (1 + maxK * params->l) * DILITHIUM_N); + #endif + #elif defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC) + y_ntt = z; + s1 = a + DILITHIUM_N; + s2 = s1 + params->s1Sz / sizeof(*s1); + t0 = s2 + params->s2Sz / sizeof(*s2); + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = (sword64*)(t0 + params->s2Sz / sizeof(*t0)); + #endif + #else + y_ntt = z; + s1 = z; + s2 = z; + t0 = z; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = (sword64*)(a + DILITHIUM_N); + #endif + #endif } } - if (ret == 0) { - /* Step 7: Copy random into buffer for hashing. */ - XMEMCPY(data, seed, DILITHIUM_RND_SZ); - - /* Step 6: Compute the hash of tr, public key hash, and message. */ - ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, - mu, DILITHIUM_MU_SZ); - } if (ret == 0) { /* Step 9: Compute private random using hash. */ - ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, data, + ret = dilithium_hash256(&key->shake, k, DILITHIUM_K_SZ, seedMu, DILITHIUM_RND_SZ + DILITHIUM_MU_SZ, priv_rand_seed, DILITHIUM_PRIV_RAND_SEED_SZ); } +#ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC + if (ret == 0) { + dilithium_make_priv_vecs(key, s1, s2, t0); + } +#endif +#ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + if (ret == 0) { + /* Step 5: Create the matrix A from the public seed. */ + ret = dilithium_expand_a(&key->shake, pub_seed, maxK, params->l, a, + key->heap); + } +#endif if (ret == 0) { word16 kappa = 0; int valid; /* Step 11: Start rejection sampling loop */ do { + byte aseed[DILITHIUM_GEN_A_SEED_SZ]; byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; sword32* w = w1; byte* commit = sig; byte r; byte s; - byte aseed[DILITHIUM_GEN_A_SEED_SZ]; sword32 hi; - sword32* at = a; sword32* wt = w; sword32* w0t = w0; sword32* w1t = w1; + sword32* at = a; + + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + w0t += WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A * DILITHIUM_N; + w1t += WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A * DILITHIUM_N; + wt += WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A * DILITHIUM_N; + at += WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A * params->l * + DILITHIUM_N; + #endif valid = 1; /* Step 12: Compute vector y from private random seed and kappa. */ @@ -5816,13 +6417,33 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, (1 << params->gamma1_bits) - params->beta); #endif + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + /* Step 13: NTT-1(A o NTT(y)) */ + XMEMCPY(y_ntt, y, params->s1Sz); + dilithium_vec_ntt(y_ntt, params->l); + dilithium_matrix_mul(w, a, y_ntt, maxK, params->l); + dilithium_vec_invntt(w, maxK); + /* Step 14, Step 22: Make values positive and decompose. */ + dilithium_vec_make_pos(w, maxK); + dilithium_vec_decompose(w, maxK, params->gamma2, w0, w1); + #endif /* Step 5: Create the matrix A from the public seed. */ /* Copy the seed into a buffer that has space for s and r. */ XMEMCPY(aseed, pub_seed, DILITHIUM_PUB_SEED_SZ); + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + r = WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A; + #else + r = 0; + #endif /* Alg 26. Step 1: Loop over first dimension of matrix. */ - for (r = 0; (ret == 0) && valid && (r < params->k); r++) { + for (; (ret == 0) && valid && (r < params->k); r++) { unsigned int e; sword32* yt = y; + #ifdef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC_A + sword32* y_ntt_t = z; + #else + sword32* y_ntt_t = y_ntt; + #endif /* Put r/i into buffer to be hashed. */ aseed[DILITHIUM_PUB_SEED_SZ + 1] = r; @@ -5831,29 +6452,115 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, /* Put s into buffer to be hashed. */ aseed[DILITHIUM_PUB_SEED_SZ + 0] = s; /* Alg 26. Step 3: Create polynomial from hashing seed. */ - ret = dilithium_rej_ntt_poly(&key->shake, aseed, at, - NULL); + ret = dilithium_rej_ntt_poly_ex(&key->shake, aseed, at, + blocks); if (ret != 0) { break; } - XMEMCPY(y_ntt, yt, DILITHIUM_POLY_SIZE); - dilithium_ntt(y_ntt); + XMEMCPY(y_ntt_t, yt, DILITHIUM_POLY_SIZE); + dilithium_ntt(y_ntt_t); /* Matrix multiply. */ + #ifndef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 if (s == 0) { + #ifdef WOLFSSL_DILITHIUM_SMALL for (e = 0; e < DILITHIUM_N; e++) { wt[e] = dilithium_mont_red((sword64)at[e] * - y_ntt[e]); + y_ntt_t[e]); + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + wt[e + 0] = dilithium_mont_red((sword64)at[e + 0] * + y_ntt_t[e + 0]); + wt[e + 1] = dilithium_mont_red((sword64)at[e + 1] * + y_ntt_t[e + 1]); + wt[e + 2] = dilithium_mont_red((sword64)at[e + 2] * + y_ntt_t[e + 2]); + wt[e + 3] = dilithium_mont_red((sword64)at[e + 3] * + y_ntt_t[e + 3]); + wt[e + 4] = dilithium_mont_red((sword64)at[e + 4] * + y_ntt_t[e + 4]); + wt[e + 5] = dilithium_mont_red((sword64)at[e + 5] * + y_ntt_t[e + 5]); + wt[e + 6] = dilithium_mont_red((sword64)at[e + 6] * + y_ntt_t[e + 6]); + wt[e + 7] = dilithium_mont_red((sword64)at[e + 7] * + y_ntt_t[e + 7]); } + #endif } else { + #ifdef WOLFSSL_DILITHIUM_SMALL for (e = 0; e < DILITHIUM_N; e++) { wt[e] += dilithium_mont_red((sword64)at[e] * - y_ntt[e]); + y_ntt_t[e]); + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + wt[e + 0] += dilithium_mont_red((sword64)at[e + 0] * + y_ntt_t[e + 0]); + wt[e + 1] += dilithium_mont_red((sword64)at[e + 1] * + y_ntt_t[e + 1]); + wt[e + 2] += dilithium_mont_red((sword64)at[e + 2] * + y_ntt_t[e + 2]); + wt[e + 3] += dilithium_mont_red((sword64)at[e + 3] * + y_ntt_t[e + 3]); + wt[e + 4] += dilithium_mont_red((sword64)at[e + 4] * + y_ntt_t[e + 4]); + wt[e + 5] += dilithium_mont_red((sword64)at[e + 5] * + y_ntt_t[e + 5]); + wt[e + 6] += dilithium_mont_red((sword64)at[e + 6] * + y_ntt_t[e + 6]); + wt[e + 7] += dilithium_mont_red((sword64)at[e + 7] * + y_ntt_t[e + 7]); + } + #endif + } + #else + if (s == 0) { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] = (sword64)at[e] * y_ntt_t[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] = (sword64)at[e+0] * y_ntt_t[e+0]; + t64[e+1] = (sword64)at[e+1] * y_ntt_t[e+1]; + t64[e+2] = (sword64)at[e+2] * y_ntt_t[e+2]; + t64[e+3] = (sword64)at[e+3] * y_ntt_t[e+3]; + t64[e+4] = (sword64)at[e+4] * y_ntt_t[e+4]; + t64[e+5] = (sword64)at[e+5] * y_ntt_t[e+5]; + t64[e+6] = (sword64)at[e+6] * y_ntt_t[e+6]; + t64[e+7] = (sword64)at[e+7] * y_ntt_t[e+7]; + } + #endif + } + else { + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] += (sword64)at[e] * y_ntt_t[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] += (sword64)at[e+0] * y_ntt_t[e+0]; + t64[e+1] += (sword64)at[e+1] * y_ntt_t[e+1]; + t64[e+2] += (sword64)at[e+2] * y_ntt_t[e+2]; + t64[e+3] += (sword64)at[e+3] * y_ntt_t[e+3]; + t64[e+4] += (sword64)at[e+4] * y_ntt_t[e+4]; + t64[e+5] += (sword64)at[e+5] * y_ntt_t[e+5]; + t64[e+6] += (sword64)at[e+6] * y_ntt_t[e+6]; + t64[e+7] += (sword64)at[e+7] * y_ntt_t[e+7]; } + #endif } + #endif /* Next polynomial. */ yt += DILITHIUM_N; } + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + for (e = 0; e < DILITHIUM_N; e++) { + wt[e] = dilithium_mont_red(t64[e]); + } + #endif dilithium_invntt(wt); /* Step 14, Step 22: Make values positive and decompose. */ dilithium_make_pos(wt); @@ -5885,19 +6592,22 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, } if ((ret == 0) && valid) { sword32* yt = y; + #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC const byte* s1pt = s1p; - byte* ze = sig + params->lambda * 2; + #endif + byte* ze = sig + params->lambda / 4; /* Step 15: Encode w1. */ dilithium_vec_encode_w1(w1, params->k, params->gamma2, w1e); /* Step 15: Hash mu and encoded w1. * Step 32: Hash is stored in signature. */ ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, - w1e, params->w1EncSz, commit, 2 * params->lambda); + w1e, params->w1EncSz, commit, params->lambda / 4); if (ret == 0) { /* Step 17: Compute c from first 256 bits of commit. */ - ret = dilithium_sample_in_ball(&key->shake, commit, - params->tau, c, NULL); + ret = dilithium_sample_in_ball_ex(params->level, + &key->shake, commit, params->lambda / 4, params->tau, c, + blocks); } if (ret == 0) { /* Step 18: NTT(c). */ @@ -5905,6 +6615,7 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, } for (s = 0; (ret == 0) && valid && (s < params->l); s++) { + #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC #if !defined(WOLFSSL_NO_ML_DSA_44) || \ !defined(WOLFSSL_NO_ML_DSA_87) /* -2..2 */ @@ -5922,6 +6633,9 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, #endif dilithium_ntt_small(s1); dilithium_mul(z, c, s1); + #else + dilithium_mul(z, c, s1 + s * DILITHIUM_N); + #endif /* Step 19: cs1 = NTT-1(c o s1) */ dilithium_invntt(z); /* Step 21: z = y + cs1 */ @@ -5958,13 +6672,16 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, } if ((ret == 0) && valid) { const byte* t0pt = t0p; + #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC const byte* s2pt = s2p; + #endif sword32* cs2 = ct0; w0t = w0; w1t = w1; byte idx = 0; for (r = 0; valid && (r < params->k); r++) { + #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC #if !defined(WOLFSSL_NO_ML_DSA_44) || \ !defined(WOLFSSL_NO_ML_DSA_87) /* -2..2 */ @@ -5979,10 +6696,14 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, dilithium_decode_eta_4_bits(s2pt, s2); s2pt += DILITHIUM_N / 2; } - #endif + #endif dilithium_ntt_small(s2); /* Step 20: cs2 = NTT-1(c o s2) */ dilithium_mul(cs2, c, s2); + #else + /* Step 20: cs2 = NTT-1(c o s2) */ + dilithium_mul(cs2, c, s2 + r * DILITHIUM_N); + #endif dilithium_invntt(cs2); /* Step 22: w0 - cs2 */ dilithium_sub(w0t, cs2); @@ -5991,11 +6712,16 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, hi = params->gamma2 - params->beta; valid = dilithium_check_low(w0t, hi); if (valid) { + #ifndef WOLFSSL_DILITHIUM_SIGN_SMALL_MEM_PRECALC dilithium_decode_t0(t0pt, t0); dilithium_ntt(t0); /* Step 25: ct0 = NTT-1(c o t0) */ dilithium_mul(ct0, c, t0); + #else + /* Step 25: ct0 = NTT-1(c o t0) */ + dilithium_mul(ct0, c, t0 + r * DILITHIUM_N); + #endif dilithium_invntt(ct0); /* Step 27: Check ct0 has low enough values. */ valid = dilithium_check_low(ct0, params->gamma2); @@ -6053,49 +6779,351 @@ static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, while ((ret == 0) && (!valid)); } - XFREE(y, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(y, key->heap, DYNAMIC_TYPE_DILITHIUM); return ret; #endif } -/* Sign a message with the key and a random number generator. +/* Sign a message with the key and a seed. + * + * FIPS 204. 5.2: Algorithm 2 ML-DSA.Sign(sk, M, ctx) + * ... + * 10: M' <- BytesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx || M) + * 11: sigma <- ML-DSA.Sign_internal(sk, M', rnd) + * 12: return sigma * - * FIPS 204. 6: Algorithm 2 MD-DSA.Sign(sk, M) + * FIPS 204. 6.2: Algorithm 7 ML-DSA.SignInternal(sk, M', rnd) * ... - * 7: rnd <- {0,1}256 [Randomly generated.] + * 6: mu <- H(BytesToBits(tr)||M', 64) * ... * * @param [in, out] key Dilithium key. - * @param [in, out] rng Random number generator. + * @param [in] seed Random seed. + * @param [in] ctx Context of signature. + * @param [in] ctxLen Length of context in bytes. * @param [in] msg Message data to sign. * @param [in] msgLen Length of message data in bytes. * @param [out] sig Buffer to hold signature. * @param [in, out] sigLen On in, length of buffer in bytes. * On out, the length of the signature in bytes. * @return 0 on success. + * @return BAD_FUNC_ARG when context length is greater than 255. * @return BUFFER_E when the signature buffer is too small. * @return MEMORY_E when memory allocation fails. * @return Other negative when an error occurs. */ -static int dilithium_sign_msg(dilithium_key* key, WC_RNG* rng, const byte* msg, +static int dilithium_sign_ctx_msg_with_seed(dilithium_key* key, + const byte* seed, const byte* ctx, byte ctxLen, const byte* msg, word32 msgLen, byte* sig, word32 *sigLen) { - int ret = 0; - byte rnd[DILITHIUM_RND_SZ]; + int ret; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = seedMu + DILITHIUM_RND_SZ; - /* Must have a random number generator. */ - if (rng == NULL) { - ret = BAD_FUNC_ARG; + XMEMCPY(seedMu, seed, DILITHIUM_RND_SZ); + /* Step 6. Calculate mu. */ + ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 0, + ctx, ctxLen, msg, msgLen, mu, DILITHIUM_MU_SZ); + if (ret == 0) { + ret = dilithium_sign_with_seed_mu(key, seedMu, sig, sigLen); } - if (ret == 0) { + return ret; +} + +/* Sign a message with the key and a seed. + * + * FIPS 204. 5.2: Algorithm 2 ML-DSA.Sign(sk, M, ctx) + * ... + * 10: M' <- BytesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx || M) + * 11: sigma <- ML-DSA.Sign_internal(sk, M', rnd) + * 12: return sigma + * + * FIPS 204. 6.2: Algorithm 7 ML-DSA.SignInternal(sk, M', rnd) + * ... + * 6: mu <- H(BytesToBits(tr)||M', 64) + * ... + * + * @param [in, out] key Dilithium key. + * @param [in] seed Random seed. + * @param [in] msg Message data to sign. + * @param [in] msgLen Length of message data in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when context length is greater than 255. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_msg_with_seed(dilithium_key* key, const byte* seed, + const byte* msg, word32 msgLen, byte* sig, word32 *sigLen) +{ + int ret; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = seedMu + DILITHIUM_RND_SZ; + + XMEMCPY(seedMu, seed, DILITHIUM_RND_SZ); + /* Step 6. Calculate mu. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, mu, + DILITHIUM_MU_SZ); + if (ret == 0) { + ret = dilithium_sign_with_seed_mu(key, seedMu, sig, sigLen); + } + + return ret; +} + +/* Sign a message with the key and a random number generator. + * + * FIPS 204. 5.2: Algorithm 2 ML-DSA.Sign(sk, M, ctx) + * ... + * 5: rnd <- B32 [Randomly generated.] + * 6: if rnd = NULL then + * 7: return falsam + * 8: end if + * 9: + * 10: M' <- BytesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx || M) + * ... + * + * FIPS 204. 6.2: Algorithm 7 ML-DSA.SignInternal(sk, M', rnd) + * ... + * 6: mu <- H(BytesToBits(tr)||M', 64) + * ... + * + * @param [in, out] key Dilithium key. + * @param [in, out] rng Random number generator. + * @param [in] ctx Context of signature. + * @param [in] ctxLen Length of context. + * @param [in] msg Message data to sign. + * @param [in] msgLen Length of message data in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_ctx_msg(dilithium_key* key, WC_RNG* rng, + const byte* ctx, byte ctxLen, const byte* msg, word32 msgLen, byte* sig, + word32 *sigLen) +{ + int ret = 0; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = seedMu + DILITHIUM_RND_SZ; + + /* Must have a random number generator. */ + if (rng == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { /* Step 7: Generate random seed. */ - ret = wc_RNG_GenerateBlock(rng, rnd, DILITHIUM_RND_SZ); + ret = wc_RNG_GenerateBlock(rng, seedMu, DILITHIUM_RND_SZ); } if (ret == 0) { - /* Sign with random seed. */ - ret = dilithium_sign_msg_with_seed(key, rnd, msg, msgLen, sig, - sigLen); + /* Step 6. Calculate mu. */ + ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 0, + ctx, ctxLen, msg, msgLen, mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + ret = dilithium_sign_with_seed_mu(key, seedMu, sig, sigLen); + } + + return ret; +} + +/* Sign a message with the key and a random number generator. + * + * FIPS 204. 5.2: Algorithm 2 ML-DSA.Sign(sk, M, ctx) + * ... + * 5: rnd <- B32 [Randomly generated.] + * 6: if rnd = NULL then + * 7: return falsam + * 8: end if + * 9: + * 10: M' <- BytesToBits(IntegerToBytes(0, 1) || IntegerToBytes(|ctx|, 1) || + * ctx || M) + * ... + * + * FIPS 204. 6.2: Algorithm 7 ML-DSA.SignInternal(sk, M', rnd) + * ... + * 6: mu <- H(BytesToBits(tr)||M', 64) + * ... + * + * @param [in, out] key Dilithium key. + * @param [in, out] rng Random number generator. + * @param [in] msg Message data to sign. + * @param [in] msgLen Length of message data in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_msg(dilithium_key* key, WC_RNG* rng, + const byte* msg, word32 msgLen, byte* sig, word32 *sigLen) +{ + int ret = 0; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = seedMu + DILITHIUM_RND_SZ; + + /* Must have a random number generator. */ + if (rng == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Step 7: Generate random seed. */ + ret = wc_RNG_GenerateBlock(rng, seedMu, DILITHIUM_RND_SZ); + } + if (ret == 0) { + /* Step 6. Calculate mu. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + ret = dilithium_sign_with_seed_mu(key, seedMu, sig, sigLen); + } + + return ret; +} + +/* Sign a pre-hashed message with the key and a seed. + * + * FIPS 204. 5.4.1: Algorithm 4 HashML-DSA.Sign(sk, M, ctx, PH) + * ... + * 10: switch PH do + * 11: case SHA-256: + * 12: OID <- IntegerToBytes(0x0609608648016503040201, 11) + * 13: PHm <- SHA256(M) (not done here as hash is passed in) + * ... + * 22: end switch + * 23: M' <- BytesToBits(IntegerToBytes(1, 1) || IntegerToBytes(|ctx|, 1) || + * ctx || OID || PHm) + * 24: sigma <- ML-DSA.Sign_internal(sk, M', rnd) + * 25: return sigma + * + * FIPS 204. 6.2: Algorithm 7 ML-DSA.SignInternal(sk, M', rnd) + * ... + * 6: mu <- H(BytesToBits(tr)||M', 64) + * ... + * + * @param [in, out] key Dilithium key. + * @param [in] seed Random seed. + * @param [in] ctx Context of signature. + * @param [in] ctxLen Length of context. + * @param [in] hashAlg Hash algorithm used on message. + * @param [in] hash Message hash to sign. + * @param [in] hashLen Length of message hash in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_ctx_hash_with_seed(dilithium_key* key, + const byte* seed, const byte* ctx, byte ctxLen, int hashAlg, + const byte* hash, word32 hashLen, byte* sig, word32 *sigLen) +{ + int ret = 0; + const byte* pub_seed = key->k; + const byte* k = pub_seed + DILITHIUM_PUB_SEED_SZ; + const byte* tr = k + DILITHIUM_K_SZ; + byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; + byte* mu = seedMu + DILITHIUM_RND_SZ; + byte oidMsgHash[DILITHIUM_HASH_OID_LEN + WC_MAX_DIGEST_SIZE]; + word32 oidMsgHashLen; + + if ((ret == 0) && (hashLen > WC_MAX_DIGEST_SIZE)) { + ret = BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(seedMu, seed, DILITHIUM_RND_SZ); + + ret = dilithium_get_hash_oid(hashAlg, oidMsgHash, &oidMsgHashLen); + } + if (ret == 0) { + XMEMCPY(oidMsgHash + oidMsgHashLen, hash, hashLen); + oidMsgHashLen += hashLen; + + /* Step 6. Calculate mu. */ + ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 1, + ctx, ctxLen, oidMsgHash, oidMsgHashLen, mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + ret = dilithium_sign_with_seed_mu(key, seedMu, sig, sigLen); + } + + return ret; +} + +/* Sign a pre-hashed message with the key and a random number generator. + * + * FIPS 204. 5.4.1: Algorithm 4 HashML-DSA.Sign(sk, M, ctx, PH) + * ... + * 5: rnd <- B32 [Randomly generated.] + * 6: if rnd = NULL then + * 7: return falsam + * 8: end if + * ... + * + * @param [in, out] key Dilithium key. + * @param [in, out] rng Random number generator. + * @param [in] ctx Context of signature. + * @param [in] ctxLen Length of context. + * @param [in] hashAlg Hash algorithm used on message. + * @param [in] hash Message hash to sign. + * @param [in] hashLen Length of message hash in bytes. + * @param [out] sig Buffer to hold signature. + * @param [in, out] sigLen On in, length of buffer in bytes. + * On out, the length of the signature in bytes. + * @return 0 on success. + * @return BUFFER_E when the signature buffer is too small. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_sign_ctx_hash(dilithium_key* key, WC_RNG* rng, + const byte* ctx, byte ctxLen, int hashAlg, const byte* hash, word32 hashLen, + byte* sig, word32 *sigLen) +{ + int ret = 0; + byte seed[DILITHIUM_RND_SZ]; + + /* Must have a random number generator. */ + if (rng == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Step 7: Generate random seed. */ + ret = wc_RNG_GenerateBlock(rng, seed, DILITHIUM_RND_SZ); + } + + if (ret == 0) { + ret = dilithium_sign_ctx_hash_with_seed(key, seed, ctx, ctxLen, hashAlg, + hash, hashLen, sig, sigLen); } return ret; @@ -6105,7 +7133,13 @@ static int dilithium_sign_msg(dilithium_key* key, WC_RNG* rng, const byte* msg, #ifndef WOLFSSL_DILITHIUM_NO_VERIFY -#ifndef WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM +#if !defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) || \ + defined(WC_DILITHIUM_CACHE_PUB_VECTORS) +/* Make public vector from public key data. + * + * @param [in, out] key Key with public key data. + * @param [out] t1 Vector in NTT form. + */ static void dilithium_make_pub_vec(dilithium_key* key, sword32* t1) { const wc_dilithium_params* params = key->params; @@ -6132,15 +7166,14 @@ static void dilithium_make_pub_vec(dilithium_key* key, sword32* t1) * 7: mu <- H(tr||M, 512) * 8: (c1_tilde, c2_tilde) E {0,1}256 x {0,1)2*lambda-256 <- c_tilde * 9: c <- SampleInBall(c1_tilde) - * 10: w'approx <- NTT-1(A_circum o NTT(z) - NTT(c) o NTT(t1.s^d)) + * 10: w'approx <- NTT-1(A_circum o NTT(z) - NTT(c) o NTT(t1.2^d)) * 11: w1' <- UseHint(h, w'approx) * 12: c'_tilde < H(mu||w1Encode(w1'), 2*lambda) * 13: return [[ ||z||inf < GAMMA1 - BETA]] and [[c_tilde = c'_tilde]] and * [[number of 1's in h is <= OMEGA * * @param [in, out] key Dilithium key. - * @param [in] msg Message to verify. - * @param [in] msgLen Length of message in bytes. + * @param [in] mu Data to verify. * @param [in] sig Signature to verify message. * @param [in] sigLen Length of message in bytes. * @param [out] res Result of verification. @@ -6151,15 +7184,15 @@ static void dilithium_make_pub_vec(dilithium_key* key, sword32* t1) * @return MEMORY_E when memory allocation fails. * @return Other negative when an error occurs. */ -static int dilithium_verify_msg(dilithium_key* key, const byte* msg, - word32 msgLen, const byte* sig, word32 sigLen, int* res) +static int dilithium_verify_mu(dilithium_key* key, const byte* mu, + const byte* sig, word32 sigLen, int* res) { #ifndef WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM int ret = 0; const wc_dilithium_params* params = key->params; const byte* pub_seed = key->p; const byte* commit = sig; - const byte* ze = sig + params->lambda * 2; + const byte* ze = sig + params->lambda / 4; const byte* h = ze + params->zEncSz; sword32* a = NULL; sword32* t1 = NULL; @@ -6167,10 +7200,8 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, sword32* z = NULL; sword32* w = NULL; sword32* t1c = NULL; - byte tr[DILITHIUM_TR_SZ]; - byte* mu = tr; + byte commit_calc[DILITHIUM_TR_SZ]; byte* w1e = NULL; - byte* commit_calc = tr; int valid = 0; sword32 hi; @@ -6185,23 +7216,29 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, /* Allocate memory for large intermediates. */ #ifdef WC_DILITHIUM_CACHE_MATRIX_A +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->a == NULL)) { - key->a = (sword32*)XMALLOC(params->aSz, NULL, DYNAMIC_TYPE_DILITHIUM); + key->a = (sword32*)XMALLOC(params->aSz, key->heap, + DYNAMIC_TYPE_DILITHIUM); if (key->a == NULL) { ret = MEMORY_E; } } +#endif if (ret == 0) { a = key->a; } #endif #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->t1 == NULL)) { - key->t1 = (sword32*)XMALLOC(params->s2Sz, NULL, DYNAMIC_TYPE_DILITHIUM); + key->t1 = (sword32*)XMALLOC(params->s2Sz, key->heap, + DYNAMIC_TYPE_DILITHIUM); if (key->t1 == NULL) { ret = MEMORY_E; } } +#endif if (ret == 0) { t1 = key->t1; } @@ -6217,7 +7254,7 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, allocSz += params->aSz; #endif - z = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + z = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (z == NULL) { ret = MEMORY_E; } @@ -6261,7 +7298,7 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, { /* Step 5: Expand pub seed to compute matrix A. */ ret = dilithium_expand_a(&key->shake, pub_seed, params->k, - params->l, a); + params->l, a, key->heap); #ifdef WC_DILITHIUM_CACHE_MATRIX_A /* Whether we have cached A is dependent on success of operation. */ key->aSet = (ret == 0); @@ -6269,19 +7306,9 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, } } if ((ret == 0) && valid) { - /* Step 6: Hash public key. */ - ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, - DILITHIUM_TR_SZ); - } - if ((ret == 0) && valid) { - /* Step 7: Hash hash of public key and message. */ - ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, - mu, DILITHIUM_MU_SZ); - } - if ((ret == 0) && valid) { - /* Step 9: Compute c from first 256 bits of commit. */ - ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, - NULL); + /* Step 9: Compute c from commit. */ + ret = dilithium_sample_in_ball(params->level, &key->shake, commit, + params->lambda / 4, params->tau, c, key->heap); } if ((ret == 0) && valid) { /* Step 10: w = NTT-1(A o NTT(z) - NTT(c) o NTT(t1)) */ @@ -6297,15 +7324,15 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, dilithium_vec_encode_w1(w, params->k, params->gamma2, w1e); /* Step 12: Hash mu and encoded w1. */ ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, w1e, - params->w1EncSz, commit_calc, 2 * params->lambda); + params->w1EncSz, commit_calc, params->lambda / 4); } if ((ret == 0) && valid) { /* Step 13: Compare commit. */ - valid = (XMEMCMP(commit, commit_calc, 2 * params->lambda) == 0); + valid = (XMEMCMP(commit, commit_calc, params->lambda / 4) == 0); } *res = valid; - XFREE(z, NULL, DYNAMIC_TYPE_DILITHIUM); + XFREE(z, key->heap, DYNAMIC_TYPE_DILITHIUM); return ret; #else int ret = 0; @@ -6313,24 +7340,27 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, const byte* pub_seed = key->p; const byte* t1p = pub_seed + DILITHIUM_PUB_SEED_SZ; const byte* commit = sig; - const byte* ze = sig + params->lambda * 2; + const byte* ze = sig + params->lambda / 4; const byte* h = ze + params->zEncSz; sword32* t1 = NULL; sword32* a = NULL; sword32* c = NULL; sword32* z = NULL; sword32* w = NULL; - byte tr[DILITHIUM_TR_SZ]; - byte* mu = tr; +#ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + sword64* t64 = NULL; +#endif +#ifndef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + byte* block = NULL; +#endif byte* w1e = NULL; - byte* commit_calc = tr; + byte commit_calc[DILITHIUM_TR_SZ]; int valid = 0; sword32 hi; - byte i; - unsigned int j; + unsigned int r; byte o; byte* encW1; - byte* seed = tr; + byte* seed = commit_calc; /* Ensure the signature is the right size for the parameters. */ if (sigLen != params->sigSz) { @@ -6345,17 +7375,27 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, /* Allocate memory for large intermediates. */ if (ret == 0) { /* z, c, w, t1, w1e. */ - z = (sword32*)XMALLOC(params->s1Sz + 3 * DILITHIUM_POLY_SIZE + - DILITHIUM_MAX_W1_ENC_SZ, NULL, DYNAMIC_TYPE_DILITHIUM); + unsigned int allocSz; + + allocSz = params->s1Sz + 3 * DILITHIUM_POLY_SIZE + + DILITHIUM_REJ_NTT_POLY_H_SIZE + params->w1EncSz; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + allocSz += DILITHIUM_POLY_SIZE * 2; + #endif + z = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (z == NULL) { ret = MEMORY_E; } else { - c = z + params->s1Sz / sizeof(*t1); - w = c + DILITHIUM_N; - t1 = w + DILITHIUM_N; - w1e = (byte*)(t1 + DILITHIUM_N); - a = t1; + c = z + params->s1Sz / sizeof(*t1); + w = c + DILITHIUM_N; + t1 = w + DILITHIUM_N; + block = (byte*)(t1 + DILITHIUM_N); + w1e = block + DILITHIUM_REJ_NTT_POLY_H_SIZE; + a = t1; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = (sword64*)(w1e + params->w1EncSz); + #endif } } #else @@ -6366,6 +7406,9 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, t1 = key->t1; w1e = key->w1e; a = t1; + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + t64 = key->t64; + #endif } #endif @@ -6382,11 +7425,11 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, /* Step 9: Compute c from first 256 bits of commit. */ #ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, - key->block); + ret = dilithium_sample_in_ball_ex(params->level, &key->shake, commit, + params->lambda / 4, params->tau, c, key->block); #else - ret = dilithium_sample_in_ball(&key->shake, commit, params->tau, c, - NULL); + ret = dilithium_sample_in_ball_ex(params->level, &key->shake, commit, + params->lambda / 4, params->tau, c, block); #endif } if ((ret == 0) && valid) { @@ -6398,8 +7441,9 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, /* Copy the seed into a buffer that has space for s and r. */ XMEMCPY(seed, pub_seed, DILITHIUM_PUB_SEED_SZ); /* Step 1: Loop over first dimension of matrix. */ - for (i = 0; (ret == 0) && (i < params->k); i++) { - byte s; + for (r = 0; (ret == 0) && (r < params->k); r++) { + unsigned int s; + unsigned int e; const sword32* zt = z; /* Step 1: Decode and NTT vector t1. */ @@ -6409,112 +7453,288 @@ static int dilithium_verify_msg(dilithium_key* key, const byte* msg, /* Step 10: - NTT(c) o NTT(t1)) */ dilithium_ntt(w); -#ifdef WOLFSSL_DILITHIUM_SMALL - for (j = 0; j < DILITHIUM_N; j++) { - w[j] = -dilithium_mont_red((sword64)c[j] * w[j]); + #ifndef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + w[e] = -dilithium_mont_red((sword64)c[e] * w[e]); } -#else - for (j = 0; j < DILITHIUM_N; j += 8) { - w[j+0] = -dilithium_mont_red((sword64)c[j+0] * w[j+0]); - w[j+1] = -dilithium_mont_red((sword64)c[j+1] * w[j+1]); - w[j+2] = -dilithium_mont_red((sword64)c[j+2] * w[j+2]); - w[j+3] = -dilithium_mont_red((sword64)c[j+3] * w[j+3]); - w[j+4] = -dilithium_mont_red((sword64)c[j+4] * w[j+4]); - w[j+5] = -dilithium_mont_red((sword64)c[j+5] * w[j+5]); - w[j+6] = -dilithium_mont_red((sword64)c[j+6] * w[j+6]); - w[j+7] = -dilithium_mont_red((sword64)c[j+7] * w[j+7]); + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + w[e+0] = -dilithium_mont_red((sword64)c[e+0] * w[e+0]); + w[e+1] = -dilithium_mont_red((sword64)c[e+1] * w[e+1]); + w[e+2] = -dilithium_mont_red((sword64)c[e+2] * w[e+2]); + w[e+3] = -dilithium_mont_red((sword64)c[e+3] * w[e+3]); + w[e+4] = -dilithium_mont_red((sword64)c[e+4] * w[e+4]); + w[e+5] = -dilithium_mont_red((sword64)c[e+5] * w[e+5]); + w[e+6] = -dilithium_mont_red((sword64)c[e+6] * w[e+6]); + w[e+7] = -dilithium_mont_red((sword64)c[e+7] * w[e+7]); } -#endif + #endif + #else + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] = -(sword64)c[e] * w[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] = -(sword64)c[e+0] * w[e+0]; + t64[e+1] = -(sword64)c[e+1] * w[e+1]; + t64[e+2] = -(sword64)c[e+2] * w[e+2]; + t64[e+3] = -(sword64)c[e+3] * w[e+3]; + t64[e+4] = -(sword64)c[e+4] * w[e+4]; + t64[e+5] = -(sword64)c[e+5] * w[e+5]; + t64[e+6] = -(sword64)c[e+6] * w[e+6]; + t64[e+7] = -(sword64)c[e+7] * w[e+7]; + } + #endif + #endif /* Step 5: Expand pub seed to compute matrix A. */ /* Put r into buffer to be hashed. */ - seed[DILITHIUM_PUB_SEED_SZ + 1] = i; + seed[DILITHIUM_PUB_SEED_SZ + 1] = r; for (s = 0; (ret == 0) && (s < params->l); s++) { /* Put s into buffer to be hashed. */ seed[DILITHIUM_PUB_SEED_SZ + 0] = s; /* Step 3: Create polynomial from hashing seed. */ #ifdef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - ret = dilithium_rej_ntt_poly(&key->shake, seed, a, key->h); + ret = dilithium_rej_ntt_poly_ex(&key->shake, seed, a, key->h); #else - ret = dilithium_rej_ntt_poly(&key->shake, seed, a, NULL); + ret = dilithium_rej_ntt_poly_ex(&key->shake, seed, a, block); #endif /* Step 10: w = A o NTT(z) - NTT(c) o NTT(t1) */ -#ifdef WOLFSSL_DILITHIUM_SMALL - for (j = 0; j < DILITHIUM_N; j++) { - w[j] += dilithium_mont_red((sword64)a[j] * zt[j]); + #ifndef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + w[e] += dilithium_mont_red((sword64)a[e] * zt[e]); } -#else - for (j = 0; j < DILITHIUM_N; j += 8) { - w[j+0] += dilithium_mont_red((sword64)a[j+0] * zt[j+0]); - w[j+1] += dilithium_mont_red((sword64)a[j+1] * zt[j+1]); - w[j+2] += dilithium_mont_red((sword64)a[j+2] * zt[j+2]); - w[j+3] += dilithium_mont_red((sword64)a[j+3] * zt[j+3]); - w[j+4] += dilithium_mont_red((sword64)a[j+4] * zt[j+4]); - w[j+5] += dilithium_mont_red((sword64)a[j+5] * zt[j+5]); - w[j+6] += dilithium_mont_red((sword64)a[j+6] * zt[j+6]); - w[j+7] += dilithium_mont_red((sword64)a[j+7] * zt[j+7]); + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + w[e+0] += dilithium_mont_red((sword64)a[e+0] * zt[e+0]); + w[e+1] += dilithium_mont_red((sword64)a[e+1] * zt[e+1]); + w[e+2] += dilithium_mont_red((sword64)a[e+2] * zt[e+2]); + w[e+3] += dilithium_mont_red((sword64)a[e+3] * zt[e+3]); + w[e+4] += dilithium_mont_red((sword64)a[e+4] * zt[e+4]); + w[e+5] += dilithium_mont_red((sword64)a[e+5] * zt[e+5]); + w[e+6] += dilithium_mont_red((sword64)a[e+6] * zt[e+6]); + w[e+7] += dilithium_mont_red((sword64)a[e+7] * zt[e+7]); } -#endif + #endif + #else + #ifdef WOLFSSL_DILITHIUM_SMALL + for (e = 0; e < DILITHIUM_N; e++) { + t64[e] += (sword64)a[e] * zt[e]; + } + #else + for (e = 0; e < DILITHIUM_N; e += 8) { + t64[e+0] += (sword64)a[e+0] * zt[e+0]; + t64[e+1] += (sword64)a[e+1] * zt[e+1]; + t64[e+2] += (sword64)a[e+2] * zt[e+2]; + t64[e+3] += (sword64)a[e+3] * zt[e+3]; + t64[e+4] += (sword64)a[e+4] * zt[e+4]; + t64[e+5] += (sword64)a[e+5] * zt[e+5]; + t64[e+6] += (sword64)a[e+6] * zt[e+6]; + t64[e+7] += (sword64)a[e+7] * zt[e+7]; + } + #endif + #endif /* Next polynomial. */ zt += DILITHIUM_N; } + #ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + for (e = 0; e < DILITHIUM_N; e++) { + w[e] = dilithium_mont_red(t64[e]); + } + #endif /* Step 10: w = NTT-1(A o NTT(z) - NTT(c) o NTT(t1)) */ dilithium_invntt(w); -#ifndef WOLFSSL_NO_ML_DSA_44 + #ifndef WOLFSSL_NO_ML_DSA_44 if (params->gamma2 == DILITHIUM_Q_LOW_88) { /* Step 11: Use hint to give full w1. */ - dilithium_use_hint_88(w, h, i, &o); + dilithium_use_hint_88(w, h, r, &o); /* Step 12: Encode w1. */ dilithium_encode_w1_88(w, encW1); encW1 += DILITHIUM_Q_HI_88_ENC_BITS * 2 * DILITHIUM_N / 16; } else -#endif -#if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) + #endif + #if !defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87) if (params->gamma2 == DILITHIUM_Q_LOW_32) { /* Step 11: Use hint to give full w1. */ - dilithium_use_hint_32(w, h, params->omega, i, &o); + dilithium_use_hint_32(w, h, params->omega, r, &o); /* Step 12: Encode w1. */ dilithium_encode_w1_32(w, encW1); encW1 += DILITHIUM_Q_HI_32_ENC_BITS * 2 * DILITHIUM_N / 16; } else -#endif + #endif { } } } - if ((ret == 0) && valid) { + if ((ret == 0) && valid) { + /* Step 12: Hash mu and encoded w1. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, w1e, + params->w1EncSz, commit_calc, params->lambda / 4); + } + if ((ret == 0) && valid) { + /* Step 13: Compare commit. */ + valid = (XMEMCMP(commit, commit_calc, params->lambda / 4) == 0); + } + + *res = valid; +#ifndef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + XFREE(z, key->heap, DYNAMIC_TYPE_DILITHIUM); +#endif + return ret; +#endif /* !WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM */ +} + +/* Verify signature of message using public key. + * + * @param [in, out] key Dilithium key. + * @param [in] ctx Context of verification. + * @param [in] ctxLen Length of context in bytes. + * @param [in] msg Message to verify. + * @param [in] msgLen Length of message in bytes. + * @param [in] sig Signature to verify message. + * @param [in] sigLen Length of message in bytes. + * @param [out] res Result of verification. + * @return 0 on success. + * @return SIG_VERIFY_E when hint is malformed. + * @return BUFFER_E when the length of the signature does not match + * parameters. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_verify_ctx_msg(dilithium_key* key, const byte* ctx, + word32 ctxLen, const byte* msg, word32 msgLen, const byte* sig, + word32 sigLen, int* res) +{ + int ret = 0; + byte tr[DILITHIUM_TR_SZ]; + byte* mu = tr; + + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Step 6: Hash public key. */ + ret = dilithium_shake256(&key->shake, key->p, key->params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if (ret == 0) { + /* Step 6. Calculate mu. */ + ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 0, + ctx, ctxLen, msg, msgLen, mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + ret = dilithium_verify_mu(key, mu, sig, sigLen, res); + } + + return ret; +} + +/* Verify signature of message using public key. + * + * @param [in, out] key Dilithium key. + * @param [in] msg Message to verify. + * @param [in] msgLen Length of message in bytes. + * @param [in] sig Signature to verify message. + * @param [in] sigLen Length of message in bytes. + * @param [out] res Result of verification. + * @return 0 on success. + * @return SIG_VERIFY_E when hint is malformed. + * @return BUFFER_E when the length of the signature does not match + * parameters. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_verify_msg(dilithium_key* key, const byte* msg, + word32 msgLen, const byte* sig, word32 sigLen, int* res) +{ + int ret = 0; + byte tr[DILITHIUM_TR_SZ]; + byte* mu = tr; + + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Step 6: Hash public key. */ + ret = dilithium_shake256(&key->shake, key->p, key->params->pkSz, tr, + DILITHIUM_TR_SZ); + } + if (ret == 0) { + /* Step 6. Calculate mu. */ + ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, + mu, DILITHIUM_MU_SZ); + } + if (ret == 0) { + ret = dilithium_verify_mu(key, mu, sig, sigLen, res); + } + + return ret; +} + +/* Verify signature of message using public key. + * + * @param [in, out] key Dilithium key. + * @param [in] ctx Context of verification. + * @param [in] ctxLen Length of context in bytes. + * @param [iu] hashAlg Hash algorithm used on message. + * @param [in] hash Hash of message to verify. + * @param [in] hashLen Length of message hash in bytes. + * @param [in] sig Signature to verify message. + * @param [in] sigLen Length of message in bytes. + * @param [out] res Result of verification. + * @return 0 on success. + * @return SIG_VERIFY_E when hint is malformed. + * @return BUFFER_E when the length of the signature does not match + * parameters. + * @return MEMORY_E when memory allocation fails. + * @return Other negative when an error occurs. + */ +static int dilithium_verify_ctx_hash(dilithium_key* key, const byte* ctx, + word32 ctxLen, int hashAlg, const byte* hash, word32 hashLen, + const byte* sig, word32 sigLen, int* res) +{ + int ret = 0; + byte tr[DILITHIUM_TR_SZ]; + byte* mu = tr; + byte oidMsgHash[DILITHIUM_HASH_OID_LEN + WC_MAX_DIGEST_SIZE]; + word32 oidMsgHashLen; + + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { /* Step 6: Hash public key. */ - ret = dilithium_shake256(&key->shake, key->p, params->pkSz, tr, + ret = dilithium_shake256(&key->shake, key->p, key->params->pkSz, tr, DILITHIUM_TR_SZ); } - if ((ret == 0) && valid) { - /* Step 7: Hash hash of public key and message. */ - ret = dilithium_hash256(&key->shake, tr, DILITHIUM_TR_SZ, msg, msgLen, - mu, DILITHIUM_MU_SZ); + if (ret == 0) { + ret = dilithium_get_hash_oid(hashAlg, oidMsgHash, &oidMsgHashLen); } - if ((ret == 0) && valid) { - /* Step 12: Hash mu and encoded w1. */ - ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, w1e, - params->w1EncSz, commit_calc, 2 * params->lambda); + if (ret == 0) { + XMEMCPY(oidMsgHash + oidMsgHashLen, hash, hashLen); + oidMsgHashLen += hashLen; + + /* Step 6. Calculate mu. */ + ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 1, + ctx, ctxLen, oidMsgHash, oidMsgHashLen, mu, DILITHIUM_MU_SZ); } - if ((ret == 0) && valid) { - /* Step 13: Compare commit. */ - valid = (XMEMCMP(commit, commit_calc, 2 * params->lambda) == 0); + if (ret == 0) { + ret = dilithium_verify_mu(key, mu, sig, sigLen, res); } - *res = valid; -#ifndef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC - XFREE(z, NULL, DYNAMIC_TYPE_DILITHIUM); -#endif return ret; -#endif /* !WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM */ } - #endif /* WOLFSSL_DILITHIUM_NO_VERIFY */ #elif defined(HAVE_LIBOQS) @@ -6525,13 +7745,13 @@ static int oqs_dilithium_make_key(dilithium_key* key, WC_RNG* rng) int ret = 0; OQS_SIG *oqssig = NULL; - if (key->level == 2) { + if (key->level == WC_ML_DSA_44) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); } - else if (key->level == 3) { + else if (key->level == WC_ML_DSA_65) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); } - else if (key->level == 5) { + else if (key->level == WC_ML_DSA_87) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); } else { @@ -6573,13 +7793,13 @@ static int oqs_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, } if (ret == 0) { - if (key->level == 2) { + if (key->level == WC_ML_DSA_44) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); } - else if (key->level == 3) { + else if (key->level == WC_ML_DSA_65) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); } - else if (key->level == 5) { + else if (key->level == WC_ML_DSA_87) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); } else { @@ -6593,16 +7813,19 @@ static int oqs_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, /* check and set up out length */ if (ret == 0) { - if ((key->level == 2) && (*sigLen < DILITHIUM_LEVEL2_SIG_SIZE)) { - *sigLen = DILITHIUM_LEVEL2_SIG_SIZE; + if ((key->level == WC_ML_DSA_44) && + (*sigLen < ML_DSA_LEVEL2_SIG_SIZE)) { + *sigLen = ML_DSA_LEVEL2_SIG_SIZE; ret = BUFFER_E; } - else if ((key->level == 3) && (*sigLen < DILITHIUM_LEVEL3_SIG_SIZE)) { - *sigLen = DILITHIUM_LEVEL3_SIG_SIZE; + else if ((key->level == WC_ML_DSA_65) && + (*sigLen < ML_DSA_LEVEL3_SIG_SIZE)) { + *sigLen = ML_DSA_LEVEL3_SIG_SIZE; ret = BUFFER_E; } - else if ((key->level == 5) && (*sigLen < DILITHIUM_LEVEL5_SIG_SIZE)) { - *sigLen = DILITHIUM_LEVEL5_SIG_SIZE; + else if ((key->level == WC_ML_DSA_87) && + (*sigLen < ML_DSA_LEVEL5_SIG_SIZE)) { + *sigLen = ML_DSA_LEVEL5_SIG_SIZE; ret = BUFFER_E; } localOutLen = *sigLen; @@ -6643,13 +7866,13 @@ static int oqs_dilithium_verify_msg(const byte* sig, word32 sigLen, } if (ret == 0) { - if (key->level == 2) { + if (key->level == WC_ML_DSA_44) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_44_ipd); } - else if (key->level == 3) { + else if (key->level == WC_ML_DSA_65) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_65_ipd); } - else if (key->level == 5) { + else if (key->level == WC_ML_DSA_87) { oqssig = OQS_SIG_new(OQS_SIG_alg_ml_dsa_87_ipd); } else { @@ -6757,6 +7980,63 @@ int wc_dilithium_make_key_from_seed(dilithium_key* key, const byte* seed) #endif #ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* Sign the message using the dilithium private key. + * + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * msg [in] Message to sign. + * msgLen [in] Length of the message in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_ctx_msg(const byte* ctx, byte ctxLen, const byte* msg, + word32 msgLen, byte* sig, word32 *sigLen, dilithium_key* key, WC_RNG* rng) +{ + int ret = 0; + + /* Validate parameters. */ + if ((msg == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, rng, + WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_ctx_msg(key, rng, ctx, ctxLen, msg, msgLen, sig, + sigLen); + #elif defined(HAVE_LIBOQS) + ret = oqs_dilithium_sign_msg(msg, msgLen, sig, sigLen, key, rng); + #endif + } + + return ret; +} + /* Sign the message using the dilithium private key. * * msg [in] Message to sign. @@ -6807,6 +8087,97 @@ int wc_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, return ret; } +/* Sign the message hash using the dilithium private key. + * + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * hashAlg [in] Hash algorithm used on message. + * hash [in] Hash of message to sign. + * hashLen [in] Length of the message hash in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_ctx_hash(const byte* ctx, byte ctxLen, int hashAlg, + const byte* hash, word32 hashLen, byte* sig, word32 *sigLen, + dilithium_key* key, WC_RNG* rng) +{ + int ret = 0; + + /* Validate parameters. */ + if ((hash == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_ctx_hash(key, rng, ctx, ctxLen, hashAlg, hash, + hashLen, sig, sigLen); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)hashAlg; + (void)hash; + (void)hashLen; + (void)rng; + #endif + } + + return ret; +} + +/* Sign the message using the dilithium private key. + * + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * msg [in] Message to sign. + * msgLen [in] Length of the message in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_ctx_msg_with_seed(const byte* ctx, byte ctxLen, + const byte* msg, word32 msgLen, byte* sig, word32 *sigLen, + dilithium_key* key, const byte* seed) +{ + int ret = 0; + + /* Validate parameters. */ + if ((msg == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_ctx_msg_with_seed(key, seed, ctx, ctxLen, msg, + msgLen, sig, sigLen); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)msgLen; + (void)seed; + #endif + } + + return ret; +} + /* Sign the message using the dilithium private key. * * msg [in] Message to sign. @@ -6820,7 +8191,7 @@ int wc_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, * 0 otherwise. */ int wc_dilithium_sign_msg_with_seed(const byte* msg, word32 msgLen, byte* sig, - word32 *sigLen, dilithium_key* key, byte* seed) + word32 *sigLen, dilithium_key* key, const byte* seed) { int ret = 0; @@ -6842,9 +8213,100 @@ int wc_dilithium_sign_msg_with_seed(const byte* msg, word32 msgLen, byte* sig, return ret; } + +/* Sign the message using the dilithium private key. + * + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * hashAlg [in] Hash algorithm used on message. + * hash [in] Hash of message to sign. + * hashLen [in] Length of the message hash in bytes. + * sig [out] Buffer to write signature into. + * sigLen [in/out] On in, size of buffer. + * On out, the length of the signature in bytes. + * key [in] Dilithium key to use when signing + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when outLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_sign_ctx_hash_with_seed(const byte* ctx, byte ctxLen, + int hashAlg, const byte* hash, word32 hashLen, byte* sig, word32 *sigLen, + dilithium_key* key, const byte* seed) +{ + int ret = 0; + + /* Validate parameters. */ + if ((hash == NULL) || (sig == NULL) || (sigLen == NULL) || (key == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Sign message. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_sign_ctx_hash_with_seed(key, seed, ctx, ctxLen, + hashAlg, hash, hashLen, sig, sigLen); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)hashAlg; + (void)hash; + (void)hashLen; + (void)seed; + #endif + } + + return ret; +} #endif /* !WOLFSSL_DILITHIUM_NO_SIGN */ #ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* Verify the message using the dilithium public key. + * + * sig [in] Signature to verify. + * sigLen [in] Size of signature in bytes. + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * msg [in] Message to verify. + * msgLen [in] Length of the message in bytes. + * res [out] *res is set to 1 on successful verification. + * key [in] Dilithium key to use to verify. + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when sigLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_verify_ctx_msg(const byte* sig, word32 sigLen, const byte* ctx, + word32 ctxLen, const byte* msg, word32 msgLen, int* res, dilithium_key* key) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (msg == NULL) || (res == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Verify message with signature. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_verify_ctx_msg(key, ctx, ctxLen, msg, msgLen, sig, + sigLen, res); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)sigLen; + (void)msgLen; + (void)res; + #endif + } + + return ret; +} + /* Verify the message using the dilithium public key. * * sig [in] Signature to verify. @@ -6894,6 +8356,53 @@ int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, return ret; } + +/* Verify the message using the dilithium public key. + * + * sig [in] Signature to verify. + * sigLen [in] Size of signature in bytes. + * ctx [in] Context of signature. + * ctxLen [in] Length of context in bytes. + * hashAlg [in] Hash algorithm used on message. + * hash [in] Hash of message to verify. + * hashLen [in] Length of the message hash in bytes. + * res [out] *res is set to 1 on successful verification. + * key [in] Dilithium key to use to verify. + * returns BAD_FUNC_ARG when a parameter is NULL, public key not set + * or ctx is NULL and ctxLen is not 0, + * BUFFER_E when sigLen is less than DILITHIUM_LEVEL2_SIG_SIZE, + * 0 otherwise. + */ +int wc_dilithium_verify_ctx_hash(const byte* sig, word32 sigLen, + const byte* ctx, word32 ctxLen, int hashAlg, const byte* hash, + word32 hashLen, int* res, dilithium_key* key) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (sig == NULL) || (hash == NULL) || (res == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (ctx == NULL) && (ctxLen > 0)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Verify message with signature. */ + #ifdef WOLFSSL_WC_DILITHIUM + ret = dilithium_verify_ctx_hash(key, ctx, ctxLen, hashAlg, hash, + hashLen, sig, sigLen, res); + #elif defined(HAVE_LIBOQS) + ret = NOT_COMPILED_IN; + (void)sigLen; + (void)hashAlg; + (void)hash; + (void)hashLen; + #endif + } + + return ret; +} #endif /* WOLFSSL_DILITHIUM_NO_VERIFY */ /* Initialize the dilithium private/public key. @@ -6917,7 +8426,6 @@ int wc_dilithium_init_ex(dilithium_key* key, void* heap, int devId) { int ret = 0; - (void)heap; (void)devId; /* Validate parameters. */ @@ -6937,6 +8445,7 @@ int wc_dilithium_init_ex(dilithium_key* key, void* heap, int devId) key->idLen = 0; key->labelLen = 0; #endif + key->heap = heap; } return ret; @@ -6964,7 +8473,7 @@ int wc_dilithium_init_id(dilithium_key* key, const unsigned char* id, int len, } /* Set the maximum level here */ - wc_dilithium_set_level(key, 5); + wc_dilithium_set_level(key, WC_ML_DSA_87); return ret; } @@ -6994,7 +8503,7 @@ int wc_dilithium_init_label(dilithium_key* key, const char* label, void* heap, } /* Set the maximum level here */ - wc_dilithium_set_level(key, 5); + wc_dilithium_set_level(key, WC_ML_DSA_87); return ret; } @@ -7014,7 +8523,17 @@ int wc_dilithium_set_level(dilithium_key* key, byte level) if (key == NULL) { ret = BAD_FUNC_ARG; } - if ((ret == 0) && (level != 2) && (level != 3) && (level != 5)) { + if ((ret == 0) && ((level == WC_ML_DSA_44) || (level == WC_ML_DSA_65) || + (level == WC_ML_DSA_87))) { + /* Nothing to do. */ + } +#if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + else if ((ret == 0) && ((level == WC_ML_DSA_44_DRAFT) || + (level == WC_ML_DSA_65_DRAFT) || (level == WC_ML_DSA_87_DRAFT))) { + /* Nothing to do. */ + } +#endif + else { ret = BAD_FUNC_ARG; } @@ -7025,27 +8544,29 @@ int wc_dilithium_set_level(dilithium_key* key, byte level) } if (ret == 0) { /* Clear any cached items. */ +#ifndef WC_DILITHIUM_FIXED_ARRAY #ifdef WC_DILITHIUM_CACHE_MATRIX_A - XFREE(key->a, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->a, key->heap, DYNAMIC_TYPE_DILITHIUM); key->a = NULL; key->aSet = 0; #endif #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS - XFREE(key->s1, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->s1, key->heap, DYNAMIC_TYPE_DILITHIUM); key->s1 = NULL; key->s2 = NULL; key->t0 = NULL; key->privVecsSet = 0; #endif #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS - XFREE(key->t1, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->t1, key->heap, DYNAMIC_TYPE_DILITHIUM); key->t1 = NULL; key->pubVecSet = 0; #endif +#endif #endif /* WOLFSSL_WC_DILITHIUM */ /* Store level and indicate public and private key are not set. */ - key->level = level; + key->level = level % WC_ML_DSA_DRAFT; key->pubKeySet = 0; key->prvKeySet = 0; } @@ -7067,8 +8588,8 @@ int wc_dilithium_get_level(dilithium_key* key, byte* level) if ((key == NULL) || (level == NULL)) { ret = BAD_FUNC_ARG; } - if ((ret == 0) && (key->level != 2) && (key->level != 3) && - (key->level != 5)) { + if ((ret == 0) && (key->level != WC_ML_DSA_44) && + (key->level != WC_ML_DSA_65) && (key->level != WC_ML_DSA_87)) { ret = BAD_FUNC_ARG; } @@ -7088,16 +8609,18 @@ void wc_dilithium_free(dilithium_key* key) { if (key != NULL) { #ifdef WOLFSSL_WC_DILITHIUM +#ifndef WC_DILITHIUM_FIXED_ARRAY /* Dispose of cached items. */ #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS - XFREE(key->t1, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->t1, key->heap, DYNAMIC_TYPE_DILITHIUM); #endif #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS - XFREE(key->s1, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->s1, key->heap, DYNAMIC_TYPE_DILITHIUM); #endif #ifdef WC_DILITHIUM_CACHE_MATRIX_A - XFREE(key->a, NULL, WOLFSSL_WC_DILITHIUM); + XFREE(key->a, key->heap, DYNAMIC_TYPE_DILITHIUM); #endif +#endif /* Free the SHAKE-128/256 object. */ wc_Shake256_Free(&key->shake); #endif @@ -7115,17 +8638,32 @@ void wc_dilithium_free(dilithium_key* key) */ int wc_dilithium_size(dilithium_key* key) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (key != NULL) { - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = DILITHIUM_LEVEL2_KEY_SIZE; } - else if (key->level == 3) { - ret = DILITHIUM_LEVEL3_KEY_SIZE; + else if (key->params->level == WC_ML_DSA_65_DRAFT) { + ret = DILITHIUM_LEVEL3_KEY_SIZE; + } + else if (key->params->level == WC_ML_DSA_87_DRAFT) { + ret = DILITHIUM_LEVEL5_KEY_SIZE; + } + else + #endif + if (key->level == WC_ML_DSA_44) { + ret = ML_DSA_LEVEL2_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + ret = ML_DSA_LEVEL3_KEY_SIZE; } - else if (key->level == 5) { - ret = DILITHIUM_LEVEL5_KEY_SIZE; + else if (key->level == WC_ML_DSA_87) { + ret = ML_DSA_LEVEL5_KEY_SIZE; } } @@ -7141,18 +8679,32 @@ int wc_dilithium_size(dilithium_key* key) */ int wc_dilithium_priv_size(dilithium_key* key) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (key != NULL) { - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = DILITHIUM_LEVEL2_PRV_KEY_SIZE; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { ret = DILITHIUM_LEVEL3_PRV_KEY_SIZE; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { ret = DILITHIUM_LEVEL5_PRV_KEY_SIZE; } + #endif + if (key->level == WC_ML_DSA_44) { + ret = ML_DSA_LEVEL2_PRV_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + ret = ML_DSA_LEVEL3_PRV_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_87) { + ret = ML_DSA_LEVEL5_PRV_KEY_SIZE; + } } return ret; @@ -7188,18 +8740,33 @@ int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len) */ int wc_dilithium_pub_size(dilithium_key* key) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (key != NULL) { - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = DILITHIUM_LEVEL2_PUB_KEY_SIZE; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { ret = DILITHIUM_LEVEL3_PUB_KEY_SIZE; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { ret = DILITHIUM_LEVEL5_PUB_KEY_SIZE; } + else + #endif + if (key->level == WC_ML_DSA_44) { + ret = ML_DSA_LEVEL2_PUB_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + ret = ML_DSA_LEVEL3_PUB_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_87) { + ret = ML_DSA_LEVEL5_PUB_KEY_SIZE; + } } return ret; @@ -7234,18 +8801,33 @@ int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len) */ int wc_dilithium_sig_size(dilithium_key* key) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); if (key != NULL) { - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = DILITHIUM_LEVEL2_SIG_SIZE; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { ret = DILITHIUM_LEVEL3_SIG_SIZE; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { ret = DILITHIUM_LEVEL5_SIG_SIZE; } + else + #endif + if (key->level == WC_ML_DSA_44) { + ret = ML_DSA_LEVEL2_SIG_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + ret = ML_DSA_LEVEL3_SIG_SIZE; + } + else if (key->level == WC_ML_DSA_87) { + ret = ML_DSA_LEVEL5_SIG_SIZE; + } } return ret; @@ -7321,7 +8903,7 @@ int wc_dilithium_check_key(dilithium_key* key) #endif /* Allocate memory for large intermediates. */ - s1 = (sword32*)XMALLOC(allocSz, NULL, DYNAMIC_TYPE_DILITHIUM); + s1 = (sword32*)XMALLOC(allocSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (s1 == NULL) { ret = MEMORY_E; } @@ -7347,7 +8929,7 @@ int wc_dilithium_check_key(dilithium_key* key) const byte* pub_seed = key->p; ret = dilithium_expand_a(&key->shake, pub_seed, params->k, - params->l, a); + params->l, a, key->heap); #ifdef WC_DILITHIUM_CACHE_MATRIX_A key->aSet = (ret == 0); #endif @@ -7400,8 +8982,10 @@ int wc_dilithium_check_key(dilithium_key* key) } } - /* Dispose of allocated memory. */ - XFREE(s1, NULL, DYNAMIC_TYPE_DILITHIUM); + if (key != NULL) { + /* Dispose of allocated memory. */ + XFREE(s1, key->heap, DYNAMIC_TYPE_DILITHIUM); + } #else /* Validate parameter. */ if (key == NULL) { @@ -7456,7 +9040,11 @@ int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen) if (ret == 0) { /* Get length passed in for checking. */ inLen = *outLen; - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { /* Set out length. */ *outLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; /* Validate length passed in. */ @@ -7464,7 +9052,7 @@ int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen) ret = BUFFER_E; } } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { /* Set out length. */ *outLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; /* Validate length passed in. */ @@ -7472,7 +9060,7 @@ int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen) ret = BUFFER_E; } } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { /* Set out length. */ *outLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; /* Validate length passed in. */ @@ -7480,6 +9068,32 @@ int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen) ret = BUFFER_E; } } + else + #endif + if (key->level == WC_ML_DSA_44) { + /* Set out length. */ + *outLen = ML_DSA_LEVEL2_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < ML_DSA_LEVEL2_PUB_KEY_SIZE) { + ret = BUFFER_E; + } + } + else if (key->level == WC_ML_DSA_65) { + /* Set out length. */ + *outLen = ML_DSA_LEVEL3_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < ML_DSA_LEVEL3_PUB_KEY_SIZE) { + ret = BUFFER_E; + } + } + else if (key->level == WC_ML_DSA_87) { + /* Set out length. */ + *outLen = ML_DSA_LEVEL5_PUB_KEY_SIZE; + /* Validate length passed in. */ + if (inLen < ML_DSA_LEVEL5_PUB_KEY_SIZE) { + ret = BUFFER_E; + } + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -7518,24 +9132,48 @@ int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key) ret = BAD_FUNC_ARG; } if (ret == 0) { - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { /* Check length. */ if (inLen != DILITHIUM_LEVEL2_PUB_KEY_SIZE) { ret = BAD_FUNC_ARG; } } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { /* Check length. */ if (inLen != DILITHIUM_LEVEL3_PUB_KEY_SIZE) { ret = BAD_FUNC_ARG; } } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { /* Check length. */ if (inLen != DILITHIUM_LEVEL5_PUB_KEY_SIZE) { ret = BAD_FUNC_ARG; } } + else + #endif + if (key->level == WC_ML_DSA_44) { + /* Check length. */ + if (inLen != ML_DSA_LEVEL2_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } + else if (key->level == WC_ML_DSA_65) { + /* Check length. */ + if (inLen != ML_DSA_LEVEL3_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } + else if (key->level == WC_ML_DSA_87) { + /* Check length. */ + if (inLen != ML_DSA_LEVEL5_PUB_KEY_SIZE) { + ret = BAD_FUNC_ARG; + } + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -7550,40 +9188,44 @@ int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key) key->p = in; #endif - #ifdef WC_DILITHIUM_CACHE_PUB_VECTORS +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + #ifndef WC_DILITHIUM_FIXED_ARRAY /* Allocate t1 if required. */ if (key->t1 == NULL) { - key->t1 = (sword32*)XMALLOC(key->params->s2Sz, NULL, + key->t1 = (sword32*)XMALLOC(key->params->s2Sz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (key->t1 == NULL) { ret = MEMORY_E; } } + #endif } if (ret == 0) { /* Compute t1 from public key data. */ dilithium_make_pub_vec(key, key->t1); - #endif - #ifdef WC_DILITHIUM_CACHE_MATRIX_A +#endif +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + #ifndef WC_DILITHIUM_FIXED_ARRAY /* Allocate matrix a if required. */ if (key->a == NULL) { - key->a = (sword32*)XMALLOC(key->params->aSz, NULL, + key->a = (sword32*)XMALLOC(key->params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (key->a == NULL) { ret = MEMORY_E; } } + #endif } if (ret == 0) { /* Compute matrix a from public key data. */ ret = dilithium_expand_a(&key->shake, key->p, key->params->k, - key->params->l, key->a); + key->params->l, key->a, key->heap); if (ret == 0) { key->aSet = 1; } } if (ret == 0) { - #endif +#endif /* Public key is set. */ key->pubKeySet = 1; } @@ -7614,9 +9256,9 @@ static int dilithium_set_priv_key(const byte* priv, word32 privSz, #endif /* Validate parameters. */ - if ((privSz != DILITHIUM_LEVEL2_KEY_SIZE) && - (privSz != DILITHIUM_LEVEL3_KEY_SIZE) && - (privSz != DILITHIUM_LEVEL5_KEY_SIZE)) { + if ((privSz != ML_DSA_LEVEL2_KEY_SIZE) && + (privSz != ML_DSA_LEVEL3_KEY_SIZE) && + (privSz != ML_DSA_LEVEL5_KEY_SIZE)) { ret = BAD_FUNC_ARG; } @@ -7631,39 +9273,44 @@ static int dilithium_set_priv_key(const byte* priv, word32 privSz, /* Allocate and create cached values. */ #ifdef WC_DILITHIUM_CACHE_MATRIX_A +#ifndef WC_DILITHIUM_FIXED_ARRAY if (ret == 0) { /* Allocate matrix a if required. */ if (key->a == NULL) { - key->a = (sword32*)XMALLOC(params->aSz, NULL, + key->a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM); if (key->a == NULL) { ret = MEMORY_E; } } } +#endif if (ret == 0) { /* Compute matrix a from private key data. */ ret = dilithium_expand_a(&key->shake, key->k, params->k, params->l, - key->a); + key->a, key->heap); if (ret == 0) { key->aSet = 1; } } #endif #ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS +#ifndef WC_DILITHIUM_FIXED_ARRAY if ((ret == 0) && (key->s1 == NULL)) { /* Allocate L vector s1, K vector s2 and K vector t0 if required. */ key->s1 = (sword32*)XMALLOC(params->s1Sz + params->s2Sz + params->s2Sz, - NULL, DYNAMIC_TYPE_DILITHIUM); - if (key->s1 == NULL) { + key->heap, DYNAMIC_TYPE_DILITHIUM); + if (key->s1 == NULL) { ret = MEMORY_E; } + if (ret == 0) { + /* Set pointers into allocated memory. */ + key->s2 = key->s1 + params->s1Sz / sizeof(*key->s1); + key->t0 = key->s2 + params->s2Sz / sizeof(*key->s2); + } } +#endif if (ret == 0) { - /* Set pointers into allocated memory. */ - key->s2 = key->s1 + params->s1Sz / sizeof(*key->s1); - key->t0 = key->s2 + params->s2Sz / sizeof(*key->s2); - /* Compute vectors from private key. */ dilithium_make_priv_vecs(key, key->s1, key->s2, key->t0); } @@ -7694,8 +9341,8 @@ int wc_dilithium_import_private(const byte* priv, word32 privSz, if ((priv == NULL) || (key == NULL)) { ret = BAD_FUNC_ARG; } - if ((ret == 0) && (key->level != 2) && (key->level != 3) && - (key->level != 5)) { + if ((ret == 0) && (key->level != WC_ML_DSA_44) && + (key->level != WC_ML_DSA_65) && (key->level != WC_ML_DSA_87)) { ret = BAD_FUNC_ARG; } @@ -7731,8 +9378,8 @@ int wc_dilithium_import_key(const byte* priv, word32 privSz, if ((pub == NULL) && (pubSz != 0)) { ret = BAD_FUNC_ARG; } - if ((ret == 0) && (key->level != 2) && (key->level != 3) && - (key->level != 5)) { + if ((ret == 0) && (key->level != WC_ML_DSA_44) && + (key->level != WC_ML_DSA_65) && (key->level != WC_ML_DSA_87)) { ret = BAD_FUNC_ARG; } @@ -7777,15 +9424,30 @@ int wc_dilithium_export_private(dilithium_key* key, byte* out, if (ret == 0) { inLen = *outLen; /* check and set up out length */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { *outLen = DILITHIUM_LEVEL2_KEY_SIZE; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { *outLen = DILITHIUM_LEVEL3_KEY_SIZE; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { *outLen = DILITHIUM_LEVEL5_KEY_SIZE; } + else + #endif + if (key->level == WC_ML_DSA_44) { + *outLen = ML_DSA_LEVEL2_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + *outLen = ML_DSA_LEVEL3_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_87) { + *outLen = ML_DSA_LEVEL5_KEY_SIZE; + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -7870,15 +9532,30 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, if (ret == 0) { /* Get OID sum for level. */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { keytype = DILITHIUM_LEVEL2k; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { keytype = DILITHIUM_LEVEL3k; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { keytype = DILITHIUM_LEVEL5k; } + else + #endif + if (key->level == WC_ML_DSA_44) { + keytype = ML_DSA_LEVEL2k; + } + else if (key->level == WC_ML_DSA_65) { + keytype = ML_DSA_LEVEL3k; + } + else if (key->level == WC_ML_DSA_87) { + keytype = ML_DSA_LEVEL5k; + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -7892,24 +9569,48 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, } if ((ret == 0) && (pubKey == NULL) && (pubKeyLen == 0)) { /* Check if the public key is included in the private key. */ - if ((key->level == 2) && + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if ((key->params->level == WC_ML_DSA_44_DRAFT) && (privKeyLen == DILITHIUM_LEVEL2_PRV_KEY_SIZE)) { pubKey = privKey + DILITHIUM_LEVEL2_KEY_SIZE; pubKeyLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; privKeyLen -= DILITHIUM_LEVEL2_PUB_KEY_SIZE; } - else if ((key->level == 3) && + else if ((key->params->level == WC_ML_DSA_65_DRAFT) && (privKeyLen == DILITHIUM_LEVEL3_PRV_KEY_SIZE)) { pubKey = privKey + DILITHIUM_LEVEL3_KEY_SIZE; pubKeyLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; privKeyLen -= DILITHIUM_LEVEL3_PUB_KEY_SIZE; } - else if ((key->level == 5) && + else if ((key->params->level == WC_ML_DSA_87_DRAFT) && (privKeyLen == DILITHIUM_LEVEL5_PRV_KEY_SIZE)) { pubKey = privKey + DILITHIUM_LEVEL5_KEY_SIZE; pubKeyLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; privKeyLen -= DILITHIUM_LEVEL5_PUB_KEY_SIZE; } + else + #endif + if ((key->level == WC_ML_DSA_44) && + (privKeyLen == ML_DSA_LEVEL2_PRV_KEY_SIZE)) { + pubKey = privKey + ML_DSA_LEVEL2_KEY_SIZE; + pubKeyLen = ML_DSA_LEVEL2_PUB_KEY_SIZE; + privKeyLen -= ML_DSA_LEVEL2_PUB_KEY_SIZE; + } + else if ((key->level == WC_ML_DSA_65) && + (privKeyLen == ML_DSA_LEVEL3_PRV_KEY_SIZE)) { + pubKey = privKey + ML_DSA_LEVEL3_KEY_SIZE; + pubKeyLen = ML_DSA_LEVEL3_PUB_KEY_SIZE; + privKeyLen -= ML_DSA_LEVEL3_PUB_KEY_SIZE; + } + else if ((key->level == WC_ML_DSA_87) && + (privKeyLen == ML_DSA_LEVEL5_PRV_KEY_SIZE)) { + pubKey = privKey + ML_DSA_LEVEL5_KEY_SIZE; + pubKeyLen = ML_DSA_LEVEL5_PUB_KEY_SIZE; + privKeyLen -= ML_DSA_LEVEL5_PUB_KEY_SIZE; + } } if (ret == 0) { @@ -7938,8 +9639,118 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, #endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ + #ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY +#if defined(WOLFSSL_DILITHIUM_NO_ASN1) +#ifndef WOLFSSL_NO_ML_DSA_44 +static unsigned char ml_dsa_oid_44[] = { + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x11 +}; +#if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) +static unsigned char dilithium_oid_44[] = { + 0x2b, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0b, + 0x0c, 0x04, 0x04 +}; +#endif +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 +static unsigned char ml_dsa_oid_65[] = { + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x12 +}; +#if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) +static unsigned char dilithium_oid_65[] = { + 0x2b, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0b, + 0x0c, 0x06, 0x05 +}; +#endif +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 +static unsigned char ml_dsa_oid_87[] = { + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13 +}; +#if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) +static unsigned char dilithium_oid_87[] = { + 0x2b, 0x06, 0x01, 0x04, 0x01, 0x02, 0x82, 0x0b, + 0x0c, 0x08, 0x07 +}; +#endif +#endif + +static int dilitihium_get_der_length(const byte* input, word32* inOutIdx, + int *length, word32 inSz) +{ + int ret = 0; + word32 idx = *inOutIdx; + word32 len = 0; + + if (idx >= inSz) { + ret = ASN_PARSE_E; + } + else if (input[idx] < 0x80) { + len = input[idx]; + idx++; + } + else if ((input[idx] == 0x80) || (input[idx] >= 0x83)) { + ret = ASN_PARSE_E; + } + else if (input[idx] == 0x81) { + if (idx + 1 >= inSz) { + ret = ASN_PARSE_E; + } + else if (input[idx + 1] < 0x80) { + ret = ASN_PARSE_E; + } + else { + len = input[idx + 1]; + idx += 2; + } + } + else if (input[idx] == 0x82) { + if (idx + 2 >= inSz) { + ret = ASN_PARSE_E; + } + else { + len = ((word16)input[idx + 1] << 8) + input[idx + 2]; + idx += 3; + if (len < 0x100) { + ret = ASN_PARSE_E; + } + } + } + + if ((ret == 0) && ((idx + len) > inSz)) { + ret = ASN_PARSE_E; + } + + *length = (int)len; + *inOutIdx = idx; + return ret; +} + +static int dilithium_check_type(const byte* input, word32* inOutIdx, byte type, + word32 inSz) +{ + int ret = 0; + word32 idx = *inOutIdx; + + if (idx >= inSz) { + ret = ASN_PARSE_E; + } + else if (input[idx] != type){ + ret = ASN_PARSE_E; + } + else { + idx++; + } + + *inOutIdx = idx; + return ret; +} + +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ + /* Decode the DER encoded Dilithium public key. * * @param [in] input Array holding DER encoded data. @@ -7958,7 +9769,6 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, int ret = 0; const byte* pubKey; word32 pubKeyLen = 0; - int keytype = 0; /* Validate parameters. */ if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) { @@ -7969,19 +9779,44 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, /* Try to import the key directly. */ ret = wc_dilithium_import_public(input, inSz, key); if (ret != 0) { + #if !defined(WOLFSSL_DILITHIUM_NO_ASN1) + int keytype = 0; + #else + int length; + unsigned char* oid; + int oidLen; + word32 idx = 0; + #endif + /* Start again. */ ret = 0; + #if !defined(WOLFSSL_DILITHIUM_NO_ASN1) /* Get OID sum for level. */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { keytype = DILITHIUM_LEVEL2k; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { keytype = DILITHIUM_LEVEL3k; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { keytype = DILITHIUM_LEVEL5k; } + else + #endif + if (key->level == WC_ML_DSA_44) { + keytype = ML_DSA_LEVEL2k; + } + else if (key->level == WC_ML_DSA_65) { + keytype = ML_DSA_LEVEL3k; + } + else if (key->level == WC_ML_DSA_87) { + keytype = ML_DSA_LEVEL5k; + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -7991,6 +9826,104 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKey, &pubKeyLen, keytype); } + #else + /* Get OID sum for level. */ + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else + #ifndef WOLFSSL_NO_ML_DSA_44 + if (key->params->level == WC_ML_DSA_44_DRAFT) { + oid = dilithium_oid_44; + oidLen = (int)sizeof(dilithium_oid_44); + } + else + #endif + #ifndef WOLFSSL_NO_ML_DSA_65 + if (key->params->level == WC_ML_DSA_65_DRAFT) { + oid = dilithium_oid_65; + oidLen = (int)sizeof(dilithium_oid_65); + } + else + #endif + #ifndef WOLFSSL_NO_ML_DSA_87 + if (key->params->level == WC_ML_DSA_87_DRAFT) { + oid = dilithium_oid_87; + oidLen = (int)sizeof(dilithium_oid_87); + } + else + #endif + #endif + #ifndef WOLFSSL_NO_ML_DSA_44 + if (key->level == WC_ML_DSA_44) { + oid = ml_dsa_oid_44; + oidLen = (int)sizeof(ml_dsa_oid_44); + } + else + #endif + #ifndef WOLFSSL_NO_ML_DSA_65 + if (key->level == WC_ML_DSA_65) { + oid = ml_dsa_oid_65; + oidLen = (int)sizeof(ml_dsa_oid_65); + } + else + #endif + #ifndef WOLFSSL_NO_ML_DSA_87 + if (key->level == WC_ML_DSA_87) { + oid = ml_dsa_oid_87; + oidLen = (int)sizeof(ml_dsa_oid_87); + } + else + #endif + { + /* Level not set. */ + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + ret = dilithium_check_type(input, &idx, 0x30, inSz); + } + if (ret == 0) { + ret = dilitihium_get_der_length(input, &idx, &length, inSz); + } + if (ret == 0) { + ret = dilithium_check_type(input, &idx, 0x30, inSz); + } + if (ret == 0) { + ret = dilitihium_get_der_length(input, &idx, &length, inSz); + } + if (ret == 0) { + ret = dilithium_check_type(input, &idx, 0x06, inSz); + } + if (ret == 0) { + ret = dilitihium_get_der_length(input, &idx, &length, inSz); + } + if (ret == 0) { + if ((length != oidLen) || + (XMEMCMP(input + idx, oid, oidLen) != 0)) { + ret = ASN_PARSE_E; + } + idx += oidLen; + } + if (ret == 0) { + ret = dilithium_check_type(input, &idx, 0x03, inSz); + } + if (ret == 0) { + ret = dilitihium_get_der_length(input, &idx, &length, inSz); + } + if (ret == 0) { + if ((input[idx] != 0) || (length == 0)) { + ret = ASN_PARSE_E; + } + idx++; + length--; + } + if (ret == 0) { + /* This is the raw point data compressed or uncompressed. */ + pubKeyLen = (word32)length; + pubKey = input + idx; + } + #endif if (ret == 0) { /* Import public key data. */ ret = wc_dilithium_import_public(pubKey, pubKeyLen, key); @@ -8000,6 +9933,8 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, return ret; } +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 + #ifdef WC_ENABLE_ASYM_KEY_EXPORT /* Encode the public part of a Dilithium key in DER. * @@ -8031,18 +9966,36 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, if (ret == 0) { /* Get OID and length for level. */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { keytype = DILITHIUM_LEVEL2k; pubKeyLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { keytype = DILITHIUM_LEVEL3k; pubKeyLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { keytype = DILITHIUM_LEVEL5k; pubKeyLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; } + else + #endif + if (key->level == WC_ML_DSA_44) { + keytype = ML_DSA_LEVEL2k; + pubKeyLen = ML_DSA_LEVEL2_PUB_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_65) { + keytype = ML_DSA_LEVEL3k; + pubKeyLen = ML_DSA_LEVEL3_PUB_KEY_SIZE; + } + else if (key->level == WC_ML_DSA_87) { + keytype = ML_DSA_LEVEL5k; + pubKeyLen = ML_DSA_LEVEL5_PUB_KEY_SIZE; + } else { /* Level not set. */ ret = BAD_FUNC_ARG; @@ -8058,10 +10011,14 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, } #endif /* WC_ENABLE_ASYM_KEY_EXPORT */ +#endif /* !WOLFSSL_DILITHIUM_NO_ASN1 */ + #endif /* WOLFSSL_DILITHIUM_PUBLIC_KEY */ #ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 + #ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY /* Encode the private and public data of a Dilithium key in DER. * @@ -8076,23 +10033,41 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, */ int wc_Dilithium_KeyToDer(dilithium_key* key, byte* output, word32 len) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Validate parameters and check public and private key set. */ if ((key != NULL) && key->prvKeySet && key->pubKeySet) { /* Create DER for level. */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, key->p, DILITHIUM_LEVEL2_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL2k); } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, key->p, DILITHIUM_LEVEL3_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL3k); } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, key->p, DILITHIUM_LEVEL5_PUB_KEY_SIZE, output, len, DILITHIUM_LEVEL5k); } + else + #endif + if (key->level == WC_ML_DSA_44) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL2_KEY_SIZE, key->p, + ML_DSA_LEVEL2_PUB_KEY_SIZE, output, len, ML_DSA_LEVEL2k); + } + else if (key->level == WC_ML_DSA_65) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL3_KEY_SIZE, key->p, + ML_DSA_LEVEL3_PUB_KEY_SIZE, output, len, ML_DSA_LEVEL3k); + } + else if (key->level == WC_ML_DSA_87) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL5_KEY_SIZE, key->p, + ML_DSA_LEVEL5_PUB_KEY_SIZE, output, len, ML_DSA_LEVEL5k); + } } return ret; @@ -8112,30 +10087,48 @@ int wc_Dilithium_KeyToDer(dilithium_key* key, byte* output, word32 len) */ int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, word32 len) { - int ret = BAD_FUNC_ARG; + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Validate parameters and check private key set. */ if ((key != NULL) && key->prvKeySet) { /* Create DER for level. */ - if (key->level == 2) { + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL2_KEY_SIZE, NULL, 0, output, len, DILITHIUM_LEVEL2k); } - else if (key->level == 3) { + else if (key->params->level == WC_ML_DSA_65_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL3_KEY_SIZE, NULL, 0, output, len, DILITHIUM_LEVEL3k); } - else if (key->level == 5) { + else if (key->params->level == WC_ML_DSA_87_DRAFT) { ret = SetAsymKeyDer(key->k, DILITHIUM_LEVEL5_KEY_SIZE, NULL, 0, output, len, DILITHIUM_LEVEL5k); } + else + #endif + if (key->level == WC_ML_DSA_44) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL2_KEY_SIZE, NULL, 0, output, + len, ML_DSA_LEVEL2k); + } + else if (key->level == WC_ML_DSA_65) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL3_KEY_SIZE, NULL, 0, output, + len, ML_DSA_LEVEL3k); + } + else if (key->level == WC_ML_DSA_87) { + ret = SetAsymKeyDer(key->k, ML_DSA_LEVEL5_KEY_SIZE, NULL, 0, output, + len, ML_DSA_LEVEL5k); + } } return ret; } -#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ - #endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ +#endif /* WOLFSSL_DILITHIUM_PRIVATE_KEY */ + #endif /* HAVE_DILITHIUM */ diff --git a/src/wolfcrypt/src/dsa.c b/src/wolfcrypt/src/dsa.c index c1606b3..6ed4435 100644 --- a/src/wolfcrypt/src/dsa.c +++ b/src/wolfcrypt/src/dsa.c @@ -1,6 +1,6 @@ /* dsa.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -542,7 +542,7 @@ int wc_DsaExportParamsRaw(DsaKey* dsa, byte* p, word32* pSz, *pSz = pLen; *qSz = qLen; *gSz = gLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (p == NULL || q == NULL || g == NULL) @@ -616,7 +616,7 @@ int wc_DsaExportKeyRaw(DsaKey* dsa, byte* x, word32* xSz, byte* y, word32* ySz) if (x == NULL && y == NULL) { *xSz = xLen; *ySz = yLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (x == NULL || y == NULL) diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index ee1e7b7..da6505c 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -1,6 +1,6 @@ /* ecc.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -236,14 +236,6 @@ ECC Curve Sizes: #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif -#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) - #define GEN_MEM_ERR MP_MEM -#elif defined(USE_FAST_MATH) - #define GEN_MEM_ERR FP_MEM -#else - #define GEN_MEM_ERR MP_MEM -#endif - #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ !defined(WOLFSSL_KCAPI_ECC) && !defined(WOLFSSL_SE050) && \ @@ -864,6 +856,14 @@ enum { /* This holds the key settings. ***MUST*** be organized by size from smallest to largest. */ +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0) + #undef ecc_sets + #undef ecc_sets_count +#endif + +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0) +static +#endif const ecc_set_type ecc_sets[] = { #ifdef ECC112 #ifndef NO_ECC_SECP @@ -1407,8 +1407,17 @@ const ecc_set_type ecc_sets[] = { } }; #define ECC_SET_COUNT (sizeof(ecc_sets)/sizeof(ecc_set_type)) +#if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0) +static +#endif const size_t ecc_sets_count = ECC_SET_COUNT - 1; +const ecc_set_type *wc_ecc_get_sets(void) { + return ecc_sets; +} +size_t wc_ecc_get_sets_count(void) { + return ecc_sets_count; +} #ifdef HAVE_OID_ENCODING /* encoded OID cache */ @@ -1417,7 +1426,13 @@ const size_t ecc_sets_count = ECC_SET_COUNT - 1; byte oid[ECC_MAX_OID_LEN]; } oid_cache_t; static oid_cache_t ecc_oid_cache[ECC_SET_COUNT]; + + static wolfSSL_Mutex ecc_oid_cache_lock + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(ecc_oid_cache_lock); +#ifndef WOLFSSL_MUTEX_INITIALIZER + static volatile int eccOidLockInit = 0; #endif +#endif /* HAVE_OID_ENCODING */ /* Forward declarations */ #if defined(HAVE_COMP_KEY) && defined(HAVE_ECC_KEY_EXPORT) @@ -2491,8 +2506,7 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, } if (err == MP_OKAY && mp_iszero((MP_INT_SIZE*)t2)) { /* T2 = X * X */ - if (err == MP_OKAY) - err = mp_sqr(x, t2); + err = mp_sqr(x, t2); if (err == MP_OKAY) err = mp_montgomery_reduce(t2, modulus, mp); /* T1 = T2 + T1 */ @@ -2506,8 +2520,7 @@ static int _ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, /* use "a" in calc */ /* T2 = T1 * T1 */ - if (err == MP_OKAY) - err = mp_sqr(t1, t2); + err = mp_sqr(t1, t2); if (err == MP_OKAY) err = mp_montgomery_reduce(t2, modulus, mp); /* T1 = T2 * a */ @@ -2904,7 +2917,7 @@ int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct) if ((mp_count_bits(modulus) == 256) && (!mp_is_bit_set(modulus, 224))) { err = sp_ecc_map_sm2_256(P->x, P->y, P->z); } -#elif defined(WOLFSSL_SP_NO_256) +#elif !defined(WOLFSSL_SP_NO_256) if (mp_count_bits(modulus) == 256) { err = sp_ecc_map_256(P->x, P->y, P->z); } @@ -3653,17 +3666,12 @@ static void ecc_key_tmp_final(ecc_key* key, void* heap) FREE_MP_INT_SIZE(key->t1, heap, DYNAMIC_TYPE_ECC); #else #ifdef ALT_ECC_SIZE - if (key->z != NULL) - XFREE(key->z, heap, DYNAMIC_TYPE_ECC); - if (key->y != NULL) - XFREE(key->y, heap, DYNAMIC_TYPE_ECC); - if (key->x != NULL) - XFREE(key->x, heap, DYNAMIC_TYPE_ECC); + XFREE(key->z, heap, DYNAMIC_TYPE_ECC); + XFREE(key->y, heap, DYNAMIC_TYPE_ECC); + XFREE(key->x, heap, DYNAMIC_TYPE_ECC); #endif - if (key->t2 != NULL) - XFREE(key->t2, heap, DYNAMIC_TYPE_ECC); - if (key->t1 != NULL) - XFREE(key->t1, heap, DYNAMIC_TYPE_ECC); + XFREE(key->t2, heap, DYNAMIC_TYPE_ECC); + XFREE(key->t1, heap, DYNAMIC_TYPE_ECC); #endif } #endif /* WOLFSSL_SMALL_STACK_CACHE */ @@ -4084,24 +4092,24 @@ static int wc_ecc_new_point_ex(ecc_point** point, void* heap) } p = *point; -#ifndef WOLFSSL_NO_MALLOC if (p == NULL) { p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC); } -#endif if (p == NULL) { return MEMORY_E; } XMEMSET(p, 0, sizeof(ecc_point)); + if (*point == NULL) + p->isAllocated = 1; + #ifndef ALT_ECC_SIZE err = mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL); if (err != MP_OKAY) { WOLFSSL_MSG("mp_init_multi failed."); - #ifndef WOLFSSL_NO_MALLOC - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - return err; + if (p->isAllocated) + XFREE(p, heap, DYNAMIC_TYPE_ECC); + p = NULL; } #else p->x = (mp_int*)&p->xyz[0]; @@ -4140,9 +4148,8 @@ static void wc_ecc_del_point_ex(ecc_point* p, void* heap) mp_clear(p->x); mp_clear(p->y); mp_clear(p->z); - #ifndef WOLFSSL_NO_MALLOC - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif + if (p->isAllocated) + XFREE(p, heap, DYNAMIC_TYPE_ECC); } (void)heap; } @@ -4255,7 +4262,7 @@ int wc_ecc_get_curve_idx(int curve_id) int wc_ecc_get_curve_id(int curve_idx) { - if (wc_ecc_is_valid_idx(curve_idx)) { + if (wc_ecc_is_valid_idx(curve_idx) && curve_idx >= 0) { return ecc_sets[curve_idx].id; } return ECC_CURVE_INVALID; @@ -4547,13 +4554,11 @@ int wc_ecc_get_curve_id_from_oid(const byte* oid, word32 len) } #endif -#if !defined(HAVE_OID_ENCODING) && !defined(HAVE_OID_DECODING) if (len == 0) { /* SAKKE has zero oidSz and will otherwise match with len==0. */ WOLFSSL_MSG("zero oidSz"); return ECC_CURVE_INVALID; } -#endif for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { #if defined(HAVE_OID_ENCODING) && !defined(HAVE_OID_DECODING) @@ -4981,8 +4986,7 @@ int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, if (k == k_lcl) mp_clear(k); #ifdef WOLFSSL_SMALL_STACK - if (k_lcl != NULL) - XFREE(k_lcl, private_key->heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(k_lcl, private_key->heap, DYNAMIC_TYPE_ECC_BUFFER); #endif #endif @@ -5526,7 +5530,7 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, /* Map in a separate call as this should be constant time */ err = wc_ecc_mulmod_ex2(ecc_get_k(key), base, pub, curve->Af, curve->prime, curve->order, rng, 0, key->heap); - if (err == MP_MEM) { + if (err == WC_NO_ERR_TRACE(MP_MEM)) { err = MEMORY_E; } } @@ -5542,7 +5546,7 @@ static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curve, if (err != MP_OKAY #ifdef WOLFSSL_ASYNC_CRYPT - && err != WC_PENDING_E + && err != WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { /* clean up if failed */ @@ -5996,7 +6000,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, if (err == MP_OKAY #ifdef WOLFSSL_ASYNC_CRYPT - || err == WC_PENDING_E + || err == WC_NO_ERR_TRACE(WC_PENDING_E) #endif ) { key->type = ECC_PRIVATEKEY; @@ -6395,9 +6399,6 @@ static int wc_ecc_get_curve_order_bit_count(const ecc_set_type* dp) #ifdef HAVE_ECC_SIGN -#ifndef NO_ASN - - #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \ defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL) || \ defined(WOLFSSL_SILABS_SE_ACCEL) || defined(WOLFSSL_KCAPI_ECC) || \ @@ -6722,6 +6723,9 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, DECL_MP_INT_SIZE_DYN(r, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); DECL_MP_INT_SIZE_DYN(s, ECC_KEY_MAX_BITS(key), MAX_ECC_BITS_USE); #endif +#ifdef NO_ASN + word32 keySz; +#endif if (in == NULL || out == NULL || outlen == NULL || key == NULL) { return ECC_BAD_ARG_E; @@ -6758,17 +6762,17 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, #else NEW_MP_INT_SIZE(r, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, DYNAMIC_TYPE_ECC); -#ifdef MP_INT_SIZE_CHECK_NULL + #ifdef MP_INT_SIZE_CHECK_NULL if (r == NULL) return MEMORY_E; -#endif + #endif NEW_MP_INT_SIZE(s, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, DYNAMIC_TYPE_ECC); -#ifdef MP_INT_SIZE_CHECK_NULL + #ifdef MP_INT_SIZE_CHECK_NULL if (s == NULL) { FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return MEMORY_E; } -#endif + #endif err = INIT_MP_INT_SIZE(r, ECC_KEY_MAX_BITS_NONULLCHECK(key)); if (err != 0) { @@ -6800,8 +6804,26 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, return err; } +#ifndef NO_ASN /* encoded with DSA header */ err = StoreECC_DSA_Sig(out, outlen, r, s); +#else + /* No support for DSA ASN.1 header. + * Signature will be r+s directly. */ + keySz = 0; + if (key->dp != NULL) { + keySz = (word32)key->dp->size; + } + if (keySz <= 0) { + WOLFSSL_MSG("Error: ECDSA sign raw signature size"); + return WC_NO_ERR_TRACE(ECC_BAD_ARG_E); + } + *outlen = keySz * 2; + + /* Export signature into r,s */ + mp_to_unsigned_bin_len(r, out, keySz); + mp_to_unsigned_bin_len(s, out + keySz, keySz); +#endif /* !NO_ASN */ /* cleanup */ mp_clear(r); @@ -6813,7 +6835,6 @@ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, return err; #endif /* !WOLF_CRYPTO_CB_ONLY_ECC */ } -#endif /* !NO_ASN */ #if defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) @@ -6837,13 +6858,17 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) if (key->sign_k == NULL) { key->sign_k = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + if (key->sign_k != NULL) { + err = mp_init(key->sign_k); + if (err != MP_OKAY) { + XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC); + key->sign_k = NULL; + } + } } - if (key->sign_k != NULL) { - /* currently limiting to SHA256 for auto create */ - if (mp_init(key->sign_k) != MP_OKAY || - wc_ecc_gen_deterministic_k(in, inlen, - WC_HASH_TYPE_SHA256, ecc_get_k(key), key->sign_k, + if (wc_ecc_gen_deterministic_k(in, inlen, + key->hashType, ecc_get_k(key), key->sign_k, curve->order, key->heap) != 0) { mp_free(key->sign_k); XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC); @@ -6861,8 +6886,7 @@ static int deterministic_sign_helper(const byte* in, word32 inlen, ecc_key* key) } #else key->sign_k_set = 0; - /* currently limiting to SHA256 for auto create */ - if (wc_ecc_gen_deterministic_k(in, inlen, WC_HASH_TYPE_SHA256, + if (wc_ecc_gen_deterministic_k(in, inlen, key->hashType, ecc_get_k(key), key->sign_k, curve->order, key->heap) != 0) { err = ECC_PRIV_KEY_E; } @@ -7479,7 +7503,7 @@ static int _HMAC_K(byte* K, word32 KSz, byte* V, word32 VSz, Hmac hmac; int ret, init; - ret = init = wc_HmacInit(&hmac, heap, 0); + ret = init = wc_HmacInit(&hmac, heap, INVALID_DEVID); if (ret == 0) ret = wc_HmacSetKey(&hmac, hashType, K, KSz); @@ -7519,7 +7543,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, enum wc_HashType hashType, mp_int* priv, mp_int* k, mp_int* order, void* heap) { - int ret = 0, qbits = 0; + int ret = 0; #ifndef WOLFSSL_SMALL_STACK byte h1[MAX_ECC_BYTES]; byte V[WC_MAX_DIGEST_SIZE]; @@ -7535,6 +7559,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, #endif word32 xSz, VSz, KSz, h1len, qLen; byte intOct; + int qbits = 0; if (hash == NULL || k == NULL || order == NULL) { return BAD_FUNC_ARG; @@ -7545,9 +7570,20 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, return BAD_FUNC_ARG; } - if (hashSz != WC_SHA256_DIGEST_SIZE) { - WOLFSSL_MSG("Currently only SHA256 digest is supported"); - return BAD_FUNC_ARG; + /* if none is provided then detect has type based on hash size */ + if (hashType == WC_HASH_TYPE_NONE) { + if (hashSz == 64) { + hashType = WC_HASH_TYPE_SHA512; + } + else if (hashSz == 48) { + hashType = WC_HASH_TYPE_SHA384; + } + else if (hashSz == 32) { + hashType = WC_HASH_TYPE_SHA256; + } + else { + return BAD_FUNC_ARG; + } } if (mp_unsigned_bin_size(priv) > MAX_ECC_BYTES) { @@ -7587,14 +7623,10 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, /* bail out if any error has been hit at this point */ if (ret != 0) { - if (x != NULL) - XFREE(x, heap, DYNAMIC_TYPE_PRIVATE_KEY); - if (K != NULL) - XFREE(K, heap, DYNAMIC_TYPE_ECC_BUFFER); - if (V != NULL) - XFREE(V, heap, DYNAMIC_TYPE_ECC_BUFFER); - if (h1 != NULL) - XFREE(h1, heap, DYNAMIC_TYPE_DIGEST); + XFREE(x, heap, DYNAMIC_TYPE_PRIVATE_KEY); + XFREE(K, heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(V, heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(h1, heap, DYNAMIC_TYPE_DIGEST); return ret; } #endif @@ -7615,6 +7647,16 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, wc_MemZero_Add("wc_ecc_gen_deterministic_k x", x, qLen); #endif qbits = mp_count_bits(order); + if (qbits < 0) + ret = MP_VAL; + } + + if (ret == 0) { + /* hash truncate if too long */ + if (((WOLFSSL_BIT_SIZE) * hashSz) > (word32)qbits) { + /* calculate truncated hash size using bits rounded up byte */ + hashSz = ((word32)qbits + (WOLFSSL_BIT_SIZE - 1)) / WOLFSSL_BIT_SIZE; + } ret = mp_read_unsigned_bin(z1, hash, hashSz); } @@ -7636,7 +7678,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, ret = BUFFER_E; } else { - ret = mp_to_unsigned_bin_len(z1, h1, h1len); + ret = mp_to_unsigned_bin_len(z1, h1, (int)h1len); } } else @@ -7705,7 +7747,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, ret = mp_read_unsigned_bin(k, x, xSz); } - if ((ret == 0) && ((int)(xSz * WOLFSSL_BIT_SIZE) != qbits)) { + if ((ret == 0) && ((xSz * WOLFSSL_BIT_SIZE) != (word32)qbits)) { /* handle odd case where shift of 'k' is needed with RFC 6979 * k = bits2int(T) in section 3.2 h.3 */ mp_rshb(k, ((int)xSz * WOLFSSL_BIT_SIZE) - qbits); @@ -7737,16 +7779,11 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, ForceZero(x, MAX_ECC_BYTES); #ifdef WOLFSSL_SMALL_STACK - if (z1 != NULL) - XFREE(z1, heap, DYNAMIC_TYPE_ECC_BUFFER); - if (x != NULL) - XFREE(x, heap, DYNAMIC_TYPE_PRIVATE_KEY); - if (K != NULL) - XFREE(K, heap, DYNAMIC_TYPE_ECC_BUFFER); - if (V != NULL) - XFREE(V, heap, DYNAMIC_TYPE_ECC_BUFFER); - if (h1 != NULL) - XFREE(h1, heap, DYNAMIC_TYPE_DIGEST); + XFREE(z1, heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(x, heap, DYNAMIC_TYPE_PRIVATE_KEY); + XFREE(K, heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(V, heap, DYNAMIC_TYPE_ECC_BUFFER); + XFREE(h1, heap, DYNAMIC_TYPE_DIGEST); #elif defined(WOLFSSL_CHECK_MEM_ZERO) wc_MemZero_Check(x, MAX_ECC_BYTES); #endif @@ -7758,15 +7795,23 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, /* Sets the deterministic flag for 'k' generation with sign. * returns 0 on success */ -int wc_ecc_set_deterministic(ecc_key* key, byte flag) +int wc_ecc_set_deterministic_ex(ecc_key* key, byte flag, + enum wc_HashType hashType) { if (key == NULL) { return BAD_FUNC_ARG; } key->deterministic = flag ? 1 : 0; + key->hashType = hashType; return 0; } + +int wc_ecc_set_deterministic(ecc_key* key, byte flag) +{ + return wc_ecc_set_deterministic_ex(key, flag, WC_HASH_TYPE_NONE); +} + #endif /* end sign_ex and deterministic sign */ @@ -7859,7 +7904,9 @@ int wc_ecc_free(ecc_key* key) return 0; } -#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) +#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \ + defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ + defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) #ifndef WOLFSSL_NO_MALLOC if (key->sign_k != NULL) #endif @@ -8169,12 +8216,12 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, /* allocate memory */ tA = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tA == NULL) { - return GEN_MEM_ERR; + return MP_MEM; } tB = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tB == NULL) { XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); - return GEN_MEM_ERR; + return MP_MEM; } #endif @@ -8183,7 +8230,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, if (key == NULL) { XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); - return GEN_MEM_ERR; + return MP_MEM; } #endif #ifdef WOLFSSL_SMALL_STACK @@ -8195,7 +8242,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, #ifdef WOLFSSL_SMALL_STACK_CACHE XFREE(key, heap, DYNAMIC_TYPE_ECC_BUFFER); #endif - return GEN_MEM_ERR; + return MP_MEM; } #endif #ifdef WOLFSSL_SMALL_STACK_CACHE @@ -8423,7 +8470,6 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, #ifdef HAVE_ECC_VERIFY -#ifndef NO_ASN /* verify * * w = s^-1 mod n @@ -8461,6 +8507,9 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, #ifdef WOLFSSL_ASYNC_CRYPT int isPrivateKeyOnly = 0; #endif +#ifdef NO_ASN + word32 keySz; +#endif if (sig == NULL || hash == NULL || res == NULL || key == NULL) { return ECC_BAD_ARG_E; @@ -8493,18 +8542,20 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, r = key->r; s = key->s; #else - NEW_MP_INT_SIZE(r, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, DYNAMIC_TYPE_ECC); -#ifdef MP_INT_SIZE_CHECK_NULL + NEW_MP_INT_SIZE(r, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, + DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL if (r == NULL) return MEMORY_E; -#endif - NEW_MP_INT_SIZE(s, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, DYNAMIC_TYPE_ECC); -#ifdef MP_INT_SIZE_CHECK_NULL + #endif + NEW_MP_INT_SIZE(s, ECC_KEY_MAX_BITS_NONULLCHECK(key), key->heap, + DYNAMIC_TYPE_ECC); + #ifdef MP_INT_SIZE_CHECK_NULL if (s == NULL) { FREE_MP_INT_SIZE(r, key->heap, DYNAMIC_TYPE_ECC); return MEMORY_E; } -#endif + #endif err = INIT_MP_INT_SIZE(r, ECC_KEY_MAX_BITS_NONULLCHECK(key)); if (err != 0) { FREE_MP_INT_SIZE(s, key->heap, DYNAMIC_TYPE_ECC); @@ -8527,6 +8578,7 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, /* default to invalid signature */ *res = 0; + #ifndef NO_ASN /* Decode ASN.1 ECDSA signature. */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) /* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s. @@ -8541,6 +8593,24 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, if (err < 0) { break; } + #else + /* No support for DSA ASN.1 header. + * Signature must be r+s directly. */ + keySz = 0; + if (key->dp != NULL) { + keySz = (word32)key->dp->size; + } + if (siglen != keySz * 2) { + WOLFSSL_MSG("Error: ECDSA Verify raw signature size"); + return WC_NO_ERR_TRACE(ECC_BAD_ARG_E); + } + + /* Import signature into r,s */ + mp_init(r); + mp_init(s); + mp_read_unsigned_bin(r, sig, keySz); + mp_read_unsigned_bin(s, sig + keySz, keySz); + #endif /* !NO_ASN */ FALL_THROUGH; case ECC_STATE_VERIFY_DO: @@ -8600,7 +8670,6 @@ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, return err; #endif /* !WOLF_CRYPTO_CB_ONLY_ECC */ } -#endif /* !NO_ASN */ #ifndef WOLF_CRYPTO_CB_ONLY_ECC @@ -9089,7 +9158,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, keySz = (word32)key->dp->size; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ - defined(WOLFSSL_ASYNC_CRYPT_SW) + defined(WOLFSSL_ASYNC_CRYPT_SW) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_ECC_VERIFY)) { WC_ASYNC_SW* sw = &key->asyncDev.sw; @@ -9466,12 +9535,8 @@ int wc_ecc_import_point_der_ex(const byte* in, word32 inLen, } #ifdef WOLFSSL_SMALL_STACK - if (t1 != NULL) { - XFREE(t1, NULL, DYNAMIC_TYPE_BIGINT); - } - if (t2 != NULL) { - XFREE(t2, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t1, NULL, DYNAMIC_TYPE_BIGINT); + XFREE(t2, NULL, DYNAMIC_TYPE_BIGINT); #endif wc_ecc_curve_free(curve); @@ -9548,7 +9613,7 @@ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, /* return length needed only */ if (point != NULL && out == NULL && outLen != NULL) { *outLen = 1 + 2*numlen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (point == NULL || out == NULL || outLen == NULL) @@ -9624,7 +9689,7 @@ int wc_ecc_export_point_der_compressed(const int curve_idx, ecc_point* point, /* return length needed only */ if (point != NULL && out == NULL && outLen != NULL) { *outLen = output_len; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (point == NULL || out == NULL || outLen == NULL) @@ -9688,7 +9753,7 @@ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) /* if key hasn't been setup assume max bytes for size estimation */ numlen = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES; *outLen = 1 + 2 * numlen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (key == NULL || out == NULL || outLen == NULL) @@ -10166,23 +10231,32 @@ static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) } if (!err && (flags & WC_ECC_FLAG_DEC_SIGN)) { +#ifndef WOLFSSL_SMALL_STACK + #define SIG_SZ ((MAX_ECC_BYTES * 2) + SIG_HEADER_SZ + ECC_MAX_PAD_SZ) + byte sig[SIG_SZ + WC_SHA256_DIGEST_SIZE]; +#else byte* sig; +#endif byte* digest; word32 sigLen, digestLen; int dynRng = 0, res = 0; sigLen = (word32)wc_ecc_sig_size(key); digestLen = WC_SHA256_DIGEST_SIZE; - sig = (byte*)XMALLOC(sigLen + digestLen, NULL, DYNAMIC_TYPE_ECC); +#ifdef WOLFSSL_SMALL_STACK + sig = (byte*)XMALLOC(sigLen + digestLen, key->heap, DYNAMIC_TYPE_ECC); if (sig == NULL) return MEMORY_E; +#endif digest = sig + sigLen; if (rng == NULL) { dynRng = 1; - rng = wc_rng_new(NULL, 0, NULL); + rng = wc_rng_new(NULL, 0, key->heap); if (rng == NULL) { - XFREE(sig, NULL, DYNAMIC_TYPE_ECC); +#ifdef WOLFSSL_SMALL_STACK + XFREE(sig, key->heap, DYNAMIC_TYPE_ECC); +#endif return MEMORY_E; } } @@ -10203,7 +10277,9 @@ static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) wc_rng_free(rng); } ForceZero(sig, sigLen + digestLen); - XFREE(sig, NULL, DYNAMIC_TYPE_ECC); +#ifdef WOLFSSL_SMALL_STACK + XFREE(sig, key->heap, DYNAMIC_TYPE_ECC); +#endif } (void)rng; @@ -10737,12 +10813,8 @@ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, mp_clear(t1); } #ifdef WOLFSSL_SMALL_STACK - if (t1 != NULL) { - XFREE(t1, NULL, DYNAMIC_TYPE_BIGINT); - } - if (t2 != NULL) { - XFREE(t2, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t1, NULL, DYNAMIC_TYPE_BIGINT); + XFREE(t2, NULL, DYNAMIC_TYPE_BIGINT); #endif wc_ecc_curve_free(curve); @@ -12366,6 +12438,9 @@ static const struct { /* find a hole and free as required, return -1 if no hole found */ static int find_hole(void) { +#ifdef WOLFSSL_NO_MALLOC + return -1; +#else int x, y, z; for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) { @@ -12394,6 +12469,7 @@ static int find_hole(void) fp_cache[z].lru_count = 0; } return z; +#endif /* !WOLFSSL_NO_MALLOC */ } /* determine if a base is already in the cache and if so, where */ @@ -12422,7 +12498,7 @@ static int add_entry(int idx, ecc_point *g) /* allocate base and LUT */ fp_cache[idx].g = wc_ecc_new_point(); if (fp_cache[idx].g == NULL) { - return GEN_MEM_ERR; + return MP_MEM; } /* copy x and y */ @@ -12431,7 +12507,7 @@ static int add_entry(int idx, ecc_point *g) (mp_copy(g->z, fp_cache[idx].g->z) != MP_OKAY)) { wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; - return GEN_MEM_ERR; + return MP_MEM; } for (x = 0; x < (1U<x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[z]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx].mu, R->z) != MP_OKAY)) { - err = GEN_MEM_ERR; + err = MP_MEM; break; } first = 0; @@ -13020,7 +13096,7 @@ static int accel_fp_mul2add(int idx1, int idx2, if ((mp_copy(fp_cache[idx1].LUT[zA]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx1].LUT[zA]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx1].mu, R->z) != MP_OKAY)) { - err = GEN_MEM_ERR; + err = MP_MEM; break; } first = 0; @@ -13035,7 +13111,7 @@ static int accel_fp_mul2add(int idx1, int idx2, if ((mp_copy(fp_cache[idx2].LUT[zB]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx2].LUT[zB]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx2].mu, R->z) != MP_OKAY)) { - err = GEN_MEM_ERR; + err = MP_MEM; break; } first = 0; @@ -13839,15 +13915,25 @@ int wc_ecc_ctx_set_kdf_salt(ecEncCtx* ctx, const byte* salt, word32 sz) if (ctx == NULL || (salt == NULL && sz != 0)) return BAD_FUNC_ARG; - ctx->kdfSalt = salt; - ctx->kdfSaltSz = sz; + /* truncate salt if exceeds max */ + if (sz > EXCHANGE_SALT_SZ) + sz = EXCHANGE_SALT_SZ; + /* using a custom kdf salt, so borrow clientSalt/serverSalt for it, + * since wc_ecc_ctx_set_peer_salt will set kdf and mac salts */ if (ctx->protocol == REQ_RESP_CLIENT) { ctx->cliSt = ecCLI_SALT_SET; + ctx->kdfSalt = ctx->clientSalt; } else if (ctx->protocol == REQ_RESP_SERVER) { ctx->srvSt = ecSRV_SALT_SET; + ctx->kdfSalt = ctx->serverSalt; + } + + if (salt != NULL) { + XMEMCPY((byte*)ctx->kdfSalt, salt, sz); } + ctx->kdfSaltSz = sz; return 0; } @@ -14695,8 +14781,9 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, if (ret == 0) ret = wc_HmacFinal(hmac, verify); if ((ret == 0) && (XMEMCMP(verify, msg + msgSz - digestSz, - digestSz) != 0)) { - ret = -1; + digestSz) != 0)) { + ret = HASH_TYPE_E; + WOLFSSL_MSG("ECC Decrypt HMAC Check failed!"); } wc_HmacFree(hmac); @@ -14805,9 +14892,7 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, #endif #ifdef WOLFSSL_SMALL_STACK #ifndef WOLFSSL_ECIES_OLD - if (peerKey != NULL) { - XFREE(peerKey, ctx->heap, DYNAMIC_TYPE_ECC_BUFFER); - } + XFREE(peerKey, ctx->heap, DYNAMIC_TYPE_ECC_BUFFER); #endif XFREE(sharedSecret, ctx->heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE(keys, ctx->heap, DYNAMIC_TYPE_ECC_BUFFER); @@ -15327,7 +15412,7 @@ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen if (*outLen < (1 + numlen)) { *outLen = 1 + numlen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (out == NULL) @@ -15351,23 +15436,57 @@ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen #endif /* HAVE_ECC_KEY_EXPORT */ #endif /* HAVE_COMP_KEY */ +#ifdef HAVE_OID_ENCODING +int wc_ecc_oid_cache_init(void) +{ + int ret = 0; +#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER) + ret = wc_InitMutex(&ecc_oid_cache_lock); +#endif + return ret; +} + +void wc_ecc_oid_cache_free(void) +{ +#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER) + wc_FreeMutex(&ecc_oid_cache_lock); +#endif +} +#endif /* HAVE_OID_ENCODING */ int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz) { int x; + int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN); +#ifdef HAVE_OID_ENCODING + oid_cache_t* o = NULL; +#endif if (oidSum == 0) { return BAD_FUNC_ARG; } +#ifdef HAVE_OID_ENCODING + #ifndef WOLFSSL_MUTEX_INITIALIZER + /* extra sanity check if wolfCrypt_Init not called */ + if (eccOidLockInit == 0) { + wc_InitMutex(&ecc_oid_cache_lock); + eccOidLockInit = 1; + } + #endif + + if (wc_LockMutex(&ecc_oid_cache_lock) != 0) { + return BAD_MUTEX_E; + } +#endif + /* find matching OID sum (based on encoded value) */ for (x = 0; ecc_sets[x].size != 0; x++) { if (ecc_sets[x].oidSum == oidSum) { - int ret; #ifdef HAVE_OID_ENCODING - ret = 0; /* check cache */ - oid_cache_t* o = &ecc_oid_cache[x]; + ret = 0; + o = &ecc_oid_cache[x]; if (o->oidSz == 0) { o->oidSz = sizeof(o->oid); ret = EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, @@ -15379,10 +15498,12 @@ int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz) if (oid) { *oid = o->oid; } + /* on success return curve id */ if (ret == 0) { ret = ecc_sets[x].id; } + break; #else if (oidSz) { *oidSz = ecc_sets[x].oidSz; @@ -15391,12 +15512,16 @@ int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz) *oid = ecc_sets[x].oid; } ret = ecc_sets[x].id; + break; #endif - return ret; } } - return NOT_COMPILED_IN; +#ifdef HAVE_OID_ENCODING + wc_UnLockMutex(&ecc_oid_cache_lock); +#endif + + return ret; } #ifdef WOLFSSL_CUSTOM_CURVES diff --git a/src/wolfcrypt/src/eccsi.c b/src/wolfcrypt/src/eccsi.c index 69d999b..2be700f 100644 --- a/src/wolfcrypt/src/eccsi.c +++ b/src/wolfcrypt/src/eccsi.c @@ -1,6 +1,6 @@ /* eccsi.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -516,7 +516,7 @@ static int eccsi_encode_point(ecc_point* point, word32 size, byte* data, if (data == NULL) { *sz = size * 2 + !raw; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*sz < size * 2 + !raw)) { err = BUFFER_E; @@ -655,7 +655,7 @@ int wc_ExportEccsiKey(EccsiKey* key, byte* data, word32* sz) if (err == 0) { if (data == NULL) { *sz = (word32)(key->ecc.dp->size * 3); - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*sz < (word32)key->ecc.dp->size * 3) { err = BUFFER_E; @@ -777,7 +777,7 @@ int wc_ExportEccsiPrivateKey(EccsiKey* key, byte* data, word32* sz) if (err == 0) { if (data == NULL) { *sz = (word32)key->ecc.dp->size; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*sz < (word32)key->ecc.dp->size) { err = BUFFER_E; @@ -1016,7 +1016,7 @@ int wc_EncodeEccsiPair(const EccsiKey* key, mp_int* ssk, ecc_point* pvt, if ((err == 0) && (data == NULL)) { *sz = (word32)(key->ecc.dp->size * 3); - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*sz < (word32)(key->ecc.dp->size * 3))) { err = BUFFER_E; @@ -1077,7 +1077,7 @@ int wc_EncodeEccsiSsk(const EccsiKey* key, mp_int* ssk, byte* data, word32* sz) if (err == 0) { if (data == NULL) { *sz = (word32)key->ecc.dp->size; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*sz < (word32)key->ecc.dp->size) { err = BUFFER_E; @@ -2000,7 +2000,7 @@ int wc_SignEccsiHash(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType, sz = (word32)key->ecc.dp->size; if (sig == NULL) { *sigSz = sz * 4 + 1; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } } if ((err == 0) && (*sigSz < sz * 4 + 1)) { diff --git a/src/wolfcrypt/src/ed25519.c b/src/wolfcrypt/src/ed25519.c index 381b911..09777dd 100644 --- a/src/wolfcrypt/src/ed25519.c +++ b/src/wolfcrypt/src/ed25519.c @@ -1,6 +1,6 @@ /* ed25519.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -968,6 +968,39 @@ int wc_ed25519ph_verify_msg(const byte* sig, word32 sigLen, const byte* msg, } #endif /* HAVE_ED25519_VERIFY */ +#ifndef WC_NO_CONSTRUCTORS +ed25519_key* wc_ed25519_new(void* heap, int devId, int *result_code) +{ + int ret; + ed25519_key* key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), heap, + DYNAMIC_TYPE_ED25519); + if (key == NULL) { + ret = MEMORY_E; + } + else { + ret = wc_ed25519_init_ex(key, heap, devId); + if (ret != 0) { + XFREE(key, heap, DYNAMIC_TYPE_ED25519); + key = NULL; + } + } + + if (result_code != NULL) + *result_code = ret; + + return key; +} + +int wc_ed25519_delete(ed25519_key* key, ed25519_key** key_p) { + if (key == NULL) + return BAD_FUNC_ARG; + wc_ed25519_free(key); + XFREE(key, key->heap, DYNAMIC_TYPE_ED25519); + if (key_p != NULL) + *key_p = NULL; + return 0; +} +#endif /* !WC_NO_CONSTRUCTORS */ /* initialize information and memory for key */ int wc_ed25519_init_ex(ed25519_key* key, void* heap, int devId) diff --git a/src/wolfcrypt/src/ed448.c b/src/wolfcrypt/src/ed448.c index e9e865c..1598c9c 100644 --- a/src/wolfcrypt/src/ed448.c +++ b/src/wolfcrypt/src/ed448.c @@ -1,6 +1,6 @@ /* ed448.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/error.c b/src/wolfcrypt/src/error.c index 2e25b60..deedcbe 100644 --- a/src/wolfcrypt/src/error.c +++ b/src/wolfcrypt/src/error.c @@ -1,6 +1,6 @@ /* error.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -42,7 +42,19 @@ WOLFSSL_ABI const char* wc_GetErrorString(int error) { - switch (error) { + switch ((enum wolfCrypt_ErrorCodes)error) { + + case MP_MEM : + return "MP integer dynamic memory allocation failed"; + + case MP_VAL : + return "MP integer invalid argument"; + + case MP_WOULDBLOCK : + return "MP integer non-blocking operation would block"; + + case MP_NOT_INF: + return "MP point not at infinity"; case OPEN_RAN_E : return "opening random device error"; @@ -352,13 +364,13 @@ const char* wc_GetErrorString(int error) return "ECC is point on curve failed"; case ECC_INF_E: - return " ECC point at infinity error"; + return "ECC point at infinity error"; case ECC_OUT_OF_RANGE_E: - return " ECC Qx or Qy out of range error"; + return "ECC Qx or Qy out of range error"; case ECC_PRIV_KEY_E: - return " ECC private key is not valid error"; + return "ECC private key is not valid error"; case SRP_CALL_ORDER_E: return "SRP function called in the wrong order error"; @@ -630,6 +642,8 @@ const char* wc_GetErrorString(int error) case PBKDF2_KAT_FIPS_E: return "wolfCrypt FIPS PBKDF2 Known Answer Test Failure"; + case MAX_CODE_E: + case MIN_CODE_E: default: return "unknown error number"; diff --git a/src/wolfcrypt/src/evp.c b/src/wolfcrypt/src/evp.c index 42949fc..808aa04 100644 --- a/src/wolfcrypt/src/evp.c +++ b/src/wolfcrypt/src/evp.c @@ -1,6 +1,6 @@ /* evp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -283,6 +283,40 @@ static const struct s_ent { static const char EVP_NULL[] = "NULL"; +static const struct pkey_type_name_ent { + int type; + const char *name; +} pkey_type_names[] = { + { EVP_PKEY_RSA, "RSA" }, + { EVP_PKEY_EC, "EC" }, + { EVP_PKEY_DH, "DH" }, + { EVP_PKEY_DSA, "DSA" } +}; + +static int pkey_type_by_name(const char *name) { + unsigned int i; + if (name == NULL) + return EVP_PKEY_NONE; + for (i = 0; i < XELEM_CNT(pkey_type_names); ++i) { + if (XSTRCMP(name, pkey_type_names[i].name) == 0) + return pkey_type_names[i].type; + } + return EVP_PKEY_NONE; +} + +int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { + int type; + + if (pkey == NULL) + return WOLFSSL_FAILURE; + + type = pkey_type_by_name(name); + if (type == EVP_PKEY_NONE) + return WOLFSSL_FAILURE; + + return (pkey->type == type) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} + #define EVP_CIPHER_TYPE_MATCHES(x, y) (XSTRCMP(x,y) == 0) #define EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 @@ -364,6 +398,9 @@ int wolfSSL_EVP_Cipher_key_length(const WOLFSSL_EVP_CIPHER* c) case DES_ECB_TYPE: return 8; case DES_EDE3_ECB_TYPE: return 24; #endif + #ifndef NO_RC4 + case ARC4_TYPE: return 16; + #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) case CHACHA20_POLY1305_TYPE: return 32; #endif @@ -452,7 +489,7 @@ void wolfSSL_EVP_CIPHER_CTX_free(WOLFSSL_EVP_CIPHER_CTX *ctx) int wolfSSL_EVP_CIPHER_CTX_reset(WOLFSSL_EVP_CIPHER_CTX *ctx) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL) { WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_reset"); @@ -1688,7 +1725,7 @@ int wolfSSL_EVP_DecryptFinal_legacy(WOLFSSL_EVP_CIPHER_CTX *ctx, { int fl; if (ctx == NULL || out == NULL || outl == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; WOLFSSL_ENTER("wolfSSL_EVP_DecryptFinal_legacy"); if (ctx->block_size == 1) { @@ -1727,7 +1764,7 @@ int wolfSSL_EVP_DecryptFinal_legacy(WOLFSSL_EVP_CIPHER_CTX *ctx, int wolfSSL_EVP_CIPHER_CTX_block_size(const WOLFSSL_EVP_CIPHER_CTX *ctx) { - if (ctx == NULL) return BAD_FUNC_ARG; + if (ctx == NULL) return WOLFSSL_FAILURE; switch (ctx->cipherType) { #if !defined(NO_AES) || !defined(NO_DES3) || defined(WOLFSSL_SM4) #if !defined(NO_AES) @@ -2009,7 +2046,7 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) { if (cipher == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; switch (cipherType(cipher)) { #if !defined(NO_AES) @@ -2269,7 +2306,7 @@ int wolfSSL_EVP_CIPHER_CTX_set_padding(WOLFSSL_EVP_CIPHER_CTX *ctx, int padding) { if (ctx == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; if (padding) { ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_NO_PADDING; } @@ -2281,9 +2318,10 @@ int wolfSSL_EVP_CIPHER_CTX_set_padding(WOLFSSL_EVP_CIPHER_CTX *ctx, int wolfSSL_EVP_add_digest(const WOLFSSL_EVP_MD *digest) { - (void)digest; /* nothing to do */ - return 0; + if (digest == NULL) + return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } @@ -2679,9 +2717,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt(WOLFSSL_EVP_PKEY_CTX* ctx, } if (ret == WOLFSSL_SUCCESS && salt != NULL && saltSz > 0) { - if (ctx->pkey->hkdfSalt != NULL) { - XFREE(ctx->pkey->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); - } + XFREE(ctx->pkey->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); ctx->pkey->hkdfSalt = (byte*)XMALLOC((size_t)saltSz, NULL, DYNAMIC_TYPE_SALT); if (ctx->pkey->hkdfSalt == NULL) { @@ -2716,9 +2752,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_key(WOLFSSL_EVP_PKEY_CTX* ctx, } if (ret == WOLFSSL_SUCCESS) { - if (ctx->pkey->hkdfKey != NULL) { - XFREE(ctx->pkey->hkdfKey, NULL, DYNAMIC_TYPE_KEY); - } + XFREE(ctx->pkey->hkdfKey, NULL, DYNAMIC_TYPE_KEY); ctx->pkey->hkdfKey = (byte*)XMALLOC((size_t)keySz, NULL, DYNAMIC_TYPE_KEY); if (ctx->pkey->hkdfKey == NULL) { @@ -3110,7 +3144,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, if (!ctx->pkey->dsa) return WOLFSSL_FAILURE; bytes = wolfSSL_BN_num_bytes(ctx->pkey->dsa->q); - if (bytes == WOLFSSL_FAILURE) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) return WOLFSSL_FAILURE; bytes *= 2; if (!sig) { @@ -3123,7 +3157,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, /* wolfSSL_DSA_do_sign() can return WOLFSSL_FATAL_ERROR */ if (ret != WOLFSSL_SUCCESS) return ret; - if (bytes == WOLFSSL_FAILURE) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) return WOLFSSL_FAILURE; *siglen = (size_t)bytes; return WOLFSSL_SUCCESS; @@ -3404,14 +3438,14 @@ int wolfSSL_EVP_PKEY_keygen_init(WOLFSSL_EVP_PKEY_CTX *ctx) int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY **ppkey) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int ownPkey = 0; WOLFSSL_EVP_PKEY* pkey; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_keygen"); if (ctx == NULL || ppkey == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } pkey = *ppkey; @@ -3421,7 +3455,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, ctx->pkey->type != EVP_PKEY_RSA && ctx->pkey->type != EVP_PKEY_DH)) { WOLFSSL_MSG("Key not set or key type not supported"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } pkey = wolfSSL_EVP_PKEY_new(); if (pkey == NULL) { @@ -3802,14 +3836,15 @@ static int DH_param_check(WOLFSSL_DH* dh_key) dh_key->q != NULL) { if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) == - WOLFSSL_FAILURE) { + wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { WOLFSSL_MSG("BN_mod_exp failed"); ret = WOLFSSL_FAILURE; } else if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_is_one(num1) == WOLFSSL_FAILURE) { + wolfSSL_BN_is_one(num1) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("dh_key->g is not suitable generator"); ret = WOLFSSL_FAILURE; } @@ -3957,7 +3992,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, (void)siglen; WOLFSSL_ENTER("EVP_SignFinal"); - if (ctx == NULL) + if (ctx == NULL || sigret == NULL || siglen == NULL || pkey == NULL) return WOLFSSL_FAILURE; ret = wolfSSL_EVP_DigestFinal(ctx, md, &mdsize); @@ -3989,15 +4024,32 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, if (ret != WOLFSSL_SUCCESS) return ret; bytes = wolfSSL_BN_num_bytes(pkey->dsa->q); - if (bytes == WOLFSSL_FAILURE || (int)*siglen < bytes * 2) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE) || + (int)*siglen < bytes * 2) + { return WOLFSSL_FAILURE; + } *siglen = (unsigned int)(bytes * 2); return WOLFSSL_SUCCESS; } #endif - case EVP_PKEY_EC: - WOLFSSL_MSG("not implemented"); - FALL_THROUGH; +#ifdef HAVE_ECC + case EVP_PKEY_EC: { + WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_ECDSA_do_sign(md, (int)mdsize, + pkey->ecc); + if (ecdsaSig == NULL) + return WOLFSSL_FAILURE; + ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); + if (ret <= 0 || ret > (int)*siglen) + return WOLFSSL_FAILURE; + ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sigret); + wolfSSL_ECDSA_SIG_free(ecdsaSig); + if (ret <= 0 || ret > (int)*siglen) + return WOLFSSL_FAILURE; + *siglen = (unsigned int)ret; + return WOLFSSL_SUCCESS; + } +#endif default: break; } @@ -4055,7 +4107,8 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, if (ctx == NULL) return WOLFSSL_FAILURE; WOLFSSL_ENTER("EVP_VerifyFinal"); ret = wolfSSL_EVP_DigestFinal(ctx, md, &mdsize); - if (ret <= 0) return ret; + if (ret <= 0) + return ret; (void)sig; (void)siglen; @@ -4072,9 +4125,19 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, (unsigned int)siglen, pkey->rsa); } #endif /* NO_RSA */ - +#ifdef HAVE_ECC + case EVP_PKEY_EC: { + WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( + NULL, (const unsigned char **)&sig, (long)siglen); + if (ecdsaSig == NULL) + return WOLFSSL_FAILURE; + ret = wolfSSL_ECDSA_do_verify(md, (int)mdsize, ecdsaSig, + pkey->ecc); + wolfSSL_ECDSA_SIG_free(ecdsaSig); + return ret; + } +#endif case EVP_PKEY_DSA: - case EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -4085,9 +4148,10 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, int wolfSSL_EVP_add_cipher(const WOLFSSL_EVP_CIPHER *cipher) { - (void)cipher; /* nothing to do */ - return 0; + if (cipher == NULL) + return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } @@ -4144,7 +4208,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_CMAC_key(WOLFSSL_ENGINE* e, } ret = wolfSSL_CMAC_Init(ctx, priv, len, cipher, e); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { wolfSSL_CMAC_CTX_free(ctx); WOLFSSL_LEAVE("wolfSSL_EVP_PKEY_new_CMAC_key", 0); return NULL; @@ -4286,7 +4350,7 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, } type = wolfSSL_EVP_get_digestbynid(default_digest); if (type == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } } @@ -4478,7 +4542,7 @@ int wolfSSL_EVP_DigestSignInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_ENTER("EVP_DigestSignInit"); if (ctx == NULL || pkey == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfSSL_evp_digest_pk_init(ctx, pctx, type, e, pkey); } @@ -4490,7 +4554,7 @@ int wolfSSL_EVP_DigestSignUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *d, WOLFSSL_ENTER("EVP_DigestSignUpdate"); if (ctx == NULL || d == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfssl_evp_digest_pk_update(ctx, d, cnt); } @@ -4500,7 +4564,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, { unsigned char digest[WC_MAX_DIGEST_SIZE]; unsigned int hashLen; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("EVP_DigestSignFinal"); @@ -4603,7 +4667,7 @@ int wolfSSL_EVP_DigestVerifyInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_ENTER("EVP_DigestVerifyInit"); if (ctx == NULL || type == NULL || pkey == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfSSL_evp_digest_pk_init(ctx, pctx, type, e, pkey); } @@ -4615,7 +4679,7 @@ int wolfSSL_EVP_DigestVerifyUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *d, WOLFSSL_ENTER("EVP_DigestVerifyUpdate"); if (ctx == NULL || d == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfssl_evp_digest_pk_update(ctx, d, (unsigned int)cnt); } @@ -4756,7 +4820,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, int wolfSSL_EVP_read_pw_string(char* buf, int bufSz, const char* banner, int v) { printf("%s", banner); - if (XGETPASSWD(buf, bufSz) == WOLFSSL_FAILURE) { + if (XGETPASSWD(buf, bufSz) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { return -1; } (void)v; /* fgets always sanity checks size of input vs buffer */ @@ -5913,7 +5977,7 @@ void wolfSSL_EVP_init(void) int wolfSSL_EVP_CIPHER_CTX_ctrl(WOLFSSL_EVP_CIPHER_CTX *ctx, int type, \ int arg, void *ptr) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) #ifndef WC_NO_RNG WC_RNG rng; @@ -6298,15 +6362,11 @@ void wolfSSL_EVP_init(void) ctx->keyLen = 0; #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA) || \ defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) - if (ctx->authBuffer) { - XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authBuffer = NULL; - } + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; ctx->authBufferLen = 0; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->authIvGenEnable = 0; ctx->authIncIv = 0; @@ -6361,7 +6421,7 @@ void wolfSSL_EVP_init(void) } ret = wolfSSL_EVP_get_hashinfo(md, &hashType, NULL); - if (ret == WOLFSSL_FAILURE) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) goto end; ret = wc_PBKDF1_ex(key, (int)info->keySz, iv, (int)info->ivSz, data, sz, @@ -6428,10 +6488,8 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -6520,7 +6578,7 @@ void wolfSSL_EVP_init(void) static int EvpCipherAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifndef WOLFSSL_AESGCM_STREAM /* No destination means only AAD. */ @@ -6635,10 +6693,8 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -6714,7 +6770,7 @@ void wolfSSL_EVP_init(void) static int EvpCipherAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -6786,10 +6842,8 @@ void wolfSSL_EVP_init(void) return WOLFSSL_FAILURE; } - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -7821,10 +7875,8 @@ void wolfSSL_EVP_init(void) ctx->ivSz = GCM_NONCE_MID_SZ; } ctx->authTagSz = SM4_BLOCK_SIZE; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7853,10 +7905,8 @@ void wolfSSL_EVP_init(void) ctx->ivSz = GCM_NONCE_MID_SZ; } ctx->authTagSz = SM4_BLOCK_SIZE; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -8224,7 +8274,7 @@ void wolfSSL_EVP_init(void) int wolfSSL_EVP_Cipher(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_EVP_Cipher"); @@ -9001,7 +9051,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) /* Get size of DER buffer only */ if (havePublic && !havePrivate) { ret = wc_DhPubKeyToDer(dhkey, NULL, &derSz); - } else if (havePrivate && !havePublic) { + } else if (havePrivate) { ret = wc_DhPrivKeyToDer(dhkey, NULL, &derSz); } else { ret = wc_DhParamsToDer(dhkey,NULL,&derSz); @@ -9021,7 +9071,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) /* Fill DER buffer */ if (havePublic && !havePrivate) { ret = wc_DhPubKeyToDer(dhkey, derBuf, &derSz); - } else if (havePrivate && !havePublic) { + } else if (havePrivate) { ret = wc_DhPrivKeyToDer(dhkey, derBuf, &derSz); } else { ret = wc_DhParamsToDer(dhkey,derBuf,&derSz); @@ -9304,7 +9354,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) { - int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); @@ -9329,7 +9379,7 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) } } else { - ret = BAD_FUNC_ARG; + ret = WOLFSSL_FAILURE; } WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); @@ -9720,7 +9770,12 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKCS82PKEY(const WOLFSSL_PKCS8_PRIV_KEY_INFO* p8) /* this function just casts and returns pointer */ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_EVP_PKEY2PKCS8(const WOLFSSL_EVP_PKEY* pkey) { - return (WOLFSSL_PKCS8_PRIV_KEY_INFO*)pkey; + if (pkey == NULL || pkey->pkey.ptr == NULL) { + return NULL; + } + + return wolfSSL_d2i_PrivateKey_EVP(NULL, (unsigned char**)&pkey->pkey.ptr, + pkey->pkey_sz); } #endif @@ -9873,10 +9928,24 @@ static const struct alias { const char *alias; } digest_alias_tbl[] = { - {"MD4", "ssl3-md4"}, - {"MD5", "ssl3-md5"}, - {"SHA1", "ssl3-sha1"}, + {"MD4", "md4"}, + {"MD5", "md5"}, + {"SHA1", "sha1"}, {"SHA1", "SHA"}, + {"SHA224", "sha224"}, + {"SHA256", "sha256"}, + {"SHA384", "sha384"}, + {"SHA512", "sha512"}, + {"SHA512_224", "sha512_224"}, + {"SHA3_224", "sha3_224"}, + {"SHA3_256", "sha3_256"}, + {"SHA3_384", "sha3_384"}, + {"SHA3_512", "sha3_512"}, + {"SM3", "sm3"}, + {"BLAKE2B512", "blake2b512"}, + {"BLAKE2S256", "blake2s256"}, + {"SHAKE128", "shake128"}, + {"SHAKE256", "shake256"}, { NULL, NULL} }; @@ -10205,7 +10274,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) * @param n message digest type name * @return alias name, otherwise NULL */ - static const char* hasAliasName(const char* n) + static const char* getMdAliasName(const char* n) { const char* aliasnm = NULL; @@ -10236,23 +10305,15 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) { struct do_all_md *md = (struct do_all_md*)arg; - const struct s_ent *ent; - /* sanity check */ if (md == NULL || nm == NULL || md->fn == NULL || nm->type != WOLFSSL_OBJ_NAME_TYPE_MD_METH) return; - /* loop all md */ - for (ent = md_tbl; ent->name != NULL; ent++){ - /* check if the md has alias */ - if(hasAliasName(ent->name) != NULL) { - md->fn(NULL, ent->name, ent->name, md->arg); - } - else { - md->fn(ent->name, ent->name, NULL, md->arg); - } - } + if (nm->alias) + md->fn(NULL, nm->name, nm->data, md->arg); + else + md->fn((const EVP_MD *)nm->data, nm->name, NULL, md->arg); } /* call md_do_all function to do all md algorithm via a callback function @@ -10287,11 +10348,30 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (!fn) return; - objnm.type = type; - switch(type) { case WOLFSSL_OBJ_NAME_TYPE_MD_METH: - fn(&objnm, arg); + { + const struct s_ent *ent; + /* loop all md */ + for (ent = md_tbl; ent->name != NULL; ent++){ + XMEMSET(&objnm, 0, sizeof(objnm)); + + /* populate objnm with info about the md */ + objnm.type = WOLFSSL_OBJ_NAME_TYPE_MD_METH; + objnm.name = ent->name; + objnm.data = (const char*) + wolfSSL_EVP_get_digestbyname(ent->name); + fn(&objnm, arg); + + /* check if the md has alias and also call fn with it */ + objnm.name = getMdAliasName(ent->name); + if (objnm.name != NULL) { + objnm.alias |= WOLFSSL_OBJ_NAME_ALIAS; + objnm.data = ent->name; + fn(&objnm, arg); + } + } + } break; case WOLFSSL_OBJ_NAME_TYPE_CIPHER_METH: case WOLFSSL_OBJ_NAME_TYPE_PKEY_METH: @@ -10420,20 +10500,17 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* md) { int ret = WOLFSSL_SUCCESS; + #ifdef WOLFSSL_ASYNC_CRYPT + wc_static_assert(WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV)); + #endif WOLFSSL_ENTER("EVP_DigestInit"); if (ctx == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } - - #ifdef WOLFSSL_ASYNC_CRYPT - /* compile-time validation of ASYNC_CTX_SIZE */ - typedef char async_test[WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV) ? - 1 : -1]; - (void)sizeof(async_test); - #endif + wolfSSL_EVP_MD_CTX_init(ctx); /* Set to 0 if no match */ ctx->macType = EvpMd2MacType(md); @@ -10522,7 +10599,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) #endif { ctx->macType = WC_HASH_TYPE_NONE; - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } return ret; @@ -10532,7 +10609,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) int wolfSSL_EVP_DigestUpdate(WOLFSSL_EVP_MD_CTX* ctx, const void* data, size_t sz) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestUpdate"); @@ -10660,7 +10737,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, unsigned int* s) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestFinal"); @@ -10839,7 +10916,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #ifndef NO_SHA @@ -10905,7 +10982,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) } else #endif - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) @@ -10914,7 +10991,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #ifndef NO_SHA @@ -10990,7 +11067,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) } #endif - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #endif /* OPENSSL_EXTRA || HAVE_CURL */ @@ -11108,18 +11185,12 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #ifdef HAVE_HKDF case EVP_PKEY_HKDF: - if (key->hkdfSalt != NULL) { - XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); - key->hkdfSalt = NULL; - } - if (key->hkdfKey != NULL) { - XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); - key->hkdfKey = NULL; - } - if (key->hkdfInfo != NULL) { - XFREE(key->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); - key->hkdfInfo = NULL; - } + XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); + key->hkdfSalt = NULL; + XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); + key->hkdfKey = NULL; + XFREE(key->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); + key->hkdfInfo = NULL; key->hkdfSaltSz = 0; key->hkdfKeySz = 0; key->hkdfInfoSz = 0; @@ -11279,7 +11350,7 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, int indent, int bitlen, ASN1_PCTX* pctx) { byte buff[8] = { 0 }; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 inOutIdx = 0; word32 nSz; /* size of modulus */ word32 eSz; /* size of public exponent */ @@ -11598,10 +11669,8 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, res = wolfSSL_BIO_write(out, "\n", 1) > 0; } - if (pub != NULL) { - XFREE(pub, NULL, DYNAMIC_TYPE_ECC_BUFFER); - pub = NULL; - } + XFREE(pub, NULL, DYNAMIC_TYPE_ECC_BUFFER); + pub = NULL; wc_ecc_free(key); mp_free(a); @@ -11633,7 +11702,7 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, byte buff[8] = { 0 }; int length; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 inOutIdx = 0; word32 oid; byte tagFound; @@ -11851,7 +11920,7 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, { byte buff[8] = { 0 }; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 length; word32 inOutIdx; word32 oid; diff --git a/src/wolfcrypt/src/ext_kyber.c b/src/wolfcrypt/src/ext_kyber.c index 77ab430..0c2cb2b 100644 --- a/src/wolfcrypt/src/ext_kyber.c +++ b/src/wolfcrypt/src/ext_kyber.c @@ -1,6 +1,6 @@ /* ext_kyber.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -27,7 +27,7 @@ #include #include -#ifdef WOLFSSL_HAVE_KYBER +#if defined(WOLFSSL_HAVE_KYBER) && !defined(WOLFSSL_WC_KYBER) #include #ifdef NO_INLINE @@ -168,12 +168,6 @@ int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) } } #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - (void)key; - if (ret == 0) { - *len = PQM4_PRIVATE_KEY_LENGTH; - } -#endif /* HAVE_PQM4 */ return ret; } @@ -216,12 +210,6 @@ int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) } } #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - (void)key; - if (ret == 0) { - *len = PQM4_PUBLIC_KEY_LENGTH; - } -#endif /* HAVE_PQM4 */ return ret; } @@ -264,12 +252,6 @@ int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) } } #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - (void)key; - if (ret == 0) { - *len = PQM4_CIPHERTEXT_LENGTH; - } -#endif /* HAVE_PQM4 */ return ret; } @@ -301,7 +283,7 @@ int wc_KyberKey_SharedSecretSize(KyberKey* key, word32* len) /** * Make a Kyber key object using a random number generator. * - * NOTE: rng is ignored. OQS and PQM4 don't use our RNG. + * NOTE: rng is ignored. OQS doesn't use our RNG. * * @param [in, out] key Kyber key ovject. * @param [in] rng Random number generator. @@ -362,14 +344,6 @@ int wc_KyberKey_MakeKey(KyberKey* key, WC_RNG* rng) wolfSSL_liboqsRngMutexUnlock(); OQS_KEM_free(kem); #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - if (ret == 0) { - if (crypto_kem_keypair(key->pub, key->priv) != 0) { - WOLFSSL_MSG("PQM4 keygen failure"); - ret = BAD_FUNC_ARG; - } - } -#endif /* HAVE_PQM4 */ if (ret != 0) { ForceZero(key, sizeof(*key)); @@ -394,7 +368,7 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, { (void)rand; (void)len; - /* OQS and PQM4 don't support external randomness. */ + /* OQS doesn't support external randomness. */ return wc_KyberKey_MakeKey(key, NULL); } @@ -471,14 +445,6 @@ int wc_KyberKey_Encapsulate(KyberKey* key, unsigned char* ct, unsigned char* ss, wolfSSL_liboqsRngMutexUnlock(); OQS_KEM_free(kem); #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - if (ret == 0) { - if (crypto_kem_enc(ct, ss, key->pub) != 0) { - WOLFSSL_MSG("PQM4 Encapsulation failure."); - ret = BAD_FUNC_ARG; - } - } -#endif /* HAVE_PQM4 */ return ret; } @@ -501,7 +467,7 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, { (void)rand; (void)len; - /* OQS and PQM4 don't support external randomness. */ + /* OQS doesn't support external randomness. */ return wc_KyberKey_Encapsulate(key, ct, ss, NULL); } @@ -577,14 +543,6 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, OQS_KEM_free(kem); #endif /* HAVE_LIBOQS */ -#ifdef HAVE_PQM4 - if (ret == 0) { - if (crypto_kem_dec(ss, ct, key->priv) != 0) { - WOLFSSL_MSG("PQM4 Decapsulation failure."); - ret = BAD_FUNC_ARG; - } - } -#endif /* HAVE_PQM4 */ return ret; @@ -750,4 +708,4 @@ int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len) return ret; } -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_KYBER && !WOLFSSL_WC_KYBER */ diff --git a/src/wolfcrypt/src/ext_lms.c b/src/wolfcrypt/src/ext_lms.c index 7a59576..70dfa5b 100644 --- a/src/wolfcrypt/src/ext_lms.c +++ b/src/wolfcrypt/src/ext_lms.c @@ -1,6 +1,6 @@ /* ext_lms.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -27,7 +27,8 @@ #include #include -#ifdef WOLFSSL_HAVE_LMS +#if defined(WOLFSSL_HAVE_LMS) && defined(HAVE_LIBLMS) + #include #ifdef NO_INLINE @@ -1048,4 +1049,4 @@ int wc_LmsKey_Verify(LmsKey * key, const byte * sig, word32 sigSz, return 0; } -#endif /* WOLFSSL_HAVE_LMS */ +#endif /* WOLFSSL_HAVE_LMS && HAVE_LIBLMS */ diff --git a/src/wolfcrypt/src/ext_xmss.c b/src/wolfcrypt/src/ext_xmss.c index 9ce012e..938d513 100644 --- a/src/wolfcrypt/src/ext_xmss.c +++ b/src/wolfcrypt/src/ext_xmss.c @@ -1,6 +1,6 @@ /* ext_xmss.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,7 +28,8 @@ #include #include -#ifdef WOLFSSL_HAVE_XMSS +#if defined(WOLFSSL_HAVE_XMSS) && defined(HAVE_LIBXMSS) + #include #ifdef NO_INLINE @@ -1042,4 +1043,4 @@ int wc_XmssKey_Verify(XmssKey * key, const byte * sig, word32 sigLen, return ret; } -#endif /* WOLFSSL_HAVE_XMSS */ +#endif /* WOLFSSL_HAVE_XMSS && HAVE_LIBXMSS */ diff --git a/src/wolfcrypt/src/falcon.c b/src/wolfcrypt/src/falcon.c index 04309db..b1aabb1 100644 --- a/src/wolfcrypt/src/falcon.c +++ b/src/wolfcrypt/src/falcon.c @@ -1,6 +1,6 @@ /* falcon.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/fe_448.c b/src/wolfcrypt/src/fe_448.c index 36c6096..ede162a 100644 --- a/src/wolfcrypt/src/fe_448.c +++ b/src/wolfcrypt/src/fe_448.c @@ -1,6 +1,6 @@ /* fe_448.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/fe_low_mem.c b/src/wolfcrypt/src/fe_low_mem.c index 3556639..ad10a0e 100644 --- a/src/wolfcrypt/src/fe_low_mem.c +++ b/src/wolfcrypt/src/fe_low_mem.c @@ -1,6 +1,6 @@ /* fe_low_mem.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/fe_operations.c b/src/wolfcrypt/src/fe_operations.c index 704b455..2910151 100644 --- a/src/wolfcrypt/src/fe_operations.c +++ b/src/wolfcrypt/src/fe_operations.c @@ -1,6 +1,6 @@ /* fe_operations.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/ge_448.c b/src/wolfcrypt/src/ge_448.c index d2033af..415928f 100644 --- a/src/wolfcrypt/src/ge_448.c +++ b/src/wolfcrypt/src/ge_448.c @@ -1,6 +1,6 @@ /* ge_448.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -10781,18 +10781,10 @@ int ge448_double_scalarmult_vartime(ge448_p2 *r, const byte *a, } #if defined(WOLFSSL_SMALL_STACK) && (!defined(WOLFSSL_NO_MALLOC) || defined(XMALLOC_USER)) - if (p2 != NULL) { - XFREE(p2, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } - if (pi != NULL) { - XFREE(pi, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } - if (bslide != NULL) { - XFREE(bslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } - if (aslide != NULL) { - XFREE(aslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(p2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(pi, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(bslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(aslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; diff --git a/src/wolfcrypt/src/ge_low_mem.c b/src/wolfcrypt/src/ge_low_mem.c index abe6ea6..df747a1 100644 --- a/src/wolfcrypt/src/ge_low_mem.c +++ b/src/wolfcrypt/src/ge_low_mem.c @@ -1,6 +1,6 @@ /* ge_low_mem.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/ge_operations.c b/src/wolfcrypt/src/ge_operations.c index 57a838c..bcf9d35 100644 --- a/src/wolfcrypt/src/ge_operations.c +++ b/src/wolfcrypt/src/ge_operations.c @@ -1,6 +1,6 @@ /* ge_operations.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -9470,18 +9470,12 @@ int ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) out: - if (aslide != NULL) - XFREE(aslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (bslide != NULL) - XFREE(bslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (Ai != NULL) - XFREE(Ai, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (A2 != NULL) - XFREE(A2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(aslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(bslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(Ai, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(u, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(A2, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; #else diff --git a/src/wolfcrypt/src/hash.c b/src/wolfcrypt/src/hash.c index bc69c3b..b16c47d 100644 --- a/src/wolfcrypt/src/hash.c +++ b/src/wolfcrypt/src/hash.c @@ -1,6 +1,6 @@ /* hash.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -686,6 +686,44 @@ int wc_Hash(enum wc_HashType hash_type, const byte* data, NULL, INVALID_DEVID); } +#ifndef WC_NO_CONSTRUCTORS +wc_HashAlg* wc_HashNew(enum wc_HashType type, void* heap, int devId, + int *result_code) +{ + int ret; + wc_HashAlg* hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), heap, + DYNAMIC_TYPE_HASHES); + if (hash == NULL) { + ret = MEMORY_E; + } + else { + ret = wc_HashInit_ex(hash, type, heap, devId); + if (ret != 0) { + XFREE(hash, heap, DYNAMIC_TYPE_HASHES); + hash = NULL; + } + } + + if (result_code != NULL) + *result_code = ret; + + return hash; +} + +int wc_HashDelete(wc_HashAlg *hash, wc_HashAlg **hash_p) { + int ret; + if (hash == NULL) + return BAD_FUNC_ARG; + ret = wc_HashFree(hash, hash->type); + if (ret < 0) + return ret; + XFREE(hash, hash->heap, DYNAMIC_TYPE_HASHES); + if (hash_p != NULL) + *hash_p = NULL; + return 0; +} +#endif /* !WC_NO_CONSTRUCTORS */ + int wc_HashInit_ex(wc_HashAlg* hash, enum wc_HashType type, void* heap, int devId) { @@ -694,42 +732,50 @@ int wc_HashInit_ex(wc_HashAlg* hash, enum wc_HashType type, void* heap, if (hash == NULL) return BAD_FUNC_ARG; + hash->type = type; + +#ifdef WC_NO_CONSTRUCTORS + (void)heap; +#else + hash->heap = heap; +#endif + switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wc_InitMd5_ex(&hash->md5, heap, devId); + ret = wc_InitMd5_ex(&hash->alg.md5, heap, devId); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wc_InitSha_ex(&hash->sha, heap, devId); + ret = wc_InitSha_ex(&hash->alg.sha, heap, devId); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wc_InitSha224_ex(&hash->sha224, heap, devId); + ret = wc_InitSha224_ex(&hash->alg.sha224, heap, devId); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wc_InitSha256_ex(&hash->sha256, heap, devId); + ret = wc_InitSha256_ex(&hash->alg.sha256, heap, devId); #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wc_InitSha384_ex(&hash->sha384, heap, devId); + ret = wc_InitSha384_ex(&hash->alg.sha384, heap, devId); #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wc_InitSha512_ex(&hash->sha512, heap, devId); + ret = wc_InitSha512_ex(&hash->alg.sha512, heap, devId); #endif break; #ifndef WOLFSSL_NOSHA512_224 case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - ret = wc_InitSha512_224_ex(&hash->sha512, heap, devId); + ret = wc_InitSha512_224_ex(&hash->alg.sha512, heap, devId); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; @@ -738,35 +784,35 @@ int wc_HashInit_ex(wc_HashAlg* hash, enum wc_HashType type, void* heap, case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - ret = wc_InitSha512_256_ex(&hash->sha512, heap, devId); + ret = wc_InitSha512_256_ex(&hash->alg.sha512, heap, devId); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; #endif case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wc_InitSha3_224(&hash->sha3, heap, devId); + ret = wc_InitSha3_224(&hash->alg.sha3, heap, devId); #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wc_InitSha3_256(&hash->sha3, heap, devId); + ret = wc_InitSha3_256(&hash->alg.sha3, heap, devId); #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wc_InitSha3_384(&hash->sha3, heap, devId); + ret = wc_InitSha3_384(&hash->alg.sha3, heap, devId); #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wc_InitSha3_512(&hash->sha3, heap, devId); + ret = wc_InitSha3_512(&hash->alg.sha3, heap, devId); #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - ret = wc_InitSm3(&hash->sm3, heap, devId); + ret = wc_InitSm3(&hash->alg.sm3, heap, devId); break; #endif @@ -787,7 +833,6 @@ int wc_HashInit_ex(wc_HashAlg* hash, enum wc_HashType type, void* heap, ret = BAD_FUNC_ARG; }; - (void)heap; (void)devId; return ret; @@ -806,42 +851,49 @@ int wc_HashUpdate(wc_HashAlg* hash, enum wc_HashType type, const byte* data, if (hash == NULL || (data == NULL && dataSz > 0)) return BAD_FUNC_ARG; +#ifdef DEBUG_WOLFSSL + if (hash->type != type) { + WOLFSSL_MSG("Hash update type mismatch!"); + return BAD_FUNC_ARG; + } +#endif + switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wc_Md5Update(&hash->md5, data, dataSz); + ret = wc_Md5Update(&hash->alg.md5, data, dataSz); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wc_ShaUpdate(&hash->sha, data, dataSz); + ret = wc_ShaUpdate(&hash->alg.sha, data, dataSz); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wc_Sha224Update(&hash->sha224, data, dataSz); + ret = wc_Sha224Update(&hash->alg.sha224, data, dataSz); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wc_Sha256Update(&hash->sha256, data, dataSz); + ret = wc_Sha256Update(&hash->alg.sha256, data, dataSz); #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wc_Sha384Update(&hash->sha384, data, dataSz); + ret = wc_Sha384Update(&hash->alg.sha384, data, dataSz); #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wc_Sha512Update(&hash->sha512, data, dataSz); + ret = wc_Sha512Update(&hash->alg.sha512, data, dataSz); #endif break; #ifndef WOLFSSL_NOSHA512_224 case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - ret = wc_Sha512_224Update(&hash->sha512, data, dataSz); + ret = wc_Sha512_224Update(&hash->alg.sha512, data, dataSz); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; @@ -850,35 +902,35 @@ int wc_HashUpdate(wc_HashAlg* hash, enum wc_HashType type, const byte* data, case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - ret = wc_Sha512_256Update(&hash->sha512, data, dataSz); + ret = wc_Sha512_256Update(&hash->alg.sha512, data, dataSz); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; #endif case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wc_Sha3_224_Update(&hash->sha3, data, dataSz); + ret = wc_Sha3_224_Update(&hash->alg.sha3, data, dataSz); #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wc_Sha3_256_Update(&hash->sha3, data, dataSz); + ret = wc_Sha3_256_Update(&hash->alg.sha3, data, dataSz); #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wc_Sha3_384_Update(&hash->sha3, data, dataSz); + ret = wc_Sha3_384_Update(&hash->alg.sha3, data, dataSz); #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wc_Sha3_512_Update(&hash->sha3, data, dataSz); + ret = wc_Sha3_512_Update(&hash->alg.sha3, data, dataSz); #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - ret = wc_Sm3Update(&hash->sm3, data, dataSz); + ret = wc_Sm3Update(&hash->alg.sm3, data, dataSz); break; #endif @@ -909,42 +961,49 @@ int wc_HashFinal(wc_HashAlg* hash, enum wc_HashType type, byte* out) if (hash == NULL || out == NULL) return BAD_FUNC_ARG; +#ifdef DEBUG_WOLFSSL + if (hash->type != type) { + WOLFSSL_MSG("Hash final type mismatch!"); + return BAD_FUNC_ARG; + } +#endif + switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wc_Md5Final(&hash->md5, out); + ret = wc_Md5Final(&hash->alg.md5, out); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wc_ShaFinal(&hash->sha, out); + ret = wc_ShaFinal(&hash->alg.sha, out); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wc_Sha224Final(&hash->sha224, out); + ret = wc_Sha224Final(&hash->alg.sha224, out); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wc_Sha256Final(&hash->sha256, out); + ret = wc_Sha256Final(&hash->alg.sha256, out); #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wc_Sha384Final(&hash->sha384, out); + ret = wc_Sha384Final(&hash->alg.sha384, out); #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wc_Sha512Final(&hash->sha512, out); + ret = wc_Sha512Final(&hash->alg.sha512, out); #endif break; #ifndef WOLFSSL_NOSHA512_224 case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - ret = wc_Sha512_224Final(&hash->sha512, out); + ret = wc_Sha512_224Final(&hash->alg.sha512, out); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; @@ -953,35 +1012,35 @@ int wc_HashFinal(wc_HashAlg* hash, enum wc_HashType type, byte* out) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - ret = wc_Sha512_256Final(&hash->sha512, out); + ret = wc_Sha512_256Final(&hash->alg.sha512, out); #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ break; #endif case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wc_Sha3_224_Final(&hash->sha3, out); + ret = wc_Sha3_224_Final(&hash->alg.sha3, out); #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wc_Sha3_256_Final(&hash->sha3, out); + ret = wc_Sha3_256_Final(&hash->alg.sha3, out); #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wc_Sha3_384_Final(&hash->sha3, out); + ret = wc_Sha3_384_Final(&hash->alg.sha3, out); #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wc_Sha3_512_Final(&hash->sha3, out); + ret = wc_Sha3_512_Final(&hash->alg.sha3, out); #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - ret = wc_Sm3Final(&hash->sm3, out); + ret = wc_Sm3Final(&hash->alg.sm3, out); break; #endif @@ -1012,40 +1071,47 @@ int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) if (hash == NULL) return BAD_FUNC_ARG; +#ifdef DEBUG_WOLFSSL + if (hash->type != type) { + WOLFSSL_MSG("Hash free type mismatch!"); + return BAD_FUNC_ARG; + } +#endif + switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - wc_Md5Free(&hash->md5); + wc_Md5Free(&hash->alg.md5); ret = 0; #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - wc_ShaFree(&hash->sha); + wc_ShaFree(&hash->alg.sha); ret = 0; #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - wc_Sha224Free(&hash->sha224); + wc_Sha224Free(&hash->alg.sha224); ret = 0; #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - wc_Sha256Free(&hash->sha256); + wc_Sha256Free(&hash->alg.sha256); ret = 0; #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - wc_Sha384Free(&hash->sha384); + wc_Sha384Free(&hash->alg.sha384); ret = 0; #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - wc_Sha512Free(&hash->sha512); + wc_Sha512Free(&hash->alg.sha512); ret = 0; #endif break; @@ -1053,7 +1119,7 @@ int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - wc_Sha512_224Free(&hash->sha512); + wc_Sha512_224Free(&hash->alg.sha512); ret = 0; #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ @@ -1063,7 +1129,7 @@ int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - wc_Sha512_256Free(&hash->sha512); + wc_Sha512_256Free(&hash->alg.sha512); ret = 0; #endif #endif /* !HAVE_FIPS && !HAVE_SELFTEST */ @@ -1071,32 +1137,32 @@ int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type) #endif case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - wc_Sha3_224_Free(&hash->sha3); + wc_Sha3_224_Free(&hash->alg.sha3); ret = 0; #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - wc_Sha3_256_Free(&hash->sha3); + wc_Sha3_256_Free(&hash->alg.sha3); ret = 0; #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - wc_Sha3_384_Free(&hash->sha3); + wc_Sha3_384_Free(&hash->alg.sha3); ret = 0; #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - wc_Sha3_512_Free(&hash->sha3); + wc_Sha3_512_Free(&hash->alg.sha3); ret = 0; #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - wc_Sm3Free(&hash->sm3); + wc_Sm3Free(&hash->alg.sm3); ret = 0; break; #endif @@ -1132,27 +1198,27 @@ int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, word32 flags) switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wc_Md5SetFlags(&hash->md5, flags); + ret = wc_Md5SetFlags(&hash->alg.md5, flags); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wc_ShaSetFlags(&hash->sha, flags); + ret = wc_ShaSetFlags(&hash->alg.sha, flags); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wc_Sha224SetFlags(&hash->sha224, flags); + ret = wc_Sha224SetFlags(&hash->alg.sha224, flags); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wc_Sha256SetFlags(&hash->sha256, flags); + ret = wc_Sha256SetFlags(&hash->alg.sha256, flags); #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wc_Sha384SetFlags(&hash->sha384, flags); + ret = wc_Sha384SetFlags(&hash->alg.sha384, flags); #endif break; case WC_HASH_TYPE_SHA512: @@ -1163,7 +1229,7 @@ int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, word32 flags) case WC_HASH_TYPE_SHA512_256: #endif #ifdef WOLFSSL_SHA512 - ret = wc_Sha512SetFlags(&hash->sha512, flags); + ret = wc_Sha512SetFlags(&hash->alg.sha512, flags); #endif break; @@ -1172,13 +1238,13 @@ int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, word32 flags) case WC_HASH_TYPE_SHA3_384: case WC_HASH_TYPE_SHA3_512: #ifdef WOLFSSL_SHA3 - ret = wc_Sha3_SetFlags(&hash->sha3, flags); + ret = wc_Sha3_SetFlags(&hash->alg.sha3, flags); #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - ret = wc_Sm3SetFlags(&hash->sm3, flags); + ret = wc_Sm3SetFlags(&hash->alg.sm3, flags); break; #endif @@ -1211,27 +1277,27 @@ int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) switch (type) { case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wc_Md5GetFlags(&hash->md5, flags); + ret = wc_Md5GetFlags(&hash->alg.md5, flags); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wc_ShaGetFlags(&hash->sha, flags); + ret = wc_ShaGetFlags(&hash->alg.sha, flags); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wc_Sha224GetFlags(&hash->sha224, flags); + ret = wc_Sha224GetFlags(&hash->alg.sha224, flags); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wc_Sha256GetFlags(&hash->sha256, flags); + ret = wc_Sha256GetFlags(&hash->alg.sha256, flags); #endif break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wc_Sha384GetFlags(&hash->sha384, flags); + ret = wc_Sha384GetFlags(&hash->alg.sha384, flags); #endif break; case WC_HASH_TYPE_SHA512: @@ -1242,7 +1308,7 @@ int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) case WC_HASH_TYPE_SHA512_256: #endif #ifdef WOLFSSL_SHA512 - ret = wc_Sha512GetFlags(&hash->sha512, flags); + ret = wc_Sha512GetFlags(&hash->alg.sha512, flags); #endif break; @@ -1251,13 +1317,13 @@ int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) case WC_HASH_TYPE_SHA3_384: case WC_HASH_TYPE_SHA3_512: #ifdef WOLFSSL_SHA3 - ret = wc_Sha3_GetFlags(&hash->sha3, flags); + ret = wc_Sha3_GetFlags(&hash->alg.sha3, flags); #endif break; #ifdef WOLFSSL_SM3 case WC_HASH_TYPE_SM3: - ret = wc_Sm3GetFlags(&hash->sm3, flags); + ret = wc_Sm3GetFlags(&hash->alg.sm3, flags); break; #endif diff --git a/src/wolfcrypt/src/hmac.c b/src/wolfcrypt/src/hmac.c index fb71bf3..47f8f13 100644 --- a/src/wolfcrypt/src/hmac.c +++ b/src/wolfcrypt/src/hmac.c @@ -1,6 +1,6 @@ /* hmac.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/hpke.c b/src/wolfcrypt/src/hpke.c index 15e8d85..450ee73 100644 --- a/src/wolfcrypt/src/hpke.c +++ b/src/wolfcrypt/src/hpke.c @@ -1,6 +1,6 @@ /* hpke.c * - * Copyright (C) 2006-2022 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/integer.c b/src/wolfcrypt/src/integer.c index dadfeb4..3deeaeb 100644 --- a/src/wolfcrypt/src/integer.c +++ b/src/wolfcrypt/src/integer.c @@ -1,6 +1,6 @@ /* integer.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/kdf.c b/src/wolfcrypt/src/kdf.c index 9edf3a5..1bb338e 100644 --- a/src/wolfcrypt/src/kdf.c +++ b/src/wolfcrypt/src/kdf.c @@ -1,6 +1,6 @@ /* kdf.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -84,11 +84,9 @@ int wc_PRF(byte* result, word32 resLen, const byte* secret, word32 lastTime; int ret = 0; #ifdef WOLFSSL_SMALL_STACK - byte* previous; byte* current; Hmac* hmac; #else - byte previous[P_HASH_MAX_SIZE]; /* max size */ byte current[P_HASH_MAX_SIZE]; /* max size */ Hmac hmac[1]; #endif @@ -153,19 +151,16 @@ int wc_PRF(byte* result, word32 resLen, const byte* secret, lastTime = times - 1; #ifdef WOLFSSL_SMALL_STACK - previous = (byte*)XMALLOC(P_HASH_MAX_SIZE, heap, DYNAMIC_TYPE_DIGEST); - current = (byte*)XMALLOC(P_HASH_MAX_SIZE, heap, DYNAMIC_TYPE_DIGEST); - hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_HMAC); - if (previous == NULL || current == NULL || hmac == NULL) { - if (previous) XFREE(previous, heap, DYNAMIC_TYPE_DIGEST); - if (current) XFREE(current, heap, DYNAMIC_TYPE_DIGEST); - if (hmac) XFREE(hmac, heap, DYNAMIC_TYPE_HMAC); + current = (byte*)XMALLOC(P_HASH_MAX_SIZE, heap, DYNAMIC_TYPE_DIGEST); + hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_HMAC); + if (current == NULL || hmac == NULL) { + XFREE(current, heap, DYNAMIC_TYPE_DIGEST); + XFREE(hmac, heap, DYNAMIC_TYPE_HMAC); return MEMORY_E; } #endif #ifdef WOLFSSL_CHECK_MEM_ZERO - XMEMSET(previous, 0xff, P_HASH_MAX_SIZE); - wc_MemZero_Add("wc_PRF previous", previous, P_HASH_MAX_SIZE); + XMEMSET(current, 0xff, P_HASH_MAX_SIZE); wc_MemZero_Add("wc_PRF current", current, P_HASH_MAX_SIZE); wc_MemZero_Add("wc_PRF hmac", hmac, sizeof(Hmac)); #endif @@ -176,53 +171,53 @@ int wc_PRF(byte* result, word32 resLen, const byte* secret, if (ret == 0) ret = wc_HmacUpdate(hmac, seed, seedLen); /* A0 = seed */ if (ret == 0) - ret = wc_HmacFinal(hmac, previous); /* A1 */ + ret = wc_HmacFinal(hmac, current); /* A1 */ if (ret == 0) { word32 i; word32 idx = 0; for (i = 0; i < times; i++) { - ret = wc_HmacUpdate(hmac, previous, len); + ret = wc_HmacUpdate(hmac, current, len); if (ret != 0) break; ret = wc_HmacUpdate(hmac, seed, seedLen); if (ret != 0) break; - ret = wc_HmacFinal(hmac, current); - if (ret != 0) - break; - - if ((i == lastTime) && lastLen) - XMEMCPY(&result[idx], current, - min(lastLen, P_HASH_MAX_SIZE)); - else { - XMEMCPY(&result[idx], current, len); + if ((i != lastTime) || !lastLen) { + ret = wc_HmacFinal(hmac, &result[idx]); + if (ret != 0) + break; idx += len; - ret = wc_HmacUpdate(hmac, previous, len); + + ret = wc_HmacUpdate(hmac, current, len); if (ret != 0) break; - ret = wc_HmacFinal(hmac, previous); + ret = wc_HmacFinal(hmac, current); if (ret != 0) break; } + else { + ret = wc_HmacFinal(hmac, current); + if (ret != 0) + break; + XMEMCPY(&result[idx], current, + min(lastLen, P_HASH_MAX_SIZE)); + } } } wc_HmacFree(hmac); } - ForceZero(previous, P_HASH_MAX_SIZE); - ForceZero(current, P_HASH_MAX_SIZE); - ForceZero(hmac, sizeof(Hmac)); + ForceZero(current, P_HASH_MAX_SIZE); + ForceZero(hmac, sizeof(Hmac)); #if defined(WOLFSSL_CHECK_MEM_ZERO) - wc_MemZero_Check(previous, P_HASH_MAX_SIZE); - wc_MemZero_Check(current, P_HASH_MAX_SIZE); - wc_MemZero_Check(hmac, sizeof(Hmac)); + wc_MemZero_Check(current, P_HASH_MAX_SIZE); + wc_MemZero_Check(hmac, sizeof(Hmac)); #endif #ifdef WOLFSSL_SMALL_STACK - XFREE(previous, heap, DYNAMIC_TYPE_DIGEST); - XFREE(current, heap, DYNAMIC_TYPE_DIGEST); + XFREE(current, heap, DYNAMIC_TYPE_DIGEST); XFREE(hmac, heap, DYNAMIC_TYPE_HMAC); #endif diff --git a/src/wolfcrypt/src/logging.c b/src/wolfcrypt/src/logging.c index de87dbf..d548cd6 100644 --- a/src/wolfcrypt/src/logging.c +++ b/src/wolfcrypt/src/logging.c @@ -1,6 +1,6 @@ /* logging.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -471,26 +471,48 @@ void WOLFSSL_BUFFER(const byte* buffer, word32 length) while (buflen > 0) { int bufidx = 0; - XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "\t"); + if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "\t") + >= (int)sizeof(line) - bufidx) + { + goto errout; + } bufidx++; for (i = 0; i < LINE_LEN; i++) { if (i < buflen) { - XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "%02x ", buffer[i]); + if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "%02x ", + buffer[i]) >= (int)sizeof(line) - bufidx) + { + goto errout; + } } else { - XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, " "); + if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, " ") + >= (int)sizeof(line) - bufidx) + { + goto errout; + } } bufidx += 3; } - XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "| "); + if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "| ") + >= (int)sizeof(line) - bufidx) + { + goto errout; + } bufidx++; for (i = 0; i < LINE_LEN; i++) { if (i < buflen) { - XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, - "%c", 31 < buffer[i] && buffer[i] < 127 ? buffer[i] : '.'); + if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, + "%c", 31 < buffer[i] && buffer[i] < 127 + ? buffer[i] + : '.') + >= (int)sizeof(line) - bufidx) + { + goto errout; + } bufidx++; } } @@ -499,6 +521,12 @@ void WOLFSSL_BUFFER(const byte* buffer, word32 length) buffer += LINE_LEN; buflen -= LINE_LEN; } + + return; + +errout: + + wolfssl_log(INFO_LOG, NULL, 0, "\t[Buffer error while rendering]"); } #undef WOLFSSL_ENTER /* undo WOLFSSL_DEBUG_CODEPOINTS wrapper */ @@ -506,7 +534,11 @@ void WOLFSSL_ENTER(const char* msg) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; - XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg); + if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg) + >= (int)sizeof(buffer)) + { + buffer[sizeof(buffer) - 1] = 0; + } wolfssl_log(ENTER_LOG, NULL, 0, buffer); } } @@ -516,7 +548,11 @@ void WOLFSSL_ENTER2(const char *file, int line, const char* msg) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; - XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg); + if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg) + >= (int)sizeof(buffer)) + { + buffer[sizeof(buffer) - 1] = 0; + } wolfssl_log(ENTER_LOG, file, line, buffer); } } @@ -527,8 +563,12 @@ void WOLFSSL_LEAVE(const char* msg, int ret) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; - XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", - msg, ret); + if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", + msg, ret) + >= (int)sizeof(buffer)) + { + buffer[sizeof(buffer) - 1] = 0; + } wolfssl_log(LEAVE_LOG, NULL, 0, buffer); } } @@ -538,8 +578,12 @@ void WOLFSSL_LEAVE2(const char *file, int line, const char* msg, int ret) { if (loggingEnabled) { char buffer[WOLFSSL_MAX_ERROR_SZ]; - XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", - msg, ret); + if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d", + msg, ret) + >= (int)sizeof(buffer)) + { + buffer[sizeof(buffer) - 1] = 0; + } wolfssl_log(LEAVE_LOG, file, line, buffer); } } @@ -1674,3 +1718,144 @@ void WOLFSSL_ERROR_MSG(const char* msg) } #endif /* DEBUG_WOLFSSL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ + +#ifdef WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES + +#ifdef WOLFSSL_LINUXKM + +void wc_backtrace_render(void) { + dump_stack(); +} + +#else /* !WOLFSSL_LINUXKM */ + +#include + +#if BACKTRACE_SUPPORTED != 1 + #error WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES is defined but BACKTRACE_SUPPORTED is 0. +#endif + +#if !defined(WOLFSSL_MUTEX_INITIALIZER) && defined(WOLFSSL_NO_ATOMICS) + #error WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES requires WOLFSSL_MUTEX_INITIALIZER or wolfSSL_Atomic_Ints. +#endif + +#include + +static int backtrace_callback(void *data, uintptr_t pc, const char *filename, + int lineno, const char *function) +{ + if (function == NULL) + return 0; + /* the first callback is for the call to wc_print_backtrace() -- skip it. */ + if (*(int *)data == 0) { + *(int *)data = 1; + return 0; + } +#ifdef NO_STDIO_FILESYSTEM + printf(" #%d %p in %s %s:%d\n", (*(int *)data)++, (void *)pc, + function, filename, lineno); +#else + fprintf(stderr, " #%d %p in %s %s:%d\n", (*(int *)data)++, (void *)pc, + function, filename, lineno); +#endif + return 0; +} + +static void backtrace_error(void *data, const char *msg, int errnum) { + (void)data; +#ifdef NO_STDIO_FILESYSTEM + printf("ERR TRACE: error %d while backtracing: %s", errnum, msg); +#else + fprintf(stderr, "ERR TRACE: error %d while backtracing: %s", errnum, msg); +#endif +} + +static void backtrace_creation_error(void *data, const char *msg, int errnum) { + (void)data; +#ifdef NO_STDIO_FILESYSTEM + printf("ERR TRACE: internal error %d " + "while initializing backtrace facility: %s", errnum, msg); + printf("ERR TRACE: internal error " + "while initializing backtrace facility"); +#else + fprintf(stderr, "ERR TRACE: internal error %d " + "while initializing backtrace facility: %s", errnum, msg); +#endif +} + +static int backtrace_init(struct backtrace_state **backtrace_state) { +#ifdef WOLFSSL_MUTEX_INITIALIZER + static wolfSSL_Mutex backtrace_create_state_mutex = + WOLFSSL_MUTEX_INITIALIZER(backtrace_create_state_mutex); + if (wc_LockMutex(&backtrace_create_state_mutex) != 0) + return -1; +#elif defined(WOLFSSL_ATOMIC_OPS) + static wolfSSL_Atomic_Int init_count = 0; + if (wolfSSL_Atomic_Int_FetchAdd(&init_count, 1) != 1) + return -1; +#endif + if (*backtrace_state == NULL) { + /* passing a NULL filename to backtrace_create_state() tells + * libbacktrace to use a target-specific strategy to determine the + * executable. "libbacktrace supports ELF, PE/COFF, Mach-O, and XCOFF + * executables with DWARF debugging information. In other words, it + * supports GNU/Linux, *BSD, macOS, Windows, and AIX." + */ + *backtrace_state = backtrace_create_state( + NULL, 0, backtrace_creation_error, NULL); + } +#ifdef WOLFSSL_MUTEX_INITIALIZER + wc_UnLockMutex(&backtrace_create_state_mutex); +#endif + if (*backtrace_state == NULL) + return -1; + return 0; +} + +void wc_backtrace_render(void) { + static wolfSSL_Mutex backtrace_mutex + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(backtrace_mutex); + static struct backtrace_state *backtrace_state = NULL; + int depth = 0; + +#ifndef WOLFSSL_MUTEX_INITIALIZER + static wolfSSL_Atomic_Int init_count = 0; + if (init_count != 1) { + int cur_init_count = wolfSSL_Atomic_Int_FetchSub(&init_count, 1); + if (cur_init_count != 0) { + (void)wolfSSL_Atomic_Int_FetchAdd(&init_count, 1); + return; + } + if (wc_InitMutex(&backtrace_mutex) != 0) + return; + /* set init_count to 1, race-free: (-1) - (0-2) = 1 */ + (void)wolfSSL_Atomic_Int_FetchSub(&init_count, cur_init_count - 2); + } +#endif + + /* backtrace_state can't be shared between threads even when + * BACKTRACE_SUPPORTS_THREADS == 1, so we serialize the render op. this + * helpfully mutexes the initialization too. + */ + if (wc_LockMutex(&backtrace_mutex) != 0) + return; + + if (backtrace_state == NULL) { + if (backtrace_init(&backtrace_state) < 0) { + wc_UnLockMutex(&backtrace_mutex); + return; + } + } + + /* note that the optimizer can produce misleading backtraces, even with + * -funwind-tables. in contrast, the macro-generated "ERR TRACE" message + * from WC_ERR_TRACE() always accurately identifies the error code point. + */ + backtrace_full(backtrace_state, 0, backtrace_callback, backtrace_error, + (void *)&depth); + + wc_UnLockMutex(&backtrace_mutex); +} +#endif /* !WOLFSSL_LINUXKM */ + +#endif /* WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES */ diff --git a/src/wolfcrypt/src/md2.c b/src/wolfcrypt/src/md2.c index 789704e..c28a049 100644 --- a/src/wolfcrypt/src/md2.c +++ b/src/wolfcrypt/src/md2.c @@ -1,6 +1,6 @@ /* md2.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -123,7 +123,7 @@ void wc_Md2Final(Md2* md2, byte* hash) for (i = 0; i < padLen; i++) padding[i] = (byte)padLen; - wc_Md2Update(md2, padding, padLen); + wc_Md2Update(md2, padding, padLen); /* cppcheck-suppress uninitvar */ wc_Md2Update(md2, md2->C, MD2_BLOCK_SIZE); XMEMCPY(hash, md2->X, MD2_DIGEST_SIZE); diff --git a/src/wolfcrypt/src/md4.c b/src/wolfcrypt/src/md4.c index 68eab5f..65b4dc2 100644 --- a/src/wolfcrypt/src/md4.c +++ b/src/wolfcrypt/src/md4.c @@ -1,6 +1,6 @@ /* md4.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/md5.c b/src/wolfcrypt/src/md5.c index daab9c9..f6ca240 100644 --- a/src/wolfcrypt/src/md5.c +++ b/src/wolfcrypt/src/md5.c @@ -1,6 +1,6 @@ /* md5.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/memory.c b/src/wolfcrypt/src/memory.c index d9958a9..75d0389 100644 --- a/src/wolfcrypt/src/memory.c +++ b/src/wolfcrypt/src/memory.c @@ -1,6 +1,6 @@ /* memory.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -32,6 +32,7 @@ #endif #include +#include /* Possible memory options: @@ -793,9 +794,13 @@ int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, void wc_UnloadStaticMemory(WOLFSSL_HEAP_HINT* heap) { WOLFSSL_ENTER("wc_UnloadStaticMemory"); +#ifndef SINGLE_THREADED if (heap != NULL && heap->memory != NULL) { wc_FreeMutex(&heap->memory->memory_mutex); } +#else + (void)heap; +#endif } #ifndef WOLFSSL_STATIC_MEMORY_LEAN @@ -1207,6 +1212,9 @@ void wolfSSL_Free(void *ptr, void* heap, int type) #else free(ptr); #endif + #ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "Free: %p at %s:%d\n", ptr, func, line); + #endif #else WOLFSSL_MSG("Error trying to call free when turned off"); #endif /* WOLFSSL_NO_MALLOC */ diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index 10f733b..e4b53d9 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -1,6 +1,6 @@ /* misc.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -211,6 +211,52 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in, #if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_NO_WORD64_OPS) +WC_MISC_STATIC WC_INLINE word64 readUnalignedWord64(const byte *in) +{ + if (((wc_ptr_t)in & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) + return *(word64 *)in; + else { + word64 out; + XMEMCPY(&out, in, sizeof(word64)); + return out; + } +} + +WC_MISC_STATIC WC_INLINE word64 writeUnalignedWord64(void *out, word64 in) +{ + if (((wc_ptr_t)out & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) + *(word64 *)out = in; + else { + XMEMCPY(out, &in, sizeof(word64)); + } + return in; +} + +WC_MISC_STATIC WC_INLINE void readUnalignedWords64(word64 *out, const byte *in, + size_t count) +{ + if (((wc_ptr_t)in & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) { + const word64 *in_word64 = (const word64 *)in; + while (count-- > 0) + *out++ = *in_word64++; + } + else { + XMEMCPY(out, in, count * sizeof(word64)); + } +} + +WC_MISC_STATIC WC_INLINE void writeUnalignedWords64(byte *out, const word64 *in, + size_t count) +{ + if (((wc_ptr_t)out & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) { + word64 *out_word64 = (word64 *)out; + while (count-- > 0) + *out_word64++ = *in++; + } + else { + XMEMCPY(out, in, count * sizeof(word64)); + } +} WC_MISC_STATIC WC_INLINE word64 rotlFixed64(word64 x, word64 y) { @@ -709,13 +755,23 @@ WC_MISC_STATIC WC_INLINE void w64SetLow32(w64wrapper *n, word32 low) { WC_MISC_STATIC WC_INLINE w64wrapper w64Add32(w64wrapper a, word32 b, byte *wrap) { - a.n = a.n + b; + a.n += b; if (a.n < b && wrap != NULL) *wrap = 1; return a; } +WC_MISC_STATIC WC_INLINE w64wrapper w64Add(w64wrapper a, w64wrapper b, + byte *wrap) +{ + a.n += b.n; + if (a.n < b.n && wrap != NULL) + *wrap = 1; + + return a; +} + WC_MISC_STATIC WC_INLINE w64wrapper w64Sub32(w64wrapper a, word32 b, byte *wrap) { if (a.n < b && wrap != NULL) @@ -796,6 +852,13 @@ WC_MISC_STATIC WC_INLINE w64wrapper w64ShiftLeft(w64wrapper a, int shift) return a; } +WC_MISC_STATIC WC_INLINE w64wrapper w64Mul(word32 a, word32 b) +{ + w64wrapper ret; + ret.n = (word64)a * (word64)b; + return ret; +} + #else WC_MISC_STATIC WC_INLINE void w64Increment(w64wrapper *n) @@ -831,7 +894,7 @@ WC_MISC_STATIC WC_INLINE void w64SetLow32(w64wrapper *n, word32 low) WC_MISC_STATIC WC_INLINE w64wrapper w64Add32(w64wrapper a, word32 b, byte *wrap) { - a.n[1] = a.n[1] + b; + a.n[1] += b; if (a.n[1] < b) { a.n[0]++; if (wrap != NULL && a.n[0] == 0) @@ -841,6 +904,24 @@ WC_MISC_STATIC WC_INLINE w64wrapper w64Add32(w64wrapper a, word32 b, byte *wrap) return a; } +WC_MISC_STATIC WC_INLINE w64wrapper w64Add(w64wrapper a, w64wrapper b, + byte *wrap) +{ + a.n[1] += b.n[1]; + if (a.n[1] < b.n[1]) { + a.n[0]++; + if (wrap != NULL && a.n[0] == 0) + *wrap = 1; + } + + a.n[0] += b.n[0]; + if (wrap != NULL && a.n[0] < b.n[0]) { + *wrap = 1; + } + + return a; +} + WC_MISC_STATIC WC_INLINE w64wrapper w64Sub32(w64wrapper a, word32 b, byte *wrap) { byte _underflow = 0; @@ -894,7 +975,7 @@ WC_MISC_STATIC WC_INLINE byte w64IsZero(w64wrapper a) return a.n[0] == 0 && a.n[1] == 0; } -WC_MISC_STATIC WC_INLINE void c64toa(w64wrapper *a, byte *out) +WC_MISC_STATIC WC_INLINE void c64toa(const w64wrapper *a, byte *out) { #ifdef BIG_ENDIAN_ORDER word32 *_out = (word32*)(out); @@ -939,7 +1020,7 @@ WC_MISC_STATIC WC_INLINE byte w64LT(w64wrapper a, w64wrapper b) WC_MISC_STATIC WC_INLINE w64wrapper w64ShiftRight(w64wrapper a, int shift) { if (shift < 32) { - a.n[1] = (a.n[1] >> shift) || (a.n[0] << (32 - shift)); + a.n[1] = (a.n[1] >> shift) | (a.n[0] << (32 - shift)); a.n[0] >>= shift; } else { @@ -951,7 +1032,7 @@ WC_MISC_STATIC WC_INLINE w64wrapper w64ShiftRight(w64wrapper a, int shift) WC_MISC_STATIC WC_INLINE w64wrapper w64ShiftLeft(w64wrapper a, int shift) { if (shift < 32) { - a.n[0] = (a.n[0] << shift) || (a.n[1] >> (32 - shift)); + a.n[0] = (a.n[0] << shift) | (a.n[1] >> (32 - shift)); a.n[1] <<= shift; } else { @@ -961,6 +1042,30 @@ WC_MISC_STATIC WC_INLINE w64wrapper w64ShiftLeft(w64wrapper a, int shift) return a; } +WC_MISC_STATIC WC_INLINE w64wrapper w64Mul(word32 a, word32 b) +{ + w64wrapper ret; + word16 ltlA, ltlB, ltlC, ltlD; + word32 bigA, bigB, bigC, bigD; + + ltlA = a & 0xFFFF; + ltlB = (a >> 16) & 0xFFFF; + ltlC = b & 0xFFFF; + ltlD = (b >> 16) & 0xFFFF; + + bigA = (word32)ltlA * (word32)ltlC; + bigC = (word32)ltlB * (word32)ltlC; + bigD = (word32)ltlA * (word32)ltlD; + bigB = (word32)ltlB * (word32)ltlD; + + ret = w64From32(0, bigB); + ret = w64ShiftLeft(ret, 16); + ret = w64Add32(ret, bigD, NULL); + ret = w64Add32(ret, bigC, NULL); + ret = w64ShiftLeft(ret, 16); + return w64Add32(ret, bigA, NULL); +} + #endif /* WORD64_AVAILABLE && !WOLFSSL_W64_WRAPPER_TEST */ #endif /* WOLFSSL_W64_WRAPPER */ diff --git a/src/wolfcrypt/src/pkcs12.c b/src/wolfcrypt/src/pkcs12.c index ef111a6..e8cc11e 100644 --- a/src/wolfcrypt/src/pkcs12.c +++ b/src/wolfcrypt/src/pkcs12.c @@ -1,6 +1,6 @@ /* pkcs12.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -165,9 +165,7 @@ static void freeSafe(AuthenticatedSafe* safe, void* heap) safe->CI = ci->next; XFREE(ci, heap, DYNAMIC_TYPE_PKCS); } - if (safe->data != NULL) { - XFREE(safe->data, heap, DYNAMIC_TYPE_PKCS); - } + XFREE(safe->data, heap, DYNAMIC_TYPE_PKCS); XFREE(safe, heap, DYNAMIC_TYPE_PKCS); (void)heap; @@ -191,22 +189,14 @@ void wc_PKCS12_free(WC_PKCS12* pkcs12) /* free mac data */ if (pkcs12->signData != NULL) { - if (pkcs12->signData->digest != NULL) { - XFREE(pkcs12->signData->digest, heap, DYNAMIC_TYPE_DIGEST); - } - if (pkcs12->signData->salt != NULL) { - XFREE(pkcs12->signData->salt, heap, DYNAMIC_TYPE_SALT); - } + XFREE(pkcs12->signData->digest, heap, DYNAMIC_TYPE_DIGEST); + XFREE(pkcs12->signData->salt, heap, DYNAMIC_TYPE_SALT); XFREE(pkcs12->signData, heap, DYNAMIC_TYPE_PKCS); } #ifdef ASN_BER_TO_DER - if (pkcs12->der != NULL) { - XFREE(pkcs12->der, pkcs12->heap, DYNAMIC_TYPE_PKCS); - } - if (pkcs12->safeDer != NULL) { - XFREE(pkcs12->safeDer, pkcs12->heap, DYNAMIC_TYPE_PKCS); - } + XFREE(pkcs12->der, pkcs12->heap, DYNAMIC_TYPE_PKCS); + XFREE(pkcs12->safeDer, pkcs12->heap, DYNAMIC_TYPE_PKCS); #endif XFREE(pkcs12, heap, DYNAMIC_TYPE_PKCS); @@ -533,8 +523,7 @@ static int GetSignData(WC_PKCS12* pkcs12, const byte* mem, word32* idx, /* failure cleanup */ if (ret != 0) { if (mac) { - if (mac->digest) - XFREE(mac->digest, pkcs12->heap, DYNAMIC_TYPE_DIGEST); + XFREE(mac->digest, pkcs12->heap, DYNAMIC_TYPE_DIGEST); XFREE(mac, pkcs12->heap, DYNAMIC_TYPE_PKCS); } } @@ -856,9 +845,7 @@ int wc_d2i_PKCS12_fp(const char* file, WC_PKCS12** pkcs12) wc_PKCS12_free(*pkcs12); *pkcs12 = NULL; } - if (buf != NULL) { - XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); WOLFSSL_LEAVE("wc_d2i_PKCS12_fp", ret); @@ -1008,7 +995,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) if (der == NULL && derSz != NULL) { *derSz = (int)totalSz; XFREE(sdBuf, pkcs12->heap, DYNAMIC_TYPE_PKCS); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*der == NULL) { @@ -1099,9 +1086,7 @@ void wc_FreeCertList(WC_DerCertList* list, void* heap) while (current != NULL) { next = current->next; - if (current->buffer != NULL) { - XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); - } + XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS); XFREE(current, heap, DYNAMIC_TYPE_PKCS); current = next; } @@ -1127,7 +1112,7 @@ static WARN_UNUSED_RESULT int freeDecCertList(WC_DerCertList** list, InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap); if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL) == 0) { - if (wc_CheckPrivateKeyCert(*pkey, *pkeySz, DeCert, 0) == 1) { + if (wc_CheckPrivateKeyCert(*pkey, *pkeySz, DeCert, 0, heap) == 1) { WOLFSSL_MSG("Key Pair found"); *cert = current->buffer; *certSz = current->bufferSz; @@ -1707,10 +1692,8 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, } /* free temporary buffer */ - if (buf != NULL) { - XFREE(buf, pkcs12->heap, DYNAMIC_TYPE_PKCS); - buf = NULL; - } + XFREE(buf, pkcs12->heap, DYNAMIC_TYPE_PKCS); + buf = NULL; ci = ci->next; WOLFSSL_MSG("Done Parsing PKCS12 Content Info Container"); @@ -1744,10 +1727,8 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, XFREE(*pkey, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); *pkey = NULL; } - if (buf) { - XFREE(buf, pkcs12->heap, DYNAMIC_TYPE_PKCS); - buf = NULL; - } + XFREE(buf, pkcs12->heap, DYNAMIC_TYPE_PKCS); + buf = NULL; wc_FreeCertList(certList, pkcs12->heap); } @@ -1828,7 +1809,7 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, } if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { *outSz = sz + MAX_LENGTH_SZ + 1; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (ret < 0) { return ret; @@ -1890,7 +1871,7 @@ static int wc_PKCS12_create_key_bag(WC_PKCS12* pkcs12, WC_RNG* rng, if (out == NULL) { *outSz = MAX_SEQ_SZ + WC_PKCS12_DATA_OBJ_SZ + 1 + MAX_LENGTH_SZ + length; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } heap = wc_PKCS12_GetHeap(pkcs12); @@ -1967,7 +1948,7 @@ static int wc_PKCS12_create_cert_bag(WC_PKCS12* pkcs12, *outSz = (word32)(MAX_SEQ_SZ + WC_CERTBAG_OBJECT_ID + 1 + MAX_LENGTH_SZ + MAX_SEQ_SZ + WC_CERTBAG1_OBJECT_ID + 1 + MAX_LENGTH_SZ + 1 + MAX_LENGTH_SZ + (int)certSz); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* check buffer size able to handle max size */ @@ -2112,7 +2093,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, totalSz += SetLength(outerSz, seq) + outerSz; if (out == NULL) { *outSz = totalSz + SetSequence(totalSz, seq); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*outSz < totalSz + SetSequence(totalSz, seq)) { @@ -2200,7 +2181,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, if (out == NULL) { *outSz = totalSz + SetSequence(totalSz, seq); - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*outSz < (totalSz + SetSequence(totalSz, seq))) { diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index acf7ef8..bb37054 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -1,6 +1,6 @@ /* pkcs7.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -118,12 +118,12 @@ struct PKCS7State { word32 peakUsed; /* most bytes used for struct at any one time */ word32 peakRead; /* most bytes used by read buffer */ #endif - byte multi:1; /* flag for if content is in multiple parts */ - byte flagOne:1; - byte detached:1; /* flag to indicate detached signature is present */ - byte noContent:1;/* indicates content isn't included in bundle */ - byte degenerate:1; - byte indefLen:1; /* flag to indicate indef-length encoding used */ + WC_BITFIELD multi:1; /* flag for if content is in multiple parts */ + WC_BITFIELD flagOne:1; + WC_BITFIELD detached:1; /* flag to indicate detached signature is present */ + WC_BITFIELD noContent:1;/* indicates content isn't included in bundle */ + WC_BITFIELD degenerate:1; + WC_BITFIELD indefLen:1; /* flag to indicate indef-length encoding used */ }; @@ -289,7 +289,7 @@ static int wc_PKCS7_AddDataToStream(PKCS7* pkcs7, byte* in, word32 inSz, /* try to store input data into stream buffer */ if (inSz - rdSz > 0 && pkcs7->stream->length < expected) { - int len = (int)min(inSz - rdSz, expected - pkcs7->stream->length); + word32 len = min(inSz - rdSz, expected - pkcs7->stream->length); /* sanity check that the input buffer is not internal buffer */ if (in == pkcs7->stream->buffer) { @@ -385,7 +385,7 @@ static int wc_PKCS7_SetMaxStream(PKCS7* pkcs7, byte* in, word32 defSz) } } #endif /* ASN_BER_TO_DER */ - pkcs7->stream->maxLen = length + idx; + pkcs7->stream->maxLen = (word32)length + idx; if (pkcs7->stream->maxLen == 0) { pkcs7->stream->maxLen = defSz; @@ -550,7 +550,7 @@ static int wc_SetContentType(int pkcs7TypeOID, byte* output, word32 outputSz) { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C }; #endif - int idSz, idx = 0; + word32 idSz, idx = 0; word32 typeSz = 0; const byte* typeName = 0; byte ID_Length[MAX_LENGTH_SZ]; @@ -630,14 +630,14 @@ static int wc_SetContentType(int pkcs7TypeOID, byte* output, word32 outputSz) return BAD_FUNC_ARG; } - idSz = (int)SetLength(typeSz, ID_Length); + idSz = SetLength(typeSz, ID_Length); output[idx++] = ASN_OBJECT_ID; XMEMCPY(output + idx, ID_Length, idSz); idx += idSz; XMEMCPY(output + idx, typeName, typeSz); idx += typeSz; - return idx; + return (int)idx; } @@ -819,7 +819,7 @@ int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId) isDynamic = pkcs7->isDynamic; XMEMSET(pkcs7, 0, sizeof(PKCS7)); - pkcs7->isDynamic = isDynamic; + pkcs7->isDynamic = (isDynamic != 0); #ifdef WOLFSSL_HEAP_TEST pkcs7->heap = (void*)WOLFSSL_HEAP_TEST; #else @@ -830,6 +830,14 @@ int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId) return 0; } +#ifdef WC_ASN_UNKNOWN_EXT_CB +void wc_PKCS7_SetUnknownExtCallback(PKCS7* pkcs7, wc_UnknownExtCallback cb) +{ + if (pkcs7 != NULL) { + pkcs7->unknownExtCallback = cb; + } +} +#endif /* Certificate structure holding der pointer, size, and pointer to next * Pkcs7Cert struct. Used when creating SignedData types with multiple @@ -879,7 +887,7 @@ static void wc_PKCS7_FreeCertSet(PKCS7* pkcs7) * Returns total size of recipients, or negative upon error */ static int wc_PKCS7_GetRecipientListSize(PKCS7* pkcs7) { - int totalSz = 0; + word32 totalSz = 0; Pkcs7EncodedRecip* tmp = NULL; if (pkcs7 == NULL) @@ -892,7 +900,7 @@ static int wc_PKCS7_GetRecipientListSize(PKCS7* pkcs7) tmp = tmp->next; } - return totalSz; + return (int)totalSz; } @@ -1074,6 +1082,9 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) int devId; Pkcs7Cert* cert; Pkcs7Cert* lastCert; +#ifdef WC_ASN_UNKNOWN_EXT_CB + wc_UnknownExtCallback cb; +#endif if (pkcs7 == NULL || (derCert == NULL && derCertSz != 0)) { return BAD_FUNC_ARG; @@ -1082,9 +1093,16 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) heap = pkcs7->heap; devId = pkcs7->devId; cert = pkcs7->certList; +#ifdef WC_ASN_UNKNOWN_EXT_CB + cb = pkcs7->unknownExtCallback; /* save / restore callback */ +#endif ret = wc_PKCS7_Init(pkcs7, heap, devId); if (ret != 0) return ret; + +#ifdef WC_ASN_UNKNOWN_EXT_CB + pkcs7->unknownExtCallback = cb; +#endif pkcs7->certList = cert; if (derCert != NULL && derCertSz > 0) { @@ -1133,6 +1151,10 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) } InitDecodedCert(dCert, derCert, derCertSz, pkcs7->heap); +#ifdef WC_ASN_UNKNOWN_EXT_CB + if (pkcs7->unknownExtCallback != NULL) + wc_SetUnknownExtCallback(dCert, pkcs7->unknownExtCallback); +#endif ret = ParseCert(dCert, CA_TYPE, NO_VERIFY, 0); if (ret < 0) { FreeDecodedCert(dCert); @@ -1143,7 +1165,7 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) } /* verify extracted public key is valid before storing */ - ret = wc_PKCS7_CheckPublicKeyDer(pkcs7, dCert->keyOID, + ret = wc_PKCS7_CheckPublicKeyDer(pkcs7, (int)dCert->keyOID, dCert->publicKey, dCert->pubKeySize); if (ret != 0) { WOLFSSL_MSG("Invalid public key, check pkcs7->cert"); @@ -1170,7 +1192,7 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) XMEMCPY(pkcs7->issuerHash, dCert->issuerHash, KEYID_SIZE); pkcs7->issuer = dCert->issuerRaw; pkcs7->issuerSz = (word32)dCert->issuerRawLen; - XMEMCPY(pkcs7->issuerSn, dCert->serial, dCert->serialSz); + XMEMCPY(pkcs7->issuerSn, dCert->serial, (word32)dCert->serialSz); pkcs7->issuerSnSz = (word32)dCert->serialSz; XMEMCPY(pkcs7->issuerSubjKeyId, dCert->extSubjKeyId, KEYID_SIZE); @@ -1243,12 +1265,8 @@ static void wc_PKCS7_FreeDecodedAttrib(PKCS7DecodedAttrib* attrib, void* heap) current = attrib; while (current != NULL) { PKCS7DecodedAttrib* next = current->next; - if (current->oid != NULL) { - XFREE(current->oid, heap, DYNAMIC_TYPE_PKCS7); - } - if (current->value != NULL) { - XFREE(current->value, heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(current->oid, heap, DYNAMIC_TYPE_PKCS7); + XFREE(current->value, heap, DYNAMIC_TYPE_PKCS7); XFREE(current, heap, DYNAMIC_TYPE_PKCS7); current = next; } @@ -1260,10 +1278,8 @@ static void wc_PKCS7_FreeDecodedAttrib(PKCS7DecodedAttrib* attrib, void* heap) /* return 0 on success */ static int wc_PKCS7_SignerInfoNew(PKCS7* pkcs7) { - if (pkcs7->signerInfo != NULL) { - XFREE(pkcs7->signerInfo, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->signerInfo = NULL; - } + XFREE(pkcs7->signerInfo, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->signerInfo = NULL; pkcs7->signerInfo = (PKCS7SignerInfo*)XMALLOC(sizeof(PKCS7SignerInfo), pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -1279,10 +1295,8 @@ static int wc_PKCS7_SignerInfoNew(PKCS7* pkcs7) static void wc_PKCS7_SignerInfoFree(PKCS7* pkcs7) { if (pkcs7->signerInfo != NULL) { - if (pkcs7->signerInfo->sid != NULL) { - XFREE(pkcs7->signerInfo->sid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->signerInfo->sid = NULL; - } + XFREE(pkcs7->signerInfo->sid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->signerInfo->sid = NULL; XFREE(pkcs7->signerInfo, pkcs7->heap, DYNAMIC_TYPE_PKCS7); pkcs7->signerInfo = NULL; } @@ -1298,16 +1312,14 @@ static int wc_PKCS7_SignerInfoSetSID(PKCS7* pkcs7, byte* in, int inSz) return BAD_FUNC_ARG; } - if (pkcs7->signerInfo->sid != NULL) { - XFREE(pkcs7->signerInfo->sid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->signerInfo->sid = NULL; - } - pkcs7->signerInfo->sid = (byte*)XMALLOC(inSz, pkcs7->heap, + XFREE(pkcs7->signerInfo->sid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->signerInfo->sid = NULL; + pkcs7->signerInfo->sid = (byte*)XMALLOC((word32)inSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->signerInfo->sid == NULL) { return MEMORY_E; } - XMEMCPY(pkcs7->signerInfo->sid, in, inSz); + XMEMCPY(pkcs7->signerInfo->sid, in, (word32)inSz); pkcs7->signerInfo->sidSz = (word32)inSz; return 0; } @@ -1329,15 +1341,11 @@ void wc_PKCS7_Free(PKCS7* pkcs7) wc_PKCS7_FreeCertSet(pkcs7); #ifdef ASN_BER_TO_DER - if (pkcs7->der != NULL) { - XFREE(pkcs7->der, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->der = NULL; - } + XFREE(pkcs7->der, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->der = NULL; #endif - if (pkcs7->contentDynamic != NULL) { - XFREE(pkcs7->contentDynamic, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->contentDynamic = NULL; - } + XFREE(pkcs7->contentDynamic, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->contentDynamic = NULL; if (pkcs7->cek != NULL) { ForceZero(pkcs7->cek, pkcs7->cekSz); @@ -1368,6 +1376,12 @@ void wc_PKCS7_Free(PKCS7* pkcs7) pkcs7->cachedEncryptedContentSz = 0; } + if (pkcs7->customSKID) { + XFREE(pkcs7->customSKID, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->customSKID = NULL; + pkcs7->customSKIDSz = 0; + } + if (pkcs7->isDynamic) { pkcs7->isDynamic = 0; XFREE(pkcs7, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -1448,7 +1462,7 @@ int wc_PKCS7_GetAttributeValue(PKCS7* pkcs7, const byte* oid, word32 oidSz, if (out == NULL) { *outSz = attrib->valueSz; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*outSz < attrib->valueSz) { @@ -1456,7 +1470,7 @@ int wc_PKCS7_GetAttributeValue(PKCS7* pkcs7, const byte* oid, word32 oidSz, } XMEMCPY(out, attrib->value, attrib->valueSz); - return attrib->valueSz; + return (int)attrib->valueSz; } @@ -1471,7 +1485,7 @@ int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz) word32 seqSz; word32 octetStrSz; word32 oidSz = (word32)sizeof(oid); - int idx = 0; + word32 idx = 0; if (pkcs7 == NULL || output == NULL) { return BAD_FUNC_ARG; @@ -1492,7 +1506,7 @@ int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz) XMEMCPY(output + idx, pkcs7->content, pkcs7->contentSz); idx += pkcs7->contentSz; - return idx; + return (int)idx; } @@ -1509,7 +1523,7 @@ typedef struct ESD { wc_HashAlg hash; enum wc_HashType hashType; byte contentDigest[WC_MAX_DIGEST_SIZE + 2]; /* content only + ASN.1 heading */ - byte contentDigestSet:1; + WC_BITFIELD contentDigestSet:1; byte contentAttribsDigest[WC_MAX_DIGEST_SIZE]; byte encContentDigest[MAX_ENCRYPTED_KEY_SZ]; @@ -1556,26 +1570,26 @@ static int EncodeAttributes(EncodedAttrib* ea, int eaSz, PKCS7Attrib* attribs, int attribsSz) { int i; - int maxSz = (int)min((word32)eaSz, attribsSz); + int maxSz = (int)min((word32)eaSz, (word32)attribsSz); int allAttribsSz = 0; for (i = 0; i < maxSz; i++) { - int attribSz = 0; + word32 attribSz = 0; ea[i].value = attribs[i].value; ea[i].valueSz = attribs[i].valueSz; attribSz += ea[i].valueSz; - ea[i].valueSetSz = SetSet((word32)attribSz, ea[i].valueSet); + ea[i].valueSetSz = SetSet(attribSz, ea[i].valueSet); attribSz += ea[i].valueSetSz; ea[i].oid = attribs[i].oid; ea[i].oidSz = attribs[i].oidSz; attribSz += ea[i].oidSz; - ea[i].valueSeqSz = SetSequence((word32)attribSz, ea[i].valueSeq); + ea[i].valueSeqSz = SetSequence(attribSz, ea[i].valueSeq); attribSz += ea[i].valueSeqSz; - ea[i].totalSz = (word32)attribSz; + ea[i].totalSz = attribSz; - allAttribsSz += attribSz; + allAttribsSz += (int)attribSz; } return allAttribsSz; } @@ -1664,7 +1678,8 @@ static int SortAttribArray(FlatAttrib** arr, int rows) static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, EncodedAttrib* ea, int eaSz) { - int i, idx, sz; + int i; + word32 idx, sz; byte* output = NULL; FlatAttrib* fa = NULL; @@ -1697,7 +1712,7 @@ static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, fa = derArr[i]; fa->data = output; - fa->dataSz = (word32)sz; + fa->dataSz = sz; } return 0; @@ -1708,7 +1723,8 @@ static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, static int FlattenAttributes(PKCS7* pkcs7, byte* output, EncodedAttrib* ea, int eaSz) { - int i, idx, ret; + int i, ret; + word32 idx; FlatAttrib** derArr = NULL; FlatAttrib* fa = NULL; @@ -2087,8 +2103,9 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, } esd->signedAttribsCount += cannedAttribsCount; - esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], - (int)idx, cannedAttribs, cannedAttribsCount); + esd->signedAttribsSz += (word32)EncodeAttributes( + &esd->signedAttribs[atrIdx], (int)idx, cannedAttribs, + (int)cannedAttribsCount); atrIdx += idx; } else { esd->signedAttribsCount = 0; @@ -2098,9 +2115,9 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, /* add custom signed attributes if set */ if (pkcs7->signedAttribsSz > 0 && pkcs7->signedAttribs != NULL) { esd->signedAttribsCount += pkcs7->signedAttribsSz; - esd->signedAttribsSz += EncodeAttributes(&esd->signedAttribs[atrIdx], - esd->signedAttribsCount, - pkcs7->signedAttribs, pkcs7->signedAttribsSz); + esd->signedAttribsSz += (word32)EncodeAttributes( + &esd->signedAttribs[atrIdx], (int)esd->signedAttribsCount, + pkcs7->signedAttribs, (int)pkcs7->signedAttribsSz); } #ifdef NO_ASN_TIME @@ -2268,12 +2285,12 @@ static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, word32 flatSignedAttribsSz, ESD* esd, byte* digestInfo, word32* digestInfoSz) { - int ret, hashSz, digIdx = 0; + int ret, digIdx = 0; byte digestInfoSeq[MAX_SEQ_SZ]; byte digestStr[MAX_OCTET_STR_SZ]; byte attribSet[MAX_SET_SZ]; byte algoId[MAX_ALGO_SZ]; - word32 digestInfoSeqSz, digestStrSz, algoIdSz; + word32 digestInfoSeqSz, digestStrSz, algoIdSz, dgstInfoSz, hashSz; word32 attribSetSz; if (pkcs7 == NULL || esd == NULL || digestInfo == NULL || @@ -2281,9 +2298,10 @@ static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, return BAD_FUNC_ARG; } - hashSz = wc_HashGetDigestSize(esd->hashType); - if (hashSz < 0) - return hashSz; + ret = wc_HashGetDigestSize(esd->hashType); + if (ret < 0) + return ret; + hashSz = (word32)ret; if (flatSignedAttribsSz != 0) { @@ -2314,25 +2332,26 @@ static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, XMEMCPY(esd->contentAttribsDigest, esd->contentDigest + 2, hashSz); } - /* set algoID, with NULL attributes */ - algoIdSz = SetAlgoID(pkcs7->hashOID, algoId, oidHashType, 0); + /* Set algoID, allow absent hash params */ + algoIdSz = SetAlgoIDEx(pkcs7->hashOID, algoId, oidHashType, + 0, pkcs7->hashParamsAbsent); digestStrSz = SetOctetString(hashSz, digestStr); - digestInfoSeqSz = SetSequence(algoIdSz + digestStrSz + hashSz, - digestInfoSeq); + dgstInfoSz = algoIdSz + digestStrSz + hashSz; + digestInfoSeqSz = SetSequence(dgstInfoSz, digestInfoSeq); - if (*digestInfoSz < (digestInfoSeqSz + algoIdSz + digestStrSz + hashSz)) { + if (*digestInfoSz < (digestInfoSeqSz + dgstInfoSz)) { return BUFFER_E; } XMEMCPY(digestInfo + digIdx, digestInfoSeq, digestInfoSeqSz); - digIdx += digestInfoSeqSz; + digIdx += (int)digestInfoSeqSz; XMEMCPY(digestInfo + digIdx, algoId, algoIdSz); - digIdx += algoIdSz; + digIdx += (int)algoIdSz; XMEMCPY(digestInfo + digIdx, digestStr, digestStrSz); - digIdx += digestStrSz; + digIdx += (int)digestStrSz; XMEMCPY(digestInfo + digIdx, esd->contentAttribsDigest, hashSz); - digIdx += hashSz; + digIdx += (int)hashSz; *digestInfoSz = (word32)digIdx; @@ -2478,7 +2497,7 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, switch (cipherType) { case WC_CIPHER_NONE: - XMEMCPY(encContentOut, contentData, contentDataSz); + XMEMCPY(encContentOut, contentData, (word32)contentDataSz); if (esd && esd->contentDigestSet != 1) { ret = wc_HashUpdate(&esd->hash, esd->hashType, contentData, (word32)contentDataSz); @@ -2515,7 +2534,7 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, *outIdx += encContentOutOctSz; wc_PKCS7_WriteOut(pkcs7, (out)? out + *outIdx : NULL, encContentOut, (word32)contentDataSz); - *outIdx += contentDataSz; + *outIdx += (word32)contentDataSz; } return ret; @@ -2552,10 +2571,10 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, byte* encContentOut; byte* contentData; word32 idx = 0, outIdx = 0; - int padSz = 0; + word32 padSz = 0; if (cipherType != WC_CIPHER_NONE) { - padSz = wc_PKCS7_GetPadSize(pkcs7->contentSz, + padSz = (word32)wc_PKCS7_GetPadSize(pkcs7->contentSz, (word32)wc_PKCS7_GetOIDBlockSize(pkcs7->encryptOID)); } @@ -2607,8 +2626,8 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, return BAD_FUNC_ARG; } - if (szLeft + totalSz > (word32)inSz) - szLeft = inSz - totalSz; + if ((word32)szLeft + totalSz > (word32)inSz) + szLeft = inSz - (int)totalSz; contentDataRead = szLeft; buf = in + totalSz; @@ -2622,11 +2641,11 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, /* check and handle octet boundary */ sz = contentDataRead; - if (idx + sz > BER_OCTET_LENGTH) { - sz = BER_OCTET_LENGTH - idx; + if ((int)idx + sz > BER_OCTET_LENGTH) { + sz = BER_OCTET_LENGTH - (int)idx; contentDataRead -= sz; - XMEMCPY(contentData + idx, buf, sz); + XMEMCPY(contentData + idx, buf, (word32)sz); ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, aes, encContentOut, contentData, BER_OCTET_LENGTH, out, &outIdx, esd); @@ -2637,20 +2656,20 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, } /* copy over any remaining data */ - XMEMCPY(contentData, buf + sz, contentDataRead); + XMEMCPY(contentData, buf + sz, (word32)contentDataRead); idx = (word32)contentDataRead; } else { /* was not on an octet boundary, copy full * amount over */ - XMEMCPY(contentData + idx, buf, sz); - idx += sz; + XMEMCPY(contentData + idx, buf, (word32)sz); + idx += (word32)sz; } } while (totalSz < pkcs7->contentSz); /* add in padding to the end */ if ((cipherType != WC_CIPHER_NONE) && (totalSz == pkcs7->contentSz)) { - int i; + word32 i; if (BER_OCTET_LENGTH < idx) { XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); @@ -2661,7 +2680,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, for (i = 0; i < padSz; i++) { contentData[idx + i] = (byte)padSz; } - idx += padSz; + idx += (word32)padSz; } /* encrypt and flush out remainder of content data */ @@ -2687,7 +2706,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, switch (cipherType) { case WC_CIPHER_NONE: if (!pkcs7->detached) { - XMEMCPY(out, in, inSz); + XMEMCPY(out, in, (word32)inSz); } if (esd && esd->contentDigestSet != 1) { ret = wc_HashInit(&esd->hash, esd->hashType); @@ -2803,6 +2822,15 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, keyIdSize = KEYID_SIZE; #endif + /* use custom SKID if set */ + if (pkcs7->customSKIDSz > 0) { + if (pkcs7->customSKID == NULL) { + WOLFSSL_MSG("Bad custom SKID setup, size > 0 and was NULL"); + return BAD_FUNC_ARG; + } + keyIdSize = pkcs7->customSKIDSz; + } + #ifdef WOLFSSL_SMALL_STACK signedDataOid = (byte *)XMALLOC(MAX_OID_SZ, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (signedDataOid == NULL) { @@ -2909,9 +2937,11 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, } else if (pkcs7->sidType == CMS_SKID) { /* SubjectKeyIdentifier */ esd->issuerSKIDSz = SetOctetString((word32)keyIdSize, esd->issuerSKID); - esd->issuerSKIDSeqSz = SetExplicit(0, esd->issuerSKIDSz + keyIdSize, + esd->issuerSKIDSeqSz = SetExplicit(0, esd->issuerSKIDSz + + (word32)keyIdSize, esd->issuerSKIDSeq, 0); - signerInfoSz += (esd->issuerSKIDSz + esd->issuerSKIDSeqSz + keyIdSize); + signerInfoSz += (esd->issuerSKIDSz + esd->issuerSKIDSeqSz + + (word32)keyIdSize); /* version MUST be 3 */ esd->signerVersionSz = (word32)SetMyVersion(3, esd->signerVersion, 0); @@ -2924,8 +2954,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, if (pkcs7->sidType != DEGENERATE_SID) { signerInfoSz += esd->signerVersionSz; - esd->signerDigAlgoIdSz = SetAlgoID(pkcs7->hashOID, esd->signerDigAlgoId, - oidHashType, 0); + esd->signerDigAlgoIdSz = SetAlgoIDEx(pkcs7->hashOID, esd->signerDigAlgoId, + oidHashType, 0, pkcs7->hashParamsAbsent); signerInfoSz += esd->signerDigAlgoIdSz; /* set signatureAlgorithm */ @@ -2935,8 +2965,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, idx = ret; goto out; } - esd->digEncAlgoIdSz = SetAlgoID(digEncAlgoId, esd->digEncAlgoId, - digEncAlgoType, 0); + esd->digEncAlgoIdSz = SetAlgoIDEx(digEncAlgoId, esd->digEncAlgoId, + digEncAlgoType, 0, pkcs7->hashParamsAbsent); signerInfoSz += esd->digEncAlgoIdSz; /* build up signed attributes, include contentType, signingTime, and @@ -2962,8 +2992,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, flatSignedAttribsSz = esd->signedAttribsSz; - FlattenAttributes(pkcs7, flatSignedAttribs, - esd->signedAttribs, esd->signedAttribsCount); + FlattenAttributes(pkcs7, flatSignedAttribs, esd->signedAttribs, + (int)esd->signedAttribsCount); esd->signedAttribSetSz = SetImplicit(ASN_SET, 0, esd->signedAttribsSz, esd->signedAttribSet, 0); } else { @@ -3010,8 +3040,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, esd->certsSetSz = SetImplicit(ASN_SET, 0, certSetSz, esd->certsSet, 0); if (pkcs7->sidType != DEGENERATE_SID) { - esd->singleDigAlgoIdSz = SetAlgoID(pkcs7->hashOID, esd->singleDigAlgoId, - oidHashType, 0); + esd->singleDigAlgoIdSz = SetAlgoIDEx(pkcs7->hashOID, esd->singleDigAlgoId, + oidHashType, 0, pkcs7->hashParamsAbsent); } esd->digAlgoIdSetSz = SetSet(esd->singleDigAlgoIdSz, esd->digAlgoIdSet); @@ -3121,37 +3151,37 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, idx = 0; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->outerSeq, esd->outerSeqSz); - idx += esd->outerSeqSz; + idx += (int)esd->outerSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, signedDataOid, signedDataOidSz); - idx += signedDataOidSz; + idx += (int)signedDataOidSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->outerContent, esd->outerContentSz); - idx += esd->outerContentSz; + idx += (int)esd->outerContentSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->innerSeq, esd->innerSeqSz); - idx += esd->innerSeqSz; + idx += (int)esd->innerSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->version, esd->versionSz); - idx += esd->versionSz; + idx += (int)esd->versionSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->digAlgoIdSet, esd->digAlgoIdSetSz); - idx += esd->digAlgoIdSetSz; + idx += (int)esd->digAlgoIdSetSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->singleDigAlgoId, esd->singleDigAlgoIdSz); - idx += esd->singleDigAlgoIdSz; + idx += (int)esd->singleDigAlgoIdSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->contentInfoSeq, esd->contentInfoSeqSz); - idx += esd->contentInfoSeqSz; + idx += (int)esd->contentInfoSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, pkcs7->contentType, pkcs7->contentTypeSz); - idx += pkcs7->contentTypeSz; + idx += (int)pkcs7->contentTypeSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->innerContSeq, esd->innerContSeqSz); - idx += esd->innerContSeqSz; + idx += (int)esd->innerContSeqSz; wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, esd->innerOctets, esd->innerOctetsSz); - idx += esd->innerOctetsSz; + idx += (int)esd->innerOctetsSz; /* support returning header and footer without content */ if (output2 && output2Sz) { @@ -3167,14 +3197,15 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, #endif && pkcs7->contentSz > 0) { wc_PKCS7_EncodeContentStream(pkcs7, esd, NULL, pkcs7->content, - pkcs7->contentSz, (output)? output + idx : NULL, WC_CIPHER_NONE); + (int)pkcs7->contentSz, (output)? output + idx : NULL, + WC_CIPHER_NONE); if (!pkcs7->detached) { #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { byte indefEnd[ASN_INDEF_END_SZ * 3]; word32 localIdx = 0; - idx += streamSz; + idx += (int)streamSz; /* end of content octet string */ localIdx += SetIndefEnd(indefEnd + localIdx); @@ -3187,12 +3218,12 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, indefEnd, localIdx); - idx += localIdx; + idx += (int)localIdx; } else #endif { - idx += pkcs7->contentSz; + idx += (int)pkcs7->contentSz; } } } @@ -3202,14 +3233,14 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, /* certificates */ wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->certsSet, esd->certsSetSz); - idx += esd->certsSetSz; + idx += (int)esd->certsSetSz; if (pkcs7->noCerts != 1) { certPtr = pkcs7->certList; while (certPtr != NULL) { wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, certPtr->der, certPtr->derSz); - idx += certPtr->derSz; + idx += (int)certPtr->derSz; certPtr = certPtr->next; } } @@ -3218,38 +3249,45 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signerInfoSet, esd->signerInfoSetSz); - idx += esd->signerInfoSetSz; + idx += (int)esd->signerInfoSetSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signerInfoSeq, esd->signerInfoSeqSz); - idx += esd->signerInfoSeqSz; + idx += (int)esd->signerInfoSeqSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signerVersion, esd->signerVersionSz); - idx += esd->signerVersionSz; + idx += (int)esd->signerVersionSz; /* SignerIdentifier */ if (pkcs7->sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { /* IssuerAndSerialNumber */ wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->issuerSnSeq, esd->issuerSnSeqSz); - idx += esd->issuerSnSeqSz; + idx += (int)esd->issuerSnSeqSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->issuerName, esd->issuerNameSz); - idx += esd->issuerNameSz; + idx += (int)esd->issuerNameSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, pkcs7->issuer, pkcs7->issuerSz); - idx += pkcs7->issuerSz; + idx += (int)pkcs7->issuerSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->issuerSn, esd->issuerSnSz); - idx += esd->issuerSnSz; + idx += (int)esd->issuerSnSz; } else if (pkcs7->sidType == CMS_SKID) { /* SubjectKeyIdentifier */ wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->issuerSKIDSeq, esd->issuerSKIDSeqSz); - idx += esd->issuerSKIDSeqSz; + idx += (int)esd->issuerSKIDSeqSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->issuerSKID, esd->issuerSKIDSz); - idx += esd->issuerSKIDSz; - wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + idx += (int)esd->issuerSKIDSz; + + if (pkcs7->customSKID) { + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, + pkcs7->customSKID, (word32)keyIdSize); + } + else { + wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, pkcs7->issuerSubjKeyId, (word32)keyIdSize); + } idx += keyIdSize; } else if (pkcs7->sidType == DEGENERATE_SID) { /* no signer infos in degenerate case */ @@ -3259,7 +3297,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, } wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signerDigAlgoId, esd->signerDigAlgoIdSz); - idx += esd->signerDigAlgoIdSz; + idx += (int)esd->signerDigAlgoIdSz; /* SignerInfo:Attributes */ if (flatSignedAttribsSz > 0) { @@ -3290,7 +3328,8 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, flatSignedAttribsSz = esd->signedAttribsSz; FlattenAttributes(pkcs7, flatSignedAttribs, - esd->signedAttribs, esd->signedAttribsCount); + esd->signedAttribs, + (int)esd->signedAttribsCount); } else { esd->signedAttribSetSz = 0; } @@ -3298,10 +3337,10 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signedAttribSet, esd->signedAttribSetSz); - idx += esd->signedAttribSetSz; + idx += (int)esd->signedAttribSetSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, flatSignedAttribs, flatSignedAttribsSz); - idx += flatSignedAttribsSz; + idx += (int)flatSignedAttribsSz; } if (hashBuf == NULL && pkcs7->sidType != DEGENERATE_SID) { @@ -3317,14 +3356,14 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->digEncAlgoId, esd->digEncAlgoIdSz); - idx += esd->digEncAlgoIdSz; + idx += (int)esd->digEncAlgoIdSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->signerDigest, esd->signerDigestSz); - idx += esd->signerDigestSz; + idx += (int)esd->signerDigestSz; wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, esd->encContentDigest, esd->encContentDigestSz); - idx += esd->encContentDigestSz; + idx += (int)esd->encContentDigestSz; #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { @@ -3342,7 +3381,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, wc_PKCS7_WriteOut(pkcs7, (output2)? (output2 + idx) : NULL, indefEnd, localIdx); - idx += localIdx; + idx += (int)localIdx; } #endif @@ -3356,14 +3395,11 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, out: - if (flatSignedAttribs != NULL) - XFREE(flatSignedAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatSignedAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); #ifdef WOLFSSL_SMALL_STACK - if (esd) - XFREE(esd, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (signedDataOid) - XFREE(signedDataOid, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(esd, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(signedDataOid, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif return idx; @@ -3404,6 +3440,40 @@ int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, return ret; } + +/* Sets a custom SKID in PKCS7 struct, used before calling an encode operation + * Returns 0 on success, negative upon error. */ +int wc_PKCS7_SetCustomSKID(PKCS7* pkcs7, const byte* in, word16 inSz) +{ + int ret = 0; + + if (pkcs7 == NULL || (in == NULL && inSz > 0)) { + return BAD_FUNC_ARG; + } + + if (in == NULL) { + if (pkcs7->customSKID != NULL) { + XFREE(pkcs7->customSKID, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + } + pkcs7->customSKIDSz = 0; + pkcs7->customSKID = NULL; + } + else { + pkcs7->customSKID = (byte*)XMALLOC(inSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (pkcs7->customSKID == NULL) { + ret = MEMORY_E; + } + else { + XMEMCPY(pkcs7->customSKID, in, inSz); + pkcs7->customSKIDSz = inSz; + } + } + + return ret; +} + + /* Toggle detached signature mode on/off for PKCS#7/CMS SignedData content type. * By default wolfCrypt includes the data to be signed in the SignedData * bundle. This data can be omitted in the case when a detached signature is @@ -3422,7 +3492,7 @@ int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag) if (pkcs7 == NULL || (flag != 0 && flag != 1)) return BAD_FUNC_ARG; - pkcs7->detached = flag; + pkcs7->detached = (flag != 0); return 0; } @@ -3664,13 +3734,14 @@ int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, } /* save encryptedData, reset output buffer and struct */ - encrypted = (byte*)XMALLOC(encryptedSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encrypted = (byte*)XMALLOC((word32)encryptedSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (encrypted == NULL) { ForceZero(output, outputSz); return MEMORY_E; } - XMEMCPY(encrypted, output, encryptedSz); + XMEMCPY(encrypted, output, (word32)encryptedSz); ForceZero(output, outputSz); ret = wc_InitRng_ex(&rng, pkcs7->heap, pkcs7->devId); @@ -3969,8 +4040,14 @@ static int wc_PKCS7_RsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, byte* digest; RsaKey* key; DecodedCert* dCert; +#else +#ifdef WOLFSSL_NO_MALLOC + byte digest[RSA_MAX_SIZE / WOLFSSL_BIT_SIZE]; /* accessed in-place with size + * key->dataLen + */ #else byte digest[MAX_PKCS7_DIGEST_SZ]; +#endif RsaKey key[1]; DecodedCert stack_dCert; DecodedCert* dCert = &stack_dCert; @@ -4181,14 +4258,18 @@ static int wc_PKCS7_EcdsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); #endif - FreeDecodedCert(dCert); - wc_ecc_free(key); - if (ret == 0 && res == 1) { /* found signer that successfully verified signature */ verified = 1; + XMEMCPY(pkcs7->issuerSubjKeyId, dCert->extSubjKeyId, KEYID_SIZE); pkcs7->verifyCert = pkcs7->cert[i]; pkcs7->verifyCertSz = pkcs7->certSz[i]; + } + + wc_ecc_free(key); + FreeDecodedCert(dCert); + + if (ret == 0 && res == 1) { break; } } @@ -4318,23 +4399,24 @@ static int wc_PKCS7_BuildSignedDataDigest(PKCS7* pkcs7, byte* signedAttrib, } } - /* Set algoID, with NULL attributes */ - algoIdSz = SetAlgoID(pkcs7->hashOID, algoId, oidHashType, 0); + /* Set algoID, match whatever was input to match either NULL or absent */ + algoIdSz = SetAlgoIDEx(pkcs7->hashOID, algoId, oidHashType, + 0, pkcs7->hashParamsAbsent); digestStrSz = SetOctetString(hashSz, digestStr); digestInfoSeqSz = SetSequence(algoIdSz + digestStrSz + hashSz, digestInfoSeq); XMEMCPY(digestInfo + digIdx, digestInfoSeq, digestInfoSeqSz); - digIdx += digestInfoSeqSz; + digIdx += (int)digestInfoSeqSz; XMEMCPY(digestInfo + digIdx, algoId, algoIdSz); - digIdx += algoIdSz; + digIdx += (int)algoIdSz; XMEMCPY(digestInfo + digIdx, digestStr, digestStrSz); - digIdx += digestStrSz; + digIdx += (int)digestStrSz; XMEMCPY(digestInfo + digIdx, digest, hashSz); - digIdx += hashSz; + digIdx += (int)hashSz; - XMEMCPY(pkcs7Digest, digestInfo, digIdx); + XMEMCPY(pkcs7Digest, digestInfo, (word32)digIdx); *pkcs7DigestSz = (word32)digIdx; /* set plain digest pointer */ @@ -4728,7 +4810,7 @@ static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) return ASN_SIG_KEY_E; } - return pkcs7->publicKeyOID; + return (int)pkcs7->publicKeyOID; } @@ -4760,7 +4842,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) while (idx < (word32)inSz) { int length = 0; - int oidIdx; + word32 oidIdx; PKCS7DecodedAttrib* attrib; if (GetSequence(in, &idx, &length, (word32)inSz) < 0) @@ -4773,7 +4855,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) } XMEMSET(attrib, 0, sizeof(PKCS7DecodedAttrib)); - oidIdx = (int)idx; + oidIdx = idx; if (GetObjectId(in, &idx, &oid, oidIgnoreType, (word32)inSz) < 0) { XFREE(attrib, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -4795,7 +4877,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) return ASN_PARSE_E; } - if ((inSz - idx) < (word32)length) { + if ((inSz - (int)idx) < length) { XFREE(attrib->oid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(attrib, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ASN_PARSE_E; @@ -4810,7 +4892,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) return MEMORY_E; } XMEMCPY(attrib->value, in + idx, attrib->valueSz); - idx += length; + idx += (word32)length; /* store attribute in linked list */ if (pkcs7->decodedAttrib != NULL) { @@ -4863,6 +4945,7 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, word32 sigOID = 0, hashOID = 0; word32 idx = *idxIn, localIdx; byte tag; + byte absentParams = FALSE; WOLFSSL_ENTER("wc_PKCS7_ParseSignerInfo"); /* require a signer if degenerate case not allowed */ @@ -4899,7 +4982,7 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, if (ret == 0) { ret = wc_PKCS7_SignerInfoSetSID(pkcs7, in + idx, length); - idx += length; + idx += (word32)length; } } else if (ret == 0 && version == 3) { @@ -4955,7 +5038,7 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, if (ret == 0) { ret = wc_PKCS7_SignerInfoSetSID(pkcs7, in + idx, length); - idx += length; + idx += (word32)length; } } else { @@ -4964,10 +5047,12 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, } /* Get the sequence of digestAlgorithm */ - if (ret == 0 && GetAlgoId(in, &idx, &hashOID, oidHashType, inSz) < 0) { + if (ret == 0 && GetAlgoIdEx(in, &idx, &hashOID, oidHashType, + inSz, &absentParams) < 0) { ret = ASN_PARSE_E; } pkcs7->hashOID = (int)hashOID; + pkcs7->hashParamsAbsent = (absentParams != 0); /* Get the IMPLICIT[0] SET OF signedAttributes */ localIdx = idx; @@ -4988,7 +5073,7 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, ret = ASN_PARSE_E; } - idx += length; + idx += (word32)length; } /* Get digestEncryptionAlgorithm - key type or signature type */ @@ -5045,10 +5130,8 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, /* no content case, do nothing */ if (pkcs7->stream->noContent) { if (pkcs7->content && pkcs7->contentSz > 0) { - if (pkcs7->stream->content != NULL) { - XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->stream->content = NULL; - } + XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->stream->content = NULL; pkcs7->stream->content = (byte*)XMALLOC(pkcs7->contentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -5063,10 +5146,8 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, } /* free pkcs7->contentDynamic buffer */ - if (pkcs7->contentDynamic != NULL) { - XFREE(pkcs7->contentDynamic, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->contentDynamic = NULL; - } + XFREE(pkcs7->contentDynamic, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->contentDynamic = NULL; while(1) { if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, @@ -5121,7 +5202,7 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, * number of indef is stored in pkcs7->stream->cntIdfCnt. */ pkcs7->stream->expected = (word32)(ASN_TAG_SZ + TRAILING_ZERO) * - pkcs7->stream->cntIdfCnt; + (word32)pkcs7->stream->cntIdfCnt; /* dec idx by one since already consumed to get ASN_EOC */ (*idx)--; @@ -5201,10 +5282,8 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, if (pkcs7->stream->content == NULL) { WOLFSSL_MSG("failed to grow content buffer."); - if (tempBuf != NULL) { - XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - tempBuf = NULL; - } + XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + tempBuf = NULL; ret = MEMORY_E; break; } @@ -5215,10 +5294,8 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, } XMEMCPY(pkcs7->stream->content + contBufSz, msg + *idx, pkcs7->stream->expected); - if (tempBuf != NULL) { - XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - tempBuf = NULL; - } + XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + tempBuf = NULL; } } @@ -5337,9 +5414,11 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, switch (pkcs7->state) { case WC_PKCS7_START: #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, MAX_SEQ_SZ + + /* The expected size calculation originally assumed digest OID + * with NULL params, -2 to also accept with absent params */ + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, (MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_SEQ_SZ + MAX_LENGTH_SZ + - ASN_TAG_SZ + MAX_OID_SZ + MAX_SEQ_SZ, + ASN_TAG_SZ + MAX_OID_SZ + MAX_SEQ_SZ) - 2, &pkiMsg, &idx)) != 0) { break; } @@ -5353,7 +5432,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, break; } if (ret == 0 && length > 0) - pkcs7->stream->maxLen = length + localIdx; + pkcs7->stream->maxLen = (word32)length + localIdx; else pkcs7->stream->maxLen = inSz; @@ -5495,7 +5574,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = ASN_PARSE_E; } /* store hashType for later hashing */ - pkcs7->stream->hashType = hashType; + pkcs7->stream->hashType = (int)hashType; /* restore idx */ idx = localIdx; @@ -5505,12 +5584,12 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, #endif /* !NO_PKCS7_STREAM */ /* Skip the set. */ - idx += length; + idx += (word32)length; degenerate = (length == 0) ? 1 : 0; #ifndef NO_PKCS7_STREAM - pkcs7->stream->degenerate = degenerate; + pkcs7->stream->degenerate = (degenerate != 0); #endif /* !NO_PKCS7_STREAM */ - if (pkcs7->noDegenerate == 1 && degenerate == 1) { + if (pkcs7->noDegenerate == 1 && degenerate != 0) { ret = PKCS7_NO_SIGNER_E; } @@ -5574,8 +5653,8 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } if (GetASNObjectId(pkiMsg, &idx, &length, pkiMsgSz) == 0) { contentType = pkiMsg + tmpIdx; - contentTypeSz = length + (idx - tmpIdx); - idx += length; + contentTypeSz = (word32)length + (idx - tmpIdx); + idx += (word32)length; } else { ret = ASN_PARSE_E; @@ -5608,7 +5687,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* Set error state if no more data left in ContentInfo, meaning * no content - may be detached. Will recover from error below */ if ((encapContentInfoLen != 0) && - (encapContentInfoLen - contentTypeSz == 0)) { + ((word32)encapContentInfoLen - contentTypeSz == 0)) { ret = ASN_PARSE_E; #ifndef NO_PKCS7_STREAM pkcs7->stream->noContent = 1; @@ -5708,11 +5787,12 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, if (ret == 0) { /* Use single OCTET_STRING directly, or reset length. */ - if (localIdx - start + length == (word32)contentLen) { + if (localIdx - start + (word32)length == + (word32)contentLen) { multiPart = 0; } else { #ifndef NO_PKCS7_STREAM - pkcs7->stream->multi = multiPart; + pkcs7->stream->multi = (multiPart != 0); pkcs7->stream->currContIdx = localIdx; pkcs7->stream->currContSz = (word32)length; pkcs7->stream->currContRmnSz = (word32)length; @@ -5740,7 +5820,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = ASN_PARSE_E; #ifndef NO_PKCS7_STREAM if (ret == 0) { - pkcs7->stream->multi = multiPart; + pkcs7->stream->multi = (multiPart != 0); pkcs7->stream->currContIdx = localIdx; pkcs7->stream->currContSz = (word32)length; pkcs7->stream->currContRmnSz = (word32)length; @@ -5792,7 +5872,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, #ifndef NO_PKCS7_STREAM /* save detached flag value */ - pkcs7->stream->detached = detached; + pkcs7->stream->detached = (detached != 0); /* save contentType */ pkcs7->stream->nonce = (byte*)XMALLOC(contentTypeSz, pkcs7->heap, @@ -5836,10 +5916,8 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, #ifndef NO_PKCS7_STREAM /* free pkcs7->stream->content buffer */ - if (pkcs7->stream->content != NULL) { - XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->stream->content = NULL; - } + XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->stream->content = NULL; #endif /* !NO_PKCS7_STREAM */ FALL_THROUGH; @@ -6059,7 +6137,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, WOLFSSL_MSG("certificate set found"); /* adjust cert length */ - length += localIdx - certIdx; + length += (int)(localIdx - certIdx); idx = certIdx; } } @@ -6137,13 +6215,13 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, if (length > 0 && in2Sz == 0) { /* free tmpCert if not NULL */ XFREE(pkcs7->stream->tmpCert, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - pkcs7->stream->tmpCert = (byte*)XMALLOC(length, + pkcs7->stream->tmpCert = (byte*)XMALLOC((word32)length, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if ((pkiMsg2 == NULL) || (pkcs7->stream->tmpCert == NULL)) { ret = MEMORY_E; break; } - XMEMCPY(pkcs7->stream->tmpCert, pkiMsg2 + idx, length); + XMEMCPY(pkcs7->stream->tmpCert, pkiMsg2 + idx, (word32)length); pkiMsg2 = pkcs7->stream->tmpCert; pkiMsg2Sz = (word32)length; idx = 0; @@ -6174,7 +6252,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = ASN_PARSE_E; cert = &pkiMsg2[idx]; - certSz += (certIdx - idx); + certSz += (int)(certIdx - idx); if (certSz > length) { ret = BUFFER_E; break; @@ -6196,7 +6274,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* Save dynamic content before freeing PKCS7 struct */ if (pkcs7->contentDynamic != NULL) { - contentDynamic = (byte*)XMALLOC(contentSz, + contentDynamic = (byte*)XMALLOC((word32)contentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (contentDynamic == NULL) { #ifndef NO_PKCS7_STREAM @@ -6206,13 +6284,13 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, break; } XMEMCPY(contentDynamic, pkcs7->contentDynamic, - contentSz); + (word32)contentSz); } /* Free pkcs7 resources but not the structure itself */ pkcs7->isDynamic = 0; wc_PKCS7_Free(pkcs7); - pkcs7->isDynamic = isDynamic; + pkcs7->isDynamic = (isDynamic != 0); /* This will reset PKCS7 structure and then set the * certificate */ ret = wc_PKCS7_InitWithCert(pkcs7, cert, (word32)certSz); @@ -6225,7 +6303,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } /* Restore content is PKCS#7 flag */ - pkcs7->contentIsPkcs7Type = contentIsPkcs7Type; + pkcs7->contentIsPkcs7Type = (contentIsPkcs7Type != 0); #ifndef NO_PKCS7_STREAM pkcs7->stream = stream; @@ -6245,7 +6323,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, pkcs7->cert[0] = cert; pkcs7->certSz[0] = (word32)certSz; - certIdx = idx + certSz; + certIdx = idx + (word32)certSz; for (i = 1; i < MAX_PKCS7_CERTS && certIdx + 1 < pkiMsg2Sz && @@ -6267,21 +6345,22 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } pkcs7->cert[i] = &pkiMsg2[localIdx]; - pkcs7->certSz[i] = sz + (certIdx - localIdx); - certIdx += sz; + pkcs7->certSz[i] = (word32)sz + + (certIdx - localIdx); + certIdx += (word32)sz; } } } } - idx += length; + idx += (word32)length; if (!detached) { /* set content and size after init of PKCS7 structure */ pkcs7->content = content; - pkcs7->contentSz = contentSz; + pkcs7->contentSz = (word32)contentSz; } - idx = certIdx2 + length; + idx = certIdx2 + (word32)length; if (ret != 0) { break; @@ -6307,7 +6386,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* if certificate set has indef-length, there maybe trailing zeros. * add expected size to include size of zeros. */ if (pkcs7->stream->cntIdfCnt > 0) { - pkcs7->stream->expected += pkcs7->stream->cntIdfCnt * 2; + pkcs7->stream->expected += (word32)pkcs7->stream->cntIdfCnt * 2; } if (pkcs7->stream->expected > (pkcs7->stream->maxLen - @@ -6367,10 +6446,10 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* prior to find set of crls, remove trailing zeros of * set of certificates */ if (ret == 0 && pkcs7->stream->cntIdfCnt > 0) { - int i; + word32 i; + word32 sz = (word32)pkcs7->stream->cntIdfCnt * ASN_INDEF_END_SZ; localIdx = idx; - for (i = 0; i < pkcs7->stream->cntIdfCnt * ASN_INDEF_END_SZ; - i++) { + for (i = 0; i < sz; i++) { if (pkiMsg2[localIdx + i] == 0) continue; else { @@ -6379,7 +6458,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, } } if (ret == 0) { - idx += pkcs7->stream->cntIdfCnt * ASN_INDEF_END_SZ; + idx += (word32)pkcs7->stream->cntIdfCnt * ASN_INDEF_END_SZ; pkcs7->stream->cntIdfCnt = 0; } } @@ -6396,7 +6475,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, ret = ASN_PARSE_E; /* Skip the set */ - idx += length; + idx += (word32)length; } /* Get the set of signerInfos */ @@ -6491,7 +6570,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, sig = &pkiMsg2[idx]; sigSz = length; - idx += length; + idx += (word32)length; } pkcs7->content = content; @@ -6508,7 +6587,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, /* make sure that terminating zero's follow */ if ((ret == WC_NO_ERR_TRACE(PKCS7_SIGNEEDS_CHECK) || ret >= 0) && pkcs7->stream->indefLen == 1) { - int i; + word32 i; for (i = 0; i < 3 * ASN_INDEF_END_SZ; i++) { if (pkiMsg2[idx + i] != 0) { ret = ASN_PARSE_E; @@ -6570,7 +6649,7 @@ int wc_PKCS7_GetSignerSID(PKCS7* pkcs7, byte* out, word32* outSz) if (out == NULL) { *outSz = pkcs7->signerInfo->sidSz; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if (*outSz < pkcs7->signerInfo->sidSz) { @@ -6750,9 +6829,9 @@ typedef struct WC_PKCS7_KARI { word32 sharedInfoSz; /* size of ECC-CMS-SharedInfo encoded */ byte ukmOwner; /* do we own ukm buffer? 1:yes, 0:no */ byte direction; /* WC_PKCS7_ENCODE | WC_PKCS7_DECODE */ - byte decodedInit : 1; /* indicates decoded was initialized */ - byte recipKeyInit : 1; /* indicates recipKey was initialized */ - byte senderKeyInit : 1; /* indicates senderKey was initialized */ + WC_BITFIELD decodedInit:1; /* indicates decoded was initialized */ + WC_BITFIELD recipKeyInit:1; /* indicates recipKey was initialized */ + WC_BITFIELD senderKeyInit:1; /* indicates senderKey was initialized */ } WC_PKCS7_KARI; @@ -7044,22 +7123,22 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) /* kekOctet */ kekOctetSz = (int)SetOctetString(sizeof(word32), kekOctet); - sharedInfoSz += (kekOctetSz + sizeof(word32)); + sharedInfoSz += (kekOctetSz + (int)sizeof(word32)); /* suppPubInfo */ - suppPubInfoSeqSz = SetImplicit(ASN_SEQUENCE, 2, - kekOctetSz + sizeof(word32), - suppPubInfoSeq, 0); + suppPubInfoSeqSz = (int)SetImplicit(ASN_SEQUENCE, 2, + (word32)kekOctetSz + sizeof(word32), + suppPubInfoSeq, 0); sharedInfoSz += suppPubInfoSeqSz; /* optional ukm/entityInfo */ if (kari->ukmSz > 0) { entityUInfoOctetSz = (int)SetOctetString(kari->ukmSz, entityUInfoOctet); - sharedInfoSz += (entityUInfoOctetSz + kari->ukmSz); + sharedInfoSz += (entityUInfoOctetSz + (int)kari->ukmSz); - entityUInfoExplicitSz = SetExplicit(0, entityUInfoOctetSz + - kari->ukmSz, - entityUInfoExplicitSeq, 0); + entityUInfoExplicitSz = (int)SetExplicit(0, + (word32)entityUInfoOctetSz + kari->ukmSz, + entityUInfoExplicitSeq, 0); sharedInfoSz += entityUInfoExplicitSz; } @@ -7071,29 +7150,30 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) sharedInfoSeqSz = (int)SetSequence((word32)sharedInfoSz, sharedInfoSeq); sharedInfoSz += sharedInfoSeqSz; - kari->sharedInfo = (byte*)XMALLOC(sharedInfoSz, kari->heap, + kari->sharedInfo = (byte*)XMALLOC((word32)sharedInfoSz, kari->heap, DYNAMIC_TYPE_PKCS7); if (kari->sharedInfo == NULL) return MEMORY_E; kari->sharedInfoSz = (word32)sharedInfoSz; - XMEMCPY(kari->sharedInfo + idx, sharedInfoSeq, sharedInfoSeqSz); + XMEMCPY(kari->sharedInfo + idx, sharedInfoSeq, (word32)sharedInfoSeqSz); idx += sharedInfoSeqSz; - XMEMCPY(kari->sharedInfo + idx, keyInfo, keyInfoSz); + XMEMCPY(kari->sharedInfo + idx, keyInfo, (word32)keyInfoSz); idx += keyInfoSz; if (kari->ukmSz > 0) { XMEMCPY(kari->sharedInfo + idx, entityUInfoExplicitSeq, - entityUInfoExplicitSz); + (word32)entityUInfoExplicitSz); idx += entityUInfoExplicitSz; - XMEMCPY(kari->sharedInfo + idx, entityUInfoOctet, entityUInfoOctetSz); + XMEMCPY(kari->sharedInfo + idx, entityUInfoOctet, + (word32)entityUInfoOctetSz); idx += entityUInfoOctetSz; XMEMCPY(kari->sharedInfo + idx, kari->ukm, kari->ukmSz); - idx += kari->ukmSz; + idx += (int)kari->ukmSz; } - XMEMCPY(kari->sharedInfo + idx, suppPubInfoSeq, suppPubInfoSeqSz); + XMEMCPY(kari->sharedInfo + idx, suppPubInfoSeq, (word32)suppPubInfoSeqSz); idx += suppPubInfoSeqSz; - XMEMCPY(kari->sharedInfo + idx, kekOctet, kekOctetSz); + XMEMCPY(kari->sharedInfo + idx, kekOctet, (word32)kekOctetSz); idx += kekOctetSz; kekBitSz = (kari->kekSz) * 8; /* convert to bits */ @@ -7126,7 +7206,7 @@ static int wc_PKCS7_KariGenerateKEK(WC_PKCS7_KARI* kari, WC_RNG* rng, if (kSz < 0) return kSz; - kari->kek = (byte*)XMALLOC(kSz, kari->heap, DYNAMIC_TYPE_PKCS7); + kari->kek = (byte*)XMALLOC((word32)kSz, kari->heap, DYNAMIC_TYPE_PKCS7); if (kari->kek == NULL) return MEMORY_E; @@ -7426,16 +7506,18 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* Start of RecipientEncryptedKeys */ /* EncryptedKey */ - encryptedKeyOctetSz = (int)SetOctetString(encryptedKeySz, encryptedKeyOctet); - totalSz += (encryptedKeyOctetSz + encryptedKeySz); + encryptedKeyOctetSz = (int)SetOctetString(encryptedKeySz, + encryptedKeyOctet); + totalSz += (encryptedKeyOctetSz + (int)encryptedKeySz); /* SubjectKeyIdentifier */ subjKeyIdOctetSz = (int)SetOctetString((word32)keyIdSize, subjKeyIdOctet); totalSz += (subjKeyIdOctetSz + keyIdSize); /* RecipientKeyIdentifier IMPLICIT [0] */ - recipKeyIdSeqSz = SetImplicit(ASN_SEQUENCE, 0, subjKeyIdOctetSz + - keyIdSize, recipKeyIdSeq, 0); + recipKeyIdSeqSz = (int)SetImplicit(ASN_SEQUENCE, 0, + (word32)(subjKeyIdOctetSz + keyIdSize), + recipKeyIdSeq, 0); totalSz += recipKeyIdSeqSz; /* RecipientEncryptedKey */ @@ -7450,9 +7532,9 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, if (kari->ukmSz > 0) { ukmOctetSz = (int)SetOctetString(kari->ukmSz, ukmOctetStr); - totalSz += (ukmOctetSz + kari->ukmSz); + totalSz += (ukmOctetSz + (int)kari->ukmSz); - ukmExplicitSz = SetExplicit(1, ukmOctetSz + kari->ukmSz, + ukmExplicitSz = (int)SetExplicit(1, (word32)ukmOctetSz + kari->ukmSz, ukmExplicitSeq, 0); totalSz += ukmExplicitSz; } @@ -7475,7 +7557,7 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, origPubKeyStr[0] = ASN_BIT_STRING; origPubKeyStrSz = (int)SetLength(kari->senderKeyExportSz + 1, origPubKeyStr + 1) + 2; - totalSz += (origPubKeyStrSz + kari->senderKeyExportSz); + totalSz += (origPubKeyStrSz + (int)kari->senderKeyExportSz); /* Originator AlgorithmIdentifier, params set to NULL for interop compatibility */ @@ -7486,15 +7568,15 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* outer OriginatorPublicKey IMPLICIT [1] */ origPubKeySeqSz = (int)SetImplicit(ASN_SEQUENCE, 1, - origAlgIdSz + origPubKeyStrSz + - kari->senderKeyExportSz, origPubKeySeq, 0); + (word32)(origAlgIdSz + origPubKeyStrSz + + (int)kari->senderKeyExportSz), origPubKeySeq, 0); totalSz += origPubKeySeqSz; /* outer OriginatorIdentifierOrKey IMPLICIT [0] */ origIdOrKeySeqSz = (int)SetImplicit(ASN_SEQUENCE, 0, - origPubKeySeqSz + origAlgIdSz + - origPubKeyStrSz + kari->senderKeyExportSz, - origIdOrKeySeq, 0); + (word32)(origPubKeySeqSz + origAlgIdSz + + origPubKeyStrSz + (int)kari->senderKeyExportSz), + origIdOrKeySeq, 0); totalSz += origIdOrKeySeqSz; /* version, always 3 */ @@ -7516,53 +7598,53 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, return BUFFER_E; } - XMEMCPY(recip->recip + idx, kariSeq, kariSeqSz); - idx += kariSeqSz; - XMEMCPY(recip->recip + idx, ver, verSz); - idx += verSz; + XMEMCPY(recip->recip + idx, kariSeq, (word32)kariSeqSz); + idx += (word32)kariSeqSz; + XMEMCPY(recip->recip + idx, ver, (word32)verSz); + idx += (word32)verSz; - XMEMCPY(recip->recip + idx, origIdOrKeySeq, origIdOrKeySeqSz); - idx += origIdOrKeySeqSz; - XMEMCPY(recip->recip + idx, origPubKeySeq, origPubKeySeqSz); - idx += origPubKeySeqSz; + XMEMCPY(recip->recip + idx, origIdOrKeySeq, (word32)origIdOrKeySeqSz); + idx += (word32)origIdOrKeySeqSz; + XMEMCPY(recip->recip + idx, origPubKeySeq, (word32)origPubKeySeqSz); + idx += (word32)origPubKeySeqSz; /* AlgorithmIdentifier with NULL parameter */ - XMEMCPY(recip->recip + idx, origAlgId, origAlgIdSz); - idx += origAlgIdSz; + XMEMCPY(recip->recip + idx, origAlgId, (word32)origAlgIdSz); + idx += (word32)origAlgIdSz; - XMEMCPY(recip->recip + idx, origPubKeyStr, origPubKeyStrSz); - idx += origPubKeyStrSz; + XMEMCPY(recip->recip + idx, origPubKeyStr, (word32)origPubKeyStrSz); + idx += (word32)origPubKeyStrSz; /* ephemeral public key */ XMEMCPY(recip->recip + idx, kari->senderKeyExport, kari->senderKeyExportSz); idx += kari->senderKeyExportSz; if (kari->ukmSz > 0) { - XMEMCPY(recip->recip + idx, ukmExplicitSeq, ukmExplicitSz); - idx += ukmExplicitSz; - XMEMCPY(recip->recip + idx, ukmOctetStr, ukmOctetSz); - idx += ukmOctetSz; + XMEMCPY(recip->recip + idx, ukmExplicitSeq, (word32)ukmExplicitSz); + idx += (word32)ukmExplicitSz; + XMEMCPY(recip->recip + idx, ukmOctetStr, (word32)ukmOctetSz); + idx += (word32)ukmOctetSz; XMEMCPY(recip->recip + idx, kari->ukm, kari->ukmSz); idx += kari->ukmSz; } - XMEMCPY(recip->recip + idx, keyEncryptAlgoId, keyEncryptAlgoIdSz); - idx += keyEncryptAlgoIdSz; - XMEMCPY(recip->recip + idx, keyWrapAlg, keyWrapAlgSz); - idx += keyWrapAlgSz; + XMEMCPY(recip->recip + idx, keyEncryptAlgoId, (word32)keyEncryptAlgoIdSz); + idx += (word32)keyEncryptAlgoIdSz; + XMEMCPY(recip->recip + idx, keyWrapAlg, (word32)keyWrapAlgSz); + idx += (word32)keyWrapAlgSz; - XMEMCPY(recip->recip + idx, recipEncKeysSeq, recipEncKeysSeqSz); - idx += recipEncKeysSeqSz; - XMEMCPY(recip->recip + idx, recipEncKeySeq, recipEncKeySeqSz); - idx += recipEncKeySeqSz; - XMEMCPY(recip->recip + idx, recipKeyIdSeq, recipKeyIdSeqSz); - idx += recipKeyIdSeqSz; - XMEMCPY(recip->recip + idx, subjKeyIdOctet, subjKeyIdOctetSz); - idx += subjKeyIdOctetSz; + XMEMCPY(recip->recip + idx, recipEncKeysSeq, (word32)recipEncKeysSeqSz); + idx += (word32)recipEncKeysSeqSz; + XMEMCPY(recip->recip + idx, recipEncKeySeq, (word32)recipEncKeySeqSz); + idx += (word32)recipEncKeySeqSz; + XMEMCPY(recip->recip + idx, recipKeyIdSeq, (word32)recipKeyIdSeqSz); + idx += (word32)recipKeyIdSeqSz; + XMEMCPY(recip->recip + idx, subjKeyIdOctet, (word32)subjKeyIdOctetSz); + idx += (word32)subjKeyIdOctetSz; /* subject key id */ - XMEMCPY(recip->recip + idx, kari->decoded->extSubjKeyId, keyIdSize); - idx += keyIdSize; - XMEMCPY(recip->recip + idx, encryptedKeyOctet, encryptedKeyOctetSz); - idx += encryptedKeyOctetSz; + XMEMCPY(recip->recip + idx, kari->decoded->extSubjKeyId, (word32)keyIdSize); + idx += (word32)keyIdSize; + XMEMCPY(recip->recip + idx, encryptedKeyOctet, (word32)encryptedKeyOctetSz); + idx += (word32)encryptedKeyOctetSz; /* encrypted CEK */ XMEMCPY(recip->recip + idx, encryptedKey, encryptedKeySz); idx += encryptedKeySz; @@ -7777,8 +7859,8 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return -1; } - snSz = SetSerialNumber(decoded->serial, decoded->serialSz, serial, - MAX_SN_SZ, MAX_SN_SZ); + snSz = SetSerialNumber(decoded->serial, (word32)decoded->serialSz, + serial, MAX_SN_SZ, MAX_SN_SZ); if (snSz < 0) { WOLFSSL_MSG("Error setting the serial number"); FreeDecodedCert(decoded); @@ -7791,8 +7873,8 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return -1; } - issuerSerialSeqSz = SetSequence(issuerSeqSz + issuerSz + snSz, - issuerSerialSeq); + issuerSerialSeqSz = (int)SetSequence((word32)(issuerSeqSz + issuerSz + + snSz), issuerSerialSeq); } else if (sidType == CMS_SKID) { /* version, must be 2 for SubjectKeyIdentifier */ @@ -7827,7 +7909,8 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, return ALGO_ID_E; } - keyEncAlgSz = SetAlgoID(pkcs7->publicKeyOID, keyAlgArray, oidKeyType, 0); + keyEncAlgSz = (int)SetAlgoID((int)pkcs7->publicKeyOID, keyAlgArray, + oidKeyType, 0); if (keyEncAlgSz == 0) { FreeDecodedCert(decoded); #ifdef WOLFSSL_SMALL_STACK @@ -7939,12 +8022,12 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* RecipientInfo */ if (sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { - recipSeqSz = (int)SetSequence(verSz + issuerSerialSeqSz + issuerSeqSz + - issuerSz + snSz + keyEncAlgSz + - encKeyOctetStrSz + encryptedKeySz, recipSeq); + int recipLen = verSz + (int)issuerSerialSeqSz + issuerSeqSz + + issuerSz + snSz + keyEncAlgSz + encKeyOctetStrSz + + (int)encryptedKeySz; + recipSeqSz = (int)SetSequence((word32)recipLen, recipSeq); - if (recipSeqSz + verSz + issuerSerialSeqSz + issuerSeqSz + snSz + - keyEncAlgSz + encKeyOctetStrSz + encryptedKeySz > MAX_RECIP_SZ) { + if ((recipSeqSz + recipLen) > MAX_RECIP_SZ) { WOLFSSL_MSG("RecipientInfo output buffer too small"); FreeDecodedCert(decoded); #ifdef WOLFSSL_SMALL_STACK @@ -7958,12 +8041,10 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, } } else { - recipSeqSz = SetSequence(verSz + ASN_TAG_SZ + issuerSKIDSz + - keyIdSize + keyEncAlgSz + encKeyOctetStrSz + - encryptedKeySz, recipSeq); - - if (recipSeqSz + verSz + ASN_TAG_SZ + issuerSKIDSz + keyIdSize + - keyEncAlgSz + encKeyOctetStrSz + encryptedKeySz > MAX_RECIP_SZ) { + int recipLen = verSz + ASN_TAG_SZ + (int)issuerSKIDSz + keyIdSize + + keyEncAlgSz + encKeyOctetStrSz + (int)encryptedKeySz; + recipSeqSz = (int)SetSequence((word32)recipLen, recipSeq); + if ((recipSeqSz + recipLen) > MAX_RECIP_SZ) { WOLFSSL_MSG("RecipientInfo output buffer too small"); FreeDecodedCert(decoded); #ifdef WOLFSSL_SMALL_STACK @@ -7978,31 +8059,31 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, } idx = 0; - XMEMCPY(recip->recip + idx, recipSeq, recipSeqSz); - idx += recipSeqSz; - XMEMCPY(recip->recip + idx, ver, verSz); - idx += verSz; + XMEMCPY(recip->recip + idx, recipSeq, (word32)recipSeqSz); + idx += (word32)recipSeqSz; + XMEMCPY(recip->recip + idx, ver, (word32)verSz); + idx += (word32)verSz; if (sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { - XMEMCPY(recip->recip + idx, issuerSerialSeq, issuerSerialSeqSz); - idx += issuerSerialSeqSz; - XMEMCPY(recip->recip + idx, issuerSeq, issuerSeqSz); - idx += issuerSeqSz; - XMEMCPY(recip->recip + idx, decoded->issuerRaw, issuerSz); - idx += issuerSz; - XMEMCPY(recip->recip + idx, serial, snSz); - idx += snSz; + XMEMCPY(recip->recip + idx, issuerSerialSeq, (word32)issuerSerialSeqSz); + idx += (word32)issuerSerialSeqSz; + XMEMCPY(recip->recip + idx, issuerSeq, (word32)issuerSeqSz); + idx += (word32)issuerSeqSz; + XMEMCPY(recip->recip + idx, decoded->issuerRaw, (word32)issuerSz); + idx += (word32)issuerSz; + XMEMCPY(recip->recip + idx, serial, (word32)snSz); + idx += (word32)snSz; } else { recip->recip[idx] = ASN_CONTEXT_SPECIFIC; idx += ASN_TAG_SZ; XMEMCPY(recip->recip + idx, issuerSKID, issuerSKIDSz); idx += issuerSKIDSz; - XMEMCPY(recip->recip + idx, pkcs7->issuerSubjKeyId, keyIdSize); - idx += keyIdSize; + XMEMCPY(recip->recip + idx, pkcs7->issuerSubjKeyId, (word32)keyIdSize); + idx += (word32)keyIdSize; } - XMEMCPY(recip->recip + idx, keyAlgArray, keyEncAlgSz); - idx += keyEncAlgSz; - XMEMCPY(recip->recip + idx, encKeyOctetStr, encKeyOctetStrSz); - idx += encKeyOctetStrSz; + XMEMCPY(recip->recip + idx, keyAlgArray, (word32)keyEncAlgSz); + idx += (word32)keyEncAlgSz; + XMEMCPY(recip->recip + idx, encKeyOctetStr, (word32)encKeyOctetStrSz); + idx += (word32)encKeyOctetStrSz; XMEMCPY(recip->recip + idx, encryptedKey, encryptedKeySz); idx += encryptedKeySz; @@ -8185,16 +8266,18 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, ret = NOT_COMPILED_IN; } else { - ret = wc_AesGcmEncrypt(aes, out, in, inSz, iv, ivSz, - authTag, authTagSz, aad, aadSz); + ret = wc_AesGcmEncrypt(aes, out, in, (word32)inSz, iv, + (word32)ivSz, authTag, authTagSz, aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT - /* async encrypt not available here, so block till done */ + /* async encrypt not available here, so block till done + */ ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); #endif } #else - ret = wc_AesGcmEncryptInit(aes, key, (word32)keySz, iv, ivSz); + ret = wc_AesGcmEncryptInit(aes, key, (word32)keySz, iv, + (word32)ivSz); if (ret == 0) { ret = wc_AesGcmEncryptUpdate(aes, NULL, NULL, 0, aad, aadSz); @@ -8246,8 +8329,9 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, if (ret == 0) { ret = wc_AesCcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesCcmEncrypt(aes, out, in, (word32)inSz, iv, ivSz, - authTag, authTagSz, aad, aadSz); + ret = wc_AesCcmEncrypt(aes, out, in, (word32)inSz, iv, + (word32)ivSz, authTag, authTagSz, + aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async encrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); @@ -8417,8 +8501,9 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, if (ret == 0) { ret = wc_AesGcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesGcmDecrypt(aes, out, in, (word32)inSz, iv, ivSz, - authTag, authTagSz, aad, aadSz); + ret = wc_AesGcmDecrypt(aes, out, in, (word32)inSz, iv, + (word32)ivSz, authTag, authTagSz, + aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); @@ -8456,8 +8541,9 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, if (ret == 0) { ret = wc_AesCcmSetKey(aes, key, (word32)keySz); if (ret == 0) { - ret = wc_AesCcmDecrypt(aes, out, in, (word32)inSz, iv, ivSz, - authTag, authTagSz, aad, aadSz); + ret = wc_AesCcmDecrypt(aes, out, in, (word32)inSz, iv, + (word32)ivSz, authTag, authTagSz, + aad, aadSz); #ifdef WOLFSSL_ASYNC_CRYPT /* async decrypt not available here, so block till done */ ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); @@ -8611,14 +8697,14 @@ int wc_PKCS7_SetContentType(PKCS7* pkcs7, byte* contentType, word32 sz) /* return size of padded data, padded to blockSz chunks, or negative on error */ int wc_PKCS7_GetPadSize(word32 inputSz, word32 blockSz) { - int padSz; + word32 padSz; if (blockSz == 0) return BAD_FUNC_ARG; padSz = blockSz - (inputSz % blockSz); - return padSz; + return (int)padSz; } @@ -8627,15 +8713,17 @@ int wc_PKCS7_GetPadSize(word32 inputSz, word32 blockSz) int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, word32 blockSz) { - int i, padSz; + int ret; + word32 i, padSz; if (in == NULL || inSz == 0 || out == NULL || outSz == 0) return BAD_FUNC_ARG; - padSz = wc_PKCS7_GetPadSize(inSz, blockSz); - if (padSz < 0) - return padSz; + ret = wc_PKCS7_GetPadSize(inSz, blockSz); + if (ret < 0) + return ret; + padSz = (word32)ret; if (outSz < (inSz + padSz)) return BAD_FUNC_ARG; @@ -8646,7 +8734,7 @@ int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, out[inSz + i] = (byte)padSz; } - return inSz + padSz; + return (int)(inSz + padSz); } @@ -8707,8 +8795,8 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, oriTypeLenSz = (int)SetLength(oriTypeSz, oriTypeLen); - recipSeqSz = SetImplicit(ASN_SEQUENCE, 4, 1 + oriTypeLenSz + oriTypeSz + - oriValueSz, recipSeq, 0); + recipSeqSz = SetImplicit(ASN_SEQUENCE, 4, 1 + (word32)oriTypeLenSz + + oriTypeSz + oriValueSz, recipSeq, 0); idx = 0; XMEMCPY(recip->recip + idx, recipSeq, recipSeqSz); @@ -8716,8 +8804,8 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, /* oriType */ recip->recip[idx] = ASN_OBJECT_ID; idx += 1; - XMEMCPY(recip->recip + idx, oriTypeLen, oriTypeLenSz); - idx += oriTypeLenSz; + XMEMCPY(recip->recip + idx, oriTypeLen, (word32)oriTypeLenSz); + idx += (word32)oriTypeLenSz; XMEMCPY(recip->recip + idx, oriType, oriTypeSz); idx += oriTypeSz; /* oriValue, input MUST already be ASN.1 encoded */ @@ -8762,8 +8850,8 @@ static int wc_PKCS7_GenerateKEK_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, case PBKDF2_OID: - ret = wc_PBKDF2(out, passwd, (int)pLen, salt, saltSz, iterations, - (int)outSz, prfOID); + ret = wc_PBKDF2(out, passwd, (int)pLen, salt, (int)saltSz, + iterations, (int)outSz, prfOID); if (ret != 0) { return ret; } @@ -8805,17 +8893,17 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, } /* get pad bytes needed to block boundary */ - padSz = blockSz - ((4 + cekSz) % blockSz); - outLen = 4 + cekSz + padSz; + padSz = (word32)blockSz - ((4 + cekSz) % (word32)blockSz); + outLen = (int)(4 + cekSz + padSz); /* must be at least two blocks long */ if (outLen < 2 * blockSz) - padSz += blockSz; + padSz += (word32)blockSz; /* if user set out to NULL, give back required length */ if (out == NULL) { *outSz = (word32)outLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } /* verify output buffer is large enough */ @@ -8895,7 +8983,7 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(PKCS7* pkcs7, const byte* kek, } /* input needs to be blockSz multiple and at least 2 * blockSz */ - if (((inSz % blockSz) != 0) || (inSz < (2 * (word32)blockSz))) { + if (((inSz % (word32)blockSz) != 0) || (inSz < (2 * (word32)blockSz))) { WOLFSSL_MSG("PWRI-KEK unwrap input must of block size and >= 2 " "times block size"); XFREE(outTmp, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -8915,15 +9003,15 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(PKCS7* pkcs7, const byte* kek, /* using last decrypted block as IV, decrypt [0 ... n-1] blocks */ lastBlock = outTmp + inSz - blockSz; ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, - lastBlock, blockSz, NULL, 0, NULL, 0, (byte*)in, inSz - blockSz, - outTmp, pkcs7->devId, pkcs7->heap); + lastBlock, blockSz, NULL, 0, NULL, 0, (byte*)in, + (int)inSz - blockSz, outTmp, pkcs7->devId, pkcs7->heap); } if (ret == 0) { /* decrypt using original kek and iv */ ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, - (byte*)iv, ivSz, NULL, 0, NULL, 0, outTmp, inSz, outTmp, - pkcs7->devId, pkcs7->heap); + (byte*)iv, (int)ivSz, NULL, 0, NULL, 0, outTmp, (int)inSz, + outTmp, pkcs7->devId, pkcs7->heap); } if (ret != 0) { @@ -9058,7 +9146,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, if (recip == NULL) return MEMORY_E; - kek = (byte*)XMALLOC(kekKeySz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + kek = (byte*)XMALLOC((word32)kekKeySz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (kek == NULL) { XFREE(recip, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return MEMORY_E; @@ -9074,7 +9162,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, encryptedKeySz = MAX_ENCRYPTED_KEY_SZ; XMEMSET(recip, 0, sizeof(Pkcs7EncodedRecip)); - XMEMSET(kek, 0, kekKeySz); + XMEMSET(kek, 0, (word32)kekKeySz); XMEMSET(encryptedKey, 0, encryptedKeySz); /* generate KEK: expand password into KEK */ @@ -9106,12 +9194,12 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, /* put together IV OCTET STRING */ ivOctetStringSz = SetOctetString((word32)kekBlockSz, ivOctetString); - totalSz += (ivOctetStringSz + kekBlockSz); + totalSz += (ivOctetStringSz + (word32)kekBlockSz); /* set PWRIAlgorithms AlgorithmIdentifier, adding (ivOctetStringSz + blockKeySz) for IV OCTET STRING */ pwriEncAlgoIdSz = SetAlgoID(encryptOID, pwriEncAlgoId, - oidBlkType, ivOctetStringSz + kekBlockSz); + oidBlkType, (int)ivOctetStringSz + kekBlockSz); totalSz += pwriEncAlgoIdSz; /* set KeyEncryptionAlgorithms OID */ @@ -9127,7 +9215,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, /* KeyEncryptionAlgorithm SEQ */ keyEncAlgoIdSeqSz = SetSequence(keyEncAlgoIdSz + pwriEncAlgoIdSz + - ivOctetStringSz + kekBlockSz, + ivOctetStringSz + (word32)kekBlockSz, keyEncAlgoIdSeq); totalSz += keyEncAlgoIdSeqSz; @@ -9203,8 +9291,8 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, idx += pwriEncAlgoIdSz; XMEMCPY(recip->recip + idx, ivOctetString, ivOctetStringSz); idx += ivOctetStringSz; - XMEMCPY(recip->recip + idx, tmpIv, kekBlockSz); - idx += kekBlockSz; + XMEMCPY(recip->recip + idx, tmpIv, (word32)kekBlockSz); + idx += (word32)kekBlockSz; XMEMCPY(recip->recip + idx, encKeyOctetStr, encKeyOctetStrSz); idx += encKeyOctetStrSz; XMEMCPY(recip->recip + idx, encryptedKey, encryptedKeySz); @@ -9339,7 +9427,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, } #endif encryptedKeySz = MAX_ENCRYPTED_KEY_SZ; - XMEMSET(encryptedKey, 0, encryptedKeySz); + XMEMSET(encryptedKey, 0, (word32)encryptedKeySz); #ifndef NO_AES direction = AES_ENCRYPTION; @@ -9367,7 +9455,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, } encKeyOctetStrSz = SetOctetString((word32)encryptedKeySz, encKeyOctetStr); - totalSz += (encKeyOctetStrSz + encryptedKeySz); + totalSz += (encKeyOctetStrSz + (word32)encryptedKeySz); /* KeyEncryptionAlgorithmIdentifier */ encAlgoIdSz = SetAlgoID(keyWrapOID, encAlgoId, oidKeyWrapType, 0); @@ -9389,7 +9477,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, #endif return timeSz; } - totalSz += timeSz; + totalSz += (word32)timeSz; } #endif @@ -9400,7 +9488,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, } /* KEKIdentifier SEQ */ - kekIdSeqSz = SetSequence(kekIdOctetStrSz + keyIdSz + timeSz + + kekIdSeqSz = SetSequence(kekIdOctetStrSz + keyIdSz + (word32)timeSz + otherAttSeqSz + otherOIDSz + otherSz, kekIdSeq); totalSz += kekIdSeqSz; @@ -9433,8 +9521,8 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, XMEMCPY(recip->recip + idx, keyId, keyIdSz); idx += keyIdSz; if (timePtr != NULL) { - XMEMCPY(recip->recip + idx, genTime, timeSz); - idx += timeSz; + XMEMCPY(recip->recip + idx, genTime, (word32)timeSz); + idx += (word32)timeSz; } if (other != NULL && otherSz > 0) { XMEMCPY(recip->recip + idx, otherAttSeq, otherAttSeqSz); @@ -9448,8 +9536,8 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, idx += encAlgoIdSz; XMEMCPY(recip->recip + idx, encKeyOctetStr, encKeyOctetStrSz); idx += encKeyOctetStrSz; - XMEMCPY(recip->recip + idx, encryptedKey, encryptedKeySz); - idx += encryptedKeySz; + XMEMCPY(recip->recip + idx, encryptedKey, (word32)encryptedKeySz); + idx += (word32)encryptedKeySz; #ifdef WOLFSSL_SMALL_STACK XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -9563,8 +9651,9 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) } #ifndef ASN_BER_TO_DER - if (output == NULL || outputSz == 0) + if (output == NULL || outputSz == 0) { return BAD_FUNC_ARG; + } #else /* if both output and callback are not set then error out */ if ((output == NULL || outputSz == 0) && (pkcs7->streamOutCb == NULL)) { @@ -9677,20 +9766,21 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) return padSz; } - encryptedOutSz = pkcs7->contentSz + padSz; + encryptedOutSz = (int)pkcs7->contentSz + padSz; #ifdef ASN_BER_TO_DER if (pkcs7->getContentCb == NULL) #endif { - plain = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + plain = (byte*)XMALLOC((word32)encryptedOutSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (plain == NULL) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); return MEMORY_E; } ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, - (word32)encryptedOutSz, blockSz); + (word32)encryptedOutSz, (word32)blockSz); if (ret < 0) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); @@ -9703,7 +9793,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) if (pkcs7->streamOutCb == NULL) #endif { - encryptedContent = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, + encryptedContent = (byte*)XMALLOC((word32)encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (encryptedContent == NULL) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -9729,9 +9819,9 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, encContentOctet, pkcs7->encodeStream); - encContentSeqSz = (int)SetSequenceEx(contentTypeSz + contentEncAlgoSz + - ivOctetStringSz + blockSz + - encContentOctetSz + encryptedOutSz, + encContentSeqSz = (int)SetSequenceEx((word32)(contentTypeSz + + contentEncAlgoSz + ivOctetStringSz + blockSz + + encContentOctetSz + encryptedOutSz), encContentSeq, pkcs7->encodeStream); /* keep track of sizes for outer wrapper layering */ @@ -9751,8 +9841,9 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) totalSz += ASN_INDEF_END_SZ; /* account for asn1 syntax around octet strings */ - StreamOctetString(NULL, (word32)encryptedOutSz, NULL, &streamSz, &tmpIdx); - totalSz += (streamSz - encryptedOutSz); + StreamOctetString(NULL, (word32)encryptedOutSz, NULL, &streamSz, + &tmpIdx); + totalSz += ((int)streamSz - encryptedOutSz); /* resize encrypted content buffer */ if (encryptedContent != NULL) { @@ -9836,7 +9927,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) while (tmpRecip != NULL) { wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, tmpRecip->recip, tmpRecip->recipSz); - idx += tmpRecip->recipSz; + idx += (int)tmpRecip->recipSz; tmpRecip = tmpRecip->next; } wc_PKCS7_FreeEncodedRecipientSet(pkcs7); @@ -9862,16 +9953,12 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* encrypt content */ ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, pkcs7->cek, - pkcs7->cekSz, tmpIv, blockSz, NULL, 0, NULL, 0, plain, + (int)pkcs7->cekSz, tmpIv, blockSz, NULL, 0, NULL, 0, plain, encryptedOutSz, encryptedContent); if (ret != 0) { - if (encryptedContent != NULL) { - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (plain != NULL) { - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); return ret; @@ -9888,7 +9975,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) wc_PKCS7_WriteOut(pkcs7, (output)? output + idx : NULL, encryptedContent, streamSz); } - idx += streamSz; + idx += (int)streamSz; /* end of encrypted content */ localIdx += SetIndefEnd(indefEnd + localIdx); @@ -9907,23 +9994,19 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, indefEnd, localIdx); - idx += localIdx; + idx += (int)localIdx; } else #endif { wc_PKCS7_WriteOut(pkcs7, (output)? (output + idx) : NULL, - encryptedContent, encryptedOutSz); + encryptedContent, (word32)encryptedOutSz); idx += encryptedOutSz; } - if (plain != NULL) { - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (encryptedContent != NULL) { - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return idx; } @@ -10063,7 +10146,8 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, return ASN_PARSE_E; /* if we found correct recipient, issuer hashes will match */ - if (XMEMCMP(issuerHash, pkcs7->issuerHash, keyIdSize) == 0) { + if (XMEMCMP(issuerHash, pkcs7->issuerHash, + (word32)keyIdSize) == 0) { *recipFound = 1; } @@ -10116,10 +10200,10 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, /* if we found correct recipient, SKID will match */ if (XMEMCMP(pkiMsg + (*idx), pkcs7->issuerSubjKeyId, - keyIdSize) == 0) { + (word32)keyIdSize) == 0) { *recipFound = 1; } - (*idx) += keyIdSize; + (*idx) += (word32)keyIdSize; } if (GetAlgoId(pkiMsg, idx, &encOID, oidKeyType, pkiMsgSz) < 0) @@ -10180,14 +10264,14 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, #endif /* Always allocate to ensure aligned use with RSA */ - encryptedKey = (byte*)XMALLOC(encryptedKeySz, pkcs7->heap, + encryptedKey = (byte*)XMALLOC((word32)encryptedKeySz, pkcs7->heap, DYNAMIC_TYPE_WOLF_BIGINT); if (encryptedKey == NULL) return MEMORY_E; if (*recipFound == 1) - XMEMCPY(encryptedKey, &pkiMsg[*idx], encryptedKeySz); - *idx += encryptedKeySz; + XMEMCPY(encryptedKey, &pkiMsg[*idx], (word32)encryptedKeySz); + *idx += (word32)encryptedKeySz; /* load private key */ #ifdef WOLFSSL_SMALL_STACK @@ -10302,7 +10386,7 @@ static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, return keySz; } else { *decryptedKeySz = (word32)keySz; - XMEMCPY(decryptedKey, outKey, keySz); + XMEMCPY(decryptedKey, outKey, (word32)keySz); ForceZero(encryptedKey, (word32)encryptedKeySz); } @@ -10408,15 +10492,16 @@ static int wc_PKCS7_KariGetOriginatorIdentifierOrKey(WC_PKCS7_KARI* kari, kari->senderKeyInit = 1; /* length-1 for unused bits counter */ - ret = wc_ecc_import_x963_ex(pkiMsg + (*idx), length - 1, kari->senderKey, - curve_id); + ret = wc_ecc_import_x963_ex(pkiMsg + (*idx), (word32)length - 1, + kari->senderKey, curve_id); if (ret != 0) { - ret = wc_EccPublicKeyDecode(pkiMsg, idx, kari->senderKey, *idx + length - 1); + ret = wc_EccPublicKeyDecode(pkiMsg, idx, kari->senderKey, + *idx + (word32)length - 1); if (ret != 0) return ret; } else { - (*idx) += length - 1; + (*idx) += (word32)(length - 1); } return 0; @@ -10469,15 +10554,16 @@ static int wc_PKCS7_KariGetUserKeyingMaterial(WC_PKCS7_KARI* kari, kari->ukm = NULL; if (length > 0) { - kari->ukm = (byte*)XMALLOC(length, kari->heap, DYNAMIC_TYPE_PKCS7); + kari->ukm = (byte*)XMALLOC((word32)length, kari->heap, + DYNAMIC_TYPE_PKCS7); if (kari->ukm == NULL) return MEMORY_E; - XMEMCPY(kari->ukm, pkiMsg + (*idx), length); + XMEMCPY(kari->ukm, pkiMsg + (*idx), (word32)length); kari->ukmOwner = 1; } - (*idx) += length; + (*idx) += (word32)length; kari->ukmSz = (word32)length; return 0; @@ -10509,7 +10595,7 @@ static int wc_PKCS7_KariGetKeyEncryptionAlgorithmId(WC_PKCS7_KARI* kari, return ASN_PARSE_E; } - if (localIdx < *idx + length) { + if (localIdx < *idx + (word32)length) { *idx = localIdx; } /* remove KeyWrapAlgorithm, stored in parameter of KeyEncAlgoId */ @@ -10568,11 +10654,11 @@ static int wc_PKCS7_KariGetSubjectKeyIdentifier(WC_PKCS7_KARI* kari, if (length != keyIdSize) return ASN_PARSE_E; - XMEMCPY(rid, pkiMsg + (*idx), keyIdSize); - (*idx) += length; + XMEMCPY(rid, pkiMsg + (*idx), (word32)keyIdSize); + (*idx) += (word32)length; /* subject key id should match if recipient found */ - if (XMEMCMP(rid, kari->decoded->extSubjKeyId, keyIdSize) == 0) { + if (XMEMCMP(rid, kari->decoded->extSubjKeyId, (word32)keyIdSize) == 0) { *recipFound = 1; } @@ -10618,7 +10704,7 @@ static int wc_PKCS7_KariGetIssuerAndSerialNumber(WC_PKCS7_KARI* kari, /* if we found correct recipient, issuer hashes will match */ if (kari->decodedInit == 1) { - if (XMEMCMP(rid, kari->decoded->issuerHash, keyIdSize) == 0) { + if (XMEMCMP(rid, kari->decoded->issuerHash, (word32)keyIdSize) == 0) { *recipFound = 1; } } @@ -10653,7 +10739,7 @@ static int wc_PKCS7_KariGetIssuerAndSerialNumber(WC_PKCS7_KARI* kari, ret = mp_init(recipSerial); if (ret == MP_OKAY) ret = mp_read_unsigned_bin(recipSerial, kari->decoded->serial, - kari->decoded->serialSz); + (word32)kari->decoded->serialSz); if (ret != MP_OKAY) { mp_clear(serial); WOLFSSL_MSG("Failed to parse CMS recipient serial number"); @@ -10745,9 +10831,9 @@ static int wc_PKCS7_KariGetRecipientEncryptedKeys(WC_PKCS7_KARI* kari, if (length > *encryptedKeySz) return BUFFER_E; - XMEMCPY(encryptedKey, pkiMsg + (*idx), length); + XMEMCPY(encryptedKey, pkiMsg + (*idx), (word32)length); *encryptedKeySz = length; - (*idx) += length; + (*idx) += (word32)length; return 0; } @@ -10858,12 +10944,12 @@ static int wc_PKCS7_DecryptOri(PKCS7* pkcs7, byte* in, word32 inSz, if (GetASNObjectId(pkiMsg, idx, &oriOIDSz, pkiMsgSz) != 0) return ASN_PARSE_E; - XMEMCPY(oriOID, pkiMsg + *idx, oriOIDSz); - *idx += oriOIDSz; + XMEMCPY(oriOID, pkiMsg + *idx, (word32)oriOIDSz); + *idx += (word32)oriOIDSz; /* get oriValue, increment idx */ oriValue = pkiMsg + *idx; - oriValueSz = seqSz - (*idx - tmpIdx); + oriValueSz = (word32)seqSz - (*idx - tmpIdx); *idx += oriValueSz; /* pass oriOID and oriValue to user callback, expect back @@ -10971,12 +11057,13 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, if (GetLength(pkiMsg, idx, &saltSz, pkiMsgSz) < 0) return ASN_PARSE_E; - salt = (byte*)XMALLOC(saltSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + salt = (byte*)XMALLOC((word32)saltSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (salt == NULL) return MEMORY_E; - XMEMCPY(salt, pkiMsg + (*idx), saltSz); - *idx += saltSz; + XMEMCPY(salt, pkiMsg + (*idx), (word32)saltSz); + *idx += (word32)saltSz; /* get KDF iterations */ if (GetMyVersion(pkiMsg, idx, &iterations, pkiMsgSz) < 0) { @@ -10997,7 +11084,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } /* get pwriEncAlgoId */ - if (GetAlgoId(pkiMsg, idx, &pwriEncAlgoId, oidBlkType, pkiMsgSz) < 0) { + if (GetAlgoId(pkiMsg, idx, &pwriEncAlgoId, oidBlkType, + pkiMsgSz) < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ASN_PARSE_E; } @@ -11037,8 +11125,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, return ASN_PARSE_E; } - XMEMCPY(tmpIv, pkiMsg + (*idx), length); - *idx += length; + XMEMCPY(tmpIv, pkiMsg + (*idx), (word32)length); + *idx += (word32)length; /* get EncryptedKey */ if (GetASNTag(pkiMsg, idx, &tag, pkiMsgSz) < 0) { @@ -11065,7 +11153,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } /* generate KEK */ - kek = (byte*)XMALLOC(kekKeySz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + kek = (byte*)XMALLOC((word32)kekKeySz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (kek == NULL) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(cek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11073,8 +11162,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, } ret = wc_PKCS7_GenerateKEK_PWRI(pkcs7, pkcs7->pass, pkcs7->passSz, - salt, (word32)saltSz, kdfAlgoId, hashOID, - iterations, kek, (word32)kekKeySz); + salt, (word32)saltSz, (int)kdfAlgoId, hashOID, + iterations, kek, (word32)kekKeySz); if (ret < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11084,8 +11173,8 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, /* decrypt CEK with KEK */ ret = wc_PKCS7_PwriKek_KeyUnWrap(pkcs7, kek, (word32)kekKeySz, - pkiMsg + (*idx), (word32)length, cek, - cekSz, tmpIv, (word32)blockSz, + pkiMsg + (*idx), (word32)length, + cek, cekSz, tmpIv, (word32)blockSz, (int)pwriEncAlgoId); if (ret < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11112,7 +11201,7 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, /* mark recipFound, since we only support one RecipientInfo for now */ *recipFound = 1; - *idx += length; + *idx += (word32)length; #ifndef NO_PKCS7_STREAM if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, idx)) != 0) { break; @@ -11190,7 +11279,7 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, &dateLen) != 0) { return ASN_PARSE_E; } - *idx += (dateLen + 1); + *idx += (word32)(dateLen + 1); } if (*idx > pkiMsgSz) { @@ -11206,7 +11295,7 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, return ASN_PARSE_E; /* skip it */ - *idx += length; + *idx += (word32)length; } if (*idx > pkiMsgSz) { @@ -11252,7 +11341,7 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, /* mark recipFound, since we only support one RecipientInfo for now */ *recipFound = 1; - *idx += length; + *idx += (word32)length; #ifndef NO_PKCS7_STREAM if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, idx)) != 0) { @@ -12299,8 +12388,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, ret = 0; #endif - XMEMCPY(tmpIv, &pkiMsg[idx], length); - idx += length; + XMEMCPY(tmpIv, &pkiMsg[idx], (word32)length); + idx += (word32)length; explicitOctet = 0; localIdx = idx; @@ -12360,7 +12449,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, * consecutive OCTET STRINGs, if so loop through * collecting and caching encrypted content bytes */ localIdx = idx; - while (idx < (localIdx + encryptedContentTotalSz)) { + while (idx < (localIdx + (word32)encryptedContentTotalSz)) { if (GetASNTag(pkiMsg, &idx, &tag, pkiMsgSz) < 0) { ret = ASN_PARSE_E; @@ -12385,7 +12474,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, } /* advance idx past encrypted content */ - idx += encryptedContentSz; + idx += (word32)encryptedContentSz; } if (ret != 0) { @@ -12399,7 +12488,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, if (ret != 0) { break; } - idx += encryptedContentTotalSz; + idx += (word32)encryptedContentTotalSz; } /* use cached content */ @@ -12423,7 +12512,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, ret = BUFFER_E; break; } - XMEMCPY(output, encryptedContent, encryptedContentSz - padLen); + XMEMCPY(output, encryptedContent, + (word32)encryptedContentSz - padLen); /* free memory, zero out keys */ ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); @@ -12731,17 +12821,18 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, contentTypeAttrib.valueSz = pkcs7->contentTypeSz; } - authAttribsSz += EncodeAttributes(authAttribs, 1, - &contentTypeAttrib, 1); + authAttribsSz += (word32)EncodeAttributes(authAttribs, 1, + &contentTypeAttrib, 1); authAttribsCount += 1; } /* authAttribs: add in user authenticated attributes */ if (pkcs7->authAttribs != NULL && pkcs7->authAttribsSz > 0) { - authAttribsSz += EncodeAttributes(authAttribs + authAttribsCount, - MAX_AUTH_ATTRIBS_SZ - authAttribsCount, + authAttribsSz += (word32)EncodeAttributes( + authAttribs + authAttribsCount, + (int)(MAX_AUTH_ATTRIBS_SZ - authAttribsCount), pkcs7->authAttribs, - pkcs7->authAttribsSz); + (int)pkcs7->authAttribsSz); authAttribsCount += pkcs7->authAttribsSz; } @@ -12789,20 +12880,19 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* build up unauthenticated attributes (unauthAttrs) */ if (pkcs7->unauthAttribsSz > 0) { - unauthAttribsSz = EncodeAttributes(unauthAttribs + unauthAttribsCount, - MAX_UNAUTH_ATTRIBS_SZ - unauthAttribsCount, - pkcs7->unauthAttribs, - pkcs7->unauthAttribsSz); + unauthAttribsSz = (word32)EncodeAttributes( + unauthAttribs + unauthAttribsCount, + (int)(MAX_UNAUTH_ATTRIBS_SZ - unauthAttribsCount), + pkcs7->unauthAttribs, + (int)pkcs7->unauthAttribsSz); unauthAttribsCount = pkcs7->unauthAttribsSz; flatUnauthAttribs = (byte*)XMALLOC(unauthAttribsSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (flatUnauthAttribs == NULL) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (aadBuffer) - XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return MEMORY_E; } @@ -12823,56 +12913,48 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* Copy content to plain buffer (zero-padded) to encrypt in full, * contiguous blocks */ - plain = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + plain = (byte*)XMALLOC((word32)encryptedAllocSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (plain == NULL) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (aadBuffer) - XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return MEMORY_E; } XMEMCPY(plain, pkcs7->content, pkcs7->contentSz); if ((encryptedAllocSz - encryptedOutSz) > 0) { - XMEMSET(plain + encryptedOutSz, 0, encryptedAllocSz - encryptedOutSz); + XMEMSET(plain + encryptedOutSz, 0, + (word32)(encryptedAllocSz - encryptedOutSz)); } - encryptedContent = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, + encryptedContent = (byte*)XMALLOC((word32)encryptedAllocSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (encryptedContent == NULL) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (aadBuffer) - XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return MEMORY_E; } /* encrypt content */ ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, pkcs7->cek, - pkcs7->cekSz, nonce, nonceSz, aadBuffer, aadBufferSz, authTag, - sizeof(authTag), plain, encryptedOutSz, encryptedContent); + (int)pkcs7->cekSz, nonce, (int)nonceSz, aadBuffer, aadBufferSz, + authTag, sizeof(authTag), plain, encryptedOutSz, encryptedContent); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); plain = NULL; - if (aadBuffer) { - XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - aadBuffer = NULL; - } + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + aadBuffer = NULL; if (ret != 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } @@ -12882,10 +12964,8 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, sizeof(contentType)); if (ret < 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } @@ -12899,41 +12979,41 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, macIntSz = (word32)SetMyVersion(sizeof(authTag), macInt, 0); /* add nonce and icv len into parameters string RFC5084 */ - algoParamSeqSz = SetSequence(nonceOctetStringSz + nonceSz + macIntSz, - algoParamSeq); + algoParamSeqSz = SetSequence((word32)nonceOctetStringSz + nonceSz + + macIntSz, algoParamSeq); /* build up our ContentEncryptionAlgorithmIdentifier sequence, * adding (nonceOctetStringSz + blockSz + macIntSz) for nonce OCTET STRING * and tag size */ contentEncAlgoSz = (int)SetAlgoID(pkcs7->encryptOID, contentEncAlgo, - oidBlkType, nonceOctetStringSz + nonceSz + - macIntSz + algoParamSeqSz); + oidBlkType, nonceOctetStringSz + (int)nonceSz + + (int)macIntSz + (int)algoParamSeqSz); if (contentEncAlgoSz == 0) { wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return BAD_FUNC_ARG; } encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, encContentOctet, 0); - encContentSeqSz = (int)SetSequence(contentTypeSz + contentEncAlgoSz + - nonceOctetStringSz + nonceSz + macIntSz + - algoParamSeqSz + encContentOctetSz + - encryptedOutSz, encContentSeq); + encContentSeqSz = (int)SetSequence((word32)contentTypeSz + + (word32)contentEncAlgoSz + + (word32)nonceOctetStringSz + nonceSz + macIntSz + + algoParamSeqSz + (word32)encContentOctetSz + + (word32)encryptedOutSz, encContentSeq); macOctetStringSz = (int)SetOctetString(sizeof(authTag), macOctetString); /* keep track of sizes for outer wrapper layering */ - totalSz = verSz + recipSetSz + recipSz + encContentSeqSz + contentTypeSz + - contentEncAlgoSz + nonceOctetStringSz + nonceSz + macIntSz + - algoParamSeqSz + encContentOctetSz + encryptedOutSz + - authAttribsSz + authAttribsSetSz + macOctetStringSz + - sizeof(authTag) + unauthAttribsSz + unauthAttribsSetSz; + totalSz = verSz + recipSetSz + recipSz + encContentSeqSz + + contentTypeSz + contentEncAlgoSz + nonceOctetStringSz + + (int)nonceSz + (int)macIntSz + (int)algoParamSeqSz + + encContentOctetSz + encryptedOutSz + (int)authAttribsSz + + (int)authAttribsSetSz + macOctetStringSz + (int)sizeof(authTag) + + (int)unauthAttribsSz + (int)unauthAttribsSetSz; /* EnvelopedData */ envDataSeqSz = (int)SetSequence((word32)totalSz, envDataSeq); @@ -12951,80 +13031,76 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, if (totalSz > (int)outputSz) { WOLFSSL_MSG("Pkcs7_encrypt output buffer too small"); wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - if (flatUnauthAttribs) - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAuthAttribs) - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return BUFFER_E; } - XMEMCPY(output + idx, contentInfoSeq, contentInfoSeqSz); + XMEMCPY(output + idx, contentInfoSeq, (word32)contentInfoSeqSz); idx += contentInfoSeqSz; - XMEMCPY(output + idx, outerContentType, outerContentTypeSz); + XMEMCPY(output + idx, outerContentType, (word32)outerContentTypeSz); idx += outerContentTypeSz; - XMEMCPY(output + idx, outerContent, outerContentSz); + XMEMCPY(output + idx, outerContent, (word32)outerContentSz); idx += outerContentSz; - XMEMCPY(output + idx, envDataSeq, envDataSeqSz); + XMEMCPY(output + idx, envDataSeq, (word32)envDataSeqSz); idx += envDataSeqSz; - XMEMCPY(output + idx, ver, verSz); + XMEMCPY(output + idx, ver, (word32)verSz); idx += verSz; - XMEMCPY(output + idx, recipSet, recipSetSz); + XMEMCPY(output + idx, recipSet, (word32)recipSetSz); idx += recipSetSz; /* copy in recipients from list */ tmpRecip = pkcs7->recipList; while (tmpRecip != NULL) { XMEMCPY(output + idx, tmpRecip->recip, tmpRecip->recipSz); - idx += tmpRecip->recipSz; + idx += (int)tmpRecip->recipSz; tmpRecip = tmpRecip->next; } wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - XMEMCPY(output + idx, encContentSeq, encContentSeqSz); + XMEMCPY(output + idx, encContentSeq, (word32)encContentSeqSz); idx += encContentSeqSz; - XMEMCPY(output + idx, contentType, contentTypeSz); + XMEMCPY(output + idx, contentType, (word32)contentTypeSz); idx += contentTypeSz; - XMEMCPY(output + idx, contentEncAlgo, contentEncAlgoSz); + XMEMCPY(output + idx, contentEncAlgo, (word32)contentEncAlgoSz); idx += contentEncAlgoSz; XMEMCPY(output + idx, algoParamSeq, algoParamSeqSz); - idx += algoParamSeqSz; - XMEMCPY(output + idx, nonceOctetString, nonceOctetStringSz); + idx += (int)algoParamSeqSz; + XMEMCPY(output + idx, nonceOctetString, (word32)nonceOctetStringSz); idx += nonceOctetStringSz; XMEMCPY(output + idx, nonce, nonceSz); - idx += nonceSz; + idx += (int)nonceSz; XMEMCPY(output + idx, macInt, macIntSz); - idx += macIntSz; + idx += (int)macIntSz; - XMEMCPY(output + idx, encContentOctet, encContentOctetSz); + XMEMCPY(output + idx, encContentOctet, (word32)encContentOctetSz); idx += encContentOctetSz; - XMEMCPY(output + idx, encryptedContent, encryptedOutSz); + XMEMCPY(output + idx, encryptedContent, (word32)encryptedOutSz); idx += encryptedOutSz; /* authenticated attributes */ if (flatAuthAttribs && authAttribsSz > 0) { XMEMCPY(output + idx, authAttribSet, authAttribsSetSz); - idx += authAttribsSetSz; + idx += (int)authAttribsSetSz; XMEMCPY(output + idx, flatAuthAttribs, authAttribsSz); - idx += authAttribsSz; + idx += (int)authAttribsSz; XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); } - XMEMCPY(output + idx, macOctetString, macOctetStringSz); + XMEMCPY(output + idx, macOctetString, (word32)macOctetStringSz); idx += macOctetStringSz; XMEMCPY(output + idx, authTag, sizeof(authTag)); - idx += sizeof(authTag); + idx += (int)sizeof(authTag); /* unauthenticated attributes */ if (unauthAttribsSz > 0) { XMEMCPY(output + idx, unauthAttribSet, unauthAttribsSetSz); - idx += unauthAttribsSetSz; + idx += (int)unauthAttribsSetSz; XMEMCPY(output + idx, flatUnauthAttribs, unauthAttribsSz); - idx += unauthAttribsSz; + idx += (int)unauthAttribsSz; } - if (flatUnauthAttribs != NULL) { - XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } + XFREE(flatUnauthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13268,8 +13344,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } if (ret == 0) { - XMEMCPY(nonce, &pkiMsg[idx], nonceSz); - idx += nonceSz; + XMEMCPY(nonce, &pkiMsg[idx], (word32)nonceSz); + idx += (word32)nonceSz; } /* get mac size, also stored in OPTIONAL parameter of AlgoID */ @@ -13324,14 +13400,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* store nonce for later */ if (nonceSz > 0) { pkcs7->stream->nonceSz = (word32)nonceSz; - pkcs7->stream->nonce = (byte*)XMALLOC(nonceSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); + pkcs7->stream->nonce = (byte*)XMALLOC((word32)nonceSz, + pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->stream->nonce == NULL) { ret = MEMORY_E; break; } else { - XMEMCPY(pkcs7->stream->nonce, nonce, nonceSz); + XMEMCPY(pkcs7->stream->nonce, nonce, (word32)nonceSz); } } @@ -13380,15 +13456,16 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, encryptedContentSz + expBlockSz - (encryptedContentSz % expBlockSz) : encryptedContentSz; - encryptedContent = (byte*)XMALLOC(encryptedAllocSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); + encryptedContent = (byte*)XMALLOC((word32)encryptedAllocSz, + pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (ret == 0 && encryptedContent == NULL) { ret = MEMORY_E; } if (ret == 0) { - XMEMCPY(encryptedContent, &pkiMsg[idx], encryptedContentSz); - idx += encryptedContentSz; + XMEMCPY(encryptedContent, &pkiMsg[idx], + (word32)encryptedContentSz); + idx += (word32)encryptedContentSz; } #ifndef NO_PKCS7_STREAM pkcs7->stream->bufferPt = encryptedContent; @@ -13407,7 +13484,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #ifndef NO_PKCS7_STREAM pkcs7->stream->expected = (word32)length; #endif - encodedAttribSz = length + (idx - encodedAttribIdx); + encodedAttribSz = (word32)length + (idx - encodedAttribIdx); if (ret != 0) break; @@ -13464,12 +13541,12 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, break; } - idx += length; + idx += (word32)length; #ifndef NO_PKCS7_STREAM if (encodedAttribSz > 0) { - XMEMCPY(pkcs7->stream->aad + (encodedAttribSz - length), - authAttrib, authAttribSz); + XMEMCPY(pkcs7->stream->aad + (encodedAttribSz - (word32)length), + authAttrib, (word32)authAttribSz); } if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; @@ -13513,8 +13590,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } if (ret == 0) { - XMEMCPY(authTag, &pkiMsg[idx], authTagSz); - idx += authTagSz; + XMEMCPY(authTag, &pkiMsg[idx], (word32)authTagSz); + idx += (word32)authTagSz; } if (ret == 0 && authAttrib != NULL) { @@ -13539,14 +13616,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* store tag for later */ if (authTagSz > 0) { pkcs7->stream->tagSz = (word32)authTagSz; - pkcs7->stream->tag = (byte*)XMALLOC(authTagSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); + pkcs7->stream->tag = (byte*)XMALLOC((word32)authTagSz, + pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->stream->tag == NULL) { ret = MEMORY_E; break; } else { - XMEMCPY(pkcs7->stream->tag, authTag, authTagSz); + XMEMCPY(pkcs7->stream->tag, authTag, (word32)authTagSz); } } @@ -13570,7 +13647,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, break; } else { - XMEMCPY(nonce, pkcs7->stream->nonce, nonceSz); + XMEMCPY(nonce, pkcs7->stream->nonce, (word32)nonceSz); } } @@ -13582,7 +13659,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, break; } else { - XMEMCPY(authTag, pkcs7->stream->tag, authTagSz); + XMEMCPY(authTag, pkcs7->stream->tag, (word32)authTagSz); } } @@ -13602,8 +13679,9 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, /* decrypt encryptedContent */ ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, decryptedKey, blockKeySz, nonce, nonceSz, encodedAttribs, encodedAttribSz, - authTag, (word32)authTagSz, encryptedContent, encryptedContentSz, - encryptedContent, pkcs7->devId, pkcs7->heap); + authTag, (word32)authTagSz, encryptedContent, + encryptedContentSz, encryptedContent, pkcs7->devId, + pkcs7->heap); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; @@ -13615,11 +13693,12 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } /* copy plaintext to output */ - XMEMCPY(output, encryptedContent, encryptedContentSz); + XMEMCPY(output, encryptedContent, (word32)encryptedContentSz); /* free memory, zero out keys */ ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encryptedContent = NULL; ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); #ifdef WOLFSSL_SMALL_STACK XFREE(decryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13646,7 +13725,17 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, } XFREE(decryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); } +#else + if (ret < 0) { + if (encryptedContent != NULL) { + ForceZero(encryptedContent, (word32)encryptedContentSz); + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encryptedContent = NULL; + } + ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); + } #endif + #ifndef NO_PKCS7_STREAM if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { wc_PKCS7_ResetStream(pkcs7); @@ -13751,21 +13840,21 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) if (padSz < 0) return padSz; - encryptedOutSz = pkcs7->contentSz + padSz; + encryptedOutSz = (int)pkcs7->contentSz + padSz; - plain = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, + plain = (byte*)XMALLOC((word32)encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (plain == NULL) return MEMORY_E; ret = wc_PKCS7_PadData(pkcs7->content, pkcs7->contentSz, plain, - (word32)encryptedOutSz, blockSz); + (word32)encryptedOutSz, (word32)blockSz); if (ret < 0) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - encryptedContent = (byte*)XMALLOC(encryptedOutSz, pkcs7->heap, + encryptedContent = (byte*)XMALLOC((word32)encryptedOutSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (encryptedContent == NULL) { XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13795,8 +13884,8 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) } ret = wc_PKCS7_EncryptContent(pkcs7, pkcs7->encryptOID, - pkcs7->encryptionKey, pkcs7->encryptionKeySz, tmpIv, blockSz, NULL, - 0, NULL, 0, plain, encryptedOutSz, encryptedContent); + pkcs7->encryptionKey, (int)pkcs7->encryptionKeySz, tmpIv, blockSz, + NULL, 0, NULL, 0, plain, encryptedOutSz, encryptedContent); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13806,9 +13895,9 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, encContentOctet, 0); - encContentSeqSz = (int)SetSequence(contentTypeSz + contentEncAlgoSz + - ivOctetStringSz + blockSz + - encContentOctetSz + encryptedOutSz, + encContentSeqSz = (int)SetSequence((word32)(contentTypeSz + + contentEncAlgoSz + ivOctetStringSz + blockSz + + encContentOctetSz + encryptedOutSz), encContentSeq); /* optional UnprotectedAttributes */ @@ -13830,11 +13919,13 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) } attribsCount = pkcs7->unprotectedAttribsSz; - attribsSz = EncodeAttributes(attribs, pkcs7->unprotectedAttribsSz, + attribsSz = (word32)EncodeAttributes(attribs, + (int)pkcs7->unprotectedAttribsSz, pkcs7->unprotectedAttribs, - pkcs7->unprotectedAttribsSz); + (int)pkcs7->unprotectedAttribsSz); - flatAttribs = (byte*)XMALLOC(attribsSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + flatAttribs = (byte*)XMALLOC(attribsSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); if (flatAttribs == NULL) { XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -13860,7 +13951,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* keep track of sizes for outer wrapper layering */ totalSz = verSz + encContentSeqSz + contentTypeSz + contentEncAlgoSz + ivOctetStringSz + blockSz + encContentOctetSz + encryptedOutSz + - attribsSz + attribsSetSz; + (int)attribsSz + (int)attribsSetSz; /* EncryptedData */ encDataSeqSz = (int)SetSequence((word32)totalSz, encDataSeq); @@ -13881,51 +13972,47 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) if (totalSz > (int)outputSz) { WOLFSSL_MSG("PKCS#7 output buffer too small"); - if (attribs != NULL) - XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAttribs != NULL) - XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return BUFFER_E; } - XMEMCPY(output + idx, contentInfoSeq, contentInfoSeqSz); + XMEMCPY(output + idx, contentInfoSeq, (word32)contentInfoSeqSz); idx += contentInfoSeqSz; - XMEMCPY(output + idx, outerContentType, outerContentTypeSz); + XMEMCPY(output + idx, outerContentType, (word32)outerContentTypeSz); idx += outerContentTypeSz; - XMEMCPY(output + idx, outerContent, outerContentSz); + XMEMCPY(output + idx, outerContent, (word32)outerContentSz); idx += outerContentSz; - XMEMCPY(output + idx, encDataSeq, encDataSeqSz); + XMEMCPY(output + idx, encDataSeq, (word32)encDataSeqSz); idx += encDataSeqSz; - XMEMCPY(output + idx, ver, verSz); + XMEMCPY(output + idx, ver, (word32)verSz); idx += verSz; - XMEMCPY(output + idx, encContentSeq, encContentSeqSz); + XMEMCPY(output + idx, encContentSeq, (word32)encContentSeqSz); idx += encContentSeqSz; - XMEMCPY(output + idx, contentType, contentTypeSz); + XMEMCPY(output + idx, contentType, (word32)contentTypeSz); idx += contentTypeSz; - XMEMCPY(output + idx, contentEncAlgo, contentEncAlgoSz); + XMEMCPY(output + idx, contentEncAlgo, (word32)contentEncAlgoSz); idx += contentEncAlgoSz; - XMEMCPY(output + idx, ivOctetString, ivOctetStringSz); + XMEMCPY(output + idx, ivOctetString, (word32)ivOctetStringSz); idx += ivOctetStringSz; - XMEMCPY(output + idx, tmpIv, blockSz); + XMEMCPY(output + idx, tmpIv, (word32)blockSz); idx += blockSz; - XMEMCPY(output + idx, encContentOctet, encContentOctetSz); + XMEMCPY(output + idx, encContentOctet, (word32)encContentOctetSz); idx += encContentOctetSz; - XMEMCPY(output + idx, encryptedContent, encryptedOutSz); + XMEMCPY(output + idx, encryptedContent, (word32)encryptedOutSz); idx += encryptedOutSz; if (pkcs7->unprotectedAttribsSz != 0) { XMEMCPY(output + idx, attribSet, attribsSetSz); - idx += attribsSetSz; + idx += (int)attribsSetSz; XMEMCPY(output + idx, flatAttribs, attribsSz); - idx += attribsSz; + idx += (int)attribsSz; } - if (attribs != NULL) - XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (flatAttribs != NULL) - XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -14186,8 +14273,8 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, tmpIv = pkcs7->stream->tmpIv; length = (int)pkcs7->stream->expected; #endif - XMEMCPY(tmpIv, &pkiMsg[idx], length); - idx += length; + XMEMCPY(tmpIv, &pkiMsg[idx], (word32)length); + idx += (word32)length; /* read encryptedContent, cont[0] */ if (ret == 0 && GetASNTag(pkiMsg, &idx, &tag, pkiMsgSz) < 0) ret = ASN_PARSE_E; @@ -14207,7 +14294,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, break; } - if (pkcs7->stream->totalRd + encryptedContentSz < + if (pkcs7->stream->totalRd + (word32)encryptedContentSz < pkcs7->stream->maxLen) { pkcs7->stream->flagOne = 1; } @@ -14236,21 +14323,23 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, tmpIv = pkcs7->stream->tmpIv; #endif if (ret == 0 && (encryptedContent = (byte*)XMALLOC( - encryptedContentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7)) == NULL) { + (unsigned int)encryptedContentSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7)) == NULL) { ret = MEMORY_E; break; } if (ret == 0) { - XMEMCPY(encryptedContent, &pkiMsg[idx], encryptedContentSz); - idx += encryptedContentSz; + XMEMCPY(encryptedContent, &pkiMsg[idx], + (unsigned int)encryptedContentSz); + idx += (word32)encryptedContentSz; /* decrypt encryptedContent */ ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, - pkcs7->encryptionKey, pkcs7->encryptionKeySz, tmpIv, - expBlockSz, NULL, 0, NULL, 0, encryptedContent, - encryptedContentSz, encryptedContent, - pkcs7->devId, pkcs7->heap); + pkcs7->encryptionKey, (int)pkcs7->encryptionKeySz, + tmpIv, expBlockSz, NULL, 0, NULL, 0, + encryptedContent, encryptedContentSz, + encryptedContent, pkcs7->devId, pkcs7->heap); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); } @@ -14267,7 +14356,8 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, } /* copy plaintext to output */ - XMEMCPY(output, encryptedContent, encryptedContentSz - padLen); + XMEMCPY(output, encryptedContent, + (unsigned int)(encryptedContentSz - padLen)); /* get implicit[1] unprotected attributes, optional */ wc_PKCS7_FreeDecodedAttrib(pkcs7->decodedAttrib, pkcs7->heap); @@ -14370,7 +14460,7 @@ int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, return BAD_FUNC_ARG; } #ifdef ASN_BER_TO_DER - pkcs7->encodeStream = flag; + pkcs7->encodeStream = (flag != 0); pkcs7->getContentCb = getContentCb; pkcs7->streamOutCb = streamOutCb; pkcs7->streamCtx = ctx; @@ -14406,7 +14496,7 @@ int wc_PKCS7_SetNoCerts(PKCS7* pkcs7, byte flag) if (pkcs7 == NULL) { return BAD_FUNC_ARG; } - pkcs7->noCerts = flag; + pkcs7->noCerts = (flag != 0); return 0; } diff --git a/src/wolfcrypt/src/poly1305.c b/src/wolfcrypt/src/poly1305.c index cde7547..718289c 100644 --- a/src/wolfcrypt/src/poly1305.c +++ b/src/wolfcrypt/src/poly1305.c @@ -1,6 +1,6 @@ /* poly1305.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,6 +29,13 @@ and Daniel J. Bernstein */ +/* + * WOLFSSL_W64_WRAPPER Uses wrappers around word64 types for a system that does + * not have word64 available. As expected it reduces + * performance. Benchmarks collected July 2024 show + * 303.004 MiB/s with and 1874.194 MiB/s without. + */ + #ifdef HAVE_CONFIG_H #include #endif @@ -199,7 +206,7 @@ extern void poly1305_final_avx2(Poly1305* ctx, byte* mac); #endif #elif defined(POLY130564) -#ifndef WOLFSSL_ARMASM +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) static word64 U8TO64(const byte* p) { return @@ -223,8 +230,9 @@ extern void poly1305_final_avx2(Poly1305* ctx, byte* mac); p[6] = (byte)(v >> 48); p[7] = (byte)(v >> 56); } -#endif/* WOLFSSL_ARMASM */ -#else /* if not 64 bit then use 32 bit */ +#endif/* !WOLFSSL_ARMASM && !WOLFSSL_RISCV_ASM */ +/* if not 64 bit then use 32 bit */ +#elif !defined(WOLFSSL_ARMASM) static word32 U8TO32(const byte *p) { @@ -261,7 +269,7 @@ static WC_INLINE void u32tole64(const word32 inLe32, byte outLe64[8]) } -#if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) /* This local function operates on a message with a given number of bytes with a given ctx pointer to a Poly1305 structure. @@ -332,8 +340,22 @@ static int poly1305_blocks(Poly1305* ctx, const unsigned char *m, word32 r0,r1,r2,r3,r4; word32 s1,s2,s3,s4; word32 h0,h1,h2,h3,h4; - word64 d0,d1,d2,d3,d4; word32 c; +#ifdef WOLFSSL_W64_WRAPPER + #ifdef WOLFSSL_SMALL_STACK + w64wrapper* d; + + d = (w64wrapper*)XMALLOC(5 * sizeof(w64wrapper), NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (d == NULL) { + return MEMORY_E; + } + #else + w64wrapper d[5]; + #endif +#else + word64 d0,d1,d2,d3,d4; +#endif r0 = ctx->r[0]; @@ -362,6 +384,41 @@ static int poly1305_blocks(Poly1305* ctx, const unsigned char *m, h4 += (U8TO32(m+12) >> 8) | hibit; /* h *= r */ +#ifdef WOLFSSL_W64_WRAPPER + { + w64wrapper tmp; + + d[0] = w64Mul(h0, r0); tmp = w64Mul(h1, s4); + d[0] = w64Add(d[0], tmp, NULL); tmp = w64Mul(h2, s3); + d[0] = w64Add(d[0], tmp, NULL); tmp = w64Mul(h3, s2); + d[0] = w64Add(d[0], tmp, NULL); tmp = w64Mul(h4, s1); + d[0] = w64Add(d[0], tmp, NULL); + + d[1] = w64Mul(h0, r1); tmp = w64Mul(h1, r0); + d[1] = w64Add(d[1], tmp, NULL); tmp = w64Mul(h2, s4); + d[1] = w64Add(d[1], tmp, NULL); tmp = w64Mul(h3, s3); + d[1] = w64Add(d[1], tmp, NULL); tmp = w64Mul(h4, s2); + d[1] = w64Add(d[1], tmp, NULL); + + d[2] = w64Mul(h0, r2); tmp = w64Mul(h1, r1); + d[2] = w64Add(d[2], tmp, NULL); tmp = w64Mul(h2, r0); + d[2] = w64Add(d[2], tmp, NULL); tmp = w64Mul(h3, s4); + d[2] = w64Add(d[2], tmp, NULL); tmp = w64Mul(h4, s3); + d[2] = w64Add(d[2], tmp, NULL); + + d[3] = w64Mul(h0, r3); tmp = w64Mul(h1, r2); + d[3] = w64Add(d[3], tmp, NULL); tmp = w64Mul(h2, r1); + d[3] = w64Add(d[3], tmp, NULL); tmp = w64Mul(h3, r0); + d[3] = w64Add(d[3], tmp, NULL); tmp = w64Mul(h4, s4); + d[3] = w64Add(d[3], tmp, NULL); + + d[4] = w64Mul(h0, r4); tmp = w64Mul(h1, r3); + d[4] = w64Add(d[4], tmp, NULL); tmp = w64Mul(h2, r2); + d[4] = w64Add(d[4], tmp, NULL); tmp = w64Mul(h3, r1); + d[4] = w64Add(d[4], tmp, NULL); tmp = w64Mul(h4, r0); + d[4] = w64Add(d[4], tmp, NULL); + } +#else d0 = ((word64)h0 * r0) + ((word64)h1 * s4) + ((word64)h2 * s3) + ((word64)h3 * s2) + ((word64)h4 * s1); d1 = ((word64)h0 * r1) + ((word64)h1 * r0) + ((word64)h2 * s4) + @@ -372,13 +429,31 @@ static int poly1305_blocks(Poly1305* ctx, const unsigned char *m, ((word64)h3 * r0) + ((word64)h4 * s4); d4 = ((word64)h0 * r4) + ((word64)h1 * r3) + ((word64)h2 * r2) + ((word64)h3 * r1) + ((word64)h4 * r0); +#endif /* (partial) h %= p */ +#ifdef WOLFSSL_W64_WRAPPER + c = w64GetLow32(w64ShiftRight(d[0], 26)); + h0 = w64GetLow32(d[0]) & 0x3ffffff; + d[1] = w64Add32(d[1], c, NULL); + c = w64GetLow32(w64ShiftRight(d[1], 26)); + h1 = w64GetLow32(d[1]) & 0x3ffffff; + d[2] = w64Add32(d[2], c, NULL); + c = w64GetLow32(w64ShiftRight(d[2], 26)); + h2 = w64GetLow32(d[2]) & 0x3ffffff; + d[3] = w64Add32(d[3], c, NULL); + c = w64GetLow32(w64ShiftRight(d[3], 26)); + h3 = w64GetLow32(d[3]) & 0x3ffffff; + d[4] = w64Add32(d[4], c, NULL); + c = w64GetLow32(w64ShiftRight(d[4], 26)); + h4 = w64GetLow32(d[4]) & 0x3ffffff; +#else c = (word32)(d0 >> 26); h0 = (word32)d0 & 0x3ffffff; d1 += c; c = (word32)(d1 >> 26); h1 = (word32)d1 & 0x3ffffff; d2 += c; c = (word32)(d2 >> 26); h2 = (word32)d2 & 0x3ffffff; d3 += c; c = (word32)(d3 >> 26); h3 = (word32)d3 & 0x3ffffff; d4 += c; c = (word32)(d4 >> 26); h4 = (word32)d4 & 0x3ffffff; +#endif h0 += c * 5; c = (h0 >> 26); h0 = h0 & 0x3ffffff; h1 += c; @@ -392,6 +467,10 @@ static int poly1305_blocks(Poly1305* ctx, const unsigned char *m, ctx->h[3] = h3; ctx->h[4] = h4; +#if defined(WOLFSSL_W64_WRAPPER) && defined(WOLFSSL_SMALL_STACK) + XFREE(d, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return 0; #endif /* end of 64 bit cpu blocks or 32 bit cpu */ @@ -413,9 +492,7 @@ static int poly1305_block(Poly1305* ctx, const unsigned char *m) return poly1305_blocks(ctx, m, POLY1305_BLOCK_SIZE); #endif } -#endif /* !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) */ -#if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) int wc_Poly1305SetKey(Poly1305* ctx, const byte* key, word32 keySz) { #if defined(POLY130564) && !defined(USE_INTEL_POLY1305_SPEEDUP) @@ -517,7 +594,11 @@ int wc_Poly1305Final(Poly1305* ctx, byte* mac) word32 h0,h1,h2,h3,h4,c; word32 g0,g1,g2,g3,g4; +#ifdef WOLFSSL_W64_WRAPPER + w64wrapper f; +#else word64 f; +#endif word32 mask; #endif @@ -656,10 +737,31 @@ int wc_Poly1305Final(Poly1305* ctx, byte* mac) h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff; /* mac = (h + pad) % (2^128) */ +#ifdef WOLFSSL_W64_WRAPPER + f = w64From32(0, h0); + f = w64Add32(f, ctx->pad[0], NULL); + h0 = w64GetLow32(f); + + f = w64ShiftRight(f, 32); + f = w64Add32(f, h1, NULL); + f = w64Add32(f, ctx->pad[1], NULL); + h1 = w64GetLow32(f); + + f = w64ShiftRight(f, 32); + f = w64Add32(f, h2, NULL); + f = w64Add32(f, ctx->pad[2], NULL); + h2 = w64GetLow32(f); + + f = w64ShiftRight(f, 32); + f = w64Add32(f, h3, NULL); + f = w64Add32(f, ctx->pad[3], NULL); + h3 = w64GetLow32(f); +#else f = (word64)h0 + ctx->pad[0] ; h0 = (word32)f; f = (word64)h1 + ctx->pad[1] + (f >> 32); h1 = (word32)f; f = (word64)h2 + ctx->pad[2] + (f >> 32); h2 = (word32)f; f = (word64)h3 + ctx->pad[3] + (f >> 32); h3 = (word32)f; +#endif U32TO8(mac + 0, h0); U32TO8(mac + 4, h1); @@ -686,7 +788,7 @@ int wc_Poly1305Final(Poly1305* ctx, byte* mac) return 0; } -#endif /* !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) */ +#endif /* !WOLFSSL_ARMASM && !WOLFSSL_RISCV_ASM */ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) @@ -781,7 +883,7 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) /* process full blocks */ if (bytes >= POLY1305_BLOCK_SIZE) { size_t want = ((size_t)bytes & ~((size_t)POLY1305_BLOCK_SIZE - 1)); -#if !defined(WOLFSSL_ARMASM) || !defined(__aarch64__) +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) int ret; ret = poly1305_blocks(ctx, m, want); if (ret != 0) diff --git a/src/wolfcrypt/src/port/Espressif/esp32_aes.c b/src/wolfcrypt/src/port/Espressif/esp32_aes.c index e8c917c..f85343e 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -637,7 +637,7 @@ int esp_hw_show_aes_metrics(void) #if defined(WOLFSSL_HW_METRICS) ESP_LOGI(TAG, "--------------------------------------------------------"); - ESP_LOGI(TAG, "------------- wolfSSL ESP HW AES Metrics----------------"); + ESP_LOGI(TAG, "------------- wolfSSL ESP HW AES Metrics -------------"); ESP_LOGI(TAG, "--------------------------------------------------------"); ESP_LOGI(TAG, "esp_aes_unsupported_length_usage_ct = %lu", diff --git a/src/wolfcrypt/src/port/Espressif/esp32_mp.c b/src/wolfcrypt/src/port/Espressif/esp32_mp.c index 5c37592..458719d 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -35,7 +35,6 @@ * * Also, beware: "we have uint32_t == unsigned long for both Xtensa and RISC-V" * see https://github.com/espressif/esp-idf/issues/9511#issuecomment-1207342464 - * https://docs.espressif.com/projects/esp-idf/en/latest/esp32/migration-guides/release-5.x/5.0/gcc.html */ #ifdef HAVE_CONFIG_H @@ -69,9 +68,70 @@ #include #endif -#define ESP_HW_RSAMAX_BIT 4096 -#define ESP_HW_MULTI_RSAMAX_BITS 2048 #define ESP_HW_RSAMIN_BIT 512 +#define ESP_HW_RSAMAX_BIT 4096 +#if defined(CONFIG_IDF_TARGET_ESP32) + /* See 24.3.2 Large Number Modular Exponentiation: + * esp32_technical_reference_manual_en.pdf + * The RSA Accelerator supports specific operand lengths of N + * {512, 1024, 1536, 2048, 2560, 3072, 3584, 4096} bits + * + * 24.3.4 Large Number Multiplication + * The length of Z is twice that of X and Y . Therefore, the RSA Accelerator + * supports large-number multiplication with only four operand lengths of + * N in {512, 1024, 1536, 2048} */ + #define ESP_HW_MOD_RSAMAX_BITS 4096 + #define ESP_HW_MULTI_RSAMAX_BITS 2048 +#elif defined(CONFIG_IDF_TARGET_ESP32S2) + /* See 18.3.1 Large Number Modular Exponentiation + * esp32-s2_technical_reference_manual_en.pdf + * RSA Accelerator supports operands of length N = (32 * x), + * where x in {1, 2, 3, . . . , 128}. The bit lengths of arguments + * Z, X, Y , M, and r can be arbitrary N, but all numbers in a calculation + * must be of the same length. 32 * 128 = 4096 */ + #define ESP_HW_MOD_RSAMAX_BITS 4096 + #define ESP_HW_MULTI_RSAMAX_BITS 2048 +#elif defined(CONFIG_IDF_TARGET_ESP32S3) + /* See 20.3.1 Large Number Modular Exponentiation + * esp32-s3_technical_reference_manual_en.pdf + * RSA Accelerator supports operands of length N = (32 * x), + * where x in {1, 2, 3, . . . , 128}. The bit lengths of arguments + * Z, X, Y , M, and r can be arbitrary N, but all numbers in a calculation + * must be of the same length. 32 * 128 = 4096 */ + #define ESP_HW_MOD_RSAMAX_BITS 4096 + #define ESP_HW_MULTI_RSAMAX_BITS 2048 +#elif defined(CONFIG_IDF_TARGET_ESP32C3) + /* See 20.3.1 Large Number Modular Exponentiation + * esp32-c3_technical_reference_manual_en.pdf + * RSA Accelerator supports operands of length N = (32 * x), + * where x in {1, 2, 3, . . . , 96}. The bit lengths of arguments + * Z, X, Y , M, and r can be arbitrary N, but all numbers in a calculation + * must be of the same length. 32 * 96 = 3072 */ + #define ESP_HW_MOD_RSAMAX_BITS 3072 + /* The length of result Z is twice that of operand X and operand Y. + * Therefore, the RSA accelerator only supports large-number multiplication + * with operand length N = 32 * x, where x in {1, 2, 3, . . . , 48}. + * 32 * (96/2) = 32 * (48/2) = 1536 */ + #define ESP_HW_MULTI_RSAMAX_BITS 1536 +#elif defined(CONFIG_IDF_TARGET_ESP32C6) + /* See 22.3.1 Large-number Modular Exponentiation + * esp32-c6_technical_reference_manual_en.pdf + * The RSA accelerator supports operands of length N = (32 * x), + * where x in {1, 2, 3, . . . , 96}. The bit lengths of arguments + * Z, X, Y , M, and r can be arbitrary N, but all numbers in a calculation + * must be of the same length. 32 * 96 = 3072 */ + #define ESP_HW_MOD_RSAMAX_BITS 3072 + /* The length of result Z is twice that of operand X and operand Y. + * Therefore, the RSA accelerator only supports large-number multiplication + * with operand length N = 32 * x, where x in {1, 2, 3, . . . , 48}. + * 32 * (96/2) = 32 * (48/2) = 1536 */ + #define ESP_HW_MULTI_RSAMAX_BITS 1536 +#else + /* No HW on ESP8266, but then we'll not even use this lib. + * Other ESP32 devices not implemented: */ + #define ESP_HW_MOD_RSAMAX_BITS 0 + #define ESP_HW_MULTI_RSAMAX_BITS 0 +#endif /* (s+(4-1))/ 4 */ #define BYTE_TO_WORDS(s) (((s+3)>>2)) @@ -81,6 +141,7 @@ #define BITS_IN_ONE_WORD 32 +/* Some minimum operand sizes, fall back to SW if too small: */ #ifndef ESP_RSA_MULM_BITS #define ESP_RSA_MULM_BITS 16 #endif @@ -93,8 +154,18 @@ #define ESP_RSA_EXPT_YBITS 8 #endif +/* RSA math calculation timeout */ +#ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x5000000 +#endif #define ESP_TIMEOUT(cnt) (cnt >= ESP_RSA_TIMEOUT_CNT) +/* Hardware Ready Timeout */ +#ifndef ESP_RSA_WAIT_TIMEOUT_CNT + #define ESP_RSA_WAIT_TIMEOUT_CNT 0x20 +#endif +#define ESP_WAIT_TIMEOUT(cnt) (cnt >= ESP_RSA_WAIT_TIMEOUT_CNT) + #if defined(CONFIG_IDF_TARGET_ESP32C3) #include #include @@ -142,33 +213,42 @@ static portMUX_TYPE wc_rsa_reg_lock = portMUX_INITIALIZER_UNLOCKED; #ifdef WOLFSSL_HW_METRICS static unsigned long esp_mp_max_used = 0; - static unsigned long esp_mp_mulmod_small_x_ct = 0; - static unsigned long esp_mp_mulmod_small_y_ct = 0; - - static unsigned long esp_mp_max_timeout = 0; + static unsigned long esp_mp_max_timeout = 0; /* Calc duration */ + static unsigned long esp_mp_max_wait_timeout; /* HW wait duration */ + /* HW Multiplication Metrics */ #ifndef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL static unsigned long esp_mp_mul_usage_ct = 0; static unsigned long esp_mp_mul_error_ct = 0; + static unsigned long esp_mp_mul_tiny_ct = 0; + static unsigned long esp_mp_mul_max_exceeded_ct = 0; #endif /* !NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL */ + /* HW Modular Multiplication Metrics */ #ifndef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + static unsigned long esp_mp_mulmod_small_x_ct = 0; + static unsigned long esp_mp_mulmod_small_y_ct = 0; + static unsigned long esp_mp_mulmod_max_exceeded_ct = 0; static unsigned long esp_mp_mulmod_usage_ct = 0; static unsigned long esp_mp_mulmod_fallback_ct = 0; static unsigned long esp_mp_mulmod_even_mod_ct = 0; static unsigned long esp_mp_mulmod_error_ct = 0; - #endif /* !NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD */ + #endif + /* HW Modular Exponentiation Metrics */ #ifndef NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD static unsigned long esp_mp_exptmod_usage_ct = 0; static unsigned long esp_mp_exptmod_error_ct = 0; + static unsigned long esp_mp_exptmod_max_exceeded_ct = 0; static unsigned long esp_mp_exptmod_fallback_ct = 0; #endif /* !NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD */ -#endif +#endif /* WOLFSSL_HW_METRICS */ /* mutex */ #ifdef SINGLE_THREADED - int single_thread_locked = 0; + /* Although freeRTOS is multithreaded, if we know we'll only be in + * a single thread for wolfSSL, we can avoid the complexity of mutexes. */ + static int single_thread_locked = 0; #else static wolfSSL_Mutex mp_mutex; static int espmp_CryptHwMutexInit = 0; @@ -185,7 +265,7 @@ static portMUX_TYPE wc_rsa_reg_lock = portMUX_INITIALIZER_UNLOCKED; * check if the HW is ready before accessing it * * See 24.3.1 Initialization of ESP32 Technical Reference Manual -* https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf +* esp32_technical_reference_manual_en.pdf * * The RSA Accelerator is activated by enabling the corresponding peripheral * clock, and by clearing the DPORT_RSA_PD bit in the DPORT_RSA_PD_CTRL_REG @@ -238,14 +318,23 @@ static int esp_mp_hw_wait_clean(void) /* no HW timeout if we don't know the platform. assumes no HW */ #endif - #if defined(WOLFSSL_HW_METRICS) - { - esp_mp_max_timeout = (timeout > esp_mp_max_timeout) ? timeout : - esp_mp_max_timeout; +#if defined(WOLFSSL_HW_METRICS) + /* The wait timeout is separate from the overall max calc timeout. */ + if (timeout > esp_mp_max_wait_timeout) { + esp_mp_max_wait_timeout = timeout; } - #endif + /* Also see if the overall timeout has been increased. */ + if (timeout > esp_mp_max_timeout) { + esp_mp_max_timeout = timeout; + } +#endif if (ESP_TIMEOUT(timeout)) { + /* This is highly unusual and will likely only occur in multi-threaded + * application. wolfSSL ctx is not thread safe. */ + #ifndef SINGLE_THREADED + ESP_LOGI(TAG, "Consider #define SINGLE_THREADED. See docs"); + #endif ESP_LOGE(TAG, "esp_mp_hw_wait_clean waiting HW ready timed out."); ret = WC_HW_WAIT_E; /* hardware is busy, MP_HW_BUSY; */ } @@ -293,7 +382,7 @@ static int esp_mp_hw_islocked(void) * Returns 0 (ESP_OK) if the HW lock was initialized and mutex lock. * * See Chapter 24: -* https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf +* esp32_technical_reference_manual_en.pdf * * The RSA Accelerator is activated by enabling the corresponding peripheral * clock, and by clearing the DPORT_RSA_PD bit in the DPORT_RSA_PD_CTRL_REG @@ -332,8 +421,7 @@ static int esp_mp_hw_lock(void) if (ret == ESP_OK) { /* lock hardware; there should be exactly one instance * of esp_CryptHwMutexLock(&mp_mutex ...) in code */ - /* TODO - do we really want to wait? - * probably not */ + ret = esp_CryptHwMutexLock(&mp_mutex, ESP_MP_HW_LOCK_MAX_DELAY); if (ret != ESP_OK) { ESP_LOGE(TAG, "mp engine lock failed."); @@ -529,7 +617,9 @@ static int esp_mp_hw_unlock(void) ESP_LOGV(TAG, "exit esp_mp_hw_unlock"); } else { +#ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGW(TAG, "Warning: esp_mp_hw_unlock called when not locked."); +#endif } return ret; @@ -736,6 +826,12 @@ static int wait_until_done(word32 reg) #endif +#if defined(WOLFSSL_HW_METRICS) + if (timeout > esp_mp_max_timeout) { + esp_mp_max_timeout = timeout; + } +#endif + if (ESP_TIMEOUT(timeout)) { ESP_LOGE(TAG, "rsa operation timed out."); ret = WC_HW_E; /* MP_HW_ERROR; */ @@ -1084,12 +1180,17 @@ int esp_mp_montgomery_init(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, mph->hwWords_sz = words2hwords(mph->maxWords_sz); if ((mph->hwWords_sz << 5) > ESP_HW_RSAMAX_BIT) { + #if defined(WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS) || \ + defined(WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS) ESP_LOGW(TAG, "Warning: hwWords_sz = %d (%d bits)" " exceeds HW maximum bits (%d), " " falling back to SW.", mph->hwWords_sz, mph->hwWords_sz << 5, ESP_HW_RSAMAX_BIT); + #endif + /* The fallback error code is expected to be handled by + * caller to perform software instead. */ ret = MP_HW_FALLBACK; } /* hwWords_sz check */ } /* X and Y size ok */ @@ -1285,17 +1386,34 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) Zs = Xs + Ys; /* RSA Accelerator only supports Large Number Multiplication - * with operand length N = 32 * x, - * where x in {1, 2, 3, . . . , 64} */ - if (Xs > 64 || Ys > 64) { - return MP_HW_FALLBACK; /* TODO add count metric on size fallback */ + * with certain operand lengths N = (32 * x); See above. */ + if (Xs > ESP_HW_MULTI_RSAMAX_BITS) { +#if defined(WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS) + ESP_LOGW(TAG, "mp-mul X %d bits exceeds max bit length (%d)", + Xs, ESP_HW_MULTI_RSAMAX_BITS); +#endif + esp_mp_mul_max_exceeded_ct++; + return MP_HW_FALLBACK; + } + if (Ys > ESP_HW_MULTI_RSAMAX_BITS) { +#if defined(WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS) + ESP_LOGW(TAG, "mp-mul Y %d bits exceeds max bit length (%d)", + Ys, ESP_HW_MULTI_RSAMAX_BITS); +#endif + esp_mp_mul_max_exceeded_ct++; + return MP_HW_FALLBACK; } - if (Zs <= sizeof(mp_digit)*8) { + /* sizeof(mp_digit) is typically 4 bytes. + * If the total Zs fits into a 4 * 8 = 32 bit word, just do regular math: */ + if (Zs <= sizeof(mp_digit) * 8) { Z->dp[0] = X->dp[0] * Y->dp[0]; Z->used = 1; #if defined(WOLFSSL_SP_INT_NEGATIVE) || defined(USE_FAST_MATH) Z->sign = res_sign; /* See above mp_isneg() for negative detection */ +#endif +#if defined(WOLFSSL_HW_METRICS) + esp_mp_mul_tiny_ct++; #endif return MP_OKAY; } @@ -1306,13 +1424,21 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) hwWords_sz = words2hwords(maxWords_sz); resultWords_sz = bits2words(Xs + Ys); - /* sanity check */ + + /* Final parameter sanity check */ if ( (hwWords_sz << 5) > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "exceeds max bit length(2048) (a)"); - ret = MP_HW_FALLBACK; /* Error: value is not able to be used. */ + #if defined(WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS) + ESP_LOGW(TAG, "mp-mul exceeds max bit length (%d)", + ESP_HW_MULTI_RSAMAX_BITS); + #endif + #if defined(WOLFSSL_HW_METRICS) + esp_mp_mul_max_exceeded_ct++; + #endif + return MP_HW_FALLBACK; /* Fallback to use SW */ } } + /* If no initial exit, proceed to hardware multiplication calculations: */ #if defined(CONFIG_IDF_TARGET_ESP32) /* assumed to be regular ESP32 Xtensa here */ @@ -1440,11 +1566,17 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* Make sure we are within capabilities of hardware. */ if ((hwWords_sz * BITS_IN_ONE_WORD) > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "exceeds max bit length(%d)", ESP_HW_MULTI_RSAMAX_BITS); +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + ESP_LOGW(TAG, "exceeds max bit length(%d)", + ESP_HW_MULTI_RSAMAX_BITS); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } if ((hwWords_sz * BITS_IN_ONE_WORD * 2) > ESP_HW_RSAMAX_BIT) { - ESP_LOGW(TAG, "result exceeds max bit length(%d)", ESP_HW_RSAMAX_BIT ); +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + ESP_LOGW(TAG, "result exceeds max bit length(%d) * 2", + ESP_HW_RSAMAX_BIT ); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } @@ -1517,21 +1649,30 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) #elif defined(CONFIG_IDF_TARGET_ESP32C6) /* Unlike the ESP32 that is limited to only four operand lengths, * the ESP32-C6 The RSA Accelerator supports large-number modular - * multiplication with operands of 128 different lengths. + * multiplication with operands of 96 different lengths. (1 .. 96 words) * * X & Y must be represented by the same number of bits. Must be - * enough to represent the larger one. */ + * enough to represent the larger one. + * + * Multiplication is limited to 48 different lengths (1 .. 48 words) */ /* Figure out how many words we need to * represent each operand & the result. */ /* Make sure we are within capabilities of hardware. */ + if ((hwWords_sz * BITS_IN_ONE_WORD) > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "exceeds max bit length(%d)", ESP_HW_MULTI_RSAMAX_BITS); +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + ESP_LOGW(TAG, "RSA mul result hwWords_sz %d exceeds max bit length %d", + hwWords_sz, ESP_HW_MULTI_RSAMAX_BITS); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } if ((hwWords_sz * BITS_IN_ONE_WORD * 2) > ESP_HW_RSAMAX_BIT) { - ESP_LOGW(TAG, "result exceeds max bit length(%d)", ESP_HW_RSAMAX_BIT ); +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + ESP_LOGW(TAG, "RSA max result hwWords_sz %d exceeds max bit length %d", + hwWords_sz, ESP_HW_RSAMAX_BIT ); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } @@ -1627,11 +1768,15 @@ int esp_mp_mul(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* Z) /* Make sure we are within capabilities of hardware. */ if ((hwWords_sz * BITS_IN_ONE_WORD) > ESP_HW_MULTI_RSAMAX_BITS) { +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS ESP_LOGW(TAG, "exceeds max bit length(%d)", ESP_HW_MULTI_RSAMAX_BITS); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } if ((hwWords_sz * BITS_IN_ONE_WORD * 2) > ESP_HW_RSAMAX_BIT) { +#ifdef WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS ESP_LOGW(TAG, "result exceeds max bit length(%d)", ESP_HW_RSAMAX_BIT ); +#endif ret = MP_HW_FALLBACK; /* let SW figure out how to deal with it */ } @@ -1934,10 +2079,9 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) } #endif ret = MP_HW_FALLBACK; - /* TODO add debug metrics */ #ifdef WOLFSSL_DEBUG_ESP_RSA_MULM_BITS { - ESP_LOGV(TAG, "esp_mp_mulmod falling back for ESP_RSA_MULM_BITS!"); + ESP_LOGW(TAG, "esp_mp_mulmod falling back for ESP_RSA_MULM_BITS!"); } #endif } @@ -2101,9 +2245,11 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS ESP_LOGW(TAG, "result exceeds max bit length"); - return MP_VAL; /* Error: value is not able to be used. */ + #endif + return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } WordsForOperand = bits2words(OperandBits); /* alt inline calc: @@ -2190,9 +2336,16 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "result exceeds max bit length"); - return MP_VAL; /* Error: value is not able to be used. */ + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS + ESP_LOGW(TAG, "mulmod OperandBits = %d " + "result exceeds max bit length %d", + OperandBits, ESP_HW_MOD_RSAMAX_BITS); + #endif + if (mulmod_lock_called) { + ret = esp_mp_hw_unlock(); + } + return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } WordsForOperand = bits2words(OperandBits); /* alt inline calc: @@ -2282,9 +2435,12 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* 3. Write (N_result_bits/32 - 1) to the RSA_MODE_REG. */ OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "result exceeds max bit length"); - return MP_VAL; /* Error: value is not able to be used. */ + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS + ESP_LOGW(TAG, "mp_mulmod OperandBits %d exceeds max bit length %d.", + OperandBits, ESP_HW_MOD_RSAMAX_BITS); + #endif + return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } WordsForOperand = bits2words(OperandBits); /* alt inline calc: @@ -2346,7 +2502,9 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) ESP_LOGV(TAG, "Lock not called due to no-lock MP_HW_FALLBACK"); } else { - ESP_LOGW(TAG, "Lock unexpectedly not called"); + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG + ESP_LOGW(TAG, "Lock unexpectedly not called for mp_mulmod"); + #endif } } @@ -2505,8 +2663,8 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) * * Z = X^Y mod M * - * ESP32, Section 24.3.2 https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf - * ESP32S3, Section 20.3.1, https://www.espressif.com/sites/default/files/documentation/esp32-s3_technical_reference_manual_en.pdf + * ESP32, Section 24.3.2 esp32_technical_reference_manual_en.pdf + * ESP32S3, Section 20.3.1, esp32-s3_technical_reference_manual_en.pdf * * The operation is based on Montgomery multiplication. Aside from the * arguments X, Y , and M, two additional ones are needed -r and M' @@ -2623,6 +2781,7 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #ifdef DEBUG_WOLFSSL esp_mp_exptmod_depth_counter--; #endif + return MP_HW_FALLBACK; /* If we can't lock HW, fall back to SW */ } } /* the only thing we expect is success or busy */ @@ -2700,6 +2859,25 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) } #elif defined(CONFIG_IDF_TARGET_ESP32C3) + OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_HW_METRICS + ESP_LOGW(TAG, "exptmod operand bits %d exceeds max bit length %d", + OperandBits, ESP_HW_MOD_RSAMAX_BITS); + esp_mp_mulmod_max_exceeded_ct++; + #endif + if (exptmod_lock_called) { + ret = esp_mp_hw_unlock(); + } + ESP_LOGV(TAG, "Return esp_mp_exptmod fallback"); + + /* HW not capable for this size, return error to fall back to SW: */ + return MP_HW_FALLBACK; + } + else { + WordsForOperand = bits2words(OperandBits); + } + /* Steps to perform large number modular exponentiation. * Calculates Z = (X ^ Y) modulo M. * The number of bits in the operands (X, Y) is N. N can be 32x, @@ -2725,17 +2903,6 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) ret = esp_mp_hw_wait_clean(); } - if (ret == MP_OKAY) { - OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "result exceeds max bit length"); - ret = MP_VAL; /* Error: value is not able to be used. */ - } - else { - WordsForOperand = bits2words(OperandBits); - } - } - if (ret == MP_OKAY) { /* 2. Disable completion interrupt signal; we don't use. ** 0 => no interrupt; 1 => interrupt on completion. */ @@ -2786,6 +2953,25 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) /* end if CONFIG_IDF_TARGET_ESP32C3 */ #elif defined(CONFIG_IDF_TARGET_ESP32C6) + OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_HW_METRICS + ESP_LOGW(TAG, "exptmod operand bits %d exceeds max bit length %d", + OperandBits, ESP_HW_MOD_RSAMAX_BITS); + esp_mp_mulmod_max_exceeded_ct++; + #endif + if (exptmod_lock_called) { + ret = esp_mp_hw_unlock(); + } + ESP_LOGV(TAG, "Return esp_mp_exptmod fallback"); + + /* HW not capable for this size, return error to fall back to SW: */ + return MP_HW_FALLBACK; + } + else { + WordsForOperand = bits2words(OperandBits); + } + /* Steps to perform large number modular exponentiation. * Calculates Z = (X ^ Y) modulo M. * The number of bits in the operands (X, Y) is N. N can be 32x, @@ -2811,17 +2997,6 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) ret = esp_mp_hw_wait_clean(); } - if (ret == MP_OKAY) { - OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "result exceeds max bit length"); - ret = MP_VAL; /* Error: value is not able to be used. */ - } - else { - WordsForOperand = bits2words(OperandBits); - } - } - if (ret == MP_OKAY) { /* 2. Disable completion interrupt signal; we don't use. ** 0 => no interrupt; 1 => interrupt on completion. */ @@ -2864,11 +3039,16 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) } /* 8. clear and release HW */ + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG + ESP_LOGI(TAG, "Unlock esp_mp_exptmod"); + #endif if (exptmod_lock_called) { ret = esp_mp_hw_unlock(); } else { + #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGV(TAG, "Lock not called"); + #endif } /* end if CONFIG_IDF_TARGET_ESP32C6 */ @@ -2900,9 +3080,12 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) if (ret == MP_OKAY) { OperandBits = max(max(mph->Xs, mph->Ys), mph->Ms); - if (OperandBits > ESP_HW_MULTI_RSAMAX_BITS) { - ESP_LOGW(TAG, "result exceeds max bit length"); - ret = MP_VAL; /* Error: value is not able to be used. */ + if (OperandBits > ESP_HW_MOD_RSAMAX_BITS) { + #ifdef WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS + ESP_LOGW(TAG, "exptmod operand bits %d exceeds max bit length %d", + OperandBits, ESP_HW_MOD_RSAMAX_BITS); + #endif + ret = MP_HW_FALLBACK; /* Error: value is not able to be used. */ } else { WordsForOperand = bits2words(OperandBits); @@ -2978,6 +3161,7 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #ifdef WOLFSSL_HW_METRICS esp_mp_max_used = (Z->used > esp_mp_max_used) ? Z->used : esp_mp_max_used; #endif + ESP_LOGV(TAG, "Return esp_mp_exptmod %d", ret); return ret; } /* esp_mp_exptmod */ @@ -2988,6 +3172,7 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #endif /* !NO_RSA || HAVE_ECC */ +/* Some optional metrics when using RSA HW Accleration */ #if defined(WOLFSSL_ESP32_CRYPT_RSA_PRI) && defined(WOLFSSL_HW_METRICS) int esp_hw_show_mp_metrics(void) { @@ -3004,6 +3189,10 @@ int esp_hw_show_mp_metrics(void) ESP_LOGI(TAG, "esp_mp_mul HW acceleration enabled."); ESP_LOGI(TAG, "Number of calls to esp_mp_mul: %lu", esp_mp_mul_usage_ct); + ESP_LOGI(TAG, "Number of calls to esp_mp_mul with tiny operands: %lu", + esp_mp_mul_tiny_ct); + ESP_LOGI(TAG, "Number of calls to esp_mp_mul HW operand exceeded: %lu", + esp_mp_mul_max_exceeded_ct); if (esp_mp_mul_error_ct == 0) { ESP_LOGI(TAG, "Success: no esp_mp_mul() errors."); } @@ -3025,6 +3214,8 @@ int esp_hw_show_mp_metrics(void) /* Metrics: esp_mp_mulmod() */ ESP_LOGI(TAG, "Number of calls to esp_mp_mulmod: %lu", esp_mp_mulmod_usage_ct); + ESP_LOGI(TAG, "Number of calls to esp_mp_mulmod HW operand exceeded: %lu", + esp_mp_mulmod_max_exceeded_ct); ESP_LOGI(TAG, "Number of fallback to SW mp_mulmod: %lu", esp_mp_mulmod_fallback_ct); @@ -3065,6 +3256,8 @@ int esp_hw_show_mp_metrics(void) ESP_LOGI(TAG, "Number of calls to esp_mp_exptmod: %lu", esp_mp_exptmod_usage_ct); + ESP_LOGI(TAG, "Number of calls to esp_mp_exptmod HW operand exceeded: %lu", + esp_mp_exptmod_max_exceeded_ct); ESP_LOGI(TAG, "Number of fallback to SW mp_exptmod: %lu", esp_mp_exptmod_fallback_ct); if (esp_mp_exptmod_error_ct == 0) { @@ -3078,7 +3271,10 @@ int esp_hw_show_mp_metrics(void) #endif /* EXPTMOD not disabled !NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD */ ESP_LOGI(TAG, "Max N->used: esp_mp_max_used = %lu", esp_mp_max_used); - ESP_LOGI(TAG, "Max timeout: esp_mp_max_timeout = %lu", esp_mp_max_timeout); + ESP_LOGI(TAG, "Max hw wait timeout: esp_mp_max_wait_timeout = %lu", + esp_mp_max_wait_timeout); + ESP_LOGI(TAG, "Max calc timeout: esp_mp_max_timeout = 0x%08lx", + esp_mp_max_timeout); #else /* no HW math, no HW math metrics */ diff --git a/src/wolfcrypt/src/port/Espressif/esp32_sha.c b/src/wolfcrypt/src/port/Espressif/esp32_sha.c index bef77b0..6fa955a 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -20,7 +20,7 @@ */ /* - * ESP32-C3: https://www.espressif.com/sites/default/files/documentation/esp32-c3_technical_reference_manual_en.pdf + * ESP32-C3: esp32-c3_technical_reference_manual_en.pdf * see page 335: no SHA-512 * */ @@ -135,7 +135,11 @@ static const char* TAG = "wolf_hw_sha"; #endif static uintptr_t mutex_ctx_owner = NULLPTR; + +#if (defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED)) \ + || defined(WOLFSSL_DEBUG_MUTEX) static portMUX_TYPE sha_crit_sect = portMUX_INITIALIZER_UNLOCKED; +#endif #if defined(ESP_MONITOR_HW_TASK_LOCK) #ifdef SINGLE_THREADED @@ -506,7 +510,7 @@ int esp_sha224_ctx_copy(struct wc_Sha256* src, struct wc_Sha256* dst) dst->ctx.initializer = (uintptr_t)&dst->ctx; #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) { - /* not HW mode for copy, so we are not interested in task owner: */ + /* Not HW mode for copy, so we are not interested in task owner: */ dst->ctx.task_owner = 0; } #endif @@ -985,8 +989,10 @@ int esp_sha_hw_in_use() */ uintptr_t esp_sha_hw_islocked(WC_ESP32SHA* ctx) { - TaskHandle_t mutexHolder; uintptr_t ret = 0; + #ifndef SINGLE_THREADED + TaskHandle_t mutexHolder; + #endif CTX_STACK_CHECK(ctx); #ifdef WOLFSSL_DEBUG_MUTEX @@ -1132,7 +1138,9 @@ uintptr_t esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) ESP_LOGW(TAG, "esp_sha_release_unfinished_lock mode = %d", ctx->mode); #endif if (ctx->mode == ESP32_SHA_HW) { +#if defined(DEBUG_WOLFSSL_ESP32_UNFINISHED_HW) ESP_LOGW(TAG, "esp_sha_release_unfinished_lock HW!"); +#endif } } return ret; @@ -2376,7 +2384,7 @@ int esp_hw_show_sha_metrics(void) int ret = 0; #if defined(WOLFSSL_ESP32_CRYPT) && !defined(NO_WOLFSSL_ESP32_CRYPT_HASH) ESP_LOGI(TAG, "--------------------------------------------------------"); - ESP_LOGI(TAG, "------------- wolfSSL ESP HW SHA Metrics----------------"); + ESP_LOGI(TAG, "------------- wolfSSL ESP HW SHA Metrics -------------"); ESP_LOGI(TAG, "--------------------------------------------------------"); ESP_LOGI(TAG, "esp_sha_hw_copy_ct = %lu", diff --git a/src/wolfcrypt/src/port/Espressif/esp32_util.c b/src/wolfcrypt/src/port/Espressif/esp32_util.c index 793554a..d5d77ed 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_util.c @@ -98,21 +98,44 @@ int esp_CryptHwMutexInit(wolfSSL_Mutex* mutex) { } /* - * call the ESP-IDF mutex lock; xSemaphoreTake + * Call the ESP-IDF mutex lock; xSemaphoreTake * this is a general mutex locker, used for different mutex objects for * different HW acclerators or other single-use HW features. + * + * We should already have known if the resource is in use or not. + * + * Return 0 (ESP_OK) on success, otherwise BAD_MUTEX_E */ int esp_CryptHwMutexLock(wolfSSL_Mutex* mutex, TickType_t block_time) { + int ret; if (mutex == NULL) { WOLFSSL_ERROR_MSG("esp_CryptHwMutexLock called with null mutex"); return BAD_MUTEX_E; } #ifdef SINGLE_THREADED - return wc_LockMutex(mutex); /* xSemaphoreTake take with portMAX_DELAY */ + /* does nothing in single thread mode, always return 0 */ + ret = wc_LockMutex(mutex); #else - return ((xSemaphoreTake(*mutex, block_time) == pdTRUE) ? 0 : BAD_MUTEX_E); + ret = xSemaphoreTake(*mutex, block_time); + ESP_LOGV(TAG, "xSemaphoreTake 0x%x = %d", (intptr_t)*mutex, ret); + if (ret == pdTRUE) { + ret = ESP_OK; + } + else { + if (ret == pdFALSE) { + ESP_LOGW(TAG, "xSemaphoreTake failed for 0x%x. Still busy?", + (intptr_t)*mutex); + ret = ESP_ERR_NOT_FINISHED; + } + else { + ESP_LOGE(TAG, "xSemaphoreTake 0x%x unexpected = %d", + (intptr_t)*mutex, ret); + ret = BAD_MUTEX_E; + } + } #endif + return ret; } /* @@ -120,17 +143,36 @@ int esp_CryptHwMutexLock(wolfSSL_Mutex* mutex, TickType_t block_time) { * */ esp_err_t esp_CryptHwMutexUnLock(wolfSSL_Mutex* mutex) { + int ret = pdTRUE; if (mutex == NULL) { WOLFSSL_ERROR_MSG("esp_CryptHwMutexLock called with null mutex"); return BAD_MUTEX_E; } #ifdef SINGLE_THREADED - return wc_UnLockMutex(mutex); + ret = wc_UnLockMutex(mutex); #else - xSemaphoreGive(*mutex); - return ESP_OK; + ESP_LOGV(TAG, ">> xSemaphoreGive 0x%x", (intptr_t)*mutex); + TaskHandle_t mutexHolder = xSemaphoreGetMutexHolder(*mutex); + + if (mutexHolder == NULL) { + ESP_LOGW(TAG, "esp_CryptHwMutexUnLock with no lock owner 0x%x", + (intptr_t)*mutex); + ret = ESP_OK; + } + else { + ret = xSemaphoreGive(*mutex); + if (ret == pdTRUE) { + ESP_LOGV(TAG, "Success: give mutex 0x%x", (intptr_t)*mutex); + ret = ESP_OK; + } + else { + ESP_LOGV(TAG, "Failed: give mutex 0x%x", (intptr_t)*mutex); + ret = ESP_FAIL; + } + } #endif + return ret; } #endif /* WOLFSSL_ESP32_CRYPT, etc. */ @@ -168,6 +210,7 @@ static int ShowExtendedSystemInfo_platform_espressif(void) WOLFSSL_VERSION_PRINTF("Xthal_have_ccount: %u", Xthal_have_ccount); +#endif /* this is the legacy stack size */ #if defined(CONFIG_MAIN_TASK_STACK_SIZE) @@ -205,24 +248,35 @@ static int ShowExtendedSystemInfo_platform_espressif(void) #endif -#elif CONFIG_IDF_TARGET_ESP32S2 - WOLFSSL_VERSION_PRINTF("Xthal_have_ccount = %u", +/* Platform-specific attributes of interest*/ +#if CONFIG_IDF_TARGET_ESP32 + #if defined(CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ) + WOLFSSL_VERSION_PRINTF("CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ: %u MHz", + CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ); + #endif + WOLFSSL_VERSION_PRINTF("Xthal_have_ccount: %u", Xthal_have_ccount); -#elif CONFIG_IDF_TARGET_ESP32C6 - /* TODO find Xthal for C6 */ + #elif CONFIG_IDF_TARGET_ESP32C2 - /* TODO find Xthal for C6 */ -#elif defined(CONFIG_IDF_TARGET_ESP8684) - /* TODO find Xthal for C6 */ + /* TODO find Xthal for C2 */ #elif CONFIG_IDF_TARGET_ESP32C3 /* not supported at this time */ -#elif CONFIG_IDF_TARGET_ESP32S3 - WOLFSSL_VERSION_PRINTF("Xthal_have_ccount = %u", - Xthal_have_ccount); +#elif CONFIG_IDF_TARGET_ESP32C6 + /* TODO find Xthal for C6 */ #elif CONFIG_IDF_TARGET_ESP32H2 - /* not supported at this time */ -#elif CONFIG_IDF_TARGET_ESP32C2 - /* not supported at this time */ + /* TODO find Xthal for H2 */ +#elif CONFIG_IDF_TARGET_ESP32S2 + ESP_LOGI(TAG, "CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ = %u MHz", + CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ + ); + ESP_LOGI(TAG, "Xthal_have_ccount = %u", Xthal_have_ccount); +#elif CONFIG_IDF_TARGET_ESP32S3 + ESP_LOGI(TAG, "CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ = %u MHz", + CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ + ); + ESP_LOGI(TAG, "Xthal_have_ccount = %u", Xthal_have_ccount); +#elif defined(CONFIG_IDF_TARGET_ESP8684) + /* TODO find Xthal for ESP8684 */ #else /* not supported at this time */ #endif @@ -438,6 +492,7 @@ esp_err_t ShowExtendedSystemInfo_config(void) { esp_ShowMacroStatus_need_header = 1; + show_macro("NO_ESP32_CRYPT", STR_IFNDEF(NO_ESP32_CRYPT)); show_macro("NO_ESPIDF_DEFAULT", STR_IFNDEF(NO_ESPIDF_DEFAULT)); show_macro("HW_MATH_ENABLED", STR_IFNDEF(HW_MATH_ENABLED)); @@ -562,11 +617,11 @@ int ShowExtendedSystemInfo(void) #if defined(WOLFSSL_MULTI_INSTALL_WARNING) /* CMake may have detected undesired multiple installs, so give warning. */ - WOLFSSL_VERSION_PRINTF(""); + WOLFSSL_VERSION_PRINTF(WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); WOLFSSL_VERSION_PRINTF("WARNING: Multiple wolfSSL installs found."); WOLFSSL_VERSION_PRINTF("Check ESP-IDF components and " "local project [components] directory."); - WOLFSSL_VERSION_PRINTF(""); + WOLFSSL_VERSION_PRINTF(WOLFSSL_ESPIDF_BLANKLINE_MESSAGE); #else #ifdef WOLFSSL_USER_SETTINGS_DIR { @@ -737,14 +792,11 @@ esp_err_t esp_EnabledWatchdog(void) ESP_IDF_VERSION_MAJOR); #endif #endif - -#ifdef DEBUG_WOLFSSL - ESP_LOGI(TAG, "Watchdog enabled."); -#endif - return ret; } + + /* Print a MATH_INT_T attribute list. * * Note with the right string parameters, the result can be pasted as @@ -904,4 +956,49 @@ esp_err_t esp_hw_show_metrics(void) return ESP_OK; } +int show_binary(byte* theVar, size_t dataSz) { + printf("*****************************************************\n"); + word32 i; + for (i = 0; i < dataSz; i++) + printf("%02X", theVar[i]); + printf("\n"); + printf("******************************************************\n"); + return 0; +} + +int hexToBinary(byte* toVar, const char* fromHexString, size_t szHexString ) { + int ret = 0; + /* Calculate the actual binary length of the hex string */ + size_t byteLen = szHexString / 2; + + if (toVar == NULL || fromHexString == NULL) { + ESP_LOGE("ssh", " error"); + return -1; + } + if ((szHexString % 2 != 0)) { + ESP_LOGE("ssh", "fromHexString length not even!"); + } + + ESP_LOGW(TAG, "Replacing %d bytes at %x", byteLen, (word32)toVar); + memset(toVar, 0, byteLen); + /* Iterate through the hex string and convert to binary */ + for (size_t i = 0; i < szHexString; i += 2) { + /* Convert hex character to decimal */ + int decimalValue; + sscanf(&fromHexString[i], "%2x", &decimalValue); + size_t index = i / 2; +#if (0) + /* Optionall peek at new values */ + byte new_val = (decimalValue & 0x0F) << ((i % 2) * 4); + ESP_LOGI("hex", "Current char = %d", toVar[index]); + ESP_LOGI("hex", "New val = %d", decimalValue); +#endif + toVar[index] = decimalValue; + } + + return ret; +} + + + #endif /* WOLFSSL_ESPIDF */ diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c index 8c5cd37..81d88a6 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c @@ -25,10 +25,10 @@ /* wolfSSL */ /* Always include wolfcrypt/settings.h before any other wolfSSL file. */ -/* Reminder: settings.h pulls in user_settings.h; don't include it here. */ -#ifdef WOLFSSL_USER_SETTINGS - #include -#endif +/* Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +/* Reminder: settings.h pulls in user_settings.h */ +/* Do not explicitly include user_settings.h here. */ +#include #if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ @@ -71,8 +71,6 @@ extern wc_ptr_t _rodata_start[]; extern wc_ptr_t _rodata_end[]; extern wc_ptr_t _bss_start[]; extern wc_ptr_t _bss_end[]; -extern wc_ptr_t _rtc_data_start[]; -extern wc_ptr_t _rtc_data_end[]; extern wc_ptr_t _rtc_bss_start[]; extern wc_ptr_t _rtc_bss_end[]; extern wc_ptr_t _iram_start[]; @@ -83,18 +81,29 @@ extern wc_ptr_t _init_end[]; #endif extern wc_ptr_t _iram_text_start[]; extern wc_ptr_t _iram_text_end[]; -extern wc_ptr_t _iram_bss_start[]; -extern wc_ptr_t _iram_bss_end[]; +#if defined(CONFIG_IDF_TARGET_ESP32S2) + /* TODO: Find ESP32-S2 equivalent */ +#else + extern wc_ptr_t _iram_bss_start[]; + extern wc_ptr_t _iram_bss_end[]; +#endif extern wc_ptr_t _noinit_start[]; extern wc_ptr_t _noinit_end[]; extern wc_ptr_t _text_start[]; extern wc_ptr_t _text_end[]; extern wc_ptr_t _heap_start[]; extern wc_ptr_t _heap_end[]; -extern wc_ptr_t _rtc_data_start[]; -extern wc_ptr_t _rtc_data_end[]; -extern void* _thread_local_start; -extern void* _thread_local_end; +#ifdef CONFIG_IDF_TARGET_ESP32C2 + /* no rtc_data on ESP32-C2*/ +#else + extern wc_ptr_t _rtc_data_start[]; + extern wc_ptr_t _rtc_data_end[]; +#endif + +#if defined(CONFIG_IDF_TARGET_ARCH_XTENSA) && CONFIG_IDF_TARGET_ARCH_XTENSA == 1 + extern void* _thread_local_start; + extern void* _thread_local_end; +#endif /* See https://github.com/esp8266/esp8266-wiki/wiki/Memory-Map */ #define MEM_MAP_IO_START ((void*)(0x3FF00000)) @@ -161,7 +170,7 @@ static const char* sdk_memory_segment_text[SDK_MEMORY_SEGMENT_COUNT + 1] = { int sdk_log_meminfo(enum sdk_memory_segment m, void* start, void* end) { const char* str; - int len = 0; + word32 len = 0; str = sdk_memory_segment_text[m]; sdk_memory_segment_start[m] = start; sdk_memory_segment_end[m] = end; @@ -173,7 +182,7 @@ int sdk_log_meminfo(enum sdk_memory_segment m, void* start, void* end) ESP_LOGI(TAG, " Start End Length"); } else { - len = (uint32_t)end - (uint32_t)start; + len = (word32)end - (word32)start; ESP_LOGI(TAG, "%s: %p ~ %p : 0x%05x (%d)", str, start, end, len, len ); } return ESP_OK; @@ -186,10 +195,16 @@ int sdk_init_meminfo(void) { sdk_log_meminfo(SDK_MEMORY_SEGMENT_COUNT, NULL, NULL); /* print header */ sdk_log_meminfo(mem_map_io, MEM_MAP_IO_START, MEM_MAP_IO_END); +#if defined(CONFIG_IDF_TARGET_ARCH_XTENSA) && CONFIG_IDF_TARGET_ARCH_XTENSA == 1 sdk_log_meminfo(thread_local, _thread_local_start, _thread_local_end); +#endif sdk_log_meminfo(data, _data_start, _data_end); sdk_log_meminfo(user_data_ram, USER_DATA_START, USER_DATA_END); +#if defined(CONFIG_IDF_TARGET_ESP32S2) + /* TODO: Find ESP32-S2 equivalent of bss */ +#else sdk_log_meminfo(bss, _bss_start, _bss_end); +#endif sdk_log_meminfo(noinit, _noinit_start, _noinit_end); sdk_log_meminfo(ets_system, ETS_SYS_START, ETS_SYS_END); sdk_log_meminfo(rodata, _rodata_start, _rodata_end); @@ -198,12 +213,20 @@ int sdk_init_meminfo(void) { sdk_log_meminfo(iramf2, IRAMF2_START, IRAMF2_END); sdk_log_meminfo(iram, _iram_start, _iram_end); sdk_log_meminfo(iram_text, _iram_text_start, _iram_text_end); +#if defined(CONFIG_IDF_TARGET_ESP32S2) + /* No iram_bss on ESP32-C2 at this time. TODO: something equivalent? */ +#else sdk_log_meminfo(iram_bss, _iram_bss_start, _iram_bss_end); +#endif #if defined(CONFIG_IDF_TARGET_ESP8266) sdk_log_meminfo(init, _init_start, _init_end); #endif sdk_log_meminfo(text, _text_start, _text_end); +#if defined(CONFIG_IDF_TARGET_ESP32C2) + /* No rtc_data on ESP32-C2 at this time. TODO: something equivalent? */ +#else sdk_log_meminfo(rtc_data, _rtc_data_start, _rtc_data_end); +#endif ESP_LOGI(TAG, "-----------------------------------------------------"); sample_heap_var = malloc(1); if (sample_heap_var == NULL) { diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c index 1ef8de4..678de3b 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c @@ -23,14 +23,17 @@ #include #endif -/* Reminder: user_settings.h is needed and included from settings.h - * Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +/* wolfSSL */ +/* Always include wolfcrypt/settings.h before any other wolfSSL file. */ +/* Reminder: settings.h pulls in user_settings.h */ +/* Do not explicitly include user_settings.h here. */ #include -#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF. */ +#include "sdkconfig.h" /* programmatically generated from sdkconfig. */ + #if defined(USE_WOLFSSL_ESP_SDK_TIME) /* Espressif */ -#include "sdkconfig.h" /* programmatically generated from sdkconfig */ #include #include @@ -71,10 +74,10 @@ esp_err_t esp_sdk_time_lib_init(void) /* ESP-IDF uses a 64-bit signed integer to represent time_t * starting from release v5.0 - * See: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#year-2036-and-2038-overflow-issues + * See: Espressif api-reference system_time (year-2036-and-2038-overflow-issues) */ -/* see https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html */ +/* see gnu TZ-Variable */ #ifndef TIME_ZONE /* * PST represents Pacific Standard Time. @@ -116,6 +119,41 @@ esp_err_t esp_sdk_time_lib_init(void) #define CONFIG_LWIP_SNTP_MAX_SERVERS NTP_SERVER_COUNT #endif +/* When reproducible builds are enabled in ESP-IDF + * (starting from version 4.0 and above), + * the __DATE__ and __TIME__ macros are deliberately disabled. */ +#ifndef __DATE__ + #define YEAR 2024 + #define MONTH 9 + #define DAY 25 +#else + /* e.g. __DATE__ "Sep 25 2024" */ + #define YEAR ( \ + ((__DATE__)[7] - '0') * 1000 + \ + ((__DATE__)[8] - '0') * 100 + \ + ((__DATE__)[9] - '0') * 10 + \ + ((__DATE__)[10] - '0') * 1 \ + ) + + #define MONTH ( \ + __DATE__[2] == 'n' ? (__DATE__[1] == 'a' ? 1 : 6) \ + : __DATE__[2] == 'b' ? 2 \ + : __DATE__[2] == 'r' ? (__DATE__[0] == 'M' ? 3 : 4) \ + : __DATE__[2] == 'y' ? 5 \ + : __DATE__[2] == 'l' ? 7 \ + : __DATE__[2] == 'g' ? 8 \ + : __DATE__[2] == 'p' ? 9 \ + : __DATE__[2] == 't' ? 10 \ + : __DATE__[2] == 'v' ? 11 \ + : 12 \ + ) + + #define DAY ( \ + ((__DATE__)[4] - '0') * 10 + \ + ((__DATE__)[5] - '0') * 1 \ + ) +#endif + /* our NTP server list is global info */ extern char* ntpServerList[NTP_SERVER_COUNT]; @@ -144,12 +182,12 @@ int set_fixed_default_time(void) /* ideally, we'd like to set time from network, * but let's set a default time, just in case */ struct tm timeinfo = { - .tm_year = 2024 - 1900, - .tm_mon = 1, - .tm_mday = 05, + .tm_year = YEAR, + .tm_mon = MONTH, /* Month, where 0 = Jan */ + .tm_mday = DAY, /* Numeric decimal day of the month */ .tm_hour = 13, - .tm_min = 01, - .tm_sec = 05 + .tm_min = 1, + .tm_sec = 5 }; struct timeval now; time_t interim_time; @@ -341,7 +379,7 @@ int set_time(void) if (NTP_SERVER_COUNT) { /* next, let's setup NTP time servers * - * see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#sntp-time-synchronization + * see Espressif api-reference system_time (sntp-time-synchronization) * * WARNING: do not set operating mode while SNTP client is running! */ diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c index 06c9f81..9a200a9 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c @@ -23,12 +23,15 @@ #include #endif -/* Reminder: user_settings.h is needed and included from settings.h - * Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +/* wolfSSL */ +/* Always include wolfcrypt/settings.h before any other wolfSSL file. */ +/* Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +/* Reminder: settings.h pulls in user_settings.h */ +/* Do not explicitly include user_settings.h here. */ #include #if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ -#if defined(USE_WOLFSSL_ESP_SDK_WIFI) +#if defined(USE_WOLFSSL_ESP_SDK_WIFI) && ESP_IDF_VERSION_MAJOR > 4 /* Espressif */ #include "sdkconfig.h" /* programmatically generated from sdkconfig */ @@ -59,8 +62,8 @@ esp_err_t esp_sdk_wifi_lib_init(void) #if defined(CONFIG_IDF_TARGET_ESP8266) #elif ESP_IDF_VERSION_MAJOR >= 5 && defined(FOUND_PROTOCOL_EXAMPLES_DIR) /* example path set in cmake file */ -#elif ESP_IDF_VERSION_MAJOR >= 4 - #include "protocol_examples_common.h" +#elif ESP_IDF_VERSION_MAJOR > 4 +/* #include "protocol_examples_common.h" */ #else const static int CONNECTED_BIT = BIT0; static EventGroupHandle_t wifi_event_group; @@ -266,7 +269,7 @@ static esp_err_t wifi_event_handler(void *ctx, system_event_t *event) ESP_LOGI(TAG, "got ip:%s", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); #endif - /* see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/freertos_idf.html */ + /* see Espressif api-reference freertos_idf */ xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); break; case SYSTEM_EVENT_STA_DISCONNECTED: diff --git a/src/wolfcrypt/src/port/atmel/atmel.c b/src/wolfcrypt/src/port/atmel/atmel.c index b3c6b79..31ad98f 100644 --- a/src/wolfcrypt/src/port/atmel/atmel.c +++ b/src/wolfcrypt/src/port/atmel/atmel.c @@ -1,6 +1,6 @@ /* atmel.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/pwdbased.c b/src/wolfcrypt/src/pwdbased.c index 1aef716..fb06dce 100644 --- a/src/wolfcrypt/src/pwdbased.c +++ b/src/wolfcrypt/src/pwdbased.c @@ -1,6 +1,6 @@ /* pwdbased.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -218,7 +218,7 @@ int wc_PBKDF2_ex(byte* output, const byte* passwd, int pLen, const byte* salt, * length", ensure the returned bits for the derived master key are at a * minimum 14-bytes or 112-bits after stretching and strengthening * (iterations) */ - if (kLen < HMAC_FIPS_MIN_KEY/8) + if (kLen < HMAC_FIPS_MIN_KEY) return BAD_LENGTH_E; #endif @@ -588,16 +588,11 @@ int wc_PKCS12_PBKDF_ex(byte* output, const byte* passwd, int passLen, #ifdef WOLFSSL_SMALL_STACK out: - if (Ai != NULL) - XFREE(Ai, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (B != NULL) - XFREE(B, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (B1 != NULL) - XFREE(B1, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (i1 != NULL) - XFREE(i1, heap, DYNAMIC_TYPE_TMP_BUFFER); - if (res != NULL) - XFREE(res, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(Ai, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(B, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(B1, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(i1, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(res, heap, DYNAMIC_TYPE_TMP_BUFFER); #endif if (dynamic) @@ -859,12 +854,9 @@ int wc_scrypt(byte* output, const byte* passwd, int passLen, ret = wc_PBKDF2(output, passwd, passLen, blocks, (int)blocksSz, 1, dkLen, WC_SHA256); end: - if (blocks != NULL) - XFREE(blocks, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (v != NULL) - XFREE(v, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (y != NULL) - XFREE(y, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(blocks, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(v, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(y, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; } diff --git a/src/wolfcrypt/src/random.c b/src/wolfcrypt/src/random.c index 89c7411..278e2d7 100644 --- a/src/wolfcrypt/src/random.c +++ b/src/wolfcrypt/src/random.c @@ -1,6 +1,6 @@ /* random.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -110,7 +110,7 @@ This library contains implementation for the random number generator. #include #include #elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) -#include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h" + #include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h" #elif defined(NO_DEV_RANDOM) #elif defined(CUSTOM_RAND_GENERATE) #elif defined(CUSTOM_RAND_GENERATE_BLOCK) @@ -126,6 +126,9 @@ This library contains implementation for the random number generator. #elif defined(WOLFSSL_PB) #elif defined(WOLFSSL_ZEPHYR) #elif defined(WOLFSSL_TELIT_M2MB) +#elif defined(WOLFSSL_RENESAS_TSIP) + /* for wc_tsip_GenerateRandBlock */ + #include "wolfssl/wolfcrypt/port/Renesas/renesas-tsip-crypt.h" #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG) #elif defined(WOLFSSL_IMXRT1170_CAAM) #elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) @@ -133,6 +136,8 @@ This library contains implementation for the random number generator. #elif defined(WOLFSSL_GETRANDOM) #include #include +#elif defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include "wolfssl/wolfcrypt/port/maxim/max3266x.h" #else /* include headers that may be needed to get good seed */ #include @@ -591,7 +596,7 @@ static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen dIdx = (int)dLen - 1; for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) { - carry += (word16)(d[dIdx] + s[sIdx]); + carry += (word16)((word16)d[dIdx] + (word16)s[sIdx]); d[dIdx] = (byte)carry; carry >>= 8; dIdx--; @@ -3652,6 +3657,14 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return 0; } +#elif defined(WOLFSSL_RENESAS_TSIP) + + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + (void)os; + return wc_tsip_GenerateRandBlock(output, sz); + } + #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG) #include "hal_data.h" @@ -3804,7 +3817,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return ret; } -#elif defined(DOLPHIN_EMULATOR) +#elif defined(DOLPHIN_EMULATOR) || defined (WOLFSSL_NDS) int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { @@ -3823,6 +3836,38 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return maxq10xx_random(output, sz); } +#elif defined(MAX3266X_RNG) + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + #ifdef WOLFSSL_MAX3266X + int status; + #endif /* WOLFSSL_MAX3266X */ + static int initDone = 0; + (void)os; + if (initDone == 0) { + #ifdef WOLFSSL_MAX3266X + status = wolfSSL_HwRngMutexLock(); + if (status != 0) { + return status; + } + #endif /* WOLFSSL_MAX3266X */ + if(MXC_TRNG_HealthTest() != 0) { + #ifdef DEBUG_WOLFSSL + WOLFSSL_MSG("TRNG HW Health Test Failed"); + #endif /* DEBUG_WOLFSSL */ + #ifdef WOLFSSL_MAX3266X + wolfSSL_HwRngMutexUnLock(); + #endif /* WOLFSSL_MAX3266X */ + return WC_HW_E; + } + #ifdef WOLFSSL_MAX3266X + wolfSSL_HwRngMutexUnLock(); + #endif /* WOLFSSL_MAX3266X */ + initDone = 1; + } + return wc_MXC_TRNG_Random(output, sz); + } + #elif defined(WOLFSSL_GETRANDOM) /* getrandom() was added to the Linux kernel in version 3.17. @@ -4044,7 +4089,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { word32 i; for (i = 0; i < sz; i++ ) - output[i] = i; + output[i] = (byte)i; (void)os; diff --git a/src/wolfcrypt/src/rc2.c b/src/wolfcrypt/src/rc2.c index 3839d49..67dc7d6 100644 --- a/src/wolfcrypt/src/rc2.c +++ b/src/wolfcrypt/src/rc2.c @@ -1,6 +1,6 @@ /* rc2.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/ripemd.c b/src/wolfcrypt/src/ripemd.c index 9402c70..36cca1b 100644 --- a/src/wolfcrypt/src/ripemd.c +++ b/src/wolfcrypt/src/ripemd.c @@ -1,6 +1,6 @@ /* ripemd.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/rsa.c b/src/wolfcrypt/src/rsa.c index 587e47c..9e34599 100644 --- a/src/wolfcrypt/src/rsa.c +++ b/src/wolfcrypt/src/rsa.c @@ -1,6 +1,6 @@ /* rsa.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -154,9 +154,43 @@ static void wc_RsaCleanup(RsaKey* key) #endif } +#ifndef WC_NO_CONSTRUCTORS +RsaKey* wc_NewRsaKey(void* heap, int devId, int *result_code) +{ + int ret; + RsaKey* key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA); + if (key == NULL) { + ret = MEMORY_E; + } + else { + ret = wc_InitRsaKey_ex(key, heap, devId); + if (ret != 0) { + XFREE(key, heap, DYNAMIC_TYPE_RSA); + key = NULL; + } + } + + if (result_code != NULL) + *result_code = ret; + + return key; +} + +int wc_DeleteRsaKey(RsaKey* key, RsaKey** key_p) +{ + if (key == NULL) + return BAD_FUNC_ARG; + wc_FreeRsaKey(key); + XFREE(key, key->heap, DYNAMIC_TYPE_RSA); + if (key_p != NULL) + *key_p = NULL; + return 0; +} +#endif /* !WC_NO_CONSTRUCTORS */ + int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) { - int ret = 0; + int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; @@ -373,9 +407,7 @@ int wc_InitRsaHw(RsaKey* key) } /* check for existing mod buffer to avoid memory leak */ - if (key->mod != NULL) { - XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); - } + XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); key->pubExp = e; key->mod = m; @@ -2144,9 +2176,7 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, #endif } - if (d != NULL) { - XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); - } + XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); } #endif break; @@ -2396,7 +2426,10 @@ static int RsaFunction_SP(const byte* in, word32 inLen, byte* out, #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1024) && - (mp_count_bits(&key->q) == 1024)) { + (mp_count_bits(&key->q) == 1024) && + (mp_count_bits(&key->dP) > 0) && + (mp_count_bits(&key->dQ) > 0) && + (mp_count_bits(&key->u) > 0)) { return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); @@ -2427,7 +2460,10 @@ static int RsaFunction_SP(const byte* in, word32 inLen, byte* out, #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1536) && - (mp_count_bits(&key->q) == 1536)) { + (mp_count_bits(&key->q) == 1536) && + (mp_count_bits(&key->dP) > 0) && + (mp_count_bits(&key->dQ) > 0) && + (mp_count_bits(&key->u) > 0)) { return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); @@ -2458,7 +2494,10 @@ static int RsaFunction_SP(const byte* in, word32 inLen, byte* out, #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 2048) && - (mp_count_bits(&key->q) == 2048)) { + (mp_count_bits(&key->q) == 2048) && + (mp_count_bits(&key->dP) > 0) && + (mp_count_bits(&key->dQ) > 0) && + (mp_count_bits(&key->u) > 0)) { return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); @@ -2555,7 +2594,13 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng) } } #else - if (ret == 0) { + if (ret == 0 && (mp_iszero(&key->p) || mp_iszero(&key->q) || + mp_iszero(&key->dP) || mp_iszero(&key->dQ))) { + if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) { + ret = MP_EXPTMOD_E; + } + } + else if (ret == 0) { mp_int* tmpa = tmp; #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) mp_int* tmpb = rnd; @@ -2915,7 +2960,7 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, if (out == NULL) { *outSz = inLen; - return LENGTH_ONLY_E; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } switch (key->state) { @@ -2952,7 +2997,7 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, } /* if async pending then skip cleanup*/ - if (ret == WC_PENDING_E + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif @@ -3116,6 +3161,9 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, int ret = 0; (void)rng; (void)checkSmallCt; +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) + RsaPadding padding; +#endif if (key == NULL || in == NULL || inLen == 0 || out == NULL || outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) { @@ -3127,7 +3175,18 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) #endif { + #if defined(WOLF_CRYPTO_CB_RSA_PAD) + /* If we are here, either the RSA PAD callback was already called + * and returned that it could not implement for that padding scheme, + * or this is a public verify operation. Either way indicate to the + * callback that this should be a raw RSA operation with no padding.*/ + XMEMSET(&padding, 0, sizeof(RsaPadding)); + padding.pad_type = WC_RSA_NO_PAD; + ret = wc_CryptoCb_RsaPad(in, inLen, out, + outLen, type, key, rng, &padding); + #else ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); + #endif #ifndef WOLF_CRYPTO_CB_ONLY_RSA if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; @@ -3181,7 +3240,7 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, RESTORE_VECTOR_REGISTERS(); /* handle error */ - if (ret < 0 && ret != WC_PENDING_E + if (ret < 0 && ret != WC_NO_ERR_TRACE(WC_PENDING_E) #ifdef WC_RSA_NONBLOCK && ret != FP_WOULDBLOCK #endif @@ -3235,6 +3294,9 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, int ret = 0; int sz; int state; +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) + RsaPadding padding; +#endif if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; @@ -3331,6 +3393,29 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, #endif #endif /* WOLFSSL_SE050 */ + #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) + if (key->devId != INVALID_DEVID) { + XMEMSET(&padding, 0, sizeof(RsaPadding)); + padding.pad_value = pad_value; + padding.pad_type = pad_type; + padding.hash = hash; + padding.mgf = mgf; + padding.label = label; + padding.labelSz = labelSz; + padding.saltLen = saltLen; + ret = wc_CryptoCb_RsaPad(in, inLen, out, &outLen, rsa_type, key, rng, + &padding); + + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + if (ret < 0) { + break; + } + + ret = outLen; + break; + } + } + #endif key->state = RSA_STATE_ENCRYPT_PAD; ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type, hash, mgf, label, labelSz, saltLen, @@ -3367,7 +3452,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, } /* if async pending then return and skip done cleanup below */ - if (ret == WC_PENDING_E + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif @@ -3410,6 +3495,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, { int ret = WC_NO_ERR_TRACE(RSA_WRONG_TYPE_E); byte* pad = NULL; +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) + RsaPadding padding; +#endif if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; @@ -3520,6 +3608,25 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, FALL_THROUGH; case RSA_STATE_DECRYPT_EXPTMOD: +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) + if ((key->devId != INVALID_DEVID) && (rsa_type != RSA_PUBLIC_DECRYPT)) { + /* Everything except verify goes to crypto cb if + * WOLF_CRYPTO_CB_RSA_PAD defined */ + XMEMSET(&padding, 0, sizeof(RsaPadding)); + padding.pad_value = pad_value; + padding.pad_type = pad_type; + padding.hash = hash; + padding.mgf = mgf; + padding.label = label; + padding.labelSz = labelSz; + padding.saltLen = saltLen; + ret = wc_CryptoCb_RsaPad(in, inLen, out, + &outLen, rsa_type, key, rng, &padding); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + break; + } + } +#endif #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ !defined(WOLFSSL_NO_MALLOC) ret = wc_RsaFunction_ex(key->data, inLen, key->data, &key->dataLen, @@ -3583,9 +3690,11 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, } #if !defined(WOLFSSL_RSA_VERIFY_ONLY) - ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, RSA_BUFFER_E); + ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN - ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E); + ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); #endif #else if (outLen < (word32)ret) @@ -3620,7 +3729,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, } /* if async pending then return and skip done cleanup below */ - if (ret == WC_PENDING_E + if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif @@ -5085,16 +5194,13 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #if !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SE050) #ifdef WOLFSSL_SMALL_STACK - if (p) + if (key != NULL) { XFREE(p, key->heap, DYNAMIC_TYPE_RSA); - if (q) XFREE(q, key->heap, DYNAMIC_TYPE_RSA); - if (tmp1) XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA); - if (tmp2) XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA); - if (tmp3) XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA); + } #elif defined(WOLFSSL_CHECK_MEM_ZERO) mp_memzero_check(p); mp_memzero_check(q); @@ -5250,7 +5356,7 @@ int wc_RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz, if (err == MP_OKAY) { key->type = RSA_PRIVATE; } - else { + else if (key != NULL) { mp_clear(&key->n); mp_clear(&key->e); mp_clear(&key->d); diff --git a/src/wolfcrypt/src/sakke.c b/src/wolfcrypt/src/sakke.c index c87963a..962299f 100644 --- a/src/wolfcrypt/src/sakke.c +++ b/src/wolfcrypt/src/sakke.c @@ -1,6 +1,6 @@ /* sakke.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -622,7 +622,7 @@ int wc_ExportSakkeKey(SakkeKey* key, byte* data, word32* sz) if ((err == 0) && (data == NULL)) { *sz = (word32)(3 * key->ecc.dp->size); - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err >= 0) && (*sz < (word32)(3 * key->ecc.dp->size))) { err = BUFFER_E; @@ -731,7 +731,7 @@ int wc_ExportSakkePrivateKey(SakkeKey* key, byte* data, word32* sz) if ((err == 0) && (data == NULL)) { *sz = (word32)key->ecc.dp->size; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err >= 0) && (*sz < (word32)key->ecc.dp->size)) { err = BUFFER_E; @@ -848,7 +848,7 @@ static int sakke_encode_point(ecc_point* point, word32 size, byte* data, if (data == NULL) { *sz = size * 2 + !raw; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*sz < size * 2 + !raw)) { err = BUFFER_E; @@ -1419,7 +1419,7 @@ int wc_GenerateSakkeRskTable(const SakkeKey* key, const ecc_point* rsk, } if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -6421,7 +6421,7 @@ int wc_GetSakkePointI(SakkeKey* key, byte* data, word32* sz) if ((err == 0) && (data == NULL)) { *sz = (word32)(key->ecc.dp->size * 2); - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*sz < (word32)key->ecc.dp->size * 2)) { err = BUFFER_E; @@ -6531,7 +6531,7 @@ int wc_GenerateSakkePointITable(SakkeKey* key, byte* table, word32* len) #else if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { *len = 0; @@ -6729,7 +6729,7 @@ int wc_MakeSakkeEncapsulatedSSV(SakkeKey* key, enum wc_HashType hashType, *authSz = outSz; if (auth == NULL) { - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } } @@ -6824,7 +6824,7 @@ int wc_GenerateSakkeSSV(SakkeKey* key, WC_RNG* rng, byte* ssv, word16* ssvSz) /* Return length only if an output buffer is NULL. */ if (ssv == NULL) { *ssvSz = (word16) (n / 8); - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else { n = *ssvSz; diff --git a/src/wolfcrypt/src/sha.c b/src/wolfcrypt/src/sha.c index 1892de4..78ce918 100644 --- a/src/wolfcrypt/src/sha.c +++ b/src/wolfcrypt/src/sha.c @@ -1,6 +1,6 @@ /* sha.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -308,6 +308,10 @@ !defined(WOLFSSL_QNX_CAAM) /* wolfcrypt/src/port/caam/caam_sha.c */ +#elif defined(MAX3266X_SHA) + /* Already brought in by sha.h */ + /* #include */ + #elif defined(WOLFSSL_USE_ESP32_CRYPT_HASH_HW) || \ defined(WOLFSSL_USE_ESP32C3_CRYPT_HASH_HW) @@ -441,7 +445,7 @@ static WC_INLINE void AddLength(wc_Sha* sha, word32 len) #define f3(x,y,z) (((x)&(y))|((z)&((x)|(y)))) #define f4(x,y,z) ((x)^(y)^(z)) - #ifdef WOLFSSL_NUCLEUS_1_2 + #if defined(WOLFSSL_NUCLEUS_1_2) || defined(NUCLEUS_PLUS_2_3) /* nucleus.h also defines R1-R4 */ #undef R1 #undef R2 @@ -560,6 +564,13 @@ int wc_InitSha_ex(wc_Sha* sha, void* heap, int devId) sha->devCtx = NULL; #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Init(&(sha->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + #ifdef WOLFSSL_USE_ESP32_CRYPT_HASH_HW if (sha->ctx.mode != ESP32_SHA_INIT) { /* it may be interesting to see old values during debugging */ @@ -1035,6 +1046,8 @@ int wc_InitSha(wc_Sha* sha) #if !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) +#ifndef MAX3266X_SHA + void wc_ShaFree(wc_Sha* sha) { if (sha == NULL) @@ -1051,6 +1064,9 @@ void wc_ShaFree(wc_Sha* sha) #ifdef WOLFSSL_PIC32MZ_HASH wc_ShaPic32Free(sha); #endif +#ifdef MAX3266X_SHA_CB + wc_MXC_TPU_SHA_Free(&(sha->mxcCtx)); +#endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) se050_hash_free(&sha->se050Ctx); #endif @@ -1058,16 +1074,15 @@ void wc_ShaFree(wc_Sha* sha) defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)) && \ !defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH) || \ defined(WOLFSSL_RENESAS_RX64_HASH) - if (sha->msg != NULL) { - XFREE(sha->msg, sha->heap, DYNAMIC_TYPE_TMP_BUFFER); - sha->msg = NULL; - } + XFREE(sha->msg, sha->heap, DYNAMIC_TYPE_TMP_BUFFER); + sha->msg = NULL; #endif #ifdef WOLFSSL_IMXRT_DCP DCPShaFree(sha); #endif } +#endif /* !MAX3266X_SHA */ #endif /* !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) */ #endif /* !WOLFSSL_TI_HASH */ @@ -1082,6 +1097,8 @@ void wc_ShaFree(wc_Sha* sha) #if !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) +#ifndef MAX3266X_SHA + /* wc_ShaGetHash get hash value */ int wc_ShaGetHash(wc_Sha* sha, byte* hash) { @@ -1146,12 +1163,20 @@ int wc_ShaCopy(wc_Sha* src, wc_Sha* dst) esp_sha_ctx_copy(src, dst); #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Copy(&(src->mxcCtx), &(dst->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + #ifdef WOLFSSL_HASH_FLAGS dst->flags |= WC_HASH_FLAG_ISCOPY; #endif return ret; } #endif /* WOLFSSL_RENESAS_RX64_HASH */ +#endif /* !MAX3266X_SHA */ #endif /* !defined(WOLFSSL_HAVE_PSA) || defined(WOLFSSL_PSA_NO_HASH) */ #endif /* !defined(WOLFSSL_RENESAS_TSIP_TLS) && \ !defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY) || diff --git a/src/wolfcrypt/src/sha256.c b/src/wolfcrypt/src/sha256.c index f955dff..c9c3b10 100644 --- a/src/wolfcrypt/src/sha256.c +++ b/src/wolfcrypt/src/sha256.c @@ -1,6 +1,6 @@ /* sha256.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -63,8 +63,8 @@ on the specific device platform. #endif -#if !defined(NO_SHA256) && (!defined(WOLFSSL_ARMASM) && \ - !defined(WOLFSSL_ARMASM_NO_NEON)) +#if !defined(NO_SHA256) && !(defined(WOLFSSL_ARMASM) || \ + defined(WOLFSSL_ARMASM_NO_NEON)) && !defined(WOLFSSL_RISCV_ASM) #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ @@ -122,7 +122,9 @@ on the specific device platform. #elif defined(WOLFSSL_PSOC6_CRYPTO) - +#elif defined(MAX3266X_SHA) + /* Already brought in by sha256.h */ + /* #include */ #else #include @@ -277,10 +279,6 @@ static int InitSha256(wc_Sha256* sha256) #endif #endif -#ifdef WOLF_CRYPTO_CB - sha256->devId = wc_CryptoCb_DefaultDevID(); -#endif - #ifdef WOLFSSL_MAXQ10XX_CRYPTO XMEMSET(&sha256->maxq_ctx, 0, sizeof(sha256->maxq_ctx)); #endif @@ -408,6 +406,10 @@ static int InitSha256(wc_Sha256* sha256) SHA256_SSE2, SHA256_C }; #ifndef WC_C_DYNAMIC_FALLBACK + /* note that all write access to this static variable must be idempotent, + * as arranged by Sha256_SetTransform(), else it will be susceptible to + * data races. + */ static enum sha_methods sha_method = SHA256_UNSET; #endif @@ -1090,6 +1092,12 @@ static int InitSha256(wc_Sha256* sha256) sha256->devId = devId; sha256->devCtx = NULL; #endif + #ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Init(&(sha256->mxcCtx)); + if (ret != 0) { + return ret; + } + #endif #ifdef WOLFSSL_SMALL_STACK_CACHE sha256->W = NULL; #endif @@ -1251,6 +1259,9 @@ static int InitSha256(wc_Sha256* sha256) { word32 S[8], t0, t1; int i; + #ifdef USE_SLOW_SHA256 + int j; + #endif word32 W[WC_SHA256_BLOCK_SIZE/sizeof(word32)]; /* Copy digest to working vars */ @@ -1264,6 +1275,16 @@ static int InitSha256(wc_Sha256* sha256) S[7] = sha256->digest[7]; i = 0; + #ifdef USE_SLOW_SHA256 + for (j = 0; j < 16; j++) { + RND1(j); + } + for (i = 16; i < 64; i += 16) { + for (j = 0; j < 16; j++) { + RNDN(j); + } + } + #else RND1( 0); RND1( 1); RND1( 2); RND1( 3); RND1( 4); RND1( 5); RND1( 6); RND1( 7); RND1( 8); RND1( 9); RND1(10); RND1(11); @@ -1275,6 +1296,7 @@ static int InitSha256(wc_Sha256* sha256) RNDN( 8); RNDN( 9); RNDN(10); RNDN(11); RNDN(12); RNDN(13); RNDN(14); RNDN(15); } + #endif /* Add the working vars back into digest */ sha256->digest[0] += S[0]; @@ -1945,6 +1967,9 @@ static int InitSha256(wc_Sha256* sha256) #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_HASH) /* implemented in wolfcrypt/src/port/psa/psa_hash.c */ +#elif defined(MAX3266X_SHA) + /* implemented in wolfcrypt/src/port/maxim/max3266x.c */ + #elif defined(WOLFSSL_RENESAS_RX64_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_rx64_hw_sha.c */ @@ -2223,6 +2248,10 @@ void wc_Sha256Free(wc_Sha256* sha256) } #endif +#ifdef MAX3266X_SHA_CB + wc_MXC_TPU_SHA_Free(&(sha256->mxcCtx)); +#endif + #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) wolfAsync_DevCtxFree(&sha256->asyncDev, WOLFSSL_ASYNC_MARKER_SHA256); #endif /* WOLFSSL_ASYNC_CRYPT */ @@ -2335,6 +2364,9 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_HASH) /* implemented in wolfcrypt/src/port/psa/psa_hash.c */ +#elif defined(MAX3266X_SHA) + /* implemented in wolfcrypt/src/port/maxim/max3266x.c */ + #else int wc_Sha224GetHash(wc_Sha224* sha224, byte* hash) @@ -2469,7 +2501,8 @@ int wc_Sha224_Grow(wc_Sha224* sha224, const byte* in, int inSz) /* implemented in wolfcrypt/src/port/psa/psa_hash.c */ #elif defined(WOLFSSL_RENESAS_RX64_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_rx64_hw_sha.c */ - +#elif defined(MAX3266X_SHA) + /* Implemented in wolfcrypt/src/port/maxim/max3266x.c */ #else int wc_Sha256GetHash(wc_Sha256* sha256, byte* hash) @@ -2496,7 +2529,7 @@ int wc_Sha256GetHash(wc_Sha256* sha256, byte* hash) ret = wc_Sha256Copy(sha256, tmpSha256); if (ret == 0) { ret = wc_Sha256Final(tmpSha256, hash); - wc_Sha256Free(tmpSha256); /* TODO move outside brackets? */ + wc_Sha256Free(tmpSha256); } @@ -2520,6 +2553,13 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) wc_MAXQ10XX_Sha256Copy(src); #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Copy(&(src->mxcCtx), &(dst->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + #ifdef WOLFSSL_SMALL_STACK_CACHE dst->W = NULL; #endif diff --git a/src/wolfcrypt/src/sha3.c b/src/wolfcrypt/src/sha3.c index 99f739b..1a3596a 100644 --- a/src/wolfcrypt/src/sha3.c +++ b/src/wolfcrypt/src/sha3.c @@ -1,6 +1,6 @@ /* sha3.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -62,8 +62,7 @@ } #endif -#if !defined(WOLFSSL_ARMASM) || (!defined(__arm__) && \ - !defined(WOLFSSL_ARMASM_CRYPTO_SHA3)) +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) #ifdef USE_INTEL_SPEEDUP #include @@ -250,7 +249,7 @@ while (0) #ifndef USE_INTEL_SPEEDUP static #endif -void BlockSha3(word64 *s) +void BlockSha3(word64* s) { byte i, x, y; word64 t0, t1; @@ -541,7 +540,7 @@ while (0) #ifndef USE_INTEL_SPEEDUP static #endif -void BlockSha3(word64 *s) +void BlockSha3(word64* s) { word64 n[25]; word64 b[5]; @@ -563,7 +562,7 @@ void BlockSha3(word64 *s) } } #endif /* WOLFSSL_SHA3_SMALL */ -#endif /* !WOLFSSL_ARMASM */ +#endif /* !WOLFSSL_ARMASM && !WOLFSSL_RISCV_ASM */ static WC_INLINE word64 Load64Unaligned(const unsigned char *a) { diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index 88c38f0..7f3e745 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -1,6 +1,6 @@ /* sha512.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,7 +28,7 @@ #if (defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)) && \ (!defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_ARMASM_NO_NEON)) && \ - !defined(WOLFSSL_PSOC6_CRYPTO) + !defined(WOLFSSL_PSOC6_CRYPTO) && !defined(WOLFSSL_RISCV_ASM) /* determine if we are using Espressif SHA hardware acceleration */ #undef WOLFSSL_USE_ESP32_CRYPT_HASH_HW @@ -96,6 +96,11 @@ #include #endif +#if defined(MAX3266X_SHA) + /* Already brought in by sha512.h */ + /* #include */ +#endif + #if defined(WOLFSSL_X86_64_BUILD) && defined(USE_INTEL_SPEEDUP) #if defined(__GNUC__) && ((__GNUC__ < 4) || \ (__GNUC__ == 4 && __GNUC_MINOR__ <= 8)) @@ -149,6 +154,9 @@ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) int wc_InitSha512(wc_Sha512* sha512) { @@ -489,6 +497,10 @@ static int InitSha512_256(wc_Sha512* sha512) SHA512_AVX1_RORX, SHA512_AVX2_RORX, SHA512_C }; #ifndef WC_C_DYNAMIC_FALLBACK + /* note that all write access to this static variable must be idempotent, + * as arranged by Sha512_SetTransform(), else it will be susceptible to + * data races. + */ static enum sha_methods sha_method = SHA512_UNSET; #endif @@ -761,6 +773,12 @@ int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) sha512->ctx.mode = ESP32_SHA_INIT; #endif +#ifdef MAX3266X_SHA_CB + if (wc_MXC_TPU_SHA_Init(&(sha512->mxcCtx)) != 0){ + return BAD_FUNC_ARG; + } +#endif + return InitSha512_Family(sha512, heap, devId, InitSha512); } @@ -1154,6 +1172,9 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) /* functions defined in wolfcrypt/src/port/renesas/renesas_fspsm_sha.c */ #elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #else static WC_INLINE int Sha512Final(wc_Sha512* sha512) @@ -1314,6 +1335,9 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #else static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, size_t digestSz) @@ -1390,6 +1414,10 @@ int wc_Sha512Final(wc_Sha512* sha512, byte* hash) #endif /* WOLFSSL_KCAPI_HASH */ +#if defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + +#else #if !defined(WOLFSSL_SE050) || !defined(WOLFSSL_SE050_HASH) int wc_InitSha512(wc_Sha512* sha512) { @@ -1432,12 +1460,18 @@ void wc_Sha512Free(wc_Sha512* sha512) } #endif +#ifdef MAX3266X_SHA_CB + wc_MXC_TPU_SHA_Free(&(sha512->mxcCtx)); +#endif + #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA512) wolfAsync_DevCtxFree(&sha512->asyncDev, WOLFSSL_ASYNC_MARKER_SHA512); #endif /* WOLFSSL_ASYNC_CRYPT */ ForceZero(sha512, sizeof(*sha512)); } +#endif + #if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) \ && !defined(WOLFSSL_KCAPI_HASH) /* Apply SHA512 transformation to the data */ @@ -1556,6 +1590,9 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #else static int InitSha384(wc_Sha384* sha384) @@ -1732,6 +1769,13 @@ int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) sha384->ctx.mode = ESP32_SHA_INIT; #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Init(&(sha384->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + ret = InitSha384(sha384); if (ret != 0) { return ret; @@ -1751,6 +1795,10 @@ int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) #endif /* WOLFSSL_IMX6_CAAM || WOLFSSL_SILABS_SHA512 || WOLFSSL_KCAPI_HASH */ +#if defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + +#else int wc_InitSha384(wc_Sha384* sha384) { int devId = INVALID_DEVID; @@ -1806,9 +1854,14 @@ void wc_Sha384Free(wc_Sha384* sha384) } #endif +#ifdef MAX3266X_SHA_CB + wc_MXC_TPU_SHA_Free(&(sha384->mxcCtx)); +#endif + ForceZero(sha384, sizeof(*sha384)); } +#endif #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 @@ -1820,6 +1873,9 @@ void wc_Sha384Free(wc_Sha384* sha384) !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #else static int Sha512_Family_GetHash(wc_Sha512* sha512, byte* hash, @@ -1923,6 +1979,13 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) } #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Copy(&(src->mxcCtx), &(dst->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + return ret; } @@ -2111,6 +2174,8 @@ int wc_Sha512_256Transform(wc_Sha512* sha, const unsigned char* data) #elif defined(WOLFSSL_RENESAS_RSIP) && \ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/renesas/renesas_fspsm_sha.c */ +#elif defined(MAX3266X_SHA) + /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ #else int wc_Sha384GetHash(wc_Sha384* sha384, byte* hash) @@ -2210,6 +2275,13 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) } #endif +#ifdef MAX3266X_SHA_CB + ret = wc_MXC_TPU_SHA_Copy(&(src->mxcCtx), &(dst->mxcCtx)); + if (ret != 0) { + return ret; + } +#endif + return ret; } diff --git a/src/wolfcrypt/src/signature.c b/src/wolfcrypt/src/signature.c index 33cec70..09ae526 100644 --- a/src/wolfcrypt/src/signature.c +++ b/src/wolfcrypt/src/signature.c @@ -1,6 +1,6 @@ /* signature.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -80,7 +80,7 @@ static int wc_SignatureDerEncode(enum wc_HashType hash_type, byte* hash_data, int wc_SignatureGetSize(enum wc_SignatureType sig_type, const void* key, word32 key_len) { - int sig_len = BAD_FUNC_ARG; + int sig_len = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Suppress possible unused args if all signature types are disabled */ (void)key; diff --git a/src/wolfcrypt/src/siphash.c b/src/wolfcrypt/src/siphash.c index 173b914..54c02f6 100644 --- a/src/wolfcrypt/src/siphash.c +++ b/src/wolfcrypt/src/siphash.c @@ -1,6 +1,6 @@ /* siphash.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -805,29 +805,29 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, #else #define SipRoundV(v0, v1, v2, v3) \ - v0 += v1; \ - v2 += v3; \ - v1 = rotlFixed64(v1, 13); \ - v3 = rotlFixed64(v3, 16); \ - v1 ^= v0; \ - v3 ^= v2; \ - v0 = rotlFixed64(v0, 32); \ - v2 += v1; \ - v0 += v3; \ - v1 = rotlFixed64(v1, 17); \ - v3 = rotlFixed64(v3, 21); \ - v1 ^= v2; \ - v3 ^= v0; \ - v2 = rotlFixed64(v2, 32); + (v0) += (v1); \ + (v2) += (v3); \ + (v1) = rotlFixed64(v1, 13); \ + (v3) = rotlFixed64(v3, 16); \ + (v1) ^= (v0); \ + (v3) ^= (v2); \ + (v0) = rotlFixed64(v0, 32); \ + (v2) += (v1); \ + (v0) += (v3); \ + (v1) = rotlFixed64(v1, 17); \ + (v3) = rotlFixed64(v3, 21); \ + (v1) ^= (v2); \ + (v3) ^= (v0); \ + (v2) = rotlFixed64(v2, 32); #define SipHashCompressV(v0, v1, v2, v3, m) \ do { \ int i; \ - v3 ^= m; \ + (v3) ^= (m); \ for (i = 0; i < WOLFSSL_SIPHASH_CROUNDS; i++) { \ SipRoundV(v0, v1, v2, v3); \ } \ - v0 ^= m; \ + (v0) ^= (m); \ } \ while (0) @@ -839,7 +839,7 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, for (i = 0; i < WOLFSSL_SIPHASH_DROUNDS; i++) { \ SipRoundV(v0, v1, v2, v3); \ } \ - n = v0 ^ v1 ^ v2 ^ v3; \ + n = (v0) ^ (v1) ^ (v2) ^ (v3); \ SET_U64(out, n); \ } \ while (0) diff --git a/src/wolfcrypt/src/sm2.c b/src/wolfcrypt/src/sm2.c index 829d5e5..24b8df9 100644 --- a/src/wolfcrypt/src/sm2.c +++ b/src/wolfcrypt/src/sm2.c @@ -1,6 +1,6 @@ /* sm2.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sm3.c b/src/wolfcrypt/src/sm3.c index 1339037..dfbef2e 100644 --- a/src/wolfcrypt/src/sm3.c +++ b/src/wolfcrypt/src/sm3.c @@ -1,6 +1,6 @@ /* sm3.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sm4.c b/src/wolfcrypt/src/sm4.c index 1e4f317..c29cc2b 100644 --- a/src/wolfcrypt/src/sm4.c +++ b/src/wolfcrypt/src/sm4.c @@ -1,6 +1,6 @@ /* sm4.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_arm32.c b/src/wolfcrypt/src/sp_arm32.c index 8529e41..68449be 100644 --- a/src/wolfcrypt/src/sp_arm32.c +++ b/src/wolfcrypt/src/sp_arm32.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -67,7 +67,7 @@ do { \ int ii; \ fprintf(stderr, name "=0x"); \ - for (ii = ((bits + 31) / 32) - 1; ii >= 0; ii--) \ + for (ii = (((bits) + 31) / 32) - 1; ii >= 0; ii--) \ fprintf(stderr, SP_PRINT_FMT, (var)[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -2231,7 +2231,8 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -2584,7 +2585,8 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "add sp, sp, #36\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -2610,7 +2612,7 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "strd %[r], %[a], [sp, #36]\n\t" #endif "mov lr, %[b]\n\t" - "ldm %[a], {%[r], %[a], %[b], r3}\n\t" + "ldm %[a], {r0, r1, r2, r3}\n\t" "ldm lr!, {r4, r5, r6}\n\t" "umull r10, r11, %[r], r4\n\t" "umull r12, r7, %[a], r4\n\t" @@ -2655,7 +2657,7 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "umaal r4, r6, %[b], r7\n\t" "sub lr, lr, #16\n\t" "umaal r5, r6, r3, r7\n\t" - "ldm %[r], {%[r], %[a], %[b], r3}\n\t" + "ldm %[r], {r0, r1, r2, r3}\n\t" "str r6, [sp, #32]\n\t" "ldm lr!, {r6}\n\t" "mov r7, #0\n\t" @@ -2715,7 +2717,8 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "add sp, sp, #44\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); } @@ -2751,7 +2754,7 @@ static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -2798,7 +2801,7 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -2848,7 +2851,7 @@ static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -2988,7 +2991,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -3066,7 +3069,7 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -3266,7 +3269,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -3400,7 +3403,7 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -4680,7 +4683,8 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -4923,7 +4927,8 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -4941,7 +4946,7 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) __asm__ __volatile__ ( "sub sp, sp, #32\n\t" "str %[r], [sp, #28]\n\t" - "ldm %[a], {%[r], %[a], r2, r3, r4, r5, r6, r7}\n\t" + "ldm %[a], {r0, r1, r2, r3, r4, r5, r6, r7}\n\t" "umull r9, r10, %[r], %[r]\n\t" "umull r11, r12, %[r], %[a]\n\t" "adds r11, r11, r11\n\t" @@ -5028,18 +5033,19 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) /* R[15] = r7 */ "ldr lr, [sp, #28]\n\t" "add lr, lr, #28\n\t" - "stm lr!, {%[r], r12}\n\t" + "stm lr!, {r0, r12}\n\t" "stm lr!, {r11}\n\t" "stm lr!, {r10}\n\t" "stm lr!, {r3, r4, r8, r9}\n\t" "stm lr!, {r7}\n\t" "sub lr, lr, #0x40\n\t" - "ldm sp, {%[r], %[a], r2, r3, r4, r5, r6}\n\t" - "stm lr, {%[r], %[a], r2, r3, r4, r5, r6}\n\t" + "ldm sp, {r0, r1, r2, r3, r4, r5, r6}\n\t" + "stm lr, {r0, r1, r2, r3, r4, r5, r6}\n\t" "add sp, sp, #32\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -5074,7 +5080,7 @@ static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -5159,7 +5165,7 @@ static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -5272,7 +5278,7 @@ static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -5347,7 +5353,8 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -5383,7 +5390,8 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -5585,7 +5593,8 @@ static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "bgt L_sp_2048_mul_64_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -5742,7 +5751,8 @@ static void sp_2048_sqr_64(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_2048_sqr_64_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -5798,7 +5808,8 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -5834,7 +5845,8 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -6036,7 +6048,8 @@ static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "bgt L_sp_2048_mul_32_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -6193,7 +6206,8 @@ static void sp_2048_sqr_32(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_2048_sqr_32_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -6314,7 +6328,7 @@ static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #256]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -8379,7 +8393,7 @@ static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r4, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -8408,7 +8422,8 @@ static void sp_2048_mont_norm_32(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -8434,7 +8449,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -8448,7 +8463,8 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -8572,7 +8588,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -9553,7 +9569,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -9848,7 +9865,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -10053,7 +10071,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -10183,7 +10202,7 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -11224,7 +11243,7 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -11283,7 +11302,7 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -11421,7 +11440,7 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -11820,7 +11839,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -12022,13 +12041,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12191,13 +12209,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12231,7 +12248,8 @@ static void sp_2048_mont_norm_64(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -12257,7 +12275,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -12271,7 +12289,8 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -12507,7 +12526,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -14416,7 +14435,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -14967,7 +14987,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -15332,7 +15353,8 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -15400,7 +15422,8 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -15534,7 +15557,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -15594,7 +15617,7 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -15732,7 +15755,7 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -16587,7 +16610,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -16783,13 +16806,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -16935,13 +16957,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17104,8 +17125,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -17121,7 +17141,8 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -17147,7 +17168,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -17161,7 +17182,8 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -17285,7 +17307,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp "adc %[r], r8, r8\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)r; } @@ -17999,7 +18021,7 @@ static void sp_2048_lshift_64(sp_digit* r_p, const sp_digit* a_p, byte n_p) "str r6, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -18117,13 +18139,12 @@ static int sp_2048_mod_exp_2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -23905,7 +23926,8 @@ static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -23947,7 +23969,7 @@ static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -24008,7 +24030,7 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -24072,7 +24094,7 @@ static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -24244,7 +24266,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -24350,7 +24372,7 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -24606,7 +24628,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -24796,7 +24818,7 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -27928,7 +27950,8 @@ static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -27969,7 +27992,7 @@ static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -28068,7 +28091,7 @@ static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -28209,7 +28232,7 @@ static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -28284,7 +28307,8 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -28320,7 +28344,8 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -28522,7 +28547,8 @@ static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "bgt L_sp_3072_mul_96_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -28679,7 +28705,8 @@ static void sp_3072_sqr_96(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_3072_sqr_96_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -28735,7 +28762,8 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -28771,7 +28799,8 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -28973,7 +29002,8 @@ static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "bgt L_sp_3072_mul_48_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -29130,7 +29160,8 @@ static void sp_3072_sqr_48(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_3072_sqr_48_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -29251,7 +29282,7 @@ static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #384]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -32340,7 +32371,7 @@ static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -32369,7 +32400,8 @@ static void sp_3072_mont_norm_48(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -32395,7 +32427,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -32409,7 +32441,8 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -32589,7 +32622,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -34034,7 +34067,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -34457,7 +34491,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -34742,7 +34777,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -34872,7 +34908,7 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #192]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -36425,7 +36461,7 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -36484,7 +36520,7 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -36622,7 +36658,7 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -37197,7 +37233,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -37399,13 +37435,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -37568,13 +37603,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -37608,7 +37642,8 @@ static void sp_3072_mont_norm_96(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -37634,7 +37669,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -37648,7 +37683,8 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -37996,7 +38032,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -40833,7 +40869,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -41640,7 +41677,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -42165,7 +42203,8 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -42233,7 +42272,8 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -42423,7 +42463,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -42483,7 +42523,7 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -42621,7 +42661,7 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -43834,7 +43874,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -44030,13 +44070,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -44182,13 +44221,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -44351,8 +44389,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -44368,7 +44405,8 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -44394,7 +44432,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -44408,7 +44446,8 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -44588,7 +44627,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp "adc %[r], r8, r8\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)r; } @@ -45494,7 +45533,7 @@ static void sp_3072_lshift_96(sp_digit* r_p, const sp_digit* a_p, byte n_p) "str r4, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -45612,13 +45651,12 @@ static int sp_3072_mod_exp_2_96(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -46146,7 +46184,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -46157,7 +46195,8 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -46392,7 +46431,7 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_dig "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -46480,7 +46519,8 @@ SP_NOINLINE static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -46506,7 +46546,8 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_dig "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -46542,7 +46583,8 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -46744,7 +46786,8 @@ static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "bgt L_sp_4096_mul_128_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -46901,7 +46944,8 @@ static void sp_4096_sqr_128(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_4096_sqr_128_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -47020,7 +47064,7 @@ static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #512]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -51133,7 +51177,7 @@ static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -51163,7 +51207,8 @@ static void sp_4096_mont_norm_128(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -51189,7 +51234,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const s "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -51203,7 +51248,8 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const s * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -51663,7 +51709,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const s "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -55428,7 +55474,8 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -56491,7 +56538,8 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -57176,7 +57224,8 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -57219,7 +57268,8 @@ SP_NOINLINE static void sp_4096_mont_sqr_128(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -57244,7 +57294,8 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_dig "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -57256,7 +57307,8 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_dig * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -57490,7 +57542,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_dig "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -57550,7 +57602,7 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -57688,7 +57740,7 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -59253,7 +59305,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -59449,13 +59501,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -59601,13 +59652,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -59770,8 +59820,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -59787,7 +59836,8 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -59813,7 +59863,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -59827,7 +59877,8 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -60063,7 +60114,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp "adc %[r], r8, r8\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)r; } @@ -61161,7 +61212,7 @@ static void sp_4096_lshift_128(sp_digit* r_p, const sp_digit* a_p, byte n_p) "str r5, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -61279,13 +61330,12 @@ static int sp_4096_mod_exp_2_128(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -61643,7 +61693,8 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "bgt L_sp_256_mul_8_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -63639,7 +63690,8 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "stm %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -63992,7 +64044,8 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "add sp, sp, #36\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -64018,7 +64071,7 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "strd %[r], %[a], [sp, #36]\n\t" #endif "mov lr, %[b]\n\t" - "ldm %[a], {%[r], %[a], %[b], r3}\n\t" + "ldm %[a], {r0, r1, r2, r3}\n\t" "ldm lr!, {r4, r5, r6}\n\t" "umull r10, r11, %[r], r4\n\t" "umull r12, r7, %[a], r4\n\t" @@ -64063,7 +64116,7 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "umaal r4, r6, %[b], r7\n\t" "sub lr, lr, #16\n\t" "umaal r5, r6, r3, r7\n\t" - "ldm %[r], {%[r], %[a], %[b], r3}\n\t" + "ldm %[r], {r0, r1, r2, r3}\n\t" "str r6, [sp, #32]\n\t" "ldm lr!, {r6}\n\t" "mov r7, #0\n\t" @@ -64123,7 +64176,8 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "add sp, sp, #44\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); } @@ -64283,7 +64337,8 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_256_sqr_8_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -65494,7 +65549,8 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -65737,7 +65793,8 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -65755,7 +65812,7 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) __asm__ __volatile__ ( "sub sp, sp, #32\n\t" "str %[r], [sp, #28]\n\t" - "ldm %[a], {%[r], %[a], r2, r3, r4, r5, r6, r7}\n\t" + "ldm %[a], {r0, r1, r2, r3, r4, r5, r6, r7}\n\t" "umull r9, r10, %[r], %[r]\n\t" "umull r11, r12, %[r], %[a]\n\t" "adds r11, r11, r11\n\t" @@ -65842,18 +65899,19 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) /* R[15] = r7 */ "ldr lr, [sp, #28]\n\t" "add lr, lr, #28\n\t" - "stm lr!, {%[r], r12}\n\t" + "stm lr!, {r0, r12}\n\t" "stm lr!, {r11}\n\t" "stm lr!, {r10}\n\t" "stm lr!, {r3, r4, r8, r9}\n\t" "stm lr!, {r7}\n\t" "sub lr, lr, #0x40\n\t" - "ldm sp, {%[r], %[a], r2, r3, r4, r5, r6}\n\t" - "stm lr, {%[r], %[a], r2, r3, r4, r5, r6}\n\t" + "ldm sp, {r0, r1, r2, r3, r4, r5, r6}\n\t" + "stm lr, {r0, r1, r2, r3, r4, r5, r6}\n\t" "add sp, sp, #32\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -65892,7 +65950,8 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -65929,7 +65988,7 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -65941,7 +66000,8 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* * a The number to convert. * m The modulus (prime). */ -static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -66165,7 +66225,8 @@ static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, const sp_di "add sp, sp, #24\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "r10", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr", "r10" ); (void)m_p; return (uint32_t)(size_t)r; @@ -66376,7 +66437,8 @@ static int sp_256_point_to_ecc_point_8(const sp_point_256* p, ecc_point* pm) * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p, sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -68480,7 +68542,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r12" ); (void)m_p; (void)mp_p; @@ -68496,7 +68559,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p, sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -68957,7 +69021,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); (void)m_p; (void)mp_p; @@ -68973,7 +69038,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p, sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -68988,7 +69054,7 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "strd %[r], %[a], [sp, #68]\n\t" #endif "mov lr, %[b]\n\t" - "ldm %[a], {%[r], %[a], %[b], r3}\n\t" + "ldm %[a], {r0, r1, r2, r3}\n\t" "ldm lr!, {r4, r5, r6}\n\t" "umull r10, r11, %[r], r4\n\t" "umull r12, r7, %[a], r4\n\t" @@ -69033,7 +69099,7 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "umaal r4, r6, %[b], r7\n\t" "sub lr, lr, #16\n\t" "umaal r5, r6, r3, r7\n\t" - "ldm %[r], {%[r], %[a], %[b], r3}\n\t" + "ldm %[r], {r0, r1, r2, r3}\n\t" "str r6, [sp, #64]\n\t" "ldm lr!, {r6}\n\t" "mov r7, #0\n\t" @@ -69212,7 +69278,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x4c\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); (void)m_p; (void)mp_p; @@ -69227,7 +69294,8 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -70410,7 +70478,8 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r12", "r8", "r9", "r10", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r12", "r8", "r9", + "r10", "lr" ); (void)m_p; (void)mp_p; @@ -70424,7 +70493,8 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -70776,7 +70846,8 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); (void)m_p; (void)mp_p; @@ -70790,7 +70861,8 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -70798,7 +70870,7 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" "str %[r], [sp, #64]\n\t" - "ldm %[a], {%[r], %[a], r2, r3, r4, r5, r6, r7}\n\t" + "ldm %[a], {r0, r1, r2, r3, r4, r5, r6, r7}\n\t" "umull r9, r10, %[r], %[r]\n\t" "umull r11, r12, %[r], %[a]\n\t" "adds r11, r11, r11\n\t" @@ -70885,7 +70957,7 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co /* R[15] = r7 */ "mov lr, sp\n\t" "add lr, lr, #28\n\t" - "stm lr!, {%[r], r12}\n\t" + "stm lr!, {r0, r12}\n\t" "stm lr!, {r11}\n\t" "stm lr!, {r10}\n\t" "stm lr!, {r3, r4, r8, r9}\n\t" @@ -71016,7 +71088,8 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "add sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); (void)m_p; (void)mp_p; @@ -71248,7 +71321,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -71268,7 +71341,8 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -71294,7 +71368,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_d "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -71308,7 +71382,8 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_d * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -71348,7 +71423,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_d "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -71636,7 +71711,8 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -71739,7 +71815,8 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -71824,7 +71901,8 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -71975,7 +72053,8 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "add sp, sp, #0x44\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11", "r12", "lr" ); (void)m_p; (void)mp_p; @@ -71988,7 +72067,8 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -72260,7 +72340,8 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -72272,7 +72353,8 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -72363,7 +72445,8 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -72375,7 +72458,8 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -72448,7 +72532,8 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -72479,7 +72564,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_8(r->x, p256_mod); - sp_256_cond_sub_8(r->x, r->x, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->x, r->x, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->x); /* y /= z^3 */ @@ -72488,7 +72573,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_8(r->y, p256_mod); - sp_256_cond_sub_8(r->y, r->y, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->y, r->y, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -72502,7 +72587,8 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -72546,7 +72632,8 @@ static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); (void)m_p; } @@ -72596,7 +72683,8 @@ static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2" ); (void)m_p; } @@ -72678,7 +72766,8 @@ static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3", "r12" ); (void)m_p; } @@ -72690,7 +72779,8 @@ static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -72732,7 +72822,8 @@ static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); (void)m_p; } @@ -72809,7 +72900,8 @@ static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r], {r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3" ); } @@ -73104,8 +73196,8 @@ static void sp_256_proj_point_add_8(sp_point_256* r, sp_256_mont_sub_8(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73122,7 +73214,7 @@ static void sp_256_proj_point_add_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -73296,8 +73388,8 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73314,7 +73406,7 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -73369,7 +73461,7 @@ static void sp_256_get_point_16_8(sp_point_256* r, const sp_point_256* table, r->z[6] = 0; r->z[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -73563,15 +73655,15 @@ static int sp_256_ecc_mulmod_fast_8(sp_point_256* r, const sp_point_256* g, cons #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_256)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_256)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -73767,8 +73859,8 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, sp_256_mont_sub_8(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73785,7 +73877,7 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -73875,8 +73967,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -73913,7 +74004,7 @@ static void sp_256_get_entry_16_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -74040,10 +74131,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74299,8 +74388,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74337,7 +74425,7 @@ static void sp_256_get_entry_256_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -74464,10 +74552,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74685,10 +74771,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74765,10 +74849,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76235,10 +76317,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76313,10 +76393,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76348,7 +76426,7 @@ static void sp_256_add_one_8(sp_digit* a_p) "stm %[a]!, {r1, r2, r3, r4}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -76399,6 +76477,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -76415,6 +76494,11 @@ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -76493,12 +76577,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76656,10 +76737,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76751,7 +76830,8 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -76785,7 +76865,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -76885,7 +76965,7 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #32]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -77158,7 +77238,7 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -77217,7 +77297,7 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -77355,7 +77435,7 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -78039,7 +78119,8 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -78075,7 +78156,7 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -78155,7 +78236,8 @@ static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "r10", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr", "r10" ); } @@ -78241,7 +78323,8 @@ static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r], {r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -78284,7 +78367,8 @@ static const unsigned char L_sp_256_num_bits_8_table[] = { static int sp_256_num_bits_8(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_256_num_bits_8_table_c asm ("r1") = (unsigned char*)&L_sp_256_num_bits_8_table; + register unsigned char* L_sp_256_num_bits_8_table_c asm ("r1") = + (unsigned char*)&L_sp_256_num_bits_8_table; __asm__ __volatile__ ( "mov lr, %[L_sp_256_num_bits_8_table]\n\t" @@ -78596,9 +78680,10 @@ static int sp_256_num_bits_8(const sp_digit* a_p) "\n" "L_sp_256_num_bits_8_9_%=: \n\t" "mov %[a], r12\n\t" - : [a] "+r" (a), [L_sp_256_num_bits_8_table] "+r" (L_sp_256_num_bits_8_table_c) + : [a] "+r" (a), + [L_sp_256_num_bits_8_table] "+r" (L_sp_256_num_bits_8_table_c) : - : "memory", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -78687,7 +78772,7 @@ static int sp_256_num_bits_8(const sp_digit* a_p) "mov %[a], r12\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -78976,10 +79061,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -79186,8 +79269,7 @@ static int sp_256_ecc_is_point_8(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -79226,8 +79308,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79335,10 +79416,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -79417,10 +79496,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79485,10 +79562,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79549,10 +79624,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79618,8 +79691,7 @@ static int sp_256_mont_sqrt_8(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79684,8 +79756,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -79974,7 +80045,8 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "bgt L_sp_384_mul_12_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -85471,7 +85543,8 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -85630,7 +85703,8 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_384_sqr_12_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -88693,7 +88767,8 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -88731,7 +88806,8 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -88775,7 +88851,7 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -88861,23 +88937,22 @@ static int sp_384_mod_mul_norm_12(sp_digit* r, const sp_digit* a, const sp_digit t[10] += t[9] >> 32; t[9] &= 0xffffffff; t[11] += t[10] >> 32; t[10] &= 0xffffffff; - r[0] = t[0]; - r[1] = t[1]; - r[2] = t[2]; - r[3] = t[3]; - r[4] = t[4]; - r[5] = t[5]; - r[6] = t[6]; - r[7] = t[7]; - r[8] = t[8]; - r[9] = t[9]; - r[10] = t[10]; - r[11] = t[11]; + r[0] = (sp_digit)t[0]; + r[1] = (sp_digit)t[1]; + r[2] = (sp_digit)t[2]; + r[3] = (sp_digit)t[3]; + r[4] = (sp_digit)t[4]; + r[5] = (sp_digit)t[5]; + r[6] = (sp_digit)t[6]; + r[7] = (sp_digit)t[7]; + r[8] = (sp_digit)t[8]; + r[9] = (sp_digit)t[9]; + r[10] = (sp_digit)t[10]; + r[11] = (sp_digit)t[11]; } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -89087,7 +89162,8 @@ static int sp_384_point_to_ecc_point_12(const sp_point_384* p, ecc_point* pm) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -89113,7 +89189,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_ "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -89127,7 +89203,8 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_ * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -89181,7 +89258,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_ "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -89584,7 +89661,8 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_384_cond_sub_12(a - 12, a, m, (sp_digit)0 - mp); } @@ -89719,7 +89797,8 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_384_cond_sub_12(a - 12, a, m, (sp_digit)0 - mp); } @@ -89824,7 +89903,8 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_384_cond_sub_12(a - 12, a, m, (sp_digit)0 - mp); } @@ -90145,7 +90225,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -90180,7 +90260,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_12(r->x, p384_mod); - sp_384_cond_sub_12(r->x, r->x, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->x, r->x, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->x); /* y /= z^3 */ @@ -90189,7 +90269,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_12(r->y, p384_mod); - sp_384_cond_sub_12(r->y, r->y, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->y, r->y, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -90203,7 +90283,8 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -90286,7 +90367,8 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -90329,7 +90411,7 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -90344,7 +90426,8 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -90370,7 +90453,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_ "mov %[r], lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -90384,7 +90467,8 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_ * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -90438,7 +90522,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_ "adc %[r], r8, r8\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)r; } @@ -90451,7 +90535,8 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_ * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -90521,7 +90606,7 @@ static void sp_384_rshift1_12(sp_digit* r_p, const sp_digit* a_p) "str r4, [%[r], #44]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -90833,8 +90918,8 @@ static void sp_384_proj_point_add_12(sp_point_384* r, sp_384_mont_sub_12(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -90851,7 +90936,7 @@ static void sp_384_proj_point_add_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -91025,8 +91110,8 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -91043,7 +91128,7 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -91110,7 +91195,7 @@ static void sp_384_get_point_16_12(sp_point_384* r, const sp_point_384* table, r->z[10] = 0; r->z[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -91316,15 +91401,15 @@ static int sp_384_ecc_mulmod_fast_12(sp_point_384* r, const sp_point_384* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_384)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_384)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -91520,8 +91605,8 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, sp_384_mont_sub_12(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -91538,7 +91623,7 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -91628,8 +91713,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -91674,7 +91758,7 @@ static void sp_384_get_entry_16_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -91809,10 +91893,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92068,8 +92150,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92114,7 +92195,7 @@ static void sp_384_get_entry_256_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -92249,10 +92330,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92470,10 +92549,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92550,10 +92627,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94020,10 +94095,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94098,10 +94171,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94139,7 +94210,7 @@ static void sp_384_add_one_12(sp_digit* a_p) "stm %[a]!, {r1, r2, r3, r4}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -94190,6 +94261,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -94206,6 +94278,11 @@ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -94284,12 +94361,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94447,10 +94521,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94542,7 +94614,8 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -94583,7 +94656,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -94683,7 +94756,7 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #48]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -95084,7 +95157,7 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -95143,7 +95216,7 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -95281,7 +95354,7 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -96009,7 +96082,8 @@ static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "str r10, [%[r], #44]\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -96052,7 +96126,8 @@ static const unsigned char L_sp_384_num_bits_12_table[] = { static int sp_384_num_bits_12(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_384_num_bits_12_table_c asm ("r1") = (unsigned char*)&L_sp_384_num_bits_12_table; + register unsigned char* L_sp_384_num_bits_12_table_c asm ("r1") = + (unsigned char*)&L_sp_384_num_bits_12_table; __asm__ __volatile__ ( "mov lr, %[L_sp_384_num_bits_12_table]\n\t" @@ -96616,9 +96691,10 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "\n" "L_sp_384_num_bits_12_13_%=: \n\t" "mov %[a], r12\n\t" - : [a] "+r" (a), [L_sp_384_num_bits_12_table] "+r" (L_sp_384_num_bits_12_table_c) + : [a] "+r" (a), + [L_sp_384_num_bits_12_table] "+r" (L_sp_384_num_bits_12_table_c) : - : "memory", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -96767,7 +96843,7 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "mov %[a], r12\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -97060,10 +97136,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -97270,8 +97344,7 @@ static int sp_384_ecc_is_point_12(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -97310,8 +97383,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -97419,10 +97491,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -97501,10 +97571,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -97569,10 +97637,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -97633,10 +97699,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -97732,8 +97796,7 @@ static int sp_384_mont_sqrt_12(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -97798,8 +97861,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -98103,7 +98165,8 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "bgt L_sp_521_mul_17_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -109119,7 +109182,8 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -109281,7 +109345,8 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_521_sqr_17_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -115153,7 +115218,8 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -115197,7 +115263,8 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "adc %[r], r4, #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -115252,7 +115319,7 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -115480,7 +115547,8 @@ static int sp_521_point_to_ecc_point_17(const sp_point_521* p, ecc_point* pm) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -115506,7 +115574,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_ "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -115520,7 +115588,8 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_ * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -115593,7 +115662,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_ "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -115721,7 +115790,8 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p "stm %[a]!, {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11", "r12", "lr" ); (void)m_p; (void)mp_p; @@ -115734,7 +115804,8 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -116350,7 +116421,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_521_cond_sub_17(a - 17, a, m, (sp_digit)0 - mp); } @@ -116362,7 +116434,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -116608,7 +116681,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_521_cond_sub_17(a - 17, a, m, (sp_digit)0 - mp); } @@ -116620,7 +116694,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) { register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; @@ -116821,7 +116896,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_521_cond_sub_17(a - 17, a, m, (sp_digit)0 - mp); } @@ -117194,7 +117270,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -117229,7 +117305,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_17(r->x, p521_mod); - sp_521_cond_sub_17(r->x, r->x, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->x, r->x, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->x); /* y /= z^3 */ @@ -117238,7 +117314,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_17(r->y, p521_mod); - sp_521_cond_sub_17(r->y, r->y, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->y, r->y, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -117252,7 +117328,8 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -117327,7 +117404,8 @@ static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); (void)m_p; } @@ -117403,7 +117481,8 @@ static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3" ); (void)m_p; } @@ -117499,7 +117578,8 @@ static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3" ); (void)m_p; } @@ -117511,7 +117591,8 @@ static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -117587,7 +117668,8 @@ static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); (void)m_p; } @@ -117666,7 +117748,7 @@ static void sp_521_rshift1_17(sp_digit* r_p, const sp_digit* a_p) "str r3, [%[r], #64]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -117982,8 +118064,8 @@ static void sp_521_proj_point_add_17(sp_point_521* r, sp_521_mont_sub_17(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -118000,7 +118082,7 @@ static void sp_521_proj_point_add_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -118174,8 +118256,8 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -118192,7 +118274,7 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -118274,7 +118356,7 @@ static void sp_521_get_point_16_17(sp_point_521* r, const sp_point_521* table, r->z[15] = 0; r->z[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -118499,15 +118581,15 @@ static int sp_521_ecc_mulmod_fast_17(sp_point_521* r, const sp_point_521* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_521)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_521)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -118703,8 +118785,8 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, sp_521_mont_sub_17(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -118721,7 +118803,7 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -118811,8 +118893,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118867,7 +118948,7 @@ static void sp_521_get_entry_16_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -119012,10 +119093,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -119271,8 +119350,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -119327,7 +119405,7 @@ static void sp_521_get_entry_256_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -119472,10 +119550,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -119693,10 +119769,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -119773,10 +119847,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121787,10 +121859,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121865,10 +121935,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121915,7 +121983,7 @@ static void sp_521_add_one_17(sp_digit* a_p) "stm %[a]!, {r1}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -121966,6 +122034,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -121983,6 +122052,11 @@ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -122061,12 +122135,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -122226,10 +122297,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -122388,7 +122457,7 @@ static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) #endif : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -122508,7 +122577,7 @@ static void sp_521_lshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) "str r5, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -122726,7 +122795,7 @@ static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) "str r6, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -122765,7 +122834,8 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], %[a], %[a]\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -122817,7 +122887,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -122917,7 +122987,7 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #68]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -123478,7 +123548,7 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -123537,7 +123607,7 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -123675,7 +123745,7 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -124365,7 +124435,8 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12", "lr" ); return (uint32_t)(size_t)r; } @@ -124419,7 +124490,7 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -124565,7 +124636,8 @@ static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "str r9, [%[r], #64]\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -124608,7 +124680,8 @@ static const unsigned char L_sp_521_num_bits_17_table[] = { static int sp_521_num_bits_17(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_521_num_bits_17_table_c asm ("r1") = (unsigned char*)&L_sp_521_num_bits_17_table; + register unsigned char* L_sp_521_num_bits_17_table_c asm ("r1") = + (unsigned char*)&L_sp_521_num_bits_17_table; __asm__ __volatile__ ( "mov lr, %[L_sp_521_num_bits_17_table]\n\t" @@ -125487,9 +125560,10 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "\n" "L_sp_521_num_bits_17_18_%=: \n\t" "mov %[a], r12\n\t" - : [a] "+r" (a), [L_sp_521_num_bits_17_table] "+r" (L_sp_521_num_bits_17_table_c) + : [a] "+r" (a), + [L_sp_521_num_bits_17_table] "+r" (L_sp_521_num_bits_17_table_c) : - : "memory", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -125713,7 +125787,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "mov %[a], r12\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (uint32_t)(size_t)a; } @@ -126015,10 +126089,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126228,8 +126300,7 @@ static int sp_521_ecc_is_point_17(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126268,8 +126339,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -126377,10 +126447,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126459,10 +126527,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -126527,10 +126593,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -126591,10 +126655,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -126644,8 +126706,7 @@ static int sp_521_mont_sqrt_17(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -126710,8 +126771,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136488,7 +136548,8 @@ static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -141720,7 +141781,8 @@ static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -141769,7 +141831,7 @@ static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -141844,7 +141906,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "sbc %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (uint32_t)(size_t)a; } @@ -141922,7 +141984,7 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "adc %[r], %[r], #0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -142040,7 +142102,7 @@ static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbc %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (uint32_t)(size_t)r; } @@ -142277,7 +142339,8 @@ static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "bgt L_sp_1024_mul_32_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -142434,7 +142497,8 @@ static void sp_1024_sqr_32(sp_digit* r_p, const sp_digit* a_p) "bgt L_sp_1024_sqr_32_store_%=\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -142554,7 +142618,8 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "mov %[a], r12\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", + "lr" ); return (uint32_t)(size_t)a; } @@ -142569,7 +142634,8 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -142595,7 +142661,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], r12\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -142609,7 +142675,8 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to subtract. * m Mask value to apply. */ -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -142733,7 +142800,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp "sbc %[r], lr, lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (uint32_t)(size_t)r; } @@ -142772,7 +142839,8 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "mov %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (uint32_t)(size_t)r; } @@ -142872,7 +142940,7 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -143913,7 +143981,7 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "str r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -143972,7 +144040,7 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "add %[d1], r4, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -144110,7 +144178,7 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d1], r3, r6\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)d1; } @@ -144539,7 +144607,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) "mov %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)a; } @@ -144661,16 +144729,16 @@ static void sp_1024_point_free_32(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -145853,7 +145921,8 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_1024_cond_sub_32(a - 32, a, m, mp); } @@ -146153,7 +146222,8 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_1024_cond_sub_32(a - 32, a, m, mp); } @@ -146363,7 +146433,8 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "mov %[mp], lr\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11" ); sp_1024_cond_sub_32(a - 32, a, m, mp); } @@ -146490,7 +146561,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_32(r->x, p1024_mod); - sp_1024_cond_sub_32(r->x, r->x, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->x, r->x, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->x); /* y /= z^3 */ @@ -146499,7 +146570,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_32(r->y, p1024_mod); - sp_1024_cond_sub_32(r->y, r->y, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->y, r->y, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -146513,7 +146584,8 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -146675,7 +146747,8 @@ static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig "stm %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r12" ); } @@ -146685,7 +146758,8 @@ static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig * a Number to double in Montgomery form. * m Modulus (prime). */ -static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -146830,7 +146904,8 @@ static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig "stm %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12", "cc" + : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", + "r12" ); } @@ -146840,7 +146915,8 @@ static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig * a Number to triple in Montgomery form. * m Modulus (prime). */ -static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -147140,7 +147216,8 @@ static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig "stm %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12", "cc" + : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", + "r12" ); } @@ -147151,7 +147228,8 @@ static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -147307,7 +147385,8 @@ static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig "stm %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r12" ); } @@ -147320,7 +147399,8 @@ static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_dig * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -147346,7 +147426,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp "mov %[r], lr\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (uint32_t)(size_t)r; } @@ -147360,7 +147440,8 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp * b A single precision number to add. * m Mask value to apply. */ -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) { register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; @@ -147484,7 +147565,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp "adc %[r], r8, r8\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (uint32_t)(size_t)r; } @@ -147624,7 +147705,7 @@ static void sp_1024_rshift1_32(sp_digit* r_p, const sp_digit* a_p) "str r3, [%[r], #124]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -147945,8 +148026,8 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, sp_1024_mont_sub_32(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -147963,7 +148044,7 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -148137,8 +148218,8 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -148155,7 +148236,7 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -148496,8 +148577,8 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, sp_1024_mont_sub_32(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -148514,7 +148595,7 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -148604,8 +148685,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -148704,10 +148784,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -148963,8 +149041,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -149063,10 +149140,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -149284,10 +149359,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -152922,10 +152995,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -153000,10 +153071,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -153037,7 +153106,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -153068,10 +153137,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -153097,7 +153164,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -153164,10 +153231,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -153314,9 +153379,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -155212,9 +155275,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -155582,9 +155643,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -156009,9 +156068,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -156041,7 +156098,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -156270,7 +156327,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -156377,9 +156434,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(neg, 1, NULL); sp_1024_point_free_32(c, 1, NULL); @@ -156572,9 +156627,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -156667,7 +156720,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, n = sp_1024_cmp_32(t1, p1024_mod); - sp_1024_cond_sub_32(t1, t1, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(t1, t1, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(t1); if (!sp_1024_iszero_32(t1)) { err = MP_VAL; @@ -156675,8 +156728,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -156715,8 +156767,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -156824,10 +156875,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_arm64.c b/src/wolfcrypt/src/sp_arm64.c index ea3ce39..0a465f4 100644 --- a/src/wolfcrypt/src/sp_arm64.c +++ b/src/wolfcrypt/src/sp_arm64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -67,7 +67,7 @@ do { \ int ii; \ fprintf(stderr, name "=0x"); \ - for (ii = ((bits + 63) / 64) - 1; ii >= 0; ii--) \ + for (ii = (((bits) + 63) / 64) - 1; ii >= 0; ii--) \ fprintf(stderr, SP_PRINT_FMT, (var)[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -4164,13 +4164,12 @@ static int sp_2048_mod_exp_16(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[16], 0, sizeof(sp_digit) * 16U); sp_2048_mont_reduce_16(r, m, mp); - mask = 0 - (sp_2048_cmp_16(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_16(r, m) >= 0); sp_2048_cond_sub_16(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4333,13 +4332,12 @@ static int sp_2048_mod_exp_16(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[16], 0, sizeof(sp_digit) * 16U); sp_2048_mont_reduce_16(r, m, mp); - mask = 0 - (sp_2048_cmp_16(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_16(r, m) >= 0); sp_2048_cond_sub_16(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5790,13 +5788,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5992,13 +5989,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6161,8 +6157,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -6837,13 +6832,12 @@ static int sp_2048_mod_exp_2_32(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13355,13 +13349,12 @@ static int sp_3072_mod_exp_24(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[24], 0, sizeof(sp_digit) * 24U); sp_3072_mont_reduce_24(r, m, mp); - mask = 0 - (sp_3072_cmp_24(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_24(r, m) >= 0); sp_3072_cond_sub_24(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13524,13 +13517,12 @@ static int sp_3072_mod_exp_24(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[24], 0, sizeof(sp_digit) * 24U); sp_3072_mont_reduce_24(r, m, mp); - mask = 0 - (sp_3072_cmp_24(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_24(r, m) >= 0); sp_3072_cond_sub_24(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15347,13 +15339,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15499,13 +15490,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15668,8 +15658,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -16440,13 +16429,12 @@ static int sp_3072_mod_exp_2_48(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20458,13 +20446,12 @@ static int sp_4096_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_4096_mont_reduce_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20610,13 +20597,12 @@ static int sp_4096_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_4096_mont_reduce_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20779,8 +20765,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -21647,13 +21632,12 @@ static int sp_4096_mod_exp_2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_4096_mont_reduce_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -22119,14 +22103,14 @@ static int sp_256_mod_mul_norm_4(sp_digit* r, const sp_digit* a, const sp_digit* (void)m; - a32[0] = a[0] & 0xffffffff; - a32[1] = a[0] >> 32; - a32[2] = a[1] & 0xffffffff; - a32[3] = a[1] >> 32; - a32[4] = a[2] & 0xffffffff; - a32[5] = a[2] >> 32; - a32[6] = a[3] & 0xffffffff; - a32[7] = a[3] >> 32; + a32[0] = (int64_t)(a[0] & 0xffffffff); + a32[1] = (int64_t)(a[0] >> 32); + a32[2] = (int64_t)(a[1] & 0xffffffff); + a32[3] = (int64_t)(a[1] >> 32); + a32[4] = (int64_t)(a[2] & 0xffffffff); + a32[5] = (int64_t)(a[2] >> 32); + a32[6] = (int64_t)(a[3] & 0xffffffff); + a32[7] = (int64_t)(a[3] >> 32); /* 1 1 0 -1 -1 -1 -1 0 */ t[0] = 0 + a32[0] + a32[1] - a32[3] - a32[4] - a32[5] - a32[6]; @@ -22176,10 +22160,10 @@ static int sp_256_mod_mul_norm_4(sp_digit* r, const sp_digit* a, const sp_digit* t[5] += t[4] >> 32; t[4] &= 0xffffffff; t[6] += t[5] >> 32; t[5] &= 0xffffffff; t[7] += t[6] >> 32; t[6] &= 0xffffffff; - r[0] = (t[1] << 32) | t[0]; - r[1] = (t[3] << 32) | t[2]; - r[2] = (t[5] << 32) | t[4]; - r[3] = (t[7] << 32) | t[6]; + r[0] = (sp_digit)((t[1] << 32) | t[0]); + r[1] = (sp_digit)((t[3] << 32) | t[2]); + r[2] = (sp_digit)((t[5] << 32) | t[4]); + r[3] = (sp_digit)((t[7] << 32) | t[6]); return MP_OKAY; } @@ -23060,7 +23044,7 @@ static void sp_256_map_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_4(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_4(r->x, p256_mod); - sp_256_cond_sub_4(r->x, r->x, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->x, r->x, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->x); /* y /= z^3 */ @@ -23069,7 +23053,7 @@ static void sp_256_map_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_4(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_4(r->y, p256_mod); - sp_256_cond_sub_4(r->y, r->y, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->y, r->y, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -24255,7 +24239,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -24486,10 +24470,8 @@ static int sp_256_ecc_mulmod_win_add_sub_4(sp_point_256* r, const sp_point_256* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24731,8 +24713,7 @@ static int sp_256_gen_stripe_table_4(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24902,10 +24883,8 @@ static int sp_256_ecc_mulmod_stripe_4(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25164,8 +25143,7 @@ static int sp_256_gen_stripe_table_4(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25335,10 +25313,8 @@ static int sp_256_ecc_mulmod_stripe_4(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25557,10 +25533,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25637,10 +25611,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -27350,7 +27322,7 @@ static void sp_256_ecc_recode_7_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<37; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -39494,8 +39466,7 @@ static int sp_256_ecc_mulmod_add_only_4(sp_point_256* r, const sp_point_256* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -39562,10 +39533,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -39640,10 +39609,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -39796,6 +39763,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_4(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -39812,6 +39780,11 @@ static int sp_256_ecc_gen_k_4(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -39890,12 +39863,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40059,10 +40029,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41930,10 +41898,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42184,8 +42150,7 @@ static int sp_256_ecc_is_point_4(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42224,8 +42189,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42333,10 +42297,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42415,10 +42377,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42483,10 +42443,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42547,10 +42505,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42616,8 +42572,7 @@ static int sp_256_mont_sqrt_4(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42682,8 +42637,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43390,18 +43344,18 @@ static int sp_384_mod_mul_norm_6(sp_digit* r, const sp_digit* a, const sp_digit* if (err == MP_OKAY) { a32 = t + 12; - a32[0] = a[0] & 0xffffffff; - a32[1] = a[0] >> 32; - a32[2] = a[1] & 0xffffffff; - a32[3] = a[1] >> 32; - a32[4] = a[2] & 0xffffffff; - a32[5] = a[2] >> 32; - a32[6] = a[3] & 0xffffffff; - a32[7] = a[3] >> 32; - a32[8] = a[4] & 0xffffffff; - a32[9] = a[4] >> 32; - a32[10] = a[5] & 0xffffffff; - a32[11] = a[5] >> 32; + a32[0] = (int64_t)(a[0] & 0xffffffff); + a32[1] = (int64_t)(a[0] >> 32); + a32[2] = (int64_t)(a[1] & 0xffffffff); + a32[3] = (int64_t)(a[1] >> 32); + a32[4] = (int64_t)(a[2] & 0xffffffff); + a32[5] = (int64_t)(a[2] >> 32); + a32[6] = (int64_t)(a[3] & 0xffffffff); + a32[7] = (int64_t)(a[3] >> 32); + a32[8] = (int64_t)(a[4] & 0xffffffff); + a32[9] = (int64_t)(a[4] >> 32); + a32[10] = (int64_t)(a[5] & 0xffffffff); + a32[11] = (int64_t)(a[5] >> 32); /* 1 0 0 0 0 0 0 0 1 1 0 -1 */ t[0] = 0 + a32[0] + a32[8] + a32[9] - a32[11]; @@ -43456,17 +43410,16 @@ static int sp_384_mod_mul_norm_6(sp_digit* r, const sp_digit* a, const sp_digit* t[10] += t[9] >> 32; t[9] &= 0xffffffff; t[11] += t[10] >> 32; t[10] &= 0xffffffff; - r[0] = (t[1] << 32) | t[0]; - r[1] = (t[3] << 32) | t[2]; - r[2] = (t[5] << 32) | t[4]; - r[3] = (t[7] << 32) | t[6]; - r[4] = (t[9] << 32) | t[8]; - r[5] = (t[11] << 32) | t[10]; + r[0] = (sp_digit)((t[1] << 32) | t[0]); + r[1] = (sp_digit)((t[3] << 32) | t[2]); + r[2] = (sp_digit)((t[5] << 32) | t[4]); + r[3] = (sp_digit)((t[7] << 32) | t[6]); + r[4] = (sp_digit)((t[9] << 32) | t[8]); + r[5] = (sp_digit)((t[11] << 32) | t[10]); } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -44245,7 +44198,7 @@ static void sp_384_map_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_6(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_6(r->x, p384_mod); - sp_384_cond_sub_6(r->x, r->x, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->x, r->x, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->x); /* y /= z^3 */ @@ -44254,7 +44207,7 @@ static void sp_384_map_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_6(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_6(r->y, p384_mod); - sp_384_cond_sub_6(r->y, r->y, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->y, r->y, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -44824,8 +44777,8 @@ static void sp_384_proj_point_add_6(sp_point_384* r, sp_384_mont_sub_6(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -44842,7 +44795,7 @@ static void sp_384_proj_point_add_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -45016,8 +44969,8 @@ static int sp_384_proj_point_add_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45034,7 +44987,7 @@ static int sp_384_proj_point_add_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -45248,7 +45201,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -45483,10 +45436,8 @@ static int sp_384_ecc_mulmod_win_add_sub_6(sp_point_384* r, const sp_point_384* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -45556,8 +45507,8 @@ static void sp_384_proj_point_add_qz1_6(sp_point_384* r, sp_384_mont_sub_6(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45574,7 +45525,7 @@ static void sp_384_proj_point_add_qz1_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -45688,8 +45639,7 @@ static int sp_384_gen_stripe_table_6(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -45859,10 +45809,8 @@ static int sp_384_ecc_mulmod_stripe_6(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46121,8 +46069,7 @@ static int sp_384_gen_stripe_table_6(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46292,10 +46239,8 @@ static int sp_384_ecc_mulmod_stripe_6(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46514,10 +46459,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46594,10 +46537,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48307,7 +48248,7 @@ static void sp_384_ecc_recode_7_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<55; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -66265,8 +66206,7 @@ static int sp_384_ecc_mulmod_add_only_6(sp_point_384* r, const sp_point_384* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -66333,10 +66273,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -66411,10 +66349,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -66571,6 +66507,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_6(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -66587,6 +66524,11 @@ static int sp_384_ecc_gen_k_6(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -66665,12 +66607,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -66834,10 +66773,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -68062,10 +67999,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -68272,8 +68207,7 @@ static int sp_384_ecc_is_point_6(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -68312,8 +68246,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -68421,10 +68354,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -68503,10 +68434,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -68571,10 +68500,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -68635,10 +68562,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -68734,8 +68659,7 @@ static int sp_384_mont_sqrt_6(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -68800,8 +68724,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -72454,7 +72377,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_9(r->x, p521_mod); - sp_521_cond_sub_9(r->x, r->x, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->x, r->x, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->x); /* y /= z^3 */ @@ -72463,7 +72386,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_9(r->y, p521_mod); - sp_521_cond_sub_9(r->y, r->y, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->y, r->y, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -73211,8 +73134,8 @@ static void sp_521_proj_point_add_9(sp_point_521* r, sp_521_mont_sub_9(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73229,7 +73152,7 @@ static void sp_521_proj_point_add_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -73403,8 +73326,8 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73421,7 +73344,7 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -73635,7 +73558,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -73897,10 +73820,8 @@ static int sp_521_ecc_mulmod_win_add_sub_9(sp_point_521* r, const sp_point_521* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -73970,8 +73891,8 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, sp_521_mont_sub_9(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -73988,7 +73909,7 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -74102,8 +74023,7 @@ static int sp_521_gen_stripe_table_9(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74291,10 +74211,8 @@ static int sp_521_ecc_mulmod_stripe_9(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74553,8 +74471,7 @@ static int sp_521_gen_stripe_table_9(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74742,10 +74659,8 @@ static int sp_521_ecc_mulmod_stripe_9(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -74964,10 +74879,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -75044,10 +74957,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -77393,7 +77304,7 @@ static void sp_521_ecc_recode_7_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<75; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -111429,8 +111340,7 @@ static int sp_521_ecc_mulmod_add_only_9(sp_point_521* r, const sp_point_521* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -111497,10 +111407,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -111575,10 +111483,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -111743,6 +111649,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -111760,6 +111667,11 @@ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -111838,12 +111750,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -112009,10 +111918,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113011,10 +112918,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113224,8 +113129,7 @@ static int sp_521_ecc_is_point_9(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113264,8 +113168,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -113373,10 +113276,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113455,10 +113356,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -113523,10 +113422,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -113587,10 +113484,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -113640,8 +113535,7 @@ static int sp_521_mont_sqrt_9(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -113706,8 +113600,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -115642,16 +115535,16 @@ static void sp_1024_point_free_16(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -116275,7 +116168,7 @@ static void sp_1024_map_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_16(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_16(r->x, p1024_mod); - sp_1024_cond_sub_16(r->x, r->x, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->x, r->x, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->x); /* y /= z^3 */ @@ -116284,7 +116177,7 @@ static void sp_1024_map_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_16(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_16(r->y, p1024_mod); - sp_1024_cond_sub_16(r->y, r->y, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->y, r->y, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -117320,8 +117213,8 @@ static void sp_1024_proj_point_add_16(sp_point_1024* r, sp_1024_mont_sub_16(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -117338,7 +117231,7 @@ static void sp_1024_proj_point_add_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -117512,8 +117405,8 @@ static int sp_1024_proj_point_add_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -117530,7 +117423,7 @@ static int sp_1024_proj_point_add_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -117752,7 +117645,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -117918,10 +117811,8 @@ static int sp_1024_ecc_mulmod_win_add_sub_16(sp_point_1024* r, const sp_point_10 } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -117993,8 +117884,8 @@ static void sp_1024_proj_point_add_qz1_16(sp_point_1024* r, sp_1024_mont_sub_16(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -118011,7 +117902,7 @@ static void sp_1024_proj_point_add_qz1_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -118122,8 +118013,7 @@ static int sp_1024_gen_stripe_table_16(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118222,10 +118112,8 @@ static int sp_1024_ecc_mulmod_stripe_16(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118442,10 +118330,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121843,10 +121729,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121921,10 +121805,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -121958,7 +121840,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -121989,10 +121871,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -122018,7 +121898,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -122085,10 +121965,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -122235,9 +122113,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -123877,9 +123753,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -124247,9 +124121,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -124674,9 +124546,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -124706,7 +124576,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -124935,7 +124805,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -125042,9 +124912,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(neg, 1, NULL); sp_1024_point_free_16(c, 1, NULL); @@ -125237,9 +125105,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -125407,7 +125273,7 @@ static int sp_1024_ecc_is_point_16(const sp_point_1024* point, n = sp_1024_cmp_16(t1, p1024_mod); - sp_1024_cond_sub_16(t1, t1, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(t1, t1, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(t1); if (!sp_1024_iszero_16(t1)) { err = MP_VAL; @@ -125415,8 +125281,7 @@ static int sp_1024_ecc_is_point_16(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -125455,8 +125320,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -125564,10 +125428,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_armthumb.c b/src/wolfcrypt/src/sp_armthumb.c index c7cb418..56c7931 100644 --- a/src/wolfcrypt/src/sp_armthumb.c +++ b/src/wolfcrypt/src/sp_armthumb.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -67,7 +67,7 @@ do { \ int ii; \ fprintf(stderr, name "=0x"); \ - for (ii = ((bits + 31) / 32) - 1; ii >= 0; ii--) \ + for (ii = (((bits) + 31) / 32) - 1; ii >= 0; ii--) \ fprintf(stderr, SP_PRINT_FMT, (var)[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -24134,13 +24134,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -24303,13 +24302,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -27715,13 +27713,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -27867,13 +27864,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -28036,8 +28032,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -30132,13 +30127,12 @@ static int sp_2048_mod_exp_2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -75596,13 +75590,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -75765,13 +75758,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -80008,13 +80000,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -80160,13 +80151,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -80329,8 +80319,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -83223,13 +83212,12 @@ static int sp_3072_mod_exp_2_96(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -92557,13 +92545,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -92709,13 +92696,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -92878,8 +92864,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -96565,13 +96550,12 @@ static int sp_4096_mod_exp_2_128(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -99151,7 +99135,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_8(r->x, p256_mod); - sp_256_cond_sub_8(r->x, r->x, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->x, r->x, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->x); /* y /= z^3 */ @@ -99160,7 +99144,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_8(r->y, p256_mod); - sp_256_cond_sub_8(r->y, r->y, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->y, r->y, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -100606,8 +100590,8 @@ static void sp_256_proj_point_add_8(sp_point_256* r, sp_256_mont_sub_8(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -100624,7 +100608,7 @@ static void sp_256_proj_point_add_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -100798,8 +100782,8 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -100816,7 +100800,7 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -100871,7 +100855,7 @@ static void sp_256_get_point_16_8(sp_point_256* r, const sp_point_256* table, r->z[6] = 0; r->z[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -101065,15 +101049,15 @@ static int sp_256_ecc_mulmod_fast_8(sp_point_256* r, const sp_point_256* g, cons #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_256)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_256)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -101269,8 +101253,8 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, sp_256_mont_sub_8(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -101287,7 +101271,7 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -101377,8 +101361,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -101415,7 +101398,7 @@ static void sp_256_get_entry_16_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -101542,10 +101525,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -101801,8 +101782,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -101839,7 +101819,7 @@ static void sp_256_get_entry_256_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -101966,10 +101946,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -102187,10 +102165,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -102267,10 +102243,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -103737,10 +103711,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -103815,10 +103787,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -103959,6 +103929,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -103975,6 +103946,11 @@ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -104053,12 +104029,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -104216,10 +104189,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -107521,10 +107492,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -107731,8 +107700,7 @@ static int sp_256_ecc_is_point_8(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -107771,8 +107739,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -107880,10 +107847,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -107962,10 +107927,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -108030,10 +107993,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -108094,10 +108055,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -108163,8 +108122,7 @@ static int sp_256_mont_sqrt_8(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -108229,8 +108187,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -109271,23 +109228,22 @@ static int sp_384_mod_mul_norm_12(sp_digit* r, const sp_digit* a, const sp_digit t[10] += t[9] >> 32; t[9] &= 0xffffffff; t[11] += t[10] >> 32; t[10] &= 0xffffffff; - r[0] = t[0]; - r[1] = t[1]; - r[2] = t[2]; - r[3] = t[3]; - r[4] = t[4]; - r[5] = t[5]; - r[6] = t[6]; - r[7] = t[7]; - r[8] = t[8]; - r[9] = t[9]; - r[10] = t[10]; - r[11] = t[11]; + r[0] = (sp_digit)t[0]; + r[1] = (sp_digit)t[1]; + r[2] = (sp_digit)t[2]; + r[3] = (sp_digit)t[3]; + r[4] = (sp_digit)t[4]; + r[5] = (sp_digit)t[5]; + r[6] = (sp_digit)t[6]; + r[7] = (sp_digit)t[7]; + r[8] = (sp_digit)t[8]; + r[9] = (sp_digit)t[9]; + r[10] = (sp_digit)t[10]; + r[11] = (sp_digit)t[11]; } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -110560,7 +110516,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_12(r->x, p384_mod); - sp_384_cond_sub_12(r->x, r->x, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->x, r->x, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->x); /* y /= z^3 */ @@ -110569,7 +110525,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_12(r->y, p384_mod); - sp_384_cond_sub_12(r->y, r->y, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->y, r->y, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -111442,8 +111398,8 @@ static void sp_384_proj_point_add_12(sp_point_384* r, sp_384_mont_sub_12(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -111460,7 +111416,7 @@ static void sp_384_proj_point_add_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -111634,8 +111590,8 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -111652,7 +111608,7 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -111719,7 +111675,7 @@ static void sp_384_get_point_16_12(sp_point_384* r, const sp_point_384* table, r->z[10] = 0; r->z[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -111925,15 +111881,15 @@ static int sp_384_ecc_mulmod_fast_12(sp_point_384* r, const sp_point_384* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_384)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_384)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -112129,8 +112085,8 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, sp_384_mont_sub_12(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -112147,7 +112103,7 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -112237,8 +112193,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -112283,7 +112238,7 @@ static void sp_384_get_entry_16_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -112418,10 +112373,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -112677,8 +112630,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -112723,7 +112675,7 @@ static void sp_384_get_entry_256_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -112858,10 +112810,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113079,10 +113029,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -113159,10 +113107,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -114629,10 +114575,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -114707,10 +114651,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -114887,6 +114829,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -114903,6 +114846,11 @@ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -114981,12 +114929,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -115144,10 +115089,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118725,10 +118668,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118935,8 +118876,7 @@ static int sp_384_ecc_is_point_12(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -118975,8 +118915,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -119084,10 +119023,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -119166,10 +119103,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -119234,10 +119169,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -119298,10 +119231,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -119397,8 +119328,7 @@ static int sp_384_mont_sqrt_12(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -119463,8 +119393,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -122849,7 +122778,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_17(r->x, p521_mod); - sp_521_cond_sub_17(r->x, r->x, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->x, r->x, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->x); /* y /= z^3 */ @@ -122858,7 +122787,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_17(r->y, p521_mod); - sp_521_cond_sub_17(r->y, r->y, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->y, r->y, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -125039,8 +124968,8 @@ static void sp_521_proj_point_add_17(sp_point_521* r, sp_521_mont_sub_17(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -125057,7 +124986,7 @@ static void sp_521_proj_point_add_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -125231,8 +125160,8 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -125249,7 +125178,7 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -125331,7 +125260,7 @@ static void sp_521_get_point_16_17(sp_point_521* r, const sp_point_521* table, r->z[15] = 0; r->z[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -125556,15 +125485,15 @@ static int sp_521_ecc_mulmod_fast_17(sp_point_521* r, const sp_point_521* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_521)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_521)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -125760,8 +125689,8 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, sp_521_mont_sub_17(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -125778,7 +125707,7 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -125868,8 +125797,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -125924,7 +125852,7 @@ static void sp_521_get_entry_16_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -126069,10 +125997,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126328,8 +126254,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126384,7 +126309,7 @@ static void sp_521_get_entry_256_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -126529,10 +126454,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126750,10 +126673,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -126830,10 +126751,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -128844,10 +128763,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -128922,10 +128839,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -129147,6 +129062,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -129164,6 +129080,11 @@ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -129242,12 +129163,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -129407,10 +129325,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -135672,10 +135588,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -135885,8 +135799,7 @@ static int sp_521_ecc_is_point_17(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -135925,8 +135838,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136034,10 +135946,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -136116,10 +136026,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136184,10 +136092,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136248,10 +136154,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136301,8 +136205,7 @@ static int sp_521_mont_sqrt_17(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -136367,8 +136270,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -202512,16 +202414,16 @@ static void sp_1024_point_free_32(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -203932,7 +203834,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_32(r->x, p1024_mod); - sp_1024_cond_sub_32(r->x, r->x, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->x, r->x, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->x); /* y /= z^3 */ @@ -203941,7 +203843,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_32(r->y, p1024_mod); - sp_1024_cond_sub_32(r->y, r->y, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->y, r->y, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -209936,8 +209838,8 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, sp_1024_mont_sub_32(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -209954,7 +209856,7 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -210128,8 +210030,8 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -210146,7 +210048,7 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -210487,8 +210389,8 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, sp_1024_mont_sub_32(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -210505,7 +210407,7 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -210595,8 +210497,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -210695,10 +210596,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -210954,8 +210853,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -211054,10 +210952,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -211275,10 +211171,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -214913,10 +214807,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -214991,10 +214883,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -215028,7 +214918,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -215059,10 +214949,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -215088,7 +214976,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -215155,10 +215043,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -215305,9 +215191,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -217203,9 +217087,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -217573,9 +217455,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -218000,9 +217880,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -218032,7 +217910,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -218261,7 +218139,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -218368,9 +218246,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(neg, 1, NULL); sp_1024_point_free_32(c, 1, NULL); @@ -218563,9 +218439,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -218658,7 +218532,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, n = sp_1024_cmp_32(t1, p1024_mod); - sp_1024_cond_sub_32(t1, t1, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(t1, t1, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(t1); if (!sp_1024_iszero_32(t1)) { err = MP_VAL; @@ -218666,8 +218540,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -218706,8 +218579,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -218815,10 +218687,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_c32.c b/src/wolfcrypt/src/sp_c32.c index 21a9e0e..9520f86 100644 --- a/src/wolfcrypt/src/sp_c32.c +++ b/src/wolfcrypt/src/sp_c32.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -71,13 +71,13 @@ #define SP_PRINT_NUM(var, name, total, words, bits) \ do { \ int ii; \ - byte nb[(bits + 7) / 8]; \ + byte nb[((bits) + 7) / 8]; \ sp_digit _s[words]; \ XMEMCPY(_s, var, sizeof(_s)); \ sp_##total##_norm_##words(_s); \ sp_##total##_to_bin_##words(_s, nb); \ fprintf(stderr, name "=0x"); \ - for (ii=0; ii<(bits + 7) / 8; ii++) \ + for (ii=0; ii<((bits) + 7) / 8; ii++) \ fprintf(stderr, "%02x", nb[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -357,29 +357,29 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, t0 = ((sp_uint64)a[ 0]) * b[ 0]; t1 = ((sp_uint64)a[ 0]) * b[ 1] + ((sp_uint64)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 0] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 0]) * b[ 2] + ((sp_uint64)a[ 1]) * b[ 1] + ((sp_uint64)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 1] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 0]) * b[ 3] + ((sp_uint64)a[ 1]) * b[ 2] + ((sp_uint64)a[ 2]) * b[ 1] + ((sp_uint64)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 2] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 0]) * b[ 4] + ((sp_uint64)a[ 1]) * b[ 3] + ((sp_uint64)a[ 2]) * b[ 2] + ((sp_uint64)a[ 3]) * b[ 1] + ((sp_uint64)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 3] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 0]) * b[ 5] + ((sp_uint64)a[ 1]) * b[ 4] + ((sp_uint64)a[ 2]) * b[ 3] + ((sp_uint64)a[ 3]) * b[ 2] + ((sp_uint64)a[ 4]) * b[ 1] + ((sp_uint64)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 4] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 0]) * b[ 6] + ((sp_uint64)a[ 1]) * b[ 5] + ((sp_uint64)a[ 2]) * b[ 4] @@ -387,7 +387,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 4]) * b[ 2] + ((sp_uint64)a[ 5]) * b[ 1] + ((sp_uint64)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 5] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 0]) * b[ 7] + ((sp_uint64)a[ 1]) * b[ 6] + ((sp_uint64)a[ 2]) * b[ 5] @@ -396,7 +396,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 5]) * b[ 2] + ((sp_uint64)a[ 6]) * b[ 1] + ((sp_uint64)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 6] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 0]) * b[ 8] + ((sp_uint64)a[ 1]) * b[ 7] + ((sp_uint64)a[ 2]) * b[ 6] @@ -406,7 +406,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 6]) * b[ 2] + ((sp_uint64)a[ 7]) * b[ 1] + ((sp_uint64)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 7] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 0]) * b[ 9] + ((sp_uint64)a[ 1]) * b[ 8] + ((sp_uint64)a[ 2]) * b[ 7] @@ -417,7 +417,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 7]) * b[ 2] + ((sp_uint64)a[ 8]) * b[ 1] + ((sp_uint64)a[ 9]) * b[ 0]; - t[ 8] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 8] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 0]) * b[10] + ((sp_uint64)a[ 1]) * b[ 9] + ((sp_uint64)a[ 2]) * b[ 8] @@ -429,7 +429,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 8]) * b[ 2] + ((sp_uint64)a[ 9]) * b[ 1] + ((sp_uint64)a[10]) * b[ 0]; - t[ 9] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 9] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 0]) * b[11] + ((sp_uint64)a[ 1]) * b[10] + ((sp_uint64)a[ 2]) * b[ 9] @@ -442,7 +442,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 2] + ((sp_uint64)a[10]) * b[ 1] + ((sp_uint64)a[11]) * b[ 0]; - t[10] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[10] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 1]) * b[11] + ((sp_uint64)a[ 2]) * b[10] + ((sp_uint64)a[ 3]) * b[ 9] @@ -454,7 +454,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 3] + ((sp_uint64)a[10]) * b[ 2] + ((sp_uint64)a[11]) * b[ 1]; - t[11] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[11] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 2]) * b[11] + ((sp_uint64)a[ 3]) * b[10] + ((sp_uint64)a[ 4]) * b[ 9] @@ -465,7 +465,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 4] + ((sp_uint64)a[10]) * b[ 3] + ((sp_uint64)a[11]) * b[ 2]; - r[12] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[12] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 3]) * b[11] + ((sp_uint64)a[ 4]) * b[10] + ((sp_uint64)a[ 5]) * b[ 9] @@ -475,7 +475,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 5] + ((sp_uint64)a[10]) * b[ 4] + ((sp_uint64)a[11]) * b[ 3]; - r[13] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[13] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 4]) * b[11] + ((sp_uint64)a[ 5]) * b[10] + ((sp_uint64)a[ 6]) * b[ 9] @@ -484,7 +484,7 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 6] + ((sp_uint64)a[10]) * b[ 5] + ((sp_uint64)a[11]) * b[ 4]; - r[14] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[14] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 5]) * b[11] + ((sp_uint64)a[ 6]) * b[10] + ((sp_uint64)a[ 7]) * b[ 9] @@ -492,35 +492,35 @@ SP_NOINLINE static void sp_2048_mul_12(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 7] + ((sp_uint64)a[10]) * b[ 6] + ((sp_uint64)a[11]) * b[ 5]; - r[15] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[15] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 6]) * b[11] + ((sp_uint64)a[ 7]) * b[10] + ((sp_uint64)a[ 8]) * b[ 9] + ((sp_uint64)a[ 9]) * b[ 8] + ((sp_uint64)a[10]) * b[ 7] + ((sp_uint64)a[11]) * b[ 6]; - r[16] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[16] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 7]) * b[11] + ((sp_uint64)a[ 8]) * b[10] + ((sp_uint64)a[ 9]) * b[ 9] + ((sp_uint64)a[10]) * b[ 8] + ((sp_uint64)a[11]) * b[ 7]; - r[17] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[17] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[ 8]) * b[11] + ((sp_uint64)a[ 9]) * b[10] + ((sp_uint64)a[10]) * b[ 9] + ((sp_uint64)a[11]) * b[ 8]; - r[18] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[18] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[ 9]) * b[11] + ((sp_uint64)a[10]) * b[10] + ((sp_uint64)a[11]) * b[ 9]; - r[19] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[19] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_uint64)a[10]) * b[11] + ((sp_uint64)a[11]) * b[10]; - r[20] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[20] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[11]) * b[11]; - r[21] = t1 & 0x1fffffff; t0 += t1 >> 29; - r[22] = t0 & 0x1fffffff; + r[21] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; + r[22] = (sp_digit)(t0 & 0x1fffffff); r[23] = (sp_digit)(t0 >> 29); XMEMCPY(r, t, sizeof(t)); } @@ -874,105 +874,105 @@ SP_NOINLINE static void sp_2048_sqr_12(sp_digit* r, const sp_digit* a) t0 = ((sp_uint64)a[ 0]) * a[ 0]; t1 = (((sp_uint64)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 0] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 0]) * a[ 2]) * 2 + ((sp_uint64)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 1] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 0]) * a[ 3] + ((sp_uint64)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 2] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 0]) * a[ 4] + ((sp_uint64)a[ 1]) * a[ 3]) * 2 + ((sp_uint64)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 3] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 0]) * a[ 5] + ((sp_uint64)a[ 1]) * a[ 4] + ((sp_uint64)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 4] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 0]) * a[ 6] + ((sp_uint64)a[ 1]) * a[ 5] + ((sp_uint64)a[ 2]) * a[ 4]) * 2 + ((sp_uint64)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 5] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 0]) * a[ 7] + ((sp_uint64)a[ 1]) * a[ 6] + ((sp_uint64)a[ 2]) * a[ 5] + ((sp_uint64)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 6] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 0]) * a[ 8] + ((sp_uint64)a[ 1]) * a[ 7] + ((sp_uint64)a[ 2]) * a[ 6] + ((sp_uint64)a[ 3]) * a[ 5]) * 2 + ((sp_uint64)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 7] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 0]) * a[ 9] + ((sp_uint64)a[ 1]) * a[ 8] + ((sp_uint64)a[ 2]) * a[ 7] + ((sp_uint64)a[ 3]) * a[ 6] + ((sp_uint64)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 8] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 0]) * a[10] + ((sp_uint64)a[ 1]) * a[ 9] + ((sp_uint64)a[ 2]) * a[ 8] + ((sp_uint64)a[ 3]) * a[ 7] + ((sp_uint64)a[ 4]) * a[ 6]) * 2 + ((sp_uint64)a[ 5]) * a[ 5]; - t[ 9] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 9] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 0]) * a[11] + ((sp_uint64)a[ 1]) * a[10] + ((sp_uint64)a[ 2]) * a[ 9] + ((sp_uint64)a[ 3]) * a[ 8] + ((sp_uint64)a[ 4]) * a[ 7] + ((sp_uint64)a[ 5]) * a[ 6]) * 2; - t[10] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[10] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 1]) * a[11] + ((sp_uint64)a[ 2]) * a[10] + ((sp_uint64)a[ 3]) * a[ 9] + ((sp_uint64)a[ 4]) * a[ 8] + ((sp_uint64)a[ 5]) * a[ 7]) * 2 + ((sp_uint64)a[ 6]) * a[ 6]; - t[11] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[11] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 2]) * a[11] + ((sp_uint64)a[ 3]) * a[10] + ((sp_uint64)a[ 4]) * a[ 9] + ((sp_uint64)a[ 5]) * a[ 8] + ((sp_uint64)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[12] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 3]) * a[11] + ((sp_uint64)a[ 4]) * a[10] + ((sp_uint64)a[ 5]) * a[ 9] + ((sp_uint64)a[ 6]) * a[ 8]) * 2 + ((sp_uint64)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[13] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 4]) * a[11] + ((sp_uint64)a[ 5]) * a[10] + ((sp_uint64)a[ 6]) * a[ 9] + ((sp_uint64)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[14] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 5]) * a[11] + ((sp_uint64)a[ 6]) * a[10] + ((sp_uint64)a[ 7]) * a[ 9]) * 2 + ((sp_uint64)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[15] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 6]) * a[11] + ((sp_uint64)a[ 7]) * a[10] + ((sp_uint64)a[ 8]) * a[ 9]) * 2; - r[16] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[16] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 7]) * a[11] + ((sp_uint64)a[ 8]) * a[10]) * 2 + ((sp_uint64)a[ 9]) * a[ 9]; - r[17] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[17] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[ 8]) * a[11] + ((sp_uint64)a[ 9]) * a[10]) * 2; - r[18] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[18] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_uint64)a[ 9]) * a[11]) * 2 + ((sp_uint64)a[10]) * a[10]; - r[19] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[19] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_uint64)a[10]) * a[11]) * 2; - r[20] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[20] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_uint64)a[11]) * a[11]; - r[21] = t1 & 0x1fffffff; t0 += t1 >> 29; - r[22] = t0 & 0x1fffffff; + r[21] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; + r[22] = (sp_digit)(t0 & 0x1fffffff); r[23] = (sp_digit)(t0 >> 29); XMEMCPY(r, t, sizeof(t)); } @@ -1626,26 +1626,26 @@ SP_NOINLINE static void sp_2048_mul_add_36(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[32]) + r[32]; t[1] = (tb * a[33]) + r[33]; t[2] = (tb * a[34]) + r[34]; t[3] = (tb * a[35]) + r[35]; - r[32] = t[0] & 0x1fffffff; + r[32] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[33] = t[1] & 0x1fffffff; + r[33] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[34] = t[2] & 0x1fffffff; + r[34] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[35] = t[3] & 0x1fffffff; + r[35] = (sp_digit)(t[3] & 0x1fffffff); r[36] += (sp_digit)(t[3] >> 29); #else sp_int64 tb = b; @@ -1662,34 +1662,34 @@ SP_NOINLINE static void sp_2048_mul_add_36(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[4] += t[3] >> 29; - r[i+4] = t[4] & 0x1fffffff; + r[i+4] = (sp_digit)(t[4] & 0x1fffffff); t[5] += t[4] >> 29; - r[i+5] = t[5] & 0x1fffffff; + r[i+5] = (sp_digit)(t[5] & 0x1fffffff); t[6] += t[5] >> 29; - r[i+6] = t[6] & 0x1fffffff; + r[i+6] = (sp_digit)(t[6] & 0x1fffffff); t[7] += t[6] >> 29; - r[i+7] = t[7] & 0x1fffffff; + r[i+7] = (sp_digit)(t[7] & 0x1fffffff); t[0] = t[7] >> 29; } t[0] += (tb * a[32]) + r[32]; t[1] = (tb * a[33]) + r[33]; t[2] = (tb * a[34]) + r[34]; t[3] = (tb * a[35]) + r[35]; - r[32] = t[0] & 0x1fffffff; + r[32] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[33] = t[1] & 0x1fffffff; + r[33] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[34] = t[2] & 0x1fffffff; + r[34] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[35] = t[3] & 0x1fffffff; + r[35] = (sp_digit)(t[3] & 0x1fffffff); r[36] += (sp_digit)(t[3] >> 29); #endif /* WOLFSSL_SP_SMALL */ #endif /* !WOLFSSL_SP_LARGE_CODE */ @@ -1708,7 +1708,7 @@ static void sp_2048_mont_shift_36(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[36]) << 20; for (i = 0; i < 35; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[37 + i]) << 20; } @@ -1718,26 +1718,26 @@ static void sp_2048_mont_shift_36(sp_digit* r, const sp_digit* a) sp_int64 n = a[35] >> 9; n += ((sp_int64)a[36]) << 20; for (i = 0; i < 32; i += 8) { - r[i + 0] = n & 0x1fffffff; + r[i + 0] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 37]) << 20; - r[i + 1] = n & 0x1fffffff; + r[i + 1] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 38]) << 20; - r[i + 2] = n & 0x1fffffff; + r[i + 2] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 39]) << 20; - r[i + 3] = n & 0x1fffffff; + r[i + 3] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 40]) << 20; - r[i + 4] = n & 0x1fffffff; + r[i + 4] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 41]) << 20; - r[i + 5] = n & 0x1fffffff; + r[i + 5] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 42]) << 20; - r[i + 6] = n & 0x1fffffff; + r[i + 6] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 43]) << 20; - r[i + 7] = n & 0x1fffffff; + r[i + 7] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 44]) << 20; } - r[32] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[69]) << 20; - r[33] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[70]) << 20; - r[34] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[71]) << 20; + r[32] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[69]) << 20; + r[33] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[70]) << 20; + r[34] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[71]) << 20; r[35] = (sp_digit)n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[36], 0, sizeof(*r) * 36U); @@ -1758,11 +1758,11 @@ static void sp_2048_mont_reduce_36(sp_digit* a, const sp_digit* m, sp_digit mp) sp_2048_norm_36(a + 36); for (i=0; i<35; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1ffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1ffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -1913,22 +1913,22 @@ SP_NOINLINE static void sp_2048_rshift_36(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<35; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } #else for (i=0; i<32; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (29 - n)) & 0x1fffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (29 - n)) & 0x1fffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (29 - n)) & 0x1fffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (29 - n)) & 0x1fffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (29 - n)) & 0x1fffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (29 - n)) & 0x1fffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (29 - n)) & 0x1fffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (29 - n)) & 0x1fffffff); - } - r[32] = (a[32] >> n) | ((a[33] << (29 - n)) & 0x1fffffff); - r[33] = (a[33] >> n) | ((a[34] << (29 - n)) & 0x1fffffff); - r[34] = (a[34] >> n) | ((a[35] << (29 - n)) & 0x1fffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (29 - n)) & 0x1fffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (29 - n)) & 0x1fffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (29 - n)) & 0x1fffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (29 - n)) & 0x1fffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (29 - n)) & 0x1fffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (29 - n)) & 0x1fffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (29 - n)) & 0x1fffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (29 - n)) & 0x1fffffff); + } + r[32] = (a[32] >> n) | (sp_digit)((a[33] << (29 - n)) & 0x1fffffff); + r[33] = (a[33] >> n) | (sp_digit)((a[34] << (29 - n)) & 0x1fffffff); + r[34] = (a[34] >> n) | (sp_digit)((a[35] << (29 - n)) & 0x1fffffff); #endif /* WOLFSSL_SP_SMALL */ r[35] = a[35] >> n; } @@ -2105,8 +2105,7 @@ static int sp_2048_div_36(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2218,14 +2217,13 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(t[0], m, mp); n = sp_2048_cmp_36(t[0], m); - sp_2048_cond_sub_36(t[0], t[0], m, ~(n >> 31)); + sp_2048_cond_sub_36(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 36 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2309,13 +2307,12 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(t[0], m, mp); n = sp_2048_cmp_36(t[0], m); - sp_2048_cond_sub_36(t[0], t[0], m, ~(n >> 31)); + sp_2048_cond_sub_36(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 36 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2455,13 +2452,12 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(rt, m, mp); n = sp_2048_cmp_36(rt, m); - sp_2048_cond_sub_36(rt, rt, m, ~(n >> 31)); + sp_2048_cond_sub_36(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 72); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2615,26 +2611,26 @@ SP_NOINLINE static void sp_2048_mul_add_72(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[68]) + r[68]; t[1] = (tb * a[69]) + r[69]; t[2] = (tb * a[70]) + r[70]; t[3] = (tb * a[71]) + r[71]; - r[68] = t[0] & 0x1fffffff; + r[68] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[69] = t[1] & 0x1fffffff; + r[69] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[70] = t[2] & 0x1fffffff; + r[70] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[71] = t[3] & 0x1fffffff; + r[71] = (sp_digit)(t[3] & 0x1fffffff); r[72] += (sp_digit)(t[3] >> 29); #else sp_int64 tb = b; @@ -2651,21 +2647,21 @@ SP_NOINLINE static void sp_2048_mul_add_72(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[4] += t[3] >> 29; - r[i+4] = t[4] & 0x1fffffff; + r[i+4] = (sp_digit)(t[4] & 0x1fffffff); t[5] += t[4] >> 29; - r[i+5] = t[5] & 0x1fffffff; + r[i+5] = (sp_digit)(t[5] & 0x1fffffff); t[6] += t[5] >> 29; - r[i+6] = t[6] & 0x1fffffff; + r[i+6] = (sp_digit)(t[6] & 0x1fffffff); t[7] += t[6] >> 29; - r[i+7] = t[7] & 0x1fffffff; + r[i+7] = (sp_digit)(t[7] & 0x1fffffff); t[0] = t[7] >> 29; } t[0] += (tb * a[64]) + r[64]; @@ -2676,21 +2672,21 @@ SP_NOINLINE static void sp_2048_mul_add_72(sp_digit* r, const sp_digit* a, t[5] = (tb * a[69]) + r[69]; t[6] = (tb * a[70]) + r[70]; t[7] = (tb * a[71]) + r[71]; - r[64] = t[0] & 0x1fffffff; + r[64] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[65] = t[1] & 0x1fffffff; + r[65] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[66] = t[2] & 0x1fffffff; + r[66] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[67] = t[3] & 0x1fffffff; + r[67] = (sp_digit)(t[3] & 0x1fffffff); t[4] += t[3] >> 29; - r[68] = t[4] & 0x1fffffff; + r[68] = (sp_digit)(t[4] & 0x1fffffff); t[5] += t[4] >> 29; - r[69] = t[5] & 0x1fffffff; + r[69] = (sp_digit)(t[5] & 0x1fffffff); t[6] += t[5] >> 29; - r[70] = t[6] & 0x1fffffff; + r[70] = (sp_digit)(t[6] & 0x1fffffff); t[7] += t[6] >> 29; - r[71] = t[7] & 0x1fffffff; + r[71] = (sp_digit)(t[7] & 0x1fffffff); r[72] += (sp_digit)(t[7] >> 29); #endif /* WOLFSSL_SP_SMALL */ #endif /* !WOLFSSL_SP_LARGE_CODE */ @@ -2709,7 +2705,7 @@ static void sp_2048_mont_shift_72(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[71]) << 11; for (i = 0; i < 70; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[72 + i]) << 11; } @@ -2719,29 +2715,29 @@ static void sp_2048_mont_shift_72(sp_digit* r, const sp_digit* a) sp_int64 n = a[70] >> 18; n += ((sp_int64)a[71]) << 11; for (i = 0; i < 64; i += 8) { - r[i + 0] = n & 0x1fffffff; + r[i + 0] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 72]) << 11; - r[i + 1] = n & 0x1fffffff; + r[i + 1] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 73]) << 11; - r[i + 2] = n & 0x1fffffff; + r[i + 2] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 74]) << 11; - r[i + 3] = n & 0x1fffffff; + r[i + 3] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 75]) << 11; - r[i + 4] = n & 0x1fffffff; + r[i + 4] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 76]) << 11; - r[i + 5] = n & 0x1fffffff; + r[i + 5] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 77]) << 11; - r[i + 6] = n & 0x1fffffff; + r[i + 6] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 78]) << 11; - r[i + 7] = n & 0x1fffffff; + r[i + 7] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[i + 79]) << 11; } - r[64] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[136]) << 11; - r[65] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[137]) << 11; - r[66] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[138]) << 11; - r[67] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[139]) << 11; - r[68] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[140]) << 11; - r[69] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[141]) << 11; + r[64] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[136]) << 11; + r[65] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[137]) << 11; + r[66] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[138]) << 11; + r[67] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[139]) << 11; + r[68] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[140]) << 11; + r[69] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[141]) << 11; r[70] = (sp_digit)n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[71], 0, sizeof(*r) * 71U); @@ -2764,33 +2760,33 @@ static void sp_2048_mont_reduce_72(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<70; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } else { for (i=0; i<70; i++) { - mu = a[i] & 0x1fffffff; + mu = (sp_digit)(a[i] & 0x1fffffff); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = a[i] & 0x3ffffL; + mu = (sp_digit)(a[i] & 0x3ffffL); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } #else for (i=0; i<70; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL); sp_2048_mul_add_72(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -2971,26 +2967,26 @@ SP_NOINLINE static void sp_2048_rshift_72(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<71; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } #else for (i=0; i<64; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (29 - n)) & 0x1fffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (29 - n)) & 0x1fffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (29 - n)) & 0x1fffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (29 - n)) & 0x1fffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (29 - n)) & 0x1fffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (29 - n)) & 0x1fffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (29 - n)) & 0x1fffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (29 - n)) & 0x1fffffff); - } - r[64] = (a[64] >> n) | ((a[65] << (29 - n)) & 0x1fffffff); - r[65] = (a[65] >> n) | ((a[66] << (29 - n)) & 0x1fffffff); - r[66] = (a[66] >> n) | ((a[67] << (29 - n)) & 0x1fffffff); - r[67] = (a[67] >> n) | ((a[68] << (29 - n)) & 0x1fffffff); - r[68] = (a[68] >> n) | ((a[69] << (29 - n)) & 0x1fffffff); - r[69] = (a[69] >> n) | ((a[70] << (29 - n)) & 0x1fffffff); - r[70] = (a[70] >> n) | ((a[71] << (29 - n)) & 0x1fffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (29 - n)) & 0x1fffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (29 - n)) & 0x1fffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (29 - n)) & 0x1fffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (29 - n)) & 0x1fffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (29 - n)) & 0x1fffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (29 - n)) & 0x1fffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (29 - n)) & 0x1fffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (29 - n)) & 0x1fffffff); + } + r[64] = (a[64] >> n) | (sp_digit)((a[65] << (29 - n)) & 0x1fffffff); + r[65] = (a[65] >> n) | (sp_digit)((a[66] << (29 - n)) & 0x1fffffff); + r[66] = (a[66] >> n) | (sp_digit)((a[67] << (29 - n)) & 0x1fffffff); + r[67] = (a[67] >> n) | (sp_digit)((a[68] << (29 - n)) & 0x1fffffff); + r[68] = (a[68] >> n) | (sp_digit)((a[69] << (29 - n)) & 0x1fffffff); + r[69] = (a[69] >> n) | (sp_digit)((a[70] << (29 - n)) & 0x1fffffff); + r[70] = (a[70] >> n) | (sp_digit)((a[71] << (29 - n)) & 0x1fffffff); #endif /* WOLFSSL_SP_SMALL */ r[71] = a[71] >> n; } @@ -3167,8 +3163,7 @@ static int sp_2048_div_72(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -3283,14 +3278,13 @@ static int sp_2048_mod_exp_72(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_72(t[0], m, mp); n = sp_2048_cmp_72(t[0], m); - sp_2048_cond_sub_72(t[0], t[0], m, ~(n >> 31)); + sp_2048_cond_sub_72(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 72 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -3374,13 +3368,12 @@ static int sp_2048_mod_exp_72(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_72(t[0], m, mp); n = sp_2048_cmp_72(t[0], m); - sp_2048_cond_sub_72(t[0], t[0], m, ~(n >> 31)); + sp_2048_cond_sub_72(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 72 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -3503,13 +3496,12 @@ static int sp_2048_mod_exp_72(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_72(rt, m, mp); n = sp_2048_cmp_72(rt, m); - sp_2048_cond_sub_72(rt, rt, m, ~(n >> 31)); + sp_2048_cond_sub_72(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 144); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -3630,8 +3622,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -3742,8 +3733,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -4113,7 +4103,7 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 36 * 13); @@ -4350,7 +4340,7 @@ SP_NOINLINE static void sp_2048_lshift_72(sp_digit* r, const sp_digit* a, r[72] = a[71] >> (29 - n); for (i=71; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff); } #else sp_int_digit s; @@ -4359,149 +4349,149 @@ SP_NOINLINE static void sp_2048_lshift_72(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[71]; r[72] = s >> (29U - n); s = (sp_int_digit)(a[71]); t = (sp_int_digit)(a[70]); - r[71] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[71] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[70]); t = (sp_int_digit)(a[69]); - r[70] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[70] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[69]); t = (sp_int_digit)(a[68]); - r[69] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[69] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[68]); t = (sp_int_digit)(a[67]); - r[68] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[68] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[67]); t = (sp_int_digit)(a[66]); - r[67] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[67] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[66]); t = (sp_int_digit)(a[65]); - r[66] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[66] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[65]); t = (sp_int_digit)(a[64]); - r[65] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[65] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[64]); t = (sp_int_digit)(a[63]); - r[64] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[64] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[63]); t = (sp_int_digit)(a[62]); - r[63] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[63] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[62]); t = (sp_int_digit)(a[61]); - r[62] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[62] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[61]); t = (sp_int_digit)(a[60]); - r[61] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[61] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[60]); t = (sp_int_digit)(a[59]); - r[60] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[60] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[59]); t = (sp_int_digit)(a[58]); - r[59] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[59] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[58]); t = (sp_int_digit)(a[57]); - r[58] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[58] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[57]); t = (sp_int_digit)(a[56]); - r[57] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[57] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[56]); t = (sp_int_digit)(a[55]); - r[56] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[56] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[55]); t = (sp_int_digit)(a[54]); - r[55] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[55] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[54]); t = (sp_int_digit)(a[53]); - r[54] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[54] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[53]); t = (sp_int_digit)(a[52]); - r[53] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[53] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[52]); t = (sp_int_digit)(a[51]); - r[52] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[52] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[51]); t = (sp_int_digit)(a[50]); - r[51] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[51] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[50]); t = (sp_int_digit)(a[49]); - r[50] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[50] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[49]); t = (sp_int_digit)(a[48]); - r[49] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[49] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[48]); t = (sp_int_digit)(a[47]); - r[48] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[48] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[47]); t = (sp_int_digit)(a[46]); - r[47] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[47] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[46]); t = (sp_int_digit)(a[45]); - r[46] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[46] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[45]); t = (sp_int_digit)(a[44]); - r[45] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[45] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[44]); t = (sp_int_digit)(a[43]); - r[44] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[44] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[43]); t = (sp_int_digit)(a[42]); - r[43] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[43] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[42]); t = (sp_int_digit)(a[41]); - r[42] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[42] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[41] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[40] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[39] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[38] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[37] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[36] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[35] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[34] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[33] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[32] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[31] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[30] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[29] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[28] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[27] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[26] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[25] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[24] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[23] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[22] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[21] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[20] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[19] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[18] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[17] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[16] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[15] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[14] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[13] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[12] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[11] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[10] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[9] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[8] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[7] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[6] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[5] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[4] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[3] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[2] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[1] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x1fffffff; + r[0] = (sp_digit)((a[0] << n) & 0x1fffffff); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -4611,12 +4601,11 @@ static int sp_2048_mod_exp_2_72(sp_digit* r, const sp_digit* e, int bits, const sp_2048_mont_reduce_72(r, m, mp); n = sp_2048_cmp_72(r, m); - sp_2048_cond_sub_72(r, r, m, ~(n >> 31)); + sp_2048_cond_sub_72(r, r, m, (sp_digit)~(n >> 31)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5335,17 +5324,17 @@ SP_NOINLINE static void sp_3072_mul_add_53(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[52]) + r[52]; - r[52] = t[0] & 0x1fffffff; + r[52] = (sp_digit)(t[0] & 0x1fffffff); r[53] += (sp_digit)(t[0] >> 29); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -5362,7 +5351,7 @@ static void sp_3072_mont_shift_53(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[53]) << 1; for (i = 0; i < 52; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[54 + i]) << 1; } @@ -5385,11 +5374,11 @@ static void sp_3072_mont_reduce_53(sp_digit* a, const sp_digit* m, sp_digit mp) sp_3072_norm_53(a + 53); for (i=0; i<52; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_3072_mul_add_53(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffffL); sp_3072_mul_add_53(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -5613,7 +5602,7 @@ SP_NOINLINE static void sp_3072_rshift_53(sp_digit* r, const sp_digit* a, int i; for (i=0; i<52; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } r[52] = a[52] >> n; } @@ -5790,8 +5779,7 @@ static int sp_3072_div_53(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5903,14 +5891,13 @@ static int sp_3072_mod_exp_53(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_53(t[0], m, mp); n = sp_3072_cmp_53(t[0], m); - sp_3072_cond_sub_53(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_53(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 53 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5994,13 +5981,12 @@ static int sp_3072_mod_exp_53(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_53(t[0], m, mp); n = sp_3072_cmp_53(t[0], m); - sp_3072_cond_sub_53(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_53(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 53 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6140,13 +6126,12 @@ static int sp_3072_mod_exp_53(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_53(rt, m, mp); n = sp_3072_cmp_53(rt, m); - sp_3072_cond_sub_53(rt, rt, m, ~(n >> 31)); + sp_3072_cond_sub_53(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 106); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6265,20 +6250,20 @@ SP_NOINLINE static void sp_3072_mul_add_106(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[104]) + r[104]; t[1] = (tb * a[105]) + r[105]; - r[104] = t[0] & 0x1fffffff; + r[104] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[105] = t[1] & 0x1fffffff; + r[105] = (sp_digit)(t[1] & 0x1fffffff); r[106] += (sp_digit)(t[1] >> 29); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -6295,7 +6280,7 @@ static void sp_3072_mont_shift_106(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[106]) << 2; for (i = 0; i < 105; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[107 + i]) << 2; } @@ -6320,33 +6305,33 @@ static void sp_3072_mont_reduce_106(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<105; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x7ffffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x7ffffffL); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } else { for (i=0; i<105; i++) { - mu = a[i] & 0x1fffffff; + mu = (sp_digit)(a[i] & 0x1fffffff); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = a[i] & 0x7ffffffL; + mu = (sp_digit)(a[i] & 0x7ffffffL); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } #else for (i=0; i<105; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x7ffffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x7ffffffL); sp_3072_mul_add_106(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -6452,7 +6437,7 @@ SP_NOINLINE static void sp_3072_rshift_106(sp_digit* r, const sp_digit* a, int i; for (i=0; i<105; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } r[105] = a[105] >> n; } @@ -6629,8 +6614,7 @@ static int sp_3072_div_106(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6743,14 +6727,13 @@ static int sp_3072_mod_exp_106(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_106(t[0], m, mp); n = sp_3072_cmp_106(t[0], m); - sp_3072_cond_sub_106(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_106(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 106 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6834,13 +6817,12 @@ static int sp_3072_mod_exp_106(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_106(t[0], m, mp); n = sp_3072_cmp_106(t[0], m); - sp_3072_cond_sub_106(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_106(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 106 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6963,13 +6945,12 @@ static int sp_3072_mod_exp_106(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_106(rt, m, mp); n = sp_3072_cmp_106(rt, m); - sp_3072_cond_sub_106(rt, rt, m, ~(n >> 31)); + sp_3072_cond_sub_106(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 212); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -7088,8 +7069,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -7200,8 +7180,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -7571,7 +7550,7 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 53 * 13); @@ -7807,9 +7786,9 @@ SP_NOINLINE static void sp_3072_lshift_106(sp_digit* r, const sp_digit* a, r[106] = a[105] >> (29 - n); for (i=105; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff); } - r[0] = (a[0] << n) & 0x1fffffff; + r[0] = (sp_digit)((a[0] << n) & 0x1fffffff); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -7919,12 +7898,11 @@ static int sp_3072_mod_exp_2_106(sp_digit* r, const sp_digit* e, int bits, const sp_3072_mont_reduce_106(r, m, mp); n = sp_3072_cmp_106(r, m); - sp_3072_cond_sub_106(r, r, m, ~(n >> 31)); + sp_3072_cond_sub_106(r, r, m, (sp_digit)~(n >> 31)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8460,29 +8438,29 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, t0 = ((sp_uint64)a[ 0]) * b[ 0]; t1 = ((sp_uint64)a[ 0]) * b[ 1] + ((sp_uint64)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 0] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[ 2] + ((sp_uint64)a[ 1]) * b[ 1] + ((sp_uint64)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 1] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[ 3] + ((sp_uint64)a[ 1]) * b[ 2] + ((sp_uint64)a[ 2]) * b[ 1] + ((sp_uint64)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 2] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[ 4] + ((sp_uint64)a[ 1]) * b[ 3] + ((sp_uint64)a[ 2]) * b[ 2] + ((sp_uint64)a[ 3]) * b[ 1] + ((sp_uint64)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 3] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[ 5] + ((sp_uint64)a[ 1]) * b[ 4] + ((sp_uint64)a[ 2]) * b[ 3] + ((sp_uint64)a[ 3]) * b[ 2] + ((sp_uint64)a[ 4]) * b[ 1] + ((sp_uint64)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 4] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[ 6] + ((sp_uint64)a[ 1]) * b[ 5] + ((sp_uint64)a[ 2]) * b[ 4] @@ -8490,7 +8468,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 4]) * b[ 2] + ((sp_uint64)a[ 5]) * b[ 1] + ((sp_uint64)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 5] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[ 7] + ((sp_uint64)a[ 1]) * b[ 6] + ((sp_uint64)a[ 2]) * b[ 5] @@ -8499,7 +8477,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 5]) * b[ 2] + ((sp_uint64)a[ 6]) * b[ 1] + ((sp_uint64)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 6] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[ 8] + ((sp_uint64)a[ 1]) * b[ 7] + ((sp_uint64)a[ 2]) * b[ 6] @@ -8509,7 +8487,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 6]) * b[ 2] + ((sp_uint64)a[ 7]) * b[ 1] + ((sp_uint64)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 7] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[ 9] + ((sp_uint64)a[ 1]) * b[ 8] + ((sp_uint64)a[ 2]) * b[ 7] @@ -8520,7 +8498,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 7]) * b[ 2] + ((sp_uint64)a[ 8]) * b[ 1] + ((sp_uint64)a[ 9]) * b[ 0]; - t[ 8] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 8] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[10] + ((sp_uint64)a[ 1]) * b[ 9] + ((sp_uint64)a[ 2]) * b[ 8] @@ -8532,7 +8510,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 8]) * b[ 2] + ((sp_uint64)a[ 9]) * b[ 1] + ((sp_uint64)a[10]) * b[ 0]; - t[ 9] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 9] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[11] + ((sp_uint64)a[ 1]) * b[10] + ((sp_uint64)a[ 2]) * b[ 9] @@ -8545,7 +8523,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 9]) * b[ 2] + ((sp_uint64)a[10]) * b[ 1] + ((sp_uint64)a[11]) * b[ 0]; - t[10] = t0 & 0xfffffff; t1 += t0 >> 28; + t[10] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 0]) * b[12] + ((sp_uint64)a[ 1]) * b[11] + ((sp_uint64)a[ 2]) * b[10] @@ -8559,7 +8537,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[10]) * b[ 2] + ((sp_uint64)a[11]) * b[ 1] + ((sp_uint64)a[12]) * b[ 0]; - t[11] = t1 & 0xfffffff; t0 += t1 >> 28; + t[11] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 0]) * b[13] + ((sp_uint64)a[ 1]) * b[12] + ((sp_uint64)a[ 2]) * b[11] @@ -8574,7 +8552,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 2] + ((sp_uint64)a[12]) * b[ 1] + ((sp_uint64)a[13]) * b[ 0]; - t[12] = t0 & 0xfffffff; t1 += t0 >> 28; + t[12] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 1]) * b[13] + ((sp_uint64)a[ 2]) * b[12] + ((sp_uint64)a[ 3]) * b[11] @@ -8588,7 +8566,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 3] + ((sp_uint64)a[12]) * b[ 2] + ((sp_uint64)a[13]) * b[ 1]; - t[13] = t1 & 0xfffffff; t0 += t1 >> 28; + t[13] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 2]) * b[13] + ((sp_uint64)a[ 3]) * b[12] + ((sp_uint64)a[ 4]) * b[11] @@ -8601,7 +8579,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 4] + ((sp_uint64)a[12]) * b[ 3] + ((sp_uint64)a[13]) * b[ 2]; - r[14] = t0 & 0xfffffff; t1 += t0 >> 28; + r[14] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 3]) * b[13] + ((sp_uint64)a[ 4]) * b[12] + ((sp_uint64)a[ 5]) * b[11] @@ -8613,7 +8591,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 5] + ((sp_uint64)a[12]) * b[ 4] + ((sp_uint64)a[13]) * b[ 3]; - r[15] = t1 & 0xfffffff; t0 += t1 >> 28; + r[15] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 4]) * b[13] + ((sp_uint64)a[ 5]) * b[12] + ((sp_uint64)a[ 6]) * b[11] @@ -8624,7 +8602,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 6] + ((sp_uint64)a[12]) * b[ 5] + ((sp_uint64)a[13]) * b[ 4]; - r[16] = t0 & 0xfffffff; t1 += t0 >> 28; + r[16] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 5]) * b[13] + ((sp_uint64)a[ 6]) * b[12] + ((sp_uint64)a[ 7]) * b[11] @@ -8634,7 +8612,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 7] + ((sp_uint64)a[12]) * b[ 6] + ((sp_uint64)a[13]) * b[ 5]; - r[17] = t1 & 0xfffffff; t0 += t1 >> 28; + r[17] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 6]) * b[13] + ((sp_uint64)a[ 7]) * b[12] + ((sp_uint64)a[ 8]) * b[11] @@ -8643,7 +8621,7 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 8] + ((sp_uint64)a[12]) * b[ 7] + ((sp_uint64)a[13]) * b[ 6]; - r[18] = t0 & 0xfffffff; t1 += t0 >> 28; + r[18] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 7]) * b[13] + ((sp_uint64)a[ 8]) * b[12] + ((sp_uint64)a[ 9]) * b[11] @@ -8651,35 +8629,35 @@ SP_NOINLINE static void sp_3072_mul_14(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[11]) * b[ 9] + ((sp_uint64)a[12]) * b[ 8] + ((sp_uint64)a[13]) * b[ 7]; - r[19] = t1 & 0xfffffff; t0 += t1 >> 28; + r[19] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[ 8]) * b[13] + ((sp_uint64)a[ 9]) * b[12] + ((sp_uint64)a[10]) * b[11] + ((sp_uint64)a[11]) * b[10] + ((sp_uint64)a[12]) * b[ 9] + ((sp_uint64)a[13]) * b[ 8]; - r[20] = t0 & 0xfffffff; t1 += t0 >> 28; + r[20] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[ 9]) * b[13] + ((sp_uint64)a[10]) * b[12] + ((sp_uint64)a[11]) * b[11] + ((sp_uint64)a[12]) * b[10] + ((sp_uint64)a[13]) * b[ 9]; - r[21] = t1 & 0xfffffff; t0 += t1 >> 28; + r[21] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[10]) * b[13] + ((sp_uint64)a[11]) * b[12] + ((sp_uint64)a[12]) * b[11] + ((sp_uint64)a[13]) * b[10]; - r[22] = t0 & 0xfffffff; t1 += t0 >> 28; + r[22] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[11]) * b[13] + ((sp_uint64)a[12]) * b[12] + ((sp_uint64)a[13]) * b[11]; - r[23] = t1 & 0xfffffff; t0 += t1 >> 28; + r[23] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = ((sp_uint64)a[12]) * b[13] + ((sp_uint64)a[13]) * b[12]; - r[24] = t0 & 0xfffffff; t1 += t0 >> 28; + r[24] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[13]) * b[13]; - r[25] = t1 & 0xfffffff; t0 += t1 >> 28; - r[26] = t0 & 0xfffffff; + r[25] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; + r[26] = (sp_digit)(t0 & 0xfffffff); r[27] = (sp_digit)(t0 >> 28); XMEMCPY(r, t, sizeof(t)); } @@ -9032,57 +9010,57 @@ SP_NOINLINE static void sp_3072_sqr_14(sp_digit* r, const sp_digit* a) t0 = ((sp_uint64)a[ 0]) * a[ 0]; t1 = (((sp_uint64)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 0] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[ 2]) * 2 + ((sp_uint64)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 1] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[ 3] + ((sp_uint64)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 2] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[ 4] + ((sp_uint64)a[ 1]) * a[ 3]) * 2 + ((sp_uint64)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 3] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[ 5] + ((sp_uint64)a[ 1]) * a[ 4] + ((sp_uint64)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 4] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[ 6] + ((sp_uint64)a[ 1]) * a[ 5] + ((sp_uint64)a[ 2]) * a[ 4]) * 2 + ((sp_uint64)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 5] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[ 7] + ((sp_uint64)a[ 1]) * a[ 6] + ((sp_uint64)a[ 2]) * a[ 5] + ((sp_uint64)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 6] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[ 8] + ((sp_uint64)a[ 1]) * a[ 7] + ((sp_uint64)a[ 2]) * a[ 6] + ((sp_uint64)a[ 3]) * a[ 5]) * 2 + ((sp_uint64)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 7] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[ 9] + ((sp_uint64)a[ 1]) * a[ 8] + ((sp_uint64)a[ 2]) * a[ 7] + ((sp_uint64)a[ 3]) * a[ 6] + ((sp_uint64)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0xfffffff; t1 += t0 >> 28; + t[ 8] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[10] + ((sp_uint64)a[ 1]) * a[ 9] + ((sp_uint64)a[ 2]) * a[ 8] + ((sp_uint64)a[ 3]) * a[ 7] + ((sp_uint64)a[ 4]) * a[ 6]) * 2 + ((sp_uint64)a[ 5]) * a[ 5]; - t[ 9] = t1 & 0xfffffff; t0 += t1 >> 28; + t[ 9] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[11] + ((sp_uint64)a[ 1]) * a[10] + ((sp_uint64)a[ 2]) * a[ 9] + ((sp_uint64)a[ 3]) * a[ 8] + ((sp_uint64)a[ 4]) * a[ 7] + ((sp_uint64)a[ 5]) * a[ 6]) * 2; - t[10] = t0 & 0xfffffff; t1 += t0 >> 28; + t[10] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 0]) * a[12] + ((sp_uint64)a[ 1]) * a[11] + ((sp_uint64)a[ 2]) * a[10] @@ -9090,7 +9068,7 @@ SP_NOINLINE static void sp_3072_sqr_14(sp_digit* r, const sp_digit* a) + ((sp_uint64)a[ 4]) * a[ 8] + ((sp_uint64)a[ 5]) * a[ 7]) * 2 + ((sp_uint64)a[ 6]) * a[ 6]; - t[11] = t1 & 0xfffffff; t0 += t1 >> 28; + t[11] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 0]) * a[13] + ((sp_uint64)a[ 1]) * a[12] + ((sp_uint64)a[ 2]) * a[11] @@ -9098,7 +9076,7 @@ SP_NOINLINE static void sp_3072_sqr_14(sp_digit* r, const sp_digit* a) + ((sp_uint64)a[ 4]) * a[ 9] + ((sp_uint64)a[ 5]) * a[ 8] + ((sp_uint64)a[ 6]) * a[ 7]) * 2; - t[12] = t0 & 0xfffffff; t1 += t0 >> 28; + t[12] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 1]) * a[13] + ((sp_uint64)a[ 2]) * a[12] + ((sp_uint64)a[ 3]) * a[11] @@ -9106,62 +9084,62 @@ SP_NOINLINE static void sp_3072_sqr_14(sp_digit* r, const sp_digit* a) + ((sp_uint64)a[ 5]) * a[ 9] + ((sp_uint64)a[ 6]) * a[ 8]) * 2 + ((sp_uint64)a[ 7]) * a[ 7]; - t[13] = t1 & 0xfffffff; t0 += t1 >> 28; + t[13] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 2]) * a[13] + ((sp_uint64)a[ 3]) * a[12] + ((sp_uint64)a[ 4]) * a[11] + ((sp_uint64)a[ 5]) * a[10] + ((sp_uint64)a[ 6]) * a[ 9] + ((sp_uint64)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0xfffffff; t1 += t0 >> 28; + r[14] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 3]) * a[13] + ((sp_uint64)a[ 4]) * a[12] + ((sp_uint64)a[ 5]) * a[11] + ((sp_uint64)a[ 6]) * a[10] + ((sp_uint64)a[ 7]) * a[ 9]) * 2 + ((sp_uint64)a[ 8]) * a[ 8]; - r[15] = t1 & 0xfffffff; t0 += t1 >> 28; + r[15] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 4]) * a[13] + ((sp_uint64)a[ 5]) * a[12] + ((sp_uint64)a[ 6]) * a[11] + ((sp_uint64)a[ 7]) * a[10] + ((sp_uint64)a[ 8]) * a[ 9]) * 2; - r[16] = t0 & 0xfffffff; t1 += t0 >> 28; + r[16] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 5]) * a[13] + ((sp_uint64)a[ 6]) * a[12] + ((sp_uint64)a[ 7]) * a[11] + ((sp_uint64)a[ 8]) * a[10]) * 2 + ((sp_uint64)a[ 9]) * a[ 9]; - r[17] = t1 & 0xfffffff; t0 += t1 >> 28; + r[17] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 6]) * a[13] + ((sp_uint64)a[ 7]) * a[12] + ((sp_uint64)a[ 8]) * a[11] + ((sp_uint64)a[ 9]) * a[10]) * 2; - r[18] = t0 & 0xfffffff; t1 += t0 >> 28; + r[18] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 7]) * a[13] + ((sp_uint64)a[ 8]) * a[12] + ((sp_uint64)a[ 9]) * a[11]) * 2 + ((sp_uint64)a[10]) * a[10]; - r[19] = t1 & 0xfffffff; t0 += t1 >> 28; + r[19] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[ 8]) * a[13] + ((sp_uint64)a[ 9]) * a[12] + ((sp_uint64)a[10]) * a[11]) * 2; - r[20] = t0 & 0xfffffff; t1 += t0 >> 28; + r[20] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[ 9]) * a[13] + ((sp_uint64)a[10]) * a[12]) * 2 + ((sp_uint64)a[11]) * a[11]; - r[21] = t1 & 0xfffffff; t0 += t1 >> 28; + r[21] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[10]) * a[13] + ((sp_uint64)a[11]) * a[12]) * 2; - r[22] = t0 & 0xfffffff; t1 += t0 >> 28; + r[22] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = (((sp_uint64)a[11]) * a[13]) * 2 + ((sp_uint64)a[12]) * a[12]; - r[23] = t1 & 0xfffffff; t0 += t1 >> 28; + r[23] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; t1 = (((sp_uint64)a[12]) * a[13]) * 2; - r[24] = t0 & 0xfffffff; t1 += t0 >> 28; + r[24] = (sp_digit)(t0 & 0xfffffff); t1 += t0 >> 28; t0 = ((sp_uint64)a[13]) * a[13]; - r[25] = t1 & 0xfffffff; t0 += t1 >> 28; - r[26] = t0 & 0xfffffff; + r[25] = (sp_digit)(t1 & 0xfffffff); t0 += t1 >> 28; + r[26] = (sp_digit)(t0 & 0xfffffff); r[27] = (sp_digit)(t0 >> 28); XMEMCPY(r, t, sizeof(t)); } @@ -9419,21 +9397,21 @@ SP_NOINLINE static void sp_3072_mul_add_56(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0xfffffff; + r[i+0] = (sp_digit)(t[0] & 0xfffffff); t[1] += t[0] >> 28; - r[i+1] = t[1] & 0xfffffff; + r[i+1] = (sp_digit)(t[1] & 0xfffffff); t[2] += t[1] >> 28; - r[i+2] = t[2] & 0xfffffff; + r[i+2] = (sp_digit)(t[2] & 0xfffffff); t[3] += t[2] >> 28; - r[i+3] = t[3] & 0xfffffff; + r[i+3] = (sp_digit)(t[3] & 0xfffffff); t[4] += t[3] >> 28; - r[i+4] = t[4] & 0xfffffff; + r[i+4] = (sp_digit)(t[4] & 0xfffffff); t[5] += t[4] >> 28; - r[i+5] = t[5] & 0xfffffff; + r[i+5] = (sp_digit)(t[5] & 0xfffffff); t[6] += t[5] >> 28; - r[i+6] = t[6] & 0xfffffff; + r[i+6] = (sp_digit)(t[6] & 0xfffffff); t[7] += t[6] >> 28; - r[i+7] = t[7] & 0xfffffff; + r[i+7] = (sp_digit)(t[7] & 0xfffffff); t[0] = t[7] >> 28; } t[0] += (tb * a[48]) + r[48]; @@ -9444,21 +9422,21 @@ SP_NOINLINE static void sp_3072_mul_add_56(sp_digit* r, const sp_digit* a, t[5] = (tb * a[53]) + r[53]; t[6] = (tb * a[54]) + r[54]; t[7] = (tb * a[55]) + r[55]; - r[48] = t[0] & 0xfffffff; + r[48] = (sp_digit)(t[0] & 0xfffffff); t[1] += t[0] >> 28; - r[49] = t[1] & 0xfffffff; + r[49] = (sp_digit)(t[1] & 0xfffffff); t[2] += t[1] >> 28; - r[50] = t[2] & 0xfffffff; + r[50] = (sp_digit)(t[2] & 0xfffffff); t[3] += t[2] >> 28; - r[51] = t[3] & 0xfffffff; + r[51] = (sp_digit)(t[3] & 0xfffffff); t[4] += t[3] >> 28; - r[52] = t[4] & 0xfffffff; + r[52] = (sp_digit)(t[4] & 0xfffffff); t[5] += t[4] >> 28; - r[53] = t[5] & 0xfffffff; + r[53] = (sp_digit)(t[5] & 0xfffffff); t[6] += t[5] >> 28; - r[54] = t[6] & 0xfffffff; + r[54] = (sp_digit)(t[6] & 0xfffffff); t[7] += t[6] >> 28; - r[55] = t[7] & 0xfffffff; + r[55] = (sp_digit)(t[7] & 0xfffffff); r[56] += (sp_digit)(t[7] >> 28); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -9474,29 +9452,29 @@ static void sp_3072_mont_shift_56(sp_digit* r, const sp_digit* a) sp_int64 n = a[54] >> 24; n += ((sp_int64)a[55]) << 4; for (i = 0; i < 48; i += 8) { - r[i + 0] = n & 0xfffffff; + r[i + 0] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 56]) << 4; - r[i + 1] = n & 0xfffffff; + r[i + 1] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 57]) << 4; - r[i + 2] = n & 0xfffffff; + r[i + 2] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 58]) << 4; - r[i + 3] = n & 0xfffffff; + r[i + 3] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 59]) << 4; - r[i + 4] = n & 0xfffffff; + r[i + 4] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 60]) << 4; - r[i + 5] = n & 0xfffffff; + r[i + 5] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 61]) << 4; - r[i + 6] = n & 0xfffffff; + r[i + 6] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 62]) << 4; - r[i + 7] = n & 0xfffffff; + r[i + 7] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 63]) << 4; } - r[48] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[104]) << 4; - r[49] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[105]) << 4; - r[50] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[106]) << 4; - r[51] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[107]) << 4; - r[52] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[108]) << 4; - r[53] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[109]) << 4; + r[48] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[104]) << 4; + r[49] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[105]) << 4; + r[50] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[106]) << 4; + r[51] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[107]) << 4; + r[52] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[108]) << 4; + r[53] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[109]) << 4; r[54] = (sp_digit)n; XMEMSET(&r[55], 0, sizeof(*r) * 55U); } @@ -9516,11 +9494,11 @@ static void sp_3072_mont_reduce_56(sp_digit* a, const sp_digit* m, sp_digit mp) sp_3072_norm_56(a + 55); for (i=0; i<54; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff); sp_3072_mul_add_56(a+i, m, mu); a[i+1] += a[i] >> 28; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xffffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xffffffL); sp_3072_mul_add_56(a+i, m, mu); a[i+1] += a[i] >> 28; a[i] &= 0xfffffff; @@ -9633,22 +9611,22 @@ SP_NOINLINE static void sp_3072_rshift_56(sp_digit* r, const sp_digit* a, int i; for (i=0; i<48; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (28 - n)) & 0xfffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (28 - n)) & 0xfffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (28 - n)) & 0xfffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (28 - n)) & 0xfffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (28 - n)) & 0xfffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (28 - n)) & 0xfffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (28 - n)) & 0xfffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (28 - n)) & 0xfffffff); - } - r[48] = (a[48] >> n) | ((a[49] << (28 - n)) & 0xfffffff); - r[49] = (a[49] >> n) | ((a[50] << (28 - n)) & 0xfffffff); - r[50] = (a[50] >> n) | ((a[51] << (28 - n)) & 0xfffffff); - r[51] = (a[51] >> n) | ((a[52] << (28 - n)) & 0xfffffff); - r[52] = (a[52] >> n) | ((a[53] << (28 - n)) & 0xfffffff); - r[53] = (a[53] >> n) | ((a[54] << (28 - n)) & 0xfffffff); - r[54] = (a[54] >> n) | ((a[55] << (28 - n)) & 0xfffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (28 - n)) & 0xfffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (28 - n)) & 0xfffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (28 - n)) & 0xfffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (28 - n)) & 0xfffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (28 - n)) & 0xfffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (28 - n)) & 0xfffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (28 - n)) & 0xfffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (28 - n)) & 0xfffffff); + } + r[48] = (a[48] >> n) | (sp_digit)((a[49] << (28 - n)) & 0xfffffff); + r[49] = (a[49] >> n) | (sp_digit)((a[50] << (28 - n)) & 0xfffffff); + r[50] = (a[50] >> n) | (sp_digit)((a[51] << (28 - n)) & 0xfffffff); + r[51] = (a[51] >> n) | (sp_digit)((a[52] << (28 - n)) & 0xfffffff); + r[52] = (a[52] >> n) | (sp_digit)((a[53] << (28 - n)) & 0xfffffff); + r[53] = (a[53] >> n) | (sp_digit)((a[54] << (28 - n)) & 0xfffffff); + r[54] = (a[54] >> n) | (sp_digit)((a[55] << (28 - n)) & 0xfffffff); r[55] = a[55] >> n; } @@ -9824,8 +9802,7 @@ static int sp_3072_div_56(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -9937,14 +9914,13 @@ static int sp_3072_mod_exp_56(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_56(t[0], m, mp); n = sp_3072_cmp_56(t[0], m); - sp_3072_cond_sub_56(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_56(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 56 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10028,13 +10004,12 @@ static int sp_3072_mod_exp_56(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_56(t[0], m, mp); n = sp_3072_cmp_56(t[0], m); - sp_3072_cond_sub_56(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_56(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 56 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10174,13 +10149,12 @@ static int sp_3072_mod_exp_56(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_56(rt, m, mp); n = sp_3072_cmp_56(rt, m); - sp_3072_cond_sub_56(rt, rt, m, ~(n >> 31)); + sp_3072_cond_sub_56(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 112); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10313,21 +10287,21 @@ SP_NOINLINE static void sp_3072_mul_add_112(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0xfffffff; + r[i+0] = (sp_digit)(t[0] & 0xfffffff); t[1] += t[0] >> 28; - r[i+1] = t[1] & 0xfffffff; + r[i+1] = (sp_digit)(t[1] & 0xfffffff); t[2] += t[1] >> 28; - r[i+2] = t[2] & 0xfffffff; + r[i+2] = (sp_digit)(t[2] & 0xfffffff); t[3] += t[2] >> 28; - r[i+3] = t[3] & 0xfffffff; + r[i+3] = (sp_digit)(t[3] & 0xfffffff); t[4] += t[3] >> 28; - r[i+4] = t[4] & 0xfffffff; + r[i+4] = (sp_digit)(t[4] & 0xfffffff); t[5] += t[4] >> 28; - r[i+5] = t[5] & 0xfffffff; + r[i+5] = (sp_digit)(t[5] & 0xfffffff); t[6] += t[5] >> 28; - r[i+6] = t[6] & 0xfffffff; + r[i+6] = (sp_digit)(t[6] & 0xfffffff); t[7] += t[6] >> 28; - r[i+7] = t[7] & 0xfffffff; + r[i+7] = (sp_digit)(t[7] & 0xfffffff); t[0] = t[7] >> 28; } t[0] += (tb * a[104]) + r[104]; @@ -10338,21 +10312,21 @@ SP_NOINLINE static void sp_3072_mul_add_112(sp_digit* r, const sp_digit* a, t[5] = (tb * a[109]) + r[109]; t[6] = (tb * a[110]) + r[110]; t[7] = (tb * a[111]) + r[111]; - r[104] = t[0] & 0xfffffff; + r[104] = (sp_digit)(t[0] & 0xfffffff); t[1] += t[0] >> 28; - r[105] = t[1] & 0xfffffff; + r[105] = (sp_digit)(t[1] & 0xfffffff); t[2] += t[1] >> 28; - r[106] = t[2] & 0xfffffff; + r[106] = (sp_digit)(t[2] & 0xfffffff); t[3] += t[2] >> 28; - r[107] = t[3] & 0xfffffff; + r[107] = (sp_digit)(t[3] & 0xfffffff); t[4] += t[3] >> 28; - r[108] = t[4] & 0xfffffff; + r[108] = (sp_digit)(t[4] & 0xfffffff); t[5] += t[4] >> 28; - r[109] = t[5] & 0xfffffff; + r[109] = (sp_digit)(t[5] & 0xfffffff); t[6] += t[5] >> 28; - r[110] = t[6] & 0xfffffff; + r[110] = (sp_digit)(t[6] & 0xfffffff); t[7] += t[6] >> 28; - r[111] = t[7] & 0xfffffff; + r[111] = (sp_digit)(t[7] & 0xfffffff); r[112] += (sp_digit)(t[7] >> 28); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -10368,28 +10342,28 @@ static void sp_3072_mont_shift_112(sp_digit* r, const sp_digit* a) sp_int64 n = a[109] >> 20; n += ((sp_int64)a[110]) << 8; for (i = 0; i < 104; i += 8) { - r[i + 0] = n & 0xfffffff; + r[i + 0] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 111]) << 8; - r[i + 1] = n & 0xfffffff; + r[i + 1] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 112]) << 8; - r[i + 2] = n & 0xfffffff; + r[i + 2] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 113]) << 8; - r[i + 3] = n & 0xfffffff; + r[i + 3] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 114]) << 8; - r[i + 4] = n & 0xfffffff; + r[i + 4] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 115]) << 8; - r[i + 5] = n & 0xfffffff; + r[i + 5] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 116]) << 8; - r[i + 6] = n & 0xfffffff; + r[i + 6] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 117]) << 8; - r[i + 7] = n & 0xfffffff; + r[i + 7] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[i + 118]) << 8; } - r[104] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[215]) << 8; - r[105] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[216]) << 8; - r[106] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[217]) << 8; - r[107] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[218]) << 8; - r[108] = n & 0xfffffff; n >>= 28; n += ((sp_int64)a[219]) << 8; + r[104] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[215]) << 8; + r[105] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[216]) << 8; + r[106] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[217]) << 8; + r[107] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[218]) << 8; + r[108] = (sp_digit)(n & 0xfffffff); n >>= 28; n += ((sp_int64)a[219]) << 8; r[109] = (sp_digit)n; XMEMSET(&r[110], 0, sizeof(*r) * 110U); } @@ -10411,33 +10385,33 @@ static void sp_3072_mont_reduce_112(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<109; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; a[i] &= 0xfffffff; } else { for (i=0; i<109; i++) { - mu = a[i] & 0xfffffff; + mu = (sp_digit)(a[i] & 0xfffffff); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; } - mu = a[i] & 0xfffffL; + mu = (sp_digit)(a[i] & 0xfffffL); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; a[i] &= 0xfffffff; } #else for (i=0; i<109; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffff); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL); sp_3072_mul_add_112(a+i, m, mu); a[i+1] += a[i] >> 28; a[i] &= 0xfffffff; @@ -10551,22 +10525,22 @@ SP_NOINLINE static void sp_3072_rshift_112(sp_digit* r, const sp_digit* a, int i; for (i=0; i<104; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (28 - n)) & 0xfffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (28 - n)) & 0xfffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (28 - n)) & 0xfffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (28 - n)) & 0xfffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (28 - n)) & 0xfffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (28 - n)) & 0xfffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (28 - n)) & 0xfffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (28 - n)) & 0xfffffff); - } - r[104] = (a[104] >> n) | ((a[105] << (28 - n)) & 0xfffffff); - r[105] = (a[105] >> n) | ((a[106] << (28 - n)) & 0xfffffff); - r[106] = (a[106] >> n) | ((a[107] << (28 - n)) & 0xfffffff); - r[107] = (a[107] >> n) | ((a[108] << (28 - n)) & 0xfffffff); - r[108] = (a[108] >> n) | ((a[109] << (28 - n)) & 0xfffffff); - r[109] = (a[109] >> n) | ((a[110] << (28 - n)) & 0xfffffff); - r[110] = (a[110] >> n) | ((a[111] << (28 - n)) & 0xfffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (28 - n)) & 0xfffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (28 - n)) & 0xfffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (28 - n)) & 0xfffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (28 - n)) & 0xfffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (28 - n)) & 0xfffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (28 - n)) & 0xfffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (28 - n)) & 0xfffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (28 - n)) & 0xfffffff); + } + r[104] = (a[104] >> n) | (sp_digit)((a[105] << (28 - n)) & 0xfffffff); + r[105] = (a[105] >> n) | (sp_digit)((a[106] << (28 - n)) & 0xfffffff); + r[106] = (a[106] >> n) | (sp_digit)((a[107] << (28 - n)) & 0xfffffff); + r[107] = (a[107] >> n) | (sp_digit)((a[108] << (28 - n)) & 0xfffffff); + r[108] = (a[108] >> n) | (sp_digit)((a[109] << (28 - n)) & 0xfffffff); + r[109] = (a[109] >> n) | (sp_digit)((a[110] << (28 - n)) & 0xfffffff); + r[110] = (a[110] >> n) | (sp_digit)((a[111] << (28 - n)) & 0xfffffff); r[111] = a[111] >> n; } @@ -10743,8 +10717,7 @@ static int sp_3072_div_112(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10859,14 +10832,13 @@ static int sp_3072_mod_exp_112(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_112(t[0], m, mp); n = sp_3072_cmp_112(t[0], m); - sp_3072_cond_sub_112(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_112(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 112 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10950,13 +10922,12 @@ static int sp_3072_mod_exp_112(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_112(t[0], m, mp); n = sp_3072_cmp_112(t[0], m); - sp_3072_cond_sub_112(t[0], t[0], m, ~(n >> 31)); + sp_3072_cond_sub_112(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 112 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -11079,13 +11050,12 @@ static int sp_3072_mod_exp_112(sp_digit* r, const sp_digit* a, const sp_digit* e sp_3072_mont_reduce_112(rt, m, mp); n = sp_3072_cmp_112(rt, m); - sp_3072_cond_sub_112(rt, rt, m, ~(n >> 31)); + sp_3072_cond_sub_112(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 224); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -11206,8 +11176,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -11318,8 +11287,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -11689,7 +11657,7 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 56 * 13); @@ -11927,228 +11895,228 @@ SP_NOINLINE static void sp_3072_lshift_112(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[111]; r[112] = s >> (28U - n); s = (sp_int_digit)(a[111]); t = (sp_int_digit)(a[110]); - r[111] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[111] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[110]); t = (sp_int_digit)(a[109]); - r[110] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[110] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[109]); t = (sp_int_digit)(a[108]); - r[109] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[109] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[108]); t = (sp_int_digit)(a[107]); - r[108] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[108] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[107]); t = (sp_int_digit)(a[106]); - r[107] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[107] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[106]); t = (sp_int_digit)(a[105]); - r[106] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[106] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[105]); t = (sp_int_digit)(a[104]); - r[105] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[105] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[104]); t = (sp_int_digit)(a[103]); - r[104] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[104] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[103]); t = (sp_int_digit)(a[102]); - r[103] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[103] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[102]); t = (sp_int_digit)(a[101]); - r[102] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[102] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[101]); t = (sp_int_digit)(a[100]); - r[101] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[101] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[100]); t = (sp_int_digit)(a[99]); - r[100] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[100] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[99]); t = (sp_int_digit)(a[98]); - r[99] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[99] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[98]); t = (sp_int_digit)(a[97]); - r[98] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[98] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[97]); t = (sp_int_digit)(a[96]); - r[97] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[97] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[96]); t = (sp_int_digit)(a[95]); - r[96] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[96] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[95]); t = (sp_int_digit)(a[94]); - r[95] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[95] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[94]); t = (sp_int_digit)(a[93]); - r[94] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[94] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[93]); t = (sp_int_digit)(a[92]); - r[93] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[93] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[92]); t = (sp_int_digit)(a[91]); - r[92] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[92] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[91]); t = (sp_int_digit)(a[90]); - r[91] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[91] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[90]); t = (sp_int_digit)(a[89]); - r[90] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[90] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[89]); t = (sp_int_digit)(a[88]); - r[89] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[89] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[88]); t = (sp_int_digit)(a[87]); - r[88] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[88] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[87]); t = (sp_int_digit)(a[86]); - r[87] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[87] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[86]); t = (sp_int_digit)(a[85]); - r[86] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[86] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[85]); t = (sp_int_digit)(a[84]); - r[85] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[85] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[84]); t = (sp_int_digit)(a[83]); - r[84] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[84] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[83]); t = (sp_int_digit)(a[82]); - r[83] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[83] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[82]); t = (sp_int_digit)(a[81]); - r[82] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[82] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[81]); t = (sp_int_digit)(a[80]); - r[81] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[81] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[80]); t = (sp_int_digit)(a[79]); - r[80] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[80] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[79]); t = (sp_int_digit)(a[78]); - r[79] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[79] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[78]); t = (sp_int_digit)(a[77]); - r[78] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[78] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[77]); t = (sp_int_digit)(a[76]); - r[77] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[77] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[76]); t = (sp_int_digit)(a[75]); - r[76] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[76] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[75]); t = (sp_int_digit)(a[74]); - r[75] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[75] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[74]); t = (sp_int_digit)(a[73]); - r[74] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[74] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[73]); t = (sp_int_digit)(a[72]); - r[73] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[73] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[72]); t = (sp_int_digit)(a[71]); - r[72] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[72] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[71]); t = (sp_int_digit)(a[70]); - r[71] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[71] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[70]); t = (sp_int_digit)(a[69]); - r[70] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[70] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[69]); t = (sp_int_digit)(a[68]); - r[69] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[69] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[68]); t = (sp_int_digit)(a[67]); - r[68] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[68] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[67]); t = (sp_int_digit)(a[66]); - r[67] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[67] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[66]); t = (sp_int_digit)(a[65]); - r[66] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[66] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[65]); t = (sp_int_digit)(a[64]); - r[65] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[65] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[64]); t = (sp_int_digit)(a[63]); - r[64] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[64] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[63]); t = (sp_int_digit)(a[62]); - r[63] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[63] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[62]); t = (sp_int_digit)(a[61]); - r[62] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[62] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[61]); t = (sp_int_digit)(a[60]); - r[61] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[61] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[60]); t = (sp_int_digit)(a[59]); - r[60] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[60] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[59]); t = (sp_int_digit)(a[58]); - r[59] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[59] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[58]); t = (sp_int_digit)(a[57]); - r[58] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[58] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[57]); t = (sp_int_digit)(a[56]); - r[57] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[57] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[56]); t = (sp_int_digit)(a[55]); - r[56] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[56] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[55]); t = (sp_int_digit)(a[54]); - r[55] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[55] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[54]); t = (sp_int_digit)(a[53]); - r[54] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[54] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[53]); t = (sp_int_digit)(a[52]); - r[53] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[53] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[52]); t = (sp_int_digit)(a[51]); - r[52] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[52] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[51]); t = (sp_int_digit)(a[50]); - r[51] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[51] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[50]); t = (sp_int_digit)(a[49]); - r[50] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[50] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[49]); t = (sp_int_digit)(a[48]); - r[49] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[49] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[48]); t = (sp_int_digit)(a[47]); - r[48] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[48] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[47]); t = (sp_int_digit)(a[46]); - r[47] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[47] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[46]); t = (sp_int_digit)(a[45]); - r[46] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[46] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[45]); t = (sp_int_digit)(a[44]); - r[45] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[45] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[44]); t = (sp_int_digit)(a[43]); - r[44] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[44] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[43]); t = (sp_int_digit)(a[42]); - r[43] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[43] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[42]); t = (sp_int_digit)(a[41]); - r[42] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[42] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[41] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[40] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[39] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[38] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[37] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[36] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[35] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[34] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[33] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[32] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[31] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[30] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[29] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[28] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[27] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[26] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[25] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[24] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[23] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[22] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[21] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[20] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[19] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[18] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[17] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[16] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[15] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[14] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[13] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[12] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[11] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[10] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[9] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[8] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[7] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[6] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[5] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[4] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[3] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (28U - n))) & 0xfffffff; + r[2] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (28U - n))) & 0xfffffff; - r[0] = (a[0] << n) & 0xfffffff; + r[1] = (sp_digit)(((s << n) | (t >> (28U - n))) & 0xfffffff); + r[0] = (sp_digit)((a[0] << n) & 0xfffffff); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -12258,12 +12226,11 @@ static int sp_3072_mod_exp_2_112(sp_digit* r, const sp_digit* e, int bits, const sp_3072_mont_reduce_112(r, m, mp); n = sp_3072_cmp_112(r, m); - sp_3072_cond_sub_112(r, r, m, ~(n >> 31)); + sp_3072_cond_sub_112(r, r, m, (sp_digit)~(n >> 31)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12986,23 +12953,23 @@ SP_NOINLINE static void sp_4096_mul_add_71(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[68]) + r[68]; t[1] = (tb * a[69]) + r[69]; t[2] = (tb * a[70]) + r[70]; - r[68] = t[0] & 0x1fffffff; + r[68] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[69] = t[1] & 0x1fffffff; + r[69] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[70] = t[2] & 0x1fffffff; + r[70] = (sp_digit)(t[2] & 0x1fffffff); r[71] += (sp_digit)(t[2] >> 29); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -13019,7 +12986,7 @@ static void sp_4096_mont_shift_71(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[71]) << 11; for (i = 0; i < 70; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[72 + i]) << 11; } @@ -13042,11 +13009,11 @@ static void sp_4096_mont_reduce_71(sp_digit* a, const sp_digit* m, sp_digit mp) sp_4096_norm_71(a + 71); for (i=0; i<70; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_4096_mul_add_71(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffL); sp_4096_mul_add_71(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -13270,7 +13237,7 @@ SP_NOINLINE static void sp_4096_rshift_71(sp_digit* r, const sp_digit* a, int i; for (i=0; i<70; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } r[70] = a[70] >> n; } @@ -13447,8 +13414,7 @@ static int sp_4096_div_71(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13560,14 +13526,13 @@ static int sp_4096_mod_exp_71(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_71(t[0], m, mp); n = sp_4096_cmp_71(t[0], m); - sp_4096_cond_sub_71(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_71(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 71 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13651,13 +13616,12 @@ static int sp_4096_mod_exp_71(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_71(t[0], m, mp); n = sp_4096_cmp_71(t[0], m); - sp_4096_cond_sub_71(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_71(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 71 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13797,13 +13761,12 @@ static int sp_4096_mod_exp_71(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_71(rt, m, mp); n = sp_4096_cmp_71(rt, m); - sp_4096_cond_sub_71(rt, rt, m, ~(n >> 31)); + sp_4096_cond_sub_71(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 142); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -13923,20 +13886,20 @@ SP_NOINLINE static void sp_4096_mul_add_142(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[140]) + r[140]; t[1] = (tb * a[141]) + r[141]; - r[140] = t[0] & 0x1fffffff; + r[140] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[141] = t[1] & 0x1fffffff; + r[141] = (sp_digit)(t[1] & 0x1fffffff); r[142] += (sp_digit)(t[1] >> 29); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -13953,7 +13916,7 @@ static void sp_4096_mont_shift_142(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[142]) << 22; for (i = 0; i < 141; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[143 + i]) << 22; } @@ -13978,33 +13941,33 @@ static void sp_4096_mont_reduce_142(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<141; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x7fL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x7fL); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } else { for (i=0; i<141; i++) { - mu = a[i] & 0x1fffffff; + mu = (sp_digit)(a[i] & 0x1fffffff); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = a[i] & 0x7fL; + mu = (sp_digit)(a[i] & 0x7fL); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; } #else for (i=0; i<141; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x7fL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x7fL); sp_4096_mul_add_142(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -14110,7 +14073,7 @@ SP_NOINLINE static void sp_4096_rshift_142(sp_digit* r, const sp_digit* a, int i; for (i=0; i<141; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } r[141] = a[141] >> n; } @@ -14287,8 +14250,7 @@ static int sp_4096_div_142(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -14401,14 +14363,13 @@ static int sp_4096_mod_exp_142(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_142(t[0], m, mp); n = sp_4096_cmp_142(t[0], m); - sp_4096_cond_sub_142(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_142(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 142 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -14492,13 +14453,12 @@ static int sp_4096_mod_exp_142(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_142(t[0], m, mp); n = sp_4096_cmp_142(t[0], m); - sp_4096_cond_sub_142(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_142(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 142 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -14621,13 +14581,12 @@ static int sp_4096_mod_exp_142(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_142(rt, m, mp); n = sp_4096_cmp_142(rt, m); - sp_4096_cond_sub_142(rt, rt, m, ~(n >> 31)); + sp_4096_cond_sub_142(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 284); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -14746,8 +14705,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -14858,8 +14816,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -15229,7 +15186,7 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 71 * 13); @@ -15465,9 +15422,9 @@ SP_NOINLINE static void sp_4096_lshift_142(sp_digit* r, const sp_digit* a, r[142] = a[141] >> (29 - n); for (i=141; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff); } - r[0] = (a[0] << n) & 0x1fffffff; + r[0] = (sp_digit)((a[0] << n) & 0x1fffffff); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -15577,12 +15534,11 @@ static int sp_4096_mod_exp_2_142(sp_digit* r, const sp_digit* e, int bits, const sp_4096_mont_reduce_142(r, m, mp); n = sp_4096_cmp_142(r, m); - sp_4096_cond_sub_142(r, r, m, ~(n >> 31)); + sp_4096_cond_sub_142(r, r, m, (sp_digit)~(n >> 31)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15965,29 +15921,29 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_uint64)a[ 0]) * b[ 0]; t1 = ((sp_uint64)a[ 0]) * b[ 1] + ((sp_uint64)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 0] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 0]) * b[ 2] + ((sp_uint64)a[ 1]) * b[ 1] + ((sp_uint64)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 1] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 0]) * b[ 3] + ((sp_uint64)a[ 1]) * b[ 2] + ((sp_uint64)a[ 2]) * b[ 1] + ((sp_uint64)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 2] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 0]) * b[ 4] + ((sp_uint64)a[ 1]) * b[ 3] + ((sp_uint64)a[ 2]) * b[ 2] + ((sp_uint64)a[ 3]) * b[ 1] + ((sp_uint64)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 3] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 0]) * b[ 5] + ((sp_uint64)a[ 1]) * b[ 4] + ((sp_uint64)a[ 2]) * b[ 3] + ((sp_uint64)a[ 3]) * b[ 2] + ((sp_uint64)a[ 4]) * b[ 1] + ((sp_uint64)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 4] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 0]) * b[ 6] + ((sp_uint64)a[ 1]) * b[ 5] + ((sp_uint64)a[ 2]) * b[ 4] @@ -15995,7 +15951,7 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 4]) * b[ 2] + ((sp_uint64)a[ 5]) * b[ 1] + ((sp_uint64)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 5] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 0]) * b[ 7] + ((sp_uint64)a[ 1]) * b[ 6] + ((sp_uint64)a[ 2]) * b[ 5] @@ -16004,7 +15960,7 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 5]) * b[ 2] + ((sp_uint64)a[ 6]) * b[ 1] + ((sp_uint64)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 6] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 0]) * b[ 8] + ((sp_uint64)a[ 1]) * b[ 7] + ((sp_uint64)a[ 2]) * b[ 6] @@ -16014,7 +15970,7 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 6]) * b[ 2] + ((sp_uint64)a[ 7]) * b[ 1] + ((sp_uint64)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 7] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 1]) * b[ 8] + ((sp_uint64)a[ 2]) * b[ 7] + ((sp_uint64)a[ 3]) * b[ 6] @@ -16023,7 +15979,7 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 6]) * b[ 3] + ((sp_uint64)a[ 7]) * b[ 2] + ((sp_uint64)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 8] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 2]) * b[ 8] + ((sp_uint64)a[ 3]) * b[ 7] + ((sp_uint64)a[ 4]) * b[ 6] @@ -16031,35 +15987,35 @@ SP_NOINLINE static void sp_4096_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint64)a[ 6]) * b[ 4] + ((sp_uint64)a[ 7]) * b[ 3] + ((sp_uint64)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[ 9] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 3]) * b[ 8] + ((sp_uint64)a[ 4]) * b[ 7] + ((sp_uint64)a[ 5]) * b[ 6] + ((sp_uint64)a[ 6]) * b[ 5] + ((sp_uint64)a[ 7]) * b[ 4] + ((sp_uint64)a[ 8]) * b[ 3]; - r[10] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[10] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 4]) * b[ 8] + ((sp_uint64)a[ 5]) * b[ 7] + ((sp_uint64)a[ 6]) * b[ 6] + ((sp_uint64)a[ 7]) * b[ 5] + ((sp_uint64)a[ 8]) * b[ 4]; - r[11] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[11] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 5]) * b[ 8] + ((sp_uint64)a[ 6]) * b[ 7] + ((sp_uint64)a[ 7]) * b[ 6] + ((sp_uint64)a[ 8]) * b[ 5]; - r[12] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[12] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 6]) * b[ 8] + ((sp_uint64)a[ 7]) * b[ 7] + ((sp_uint64)a[ 8]) * b[ 6]; - r[13] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[13] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_uint64)a[ 7]) * b[ 8] + ((sp_uint64)a[ 8]) * b[ 7]; - r[14] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[14] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 8]) * b[ 8]; - r[15] = t1 & 0x3ffffff; t0 += t1 >> 26; - r[16] = t0 & 0x3ffffff; + r[15] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; + r[16] = (sp_digit)(t0 & 0x3ffffff); r[17] = (sp_digit)(t0 >> 26); XMEMCPY(r, t, sizeof(t)); } @@ -16573,66 +16529,66 @@ SP_NOINLINE static void sp_4096_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_uint64)a[ 0]) * a[ 0]; t1 = (((sp_uint64)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 0] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 0]) * a[ 2]) * 2 + ((sp_uint64)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 1] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 0]) * a[ 3] + ((sp_uint64)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 2] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 0]) * a[ 4] + ((sp_uint64)a[ 1]) * a[ 3]) * 2 + ((sp_uint64)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 3] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 0]) * a[ 5] + ((sp_uint64)a[ 1]) * a[ 4] + ((sp_uint64)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 4] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 0]) * a[ 6] + ((sp_uint64)a[ 1]) * a[ 5] + ((sp_uint64)a[ 2]) * a[ 4]) * 2 + ((sp_uint64)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 5] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 0]) * a[ 7] + ((sp_uint64)a[ 1]) * a[ 6] + ((sp_uint64)a[ 2]) * a[ 5] + ((sp_uint64)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 6] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 0]) * a[ 8] + ((sp_uint64)a[ 1]) * a[ 7] + ((sp_uint64)a[ 2]) * a[ 6] + ((sp_uint64)a[ 3]) * a[ 5]) * 2 + ((sp_uint64)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 7] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 1]) * a[ 8] + ((sp_uint64)a[ 2]) * a[ 7] + ((sp_uint64)a[ 3]) * a[ 6] + ((sp_uint64)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 8] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 2]) * a[ 8] + ((sp_uint64)a[ 3]) * a[ 7] + ((sp_uint64)a[ 4]) * a[ 6]) * 2 + ((sp_uint64)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[ 9] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 3]) * a[ 8] + ((sp_uint64)a[ 4]) * a[ 7] + ((sp_uint64)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[10] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 4]) * a[ 8] + ((sp_uint64)a[ 5]) * a[ 7]) * 2 + ((sp_uint64)a[ 6]) * a[ 6]; - r[11] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[11] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 5]) * a[ 8] + ((sp_uint64)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[12] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_uint64)a[ 6]) * a[ 8]) * 2 + ((sp_uint64)a[ 7]) * a[ 7]; - r[13] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[13] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_uint64)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[14] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_uint64)a[ 8]) * a[ 8]; - r[15] = t1 & 0x3ffffff; t0 += t1 >> 26; - r[16] = t0 & 0x3ffffff; + r[15] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; + r[16] = (sp_digit)(t0 & 0x3ffffff); r[17] = (sp_digit)(t0 >> 26); XMEMCPY(r, t, sizeof(t)); } @@ -16980,25 +16936,25 @@ SP_NOINLINE static void sp_4096_mul_add_81(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0x3ffffff; + r[i+0] = (sp_digit)(t[0] & 0x3ffffff); t[1] += t[0] >> 26; - r[i+1] = t[1] & 0x3ffffff; + r[i+1] = (sp_digit)(t[1] & 0x3ffffff); t[2] += t[1] >> 26; - r[i+2] = t[2] & 0x3ffffff; + r[i+2] = (sp_digit)(t[2] & 0x3ffffff); t[3] += t[2] >> 26; - r[i+3] = t[3] & 0x3ffffff; + r[i+3] = (sp_digit)(t[3] & 0x3ffffff); t[4] += t[3] >> 26; - r[i+4] = t[4] & 0x3ffffff; + r[i+4] = (sp_digit)(t[4] & 0x3ffffff); t[5] += t[4] >> 26; - r[i+5] = t[5] & 0x3ffffff; + r[i+5] = (sp_digit)(t[5] & 0x3ffffff); t[6] += t[5] >> 26; - r[i+6] = t[6] & 0x3ffffff; + r[i+6] = (sp_digit)(t[6] & 0x3ffffff); t[7] += t[6] >> 26; - r[i+7] = t[7] & 0x3ffffff; + r[i+7] = (sp_digit)(t[7] & 0x3ffffff); t[0] = t[7] >> 26; } t[0] += (tb * a[80]) + r[80]; - r[80] = t[0] & 0x3ffffff; + r[80] = (sp_digit)(t[0] & 0x3ffffff); r[81] += (sp_digit)(t[0] >> 26); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -17014,29 +16970,29 @@ static void sp_4096_mont_shift_81(sp_digit* r, const sp_digit* a) sp_int64 n = a[78] >> 20; n += ((sp_int64)a[79]) << 6; for (i = 0; i < 72; i += 8) { - r[i + 0] = n & 0x3ffffff; + r[i + 0] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 80]) << 6; - r[i + 1] = n & 0x3ffffff; + r[i + 1] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 81]) << 6; - r[i + 2] = n & 0x3ffffff; + r[i + 2] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 82]) << 6; - r[i + 3] = n & 0x3ffffff; + r[i + 3] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 83]) << 6; - r[i + 4] = n & 0x3ffffff; + r[i + 4] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 84]) << 6; - r[i + 5] = n & 0x3ffffff; + r[i + 5] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 85]) << 6; - r[i + 6] = n & 0x3ffffff; + r[i + 6] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 86]) << 6; - r[i + 7] = n & 0x3ffffff; + r[i + 7] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 87]) << 6; } - r[72] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[152]) << 6; - r[73] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[153]) << 6; - r[74] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[154]) << 6; - r[75] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[155]) << 6; - r[76] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[156]) << 6; - r[77] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[157]) << 6; + r[72] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[152]) << 6; + r[73] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[153]) << 6; + r[74] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[154]) << 6; + r[75] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[155]) << 6; + r[76] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[156]) << 6; + r[77] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[157]) << 6; r[78] = (sp_digit)n; XMEMSET(&r[79], 0, sizeof(*r) * 79U); } @@ -17056,11 +17012,11 @@ static void sp_4096_mont_reduce_81(sp_digit* a, const sp_digit* m, sp_digit mp) sp_4096_norm_81(a + 79); for (i=0; i<78; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff); sp_4096_mul_add_81(a+i, m, mu); a[i+1] += a[i] >> 26; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL); sp_4096_mul_add_81(a+i, m, mu); a[i+1] += a[i] >> 26; a[i] &= 0x3ffffff; @@ -17177,14 +17133,14 @@ SP_NOINLINE static void sp_4096_rshift_81(sp_digit* r, const sp_digit* a, int i; for (i=0; i<80; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (26 - n)) & 0x3ffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (26 - n)) & 0x3ffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (26 - n)) & 0x3ffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (26 - n)) & 0x3ffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (26 - n)) & 0x3ffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (26 - n)) & 0x3ffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (26 - n)) & 0x3ffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (26 - n)) & 0x3ffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (26 - n)) & 0x3ffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (26 - n)) & 0x3ffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (26 - n)) & 0x3ffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (26 - n)) & 0x3ffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (26 - n)) & 0x3ffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (26 - n)) & 0x3ffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (26 - n)) & 0x3ffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (26 - n)) & 0x3ffffff); } r[80] = a[80] >> n; } @@ -17362,8 +17318,7 @@ static int sp_4096_div_81(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17475,14 +17430,13 @@ static int sp_4096_mod_exp_81(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_81(t[0], m, mp); n = sp_4096_cmp_81(t[0], m); - sp_4096_cond_sub_81(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_81(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 81 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17566,13 +17520,12 @@ static int sp_4096_mod_exp_81(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_81(t[0], m, mp); n = sp_4096_cmp_81(t[0], m); - sp_4096_cond_sub_81(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_81(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 81 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17712,13 +17665,12 @@ static int sp_4096_mod_exp_81(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_81(rt, m, mp); n = sp_4096_cmp_81(rt, m); - sp_4096_cond_sub_81(rt, rt, m, ~(n >> 31)); + sp_4096_cond_sub_81(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 162); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17858,28 +17810,28 @@ SP_NOINLINE static void sp_4096_mul_add_162(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0x3ffffff; + r[i+0] = (sp_digit)(t[0] & 0x3ffffff); t[1] += t[0] >> 26; - r[i+1] = t[1] & 0x3ffffff; + r[i+1] = (sp_digit)(t[1] & 0x3ffffff); t[2] += t[1] >> 26; - r[i+2] = t[2] & 0x3ffffff; + r[i+2] = (sp_digit)(t[2] & 0x3ffffff); t[3] += t[2] >> 26; - r[i+3] = t[3] & 0x3ffffff; + r[i+3] = (sp_digit)(t[3] & 0x3ffffff); t[4] += t[3] >> 26; - r[i+4] = t[4] & 0x3ffffff; + r[i+4] = (sp_digit)(t[4] & 0x3ffffff); t[5] += t[4] >> 26; - r[i+5] = t[5] & 0x3ffffff; + r[i+5] = (sp_digit)(t[5] & 0x3ffffff); t[6] += t[5] >> 26; - r[i+6] = t[6] & 0x3ffffff; + r[i+6] = (sp_digit)(t[6] & 0x3ffffff); t[7] += t[6] >> 26; - r[i+7] = t[7] & 0x3ffffff; + r[i+7] = (sp_digit)(t[7] & 0x3ffffff); t[0] = t[7] >> 26; } t[0] += (tb * a[160]) + r[160]; t[1] = (tb * a[161]) + r[161]; - r[160] = t[0] & 0x3ffffff; + r[160] = (sp_digit)(t[0] & 0x3ffffff); t[1] += t[0] >> 26; - r[161] = t[1] & 0x3ffffff; + r[161] = (sp_digit)(t[1] & 0x3ffffff); r[162] += (sp_digit)(t[1] >> 26); #endif /* !WOLFSSL_SP_LARGE_CODE */ } @@ -17895,28 +17847,28 @@ static void sp_4096_mont_shift_162(sp_digit* r, const sp_digit* a) sp_int64 n = a[157] >> 14; n += ((sp_int64)a[158]) << 12; for (i = 0; i < 152; i += 8) { - r[i + 0] = n & 0x3ffffff; + r[i + 0] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 159]) << 12; - r[i + 1] = n & 0x3ffffff; + r[i + 1] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 160]) << 12; - r[i + 2] = n & 0x3ffffff; + r[i + 2] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 161]) << 12; - r[i + 3] = n & 0x3ffffff; + r[i + 3] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 162]) << 12; - r[i + 4] = n & 0x3ffffff; + r[i + 4] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 163]) << 12; - r[i + 5] = n & 0x3ffffff; + r[i + 5] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 164]) << 12; - r[i + 6] = n & 0x3ffffff; + r[i + 6] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 165]) << 12; - r[i + 7] = n & 0x3ffffff; + r[i + 7] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[i + 166]) << 12; } - r[152] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[311]) << 12; - r[153] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[312]) << 12; - r[154] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[313]) << 12; - r[155] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[314]) << 12; - r[156] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[315]) << 12; + r[152] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[311]) << 12; + r[153] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[312]) << 12; + r[154] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[313]) << 12; + r[155] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[314]) << 12; + r[156] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[315]) << 12; r[157] = (sp_digit)n; XMEMSET(&r[158], 0, sizeof(*r) * 158U); } @@ -17938,33 +17890,33 @@ static void sp_4096_mont_reduce_162(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<157; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3fffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3fffL); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; a[i] &= 0x3ffffff; } else { for (i=0; i<157; i++) { - mu = a[i] & 0x3ffffff; + mu = (sp_digit)(a[i] & 0x3ffffff); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; } - mu = a[i] & 0x3fffL; + mu = (sp_digit)(a[i] & 0x3fffL); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; a[i] &= 0x3ffffff; } #else for (i=0; i<157; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3fffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3fffL); sp_4096_mul_add_162(a+i, m, mu); a[i+1] += a[i] >> 26; a[i] &= 0x3ffffff; @@ -18080,16 +18032,16 @@ SP_NOINLINE static void sp_4096_rshift_162(sp_digit* r, const sp_digit* a, int i; for (i=0; i<160; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (26 - n)) & 0x3ffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (26 - n)) & 0x3ffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (26 - n)) & 0x3ffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (26 - n)) & 0x3ffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (26 - n)) & 0x3ffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (26 - n)) & 0x3ffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (26 - n)) & 0x3ffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (26 - n)) & 0x3ffffff); - } - r[160] = (a[160] >> n) | ((a[161] << (26 - n)) & 0x3ffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (26 - n)) & 0x3ffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (26 - n)) & 0x3ffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (26 - n)) & 0x3ffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (26 - n)) & 0x3ffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (26 - n)) & 0x3ffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (26 - n)) & 0x3ffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (26 - n)) & 0x3ffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (26 - n)) & 0x3ffffff); + } + r[160] = (a[160] >> n) | (sp_digit)((a[161] << (26 - n)) & 0x3ffffff); r[161] = a[161] >> n; } @@ -18268,8 +18220,7 @@ static int sp_4096_div_162(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18384,14 +18335,13 @@ static int sp_4096_mod_exp_162(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_162(t[0], m, mp); n = sp_4096_cmp_162(t[0], m); - sp_4096_cond_sub_162(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_162(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 162 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18475,13 +18425,12 @@ static int sp_4096_mod_exp_162(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_162(t[0], m, mp); n = sp_4096_cmp_162(t[0], m); - sp_4096_cond_sub_162(t[0], t[0], m, ~(n >> 31)); + sp_4096_cond_sub_162(t[0], t[0], m, (sp_digit)~(n >> 31)); XMEMCPY(r, t[0], sizeof(*r) * 162 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18604,13 +18553,12 @@ static int sp_4096_mod_exp_162(sp_digit* r, const sp_digit* a, const sp_digit* e sp_4096_mont_reduce_162(rt, m, mp); n = sp_4096_cmp_162(rt, m); - sp_4096_cond_sub_162(rt, rt, m, ~(n >> 31)); + sp_4096_cond_sub_162(rt, rt, m, (sp_digit)~(n >> 31)); XMEMCPY(r, rt, sizeof(sp_digit) * 324); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18731,8 +18679,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -18843,8 +18790,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -19214,7 +19160,7 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 81 * 13); @@ -19452,328 +19398,328 @@ SP_NOINLINE static void sp_4096_lshift_162(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[161]; r[162] = s >> (26U - n); s = (sp_int_digit)(a[161]); t = (sp_int_digit)(a[160]); - r[161] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[161] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[160]); t = (sp_int_digit)(a[159]); - r[160] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[160] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[159]); t = (sp_int_digit)(a[158]); - r[159] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[159] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[158]); t = (sp_int_digit)(a[157]); - r[158] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[158] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[157]); t = (sp_int_digit)(a[156]); - r[157] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[157] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[156]); t = (sp_int_digit)(a[155]); - r[156] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[156] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[155]); t = (sp_int_digit)(a[154]); - r[155] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[155] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[154]); t = (sp_int_digit)(a[153]); - r[154] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[154] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[153]); t = (sp_int_digit)(a[152]); - r[153] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[153] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[152]); t = (sp_int_digit)(a[151]); - r[152] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[152] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[151]); t = (sp_int_digit)(a[150]); - r[151] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[151] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[150]); t = (sp_int_digit)(a[149]); - r[150] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[150] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[149]); t = (sp_int_digit)(a[148]); - r[149] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[149] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[148]); t = (sp_int_digit)(a[147]); - r[148] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[148] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[147]); t = (sp_int_digit)(a[146]); - r[147] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[147] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[146]); t = (sp_int_digit)(a[145]); - r[146] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[146] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[145]); t = (sp_int_digit)(a[144]); - r[145] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[145] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[144]); t = (sp_int_digit)(a[143]); - r[144] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[144] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[143]); t = (sp_int_digit)(a[142]); - r[143] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[143] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[142]); t = (sp_int_digit)(a[141]); - r[142] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[142] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[141]); t = (sp_int_digit)(a[140]); - r[141] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[141] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[140]); t = (sp_int_digit)(a[139]); - r[140] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[140] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[139]); t = (sp_int_digit)(a[138]); - r[139] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[139] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[138]); t = (sp_int_digit)(a[137]); - r[138] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[138] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[137]); t = (sp_int_digit)(a[136]); - r[137] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[137] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[136]); t = (sp_int_digit)(a[135]); - r[136] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[136] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[135]); t = (sp_int_digit)(a[134]); - r[135] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[135] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[134]); t = (sp_int_digit)(a[133]); - r[134] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[134] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[133]); t = (sp_int_digit)(a[132]); - r[133] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[133] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[132]); t = (sp_int_digit)(a[131]); - r[132] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[132] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[131]); t = (sp_int_digit)(a[130]); - r[131] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[131] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[130]); t = (sp_int_digit)(a[129]); - r[130] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[130] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[129]); t = (sp_int_digit)(a[128]); - r[129] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[129] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[128]); t = (sp_int_digit)(a[127]); - r[128] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[128] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[127]); t = (sp_int_digit)(a[126]); - r[127] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[127] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[126]); t = (sp_int_digit)(a[125]); - r[126] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[126] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[125]); t = (sp_int_digit)(a[124]); - r[125] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[125] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[124]); t = (sp_int_digit)(a[123]); - r[124] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[124] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[123]); t = (sp_int_digit)(a[122]); - r[123] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[123] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[122]); t = (sp_int_digit)(a[121]); - r[122] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[122] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[121]); t = (sp_int_digit)(a[120]); - r[121] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[121] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[120]); t = (sp_int_digit)(a[119]); - r[120] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[120] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[119]); t = (sp_int_digit)(a[118]); - r[119] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[119] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[118]); t = (sp_int_digit)(a[117]); - r[118] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[118] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[117]); t = (sp_int_digit)(a[116]); - r[117] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[117] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[116]); t = (sp_int_digit)(a[115]); - r[116] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[116] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[115]); t = (sp_int_digit)(a[114]); - r[115] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[115] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[114]); t = (sp_int_digit)(a[113]); - r[114] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[114] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[113]); t = (sp_int_digit)(a[112]); - r[113] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[113] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[112]); t = (sp_int_digit)(a[111]); - r[112] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[112] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[111]); t = (sp_int_digit)(a[110]); - r[111] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[111] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[110]); t = (sp_int_digit)(a[109]); - r[110] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[110] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[109]); t = (sp_int_digit)(a[108]); - r[109] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[109] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[108]); t = (sp_int_digit)(a[107]); - r[108] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[108] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[107]); t = (sp_int_digit)(a[106]); - r[107] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[107] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[106]); t = (sp_int_digit)(a[105]); - r[106] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[106] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[105]); t = (sp_int_digit)(a[104]); - r[105] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[105] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[104]); t = (sp_int_digit)(a[103]); - r[104] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[104] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[103]); t = (sp_int_digit)(a[102]); - r[103] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[103] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[102]); t = (sp_int_digit)(a[101]); - r[102] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[102] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[101]); t = (sp_int_digit)(a[100]); - r[101] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[101] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[100]); t = (sp_int_digit)(a[99]); - r[100] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[100] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[99]); t = (sp_int_digit)(a[98]); - r[99] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[99] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[98]); t = (sp_int_digit)(a[97]); - r[98] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[98] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[97]); t = (sp_int_digit)(a[96]); - r[97] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[97] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[96]); t = (sp_int_digit)(a[95]); - r[96] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[96] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[95]); t = (sp_int_digit)(a[94]); - r[95] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[95] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[94]); t = (sp_int_digit)(a[93]); - r[94] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[94] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[93]); t = (sp_int_digit)(a[92]); - r[93] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[93] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[92]); t = (sp_int_digit)(a[91]); - r[92] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[92] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[91]); t = (sp_int_digit)(a[90]); - r[91] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[91] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[90]); t = (sp_int_digit)(a[89]); - r[90] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[90] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[89]); t = (sp_int_digit)(a[88]); - r[89] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[89] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[88]); t = (sp_int_digit)(a[87]); - r[88] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[88] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[87]); t = (sp_int_digit)(a[86]); - r[87] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[87] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[86]); t = (sp_int_digit)(a[85]); - r[86] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[86] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[85]); t = (sp_int_digit)(a[84]); - r[85] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[85] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[84]); t = (sp_int_digit)(a[83]); - r[84] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[84] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[83]); t = (sp_int_digit)(a[82]); - r[83] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[83] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[82]); t = (sp_int_digit)(a[81]); - r[82] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[82] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[81]); t = (sp_int_digit)(a[80]); - r[81] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[81] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[80]); t = (sp_int_digit)(a[79]); - r[80] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[80] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[79]); t = (sp_int_digit)(a[78]); - r[79] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[79] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[78]); t = (sp_int_digit)(a[77]); - r[78] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[78] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[77]); t = (sp_int_digit)(a[76]); - r[77] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[77] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[76]); t = (sp_int_digit)(a[75]); - r[76] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[76] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[75]); t = (sp_int_digit)(a[74]); - r[75] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[75] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[74]); t = (sp_int_digit)(a[73]); - r[74] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[74] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[73]); t = (sp_int_digit)(a[72]); - r[73] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[73] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[72]); t = (sp_int_digit)(a[71]); - r[72] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[72] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[71]); t = (sp_int_digit)(a[70]); - r[71] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[71] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[70]); t = (sp_int_digit)(a[69]); - r[70] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[70] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[69]); t = (sp_int_digit)(a[68]); - r[69] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[69] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[68]); t = (sp_int_digit)(a[67]); - r[68] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[68] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[67]); t = (sp_int_digit)(a[66]); - r[67] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[67] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[66]); t = (sp_int_digit)(a[65]); - r[66] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[66] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[65]); t = (sp_int_digit)(a[64]); - r[65] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[65] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[64]); t = (sp_int_digit)(a[63]); - r[64] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[64] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[63]); t = (sp_int_digit)(a[62]); - r[63] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[63] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[62]); t = (sp_int_digit)(a[61]); - r[62] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[62] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[61]); t = (sp_int_digit)(a[60]); - r[61] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[61] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[60]); t = (sp_int_digit)(a[59]); - r[60] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[60] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[59]); t = (sp_int_digit)(a[58]); - r[59] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[59] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[58]); t = (sp_int_digit)(a[57]); - r[58] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[58] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[57]); t = (sp_int_digit)(a[56]); - r[57] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[57] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[56]); t = (sp_int_digit)(a[55]); - r[56] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[56] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[55]); t = (sp_int_digit)(a[54]); - r[55] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[55] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[54]); t = (sp_int_digit)(a[53]); - r[54] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[54] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[53]); t = (sp_int_digit)(a[52]); - r[53] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[53] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[52]); t = (sp_int_digit)(a[51]); - r[52] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[52] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[51]); t = (sp_int_digit)(a[50]); - r[51] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[51] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[50]); t = (sp_int_digit)(a[49]); - r[50] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[50] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[49]); t = (sp_int_digit)(a[48]); - r[49] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[49] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[48]); t = (sp_int_digit)(a[47]); - r[48] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[48] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[47]); t = (sp_int_digit)(a[46]); - r[47] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[47] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[46]); t = (sp_int_digit)(a[45]); - r[46] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[46] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[45]); t = (sp_int_digit)(a[44]); - r[45] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[45] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[44]); t = (sp_int_digit)(a[43]); - r[44] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[44] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[43]); t = (sp_int_digit)(a[42]); - r[43] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[43] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[42]); t = (sp_int_digit)(a[41]); - r[42] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[42] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[41] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[40] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[39] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[38] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[37] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[36] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[35] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[34] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[33] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[32] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[31] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[30] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[29] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[28] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[27] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[26] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[25] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[24] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[23] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[22] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[21] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[20] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[19] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[18] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[17] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[16] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[15] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[14] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[13] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[12] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[11] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[10] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[9] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[8] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[7] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[6] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[5] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[4] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[3] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[2] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; - r[0] = (a[0] << n) & 0x3ffffff; + r[1] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); + r[0] = (sp_digit)((a[0] << n) & 0x3ffffff); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -19883,12 +19829,11 @@ static int sp_4096_mod_exp_2_162(sp_digit* r, const sp_digit* e, int bits, const sp_4096_mont_reduce_162(r, m, mp); n = sp_4096_cmp_162(r, m); - sp_4096_cond_sub_162(r, r, m, ~(n >> 31)); + sp_4096_cond_sub_162(r, r, m, (sp_digit)~(n >> 31)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20139,29 +20084,29 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_int64)a[ 0]) * b[ 0]; t1 = ((sp_int64)a[ 0]) * b[ 1] + ((sp_int64)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 0] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 0]) * b[ 2] + ((sp_int64)a[ 1]) * b[ 1] + ((sp_int64)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 1] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 0]) * b[ 3] + ((sp_int64)a[ 1]) * b[ 2] + ((sp_int64)a[ 2]) * b[ 1] + ((sp_int64)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 2] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 0]) * b[ 4] + ((sp_int64)a[ 1]) * b[ 3] + ((sp_int64)a[ 2]) * b[ 2] + ((sp_int64)a[ 3]) * b[ 1] + ((sp_int64)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 3] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 0]) * b[ 5] + ((sp_int64)a[ 1]) * b[ 4] + ((sp_int64)a[ 2]) * b[ 3] + ((sp_int64)a[ 3]) * b[ 2] + ((sp_int64)a[ 4]) * b[ 1] + ((sp_int64)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 4] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 0]) * b[ 6] + ((sp_int64)a[ 1]) * b[ 5] + ((sp_int64)a[ 2]) * b[ 4] @@ -20169,7 +20114,7 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 4]) * b[ 2] + ((sp_int64)a[ 5]) * b[ 1] + ((sp_int64)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 5] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 0]) * b[ 7] + ((sp_int64)a[ 1]) * b[ 6] + ((sp_int64)a[ 2]) * b[ 5] @@ -20178,7 +20123,7 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 5]) * b[ 2] + ((sp_int64)a[ 6]) * b[ 1] + ((sp_int64)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 6] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 0]) * b[ 8] + ((sp_int64)a[ 1]) * b[ 7] + ((sp_int64)a[ 2]) * b[ 6] @@ -20188,7 +20133,7 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 6]) * b[ 2] + ((sp_int64)a[ 7]) * b[ 1] + ((sp_int64)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 7] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 1]) * b[ 8] + ((sp_int64)a[ 2]) * b[ 7] + ((sp_int64)a[ 3]) * b[ 6] @@ -20197,7 +20142,7 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 6]) * b[ 3] + ((sp_int64)a[ 7]) * b[ 2] + ((sp_int64)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 8] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 2]) * b[ 8] + ((sp_int64)a[ 3]) * b[ 7] + ((sp_int64)a[ 4]) * b[ 6] @@ -20205,35 +20150,35 @@ SP_NOINLINE static void sp_256_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 6]) * b[ 4] + ((sp_int64)a[ 7]) * b[ 3] + ((sp_int64)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[ 9] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 3]) * b[ 8] + ((sp_int64)a[ 4]) * b[ 7] + ((sp_int64)a[ 5]) * b[ 6] + ((sp_int64)a[ 6]) * b[ 5] + ((sp_int64)a[ 7]) * b[ 4] + ((sp_int64)a[ 8]) * b[ 3]; - r[10] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[10] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 4]) * b[ 8] + ((sp_int64)a[ 5]) * b[ 7] + ((sp_int64)a[ 6]) * b[ 6] + ((sp_int64)a[ 7]) * b[ 5] + ((sp_int64)a[ 8]) * b[ 4]; - r[11] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[11] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 5]) * b[ 8] + ((sp_int64)a[ 6]) * b[ 7] + ((sp_int64)a[ 7]) * b[ 6] + ((sp_int64)a[ 8]) * b[ 5]; - r[12] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[12] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 6]) * b[ 8] + ((sp_int64)a[ 7]) * b[ 7] + ((sp_int64)a[ 8]) * b[ 6]; - r[13] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[13] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = ((sp_int64)a[ 7]) * b[ 8] + ((sp_int64)a[ 8]) * b[ 7]; - r[14] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[14] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 8]) * b[ 8]; - r[15] = t1 & 0x1fffffff; t0 += t1 >> 29; - r[16] = t0 & 0x1fffffff; + r[15] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; + r[16] = (sp_digit)(t0 & 0x1fffffff); r[17] = (sp_digit)(t0 >> 29); XMEMCPY(r, t, sizeof(t)); } @@ -20295,66 +20240,66 @@ SP_NOINLINE static void sp_256_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_int64)a[ 0]) * a[ 0]; t1 = (((sp_int64)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 0] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 0]) * a[ 2]) * 2 + ((sp_int64)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 1] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 0]) * a[ 3] + ((sp_int64)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 2] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 0]) * a[ 4] + ((sp_int64)a[ 1]) * a[ 3]) * 2 + ((sp_int64)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 3] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 0]) * a[ 5] + ((sp_int64)a[ 1]) * a[ 4] + ((sp_int64)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 4] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 0]) * a[ 6] + ((sp_int64)a[ 1]) * a[ 5] + ((sp_int64)a[ 2]) * a[ 4]) * 2 + ((sp_int64)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 5] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 0]) * a[ 7] + ((sp_int64)a[ 1]) * a[ 6] + ((sp_int64)a[ 2]) * a[ 5] + ((sp_int64)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 6] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 0]) * a[ 8] + ((sp_int64)a[ 1]) * a[ 7] + ((sp_int64)a[ 2]) * a[ 6] + ((sp_int64)a[ 3]) * a[ 5]) * 2 + ((sp_int64)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1fffffff; t0 += t1 >> 29; + t[ 7] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 1]) * a[ 8] + ((sp_int64)a[ 2]) * a[ 7] + ((sp_int64)a[ 3]) * a[ 6] + ((sp_int64)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1fffffff; t1 += t0 >> 29; + t[ 8] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 2]) * a[ 8] + ((sp_int64)a[ 3]) * a[ 7] + ((sp_int64)a[ 4]) * a[ 6]) * 2 + ((sp_int64)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[ 9] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 3]) * a[ 8] + ((sp_int64)a[ 4]) * a[ 7] + ((sp_int64)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[10] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 4]) * a[ 8] + ((sp_int64)a[ 5]) * a[ 7]) * 2 + ((sp_int64)a[ 6]) * a[ 6]; - r[11] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[11] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 5]) * a[ 8] + ((sp_int64)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[12] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = (((sp_int64)a[ 6]) * a[ 8]) * 2 + ((sp_int64)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1fffffff; t0 += t1 >> 29; + r[13] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; t1 = (((sp_int64)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1fffffff; t1 += t0 >> 29; + r[14] = (sp_digit)(t0 & 0x1fffffff); t1 += t0 >> 29; t0 = ((sp_int64)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1fffffff; t0 += t1 >> 29; - r[16] = t0 & 0x1fffffff; + r[15] = (sp_digit)(t1 & 0x1fffffff); t0 += t1 >> 29; + r[16] = (sp_digit)(t0 & 0x1fffffff); r[17] = (sp_digit)(t0 >> 29); XMEMCPY(r, t, sizeof(t)); } @@ -20734,17 +20679,17 @@ SP_NOINLINE static void sp_256_mul_add_9(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[0] = t[3] >> 29; } t[0] += (tb * a[8]) + r[8]; - r[8] = t[0] & 0x1fffffff; + r[8] = (sp_digit)(t[0] & 0x1fffffff); r[9] += (sp_digit)(t[0] >> 29); #else sp_int64 tb = b; @@ -20761,25 +20706,25 @@ SP_NOINLINE static void sp_256_mul_add_9(sp_digit* r, const sp_digit* a, t[5] = (tb * a[i+5]) + r[i+5]; t[6] = (tb * a[i+6]) + r[i+6]; t[7] = (tb * a[i+7]) + r[i+7]; - r[i+0] = t[0] & 0x1fffffff; + r[i+0] = (sp_digit)(t[0] & 0x1fffffff); t[1] += t[0] >> 29; - r[i+1] = t[1] & 0x1fffffff; + r[i+1] = (sp_digit)(t[1] & 0x1fffffff); t[2] += t[1] >> 29; - r[i+2] = t[2] & 0x1fffffff; + r[i+2] = (sp_digit)(t[2] & 0x1fffffff); t[3] += t[2] >> 29; - r[i+3] = t[3] & 0x1fffffff; + r[i+3] = (sp_digit)(t[3] & 0x1fffffff); t[4] += t[3] >> 29; - r[i+4] = t[4] & 0x1fffffff; + r[i+4] = (sp_digit)(t[4] & 0x1fffffff); t[5] += t[4] >> 29; - r[i+5] = t[5] & 0x1fffffff; + r[i+5] = (sp_digit)(t[5] & 0x1fffffff); t[6] += t[5] >> 29; - r[i+6] = t[6] & 0x1fffffff; + r[i+6] = (sp_digit)(t[6] & 0x1fffffff); t[7] += t[6] >> 29; - r[i+7] = t[7] & 0x1fffffff; + r[i+7] = (sp_digit)(t[7] & 0x1fffffff); t[0] = t[7] >> 29; } t[0] += (tb * a[8]) + r[8]; - r[8] = t[0] & 0x1fffffff; + r[8] = (sp_digit)(t[0] & 0x1fffffff); r[9] += (sp_digit)(t[0] >> 29); #endif /* WOLFSSL_SP_SMALL */ #endif /* !WOLFSSL_SP_LARGE_CODE */ @@ -20822,7 +20767,7 @@ static void sp_256_mont_shift_9(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[9]) << 5; for (i = 0; i < 8; i++) { - r[i] = n & 0x1fffffff; + r[i] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[10 + i]) << 5; } @@ -20830,14 +20775,14 @@ static void sp_256_mont_shift_9(sp_digit* r, const sp_digit* a) #else sp_int64 n = a[8] >> 24; n += ((sp_int64)a[9]) << 5; - r[ 0] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[10]) << 5; - r[ 1] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[11]) << 5; - r[ 2] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[12]) << 5; - r[ 3] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[13]) << 5; - r[ 4] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[14]) << 5; - r[ 5] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[15]) << 5; - r[ 6] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[16]) << 5; - r[ 7] = n & 0x1fffffff; n >>= 29; n += ((sp_int64)a[17]) << 5; + r[ 0] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[10]) << 5; + r[ 1] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[11]) << 5; + r[ 2] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[12]) << 5; + r[ 3] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[13]) << 5; + r[ 4] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[14]) << 5; + r[ 5] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[15]) << 5; + r[ 6] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[16]) << 5; + r[ 7] = (sp_digit)(n & 0x1fffffff); n >>= 29; n += ((sp_int64)a[17]) << 5; r[8] = (sp_digit)n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[9], 0, sizeof(*r) * 9U); @@ -20858,11 +20803,11 @@ static void sp_256_mont_reduce_order_9(sp_digit* a, const sp_digit* m, sp_digit sp_256_norm_9(a + 9); for (i=0; i<8; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffff); sp_256_mul_add_9(a+i, m, mu); a[i+1] += a[i] >> 29; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xffffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xffffffL); sp_256_mul_add_9(a+i, m, mu); a[i+1] += a[i] >> 29; a[i] &= 0x1fffffff; @@ -20887,32 +20832,32 @@ static void sp_256_mont_reduce_9(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 8; i++) { - am = a[i] & 0x1fffffff; - a[i + 3] += (am << 9) & 0x1fffffff; + am = (sp_digit)(a[i] & 0x1fffffff); + a[i + 3] += (sp_digit)((am << 9) & 0x1fffffff); a[i + 4] += am >> 20; - a[i + 6] += (am << 18) & 0x1fffffff; - a[i + 7] += (am >> 11) - ((am << 21) & 0x1fffffff); - a[i + 8] += -(am >> 8) + ((am << 24) & 0x1fffffff); + a[i + 6] += (sp_digit)((am << 18) & 0x1fffffff); + a[i + 7] += (am >> 11) - (sp_digit)((am << 21) & 0x1fffffff); + a[i + 8] += -(am >> 8) + (sp_digit)((am << 24) & 0x1fffffff); a[i + 9] += am >> 5; a[i + 1] += a[i] >> 29; } - am = a[8] & 0xffffff; - a[8 + 3] += (am << 9) & 0x1fffffff; + am = (sp_digit)(a[8] & 0xffffff); + a[8 + 3] += (sp_digit)((am << 9) & 0x1fffffff); a[8 + 4] += am >> 20; - a[8 + 6] += (am << 18) & 0x1fffffff; - a[8 + 7] += (am >> 11) - ((am << 21) & 0x1fffffff); - a[8 + 8] += -(am >> 8) + ((am << 24) & 0x1fffffff); + a[8 + 6] += (sp_digit)((am << 18) & 0x1fffffff); + a[8 + 7] += (am >> 11) - (sp_digit)((am << 21) & 0x1fffffff); + a[8 + 8] += -(am >> 8) + (sp_digit)((am << 24) & 0x1fffffff); a[8 + 9] += am >> 5; - a[0] = (a[ 8] >> 24) + ((a[ 9] << 5) & 0x1fffffff); - a[1] = (a[ 9] >> 24) + ((a[10] << 5) & 0x1fffffff); - a[2] = (a[10] >> 24) + ((a[11] << 5) & 0x1fffffff); - a[3] = (a[11] >> 24) + ((a[12] << 5) & 0x1fffffff); - a[4] = (a[12] >> 24) + ((a[13] << 5) & 0x1fffffff); - a[5] = (a[13] >> 24) + ((a[14] << 5) & 0x1fffffff); - a[6] = (a[14] >> 24) + ((a[15] << 5) & 0x1fffffff); - a[7] = (a[15] >> 24) + ((a[16] << 5) & 0x1fffffff); + a[0] = (a[ 8] >> 24) + (sp_digit)((a[ 9] << 5) & 0x1fffffff); + a[1] = (a[ 9] >> 24) + (sp_digit)((a[10] << 5) & 0x1fffffff); + a[2] = (a[10] >> 24) + (sp_digit)((a[11] << 5) & 0x1fffffff); + a[3] = (a[11] >> 24) + (sp_digit)((a[12] << 5) & 0x1fffffff); + a[4] = (a[12] >> 24) + (sp_digit)((a[13] << 5) & 0x1fffffff); + a[5] = (a[13] >> 24) + (sp_digit)((a[14] << 5) & 0x1fffffff); + a[6] = (a[14] >> 24) + (sp_digit)((a[15] << 5) & 0x1fffffff); + a[7] = (a[15] >> 24) + (sp_digit)((a[16] << 5) & 0x1fffffff); a[8] = (a[16] >> 24) + (a[17] << 5); a[1] += a[0] >> 29; a[0] &= 0x1fffffff; @@ -20929,15 +20874,15 @@ static void sp_256_mont_reduce_9(sp_digit* a, const sp_digit* m, sp_digit mp) /* Create mask. */ am = 0 - am; - a[0] -= 0x1fffffff & am; - a[1] -= 0x1fffffff & am; - a[2] -= 0x1fffffff & am; - a[3] -= 0x000001ff & am; + a[0] -= (sp_digit)(0x1fffffff & am); + a[1] -= (sp_digit)(0x1fffffff & am); + a[2] -= (sp_digit)(0x1fffffff & am); + a[3] -= (sp_digit)(0x000001ff & am); /* p256_mod[4] is zero */ /* p256_mod[5] is zero */ - a[6] -= 0x00040000 & am; - a[7] -= 0x1fe00000 & am; - a[8] -= 0x00ffffff & am; + a[6] -= (sp_digit)(0x00040000 & am); + a[7] -= (sp_digit)(0x1fe00000 & am); + a[8] -= (sp_digit)(0x00ffffff & am); a[1] += a[0] >> 29; a[0] &= 0x1fffffff; a[2] += a[1] >> 29; a[1] &= 0x1fffffff; @@ -21099,7 +21044,7 @@ static void sp_256_map_9(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_9(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_9(r->x, p256_mod); - sp_256_cond_sub_9(r->x, r->x, p256_mod, ~(n >> 28)); + sp_256_cond_sub_9(r->x, r->x, p256_mod, (sp_digit)~(n >> 28)); sp_256_norm_9(r->x); /* y /= z^3 */ @@ -21108,7 +21053,7 @@ static void sp_256_map_9(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_9(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_9(r->y, p256_mod); - sp_256_cond_sub_9(r->y, r->y, p256_mod, ~(n >> 28)); + sp_256_cond_sub_9(r->y, r->y, p256_mod, (sp_digit)~(n >> 28)); sp_256_norm_9(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -21242,17 +21187,17 @@ SP_NOINLINE static void sp_256_rshift1_9(sp_digit* r, const sp_digit* a) int i; for (i=0; i<8; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 28) & 0x1fffffff); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 28) & 0x1fffffff); } #else - r[0] = (a[0] >> 1) + ((a[1] << 28) & 0x1fffffff); - r[1] = (a[1] >> 1) + ((a[2] << 28) & 0x1fffffff); - r[2] = (a[2] >> 1) + ((a[3] << 28) & 0x1fffffff); - r[3] = (a[3] >> 1) + ((a[4] << 28) & 0x1fffffff); - r[4] = (a[4] >> 1) + ((a[5] << 28) & 0x1fffffff); - r[5] = (a[5] >> 1) + ((a[6] << 28) & 0x1fffffff); - r[6] = (a[6] >> 1) + ((a[7] << 28) & 0x1fffffff); - r[7] = (a[7] >> 1) + ((a[8] << 28) & 0x1fffffff); + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 28) & 0x1fffffff); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 28) & 0x1fffffff); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 28) & 0x1fffffff); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 28) & 0x1fffffff); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 28) & 0x1fffffff); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 28) & 0x1fffffff); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 28) & 0x1fffffff); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 28) & 0x1fffffff); #endif r[8] = a[8] >> 1; } @@ -21563,8 +21508,8 @@ static void sp_256_proj_point_add_9(sp_point_256* r, sp_256_mont_sub_9(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -21581,7 +21526,7 @@ static void sp_256_proj_point_add_9(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -21755,8 +21700,8 @@ static int sp_256_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -21773,7 +21718,7 @@ static int sp_256_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -21907,8 +21852,7 @@ static int sp_256_mod_mul_norm_9(sp_digit* r, const sp_digit* a, const sp_digit* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -22483,7 +22427,7 @@ static void sp_256_ecc_recode_6_9(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 29) { y &= 0x3f; n >>= 6; @@ -22550,7 +22494,7 @@ static void sp_256_get_point_33_9(sp_point_256* r, const sp_point_256* table, r->z[7] = 0; r->z[8] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -22717,10 +22661,8 @@ static int sp_256_ecc_mulmod_win_add_sub_9(sp_point_256* r, const sp_point_256* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -22786,8 +22728,8 @@ static void sp_256_proj_point_add_qz1_9(sp_point_256* r, sp_256_mont_sub_9(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -22804,7 +22746,7 @@ static void sp_256_proj_point_add_qz1_9(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -22915,8 +22857,7 @@ static int sp_256_gen_stripe_table_9(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -22955,7 +22896,7 @@ static void sp_256_get_entry_256_9(sp_point_256* r, r->y[7] = 0; r->y[8] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -23084,10 +23025,8 @@ static int sp_256_ecc_mulmod_stripe_9(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -23305,10 +23244,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -23385,10 +23322,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24774,10 +24709,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24852,10 +24785,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24919,6 +24850,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -24935,6 +24867,11 @@ static int sp_256_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -25013,12 +24950,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25201,10 +25135,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25271,18 +25203,18 @@ SP_NOINLINE static void sp_256_rshift_9(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<8; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (29 - n))) & 0x1fffffff); } #else for (i=0; i<8; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (29 - n)) & 0x1fffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (29 - n)) & 0x1fffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (29 - n)) & 0x1fffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (29 - n)) & 0x1fffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (29 - n)) & 0x1fffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (29 - n)) & 0x1fffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (29 - n)) & 0x1fffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (29 - n)) & 0x1fffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (29 - n)) & 0x1fffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (29 - n)) & 0x1fffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (29 - n)) & 0x1fffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (29 - n)) & 0x1fffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (29 - n)) & 0x1fffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (29 - n)) & 0x1fffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (29 - n)) & 0x1fffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (29 - n)) & 0x1fffffff); } #endif /* WOLFSSL_SP_SMALL */ r[8] = a[8] >> n; @@ -25342,7 +25274,7 @@ SP_NOINLINE static void sp_256_lshift_18(sp_digit* r, const sp_digit* a, r[18] = a[17] >> (29 - n); for (i=17; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (29 - n))) & 0x1fffffff); } #else sp_int_digit s; @@ -25351,41 +25283,41 @@ SP_NOINLINE static void sp_256_lshift_18(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[17]; r[18] = s >> (29U - n); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[17] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[16] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[15] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[14] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[13] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[12] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[11] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[10] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[9] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[8] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[7] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[6] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[5] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[4] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[3] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[2] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (29U - n))) & 0x1fffffff; + r[1] = (sp_digit)(((s << n) | (t >> (29U - n))) & 0x1fffffff); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x1fffffff; + r[0] = (sp_digit)((a[0] << n) & 0x1fffffff); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -25449,8 +25381,7 @@ static int sp_256_div_9(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -26175,8 +26106,7 @@ static int sp_256_mod_inv_9(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 9); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26384,10 +26314,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26594,8 +26522,7 @@ static int sp_256_ecc_is_point_9(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26634,8 +26561,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26743,10 +26669,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26825,10 +26749,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26893,10 +26815,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26957,10 +26877,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27026,8 +26944,7 @@ static int sp_256_mont_sqrt_9(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27092,8 +27009,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27252,29 +27168,29 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, t0 = ((sp_int64)a[ 0]) * b[ 0]; t1 = ((sp_int64)a[ 0]) * b[ 1] + ((sp_int64)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 0] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[ 2] + ((sp_int64)a[ 1]) * b[ 1] + ((sp_int64)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 1] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[ 3] + ((sp_int64)a[ 1]) * b[ 2] + ((sp_int64)a[ 2]) * b[ 1] + ((sp_int64)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 2] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[ 4] + ((sp_int64)a[ 1]) * b[ 3] + ((sp_int64)a[ 2]) * b[ 2] + ((sp_int64)a[ 3]) * b[ 1] + ((sp_int64)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 3] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[ 5] + ((sp_int64)a[ 1]) * b[ 4] + ((sp_int64)a[ 2]) * b[ 3] + ((sp_int64)a[ 3]) * b[ 2] + ((sp_int64)a[ 4]) * b[ 1] + ((sp_int64)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 4] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[ 6] + ((sp_int64)a[ 1]) * b[ 5] + ((sp_int64)a[ 2]) * b[ 4] @@ -27282,7 +27198,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 4]) * b[ 2] + ((sp_int64)a[ 5]) * b[ 1] + ((sp_int64)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 5] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[ 7] + ((sp_int64)a[ 1]) * b[ 6] + ((sp_int64)a[ 2]) * b[ 5] @@ -27291,7 +27207,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 5]) * b[ 2] + ((sp_int64)a[ 6]) * b[ 1] + ((sp_int64)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 6] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[ 8] + ((sp_int64)a[ 1]) * b[ 7] + ((sp_int64)a[ 2]) * b[ 6] @@ -27301,7 +27217,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 6]) * b[ 2] + ((sp_int64)a[ 7]) * b[ 1] + ((sp_int64)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 7] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[ 9] + ((sp_int64)a[ 1]) * b[ 8] + ((sp_int64)a[ 2]) * b[ 7] @@ -27312,7 +27228,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 7]) * b[ 2] + ((sp_int64)a[ 8]) * b[ 1] + ((sp_int64)a[ 9]) * b[ 0]; - t[ 8] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 8] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[10] + ((sp_int64)a[ 1]) * b[ 9] + ((sp_int64)a[ 2]) * b[ 8] @@ -27324,7 +27240,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 8]) * b[ 2] + ((sp_int64)a[ 9]) * b[ 1] + ((sp_int64)a[10]) * b[ 0]; - t[ 9] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 9] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[11] + ((sp_int64)a[ 1]) * b[10] + ((sp_int64)a[ 2]) * b[ 9] @@ -27337,7 +27253,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 9]) * b[ 2] + ((sp_int64)a[10]) * b[ 1] + ((sp_int64)a[11]) * b[ 0]; - t[10] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[10] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[12] + ((sp_int64)a[ 1]) * b[11] + ((sp_int64)a[ 2]) * b[10] @@ -27351,7 +27267,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[10]) * b[ 2] + ((sp_int64)a[11]) * b[ 1] + ((sp_int64)a[12]) * b[ 0]; - t[11] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[11] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 0]) * b[13] + ((sp_int64)a[ 1]) * b[12] + ((sp_int64)a[ 2]) * b[11] @@ -27366,7 +27282,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[11]) * b[ 2] + ((sp_int64)a[12]) * b[ 1] + ((sp_int64)a[13]) * b[ 0]; - t[12] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[12] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 0]) * b[14] + ((sp_int64)a[ 1]) * b[13] + ((sp_int64)a[ 2]) * b[12] @@ -27382,7 +27298,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 2] + ((sp_int64)a[13]) * b[ 1] + ((sp_int64)a[14]) * b[ 0]; - t[13] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[13] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 1]) * b[14] + ((sp_int64)a[ 2]) * b[13] + ((sp_int64)a[ 3]) * b[12] @@ -27397,7 +27313,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 3] + ((sp_int64)a[13]) * b[ 2] + ((sp_int64)a[14]) * b[ 1]; - t[14] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[14] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 2]) * b[14] + ((sp_int64)a[ 3]) * b[13] + ((sp_int64)a[ 4]) * b[12] @@ -27411,7 +27327,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 4] + ((sp_int64)a[13]) * b[ 3] + ((sp_int64)a[14]) * b[ 2]; - r[15] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[15] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 3]) * b[14] + ((sp_int64)a[ 4]) * b[13] + ((sp_int64)a[ 5]) * b[12] @@ -27424,7 +27340,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 5] + ((sp_int64)a[13]) * b[ 4] + ((sp_int64)a[14]) * b[ 3]; - r[16] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[16] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 4]) * b[14] + ((sp_int64)a[ 5]) * b[13] + ((sp_int64)a[ 6]) * b[12] @@ -27436,7 +27352,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 6] + ((sp_int64)a[13]) * b[ 5] + ((sp_int64)a[14]) * b[ 4]; - r[17] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[17] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 5]) * b[14] + ((sp_int64)a[ 6]) * b[13] + ((sp_int64)a[ 7]) * b[12] @@ -27447,7 +27363,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 7] + ((sp_int64)a[13]) * b[ 6] + ((sp_int64)a[14]) * b[ 5]; - r[18] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[18] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 6]) * b[14] + ((sp_int64)a[ 7]) * b[13] + ((sp_int64)a[ 8]) * b[12] @@ -27457,7 +27373,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 8] + ((sp_int64)a[13]) * b[ 7] + ((sp_int64)a[14]) * b[ 6]; - r[19] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[19] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 7]) * b[14] + ((sp_int64)a[ 8]) * b[13] + ((sp_int64)a[ 9]) * b[12] @@ -27466,7 +27382,7 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[ 9] + ((sp_int64)a[13]) * b[ 8] + ((sp_int64)a[14]) * b[ 7]; - r[20] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[20] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[ 8]) * b[14] + ((sp_int64)a[ 9]) * b[13] + ((sp_int64)a[10]) * b[12] @@ -27474,35 +27390,35 @@ SP_NOINLINE static void sp_384_mul_15(sp_digit* r, const sp_digit* a, + ((sp_int64)a[12]) * b[10] + ((sp_int64)a[13]) * b[ 9] + ((sp_int64)a[14]) * b[ 8]; - r[21] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[21] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[ 9]) * b[14] + ((sp_int64)a[10]) * b[13] + ((sp_int64)a[11]) * b[12] + ((sp_int64)a[12]) * b[11] + ((sp_int64)a[13]) * b[10] + ((sp_int64)a[14]) * b[ 9]; - r[22] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[22] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[10]) * b[14] + ((sp_int64)a[11]) * b[13] + ((sp_int64)a[12]) * b[12] + ((sp_int64)a[13]) * b[11] + ((sp_int64)a[14]) * b[10]; - r[23] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[23] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[11]) * b[14] + ((sp_int64)a[12]) * b[13] + ((sp_int64)a[13]) * b[12] + ((sp_int64)a[14]) * b[11]; - r[24] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[24] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[12]) * b[14] + ((sp_int64)a[13]) * b[13] + ((sp_int64)a[14]) * b[12]; - r[25] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[25] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = ((sp_int64)a[13]) * b[14] + ((sp_int64)a[14]) * b[13]; - r[26] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[26] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[14]) * b[14]; - r[27] = t1 & 0x3ffffff; t0 += t1 >> 26; - r[28] = t0 & 0x3ffffff; + r[27] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; + r[28] = (sp_digit)(t0 & 0x3ffffff); r[29] = (sp_digit)(t0 >> 26); XMEMCPY(r, t, sizeof(t)); } @@ -27564,57 +27480,57 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) t0 = ((sp_int64)a[ 0]) * a[ 0]; t1 = (((sp_int64)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 0] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[ 2]) * 2 + ((sp_int64)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 1] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[ 3] + ((sp_int64)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 2] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[ 4] + ((sp_int64)a[ 1]) * a[ 3]) * 2 + ((sp_int64)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 3] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[ 5] + ((sp_int64)a[ 1]) * a[ 4] + ((sp_int64)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 4] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[ 6] + ((sp_int64)a[ 1]) * a[ 5] + ((sp_int64)a[ 2]) * a[ 4]) * 2 + ((sp_int64)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 5] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[ 7] + ((sp_int64)a[ 1]) * a[ 6] + ((sp_int64)a[ 2]) * a[ 5] + ((sp_int64)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 6] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[ 8] + ((sp_int64)a[ 1]) * a[ 7] + ((sp_int64)a[ 2]) * a[ 6] + ((sp_int64)a[ 3]) * a[ 5]) * 2 + ((sp_int64)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 7] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[ 9] + ((sp_int64)a[ 1]) * a[ 8] + ((sp_int64)a[ 2]) * a[ 7] + ((sp_int64)a[ 3]) * a[ 6] + ((sp_int64)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[ 8] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[10] + ((sp_int64)a[ 1]) * a[ 9] + ((sp_int64)a[ 2]) * a[ 8] + ((sp_int64)a[ 3]) * a[ 7] + ((sp_int64)a[ 4]) * a[ 6]) * 2 + ((sp_int64)a[ 5]) * a[ 5]; - t[ 9] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[ 9] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[11] + ((sp_int64)a[ 1]) * a[10] + ((sp_int64)a[ 2]) * a[ 9] + ((sp_int64)a[ 3]) * a[ 8] + ((sp_int64)a[ 4]) * a[ 7] + ((sp_int64)a[ 5]) * a[ 6]) * 2; - t[10] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[10] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[12] + ((sp_int64)a[ 1]) * a[11] + ((sp_int64)a[ 2]) * a[10] @@ -27622,7 +27538,7 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) + ((sp_int64)a[ 4]) * a[ 8] + ((sp_int64)a[ 5]) * a[ 7]) * 2 + ((sp_int64)a[ 6]) * a[ 6]; - t[11] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[11] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 0]) * a[13] + ((sp_int64)a[ 1]) * a[12] + ((sp_int64)a[ 2]) * a[11] @@ -27630,7 +27546,7 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) + ((sp_int64)a[ 4]) * a[ 9] + ((sp_int64)a[ 5]) * a[ 8] + ((sp_int64)a[ 6]) * a[ 7]) * 2; - t[12] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[12] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 0]) * a[14] + ((sp_int64)a[ 1]) * a[13] + ((sp_int64)a[ 2]) * a[12] @@ -27639,7 +27555,7 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) + ((sp_int64)a[ 5]) * a[ 9] + ((sp_int64)a[ 6]) * a[ 8]) * 2 + ((sp_int64)a[ 7]) * a[ 7]; - t[13] = t1 & 0x3ffffff; t0 += t1 >> 26; + t[13] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 1]) * a[14] + ((sp_int64)a[ 2]) * a[13] + ((sp_int64)a[ 3]) * a[12] @@ -27647,7 +27563,7 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) + ((sp_int64)a[ 5]) * a[10] + ((sp_int64)a[ 6]) * a[ 9] + ((sp_int64)a[ 7]) * a[ 8]) * 2; - t[14] = t0 & 0x3ffffff; t1 += t0 >> 26; + t[14] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 2]) * a[14] + ((sp_int64)a[ 3]) * a[13] + ((sp_int64)a[ 4]) * a[12] @@ -27655,62 +27571,62 @@ SP_NOINLINE static void sp_384_sqr_15(sp_digit* r, const sp_digit* a) + ((sp_int64)a[ 6]) * a[10] + ((sp_int64)a[ 7]) * a[ 9]) * 2 + ((sp_int64)a[ 8]) * a[ 8]; - r[15] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[15] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 3]) * a[14] + ((sp_int64)a[ 4]) * a[13] + ((sp_int64)a[ 5]) * a[12] + ((sp_int64)a[ 6]) * a[11] + ((sp_int64)a[ 7]) * a[10] + ((sp_int64)a[ 8]) * a[ 9]) * 2; - r[16] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[16] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 4]) * a[14] + ((sp_int64)a[ 5]) * a[13] + ((sp_int64)a[ 6]) * a[12] + ((sp_int64)a[ 7]) * a[11] + ((sp_int64)a[ 8]) * a[10]) * 2 + ((sp_int64)a[ 9]) * a[ 9]; - r[17] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[17] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 5]) * a[14] + ((sp_int64)a[ 6]) * a[13] + ((sp_int64)a[ 7]) * a[12] + ((sp_int64)a[ 8]) * a[11] + ((sp_int64)a[ 9]) * a[10]) * 2; - r[18] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[18] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 6]) * a[14] + ((sp_int64)a[ 7]) * a[13] + ((sp_int64)a[ 8]) * a[12] + ((sp_int64)a[ 9]) * a[11]) * 2 + ((sp_int64)a[10]) * a[10]; - r[19] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[19] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 7]) * a[14] + ((sp_int64)a[ 8]) * a[13] + ((sp_int64)a[ 9]) * a[12] + ((sp_int64)a[10]) * a[11]) * 2; - r[20] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[20] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[ 8]) * a[14] + ((sp_int64)a[ 9]) * a[13] + ((sp_int64)a[10]) * a[12]) * 2 + ((sp_int64)a[11]) * a[11]; - r[21] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[21] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[ 9]) * a[14] + ((sp_int64)a[10]) * a[13] + ((sp_int64)a[11]) * a[12]) * 2; - r[22] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[22] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[10]) * a[14] + ((sp_int64)a[11]) * a[13]) * 2 + ((sp_int64)a[12]) * a[12]; - r[23] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[23] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[11]) * a[14] + ((sp_int64)a[12]) * a[13]) * 2; - r[24] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[24] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = (((sp_int64)a[12]) * a[14]) * 2 + ((sp_int64)a[13]) * a[13]; - r[25] = t1 & 0x3ffffff; t0 += t1 >> 26; + r[25] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; t1 = (((sp_int64)a[13]) * a[14]) * 2; - r[26] = t0 & 0x3ffffff; t1 += t0 >> 26; + r[26] = (sp_digit)(t0 & 0x3ffffff); t1 += t0 >> 26; t0 = ((sp_int64)a[14]) * a[14]; - r[27] = t1 & 0x3ffffff; t0 += t1 >> 26; - r[28] = t0 & 0x3ffffff; + r[27] = (sp_digit)(t1 & 0x3ffffff); t0 += t1 >> 26; + r[28] = (sp_digit)(t0 & 0x3ffffff); r[29] = (sp_digit)(t0 >> 26); XMEMCPY(r, t, sizeof(t)); } @@ -28101,23 +28017,23 @@ SP_NOINLINE static void sp_384_mul_add_15(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x3ffffff; + r[i+0] = (sp_digit)(t[0] & 0x3ffffff); t[1] += t[0] >> 26; - r[i+1] = t[1] & 0x3ffffff; + r[i+1] = (sp_digit)(t[1] & 0x3ffffff); t[2] += t[1] >> 26; - r[i+2] = t[2] & 0x3ffffff; + r[i+2] = (sp_digit)(t[2] & 0x3ffffff); t[3] += t[2] >> 26; - r[i+3] = t[3] & 0x3ffffff; + r[i+3] = (sp_digit)(t[3] & 0x3ffffff); t[0] = t[3] >> 26; } t[0] += (tb * a[12]) + r[12]; t[1] = (tb * a[13]) + r[13]; t[2] = (tb * a[14]) + r[14]; - r[12] = t[0] & 0x3ffffff; + r[12] = (sp_digit)(t[0] & 0x3ffffff); t[1] += t[0] >> 26; - r[13] = t[1] & 0x3ffffff; + r[13] = (sp_digit)(t[1] & 0x3ffffff); t[2] += t[1] >> 26; - r[14] = t[2] & 0x3ffffff; + r[14] = (sp_digit)(t[2] & 0x3ffffff); r[15] += (sp_digit)(t[2] >> 26); #else sp_int64 tb = b; @@ -28200,7 +28116,7 @@ static void sp_384_mont_shift_15(sp_digit* r, const sp_digit* a) n += ((sp_int64)a[15]) << 6; for (i = 0; i < 14; i++) { - r[i] = n & 0x3ffffff; + r[i] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[16 + i]) << 6; } @@ -28208,20 +28124,20 @@ static void sp_384_mont_shift_15(sp_digit* r, const sp_digit* a) #else sp_int64 n = a[14] >> 20; n += ((sp_int64)a[15]) << 6; - r[ 0] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[16]) << 6; - r[ 1] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[17]) << 6; - r[ 2] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[18]) << 6; - r[ 3] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[19]) << 6; - r[ 4] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[20]) << 6; - r[ 5] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[21]) << 6; - r[ 6] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[22]) << 6; - r[ 7] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[23]) << 6; - r[ 8] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[24]) << 6; - r[ 9] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[25]) << 6; - r[10] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[26]) << 6; - r[11] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[27]) << 6; - r[12] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[28]) << 6; - r[13] = n & 0x3ffffff; n >>= 26; n += ((sp_int64)a[29]) << 6; + r[ 0] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[16]) << 6; + r[ 1] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[17]) << 6; + r[ 2] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[18]) << 6; + r[ 3] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[19]) << 6; + r[ 4] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[20]) << 6; + r[ 5] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[21]) << 6; + r[ 6] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[22]) << 6; + r[ 7] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[23]) << 6; + r[ 8] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[24]) << 6; + r[ 9] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[25]) << 6; + r[10] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[26]) << 6; + r[11] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[27]) << 6; + r[12] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[28]) << 6; + r[13] = (sp_digit)(n & 0x3ffffff); n >>= 26; n += ((sp_int64)a[29]) << 6; r[14] = (sp_digit)n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[15], 0, sizeof(*r) * 15U); @@ -28242,11 +28158,11 @@ static void sp_384_mont_reduce_order_15(sp_digit* a, const sp_digit* m, sp_digit sp_384_norm_15(a + 15); for (i=0; i<14; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x3ffffff); sp_384_mul_add_15(a+i, m, mu); a[i+1] += a[i] >> 26; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0xfffffL); sp_384_mul_add_15(a+i, m, mu); a[i+1] += a[i] >> 26; a[i] &= 0x3ffffff; @@ -28271,42 +28187,42 @@ static void sp_384_mont_reduce_15(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 14; i++) { - am = (a[i] * 0x1) & 0x3ffffff; - a[i + 1] += (am << 6) & 0x3ffffff; + am = (sp_digit)((a[i] * 0x1) & 0x3ffffff); + a[i + 1] += (sp_digit)((am << 6) & 0x3ffffff); a[i + 2] += am >> 20; - a[i + 3] -= (am << 18) & 0x3ffffff; + a[i + 3] -= (sp_digit)((am << 18) & 0x3ffffff); a[i + 4] -= am >> 8; - a[i + 4] -= (am << 24) & 0x3ffffff; + a[i + 4] -= (sp_digit)((am << 24) & 0x3ffffff); a[i + 5] -= am >> 2; - a[i + 14] += (am << 20) & 0x3ffffff; + a[i + 14] += (sp_digit)((am << 20) & 0x3ffffff); a[i + 15] += am >> 6; a[i + 1] += a[i] >> 26; } - am = (a[14] * 0x1) & 0xfffff; - a[14 + 1] += (am << 6) & 0x3ffffff; + am = (sp_digit)((a[14] * 0x1) & 0xfffff); + a[14 + 1] += (sp_digit)((am << 6) & 0x3ffffff); a[14 + 2] += am >> 20; - a[14 + 3] -= (am << 18) & 0x3ffffff; + a[14 + 3] -= (sp_digit)((am << 18) & 0x3ffffff); a[14 + 4] -= am >> 8; - a[14 + 4] -= (am << 24) & 0x3ffffff; + a[14 + 4] -= (sp_digit)((am << 24) & 0x3ffffff); a[14 + 5] -= am >> 2; - a[14 + 14] += (am << 20) & 0x3ffffff; + a[14 + 14] += (sp_digit)((am << 20) & 0x3ffffff); a[14 + 15] += am >> 6; - a[0] = (a[14] >> 20) + ((a[15] << 6) & 0x3ffffff); - a[1] = (a[15] >> 20) + ((a[16] << 6) & 0x3ffffff); - a[2] = (a[16] >> 20) + ((a[17] << 6) & 0x3ffffff); - a[3] = (a[17] >> 20) + ((a[18] << 6) & 0x3ffffff); - a[4] = (a[18] >> 20) + ((a[19] << 6) & 0x3ffffff); - a[5] = (a[19] >> 20) + ((a[20] << 6) & 0x3ffffff); - a[6] = (a[20] >> 20) + ((a[21] << 6) & 0x3ffffff); - a[7] = (a[21] >> 20) + ((a[22] << 6) & 0x3ffffff); - a[8] = (a[22] >> 20) + ((a[23] << 6) & 0x3ffffff); - a[9] = (a[23] >> 20) + ((a[24] << 6) & 0x3ffffff); - a[10] = (a[24] >> 20) + ((a[25] << 6) & 0x3ffffff); - a[11] = (a[25] >> 20) + ((a[26] << 6) & 0x3ffffff); - a[12] = (a[26] >> 20) + ((a[27] << 6) & 0x3ffffff); - a[13] = (a[27] >> 20) + ((a[28] << 6) & 0x3ffffff); + a[0] = (a[14] >> 20) + (sp_digit)((a[15] << 6) & 0x3ffffff); + a[1] = (a[15] >> 20) + (sp_digit)((a[16] << 6) & 0x3ffffff); + a[2] = (a[16] >> 20) + (sp_digit)((a[17] << 6) & 0x3ffffff); + a[3] = (a[17] >> 20) + (sp_digit)((a[18] << 6) & 0x3ffffff); + a[4] = (a[18] >> 20) + (sp_digit)((a[19] << 6) & 0x3ffffff); + a[5] = (a[19] >> 20) + (sp_digit)((a[20] << 6) & 0x3ffffff); + a[6] = (a[20] >> 20) + (sp_digit)((a[21] << 6) & 0x3ffffff); + a[7] = (a[21] >> 20) + (sp_digit)((a[22] << 6) & 0x3ffffff); + a[8] = (a[22] >> 20) + (sp_digit)((a[23] << 6) & 0x3ffffff); + a[9] = (a[23] >> 20) + (sp_digit)((a[24] << 6) & 0x3ffffff); + a[10] = (a[24] >> 20) + (sp_digit)((a[25] << 6) & 0x3ffffff); + a[11] = (a[25] >> 20) + (sp_digit)((a[26] << 6) & 0x3ffffff); + a[12] = (a[26] >> 20) + (sp_digit)((a[27] << 6) & 0x3ffffff); + a[13] = (a[27] >> 20) + (sp_digit)((a[28] << 6) & 0x3ffffff); a[14] = (a[14 + 14] >> 20) + (a[29] << 6); a[1] += a[0] >> 26; a[0] &= 0x3ffffff; @@ -28329,21 +28245,21 @@ static void sp_384_mont_reduce_15(sp_digit* a, const sp_digit* m, sp_digit mp) /* Create mask. */ am = 0 - am; - a[0] -= 0x03ffffff & am; - a[1] -= 0x0000003f & am; + a[0] -= (sp_digit)(0x03ffffff & am); + a[1] -= (sp_digit)(0x0000003f & am); /* p384_mod[2] is zero */ - a[3] -= 0x03fc0000 & am; - a[4] -= 0x02ffffff & am; - a[5] -= 0x03ffffff & am; - a[6] -= 0x03ffffff & am; - a[7] -= 0x03ffffff & am; - a[8] -= 0x03ffffff & am; - a[9] -= 0x03ffffff & am; - a[10] -= 0x03ffffff & am; - a[11] -= 0x03ffffff & am; - a[12] -= 0x03ffffff & am; - a[13] -= 0x03ffffff & am; - a[14] -= 0x000fffff & am; + a[3] -= (sp_digit)(0x03fc0000 & am); + a[4] -= (sp_digit)(0x02ffffff & am); + a[5] -= (sp_digit)(0x03ffffff & am); + a[6] -= (sp_digit)(0x03ffffff & am); + a[7] -= (sp_digit)(0x03ffffff & am); + a[8] -= (sp_digit)(0x03ffffff & am); + a[9] -= (sp_digit)(0x03ffffff & am); + a[10] -= (sp_digit)(0x03ffffff & am); + a[11] -= (sp_digit)(0x03ffffff & am); + a[12] -= (sp_digit)(0x03ffffff & am); + a[13] -= (sp_digit)(0x03ffffff & am); + a[14] -= (sp_digit)(0x000fffff & am); a[1] += a[0] >> 26; a[0] &= 0x3ffffff; a[2] += a[1] >> 26; a[1] &= 0x3ffffff; @@ -28527,7 +28443,7 @@ static void sp_384_map_15(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_15(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_15(r->x, p384_mod); - sp_384_cond_sub_15(r->x, r->x, p384_mod, ~(n >> 25)); + sp_384_cond_sub_15(r->x, r->x, p384_mod, (sp_digit)~(n >> 25)); sp_384_norm_15(r->x); /* y /= z^3 */ @@ -28536,7 +28452,7 @@ static void sp_384_map_15(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_15(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_15(r->y, p384_mod); - sp_384_cond_sub_15(r->y, r->y, p384_mod, ~(n >> 25)); + sp_384_cond_sub_15(r->y, r->y, p384_mod, (sp_digit)~(n >> 25)); sp_384_norm_15(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -28676,23 +28592,23 @@ SP_NOINLINE static void sp_384_rshift1_15(sp_digit* r, const sp_digit* a) int i; for (i=0; i<14; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 25) & 0x3ffffff); - } -#else - r[0] = (a[0] >> 1) + ((a[1] << 25) & 0x3ffffff); - r[1] = (a[1] >> 1) + ((a[2] << 25) & 0x3ffffff); - r[2] = (a[2] >> 1) + ((a[3] << 25) & 0x3ffffff); - r[3] = (a[3] >> 1) + ((a[4] << 25) & 0x3ffffff); - r[4] = (a[4] >> 1) + ((a[5] << 25) & 0x3ffffff); - r[5] = (a[5] >> 1) + ((a[6] << 25) & 0x3ffffff); - r[6] = (a[6] >> 1) + ((a[7] << 25) & 0x3ffffff); - r[7] = (a[7] >> 1) + ((a[8] << 25) & 0x3ffffff); - r[8] = (a[8] >> 1) + ((a[9] << 25) & 0x3ffffff); - r[9] = (a[9] >> 1) + ((a[10] << 25) & 0x3ffffff); - r[10] = (a[10] >> 1) + ((a[11] << 25) & 0x3ffffff); - r[11] = (a[11] >> 1) + ((a[12] << 25) & 0x3ffffff); - r[12] = (a[12] >> 1) + ((a[13] << 25) & 0x3ffffff); - r[13] = (a[13] >> 1) + ((a[14] << 25) & 0x3ffffff); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 25) & 0x3ffffff); + } +#else + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 25) & 0x3ffffff); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 25) & 0x3ffffff); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 25) & 0x3ffffff); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 25) & 0x3ffffff); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 25) & 0x3ffffff); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 25) & 0x3ffffff); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 25) & 0x3ffffff); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 25) & 0x3ffffff); + r[8] = (a[8] >> 1) + (sp_digit)((a[9] << 25) & 0x3ffffff); + r[9] = (a[9] >> 1) + (sp_digit)((a[10] << 25) & 0x3ffffff); + r[10] = (a[10] >> 1) + (sp_digit)((a[11] << 25) & 0x3ffffff); + r[11] = (a[11] >> 1) + (sp_digit)((a[12] << 25) & 0x3ffffff); + r[12] = (a[12] >> 1) + (sp_digit)((a[13] << 25) & 0x3ffffff); + r[13] = (a[13] >> 1) + (sp_digit)((a[14] << 25) & 0x3ffffff); #endif r[14] = a[14] >> 1; } @@ -29005,8 +28921,8 @@ static void sp_384_proj_point_add_15(sp_point_384* r, sp_384_mont_sub_15(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29023,7 +28939,7 @@ static void sp_384_proj_point_add_15(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -29197,8 +29113,8 @@ static int sp_384_proj_point_add_15_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29215,7 +29131,7 @@ static int sp_384_proj_point_add_15_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -29393,8 +29309,7 @@ static int sp_384_mod_mul_norm_15(sp_digit* r, const sp_digit* a, const sp_digit } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -29981,7 +29896,7 @@ static void sp_384_ecc_recode_6_15(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 26) { y &= 0x3f; n >>= 6; @@ -30066,7 +29981,7 @@ static void sp_384_get_point_33_15(sp_point_384* r, const sp_point_384* table, r->z[13] = 0; r->z[14] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -30251,10 +30166,8 @@ static int sp_384_ecc_mulmod_win_add_sub_15(sp_point_384* r, const sp_point_384* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30320,8 +30233,8 @@ static void sp_384_proj_point_add_qz1_15(sp_point_384* r, sp_384_mont_sub_15(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -30338,7 +30251,7 @@ static void sp_384_proj_point_add_qz1_15(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -30449,8 +30362,7 @@ static int sp_384_gen_stripe_table_15(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30501,7 +30413,7 @@ static void sp_384_get_entry_256_15(sp_point_384* r, r->y[13] = 0; r->y[14] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -30642,10 +30554,8 @@ static int sp_384_ecc_mulmod_stripe_15(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30863,10 +30773,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30943,10 +30851,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -32844,10 +32750,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -32922,10 +32826,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -32989,6 +32891,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_15(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -33005,6 +32908,11 @@ static int sp_384_ecc_gen_k_15(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -33083,12 +32991,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33271,10 +33176,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33341,25 +33244,25 @@ SP_NOINLINE static void sp_384_rshift_15(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<14; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (26 - n))) & 0x3ffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (26 - n))) & 0x3ffffff); } #else for (i=0; i<8; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (26 - n)) & 0x3ffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (26 - n)) & 0x3ffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (26 - n)) & 0x3ffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (26 - n)) & 0x3ffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (26 - n)) & 0x3ffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (26 - n)) & 0x3ffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (26 - n)) & 0x3ffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (26 - n)) & 0x3ffffff); - } - r[8] = (a[8] >> n) | ((a[9] << (26 - n)) & 0x3ffffff); - r[9] = (a[9] >> n) | ((a[10] << (26 - n)) & 0x3ffffff); - r[10] = (a[10] >> n) | ((a[11] << (26 - n)) & 0x3ffffff); - r[11] = (a[11] >> n) | ((a[12] << (26 - n)) & 0x3ffffff); - r[12] = (a[12] >> n) | ((a[13] << (26 - n)) & 0x3ffffff); - r[13] = (a[13] >> n) | ((a[14] << (26 - n)) & 0x3ffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (26 - n)) & 0x3ffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (26 - n)) & 0x3ffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (26 - n)) & 0x3ffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (26 - n)) & 0x3ffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (26 - n)) & 0x3ffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (26 - n)) & 0x3ffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (26 - n)) & 0x3ffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (26 - n)) & 0x3ffffff); + } + r[8] = (a[8] >> n) | (sp_digit)((a[9] << (26 - n)) & 0x3ffffff); + r[9] = (a[9] >> n) | (sp_digit)((a[10] << (26 - n)) & 0x3ffffff); + r[10] = (a[10] >> n) | (sp_digit)((a[11] << (26 - n)) & 0x3ffffff); + r[11] = (a[11] >> n) | (sp_digit)((a[12] << (26 - n)) & 0x3ffffff); + r[12] = (a[12] >> n) | (sp_digit)((a[13] << (26 - n)) & 0x3ffffff); + r[13] = (a[13] >> n) | (sp_digit)((a[14] << (26 - n)) & 0x3ffffff); #endif /* WOLFSSL_SP_SMALL */ r[14] = a[14] >> n; } @@ -33430,7 +33333,7 @@ SP_NOINLINE static void sp_384_lshift_30(sp_digit* r, const sp_digit* a, r[30] = a[29] >> (26 - n); for (i=29; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (26 - n))) & 0x3ffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (26 - n))) & 0x3ffffff); } #else sp_int_digit s; @@ -33439,65 +33342,65 @@ SP_NOINLINE static void sp_384_lshift_30(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[29]; r[30] = s >> (26U - n); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[29] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[28] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[27] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[26] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[25] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[24] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[23] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[22] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[21] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[20] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[19] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[18] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[17] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[16] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[15] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[14] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[13] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[12] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[11] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[10] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[9] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[8] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[7] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[6] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[5] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[4] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[3] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[2] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (26U - n))) & 0x3ffffff; + r[1] = (sp_digit)(((s << n) | (t >> (26U - n))) & 0x3ffffff); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x3ffffff; + r[0] = (sp_digit)((a[0] << n) & 0x3ffffff); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -33561,8 +33464,7 @@ static int sp_384_div_15(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -34254,8 +34156,7 @@ static int sp_384_mod_inv_15(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 15); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -34469,10 +34370,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -34679,8 +34578,7 @@ static int sp_384_ecc_is_point_15(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -34719,8 +34617,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -34828,10 +34725,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -34910,10 +34805,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -34978,10 +34871,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35042,10 +34933,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35141,8 +35030,7 @@ static int sp_384_mont_sqrt_15(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35207,8 +35095,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35377,7 +35264,7 @@ SP_NOINLINE static void sp_521_mul_21(sp_digit* r, const sp_digit* a, } } for (i=0; i<41; i++) { - r[i] = t[i] & 0x1ffffff; + r[i] = (sp_digit)(t[i] & 0x1ffffff); t[i+1] += t[i] >> 25; } r[41] = (sp_digit)t[41]; @@ -35446,7 +35333,7 @@ SP_NOINLINE static void sp_521_sqr_21(sp_digit* r, const sp_digit* a) t[i+i] += ((sp_int64)a[i]) * a[i]; } for (i=0; i<41; i++) { - r[i] = t[i] & 0x1ffffff; + r[i] = (sp_digit)(t[i] & 0x1ffffff); t[i+1] += t[i] >> 25; } r[41] = (sp_digit)t[41]; @@ -35794,10 +35681,10 @@ static void sp_521_mont_reduce_21(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 20; i++) { - a[i] += ((a[20 + i] >> 21) + (a[20 + i + 1] << 4)) & 0x1ffffff; + a[i] += (sp_digit)(((a[20 + i] >> 21) + (a[20 + i + 1] << 4)) & 0x1ffffff); } a[20] &= 0x1fffff; - a[20] += ((a[40] >> 21) + (a[41] << 4)) & 0x1ffffff; + a[20] += (sp_digit)(((a[40] >> 21) + (a[41] << 4)) & 0x1ffffff); sp_521_norm_21(a); @@ -35902,17 +35789,17 @@ SP_NOINLINE static void sp_521_mul_add_21(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1ffffff; + r[i+0] = (sp_digit)(t[0] & 0x1ffffff); t[1] += t[0] >> 25; - r[i+1] = t[1] & 0x1ffffff; + r[i+1] = (sp_digit)(t[1] & 0x1ffffff); t[2] += t[1] >> 25; - r[i+2] = t[2] & 0x1ffffff; + r[i+2] = (sp_digit)(t[2] & 0x1ffffff); t[3] += t[2] >> 25; - r[i+3] = t[3] & 0x1ffffff; + r[i+3] = (sp_digit)(t[3] & 0x1ffffff); t[0] = t[3] >> 25; } t[0] += (tb * a[20]) + r[20]; - r[20] = t[0] & 0x1ffffff; + r[20] = (sp_digit)(t[0] & 0x1ffffff); r[21] += (sp_digit)(t[0] >> 25); #else sp_int64 tb = b; @@ -35965,8 +35852,8 @@ static void sp_521_mont_shift_21(sp_digit* r, const sp_digit* a) s = a[21]; n = a[20] >> 21; for (i = 0; i < 20; i++) { - n += (s & 0x1ffffff) << 4; - r[i] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); + r[i] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[22 + i] + (s >> 25); } @@ -35979,30 +35866,30 @@ static void sp_521_mont_shift_21(sp_digit* r, const sp_digit* a) s = a[21]; n = a[20] >> 21; for (i = 0; i < 16; i += 8) { - n += (s & 0x1ffffff) << 4; r[i+0] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+0] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+22] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+1] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+1] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+23] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+2] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+2] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+24] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+3] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+3] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+25] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+4] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+4] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+26] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+5] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+5] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+27] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+6] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+6] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+28] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[i+7] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[i+7] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[i+29] + (s >> 25); } - n += (s & 0x1ffffff) << 4; r[16] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[16] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[38] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[17] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[17] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[39] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[18] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[18] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[40] + (s >> 25); - n += (s & 0x1ffffff) << 4; r[19] = n & 0x1ffffff; + n += (sp_digit)((s & 0x1ffffff) << 4); r[19] = (sp_digit)(n & 0x1ffffff); n >>= 25; s = a[41] + (s >> 25); n += s << 4; r[20] = n; #endif /* WOLFSSL_SP_SMALL */ @@ -36024,11 +35911,11 @@ static void sp_521_mont_reduce_order_21(sp_digit* a, const sp_digit* m, sp_digit sp_521_norm_21(a + 21); for (i=0; i<20; i++) { - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1ffffff; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1ffffff); sp_521_mul_add_21(a+i, m, mu); a[i+1] += a[i] >> 25; } - mu = ((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffL; + mu = (sp_digit)(((sp_uint32)a[i] * (sp_uint32)mp) & 0x1fffffL); sp_521_mul_add_21(a+i, m, mu); a[i+1] += a[i] >> 25; a[i] &= 0x1ffffff; @@ -36201,7 +36088,7 @@ static void sp_521_map_21(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_21(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_21(r->x, p521_mod); - sp_521_cond_sub_21(r->x, r->x, p521_mod, ~(n >> 24)); + sp_521_cond_sub_21(r->x, r->x, p521_mod, (sp_digit)~(n >> 24)); sp_521_norm_21(r->x); /* y /= z^3 */ @@ -36210,7 +36097,7 @@ static void sp_521_map_21(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_21(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_21(r->y, p521_mod); - sp_521_cond_sub_21(r->y, r->y, p521_mod, ~(n >> 24)); + sp_521_cond_sub_21(r->y, r->y, p521_mod, (sp_digit)~(n >> 24)); sp_521_norm_21(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -36352,29 +36239,29 @@ SP_NOINLINE static void sp_521_rshift1_21(sp_digit* r, const sp_digit* a) int i; for (i=0; i<20; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 24) & 0x1ffffff); - } -#else - r[0] = (a[0] >> 1) + ((a[1] << 24) & 0x1ffffff); - r[1] = (a[1] >> 1) + ((a[2] << 24) & 0x1ffffff); - r[2] = (a[2] >> 1) + ((a[3] << 24) & 0x1ffffff); - r[3] = (a[3] >> 1) + ((a[4] << 24) & 0x1ffffff); - r[4] = (a[4] >> 1) + ((a[5] << 24) & 0x1ffffff); - r[5] = (a[5] >> 1) + ((a[6] << 24) & 0x1ffffff); - r[6] = (a[6] >> 1) + ((a[7] << 24) & 0x1ffffff); - r[7] = (a[7] >> 1) + ((a[8] << 24) & 0x1ffffff); - r[8] = (a[8] >> 1) + ((a[9] << 24) & 0x1ffffff); - r[9] = (a[9] >> 1) + ((a[10] << 24) & 0x1ffffff); - r[10] = (a[10] >> 1) + ((a[11] << 24) & 0x1ffffff); - r[11] = (a[11] >> 1) + ((a[12] << 24) & 0x1ffffff); - r[12] = (a[12] >> 1) + ((a[13] << 24) & 0x1ffffff); - r[13] = (a[13] >> 1) + ((a[14] << 24) & 0x1ffffff); - r[14] = (a[14] >> 1) + ((a[15] << 24) & 0x1ffffff); - r[15] = (a[15] >> 1) + ((a[16] << 24) & 0x1ffffff); - r[16] = (a[16] >> 1) + ((a[17] << 24) & 0x1ffffff); - r[17] = (a[17] >> 1) + ((a[18] << 24) & 0x1ffffff); - r[18] = (a[18] >> 1) + ((a[19] << 24) & 0x1ffffff); - r[19] = (a[19] >> 1) + ((a[20] << 24) & 0x1ffffff); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 24) & 0x1ffffff); + } +#else + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 24) & 0x1ffffff); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 24) & 0x1ffffff); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 24) & 0x1ffffff); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 24) & 0x1ffffff); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 24) & 0x1ffffff); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 24) & 0x1ffffff); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 24) & 0x1ffffff); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 24) & 0x1ffffff); + r[8] = (a[8] >> 1) + (sp_digit)((a[9] << 24) & 0x1ffffff); + r[9] = (a[9] >> 1) + (sp_digit)((a[10] << 24) & 0x1ffffff); + r[10] = (a[10] >> 1) + (sp_digit)((a[11] << 24) & 0x1ffffff); + r[11] = (a[11] >> 1) + (sp_digit)((a[12] << 24) & 0x1ffffff); + r[12] = (a[12] >> 1) + (sp_digit)((a[13] << 24) & 0x1ffffff); + r[13] = (a[13] >> 1) + (sp_digit)((a[14] << 24) & 0x1ffffff); + r[14] = (a[14] >> 1) + (sp_digit)((a[15] << 24) & 0x1ffffff); + r[15] = (a[15] >> 1) + (sp_digit)((a[16] << 24) & 0x1ffffff); + r[16] = (a[16] >> 1) + (sp_digit)((a[17] << 24) & 0x1ffffff); + r[17] = (a[17] >> 1) + (sp_digit)((a[18] << 24) & 0x1ffffff); + r[18] = (a[18] >> 1) + (sp_digit)((a[19] << 24) & 0x1ffffff); + r[19] = (a[19] >> 1) + (sp_digit)((a[20] << 24) & 0x1ffffff); #endif r[20] = a[20] >> 1; } @@ -36690,8 +36577,8 @@ static void sp_521_proj_point_add_21(sp_point_521* r, sp_521_mont_sub_21(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -36708,7 +36595,7 @@ static void sp_521_proj_point_add_21(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -36882,8 +36769,8 @@ static int sp_521_proj_point_add_21_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -36900,7 +36787,7 @@ static int sp_521_proj_point_add_21_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -37528,7 +37415,7 @@ static void sp_521_ecc_recode_6_21(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 25) { y &= 0x3f; n >>= 6; @@ -37631,7 +37518,7 @@ static void sp_521_get_point_33_21(sp_point_521* r, const sp_point_521* table, r->z[19] = 0; r->z[20] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -37834,10 +37721,8 @@ static int sp_521_ecc_mulmod_win_add_sub_21(sp_point_521* r, const sp_point_521* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -37903,8 +37788,8 @@ static void sp_521_proj_point_add_qz1_21(sp_point_521* r, sp_521_mont_sub_21(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -37921,7 +37806,7 @@ static void sp_521_proj_point_add_qz1_21(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -38032,8 +37917,7 @@ static int sp_521_gen_stripe_table_21(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38096,7 +37980,7 @@ static void sp_521_get_entry_256_21(sp_point_521* r, r->y[19] = 0; r->y[20] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -38249,10 +38133,8 @@ static int sp_521_ecc_mulmod_stripe_21(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38470,10 +38352,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38550,10 +38430,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40961,10 +40839,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41039,10 +40915,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41106,6 +40980,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_21(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -41123,6 +40998,11 @@ static int sp_521_ecc_gen_k_21(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -41201,12 +41081,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41389,10 +41266,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41457,23 +41332,23 @@ SP_NOINLINE static void sp_521_rshift_21(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<20; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (25 - n))) & 0x1ffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (25 - n))) & 0x1ffffff); } #else for (i=0; i<16; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (25 - n)) & 0x1ffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (25 - n)) & 0x1ffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (25 - n)) & 0x1ffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (25 - n)) & 0x1ffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (25 - n)) & 0x1ffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (25 - n)) & 0x1ffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (25 - n)) & 0x1ffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (25 - n)) & 0x1ffffff); - } - r[16] = (a[16] >> n) | ((a[17] << (25 - n)) & 0x1ffffff); - r[17] = (a[17] >> n) | ((a[18] << (25 - n)) & 0x1ffffff); - r[18] = (a[18] >> n) | ((a[19] << (25 - n)) & 0x1ffffff); - r[19] = (a[19] >> n) | ((a[20] << (25 - n)) & 0x1ffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (25 - n)) & 0x1ffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (25 - n)) & 0x1ffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (25 - n)) & 0x1ffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (25 - n)) & 0x1ffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (25 - n)) & 0x1ffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (25 - n)) & 0x1ffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (25 - n)) & 0x1ffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (25 - n)) & 0x1ffffff); + } + r[16] = (a[16] >> n) | (sp_digit)((a[17] << (25 - n)) & 0x1ffffff); + r[17] = (a[17] >> n) | (sp_digit)((a[18] << (25 - n)) & 0x1ffffff); + r[18] = (a[18] >> n) | (sp_digit)((a[19] << (25 - n)) & 0x1ffffff); + r[19] = (a[19] >> n) | (sp_digit)((a[20] << (25 - n)) & 0x1ffffff); #endif /* WOLFSSL_SP_SMALL */ r[20] = a[20] >> n; } @@ -41544,7 +41419,7 @@ SP_NOINLINE static void sp_521_lshift_42(sp_digit* r, const sp_digit* a, r[42] = a[41] >> (25 - n); for (i=41; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (25 - n))) & 0x1ffffff; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (25 - n))) & 0x1ffffff); } #else sp_int_digit s; @@ -41553,89 +41428,89 @@ SP_NOINLINE static void sp_521_lshift_42(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[41]; r[42] = s >> (25U - n); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[41] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[40] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[39] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[38] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[37] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[36] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[35] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[34] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[33] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[32] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[31] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[30] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[29] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[28] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[27] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[26] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[25] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[24] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[23] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[22] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[21] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[20] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[19] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[18] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[17] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[16] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[15] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[14] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[13] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[12] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[11] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[10] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[9] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[8] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[7] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[6] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[5] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[4] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[3] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[2] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (25U - n))) & 0x1ffffff; + r[1] = (sp_digit)(((s << n) | (t >> (25U - n))) & 0x1ffffff); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x1ffffff; + r[0] = (sp_digit)((a[0] << n) & 0x1ffffff); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -41699,8 +41574,7 @@ static int sp_521_div_21(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -42417,8 +42291,7 @@ static int sp_521_mod_inv_21(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 21); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42643,10 +42516,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42857,8 +42728,7 @@ static int sp_521_ecc_is_point_21(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42897,8 +42767,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43006,10 +42875,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -43088,10 +42955,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43156,10 +43021,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43220,10 +43083,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43273,8 +43134,7 @@ static int sp_521_mont_sqrt_21(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43339,8 +43199,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43422,20 +43281,20 @@ SP_NOINLINE static void sp_1024_mul_7(sp_digit* r, const sp_digit* a, + ((sp_int64)a[ 6]) * b[ 5]; sp_int64 t12 = ((sp_int64)a[ 6]) * b[ 6]; - t1 += t0 >> 25; r[ 0] = t0 & 0x1ffffff; - t2 += t1 >> 25; r[ 1] = t1 & 0x1ffffff; - t3 += t2 >> 25; r[ 2] = t2 & 0x1ffffff; - t4 += t3 >> 25; r[ 3] = t3 & 0x1ffffff; - t5 += t4 >> 25; r[ 4] = t4 & 0x1ffffff; - t6 += t5 >> 25; r[ 5] = t5 & 0x1ffffff; - t7 += t6 >> 25; r[ 6] = t6 & 0x1ffffff; - t8 += t7 >> 25; r[ 7] = t7 & 0x1ffffff; - t9 += t8 >> 25; r[ 8] = t8 & 0x1ffffff; - t10 += t9 >> 25; r[ 9] = t9 & 0x1ffffff; - t11 += t10 >> 25; r[10] = t10 & 0x1ffffff; - t12 += t11 >> 25; r[11] = t11 & 0x1ffffff; + t1 += t0 >> 25; r[ 0] = (sp_digit)(t0 & 0x1ffffff); + t2 += t1 >> 25; r[ 1] = (sp_digit)(t1 & 0x1ffffff); + t3 += t2 >> 25; r[ 2] = (sp_digit)(t2 & 0x1ffffff); + t4 += t3 >> 25; r[ 3] = (sp_digit)(t3 & 0x1ffffff); + t5 += t4 >> 25; r[ 4] = (sp_digit)(t4 & 0x1ffffff); + t6 += t5 >> 25; r[ 5] = (sp_digit)(t5 & 0x1ffffff); + t7 += t6 >> 25; r[ 6] = (sp_digit)(t6 & 0x1ffffff); + t8 += t7 >> 25; r[ 7] = (sp_digit)(t7 & 0x1ffffff); + t9 += t8 >> 25; r[ 8] = (sp_digit)(t8 & 0x1ffffff); + t10 += t9 >> 25; r[ 9] = (sp_digit)(t9 & 0x1ffffff); + t11 += t10 >> 25; r[10] = (sp_digit)(t10 & 0x1ffffff); + t12 += t11 >> 25; r[11] = (sp_digit)(t11 & 0x1ffffff); r[13] = (sp_digit)(t12 >> 25); - r[12] = t12 & 0x1ffffff; + r[12] = (sp_digit)(t12 & 0x1ffffff); } /* Square a and put result in r. (r = a * a) @@ -43474,20 +43333,20 @@ SP_NOINLINE static void sp_1024_sqr_7(sp_digit* r, const sp_digit* a) sp_int64 t11 = (((sp_int64)a[ 5]) * a[ 6]) * 2; sp_int64 t12 = ((sp_int64)a[ 6]) * a[ 6]; - t1 += t0 >> 25; r[ 0] = t0 & 0x1ffffff; - t2 += t1 >> 25; r[ 1] = t1 & 0x1ffffff; - t3 += t2 >> 25; r[ 2] = t2 & 0x1ffffff; - t4 += t3 >> 25; r[ 3] = t3 & 0x1ffffff; - t5 += t4 >> 25; r[ 4] = t4 & 0x1ffffff; - t6 += t5 >> 25; r[ 5] = t5 & 0x1ffffff; - t7 += t6 >> 25; r[ 6] = t6 & 0x1ffffff; - t8 += t7 >> 25; r[ 7] = t7 & 0x1ffffff; - t9 += t8 >> 25; r[ 8] = t8 & 0x1ffffff; - t10 += t9 >> 25; r[ 9] = t9 & 0x1ffffff; - t11 += t10 >> 25; r[10] = t10 & 0x1ffffff; - t12 += t11 >> 25; r[11] = t11 & 0x1ffffff; + t1 += t0 >> 25; r[ 0] = (sp_digit)(t0 & 0x1ffffff); + t2 += t1 >> 25; r[ 1] = (sp_digit)(t1 & 0x1ffffff); + t3 += t2 >> 25; r[ 2] = (sp_digit)(t2 & 0x1ffffff); + t4 += t3 >> 25; r[ 3] = (sp_digit)(t3 & 0x1ffffff); + t5 += t4 >> 25; r[ 4] = (sp_digit)(t4 & 0x1ffffff); + t6 += t5 >> 25; r[ 5] = (sp_digit)(t5 & 0x1ffffff); + t7 += t6 >> 25; r[ 6] = (sp_digit)(t6 & 0x1ffffff); + t8 += t7 >> 25; r[ 7] = (sp_digit)(t7 & 0x1ffffff); + t9 += t8 >> 25; r[ 8] = (sp_digit)(t8 & 0x1ffffff); + t10 += t9 >> 25; r[ 9] = (sp_digit)(t9 & 0x1ffffff); + t11 += t10 >> 25; r[10] = (sp_digit)(t10 & 0x1ffffff); + t12 += t11 >> 25; r[11] = (sp_digit)(t11 & 0x1ffffff); r[13] = (sp_digit)(t12 >> 25); - r[12] = t12 & 0x1ffffff; + r[12] = (sp_digit)(t12 & 0x1ffffff); } /* Add b to a into r. (r = a + b) @@ -44192,20 +44051,20 @@ SP_NOINLINE static void sp_1024_rshift_42(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<41; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (25 - n))) & 0x1ffffff; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (25 - n))) & 0x1ffffff); } #else for (i=0; i<40; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (25 - n)) & 0x1ffffff); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (25 - n)) & 0x1ffffff); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (25 - n)) & 0x1ffffff); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (25 - n)) & 0x1ffffff); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (25 - n)) & 0x1ffffff); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (25 - n)) & 0x1ffffff); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (25 - n)) & 0x1ffffff); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (25 - n)) & 0x1ffffff); - } - r[40] = (a[40] >> n) | ((a[41] << (25 - n)) & 0x1ffffff); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (25 - n)) & 0x1ffffff); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (25 - n)) & 0x1ffffff); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (25 - n)) & 0x1ffffff); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (25 - n)) & 0x1ffffff); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (25 - n)) & 0x1ffffff); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (25 - n)) & 0x1ffffff); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (25 - n)) & 0x1ffffff); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (25 - n)) & 0x1ffffff); + } + r[40] = (a[40] >> n) | (sp_digit)((a[41] << (25 - n)) & 0x1ffffff); #endif /* WOLFSSL_SP_SMALL */ r[41] = a[41] >> n; } @@ -44382,8 +44241,7 @@ static int sp_1024_div_42(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -44462,16 +44320,16 @@ static void sp_1024_point_free_42(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -44765,20 +44623,20 @@ SP_NOINLINE static void sp_1024_mul_add_42(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1ffffff; + r[i+0] = (sp_digit)(t[0] & 0x1ffffff); t[1] += t[0] >> 25; - r[i+1] = t[1] & 0x1ffffff; + r[i+1] = (sp_digit)(t[1] & 0x1ffffff); t[2] += t[1] >> 25; - r[i+2] = t[2] & 0x1ffffff; + r[i+2] = (sp_digit)(t[2] & 0x1ffffff); t[3] += t[2] >> 25; - r[i+3] = t[3] & 0x1ffffff; + r[i+3] = (sp_digit)(t[3] & 0x1ffffff); t[0] = t[3] >> 25; } t[0] += (tb * a[40]) + r[40]; t[1] = (tb * a[41]) + r[41]; - r[40] = t[0] & 0x1ffffff; + r[40] = (sp_digit)(t[0] & 0x1ffffff); t[1] += t[0] >> 25; - r[41] = t[1] & 0x1ffffff; + r[41] = (sp_digit)(t[1] & 0x1ffffff); r[42] += (sp_digit)(t[1] >> 25); #else sp_int64 tb = b; @@ -44852,7 +44710,7 @@ static void sp_1024_mont_shift_42(sp_digit* r, const sp_digit* a) n = a[40] >> 24; for (i = 0; i < 40; i++) { n += (sp_uint32)a[41 + i] << 1; - r[i] = n & 0x1ffffff; + r[i] = (sp_digit)(n & 0x1ffffff); n >>= 25; } n += (sp_uint32)a[81] << 1; @@ -44864,14 +44722,14 @@ static void sp_1024_mont_shift_42(sp_digit* r, const sp_digit* a) n = (sp_uint32)a[40]; n = n >> 24U; for (i = 0; i < 40; i += 8) { - n += (sp_uint32)a[i+41] << 1U; r[i+0] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+42] << 1U; r[i+1] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+43] << 1U; r[i+2] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+44] << 1U; r[i+3] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+45] << 1U; r[i+4] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+46] << 1U; r[i+5] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+47] << 1U; r[i+6] = n & 0x1ffffff; n >>= 25U; - n += (sp_uint32)a[i+48] << 1U; r[i+7] = n & 0x1ffffff; n >>= 25U; + n += (sp_uint32)a[i+41] << 1U; r[i+0] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+42] << 1U; r[i+1] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+43] << 1U; r[i+2] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+44] << 1U; r[i+3] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+45] << 1U; r[i+4] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+46] << 1U; r[i+5] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+47] << 1U; r[i+6] = (sp_digit)(n & 0x1ffffff); n >>= 25U; + n += (sp_uint32)a[i+48] << 1U; r[i+7] = (sp_digit)(n & 0x1ffffff); n >>= 25U; } n += (sp_uint32)a[81] << 1U; r[40] = n; #endif /* WOLFSSL_SP_SMALL */ @@ -44894,22 +44752,22 @@ static void sp_1024_mont_reduce_42(sp_digit* a, const sp_digit* m, sp_digit mp) if (mp != 1) { for (i=0; i<40; i++) { - mu = (a[i] * mp) & 0x1ffffff; + mu = (sp_digit)((a[i] * mp) & 0x1ffffff); sp_1024_mul_add_42(a+i, m, mu); a[i+1] += a[i] >> 25; } - mu = (a[i] * mp) & 0xffffffL; + mu = (sp_digit)((a[i] * mp) & 0xffffffL); sp_1024_mul_add_42(a+i, m, mu); a[i+1] += a[i] >> 25; a[i] &= 0x1ffffff; } else { for (i=0; i<40; i++) { - mu = a[i] & 0x1ffffff; + mu = (sp_digit)(a[i] & 0x1ffffff); sp_1024_mul_add_42(a+i, m, mu); a[i+1] += a[i] >> 25; } - mu = a[i] & 0xffffffL; + mu = (sp_digit)(a[i] & 0xffffffL); sp_1024_mul_add_42(a+i, m, mu); a[i+1] += a[i] >> 25; a[i] &= 0x1ffffff; @@ -45036,7 +44894,7 @@ static void sp_1024_map_42(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_42(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_42(r->x, p1024_mod); - sp_1024_cond_sub_42(r->x, r->x, p1024_mod, ~(n >> 24)); + sp_1024_cond_sub_42(r->x, r->x, p1024_mod, (sp_digit)~(n >> 24)); sp_1024_norm_42(r->x); /* y /= z^3 */ @@ -45045,7 +44903,7 @@ static void sp_1024_map_42(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_42(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_42(r->y, p1024_mod); - sp_1024_cond_sub_42(r->y, r->y, p1024_mod, ~(n >> 24)); + sp_1024_cond_sub_42(r->y, r->y, p1024_mod, (sp_digit)~(n >> 24)); sp_1024_norm_42(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -45135,50 +44993,50 @@ SP_NOINLINE static void sp_1024_rshift1_42(sp_digit* r, const sp_digit* a) int i; for (i=0; i<41; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 24) & 0x1ffffff); - } -#else - r[0] = (a[0] >> 1) + ((a[1] << 24) & 0x1ffffff); - r[1] = (a[1] >> 1) + ((a[2] << 24) & 0x1ffffff); - r[2] = (a[2] >> 1) + ((a[3] << 24) & 0x1ffffff); - r[3] = (a[3] >> 1) + ((a[4] << 24) & 0x1ffffff); - r[4] = (a[4] >> 1) + ((a[5] << 24) & 0x1ffffff); - r[5] = (a[5] >> 1) + ((a[6] << 24) & 0x1ffffff); - r[6] = (a[6] >> 1) + ((a[7] << 24) & 0x1ffffff); - r[7] = (a[7] >> 1) + ((a[8] << 24) & 0x1ffffff); - r[8] = (a[8] >> 1) + ((a[9] << 24) & 0x1ffffff); - r[9] = (a[9] >> 1) + ((a[10] << 24) & 0x1ffffff); - r[10] = (a[10] >> 1) + ((a[11] << 24) & 0x1ffffff); - r[11] = (a[11] >> 1) + ((a[12] << 24) & 0x1ffffff); - r[12] = (a[12] >> 1) + ((a[13] << 24) & 0x1ffffff); - r[13] = (a[13] >> 1) + ((a[14] << 24) & 0x1ffffff); - r[14] = (a[14] >> 1) + ((a[15] << 24) & 0x1ffffff); - r[15] = (a[15] >> 1) + ((a[16] << 24) & 0x1ffffff); - r[16] = (a[16] >> 1) + ((a[17] << 24) & 0x1ffffff); - r[17] = (a[17] >> 1) + ((a[18] << 24) & 0x1ffffff); - r[18] = (a[18] >> 1) + ((a[19] << 24) & 0x1ffffff); - r[19] = (a[19] >> 1) + ((a[20] << 24) & 0x1ffffff); - r[20] = (a[20] >> 1) + ((a[21] << 24) & 0x1ffffff); - r[21] = (a[21] >> 1) + ((a[22] << 24) & 0x1ffffff); - r[22] = (a[22] >> 1) + ((a[23] << 24) & 0x1ffffff); - r[23] = (a[23] >> 1) + ((a[24] << 24) & 0x1ffffff); - r[24] = (a[24] >> 1) + ((a[25] << 24) & 0x1ffffff); - r[25] = (a[25] >> 1) + ((a[26] << 24) & 0x1ffffff); - r[26] = (a[26] >> 1) + ((a[27] << 24) & 0x1ffffff); - r[27] = (a[27] >> 1) + ((a[28] << 24) & 0x1ffffff); - r[28] = (a[28] >> 1) + ((a[29] << 24) & 0x1ffffff); - r[29] = (a[29] >> 1) + ((a[30] << 24) & 0x1ffffff); - r[30] = (a[30] >> 1) + ((a[31] << 24) & 0x1ffffff); - r[31] = (a[31] >> 1) + ((a[32] << 24) & 0x1ffffff); - r[32] = (a[32] >> 1) + ((a[33] << 24) & 0x1ffffff); - r[33] = (a[33] >> 1) + ((a[34] << 24) & 0x1ffffff); - r[34] = (a[34] >> 1) + ((a[35] << 24) & 0x1ffffff); - r[35] = (a[35] >> 1) + ((a[36] << 24) & 0x1ffffff); - r[36] = (a[36] >> 1) + ((a[37] << 24) & 0x1ffffff); - r[37] = (a[37] >> 1) + ((a[38] << 24) & 0x1ffffff); - r[38] = (a[38] >> 1) + ((a[39] << 24) & 0x1ffffff); - r[39] = (a[39] >> 1) + ((a[40] << 24) & 0x1ffffff); - r[40] = (a[40] >> 1) + ((a[41] << 24) & 0x1ffffff); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 24) & 0x1ffffff); + } +#else + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 24) & 0x1ffffff); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 24) & 0x1ffffff); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 24) & 0x1ffffff); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 24) & 0x1ffffff); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 24) & 0x1ffffff); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 24) & 0x1ffffff); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 24) & 0x1ffffff); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 24) & 0x1ffffff); + r[8] = (a[8] >> 1) + (sp_digit)((a[9] << 24) & 0x1ffffff); + r[9] = (a[9] >> 1) + (sp_digit)((a[10] << 24) & 0x1ffffff); + r[10] = (a[10] >> 1) + (sp_digit)((a[11] << 24) & 0x1ffffff); + r[11] = (a[11] >> 1) + (sp_digit)((a[12] << 24) & 0x1ffffff); + r[12] = (a[12] >> 1) + (sp_digit)((a[13] << 24) & 0x1ffffff); + r[13] = (a[13] >> 1) + (sp_digit)((a[14] << 24) & 0x1ffffff); + r[14] = (a[14] >> 1) + (sp_digit)((a[15] << 24) & 0x1ffffff); + r[15] = (a[15] >> 1) + (sp_digit)((a[16] << 24) & 0x1ffffff); + r[16] = (a[16] >> 1) + (sp_digit)((a[17] << 24) & 0x1ffffff); + r[17] = (a[17] >> 1) + (sp_digit)((a[18] << 24) & 0x1ffffff); + r[18] = (a[18] >> 1) + (sp_digit)((a[19] << 24) & 0x1ffffff); + r[19] = (a[19] >> 1) + (sp_digit)((a[20] << 24) & 0x1ffffff); + r[20] = (a[20] >> 1) + (sp_digit)((a[21] << 24) & 0x1ffffff); + r[21] = (a[21] >> 1) + (sp_digit)((a[22] << 24) & 0x1ffffff); + r[22] = (a[22] >> 1) + (sp_digit)((a[23] << 24) & 0x1ffffff); + r[23] = (a[23] >> 1) + (sp_digit)((a[24] << 24) & 0x1ffffff); + r[24] = (a[24] >> 1) + (sp_digit)((a[25] << 24) & 0x1ffffff); + r[25] = (a[25] >> 1) + (sp_digit)((a[26] << 24) & 0x1ffffff); + r[26] = (a[26] >> 1) + (sp_digit)((a[27] << 24) & 0x1ffffff); + r[27] = (a[27] >> 1) + (sp_digit)((a[28] << 24) & 0x1ffffff); + r[28] = (a[28] >> 1) + (sp_digit)((a[29] << 24) & 0x1ffffff); + r[29] = (a[29] >> 1) + (sp_digit)((a[30] << 24) & 0x1ffffff); + r[30] = (a[30] >> 1) + (sp_digit)((a[31] << 24) & 0x1ffffff); + r[31] = (a[31] >> 1) + (sp_digit)((a[32] << 24) & 0x1ffffff); + r[32] = (a[32] >> 1) + (sp_digit)((a[33] << 24) & 0x1ffffff); + r[33] = (a[33] >> 1) + (sp_digit)((a[34] << 24) & 0x1ffffff); + r[34] = (a[34] >> 1) + (sp_digit)((a[35] << 24) & 0x1ffffff); + r[35] = (a[35] >> 1) + (sp_digit)((a[36] << 24) & 0x1ffffff); + r[36] = (a[36] >> 1) + (sp_digit)((a[37] << 24) & 0x1ffffff); + r[37] = (a[37] >> 1) + (sp_digit)((a[38] << 24) & 0x1ffffff); + r[38] = (a[38] >> 1) + (sp_digit)((a[39] << 24) & 0x1ffffff); + r[39] = (a[39] >> 1) + (sp_digit)((a[40] << 24) & 0x1ffffff); + r[40] = (a[40] >> 1) + (sp_digit)((a[41] << 24) & 0x1ffffff); #endif r[41] = a[41] >> 1; } @@ -45504,8 +45362,8 @@ static void sp_1024_proj_point_add_42(sp_point_1024* r, sp_1024_mont_sub_42(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45522,7 +45380,7 @@ static void sp_1024_proj_point_add_42(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -45696,8 +45554,8 @@ static int sp_1024_proj_point_add_42_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45714,7 +45572,7 @@ static int sp_1024_proj_point_add_42_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -46374,7 +46232,7 @@ static void sp_1024_ecc_recode_7_42(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 25) { y &= 0x7f; n >>= 7; @@ -46540,10 +46398,8 @@ static int sp_1024_ecc_mulmod_win_add_sub_42(sp_point_1024* r, const sp_point_10 } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46609,8 +46465,8 @@ static void sp_1024_proj_point_add_qz1_42(sp_point_1024* r, sp_1024_mont_sub_42(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -46627,7 +46483,7 @@ static void sp_1024_proj_point_add_qz1_42(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -46738,8 +46594,7 @@ static int sp_1024_gen_stripe_table_42(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46838,10 +46693,8 @@ static int sp_1024_ecc_mulmod_stripe_42(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -47059,10 +46912,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51004,10 +50855,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51082,10 +50931,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51119,7 +50966,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -51150,10 +50997,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51179,7 +51024,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -51246,10 +51091,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51396,9 +51239,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -53294,9 +53135,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -53664,9 +53503,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_42(c, 1, NULL); sp_1024_point_free_42(q, 1, NULL); @@ -54091,9 +53928,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_42(c, 1, NULL); sp_1024_point_free_42(q, 1, NULL); @@ -54123,7 +53958,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -54352,7 +54187,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -54459,9 +54294,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_42(neg, 1, NULL); sp_1024_point_free_42(c, 1, NULL); @@ -54654,9 +54487,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_42(c, 1, NULL); sp_1024_point_free_42(q, 1, NULL); @@ -54746,7 +54577,7 @@ static int sp_1024_ecc_is_point_42(const sp_point_1024* point, n = sp_1024_cmp_42(t1, p1024_mod); - sp_1024_cond_sub_42(t1, t1, p1024_mod, ~(n >> 24)); + sp_1024_cond_sub_42(t1, t1, p1024_mod, (sp_digit)~(n >> 24)); sp_1024_norm_42(t1); if (!sp_1024_iszero_42(t1)) { err = MP_VAL; @@ -54754,8 +54585,7 @@ static int sp_1024_ecc_is_point_42(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -54794,8 +54624,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -54903,10 +54732,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_c64.c b/src/wolfcrypt/src/sp_c64.c index 93fd140..ab0ceda 100644 --- a/src/wolfcrypt/src/sp_c64.c +++ b/src/wolfcrypt/src/sp_c64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -71,13 +71,13 @@ #define SP_PRINT_NUM(var, name, total, words, bits) \ do { \ int ii; \ - byte nb[(bits + 7) / 8]; \ + byte nb[((bits) + 7) / 8]; \ sp_digit _s[words]; \ XMEMCPY(_s, var, sizeof(_s)); \ sp_##total##_norm_##words(_s); \ sp_##total##_to_bin_##words(_s, nb); \ fprintf(stderr, name "=0x"); \ - for (ii=0; ii<(bits + 7) / 8; ii++) \ + for (ii=0; ii<((bits) + 7) / 8; ii++) \ fprintf(stderr, "%02x", nb[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -563,17 +563,17 @@ SP_NOINLINE static void sp_2048_mul_add_17(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x1fffffffffffffffL); t[1] += t[0] >> 61; - r[i+1] = t[1] & 0x1fffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x1fffffffffffffffL); t[2] += t[1] >> 61; - r[i+2] = t[2] & 0x1fffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x1fffffffffffffffL); t[3] += t[2] >> 61; - r[i+3] = t[3] & 0x1fffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x1fffffffffffffffL); t[0] = t[3] >> 61; } t[0] += (tb * a[16]) + r[16]; - r[16] = t[0] & 0x1fffffffffffffffL; + r[16] = (sp_digit)(t[0] & 0x1fffffffffffffffL); r[17] += (sp_digit)(t[0] >> 61); } @@ -589,7 +589,7 @@ static void sp_2048_mont_shift_17(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[17]) << 13; for (i = 0; i < 16; i++) { - r[i] = n & 0x1fffffffffffffffL; + r[i] = (sp_digit)(n & 0x1fffffffffffffffL); n >>= 61; n += ((sp_int128)a[18 + i]) << 13; } @@ -612,11 +612,11 @@ static void sp_2048_mont_reduce_17(sp_digit* a, const sp_digit* m, sp_digit mp) sp_2048_norm_17(a + 17); for (i=0; i<16; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL); sp_2048_mul_add_17(a+i, m, mu); a[i+1] += a[i] >> 61; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xffffffffffffL); sp_2048_mul_add_17(a+i, m, mu); a[i+1] += a[i] >> 61; a[i] &= 0x1fffffffffffffffL; @@ -840,7 +840,7 @@ SP_NOINLINE static void sp_2048_rshift_17(sp_digit* r, const sp_digit* a, int i; for (i=0; i<16; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (61 - n))) & 0x1fffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (61 - n))) & 0x1fffffffffffffffL); } r[16] = a[16] >> n; } @@ -1017,8 +1017,7 @@ static int sp_2048_div_17(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1130,14 +1129,13 @@ static int sp_2048_mod_exp_17(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_17(t[0], m, mp); n = sp_2048_cmp_17(t[0], m); - sp_2048_cond_sub_17(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_17(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 17 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1221,13 +1219,12 @@ static int sp_2048_mod_exp_17(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_17(t[0], m, mp); n = sp_2048_cmp_17(t[0], m); - sp_2048_cond_sub_17(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_17(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 17 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1367,13 +1364,12 @@ static int sp_2048_mod_exp_17(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_17(rt, m, mp); n = sp_2048_cmp_17(rt, m); - sp_2048_cond_sub_17(rt, rt, m, ~(n >> 63)); + sp_2048_cond_sub_17(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 34); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1479,20 +1475,20 @@ SP_NOINLINE static void sp_2048_mul_add_34(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1fffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x1fffffffffffffffL); t[1] += t[0] >> 61; - r[i+1] = t[1] & 0x1fffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x1fffffffffffffffL); t[2] += t[1] >> 61; - r[i+2] = t[2] & 0x1fffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x1fffffffffffffffL); t[3] += t[2] >> 61; - r[i+3] = t[3] & 0x1fffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x1fffffffffffffffL); t[0] = t[3] >> 61; } t[0] += (tb * a[32]) + r[32]; t[1] = (tb * a[33]) + r[33]; - r[32] = t[0] & 0x1fffffffffffffffL; + r[32] = (sp_digit)(t[0] & 0x1fffffffffffffffL); t[1] += t[0] >> 61; - r[33] = t[1] & 0x1fffffffffffffffL; + r[33] = (sp_digit)(t[1] & 0x1fffffffffffffffL); r[34] += (sp_digit)(t[1] >> 61); } @@ -1508,7 +1504,7 @@ static void sp_2048_mont_shift_34(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[34]) << 26; for (i = 0; i < 33; i++) { - r[i] = n & 0x1fffffffffffffffL; + r[i] = (sp_digit)(n & 0x1fffffffffffffffL); n >>= 61; n += ((sp_int128)a[35 + i]) << 26; } @@ -1533,33 +1529,33 @@ static void sp_2048_mont_reduce_34(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<33; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; a[i] &= 0x1fffffffffffffffL; } else { for (i=0; i<33; i++) { - mu = a[i] & 0x1fffffffffffffffL; + mu = (sp_digit)(a[i] & 0x1fffffffffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; } - mu = a[i] & 0x7ffffffffL; + mu = (sp_digit)(a[i] & 0x7ffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; a[i] &= 0x1fffffffffffffffL; } #else for (i=0; i<33; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffL); sp_2048_mul_add_34(a+i, m, mu); a[i+1] += a[i] >> 61; a[i] &= 0x1fffffffffffffffL; @@ -1665,7 +1661,7 @@ SP_NOINLINE static void sp_2048_rshift_34(sp_digit* r, const sp_digit* a, int i; for (i=0; i<33; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (61 - n))) & 0x1fffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (61 - n))) & 0x1fffffffffffffffL); } r[33] = a[33] >> n; } @@ -1842,8 +1838,7 @@ static int sp_2048_div_34(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1956,14 +1951,13 @@ static int sp_2048_mod_exp_34(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_34(t[0], m, mp); n = sp_2048_cmp_34(t[0], m); - sp_2048_cond_sub_34(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_34(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 34 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2047,13 +2041,12 @@ static int sp_2048_mod_exp_34(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_34(t[0], m, mp); n = sp_2048_cmp_34(t[0], m); - sp_2048_cond_sub_34(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_34(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 34 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2176,13 +2169,12 @@ static int sp_2048_mod_exp_34(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_34(rt, m, mp); n = sp_2048_cmp_34(rt, m); - sp_2048_cond_sub_34(rt, rt, m, ~(n >> 63)); + sp_2048_cond_sub_34(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 68); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2301,8 +2293,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -2413,8 +2404,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -2784,7 +2774,7 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 17 * 13); @@ -3020,9 +3010,9 @@ SP_NOINLINE static void sp_2048_lshift_34(sp_digit* r, const sp_digit* a, r[34] = a[33] >> (61 - n); for (i=33; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (61 - n))) & 0x1fffffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (61 - n))) & 0x1fffffffffffffffL); } - r[0] = (a[0] << n) & 0x1fffffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0x1fffffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -3133,12 +3123,11 @@ static int sp_2048_mod_exp_2_34(sp_digit* r, const sp_digit* e, int bits, const sp_2048_mont_reduce_34(r, m, mp); n = sp_2048_cmp_34(r, m); - sp_2048_cond_sub_34(r, r, m, ~(n >> 63)); + sp_2048_cond_sub_34(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -3615,29 +3604,29 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_uint128)a[ 0]) * b[ 0]; t1 = ((sp_uint128)a[ 0]) * b[ 1] + ((sp_uint128)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 2] + ((sp_uint128)a[ 1]) * b[ 1] + ((sp_uint128)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 3] + ((sp_uint128)a[ 1]) * b[ 2] + ((sp_uint128)a[ 2]) * b[ 1] + ((sp_uint128)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 4] + ((sp_uint128)a[ 1]) * b[ 3] + ((sp_uint128)a[ 2]) * b[ 2] + ((sp_uint128)a[ 3]) * b[ 1] + ((sp_uint128)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 5] + ((sp_uint128)a[ 1]) * b[ 4] + ((sp_uint128)a[ 2]) * b[ 3] + ((sp_uint128)a[ 3]) * b[ 2] + ((sp_uint128)a[ 4]) * b[ 1] + ((sp_uint128)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 6] + ((sp_uint128)a[ 1]) * b[ 5] + ((sp_uint128)a[ 2]) * b[ 4] @@ -3645,7 +3634,7 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 4]) * b[ 2] + ((sp_uint128)a[ 5]) * b[ 1] + ((sp_uint128)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 7] + ((sp_uint128)a[ 1]) * b[ 6] + ((sp_uint128)a[ 2]) * b[ 5] @@ -3654,7 +3643,7 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 5]) * b[ 2] + ((sp_uint128)a[ 6]) * b[ 1] + ((sp_uint128)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 8] + ((sp_uint128)a[ 1]) * b[ 7] + ((sp_uint128)a[ 2]) * b[ 6] @@ -3664,7 +3653,7 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 2] + ((sp_uint128)a[ 7]) * b[ 1] + ((sp_uint128)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 1]) * b[ 8] + ((sp_uint128)a[ 2]) * b[ 7] + ((sp_uint128)a[ 3]) * b[ 6] @@ -3673,7 +3662,7 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 3] + ((sp_uint128)a[ 7]) * b[ 2] + ((sp_uint128)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 2]) * b[ 8] + ((sp_uint128)a[ 3]) * b[ 7] + ((sp_uint128)a[ 4]) * b[ 6] @@ -3681,35 +3670,35 @@ SP_NOINLINE static void sp_2048_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 4] + ((sp_uint128)a[ 7]) * b[ 3] + ((sp_uint128)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 3]) * b[ 8] + ((sp_uint128)a[ 4]) * b[ 7] + ((sp_uint128)a[ 5]) * b[ 6] + ((sp_uint128)a[ 6]) * b[ 5] + ((sp_uint128)a[ 7]) * b[ 4] + ((sp_uint128)a[ 8]) * b[ 3]; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 4]) * b[ 8] + ((sp_uint128)a[ 5]) * b[ 7] + ((sp_uint128)a[ 6]) * b[ 6] + ((sp_uint128)a[ 7]) * b[ 5] + ((sp_uint128)a[ 8]) * b[ 4]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 5]) * b[ 8] + ((sp_uint128)a[ 6]) * b[ 7] + ((sp_uint128)a[ 7]) * b[ 6] + ((sp_uint128)a[ 8]) * b[ 5]; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 6]) * b[ 8] + ((sp_uint128)a[ 7]) * b[ 7] + ((sp_uint128)a[ 8]) * b[ 6]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 7]) * b[ 8] + ((sp_uint128)a[ 8]) * b[ 7]; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 8]) * b[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -3909,66 +3898,66 @@ SP_NOINLINE static void sp_2048_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_uint128)a[ 0]) * a[ 0]; t1 = (((sp_uint128)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 2]) * 2 + ((sp_uint128)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 3] + ((sp_uint128)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 4] + ((sp_uint128)a[ 1]) * a[ 3]) * 2 + ((sp_uint128)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 5] + ((sp_uint128)a[ 1]) * a[ 4] + ((sp_uint128)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 6] + ((sp_uint128)a[ 1]) * a[ 5] + ((sp_uint128)a[ 2]) * a[ 4]) * 2 + ((sp_uint128)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 7] + ((sp_uint128)a[ 1]) * a[ 6] + ((sp_uint128)a[ 2]) * a[ 5] + ((sp_uint128)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 8] + ((sp_uint128)a[ 1]) * a[ 7] + ((sp_uint128)a[ 2]) * a[ 6] + ((sp_uint128)a[ 3]) * a[ 5]) * 2 + ((sp_uint128)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 1]) * a[ 8] + ((sp_uint128)a[ 2]) * a[ 7] + ((sp_uint128)a[ 3]) * a[ 6] + ((sp_uint128)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 2]) * a[ 8] + ((sp_uint128)a[ 3]) * a[ 7] + ((sp_uint128)a[ 4]) * a[ 6]) * 2 + ((sp_uint128)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 3]) * a[ 8] + ((sp_uint128)a[ 4]) * a[ 7] + ((sp_uint128)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 4]) * a[ 8] + ((sp_uint128)a[ 5]) * a[ 7]) * 2 + ((sp_uint128)a[ 6]) * a[ 6]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 5]) * a[ 8] + ((sp_uint128)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 6]) * a[ 8]) * 2 + ((sp_uint128)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -4213,16 +4202,16 @@ static void sp_2048_mont_shift_18(sp_digit* r, const sp_digit* a) n = (sp_uint64)a[17]; n = n >> 55U; for (i = 0; i < 16; i += 8) { - n += (sp_uint64)a[i+18] << 2U; r[i+0] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+19] << 2U; r[i+1] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+20] << 2U; r[i+2] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+21] << 2U; r[i+3] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+22] << 2U; r[i+4] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+23] << 2U; r[i+5] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+24] << 2U; r[i+6] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+25] << 2U; r[i+7] = n & 0x1ffffffffffffffUL; n >>= 57U; - } - n += (sp_uint64)a[34] << 2U; r[16] = n & 0x1ffffffffffffffUL; n >>= 57U; + n += (sp_uint64)a[i+18] << 2U; r[i+0] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+19] << 2U; r[i+1] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+20] << 2U; r[i+2] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+21] << 2U; r[i+3] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+22] << 2U; r[i+4] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+23] << 2U; r[i+5] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+24] << 2U; r[i+6] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+25] << 2U; r[i+7] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + } + n += (sp_uint64)a[34] << 2U; r[16] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; n += (sp_uint64)a[35] << 2U; r[17] = n; XMEMSET(&r[18], 0, sizeof(*r) * 18U); } @@ -4242,11 +4231,11 @@ static void sp_2048_mont_reduce_18(sp_digit* a, const sp_digit* m, sp_digit mp) sp_2048_norm_18(a + 18); for (i=0; i<17; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_2048_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffffffffffffL); sp_2048_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; @@ -4367,16 +4356,16 @@ SP_NOINLINE static void sp_2048_rshift_18(sp_digit* r, const sp_digit* a, int i; for (i=0; i<16; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); - } - r[16] = (a[16] >> n) | ((a[17] << (57 - n)) & 0x1ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); + } + r[16] = (a[16] >> n) | (sp_digit)((a[17] << (57 - n)) & 0x1ffffffffffffffL); r[17] = a[17] >> n; } @@ -4552,8 +4541,7 @@ static int sp_2048_div_18(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4665,14 +4653,13 @@ static int sp_2048_mod_exp_18(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_18(t[0], m, mp); n = sp_2048_cmp_18(t[0], m); - sp_2048_cond_sub_18(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_18(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 18 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4756,13 +4743,12 @@ static int sp_2048_mod_exp_18(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_18(t[0], m, mp); n = sp_2048_cmp_18(t[0], m); - sp_2048_cond_sub_18(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_18(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 18 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4902,13 +4888,12 @@ static int sp_2048_mod_exp_18(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_18(rt, m, mp); n = sp_2048_cmp_18(rt, m); - sp_2048_cond_sub_18(rt, rt, m, ~(n >> 63)); + sp_2048_cond_sub_18(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 36); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5063,28 +5048,28 @@ static void sp_2048_mont_shift_36(sp_digit* r, const sp_digit* a) s = a[36]; n = a[35] >> 53; for (i = 0; i < 32; i += 8) { - n += (s & 0x1ffffffffffffffL) << 4; r[i+0] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+0] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+37] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+1] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+1] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+38] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+2] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+2] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+39] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+3] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+3] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+40] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+4] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+4] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+41] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+5] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+5] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+42] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+6] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+6] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+43] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[i+7] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[i+7] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+44] + (s >> 57); } - n += (s & 0x1ffffffffffffffL) << 4; r[32] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[32] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[69] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[33] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[33] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[70] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 4; r[34] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 4); r[34] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[71] + (s >> 57); n += s << 4; r[35] = n; XMEMSET(&r[36], 0, sizeof(*r) * 36U); @@ -5107,33 +5092,33 @@ static void sp_2048_mont_reduce_36(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<35; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; } else { for (i=0; i<35; i++) { - mu = a[i] & 0x1ffffffffffffffL; + mu = (sp_digit)(a[i] & 0x1ffffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = a[i] & 0x1fffffffffffffL; + mu = (sp_digit)(a[i] & 0x1fffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; } #else for (i=0; i<35; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL); sp_2048_mul_add_36(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; @@ -5251,18 +5236,18 @@ SP_NOINLINE static void sp_2048_rshift_36(sp_digit* r, const sp_digit* a, int i; for (i=0; i<32; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); - } - r[32] = (a[32] >> n) | ((a[33] << (57 - n)) & 0x1ffffffffffffffL); - r[33] = (a[33] >> n) | ((a[34] << (57 - n)) & 0x1ffffffffffffffL); - r[34] = (a[34] >> n) | ((a[35] << (57 - n)) & 0x1ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); + } + r[32] = (a[32] >> n) | (sp_digit)((a[33] << (57 - n)) & 0x1ffffffffffffffL); + r[33] = (a[33] >> n) | (sp_digit)((a[34] << (57 - n)) & 0x1ffffffffffffffL); + r[34] = (a[34] >> n) | (sp_digit)((a[35] << (57 - n)) & 0x1ffffffffffffffL); r[35] = a[35] >> n; } @@ -5438,8 +5423,7 @@ static int sp_2048_div_36(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5554,14 +5538,13 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(t[0], m, mp); n = sp_2048_cmp_36(t[0], m); - sp_2048_cond_sub_36(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_36(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 36 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5645,13 +5628,12 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(t[0], m, mp); n = sp_2048_cmp_36(t[0], m); - sp_2048_cond_sub_36(t[0], t[0], m, ~(n >> 63)); + sp_2048_cond_sub_36(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 36 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5774,13 +5756,12 @@ static int sp_2048_mod_exp_36(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_2048_mont_reduce_36(rt, m, mp); n = sp_2048_cmp_36(rt, m); - sp_2048_cond_sub_36(rt, rt, m, ~(n >> 63)); + sp_2048_cond_sub_36(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 72); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5901,8 +5882,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -6013,8 +5993,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -6384,7 +6363,7 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 18 * 13); @@ -6622,76 +6601,76 @@ SP_NOINLINE static void sp_2048_lshift_36(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[35]; r[36] = s >> (57U - n); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[35] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[34] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[33] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[32] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[31] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[30] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[29] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[28] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[27] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[26] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[25] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[24] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[23] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[22] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[21] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[20] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[19] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[18] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[17] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[16] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[15] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[14] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[13] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[12] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[11] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[10] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; - r[0] = (a[0] << n) & 0x1ffffffffffffffL; + r[1] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); + r[0] = (sp_digit)((a[0] << n) & 0x1ffffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -6802,12 +6781,11 @@ static int sp_2048_mod_exp_2_36(sp_digit* r, const sp_digit* e, int bits, const sp_2048_mont_reduce_36(r, m, mp); n = sp_2048_cmp_36(r, m); - sp_2048_cond_sub_36(r, r, m, ~(n >> 63)); + sp_2048_cond_sub_36(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -7476,20 +7454,20 @@ SP_NOINLINE static void sp_3072_mul_add_26(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0xfffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0xfffffffffffffffL); t[1] += t[0] >> 60; - r[i+1] = t[1] & 0xfffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0xfffffffffffffffL); t[2] += t[1] >> 60; - r[i+2] = t[2] & 0xfffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0xfffffffffffffffL); t[3] += t[2] >> 60; - r[i+3] = t[3] & 0xfffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0xfffffffffffffffL); t[0] = t[3] >> 60; } t[0] += (tb * a[24]) + r[24]; t[1] = (tb * a[25]) + r[25]; - r[24] = t[0] & 0xfffffffffffffffL; + r[24] = (sp_digit)(t[0] & 0xfffffffffffffffL); t[1] += t[0] >> 60; - r[25] = t[1] & 0xfffffffffffffffL; + r[25] = (sp_digit)(t[1] & 0xfffffffffffffffL); r[26] += (sp_digit)(t[1] >> 60); } @@ -7505,7 +7483,7 @@ static void sp_3072_mont_shift_26(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[26]) << 24; for (i = 0; i < 25; i++) { - r[i] = n & 0xfffffffffffffffL; + r[i] = (sp_digit)(n & 0xfffffffffffffffL); n >>= 60; n += ((sp_int128)a[27 + i]) << 24; } @@ -7528,11 +7506,11 @@ static void sp_3072_mont_reduce_26(sp_digit* a, const sp_digit* m, sp_digit mp) sp_3072_norm_26(a + 26); for (i=0; i<25; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL); sp_3072_mul_add_26(a+i, m, mu); a[i+1] += a[i] >> 60; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffL); sp_3072_mul_add_26(a+i, m, mu); a[i+1] += a[i] >> 60; a[i] &= 0xfffffffffffffffL; @@ -7717,7 +7695,7 @@ SP_NOINLINE static void sp_3072_rshift_26(sp_digit* r, const sp_digit* a, int i; for (i=0; i<25; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (60 - n))) & 0xfffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (60 - n))) & 0xfffffffffffffffL); } r[25] = a[25] >> n; } @@ -7894,8 +7872,7 @@ static int sp_3072_div_26(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8007,14 +7984,13 @@ static int sp_3072_mod_exp_26(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_26(t[0], m, mp); n = sp_3072_cmp_26(t[0], m); - sp_3072_cond_sub_26(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_26(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 26 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8098,13 +8074,12 @@ static int sp_3072_mod_exp_26(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_26(t[0], m, mp); n = sp_3072_cmp_26(t[0], m); - sp_3072_cond_sub_26(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_26(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 26 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8244,13 +8219,12 @@ static int sp_3072_mod_exp_26(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_26(rt, m, mp); n = sp_3072_cmp_26(rt, m); - sp_3072_cond_sub_26(rt, rt, m, ~(n >> 63)); + sp_3072_cond_sub_26(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 52); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8356,26 +8330,26 @@ SP_NOINLINE static void sp_3072_mul_add_52(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0xfffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0xfffffffffffffffL); t[1] += t[0] >> 60; - r[i+1] = t[1] & 0xfffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0xfffffffffffffffL); t[2] += t[1] >> 60; - r[i+2] = t[2] & 0xfffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0xfffffffffffffffL); t[3] += t[2] >> 60; - r[i+3] = t[3] & 0xfffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0xfffffffffffffffL); t[0] = t[3] >> 60; } t[0] += (tb * a[48]) + r[48]; t[1] = (tb * a[49]) + r[49]; t[2] = (tb * a[50]) + r[50]; t[3] = (tb * a[51]) + r[51]; - r[48] = t[0] & 0xfffffffffffffffL; + r[48] = (sp_digit)(t[0] & 0xfffffffffffffffL); t[1] += t[0] >> 60; - r[49] = t[1] & 0xfffffffffffffffL; + r[49] = (sp_digit)(t[1] & 0xfffffffffffffffL); t[2] += t[1] >> 60; - r[50] = t[2] & 0xfffffffffffffffL; + r[50] = (sp_digit)(t[2] & 0xfffffffffffffffL); t[3] += t[2] >> 60; - r[51] = t[3] & 0xfffffffffffffffL; + r[51] = (sp_digit)(t[3] & 0xfffffffffffffffL); r[52] += (sp_digit)(t[3] >> 60); } @@ -8391,7 +8365,7 @@ static void sp_3072_mont_shift_52(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[52]) << 48; for (i = 0; i < 51; i++) { - r[i] = n & 0xfffffffffffffffL; + r[i] = (sp_digit)(n & 0xfffffffffffffffL); n >>= 60; n += ((sp_int128)a[53 + i]) << 48; } @@ -8416,33 +8390,33 @@ static void sp_3072_mont_reduce_52(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<51; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; a[i] &= 0xfffffffffffffffL; } else { for (i=0; i<51; i++) { - mu = a[i] & 0xfffffffffffffffL; + mu = (sp_digit)(a[i] & 0xfffffffffffffffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; } - mu = a[i] & 0xfffL; + mu = (sp_digit)(a[i] & 0xfffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; a[i] &= 0xfffffffffffffffL; } #else for (i=0; i<51; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffL); sp_3072_mul_add_52(a+i, m, mu); a[i+1] += a[i] >> 60; a[i] &= 0xfffffffffffffffL; @@ -8548,7 +8522,7 @@ SP_NOINLINE static void sp_3072_rshift_52(sp_digit* r, const sp_digit* a, int i; for (i=0; i<51; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (60 - n))) & 0xfffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (60 - n))) & 0xfffffffffffffffL); } r[51] = a[51] >> n; } @@ -8725,8 +8699,7 @@ static int sp_3072_div_52(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8839,14 +8812,13 @@ static int sp_3072_mod_exp_52(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_52(t[0], m, mp); n = sp_3072_cmp_52(t[0], m); - sp_3072_cond_sub_52(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_52(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 52 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8930,13 +8902,12 @@ static int sp_3072_mod_exp_52(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_52(t[0], m, mp); n = sp_3072_cmp_52(t[0], m); - sp_3072_cond_sub_52(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_52(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 52 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -9059,13 +9030,12 @@ static int sp_3072_mod_exp_52(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_52(rt, m, mp); n = sp_3072_cmp_52(rt, m); - sp_3072_cond_sub_52(rt, rt, m, ~(n >> 63)); + sp_3072_cond_sub_52(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 104); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -9184,8 +9154,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -9296,8 +9265,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -9667,7 +9635,7 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 26 * 13); @@ -9903,9 +9871,9 @@ SP_NOINLINE static void sp_3072_lshift_52(sp_digit* r, const sp_digit* a, r[52] = a[51] >> (60 - n); for (i=51; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (60 - n))) & 0xfffffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (60 - n))) & 0xfffffffffffffffL); } - r[0] = (a[0] << n) & 0xfffffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0xfffffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -10016,12 +9984,11 @@ static int sp_3072_mod_exp_2_52(sp_digit* r, const sp_digit* e, int bits, const sp_3072_mont_reduce_52(r, m, mp); n = sp_3072_cmp_52(r, m); - sp_3072_cond_sub_52(r, r, m, ~(n >> 63)); + sp_3072_cond_sub_52(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -10501,29 +10468,29 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_uint128)a[ 0]) * b[ 0]; t1 = ((sp_uint128)a[ 0]) * b[ 1] + ((sp_uint128)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 2] + ((sp_uint128)a[ 1]) * b[ 1] + ((sp_uint128)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 3] + ((sp_uint128)a[ 1]) * b[ 2] + ((sp_uint128)a[ 2]) * b[ 1] + ((sp_uint128)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 4] + ((sp_uint128)a[ 1]) * b[ 3] + ((sp_uint128)a[ 2]) * b[ 2] + ((sp_uint128)a[ 3]) * b[ 1] + ((sp_uint128)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 5] + ((sp_uint128)a[ 1]) * b[ 4] + ((sp_uint128)a[ 2]) * b[ 3] + ((sp_uint128)a[ 3]) * b[ 2] + ((sp_uint128)a[ 4]) * b[ 1] + ((sp_uint128)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 6] + ((sp_uint128)a[ 1]) * b[ 5] + ((sp_uint128)a[ 2]) * b[ 4] @@ -10531,7 +10498,7 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 4]) * b[ 2] + ((sp_uint128)a[ 5]) * b[ 1] + ((sp_uint128)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 0]) * b[ 7] + ((sp_uint128)a[ 1]) * b[ 6] + ((sp_uint128)a[ 2]) * b[ 5] @@ -10540,7 +10507,7 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 5]) * b[ 2] + ((sp_uint128)a[ 6]) * b[ 1] + ((sp_uint128)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 0]) * b[ 8] + ((sp_uint128)a[ 1]) * b[ 7] + ((sp_uint128)a[ 2]) * b[ 6] @@ -10550,7 +10517,7 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 2] + ((sp_uint128)a[ 7]) * b[ 1] + ((sp_uint128)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 1]) * b[ 8] + ((sp_uint128)a[ 2]) * b[ 7] + ((sp_uint128)a[ 3]) * b[ 6] @@ -10559,7 +10526,7 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 3] + ((sp_uint128)a[ 7]) * b[ 2] + ((sp_uint128)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 2]) * b[ 8] + ((sp_uint128)a[ 3]) * b[ 7] + ((sp_uint128)a[ 4]) * b[ 6] @@ -10567,35 +10534,35 @@ SP_NOINLINE static void sp_3072_mul_9(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 4] + ((sp_uint128)a[ 7]) * b[ 3] + ((sp_uint128)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 3]) * b[ 8] + ((sp_uint128)a[ 4]) * b[ 7] + ((sp_uint128)a[ 5]) * b[ 6] + ((sp_uint128)a[ 6]) * b[ 5] + ((sp_uint128)a[ 7]) * b[ 4] + ((sp_uint128)a[ 8]) * b[ 3]; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 4]) * b[ 8] + ((sp_uint128)a[ 5]) * b[ 7] + ((sp_uint128)a[ 6]) * b[ 6] + ((sp_uint128)a[ 7]) * b[ 5] + ((sp_uint128)a[ 8]) * b[ 4]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 5]) * b[ 8] + ((sp_uint128)a[ 6]) * b[ 7] + ((sp_uint128)a[ 7]) * b[ 6] + ((sp_uint128)a[ 8]) * b[ 5]; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 6]) * b[ 8] + ((sp_uint128)a[ 7]) * b[ 7] + ((sp_uint128)a[ 8]) * b[ 6]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_uint128)a[ 7]) * b[ 8] + ((sp_uint128)a[ 8]) * b[ 7]; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 8]) * b[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -10853,66 +10820,66 @@ SP_NOINLINE static void sp_3072_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_uint128)a[ 0]) * a[ 0]; t1 = (((sp_uint128)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 2]) * 2 + ((sp_uint128)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 3] + ((sp_uint128)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 4] + ((sp_uint128)a[ 1]) * a[ 3]) * 2 + ((sp_uint128)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 5] + ((sp_uint128)a[ 1]) * a[ 4] + ((sp_uint128)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 6] + ((sp_uint128)a[ 1]) * a[ 5] + ((sp_uint128)a[ 2]) * a[ 4]) * 2 + ((sp_uint128)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 0]) * a[ 7] + ((sp_uint128)a[ 1]) * a[ 6] + ((sp_uint128)a[ 2]) * a[ 5] + ((sp_uint128)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 0]) * a[ 8] + ((sp_uint128)a[ 1]) * a[ 7] + ((sp_uint128)a[ 2]) * a[ 6] + ((sp_uint128)a[ 3]) * a[ 5]) * 2 + ((sp_uint128)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 1]) * a[ 8] + ((sp_uint128)a[ 2]) * a[ 7] + ((sp_uint128)a[ 3]) * a[ 6] + ((sp_uint128)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 2]) * a[ 8] + ((sp_uint128)a[ 3]) * a[ 7] + ((sp_uint128)a[ 4]) * a[ 6]) * 2 + ((sp_uint128)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 3]) * a[ 8] + ((sp_uint128)a[ 4]) * a[ 7] + ((sp_uint128)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 4]) * a[ 8] + ((sp_uint128)a[ 5]) * a[ 7]) * 2 + ((sp_uint128)a[ 6]) * a[ 6]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 5]) * a[ 8] + ((sp_uint128)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_uint128)a[ 6]) * a[ 8]) * 2 + ((sp_uint128)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_uint128)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_uint128)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -11218,26 +11185,26 @@ static void sp_3072_mont_shift_27(sp_digit* r, const sp_digit* a) s = a[27]; n = a[26] >> 54; for (i = 0; i < 24; i += 8) { - n += (s & 0x1ffffffffffffffL) << 3; r[i+0] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+0] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+28] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+1] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+1] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+29] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+2] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+2] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+30] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+3] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+3] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+31] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+4] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+4] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+32] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+5] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+5] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+33] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+6] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+6] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+34] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[i+7] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[i+7] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[i+35] + (s >> 57); } - n += (s & 0x1ffffffffffffffL) << 3; r[24] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[24] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[52] + (s >> 57); - n += (s & 0x1ffffffffffffffL) << 3; r[25] = n & 0x1ffffffffffffffL; + n += (sp_digit)((s & 0x1ffffffffffffffL) << 3); r[25] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; s = a[53] + (s >> 57); n += s << 3; r[26] = n; XMEMSET(&r[27], 0, sizeof(*r) * 27U); @@ -11258,11 +11225,11 @@ static void sp_3072_mont_reduce_27(sp_digit* a, const sp_digit* m, sp_digit mp) sp_3072_norm_27(a + 27); for (i=0; i<26; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_3072_mul_add_27(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x3fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x3fffffffffffffL); sp_3072_mul_add_27(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; @@ -11387,17 +11354,17 @@ SP_NOINLINE static void sp_3072_rshift_27(sp_digit* r, const sp_digit* a, int i; for (i=0; i<24; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); - } - r[24] = (a[24] >> n) | ((a[25] << (57 - n)) & 0x1ffffffffffffffL); - r[25] = (a[25] >> n) | ((a[26] << (57 - n)) & 0x1ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); + } + r[24] = (a[24] >> n) | (sp_digit)((a[25] << (57 - n)) & 0x1ffffffffffffffL); + r[25] = (a[25] >> n) | (sp_digit)((a[26] << (57 - n)) & 0x1ffffffffffffffL); r[26] = a[26] >> n; } @@ -11573,8 +11540,7 @@ static int sp_3072_div_27(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -11686,14 +11652,13 @@ static int sp_3072_mod_exp_27(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_27(t[0], m, mp); n = sp_3072_cmp_27(t[0], m); - sp_3072_cond_sub_27(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_27(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 27 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -11777,13 +11742,12 @@ static int sp_3072_mod_exp_27(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_27(t[0], m, mp); n = sp_3072_cmp_27(t[0], m); - sp_3072_cond_sub_27(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_27(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 27 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -11923,13 +11887,12 @@ static int sp_3072_mod_exp_27(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_27(rt, m, mp); n = sp_3072_cmp_27(rt, m); - sp_3072_cond_sub_27(rt, rt, m, ~(n >> 63)); + sp_3072_cond_sub_27(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 54); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12092,28 +12055,28 @@ static void sp_3072_mont_shift_54(sp_digit* r, const sp_digit* a) sp_int128 n = a[53] >> 51; n += ((sp_int128)a[54]) << 6; for (i = 0; i < 48; i += 8) { - r[i + 0] = n & 0x1ffffffffffffffL; + r[i + 0] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 55]) << 6; - r[i + 1] = n & 0x1ffffffffffffffL; + r[i + 1] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 56]) << 6; - r[i + 2] = n & 0x1ffffffffffffffL; + r[i + 2] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 57]) << 6; - r[i + 3] = n & 0x1ffffffffffffffL; + r[i + 3] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 58]) << 6; - r[i + 4] = n & 0x1ffffffffffffffL; + r[i + 4] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 59]) << 6; - r[i + 5] = n & 0x1ffffffffffffffL; + r[i + 5] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 60]) << 6; - r[i + 6] = n & 0x1ffffffffffffffL; + r[i + 6] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 61]) << 6; - r[i + 7] = n & 0x1ffffffffffffffL; + r[i + 7] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[i + 62]) << 6; } - r[48] = n & 0x1ffffffffffffffL; n >>= 57; n += ((sp_int128)a[103]) << 6; - r[49] = n & 0x1ffffffffffffffL; n >>= 57; n += ((sp_int128)a[104]) << 6; - r[50] = n & 0x1ffffffffffffffL; n >>= 57; n += ((sp_int128)a[105]) << 6; - r[51] = n & 0x1ffffffffffffffL; n >>= 57; n += ((sp_int128)a[106]) << 6; - r[52] = n & 0x1ffffffffffffffL; n >>= 57; n += ((sp_int128)a[107]) << 6; + r[48] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[103]) << 6; + r[49] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[104]) << 6; + r[50] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[105]) << 6; + r[51] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[106]) << 6; + r[52] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; n += ((sp_int128)a[107]) << 6; r[53] = (sp_digit)n; XMEMSET(&r[54], 0, sizeof(*r) * 54U); } @@ -12135,33 +12098,33 @@ static void sp_3072_mont_reduce_54(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<53; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; } else { for (i=0; i<53; i++) { - mu = a[i] & 0x1ffffffffffffffL; + mu = (sp_digit)(a[i] & 0x1ffffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = a[i] & 0x7ffffffffffffL; + mu = (sp_digit)(a[i] & 0x7ffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; } #else for (i=0; i<53; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffL); sp_3072_mul_add_54(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; @@ -12281,20 +12244,20 @@ SP_NOINLINE static void sp_3072_rshift_54(sp_digit* r, const sp_digit* a, int i; for (i=0; i<48; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); - } - r[48] = (a[48] >> n) | ((a[49] << (57 - n)) & 0x1ffffffffffffffL); - r[49] = (a[49] >> n) | ((a[50] << (57 - n)) & 0x1ffffffffffffffL); - r[50] = (a[50] >> n) | ((a[51] << (57 - n)) & 0x1ffffffffffffffL); - r[51] = (a[51] >> n) | ((a[52] << (57 - n)) & 0x1ffffffffffffffL); - r[52] = (a[52] >> n) | ((a[53] << (57 - n)) & 0x1ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); + } + r[48] = (a[48] >> n) | (sp_digit)((a[49] << (57 - n)) & 0x1ffffffffffffffL); + r[49] = (a[49] >> n) | (sp_digit)((a[50] << (57 - n)) & 0x1ffffffffffffffL); + r[50] = (a[50] >> n) | (sp_digit)((a[51] << (57 - n)) & 0x1ffffffffffffffL); + r[51] = (a[51] >> n) | (sp_digit)((a[52] << (57 - n)) & 0x1ffffffffffffffL); + r[52] = (a[52] >> n) | (sp_digit)((a[53] << (57 - n)) & 0x1ffffffffffffffL); r[53] = a[53] >> n; } @@ -12470,8 +12433,7 @@ static int sp_3072_div_54(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12586,14 +12548,13 @@ static int sp_3072_mod_exp_54(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_54(t[0], m, mp); n = sp_3072_cmp_54(t[0], m); - sp_3072_cond_sub_54(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_54(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 54 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12677,13 +12638,12 @@ static int sp_3072_mod_exp_54(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_54(t[0], m, mp); n = sp_3072_cmp_54(t[0], m); - sp_3072_cond_sub_54(t[0], t[0], m, ~(n >> 63)); + sp_3072_cond_sub_54(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 54 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12806,13 +12766,12 @@ static int sp_3072_mod_exp_54(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_3072_mont_reduce_54(rt, m, mp); n = sp_3072_cmp_54(rt, m); - sp_3072_cond_sub_54(rt, rt, m, ~(n >> 63)); + sp_3072_cond_sub_54(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 108); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12933,8 +12892,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -13045,8 +13003,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -13416,7 +13373,7 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 27 * 13); @@ -13654,112 +13611,112 @@ SP_NOINLINE static void sp_3072_lshift_54(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[53]; r[54] = s >> (57U - n); s = (sp_int_digit)(a[53]); t = (sp_int_digit)(a[52]); - r[53] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[53] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[52]); t = (sp_int_digit)(a[51]); - r[52] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[52] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[51]); t = (sp_int_digit)(a[50]); - r[51] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[51] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[50]); t = (sp_int_digit)(a[49]); - r[50] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[50] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[49]); t = (sp_int_digit)(a[48]); - r[49] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[49] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[48]); t = (sp_int_digit)(a[47]); - r[48] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[48] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[47]); t = (sp_int_digit)(a[46]); - r[47] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[47] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[46]); t = (sp_int_digit)(a[45]); - r[46] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[46] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[45]); t = (sp_int_digit)(a[44]); - r[45] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[45] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[44]); t = (sp_int_digit)(a[43]); - r[44] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[44] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[43]); t = (sp_int_digit)(a[42]); - r[43] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[43] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[42]); t = (sp_int_digit)(a[41]); - r[42] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[42] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[41] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[40] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[39] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[38] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[37] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[36] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[35] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[34] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[33] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[32] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[31] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[30] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[29] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[28] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[27] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[26] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[25] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[24] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[23] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[22] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[21] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[20] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[19] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[18] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[17] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[16] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[15] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[14] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[13] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[12] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[11] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[10] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL; - r[0] = (a[0] << n) & 0x1ffffffffffffffL; + r[1] = (sp_digit)(((s << n) | (t >> (57U - n))) & 0x1ffffffffffffffUL); + r[0] = (sp_digit)((a[0] << n) & 0x1ffffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -13870,12 +13827,11 @@ static int sp_3072_mod_exp_2_54(sp_digit* r, const sp_digit* e, int bits, const sp_3072_mont_reduce_54(r, m, mp); n = sp_3072_cmp_54(r, m); - sp_3072_cond_sub_54(r, r, m, ~(n >> 63)); + sp_3072_cond_sub_54(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -14547,23 +14503,23 @@ SP_NOINLINE static void sp_4096_mul_add_35(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x7ffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x7ffffffffffffffL); t[1] += t[0] >> 59; - r[i+1] = t[1] & 0x7ffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x7ffffffffffffffL); t[2] += t[1] >> 59; - r[i+2] = t[2] & 0x7ffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x7ffffffffffffffL); t[3] += t[2] >> 59; - r[i+3] = t[3] & 0x7ffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x7ffffffffffffffL); t[0] = t[3] >> 59; } t[0] += (tb * a[32]) + r[32]; t[1] = (tb * a[33]) + r[33]; t[2] = (tb * a[34]) + r[34]; - r[32] = t[0] & 0x7ffffffffffffffL; + r[32] = (sp_digit)(t[0] & 0x7ffffffffffffffL); t[1] += t[0] >> 59; - r[33] = t[1] & 0x7ffffffffffffffL; + r[33] = (sp_digit)(t[1] & 0x7ffffffffffffffL); t[2] += t[1] >> 59; - r[34] = t[2] & 0x7ffffffffffffffL; + r[34] = (sp_digit)(t[2] & 0x7ffffffffffffffL); r[35] += (sp_digit)(t[2] >> 59); } @@ -14579,7 +14535,7 @@ static void sp_4096_mont_shift_35(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[35]) << 17; for (i = 0; i < 34; i++) { - r[i] = n & 0x7ffffffffffffffL; + r[i] = (sp_digit)(n & 0x7ffffffffffffffL); n >>= 59; n += ((sp_int128)a[36 + i]) << 17; } @@ -14602,11 +14558,11 @@ static void sp_4096_mont_reduce_35(sp_digit* a, const sp_digit* m, sp_digit mp) sp_4096_norm_35(a + 35); for (i=0; i<34; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL); sp_4096_mul_add_35(a+i, m, mu); a[i+1] += a[i] >> 59; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffffL); sp_4096_mul_add_35(a+i, m, mu); a[i+1] += a[i] >> 59; a[i] &= 0x7ffffffffffffffL; @@ -14791,7 +14747,7 @@ SP_NOINLINE static void sp_4096_rshift_35(sp_digit* r, const sp_digit* a, int i; for (i=0; i<34; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (59 - n))) & 0x7ffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (59 - n))) & 0x7ffffffffffffffL); } r[34] = a[34] >> n; } @@ -14968,8 +14924,7 @@ static int sp_4096_div_35(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15081,14 +15036,13 @@ static int sp_4096_mod_exp_35(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_35(t[0], m, mp); n = sp_4096_cmp_35(t[0], m); - sp_4096_cond_sub_35(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_35(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 35 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15172,13 +15126,12 @@ static int sp_4096_mod_exp_35(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_35(t[0], m, mp); n = sp_4096_cmp_35(t[0], m); - sp_4096_cond_sub_35(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_35(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 35 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15318,13 +15271,12 @@ static int sp_4096_mod_exp_35(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_35(rt, m, mp); n = sp_4096_cmp_35(rt, m); - sp_4096_cond_sub_35(rt, rt, m, ~(n >> 63)); + sp_4096_cond_sub_35(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 70); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15431,20 +15383,20 @@ SP_NOINLINE static void sp_4096_mul_add_70(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x7ffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x7ffffffffffffffL); t[1] += t[0] >> 59; - r[i+1] = t[1] & 0x7ffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x7ffffffffffffffL); t[2] += t[1] >> 59; - r[i+2] = t[2] & 0x7ffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x7ffffffffffffffL); t[3] += t[2] >> 59; - r[i+3] = t[3] & 0x7ffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x7ffffffffffffffL); t[0] = t[3] >> 59; } t[0] += (tb * a[68]) + r[68]; t[1] = (tb * a[69]) + r[69]; - r[68] = t[0] & 0x7ffffffffffffffL; + r[68] = (sp_digit)(t[0] & 0x7ffffffffffffffL); t[1] += t[0] >> 59; - r[69] = t[1] & 0x7ffffffffffffffL; + r[69] = (sp_digit)(t[1] & 0x7ffffffffffffffL); r[70] += (sp_digit)(t[1] >> 59); } @@ -15460,7 +15412,7 @@ static void sp_4096_mont_shift_70(sp_digit* r, const sp_digit* a) n += ((sp_int128)a[70]) << 34; for (i = 0; i < 69; i++) { - r[i] = n & 0x7ffffffffffffffL; + r[i] = (sp_digit)(n & 0x7ffffffffffffffL); n >>= 59; n += ((sp_int128)a[71 + i]) << 34; } @@ -15485,33 +15437,33 @@ static void sp_4096_mont_reduce_70(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<69; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; a[i] &= 0x7ffffffffffffffL; } else { for (i=0; i<69; i++) { - mu = a[i] & 0x7ffffffffffffffL; + mu = (sp_digit)(a[i] & 0x7ffffffffffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; } - mu = a[i] & 0x1ffffffL; + mu = (sp_digit)(a[i] & 0x1ffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; a[i] &= 0x7ffffffffffffffL; } #else for (i=0; i<69; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7ffffffffffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffL); sp_4096_mul_add_70(a+i, m, mu); a[i+1] += a[i] >> 59; a[i] &= 0x7ffffffffffffffL; @@ -15617,7 +15569,7 @@ SP_NOINLINE static void sp_4096_rshift_70(sp_digit* r, const sp_digit* a, int i; for (i=0; i<69; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (59 - n))) & 0x7ffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (59 - n))) & 0x7ffffffffffffffL); } r[69] = a[69] >> n; } @@ -15794,8 +15746,7 @@ static int sp_4096_div_70(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15908,14 +15859,13 @@ static int sp_4096_mod_exp_70(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_70(t[0], m, mp); n = sp_4096_cmp_70(t[0], m); - sp_4096_cond_sub_70(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_70(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 70 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -15999,13 +15949,12 @@ static int sp_4096_mod_exp_70(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_70(t[0], m, mp); n = sp_4096_cmp_70(t[0], m); - sp_4096_cond_sub_70(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_70(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 70 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -16128,13 +16077,12 @@ static int sp_4096_mod_exp_70(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_70(rt, m, mp); n = sp_4096_cmp_70(rt, m); - sp_4096_cond_sub_70(rt, rt, m, ~(n >> 63)); + sp_4096_cond_sub_70(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 140); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -16253,8 +16201,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -16365,8 +16312,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -16736,7 +16682,7 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 35 * 13); @@ -16972,9 +16918,9 @@ SP_NOINLINE static void sp_4096_lshift_70(sp_digit* r, const sp_digit* a, r[70] = a[69] >> (59 - n); for (i=69; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (59 - n))) & 0x7ffffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (59 - n))) & 0x7ffffffffffffffL); } - r[0] = (a[0] << n) & 0x7ffffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0x7ffffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -17085,12 +17031,11 @@ static int sp_4096_mod_exp_2_70(sp_digit* r, const sp_digit* e, int bits, const sp_4096_mont_reduce_70(r, m, mp); n = sp_4096_cmp_70(r, m); - sp_4096_cond_sub_70(r, r, m, ~(n >> 63)); + sp_4096_cond_sub_70(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -17434,29 +17379,29 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, t0 = ((sp_uint128)a[ 0]) * b[ 0]; t1 = ((sp_uint128)a[ 0]) * b[ 1] + ((sp_uint128)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 0] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[ 2] + ((sp_uint128)a[ 1]) * b[ 1] + ((sp_uint128)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 1] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 0]) * b[ 3] + ((sp_uint128)a[ 1]) * b[ 2] + ((sp_uint128)a[ 2]) * b[ 1] + ((sp_uint128)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 2] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[ 4] + ((sp_uint128)a[ 1]) * b[ 3] + ((sp_uint128)a[ 2]) * b[ 2] + ((sp_uint128)a[ 3]) * b[ 1] + ((sp_uint128)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 3] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 0]) * b[ 5] + ((sp_uint128)a[ 1]) * b[ 4] + ((sp_uint128)a[ 2]) * b[ 3] + ((sp_uint128)a[ 3]) * b[ 2] + ((sp_uint128)a[ 4]) * b[ 1] + ((sp_uint128)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 4] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[ 6] + ((sp_uint128)a[ 1]) * b[ 5] + ((sp_uint128)a[ 2]) * b[ 4] @@ -17464,7 +17409,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 4]) * b[ 2] + ((sp_uint128)a[ 5]) * b[ 1] + ((sp_uint128)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 5] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 0]) * b[ 7] + ((sp_uint128)a[ 1]) * b[ 6] + ((sp_uint128)a[ 2]) * b[ 5] @@ -17473,7 +17418,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 5]) * b[ 2] + ((sp_uint128)a[ 6]) * b[ 1] + ((sp_uint128)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 6] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[ 8] + ((sp_uint128)a[ 1]) * b[ 7] + ((sp_uint128)a[ 2]) * b[ 6] @@ -17483,7 +17428,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 6]) * b[ 2] + ((sp_uint128)a[ 7]) * b[ 1] + ((sp_uint128)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 7] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 0]) * b[ 9] + ((sp_uint128)a[ 1]) * b[ 8] + ((sp_uint128)a[ 2]) * b[ 7] @@ -17494,7 +17439,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 7]) * b[ 2] + ((sp_uint128)a[ 8]) * b[ 1] + ((sp_uint128)a[ 9]) * b[ 0]; - t[ 8] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 8] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[10] + ((sp_uint128)a[ 1]) * b[ 9] + ((sp_uint128)a[ 2]) * b[ 8] @@ -17506,7 +17451,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 8]) * b[ 2] + ((sp_uint128)a[ 9]) * b[ 1] + ((sp_uint128)a[10]) * b[ 0]; - t[ 9] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 9] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 0]) * b[11] + ((sp_uint128)a[ 1]) * b[10] + ((sp_uint128)a[ 2]) * b[ 9] @@ -17519,7 +17464,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[ 9]) * b[ 2] + ((sp_uint128)a[10]) * b[ 1] + ((sp_uint128)a[11]) * b[ 0]; - t[10] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[10] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 0]) * b[12] + ((sp_uint128)a[ 1]) * b[11] + ((sp_uint128)a[ 2]) * b[10] @@ -17533,7 +17478,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 2] + ((sp_uint128)a[11]) * b[ 1] + ((sp_uint128)a[12]) * b[ 0]; - t[11] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[11] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 1]) * b[12] + ((sp_uint128)a[ 2]) * b[11] + ((sp_uint128)a[ 3]) * b[10] @@ -17546,7 +17491,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 3] + ((sp_uint128)a[11]) * b[ 2] + ((sp_uint128)a[12]) * b[ 1]; - t[12] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[12] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 2]) * b[12] + ((sp_uint128)a[ 3]) * b[11] + ((sp_uint128)a[ 4]) * b[10] @@ -17558,7 +17503,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 4] + ((sp_uint128)a[11]) * b[ 3] + ((sp_uint128)a[12]) * b[ 2]; - r[13] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[13] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 3]) * b[12] + ((sp_uint128)a[ 4]) * b[11] + ((sp_uint128)a[ 5]) * b[10] @@ -17569,7 +17514,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 5] + ((sp_uint128)a[11]) * b[ 4] + ((sp_uint128)a[12]) * b[ 3]; - r[14] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[14] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 4]) * b[12] + ((sp_uint128)a[ 5]) * b[11] + ((sp_uint128)a[ 6]) * b[10] @@ -17579,7 +17524,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 6] + ((sp_uint128)a[11]) * b[ 5] + ((sp_uint128)a[12]) * b[ 4]; - r[15] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[15] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 5]) * b[12] + ((sp_uint128)a[ 6]) * b[11] + ((sp_uint128)a[ 7]) * b[10] @@ -17588,7 +17533,7 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 7] + ((sp_uint128)a[11]) * b[ 6] + ((sp_uint128)a[12]) * b[ 5]; - r[16] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[16] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 6]) * b[12] + ((sp_uint128)a[ 7]) * b[11] + ((sp_uint128)a[ 8]) * b[10] @@ -17596,35 +17541,35 @@ SP_NOINLINE static void sp_4096_mul_13(sp_digit* r, const sp_digit* a, + ((sp_uint128)a[10]) * b[ 8] + ((sp_uint128)a[11]) * b[ 7] + ((sp_uint128)a[12]) * b[ 6]; - r[17] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[17] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 7]) * b[12] + ((sp_uint128)a[ 8]) * b[11] + ((sp_uint128)a[ 9]) * b[10] + ((sp_uint128)a[10]) * b[ 9] + ((sp_uint128)a[11]) * b[ 8] + ((sp_uint128)a[12]) * b[ 7]; - r[18] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[18] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[ 8]) * b[12] + ((sp_uint128)a[ 9]) * b[11] + ((sp_uint128)a[10]) * b[10] + ((sp_uint128)a[11]) * b[ 9] + ((sp_uint128)a[12]) * b[ 8]; - r[19] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[19] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[ 9]) * b[12] + ((sp_uint128)a[10]) * b[11] + ((sp_uint128)a[11]) * b[10] + ((sp_uint128)a[12]) * b[ 9]; - r[20] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[20] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[10]) * b[12] + ((sp_uint128)a[11]) * b[11] + ((sp_uint128)a[12]) * b[10]; - r[21] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[21] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = ((sp_uint128)a[11]) * b[12] + ((sp_uint128)a[12]) * b[11]; - r[22] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[22] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[12]) * b[12]; - r[23] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; - r[24] = t0 & 0x1fffffffffffffL; + r[23] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; + r[24] = (sp_digit)(t0 & 0x1fffffffffffffL); r[25] = (sp_digit)(t0 >> 53); XMEMCPY(r, t, sizeof(t)); } @@ -17890,57 +17835,57 @@ SP_NOINLINE static void sp_4096_sqr_13(sp_digit* r, const sp_digit* a) t0 = ((sp_uint128)a[ 0]) * a[ 0]; t1 = (((sp_uint128)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 0] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[ 2]) * 2 + ((sp_uint128)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 1] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 0]) * a[ 3] + ((sp_uint128)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 2] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[ 4] + ((sp_uint128)a[ 1]) * a[ 3]) * 2 + ((sp_uint128)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 3] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 0]) * a[ 5] + ((sp_uint128)a[ 1]) * a[ 4] + ((sp_uint128)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 4] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[ 6] + ((sp_uint128)a[ 1]) * a[ 5] + ((sp_uint128)a[ 2]) * a[ 4]) * 2 + ((sp_uint128)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 5] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 0]) * a[ 7] + ((sp_uint128)a[ 1]) * a[ 6] + ((sp_uint128)a[ 2]) * a[ 5] + ((sp_uint128)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 6] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[ 8] + ((sp_uint128)a[ 1]) * a[ 7] + ((sp_uint128)a[ 2]) * a[ 6] + ((sp_uint128)a[ 3]) * a[ 5]) * 2 + ((sp_uint128)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 7] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 0]) * a[ 9] + ((sp_uint128)a[ 1]) * a[ 8] + ((sp_uint128)a[ 2]) * a[ 7] + ((sp_uint128)a[ 3]) * a[ 6] + ((sp_uint128)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[ 8] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[10] + ((sp_uint128)a[ 1]) * a[ 9] + ((sp_uint128)a[ 2]) * a[ 8] + ((sp_uint128)a[ 3]) * a[ 7] + ((sp_uint128)a[ 4]) * a[ 6]) * 2 + ((sp_uint128)a[ 5]) * a[ 5]; - t[ 9] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[ 9] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 0]) * a[11] + ((sp_uint128)a[ 1]) * a[10] + ((sp_uint128)a[ 2]) * a[ 9] + ((sp_uint128)a[ 3]) * a[ 8] + ((sp_uint128)a[ 4]) * a[ 7] + ((sp_uint128)a[ 5]) * a[ 6]) * 2; - t[10] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[10] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 0]) * a[12] + ((sp_uint128)a[ 1]) * a[11] + ((sp_uint128)a[ 2]) * a[10] @@ -17948,62 +17893,62 @@ SP_NOINLINE static void sp_4096_sqr_13(sp_digit* r, const sp_digit* a) + ((sp_uint128)a[ 4]) * a[ 8] + ((sp_uint128)a[ 5]) * a[ 7]) * 2 + ((sp_uint128)a[ 6]) * a[ 6]; - t[11] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + t[11] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 1]) * a[12] + ((sp_uint128)a[ 2]) * a[11] + ((sp_uint128)a[ 3]) * a[10] + ((sp_uint128)a[ 4]) * a[ 9] + ((sp_uint128)a[ 5]) * a[ 8] + ((sp_uint128)a[ 6]) * a[ 7]) * 2; - t[12] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + t[12] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 2]) * a[12] + ((sp_uint128)a[ 3]) * a[11] + ((sp_uint128)a[ 4]) * a[10] + ((sp_uint128)a[ 5]) * a[ 9] + ((sp_uint128)a[ 6]) * a[ 8]) * 2 + ((sp_uint128)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[13] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 3]) * a[12] + ((sp_uint128)a[ 4]) * a[11] + ((sp_uint128)a[ 5]) * a[10] + ((sp_uint128)a[ 6]) * a[ 9] + ((sp_uint128)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[14] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 4]) * a[12] + ((sp_uint128)a[ 5]) * a[11] + ((sp_uint128)a[ 6]) * a[10] + ((sp_uint128)a[ 7]) * a[ 9]) * 2 + ((sp_uint128)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[15] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 5]) * a[12] + ((sp_uint128)a[ 6]) * a[11] + ((sp_uint128)a[ 7]) * a[10] + ((sp_uint128)a[ 8]) * a[ 9]) * 2; - r[16] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[16] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 6]) * a[12] + ((sp_uint128)a[ 7]) * a[11] + ((sp_uint128)a[ 8]) * a[10]) * 2 + ((sp_uint128)a[ 9]) * a[ 9]; - r[17] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[17] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 7]) * a[12] + ((sp_uint128)a[ 8]) * a[11] + ((sp_uint128)a[ 9]) * a[10]) * 2; - r[18] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[18] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[ 8]) * a[12] + ((sp_uint128)a[ 9]) * a[11]) * 2 + ((sp_uint128)a[10]) * a[10]; - r[19] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[19] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[ 9]) * a[12] + ((sp_uint128)a[10]) * a[11]) * 2; - r[20] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[20] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = (((sp_uint128)a[10]) * a[12]) * 2 + ((sp_uint128)a[11]) * a[11]; - r[21] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; + r[21] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; t1 = (((sp_uint128)a[11]) * a[12]) * 2; - r[22] = t0 & 0x1fffffffffffffL; t1 += t0 >> 53; + r[22] = (sp_digit)(t0 & 0x1fffffffffffffL); t1 += t0 >> 53; t0 = ((sp_uint128)a[12]) * a[12]; - r[23] = t1 & 0x1fffffffffffffL; t0 += t1 >> 53; - r[24] = t0 & 0x1fffffffffffffL; + r[23] = (sp_digit)(t1 & 0x1fffffffffffffL); t0 += t1 >> 53; + r[24] = (sp_digit)(t0 & 0x1fffffffffffffL); r[25] = (sp_digit)(t0 >> 53); XMEMCPY(r, t, sizeof(t)); } @@ -18332,29 +18277,29 @@ static void sp_4096_mont_shift_39(sp_digit* r, const sp_digit* a) sp_int128 n = a[38] >> 34; n += ((sp_int128)a[39]) << 19; for (i = 0; i < 32; i += 8) { - r[i + 0] = n & 0x1fffffffffffffL; + r[i + 0] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 40]) << 19; - r[i + 1] = n & 0x1fffffffffffffL; + r[i + 1] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 41]) << 19; - r[i + 2] = n & 0x1fffffffffffffL; + r[i + 2] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 42]) << 19; - r[i + 3] = n & 0x1fffffffffffffL; + r[i + 3] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 43]) << 19; - r[i + 4] = n & 0x1fffffffffffffL; + r[i + 4] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 44]) << 19; - r[i + 5] = n & 0x1fffffffffffffL; + r[i + 5] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 45]) << 19; - r[i + 6] = n & 0x1fffffffffffffL; + r[i + 6] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 46]) << 19; - r[i + 7] = n & 0x1fffffffffffffL; + r[i + 7] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 47]) << 19; } - r[32] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[72]) << 19; - r[33] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[73]) << 19; - r[34] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[74]) << 19; - r[35] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[75]) << 19; - r[36] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[76]) << 19; - r[37] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[77]) << 19; + r[32] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[72]) << 19; + r[33] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[73]) << 19; + r[34] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[74]) << 19; + r[35] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[75]) << 19; + r[36] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[76]) << 19; + r[37] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[77]) << 19; r[38] = (sp_digit)n; XMEMSET(&r[39], 0, sizeof(*r) * 39U); } @@ -18374,11 +18319,11 @@ static void sp_4096_mont_reduce_39(sp_digit* a, const sp_digit* m, sp_digit mp) sp_4096_norm_39(a + 39); for (i=0; i<38; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL); sp_4096_mul_add_39(a+i, m, mu); a[i+1] += a[i] >> 53; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffL); sp_4096_mul_add_39(a+i, m, mu); a[i+1] += a[i] >> 53; a[i] &= 0x1fffffffffffffL; @@ -18507,21 +18452,21 @@ SP_NOINLINE static void sp_4096_rshift_39(sp_digit* r, const sp_digit* a, int i; for (i=0; i<32; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (53 - n)) & 0x1fffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (53 - n)) & 0x1fffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (53 - n)) & 0x1fffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (53 - n)) & 0x1fffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (53 - n)) & 0x1fffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (53 - n)) & 0x1fffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (53 - n)) & 0x1fffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (53 - n)) & 0x1fffffffffffffL); - } - r[32] = (a[32] >> n) | ((a[33] << (53 - n)) & 0x1fffffffffffffL); - r[33] = (a[33] >> n) | ((a[34] << (53 - n)) & 0x1fffffffffffffL); - r[34] = (a[34] >> n) | ((a[35] << (53 - n)) & 0x1fffffffffffffL); - r[35] = (a[35] >> n) | ((a[36] << (53 - n)) & 0x1fffffffffffffL); - r[36] = (a[36] >> n) | ((a[37] << (53 - n)) & 0x1fffffffffffffL); - r[37] = (a[37] >> n) | ((a[38] << (53 - n)) & 0x1fffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (53 - n)) & 0x1fffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (53 - n)) & 0x1fffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (53 - n)) & 0x1fffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (53 - n)) & 0x1fffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (53 - n)) & 0x1fffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (53 - n)) & 0x1fffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (53 - n)) & 0x1fffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (53 - n)) & 0x1fffffffffffffL); + } + r[32] = (a[32] >> n) | (sp_digit)((a[33] << (53 - n)) & 0x1fffffffffffffL); + r[33] = (a[33] >> n) | (sp_digit)((a[34] << (53 - n)) & 0x1fffffffffffffL); + r[34] = (a[34] >> n) | (sp_digit)((a[35] << (53 - n)) & 0x1fffffffffffffL); + r[35] = (a[35] >> n) | (sp_digit)((a[36] << (53 - n)) & 0x1fffffffffffffL); + r[36] = (a[36] >> n) | (sp_digit)((a[37] << (53 - n)) & 0x1fffffffffffffL); + r[37] = (a[37] >> n) | (sp_digit)((a[38] << (53 - n)) & 0x1fffffffffffffL); r[38] = a[38] >> n; } @@ -18697,8 +18642,7 @@ static int sp_4096_div_39(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18810,14 +18754,13 @@ static int sp_4096_mod_exp_39(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_39(t[0], m, mp); n = sp_4096_cmp_39(t[0], m); - sp_4096_cond_sub_39(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_39(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 39 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -18901,13 +18844,12 @@ static int sp_4096_mod_exp_39(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_39(t[0], m, mp); n = sp_4096_cmp_39(t[0], m); - sp_4096_cond_sub_39(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_39(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 39 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -19047,13 +18989,12 @@ static int sp_4096_mod_exp_39(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_39(rt, m, mp); n = sp_4096_cmp_39(rt, m); - sp_4096_cond_sub_39(rt, rt, m, ~(n >> 63)); + sp_4096_cond_sub_39(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 78); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -19217,28 +19158,28 @@ static void sp_4096_mont_shift_78(sp_digit* r, const sp_digit* a) sp_int128 n = a[77] >> 15; n += ((sp_int128)a[78]) << 38; for (i = 0; i < 72; i += 8) { - r[i + 0] = n & 0x1fffffffffffffL; + r[i + 0] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 79]) << 38; - r[i + 1] = n & 0x1fffffffffffffL; + r[i + 1] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 80]) << 38; - r[i + 2] = n & 0x1fffffffffffffL; + r[i + 2] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 81]) << 38; - r[i + 3] = n & 0x1fffffffffffffL; + r[i + 3] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 82]) << 38; - r[i + 4] = n & 0x1fffffffffffffL; + r[i + 4] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 83]) << 38; - r[i + 5] = n & 0x1fffffffffffffL; + r[i + 5] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 84]) << 38; - r[i + 6] = n & 0x1fffffffffffffL; + r[i + 6] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 85]) << 38; - r[i + 7] = n & 0x1fffffffffffffL; + r[i + 7] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[i + 86]) << 38; } - r[72] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[151]) << 38; - r[73] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[152]) << 38; - r[74] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[153]) << 38; - r[75] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[154]) << 38; - r[76] = n & 0x1fffffffffffffL; n >>= 53; n += ((sp_int128)a[155]) << 38; + r[72] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[151]) << 38; + r[73] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[152]) << 38; + r[74] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[153]) << 38; + r[75] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[154]) << 38; + r[76] = (sp_digit)(n & 0x1fffffffffffffL); n >>= 53; n += ((sp_int128)a[155]) << 38; r[77] = (sp_digit)n; XMEMSET(&r[78], 0, sizeof(*r) * 78U); } @@ -19260,33 +19201,33 @@ static void sp_4096_mont_reduce_78(sp_digit* a, const sp_digit* m, sp_digit mp) #ifdef WOLFSSL_SP_DH if (mp != 1) { for (i=0; i<77; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; a[i] &= 0x1fffffffffffffL; } else { for (i=0; i<77; i++) { - mu = a[i] & 0x1fffffffffffffL; + mu = (sp_digit)(a[i] & 0x1fffffffffffffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; } - mu = a[i] & 0x7fffL; + mu = (sp_digit)(a[i] & 0x7fffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; a[i] &= 0x1fffffffffffffL; } #else for (i=0; i<77; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1fffffffffffffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffL); sp_4096_mul_add_78(a+i, m, mu); a[i+1] += a[i] >> 53; a[i] &= 0x1fffffffffffffL; @@ -19406,20 +19347,20 @@ SP_NOINLINE static void sp_4096_rshift_78(sp_digit* r, const sp_digit* a, int i; for (i=0; i<72; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (53 - n)) & 0x1fffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (53 - n)) & 0x1fffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (53 - n)) & 0x1fffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (53 - n)) & 0x1fffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (53 - n)) & 0x1fffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (53 - n)) & 0x1fffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (53 - n)) & 0x1fffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (53 - n)) & 0x1fffffffffffffL); - } - r[72] = (a[72] >> n) | ((a[73] << (53 - n)) & 0x1fffffffffffffL); - r[73] = (a[73] >> n) | ((a[74] << (53 - n)) & 0x1fffffffffffffL); - r[74] = (a[74] >> n) | ((a[75] << (53 - n)) & 0x1fffffffffffffL); - r[75] = (a[75] >> n) | ((a[76] << (53 - n)) & 0x1fffffffffffffL); - r[76] = (a[76] >> n) | ((a[77] << (53 - n)) & 0x1fffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (53 - n)) & 0x1fffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (53 - n)) & 0x1fffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (53 - n)) & 0x1fffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (53 - n)) & 0x1fffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (53 - n)) & 0x1fffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (53 - n)) & 0x1fffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (53 - n)) & 0x1fffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (53 - n)) & 0x1fffffffffffffL); + } + r[72] = (a[72] >> n) | (sp_digit)((a[73] << (53 - n)) & 0x1fffffffffffffL); + r[73] = (a[73] >> n) | (sp_digit)((a[74] << (53 - n)) & 0x1fffffffffffffL); + r[74] = (a[74] >> n) | (sp_digit)((a[75] << (53 - n)) & 0x1fffffffffffffL); + r[75] = (a[75] >> n) | (sp_digit)((a[76] << (53 - n)) & 0x1fffffffffffffL); + r[76] = (a[76] >> n) | (sp_digit)((a[77] << (53 - n)) & 0x1fffffffffffffL); r[77] = a[77] >> n; } @@ -19595,8 +19536,7 @@ static int sp_4096_div_78(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -19711,14 +19651,13 @@ static int sp_4096_mod_exp_78(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_78(t[0], m, mp); n = sp_4096_cmp_78(t[0], m); - sp_4096_cond_sub_78(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_78(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 78 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -19802,13 +19741,12 @@ static int sp_4096_mod_exp_78(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_78(t[0], m, mp); n = sp_4096_cmp_78(t[0], m); - sp_4096_cond_sub_78(t[0], t[0], m, ~(n >> 63)); + sp_4096_cond_sub_78(t[0], t[0], m, (sp_digit)~(n >> 63)); XMEMCPY(r, t[0], sizeof(*r) * 78 * 2); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -19931,13 +19869,12 @@ static int sp_4096_mod_exp_78(sp_digit* r, const sp_digit* a, const sp_digit* e, sp_4096_mont_reduce_78(rt, m, mp); n = sp_4096_cmp_78(rt, m); - sp_4096_cond_sub_78(rt, rt, m, ~(n >> 63)); + sp_4096_cond_sub_78(rt, rt, m, (sp_digit)~(n >> 63)); XMEMCPY(r, rt, sizeof(sp_digit) * 156); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20058,8 +19995,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -20170,8 +20106,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (d != NULL) - XFREE(d, NULL, DYNAMIC_TYPE_RSA); + XFREE(d, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -20541,7 +20476,7 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, } #ifdef WOLFSSL_SP_SMALL_STACK -if (a != NULL) + if (a != NULL) #endif { ForceZero(a, sizeof(sp_digit) * 39 * 13); @@ -20779,160 +20714,160 @@ SP_NOINLINE static void sp_4096_lshift_78(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[77]; r[78] = s >> (53U - n); s = (sp_int_digit)(a[77]); t = (sp_int_digit)(a[76]); - r[77] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[77] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[76]); t = (sp_int_digit)(a[75]); - r[76] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[76] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[75]); t = (sp_int_digit)(a[74]); - r[75] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[75] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[74]); t = (sp_int_digit)(a[73]); - r[74] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[74] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[73]); t = (sp_int_digit)(a[72]); - r[73] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[73] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[72]); t = (sp_int_digit)(a[71]); - r[72] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[72] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[71]); t = (sp_int_digit)(a[70]); - r[71] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[71] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[70]); t = (sp_int_digit)(a[69]); - r[70] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[70] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[69]); t = (sp_int_digit)(a[68]); - r[69] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[69] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[68]); t = (sp_int_digit)(a[67]); - r[68] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[68] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[67]); t = (sp_int_digit)(a[66]); - r[67] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[67] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[66]); t = (sp_int_digit)(a[65]); - r[66] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[66] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[65]); t = (sp_int_digit)(a[64]); - r[65] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[65] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[64]); t = (sp_int_digit)(a[63]); - r[64] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[64] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[63]); t = (sp_int_digit)(a[62]); - r[63] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[63] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[62]); t = (sp_int_digit)(a[61]); - r[62] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[62] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[61]); t = (sp_int_digit)(a[60]); - r[61] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[61] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[60]); t = (sp_int_digit)(a[59]); - r[60] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[60] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[59]); t = (sp_int_digit)(a[58]); - r[59] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[59] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[58]); t = (sp_int_digit)(a[57]); - r[58] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[58] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[57]); t = (sp_int_digit)(a[56]); - r[57] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[57] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[56]); t = (sp_int_digit)(a[55]); - r[56] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[56] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[55]); t = (sp_int_digit)(a[54]); - r[55] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[55] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[54]); t = (sp_int_digit)(a[53]); - r[54] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[54] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[53]); t = (sp_int_digit)(a[52]); - r[53] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[53] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[52]); t = (sp_int_digit)(a[51]); - r[52] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[52] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[51]); t = (sp_int_digit)(a[50]); - r[51] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[51] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[50]); t = (sp_int_digit)(a[49]); - r[50] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[50] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[49]); t = (sp_int_digit)(a[48]); - r[49] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[49] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[48]); t = (sp_int_digit)(a[47]); - r[48] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[48] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[47]); t = (sp_int_digit)(a[46]); - r[47] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[47] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[46]); t = (sp_int_digit)(a[45]); - r[46] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[46] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[45]); t = (sp_int_digit)(a[44]); - r[45] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[45] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[44]); t = (sp_int_digit)(a[43]); - r[44] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[44] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[43]); t = (sp_int_digit)(a[42]); - r[43] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[43] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[42]); t = (sp_int_digit)(a[41]); - r[42] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[42] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[41]); t = (sp_int_digit)(a[40]); - r[41] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[41] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[40]); t = (sp_int_digit)(a[39]); - r[40] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[40] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[39]); t = (sp_int_digit)(a[38]); - r[39] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[39] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[38]); t = (sp_int_digit)(a[37]); - r[38] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[38] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[37]); t = (sp_int_digit)(a[36]); - r[37] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[37] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[36]); t = (sp_int_digit)(a[35]); - r[36] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[36] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[35]); t = (sp_int_digit)(a[34]); - r[35] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[35] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[34]); t = (sp_int_digit)(a[33]); - r[34] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[34] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[33]); t = (sp_int_digit)(a[32]); - r[33] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[33] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[32]); t = (sp_int_digit)(a[31]); - r[32] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[32] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[31]); t = (sp_int_digit)(a[30]); - r[31] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[31] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[30]); t = (sp_int_digit)(a[29]); - r[30] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[30] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[29]); t = (sp_int_digit)(a[28]); - r[29] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[29] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[28]); t = (sp_int_digit)(a[27]); - r[28] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[28] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[27]); t = (sp_int_digit)(a[26]); - r[27] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[27] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[26]); t = (sp_int_digit)(a[25]); - r[26] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[26] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[25]); t = (sp_int_digit)(a[24]); - r[25] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[25] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[24]); t = (sp_int_digit)(a[23]); - r[24] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[24] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[23]); t = (sp_int_digit)(a[22]); - r[23] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[23] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[22]); t = (sp_int_digit)(a[21]); - r[22] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[22] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[21]); t = (sp_int_digit)(a[20]); - r[21] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[21] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[20]); t = (sp_int_digit)(a[19]); - r[20] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[20] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[19]); t = (sp_int_digit)(a[18]); - r[19] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[19] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[18]); t = (sp_int_digit)(a[17]); - r[18] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[18] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[17] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[16] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[15] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[14] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[13] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[12] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[11] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[10] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL; - r[0] = (a[0] << n) & 0x1fffffffffffffL; + r[1] = (sp_digit)(((s << n) | (t >> (53U - n))) & 0x1fffffffffffffUL); + r[0] = (sp_digit)((a[0] << n) & 0x1fffffffffffffL); } /* Modular exponentiate 2 to the e mod m. (r = 2^e mod m) @@ -21043,12 +20978,11 @@ static int sp_4096_mod_exp_2_78(sp_digit* r, const sp_digit* e, int bits, const sp_4096_mont_reduce_78(r, m, mp); n = sp_4096_cmp_78(r, m); - sp_4096_cond_sub_78(r, r, m, ~(n >> 63)); + sp_4096_cond_sub_78(r, r, m, (sp_digit)~(n >> 63)); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -21315,16 +21249,16 @@ SP_NOINLINE static void sp_256_mul_5(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 4]) * b[ 3]; sp_int128 t8 = ((sp_int128)a[ 4]) * b[ 4]; - t1 += t0 >> 52; r[ 0] = t0 & 0xfffffffffffffL; - t2 += t1 >> 52; r[ 1] = t1 & 0xfffffffffffffL; - t3 += t2 >> 52; r[ 2] = t2 & 0xfffffffffffffL; - t4 += t3 >> 52; r[ 3] = t3 & 0xfffffffffffffL; - t5 += t4 >> 52; r[ 4] = t4 & 0xfffffffffffffL; - t6 += t5 >> 52; r[ 5] = t5 & 0xfffffffffffffL; - t7 += t6 >> 52; r[ 6] = t6 & 0xfffffffffffffL; - t8 += t7 >> 52; r[ 7] = t7 & 0xfffffffffffffL; + t1 += t0 >> 52; r[ 0] = (sp_digit)(t0 & 0xfffffffffffffL); + t2 += t1 >> 52; r[ 1] = (sp_digit)(t1 & 0xfffffffffffffL); + t3 += t2 >> 52; r[ 2] = (sp_digit)(t2 & 0xfffffffffffffL); + t4 += t3 >> 52; r[ 3] = (sp_digit)(t3 & 0xfffffffffffffL); + t5 += t4 >> 52; r[ 4] = (sp_digit)(t4 & 0xfffffffffffffL); + t6 += t5 >> 52; r[ 5] = (sp_digit)(t5 & 0xfffffffffffffL); + t7 += t6 >> 52; r[ 6] = (sp_digit)(t6 & 0xfffffffffffffL); + t8 += t7 >> 52; r[ 7] = (sp_digit)(t7 & 0xfffffffffffffL); r[9] = (sp_digit)(t8 >> 52); - r[8] = t8 & 0xfffffffffffffL; + r[8] = (sp_digit)(t8 & 0xfffffffffffffL); } #endif /* WOLFSSL_SP_SMALL */ @@ -21394,16 +21328,16 @@ SP_NOINLINE static void sp_256_sqr_5(sp_digit* r, const sp_digit* a) sp_int128 t7 = (((sp_int128)a[ 3]) * a[ 4]) * 2; sp_int128 t8 = ((sp_int128)a[ 4]) * a[ 4]; - t1 += t0 >> 52; r[ 0] = t0 & 0xfffffffffffffL; - t2 += t1 >> 52; r[ 1] = t1 & 0xfffffffffffffL; - t3 += t2 >> 52; r[ 2] = t2 & 0xfffffffffffffL; - t4 += t3 >> 52; r[ 3] = t3 & 0xfffffffffffffL; - t5 += t4 >> 52; r[ 4] = t4 & 0xfffffffffffffL; - t6 += t5 >> 52; r[ 5] = t5 & 0xfffffffffffffL; - t7 += t6 >> 52; r[ 6] = t6 & 0xfffffffffffffL; - t8 += t7 >> 52; r[ 7] = t7 & 0xfffffffffffffL; + t1 += t0 >> 52; r[ 0] = (sp_digit)(t0 & 0xfffffffffffffL); + t2 += t1 >> 52; r[ 1] = (sp_digit)(t1 & 0xfffffffffffffL); + t3 += t2 >> 52; r[ 2] = (sp_digit)(t2 & 0xfffffffffffffL); + t4 += t3 >> 52; r[ 3] = (sp_digit)(t3 & 0xfffffffffffffL); + t5 += t4 >> 52; r[ 4] = (sp_digit)(t4 & 0xfffffffffffffL); + t6 += t5 >> 52; r[ 5] = (sp_digit)(t5 & 0xfffffffffffffL); + t7 += t6 >> 52; r[ 6] = (sp_digit)(t6 & 0xfffffffffffffL); + t8 += t7 >> 52; r[ 7] = (sp_digit)(t7 & 0xfffffffffffffL); r[9] = (sp_digit)(t8 >> 52); - r[8] = t8 & 0xfffffffffffffL; + r[8] = (sp_digit)(t8 & 0xfffffffffffffL); } #endif /* WOLFSSL_SP_SMALL */ @@ -21752,17 +21686,17 @@ SP_NOINLINE static void sp_256_mul_add_5(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0xfffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0xfffffffffffffL); t[1] += t[0] >> 52; - r[i+1] = t[1] & 0xfffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0xfffffffffffffL); t[2] += t[1] >> 52; - r[i+2] = t[2] & 0xfffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0xfffffffffffffL); t[3] += t[2] >> 52; - r[i+3] = t[3] & 0xfffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0xfffffffffffffL); t[0] = t[3] >> 52; } t[0] += (tb * a[4]) + r[4]; - r[4] = t[0] & 0xfffffffffffffL; + r[4] = (sp_digit)(t[0] & 0xfffffffffffffL); r[5] += (sp_digit)(t[0] >> 52); #else sp_int128 tb = b; @@ -21816,7 +21750,7 @@ static void sp_256_mont_shift_5(sp_digit* r, const sp_digit* a) n = a[4] >> 48; for (i = 0; i < 4; i++) { n += (sp_uint64)a[5 + i] << 4; - r[i] = n & 0xfffffffffffffL; + r[i] = (sp_digit)(n & 0xfffffffffffffL); n >>= 52; } n += (sp_uint64)a[9] << 4; @@ -21825,10 +21759,10 @@ static void sp_256_mont_shift_5(sp_digit* r, const sp_digit* a) sp_uint64 n; n = a[4] >> 48; - n += (sp_uint64)a[ 5] << 4U; r[ 0] = n & 0xfffffffffffffUL; n >>= 52U; - n += (sp_uint64)a[ 6] << 4U; r[ 1] = n & 0xfffffffffffffUL; n >>= 52U; - n += (sp_uint64)a[ 7] << 4U; r[ 2] = n & 0xfffffffffffffUL; n >>= 52U; - n += (sp_uint64)a[ 8] << 4U; r[ 3] = n & 0xfffffffffffffUL; n >>= 52U; + n += (sp_uint64)a[ 5] << 4U; r[ 0] = (sp_digit)(n & 0xfffffffffffffUL); n >>= 52U; + n += (sp_uint64)a[ 6] << 4U; r[ 1] = (sp_digit)(n & 0xfffffffffffffUL); n >>= 52U; + n += (sp_uint64)a[ 7] << 4U; r[ 2] = (sp_digit)(n & 0xfffffffffffffUL); n >>= 52U; + n += (sp_uint64)a[ 8] << 4U; r[ 3] = (sp_digit)(n & 0xfffffffffffffUL); n >>= 52U; n += (sp_uint64)a[ 9] << 4U; r[ 4] = n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[5], 0, sizeof(*r) * 5U); @@ -21849,11 +21783,11 @@ static void sp_256_mont_reduce_order_5(sp_digit* a, const sp_digit* m, sp_digit sp_256_norm_5(a + 5); for (i=0; i<4; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xfffffffffffffL); sp_256_mul_add_5(a+i, m, mu); a[i+1] += a[i] >> 52; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0xffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0xffffffffffffL); sp_256_mul_add_5(a+i, m, mu); a[i+1] += a[i] >> 52; a[i] &= 0xfffffffffffffL; @@ -21879,32 +21813,32 @@ static void sp_256_mont_reduce_5(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 4; i++) { - am = a[i] & 0xfffffffffffffL; + am = (sp_digit)(a[i] & 0xfffffffffffffL); /* Fifth word of modulus word */ t = am; t *= 0x0ffffffff0000L; - a[i + 1] += (am << 44) & 0xfffffffffffffL; + a[i + 1] += (sp_digit)((am << 44) & 0xfffffffffffffL); a[i + 2] += am >> 8; - a[i + 3] += (am << 36) & 0xfffffffffffffL; - a[i + 4] += (am >> 16) + (t & 0xfffffffffffffL); + a[i + 3] += (sp_digit)((am << 36) & 0xfffffffffffffL); + a[i + 4] += (am >> 16) + (sp_digit)(t & 0xfffffffffffffL); a[i + 5] += t >> 52; a[i + 1] += a[i] >> 52; } - am = a[4] & 0xffffffffffff; + am = (sp_digit)(a[4] & 0xffffffffffff); /* Fifth word of modulus word */ t = am; t *= 0x0ffffffff0000L; - a[4 + 1] += (am << 44) & 0xfffffffffffffL; + a[4 + 1] += (sp_digit)((am << 44) & 0xfffffffffffffL); a[4 + 2] += am >> 8; - a[4 + 3] += (am << 36) & 0xfffffffffffffL; - a[4 + 4] += (am >> 16) + (t & 0xfffffffffffffL); + a[4 + 3] += (sp_digit)((am << 36) & 0xfffffffffffffL); + a[4 + 4] += (am >> 16) + (sp_digit)(t & 0xfffffffffffffL); a[4 + 5] += t >> 52; - a[0] = (a[4] >> 48) + ((a[5] << 4) & 0xfffffffffffffL); - a[1] = (a[5] >> 48) + ((a[6] << 4) & 0xfffffffffffffL); - a[2] = (a[6] >> 48) + ((a[7] << 4) & 0xfffffffffffffL); - a[3] = (a[7] >> 48) + ((a[8] << 4) & 0xfffffffffffffL); + a[0] = (a[4] >> 48) + (sp_digit)((a[5] << 4) & 0xfffffffffffffL); + a[1] = (a[5] >> 48) + (sp_digit)((a[6] << 4) & 0xfffffffffffffL); + a[2] = (a[6] >> 48) + (sp_digit)((a[7] << 4) & 0xfffffffffffffL); + a[3] = (a[7] >> 48) + (sp_digit)((a[8] << 4) & 0xfffffffffffffL); a[4] = (a[8] >> 48) + (a[9] << 4); a[1] += a[0] >> 52; a[0] &= 0xfffffffffffffL; @@ -21917,11 +21851,11 @@ static void sp_256_mont_reduce_5(sp_digit* a, const sp_digit* m, sp_digit mp) /* Create mask. */ am = 0 - am; - a[0] -= 0x000fffffffffffffL & am; - a[1] -= 0x00000fffffffffffL & am; + a[0] -= (sp_digit)(0x000fffffffffffffL & am); + a[1] -= (sp_digit)(0x00000fffffffffffL & am); /* p256_mod[2] is zero */ - a[3] -= 0x0000001000000000L & am; - a[4] -= 0x0000ffffffff0000L & am; + a[3] -= (sp_digit)(0x0000001000000000L & am); + a[4] -= (sp_digit)(0x0000ffffffff0000L & am); a[1] += a[0] >> 52; a[0] &= 0xfffffffffffffL; a[2] += a[1] >> 52; a[1] &= 0xfffffffffffffL; @@ -22079,7 +22013,7 @@ static void sp_256_map_5(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_5(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_5(r->x, p256_mod); - sp_256_cond_sub_5(r->x, r->x, p256_mod, ~(n >> 51)); + sp_256_cond_sub_5(r->x, r->x, p256_mod, (sp_digit)~(n >> 51)); sp_256_norm_5(r->x); /* y /= z^3 */ @@ -22088,7 +22022,7 @@ static void sp_256_map_5(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_5(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_5(r->y, p256_mod); - sp_256_cond_sub_5(r->y, r->y, p256_mod, ~(n >> 51)); + sp_256_cond_sub_5(r->y, r->y, p256_mod, (sp_digit)~(n >> 51)); sp_256_norm_5(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -22218,13 +22152,13 @@ SP_NOINLINE static void sp_256_rshift1_5(sp_digit* r, const sp_digit* a) int i; for (i=0; i<4; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 51) & 0xfffffffffffffL); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 51) & 0xfffffffffffffL); } #else - r[0] = (a[0] >> 1) + ((a[1] << 51) & 0xfffffffffffffL); - r[1] = (a[1] >> 1) + ((a[2] << 51) & 0xfffffffffffffL); - r[2] = (a[2] >> 1) + ((a[3] << 51) & 0xfffffffffffffL); - r[3] = (a[3] >> 1) + ((a[4] << 51) & 0xfffffffffffffL); + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 51) & 0xfffffffffffffL); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 51) & 0xfffffffffffffL); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 51) & 0xfffffffffffffL); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 51) & 0xfffffffffffffL); #endif r[4] = a[4] >> 1; } @@ -22533,8 +22467,8 @@ static void sp_256_proj_point_add_5(sp_point_256* r, sp_256_mont_sub_5(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -22551,7 +22485,7 @@ static void sp_256_proj_point_add_5(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -22725,8 +22659,8 @@ static int sp_256_proj_point_add_5_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -22743,7 +22677,7 @@ static int sp_256_proj_point_add_5_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -22862,8 +22796,7 @@ static int sp_256_mod_mul_norm_5(sp_digit* r, const sp_digit* a, const sp_digit* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -23430,7 +23363,7 @@ static void sp_256_ecc_recode_6_5(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 52) { y &= 0x3f; n >>= 6; @@ -23485,7 +23418,7 @@ static void sp_256_get_point_33_5(sp_point_256* r, const sp_point_256* table, r->z[3] = 0; r->z[4] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -23640,10 +23573,8 @@ static int sp_256_ecc_mulmod_win_add_sub_5(sp_point_256* r, const sp_point_256* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -23709,8 +23640,8 @@ static void sp_256_proj_point_add_qz1_5(sp_point_256* r, sp_256_mont_sub_5(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -23727,7 +23658,7 @@ static void sp_256_proj_point_add_qz1_5(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -23838,8 +23769,7 @@ static int sp_256_gen_stripe_table_5(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -23870,7 +23800,7 @@ static void sp_256_get_entry_256_5(sp_point_256* r, r->y[3] = 0; r->y[4] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -23991,10 +23921,8 @@ static int sp_256_ecc_mulmod_stripe_5(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24212,10 +24140,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24292,10 +24218,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25681,10 +25605,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25759,10 +25681,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -25826,6 +25746,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_5(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -25842,6 +25763,11 @@ static int sp_256_ecc_gen_k_5(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -25920,12 +25846,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26108,10 +26031,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26178,23 +26099,23 @@ SP_NOINLINE static void sp_256_rshift_5(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<4; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (52 - n))) & 0xfffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (52 - n))) & 0xfffffffffffffL); } #else for (i=0; i<0; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (52 - n)) & 0xfffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (52 - n)) & 0xfffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (52 - n)) & 0xfffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (52 - n)) & 0xfffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (52 - n)) & 0xfffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (52 - n)) & 0xfffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (52 - n)) & 0xfffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (52 - n)) & 0xfffffffffffffL); - } - r[0] = (a[0] >> n) | ((a[1] << (52 - n)) & 0xfffffffffffffL); - r[1] = (a[1] >> n) | ((a[2] << (52 - n)) & 0xfffffffffffffL); - r[2] = (a[2] >> n) | ((a[3] << (52 - n)) & 0xfffffffffffffL); - r[3] = (a[3] >> n) | ((a[4] << (52 - n)) & 0xfffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (52 - n)) & 0xfffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (52 - n)) & 0xfffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (52 - n)) & 0xfffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (52 - n)) & 0xfffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (52 - n)) & 0xfffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (52 - n)) & 0xfffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (52 - n)) & 0xfffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (52 - n)) & 0xfffffffffffffL); + } + r[0] = (a[0] >> n) | (sp_digit)((a[1] << (52 - n)) & 0xfffffffffffffL); + r[1] = (a[1] >> n) | (sp_digit)((a[2] << (52 - n)) & 0xfffffffffffffL); + r[2] = (a[2] >> n) | (sp_digit)((a[3] << (52 - n)) & 0xfffffffffffffL); + r[3] = (a[3] >> n) | (sp_digit)((a[4] << (52 - n)) & 0xfffffffffffffL); #endif /* WOLFSSL_SP_SMALL */ r[4] = a[4] >> n; } @@ -26245,7 +26166,7 @@ SP_NOINLINE static void sp_256_lshift_10(sp_digit* r, const sp_digit* a, r[10] = a[9] >> (52 - n); for (i=9; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (52 - n))) & 0xfffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (52 - n))) & 0xfffffffffffffL); } #else sp_int_digit s; @@ -26254,25 +26175,25 @@ SP_NOINLINE static void sp_256_lshift_10(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[9]; r[10] = s >> (52U - n); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL; + r[1] = (sp_digit)(((s << n) | (t >> (52U - n))) & 0xfffffffffffffUL); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0xfffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0xfffffffffffffL); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -26342,8 +26263,7 @@ static int sp_256_div_5(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -27073,8 +26993,7 @@ static int sp_256_mod_inv_5(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 5); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27278,10 +27197,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -27488,8 +27405,7 @@ static int sp_256_ecc_is_point_5(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -27528,8 +27444,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27637,10 +27552,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -27719,10 +27632,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27787,10 +27698,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27851,10 +27760,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27920,8 +27827,7 @@ static int sp_256_mont_sqrt_5(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27986,8 +27892,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -28177,20 +28082,20 @@ SP_NOINLINE static void sp_384_mul_7(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 5]; sp_int128 t12 = ((sp_int128)a[ 6]) * b[ 6]; - t1 += t0 >> 55; r[ 0] = t0 & 0x7fffffffffffffL; - t2 += t1 >> 55; r[ 1] = t1 & 0x7fffffffffffffL; - t3 += t2 >> 55; r[ 2] = t2 & 0x7fffffffffffffL; - t4 += t3 >> 55; r[ 3] = t3 & 0x7fffffffffffffL; - t5 += t4 >> 55; r[ 4] = t4 & 0x7fffffffffffffL; - t6 += t5 >> 55; r[ 5] = t5 & 0x7fffffffffffffL; - t7 += t6 >> 55; r[ 6] = t6 & 0x7fffffffffffffL; - t8 += t7 >> 55; r[ 7] = t7 & 0x7fffffffffffffL; - t9 += t8 >> 55; r[ 8] = t8 & 0x7fffffffffffffL; - t10 += t9 >> 55; r[ 9] = t9 & 0x7fffffffffffffL; - t11 += t10 >> 55; r[10] = t10 & 0x7fffffffffffffL; - t12 += t11 >> 55; r[11] = t11 & 0x7fffffffffffffL; + t1 += t0 >> 55; r[ 0] = (sp_digit)(t0 & 0x7fffffffffffffL); + t2 += t1 >> 55; r[ 1] = (sp_digit)(t1 & 0x7fffffffffffffL); + t3 += t2 >> 55; r[ 2] = (sp_digit)(t2 & 0x7fffffffffffffL); + t4 += t3 >> 55; r[ 3] = (sp_digit)(t3 & 0x7fffffffffffffL); + t5 += t4 >> 55; r[ 4] = (sp_digit)(t4 & 0x7fffffffffffffL); + t6 += t5 >> 55; r[ 5] = (sp_digit)(t5 & 0x7fffffffffffffL); + t7 += t6 >> 55; r[ 6] = (sp_digit)(t6 & 0x7fffffffffffffL); + t8 += t7 >> 55; r[ 7] = (sp_digit)(t7 & 0x7fffffffffffffL); + t9 += t8 >> 55; r[ 8] = (sp_digit)(t8 & 0x7fffffffffffffL); + t10 += t9 >> 55; r[ 9] = (sp_digit)(t9 & 0x7fffffffffffffL); + t11 += t10 >> 55; r[10] = (sp_digit)(t10 & 0x7fffffffffffffL); + t12 += t11 >> 55; r[11] = (sp_digit)(t11 & 0x7fffffffffffffL); r[13] = (sp_digit)(t12 >> 55); - r[12] = t12 & 0x7fffffffffffffL; + r[12] = (sp_digit)(t12 & 0x7fffffffffffffL); } #endif /* WOLFSSL_SP_SMALL */ @@ -28273,20 +28178,20 @@ SP_NOINLINE static void sp_384_sqr_7(sp_digit* r, const sp_digit* a) sp_int128 t11 = (((sp_int128)a[ 5]) * a[ 6]) * 2; sp_int128 t12 = ((sp_int128)a[ 6]) * a[ 6]; - t1 += t0 >> 55; r[ 0] = t0 & 0x7fffffffffffffL; - t2 += t1 >> 55; r[ 1] = t1 & 0x7fffffffffffffL; - t3 += t2 >> 55; r[ 2] = t2 & 0x7fffffffffffffL; - t4 += t3 >> 55; r[ 3] = t3 & 0x7fffffffffffffL; - t5 += t4 >> 55; r[ 4] = t4 & 0x7fffffffffffffL; - t6 += t5 >> 55; r[ 5] = t5 & 0x7fffffffffffffL; - t7 += t6 >> 55; r[ 6] = t6 & 0x7fffffffffffffL; - t8 += t7 >> 55; r[ 7] = t7 & 0x7fffffffffffffL; - t9 += t8 >> 55; r[ 8] = t8 & 0x7fffffffffffffL; - t10 += t9 >> 55; r[ 9] = t9 & 0x7fffffffffffffL; - t11 += t10 >> 55; r[10] = t10 & 0x7fffffffffffffL; - t12 += t11 >> 55; r[11] = t11 & 0x7fffffffffffffL; + t1 += t0 >> 55; r[ 0] = (sp_digit)(t0 & 0x7fffffffffffffL); + t2 += t1 >> 55; r[ 1] = (sp_digit)(t1 & 0x7fffffffffffffL); + t3 += t2 >> 55; r[ 2] = (sp_digit)(t2 & 0x7fffffffffffffL); + t4 += t3 >> 55; r[ 3] = (sp_digit)(t3 & 0x7fffffffffffffL); + t5 += t4 >> 55; r[ 4] = (sp_digit)(t4 & 0x7fffffffffffffL); + t6 += t5 >> 55; r[ 5] = (sp_digit)(t5 & 0x7fffffffffffffL); + t7 += t6 >> 55; r[ 6] = (sp_digit)(t6 & 0x7fffffffffffffL); + t8 += t7 >> 55; r[ 7] = (sp_digit)(t7 & 0x7fffffffffffffL); + t9 += t8 >> 55; r[ 8] = (sp_digit)(t8 & 0x7fffffffffffffL); + t10 += t9 >> 55; r[ 9] = (sp_digit)(t9 & 0x7fffffffffffffL); + t11 += t10 >> 55; r[10] = (sp_digit)(t10 & 0x7fffffffffffffL); + t12 += t11 >> 55; r[11] = (sp_digit)(t11 & 0x7fffffffffffffL); r[13] = (sp_digit)(t12 >> 55); - r[12] = t12 & 0x7fffffffffffffL; + r[12] = (sp_digit)(t12 & 0x7fffffffffffffL); } #endif /* WOLFSSL_SP_SMALL */ @@ -28643,23 +28548,23 @@ SP_NOINLINE static void sp_384_mul_add_7(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x7fffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x7fffffffffffffL); t[1] += t[0] >> 55; - r[i+1] = t[1] & 0x7fffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x7fffffffffffffL); t[2] += t[1] >> 55; - r[i+2] = t[2] & 0x7fffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x7fffffffffffffL); t[3] += t[2] >> 55; - r[i+3] = t[3] & 0x7fffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x7fffffffffffffL); t[0] = t[3] >> 55; } t[0] += (tb * a[4]) + r[4]; t[1] = (tb * a[5]) + r[5]; t[2] = (tb * a[6]) + r[6]; - r[4] = t[0] & 0x7fffffffffffffL; + r[4] = (sp_digit)(t[0] & 0x7fffffffffffffL); t[1] += t[0] >> 55; - r[5] = t[1] & 0x7fffffffffffffL; + r[5] = (sp_digit)(t[1] & 0x7fffffffffffffL); t[2] += t[1] >> 55; - r[6] = t[2] & 0x7fffffffffffffL; + r[6] = (sp_digit)(t[2] & 0x7fffffffffffffL); r[7] += (sp_digit)(t[2] >> 55); #else sp_int128 tb = b; @@ -28719,7 +28624,7 @@ static void sp_384_mont_shift_7(sp_digit* r, const sp_digit* a) n = a[6] >> 54; for (i = 0; i < 6; i++) { n += (sp_uint64)a[7 + i] << 1; - r[i] = n & 0x7fffffffffffffL; + r[i] = (sp_digit)(n & 0x7fffffffffffffL); n >>= 55; } n += (sp_uint64)a[13] << 1; @@ -28728,12 +28633,12 @@ static void sp_384_mont_shift_7(sp_digit* r, const sp_digit* a) sp_uint64 n; n = a[6] >> 54; - n += (sp_uint64)a[ 7] << 1U; r[ 0] = n & 0x7fffffffffffffUL; n >>= 55U; - n += (sp_uint64)a[ 8] << 1U; r[ 1] = n & 0x7fffffffffffffUL; n >>= 55U; - n += (sp_uint64)a[ 9] << 1U; r[ 2] = n & 0x7fffffffffffffUL; n >>= 55U; - n += (sp_uint64)a[10] << 1U; r[ 3] = n & 0x7fffffffffffffUL; n >>= 55U; - n += (sp_uint64)a[11] << 1U; r[ 4] = n & 0x7fffffffffffffUL; n >>= 55U; - n += (sp_uint64)a[12] << 1U; r[ 5] = n & 0x7fffffffffffffUL; n >>= 55U; + n += (sp_uint64)a[ 7] << 1U; r[ 0] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; + n += (sp_uint64)a[ 8] << 1U; r[ 1] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; + n += (sp_uint64)a[ 9] << 1U; r[ 2] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; + n += (sp_uint64)a[10] << 1U; r[ 3] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; + n += (sp_uint64)a[11] << 1U; r[ 4] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; + n += (sp_uint64)a[12] << 1U; r[ 5] = (sp_digit)(n & 0x7fffffffffffffUL); n >>= 55U; n += (sp_uint64)a[13] << 1U; r[ 6] = n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[7], 0, sizeof(*r) * 7U); @@ -28754,11 +28659,11 @@ static void sp_384_mont_reduce_order_7(sp_digit* a, const sp_digit* m, sp_digit sp_384_norm_7(a + 7); for (i=0; i<6; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x7fffffffffffffL); sp_384_mul_add_7(a+i, m, mu); a[i+1] += a[i] >> 55; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x3fffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x3fffffffffffffL); sp_384_mul_add_7(a+i, m, mu); a[i+1] += a[i] >> 55; a[i] &= 0x7fffffffffffffL; @@ -28783,30 +28688,30 @@ static void sp_384_mont_reduce_7(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 6; i++) { - am = (a[i] * 0x100000001) & 0x7fffffffffffffL; - a[i + 0] += (am << 32) & 0x7fffffffffffffL; - a[i + 1] += (am >> 23) - ((am << 41) & 0x7fffffffffffffL); - a[i + 2] += -(am >> 14) - ((am << 18) & 0x7fffffffffffffL); + am = (sp_digit)((a[i] * 0x100000001) & 0x7fffffffffffffL); + a[i + 0] += (sp_digit)((am << 32) & 0x7fffffffffffffL); + a[i + 1] += (am >> 23) - (sp_digit)((am << 41) & 0x7fffffffffffffL); + a[i + 2] += -(am >> 14) - ((sp_digit)(am << 18) & 0x7fffffffffffffL); a[i + 3] += -(am >> 37); - a[i + 6] += (am << 54) & 0x7fffffffffffffL; + a[i + 6] += ((sp_digit)(am << 54) & 0x7fffffffffffffL); a[i + 7] += am >> 1; a[i + 1] += a[i] >> 55; } - am = (a[6] * 0x100000001) & 0x3fffffffffffff; - a[6 + 0] += (am << 32) & 0x7fffffffffffffL; - a[6 + 1] += (am >> 23) - ((am << 41) & 0x7fffffffffffffL); - a[6 + 2] += -(am >> 14) - ((am << 18) & 0x7fffffffffffffL); + am = (sp_digit)((a[6] * 0x100000001) & 0x3fffffffffffff); + a[6 + 0] += (sp_digit)((am << 32) & 0x7fffffffffffffL); + a[6 + 1] += (am >> 23) - (sp_digit)((am << 41) & 0x7fffffffffffffL); + a[6 + 2] += -(am >> 14) - (sp_digit)((am << 18) & 0x7fffffffffffffL); a[6 + 3] += -(am >> 37); - a[6 + 6] += (am << 54) & 0x7fffffffffffffL; + a[6 + 6] += (sp_digit)((am << 54) & 0x7fffffffffffffL); a[6 + 7] += am >> 1; - a[0] = (a[6] >> 54) + ((a[7] << 1) & 0x7fffffffffffffL); - a[1] = (a[7] >> 54) + ((a[8] << 1) & 0x7fffffffffffffL); - a[2] = (a[8] >> 54) + ((a[9] << 1) & 0x7fffffffffffffL); - a[3] = (a[9] >> 54) + ((a[10] << 1) & 0x7fffffffffffffL); - a[4] = (a[10] >> 54) + ((a[11] << 1) & 0x7fffffffffffffL); - a[5] = (a[11] >> 54) + ((a[12] << 1) & 0x7fffffffffffffL); + a[0] = (a[6] >> 54) + (sp_digit)((a[7] << 1) & 0x7fffffffffffffL); + a[1] = (a[7] >> 54) + (sp_digit)((a[8] << 1) & 0x7fffffffffffffL); + a[2] = (a[8] >> 54) + (sp_digit)((a[9] << 1) & 0x7fffffffffffffL); + a[3] = (a[9] >> 54) + (sp_digit)((a[10] << 1) & 0x7fffffffffffffL); + a[4] = (a[10] >> 54) + (sp_digit)((a[11] << 1) & 0x7fffffffffffffL); + a[5] = (a[11] >> 54) + (sp_digit)((a[12] << 1) & 0x7fffffffffffffL); a[6] = (a[12] >> 54) + (a[13] << 1); a[1] += a[0] >> 55; a[0] &= 0x7fffffffffffffL; @@ -28821,13 +28726,13 @@ static void sp_384_mont_reduce_7(sp_digit* a, const sp_digit* m, sp_digit mp) /* Create mask. */ am = 0 - am; - a[0] -= 0x00000000ffffffffL & am; - a[1] -= 0x007ffe0000000000L & am; - a[2] -= 0x007ffffffffbffffL & am; - a[3] -= 0x007fffffffffffffL & am; - a[4] -= 0x007fffffffffffffL & am; - a[5] -= 0x007fffffffffffffL & am; - a[6] -= 0x003fffffffffffffL & am; + a[0] -= (sp_digit)(0x00000000ffffffffL & am); + a[1] -= (sp_digit)(0x007ffe0000000000L & am); + a[2] -= (sp_digit)(0x007ffffffffbffffL & am); + a[3] -= (sp_digit)(0x007fffffffffffffL & am); + a[4] -= (sp_digit)(0x007fffffffffffffL & am); + a[5] -= (sp_digit)(0x007fffffffffffffL & am); + a[6] -= (sp_digit)(0x003fffffffffffffL & am); a[1] += a[0] >> 55; a[0] &= 0x7fffffffffffffL; a[2] += a[1] >> 55; a[1] &= 0x7fffffffffffffL; @@ -29003,7 +28908,7 @@ static void sp_384_map_7(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_7(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_7(r->x, p384_mod); - sp_384_cond_sub_7(r->x, r->x, p384_mod, ~(n >> 54)); + sp_384_cond_sub_7(r->x, r->x, p384_mod, (sp_digit)~(n >> 54)); sp_384_norm_7(r->x); /* y /= z^3 */ @@ -29012,7 +28917,7 @@ static void sp_384_map_7(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_7(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_7(r->y, p384_mod); - sp_384_cond_sub_7(r->y, r->y, p384_mod, ~(n >> 54)); + sp_384_cond_sub_7(r->y, r->y, p384_mod, (sp_digit)~(n >> 54)); sp_384_norm_7(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -29144,15 +29049,15 @@ SP_NOINLINE static void sp_384_rshift1_7(sp_digit* r, const sp_digit* a) int i; for (i=0; i<6; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 54) & 0x7fffffffffffffL); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 54) & 0x7fffffffffffffL); } #else - r[0] = (a[0] >> 1) + ((a[1] << 54) & 0x7fffffffffffffL); - r[1] = (a[1] >> 1) + ((a[2] << 54) & 0x7fffffffffffffL); - r[2] = (a[2] >> 1) + ((a[3] << 54) & 0x7fffffffffffffL); - r[3] = (a[3] >> 1) + ((a[4] << 54) & 0x7fffffffffffffL); - r[4] = (a[4] >> 1) + ((a[5] << 54) & 0x7fffffffffffffL); - r[5] = (a[5] >> 1) + ((a[6] << 54) & 0x7fffffffffffffL); + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 54) & 0x7fffffffffffffL); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 54) & 0x7fffffffffffffL); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 54) & 0x7fffffffffffffL); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 54) & 0x7fffffffffffffL); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 54) & 0x7fffffffffffffL); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 54) & 0x7fffffffffffffL); #endif r[6] = a[6] >> 1; } @@ -29462,8 +29367,8 @@ static void sp_384_proj_point_add_7(sp_point_384* r, sp_384_mont_sub_7(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29480,7 +29385,7 @@ static void sp_384_proj_point_add_7(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -29654,8 +29559,8 @@ static int sp_384_proj_point_add_7_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29672,7 +29577,7 @@ static int sp_384_proj_point_add_7_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -29823,8 +29728,7 @@ static int sp_384_mod_mul_norm_7(sp_digit* r, const sp_digit* a, const sp_digit* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -30395,7 +30299,7 @@ static void sp_384_ecc_recode_6_7(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 55) { y &= 0x3f; n >>= 6; @@ -30456,7 +30360,7 @@ static void sp_384_get_point_33_7(sp_point_384* r, const sp_point_384* table, r->z[5] = 0; r->z[6] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -30617,10 +30521,8 @@ static int sp_384_ecc_mulmod_win_add_sub_7(sp_point_384* r, const sp_point_384* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30686,8 +30588,8 @@ static void sp_384_proj_point_add_qz1_7(sp_point_384* r, sp_384_mont_sub_7(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -30704,7 +30606,7 @@ static void sp_384_proj_point_add_qz1_7(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -30815,8 +30717,7 @@ static int sp_384_gen_stripe_table_7(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30851,7 +30752,7 @@ static void sp_384_get_entry_256_7(sp_point_384* r, r->y[5] = 0; r->y[6] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -30976,10 +30877,8 @@ static int sp_384_ecc_mulmod_stripe_7(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -31197,10 +31096,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -31277,10 +31174,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33176,10 +33071,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33254,10 +33147,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33321,6 +33212,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_7(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -33337,6 +33229,11 @@ static int sp_384_ecc_gen_k_7(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -33415,12 +33312,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33603,10 +33497,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -33673,25 +33565,25 @@ SP_NOINLINE static void sp_384_rshift_7(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<6; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (55 - n))) & 0x7fffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (55 - n))) & 0x7fffffffffffffL); } #else for (i=0; i<0; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (55 - n)) & 0x7fffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (55 - n)) & 0x7fffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (55 - n)) & 0x7fffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (55 - n)) & 0x7fffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (55 - n)) & 0x7fffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (55 - n)) & 0x7fffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (55 - n)) & 0x7fffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (55 - n)) & 0x7fffffffffffffL); - } - r[0] = (a[0] >> n) | ((a[1] << (55 - n)) & 0x7fffffffffffffL); - r[1] = (a[1] >> n) | ((a[2] << (55 - n)) & 0x7fffffffffffffL); - r[2] = (a[2] >> n) | ((a[3] << (55 - n)) & 0x7fffffffffffffL); - r[3] = (a[3] >> n) | ((a[4] << (55 - n)) & 0x7fffffffffffffL); - r[4] = (a[4] >> n) | ((a[5] << (55 - n)) & 0x7fffffffffffffL); - r[5] = (a[5] >> n) | ((a[6] << (55 - n)) & 0x7fffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (55 - n)) & 0x7fffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (55 - n)) & 0x7fffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (55 - n)) & 0x7fffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (55 - n)) & 0x7fffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (55 - n)) & 0x7fffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (55 - n)) & 0x7fffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (55 - n)) & 0x7fffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (55 - n)) & 0x7fffffffffffffL); + } + r[0] = (a[0] >> n) | (sp_digit)((a[1] << (55 - n)) & 0x7fffffffffffffL); + r[1] = (a[1] >> n) | (sp_digit)((a[2] << (55 - n)) & 0x7fffffffffffffL); + r[2] = (a[2] >> n) | (sp_digit)((a[3] << (55 - n)) & 0x7fffffffffffffL); + r[3] = (a[3] >> n) | (sp_digit)((a[4] << (55 - n)) & 0x7fffffffffffffL); + r[4] = (a[4] >> n) | (sp_digit)((a[5] << (55 - n)) & 0x7fffffffffffffL); + r[5] = (a[5] >> n) | (sp_digit)((a[6] << (55 - n)) & 0x7fffffffffffffL); #endif /* WOLFSSL_SP_SMALL */ r[6] = a[6] >> n; } @@ -33746,7 +33638,7 @@ SP_NOINLINE static void sp_384_lshift_14(sp_digit* r, const sp_digit* a, r[14] = a[13] >> (55 - n); for (i=13; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (55 - n))) & 0x7fffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (55 - n))) & 0x7fffffffffffffL); } #else sp_int_digit s; @@ -33755,33 +33647,33 @@ SP_NOINLINE static void sp_384_lshift_14(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[13]; r[14] = s >> (55U - n); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[13] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[12] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[11] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[10] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL; + r[1] = (sp_digit)(((s << n) | (t >> (55U - n))) & 0x7fffffffffffffUL); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x7fffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0x7fffffffffffffL); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -33845,8 +33737,7 @@ static int sp_384_div_7(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -34543,8 +34434,7 @@ static int sp_384_mod_inv_7(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 7); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -34750,10 +34640,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -34960,8 +34848,7 @@ static int sp_384_ecc_is_point_7(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -35000,8 +34887,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35109,10 +34995,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -35191,10 +35075,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35259,10 +35141,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35323,10 +35203,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35422,8 +35300,7 @@ static int sp_384_mont_sqrt_7(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35488,8 +35365,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -35645,29 +35521,29 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_int128)a[ 0]) * b[ 0]; t1 = ((sp_int128)a[ 0]) * b[ 1] + ((sp_int128)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 0] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 0]) * b[ 2] + ((sp_int128)a[ 1]) * b[ 1] + ((sp_int128)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 1] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 0]) * b[ 3] + ((sp_int128)a[ 1]) * b[ 2] + ((sp_int128)a[ 2]) * b[ 1] + ((sp_int128)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 2] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 0]) * b[ 4] + ((sp_int128)a[ 1]) * b[ 3] + ((sp_int128)a[ 2]) * b[ 2] + ((sp_int128)a[ 3]) * b[ 1] + ((sp_int128)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 3] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 0]) * b[ 5] + ((sp_int128)a[ 1]) * b[ 4] + ((sp_int128)a[ 2]) * b[ 3] + ((sp_int128)a[ 3]) * b[ 2] + ((sp_int128)a[ 4]) * b[ 1] + ((sp_int128)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 4] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 0]) * b[ 6] + ((sp_int128)a[ 1]) * b[ 5] + ((sp_int128)a[ 2]) * b[ 4] @@ -35675,7 +35551,7 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 4]) * b[ 2] + ((sp_int128)a[ 5]) * b[ 1] + ((sp_int128)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 5] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 0]) * b[ 7] + ((sp_int128)a[ 1]) * b[ 6] + ((sp_int128)a[ 2]) * b[ 5] @@ -35684,7 +35560,7 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 5]) * b[ 2] + ((sp_int128)a[ 6]) * b[ 1] + ((sp_int128)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 6] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 0]) * b[ 8] + ((sp_int128)a[ 1]) * b[ 7] + ((sp_int128)a[ 2]) * b[ 6] @@ -35694,7 +35570,7 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 2] + ((sp_int128)a[ 7]) * b[ 1] + ((sp_int128)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 7] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 1]) * b[ 8] + ((sp_int128)a[ 2]) * b[ 7] + ((sp_int128)a[ 3]) * b[ 6] @@ -35703,7 +35579,7 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 3] + ((sp_int128)a[ 7]) * b[ 2] + ((sp_int128)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 8] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 2]) * b[ 8] + ((sp_int128)a[ 3]) * b[ 7] + ((sp_int128)a[ 4]) * b[ 6] @@ -35711,35 +35587,35 @@ SP_NOINLINE static void sp_521_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 4] + ((sp_int128)a[ 7]) * b[ 3] + ((sp_int128)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[ 9] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 3]) * b[ 8] + ((sp_int128)a[ 4]) * b[ 7] + ((sp_int128)a[ 5]) * b[ 6] + ((sp_int128)a[ 6]) * b[ 5] + ((sp_int128)a[ 7]) * b[ 4] + ((sp_int128)a[ 8]) * b[ 3]; - r[10] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[10] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 4]) * b[ 8] + ((sp_int128)a[ 5]) * b[ 7] + ((sp_int128)a[ 6]) * b[ 6] + ((sp_int128)a[ 7]) * b[ 5] + ((sp_int128)a[ 8]) * b[ 4]; - r[11] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[11] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 5]) * b[ 8] + ((sp_int128)a[ 6]) * b[ 7] + ((sp_int128)a[ 7]) * b[ 6] + ((sp_int128)a[ 8]) * b[ 5]; - r[12] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[12] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 6]) * b[ 8] + ((sp_int128)a[ 7]) * b[ 7] + ((sp_int128)a[ 8]) * b[ 6]; - r[13] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[13] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = ((sp_int128)a[ 7]) * b[ 8] + ((sp_int128)a[ 8]) * b[ 7]; - r[14] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[14] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 8]) * b[ 8]; - r[15] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; - r[16] = t0 & 0x3ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; + r[16] = (sp_digit)(t0 & 0x3ffffffffffffffL); r[17] = (sp_digit)(t0 >> 58); XMEMCPY(r, t, sizeof(t)); } @@ -35801,66 +35677,66 @@ SP_NOINLINE static void sp_521_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_int128)a[ 0]) * a[ 0]; t1 = (((sp_int128)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 0] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 0]) * a[ 2]) * 2 + ((sp_int128)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 1] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 0]) * a[ 3] + ((sp_int128)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 2] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 0]) * a[ 4] + ((sp_int128)a[ 1]) * a[ 3]) * 2 + ((sp_int128)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 3] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 0]) * a[ 5] + ((sp_int128)a[ 1]) * a[ 4] + ((sp_int128)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 4] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 0]) * a[ 6] + ((sp_int128)a[ 1]) * a[ 5] + ((sp_int128)a[ 2]) * a[ 4]) * 2 + ((sp_int128)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 5] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 0]) * a[ 7] + ((sp_int128)a[ 1]) * a[ 6] + ((sp_int128)a[ 2]) * a[ 5] + ((sp_int128)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 6] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 0]) * a[ 8] + ((sp_int128)a[ 1]) * a[ 7] + ((sp_int128)a[ 2]) * a[ 6] + ((sp_int128)a[ 3]) * a[ 5]) * 2 + ((sp_int128)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + t[ 7] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 1]) * a[ 8] + ((sp_int128)a[ 2]) * a[ 7] + ((sp_int128)a[ 3]) * a[ 6] + ((sp_int128)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + t[ 8] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 2]) * a[ 8] + ((sp_int128)a[ 3]) * a[ 7] + ((sp_int128)a[ 4]) * a[ 6]) * 2 + ((sp_int128)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[ 9] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 3]) * a[ 8] + ((sp_int128)a[ 4]) * a[ 7] + ((sp_int128)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[10] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 4]) * a[ 8] + ((sp_int128)a[ 5]) * a[ 7]) * 2 + ((sp_int128)a[ 6]) * a[ 6]; - r[11] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[11] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 5]) * a[ 8] + ((sp_int128)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[12] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = (((sp_int128)a[ 6]) * a[ 8]) * 2 + ((sp_int128)a[ 7]) * a[ 7]; - r[13] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; + r[13] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; t1 = (((sp_int128)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x3ffffffffffffffL; t1 += t0 >> 58; + r[14] = (sp_digit)(t0 & 0x3ffffffffffffffL); t1 += t0 >> 58; t0 = ((sp_int128)a[ 8]) * a[ 8]; - r[15] = t1 & 0x3ffffffffffffffL; t0 += t1 >> 58; - r[16] = t0 & 0x3ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x3ffffffffffffffL); t0 += t1 >> 58; + r[16] = (sp_digit)(t0 & 0x3ffffffffffffffL); r[17] = (sp_digit)(t0 >> 58); XMEMCPY(r, t, sizeof(t)); } @@ -36184,10 +36060,10 @@ static void sp_521_mont_reduce_9(sp_digit* a, const sp_digit* m, sp_digit mp) (void)mp; for (i = 0; i < 8; i++) { - a[i] += ((a[8 + i] >> 57) + (a[8 + i + 1] << 1)) & 0x3ffffffffffffffL; + a[i] += (sp_digit)(((a[8 + i] >> 57) + (a[8 + i + 1] << 1)) & 0x3ffffffffffffffL); } a[8] &= 0x1ffffffffffffff; - a[8] += ((a[16] >> 57) + (a[17] << 1)) & 0x3ffffffffffffffL; + a[8] += (sp_digit)(((a[16] >> 57) + (a[17] << 1)) & 0x3ffffffffffffffL); sp_521_norm_9(a); @@ -36276,17 +36152,17 @@ SP_NOINLINE static void sp_521_mul_add_9(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x3ffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x3ffffffffffffffL); t[1] += t[0] >> 58; - r[i+1] = t[1] & 0x3ffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x3ffffffffffffffL); t[2] += t[1] >> 58; - r[i+2] = t[2] & 0x3ffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x3ffffffffffffffL); t[3] += t[2] >> 58; - r[i+3] = t[3] & 0x3ffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x3ffffffffffffffL); t[0] = t[3] >> 58; } t[0] += (tb * a[8]) + r[8]; - r[8] = t[0] & 0x3ffffffffffffffL; + r[8] = (sp_digit)(t[0] & 0x3ffffffffffffffL); r[9] += (sp_digit)(t[0] >> 58); #else sp_int128 tb = b; @@ -36328,7 +36204,7 @@ static void sp_521_mont_shift_9(sp_digit* r, const sp_digit* a) n = a[8] >> 57; for (i = 0; i < 8; i++) { n += (sp_uint64)a[9 + i] << 1; - r[i] = n & 0x3ffffffffffffffL; + r[i] = (sp_digit)(n & 0x3ffffffffffffffL); n >>= 58; } n += (sp_uint64)a[17] << 1; @@ -36337,14 +36213,14 @@ static void sp_521_mont_shift_9(sp_digit* r, const sp_digit* a) sp_uint64 n; n = a[8] >> 57; - n += (sp_uint64)a[ 9] << 1U; r[ 0] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[10] << 1U; r[ 1] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[11] << 1U; r[ 2] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[12] << 1U; r[ 3] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[13] << 1U; r[ 4] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[14] << 1U; r[ 5] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[15] << 1U; r[ 6] = n & 0x3ffffffffffffffUL; n >>= 58U; - n += (sp_uint64)a[16] << 1U; r[ 7] = n & 0x3ffffffffffffffUL; n >>= 58U; + n += (sp_uint64)a[ 9] << 1U; r[ 0] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[10] << 1U; r[ 1] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[11] << 1U; r[ 2] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[12] << 1U; r[ 3] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[13] << 1U; r[ 4] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[14] << 1U; r[ 5] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[15] << 1U; r[ 6] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; + n += (sp_uint64)a[16] << 1U; r[ 7] = (sp_digit)(n & 0x3ffffffffffffffUL); n >>= 58U; n += (sp_uint64)a[17] << 1U; r[ 8] = n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[9], 0, sizeof(*r) * 9U); @@ -36365,11 +36241,11 @@ static void sp_521_mont_reduce_order_9(sp_digit* a, const sp_digit* m, sp_digit sp_521_norm_9(a + 9); for (i=0; i<8; i++) { - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x3ffffffffffffffL); sp_521_mul_add_9(a+i, m, mu); a[i+1] += a[i] >> 58; } - mu = ((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL; + mu = (sp_digit)(((sp_uint64)a[i] * (sp_uint64)mp) & 0x1ffffffffffffffL); sp_521_mul_add_9(a+i, m, mu); a[i+1] += a[i] >> 58; a[i] &= 0x3ffffffffffffffL; @@ -36542,7 +36418,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_9(r->x, p521_mod); - sp_521_cond_sub_9(r->x, r->x, p521_mod, ~(n >> 57)); + sp_521_cond_sub_9(r->x, r->x, p521_mod, (sp_digit)~(n >> 57)); sp_521_norm_9(r->x); /* y /= z^3 */ @@ -36551,7 +36427,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_9(r->y, p521_mod); - sp_521_cond_sub_9(r->y, r->y, p521_mod, ~(n >> 57)); + sp_521_cond_sub_9(r->y, r->y, p521_mod, (sp_digit)~(n >> 57)); sp_521_norm_9(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -36685,17 +36561,17 @@ SP_NOINLINE static void sp_521_rshift1_9(sp_digit* r, const sp_digit* a) int i; for (i=0; i<8; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 57) & 0x3ffffffffffffffL); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 57) & 0x3ffffffffffffffL); } #else - r[0] = (a[0] >> 1) + ((a[1] << 57) & 0x3ffffffffffffffL); - r[1] = (a[1] >> 1) + ((a[2] << 57) & 0x3ffffffffffffffL); - r[2] = (a[2] >> 1) + ((a[3] << 57) & 0x3ffffffffffffffL); - r[3] = (a[3] >> 1) + ((a[4] << 57) & 0x3ffffffffffffffL); - r[4] = (a[4] >> 1) + ((a[5] << 57) & 0x3ffffffffffffffL); - r[5] = (a[5] >> 1) + ((a[6] << 57) & 0x3ffffffffffffffL); - r[6] = (a[6] >> 1) + ((a[7] << 57) & 0x3ffffffffffffffL); - r[7] = (a[7] >> 1) + ((a[8] << 57) & 0x3ffffffffffffffL); + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 57) & 0x3ffffffffffffffL); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 57) & 0x3ffffffffffffffL); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 57) & 0x3ffffffffffffffL); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 57) & 0x3ffffffffffffffL); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 57) & 0x3ffffffffffffffL); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 57) & 0x3ffffffffffffffL); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 57) & 0x3ffffffffffffffL); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 57) & 0x3ffffffffffffffL); #endif r[8] = a[8] >> 1; } @@ -37006,8 +36882,8 @@ static void sp_521_proj_point_add_9(sp_point_521* r, sp_521_mont_sub_9(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -37024,7 +36900,7 @@ static void sp_521_proj_point_add_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -37198,8 +37074,8 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -37216,7 +37092,7 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -37820,7 +37696,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 58) { y &= 0x3f; n >>= 6; @@ -37887,7 +37763,7 @@ static void sp_521_get_point_33_9(sp_point_521* r, const sp_point_521* table, r->z[7] = 0; r->z[8] = 0; for (i = 1; i < 33; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -38054,10 +37930,8 @@ static int sp_521_ecc_mulmod_win_add_sub_9(sp_point_521* r, const sp_point_521* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38123,8 +37997,8 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, sp_521_mont_sub_9(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -38141,7 +38015,7 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -38252,8 +38126,7 @@ static int sp_521_gen_stripe_table_9(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38292,7 +38165,7 @@ static void sp_521_get_entry_256_9(sp_point_521* r, r->y[7] = 0; r->y[8] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -38421,10 +38294,8 @@ static int sp_521_ecc_mulmod_stripe_9(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38642,10 +38513,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38722,10 +38591,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40621,10 +40488,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40699,10 +40564,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40766,6 +40629,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -40783,6 +40647,11 @@ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -40861,12 +40730,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41049,10 +40915,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41117,18 +40981,18 @@ SP_NOINLINE static void sp_521_rshift_9(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<8; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (58 - n))) & 0x3ffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (58 - n))) & 0x3ffffffffffffffL); } #else for (i=0; i<8; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (58 - n)) & 0x3ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (58 - n)) & 0x3ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (58 - n)) & 0x3ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (58 - n)) & 0x3ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (58 - n)) & 0x3ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (58 - n)) & 0x3ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (58 - n)) & 0x3ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (58 - n)) & 0x3ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (58 - n)) & 0x3ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (58 - n)) & 0x3ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (58 - n)) & 0x3ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (58 - n)) & 0x3ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (58 - n)) & 0x3ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (58 - n)) & 0x3ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (58 - n)) & 0x3ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (58 - n)) & 0x3ffffffffffffffL); } #endif /* WOLFSSL_SP_SMALL */ r[8] = a[8] >> n; @@ -41190,7 +41054,7 @@ SP_NOINLINE static void sp_521_lshift_18(sp_digit* r, const sp_digit* a, r[18] = a[17] >> (58 - n); for (i=17; i>0; i--) { - r[i] = ((a[i] << n) | (a[i-1] >> (58 - n))) & 0x3ffffffffffffffL; + r[i] = (sp_digit)(((a[i] << n) | (a[i-1] >> (58 - n))) & 0x3ffffffffffffffL); } #else sp_int_digit s; @@ -41199,41 +41063,41 @@ SP_NOINLINE static void sp_521_lshift_18(sp_digit* r, const sp_digit* a, s = (sp_int_digit)a[17]; r[18] = s >> (58U - n); s = (sp_int_digit)(a[17]); t = (sp_int_digit)(a[16]); - r[17] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[17] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[16]); t = (sp_int_digit)(a[15]); - r[16] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[16] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[15]); t = (sp_int_digit)(a[14]); - r[15] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[15] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[14]); t = (sp_int_digit)(a[13]); - r[14] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[14] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[13]); t = (sp_int_digit)(a[12]); - r[13] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[13] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[12]); t = (sp_int_digit)(a[11]); - r[12] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[12] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[11]); t = (sp_int_digit)(a[10]); - r[11] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[11] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[10]); t = (sp_int_digit)(a[9]); - r[10] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[10] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[9]); t = (sp_int_digit)(a[8]); - r[9] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[9] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[8]); t = (sp_int_digit)(a[7]); - r[8] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[8] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[7]); t = (sp_int_digit)(a[6]); - r[7] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[7] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[6]); t = (sp_int_digit)(a[5]); - r[6] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[6] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[5]); t = (sp_int_digit)(a[4]); - r[5] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[5] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[4]); t = (sp_int_digit)(a[3]); - r[4] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[4] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[3]); t = (sp_int_digit)(a[2]); - r[3] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[3] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[2]); t = (sp_int_digit)(a[1]); - r[2] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[2] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); s = (sp_int_digit)(a[1]); t = (sp_int_digit)(a[0]); - r[1] = ((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL; + r[1] = (sp_digit)(((s << n) | (t >> (58U - n))) & 0x3ffffffffffffffUL); #endif /* WOLFSSL_SP_SMALL */ - r[0] = (a[0] << n) & 0x3ffffffffffffffL; + r[0] = (sp_digit)((a[0] << n) & 0x3ffffffffffffffL); } /* Divide d in a and put remainder into r (m*d + r = a) @@ -41297,8 +41161,7 @@ static int sp_521_div_9(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -42020,8 +41883,7 @@ static int sp_521_mod_inv_9(sp_digit* r, const sp_digit* a, const sp_digit* m) XMEMCPY(r, d, sizeof(sp_digit) * 9); } #ifdef WOLFSSL_SP_SMALL_STACK - if (u != NULL) - XFREE(u, NULL, DYNAMIC_TYPE_ECC); + XFREE(u, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42234,10 +42096,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42448,8 +42308,7 @@ static int sp_521_ecc_is_point_9(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42488,8 +42347,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42597,10 +42455,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -42679,10 +42535,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42747,10 +42601,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42811,10 +42663,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42864,8 +42714,7 @@ static int sp_521_mont_sqrt_9(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42930,8 +42779,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -42970,29 +42818,29 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, t0 = ((sp_int128)a[ 0]) * b[ 0]; t1 = ((sp_int128)a[ 0]) * b[ 1] + ((sp_int128)a[ 1]) * b[ 0]; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 0]) * b[ 2] + ((sp_int128)a[ 1]) * b[ 1] + ((sp_int128)a[ 2]) * b[ 0]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 0]) * b[ 3] + ((sp_int128)a[ 1]) * b[ 2] + ((sp_int128)a[ 2]) * b[ 1] + ((sp_int128)a[ 3]) * b[ 0]; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 0]) * b[ 4] + ((sp_int128)a[ 1]) * b[ 3] + ((sp_int128)a[ 2]) * b[ 2] + ((sp_int128)a[ 3]) * b[ 1] + ((sp_int128)a[ 4]) * b[ 0]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 0]) * b[ 5] + ((sp_int128)a[ 1]) * b[ 4] + ((sp_int128)a[ 2]) * b[ 3] + ((sp_int128)a[ 3]) * b[ 2] + ((sp_int128)a[ 4]) * b[ 1] + ((sp_int128)a[ 5]) * b[ 0]; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 0]) * b[ 6] + ((sp_int128)a[ 1]) * b[ 5] + ((sp_int128)a[ 2]) * b[ 4] @@ -43000,7 +42848,7 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 4]) * b[ 2] + ((sp_int128)a[ 5]) * b[ 1] + ((sp_int128)a[ 6]) * b[ 0]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 0]) * b[ 7] + ((sp_int128)a[ 1]) * b[ 6] + ((sp_int128)a[ 2]) * b[ 5] @@ -43009,7 +42857,7 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 5]) * b[ 2] + ((sp_int128)a[ 6]) * b[ 1] + ((sp_int128)a[ 7]) * b[ 0]; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 0]) * b[ 8] + ((sp_int128)a[ 1]) * b[ 7] + ((sp_int128)a[ 2]) * b[ 6] @@ -43019,7 +42867,7 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 2] + ((sp_int128)a[ 7]) * b[ 1] + ((sp_int128)a[ 8]) * b[ 0]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 1]) * b[ 8] + ((sp_int128)a[ 2]) * b[ 7] + ((sp_int128)a[ 3]) * b[ 6] @@ -43028,7 +42876,7 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 3] + ((sp_int128)a[ 7]) * b[ 2] + ((sp_int128)a[ 8]) * b[ 1]; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 2]) * b[ 8] + ((sp_int128)a[ 3]) * b[ 7] + ((sp_int128)a[ 4]) * b[ 6] @@ -43036,35 +42884,35 @@ SP_NOINLINE static void sp_1024_mul_9(sp_digit* r, const sp_digit* a, + ((sp_int128)a[ 6]) * b[ 4] + ((sp_int128)a[ 7]) * b[ 3] + ((sp_int128)a[ 8]) * b[ 2]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 3]) * b[ 8] + ((sp_int128)a[ 4]) * b[ 7] + ((sp_int128)a[ 5]) * b[ 6] + ((sp_int128)a[ 6]) * b[ 5] + ((sp_int128)a[ 7]) * b[ 4] + ((sp_int128)a[ 8]) * b[ 3]; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 4]) * b[ 8] + ((sp_int128)a[ 5]) * b[ 7] + ((sp_int128)a[ 6]) * b[ 6] + ((sp_int128)a[ 7]) * b[ 5] + ((sp_int128)a[ 8]) * b[ 4]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 5]) * b[ 8] + ((sp_int128)a[ 6]) * b[ 7] + ((sp_int128)a[ 7]) * b[ 6] + ((sp_int128)a[ 8]) * b[ 5]; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 6]) * b[ 8] + ((sp_int128)a[ 7]) * b[ 7] + ((sp_int128)a[ 8]) * b[ 6]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = ((sp_int128)a[ 7]) * b[ 8] + ((sp_int128)a[ 8]) * b[ 7]; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 8]) * b[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -43082,66 +42930,66 @@ SP_NOINLINE static void sp_1024_sqr_9(sp_digit* r, const sp_digit* a) t0 = ((sp_int128)a[ 0]) * a[ 0]; t1 = (((sp_int128)a[ 0]) * a[ 1]) * 2; - t[ 0] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 0] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 0]) * a[ 2]) * 2 + ((sp_int128)a[ 1]) * a[ 1]; - t[ 1] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 1] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 0]) * a[ 3] + ((sp_int128)a[ 1]) * a[ 2]) * 2; - t[ 2] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 2] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 0]) * a[ 4] + ((sp_int128)a[ 1]) * a[ 3]) * 2 + ((sp_int128)a[ 2]) * a[ 2]; - t[ 3] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 3] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 0]) * a[ 5] + ((sp_int128)a[ 1]) * a[ 4] + ((sp_int128)a[ 2]) * a[ 3]) * 2; - t[ 4] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 4] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 0]) * a[ 6] + ((sp_int128)a[ 1]) * a[ 5] + ((sp_int128)a[ 2]) * a[ 4]) * 2 + ((sp_int128)a[ 3]) * a[ 3]; - t[ 5] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 5] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 0]) * a[ 7] + ((sp_int128)a[ 1]) * a[ 6] + ((sp_int128)a[ 2]) * a[ 5] + ((sp_int128)a[ 3]) * a[ 4]) * 2; - t[ 6] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 6] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 0]) * a[ 8] + ((sp_int128)a[ 1]) * a[ 7] + ((sp_int128)a[ 2]) * a[ 6] + ((sp_int128)a[ 3]) * a[ 5]) * 2 + ((sp_int128)a[ 4]) * a[ 4]; - t[ 7] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + t[ 7] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 1]) * a[ 8] + ((sp_int128)a[ 2]) * a[ 7] + ((sp_int128)a[ 3]) * a[ 6] + ((sp_int128)a[ 4]) * a[ 5]) * 2; - t[ 8] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + t[ 8] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 2]) * a[ 8] + ((sp_int128)a[ 3]) * a[ 7] + ((sp_int128)a[ 4]) * a[ 6]) * 2 + ((sp_int128)a[ 5]) * a[ 5]; - r[ 9] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[ 9] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 3]) * a[ 8] + ((sp_int128)a[ 4]) * a[ 7] + ((sp_int128)a[ 5]) * a[ 6]) * 2; - r[10] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[10] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 4]) * a[ 8] + ((sp_int128)a[ 5]) * a[ 7]) * 2 + ((sp_int128)a[ 6]) * a[ 6]; - r[11] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[11] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 5]) * a[ 8] + ((sp_int128)a[ 6]) * a[ 7]) * 2; - r[12] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[12] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = (((sp_int128)a[ 6]) * a[ 8]) * 2 + ((sp_int128)a[ 7]) * a[ 7]; - r[13] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; + r[13] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; t1 = (((sp_int128)a[ 7]) * a[ 8]) * 2; - r[14] = t0 & 0x1ffffffffffffffL; t1 += t0 >> 57; + r[14] = (sp_digit)(t0 & 0x1ffffffffffffffL); t1 += t0 >> 57; t0 = ((sp_int128)a[ 8]) * a[ 8]; - r[15] = t1 & 0x1ffffffffffffffL; t0 += t1 >> 57; - r[16] = t0 & 0x1ffffffffffffffL; + r[15] = (sp_digit)(t1 & 0x1ffffffffffffffL); t0 += t1 >> 57; + r[16] = (sp_digit)(t0 & 0x1ffffffffffffffL); r[17] = (sp_digit)(t0 >> 57); XMEMCPY(r, t, sizeof(t)); } @@ -43657,20 +43505,20 @@ SP_NOINLINE static void sp_1024_rshift_18(sp_digit* r, const sp_digit* a, #ifdef WOLFSSL_SP_SMALL for (i=0; i<17; i++) { - r[i] = ((a[i] >> n) | (a[i + 1] << (57 - n))) & 0x1ffffffffffffffL; + r[i] = (sp_digit)(((a[i] >> n) | (a[i + 1] << (57 - n))) & 0x1ffffffffffffffL); } #else for (i=0; i<16; i += 8) { - r[i+0] = (a[i+0] >> n) | ((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); - r[i+1] = (a[i+1] >> n) | ((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); - r[i+2] = (a[i+2] >> n) | ((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); - r[i+3] = (a[i+3] >> n) | ((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); - r[i+4] = (a[i+4] >> n) | ((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); - r[i+5] = (a[i+5] >> n) | ((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); - r[i+6] = (a[i+6] >> n) | ((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); - r[i+7] = (a[i+7] >> n) | ((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); - } - r[16] = (a[16] >> n) | ((a[17] << (57 - n)) & 0x1ffffffffffffffL); + r[i+0] = (a[i+0] >> n) | (sp_digit)((a[i+1] << (57 - n)) & 0x1ffffffffffffffL); + r[i+1] = (a[i+1] >> n) | (sp_digit)((a[i+2] << (57 - n)) & 0x1ffffffffffffffL); + r[i+2] = (a[i+2] >> n) | (sp_digit)((a[i+3] << (57 - n)) & 0x1ffffffffffffffL); + r[i+3] = (a[i+3] >> n) | (sp_digit)((a[i+4] << (57 - n)) & 0x1ffffffffffffffL); + r[i+4] = (a[i+4] >> n) | (sp_digit)((a[i+5] << (57 - n)) & 0x1ffffffffffffffL); + r[i+5] = (a[i+5] >> n) | (sp_digit)((a[i+6] << (57 - n)) & 0x1ffffffffffffffL); + r[i+6] = (a[i+6] >> n) | (sp_digit)((a[i+7] << (57 - n)) & 0x1ffffffffffffffL); + r[i+7] = (a[i+7] >> n) | (sp_digit)((a[i+8] << (57 - n)) & 0x1ffffffffffffffL); + } + r[16] = (a[16] >> n) | (sp_digit)((a[17] << (57 - n)) & 0x1ffffffffffffffL); #endif /* WOLFSSL_SP_SMALL */ r[17] = a[17] >> n; } @@ -43847,8 +43695,7 @@ static int sp_1024_div_18(const sp_digit* a, const sp_digit* d, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(t1, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -43927,16 +43774,16 @@ static void sp_1024_point_free_18(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -44230,20 +44077,20 @@ SP_NOINLINE static void sp_1024_mul_add_18(sp_digit* r, const sp_digit* a, t[1] = (tb * a[i+1]) + r[i+1]; t[2] = (tb * a[i+2]) + r[i+2]; t[3] = (tb * a[i+3]) + r[i+3]; - r[i+0] = t[0] & 0x1ffffffffffffffL; + r[i+0] = (sp_digit)(t[0] & 0x1ffffffffffffffL); t[1] += t[0] >> 57; - r[i+1] = t[1] & 0x1ffffffffffffffL; + r[i+1] = (sp_digit)(t[1] & 0x1ffffffffffffffL); t[2] += t[1] >> 57; - r[i+2] = t[2] & 0x1ffffffffffffffL; + r[i+2] = (sp_digit)(t[2] & 0x1ffffffffffffffL); t[3] += t[2] >> 57; - r[i+3] = t[3] & 0x1ffffffffffffffL; + r[i+3] = (sp_digit)(t[3] & 0x1ffffffffffffffL); t[0] = t[3] >> 57; } t[0] += (tb * a[16]) + r[16]; t[1] = (tb * a[17]) + r[17]; - r[16] = t[0] & 0x1ffffffffffffffL; + r[16] = (sp_digit)(t[0] & 0x1ffffffffffffffL); t[1] += t[0] >> 57; - r[17] = t[1] & 0x1ffffffffffffffL; + r[17] = (sp_digit)(t[1] & 0x1ffffffffffffffL); r[18] += (sp_digit)(t[1] >> 57); #else sp_int128 tb = b; @@ -44289,7 +44136,7 @@ static void sp_1024_mont_shift_18(sp_digit* r, const sp_digit* a) n = a[17] >> 55; for (i = 0; i < 17; i++) { n += (sp_uint64)a[18 + i] << 2; - r[i] = n & 0x1ffffffffffffffL; + r[i] = (sp_digit)(n & 0x1ffffffffffffffL); n >>= 57; } n += (sp_uint64)a[35] << 2; @@ -44301,16 +44148,16 @@ static void sp_1024_mont_shift_18(sp_digit* r, const sp_digit* a) n = (sp_uint64)a[17]; n = n >> 55U; for (i = 0; i < 16; i += 8) { - n += (sp_uint64)a[i+18] << 2U; r[i+0] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+19] << 2U; r[i+1] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+20] << 2U; r[i+2] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+21] << 2U; r[i+3] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+22] << 2U; r[i+4] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+23] << 2U; r[i+5] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+24] << 2U; r[i+6] = n & 0x1ffffffffffffffUL; n >>= 57U; - n += (sp_uint64)a[i+25] << 2U; r[i+7] = n & 0x1ffffffffffffffUL; n >>= 57U; - } - n += (sp_uint64)a[34] << 2U; r[16] = n & 0x1ffffffffffffffUL; n >>= 57U; + n += (sp_uint64)a[i+18] << 2U; r[i+0] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+19] << 2U; r[i+1] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+20] << 2U; r[i+2] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+21] << 2U; r[i+3] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+22] << 2U; r[i+4] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+23] << 2U; r[i+5] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+24] << 2U; r[i+6] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + n += (sp_uint64)a[i+25] << 2U; r[i+7] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; + } + n += (sp_uint64)a[34] << 2U; r[16] = (sp_digit)(n & 0x1ffffffffffffffUL); n >>= 57U; n += (sp_uint64)a[35] << 2U; r[17] = n; #endif /* WOLFSSL_SP_SMALL */ XMEMSET(&r[18], 0, sizeof(*r) * 18U); @@ -44332,22 +44179,22 @@ static void sp_1024_mont_reduce_18(sp_digit* a, const sp_digit* m, sp_digit mp) if (mp != 1) { for (i=0; i<17; i++) { - mu = (a[i] * mp) & 0x1ffffffffffffffL; + mu = (sp_digit)((a[i] * mp) & 0x1ffffffffffffffL); sp_1024_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = (a[i] * mp) & 0x7fffffffffffffL; + mu = (sp_digit)((a[i] * mp) & 0x7fffffffffffffL); sp_1024_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; } else { for (i=0; i<17; i++) { - mu = a[i] & 0x1ffffffffffffffL; + mu = (sp_digit)(a[i] & 0x1ffffffffffffffL); sp_1024_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; } - mu = a[i] & 0x7fffffffffffffL; + mu = (sp_digit)(a[i] & 0x7fffffffffffffL); sp_1024_mul_add_18(a+i, m, mu); a[i+1] += a[i] >> 57; a[i] &= 0x1ffffffffffffffL; @@ -44473,7 +44320,7 @@ static void sp_1024_map_18(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_18(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_18(r->x, p1024_mod); - sp_1024_cond_sub_18(r->x, r->x, p1024_mod, ~(n >> 56)); + sp_1024_cond_sub_18(r->x, r->x, p1024_mod, (sp_digit)~(n >> 56)); sp_1024_norm_18(r->x); /* y /= z^3 */ @@ -44482,7 +44329,7 @@ static void sp_1024_map_18(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_18(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_18(r->y, p1024_mod); - sp_1024_cond_sub_18(r->y, r->y, p1024_mod, ~(n >> 56)); + sp_1024_cond_sub_18(r->y, r->y, p1024_mod, (sp_digit)~(n >> 56)); sp_1024_norm_18(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -44572,26 +44419,26 @@ SP_NOINLINE static void sp_1024_rshift1_18(sp_digit* r, const sp_digit* a) int i; for (i=0; i<17; i++) { - r[i] = (a[i] >> 1) + ((a[i + 1] << 56) & 0x1ffffffffffffffL); - } -#else - r[0] = (a[0] >> 1) + ((a[1] << 56) & 0x1ffffffffffffffL); - r[1] = (a[1] >> 1) + ((a[2] << 56) & 0x1ffffffffffffffL); - r[2] = (a[2] >> 1) + ((a[3] << 56) & 0x1ffffffffffffffL); - r[3] = (a[3] >> 1) + ((a[4] << 56) & 0x1ffffffffffffffL); - r[4] = (a[4] >> 1) + ((a[5] << 56) & 0x1ffffffffffffffL); - r[5] = (a[5] >> 1) + ((a[6] << 56) & 0x1ffffffffffffffL); - r[6] = (a[6] >> 1) + ((a[7] << 56) & 0x1ffffffffffffffL); - r[7] = (a[7] >> 1) + ((a[8] << 56) & 0x1ffffffffffffffL); - r[8] = (a[8] >> 1) + ((a[9] << 56) & 0x1ffffffffffffffL); - r[9] = (a[9] >> 1) + ((a[10] << 56) & 0x1ffffffffffffffL); - r[10] = (a[10] >> 1) + ((a[11] << 56) & 0x1ffffffffffffffL); - r[11] = (a[11] >> 1) + ((a[12] << 56) & 0x1ffffffffffffffL); - r[12] = (a[12] >> 1) + ((a[13] << 56) & 0x1ffffffffffffffL); - r[13] = (a[13] >> 1) + ((a[14] << 56) & 0x1ffffffffffffffL); - r[14] = (a[14] >> 1) + ((a[15] << 56) & 0x1ffffffffffffffL); - r[15] = (a[15] >> 1) + ((a[16] << 56) & 0x1ffffffffffffffL); - r[16] = (a[16] >> 1) + ((a[17] << 56) & 0x1ffffffffffffffL); + r[i] = (a[i] >> 1) + (sp_digit)((a[i + 1] << 56) & 0x1ffffffffffffffL); + } +#else + r[0] = (a[0] >> 1) + (sp_digit)((a[1] << 56) & 0x1ffffffffffffffL); + r[1] = (a[1] >> 1) + (sp_digit)((a[2] << 56) & 0x1ffffffffffffffL); + r[2] = (a[2] >> 1) + (sp_digit)((a[3] << 56) & 0x1ffffffffffffffL); + r[3] = (a[3] >> 1) + (sp_digit)((a[4] << 56) & 0x1ffffffffffffffL); + r[4] = (a[4] >> 1) + (sp_digit)((a[5] << 56) & 0x1ffffffffffffffL); + r[5] = (a[5] >> 1) + (sp_digit)((a[6] << 56) & 0x1ffffffffffffffL); + r[6] = (a[6] >> 1) + (sp_digit)((a[7] << 56) & 0x1ffffffffffffffL); + r[7] = (a[7] >> 1) + (sp_digit)((a[8] << 56) & 0x1ffffffffffffffL); + r[8] = (a[8] >> 1) + (sp_digit)((a[9] << 56) & 0x1ffffffffffffffL); + r[9] = (a[9] >> 1) + (sp_digit)((a[10] << 56) & 0x1ffffffffffffffL); + r[10] = (a[10] >> 1) + (sp_digit)((a[11] << 56) & 0x1ffffffffffffffL); + r[11] = (a[11] >> 1) + (sp_digit)((a[12] << 56) & 0x1ffffffffffffffL); + r[12] = (a[12] >> 1) + (sp_digit)((a[13] << 56) & 0x1ffffffffffffffL); + r[13] = (a[13] >> 1) + (sp_digit)((a[14] << 56) & 0x1ffffffffffffffL); + r[14] = (a[14] >> 1) + (sp_digit)((a[15] << 56) & 0x1ffffffffffffffL); + r[15] = (a[15] >> 1) + (sp_digit)((a[16] << 56) & 0x1ffffffffffffffL); + r[16] = (a[16] >> 1) + (sp_digit)((a[17] << 56) & 0x1ffffffffffffffL); #endif r[17] = a[17] >> 1; } @@ -44906,8 +44753,8 @@ static void sp_1024_proj_point_add_18(sp_point_1024* r, sp_1024_mont_sub_18(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -44924,7 +44771,7 @@ static void sp_1024_proj_point_add_18(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -45098,8 +44945,8 @@ static int sp_1024_proj_point_add_18_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45116,7 +44963,7 @@ static int sp_1024_proj_point_add_18_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -45728,7 +45575,7 @@ static void sp_1024_ecc_recode_7_18(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 57) { y &= 0x7f; n >>= 7; @@ -45894,10 +45741,8 @@ static int sp_1024_ecc_mulmod_win_add_sub_18(sp_point_1024* r, const sp_point_10 } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -45963,8 +45808,8 @@ static void sp_1024_proj_point_add_qz1_18(sp_point_1024* r, sp_1024_mont_sub_18(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45981,7 +45826,7 @@ static void sp_1024_proj_point_add_qz1_18(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -46092,8 +45937,7 @@ static int sp_1024_gen_stripe_table_18(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46192,10 +46036,8 @@ static int sp_1024_ecc_mulmod_stripe_18(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46413,10 +46255,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49844,10 +49684,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49922,10 +49760,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49959,7 +49795,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -49990,10 +49826,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -50019,7 +49853,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -50086,10 +49920,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -50236,9 +50068,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -51878,9 +51708,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -52248,9 +52076,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_18(c, 1, NULL); sp_1024_point_free_18(q, 1, NULL); @@ -52675,9 +52501,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_18(c, 1, NULL); sp_1024_point_free_18(q, 1, NULL); @@ -52707,7 +52531,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -52936,7 +52760,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -53043,9 +52867,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_18(neg, 1, NULL); sp_1024_point_free_18(c, 1, NULL); @@ -53238,9 +53060,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_18(c, 1, NULL); sp_1024_point_free_18(q, 1, NULL); @@ -53330,7 +53150,7 @@ static int sp_1024_ecc_is_point_18(const sp_point_1024* point, n = sp_1024_cmp_18(t1, p1024_mod); - sp_1024_cond_sub_18(t1, t1, p1024_mod, ~(n >> 56)); + sp_1024_cond_sub_18(t1, t1, p1024_mod, (sp_digit)~(n >> 56)); sp_1024_norm_18(t1); if (!sp_1024_iszero_18(t1)) { err = MP_VAL; @@ -53338,8 +53158,7 @@ static int sp_1024_ecc_is_point_18(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -53378,8 +53197,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -53487,10 +53305,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_cortexm.c b/src/wolfcrypt/src/sp_cortexm.c index 8ef1a13..25404a7 100644 --- a/src/wolfcrypt/src/sp_cortexm.c +++ b/src/wolfcrypt/src/sp_cortexm.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -67,7 +67,7 @@ do { \ int ii; \ fprintf(stderr, name "=0x"); \ - for (ii = ((bits + 31) / 32) - 1; ii >= 0; ii--) \ + for (ii = (((bits) + 31) / 32) - 1; ii >= 0; ii--) \ fprintf(stderr, SP_PRINT_FMT, (var)[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -240,7 +240,7 @@ static void sp_2048_to_bin_64(sp_digit* r, byte* a) #define sp_2048_norm_64(a) #ifndef WOLFSSL_SP_SMALL -#ifdef WOLFSSL_SP_NO_UMAAL +#ifdef WOLFSSL_ARM_ARCH_7M /* Multiply a and b into r. (r = a * b) * * r A single precision integer. @@ -736,7 +736,7 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_d ); } -#endif /* WOLFSSL_SP_NO_UMAAL */ +#endif /* WOLFSSL_ARM_ARCH_7M */ /* Add b to a into r. (r = a + b) * * r A single precision integer. @@ -1533,7 +1533,7 @@ SP_NOINLINE static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, (void)sp_2048_add_32(r + 96, r + 96, a1); } -#ifdef WOLFSSL_SP_NO_UMAAL +#ifdef WOLFSSL_ARM_ARCH_7M /* Square a and put result in r. (r = a * a) * * r A single precision integer. @@ -1899,7 +1899,7 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) ); } -#endif /* WOLFSSL_SP_NO_UMAAL */ +#endif /* WOLFSSL_ARM_ARCH_7M */ /* Sub b from a into r. (r = a - b) * * r A single precision integer. @@ -2211,7 +2211,11 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x100\n\t" "\n" - "L_sp_2048_add_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_add_64_word:\n\t" +#else + "L_sp_2048_add_64_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -2223,10 +2227,12 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_add_64_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_2048_add_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_2048_add_64_word\n\t" #else - "BNE.N L_sp_2048_add_64_word%=\n\t" + "BNE.N L_sp_2048_add_64_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -2258,7 +2264,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x100\n\t" "\n" - "L_sp_2048_sub_in_pkace_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sub_in_pkace_64_word:\n\t" +#else + "L_sp_2048_sub_in_pkace_64_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -2269,10 +2279,12 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_in_pkace_64_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_2048_sub_in_pkace_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_2048_sub_in_pkace_64_word\n\t" #else - "BNE.N L_sp_2048_sub_in_pkace_64_word%=\n\t" + "BNE.N L_sp_2048_sub_in_pkace_64_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -2312,13 +2324,21 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_mul_64_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_64_outer:\n\t" +#else + "L_sp_2048_mul_64_outer_%=:\n\t" +#endif "SUBS r3, r5, #0xfc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_mul_64_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_64_inner:\n\t" +#else + "L_sp_2048_mul_64_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2334,15 +2354,19 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_64_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_mul_64_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_mul_64_inner_done\n\t" #else - "BGT.N L_sp_2048_mul_64_inner_done%=\n\t" + "BGT.N L_sp_2048_mul_64_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_64_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mul_64_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mul_64_inner\n\t" #else - "BLT.N L_sp_2048_mul_64_inner%=\n\t" + "BLT.N L_sp_2048_mul_64_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -2351,17 +2375,23 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_mul_64_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_64_inner_done:\n\t" +#else + "L_sp_2048_mul_64_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x1f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_mul_64_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_2048_mul_64_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_2048_mul_64_outer\n\t" #else - "BLE.N L_sp_2048_mul_64_outer%=\n\t" + "BLE.N L_sp_2048_mul_64_outer_%=\n\t" #endif "LDR lr, [%[a], #252]\n\t" "LDR r11, [%[b], #252]\n\t" @@ -2370,14 +2400,20 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_mul_64_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_64_store:\n\t" +#else + "L_sp_2048_mul_64_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_64_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_mul_64_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_mul_64_store\n\t" #else - "BGT.N L_sp_2048_mul_64_store%=\n\t" + "BGT.N L_sp_2048_mul_64_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -2410,13 +2446,21 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_sqr_64_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_64_outer:\n\t" +#else + "L_sp_2048_sqr_64_outer_%=:\n\t" +#endif "SUBS r3, r5, #0xfc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_sqr_64_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_64_inner:\n\t" +#else + "L_sp_2048_sqr_64_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2429,15 +2473,19 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_64_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_sqr_64_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_sqr_64_inner_done\n\t" #else - "BGT.N L_sp_2048_sqr_64_inner_done%=\n\t" + "BGT.N L_sp_2048_sqr_64_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_sqr_64_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_sqr_64_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_sqr_64_inner\n\t" #else - "BLT.N L_sp_2048_sqr_64_inner%=\n\t" + "BLT.N L_sp_2048_sqr_64_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -2445,17 +2493,23 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_sqr_64_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_64_inner_done:\n\t" +#else + "L_sp_2048_sqr_64_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x1f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_sqr_64_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_2048_sqr_64_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_2048_sqr_64_outer\n\t" #else - "BLE.N L_sp_2048_sqr_64_outer%=\n\t" + "BLE.N L_sp_2048_sqr_64_outer_%=\n\t" #endif "LDR lr, [%[a], #252]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -2463,14 +2517,20 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_sqr_64_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_64_store:\n\t" +#else + "L_sp_2048_sqr_64_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_64_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_sqr_64_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_sqr_64_store\n\t" #else - "BGT.N L_sp_2048_sqr_64_store%=\n\t" + "BGT.N L_sp_2048_sqr_64_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -2520,7 +2580,11 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x80\n\t" "\n" - "L_sp_2048_add_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_add_32_word:\n\t" +#else + "L_sp_2048_add_32_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -2532,10 +2596,12 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_add_32_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_2048_add_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_2048_add_32_word\n\t" #else - "BNE.N L_sp_2048_add_32_word%=\n\t" + "BNE.N L_sp_2048_add_32_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -2567,7 +2633,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x80\n\t" "\n" - "L_sp_2048_sub_in_pkace_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sub_in_pkace_32_word:\n\t" +#else + "L_sp_2048_sub_in_pkace_32_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -2578,10 +2648,12 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_in_pkace_32_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_2048_sub_in_pkace_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_2048_sub_in_pkace_32_word\n\t" #else - "BNE.N L_sp_2048_sub_in_pkace_32_word%=\n\t" + "BNE.N L_sp_2048_sub_in_pkace_32_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -2621,13 +2693,21 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_mul_32_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_32_outer:\n\t" +#else + "L_sp_2048_mul_32_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_mul_32_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_32_inner:\n\t" +#else + "L_sp_2048_mul_32_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2643,15 +2723,19 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_32_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_mul_32_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_mul_32_inner_done\n\t" #else - "BGT.N L_sp_2048_mul_32_inner_done%=\n\t" + "BGT.N L_sp_2048_mul_32_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_32_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mul_32_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mul_32_inner\n\t" #else - "BLT.N L_sp_2048_mul_32_inner%=\n\t" + "BLT.N L_sp_2048_mul_32_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -2660,17 +2744,23 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_mul_32_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_32_inner_done:\n\t" +#else + "L_sp_2048_mul_32_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_mul_32_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_2048_mul_32_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_2048_mul_32_outer\n\t" #else - "BLE.N L_sp_2048_mul_32_outer%=\n\t" + "BLE.N L_sp_2048_mul_32_outer_%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "LDR r11, [%[b], #124]\n\t" @@ -2679,14 +2769,20 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_mul_32_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_32_store:\n\t" +#else + "L_sp_2048_mul_32_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_mul_32_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_mul_32_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_mul_32_store\n\t" #else - "BGT.N L_sp_2048_mul_32_store%=\n\t" + "BGT.N L_sp_2048_mul_32_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -2719,13 +2815,21 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_2048_sqr_32_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_32_outer:\n\t" +#else + "L_sp_2048_sqr_32_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_2048_sqr_32_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_32_inner:\n\t" +#else + "L_sp_2048_sqr_32_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -2738,15 +2842,19 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_32_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_sqr_32_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_sqr_32_inner_done\n\t" #else - "BGT.N L_sp_2048_sqr_32_inner_done%=\n\t" + "BGT.N L_sp_2048_sqr_32_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_sqr_32_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_sqr_32_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_sqr_32_inner\n\t" #else - "BLT.N L_sp_2048_sqr_32_inner%=\n\t" + "BLT.N L_sp_2048_sqr_32_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -2754,17 +2862,23 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_2048_sqr_32_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_32_inner_done:\n\t" +#else + "L_sp_2048_sqr_32_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_2048_sqr_32_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_2048_sqr_32_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_2048_sqr_32_outer\n\t" #else - "BLE.N L_sp_2048_sqr_32_outer%=\n\t" + "BLE.N L_sp_2048_sqr_32_outer_%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -2772,14 +2886,20 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_2048_sqr_32_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sqr_32_store:\n\t" +#else + "L_sp_2048_sqr_32_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_2048_sqr_32_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_2048_sqr_32_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_2048_sqr_32_store\n\t" #else - "BGT.N L_sp_2048_sqr_32_store%=\n\t" + "BGT.N L_sp_2048_sqr_32_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -2838,7 +2958,11 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_2048_mul_d_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_d_64_word:\n\t" +#else + "L_sp_2048_mul_d_64_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -2851,10 +2975,12 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_d_64_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mul_d_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mul_d_64_word\n\t" #else - "BLT.N L_sp_2048_mul_d_64_word%=\n\t" + "BLT.N L_sp_2048_mul_d_64_word_%=\n\t" #endif "STR r3, [%[r], #256]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -3252,7 +3378,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_2048_cond_sub_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_cond_sub_32_words:\n\t" +#else + "L_sp_2048_cond_sub_32_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -3262,10 +3392,12 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_sub_32_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_cond_sub_32_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_cond_sub_32_words\n\t" #else - "BLT.N L_sp_2048_cond_sub_32_words%=\n\t" + "BLT.N L_sp_2048_cond_sub_32_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -3448,7 +3580,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_2048_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_word:\n\t" +#else + "L_sp_2048_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -3710,10 +3846,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x80\n\t" -#ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_2048_mont_reduce_32_word\n\t" #else - "BLT.W L_sp_2048_mont_reduce_32_word%=\n\t" + "BLT.W L_sp_2048_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -3752,7 +3890,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_word:\n\t" +#else + "L_sp_2048_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -3760,7 +3902,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_mul:\n\t" +#else + "L_sp_2048_mont_reduce_32_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -3802,10 +3948,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_32_mul\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_mul%=\n\t" + "BLT.N L_sp_2048_mont_reduce_32_mul_%=\n\t" #endif "LDR r10, [%[a], #128]\n\t" "ADDS r4, r4, r3\n\t" @@ -3818,10 +3966,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_32_word\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_word%=\n\t" + "BLT.N L_sp_2048_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -3863,7 +4013,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_2048_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_word:\n\t" +#else + "L_sp_2048_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -4030,10 +4184,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x80\n\t" -#ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_2048_mont_reduce_32_word\n\t" #else - "BLT.W L_sp_2048_mont_reduce_32_word%=\n\t" + "BLT.W L_sp_2048_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -4075,7 +4231,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_word:\n\t" +#else + "L_sp_2048_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -4083,7 +4243,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_32_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_32_mul:\n\t" +#else + "L_sp_2048_mont_reduce_32_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -4113,10 +4277,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_32_mul\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_mul%=\n\t" + "BLT.N L_sp_2048_mont_reduce_32_mul_%=\n\t" #endif "LDR r10, [%[a], #128]\n\t" "ADDS r4, r4, r3\n\t" @@ -4129,10 +4295,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_32_word\n\t" #else - "BLT.N L_sp_2048_mont_reduce_32_word%=\n\t" + "BLT.N L_sp_2048_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -4203,7 +4371,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_2048_mul_d_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mul_d_32_word:\n\t" +#else + "L_sp_2048_mul_d_32_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -4216,10 +4388,12 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mul_d_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mul_d_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mul_d_32_word\n\t" #else - "BLT.N L_sp_2048_mul_d_32_word%=\n\t" + "BLT.N L_sp_2048_mul_d_32_word_%=\n\t" #endif "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -4517,7 +4691,11 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_2048_word_32_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_2048_word_32_bit:\n\t" +#else + "L_div_2048_word_32_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -4527,7 +4705,13 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_2048_word_32_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_2048_word_32_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_2048_word_32_bit\n\t" +#else + "BPL.N L_div_2048_word_32_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -4579,7 +4763,11 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x7c\n\t" "\n" - "L_sp_2048_cmp_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_cmp_32_words:\n\t" +#else + "L_sp_2048_cmp_32_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -4592,7 +4780,11 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_2048_cmp_32_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_2048_cmp_32_words\n\t" +#else + "bcs L_sp_2048_cmp_32_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #124]\n\t" @@ -5153,13 +5345,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5322,13 +5513,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32U); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5380,7 +5570,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_2048_cond_sub_64_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_cond_sub_64_words:\n\t" +#else + "L_sp_2048_cond_sub_64_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -5390,10 +5584,12 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_sub_64_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_cond_sub_64_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_cond_sub_64_words\n\t" #else - "BLT.N L_sp_2048_cond_sub_64_words%=\n\t" + "BLT.N L_sp_2048_cond_sub_64_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -5688,7 +5884,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_2048_mont_reduce_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_word:\n\t" +#else + "L_sp_2048_mont_reduce_64_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -6206,10 +6406,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x100\n\t" -#ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_64_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_2048_mont_reduce_64_word\n\t" #else - "BLT.W L_sp_2048_mont_reduce_64_word%=\n\t" + "BLT.W L_sp_2048_mont_reduce_64_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -6248,7 +6450,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_word:\n\t" +#else + "L_sp_2048_mont_reduce_64_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -6256,7 +6462,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_mul:\n\t" +#else + "L_sp_2048_mont_reduce_64_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -6298,10 +6508,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_64_mul\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_mul%=\n\t" + "BLT.N L_sp_2048_mont_reduce_64_mul_%=\n\t" #endif "LDR r10, [%[a], #256]\n\t" "ADDS r4, r4, r3\n\t" @@ -6314,10 +6526,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_64_word\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_word%=\n\t" + "BLT.N L_sp_2048_mont_reduce_64_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -6359,7 +6573,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_2048_mont_reduce_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_word:\n\t" +#else + "L_sp_2048_mont_reduce_64_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -6686,10 +6904,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x100\n\t" -#ifdef __GNUC__ - "BLT L_sp_2048_mont_reduce_64_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_2048_mont_reduce_64_word\n\t" #else - "BLT.W L_sp_2048_mont_reduce_64_word%=\n\t" + "BLT.W L_sp_2048_mont_reduce_64_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -6731,7 +6951,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_word:\n\t" +#else + "L_sp_2048_mont_reduce_64_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -6739,7 +6963,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_mont_reduce_64_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_mont_reduce_64_mul:\n\t" +#else + "L_sp_2048_mont_reduce_64_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -6769,10 +6997,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_64_mul\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_mul%=\n\t" + "BLT.N L_sp_2048_mont_reduce_64_mul_%=\n\t" #endif "LDR r10, [%[a], #256]\n\t" "ADDS r4, r4, r3\n\t" @@ -6785,10 +7015,12 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_mont_reduce_64_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_mont_reduce_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_mont_reduce_64_word\n\t" #else - "BLT.N L_sp_2048_mont_reduce_64_word%=\n\t" + "BLT.N L_sp_2048_mont_reduce_64_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -6854,7 +7086,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x100\n\t" "\n" - "L_sp_2048_sub_64_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_sub_64_word:\n\t" +#else + "L_sp_2048_sub_64_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -6865,10 +7101,12 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_2048_sub_64_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_2048_sub_64_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_2048_sub_64_word\n\t" #else - "BNE.N L_sp_2048_sub_64_word%=\n\t" + "BNE.N L_sp_2048_sub_64_word_%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -7121,7 +7359,11 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_2048_word_64_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_2048_word_64_bit:\n\t" +#else + "L_div_2048_word_64_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -7131,7 +7373,13 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_2048_word_64_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_2048_word_64_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_2048_word_64_bit\n\t" +#else + "BPL.N L_div_2048_word_64_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -7286,7 +7534,11 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0xfc\n\t" "\n" - "L_sp_2048_cmp_64_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_cmp_64_words:\n\t" +#else + "L_sp_2048_cmp_64_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -7299,7 +7551,11 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_2048_cmp_64_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_2048_cmp_64_words\n\t" +#else + "bcs L_sp_2048_cmp_64_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #252]\n\t" @@ -8206,13 +8462,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8358,13 +8613,12 @@ static int sp_2048_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -8527,8 +8781,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -8562,7 +8815,11 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_2048_cond_add_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_2048_cond_add_32_words:\n\t" +#else + "L_sp_2048_cond_add_32_words_%=:\n\t" +#endif "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -8572,10 +8829,12 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r4]\n\t" "ADD r4, r4, #0x4\n\t" "CMP r4, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_2048_cond_add_32_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_2048_cond_add_32_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_2048_cond_add_32_words\n\t" #else - "BLT.N L_sp_2048_cond_add_32_words%=\n\t" + "BLT.N L_sp_2048_cond_add_32_words_%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -9562,13 +9821,12 @@ static int sp_2048_mod_exp_2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64U); sp_2048_mont_reduce_64(r, m, mp); - mask = 0 - (sp_2048_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_64(r, m) >= 0); sp_2048_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -12948,7 +13206,11 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x180\n\t" "\n" - "L_sp_3072_add_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_add_96_word:\n\t" +#else + "L_sp_3072_add_96_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -12960,10 +13222,12 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_add_96_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_3072_add_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_3072_add_96_word\n\t" #else - "BNE.N L_sp_3072_add_96_word%=\n\t" + "BNE.N L_sp_3072_add_96_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -12995,7 +13259,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x180\n\t" "\n" - "L_sp_3072_sub_in_pkace_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sub_in_pkace_96_word:\n\t" +#else + "L_sp_3072_sub_in_pkace_96_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -13006,10 +13274,12 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_in_pkace_96_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_3072_sub_in_pkace_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_3072_sub_in_pkace_96_word\n\t" #else - "BNE.N L_sp_3072_sub_in_pkace_96_word%=\n\t" + "BNE.N L_sp_3072_sub_in_pkace_96_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -13049,13 +13319,21 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_mul_96_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_96_outer:\n\t" +#else + "L_sp_3072_mul_96_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x17c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_mul_96_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_96_inner:\n\t" +#else + "L_sp_3072_mul_96_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13071,15 +13349,19 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_96_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_mul_96_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_mul_96_inner_done\n\t" #else - "BGT.N L_sp_3072_mul_96_inner_done%=\n\t" + "BGT.N L_sp_3072_mul_96_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_96_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mul_96_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mul_96_inner\n\t" #else - "BLT.N L_sp_3072_mul_96_inner%=\n\t" + "BLT.N L_sp_3072_mul_96_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -13088,17 +13370,23 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_mul_96_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_96_inner_done:\n\t" +#else + "L_sp_3072_mul_96_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x2f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_mul_96_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_3072_mul_96_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_3072_mul_96_outer\n\t" #else - "BLE.N L_sp_3072_mul_96_outer%=\n\t" + "BLE.N L_sp_3072_mul_96_outer_%=\n\t" #endif "LDR lr, [%[a], #380]\n\t" "LDR r11, [%[b], #380]\n\t" @@ -13107,14 +13395,20 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_mul_96_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_96_store:\n\t" +#else + "L_sp_3072_mul_96_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_96_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_mul_96_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_mul_96_store\n\t" #else - "BGT.N L_sp_3072_mul_96_store%=\n\t" + "BGT.N L_sp_3072_mul_96_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -13147,13 +13441,21 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_sqr_96_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_96_outer:\n\t" +#else + "L_sp_3072_sqr_96_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x17c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_sqr_96_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_96_inner:\n\t" +#else + "L_sp_3072_sqr_96_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13166,15 +13468,19 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_96_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_sqr_96_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_sqr_96_inner_done\n\t" #else - "BGT.N L_sp_3072_sqr_96_inner_done%=\n\t" + "BGT.N L_sp_3072_sqr_96_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_sqr_96_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_sqr_96_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_sqr_96_inner\n\t" #else - "BLT.N L_sp_3072_sqr_96_inner%=\n\t" + "BLT.N L_sp_3072_sqr_96_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -13182,17 +13488,23 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_sqr_96_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_96_inner_done:\n\t" +#else + "L_sp_3072_sqr_96_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x2f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_sqr_96_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_3072_sqr_96_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_3072_sqr_96_outer\n\t" #else - "BLE.N L_sp_3072_sqr_96_outer%=\n\t" + "BLE.N L_sp_3072_sqr_96_outer_%=\n\t" #endif "LDR lr, [%[a], #380]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -13200,14 +13512,20 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_sqr_96_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_96_store:\n\t" +#else + "L_sp_3072_sqr_96_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_96_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_sqr_96_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_sqr_96_store\n\t" #else - "BGT.N L_sp_3072_sqr_96_store%=\n\t" + "BGT.N L_sp_3072_sqr_96_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -13257,7 +13575,11 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0xc0\n\t" "\n" - "L_sp_3072_add_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_add_48_word:\n\t" +#else + "L_sp_3072_add_48_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -13269,10 +13591,12 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_add_48_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_3072_add_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_3072_add_48_word\n\t" #else - "BNE.N L_sp_3072_add_48_word%=\n\t" + "BNE.N L_sp_3072_add_48_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -13304,7 +13628,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0xc0\n\t" "\n" - "L_sp_3072_sub_in_pkace_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sub_in_pkace_48_word:\n\t" +#else + "L_sp_3072_sub_in_pkace_48_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -13315,10 +13643,12 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_in_pkace_48_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_3072_sub_in_pkace_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_3072_sub_in_pkace_48_word\n\t" #else - "BNE.N L_sp_3072_sub_in_pkace_48_word%=\n\t" + "BNE.N L_sp_3072_sub_in_pkace_48_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -13358,13 +13688,21 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_mul_48_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_48_outer:\n\t" +#else + "L_sp_3072_mul_48_outer_%=:\n\t" +#endif "SUBS r3, r5, #0xbc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_mul_48_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_48_inner:\n\t" +#else + "L_sp_3072_mul_48_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13380,15 +13718,19 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_48_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_mul_48_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_mul_48_inner_done\n\t" #else - "BGT.N L_sp_3072_mul_48_inner_done%=\n\t" + "BGT.N L_sp_3072_mul_48_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_48_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mul_48_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mul_48_inner\n\t" #else - "BLT.N L_sp_3072_mul_48_inner%=\n\t" + "BLT.N L_sp_3072_mul_48_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -13397,17 +13739,23 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_mul_48_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_48_inner_done:\n\t" +#else + "L_sp_3072_mul_48_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x174\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_mul_48_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_3072_mul_48_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_3072_mul_48_outer\n\t" #else - "BLE.N L_sp_3072_mul_48_outer%=\n\t" + "BLE.N L_sp_3072_mul_48_outer_%=\n\t" #endif "LDR lr, [%[a], #188]\n\t" "LDR r11, [%[b], #188]\n\t" @@ -13416,14 +13764,20 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_mul_48_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_48_store:\n\t" +#else + "L_sp_3072_mul_48_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_mul_48_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_mul_48_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_mul_48_store\n\t" #else - "BGT.N L_sp_3072_mul_48_store%=\n\t" + "BGT.N L_sp_3072_mul_48_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -13456,13 +13810,21 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_3072_sqr_48_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_48_outer:\n\t" +#else + "L_sp_3072_sqr_48_outer_%=:\n\t" +#endif "SUBS r3, r5, #0xbc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_3072_sqr_48_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_48_inner:\n\t" +#else + "L_sp_3072_sqr_48_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -13475,15 +13837,19 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_48_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_sqr_48_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_sqr_48_inner_done\n\t" #else - "BGT.N L_sp_3072_sqr_48_inner_done%=\n\t" + "BGT.N L_sp_3072_sqr_48_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_sqr_48_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_sqr_48_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_sqr_48_inner\n\t" #else - "BLT.N L_sp_3072_sqr_48_inner%=\n\t" + "BLT.N L_sp_3072_sqr_48_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -13491,17 +13857,23 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_3072_sqr_48_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_48_inner_done:\n\t" +#else + "L_sp_3072_sqr_48_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x174\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_3072_sqr_48_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_3072_sqr_48_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_3072_sqr_48_outer\n\t" #else - "BLE.N L_sp_3072_sqr_48_outer%=\n\t" + "BLE.N L_sp_3072_sqr_48_outer_%=\n\t" #endif "LDR lr, [%[a], #188]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -13509,14 +13881,20 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_3072_sqr_48_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sqr_48_store:\n\t" +#else + "L_sp_3072_sqr_48_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_3072_sqr_48_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_3072_sqr_48_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_3072_sqr_48_store\n\t" #else - "BGT.N L_sp_3072_sqr_48_store%=\n\t" + "BGT.N L_sp_3072_sqr_48_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -13575,7 +13953,11 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_3072_mul_d_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_d_96_word:\n\t" +#else + "L_sp_3072_mul_d_96_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -13588,10 +13970,12 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_d_96_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mul_d_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mul_d_96_word\n\t" #else - "BLT.N L_sp_3072_mul_d_96_word%=\n\t" + "BLT.N L_sp_3072_mul_d_96_word_%=\n\t" #endif "STR r3, [%[r], #384]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -14149,7 +14533,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_3072_cond_sub_48_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_cond_sub_48_words:\n\t" +#else + "L_sp_3072_cond_sub_48_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -14159,10 +14547,12 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_sub_48_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_cond_sub_48_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_cond_sub_48_words\n\t" #else - "BLT.N L_sp_3072_cond_sub_48_words%=\n\t" + "BLT.N L_sp_3072_cond_sub_48_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -14401,7 +14791,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_3072_mont_reduce_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_word:\n\t" +#else + "L_sp_3072_mont_reduce_48_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -14791,10 +15185,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0xc0\n\t" -#ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_48_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_3072_mont_reduce_48_word\n\t" #else - "BLT.W L_sp_3072_mont_reduce_48_word%=\n\t" + "BLT.W L_sp_3072_mont_reduce_48_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -14833,7 +15229,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_word:\n\t" +#else + "L_sp_3072_mont_reduce_48_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -14841,7 +15241,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_mul:\n\t" +#else + "L_sp_3072_mont_reduce_48_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -14883,10 +15287,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_48_mul\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_mul%=\n\t" + "BLT.N L_sp_3072_mont_reduce_48_mul_%=\n\t" #endif "LDR r10, [%[a], #192]\n\t" "ADDS r4, r4, r3\n\t" @@ -14899,10 +15305,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_48_word\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_word%=\n\t" + "BLT.N L_sp_3072_mont_reduce_48_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -14944,7 +15352,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_3072_mont_reduce_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_word:\n\t" +#else + "L_sp_3072_mont_reduce_48_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -15191,10 +15603,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0xc0\n\t" -#ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_48_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_3072_mont_reduce_48_word\n\t" #else - "BLT.W L_sp_3072_mont_reduce_48_word%=\n\t" + "BLT.W L_sp_3072_mont_reduce_48_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -15236,7 +15650,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_word:\n\t" +#else + "L_sp_3072_mont_reduce_48_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -15244,7 +15662,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_48_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_48_mul:\n\t" +#else + "L_sp_3072_mont_reduce_48_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -15274,10 +15696,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_48_mul\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_mul%=\n\t" + "BLT.N L_sp_3072_mont_reduce_48_mul_%=\n\t" #endif "LDR r10, [%[a], #192]\n\t" "ADDS r4, r4, r3\n\t" @@ -15290,10 +15714,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_48_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_48_word\n\t" #else - "BLT.N L_sp_3072_mont_reduce_48_word%=\n\t" + "BLT.N L_sp_3072_mont_reduce_48_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -15364,7 +15790,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_3072_mul_d_48_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mul_d_48_word:\n\t" +#else + "L_sp_3072_mul_d_48_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -15377,10 +15807,12 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mul_d_48_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mul_d_48_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mul_d_48_word\n\t" #else - "BLT.N L_sp_3072_mul_d_48_word%=\n\t" + "BLT.N L_sp_3072_mul_d_48_word_%=\n\t" #endif "STR r3, [%[r], #192]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -15758,7 +16190,11 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_3072_word_48_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_3072_word_48_bit:\n\t" +#else + "L_div_3072_word_48_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -15768,7 +16204,13 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_3072_word_48_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_3072_word_48_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_3072_word_48_bit\n\t" +#else + "BPL.N L_div_3072_word_48_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -15820,7 +16262,11 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0xbc\n\t" "\n" - "L_sp_3072_cmp_48_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_cmp_48_words:\n\t" +#else + "L_sp_3072_cmp_48_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -15833,7 +16279,11 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_3072_cmp_48_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_3072_cmp_48_words\n\t" +#else + "bcs L_sp_3072_cmp_48_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #188]\n\t" @@ -16570,13 +17020,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -16739,13 +17188,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48U); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -16797,7 +17245,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_3072_cond_sub_96_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_cond_sub_96_words:\n\t" +#else + "L_sp_3072_cond_sub_96_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -16807,10 +17259,12 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_sub_96_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_cond_sub_96_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_cond_sub_96_words\n\t" #else - "BLT.N L_sp_3072_cond_sub_96_words%=\n\t" + "BLT.N L_sp_3072_cond_sub_96_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -17217,7 +17671,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_3072_mont_reduce_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_word:\n\t" +#else + "L_sp_3072_mont_reduce_96_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -17991,10 +18449,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x180\n\t" -#ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_96_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_3072_mont_reduce_96_word\n\t" #else - "BLT.W L_sp_3072_mont_reduce_96_word%=\n\t" + "BLT.W L_sp_3072_mont_reduce_96_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -18033,7 +18493,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_word:\n\t" +#else + "L_sp_3072_mont_reduce_96_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -18041,7 +18505,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_mul:\n\t" +#else + "L_sp_3072_mont_reduce_96_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -18083,10 +18551,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_96_mul\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_mul%=\n\t" + "BLT.N L_sp_3072_mont_reduce_96_mul_%=\n\t" #endif "LDR r10, [%[a], #384]\n\t" "ADDS r4, r4, r3\n\t" @@ -18099,10 +18569,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_96_word\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_word%=\n\t" + "BLT.N L_sp_3072_mont_reduce_96_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -18144,7 +18616,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_3072_mont_reduce_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_word:\n\t" +#else + "L_sp_3072_mont_reduce_96_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -18631,10 +19107,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x180\n\t" -#ifdef __GNUC__ - "BLT L_sp_3072_mont_reduce_96_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_3072_mont_reduce_96_word\n\t" #else - "BLT.W L_sp_3072_mont_reduce_96_word%=\n\t" + "BLT.W L_sp_3072_mont_reduce_96_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -18676,7 +19154,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_word:\n\t" +#else + "L_sp_3072_mont_reduce_96_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -18684,7 +19166,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_mont_reduce_96_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_mont_reduce_96_mul:\n\t" +#else + "L_sp_3072_mont_reduce_96_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -18714,10 +19200,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_96_mul\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_mul%=\n\t" + "BLT.N L_sp_3072_mont_reduce_96_mul_%=\n\t" #endif "LDR r10, [%[a], #384]\n\t" "ADDS r4, r4, r3\n\t" @@ -18730,10 +19218,12 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x180\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_mont_reduce_96_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_mont_reduce_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_mont_reduce_96_word\n\t" #else - "BLT.N L_sp_3072_mont_reduce_96_word%=\n\t" + "BLT.N L_sp_3072_mont_reduce_96_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -18799,7 +19289,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x180\n\t" "\n" - "L_sp_3072_sub_96_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_sub_96_word:\n\t" +#else + "L_sp_3072_sub_96_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -18810,10 +19304,12 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_3072_sub_96_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_3072_sub_96_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_3072_sub_96_word\n\t" #else - "BNE.N L_sp_3072_sub_96_word%=\n\t" + "BNE.N L_sp_3072_sub_96_word_%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -19122,7 +19618,11 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_3072_word_96_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_3072_word_96_bit:\n\t" +#else + "L_div_3072_word_96_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -19132,7 +19632,13 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_3072_word_96_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_3072_word_96_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_3072_word_96_bit\n\t" +#else + "BPL.N L_div_3072_word_96_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -19287,7 +19793,11 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x17c\n\t" "\n" - "L_sp_3072_cmp_96_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_cmp_96_words:\n\t" +#else + "L_sp_3072_cmp_96_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -19300,7 +19810,11 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_3072_cmp_96_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_3072_cmp_96_words\n\t" +#else + "bcs L_sp_3072_cmp_96_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #380]\n\t" @@ -20559,13 +21073,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20711,13 +21224,12 @@ static int sp_3072_mod_exp_96(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -20880,8 +21392,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -20915,7 +21426,11 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_3072_cond_add_48_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_3072_cond_add_48_words:\n\t" +#else + "L_sp_3072_cond_add_48_words_%=:\n\t" +#endif "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -20925,10 +21440,12 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r4]\n\t" "ADD r4, r4, #0x4\n\t" "CMP r4, #0xc0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_3072_cond_add_48_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_3072_cond_add_48_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_3072_cond_add_48_words\n\t" #else - "BLT.N L_sp_3072_cond_add_48_words%=\n\t" + "BLT.N L_sp_3072_cond_add_48_words_%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -22163,13 +22680,12 @@ static int sp_3072_mod_exp_2_96(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[96], 0, sizeof(sp_digit) * 96U); sp_3072_mont_reduce_96(r, m, mp); - mask = 0 - (sp_3072_cmp_96(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_96(r, m) >= 0); sp_3072_cond_sub_96(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -23059,7 +23575,11 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x200\n\t" "\n" - "L_sp_4096_add_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_add_128_word:\n\t" +#else + "L_sp_4096_add_128_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -23071,10 +23591,12 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_add_128_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_4096_add_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_4096_add_128_word\n\t" #else - "BNE.N L_sp_4096_add_128_word%=\n\t" + "BNE.N L_sp_4096_add_128_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -23106,7 +23628,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x200\n\t" "\n" - "L_sp_4096_sub_in_pkace_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sub_in_pkace_128_word:\n\t" +#else + "L_sp_4096_sub_in_pkace_128_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -23117,10 +23643,12 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_sub_in_pkace_128_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_4096_sub_in_pkace_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_4096_sub_in_pkace_128_word\n\t" #else - "BNE.N L_sp_4096_sub_in_pkace_128_word%=\n\t" + "BNE.N L_sp_4096_sub_in_pkace_128_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -23160,13 +23688,21 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_4096_mul_128_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mul_128_outer:\n\t" +#else + "L_sp_4096_mul_128_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x1fc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_4096_mul_128_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mul_128_inner:\n\t" +#else + "L_sp_4096_mul_128_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -23182,15 +23718,19 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_mul_128_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_4096_mul_128_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_4096_mul_128_inner_done\n\t" #else - "BGT.N L_sp_4096_mul_128_inner_done%=\n\t" + "BGT.N L_sp_4096_mul_128_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mul_128_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mul_128_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mul_128_inner\n\t" #else - "BLT.N L_sp_4096_mul_128_inner%=\n\t" + "BLT.N L_sp_4096_mul_128_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -23199,17 +23739,23 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_4096_mul_128_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mul_128_inner_done:\n\t" +#else + "L_sp_4096_mul_128_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x3f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_4096_mul_128_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_4096_mul_128_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_4096_mul_128_outer\n\t" #else - "BLE.N L_sp_4096_mul_128_outer%=\n\t" + "BLE.N L_sp_4096_mul_128_outer_%=\n\t" #endif "LDR lr, [%[a], #508]\n\t" "LDR r11, [%[b], #508]\n\t" @@ -23218,14 +23764,20 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_4096_mul_128_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mul_128_store:\n\t" +#else + "L_sp_4096_mul_128_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_mul_128_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_4096_mul_128_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_4096_mul_128_store\n\t" #else - "BGT.N L_sp_4096_mul_128_store%=\n\t" + "BGT.N L_sp_4096_mul_128_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -23258,13 +23810,21 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_4096_sqr_128_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sqr_128_outer:\n\t" +#else + "L_sp_4096_sqr_128_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x1fc\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_4096_sqr_128_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sqr_128_inner:\n\t" +#else + "L_sp_4096_sqr_128_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -23277,15 +23837,19 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_sqr_128_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_4096_sqr_128_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_4096_sqr_128_inner_done\n\t" #else - "BGT.N L_sp_4096_sqr_128_inner_done%=\n\t" + "BGT.N L_sp_4096_sqr_128_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_sqr_128_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_sqr_128_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_sqr_128_inner\n\t" #else - "BLT.N L_sp_4096_sqr_128_inner%=\n\t" + "BLT.N L_sp_4096_sqr_128_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -23293,17 +23857,23 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_4096_sqr_128_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sqr_128_inner_done:\n\t" +#else + "L_sp_4096_sqr_128_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x3f4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_4096_sqr_128_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_4096_sqr_128_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_4096_sqr_128_outer\n\t" #else - "BLE.N L_sp_4096_sqr_128_outer%=\n\t" + "BLE.N L_sp_4096_sqr_128_outer_%=\n\t" #endif "LDR lr, [%[a], #508]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -23311,14 +23881,20 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_4096_sqr_128_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sqr_128_store:\n\t" +#else + "L_sp_4096_sqr_128_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_4096_sqr_128_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_4096_sqr_128_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_4096_sqr_128_store\n\t" #else - "BGT.N L_sp_4096_sqr_128_store%=\n\t" + "BGT.N L_sp_4096_sqr_128_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -23375,7 +23951,11 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_4096_mul_d_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mul_d_128_word:\n\t" +#else + "L_sp_4096_mul_d_128_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -23388,10 +23968,12 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mul_d_128_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mul_d_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mul_d_128_word\n\t" #else - "BLT.N L_sp_4096_mul_d_128_word%=\n\t" + "BLT.N L_sp_4096_mul_d_128_word_%=\n\t" #endif "STR r3, [%[r], #512]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -24110,7 +24692,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_4096_cond_sub_128_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_cond_sub_128_words:\n\t" +#else + "L_sp_4096_cond_sub_128_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -24120,10 +24706,12 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_cond_sub_128_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_cond_sub_128_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_cond_sub_128_words\n\t" #else - "BLT.N L_sp_4096_cond_sub_128_words%=\n\t" + "BLT.N L_sp_4096_cond_sub_128_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -24642,7 +25230,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_4096_mont_reduce_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_word:\n\t" +#else + "L_sp_4096_mont_reduce_128_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -25672,10 +26264,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x200\n\t" -#ifdef __GNUC__ - "BLT L_sp_4096_mont_reduce_128_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_4096_mont_reduce_128_word\n\t" #else - "BLT.W L_sp_4096_mont_reduce_128_word%=\n\t" + "BLT.W L_sp_4096_mont_reduce_128_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -25714,7 +26308,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_word:\n\t" +#else + "L_sp_4096_mont_reduce_128_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -25722,7 +26320,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_mul:\n\t" +#else + "L_sp_4096_mont_reduce_128_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -25764,10 +26366,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mont_reduce_128_mul\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_mul%=\n\t" + "BLT.N L_sp_4096_mont_reduce_128_mul_%=\n\t" #endif "LDR r10, [%[a], #512]\n\t" "ADDS r4, r4, r3\n\t" @@ -25780,10 +26384,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mont_reduce_128_word\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_word%=\n\t" + "BLT.N L_sp_4096_mont_reduce_128_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -25825,7 +26431,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_4096_mont_reduce_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_word:\n\t" +#else + "L_sp_4096_mont_reduce_128_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -26472,10 +27082,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x200\n\t" -#ifdef __GNUC__ - "BLT L_sp_4096_mont_reduce_128_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_4096_mont_reduce_128_word\n\t" #else - "BLT.W L_sp_4096_mont_reduce_128_word%=\n\t" + "BLT.W L_sp_4096_mont_reduce_128_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -26517,7 +27129,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* ca = 0 */ "MOV r3, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_word:\n\t" +#else + "L_sp_4096_mont_reduce_128_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "LDR r10, [%[a]]\n\t" "MUL r8, %[mp], r10\n\t" @@ -26525,7 +27141,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV r12, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_mont_reduce_128_mul%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_mont_reduce_128_mul:\n\t" +#else + "L_sp_4096_mont_reduce_128_mul_%=:\n\t" +#endif /* a[i+j+0] += m[j+0] * mu */ "LDR r7, [%[m], r12]\n\t" "LDR r10, [%[a], r12]\n\t" @@ -26555,10 +27175,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, /* j += 1 */ "ADD r12, r12, #0x4\n\t" "CMP r12, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_mul%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_mul_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mont_reduce_128_mul\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_mul%=\n\t" + "BLT.N L_sp_4096_mont_reduce_128_mul_%=\n\t" #endif "LDR r10, [%[a], #512]\n\t" "ADDS r4, r4, r3\n\t" @@ -26571,10 +27193,12 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "ADD r9, r9, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r9, #0x200\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_mont_reduce_128_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_mont_reduce_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_mont_reduce_128_word\n\t" #else - "BLT.N L_sp_4096_mont_reduce_128_word%=\n\t" + "BLT.N L_sp_4096_mont_reduce_128_word_%=\n\t" #endif /* Loop Done */ "MOV %[mp], r3\n\t" @@ -26640,7 +27264,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x200\n\t" "\n" - "L_sp_4096_sub_128_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_sub_128_word:\n\t" +#else + "L_sp_4096_sub_128_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -26651,10 +27279,12 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_4096_sub_128_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_4096_sub_128_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_4096_sub_128_word\n\t" #else - "BNE.N L_sp_4096_sub_128_word%=\n\t" + "BNE.N L_sp_4096_sub_128_word_%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -27019,7 +27649,11 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_4096_word_128_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_4096_word_128_bit:\n\t" +#else + "L_div_4096_word_128_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -27029,7 +27663,13 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_4096_word_128_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_4096_word_128_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_4096_word_128_bit\n\t" +#else + "BPL.N L_div_4096_word_128_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -27184,7 +27824,11 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x1fc\n\t" "\n" - "L_sp_4096_cmp_128_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_cmp_128_words:\n\t" +#else + "L_sp_4096_cmp_128_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -27197,7 +27841,11 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_4096_cmp_128_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_4096_cmp_128_words\n\t" +#else + "bcs L_sp_4096_cmp_128_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #508]\n\t" @@ -28808,13 +29456,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -28960,13 +29607,12 @@ static int sp_4096_mod_exp_128(sp_digit* r, const sp_digit* a, const sp_digit* e XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -29129,8 +29775,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -29164,7 +29809,11 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_4096_cond_add_64_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_4096_cond_add_64_words:\n\t" +#else + "L_sp_4096_cond_add_64_words_%=:\n\t" +#endif "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -29174,10 +29823,12 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r4]\n\t" "ADD r4, r4, #0x4\n\t" "CMP r4, #0x100\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_4096_cond_add_64_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_4096_cond_add_64_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_4096_cond_add_64_words\n\t" #else - "BLT.N L_sp_4096_cond_add_64_words%=\n\t" + "BLT.N L_sp_4096_cond_add_64_words_%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -30660,13 +31311,12 @@ static int sp_4096_mod_exp_2_128(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[128], 0, sizeof(sp_digit) * 128U); sp_4096_mont_reduce_128(r, m, mp); - mask = 0 - (sp_4096_cmp_128(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_128(r, m) >= 0); sp_4096_cond_sub_128(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -30857,13 +31507,21 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_256_mul_8_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mul_8_outer:\n\t" +#else + "L_sp_256_mul_8_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x1c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_256_mul_8_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mul_8_inner:\n\t" +#else + "L_sp_256_mul_8_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -30879,15 +31537,19 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_mul_8_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_256_mul_8_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_256_mul_8_inner_done\n\t" #else - "BGT.N L_sp_256_mul_8_inner_done%=\n\t" + "BGT.N L_sp_256_mul_8_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_mul_8_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mul_8_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_256_mul_8_inner\n\t" #else - "BLT.N L_sp_256_mul_8_inner%=\n\t" + "BLT.N L_sp_256_mul_8_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -30896,17 +31558,23 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_256_mul_8_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mul_8_inner_done:\n\t" +#else + "L_sp_256_mul_8_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x34\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_256_mul_8_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_256_mul_8_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_256_mul_8_outer\n\t" #else - "BLE.N L_sp_256_mul_8_outer%=\n\t" + "BLE.N L_sp_256_mul_8_outer_%=\n\t" #endif "LDR lr, [%[a], #28]\n\t" "LDR r11, [%[b], #28]\n\t" @@ -30915,14 +31583,20 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_256_mul_8_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mul_8_store:\n\t" +#else + "L_sp_256_mul_8_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_mul_8_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_256_mul_8_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_256_mul_8_store\n\t" #else - "BGT.N L_sp_256_mul_8_store%=\n\t" + "BGT.N L_sp_256_mul_8_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -30931,7 +31605,7 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) } #else -#ifdef WOLFSSL_SP_NO_UMAAL +#ifdef WOLFSSL_ARM_ARCH_7M /* Multiply a and b into r. (r = a * b) * * r A single precision integer. @@ -31427,7 +32101,7 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_di ); } -#endif /* WOLFSSL_SP_NO_UMAAL */ +#endif /* WOLFSSL_ARM_ARCH_7M */ #endif /* WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Square a and put result in r. (r = a * a) @@ -31455,13 +32129,21 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_256_sqr_8_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sqr_8_outer:\n\t" +#else + "L_sp_256_sqr_8_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x1c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_256_sqr_8_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sqr_8_inner:\n\t" +#else + "L_sp_256_sqr_8_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -31474,15 +32156,19 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_sqr_8_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_256_sqr_8_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_256_sqr_8_inner_done\n\t" #else - "BGT.N L_sp_256_sqr_8_inner_done%=\n\t" + "BGT.N L_sp_256_sqr_8_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_sqr_8_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_sqr_8_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_256_sqr_8_inner\n\t" #else - "BLT.N L_sp_256_sqr_8_inner%=\n\t" + "BLT.N L_sp_256_sqr_8_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -31490,17 +32176,23 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_256_sqr_8_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sqr_8_inner_done:\n\t" +#else + "L_sp_256_sqr_8_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x34\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_256_sqr_8_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_256_sqr_8_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_256_sqr_8_outer\n\t" #else - "BLE.N L_sp_256_sqr_8_outer%=\n\t" + "BLE.N L_sp_256_sqr_8_outer_%=\n\t" #endif "LDR lr, [%[a], #28]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -31508,14 +32200,20 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_256_sqr_8_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sqr_8_store:\n\t" +#else + "L_sp_256_sqr_8_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_256_sqr_8_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_256_sqr_8_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_256_sqr_8_store\n\t" #else - "BGT.N L_sp_256_sqr_8_store%=\n\t" + "BGT.N L_sp_256_sqr_8_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -31524,7 +32222,7 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) } #else -#ifdef WOLFSSL_SP_NO_UMAAL +#ifdef WOLFSSL_ARM_ARCH_7M /* Square a and put result in r. (r = a * a) * * r A single precision integer. @@ -31890,7 +32588,7 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) ); } -#endif /* WOLFSSL_SP_NO_UMAAL */ +#endif /* WOLFSSL_ARM_ARCH_7M */ #endif /* WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Add b to a into r. (r = a + b) @@ -31915,7 +32613,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x20\n\t" "\n" - "L_sp_256_add_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_add_8_word:\n\t" +#else + "L_sp_256_add_8_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -31927,10 +32629,12 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_add_8_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_256_add_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_256_add_8_word\n\t" #else - "BNE.N L_sp_256_add_8_word%=\n\t" + "BNE.N L_sp_256_add_8_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -33938,7 +34642,11 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x1c\n\t" "\n" - "L_sp_256_cmp_8_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_cmp_8_words:\n\t" +#else + "L_sp_256_cmp_8_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -33951,7 +34659,11 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_256_cmp_8_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_256_cmp_8_words\n\t" +#else + "bcs L_sp_256_cmp_8_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #28]\n\t" @@ -34085,7 +34797,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_256_cond_sub_8_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_cond_sub_8_words:\n\t" +#else + "L_sp_256_cond_sub_8_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -34095,10 +34811,12 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_cond_sub_8_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_cond_sub_8_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_256_cond_sub_8_words\n\t" #else - "BLT.N L_sp_256_cond_sub_8_words%=\n\t" + "BLT.N L_sp_256_cond_sub_8_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -34199,7 +34917,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_256_mont_reduce_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mont_reduce_8_word:\n\t" +#else + "L_sp_256_mont_reduce_8_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -34269,10 +34991,12 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x20\n\t" -#ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_8_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mont_reduce_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_256_mont_reduce_8_word\n\t" #else - "BLT.W L_sp_256_mont_reduce_8_word%=\n\t" + "BLT.W L_sp_256_mont_reduce_8_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -34314,7 +35038,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_256_mont_reduce_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mont_reduce_8_word:\n\t" +#else + "L_sp_256_mont_reduce_8_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -34361,10 +35089,12 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x20\n\t" -#ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_8_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mont_reduce_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_256_mont_reduce_8_word\n\t" #else - "BLT.W L_sp_256_mont_reduce_8_word%=\n\t" + "BLT.W L_sp_256_mont_reduce_8_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -34573,7 +35303,11 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_256_mont_reduce_order_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mont_reduce_order_8_word:\n\t" +#else + "L_sp_256_mont_reduce_order_8_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -34643,10 +35377,12 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x20\n\t" -#ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_order_8_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mont_reduce_order_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_256_mont_reduce_order_8_word\n\t" #else - "BLT.W L_sp_256_mont_reduce_order_8_word%=\n\t" + "BLT.W L_sp_256_mont_reduce_order_8_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -34688,7 +35424,11 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_256_mont_reduce_order_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mont_reduce_order_8_word:\n\t" +#else + "L_sp_256_mont_reduce_order_8_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -34735,10 +35475,12 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x20\n\t" -#ifdef __GNUC__ - "BLT L_sp_256_mont_reduce_order_8_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mont_reduce_order_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_256_mont_reduce_order_8_word\n\t" #else - "BLT.W L_sp_256_mont_reduce_order_8_word%=\n\t" + "BLT.W L_sp_256_mont_reduce_order_8_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -34780,7 +35522,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_8(r->x, p256_mod); - sp_256_cond_sub_8(r->x, r->x, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->x, r->x, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->x); /* y /= z^3 */ @@ -34789,7 +35531,7 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_8(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_8(r->y, p256_mod); - sp_256_cond_sub_8(r->y, r->y, p256_mod, ~(n >> 31)); + sp_256_cond_sub_8(r->y, r->y, p256_mod, (sp_digit)~(n >> 31)); sp_256_norm_8(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -35431,8 +36173,8 @@ static void sp_256_proj_point_add_8(sp_point_256* r, sp_256_mont_sub_8(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -35449,7 +36191,7 @@ static void sp_256_proj_point_add_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -35623,8 +36365,8 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -35641,7 +36383,7 @@ static int sp_256_proj_point_add_8_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -35696,7 +36438,7 @@ static void sp_256_get_point_16_8(sp_point_256* r, const sp_point_256* table, r->z[6] = 0; r->z[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -35890,15 +36632,15 @@ static int sp_256_ecc_mulmod_fast_8(sp_point_256* r, const sp_point_256* g, cons #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_256)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_256)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -36094,8 +36836,8 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, sp_256_mont_sub_8(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -36112,7 +36854,7 @@ static void sp_256_proj_point_add_qz1_8(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -36202,8 +36944,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -36240,7 +36981,7 @@ static void sp_256_get_entry_16_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -36367,10 +37108,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -36626,8 +37365,7 @@ static int sp_256_gen_stripe_table_8(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -36664,7 +37402,7 @@ static void sp_256_get_entry_256_8(sp_point_256* r, r->y[6] = 0; r->y[7] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -36791,10 +37529,8 @@ static int sp_256_ecc_mulmod_stripe_8(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -37012,10 +37748,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -37092,10 +37826,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38562,10 +39294,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38640,10 +39370,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38732,6 +39460,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -38748,6 +39477,11 @@ static int sp_256_ecc_gen_k_8(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -38826,12 +39560,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -38989,10 +39720,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -39075,7 +39804,11 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x20\n\t" "\n" - "L_sp_256_sub_in_pkace_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sub_in_pkace_8_word:\n\t" +#else + "L_sp_256_sub_in_pkace_8_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -39086,10 +39819,12 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_sub_in_pkace_8_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_256_sub_in_pkace_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_256_sub_in_pkace_8_word\n\t" #else - "BNE.N L_sp_256_sub_in_pkace_8_word%=\n\t" + "BNE.N L_sp_256_sub_in_pkace_8_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -39168,7 +39903,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_256_mul_d_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_mul_d_8_word:\n\t" +#else + "L_sp_256_mul_d_8_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -39181,10 +39920,12 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_256_mul_d_8_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_256_mul_d_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_256_mul_d_8_word\n\t" #else - "BLT.N L_sp_256_mul_d_8_word%=\n\t" + "BLT.N L_sp_256_mul_d_8_word_%=\n\t" #endif "STR r3, [%[r], #32]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -39362,7 +40103,11 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_256_word_8_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_256_word_8_bit:\n\t" +#else + "L_div_256_word_8_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -39372,7 +40117,13 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_256_word_8_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_256_word_8_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_256_word_8_bit\n\t" +#else + "BPL.N L_div_256_word_8_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -40066,7 +40817,11 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x20\n\t" "\n" - "L_sp_256_sub_8_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_sub_8_word:\n\t" +#else + "L_sp_256_sub_8_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -40077,10 +40832,12 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_256_sub_8_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_256_sub_8_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_256_sub_8_word\n\t" #else - "BNE.N L_sp_256_sub_8_word%=\n\t" + "BNE.N L_sp_256_sub_8_word_%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -40199,10 +40956,12 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) "MOV r12, #0x0\n\t" "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_div2_mod_8_even%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_div2_mod_8_even_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_div2_mod_8_even\n\t" #else - "BEQ.N L_sp_256_div2_mod_8_even%=\n\t" + "BEQ.N L_sp_256_div2_mod_8_even_%=\n\t" #endif "LDM %[a]!, {r5, r6, r7}\n\t" "LDM %[m]!, {r8, r9, r10, r11}\n\t" @@ -40218,17 +40977,27 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) "ADCS r6, r6, r10\n\t" "ADCS r7, r7, r11\n\t" "ADC r3, r12, r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_div2_mod_8_div2%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_div2_mod_8_div2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_div2_mod_8_div2\n\t" #else - "B.N L_sp_256_div2_mod_8_div2%=\n\t" + "B.N L_sp_256_div2_mod_8_div2_%=\n\t" #endif "\n" - "L_sp_256_div2_mod_8_even%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_div2_mod_8_even:\n\t" +#else + "L_sp_256_div2_mod_8_even_%=:\n\t" +#endif "LDRD r4, r5, [%[a], #12]\n\t" "LDRD r6, r7, [%[a], #20]\n\t" "\n" - "L_sp_256_div2_mod_8_div2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_div2_mod_8_div2:\n\t" +#else + "L_sp_256_div2_mod_8_div2_%=:\n\t" +#endif "LSR r8, r4, #1\n\t" "AND r4, r4, #0x1\n\t" "LSR r9, r5, #1\n\t" @@ -40270,129 +41039,189 @@ static int sp_256_num_bits_8(const sp_digit* a) __asm__ __volatile__ ( "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_7%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_7_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_7\n\t" #else - "BEQ.N L_sp_256_num_bits_8_7%=\n\t" + "BEQ.N L_sp_256_num_bits_8_7_%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_7%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_7:\n\t" +#else + "L_sp_256_num_bits_8_7_%=:\n\t" +#endif "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_6%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_6_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_6\n\t" #else - "BEQ.N L_sp_256_num_bits_8_6%=\n\t" + "BEQ.N L_sp_256_num_bits_8_6_%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_6%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_6:\n\t" +#else + "L_sp_256_num_bits_8_6_%=:\n\t" +#endif "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_5%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_5_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_5\n\t" #else - "BEQ.N L_sp_256_num_bits_8_5%=\n\t" + "BEQ.N L_sp_256_num_bits_8_5_%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_5%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_5:\n\t" +#else + "L_sp_256_num_bits_8_5_%=:\n\t" +#endif "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_4%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_4_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_4\n\t" #else - "BEQ.N L_sp_256_num_bits_8_4%=\n\t" + "BEQ.N L_sp_256_num_bits_8_4_%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_4%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_4:\n\t" +#else + "L_sp_256_num_bits_8_4_%=:\n\t" +#endif "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_3%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_3_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_3\n\t" #else - "BEQ.N L_sp_256_num_bits_8_3%=\n\t" + "BEQ.N L_sp_256_num_bits_8_3_%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_3%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_3:\n\t" +#else + "L_sp_256_num_bits_8_3_%=:\n\t" +#endif "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_2%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_2\n\t" #else - "BEQ.N L_sp_256_num_bits_8_2%=\n\t" + "BEQ.N L_sp_256_num_bits_8_2_%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_2:\n\t" +#else + "L_sp_256_num_bits_8_2_%=:\n\t" +#endif "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_256_num_bits_8_1%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_256_num_bits_8_1_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_256_num_bits_8_1\n\t" #else - "BEQ.N L_sp_256_num_bits_8_1%=\n\t" + "BEQ.N L_sp_256_num_bits_8_1_%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_256_num_bits_8_9%=\n\t" +#if defined(__GNUC__) + "B L_sp_256_num_bits_8_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_256_num_bits_8_9\n\t" #else - "B.N L_sp_256_num_bits_8_9%=\n\t" + "B.N L_sp_256_num_bits_8_9_%=\n\t" #endif "\n" - "L_sp_256_num_bits_8_1%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_1:\n\t" +#else + "L_sp_256_num_bits_8_1_%=:\n\t" +#endif "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_256_num_bits_8_9%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_256_num_bits_8_9:\n\t" +#else + "L_sp_256_num_bits_8_9_%=:\n\t" +#endif "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -40684,10 +41513,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40894,8 +41721,7 @@ static int sp_256_ecc_is_point_8(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -40934,8 +41760,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41043,10 +41868,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -41125,10 +41948,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41193,10 +42014,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41257,10 +42076,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41326,8 +42143,7 @@ static int sp_256_mont_sqrt_8(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41392,8 +42208,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -41515,13 +42330,21 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_384_mul_12_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mul_12_outer:\n\t" +#else + "L_sp_384_mul_12_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x2c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_384_mul_12_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mul_12_inner:\n\t" +#else + "L_sp_384_mul_12_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -41537,15 +42360,19 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_mul_12_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_384_mul_12_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_384_mul_12_inner_done\n\t" #else - "BGT.N L_sp_384_mul_12_inner_done%=\n\t" + "BGT.N L_sp_384_mul_12_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_mul_12_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_mul_12_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_384_mul_12_inner\n\t" #else - "BLT.N L_sp_384_mul_12_inner%=\n\t" + "BLT.N L_sp_384_mul_12_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -41554,17 +42381,23 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_384_mul_12_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mul_12_inner_done:\n\t" +#else + "L_sp_384_mul_12_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x54\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_384_mul_12_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_384_mul_12_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_384_mul_12_outer\n\t" #else - "BLE.N L_sp_384_mul_12_outer%=\n\t" + "BLE.N L_sp_384_mul_12_outer_%=\n\t" #endif "LDR lr, [%[a], #44]\n\t" "LDR r11, [%[b], #44]\n\t" @@ -41573,14 +42406,20 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_384_mul_12_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mul_12_store:\n\t" +#else + "L_sp_384_mul_12_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_mul_12_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_384_mul_12_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_384_mul_12_store\n\t" #else - "BGT.N L_sp_384_mul_12_store%=\n\t" + "BGT.N L_sp_384_mul_12_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -42643,13 +43482,21 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_384_sqr_12_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sqr_12_outer:\n\t" +#else + "L_sp_384_sqr_12_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x2c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_384_sqr_12_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sqr_12_inner:\n\t" +#else + "L_sp_384_sqr_12_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -42662,15 +43509,19 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_sqr_12_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_384_sqr_12_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_384_sqr_12_inner_done\n\t" #else - "BGT.N L_sp_384_sqr_12_inner_done%=\n\t" + "BGT.N L_sp_384_sqr_12_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_sqr_12_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_sqr_12_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_384_sqr_12_inner\n\t" #else - "BLT.N L_sp_384_sqr_12_inner%=\n\t" + "BLT.N L_sp_384_sqr_12_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -42678,17 +43529,23 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_384_sqr_12_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sqr_12_inner_done:\n\t" +#else + "L_sp_384_sqr_12_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x54\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_384_sqr_12_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_384_sqr_12_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_384_sqr_12_outer\n\t" #else - "BLE.N L_sp_384_sqr_12_outer%=\n\t" + "BLE.N L_sp_384_sqr_12_outer_%=\n\t" #endif "LDR lr, [%[a], #44]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -42696,14 +43553,20 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_384_sqr_12_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sqr_12_store:\n\t" +#else + "L_sp_384_sqr_12_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_384_sqr_12_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_384_sqr_12_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_384_sqr_12_store\n\t" #else - "BGT.N L_sp_384_sqr_12_store%=\n\t" + "BGT.N L_sp_384_sqr_12_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -43436,7 +44299,11 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x30\n\t" "\n" - "L_sp_384_add_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_add_12_word:\n\t" +#else + "L_sp_384_add_12_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -43448,10 +44315,12 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_add_12_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_384_add_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_384_add_12_word\n\t" #else - "BNE.N L_sp_384_add_12_word%=\n\t" + "BNE.N L_sp_384_add_12_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -43592,23 +44461,22 @@ static int sp_384_mod_mul_norm_12(sp_digit* r, const sp_digit* a, const sp_digit t[10] += t[9] >> 32; t[9] &= 0xffffffff; t[11] += t[10] >> 32; t[10] &= 0xffffffff; - r[0] = t[0]; - r[1] = t[1]; - r[2] = t[2]; - r[3] = t[3]; - r[4] = t[4]; - r[5] = t[5]; - r[6] = t[6]; - r[7] = t[7]; - r[8] = t[8]; - r[9] = t[9]; - r[10] = t[10]; - r[11] = t[11]; + r[0] = (sp_digit)t[0]; + r[1] = (sp_digit)t[1]; + r[2] = (sp_digit)t[2]; + r[3] = (sp_digit)t[3]; + r[4] = (sp_digit)t[4]; + r[5] = (sp_digit)t[5]; + r[6] = (sp_digit)t[6]; + r[7] = (sp_digit)t[7]; + r[8] = (sp_digit)t[8]; + r[9] = (sp_digit)t[9]; + r[10] = (sp_digit)t[10]; + r[11] = (sp_digit)t[11]; } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -43836,7 +44704,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_384_cond_sub_12_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_cond_sub_12_words:\n\t" +#else + "L_sp_384_cond_sub_12_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -43846,10 +44718,12 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x30\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_cond_sub_12_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_cond_sub_12_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_384_cond_sub_12_words\n\t" #else - "BLT.N L_sp_384_cond_sub_12_words%=\n\t" + "BLT.N L_sp_384_cond_sub_12_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -43963,7 +44837,11 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_384_mont_reduce_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mont_reduce_12_word:\n\t" +#else + "L_sp_384_mont_reduce_12_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -44065,10 +44943,12 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x30\n\t" -#ifdef __GNUC__ - "BLT L_sp_384_mont_reduce_12_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_mont_reduce_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_384_mont_reduce_12_word\n\t" #else - "BLT.W L_sp_384_mont_reduce_12_word%=\n\t" + "BLT.W L_sp_384_mont_reduce_12_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -44110,7 +44990,11 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_384_mont_reduce_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mont_reduce_12_word:\n\t" +#else + "L_sp_384_mont_reduce_12_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -44177,10 +45061,12 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x30\n\t" -#ifdef __GNUC__ - "BLT L_sp_384_mont_reduce_12_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_mont_reduce_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_384_mont_reduce_12_word\n\t" #else - "BLT.W L_sp_384_mont_reduce_12_word%=\n\t" + "BLT.W L_sp_384_mont_reduce_12_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -44365,7 +45251,11 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x2c\n\t" "\n" - "L_sp_384_cmp_12_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_cmp_12_words:\n\t" +#else + "L_sp_384_cmp_12_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -44378,7 +45268,11 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_384_cmp_12_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_384_cmp_12_words\n\t" +#else + "bcs L_sp_384_cmp_12_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #44]\n\t" @@ -44553,7 +45447,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_12(r->x, p384_mod); - sp_384_cond_sub_12(r->x, r->x, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->x, r->x, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->x); /* y /= z^3 */ @@ -44562,7 +45456,7 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_12(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_12(r->y, p384_mod); - sp_384_cond_sub_12(r->y, r->y, p384_mod, ~(n >> 31)); + sp_384_cond_sub_12(r->y, r->y, p384_mod, (sp_digit)~(n >> 31)); sp_384_norm_12(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -44668,7 +45562,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x30\n\t" "\n" - "L_sp_384_sub_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sub_12_word:\n\t" +#else + "L_sp_384_sub_12_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -44679,10 +45577,12 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_sub_12_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_384_sub_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_384_sub_12_word\n\t" #else - "BNE.N L_sp_384_sub_12_word%=\n\t" + "BNE.N L_sp_384_sub_12_word_%=\n\t" #endif "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -44769,7 +45669,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_384_cond_add_12_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_cond_add_12_words:\n\t" +#else + "L_sp_384_cond_add_12_words_%=:\n\t" +#endif "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -44779,10 +45683,12 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "STR r6, [%[r], r4]\n\t" "ADD r4, r4, #0x4\n\t" "CMP r4, #0x30\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_cond_add_12_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_cond_add_12_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_384_cond_add_12_words\n\t" #else - "BLT.N L_sp_384_cond_add_12_words%=\n\t" + "BLT.N L_sp_384_cond_add_12_words_%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -45268,8 +46174,8 @@ static void sp_384_proj_point_add_12(sp_point_384* r, sp_384_mont_sub_12(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45286,7 +46192,7 @@ static void sp_384_proj_point_add_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -45460,8 +46366,8 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45478,7 +46384,7 @@ static int sp_384_proj_point_add_12_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -45545,7 +46451,7 @@ static void sp_384_get_point_16_12(sp_point_384* r, const sp_point_384* table, r->z[10] = 0; r->z[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -45751,15 +46657,15 @@ static int sp_384_ecc_mulmod_fast_12(sp_point_384* r, const sp_point_384* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_384)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_384)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -45955,8 +46861,8 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, sp_384_mont_sub_12(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -45973,7 +46879,7 @@ static void sp_384_proj_point_add_qz1_12(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -46063,8 +46969,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46109,7 +47014,7 @@ static void sp_384_get_entry_16_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -46244,10 +47149,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46503,8 +47406,7 @@ static int sp_384_gen_stripe_table_12(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46549,7 +47451,7 @@ static void sp_384_get_entry_256_12(sp_point_384* r, r->y[10] = 0; r->y[11] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -46684,10 +47586,8 @@ static int sp_384_ecc_mulmod_stripe_12(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46905,10 +47805,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -46985,10 +47883,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48455,10 +49351,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48533,10 +49427,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48631,6 +49523,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -48647,6 +49540,11 @@ static int sp_384_ecc_gen_k_12(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -48725,12 +49623,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48888,10 +49783,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -48974,7 +49867,11 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x30\n\t" "\n" - "L_sp_384_sub_in_pkace_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_sub_in_pkace_12_word:\n\t" +#else + "L_sp_384_sub_in_pkace_12_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -48985,10 +49882,12 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_384_sub_in_pkace_12_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_384_sub_in_pkace_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_384_sub_in_pkace_12_word\n\t" #else - "BNE.N L_sp_384_sub_in_pkace_12_word%=\n\t" + "BNE.N L_sp_384_sub_in_pkace_12_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -49074,7 +49973,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_384_mul_d_12_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_mul_d_12_word:\n\t" +#else + "L_sp_384_mul_d_12_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -49087,10 +49990,12 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x30\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_384_mul_d_12_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_384_mul_d_12_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_384_mul_d_12_word\n\t" #else - "BLT.N L_sp_384_mul_d_12_word%=\n\t" + "BLT.N L_sp_384_mul_d_12_word_%=\n\t" #endif "STR r3, [%[r], #48]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -49288,7 +50193,11 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_384_word_12_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_384_word_12_bit:\n\t" +#else + "L_div_384_word_12_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -49298,7 +50207,13 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_384_word_12_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_384_word_12_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_384_word_12_bit\n\t" +#else + "BPL.N L_div_384_word_12_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -49961,10 +50876,12 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m __asm__ __volatile__ ( "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_div2_mod_12_even%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_div2_mod_12_even_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_div2_mod_12_even\n\t" #else - "BEQ.N L_sp_384_div2_mod_12_even%=\n\t" + "BEQ.N L_sp_384_div2_mod_12_even_%=\n\t" #endif "MOV r12, #0x0\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" @@ -49989,13 +50906,19 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "ADCS r7, r7, r11\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "ADC r3, r12, r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_div2_mod_12_div2%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_div2_mod_12_div2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_div2_mod_12_div2\n\t" #else - "B.N L_sp_384_div2_mod_12_div2%=\n\t" + "B.N L_sp_384_div2_mod_12_div2_%=\n\t" #endif "\n" - "L_sp_384_div2_mod_12_even%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_div2_mod_12_even:\n\t" +#else + "L_sp_384_div2_mod_12_even_%=:\n\t" +#endif "LDM %[a]!, {r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" @@ -50003,7 +50926,11 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4, r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "\n" - "L_sp_384_div2_mod_12_div2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_div2_mod_12_div2:\n\t" +#else + "L_sp_384_div2_mod_12_div2_%=:\n\t" +#endif "SUB %[r], %[r], #0x30\n\t" "LDRD r8, r9, [%[r]]\n\t" "LSR r8, r8, #1\n\t" @@ -50071,197 +50998,289 @@ static int sp_384_num_bits_12(const sp_digit* a) __asm__ __volatile__ ( "LDR r1, [%[a], #44]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_11%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_11_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_11\n\t" #else - "BEQ.N L_sp_384_num_bits_12_11%=\n\t" + "BEQ.N L_sp_384_num_bits_12_11_%=\n\t" #endif "MOV r2, #0x180\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_11%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_11:\n\t" +#else + "L_sp_384_num_bits_12_11_%=:\n\t" +#endif "LDR r1, [%[a], #40]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_10%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_10_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_10\n\t" #else - "BEQ.N L_sp_384_num_bits_12_10%=\n\t" + "BEQ.N L_sp_384_num_bits_12_10_%=\n\t" #endif "MOV r2, #0x160\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_10%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_10:\n\t" +#else + "L_sp_384_num_bits_12_10_%=:\n\t" +#endif "LDR r1, [%[a], #36]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_9%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_9\n\t" #else - "BEQ.N L_sp_384_num_bits_12_9%=\n\t" + "BEQ.N L_sp_384_num_bits_12_9_%=\n\t" #endif "MOV r2, #0x140\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_9%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_9:\n\t" +#else + "L_sp_384_num_bits_12_9_%=:\n\t" +#endif "LDR r1, [%[a], #32]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_8%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_8_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_8\n\t" #else - "BEQ.N L_sp_384_num_bits_12_8%=\n\t" + "BEQ.N L_sp_384_num_bits_12_8_%=\n\t" #endif "MOV r2, #0x120\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_8%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_8:\n\t" +#else + "L_sp_384_num_bits_12_8_%=:\n\t" +#endif "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_7%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_7_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_7\n\t" #else - "BEQ.N L_sp_384_num_bits_12_7%=\n\t" + "BEQ.N L_sp_384_num_bits_12_7_%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_7%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_7:\n\t" +#else + "L_sp_384_num_bits_12_7_%=:\n\t" +#endif "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_6%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_6_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_6\n\t" #else - "BEQ.N L_sp_384_num_bits_12_6%=\n\t" + "BEQ.N L_sp_384_num_bits_12_6_%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_6%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_6:\n\t" +#else + "L_sp_384_num_bits_12_6_%=:\n\t" +#endif "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_5%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_5_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_5\n\t" #else - "BEQ.N L_sp_384_num_bits_12_5%=\n\t" + "BEQ.N L_sp_384_num_bits_12_5_%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_5%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_5:\n\t" +#else + "L_sp_384_num_bits_12_5_%=:\n\t" +#endif "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_4%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_4_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_4\n\t" #else - "BEQ.N L_sp_384_num_bits_12_4%=\n\t" + "BEQ.N L_sp_384_num_bits_12_4_%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_4%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_4:\n\t" +#else + "L_sp_384_num_bits_12_4_%=:\n\t" +#endif "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_3%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_3_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_3\n\t" #else - "BEQ.N L_sp_384_num_bits_12_3%=\n\t" + "BEQ.N L_sp_384_num_bits_12_3_%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_3%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_3:\n\t" +#else + "L_sp_384_num_bits_12_3_%=:\n\t" +#endif "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_2%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_2\n\t" #else - "BEQ.N L_sp_384_num_bits_12_2%=\n\t" + "BEQ.N L_sp_384_num_bits_12_2_%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_2:\n\t" +#else + "L_sp_384_num_bits_12_2_%=:\n\t" +#endif "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_384_num_bits_12_1%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_384_num_bits_12_1_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_384_num_bits_12_1\n\t" #else - "BEQ.N L_sp_384_num_bits_12_1%=\n\t" + "BEQ.N L_sp_384_num_bits_12_1_%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_384_num_bits_12_13%=\n\t" +#if defined(__GNUC__) + "B L_sp_384_num_bits_12_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_384_num_bits_12_13\n\t" #else - "B.N L_sp_384_num_bits_12_13%=\n\t" + "B.N L_sp_384_num_bits_12_13_%=\n\t" #endif "\n" - "L_sp_384_num_bits_12_1%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_1:\n\t" +#else + "L_sp_384_num_bits_12_1_%=:\n\t" +#endif "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_384_num_bits_12_13%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_384_num_bits_12_13:\n\t" +#else + "L_sp_384_num_bits_12_13_%=:\n\t" +#endif "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -50557,10 +51576,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -50767,8 +51784,7 @@ static int sp_384_ecc_is_point_12(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -50807,8 +51823,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -50916,10 +51931,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -50998,10 +52011,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51066,10 +52077,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51130,10 +52139,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51229,8 +52236,7 @@ static int sp_384_mont_sqrt_12(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51295,8 +52301,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51430,13 +52435,21 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_521_mul_17_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mul_17_outer:\n\t" +#else + "L_sp_521_mul_17_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x40\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_521_mul_17_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mul_17_inner:\n\t" +#else + "L_sp_521_mul_17_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -51452,15 +52465,19 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_mul_17_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_521_mul_17_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_521_mul_17_inner_done\n\t" #else - "BGT.N L_sp_521_mul_17_inner_done%=\n\t" + "BGT.N L_sp_521_mul_17_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_mul_17_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_mul_17_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_521_mul_17_inner\n\t" #else - "BLT.N L_sp_521_mul_17_inner%=\n\t" + "BLT.N L_sp_521_mul_17_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -51469,17 +52486,23 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_521_mul_17_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mul_17_inner_done:\n\t" +#else + "L_sp_521_mul_17_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x7c\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_521_mul_17_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_521_mul_17_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_521_mul_17_outer\n\t" #else - "BLE.N L_sp_521_mul_17_outer%=\n\t" + "BLE.N L_sp_521_mul_17_outer_%=\n\t" #endif "LDR lr, [%[a], #64]\n\t" "LDR r11, [%[b], #64]\n\t" @@ -51491,14 +52514,20 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r6, r7}\n\t" "SUB r5, r5, #0x8\n\t" "\n" - "L_sp_521_mul_17_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mul_17_store:\n\t" +#else + "L_sp_521_mul_17_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_mul_17_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_521_mul_17_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_521_mul_17_store\n\t" #else - "BGT.N L_sp_521_mul_17_store%=\n\t" + "BGT.N L_sp_521_mul_17_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -53575,13 +54604,21 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_521_sqr_17_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sqr_17_outer:\n\t" +#else + "L_sp_521_sqr_17_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x40\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_521_sqr_17_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sqr_17_inner:\n\t" +#else + "L_sp_521_sqr_17_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -53594,15 +54631,19 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_sqr_17_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_521_sqr_17_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_521_sqr_17_inner_done\n\t" #else - "BGT.N L_sp_521_sqr_17_inner_done%=\n\t" + "BGT.N L_sp_521_sqr_17_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_sqr_17_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_sqr_17_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_521_sqr_17_inner\n\t" #else - "BLT.N L_sp_521_sqr_17_inner%=\n\t" + "BLT.N L_sp_521_sqr_17_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -53610,17 +54651,23 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_521_sqr_17_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sqr_17_inner_done:\n\t" +#else + "L_sp_521_sqr_17_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x7c\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_521_sqr_17_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_521_sqr_17_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_521_sqr_17_outer\n\t" #else - "BLE.N L_sp_521_sqr_17_outer%=\n\t" + "BLE.N L_sp_521_sqr_17_outer_%=\n\t" #endif "LDR lr, [%[a], #64]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -53631,14 +54678,20 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "STM %[r]!, {r6, r7}\n\t" "SUB r5, r5, #0x8\n\t" "\n" - "L_sp_521_sqr_17_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sqr_17_store:\n\t" +#else + "L_sp_521_sqr_17_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_521_sqr_17_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_521_sqr_17_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_521_sqr_17_store\n\t" #else - "BGT.N L_sp_521_sqr_17_store%=\n\t" + "BGT.N L_sp_521_sqr_17_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -54955,7 +56008,11 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x40\n\t" "\n" - "L_sp_521_add_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_add_17_word:\n\t" +#else + "L_sp_521_add_17_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -54967,10 +56024,12 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_add_17_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_521_add_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_521_add_17_word\n\t" #else - "BNE.N L_sp_521_add_17_word%=\n\t" + "BNE.N L_sp_521_add_17_word_%=\n\t" #endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a], {r4}\n\t" @@ -55288,7 +56347,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_521_cond_sub_17_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_cond_sub_17_words:\n\t" +#else + "L_sp_521_cond_sub_17_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -55298,10 +56361,12 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x44\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_cond_sub_17_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_cond_sub_17_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_521_cond_sub_17_words\n\t" #else - "BLT.N L_sp_521_cond_sub_17_words%=\n\t" + "BLT.N L_sp_521_cond_sub_17_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -55568,19 +56633,29 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_521_mont_reduce_order_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mont_reduce_order_17_word:\n\t" +#else + "L_sp_521_mont_reduce_order_17_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" "CMP r11, #0x40\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_mont_reduce_order_17_nomask%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_521_mont_reduce_order_17_nomask_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_521_mont_reduce_order_17_nomask\n\t" #else - "BNE.N L_sp_521_mont_reduce_order_17_nomask%=\n\t" + "BNE.N L_sp_521_mont_reduce_order_17_nomask_%=\n\t" #endif "MOV r9, #0x1ff\n\t" "AND r10, r10, r9\n\t" "\n" - "L_sp_521_mont_reduce_order_17_nomask%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mont_reduce_order_17_nomask:\n\t" +#else + "L_sp_521_mont_reduce_order_17_nomask_%=:\n\t" +#endif /* a[i+0] += m[0] * mu */ "MOV r7, #0x0\n\t" "UMLAL r4, r7, r10, lr\n\t" @@ -55721,10 +56796,12 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x44\n\t" -#ifdef __GNUC__ - "BLT L_sp_521_mont_reduce_order_17_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_mont_reduce_order_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_521_mont_reduce_order_17_word\n\t" #else - "BLT.W L_sp_521_mont_reduce_order_17_word%=\n\t" + "BLT.W L_sp_521_mont_reduce_order_17_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -55836,19 +56913,29 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_521_mont_reduce_order_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mont_reduce_order_17_word:\n\t" +#else + "L_sp_521_mont_reduce_order_17_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" "CMP r4, #0x40\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_mont_reduce_order_17_nomask%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_521_mont_reduce_order_17_nomask_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_521_mont_reduce_order_17_nomask\n\t" #else - "BNE.N L_sp_521_mont_reduce_order_17_nomask%=\n\t" + "BNE.N L_sp_521_mont_reduce_order_17_nomask_%=\n\t" #endif "MOV r12, #0x1ff\n\t" "AND lr, lr, r12\n\t" "\n" - "L_sp_521_mont_reduce_order_17_nomask%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mont_reduce_order_17_nomask:\n\t" +#else + "L_sp_521_mont_reduce_order_17_nomask_%=:\n\t" +#endif /* a[i+0] += m[0] * mu */ "LDR r12, [%[m]]\n\t" "MOV r3, #0x0\n\t" @@ -55939,10 +57026,12 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x44\n\t" -#ifdef __GNUC__ - "BLT L_sp_521_mont_reduce_order_17_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_mont_reduce_order_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_521_mont_reduce_order_17_word\n\t" #else - "BLT.W L_sp_521_mont_reduce_order_17_word%=\n\t" + "BLT.W L_sp_521_mont_reduce_order_17_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -56194,7 +57283,11 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x40\n\t" "\n" - "L_sp_521_cmp_17_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_cmp_17_words:\n\t" +#else + "L_sp_521_cmp_17_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -56207,7 +57300,11 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_521_cmp_17_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_521_cmp_17_words\n\t" +#else + "bcs L_sp_521_cmp_17_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #64]\n\t" @@ -56437,7 +57534,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_17(r->x, p521_mod); - sp_521_cond_sub_17(r->x, r->x, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->x, r->x, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->x); /* y /= z^3 */ @@ -56446,7 +57543,7 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_17(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_17(r->y, p521_mod); - sp_521_cond_sub_17(r->y, r->y, p521_mod, ~(n >> 31)); + sp_521_cond_sub_17(r->y, r->y, p521_mod, (sp_digit)~(n >> 31)); sp_521_norm_17(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -57212,8 +58309,8 @@ static void sp_521_proj_point_add_17(sp_point_521* r, sp_521_mont_sub_17(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -57230,7 +58327,7 @@ static void sp_521_proj_point_add_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -57404,8 +58501,8 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -57422,7 +58519,7 @@ static int sp_521_proj_point_add_17_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -57504,7 +58601,7 @@ static void sp_521_get_point_16_17(sp_point_521* r, const sp_point_521* table, r->z[15] = 0; r->z[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -57729,15 +58826,15 @@ static int sp_521_ecc_mulmod_fast_17(sp_point_521* r, const sp_point_521* g, con #endif } #ifndef WC_NO_CACHE_RESISTANT - #ifdef WOLFSSL_SP_SMALL_STACK +#ifdef WOLFSSL_SP_SMALL_STACK if (p != NULL) +#endif + { + ForceZero(p, sizeof(sp_point_521)); + #ifdef WOLFSSL_SP_SMALL_STACK + XFREE(p, heap, DYNAMIC_TYPE_ECC); #endif - { - ForceZero(p, sizeof(sp_point_521)); - #ifdef WOLFSSL_SP_SMALL_STACK - XFREE(p, heap, DYNAMIC_TYPE_ECC); - #endif - } + } #endif /* !WC_NO_CACHE_RESISTANT */ #ifdef WOLFSSL_SP_SMALL_STACK if (t != NULL) @@ -57933,8 +59030,8 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, sp_521_mont_sub_17(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -57951,7 +59048,7 @@ static void sp_521_proj_point_add_qz1_17(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -58041,8 +59138,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -58097,7 +59193,7 @@ static void sp_521_get_entry_16_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 16; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -58242,10 +59338,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -58501,8 +59595,7 @@ static int sp_521_gen_stripe_table_17(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -58557,7 +59650,7 @@ static void sp_521_get_entry_256_17(sp_point_521* r, r->y[15] = 0; r->y[16] = 0; for (i = 1; i < 256; i++) { - mask = 0 - (i == idx); + mask = (sp_digit)0 - (i == idx); r->x[0] |= mask & table[i].x[0]; r->x[1] |= mask & table[i].x[1]; r->x[2] |= mask & table[i].x[2]; @@ -58702,10 +59795,8 @@ static int sp_521_ecc_mulmod_stripe_17(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -58923,10 +60014,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -59003,10 +60092,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -61017,10 +62104,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -61095,10 +62180,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -61202,6 +62285,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -61219,6 +62303,11 @@ static int sp_521_ecc_gen_k_17(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -61297,12 +62386,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -61462,10 +62548,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -61995,7 +63079,11 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x40\n\t" "\n" - "L_sp_521_sub_in_pkace_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sub_in_pkace_17_word:\n\t" +#else + "L_sp_521_sub_in_pkace_17_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -62006,10 +63094,12 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_sub_in_pkace_17_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_521_sub_in_pkace_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_521_sub_in_pkace_17_word\n\t" #else - "BNE.N L_sp_521_sub_in_pkace_17_word%=\n\t" + "BNE.N L_sp_521_sub_in_pkace_17_word_%=\n\t" #endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2}\n\t" @@ -62111,7 +63201,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_521_mul_d_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_mul_d_17_word:\n\t" +#else + "L_sp_521_mul_d_17_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -62124,10 +63218,12 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x44\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_521_mul_d_17_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_521_mul_d_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_521_mul_d_17_word\n\t" #else - "BLT.N L_sp_521_mul_d_17_word%=\n\t" + "BLT.N L_sp_521_mul_d_17_word_%=\n\t" #endif "STR r3, [%[r], #68]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -62350,7 +63446,11 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_521_word_17_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_521_word_17_bit:\n\t" +#else + "L_div_521_word_17_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -62360,7 +63460,13 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_521_word_17_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_521_word_17_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_521_word_17_bit\n\t" +#else + "BPL.N L_div_521_word_17_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -63055,7 +64161,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r11, #0x0\n\t" "ADD r12, %[a], #0x40\n\t" "\n" - "L_sp_521_sub_17_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_sub_17_word:\n\t" +#else + "L_sp_521_sub_17_word_%=:\n\t" +#endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3, r4, r5, r6}\n\t" "LDM %[b]!, {r7, r8, r9, r10}\n\t" @@ -63066,10 +64176,12 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" "SBC r11, r3, r3\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_521_sub_17_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_521_sub_17_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_521_sub_17_word\n\t" #else - "BNE.N L_sp_521_sub_17_word%=\n\t" + "BNE.N L_sp_521_sub_17_word_%=\n\t" #endif "RSBS r11, r11, #0x0\n\t" "LDM %[a]!, {r3}\n\t" @@ -63166,10 +64278,12 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m __asm__ __volatile__ ( "LDM %[a]!, {r4}\n\t" "ANDS r3, r4, #0x1\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_div2_mod_17_even%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_div2_mod_17_even_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_div2_mod_17_even\n\t" #else - "BEQ.N L_sp_521_div2_mod_17_even%=\n\t" + "BEQ.N L_sp_521_div2_mod_17_even_%=\n\t" #endif "MOV r12, #0x0\n\t" "LDM %[a]!, {r5, r6, r7}\n\t" @@ -63205,13 +64319,19 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "ADCS r4, r4, r8\n\t" "STM %[r]!, {r4}\n\t" "ADC r3, r12, r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_div2_mod_17_div2%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_div2_mod_17_div2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_div2_mod_17_div2\n\t" #else - "B.N L_sp_521_div2_mod_17_div2%=\n\t" + "B.N L_sp_521_div2_mod_17_div2_%=\n\t" #endif "\n" - "L_sp_521_div2_mod_17_even%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_div2_mod_17_even:\n\t" +#else + "L_sp_521_div2_mod_17_even_%=:\n\t" +#endif "LDM %[a]!, {r5, r6, r7}\n\t" "STM %[r]!, {r4, r5, r6, r7}\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" @@ -63223,7 +64343,11 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "LDM %[a]!, {r4}\n\t" "STM %[r]!, {r4}\n\t" "\n" - "L_sp_521_div2_mod_17_div2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_div2_mod_17_div2:\n\t" +#else + "L_sp_521_div2_mod_17_div2_%=:\n\t" +#endif "SUB %[r], %[r], #0x44\n\t" "LDRD r8, r9, [%[r]]\n\t" "LSR r8, r8, #1\n\t" @@ -63311,282 +64435,414 @@ static int sp_521_num_bits_17(const sp_digit* a) __asm__ __volatile__ ( "LDR r1, [%[a], #64]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_16%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_16_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_16\n\t" #else - "BEQ.N L_sp_521_num_bits_17_16%=\n\t" + "BEQ.N L_sp_521_num_bits_17_16_%=\n\t" #endif "MOV r2, #0x220\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_16%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_16:\n\t" +#else + "L_sp_521_num_bits_17_16_%=:\n\t" +#endif "LDR r1, [%[a], #60]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_15%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_15_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_15\n\t" #else - "BEQ.N L_sp_521_num_bits_17_15%=\n\t" + "BEQ.N L_sp_521_num_bits_17_15_%=\n\t" #endif "MOV r2, #0x200\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_15%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_15:\n\t" +#else + "L_sp_521_num_bits_17_15_%=:\n\t" +#endif "LDR r1, [%[a], #56]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_14%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_14_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_14\n\t" #else - "BEQ.N L_sp_521_num_bits_17_14%=\n\t" + "BEQ.N L_sp_521_num_bits_17_14_%=\n\t" #endif "MOV r2, #0x1e0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_14%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_14:\n\t" +#else + "L_sp_521_num_bits_17_14_%=:\n\t" +#endif "LDR r1, [%[a], #52]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_13%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_13_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_13\n\t" #else - "BEQ.N L_sp_521_num_bits_17_13%=\n\t" + "BEQ.N L_sp_521_num_bits_17_13_%=\n\t" #endif "MOV r2, #0x1c0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_13%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_13:\n\t" +#else + "L_sp_521_num_bits_17_13_%=:\n\t" +#endif "LDR r1, [%[a], #48]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_12%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_12_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_12\n\t" #else - "BEQ.N L_sp_521_num_bits_17_12%=\n\t" + "BEQ.N L_sp_521_num_bits_17_12_%=\n\t" #endif "MOV r2, #0x1a0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_12%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_12:\n\t" +#else + "L_sp_521_num_bits_17_12_%=:\n\t" +#endif "LDR r1, [%[a], #44]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_11%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_11_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_11\n\t" #else - "BEQ.N L_sp_521_num_bits_17_11%=\n\t" + "BEQ.N L_sp_521_num_bits_17_11_%=\n\t" #endif "MOV r2, #0x180\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_11%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_11:\n\t" +#else + "L_sp_521_num_bits_17_11_%=:\n\t" +#endif "LDR r1, [%[a], #40]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_10%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_10_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_10\n\t" #else - "BEQ.N L_sp_521_num_bits_17_10%=\n\t" + "BEQ.N L_sp_521_num_bits_17_10_%=\n\t" #endif "MOV r2, #0x160\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_10%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_10:\n\t" +#else + "L_sp_521_num_bits_17_10_%=:\n\t" +#endif "LDR r1, [%[a], #36]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_9%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_9_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_9\n\t" #else - "BEQ.N L_sp_521_num_bits_17_9%=\n\t" + "BEQ.N L_sp_521_num_bits_17_9_%=\n\t" #endif "MOV r2, #0x140\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_9%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_9:\n\t" +#else + "L_sp_521_num_bits_17_9_%=:\n\t" +#endif "LDR r1, [%[a], #32]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_8%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_8_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_8\n\t" #else - "BEQ.N L_sp_521_num_bits_17_8%=\n\t" + "BEQ.N L_sp_521_num_bits_17_8_%=\n\t" #endif "MOV r2, #0x120\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_8%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_8:\n\t" +#else + "L_sp_521_num_bits_17_8_%=:\n\t" +#endif "LDR r1, [%[a], #28]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_7%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_7_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_7\n\t" #else - "BEQ.N L_sp_521_num_bits_17_7%=\n\t" + "BEQ.N L_sp_521_num_bits_17_7_%=\n\t" #endif "MOV r2, #0x100\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_7%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_7:\n\t" +#else + "L_sp_521_num_bits_17_7_%=:\n\t" +#endif "LDR r1, [%[a], #24]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_6%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_6_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_6\n\t" #else - "BEQ.N L_sp_521_num_bits_17_6%=\n\t" + "BEQ.N L_sp_521_num_bits_17_6_%=\n\t" #endif "MOV r2, #0xe0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_6%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_6:\n\t" +#else + "L_sp_521_num_bits_17_6_%=:\n\t" +#endif "LDR r1, [%[a], #20]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_5%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_5_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_5\n\t" #else - "BEQ.N L_sp_521_num_bits_17_5%=\n\t" + "BEQ.N L_sp_521_num_bits_17_5_%=\n\t" #endif "MOV r2, #0xc0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_5%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_5:\n\t" +#else + "L_sp_521_num_bits_17_5_%=:\n\t" +#endif "LDR r1, [%[a], #16]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_4%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_4_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_4\n\t" #else - "BEQ.N L_sp_521_num_bits_17_4%=\n\t" + "BEQ.N L_sp_521_num_bits_17_4_%=\n\t" #endif "MOV r2, #0xa0\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_4%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_4:\n\t" +#else + "L_sp_521_num_bits_17_4_%=:\n\t" +#endif "LDR r1, [%[a], #12]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_3%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_3_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_3\n\t" #else - "BEQ.N L_sp_521_num_bits_17_3%=\n\t" + "BEQ.N L_sp_521_num_bits_17_3_%=\n\t" #endif "MOV r2, #0x80\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_3%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_3:\n\t" +#else + "L_sp_521_num_bits_17_3_%=:\n\t" +#endif "LDR r1, [%[a], #8]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_2%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_2_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_2\n\t" #else - "BEQ.N L_sp_521_num_bits_17_2%=\n\t" + "BEQ.N L_sp_521_num_bits_17_2_%=\n\t" #endif "MOV r2, #0x60\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_2%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_2:\n\t" +#else + "L_sp_521_num_bits_17_2_%=:\n\t" +#endif "LDR r1, [%[a], #4]\n\t" "CMP r1, #0x0\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BEQ L_sp_521_num_bits_17_1%=\n\t" +#if defined(__GNUC__) + "BEQ L_sp_521_num_bits_17_1_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BEQ.N L_sp_521_num_bits_17_1\n\t" #else - "BEQ.N L_sp_521_num_bits_17_1%=\n\t" + "BEQ.N L_sp_521_num_bits_17_1_%=\n\t" #endif "MOV r2, #0x40\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "B L_sp_521_num_bits_17_18%=\n\t" +#if defined(__GNUC__) + "B L_sp_521_num_bits_17_18_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "B.N L_sp_521_num_bits_17_18\n\t" #else - "B.N L_sp_521_num_bits_17_18%=\n\t" + "B.N L_sp_521_num_bits_17_18_%=\n\t" #endif "\n" - "L_sp_521_num_bits_17_1%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_1:\n\t" +#else + "L_sp_521_num_bits_17_1_%=:\n\t" +#endif "LDR r1, [%[a]]\n\t" "MOV r2, #0x20\n\t" "CLZ r4, r1\n\t" "SUB r4, r2, r4\n\t" "\n" - "L_sp_521_num_bits_17_18%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_521_num_bits_17_18:\n\t" +#else + "L_sp_521_num_bits_17_18_%=:\n\t" +#endif "MOV %[a], r4\n\t" : [a] "+r" (a) : @@ -63891,10 +65147,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -64104,8 +65358,7 @@ static int sp_521_ecc_is_point_17(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -64144,8 +65397,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -64253,10 +65505,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -64335,10 +65585,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -64403,10 +65651,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -64467,10 +65713,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -64520,8 +65764,7 @@ static int sp_521_mont_sqrt_17(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -64586,8 +65829,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -67981,13 +69223,21 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_1024_mul_32_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mul_32_outer:\n\t" +#else + "L_sp_1024_mul_32_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_1024_mul_32_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mul_32_inner:\n\t" +#else + "L_sp_1024_mul_32_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -68003,15 +69253,19 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_mul_32_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_1024_mul_32_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_1024_mul_32_inner_done\n\t" #else - "BGT.N L_sp_1024_mul_32_inner_done%=\n\t" + "BGT.N L_sp_1024_mul_32_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_mul_32_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_mul_32_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_1024_mul_32_inner\n\t" #else - "BLT.N L_sp_1024_mul_32_inner%=\n\t" + "BLT.N L_sp_1024_mul_32_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[b], r3]\n\t" @@ -68020,17 +69274,23 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_1024_mul_32_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mul_32_inner_done:\n\t" +#else + "L_sp_1024_mul_32_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_1024_mul_32_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_1024_mul_32_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_1024_mul_32_outer\n\t" #else - "BLE.N L_sp_1024_mul_32_outer%=\n\t" + "BLE.N L_sp_1024_mul_32_outer_%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "LDR r11, [%[b], #124]\n\t" @@ -68039,14 +69299,20 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_1024_mul_32_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mul_32_store:\n\t" +#else + "L_sp_1024_mul_32_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_mul_32_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_1024_mul_32_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_1024_mul_32_store\n\t" #else - "BGT.N L_sp_1024_mul_32_store%=\n\t" + "BGT.N L_sp_1024_mul_32_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : @@ -68079,13 +69345,21 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "MOV r8, #0x0\n\t" "MOV r5, #0x4\n\t" "\n" - "L_sp_1024_sqr_32_outer%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_sqr_32_outer:\n\t" +#else + "L_sp_1024_sqr_32_outer_%=:\n\t" +#endif "SUBS r3, r5, #0x7c\n\t" "IT cc\n\t" "MOVCC r3, #0x0\n\t" "SUB r4, r5, r3\n\t" "\n" - "L_sp_1024_sqr_32_inner%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_sqr_32_inner:\n\t" +#else + "L_sp_1024_sqr_32_inner_%=:\n\t" +#endif "LDR lr, [%[a], r3]\n\t" "LDR r11, [%[a], r4]\n\t" "UMULL r9, r10, lr, r11\n\t" @@ -68098,15 +69372,19 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADD r3, r3, #0x4\n\t" "SUB r4, r4, #0x4\n\t" "CMP r3, r4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_sqr_32_inner_done%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_1024_sqr_32_inner_done_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_1024_sqr_32_inner_done\n\t" #else - "BGT.N L_sp_1024_sqr_32_inner_done%=\n\t" + "BGT.N L_sp_1024_sqr_32_inner_done_%=\n\t" #endif -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_sqr_32_inner%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_sqr_32_inner_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_1024_sqr_32_inner\n\t" #else - "BLT.N L_sp_1024_sqr_32_inner%=\n\t" + "BLT.N L_sp_1024_sqr_32_inner_%=\n\t" #endif "LDR lr, [%[a], r3]\n\t" "UMULL r9, r10, lr, lr\n\t" @@ -68114,17 +69392,23 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADCS r7, r7, r10\n\t" "ADC r8, r8, #0x0\n\t" "\n" - "L_sp_1024_sqr_32_inner_done%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_sqr_32_inner_done:\n\t" +#else + "L_sp_1024_sqr_32_inner_done_%=:\n\t" +#endif "STR r6, [sp, r5]\n\t" "MOV r6, r7\n\t" "MOV r7, r8\n\t" "MOV r8, #0x0\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0xf4\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLE L_sp_1024_sqr_32_outer%=\n\t" +#if defined(__GNUC__) + "BLE L_sp_1024_sqr_32_outer_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLE.N L_sp_1024_sqr_32_outer\n\t" #else - "BLE.N L_sp_1024_sqr_32_outer%=\n\t" + "BLE.N L_sp_1024_sqr_32_outer_%=\n\t" #endif "LDR lr, [%[a], #124]\n\t" "UMLAL r6, r7, lr, lr\n\t" @@ -68132,14 +69416,20 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) "ADD r5, r5, #0x4\n\t" "STR r7, [sp, r5]\n\t" "\n" - "L_sp_1024_sqr_32_store%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_sqr_32_store:\n\t" +#else + "L_sp_1024_sqr_32_store_%=:\n\t" +#endif "LDM sp!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "STM %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "SUBS r5, r5, #0x20\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BGT L_sp_1024_sqr_32_store%=\n\t" +#if defined(__GNUC__) + "BGT L_sp_1024_sqr_32_store_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BGT.N L_sp_1024_sqr_32_store\n\t" #else - "BGT.N L_sp_1024_sqr_32_store%=\n\t" + "BGT.N L_sp_1024_sqr_32_store_%=\n\t" #endif : [r] "+r" (r), [a] "+r" (a) : @@ -68254,7 +69544,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV r10, #0x0\n\t" "ADD r11, %[a], #0x80\n\t" "\n" - "L_sp_1024_sub_in_pkace_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_sub_in_pkace_32_word:\n\t" +#else + "L_sp_1024_sub_in_pkace_32_word_%=:\n\t" +#endif "RSBS r10, r10, #0x0\n\t" "LDM %[a], {r2, r3, r4, r5}\n\t" "LDM %[b]!, {r6, r7, r8, r9}\n\t" @@ -68265,10 +69559,12 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "STM %[a]!, {r2, r3, r4, r5}\n\t" "SBC r10, r10, r10\n\t" "CMP %[a], r11\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_1024_sub_in_pkace_32_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_1024_sub_in_pkace_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_1024_sub_in_pkace_32_word\n\t" #else - "BNE.N L_sp_1024_sub_in_pkace_32_word%=\n\t" + "BNE.N L_sp_1024_sub_in_pkace_32_word_%=\n\t" #endif "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) @@ -68306,7 +69602,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r4, #0x0\n\t" "MOV r5, #0x0\n\t" "\n" - "L_sp_1024_cond_sub_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_cond_sub_32_words:\n\t" +#else + "L_sp_1024_cond_sub_32_words_%=:\n\t" +#endif "SUBS r4, r8, r4\n\t" "LDR r6, [%[a], r5]\n\t" "LDR r7, [%[b], r5]\n\t" @@ -68316,10 +69616,12 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r5]\n\t" "ADD r5, r5, #0x4\n\t" "CMP r5, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_cond_sub_32_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_cond_sub_32_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_1024_cond_sub_32_words\n\t" #else - "BLT.N L_sp_1024_cond_sub_32_words%=\n\t" + "BLT.N L_sp_1024_cond_sub_32_words_%=\n\t" #endif "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -68497,7 +69799,11 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r3, #0x0\n\t" "ADD r12, %[a], #0x80\n\t" "\n" - "L_sp_1024_add_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_add_32_word:\n\t" +#else + "L_sp_1024_add_32_word_%=:\n\t" +#endif "ADDS r3, r3, #0xffffffff\n\t" "LDM %[a]!, {r4, r5, r6, r7}\n\t" "LDM %[b]!, {r8, r9, r10, r11}\n\t" @@ -68509,10 +69815,12 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV r4, #0x0\n\t" "ADC r3, r4, #0x0\n\t" "CMP %[a], r12\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BNE L_sp_1024_add_32_word%=\n\t" +#if defined(__GNUC__) + "BNE L_sp_1024_add_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BNE.N L_sp_1024_add_32_word\n\t" #else - "BNE.N L_sp_1024_add_32_word%=\n\t" + "BNE.N L_sp_1024_add_32_word_%=\n\t" #endif "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -68551,7 +69859,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "MOV r9, #0x4\n\t" "\n" - "L_sp_1024_mul_d_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mul_d_32_word:\n\t" +#else + "L_sp_1024_mul_d_32_word_%=:\n\t" +#endif /* A[i] * B */ "LDR r8, [%[a], r9]\n\t" "UMULL r6, r7, %[b], r8\n\t" @@ -68564,10 +69876,12 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "MOV r5, #0x0\n\t" "ADD r9, r9, #0x4\n\t" "CMP r9, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_mul_d_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_mul_d_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_1024_mul_d_32_word\n\t" #else - "BLT.N L_sp_1024_mul_d_32_word%=\n\t" + "BLT.N L_sp_1024_mul_d_32_word_%=\n\t" #endif "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) @@ -68865,7 +70179,11 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit /* Next 30 bits */ "MOV r4, #0x1d\n\t" "\n" - "L_div_1024_word_32_bit%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_div_1024_word_32_bit:\n\t" +#else + "L_div_1024_word_32_bit_%=:\n\t" +#endif "LSLS r6, r6, #1\n\t" "ADC r7, r7, r7\n\t" "SUBS r8, r5, r7\n\t" @@ -68875,7 +70193,13 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit "AND r8, r8, r5\n\t" "SUBS r7, r7, r8\n\t" "SUBS r4, r4, #0x1\n\t" - "bpl L_div_1024_word_32_bit%=\n\t" +#if defined(__GNUC__) + "BPL L_div_1024_word_32_bit_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BPL.N L_div_1024_word_32_bit\n\t" +#else + "BPL.N L_div_1024_word_32_bit_%=\n\t" +#endif "ADD r3, r3, r3\n\t" "ADD r3, r3, #0x1\n\t" "UMULL r6, r7, r3, %[div]\n\t" @@ -68957,7 +70281,11 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) #ifdef WOLFSSL_SP_SMALL "MOV r6, #0x7c\n\t" "\n" - "L_sp_1024_cmp_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_cmp_32_words:\n\t" +#else + "L_sp_1024_cmp_32_words_%=:\n\t" +#endif "LDR r4, [%[a], r6]\n\t" "LDR r5, [%[b], r6]\n\t" "AND r4, r4, r3\n\t" @@ -68970,7 +70298,11 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) "IT ne\n\t" "movne r3, r7\n\t" "SUBS r6, r6, #0x4\n\t" - "bcs L_sp_1024_cmp_32_words%=\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "bcs L_sp_1024_cmp_32_words\n\t" +#else + "bcs L_sp_1024_cmp_32_words_%=\n\t" +#endif "EOR r2, r2, r3\n\t" #else "LDR r4, [%[a], #124]\n\t" @@ -69451,16 +70783,16 @@ static void sp_1024_point_free_32(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -69690,7 +71022,11 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r4, [%[a]]\n\t" "LDR r5, [%[a], #4]\n\t" "\n" - "L_sp_1024_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mont_reduce_32_word:\n\t" +#else + "L_sp_1024_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL r10, %[mp], r4\n\t" /* a[i+0] += m[0] * mu */ @@ -69952,10 +71288,12 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r11, r11, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r11, #0x80\n\t" -#ifdef __GNUC__ - "BLT L_sp_1024_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_1024_mont_reduce_32_word\n\t" #else - "BLT.W L_sp_1024_mont_reduce_32_word%=\n\t" + "BLT.W L_sp_1024_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "STR r4, [%[a]]\n\t" @@ -70002,7 +71340,11 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "LDR r9, [%[a], #12]\n\t" "LDR r10, [%[a], #16]\n\t" "\n" - "L_sp_1024_mont_reduce_32_word%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_mont_reduce_32_word:\n\t" +#else + "L_sp_1024_mont_reduce_32_word_%=:\n\t" +#endif /* mu = a[i] * mp */ "MUL lr, %[mp], r6\n\t" /* a[i+0] += m[0] * mu */ @@ -70169,10 +71511,12 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "ADD r4, r4, #0x4\n\t" "ADD %[a], %[a], #0x4\n\t" "CMP r4, #0x80\n\t" -#ifdef __GNUC__ - "BLT L_sp_1024_mont_reduce_32_word%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_mont_reduce_32_word_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.W L_sp_1024_mont_reduce_32_word\n\t" #else - "BLT.W L_sp_1024_mont_reduce_32_word%=\n\t" + "BLT.W L_sp_1024_mont_reduce_32_word_%=\n\t" #endif /* Loop Done */ "STR r6, [%[a]]\n\t" @@ -70315,7 +71659,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_32(r->x, p1024_mod); - sp_1024_cond_sub_32(r->x, r->x, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->x, r->x, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->x); /* y /= z^3 */ @@ -70324,7 +71668,7 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_32(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_32(r->y, p1024_mod); - sp_1024_cond_sub_32(r->y, r->y, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(r->y, r->y, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -71187,7 +72531,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV r8, #0x0\n\t" "MOV r4, #0x0\n\t" "\n" - "L_sp_1024_cond_add_32_words%=:\n\t" +#if defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "L_sp_1024_cond_add_32_words:\n\t" +#else + "L_sp_1024_cond_add_32_words_%=:\n\t" +#endif "ADDS r5, r5, #0xffffffff\n\t" "LDR r6, [%[a], r4]\n\t" "LDR r7, [%[b], r4]\n\t" @@ -71197,10 +72545,12 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "STR r6, [%[r], r4]\n\t" "ADD r4, r4, #0x4\n\t" "CMP r4, #0x80\n\t" -#if defined(__GNUC__) || defined(__ICCARM__) || defined(__IAR_SYSTEMS_ICC__) - "BLT L_sp_1024_cond_add_32_words%=\n\t" +#if defined(__GNUC__) + "BLT L_sp_1024_cond_add_32_words_%=\n\t" +#elif defined(__IAR_SYSTEMS_ICC__) && (__VER__ < 9000000) + "BLT.N L_sp_1024_cond_add_32_words\n\t" #else - "BLT.N L_sp_1024_cond_add_32_words%=\n\t" + "BLT.N L_sp_1024_cond_add_32_words_%=\n\t" #endif "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) @@ -71816,8 +73166,8 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, sp_1024_mont_sub_32(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -71834,7 +73184,7 @@ static void sp_1024_proj_point_add_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -72008,8 +73358,8 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -72026,7 +73376,7 @@ static int sp_1024_proj_point_add_32_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -72367,8 +73717,8 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, sp_1024_mont_sub_32(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -72385,7 +73735,7 @@ static void sp_1024_proj_point_add_qz1_32(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -72475,8 +73825,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -72575,10 +73924,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -72834,8 +74181,7 @@ static int sp_1024_gen_stripe_table_32(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -72934,10 +74280,8 @@ static int sp_1024_ecc_mulmod_stripe_32(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -73155,10 +74499,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76793,10 +78135,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76871,10 +78211,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76908,7 +78246,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -76939,10 +78277,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -76968,7 +78304,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -77035,10 +78371,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -77185,9 +78519,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -79083,9 +80415,7 @@ int sp_ModExp_Fp_star_1024(const mp_int* base, mp_int* exp, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -79453,9 +80783,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -79880,9 +81208,7 @@ int sp_Pairing_1024(const ecc_point* pm, const ecc_point* qm, mp_int* res) #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -79912,7 +81238,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -80141,7 +81467,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -80248,9 +81574,7 @@ int sp_Pairing_gen_precomp_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(neg, 1, NULL); sp_1024_point_free_32(c, 1, NULL); @@ -80443,9 +81767,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_32(c, 1, NULL); sp_1024_point_free_32(q, 1, NULL); @@ -80538,7 +81860,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, n = sp_1024_cmp_32(t1, p1024_mod); - sp_1024_cond_sub_32(t1, t1, p1024_mod, ~(n >> 31)); + sp_1024_cond_sub_32(t1, t1, p1024_mod, (sp_digit)~(n >> 31)); sp_1024_norm_32(t1); if (!sp_1024_iszero_32(t1)) { err = MP_VAL; @@ -80546,8 +81868,7 @@ static int sp_1024_ecc_is_point_32(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -80586,8 +81907,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -80695,10 +82015,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_dsp32.c b/src/wolfcrypt/src/sp_dsp32.c index d3b1745..f14e1ab 100644 --- a/src/wolfcrypt/src/sp_dsp32.c +++ b/src/wolfcrypt/src/sp_dsp32.c @@ -1,6 +1,6 @@ /* sp_cdsp_signed.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -296,9 +296,7 @@ static int sp_256_mod_mul_norm_10(sp_digit* r, const sp_digit* a, const sp_digit } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(td, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -2592,9 +2590,7 @@ static int sp_256_ecc_mulmod_stripe_10(sp_point* r, const sp_point* g, } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (t != NULL) { - XFREE(t, heap, DYNAMIC_TYPE_ECC); - } + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif sp_ecc_point_free(p, 0, heap); sp_ecc_point_free(rt, 0, heap); @@ -4233,9 +4229,7 @@ static int sp_256_div_10(const sp_digit* a, const sp_digit* d, sp_digit* m, } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4530,8 +4524,7 @@ int wolfSSL_DSP_ECC_Verify_256(remote_handle64 h, int32 *u1, int hashLen, int32* } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (d != NULL) - XFREE(d, heap, DYNAMIC_TYPE_ECC); + XFREE(d, heap, DYNAMIC_TYPE_ECC); #endif sp_ecc_point_free(p1, 0, heap); sp_ecc_point_free(p2, 0, heap); @@ -4631,9 +4624,7 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (tmp != NULL) { - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); #endif sp_ecc_point_free(q, 0, NULL); sp_ecc_point_free(p, 0, NULL); @@ -4696,9 +4687,7 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (tmp != NULL) { - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); #endif sp_ecc_point_free(p, 0, NULL); @@ -4754,9 +4743,7 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (tmp != NULL) { - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); #endif sp_ecc_point_free(p, 0, NULL); @@ -4831,9 +4818,7 @@ static int sp_256_mont_sqrt_10(sp_digit* y) } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (d != NULL) { - XFREE(d, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(d, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -4906,9 +4891,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #if defined(WOLFSSL_SP_SMALL) || defined(WOLFSSL_SMALL_STACK) - if (d != NULL) { - XFREE(d, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(d, NULL, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sp_int.c b/src/wolfcrypt/src/sp_int.c index 3a6884a..d9ac60b 100644 --- a/src/wolfcrypt/src/sp_int.c +++ b/src/wolfcrypt/src/sp_int.c @@ -1,6 +1,6 @@ /* sp_int.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -31,6 +31,7 @@ This library provides single precision (SP) integer math functions. #endif #include +#include #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) @@ -167,7 +168,7 @@ This library provides single precision (SP) integer math functions. do { \ ALLOC_SP_INT(n, s, err, h); \ if ((err) == MP_OKAY) { \ - (n)->size = (s); \ + (n)->size = (sp_size_t)(s); \ } \ } \ while (0) @@ -186,7 +187,7 @@ This library provides single precision (SP) integer math functions. do { \ ALLOC_SP_INT(n, s, err, h); \ if ((err) == MP_OKAY) { \ - (n)->size = (unsigned int)(s); \ + (n)->size = (sp_size_t)(s); \ } \ } \ while (0) @@ -210,9 +211,10 @@ This library provides single precision (SP) integer math functions. /* Declare a variable that will be assigned a value on XMALLOC. */ -#define DECL_DYN_SP_INT_ARRAY(n, s, c) \ - sp_int* n##d = NULL; \ - sp_int* (n)[c] = { NULL, } +#define DECL_DYN_SP_INT_ARRAY(n, s, c) \ + sp_int* n##d = NULL; \ + sp_int* (n)[c]; \ + void *n ## _dummy_var = XMEMSET(n, 0, sizeof(n)) /* DECL_SP_INT_ARRAY: Declare array of 'sp_int'. */ #if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ @@ -220,19 +222,17 @@ This library provides single precision (SP) integer math functions. /* Declare a variable that will be assigned a value on XMALLOC. */ #define DECL_SP_INT_ARRAY(n, s, c) \ DECL_DYN_SP_INT_ARRAY(n, s, c) -#else - #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(WOLFSSL_SP_NO_DYN_STACK) - /* Declare a variable on the stack with the required data size. */ - #define DECL_SP_INT_ARRAY(n, s, c) \ - byte n##d[MP_INT_SIZEOF(s) * (c)]; \ - sp_int* (n)[c] = { NULL, } - #else - /* Declare a variable on the stack. */ - #define DECL_SP_INT_ARRAY(n, s, c) \ - sp_int n##d[c]; \ - sp_int* (n)[c] - #endif + /* Declare a variable on the stack with the required data size. */ + #define DECL_SP_INT_ARRAY(n, s, c) \ + byte n##d[MP_INT_SIZEOF(s) * (c)]; \ + sp_int* (n)[c] = { NULL, } +#else + /* Declare a variable on the stack. */ + #define DECL_SP_INT_ARRAY(n, s, c) \ + sp_int n##d[c]; \ + sp_int* (n)[c] #endif /* Dynamically allocate just enough data to support multiple sp_ints of the @@ -240,6 +240,7 @@ This library provides single precision (SP) integer math functions. */ #define ALLOC_DYN_SP_INT_ARRAY(n, s, c, err, h) \ do { \ + (void)n ## _dummy_var; \ if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ (err) = MP_VAL; \ } \ @@ -252,10 +253,10 @@ do { \ else { \ int n##ii; \ (n)[0] = n##d; \ - (n)[0]->size = (s); \ + (n)[0]->size = (sp_size_t)(s); \ for (n##ii = 1; n##ii < (int)(c); n##ii++) { \ (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ - (n)[n##ii]->size = (s); \ + (n)[n##ii]->size = (sp_size_t)(s); \ } \ } \ } \ @@ -267,47 +268,45 @@ while (0) !defined(WOLFSSL_SP_NO_MALLOC) #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ ALLOC_DYN_SP_INT_ARRAY(n, s, c, err, h) -#else - #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(WOLFSSL_SP_NO_DYN_STACK) - /* Data declared on stack that supports multiple sp_ints of the - * required size. Use pointers into data to make up array and set sizes. - */ - #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ - do { \ - if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ - (err) = MP_VAL; \ - } \ - if ((err) == MP_OKAY) { \ - int n##ii; \ - (n)[0] = (sp_int*)n##d; \ - ((sp_int_minimal*)(n)[0])->size = (s); \ - for (n##ii = 1; n##ii < (int)(c); n##ii++) { \ - (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ - ((sp_int_minimal*)(n)[n##ii])->size = (s); \ - } \ - } \ + /* Data declared on stack that supports multiple sp_ints of the + * required size. Use pointers into data to make up array and set sizes. + */ + #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ + do { \ + if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ + (err) = MP_VAL; \ } \ - while (0) - #else - /* Data declared on stack that supports multiple sp_ints of the - * required size. Set into array and set sizes. - */ - #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ - do { \ - if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ - (err) = MP_VAL; \ + if ((err) == MP_OKAY) { \ + int n##ii; \ + (n)[0] = (sp_int*)n##d; \ + ((sp_int_minimal*)(n)[0])->size = (sp_size_t)(s); \ + for (n##ii = 1; n##ii < (int)(c); n##ii++) { \ + (n)[n##ii] = MP_INT_NEXT((n)[n##ii-1], s); \ + ((sp_int_minimal*)(n)[n##ii])->size = (sp_size_t)(s); \ } \ - if ((err) == MP_OKAY) { \ - int n##ii; \ - for (n##ii = 0; n##ii < (int)(c); n##ii++) { \ - (n)[n##ii] = &n##d[n##ii]; \ - (n)[n##ii]->size = (s); \ - } \ + } \ + } \ + while (0) +#else + /* Data declared on stack that supports multiple sp_ints of the + * required size. Set into array and set sizes. + */ + #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ + do { \ + if (((err) == MP_OKAY) && ((s) > SP_INT_DIGITS)) { \ + (err) = MP_VAL; \ + } \ + if ((err) == MP_OKAY) { \ + int n##ii; \ + for (n##ii = 0; n##ii < (int)(c); n##ii++) { \ + (n)[n##ii] = &n##d[n##ii]; \ + (n)[n##ii]->size = (sp_size_t)(s); \ } \ } \ - while (0) - #endif + } \ + while (0) #endif /* Free data variable that was dynamically allocated. */ @@ -3474,6 +3473,156 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, * CPU: PPC64 */ + #ifdef __APPLE__ + +/* Multiply va by vb and store double size result in: vh | vl */ +#define SP_ASM_MUL(vl, vh, va, vb) \ + __asm__ __volatile__ ( \ + "mulld %[l], %[a], %[b] \n\t" \ + "mulhdu %[h], %[a], %[b] \n\t" \ + : [h] "+r" (vh), [l] "+r" (vl) \ + : [a] "r" (va), [b] "r" (vb) \ + : "memory" \ + ) +/* Multiply va by vb and store double size result in: vo | vh | vl */ +#define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mulhdu %[h], %[a], %[b] \n\t" \ + "mulld %[l], %[a], %[b] \n\t" \ + "li %[o], 0 \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "=r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : \ + ) +/* Multiply va by vb and add double size result into: vo | vh | vl */ +#define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[b] \n\t" \ + "mulhdu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result into: vh | vl */ +#define SP_ASM_MUL_ADD_NO(vl, vh, va, vb) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[b] \n\t" \ + "mulhdu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result twice into: vo | vh | vl */ +#define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[b] \n\t" \ + "mulhdu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result twice into: vo | vh | vl + * Assumes first add will not overflow vh | vl + */ +#define SP_ASM_MUL_ADD2_NO(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[b] \n\t" \ + "mulhdu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Square va and store double size result in: vh | vl */ +#define SP_ASM_SQR(vl, vh, va) \ + __asm__ __volatile__ ( \ + "mulld %[l], %[a], %[a] \n\t" \ + "mulhdu %[h], %[a], %[a] \n\t" \ + : [h] "+r" (vh), [l] "+r" (vl) \ + : [a] "r" (va) \ + : "memory" \ + ) +/* Square va and add double size result into: vo | vh | vl */ +#define SP_ASM_SQR_ADD(vl, vh, vo, va) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[a] \n\t" \ + "mulhdu r17, %[a], %[a] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va) \ + : "r16", "r17", "cc" \ + ) +/* Square va and add double size result into: vh | vl */ +#define SP_ASM_SQR_ADD_NO(vl, vh, va) \ + __asm__ __volatile__ ( \ + "mulld r16, %[a], %[a] \n\t" \ + "mulhdu r17, %[a], %[a] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "r16", "r17", "cc" \ + ) +/* Add va into: vh | vl */ +#define SP_ASM_ADDC(vl, vh, va) \ + __asm__ __volatile__ ( \ + "addc %[l], %[l], %[a] \n\t" \ + "addze %[h], %[h] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "cc" \ + ) +/* Sub va from: vh | vl */ +#define SP_ASM_SUBB(vl, vh, va) \ + __asm__ __volatile__ ( \ + "subfc %[l], %[a], %[l] \n\t" \ + "li r16, 0 \n\t" \ + "subfe %[h], r16, %[h] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "r16", "cc" \ + ) +/* Add two times vc | vb | va into vo | vh | vl */ +#define SP_ASM_ADD_DBL_3(vl, vh, vo, va, vb, vc) \ + __asm__ __volatile__ ( \ + "addc %[l], %[l], %[a] \n\t" \ + "adde %[h], %[h], %[b] \n\t" \ + "adde %[o], %[o], %[c] \n\t" \ + "addc %[l], %[l], %[a] \n\t" \ + "adde %[h], %[h], %[b] \n\t" \ + "adde %[o], %[o], %[c] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb), [c] "r" (vc) \ + : "cc" \ + ) +/* Count leading zeros. */ +#define SP_ASM_LZCNT(va, vn) \ + __asm__ __volatile__ ( \ + "cntlzd %[n], %[a] \n\t" \ + : [n] "=r" (vn) \ + : [a] "r" (va) \ + : \ + ) + + #else /* !defined(__APPLE__) */ + /* Multiply va by vb and store double size result in: vh | vl */ #define SP_ASM_MUL(vl, vh, va, vb) \ __asm__ __volatile__ ( \ @@ -3620,6 +3769,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : \ ) + #endif /* !defined(__APPLE__) */ + #define SP_INT_ASM_AVAILABLE #endif /* WOLFSSL_SP_PPC64 && SP_WORD_SIZE == 64 */ @@ -3629,6 +3780,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, * CPU: PPC 32-bit */ + #ifdef __APPLE__ + /* Multiply va by vb and store double size result in: vh | vl */ #define SP_ASM_MUL(vl, vh, va, vb) \ __asm__ __volatile__ ( \ @@ -3648,6 +3801,152 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "r" (va), [b] "r" (vb) \ ) /* Multiply va by vb and add double size result into: vo | vh | vl */ +#define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[b] \n\t" \ + "mulhwu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result into: vh | vl */ +#define SP_ASM_MUL_ADD_NO(vl, vh, va, vb) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[b] \n\t" \ + "mulhwu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result twice into: vo | vh | vl */ +#define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[b] \n\t" \ + "mulhwu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Multiply va by vb and add double size result twice into: vo | vh | vl + * Assumes first add will not overflow vh | vl + */ +#define SP_ASM_MUL_ADD2_NO(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[b] \n\t" \ + "mulhwu r17, %[a], %[b] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + : "r16", "r17", "cc" \ + ) +/* Square va and store double size result in: vh | vl */ +#define SP_ASM_SQR(vl, vh, va) \ + __asm__ __volatile__ ( \ + "mullw %[l], %[a], %[a] \n\t" \ + "mulhwu %[h], %[a], %[a] \n\t" \ + : [h] "+r" (vh), [l] "+r" (vl) \ + : [a] "r" (va) \ + : "memory" \ + ) +/* Square va and add double size result into: vo | vh | vl */ +#define SP_ASM_SQR_ADD(vl, vh, vo, va) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[a] \n\t" \ + "mulhwu r17, %[a], %[a] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + "addze %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va) \ + : "r16", "r17", "cc" \ + ) +/* Square va and add double size result into: vh | vl */ +#define SP_ASM_SQR_ADD_NO(vl, vh, va) \ + __asm__ __volatile__ ( \ + "mullw r16, %[a], %[a] \n\t" \ + "mulhwu r17, %[a], %[a] \n\t" \ + "addc %[l], %[l], r16 \n\t" \ + "adde %[h], %[h], r17 \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "r16", "r17", "cc" \ + ) +/* Add va into: vh | vl */ +#define SP_ASM_ADDC(vl, vh, va) \ + __asm__ __volatile__ ( \ + "addc %[l], %[l], %[a] \n\t" \ + "addze %[h], %[h] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "cc" \ + ) +/* Sub va from: vh | vl */ +#define SP_ASM_SUBB(vl, vh, va) \ + __asm__ __volatile__ ( \ + "subfc %[l], %[a], %[l] \n\t" \ + "li r16, 0 \n\t" \ + "subfe %[h], r16, %[h] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh) \ + : [a] "r" (va) \ + : "r16", "cc" \ + ) +/* Add two times vc | vb | va into vo | vh | vl */ +#define SP_ASM_ADD_DBL_3(vl, vh, vo, va, vb, vc) \ + __asm__ __volatile__ ( \ + "addc %[l], %[l], %[a] \n\t" \ + "adde %[h], %[h], %[b] \n\t" \ + "adde %[o], %[o], %[c] \n\t" \ + "addc %[l], %[l], %[a] \n\t" \ + "adde %[h], %[h], %[b] \n\t" \ + "adde %[o], %[o], %[c] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "r" (va), [b] "r" (vb), [c] "r" (vc) \ + : "cc" \ + ) +/* Count leading zeros. */ +#define SP_ASM_LZCNT(va, vn) \ + __asm__ __volatile__ ( \ + "cntlzw %[n], %[a] \n\t" \ + : [n] "=r" (vn) \ + : [a] "r" (va) \ + ) + + #else /* !defined(__APPLE__) */ + +/* Multiply va by vb and store double size result in: vh | vl */ +#define SP_ASM_MUL(vl, vh, va, vb) \ + __asm__ __volatile__ ( \ + "mullw %[l], %[a], %[b] \n\t" \ + "mulhwu %[h], %[a], %[b] \n\t" \ + : [h] "+r" (vh), [l] "+r" (vl) \ + : [a] "r" (va), [b] "r" (vb) \ + : "memory" \ + ) +/* Multiply va by vb and store double size result in: vo | vh | vl */ +#define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ + __asm__ __volatile__ ( \ + "mulhwu %[h], %[a], %[b] \n\t" \ + "mullw %[l], %[a], %[b] \n\t" \ + "xor %[o], %[o], %[o] \n\t" \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "=r" (vo) \ + : [a] "r" (va), [b] "r" (vb) \ + ) +/* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ __asm__ __volatile__ ( \ "mullw 16, %[a], %[b] \n\t" \ @@ -3746,7 +4045,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, #define SP_ASM_SUBB(vl, vh, va) \ __asm__ __volatile__ ( \ "subfc %[l], %[a], %[l] \n\t" \ - "li 16, 0 \n\t" \ + "xor 16, 16, 16 \n\t" \ "subfe %[h], 16, %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ : [a] "r" (va) \ @@ -3773,6 +4072,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : [a] "r" (va) \ ) + #endif /* !defined(__APPLE__) */ + #define SP_INT_ASM_AVAILABLE #endif /* WOLFSSL_SP_PPC && SP_WORD_SIZE == 64 */ @@ -4827,6 +5128,12 @@ static void _sp_mont_setup(const sp_int* m, sp_int_digit* rho); #define WOLFSSL_SP_PRIME_GEN #endif +#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || defined(OPENSSL_EXTRA) +/* Determine when mp_mul_d is required */ +#define WOLFSSL_SP_MUL_D +#endif + /* Set the multi-precision number to zero. * * Assumes a is not NULL. @@ -4859,7 +5166,7 @@ static void _sp_init_size(sp_int* a, unsigned int size) #endif _sp_zero((sp_int*)am); - a->size = size; + a->size = (sp_size_t)size; } /* Initialize the multi-precision number to be zero with a given max size. @@ -5214,8 +5521,8 @@ int sp_exch(sp_int* a, sp_int* b) ALLOC_SP_INT(t, a->used, err, NULL); if (err == MP_OKAY) { /* Cache allocated size of a and b. */ - unsigned int asize = a->size; - unsigned int bsize = b->size; + sp_size_t asize = a->size; + sp_size_t bsize = b->size; /* Copy all of SP int: t <- a, a <- b, b <- t. */ XMEMCPY(t, a, MP_INT_SIZEOF(a->used)); XMEMCPY(a, b, MP_INT_SIZEOF(b->used)); @@ -5251,9 +5558,9 @@ int sp_cond_swap_ct_ex(sp_int* a, sp_int* b, int cnt, int swap, sp_int* t) sp_int_digit mask = (sp_int_digit)0 - (sp_int_digit)swap; /* XOR other fields in sp_int into temp - mask set when swapping. */ - t->used = (a->used ^ b->used) & (unsigned int)mask; + t->used = (a->used ^ b->used) & (sp_size_t)mask; #ifdef WOLFSSL_SP_INT_NEGATIVE - t->sign = (a->sign ^ b->sign) & (unsigned int)mask; + t->sign = (a->sign ^ b->sign) & (sp_uint8)mask; #endif /* XOR requested words into temp - mask set when swapping. */ @@ -5719,7 +6026,7 @@ int sp_cnt_lsb(const sp_int* a) unsigned int j; /* Count least significant words that are zero. */ - for (i = 0; i < a->used && a->dp[i] == 0; i++, bc += SP_WORD_SIZE) { + for (i = 0; (i < a->used) && (a->dp[i] == 0); i++, bc += SP_WORD_SIZE) { } /* Use 4-bit table to get count. */ @@ -5790,7 +6097,7 @@ int sp_set_bit(sp_int* a, int i) { int err = MP_OKAY; /* Get index of word to set. */ - unsigned int w = (unsigned int)(i >> SP_WORD_SHIFT); + sp_size_t w = (sp_size_t)(i >> SP_WORD_SHIFT); /* Check for valid number and and space for bit. */ if ((a == NULL) || (i < 0) || (w >= a->size)) { @@ -6252,7 +6559,8 @@ int sp_sub_d(const sp_int* a, sp_int_digit d, sp_int* r) !defined(NO_DH) || defined(HAVE_ECC) || \ (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ !defined(WOLFSSL_RSA_PUBLIC_ONLY))) || \ - (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) + (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || \ + defined(WOLFSSL_SP_MUL_D) /* Multiply a by digit n and put result into r shifting up o digits. * r = (a * n) << (o * SP_WORD_SIZE) * @@ -6326,7 +6634,7 @@ static int _sp_mul_d(const sp_int* a, sp_int_digit d, sp_int* r, unsigned int o) } } /* Update number of words in result. */ - r->used = o; + r->used = (sp_size_t)o; /* In case n is zero. */ sp_clamp(r); @@ -6335,8 +6643,7 @@ static int _sp_mul_d(const sp_int* a, sp_int_digit d, sp_int* r, unsigned int o) #endif /* (WOLFSSL_SP_MATH_ALL && !WOLFSSL_RSA_VERIFY_ONLY) || * WOLFSSL_SP_SMALL || (WOLFSSL_KEY_GEN && !NO_RSA) */ -#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ - (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) +#ifdef WOLFSSL_SP_MUL_D /* Multiply a by digit n and put result into r. r = a * n * * @param [in] a SP integer to multiply. @@ -6374,8 +6681,7 @@ int sp_mul_d(const sp_int* a, sp_int_digit d, sp_int* r) return err; } -#endif /* (WOLFSSL_SP_MATH_ALL && !WOLFSSL_RSA_VERIFY_ONLY) || - * (WOLFSSL_KEY_GEN && !NO_RSA) */ +#endif /* WOLFSSL_SP_MUL_D */ /* Predefine complicated rules of when to compile in sp_div_d and sp_mod_d. */ #if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ @@ -7057,7 +7363,7 @@ static void _sp_div_2(const sp_int* a, sp_int* r) /* Last word only needs to be shifted down. */ r->dp[i] = a->dp[i] >> 1; /* Set used to be all words seen. */ - r->used = (unsigned int)i + 1; + r->used = (sp_size_t)i + 1; /* Remove leading zeros. */ sp_clamp(r); #ifdef WOLFSSL_SP_INT_NEGATIVE @@ -7133,7 +7439,7 @@ int sp_div_2_mod_ct(const sp_int* a, const sp_int* m, sp_int* r) #endif /* Mask to apply to modulus. */ sp_int_digit mask = (sp_int_digit)0 - (a->dp[0] & 1); - unsigned int i; + sp_size_t i; #if 0 sp_print(a, "a"); @@ -7208,7 +7514,7 @@ int sp_div_2_mod_ct(const sp_int* a, const sp_int* m, sp_int* r) */ static void _sp_add_off(const sp_int* a, const sp_int* b, sp_int* r, int o) { - unsigned int i = 0; + sp_size_t i = 0; #ifndef SQR_MUL_ASM sp_int_word t = 0; #else @@ -7329,10 +7635,10 @@ static void _sp_add_off(const sp_int* a, const sp_int* b, sp_int* r, int o) /* Put in carry. */ #ifndef SQR_MUL_ASM r->dp[i] = (sp_int_digit)t; - r->used += (t != 0); + r->used = (sp_size_t)(r->used + (sp_size_t)(t != 0)); #else r->dp[i] = l; - r->used += (l != 0); + r->used = (sp_size_t)(r->used + (sp_size_t)(l != 0)); #endif /* Remove leading zeros. */ @@ -7356,8 +7662,8 @@ static void _sp_add_off(const sp_int* a, const sp_int* b, sp_int* r, int o) static void _sp_sub_off(const sp_int* a, const sp_int* b, sp_int* r, unsigned int o) { - unsigned int i = 0; - unsigned int j; + sp_size_t i = 0; + sp_size_t j; #ifndef SQR_MUL_ASM sp_int_sword t = 0; #else @@ -7372,7 +7678,7 @@ static void _sp_sub_off(const sp_int* a, const sp_int* b, sp_int* r, } } else { - i = o; + i = (sp_size_t)o; } /* Index to add at is the offset now. */ @@ -7566,7 +7872,7 @@ static int _sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, { int err = MP_OKAY; /* Calculate used based on digits used in a and b. */ - unsigned int used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); + sp_size_t used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); DECL_SP_INT(t, used); /* Allocate a temporary SP int to hold sum. */ @@ -7687,7 +7993,7 @@ static int _sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, FREE_SP_INT_ARRAY(t, NULL); #else /* WOLFSSL_SP_INT_NEGATIVE */ - unsigned int used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); + sp_size_t used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); DECL_SP_INT(t, used); ALLOC_SP_INT_SIZE(t, used, err, NULL); @@ -7763,12 +8069,12 @@ int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) static void sp_clamp_ct(sp_int* a) { int i; - unsigned int used = a->used; - unsigned int mask = (unsigned int)-1; + sp_size_t used = a->used; + sp_size_t mask = (sp_size_t)-1; for (i = (int)a->used - 1; i >= 0; i--) { - used -= ((unsigned int)(a->dp[i] == 0)) & mask; - mask &= (unsigned int)0 - (a->dp[i] == 0); + used = (sp_size_t)(used - ((a->dp[i] == 0) & mask)); + mask &= (sp_size_t)(0 - (a->dp[i] == 0)); } a->used = used; } @@ -7804,7 +8110,7 @@ int sp_addmod_ct(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) sp_int_digit mask; sp_int_digit mask_a = (sp_int_digit)-1; sp_int_digit mask_b = (sp_int_digit)-1; - unsigned int i; + sp_size_t i; /* Check result is as big as modulus. */ if (m->used > r->size) { @@ -8041,7 +8347,7 @@ static void _sp_submod_ct(const sp_int* a, const sp_int* b, const sp_int* m, } /* Result will always have digits equal to or less than those in * modulus. */ - r->used = i; + r->used = (sp_size_t)i; #ifdef WOLFSSL_SP_INT_NEGATIVE r->sign = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ @@ -8150,7 +8456,7 @@ int sp_lshd(sp_int* a, int s) /* Back fill with zeros. */ XMEMSET(a->dp, 0, (size_t)s * SP_WORD_SIZEOF); /* Update used. */ - a->used += (unsigned int)s; + a->used += (sp_size_t)s; /* Remove leading zeros. */ sp_clamp(a); } @@ -8179,7 +8485,7 @@ static int sp_lshb(sp_int* a, int n) if (a->used != 0) { /* Calculate number of digits to shift. */ - unsigned int s = (unsigned int)n >> SP_WORD_SHIFT; + sp_size_t s = (sp_size_t)n >> SP_WORD_SHIFT; /* Ensure number has enough digits for result. */ if (a->used + s >= a->size) { @@ -8237,14 +8543,14 @@ void sp_rshd(sp_int* a, int c) /* Do shift if we have an SP int. */ if ((a != NULL) && (c > 0)) { /* Make zero if shift removes all digits. */ - if ((unsigned int)c >= a->used) { + if ((sp_size_t)c >= a->used) { _sp_zero(a); } else { - unsigned int i; + sp_size_t i; /* Update used digits count. */ - a->used -= (unsigned int)c; + a->used -= (sp_size_t)c; /* Move digits down. */ for (i = 0; i < a->used; i++, c++) { a->dp[i] = a->dp[c]; @@ -8267,7 +8573,7 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) { int err = MP_OKAY; /* Number of digits to shift down. */ - unsigned int i = (unsigned int)(n >> SP_WORD_SHIFT); + sp_size_t i = (sp_size_t)(n >> SP_WORD_SHIFT); if ((a == NULL) || (n < 0)) { err = MP_VAL; @@ -8281,7 +8587,7 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) err = MP_VAL; } else if (err == MP_OKAY) { - unsigned int j; + sp_size_t j; /* Number of bits to shift in digits. */ n &= SP_WORD_SIZE - 1; @@ -8299,12 +8605,12 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) } else { /* Move the bits down starting at least significant digit. */ - for (j = 0; i < a->used-1; i++, j++) + for (j = 0; i < a->used - 1; i++, j++) r->dp[j] = (a->dp[i] >> n) | (a->dp[i+1] << (SP_WORD_SIZE - n)); /* Most significant digit has no higher digit to pull from. */ r->dp[j] = a->dp[i] >> n; /* Set the count of used digits. */ - r->used = j + (r->dp[j] > 0); + r->used = (sp_size_t)(j + (r->dp[j] > 0)); } #ifdef WOLFSSL_SP_INT_NEGATIVE if (sp_iszero(r)) { @@ -8328,7 +8634,7 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) !defined(WOLFSSL_RSA_PUBLIC_ONLY)) static void _sp_div_same_size(sp_int* a, const sp_int* d, sp_int* r) { - unsigned int i; + sp_size_t i; /* Compare top digits of dividend with those of divisor up to last. */ for (i = d->used - 1; i > 0; i--) { @@ -8366,12 +8672,12 @@ static void _sp_div_same_size(sp_int* a, const sp_int* d, sp_int* r) static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) { int err = MP_OKAY; - unsigned int i; + sp_size_t i; #ifdef WOLFSSL_SP_SMALL int c; #else - unsigned int j; - unsigned int o; + sp_size_t j; + sp_size_t o; #ifndef SQR_MUL_ASM sp_int_sword sw; #else @@ -8384,7 +8690,7 @@ static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) sp_int_digit dt; /* Set result size to clear. */ - r->used = a->used - d->used + 1; + r->used = (sp_size_t)(a->used - d->used + 1); /* Set all potentially used digits to zero. */ for (i = 0; i < r->used; i++) { r->dp[i] = 0; @@ -8557,8 +8863,8 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, sp_int* tr = NULL; sp_int* trial = NULL; #ifdef WOLFSSL_SP_INT_NEGATIVE - unsigned int signA = MP_ZPOS; - unsigned int signD = MP_ZPOS; + sp_uint8 signA = MP_ZPOS; + sp_uint8 signD = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ /* Intermediates will always be less than or equal to dividend. */ DECL_SP_INT_ARRAY(td, used, 4); @@ -8652,7 +8958,7 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, tr = td[3]; _sp_init_size(sa, used); - _sp_init_size(tr, a->used - d->used + 2); + _sp_init_size(tr, (unsigned int)(a->used - d->used + 2)); #endif sd = td[0]; trial = td[1]; @@ -8933,7 +9239,7 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) t[0] = h; h = 0; o = 0; - for (k = 1; k <= a->used - 1; k++) { + for (k = 1; k <= (unsigned int)a->used - 1; k++) { j = (int)k; dp = a->dp; for (; j >= 0; dp++, j--) { @@ -8944,8 +9250,8 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) h = o; o = 0; } - for (; k <= (a->used - 1) * 2; k++) { - i = k - (b->used - 1); + for (; k <= ((unsigned int)a->used - 1) * 2; k++) { + i = k - (sp_size_t)(b->used - 1); dp = &b->dp[b->used - 1]; for (; i < a->used; i++, dp--) { SP_ASM_MUL_ADD(l, h, o, a->dp[i], dp[0]); @@ -8957,14 +9263,12 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) } r->dp[k] = l; XMEMCPY(r->dp, t, a->used * sizeof(sp_int_digit)); - r->used = k + 1; + r->used = (sp_size_t)(k + 1); sp_clamp(r); } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -8981,9 +9285,9 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; - unsigned int i; + sp_size_t i; int j; - unsigned int k; + sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ @@ -9011,7 +9315,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) t[0] = h; h = 0; o = 0; - for (k = 1; k <= b->used - 1; k++) { + for (k = 1; k <= (sp_size_t)(b->used - 1); k++) { i = 0; j = (int)k; for (; (i < a->used) && (j >= 0); i++, j--) { @@ -9022,9 +9326,9 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) h = o; o = 0; } - for (; k <= (a->used - 1) + (b->used - 1); k++) { + for (; k <= (sp_size_t)((a->used - 1) + (b->used - 1)); k++) { j = (int)(b->used - 1); - i = k - (unsigned int)j; + i = k - (sp_size_t)j; for (; (i < a->used) && (j >= 0); i++, j--) { SP_ASM_MUL_ADD(l, h, o, a->dp[i], b->dp[j]); } @@ -9034,15 +9338,13 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) o = 0; } t[k] = l; - r->used = k + 1; + r->used = (sp_size_t)(k + 1); XMEMCPY(r->dp, t, r->used * sizeof(sp_int_digit)); sp_clamp(r); } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -9059,9 +9361,9 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; - unsigned int i; + sp_size_t i; int j; - unsigned int k; + sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ @@ -9093,9 +9395,9 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #ifdef SP_WORD_OVERFLOW o = 0; #endif - for (k = 1; k <= (a->used - 1) + (b->used - 1); k++) { - i = k - (b->used - 1); - i &= (((unsigned int)i >> (sizeof(i) * 8 - 1)) - 1U); + for (k = 1; (int)k <= ((int)a->used - 1) + ((int)b->used - 1); k++) { + i = k - (sp_size_t)(b->used - 1); + i &= (sp_size_t)(((unsigned int)i >> (sizeof(i) * 8 - 1)) - 1U); j = (int)(k - i); for (; (i < a->used) && (j >= 0); i++, j--) { w = (sp_int_word)a->dp[i] * b->dp[j]; @@ -9118,15 +9420,13 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #endif } t[k] = (sp_int_digit)l; - r->used = k + 1; + r->used = (sp_size_t)(k + 1); XMEMCPY(r->dp, t, r->used * sizeof(sp_int_digit)); sp_clamp(r); } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -9250,9 +9550,7 @@ static int _sp_mul_4(const sp_int* a, const sp_int* b, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (w != NULL) { - XFREE(w, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(w, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -10249,9 +10547,7 @@ static int _sp_mul_16(const sp_int* a, const sp_int* b, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -11057,9 +11353,7 @@ static int _sp_mul_24(const sp_int* a, const sp_int* b, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -11747,7 +12041,7 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - unsigned int sign = MP_ZPOS; + sp_uint8 sign = MP_ZPOS; #endif if ((a == NULL) || (b == NULL) || (r == NULL)) { @@ -12140,8 +12434,10 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, ALLOC_SP_INT(d, m->used + 1, err, NULL); if (err == MP_OKAY) { - mp_init(d); + err = sp_init_size(d, m->used + 1); + } + if (err == MP_OKAY) { /* 1. x = m, y = a, b = 1, c = 0 */ if (a != y) { _sp_copy(a, y); @@ -12302,7 +12598,7 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) err = sp_init_size(b, m->used + 1); } if (err == MP_OKAY) { - err = sp_init_size(c, 2 * m->used + 1); + err = sp_init_size(c, (sp_size_t)(2 * m->used + 1)); } if (err == MP_OKAY) { @@ -12506,12 +12802,12 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, t = pre[CT_INV_MOD_PRE_CNT + 0]; e = pre[CT_INV_MOD_PRE_CNT + 1]; /* Space for sqr and mul result. */ - _sp_init_size(t, m->used * 2 + 1); + _sp_init_size(t, (sp_size_t)(m->used * 2 + 1)); /* e = mod - 2 */ - _sp_init_size(e, m->used + 1); + _sp_init_size(e, (sp_size_t)(m->used + 1)); /* Create pre-computation results: ((2^(1..8))-1).a. */ - _sp_init_size(pre[0], m->used * 2 + 1); + _sp_init_size(pre[0], (sp_size_t)(m->used * 2 + 1)); /* 1. pre[0] = 2^0 * a mod m * Start with 1.a = a. */ @@ -12522,7 +12818,7 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, for (i = 1; (err == MP_OKAY) && (i < CT_INV_MOD_PRE_CNT); i++) { /* 2.1 pre[i-1] = ((pre[i-1] ^ 2) * a) mod m */ /* Previous value ..1 -> ..10 */ - _sp_init_size(pre[i], m->used * 2 + 1); + _sp_init_size(pre[i], (sp_size_t)(m->used * 2 + 1)); err = sp_sqr(pre[i-1], pre[i]); if (err == MP_OKAY) { err = _sp_mont_red(pre[i], m, mp, 0); @@ -12748,10 +13044,10 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, #endif if (err == MP_OKAY) { /* Initialize temporaries. */ - _sp_init_size(t[0], 2 * m->used + 1); - _sp_init_size(t[1], 2 * m->used + 1); + _sp_init_size(t[0], (sp_size_t)(m->used * 2 + 1)); + _sp_init_size(t[1], (sp_size_t)(m->used * 2 + 1)); #ifndef WC_NO_CACHE_RESISTANT - _sp_init_size(t[2], 2 * m->used + 1); + _sp_init_size(t[2], (sp_size_t)(m->used * 2 + 1)); #endif /* 2. t[0] = b mod m @@ -12979,10 +13275,10 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, 4, err, NULL); if (err == MP_OKAY) { /* Initialize temporaries. */ - _sp_init_size(t[0], m->used * 2 + 1); - _sp_init_size(t[1], m->used * 2 + 1); - _sp_init_size(t[2], m->used * 2 + 1); - _sp_init_size(t[3], m->used * 2 + 1); + _sp_init_size(t[0], (sp_size_t)(m->used * 2 + 1)); + _sp_init_size(t[1], (sp_size_t)(m->used * 2 + 1)); + _sp_init_size(t[2], (sp_size_t)(m->used * 2 + 1)); + _sp_init_size(t[3], (sp_size_t)(m->used * 2 + 1)); /* 1. Ensure base is less than modulus. */ if (_sp_cmp_abs(b, m) != MP_LT) { @@ -13521,9 +13817,9 @@ static int _sp_exptmod_base_2(const sp_int* e, int digits, const sp_int* m, a = d[0]; tr = d[1]; - _sp_init_size(a, m->used * 2 + 1); + _sp_init_size(a, (sp_size_t)(m->used * 2 + 1)); #endif - _sp_init_size(tr, m->used * 2 + 1); + _sp_init_size(tr, (sp_size_t)(m->used * 2 + 1)); } @@ -13664,7 +13960,7 @@ static int _sp_exptmod_base_2(const sp_int* e, int digits, const sp_int* m, #ifndef WC_NO_HARDEN FREE_SP_INT_ARRAY(d, NULL); #else - FREE_SP_INT(tr, m->used * 2 + 1); + FREE_SP_INT(tr, NULL); #endif return err; } @@ -13983,10 +14279,10 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, /* Initialize all allocated */ for (i = 0; i < preCnt; i++) { - _sp_init_size(t[i], m->used * 2 + 1); + _sp_init_size(t[i], (sp_size_t)(m->used * 2 + 1)); } - _sp_init_size(tr, m->used * 2 + 1); - _sp_init_size(bm, m->used * 2 + 1); + _sp_init_size(tr, (sp_size_t)(m->used * 2 + 1)); + _sp_init_size(bm, (sp_size_t)(m->used * 2 + 1)); /* 1. Ensure base is less than modulus. */ if (_sp_cmp_abs(b, m) != MP_LT) { @@ -14441,8 +14737,8 @@ int sp_div_2d(const sp_int* a, int e, sp_int* r, sp_int* rem) } if ((err == MP_OKAY) && (rem != NULL)) { /* Set used and mask off top digit of remainder. */ - rem->used = ((unsigned int)e + SP_WORD_SIZE - 1) >> - SP_WORD_SHIFT; + rem->used = (sp_size_t)((e + SP_WORD_SIZE - 1) >> + SP_WORD_SHIFT); e &= SP_WORD_MASK; if (e > 0) { rem->dp[rem->used - 1] &= ((sp_int_digit)1 << e) - 1; @@ -14476,7 +14772,7 @@ int sp_div_2d(const sp_int* a, int e, sp_int* r, sp_int* rem) int sp_mod_2d(const sp_int* a, int e, sp_int* r) { int err = MP_OKAY; - unsigned int digits = ((unsigned int)e + SP_WORD_SIZE - 1) >> SP_WORD_SHIFT; + sp_size_t digits = (sp_size_t)((e + SP_WORD_SIZE - 1) >> SP_WORD_SHIFT); if ((a == NULL) || (r == NULL) || (e < 0)) { err = MP_VAL; @@ -14557,7 +14853,8 @@ int sp_mul_2d(const sp_int* a, int e, sp_int* r) /* Ensure result has enough allocated digits for result. */ if ((err == MP_OKAY) && - ((unsigned int)(sp_count_bits(a) + e) > r->size * SP_WORD_SIZE)) { + ((unsigned int)(sp_count_bits(a) + e) > + (unsigned int)r->size * SP_WORD_SIZE)) { err = MP_VAL; } @@ -14607,9 +14904,9 @@ int sp_mul_2d(const sp_int* a, int e, sp_int* r) static int _sp_sqr(const sp_int* a, sp_int* r) { int err = MP_OKAY; - unsigned int i; + sp_size_t i; int j; - unsigned int k; + sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ @@ -14649,7 +14946,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) t[0] = h; h = 0; o = 0; - for (k = 1; k < (a->used + 1) / 2; k++) { + for (k = 1; k < (sp_size_t)((a->used + 1) / 2); k++) { i = k; j = (int)(k - 1); for (; (j >= 0); i++, j--) { @@ -14661,7 +14958,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) o = 0; SP_ASM_SQR_ADD(l, h, o, a->dp[k]); - i = k + 1; + i = (sp_size_t)(k + 1); j = (int)(k - 1); for (; (j >= 0); i++, j--) { SP_ASM_MUL_ADD2(l, h, o, a->dp[i], a->dp[j]); @@ -14683,7 +14980,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) o = 0; SP_ASM_SQR_ADD(l, h, o, a->dp[k]); - i = k + 1; + i = (sp_size_t)(k + 1); j = (int)(k - 1); for (; (i < a->used); i++, j--) { SP_ASM_MUL_ADD2(l, h, o, a->dp[i], a->dp[j]); @@ -14696,7 +14993,8 @@ static int _sp_sqr(const sp_int* a, sp_int* r) p = r->dp; } r->dp[k * 2 - 1] = l; - XMEMCPY(r->dp, t, (((a->used + 1) / 2) * 2 + 1) * sizeof(sp_int_digit)); + XMEMCPY(r->dp, t, (size_t)(((a->used + 1) / 2) * 2 + 1) * + sizeof(sp_int_digit)); } if (err == MP_OKAY) { @@ -14705,9 +15003,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -14723,9 +15019,9 @@ static int _sp_sqr(const sp_int* a, sp_int* r) static int _sp_sqr(const sp_int* a, sp_int* r) { int err = MP_OKAY; - unsigned int i; + sp_size_t i; int j; - unsigned int k; + sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ @@ -14763,7 +15059,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #ifdef SP_WORD_OVERFLOW o = 0; #endif - for (k = 1; k <= (a->used - 1) * 2; k++) { + for (k = 1; k <= (sp_size_t)((a->used - 1) * 2); k++) { i = k / 2; j = (int)(k - i); if (i == (unsigned int)j) { @@ -14806,15 +15102,13 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #endif } t[k] = (sp_int_digit)l; - r->used = k + 1; + r->used = (sp_size_t)(k + 1); XMEMCPY(r->dp, t, r->used * sizeof(sp_int_digit)); sp_clamp(r); } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -14926,9 +15220,7 @@ static int _sp_sqr_4(const sp_int* a, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (w != NULL) { - XFREE(w, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(w, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -15753,9 +16045,7 @@ static int _sp_sqr_16(const sp_int* a, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -16328,9 +16618,7 @@ static int _sp_sqr_24(const sp_int* a, sp_int* r) } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - if (t != NULL) { - XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); - } + XFREE(t, NULL, DYNAMIC_TYPE_BIGINT); #endif return err; } @@ -17167,7 +17455,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) /* Adding numbers into m->used * 2 digits - zero out unused digits. */ #ifndef WOLFSSL_NO_CT_OPS if (ct) { - for (i = 0; i < m->used * 2; i++) { + for (i = 0; i < (unsigned int)m->used * 2; i++) { a->dp[i] &= (sp_int_digit) (sp_int_sdigit)ctMaskIntGTE((int)(a->used-1), (int)i); @@ -17176,7 +17464,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) else #endif /* !WOLFSSL_NO_CT_OPS */ { - for (i = a->used; i < m->used * 2; i++) { + for (i = a->used; i < (unsigned int)m->used * 2; i++) { a->dp[i] = 0; } } @@ -17214,7 +17502,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) /* 2.1. mu = (mp * DigitMask(a, i)) & WORD_MASK */ mu = mp * a->dp[i]; /* 2.2. If i == NumDigits(m)-1 and mask != 0 then mu & = mask */ - if ((i == m->used - 1) && (mask != 0)) { + if ((i == (unsigned int)m->used - 1) && (mask != 0)) { mu &= mask; } @@ -17224,7 +17512,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) a->dp[i] = (sp_int_digit)w; w >>= SP_WORD_SIZE; /* 2.4. For j = 1 up to NumDigits(m)-2 */ - for (j = 1; j < m->used - 1; j++) { + for (j = 1; j < (unsigned int)m->used - 1; j++) { /* 2.4.1 a += mu * DigitMask(m, j) */ w += a->dp[i + j]; w += (sp_int_word)mu * m->dp[j]; @@ -17246,7 +17534,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) a->dp[m->used * 2 - 1] = (sp_int_digit)o; o >>= SP_WORD_SIZE; a->dp[m->used * 2] = (sp_int_digit)o; - a->used = m->used * 2 + 1; + a->used = (sp_size_t)(m->used * 2 + 1); } if (!ct) { @@ -17295,7 +17583,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) #ifndef WOLFSSL_NO_CT_OPS if (ct) { - for (i = 0; i < m->used * 2; i++) { + for (i = 0; i < (unsigned int)m->used * 2; i++) { a->dp[i] &= (sp_int_digit) (sp_int_sdigit)ctMaskIntGTE((int)(a->used-1), (int)i); @@ -17304,7 +17592,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) else #endif { - for (i = a->used; i < m->used * 2; i++) { + for (i = a->used; i < (unsigned int)m->used * 2; i++) { a->dp[i] = 0; } } @@ -17325,7 +17613,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) SP_ASM_ADDC(l, h, a->dp[1]); a->dp[1] = l; a->dp[2] = h; - a->used = m->used * 2 + 1; + a->used = (sp_size_t)(m->used * 2 + 1); /* mp is SP_WORD_SIZE */ bits = SP_WORD_SIZE; } @@ -17475,7 +17763,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) h = 0; SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); l = h; - for (j = 1; j + 1 < m->used - 1; j += 2) { + for (j = 1; j + 1 < (unsigned int)m->used - 1; j += 2) { h = 0; SP_ASM_ADDC(l, h, ad[j]); SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); @@ -17485,7 +17773,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) SP_ASM_MUL_ADD_NO(h, l, mu, *(md++)); ad[j] = h; } - for (; j < m->used - 1; j++) { + for (; j < (unsigned int)m->used - 1; j++) { h = 0; SP_ASM_ADDC(l, h, ad[j]); SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); @@ -17536,7 +17824,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) /* 2.1. mu = (mp * DigitMask(a, i)) & WORD_MASK */ mu = mp * ad[0]; /* 2.2. If i == NumDigits(m)-1 and mask != 0 then mu & = mask */ - if ((i == m->used - 1) && (mask != 0)) { + if ((i == (unsigned int)m->used - 1) && (mask != 0)) { mu &= mask; } @@ -17547,7 +17835,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) ad[0] = l; l = h; /* 2.4. If i == NumDigits(m)-1 and mask != 0 then mu & = mask */ - for (j = 1; j + 1 < m->used - 1; j += 2) { + for (j = 1; j + 1 < (unsigned int)m->used - 1; j += 2) { h = 0; /* 2.4.1. a += mu * DigitMask(m, j) */ SP_ASM_ADDC(l, h, ad[j + 0]); @@ -17559,7 +17847,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) SP_ASM_MUL_ADD_NO(h, l, mu, *(md++)); ad[j + 1] = h; } - for (; j < m->used - 1; j++) { + for (; j < (unsigned int)m->used - 1; j++) { h = 0; /* 2.4.1. a += mu * DigitMask(m, j) */ SP_ASM_ADDC(l, h, ad[j]); @@ -17582,7 +17870,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) SP_ASM_ADDC(l, h, a->dp[m->used * 2 - 1]); a->dp[m->used * 2 - 1] = l; a->dp[m->used * 2] = h; - a->used = m->used * 2 + 1; + a->used = (sp_size_t)(m->used * 2 + 1); } if (!ct) { @@ -17653,7 +17941,7 @@ int sp_mont_red_ex(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) * * Used when performing Montgomery Reduction. * m must be odd. - * Jeffrey Hurchalla’s method. + * Jeffrey Hurchalla's method. * https://arxiv.org/pdf/2204.04342.pdf * * @param [in] m SP integer that is the modulus. @@ -17734,7 +18022,7 @@ int sp_mont_norm(sp_int* norm, const sp_int* m) if (err == MP_OKAY) { /* Find top bit and ensure norm has enough space. */ bits = (unsigned int)sp_count_bits(m); - if (bits >= norm->size * SP_WORD_SIZE) { + if (bits >= (unsigned int)norm->size * SP_WORD_SIZE) { err = MP_VAL; } } @@ -17821,7 +18109,7 @@ int sp_read_unsigned_bin(sp_int* a, const byte* in, word32 inSz) int i; int j = 0; - a->used = (inSz + SP_WORD_SIZEOF - 1) / SP_WORD_SIZEOF; + a->used = (sp_size_t)((inSz + SP_WORD_SIZEOF - 1) / SP_WORD_SIZEOF); #if defined(BIG_ENDIAN_ORDER) && !defined(WOLFSSL_SP_INT_DIGIT_ALIGN) /* Data endian matches representation of number. @@ -17949,7 +18237,7 @@ int sp_to_unsigned_bin_len(const sp_int* a, byte* out, int outSz) d >>= 8; /* Stop if the output buffer is filled. */ if (j < 0) { - if ((i < a->used - 1) || (d > 0)) { + if ((i < (unsigned int)a->used - 1) || (d > 0)) { err = MP_VAL; } break; @@ -18023,7 +18311,7 @@ int sp_to_unsigned_bin_len_ct(const sp_int* a, byte* out, int outSz) out[j--] = (byte)(d & mask); d >>= 8; } - mask &= (sp_int_digit)0 - (i < a->used - 1); + mask &= (sp_int_digit)0 - (i < (unsigned int)a->used - 1); i += (unsigned int)(1 & mask); } } @@ -18039,7 +18327,7 @@ int sp_to_unsigned_bin_len_ct(const sp_int* a, byte* out, int outSz) i = 0; for (j = outSz - 1; j >= 0; j--) { out[j] = a->dp[i] & mask; - mask &= (sp_int_digit)0 - (i < a->used - 1); + mask &= (sp_int_digit)0 - (i < (unsigned int)a->used - 1); i += (unsigned int)(1 & mask); } } @@ -18095,7 +18383,7 @@ static int _sp_read_radix_16(sp_int* a, const char* in) int err = MP_OKAY; int i; unsigned int s = 0; - unsigned int j = 0; + sp_size_t j = 0; sp_int_digit d; /* Skip whitespace at end of line */ int eol_done = 0; @@ -18225,7 +18513,7 @@ int sp_read_radix(sp_int* a, const char* in, int radix) { int err = MP_OKAY; #ifdef WOLFSSL_SP_INT_NEGATIVE - unsigned int sign = MP_ZPOS; + sp_uint8 sign = MP_ZPOS; #endif if ((a == NULL) || (in == NULL)) { @@ -18702,7 +18990,7 @@ int sp_rand_prime(sp_int* r, int len, WC_RNG* rng, void* heap) r->sign = MP_ZPOS; #endif /* WOLFSSL_SP_INT_NEGATIVE */ /* Set number of digits that will be used. */ - r->used = digits; + r->used = (sp_size_t)digits; #if defined(WOLFSSL_SP_MATH_ALL) || defined(BIG_ENDIAN_ORDER) /* Calculate number of bits in last digit. */ bits = (len * 8) & SP_WORD_MASK; @@ -19039,7 +19327,7 @@ static int _sp_prime_trials(const sp_int* a, int trials, int* result) _sp_init_size(n1, a->used + 1); _sp_init_size(r, a->used + 1); - _sp_init_size(b, a->used * 2 + 1); + _sp_init_size(b, (sp_size_t)(a->used * 2 + 1)); /* Do requested number of trials of Miller-Rabin test. */ for (i = 0; i < trials; i++) { @@ -19163,8 +19451,8 @@ static int _sp_prime_random_trials(const sp_int* a, int trials, int* result, _sp_init_size(c , a->used + 1); _sp_init_size(n1, a->used + 1); - _sp_init_size(b , a->used * 2 + 1); - _sp_init_size(r , a->used * 2 + 1); + _sp_init_size(b , (sp_size_t)(a->used * 2 + 1)); + _sp_init_size(r , (sp_size_t)(a->used * 2 + 1)); _sp_sub_d(a, 2, c); diff --git a/src/wolfcrypt/src/sp_sm2_arm32.c b/src/wolfcrypt/src/sp_sm2_arm32.c index 211b143..4dc5377 100644 --- a/src/wolfcrypt/src/sp_sm2_arm32.c +++ b/src/wolfcrypt/src/sp_sm2_arm32.c @@ -1,6 +1,6 @@ /* sp_sm2_arm32.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_arm64.c b/src/wolfcrypt/src/sp_sm2_arm64.c index 5c84948..8f87711 100644 --- a/src/wolfcrypt/src/sp_sm2_arm64.c +++ b/src/wolfcrypt/src/sp_sm2_arm64.c @@ -1,6 +1,6 @@ /* sp_sm2_arm64.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_armthumb.c b/src/wolfcrypt/src/sp_sm2_armthumb.c index 5d26e27..0be6685 100644 --- a/src/wolfcrypt/src/sp_sm2_armthumb.c +++ b/src/wolfcrypt/src/sp_sm2_armthumb.c @@ -1,6 +1,6 @@ /* sp_sm2_armthumb.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_c32.c b/src/wolfcrypt/src/sp_sm2_c32.c index 41c40d1..754b80a 100644 --- a/src/wolfcrypt/src/sp_sm2_c32.c +++ b/src/wolfcrypt/src/sp_sm2_c32.c @@ -1,6 +1,6 @@ /* sp_sm2_c32.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_c64.c b/src/wolfcrypt/src/sp_sm2_c64.c index ee38016..861bfe3 100644 --- a/src/wolfcrypt/src/sp_sm2_c64.c +++ b/src/wolfcrypt/src/sp_sm2_c64.c @@ -1,6 +1,6 @@ /* sp_sm2_c64.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_cortexm.c b/src/wolfcrypt/src/sp_sm2_cortexm.c index 3bda85f..4b1083f 100644 --- a/src/wolfcrypt/src/sp_sm2_cortexm.c +++ b/src/wolfcrypt/src/sp_sm2_cortexm.c @@ -1,6 +1,6 @@ /* sp_sm2_cortexm.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_sm2_x86_64.c b/src/wolfcrypt/src/sp_sm2_x86_64.c index f73e408..24a5b9e 100644 --- a/src/wolfcrypt/src/sp_sm2_x86_64.c +++ b/src/wolfcrypt/src/sp_sm2_x86_64.c @@ -1,6 +1,6 @@ /* sp_sm2_x86_64.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/sp_x86_64.c b/src/wolfcrypt/src/sp_x86_64.c index b57f5a3..2529432 100644 --- a/src/wolfcrypt/src/sp_x86_64.c +++ b/src/wolfcrypt/src/sp_x86_64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -67,7 +67,7 @@ do { \ int ii; \ fprintf(stderr, name "=0x"); \ - for (ii = ((bits + 63) / 64) - 1; ii >= 0; ii--) \ + for (ii = (((bits) + 63) / 64) - 1; ii >= 0; ii--) \ fprintf(stderr, SP_PRINT_FMT, (var)[ii]); \ fprintf(stderr, "\n"); \ } while (0) @@ -492,8 +492,8 @@ static WC_INLINE sp_digit div_2048_word_16(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_2048_word_16(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -575,7 +575,7 @@ static WC_INLINE int sp_2048_div_16(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_2048_cond_sub_16(&t1[16], &t1[16], d, (sp_digit)0 - r1); for (i = 15; i >= 0; i--) { - sp_digit mask = 0 - (t1[16 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[16 + i] == div); sp_digit hi = t1[16 + i] + mask; r1 = div_2048_word_16(hi, t1[16 + i - 1], div); r1 |= mask; @@ -806,13 +806,12 @@ static int sp_2048_mod_exp_16(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[16], 0, sizeof(sp_digit) * 16); sp_2048_mont_reduce_16(r, m, mp); - mask = 0 - (sp_2048_cmp_16(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_16(r, m) >= 0); sp_2048_cond_sub_16(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1047,13 +1046,12 @@ static int sp_2048_mod_exp_avx2_16(sp_digit* r, const sp_digit* a, const sp_digi XMEMSET(&r[16], 0, sizeof(sp_digit) * 16); sp_2048_mont_reduce_avx2_16(r, m, mp); - mask = 0 - (sp_2048_cmp_16(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_16(r, m) >= 0); sp_2048_cond_sub_avx2_16(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1176,8 +1174,8 @@ static WC_INLINE sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -1352,7 +1350,7 @@ static WC_INLINE int sp_2048_div_32(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_2048_cond_sub_32(&t1[32], &t1[32], d, (sp_digit)0 - r1); for (i = 31; i >= 0; i--) { - sp_digit mask = 0 - (t1[32 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[32 + i] == div); sp_digit hi = t1[32 + i] + mask; r1 = div_2048_word_32(hi, t1[32 + i - 1], div); r1 |= mask; @@ -1618,13 +1616,12 @@ static int sp_2048_mod_exp_32(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1894,13 +1891,12 @@ static int sp_2048_mod_exp_avx2_32(sp_digit* r, const sp_digit* a, const sp_digi XMEMSET(&r[32], 0, sizeof(sp_digit) * 32); sp_2048_mont_reduce_avx2_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_avx2_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -1965,7 +1961,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, m = r + 32 * 2; ah = a + 32; - sp_2048_from_bin(ah, 32, in, inLen); + sp_2048_from_bin(ah, 32, in, (int)inLen); #if DIGIT_BIT >= 64 e = em->dp[0]; #else @@ -1993,7 +1989,8 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, if (err == MP_OKAY) { /* r = a ^ 0x10000 => r = a squared 16 times */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i = 15; i >= 0; i--) { sp_2048_mont_sqr_avx2_32(r, r, m, mp); } @@ -2024,7 +2021,8 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } else if (e == 0x3) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { if (err == MP_OKAY) { sp_2048_sqr_avx2_32(r, ah); err = sp_2048_mod_32_cond(r, r, m); @@ -2066,7 +2064,8 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, XMEMCPY(r, a, sizeof(sp_digit) * 32); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i--; i>=0; i--) { sp_2048_mont_sqr_avx2_32(r, r, m, mp); if (((e >> i) & 1) == 1) { @@ -2105,8 +2104,7 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -2187,7 +2185,7 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, r = a; - sp_2048_from_bin(a, 32, in, inLen); + sp_2048_from_bin(a, 32, in, (int)inLen); sp_2048_from_mp(d, 32, dm); sp_2048_from_mp(m, 32, mm); err = sp_2048_mod_exp_32(r, a, d, 2048, m, 0); @@ -2305,14 +2303,16 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, tmpb = tmpa + 32; r = a + 32; - sp_2048_from_bin(a, 32, in, inLen); + sp_2048_from_bin(a, 32, in, (int)inLen); sp_2048_from_mp(p, 16, pm); sp_2048_from_mp(q, 16, qm); sp_2048_from_mp(dp, 16, dpm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_16(tmpa, a, dp, 1024, p, 1); + } else #endif err = sp_2048_mod_exp_16(tmpa, a, dp, 1024, p, 1); @@ -2320,8 +2320,10 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { sp_2048_from_mp(dq, 16, dqm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_16(tmpb, a, dq, 1024, q, 1); + } else #endif err = sp_2048_mod_exp_16(tmpb, a, dq, 1024, q, 1); @@ -2330,7 +2332,8 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { c = sp_2048_sub_in_place_16(tmpa, tmpb); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { c += sp_2048_cond_add_avx2_16(tmpa, tmpa, p, c); sp_2048_cond_add_avx2_16(tmpa, tmpa, p, c); } @@ -2343,7 +2346,8 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, sp_2048_from_mp(qi, 16, qim); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_2048_mul_avx2_16(tmpa, tmpa, qi); } else @@ -2356,7 +2360,8 @@ int sp_RsaPrivate_2048(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_2048_mul_avx2_16(tmpa, q, tmpa); } else @@ -2519,8 +2524,10 @@ int sp_ModExp_2048(const mp_int* base, const mp_int* exp, const mp_int* mod, sp_2048_from_mp(m, 32, mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_32(r, b, e, expBits, m, 0); + } else #endif err = sp_2048_mod_exp_32(r, b, e, expBits, m, 0); @@ -2531,14 +2538,12 @@ int sp_ModExp_2048(const mp_int* base, const mp_int* exp, const mp_int* mod, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 32); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -2682,13 +2687,12 @@ static int sp_2048_mod_exp_2_avx2_32(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32); sp_2048_mont_reduce_avx2_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_avx2_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2821,13 +2825,12 @@ static int sp_2048_mod_exp_2_32(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[32], 0, sizeof(sp_digit) * 32); sp_2048_mont_reduce_32(r, m, mp); - mask = 0 - (sp_2048_cmp_32(r, m) >= 0); + mask = (sp_digit)0 - (sp_2048_cmp_32(r, m) >= 0); sp_2048_cond_sub_32(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -2897,27 +2900,31 @@ int sp_DhExp_2048(const mp_int* base, const byte* exp, word32 expLen, if (err == MP_OKAY) { sp_2048_from_mp(b, 32, base); - sp_2048_from_bin(e, 32, exp, expLen); + sp_2048_from_bin(e, 32, exp, (int)expLen); sp_2048_from_mp(m, 32, mod); #ifdef HAVE_FFDHE_2048 if (base->used == 1 && base->dp[0] == 2 && m[31] == (sp_digit)-1) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_2048_mod_exp_2_avx2_32(r, e, expLen * 8, m); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_2048_mod_exp_2_avx2_32(r, e, (int)expLen * 8, m); + } else #endif - err = sp_2048_mod_exp_2_32(r, e, expLen * 8, m); + err = sp_2048_mod_exp_2_32(r, e, (int)expLen * 8, m); } else #endif { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_2048_mod_exp_avx2_32(r, b, e, expLen * 8, m, 0); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_2048_mod_exp_avx2_32(r, b, e, (int)expLen * 8, m, 0); + } else #endif - err = sp_2048_mod_exp_32(r, b, e, expLen * 8, m, 0); + err = sp_2048_mod_exp_32(r, b, e, (int)expLen * 8, m, 0); } } @@ -2932,14 +2939,12 @@ int sp_DhExp_2048(const mp_int* base, const byte* exp, word32 expLen, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 32); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -3010,8 +3015,10 @@ int sp_ModExp_1024(const mp_int* base, const mp_int* exp, const mp_int* mod, sp_2048_from_mp(m, 16, mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_16(r, b, e, expBits, m, 0); + } else #endif err = sp_2048_mod_exp_16(r, b, e, expBits, m, 0); @@ -3023,14 +3030,12 @@ int sp_ModExp_1024(const mp_int* base, const mp_int* exp, const mp_int* mod, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 16); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -3494,8 +3499,8 @@ static WC_INLINE sp_digit div_3072_word_24(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_3072_word_24(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -3577,7 +3582,7 @@ static WC_INLINE int sp_3072_div_24(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_3072_cond_sub_24(&t1[24], &t1[24], d, (sp_digit)0 - r1); for (i = 23; i >= 0; i--) { - sp_digit mask = 0 - (t1[24 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[24 + i] == div); sp_digit hi = t1[24 + i] + mask; r1 = div_3072_word_24(hi, t1[24 + i - 1], div); r1 |= mask; @@ -3808,13 +3813,12 @@ static int sp_3072_mod_exp_24(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[24], 0, sizeof(sp_digit) * 24); sp_3072_mont_reduce_24(r, m, mp); - mask = 0 - (sp_3072_cmp_24(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_24(r, m) >= 0); sp_3072_cond_sub_24(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4049,13 +4053,12 @@ static int sp_3072_mod_exp_avx2_24(sp_digit* r, const sp_digit* a, const sp_digi XMEMSET(&r[24], 0, sizeof(sp_digit) * 24); sp_3072_mont_reduce_avx2_24(r, m, mp); - mask = 0 - (sp_3072_cmp_24(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_24(r, m) >= 0); sp_3072_cond_sub_avx2_24(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4178,8 +4181,8 @@ static WC_INLINE sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -4354,7 +4357,7 @@ static WC_INLINE int sp_3072_div_48(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_3072_cond_sub_48(&t1[48], &t1[48], d, (sp_digit)0 - r1); for (i = 47; i >= 0; i--) { - sp_digit mask = 0 - (t1[48 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[48 + i] == div); sp_digit hi = t1[48 + i] + mask; r1 = div_3072_word_48(hi, t1[48 + i - 1], div); r1 |= mask; @@ -4568,13 +4571,12 @@ static int sp_3072_mod_exp_48(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4792,13 +4794,12 @@ static int sp_3072_mod_exp_avx2_48(sp_digit* r, const sp_digit* a, const sp_digi XMEMSET(&r[48], 0, sizeof(sp_digit) * 48); sp_3072_mont_reduce_avx2_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_avx2_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -4863,7 +4864,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, m = r + 48 * 2; ah = a + 48; - sp_3072_from_bin(ah, 48, in, inLen); + sp_3072_from_bin(ah, 48, in, (int)inLen); #if DIGIT_BIT >= 64 e = em->dp[0]; #else @@ -4891,7 +4892,8 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, if (err == MP_OKAY) { /* r = a ^ 0x10000 => r = a squared 16 times */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i = 15; i >= 0; i--) { sp_3072_mont_sqr_avx2_48(r, r, m, mp); } @@ -4922,7 +4924,8 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } else if (e == 0x3) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { if (err == MP_OKAY) { sp_3072_sqr_avx2_48(r, ah); err = sp_3072_mod_48_cond(r, r, m); @@ -4964,7 +4967,8 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, XMEMCPY(r, a, sizeof(sp_digit) * 48); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i--; i>=0; i--) { sp_3072_mont_sqr_avx2_48(r, r, m, mp); if (((e >> i) & 1) == 1) { @@ -5003,8 +5007,7 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -5085,7 +5088,7 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, r = a; - sp_3072_from_bin(a, 48, in, inLen); + sp_3072_from_bin(a, 48, in, (int)inLen); sp_3072_from_mp(d, 48, dm); sp_3072_from_mp(m, 48, mm); err = sp_3072_mod_exp_48(r, a, d, 3072, m, 0); @@ -5203,14 +5206,16 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, tmpb = tmpa + 48; r = a + 48; - sp_3072_from_bin(a, 48, in, inLen); + sp_3072_from_bin(a, 48, in, (int)inLen); sp_3072_from_mp(p, 24, pm); sp_3072_from_mp(q, 24, qm); sp_3072_from_mp(dp, 24, dpm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_3072_mod_exp_avx2_24(tmpa, a, dp, 1536, p, 1); + } else #endif err = sp_3072_mod_exp_24(tmpa, a, dp, 1536, p, 1); @@ -5218,8 +5223,10 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { sp_3072_from_mp(dq, 24, dqm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_3072_mod_exp_avx2_24(tmpb, a, dq, 1536, q, 1); + } else #endif err = sp_3072_mod_exp_24(tmpb, a, dq, 1536, q, 1); @@ -5228,7 +5235,8 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { c = sp_3072_sub_in_place_24(tmpa, tmpb); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { c += sp_3072_cond_add_avx2_24(tmpa, tmpa, p, c); sp_3072_cond_add_avx2_24(tmpa, tmpa, p, c); } @@ -5241,7 +5249,8 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, sp_3072_from_mp(qi, 24, qim); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_3072_mul_avx2_24(tmpa, tmpa, qi); } else @@ -5254,7 +5263,8 @@ int sp_RsaPrivate_3072(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_3072_mul_avx2_24(tmpa, q, tmpa); } else @@ -5417,8 +5427,10 @@ int sp_ModExp_3072(const mp_int* base, const mp_int* exp, const mp_int* mod, sp_3072_from_mp(m, 48, mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_3072_mod_exp_avx2_48(r, b, e, expBits, m, 0); + } else #endif err = sp_3072_mod_exp_48(r, b, e, expBits, m, 0); @@ -5429,14 +5441,12 @@ int sp_ModExp_3072(const mp_int* base, const mp_int* exp, const mp_int* mod, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 48); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -5580,13 +5590,12 @@ static int sp_3072_mod_exp_2_avx2_48(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48); sp_3072_mont_reduce_avx2_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_avx2_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5719,13 +5728,12 @@ static int sp_3072_mod_exp_2_48(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[48], 0, sizeof(sp_digit) * 48); sp_3072_mont_reduce_48(r, m, mp); - mask = 0 - (sp_3072_cmp_48(r, m) >= 0); + mask = (sp_digit)0 - (sp_3072_cmp_48(r, m) >= 0); sp_3072_cond_sub_48(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -5795,27 +5803,31 @@ int sp_DhExp_3072(const mp_int* base, const byte* exp, word32 expLen, if (err == MP_OKAY) { sp_3072_from_mp(b, 48, base); - sp_3072_from_bin(e, 48, exp, expLen); + sp_3072_from_bin(e, 48, exp, (int)expLen); sp_3072_from_mp(m, 48, mod); #ifdef HAVE_FFDHE_3072 if (base->used == 1 && base->dp[0] == 2 && m[47] == (sp_digit)-1) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_3072_mod_exp_2_avx2_48(r, e, expLen * 8, m); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_3072_mod_exp_2_avx2_48(r, e, (int)expLen * 8, m); + } else #endif - err = sp_3072_mod_exp_2_48(r, e, expLen * 8, m); + err = sp_3072_mod_exp_2_48(r, e, (int)expLen * 8, m); } else #endif { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_3072_mod_exp_avx2_48(r, b, e, expLen * 8, m, 0); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_3072_mod_exp_avx2_48(r, b, e, (int)expLen * 8, m, 0); + } else #endif - err = sp_3072_mod_exp_48(r, b, e, expLen * 8, m, 0); + err = sp_3072_mod_exp_48(r, b, e, (int)expLen * 8, m, 0); } } @@ -5830,14 +5842,12 @@ int sp_DhExp_3072(const mp_int* base, const byte* exp, word32 expLen, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 48); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -5908,8 +5918,10 @@ int sp_ModExp_1536(const mp_int* base, const mp_int* exp, const mp_int* mod, sp_3072_from_mp(m, 24, mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_3072_mod_exp_avx2_24(r, b, e, expBits, m, 0); + } else #endif err = sp_3072_mod_exp_24(r, b, e, expBits, m, 0); @@ -5921,14 +5933,12 @@ int sp_ModExp_1536(const mp_int* base, const mp_int* exp, const mp_int* mod, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 24); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -6302,8 +6312,8 @@ static WC_INLINE sp_digit div_4096_word_64(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_4096_word_64(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -6478,7 +6488,7 @@ static WC_INLINE int sp_4096_div_64(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_4096_cond_sub_64(&t1[64], &t1[64], d, (sp_digit)0 - r1); for (i = 63; i >= 0; i--) { - sp_digit mask = 0 - (t1[64 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[64 + i] == div); sp_digit hi = t1[64 + i] + mask; r1 = div_4096_word_64(hi, t1[64 + i - 1], div); r1 |= mask; @@ -6692,13 +6702,12 @@ static int sp_4096_mod_exp_64(sp_digit* r, const sp_digit* a, const sp_digit* e, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64); sp_4096_mont_reduce_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6916,13 +6925,12 @@ static int sp_4096_mod_exp_avx2_64(sp_digit* r, const sp_digit* a, const sp_digi XMEMSET(&r[64], 0, sizeof(sp_digit) * 64); sp_4096_mont_reduce_avx2_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_avx2_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -6987,7 +6995,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, m = r + 64 * 2; ah = a + 64; - sp_4096_from_bin(ah, 64, in, inLen); + sp_4096_from_bin(ah, 64, in, (int)inLen); #if DIGIT_BIT >= 64 e = em->dp[0]; #else @@ -7015,7 +7023,8 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, if (err == MP_OKAY) { /* r = a ^ 0x10000 => r = a squared 16 times */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i = 15; i >= 0; i--) { sp_4096_mont_sqr_avx2_64(r, r, m, mp); } @@ -7046,7 +7055,8 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } else if (e == 0x3) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { if (err == MP_OKAY) { sp_4096_sqr_avx2_64(r, ah); err = sp_4096_mod_64_cond(r, r, m); @@ -7088,7 +7098,8 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, XMEMCPY(r, a, sizeof(sp_digit) * 64); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { for (i--; i>=0; i--) { sp_4096_mont_sqr_avx2_64(r, r, m, mp); if (((e >> i) & 1) == 1) { @@ -7127,8 +7138,7 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, } #ifdef WOLFSSL_SP_SMALL_STACK - if (a != NULL) - XFREE(a, NULL, DYNAMIC_TYPE_RSA); + XFREE(a, NULL, DYNAMIC_TYPE_RSA); #endif return err; @@ -7209,7 +7219,7 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, r = a; - sp_4096_from_bin(a, 64, in, inLen); + sp_4096_from_bin(a, 64, in, (int)inLen); sp_4096_from_mp(d, 64, dm); sp_4096_from_mp(m, 64, mm); err = sp_4096_mod_exp_64(r, a, d, 4096, m, 0); @@ -7327,14 +7337,16 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, tmpb = tmpa + 64; r = a + 64; - sp_4096_from_bin(a, 64, in, inLen); + sp_4096_from_bin(a, 64, in, (int)inLen); sp_4096_from_mp(p, 32, pm); sp_4096_from_mp(q, 32, qm); sp_4096_from_mp(dp, 32, dpm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_32(tmpa, a, dp, 2048, p, 1); + } else #endif err = sp_2048_mod_exp_32(tmpa, a, dp, 2048, p, 1); @@ -7342,8 +7354,10 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { sp_4096_from_mp(dq, 32, dqm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_2048_mod_exp_avx2_32(tmpb, a, dq, 2048, q, 1); + } else #endif err = sp_2048_mod_exp_32(tmpb, a, dq, 2048, q, 1); @@ -7352,7 +7366,8 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { c = sp_2048_sub_in_place_32(tmpa, tmpb); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { c += sp_4096_cond_add_avx2_32(tmpa, tmpa, p, c); sp_4096_cond_add_avx2_32(tmpa, tmpa, p, c); } @@ -7365,7 +7380,8 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, sp_2048_from_mp(qi, 32, qim); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_2048_mul_avx2_32(tmpa, tmpa, qi); } else @@ -7378,7 +7394,8 @@ int sp_RsaPrivate_4096(const byte* in, word32 inLen, const mp_int* dm, if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_2048_mul_avx2_32(tmpa, q, tmpa); } else @@ -7541,8 +7558,10 @@ int sp_ModExp_4096(const mp_int* base, const mp_int* exp, const mp_int* mod, sp_4096_from_mp(m, 64, mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_4096_mod_exp_avx2_64(r, b, e, expBits, m, 0); + } else #endif err = sp_4096_mod_exp_64(r, b, e, expBits, m, 0); @@ -7553,14 +7572,12 @@ int sp_ModExp_4096(const mp_int* base, const mp_int* exp, const mp_int* mod, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 64); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -7704,13 +7721,12 @@ static int sp_4096_mod_exp_2_avx2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64); sp_4096_mont_reduce_avx2_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_avx2_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -7843,13 +7859,12 @@ static int sp_4096_mod_exp_2_64(sp_digit* r, const sp_digit* e, int bits, XMEMSET(&r[64], 0, sizeof(sp_digit) * 64); sp_4096_mont_reduce_64(r, m, mp); - mask = 0 - (sp_4096_cmp_64(r, m) >= 0); + mask = (sp_digit)0 - (sp_4096_cmp_64(r, m) >= 0); sp_4096_cond_sub_64(r, r, m, mask); } #ifdef WOLFSSL_SP_SMALL_STACK - if (td != NULL) - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; @@ -7919,27 +7934,31 @@ int sp_DhExp_4096(const mp_int* base, const byte* exp, word32 expLen, if (err == MP_OKAY) { sp_4096_from_mp(b, 64, base); - sp_4096_from_bin(e, 64, exp, expLen); + sp_4096_from_bin(e, 64, exp, (int)expLen); sp_4096_from_mp(m, 64, mod); #ifdef HAVE_FFDHE_4096 if (base->used == 1 && base->dp[0] == 2 && m[63] == (sp_digit)-1) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_4096_mod_exp_2_avx2_64(r, e, expLen * 8, m); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_4096_mod_exp_2_avx2_64(r, e, (int)expLen * 8, m); + } else #endif - err = sp_4096_mod_exp_2_64(r, e, expLen * 8, m); + err = sp_4096_mod_exp_2_64(r, e, (int)expLen * 8, m); } else #endif { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) - err = sp_4096_mod_exp_avx2_64(r, b, e, expLen * 8, m, 0); + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { + err = sp_4096_mod_exp_avx2_64(r, b, e, (int)expLen * 8, m, 0); + } else #endif - err = sp_4096_mod_exp_64(r, b, e, expLen * 8, m, 0); + err = sp_4096_mod_exp_64(r, b, e, (int)expLen * 8, m, 0); } } @@ -7954,14 +7973,12 @@ int sp_DhExp_4096(const mp_int* base, const byte* exp, word32 expLen, } #ifdef WOLFSSL_SP_SMALL_STACK - if (b != NULL) - XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(b, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (e != NULL) { XMEMSET(e, 0, 64); XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER); } - if (m != NULL) - XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); #else XMEMSET(e, 0, sizeof(e)); #endif @@ -8119,14 +8136,14 @@ static int sp_256_mod_mul_norm_4(sp_digit* r, const sp_digit* a, const sp_digit* (void)m; - a32[0] = a[0] & 0xffffffff; - a32[1] = a[0] >> 32; - a32[2] = a[1] & 0xffffffff; - a32[3] = a[1] >> 32; - a32[4] = a[2] & 0xffffffff; - a32[5] = a[2] >> 32; - a32[6] = a[3] & 0xffffffff; - a32[7] = a[3] >> 32; + a32[0] = (int64_t)(a[0] & 0xffffffff); + a32[1] = (int64_t)(a[0] >> 32); + a32[2] = (int64_t)(a[1] & 0xffffffff); + a32[3] = (int64_t)(a[1] >> 32); + a32[4] = (int64_t)(a[2] & 0xffffffff); + a32[5] = (int64_t)(a[2] >> 32); + a32[6] = (int64_t)(a[3] & 0xffffffff); + a32[7] = (int64_t)(a[3] >> 32); /* 1 1 0 -1 -1 -1 -1 0 */ t[0] = 0 + a32[0] + a32[1] - a32[3] - a32[4] - a32[5] - a32[6]; @@ -8176,10 +8193,10 @@ static int sp_256_mod_mul_norm_4(sp_digit* r, const sp_digit* a, const sp_digit* t[5] += t[4] >> 32; t[4] &= 0xffffffff; t[6] += t[5] >> 32; t[5] &= 0xffffffff; t[7] += t[6] >> 32; t[6] &= 0xffffffff; - r[0] = (t[1] << 32) | t[0]; - r[1] = (t[3] << 32) | t[2]; - r[2] = (t[5] << 32) | t[4]; - r[3] = (t[7] << 32) | t[6]; + r[0] = (sp_digit)((t[1] << 32) | t[0]); + r[1] = (sp_digit)((t[3] << 32) | t[2]); + r[2] = (sp_digit)((t[5] << 32) | t[4]); + r[3] = (sp_digit)((t[7] << 32) | t[6]); return MP_OKAY; } @@ -8554,7 +8571,7 @@ static void sp_256_map_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_4(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_4(r->x, p256_mod); - sp_256_cond_sub_4(r->x, r->x, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->x, r->x, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->x); /* y /= z^3 */ @@ -8563,7 +8580,7 @@ static void sp_256_map_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_4(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_4(r->y, p256_mod); - sp_256_cond_sub_4(r->y, r->y, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->y, r->y, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -8980,8 +8997,8 @@ static void sp_256_proj_point_add_4(sp_point_256* r, sp_256_mont_sub_4(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -8998,7 +9015,7 @@ static void sp_256_proj_point_add_4(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -9170,8 +9187,8 @@ static int sp_256_proj_point_add_4_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -9188,7 +9205,7 @@ static int sp_256_proj_point_add_4_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -9399,7 +9416,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -9575,10 +9592,8 @@ static int sp_256_ecc_mulmod_win_add_sub_4(sp_point_256* r, const sp_point_256* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -9728,7 +9743,7 @@ static void sp_256_map_avx2_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_avx2_4(r->x, p256_mod, p256_mp_mod); /* Reduce x to less than modulus */ n = sp_256_cmp_4(r->x, p256_mod); - sp_256_cond_sub_4(r->x, r->x, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->x, r->x, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->x); /* y /= z^3 */ @@ -9737,7 +9752,7 @@ static void sp_256_map_avx2_4(sp_point_256* r, const sp_point_256* p, sp_256_mont_reduce_avx2_4(r->y, p256_mod, p256_mp_mod); /* Reduce y to less than modulus */ n = sp_256_cmp_4(r->y, p256_mod); - sp_256_cond_sub_4(r->y, r->y, p256_mod, ~(n >> 63)); + sp_256_cond_sub_4(r->y, r->y, p256_mod, (sp_digit)~(n >> 63)); sp_256_norm_4(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -10100,8 +10115,8 @@ static void sp_256_proj_point_add_avx2_4(sp_point_256* r, sp_256_mont_sub_avx2_4(y, y, t5, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -10118,7 +10133,7 @@ static void sp_256_proj_point_add_avx2_4(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -10290,8 +10305,8 @@ static int sp_256_proj_point_add_avx2_4_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -10308,7 +10323,7 @@ static int sp_256_proj_point_add_avx2_4_nb(sp_ecc_ctx_t* sp_ctx, sp_point_256* r (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -10610,10 +10625,8 @@ static int sp_256_ecc_mulmod_win_add_sub_avx2_4(sp_point_256* r, const sp_point_ } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -10683,8 +10696,8 @@ static void sp_256_proj_point_add_qz1_4(sp_point_256* r, sp_256_mont_sub_4(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -10701,7 +10714,7 @@ static void sp_256_proj_point_add_qz1_4(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -10812,8 +10825,7 @@ static int sp_256_gen_stripe_table_4(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -10942,10 +10954,8 @@ static int sp_256_ecc_mulmod_stripe_4(sp_point_256* r, const sp_point_256* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -11175,8 +11185,8 @@ static void sp_256_proj_point_add_qz1_avx2_4(sp_point_256* r, sp_256_mont_sub_avx2_4(y, t3, t1, p256_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -11193,7 +11203,7 @@ static void sp_256_proj_point_add_qz1_avx2_4(sp_point_256* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -11304,8 +11314,7 @@ static int sp_256_gen_stripe_table_avx2_4(const sp_point_256* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -11420,10 +11429,8 @@ static int sp_256_ecc_mulmod_stripe_avx2_4(sp_point_256* r, const sp_point_256* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -11544,8 +11551,10 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, sp_256_point_from_ecc_point_4(point, gm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(point, point, k, map, 1, heap); + } else #endif err = sp_256_ecc_mulmod_4(point, point, k, map, 1, heap); @@ -11555,10 +11564,8 @@ int sp_ecc_mulmod_256(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -11626,24 +11633,30 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(point, point, k, 0, 0, heap); + } else #endif err = sp_256_ecc_mulmod_4(point, point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_add_avx2_4(point, point, addP, tmp); + } else #endif sp_256_proj_point_add_4(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_map_avx2_4(point, point, tmp); + } else #endif sp_256_map_4(point, point, tmp); @@ -11653,10 +11666,8 @@ int sp_ecc_mulmod_add_256(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -12080,7 +12091,7 @@ static void sp_256_ecc_recode_7_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<37; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -24183,8 +24194,7 @@ static int sp_256_ecc_mulmod_add_only_4(sp_point_256* r, const sp_point_256* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24317,8 +24327,7 @@ static int sp_256_ecc_mulmod_add_only_avx2_4(sp_point_256* r, const sp_point_256 #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24383,8 +24392,10 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) sp_256_from_mp(k, 4, km); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(point, k, map, 1, heap); + } else #endif err = sp_256_ecc_mulmod_base_4(point, k, map, 1, heap); @@ -24394,10 +24405,8 @@ int sp_ecc_mulmod_base_256(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24463,24 +24472,30 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(point, k, 0, 0, heap); + } else #endif err = sp_256_ecc_mulmod_base_4(point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_add_avx2_4(point, point, addP, tmp); + } else #endif sp_256_proj_point_add_4(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_map_avx2_4(point, point, tmp); + } else #endif sp_256_map_4(point, point, tmp); @@ -24490,10 +24505,8 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24554,6 +24567,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_256_ecc_gen_k_4(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[32]; @@ -24570,6 +24584,11 @@ static int sp_256_ecc_gen_k_4(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -24630,8 +24649,10 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(point, k, 1, 1, NULL); + } else #endif err = sp_256_ecc_mulmod_base_4(point, k, 1, 1, NULL); @@ -24640,7 +24661,8 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) #ifdef WOLFSSL_VALIDATE_ECC_KEYGEN if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(infinity, point, p256_order, 1, 1, NULL); } @@ -24663,12 +24685,9 @@ int sp_ecc_make_key_256(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24838,8 +24857,10 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, sp_256_from_mp(k, 4, priv); sp_256_point_from_ecc_point_4(point, pub); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(point, point, k, 1, 1, heap); + } else #endif err = sp_256_ecc_mulmod_4(point, point, k, 1, 1, heap); @@ -24850,10 +24871,8 @@ int sp_ecc_secret_gen_256(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -24972,8 +24991,8 @@ static WC_INLINE sp_digit div_256_word_4(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_256_word_4(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -25040,7 +25059,7 @@ static WC_INLINE int sp_256_div_4(const sp_digit* a, const sp_digit* d, sp_digit #endif sp_256_cond_sub_4(&t1[4], &t1[4], d, (sp_digit)0 - r1); for (i = 3; i >= 0; i--) { - sp_digit mask = 0 - (t1[4 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[4 + i] == div); sp_digit hi = t1[4 + i] + mask; r1 = div_256_word_4(hi, t1[4 + i - 1], div); r1 |= mask; @@ -25586,8 +25605,10 @@ static int sp_256_calc_s_4(sp_digit* s, const sp_digit* r, sp_digit* k, /* Conv k to Montgomery form (mod order) */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mul_avx2_4(k, k, p256_norm_order); + } else #endif sp_256_mul_4(k, k, p256_norm_order); @@ -25597,8 +25618,10 @@ static int sp_256_calc_s_4(sp_digit* s, const sp_digit* r, sp_digit* k, /* kInv = 1/k mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_inv_order_avx2_4(kInv, k, tmp); + } else #endif sp_256_mont_inv_order_4(kInv, k, tmp); @@ -25606,8 +25629,10 @@ static int sp_256_calc_s_4(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = r * x + e */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mul_avx2_4(x, x, r); + } else #endif sp_256_mul_4(x, x, r); @@ -25625,8 +25650,10 @@ static int sp_256_calc_s_4(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = s * k^-1 mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_mul_order_avx2_4(s, s, kInv); + } else #endif sp_256_mont_mul_order_4(s, s, kInv); @@ -25714,8 +25741,10 @@ int sp_ecc_sign_256(const byte* hash, word32 hashLen, WC_RNG* rng, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(point, k, 1, 1, heap); + } else #endif err = sp_256_ecc_mulmod_base_4(point, k, 1, 1, heap); @@ -25977,7 +26006,8 @@ static void sp_256_add_points_4(sp_point_256* p1, const sp_point_256* p2, #endif #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_add_avx2_4(p1, p1, p2, tmp); } else @@ -25986,7 +26016,8 @@ static void sp_256_add_points_4(sp_point_256* p1, const sp_point_256* p2, if (sp_256_iszero_4(p1->z)) { if (sp_256_iszero_4(p1->x) && sp_256_iszero_4(p1->y)) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_dbl_avx2_4(p1, p2, tmp); } else @@ -26024,7 +26055,8 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, #ifndef WOLFSSL_SP_SMALL #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mod_inv_avx2_4(s, s, p256_order); } else @@ -26035,7 +26067,8 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, #endif /* !WOLFSSL_SP_SMALL */ { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mul_avx2_4(s, s, p256_norm_order); } else @@ -26049,7 +26082,8 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, sp_256_norm_4(s); #ifdef WOLFSSL_SP_SMALL #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_inv_order_avx2_4(s, s, tmp); sp_256_mont_mul_order_avx2_4(u1, u1, s); sp_256_mont_mul_order_avx2_4(u2, u2, s); @@ -26063,7 +26097,8 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, } #else #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_mul_order_avx2_4(u1, u1, s); sp_256_mont_mul_order_avx2_4(u2, u2, s); } @@ -26075,7 +26110,8 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, } #endif /* WOLFSSL_SP_SMALL */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(p1, u1, 0, 0, heap); } else @@ -26089,8 +26125,10 @@ static int sp_256_calc_vfy_point_4(sp_point_256* p1, sp_point_256* p2, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(p2, p2, u2, 0, 0, heap); + } else #endif err = sp_256_ecc_mulmod_4(p2, p2, u2, 0, 0, heap); @@ -26192,14 +26230,18 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = r.z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_sqr_avx2_4(p1->z, p1->z, p256_mod, p256_mp_mod); + } else #endif sp_256_mont_sqr_4(p1->z, p1->z, p256_mod, p256_mp_mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_mul_avx2_4(u1, u2, p1->z, p256_mod, p256_mp_mod); + } else #endif sp_256_mont_mul_4(u1, u2, p1->z, p256_mod, p256_mp_mod); @@ -26222,7 +26264,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = (r + 1*order).z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_mul_avx2_4(u1, u2, p1->z, p256_mod, p256_mp_mod); } @@ -26237,10 +26280,8 @@ int sp_ecc_verify_256(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26447,8 +26488,7 @@ static int sp_256_ecc_is_point_4(const sp_point_256* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26487,8 +26527,7 @@ int sp_ecc_is_point_256(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26578,8 +26617,10 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Point * order = infinity */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_avx2_4(p, pub, p256_order, 1, 1, heap); + } else #endif err = sp_256_ecc_mulmod_4(p, pub, p256_order, 1, 1, heap); @@ -26594,8 +26635,10 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Base * private = point */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_256_ecc_mulmod_base_avx2_4(p, priv, 1, 1, heap); + } else #endif err = sp_256_ecc_mulmod_base_4(p, priv, 1, 1, heap); @@ -26609,10 +26652,8 @@ int sp_ecc_check_key_256(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -26681,8 +26722,10 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, sp_256_iszero_4(q->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_add_avx2_4(p, p, q, tmp); + } else #endif sp_256_proj_point_add_4(p, p, q, tmp); @@ -26699,10 +26742,8 @@ int sp_ecc_proj_add_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26757,8 +26798,10 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, sp_256_iszero_4(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_proj_point_dbl_avx2_4(p, p, tmp); + } else #endif sp_256_proj_point_dbl_4(p, p, tmp); @@ -26775,10 +26818,8 @@ int sp_ecc_proj_dbl_point_256(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26829,8 +26870,10 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) sp_256_iszero_4(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_map_avx2_4(p, p, tmp); + } else #endif sp_256_map_4(p, p, tmp); @@ -26847,10 +26890,8 @@ int sp_ecc_map_256(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26886,7 +26927,8 @@ static int sp_256_mont_sqrt_4(sp_digit* y) t2 = t1 + 2 * 4; #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { /* t2 = y ^ 0x2 */ sp_256_mont_sqr_avx2_4(t2, y, p256_mod, p256_mp_mod); /* t1 = y ^ 0x3 */ @@ -26953,8 +26995,7 @@ static int sp_256_mont_sqrt_4(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -26996,7 +27037,8 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) if (err == MP_OKAY) { /* y = x^3 */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_256_mont_sqr_avx2_4(y, x, p256_mod, p256_mp_mod); sp_256_mont_mul_avx2_4(y, y, x, p256_mod, p256_mp_mod); } @@ -27029,8 +27071,7 @@ int sp_ecc_uncompress_256(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27197,18 +27238,18 @@ static int sp_384_mod_mul_norm_6(sp_digit* r, const sp_digit* a, const sp_digit* if (err == MP_OKAY) { a32 = t + 12; - a32[0] = a[0] & 0xffffffff; - a32[1] = a[0] >> 32; - a32[2] = a[1] & 0xffffffff; - a32[3] = a[1] >> 32; - a32[4] = a[2] & 0xffffffff; - a32[5] = a[2] >> 32; - a32[6] = a[3] & 0xffffffff; - a32[7] = a[3] >> 32; - a32[8] = a[4] & 0xffffffff; - a32[9] = a[4] >> 32; - a32[10] = a[5] & 0xffffffff; - a32[11] = a[5] >> 32; + a32[0] = (int64_t)(a[0] & 0xffffffff); + a32[1] = (int64_t)(a[0] >> 32); + a32[2] = (int64_t)(a[1] & 0xffffffff); + a32[3] = (int64_t)(a[1] >> 32); + a32[4] = (int64_t)(a[2] & 0xffffffff); + a32[5] = (int64_t)(a[2] >> 32); + a32[6] = (int64_t)(a[3] & 0xffffffff); + a32[7] = (int64_t)(a[3] >> 32); + a32[8] = (int64_t)(a[4] & 0xffffffff); + a32[9] = (int64_t)(a[4] >> 32); + a32[10] = (int64_t)(a[5] & 0xffffffff); + a32[11] = (int64_t)(a[5] >> 32); /* 1 0 0 0 0 0 0 0 1 1 0 -1 */ t[0] = 0 + a32[0] + a32[8] + a32[9] - a32[11]; @@ -27263,17 +27304,16 @@ static int sp_384_mod_mul_norm_6(sp_digit* r, const sp_digit* a, const sp_digit* t[10] += t[9] >> 32; t[9] &= 0xffffffff; t[11] += t[10] >> 32; t[10] &= 0xffffffff; - r[0] = (t[1] << 32) | t[0]; - r[1] = (t[3] << 32) | t[2]; - r[2] = (t[5] << 32) | t[4]; - r[3] = (t[7] << 32) | t[6]; - r[4] = (t[9] << 32) | t[8]; - r[5] = (t[11] << 32) | t[10]; + r[0] = (sp_digit)((t[1] << 32) | t[0]); + r[1] = (sp_digit)((t[3] << 32) | t[2]); + r[2] = (sp_digit)((t[5] << 32) | t[4]); + r[3] = (sp_digit)((t[7] << 32) | t[6]); + r[4] = (sp_digit)((t[9] << 32) | t[8]); + r[5] = (sp_digit)((t[11] << 32) | t[10]); } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -27681,7 +27721,7 @@ static void sp_384_map_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_6(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_6(r->x, p384_mod); - sp_384_cond_sub_6(r->x, r->x, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->x, r->x, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->x); /* y /= z^3 */ @@ -27690,7 +27730,7 @@ static void sp_384_map_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_6(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_6(r->y, p384_mod); - sp_384_cond_sub_6(r->y, r->y, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->y, r->y, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -28113,8 +28153,8 @@ static void sp_384_proj_point_add_6(sp_point_384* r, sp_384_mont_sub_6(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -28131,7 +28171,7 @@ static void sp_384_proj_point_add_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -28305,8 +28345,8 @@ static int sp_384_proj_point_add_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -28323,7 +28363,7 @@ static int sp_384_proj_point_add_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -28537,7 +28577,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -28713,10 +28753,8 @@ static int sp_384_ecc_mulmod_win_add_sub_6(sp_point_384* r, const sp_point_384* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -28902,7 +28940,7 @@ static void sp_384_map_avx2_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_avx2_6(r->x, p384_mod, p384_mp_mod); /* Reduce x to less than modulus */ n = sp_384_cmp_6(r->x, p384_mod); - sp_384_cond_sub_6(r->x, r->x, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->x, r->x, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->x); /* y /= z^3 */ @@ -28911,7 +28949,7 @@ static void sp_384_map_avx2_6(sp_point_384* r, const sp_point_384* p, sp_384_mont_reduce_avx2_6(r->y, p384_mod, p384_mp_mod); /* Reduce y to less than modulus */ n = sp_384_cmp_6(r->y, p384_mod); - sp_384_cond_sub_6(r->y, r->y, p384_mod, ~(n >> 63)); + sp_384_cond_sub_6(r->y, r->y, p384_mod, (sp_digit)~(n >> 63)); sp_384_norm_6(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -29286,8 +29324,8 @@ static void sp_384_proj_point_add_avx2_6(sp_point_384* r, sp_384_mont_sub_avx2_6(y, y, t5, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29304,7 +29342,7 @@ static void sp_384_proj_point_add_avx2_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -29478,8 +29516,8 @@ static int sp_384_proj_point_add_avx2_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29496,7 +29534,7 @@ static int sp_384_proj_point_add_avx2_6_nb(sp_ecc_ctx_t* sp_ctx, sp_point_384* r (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -29801,10 +29839,8 @@ static int sp_384_ecc_mulmod_win_add_sub_avx2_6(sp_point_384* r, const sp_point_ } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -29877,8 +29913,8 @@ static void sp_384_proj_point_add_qz1_6(sp_point_384* r, sp_384_mont_sub_6(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -29895,7 +29931,7 @@ static void sp_384_proj_point_add_qz1_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -30006,8 +30042,7 @@ static int sp_384_gen_stripe_table_6(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30136,10 +30171,8 @@ static int sp_384_ecc_mulmod_stripe_6(sp_point_384* r, const sp_point_384* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30372,8 +30405,8 @@ static void sp_384_proj_point_add_qz1_avx2_6(sp_point_384* r, sp_384_mont_sub_avx2_6(y, t3, t1, p384_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -30390,7 +30423,7 @@ static void sp_384_proj_point_add_qz1_avx2_6(sp_point_384* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -30501,8 +30534,7 @@ static int sp_384_gen_stripe_table_avx2_6(const sp_point_384* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30617,10 +30649,8 @@ static int sp_384_ecc_mulmod_stripe_avx2_6(sp_point_384* r, const sp_point_384* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30741,8 +30771,10 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, sp_384_point_from_ecc_point_6(point, gm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(point, point, k, map, 1, heap); + } else #endif err = sp_384_ecc_mulmod_6(point, point, k, map, 1, heap); @@ -30752,10 +30784,8 @@ int sp_ecc_mulmod_384(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -30823,24 +30853,30 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(point, point, k, 0, 0, heap); + } else #endif err = sp_384_ecc_mulmod_6(point, point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_add_avx2_6(point, point, addP, tmp); + } else #endif sp_384_proj_point_add_6(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_map_avx2_6(point, point, tmp); + } else #endif sp_384_map_6(point, point, tmp); @@ -30850,10 +30886,8 @@ int sp_ecc_mulmod_add_384(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -31277,7 +31311,7 @@ static void sp_384_ecc_recode_7_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<55; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -49194,8 +49228,7 @@ static int sp_384_ecc_mulmod_add_only_6(sp_point_384* r, const sp_point_384* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49328,8 +49361,7 @@ static int sp_384_ecc_mulmod_add_only_avx2_6(sp_point_384* r, const sp_point_384 #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49394,8 +49426,10 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) sp_384_from_mp(k, 6, km); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(point, k, map, 1, heap); + } else #endif err = sp_384_ecc_mulmod_base_6(point, k, map, 1, heap); @@ -49405,10 +49439,8 @@ int sp_ecc_mulmod_base_384(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49474,24 +49506,30 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(point, k, 0, 0, heap); + } else #endif err = sp_384_ecc_mulmod_base_6(point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_add_avx2_6(point, point, addP, tmp); + } else #endif sp_384_proj_point_add_6(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_map_avx2_6(point, point, tmp); + } else #endif sp_384_map_6(point, point, tmp); @@ -49501,10 +49539,8 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49565,6 +49601,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_384_ecc_gen_k_6(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[48]; @@ -49581,6 +49618,11 @@ static int sp_384_ecc_gen_k_6(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -49641,8 +49683,10 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(point, k, 1, 1, NULL); + } else #endif err = sp_384_ecc_mulmod_base_6(point, k, 1, 1, NULL); @@ -49651,7 +49695,8 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) #ifdef WOLFSSL_VALIDATE_ECC_KEYGEN if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(infinity, point, p384_order, 1, 1, NULL); } @@ -49674,12 +49719,9 @@ int sp_ecc_make_key_384(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49849,8 +49891,10 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, sp_384_from_mp(k, 6, priv); sp_384_point_from_ecc_point_6(point, pub); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(point, point, k, 1, 1, heap); + } else #endif err = sp_384_ecc_mulmod_6(point, point, k, 1, 1, heap); @@ -49861,10 +49905,8 @@ int sp_ecc_secret_gen_384(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -49983,8 +50025,8 @@ static WC_INLINE sp_digit div_384_word_6(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_384_word_6(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -50053,7 +50095,7 @@ static WC_INLINE int sp_384_div_6(const sp_digit* a, const sp_digit* d, sp_digit #endif sp_384_cond_sub_6(&t1[6], &t1[6], d, (sp_digit)0 - r1); for (i = 5; i >= 0; i--) { - sp_digit mask = 0 - (t1[6 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[6 + i] == div); sp_digit hi = t1[6 + i] + mask; r1 = div_384_word_6(hi, t1[6 + i - 1], div); r1 |= mask; @@ -50455,8 +50497,10 @@ static int sp_384_calc_s_6(sp_digit* s, const sp_digit* r, sp_digit* k, /* Conv k to Montgomery form (mod order) */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mul_avx2_6(k, k, p384_norm_order); + } else #endif sp_384_mul_6(k, k, p384_norm_order); @@ -50466,8 +50510,10 @@ static int sp_384_calc_s_6(sp_digit* s, const sp_digit* r, sp_digit* k, /* kInv = 1/k mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_inv_order_avx2_6(kInv, k, tmp); + } else #endif sp_384_mont_inv_order_6(kInv, k, tmp); @@ -50475,8 +50521,10 @@ static int sp_384_calc_s_6(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = r * x + e */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mul_avx2_6(x, x, r); + } else #endif sp_384_mul_6(x, x, r); @@ -50494,8 +50542,10 @@ static int sp_384_calc_s_6(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = s * k^-1 mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_mul_order_avx2_6(s, s, kInv); + } else #endif sp_384_mont_mul_order_6(s, s, kInv); @@ -50583,8 +50633,10 @@ int sp_ecc_sign_384(const byte* hash, word32 hashLen, WC_RNG* rng, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(point, k, 1, 1, heap); + } else #endif err = sp_384_ecc_mulmod_base_6(point, k, 1, 1, heap); @@ -50935,7 +50987,8 @@ static void sp_384_add_points_6(sp_point_384* p1, const sp_point_384* p2, #endif #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_add_avx2_6(p1, p1, p2, tmp); } else @@ -50944,7 +50997,8 @@ static void sp_384_add_points_6(sp_point_384* p1, const sp_point_384* p2, if (sp_384_iszero_6(p1->z)) { if (sp_384_iszero_6(p1->x) && sp_384_iszero_6(p1->y)) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_dbl_avx2_6(p1, p2, tmp); } else @@ -50988,7 +51042,8 @@ static int sp_384_calc_vfy_point_6(sp_point_384* p1, sp_point_384* p2, #endif /* !WOLFSSL_SP_SMALL */ { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mul_avx2_6(s, s, p384_norm_order); } else @@ -51002,7 +51057,8 @@ static int sp_384_calc_vfy_point_6(sp_point_384* p1, sp_point_384* p2, sp_384_norm_6(s); #ifdef WOLFSSL_SP_SMALL #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_inv_order_avx2_6(s, s, tmp); sp_384_mont_mul_order_avx2_6(u1, u1, s); sp_384_mont_mul_order_avx2_6(u2, u2, s); @@ -51016,7 +51072,8 @@ static int sp_384_calc_vfy_point_6(sp_point_384* p1, sp_point_384* p2, } #else #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_mul_order_avx2_6(u1, u1, s); sp_384_mont_mul_order_avx2_6(u2, u2, s); } @@ -51028,7 +51085,8 @@ static int sp_384_calc_vfy_point_6(sp_point_384* p1, sp_point_384* p2, } #endif /* WOLFSSL_SP_SMALL */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(p1, u1, 0, 0, heap); } else @@ -51042,8 +51100,10 @@ static int sp_384_calc_vfy_point_6(sp_point_384* p1, sp_point_384* p2, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(p2, p2, u2, 0, 0, heap); + } else #endif err = sp_384_ecc_mulmod_6(p2, p2, u2, 0, 0, heap); @@ -51145,14 +51205,18 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = r.z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_sqr_avx2_6(p1->z, p1->z, p384_mod, p384_mp_mod); + } else #endif sp_384_mont_sqr_6(p1->z, p1->z, p384_mod, p384_mp_mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_mul_avx2_6(u1, u2, p1->z, p384_mod, p384_mp_mod); + } else #endif sp_384_mont_mul_6(u1, u2, p1->z, p384_mod, p384_mp_mod); @@ -51175,7 +51239,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = (r + 1*order).z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_mul_avx2_6(u1, u2, p1->z, p384_mod, p384_mp_mod); } @@ -51190,10 +51255,8 @@ int sp_ecc_verify_384(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51400,8 +51463,7 @@ static int sp_384_ecc_is_point_6(const sp_point_384* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51440,8 +51502,7 @@ int sp_ecc_is_point_384(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51531,8 +51592,10 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Point * order = infinity */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_avx2_6(p, pub, p384_order, 1, 1, heap); + } else #endif err = sp_384_ecc_mulmod_6(p, pub, p384_order, 1, 1, heap); @@ -51547,8 +51610,10 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Base * private = point */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_384_ecc_mulmod_base_avx2_6(p, priv, 1, 1, heap); + } else #endif err = sp_384_ecc_mulmod_base_6(p, priv, 1, 1, heap); @@ -51562,10 +51627,8 @@ int sp_ecc_check_key_384(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -51634,8 +51697,10 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, sp_384_iszero_6(q->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_add_avx2_6(p, p, q, tmp); + } else #endif sp_384_proj_point_add_6(p, p, q, tmp); @@ -51652,10 +51717,8 @@ int sp_ecc_proj_add_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51710,8 +51773,10 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, sp_384_iszero_6(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_proj_point_dbl_avx2_6(p, p, tmp); + } else #endif sp_384_proj_point_dbl_6(p, p, tmp); @@ -51728,10 +51793,8 @@ int sp_ecc_proj_dbl_point_384(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51782,8 +51845,10 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) sp_384_iszero_6(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_map_avx2_6(p, p, tmp); + } else #endif sp_384_map_6(p, p, tmp); @@ -51800,10 +51865,8 @@ int sp_ecc_map_384(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -51844,7 +51907,8 @@ static int sp_384_mont_sqrt_6(sp_digit* y) t5 = t1 + 8 * 6; #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { /* t2 = y ^ 0x2 */ sp_384_mont_sqr_avx2_6(t2, y, p384_mod, p384_mp_mod); /* t1 = y ^ 0x3 */ @@ -51961,8 +52025,7 @@ static int sp_384_mont_sqrt_6(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, NULL, DYNAMIC_TYPE_ECC); + XFREE(t1, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -52004,7 +52067,8 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) if (err == MP_OKAY) { /* y = x^3 */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_384_mont_sqr_avx2_6(y, x, p384_mod, p384_mp_mod); sp_384_mont_mul_avx2_6(y, y, x, p384_mod, p384_mp_mod); } @@ -52037,8 +52101,7 @@ int sp_ecc_uncompress_384(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -52586,7 +52649,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_9(r->x, p521_mod); - sp_521_cond_sub_9(r->x, r->x, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->x, r->x, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->x); /* y /= z^3 */ @@ -52595,7 +52658,7 @@ static void sp_521_map_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_9(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_9(r->y, p521_mod); - sp_521_cond_sub_9(r->y, r->y, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->y, r->y, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -53020,8 +53083,8 @@ static void sp_521_proj_point_add_9(sp_point_521* r, sp_521_mont_sub_9(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -53038,7 +53101,7 @@ static void sp_521_proj_point_add_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -53212,8 +53275,8 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -53230,7 +53293,7 @@ static int sp_521_proj_point_add_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -53444,7 +53507,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -53620,10 +53683,8 @@ static int sp_521_ecc_mulmod_win_add_sub_9(sp_point_521* r, const sp_point_521* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -53786,7 +53847,7 @@ static void sp_521_map_avx2_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_avx2_9(r->x, p521_mod, p521_mp_mod); /* Reduce x to less than modulus */ n = sp_521_cmp_9(r->x, p521_mod); - sp_521_cond_sub_9(r->x, r->x, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->x, r->x, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->x); /* y /= z^3 */ @@ -53795,7 +53856,7 @@ static void sp_521_map_avx2_9(sp_point_521* r, const sp_point_521* p, sp_521_mont_reduce_avx2_9(r->y, p521_mod, p521_mp_mod); /* Reduce y to less than modulus */ n = sp_521_cmp_9(r->y, p521_mod); - sp_521_cond_sub_9(r->y, r->y, p521_mod, ~(n >> 63)); + sp_521_cond_sub_9(r->y, r->y, p521_mod, (sp_digit)~(n >> 63)); sp_521_norm_9(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -54170,8 +54231,8 @@ static void sp_521_proj_point_add_avx2_9(sp_point_521* r, sp_521_mont_sub_avx2_9(y, y, t5, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -54188,7 +54249,7 @@ static void sp_521_proj_point_add_avx2_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -54362,8 +54423,8 @@ static int sp_521_proj_point_add_avx2_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -54380,7 +54441,7 @@ static int sp_521_proj_point_add_avx2_9_nb(sp_ecc_ctx_t* sp_ctx, sp_point_521* r (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -54685,10 +54746,8 @@ static int sp_521_ecc_mulmod_win_add_sub_avx2_9(sp_point_521* r, const sp_point_ } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -54761,8 +54820,8 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, sp_521_mont_sub_9(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -54779,7 +54838,7 @@ static void sp_521_proj_point_add_qz1_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -54890,8 +54949,7 @@ static int sp_521_gen_stripe_table_9(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -55020,10 +55078,8 @@ static int sp_521_ecc_mulmod_stripe_9(sp_point_521* r, const sp_point_521* g, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -55256,8 +55312,8 @@ static void sp_521_proj_point_add_qz1_avx2_9(sp_point_521* r, sp_521_mont_sub_avx2_9(y, t3, t1, p521_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -55274,7 +55330,7 @@ static void sp_521_proj_point_add_qz1_avx2_9(sp_point_521* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -55385,8 +55441,7 @@ static int sp_521_gen_stripe_table_avx2_9(const sp_point_521* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -55501,10 +55556,8 @@ static int sp_521_ecc_mulmod_stripe_avx2_9(sp_point_521* r, const sp_point_521* } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -55625,8 +55678,10 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, sp_521_point_from_ecc_point_9(point, gm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(point, point, k, map, 1, heap); + } else #endif err = sp_521_ecc_mulmod_9(point, point, k, map, 1, heap); @@ -55636,10 +55691,8 @@ int sp_ecc_mulmod_521(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -55707,24 +55760,30 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(point, point, k, 0, 0, heap); + } else #endif err = sp_521_ecc_mulmod_9(point, point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_add_avx2_9(point, point, addP, tmp); + } else #endif sp_521_proj_point_add_9(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_map_avx2_9(point, point, tmp); + } else #endif sp_521_map_9(point, point, tmp); @@ -55734,10 +55793,8 @@ int sp_ecc_mulmod_add_521(const mp_int* km, const ecc_point* gm, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -56287,7 +56344,7 @@ static void sp_521_ecc_recode_7_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<75; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -90264,8 +90321,7 @@ static int sp_521_ecc_mulmod_add_only_9(sp_point_521* r, const sp_point_521* g, #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -90398,8 +90454,7 @@ static int sp_521_ecc_mulmod_add_only_avx2_9(sp_point_521* r, const sp_point_521 #endif } #ifdef WOLFSSL_SP_SMALL_STACK - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -90464,8 +90519,10 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) sp_521_from_mp(k, 9, km); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(point, k, map, 1, heap); + } else #endif err = sp_521_ecc_mulmod_base_9(point, k, map, 1, heap); @@ -90475,10 +90532,8 @@ int sp_ecc_mulmod_base_521(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -90544,24 +90599,30 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(point, k, 0, 0, heap); + } else #endif err = sp_521_ecc_mulmod_base_9(point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_add_avx2_9(point, point, addP, tmp); + } else #endif sp_521_proj_point_add_9(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_map_avx2_9(point, point, tmp); + } else #endif sp_521_map_9(point, point, tmp); @@ -90571,10 +90632,8 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -90635,6 +90694,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) */ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) { +#ifndef WC_NO_RNG int err; byte buf[66]; @@ -90652,6 +90712,11 @@ static int sp_521_ecc_gen_k_9(WC_RNG* rng, sp_digit* k) while (err == 0); return err; +#else + (void)rng; + (void)k; + return NOT_COMPILED_IN; +#endif } /* Makes a random EC key pair. @@ -90712,8 +90777,10 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(point, k, 1, 1, NULL); + } else #endif err = sp_521_ecc_mulmod_base_9(point, k, 1, 1, NULL); @@ -90722,7 +90789,8 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) #ifdef WOLFSSL_VALIDATE_ECC_KEYGEN if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(infinity, point, p521_order, 1, 1, NULL); } @@ -90745,12 +90813,9 @@ int sp_ecc_make_key_521(WC_RNG* rng, mp_int* priv, ecc_point* pub, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) { - /* point is not sensitive, so no need to zeroize */ - XFREE(point, heap, DYNAMIC_TYPE_ECC); - } + XFREE(k, heap, DYNAMIC_TYPE_ECC); + /* point is not sensitive, so no need to zeroize */ + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -90920,8 +90985,10 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, sp_521_from_mp(k, 9, priv); sp_521_point_from_ecc_point_9(point, pub); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(point, point, k, 1, 1, heap); + } else #endif err = sp_521_ecc_mulmod_9(point, point, k, 1, 1, heap); @@ -90932,10 +90999,8 @@ int sp_ecc_secret_gen_521(const mp_int* priv, const ecc_point* pub, byte* out, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -91075,8 +91140,8 @@ static WC_INLINE sp_digit div_521_word_9(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_521_word_9(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -91581,8 +91646,10 @@ static int sp_521_calc_s_9(sp_digit* s, const sp_digit* r, sp_digit* k, /* Conv k to Montgomery form (mod order) */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mul_avx2_9(k, k, p521_norm_order); + } else #endif sp_521_mul_9(k, k, p521_norm_order); @@ -91592,8 +91659,10 @@ static int sp_521_calc_s_9(sp_digit* s, const sp_digit* r, sp_digit* k, /* kInv = 1/k mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_inv_order_avx2_9(kInv, k, tmp); + } else #endif sp_521_mont_inv_order_9(kInv, k, tmp); @@ -91601,8 +91670,10 @@ static int sp_521_calc_s_9(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = r * x + e */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mul_avx2_9(x, x, r); + } else #endif sp_521_mul_9(x, x, r); @@ -91620,8 +91691,10 @@ static int sp_521_calc_s_9(sp_digit* s, const sp_digit* r, sp_digit* k, /* s = s * k^-1 mod order */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_mul_order_avx2_9(s, s, kInv); + } else #endif sp_521_mont_mul_order_9(s, s, kInv); @@ -91709,8 +91782,10 @@ int sp_ecc_sign_521(const byte* hash, word32 hashLen, WC_RNG* rng, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(point, k, 1, 1, heap); + } else #endif err = sp_521_ecc_mulmod_base_9(point, k, 1, 1, heap); @@ -92069,7 +92144,8 @@ static void sp_521_add_points_9(sp_point_521* p1, const sp_point_521* p2, #endif #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_add_avx2_9(p1, p1, p2, tmp); } else @@ -92078,7 +92154,8 @@ static void sp_521_add_points_9(sp_point_521* p1, const sp_point_521* p2, if (sp_521_iszero_9(p1->z)) { if (sp_521_iszero_9(p1->x) && sp_521_iszero_9(p1->y)) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_dbl_avx2_9(p1, p2, tmp); } else @@ -92125,7 +92202,8 @@ static int sp_521_calc_vfy_point_9(sp_point_521* p1, sp_point_521* p2, #endif /* !WOLFSSL_SP_SMALL */ { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mul_avx2_9(s, s, p521_norm_order); } else @@ -92139,7 +92217,8 @@ static int sp_521_calc_vfy_point_9(sp_point_521* p1, sp_point_521* p2, sp_521_norm_9(s); #ifdef WOLFSSL_SP_SMALL #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_inv_order_avx2_9(s, s, tmp); sp_521_mont_mul_order_avx2_9(u1, u1, s); sp_521_mont_mul_order_avx2_9(u2, u2, s); @@ -92153,7 +92232,8 @@ static int sp_521_calc_vfy_point_9(sp_point_521* p1, sp_point_521* p2, } #else #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_mul_order_avx2_9(u1, u1, s); sp_521_mont_mul_order_avx2_9(u2, u2, s); } @@ -92165,7 +92245,8 @@ static int sp_521_calc_vfy_point_9(sp_point_521* p1, sp_point_521* p2, } #endif /* WOLFSSL_SP_SMALL */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(p1, u1, 0, 0, heap); } else @@ -92179,8 +92260,10 @@ static int sp_521_calc_vfy_point_9(sp_point_521* p1, sp_point_521* p2, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(p2, p2, u2, 0, 0, heap); + } else #endif err = sp_521_ecc_mulmod_9(p2, p2, u2, 0, 0, heap); @@ -92286,14 +92369,18 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = r.z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_sqr_avx2_9(p1->z, p1->z, p521_mod, p521_mp_mod); + } else #endif sp_521_mont_sqr_9(p1->z, p1->z, p521_mod, p521_mp_mod); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_mul_avx2_9(u1, u2, p1->z, p521_mod, p521_mp_mod); + } else #endif sp_521_mont_mul_9(u1, u2, p1->z, p521_mod, p521_mp_mod); @@ -92316,7 +92403,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, if (err == MP_OKAY) { /* u1 = (r + 1*order).z'.z' mod prime */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_mul_avx2_9(u1, u2, p1->z, p521_mod, p521_mp_mod); } @@ -92331,10 +92419,8 @@ int sp_ecc_verify_521(const byte* hash, word32 hashLen, const mp_int* pX, } #ifdef WOLFSSL_SP_SMALL_STACK - if (u1 != NULL) - XFREE(u1, heap, DYNAMIC_TYPE_ECC); - if (p1 != NULL) - XFREE(p1, heap, DYNAMIC_TYPE_ECC); + XFREE(u1, heap, DYNAMIC_TYPE_ECC); + XFREE(p1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92544,8 +92630,7 @@ static int sp_521_ecc_is_point_9(const sp_point_521* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92584,8 +92669,7 @@ int sp_ecc_is_point_521(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -92675,8 +92759,10 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Point * order = infinity */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_avx2_9(p, pub, p521_order, 1, 1, heap); + } else #endif err = sp_521_ecc_mulmod_9(p, pub, p521_order, 1, 1, heap); @@ -92691,8 +92777,10 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Base * private = point */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_521_ecc_mulmod_base_avx2_9(p, priv, 1, 1, heap); + } else #endif err = sp_521_ecc_mulmod_base_9(p, priv, 1, 1, heap); @@ -92706,10 +92794,8 @@ int sp_ecc_check_key_521(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -92778,8 +92864,10 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, sp_521_iszero_9(q->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_add_avx2_9(p, p, q, tmp); + } else #endif sp_521_proj_point_add_9(p, p, q, tmp); @@ -92796,10 +92884,8 @@ int sp_ecc_proj_add_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -92854,8 +92940,10 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, sp_521_iszero_9(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_proj_point_dbl_avx2_9(p, p, tmp); + } else #endif sp_521_proj_point_dbl_9(p, p, tmp); @@ -92872,10 +92960,8 @@ int sp_ecc_proj_dbl_point_521(mp_int* pX, mp_int* pY, mp_int* pZ, } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -92926,8 +93012,10 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) sp_521_iszero_9(p->y); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_map_avx2_9(p, p, tmp); + } else #endif sp_521_map_9(p, p, tmp); @@ -92944,10 +93032,8 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) } #ifdef WOLFSSL_SP_SMALL_STACK - if (tmp != NULL) - XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); - if (p != NULL) - XFREE(p, NULL, DYNAMIC_TYPE_ECC); + XFREE(tmp, NULL, DYNAMIC_TYPE_ECC); + XFREE(p, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -92987,7 +93073,8 @@ static int sp_521_mont_sqrt_9(sp_digit* y) if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { int i; XMEMCPY(t, y, sizeof(sp_digit) * 9); @@ -93014,8 +93101,7 @@ static int sp_521_mont_sqrt_9(sp_digit* y) } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, NULL, DYNAMIC_TYPE_ECC); + XFREE(t, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -93057,7 +93143,8 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) if (err == MP_OKAY) { /* y = x^3 */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) { + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_521_mont_sqr_avx2_9(y, x, p521_mod, p521_mp_mod); sp_521_mont_mul_avx2_9(y, y, x, p521_mod, p521_mp_mod); } @@ -93090,8 +93177,7 @@ int sp_ecc_uncompress_521(mp_int* xm, int odd, mp_int* ym) } #ifdef WOLFSSL_SP_SMALL_STACK - if (x != NULL) - XFREE(x, NULL, DYNAMIC_TYPE_ECC); + XFREE(x, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -93297,8 +93383,8 @@ static WC_INLINE sp_digit div_1024_word_16(sp_digit d1, sp_digit d0, static WC_INLINE sp_digit div_1024_word_16(sp_digit d1, sp_digit d0, sp_digit div) { - ASSERT_SAVED_VECTOR_REGISTERS(); register sp_digit r asm("rax"); + ASSERT_SAVED_VECTOR_REGISTERS(); __asm__ __volatile__ ( "divq %3" : "=a" (r) @@ -93380,7 +93466,7 @@ static WC_INLINE int sp_1024_div_16(const sp_digit* a, const sp_digit* d, sp_dig #endif sp_1024_cond_sub_16(&t1[16], &t1[16], d, (sp_digit)0 - r1); for (i = 15; i >= 0; i--) { - sp_digit mask = 0 - (t1[16 + i] == div); + sp_digit mask = (sp_digit)0 - (t1[16 + i] == div); sp_digit hi = t1[16 + i] + mask; r1 = div_1024_word_16(hi, t1[16 + i - 1], div); r1 |= mask; @@ -93499,16 +93585,16 @@ static void sp_1024_point_free_16(sp_point_1024* p, int clear, void* heap) { #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) -/* If valid pointer then clear point data if requested and free data. */ + /* If valid pointer then clear point data if requested and free data. */ if (p != NULL) { - if (clear != 0) { + if (clear) { XMEMSET(p, 0, sizeof(*p)); } XFREE(p, heap, DYNAMIC_TYPE_ECC); } #else -/* Clear point data if requested. */ - if ((p != NULL) && (clear != 0)) { + /* Clear point data if requested. */ + if ((p != NULL) && clear) { XMEMSET(p, 0, sizeof(*p)); } #endif @@ -93846,7 +93932,7 @@ static void sp_1024_map_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_16(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_16(r->x, p1024_mod); - sp_1024_cond_sub_16(r->x, r->x, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->x, r->x, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->x); /* y /= z^3 */ @@ -93855,7 +93941,7 @@ static void sp_1024_map_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_16(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_16(r->y, p1024_mod); - sp_1024_cond_sub_16(r->y, r->y, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->y, r->y, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -94283,8 +94369,8 @@ static void sp_1024_proj_point_add_16(sp_point_1024* r, sp_1024_mont_sub_16(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -94301,7 +94387,7 @@ static void sp_1024_proj_point_add_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -94475,8 +94561,8 @@ static int sp_1024_proj_point_add_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -94493,7 +94579,7 @@ static int sp_1024_proj_point_add_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024* r, (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -94715,7 +94801,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (int8_t)n; + y = (uint8_t)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -94881,10 +94967,8 @@ static int sp_1024_ecc_mulmod_win_add_sub_16(sp_point_1024* r, const sp_point_10 } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -94995,7 +95079,7 @@ static void sp_1024_map_avx2_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_avx2_16(r->x, p1024_mod, p1024_mp_mod); /* Reduce x to less than modulus */ n = sp_1024_cmp_16(r->x, p1024_mod); - sp_1024_cond_sub_16(r->x, r->x, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->x, r->x, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->x); /* y /= z^3 */ @@ -95004,7 +95088,7 @@ static void sp_1024_map_avx2_16(sp_point_1024* r, const sp_point_1024* p, sp_1024_mont_reduce_avx2_16(r->y, p1024_mod, p1024_mp_mod); /* Reduce y to less than modulus */ n = sp_1024_cmp_16(r->y, p1024_mod); - sp_1024_cond_sub_16(r->y, r->y, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(r->y, r->y, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(r->y); XMEMSET(r->z, 0, sizeof(r->z) / 2); @@ -95403,8 +95487,8 @@ static void sp_1024_proj_point_add_avx2_16(sp_point_1024* r, sp_1024_mont_sub_avx2_16(y, y, t5, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -95421,7 +95505,7 @@ static void sp_1024_proj_point_add_avx2_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -95595,8 +95679,8 @@ static int sp_1024_proj_point_add_avx2_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024 { { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -95613,7 +95697,7 @@ static int sp_1024_proj_point_add_avx2_16_nb(sp_ecc_ctx_t* sp_ctx, sp_point_1024 (ctx->z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } ctx->state = 25; break; @@ -95922,10 +96006,8 @@ static int sp_1024_ecc_mulmod_win_add_sub_avx2_16(sp_point_1024* r, const sp_poi } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (tmp != NULL) - XFREE(tmp, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(tmp, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -95998,8 +96080,8 @@ static void sp_1024_proj_point_add_qz1_16(sp_point_1024* r, sp_1024_mont_sub_16(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -96016,7 +96098,7 @@ static void sp_1024_proj_point_add_qz1_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -96127,8 +96209,7 @@ static int sp_1024_gen_stripe_table_16(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -96227,10 +96308,8 @@ static int sp_1024_ecc_mulmod_stripe_16(sp_point_1024* r, const sp_point_1024* g } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -96462,8 +96541,8 @@ static void sp_1024_proj_point_add_qz1_avx2_16(sp_point_1024* r, sp_1024_mont_sub_avx2_16(y, t3, t1, p1024_mod); { int i; - sp_digit maskp = 0 - (q->infinity & (!p->infinity)); - sp_digit maskq = 0 - (p->infinity & (!q->infinity)); + sp_digit maskp = (sp_digit)(0 - (q->infinity & (!p->infinity))); + sp_digit maskq = (sp_digit)(0 - (p->infinity & (!q->infinity))); sp_digit maskt = ~(maskp | maskq); sp_digit inf = (sp_digit)(p->infinity & q->infinity); @@ -96480,7 +96559,7 @@ static void sp_1024_proj_point_add_qz1_avx2_16(sp_point_1024* r, (z[i] & maskt); } r->z[0] |= inf; - r->infinity = (word32)inf; + r->infinity = (int)inf; } } } @@ -96591,8 +96670,7 @@ static int sp_1024_gen_stripe_table_avx2_16(const sp_point_1024* a, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -96691,10 +96769,8 @@ static int sp_1024_ecc_mulmod_stripe_avx2_16(sp_point_1024* r, const sp_point_10 } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (rt != NULL) - XFREE(rt, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(rt, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -96814,8 +96890,10 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, sp_1024_point_from_ecc_point_16(point, gm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_avx2_16(point, point, k, map, 1, heap); + } else #endif err = sp_1024_ecc_mulmod_16(point, point, k, map, 1, heap); @@ -96825,10 +96903,8 @@ int sp_ecc_mulmod_1024(const mp_int* km, const ecc_point* gm, ecc_point* r, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -100247,8 +100323,10 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) sp_1024_from_mp(k, 16, km); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_base_avx2_16(point, k, map, 1, heap); + } else #endif err = sp_1024_ecc_mulmod_base_16(point, k, map, 1, heap); @@ -100258,10 +100336,8 @@ int sp_ecc_mulmod_base_1024(const mp_int* km, ecc_point* r, int map, void* heap) } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -100327,24 +100403,30 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_base_avx2_16(point, k, 0, 0, heap); + } else #endif err = sp_1024_ecc_mulmod_base_16(point, k, 0, 0, heap); } if (err == MP_OKAY) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_1024_proj_point_add_avx2_16(point, point, addP, tmp); + } else #endif sp_1024_proj_point_add_16(point, point, addP, tmp); if (map) { #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { sp_1024_map_avx2_16(point, point, tmp); + } else #endif sp_1024_map_16(point, point, tmp); @@ -100354,10 +100436,8 @@ int sp_ecc_mulmod_base_add_1024(const mp_int* km, const ecc_point* am, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -100394,7 +100474,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == MP_OKAY) && (table == NULL)) { *len = sizeof(sp_table_entry_1024) * 256; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && (*len < (int)(sizeof(sp_table_entry_1024) * 256))) { err = BUFFER_E; @@ -100418,9 +100498,11 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if (err == MP_OKAY) { sp_1024_point_from_ecc_point_16(point, gm); #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_gen_stripe_table_avx2_16(point, (sp_table_entry_1024*)table, t, heap); + } else #endif err = sp_1024_gen_stripe_table_16(point, @@ -100431,10 +100513,8 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t != NULL) - XFREE(t, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(t, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -100460,7 +100540,7 @@ int sp_ecc_gen_table_1024(const ecc_point* gm, byte* table, word32* len, if ((err == 0) && (table == NULL)) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == 0) && (*len != 0)) { err = BUFFER_E; @@ -100519,9 +100599,11 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, #ifndef WOLFSSL_SP_SMALL #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_stripe_avx2_16(point, point, (const sp_table_entry_1024*)table, k, map, 0, heap); + } else #endif err = sp_1024_ecc_mulmod_stripe_16(point, point, @@ -100536,10 +100618,8 @@ int sp_ecc_mulmod_table_1024(const mp_int* km, const ecc_point* gm, byte* table, } #ifdef WOLFSSL_SP_SMALL_STACK - if (k != NULL) - XFREE(k, heap, DYNAMIC_TYPE_ECC); - if (point != NULL) - XFREE(point, heap, DYNAMIC_TYPE_ECC); + XFREE(k, heap, DYNAMIC_TYPE_ECC); + XFREE(point, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -100686,9 +100766,7 @@ static int sp_ModExp_Fp_star_x64_1024(const mp_int* base, mp_int* exp, mp_int* r #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -102328,9 +102406,7 @@ static int sp_ModExp_Fp_star_x64_1024(const mp_int* base, mp_int* exp, mp_int* r #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -102478,9 +102554,7 @@ static int sp_ModExp_Fp_star_avx2_1024(const mp_int* base, mp_int* exp, mp_int* #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -102577,9 +102651,7 @@ static int sp_ModExp_Fp_star_avx2_1024(const mp_int* base, mp_int* exp, mp_int* #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return err; } @@ -102978,9 +103050,7 @@ static int sp_Pairing_x64_1024(const ecc_point* pm, const ecc_point* qm, mp_int* #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -103405,9 +103475,7 @@ static int sp_Pairing_x64_1024(const ecc_point* pm, const ecc_point* qm, mp_int* #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -103779,9 +103847,7 @@ static int sp_Pairing_avx2_1024(const ecc_point* pm, const ecc_point* qm, mp_int #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -104179,9 +104245,7 @@ static int sp_Pairing_avx2_1024(const ecc_point* pm, const ecc_point* qm, mp_int #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -104247,7 +104311,7 @@ static int sp_Pairing_gen_precomp_x64_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -104476,7 +104540,7 @@ static int sp_Pairing_gen_precomp_x64_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -104583,9 +104647,7 @@ static int sp_Pairing_gen_precomp_x64_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(neg, 1, NULL); sp_1024_point_free_16(c, 1, NULL); @@ -104778,9 +104840,7 @@ static int sp_Pairing_precomp_x64_1024(const ecc_point* pm, const ecc_point* qm, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -104811,7 +104871,7 @@ static int sp_Pairing_gen_precomp_avx2_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = 0; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } else if (*len != 0) { err = BUFFER_E; @@ -105013,7 +105073,7 @@ static int sp_Pairing_gen_precomp_avx2_1024(const ecc_point* pm, byte* table, if (table == NULL) { *len = sizeof(sp_table_entry_1024) * 1167; - err = LENGTH_ONLY_E; + err = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } if ((err == MP_OKAY) && @@ -105120,9 +105180,7 @@ static int sp_Pairing_gen_precomp_avx2_1024(const ecc_point* pm, byte* table, #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(neg, 1, NULL); sp_1024_point_free_16(c, 1, NULL); @@ -105315,9 +105373,7 @@ static int sp_Pairing_precomp_avx2_1024(const ecc_point* pm, const ecc_point* qm #if (defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_NO_MALLOC)) || \ defined(WOLFSSL_SP_SMALL_STACK) - if (td != NULL) { - XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(td, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif sp_1024_point_free_16(c, 1, NULL); sp_1024_point_free_16(q, 1, NULL); @@ -105477,7 +105533,7 @@ static int sp_1024_ecc_is_point_16(const sp_point_1024* point, n = sp_1024_cmp_16(t1, p1024_mod); - sp_1024_cond_sub_16(t1, t1, p1024_mod, ~(n >> 63)); + sp_1024_cond_sub_16(t1, t1, p1024_mod, (sp_digit)~(n >> 63)); sp_1024_norm_16(t1); if (!sp_1024_iszero_16(t1)) { err = MP_VAL; @@ -105485,8 +105541,7 @@ static int sp_1024_ecc_is_point_16(const sp_point_1024* point, } #ifdef WOLFSSL_SP_SMALL_STACK - if (t1 != NULL) - XFREE(t1, heap, DYNAMIC_TYPE_ECC); + XFREE(t1, heap, DYNAMIC_TYPE_ECC); #endif return err; @@ -105525,8 +105580,7 @@ int sp_ecc_is_point_1024(const mp_int* pX, const mp_int* pY) } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return err; @@ -105616,8 +105670,10 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Point * order = infinity */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_avx2_16(p, pub, p1024_order, 1, 1, heap); + } else #endif err = sp_1024_ecc_mulmod_16(p, pub, p1024_order, 1, 1, heap); @@ -105632,8 +105688,10 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, if (err == MP_OKAY) { /* Base * private = point */ #ifdef HAVE_INTEL_AVX2 - if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags)) + if (IS_INTEL_BMI2(cpuid_flags) && IS_INTEL_ADX(cpuid_flags) && + IS_INTEL_AVX2(cpuid_flags)) { err = sp_1024_ecc_mulmod_base_avx2_16(p, priv, 1, 1, heap); + } else #endif err = sp_1024_ecc_mulmod_base_16(p, priv, 1, 1, heap); @@ -105647,10 +105705,8 @@ int sp_ecc_check_key_1024(const mp_int* pX, const mp_int* pY, } #ifdef WOLFSSL_SP_SMALL_STACK - if (pub != NULL) - XFREE(pub, heap, DYNAMIC_TYPE_ECC); - if (priv != NULL) - XFREE(priv, heap, DYNAMIC_TYPE_ECC); + XFREE(pub, heap, DYNAMIC_TYPE_ECC); + XFREE(priv, heap, DYNAMIC_TYPE_ECC); #endif return err; diff --git a/src/wolfcrypt/src/sphincs.c b/src/wolfcrypt/src/sphincs.c index 05ba27f..5fc054d 100644 --- a/src/wolfcrypt/src/sphincs.c +++ b/src/wolfcrypt/src/sphincs.c @@ -1,6 +1,6 @@ /* sphincs.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/srp.c b/src/wolfcrypt/src/srp.c index b914f58..b06f62a 100644 --- a/src/wolfcrypt/src/srp.c +++ b/src/wolfcrypt/src/srp.c @@ -1,6 +1,6 @@ /* srp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -656,7 +656,7 @@ static int wc_SrpSetKey(Srp* srp, byte* secret, word32 size) byte digest[SRP_MAX_DIGEST_SIZE]; word32 i, j, digestSz = SrpHashSize(srp->type); byte counter[4]; - int r = BAD_FUNC_ARG; + int r = WC_NO_ERR_TRACE(BAD_FUNC_ARG); XMEMSET(digest, 0, SRP_MAX_DIGEST_SIZE); @@ -903,10 +903,8 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, } #ifdef WOLFSSL_SMALL_STACK - if (hash) - XFREE(hash, srp->heap, DYNAMIC_TYPE_SRP); - if (digest) - XFREE(digest, srp->heap, DYNAMIC_TYPE_SRP); + XFREE(hash, srp->heap, DYNAMIC_TYPE_SRP); + XFREE(digest, srp->heap, DYNAMIC_TYPE_SRP); if (u) { if (r != WC_NO_ERR_TRACE(MP_INIT_E)) mp_clear(u); diff --git a/src/wolfcrypt/src/tfm.c b/src/wolfcrypt/src/tfm.c index 07cd1fe..fc85785 100644 --- a/src/wolfcrypt/src/tfm.c +++ b/src/wolfcrypt/src/tfm.c @@ -1,6 +1,6 @@ /* tfm.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -321,7 +321,7 @@ int fp_mul(fp_int *A, fp_int *B, fp_int *C) goto clean; /* success */ break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ /* fall back to software, below */ @@ -3125,9 +3125,9 @@ int fp_exptmod(fp_int * G, fp_int * X, fp_int * P, fp_int * Y) return retHW; break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ - case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ + case WC_NO_ERR_TRACE(MP_HW_VALIDATION_ACTIVE): /* use SW to compare to HW */ /* use software calc */ break; @@ -3227,7 +3227,7 @@ int fp_exptmod_ex(fp_int * G, fp_int * X, int digits, fp_int * P, fp_int * Y) return retHW; break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ /* use software calc */ @@ -3328,7 +3328,7 @@ int fp_exptmod_nct(fp_int * G, fp_int * X, fp_int * P, fp_int * Y) return retHW; break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ /* use software calc */ @@ -3440,7 +3440,7 @@ int fp_sqr(fp_int *A, fp_int *B) goto clean; /* success */ break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ /* fall back to software, below */ @@ -4698,7 +4698,7 @@ int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) /* successfully computed in HW */ break; - case WC_HW_WAIT_E: /* MP_HW_BUSY math HW busy, fall back */ + case WC_NO_ERR_TRACE(WC_HW_WAIT_E): /* MP_HW_BUSY math HW busy, fall back */ case MP_HW_FALLBACK: /* forced fallback from HW to SW */ case MP_HW_VALIDATION_ACTIVE: /* use SW to compare to HW */ /* use software calc */ @@ -5685,9 +5685,9 @@ int mp_rand_prime(mp_int* a, int len, WC_RNG* rng, void* heap) err = fp_randprime(a, len, rng, heap); switch(err) { - case FP_VAL: + case WC_NO_ERR_TRACE(MP_VAL): return MP_VAL; - case FP_MEM: + case WC_NO_ERR_TRACE(MP_MEM): return MP_MEM; default: break; diff --git a/src/wolfcrypt/src/wc_dsp.c b/src/wolfcrypt/src/wc_dsp.c index c31c62b..c6c76c2 100644 --- a/src/wolfcrypt/src/wc_dsp.c +++ b/src/wolfcrypt/src/wc_dsp.c @@ -1,6 +1,6 @@ /* wc_dsp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wc_encrypt.c b/src/wolfcrypt/src/wc_encrypt.c index 3b6d87d..9393a69 100644 --- a/src/wolfcrypt/src/wc_encrypt.c +++ b/src/wolfcrypt/src/wc_encrypt.c @@ -1,6 +1,6 @@ /* wc_encrypt.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wc_kyber.c b/src/wolfcrypt/src/wc_kyber.c index ffa37d8..bca5e1f 100644 --- a/src/wolfcrypt/src/wc_kyber.c +++ b/src/wolfcrypt/src/wc_kyber.c @@ -47,14 +47,15 @@ /******************************************************************************/ /* Use SHA3-256 to generate 32-bytes of hash. */ -#define KYBER_HASH_H wc_Sha3_256Hash +#define KYBER_HASH_H kyber_hash256 /* Use SHA3-512 to generate 64-bytes of hash. */ -#define KYBER_HASH_G wc_Sha3_512Hash +#define KYBER_HASH_G kyber_hash512 /* Use SHAKE-256 as a key derivation function (KDF). */ -#ifdef USE_INTEL_SPEEDUP -#define KYBER_KDF kyber_kdf +#if defined(USE_INTEL_SPEEDUP) || \ + (defined(WOLFSSL_ARMASM) && defined(__aarch64__)) + #define KYBER_KDF kyber_kdf #else -#define KYBER_KDF wc_Shake256Hash + #define KYBER_KDF wc_Shake256Hash #endif /******************************************************************************/ @@ -123,6 +124,10 @@ int wc_KyberKey_Init(int type, KyberKey* key, void* heap, int devId) key->devId = devId; #endif + /* Initialize the hash algorithm object. */ + ret = kyber_hash_new(&key->hash, heap, devId); + } + if (ret == 0) { /* Initialize the PRF algorithm object. */ ret = kyber_prf_new(&key->prf, heap, devId); } @@ -145,6 +150,8 @@ void wc_KyberKey_Free(KyberKey* key) if (key != NULL) { /* Dispose of PRF object. */ kyber_prf_free(&key->prf); + /* Dispose of hash object. */ + kyber_hash_free(&key->hash); /* Ensure all private data is zeroed. */ ForceZero(key, sizeof(*key)); } @@ -254,18 +261,28 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, } } if (ret == 0) { + const byte* d = rand; + /* Error vector allocated at end of a. */ e = a + (kp * kp * KYBER_N); - /* Expand 16 bytes of random to 32. */ - ret = KYBER_HASH_G(rand, KYBER_SYM_SZ, buf); +#ifdef WOLFSSL_KYBER_ORIGINAL + /* Expand 32 bytes of random to 32. */ + ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, NULL, 0, buf); +#else + buf[0] = kp; + /* Expand 33 bytes of random to 32. */ + ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, buf, 1, buf); +#endif } if (ret == 0) { + const byte* z = rand + KYBER_SYM_SZ; + /* Cache the public seed for use in encapsulation and encoding public * key. */ XMEMCPY(key->pubSeed, pubSeed, KYBER_SYM_SZ); /* Cache the z value for decapsulation and encoding private key. */ - XMEMCPY(key->z, rand + KYBER_SYM_SZ, sizeof(key->z)); + XMEMCPY(key->z, z, sizeof(key->z)); /* Generate the matrix A. */ ret = kyber_gen_matrix(&key->prf, a, kp, pubSeed, 0); @@ -286,7 +303,9 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, } /* Free dynamic memory allocated in function. */ - XFREE(a, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (key != NULL) { + XFREE(a, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + } return ret; } @@ -375,11 +394,7 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, sword16* epp = NULL; unsigned int kp = 0; unsigned int compVecSz = 0; -#ifndef USE_INTEL_SPEEDUP sword16* at = NULL; -#else - sword16 at[((KYBER_MAX_K + 3) * KYBER_MAX_K + 3) * KYBER_N]; -#endif /* Establish parameters based on key type. */ switch (key->type) { @@ -407,7 +422,6 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, break; } -#ifndef USE_INTEL_SPEEDUP if (ret == 0) { /* Allocate dynamic memory for all matrices, vectors and polynomials. */ at = (sword16*)XMALLOC(((kp + 3) * kp + 3) * KYBER_N * sizeof(sword16), @@ -416,7 +430,6 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, ret = MEMORY_E; } } -#endif if (ret == 0) { /* Assign allocated dynamic memory to pointers. @@ -470,10 +483,8 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, #endif } -#ifndef USE_INTEL_SPEEDUP /* Dispose of dynamic memory allocated in function. */ XFREE(at, key->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif return ret; } @@ -530,10 +541,12 @@ int wc_KyberKey_Encapsulate(KyberKey* key, unsigned char* ct, unsigned char* ss, int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, unsigned char* ss, const unsigned char* rand, int len) { - byte msg[2 * KYBER_SYM_SZ]; +#ifdef WOLFSSL_KYBER_ORIGINAL + byte msg[KYBER_SYM_SZ]; +#endif byte kr[2 * KYBER_SYM_SZ + 1]; int ret = 0; -#ifndef WOLFSSL_ML_KEM +#ifdef WOLFSSL_KYBER_ORIGINAL unsigned int ctSz = 0; #endif @@ -545,7 +558,7 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, ret = BUFFER_E; } -#ifndef WOLFSSL_ML_KEM +#ifdef WOLFSSL_KYBER_ORIGINAL if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { @@ -599,31 +612,36 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, ret = BAD_STATE_E; } +#ifdef WOLFSSL_KYBER_ORIGINAL if (ret == 0) { -#ifndef WOLFSSL_ML_KEM /* Hash random to anonymize as seed data. */ - ret = KYBER_HASH_H(rand, KYBER_SYM_SZ, msg); -#else - XMEMCPY(msg, rand, KYBER_SYM_SZ); -#endif + ret = KYBER_HASH_H(&key->hash, rand, KYBER_SYM_SZ, msg); } +#endif if (ret == 0) { - /* Copy the hash of the public key into msg. */ - XMEMCPY(msg + KYBER_SYM_SZ, key->h, KYBER_SYM_SZ); - /* Hash message into seed buffer. */ - ret = KYBER_HASH_G(msg, 2 * KYBER_SYM_SZ, kr); +#ifdef WOLFSSL_KYBER_ORIGINAL + ret = KYBER_HASH_G(&key->hash, msg, KYBER_SYM_SZ, key->h, KYBER_SYM_SZ, + kr); +#else + ret = KYBER_HASH_G(&key->hash, rand, KYBER_SYM_SZ, key->h, KYBER_SYM_SZ, + kr); +#endif } if (ret == 0) { /* Encapsulate the message using the key and the seed (coins). */ +#ifdef WOLFSSL_KYBER_ORIGINAL ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, ct); +#else + ret = kyberkey_encapsulate(key, rand, kr + KYBER_SYM_SZ, ct); +#endif } -#ifndef WOLFSSL_ML_KEM +#ifdef WOLFSSL_KYBER_ORIGINAL if (ret == 0) { /* Hash the cipher text after the seed. */ - ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); + ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); } if (ret == 0) { /* Derive the secret from the seed and hash of cipher text. */ @@ -739,7 +757,7 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, return ret; } -#ifdef WOLFSSL_ML_KEM +#ifndef WOLFSSL_KYBER_ORIGINAL /* Derive the secret from z and cipher text. * * @param [in] z Implicit rejection value. @@ -790,7 +808,7 @@ static int kyber_derive_secret(const byte* z, const byte* ct, word32 ctSz, int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, const unsigned char* ct, word32 len) { - byte msg[2 * KYBER_SYM_SZ]; + byte msg[KYBER_SYM_SZ]; byte kr[2 * KYBER_SYM_SZ + 1]; int ret = 0; unsigned int ctSz = 0; @@ -852,10 +870,9 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, ret = kyberkey_decapsulate(key, msg, ct); } if (ret == 0) { - /* Copy public hash over after the seed. */ - XMEMCPY(msg + KYBER_SYM_SZ, key->h, KYBER_SYM_SZ); /* Hash message into seed buffer. */ - ret = KYBER_HASH_G(msg, 2 * KYBER_SYM_SZ, kr); + ret = KYBER_HASH_G(&key->hash, msg, KYBER_SYM_SZ, key->h, KYBER_SYM_SZ, + kr); } if (ret == 0) { /* Encapsulate the message. */ @@ -865,9 +882,9 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, /* Compare generated cipher text with that passed in. */ fail = kyber_cmp(ct, cmp, ctSz); -#ifndef WOLFSSL_ML_KEM +#ifdef WOLFSSL_KYBER_ORIGINAL /* Hash the cipher text after the seed. */ - ret = KYBER_HASH_H(ct, ctSz, kr + KYBER_SYM_SZ); + ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); } if (ret == 0) { /* Change seed to z on comparison failure. */ @@ -890,7 +907,9 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, #ifndef USE_INTEL_SPEEDUP /* Dispose of dynamic memory allocated in function. */ - XFREE(cmp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (key != NULL) { + XFREE(cmp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + } #endif return ret; @@ -1052,7 +1071,7 @@ int wc_KyberKey_DecodePublicKey(KyberKey* key, const unsigned char* in, key->pubSeed[i] = p[i]; } /* Calculate public hash. */ - ret = KYBER_HASH_H(in, len, key->h); + ret = KYBER_HASH_H(&key->hash, in, len, key->h); } if (ret == 0) { /* Record public key and public hash set. */ @@ -1230,7 +1249,7 @@ int wc_KyberKey_EncodePrivateKey(KyberKey* key, unsigned char* out, word32 len) } /* Ensure hash of public key is available. */ if ((ret == 0) && ((key->flags & KYBER_FLAG_H_SET) == 0)) { - ret = KYBER_HASH_H(p - pubLen, pubLen, key->h); + ret = KYBER_HASH_H(&key->hash, p - pubLen, pubLen, key->h); } if (ret == 0) { /* Public hash is available. */ @@ -1317,7 +1336,7 @@ int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len) /* Make sure public hash is set. */ if ((key->flags & KYBER_FLAG_H_SET) == 0) { - ret = KYBER_HASH_H(out, len, key->h); + ret = KYBER_HASH_H(&key->hash, out, len, key->h); } } if (ret == 0) { diff --git a/src/wolfcrypt/src/wc_kyber_poly.c b/src/wolfcrypt/src/wc_kyber_poly.c index aed437c..52c8af3 100644 --- a/src/wolfcrypt/src/wc_kyber_poly.c +++ b/src/wolfcrypt/src/wc_kyber_poly.c @@ -57,12 +57,23 @@ * some platforms and is smaller in code size. */ +#ifdef HAVE_CONFIG_H + #include +#endif + #include #include #include #ifdef WOLFSSL_WC_KYBER +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + /* Declared in wc_kyber.c to stop compiler optimizer from simplifying. */ extern volatile sword16 kyber_opt_blocker; @@ -162,7 +173,16 @@ const sword16 zetas_inv[KYBER_N / 2] = { 3127, 3042, 1907, 1836, 1517, 359, 758, 1441 }; +#define KYBER_BARRETT(a) \ + "SMULWB r10, r14, " #a "\n\t" \ + "SMULWT r11, r14, " #a "\n\t" \ + "SMULBT r10, r12, r10\n\t" \ + "SMULBT r11, r12, r11\n\t" \ + "PKHBT r10, r10, r11, LSL #16\n\t" \ + "SSUB16 " #a ", " #a ", r10\n\t" + +#if !defined(WOLFSSL_ARMASM) /* Number-Theoretic Transform. * * @param [in, out] r Polynomial to transform. @@ -927,15 +947,16 @@ static void kyber_basemul(sword16* r, const sword16* a, const sword16* b, */ static void kyber_basemul_mont(sword16* r, const sword16* a, const sword16* b) { - unsigned int i; const sword16* zeta = zetas + 64; -#ifdef WOLFSSL_KYBER_SMALL +#if defined(WOLFSSL_KYBER_SMALL) + unsigned int i; for (i = 0; i < KYBER_N; i += 4, zeta++) { kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); } #elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) + unsigned int i; for (i = 0; i < KYBER_N; i += 8, zeta += 2) { kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); @@ -943,6 +964,7 @@ static void kyber_basemul_mont(sword16* r, const sword16* a, const sword16* b) kyber_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); } #else + unsigned int i; for (i = 0; i < KYBER_N; i += 16, zeta += 4) { kyber_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); kyber_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); @@ -965,10 +987,10 @@ static void kyber_basemul_mont(sword16* r, const sword16* a, const sword16* b) static void kyber_basemul_mont_add(sword16* r, const sword16* a, const sword16* b) { - unsigned int i; const sword16* zeta = zetas + 64; -#ifdef WOLFSSL_KYBER_SMALL +#if defined(WOLFSSL_KYBER_SMALL) + unsigned int i; for (i = 0; i < KYBER_N; i += 4, zeta++) { sword16 t0[2]; sword16 t2[2]; @@ -982,6 +1004,7 @@ static void kyber_basemul_mont_add(sword16* r, const sword16* a, r[i + 3] += t2[1]; } #elif defined(WOLFSSL_KYBER_NO_LARGE_CODE) + unsigned int i; for (i = 0; i < KYBER_N; i += 8, zeta += 2) { sword16 t0[2]; sword16 t2[2]; @@ -1003,6 +1026,7 @@ static void kyber_basemul_mont_add(sword16* r, const sword16* a, r[i + 7] += t6[1]; } #else + unsigned int i; for (i = 0; i < KYBER_N; i += 16, zeta += 4) { sword16 t0[2]; sword16 t2[2]; @@ -1041,6 +1065,7 @@ static void kyber_basemul_mont_add(sword16* r, const sword16* a, } #endif } +#endif /* Pointwise multiply elements of a and b, into r, and multiply by 2^-16. * @@ -1074,6 +1099,110 @@ void kyber_init(void) /******************************************************************************/ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + +/* Generate a public-private key pair from randomly generated data. + * + * @param [in, out] priv Private key vector of polynomials. + * @param [out] pub Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, + int kp) +{ + int i; + + /* Transform private key. All of result used in public key calculation */ + for (i = 0; i < kp; ++i) { + kyber_ntt(priv + i * KYBER_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < kp; ++i) { + /* Multiply a by private into public polynomial. */ + kyber_pointwise_acc_mont(pub + i * KYBER_N, a + i * kp * KYBER_N, priv, + kp); + /* Convert public polynomial to Montgomery form. */ + kyber_to_mont(pub + i * KYBER_N); + /* Transform error values polynomial. */ + kyber_ntt(e + i * KYBER_N); + /* Add errors to public key and reduce. */ + kyber_add_reduce(pub + i * KYBER_N, e + i * KYBER_N); + } +} + +/* Encapsuluate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [out] bp Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] at Array of vector of polynomials. + * @param [in] sp Vector of polynomials. + * @param [in] ep Error Vector of polynomials. + * @param [in] epp Error polynomial. + * @param [in] m Message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_encapsulate(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp) +{ + int i; + + /* Transform sp. All of result used in calculation of bp and v. */ + for (i = 0; i < kp; ++i) { + kyber_ntt(sp + i * KYBER_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < kp; ++i) { + /* Multiply at by sp into bp polynomial. */ + kyber_pointwise_acc_mont(bp + i * KYBER_N, at + i * kp * KYBER_N, sp, + kp); + /* Inverse transform bp polynomial. */ + kyber_invntt(bp + i * KYBER_N); + /* Add errors to bp and reduce. */ + kyber_add_reduce(bp + i * KYBER_N, ep + i * KYBER_N); + } + + /* Multiply public key by sp into v polynomial. */ + kyber_pointwise_acc_mont(v, pub, sp, kp); + /* Inverse transform v. */ + kyber_invntt(v); + /* Add errors and message to v and reduce. */ + kyber_add3_reduce(v, epp, m); +} + +/* Decapsulate message. + * + * @param [in] priv Private key vector of polynomials. + * @param [out] mp Message polynomial. + * @param [in] bp Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] kp Number of polynomials in vector. + */ +void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp) +{ + int i; + + /* Transform bp. All of result used in calculation of mp. */ + for (i = 0; i < kp; ++i) { + kyber_ntt(bp + i * KYBER_N); + } + + /* Multiply private key by bp into mp polynomial. */ + kyber_pointwise_acc_mont(mp, priv, bp, kp); + /* Inverse transform mp. */ + kyber_invntt(mp); + /* Subtract errors (mp) out of v and reduce into mp. */ + kyber_rsub_reduce(mp, v); +} + +#else + /* Generate a public-private key pair from randomly generated data. * * @param [in, out] priv Private key vector of polynomials. @@ -1126,8 +1255,9 @@ void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, int kp) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if ((IS_INTEL_AVX2(cpuid_flags)) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_keygen_avx2(priv, pub, e, a, kp); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -1204,8 +1334,9 @@ void kyber_encapsulate(const sword16* pub, sword16* bp, sword16* v, const sword16* m, int kp) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_encapsulate_avx2(pub, bp, v, at, sp, ep, epp, m, kp); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -1255,8 +1386,9 @@ void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, const sword16* v, int kp) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_decapsulate_avx2(priv, mp, bp, v, kp); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -1265,6 +1397,8 @@ void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, } } +#endif + /******************************************************************************/ #ifdef USE_INTEL_SPEEDUP @@ -1445,20 +1579,18 @@ static int kyber_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) a += 4 * KYBER_N; } - state[0] = ((word64*)seed)[0]; - state[1] = ((word64*)seed)[1]; - state[2] = ((word64*)seed)[2]; - state[3] = ((word64*)seed)[3]; + readUnalignedWords64(state, seed, 4); /* Transposed value same as not. */ state[4] = 0x1f0000 + (2 << 8) + 2; XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); - state[20] = 0x8000000000000000UL; + state[20] = W64LIT(0x8000000000000000); for (i = 0; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } - else if (IS_INTEL_AVX2(cpuid_flags)) { + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); } else { BlockSha3(state); @@ -1470,8 +1602,9 @@ static int kyber_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } - else if (IS_INTEL_AVX2(cpuid_flags)) { + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); } else { BlockSha3(state); @@ -1574,8 +1707,231 @@ static int kyber_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) return 0; } #endif /* KYBER1024 */ +#elif defined(WOLFSSL_ARMASM) && defined(__aarch64__) +#ifdef WOLFSSL_KYBER512 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k2_aarch64(sword16* a, byte* seed, int transposed) +{ + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + if (!transposed) { + state[0*25 + 4] = 0x1f0000 + (0 << 8) + 0; + state[1*25 + 4] = 0x1f0000 + (0 << 8) + 1; + state[2*25 + 4] = 0x1f0000 + (1 << 8) + 0; + } + else { + state[0*25 + 4] = 0x1f0000 + (0 << 8) + 0; + state[1*25 + 4] = 0x1f0000 + (1 << 8) + 0; + state[2*25 + 4] = 0x1f0000 + (0 << 8) + 1; + } + + kyber_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = kyber_rej_uniform_neon(a + 0 * KYBER_N, KYBER_N, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = kyber_rej_uniform_neon(a + 1 * KYBER_N, KYBER_N, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 = kyber_rej_uniform_neon(a + 2 * KYBER_N, KYBER_N, p, XOF_BLOCK_SIZE); + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N)) { + kyber_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += kyber_rej_uniform_neon(a + 0 * KYBER_N + ctr0, KYBER_N - ctr0, + p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += kyber_rej_uniform_neon(a + 1 * KYBER_N + ctr1, KYBER_N - ctr1, + p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += kyber_rej_uniform_neon(a + 2 * KYBER_N + ctr2, KYBER_N - ctr2, + p, XOF_BLOCK_SIZE); + } + + a += 3 * KYBER_N; + + readUnalignedWords64(state, seed, 4); + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (1 << 8) + 1; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = W64LIT(0x8000000000000000); + BlockSha3(state); + p = (byte*)state; + ctr0 = kyber_rej_uniform_neon(a, KYBER_N, p, XOF_BLOCK_SIZE); + while (ctr0 < KYBER_N) { + BlockSha3(state); + ctr0 += kyber_rej_uniform_neon(a + ctr0, KYBER_N - ctr0, p, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif + +#ifdef WOLFSSL_KYBER768 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k3_aarch64(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + for (k = 0; k < 3; k++) { + for (i = 0; i < 3; i++) { + if (!transposed) { + state[i*25 + 4] = 0x1f0000 + ((k << 8) + i); + } + else { + state[i*25 + 4] = 0x1f0000 + ((i << 8) + k); + } + } + + kyber_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = kyber_rej_uniform_neon(a + 0 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = kyber_rej_uniform_neon(a + 1 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + p +=25 * 8; + ctr2 = kyber_rej_uniform_neon(a + 2 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N)) { + kyber_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += kyber_rej_uniform_neon(a + 0 * KYBER_N + ctr0, + KYBER_N - ctr0, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += kyber_rej_uniform_neon(a + 1 * KYBER_N + ctr1, + KYBER_N - ctr1, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += kyber_rej_uniform_neon(a + 2 * KYBER_N + ctr2, + KYBER_N - ctr2, p, XOF_BLOCK_SIZE); + } + + a += 3 * KYBER_N; + } + + return 0; +} +#endif + +#ifdef WOLFSSL_KYBER1024 +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int kyber_gen_matrix_k4_aarch64(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + for (k = 0; k < 5; k++) { + for (i = 0; i < 3; i++) { + byte bi = ((k * 3) + i) / 4; + byte bj = ((k * 3) + i) % 4; + if (!transposed) { + state[i*25 + 4] = 0x1f0000 + (bi << 8) + bj; + } + else { + state[i*25 + 4] = 0x1f0000 + (bj << 8) + bi; + } + } + + kyber_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = kyber_rej_uniform_neon(a + 0 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = kyber_rej_uniform_neon(a + 1 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 = kyber_rej_uniform_neon(a + 2 * KYBER_N, KYBER_N, p, + XOF_BLOCK_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < KYBER_N) || (ctr1 < KYBER_N) || (ctr2 < KYBER_N)) { + kyber_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += kyber_rej_uniform_neon(a + 0 * KYBER_N + ctr0, + KYBER_N - ctr0, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += kyber_rej_uniform_neon(a + 1 * KYBER_N + ctr1, + KYBER_N - ctr1, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += kyber_rej_uniform_neon(a + 2 * KYBER_N + ctr2, + KYBER_N - ctr2, p, XOF_BLOCK_SIZE); + } + + a += 3 * KYBER_N; + } + + readUnalignedWords64(state, seed, 4); + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (3 << 8) + 3; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = W64LIT(0x8000000000000000); + BlockSha3(state); + p = (byte*)state; + ctr0 = kyber_rej_uniform_neon(a, KYBER_N, p, XOF_BLOCK_SIZE); + while (ctr0 < KYBER_N) { + BlockSha3(state); + ctr0 += kyber_rej_uniform_neon(a + ctr0, KYBER_N - ctr0, p, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif #endif /* USE_INTEL_SPEEDUP */ +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) /* Absorb the seed data for squeezing out pseudo-random data. * * @param [in, out] shake128 SHAKE-128 object. @@ -1606,6 +1962,56 @@ static int kyber_xof_squeezeblocks(wc_Shake* shake128, byte* out, int blocks) { return wc_Shake128_SqueezeBlocks(shake128, out, blocks); } +#endif + +/* New/Initialize SHA-3 object. + * + * @param [in, out] hash SHA-3 object. + * @param [in] heap Dynamic memory allocator hint. + * @param [in] devId Device id. + * @return 0 on success always. + */ +int kyber_hash_new(wc_Sha3* hash, void* heap, int devId) +{ + return wc_InitSha3_256(hash, heap, devId); +} + +/* Free SHA-3 object. + * + * @param [in, out] hash SHA-3 object. + */ +void kyber_hash_free(wc_Sha3* hash) +{ + wc_Sha3_256_Free(hash); +} + +int kyber_hash256(wc_Sha3* hash, const byte* data, word32 dataLen, byte* out) +{ + int ret; + + ret = wc_Sha3_256_Update(hash, data, dataLen); + if (ret == 0) { + ret = wc_Sha3_256_Final(hash, out); + } + + return ret; +} + +int kyber_hash512(wc_Sha3* hash, const byte* data1, word32 data1Len, + const byte* data2, word32 data2Len, byte* out) +{ + int ret; + + ret = wc_Sha3_512_Update(hash, data1, data1Len); + if ((ret == 0) && (data2Len > 0)) { + ret = wc_Sha3_512_Update(hash, data2, data2Len); + } + if (ret == 0) { + ret = wc_Sha3_512_Final(hash, out); + } + + return ret; +} /* Initialize SHAKE-256 object. * @@ -1637,6 +2043,7 @@ void kyber_prf_free(wc_Shake* prf) wc_Shake256_Free(prf); } +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) /* Create pseudo-random data from the key using SHAKE-256. * * @param [in, out] shake256 SHAKE-256 object. @@ -1650,24 +2057,22 @@ static int kyber_prf(wc_Shake* shake256, byte* out, unsigned int outLen, const byte* key) { #ifdef USE_INTEL_SPEEDUP - int i; word64 state[25]; (void)shake256; - for (i = 0; i < KYBER_SYM_SZ / 8; i++) { - state[i] = ((word64*)key)[i]; - } + readUnalignedWords64(state, key, KYBER_SYM_SZ / sizeof(word64)); state[KYBER_SYM_SZ / 8] = 0x1f00 | key[KYBER_SYM_SZ]; XMEMSET(state + KYBER_SYM_SZ / 8 + 1, 0, (25 - KYBER_SYM_SZ / 8 - 1) * sizeof(word64)); - state[WC_SHA3_256_COUNT - 1] = 0x8000000000000000UL; + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } - else if (IS_INTEL_AVX2(cpuid_flags)) { + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); } else { BlockSha3(state); @@ -1686,6 +2091,7 @@ static int kyber_prf(wc_Shake* shake256, byte* out, unsigned int outLen, return ret; #endif } +#endif #ifdef USE_INTEL_SPEEDUP /* Create pseudo-random key from the seed using SHAKE-256. @@ -1699,21 +2105,19 @@ static int kyber_prf(wc_Shake* shake256, byte* out, unsigned int outLen, int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen) { word64 state[25]; - int i; - int len64 = seedLen / 8; + word32 len64 = seedLen / 8; - for (i = 0; i < len64; i++) { - state[i] = ((word64*)seed)[i]; - } + readUnalignedWords64(state, seed, len64); state[len64] = 0x1f; XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); - state[WC_SHA3_256_COUNT - 1] = 0x8000000000000000UL; + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } - else if (IS_INTEL_AVX2(cpuid_flags)) { + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); } else { BlockSha3(state); @@ -1724,6 +2128,33 @@ int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen) } #endif +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) +/* Create pseudo-random key from the seed using SHAKE-256. + * + * @param [in] seed Data to derive from. + * @param [in] seedLen Length of data to derive from in bytes. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to derive. + * @return 0 on success always. + */ +int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen) +{ + word64 state[25]; + word32 len64 = seedLen / 8; + + readUnalignedWords64(state, seed, len64); + state[len64] = 0x1f; + XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); + + BlockSha3(state); + XMEMCPY(out, state, outLen); + + return 0; +} +#endif + +#if !defined(WOLFSSL_ARMASM) /* Rejection sampling on uniform random bytes to generate uniform random * integers mod q. * @@ -1739,6 +2170,7 @@ static unsigned int kyber_rej_uniform_c(sword16* p, unsigned int len, unsigned int i; unsigned int j; +#if defined(WOLFSSL_KYBER_SMALL) || !defined(WC_64BIT_CPU) /* Keep sampling until maximum number of integers reached or buffer used up. */ for (i = 0, j = 0; (i < len) && (j <= rLen - 3); j += 3) { @@ -1759,10 +2191,93 @@ static unsigned int kyber_rej_uniform_c(sword16* p, unsigned int len, /* Move over used bytes. */ r += 3; } +#else + unsigned int minJ; + + minJ = len / 4 * 6; + if (minJ > rLen) + minJ = rLen; + i = 0; + for (j = 0; j < minJ; j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + p[i] = v0 & (0 - (v0 < KYBER_Q)); + i += v0 < KYBER_Q; + p[i] = v1 & (0 - (v1 < KYBER_Q)); + i += v1 < KYBER_Q; + p[i] = v2 & (0 - (v2 < KYBER_Q)); + i += v2 < KYBER_Q; + p[i] = v3 & (0 - (v3 < KYBER_Q)); + i += v3 < KYBER_Q; + + /* Move over used bytes. */ + r += 6; + } + if (j < rLen) { + for (; (i + 4 < len) && (j < rLen); j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + p[i] = v0; + i += v0 < KYBER_Q; + p[i] = v1; + i += v1 < KYBER_Q; + p[i] = v2; + i += v2 < KYBER_Q; + p[i] = v3; + i += v3 < KYBER_Q; + + /* Move over used bytes. */ + r += 6; + } + for (; (i < len) && (j < rLen); j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + /* Reject first 12-bit integer if greater than or equal to q. */ + if (v0 < KYBER_Q) { + p[i++] = v0; + } + /* Check second if we don't have enough integers yet. + * Reject second 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v1 < KYBER_Q)) { + p[i++] = v1; + } + /* Check second if we don't have enough integers yet. + * Reject third 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v2 < KYBER_Q)) { + p[i++] = v2; + } + /* Check second if we don't have enough integers yet. + * Reject fourth 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v3 < KYBER_Q)) { + p[i++] = v3; + } + + /* Move over used bytes. */ + r += 6; + } + } +#endif return i; } +#endif +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1798,6 +2313,12 @@ static int kyber_gen_matrix_c(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, } #endif +#if !defined(WOLFSSL_KYBER_SMALL) && defined(WC_64BIT_CPU) + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[GEN_MATRIX_SIZE+0] = 0xff; + rand[GEN_MATRIX_SIZE+1] = 0xff; +#endif + /* Generate each vector of polynomials. */ for (i = 0; (ret == 0) && (i < kp); i++, a += kp * KYBER_N) { int j; @@ -1818,35 +2339,17 @@ static int kyber_gen_matrix_c(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, ret = kyber_xof_squeezeblocks(prf, rand, GEN_MATRIX_NBLOCKS); } if (ret == 0) { - #if (GEN_MATRIX_SIZE % 3) != 0 - unsigned int randLen; - #endif unsigned int ctr; /* Sample random bytes to create a polynomial. */ ctr = kyber_rej_uniform_c(a + j * KYBER_N, KYBER_N, rand, GEN_MATRIX_SIZE); /* Create more blocks if too many rejected. */ - #if (GEN_MATRIX_SIZE % 3) != 0 - randLen = GEN_MATRIX_SIZE; - while (ctr < KYBER_N) { - int off = randLen % 3; - int k; - for (k = 0; k < off; k++) { - rand[k] = rand[randLen - off + k]; - } - kyber_xof_squeezeblocks(prf, rand + off, 1); - randLen = off + XOF_BLOCK_SIZE; - ctr += kyber_rej_uniform_c(a + j * KYBER_N + ctr, - KYBER_N - ctr, rand, randLen); - } - #else while (ctr < KYBER_N) { kyber_xof_squeezeblocks(prf, rand, 1); ctr += kyber_rej_uniform_c(a + j * KYBER_N + ctr, KYBER_N - ctr, rand, XOF_BLOCK_SIZE); } - #endif } } } @@ -1858,6 +2361,7 @@ static int kyber_gen_matrix_c(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, return ret; } +#endif /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * @@ -1879,43 +2383,58 @@ int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, #ifdef WOLFSSL_KYBER512 if (kp == KYBER512_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_gen_matrix_k2_aarch64(a, seed, transposed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_gen_matrix_k2_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); } else #endif { ret = kyber_gen_matrix_c(prf, a, KYBER512_K, seed, transposed); } +#endif } else #endif #ifdef WOLFSSL_KYBER768 if (kp == KYBER768_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_gen_matrix_k3_aarch64(a, seed, transposed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_gen_matrix_k3_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); } else #endif { ret = kyber_gen_matrix_c(prf, a, KYBER768_K, seed, transposed); } +#endif } else #endif #ifdef WOLFSSL_KYBER1024 if (kp == KYBER1024_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_gen_matrix_k4_aarch64(a, seed, transposed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_gen_matrix_k4_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); } else #endif { ret = kyber_gen_matrix_c(prf, a, KYBER1024_K, seed, transposed); } +#endif } else #endif @@ -1923,6 +2442,8 @@ int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, ret = BAD_STATE_E; } + (void)prf; + return ret; } @@ -1994,9 +2515,9 @@ static void kyber_cbd_eta2(sword16* p, const byte* r) #endif /* Take the next 8 bytes, little endian, as a 64 bit value. */ #ifdef BIG_ENDIAN_ORDER - word64 t = ByteReverseWord64(*(word64*)r); + word64 t = ByteReverseWord64(readUnalignedWord64(r)); #else - word64 t = *(word64*)r; + word64 t = readUnalignedWord64(r); #endif word64 d; /* Add second bits to first. */ @@ -2187,6 +2708,8 @@ static void kyber_cbd_eta3(sword16* p, const byte* r) } #endif +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) + /* Get noise/error by calculating random bytes and sampling to a binomial * distribution. * @@ -2253,6 +2776,8 @@ static int kyber_get_noise_eta2_c(KYBER_PRF_T* prf, sword16* p, return ret; } +#endif + #ifdef USE_INTEL_SPEEDUP #define PRF_RAND_SZ (2 * SHA3_256_BYTES) @@ -2435,6 +2960,206 @@ static int kyber_get_noise_k4_avx2(KYBER_PRF_T* prf, sword16* vec1, #endif #endif /* USE_INTEL_SPEEDUP */ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + +#define PRF_RAND_SZ (2 * SHA3_256_BYTES) + +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void kyber_get_noise_x3_eta2_aarch64(byte* rand, byte* seed, byte o) +{ + word64* state = (word64*)rand; + + state[0*25 + 4] = 0x1f00 + 0 + o; + state[1*25 + 4] = 0x1f00 + 1 + o; + state[2*25 + 4] = 0x1f00 + 2 + o; + + kyber_shake256_blocksx3_seed_neon(state, seed); +} + +#ifdef WOLFSSL_KYBER512 +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void kyber_get_noise_x3_eta3_aarch64(byte* rand, byte* seed, byte o) +{ + word64 state[3 * 25]; + + state[0*25 + 4] = 0x1f00 + 0 + o; + state[1*25 + 4] = 0x1f00 + 1 + o; + state[2*25 + 4] = 0x1f00 + 2 + o; + + kyber_shake256_blocksx3_seed_neon(state, seed); + XMEMCPY(rand + 0 * ETA3_RAND_SIZE, state + 0*25, SHA3_256_BYTES); + XMEMCPY(rand + 1 * ETA3_RAND_SIZE, state + 1*25, SHA3_256_BYTES); + XMEMCPY(rand + 2 * ETA3_RAND_SIZE, state + 2*25, SHA3_256_BYTES); + kyber_sha3_blocksx3_neon(state); + rand += SHA3_256_BYTES; + XMEMCPY(rand + 0 * ETA3_RAND_SIZE, state + 0*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); + XMEMCPY(rand + 1 * ETA3_RAND_SIZE, state + 1*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); + XMEMCPY(rand + 2 * ETA3_RAND_SIZE, state + 2*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); +} + +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + * @return 0 on success. + */ +static void kyber_get_noise_eta3_aarch64(byte* rand, byte* seed, byte o) +{ + word64 state[25]; + + state[0] = ((word64*)seed)[0]; + state[1] = ((word64*)seed)[1]; + state[2] = ((word64*)seed)[2]; + state[3] = ((word64*)seed)[3]; + state[4] = 0x1f00 + o; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[16] = W64LIT(0x8000000000000000); + BlockSha3(state); + XMEMCPY(rand , state, SHA3_256_BYTES); + BlockSha3(state); + XMEMCPY(rand + SHA3_256_BYTES, state, ETA3_RAND_SIZE - SHA3_256_BYTES); +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k2_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[3 * 25 * 8]; + + kyber_get_noise_x3_eta3_aarch64(rand, seed, 0); + kyber_cbd_eta3(vec1 , rand + 0 * ETA3_RAND_SIZE); + kyber_cbd_eta3(vec1 + KYBER_N, rand + 1 * ETA3_RAND_SIZE); + if (poly == NULL) { + kyber_cbd_eta3(vec2 , rand + 2 * ETA3_RAND_SIZE); + kyber_get_noise_eta3_aarch64(rand, seed, 3); + kyber_cbd_eta3(vec2 + KYBER_N, rand ); + } + else { + kyber_get_noise_x3_eta2_aarch64(rand, seed, 2); + kyber_cbd_eta2(vec2 , rand + 0 * 25 * 8); + kyber_cbd_eta2(vec2 + KYBER_N, rand + 1 * 25 * 8); + kyber_cbd_eta2(poly , rand + 2 * 25 * 8); + } + + return ret; +} +#endif + +#ifdef WOLFSSL_KYBER768 +/* Get the noise/error by calculating random bytes. + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + * @return 0 on success. + */ +static void kyber_get_noise_eta2_aarch64(byte* rand, byte* seed, byte o) +{ + word64* state = (word64*)rand; + + state[0] = ((word64*)seed)[0]; + state[1] = ((word64*)seed)[1]; + state[2] = ((word64*)seed)[2]; + state[3] = ((word64*)seed)[3]; + /* Transposed value same as not. */ + state[4] = 0x1f00 + o; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[16] = W64LIT(0x8000000000000000); + BlockSha3(state); +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k3_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + byte rand[3 * 25 * 8]; + + kyber_get_noise_x3_eta2_aarch64(rand, seed, 0); + kyber_cbd_eta2(vec1 , rand + 0 * 25 * 8); + kyber_cbd_eta2(vec1 + 1 * KYBER_N, rand + 1 * 25 * 8); + kyber_cbd_eta2(vec1 + 2 * KYBER_N, rand + 2 * 25 * 8); + kyber_get_noise_x3_eta2_aarch64(rand, seed, 3); + kyber_cbd_eta2(vec2 , rand + 0 * 25 * 8); + kyber_cbd_eta2(vec2 + 1 * KYBER_N, rand + 1 * 25 * 8); + kyber_cbd_eta2(vec2 + 2 * KYBER_N, rand + 2 * 25 * 8); + if (poly != NULL) { + kyber_get_noise_eta2_aarch64(rand, seed, 6); + kyber_cbd_eta2(poly , rand + 0 * 25 * 8); + } + + return 0; +} +#endif + +#ifdef WOLFSSL_KYBER1024 +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int kyber_get_noise_k4_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[3 * 25 * 8]; + + kyber_get_noise_x3_eta2_aarch64(rand, seed, 0); + kyber_cbd_eta2(vec1 , rand + 0 * 25 * 8); + kyber_cbd_eta2(vec1 + 1 * KYBER_N, rand + 1 * 25 * 8); + kyber_cbd_eta2(vec1 + 2 * KYBER_N, rand + 2 * 25 * 8); + kyber_get_noise_x3_eta2_aarch64(rand, seed, 3); + kyber_cbd_eta2(vec1 + 3 * KYBER_N, rand + 0 * 25 * 8); + kyber_cbd_eta2(vec2 , rand + 1 * 25 * 8); + kyber_cbd_eta2(vec2 + 1 * KYBER_N, rand + 2 * 25 * 8); + kyber_get_noise_x3_eta2_aarch64(rand, seed, 6); + kyber_cbd_eta2(vec2 + 2 * KYBER_N, rand + 0 * 25 * 8); + kyber_cbd_eta2(vec2 + 3 * KYBER_N, rand + 1 * 25 * 8); + if (poly != NULL) { + kyber_cbd_eta2(poly, rand + 2 * 25 * 8); + } + + return ret; +} +#endif +#endif /* __aarch64__ && WOLFSSL_ARMASM */ + +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) + /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * @@ -2478,6 +3203,8 @@ static int kyber_get_noise_c(KYBER_PRF_T* prf, int kp, sword16* vec1, int eta1, return ret; } +#endif /* __aarch64__ && WOLFSSL_ARMASM */ + /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * @@ -2496,9 +3223,13 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, #ifdef WOLFSSL_KYBER512 if (kp == KYBER512_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_get_noise_k2_aarch64(vec1, vec2, poly, seed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_get_noise_k2_avx2(prf, vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -2510,14 +3241,19 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA3, vec2, KYBER_CBD_ETA2, poly, seed); } +#endif } else #endif #ifdef WOLFSSL_KYBER768 if (kp == KYBER768_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_get_noise_k3_aarch64(vec1, vec2, poly, seed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_get_noise_k3_avx2(vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -2525,14 +3261,19 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA2, vec2, KYBER_CBD_ETA2, poly, seed); } +#endif } else #endif #ifdef WOLFSSL_KYBER1024 if (kp == KYBER1024_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = kyber_get_noise_k4_aarch64(vec1, vec2, poly, seed); +#else #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { ret = kyber_get_noise_k4_avx2(prf, vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -2540,6 +3281,7 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, ret = kyber_get_noise_c(prf, kp, vec1, KYBER_CBD_ETA2, vec2, KYBER_CBD_ETA2, poly, seed); } +#endif } else #endif @@ -2547,11 +3289,14 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, ret = BAD_STATE_E; } + (void)prf; + return ret; } /******************************************************************************/ +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) /* Compare two byte arrays of equal size. * * @param [in] a First array to compare. @@ -2571,6 +3316,7 @@ static int kyber_cmp_c(const byte* a, const byte* b, int sz) } return 0 - ((-(word32)r) >> 31); } +#endif /* Compare two byte arrays of equal size. * @@ -2582,11 +3328,15 @@ static int kyber_cmp_c(const byte* a, const byte* b, int sz) */ int kyber_cmp(const byte* a, const byte* b, int sz) { +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + return kyber_cmp_neon(a, b, sz); +#else int fail; #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { fail = kyber_cmp_avx2(a, b, sz); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -2595,10 +3345,13 @@ int kyber_cmp(const byte* a, const byte* b, int sz) } return fail; +#endif } /******************************************************************************/ +#if !defined(WOLFSSL_ARMASM) + /* Conditional subtraction of q to each coefficient of a polynomial. * * @param [in, out] p Polynomial. @@ -2614,6 +3367,20 @@ static KYBER_NOINLINE void kyber_csubq_c(sword16* p) } } +#elif defined(__aarch64__) + +#define kyber_csubq_c kyber_csubq_neon + +#elif defined(WOLFSSL_ARMASM_THUMB2) + +#define kyber_csubq_c kyber_thumb2_csubq + +#else + +#define kyber_csubq_c kyber_arm32_csubq + +#endif + /******************************************************************************/ #if defined(CONV_WITH_DIV) || !defined(WORD64_AVAILABLE) @@ -2814,8 +3581,9 @@ static void kyber_vec_compress_10_c(byte* r, sword16* v, unsigned int kp) void kyber_vec_compress_10(byte* r, sword16* v, unsigned int kp) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_compress_10_avx2(r, v, kp); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -2907,8 +3675,9 @@ static void kyber_vec_compress_11_c(byte* r, sword16* v) void kyber_vec_compress_11(byte* r, sword16* v) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_compress_11_avx2(r, v, 4); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3005,8 +3774,9 @@ void kyber_vec_decompress_10(sword16* v, const unsigned char* b, unsigned int kp) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_decompress_10_avx2(v, b, kp); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3088,8 +3858,9 @@ static void kyber_vec_decompress_11_c(sword16* v, const unsigned char* b) void kyber_vec_decompress_11(sword16* v, const unsigned char* b) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_decompress_11_avx2(v, b, 4); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3238,8 +4009,9 @@ static void kyber_compress_4_c(byte* b, sword16* p) void kyber_compress_4(byte* b, sword16* p) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_compress_4_avx2(b, p); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3311,8 +4083,9 @@ static void kyber_compress_5_c(byte* b, sword16* p) void kyber_compress_5(byte* b, sword16* p) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_compress_5_avx2(b, p); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3371,8 +4144,9 @@ static void kyber_decompress_4_c(sword16* p, const unsigned char* b) void kyber_decompress_4(sword16* p, const unsigned char* b) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_decompress_4_avx2(p, b); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3445,8 +4219,9 @@ static void kyber_decompress_5_c(sword16* p, const unsigned char* b) void kyber_decompress_5(sword16* p, const unsigned char* b) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_decompress_5_avx2(p, b); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3458,6 +4233,7 @@ void kyber_decompress_5(sword16* p, const unsigned char* b) /******************************************************************************/ +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) /* Convert bit from byte to 0 or (KYBER_Q + 1) / 2. * * Constant time implementation. @@ -3511,8 +4287,9 @@ static void kyber_from_msg_c(sword16* p, const byte* msg) void kyber_from_msg(sword16* p, const byte* msg) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { kyber_from_msg_avx2(p, msg); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3569,7 +4346,7 @@ static void kyber_to_msg_c(byte* msg, sword16* p) /* Reduce each coefficient to mod q. */ kyber_csubq_c(p); - /* All values are now positive. */ + /* All values are now in range. */ for (i = 0; i < KYBER_N / 8; i++) { #ifdef WOLFSSL_KYBER_SMALL @@ -3600,9 +4377,10 @@ static void kyber_to_msg_c(byte* msg, sword16* p) void kyber_to_msg(byte* msg, sword16* p) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { /* Convert the polynomial into a array of bytes (message). */ kyber_to_msg_avx2(msg, p); + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3610,6 +4388,27 @@ void kyber_to_msg(byte* msg, sword16* p) kyber_to_msg_c(msg, p); } } +#else +/* Convert message to polynomial. + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +void kyber_from_msg(sword16* p, const byte* msg) +{ + kyber_from_msg_neon(p, msg); +} + +/* Convert polynomial to message. + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +void kyber_to_msg(byte* msg, sword16* p) +{ + kyber_to_msg_neon(msg, p); +} +#endif /******************************************************************************/ @@ -3651,7 +4450,7 @@ static void kyber_from_bytes_c(sword16* p, const byte* b, int k) void kyber_from_bytes(sword16* p, const byte* b, int k) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { int i; for (i = 0; i < k; i++) { @@ -3659,6 +4458,8 @@ void kyber_from_bytes(sword16* p, const byte* b, int k) p += KYBER_N; b += KYBER_POLY_SIZE; } + + RESTORE_VECTOR_REGISTERS(); } else #endif @@ -3710,7 +4511,7 @@ static void kyber_to_bytes_c(byte* b, sword16* p, int k) void kyber_to_bytes(byte* b, sword16* p, int k) { #ifdef USE_INTEL_SPEEDUP - if (IS_INTEL_AVX2(cpuid_flags)) { + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { int i; for (i = 0; i < k; i++) { @@ -3718,6 +4519,8 @@ void kyber_to_bytes(byte* b, sword16* p, int k) p += KYBER_N; b += KYBER_POLY_SIZE; } + + RESTORE_VECTOR_REGISTERS(); } else #endif diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index 0ef0b59..4559001 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -42,8 +42,8 @@ * * @param [in] w Winternitz width. */ -#define LMS_U(w) \ - (8 * WC_SHA256_DIGEST_SIZE / (w)) +#define LMS_U(w, hLen) \ + (8 * (hLen) / (w)) /* Calculate u. Appendix B. Works for w of 1, 2, 4, or 8. * * @param [in] w Winternitz width. @@ -63,17 +63,17 @@ * @param [in] w Winternitz width. * @param [in] wb Winternitz width length in bits. */ -#define LMS_P(w, wb) \ - (LMS_U(w) + LMS_V(w, wb)) +#define LMS_P(w, wb, hLen) \ + (LMS_U(w, hLen) + LMS_V(w, wb)) /* Calculate signature length. * * @param [in] l Number of levels. * @param [in] h Height of the trees. * @param [in] p Number of n-byte string elements in signature for a tree. */ -#define LMS_PARAMS_SIG_LEN(l, h, p) \ - (4 + (l) * (4 + 4 + 4 + WC_SHA256_DIGEST_SIZE * (1 + (p) + (h))) + \ - ((l) - 1) * LMS_PUBKEY_LEN) +#define LMS_PARAMS_SIG_LEN(l, h, p, hLen) \ + (4 + (l) * (4 + 4 + 4 + (hLen) * (1 + (p) + (h))) + \ + ((l) - 1) * LMS_PUBKEY_LEN(hLen)) #ifndef WOLFSSL_WC_LMS_SMALL /* Root levels and leaf cache bits. */ @@ -94,9 +94,10 @@ * @param [in] t LMS type. * @param [in] t2 LM-OTS type. */ -#define LMS_PARAMS(l, h, w, wb, t, t2) \ - { l, h, w, LMS_LS(w, wb), LMS_P(w, wb), t, t2, \ - LMS_PARAMS_SIG_LEN(l, h, LMS_P(w, wb)), LMS_PARAMS_CACHE(h) } +#define LMS_PARAMS(l, h, w, wb, t, t2, hLen) \ + { l, h, w, LMS_LS(w, wb), LMS_P(w, wb, hLen), t, t2, \ + LMS_PARAMS_SIG_LEN(l, h, LMS_P(w, wb, hLen), hLen), \ + (hLen), LMS_PARAMS_CACHE(h) } /* Initialize the working state for LMS operations. @@ -138,112 +139,230 @@ static void wc_lmskey_state_free(LmsState* state) /* Supported LMS parameters. */ static const wc_LmsParamsMap wc_lms_map[] = { +#ifndef WOLFSSL_NO_LMS_SHA256_256 #if LMS_MAX_HEIGHT >= 15 { WC_LMS_PARM_NONE , "LMS_NONE" , - LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H15_W2, "LMS/HSS L1_H15_W2", - LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H15_W4, "LMS/HSS L1_H15_W4", - LMS_PARAMS(1, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(1, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, #endif #if LMS_MAX_LEVELS >= 2 #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_L2_H10_W2, "LMS/HSS L2_H10_W2", - LMS_PARAMS(2, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(2, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H10_W4, "LMS/HSS L2_H10_W4", - LMS_PARAMS(2, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(2, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H10_W8, "LMS/HSS L2_H10_W8", - LMS_PARAMS(2, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(2, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 3 { WC_LMS_PARM_L3_H5_W2 , "LMS/HSS L3_H5_W2" , - LMS_PARAMS(3, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(3, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L3_H5_W4 , "LMS/HSS L3_H5_W4" , - LMS_PARAMS(3, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(3, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L3_H5_W8 , "LMS/HSS L3_H5_W8" , - LMS_PARAMS(3, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(3, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_L3_H10_W4, "LMS/HSS L3_H10_W4", - LMS_PARAMS(3, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(3, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 4 { WC_LMS_PARM_L4_H5_W8 , "LMS/HSS L4_H5_W8" , - LMS_PARAMS(4, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(4, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif /* For when user sets L, H, W explicitly. */ { WC_LMS_PARM_L1_H5_W1 , "LMS/HSS_L1_H5_W1" , - LMS_PARAMS(1, 5, 1, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W1) }, + LMS_PARAMS(1, 5, 1, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W1, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H5_W2 , "LMS/HSS_L1_H5_W2" , - LMS_PARAMS(1, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(1, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H5_W4 , "LMS/HSS_L1_H5_W4" , - LMS_PARAMS(1, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(1, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H5_W8 , "LMS/HSS_L1_H5_W8" , - LMS_PARAMS(1, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(1, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_L1_H10_W2 , "LMS/HSS_L1_H10_W2", - LMS_PARAMS(1, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(1, 10, 2, 1, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H10_W4 , "LMS/HSS_L1_H10_W4", - LMS_PARAMS(1, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(1, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H10_W8 , "LMS/HSS_L1_H10_W8", - LMS_PARAMS(1, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(1, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #if LMS_MAX_HEIGHT >= 15 { WC_LMS_PARM_L1_H15_W8 , "LMS/HSS L1_H15_W8", - LMS_PARAMS(1, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(1, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #if LMS_MAX_HEIGHT >= 20 { WC_LMS_PARM_L1_H20_W2 , "LMS/HSS_L1_H20_W2", - LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H20_W4 , "LMS/HSS_L1_H20_W4", - LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L1_H20_W8 , "LMS/HSS_L1_H20_W8", - LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #if LMS_MAX_LEVELS >= 2 { WC_LMS_PARM_L2_H5_W2 , "LMS/HSS_L2_H5_W2" , - LMS_PARAMS(2, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(2, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H5_W4 , "LMS/HSS_L2_H5_W4" , - LMS_PARAMS(2, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(2, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H5_W8 , "LMS/HSS_L2_H5_W8" , - LMS_PARAMS(2, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(2, 5, 8, 3, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 15 { WC_LMS_PARM_L2_H15_W2 , "LMS/HSS_L2_H15_W2", - LMS_PARAMS(2, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(2, 15, 2, 1, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H15_W4 , "LMS/HSS_L2_H15_W4", - LMS_PARAMS(2, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(2, 15, 4, 2, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H15_W8 , "LMS/HSS_L2_H15_W8", - LMS_PARAMS(2, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(2, 15, 8, 3, LMS_SHA256_M32_H15, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #if LMS_MAX_HEIGHT >= 20 { WC_LMS_PARM_L2_H20_W2 , "LMS/HSS_L2_H20_W2", - LMS_PARAMS(2, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(2, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H20_W4 , "LMS/HSS_L2_H20_W4", - LMS_PARAMS(2, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(2, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L2_H20_W8 , "LMS/HSS_L2_H20_W8", - LMS_PARAMS(2, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(2, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 3 #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_L3_H10_W8 , "LMS/HSS L3_H10_W8", - LMS_PARAMS(3, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(3, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 4 { WC_LMS_PARM_L4_H5_W2 , "LMS/HSS L4_H5_W2" , - LMS_PARAMS(4, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2) }, + LMS_PARAMS(4, 5, 2, 1, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W2, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L4_H5_W4 , "LMS/HSS L4_H5_W4" , - LMS_PARAMS(4, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(4, 5, 4, 2, LMS_SHA256_M32_H5 , LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_L4_H10_W4 , "LMS/HSS L4_H10_W4", - LMS_PARAMS(4, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4) }, + LMS_PARAMS(4, 10, 4, 2, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4, + WC_SHA256_DIGEST_SIZE) }, { WC_LMS_PARM_L4_H10_W8 , "LMS/HSS L4_H10_W8", - LMS_PARAMS(4, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8) }, + LMS_PARAMS(4, 10, 8, 3, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W8, + WC_SHA256_DIGEST_SIZE) }, #endif #endif +#endif /* !WOLFSSL_NO_LMS_SHA256_256 */ + +#ifdef WOLFSSL_LMS_SHA256_192 +#if LMS_MAX_HEIGHT >= 15 + { WC_LMS_PARM_SHA256_192_L1_H15_W2, "LMS/HSS_SHA256/192 L1_H15_W2", + LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H15_W4, "LMS/HSS_SHA256/192 L1_H15_W4", + LMS_PARAMS(1, 15, 4, 2, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, +#endif +#if LMS_MAX_LEVELS >= 2 +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_SHA256_192_L2_H10_W2, "LMS/HSS SHA256/192 L2_H10_W2", + LMS_PARAMS(2, 10, 2, 1, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L2_H10_W4, "LMS/HSS SHA256/192 L2_H10_W4", + LMS_PARAMS(2, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L2_H10_W8, "LMS/HSS SHA256/192 L2_H10_W8", + LMS_PARAMS(2, 10, 8, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#endif +#endif +#if LMS_MAX_LEVELS >= 3 + { WC_LMS_PARM_SHA256_192_L3_H5_W2 , "LMS/HSS_SHA256/192 L3_H5_W2" , + LMS_PARAMS(3, 5, 2, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L3_H5_W4 , "LMS/HSS_SHA256/192 L3_H5_W4" , + LMS_PARAMS(3, 5, 4, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L3_H5_W8 , "LMS/HSS_SHA256/192 L3_H5_W8" , + LMS_PARAMS(3, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_SHA256_192_L3_H10_W4, "LMS/HSS_SHA256/192 L3_H10_W4", + LMS_PARAMS(3, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, +#endif +#endif +#if LMS_MAX_LEVELS >= 4 + { WC_LMS_PARM_SHA256_192_L4_H5_W8 , "LMS/HSS_SHA256/192 L4_H5_W8" , + LMS_PARAMS(4, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#endif + + { WC_LMS_PARM_SHA256_192_L1_H5_W1 , "LMS/HSS_SHA256/192_L1_H5_W1" , + LMS_PARAMS(1, 5, 1, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W1, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H5_W2 , "LMS/HSS_SHA256/192_L1_H5_W2" , + LMS_PARAMS(1, 5, 2, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H5_W4 , "LMS/HSS_SHA256/192_L1_H5_W4" , + LMS_PARAMS(1, 5, 4, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H5_W8 , "LMS/HSS_SHA256/192_L1_H5_W8" , + LMS_PARAMS(1, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#if LMS_MAX_HEIGHT >= 10 + { WC_LMS_PARM_SHA256_192_L1_H10_W2 , "LMS/HSS_SHA256/192_L1_H10_W2", + LMS_PARAMS(1, 10, 2, 1, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H10_W4 , "LMS/HSS_SHA256/192_L1_H10_W4", + LMS_PARAMS(1, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_SHA256_192_L1_H10_W8 , "LMS/HSS_SHA256/192_L1_H10_W8", + LMS_PARAMS(1, 10, 8, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#endif +#if LMS_MAX_HEIGHT >= 20 + { WC_LMS_PARM_L1_H20_W2 , "LMS/HSS_SHA256/192_L1_H20_W2", + LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_L1_H20_W4 , "LMS/HSS_SHA256/192_L1_H20_W4", + LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4, + WC_SHA256_192_DIGEST_SIZE) }, + { WC_LMS_PARM_L1_H20_W8 , "LMS/HSS_SHA256/192_L1_H20_W8", + LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8, + WC_SHA256_192_DIGEST_SIZE) }, +#endif +#endif /* WOLFSSL_LMS_SHA256_192 */ }; /* Number of parameter sets supported. */ #define WC_LMS_MAP_LEN ((int)(sizeof(wc_lms_map) / sizeof(*wc_lms_map))) @@ -476,7 +595,7 @@ void wc_LmsKey_Free(LmsKey* key) ForceZero(key->priv_data, LMS_PRIV_DATA_LEN(params->levels, params->height, params->p, params->rootLevels, - params->cacheBits)); + params->cacheBits, params->hash_len)); XFREE(key->priv_data, key->heap, DYNAMIC_TYPE_LMS); } @@ -629,9 +748,9 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) const LmsParams* params = key->params; /* Allocate memory for the private key data. */ - key->priv_data = XMALLOC(LMS_PRIV_DATA_LEN(params->levels, - params->height, params->p, params->rootLevels, params->cacheBits), - key->heap, DYNAMIC_TYPE_LMS); + key->priv_data = (byte *)XMALLOC(LMS_PRIV_DATA_LEN(params->levels, + params->height, params->p, params->rootLevels, params->cacheBits, + params->hash_len), key->heap, DYNAMIC_TYPE_LMS); /* Check pointer is valid. */ if (key->priv_data == NULL) { ret = MEMORY_E; @@ -669,8 +788,8 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) } if (ret == 0) { /* Write private key to storage. */ - int rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, - key->context); + int rv = key->write_private_key(key->priv_raw, + HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { ret = IO_FAILED_E; } @@ -728,9 +847,9 @@ int wc_LmsKey_Reload(LmsKey* key) const LmsParams* params = key->params; /* Allocate memory for the private key data. */ - key->priv_data = XMALLOC(LMS_PRIV_DATA_LEN(params->levels, - params->height, params->p, params->rootLevels, params->cacheBits), - key->heap, DYNAMIC_TYPE_LMS); + key->priv_data = (byte *)XMALLOC(LMS_PRIV_DATA_LEN(params->levels, + params->height, params->p, params->rootLevels, params->cacheBits, + params->hash_len), key->heap, DYNAMIC_TYPE_LMS); /* Check pointer is valid. */ if (key->priv_data == NULL) { ret = MEMORY_E; @@ -738,8 +857,8 @@ int wc_LmsKey_Reload(LmsKey* key) } if (ret == 0) { /* Load private key. */ - int rv = key->read_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, - key->context); + int rv = key->read_private_key(key->priv_raw, + HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); if (rv != WC_LMS_RC_READ_TO_MEMORY) { ret = IO_FAILED_E; } @@ -808,7 +927,7 @@ int wc_LmsKey_GetPrivLen(const LmsKey* key, word32* len) if (ret == 0) { /* Return private key length from parameter set. */ - *len = HSS_PRIVATE_KEY_LEN; + *len = HSS_PRIVATE_KEY_LEN(key->params->hash_len); } return ret; @@ -885,8 +1004,8 @@ int wc_LmsKey_Sign(LmsKey* key, byte* sig, word32* sigSz, const byte* msg, } if (ret == 0) { /* Write private key to storage. */ - int rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN, - key->context); + int rv = key->write_private_key(key->priv_raw, + HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { ret = IO_FAILED_E; } @@ -933,7 +1052,7 @@ int wc_LmsKey_GetPubLen(const LmsKey* key, word32* len) } if (ret == 0) { - *len = HSS_PUBLIC_KEY_LEN; + *len = HSS_PUBLIC_KEY_LEN(key->params->hash_len); } return ret; @@ -996,14 +1115,15 @@ int wc_LmsKey_ExportPubRaw(const LmsKey* key, byte* out, word32* outLen) ret = BAD_FUNC_ARG; } /* Check size of out is sufficient. */ - if ((ret == 0) && (*outLen < HSS_PUBLIC_KEY_LEN)) { + if ((ret == 0) && + (*outLen < (word32)HSS_PUBLIC_KEY_LEN(key->params->hash_len))) { ret = BUFFER_E; } if (ret == 0) { /* Return encoded public key. */ - XMEMCPY(out, key->pub, HSS_PUBLIC_KEY_LEN); - *outLen = HSS_PUBLIC_KEY_LEN; + XMEMCPY(out, key->pub, HSS_PUBLIC_KEY_LEN(key->params->hash_len)); + *outLen = HSS_PUBLIC_KEY_LEN(key->params->hash_len); } return ret; @@ -1032,7 +1152,8 @@ int wc_LmsKey_ImportPubRaw(LmsKey* key, const byte* in, word32 inLen) if ((key == NULL) || (in == NULL)) { ret = BAD_FUNC_ARG; } - if ((ret == 0) && (inLen != HSS_PUBLIC_KEY_LEN)) { + if ((ret == 0) && + (inLen != (word32)HSS_PUBLIC_KEY_LEN(key->params->hash_len))) { /* Something inconsistent. Parameters weren't set, or input * pub key is wrong.*/ return BUFFER_E; diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c index 3f48420..bb9345c 100644 --- a/src/wolfcrypt/src/wc_lms_impl.c +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -37,6 +37,10 @@ * Enable when memory is limited. */ +#ifdef HAVE_CONFIG_H + #include +#endif + #include #include @@ -75,24 +79,19 @@ #define LMS_D_CHILD_I 0xffff /* Length of data to hash when computing seed: - * 16 + 4 + 2 + 32 = 54 */ -#define LMS_SEED_HASH_LEN \ - (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + LMS_MAX_NODE_LEN) + * 16 + 4 + 2 + 32/24 = 54/46 */ +#define LMS_SEED_HASH_LEN(hLen) \ + (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + (hLen)) /* Length of data to hash when computing a node: - * 16 + 4 + 2 + 32 + 32 = 86 */ -#define LMS_NODE_HASH_LEN \ - (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + 2 * LMS_MAX_NODE_LEN) + * 16 + 4 + 2 + 32/24 + 32/24 = 86/70 */ +#define LMS_NODE_HASH_LEN(hLen) \ + (LMS_I_LEN + LMS_R_LEN + LMS_D_LEN + 2 * (hLen)) /* Length of data to hash when computing most results: - * 16 + 4 + 2 + 1 + 32 = 55 */ -#define LMS_HASH_BUFFER_LEN \ - (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_W_LEN + LMS_MAX_NODE_LEN) - -/* Length of data to hash when computing Q: - * 16 + 4 + 2 + 32 = 54 */ -#define LMS_Q_BUFFER_LEN \ - (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_MAX_NODE_LEN) + * 16 + 4 + 2 + 1 + 32/24 = 55/47 */ +#define LMS_HASH_BUFFER_LEN(hLen) \ + (LMS_I_LEN + LMS_Q_LEN + LMS_P_LEN + LMS_W_LEN + (hLen)) /* Length of preliminary data to hash when computing K: * 16 + 4 + 2 = 22 */ @@ -222,6 +221,7 @@ do { \ (buffer)[63] = 0xb8; \ } while (0) +#ifndef WOLFSSL_NO_LMS_SHA256_256 #ifndef WC_LMS_FULL_HASH /* Hash one full block of data and compute result. * @@ -286,6 +286,7 @@ static WC_INLINE int wc_lms_hash(wc_Sha256* sha256, byte* data, word32 len, return ret; } +#endif /* !WOLFSSL_NO_LMS_SHA256_256 */ /* Update hash with first data. * @@ -357,6 +358,7 @@ static WC_INLINE int wc_lms_hash_update(wc_Sha256* sha256, const byte* data, return ret; } +#ifndef WOLFSSL_NO_LMS_SHA256_256 /* Finalize hash. * * @param [in] sha256 SHA-256 hash object. @@ -399,6 +401,201 @@ static WC_INLINE int wc_lms_hash_final(wc_Sha256* sha256, byte* hash) return wc_Sha256Final(sha256, hash); #endif } +#endif /* !WOLFSSL_NO_LMS_SHA256_256 */ + +#ifdef WOLFSSL_LMS_SHA256_192 +/* Set the length of 46 bytes in buffer as per SHA-256 final operation. + * + * @param [in, out] buffer Hash data buffer to add length to. + */ +#define LMS_SHA256_SET_LEN_46(buffer) \ +do { \ + (buffer)[46] = 0x80; \ + (buffer)[47] = 0x00; \ + (buffer)[48] = 0x00; \ + (buffer)[49] = 0x00; \ + (buffer)[50] = 0x00; \ + (buffer)[51] = 0x00; \ + (buffer)[52] = 0x00; \ + (buffer)[53] = 0x00; \ + (buffer)[54] = 0x00; \ + (buffer)[55] = 0x00; \ + (buffer)[56] = 0x00; \ + (buffer)[57] = 0x00; \ + (buffer)[58] = 0x00; \ + (buffer)[59] = 0x00; \ + (buffer)[60] = 0x00; \ + (buffer)[61] = 0x00; \ + (buffer)[62] = 0x01; \ + (buffer)[63] = 0x70; \ +} while (0) + +/* Set the length of 47 bytes in buffer as per SHA-256 final operation. + * + * @param [in, out] buffer Hash data buffer to add length to. + */ +#define LMS_SHA256_SET_LEN_47(buffer) \ +do { \ + (buffer)[47] = 0x80; \ + (buffer)[48] = 0x00; \ + (buffer)[49] = 0x00; \ + (buffer)[50] = 0x00; \ + (buffer)[51] = 0x00; \ + (buffer)[52] = 0x00; \ + (buffer)[53] = 0x00; \ + (buffer)[54] = 0x00; \ + (buffer)[55] = 0x00; \ + (buffer)[56] = 0x00; \ + (buffer)[57] = 0x00; \ + (buffer)[58] = 0x00; \ + (buffer)[59] = 0x00; \ + (buffer)[60] = 0x00; \ + (buffer)[61] = 0x00; \ + (buffer)[62] = 0x01; \ + (buffer)[63] = 0x78; \ +} while (0) + +#ifndef WC_LMS_FULL_HASH +/* Hash one full block of data and compute result. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_sha256_192_hash_block(wc_Sha256* sha256, + const byte* data, byte* hash) +{ + int ret; + unsigned char output[WC_SHA256_DIGEST_SIZE]; + + /* Hash the block and reset SHA-256 state. */ + ret = wc_Sha256HashBlock(sha256, data, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + + return ret; +} +#endif /* !WC_LMS_FULL_HASH */ + +/* Hash data and compute result. + * + * @param [in] sha256 SHA-256 hash object. + * @param [in] data Data to hash. + * @param [in] len Length of data to hash. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_sha256_192(wc_Sha256* sha256, byte* data, + word32 len, byte* hash) +{ + int ret; + unsigned char output[WC_SHA256_DIGEST_SIZE]; + +#ifndef WC_LMS_FULL_HASH + if (len < WC_SHA256_BLOCK_SIZE) { + /* Store data into SHA-256 object's buffer. */ + LMS_SHA256_SET_DATA(sha256, data, len); + ret = wc_Sha256Final(sha256, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + } + else if (len < WC_SHA256_BLOCK_SIZE + WC_SHA256_PAD_SIZE) { + ret = wc_Sha256HashBlock(sha256, data, NULL); + if (ret == 0) { + byte* buffer = (byte*)sha256->buffer; + int rem = len - WC_SHA256_BLOCK_SIZE; + + XMEMCPY(buffer, data + WC_SHA256_BLOCK_SIZE, rem); + buffer[rem++] = 0x80; + XMEMSET(buffer + rem, 0, WC_SHA256_BLOCK_SIZE - 2 - rem); + buffer[WC_SHA256_BLOCK_SIZE - 2] = (byte)(len >> 5); + buffer[WC_SHA256_BLOCK_SIZE - 1] = (byte)(len << 3); + ret = wc_Sha256HashBlock(sha256, buffer, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + } + } + else { + ret = wc_Sha256Update(sha256, data, len); + if (ret == 0) { + ret = wc_Sha256Final(sha256, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + } + } +#else + ret = wc_Sha256Update(sha256, data, len); + if (ret == 0) { + ret = wc_Sha256Final(sha256, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + } +#endif /* !WC_LMS_FULL_HASH */ + + return ret; +} + +/* Finalize hash. + * + * @param [in] sha256 SHA-256 hash object. + * @param [out] hash Hash output. + * @return 0 on success. + */ +static WC_INLINE int wc_lms_hash_sha256_192_final(wc_Sha256* sha256, byte* hash) +{ +#ifndef WC_LMS_FULL_HASH + int ret = 0; + byte* buffer = (byte*)sha256->buffer; + unsigned char output[WC_SHA256_DIGEST_SIZE]; + + buffer[sha256->buffLen++] = 0x80; + if (sha256->buffLen > WC_SHA256_PAD_SIZE) { + XMEMSET(buffer + sha256->buffLen, 0, + WC_SHA256_BLOCK_SIZE - sha256->buffLen); + ret = wc_Sha256HashBlock(sha256, buffer, NULL); + sha256->buffLen = 0; + } + if (ret == 0) { + XMEMSET(buffer + sha256->buffLen, 0, + WC_SHA256_BLOCK_SIZE - 8 - sha256->buffLen); + sha256->hiLen = (sha256->hiLen << 3) + (sha256->loLen >> 29); + sha256->loLen = sha256->loLen << 3; + #ifdef LITTLE_ENDIAN_ORDER + sha256->buffer[14] = ByteReverseWord32(sha256->hiLen); + sha256->buffer[15] = ByteReverseWord32(sha256->loLen); + #else + sha256->buffer[14] = sha256->hiLen; + sha256->buffer[15] = sha256->loLen; + #endif + ret = wc_Sha256HashBlock(sha256, buffer, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + sha256->buffLen = 0; + sha256->hiLen = 0; + sha256->loLen = 0; + } + + return ret; +#else + int ret; + unsigned char output[WC_SHA256_DIGEST_SIZE]; + + ret = wc_Sha256Final(sha256, output); + if (ret == 0) { + XMEMCPY(hash, output, WC_SHA256_192_DIGEST_SIZE); + } + + return ret; +#endif +} +#endif /* WOLFSSL_LMS_SHA256_192 */ /*************************************** * LM-OTS APIs @@ -615,16 +812,30 @@ static int wc_lmots_msg_hash(LmsState* state, const byte* msg, word32 msgSz, ret = wc_lms_hash_first(&state->hash, buffer, LMS_MSG_PRE_LEN); if (ret == 0) { /* H(... || C || ...) */ - ret = wc_lms_hash_update(&state->hash, c, LMS_MAX_NODE_LEN); + ret = wc_lms_hash_update(&state->hash, c, state->params->hash_len); } if (ret == 0) { /* H(... || message) */ ret = wc_lms_hash_update(&state->hash, msg, msgSz); } +#ifdef WOLFSSL_LMS_SHA256_192 + if ((ret == 0) && + ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192)) { + /* Q = H(...) */ + ret = wc_lms_hash_sha256_192_final(&state->hash, q); + } + else +#endif +#ifndef WOLFSSL_NO_LMS_SHA256_256 if (ret == 0) { /* Q = H(...) */ ret = wc_lms_hash_final(&state->hash, q); } + else +#endif + { + ret = NOT_COMPILED_IN; + } return ret; } @@ -680,15 +891,26 @@ static int wc_lmots_compute_y_from_seed(LmsState* state, const byte* seed, ret = wc_lmots_msg_hash(state, msg, msgSz, c, q); if (ret == 0) { /* Calculate checksum list all coefficients. */ - ret = wc_lmots_q_expand(q, LMS_MAX_NODE_LEN, params->width, params->ls, + ret = wc_lmots_q_expand(q, params->hash_len, params->width, params->ls, a); } - #ifndef WC_LMS_FULL_HASH +#ifndef WC_LMS_FULL_HASH if (ret == 0) { - /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_55(buffer); + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_47(buffer); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + #endif + } } - #endif /* !WC_LMS_FULL_HASH */ +#endif /* !WC_LMS_FULL_HASH */ /* Compute y for each coefficient. */ for (i = 0; (ret == 0) && (i < params->p); i++) { @@ -698,29 +920,84 @@ static int wc_lmots_compute_y_from_seed(LmsState* state, const byte* seed, * = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). */ c16toa(i, ip); *jp = LMS_D_FIXED; - XMEMCPY(tmp, seed, LMS_SEED_LEN); - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ +#ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#endif /* !WC_LMS_FULL_HASH */ /* Apply the hash function coefficient number of times. */ for (j = 0; (ret == 0) && (j < a[i]); j++) { /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ *jp = j; /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ + #ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + #else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + #endif /* !WC_LMS_FULL_HASH */ } if (ret == 0) { /* y[i] = tmp */ - XMEMCPY(y, tmp, LMS_MAX_NODE_LEN); - y += LMS_MAX_NODE_LEN; + XMEMCPY(y, tmp, params->hash_len); + y += params->hash_len; } } @@ -785,15 +1062,26 @@ static int wc_lmots_compute_kc_from_sig(LmsState* state, const byte* msg, } if (ret == 0) { /* Calculate checksum list all coefficients. */ - ret = wc_lmots_q_expand(q, LMS_MAX_NODE_LEN, params->width, params->ls, + ret = wc_lmots_q_expand(q, params->hash_len, params->width, params->ls, a); } - #ifndef WC_LMS_FULL_HASH +#ifndef WC_LMS_FULL_HASH if (ret == 0) { - /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_55(buffer); + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_47(buffer); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + #endif + } } - #endif /* !WC_LMS_FULL_HASH */ +#endif /* !WC_LMS_FULL_HASH */ /* Compute z for each coefficient. */ for (i = 0; (ret == 0) && (i < params->p); i++) { @@ -804,30 +1092,69 @@ static int wc_lmots_compute_kc_from_sig(LmsState* state, const byte* msg, /* tmp = y[i]. * I || u32(str) || u16str(i) || ... || tmp */ - XMEMCPY(tmp, sig_y, LMS_MAX_NODE_LEN); - sig_y += LMS_MAX_NODE_LEN; + XMEMCPY(tmp, sig_y, params->hash_len); + sig_y += params->hash_len; /* Finish iterations of hash from coefficient to max. */ for (j = a[i]; (ret == 0) && (j < max); j++) { /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ *jp = (word8)j; /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ + #ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + /* Apply the hash function coefficient number of times. */ + #else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + #endif /* !WC_LMS_FULL_HASH */ } if (ret == 0) { /* H(... || z[i] || ...) (for calculating Kc). */ - ret = wc_lms_hash_update(&state->hash_k, tmp, LMS_MAX_NODE_LEN); + ret = wc_lms_hash_update(&state->hash_k, tmp, params->hash_len); } } +#ifdef WOLFSSL_LMS_SHA256_192 + if ((ret == 0) && + ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192)) { + /* Kc = H(...) */ + ret = wc_lms_hash_sha256_192_final(&state->hash_k, kc); + } + else +#endif if (ret == 0) { + #ifndef WOLFSSL_NO_LMS_SHA256_256 /* Kc = H(...) */ ret = wc_lms_hash_final(&state->hash_k, kc); + #else + ret = NOT_COMPILED_IN; + #endif } return ret; @@ -875,8 +1202,19 @@ static int wc_lmots_make_public_hash(LmsState* state, const byte* seed, byte* k) ret = wc_lms_hash_first(&state->hash_k, buffer, LMS_K_PRE_LEN); #ifndef WC_LMS_FULL_HASH - /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_55(buffer); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_47(buffer); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + #endif + } #endif /* !WC_LMS_FULL_HASH */ for (i = 0; (ret == 0) && (i < params->p); i++) { @@ -886,31 +1224,97 @@ static int wc_lmots_make_public_hash(LmsState* state, const byte* seed, byte* k) * = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). */ c16toa(i, ip); *jp = LMS_D_FIXED; - XMEMCPY(tmp, seed, LMS_SEED_LEN); - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ +#ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#endif /* !WC_LMS_FULL_HASH */ /* Do all iterations to calculate y. */ for (j = 0; (ret == 0) && (j < max); j++) { /* I || u32str(q) || u16str(i) || u8str(j) || tmp */ *jp = (word8)j; /* tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) */ - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ + #ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + #else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } + #endif /* !WC_LMS_FULL_HASH */ } if (ret == 0) { /* K = H(... || y[i] || ...) */ - ret = wc_lms_hash_update(&state->hash_k, tmp, LMS_MAX_NODE_LEN); + ret = wc_lms_hash_update(&state->hash_k, tmp, params->hash_len); } } +#ifdef WOLFSSL_LMS_SHA256_192 + if ((ret == 0) && ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192)) { + /* K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) */ + ret = wc_lms_hash_sha256_192_final(&state->hash_k, k); + } + else +#endif if (ret == 0) { + #ifndef WOLFSSL_NO_LMS_SHA256_256 /* K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) */ ret = wc_lms_hash_final(&state->hash_k, k); + #else + ret = NOT_COMPILED_IN; + #endif } return ret; @@ -931,7 +1335,7 @@ static int wc_lmots_make_public_hash(LmsState* state, const byte* seed, byte* k) static void wc_lmots_public_key_encode(const LmsParams* params, const byte* priv, byte* pub) { - const byte* priv_i = priv + LMS_Q_LEN + LMS_SEED_LEN; + const byte* priv_i = priv + LMS_Q_LEN + params->hash_len; /* u32str(type) || ... || T(1) */ c32toa(params->lmsType, pub); @@ -1012,7 +1416,7 @@ static int wc_lmots_calc_kc(LmsState* state, const byte* pub, const byte* msg, /* Get C or randomizer value from signature. */ const byte* c = sig + LMS_TYPE_LEN; /* Get array y from signature. */ - const byte* y = c + LMS_MAX_NODE_LEN; + const byte* y = c + state->params->hash_len; /* Compute the public key candidate Kc from the signature. */ ret = wc_lmots_compute_kc_from_sig(state, msg, msgSz, c, y, kc); @@ -1028,12 +1432,13 @@ static int wc_lmots_calc_kc(LmsState* state, const byte* pub, const byte* msg, * But use Appendix A to generate x on the fly. * PRIV = SEED | I * - * @param [in] rng Random number generator. - * @param [out] priv Private key data. + * @param [in] rng Random number generator. + * @param [in] seed_len Length of seed to generate. + * @param [out] priv Private key data. */ -static int wc_lmots_make_private_key(WC_RNG* rng, byte* priv) +static int wc_lmots_make_private_key(WC_RNG* rng, word16 seed_len, byte* priv) { - return wc_RNG_GenerateBlock(rng, priv, LMS_SEED_LEN + LMS_I_LEN); + return wc_RNG_GenerateBlock(rng, priv, seed_len + LMS_I_LEN); } /* Generate LM-OTS signature. @@ -1067,20 +1472,60 @@ static int wc_lmots_sign(LmsState* state, const byte* seed, const byte* msg, c16toa(LMS_D_C, ip); /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || ... */ *jp = LMS_D_FIXED; - /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ - XMEMCPY(tmp, seed, LMS_SEED_LEN); - /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) - * sig = u32str(type) || C || ... */ #ifndef WC_LMS_FULL_HASH - /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_55(buffer); - ret = wc_lms_hash_block(&state->hash, buffer, sig_c); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) + * sig = u32str(type) || C || ... */ + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_47(buffer); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, sig_c); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) + * sig = u32str(type) || C || ... */ + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, sig_c); + #else + ret = NOT_COMPILED_IN; + #endif + } #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, sig_c); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ + XMEMCPY(tmp, seed, WC_SHA256_192_DIGEST_SIZE); + /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) + * sig = u32str(type) || C || ... */ + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), sig_c); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED */ + XMEMCPY(tmp, seed, WC_SHA256_DIGEST_SIZE); + /* C = H(I || u32str(q) || u16str(0xFFFD) || u8str(0xFF) || SEED) + * sig = u32str(type) || C || ... */ + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), sig_c); + #else + ret = NOT_COMPILED_IN; + #endif + } #endif /* !WC_LMS_FULL_HASH */ if (ret == 0) { - byte* sig_y = sig_c + LMS_MAX_NODE_LEN; + byte* sig_y = sig_c + state->params->hash_len; /* Compute array y. * sig = u32str(type) || C || y[0] || ... || y[p-1] */ @@ -1109,21 +1554,21 @@ static void wc_lms_priv_state_load(const LmsParams* params, LmsPrivState* state, { /* Authentication path data. */ state->auth_path = priv_data; - priv_data += params->height * LMS_MAX_NODE_LEN; + priv_data += params->height * params->hash_len; /* Stack of nodes. */ state->stack.stack = priv_data; - priv_data += (params->height + 1) * LMS_MAX_NODE_LEN; + priv_data += (params->height + 1) * params->hash_len; ato32(priv_data, &state->stack.offset); priv_data += 4; /* Cached root nodes. */ state->root = priv_data; - priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels); + priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels, params->hash_len); /* Cached leaf nodes. */ state->leaf.cache = priv_data; - priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits); + priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits, params->hash_len); ato32(priv_data, &state->leaf.idx); priv_data += 4; ato32(priv_data, &state->leaf.offset); @@ -1140,18 +1585,18 @@ static void wc_lms_priv_state_store(const LmsParams* params, LmsPrivState* state, byte* priv_data) { /* Authentication path data. */ - priv_data += params->height * LMS_MAX_NODE_LEN; + priv_data += params->height * params->hash_len; /* Stack of nodes. */ - priv_data += (params->height + 1) * LMS_MAX_NODE_LEN; + priv_data += (params->height + 1) * params->hash_len; c32toa(state->stack.offset, priv_data); priv_data += 4; /* Cached root nodes. */ - priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels); + priv_data += LMS_ROOT_CACHE_LEN(params->rootLevels, params->hash_len); /* Cached leaf nodes. */ - priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits); + priv_data += LMS_LEAF_CACHE_LEN(params->cacheBits, params->hash_len); c32toa(state->leaf.idx, priv_data); priv_data += 4; c32toa(state->leaf.offset, priv_data); @@ -1169,7 +1614,7 @@ static void wc_lms_priv_state_copy(const LmsParams* params, LmsPrivState* dst, const LmsPrivState* src) { XMEMCPY(dst->auth_path, src->auth_path, LMS_PRIV_STATE_LEN(params->height, - params->rootLevels, params->cacheBits)); + params->rootLevels, params->cacheBits, params->hash_len)); dst->stack.offset = src->stack.offset; dst->leaf.idx = src->leaf.idx; dst->leaf.offset = src->leaf.offset; @@ -1225,13 +1670,40 @@ static int wc_lms_leaf_hash(LmsState* state, const byte* seed, word32 i, /* I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i] */ c16toa(LMS_D_LEAF, dp); /* temp = H(I || u32str(r) || u16str(D_LEAF) || OTS_PUB_HASH[i]) */ - #ifndef WC_LMS_FULL_HASH +#ifndef WC_LMS_FULL_HASH /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_54(buffer); - ret = wc_lms_hash_block(&state->hash, buffer, leaf); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_SEED_HASH_LEN, leaf); - #endif /* !WC_LMS_FULL_HASH */ + #ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + LMS_SHA256_SET_LEN_46(buffer); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, leaf); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + LMS_SHA256_SET_LEN_54(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, leaf); + #else + ret = NOT_COMPILED_IN; + #endif + } +#else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_SEED_HASH_LEN(WC_SHA256_192_DIGEST_SIZE), leaf); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_SEED_HASH_LEN(WC_SHA256_DIGEST_SIZE), leaf); + #else + ret = NOT_COMPILED_IN; + #endif + } +#endif /* !WC_LMS_FULL_HASH */ } return ret; @@ -1255,17 +1727,38 @@ static int wc_lms_leaf_hash(LmsState* state, const byte* seed, word32 i, static int wc_lms_interior_hash(LmsState* state, byte* sp, word32 r, byte* node) { + int ret; byte* buffer = state->buffer; byte* rp = buffer + LMS_I_LEN; byte* left = rp + LMS_R_LEN + LMS_D_LEN; /* I || u32str(r) || u16str(D_INTR) || ... || temp */ c32toa(r, rp); - /* left_side = pop(data stack) - * I || u32str(r) || u16str(D_INTR) || left_side || temp */ - XMEMCPY(left, sp, LMS_MAX_NODE_LEN); - /* temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ - return wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, node); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* left_side = pop(data stack) + * I || u32str(r) || u16str(D_INTR) || left_side || temp */ + XMEMCPY(left, sp, WC_SHA256_192_DIGEST_SIZE); + /* temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_192_DIGEST_SIZE), node); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* left_side = pop(data stack) + * I || u32str(r) || u16str(D_INTR) || left_side || temp */ + XMEMCPY(left, sp, WC_SHA256_DIGEST_SIZE); + /* temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ + ret = wc_lms_hash(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_DIGEST_SIZE), node); + #else + ret = NOT_COMPILED_IN; + #endif + } + + return ret; } #ifdef WOLFSSL_WC_LMS_SMALL @@ -1306,7 +1799,7 @@ static int wc_lms_treehash(LmsState* state, const byte* id, const byte* seed, byte* rp = buffer + LMS_I_LEN; byte* dp = rp + LMS_R_LEN; byte* left = dp + LMS_D_LEN; - byte* temp = left + LMS_MAX_NODE_LEN; + byte* temp = left + params->hash_len; #ifdef WOLFSSL_SMALL_STACK byte* stack = NULL; #else @@ -1320,7 +1813,7 @@ static int wc_lms_treehash(LmsState* state, const byte* id, const byte* seed, #ifdef WOLFSSL_SMALL_STACK /* Allocate stack of left side hashes. */ - stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + stack = XMALLOC((params->height + 1) * params->hash_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (stack == NULL) { ret = MEMORY_E; @@ -1340,7 +1833,7 @@ static int wc_lms_treehash(LmsState* state, const byte* id, const byte* seed, /* Store the node if on the authentication path. */ if ((ret == 0) && (auth_path != NULL) && ((q ^ 0x1) == i)) { - XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + XMEMCPY(auth_path, temp, params->hash_len); } /* I || ... || u16str(D_INTR) || ... || temp */ @@ -1355,23 +1848,23 @@ static int wc_lms_treehash(LmsState* state, const byte* id, const byte* seed, /* Calculate interior node hash. * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ - sp -= LMS_MAX_NODE_LEN; + sp -= params->hash_len; ret = wc_lms_interior_hash(state, sp, r, temp); /* Copy out node to authentication path if on path. */ if ((ret == 0) && (auth_path != NULL) && ((q >> h) ^ 0x1) == j) { - XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, - LMS_MAX_NODE_LEN); + XMEMCPY(auth_path + h * params->hash_len, temp, + params->hash_len); } } /* Push temp onto the data stack. */ - XMEMCPY(sp, temp, LMS_MAX_NODE_LEN); - sp += LMS_MAX_NODE_LEN; + XMEMCPY(sp, temp, params->hash_len); + sp += params->hash_len; } if ((ret == 0) && (pub != NULL)) { /* Public key, root node, is top of data stack. */ - XMEMCPY(pub, stack, LMS_MAX_NODE_LEN); + XMEMCPY(pub, stack, params->hash_len); } #ifdef WOLFSSL_SMALL_STACK XFREE(stack, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -1445,7 +1938,7 @@ static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, byte* rp = buffer + LMS_I_LEN; byte* dp = rp + LMS_R_LEN; byte* left = dp + LMS_D_LEN; - byte* temp = left + LMS_MAX_NODE_LEN; + byte* temp = left + params->hash_len; #ifdef WOLFSSL_SMALL_STACK byte* stack = NULL; #else @@ -1469,7 +1962,7 @@ static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, #ifdef WOLFSSL_SMALL_STACK /* Allocate stack of left side hashes. */ - stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + stack = XMALLOC((params->height + 1) * params->hash_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (stack == NULL) { ret = MEMORY_E; @@ -1488,12 +1981,12 @@ static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, /* Cache leaf node if in range. */ if ((ret == 0) && (i >= leaf->idx) && (i < leaf->idx + max_cb)) { - XMEMCPY(leaf->cache + i * LMS_MAX_NODE_LEN, temp, LMS_MAX_NODE_LEN); + XMEMCPY(leaf->cache + i * params->hash_len, temp, params->hash_len); } /* Store the node if on the authentication path. */ if ((ret == 0) && (auth_path != NULL) && ((q ^ 0x1) == i)) { - XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + XMEMCPY(auth_path, temp, params->hash_len); } /* I || ... || u16str(D_INTR) || ... || temp */ @@ -1508,25 +2001,25 @@ static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, /* Calculate interior node hash. * temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp) */ - spi -= LMS_MAX_NODE_LEN; + spi -= params->hash_len; ret = wc_lms_interior_hash(state, stack + spi, r, temp); /* Copy out top root nodes. */ if ((h > params->height - params->rootLevels) && ((i >> (h-1)) != ((i + 1) >> (h - 1)))) { int off = (1 << (params->height - h)) + (i >> h) - 1; - XMEMCPY(root + off * LMS_MAX_NODE_LEN, temp, LMS_MAX_NODE_LEN); + XMEMCPY(root + off * params->hash_len, temp, params->hash_len); } /* Copy out node to authentication path if on path. */ if ((ret == 0) && (auth_path != NULL) && ((q >> h) ^ 0x1) == j) { - XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, - LMS_MAX_NODE_LEN); + XMEMCPY(auth_path + h * params->hash_len, temp, + params->hash_len); } } /* Push temp onto the data stack. */ - XMEMCPY(stack + spi, temp, LMS_MAX_NODE_LEN); - spi += LMS_MAX_NODE_LEN; + XMEMCPY(stack + spi, temp, params->hash_len); + spi += params->hash_len; if (i == q - 1) { XMEMCPY(privState->stack.stack, stack, spi); @@ -1580,7 +2073,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, byte* rp = buffer + LMS_I_LEN; byte* dp = rp + LMS_R_LEN; byte* left = dp + LMS_D_LEN; - byte* temp = left + LMS_MAX_NODE_LEN; + byte* temp = left + params->hash_len; #ifdef WOLFSSL_SMALL_STACK byte* stack = NULL; #else @@ -1595,7 +2088,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, #ifdef WOLFSSL_SMALL_STACK /* Allocate stack of left side hashes. */ - stack = XMALLOC((params->height + 1) * LMS_MAX_NODE_LEN, NULL, + stack = XMALLOC((params->height + 1) * params->hash_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (stack == NULL) { ret = MEMORY_E; @@ -1603,7 +2096,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, #endif /* WOLFSSL_SMALL_STACK */ /* Public key, root node, is top of data stack. */ - XMEMCPY(stack, stackCache->stack, params->height * LMS_MAX_NODE_LEN); + XMEMCPY(stack, stackCache->stack, params->height * params->hash_len); sp = stack + stackCache->offset; /* Compute all nodes requested. */ @@ -1616,9 +2109,9 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, if ((i >= leaf->idx) && (i < leaf->idx + max_cb)) { /* Calculate offset of node in cache. */ word32 off = ((i - (leaf->idx + max_cb) + leaf->offset) % max_cb) * - LMS_MAX_NODE_LEN; + params->hash_len; /* Copy cached node into working buffer. */ - XMEMCPY(temp, leaf->cache + off, LMS_MAX_NODE_LEN); + XMEMCPY(temp, leaf->cache + off, params->hash_len); /* I || u32str(i) || ... */ c32toa(i, rp); } @@ -1630,8 +2123,8 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, * the number of leaf nodes. */ if ((i == leaf->idx + max_cb) && (i < (q + max_cb))) { /* Copy working node into cache over old first node. */ - XMEMCPY(leaf->cache + leaf->offset * LMS_MAX_NODE_LEN, temp, - LMS_MAX_NODE_LEN); + XMEMCPY(leaf->cache + leaf->offset * params->hash_len, temp, + params->hash_len); /* Increase start index as first node replaced. */ leaf->idx++; /* Update offset of first leaf node. */ @@ -1641,7 +2134,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, /* Store the node if on the authentication path. */ if ((ret == 0) && ((q ^ 0x1) == i)) { - XMEMCPY(auth_path, temp, LMS_MAX_NODE_LEN); + XMEMCPY(auth_path, temp, params->hash_len); } /* I || ... || u16str(D_INTR) || ... || temp */ @@ -1653,14 +2146,14 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, j >>= 1; h++; - sp -= LMS_MAX_NODE_LEN; + sp -= params->hash_len; if (useRoot && (h > params->height - params->rootLevels) && (h <= params->height)) { /* Calculate offset of cached root node. */ word32 off = ((word32)1U << (params->height - h)) + (i >> h) - 1; - XMEMCPY(temp, privState->root + (off * LMS_MAX_NODE_LEN), - LMS_MAX_NODE_LEN); + XMEMCPY(temp, privState->root + (off * params->hash_len), + params->hash_len); } else { /* Calculate interior node hash. @@ -1675,20 +2168,20 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, (h > params->height - params->rootLevels) && ((i >> (h-1)) != ((i + 1) >> (h - 1)))) { int off = (1 << (params->height - h)) + (i >> h) - 1; - XMEMCPY(privState->root + off * LMS_MAX_NODE_LEN, temp, - LMS_MAX_NODE_LEN); + XMEMCPY(privState->root + off * params->hash_len, temp, + params->hash_len); } /* Copy out node to authentication path if on path. */ if ((ret == 0) && (((q >> h) ^ 0x1) == j)) { - XMEMCPY(auth_path + h * LMS_MAX_NODE_LEN, temp, - LMS_MAX_NODE_LEN); + XMEMCPY(auth_path + h * params->hash_len, temp, + params->hash_len); } } if (ret == 0) { /* Push temp onto the data stack. */ - XMEMCPY(sp, temp, LMS_MAX_NODE_LEN); - sp += LMS_MAX_NODE_LEN; + XMEMCPY(sp, temp, params->hash_len); + sp += params->hash_len; /* Save stack after updating first node. */ if (i == min_idx) { @@ -1701,7 +2194,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, if (!useRoot) { /* Copy stack back. */ - XMEMCPY(stackCache->stack, stack, params->height * LMS_MAX_NODE_LEN); + XMEMCPY(stackCache->stack, stack, params->height * params->hash_len); stackCache->offset = (word32)((size_t)sp - (size_t)stack); } @@ -1742,7 +2235,7 @@ static int wc_lms_sign(LmsState* state, const byte* priv, const byte* msg, byte* s = sig; const byte* priv_q = priv; const byte* priv_seed = priv_q + LMS_Q_LEN; - const byte* priv_i = priv_seed + LMS_SEED_LEN; + const byte* priv_i = priv_seed + params->hash_len; /* Setup for hashing: I || Q */ XMEMCPY(buffer, priv_i, LMS_I_LEN); @@ -1761,7 +2254,7 @@ static int wc_lms_sign(LmsState* state, const byte* priv, const byte* msg, ret = wc_lmots_sign(state, priv_seed, msg, msgSz, s); if (ret == 0) { /* Skip over ots_signature. */ - s += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN; + s += params->hash_len + params->p * params->hash_len; /* S = u32str(q) || ots_signature || u32str(type) || ... */ c32toa(params->lmsType, s); } @@ -1787,8 +2280,8 @@ static void wc_lms_sig_copy(const LmsParams* params, const byte* y, c32toa(params->lmOtsType, sig); sig += LMS_TYPE_LEN; /* S = u32str(q) || ots_signature || ... */ - XMEMCPY(sig, y, LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN); - sig += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN; + XMEMCPY(sig, y, params->hash_len + params->p * params->hash_len); + sig += params->hash_len + params->p * params->hash_len; /* S = u32str(q) || ots_signature || u32str(type) || ... */ c32toa(params->lmsType, sig); } @@ -1831,22 +2324,64 @@ static int wc_lms_compute_root(LmsState* state, word32 q, const byte* kc, byte* rp = buffer + LMS_I_LEN; byte* ip = rp + LMS_Q_LEN; byte* node = ip + LMS_P_LEN; - byte* b[2][2] = { { node, node + LMS_MAX_NODE_LEN }, - { node + LMS_MAX_NODE_LEN, node } }; + byte* b[2][2]; /* node_num = 2^h + q */ word32 r = (1 << params->height) + q; /* tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc) */ c32toa(r, rp); c16toa(LMS_D_LEAF, ip); - XMEMCPY(node, kc, LMS_MAX_NODE_LEN); + XMEMCPY(node, kc, params->hash_len); /* Put tmp into offset required for first iteration. */ #ifndef WC_LMS_FULL_HASH /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_54(buffer); - ret = wc_lms_hash_block(&state->hash, buffer, b[r & 1][0]); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + b[0][0] = node; + b[0][1] = node + WC_SHA256_192_DIGEST_SIZE; + b[1][0] = node + WC_SHA256_192_DIGEST_SIZE; + b[1][1] = node; + LMS_SHA256_SET_LEN_46(buffer); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, b[r & 1][0]); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + b[0][0] = node; + b[0][1] = node + WC_SHA256_DIGEST_SIZE; + b[1][0] = node + WC_SHA256_DIGEST_SIZE; + b[1][1] = node; + LMS_SHA256_SET_LEN_54(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, b[r & 1][0]); + #else + ret = NOT_COMPILED_IN; + #endif + } #else - ret = wc_lms_hash(&state->hash, buffer, LMS_SEED_HASH_LEN, b[r & 1][0]); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + b[0][0] = node; + b[0][1] = node + WC_SHA256_192_DIGEST_SIZE; + b[1][0] = node + WC_SHA256_192_DIGEST_SIZE; + b[1][1] = node; + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_SEED_HASH_LEN(WC_SHA256_192_DIGEST_SIZE), b[r & 1][0]); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + b[0][0] = node; + b[0][1] = node + WC_SHA256_DIGEST_SIZE; + b[1][0] = node + WC_SHA256_DIGEST_SIZE; + b[1][1] = node; + ret = wc_lms_hash(&state->hash, buffer, + LMS_SEED_HASH_LEN(WC_SHA256_DIGEST_SIZE), b[r & 1][0]); + #else + ret = NOT_COMPILED_IN; + #endif + } #endif /* !WC_LMS_FULL_HASH */ if (ret == 0) { @@ -1856,33 +2391,78 @@ static int wc_lms_compute_root(LmsState* state, word32 q, const byte* kc, c16toa(LMS_D_INTR, ip); /* Do all but last height. */ - for (i = 0; (ret == 0) && (i < params->height - 1); i++) { - /* Put path into offset required. */ - XMEMCPY(b[r & 1][1], path, LMS_MAX_NODE_LEN); - path += LMS_MAX_NODE_LEN; - - /* node_num = node_num / 2 */ - r >>= 1; - /* H(...||u32str(node_num/2)||..) */ - c32toa(r, rp); - /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) or - * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) - * Put tmp result into offset required for next iteration. */ - ret = wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, - b[r & 1][0]); + #ifdef WOLFSSL_LMS_SHA256_192 + if ((params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + for (i = 0; (ret == 0) && (i < params->height - 1); i++) { + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, WC_SHA256_192_DIGEST_SIZE); + path += WC_SHA256_192_DIGEST_SIZE; + + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) + * or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into offset required for next iteration. */ + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_192_DIGEST_SIZE), b[r & 1][0]); + } + if (ret == 0) { + /* Last height. */ + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, WC_SHA256_192_DIGEST_SIZE); + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) + * or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into Tc.*/ + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_192_DIGEST_SIZE), tc); + } } - if (ret == 0) { - /* Last height. */ - /* Put path into offset required. */ - XMEMCPY(b[r & 1][1], path, LMS_MAX_NODE_LEN); - /* node_num = node_num / 2 */ - r >>= 1; - /* H(...||u32str(node_num/2)||..) */ - c32toa(r, rp); - /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) or - * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) - * Put tmp result into Tc.*/ - ret = wc_lms_hash(&state->hash, buffer, LMS_NODE_HASH_LEN, tc); + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + for (i = 0; (ret == 0) && (i < params->height - 1); i++) { + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, WC_SHA256_DIGEST_SIZE); + path += WC_SHA256_DIGEST_SIZE; + + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) + * or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into offset required for next iteration. */ + ret = wc_lms_hash(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_DIGEST_SIZE), b[r & 1][0]); + } + if (ret == 0) { + /* Last height. */ + /* Put path into offset required. */ + XMEMCPY(b[r & 1][1], path, WC_SHA256_DIGEST_SIZE); + /* node_num = node_num / 2 */ + r >>= 1; + /* H(...||u32str(node_num/2)||..) */ + c32toa(r, rp); + /* tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||path[i]||tmp) + * or + * tmp = H(I||u32str(node_num/2)||u16str(D_INTR)||tmp||path[i]) + * Put tmp result into Tc.*/ + ret = wc_lms_hash(&state->hash, buffer, + LMS_NODE_HASH_LEN(WC_SHA256_DIGEST_SIZE), tc); + } + #else + ret = NOT_COMPILED_IN; + #endif } } @@ -1955,7 +2535,7 @@ static int wc_lms_verify(LmsState* state, const byte* pub, const byte* msg, if (ret == 0) { /* Algorithm 6a. Step 2.j. */ const byte* sig_path = sig + LMS_Q_LEN + LMS_TYPE_LEN + - LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN; + params->hash_len + params->p * params->hash_len + LMS_TYPE_LEN; word32 q; /* Algorithm 6a. Step 2.a. */ @@ -1965,7 +2545,7 @@ static int wc_lms_verify(LmsState* state, const byte* pub, const byte* msg, ret = wc_lms_compute_root(state, q, kc, sig_path, tc); } /* Algorithm 6. Step 4. */ - if ((ret == 0) && (XMEMCMP(pub_k, tc, LMS_MAX_NODE_LEN) != 0)) { + if ((ret == 0) && (XMEMCMP(pub_k, tc, params->hash_len) != 0)) { ret = SIG_VERIFY_E; } @@ -2006,26 +2586,85 @@ static int wc_hss_derive_seed_i(LmsState* state, const byte* id, /* parent's I || q || D_CHILD_SEED || D_FIXED || ... */ *jp = LMS_D_FIXED; /* parent's I || q || D_CHILD_SEED || D_FIXED || parent's SEED */ - XMEMCPY(tmp, seed, LMS_SEED_LEN); + XMEMCPY(tmp, seed, state->params->hash_len); /* SEED = H(parent's I || q || D_CHILD_SEED || D_FIXED || parent's SEED) */ #ifndef WC_LMS_FULL_HASH - /* Put in padding for final block. */ - LMS_SHA256_SET_LEN_55(buffer); - ret = wc_lms_hash_block(&state->hash, buffer, seed_i); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_47(buffer); + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, seed_i); + if (ret == 0) { + seed_i += WC_SHA256_192_DIGEST_SIZE; + } + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + /* Put in padding for final block. */ + LMS_SHA256_SET_LEN_55(buffer); + ret = wc_lms_hash_block(&state->hash, buffer, seed_i); + if (ret == 0) { + seed_i += WC_SHA256_DIGEST_SIZE; + } + #else + ret = NOT_COMPILED_IN; + #endif + } #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, seed_i); +#ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), seed_i); + } + else +#endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), seed_i); + #else + ret = NOT_COMPILED_IN; + #endif + } #endif /* !WC_LMS_FULL_HASH */ if (ret == 0) { - seed_i += LMS_SEED_LEN; /* parent's I || q || D_CHILD_I || D_FIXED || parent's SEED */ c16toa(LMS_D_CHILD_I, ip); /* I = H(parent's I || q || D_CHILD_I || D_FIXED || parent's SEED) */ - #ifndef WC_LMS_FULL_HASH - ret = wc_lms_hash_block(&state->hash, buffer, tmp); - #else - ret = wc_lms_hash(&state->hash, buffer, LMS_HASH_BUFFER_LEN, tmp); - #endif /* !WC_LMS_FULL_HASH */ +#ifndef WC_LMS_FULL_HASH + #ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_sha256_192_hash_block(&state->hash, buffer, tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash_block(&state->hash, buffer, tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#else + #ifdef WOLFSSL_LMS_SHA256_192 + if ((state->params->lmOtsType & LMS_HASH_MASK) == LMS_SHA256_192) { + ret = wc_lms_hash_sha256_192(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_192_DIGEST_SIZE), tmp); + } + else + #endif + { + #ifndef WOLFSSL_NO_LMS_SHA256_256 + ret = wc_lms_hash(&state->hash, buffer, + LMS_HASH_BUFFER_LEN(WC_SHA256_DIGEST_SIZE), tmp); + #else + ret = NOT_COMPILED_IN; + #endif + } +#endif /* !WC_LMS_FULL_HASH */ /* Copy part of hash as new I into private key. */ XMEMCPY(seed_i, tmp, LMS_I_LEN); } @@ -2076,7 +2715,7 @@ static int wc_hss_expand_private_key(LmsState* state, byte* priv, } else { /* Copy out SEED and I into private key. */ - XMEMCPY(priv + LMS_Q_LEN, priv_raw, LMS_SEED_I_LEN); + XMEMCPY(priv + LMS_Q_LEN, priv_raw, params->hash_len + LMS_I_LEN); } /* Compute SEED and I for rest of levels. */ @@ -2100,7 +2739,7 @@ static int wc_hss_expand_private_key(LmsState* state, byte* priv, priv_q = priv; priv += LMS_Q_LEN; priv_seed_i = priv; - priv += LMS_SEED_I_LEN; + priv += params->hash_len + LMS_I_LEN; /* Get q for level from 64-bit composite. */ q32 = w64GetLow32(w64ShiftRight(q, (params->levels - 1 - i) * @@ -2110,7 +2749,7 @@ static int wc_hss_expand_private_key(LmsState* state, byte* priv, if (!skip) { /* Derive SEED and I into private key. */ - ret = wc_hss_derive_seed_i(state, priv_seed_i + LMS_SEED_LEN, + ret = wc_hss_derive_seed_i(state, priv_seed_i + params->hash_len, priv_seed_i, priv_q, priv + LMS_Q_LEN); } } @@ -2142,8 +2781,8 @@ static int wc_lms_next_subtree_init(LmsState* state, LmsPrivState* privState, priv_q = priv; priv += LMS_Q_LEN; priv_seed = curr + LMS_Q_LEN; - priv += LMS_SEED_LEN; - priv_i = curr + LMS_Q_LEN + LMS_SEED_LEN; + priv += params->hash_len; + priv_i = curr + LMS_Q_LEN + params->hash_len; priv += LMS_I_LEN; ato32(curr, &pq); @@ -2160,7 +2799,7 @@ static int wc_lms_next_subtree_init(LmsState* state, LmsPrivState* privState, if (ret == 0) { /* Update treehash for first leaf. */ ret = wc_lms_treehash_update(state, privState, - priv + LMS_Q_LEN + LMS_SEED_LEN, priv + LMS_Q_LEN, 0, q, 0, 0); + priv + LMS_Q_LEN + params->hash_len, priv + LMS_Q_LEN, 0, q, 0, 0); } return ret; @@ -2182,7 +2821,7 @@ static int wc_hss_next_subtree_inc(LmsState* state, HssPrivKey* priv_key, byte* priv = priv_key->next_priv; int i; w64wrapper p64 = q64; - byte tmp_priv[LMS_PRIV_LEN]; + byte tmp_priv[LMS_PRIV_LEN(LMS_MAX_NODE_LEN)]; int use_tmp = 0; int lastQMax = 0; w64wrapper p64_hi; @@ -2202,7 +2841,7 @@ static int wc_hss_next_subtree_inc(LmsState* state, HssPrivKey* priv_key, cp64_hi = w64ShiftRight(p64, (params->levels - i - 1) * params->height); cq64_hi = w64ShiftRight(q64, (params->levels - i - 1) * params->height); /* Get the q for the child. */ - ato32(curr + LMS_PRIV_LEN, &qc); + ato32(curr + LMS_PRIV_LEN(params->hash_len), &qc); /* Compare index of parent node with previous value. */ if (w64LT(p64_hi, q64_hi)) { @@ -2221,25 +2860,25 @@ static int wc_hss_next_subtree_inc(LmsState* state, HssPrivKey* priv_key, if (lastQMax) { /* Calculate new SEED and I based on new subtree. */ ret = wc_hss_derive_seed_i(state, - priv + LMS_Q_LEN + LMS_SEED_LEN, priv + LMS_Q_LEN, tmp_priv, - tmp_priv + LMS_Q_LEN); + priv + LMS_Q_LEN + params->hash_len, priv + LMS_Q_LEN, + tmp_priv, tmp_priv + LMS_Q_LEN); } else { /* Calculate new SEED and I based on parent. */ ret = wc_hss_derive_seed_i(state, - curr + LMS_Q_LEN + LMS_SEED_LEN, curr + LMS_Q_LEN, priv, + curr + LMS_Q_LEN + params->hash_len, curr + LMS_Q_LEN, priv, tmp_priv + LMS_Q_LEN); } /* Values not stored so note that they are in temporary. */ use_tmp = 1; /* Set the the q. */ - XMEMCPY(tmp_priv, curr + LMS_PRIV_LEN, LMS_Q_LEN); + XMEMCPY(tmp_priv, curr + LMS_PRIV_LEN(params->hash_len), LMS_Q_LEN); } lastQMax = (qc == ((word32)1 << params->height) - 1); - curr += LMS_PRIV_LEN; - priv += LMS_PRIV_LEN; + curr += LMS_PRIV_LEN(params->hash_len); + priv += LMS_PRIV_LEN(params->hash_len); p64_hi = cp64_hi; q64_hi = cq64_hi; } @@ -2261,18 +2900,18 @@ static int wc_hss_next_subtrees_init(LmsState* state, HssPrivKey* priv_key) byte* priv = priv_key->next_priv; int i; - XMEMCPY(priv, curr, LMS_PRIV_LEN); + XMEMCPY(priv, curr, LMS_PRIV_LEN(params->hash_len)); wc_lms_idx_inc(priv, LMS_Q_LEN); for (i = 1; (ret == 0) && (i < params->levels); i++) { word32 q; - ato32(curr + LMS_PRIV_LEN, &q); + ato32(curr + LMS_PRIV_LEN(params->hash_len), &q); ret = wc_lms_next_subtree_init(state, &priv_key->next_state[i - 1], curr, priv, q); - curr += LMS_PRIV_LEN; - priv += LMS_PRIV_LEN; + curr += LMS_PRIV_LEN(params->hash_len); + priv += LMS_PRIV_LEN(params->hash_len); } return ret; @@ -2292,14 +2931,15 @@ static int wc_hss_init_auth_path(LmsState* state, HssPrivKey* priv_key, { int ret = 0; int levels = state->params->levels; - byte* priv = priv_key->priv + LMS_PRIV_LEN * (levels - 1); + byte* priv = priv_key->priv + + LMS_PRIV_LEN(state->params->hash_len) * (levels - 1); int l; for (l = levels - 1; (ret == 0) && (l >= 0); l--) { word32 q; const byte* priv_q = priv; const byte* priv_seed = priv_q + LMS_Q_LEN; - const byte* priv_i = priv_seed + LMS_SEED_LEN; + const byte* priv_i = priv_seed + state->params->hash_len; /* Get current q for tree at level. */ ato32(priv_q, &q); @@ -2308,11 +2948,11 @@ static int wc_hss_init_auth_path(LmsState* state, HssPrivKey* priv_key, priv_seed, q); /* Move onto next level's data. */ - priv -= LMS_PRIV_LEN; + priv -= LMS_PRIV_LEN(state->params->hash_len); } if ((ret == 0) && (pub_root != NULL)) { - XMEMCPY(pub_root, priv_key->state[0].root, LMS_MAX_NODE_LEN); + XMEMCPY(pub_root, priv_key->state[0].root, state->params->hash_len); } return ret; @@ -2339,7 +2979,7 @@ static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, { const LmsParams* params = state->params; int ret = 0; - byte* priv = priv_key->priv + LMS_PRIV_LEN * (levels - 1); + byte* priv = priv_key->priv + LMS_PRIV_LEN(params->hash_len) * (levels - 1); int i; #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING w64wrapper q64; @@ -2354,13 +2994,12 @@ static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, word32 q; const byte* priv_q = priv; const byte* priv_seed = priv_q + LMS_Q_LEN; - const byte* priv_i = priv_seed + LMS_SEED_LEN; + const byte* priv_i = priv_seed + params->hash_len; LmsPrivState* privState = &priv_key->state[i]; /* Get q for tree at level. */ ato32(priv_q, &q); #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING - if ((levels > 1) && (i == levels - 1) && (q == 0)) { /* New sub-tree. */ ret = wc_hss_next_subtree_inc(state, priv_key, q64); @@ -2395,9 +3034,9 @@ static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, /* If different then copy in cached hash. */ if ((qa != qm1a) && (qa > maxq)) { int off = (1 << (params->height - h)) + (qa >> h) - 1; - XMEMCPY(privState->auth_path + h * LMS_MAX_NODE_LEN, - privState->root + off * LMS_MAX_NODE_LEN, - LMS_MAX_NODE_LEN); + XMEMCPY(privState->auth_path + h * params->hash_len, + privState->root + off * params->hash_len, + params->hash_len); } } /* Update the treehash and calculate the extra indices for @@ -2411,9 +3050,9 @@ static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, w64Increment(&tmp64); tmp64 = w64ShiftLeft(tmp64, 64 - (i * params->height)); if (!w64IsZero(tmp64)) { - priv_seed = priv_key->next_priv + i * LMS_PRIV_LEN + - LMS_Q_LEN; - priv_i = priv_seed + LMS_SEED_LEN; + priv_seed = priv_key->next_priv + + i * LMS_PRIV_LEN(params->hash_len) + LMS_Q_LEN; + priv_i = priv_seed + params->hash_len; privState = &priv_key->next_state[i - 1]; ret = wc_lms_treehash_update(state, privState, priv_i, @@ -2425,7 +3064,7 @@ static int wc_hss_update_auth_path(LmsState* state, HssPrivKey* priv_key, } /* Move onto next level's data. */ - priv -= LMS_PRIV_LEN; + priv -= LMS_PRIV_LEN(params->hash_len); } return ret; @@ -2442,21 +3081,21 @@ static int wc_hss_presign(LmsState* state, HssPrivKey* priv_key) int ret = 0; const LmsParams* params = state->params; byte* buffer = state->buffer; - byte pub[LMS_PUBKEY_LEN]; - byte* root = pub + LMS_PUBKEY_LEN - LMS_MAX_NODE_LEN; + byte pub[LMS_PUBKEY_LEN(LMS_MAX_NODE_LEN)]; + byte* root = pub + LMS_PUBKEY_LEN(LMS_MAX_NODE_LEN) - params->hash_len; byte* priv = priv_key->priv; int i; for (i = params->levels - 2; i >= 0; i--) { - const byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + const byte* p = priv + i * (LMS_Q_LEN + params->hash_len + LMS_I_LEN); const byte* priv_q = p; const byte* priv_seed = priv_q + LMS_Q_LEN; - const byte* priv_i = priv_seed + LMS_SEED_LEN; + const byte* priv_i = priv_seed + params->hash_len; /* ... || T(1) */ - XMEMCPY(root, priv_key->state[i + 1].root, LMS_MAX_NODE_LEN); + XMEMCPY(root, priv_key->state[i + 1].root, params->hash_len); /* u32str(type) || u32str(otstype) || I || T(1) */ - p = priv + (i + 1) * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + p = priv + (i + 1) * (LMS_Q_LEN + params->hash_len + LMS_I_LEN); wc_lmots_public_key_encode(params, p, pub); /* Setup for hashing: I || Q || ... */ @@ -2464,8 +3103,9 @@ static int wc_hss_presign(LmsState* state, HssPrivKey* priv_key) XMEMCPY(buffer + LMS_I_LEN, priv_q, LMS_Q_LEN); /* LM-OTS Sign this level. */ - ret = wc_lmots_sign(state, priv_seed, pub, LMS_PUBKEY_LEN, - priv_key->y + i * LMS_PRIV_Y_TREE_LEN(params->p)); + ret = wc_lmots_sign(state, priv_seed, pub, + LMS_PUBKEY_LEN(params->hash_len), + priv_key->y + i * LMS_PRIV_Y_TREE_LEN(params->p, params->hash_len)); } return ret; @@ -2488,25 +3128,25 @@ static void wc_hss_priv_data_load(const LmsParams* params, HssPrivKey* key, /* Expanded private keys. */ key->priv = priv_data; - priv_data += LMS_PRIV_KEY_LEN(params->levels); + priv_data += LMS_PRIV_KEY_LEN(params->levels, params->hash_len); #ifndef WOLFSSL_WC_LMS_SMALL for (l = 0; l < params->levels; l++) { /* Caches for subtree. */ wc_lms_priv_state_load(params, &key->state[l], priv_data); priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, - params->cacheBits); + params->cacheBits, params->hash_len); } #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING /* Next subtree's expanded private keys. */ key->next_priv = priv_data; - priv_data += LMS_PRIV_KEY_LEN(params->levels); + priv_data += LMS_PRIV_KEY_LEN(params->levels, params->hash_len); for (l = 0; l < params->levels - 1; l++) { /* Next subtree's caches. */ wc_lms_priv_state_load(params, &key->next_state[l], priv_data); priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, - params->cacheBits); + params->cacheBits, params->hash_len); } #endif /* WOLFSSL_LMS_NO_SIGN_SMOOTHING */ @@ -2532,22 +3172,22 @@ static void wc_hss_priv_data_store(const LmsParams* params, HssPrivKey* key, (void)key; /* Expanded private keys. */ - priv_data += LMS_PRIV_KEY_LEN(params->levels); + priv_data += LMS_PRIV_KEY_LEN(params->levels, params->hash_len); for (l = 0; l < params->levels; l++) { /* Caches for subtrees. */ wc_lms_priv_state_store(params, &key->state[l], priv_data); priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, - params->cacheBits); + params->cacheBits, params->hash_len); } #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING /* Next subtree's expanded private keys. */ - priv_data += LMS_PRIV_KEY_LEN(params->levels); + priv_data += LMS_PRIV_KEY_LEN(params->levels, params->hash_len); for (l = 0; l < params->levels - 1; l++) { /* Next subtree's caches. */ wc_lms_priv_state_store(params, &key->next_state[l], priv_data); priv_data += LMS_PRIV_STATE_LEN(params->height, params->rootLevels, - params->cacheBits); + params->cacheBits, params->hash_len); } #endif /* WOLFSSL_LMS_NO_SIGN_SMOOTHING */ @@ -2628,7 +3268,8 @@ int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, /* Set the LMS and LM-OTS types for each level. */ for (i = 0; i < params->levels; i++) { - p[i] = (params->lmsType << 4) + params->lmOtsType; + p[i] = ((params->lmsType & LMS_H_W_MASK) << 4) + + (params->lmOtsType & LMS_H_W_MASK); } /* Set rest of levels to an invalid value. */ for (; i < HSS_MAX_LEVELS; i++) { @@ -2637,7 +3278,7 @@ int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, p += HSS_PRIV_KEY_PARAM_SET_LEN; /* Make the private key. */ - ret = wc_lmots_make_private_key(rng, p); + ret = wc_lmots_make_private_key(rng, params->hash_len, p); if (ret == 0) { /* Set the levels into the public key data. */ @@ -2649,7 +3290,7 @@ int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, #ifdef WOLFSSL_WC_LMS_SMALL if (ret == 0) { byte* priv_seed = priv_key->priv + LMS_Q_LEN; - byte* priv_i = priv_seed + LMS_SEED_LEN; + byte* priv_i = priv_seed + params->hash_len; /* Compute the root of the highest tree to get the root for public key. */ @@ -2738,24 +3379,24 @@ int wc_hss_sign(LmsState* state, byte* priv_raw, HssPrivKey* priv_key, /* Build from bottom up. */ for (i = params->levels - 1; (ret == 0) && (i >= 0); i--) { - byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + byte* p = priv + i * (LMS_Q_LEN + params->hash_len + LMS_I_LEN); byte* root = NULL; /* Move to start of next signature at this level. */ - sig -= LMS_SIG_LEN(params->height, params->p); + sig -= LMS_SIG_LEN(params->height, params->p, params->hash_len); if (i != 0) { /* Put root node into signature at this index. */ - root = sig - LMS_MAX_NODE_LEN; + root = sig - params->hash_len; } /* Sign using LMS for this level. */ ret = wc_lms_sign(state, p, msg, msgSz, sig); if (ret == 0) { - byte* s = sig + LMS_Q_LEN + LMS_TYPE_LEN + LMS_MAX_NODE_LEN + - params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN; + byte* s = sig + LMS_Q_LEN + LMS_TYPE_LEN + params->hash_len + + params->p * params->hash_len + LMS_TYPE_LEN; byte* priv_q = p; byte* priv_seed = priv_q + LMS_Q_LEN; - byte* priv_i = priv_seed + LMS_SEED_LEN; + byte* priv_i = priv_seed + params->hash_len; word32 q32; /* Get Q from private key as a number. */ @@ -2765,9 +3406,9 @@ int wc_hss_sign(LmsState* state, byte* priv_raw, HssPrivKey* priv_key, } if ((ret == 0) && (i != 0)) { /* Create public data for this level if there is another. */ - sig -= LMS_PUBKEY_LEN; + sig -= LMS_PUBKEY_LEN(params->hash_len); msg = sig; - msgSz = LMS_PUBKEY_LEN; + msgSz = LMS_PUBKEY_LEN(params->hash_len); wc_lmots_public_key_encode(params, p, sig); } } @@ -2835,7 +3476,7 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, /* Build from bottom up. */ for (i = params->levels - 1; (ret == 0) && (i >= 0); i--) { - byte* p = priv + i * (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN); + byte* p = priv + i * (LMS_Q_LEN + params->hash_len + LMS_I_LEN); byte* root = NULL; #ifndef WOLFSSL_LMS_NO_SIG_CACHE int store_p = 0; @@ -2846,10 +3487,10 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ /* Move to start of next signature at this level. */ - sig -= LMS_SIG_LEN(params->height, params->p); + sig -= LMS_SIG_LEN(params->height, params->p, params->hash_len); if (i != 0) { /* Put root node into signature at this index. */ - root = sig - LMS_MAX_NODE_LEN; + root = sig - params->hash_len; } #ifndef WOLFSSL_LMS_NO_SIG_CACHE @@ -2857,7 +3498,7 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, * can reuse. */ if ((i < params->levels - 1) && (q_32 == qm1_32)) { wc_lms_sig_copy(params, priv_key->y + - i * LMS_PRIV_Y_TREE_LEN(params->p), p, sig); + i * LMS_PRIV_Y_TREE_LEN(params->p, params->hash_len), p, sig); } else #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ @@ -2875,26 +3516,27 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, /* Check if we computed new C and p hashes. */ if (store_p) { /* Cache the C and p hashes. */ - XMEMCPY(priv_key->y + i * LMS_PRIV_Y_TREE_LEN(params->p), s, - LMS_PRIV_Y_TREE_LEN(params->p)); + XMEMCPY(priv_key->y + + i * LMS_PRIV_Y_TREE_LEN(params->p, params->hash_len), s, + LMS_PRIV_Y_TREE_LEN(params->p, params->hash_len)); } #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ - s += LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + + s += params->hash_len + params->p * params->hash_len + LMS_TYPE_LEN; /* Copy the authentication path out of the private key. */ XMEMCPY(s, priv_key->state[i].auth_path, - params->height * LMS_MAX_NODE_LEN); + params->height * params->hash_len); /* Copy the root node into signature unless at top. */ if (i != 0) { - XMEMCPY(root, priv_key->state[i].root, LMS_MAX_NODE_LEN); + XMEMCPY(root, priv_key->state[i].root, params->hash_len); } } if ((ret == 0) && (i != 0)) { /* Create public data for this level if there is another. */ - sig -= LMS_PUBKEY_LEN; + sig -= LMS_PUBKEY_LEN(params->hash_len); msg = sig; - msgSz = LMS_PUBKEY_LEN; + msgSz = LMS_PUBKEY_LEN(params->hash_len); wc_lmots_public_key_encode(params, p, sig); } } @@ -3070,14 +3712,15 @@ int wc_hss_verify(LmsState* state, const byte* pub, const byte* msg, for (i = 0; (ret == 0) && (i < nspk); i++) { /* Line 7: Get start of public key in signature. */ const byte* pubList = sig + LMS_Q_LEN + LMS_TYPE_LEN + - LMS_MAX_NODE_LEN + params->p * LMS_MAX_NODE_LEN + LMS_TYPE_LEN + - params->height * LMS_MAX_NODE_LEN; + params->hash_len + params->p * params->hash_len + LMS_TYPE_LEN + + params->height * params->hash_len; /* Line 8: Verify the LMS signature with public key as message. */ - ret = wc_lms_verify(state, key, pubList, LMS_PUBKEY_LEN, sig); + ret = wc_lms_verify(state, key, pubList, + LMS_PUBKEY_LEN(params->hash_len), sig); /* Line 10: Next key is from signature. */ key = pubList; /* Line 6: Move to start of next signature. */ - sig = pubList + LMS_PUBKEY_LEN; + sig = pubList + LMS_PUBKEY_LEN(params->hash_len); } } if (ret == 0) { diff --git a/src/wolfcrypt/src/wc_pkcs11.c b/src/wolfcrypt/src/wc_pkcs11.c index e248d8e..4a3b28a 100644 --- a/src/wolfcrypt/src/wc_pkcs11.c +++ b/src/wolfcrypt/src/wc_pkcs11.c @@ -1,6 +1,6 @@ /* wc_pkcs11.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -531,22 +531,36 @@ void wc_Pkcs11_Finalize(Pkcs11Dev* dev) static int Pkcs11Slot_FindByTokenName(Pkcs11Dev* dev, const char* tokenName, size_t tokenNameSz) { + int ret = -1; CK_RV rv; CK_ULONG slotCnt = 0; CK_TOKEN_INFO tinfo; - int slotId = -1; + int index = -1; + CK_SLOT_ID* slot = NULL; + rv = dev->func->C_GetSlotList(CK_TRUE, NULL, &slotCnt); if (rv == CKR_OK) { - for (slotId = 0; slotId < (int)slotCnt; slotId++) { - rv = dev->func->C_GetTokenInfo(slotId, &tinfo); + slot = (CK_SLOT_ID*)XMALLOC(slotCnt * sizeof(*slot), dev->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (slot == NULL) + goto out; + rv = dev->func->C_GetSlotList(CK_TRUE, slot, &slotCnt); + if (rv != CKR_OK) + goto out; + for (index = 0; index < (int)slotCnt; index++) { + rv = dev->func->C_GetTokenInfo(slot[index], &tinfo); PKCS11_RV("C_GetTokenInfo", rv); if (rv == CKR_OK && XMEMCMP(tinfo.label, tokenName, tokenNameSz) == 0) { - return slotId; + ret = (int)slot[index]; + break; } } } - return -1; + +out: + XFREE(slot, dev->heap, DYNAMIC_TYPE_TMP_BUFFER); + return ret; } /* lookup by slotId or tokenName */ @@ -613,9 +627,7 @@ static int Pkcs11Token_Init(Pkcs11Token* token, Pkcs11Dev* dev, int slotId, token->userPinLogin = 0; } - if (slot != NULL) { - XFREE(slot, dev->heap, DYNAMIC_TYPE_TMP_BUFFER); - } + XFREE(slot, dev->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -645,7 +657,7 @@ int wc_Pkcs11Token_Init(Pkcs11Token* token, Pkcs11Dev* dev, int slotId, tokenNameSz = XSTRLEN(tokenName); } ret = Pkcs11Token_Init(token, dev, slotId, tokenName, tokenNameSz); - if (ret == 0) { + if (ret == 0 && userPin != NULL) { token->userPin = (CK_UTF8CHAR_PTR)userPin; token->userPinSz = (CK_ULONG)userPinSz; token->userPinLogin = 1; @@ -696,7 +708,7 @@ int wc_Pkcs11Token_InitName(Pkcs11Token* token, Pkcs11Dev* dev, const unsigned char* userPin, int userPinSz) { int ret = Pkcs11Token_Init(token, dev, -1, tokenName, (size_t)tokenNameSz); - if (ret == 0) { + if (ret == 0 && userPin != NULL) { token->userPin = (CK_UTF8CHAR_PTR)userPin; token->userPinSz = (CK_ULONG)userPinSz; token->userPinLogin = 1; @@ -947,7 +959,7 @@ static int Pkcs11CreateSecretKey(CK_OBJECT_HANDLE* key, Pkcs11Session* session, } #endif -#ifndef NO_RSA +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) /** * Create a PKCS#11 object containing the RSA private key data. * @@ -1024,7 +1036,7 @@ static int Pkcs11CreateRsaPrivateKey(CK_OBJECT_HANDLE* privateKey, return ret; } -#endif +#endif /* !NO_RSA && WOLFSSL_KEY_GEN */ #ifdef HAVE_ECC /** @@ -1138,8 +1150,7 @@ static int Pkcs11CreateEccPublicKey(CK_OBJECT_HANDLE* publicKey, } } - if (ecPoint != NULL) - XFREE(ecPoint, public_key->heap, DYNAMIC_TYPE_ECC); + XFREE(ecPoint, public_key->heap, DYNAMIC_TYPE_ECC); return ret; } @@ -1380,7 +1391,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) break; } #endif - #ifndef NO_RSA + #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) case PKCS11_KEY_TYPE_RSA: { RsaKey* rsaKey = (RsaKey*)key; @@ -1402,7 +1413,7 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) #ifdef HAVE_ECC case PKCS11_KEY_TYPE_EC: { ecc_key* eccKey = (ecc_key*)key; - int ret2 = NOT_COMPILED_IN; + int ret2 = WC_NO_ERR_TRACE(NOT_COMPILED_IN); #ifndef NO_PKCS11_ECDH if ((eccKey->flags & WC_ECC_FLAG_DEC_SIGN) == 0) { @@ -1716,10 +1727,8 @@ static int Pkcs11GetRsaPublicKey(RsaKey* key, Pkcs11Session* session, if (ret == 0) ret = wc_RsaPublicKeyDecodeRaw(mod, modSz, exp, expSz, key); - if (exp != NULL) - XFREE(exp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (mod != NULL) - XFREE(mod, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(exp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(mod, key->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -1774,7 +1783,12 @@ static int Pkcs11RsaPrivateKey(Pkcs11Session* session, RsaKey* rsaKey, int ret; if (sessionKey) { + #ifdef WOLFSSL_KEY_GEN ret = Pkcs11CreateRsaPrivateKey(privateKey, session, rsaKey, 0); + #else + /* RSA Key Generation support not compiled in */ + ret = NOT_COMPILED_IN; + #endif } else if (rsaKey->labelLen > 0) { ret = Pkcs11FindKeyByLabel(privateKey, CKO_PRIVATE_KEY, CKK_RSA, @@ -1795,6 +1809,84 @@ static int Pkcs11RsaPrivateKey(Pkcs11Session* session, RsaKey* rsaKey, return ret; } +/** + * Get the hash length associated with the WolfCrypt hash type. + * + * @param [in] hType Hash Type. + * @return -1 if hash type not recognized. + * @return hash length on success. + */ +int wc_hash2sz(int hType) +{ + switch(hType) { + case WC_HASH_TYPE_SHA: + return 20; + case WC_HASH_TYPE_SHA224: + return 24; + case WC_HASH_TYPE_SHA256: + return 32; + case WC_HASH_TYPE_SHA384: + return 48; + case WC_HASH_TYPE_SHA512: + return 64; + default: + /* unsupported WC_HASH_TYPE_XXXX */ + return -1; + } +} + +/** + * Get PKCS11 hash mechanism associated with the WolfCrypt hash type. + * + * @param [in] hType Hash Type. + * @return 0 if hash type not recognized. + * @return PKCS11 mechanism on success. + */ +CK_MECHANISM_TYPE wc_hash2ckm(int hType) +{ + switch(hType) { + case WC_HASH_TYPE_SHA: + return CKM_SHA_1; + case WC_HASH_TYPE_SHA224: + return CKM_SHA224; + case WC_HASH_TYPE_SHA256: + return CKM_SHA256; + case WC_HASH_TYPE_SHA384: + return CKM_SHA384; + case WC_HASH_TYPE_SHA512: + return CKM_SHA512; + default: + /* unsupported WC_HASH_TYPE_XXXX */ + return 0UL; + } +} + +/** + * Get PKCS11 MGF hash mechanism associated with the WolfCrypt MGF hash type. + * + * @param [in] mgf MGF Type. + * @return 0 if MGF type not recognized. + * @return PKCS11 MGF hash mechanism on success. + */ +CK_MECHANISM_TYPE wc_mgf2ckm(int mgf) +{ + switch(mgf) { + case WC_MGF1SHA1: + return CKG_MGF1_SHA1; + case WC_MGF1SHA224: + return CKG_MGF1_SHA224; + case WC_MGF1SHA256: + return CKG_MGF1_SHA256; + case WC_MGF1SHA384: + return CKG_MGF1_SHA384; + case WC_MGF1SHA512: + return CKG_MGF1_SHA512; + default: + /* unsupported WC_MGF1XXXX */ + return 0x0UL; + } +} + /** * Exponentiate the input with the public part of the RSA key. * Used in public encrypt and decrypt. @@ -1808,9 +1900,13 @@ static int Pkcs11RsaEncrypt(Pkcs11Session* session, wc_CryptoInfo* info, CK_OBJECT_HANDLE key) { int ret = 0; + CK_MECHANISM_TYPE mechanism = 0x0UL; CK_RV rv; CK_MECHANISM mech; CK_ULONG outLen; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + CK_RSA_PKCS_OAEP_PARAMS oaepParams; +#endif WOLFSSL_MSG("PKCS#11: RSA Public Key Operation"); @@ -1818,12 +1914,37 @@ static int Pkcs11RsaEncrypt(Pkcs11Session* session, wc_CryptoInfo* info, ret = BAD_FUNC_ARG; } + switch(info->pk.type) { +#ifdef WOLF_CRYPTO_CB_RSA_PAD + case WC_PK_TYPE_RSA_PKCS: + mechanism = CKM_RSA_PKCS; + break; + case WC_PK_TYPE_RSA_OAEP: + mechanism = CKM_RSA_PKCS_OAEP; + break; +#endif + case WC_PK_TYPE_RSA: + mechanism = CKM_RSA_X_509; + break; + } + if (ret == 0) { /* Raw RSA encrypt/decrypt operation. */ - mech.mechanism = CKM_RSA_X_509; + mech.mechanism = mechanism; mech.ulParameterLen = 0; mech.pParameter = NULL; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + if (mechanism == CKM_RSA_PKCS_OAEP) { + XMEMSET(&oaepParams, 0, sizeof(oaepParams)); + mech.ulParameterLen = sizeof(CK_RSA_PKCS_OAEP_PARAMS); + mech.pParameter = &oaepParams; + oaepParams.source = CKZ_DATA_SPECIFIED; + oaepParams.hashAlg = wc_hash2ckm(info->pk.rsa.padding->hash); + oaepParams.mgf = wc_mgf2ckm(info->pk.rsa.padding->mgf); + } +#endif + rv = session->func->C_EncryptInit(session->handle, &mech, key); PKCS11_RV("C_EncryptInit", rv); if (rv != CKR_OK) { @@ -1861,9 +1982,13 @@ static int Pkcs11RsaDecrypt(Pkcs11Session* session, wc_CryptoInfo* info, CK_OBJECT_HANDLE key) { int ret = 0; + CK_MECHANISM_TYPE mechanism = 0x0UL; CK_RV rv; CK_MECHANISM mech; CK_ULONG outLen; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + CK_RSA_PKCS_OAEP_PARAMS oaepParams; +#endif WOLFSSL_MSG("PKCS#11: RSA Private Key Operation"); @@ -1871,12 +1996,37 @@ static int Pkcs11RsaDecrypt(Pkcs11Session* session, wc_CryptoInfo* info, ret = BAD_FUNC_ARG; } + switch(info->pk.type) { +#ifdef WOLF_CRYPTO_CB_RSA_PAD + case WC_PK_TYPE_RSA_PKCS: + mechanism = CKM_RSA_PKCS; + break; + case WC_PK_TYPE_RSA_OAEP: + mechanism = CKM_RSA_PKCS_OAEP; + break; +#endif + case WC_PK_TYPE_RSA: + mechanism = CKM_RSA_X_509; + break; + } + if (ret == 0) { /* Raw RSA encrypt/decrypt operation. */ - mech.mechanism = CKM_RSA_X_509; + mech.mechanism = mechanism; mech.ulParameterLen = 0; mech.pParameter = NULL; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + if (mechanism == CKM_RSA_PKCS_OAEP) { + XMEMSET(&oaepParams, 0, sizeof(oaepParams)); + mech.ulParameterLen = sizeof(CK_RSA_PKCS_OAEP_PARAMS); + mech.pParameter = &oaepParams; + oaepParams.source = CKZ_DATA_SPECIFIED; + oaepParams.hashAlg = wc_hash2ckm(info->pk.rsa.padding->hash); + oaepParams.mgf = wc_mgf2ckm(info->pk.rsa.padding->mgf); + } +#endif + rv = session->func->C_DecryptInit(session->handle, &mech, key); PKCS11_RV("C_DecryptInit", rv); if (rv != CKR_OK) { @@ -1919,6 +2069,12 @@ static int Pkcs11RsaSign(Pkcs11Session* session, wc_CryptoInfo* info, CK_RV rv; CK_MECHANISM mech; CK_ULONG outLen; + CK_MECHANISM_TYPE mechanism; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + CK_RSA_PKCS_PSS_PARAMS pssParams; + int hLen; + int saltLen; +#endif WOLFSSL_MSG("PKCS#11: RSA Private Key Operation"); @@ -1926,12 +2082,67 @@ static int Pkcs11RsaSign(Pkcs11Session* session, wc_CryptoInfo* info, ret = BAD_FUNC_ARG; } + switch(info->pk.type) { +#ifdef WOLF_CRYPTO_CB_RSA_PAD + case WC_PK_TYPE_RSA_PKCS: + mechanism = CKM_RSA_PKCS; + break; + case WC_PK_TYPE_RSA_PSS: + mechanism = CKM_RSA_PKCS_PSS; + break; +#endif /* WOLF_CRYPTO_CB_RSA_PAD */ + default: + mechanism = CKM_RSA_X_509; + break; + } + if (ret == 0) { /* Raw RSA encrypt/decrypt operation. */ - mech.mechanism = CKM_RSA_X_509; + mech.mechanism = mechanism; mech.ulParameterLen = 0; mech.pParameter = NULL; +#ifdef WOLF_CRYPTO_CB_RSA_PAD + if (mechanism == CKM_RSA_PKCS_PSS) { + mech.ulParameterLen = sizeof(CK_RSA_PKCS_PSS_PARAMS); + mech.pParameter = &pssParams; + pssParams.hashAlg = wc_hash2ckm(info->pk.rsa.padding->hash); + pssParams.mgf = wc_mgf2ckm(info->pk.rsa.padding->mgf); + + saltLen = info->pk.rsa.padding->saltLen; + hLen = wc_hash2sz(info->pk.rsa.padding->hash); + + /* Same salt length code as rsa.c */ + if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) + saltLen = hLen; +#ifndef WOLFSSL_PSS_LONG_SALT + else if (saltLen > hLen) { + return PSS_SALTLEN_E; + } +#endif +#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER + else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { + return PSS_SALTLEN_E; + } +#else + else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { + saltLen = *(info->pk.rsa.outLen) - hLen - 2; + if (saltLen < 0) { + return PSS_SALTLEN_E; + } + } + else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { + return PSS_SALTLEN_E; + } +#endif + if (*(info->pk.rsa.outLen) - hLen < (word32)(saltLen + 2)) { + return PSS_SALTLEN_E; + } + + pssParams.sLen = saltLen; + } +#endif /* WOLF_CRYPTO_CB_RSA_PAD */ + rv = session->func->C_SignInit(session->handle, &mech, key); PKCS11_RV("C_SignInit", rv); if (rv != CKR_OK) { @@ -1970,13 +2181,31 @@ static int Pkcs11Rsa(Pkcs11Session* session, wc_CryptoInfo* info) int ret = 0; CK_RV rv; CK_MECHANISM_INFO mechInfo; + CK_MECHANISM_TYPE mechanism = 0x0UL; int sessionKey = 0; CK_OBJECT_HANDLE key; RsaKey* rsaKey = info->pk.rsa.key; int type = info->pk.rsa.type; + switch(info->pk.type) { +#ifndef NO_PKCS11_RSA_PKCS + case WC_PK_TYPE_RSA_PKCS: + mechanism = CKM_RSA_PKCS; + break; + case WC_PK_TYPE_RSA_PSS: + mechanism = CKM_RSA_PKCS_PSS; + break; + case WC_PK_TYPE_RSA_OAEP: + mechanism = CKM_RSA_PKCS_OAEP; + break; +#endif /* NO_PKCS11_RSA_PKCS */ + case WC_PK_TYPE_RSA: + mechanism = CKM_RSA_X_509; + break; + } + /* Check operation is supported. */ - rv = session->func->C_GetMechanismInfo(session->slotId, CKM_RSA_X_509, + rv = session->func->C_GetMechanismInfo(session->slotId, mechanism, &mechInfo); PKCS11_RV("C_GetMechanismInfo", rv); if (rv != CKR_OK) { @@ -1996,7 +2225,8 @@ static int Pkcs11Rsa(Pkcs11Session* session, wc_CryptoInfo* info) /* Make a handle to a private key. */ ret = Pkcs11RsaPrivateKey(session, rsaKey, sessionKey, &key); } - + } + if (ret == 0) { if (type == RSA_PUBLIC_ENCRYPT) { WOLFSSL_MSG("PKCS#11: Public Encrypt"); if ((mechInfo.flags & CKF_ENCRYPT) != 0) { @@ -2008,7 +2238,7 @@ static int Pkcs11Rsa(Pkcs11Session* session, wc_CryptoInfo* info) } else if (type == RSA_PUBLIC_DECRYPT) { WOLFSSL_MSG("PKCS#11: Public Decrypt"); - if ((mechInfo.flags & CKF_DECRYPT) != 0) { + if ((mechInfo.flags & CKF_ENCRYPT) != 0) { ret = Pkcs11RsaEncrypt(session, info, key); } else { @@ -2216,8 +2446,7 @@ static int Pkcs11FindEccKey(CK_OBJECT_HANDLE* key, CK_OBJECT_CLASS keyClass, } } - if (ecPoint != NULL) - XFREE(ecPoint, eccKey->heap, DYNAMIC_TYPE_ECC); + XFREE(ecPoint, eccKey->heap, DYNAMIC_TYPE_ECC); return ret; } @@ -2300,8 +2529,7 @@ static int Pkcs11GetEccPublicKey(ecc_key* key, Pkcs11Session* session, key->type = ECC_PUBLICKEY; } - if (point != NULL) - XFREE(point, key->heap, DYNAMIC_TYPE_ECC); + XFREE(point, key->heap, DYNAMIC_TYPE_ECC); return ret; } @@ -2986,9 +3214,7 @@ static int wc_Pkcs11CheckPrivKey_Rsa(RsaKey* priv, wc_FreeRsaKey(pub); } #ifdef WOLFSSL_SMALL_STACK - if (pub != NULL) { - XFREE(pub, NULL, DYNAMIC_TYPE_RSA); - } + XFREE(pub, NULL, DYNAMIC_TYPE_RSA); #endif return ret; @@ -3133,9 +3359,7 @@ static int wc_Pkcs11CheckPrivKey_Ecc(ecc_key* priv, wc_ecc_free(pub); } #ifdef WOLFSSL_SMALL_STACK - if (pub != NULL) { - XFREE(pub, NULL, DYNAMIC_TYPE_ECC); - } + XFREE(pub, NULL, DYNAMIC_TYPE_ECC); #endif return ret; @@ -3774,6 +3998,11 @@ int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx) switch (info->pk.type) { #ifndef NO_RSA case WC_PK_TYPE_RSA: + #ifdef WOLF_CRYPTO_CB_RSA_PAD + case WC_PK_TYPE_RSA_PKCS: + case WC_PK_TYPE_RSA_PSS: + case WC_PK_TYPE_RSA_OAEP: + #endif ret = Pkcs11OpenSession(token, &session, readWrite); if (ret == 0) { ret = Pkcs11Rsa(&session, info); diff --git a/src/wolfcrypt/src/wc_port.c b/src/wolfcrypt/src/wc_port.c index 32ffb9e..7fe2d35 100644 --- a/src/wolfcrypt/src/wc_port.c +++ b/src/wolfcrypt/src/wc_port.c @@ -1,6 +1,6 @@ /* port.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,6 +24,10 @@ #include #endif +#ifdef __APPLE__ + #include +#endif + #include #include #include @@ -40,6 +44,13 @@ #include #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include +#ifdef WOLF_CRYPTO_CB + #include +#endif +#endif + #ifdef WOLFSSL_PSOC6_CRYPTO #include #endif @@ -132,6 +143,13 @@ #include #endif +#if defined(WOLFSSL_ZEPHYR) +#if defined(CONFIG_BOARD_NATIVE_POSIX) +#include "native_rtc.h" +#define CONFIG_RTC +#endif +#endif + /* prevent multiple mutex initializations */ static volatile int initRefCount = 0; @@ -240,6 +258,22 @@ int wolfCrypt_Init(void) } #endif + /* Crypto Callbacks only works on AES for MAX32666/5 HW */ + #if defined(MAX3266X_AES) && defined(WOLF_CRYPTO_CB) + ret = wc_CryptoCb_RegisterDevice(WOLFSSL_MAX3266X_DEVID, wc_MxcCryptoCb, + NULL); + if(ret != 0) { + return ret; + } + #endif + #if defined(MAX3266X_RTC) + ret = wc_MXC_RTC_Init(); + if (ret != 0) { + WOLFSSL_MSG("MXC RTC Init Failed"); + return WC_HW_E; + } + #endif + #if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A) || \ defined(WOLFSSL_ATECC608A) ret = atmel_init(); @@ -331,6 +365,13 @@ int wolfCrypt_Init(void) return ret; } #endif + #if defined(HAVE_OID_ENCODING) && (!defined(HAVE_FIPS) || \ + (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))) + if ((ret = wc_ecc_oid_cache_init()) != 0) { + WOLFSSL_MSG("Error creating ECC oid cache"); + return ret; + } + #endif #endif #ifdef WOLFSSL_SCE @@ -422,6 +463,10 @@ int wolfCrypt_Cleanup(void) #ifdef ECC_CACHE_CURVE wc_ecc_curve_cache_free(); #endif + #if defined(HAVE_OID_ENCODING) && (!defined(HAVE_FIPS) || \ + (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))) + wc_ecc_oid_cache_free(); + #endif #endif /* HAVE_ECC */ #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) @@ -1170,6 +1215,23 @@ int wc_strncasecmp(const char *s1, const char *s2, size_t n) } #endif /* USE_WOLF_STRNCASECMP */ +#ifdef USE_WOLF_STRDUP +char* wc_strdup_ex(const char *src, int memType) { + char *ret = NULL; + word32 len = 0; + + if (src) { + len = (word32)XSTRLEN(src) + 1; /* Add one for null terminator */ + ret = (char*)XMALLOC(len, NULL, memType); + if (ret != NULL) { + XMEMCPY(ret, src, len); + } + } + + return ret; +} +#endif + #ifdef WOLFSSL_ATOMIC_OPS #ifdef HAVE_C___ATOMIC @@ -1322,6 +1384,196 @@ int wolfSSL_CryptHwMutexUnLock(void) #endif /* WOLFSSL_CRYPT_HW_MUTEX */ +#if WOLFSSL_CRYPT_HW_MUTEX && defined(WOLFSSL_ALGO_HW_MUTEX) +/* Mutex for protection of cryptography hardware */ +#ifndef NO_RNG_MUTEX +static wolfSSL_Mutex wcCryptHwRngMutex \ + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wcCryptHwRngMutex); +#endif /* NO_RNG_MUTEX */ +#ifndef NO_AES_MUTEX +static wolfSSL_Mutex wcCryptHwAesMutex \ + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wcCryptHwAesMutex); +#endif /* NO_AES_MUTEX */ +#ifndef NO_HASH_MUTEX +static wolfSSL_Mutex wcCryptHwHashMutex \ + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wcCryptHwHashMutex); +#endif /* NO_HASH_MUTEX */ +#ifndef NO_PK_MUTEX +static wolfSSL_Mutex wcCryptHwPkMutex \ + WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wcCryptHwPkMutex); +#endif /* NO_PK_MUTEX */ + +#ifndef WOLFSSL_MUTEX_INITIALIZER +#ifndef NO_RNG_MUTEX +static int wcCryptHwRngMutexInit = 0; +#endif /* NO_RNG_MUTEX */ +#ifndef NO_AES_MUTEX +static int wcCryptHwAesMutexInit = 0; +#endif /* NO_AES_MUTEX */ +#ifndef NO_HASH_MUTEX +static int wcCryptHwHashMutexInit = 0; +#endif /* NO_HASH_MUTEX */ +#ifndef NO_PK_MUTEX +static int wcCryptHwPkMutexInit = 0; +#endif /* NO_PK_MUTEX */ +#endif /* WOLFSSL_MUTEX_INITIALIZER */ + + +/* Allows ability to switch to different mutex based on enum type */ +/* hw_mutex_algo, expects the dereferenced Ptrs to be set to NULL */ +static int hwAlgoPtrSet(hw_mutex_algo hwAlgo, wolfSSL_Mutex** wcHwAlgoMutexPtr, + int** wcHwAlgoInitPtr) +{ + if (*wcHwAlgoMutexPtr != NULL || *wcHwAlgoInitPtr != NULL) { + return BAD_FUNC_ARG; + } + switch (hwAlgo) { + #ifndef NO_RNG_MUTEX + case rng_mutex: + *wcHwAlgoMutexPtr = &wcCryptHwRngMutex; + *wcHwAlgoInitPtr = &wcCryptHwRngMutexInit; + break; + #endif + #ifndef NO_AES_MUTEX + case aes_mutex: + *wcHwAlgoMutexPtr = &wcCryptHwAesMutex; + *wcHwAlgoInitPtr = &wcCryptHwAesMutexInit; + break; + #endif + #ifndef NO_HASH_MUTEX + case hash_mutex: + *wcHwAlgoMutexPtr = &wcCryptHwHashMutex; + *wcHwAlgoInitPtr = &wcCryptHwHashMutexInit; + break; + #endif + #ifndef NO_PK_MUTEX + case pk_mutex: + *wcHwAlgoMutexPtr = &wcCryptHwPkMutex; + *wcHwAlgoInitPtr = &wcCryptHwPkMutexInit; + break; + #endif + default: + return BAD_FUNC_ARG; + } + return 0; +} + +static int hwAlgoMutexInit(hw_mutex_algo hwAlgo) +{ + int ret = 0; +#ifndef WOLFSSL_MUTEX_INITIALIZER + wolfSSL_Mutex* wcHwAlgoMutexPtr = NULL; + int* wcHwAlgoInitPtr = NULL; + ret = hwAlgoPtrSet(hwAlgo, &wcHwAlgoMutexPtr, &wcHwAlgoInitPtr); + if (ret != 0) { + return ret; + } + if (*wcHwAlgoInitPtr == 0) { + ret = wc_InitMutex(wcHwAlgoMutexPtr); + if (ret == 0) { + *wcHwAlgoInitPtr = 1; + } + } +#endif + return ret; +} + +static int hwAlgoMutexLock(hw_mutex_algo hwAlgo) +{ + /* Make sure HW Mutex has been initialized */ + int ret = 0; + wolfSSL_Mutex* wcHwAlgoMutexPtr = NULL; + int* wcHwAlgoInitPtr = NULL; + ret = hwAlgoPtrSet(hwAlgo, &wcHwAlgoMutexPtr, &wcHwAlgoInitPtr); + if (ret != 0) { + return ret; + } + ret = hwAlgoMutexInit(hwAlgo); + if (ret == 0) { + ret = wc_LockMutex(wcHwAlgoMutexPtr); + } + return ret; +} + +static int hwAlgoMutexUnLock(hw_mutex_algo hwAlgo) +{ + wolfSSL_Mutex* wcHwAlgoMutexPtr = NULL; + int* wcHwAlgoInitPtr = NULL; + if (hwAlgoPtrSet(hwAlgo, &wcHwAlgoMutexPtr, &wcHwAlgoInitPtr) != 0) { + return BAD_FUNC_ARG; + } + if (*wcHwAlgoInitPtr) { + return wc_UnLockMutex(wcHwAlgoMutexPtr); + } + else { + return BAD_MUTEX_E; + } +} + +/* Wrap around generic hwAlgo* functions and use correct */ +/* global mutex to determine if it can be unlocked/locked */ +#ifndef NO_RNG_MUTEX +int wolfSSL_HwRngMutexInit(void) +{ + return hwAlgoMutexInit(rng_mutex); +} +int wolfSSL_HwRngMutexLock(void) +{ + return hwAlgoMutexLock(rng_mutex); +} +int wolfSSL_HwRngMutexUnLock(void) +{ + return hwAlgoMutexUnLock(rng_mutex); +} +#endif /* NO_RNG_MUTEX */ + +#ifndef NO_AES_MUTEX +int wolfSSL_HwAesMutexInit(void) +{ + return hwAlgoMutexInit(aes_mutex); +} +int wolfSSL_HwAesMutexLock(void) +{ + return hwAlgoMutexLock(aes_mutex); +} +int wolfSSL_HwAesMutexUnLock(void) +{ + return hwAlgoMutexUnLock(aes_mutex); +} +#endif /* NO_AES_MUTEX */ + +#ifndef NO_HASH_MUTEX +int wolfSSL_HwHashMutexInit(void) +{ + return hwAlgoMutexInit(hash_mutex); +} +int wolfSSL_HwHashMutexLock(void) +{ + return hwAlgoMutexLock(hash_mutex); +} +int wolfSSL_HwHashMutexUnLock(void) +{ + return hwAlgoMutexUnLock(hash_mutex); +} +#endif /* NO_HASH_MUTEX */ + +#ifndef NO_PK_MUTEX +int wolfSSL_HwPkMutexInit(void) +{ + return hwAlgoMutexInit(pk_mutex); +} +int wolfSSL_HwPkMutexLock(void) +{ + return hwAlgoMutexLock(pk_mutex); +} +int wolfSSL_HwPkMutexUnLock(void) +{ + return hwAlgoMutexUnLock(pk_mutex); +} +#endif /* NO_PK_MUTEX */ + +#endif /* WOLFSSL_CRYPT_HW_MUTEX && defined(WOLFSSL_ALGO_HW_MUTEX) */ + /* ---------------------------------------------------------------------------*/ /* Mutex Ports */ /* ---------------------------------------------------------------------------*/ @@ -3121,6 +3373,9 @@ time_t mqx_time(time_t* timer) #endif /* FREESCALE_MQX || FREESCALE_KSDK_MQX */ +#if defined(MAX3266X_RTC) + #define XTIME wc_MXC_RTC_Time +#endif #if defined(WOLFSSL_TIRTOS) && defined(USER_TIME) @@ -3173,6 +3428,21 @@ time_t z_time(time_t * timer) #if defined(CONFIG_RTC) && \ (defined(CONFIG_PICOLIBC) || defined(CONFIG_NEWLIB_LIBC)) + + #if defined(CONFIG_BOARD_NATIVE_POSIX) + + /* When using native sim, get time from simulator rtc */ + uint32_t nsec = 0; + uint64_t sec = 0; + native_rtc_gettime(RTC_CLOCK_PSEUDOHOSTREALTIME, &nsec, &sec); + + if (timer != NULL) + *timer = sec; + + return sec; + + #else + /* Try to obtain the actual time from an RTC */ static const struct device *rtc = DEVICE_DT_GET(DT_NODELABEL(rtc)); @@ -3191,6 +3461,7 @@ time_t z_time(time_t * timer) return epochTime; } } + #endif /* defined(CONFIG_BOARD_NATIVE_POSIX) */ #endif /* Fallback to uptime since boot. This works for relative times, but @@ -3353,6 +3624,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) } #endif + /* custom memory wrappers */ #ifdef WOLFSSL_NUCLEUS_1_2 @@ -3774,20 +4046,25 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) } #ifdef WOLFSSL_COND - #ifndef __MACH__ - /* Generic POSIX conditional */ + #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 \ + && !defined(__ppc__) + /* Apple style dispatch semaphore */ int wolfSSL_CondInit(COND_TYPE* cond) { if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_mutex_init(&cond->mutex, NULL) != 0) + /* dispatch_release() fails hard, with Trace/BPT trap signal, if the + * sem's internal count is less than the value passed in with + * dispatch_semaphore_create(). work around this by initing + * with 0, then incrementing it afterwards. + */ + cond->cond = dispatch_semaphore_create(0); + if (cond->cond == NULL) return MEMORY_E; - if (pthread_cond_init(&cond->cond, NULL) != 0) { - /* Keep compilers happy that we are using the return code */ - if (pthread_mutex_destroy(&cond->mutex) != 0) - return MEMORY_E; + if (wc_InitMutex(&cond->mutex) != 0) { + dispatch_release(cond->cond); return MEMORY_E; } @@ -3796,18 +4073,17 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) int wolfSSL_CondFree(COND_TYPE* cond) { - int ret = 0; - if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_mutex_destroy(&cond->mutex) != 0) - ret = MEMORY_E; + dispatch_release(cond->cond); + cond->cond = NULL; - if (pthread_cond_destroy(&cond->cond) != 0) - ret = MEMORY_E; + if (wc_FreeMutex(&cond->mutex) != 0) { + return MEMORY_E; + } - return ret; + return 0; } int wolfSSL_CondStart(COND_TYPE* cond) @@ -3815,7 +4091,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_mutex_lock(&cond->mutex) != 0) + if (wc_LockMutex(&cond->mutex) != 0) return BAD_MUTEX_E; return 0; @@ -3826,8 +4102,13 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_cond_signal(&cond->cond) != 0) - return MEMORY_E; + if (wc_UnLockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + + dispatch_semaphore_signal(cond->cond); + + if (wc_LockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; return 0; } @@ -3837,8 +4118,13 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_cond_wait(&cond->cond, &cond->mutex) != 0) - return MEMORY_E; + if (wc_UnLockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + + dispatch_semaphore_wait(cond->cond, DISPATCH_TIME_FOREVER); + + if (wc_LockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; return 0; } @@ -3848,29 +4134,26 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (pthread_mutex_unlock(&cond->mutex) != 0) + if (wc_UnLockMutex(&cond->mutex) != 0) return BAD_MUTEX_E; return 0; } - #else /* __MACH__ */ - /* Apple style dispatch semaphore */ + + #else /* Generic POSIX conditional */ + int wolfSSL_CondInit(COND_TYPE* cond) { if (cond == NULL) return BAD_FUNC_ARG; - /* dispatch_release() fails hard, with Trace/BPT trap signal, if the - * sem's internal count is less than the value passed in with - * dispatch_semaphore_create(). work around this by initing - * with 0, then incrementing it afterwards. - */ - cond->cond = dispatch_semaphore_create(0); - if (cond->cond == NULL) + if (pthread_mutex_init(&cond->mutex, NULL) != 0) return MEMORY_E; - if (wc_InitMutex(&cond->mutex) != 0) { - dispatch_release(cond->cond); + if (pthread_cond_init(&cond->cond, NULL) != 0) { + /* Keep compilers happy that we are using the return code */ + if (pthread_mutex_destroy(&cond->mutex) != 0) + return MEMORY_E; return MEMORY_E; } @@ -3879,17 +4162,18 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) int wolfSSL_CondFree(COND_TYPE* cond) { + int ret = 0; + if (cond == NULL) return BAD_FUNC_ARG; - dispatch_release(cond->cond); - cond->cond = NULL; + if (pthread_mutex_destroy(&cond->mutex) != 0) + ret = MEMORY_E; - if (wc_FreeMutex(&cond->mutex) != 0) { - return MEMORY_E; - } + if (pthread_cond_destroy(&cond->cond) != 0) + ret = MEMORY_E; - return 0; + return ret; } int wolfSSL_CondStart(COND_TYPE* cond) @@ -3897,7 +4181,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (wc_LockMutex(&cond->mutex) != 0) + if (pthread_mutex_lock(&cond->mutex) != 0) return BAD_MUTEX_E; return 0; @@ -3908,13 +4192,8 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (wc_UnLockMutex(&cond->mutex) != 0) - return BAD_MUTEX_E; - - dispatch_semaphore_signal(cond->cond); - - if (wc_LockMutex(&cond->mutex) != 0) - return BAD_MUTEX_E; + if (pthread_cond_signal(&cond->cond) != 0) + return MEMORY_E; return 0; } @@ -3924,13 +4203,8 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (wc_UnLockMutex(&cond->mutex) != 0) - return BAD_MUTEX_E; - - dispatch_semaphore_wait(cond->cond, DISPATCH_TIME_FOREVER); - - if (wc_LockMutex(&cond->mutex) != 0) - return BAD_MUTEX_E; + if (pthread_cond_wait(&cond->cond, &cond->mutex) != 0) + return MEMORY_E; return 0; } @@ -3940,11 +4214,12 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) if (cond == NULL) return BAD_FUNC_ARG; - if (wc_UnLockMutex(&cond->mutex) != 0) + if (pthread_mutex_unlock(&cond->mutex) != 0) return BAD_MUTEX_E; return 0; } + #endif /* __MACH__ */ #endif /* WOLFSSL_COND */ diff --git a/src/wolfcrypt/src/wc_xmss.c b/src/wolfcrypt/src/wc_xmss.c index 0e63722..5c016db 100644 --- a/src/wolfcrypt/src/wc_xmss.c +++ b/src/wolfcrypt/src/wc_xmss.c @@ -1,6 +1,6 @@ /* wc_xmss.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wc_xmss_impl.c b/src/wolfcrypt/src/wc_xmss_impl.c index b45bc59..80ca967 100644 --- a/src/wolfcrypt/src/wc_xmss_impl.c +++ b/src/wolfcrypt/src/wc_xmss_impl.c @@ -1,6 +1,6 @@ /* wc_xmss_impl.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wolfevent.c b/src/wolfcrypt/src/wolfevent.c index 4ed7b8f..bf155c1 100644 --- a/src/wolfcrypt/src/wolfevent.c +++ b/src/wolfcrypt/src/wolfevent.c @@ -1,6 +1,6 @@ /* wolfevent.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/wolfmath.c b/src/wolfcrypt/src/wolfmath.c index df5f0f8..ce36b60 100644 --- a/src/wolfcrypt/src/wolfmath.c +++ b/src/wolfcrypt/src/wolfmath.c @@ -1,6 +1,6 @@ /* wolfmath.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -149,10 +149,10 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) for (; i < b->used; i++) { b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; } - b->used ^= (a->used ^ b->used) & (unsigned int)mask; + b->used ^= (a->used ^ b->used) & (mp_size_t)mask; #if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \ defined(WOLFSSL_SP_INT_NEGATIVE) - b->sign ^= (a->sign ^ b->sign) & (unsigned int)mask; + b->sign ^= (mp_sign_t)(a->sign ^ b->sign) & (mp_sign_t)mask; #endif } @@ -196,7 +196,7 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) ret = BAD_FUNC_ARG; } if (ret == MP_OKAY) { - a->used = (word32)digits; + a->used = (mp_size_t)digits; } #endif /* fill the data with random bytes */ @@ -358,9 +358,7 @@ void wc_bigint_zero(WC_BIGINT* a) void wc_bigint_free(WC_BIGINT* a) { if (a) { - if (a->buf) { - XFREE(a->buf, a->heap, DYNAMIC_TYPE_WOLF_BIGINT); - } + XFREE(a->buf, a->heap, DYNAMIC_TYPE_WOLF_BIGINT); a->buf = NULL; a->len = 0; } diff --git a/src/wolfssl/bio.c b/src/wolfssl/bio.c index 340cbfd..ac4eb03 100644 --- a/src/wolfssl/bio.c +++ b/src/wolfssl/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,10 +24,9 @@ #endif #include -#if defined(OPENSSL_EXTRA) && !defined(_WIN32) +#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ - #undef _GNU_SOURCE - #define _GNU_SOURCE + #define _GNU_SOURCE 1 #endif #if !defined(WOLFSSL_BIO_INCLUDED) @@ -161,7 +160,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->wrSz = 0; bio->mem_buf->length = 0; } - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { @@ -180,7 +179,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } bio->mem_buf->length = (size_t)bio->wrSz; - bio->ptr = bio->mem_buf->data; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } } else { @@ -217,11 +216,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return WOLFSSL_FATAL_ERROR; bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_read((WOLFSSL*)bio->ptr, buf, len); + ret = wolfSSL_read(bio->ptr.ssl, buf, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -235,15 +234,15 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, buf, (size_t)sz) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, buf, (size_t)sz) != WOLFSSL_SUCCESS) { return WOLFSSL_FATAL_ERROR; } @@ -290,6 +289,9 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom read */ if (bio->method && bio->method->readCb) { ret = bio->method->readCb(bio, (char*)buf, len); @@ -302,19 +304,22 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) break; case WOLFSSL_BIO_BIO: /* read BIOs */ ret = wolfSSL_BIO_BIO_read(bio, buf, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_read(bio, buf, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFREAD(buf, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFREAD(buf, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XREAD) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XREAD(bio->num, buf, (size_t)len); + ret = (int)XREAD(bio->num.fd, buf, (size_t)len); #else WOLFSSL_MSG("No file pointer and XREAD not enabled"); ret = NOT_COMPILED_IN; @@ -345,14 +350,52 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Recv(bio->num, (char*)buf, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Recv(bio->num.fd, (char*)buf, len, 0); + else { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + ret = wolfIO_RecvFrom(bio->num.fd, &bio->peer_addr, + (char*)buf, len, 0); + } + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (!inhibit_flow_increment)) { + bio->bytes_read += (word32)ret; + } +#endif + /* case where front of list is done */ if (bio == front) { break; /* at front of list so be done */ @@ -409,8 +452,9 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } } else { - if (Base64_Encode((const byte*)data, inLen, NULL, &sz) != - LENGTH_ONLY_E) { + if (Base64_Encode((const byte*)data, inLen, NULL, &sz) + != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + { WOLFSSL_MSG("Error with base64 get length"); return WOLFSSL_FATAL_ERROR; } @@ -468,16 +512,16 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_ENTER("wolfSSL_BIO_SSL_write"); - if (bio->ptr == NULL) { + if (bio->ptr.ssl == NULL) { return BAD_FUNC_ARG; } bio->flags &= ~(WOLFSSL_BIO_FLAG_RETRY); /* default no retry */ - ret = wolfSSL_write((WOLFSSL*)bio->ptr, data, len); + ret = wolfSSL_write(bio->ptr.ssl, data, len); if (ret == 0) front->eof = 1; else if (ret < 0) { - int err = wolfSSL_get_error((WOLFSSL*)bio->ptr, 0); + int err = wolfSSL_get_error(bio->ptr.ssl, 0); if ( !(err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE) ) { front->eof = 1; } @@ -576,8 +620,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, } XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); - bio->ptr = bio->mem_buf->data; - bio->num = (int)bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; bio->wrSz += len; bio->wrIdx += len; @@ -598,14 +642,14 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type((WOLFSSL_EVP_MD_CTX*)bio->ptr) == NID_hmac) { - if (wolfSSL_EVP_DigestSignUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } } else { - if (wolfSSL_EVP_DigestUpdate((WOLFSSL_EVP_MD_CTX*)bio->ptr, data, (size_t)len) + if (wolfSSL_EVP_DigestUpdate(bio->ptr.md_ctx, data, (size_t)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; } @@ -647,6 +691,9 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } while (bio != NULL && ret >= 0) { +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + int inhibit_flow_increment = 0; +#endif /* check for custom write */ if (bio->method && bio->method->writeCb) { ret = bio->method->writeCb(bio, (const char*)data, len); @@ -672,19 +719,22 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) } case WOLFSSL_BIO_BIO: /* write bios */ ret = wolfSSL_BIO_BIO_write(bio, data, len); +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + inhibit_flow_increment = 1; +#endif break; case WOLFSSL_BIO_MEMORY: ret = wolfSSL_BIO_MEMORY_write(bio, data, len); break; case WOLFSSL_BIO_FILE: #ifndef NO_FILESYSTEM - if (bio->ptr) { - ret = (int)XFWRITE(data, 1, (size_t)len, (XFILE)bio->ptr); + if (bio->ptr.fh) { + ret = (int)XFWRITE(data, 1, (size_t)len, bio->ptr.fh); } else { #if defined(XWRITE) && !defined(NO_WOLFSSL_DIR) && \ !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - ret = (int)XWRITE(bio->num, data, (size_t)len); + ret = (int)XWRITE(bio->num.fd, data, (size_t)len); #else WOLFSSL_MSG("No file pointer and XWRITE not enabled"); ret = NOT_COMPILED_IN; @@ -725,14 +775,50 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #ifdef USE_WOLFSSL_IO /* BIO requires built-in socket support * (cannot be used with WOLFSSL_USER_IO) */ - ret = wolfIO_Send(bio->num, (char*)data, len, 0); + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } #else ret = NOT_COMPILED_IN; #endif break; + + case WOLFSSL_BIO_DGRAM: + #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) && \ + defined(USE_WOLFSSL_IO) + /* BIO requires built-in socket support + * (cannot be used with WOLFSSL_USER_IO) */ + bio->flags &= ~WOLFSSL_BIO_FLAG_RETRY; + if (bio->connected) + ret = wolfIO_Send(bio->num.fd, (char*)data, len, 0); + else if (bio->peer_addr.sa.sa_family == AF_UNSPEC) + ret = SOCKET_ERROR_E; + else + ret = wolfIO_SendTo(bio->num.fd, &bio->peer_addr, (char*)data, len, 0); + if (ret == WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE)) { + bio->flags |= WOLFSSL_BIO_FLAG_RETRY; + } + if (ret < 0) { + ret = WOLFSSL_BIO_ERROR; + } + #else + ret = NOT_COMPILED_IN; + #endif + break; + } /* switch */ } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + if ((ret > 0) && (! inhibit_flow_increment)) + bio->bytes_written += (word32)ret; +#endif + /* advance to the next bio in list */ bio = bio->next; } @@ -748,7 +834,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) (const char*)data, len, 0, ret); } - if (frmt != NULL) { + if (front != NULL) { XFREE(frmt, front->heap, DYNAMIC_TYPE_TMP_BUFFER); } @@ -793,6 +879,49 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) case BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; + +#ifdef WOLFSSL_HAVE_BIO_ADDR + case BIO_CTRL_DGRAM_CONNECT: + case BIO_CTRL_DGRAM_SET_PEER: + { + socklen_t addr_size; + if (parg == NULL) { + ret = WOLFSSL_FAILURE; + break; + } + addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + ret = WOLFSSL_SUCCESS; + break; + } + + case BIO_CTRL_DGRAM_SET_CONNECTED: + if (parg == NULL) { + wolfSSL_BIO_ADDR_clear(&bio->peer_addr); + bio->connected = 0; + } + else { + socklen_t addr_size = wolfSSL_BIO_ADDR_size((WOLFSSL_BIO_ADDR *)parg); + if (addr_size == 0) { + ret = WOLFSSL_FAILURE; + break; + } + XMEMCPY(&bio->peer_addr, parg, addr_size); + bio->connected = 1; + } + ret = WOLFSSL_SUCCESS; + break; + + case BIO_CTRL_DGRAM_QUERY_MTU: + ret = 0; /* not implemented */ + break; + +#endif /* WOLFSSL_HAVE_BIO_ADDR */ + default: WOLFSSL_MSG("CMD not yet implemented"); ret = WOLFSSL_FAILURE; @@ -826,8 +955,51 @@ int wolfSSL_BIO_up_ref(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } + +#ifdef WOLFSSL_HAVE_BIO_ADDR +WOLFSSL_BIO_ADDR *wolfSSL_BIO_ADDR_new(void) { + WOLFSSL_BIO_ADDR *addr = + (WOLFSSL_BIO_ADDR *)XMALLOC(sizeof(*addr), NULL, DYNAMIC_TYPE_BIO); + if (addr) + addr->sa.sa_family = AF_UNSPEC; + return addr; +} + +void wolfSSL_BIO_ADDR_free(WOLFSSL_BIO_ADDR *addr) { + XFREE(addr, NULL, DYNAMIC_TYPE_BIO); +} + +void wolfSSL_BIO_ADDR_clear(WOLFSSL_BIO_ADDR *addr) { + if (addr == NULL) + return; + XMEMSET(addr, 0, sizeof(*addr)); + addr->sa.sa_family = AF_UNSPEC; +} + +socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr) { + switch (addr->sa.sa_family) { +#ifndef WOLFSSL_NO_BIO_ADDR_IN + case AF_INET: + return sizeof(addr->sa_in); +#endif +#ifdef WOLFSSL_IPV6 + case AF_INET6: + return sizeof(addr->sa_in6); #endif +#if defined(HAVE_SYS_UN_H) && !defined(WOLFSSL_NO_SOCKADDR_UN) + case AF_UNIX: + return sizeof(addr->sa_un); +#endif + default: + /* must return zero if length can't be determined, to avoid buffer + * overruns in callers. + */ + return 0; + } +} +#endif /* WOLFSSL_HAVE_BIO_ADDR */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ /* helper function for wolfSSL_BIO_gets * size till a newline is hit @@ -888,15 +1060,15 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (((XFILE)bio->ptr) == XBADFILE) { + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_BIO_ERROR; } #if defined(MICRIUM) || defined(LSR_FS) || defined(EBSNET) WOLFSSL_MSG("XFGETS not ported for this system yet"); - ret = XFGETS(buf, sz, (XFILE)bio->ptr); + ret = XFGETS(buf, sz, bio->ptr.fh); #else - if (XFGETS(buf, sz, (XFILE)bio->ptr) != NULL) { + if (XFGETS(buf, sz, bio->ptr.fh) != NULL) { ret = (int)XSTRLEN(buf); } else { @@ -972,13 +1144,13 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) #ifndef WOLFCRYPT_ONLY /* call final on hash */ case WOLFSSL_BIO_MD: - if (wolfSSL_EVP_MD_CTX_size((WOLFSSL_EVP_MD_CTX*)bio->ptr) > sz) { + if (wolfSSL_EVP_MD_CTX_size(bio->ptr.md_ctx) > sz) { WOLFSSL_MSG("Output buffer was too small for digest"); ret = WOLFSSL_FAILURE; } else { unsigned int szOut = 0; - ret = wolfSSL_EVP_DigestFinal((WOLFSSL_EVP_MD_CTX*)bio->ptr, + ret = wolfSSL_EVP_DigestFinal(bio->ptr.md_ctx, (unsigned char*)buf, &szOut); if (ret == WOLFSSL_SUCCESS) { ret = (int)szOut; @@ -1133,8 +1305,8 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) } #ifndef WOLFCRYPT_ONLY - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr != NULL) { - return (long)wolfSSL_pending((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { + return (long)wolfSSL_pending(bio->ptr.ssl); } #endif @@ -1162,7 +1334,7 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) { WOLFSSL_BIO* front = bio; - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_get_mem_ptr"); @@ -1188,7 +1360,10 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio = bio->prev; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } #ifdef OPENSSL_ALL @@ -1208,8 +1383,8 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; - bio->num = (int)bio->mem_buf->max; - bio->ptr = bio->mem_buf->data; + bio->num.length = bio->mem_buf->max; + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->wrIdx = 0; bio->rdIdx = 0; @@ -1242,15 +1417,16 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } - if (bio->ptr != NULL) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data != NULL) { + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr = (byte*)XMALLOC(size, bio->heap, DYNAMIC_TYPE_OPENSSL); - if (bio->ptr == NULL) { + bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + DYNAMIC_TYPE_OPENSSL); + if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); bio->wrSz = 0; - bio->num = 0; + bio->num.length = 0; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1261,13 +1437,13 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num = (int)size; + bio->num.length = size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { - bio->mem_buf->data = (char*)bio->ptr; - bio->mem_buf->length = (size_t)bio->num; - bio->mem_buf->max = (size_t)bio->num; + bio->mem_buf->data = (char*)bio->ptr.mem_buf_data; + bio->mem_buf->length = bio->num.length; + bio->mem_buf->max = bio->num.length; } return WOLFSSL_SUCCESS; @@ -1295,12 +1471,12 @@ int wolfSSL_BIO_make_bio_pair(WOLFSSL_BIO *b1, WOLFSSL_BIO *b2) } /* set default write size if not already set */ - if (b1->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b1, + if (b1->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b1, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } - if (b2->ptr == NULL && wolfSSL_BIO_set_write_buf_size(b2, + if (b2->ptr.mem_buf_data == NULL && wolfSSL_BIO_set_write_buf_size(b2, WOLFSSL_BIO_SIZE) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -1341,7 +1517,7 @@ int wolfSSL_BIO_nread0(WOLFSSL_BIO *bio, char **buf) WOLFSSL_BIO* pair = bio->pair; /* case where have wrapped around write buffer */ - *buf = (char*)pair->ptr + pair->rdIdx; + *buf = (char*)pair->ptr.mem_buf_data + pair->rdIdx; if (pair->wrIdx > 0 && pair->rdIdx >= pair->wrIdx) { return pair->wrSz - pair->rdIdx; } @@ -1373,7 +1549,7 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { /* special case if asking to read 0 bytes */ if (num == 0) { - *buf = (char*)bio->pair->ptr + bio->pair->rdIdx; + *buf = (char*)bio->pair->ptr.mem_buf_data + bio->pair->rdIdx; return 0; } @@ -1387,6 +1563,9 @@ int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num) sz = num; } bio->pair->rdIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->pair->bytes_read += (word32)sz; +#endif /* check if have read to the end of the buffer and need to reset */ if (bio->pair->rdIdx == bio->pair->wrSz) { @@ -1424,7 +1603,7 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (bio->pair != NULL) { if (num == 0) { - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; return 0; } @@ -1463,8 +1642,11 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) if (num < sz) { sz = num; } - *buf = (char*)bio->ptr + bio->wrIdx; + *buf = (char*)bio->ptr.mem_buf_data + bio->wrIdx; bio->wrIdx += sz; +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS + bio->bytes_written += (word32)sz; +#endif /* if at the end of the buffer and space for wrap around then set * write index back to 0 */ @@ -1476,6 +1658,37 @@ int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num) return sz; } +#ifdef WOLFSSL_BIO_HAVE_FLOW_STATS +word64 wolfSSL_BIO_number_read(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_read; + bio = bio->next; + } + + return ret; +} + +word64 wolfSSL_BIO_number_written(WOLFSSL_BIO *bio) +{ + word64 ret = 0; + if (bio == NULL) { + WOLFSSL_MSG("NULL argument passed in"); + return 0; + } + while (bio) { + ret += bio->bytes_written; + bio = bio->next; + } + + return ret; +} +#endif /* WOLFSSL_BIO_HAVE_FLOW_STATS */ /* Reset BIO to initial state */ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) @@ -1491,16 +1704,16 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) switch (bio->type) { #ifndef NO_FILESYSTEM case WOLFSSL_BIO_FILE: - if (XFSEEK((XFILE)bio->ptr, 0, XSEEK_SET) != 0) + if (XFSEEK(bio->ptr.fh, 0, XSEEK_SET) != 0) return WOLFSSL_BIO_ERROR; else - return 0; + return WOLFSSL_SUCCESS; #endif case WOLFSSL_BIO_BIO: bio->rdIdx = 0; bio->wrIdx = 0; - return 0; + return WOLFSSL_SUCCESS; case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; @@ -1510,27 +1723,27 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) } else { bio->wrSz = 0; - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; - bio->num = 0; + XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; + bio->num.length = 0; if (bio->mem_buf != NULL) { bio->mem_buf->data = NULL; bio->mem_buf->length = 0; bio->mem_buf->max = 0; } } - return 0; + return WOLFSSL_SUCCESS; #ifndef WOLFCRYPT_ONLY case WOLFSSL_BIO_MD: - if (bio->ptr != NULL) { + if (bio->ptr.md_ctx != NULL) { const WOLFSSL_EVP_MD* md = - wolfSSL_EVP_MD_CTX_md((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_cleanup((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_MD_CTX_init((WOLFSSL_EVP_MD_CTX*)bio->ptr); - wolfSSL_EVP_DigestInit((WOLFSSL_EVP_MD_CTX*)bio->ptr, md); + wolfSSL_EVP_MD_CTX_md(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_cleanup(bio->ptr.md_ctx); + wolfSSL_EVP_MD_CTX_init(bio->ptr.md_ctx); + wolfSSL_EVP_DigestInit(bio->ptr.md_ctx, md); } - return 0; + return WOLFSSL_SUCCESS; #endif /* WOLFCRYPT_ONLY */ default: @@ -1580,7 +1793,7 @@ long wolfSSL_BIO_set_fp(WOLFSSL_BIO *bio, XFILE fp, int c) } bio->shutdown = (byte)c; - bio->ptr = (XFILE)fp; + bio->ptr.fh = fp; return WOLFSSL_SUCCESS; } @@ -1598,7 +1811,7 @@ long wolfSSL_BIO_get_fp(WOLFSSL_BIO *bio, XFILE* fp) return WOLFSSL_FAILURE; } - *fp = (XFILE)bio->ptr; + *fp = bio->ptr.fh; return WOLFSSL_SUCCESS; } @@ -1613,8 +1826,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (((XFILE)bio->ptr) != XBADFILE && bio->shutdown == BIO_CLOSE) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + XFCLOSE(bio->ptr.fh); } /* 'b' flag is ignored on POSIX targets, but on Windows it assures @@ -1622,8 +1835,8 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) * between the size and contents of the representation in memory and on * disk. */ - bio->ptr = XFOPEN(name, "wb"); - if (((XFILE)bio->ptr) == XBADFILE) { + bio->ptr.fh = XFOPEN(name, "wb"); + if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } bio->shutdown = BIO_CLOSE; @@ -1640,13 +1853,13 @@ int wolfSSL_BIO_seek(WOLFSSL_BIO *bio, int ofs) WOLFSSL_ENTER("wolfSSL_BIO_seek"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } /* offset ofs from beginning of file */ if (bio->type == WOLFSSL_BIO_FILE && - XFSEEK((XFILE)bio->ptr, ofs, SEEK_SET) < 0) { - return -1; + XFSEEK(bio->ptr.fh, ofs, SEEK_SET) < 0) { + return WOLFSSL_FATAL_ERROR; } return 0; @@ -1663,16 +1876,16 @@ int wolfSSL_BIO_tell(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_tell"); if (bio == NULL) { - return -1; + return WOLFSSL_FATAL_ERROR; } if (bio->type != WOLFSSL_BIO_FILE) { return 0; } - pos = (int)XFTELL((XFILE)bio->ptr); + pos = (int)XFTELL(bio->ptr.fh); if (pos < 0) - return -1; + return WOLFSSL_FATAL_ERROR; else return pos; } @@ -1799,15 +2012,16 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) if (bio) { switch (bio->type) { case WOLFSSL_BIO_SOCKET: + case WOLFSSL_BIO_DGRAM: #ifdef XFCNTL { int ret; - int flag = XFCNTL(bio->num, F_GETFL, 0); + int flag = XFCNTL(bio->num.fd, F_GETFL, 0); if (on) { - ret = XFCNTL(bio->num, F_SETFL, flag | O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag | O_NONBLOCK); } else { - ret = XFCNTL(bio->num, F_SETFL, flag & ~O_NONBLOCK); + ret = XFCNTL(bio->num.fd, F_SETFL, flag & ~O_NONBLOCK); } if (ret == -1) { @@ -1818,7 +2032,7 @@ long wolfSSL_BIO_set_nbio(WOLFSSL_BIO* bio, long on) break; case WOLFSSL_BIO_SSL: #ifdef WOLFSSL_DTLS - wolfSSL_dtls_set_using_nonblock((WOLFSSL*)bio->ptr, (int)on); + wolfSSL_dtls_set_using_nonblock(bio->ptr.ssl, (int)on); #endif break; @@ -1966,7 +2180,7 @@ int wolfSSL_BIO_get_mem_data(WOLFSSL_BIO* bio, void* p) } if (p) { - *(byte**)p = (byte*)mem_bio->ptr + mem_bio->rdIdx; + *(byte**)p = mem_bio->ptr.mem_buf_data + mem_bio->rdIdx; } return mem_bio->wrSz - mem_bio->rdIdx; @@ -1991,7 +2205,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) - if (XFFLUSH((FILE *)bio->ptr) != 0) + if (XFFLUSH(bio->ptr.fh) != 0) return WOLFSSL_FAILURE; #endif /* !NO_FILESYSTEM && XFFLUSH */ @@ -2015,14 +2229,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) /* return the context and initialize the BIO state */ int wolfSSL_BIO_get_md_ctx(WOLFSSL_BIO *bio, WOLFSSL_EVP_MD_CTX **mdcp) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if ((bio != NULL) && (mdcp != NULL)) { - *mdcp = (WOLFSSL_EVP_MD_CTX*)bio->ptr; + *mdcp = bio->ptr.md_ctx; ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } WOLFSSL_BIO_METHOD* wolfSSL_BIO_f_buffer(void) @@ -2110,11 +2327,39 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio) { bio->type = WOLFSSL_BIO_SOCKET; bio->shutdown = (byte)closeF; - bio->num = sfd; + bio->num.fd = (SOCKET_T)sfd; } return bio; } + +#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(WOLFSSL_DTLS) + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_datagram(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_DGRAM); + + WOLFSSL_ENTER("wolfSSL_BIO_s_datagram"); + + return &meth; + } + + + WOLFSSL_BIO* wolfSSL_BIO_new_dgram(int fd, int closeF) + { + WOLFSSL_BIO* bio = wolfSSL_BIO_new(wolfSSL_BIO_s_datagram()); + + WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); + if (bio) { + bio->type = WOLFSSL_BIO_DGRAM; + bio->shutdown = (byte)closeF; + bio->num.fd = (SOCKET_T)fd; + } + return bio; + } +#endif + + /** * Create new socket BIO object. This is a pure TCP connection with * no SSL or TLS protection. @@ -2231,7 +2476,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2255,17 +2500,17 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - if (b->num == WOLFSSL_BIO_ERROR) { + if (b->num.fd == SOCKET_INVALID) { if (wolfIO_TcpBind(&sfd, b->port) < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; } - b->num = (int)sfd; + b->num.fd = sfd; b->shutdown = BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; - int newfd = wolfIO_TcpAccept(b->num, NULL, NULL); + int newfd = wolfIO_TcpAccept(b->num.fd, NULL, NULL); if (newfd < 0) { WOLFSSL_MSG("wolfIO_TcpBind error"); return WOLFSSL_FAILURE; @@ -2322,8 +2567,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } - if (b->type == WOLFSSL_BIO_SSL && b->ptr != NULL) { - return wolfSSL_negotiate((WOLFSSL*)b->ptr); + if (b->type == WOLFSSL_BIO_SSL && b->ptr.ssl != NULL) { + return wolfSSL_negotiate(b->ptr.ssl); } else { WOLFSSL_MSG("Not SSL BIO or no SSL object set"); @@ -2348,12 +2593,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return; } - if (b->ptr != NULL) { - int rc = wolfSSL_shutdown((WOLFSSL*)b->ptr); + if (b->ptr.ssl != NULL) { + int rc = wolfSSL_shutdown(b->ptr.ssl); if (rc == SSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ - wolfSSL_shutdown((WOLFSSL*)b->ptr); + wolfSSL_shutdown(b->ptr.ssl); } } else { @@ -2363,12 +2608,12 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { - long ret = WOLFSSL_FAILURE; + long ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_BIO_set_ssl"); if (b != NULL) { - b->ptr = ssl; + b->ptr.ssl = ssl; b->shutdown = (byte)closeF; if (b->next != NULL) wolfSSL_set_bio(ssl, b->next, b->next); @@ -2376,7 +2621,10 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) ret = WOLFSSL_SUCCESS; } - return ret; + if (ret == WOLFSSL_SUCCESS) + return ret; + else + return WOLFSSL_FAILURE; } long wolfSSL_BIO_get_ssl(WOLFSSL_BIO* bio, WOLFSSL** ssl) @@ -2396,7 +2644,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } - *ssl = (WOLFSSL*)bio->ptr; + *ssl = bio->ptr.ssl; return WOLFSSL_SUCCESS; } @@ -2540,7 +2788,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_set_fd"); if (b != NULL) { - b->num = fd; + b->num.fd = (SOCKET_T)fd; b->shutdown = (byte)closeF; } @@ -2584,7 +2832,14 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->method = method; #endif bio->shutdown = BIO_CLOSE; /* default to close things */ - bio->num = WOLFSSL_BIO_ERROR; + + if ((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) + { + bio->num.fd = SOCKET_INVALID; + } else { + bio->num.length = 0; + } bio->init = 1; #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) @@ -2616,8 +2871,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (method->type == WOLFSSL_BIO_MD) { - bio->ptr = wolfSSL_EVP_MD_CTX_new(); - if (bio->ptr == NULL) { + bio->ptr.md_ctx = wolfSSL_EVP_MD_CTX_new(); + if (bio->ptr.md_ctx == NULL) { WOLFSSL_MSG("Memory error"); wolfSSL_BIO_free(bio); return NULL; @@ -2656,11 +2911,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return NULL; } - bio->num = (int)bio->mem_buf->max; + bio->num.length = bio->mem_buf->max; bio->wrSz = len; - bio->ptr = bio->mem_buf->data; - if (len > 0 && bio->ptr != NULL) { - XMEMCPY(bio->ptr, buf, len); + bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; + if (len > 0 && bio->ptr.mem_buf_data != NULL) { + XMEMCPY(bio->ptr.mem_buf_data, buf, len); bio->flags |= BIO_FLAGS_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2723,44 +2978,51 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->pair->pair = NULL; } - if (bio->ip != NULL) { - XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); - } + XFREE(bio->ip, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->shutdown) { - if (bio->type == WOLFSSL_BIO_SSL && bio->ptr) - wolfSSL_free((WOLFSSL*)bio->ptr); + if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl) + wolfSSL_free(bio->ptr.ssl); #ifdef CloseSocket - if ((bio->type == WOLFSSL_BIO_SOCKET) && (bio->num > 0)) - CloseSocket(bio->num); + if (((bio->type == WOLFSSL_BIO_SOCKET) || + (bio->type == WOLFSSL_BIO_DGRAM)) && + (bio->num.fd != SOCKET_INVALID)) + { + CloseSocket(bio->num.fd); + } #endif } #ifndef NO_FILESYSTEM if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { - if (bio->ptr) { - XFCLOSE((XFILE)bio->ptr); + if (bio->ptr.fh) { + XFCLOSE(bio->ptr.fh); } #if !defined(USE_WINDOWS_API) && !defined(NO_WOLFSSL_DIR)\ && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - else if (bio->num != WOLFSSL_BIO_ERROR) { - XCLOSE(bio->num); + else if (bio->num.fd != SOCKET_INVALID) { + XCLOSE(bio->num.fd); } #endif } #endif if (bio->shutdown != BIO_NOCLOSE) { - if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr != NULL) { + if (bio->type == WOLFSSL_BIO_MEMORY && + bio->ptr.mem_buf_data != NULL) + { if (bio->mem_buf != NULL) { - if (bio->mem_buf->data != (char*)bio->ptr) { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + if ((byte *)bio->mem_buf->data != bio->ptr.mem_buf_data) + { + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } else { - XFREE(bio->ptr, bio->heap, DYNAMIC_TYPE_OPENSSL); - bio->ptr = NULL; + XFREE(bio->ptr.mem_buf_data, bio->heap, + DYNAMIC_TYPE_OPENSSL); + bio->ptr.mem_buf_data = NULL; } } if (bio->mem_buf != NULL) { @@ -2770,7 +3032,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } if (bio->type == WOLFSSL_BIO_MD) { - wolfSSL_EVP_MD_CTX_free((WOLFSSL_EVP_MD_CTX*)bio->ptr); + wolfSSL_EVP_MD_CTX_free(bio->ptr.md_ctx); } XFREE(bio, 0, DYNAMIC_TYPE_OPENSSL); @@ -2809,8 +3071,8 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } /* SSL BIO's should use the next object in the chain for IO */ - if (top->type == WOLFSSL_BIO_SSL && top->ptr) - wolfSSL_set_bio((WOLFSSL*)top->ptr, append, append); + if (top->type == WOLFSSL_BIO_SSL && top->ptr.ssl) + wolfSSL_set_bio(top->ptr.ssl, append, append); return top; } @@ -2914,9 +3176,11 @@ int wolfSSL_BIO_get_fd(WOLFSSL_BIO *bio, int* fd) WOLFSSL_ENTER("wolfSSL_BIO_get_fd"); if (bio != NULL) { + if (bio->num.fd == SOCKET_INVALID) + return WOLFSSL_BIO_ERROR; if (fd != NULL) - *fd = bio->num; - return bio->num; + *fd = (int)bio->num.fd; + return (int)bio->num.fd; } return WOLFSSL_BIO_ERROR; @@ -2991,10 +3255,10 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) switch (bio->type) { #if !defined(NO_FILESYSTEM) case WOLFSSL_BIO_FILE: - if (bio->ptr == NULL) { - return -1; + if (bio->ptr.fh == XBADFILE) { + return WOLFSSL_FATAL_ERROR; } - ret = XVFPRINTF((XFILE)bio->ptr, format, args); + ret = XVFPRINTF(bio->ptr.fh, format, args); break; #endif @@ -3088,21 +3352,22 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) return wolfSSL_BIO_write(bio, "\tNULL", 5); } - XSPRINTF(line, "%04x - ", lineOffset); + (void)XSNPRINTF(line, sizeof(line), "%04x - ", lineOffset); o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - XSPRINTF(line + o,"%02x ", (unsigned char)buf[i]); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + "%02x ", (unsigned char)buf[i]); else - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); if (i == 7) - XSPRINTF(line + o + 2, "-"); + (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); o += 3; } - XSPRINTF(line + o, " "); + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - XSPRINTF(line + o, "%c", + (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/wolfssl/callbacks.h b/src/wolfssl/callbacks.h index bf996fa..1010eca 100644 --- a/src/wolfssl/callbacks.h +++ b/src/wolfssl/callbacks.h @@ -1,6 +1,6 @@ /* callbacks.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/crl.h b/src/wolfssl/crl.h index 4b4dcc2..5e5205e 100644 --- a/src/wolfssl/crl.h +++ b/src/wolfssl/crl.h @@ -1,6 +1,6 @@ /* crl.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/error-ssl.h b/src/wolfssl/error-ssl.h index 724d7de..3130780 100644 --- a/src/wolfssl/error-ssl.h +++ b/src/wolfssl/error-ssl.h @@ -1,6 +1,6 @@ /* error-ssl.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -35,6 +35,19 @@ #endif enum wolfSSL_ErrorCodes { + WOLFSSL_FATAL_ERROR = -1, /* must be -1 for backward compat. */ + + /* negative counterparts to namesake positive constants in ssl.h */ + WOLFSSL_ERROR_WANT_READ_E = -2, + WOLFSSL_ERROR_WANT_WRITE_E = -3, + WOLFSSL_ERROR_WANT_X509_LOOKUP_E = -4, + WOLFSSL_ERROR_SYSCALL_E = -5, + WOLFSSL_ERROR_ZERO_RETURN_E = -6, + WOLFSSL_ERROR_WANT_CONNECT_E = -7, + WOLFSSL_ERROR_WANT_ACCEPT_E = -8, + + WOLFSSL_FIRST_E = -301, /* start of native TLS codes */ + INPUT_CASE_ERROR = -301, /* process input state error */ PREFIX_ERROR = -302, /* bad index to key rounds */ MEMORY_ERROR = -303, /* out of memory */ @@ -79,12 +92,14 @@ enum wolfSSL_ErrorCodes { ZERO_RETURN = -343, /* peer sent close notify */ SIDE_ERROR = -344, /* wrong client/server type */ NO_PEER_CERT = -345, /* peer didn't send key */ + ECC_CURVETYPE_ERROR = -350, /* Bad ECC Curve Type */ ECC_CURVE_ERROR = -351, /* Bad ECC Curve */ ECC_PEERKEY_ERROR = -352, /* Bad Peer ECC Key */ ECC_MAKEKEY_ERROR = -353, /* Bad Make ECC Key */ ECC_EXPORT_ERROR = -354, /* Bad ECC Export Key */ ECC_SHARED_ERROR = -355, /* Bad ECC Shared Secret */ + NOT_CA_ERROR = -357, /* Not a CA cert error */ BAD_CERT_MANAGER_ERROR = -359, /* Bad Cert Manager */ @@ -100,7 +115,7 @@ enum wolfSSL_ErrorCodes { COOKIE_ERROR = -369, /* dtls cookie error */ SEQUENCE_ERROR = -370, /* dtls sequence error */ SUITES_ERROR = -371, /* suites pointer error */ - + MAX_CERT_EXTENSIONS_ERR = -372, /* max cert extension exceeded */ OUT_OF_ORDER_E = -373, /* out of order message */ BAD_KEA_TYPE_E = -374, /* bad KEA type found */ SANITY_CIPHER_E = -375, /* sanity check on cipher error */ @@ -185,24 +200,40 @@ enum wolfSSL_ErrorCodes { DTLS_CID_ERROR = -454, /* Wrong or missing CID */ DTLS_TOO_MANY_FRAGMENTS_E = -455, /* Received too many fragments */ QUIC_WRONG_ENC_LEVEL = -456, /* QUIC data received on wrong encryption level */ - DUPLICATE_TLS_EXT_E = -457, /* Duplicate TLS extension in msg. */ - /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ - /* begin negotiation parameter errors */ + /* legacy CyaSSL compat layer error codes */ + WOLFSSL_ALPN_NOT_FOUND = -458, /* TLS extension not found */ + WOLFSSL_BAD_CERTTYPE = -459, /* Certificate type not supported */ + WOLFSSL_BAD_STAT = -460, /* not used */ + WOLFSSL_BAD_PATH = -461, /* No certificates found at designated path */ + WOLFSSL_BAD_FILETYPE = -462, /* Data format not supported */ + WOLFSSL_BAD_FILE = -463, /* Input/output error on file */ + WOLFSSL_NOT_IMPLEMENTED = -464, /* Function not implemented */ + WOLFSSL_UNKNOWN = -465, /* Unknown algorithm (EVP) */ + + /* negotiation parameter errors */ UNSUPPORTED_SUITE = -500, /* unsupported cipher suite */ MATCH_SUITE_ERROR = -501, /* can't match cipher suite */ COMPRESSION_ERROR = -502, /* compression mismatch */ KEY_SHARE_ERROR = -503, /* key share mismatch */ POST_HAND_AUTH_ERROR = -504, /* client won't do post-hand auth */ HRR_COOKIE_ERROR = -505, /* HRR msg cookie mismatch */ - UNSUPPORTED_CERTIFICATE = -506 /* unsupported certificate type */ - /* end negotiation parameter errors only 10 for now */ - /* add strings to wolfSSL_ERR_reason_error_string in internal.c !!!!! */ + UNSUPPORTED_CERTIFICATE = -506, /* unsupported certificate type */ - /* no error strings go down here, add above negotiation errors !!!! */ + WOLFSSL_LAST_E = -506 }; +/* I/O Callback default errors */ +enum IOerrors { + WOLFSSL_CBIO_ERR_GENERAL = -1, /* general unexpected err */ + WOLFSSL_CBIO_ERR_WANT_READ = -2, /* need to call read again */ + WOLFSSL_CBIO_ERR_WANT_WRITE = -2, /* need to call write again */ + WOLFSSL_CBIO_ERR_CONN_RST = -3, /* connection reset */ + WOLFSSL_CBIO_ERR_ISR = -4, /* interrupt */ + WOLFSSL_CBIO_ERR_CONN_CLOSE = -5, /* connection closed or epipe */ + WOLFSSL_CBIO_ERR_TIMEOUT = -6 /* socket timeout */ +}; #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) enum { @@ -215,7 +246,9 @@ enum wolfSSL_ErrorCodes { WOLFSSL_LOCAL void SetErrorString(int err, char* buff); -#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && \ + (defined(BUILDING_WOLFSSL) || \ + defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES_ALWAYS)) #include #endif diff --git a/src/wolfssl/evp.c b/src/wolfssl/evp.c index 42949fc..808aa04 100644 --- a/src/wolfssl/evp.c +++ b/src/wolfssl/evp.c @@ -1,6 +1,6 @@ /* evp.c * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -283,6 +283,40 @@ static const struct s_ent { static const char EVP_NULL[] = "NULL"; +static const struct pkey_type_name_ent { + int type; + const char *name; +} pkey_type_names[] = { + { EVP_PKEY_RSA, "RSA" }, + { EVP_PKEY_EC, "EC" }, + { EVP_PKEY_DH, "DH" }, + { EVP_PKEY_DSA, "DSA" } +}; + +static int pkey_type_by_name(const char *name) { + unsigned int i; + if (name == NULL) + return EVP_PKEY_NONE; + for (i = 0; i < XELEM_CNT(pkey_type_names); ++i) { + if (XSTRCMP(name, pkey_type_names[i].name) == 0) + return pkey_type_names[i].type; + } + return EVP_PKEY_NONE; +} + +int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { + int type; + + if (pkey == NULL) + return WOLFSSL_FAILURE; + + type = pkey_type_by_name(name); + if (type == EVP_PKEY_NONE) + return WOLFSSL_FAILURE; + + return (pkey->type == type) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} + #define EVP_CIPHER_TYPE_MATCHES(x, y) (XSTRCMP(x,y) == 0) #define EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 @@ -364,6 +398,9 @@ int wolfSSL_EVP_Cipher_key_length(const WOLFSSL_EVP_CIPHER* c) case DES_ECB_TYPE: return 8; case DES_EDE3_ECB_TYPE: return 24; #endif + #ifndef NO_RC4 + case ARC4_TYPE: return 16; + #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) case CHACHA20_POLY1305_TYPE: return 32; #endif @@ -452,7 +489,7 @@ void wolfSSL_EVP_CIPHER_CTX_free(WOLFSSL_EVP_CIPHER_CTX *ctx) int wolfSSL_EVP_CIPHER_CTX_reset(WOLFSSL_EVP_CIPHER_CTX *ctx) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); if (ctx != NULL) { WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_reset"); @@ -1688,7 +1725,7 @@ int wolfSSL_EVP_DecryptFinal_legacy(WOLFSSL_EVP_CIPHER_CTX *ctx, { int fl; if (ctx == NULL || out == NULL || outl == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; WOLFSSL_ENTER("wolfSSL_EVP_DecryptFinal_legacy"); if (ctx->block_size == 1) { @@ -1727,7 +1764,7 @@ int wolfSSL_EVP_DecryptFinal_legacy(WOLFSSL_EVP_CIPHER_CTX *ctx, int wolfSSL_EVP_CIPHER_CTX_block_size(const WOLFSSL_EVP_CIPHER_CTX *ctx) { - if (ctx == NULL) return BAD_FUNC_ARG; + if (ctx == NULL) return WOLFSSL_FAILURE; switch (ctx->cipherType) { #if !defined(NO_AES) || !defined(NO_DES3) || defined(WOLFSSL_SM4) #if !defined(NO_AES) @@ -2009,7 +2046,7 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) { if (cipher == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; switch (cipherType(cipher)) { #if !defined(NO_AES) @@ -2269,7 +2306,7 @@ int wolfSSL_EVP_CIPHER_CTX_set_padding(WOLFSSL_EVP_CIPHER_CTX *ctx, int padding) { if (ctx == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; if (padding) { ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_NO_PADDING; } @@ -2281,9 +2318,10 @@ int wolfSSL_EVP_CIPHER_CTX_set_padding(WOLFSSL_EVP_CIPHER_CTX *ctx, int wolfSSL_EVP_add_digest(const WOLFSSL_EVP_MD *digest) { - (void)digest; /* nothing to do */ - return 0; + if (digest == NULL) + return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } @@ -2679,9 +2717,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt(WOLFSSL_EVP_PKEY_CTX* ctx, } if (ret == WOLFSSL_SUCCESS && salt != NULL && saltSz > 0) { - if (ctx->pkey->hkdfSalt != NULL) { - XFREE(ctx->pkey->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); - } + XFREE(ctx->pkey->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); ctx->pkey->hkdfSalt = (byte*)XMALLOC((size_t)saltSz, NULL, DYNAMIC_TYPE_SALT); if (ctx->pkey->hkdfSalt == NULL) { @@ -2716,9 +2752,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_key(WOLFSSL_EVP_PKEY_CTX* ctx, } if (ret == WOLFSSL_SUCCESS) { - if (ctx->pkey->hkdfKey != NULL) { - XFREE(ctx->pkey->hkdfKey, NULL, DYNAMIC_TYPE_KEY); - } + XFREE(ctx->pkey->hkdfKey, NULL, DYNAMIC_TYPE_KEY); ctx->pkey->hkdfKey = (byte*)XMALLOC((size_t)keySz, NULL, DYNAMIC_TYPE_KEY); if (ctx->pkey->hkdfKey == NULL) { @@ -3110,7 +3144,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, if (!ctx->pkey->dsa) return WOLFSSL_FAILURE; bytes = wolfSSL_BN_num_bytes(ctx->pkey->dsa->q); - if (bytes == WOLFSSL_FAILURE) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) return WOLFSSL_FAILURE; bytes *= 2; if (!sig) { @@ -3123,7 +3157,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, /* wolfSSL_DSA_do_sign() can return WOLFSSL_FATAL_ERROR */ if (ret != WOLFSSL_SUCCESS) return ret; - if (bytes == WOLFSSL_FAILURE) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) return WOLFSSL_FAILURE; *siglen = (size_t)bytes; return WOLFSSL_SUCCESS; @@ -3404,14 +3438,14 @@ int wolfSSL_EVP_PKEY_keygen_init(WOLFSSL_EVP_PKEY_CTX *ctx) int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY **ppkey) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); int ownPkey = 0; WOLFSSL_EVP_PKEY* pkey; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_keygen"); if (ctx == NULL || ppkey == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } pkey = *ppkey; @@ -3421,7 +3455,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, ctx->pkey->type != EVP_PKEY_RSA && ctx->pkey->type != EVP_PKEY_DH)) { WOLFSSL_MSG("Key not set or key type not supported"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } pkey = wolfSSL_EVP_PKEY_new(); if (pkey == NULL) { @@ -3802,14 +3836,15 @@ static int DH_param_check(WOLFSSL_DH* dh_key) dh_key->q != NULL) { if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) == - WOLFSSL_FAILURE) { + wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) + { WOLFSSL_MSG("BN_mod_exp failed"); ret = WOLFSSL_FAILURE; } else if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_is_one(num1) == WOLFSSL_FAILURE) { + wolfSSL_BN_is_one(num1) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("dh_key->g is not suitable generator"); ret = WOLFSSL_FAILURE; } @@ -3957,7 +3992,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, (void)siglen; WOLFSSL_ENTER("EVP_SignFinal"); - if (ctx == NULL) + if (ctx == NULL || sigret == NULL || siglen == NULL || pkey == NULL) return WOLFSSL_FAILURE; ret = wolfSSL_EVP_DigestFinal(ctx, md, &mdsize); @@ -3989,15 +4024,32 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, if (ret != WOLFSSL_SUCCESS) return ret; bytes = wolfSSL_BN_num_bytes(pkey->dsa->q); - if (bytes == WOLFSSL_FAILURE || (int)*siglen < bytes * 2) + if (bytes == WC_NO_ERR_TRACE(WOLFSSL_FAILURE) || + (int)*siglen < bytes * 2) + { return WOLFSSL_FAILURE; + } *siglen = (unsigned int)(bytes * 2); return WOLFSSL_SUCCESS; } #endif - case EVP_PKEY_EC: - WOLFSSL_MSG("not implemented"); - FALL_THROUGH; +#ifdef HAVE_ECC + case EVP_PKEY_EC: { + WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_ECDSA_do_sign(md, (int)mdsize, + pkey->ecc); + if (ecdsaSig == NULL) + return WOLFSSL_FAILURE; + ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); + if (ret <= 0 || ret > (int)*siglen) + return WOLFSSL_FAILURE; + ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sigret); + wolfSSL_ECDSA_SIG_free(ecdsaSig); + if (ret <= 0 || ret > (int)*siglen) + return WOLFSSL_FAILURE; + *siglen = (unsigned int)ret; + return WOLFSSL_SUCCESS; + } +#endif default: break; } @@ -4055,7 +4107,8 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, if (ctx == NULL) return WOLFSSL_FAILURE; WOLFSSL_ENTER("EVP_VerifyFinal"); ret = wolfSSL_EVP_DigestFinal(ctx, md, &mdsize); - if (ret <= 0) return ret; + if (ret <= 0) + return ret; (void)sig; (void)siglen; @@ -4072,9 +4125,19 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, (unsigned int)siglen, pkey->rsa); } #endif /* NO_RSA */ - +#ifdef HAVE_ECC + case EVP_PKEY_EC: { + WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( + NULL, (const unsigned char **)&sig, (long)siglen); + if (ecdsaSig == NULL) + return WOLFSSL_FAILURE; + ret = wolfSSL_ECDSA_do_verify(md, (int)mdsize, ecdsaSig, + pkey->ecc); + wolfSSL_ECDSA_SIG_free(ecdsaSig); + return ret; + } +#endif case EVP_PKEY_DSA: - case EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -4085,9 +4148,10 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, int wolfSSL_EVP_add_cipher(const WOLFSSL_EVP_CIPHER *cipher) { - (void)cipher; /* nothing to do */ - return 0; + if (cipher == NULL) + return WOLFSSL_FAILURE; + return WOLFSSL_SUCCESS; } @@ -4144,7 +4208,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_CMAC_key(WOLFSSL_ENGINE* e, } ret = wolfSSL_CMAC_Init(ctx, priv, len, cipher, e); - if (ret == WOLFSSL_FAILURE) { + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { wolfSSL_CMAC_CTX_free(ctx); WOLFSSL_LEAVE("wolfSSL_EVP_PKEY_new_CMAC_key", 0); return NULL; @@ -4286,7 +4350,7 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, } type = wolfSSL_EVP_get_digestbynid(default_digest); if (type == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } } @@ -4478,7 +4542,7 @@ int wolfSSL_EVP_DigestSignInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_ENTER("EVP_DigestSignInit"); if (ctx == NULL || pkey == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfSSL_evp_digest_pk_init(ctx, pctx, type, e, pkey); } @@ -4490,7 +4554,7 @@ int wolfSSL_EVP_DigestSignUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *d, WOLFSSL_ENTER("EVP_DigestSignUpdate"); if (ctx == NULL || d == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfssl_evp_digest_pk_update(ctx, d, cnt); } @@ -4500,7 +4564,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, { unsigned char digest[WC_MAX_DIGEST_SIZE]; unsigned int hashLen; - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("EVP_DigestSignFinal"); @@ -4603,7 +4667,7 @@ int wolfSSL_EVP_DigestVerifyInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_ENTER("EVP_DigestVerifyInit"); if (ctx == NULL || type == NULL || pkey == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfSSL_evp_digest_pk_init(ctx, pctx, type, e, pkey); } @@ -4615,7 +4679,7 @@ int wolfSSL_EVP_DigestVerifyUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *d, WOLFSSL_ENTER("EVP_DigestVerifyUpdate"); if (ctx == NULL || d == NULL) - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; return wolfssl_evp_digest_pk_update(ctx, d, (unsigned int)cnt); } @@ -4756,7 +4820,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, int wolfSSL_EVP_read_pw_string(char* buf, int bufSz, const char* banner, int v) { printf("%s", banner); - if (XGETPASSWD(buf, bufSz) == WOLFSSL_FAILURE) { + if (XGETPASSWD(buf, bufSz) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { return -1; } (void)v; /* fgets always sanity checks size of input vs buffer */ @@ -5913,7 +5977,7 @@ void wolfSSL_EVP_init(void) int wolfSSL_EVP_CIPHER_CTX_ctrl(WOLFSSL_EVP_CIPHER_CTX *ctx, int type, \ int arg, void *ptr) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #if defined(HAVE_AESGCM) || (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) #ifndef WC_NO_RNG WC_RNG rng; @@ -6298,15 +6362,11 @@ void wolfSSL_EVP_init(void) ctx->keyLen = 0; #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA) || \ defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) - if (ctx->authBuffer) { - XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authBuffer = NULL; - } + XFREE(ctx->authBuffer, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authBuffer = NULL; ctx->authBufferLen = 0; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->authIvGenEnable = 0; ctx->authIncIv = 0; @@ -6361,7 +6421,7 @@ void wolfSSL_EVP_init(void) } ret = wolfSSL_EVP_get_hashinfo(md, &hashType, NULL); - if (ret == WOLFSSL_FAILURE) + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) goto end; ret = wc_PBKDF1_ex(key, (int)info->keySz, iv, (int)info->ivSz, data, sz, @@ -6428,10 +6488,8 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -6520,7 +6578,7 @@ void wolfSSL_EVP_init(void) static int EvpCipherAesGCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); #ifndef WOLFSSL_AESGCM_STREAM /* No destination means only AAD. */ @@ -6635,10 +6693,8 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -6714,7 +6770,7 @@ void wolfSSL_EVP_init(void) static int EvpCipherAesCCM(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -6786,10 +6842,8 @@ void wolfSSL_EVP_init(void) return WOLFSSL_FAILURE; } - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; ctx->block_size = AES_BLOCK_SIZE; @@ -7821,10 +7875,8 @@ void wolfSSL_EVP_init(void) ctx->ivSz = GCM_NONCE_MID_SZ; } ctx->authTagSz = SM4_BLOCK_SIZE; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7853,10 +7905,8 @@ void wolfSSL_EVP_init(void) ctx->ivSz = GCM_NONCE_MID_SZ; } ctx->authTagSz = SM4_BLOCK_SIZE; - if (ctx->authIn) { - XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); - ctx->authIn = NULL; - } + XFREE(ctx->authIn, NULL, DYNAMIC_TYPE_OPENSSL); + ctx->authIn = NULL; ctx->authInSz = 0; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -8224,7 +8274,7 @@ void wolfSSL_EVP_init(void) int wolfSSL_EVP_Cipher(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src, word32 len) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_EVP_Cipher"); @@ -9001,7 +9051,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) /* Get size of DER buffer only */ if (havePublic && !havePrivate) { ret = wc_DhPubKeyToDer(dhkey, NULL, &derSz); - } else if (havePrivate && !havePublic) { + } else if (havePrivate) { ret = wc_DhPrivKeyToDer(dhkey, NULL, &derSz); } else { ret = wc_DhParamsToDer(dhkey,NULL,&derSz); @@ -9021,7 +9071,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) /* Fill DER buffer */ if (havePublic && !havePrivate) { ret = wc_DhPubKeyToDer(dhkey, derBuf, &derSz); - } else if (havePrivate && !havePublic) { + } else if (havePrivate) { ret = wc_DhPrivKeyToDer(dhkey, derBuf, &derSz); } else { ret = wc_DhParamsToDer(dhkey,derBuf,&derSz); @@ -9304,7 +9354,7 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_ripemd160(void) int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) { - int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); @@ -9329,7 +9379,7 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) } } else { - ret = BAD_FUNC_ARG; + ret = WOLFSSL_FAILURE; } WOLFSSL_LEAVE("wolfSSL_EVP_MD_pkey_type", ret); @@ -9720,7 +9770,12 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKCS82PKEY(const WOLFSSL_PKCS8_PRIV_KEY_INFO* p8) /* this function just casts and returns pointer */ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_EVP_PKEY2PKCS8(const WOLFSSL_EVP_PKEY* pkey) { - return (WOLFSSL_PKCS8_PRIV_KEY_INFO*)pkey; + if (pkey == NULL || pkey->pkey.ptr == NULL) { + return NULL; + } + + return wolfSSL_d2i_PrivateKey_EVP(NULL, (unsigned char**)&pkey->pkey.ptr, + pkey->pkey_sz); } #endif @@ -9873,10 +9928,24 @@ static const struct alias { const char *alias; } digest_alias_tbl[] = { - {"MD4", "ssl3-md4"}, - {"MD5", "ssl3-md5"}, - {"SHA1", "ssl3-sha1"}, + {"MD4", "md4"}, + {"MD5", "md5"}, + {"SHA1", "sha1"}, {"SHA1", "SHA"}, + {"SHA224", "sha224"}, + {"SHA256", "sha256"}, + {"SHA384", "sha384"}, + {"SHA512", "sha512"}, + {"SHA512_224", "sha512_224"}, + {"SHA3_224", "sha3_224"}, + {"SHA3_256", "sha3_256"}, + {"SHA3_384", "sha3_384"}, + {"SHA3_512", "sha3_512"}, + {"SM3", "sm3"}, + {"BLAKE2B512", "blake2b512"}, + {"BLAKE2S256", "blake2s256"}, + {"SHAKE128", "shake128"}, + {"SHAKE256", "shake256"}, { NULL, NULL} }; @@ -10205,7 +10274,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) * @param n message digest type name * @return alias name, otherwise NULL */ - static const char* hasAliasName(const char* n) + static const char* getMdAliasName(const char* n) { const char* aliasnm = NULL; @@ -10236,23 +10305,15 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) { struct do_all_md *md = (struct do_all_md*)arg; - const struct s_ent *ent; - /* sanity check */ if (md == NULL || nm == NULL || md->fn == NULL || nm->type != WOLFSSL_OBJ_NAME_TYPE_MD_METH) return; - /* loop all md */ - for (ent = md_tbl; ent->name != NULL; ent++){ - /* check if the md has alias */ - if(hasAliasName(ent->name) != NULL) { - md->fn(NULL, ent->name, ent->name, md->arg); - } - else { - md->fn(ent->name, ent->name, NULL, md->arg); - } - } + if (nm->alias) + md->fn(NULL, nm->name, nm->data, md->arg); + else + md->fn((const EVP_MD *)nm->data, nm->name, NULL, md->arg); } /* call md_do_all function to do all md algorithm via a callback function @@ -10287,11 +10348,30 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (!fn) return; - objnm.type = type; - switch(type) { case WOLFSSL_OBJ_NAME_TYPE_MD_METH: - fn(&objnm, arg); + { + const struct s_ent *ent; + /* loop all md */ + for (ent = md_tbl; ent->name != NULL; ent++){ + XMEMSET(&objnm, 0, sizeof(objnm)); + + /* populate objnm with info about the md */ + objnm.type = WOLFSSL_OBJ_NAME_TYPE_MD_METH; + objnm.name = ent->name; + objnm.data = (const char*) + wolfSSL_EVP_get_digestbyname(ent->name); + fn(&objnm, arg); + + /* check if the md has alias and also call fn with it */ + objnm.name = getMdAliasName(ent->name); + if (objnm.name != NULL) { + objnm.alias |= WOLFSSL_OBJ_NAME_ALIAS; + objnm.data = ent->name; + fn(&objnm, arg); + } + } + } break; case WOLFSSL_OBJ_NAME_TYPE_CIPHER_METH: case WOLFSSL_OBJ_NAME_TYPE_PKEY_METH: @@ -10420,20 +10500,17 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* md) { int ret = WOLFSSL_SUCCESS; + #ifdef WOLFSSL_ASYNC_CRYPT + wc_static_assert(WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV)); + #endif WOLFSSL_ENTER("EVP_DigestInit"); if (ctx == NULL) { - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } - - #ifdef WOLFSSL_ASYNC_CRYPT - /* compile-time validation of ASYNC_CTX_SIZE */ - typedef char async_test[WC_ASYNC_DEV_SIZE >= sizeof(WC_ASYNC_DEV) ? - 1 : -1]; - (void)sizeof(async_test); - #endif + wolfSSL_EVP_MD_CTX_init(ctx); /* Set to 0 if no match */ ctx->macType = EvpMd2MacType(md); @@ -10522,7 +10599,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) #endif { ctx->macType = WC_HASH_TYPE_NONE; - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } return ret; @@ -10532,7 +10609,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) int wolfSSL_EVP_DigestUpdate(WOLFSSL_EVP_MD_CTX* ctx, const void* data, size_t sz) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestUpdate"); @@ -10660,7 +10737,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, unsigned int* s) { - int ret = WOLFSSL_FAILURE; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestFinal"); @@ -10839,7 +10916,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #ifndef NO_SHA @@ -10905,7 +10982,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) } else #endif - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) @@ -10914,7 +10991,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("No md type arg"); - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #ifndef NO_SHA @@ -10990,7 +11067,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) } #endif - return BAD_FUNC_ARG; + return WOLFSSL_FAILURE; } #endif /* OPENSSL_EXTRA || HAVE_CURL */ @@ -11108,18 +11185,12 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #ifdef HAVE_HKDF case EVP_PKEY_HKDF: - if (key->hkdfSalt != NULL) { - XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); - key->hkdfSalt = NULL; - } - if (key->hkdfKey != NULL) { - XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); - key->hkdfKey = NULL; - } - if (key->hkdfInfo != NULL) { - XFREE(key->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); - key->hkdfInfo = NULL; - } + XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); + key->hkdfSalt = NULL; + XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); + key->hkdfKey = NULL; + XFREE(key->hkdfInfo, NULL, DYNAMIC_TYPE_INFO); + key->hkdfInfo = NULL; key->hkdfSaltSz = 0; key->hkdfKeySz = 0; key->hkdfInfoSz = 0; @@ -11279,7 +11350,7 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, int indent, int bitlen, ASN1_PCTX* pctx) { byte buff[8] = { 0 }; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 inOutIdx = 0; word32 nSz; /* size of modulus */ word32 eSz; /* size of public exponent */ @@ -11598,10 +11669,8 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, res = wolfSSL_BIO_write(out, "\n", 1) > 0; } - if (pub != NULL) { - XFREE(pub, NULL, DYNAMIC_TYPE_ECC_BUFFER); - pub = NULL; - } + XFREE(pub, NULL, DYNAMIC_TYPE_ECC_BUFFER); + pub = NULL; wc_ecc_free(key); mp_free(a); @@ -11633,7 +11702,7 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, byte buff[8] = { 0 }; int length; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 inOutIdx = 0; word32 oid; byte tagFound; @@ -11851,7 +11920,7 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, { byte buff[8] = { 0 }; - int res = WOLFSSL_FAILURE; + int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); word32 length; word32 inOutIdx; word32 oid; diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index 390b21b..c62ef35 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -1,6 +1,6 @@ /* internal.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -1329,6 +1329,10 @@ enum { #endif #endif +#ifndef MAX_PSK_KEY_LEN + #define MAX_PSK_KEY_LEN 64 +#endif + #ifndef MAX_EARLY_DATA_SZ /* maximum early data size */ #define MAX_EARLY_DATA_SZ 4096 @@ -1421,15 +1425,15 @@ enum { #define ENCRYPT_BASE_BITS (256 * 2) #else /* No secret from public key operation but PSK key plus length used. */ - #define ENCRYPT_BASE_BITS ((MAX_PSK_ID_LEN + 2) * 8) + #define ENCRYPT_BASE_BITS ((MAX_PSK_KEY_LEN + 2) * 8) #endif #ifdef WOLFSSL_DTLS_CID #ifndef DTLS_CID_MAX_SIZE -/* DTLSv1.3 parsing code copies the record header in a static buffer to decrypt +/* DTLS parsing code copies the record header in a static buffer to decrypt * the record. Increasing the CID max size does increase also this buffer, * impacting on per-session runtime memory footprint. */ -#define DTLS_CID_MAX_SIZE 2 +#define DTLS_CID_MAX_SIZE 10 #endif #else #undef DTLS_CID_MAX_SIZE @@ -1440,6 +1444,30 @@ enum { #error "Max size for DTLS CID is 255 bytes" #endif +/* Record Payload Protection Section 5 + * https://www.rfc-editor.org/rfc/rfc9146.html#section-5 */ +#define WOLFSSL_TLS_HMAC_CID_INNER_SZ \ + (8 + /* seq_num_placeholder */ \ + 1 + /* tls12_cid */ \ + 1 + /* cid_length */ \ + 1 + /* tls12_cid */ \ + 2 + /* DTLSCiphertext.version */ \ + 2 + /* epoch */ \ + 6 + /* sequence_number */ \ + DTLS_CID_MAX_SIZE + /* cid */ \ + 2) /* length_of_DTLSInnerPlaintext */ + +#define WOLFSSL_TLS_AEAD_CID_AAD_SZ \ + (8 + /* seq_num_placeholder */ \ + 1 + /* tls12_cid */ \ + 1 + /* cid_length */ \ + 1 + /* tls12_cid */ \ + 2 + /* DTLSCiphertext.version */ \ + 2 + /* epoch */ \ + 6 + /* sequence_number */ \ + DTLS_CID_MAX_SIZE + /* cid */ \ + 2) /* length_of_DTLSInnerPlaintext */ + #ifndef MAX_TICKET_AGE_DIFF /* maximum ticket age difference in seconds, 10 seconds */ #define MAX_TICKET_AGE_DIFF 10 @@ -1561,7 +1589,7 @@ enum Misc { * hybridization with other algs. */ #else #ifndef NO_PSK - ENCRYPT_LEN = (ENCRYPT_BASE_BITS / 8) + MAX_PSK_ID_LEN + 2, + ENCRYPT_LEN = (ENCRYPT_BASE_BITS / 8) + MAX_PSK_KEY_LEN + 2, #else ENCRYPT_LEN = (ENCRYPT_BASE_BITS / 8), #endif @@ -1633,6 +1661,7 @@ enum Misc { #endif HANDSHAKE_HEADER_SZ = 4, /* type + length(3) */ + DTLS13_HANDSHAKE_HEADER_SZ = 12, /* sizeof(Dtls13HandshakeHeader) */ RECORD_HEADER_SZ = 5, /* type + version + len(2) */ CERT_HEADER_SZ = 3, /* always 3 bytes */ REQ_HEADER_SZ = 2, /* cert request header sz */ @@ -1645,6 +1674,7 @@ enum Misc { DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */ DTLS_RECORD_HEADER_SZ = 13, /* normal + epoch(2) + seq_num(6) */ + DTLS12_CID_OFFSET = 11, DTLS_UNIFIED_HEADER_MIN_SZ = 2, /* flags + seq_number(2) + length(2) + CID */ DTLS_RECVD_RL_HEADER_MAX_SZ = 5 + DTLS_CID_MAX_SIZE, @@ -1745,6 +1775,7 @@ enum Misc { CHACHA20_IMP_IV_SZ = 12, /* Size of ChaCha20 AEAD implicit IV */ CHACHA20_NONCE_SZ = 12, /* Size of ChacCha20 nonce */ CHACHA20_OLD_OFFSET = 4, /* Offset for seq # in old poly1305 */ + CHACHA20_OFFSET = 4, /* Offset for seq # in poly1305 */ /* For any new implicit/explicit IV size adjust AEAD_MAX_***_SZ */ @@ -1828,7 +1859,6 @@ enum Misc { DTLS_TIMEOUT_MULTIPLIER = 2, /* default timeout multiplier for DTLS recv */ NULL_TERM_LEN = 1, /* length of null '\0' termination character */ - MAX_PSK_KEY_LEN = 64, /* max psk key supported */ MIN_PSK_ID_LEN = 6, /* min length of identities */ MIN_PSK_BINDERS_LEN = 33, /* min length of binders */ @@ -1855,6 +1885,14 @@ enum Misc { READ_PROTO = 0 /* reading a protocol message */ }; + +/* Size of the data to authenticate */ +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#define AEAD_AUTH_DATA_SZ WOLFSSL_TLS_AEAD_CID_AAD_SZ +#else +#define AEAD_AUTH_DATA_SZ 13 +#endif + #define WOLFSSL_NAMED_GROUP_IS_FFHDE(group) \ (MIN_FFHDE_GROUP <= (group) && (group) <= MAX_FFHDE_GROUP) #ifdef WOLFSSL_HAVE_KYBER @@ -1986,6 +2024,22 @@ enum Misc { #define MAX_CHAIN_DEPTH 9 #endif +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ + defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + #if !defined(HAVE_OCSP) + #error OCSP Stapling and Stapling V2 needs OCSP. Please define HAVE_OCSP. + #endif +#endif + +/* Max certificate extensions in TLS1.3 */ +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) + /* Number of extensions to set each OCSP response */ + #define MAX_CERT_EXTENSIONS (1 + MAX_CHAIN_DEPTH) +#else + /* Only empty extensions */ + #define MAX_CERT_EXTENSIONS 1 +#endif + /* max size of a certificate message payload */ /* assumes MAX_CHAIN_DEPTH number of certificates at 2kb per certificate */ #ifndef MAX_CERTIFICATE_SZ @@ -2033,18 +2087,9 @@ enum Misc { #define MAX_ENCRYPT_SZ ENCRYPT_LEN -/* A static check to assert a relation between x and y */ -#define WOLFSSL_ASSERT_TEST(x, y, op) do { \ - typedef char _args_test_[(x) op (y) ? 1 : -1]; \ - (void)sizeof(_args_test_); \ -} while(0) - -#define WOLFSSL_ASSERT_EQ(x, y) WOLFSSL_ASSERT_TEST(x, y, ==) +#define WOLFSSL_ASSERT_EQ(x, y) wc_static_assert((x) == (y)) -#define WOLFSSL_ASSERT_SIZEOF_TEST(x, y, op) \ - WOLFSSL_ASSERT_TEST(sizeof((x)), sizeof((y)), op) - -#define WOLFSSL_ASSERT_SIZEOF_GE(x, y) WOLFSSL_ASSERT_SIZEOF_TEST(x, y, >=) +#define WOLFSSL_ASSERT_SIZEOF_GE(x, y) wc_static_assert(sizeof(x) >= sizeof(y)) /* states. Adding state before HANDSHAKE_DONE will break session importing */ enum states { @@ -2211,9 +2256,13 @@ WOLFSSL_LOCAL void FreeAsyncCtx(WOLFSSL* ssl, byte freeAsync); WOLFSSL_LOCAL void FreeKeyExchange(WOLFSSL* ssl); WOLFSSL_LOCAL void FreeSuites(WOLFSSL* ssl); WOLFSSL_LOCAL int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz); -WOLFSSL_LOCAL int MatchDomainName(const char* pattern, int len, const char* str, word32 strLen); -#ifndef NO_CERTS -WOLFSSL_LOCAL int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen, int* checkCN); +WOLFSSL_LOCAL int MatchDomainName(const char* pattern, int len, + const char* str, word32 strLen, + unsigned int flags); +#if !defined(NO_CERTS) && !defined(NO_ASN) +WOLFSSL_LOCAL int CheckForAltNames(DecodedCert* dCert, const char* domain, + word32 domainLen, int* checkCN, + unsigned int flags); WOLFSSL_LOCAL int CheckIPAddr(DecodedCert* dCert, const char* ipasc); WOLFSSL_LOCAL void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType); #endif @@ -2235,7 +2284,7 @@ WOLFSSL_LOCAL int ALPN_Select(WOLFSSL* ssl); #endif WOLFSSL_LOCAL int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, - word16 sz); /* needed by sniffer */ + word16 sz, byte type); /* needed by sniffer */ WOLFSSL_LOCAL int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, word16 sz); /* needed by sniffer */ @@ -2614,6 +2663,8 @@ struct WOLFSSL_CERT_MANAGER { #endif CallbackCACache caCacheCallback; /* CA cache addition callback */ CbMissingCRL cbMissingCRL; /* notify thru cb of missing crl */ + crlErrorCb crlCb; /* Allow user to override error */ + void* crlCbCtx; CbOCSPIO ocspIOCb; /* I/O callback for OCSP lookup */ CbOCSPRespFree ocspRespFreeCb; /* Frees OCSP Response from IO Cb */ wolfSSL_Mutex caLock; /* CA list lock */ @@ -2647,8 +2698,7 @@ struct WOLFSSL_CERT_MANAGER { #ifdef HAVE_DILITHIUM short minDilithiumKeySz; /* minimum allowed Dilithium key size */ #endif -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB wc_UnknownExtCallback unknownExtCallback; #endif }; @@ -2673,7 +2723,9 @@ typedef struct ProcPeerCertArgs { #ifdef WOLFSSL_TLS13 buffer* exts; /* extensions */ #endif +#ifndef NO_ASN DecodedCert* dCert; +#endif word32 idx; word32 begin; int totalCerts; /* number of certs in certs buffer */ @@ -2704,6 +2756,8 @@ WOLFSSL_LOCAL int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, WOLFSSL_LOCAL void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store, WOLFSSL* ssl, void* heap, int x509Free); #endif /* !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) */ +WOLFSSL_LOCAL int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, + byte *buf, word32 bufLen, int type); #endif /* !defined NO_CERTS */ /* wolfSSL Sock Addr */ @@ -2743,6 +2797,70 @@ typedef struct WOLFSSL_DTLS_PEERSEQ { #endif } WOLFSSL_DTLS_PEERSEQ; +struct WOLFSSL_BIO { + WOLFSSL_BUF_MEM* mem_buf; + WOLFSSL_BIO_METHOD* method; + WOLFSSL_BIO* prev; /* previous in chain */ + WOLFSSL_BIO* next; /* next in chain */ + WOLFSSL_BIO* pair; /* BIO paired with */ + void* heap; /* user heap hint */ + union { + byte* mem_buf_data; +#ifndef WOLFCRYPT_ONLY + WOLFSSL* ssl; + WOLFSSL_EVP_MD_CTX* md_ctx; +#endif +#ifndef NO_FILESYSTEM + XFILE fh; +#endif + } ptr; + void* usrCtx; /* user set pointer */ + char* ip; /* IP address for wolfIO_TcpConnect */ + word16 port; /* Port for wolfIO_TcpConnect */ + char* infoArg; /* BIO callback argument */ + wolf_bio_info_cb infoCb; /* BIO callback */ + int wrSz; /* write buffer size (mem) */ + int wrSzReset; /* First buffer size (mem) - read ONLY data */ + int wrIdx; /* current index for write buffer */ + int rdIdx; /* current read index */ + int readRq; /* read request */ + union { + SOCKET_T fd; + size_t length; + } num; + int eof; /* eof flag */ + int flags; + byte type; /* method type */ + byte init:1; /* bio has been initialized */ + byte shutdown:1; /* close flag */ + byte connected:1; /* connected state, for datagram BIOs -- as for + * struct WOLFSSL_DTLS_CTX, when set, sendto and + * recvfrom leave the peer_addr unchanged. */ +#ifdef WOLFSSL_HAVE_BIO_ADDR + union WOLFSSL_BIO_ADDR peer_addr; /* for datagram BIOs, the socket address stored + * with BIO_CTRL_DGRAM_CONNECT, + * BIO_CTRL_DGRAM_SET_CONNECTED, or + * BIO_CTRL_DGRAM_SET_PEER, or stored when a + * packet was received on an unconnected BIO. */ +#endif + +#if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_BIO_NO_FLOW_STATS) + #define WOLFSSL_BIO_HAVE_FLOW_STATS + word64 bytes_read; + word64 bytes_written; +#endif + +#ifdef HAVE_EX_DATA + WOLFSSL_CRYPTO_EX_DATA ex_data; +#endif +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) + wolfSSL_Ref ref; +#endif +}; + +#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(OPENSSL_EXTRA) +WOLFSSL_LOCAL socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr); +#endif #define MAX_WRITE_IV_SZ 16 /* max size of client/server write_IV */ @@ -2804,8 +2922,8 @@ typedef struct Keys { byte encryptionOn; /* true after change cipher spec */ byte decryptedCur; /* only decrypt current record once */ #ifdef WOLFSSL_TLS13 - byte updateResponseReq:1; /* KeyUpdate response from peer required. */ - byte keyUpdateRespond:1; /* KeyUpdate is to be responded to. */ + byte updateResponseReq; /* KeyUpdate response from peer required. */ + byte keyUpdateRespond; /* KeyUpdate is to be responded to. */ #endif #ifdef WOLFSSL_RENESAS_TSIP_TLS @@ -2889,9 +3007,6 @@ typedef enum { TLSX_EXTENDED_MASTER_SECRET = TLSXT_EXTENDED_MASTER_SECRET, TLSX_SESSION_TICKET = TLSXT_SESSION_TICKET, #ifdef WOLFSSL_TLS13 - #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) - TLSX_PRE_SHARED_KEY = TLSXT_PRE_SHARED_KEY, - #endif #ifdef WOLFSSL_EARLY_DATA TLSX_EARLY_DATA = TLSXT_EARLY_DATA, #endif @@ -2911,7 +3026,6 @@ typedef enum { #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) TLSX_SIGNATURE_ALGORITHMS_CERT = TLSXT_SIGNATURE_ALGORITHMS_CERT, #endif - TLSX_KEY_SHARE = TLSXT_KEY_SHARE, #if defined(WOLFSSL_DTLS_CID) TLSX_CONNECTION_ID = TLSXT_CONNECTION_ID, #endif /* defined(WOLFSSL_DTLS_CID) */ @@ -2922,6 +3036,12 @@ typedef enum { TLSX_ECH = TLSXT_ECH, #endif #endif +#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) + #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) + TLSX_PRE_SHARED_KEY = TLSXT_PRE_SHARED_KEY, + #endif + TLSX_KEY_SHARE = TLSXT_KEY_SHARE, +#endif #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_DUAL_ALG_CERTS) TLSX_CKS = TLSXT_CKS, #endif @@ -3022,6 +3142,8 @@ WOLFSSL_LOCAL int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, WOLFSSL_LOCAL int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen); + +WOLFSSL_LOCAL void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap); #endif struct TLSX { @@ -3165,10 +3287,11 @@ typedef struct { byte options; WOLFSSL* ssl; union { - OcspRequest ocsp; + OcspRequest ocsp[MAX_CERT_EXTENSIONS]; } request; + word16 requests; #ifdef WOLFSSL_TLS13 - buffer response; + buffer responses[MAX_CERT_EXTENSIONS]; #endif } CertificateStatusRequest; @@ -3177,12 +3300,25 @@ WOLFSSL_LOCAL int TLSX_UseCertificateStatusRequest(TLSX** extensions, #ifndef NO_CERTS WOLFSSL_LOCAL int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap); +WOLFSSL_LOCAL int TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert, + void* heap, int idx); #endif WOLFSSL_LOCAL void* TLSX_CSR_GetRequest(TLSX* extensions); WOLFSSL_LOCAL int TLSX_CSR_ForceRequest(WOLFSSL* ssl); +WOLFSSL_LOCAL word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr, + byte isRequest, + int idx); +WOLFSSL_LOCAL int TLSX_CSR_Write_ex(CertificateStatusRequest* csr, byte* output, + byte isRequest, int idx); +WOLFSSL_LOCAL void* TLSX_CSR_GetRequest_ex(TLSX* extensions, int idx); #endif - +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ + defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) +WOLFSSL_LOCAL int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, + DecodedCert* cert, byte* certData, word32 length, + byte *ctxOwnsRequest); +#endif /** Certificate Status Request v2 - RFC 6961 */ #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 @@ -3334,6 +3470,13 @@ typedef struct InternalTicket { #endif /* OPENSSL_EXTRA */ } InternalTicket; +#ifndef WOLFSSL_TICKET_ENC_CBC_HMAC + #define WOLFSSL_INTERNAL_TICKET_LEN sizeof(InternalTicket) +#else + #define WOLFSSL_INTERNAL_TICKET_LEN \ + (((sizeof(InternalTicket) + 15) / 16) * 16) +#endif + #ifndef WOLFSSL_TICKET_EXTRA_PADDING_SZ #define WOLFSSL_TICKET_EXTRA_PADDING_SZ 32 #endif @@ -3578,6 +3721,8 @@ WOLFSSL_LOCAL void DtlsCIDOnExtensionsParsed(WOLFSSL* ssl); WOLFSSL_LOCAL byte DtlsCIDCheck(WOLFSSL* ssl, const byte* input, word16 inputSize); #endif /* WOLFSSL_DTLS_CID */ +WOLFSSL_LOCAL byte DtlsGetCidTxSize(WOLFSSL* ssl); +WOLFSSL_LOCAL byte DtlsGetCidRxSize(WOLFSSL* ssl); #ifdef OPENSSL_EXTRA enum SetCBIO { @@ -3733,6 +3878,9 @@ struct WOLFSSL_CTX { #endif #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SCTP) byte dtlsSctp:1; /* DTLS-over-SCTP mode */ +#endif +#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) + byte disableECH:1; #endif word16 minProto:1; /* sets min to min available */ word16 maxProto:1; /* sets max to max available */ @@ -4598,10 +4746,34 @@ enum AcceptStateTls13 { TLS13_TICKET_SENT }; +#ifdef WOLFSSL_THREADED_CRYPT + +#include + +typedef struct ThreadCrypt { + Ciphers encrypt; + bufferStatic buffer; + unsigned char nonce[AESGCM_NONCE_SZ]; + unsigned char additional[AEAD_AUTH_DATA_SZ]; + int init; + int offset; + int cryptLen; + int done; + int avail; + int stop; + WOLFSSL_THREAD_SIGNAL signal; + void* signalCtx; +} ThreadCrypt; + +#endif + /* buffers for struct WOLFSSL */ typedef struct Buffers { bufferStatic inputBuffer; bufferStatic outputBuffer; +#ifdef WOLFSSL_THREADED_CRYPT + ThreadCrypt encrypt[WOLFSSL_THREADED_CRYPT_CNT]; +#endif buffer domainName; /* for client check */ buffer clearOutputBuffer; buffer sig; /* signature data */ @@ -4650,7 +4822,7 @@ typedef struct Buffers { /* chain after self, in DER, with leading size for each cert */ #ifdef WOLFSSL_TLS13 int certChainCnt; - DerBuffer* certExts; + DerBuffer* certExts[MAX_CERT_EXTENSIONS]; #endif #endif #ifdef WOLFSSL_SEND_HRR_COOKIE @@ -4755,7 +4927,6 @@ struct Options { word16 tls:1; /* using TLS ? */ word16 tls1_1:1; /* using TLSv1.1+ ? */ word16 tls1_3:1; /* using TLSv1.3+ ? */ - word16 seenUnifiedHdr:1; /* received msg with unified header */ word16 dtls:1; /* using datagrams ? */ #ifdef WOLFSSL_DTLS word16 dtlsStateful:1; /* allow stateful processing ? */ @@ -4764,7 +4935,6 @@ struct Options { word16 isClosed:1; /* if we consider conn closed */ word16 closeNotify:1; /* we've received a close notify */ word16 sentNotify:1; /* we've sent a close notify */ - word16 shutdownDone:1; /* we've completed a shutdown */ word16 usingCompression:1; /* are we using compression */ word16 haveRSA:1; /* RSA available */ word16 haveECC:1; /* ECC available */ @@ -4812,7 +4982,6 @@ struct Options { #endif word16 dtlsUseNonblock:1; /* are we using nonblocking socket */ word16 dtlsHsRetain:1; /* DTLS retaining HS data */ - word16 haveMcast:1; /* using multicast ? */ #ifdef WOLFSSL_SCTP word16 dtlsSctp:1; /* DTLS-over-SCTP mode */ #endif @@ -4865,8 +5034,6 @@ struct Options { word16 buildArgsSet:1; /* buildArgs are set and need to * be free'd */ #endif - word16 buildingMsg:1; /* If set then we need to re-enter the - * handshake logic. */ #ifdef WOLFSSL_DTLS13 word16 dtls13SendMoreAcks:1; /* Send more acks during the * handshake process */ @@ -4884,7 +5051,8 @@ struct Options { word16 useDtlsCID:1; #endif /* WOLFSSL_DTLS_CID */ #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) - word16 useEch:1; + word16 useEch:1; /* Do we have a valid config */ + byte disableECH:1; /* Did the user disable ech */ #endif #ifdef WOLFSSL_SEND_HRR_COOKIE word16 cookieGood:1; @@ -4892,6 +5060,14 @@ struct Options { #if defined(HAVE_DANE) word16 useDANE:1; #endif /* HAVE_DANE */ +#ifdef WOLFSSL_DTLS + byte haveMcast; /* using multicast ? */ +#endif + byte buildingMsg; /* If set then we need to re-enter the + * handshake logic. */ + byte seenUnifiedHdr; /* received msg with unified header */ + byte shutdownDone; /* we've completed a shutdown */ + byte sendKeyUpdate; /* Key Update to write */ #if defined(HAVE_RPK) RpkConfig rpkConfig; RpkState rpkState; @@ -5102,13 +5278,9 @@ struct WOLFSSL_X509 { byte hwType[EXTERNAL_SERIAL_SIZE]; int hwSerialNumSz; byte hwSerialNum[EXTERNAL_SERIAL_SIZE]; -#endif /* WOLFSSL_SEP */ -#if (defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \ - defined (OPENSSL_EXTRA)) && \ - (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) byte certPolicySet; byte certPolicyCrit; -#endif /* (WOLFSSL_SEP || WOLFSSL_QT) && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ +#endif /* WOLFSSL_SEP */ #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) WOLFSSL_STACK* ext_sk; /* Store X509_EXTENSIONS from wolfSSL_X509_get_ext */ WOLFSSL_STACK* ext_sk_full; /* Store X509_EXTENSIONS from wolfSSL_X509_get0_extensions */ @@ -5149,6 +5321,7 @@ struct WOLFSSL_X509 { byte* authKeyId; /* Points into authKeyIdSrc */ byte* authKeyIdSrc; byte* subjKeyId; + WOLFSSL_ASN1_STRING* subjKeyIdStr; byte* extKeyUsageSrc; #ifdef OPENSSL_ALL byte* subjAltNameSrc; @@ -5241,6 +5414,30 @@ struct WOLFSSL_X509 { #endif /* WOLFSSL_DUAL_ALG_CERTS */ }; +#if defined(WOLFSSL_ACERT) +struct WOLFSSL_X509_ACERT { + int version; + int serialSz; + byte serial[EXTERNAL_SERIAL_SIZE]; + WOLFSSL_ASN1_TIME notBefore; + WOLFSSL_ASN1_TIME notAfter; + buffer sig; + int sigOID; +#ifndef NO_CERTS + DerBuffer * derCert; +#endif + void * heap; + int dynamic; /* whether struct was dynamically allocated */ + /* copy of raw Attributes field from */ + byte holderSerial[EXTERNAL_SERIAL_SIZE]; + int holderSerialSz; + DNS_entry * holderEntityName; /* Holder entityName from ACERT */ + DNS_entry * holderIssuerName; /* issuerName from ACERT */ + DNS_entry * AttCertIssuerName; /* AttCertIssuer name from ACERT */ + byte * rawAttr; + word32 rawAttrLen; +}; +#endif /* WOLFSSL_ACERT */ /* record layer header for PlainText, Compressed, and CipherText */ typedef struct RecordLayerHeader { @@ -5376,6 +5573,7 @@ typedef struct BuildMsgArgs { word32 headerSz; word16 size; word32 ivSz; /* TLSv1.1 IV */ + byte type; byte* iv; ALIGN16 byte staticIvBuffer[MAX_IV_SZ]; } BuildMsgArgs; @@ -5509,20 +5707,37 @@ typedef struct Dtls13RecordNumber { } Dtls13RecordNumber; typedef struct Dtls13Rtx { - enum Dtls13RtxFsmState state; +#ifdef WOLFSSL_RW_THREADED + wolfSSL_Mutex mutex; +#endif + enum Dtls13RtxFsmState state; /* Unused? */ Dtls13RtxRecord *rtxRecords; Dtls13RtxRecord **rtxRecordTailPtr; Dtls13RecordNumber *seenRecords; word32 lastRtx; - byte triggeredRtxs; - byte sendAcks:1; - byte retransmit:1; + byte triggeredRtxs; /* Unused? */ + byte sendAcks; + byte retransmit; } Dtls13Rtx; #endif /* WOLFSSL_DTLS13 */ #ifdef WOLFSSL_DTLS_CID -typedef struct CIDInfo CIDInfo; +typedef struct ConnectionID { + byte length; +/* Ignore "nonstandard extension used : zero-sized array in struct/union" + * MSVC warning */ +#ifdef _MSC_VER +#pragma warning(disable: 4200) +#endif + byte id[]; +} ConnectionID; + +typedef struct CIDInfo { + ConnectionID* tx; + ConnectionID* rx; + byte negotiated : 1; +} CIDInfo; #endif /* WOLFSSL_DTLS_CID */ /* The idea is to reuse the context suites object whenever possible to save @@ -5780,10 +5995,10 @@ struct WOLFSSL { /* used to store the message if it needs to be fragmented */ buffer dtls13FragmentsBuffer; byte dtls13SendingFragments:1; - byte dtls13SendingAckOrRtx:1; + byte dtls13SendingAckOrRtx; byte dtls13FastTimeout:1; - byte dtls13WaitKeyUpdateAck:1; - byte dtls13DoKeyUpdate:1; + byte dtls13WaitKeyUpdateAck; + byte dtls13DoKeyUpdate; word32 dtls13MessageLength; word32 dtls13FragOffset; byte dtls13FragHandshakeType; @@ -5883,6 +6098,9 @@ struct WOLFSSL { char* url; #endif #endif +#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) + word32 response_idx; +#endif #endif #ifdef HAVE_NETX NetX_Ctx nxCtx; /* NetX IO Context */ @@ -6102,8 +6320,10 @@ WOLFSSL_API void SSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ int type, WOLFSSL* ssl, int userChain, WOLFSSL_CRL* crl, int verify); + #ifndef NO_ASN WOLFSSL_LOCAL int CheckHostName(DecodedCert* dCert, const char *domainName, - size_t domainNameLen); + size_t domainNameLen, unsigned int flags); + #endif #endif @@ -6130,6 +6350,7 @@ enum ContentType { alert = 21, handshake = 22, application_data = 23, + dtls12_cid = 25, #ifdef WOLFSSL_DTLS13 ack = 26, #endif /* WOLFSSL_DTLS13 */ @@ -6234,6 +6455,9 @@ WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk, WOLFSSL_LOCAL int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len); #endif /* HAVE_SESSION_TICKET */ WOLFSSL_LOCAL int SendData(WOLFSSL* ssl, const void* data, int sz); +#ifdef WOLFSSL_THREADED_CRYPT +WOLFSSL_LOCAL int SendAsyncData(WOLFSSL* ssl); +#endif #ifdef WOLFSSL_TLS13 WOLFSSL_LOCAL int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType); #endif @@ -6386,10 +6610,13 @@ WOLFSSL_LOCAL WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA *rsa, WC_RNG **tmpRNG, #ifndef GetCA WOLFSSL_LOCAL Signer* GetCA(void* vp, byte* hash); #endif - #ifdef WOLFSSL_AKID_NAME + #if defined(WOLFSSL_AKID_NAME) && !defined(GetCAByAKID) WOLFSSL_LOCAL Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz, const byte* serial, word32 serialSz); #endif + #if defined(HAVE_OCSP) && !defined(GetCAByKeyHash) + WOLFSSL_LOCAL Signer* GetCAByKeyHash(void* vp, const byte* keyHash); + #endif #if !defined(NO_SKID) && !defined(GetCAByName) WOLFSSL_LOCAL Signer* GetCAByName(void* cm, byte* hash); #endif @@ -6416,6 +6643,7 @@ WOLFSSL_LOCAL void DoCertFatalAlert(WOLFSSL* ssl, int ret); #endif WOLFSSL_LOCAL int cipherExtraData(WOLFSSL* ssl); +WOLFSSL_LOCAL word32 MacSize(const WOLFSSL* ssl); #ifndef NO_WOLFSSL_CLIENT WOLFSSL_LOCAL int HaveUniqueSessionObj(WOLFSSL* ssl); @@ -6434,6 +6662,10 @@ WOLFSSL_LOCAL int cipherExtraData(WOLFSSL* ssl); WOLFSSL_LOCAL int SendServerHelloDone(WOLFSSL* ssl); #endif /* NO_WOLFSSL_SERVER */ +#ifdef WOLFSSL_TLS13 + WOLFSSL_LOCAL int SendTls13KeyUpdate(WOLFSSL* ssl); +#endif + #ifdef WOLFSSL_DTLS WOLFSSL_LOCAL DtlsMsg* DtlsMsgNew(word32 sz, byte tx, void* heap); WOLFSSL_LOCAL void DtlsMsgDelete(DtlsMsg* item, void* heap); @@ -6512,10 +6744,18 @@ WOLFSSL_LOCAL enum wc_HashType HashAlgoToType(int hashAlgo); WOLFSSL_LOCAL void InitX509(WOLFSSL_X509* x509, int dynamicFlag, void* heap); WOLFSSL_LOCAL void FreeX509(WOLFSSL_X509* x509); + #ifndef NO_ASN WOLFSSL_LOCAL int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert); + #endif #endif +#if defined(WOLFSSL_ACERT) + WOLFSSL_LOCAL int CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509, + DecodedAcert* dAcert); +#endif /* WOLFSSL_ACERT */ + + #ifndef MAX_CIPHER_NAME #define MAX_CIPHER_NAME 50 #endif @@ -6533,7 +6773,7 @@ typedef struct CipherSuiteInfo { #endif byte cipherSuite0; byte cipherSuite; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \ +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \ defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX) byte minor; byte major; @@ -6563,7 +6803,7 @@ WOLFSSL_LOCAL const char* GetCipherNameIana(byte cipherSuite0, byte cipherSuite) WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl); WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl); WOLFSSL_LOCAL int GetCipherSuiteFromName(const char* name, byte* cipherSuite0, - byte* cipherSuite, int* flags); + byte* cipherSuite, byte* major, byte* minor, int* flags); enum encrypt_side { @@ -6572,6 +6812,9 @@ enum encrypt_side { ENCRYPT_AND_DECRYPT_SIDE }; +WOLFSSL_LOCAL int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, + CipherSpecs* specs, int side, void* heap, int devId, WC_RNG* rng, + int tls13); WOLFSSL_LOCAL int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side); /* Set*Internal and Set*External functions */ @@ -6714,6 +6957,7 @@ WOLFSSL_LOCAL int Dtls13RlAddCiphertextHeader(WOLFSSL* ssl, byte* out, word16 length); WOLFSSL_LOCAL int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out, enum ContentType content_type, word16 length); +WOLFSSL_LOCAL int Dtls13MinimumRecordLength(WOLFSSL* ssl); WOLFSSL_LOCAL int Dtls13EncryptRecordNumber(WOLFSSL* ssl, byte* hdr, word16 recordLength); WOLFSSL_LOCAL int Dtls13IsUnifiedHeader(byte header_flags); @@ -6731,6 +6975,7 @@ WOLFSSL_LOCAL int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output, enum HandShakeType msg_type, word32 length); #define EE_MASK (0x3) WOLFSSL_LOCAL int Dtls13FragmentsContinue(WOLFSSL* ssl); +WOLFSSL_LOCAL int DoDtls13KeyUpdateAck(WOLFSSL* ssl); WOLFSSL_LOCAL int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize, word32* processedSize); WOLFSSL_LOCAL int Dtls13ReconstructEpochNumber(WOLFSSL* ssl, byte epochBits, @@ -6863,10 +7108,20 @@ WOLFSSL_LOCAL int CreateCookieExt(const WOLFSSL* ssl, byte* hash, WOLFSSL_LOCAL int TranslateErrorToAlert(int err); #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) -void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, WOLF_STACK_TYPE type); -WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type); +WOLFSSL_LOCAL void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, + WOLF_STACK_TYPE type); +WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type); + +WOLFSSL_LOCAL int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj, + const byte* der, word32 len, int addHdr); #endif +WOLFSSL_LOCAL int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, + word32* keySz); +WOLFSSL_LOCAL int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, + const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key, + word32* keySz); + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/ocsp.h b/src/wolfssl/ocsp.h index 4dff068..f2e234f 100644 --- a/src/wolfssl/ocsp.h +++ b/src/wolfssl/ocsp.h @@ -1,6 +1,6 @@ /* ocsp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -48,6 +48,16 @@ typedef struct OcspEntry WOLFSSL_OCSP_SINGLERESP; typedef struct OcspRequest WOLFSSL_OCSP_ONEREQ; typedef struct OcspRequest WOLFSSL_OCSP_REQUEST; + +typedef struct { + WOLFSSL_BIO *bio; + WOLFSSL_BIO *reqResp; /* First used for request then for response */ + byte* buf; + int bufLen; + int state; + int ioState; + int sent; +} WOLFSSL_OCSP_REQ_CTX; #endif WOLFSSL_LOCAL int InitOCSP(WOLFSSL_OCSP* ocsp, WOLFSSL_CERT_MANAGER* cm); @@ -67,13 +77,11 @@ WOLFSSL_LOCAL int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int resp WOLFSSL_LOCAL int CheckOcspResponder(OcspResponse *bs, DecodedCert *cert, void* vp); -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_APACHE_HTTPD) || defined(HAVE_LIGHTY) - - WOLFSSL_API int wolfSSL_OCSP_resp_find_status(WOLFSSL_OCSP_BASICRESP *bs, - WOLFSSL_OCSP_CERTID *id, int *status, int *reason, - WOLFSSL_ASN1_TIME **revtime, WOLFSSL_ASN1_TIME **thisupd, - WOLFSSL_ASN1_TIME **nextupd); +#ifdef OPENSSL_EXTRA +WOLFSSL_API int wolfSSL_OCSP_resp_find_status(WOLFSSL_OCSP_BASICRESP *bs, + WOLFSSL_OCSP_CERTID *id, int *status, int *reason, + WOLFSSL_ASN1_TIME **revtime, WOLFSSL_ASN1_TIME **thisupd, + WOLFSSL_ASN1_TIME **nextupd); WOLFSSL_API const char *wolfSSL_OCSP_cert_status_str(long s); WOLFSSL_API int wolfSSL_OCSP_check_validity(WOLFSSL_ASN1_TIME* thisupd, WOLFSSL_ASN1_TIME* nextupd, long sec, long maxsec); @@ -132,8 +140,21 @@ WOLFSSL_API int wolfSSL_OCSP_resp_count(WOLFSSL_OCSP_BASICRESP *bs); WOLFSSL_API WOLFSSL_OCSP_SINGLERESP* wolfSSL_OCSP_resp_get0( WOLFSSL_OCSP_BASICRESP *bs, int idx); -#endif -#ifdef OPENSSL_EXTRA +WOLFSSL_API WOLFSSL_OCSP_REQ_CTX* wolfSSL_OCSP_REQ_CTX_new(WOLFSSL_BIO *bio, + int maxline); +WOLFSSL_API void wolfSSL_OCSP_REQ_CTX_free(WOLFSSL_OCSP_REQ_CTX *ctx); +WOLFSSL_API WOLFSSL_OCSP_REQ_CTX *wolfSSL_OCSP_sendreq_new(WOLFSSL_BIO *bio, + const char *path, OcspRequest *req, int maxline); +WOLFSSL_API int wolfSSL_OCSP_REQ_CTX_set1_req(WOLFSSL_OCSP_REQ_CTX *ctx, + OcspRequest *req); +WOLFSSL_API int wolfSSL_OCSP_REQ_CTX_add1_header(WOLFSSL_OCSP_REQ_CTX *ctx, + const char *name, const char *value); +WOLFSSL_API int wolfSSL_OCSP_REQ_CTX_http(WOLFSSL_OCSP_REQ_CTX *ctx, + const char *op, const char *path); +WOLFSSL_API int wolfSSL_OCSP_REQ_CTX_nbio(WOLFSSL_OCSP_REQ_CTX *ctx); +WOLFSSL_API int wolfSSL_OCSP_sendreq_nbio(OcspResponse **presp, + WOLFSSL_OCSP_REQ_CTX *rctx); + WOLFSSL_API int wolfSSL_OCSP_REQUEST_add_ext(OcspRequest* req, WOLFSSL_X509_EXTENSION* ext, int idx); WOLFSSL_API OcspResponse* wolfSSL_OCSP_response_create(int status, @@ -148,7 +169,7 @@ WOLFSSL_API int wolfSSL_OCSP_request_add1_nonce(OcspRequest* req, unsigned char* val, int sz); WOLFSSL_API int wolfSSL_OCSP_check_nonce(OcspRequest* req, WOLFSSL_OCSP_BASICRESP* bs); -#endif +#endif /* OPENSSL_EXTRA */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/aes.h b/src/wolfssl/openssl/aes.h index 38e71ae..2991ff0 100644 --- a/src/wolfssl/openssl/aes.h +++ b/src/wolfssl/openssl/aes.h @@ -1,6 +1,6 @@ /* aes.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/asn1.h b/src/wolfssl/openssl/asn1.h index 12ad369..5fbb726 100644 --- a/src/wolfssl/openssl/asn1.h +++ b/src/wolfssl/openssl/asn1.h @@ -1,6 +1,6 @@ /* asn1.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -38,7 +38,6 @@ #define c2i_ASN1_OBJECT wolfSSL_c2i_ASN1_OBJECT #define V_ASN1_INTEGER 0x02 -#define V_ASN1_OCTET_STRING 0x04 /* tag for ASN1_OCTET_STRING */ #define V_ASN1_NEG 0x100 #define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG) #define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG) @@ -73,6 +72,8 @@ #define ASN1_TIME_set wolfSSL_ASN1_TIME_set #define V_ASN1_EOC 0 +#define V_ASN1_BOOLEAN 1 +#define V_ASN1_OCTET_STRING 4 #define V_ASN1_NULL 5 #define V_ASN1_OBJECT 6 #define V_ASN1_UTF8STRING 12 @@ -111,6 +112,7 @@ WOLFSSL_API WOLFSSL_ASN1_INTEGER *wolfSSL_BN_to_ASN1_INTEGER( const WOLFSSL_BIGNUM *bn, WOLFSSL_ASN1_INTEGER *ai); WOLFSSL_API void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value); +WOLFSSL_API int wolfSSL_ASN1_TYPE_get(const WOLFSSL_ASN1_TYPE *a); WOLFSSL_API int wolfSSL_ASN1_get_object(const unsigned char **in, long *len, int *tag, int *cls, long inLen); @@ -122,50 +124,165 @@ WOLFSSL_API WOLFSSL_ASN1_OBJECT *wolfSSL_c2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a /* IMPLEMENT_ASN1_FUNCTIONS is strictly for external use only. Internally * we don't use this. Some projects use OpenSSL to implement ASN1 types and * this section is only to provide those projects with ASN1 functionality. */ -typedef struct { + +typedef void* (*WolfsslAsn1NewCb)(void); +typedef void (*WolfsslAsn1FreeCb)(void*); +typedef int (*WolfsslAsn1i2dCb)(const void*, unsigned char**); +typedef void* (*WolfsslAsn1d2iCb)(void**, const byte **, long); + +struct WOLFSSL_ASN1_TEMPLATE { + /* Type functions */ + WolfsslAsn1NewCb new_func; + WolfsslAsn1FreeCb free_func; + WolfsslAsn1i2dCb i2d_func; + WolfsslAsn1d2iCb d2i_func; + /* Member info */ size_t offset; /* Offset of this field in structure */ - byte type; /* The type of the member as defined in - * WOLFSSL_ASN1_TYPES */ -} WOLFSSL_ASN1_TEMPLATE; - -typedef struct { - byte type; /* One of the ASN_Tags types */ - const WOLFSSL_ASN1_TEMPLATE *members; /* If SEQUENCE or CHOICE this - * contains the contents */ + /* DER info */ + int tag; + byte first_byte; /* First expected byte. Required for + * IMPLICIT types. */ + byte ex:1; /* explicit, name conflicts with C++ keyword */ + byte sequence:1; +}; + +enum WOLFSSL_ASN1_TYPES { + WOLFSSL_ASN1_SEQUENCE = 0, + WOLFSSL_ASN1_CHOICE, + WOLFSSL_ASN1_OBJECT_TYPE, +}; + +struct WOLFSSL_ASN1_ITEM { + enum WOLFSSL_ASN1_TYPES type; + const struct WOLFSSL_ASN1_TEMPLATE* members; /* If SEQUENCE or CHOICE this + * contains the contents */ size_t mcount; /* Number of members if SEQUENCE * or CHOICE */ size_t size; /* Structure size */ -} WOLFSSL_ASN1_ITEM; + size_t toffset; /* Type offset */ +}; -typedef enum { - WOLFSSL_X509_ALGOR_ASN1 = 0, - WOLFSSL_ASN1_BIT_STRING_ASN1, - WOLFSSL_ASN1_INTEGER_ASN1, -} WOLFSSL_ASN1_TYPES; +typedef struct WOLFSSL_ASN1_TEMPLATE WOLFSSL_ASN1_TEMPLATE; +typedef struct WOLFSSL_ASN1_ITEM WOLFSSL_ASN1_ITEM; -#define ASN1_SEQUENCE(type) \ - static const WOLFSSL_ASN1_TEMPLATE type##_member_data[] +#define ASN1_BIT_STRING_FIRST_BYTE ASN_BIT_STRING +#define ASN1_TFLG_EXPLICIT (0x1 << 0) +#define ASN1_TFLG_SEQUENCE_OF (0x1 << 1) +#define ASN1_TFLG_IMPTAG (0x1 << 2) +#define ASN1_TFLG_EXPTAG (0x1 << 3) -#define ASN1_SIMPLE(type, member, member_type) \ - { OFFSETOF(type, member), \ - WOLFSSL_##member_type##_ASN1 } +#define ASN1_TFLG_TAG_MASK (ASN1_TFLG_IMPTAG|ASN1_TFLG_EXPTAG) + +#define ASN1_ITEM_TEMPLATE(mtype) \ + static const WOLFSSL_ASN1_TEMPLATE mtype##_member_data + +#define ASN1_ITEM_TEMPLATE_END(mtype) \ + ; \ + const WOLFSSL_ASN1_ITEM mtype##_template_data = { \ + WOLFSSL_ASN1_OBJECT_TYPE, \ + &mtype##_member_data, \ + 1, \ + 0, \ + 0 \ + }; + +#define ASN1_SEQUENCE(mtype) \ + static const WOLFSSL_ASN1_TEMPLATE mtype##_member_data[] + +#define ASN1_SEQUENCE_END(mtype) \ + ; \ + const WOLFSSL_ASN1_ITEM mtype##_template_data = { \ + WOLFSSL_ASN1_SEQUENCE, \ + mtype##_member_data, \ + sizeof(mtype##_member_data) / sizeof(WOLFSSL_ASN1_TEMPLATE), \ + sizeof(mtype), \ + 0 \ + }; \ + static WC_MAYBE_UNUSED const byte mtype##_FIRST_BYTE = \ + ASN_CONSTRUCTED | ASN_SEQUENCE; + +/* This is what a ASN1_CHOICE type should look like + * typedef struct { + * int type; + * union { + * ASN1_SOMETHING *opt1; + * ASN1_SOMEOTHER *opt2; + * } value; + * } chname; + */ + +#define ASN1_CHOICE(mtype) \ + static const WOLFSSL_ASN1_TEMPLATE mtype##_member_data[] -#define ASN1_SEQUENCE_END(type) \ +#define ASN1_CHOICE_END(mtype) \ ; \ - const WOLFSSL_ASN1_ITEM type##_template_data = { \ - ASN_SEQUENCE, \ - type##_member_data, \ - sizeof(type##_member_data) / sizeof(WOLFSSL_ASN1_TEMPLATE), \ - sizeof(type) \ + const WOLFSSL_ASN1_ITEM mtype##_template_data = { \ + WOLFSSL_ASN1_CHOICE, \ + mtype##_member_data, \ + sizeof(mtype##_member_data) / sizeof(WOLFSSL_ASN1_TEMPLATE), \ + sizeof(mtype) ,\ + OFFSETOF(mtype, type) \ }; +#define ASN1_TYPE(type, member, tag, first_byte, exp, seq) \ + OFFSETOF(type, member), tag, first_byte, exp, seq + +/* Function callbacks need to be defined immediately otherwise we will + * incorrectly expand the type. Ex: ASN1_INTEGER -> WOLFSSL_ASN1_INTEGER */ + +#define ASN1_SIMPLE(type, member, member_type) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + ASN1_TYPE(type, member, -1, 0, 0, 0) } + +#define ASN1_IMP(type, member, member_type, tag) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + ASN1_TYPE(type, member, tag, member_type##_FIRST_BYTE, 0, 0) } + +#define ASN1_EXP(type, member, member_type, tag) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + ASN1_TYPE(type, member, tag, 0, 1, 0) } + +#define ASN1_SEQUENCE_OF(type, member, member_type) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + ASN1_TYPE(type, member, -1, 0, 0, 1) } + +#define ASN1_EXP_SEQUENCE_OF(type, member, member_type, tag) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + ASN1_TYPE(type, member, tag, 0, 1, 1) } + +#define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, member_type) \ + { (WolfsslAsn1NewCb)member_type##_new, \ + (WolfsslAsn1FreeCb)member_type##_free, \ + (WolfsslAsn1i2dCb)i2d_##member_type, \ + (WolfsslAsn1d2iCb)d2i_##member_type, \ + 0, (flags) & ASN1_TFLG_TAG_MASK ? (tag) : -1, 0, \ + !!((flags) & ASN1_TFLG_EXPLICIT), TRUE } + WOLFSSL_API void *wolfSSL_ASN1_item_new(const WOLFSSL_ASN1_ITEM *tpl); -WOLFSSL_API void wolfSSL_ASN1_item_free(void *val, const WOLFSSL_ASN1_ITEM *tpl); +WOLFSSL_API void wolfSSL_ASN1_item_free(void *obj, + const WOLFSSL_ASN1_ITEM *item); WOLFSSL_API int wolfSSL_ASN1_item_i2d(const void *src, byte **dest, const WOLFSSL_ASN1_ITEM *tpl); +WOLFSSL_API void* wolfSSL_ASN1_item_d2i(void** dst, const byte **src, long len, + const WOLFSSL_ASN1_ITEM* item); /* Need function declaration otherwise compiler complains */ -/* // NOLINTBEGIN(readability-named-parameter) */ +/* // NOLINTBEGIN(readability-named-parameter,bugprone-macro-parentheses) */ #define IMPLEMENT_ASN1_FUNCTIONS(type) \ type *type##_new(void); \ type *type##_new(void){ \ @@ -178,15 +295,23 @@ WOLFSSL_API int wolfSSL_ASN1_item_i2d(const void *src, byte **dest, int i2d_##type(type *src, byte **dest); \ int i2d_##type(type *src, byte **dest) \ { \ - return wolfSSL_ASN1_item_i2d(src, dest, &type##_template_data);\ + return wolfSSL_ASN1_item_i2d(src, dest, &type##_template_data); \ + } \ + type* d2i_##type(type **dst, const byte **src, long len); \ + type* d2i_##type(type **dst, const byte **src, long len) \ + { \ + return (type*)wolfSSL_ASN1_item_d2i((void**)dst, src, len, \ + &type##_template_data); \ } -/* // NOLINTEND(readability-named-parameter) */ +/* // NOLINTEND(readability-named-parameter,bugprone-macro-parentheses) */ #endif /* OPENSSL_ALL */ #define BN_to_ASN1_INTEGER wolfSSL_BN_to_ASN1_INTEGER #define ASN1_TYPE_set wolfSSL_ASN1_TYPE_set +#define ASN1_TYPE_get wolfSSL_ASN1_TYPE_get #define ASN1_TYPE_new wolfSSL_ASN1_TYPE_new #define ASN1_TYPE_free wolfSSL_ASN1_TYPE_free +#define i2d_ASN1_TYPE wolfSSL_i2d_ASN1_TYPE #endif /* WOLFSSL_ASN1_H_ */ diff --git a/src/wolfssl/openssl/asn1t.h b/src/wolfssl/openssl/asn1t.h index e7d5aff..e74ee26 100644 --- a/src/wolfssl/openssl/asn1t.h +++ b/src/wolfssl/openssl/asn1t.h @@ -1,6 +1,6 @@ /* asn1t.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/bio.h b/src/wolfssl/openssl/bio.h index 9206b09..198ca4e 100644 --- a/src/wolfssl/openssl/bio.h +++ b/src/wolfssl/openssl/bio.h @@ -1,6 +1,6 @@ /* bio.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -61,6 +61,7 @@ #define BIO_s_file wolfSSL_BIO_s_file #define BIO_s_bio wolfSSL_BIO_s_bio #define BIO_s_socket wolfSSL_BIO_s_socket +#define BIO_s_datagram wolfSSL_BIO_s_datagram #define BIO_s_accept wolfSSL_BIO_s_socket #define BIO_set_fd wolfSSL_BIO_set_fd #define BIO_set_close wolfSSL_BIO_set_close @@ -168,7 +169,10 @@ #define BIO_C_SET_WRITE_BUF_SIZE 136 #define BIO_C_MAKE_BIO_PAIR 138 -#define BIO_CTRL_DGRAM_QUERY_MTU 40 +#define BIO_CTRL_DGRAM_CONNECT 31 +#define BIO_CTRL_DGRAM_SET_CONNECTED 32 +#define BIO_CTRL_DGRAM_QUERY_MTU 40 +#define BIO_CTRL_DGRAM_SET_PEER 44 #define BIO_FP_TEXT 0x00 #define BIO_NOCLOSE 0x00 diff --git a/src/wolfssl/openssl/bn.h b/src/wolfssl/openssl/bn.h index d5ad52b..a3afd61 100644 --- a/src/wolfssl/openssl/bn.h +++ b/src/wolfssl/openssl/bn.h @@ -1,6 +1,6 @@ /* bn.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -150,6 +150,7 @@ WOLFSSL_API int wolfSSL_BN_lshift(WOLFSSL_BIGNUM* r, const WOLFSSL_BIGNUM* bn, int n); WOLFSSL_API int wolfSSL_BN_add_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); +WOLFSSL_API int wolfSSL_BN_mul_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_set_bit(WOLFSSL_BIGNUM* bn, int n); WOLFSSL_API int wolfSSL_BN_clear_bit(WOLFSSL_BIGNUM* bn, int n); WOLFSSL_API int wolfSSL_BN_set_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); @@ -254,6 +255,7 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_lshift wolfSSL_BN_lshift #define BN_add_word wolfSSL_BN_add_word +#define BN_mul_word wolfSSL_BN_mul_word #define BN_sub_word wolfSSL_BN_sub_word #define BN_add wolfSSL_BN_add #define BN_mod_add wolfSSL_BN_mod_add diff --git a/src/wolfssl/openssl/buffer.h b/src/wolfssl/openssl/buffer.h index 52a7813..c9f2790 100644 --- a/src/wolfssl/openssl/buffer.h +++ b/src/wolfssl/openssl/buffer.h @@ -1,6 +1,6 @@ /* buffer.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/camellia.h b/src/wolfssl/openssl/camellia.h index aa830f5..0cad9c9 100644 --- a/src/wolfssl/openssl/camellia.h +++ b/src/wolfssl/openssl/camellia.h @@ -1,6 +1,6 @@ /* camellia.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/cmac.h b/src/wolfssl/openssl/cmac.h index 5ae013c..dd08497 100644 --- a/src/wolfssl/openssl/cmac.h +++ b/src/wolfssl/openssl/cmac.h @@ -1,6 +1,6 @@ /* cmac.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/cms.h b/src/wolfssl/openssl/cms.h index 5355c61..7febb67 100644 --- a/src/wolfssl/openssl/cms.h +++ b/src/wolfssl/openssl/cms.h @@ -1,6 +1,6 @@ /* cms.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/compat_types.h b/src/wolfssl/openssl/compat_types.h index c1afd62..61cc80a 100644 --- a/src/wolfssl/openssl/compat_types.h +++ b/src/wolfssl/openssl/compat_types.h @@ -1,6 +1,6 @@ /* compat_types.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -50,6 +50,8 @@ typedef struct WOLFSSL_EVP_PKEY_CTX WOLFSSL_EVP_PKEY_CTX; typedef struct WOLFSSL_EVP_CIPHER_CTX WOLFSSL_EVP_CIPHER_CTX; typedef struct WOLFSSL_ASN1_PCTX WOLFSSL_ASN1_PCTX; +typedef struct WOLFSSL_BIO WOLFSSL_BIO; + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) typedef WOLFSSL_EVP_MD EVP_MD; typedef WOLFSSL_EVP_MD_CTX EVP_MD_CTX; diff --git a/src/wolfssl/openssl/conf.h b/src/wolfssl/openssl/conf.h index 7c3d721..4e9115f 100644 --- a/src/wolfssl/openssl/conf.h +++ b/src/wolfssl/openssl/conf.h @@ -1,6 +1,6 @@ /* conf.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/crypto.h b/src/wolfssl/openssl/crypto.h index a787da2..e436e93 100644 --- a/src/wolfssl/openssl/crypto.h +++ b/src/wolfssl/openssl/crypto.h @@ -1,6 +1,6 @@ /* crypto.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/des.h b/src/wolfssl/openssl/des.h index ca0be35..0f385a6 100644 --- a/src/wolfssl/openssl/des.h +++ b/src/wolfssl/openssl/des.h @@ -1,6 +1,6 @@ /* des.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/dh.h b/src/wolfssl/openssl/dh.h index eacd033..7ea0f62 100644 --- a/src/wolfssl/openssl/dh.h +++ b/src/wolfssl/openssl/dh.h @@ -1,6 +1,6 @@ /* dh.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -26,6 +26,7 @@ #define WOLFSSL_DH_H_ #include +#include #include #ifdef __cplusplus @@ -67,6 +68,9 @@ WOLFSSL_API int wolfSSL_DH_size(WOLFSSL_DH* dh); WOLFSSL_API int wolfSSL_DH_generate_key(WOLFSSL_DH* dh); WOLFSSL_API int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* pub, WOLFSSL_DH* dh); +WOLFSSL_API int wolfSSL_DH_compute_key_padded(unsigned char* key, + const WOLFSSL_BIGNUM* otherPub, WOLFSSL_DH* dh); + WOLFSSL_API int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz); WOLFSSL_API int wolfSSL_DH_set_length(WOLFSSL_DH* dh, long len); @@ -91,6 +95,7 @@ typedef WOLFSSL_DH DH; #define DH_size wolfSSL_DH_size #define DH_generate_key wolfSSL_DH_generate_key #define DH_compute_key wolfSSL_DH_compute_key +#define DH_compute_key_padded wolfSSL_DH_compute_key_padded #define DH_set_length wolfSSL_DH_set_length #define DH_set0_pqg wolfSSL_DH_set0_pqg #define DH_get0_pqg wolfSSL_DH_get0_pqg @@ -98,6 +103,8 @@ typedef WOLFSSL_DH DH; #define DH_set0_key wolfSSL_DH_set0_key #define DH_bits(x) (BN_num_bits((x)->p)) +#define OPENSSL_DH_MAX_MODULUS_BITS DH_MAX_SIZE + #define DH_GENERATOR_2 2 #define DH_CHECK_P_NOT_PRIME 0x01 #define DH_CHECK_P_NOT_SAFE_PRIME 0x02 diff --git a/src/wolfssl/openssl/dsa.h b/src/wolfssl/openssl/dsa.h index 5a8c31c..6acb59e 100644 --- a/src/wolfssl/openssl/dsa.h +++ b/src/wolfssl/openssl/dsa.h @@ -1,6 +1,6 @@ /* dsa.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -26,6 +26,7 @@ #define WOLFSSL_DSA_H_ #include +#include #ifdef __cplusplus extern "C" { @@ -119,6 +120,8 @@ WOLFSSL_API WOLFSSL_DSA* wolfSSL_d2i_DSAparams( typedef WOLFSSL_DSA DSA; +#define OPENSSL_DSA_MAX_MODULUS_BITS 3072 + #define WOLFSSL_DSA_LOAD_PRIVATE 1 #define WOLFSSL_DSA_LOAD_PUBLIC 2 diff --git a/src/wolfssl/openssl/ec.h b/src/wolfssl/openssl/ec.h index da988c6..bd81894 100644 --- a/src/wolfssl/openssl/ec.h +++ b/src/wolfssl/openssl/ec.h @@ -1,6 +1,6 @@ /* ec.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -25,7 +25,9 @@ #define WOLFSSL_EC_H_ #include +#include #include +#include #include #include @@ -205,6 +207,9 @@ WOLFSSL_API int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* der, int derSz, int opt); WOLFSSL_API +WOLFSSL_EC_KEY *wolfSSL_d2i_EC_PUBKEY_bio(WOLFSSL_BIO *bio, + WOLFSSL_EC_KEY **out); +WOLFSSL_API void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key); WOLFSSL_API WOLFSSL_EC_POINT *wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key); @@ -371,6 +376,8 @@ typedef WOLFSSL_EC_KEY_METHOD EC_KEY_METHOD; #define EC_KEY_check_key wolfSSL_EC_KEY_check_key #define EC_KEY_print_fp wolfSSL_EC_KEY_print_fp +#define d2i_EC_PUBKEY_bio wolfSSL_d2i_EC_PUBKEY_bio + #define ECDSA_size wolfSSL_ECDSA_size #define ECDSA_sign wolfSSL_ECDSA_sign #define ECDSA_verify wolfSSL_ECDSA_verify @@ -424,6 +431,8 @@ typedef WOLFSSL_EC_KEY_METHOD EC_KEY_METHOD; #define i2d_ECPrivateKey wolfSSL_i2d_ECPrivateKey #define EC_KEY_set_conv_form wolfSSL_EC_KEY_set_conv_form #define EC_KEY_get_conv_form wolfSSL_EC_KEY_get_conv_form +#define d2i_ECPKParameters wolfSSL_d2i_ECPKParameters +#define i2d_ECPKParameters wolfSSL_i2d_ECPKParameters #define EC_POINT_point2hex wolfSSL_EC_POINT_point2hex #define EC_POINT_hex2point wolfSSL_EC_POINT_hex2point diff --git a/src/wolfssl/openssl/ec25519.h b/src/wolfssl/openssl/ec25519.h index 6090311..0421ce8 100644 --- a/src/wolfssl/openssl/ec25519.h +++ b/src/wolfssl/openssl/ec25519.h @@ -1,6 +1,6 @@ /* ec25519.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ec448.h b/src/wolfssl/openssl/ec448.h index 06ce1dd..89a9e1c 100644 --- a/src/wolfssl/openssl/ec448.h +++ b/src/wolfssl/openssl/ec448.h @@ -1,6 +1,6 @@ /* ec448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ecdh.h b/src/wolfssl/openssl/ecdh.h index 9f816b2..74b8c91 100644 --- a/src/wolfssl/openssl/ecdh.h +++ b/src/wolfssl/openssl/ecdh.h @@ -1,6 +1,6 @@ /* ecdh.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ecdsa.h b/src/wolfssl/openssl/ecdsa.h index 385e5c0..704f56d 100644 --- a/src/wolfssl/openssl/ecdsa.h +++ b/src/wolfssl/openssl/ecdsa.h @@ -1,6 +1,6 @@ /* ecdsa.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ed25519.h b/src/wolfssl/openssl/ed25519.h index a4f2a3a..d4c1b1b 100644 --- a/src/wolfssl/openssl/ed25519.h +++ b/src/wolfssl/openssl/ed25519.h @@ -1,6 +1,6 @@ /* ed25519.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ed448.h b/src/wolfssl/openssl/ed448.h index 2d2b4b7..3c97862 100644 --- a/src/wolfssl/openssl/ed448.h +++ b/src/wolfssl/openssl/ed448.h @@ -1,6 +1,6 @@ /* ed448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/err.h b/src/wolfssl/openssl/err.h index 178afa5..2af6407 100644 --- a/src/wolfssl/openssl/err.h +++ b/src/wolfssl/openssl/err.h @@ -1,6 +1,6 @@ /* err.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/evp.h b/src/wolfssl/openssl/evp.h index 346cefc..fbfea20 100644 --- a/src/wolfssl/openssl/evp.h +++ b/src/wolfssl/openssl/evp.h @@ -1,6 +1,6 @@ /* evp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -722,6 +722,8 @@ WOLFSSL_API int wolfSSL_EVP_PKEY_keygen_init(WOLFSSL_EVP_PKEY_CTX *ctx); WOLFSSL_API int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY **ppkey); WOLFSSL_API int wolfSSL_EVP_PKEY_bits(const WOLFSSL_EVP_PKEY *pkey); +WOLFSSL_API int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, + const char *name); #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L WOLFSSL_API void wolfSSL_EVP_PKEY_CTX_free(WOLFSSL_EVP_PKEY_CTX *ctx); #else @@ -1111,6 +1113,7 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_PKEY_keygen wolfSSL_EVP_PKEY_keygen #define EVP_PKEY_keygen_init wolfSSL_EVP_PKEY_keygen_init #define EVP_PKEY_bits wolfSSL_EVP_PKEY_bits +#define EVP_PKEY_is_a wolfSSL_EVP_PKEY_is_a #define EVP_PKEY_CTX_free wolfSSL_EVP_PKEY_CTX_free #define EVP_PKEY_CTX_new wolfSSL_EVP_PKEY_CTX_new #define EVP_PKEY_CTX_set_rsa_padding wolfSSL_EVP_PKEY_CTX_set_rsa_padding diff --git a/src/wolfssl/openssl/fips_rand.h b/src/wolfssl/openssl/fips_rand.h index 586a957..58f21b3 100644 --- a/src/wolfssl/openssl/fips_rand.h +++ b/src/wolfssl/openssl/fips_rand.h @@ -1,6 +1,6 @@ /* fips_rand.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/hmac.h b/src/wolfssl/openssl/hmac.h index 818c860..71a473b 100644 --- a/src/wolfssl/openssl/hmac.h +++ b/src/wolfssl/openssl/hmac.h @@ -1,6 +1,6 @@ /* hmac.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/include.am b/src/wolfssl/openssl/include.am index dee416c..84e0dbb 100644 --- a/src/wolfssl/openssl/include.am +++ b/src/wolfssl/openssl/include.am @@ -46,6 +46,7 @@ nobase_include_HEADERS+= \ wolfssl/openssl/pkcs7.h \ wolfssl/openssl/rand.h \ wolfssl/openssl/rsa.h \ + wolfssl/openssl/safestack.h \ wolfssl/openssl/sha.h \ wolfssl/openssl/sha3.h \ wolfssl/openssl/srp.h \ diff --git a/src/wolfssl/openssl/kdf.h b/src/wolfssl/openssl/kdf.h index 29537df..08d8327 100644 --- a/src/wolfssl/openssl/kdf.h +++ b/src/wolfssl/openssl/kdf.h @@ -1,6 +1,6 @@ /* kdf.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/lhash.h b/src/wolfssl/openssl/lhash.h index 06c62a2..4c1637a 100644 --- a/src/wolfssl/openssl/lhash.h +++ b/src/wolfssl/openssl/lhash.h @@ -1,6 +1,6 @@ /* lhash.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/md4.h b/src/wolfssl/openssl/md4.h index e1f8b9e..d478e96 100644 --- a/src/wolfssl/openssl/md4.h +++ b/src/wolfssl/openssl/md4.h @@ -1,6 +1,6 @@ /* md4.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/md5.h b/src/wolfssl/openssl/md5.h index 81b6000..62533a9 100644 --- a/src/wolfssl/openssl/md5.h +++ b/src/wolfssl/openssl/md5.h @@ -1,6 +1,6 @@ /* md5.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/modes.h b/src/wolfssl/openssl/modes.h index 3288f50..e6a584c 100644 --- a/src/wolfssl/openssl/modes.h +++ b/src/wolfssl/openssl/modes.h @@ -1,6 +1,6 @@ /* modes.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/obj_mac.h b/src/wolfssl/openssl/obj_mac.h index f3fcd85..b083f04 100644 --- a/src/wolfssl/openssl/obj_mac.h +++ b/src/wolfssl/openssl/obj_mac.h @@ -1,6 +1,6 @@ /* obj_mac.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/objects.h b/src/wolfssl/openssl/objects.h index 5f8d8f7..08640fb 100644 --- a/src/wolfssl/openssl/objects.h +++ b/src/wolfssl/openssl/objects.h @@ -1,6 +1,6 @@ /* objects.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ocsp.h b/src/wolfssl/openssl/ocsp.h index 8cd3372..28eb159 100644 --- a/src/wolfssl/openssl/ocsp.h +++ b/src/wolfssl/openssl/ocsp.h @@ -1,6 +1,6 @@ /* ocsp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -27,12 +27,16 @@ #ifdef HAVE_OCSP #include -#define OCSP_REQUEST OcspRequest -#define OCSP_RESPONSE OcspResponse -#define OCSP_BASICRESP WOLFSSL_OCSP_BASICRESP -#define OCSP_SINGLERESP WOLFSSL_OCSP_SINGLERESP -#define OCSP_CERTID WOLFSSL_OCSP_CERTID -#define OCSP_ONEREQ WOLFSSL_OCSP_ONEREQ +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) ||\ + defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) +typedef OcspRequest OCSP_REQUEST; +typedef OcspResponse OCSP_RESPONSE; +typedef WOLFSSL_OCSP_BASICRESP OCSP_BASICRESP; +typedef WOLFSSL_OCSP_SINGLERESP OCSP_SINGLERESP; +typedef WOLFSSL_OCSP_CERTID OCSP_CERTID; +typedef WOLFSSL_OCSP_ONEREQ OCSP_ONEREQ; +typedef WOLFSSL_OCSP_REQ_CTX OCSP_REQ_CTX; +#endif #define OCSP_REVOKED_STATUS_NOSTATUS (-1) @@ -85,6 +89,15 @@ #define OCSP_resp_count wolfSSL_OCSP_resp_count #define OCSP_resp_get0 wolfSSL_OCSP_resp_get0 +#define OCSP_REQ_CTX_new wolfSSL_OCSP_REQ_CTX_new +#define OCSP_REQ_CTX_free wolfSSL_OCSP_REQ_CTX_free +#define OCSP_sendreq_new wolfSSL_OCSP_sendreq_new +#define OCSP_REQ_CTX_set1_req wolfSSL_OCSP_REQ_CTX_set1_req +#define OCSP_REQ_CTX_add1_header wolfSSL_OCSP_REQ_CTX_add1_header +#define OCSP_REQ_CTX_http wolfSSL_OCSP_REQ_CTX_http +#define OCSP_REQ_CTX_nbio wolfSSL_OCSP_REQ_CTX_nbio +#define OCSP_sendreq_nbio wolfSSL_OCSP_sendreq_nbio + #endif /* HAVE_OCSP */ #endif /* WOLFSSL_OCSP_H_ */ diff --git a/src/wolfssl/openssl/opensslv.h b/src/wolfssl/openssl/opensslv.h index f68b6ca..481f74e 100644 --- a/src/wolfssl/openssl/opensslv.h +++ b/src/wolfssl/openssl/opensslv.h @@ -1,6 +1,6 @@ /* opensslv.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -34,32 +34,41 @@ defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER == 0x0090810fL) ||\ defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER == 0x10100000L) ||\ defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER == 0x10001040L) - /* valid version */ + /* valid version */ +#elif defined(OPENSSL_VERSION_NUMBER) + /* unrecognized version, but continue. */ + #define WOLFSSL_OPENSSL_VERSION_NUMBER_UNRECOGNIZED +#elif defined(HAVE_MOSQUITTO) + #define OPENSSL_VERSION_NUMBER 0x10100000L #elif defined(WOLFSSL_APACHE_HTTPD) || defined(HAVE_LIBEST) || \ defined(WOLFSSL_BIND) || defined(WOLFSSL_NGINX) || \ defined(WOLFSSL_RSYSLOG) || defined(WOLFSSL_KRB) || defined(HAVE_STUNNEL) || \ defined(WOLFSSL_OPENSSH) /* For Apache httpd, Use 1.1.0 compatibility */ - #define OPENSSL_VERSION_NUMBER 0x10100003L -#elif defined(WOLFSSL_QT) || defined(WOLFSSL_PYTHON) || defined(WOLFSSL_KRB) + #define OPENSSL_VERSION_NUMBER 0x10100003L +#elif defined(WOLFSSL_QT) || defined(WOLFSSL_PYTHON) /* For Qt and Python 3.8.5 compatibility */ - #define OPENSSL_VERSION_NUMBER 0x10101000L + #define OPENSSL_VERSION_NUMBER 0x10101000L #elif defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_FFMPEG) - #define OPENSSL_VERSION_NUMBER 0x1010000fL + #define OPENSSL_VERSION_NUMBER 0x1010000fL #elif defined(OPENSSL_ALL) || defined(HAVE_LIGHTY) || \ - defined(WOLFSSL_NGINX) || defined(WOLFSSL_OPENVPN) - /* version number can be increased for Lighty after compatibility for ECDH - is added */ - #define OPENSSL_VERSION_NUMBER 0x10001040L + defined(WOLFSSL_NGINX) || defined(WOLFSSL_OPENSSH) || defined(WOLFSSL_OPENVPN) + /* version number can be increased for Lighty after compatibility for ECDH + is added */ + #define OPENSSL_VERSION_NUMBER 0x10001040L #else - #define OPENSSL_VERSION_NUMBER 0x0090810fL + #define OPENSSL_VERSION_NUMBER 0x0090810fL #endif -#define OPENSSL_VERSION_TEXT "wolfSSL " LIBWOLFSSL_VERSION_STRING -#define OPENSSL_VERSION 0 +#ifndef OPENSSL_VERSION_TEXT + #define OPENSSL_VERSION_TEXT "wolfSSL " LIBWOLFSSL_VERSION_STRING +#endif +#ifndef OPENSSL_VERSION + #define OPENSSL_VERSION 0 +#endif #ifndef OPENSSL_IS_WOLFSSL -#define OPENSSL_IS_WOLFSSL + #define OPENSSL_IS_WOLFSSL #endif #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ diff --git a/src/wolfssl/openssl/ossl_typ.h b/src/wolfssl/openssl/ossl_typ.h index 85b83c3..8214fa3 100644 --- a/src/wolfssl/openssl/ossl_typ.h +++ b/src/wolfssl/openssl/ossl_typ.h @@ -1,6 +1,6 @@ /* ossl_typ.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/pem.h b/src/wolfssl/openssl/pem.h index 221e8d6..8ecc02c 100644 --- a/src/wolfssl/openssl/pem.h +++ b/src/wolfssl/openssl/pem.h @@ -1,6 +1,6 @@ /* pem.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -56,6 +56,8 @@ WOLFSSL_API WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA** rsa, wc_pem_password_cb* cb, void *u); +WOLFSSL_API +WOLFSSL_RSA *wolfSSL_d2i_RSA_PUBKEY_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out); WOLFSSL_API WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio, @@ -63,6 +65,12 @@ WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio, wc_pem_password_cb* cb, void* pass); WOLFSSL_API +WOLFSSL_EC_GROUP *wolfSSL_d2i_ECPKParameters(WOLFSSL_EC_GROUP **out, + const unsigned char **in, + long len); +WOLFSSL_API +int wolfSSL_i2d_ECPKParameters(const WOLFSSL_EC_GROUP* grp, unsigned char** pp); +WOLFSSL_API int wolfSSL_PEM_write_mem_RSAPrivateKey(WOLFSSL_RSA* rsa, const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len, @@ -173,6 +181,11 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY** key, wc_pem_password_cb* cb, void* pass); +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +WOLFSSL_API +PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, + PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, void* arg); +#endif WOLFSSL_API WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY **key, @@ -243,12 +256,12 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #define PEM_write_bio_RSA_PUBKEY wolfSSL_PEM_write_bio_RSA_PUBKEY #define PEM_read_bio_RSA_PUBKEY wolfSSL_PEM_read_bio_RSA_PUBKEY #define PEM_read_bio_RSAPublicKey wolfSSL_PEM_read_bio_RSA_PUBKEY -#define PEM_read_bio_ECPKParameters wolfSSL_PEM_read_bio_ECPKParameters #define PEM_write_RSAPrivateKey wolfSSL_PEM_write_RSAPrivateKey #define PEM_write_RSA_PUBKEY wolfSSL_PEM_write_RSA_PUBKEY #define PEM_read_RSA_PUBKEY wolfSSL_PEM_read_RSA_PUBKEY #define PEM_write_RSAPublicKey wolfSSL_PEM_write_RSAPublicKey #define PEM_read_RSAPublicKey wolfSSL_PEM_read_RSAPublicKey +#define d2i_RSA_PUBKEY_bio wolfSSL_d2i_RSA_PUBKEY_bio /* DSA */ #define PEM_write_bio_DSAPrivateKey wolfSSL_PEM_write_bio_DSAPrivateKey #define PEM_write_DSAPrivateKey wolfSSL_PEM_write_DSAPrivateKey @@ -263,6 +276,7 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #define PEM_write_ECPrivateKey wolfSSL_PEM_write_ECPrivateKey #define PEM_read_bio_ECPrivateKey wolfSSL_PEM_read_bio_ECPrivateKey #define PEM_read_bio_EC_PUBKEY wolfSSL_PEM_read_bio_EC_PUBKEY +#define PEM_read_bio_ECPKParameters wolfSSL_PEM_read_bio_ECPKParameters #ifndef NO_WOLFSSL_STUB #define PEM_write_bio_ECPKParameters(...) 0 #endif @@ -272,6 +286,9 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #define PEM_read_bio_PUBKEY wolfSSL_PEM_read_bio_PUBKEY #define PEM_write_bio_PUBKEY wolfSSL_PEM_write_bio_PUBKEY +#define PEM_write_bio_PKCS8_PRIV_KEY_INFO wolfSSL_PEM_write_bio_PKCS8_PRIV_KEY_INFO +#define PEM_read_bio_PKCS8_PRIV_KEY_INFO wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/pkcs12.h b/src/wolfssl/openssl/pkcs12.h index 28a0a37..d82954d 100644 --- a/src/wolfssl/openssl/pkcs12.h +++ b/src/wolfssl/openssl/pkcs12.h @@ -1,6 +1,6 @@ /* pkcs12.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/pkcs7.h b/src/wolfssl/openssl/pkcs7.h index 41f8901..9a53b89 100644 --- a/src/wolfssl/openssl/pkcs7.h +++ b/src/wolfssl/openssl/pkcs7.h @@ -1,6 +1,6 @@ /* pkcs7.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rand.h b/src/wolfssl/openssl/rand.h index cc0d72a..c88cd12 100644 --- a/src/wolfssl/openssl/rand.h +++ b/src/wolfssl/openssl/rand.h @@ -1,6 +1,6 @@ /* rand.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rc4.h b/src/wolfssl/openssl/rc4.h index ca56ac8..cef9330 100644 --- a/src/wolfssl/openssl/rc4.h +++ b/src/wolfssl/openssl/rc4.h @@ -1,6 +1,6 @@ /* rc4.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ripemd.h b/src/wolfssl/openssl/ripemd.h index 7ba600d..a7c4247 100644 --- a/src/wolfssl/openssl/ripemd.h +++ b/src/wolfssl/openssl/ripemd.h @@ -1,6 +1,6 @@ /* ripemd.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rsa.h b/src/wolfssl/openssl/rsa.h index 7284948..9311283 100644 --- a/src/wolfssl/openssl/rsa.h +++ b/src/wolfssl/openssl/rsa.h @@ -1,6 +1,6 @@ /* rsa.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -27,7 +27,9 @@ #include #include +#include #include +#include #ifdef __cplusplus extern "C" { @@ -189,6 +191,8 @@ WOLFSSL_API int wolfSSL_RSA_set_ex_data_with_cleanup( #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#define OPENSSL_RSA_MAX_MODULUS_BITS RSA_MAX_SIZE + #define WOLFSSL_RSA_LOAD_PRIVATE 1 #define WOLFSSL_RSA_LOAD_PUBLIC 2 #define WOLFSSL_RSA_F4 0x10001L @@ -240,6 +244,9 @@ WOLFSSL_API int wolfSSL_RSA_set_ex_data_with_cleanup( #define RSA_F4 WOLFSSL_RSA_F4 +#define OPENSSL_RSA_MAX_MODULUS_BITS RSA_MAX_SIZE +#define OPENSSL_RSA_MAX_PUBEXP_BITS RSA_MAX_SIZE + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/safestack.h b/src/wolfssl/openssl/safestack.h new file mode 100644 index 0000000..ee1f872 --- /dev/null +++ b/src/wolfssl/openssl/safestack.h @@ -0,0 +1,40 @@ +/* safestack.h + * + * Copyright (C) 2006-2023 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* stack.h for openSSL */ + +#ifndef WOLFSSL_SAFESTACK_H_ +#define WOLFSSL_SAFESTACK_H_ + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/src/wolfssl/openssl/sha.h b/src/wolfssl/openssl/sha.h index ab38c5c..f9bc1a5 100644 --- a/src/wolfssl/openssl/sha.h +++ b/src/wolfssl/openssl/sha.h @@ -1,6 +1,6 @@ /* sha.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/sha3.h b/src/wolfssl/openssl/sha3.h index 4407bca..c2f5535 100644 --- a/src/wolfssl/openssl/sha3.h +++ b/src/wolfssl/openssl/sha3.h @@ -1,6 +1,6 @@ /* sha3.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/srp.h b/src/wolfssl/openssl/srp.h index b60981d..097cf51 100644 --- a/src/wolfssl/openssl/srp.h +++ b/src/wolfssl/openssl/srp.h @@ -1,6 +1,6 @@ /* srp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ssl.h b/src/wolfssl/openssl/ssl.h index 0fbf621..f6d29f0 100644 --- a/src/wolfssl/openssl/ssl.h +++ b/src/wolfssl/openssl/ssl.h @@ -1,6 +1,6 @@ /* ssl.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -82,6 +82,7 @@ typedef WOLFSSL_CTX SSL_CTX; typedef WOLFSSL_X509 X509; typedef WOLFSSL_X509 X509_REQ; +typedef WOLFSSL_X509 X509_REQ_INFO; typedef WOLFSSL_X509_NAME X509_NAME; typedef WOLFSSL_X509_INFO X509_INFO; typedef WOLFSSL_X509_CHAIN X509_CHAIN; @@ -99,6 +100,7 @@ typedef WOLFSSL_CIPHER SSL_CIPHER; typedef WOLFSSL_X509_LOOKUP X509_LOOKUP; typedef WOLFSSL_X509_LOOKUP_METHOD X509_LOOKUP_METHOD; typedef WOLFSSL_X509_CRL X509_CRL; +typedef WOLFSSL_X509_ACERT X509_ACERT; typedef WOLFSSL_X509_EXTENSION X509_EXTENSION; typedef WOLFSSL_X509_PUBKEY X509_PUBKEY; typedef WOLFSSL_X509_ALGOR X509_ALGOR; @@ -205,7 +207,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_use_certificate_ASN1 wolfSSL_use_certificate_ASN1 #define d2i_PKCS8_PRIV_KEY_INFO_bio wolfSSL_d2i_PKCS8_PKEY_bio #define d2i_PKCS8_PRIV_KEY_INFO wolfSSL_d2i_PKCS8_PKEY -#define i2d_PKCS8_PRIV_KEY_INFO wolfSSL_i2d_PrivateKey +#define i2d_PKCS8_PRIV_KEY_INFO wolfSSL_i2d_PKCS8_PKEY #define d2i_PKCS8PrivateKey_bio wolfSSL_d2i_PKCS8PrivateKey_bio #define i2d_PKCS8PrivateKey_bio wolfSSL_PEM_write_bio_PKCS8PrivateKey #define PKCS8_PRIV_KEY_INFO_free wolfSSL_EVP_PKEY_free @@ -214,6 +216,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_CTX_set_ecdh_auto wolfSSL_CTX_set_ecdh_auto #define i2d_PUBKEY wolfSSL_i2d_PUBKEY +#define i2d_X509_PUBKEY wolfSSL_i2d_X509_PUBKEY #define d2i_PUBKEY wolfSSL_d2i_PUBKEY #define d2i_PUBKEY_bio wolfSSL_d2i_PUBKEY_bio #define d2i_PublicKey wolfSSL_d2i_PublicKey @@ -254,6 +257,8 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define X509_F_X509_CHECK_PRIVATE_KEY 128 #ifdef WOLFSSL_DTLS + #define DTLS_client_method wolfDTLS_client_method + #define DTLS_server_method wolfDTLS_server_method #define DTLSv1_client_method wolfDTLSv1_client_method #define DTLSv1_server_method wolfDTLSv1_server_method #define DTLSv1_2_client_method wolfDTLSv1_2_client_method @@ -265,13 +270,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #ifndef NO_FILESYSTEM #define SSL_CTX_use_certificate_file wolfSSL_CTX_use_certificate_file #define SSL_CTX_use_PrivateKey_file wolfSSL_CTX_use_PrivateKey_file -#ifdef WOLFSSL_APACHE_HTTPD - #define SSL_CTX_load_verify_locations(ctx,file,path) \ - wolfSSL_CTX_load_verify_locations_ex(ctx,file,path,\ - WOLFSSL_LOAD_FLAG_IGNORE_ERR) -#else - #define SSL_CTX_load_verify_locations wolfSSL_CTX_load_verify_locations -#endif + #define SSL_CTX_load_verify_locations wolfSSL_CTX_load_verify_locations_compat #define SSL_CTX_set_default_verify_paths wolfSSL_CTX_set_default_verify_paths #define SSL_CTX_use_certificate_chain_file wolfSSL_CTX_use_certificate_chain_file #define SSL_CTX_use_RSAPrivateKey_file wolfSSL_CTX_use_RSAPrivateKey_file @@ -400,7 +399,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_SESSION_get_master_key_length wolfSSL_SESSION_get_master_key_length #define SSL_SESSION_get_max_early_data wolfSSL_SESSION_get_max_early_data -#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) +#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) #define SSL_MODE_RELEASE_BUFFERS 0x00000010U #define ASN1_BOOLEAN WOLFSSL_ASN1_BOOLEAN #define X509_get_ext wolfSSL_X509_get_ext @@ -429,6 +428,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define d2i_X509_fp wolfSSL_d2i_X509_fp #define i2d_X509 wolfSSL_i2d_X509 #define d2i_X509 wolfSSL_d2i_X509 +#define d2i_X509_REQ_INFO wolfSSL_d2i_X509_REQ_INFO #define PEM_read_bio_X509 wolfSSL_PEM_read_bio_X509 #define PEM_read_bio_X509_REQ wolfSSL_PEM_read_bio_X509_REQ #define PEM_read_X509_REQ wolfSSL_PEM_read_X509_REQ @@ -446,6 +446,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define d2i_X509_REQ wolfSSL_d2i_X509_REQ #define X509_REQ_new wolfSSL_X509_REQ_new #define X509_REQ_free wolfSSL_X509_REQ_free +#define X509_REQ_INFO_free wolfSSL_X509_REQ_free #define X509_REQ_sign wolfSSL_X509_REQ_sign #define X509_REQ_sign_ctx wolfSSL_X509_REQ_sign_ctx #define X509_REQ_add_extensions wolfSSL_X509_REQ_add_extensions @@ -491,6 +492,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define X509_get0_notAfter wolfSSL_X509_get_notAfter #define X509_getm_notAfter wolfSSL_X509_get_notAfter #define X509_get_serialNumber wolfSSL_X509_get_serialNumber +#define X509_get0_serialNumber wolfSSL_X509_get_serialNumber #define X509_get0_pubkey_bitstr wolfSSL_X509_get0_pubkey_bitstr #define X509_get_ex_new_index wolfSSL_X509_get_ex_new_index #define X509_get_ex_data wolfSSL_X509_get_ex_data @@ -533,6 +535,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define X509_dup wolfSSL_X509_dup #define X509_add_ext wolfSSL_X509_add_ext #define X509_delete_ext wolfSSL_X509_delete_ext +#define X509_get0_subject_key_id wolfSSL_X509_get0_subject_key_id #define X509_EXTENSION_get_object wolfSSL_X509_EXTENSION_get_object #define X509_EXTENSION_get_data wolfSSL_X509_EXTENSION_get_data @@ -566,6 +569,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define sk_X509_EXTENSION_new_null wolfSSL_sk_X509_EXTENSION_new_null #define sk_X509_EXTENSION_pop_free wolfSSL_sk_X509_EXTENSION_pop_free #define sk_X509_EXTENSION_push wolfSSL_sk_X509_EXTENSION_push +#define sk_X509_EXTENSION_free wolfSSL_sk_X509_EXTENSION_free #define X509_INFO_new wolfSSL_X509_INFO_new #define X509_INFO_free wolfSSL_X509_INFO_free @@ -639,14 +643,15 @@ typedef WOLFSSL_X509_NAME_ENTRY X509_NAME_ENTRY; #define X509_V_FLAG_CRL_CHECK WOLFSSL_CRL_CHECK #define X509_V_FLAG_CRL_CHECK_ALL WOLFSSL_CRL_CHECKALL -#define X509_V_FLAG_PARTIAL_CHAIN 0 -#define X509_V_FLAG_TRUSTED_FIRST 0 +#define X509_V_FLAG_PARTIAL_CHAIN WOLFSSL_PARTIAL_CHAIN +#define X509_V_FLAG_TRUSTED_FIRST 0 /* dummy value needed for gRPC port */ #define X509_V_FLAG_USE_CHECK_TIME WOLFSSL_USE_CHECK_TIME #define X509_V_FLAG_NO_CHECK_TIME WOLFSSL_NO_CHECK_TIME #define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT WOLFSSL_ALWAYS_CHECK_SUBJECT #define X509_CHECK_FLAG_NO_WILDCARDS WOLFSSL_NO_WILDCARDS #define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS WOLFSSL_NO_PARTIAL_WILDCARDS +#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS WOLFSSL_MULTI_LABEL_WILDCARDS #define X509_VP_FLAG_DEFAULT WOLFSSL_VPARAM_DEFAULT #define X509_VP_FLAG_OVERWRITE WOLFSSL_VPARAM_OVERWRITE @@ -698,6 +703,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_STORE_set_ex_data wolfSSL_X509_STORE_set_ex_data #define X509_STORE_get_ex_data wolfSSL_X509_STORE_get_ex_data #define X509_STORE_get0_param wolfSSL_X509_STORE_get0_param +#define X509_STORE_set1_param wolfSSL_X509_STORE_set1_param #define X509_STORE_CTX_get1_issuer wolfSSL_X509_STORE_CTX_get1_issuer #define X509_STORE_CTX_set_time wolfSSL_X509_STORE_CTX_set_time #define X509_STORE_CTX_get0_param wolfSSL_X509_STORE_CTX_get0_param @@ -712,7 +718,10 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_VERIFY_PARAM_set1_ip_asc wolfSSL_X509_VERIFY_PARAM_set1_ip_asc #define X509_VERIFY_PARAM_set1_ip wolfSSL_X509_VERIFY_PARAM_set1_ip #define X509_VERIFY_PARAM_set1 wolfSSL_X509_VERIFY_PARAM_set1 +#define X509_VERIFY_PARAM_lookup wolfSSL_X509_VERIFY_PARAM_lookup +#define X509_VERIFY_PARAM_inherit wolfSSL_X509_VERIFY_PARAM_inherit #define X509_STORE_load_locations wolfSSL_X509_STORE_load_locations +#define X509_STORE_get0_param wolfSSL_X509_STORE_get0_param #define X509_LOOKUP_add_dir wolfSSL_X509_LOOKUP_add_dir #define X509_LOOKUP_load_file wolfSSL_X509_LOOKUP_load_file @@ -737,6 +746,14 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_CRL_get_version wolfSSL_X509_CRL_version #define X509_load_crl_file wolfSSL_X509_load_crl_file +#define X509_ACERT_free wolfSSL_X509_ACERT_free +#define X509_ACERT_get_version wolfSSL_X509_ACERT_get_version +#define X509_ACERT_get_signature_nid wolfSSL_X509_ACERT_get_signature_nid +#define X509_ACERT_print wolfSSL_X509_ACERT_print +#define X509_ACERT_verify wolfSSL_X509_ACERT_verify +#define X509_ACERT_sign wolfSSL_X509_ACERT_sign +#define PEM_read_bio_X509_ACERT wolfSSL_PEM_read_bio_X509_ACERT + #define X509_get_X509_PUBKEY wolfSSL_X509_get_X509_PUBKEY #define X509_REQ_get_X509_PUBKEY wolfSSL_X509_get_X509_PUBKEY #define X509_get0_tbs_sigalg wolfSSL_X509_get0_tbs_sigalg @@ -748,6 +765,8 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_ALGOR_new wolfSSL_X509_ALGOR_new #define X509_ALGOR_free wolfSSL_X509_ALGOR_free +#define i2d_X509_ALGOR wolfSSL_i2d_X509_ALGOR +#define d2i_X509_ALGOR wolfSSL_d2i_X509_ALGOR #define X509_PUBKEY_new wolfSSL_X509_PUBKEY_new #define X509_PUBKEY_free wolfSSL_X509_PUBKEY_free @@ -784,7 +803,9 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define BIO_pop wolfSSL_BIO_pop #define BIO_flush wolfSSL_BIO_flush #define BIO_pending wolfSSL_BIO_pending - +#define BIO_number_read wolfSSL_BIO_number_read +#define BIO_number_written wolfSSL_BIO_number_written +#define BIO_reset wolfSSL_BIO_reset #define BIO_get_mem_data wolfSSL_BIO_get_mem_data #define BIO_new_mem_buf wolfSSL_BIO_new_mem_buf @@ -792,6 +813,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define BIO_set_write_buffer_size wolfSSL_BIO_set_write_buffer_size #define BIO_f_ssl wolfSSL_BIO_f_ssl #define BIO_new_socket wolfSSL_BIO_new_socket +#define BIO_new_dgram wolfSSL_BIO_new_dgram #define BIO_new_connect wolfSSL_BIO_new_connect #define BIO_new_accept wolfSSL_BIO_new_accept #define BIO_set_conn_port wolfSSL_BIO_set_conn_port @@ -800,6 +822,8 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define BIO_do_handshake wolfSSL_BIO_do_handshake #define BIO_ssl_shutdown wolfSSL_BIO_ssl_shutdown #define SSL_set_bio wolfSSL_set_bio +#define SSL_set0_rbio wolfSSL_set_rbio +#define SSL_set0_wbio wolfSSL_set_wbio #define BIO_method_type wolfSSL_BIO_method_type #define BIO_set_ssl wolfSSL_BIO_set_ssl #define BIO_get_ssl wolfSSL_BIO_get_ssl @@ -835,10 +859,9 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define COMP_zlib wolfSSL_COMP_zlib #define COMP_rle wolfSSL_COMP_rle #define SSL_COMP_add_compression_method wolfSSL_COMP_add_compression_method - -#define SSL_get_current_compression(ssl) 0 -#define SSL_get_current_expansion(ssl) 0 #define SSL_COMP_get_name wolfSSL_COMP_get_name +#define SSL_get_current_compression wolfSSL_get_current_compression +#define SSL_get_current_expansion wolfSSL_get_current_expansion #define SSL_get_ex_new_index wolfSSL_get_ex_new_index #define RSA_get_ex_new_index wolfSSL_get_ex_new_index @@ -847,6 +870,8 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ASN1_BIT_STRING_free wolfSSL_ASN1_BIT_STRING_free #define ASN1_BIT_STRING_get_bit wolfSSL_ASN1_BIT_STRING_get_bit #define ASN1_BIT_STRING_set_bit wolfSSL_ASN1_BIT_STRING_set_bit +#define i2d_ASN1_BIT_STRING wolfSSL_i2d_ASN1_BIT_STRING +#define d2i_ASN1_BIT_STRING wolfSSL_d2i_ASN1_BIT_STRING #define sk_ASN1_OBJECT_free wolfSSL_sk_ASN1_OBJECT_free @@ -866,6 +891,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #endif #define ASN1_TIME_set wolfSSL_ASN1_TIME_set #define ASN1_TIME_set_string wolfSSL_ASN1_TIME_set_string +#define ASN1_TIME_set_string_X509 wolfSSL_ASN1_TIME_set_string_X509 #define ASN1_GENERALIZEDTIME_set_string wolfSSL_ASN1_TIME_set_string #define ASN1_GENERALIZEDTIME_print wolfSSL_ASN1_GENERALIZEDTIME_print @@ -903,6 +929,22 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ASN1_STRING_set_default_mask_asc(...) 1 #endif +#define ASN1_GENERALSTRING WOLFSSL_ASN1_STRING +#define ASN1_GENERALSTRING_new wolfSSL_ASN1_STRING_new +#define ASN1_GENERALSTRING_free wolfSSL_ASN1_STRING_free +#define ASN1_GENERALSTRING_set wolfSSL_ASN1_STRING_set +#define i2d_ASN1_GENERALSTRING wolfSSL_i2d_ASN1_GENERALSTRING +#define i2d_ASN1_OCTET_STRING wolfSSL_i2d_ASN1_OCTET_STRING +#define i2d_ASN1_UTF8STRING wolfSSL_i2d_ASN1_UTF8STRING +#define i2d_ASN1_SEQUENCE wolfSSL_i2d_ASN1_SEQUENCE +#define d2i_ASN1_GENERALSTRING wolfSSL_d2i_ASN1_GENERALSTRING +#define d2i_ASN1_OCTET_STRING wolfSSL_d2i_ASN1_OCTET_STRING +#define d2i_ASN1_UTF8STRING wolfSSL_d2i_ASN1_UTF8STRING + +#define sk_ASN1_GENERALSTRING_num wolfSSL_sk_num +#define sk_ASN1_GENERALSTRING_value wolfSSL_sk_value +#define sk_ASN1_GENERALSTRING_push wolfSSL_sk_push + #define ASN1_OCTET_STRING WOLFSSL_ASN1_STRING #define ASN1_OCTET_STRING_new wolfSSL_ASN1_STRING_new #define ASN1_OCTET_STRING_free wolfSSL_ASN1_STRING_free @@ -967,7 +1009,9 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define RSA_print_fp wolfSSL_RSA_print_fp #define RSA_bits wolfSSL_RSA_bits #define RSA_up_ref wolfSSL_RSA_up_ref +#define RSA_padding_add_PKCS1_PSS_mgf1 wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1 #define RSA_padding_add_PKCS1_PSS wolfSSL_RSA_padding_add_PKCS1_PSS +#define RSA_verify_PKCS1_PSS_mgf1 wolfSSL_RSA_verify_PKCS1_PSS_mgf1 #define RSA_verify_PKCS1_PSS wolfSSL_RSA_verify_PKCS1_PSS #define PEM_def_callback wolfSSL_PEM_def_callback @@ -1149,6 +1193,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define DTLSv1_get_timeout(ssl, timeleft) wolfSSL_DTLSv1_get_timeout((ssl), (WOLFSSL_TIMEVAL*)(timeleft)) #define DTLSv1_handle_timeout wolfSSL_DTLSv1_handle_timeout #define DTLSv1_set_initial_timeout_duration wolfSSL_DTLSv1_set_initial_timeout_duration +#define SSL_set_mtu wolfSSL_set_mtu_compat /* DTLS SRTP */ #ifdef WOLFSSL_SRTP @@ -1201,6 +1246,10 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define sk_SSL_CIPHER_free wolfSSL_sk_SSL_CIPHER_free #define sk_SSL_CIPHER_find wolfSSL_sk_SSL_CIPHER_find +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) +#define SSL_get0_peername wolfSSL_get0_peername +#endif + #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \ || defined(WOLFSSL_NGINX) #include @@ -1209,7 +1258,6 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL_R_SHORT_READ 10 #define ERR_R_PEM_LIB 9 #define SSL_CTRL_MODE 33 - #define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83 #define SSL_CTX_clear_chain_certs(ctx) SSL_CTX_set0_chain(ctx,NULL) @@ -1229,6 +1277,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; (char *)(arg)) #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY */ +#define SSL_CTX_set_dh_auto wolfSSL_CTX_set_dh_auto #define SSL_CTX_set_tmp_dh wolfSSL_CTX_set_tmp_dh #define TLSEXT_STATUSTYPE_ocsp 1 @@ -1515,10 +1564,8 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define PEM_R_BAD_DECRYPT (-MIN_CODE_E + 4) #define ASN1_R_HEADER_TOO_LONG (-MIN_CODE_E + 5) +#define ERR_LIB_SYS 2 #define ERR_LIB_RSA 4 -#define ERR_LIB_EC 16 -#define ERR_LIB_SSL 20 -#define ERR_LIB_PKCS12 35 #define ERR_LIB_PEM 9 #define ERR_LIB_X509 10 #define ERR_LIB_EVP 11 @@ -1526,6 +1573,9 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define ERR_LIB_DIGEST 13 #define ERR_LIB_CIPHER 14 #define ERR_LIB_USER 15 +#define ERR_LIB_EC 16 +#define ERR_LIB_SSL 20 +#define ERR_LIB_PKCS12 35 #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) || \ @@ -1692,11 +1742,16 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define OpenSSL_version(x) wolfSSL_OpenSSL_version() #endif +#define X509_OBJECT_retrieve_by_subject wolfSSL_X509_OBJECT_retrieve_by_subject + #ifndef NO_WOLFSSL_STUB #define OBJ_create_objects(...) WC_DO_NOTHING #define sk_SSL_COMP_free(...) WC_DO_NOTHING #endif +#define ASN1_OBJECT_new wolfSSL_ASN1_OBJECT_new +#define ASN1_OBJECT_free wolfSSL_ASN1_OBJECT_free +#define i2d_ASN1_OBJECT wolfSSL_i2d_ASN1_OBJECT #define OBJ_dup wolfSSL_ASN1_OBJECT_dup #define SSL_set_psk_use_session_callback wolfSSL_set_psk_use_session_callback diff --git a/src/wolfssl/openssl/stack.h b/src/wolfssl/openssl/stack.h index cee7cfc..fe697c4 100644 --- a/src/wolfssl/openssl/stack.h +++ b/src/wolfssl/openssl/stack.h @@ -1,6 +1,6 @@ /* stack.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/tls1.h b/src/wolfssl/openssl/tls1.h index 843696a..933ed5d 100644 --- a/src/wolfssl/openssl/tls1.h +++ b/src/wolfssl/openssl/tls1.h @@ -1,6 +1,6 @@ /* tls1.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/txt_db.h b/src/wolfssl/openssl/txt_db.h index 511235b..b8aa56f 100644 --- a/src/wolfssl/openssl/txt_db.h +++ b/src/wolfssl/openssl/txt_db.h @@ -1,6 +1,6 @@ /* txt_db.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/x509.h b/src/wolfssl/openssl/x509.h index 9afb8e0..eb03578 100644 --- a/src/wolfssl/openssl/x509.h +++ b/src/wolfssl/openssl/x509.h @@ -1,6 +1,6 @@ /* x509.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/x509_vfy.h b/src/wolfssl/openssl/x509_vfy.h index 025f526..977e0c0 100644 --- a/src/wolfssl/openssl/x509_vfy.h +++ b/src/wolfssl/openssl/x509_vfy.h @@ -1,6 +1,6 @@ /* x509_vfy.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -33,10 +33,13 @@ #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) WOLFSSL_API int wolfSSL_X509_STORE_CTX_set_purpose(WOLFSSL_X509_STORE_CTX *ctx, int purpose); +#endif +#ifdef OPENSSL_EXTRA WOLFSSL_API void wolfSSL_X509_STORE_CTX_set_flags(WOLFSSL_X509_STORE_CTX *ctx, unsigned long flags); #endif + #define X509_STORE_CTX_set_purpose wolfSSL_X509_STORE_CTX_set_purpose #define X509_STORE_CTX_set_flags wolfSSL_X509_STORE_CTX_set_flags diff --git a/src/wolfssl/openssl/x509v3.h b/src/wolfssl/openssl/x509v3.h index 51b4e65..401f8e8 100644 --- a/src/wolfssl/openssl/x509v3.h +++ b/src/wolfssl/openssl/x509v3.h @@ -1,6 +1,6 @@ /* x509v3.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -137,10 +137,24 @@ WOLFSSL_API WOLFSSL_v3_ext_method* wolfSSL_X509V3_EXT_get( WOLFSSL_API void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ex); WOLFSSL_API char* wolfSSL_i2s_ASN1_STRING(WOLFSSL_v3_ext_method *method, const WOLFSSL_ASN1_STRING *s); +WOLFSSL_API int wolfSSL_i2d_ASN1_GENERALSTRING(WOLFSSL_ASN1_STRING* s, + unsigned char **pp); +WOLFSSL_API int wolfSSL_i2d_ASN1_SEQUENCE(WOLFSSL_ASN1_STRING* s, + unsigned char **pp); +WOLFSSL_API int wolfSSL_i2d_ASN1_OCTET_STRING(WOLFSSL_ASN1_STRING* s, + unsigned char **pp); +WOLFSSL_API int wolfSSL_i2d_ASN1_UTF8STRING(WOLFSSL_ASN1_STRING* s, + unsigned char **pp); +WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_GENERALSTRING( + WOLFSSL_ASN1_STRING** out, const byte** src, long len); +WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_OCTET_STRING( + WOLFSSL_ASN1_STRING** out, const byte** src, long len); +WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_d2i_ASN1_UTF8STRING( + WOLFSSL_ASN1_STRING** out, const byte** src, long len); WOLFSSL_API int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, unsigned long flag, int indent); -WOLFSSL_API int wolfSSL_X509V3_EXT_add_nconf(WOLFSSL_CONF *conf, WOLFSSL_X509V3_CTX *ctx, - const char *section, WOLFSSL_X509 *cert); +WOLFSSL_API int wolfSSL_X509V3_EXT_add_nconf(WOLFSSL_CONF *conf, + WOLFSSL_X509V3_CTX *ctx, const char *section, WOLFSSL_X509 *cert); WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); #define BASIC_CONSTRAINTS_free wolfSSL_BASIC_CONSTRAINTS_free diff --git a/src/wolfssl/quic.h b/src/wolfssl/quic.h index d415242..70ae61c 100644 --- a/src/wolfssl/quic.h +++ b/src/wolfssl/quic.h @@ -1,6 +1,6 @@ /* quic.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/sniffer.h b/src/wolfssl/sniffer.h index 3b5f237..3eabd42 100644 --- a/src/wolfssl/sniffer.h +++ b/src/wolfssl/sniffer.h @@ -1,6 +1,6 @@ /* sniffer.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/sniffer_error.h b/src/wolfssl/sniffer_error.h index 841241d..1794ba8 100644 --- a/src/wolfssl/sniffer_error.h +++ b/src/wolfssl/sniffer_error.h @@ -1,6 +1,6 @@ /* sniffer_error.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index d1a88bd..4bbdf65 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -1,6 +1,6 @@ /* ssl.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -32,8 +32,8 @@ /* for users not using preprocessor flags*/ #include #include +#include #include -#include #include #include #include @@ -67,6 +67,15 @@ #undef OCSP_RESPONSE #endif +#ifdef OPENSSL_ALL + #ifndef WOLFSSL_HAVE_BIO_ADDR + #define WOLFSSL_HAVE_BIO_ADDR + #endif + #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DTLS_MTU) + #define WOLFSSL_DTLS_MTU + #endif +#endif + #ifdef OPENSSL_COEXIST /* mode to allow wolfSSL and OpenSSL to exist together */ #ifdef TEST_OPENSSL_COEXIST @@ -140,6 +149,7 @@ typedef struct WOLFSSL_CTX WOLFSSL_CTX; typedef struct WOLFSSL_STACK WOLFSSL_STACK; typedef struct WOLFSSL_X509 WOLFSSL_X509; +typedef struct WOLFSSL_X509_ACERT WOLFSSL_X509_ACERT; typedef struct WOLFSSL_X509_NAME WOLFSSL_X509_NAME; typedef struct WOLFSSL_X509_NAME_ENTRY WOLFSSL_X509_NAME_ENTRY; typedef struct WOLFSSL_X509_PUBKEY WOLFSSL_X509_PUBKEY; @@ -199,11 +209,11 @@ typedef struct WOLFSSL_X509_LOOKUP_METHOD WOLFSSL_X509_LOOKUP_METHOD; typedef struct WOLFSSL_CRL WOLFSSL_X509_CRL; typedef struct WOLFSSL_X509_STORE WOLFSSL_X509_STORE; typedef struct WOLFSSL_X509_VERIFY_PARAM WOLFSSL_X509_VERIFY_PARAM; -typedef struct WOLFSSL_BIO WOLFSSL_BIO; typedef struct WOLFSSL_BIO_METHOD WOLFSSL_BIO_METHOD; typedef struct WOLFSSL_X509_EXTENSION WOLFSSL_X509_EXTENSION; typedef struct WOLFSSL_ASN1_OBJECT WOLFSSL_ASN1_OBJECT; typedef struct WOLFSSL_ASN1_OTHERNAME WOLFSSL_ASN1_OTHERNAME; +typedef struct WOLFSSL_ASN1_OTHERNAME OTHERNAME; typedef struct WOLFSSL_X509V3_CTX WOLFSSL_X509V3_CTX; typedef struct WOLFSSL_v3_ext_method WOLFSSL_v3_ext_method; typedef struct WOLFSSL_OBJ_NAME WOLFSSL_OBJ_NAME; @@ -237,6 +247,9 @@ typedef int (*WOLFSSL_X509_STORE_CTX_check_crl_cb)(WOLFSSL_X509_STORE_CTX *, struct WOLFSSL_OBJ_NAME { int type; + int alias; + const char *name; + const char *data; }; struct WOLFSSL_AUTHORITY_KEYID { @@ -474,7 +487,8 @@ enum BIO_TYPE { WOLFSSL_BIO_BIO = 5, WOLFSSL_BIO_FILE = 6, WOLFSSL_BIO_BASE64 = 7, - WOLFSSL_BIO_MD = 8 + WOLFSSL_BIO_MD = 8, + WOLFSSL_BIO_DGRAM = 9 }; enum BIO_FLAGS { @@ -537,38 +551,6 @@ struct WOLFSSL_BIO_METHOD { typedef long (*wolf_bio_info_cb)(WOLFSSL_BIO *bio, int event, const char *parg, int iarg, long larg, long return_value); -struct WOLFSSL_BIO { - WOLFSSL_BUF_MEM* mem_buf; - WOLFSSL_BIO_METHOD* method; - WOLFSSL_BIO* prev; /* previous in chain */ - WOLFSSL_BIO* next; /* next in chain */ - WOLFSSL_BIO* pair; /* BIO paired with */ - void* heap; /* user heap hint */ - void* ptr; /* WOLFSSL, file descriptor, MD, or mem buf */ - void* usrCtx; /* user set pointer */ - char* ip; /* IP address for wolfIO_TcpConnect */ - word16 port; /* Port for wolfIO_TcpConnect */ - char* infoArg; /* BIO callback argument */ - wolf_bio_info_cb infoCb; /* BIO callback */ - int wrSz; /* write buffer size (mem) */ - int wrSzReset; /* First buffer size (mem) - read ONLY data */ - int wrIdx; /* current index for write buffer */ - int rdIdx; /* current read index */ - int readRq; /* read request */ - int num; /* socket num or length */ - int eof; /* eof flag */ - int flags; - byte type; /* method type */ - byte init:1; /* bio has been initialized */ - byte shutdown:1; /* close flag */ -#ifdef HAVE_EX_DATA - WOLFSSL_CRYPTO_EX_DATA ex_data; -#endif -#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - wolfSSL_Ref ref; -#endif -}; - typedef struct WOLFSSL_COMP_METHOD { int type; /* stunnel dereference */ } WOLFSSL_COMP_METHOD; @@ -618,15 +600,23 @@ struct WOLFSSL_X509_STORE { WOLFSSL_X509_CRL *crl; /* points to cm->crl */ #endif wolfSSL_Ref ref; + WOLF_STACK_OF(WOLFSSL_X509)* certs; + WOLF_STACK_OF(WOLFSSL_X509)* trusted; + WOLF_STACK_OF(WOLFSSL_X509)* owned; + word32 numAdded; /* Number of objs in objs that are in certs sk */ }; #define WOLFSSL_ALWAYS_CHECK_SUBJECT 0x1 #define WOLFSSL_NO_WILDCARDS 0x2 #define WOLFSSL_NO_PARTIAL_WILDCARDS 0x4 +#define WOLFSSL_MULTI_LABEL_WILDCARDS 0x8 +/* Custom to wolfSSL, OpenSSL compat goes up to 0x20 */ +#define WOLFSSL_LEFT_MOST_WILDCARD_ONLY 0x40 #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) #define WOLFSSL_USE_CHECK_TIME 0x2 #define WOLFSSL_NO_CHECK_TIME 0x200000 +#define WOLFSSL_PARTIAL_CHAIN 0x80000 #define WOLFSSL_HOST_NAME_MAX 256 #define WOLFSSL_VPARAM_DEFAULT 0x1 @@ -640,12 +630,13 @@ struct WOLFSSL_X509_STORE { #endif struct WOLFSSL_X509_VERIFY_PARAM { + const char *name; time_t check_time; unsigned int inherit_flags; unsigned long flags; char hostName[WOLFSSL_HOST_NAME_MAX]; - unsigned int hostFlags; - char ipasc[WOLFSSL_MAX_IPSTR]; + unsigned int hostFlags; + char ipasc[WOLFSSL_MAX_IPSTR]; }; #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ @@ -688,7 +679,7 @@ typedef struct WOLFSSL_BUFFER_INFO { struct WOLFSSL_X509_STORE_CTX { WOLFSSL_X509_STORE* store; /* Store full of a CA cert chain */ WOLFSSL_X509* current_cert; /* current X509 (OPENSSL_EXTRA) */ -#ifdef WOLFSSL_ASIO +#if defined(WOLFSSL_ASIO) || defined(OPENSSL_EXTRA) WOLFSSL_X509* current_issuer; /* asio dereference */ #endif WOLFSSL_X509_CHAIN* sesChain; /* pointer to WOLFSSL_SESSION peer chain */ @@ -711,6 +702,13 @@ struct WOLFSSL_X509_STORE_CTX { WOLFSSL_BUFFER_INFO* certs; /* peer certs */ WOLFSSL_X509_STORE_CTX_verify_cb verify_cb; /* verify callback */ void* heap; + int flags; + WOLF_STACK_OF(WOLFSSL_X509)* owned; /* Certs owned by this CTX */ + WOLF_STACK_OF(WOLFSSL_X509)* ctxIntermediates; /* Intermediates specified + * on store ctx init */ + WOLF_STACK_OF(WOLFSSL_X509)* setTrustedSk;/* A trusted stack override + * set with + * X509_STORE_CTX_trusted_stack*/ }; typedef char* WOLFSSL_STRING; @@ -992,6 +990,10 @@ WOLFSSL_API WOLFSSL_METHOD *wolfSSLv23_method(void); #ifndef NO_WOLFSSL_SERVER WOLFSSL_API WOLFSSL_METHOD *wolfDTLSv1_3_server_method_ex(void* heap); WOLFSSL_API WOLFSSL_METHOD *wolfDTLSv1_3_server_method(void); +#endif +#if defined(WOLFSSL_EITHER_SIDE) || defined(OPENSSL_EXTRA) + WOLFSSL_API WOLFSSL_METHOD *wolfDTLSv1_3_method_ex(void* heap); + WOLFSSL_API WOLFSSL_METHOD *wolfDTLSv1_3_method(void); #endif WOLFSSL_API int wolfSSL_dtls13_has_pending_msg(WOLFSSL *ssl); #endif /* WOLFSSL_DTLS13 */ @@ -1005,6 +1007,8 @@ WOLFSSL_API int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, WOLFSSL_API int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output, word32* outputLen); +WOLFSSL_API void wolfSSL_CTX_SetEchEnable(WOLFSSL_CTX* ctx, byte enable); + WOLFSSL_API int wolfSSL_SetEchConfigsBase64(WOLFSSL* ssl, char* echConfigs64, word32 echConfigs64Len); @@ -1013,6 +1017,8 @@ WOLFSSL_API int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, WOLFSSL_API int wolfSSL_GetEchConfigs(WOLFSSL* ssl, byte* echConfigs, word32* echConfigsLen); + +WOLFSSL_API void wolfSSL_SetEchEnable(WOLFSSL* ssl, byte enable); #endif /* WOLFSSL_TLS13 && HAVE_ECH */ #ifdef HAVE_POLY1305 @@ -1103,6 +1109,8 @@ WOLFSSL_API int wolfSSL_CTX_load_verify_locations_ex( WOLFSSL_CTX* ctx, const char* file, const char* path, word32 flags); WOLFSSL_ABI WOLFSSL_API int wolfSSL_CTX_load_verify_locations( WOLFSSL_CTX* ctx, const char* file, const char* path); +WOLFSSL_API int wolfSSL_CTX_load_verify_locations_compat( + WOLFSSL_CTX* ctx, const char* file, const char* path); #ifndef _WIN32 WOLFSSL_API const char** wolfSSL_get_system_CA_dirs(word32* num); #endif /* !_WIN32 */ @@ -1143,6 +1151,7 @@ WOLFSSL_API int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx); #ifdef OPENSSL_EXTRA WOLFSSL_API int wolfSSL_set_ecdh_auto(WOLFSSL* ssl, int onoff); WOLFSSL_API int wolfSSL_CTX_set_ecdh_auto(WOLFSSL_CTX* ctx, int onoff); +WOLFSSL_API int wolfSSL_CTX_set_dh_auto(WOLFSSL_CTX* ctx, int onoff); WOLFSSL_API int wolfSSL_get_signature_nid(WOLFSSL* ssl, int* nid); WOLFSSL_API int wolfSSL_get_signature_type_nid(const WOLFSSL* ssl, int* nid); WOLFSSL_API int wolfSSL_get_peer_signature_nid(WOLFSSL* ssl, int* nid); @@ -1272,11 +1281,18 @@ WOLFSSL_API int wolfSSL_SetServerID(WOLFSSL* ssl, const unsigned char* id, int WOLFSSL_API int wolfSSL_BIO_new_bio_pair(WOLFSSL_BIO** bio1_p, size_t writebuf1, WOLFSSL_BIO** bio2_p, size_t writebuf2); +WOLFSSL_API int wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, + unsigned char *em, const unsigned char *mHash, + const WOLFSSL_EVP_MD *hashAlg, const WOLFSSL_EVP_MD *mgf1Hash, + int saltLen); WOLFSSL_API int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *EM, const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen); +WOLFSSL_API int wolfSSL_RSA_verify_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, + const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, + const WOLFSSL_EVP_MD *mgf1Hash, const unsigned char *em, int saltLen); WOLFSSL_API int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, const unsigned char *EM, int saltLen); @@ -1482,10 +1498,18 @@ WOLFSSL_API int wolfSSL_dtls_free_peer(void* addr); WOLFSSL_API int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz); WOLFSSL_API int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz); +#if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS) WOLFSSL_API int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx); WOLFSSL_API int wolfSSL_dtls_set_sctp(WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, unsigned short); -WOLFSSL_API int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, unsigned short); +#endif +#if (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)) && \ + defined(WOLFSSL_DTLS) +WOLFSSL_API int wolfSSL_CTX_dtls_set_mtu(WOLFSSL_CTX* ctx, unsigned short mtu); +WOLFSSL_API int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, unsigned short mtu); +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) +WOLFSSL_API int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu); +#endif +#endif #ifdef WOLFSSL_SRTP @@ -1562,6 +1586,7 @@ WOLFSSL_API WOLFSSL_STACK* wolfSSL_shallow_sk_dup(WOLFSSL_STACK* sk); WOLFSSL_API int wolfSSL_sk_push_node(WOLFSSL_STACK** stack, WOLFSSL_STACK* in); WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx); WOLFSSL_API int wolfSSL_sk_push(WOLFSSL_STACK *st, const void *data); +WOLFSSL_API int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx); #if defined(HAVE_OCSP) || defined(HAVE_CRL) || (defined(WOLFSSL_CUSTOM_OID) && \ defined(WOLFSSL_ASN_TEMPLATE) && defined(HAVE_OID_DECODING)) @@ -1647,6 +1672,8 @@ WOLFSSL_API void wolfSSL_ACCESS_DESCRIPTION_free(WOLFSSL_ACCESS_DESCRIPTION* a); WOLFSSL_API void wolfSSL_sk_X509_EXTENSION_pop_free( WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, void (*f) (WOLFSSL_X509_EXTENSION*)); +WOLFSSL_API void wolfSSL_sk_X509_EXTENSION_free( + WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk); WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* wolfSSL_sk_X509_EXTENSION_new_null(void); WOLFSSL_API WOLFSSL_ASN1_OBJECT* wolfSSL_ASN1_OBJECT_new(void); WOLFSSL_API WOLFSSL_ASN1_OBJECT* wolfSSL_ASN1_OBJECT_dup(WOLFSSL_ASN1_OBJECT* obj); @@ -1664,7 +1691,7 @@ WOLFSSL_API int wolfSSL_ASN1_STRING_to_UTF8(unsigned char **out, WOLFSSL_ASN1_ST WOLFSSL_API int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s); WOLFSSL_API int wolfSSL_sk_X509_EXTENSION_num(WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_sk_X509_EXTENSION_value( - WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int idx); + const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int idx); WOLFSSL_API int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data); #ifdef HAVE_EX_DATA_CLEANUP_HOOKS WOLFSSL_API int wolfSSL_set_ex_data_with_cleanup( @@ -1728,8 +1755,8 @@ WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref(WOLF_STACK_OF(WOLFSSL_X509)* chain); #endif -WOLFSSL_API int wolfSSL_OCSP_parse_url(char* url, char** host, char** port, - char** path, int* ssl); +WOLFSSL_API int wolfSSL_OCSP_parse_url(const char* url, char** host, + char** port, char** path, int* ssl); #ifndef NO_BIO #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L @@ -1764,6 +1791,7 @@ WOLFSSL_API WOLFSSL_BIO_METHOD* wolfSSL_BIO_f_buffer(void); WOLFSSL_API long wolfSSL_BIO_set_write_buffer_size(WOLFSSL_BIO* bio, long size); WOLFSSL_API WOLFSSL_BIO_METHOD* wolfSSL_BIO_f_ssl(void); WOLFSSL_API WOLFSSL_BIO* wolfSSL_BIO_new_socket(int sfd, int flag); +WOLFSSL_API WOLFSSL_BIO* wolfSSL_BIO_new_dgram(int fd, int closeF); WOLFSSL_API int wolfSSL_BIO_eof(WOLFSSL_BIO* b); WOLFSSL_API WOLFSSL_BIO_METHOD* wolfSSL_BIO_s_mem(void); @@ -1812,6 +1840,8 @@ WOLFSSL_API long wolfSSL_BIO_set_fd(WOLFSSL_BIO* b, int fd, int flag); #endif WOLFSSL_API int wolfSSL_BIO_set_close(WOLFSSL_BIO *b, long flag); WOLFSSL_API void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr); +WOLFSSL_API void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd); +WOLFSSL_API void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr); WOLFSSL_API int wolfSSL_BIO_method_type(const WOLFSSL_BIO *b); #ifndef NO_FILESYSTEM @@ -1821,6 +1851,7 @@ WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_fd(int fd, int close_flag); WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_bio(void); WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_socket(void); +WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_datagram(void); WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_connect(const char *str); WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_accept(const char *port); @@ -1844,6 +1875,10 @@ WOLFSSL_API int wolfSSL_BIO_ctrl_reset_read_request(WOLFSSL_BIO *b); WOLFSSL_API int wolfSSL_BIO_nread0(WOLFSSL_BIO *bio, char **buf); WOLFSSL_API int wolfSSL_BIO_nread(WOLFSSL_BIO *bio, char **buf, int num); WOLFSSL_API int wolfSSL_BIO_nwrite(WOLFSSL_BIO *bio, char **buf, int num); +#if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_BIO_NO_FLOW_STATS) +WOLFSSL_API word64 wolfSSL_BIO_number_read(WOLFSSL_BIO *bio); +WOLFSSL_API word64 wolfSSL_BIO_number_written(WOLFSSL_BIO *bio); +#endif WOLFSSL_API int wolfSSL_BIO_reset(WOLFSSL_BIO *bio); WOLFSSL_API int wolfSSL_BIO_seek(WOLFSSL_BIO *bio, int ofs); @@ -1856,7 +1891,14 @@ WOLFSSL_API int wolfSSL_BIO_set_mem_buf(WOLFSSL_BIO* bio, WOLFSSL_BUF_MEM* bufMe int closeFlag); #endif WOLFSSL_API int wolfSSL_BIO_get_len(WOLFSSL_BIO *bio); -#endif + +#ifdef WOLFSSL_HAVE_BIO_ADDR +WOLFSSL_API WOLFSSL_BIO_ADDR *wolfSSL_BIO_ADDR_new(void); +WOLFSSL_API void wolfSSL_BIO_ADDR_free(WOLFSSL_BIO_ADDR *addr); +WOLFSSL_API void wolfSSL_BIO_ADDR_clear(WOLFSSL_BIO_ADDR *addr); +#endif /* WOLFSSL_HAVE_BIO_ADDR */ + +#endif /* !NO_BIO */ WOLFSSL_API void wolfSSL_RAND_screen(void); WOLFSSL_API const char* wolfSSL_RAND_file_name(char* fname, unsigned long len); @@ -1868,9 +1910,14 @@ WOLFSSL_API void wolfSSL_RAND_Cleanup(void); WOLFSSL_API void wolfSSL_RAND_add(const void* add, int len, double entropy); WOLFSSL_API int wolfSSL_RAND_poll(void); +#ifndef NO_WOLFSSL_STUB WOLFSSL_API WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void); WOLFSSL_API WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void); WOLFSSL_API int wolfSSL_COMP_add_compression_method(int method, void* data); +WOLFSSL_API const char *wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp); +WOLFSSL_API const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl); +WOLFSSL_API const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl); +#endif /* !NO_WOLFSSL_STUB */ WOLFSSL_API unsigned long wolfSSL_thread_id(void); WOLFSSL_API void wolfSSL_set_id_callback(unsigned long (*f)(void)); @@ -1948,6 +1995,8 @@ WOLFSSL_API unsigned char* wolfSSL_X509_get_authorityKeyID( WOLFSSL_X509* x509, unsigned char* dst, int* dstLen); WOLFSSL_API unsigned char* wolfSSL_X509_get_subjectKeyID( WOLFSSL_X509* x509, unsigned char* dst, int* dstLen); +WOLFSSL_API const WOLFSSL_ASN1_STRING *wolfSSL_X509_get0_subject_key_id( + WOLFSSL_X509 *x509); WOLFSSL_API int wolfSSL_X509_verify(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey); #ifdef WOLFSSL_CERT_REQ @@ -1996,7 +2045,7 @@ WOLFSSL_API int wolfSSL_ASN1_STRING_set(WOLFSSL_ASN1_STRING* asn1, WOLFSSL_API unsigned char* wolfSSL_ASN1_STRING_data(WOLFSSL_ASN1_STRING* asn); WOLFSSL_API const unsigned char* wolfSSL_ASN1_STRING_get0_data( const WOLFSSL_ASN1_STRING* asn); -WOLFSSL_API int wolfSSL_ASN1_STRING_length(WOLFSSL_ASN1_STRING* asn); +WOLFSSL_API int wolfSSL_ASN1_STRING_length(const WOLFSSL_ASN1_STRING* asn); WOLFSSL_API int wolfSSL_ASN1_STRING_copy(WOLFSSL_ASN1_STRING* dst, const WOLFSSL_ASN1_STRING* src); WOLFSSL_API int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx); @@ -2024,6 +2073,8 @@ WOLFSSL_API int wolfSSL_X509_STORE_add_cert( WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_get0_param( const WOLFSSL_X509_STORE *ctx); +WOLFSSL_API int wolfSSL_X509_STORE_set1_param(WOLFSSL_X509_STORE *ctx, + WOLFSSL_X509_VERIFY_PARAM *param); WOLFSSL_API WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain( WOLFSSL_X509_STORE_CTX* ctx); WOLFSSL_API WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get1_chain( @@ -2056,11 +2107,15 @@ WOLFSSL_API WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY_bio( WOLFSSL_BIO* bio, WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey); WOLFSSL_API WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( WOLFSSL_PKCS8_PRIV_KEY_INFO** pkey, const unsigned char** keyBuf, long keyLen); +WOLFSSL_API int wolfSSL_i2d_PKCS8_PKEY(WOLFSSL_PKCS8_PRIV_KEY_INFO* key, + unsigned char** pp); WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY** out); WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY(WOLFSSL_EVP_PKEY** key, const unsigned char** in, long inSz); WOLFSSL_API int wolfSSL_i2d_PUBKEY(const WOLFSSL_EVP_PKEY *key, unsigned char **der); +WOLFSSL_API int wolfSSL_i2d_X509_PUBKEY(WOLFSSL_X509_PUBKEY* x509_PubKey, + unsigned char** der); WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** pkey, const unsigned char ** in, long inSz); WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey(int type, @@ -2113,6 +2168,10 @@ WOLFSSL_API int wolfSSL_X509_VERIFY_PARAM_set1_ip( WOLFSSL_X509_VERIFY_PARAM* param, const unsigned char* ip, size_t iplen); WOLFSSL_API int wolfSSL_X509_VERIFY_PARAM_set1(WOLFSSL_X509_VERIFY_PARAM* to, const WOLFSSL_X509_VERIFY_PARAM* from); +WOLFSSL_API const WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_VERIFY_PARAM_lookup( + const char *name); +WOLFSSL_API int wolfSSL_X509_VERIFY_PARAM_inherit(WOLFSSL_X509_VERIFY_PARAM *to, + const WOLFSSL_X509_VERIFY_PARAM *from); WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, const char *file, int type); WOLFSSL_API int wolfSSL_X509_load_cert_crl_file(WOLFSSL_X509_LOOKUP *ctx, @@ -2132,7 +2191,7 @@ WOLFSSL_API WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER( const unsigned char** in, long inSz); WOLFSSL_API int wolfSSL_i2d_ASN1_INTEGER(const WOLFSSL_ASN1_INTEGER* a, - unsigned char** out); + unsigned char** pp); WOLFSSL_API int wolfSSL_ASN1_TIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_TIME* asnTime); @@ -2440,12 +2499,6 @@ enum { OCSP_TRUSTOTHER = 512, OCSP_RESPID_KEY = 1024, OCSP_NOTIME = 2048, - - /* OCSP Types */ - OCSP_CERTID = 2, - OCSP_REQUEST = 4, - OCSP_RESPONSE = 8, - OCSP_BASICRESP = 16, #endif SSL_ST_CONNECT = 0x1000, @@ -2580,6 +2633,14 @@ WOLFSSL_API void wolfSSL_ERR_print_errors(WOLFSSL_BIO *bio); enum { /* ssl Constants */ WOLFSSL_ERROR_NONE = 0, /* for most functions */ WOLFSSL_FAILURE = 0, /* for some functions */ + + #if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && \ + (defined(BUILDING_WOLFSSL) || \ + defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES_ALWAYS)) + #define WOLFSSL_FAILURE WC_ERR_TRACE(WOLFSSL_FAILURE) + #define CONST_NUM_ERR_WOLFSSL_FAILURE 0 + #endif + WOLFSSL_SUCCESS = 1, /* WOLFSSL_SHUTDOWN_NOT_DONE is returned by wolfSSL_shutdown and @@ -2597,16 +2658,6 @@ enum { /* ssl Constants */ WOLFSSL_SHUTDOWN_NOT_DONE = 2, #endif - WOLFSSL_ALPN_NOT_FOUND = -9, - WOLFSSL_BAD_CERTTYPE = -8, - WOLFSSL_BAD_STAT = -7, - WOLFSSL_BAD_PATH = -6, - WOLFSSL_BAD_FILETYPE = -5, - WOLFSSL_BAD_FILE = -4, - WOLFSSL_NOT_IMPLEMENTED = -3, - WOLFSSL_UNKNOWN = -2, - WOLFSSL_FATAL_ERROR = -1, - WOLFSSL_FILETYPE_ASN1 = CTC_FILETYPE_ASN1, WOLFSSL_FILETYPE_PEM = CTC_FILETYPE_PEM, WOLFSSL_FILETYPE_DEFAULT = CTC_FILETYPE_ASN1, /* ASN1 */ @@ -2630,14 +2681,15 @@ enum { /* ssl Constants */ (WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE | WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP), + /* These values match OpenSSL values for corresponding names. */ + WOLFSSL_ERROR_SSL = 1, WOLFSSL_ERROR_WANT_READ = 2, WOLFSSL_ERROR_WANT_WRITE = 3, - WOLFSSL_ERROR_WANT_CONNECT = 7, - WOLFSSL_ERROR_WANT_ACCEPT = 8, + WOLFSSL_ERROR_WANT_X509_LOOKUP = 4, WOLFSSL_ERROR_SYSCALL = 5, - WOLFSSL_ERROR_WANT_X509_LOOKUP = 83, WOLFSSL_ERROR_ZERO_RETURN = 6, - WOLFSSL_ERROR_SSL = 85, + WOLFSSL_ERROR_WANT_CONNECT = 7, + WOLFSSL_ERROR_WANT_ACCEPT = 8, WOLFSSL_SENT_SHUTDOWN = 1, WOLFSSL_RECEIVED_SHUTDOWN = 2, @@ -2808,6 +2860,8 @@ WOLFSSL_API int wolfSSL_ASN1_TIME_compare(const WOLFSSL_ASN1_TIME *a, #ifdef OPENSSL_EXTRA WOLFSSL_API WOLFSSL_ASN1_TIME *wolfSSL_ASN1_TIME_set(WOLFSSL_ASN1_TIME *s, time_t t); WOLFSSL_API int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *s, const char *str); +WOLFSSL_API int wolfSSL_ASN1_TIME_set_string_X509(WOLFSSL_ASN1_TIME *t, + const char *str); #endif WOLFSSL_API int wolfSSL_sk_num(const WOLFSSL_STACK* sk); @@ -2871,6 +2925,10 @@ WOLFSSL_API int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, date check and signature check */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn); +#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) +WOLFSSL_API const char *wolfSSL_get0_peername(WOLFSSL *ssl); +#endif + /* need to call once to load library (session cache) */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_Init(void); /* call when done to cleanup/free session cache mutex / resources */ @@ -2914,6 +2972,7 @@ WOLFSSL_API WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int /* free X509 */ #define wolfSSL_FreeX509(x509) wolfSSL_X509_free((x509)) WOLFSSL_ABI WOLFSSL_API void wolfSSL_X509_free(WOLFSSL_X509* x509); + /* get index cert in PEM */ WOLFSSL_API int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, unsigned char* buf, int inLen, int* outLen); @@ -2943,6 +3002,8 @@ WOLFSSL_API WOLFSSL_X509* #ifdef WOLFSSL_CERT_REQ WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_REQ_d2i(WOLFSSL_X509** x509, const unsigned char* in, int len); +WOLFSSL_API WOLFSSL_X509* wolfSSL_d2i_X509_REQ_INFO(WOLFSSL_X509** req, + const unsigned char** in, int len); #endif WOLFSSL_API int wolfSSL_i2d_X509(WOLFSSL_X509* x509, unsigned char** out); WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL(WOLFSSL_X509_CRL **crl, @@ -2971,6 +3032,45 @@ WOLFSSL_API WOLFSSL_X509_CRL* wolfSSL_X509_CRL_dup(const WOLFSSL_X509_CRL* crl); WOLFSSL_API void wolfSSL_X509_CRL_free(WOLFSSL_X509_CRL *crl); #endif +#if defined(WOLFSSL_ACERT) && \ + (defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA)) +WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new_ex(void * heap); +WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new(void); +WOLFSSL_API void wolfSSL_X509_ACERT_init(WOLFSSL_X509_ACERT * x509, + int dynamic, void * heap); +WOLFSSL_API void wolfSSL_X509_ACERT_free(WOLFSSL_X509_ACERT* x509); +#ifndef NO_WOLFSSL_STUB +WOLFSSL_API int wolfSSL_X509_ACERT_sign(WOLFSSL_X509_ACERT * x509, + WOLFSSL_EVP_PKEY * pkey, + const WOLFSSL_EVP_MD * md); +#endif /* !NO_WOLFSSL_STUB */ +WOLFSSL_API int wolfSSL_X509_ACERT_verify(WOLFSSL_X509_ACERT* x509, + WOLFSSL_EVP_PKEY* pkey); +#if defined(OPENSSL_EXTRA) +WOLFSSL_API int wolfSSL_X509_ACERT_get_signature_nid( + const WOLFSSL_X509_ACERT* x); +WOLFSSL_API int wolfSSL_X509_ACERT_print(WOLFSSL_BIO* bio, + WOLFSSL_X509_ACERT* x509_acert); +WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_PEM_read_bio_X509_ACERT( + WOLFSSL_BIO *bp, WOLFSSL_X509_ACERT **x, wc_pem_password_cb *cb, void *u); +WOLFSSL_API long wolfSSL_X509_ACERT_get_version(const WOLFSSL_X509_ACERT *x); +#endif /* OPENSSL_EXTRA */ +WOLFSSL_API int wolfSSL_X509_ACERT_get_attr_buf(const WOLFSSL_X509_ACERT* x509, + const byte ** rawAttr, + word32 * rawAttrLen); +WOLFSSL_API int wolfSSL_X509_ACERT_get_serial_number(WOLFSSL_X509_ACERT* x509, + unsigned char* in, + int * inOutSz); +WOLFSSL_API int wolfSSL_X509_ACERT_version(WOLFSSL_X509_ACERT* x509); +WOLFSSL_API int wolfSSL_X509_ACERT_get_signature(WOLFSSL_X509_ACERT* x509, + unsigned char* buf, + int* bufSz); +WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer_ex( + const unsigned char* buf, int sz, int format, void * heap); +WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer( + const unsigned char* buf, int sz, int format); +#endif /* WOLFSSL_ACERT && (OPENSSL_EXTRA_X509_SMALL || OPENSSL_EXTRA) */ + WOLFSSL_API const WOLFSSL_ASN1_INTEGER* wolfSSL_X509_REVOKED_get0_serial_number(const WOLFSSL_X509_REVOKED *rev); @@ -3089,11 +3189,14 @@ WOLFSSL_API int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* key, unsigned int len, #include #elif defined(ARDUINO) /* TODO board specific */ + #elif defined(NUCLEUS_PLUS_2_3) + #include "services/sys/uio.h" #elif !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_IAR_ARM) && \ !defined(WOLFSSL_PICOTCP) && !defined(WOLFSSL_ROWLEY_ARM) && \ !defined(WOLFSSL_EMBOS) && !defined(WOLFSSL_FROSTED) && \ !defined(WOLFSSL_CHIBIOS) && !defined(WOLFSSL_CONTIKI) && \ - !defined(WOLFSSL_ZEPHYR) && !defined(NETOS) + !defined(WOLFSSL_ZEPHYR) && !defined(NETOS) && \ + !defined(WOLFSSL_NDS) #include #endif /* allow writev style writing */ @@ -3210,18 +3313,6 @@ WOLFSSL_API void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCt WOLFSSL_API int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, const byte* secret, word32 secretSz); -/* I/O Callback default errors */ -enum IOerrors { - WOLFSSL_CBIO_ERR_GENERAL = -1, /* general unexpected err */ - WOLFSSL_CBIO_ERR_WANT_READ = -2, /* need to call read again */ - WOLFSSL_CBIO_ERR_WANT_WRITE = -2, /* need to call write again */ - WOLFSSL_CBIO_ERR_CONN_RST = -3, /* connection reset */ - WOLFSSL_CBIO_ERR_ISR = -4, /* interrupt */ - WOLFSSL_CBIO_ERR_CONN_CLOSE = -5, /* connection closed or epipe */ - WOLFSSL_CBIO_ERR_TIMEOUT = -6 /* socket timeout */ -}; - - /* CA cache callbacks */ enum { WOLFSSL_SSLV3 = 0, @@ -3234,7 +3325,9 @@ enum { WOLFSSL_DTLSV1_3 = 7, WOLFSSL_USER_CA = 1, /* user added as trusted */ - WOLFSSL_CHAIN_CA = 2 /* added to cache from trusted chain */ + WOLFSSL_CHAIN_CA = 2, /* added to cache from trusted chain */ + WOLFSSL_TEMP_CA = 3 /* Temp intermediate CA, only for use by + * X509_STORE */ }; WOLFSSL_ABI WOLFSSL_API WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl); @@ -3259,6 +3352,8 @@ WOLFSSL_API int wolfSSL_SetVersion(WOLFSSL* ssl, int version); typedef void (*CallbackCACache)(unsigned char* der, int sz, int type); typedef void (*CbMissingCRL)(const char* url); +typedef int (*crlErrorCb)(int ret, WOLFSSL_CRL* crl, WOLFSSL_CERT_MANAGER* cm, + void* ctx); typedef int (*CbOCSPIO)(void*, const char*, int, unsigned char*, int, unsigned char**); typedef void (*CbOCSPRespFree)(void*,unsigned char*); @@ -3292,6 +3387,21 @@ WOLFSSL_API void wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptM WOLFSSL_API void wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx); WOLFSSL_API void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl); +#ifdef WOLFSSL_THREADED_CRYPT + #ifndef WOLFSSL_THREADED_CRYPT_CNT + #define WOLFSSL_THREADED_CRYPT_CNT 16 + #endif + +typedef void (*WOLFSSL_THREAD_SIGNAL)(void* ctx, WOLFSSL* ssl); + +WOLFSSL_API int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx); +WOLFSSL_API int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx); +WOLFSSL_API int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx); +WOLFSSL_API int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx, + WOLFSSL_THREAD_SIGNAL signal, void* ctx); +#endif + + typedef int (*CallbackVerifyDecrypt)(WOLFSSL* ssl, unsigned char* decOut, const unsigned char* decIn, unsigned int decSz, int content, int verify, unsigned int* padSz, @@ -3332,7 +3442,7 @@ enum { WOLFSSL_BLOCK_TYPE = 2, WOLFSSL_STREAM_TYPE = 3, WOLFSSL_AEAD_TYPE = 4, - WOLFSSL_TLS_HMAC_INNER_SZ = 13 /* SEQ_SZ + ENUM + VERSION_SZ + LEN_SZ */ + WOLFSSL_TLS_HMAC_INNER_SZ = 13, /* SEQ_SZ + ENUM + VERSION_SZ + LEN_SZ */ }; /* for GetBulkCipher and internal use @@ -3667,8 +3777,7 @@ WOLFSSL_API void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, WOLFSSL_API void wolfSSL_CertManagerFree(WOLFSSL_CERT_MANAGER* cm); WOLFSSL_API int wolfSSL_CertManager_up_ref(WOLFSSL_CERT_MANAGER* cm); -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB WOLFSSL_API void wolfSSL_CertManagerSetUnknownExtCallback( WOLFSSL_CERT_MANAGER* cm, wc_UnknownExtCallback cb); @@ -3708,6 +3817,8 @@ WOLFSSL_API void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, int type); WOLFSSL_API int wolfSSL_CertManagerSetCRL_Cb(WOLFSSL_CERT_MANAGER* cm, CbMissingCRL cb); + WOLFSSL_API int wolfSSL_CertManagerSetCRL_ErrorCb(WOLFSSL_CERT_MANAGER* cm, + crlErrorCb cb, void* ctx); WOLFSSL_API int wolfSSL_CertManagerFreeCRL(WOLFSSL_CERT_MANAGER* cm); #ifdef HAVE_CRL_IO WOLFSSL_API int wolfSSL_CertManagerSetCRL_IOCb(WOLFSSL_CERT_MANAGER* cm, @@ -3751,6 +3862,8 @@ WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_STORE_get1_certs( WOLFSSL_API int wolfSSL_LoadCRLBuffer(WOLFSSL* ssl, const unsigned char* buff, long sz, int type); WOLFSSL_API int wolfSSL_SetCRL_Cb(WOLFSSL* ssl, CbMissingCRL cb); + WOLFSSL_API int wolfSSL_SetCRL_ErrorCb(WOLFSSL* ssl, crlErrorCb cb, + void* ctx); #ifdef HAVE_CRL_IO WOLFSSL_API int wolfSSL_SetCRL_IOCb(WOLFSSL* ssl, CbCrlIO cb); #endif @@ -3768,6 +3881,8 @@ WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_STORE_get1_certs( WOLFSSL_API int wolfSSL_CTX_LoadCRLBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, int type); WOLFSSL_API int wolfSSL_CTX_SetCRL_Cb(WOLFSSL_CTX* ctx, CbMissingCRL cb); + WOLFSSL_API int wolfSSL_CTX_SetCRL_ErrorCb(WOLFSSL_CTX* ctx, crlErrorCb cb, + void* cbCtx); #ifdef HAVE_CRL_IO WOLFSSL_API int wolfSSL_CTX_SetCRL_IOCb(WOLFSSL_CTX* ctx, CbCrlIO cb); #endif @@ -4046,9 +4161,9 @@ enum { WOLFSSL_FFDHE_8192 = 260, #ifdef HAVE_PQC - /* These group numbers were taken from OQS's openssl fork, see: - * https://github.com/open-quantum-safe/openssl/blob/OQS-OpenSSL_1_1_1-stable/ - * oqs-template/oqs-kem-info.md. + /* These group numbers were taken from OQS's openssl provider, see: + * https://github.com/open-quantum-safe/oqs-provider/blob/main/oqs-template/ + * oqs-kem-info.md. * * The levels in the group name refer to the claimed NIST level of each * parameter set. The associated parameter set name is listed as a comment @@ -4062,6 +4177,7 @@ enum { * algorithms have LEVEL2 and LEVEL4 because none of these submissions * included them. */ +#ifndef WOLFSSL_ML_KEM WOLFSSL_PQC_MIN = 570, WOLFSSL_PQC_SIMPLE_MIN = 570, WOLFSSL_KYBER_LEVEL1 = 570, /* KYBER_512 */ @@ -4075,7 +4191,22 @@ enum { WOLFSSL_P521_KYBER_LEVEL5 = 12093, WOLFSSL_PQC_HYBRID_MAX = 12093, WOLFSSL_PQC_MAX = 12093, -#endif +#else + WOLFSSL_PQC_MIN = 583, + WOLFSSL_PQC_SIMPLE_MIN = 583, + WOLFSSL_KYBER_LEVEL1 = 583, /* ML-KEM 512 */ + WOLFSSL_KYBER_LEVEL3 = 584, /* ML-KEM 768 */ + WOLFSSL_KYBER_LEVEL5 = 585, /* ML-KEM 1024 */ + WOLFSSL_PQC_SIMPLE_MAX = 585, + + WOLFSSL_PQC_HYBRID_MIN = 12103, + WOLFSSL_P256_KYBER_LEVEL1 = 12103, + WOLFSSL_P384_KYBER_LEVEL3 = 12104, + WOLFSSL_P521_KYBER_LEVEL5 = 12105, + WOLFSSL_PQC_HYBRID_MAX = 12105, + WOLFSSL_PQC_MAX = 12105, +#endif /* WOLFSSL_ML_KEM */ +#endif /* HAVE_PQC */ }; enum { @@ -4140,7 +4271,25 @@ WOLFSSL_API long wolfSSL_SSL_get_secure_renegotiation_support(WOLFSSL* ssl); #ifdef HAVE_SESSION_TICKET #if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_WOLFSSL_SERVER) - #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \ + #ifdef WOLFSSL_TICKET_ENC_CBC_HMAC + #if defined(WOLFSSL_TICKET_ENC_HMAC_SHA512) + #define WOLFSSL_TICKET_ENC_HMAC WC_HASH_TYPE_SHA512 + #define WOLFSSL_TICKET_HMAC_KEY_SZ 64 + #elif defined(WOLFSSL_TICKET_ENC_HMAC_SHA384) + #define WOLFSSL_TICKET_ENC_HMAC WC_HASH_TYPE_SHA384 + #define WOLFSSL_TICKET_HMAC_KEY_SZ 48 + #else + #define WOLFSSL_TICKET_ENC_HMAC WC_HASH_TYPE_SHA256 + #define WOLFSSL_TICKET_HMAC_KEY_SZ 32 + #endif + #ifdef WOLFSSL_TICKET_ENC_AES256_CBC + #define WOLFSSL_TICKET_KEY_SZ \ + (AES_256_KEY_SIZE + WOLFSSL_TICKET_HMAC_KEY_SZ) + #else + #define WOLFSSL_TICKET_KEY_SZ \ + (AES_128_KEY_SIZE + WOLFSSL_TICKET_HMAC_KEY_SZ) + #endif + #elif defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \ !defined(WOLFSSL_TICKET_ENC_AES128_GCM) && \ !defined(WOLFSSL_TICKET_ENC_AES256_GCM) #define WOLFSSL_TICKET_KEY_SZ CHACHA20_POLY1305_AEAD_KEYSIZE @@ -4171,7 +4320,11 @@ WOLFSSL_API int wolfSSL_send_SessionTicket(WOLFSSL* ssl); #define WOLFSSL_TICKET_NAME_SZ 16 #define WOLFSSL_TICKET_IV_SZ 16 -#define WOLFSSL_TICKET_MAC_SZ 32 +#ifndef WOLFSSL_TICKET_ENC_CBC_HMAC + #define WOLFSSL_TICKET_MAC_SZ 32 +#else + #define WOLFSSL_TICKET_MAC_SZ WOLFSSL_TICKET_HMAC_KEY_SZ +#endif enum TicketEncRet { WOLFSSL_TICKET_RET_FATAL = -1, /* fatal error, don't use ticket */ @@ -4448,7 +4601,6 @@ WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_dup( WOLFSSL_X509_EXTENSION* src); WOLFSSL_API int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk, WOLFSSL_X509_EXTENSION* ext); -WOLFSSL_API void wolfSSL_sk_X509_EXTENSION_free(WOLFSSL_STACK* sk); WOLFSSL_API void wolfSSL_X509_EXTENSION_free(WOLFSSL_X509_EXTENSION* ext_to_free); WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_new_x509_ext(void); #endif @@ -4819,6 +4971,10 @@ WOLFSSL_API int wolfSSL_ASN1_BIT_STRING_get_bit( const WOLFSSL_ASN1_BIT_STRING* str, int i); WOLFSSL_API int wolfSSL_ASN1_BIT_STRING_set_bit( WOLFSSL_ASN1_BIT_STRING* str, int pos, int val); +WOLFSSL_API int wolfSSL_i2d_ASN1_BIT_STRING(const WOLFSSL_ASN1_BIT_STRING* bstr, + unsigned char** pp); +WOLFSSL_API WOLFSSL_ASN1_BIT_STRING* wolfSSL_d2i_ASN1_BIT_STRING( + WOLFSSL_ASN1_BIT_STRING** out, const byte** src, long len); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ WOLFSSL_API int wolfSSL_version(WOLFSSL* ssl); @@ -4919,6 +5075,11 @@ WOLFSSL_API WOLFSSL_X509_OBJECT* wolfSSL_X509_OBJECT_new(void); WOLFSSL_API void wolfSSL_X509_OBJECT_free(WOLFSSL_X509_OBJECT *obj); WOLFSSL_API WOLFSSL_X509 *wolfSSL_X509_OBJECT_get0_X509(const WOLFSSL_X509_OBJECT *obj); WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_X509_OBJECT_get0_X509_CRL(WOLFSSL_X509_OBJECT *obj); + +WOLFSSL_API WOLFSSL_X509_OBJECT *wolfSSL_X509_OBJECT_retrieve_by_subject( + WOLF_STACK_OF(WOLFSSL_X509_OBJECT) *sk, + WOLFSSL_X509_LOOKUP_TYPE type, + WOLFSSL_X509_NAME *name); #endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || HAVE_LIGHTY */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) @@ -5191,8 +5352,14 @@ WOLFSSL_API void wolfSSL_X509_ALGOR_free(WOLFSSL_X509_ALGOR *alg); WOLFSSL_API const WOLFSSL_X509_ALGOR* wolfSSL_X509_get0_tbs_sigalg(const WOLFSSL_X509 *x); WOLFSSL_API void wolfSSL_X509_ALGOR_get0(const WOLFSSL_ASN1_OBJECT **paobj, int *pptype, const void **ppval, const WOLFSSL_X509_ALGOR *algor); WOLFSSL_API int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, WOLFSSL_ASN1_OBJECT *aobj, int ptype, void *pval); +WOLFSSL_API int wolfSSL_i2d_X509_ALGOR(const WOLFSSL_X509_ALGOR* alg, + unsigned char** pp); +WOLFSSL_API WOLFSSL_X509_ALGOR* wolfSSL_d2i_X509_ALGOR(WOLFSSL_X509_ALGOR** out, + const byte** src, long len); WOLFSSL_API WOLFSSL_ASN1_TYPE* wolfSSL_ASN1_TYPE_new(void); WOLFSSL_API void wolfSSL_ASN1_TYPE_free(WOLFSSL_ASN1_TYPE* at); +WOLFSSL_API int wolfSSL_i2d_ASN1_TYPE(WOLFSSL_ASN1_TYPE* at, + unsigned char** pp); WOLFSSL_API WOLFSSL_X509_PUBKEY *wolfSSL_X509_PUBKEY_new(void); WOLFSSL_API void wolfSSL_X509_PUBKEY_free(WOLFSSL_X509_PUBKEY *x); WOLFSSL_API WOLFSSL_X509_PUBKEY *wolfSSL_X509_get_X509_PUBKEY(const WOLFSSL_X509* x509); @@ -5207,7 +5374,6 @@ WOLFSSL_API int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) WOLFSSL_API int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp); WOLFSSL_API void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)); WOLFSSL_API WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); -WOLFSSL_API const char* wolfSSL_COMP_get_name(const void* comp); WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, const char *file, const char *dir); WOLFSSL_API int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *ctx, WOLFSSL_X509_CRL *x); WOLFSSL_API int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p); @@ -5239,6 +5405,8 @@ WOLFSSL_API int wolfSSL_X509_get_signature_nid(const WOLFSSL_X509* x); WOLFSSL_API int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, wc_pem_password_cb* cb, void* ctx); +WOLFSSL_API int wolfSSL_PEM_write_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, + PKCS8_PRIV_KEY_INFO* keyInfo); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) WOLFSSL_API int wolfSSL_PEM_write_PKCS8PrivateKey( XFILE fp, WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, @@ -5358,6 +5526,7 @@ WOLFSSL_API int wolfSSL_dtls_cid_get_tx_size(WOLFSSL* ssl, unsigned int* size); WOLFSSL_API int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buffer, unsigned int bufferSz); +WOLFSSL_API int wolfSSL_dtls_cid_max_size(void); #endif /* defined(WOLFSSL_DTLS_CID) */ #ifdef WOLFSSL_DTLS_CH_FRAG diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index 4dd6320..bbe7d0f 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -1,6 +1,6 @@ /* test.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -203,7 +203,9 @@ #include #include #include - #include + #ifndef WOLFSSL_NDS + #include + #endif #include #include #ifdef HAVE_PTHREAD @@ -1099,10 +1101,11 @@ static WC_INLINE void ShowX509Ex(WOLFSSL_X509* x509, const char* hdr, char serialMsg[80]; /* testsuite has multiple threads writing to stdout, get output - message ready to write once */ - strLen = sprintf(serialMsg, " %s", words[3]); + * message ready to write once */ + strLen = XSNPRINTF(serialMsg, sizeof(serialMsg), " %s", words[3]); for (i = 0; i < sz; i++) - sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]); + strLen = XSNPRINTF(serialMsg + strLen, + sizeof(serialMsg) - (size_t)strLen, ":%02x ", serial[i]); printf("%s\n", serialMsg); } @@ -1850,7 +1853,8 @@ static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint, /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */ XSTRNCPY(identity, kIdentityStr, id_max_len); - if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) { + if (wolfSSL_GetVersion(ssl) != WOLFSSL_TLSV1_3 && + wolfSSL_GetVersion(ssl) != WOLFSSL_DTLSV1_3) { /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using * unsigned binary */ key[0] = 0x1a; @@ -1894,7 +1898,8 @@ static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identit if (XSTRCMP(identity, kIdentityStr) != 0) return 0; - if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) { + if (wolfSSL_GetVersion(ssl) != WOLFSSL_TLSV1_3 && + wolfSSL_GetVersion(ssl) != WOLFSSL_DTLSV1_3) { /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using * unsigned binary */ key[0] = 0x1a; @@ -3341,8 +3346,9 @@ static WC_INLINE int myEccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey, ret = BAD_FUNC_ARG; } -#if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_FIPS) && \ - !defined(HAVE_SELFTEST) +#if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \ + (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ + !defined(HAVE_SELFTEST) if (ret == 0) { ret = wc_ecc_set_rng(privKey, wolfSSL_GetRNG(ssl)); } @@ -3901,9 +3907,11 @@ static WC_INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz, { enum wc_HashType hashType = WC_HASH_TYPE_NONE; WC_RNG rng; - int ret; + int ret = 0; word32 idx = 0; RsaKey myKey; + byte* inBuf = (byte*)in; + word32 inBufSz = inSz; byte* keyBuf = (byte*)key; PkCbInfo* cbInfo = (PkCbInfo*)ctx; @@ -3941,17 +3949,40 @@ static WC_INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz, if (ret != 0) return ret; - ret = wc_InitRsaKey(&myKey, NULL); + #ifdef TLS13_RSA_PSS_SIGN_CB_NO_PREHASH + /* With this defined, RSA-PSS sign callback when used from TLS 1.3 + * does not hash data before giving to this callback. User must + * compute hash themselves. */ + if (wolfSSL_GetVersion(ssl) == WOLFSSL_TLSV1_3) { + inBufSz = wc_HashGetDigestSize(hashType); + inBuf = (byte*)XMALLOC(inBufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (inBuf == NULL) { + ret = MEMORY_E; + } + if (ret == 0) { + ret = wc_Hash(hashType, in, inSz, inBuf, inBufSz); + } + } + #endif + + if (ret == 0) { + ret = wc_InitRsaKey(&myKey, NULL); + } if (ret == 0) { ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz); if (ret == 0) { - ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, &myKey, - &rng); + ret = wc_RsaPSS_Sign(inBuf, inBufSz, out, *outSz, hashType, mgf, + &myKey, &rng); } if (ret > 0) { /* save and convert to 0 success */ *outSz = (word32) ret; ret = 0; } + #ifdef TLS13_RSA_PSS_SIGN_CB_NO_PREHASH + if ((inBuf != NULL) && (wolfSSL_GetVersion(ssl) == WOLFSSL_TLSV1_3)) { + XFREE(inBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + #endif wc_FreeRsaKey(&myKey); } wc_FreeRng(&rng); @@ -4826,4 +4857,23 @@ void DEBUG_WRITE_DER(const byte* der, int derSz, const char* fileName); #define DTLS_CID_BUFFER_SIZE 256 +static WC_MAYBE_UNUSED void *mymemmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen) +{ + size_t i, j; + const char* h = (const char*)haystack; + const char* n = (const char*)needle; + if (needlelen > haystacklen) + return NULL; + for (i = 0; i <= haystacklen - needlelen; i++) { + for (j = 0; j < needlelen; j++) { + if (h[i + j] != n[j]) + break; + } + if (j == needlelen) + return (void*)(h + i); + } + return NULL; +} + #endif /* wolfSSL_TEST_H */ diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index 2da6e5e..b494238 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -1,6 +1,6 @@ /* wolfssl_version.h.in * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.7.2" -#define LIBWOLFSSL_VERSION_HEX 0x05007002 +#define LIBWOLFSSL_VERSION_STRING "5.7.4" +#define LIBWOLFSSL_VERSION_HEX 0x05007004 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/aes.h b/src/wolfssl/wolfcrypt/aes.h index 46687da..eaa0c47 100644 --- a/src/wolfssl/wolfcrypt/aes.h +++ b/src/wolfssl/wolfcrypt/aes.h @@ -1,6 +1,6 @@ /* aes.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -327,7 +327,7 @@ struct Aes { int alFd; /* server socket to bind to */ int rdFd; /* socket to read from */ struct msghdr msg; - int dir; /* flag for encrpyt or decrypt */ + int dir; /* flag for encrypt or decrypt */ #ifdef WOLFSSL_AFALG_XILINX_AES word32 msgBuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + GCM_NONCE_MID_SZ)]; @@ -382,15 +382,16 @@ struct Aes { ALIGN16 byte streamData[5 * AES_BLOCK_SIZE]; #else byte* streamData; + word32 streamData_sz; #endif word32 aSz; word32 cSz; byte over; byte aOver; byte cOver; - byte gcmKeySet:1; - byte nonceSet:1; - byte ctrSet:1; + WC_BITFIELD gcmKeySet:1; + WC_BITFIELD nonceSet:1; + WC_BITFIELD ctrSet:1; #endif #ifdef WC_DEBUG_CIPHER_LIFECYCLE void *CipherLifecycleTag; /* used for dummy allocation and initialization, @@ -726,8 +727,17 @@ WOLFSSL_API int wc_AesInit_Label(Aes* aes, const char* label, void* heap, int devId); #endif WOLFSSL_API void wc_AesFree(Aes* aes); +#ifndef WC_NO_CONSTRUCTORS +WOLFSSL_API Aes* wc_AesNew(void* heap, int devId, int *result_code); +WOLFSSL_API int wc_AesDelete(Aes* aes, Aes** aes_p); +#endif #ifdef WOLFSSL_AES_SIV +typedef struct AesSivAssoc { + const byte* assoc; + word32 assocSz; +} AesSivAssoc; + WOLFSSL_API int wc_AesSivEncrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, @@ -736,6 +746,15 @@ WOLFSSL_API int wc_AesSivDecrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out); + +WOLFSSL_API +int wc_AesSivEncrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, + word32 numAssoc, const byte* nonce, word32 nonceSz, + const byte* in, word32 inSz, byte* siv, byte* out); +WOLFSSL_API +int wc_AesSivDecrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, + word32 numAssoc, const byte* nonce, word32 nonceSz, + const byte* in, word32 inSz, byte* siv, byte* out); #endif #ifdef WOLFSSL_AES_EAX diff --git a/src/wolfssl/wolfcrypt/arc4.h b/src/wolfssl/wolfcrypt/arc4.h index fe58b10..0dc29d3 100644 --- a/src/wolfssl/wolfcrypt/arc4.h +++ b/src/wolfssl/wolfcrypt/arc4.h @@ -1,6 +1,6 @@ /* arc4.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/asn.h b/src/wolfssl/wolfcrypt/asn.h index 503c985..11803d6 100644 --- a/src/wolfssl/wolfcrypt/asn.h +++ b/src/wolfssl/wolfcrypt/asn.h @@ -1,6 +1,6 @@ /* asn.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -76,13 +76,28 @@ that can be serialized and deserialized in a cross-platform way. #endif enum { - ISSUER = 0, - SUBJECT = 1, + ASN_ISSUER = 0, + ASN_SUBJECT = 1, - BEFORE = 0, - AFTER = 1 + ASN_BEFORE = 0, + ASN_AFTER = 1 }; +#ifndef NO_ASN_OLD_TYPE_NAMES + #ifndef ISSUER + #define ISSUER ASN_ISSUER + #endif + #ifndef SUBJECT + #define SUBJECT ASN_SUBJECT + #endif + #ifndef BEFORE + #define BEFORE ASN_BEFORE + #endif + #ifndef AFTER + #define AFTER ASN_AFTER + #endif +#endif + /* ASN Tags */ enum ASN_Tags { ASN_EOC = 0x00, @@ -209,11 +224,11 @@ typedef struct ASNItem { /* BER/DER tag to expect. */ byte tag; /* Whether the ASN.1 item is constructed. */ - byte constructed:1; + WC_BITFIELD constructed:1; /* Whether to parse the header only or skip data. If * ASNSetData.data.buffer.data is supplied then this option gets * overwritten and the child nodes get ignored. */ - byte headerOnly:1; + WC_BITFIELD headerOnly:1; /* Whether ASN.1 item is optional. * - 0 means not optional * - 1 means is optional @@ -351,7 +366,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Int8Bit(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_WORD8; \ - (dataASN)->data.u8 = num; \ + (dataASN)->data.u8 = (num); \ } while (0) /* Setup ASN data item to get a 16-bit number. @@ -362,7 +377,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Int16Bit(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_WORD16; \ - (dataASN)->data.u16 = num; \ + (dataASN)->data.u16 = (num); \ } while (0) /* Setup ASN data item to get a 32-bit number. @@ -373,7 +388,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Int32Bit(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_WORD32; \ - (dataASN)->data.u32 = num; \ + (dataASN)->data.u32 = (num); \ } while (0) /* Setup ASN data item to get data into a buffer of a specific length. @@ -385,8 +400,8 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Buffer(dataASN, d, l) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_BUFFER; \ - (dataASN)->data.buffer.data = d; \ - (dataASN)->data.buffer.length = l; \ + (dataASN)->data.buffer.data = (d); \ + (dataASN)->data.buffer.length = (l); \ } while (0) /* Setup ASN data item to check parsed data against expected buffer. @@ -398,8 +413,8 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_ExpBuffer(dataASN, d, l) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_EXP_BUFFER; \ - (dataASN)->data.ref.data = d; \ - (dataASN)->data.ref.length = l; \ + (dataASN)->data.ref.data = (d); \ + (dataASN)->data.ref.length = (l); \ } while (0) /* Setup ASN data item to get a number into an mp_int. @@ -410,7 +425,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_MP(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_MP; \ - (dataASN)->data.mp = num; \ + (dataASN)->data.mp = (num); \ } while (0) /* Setup ASN data item to get a number into an mp_int that is initialized. @@ -421,7 +436,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_MP_Inited(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_MP_INITED; \ - (dataASN)->data.mp = num; \ + (dataASN)->data.mp = (num); \ } while (0) /* Setup ASN data item to get a positive or negative number into an mp_int. @@ -432,7 +447,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_MP_PosNeg(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_MP_POS_NEG; \ - (dataASN)->data.mp = num; \ + (dataASN)->data.mp = (num); \ } while (0) /* Setup ASN data item to be a choice of tags. @@ -443,7 +458,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Choice(dataASN, options) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_CHOICE; \ - (dataASN)->data.choice = options; \ + (dataASN)->data.choice = (options); \ } while (0) /* Setup ASN data item to get a boolean value. @@ -454,7 +469,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define GetASN_Boolean(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_NONE; \ - (dataASN)->data.u8 = num; \ + (dataASN)->data.u8 = (num); \ } while (0) /* Setup ASN data item to be a an OID of a specific type. @@ -463,7 +478,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); * @param [in] oidType Type of OID to expect. */ #define GetASN_OID(dataASN, oidType) \ - (dataASN)->data.oid.type = oidType + (dataASN)->data.oid.type = (oidType) /* Get the data and length from an ASN data item. * @@ -509,7 +524,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define SetASN_Boolean(dataASN, val) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_NONE; \ - (dataASN)->data.u8 = val; \ + (dataASN)->data.u8 = (val); \ } while (0) /* Setup an ASN data item to set an 8-bit number. @@ -520,7 +535,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define SetASN_Int8Bit(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_WORD8; \ - (dataASN)->data.u8 = num; \ + (dataASN)->data.u8 = (num); \ } while (0) /* Setup an ASN data item to set a 16-bit number. @@ -531,7 +546,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define SetASN_Int16Bit(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_WORD16; \ - (dataASN)->data.u16 = num; \ + (dataASN)->data.u16 = (num); \ } while (0) /* Setup an ASN data item to set the data in a buffer. @@ -542,8 +557,8 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); */ #define SetASN_Buffer(dataASN, d, l) \ do { \ - (dataASN)->data.buffer.data = d; \ - (dataASN)->data.buffer.length = l; \ + (dataASN)->data.buffer.data = (d); \ + (dataASN)->data.buffer.length = (word32)(l); \ } while (0) /* Setup an ASN data item to set the DER encode data in a buffer. @@ -555,8 +570,8 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define SetASN_ReplaceBuffer(dataASN, d, l) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_REPLACE_BUFFER; \ - (dataASN)->data.buffer.data = d; \ - (dataASN)->data.buffer.length = l; \ + (dataASN)->data.buffer.data = (d); \ + (dataASN)->data.buffer.length = (l); \ } while (0) /* Setup an ASN data item to set an muli-precision number. @@ -567,7 +582,7 @@ WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType); #define SetASN_MP(dataASN, num) \ do { \ (dataASN)->dataType = ASN_DATA_TYPE_MP; \ - (dataASN)->data.mp = num; \ + (dataASN)->data.mp = (num); \ } while (0) /* Setup an ASN data item to set an OID based on id and type. @@ -784,7 +799,7 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; * Any certificate containing more than this number of subject * alternative names will cause an error when attempting to parse. */ #ifndef WOLFSSL_MAX_ALT_NAMES -#define WOLFSSL_MAX_ALT_NAMES 128 +#define WOLFSSL_MAX_ALT_NAMES 1024 #endif /* Maximum number of allowed name constraints in a certificate. @@ -864,6 +879,10 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define NID_X9_62_prime_field 406 /* 1.2.840.10045.1.1 */ #endif /* OPENSSL_EXTRA */ +#define NID_id_GostR3410_2001 811 +#define NID_id_GostR3410_2012_256 979 +#define NID_id_GostR3410_2012_512 980 + enum ECC_TYPES { ECC_PREFIX_0 = 160, @@ -932,13 +951,14 @@ enum Misc_ASN { #else KEYID_SIZE = WC_SHA_DIGEST_SIZE, #endif -#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) - RSA_INTS = 8, /* RSA ints in private key */ -#elif !defined(WOLFSSL_RSA_PUBLIC_ONLY) - RSA_INTS = 5, /* RSA ints in private key */ -#else - RSA_INTS = 2, /* RSA ints in private key */ + RSA_INTS = 2 /* RSA ints in private key */ +#ifndef WOLFSSL_RSA_PUBLIC_ONLY + + 3 +#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) + + 3 +#endif #endif + , DSA_PARAM_INTS = 3, /* DSA parameter ints */ RSA_PUB_INTS = 2, /* RSA ints in public key */ DSA_PUB_INTS = 4, /* DSA ints in public key */ @@ -1167,6 +1187,9 @@ enum Key_Sum { DILITHIUM_LEVEL2k = 218, /* 1.3.6.1.4.1.2.267.12.4.4 */ DILITHIUM_LEVEL3k = 221, /* 1.3.6.1.4.1.2.267.12.6.5 */ DILITHIUM_LEVEL5k = 225, /* 1.3.6.1.4.1.2.267.12.8.7 */ + ML_DSA_LEVEL2k = 431, /* 2.16.840.1.101.3.4.3.17 */ + ML_DSA_LEVEL3k = 432, /* 2.16.840.1.101.3.4.3.18 */ + ML_DSA_LEVEL5k = 433, /* 2.16.840.1.101.3.4.3.19 */ SPHINCS_FAST_LEVEL1k = 281, /* 1 3 9999 6 7 4 */ SPHINCS_FAST_LEVEL3k = 283, /* 1 3 9999 6 8 3 + 2 (See GetOID() in asn.c) */ SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ @@ -1251,8 +1274,9 @@ enum Extensions_Sum { #ifdef WOLFSSL_DUAL_ALG_CERTS SUBJ_ALT_PUB_KEY_INFO_OID = 186, /* 2.5.29.72 subject alt public key info */ ALT_SIG_ALG_OID = 187, /* 2.5.29.73 alt sig alg */ - ALT_SIG_VAL_OID = 188 /* 2.5.29.74 alt sig val */ + ALT_SIG_VAL_OID = 188, /* 2.5.29.74 alt sig val */ #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(Extensions_Sum) }; enum CertificatePolicy_Sum { @@ -1399,10 +1423,10 @@ struct DNS_entry { int type; /* i.e. ASN_DNS_TYPE */ int len; /* actual DNS len */ char* name; /* actual DNS name */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME) +#ifdef WOLFSSL_IP_ALT_NAME char* ipString; /* human readable form of IP address */ #endif -#if defined(OPENSSL_ALL) +#ifdef WOLFSSL_RID_ALT_NAME char* ridString; /* human readable form of registeredID */ #endif @@ -1641,10 +1665,12 @@ typedef struct TrustedPeerCert TrustedPeerCert; typedef struct SignatureCtx SignatureCtx; typedef struct CertSignCtx CertSignCtx; -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB typedef int (*wc_UnknownExtCallback)(const word16* oid, word32 oidSz, int crit, const unsigned char* der, word32 derSz); +typedef int (*wc_UnknownExtCallbackEx)(const word16* oid, word32 oidSz, + int crit, const unsigned char* der, + word32 derSz, void *ctx); #endif struct DecodedCert { @@ -1692,7 +1718,7 @@ struct DecodedCert { word32 extensionsIdx; /* if want to go back and parse later */ const byte* extAuthInfo; /* Authority Information Access URI */ int extAuthInfoSz; /* length of the URI */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) +#ifdef WOLFSSL_ASN_CA_ISSUER const byte* extAuthInfoCaIssuer; /* Authority Info Access caIssuer URI */ int extAuthInfoCaIssuerSz; /* length of the caIssuer URI */ #endif @@ -1703,7 +1729,9 @@ struct DecodedCert { const byte* extCrlInfo; /* CRL Distribution Points */ int extCrlInfoSz; /* length of the URI */ byte extSubjKeyId[KEYID_SIZE]; /* Subject Key ID */ + word32 extSubjKeyIdSz; byte extAuthKeyId[KEYID_SIZE]; /* Authority Key ID */ + word32 extAuthKeyIdSz; #ifdef WOLFSSL_AKID_NAME const byte* extAuthKeyIdIssuer; /* Authority Key ID authorityCertIssuer */ word32 extAuthKeyIdIssuerSz; /* Authority Key ID authorityCertIssuer length */ @@ -1730,9 +1758,7 @@ struct DecodedCert { word32 extRawAuthKeyIdSz; #endif const byte* extAuthKeyIdSrc; - word32 extAuthKeyIdSz; const byte* extSubjKeyIdSrc; - word32 extSubjKeyIdSz; #endif #ifdef OPENSSL_ALL const byte* extSubjAltNameSrc; @@ -1782,7 +1808,7 @@ struct DecodedCert { char* subjectSN; int subjectSNLen; char subjectSNEnc; - #ifdef WOLFSSL_CERT_NAME_ALL +#ifdef WOLFSSL_CERT_NAME_ALL char* subjectN; int subjectNLen; char subjectNEnc; @@ -1795,7 +1821,7 @@ struct DecodedCert { char* subjectDNQ; int subjectDNQLen; char subjectDNQEnc; - #endif /*WOLFSSL_CERT_NAME_ALL */ +#endif /* WOLFSSL_CERT_NAME_ALL */ char* subjectC; int subjectCLen; char subjectCEnc; @@ -1860,12 +1886,12 @@ struct DecodedCert { char* issuerEmail; int issuerEmailLen; #endif /* WOLFSSL_HAVE_ISSUER_NAMES */ -#endif /* defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) */ +#endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* WOLFSSL_X509_NAME structures (used void* to avoid including ssl.h) */ void* issuerName; void* subjectName; -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef WOLFSSL_SEP int deviceTypeSz; byte* deviceType; @@ -1917,67 +1943,68 @@ struct DecodedCert { int criticalExt; /* Option Bits */ - byte subjectCNStored : 1; /* have we saved a copy we own */ - byte extSubjKeyIdSet : 1; /* Set when the SKID was read from cert */ - byte extAuthKeyIdSet : 1; /* Set when the AKID was read from cert */ + WC_BITFIELD subjectCNStored:1; /* have we saved a copy we own */ + WC_BITFIELD extSubjKeyIdSet:1; /* Set when the SKID was read from cert */ + WC_BITFIELD extAuthKeyIdSet:1; /* Set when the AKID was read from cert */ #ifndef IGNORE_NAME_CONSTRAINTS - byte extNameConstraintSet : 1; + WC_BITFIELD extNameConstraintSet:1; #endif - byte isCA : 1; /* CA basic constraint true */ - byte pathLengthSet : 1; /* CA basic const path length set */ - byte weOwnAltNames : 1; /* altNames haven't been given to copy */ - byte extKeyUsageSet : 1; - byte extExtKeyUsageSet : 1; /* Extended Key Usage set */ + WC_BITFIELD isCA:1; /* CA basic constraint true */ + WC_BITFIELD pathLengthSet:1; /* CA basic const path length set */ + WC_BITFIELD weOwnAltNames:1; /* altNames haven't been given to copy */ + WC_BITFIELD extKeyUsageSet:1; + WC_BITFIELD extExtKeyUsageSet:1; /* Extended Key Usage set */ #ifdef HAVE_OCSP - byte ocspNoCheckSet : 1; /* id-pkix-ocsp-nocheck set */ -#endif - byte extCRLdistSet : 1; - byte extAuthInfoSet : 1; - byte extBasicConstSet : 1; - byte extPolicyConstSet : 1; - byte extPolicyConstRxpSet : 1; /* requireExplicitPolicy set */ - byte extPolicyConstIpmSet : 1; /* inhibitPolicyMapping set */ - byte extSubjAltNameSet : 1; - byte inhibitAnyOidSet : 1; - byte selfSigned : 1; /* Indicates subject and issuer are same */ -#if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) - byte extCertPolicySet : 1; -#endif - byte extCRLdistCrit : 1; - byte extAuthInfoCrit : 1; - byte extBasicConstCrit : 1; - byte extPolicyConstCrit : 1; - byte extSubjAltNameCrit : 1; - byte extAuthKeyIdCrit : 1; + WC_BITFIELD ocspNoCheckSet:1; /* id-pkix-ocsp-nocheck set */ +#endif + WC_BITFIELD extCRLdistSet:1; + WC_BITFIELD extAuthInfoSet:1; + WC_BITFIELD extBasicConstSet:1; + WC_BITFIELD extPolicyConstSet:1; + WC_BITFIELD extPolicyConstRxpSet:1; /* requireExplicitPolicy set */ + WC_BITFIELD extPolicyConstIpmSet:1; /* inhibitPolicyMapping set */ + WC_BITFIELD extSubjAltNameSet:1; + WC_BITFIELD inhibitAnyOidSet:1; + WC_BITFIELD selfSigned:1; /* Indicates subject and issuer are same */ +#ifdef WOLFSSL_SEP + WC_BITFIELD extCertPolicySet:1; +#endif + WC_BITFIELD extCRLdistCrit:1; + WC_BITFIELD extAuthInfoCrit:1; + WC_BITFIELD extBasicConstCrit:1; + WC_BITFIELD extPolicyConstCrit:1; + WC_BITFIELD extSubjAltNameCrit:1; + WC_BITFIELD extAuthKeyIdCrit:1; #ifndef IGNORE_NAME_CONSTRAINTS - byte extNameConstraintCrit : 1; + WC_BITFIELD extNameConstraintCrit:1; #endif - byte extSubjKeyIdCrit : 1; - byte extKeyUsageCrit : 1; - byte extExtKeyUsageCrit : 1; + WC_BITFIELD extSubjKeyIdCrit:1; + WC_BITFIELD extKeyUsageCrit:1; + WC_BITFIELD extExtKeyUsageCrit:1; #ifdef WOLFSSL_SUBJ_DIR_ATTR - byte extSubjDirAttrSet : 1; + WC_BITFIELD extSubjDirAttrSet:1; #endif #ifdef WOLFSSL_SUBJ_INFO_ACC - byte extSubjInfoAccSet : 1; + WC_BITFIELD extSubjInfoAccSet:1; #endif #ifdef WOLFSSL_DUAL_ALG_CERTS - byte extSapkiSet : 1; - byte extAltSigAlgSet : 1; - byte extAltSigValSet : 1; + WC_BITFIELD extSapkiSet:1; + WC_BITFIELD extAltSigAlgSet:1; + WC_BITFIELD extAltSigValSet:1; #endif /* WOLFSSL_DUAL_ALG_CERTS */ -#if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) - byte extCertPolicyCrit : 1; +#ifdef WOLFSSL_SEP + WC_BITFIELD extCertPolicyCrit:1; #endif #ifdef WOLFSSL_CERT_REQ - byte isCSR : 1; /* Do we intend on parsing a CSR? */ + WC_BITFIELD isCSR:1; /* Do we intend on parsing a CSR? */ #endif #ifdef HAVE_RPK - byte isRPK : 1; /* indicate the cert is Raw-Public-Key cert in RFC7250 */ + WC_BITFIELD isRPK:1; /* indicate the cert is Raw-Public-Key cert in RFC7250 */ #endif -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) +#ifdef WC_ASN_UNKNOWN_EXT_CB wc_UnknownExtCallback unknownExtCallback; + wc_UnknownExtCallbackEx unknownExtCallbackEx; + void *unknownExtCallbackExCtx; #endif #ifdef WOLFSSL_DUAL_ALG_CERTS /* Subject Alternative Public Key Info */ @@ -2009,14 +2036,14 @@ struct Signer { word32 keyOID; /* key type */ word16 keyUsage; byte maxPathLen; - byte selfSigned : 1; + WC_BITFIELD selfSigned:1; const byte* publicKey; int nameLen; char* name; /* common name */ #ifndef IGNORE_NAME_CONSTRAINTS Base_entry* permittedNames; Base_entry* excludedNames; -#endif /* IGNORE_NAME_CONSTRAINTS */ +#endif /* !IGNORE_NAME_CONSTRAINTS */ byte subjectNameHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ #if defined(HAVE_OCSP) || defined(HAVE_CRL) @@ -2117,15 +2144,16 @@ typedef enum MimeStatus } MimeStatus; #endif /* HAVE_SMIME */ - WOLFSSL_LOCAL int HashIdAlg(word32 oidSum); WOLFSSL_LOCAL int CalcHashId(const byte* data, word32 len, byte* hash); WOLFSSL_LOCAL int CalcHashId_ex(const byte* data, word32 len, byte* hash, int hashAlg); WOLFSSL_LOCAL int GetName(DecodedCert* cert, int nameType, int maxIdx); -WOLFSSL_ASN_API int wc_BerToDer(const byte* ber, word32 berSz, byte* der, +#ifdef ASN_BER_TO_DER +WOLFSSL_API int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz); +#endif WOLFSSL_LOCAL int StreamOctetString(const byte* inBuf, word32 inBufSz, byte* out, word32* outSz, word32* idx); @@ -2143,10 +2171,12 @@ WOLFSSL_ASN_API void FreeDecodedCert(DecodedCert* cert); WOLFSSL_ASN_API int ParseCert(DecodedCert* cert, int type, int verify, void* cm); -#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \ - && defined(HAVE_OID_DECODING) -WOLFSSL_ASN_API int wc_SetUnknownExtCallback(DecodedCert* cert, +#ifdef WC_ASN_UNKNOWN_EXT_CB +WOLFSSL_API int wc_SetUnknownExtCallback(DecodedCert* cert, wc_UnknownExtCallback cb); +WOLFSSL_API int wc_SetUnknownExtCallbackEx(DecodedCert* cert, + wc_UnknownExtCallbackEx cb, + void *ctx); #endif WOLFSSL_LOCAL int DecodePolicyOID(char *out, word32 outSz, const byte *in, @@ -2158,7 +2188,7 @@ WOLFSSL_LOCAL int CheckCertSignaturePubKey(const byte* cert, word32 certSz, #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SMALL_CERT_VERIFY) WOLFSSL_API int wc_CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm); - /* Depricated public API name kept for backwards build compatibility */ + /* Deprecated public API name kept for backwards build compatibility */ #define CheckCertSignature(cert, certSz, heap, cm) \ wc_CheckCertSignature(cert, certSz, heap, cm) @@ -2216,6 +2246,9 @@ WOLFSSL_LOCAL int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 length); WOLFSSL_LOCAL int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 length, word32* algId); +WOLFSSL_LOCAL int ToTraditionalInline_ex2(const byte* input, word32* inOutIdx, + word32 length, word32* algId, + word32* eccOid); WOLFSSL_LOCAL int ToTraditionalEnc(byte* input, word32 sz, const char* password, int passwordSz, word32* algId); WOLFSSL_ASN_API int UnTraditionalEnc(byte* key, word32 keySz, byte* out, @@ -2233,8 +2266,7 @@ WOLFSSL_LOCAL int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, int* algoID, void* heap); typedef struct tm wolfssl_tm; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) || \ - defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#ifdef WOLFSSL_ASN_TIME_STRING WOLFSSL_LOCAL int GetTimeString(byte* date, int format, char* buf, int len); #endif #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \ @@ -2260,10 +2292,12 @@ WOLFSSL_LOCAL int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx); WOLFSSL_LOCAL const char* GetSigName(int oid); -WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len, - word32 maxIdx); +WOLFSSL_ASN_API int GetLength(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx); WOLFSSL_LOCAL int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx, int check); +WOLFSSL_LOCAL int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, + int* len, word32 maxIdx); WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len, word32 maxIdx); WOLFSSL_LOCAL int GetSequence_ex(const byte* input, word32* inOutIdx, int* len, @@ -2301,8 +2335,11 @@ WOLFSSL_LOCAL int GetObjectId(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx); WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx); -WOLFSSL_LOCAL int GetASNTag(const byte* input, word32* idx, byte* tag, - word32 inputSz); +WOLFSSL_LOCAL int GetAlgoIdEx(const byte* input, word32* inOutIdx, word32* oid, + word32 oidType, word32 maxIdx, byte *absentParams); +WOLFSSL_ASN_API int GetASNTag(const byte* input, word32* idx, byte* tag, + word32 inputSz); +WOLFSSL_LOCAL int GetASN_BitString(const byte* input, word32 idx, int length); WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output); WOLFSSL_LOCAL word32 SetASNSequence(word32 len, byte* output); @@ -2314,6 +2351,8 @@ WOLFSSL_LOCAL word32 SetASNSet(word32 len, byte* output); WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output); WOLFSSL_LOCAL word32 SetLengthEx(word32 length, byte* output, byte isIndef); +WOLFSSL_LOCAL word32 SetHeader(byte tag, word32 len, byte* output, + byte isIndef); WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output); WOLFSSL_LOCAL word32 SetSequenceEx(word32 len, byte* output, byte isIndef); WOLFSSL_LOCAL word32 SetIndefEnd(byte* output); @@ -2327,6 +2366,8 @@ WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output, byte isIndef); WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output); WOLFSSL_API word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz); +WOLFSSL_LOCAL word32 SetAlgoIDEx(int algoOID, byte* output, int type, int curveSz, + byte absentParams); WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header); WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output, word32 outputSz, int maxSnSz); @@ -2342,9 +2383,11 @@ WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash, WOLFSSL_LOCAL int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx, word32 sigOID); WOLFSSL_LOCAL int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, - DecodedCert* der, int checkAlt); + DecodedCert* der, int checkAlt, + void* heap); WOLFSSL_LOCAL int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz, - const byte* pubKey, word32 pubKeySz, enum Key_Sum ks); + const byte* pubKey, word32 pubKeySz, + enum Key_Sum ks, void* heap); WOLFSSL_LOCAL int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g); #ifdef WOLFSSL_DH_EXTRA WOLFSSL_API int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx, @@ -2401,13 +2444,12 @@ WOLFSSL_LOCAL int AllocCopyDer(DerBuffer** der, const unsigned char* buff, word32 length, int type, void* heap); WOLFSSL_LOCAL void FreeDer(DerBuffer** der); -#if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \ - (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)) +#ifdef WOLFSSL_ASN_PARSE_KEYUSAGE WOLFSSL_LOCAL int ParseKeyUsageStr(const char* value, word16* keyUsage, void* heap); WOLFSSL_LOCAL int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage, void* heap); -#endif /* (CERT_GEN && CERT_EXT) || (OPENSSL_ALL || OPENSSL_EXTRA) */ +#endif #endif /* !NO_CERTS */ @@ -2433,6 +2475,9 @@ enum cert_enums { DILITHIUM_LEVEL2_KEY = 18, DILITHIUM_LEVEL3_KEY = 19, DILITHIUM_LEVEL5_KEY = 20, + ML_DSA_LEVEL2_KEY = 21, + ML_DSA_LEVEL3_KEY = 22, + ML_DSA_LEVEL5_KEY = 23, SPHINCS_FAST_LEVEL1_KEY = 24, SPHINCS_FAST_LEVEL3_KEY = 25, SPHINCS_FAST_LEVEL5_KEY = 26, @@ -2499,8 +2544,7 @@ struct CertStatus { byte nextDate[MAX_DATE_SIZE]; byte thisDateFormat; byte nextDateFormat; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) +#ifdef WOLFSSL_OCSP_PARSE_STATUS WOLFSSL_ASN1_TIME thisDateParsed; WOLFSSL_ASN1_TIME nextDateParsed; byte* thisDateAsn; @@ -2532,10 +2576,10 @@ struct OcspEntry byte* rawCertId; /* raw bytes of the CertID */ int rawCertIdSize; /* num bytes in raw CertID */ /* option bits - using 32-bit for alignment */ - word32 ownStatus:1; /* do we need to free the status + WC_BITFIELD ownStatus:1; /* do we need to free the status * response list */ - word32 isDynamic:1; /* was dynamically allocated */ - word32 used:1; /* entry used */ + WC_BITFIELD isDynamic:1; /* was dynamically allocated */ + WC_BITFIELD used:1; /* entry used */ }; /* TODO: Long-term, it would be helpful if we made this struct and other OCSP @@ -2585,10 +2629,6 @@ struct OcspRequest { int serialSz; #ifdef OPENSSL_EXTRA WOLFSSL_ASN1_INTEGER* serialInt; -#endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \ - defined(HAVE_LIGHTY) void* cid; /* WOLFSSL_OCSP_CERTID kept to free */ #endif byte* url; /* copy of the extAuthInfo in source cert */ @@ -2677,9 +2717,55 @@ WOLFSSL_LOCAL int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, int verify, void* cm); WOLFSSL_LOCAL void FreeDecodedCRL(DecodedCRL* dcrl); - #endif /* HAVE_CRL */ +#if defined(WOLFSSL_ACERT) +/* Minimal structure for x509 attribute certificate (rfc 5755). + * + * The attributes field is not parsed, but is stored as raw buffer. + * */ +struct DecodedAcert { + word32 certBegin; /* Offset to start of acert. */ + word32 sigIndex; /* Offset to start of signature. */ + word32 sigLength; /* Signature length. */ + word32 signatureOID; /* Sum of algorithm object id. */ +#ifdef WC_RSA_PSS + word32 sigParamsIndex; /* start of signature parameters */ + word32 sigParamsLength; /* length of signature parameters */ +#endif + const byte * signature; /* Not owned, points into raw acert. */ + const byte * source; /* Byte buffer holding acert, NOT owned. */ + word32 srcIdx; /* Current offset into buffer. */ + word32 maxIdx; /* Max allowed offset. Set in init. */ + void * heap; /* For user memory overrides. */ + int version; /* attribute cert version. */ + byte serial[EXTERNAL_SERIAL_SIZE]; /* Raw serial number. */ + int serialSz; + const byte * beforeDate; /* Before and After dates. */ + int beforeDateLen; + const byte * afterDate; + int afterDateLen; + byte holderSerial[EXTERNAL_SERIAL_SIZE]; + int holderSerialSz; + DNS_entry * holderEntityName; /* Holder entityName from ACERT */ + DNS_entry * holderIssuerName; /* Holder issuerName from ACERT */ + DNS_entry * AttCertIssuerName; /* AttCertIssuer name from ACERT */ + const byte * rawAttr; /* Not owned, points into raw acert. */ + word32 rawAttrLen; + SignatureCtx sigCtx; +}; + +typedef struct DecodedAcert DecodedAcert; + +WOLFSSL_LOCAL void InitDecodedAcert(DecodedAcert* acert, + const byte* source, word32 inSz, + void* heap); +WOLFSSL_LOCAL void FreeDecodedAcert(DecodedAcert * acert); +WOLFSSL_LOCAL int ParseX509Acert(DecodedAcert* cert, int verify); +WOLFSSL_LOCAL int VerifyX509Acert(const byte* cert, word32 certSz, + const byte* pubKey, word32 pubKeySz, + int pubKeyOID, void * heap); +#endif /* WOLFSSL_ACERT */ #ifdef __cplusplus } /* extern "C" */ @@ -2739,7 +2825,9 @@ enum PBESTypes { PBES2 = 13, /* algo ID */ PBES1_MD5_DES = 3, - PBES1_SHA1_DES = 10 + PBES1_SHA1_DES = 10, + + PBE_NONE = 999 }; enum PKCSTypes { diff --git a/src/wolfssl/wolfcrypt/asn_public.h b/src/wolfssl/wolfcrypt/asn_public.h index f233004..b8bbce4 100644 --- a/src/wolfssl/wolfcrypt/asn_public.h +++ b/src/wolfssl/wolfcrypt/asn_public.h @@ -1,6 +1,6 @@ /* asn_public.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -148,6 +148,7 @@ enum CertType { CA_TYPE, ECC_PRIVATEKEY_TYPE, DSA_PRIVATEKEY_TYPE, + ACERT_TYPE, CERTREQ_TYPE, DSA_TYPE, ECC_TYPE, @@ -170,6 +171,9 @@ enum CertType { DILITHIUM_LEVEL2_TYPE, DILITHIUM_LEVEL3_TYPE, DILITHIUM_LEVEL5_TYPE, + ML_DSA_LEVEL2_TYPE, + ML_DSA_LEVEL3_TYPE, + ML_DSA_LEVEL5_TYPE, SPHINCS_FAST_LEVEL1_TYPE, SPHINCS_FAST_LEVEL3_TYPE, SPHINCS_FAST_LEVEL5_TYPE, @@ -177,7 +181,8 @@ enum CertType { SPHINCS_SMALL_LEVEL3_TYPE, SPHINCS_SMALL_LEVEL5_TYPE, ECC_PARAM_TYPE, - CHAIN_CERT_TYPE + CHAIN_CERT_TYPE, + PKCS7_TYPE }; @@ -221,6 +226,9 @@ enum Ctc_SigType { CTC_DILITHIUM_LEVEL2 = 218, CTC_DILITHIUM_LEVEL3 = 221, CTC_DILITHIUM_LEVEL5 = 225, + CTC_ML_DSA_LEVEL2 = 431, + CTC_ML_DSA_LEVEL3 = 432, + CTC_ML_DSA_LEVEL5 = 433, CTC_SPHINCS_FAST_LEVEL1 = 281, CTC_SPHINCS_FAST_LEVEL3 = 283, @@ -324,7 +332,7 @@ typedef struct EncryptedInfo { char name[NAME_SZ]; /* cipher name, such as "DES-CBC" */ byte iv[IV_SZ]; /* salt or encrypted IV */ - word16 set:1; /* if encryption set */ + WC_BITFIELD set:1; /* if encryption set */ #endif } EncryptedInfo; @@ -339,7 +347,7 @@ typedef struct WOLFSSL_ASN1_INTEGER { unsigned char* data; unsigned int dataMax; /* max size of data buffer */ - unsigned int isDynamic:1; /* flag for if data pointer dynamic (1 is yes 0 is no) */ + WC_BITFIELD isDynamic:1; /* flag for if data pointer dynamic (1 is yes 0 is no) */ int length; /* Length of DER encoding. */ int type; /* ASN.1 type. Includes negative flag. */ @@ -360,7 +368,6 @@ typedef struct WOLFSSL_ASN1_INTEGER { #endif #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ -#if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #ifdef WOLFSSL_MULTI_ATTRIB #ifndef CTC_MAX_ATTRIB #define CTC_MAX_ATTRIB 4 @@ -374,7 +381,6 @@ typedef struct NameAttrib { char value[CTC_NAME_SIZE]; /* name */ } NameAttrib; #endif /* WOLFSSL_MULTI_ATTRIB */ -#endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef WOLFSSL_CUSTOM_OID typedef struct CertOidField { @@ -543,13 +549,13 @@ typedef struct Cert { void* decodedCert; /* internal DecodedCert allocated from heap */ byte* der; /* Pointer to buffer of current DecodedCert cache */ void* heap; /* heap hint */ - byte basicConstSet:1; /* Indicator for when Basic Constraint is set */ + WC_BITFIELD basicConstSet:1; /* Indicator for when Basic Constraint is set */ #ifdef WOLFSSL_ALLOW_ENCODING_CA_FALSE - byte isCaSet:1; /* Indicator for when isCA is set */ + WC_BITFIELD isCaSet:1; /* Indicator for when isCA is set */ #endif - byte pathLenSet:1; /* Indicator for when path length is set */ + WC_BITFIELD pathLenSet:1; /* Indicator for when path length is set */ #ifdef WOLFSSL_ALT_NAMES - byte altNamesCrit:1; /* Indicator of criticality of SAN extension */ + WC_BITFIELD altNamesCrit:1; /* Indicator of criticality of SAN extension */ #endif } Cert; @@ -931,9 +937,9 @@ typedef struct _wc_CertPIV { word32 signedNonceSz; /* Identiv Only */ /* flags */ - word16 compression:2; - word16 isX509:1; - word16 isIdentiv:1; + WC_BITFIELD compression:2; + WC_BITFIELD isX509:1; + WC_BITFIELD isIdentiv:1; } wc_CertPIV; WOLFSSL_API int wc_ParseCertPIV(wc_CertPIV* cert, const byte* buf, word32 totalSz); @@ -963,6 +969,19 @@ WOLFSSL_API int wc_GeneratePreTBS(struct DecodedCert* cert, byte *der, int derSz); #endif +#if defined(WOLFSSL_ACERT) +/* Forward declaration needed, as DecodedAcert is defined in asn.h.*/ +struct DecodedAcert; +WOLFSSL_API void wc_InitDecodedAcert(struct DecodedAcert* acert, + const byte* source, word32 inSz, + void* heap); +WOLFSSL_API void wc_FreeDecodedAcert(struct DecodedAcert * acert); +WOLFSSL_API int wc_ParseX509Acert(struct DecodedAcert* acert, int verify); +WOLFSSL_API int wc_VerifyX509Acert(const byte* acert, word32 acertSz, + const byte* pubKey, word32 pubKeySz, + int pubKeyOID, void * heap); +#endif /* WOLFSSL_ACERT */ + #if !defined(XFPRINTF) || defined(NO_FILESYSTEM) || \ defined(NO_STDIO_FILESYSTEM) && defined(WOLFSSL_ASN_PRINT) #undef WOLFSSL_ASN_PRINT @@ -988,7 +1007,7 @@ enum Asn1PrintOpt { /* Don't show text representations of primitive types. */ ASN1_PRINT_OPT_SHOW_NO_TEXT, /* Don't show dump text representations of primitive types. */ - ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT, + ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT }; /* ASN.1 print options. */ @@ -1000,17 +1019,17 @@ typedef struct Asn1PrintOptions { /* Number of spaces to indent for each change in depth. */ word8 indent; /* Draw branches instead of indenting. */ - word8 draw_branch:1; + WC_BITFIELD draw_branch:1; /* Show raw data of primitive types as octets. */ - word8 show_data:1; + WC_BITFIELD show_data:1; /* Show header data as octets. */ - word8 show_header_data:1; + WC_BITFIELD show_header_data:1; /* Show the wolfSSL OID value for OBJECT_ID. */ - word8 show_oid:1; + WC_BITFIELD show_oid:1; /* Don't show text representations of primitive types. */ - word8 show_no_text:1; + WC_BITFIELD show_no_text:1; /* Don't show dump text representations of primitive types. */ - word8 show_no_dump_text:1; + WC_BITFIELD show_no_dump_text:1; } Asn1PrintOptions; /* ASN.1 item data. */ diff --git a/src/wolfssl/wolfcrypt/blake2-impl.h b/src/wolfssl/wolfcrypt/blake2-impl.h index 2cdbf40..1a0db32 100644 --- a/src/wolfssl/wolfcrypt/blake2-impl.h +++ b/src/wolfssl/wolfcrypt/blake2-impl.h @@ -12,7 +12,7 @@ */ /* blake2-impl.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/blake2-int.h b/src/wolfssl/wolfcrypt/blake2-int.h index 0ad625e..b048ca5 100644 --- a/src/wolfssl/wolfcrypt/blake2-int.h +++ b/src/wolfssl/wolfcrypt/blake2-int.h @@ -12,7 +12,7 @@ */ /* blake2-int.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/blake2.h b/src/wolfssl/wolfcrypt/blake2.h index 1c62e64..1f4ac77 100644 --- a/src/wolfssl/wolfcrypt/blake2.h +++ b/src/wolfssl/wolfcrypt/blake2.h @@ -1,6 +1,6 @@ /* blake2.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/camellia.h b/src/wolfssl/wolfcrypt/camellia.h index 9283123..bdba23b 100644 --- a/src/wolfssl/wolfcrypt/camellia.h +++ b/src/wolfssl/wolfcrypt/camellia.h @@ -27,7 +27,7 @@ /* camellia.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/chacha.h b/src/wolfssl/wolfcrypt/chacha.h index 6c9577b..1c6ae17 100644 --- a/src/wolfssl/wolfcrypt/chacha.h +++ b/src/wolfssl/wolfcrypt/chacha.h @@ -1,6 +1,6 @@ /* chacha.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -82,7 +82,8 @@ typedef struct ChaCha { byte extra[12]; #endif word32 left; /* number of bytes leftover */ -#if defined(USE_INTEL_CHACHA_SPEEDUP) || defined(WOLFSSL_ARMASM) +#if defined(USE_INTEL_CHACHA_SPEEDUP) || defined(WOLFSSL_ARMASM) || \ + defined(WOLFSSL_RISCV_ASM) word32 over[CHACHA_CHUNK_WORDS]; #endif } ChaCha; @@ -96,16 +97,32 @@ WOLFSSL_API int wc_Chacha_SetIV(ChaCha* ctx, const byte* inIv, word32 counter); WOLFSSL_API int wc_Chacha_Process(ChaCha* ctx, byte* cipher, const byte* plain, word32 msglen); -WOLFSSL_LOCAL void wc_Chacha_purge_current_block(ChaCha* ctx); - WOLFSSL_API int wc_Chacha_SetKey(ChaCha* ctx, const byte* key, word32 keySz); #ifdef HAVE_XCHACHA +WOLFSSL_LOCAL void wc_Chacha_purge_current_block(ChaCha* ctx); + WOLFSSL_API int wc_XChacha_SetKey(ChaCha *ctx, const byte *key, word32 keySz, const byte *nonce, word32 nonceSz, word32 counter); #endif +#if defined(WOLFSSL_ARMASM) + +#ifndef __aarch64__ +void wc_chacha_setiv(word32* x, const byte* iv, word32 counter); +void wc_chacha_setkey(word32* x, const byte* key, word32 keySz); +#endif + +#if defined(WOLFSSL_ARMASM_NO_NEON) || defined(WOLFSSL_ARMASM_THUMB2) +void wc_chacha_use_over(byte* over, byte* output, const byte* input, + word32 len); +void wc_chacha_crypt_bytes(ChaCha* ctx, byte* c, const byte* m, word32 len); +#endif + +#endif + + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/chacha20_poly1305.h b/src/wolfssl/wolfcrypt/chacha20_poly1305.h index 6c04912..ffa4031 100644 --- a/src/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/src/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -1,6 +1,6 @@ /* chacha20_poly1305.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -72,7 +72,7 @@ typedef struct ChaChaPoly_Aead { word32 dataLen; byte state; - byte isEncrypt:1; + WC_BITFIELD isEncrypt:1; } ChaChaPoly_Aead; diff --git a/src/wolfssl/wolfcrypt/cmac.h b/src/wolfssl/wolfcrypt/cmac.h index a92e832..a1c05f9 100644 --- a/src/wolfssl/wolfcrypt/cmac.h +++ b/src/wolfssl/wolfcrypt/cmac.h @@ -1,6 +1,6 @@ /* cmac.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,9 +24,12 @@ #define WOLF_CRYPT_CMAC_H #include -#include -#if !defined(NO_AES) && defined(WOLFSSL_CMAC) +#ifdef WOLFSSL_CMAC + +#ifndef NO_AES +#include +#endif #if defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) @@ -40,16 +43,22 @@ /* avoid redefinition of structs */ #if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(2,0,0) +typedef enum CmacType { + WC_CMAC_AES = 1 +} CmacType; + #ifndef WC_CMAC_TYPE_DEFINED typedef struct Cmac Cmac; #define WC_CMAC_TYPE_DEFINED #endif struct Cmac { +#ifndef NO_AES Aes aes; byte buffer[AES_BLOCK_SIZE]; /* partially stored block */ byte digest[AES_BLOCK_SIZE]; /* running digest */ byte k1[AES_BLOCK_SIZE]; byte k2[AES_BLOCK_SIZE]; +#endif word32 bufferSz; word32 totalSz; #ifdef WOLF_CRYPTO_CB @@ -70,16 +79,20 @@ struct Cmac { #ifdef WOLFSSL_SE050 byte useSWCrypt; /* Use SW crypt instead of SE050, before SCP03 auth */ #endif + CmacType type; }; -typedef enum CmacType { - WC_CMAC_AES = 1 -} CmacType; +#ifndef NO_AES #define WC_CMAC_TAG_MAX_SZ AES_BLOCK_SIZE #define WC_CMAC_TAG_MIN_SZ (AES_BLOCK_SIZE/4) +#else +/* Reasonable defaults */ +#define WC_CMAC_TAG_MAX_SZ 16 +#define WC_CMAC_TAG_MIN_SZ 4 +#endif #if FIPS_VERSION3_GE(6,0,0) extern const unsigned int wolfCrypt_FIPS_cmac_ro_sanity[2]; @@ -111,6 +124,7 @@ int wc_CmacFinal(Cmac* cmac, WOLFSSL_API int wc_CmacFree(Cmac* cmac); +#ifndef NO_AES WOLFSSL_API int wc_AesCmacGenerate(byte* out, word32* outSz, const byte* in, word32 inSz, @@ -134,10 +148,11 @@ int wc_AesCmacVerify_ex(Cmac* cmac, const byte* key, word32 keySz, void* heap, int devId); - WOLFSSL_LOCAL void ShiftAndXorRb(byte* out, byte* in); +#endif /* !NO_AES */ + #ifdef WOLFSSL_HASH_KEEP WOLFSSL_API int wc_CMAC_Grow(Cmac* cmac, const byte* in, int inSz); @@ -148,6 +163,6 @@ int wc_CMAC_Grow(Cmac* cmac, const byte* in, int inSz); #endif -#endif /* NO_AES && WOLFSSL_CMAC */ +#endif /* WOLFSSL_CMAC */ #endif /* WOLF_CRYPT_CMAC_H */ diff --git a/src/wolfssl/wolfcrypt/coding.h b/src/wolfssl/wolfcrypt/coding.h index e0aecc6..5aef5b1 100644 --- a/src/wolfssl/wolfcrypt/coding.h +++ b/src/wolfssl/wolfcrypt/coding.h @@ -1,6 +1,6 @@ /* coding.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/compress.h b/src/wolfssl/wolfcrypt/compress.h index a4efc78..2886b2b 100644 --- a/src/wolfssl/wolfcrypt/compress.h +++ b/src/wolfssl/wolfcrypt/compress.h @@ -1,6 +1,6 @@ /* compress.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/cpuid.h b/src/wolfssl/wolfcrypt/cpuid.h index 9d25dcf..c91b628 100644 --- a/src/wolfssl/wolfcrypt/cpuid.h +++ b/src/wolfssl/wolfcrypt/cpuid.h @@ -1,6 +1,6 @@ /* cpuid.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/cryptocb.h b/src/wolfssl/wolfcrypt/cryptocb.h index 29580ea..4ec42ec 100644 --- a/src/wolfssl/wolfcrypt/cryptocb.h +++ b/src/wolfssl/wolfcrypt/cryptocb.h @@ -1,6 +1,6 @@ /* cryptocb.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -75,7 +75,7 @@ #include #ifdef WOLFSSL_WC_KYBER #include -#elif defined(HAVE_LIBOQS) || defined(HAVE_PQM4) +#elif defined(HAVE_LIBOQS) #include #endif #endif @@ -118,6 +118,9 @@ typedef struct wc_CryptoInfo { int type; RsaKey* key; WC_RNG* rng; + #ifdef WOLF_CRYPTO_CB_RSA_PAD + RsaPadding *padding; + #endif } rsa; #ifdef WOLFSSL_KEY_GEN struct { @@ -481,6 +484,11 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info); WOLFSSL_LOCAL int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng); +#ifdef WOLF_CRYPTO_CB_RSA_PAD +WOLFSSL_LOCAL int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, + word32* outLen, int type, RsaKey* key, WC_RNG* rng, RsaPadding *padding); +#endif + #ifdef WOLFSSL_KEY_GEN WOLFSSL_LOCAL int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng); diff --git a/src/wolfssl/wolfcrypt/curve25519.h b/src/wolfssl/wolfcrypt/curve25519.h index 3b25a9d..4d18c56 100644 --- a/src/wolfssl/wolfcrypt/curve25519.h +++ b/src/wolfssl/wolfcrypt/curve25519.h @@ -1,6 +1,6 @@ /* curve25519.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -90,15 +90,15 @@ struct curve25519_key { void* devCtx; int devId; #endif - + void *heap; #ifdef WOLFSSL_SE050 word32 keyId; byte keyIdSet; #endif /* bit fields */ - byte pubSet:1; - byte privSet:1; + WC_BITFIELD pubSet:1; + WC_BITFIELD privSet:1; }; enum { @@ -139,6 +139,13 @@ int wc_curve25519_init_ex(curve25519_key* key, void* heap, int devId); WOLFSSL_API void wc_curve25519_free(curve25519_key* key); +#ifndef WC_NO_CONSTRUCTORS +WOLFSSL_API +curve25519_key* wc_curve25519_new(void* heap, int devId, int *result_code); +WOLFSSL_API +int wc_curve25519_delete(curve25519_key* key, curve25519_key** key_p); +#endif +WOLFSSL_API /* raw key helpers */ WOLFSSL_API diff --git a/src/wolfssl/wolfcrypt/curve448.h b/src/wolfssl/wolfcrypt/curve448.h index aa00e10..b722727 100644 --- a/src/wolfssl/wolfcrypt/curve448.h +++ b/src/wolfssl/wolfcrypt/curve448.h @@ -1,6 +1,6 @@ /* curve448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -58,8 +58,8 @@ struct curve448_key { #endif /* bit fields */ - byte pubSet:1; - byte privSet:1; + WC_BITFIELD pubSet:1; + WC_BITFIELD privSet:1; }; enum { diff --git a/src/wolfssl/wolfcrypt/des3.h b/src/wolfssl/wolfcrypt/des3.h index d5b1232..78a5164 100644 --- a/src/wolfssl/wolfcrypt/des3.h +++ b/src/wolfssl/wolfcrypt/des3.h @@ -1,6 +1,6 @@ /* des3.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -134,9 +134,16 @@ WOLFSSL_API int wc_Des_EcbEncrypt(Des* des, byte* out, WOLFSSL_API int wc_Des3_EcbEncrypt(Des3* des, byte* out, const byte* in, word32 sz); +#ifdef FREESCALE_MMCAU /* Has separate encrypt/decrypt functions */ +WOLFSSL_API int wc_Des_EcbDecrypt(Des* des, byte* out, + const byte* in, word32 sz); +WOLFSSL_API int wc_Des3_EcbDecrypt(Des3* des, byte* out, + const byte* in, word32 sz); +#else /* ECB decrypt same process as encrypt but with decrypt key */ #define wc_Des_EcbDecrypt wc_Des_EcbEncrypt #define wc_Des3_EcbDecrypt wc_Des3_EcbEncrypt +#endif WOLFSSL_API int wc_Des3_SetKey(Des3* des, const byte* key, const byte* iv,int dir); diff --git a/src/wolfssl/wolfcrypt/dh.h b/src/wolfssl/wolfcrypt/dh.h index 93e8475..865baa3 100644 --- a/src/wolfssl/wolfcrypt/dh.h +++ b/src/wolfssl/wolfcrypt/dh.h @@ -1,6 +1,6 @@ /* dh.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -151,6 +151,9 @@ WOLFSSL_API int wc_DhGenerateKeyPair(DhKey* key, WC_RNG* rng, byte* priv, WOLFSSL_API int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv, word32 privSz, const byte* otherPub, word32 pubSz); +WOLFSSL_API int wc_DhAgree_ct(DhKey* key, byte* agree, word32* agreeSz, + const byte* priv, word32 privSz, const byte* otherPub, + word32 pubSz); WOLFSSL_API int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz); /* wc_DhKeyDecode is in asn.c */ diff --git a/src/wolfssl/wolfcrypt/dilithium.h b/src/wolfssl/wolfcrypt/dilithium.h index 8b336cf..6e9cfb6 100644 --- a/src/wolfssl/wolfcrypt/dilithium.h +++ b/src/wolfssl/wolfcrypt/dilithium.h @@ -1,6 +1,6 @@ /* dilithium.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -128,6 +128,26 @@ (DILITHIUM_LEVEL5_PUB_KEY_SIZE + DILITHIUM_LEVEL5_KEY_SIZE) +#define ML_DSA_LEVEL2_KEY_SIZE 2560 +#define ML_DSA_LEVEL2_SIG_SIZE 2420 +#define ML_DSA_LEVEL2_PUB_KEY_SIZE 1312 +#define ML_DSA_LEVEL2_PRV_KEY_SIZE \ + (ML_DSA_LEVEL2_PUB_KEY_SIZE + ML_DSA_LEVEL2_KEY_SIZE) + +#define ML_DSA_LEVEL3_KEY_SIZE 4032 +#define ML_DSA_LEVEL3_SIG_SIZE 3309 +#define ML_DSA_LEVEL3_PUB_KEY_SIZE 1952 +#define ML_DSA_LEVEL3_PRV_KEY_SIZE \ + (ML_DSA_LEVEL3_PUB_KEY_SIZE + ML_DSA_LEVEL3_KEY_SIZE) + +#define ML_DSA_LEVEL5_KEY_SIZE 4896 +#define ML_DSA_LEVEL5_SIG_SIZE 4627 +#define ML_DSA_LEVEL5_PUB_KEY_SIZE 2592 +#define ML_DSA_LEVEL5_PRV_KEY_SIZE \ + (ML_DSA_LEVEL5_PUB_KEY_SIZE + ML_DSA_LEVEL5_KEY_SIZE) + + + /* Modulus. */ #define DILITHIUM_Q 0x7fe001 /* Number of bits in modulus. */ @@ -197,8 +217,8 @@ #define PARAMS_ML_DSA_44_ETA DILITHIUM_ETA_2 /* Number of bits in private key for ML-DSA-44. */ #define PARAMS_ML_DSA_44_ETA_BITS DILITHIUM_ETA_2_BITS -/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-44. */ -#define PARAMS_ML_DSA_44_LAMBDA 16 +/* Collision strength of c-tilde, LAMBDA, in bits for ML-DSA-44. */ +#define PARAMS_ML_DSA_44_LAMBDA 128 /* # +/-1's in polynomial c, TAU, for ML-DSA-44. */ #define PARAMS_ML_DSA_44_TAU 39 /* BETA = TAU * ETA for ML-DSA-44. */ @@ -242,7 +262,7 @@ (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_44_K * DILITHIUM_N * DILITHIUM_U / 8) /* Encoding size of signature in bytes for ML-DSA-44. */ #define PARAMS_ML_DSA_44_SIG_SIZE \ - ((PARAMS_ML_DSA_44_LAMBDA * 2) + \ + ((PARAMS_ML_DSA_44_LAMBDA / 4) + \ PARAMS_ML_DSA_44_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_44_GAMMA1_BITS + 1) + \ PARAMS_ML_DSA_44_OMEGA + PARAMS_ML_DSA_44_K) @@ -258,8 +278,8 @@ #define PARAMS_ML_DSA_65_ETA DILITHIUM_ETA_4 /* Number of bits in private key for ML-DSA-65. */ #define PARAMS_ML_DSA_65_ETA_BITS DILITHIUM_ETA_4_BITS -/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-65. */ -#define PARAMS_ML_DSA_65_LAMBDA 24 +/* Collision strength of c-tilde, LAMBDA, in bits for ML-DSA-65. */ +#define PARAMS_ML_DSA_65_LAMBDA 192 /* # +/-1's in polynomial c, TAU, for ML-DSA-65. */ #define PARAMS_ML_DSA_65_TAU 49 /* BETA = TAU * ETA for ML-DSA-65. */ @@ -303,7 +323,7 @@ (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_65_K * DILITHIUM_N * DILITHIUM_U / 8) /* Encoding size of signature in bytes for ML-DSA-65. */ #define PARAMS_ML_DSA_65_SIG_SIZE \ - ((PARAMS_ML_DSA_65_LAMBDA * 2) + \ + ((PARAMS_ML_DSA_65_LAMBDA / 4) + \ PARAMS_ML_DSA_65_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_65_GAMMA1_BITS + 1) + \ PARAMS_ML_DSA_65_OMEGA + PARAMS_ML_DSA_65_K) @@ -319,8 +339,8 @@ #define PARAMS_ML_DSA_87_ETA DILITHIUM_ETA_2 /* Number of bits in private key for ML-DSA-87. */ #define PARAMS_ML_DSA_87_ETA_BITS DILITHIUM_ETA_2_BITS -/* Collision strength of c-tilde, LAMBDA, in bytes for ML-DSA-87. */ -#define PARAMS_ML_DSA_87_LAMBDA 32 +/* Collision strength of c-tilde, LAMBDA, in bits for ML-DSA-87. */ +#define PARAMS_ML_DSA_87_LAMBDA 256 /* # +/-1's in polynomial c, TAU, for ML-DSA-87. */ #define PARAMS_ML_DSA_87_TAU 60 /* BETA = TAU * ETA for ML-DSA-87. */ @@ -365,7 +385,7 @@ (DILITHIUM_PUB_SEED_SZ + PARAMS_ML_DSA_87_K * DILITHIUM_N * DILITHIUM_U / 8) /* Encoding size of signature in bytes for ML-DSA-87. */ #define PARAMS_ML_DSA_87_SIG_SIZE \ - ((PARAMS_ML_DSA_87_LAMBDA * 2) + \ + ((PARAMS_ML_DSA_87_LAMBDA / 4) + \ PARAMS_ML_DSA_87_L * DILITHIUM_N/8 * (PARAMS_ML_DSA_87_GAMMA1_BITS + 1) + \ PARAMS_ML_DSA_87_OMEGA + PARAMS_ML_DSA_87_K) @@ -384,6 +404,9 @@ /* Maximum count of elements of a vector with dimension L. */ #define DILITHIUM_MAX_L_VECTOR_COUNT \ (PARAMS_ML_DSA_87_L * DILITHIUM_N) +/* Maximum count of elements of a matrix with dimension KxL. */ +#define DILITHIUM_MAX_MATRIX_COUNT \ + (PARAMS_ML_DSA_87_K * PARAMS_ML_DSA_87_L * DILITHIUM_N) #elif !defined(WOLFSSL_NO_ML_DSA_65) @@ -398,6 +421,9 @@ /* Maximum count of elements of a vector with dimension L. */ #define DILITHIUM_MAX_L_VECTOR_COUNT \ (PARAMS_ML_DSA_65_L * DILITHIUM_N) +/* Maximum count of elements of a matrix with dimension KxL. */ +#define DILITHIUM_MAX_MATRIX_COUNT \ + (PARAMS_ML_DSA_65_K * PARAMS_ML_DSA_65_L * DILITHIUM_N) #else @@ -412,6 +438,9 @@ /* Maximum count of elements of a vector with dimension L. */ #define DILITHIUM_MAX_L_VECTOR_COUNT \ (PARAMS_ML_DSA_44_L * DILITHIUM_N) +/* Maximum count of elements of a matrix with dimension KxL. */ +#define DILITHIUM_MAX_MATRIX_COUNT \ + (PARAMS_ML_DSA_44_K * PARAMS_ML_DSA_44_L * DILITHIUM_N) #endif @@ -487,6 +516,25 @@ #define DILITHIUM_LEVEL5_PRV_KEY_SIZE \ (DILITHIUM_LEVEL5_PUB_KEY_SIZE+DILITHIUM_LEVEL5_KEY_SIZE) + +#define ML_DSA_LEVEL2_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_secret_key +#define ML_DSA_LEVEL2_SIG_SIZE OQS_SIG_ml_dsa_44_ipd_length_signature +#define ML_DSA_LEVEL2_PUB_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_public_key +#define ML_DSA_LEVEL2_PRV_KEY_SIZE \ + (ML_DSA_LEVEL2_PUB_KEY_SIZE+ML_DSA_LEVEL2_KEY_SIZE) + +#define ML_DSA_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key +#define ML_DSA_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature +#define ML_DSA_LEVEL3_PUB_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_public_key +#define ML_DSA_LEVEL3_PRV_KEY_SIZE \ + (ML_DSA_LEVEL3_PUB_KEY_SIZE+ML_DSA_LEVEL3_KEY_SIZE) + +#define ML_DSA_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key +#define ML_DSA_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature +#define ML_DSA_LEVEL5_PUB_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_public_key +#define ML_DSA_LEVEL5_PRV_KEY_SIZE \ + (ML_DSA_LEVEL5_PUB_KEY_SIZE+ML_DSA_LEVEL5_KEY_SIZE) + #endif #define DILITHIUM_MAX_KEY_SIZE DILITHIUM_LEVEL5_KEY_SIZE @@ -511,7 +559,7 @@ typedef struct wc_dilithium_params { byte tau; byte beta; byte omega; - byte lambda; + word16 lambda; byte gamma1_bits; word32 gamma2; word32 w1EncSz; @@ -531,6 +579,8 @@ struct dilithium_key { byte prvKeySet; byte level; /* 2,3 or 5 */ + void* heap; /* heap hint */ + #ifdef WOLF_CRYPTO_CB void* devCtx; int devId; @@ -553,6 +603,7 @@ struct dilithium_key { #ifdef WOLFSSL_WC_DILITHIUM const wc_dilithium_params* params; wc_Shake shake; +#ifndef WC_DILITHIUM_FIXED_ARRAY #ifdef WC_DILITHIUM_CACHE_MATRIX_A sword32* a; byte aSet; @@ -567,6 +618,22 @@ struct dilithium_key { sword32* t1; byte pubVecSet; #endif +#else +#ifdef WC_DILITHIUM_CACHE_MATRIX_A + sword32 a[DILITHIUM_MAX_MATRIX_COUNT]; + byte aSet; +#endif +#ifdef WC_DILITHIUM_CACHE_PRIV_VECTORS + sword32 s1[DILITHIUM_MAX_L_VECTOR_COUNT]; + sword32 s2[DILITHIUM_MAX_K_VECTOR_COUNT]; + sword32 t0[DILITHIUM_MAX_K_VECTOR_COUNT]; + byte privVecsSet; +#endif +#ifdef WC_DILITHIUM_CACHE_PUB_VECTORS + sword32 t1[DILITHIUM_MAX_K_VECTOR_COUNT]; + byte pubVecSet; +#endif +#endif #if defined(WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC) && \ defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) sword32 z[DILITHIUM_MAX_L_VECTOR_COUNT]; @@ -574,6 +641,9 @@ struct dilithium_key { sword32 w[DILITHIUM_N]; sword32 t1[DILITHIUM_N]; byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; +#ifdef WOLFSSL_DILITHIUM_SMALL_MEM_POLY64 + sword64 t64[DILITHIUM_N]; +#endif byte h[DILITHIUM_REJ_NTT_POLY_H_SIZE]; byte block[DILITHIUM_GEN_C_BLOCK_BYTES]; #endif /* WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC && @@ -595,15 +665,38 @@ WOLFSSL_API int wc_dilithium_make_key_from_seed(dilithium_key* key, const byte* seed); WOLFSSL_API -int wc_dilithium_sign_msg(const byte* in, word32 inLen, byte* out, - word32 *outLen, dilithium_key* key, WC_RNG* rng); +int wc_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, + word32* sigLen, dilithium_key* key, WC_RNG* rng); +WOLFSSL_API +int wc_dilithium_sign_ctx_msg(const byte* ctx, byte ctxLen, const byte* msg, + word32 msgLen, byte* sig, word32* sigLen, dilithium_key* key, WC_RNG* rng); +WOLFSSL_API +int wc_dilithium_sign_ctx_hash(const byte* ctx, byte ctxLen, int hashAlg, + const byte* hash, word32 hashLen, byte* sig, word32* sigLen, + dilithium_key* key, WC_RNG* rng); WOLFSSL_API -int wc_dilithium_sign_msg_with_seed(const byte* in, word32 inLen, byte* out, - word32 *outLen, dilithium_key* key, byte* seed); +int wc_dilithium_sign_msg_with_seed(const byte* msg, word32 msgLen, byte* sig, + word32 *sigLen, dilithium_key* key, const byte* seed); +WOLFSSL_API +int wc_dilithium_sign_ctx_msg_with_seed(const byte* ctx, byte ctxLen, + const byte* msg, word32 msgLen, byte* sig, word32 *sigLen, + dilithium_key* key, const byte* seed); +WOLFSSL_API +int wc_dilithium_sign_ctx_hash_with_seed(const byte* ctx, byte ctxLen, + int hashAlg, const byte* hash, word32 hashLen, byte* sig, word32 *sigLen, + dilithium_key* key, const byte* seed); #endif WOLFSSL_API int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, word32 msgLen, int* res, dilithium_key* key); +WOLFSSL_API +int wc_dilithium_verify_ctx_msg(const byte* sig, word32 sigLen, const byte* ctx, + word32 ctxLen, const byte* msg, word32 msgLen, int* res, + dilithium_key* key); +WOLFSSL_API +int wc_dilithium_verify_ctx_hash(const byte* sig, word32 sigLen, + const byte* ctx, word32 ctxLen, int hashAlg, const byte* hash, + word32 hashLen, int* res, dilithium_key* key); WOLFSSL_API int wc_dilithium_init(dilithium_key* key); @@ -672,6 +765,7 @@ int wc_dilithium_export_public(dilithium_key* key, byte* out, word32* outLen); #ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY WOLFSSL_API int wc_dilithium_export_private(dilithium_key* key, byte* out, word32* outLen); +#define wc_dilithium_export_private_only wc_dilithium_export_private #endif #ifdef WOLFSSL_DILITHIUM_PRIVATE_KEY WOLFSSL_API @@ -684,11 +778,13 @@ int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, WOLFSSL_API int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, dilithium_key* key, word32 inSz); #endif +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ #ifdef WOLFSSL_DILITHIUM_PUBLIC_KEY WOLFSSL_API int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, dilithium_key* key, word32 inSz); #endif +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 #ifdef WC_ENABLE_ASYM_KEY_EXPORT WOLFSSL_API int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 inLen, int withAlg); @@ -704,10 +800,14 @@ WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, #endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ +#define WC_ML_DSA_DRAFT 10 #define WC_ML_DSA_44 2 #define WC_ML_DSA_65 3 #define WC_ML_DSA_87 5 +#define WC_ML_DSA_44_DRAFT (2 + WC_ML_DSA_DRAFT) +#define WC_ML_DSA_65_DRAFT (3 + WC_ML_DSA_DRAFT) +#define WC_ML_DSA_87_DRAFT (5 + WC_ML_DSA_DRAFT) #define DILITHIUM_ML_DSA_44_KEY_SIZE 2560 #define DILITHIUM_ML_DSA_44_SIG_SIZE 2420 @@ -742,7 +842,7 @@ WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, #define wc_MlDsaKey_ExportPrivRaw(key, out, outLen) \ wc_dilithium_export_private_only(key, out, outLen) #define wc_MlDsaKey_ImportPrivRaw(key, in, inLen) \ - wc_dilithium_import_private_only(out, outLen, key) + wc_dilithium_import_private_only(in, inLen, key) #define wc_MlDsaKey_Sign(key, sig, sigSz, msg, msgSz, rng) \ wc_dilithium_sign_msg(msg, msgSz, sig, sigSz, key, rng) #define wc_MlDsaKey_Free(key) \ @@ -750,7 +850,7 @@ WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, #define wc_MlDsaKey_ExportPubRaw(key, out, outLen) \ wc_dilithium_export_public(key, out, outLen) #define wc_MlDsaKey_ImportPubRaw(key, in, inLen) \ - wc_dilithium_import_public(out, outLen, key) + wc_dilithium_import_public(in, inLen, key) #define wc_MlDsaKey_Verify(key, sig, sigSz, msg, msgSz, res) \ wc_dilithium_verify_msg(sig, sigSz, msg, msgSz, res, key) diff --git a/src/wolfssl/wolfcrypt/dsa.h b/src/wolfssl/wolfcrypt/dsa.h index d5ae3a4..1e92fd5 100644 --- a/src/wolfssl/wolfcrypt/dsa.h +++ b/src/wolfssl/wolfcrypt/dsa.h @@ -1,6 +1,6 @@ /* dsa.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ecc.h b/src/wolfssl/wolfcrypt/ecc.h index 4a198a6..71a7a8b 100644 --- a/src/wolfssl/wolfcrypt/ecc.h +++ b/src/wolfssl/wolfcrypt/ecc.h @@ -1,6 +1,6 @@ /* ecc.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -467,6 +467,7 @@ struct ecc_point { #if defined(WOLFSSL_SMALL_STACK_CACHE) && !defined(WOLFSSL_ECC_NO_SMALL_STACK) ecc_key* key; #endif + WC_BITFIELD isAllocated:1; }; /* ECC Flags */ @@ -589,12 +590,13 @@ struct ecc_key { mp_int* sign_k; #else mp_int sign_k[1]; - byte sign_k_set:1; + WC_BITFIELD sign_k_set:1; #endif #endif #if defined(WOLFSSL_ECDSA_DETERMINISTIC_K) || \ defined(WOLFSSL_ECDSA_DETERMINISTIC_K_VARIANT) - byte deterministic:1; + WC_BITFIELD deterministic:1; + enum wc_HashType hashType; #endif #if defined(WOLFSSL_SMALL_STACK_CACHE) && !defined(WOLFSSL_ECC_NO_SMALL_STACK) @@ -640,8 +642,15 @@ WOLFSSL_ABI WOLFSSL_API void wc_ecc_key_free(ecc_key* key); /* ECC predefined curve sets */ -extern const ecc_set_type ecc_sets[]; -extern const size_t ecc_sets_count; +#if defined(HAVE_FIPS) && FIPS_VERSION3_LT(6,0,0) + extern const ecc_set_type ecc_sets[]; + extern const size_t ecc_sets_count; +#else + WOLFSSL_API const ecc_set_type *wc_ecc_get_sets(void); + WOLFSSL_API size_t wc_ecc_get_sets_count(void); + #define ecc_sets wc_ecc_get_sets() + #define ecc_sets_count wc_ecc_get_sets_count() +#endif WOLFSSL_API const char* wc_ecc_get_name(int curve_id); @@ -719,6 +728,9 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, WOLFSSL_API int wc_ecc_set_deterministic(ecc_key* key, byte flag); WOLFSSL_API +int wc_ecc_set_deterministic_ex(ecc_key* key, byte flag, + enum wc_HashType hashType); +WOLFSSL_API int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, enum wc_HashType hashType, mp_int* priv, mp_int* k, mp_int* order, void* heap); @@ -759,7 +771,7 @@ WOLFSSL_API int wc_ecc_set_flags(ecc_key* key, word32 flags); WOLFSSL_ABI WOLFSSL_API void wc_ecc_fp_free(void); -WOLFSSL_LOCAL +WOLFSSL_API void wc_ecc_fp_init(void); WOLFSSL_API int wc_ecc_set_rng(ecc_key* key, WC_RNG* rng); @@ -1016,6 +1028,11 @@ WOLFSSL_API int wc_ecc_curve_cache_init(void); WOLFSSL_API void wc_ecc_curve_cache_free(void); #endif +#ifdef HAVE_OID_ENCODING +WOLFSSL_LOCAL int wc_ecc_oid_cache_init(void); +WOLFSSL_LOCAL void wc_ecc_oid_cache_free(void); +#endif + WOLFSSL_API int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order); diff --git a/src/wolfssl/wolfcrypt/eccsi.h b/src/wolfssl/wolfcrypt/eccsi.h index 8e0124c..34e10bf 100644 --- a/src/wolfssl/wolfcrypt/eccsi.h +++ b/src/wolfssl/wolfcrypt/eccsi.h @@ -1,6 +1,6 @@ /* eccsi.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -62,15 +62,15 @@ typedef struct EccsiKeyParams { ecc_point* base; /** Bit indicates order (q) is set as an MP integer in ECCSI key. */ - byte haveOrder:1; + WC_BITFIELD haveOrder:1; /** Bit indicates A is set as an MP integer in ECCSI key. */ - byte haveA:1; + WC_BITFIELD haveA:1; /** Bit indicates B is set as an MP integer in ECCSI key. */ - byte haveB:1; + WC_BITFIELD haveB:1; /** Bit indicates prime is set as an MP integer in ECCSI key. */ - byte havePrime:1; + WC_BITFIELD havePrime:1; /** Bit indicates base point is set as an MP integer in ECCSI key. */ - byte haveBase:1; + WC_BITFIELD haveBase:1; } EccsiKeyParams; /** @@ -104,7 +104,7 @@ typedef struct EccsiKey { /** Heap hint for dynamic memory allocation. */ void* heap; /** Bit indicates KPAK (public key) is in montgomery form. */ - word16 kpakMont:1; + WC_BITFIELD kpakMont:1; } EccsiKey; #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/ed25519.h b/src/wolfssl/wolfcrypt/ed25519.h index efba650..8c660b2 100644 --- a/src/wolfssl/wolfcrypt/ed25519.h +++ b/src/wolfssl/wolfcrypt/ed25519.h @@ -1,6 +1,6 @@ /* ed25519.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -94,8 +94,9 @@ struct ed25519_key { word32 flags; byte keyIdSet; #endif - word16 privKeySet:1; - word16 pubKeySet:1; + WC_BITFIELD privKeySet:1; + WC_BITFIELD pubKeySet:1; + WC_BITFIELD sha_clean_flag:1; /* only used if WOLFSSL_ED25519_PERSISTENT_SHA */ #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #endif @@ -106,7 +107,6 @@ struct ed25519_key { void *heap; #ifdef WOLFSSL_ED25519_PERSISTENT_SHA wc_Sha512 sha; - int sha_clean_flag; #endif }; @@ -175,13 +175,20 @@ int wc_ed25519_verify_msg_final(const byte* sig, word32 sigLen, int* res, #endif /* WOLFSSL_ED25519_STREAMING_VERIFY */ #endif /* HAVE_ED25519_VERIFY */ - WOLFSSL_API int wc_ed25519_init(ed25519_key* key); WOLFSSL_API int wc_ed25519_init_ex(ed25519_key* key, void* heap, int devId); WOLFSSL_API void wc_ed25519_free(ed25519_key* key); +#ifndef WC_NO_CONSTRUCTORS +WOLFSSL_API +ed25519_key* wc_ed25519_new(void* heap, int devId, int *result_code); +WOLFSSL_API +int wc_ed25519_delete(ed25519_key* key, ed25519_key** key_p); +#endif +WOLFSSL_API + #ifdef HAVE_ED25519_KEY_IMPORT WOLFSSL_API int wc_ed25519_import_public(const byte* in, word32 inLen, ed25519_key* key); diff --git a/src/wolfssl/wolfcrypt/ed448.h b/src/wolfssl/wolfcrypt/ed448.h index 5884bda..9e2e890 100644 --- a/src/wolfssl/wolfcrypt/ed448.h +++ b/src/wolfssl/wolfcrypt/ed448.h @@ -1,6 +1,6 @@ /* ed448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -85,8 +85,8 @@ struct ed448_key { byte pointX[ED448_KEY_SIZE]; /* recovered X coordinate */ byte pointY[ED448_KEY_SIZE]; /* Y coordinate is the public key with The most significant bit of the final octet always zero. */ #endif - word16 privKeySet:1; - word16 pubKeySet:1; + WC_BITFIELD privKeySet:1; + WC_BITFIELD pubKeySet:1; #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #endif @@ -97,7 +97,7 @@ struct ed448_key { void *heap; #ifdef WOLFSSL_ED448_PERSISTENT_SHA wc_Shake sha; - int sha_clean_flag; + unsigned int sha_clean_flag : 1; #endif }; diff --git a/src/wolfssl/wolfcrypt/error-crypt.h b/src/wolfssl/wolfcrypt/error-crypt.h index dbe0553..3f188f7 100644 --- a/src/wolfssl/wolfcrypt/error-crypt.h +++ b/src/wolfssl/wolfcrypt/error-crypt.h @@ -1,6 +1,6 @@ /* error-crypt.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -37,10 +37,25 @@ the error status. extern "C" { #endif +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H +#include +#endif /* error codes, add string for new errors !!! */ -enum { - MAX_CODE_E = -100, /* errors -101 - -299 */ +enum wolfCrypt_ErrorCodes { + /* note that WOLFSSL_FATAL_ERROR is defined as -1 in error-ssl.h, for + * reasons of backward compatibility. + */ + + MAX_CODE_E = -96, /* errors -97 - -299 */ + WC_FIRST_E = -97, /* errors -97 - -299 */ + + MP_MEM = -97, /* MP dynamic memory allocation failed. */ + MP_VAL = -98, /* MP value passed is not able to be used. */ + MP_WOULDBLOCK = -99, /* MP non-blocking operation is returning after + * partial completion. */ + MP_NOT_INF = -100, /* MP point not at infinity */ + OPEN_RAN_E = -101, /* opening random device error */ READ_RAN_E = -102, /* reading random device error */ WINCRYPT_E = -103, /* windows crypt init error */ @@ -276,13 +291,12 @@ enum { SM4_CCM_AUTH_E = -299, /* SM4-CCM Authentication check failure */ WC_LAST_E = -299, /* Update this to indicate last error */ - MIN_CODE_E = -300 /* errors -101 - -299 */ + MIN_CODE_E = -300 /* errors -2 - -299 */ /* add new companion error id strings for any new error codes wolfcrypt/src/error.c !!! */ }; - #ifdef NO_ERROR_STRINGS #define wc_GetErrorString(error) "no support for error strings built in" #define wc_ErrorString(err, buf) \ @@ -294,16 +308,35 @@ WOLFSSL_API void wc_ErrorString(int err, char* buff); WOLFSSL_ABI WOLFSSL_API const char* wc_GetErrorString(int error); #endif -#if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && !defined(BUILDING_WOLFSSL) - #undef WOLFSSL_DEBUG_TRACE_ERROR_CODES -#endif -#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && \ + (defined(BUILDING_WOLFSSL) || \ + defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES_ALWAYS)) + WOLFSSL_API extern void wc_backtrace_render(void); #define WC_NO_ERR_TRACE(label) (CONST_NUM_ERR_ ## label) + #ifndef WOLFSSL_DEBUG_BACKTRACE_RENDER_CLAUSE + #ifdef WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES + #define WOLFSSL_DEBUG_BACKTRACE_RENDER_CLAUSE wc_backtrace_render() + #else + #define WOLFSSL_DEBUG_BACKTRACE_RENDER_CLAUSE (void)0 + #endif + #endif #ifndef WC_ERR_TRACE + #ifdef NO_STDIO_FILESYSTEM + #define WC_ERR_TRACE(label) \ + ( printf("ERR TRACE: %s L %d %s (%d)\n", \ + __FILE__, __LINE__, #label, label), \ + WOLFSSL_DEBUG_BACKTRACE_RENDER_CLAUSE, \ + label \ + ) + #else #define WC_ERR_TRACE(label) \ ( fprintf(stderr, \ - "ERR TRACE: %s L %d " #label " (%d)\n", \ - __FILE__, __LINE__, label), label) + "ERR TRACE: %s L %d %s (%d)\n", \ + __FILE__, __LINE__, #label, label), \ + WOLFSSL_DEBUG_BACKTRACE_RENDER_CLAUSE, \ + label \ + ) + #endif #endif #include #else diff --git a/src/wolfssl/wolfcrypt/ext_kyber.h b/src/wolfssl/wolfcrypt/ext_kyber.h index 0ea7108..6e7f690 100644 --- a/src/wolfssl/wolfcrypt/ext_kyber.h +++ b/src/wolfssl/wolfcrypt/ext_kyber.h @@ -1,6 +1,6 @@ /* ext_kyber.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,8 +29,8 @@ #ifdef WOLFSSL_HAVE_KYBER #include -#if !defined(HAVE_LIBOQS) && !defined(HAVE_PQM4) -#error "This code requires liboqs or pqm4" +#if !defined(HAVE_LIBOQS) +#error "This code requires liboqs" #endif #if defined(WOLFSSL_WC_KYBER) @@ -41,15 +41,6 @@ #include #define EXT_KYBER_MAX_PRIV_SZ OQS_KEM_kyber_1024_length_secret_key #define EXT_KYBER_MAX_PUB_SZ OQS_KEM_kyber_1024_length_public_key -#elif defined(HAVE_PQM4) - #include "api_kyber.h" - #define PQM4_PUBLIC_KEY_LENGTH CRYPTO_PUBLICKEYBYTES - #define PQM4_PRIVATE_KEY_LENGTH CRYPTO_SECRETKEYBYTES - #define PQM4_SHARED_SECRET_LENGTH CRYPTO_BYTES - #define PQM4_CIPHERTEXT_LENGTH CRYPTO_CIPHERTEXTBYTES - - #define EXT_KYBER_MAX_PRIV_SZ PQM4_PRIVATE_KEY_LENGTH - #define EXT_KYBER_MAX_PUB_SZ PQM4_PUBLIC_KEY_LENGTH #endif struct KyberKey { diff --git a/src/wolfssl/wolfcrypt/ext_lms.h b/src/wolfssl/wolfcrypt/ext_lms.h index fae812f..4120335 100644 --- a/src/wolfssl/wolfcrypt/ext_lms.h +++ b/src/wolfssl/wolfcrypt/ext_lms.h @@ -1,6 +1,6 @@ /* ext_lms.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,12 +22,9 @@ #ifndef EXT_LMS_H #define EXT_LMS_H -#ifdef WOLFSSL_HAVE_LMS -#include +#if defined(WOLFSSL_HAVE_LMS) && defined(HAVE_LIBLMS) -#if !defined(HAVE_LIBLMS) -#error "This code requires liblms" -#endif +#include /* hash-sigs LMS HSS includes */ #include diff --git a/src/wolfssl/wolfcrypt/ext_xmss.h b/src/wolfssl/wolfcrypt/ext_xmss.h index 5f51bf5..cb041bc 100644 --- a/src/wolfssl/wolfcrypt/ext_xmss.h +++ b/src/wolfssl/wolfcrypt/ext_xmss.h @@ -1,6 +1,6 @@ /* ext_xmss.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,12 +22,9 @@ #ifndef EXT_XMSS_H #define EXT_XMSS_H -#ifdef WOLFSSL_HAVE_XMSS -#include +#if defined(WOLFSSL_HAVE_XMSS) && defined(HAVE_LIBXMSS) -#if !defined(HAVE_LIBXMSS) - #error "This code requires libxmss" -#endif +#include #include #include diff --git a/src/wolfssl/wolfcrypt/falcon.h b/src/wolfssl/wolfcrypt/falcon.h index 9d4bff8..a103034 100644 --- a/src/wolfssl/wolfcrypt/falcon.h +++ b/src/wolfssl/wolfcrypt/falcon.h @@ -1,6 +1,6 @@ /* falcon.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/fe_448.h b/src/wolfssl/wolfcrypt/fe_448.h index c925d7d..09ff150 100644 --- a/src/wolfssl/wolfcrypt/fe_448.h +++ b/src/wolfssl/wolfcrypt/fe_448.h @@ -1,6 +1,6 @@ /* fe448_448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/fe_operations.h b/src/wolfssl/wolfcrypt/fe_operations.h index 8a1cab7..23928f2 100644 --- a/src/wolfssl/wolfcrypt/fe_operations.h +++ b/src/wolfssl/wolfcrypt/fe_operations.h @@ -1,6 +1,6 @@ /* fe_operations.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/fips_test.h b/src/wolfssl/wolfcrypt/fips_test.h index 452e651..6523753 100644 --- a/src/wolfssl/wolfcrypt/fips_test.h +++ b/src/wolfssl/wolfcrypt/fips_test.h @@ -1,6 +1,6 @@ /* fips_test.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -114,6 +114,13 @@ WOLFSSL_API int wc_RunCast_fips(int type); WOLFSSL_API int wc_GetCastStatus_fips(int type); WOLFSSL_API int wc_RunAllCast_fips(void); +#ifdef NO_ATTRIBUTE_CONSTRUCTOR + /* NOTE: Must be called in OS initialization section outside user control + * and must prove during operational testing/code review with the lab that + * this is outside user-control if called by the OS */ + void fipsEntry(void); +#endif + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/ge_448.h b/src/wolfssl/wolfcrypt/ge_448.h index 38ac71a..bbdb067 100644 --- a/src/wolfssl/wolfcrypt/ge_448.h +++ b/src/wolfssl/wolfcrypt/ge_448.h @@ -1,6 +1,6 @@ /* ge_448.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ge_operations.h b/src/wolfssl/wolfcrypt/ge_operations.h index 0c6ce8d..75d4b07 100644 --- a/src/wolfssl/wolfcrypt/ge_operations.h +++ b/src/wolfssl/wolfcrypt/ge_operations.h @@ -1,6 +1,6 @@ /* ge_operations.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -112,7 +112,6 @@ typedef struct { ge Z; ge T2d; } ge_cached; -#endif /* !ED25519_SMALL */ #ifdef CURVED25519_ASM void ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p); @@ -124,6 +123,7 @@ void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q); void ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q); void ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q); #endif +#endif /* !ED25519_SMALL */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/hash.h b/src/wolfssl/wolfcrypt/hash.h index 27b1423..edbc949 100644 --- a/src/wolfssl/wolfcrypt/hash.h +++ b/src/wolfssl/wolfcrypt/hash.h @@ -1,6 +1,6 @@ /* hash.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -80,7 +80,7 @@ enum wc_MACAlgorithm { sha512_mac, rmd_mac, blake2b_mac, - sm3_mac, + sm3_mac }; enum wc_HashFlags { @@ -93,32 +93,41 @@ enum wc_HashFlags { WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) }; -#ifndef NO_HASH_WRAPPER +/* hash union */ typedef union { - #ifndef NO_MD5 - wc_Md5 md5; - #endif - #ifndef NO_SHA - wc_Sha sha; - #endif - #ifdef WOLFSSL_SHA224 - wc_Sha224 sha224; - #endif - #ifndef NO_SHA256 - wc_Sha256 sha256; - #endif - #ifdef WOLFSSL_SHA384 - wc_Sha384 sha384; - #endif - #ifdef WOLFSSL_SHA512 - wc_Sha512 sha512; - #endif - #ifdef WOLFSSL_SHA3 - wc_Sha3 sha3; - #endif - #ifdef WOLFSSL_SM3 - wc_Sm3 sm3; - #endif +#ifndef NO_MD5 + wc_Md5 md5; +#endif +#ifndef NO_SHA + wc_Sha sha; +#endif +#ifdef WOLFSSL_SHA224 + wc_Sha224 sha224; +#endif +#ifndef NO_SHA256 + wc_Sha256 sha256; +#endif +#ifdef WOLFSSL_SHA384 + wc_Sha384 sha384; +#endif +#ifdef WOLFSSL_SHA512 + wc_Sha512 sha512; +#endif +#ifdef WOLFSSL_SHA3 + wc_Sha3 sha3; +#endif +#ifdef WOLFSSL_SM3 + wc_Sm3 sm3; +#endif +} wc_Hashes; + +#ifndef NO_HASH_WRAPPER +typedef struct { + wc_Hashes alg; + enum wc_HashType type; /* sanity check */ +#ifndef WC_NO_CONSTRUCTORS + void *heap; +#endif } wc_HashAlg; #endif /* !NO_HASH_WRAPPER */ @@ -183,6 +192,11 @@ WOLFSSL_API int wc_HashUpdate(wc_HashAlg* hash, enum wc_HashType type, WOLFSSL_API int wc_HashFinal(wc_HashAlg* hash, enum wc_HashType type, byte* out); WOLFSSL_API int wc_HashFree(wc_HashAlg* hash, enum wc_HashType type); +#ifndef WC_NO_CONSTRUCTORS +WOLFSSL_API wc_HashAlg* wc_HashNew(enum wc_HashType type, void* heap, + int devId, int *result_code); +WOLFSSL_API int wc_HashDelete(wc_HashAlg *hash, wc_HashAlg **hash_p); +#endif #ifdef WOLFSSL_HASH_FLAGS WOLFSSL_API int wc_HashSetFlags(wc_HashAlg* hash, enum wc_HashType type, diff --git a/src/wolfssl/wolfcrypt/hmac.h b/src/wolfssl/wolfcrypt/hmac.h index 0d0844e..fd5d8d3 100644 --- a/src/wolfssl/wolfcrypt/hmac.h +++ b/src/wolfssl/wolfcrypt/hmac.h @@ -1,6 +1,6 @@ /* hmac.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -119,34 +119,7 @@ enum { #error "You have to have some kind of hash if you want to use HMAC." #endif - -/* hmac hash union */ -typedef union { -#ifndef NO_MD5 - wc_Md5 md5; -#endif -#ifndef NO_SHA - wc_Sha sha; -#endif -#ifdef WOLFSSL_SHA224 - wc_Sha224 sha224; -#endif -#ifndef NO_SHA256 - wc_Sha256 sha256; -#endif -#ifdef WOLFSSL_SHA384 - wc_Sha384 sha384; -#endif -#ifdef WOLFSSL_SHA512 - wc_Sha512 sha512; -#endif -#ifdef WOLFSSL_SHA3 - wc_Sha3 sha3; -#endif -#ifdef WOLFSSL_SM3 - wc_Sm3 sm3; -#endif -} wc_HmacHash; +typedef wc_Hashes wc_HmacHash; /* Hmac digest */ struct Hmac { diff --git a/src/wolfssl/wolfcrypt/hpke.h b/src/wolfssl/wolfcrypt/hpke.h index 432f574..6e406ba 100644 --- a/src/wolfssl/wolfcrypt/hpke.h +++ b/src/wolfssl/wolfcrypt/hpke.h @@ -1,6 +1,6 @@ /* hpke.h * - * Copyright (C) 2006-2022 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/integer.h b/src/wolfssl/wolfcrypt/integer.h index 243d3f0..927a1f6 100644 --- a/src/wolfssl/wolfcrypt/integer.h +++ b/src/wolfssl/wolfcrypt/integer.h @@ -1,6 +1,6 @@ /* integer.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -42,6 +42,8 @@ #else +#include +#include #include #ifndef CHAR_BIT @@ -162,9 +164,6 @@ extern "C" { #define MP_NEG 1 /* negative */ #define MP_OKAY 0 /* ok result */ -#define MP_MEM (-2) /* out of mem */ -#define MP_VAL (-3) /* invalid input */ -#define MP_NOT_INF (-4) /* point not at infinity */ #define MP_RANGE MP_NOT_INF #define MP_YES 1 /* yes response */ @@ -223,6 +222,9 @@ typedef int mp_err; #define WOLF_BIGINT_DEFINED #endif +#define mp_size_t int +#define mp_sign_t int + /* the mp_int structure */ typedef struct mp_int { int used, alloc, sign; diff --git a/src/wolfssl/wolfcrypt/kdf.h b/src/wolfssl/wolfcrypt/kdf.h index ad107e5..66b3a7a 100644 --- a/src/wolfssl/wolfcrypt/kdf.h +++ b/src/wolfssl/wolfcrypt/kdf.h @@ -1,6 +1,6 @@ /* kdf.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -140,7 +140,7 @@ WOLFSSL_API int wc_SSH_KDF(byte hashId, byte keyId, /* Indicators */ enum { WC_SRTCP_32BIT_IDX = 0, - WC_SRTCP_48BIT_IDX = 1, + WC_SRTCP_48BIT_IDX = 1 }; /* Maximum length of salt that can be used with SRTP/SRTCP. */ diff --git a/src/wolfssl/wolfcrypt/kyber.h b/src/wolfssl/wolfcrypt/kyber.h index 8e9a7b3..93b5022 100644 --- a/src/wolfssl/wolfcrypt/kyber.h +++ b/src/wolfssl/wolfcrypt/kyber.h @@ -1,6 +1,6 @@ /* kyber.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -213,6 +213,58 @@ WOLFSSL_API int wc_KyberKey_EncodePrivateKey(KyberKey* key, unsigned char* out, WOLFSSL_API int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len); + + +#define WC_ML_KEM_512_K KYBER512_K +#define WC_ML_KEM_512_PUBLIC_KEY_SIZE KYBER512_PUBLIC_KEY_SIZE +#define wC_ML_KEM_512_PRIVATE_KEY_SIZE KYBER512_PRIVATE_KEY_SIZE +#define wC_ML_KEM_512_CIPHER_TEXT_SIZE KYBER512_CIPHER_TEXT_SIZE + +#define WC_ML_KEM_768_K KYBER768_K +#define WC_ML_KEM_768_PUBLIC_KEY_SIZE KYBER768_PUBLIC_KEY_SIZE +#define wC_ML_KEM_768_PRIVATE_KEY_SIZE KYBER768_PRIVATE_KEY_SIZE +#define wC_ML_KEM_768_CIPHER_TEXT_SIZE KYBER768_CIPHER_TEXT_SIZE + +#define WC_ML_KEM_1024_K KYBER1024_K +#define WC_ML_KEM_1024_PUBLIC_KEY_SIZE KYBER1024_PUBLIC_KEY_SIZE +#define wC_ML_KEM_1024_PRIVATE_KEY_SIZE KYBER1024_PRIVATE_KEY_SIZE +#define wC_ML_KEM_1024_CIPHER_TEXT_SIZE KYBER1024_CIPHER_TEXT_SIZE + +#define WC_ML_KEM_MAX_K KYBER_MAX_K +#define WC_ML_KEM_MAX_PRIVATE_KEY_SIZE KYBER_MAX_PRIVATE_KEY_SIZE +#define WC_ML_KEM_MAX_PUBLIC_KEY_SIZE KYBER_MAX_PUBLIC_KEY_SIZE +#define WC_ML_KEM_MAX_CIPHER_TEXT_SIZE KYBER_MAX_CIPHER_TEXT_SIZE + +#define WC_ML_KEM_512 KYBER512 +#define WC_ML_KEM_768 KYBER768 +#define WC_ML_KEM_1024 KYBER1024 + +#define WC_ML_KEM_SYM_SZ KYBER_SYM_SZ +#define WC_ML_KEM_SS_SZ KYBER_SS_SZ +#define WC_ML_KEM_MAKEKEY_RAND_SZ KYBER_MAKEKEY_RAND_SZ +#define WC_ML_KEM_ENC_RAND_SZ KYBER_ENC_RAND_SZ +#define WC_ML_KEM_POLY_SIZE KYBER_POLY_SIZE + +#define MlKemKey KyberKey + +#define wc_MlKemKey_Init(key, type, heap, devId) \ + wc_KyberKey_Init(type, key, heap, devId) +#define wc_MlKemKey_Free wc_KyberKey_Free +#define wc_MlKemKey_MakeKey wc_KyberKey_MakeKey +#define wc_MlKemKey_MakeKeyWithRandom wc_KyberKey_MakeKeyWithRandom +#define wc_MlKemKey_CipherTextSize wc_KyberKey_CipherTextSize +#define wc_MlKemKey_SharedSecretSize wc_KyberKey_SharedSecretSize +#define wc_MlKemKey_Encapsulate wc_KyberKey_Encapsulate +#define wc_MlKemKey_EncapsulateWithRandom wc_KyberKey_EncapsulateWithRandom +#define wc_MlKemKey_Decapsulate wc_KyberKey_Encapsulate +#define wc_MlKemKey_DecodePrivateKey wc_KyberKey_DecodePrivateKey +#define wc_MlKemKey_DecodePublicKey wc_KyberKey_DecodePublicKey +#define wc_MlKemKey_PrivateKeySize wc_KyberKey_PrivateKeySize +#define wc_MlKemKey_PublicKeySize wc_KyberKey_PublicKeySize +#define wc_MlKemKey_EncodePrivateKey wc_KyberKey_EncodePrivateKey +#define wc_MlKemKey_EncodePublicKey wc_KyberKey_EncodePublicKey + + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/lms.h b/src/wolfssl/wolfcrypt/lms.h index fe87388..1534fb1 100644 --- a/src/wolfssl/wolfcrypt/lms.h +++ b/src/wolfssl/wolfcrypt/lms.h @@ -1,6 +1,6 @@ /* lms.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -78,6 +78,7 @@ enum wc_LmsRc { * Not predefining many sets with Winternitz=1, because the signatures * will be large. */ enum wc_LmsParm { +#ifndef WOLFSSL_NO_LMS_SHA256_256 WC_LMS_PARM_NONE = 0, WC_LMS_PARM_L1_H5_W1 = 1, WC_LMS_PARM_L1_H5_W2 = 2, @@ -114,6 +115,27 @@ enum wc_LmsParm { WC_LMS_PARM_L4_H5_W8 = 33, WC_LMS_PARM_L4_H10_W4 = 34, WC_LMS_PARM_L4_H10_W8 = 35, +#endif + +#ifdef WOLFSSL_LMS_SHA256_192 + WC_LMS_PARM_SHA256_192_L1_H5_W1 = 36, + WC_LMS_PARM_SHA256_192_L1_H5_W2 = 37, + WC_LMS_PARM_SHA256_192_L1_H5_W4 = 38, + WC_LMS_PARM_SHA256_192_L1_H5_W8 = 39, + WC_LMS_PARM_SHA256_192_L1_H10_W2 = 40, + WC_LMS_PARM_SHA256_192_L1_H10_W4 = 41, + WC_LMS_PARM_SHA256_192_L1_H10_W8 = 42, + WC_LMS_PARM_SHA256_192_L1_H15_W2 = 43, + WC_LMS_PARM_SHA256_192_L1_H15_W4 = 44, + WC_LMS_PARM_SHA256_192_L2_H10_W2 = 45, + WC_LMS_PARM_SHA256_192_L2_H10_W4 = 46, + WC_LMS_PARM_SHA256_192_L2_H10_W8 = 47, + WC_LMS_PARM_SHA256_192_L3_H5_W2 = 48, + WC_LMS_PARM_SHA256_192_L3_H5_W4 = 49, + WC_LMS_PARM_SHA256_192_L3_H5_W8 = 50, + WC_LMS_PARM_SHA256_192_L3_H10_W4 = 51, + WC_LMS_PARM_SHA256_192_L4_H5_W8 = 52, +#endif }; /* enum wc_LmsState is to help track the state of an LMS/HSS Key. */ diff --git a/src/wolfssl/wolfcrypt/logging.h b/src/wolfssl/wolfcrypt/logging.h index d17f834..7d349fe 100644 --- a/src/wolfssl/wolfcrypt/logging.h +++ b/src/wolfssl/wolfcrypt/logging.h @@ -1,6 +1,6 @@ /* logging.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/md2.h b/src/wolfssl/wolfcrypt/md2.h index e326a4d..fe92756 100644 --- a/src/wolfssl/wolfcrypt/md2.h +++ b/src/wolfssl/wolfcrypt/md2.h @@ -1,6 +1,6 @@ /* md2.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/md4.h b/src/wolfssl/wolfcrypt/md4.h index f367cde..c4bd266 100644 --- a/src/wolfssl/wolfcrypt/md4.h +++ b/src/wolfssl/wolfcrypt/md4.h @@ -1,6 +1,6 @@ /* md4.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/md5.h b/src/wolfssl/wolfcrypt/md5.h index 6506be9..c19f6c1 100644 --- a/src/wolfssl/wolfcrypt/md5.h +++ b/src/wolfssl/wolfcrypt/md5.h @@ -1,6 +1,6 @@ /* md5.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/mem_track.h b/src/wolfssl/wolfcrypt/mem_track.h index c6d8163..b45bf23 100644 --- a/src/wolfssl/wolfcrypt/mem_track.h +++ b/src/wolfssl/wolfcrypt/mem_track.h @@ -1,6 +1,6 @@ /* mem_track.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/memory.h b/src/wolfssl/wolfcrypt/memory.h index 31b6a28..481f8aa 100644 --- a/src/wolfssl/wolfcrypt/memory.h +++ b/src/wolfssl/wolfcrypt/memory.h @@ -1,6 +1,6 @@ /* memory.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/misc.h b/src/wolfssl/wolfcrypt/misc.h index 9761d68..9acc31b 100644 --- a/src/wolfssl/wolfcrypt/misc.h +++ b/src/wolfssl/wolfcrypt/misc.h @@ -1,6 +1,6 @@ /* misc.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -76,6 +76,14 @@ int ConstantCompare(const byte* a, const byte* b, int length); #ifdef WORD64_AVAILABLE WOLFSSL_LOCAL +word64 readUnalignedWord64(const byte *in); +WOLFSSL_LOCAL +word64 writeUnalignedWord64(void *out, word64 in); +WOLFSSL_LOCAL +void readUnalignedWords64(word64 *out, const byte *in, size_t count); +WOLFSSL_LOCAL +void writeUnalignedWords64(byte *out, const word64 *in, size_t count); +WOLFSSL_LOCAL word64 rotlFixed64(word64 x, word64 y); WOLFSSL_LOCAL word64 rotrFixed64(word64 x, word64 y); @@ -145,6 +153,7 @@ WOLFSSL_LOCAL word32 w64GetLow32(w64wrapper n); WOLFSSL_LOCAL word32 w64GetHigh32(w64wrapper n); WOLFSSL_LOCAL void w64SetLow32(w64wrapper *n, word32 low); WOLFSSL_LOCAL w64wrapper w64Add32(w64wrapper a, word32 b, byte *wrap); +WOLFSSL_LOCAL w64wrapper w64Add(w64wrapper a, w64wrapper b, byte *wrap); WOLFSSL_LOCAL w64wrapper w64Sub32(w64wrapper a, word32 b, byte *wrap); WOLFSSL_LOCAL byte w64GT(w64wrapper a, w64wrapper b); WOLFSSL_LOCAL byte w64IsZero(w64wrapper a); @@ -157,6 +166,7 @@ WOLFSSL_LOCAL w64wrapper w64Sub(w64wrapper a, w64wrapper b); WOLFSSL_LOCAL void w64Zero(w64wrapper *a); WOLFSSL_LOCAL w64wrapper w64ShiftRight(w64wrapper a, int shift); WOLFSSL_LOCAL w64wrapper w64ShiftLeft(w64wrapper a, int shift); +WOLFSSL_LOCAL w64wrapper w64Mul(word32 a, word32 b); #else /* !NO_INLINE */ diff --git a/src/wolfssl/wolfcrypt/mpi_class.h b/src/wolfssl/wolfcrypt/mpi_class.h index 0736d6f..831fae3 100644 --- a/src/wolfssl/wolfcrypt/mpi_class.h +++ b/src/wolfssl/wolfcrypt/mpi_class.h @@ -1,6 +1,6 @@ /* mpi_class.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/mpi_superclass.h b/src/wolfssl/wolfcrypt/mpi_superclass.h index abfac6a..f27f61a 100644 --- a/src/wolfssl/wolfcrypt/mpi_superclass.h +++ b/src/wolfssl/wolfcrypt/mpi_superclass.h @@ -1,6 +1,6 @@ /* mpi_superclass.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pkcs11.h b/src/wolfssl/wolfcrypt/pkcs11.h index c754784..7a53710 100644 --- a/src/wolfssl/wolfcrypt/pkcs11.h +++ b/src/wolfssl/wolfcrypt/pkcs11.h @@ -1,6 +1,6 @@ /* pkcs11.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -138,14 +138,22 @@ extern "C" { #define CKA_HAS_RESET 0x00000302UL #define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000UL +#define CKM_RSA_PKCS 0x00000001UL #define CKM_RSA_X_509 0x00000003UL +#define CKM_RSA_PKCS_OAEP 0x00000009UL +#define CKM_RSA_PKCS_PSS 0x0000000DUL #define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020UL #define CKM_DH_PKCS_DERIVE 0x00000021UL #define CKM_MD5_HMAC 0x00000211UL +#define CKM_SHA_1 0x00000220UL #define CKM_SHA_1_HMAC 0x00000221UL +#define CKM_SHA256 0x00000250UL #define CKM_SHA256_HMAC 0x00000251UL +#define CKM_SHA224 0x00000255UL #define CKM_SHA224_HMAC 0x00000256UL +#define CKM_SHA384 0x00000260UL #define CKM_SHA384_HMAC 0x00000261UL +#define CKM_SHA512 0x00000270UL #define CKM_SHA512_HMAC 0x00000271UL #define CKM_GENERIC_SECRET_KEY_GEN 0x00000350UL #define CKM_EC_KEY_PAIR_GEN 0x00001040UL @@ -156,12 +164,26 @@ extern "C" { #define CKM_AES_CBC 0x00001082UL #define CKM_AES_GCM 0x00001087UL +/* full data RSA PK callbacks */ +#define CKM_SHA1_RSA_PKCS_PSS 0x0000000EUL +#define CKM_SHA256_RSA_PKCS_PSS 0x00000043UL +#define CKM_SHA384_RSA_PKCS_PSS 0x00000044UL +#define CKM_SHA512_RSA_PKCS_PSS 0x00000045UL +#define CKM_SHA224_RSA_PKCS_PSS 0x00000047UL + +#define CKG_MGF1_SHA1 0x00000001UL +#define CKG_MGF1_SHA224 0x00000005UL +#define CKG_MGF1_SHA256 0x00000002UL +#define CKG_MGF1_SHA384 0x00000003UL +#define CKG_MGF1_SHA512 0x00000004UL + + #define CKR_OK 0x00000000UL #define CKR_MECHANISM_INVALID 0x00000070UL #define CKR_SIGNATURE_INVALID 0x000000C0UL #define CKD_NULL 0x00000001UL - +#define CKZ_DATA_SPECIFIED 0x00000001UL typedef unsigned char CK_BYTE; typedef CK_BYTE CK_CHAR; @@ -339,6 +361,26 @@ typedef struct CK_GCM_PARAMS { } CK_GCM_PARAMS; typedef CK_GCM_PARAMS* CK_GCM_PARAMS_PTR; +typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE; + +typedef struct CK_RSA_PKCS_PSS_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_ULONG sLen; +} CK_RSA_PKCS_PSS_PARAMS; +typedef CK_RSA_PKCS_PSS_PARAMS *CK_RSA_PKCS_PSS_PARAMS_PTR; + +typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE; + +typedef struct CK_RSA_PKCS_OAEP_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_RSA_PKCS_OAEP_SOURCE_TYPE source; + CK_VOID_PTR pSourceData; + CK_ULONG ulSourceDataLen; +} CK_RSA_PKCS_OAEP_PARAMS; +typedef CK_RSA_PKCS_OAEP_PARAMS *CK_RSA_PKCS_OAEP_PARAMS_PTR; + /* Function list types. */ typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST; typedef CK_FUNCTION_LIST* CK_FUNCTION_LIST_PTR; @@ -538,4 +580,3 @@ struct CK_FUNCTION_LIST { #endif #endif /* _PKCS11_H_ */ - diff --git a/src/wolfssl/wolfcrypt/pkcs12.h b/src/wolfssl/wolfcrypt/pkcs12.h index dc06c9d..d7bf967 100644 --- a/src/wolfssl/wolfcrypt/pkcs12.h +++ b/src/wolfssl/wolfcrypt/pkcs12.h @@ -1,6 +1,6 @@ /* pkcs12.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pkcs7.h b/src/wolfssl/wolfcrypt/pkcs7.h index 2af117d..80c687b 100644 --- a/src/wolfssl/wolfcrypt/pkcs7.h +++ b/src/wolfssl/wolfcrypt/pkcs7.h @@ -1,6 +1,6 @@ /* pkcs7.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -257,8 +257,8 @@ struct PKCS7 { CallbackStreamOut streamOutCb; void* streamCtx; /* passed to getcontentCb and streamOutCb */ #endif - byte encodeStream:1; /* use BER when encoding */ - byte noCerts:1; /* if certificates should be added into bundle + WC_BITFIELD encodeStream:1; /* use BER when encoding */ + WC_BITFIELD noCerts:1; /* if certificates should be added into bundle during creation */ byte* cert[MAX_PKCS7_CERTS]; /* array of certs parsed from bundle */ byte* verifyCert; /* cert from array used for verify */ @@ -296,9 +296,9 @@ struct PKCS7 { word32 certSz[MAX_PKCS7_CERTS]; /* flags - up to 16-bits */ - word16 isDynamic:1; - word16 noDegenerate:1; /* allow degenerate case in verify function */ - word16 detached:1; /* generate detached SignedData signature bundles */ + WC_BITFIELD isDynamic:1; + WC_BITFIELD noDegenerate:1; /* allow degenerate case in verify function */ + WC_BITFIELD detached:1; /* generate detached SignedData signature bundles */ byte contentType[MAX_OID_SZ]; /* custom contentType byte array */ word32 contentTypeSz; /* size of contentType, bytes */ @@ -345,6 +345,10 @@ struct PKCS7 { word32 plainDigestSz; word32 pkcs7DigestSz; +#ifdef WC_ASN_UNKNOWN_EXT_CB + wc_UnknownExtCallback unknownExtCallback; +#endif + #if defined(HAVE_PKCS7_RSA_RAW_SIGN_CALLBACK) && !defined(NO_RSA) CallbackRsaSignRawDigest rsaSignRawDigestCb; #endif @@ -352,12 +356,25 @@ struct PKCS7 { /* used by DecodeEnvelopedData with multiple encrypted contents */ byte* cachedEncryptedContent; word32 cachedEncryptedContentSz; - word16 contentCRLF:1; /* have content line endings been converted to CRLF */ - word16 contentIsPkcs7Type:1; /* eContent follows PKCS#7 RFC not CMS */ + WC_BITFIELD contentCRLF:1; /* have content line endings been converted to CRLF */ + WC_BITFIELD contentIsPkcs7Type:1; /* eContent follows PKCS#7 RFC not CMS */ + WC_BITFIELD hashParamsAbsent:1; + + /* RFC 5280 section-4.2.1.2 lists a possible method for creating the SKID as + * a SHA1 hash of the public key, but leaves it open to other methods as + * long as it is a unique ID. This allows for setting a custom SKID when + * creating PKCS7 bundles*/ + byte* customSKID; + word16 customSKIDSz; + /* !! NEW DATA MEMBERS MUST BE ADDED AT END !! */ }; WOLFSSL_API PKCS7* wc_PKCS7_New(void* heap, int devId); +#ifdef WC_ASN_UNKNOWN_EXT_CB + WOLFSSL_API void wc_PKCS7_SetUnknownExtCallback(PKCS7* pkcs7, + wc_UnknownExtCallback cb); +#endif WOLFSSL_API int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId); WOLFSSL_API int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* der, word32 derSz); WOLFSSL_API int wc_PKCS7_AddCertificate(PKCS7* pkcs7, byte* der, word32 derSz); @@ -378,6 +395,8 @@ WOLFSSL_API int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz); /* CMS/PKCS#7 SignedData */ +WOLFSSL_API int wc_PKCS7_SetCustomSKID(PKCS7* pkcs7, const byte* in, + word16 inSz); WOLFSSL_API int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag); WOLFSSL_API int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7); WOLFSSL_API int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag); diff --git a/src/wolfssl/wolfcrypt/poly1305.h b/src/wolfssl/wolfcrypt/poly1305.h index cc31254..d4db487 100644 --- a/src/wolfssl/wolfcrypt/poly1305.h +++ b/src/wolfssl/wolfcrypt/poly1305.h @@ -1,6 +1,6 @@ /* poly1305.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -57,7 +57,7 @@ #if defined(USE_INTEL_POLY1305_SPEEDUP) #elif (defined(WC_HAS_SIZEOF_INT128_64BIT) || defined(WC_HAS_MSVC_64BIT) || \ - defined(WC_HAS_GCC_4_4_64BIT)) + defined(WC_HAS_GCC_4_4_64BIT)) && !defined(WOLFSSL_W64_WRAPPER_TEST) #define POLY130564 #else #define POLY130532 @@ -88,14 +88,31 @@ typedef struct Poly1305 { size_t leftover; unsigned char finished; unsigned char started; -#else -#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) +#elif defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ALIGN128 word64 r64[2]; ALIGN128 word32 r[5]; ALIGN128 word32 r_2[5]; /* r^2 */ ALIGN128 word32 r_4[5]; /* r^4 */ ALIGN128 word32 h[5]; word32 pad[4]; word64 leftover; + unsigned char buffer[POLY1305_BLOCK_SIZE]; + unsigned char finished; +#elif defined(WOLFSSL_ARMASM) + word32 r[4]; + word32 h[5]; + word32 pad[4]; + word32 leftover; + unsigned char buffer[POLY1305_BLOCK_SIZE]; +#elif defined(WOLFSSL_RISCV_ASM) + word64 r[2]; +#ifdef WOLFSSL_RISCV_VECTOR + word64 r2[6]; +#endif + word64 h[3]; + word64 pad[2]; + size_t leftover; + unsigned char buffer[POLY1305_BLOCK_SIZE]; #else #if defined(POLY130564) word64 r[3]; @@ -107,10 +124,9 @@ typedef struct Poly1305 { word32 pad[4]; #endif size_t leftover; -#endif /* WOLFSSL_ARMASM */ unsigned char buffer[POLY1305_BLOCK_SIZE]; unsigned char finished; -#endif +#endif /* WOLFSSL_ARMASM */ } Poly1305; /* does init */ @@ -131,10 +147,47 @@ WOLFSSL_API int wc_Poly1305_EncodeSizes64(Poly1305* ctx, word64 aadSz, WOLFSSL_API int wc_Poly1305_MAC(Poly1305* ctx, const byte* additional, word32 addSz, const byte* input, word32 sz, byte* tag, word32 tagSz); -#if defined(__aarch64__ ) && defined(WOLFSSL_ARMASM) -void poly1305_blocks(Poly1305* ctx, const unsigned char *m, - size_t bytes); -void poly1305_block(Poly1305* ctx, const unsigned char *m); +#if defined(WOLFSSL_ARMASM) +#if defined(__aarch64__ ) +#define poly1305_blocks poly1305_blocks_aarch64 +#define poly1305_block poly1305_block_aarch64 + +void poly1305_blocks_aarch64(Poly1305* ctx, const unsigned char *m, + size_t bytes); +void poly1305_block_aarch64(Poly1305* ctx, const unsigned char *m); +#else +#if defined(WOLFSSL_ARMASM_THUMB2) +#define poly1305_blocks poly1305_blocks_thumb2 +#define poly1305_block poly1305_block_thumb2 + +void poly1305_blocks_thumb2(Poly1305* ctx, const unsigned char *m, + size_t bytes); +void poly1305_block_thumb2(Poly1305* ctx, const unsigned char *m); + +void poly1305_blocks_thumb2_16(Poly1305* ctx, const unsigned char* m, + word32 len, int notLast); +#else +#define poly1305_blocks poly1305_blocks_arm32 +#define poly1305_block poly1305_block_arm32 + +void poly1305_blocks_arm32(Poly1305* ctx, const unsigned char *m, size_t bytes); +void poly1305_block_arm32(Poly1305* ctx, const unsigned char *m); + +void poly1305_blocks_arm32_16(Poly1305* ctx, const unsigned char* m, word32 len, + int notLast); +#endif +void poly1305_set_key(Poly1305* ctx, const byte* key); +void poly1305_final(Poly1305* ctx, byte* mac); +#endif +#endif /* WOLFSSL_ARMASM */ + +#if defined(WOLFSSL_RISCV_ASM) +#define poly1305_blocks poly1305_blocks_riscv64 +#define poly1305_block poly1305_block_riscv64 + +void poly1305_blocks_riscv64(Poly1305* ctx, const unsigned char *m, + size_t bytes); +void poly1305_block_riscv64(Poly1305* ctx, const unsigned char *m); #endif #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h index 55ff661..85b4ed1 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h @@ -116,7 +116,7 @@ ** the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" */ #if defined(CONFIG_ESP_WIFI_SSID) - /* tyically from ESP32 with ESP-IDF v4 ot v5 */ + /* tyically from ESP32 with ESP-IDF v4 or v5 */ #define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID #elif defined(CONFIG_EXAMPLE_WIFI_SSID) /* typically from ESP8266 rtos-sdk/v3.4 */ @@ -148,9 +148,13 @@ WOLFSSL_LOCAL esp_err_t sdk_var_whereis(const char* v_name, void* v); WOLFSSL_LOCAL intptr_t esp_sdk_stack_pointer(void); +#if defined(USE_WOLFSSL_ESP_SDK_TIME) + /****************************************************************************** * Time helpers ******************************************************************************/ +WOLFSSL_LOCAL esp_err_t esp_sdk_time_mem_init(void); + WOLFSSL_LOCAL esp_err_t esp_sdk_time_lib_init(void); /* a function to show the current data and time */ @@ -168,8 +172,9 @@ WOLFSSL_LOCAL esp_err_t set_time(void); /* wait NTP_RETRY_COUNT seconds before giving up on NTP time */ WOLFSSL_LOCAL esp_err_t set_time_wait_for_ntp(void); +#endif -#ifndef NO_ESP_SDK_WIFI +#if defined(USE_WOLFSSL_ESP_SDK_WIFI) /****************************************************************************** * WiFi helpers @@ -201,8 +206,7 @@ WOLFSSL_LOCAL esp_err_t esp_sdk_wifi_init_sta(void); WOLFSSL_LOCAL esp_err_t esp_sdk_wifi_show_ip(void); -#endif /* !NO_ESP_SDK_WIFI */ - +#endif /* USE_WOLFSSL_ESP_SDK_WIFI */ /****************************************************************************** * Debug helpers diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index 9a33bf5..99d2ca2 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -216,6 +216,10 @@ enum { ** Turns on diagnostic messages for SHA mutex. Note that given verbosity, ** there may be TLS timing issues encountered. Use with caution. ** +** DEBUG_WOLFSSL_ESP32_UNFINISHED_HW +** This may be interesting in that HW may have been unnessearily locked +** for hash that was never completed. (typically encountered at `free1` time) +** ** LOG_LOCAL_LEVEL ** Debugging. Default value is ESP_LOG_DEBUG ** @@ -229,6 +233,14 @@ enum { ** WOLFSSL_DEBUG_ESP_RSA_MULM_BITS ** Shows a warning when mulm falls back for minimum number of bits. ** +** WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS +** Shows a marning when multiplication math bits have exceeded hardware +** capabilities and will fall back to slower software. +** +** WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS +** Shows a marning when modular math bits have exceeded hardware capabilities +** and will fall back to slower software. +** ** NO_HW_MATH_TEST ** Even if HW is enabled, do not run HW math tests. See HW_MATH_ENABLED. ** @@ -563,6 +575,95 @@ enum { defined(WOLFSSL_ESP32_CRYPT_DEBUG) #endif +/* +****************************************************************************** +** wolfssl component Kconfig file settings +****************************************************************************** + * Naming convention: + * + * CONFIG_ + * This prefix indicates the setting came from the sdkconfig / Kconfig. + * + * May or may not be related to wolfSSL. + * + * The name after this prefix must exactly match that in the Kconfig file. + * + * WOLFSSL_ + * Typical of many, but not all wolfSSL macro names. + * + * Applies to all wolfSSL products such as wolfSSH, wolfMQTT, etc. + * + * May or may not have a corresponding sdkconfig / Kconfig control. + * + * ESP_WOLFSSL_ + * These are NOT valid wolfSSL macro names. These are names only used in + * the ESP-IDF Kconfig files. When parsed, they will have a "CONFIG_" + * suffix added. See next section. + * + * CONFIG_ESP_WOLFSSL_ + * This is a wolfSSL-specific macro that has been defined in the ESP-IDF + * via the sdkconfig / menuconfig. Any text after this prefix should + * exactly match an existing wolfSSL macro name. + * + * Applies to all wolfSSL products such as wolfSSH, wolfMQTT, etc. + * + * These macros may also be specific to only the project or environment, + * and possibly not used anywhere else in the wolfSSL libraries. + */ + + + +/* Pre-set some hardware acceleration from Kconfig / menuconfig settings */ +#ifdef CONFIG_ESP_WOLFSSL_NO_ESP32_CRYPT + #define NO_ESP32_CRYPT + #define NO_WOLFSSL_ESP32_CRYPT_AES + #define NO_WOLFSSL_ESP32_CRYPT_HASH + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_AES + #define NO_WOLFSSL_ESP32_CRYPT_AES +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_HASH + #define NO_WOLFSSL_ESP32_CRYPT_HASH +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_RSA_PRI + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_RSA_PRI_MP_MUL + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MP_MUL +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_RSA_PRI_MULMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_MULMOD +#endif +#ifdef CONFIG_ESP_WOLFSSL_NO_HW_RSA_PRI_EXPTMOD + #define NO_WOLFSSL_ESP32_CRYPT_RSA_PRI_EXPTMOD +#endif + +/* wolfCrypt test settings */ +#ifdef CONFIG_ESP_WOLFSSL_ENABLE_TEST + #ifdef CONFIG_WOLFSSL_HAVE_WOLFCRYPT_TEST_OPTIONS + #define HAVE_WOLFCRYPT_TEST_OPTIONS + #endif +#endif + +/* debug options */ +#if defined(CONFIG_ESP_WOLFSSL_DEBUG_WOLFSSL) + /* wolfSSH debugging enabled via Kconfig / menuconfig */ + #define DEBUG_WOLFSSL +#endif + +/* +****************************************************************************** +** END wolfssl component Kconfig file settings +****************************************************************************** +*/ + #ifdef __cplusplus extern "C" { @@ -623,7 +724,8 @@ extern "C" #elif defined(CONFIG_IDF_TARGET_ESP8266) /* no hardware includes for ESP8266*/ #else - #include "rom/aes.h" + /* TODO: Confirm for older versions: */ + /* #include "rom/aes.h" */ #endif typedef enum tagES32_AES_PROCESS /* TODO what's this ? */ @@ -759,7 +861,7 @@ extern "C" #if defined(WOLFSSL_STACK_CHECK) word32 last_word; #endif - } WC_ESP32SHA; + } WC_ESP32SHA __attribute__((aligned(4))); WOLFSSL_LOCAL int esp_sha_need_byte_reversal(WC_ESP32SHA* ctx); WOLFSSL_LOCAL int esp_sha_init(WC_ESP32SHA* ctx, @@ -907,9 +1009,9 @@ WOLFSSL_LOCAL int esp_sha_stack_check(WC_ESP32SHA* sha); /* * Errata Mitigation. See - * https://www.espressif.com/sites/default/files/documentation/esp32_errata_en.pdf - * https://www.espressif.com/sites/default/files/documentation/esp32-c3_errata_en.pdf - * https://www.espressif.com/sites/default/files/documentation/esp32-s3_errata_en.pdf + * esp32_errata_en.pdf + * esp32-c3_errata_en.pdf + * esp32-s3_errata_en.pdf */ #define ESP_MP_HW_LOCK_MAX_DELAY ( TickType_t ) 0xffUL @@ -986,6 +1088,29 @@ WOLFSSL_LOCAL int esp_sha_stack_check(WC_ESP32SHA* sha); } #endif +/****************************************************************************** +** Sanity Checks +******************************************************************************/ +#if defined(CONFIG_ESP_MAIN_TASK_STACK_SIZE) + #if defined(WOLFCRYPT_HAVE_SRP) + #if defined(FP_MAX_BITS) + #if FP_MAX_BITS < (8192 * 2) + #define ESP_SRP_MINIMUM_STACK_8K (24 * 1024) + #else + #define ESP_SRP_MINIMUM_STACK_8K (28 * 1024) + #endif + #else + #error "Please define FP_MAX_BITS when using WOLFCRYPT_HAVE_SRP." + #endif + + #if (CONFIG_ESP_MAIN_TASK_STACK_SIZE < ESP_SRP_MINIMUM_STACK) + #warning "WOLFCRYPT_HAVE_SRP enabled with small stack size" + #endif + #endif +#else + #warning "CONFIG_ESP_MAIN_TASK_STACK_SIZE not defined!" +#endif + #endif /* WOLFSSL_ESPIDF (entire contents excluded when not Espressif ESP-IDF) */ #endif /* __ESP32_CRYPT_H__ */ diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h new file mode 100644 index 0000000..afeb352 --- /dev/null +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h @@ -0,0 +1,242 @@ +/* esp_crt_bundle.h + * + * Copyright (C) 2006-2024 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifndef __ESP_CRT_BUNDLE_wolfssl_LIB_H__ + +#define __ESP_CRT_BUNDLE_wolfssl_LIB_H__ + +/* This file is typically NOT directly used by applications utilizing the + * wolfSSL libraries. It is used when the wolfssl library component is + * configured to be utilized by the Espressif ESP-IDF, specifically the + * esp-tls layer. + * + * See: esp-idf api-reference for esp_tls. + * https://github.com/espressif/esp-idf/blob/master/components/esp-tls/esp_tls.h + * + ******************************************************************************* + ** Optional Settings: + ******************************************************************************* + * WOLFSSL_DEBUG_CERT_BUNDLE_NAME + * Optionally show certificate bundle debugging info. + * + * WOLFSSL_DEBUG_CERT_BUNDLE_NAME + * Optionally show certificate bundle name debugging info. + * + * WOLFSSL_EXAMPLE_VERBOSITY + * Optionally print example application information that may be interesting. + * + * IS_WOLFSSL_CERT_BUNDLE_FORMAT + * This should be left on as no other bundle format is supported at this time. + * + * CB_INLINE + * Normally on, this uses the compiler `inline` decorator for bundle functions + * to be optimized, since they are called during a TLS connection. + * + * See Kconfig file (or use idy.py menuconfig) for other bundle settings. + * + ******************************************************************************* + ** Other Settings: + ******************************************************************************* + * WOLFSSL_CMAKE_REQUIRED_ESP_TLS + * This is defined in the wolfssl component cmake file when the esp-tls + * component is required. This is typically when Certificate Bundles are + * enabled, and the esp_tls_free_global_ca_store() in the esp-tls needs + * to be called from the wolfSSL wolfSSL_bundle_cleanup(). + */ + +/* wolfSSL */ +/* Always include wolfcrypt/settings.h before any other wolfSSL file. */ +/* Be sure to define WOLFSSL_USER_SETTINGS, typically in CMakeLists.txt */ +/* Reminder: settings.h pulls in user_settings.h */ +/* Do not explicitly include user_settings.h here. */ +#include + +#if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ + +#ifndef WOLFSSL_USER_SETTINGS + #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targts" +#endif + +#if defined(CONFIG_ESP_TLS_USING_WOLFSSL) || \ + defined(CONFIG_WOLFSSL_CERTIFICATE_BUNDLE) + + +#ifdef __cplusplus +extern "C" { +#endif + +#define WOLFSSL_X509_VERIFY_CALLBACK (void *, WOLFSSL_X509 *, int, uint32_t *) +#include + +typedef struct wolfssl_ssl_config wolfssl_ssl_config; + +struct wolfssl_ssl_config +{ + WOLFSSL_X509* ca_chain; + WOLFSSL_X509_CRL* ca_crl; + void *priv_ctx; + void *priv_ssl; +}; + +/** + * @brief Attach and enable use of a bundle for certificate verification + * + * Attach and enable use of a bundle for certificate verification through a + * verification callback.If no specific bundle has been set through + * esp_crt_bundle_set() it will default to the bundle defined in menuconfig + * and embedded in the binary. + * + * Note this must be visible for both the regular bundles, as well as the + *"none" option. + * + * Other code gated out, below, when the "none" option is selected. + * + * @param[in] conf The config struct for the SSL connection. + * + * @return + * - ESP_OK if adding certificates was successful. + * - Other if an error occurred or an action must be taken by the + * calling process. + */ +esp_err_t esp_crt_bundle_attach(void *conf); + + +#if defined(CONFIG_WOLFSSL_CERTIFICATE_BUNDLE) && \ + defined(CONFIG_WOLFSSL_CERTIFICATE_BUNDLE_DEFAULT_NONE) && \ + (CONFIG_WOLFSSL_CERTIFICATE_BUNDLE_DEFAULT_NONE == 1) + +/* Certificate bundles are enabled, but the "none" option selected */ + +#else +/** + * @brief Return ESP_OK for valid bundle, otherwise ESP_FAIL. + * + * Specific to wolfSSL. Not used by ESP-IDF esp-tls layer. + */ +esp_err_t esp_crt_bundle_is_valid(void); + +/** + * @brief Return 1 if Cert Bundle loaded, otherwise 0. + * + * Specific to wolfSSL. Not used by ESP-IDF esp-tls layer. + */ +int wolfssl_cert_bundle_loaded(void); + +/** + * @brief Return 1 is a cert from the bundle was needed + * at connection time, otherwise 0. + * + * Specific to wolfSSL. Not used by ESP-IDF esp-tls layer. + */ +int wolfssl_need_bundle_cert(void); + +/** + * @brief Disable and dealloc the certification bundle + * + * Used by ESP-IDF esp-tls layer. + * + * Removes the certificate verification callback and deallocates used resources + * + * @param[in] conf The config struct for the SSL connection. + */ +void esp_crt_bundle_detach(wolfssl_ssl_config *conf); + +/** + * @brief Set the default certificate bundle used for verification + * + * Used by ESP-IDF esp-tls layer. + * + * Overrides the default certificate bundle only in case of successful + * initialization. In most use cases the bundle should be set through + * menuconfig. The bundle needs to be sorted by subject name since binary + * search is used to find certificates. + * + * @param[in] x509_bundle A pointer to the certificate bundle. + * + * @param[in] bundle_size Size of the certificate bundle in bytes. + * + * @return + * - ESP_OK if adding certificates was successful. + * - Other if an error occurred or an action must be taken + * by the calling process. + */ +esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size); + + +/** + * @brief Set the issuer and subject values given the current cert. + * + * Used internally by ESP-IDF esp-tls layer. Also helpful for debugging + * and general visibility to certificate attributes. + * + * The CERT_TAG can be used at the esp-tls or application layer to indicate + * the usage of the respective cert (e.g. the string "peer"). + * + * Turn on WOLFSSL_DEBUG_CERT_BUNDLE to also see ASN1 before/after values. + * + * @return + * - WOLFSSL_SUCCESS (1) + * - WOLFSSL_FAILURE (0) if unable to get issues and/or subject. + */ +int wolfSSL_X509_get_cert_items(char* CERT_TAG, + WOLFSSL_X509* cert, + WOLFSSL_X509_NAME** issuer, + WOLFSSL_X509_NAME** subject); + +esp_err_t wolfSSL_bundle_cleanup(void); + +WOLFSSL_LOCAL void wolfssl_ssl_conf_verify(wolfssl_ssl_config *conf, + int (*f_vrfy) WOLFSSL_X509_VERIFY_CALLBACK, + void *p_vrfy); + +WOLFSSL_LOCAL void wolfssl_ssl_conf_authmode(wolfssl_ssl_config *conf, + int authmode); + +WOLFSSL_LOCAL void wolfssl_ssl_conf_ca_chain(wolfssl_ssl_config *conf, + WOLFSSL_X509 *ca_chain, + WOLFSSL_X509_CRL *ca_crl); + +WOLFSSL_LOCAL void wolfssl_x509_crt_init(WOLFSSL_X509 *crt); + +WOLFSSL_LOCAL int esp_crt_verify_callback(void *buf, WOLFSSL_X509 *crt, + int depth, uint32_t *flags); + +#ifdef __cplusplus +} +#endif + +/* Detect if wolfSSL is enabled, but so are mbedTLS bundles */ +#if defined(CONFIG_MBEDTLS_CERTIFICATE_BUNDLE) && \ + CONFIG_MBEDTLS_CERTIFICATE_BUNDLE + #error "wolfSSL cannot use mbedTLS certificate bundles. Please disable them" +#endif + +#endif /* CONFIG_WOLFSSL_CERTIFICATE_BUNDLE */ + +#endif /* CONFIG_ESP_TLS_USING_WOLFSSL */ + +#endif /* WOLFSSL_ESPIDF */ + +#endif /* __ESP_CRT_BUNDLE_wolfssl_LIB_H__ */ diff --git a/src/wolfssl/wolfcrypt/port/atmel/atmel.h b/src/wolfssl/wolfcrypt/port/atmel/atmel.h index 4f92236..c2f9940 100644 --- a/src/wolfssl/wolfcrypt/port/atmel/atmel.h +++ b/src/wolfssl/wolfcrypt/port/atmel/atmel.h @@ -1,6 +1,6 @@ /* atmel.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pwdbased.h b/src/wolfssl/wolfcrypt/pwdbased.h index bcf0939..9535b0a 100644 --- a/src/wolfssl/wolfcrypt/pwdbased.h +++ b/src/wolfssl/wolfcrypt/pwdbased.h @@ -1,6 +1,6 @@ /* pwdbased.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/random.h b/src/wolfssl/wolfcrypt/random.h index 9dd6163..cc4c797 100644 --- a/src/wolfssl/wolfcrypt/random.h +++ b/src/wolfssl/wolfcrypt/random.h @@ -1,6 +1,6 @@ /* random.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/rc2.h b/src/wolfssl/wolfcrypt/rc2.h index 2d1950e..22b2ad1 100644 --- a/src/wolfssl/wolfcrypt/rc2.h +++ b/src/wolfssl/wolfcrypt/rc2.h @@ -1,6 +1,6 @@ /* rc2.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ripemd.h b/src/wolfssl/wolfcrypt/ripemd.h index 3e1d5b4..d1a0e6f 100644 --- a/src/wolfssl/wolfcrypt/ripemd.h +++ b/src/wolfssl/wolfcrypt/ripemd.h @@ -1,6 +1,6 @@ /* ripemd.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/rsa.h b/src/wolfssl/wolfcrypt/rsa.h index f73974d..3f39d5b 100644 --- a/src/wolfssl/wolfcrypt/rsa.h +++ b/src/wolfssl/wolfcrypt/rsa.h @@ -1,6 +1,6 @@ /* rsa.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -103,7 +103,11 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. #endif #ifndef RSA_MIN_SIZE -#define RSA_MIN_SIZE 512 + #if defined(HAVE_WOLFENGINE) || defined(HAVE_WOLFPROVIDER) + #define RSA_MIN_SIZE 1024 + #else + #define RSA_MIN_SIZE 2048 + #endif #endif #ifndef RSA_MAX_SIZE @@ -274,9 +278,28 @@ struct RsaKey { #endif /* HAVE_FIPS */ +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) +struct RsaPadding { + byte pad_value; + int pad_type; + enum wc_HashType hash; + int mgf; + byte* label; + word32 labelSz; + int saltLen; + int unpadded; +}; +typedef struct RsaPadding RsaPadding; +#endif + WOLFSSL_API int wc_InitRsaKey(RsaKey* key, void* heap); WOLFSSL_API int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId); WOLFSSL_API int wc_FreeRsaKey(RsaKey* key); +#ifndef WC_NO_CONSTRUCTORS +WOLFSSL_API RsaKey* wc_NewRsaKey(void* heap, int devId, int *result_code); +WOLFSSL_API int wc_DeleteRsaKey(RsaKey* key, RsaKey** key_p); +#endif + #ifdef WOLF_PRIVATE_KEY_ID WOLFSSL_API int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, int devId); diff --git a/src/wolfssl/wolfcrypt/sakke.h b/src/wolfssl/wolfcrypt/sakke.h index 173c33b..0f7a75c 100644 --- a/src/wolfssl/wolfcrypt/sakke.h +++ b/src/wolfssl/wolfcrypt/sakke.h @@ -1,6 +1,6 @@ /* sakke.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -64,15 +64,15 @@ typedef struct SakkeKeyParams { ecc_point* base; /** Bit indicate prime is set as an MP integer in SAKKE key. */ - byte havePrime:1; + WC_BITFIELD havePrime:1; /** Bit indicates q (order) is set as an MP integer in SAKKE key. */ - byte haveQ:1; + WC_BITFIELD haveQ:1; /** Bit indicates g (pairing base) is set as an MP integer in SAKKE key. */ - byte haveG:1; + WC_BITFIELD haveG:1; /** Bit indicates a is set as an MP integer in SAKKE key. */ - byte haveA:1; + WC_BITFIELD haveA:1; /** Bit indicates base point is set as an ECC point in SAKKE key. */ - byte haveBase:1; + WC_BITFIELD haveBase:1; } SakkeKeyParams; /** Temporary values to use in SAKKE calculations. */ @@ -116,7 +116,7 @@ typedef struct SakkeKeyRsk { /** Length of table */ word32 tableLen; /** Indicates whether an RSK value has been set. */ - byte set:1; + WC_BITFIELD set:1; } SakkeKeyRsk; #endif @@ -153,9 +153,9 @@ typedef struct SakkeKey { void* heap; /** Bit indicates Z, public key, is in montgomery form. */ - byte zMont:1; + WC_BITFIELD zMont:1; /** Bit indicate MP integers have been initialized. */ - byte mpInit:1; + WC_BITFIELD mpInit:1; } SakkeKey; #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/selftest.h b/src/wolfssl/wolfcrypt/selftest.h index a0c7c0e..198013b 100644 --- a/src/wolfssl/wolfcrypt/selftest.h +++ b/src/wolfssl/wolfcrypt/selftest.h @@ -1,6 +1,6 @@ /* selftest.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index a4302c7..e02870c 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -20,24 +20,17 @@ */ /* - * ************************************************************************ + * Note, this file should not be edited to activate/deactivate features. * - * ******************************** NOTICE ******************************** - * - * ************************************************************************ - * - * This method of uncommenting a line in settings.h is outdated. - * - * Please use user_settings.h / WOLFSSL_USER_SETTINGS + * Instead, add/edit user_settings.h, and compile with -DWOLFSSL_USER_SETTINGS * * or * - * ./configure CFLAGS="-DFLAG" + * ./configure CFLAGS="-DFEATURE_FLAG_TO_DEFINE -UFEATURE_FLAG_TO_CLEAR [...]" * * For more information see: * * https://www.wolfssl.com/how-do-i-manage-the-build-configuration-of-wolfssl/ - * */ @@ -55,7 +48,7 @@ /* This flag allows wolfSSL to include options.h instead of having client * projects do it themselves. This should *NEVER* be defined when building * wolfSSL as it can cause hard to debug problems. */ -#ifdef EXTERNAL_OPTS_OPENVPN +#if defined(EXTERNAL_OPTS_OPENVPN) || defined(WOLFSSL_USE_OPTIONS_H) #include #endif @@ -212,6 +205,9 @@ /* Uncomment next line if building for Nucleus 1.2 */ /* #define WOLFSSL_NUCLEUS_1_2 */ +/* Uncomment next line if building for Nucleus Plus 2.3 */ +/* #define NUCLEUS_PLUS_2_3 */ + /* Uncomment next line if building for using Apache mynewt */ /* #define WOLFSSL_APACHE_MYNEWT */ @@ -259,6 +255,9 @@ /* Uncomment next line if building for Dolphin Emulator */ /* #define DOLPHIN_EMULATOR */ +/* Uncomment next line if building for WOLFSSL_NDS */ +/* #define WOLFSSL_NDS */ + /* Uncomment next line if using MAXQ1065 */ /* #define WOLFSSL_MAXQ1065 */ @@ -269,6 +268,7 @@ #ifdef PLATFORMIO #ifdef ESP_PLATFORM /* Turn on the wolfSSL ESPIDF flag for the PlatformIO ESP-IDF detect */ + #undef WOLFSSL_ESPIDF #define WOLFSSL_ESPIDF #endif /* ESP_PLATFORM */ @@ -319,11 +319,27 @@ #elif defined(USE_HAL_DRIVER) && !defined(HAVE_CONFIG_H) /* STM Configuration File (generated by CubeMX) */ #include "wolfSSL.I-CUBE-wolfSSL_conf.h" +#elif defined(NUCLEUS_PLUS_2_3) + /* NOTE: cyassl_nucleus_defs.h is akin to user_settings.h */ + #include "nucleus.h" + #include "os/networking/ssl/lite/cyassl_nucleus_defs.h" #endif #include /*------------------------------------------------------------*/ +#if defined(WOLFSSL_FIPS_READY) || defined(WOLFSSL_FIPS_DEV) + #undef HAVE_FIPS_VERSION_MAJOR + #define HAVE_FIPS_VERSION_MAJOR 7 /* always one more than major version */ + /* of most recent FIPS certificate */ + #undef HAVE_FIPS_VERSION + #define HAVE_FIPS_VERSION HAVE_FIPS_VERSION_MAJOR + #undef HAVE_FIPS_VERSION_MINOR + #define HAVE_FIPS_VERSION_MINOR 0 /* always 0 */ + #undef HAVE_FIPS_VERSION_PATCH + #define HAVE_FIPS_VERSION_PATCH 0 /* always 0 */ +#endif + #define WOLFSSL_MAKE_FIPS_VERSION3(major, minor, patch) \ (((major) * 65536) + ((minor) * 256) + (patch)) #define WOLFSSL_MAKE_FIPS_VERSION(major, minor) \ @@ -408,36 +424,31 @@ * --------------------------------------------------------------------------- */ #ifdef WOLFSSL_DUAL_ALG_CERTS + #ifdef NO_RSA + #error "Need RSA or else dual alg cert example will not work." + #endif -#ifndef WOLFSSL_ASN_TEMPLATE - #error "Dual alg cert support requires the ASN.1 template feature." -#endif - -#ifdef NO_RSA - #error "Need RSA or else dual alg cert example will not work." -#endif - -#ifndef HAVE_ECC - #error "Need ECDSA or else dual alg cert example will not work." -#endif + #ifndef HAVE_ECC + #error "Need ECDSA or else dual alg cert example will not work." + #endif -#undef WOLFSSL_CERT_GEN -#define WOLFSSL_CERT_GEN + #undef WOLFSSL_CERT_GEN + #define WOLFSSL_CERT_GEN -#undef WOLFSSL_CUSTOM_OID -#define WOLFSSL_CUSTOM_OID + #undef WOLFSSL_CUSTOM_OID + #define WOLFSSL_CUSTOM_OID -#undef HAVE_OID_ENCODING -#define HAVE_OID_ENCODING + #undef HAVE_OID_ENCODING + #define HAVE_OID_ENCODING -#undef WOLFSSL_CERT_EXT -#define WOLFSSL_CERT_EXT + #undef WOLFSSL_CERT_EXT + #define WOLFSSL_CERT_EXT -#undef OPENSSL_EXTRA -#define OPENSSL_EXTRA + #undef OPENSSL_EXTRA + #define OPENSSL_EXTRA -#undef HAVE_OID_DECODING -#define HAVE_OID_DECODING + #undef HAVE_OID_DECODING + #define HAVE_OID_DECODING #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -467,6 +478,16 @@ #include #endif + +#ifdef WOLFSSL_NDS + #include + #define SIZEOF_LONG_LONG 8 + #define socklen_t int + #define IPPROTO_UDP 17 + #define IPPROTO_TCP 6 + #define NO_WRITEV +#endif + #if defined(ARDUINO) #if defined(ESP32) #ifndef NO_ARDUINO_DEFAULT @@ -496,6 +517,316 @@ #if defined(WOLFSSL_ESPIDF) #define SIZEOF_LONG_LONG 8 + + #ifndef WOLFSSL_MAX_ERROR_SZ + /* Espressif paths can be quite long. Ensure error prints full path. */ + #define WOLFSSL_MAX_ERROR_SZ 200 + #endif + + /* Parse any Kconfig / menuconfig items into wolfSSL macro equivalents. + * Macros may or may not be defined. If defined, they may have a value of + * + * 0 - not enabled (also the equivalent of not defined) + * 1 - enabled + * + * The naming convention is generally an exact match of wolfSSL macros + * in the Kconfig file. At cmake time, the Kconfig is processed and an + * sdkconfig.h file is created by the ESP-IDF. Any configured options are + * named CONFIG_[Kconfig name] and thus CONFIG_[macro name]. Those that + * are expected to be ESP-IDF specific and may be ambiguous can named + * with an ESP prefix, for example CONFIG_[ESP_(Kconfig name)] + * + * Note there are some inconsistent macro names that may have been + * used in the esp-wolfssl or other places in the ESP-IDF. They should + * be always be included for backward compatibility. + * + * See also: Espressif api-reference kconfig docs. + * + * These settings should be checked and assigned wolfssl equivalents before + * any others. + * + * Only the actual config settings should be defined here. Any others that + * may be application specific should be conditionally defined in the + * respective user_settings.h file. + * + * See the template example for reference: + * https://github.com/wolfSSL/wolfssl/tree/master/IDE/Espressif/ESP-IDF/examples/template + * + * Reminder that by the time we are here, the user_settings.h has already + * been processed. The following settings are additive; Enabled settings + * from user_settings are not disabled here. + */ + #if defined(CONFIG_ESP_WOLFSSL_TEST_LOOP) && \ + CONFIG_ESP_WOLFSSL_TEST_LOOP + #define WOLFSSL_TEST_LOOP 1 + #else + #define WOLFSSL_TEST_LOOP 0 + #endif + #if (defined(CONFIG_DEBUG_WOLFSSL) && \ + CONFIG_DEBUG_WOLFSSL) || \ + (defined(CONFIG_ESP_WOLFSSL_DEBUG_WOLFSSL) && \ + CONFIG_ESP_WOLFSSL_DEBUG_WOLFSSL ) + #define DEBUG_WOLFSSL + #endif + #if defined(CONFIG_ESP_WOLFSSL_ENABLE_WOLFSSH) && \ + CONFIG_ESP_WOLFSSL_ENABLE_WOLFSSH + #define WOLFSSL_ENABLE_WOLFSSH + #endif + #if (defined(CONFIG_TEST_ESPIDF_ALL_WOLFSSL) && \ + CONFIG_TEST_ESPIDF_ALL_WOLFSSL ) + #define TEST_ESPIDF_ALL_WOLFSSL + #endif + #if (defined(CONFIG_WOLFSSL_ALT_CERT_CHAINS) && \ + CONFIG_WOLFSSL_ALT_CERT_CHAINS ) + #define WOLFSSL_ALT_CERT_CHAINS + #endif + #if defined(CONFIG_WOLFSSL_ASN_ALLOW_0_SERIAL) && \ + CONFIG_WOLFSSL_ASN_ALLOW_0_SERIAL + #define WOLFSSL_ASN_ALLOW_0_SERIAL + #endif + #if defined(CONFIG_WOLFSSL_NO_ASN_STRICT) && \ + CONFIG_WOLFSSL_NO_ASN_STRICT + #define WOLFSSL_NO_ASN_STRICT + #endif + #if defined(CONFIG_WOLFSSL_DEBUG_CERT_BUNDLE) && \ + CONFIG_WOLFSSL_DEBUG_CERT_BUNDLE + #define WOLFSSL_DEBUG_CERT_BUNDLE + #endif + #if defined(CONFIG_USE_WOLFSSL_ESP_SDK_TIME) && \ + CONFIG_USE_WOLFSSL_ESP_SDK_TIME + #define USE_WOLFSSL_ESP_SDK_TIME + #endif + #if defined(CONFIG_USE_WOLFSSL_ESP_SDK_WIFI) && \ + CONFIG_USE_WOLFSSL_ESP_SDK_WIFI + #define USE_WOLFSSL_ESP_SDK_WIFI + #endif + #if defined(CONFIG_WOLFSSL_APPLE_HOMEKIT) && \ + CONFIG_WOLFSSL_APPLE_HOMEKIT + #define WOLFSSL_APPLE_HOMEKIT + #endif + #if defined(CONFIG_ESP_WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS) && \ + CONFIG_ESP_WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + #define WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS + #endif + #if defined(CONFIG_ESP_WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS) && \ + CONFIG_ESP_WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS + #define WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS + #endif + + #if defined(CONFIG_TLS_STACK_WOLFSSL) && (CONFIG_TLS_STACK_WOLFSSL) + /* When using ESP-TLS, some old algorithms such as SHA1 are no longer + * enabled in wolfSSL, except for the OpenSSL compatibility. So enable + * that here: */ + #define OPENSSL_EXTRA + #endif + + /* Optional Apple HomeKit support. See below for related sanity checks. */ + #if defined(WOLFSSL_APPLE_HOMEKIT) + /* SRP is known to need 8K; slow on some devices */ + #undef FP_MAX_BITS + #define FP_MAX_BITS (8192 * 2) + #define WOLFCRYPT_HAVE_SRP + #define HAVE_CHACHA + #define HAVE_POLY1305 + #define WOLFSSL_BASE64_ENCODE + #define HAVE_HKDF + #define WOLFSSL_SHA512 + #endif + + /* Enable benchmark code via menuconfig, or when not otherwise disable: */ + #ifdef CONFIG_ESP_WOLFSSL_ENABLE_BENCHMARK + #ifdef NO_CRYPT_BENCHMARK + #pragma message("Benchmark conflict:") + #pragma message("-- NO_CRYPT_BENCHMARK defined.") + #pragma message("-- CONFIG_WOLFSSL_ENABLE_BENCHMARK also defined.") + #pragma message("-- NO_CRYPT_BENCHMARK will be undefined.") + #undef NO_CRYPT_BENCHMARK + #endif + #endif + + #if !defined(NO_CRYPT_BENCHMARK) || \ + defined(CONFIG_ESP_WOLFSSL_ENABLE_BENCHMARK) + + #define BENCH_EMBEDDED + #define WOLFSSL_BENCHMARK_FIXED_UNITS_KB + + /* See wolfcrypt/benchmark/benchmark.c for debug and other settings: */ + + /* Turn on benchmark timing debugging (CPU Cycles, RTOS ticks, etc) */ + #ifdef CONFIG_ESP_DEBUG_WOLFSSL_BENCHMARK_TIMING + #define DEBUG_WOLFSSL_BENCHMARK_TIMING + #endif + + /* Turn on timer debugging (used when CPU cycles not available) */ + #ifdef CONFIG_ESP_WOLFSSL_BENCHMARK_TIMER_DEBUG + #define WOLFSSL_BENCHMARK_TIMER_DEBUG + #endif + #endif + + /* Typically only used in tests, but available to all apps is + * the "enable all" feature: */ + #if defined(TEST_ESPIDF_ALL_WOLFSSL) + #define WOLFSSL_MD2 + #define HAVE_BLAKE2 + #define HAVE_BLAKE2B + #define HAVE_BLAKE2S + + #define WC_RC2 + #define WOLFSSL_ALLOW_RC4 + + #define HAVE_POLY1305 + + #define WOLFSSL_AES_128 + #define WOLFSSL_AES_OFB + #define WOLFSSL_AES_CFB + #define WOLFSSL_AES_XTS + + /* #define WC_SRTP_KDF */ + /* TODO Causes failure with Espressif AES HW Enabled */ + /* #define HAVE_AES_ECB */ + /* #define HAVE_AESCCM */ + /* TODO sanity check when missing HAVE_AES_ECB */ + #define WOLFSSL_WOLFSSH + + #define HAVE_AESGCM + #define WOLFSSL_AES_COUNTER + + #define HAVE_FFDHE + #define HAVE_FFDHE_2048 + #if defined(CONFIG_IDF_TARGET_ESP8266) + /* TODO Full size SRP is disabled on the ESP8266 at this time. + * Low memory issue? */ + #define WOLFCRYPT_HAVE_SRP + /* MIN_FFDHE_FP_MAX_BITS = (MIN_FFDHE_BITS * 2); see settings.h */ + #define FP_MAX_BITS MIN_FFDHE_FP_MAX_BITS + #elif defined(CONFIG_IDF_TARGET_ESP32) || \ + defined(CONFIG_IDF_TARGET_ESP32S2) || \ + defined(CONFIG_IDF_TARGET_ESP32S3) + #define WOLFCRYPT_HAVE_SRP + #define FP_MAX_BITS (8192 * 2) + #elif defined(CONFIG_IDF_TARGET_ESP32C3) || \ + defined(CONFIG_IDF_TARGET_ESP32H2) + /* SRP Known to be working on this target::*/ + #define WOLFCRYPT_HAVE_SRP + #define FP_MAX_BITS (8192 * 2) + #else + /* For everything else, give a try and see if SRP working: */ + #define WOLFCRYPT_HAVE_SRP + #define FP_MAX_BITS (8192 * 2) + #endif + + #define HAVE_DH + + /* TODO: there may be a problem with HAVE_CAMELLIA with HW AES disabled. + * Do not define NO_WOLFSSL_ESP32_CRYPT_AES when enabled: */ + /* #define HAVE_CAMELLIA */ + + /* DSA requires old SHA */ + #define HAVE_DSA + + /* Needs SHA512 ? */ + #define HAVE_HPKE + + /* Not for Espressif? */ + #if defined(CONFIG_IDF_TARGET_ESP32C2) || \ + defined(CONFIG_IDF_TARGET_ESP8684) || \ + defined(CONFIG_IDF_TARGET_ESP32H2) || \ + defined(CONFIG_IDF_TARGET_ESP8266) + + #if defined(CONFIG_IDF_TARGET_ESP8266) + #undef HAVE_ECC + #undef HAVE_ECC_CDH + #undef HAVE_CURVE25519 + + #ifdef HAVE_CHACHA + #error "HAVE_CHACHA not supported on ESP8266" + #endif + #ifdef HAVE_XCHACHA + #error "HAVE_XCHACHA not supported on ESP8266" + #endif + #else + #define HAVE_XCHACHA + #define HAVE_CHACHA + /* TODO Not enabled at this time, needs further testing: + * #define WC_SRTP_KDF + * #define HAVE_COMP_KEY + * #define WOLFSSL_HAVE_XMSS + */ + #endif + /* TODO AES-EAX needs stesting on this platform */ + + /* Optionally disable DH + * #undef HAVE_DH + * #undef HAVE_FFDHE + */ + + /* ECC_SHAMIR out of memory on ESP32-C2 during ECC */ + #ifndef HAVE_ECC + #define ECC_SHAMIR + #endif + #else + #define WOLFSSL_AES_EAX + + #define ECC_SHAMIR + #endif + + /* Only for WOLFSSL_IMX6_CAAM / WOLFSSL_QNX_CAAM ? */ + /* #define WOLFSSL_CAAM */ + /* #define WOLFSSL_CAAM_BLOB */ + + #define WOLFSSL_AES_SIV + #define WOLFSSL_CMAC + + #define WOLFSSL_CERT_PIV + + /* HAVE_SCRYPT may turn on HAVE_PBKDF2 see settings.h */ + /* #define HAVE_SCRYPT */ + #define SCRYPT_TEST_ALL + #define HAVE_X963_KDF + #endif + + /* Optionally enable some wolfSSH settings via compiler def or Kconfig */ + #if defined(ESP_ENABLE_WOLFSSH) + /* The default SSH Windows size is massive for an embedded target. + * Limit it: */ + #define DEFAULT_WINDOW_SZ 2000 + + /* These may be defined in cmake for other examples: */ + #undef WOLFSSH_TERM + #define WOLFSSH_TERM + + #if defined(CONFIG_ESP_WOLFSSL_DEBUG_WOLFSSH) + /* wolfSSH debugging enabled via Kconfig / menuconfig */ + #undef DEBUG_WOLFSSH + #define DEBUG_WOLFSSH + #endif + + #undef WOLFSSL_KEY_GEN + #define WOLFSSL_KEY_GEN + + #undef WOLFSSL_PTHREADS + #define WOLFSSL_PTHREADS + + #define WOLFSSH_TEST_SERVER + #define WOLFSSH_TEST_THREADING + + #endif /* ESP_ENABLE_WOLFSSH */ + + /* Experimental Kyber. */ + #ifdef CONFIG_ESP_WOLFSSL_ENABLE_KYBER + /* Kyber typically needs a minimum 10K stack */ + #define WOLFSSL_EXPERIMENTAL_SETTINGS + #define WOLFSSL_HAVE_KYBER + #define WOLFSSL_WC_KYBER + #define WOLFSSL_SHA3 + #if defined(CONFIG_IDF_TARGET_ESP8266) + /* With limited RAM, we'll disable some of the Kyber sizes: */ + #define WOLFSSL_NO_KYBER1024 + #define WOLFSSL_NO_KYBER768 + #define NO_SESSION_CACHE + #endif + #endif + #ifndef NO_ESPIDF_DEFAULT #define FREERTOS #define WOLFSSL_LWIP @@ -605,7 +936,58 @@ #undef HAVE_AESGCM #define HAVE_AESGCM #endif /* SM */ + #endif /* defined(WOLFSSL_ESP32) || defined(WOLFSSL_ESPWROOM32SE) */ + /* Final device-specific hardware settings. user_settings.h loaded above. */ + + /* Counters for RSA wait timeout. CPU and frequency specific. */ + #define ESP_RSA_WAIT_TIMEOUT_CNT 0x000020 + #if defined(CONFIG_IDF_TARGET_ESP32) || defined(WOLFSSL_ESPWROOM32SE) + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32S2) + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32S3) + #ifndef ESP_RSA_TIMEOUT_CNT + /* Observed: 0xAE8C8F @ 80MHz */ + #define ESP_RSA_TIMEOUT_CNT 0xAF0000 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32C2) + /* See also CONFIG_IDF_TARGET_ESP8684 equivalent */ + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32C3) + #ifndef ESP_RSA_TIMEOUT_CNT + /* Observed: 0x2624B2 @ 80MHz */ + #define ESP_RSA_TIMEOUT_CNT 0x280000 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32C6) + #ifndef ESP_RSA_TIMEOUT_CNT + /* Observed: 144323 @ 80MHz */ + #define ESP_RSA_TIMEOUT_CNT 0x160000 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP32H2) + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP8266) + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #elif defined(CONFIG_IDF_TARGET_ESP8684) + /* See also CONFIG_IDF_TARGET_ESP8684 equivalent */ + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #else + #ifndef ESP_RSA_TIMEOUT_CNT + #define ESP_RSA_TIMEOUT_CNT 0x349F00 + #endif + #endif #endif /* WOLFSSL_ESPIDF */ #if defined(WOLFSSL_RENESAS_TSIP) @@ -693,7 +1075,6 @@ #define NO_DEV_RANDOM #define NO_FILESYSTEM #define TFM_TIMING_RESISTANT - #define NO_BIG_INT #endif #ifdef WOLFSSL_MICROCHIP_PIC32MZ @@ -1087,7 +1468,8 @@ extern void uITRON4_free(void *p) ; * heap_caps_realloc(p, s, MALLOC_CAP_8BIT) * There's no pvPortRealloc available: */ #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) - #elif defined(USE_INTEGER_HEAP_MATH) || defined(OPENSSL_EXTRA) + #elif defined(USE_INTEGER_HEAP_MATH) || defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_ALL) /* FreeRTOS pvPortRealloc() implementation can be found here: * https://github.com/wolfSSL/wolfssl-freertos/pull/3/files */ #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), pvPortRealloc((p), (n))) @@ -1099,7 +1481,7 @@ extern void uITRON4_free(void *p) ; #ifndef NO_WRITEV #define NO_WRITEV #endif - #ifndef HAVE_SHA512 + #ifndef WOLFSSL_SHA512 #ifndef NO_SHA512 #define NO_SHA512 #endif @@ -1640,6 +2022,7 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_STATIC_PSK /* Server side support to be added at a later date. */ #define NO_WOLFSSL_SERVER + /* Need WOLFSSL_PUBLIC_ASN to use ProcessPeerCert callback. */ #define WOLFSSL_PUBLIC_ASN @@ -1671,7 +2054,8 @@ extern void uITRON4_free(void *p) ; defined(WOLFSSL_STM32L4) || defined(WOLFSSL_STM32L5) || \ defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32H7) || \ defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ - defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) + defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) || \ + defined(WOLFSSL_STM32G4) #define SIZEOF_LONG_LONG 8 #ifndef CHAR_BIT @@ -1727,6 +2111,8 @@ extern void uITRON4_free(void *p) ; #include "stm32wlxx_hal.h" #elif defined(WOLFSSL_STM32G0) #include "stm32g0xx_hal.h" + #elif defined(WOLFSSL_STM32G4) + #include "stm32g4xx_hal.h" #elif defined(WOLFSSL_STM32U5) #include "stm32u5xx_hal.h" #elif defined(WOLFSSL_STM32H5) @@ -1785,10 +2171,7 @@ extern void uITRON4_free(void *p) ; #include "stm32f1xx.h" #endif #endif /* WOLFSSL_STM32_CUBEMX */ -#endif /* WOLFSSL_STM32F2 || WOLFSSL_STM32F4 || WOLFSSL_STM32L4 || - WOLFSSL_STM32L5 || WOLFSSL_STM32F7 || WOLFSSL_STMWB || - WOLFSSL_STM32H7 || WOLFSSL_STM32G0 || WOLFSSL_STM32U5 || - WOLFSSL_STM32H5 */ +#endif /* WOLFSSL_STM32* */ #ifdef WOLFSSL_DEOS #include #include @@ -2020,6 +2403,15 @@ extern void uITRON4_free(void *p) ; #define HAVE_AESGCM #endif +/* Detect Cortex M3 (no UMAAL) */ +#if defined(__ARM_ARCH_7M__) && !defined(WOLFSSL_ARM_ARCH_7M) + #define WOLFSSL_ARM_ARCH_7M +#endif +#if defined(WOLFSSL_SP_ARM_CORTEX_M_ASM) && defined(WOLFSSL_ARM_ARCH_7M) + #undef WOLFSSL_SP_NO_UMAAL + #define WOLFSSL_SP_NO_UMAAL +#endif + #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_AFALG_XILINX) #if defined(WOLFSSL_ARMASM) #error can not use both ARMv8 instructions and XILINX hardened crypto @@ -2032,6 +2424,12 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_NOSHA3_224 #define WOLFSSL_NOSHA3_256 #define WOLFSSL_NOSHA3_512 + #ifndef WOLFSSL_NO_SHAKE128 + #define WOLFSSL_NO_SHAKE128 + #endif + #ifndef WOLFSSL_NO_SHAKE256 + #define WOLFSSL_NO_SHAKE256 + #endif #endif #ifdef WOLFSSL_AFALG_XILINX_AES #undef WOLFSSL_AES_DIRECT @@ -2112,6 +2510,7 @@ extern void uITRON4_free(void *p) ; void *z_realloc(void *ptr, size_t size); #define realloc z_realloc + #define max MAX #if !defined(CONFIG_NET_SOCKETS_POSIX_NAMES) && !defined(CONFIG_POSIX_API) #define CONFIG_NET_SOCKETS_POSIX_NAMES @@ -2344,7 +2743,7 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_SP_INT_DIGIT_ALIGN #define WOLFSSL_SP_INT_DIGIT_ALIGN #endif -#ifdef __APPLE__ +#if defined(__APPLE__) || defined(WOLF_C89) #define WOLFSSL_SP_NO_DYN_STACK #endif @@ -2878,6 +3277,167 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_ASN_TEMPLATE #endif +#if defined(WOLFSSL_DUAL_ALG_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE) + #error "Dual alg cert support requires the ASN.1 template feature." +#endif + +#if defined(WOLFSSL_ACERT) && !defined(WOLFSSL_ASN_TEMPLATE) + #error "Attribute Certificate support requires the ASN.1 template feature." +#endif + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + #undef WOLFSSL_ASN_ALL + #define WOLFSSL_ASN_ALL +#endif + +/* Enable all parsing features for ASN */ +#ifdef WOLFSSL_ASN_ALL + /* Alternate Names */ + #undef WOLFSSL_ALT_NAMES + #define WOLFSSL_ALT_NAMES + + /* Alternate Name: human readable form of IP address*/ + #undef WOLFSSL_IP_ALT_NAME + #define WOLFSSL_IP_ALT_NAME + + /* Alternate name: human readable form of registered ID */ + #undef WOLFSSL_RID_ALT_NAME + #define WOLFSSL_RID_ALT_NAME + + /* CA Issuer URI */ + #undef WOLFSSL_ASN_CA_ISSUER + #define WOLFSSL_ASN_CA_ISSUER + + /* FPKI (Federal PKI) extensions */ + #undef WOLFSSL_FPKI + #define WOLFSSL_FPKI + + /* Certificate policies */ + #undef WOLFSSL_SEP + #define WOLFSSL_SEP + + /* Support for full AuthorityKeyIdentifier extension. + * Only supports copying full AKID from an existing certificate */ + #undef WOLFSSL_AKID_NAME + #define WOLFSSL_AKID_NAME + + /* Extended ASN.1 parsing support (typically used with cert gen) */ + #undef WOLFSSL_CERT_EXT + #define WOLFSSL_CERT_EXT + + /* Support for SubjectDirectoryAttributes extension */ + #undef WOLFSSL_SUBJ_DIR_ATTR + #define WOLFSSL_SUBJ_DIR_ATTR + + /* Support for SubjectInfoAccess extension */ + #undef WOLFSSL_SUBJ_INFO_ACC + #define WOLFSSL_SUBJ_INFO_ACC + + #undef WOLFSSL_CERT_NAME_ALL + #define WOLFSSL_CERT_NAME_ALL + + /* Store pointers to issuer name components (lengths and encodings) */ + #undef WOLFSSL_HAVE_ISSUER_NAMES + #define WOLFSSL_HAVE_ISSUER_NAMES + + /* Additional ASN.1 encoded name fields. See CTC_MAX_ATTRIB for max limit */ + #undef WOLFSSL_MULTI_ATTRIB + #define WOLFSSL_MULTI_ATTRIB + + /* Parsing of indefinite length encoded ASN.1 + * Optionally used by PKCS7/PKCS12 */ + #undef ASN_BER_TO_DER + #define ASN_BER_TO_DER + + /* Enable custom OID support for subject and request extensions */ + #undef WOLFSSL_CUSTOM_OID + #define WOLFSSL_CUSTOM_OID + + /* Support for full OID (not just sum) encoding */ + #undef HAVE_OID_ENCODING + #define HAVE_OID_ENCODING + + /* Support for full OID (not just sum) decoding */ + #undef HAVE_OID_DECODING + #define HAVE_OID_DECODING + + /* S/MIME - Secure Multipurpose Internet Mail Extension (used with PKCS7) */ + #undef HAVE_SMIME + #define HAVE_SMIME + + /* Enable compatibility layer function for getting time string */ + #undef WOLFSSL_ASN_TIME_STRING + #define WOLFSSL_ASN_TIME_STRING + + /* Support for parsing key usage */ + #undef WOLFSSL_ASN_PARSE_KEYUSAGE + #define WOLFSSL_ASN_PARSE_KEYUSAGE + + /* Support for parsing OCSP status */ + #undef WOLFSSL_OCSP_PARSE_STATUS + #define WOLFSSL_OCSP_PARSE_STATUS + + /* Extended Key Usage */ + #undef WOLFSSL_EKU_OID + #define WOLFSSL_EKU_OID + + /* Attribute Certificate support */ + #if defined(WOLFSSL_ASN_TEMPLATE) && !defined(WOLFSSL_ACERT) + #define WOLFSSL_ACERT + #endif +#endif + +#if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ + defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + #undef WOLFSSL_ASN_TIME_STRING + #define WOLFSSL_ASN_TIME_STRING +#endif + +#if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \ + (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)) + #undef WOLFSSL_ASN_PARSE_KEYUSAGE + #define WOLFSSL_ASN_PARSE_KEYUSAGE +#endif + +#if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_APACHE_HTTPD)) + #undef WOLFSSL_OCSP_PARSE_STATUS + #define WOLFSSL_OCSP_PARSE_STATUS +#endif + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_CERT_GEN) + #undef WOLFSSL_MULTI_ATTRIB + #define WOLFSSL_MULTI_ATTRIB +#endif + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + #undef WOLFSSL_EKU_OID + #define WOLFSSL_EKU_OID +#endif + +/* Disable time checking if no timer */ +#if defined(NO_ASN_TIME) + #define NO_ASN_TIME_CHECK +#endif + +/* ASN Unknown Extension Callback support */ +#if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING) && \ + defined(WOLFSSL_ASN_TEMPLATE) + #undef WC_ASN_UNKNOWN_EXT_CB + #define WC_ASN_UNKNOWN_EXT_CB +#else + /* if user supplied build option and not using ASN template, raise error */ + #if defined(WC_ASN_UNKNOWN_EXT_CB) && !defined(WOLFSSL_ASN_TEMPLATE) + #error ASN unknown extension callback is only supported \ + with ASN template + #endif +#endif + + +/* Linux Kernel Module */ #ifdef WOLFSSL_LINUXKM #ifdef HAVE_CONFIG_H #include @@ -3003,30 +3563,15 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_SESSION_ID_CTX #endif /* OPENSSL_EXTRA && !OPENSSL_COEXIST */ -/* --------------------------------------------------------------------------- - * Special small OpenSSL compat layer for certs - * --------------------------------------------------------------------------- - */ #ifdef OPENSSL_EXTRA_X509_SMALL - #undef WOLFSSL_EKU_OID - #define WOLFSSL_EKU_OID - - #undef WOLFSSL_MULTI_ATTRIB - #define WOLFSSL_MULTI_ATTRIB - #undef WOLFSSL_NO_OPENSSL_RAND_CB #define WOLFSSL_NO_OPENSSL_RAND_CB -#endif /* OPENSSL_EXTRA_X509_SMALL */ +#endif #ifdef HAVE_SNI #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 #endif -/* Disable time checking if no timer */ -#if defined(NO_ASN_TIME) - #define NO_ASN_TIME_CHECK -#endif - /* both CURVE and ED small math should be enabled */ #ifdef CURVED25519_SMALL #define CURVE25519_SMALL @@ -3117,6 +3662,22 @@ extern void uITRON4_free(void *p) ; #define KEEP_PEER_CERT #endif +/* Always copy certificate(s) from SSL CTX to each SSL object on creation, + * if this is not defined then each SSL object shares a pointer to the + * original certificate buffer owned by the SSL CTX. */ +#if defined(OPENSSL_ALL) && !defined(WOLFSSL_NO_COPY_CERT) + #undef WOLFSSL_COPY_CERT + #define WOLFSSL_COPY_CERT +#endif + +/* Always copy private key from SSL CTX to each SSL object on creation, + * if this is not defined then each SSL object shares a pointer to the + * original key buffer owned by the SSL CTX. */ +#if defined(OPENSSL_ALL) && !defined(WOLFSSL_NO_COPY_KEY) + #undef WOLFSSL_COPY_KEY + #define WOLFSSL_COPY_KEY +#endif + /* * Keeps the "Finished" messages after a TLS handshake for use as the so-called * "tls-unique" channel binding. See comment in internal.h around clientFinished @@ -3133,8 +3694,8 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_NO_HASH_RAW #endif -/* XChacha not implemented with ARM assembly ChaCha */ -#if defined(WOLFSSL_ARMASM) +#if defined(HAVE_XCHACHA) && !defined(HAVE_CHACHA) + /* XChacha requires ChaCha */ #undef HAVE_XCHACHA #endif @@ -3366,17 +3927,7 @@ extern void uITRON4_free(void *p) ; #endif #endif -#ifdef HAVE_PQM4 -#define HAVE_PQC -#define WOLFSSL_HAVE_KYBER -#define WOLFSSL_KYBER512 -#define WOLFSSL_NO_KYBER768 -#define WOLFSSL_NO_KYBER1024 -#endif - #if (defined(HAVE_LIBOQS) || \ - defined(WOLFSSL_WC_KYBER) || \ - defined(WOLFSSL_WC_DILITHIUM) || \ defined(HAVE_LIBXMSS) || \ defined(HAVE_LIBLMS) || \ defined(WOLFSSL_DUAL_ALG_CERTS)) && \ @@ -3384,15 +3935,10 @@ extern void uITRON4_free(void *p) ; #error Experimental settings without WOLFSSL_EXPERIMENTAL_SETTINGS #endif -#if defined(HAVE_PQC) && !defined(HAVE_LIBOQS) && !defined(HAVE_PQM4) && \ - !defined(WOLFSSL_HAVE_KYBER) +#if defined(HAVE_PQC) && !defined(HAVE_LIBOQS) && !defined(WOLFSSL_HAVE_KYBER) #error Please do not define HAVE_PQC yourself. #endif -#if defined(HAVE_PQC) && defined(HAVE_LIBOQS) && defined(HAVE_PQM4) -#error Please do not define both HAVE_LIBOQS and HAVE_PQM4. -#endif - #if defined(HAVE_PQC) && defined(WOLFSSL_DTLS13) && \ !defined(WOLFSSL_DTLS_CH_FRAG) #warning "Using DTLS 1.3 + pqc without WOLFSSL_DTLS_CH_FRAG will probably" \ @@ -3475,22 +4021,28 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_RSA_KEY_CHECK #endif -/* SHAKE - Not allowed in FIPS */ -#if defined(WOLFSSL_SHA3) && !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - #ifndef WOLFSSL_NO_SHAKE128 - #undef WOLFSSL_SHAKE128 - #define WOLFSSL_SHAKE128 - #endif - #ifndef WOLFSSL_NO_SHAKE256 - #undef WOLFSSL_SHAKE256 - #define WOLFSSL_SHAKE256 - #endif -#else +/* ED448 Requires Shake256 */ +#if defined(HAVE_ED448) && defined(WOLFSSL_SHA3) + #undef WOLFSSL_SHAKE256 + #define WOLFSSL_SHAKE256 +#endif + +/* SHAKE - Not allowed in FIPS v5.2 or older */ +#if defined(WOLFSSL_SHA3) && (defined(HAVE_SELFTEST) || \ + (defined(HAVE_FIPS) && FIPS_VERSION_LE(5,2))) #undef WOLFSSL_NO_SHAKE128 #define WOLFSSL_NO_SHAKE128 #undef WOLFSSL_NO_SHAKE256 #define WOLFSSL_NO_SHAKE256 #endif +/* SHAKE Disable */ +#ifdef WOLFSSL_NO_SHAKE128 + #undef WOLFSSL_SHAKE128 +#endif +#ifdef WOLFSSL_NO_SHAKE256 + #undef WOLFSSL_SHAKE256 +#endif + /* Encrypted Client Hello - requires HPKE */ #if defined(HAVE_ECH) && !defined(HAVE_HPKE) @@ -3559,8 +4111,8 @@ extern void uITRON4_free(void *p) ; /* Ciphersuite check done in internal.h */ #endif -/* Some final sanity checks */ -#ifdef WOLFSSL_APPLE_HOMEKIT +/* Some final sanity checks. See esp32-crypt.h for Apple HomeKit config. */ +#if defined(WOLFSSL_APPLE_HOMEKIT) || defined(CONFIG_WOLFSSL_APPLE_HOMEKIT) #ifndef WOLFCRYPT_HAVE_SRP #error "WOLFCRYPT_HAVE_SRP is required for Apple Homekit" #endif @@ -3578,10 +4130,23 @@ extern void uITRON4_free(void *p) ; #endif #endif +#if defined(CONFIG_WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_NO_ASN_STRICT) + /* The settings.h and/or user_settings.h should have detected config + * values from Kconfig and set the appropriate wolfSSL macro: */ + #error "CONFIG_WOLFSSL_NO_ASN_STRICT found without WOLFSSL_NO_ASN_STRICT" +#endif + #if defined(WOLFSSL_ESPIDF) && defined(ARDUINO) #error "Found both ESPIDF and ARDUINO. Pick one." #endif +#if defined(CONFIG_MBEDTLS_CERTIFICATE_BUNDLE) && \ + defined(CONFIG_WOLFSSL_CERTIFICATE_BUNDLE) && \ + CONFIG_MBEDTLS_CERTIFICATE_BUNDLE && \ + CONFIG_WOLFSSL_CERTIFICATE_BUNDLE + #error "mbedTLS and wolfSSL Certificate Bundles both enabled. Pick one". +#endif + #if defined(HAVE_FIPS) && defined(HAVE_PKCS11) #error "PKCS11 not allowed with FIPS enabled (Crypto outside boundary)" #endif diff --git a/src/wolfssl/wolfcrypt/sha.h b/src/wolfssl/wolfcrypt/sha.h index eb599ab..063784e 100644 --- a/src/wolfssl/wolfcrypt/sha.h +++ b/src/wolfssl/wolfcrypt/sha.h @@ -1,6 +1,6 @@ /* sha.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -76,6 +76,9 @@ #if defined(WOLFSSL_SILABS_SE_ACCEL) #include #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include +#endif #if !defined(NO_OLD_SHA_NAMES) #define SHA WC_SHA @@ -148,8 +151,8 @@ struct wc_Sha { #else word32 digest[WC_SHA_DIGEST_SIZE / sizeof(word32)]; #endif - void* heap; #endif + void* heap; #ifdef WOLFSSL_PIC32MZ_HASH hashUpdCache cache; /* cache for updates */ #endif @@ -160,6 +163,9 @@ struct wc_Sha { int devId; void* devCtx; /* generic crypto callback context */ #endif +#if defined(MAX3266X_SHA_CB) || defined(MAX3266X_SHA) + wc_MXC_Sha mxcCtx; +#endif #ifdef WOLFSSL_IMXRT1170_CAAM caam_hash_ctx_t ctx; caam_handle_t hndl; diff --git a/src/wolfssl/wolfcrypt/sha256.h b/src/wolfssl/wolfcrypt/sha256.h index a6c4ea4..b5534d4 100644 --- a/src/wolfssl/wolfcrypt/sha256.h +++ b/src/wolfssl/wolfcrypt/sha256.h @@ -1,6 +1,6 @@ /* sha256.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -146,6 +146,10 @@ enum { #include "wolfssl/wolfcrypt/port/Renesas/renesas-rx64-hw-crypt.h" #else +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include "wolfssl/wolfcrypt/port/maxim/max3266x.h" +#endif + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) #include "wolfssl/wolfcrypt/port/nxp/se050_port.h" #endif @@ -190,13 +194,13 @@ struct wc_Sha256 { word32 buffLen; /* in bytes */ word32 loLen; /* length in bytes */ word32 hiLen; /* length in bytes */ - void* heap; #ifdef WC_C_DYNAMIC_FALLBACK int sha_method; #endif #endif + void* heap; #ifdef WOLFSSL_PIC32MZ_HASH hashUpdCache cache; /* cache for updates */ #endif @@ -209,6 +213,9 @@ struct wc_Sha256 { #ifdef WOLFSSL_DEVCRYPTO_HASH WC_CRYPTODEV ctx; #endif +#if defined(MAX3266X_SHA_CB) || defined(MAX3266X_SHA) + wc_MXC_Sha mxcCtx; +#endif #if defined(WOLFSSL_DEVCRYPTO_HASH) || defined(WOLFSSL_HASH_KEEP) byte* msg; word32 used; diff --git a/src/wolfssl/wolfcrypt/sha3.h b/src/wolfssl/wolfcrypt/sha3.h index e1ce33a..f65c41d 100644 --- a/src/wolfssl/wolfcrypt/sha3.h +++ b/src/wolfssl/wolfcrypt/sha3.h @@ -1,6 +1,6 @@ /* sha3.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -220,8 +220,7 @@ WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); WOLFSSL_LOCAL void sha3_block_avx2(word64* s); WOLFSSL_LOCAL void BlockSha3(word64 *s); #endif -#if defined(WOLFSSL_ARMASM) && (defined(__arm__) || \ - defined(WOLFSSL_ARMASM_CRYPTO_SHA3)) +#if defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) WOLFSSL_LOCAL void BlockSha3(word64 *s); #endif diff --git a/src/wolfssl/wolfcrypt/sha512.h b/src/wolfssl/wolfcrypt/sha512.h index bf3cff6..e971a8d 100644 --- a/src/wolfssl/wolfcrypt/sha512.h +++ b/src/wolfssl/wolfcrypt/sha512.h @@ -1,6 +1,6 @@ /* sha512.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -135,12 +135,16 @@ enum { #include "mcapi.h" #include "mcapi_error.h" #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include "wolfssl/wolfcrypt/port/maxim/max3266x.h" +#endif /* wc_Sha512 digest */ struct wc_Sha512 { #ifdef WOLFSSL_PSOC6_CRYPTO cy_stc_crypto_sha_state_t hash_state; cy_en_crypto_sha_mode_t sha_mode; cy_stc_crypto_v2_sha512_buffers_t sha_buffers; + void* heap; #else word64 digest[WC_SHA512_DIGEST_SIZE / sizeof(word64)]; word64 buffer[WC_SHA512_BLOCK_SIZE / sizeof(word64)]; @@ -185,6 +189,9 @@ struct wc_Sha512 { int devId; void* devCtx; /* generic crypto callback context */ #endif +#if defined(MAX3266X_SHA_CB) || defined(MAX3266X_SHA) + wc_MXC_Sha mxcCtx; +#endif #ifdef WOLFSSL_HASH_FLAGS word32 flags; /* enum wc_HashFlags in hash.h */ #endif diff --git a/src/wolfssl/wolfcrypt/signature.h b/src/wolfssl/wolfcrypt/signature.h index f712c04..51c07af 100644 --- a/src/wolfssl/wolfcrypt/signature.h +++ b/src/wolfssl/wolfcrypt/signature.h @@ -1,6 +1,6 @@ /* signature.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/siphash.h b/src/wolfssl/wolfcrypt/siphash.h index ebb1302..6b75a46 100644 --- a/src/wolfssl/wolfcrypt/siphash.h +++ b/src/wolfssl/wolfcrypt/siphash.h @@ -1,6 +1,6 @@ /* siphash.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm2.h b/src/wolfssl/wolfcrypt/sm2.h index 87167f4..ae9885e 100644 --- a/src/wolfssl/wolfcrypt/sm2.h +++ b/src/wolfssl/wolfcrypt/sm2.h @@ -1,6 +1,6 @@ /* sm2.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm3.h b/src/wolfssl/wolfcrypt/sm3.h index 2b3fc50..b24fcf4 100644 --- a/src/wolfssl/wolfcrypt/sm3.h +++ b/src/wolfssl/wolfcrypt/sm3.h @@ -1,6 +1,6 @@ /* sm3.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm4.h b/src/wolfssl/wolfcrypt/sm4.h index f3e66cb..84a8166 100644 --- a/src/wolfssl/wolfcrypt/sm4.h +++ b/src/wolfssl/wolfcrypt/sm4.h @@ -1,6 +1,6 @@ /* sm4.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sp.h b/src/wolfssl/wolfcrypt/sp.h index 88e9a06..3ede752 100644 --- a/src/wolfssl/wolfcrypt/sp.h +++ b/src/wolfssl/wolfcrypt/sp.h @@ -1,6 +1,6 @@ /* sp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sp_int.h b/src/wolfssl/wolfcrypt/sp_int.h index ba16895..2a9a880 100644 --- a/src/wolfssl/wolfcrypt/sp_int.h +++ b/src/wolfssl/wolfcrypt/sp_int.h @@ -1,6 +1,6 @@ /* sp_int.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -178,13 +178,6 @@ extern "C" { #define WOLFSSL_SP_DIV_WORD_HALF #endif -/* Detect Cortex M3 (no UMAAL) */ -#if defined(WOLFSSL_SP_ARM_CORTEX_M_ASM) && defined(__ARM_ARCH_7M__) - #undef WOLFSSL_SP_NO_UMAAL - #define WOLFSSL_SP_NO_UMAAL -#endif - - /* Make sure WOLFSSL_SP_ASM build option defined when requested */ #if !defined(WOLFSSL_SP_ASM) && ( \ defined(WOLFSSL_SP_X86_64_ASM) || defined(WOLFSSL_SP_ARM32_ASM) || \ @@ -692,14 +685,14 @@ typedef struct sp_ecc_ctx { * * @param [in] a SP integer to update. */ -#define sp_clamp(a) \ - do { \ - int ii; \ - if ((a)->used > 0) { \ +#define sp_clamp(a) \ + do { \ + int ii; \ + if ((a)->used > 0) { \ for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ - } \ - (a)->used = (unsigned int)ii + 1; \ - } \ + } \ + (a)->used = (mp_size_t)(ii + 1); \ + } \ } while (0) /* Check the compiled and linked math implementation are the same. @@ -742,24 +735,18 @@ typedef struct sp_ecc_ctx { #define MP_LT (-1) /* ERROR VALUES */ + +/* MP_MEM, MP_VAL, MP_WOULDBLOCK, and MP_NOT_INF are defined in error-crypt.h */ + /** Error value on success. */ #define MP_OKAY 0 -/** Error value when dynamic memory allocation fails. */ -#define MP_MEM (-2) -/** Error value when value passed is not able to be used. */ -#define MP_VAL (-3) -/** Error value when non-blocking operation is returning after partial - * completion. - */ -#define FP_WOULDBLOCK (-4) -/* Unused error. Defined for backward compatibility. */ -#define MP_NOT_INF (-5) + +#define FP_WOULDBLOCK MP_WOULDBLOCK /* Unused error. Defined for backward compatibility. */ #define MP_RANGE MP_NOT_INF - #ifdef USE_FAST_MATH /* For old FIPS, need FP_MEM defined for old implementation. */ -#define FP_MEM (-2) +#define FP_MEM MP_MEM #endif /* Number of bits in each word/digit. */ @@ -776,8 +763,8 @@ typedef struct sp_ecc_ctx { /* The number of bytes to a sp_int with 'cnt' digits. * Must have at least one digit. */ -#define MP_INT_SIZEOF(cnt) \ - (sizeof(sp_int_minimal) + (((cnt) <= 1) ? 0 : ((cnt) - 1)) * \ +#define MP_INT_SIZEOF(cnt) \ + (sizeof(sp_int_minimal) + (((cnt) <= 1) ? 0 : ((size_t)((cnt) - 1))) * \ sizeof(sp_int_digit)) /* The address of the next sp_int after one with 'cnt' digits. */ #define MP_INT_NEXT(t, cnt) \ @@ -786,7 +773,7 @@ typedef struct sp_ecc_ctx { /* Calculate the number of words required to support a number of bits. */ #define MP_BITS_CNT(bits) \ - ((((bits) + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1) + ((unsigned int)(((((bits) + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1))) #ifdef WOLFSSL_SMALL_STACK /* @@ -871,6 +858,20 @@ while (0) #define WOLF_BIGINT_DEFINED #endif +#if SP_INT_DIGITS < (65536 / SP_WORD_SIZEOF) +/* Type for number of digits. */ +typedef word16 sp_size_t; +#else +/* Type for number of digits. */ +typedef unsigned int sp_size_t; +#endif + +/* Type for number of digits. */ +#define mp_size_t sp_size_t +#ifdef WOLFSSL_SP_INT_NEGATIVE + typedef sp_uint8 sp_sign_t; + #define mp_sign_t sp_sign_t +#endif /** * SP integer. @@ -879,12 +880,12 @@ while (0) */ typedef struct sp_int { /** Number of words that contain data. */ - unsigned int used; + sp_size_t used; /** Maximum number of words in data. */ - unsigned int size; + sp_size_t size; #ifdef WOLFSSL_SP_INT_NEGATIVE /** Indicates whether number is 0/positive or negative. */ - unsigned int sign; + sp_sign_t sign; #endif #ifdef HAVE_WOLF_BIGINT /** Unsigned binary (big endian) representation of number. */ @@ -895,12 +896,16 @@ typedef struct sp_int { } sp_int; typedef struct sp_int_minimal { - unsigned int used; - unsigned int size; + /** Number of words that contain data. */ + sp_size_t used; + /** Maximum number of words in data. */ + sp_size_t size; #ifdef WOLFSSL_SP_INT_NEGATIVE - unsigned int sign; + /** Indicates whether number is 0/positive or negative. */ + sp_uint8 sign; #endif #ifdef HAVE_WOLF_BIGINT + /** Unsigned binary (big endian) representation of number. */ struct WC_BIGINT raw; #endif /** First digit of number. */ @@ -1145,27 +1150,22 @@ WOLFSSL_LOCAL void sp_memzero_check(sp_int* sp); #define mp_div_2 sp_div_2 #define mp_add sp_add #define mp_sub sp_sub -#define mp_addmod sp_addmod -#define mp_submod sp_submod + #define mp_addmod_ct sp_addmod_ct #define mp_submod_ct sp_submod_ct #define mp_xor_ct sp_xor_ct #define mp_lshd sp_lshd #define mp_rshd sp_rshd #define mp_div sp_div -#define mp_mod sp_mod #define mp_mul sp_mul -#define mp_mulmod sp_mulmod #define mp_invmod sp_invmod #define mp_invmod_mont_ct sp_invmod_mont_ct #define mp_exptmod_ex sp_exptmod_ex -#define mp_exptmod sp_exptmod #define mp_exptmod_nct sp_exptmod_nct #define mp_div_2d sp_div_2d #define mp_mod_2d sp_mod_2d #define mp_mul_2d sp_mul_2d #define mp_sqr sp_sqr -#define mp_sqrmod sp_sqrmod #define mp_unsigned_bin_size sp_unsigned_bin_size #define mp_read_unsigned_bin sp_read_unsigned_bin @@ -1188,6 +1188,17 @@ WOLFSSL_LOCAL void sp_memzero_check(sp_int* sp); #define mp_memzero_add sp_memzero_add #define mp_memzero_check sp_memzero_check +/* Allow for Hardware Based Mod Math */ +/* Avoid redeclaration warnings */ +#ifndef WOLFSSL_USE_HW_MP + #define mp_mod sp_mod + #define mp_addmod sp_addmod + #define mp_submod sp_submod + #define mp_mulmod sp_mulmod + #define mp_exptmod sp_exptmod + #define mp_sqrmod sp_sqrmod +#endif + #ifdef WOLFSSL_DEBUG_MATH #define mp_dump(d, a, v) sp_print(a, d) #endif diff --git a/src/wolfssl/wolfcrypt/sphincs.h b/src/wolfssl/wolfcrypt/sphincs.h index 84871f5..6dd3a8e 100644 --- a/src/wolfssl/wolfcrypt/sphincs.h +++ b/src/wolfssl/wolfcrypt/sphincs.h @@ -1,6 +1,6 @@ /* sphincs.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/srp.h b/src/wolfssl/wolfcrypt/srp.h index 7832113..d1307c7 100644 --- a/src/wolfssl/wolfcrypt/srp.h +++ b/src/wolfssl/wolfcrypt/srp.h @@ -1,6 +1,6 @@ /* srp.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/tfm.h b/src/wolfssl/wolfcrypt/tfm.h index 915a335..a9b0df2 100644 --- a/src/wolfssl/wolfcrypt/tfm.h +++ b/src/wolfssl/wolfcrypt/tfm.h @@ -1,6 +1,6 @@ /* tfm.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -40,6 +40,7 @@ #define WOLF_CRYPT_TFM_H #include +#include #ifndef CHAR_BIT #include #endif @@ -305,10 +306,10 @@ /* return codes */ #define FP_OKAY 0 -#define FP_VAL (-1) -#define FP_MEM (-2) -#define FP_NOT_INF (-3) -#define FP_WOULDBLOCK (-4) +#define FP_VAL MP_VAL +#define FP_MEM MP_MEM +#define FP_NOT_INF MP_NOT_INF +#define FP_WOULDBLOCK MP_WOULDBLOCK /* equalities */ #define FP_LT (-1) /* less than */ @@ -378,6 +379,9 @@ while (0) #define WOLF_BIGINT_DEFINED #endif +#define mp_size_t int +#define mp_sign_t int + /* a FP type */ typedef struct fp_int { int used; @@ -776,9 +780,7 @@ int fp_sqr_comba64(fp_int *a, fp_int *b); #define MP_LT FP_LT /* less than */ #define MP_EQ FP_EQ /* equal to */ #define MP_GT FP_GT /* greater than */ -#define MP_VAL FP_VAL /* invalid */ -#define MP_MEM FP_MEM /* memory error */ -#define MP_NOT_INF FP_NOT_INF /* point not at infinity */ +#define MP_RANGE MP_NOT_INF #define MP_OKAY FP_OKAY /* ok result */ #define MP_NO FP_NO /* yes/no result */ #define MP_YES FP_YES /* yes/no result */ diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index 9dd2f75..1b437c1 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -1,6 +1,6 @@ /* types.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -34,6 +34,10 @@ decouple library dependencies with standard string, memory and so on. #include #include + #ifdef __APPLE__ + #include + #endif + #ifdef __cplusplus extern "C" { #endif @@ -108,6 +112,10 @@ decouple library dependencies with standard string, memory and so on. typedef const char* const wcchar; #endif + #ifndef WC_BITFIELD + #define WC_BITFIELD byte + #endif + #ifndef HAVE_ANONYMOUS_INLINE_AGGREGATES /* if a version is available, pivot on the version, otherwise guess it's * allowed, subject to override. @@ -158,16 +166,16 @@ decouple library dependencies with standard string, memory and so on. #elif !defined(__BCPLUSPLUS__) && !defined(__EMSCRIPTEN__) #if !defined(SIZEOF_LONG_LONG) && !defined(SIZEOF_LONG) #if (defined(__alpha__) || defined(__ia64__) || \ - defined(_ARCH_PPC64) || defined(__mips64) || \ + defined(_ARCH_PPC64) || defined(__ppc64__) || \ defined(__x86_64__) || defined(__s390x__ ) || \ ((defined(sun) || defined(__sun)) && \ (defined(LP64) || defined(_LP64))) || \ (defined(__riscv_xlen) && (__riscv_xlen == 64)) || \ - defined(__aarch64__) || \ + defined(__aarch64__) || defined(__mips64) || \ (defined(__DCC__) && (defined(__LP64) || defined(__LP64__)))) /* long should be 64bit */ #define SIZEOF_LONG 8 - #elif defined(__i386__) || defined(__CORTEX_M3__) + #elif defined(__i386__) || defined(__CORTEX_M3__) || defined(__ppc__) /* long long should be 64bit */ #define SIZEOF_LONG_LONG 8 #endif @@ -230,7 +238,7 @@ decouple library dependencies with standard string, memory and so on. defined(__x86_64__) || defined(_M_X64)) || \ defined(__aarch64__) || defined(__sparc64__) || defined(__s390x__ ) || \ (defined(__riscv_xlen) && (__riscv_xlen == 64)) || defined(_M_ARM64) || \ - defined(__aarch64__) || \ + defined(__aarch64__) || defined(__ppc64__) || \ (defined(__DCC__) && (defined(__LP64) || defined(__LP64__))) #define WC_64BIT_CPU #elif (defined(sun) || defined(__sun)) && \ @@ -420,10 +428,13 @@ typedef struct w64wrapper { #define FALL_THROUGH #endif - /* Micrium will use Visual Studio for compilation but not the Win32 API */ + /* For platforms where the target OS is not Windows, but compilation is + * done on Windows/Visual Studio, enable a way to disable USE_WINDOWS_API. + * Examples: Micrium, TenAsus INtime, uTasker, FreeRTOS simulator */ #if defined(_WIN32) && !defined(MICRIUM) && !defined(FREERTOS) && \ !defined(FREERTOS_TCP) && !defined(EBSNET) && \ - !defined(WOLFSSL_UTASKER) && !defined(INTIME_RTOS) + !defined(WOLFSSL_UTASKER) && !defined(INTIME_RTOS) && \ + !defined(WOLFSSL_NOT_WINDOWS_API) #define USE_WINDOWS_API #endif @@ -437,7 +448,13 @@ typedef struct w64wrapper { /* idea to add global alloc override by Moises Guimaraes */ /* default to libc stuff */ /* XREALLOC is used once in normal math lib, not in fast math lib */ - /* XFREE on some embedded systems doesn't like free(0) so test */ + /* XFREE on some embedded systems doesn't like free(0) so test for NULL + * explicitly. + * + * For example: + * #define XFREE(p, h, t) \ + * {void* xp = (p); if (xp != NULL) free(xp, h, t);} + */ #if defined(HAVE_IO_POOL) WOLFSSL_API void* XMALLOC(size_t n, void* heap, int type); WOLFSSL_API void* XREALLOC(void *p, size_t n, void* heap, int type); @@ -498,25 +515,33 @@ typedef struct w64wrapper { #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK #define XFREE(p, h, t) m2mb_os_free(xp) #else - #define XFREE(p, h, t) {void* xp = (p); if (xp) m2mb_os_free(xp);} + #define XFREE(p, h, t) do { void* xp = (p); if (xp) m2mb_os_free(xp); } while (0) #endif #define XREALLOC(p, n, h, t) m2mb_os_realloc((p), (n)) #elif defined(NO_WOLFSSL_MEMORY) #ifdef WOLFSSL_NO_MALLOC /* this platform does not support heap use */ + #ifdef WOLFSSL_SMALL_STACK + #error WOLFSSL_SMALL_STACK requires a heap implementation. + #endif + #ifndef WC_NO_CONSTRUCTORS + #define WC_NO_CONSTRUCTORS + #endif #ifdef WOLFSSL_MALLOC_CHECK + #ifndef NO_STDIO_FILESYSTEM #include + #endif static inline void* malloc_check(size_t sz) { fprintf(stderr, "wolfSSL_malloc failed"); return NULL; }; #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc_check((s))) - #define XFREE(p, h, t) (void)(h); (void)(t) + #define XFREE(p, h, t) do { (void)(h); (void)(t); } while (0) #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), NULL) #else #define XMALLOC(s, h, t) ((void)(s), (void)(h), (void)(t), NULL) - #define XFREE(p, h, t) (void)(p); (void)(h); (void)(t) + #define XFREE(p, h, t) do { (void)(p); (void)(h); (void)(t); } while(0) #define XREALLOC(p, n, h, t) ((void)(p), (void)(n), (void)(h), (void)(t), NULL) #endif #else @@ -524,9 +549,9 @@ typedef struct w64wrapper { #include #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc((size_t)(s))) #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) ((void)(h), (void)(t), free(p)) + #define XFREE(p, h, t) do { (void)(h); (void)(t); free(p); } while (0) #else - #define XFREE(p, h, t) {void* xp = (p); (void)(h); if (xp) free(xp);} + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); if (xp) free(xp); } while (0) #endif #define XREALLOC(p, n, h, t) \ ((void)(h), (void)(t), realloc((p), (size_t)(n))) @@ -550,7 +575,7 @@ typedef struct w64wrapper { #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK #define XFREE(p, h, t) wolfSSL_Free(xp, h, t, __func__, __LINE__) #else - #define XFREE(p, h, t) {void* xp = (p); if (xp) wolfSSL_Free(xp, h, t, __func__, __LINE__);} + #define XFREE(p, h, t) do { void* xp = (p); if (xp) wolfSSL_Free(xp, h, t, __func__, __LINE__); } while (0) #endif #define XREALLOC(p, n, h, t) wolfSSL_Realloc((p), (n), (h), (t), __func__, __LINE__) #else @@ -558,7 +583,7 @@ typedef struct w64wrapper { #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK #define XFREE(p, h, t) wolfSSL_Free(xp, h, t) #else - #define XFREE(p, h, t) {void* xp = (p); if (xp) wolfSSL_Free(xp, h, t);} + #define XFREE(p, h, t) do { void* xp = (p); if (xp) wolfSSL_Free(xp, h, t); } while (0) #endif #define XREALLOC(p, n, h, t) wolfSSL_Realloc((p), (n), (h), (t)) #endif /* WOLFSSL_DEBUG_MEMORY */ @@ -570,23 +595,29 @@ typedef struct w64wrapper { #ifdef WOLFSSL_DEBUG_MEMORY #define XMALLOC(s, h, t) ((void)(h), (void)(t), wolfSSL_Malloc((s), __func__, __LINE__)) #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) ((void)(h), (void)(t), wolfSSL_Free(xp, __func__, __LINE__)) + #define XFREE(p, h, t) do { (void)(h); (void)(t); wolfSSL_Free(xp, __func__, __LINE__); } while (0) #else - #define XFREE(p, h, t) {void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp, __func__, __LINE__);} + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp, __func__, __LINE__); } while (0) #endif #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), wolfSSL_Realloc((p), (n), __func__, __LINE__)) #else #define XMALLOC(s, h, t) ((void)(h), (void)(t), wolfSSL_Malloc((s))) #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) ((void)(h), (void)(t), wolfSSL_Free(p)) + #define XFREE(p, h, t) do { (void)(h); (void)(t); wolfSSL_Free(p); } while (0) #else - #define XFREE(p, h, t) {void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp);} + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp); } while (0) #endif #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), wolfSSL_Realloc((p), (n))) #endif /* WOLFSSL_DEBUG_MEMORY */ #endif /* WOLFSSL_STATIC_MEMORY */ #endif + #if defined(WOLFSSL_SMALL_STACK) && defined(WC_NO_CONSTRUCTORS) + #error WOLFSSL_SMALL_STACK requires constructors. + #endif + + #include + /* declare/free variable handling for async and smallstack */ #ifndef WC_ALLOC_DO_ON_FAILURE #define WC_ALLOC_DO_ON_FAILURE() WC_DO_NOTHING @@ -711,10 +742,10 @@ typedef struct w64wrapper { #include #endif - #define XMEMCPY(d,s,l) memcpy((d),(s),(l)) - #define XMEMSET(b,c,l) memset((b),(c),(l)) - #define XMEMCMP(s1,s2,n) memcmp((s1),(s2),(n)) - #define XMEMMOVE(d,s,l) memmove((d),(s),(l)) + #define XMEMCPY(d,s,l) memcpy((d),(s),(l)) + #define XMEMSET(b,c,l) memset((b),(c),(l)) + #define XMEMCMP(s1,s2,n) memcmp((s1),(s2),(n)) + #define XMEMMOVE(d,s,l) memmove((d),(s),(l)) #define XSTRLEN(s1) strlen((s1)) #define XSTRNCPY(s1,s2,n) strncpy((s1),(s2),(n)) @@ -740,7 +771,6 @@ typedef struct w64wrapper { defined(WOLFSSL_ZEPHYR) || defined(MICROCHIP_PIC24) /* XC32 version < 1.0 does not support strcasecmp. */ #define USE_WOLF_STRCASECMP - #define XSTRCASECMP(s1,s2) wc_strcasecmp(s1,s2) #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) #define XSTRCASECMP(s1,s2) _stricmp((s1),(s2)) #else @@ -753,13 +783,16 @@ typedef struct w64wrapper { #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) \ || defined(WOLF_C89) #define USE_WOLF_STRCASECMP - #define XSTRCASECMP(s1,s2) wc_strcasecmp(s1, s2) #elif defined(WOLF_C89) #define XSTRCASECMP(s1,s2) strcmp((s1),(s2)) #else #define XSTRCASECMP(s1,s2) strcasecmp((s1),(s2)) #endif #endif + #ifdef USE_WOLF_STRCASECMP + #undef XSTRCASECMP + #define XSTRCASECMP(s1,s2) wc_strcasecmp((s1), (s2)) + #endif #endif /* !XSTRCASECMP */ #ifndef XSTRNCASECMP @@ -770,7 +803,6 @@ typedef struct w64wrapper { defined(WOLFSSL_ZEPHYR) || defined(MICROCHIP_PIC24) /* XC32 version < 1.0 does not support strncasecmp. */ #define USE_WOLF_STRNCASECMP - #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp((s1),(s2),(n)) #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) #define XSTRNCASECMP(s1,s2,n) _strnicmp((s1),(s2),(n)) #else @@ -783,13 +815,16 @@ typedef struct w64wrapper { #elif defined(WOLFSSL_CMSIS_RTOSv2) || defined(WOLFSSL_AZSPHERE) \ || defined(WOLF_C89) #define USE_WOLF_STRNCASECMP - #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp(s1, s2 ,n) #elif defined(WOLF_C89) #define XSTRNCASECMP(s1,s2,n) strncmp((s1),(s2),(n)) #else #define XSTRNCASECMP(s1,s2,n) strncasecmp((s1),(s2),(n)) #endif #endif + #ifdef USE_WOLF_STRNCASECMP + #undef XSTRNCASECMP + #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp((s1),(s2),(n)) + #endif #endif /* !XSTRNCASECMP */ /* snprintf is used in asn.c for GetTimeString, PKCS7 test, and when @@ -829,10 +864,16 @@ typedef struct w64wrapper { have stdio.h available, so it needs its own section. */ #define XSNPRINTF snprintf #elif defined(WOLF_C89) + #ifndef NO_STDIO_FILESYSTEM #include + #endif #define XSPRINTF sprintf + /* snprintf not available for C89, so remap using macro */ + #define XSNPRINTF(f, len, ...) sprintf(f, __VA_ARGS__) #else + #ifndef NO_STDIO_FILESYSTEM #include + #endif #define XSNPRINTF snprintf #endif #else @@ -873,7 +914,8 @@ typedef struct w64wrapper { #endif /* !XSNPRINTF */ #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_ALPN) || defined(WOLFSSL_SNIFFER) + defined(HAVE_ALPN) || defined(WOLFSSL_SNIFFER) || \ + defined(WOLFSSL_ASN_PARSE_KEYUSAGE) /* use only Thread Safe version of strtok */ #if defined(USE_WOLF_STRTOK) #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) @@ -917,6 +959,15 @@ typedef struct w64wrapper { WOLFSSL_API int wc_strncasecmp(const char *s1, const char *s2, size_t n); #endif + #if !defined(XSTRDUP) && !defined(USE_WOLF_STRDUP) + #define USE_WOLF_STRDUP + #endif + #ifdef USE_WOLF_STRDUP + WOLFSSL_LOCAL char* wc_strdup_ex(const char *src, int memType); + #define wc_strdup(src) wc_strdup_ex(src, DYNAMIC_TYPE_TMP_BUFFER) + #define XSTRDUP(src) wc_strdup(src) + #endif + #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) #ifndef XGETENV #ifdef NO_GETENV @@ -1061,6 +1112,8 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SM4_BUFFER = 99, DYNAMIC_TYPE_DEBUG_TAG = 100, DYNAMIC_TYPE_LMS = 101, + DYNAMIC_TYPE_BIO = 102, + DYNAMIC_TYPE_X509_ACERT = 103, DYNAMIC_TYPE_SNIFFER_SERVER = 1000, DYNAMIC_TYPE_SNIFFER_SESSION = 1001, DYNAMIC_TYPE_SNIFFER_PB = 1002, @@ -1069,7 +1122,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, DYNAMIC_TYPE_SNIFFER_KEY = 1006, DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE = 1007, - DYNAMIC_TYPE_AES_EAX = 1008, + DYNAMIC_TYPE_AES_EAX = 1008 }; /* max error buffer string size */ @@ -1231,6 +1284,9 @@ typedef struct w64wrapper { #undef _WC_PK_TYPE_MAX #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_SIG_CHECK_PRIV_KEY #endif + WC_PK_TYPE_RSA_PKCS = 25, + WC_PK_TYPE_RSA_PSS = 26, + WC_PK_TYPE_RSA_OAEP = 27, WC_PK_TYPE_MAX = _WC_PK_TYPE_MAX }; @@ -1458,18 +1514,19 @@ typedef struct w64wrapper { typedef size_t THREAD_TYPE; #define WOLFSSL_THREAD #elif defined(WOLFSSL_PTHREADS) - #ifndef __MACH__ - #include - typedef struct COND_TYPE { - pthread_mutex_t mutex; - pthread_cond_t cond; - } COND_TYPE; - #else + #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 \ + && !defined(__ppc__) #include typedef struct COND_TYPE { wolfSSL_Mutex mutex; dispatch_semaphore_t cond; } COND_TYPE; + #else + #include + typedef struct COND_TYPE { + pthread_mutex_t mutex; + pthread_cond_t cond; + } COND_TYPE; #endif typedef void* THREAD_RETURN; typedef pthread_t THREAD_TYPE; @@ -1652,14 +1709,63 @@ typedef struct w64wrapper { #define PRAGMA_DIAG_POP /* null expansion */ #endif + #define WC_CPP_CAT_(a, b) a ## b + #define WC_CPP_CAT(a, b) WC_CPP_CAT_(a, b) + #if defined(WC_NO_STATIC_ASSERT) + #define wc_static_assert(expr) struct wc_static_assert_dummy_struct + #define wc_static_assert2(expr, msg) wc_static_assert(expr) + #elif !defined(wc_static_assert) + #if (defined(__cplusplus) && (__cplusplus >= 201703L)) || \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)) || \ + (defined(_MSVC_LANG) && (_MSVC_LANG >= 201103L)) + /* native variadic static_assert() */ + #define wc_static_assert static_assert + #ifndef wc_static_assert2 + #define wc_static_assert2 static_assert + #endif + #elif defined(_MSC_VER) && (__STDC_VERSION__ >= 201112L) + /* native 2-argument static_assert() */ + #define wc_static_assert(expr) static_assert(expr, #expr) + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) static_assert(expr, msg) + #endif + #elif !defined(__cplusplus) && \ + !defined(__STRICT_ANSI__) && \ + !defined(WOLF_C89) && \ + defined(__STDC_VERSION__) && \ + (__STDC_VERSION__ >= 201112L) && \ + ((defined(__GNUC__) && \ + (__GNUC__ >= 5)) || \ + defined(__clang__)) + /* native 2-argument _Static_assert() */ + #define wc_static_assert(expr) _Static_assert(expr, #expr) + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) _Static_assert(expr, msg) + #endif + #else + /* C89-compatible fallback */ + #define wc_static_assert(expr) \ + struct WC_CPP_CAT(wc_static_assert_dummy_struct_L, __LINE__) { \ + char t[(expr) ? 1 : -1]; \ + } + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) wc_static_assert(expr) + #endif + #endif + #elif !defined(wc_static_assert2) + #define wc_static_assert2(expr, msg) wc_static_assert(expr) + #endif + #ifndef SAVE_VECTOR_REGISTERS #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING #endif #ifndef SAVE_VECTOR_REGISTERS2 #define SAVE_VECTOR_REGISTERS2() 0 + #define SAVE_VECTOR_REGISTERS2_DOES_NOTHING #endif #ifndef CAN_SAVE_VECTOR_REGISTERS #define CAN_SAVE_VECTOR_REGISTERS() 1 + #define CAN_SAVE_VECTOR_REGISTERS_ALWAYS_TRUE #endif #ifndef WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL #define WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL(x) WC_DO_NOTHING diff --git a/src/wolfssl/wolfcrypt/visibility.h b/src/wolfssl/wolfcrypt/visibility.h index 6ee10df..30a19e2 100644 --- a/src/wolfssl/wolfcrypt/visibility.h +++ b/src/wolfssl/wolfcrypt/visibility.h @@ -1,6 +1,6 @@ /* visibility.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wc_encrypt.h b/src/wolfssl/wolfcrypt/wc_encrypt.h index b6591ff..e3cf9ad 100644 --- a/src/wolfssl/wolfcrypt/wc_encrypt.h +++ b/src/wolfssl/wolfcrypt/wc_encrypt.h @@ -1,6 +1,6 @@ /* wc_encrypt.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wc_kyber.h b/src/wolfssl/wolfcrypt/wc_kyber.h index 5491285..79a03cb 100644 --- a/src/wolfssl/wolfcrypt/wc_kyber.h +++ b/src/wolfssl/wolfcrypt/wc_kyber.h @@ -103,6 +103,9 @@ enum { +/* The data type of the hash function. */ +#define KYBER_HASH_T wc_Sha3 + /* The data type of the pseudo-random function. */ #define KYBER_PRF_T wc_Shake @@ -119,6 +122,8 @@ struct KyberKey { /* Flags indicating what is stored in the key. */ int flags; + /* A pseudo-random function object. */ + KYBER_HASH_T hash; /* A pseudo-random function object. */ KYBER_PRF_T prf; @@ -158,10 +163,23 @@ WOLFSSL_LOCAL int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, sword16* vec2, sword16* poly, byte* seed); -#ifdef USE_INTEL_SPEEDUP +#if defined(USE_INTEL_SPEEDUP) || \ + (defined(WOLFSSL_ARMASM) && defined(__aarch64__)) WOLFSSL_LOCAL int kyber_kdf(byte* seed, int seedLen, byte* out, int outLen); #endif +WOLFSSL_LOCAL +void kyber_hash_init(KYBER_HASH_T* hash); +WOLFSSL_LOCAL +int kyber_hash_new(KYBER_HASH_T* hash, void* heap, int devId); +WOLFSSL_LOCAL +void kyber_hash_free(KYBER_HASH_T* hash); +WOLFSSL_LOCAL +int kyber_hash256(wc_Sha3* hash, const byte* data, word32 dataLen, byte* out); +WOLFSSL_LOCAL +int kyber_hash512(wc_Sha3* hash, const byte* data1, word32 data1Len, + const byte* data2, word32 data2Len, byte* out); + WOLFSSL_LOCAL void kyber_prf_init(KYBER_PRF_T* prf); WOLFSSL_LOCAL @@ -271,6 +289,59 @@ void kyber_decompress_5_avx2(sword16* p, const byte* r); WOLFSSL_LOCAL int kyber_cmp_avx2(const byte* a, const byte* b, int sz); +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) +WOLFSSL_LOCAL void kyber_ntt(sword16* r); +WOLFSSL_LOCAL void kyber_invntt(sword16* r); +WOLFSSL_LOCAL void kyber_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_add_reduce(sword16* r, const sword16* a); +WOLFSSL_LOCAL void kyber_add3_reduce(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_rsub_reduce(sword16* r, const sword16* a); +WOLFSSL_LOCAL void kyber_to_mont(sword16* p); +WOLFSSL_LOCAL void kyber_sha3_blocksx3_neon(word64* state); +WOLFSSL_LOCAL void kyber_shake128_blocksx3_seed_neon(word64* state, byte* seed); +WOLFSSL_LOCAL void kyber_shake256_blocksx3_seed_neon(word64* state, byte* seed); +WOLFSSL_LOCAL unsigned int kyber_rej_uniform_neon(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); +WOLFSSL_LOCAL int kyber_cmp_neon(const byte* a, const byte* b, int sz); +WOLFSSL_LOCAL void kyber_csubq_neon(sword16* p); +WOLFSSL_LOCAL void kyber_from_msg_neon(sword16* p, const byte* msg); +WOLFSSL_LOCAL void kyber_to_msg_neon(byte* msg, sword16* p); +#elif defined(WOLFSSL_ARMASM_THUMB2) && defined(WOLFSSL_ARMASM) +#define kyber_ntt kyber_thumb2_ntt +#define kyber_invntt kyber_thumb2_invntt +#define kyber_basemul_mont kyber_thumb2_basemul_mont +#define kyber_basemul_mont_add kyber_thumb2_basemul_mont_add +#define kyber_rej_uniform_c kyber_thumb2_rej_uniform + +WOLFSSL_LOCAL void kyber_thumb2_ntt(sword16* r); +WOLFSSL_LOCAL void kyber_thumb2_invntt(sword16* r); +WOLFSSL_LOCAL void kyber_thumb2_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_thumb2_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_thumb2_csubq(sword16* p); +WOLFSSL_LOCAL unsigned int kyber_thumb2_rej_uniform(sword16* p, + unsigned int len, const byte* r, unsigned int rLen); +#elif defined(WOLFSSL_ARMASM) +#define kyber_ntt kyber_arm32_ntt +#define kyber_invntt kyber_arm32_invntt +#define kyber_basemul_mont kyber_arm32_basemul_mont +#define kyber_basemul_mont_add kyber_arm32_basemul_mont_add +#define kyber_rej_uniform_c kyber_arm32_rej_uniform + +WOLFSSL_LOCAL void kyber_arm32_ntt(sword16* r); +WOLFSSL_LOCAL void kyber_arm32_invntt(sword16* r); +WOLFSSL_LOCAL void kyber_arm32_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_arm32_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void kyber_arm32_csubq(sword16* p); +WOLFSSL_LOCAL unsigned int kyber_arm32_rej_uniform(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); #endif #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index 6f90eaa..0f31696 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -134,6 +134,9 @@ /* Length of numeric types when encoding. */ #define LMS_TYPE_LEN 4 +/* Size of digest output when truncatint SHA-256 to 192 bits. */ +#define WC_SHA256_192_DIGEST_SIZE 24 + /* Maximum size of a node hash. */ #define LMS_MAX_NODE_LEN WC_SHA256_DIGEST_SIZE /* Maximum size of SEED (produced by hash). */ @@ -142,8 +145,6 @@ * Value of P when N=32 and W=1. */ #define LMS_MAX_P 265 -/* Length of SEED and I in bytes. */ -#define LMS_SEED_I_LEN (LMS_SEED_LEN + LMS_I_LEN) #ifndef WOLFSSL_LMS_ROOT_LEVELS @@ -192,33 +193,32 @@ (HSS_COMPRESS_PARAM_SET_LEN * HSS_MAX_LEVELS) /* Private key length for one level. */ -#define LMS_PRIV_LEN \ - (LMS_Q_LEN + LMS_SEED_LEN + LMS_I_LEN) +#define LMS_PRIV_LEN(hLen) \ + (LMS_Q_LEN + (hLen) + LMS_I_LEN) /* Public key length in signature. */ -#define LMS_PUBKEY_LEN \ - (LMS_TYPE_LEN + LMS_TYPE_LEN + LMS_I_LEN + LMS_MAX_NODE_LEN) +#define LMS_PUBKEY_LEN(hLen) \ + (LMS_TYPE_LEN + LMS_TYPE_LEN + LMS_I_LEN + (hLen)) /* LMS signature data length. */ -#define LMS_SIG_LEN(h, p) \ - (LMS_Q_LEN + LMS_TYPE_LEN + LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN + \ - LMS_TYPE_LEN + (h) * LMS_MAX_NODE_LEN) +#define LMS_SIG_LEN(h, p, hLen) \ + (LMS_Q_LEN + LMS_TYPE_LEN + (hLen) + (p) * (hLen) + LMS_TYPE_LEN + \ + (h) * (hLen)) /* Length of public key. */ -#define HSS_PUBLIC_KEY_LEN (LMS_L_LEN + LMS_PUBKEY_LEN) +#define HSS_PUBLIC_KEY_LEN(hLen) (LMS_L_LEN + LMS_PUBKEY_LEN(hLen)) /* Length of private key. */ -#define HSS_PRIVATE_KEY_LEN \ - (HSS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN + LMS_SEED_LEN + LMS_I_LEN) +#define HSS_PRIVATE_KEY_LEN(hLen) \ + (HSS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN + (hLen) + LMS_I_LEN) /* Maximum public key length - length is constant for all parameters. */ -#define HSS_MAX_PRIVATE_KEY_LEN HSS_PRIVATE_KEY_LEN +#define HSS_MAX_PRIVATE_KEY_LEN HSS_PRIVATE_KEY_LEN(LMS_MAX_NODE_LEN) /* Maximum private key length - length is constant for all parameters. */ -#define HSS_MAX_PUBLIC_KEY_LEN HSS_PUBLIC_KEY_LEN +#define HSS_MAX_PUBLIC_KEY_LEN HSS_PUBLIC_KEY_LEN(LMS_MAX_NODE_LEN) /* Maximum signature length. */ #define HSS_MAX_SIG_LEN \ (LMS_TYPE_LEN + \ LMS_MAX_LEVELS * (LMS_Q_LEN + LMS_TYPE_LEN + LMS_TYPE_LEN + \ LMS_MAX_NODE_LEN * (1 + LMS_MAX_P + LMS_MAX_HEIGHT)) + \ - (LMS_MAX_LEVELS - 1) * LMS_PUBKEY_LEN \ - ) + (LMS_MAX_LEVELS - 1) * LMS_PUBKEY_LEN(LMS_MAX_NODE_LEN)) /* Maximum buffer length required for use when hashing. */ #define LMS_MAX_BUFFER_LEN \ @@ -229,20 +229,20 @@ * * HSSPrivKey.priv */ -#define LMS_PRIV_KEY_LEN(l) \ - ((l) * LMS_PRIV_LEN) +#define LMS_PRIV_KEY_LEN(l, hLen) \ + ((l) * LMS_PRIV_LEN(hLen)) /* Stack of nodes. */ -#define LMS_STACK_CACHE_LEN(h) \ - (((h) + 1) * LMS_MAX_NODE_LEN) +#define LMS_STACK_CACHE_LEN(h, hLen) \ + (((h) + 1) * (hLen)) /* Root cache length. */ -#define LMS_ROOT_CACHE_LEN(rl) \ - (((1 << (rl)) - 1) * LMS_MAX_NODE_LEN) +#define LMS_ROOT_CACHE_LEN(rl, hLen) \ + (((1 << (rl)) - 1) * (hLen)) /* Leaf cache length. */ -#define LMS_LEAF_CACHE_LEN(cb) \ - ((1 << (cb)) * LMS_MAX_NODE_LEN) +#define LMS_LEAF_CACHE_LEN(cb, hLen) \ + ((1 << (cb)) * (hLen)) /* Length of LMS private key state. * @@ -252,75 +252,103 @@ * stack.stack + stack.offset + * cache.leaf + cache.index + cache.offset */ -#define LMS_PRIV_STATE_LEN(h, rl, cb) \ - (((h) * LMS_MAX_NODE_LEN) + \ - LMS_STACK_CACHE_LEN(h) + 4 + \ - LMS_ROOT_CACHE_LEN(rl) + \ - LMS_LEAF_CACHE_LEN(cb) + 4 + 4) +#define LMS_PRIV_STATE_LEN(h, rl, cb, hLen) \ + (((h) * (hLen)) + \ + LMS_STACK_CACHE_LEN(h, hLen) + 4 + \ + LMS_ROOT_CACHE_LEN(rl, hLen) + \ + LMS_LEAF_CACHE_LEN(cb, hLen) + 4 + 4) #ifndef WOLFSSL_WC_LMS_SMALL /* Private key data state for all levels. */ - #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) \ - ((l) * LMS_PRIV_STATE_LEN(h, rl, cb)) + #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb, hLen) \ + ((l) * LMS_PRIV_STATE_LEN(h, rl, cb, hLen)) #else /* Private key data state for all levels. */ - #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) 0 + #define LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb, hLen) 0 #endif #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING /* Extra private key data for smoothing. */ - #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) \ - (LMS_PRIV_KEY_LEN(l) + \ - ((l) - 1) * LMS_PRIV_STATE_LEN(h, rl, cb)) + #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb, hLen) \ + (LMS_PRIV_KEY_LEN(l, hLen) + \ + ((l) - 1) * LMS_PRIV_STATE_LEN(h, rl, cb, hLen)) #else /* Extra private key data for smoothing. */ - #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) 0 + #define LMS_PRIV_SMOOTH_LEN(l, h, rl, cb, hLen) 0 #endif #ifndef WOLFSSL_LMS_NO_SIG_CACHE - #define LMS_PRIV_Y_TREE_LEN(p) \ - (LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN) + #define LMS_PRIV_Y_TREE_LEN(p, hLen) \ + ((hLen) + (p) * (hLen)) /* Length of the y data cached in private key data. */ - #define LMS_PRIV_Y_LEN(l, p) \ - (((l) - 1) * (LMS_MAX_NODE_LEN + (p) * LMS_MAX_NODE_LEN)) + #define LMS_PRIV_Y_LEN(l, p, hLen) \ + (((l) - 1) * ((hLen) + (p) * (hLen))) #else /* Length of the y data cached in private key data. */ - #define LMS_PRIV_Y_LEN(l, p) 0 + #define LMS_PRIV_Y_LEN(l, p, hLen) 0 #endif #ifndef WOLFSSL_WC_LMS_SMALL /* Length of private key data. */ -#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb) \ - (LMS_PRIV_KEY_LEN(l) + \ - LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb) + \ - LMS_PRIV_SMOOTH_LEN(l, h, rl, cb) + \ - LMS_PRIV_Y_LEN(l, p)) +#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb, hLen) \ + (LMS_PRIV_KEY_LEN(l, hLen) + \ + LMS_PRIV_STATE_ALL_LEN(l, h, rl, cb, hLen) + \ + LMS_PRIV_SMOOTH_LEN(l, h, rl, cb, hLen) + \ + LMS_PRIV_Y_LEN(l, p, hLen)) #else -#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb) \ - LMS_PRIV_KEY_LEN(l) +#define LMS_PRIV_DATA_LEN(l, h, p, rl, cb, hLen) \ + LMS_PRIV_KEY_LEN(l, hLen) #endif +/* Indicates using SHA-256 for hashing. */ +#define LMS_SHA256 0x00 +/* Indicates using SHA-256/192 for hashing. */ +#define LMS_SHA256_192 0x10 +/* Mask to get hashing algorithm from type. */ +#define LMS_HASH_MASK 0xf0 +/* Mask to get height or Winternitz width from type. */ +#define LMS_H_W_MASK 0x0f /* LMS Parameters. */ /* SHA-256 hash, 32-bytes of hash used, tree height of 5. */ -#define LMS_SHA256_M32_H5 5 +#define LMS_SHA256_M32_H5 0x05 +/* SHA-256 hash, 32-bytes of hash used, tree height of 10. */ +#define LMS_SHA256_M32_H10 0x06 +/* SHA-256 hash, 32-bytes of hash used, tree height of 15. */ +#define LMS_SHA256_M32_H15 0x07 +/* SHA-256 hash, 32-bytes of hash used, tree height of 20. */ +#define LMS_SHA256_M32_H20 0x08 +/* SHA-256 hash, 32-bytes of hash used, tree height of 25. */ +#define LMS_SHA256_M32_H25 0x09 + +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 1 bit. */ +#define LMOTS_SHA256_N32_W1 0x01 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 2 bits. */ +#define LMOTS_SHA256_N32_W2 0x02 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 4 bits. */ +#define LMOTS_SHA256_N32_W4 0x03 +/* SHA-256 hash, 32-bytes of hash used, Winternitz width of 8 bits. */ +#define LMOTS_SHA256_N32_W8 0x04 + +/* SHA-256 hash, 32-bytes of hash used, tree height of 5. */ +#define LMS_SHA256_M24_H5 (0x05 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 10. */ -#define LMS_SHA256_M32_H10 6 +#define LMS_SHA256_M24_H10 (0x06 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 15. */ -#define LMS_SHA256_M32_H15 7 +#define LMS_SHA256_M24_H15 (0x07 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 20. */ -#define LMS_SHA256_M32_H20 8 +#define LMS_SHA256_M24_H20 (0x08 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 25. */ -#define LMS_SHA256_M32_H25 9 +#define LMS_SHA256_M24_H25 (0x09 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 1 bit. */ -#define LMOTS_SHA256_N32_W1 1 +#define LMOTS_SHA256_N24_W1 (0x01 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 2 bits. */ -#define LMOTS_SHA256_N32_W2 2 +#define LMOTS_SHA256_N24_W2 (0x02 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 4 bits. */ -#define LMOTS_SHA256_N32_W4 3 +#define LMOTS_SHA256_N24_W4 (0x03 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 8 bits. */ -#define LMOTS_SHA256_N32_W8 4 +#define LMOTS_SHA256_N24_W8 (0x04 | LMS_SHA256_192) typedef struct LmsParams { /* Number of tree levels. */ @@ -339,6 +367,8 @@ typedef struct LmsParams { word16 lmOtsType; /* Length of LM-OTS signature. */ word16 sig_len; + /* Length of seed. */ + word16 hash_len; #ifndef WOLFSSL_WC_LMS_SMALL /* Number of root levels of interior nodes to store. */ word8 rootLevels; @@ -426,10 +456,10 @@ typedef struct HssPrivKey { struct LmsKey { /* Public key. */ - ALIGN16 byte pub[HSS_PUBLIC_KEY_LEN]; + ALIGN16 byte pub[HSS_PUBLIC_KEY_LEN(LMS_MAX_NODE_LEN)]; #ifndef WOLFSSL_LMS_VERIFY_ONLY /* Encoded private key. */ - ALIGN16 byte priv_raw[HSS_PRIVATE_KEY_LEN]; + ALIGN16 byte priv_raw[HSS_MAX_PRIVATE_KEY_LEN]; /* Packed private key data. */ byte* priv_data; diff --git a/src/wolfssl/wolfcrypt/wc_pkcs11.h b/src/wolfssl/wolfcrypt/wc_pkcs11.h index 85717c2..0b8942b 100644 --- a/src/wolfssl/wolfcrypt/wc_pkcs11.h +++ b/src/wolfssl/wolfcrypt/wc_pkcs11.h @@ -1,6 +1,6 @@ /* wc_pkcs11.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -97,6 +97,10 @@ WOLFSSL_API int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, WOLFSSL_API int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx); +WOLFSSL_LOCAL int wc_hash2sz(int); +WOLFSSL_LOCAL CK_MECHANISM_TYPE wc_hash2ckm(int); +WOLFSSL_LOCAL CK_MECHANISM_TYPE wc_mgf2ckm(int); + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/wc_port.h b/src/wolfssl/wolfcrypt/wc_port.h index 23110b9..6dc7d2c 100644 --- a/src/wolfssl/wolfcrypt/wc_port.h +++ b/src/wolfssl/wolfcrypt/wc_port.h @@ -1,6 +1,6 @@ /* wc_port.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -54,12 +54,18 @@ #endif #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include +#endif + #ifdef WOLFSSL_LINUXKM #include "../../linuxkm/linuxkm_wc_port.h" #endif /* WOLFSSL_LINUXKM */ /* THREADING/MUTEX SECTION */ -#ifdef USE_WINDOWS_API +#if defined(SINGLE_THREADED) && defined(NO_FILESYSTEM) + /* No system headers required for build. */ +#elif defined(USE_WINDOWS_API) #if defined(WOLFSSL_PTHREADS) #include #endif @@ -147,8 +153,8 @@ #elif defined(WOLFSSL_ZEPHYR) #include #ifndef SINGLE_THREADED - #ifndef CONFIG_PTHREAD_IPC - #error "Need CONFIG_PTHREAD_IPC for threading" + #if !defined(CONFIG_PTHREAD_IPC) && !defined(CONFIG_POSIX_THREADS) + #error "Threading needs CONFIG_PTHREAD_IPC / CONFIG_POSIX_THREADS" #endif #if KERNEL_VERSION_NUMBER >= 0x30100 #include @@ -353,11 +359,20 @@ #endif /* WOLFSSL_NO_ATOMICS */ #ifdef WOLFSSL_ATOMIC_OPS - WOLFSSL_LOCAL void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i); + WOLFSSL_API void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i); /* Fetch* functions return the value of the counter immediately preceding * the effects of the function. */ - WOLFSSL_LOCAL int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i); - WOLFSSL_LOCAL int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i); + WOLFSSL_API int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i); + WOLFSSL_API int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i); +#else + /* Code using these fallback macros needs to arrange its own fallback for + * wolfSSL_Atomic_Int, which is never defined if + * !defined(WOLFSSL_ATOMIC_OPS). This forces local awareness of + * thread-unsafe semantics. + */ + #define wolfSSL_Atomic_Int_Init(c, i) (*(c) = (i)) + #define wolfSSL_Atomic_Int_FetchAdd(c, i) (*(c) += (i), *(c) - (i)) + #define wolfSSL_Atomic_Int_FetchSub(c, i) (*(c) -= (i), *(c) + (i)) #endif /* Reference counting. */ @@ -372,27 +387,7 @@ typedef struct wolfSSL_Ref { #endif } wolfSSL_Ref; -#ifdef SINGLE_THREADED - -#define wolfSSL_RefInit(ref, err) \ - do { \ - (ref)->count = 1; \ - *(err) = 0; \ - } while(0) -#define wolfSSL_RefFree(ref) WC_DO_NOTHING - #define wolfSSL_RefInc(ref, err) \ - do { \ - (ref)->count++; \ - *(err) = 0; \ - } while(0) -#define wolfSSL_RefDec(ref, isZero, err) \ - do { \ - (ref)->count--; \ - *(isZero) = ((ref)->count == 0); \ - *(err) = 0; \ - } while(0) - -#elif defined(WOLFSSL_ATOMIC_OPS) +#if defined(SINGLE_THREADED) || defined(WOLFSSL_ATOMIC_OPS) #define wolfSSL_RefInit(ref, err) \ do { \ @@ -427,7 +422,8 @@ WOLFSSL_LOCAL void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err); /* Enable crypt HW mutex for Freescale MMCAU, PIC32MZ or STM32 */ #if defined(FREESCALE_MMCAU) || defined(WOLFSSL_MICROCHIP_PIC32MZ) || \ - defined(STM32_CRYPTO) || defined(STM32_HASH) || defined(STM32_RNG) + defined(STM32_CRYPTO) || defined(STM32_HASH) || defined(STM32_RNG) || \ + defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) #ifndef WOLFSSL_CRYPT_HW_MUTEX #define WOLFSSL_CRYPT_HW_MUTEX 1 #endif @@ -442,9 +438,9 @@ WOLFSSL_LOCAL void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err); however it's recommended to call this directly on Hw init to avoid possible race condition where two calls to wolfSSL_CryptHwMutexLock are made at the same time. */ - int wolfSSL_CryptHwMutexInit(void); - int wolfSSL_CryptHwMutexLock(void); - int wolfSSL_CryptHwMutexUnLock(void); + WOLFSSL_LOCAL int wolfSSL_CryptHwMutexInit(void); + WOLFSSL_LOCAL int wolfSSL_CryptHwMutexLock(void); + WOLFSSL_LOCAL int wolfSSL_CryptHwMutexUnLock(void); #else /* Define stubs, since HW mutex is disabled */ #define wolfSSL_CryptHwMutexInit() 0 /* Success */ @@ -452,6 +448,74 @@ WOLFSSL_LOCAL void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err); #define wolfSSL_CryptHwMutexUnLock() (void)0 /* Success */ #endif /* WOLFSSL_CRYPT_HW_MUTEX */ +#if defined(WOLFSSL_ALGO_HW_MUTEX) && (defined(NO_RNG_MUTEX) && \ + defined(NO_AES_MUTEX) && defined(NO_HASH_MUTEX) && defined(NO_PK_MUTEX)) + #error WOLFSSL_ALGO_HW_MUTEX does not support having all mutexes off +#endif +/* To support HW that can do different Crypto in parallel */ +#if WOLFSSL_CRYPT_HW_MUTEX && defined(WOLFSSL_ALGO_HW_MUTEX) + typedef enum { + #ifndef NO_RNG_MUTEX + rng_mutex, + #endif + #ifndef NO_AES_MUTEX + aes_mutex, + #endif + #ifndef NO_HASH_MUTEX + hash_mutex, + #endif + #ifndef NO_PK_MUTEX + pk_mutex, + #endif + } hw_mutex_algo; +#endif + +/* If algo mutex is off, or WOLFSSL_ALGO_HW_MUTEX is not define, default */ +/* to using the generic wolfSSL_CryptHwMutex */ +#if (!defined(NO_RNG_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX)) && \ + WOLFSSL_CRYPT_HW_MUTEX + WOLFSSL_LOCAL int wolfSSL_HwRngMutexInit(void); + WOLFSSL_LOCAL int wolfSSL_HwRngMutexLock(void); + WOLFSSL_LOCAL int wolfSSL_HwRngMutexUnLock(void); +#else + #define wolfSSL_HwRngMutexInit wolfSSL_CryptHwMutexInit + #define wolfSSL_HwRngMutexLock wolfSSL_CryptHwMutexLock + #define wolfSSL_HwRngMutexUnLock wolfSSL_CryptHwMutexUnLock +#endif /* !defined(NO_RNG_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX) */ + +#if (!defined(NO_AES_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX)) && \ + WOLFSSL_CRYPT_HW_MUTEX + WOLFSSL_LOCAL int wolfSSL_HwAesMutexInit(void); + WOLFSSL_LOCAL int wolfSSL_HwAesMutexLock(void); + WOLFSSL_LOCAL int wolfSSL_HwAesMutexUnLock(void); +#else + #define wolfSSL_HwAesMutexInit wolfSSL_CryptHwMutexInit + #define wolfSSL_HwAesMutexLock wolfSSL_CryptHwMutexLock + #define wolfSSL_HwAesMutexUnLock wolfSSL_CryptHwMutexUnLock +#endif /* !defined(NO_AES_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX) */ + +#if (!defined(NO_HASH_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX)) && \ + WOLFSSL_CRYPT_HW_MUTEX + WOLFSSL_LOCAL int wolfSSL_HwHashMutexInit(void); + WOLFSSL_LOCAL int wolfSSL_HwHashMutexLock(void); + WOLFSSL_LOCAL int wolfSSL_HwHashMutexUnLock(void); +#else + #define wolfSSL_HwHashMutexInit wolfSSL_CryptHwMutexInit + #define wolfSSL_HwHashMutexLock wolfSSL_CryptHwMutexLock + #define wolfSSL_HwHashMutexUnLock wolfSSL_CryptHwMutexUnLock +#endif /* !defined(NO_HASH_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX) */ + +#if (!defined(NO_PK_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX)) && \ + WOLFSSL_CRYPT_HW_MUTEX + WOLFSSL_LOCAL int wolfSSL_HwPkMutexInit(void); + WOLFSSL_LOCAL int wolfSSL_HwPkMutexLock(void); + WOLFSSL_LOCAL int wolfSSL_HwPkMutexUnLock(void); +#else + #define wolfSSL_HwPkMutexInit wolfSSL_CryptHwMutexInit + #define wolfSSL_HwPkMutexLock wolfSSL_CryptHwMutexLock + #define wolfSSL_HwPkMutexUnLock wolfSSL_CryptHwMutexUnLock +#endif /* !defined(NO_PK_MUTEX) && defined(WOLFSSL_ALGO_HW_MUTEX) */ + /* Mutex functions */ WOLFSSL_API int wc_InitMutex(wolfSSL_Mutex* m); WOLFSSL_API wolfSSL_Mutex* wc_InitAndAllocMutex(void); @@ -859,6 +923,25 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XSPRINTF sprintf #endif +#ifdef USE_WINDOWS_API + #ifndef SOCKET_T + #ifdef __MINGW64__ + typedef size_t SOCKET_T; + #else + typedef unsigned int SOCKET_T; + #endif + #endif + #ifndef SOCKET_INVALID + #define SOCKET_INVALID INVALID_SOCKET + #endif +#else + #ifndef SOCKET_T + typedef int SOCKET_T; + #endif + #ifndef SOCKET_INVALID + #define SOCKET_INVALID (-1) + #endif +#endif /* MIN/MAX MACRO SECTION */ /* Windows API defines its own min() macro. */ @@ -1085,7 +1168,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #endif /* PowerPC time_t is int */ - #ifdef __PPC__ + #if defined(__PPC__) || defined(__ppc__) #define TIME_T_NOT_64BIT #endif @@ -1243,19 +1326,28 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #endif #ifndef WOLFSSL_NO_FENCE - #if defined (__i386__) || defined(__x86_64__) + #ifdef XFENCE + /* use user-supplied XFENCE definition. */ + #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) + #include + #define XFENCE() atomic_thread_fence(memory_order_seq_cst) + #elif defined(__GNUC__) && (__GNUC__ >= 4) && (__GNUC__ < 5) + #define XFENCE() __sync_synchronize() + #elif (defined(__GNUC__) && (__GNUC__ >= 5)) || defined (__clang__) + #define XFENCE() __atomic_thread_fence(__ATOMIC_SEQ_CST) + #elif defined (__i386__) || defined(__x86_64__) #define XFENCE() XASM_VOLATILE("lfence") #elif (defined (__arm__) && (__ARM_ARCH > 6)) || defined(__aarch64__) #define XFENCE() XASM_VOLATILE("isb") #elif defined(__riscv) #define XFENCE() XASM_VOLATILE("fence") - #elif defined(__PPC__) + #elif defined(__PPC__) || defined(__POWERPC__) #define XFENCE() XASM_VOLATILE("isync; sync") #else - #define XFENCE() do{}while(0) + #define XFENCE() WC_DO_NOTHING #endif #else - #define XFENCE() do{}while(0) + #define XFENCE() WC_DO_NOTHING #endif diff --git a/src/wolfssl/wolfcrypt/wc_xmss.h b/src/wolfssl/wolfcrypt/wc_xmss.h index 9d88fbf..21d5fe8 100644 --- a/src/wolfssl/wolfcrypt/wc_xmss.h +++ b/src/wolfssl/wolfcrypt/wc_xmss.h @@ -1,6 +1,6 @@ /* wc_xmss.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wolfevent.h b/src/wolfssl/wolfcrypt/wolfevent.h index 31cc7c5..cb3cb58 100644 --- a/src/wolfssl/wolfcrypt/wolfevent.h +++ b/src/wolfssl/wolfcrypt/wolfevent.h @@ -1,6 +1,6 @@ /* wolfevent.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wolfmath.h b/src/wolfssl/wolfcrypt/wolfmath.h index 4ed88b8..e012ff6 100644 --- a/src/wolfssl/wolfcrypt/wolfmath.h +++ b/src/wolfssl/wolfcrypt/wolfmath.h @@ -1,6 +1,6 @@ /* wolfmath.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -52,6 +52,10 @@ This library provides big integer math functions. #include #endif +#if defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) + #include +#endif + #ifndef MIN #define MIN(x,y) ((x)<(y)?(x):(y)) #endif @@ -118,6 +122,28 @@ WOLFSSL_API int wc_export_int(mp_int* mp, byte* buf, word32* len, WOLFSSL_API const char *wc_GetMathInfo(void); #endif +/* Support for generic Hardware based Math Functions */ +#ifdef WOLFSSL_USE_HW_MP + +WOLFSSL_LOCAL int hw_mod(mp_int* multiplier, mp_int* mod, mp_int* result); +WOLFSSL_LOCAL int hw_mulmod(mp_int* multiplier, mp_int* multiplicand, + mp_int* mod, mp_int* result); +WOLFSSL_LOCAL int hw_addmod(mp_int* a, mp_int* b, mp_int* mod, mp_int* result); +WOLFSSL_LOCAL int hw_submod(mp_int* a, mp_int* b, mp_int* mod, mp_int* result); +WOLFSSL_LOCAL int hw_exptmod(mp_int* base, mp_int* exp, mp_int* mod, + mp_int* result); +WOLFSSL_LOCAL int hw_sqrmod(mp_int* base, mp_int* mod, mp_int* result); + +/* One to one mappings */ +#define mp_mod hw_mod +#define mp_addmod hw_addmod +#define mp_submod hw_submod +#define mp_mulmod hw_mulmod +#define mp_exptmod hw_exptmod +#define mp_sqrmod hw_sqrmod + +#endif + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/xmss.h b/src/wolfssl/wolfcrypt/xmss.h index 37aab34..548700c 100644 --- a/src/wolfssl/wolfcrypt/xmss.h +++ b/src/wolfssl/wolfcrypt/xmss.h @@ -1,6 +1,6 @@ /* xmss.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfio.h b/src/wolfssl/wolfio.h index e2a1c88..2cd43c7 100644 --- a/src/wolfssl/wolfio.h +++ b/src/wolfssl/wolfio.h @@ -1,6 +1,6 @@ /* io.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2024 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -168,6 +168,9 @@ #include "socket.h" #elif defined(NETOS) #include + #elif defined(NUCLEUS_PLUS_2_3) + #define SO_TYPE 17 /* Socket type */ + #define SO_RCVTIMEO 13 /* Recv Timeout */ #elif !defined(DEVKITPRO) && !defined(WOLFSSL_PICOTCP) \ && !defined(WOLFSSL_CONTIKI) && !defined(WOLFSSL_WICED) \ && !defined(WOLFSSL_GNRC) && !defined(WOLFSSL_RIOT_OS) @@ -198,6 +201,9 @@ #include #endif +#define SOCKET_RECEIVING 1 +#define SOCKET_SENDING 2 + #ifdef USE_WINDOWS_API /* no epipe yet */ #ifndef WSAEPIPE @@ -205,6 +211,7 @@ #endif #define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK #define SOCKET_EAGAIN WSAETIMEDOUT + #define SOCKET_ETIMEDOUT WSAETIMEDOUT #define SOCKET_ECONNRESET WSAECONNRESET #define SOCKET_EINTR WSAEINTR #define SOCKET_EPIPE WSAEPIPE @@ -224,6 +231,7 @@ /* RTCS old I/O doesn't have an EWOULDBLOCK */ #define SOCKET_EWOULDBLOCK EAGAIN #define SOCKET_EAGAIN EAGAIN + #define SOCKET_ETIMEDOUT RTCSERR_TCP_TIMED_OUT #define SOCKET_ECONNRESET RTCSERR_TCP_CONN_RESET #define SOCKET_EINTR EINTR #define SOCKET_EPIPE EPIPE @@ -232,6 +240,7 @@ #else #define SOCKET_EWOULDBLOCK NIO_EWOULDBLOCK #define SOCKET_EAGAIN NIO_EAGAIN + #define SOCKET_ETIMEDOUT NIO_ETIMEDOUT #define SOCKET_ECONNRESET NIO_ECONNRESET #define SOCKET_EINTR NIO_EINTR #define SOCKET_EPIPE NIO_EPIPE @@ -249,6 +258,7 @@ #elif defined(WOLFSSL_PICOTCP) #define SOCKET_EWOULDBLOCK PICO_ERR_EAGAIN #define SOCKET_EAGAIN PICO_ERR_EAGAIN + #define SOCKET_ETIMEDOUT PICO_ERR_ETIMEDOUT #define SOCKET_ECONNRESET PICO_ERR_ECONNRESET #define SOCKET_EINTR PICO_ERR_EINTR #define SOCKET_EPIPE PICO_ERR_EIO @@ -257,6 +267,7 @@ #elif defined(FREERTOS_TCP) #define SOCKET_EWOULDBLOCK FREERTOS_EWOULDBLOCK #define SOCKET_EAGAIN FREERTOS_EWOULDBLOCK + #define SOCKET_ETIMEDOUT (-pdFREERTOS_ERRNO_ETIMEDOUT) #define SOCKET_ECONNRESET FREERTOS_SOCKET_ERROR #define SOCKET_EINTR FREERTOS_SOCKET_ERROR #define SOCKET_EPIPE FREERTOS_SOCKET_ERROR @@ -270,6 +281,14 @@ #define SOCKET_EPIPE NU_NOT_CONNECTED #define SOCKET_ECONNREFUSED NU_CONNECTION_REFUSED #define SOCKET_ECONNABORTED NU_NOT_CONNECTED +#elif defined(NUCLEUS_PLUS_2_3) + #define SOCKET_EWOULDBLOCK NU_WOULD_BLOCK + #define SOCKET_EAGAIN NU_NO_DATA + #define SOCKET_ECONNRESET NU_RESET + #define SOCKET_EINTR 0 + #define SOCKET_EPIPE 0 + #define SOCKET_ECONNREFUSED NU_CONNECTION_REFUSED + #define SOCKET_ECONNABORTED NU_CONNECTION_REFUSED #elif defined(WOLFSSL_DEOS) /* `sockaddr_storage` is not defined in DEOS. This workaround will * work for IPV4, but not IPV6 @@ -301,6 +320,7 @@ #elif defined(WOLFSSL_LWIP_NATIVE) #define SOCKET_EWOULDBLOCK ERR_WOULDBLOCK #define SOCKET_EAGAIN ERR_WOULDBLOCK + #define SOCKET_TIMEDOUT ERR_TIMEOUT #define SOCKET_ECONNRESET ERR_RST #define SOCKET_EINTR ERR_CLSD #define SOCKET_EPIPE ERR_CLSD @@ -318,6 +338,7 @@ #else #define SOCKET_EWOULDBLOCK EWOULDBLOCK #define SOCKET_EAGAIN EAGAIN + #define SOCKET_ETIMEDOUT ETIMEDOUT #define SOCKET_ECONNRESET ECONNRESET #define SOCKET_EINTR EINTR #define SOCKET_EPIPE EPIPE @@ -354,6 +375,11 @@ #elif defined(WOLFSSL_NUCLEUS_1_2) #define SEND_FUNCTION NU_Send #define RECV_FUNCTION NU_Recv +#elif defined(NUCLEUS_PLUS_2_3) + #define SEND_FUNCTION nucyassl_send + #define RECV_FUNCTION nucyassl_recv + #define DTLS_RECVFROM_FUNCTION nucyassl_recvfrom + #define DTLS_SENDTO_FUNCTION nucyassl_sendto #elif defined(FUSION_RTOS) #define SEND_FUNCTION FNS_SEND #define RECV_FUNCTION FNS_RECV @@ -378,26 +404,13 @@ #endif #endif -#ifdef USE_WINDOWS_API - #if defined(__MINGW64__) - typedef size_t SOCKET_T; - #else - typedef unsigned int SOCKET_T; - #endif - #ifndef SOCKET_INVALID - #define SOCKET_INVALID INVALID_SOCKET - #endif -#else - typedef int SOCKET_T; - #ifndef SOCKET_INVALID - #define SOCKET_INVALID (-1) - #endif -#endif - #ifndef WOLFSSL_NO_SOCK #ifndef XSOCKLENT #ifdef USE_WINDOWS_API #define XSOCKLENT int + #elif defined(NUCLEUS_PLUS_2_3) + typedef int socklen_t; + #define XSOCKLENT socklen_t #else #define XSOCKLENT socklen_t #endif @@ -420,6 +433,10 @@ #ifdef WOLFSSL_IPV6 typedef struct sockaddr_in6 SOCKADDR_IN6; #endif + #if defined(HAVE_SYS_UN_H) && !defined(WOLFSSL_NO_SOCKADDR_UN) + #include + typedef struct sockaddr_un SOCKADDR_UN; + #endif typedef struct hostent HOSTENT; #endif /* HAVE_SOCKADDR */ @@ -444,6 +461,32 @@ WOLFSSL_API int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port); WOLFSSL_API int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags); WOLFSSL_API int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags); +#ifdef WOLFSSL_HAVE_BIO_ADDR + +#ifdef WOLFSSL_NO_SOCK +#error WOLFSSL_HAVE_BIO_ADDR and WOLFSSL_NO_SOCK are mutually incompatible. +#endif + +union WOLFSSL_BIO_ADDR { + SOCKADDR sa; + SOCKADDR_IN sa_in; +#ifdef WOLFSSL_IPV6 + SOCKADDR_IN6 sa_in6; +#endif +#if defined(HAVE_SYS_UN_H) && !defined(WOLFSSL_NO_SOCKADDR_UN) + SOCKADDR_UN sa_un; +#endif +}; + +typedef union WOLFSSL_BIO_ADDR WOLFSSL_BIO_ADDR; + +#if defined(WOLFSSL_DTLS) && defined(OPENSSL_EXTRA) +WOLFSSL_API int wolfIO_SendTo(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int wrFlags); +WOLFSSL_API int wolfIO_RecvFrom(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int rdFlags); +#endif + +#endif /* WOLFSSL_HAVE_BIO_ADDR */ + #endif /* USE_WOLFSSL_IO || HAVE_HTTP_CLIENT */ #ifndef WOLFSSL_NO_SOCK @@ -465,6 +508,7 @@ WOLFSSL_API int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags); FNS_CLOSE(s, &err); \ } while(0) #endif + #define StartTCP() WC_DO_NOTHING #else #ifndef CloseSocket #define CloseSocket(s) close(s) @@ -476,15 +520,24 @@ WOLFSSL_API int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags); #endif #endif /* WOLFSSL_NO_SOCK */ - +/* Preserve API previously exposed */ WOLFSSL_API int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx); WOLFSSL_API int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); + +WOLFSSL_LOCAL int SslBioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx); +WOLFSSL_LOCAL int BioReceiveInternal(WOLFSSL_BIO* biord, WOLFSSL_BIO* biowr, + char* buf, int sz); +WOLFSSL_LOCAL int SslBioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); #if defined(USE_WOLFSSL_IO) /* default IO callbacks */ WOLFSSL_API int EmbedReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); WOLFSSL_API int EmbedSend(WOLFSSL* ssl, char* buf, int sz, void* ctx); #ifdef WOLFSSL_DTLS + #ifdef NUCLEUS_PLUS_2_3 + #define SELECT_FUNCTION nucyassl_select + WOLFSSL_LOCAL int nucyassl_select(INT sd, UINT32 timeout); + #endif WOLFSSL_API int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx); WOLFSSL_API int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx); @@ -497,9 +550,14 @@ WOLFSSL_API int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); #endif /* WOLFSSL_DTLS */ #endif /* USE_WOLFSSL_IO */ + +typedef int (*WolfSSLGenericIORecvCb)(char *buf, int sz, void *ctx); #ifdef HAVE_OCSP WOLFSSL_API int wolfIO_HttpBuildRequestOcsp(const char* domainName, const char* path, int ocspReqSz, unsigned char* buf, int bufSize); + WOLFSSL_API int wolfIO_HttpProcessResponseOcspGenericIO( + WolfSSLGenericIORecvCb ioCb, void* ioCbCtx, unsigned char** respBuf, + unsigned char* httpBuf, int httpBufSz, void* heap); WOLFSSL_API int wolfIO_HttpProcessResponseOcsp(int sfd, unsigned char** respBuf, unsigned char* httpBuf, int httpBufSz, void* heap); @@ -530,6 +588,10 @@ WOLFSSL_API int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); WOLFSSL_LOCAL int wolfIO_HttpBuildRequest_ex(const char* reqType, const char* domainName, const char* path, int pathLen, int reqSz, const char* contentType, const char *exHdrs, unsigned char* buf, int bufSize); + WOLFSSL_API int wolfIO_HttpProcessResponseGenericIO( + WolfSSLGenericIORecvCb ioCb, void* ioCbCtx, const char** appStrList, + unsigned char** respBuf, unsigned char* httpBuf, int httpBufSz, + int dynType, void* heap); WOLFSSL_API int wolfIO_HttpProcessResponse(int sfd, const char** appStrList, unsigned char** respBuf, unsigned char* httpBuf, int httpBufSz, int dynType, void* heap); @@ -556,7 +618,6 @@ WOLFSSL_API void* wolfSSL_GetIOWriteCtx(WOLFSSL* ssl); WOLFSSL_API void wolfSSL_SetIOReadFlags( WOLFSSL* ssl, int flags); WOLFSSL_API void wolfSSL_SetIOWriteFlags(WOLFSSL* ssl, int flags); - #ifdef HAVE_NETX WOLFSSL_LOCAL int NetX_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx); WOLFSSL_LOCAL int NetX_Send(WOLFSSL *ssl, char *buf, int sz, void *ctx); From fdeb34eb2c2f287258a9e547418f4dd981d3c345 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Mon, 27 Jan 2025 11:09:17 -0800 Subject: [PATCH 06/13] wolfssl 5.7.6 Release for Arduino --- ChangeLog.md | 126 + README | 278 +- README.md | 322 +-- examples/wolfssl_client/wolfssl_client.ino | 11 +- examples/wolfssl_server/wolfssl_server.ino | 9 + examples/wolfssl_version/wolfssl_version.ino | 79 +- library.properties | 2 +- src/src/bio.c | 91 +- src/src/conf.c | 19 +- src/src/crl.c | 158 +- src/src/dtls.c | 81 +- src/src/dtls13.c | 8 +- src/src/internal.c | 1041 +++++--- src/src/keys.c | 154 +- src/src/ocsp.c | 10 +- src/src/pk.c | 414 +-- src/src/quic.c | 20 +- src/src/sniffer.c | 216 +- src/src/ssl.c | 2301 +++++++++++------ src/src/ssl_asn1.c | 158 +- src/src/ssl_bn.c | 2 +- src/src/ssl_certman.c | 38 +- src/src/ssl_crypto.c | 143 +- src/src/ssl_load.c | 109 +- src/src/ssl_p7p12.c | 6 +- src/src/ssl_sess.c | 70 +- src/src/tls.c | 212 +- src/src/tls13.c | 135 +- src/src/wolfio.c | 154 +- src/src/x509.c | 1947 +++++++------- src/src/x509_str.c | 196 +- src/wolfcrypt/src/aes.c | 1827 +++++++------ src/wolfcrypt/src/asn.c | 614 +++-- src/wolfcrypt/src/bio.c | 91 +- src/wolfcrypt/src/camellia.c | 44 +- src/wolfcrypt/src/chacha.c | 2 +- src/wolfcrypt/src/cmac.c | 34 +- src/wolfcrypt/src/coding.c | 20 +- src/wolfcrypt/src/cpuid.c | 207 +- src/wolfcrypt/src/cryptocb.c | 46 +- src/wolfcrypt/src/curve25519.c | 2 +- src/wolfcrypt/src/des3.c | 18 +- src/wolfcrypt/src/dh.c | 2 +- src/wolfcrypt/src/dilithium.c | 93 +- src/wolfcrypt/src/dsa.c | 16 +- src/wolfcrypt/src/ecc.c | 127 +- src/wolfcrypt/src/eccsi.c | 2 +- src/wolfcrypt/src/ed25519.c | 57 +- src/wolfcrypt/src/error.c | 9 +- src/wolfcrypt/src/evp.c | 2014 ++++++++------- src/wolfcrypt/src/ext_kyber.c | 59 +- src/wolfcrypt/src/fe_448.c | 19 +- src/wolfcrypt/src/ge_448.c | 797 +++--- src/wolfcrypt/src/ge_low_mem.c | 37 + src/wolfcrypt/src/ge_operations.c | 22 +- src/wolfcrypt/src/hash.c | 8 +- src/wolfcrypt/src/hmac.c | 8 + src/wolfcrypt/src/hpke.c | 4 +- src/wolfcrypt/src/kdf.c | 27 +- src/wolfcrypt/src/md2.c | 40 +- src/wolfcrypt/src/md4.c | 38 +- src/wolfcrypt/src/md5.c | 2 +- src/wolfcrypt/src/memory.c | 85 +- src/wolfcrypt/src/misc.c | 73 +- src/wolfcrypt/src/pkcs12.c | 16 +- src/wolfcrypt/src/pkcs7.c | 274 +- src/wolfcrypt/src/port/Espressif/esp32_aes.c | 24 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 145 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 4 +- src/wolfcrypt/src/pwdbased.c | 4 +- src/wolfcrypt/src/random.c | 9 +- src/wolfcrypt/src/rsa.c | 55 +- src/wolfcrypt/src/sakke.c | 2 +- src/wolfcrypt/src/sha3.c | 161 +- src/wolfcrypt/src/sha512.c | 251 +- src/wolfcrypt/src/signature.c | 13 +- src/wolfcrypt/src/siphash.c | 14 +- src/wolfcrypt/src/sp_arm32.c | 451 ++-- src/wolfcrypt/src/sp_arm64.c | 154 +- src/wolfcrypt/src/sp_armthumb.c | 397 +-- src/wolfcrypt/src/sp_c32.c | 106 +- src/wolfcrypt/src/sp_c64.c | 106 +- src/wolfcrypt/src/sp_cortexm.c | 427 +-- src/wolfcrypt/src/sp_dsp32.c | 38 +- src/wolfcrypt/src/sp_int.c | 185 +- src/wolfcrypt/src/sp_x86_64.c | 150 +- src/wolfcrypt/src/tfm.c | 4 +- src/wolfcrypt/src/wc_kyber.c | 431 ++- src/wolfcrypt/src/wc_kyber_poly.c | 119 +- src/wolfcrypt/src/wc_lms.c | 8 +- src/wolfcrypt/src/wc_lms_impl.c | 25 +- src/wolfcrypt/src/wc_pkcs11.c | 110 +- src/wolfcrypt/src/wc_port.c | 78 +- src/wolfcrypt/src/wc_xmss.c | 6 +- src/wolfcrypt/src/wolfmath.c | 27 +- src/wolfssl.h | 10 +- src/wolfssl/bio.c | 91 +- src/wolfssl/callbacks.h | 2 +- src/wolfssl/certs_test.h | 1759 ++++++------- src/wolfssl/crl.h | 5 +- src/wolfssl/error-ssl.h | 21 +- src/wolfssl/evp.c | 2014 ++++++++------- src/wolfssl/internal.h | 171 +- src/wolfssl/openssl/aes.h | 33 +- src/wolfssl/openssl/asn1.h | 113 +- src/wolfssl/openssl/bio.h | 125 +- src/wolfssl/openssl/bn.h | 4 +- src/wolfssl/openssl/buffer.h | 3 + src/wolfssl/openssl/cmac.h | 8 +- src/wolfssl/openssl/compat_types.h | 4 +- src/wolfssl/openssl/conf.h | 6 +- src/wolfssl/openssl/crypto.h | 15 +- src/wolfssl/openssl/des.h | 13 +- src/wolfssl/openssl/dh.h | 4 +- src/wolfssl/openssl/dsa.h | 10 +- src/wolfssl/openssl/ec.h | 146 +- src/wolfssl/openssl/ecdsa.h | 6 + src/wolfssl/openssl/err.h | 45 +- src/wolfssl/openssl/evp.h | 665 +++-- src/wolfssl/openssl/hmac.h | 3 + src/wolfssl/openssl/kdf.h | 14 +- src/wolfssl/openssl/md4.h | 3 + src/wolfssl/openssl/md5.h | 4 + src/wolfssl/openssl/obj_mac.h | 47 +- src/wolfssl/openssl/objects.h | 10 +- src/wolfssl/openssl/ocsp.h | 4 + src/wolfssl/openssl/pem.h | 10 +- src/wolfssl/openssl/pkcs12.h | 15 +- src/wolfssl/openssl/rand.h | 9 + src/wolfssl/openssl/rc4.h | 7 +- src/wolfssl/openssl/rsa.h | 37 +- src/wolfssl/openssl/sha.h | 28 +- src/wolfssl/openssl/srp.h | 4 + src/wolfssl/openssl/ssl.h | 178 +- src/wolfssl/openssl/tls1.h | 12 +- src/wolfssl/openssl/x509.h | 325 +-- src/wolfssl/openssl/x509v3.h | 172 +- src/wolfssl/ssl.h | 1254 +++++---- src/wolfssl/test.h | 32 +- src/wolfssl/version.h | 4 +- src/wolfssl/wolfcrypt/aes.h | 101 +- src/wolfssl/wolfcrypt/asn.h | 300 ++- src/wolfssl/wolfcrypt/asn_public.h | 4 + src/wolfssl/wolfcrypt/camellia.h | 45 +- src/wolfssl/wolfcrypt/cmac.h | 12 +- src/wolfssl/wolfcrypt/cpuid.h | 25 + src/wolfssl/wolfcrypt/cryptocb.h | 37 +- src/wolfssl/wolfcrypt/dilithium.h | 48 +- src/wolfssl/wolfcrypt/error-crypt.h | 33 +- src/wolfssl/wolfcrypt/ge_448.h | 1 + src/wolfssl/wolfcrypt/hash.h | 1 + src/wolfssl/wolfcrypt/hpke.h | 6 +- src/wolfssl/wolfcrypt/integer.h | 4 +- src/wolfssl/wolfcrypt/kyber.h | 49 +- src/wolfssl/wolfcrypt/logging.h | 30 +- src/wolfssl/wolfcrypt/md2.h | 40 +- src/wolfssl/wolfcrypt/md4.h | 34 +- src/wolfssl/wolfcrypt/md5.h | 4 +- src/wolfssl/wolfcrypt/mem_track.h | 26 +- src/wolfssl/wolfcrypt/memory.h | 15 +- src/wolfssl/wolfcrypt/misc.h | 11 +- src/wolfssl/wolfcrypt/pkcs11.h | 2 + src/wolfssl/wolfcrypt/pkcs7.h | 129 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 2 +- .../wolfcrypt/port/Espressif/esp32-crypt.h | 2 +- .../wolfcrypt/port/Espressif/esp_crt_bundle.h | 2 +- src/wolfssl/wolfcrypt/rsa.h | 10 +- src/wolfssl/wolfcrypt/settings.h | 281 +- src/wolfssl/wolfcrypt/sha3.h | 14 +- src/wolfssl/wolfcrypt/sha512.h | 12 +- src/wolfssl/wolfcrypt/sp_int.h | 27 +- src/wolfssl/wolfcrypt/tfm.h | 4 +- src/wolfssl/wolfcrypt/types.h | 233 +- src/wolfssl/wolfcrypt/wc_lms.h | 2 + src/wolfssl/wolfcrypt/wc_port.h | 156 +- src/wolfssl/wolfio.h | 14 +- 177 files changed, 17104 insertions(+), 10807 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index a0585b3..0b32346 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,129 @@ +# wolfSSL Release 5.7.6 (Dec 31, 2024) + +Release 5.7.6 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: + * --enable-heapmath is deprecated. + * In this release, the default cipher suite preference is updated to prioritize + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256 when enabled. + * This release adds a sanity check for including wolfssl/options.h or + user_settings.h. + + +PR stands for Pull Request, and PR references a GitHub pull request + number where the code change was added. + + +## Vulnerabilities +* [Med] An OCSP (non stapling) issue was introduced in wolfSSL version 5.7.4 + when performing OCSP requests for intermediate certificates in a certificate + chain. This affects only TLS 1.3 connections on the server side. It would not + impact other TLS protocol versions or connections that are not using the + traditional OCSP implementation. (Fix in pull request 8115) + + +## New Feature Additions +* Add support for RP2350 and improve RP2040 support, both with RNG optimizations + (PR 8153) +* Add support for STM32MP135F, including STM32CubeIDE support and HAL support + for SHA2/SHA3/AES/RNG/ECC optimizations. (PR 8223, 8231, 8241) +* Implement Renesas TSIP RSA Public Enc/Private support (PR 8122) +* Add support for Fedora/RedHat system-wide crypto-policies (PR 8205) +* Curve25519 generic keyparsing API added with wc_Curve25519KeyToDer and + wc_Curve25519KeyDecode (PR 8129) +* CRL improvements and update callback, added the functions + wolfSSL_CertManagerGetCRLInfo and wolfSSL_CertManagerSetCRLUpdate_Cb (PR 8006) +* For DTLS, add server-side stateless and CID quality-of-life API. (PR 8224) + + +## Enhancements and Optimizations +* Add a CMake dependency check for pthreads when required. (PR 8162) +* Update OS_Seed declarations for legacy compilers and FIPS modules (boundary + not affected). (PR 8170) +* Enable WOLFSSL_ALWAYS_KEEP_SNI by default when using --enable-jni. (PR 8283) +* Change the default cipher suite preference, prioritizing + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256. (PR 7771) +* Add SRTP-KDF (FIPS module v6.0.0) to checkout script for release bundling + (PR 8215) +* Make library build when no hardware crypto available for Aarch64 (PR 8293) +* Update assembly code to avoid `uint*_t` types for better compatibility with + older C standards. (PR 8133) +* Add initial documentation for writing ASN template code to decode BER/DER. + (PR 8120) +* Perform full reduction in sc_muladd for EdDSA with Curve448 (PR 8276) +* Allow SHA-3 hardware cryptography instructions to be explicitly not used in + MacOS builds (PR 8282) +* Make Kyber and ML-KEM available individually and together. (PR 8143) +* Update configuration options to include Kyber/ML-KEM and fix defines used in + wolfSSL_get_curve_name. (PR 8183) +* Make GetShortInt available with WOLFSSL_ASN_EXTRA (PR 8149) +* Improved test coverage and minor improvements of X509 (PR 8176) +* Add sanity checks for configuration methods, ensuring the inclusion of + wolfssl/options.h or user_settings.h. (PR 8262) +* Enable support for building without TLS (NO_TLS). Provides reduced code size + option for non-TLS users who want features like the certificate manager or + compatibility layer. (PR 8273) +* Exposed get_verify functions with OPENSSL_EXTRA. (PR 8258) +* ML-DSA/Dilithium: obtain security level from DER when decoding (PR 8177) +* Implementation for using PKCS11 to retrieve certificate for SSL CTX (PR 8267) +* Add support for the RFC822 Mailbox attribute (PR 8280) +* Initialize variables and adjust types resolve warnings with Visual Studio in + Windows builds. (PR 8181) +* Refactors and expansion of opensslcoexist build (PR 8132, 8216, 8230) +* Add DTLS 1.3 interoperability, libspdm and DTLS CID interoperability tests + (PR 8261, 8255, 8245) +* Remove trailing error exit code in wolfSSL install setup script (PR 8189) +* Update Arduino files for wolfssl 5.7.4 (PR 8219) +* Improve Espressif SHA HW/SW mutex messages (PR 8225) +* Apply post-5.7.4 release updates for Espressif Managed Component examples + (PR 8251) +* Expansion of c89 conformance (PR 8164) +* Added configure option for additional sanity checks with --enable-faultharden + (PR 8289) +* Aarch64 ASM additions to check CPU features before hardware crypto instruction + use (PR 8314) + + +## Fixes +* Fix a memory issue when using the compatibility layer with + WOLFSSL_GENERAL_NAME and handling registered ID types. (PR 8155) +* Fix a build issue with signature fault hardening when using public key + callbacks (HAVE_PK_CALLBACKS). (PR 8287) +* Fix for handling heap hint pointer properly when managing multiple WOLFSSL_CTX + objects and free’ing one of them (PR 8180) +* Fix potential memory leak in error case with Aria. (PR 8268) +* Fix Set_Verify flag behaviour on Ada wrapper. (PR 8256) +* Fix a compilation error with the NO_WOLFSSL_DIR flag. (PR 8294) +* Resolve a corner case for Poly1305 assembly code on Aarch64. (PR 8275) +* Fix incorrect version setting in CSRs. (PR 8136) +* Correct debugging output for cryptodev. (PR 8202) +* Fix for benchmark application use with /dev/crypto GMAC auth error due to size + of AAD (PR 8210) +* Add missing checks for the initialization of sp_int/mp_int with DSA to free + memory properly in error cases. (PR 8209) +* Fix return value of wolfSSL_CTX_set_tlsext_use_srtp (8252) +* Check Root CA by Renesas TSIP before adding it to ca-table (PR 8101) +* Prevent adding a certificate to the CA cache for Renesas builds if it does not + set CA:TRUE in basic constraints. (PR 8060) +* Fix attribute certificate holder entityName parsing. (PR 8166) +* Resolve build issues for configurations without any wolfSSL/openssl + compatibility layer headers. (PR 8182) +* Fix for building SP RSA small and RSA public only (PR 8235) +* Fix for Renesas RX TSIP RSA Sign/Verify with wolfCrypt only (PR 8206) +* Fix to ensure all files have settings.h included (like wc_lms.c) and guards + for building all `*.c` files (PR 8257 and PR 8140) +* Fix x86 target build issues in Visual Studio for non-Windows operating + systems. (PR 8098) +* Fix wolfSSL_X509_STORE_get0_objects to handle no CA (PR 8226) +* Properly handle reference counting when adding to the X509 store. (PR 8233) +* Fix for various typos and improper size used with FreeRTOS_bind in the Renesas + example. Thanks to Hongbo for the report on example issues. (PR 7537) +* Fix for potential heap use after free with wolfSSL_PEM_read_bio_PrivateKey. + Thanks to Peter for the issue reported. (PR 8139) + + # wolfSSL Release 5.7.4 (Oct 24, 2024) Release 5.7.4 has been developed according to wolfSSL's development and QA diff --git a/README b/README index 2b462bc..47579ee 100644 --- a/README +++ b/README @@ -70,198 +70,130 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.7.4 (Oct 24, 2024) +# wolfSSL Release 5.7.6 (Dec 31, 2024) -Release 5.7.4 has been developed according to wolfSSL's development and QA +Release 5.7.6 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 +NOTE: + * --enable-heapmath is deprecated. + * In this release, the default cipher suite preference is updated to prioritize + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256 when enabled. + * This release adds a sanity check for including wolfssl/options.h or + user_settings.h. + PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. ## Vulnerabilities -* [Low] When the OpenSSL compatibility layer is enabled, certificate - verification behaved differently in wolfSSL than OpenSSL, in the - X509_STORE_add_cert() and X509_STORE_load_locations() implementations. - Previously, in cases where an application explicitly loaded an intermediate - certificate, wolfSSL was verifying only up to that intermediate certificate, - rather than verifying up to the root CA. This only affects use cases where the - API is called directly, and does not affect TLS connections. Users that call - the API X509_STORE_add_cert() or X509_STORE_load_locations() directly in their - applications are recommended to update the version of wolfSSL used or to have - additional sanity checks on certificates loaded into the X509_STORE when - verifying a certificate. (https://github.com/wolfSSL/wolfssl/pull/8087) - - -## PQC TLS Experimental Build Fix -* When using TLS with post quantum algorithms enabled, the connection uses a - smaller EC curve than agreed on. Users building with --enable-experimental and - enabling PQC cipher suites with TLS connections are recommended to update the - version of wolfSSL used. Thanks to Daniel Correa for the report. - (https://github.com/wolfSSL/wolfssl/pull/8084) +* [Med] An OCSP (non stapling) issue was introduced in wolfSSL version 5.7.4 + when performing OCSP requests for intermediate certificates in a certificate + chain. This affects only TLS 1.3 connections on the server side. It would not + impact other TLS protocol versions or connections that are not using the + traditional OCSP implementation. (Fix in pull request 8115) ## New Feature Additions -* RISC-V 64 new assembly optimizations added for SHA-256, SHA-512, ChaCha20, - Poly1305, and SHA-3 (PR 7758,7833,7818,7873,7916) -* Implement support for Connection ID (CID) with DTLS 1.2 (PR 7995) -* Add support for (DevkitPro)libnds (PR 7990) -* Add port for Mosquitto OSP (Open Source Project) (PR 6460) -* Add port for init sssd (PR 7781) -* Add port for eXosip2 (PR 7648) -* Add support for STM32G4 (PR 7997) -* Add support for MAX32665 and MAX32666 TPU HW and ARM ASM Crypto Callback - Support (PR 7777) -* Add support for building wolfSSL to be used in libspdm (PR 7869) -* Add port for use with Nucleus Plus 2.3 (PR 7732) -* Initial support for RFC5755 x509 attribute certificates (acerts). Enabled with - --enable-acert (PR 7926) -* PKCS#11 RSA Padding offload allows tokens to perform CKM_RSA_PKCS - (sign/encrypt), CKM_RSA_PKCS_PSS (sign), and CKM_RSA_PKCS_OAEP (encrypt). - (PR 7750) -* Added “new” and “delete” style functions for heap/pool allocation and freeing - of low level crypto structures (PR 3166 and 8089) +* Add support for RP2350 and improve RP2040 support, both with RNG optimizations + (PR 8153) +* Add support for STM32MP135F, including STM32CubeIDE support and HAL support + for SHA2/SHA3/AES/RNG/ECC optimizations. (PR 8223, 8231, 8241) +* Implement Renesas TSIP RSA Public Enc/Private support (PR 8122) +* Add support for Fedora/RedHat system-wide crypto-policies (PR 8205) +* Curve25519 generic keyparsing API added with wc_Curve25519KeyToDer and + wc_Curve25519KeyDecode (PR 8129) +* CRL improvements and update callback, added the functions + wolfSSL_CertManagerGetCRLInfo and wolfSSL_CertManagerSetCRLUpdate_Cb (PR 8006) +* For DTLS, add server-side stateless and CID quality-of-life API. (PR 8224) ## Enhancements and Optimizations -* Increase default max alt. names from 128 to 1024 (PR 7762) -* Added new constant time DH agree function wc_DhAgree_ct (PR 7802) -* Expanded compatibility layer with the API EVP_PKEY_is_a (PR 7804) -* Add option to disable cryptocb test software test using - --disable-cryptocb-sw-test (PR 7862) -* Add a call to certificate verify callback before checking certificate dates - (PR 7895) -* Expanded algorithms supported with the wolfCrypt CSharp wrapper. Adding - support for RNG, ECC(ECIES and ECDHE), RSA, ED25519/Curve25519, AES-GCM, and - Hashing (PR 3166) -* Expand MMCAU support for use with DES ECB (PR 7960) -* Update AES SIV to handle multiple associated data inputs (PR 7911) -* Remove HAVE_NULL_CIPHER from --enable-openssh (PR 7811) -* Removed duplicate if(NULL) checks when calling XFREE (macro does) (PR 7839) -* Set RSA_MIN_SIZE default to 2048 bits (PR 7923) -* Added support for wolfSSL to be used as the default TLS in the zephyr kernel - (PR 7731) -* Add enable provider build using --enable-wolfprovider with autotools (PR 7550) -* Renesas RX TSIP ECDSA support (PR 7685) -* Support DTLS1.3 downgrade when the server supports CID (PR 7841) -* Server-side checks OCSP even if it uses v2 multi (PR 7828) -* Add handling of absent hash params in PKCS7 bundle parsing and creation - (PR 7845) -* Add the use of w64wrapper for Poly1305, enabling Poly1305 to be used in - environments that do not have a word64 type (PR 7759) -* Update to the maxq10xx support (PR 7824) -* Add support for parsing over optional PKCS8 attributes (PR 7944) -* Add support for either side method with DTLS 1.3 (PR 8012) -* Added PKCS7 PEM support for parsing PEM data with BEGIN/END PKCS7 (PR 7704) -* Add CMake support for WOLFSSL_CUSTOM_CURVES (PR 7962) -* Add left-most wildcard matching support to X509_check_host() (PR 7966) -* Add option to set custom SKID with PKCS7 bundle creation (PR 7954) -* Building wolfSSL as a library with Ada and corrections to Alire manifest - (PR 7303,7940) -* Renesas RX72N support updated (PR 7849) -* New option WOLFSSL_COPY_KEY added to always copy the key to the SSL object - (PR 8005) -* Add the new option WOLFSSL_COPY_CERT to always copy the cert buffer for each - SSL object (PR 7867) -* Add an option to use AES-CBC with HMAC for default session ticket enc/dec. - Defaults to AES-128-CBC with HMAC-SHA256 (PR 7703) -* Memory usage improvements in wc_PRF, sha256 (for small code when many - registers are available) and sp_int objects (PR 7901) -* Change in the configure script to work around ">>" with no command. In older - /bin/sh it can be ambiguous, as used in OS’s such as FreeBSD 9.2 (PR 7876) -* Don't attempt to include system headers when not required (PR 7813) -* Certificates: DER encoding of ECC signature algorithm parameter is now - allowed to be NULL with a define (PR 7903) -* SP x86_64 asm: check for AVX2 support for VMs (PR 7979) -* Update rx64n support on gr-rose (PR 7889) -* Update FSP version to v5.4.0 for RA6M4 (PR 7994) -* Update TSIP driver version to v1.21 for RX65N RSK (PR 7993) -* Add a new crypto callback for RSA with padding (PR 7907) -* Replaced the use of pqm4 with wolfSSL implementations of Kyber/MLDSA - (PR 7924) -* Modernized memory fence support for C11 and clang (PR 7938) -* Add a CRL error override callback (PR 7986) -* Extend the X509 unknown extension callback for use with a user context - (PR 7730) -* Additional debug error tracing added with TLS (PR 7917) -* Added runtime support for library call stack traces with - –enable-debug-trace-errcodes=backtrace, using libbacktrace (PR 7846) -* Expanded C89 conformance (PR 8077) -* Expanded support for WOLFSSL_NO_MALLOC (PR 8065) -* Added support for cross-compilation of Linux kernel module (PR 7746) -* Updated Linux kernel module with support for kernel 6.11 and 6.12 (PR 7826) -* Introduce WOLFSSL_ASN_ALLOW_0_SERIAL to allow parsing of certificates with a - serial number of 0 (PR 7893) -* Add conditional repository_owner to all wolfSSL GitHub workflows (PR 7871) - -### Espressif / Arduino Updates -* Update wolfcrypt settings.h for Espressif ESP-IDF, template update (PR 7953) -* Update Espressif sha, util, mem, time helpers (PR 7955) -* Espressif _thread_local_start and _thread_local_end fix (PR 8030) -* Improve benchmark for Espressif devices (PR 8037) -* Introduce Espressif common CONFIG_WOLFSSL_EXAMPLE_NAME, Kconfig (PR 7866) -* Add wolfSSL esp-tls and Certificate Bundle Support for Espressif ESP-IDF - (PR 7936) -* Update wolfssl Release for Arduino (PR 7775) - -### Post Quantum Crypto Updates -* Dilithium: support fixed size arrays in dilithium_key (PR 7727) -* Dilithium: add option to use precalc with small sign (PR 7744) -* Allow Kyber to be built with FIPS (PR 7788) -* Allow Kyber asm to be used in the Linux kernel module (PR 7872) -* Dilithium, Kyber: Update to final specification (PR 7877) -* Dilithium: Support FIPS 204 Draft and Final Draft (PR 7909,8016) - -### ARM Assembly Optimizations -* ARM32 assembly optimizations added for ChaCha20 and Poly1305 (PR 8020) -* Poly1305 assembly optimizations improvements for Aarch64 (PR 7859) -* Poly1305 assembly optimizations added for Thumb-2 (PR 7939) -* Adding ARM ASM build option to STM32CubePack (PR 7747) -* Add ARM64 to Visual Studio Project (PR 8010) -* Kyber assembly optimizations for ARM32 and Aarch64 (PR 8040,7998) -* Kyber assembly optimizations for ARMv7E-M/ARMv7-M (PR 7706) +* Add a CMake dependency check for pthreads when required. (PR 8162) +* Update OS_Seed declarations for legacy compilers and FIPS modules (boundary + not affected). (PR 8170) +* Enable WOLFSSL_ALWAYS_KEEP_SNI by default when using --enable-jni. (PR 8283) +* Change the default cipher suite preference, prioritizing + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256. (PR 7771) +* Add SRTP-KDF (FIPS module v6.0.0) to checkout script for release bundling + (PR 8215) +* Make library build when no hardware crypto available for Aarch64 (PR 8293) +* Update assembly code to avoid `uint*_t` types for better compatibility with + older C standards. (PR 8133) +* Add initial documentation for writing ASN template code to decode BER/DER. + (PR 8120) +* Perform full reduction in sc_muladd for EdDSA with Curve448 (PR 8276) +* Allow SHA-3 hardware cryptography instructions to be explicitly not used in + MacOS builds (PR 8282) +* Make Kyber and ML-KEM available individually and together. (PR 8143) +* Update configuration options to include Kyber/ML-KEM and fix defines used in + wolfSSL_get_curve_name. (PR 8183) +* Make GetShortInt available with WOLFSSL_ASN_EXTRA (PR 8149) +* Improved test coverage and minor improvements of X509 (PR 8176) +* Add sanity checks for configuration methods, ensuring the inclusion of + wolfssl/options.h or user_settings.h. (PR 8262) +* Enable support for building without TLS (NO_TLS). Provides reduced code size + option for non-TLS users who want features like the certificate manager or + compatibility layer. (PR 8273) +* Exposed get_verify functions with OPENSSL_EXTRA. (PR 8258) +* ML-DSA/Dilithium: obtain security level from DER when decoding (PR 8177) +* Implementation for using PKCS11 to retrieve certificate for SSL CTX (PR 8267) +* Add support for the RFC822 Mailbox attribute (PR 8280) +* Initialize variables and adjust types resolve warnings with Visual Studio in + Windows builds. (PR 8181) +* Refactors and expansion of opensslcoexist build (PR 8132, 8216, 8230) +* Add DTLS 1.3 interoperability, libspdm and DTLS CID interoperability tests + (PR 8261, 8255, 8245) +* Remove trailing error exit code in wolfSSL install setup script (PR 8189) +* Update Arduino files for wolfssl 5.7.4 (PR 8219) +* Improve Espressif SHA HW/SW mutex messages (PR 8225) +* Apply post-5.7.4 release updates for Espressif Managed Component examples + (PR 8251) +* Expansion of c89 conformance (PR 8164) +* Added configure option for additional sanity checks with --enable-faultharden + (PR 8289) +* Aarch64 ASM additions to check CPU features before hardware crypto instruction + use (PR 8314) ## Fixes -* ECC key load: fixes for certificates with parameters that are not default for - size (PR 7751) -* Fixes for building x86 in Visual Studio for non-windows OS (PR 7884) -* Fix for TLS v1.2 secret callback, incorrectly detecting bad master secret - (PR 7812) -* Fixes for PowerPC assembly use with Darwin and SP math all (PR 7931) -* Fix for detecting older versions of Mac OS when trying to link with - libdispatch (PR 7932) -* Fix for DTLS1.3 downgrade to DTLS1.2 when the server sends multiple handshake - packets combined into a single transmission. (PR 7840) -* Fix for OCSP to save the request if it was stored in ssl->ctx->certOcspRequest - (PR 7779) -* Fix to OCSP for searching for CA by key hash instead of ext. key id (PR 7934) -* Fix for staticmemory and singlethreaded build (PR 7737) -* Fix to not allow Shake128/256 with Xilinx AFALG (PR 7708) -* Fix to support PKCS11 without RSA key generation (PR 7738) -* Fix not calling the signing callback when using PK callbacks + TLS 1.3 - (PR 7761) -* Cortex-M/Thumb2 ASM fix label for IAR compiler (PR 7753) -* Fix with PKCS11 to iterate correctly over slotId (PR 7736) -* Stop stripping out the sequence header on the AltSigAlg extension (PR 7710) -* Fix ParseCRL_AuthKeyIdExt with ASN template to set extAuthKeyIdSet value - (PR 7742) -* Use max key length for PSK encrypt buffer size (PR 7707) -* DTLS 1.3 fix for size check to include headers and CID fixes (PR 7912,7951) -* Fix STM32 Hash FIFO and add support for STM32U5A9xx (PR 7787) -* Fix CMake build error for curl builds (PR 8021) -* SP Maths: PowerPC ASM fix to use XOR instead of LI (PR 8038) -* SSL loading of keys/certs: testing and fixes (PR 7789) -* Misc. fixes for Dilithium and Kyber (PR 7721,7765,7803,8027,7904) -* Fixes for building wolfBoot sources for PQ LMS/XMSS (PR 7868) -* Fixes for building with Kyber enabled using CMake and zephyr port (PR 7773) -* Fix for edge cases with session resumption with TLS 1.2 (PR 8097) -* Fix issue with ARM ASM with AES CFB/OFB not initializing the "left" member - (PR 8099) - +* Fix a memory issue when using the compatibility layer with + WOLFSSL_GENERAL_NAME and handling registered ID types. (PR 8155) +* Fix a build issue with signature fault hardening when using public key + callbacks (HAVE_PK_CALLBACKS). (PR 8287) +* Fix for handling heap hint pointer properly when managing multiple WOLFSSL_CTX + objects and free’ing one of them (PR 8180) +* Fix potential memory leak in error case with Aria. (PR 8268) +* Fix Set_Verify flag behaviour on Ada wrapper. (PR 8256) +* Fix a compilation error with the NO_WOLFSSL_DIR flag. (PR 8294) +* Resolve a corner case for Poly1305 assembly code on Aarch64. (PR 8275) +* Fix incorrect version setting in CSRs. (PR 8136) +* Correct debugging output for cryptodev. (PR 8202) +* Fix for benchmark application use with /dev/crypto GMAC auth error due to size + of AAD (PR 8210) +* Add missing checks for the initialization of sp_int/mp_int with DSA to free + memory properly in error cases. (PR 8209) +* Fix return value of wolfSSL_CTX_set_tlsext_use_srtp (8252) +* Check Root CA by Renesas TSIP before adding it to ca-table (PR 8101) +* Prevent adding a certificate to the CA cache for Renesas builds if it does not + set CA:TRUE in basic constraints. (PR 8060) +* Fix attribute certificate holder entityName parsing. (PR 8166) +* Resolve build issues for configurations without any wolfSSL/openssl + compatibility layer headers. (PR 8182) +* Fix for building SP RSA small and RSA public only (PR 8235) +* Fix for Renesas RX TSIP RSA Sign/Verify with wolfCrypt only (PR 8206) +* Fix to ensure all files have settings.h included (like wc_lms.c) and guards + for building all `*.c` files (PR 8257 and PR 8140) +* Fix x86 target build issues in Visual Studio for non-Windows operating + systems. (PR 8098) +* Fix wolfSSL_X509_STORE_get0_objects to handle no CA (PR 8226) +* Properly handle reference counting when adding to the X509 store. (PR 8233) +* Fix for various typos and improper size used with FreeRTOS_bind in the Renesas + example. Thanks to Hongbo for the report on example issues. (PR 7537) +* Fix for potential heap use after free with wolfSSL_PEM_read_bio_PrivateKey. + Thanks to Peter for the issue reported. (PR 8139) For additional vulnerability information visit the vulnerability page at: diff --git a/README.md b/README.md index 2deaa8c..b75d0d5 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,52 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.4 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.6 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). -See the [Arduino-wolfSSL logs](https://downloads.arduino.cc/libraries/logs/github.com/wolfSSL/Arduino-wolfSSL/). +See the [Arduino-wolfSSL logs](https://downloads.arduino.cc/libraries/logs/github.com/wolfSSL/Arduino-wolfSSL/) for publishing status. -## Arduino Releases +Instructions for installing and using libraries can be found in the [Arduino docs](https://docs.arduino.cc/software/ide-v1/tutorials/installing-libraries/). + +## wolfSSL Configuration + +As described in the [Getting Started with wolfSSL on Arduino](https://www.wolfssl.com/getting-started-with-wolfssl-on-arduino/), wolfSSL features are enabled and disabled in the `user_settings.h` file. + +The `user_settings.h` file is found in the `/libraries/wolfssl/src` directory. + +For Windows this is typically `C:\Users\%USERNAME%\Documents\Arduino\libraries\wolfssl\src` + +For Mac: `~/Documents/Arduino/libraries/wolfssl/src` + +For Linux: `~/Arduino/libraries/wolfssl/src` + +Tips for success: + +- The `WOLFSSL_USER_SETTINGS` macro must be defined project-wide. (see [wolfssl.h](https://github.com/wolfSSL/wolfssl/blob/master/IDE/ARDUINO/wolfssl.h)) +- Apply any customizations only to `user_settings.h`; Do not edit wolfSSL `settings.h` or `configh.h` files. +- Do not explicitly include `user_settings.h` in any source file. +- For every source file that uses wolfssl, include `wolfssl/wolfcrypt/settings.h` before any other wolfSSL include, typically via `#include "wolfssl.h"`. +- See the [wolfSSL docs](https://www.wolfssl.com/documentation/manuals/wolfssl/chapter02.html) for details on build configuration macros. -This release of wolfSSL is version [5.7.4](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.4-stable). +## wolfSSL Examples -Version [5.7.2](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.2-stable) of the Arduino wolfSSL was published August 3, 2024. +Additional wolfSSL examples can be found at: -The next Official wolfSSL Arduino Library was [5.7.0](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.0-stable) +- https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO + +- https://github.com/wolfSSL/wolfssl/tree/master/examples + +- https://github.com/wolfSSL/wolfssl-examples/ + +## Arduino Releases + +This release of wolfSSL is version [5.7.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.6-stable). + +See GitHub for [all Arduino wolfSSL releases](https://github.com/wolfSSL/Arduino-wolfSSL/releases). The first Official wolfSSL Arduino Library was `5.6.6-Arduino.1`: a slightly modified, post [release 5.6.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.6.6-stable) version update. -See other [wolfSSL releases versions](https://github.com/wolfSSL/wolfssl/releases). The `./wolfssl-arduino.sh INSTALL` [script](https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO) can be used to install specific GitHub versions as needed. +The `./wolfssl-arduino.sh INSTALL` [script](https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO) can be used to install specific GitHub versions as needed. # wolfSSL Embedded SSL/TLS Library The [wolfSSL embedded SSL library](https://www.wolfssl.com/products/wolfssl/) @@ -94,197 +124,131 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.7.4 (Oct 24, 2024) +# wolfSSL Release 5.7.6 (Dec 31, 2024) -Release 5.7.4 has been developed according to wolfSSL's development and QA +Release 5.7.6 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 +NOTE: + * --enable-heapmath is deprecated. + * In this release, the default cipher suite preference is updated to prioritize + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256 when enabled. + * This release adds a sanity check for including wolfssl/options.h or + user_settings.h. + PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. ## Vulnerabilities -* [Low] When the OpenSSL compatibility layer is enabled, certificate - verification behaved differently in wolfSSL than OpenSSL, in the - X509_STORE_add_cert() and X509_STORE_load_locations() implementations. - Previously, in cases where an application explicitly loaded an intermediate - certificate, wolfSSL was verifying only up to that intermediate certificate, - rather than verifying up to the root CA. This only affects use cases where the - API is called directly, and does not affect TLS connections. Users that call - the API X509_STORE_add_cert() or X509_STORE_load_locations() directly in their - applications are recommended to update the version of wolfSSL used or to have - additional sanity checks on certificates loaded into the X509_STORE when - verifying a certificate. (https://github.com/wolfSSL/wolfssl/pull/8087) - - -## PQC TLS Experimental Build Fix -* When using TLS with post quantum algorithms enabled, the connection uses a - smaller EC curve than agreed on. Users building with --enable-experimental and - enabling PQC cipher suites with TLS connections are recommended to update the - version of wolfSSL used. Thanks to Daniel Correa for the report. - (https://github.com/wolfSSL/wolfssl/pull/8084) +* [Med] An OCSP (non stapling) issue was introduced in wolfSSL version 5.7.4 + when performing OCSP requests for intermediate certificates in a certificate + chain. This affects only TLS 1.3 connections on the server side. It would not + impact other TLS protocol versions or connections that are not using the + traditional OCSP implementation. (Fix in pull request 8115) ## New Feature Additions -* RISC-V 64 new assembly optimizations added for SHA-256, SHA-512, ChaCha20, - Poly1305, and SHA-3 (PR 7758,7833,7818,7873,7916) -* Implement support for Connection ID (CID) with DTLS 1.2 (PR 7995) -* Add support for (DevkitPro)libnds (PR 7990) -* Add port for Mosquitto OSP (Open Source Project) (PR 6460) -* Add port for init sssd (PR 7781) -* Add port for eXosip2 (PR 7648) -* Add support for STM32G4 (PR 7997) -* Add support for MAX32665 and MAX32666 TPU HW and ARM ASM Crypto Callback - Support (PR 7777) -* Add support for building wolfSSL to be used in libspdm (PR 7869) -* Add port for use with Nucleus Plus 2.3 (PR 7732) -* Initial support for RFC5755 x509 attribute certificates (acerts). Enabled with - --enable-acert (PR 7926) -* PKCS#11 RSA Padding offload allows tokens to perform CKM_RSA_PKCS - (sign/encrypt), CKM_RSA_PKCS_PSS (sign), and CKM_RSA_PKCS_OAEP (encrypt). - (PR 7750) -* Added “new” and “delete” style functions for heap/pool allocation and freeing - of low level crypto structures (PR 3166 and 8089) +* Add support for RP2350 and improve RP2040 support, both with RNG optimizations + (PR 8153) +* Add support for STM32MP135F, including STM32CubeIDE support and HAL support + for SHA2/SHA3/AES/RNG/ECC optimizations. (PR 8223, 8231, 8241) +* Implement Renesas TSIP RSA Public Enc/Private support (PR 8122) +* Add support for Fedora/RedHat system-wide crypto-policies (PR 8205) +* Curve25519 generic keyparsing API added with wc_Curve25519KeyToDer and + wc_Curve25519KeyDecode (PR 8129) +* CRL improvements and update callback, added the functions + wolfSSL_CertManagerGetCRLInfo and wolfSSL_CertManagerSetCRLUpdate_Cb (PR 8006) +* For DTLS, add server-side stateless and CID quality-of-life API. (PR 8224) ## Enhancements and Optimizations -* Increase default max alt. names from 128 to 1024 (PR 7762) -* Added new constant time DH agree function wc_DhAgree_ct (PR 7802) -* Expanded compatibility layer with the API EVP_PKEY_is_a (PR 7804) -* Add option to disable cryptocb test software test using - --disable-cryptocb-sw-test (PR 7862) -* Add a call to certificate verify callback before checking certificate dates - (PR 7895) -* Expanded algorithms supported with the wolfCrypt CSharp wrapper. Adding - support for RNG, ECC(ECIES and ECDHE), RSA, ED25519/Curve25519, AES-GCM, and - Hashing (PR 3166) -* Expand MMCAU support for use with DES ECB (PR 7960) -* Update AES SIV to handle multiple associated data inputs (PR 7911) -* Remove HAVE_NULL_CIPHER from --enable-openssh (PR 7811) -* Removed duplicate if(NULL) checks when calling XFREE (macro does) (PR 7839) -* Set RSA_MIN_SIZE default to 2048 bits (PR 7923) -* Added support for wolfSSL to be used as the default TLS in the zephyr kernel - (PR 7731) -* Add enable provider build using --enable-wolfprovider with autotools (PR 7550) -* Renesas RX TSIP ECDSA support (PR 7685) -* Support DTLS1.3 downgrade when the server supports CID (PR 7841) -* Server-side checks OCSP even if it uses v2 multi (PR 7828) -* Add handling of absent hash params in PKCS7 bundle parsing and creation - (PR 7845) -* Add the use of w64wrapper for Poly1305, enabling Poly1305 to be used in - environments that do not have a word64 type (PR 7759) -* Update to the maxq10xx support (PR 7824) -* Add support for parsing over optional PKCS8 attributes (PR 7944) -* Add support for either side method with DTLS 1.3 (PR 8012) -* Added PKCS7 PEM support for parsing PEM data with BEGIN/END PKCS7 (PR 7704) -* Add CMake support for WOLFSSL_CUSTOM_CURVES (PR 7962) -* Add left-most wildcard matching support to X509_check_host() (PR 7966) -* Add option to set custom SKID with PKCS7 bundle creation (PR 7954) -* Building wolfSSL as a library with Ada and corrections to Alire manifest - (PR 7303,7940) -* Renesas RX72N support updated (PR 7849) -* New option WOLFSSL_COPY_KEY added to always copy the key to the SSL object - (PR 8005) -* Add the new option WOLFSSL_COPY_CERT to always copy the cert buffer for each - SSL object (PR 7867) -* Add an option to use AES-CBC with HMAC for default session ticket enc/dec. - Defaults to AES-128-CBC with HMAC-SHA256 (PR 7703) -* Memory usage improvements in wc_PRF, sha256 (for small code when many - registers are available) and sp_int objects (PR 7901) -* Change in the configure script to work around ">>" with no command. In older - /bin/sh it can be ambiguous, as used in OS’s such as FreeBSD 9.2 (PR 7876) -* Don't attempt to include system headers when not required (PR 7813) -* Certificates: DER encoding of ECC signature algorithm parameter is now - allowed to be NULL with a define (PR 7903) -* SP x86_64 asm: check for AVX2 support for VMs (PR 7979) -* Update rx64n support on gr-rose (PR 7889) -* Update FSP version to v5.4.0 for RA6M4 (PR 7994) -* Update TSIP driver version to v1.21 for RX65N RSK (PR 7993) -* Add a new crypto callback for RSA with padding (PR 7907) -* Replaced the use of pqm4 with wolfSSL implementations of Kyber/MLDSA - (PR 7924) -* Modernized memory fence support for C11 and clang (PR 7938) -* Add a CRL error override callback (PR 7986) -* Extend the X509 unknown extension callback for use with a user context - (PR 7730) -* Additional debug error tracing added with TLS (PR 7917) -* Added runtime support for library call stack traces with - –enable-debug-trace-errcodes=backtrace, using libbacktrace (PR 7846) -* Expanded C89 conformance (PR 8077) -* Expanded support for WOLFSSL_NO_MALLOC (PR 8065) -* Added support for cross-compilation of Linux kernel module (PR 7746) -* Updated Linux kernel module with support for kernel 6.11 and 6.12 (PR 7826) -* Introduce WOLFSSL_ASN_ALLOW_0_SERIAL to allow parsing of certificates with a - serial number of 0 (PR 7893) -* Add conditional repository_owner to all wolfSSL GitHub workflows (PR 7871) - -### Espressif / Arduino Updates -* Update wolfcrypt settings.h for Espressif ESP-IDF, template update (PR 7953) -* Update Espressif sha, util, mem, time helpers (PR 7955) -* Espressif _thread_local_start and _thread_local_end fix (PR 8030) -* Improve benchmark for Espressif devices (PR 8037) -* Introduce Espressif common CONFIG_WOLFSSL_EXAMPLE_NAME, Kconfig (PR 7866) -* Add wolfSSL esp-tls and Certificate Bundle Support for Espressif ESP-IDF - (PR 7936) -* Update wolfssl Release for Arduino (PR 7775) - -### Post Quantum Crypto Updates -* Dilithium: support fixed size arrays in dilithium_key (PR 7727) -* Dilithium: add option to use precalc with small sign (PR 7744) -* Allow Kyber to be built with FIPS (PR 7788) -* Allow Kyber asm to be used in the Linux kernel module (PR 7872) -* Dilithium, Kyber: Update to final specification (PR 7877) -* Dilithium: Support FIPS 204 Draft and Final Draft (PR 7909,8016) - -### ARM Assembly Optimizations -* ARM32 assembly optimizations added for ChaCha20 and Poly1305 (PR 8020) -* Poly1305 assembly optimizations improvements for Aarch64 (PR 7859) -* Poly1305 assembly optimizations added for Thumb-2 (PR 7939) -* Adding ARM ASM build option to STM32CubePack (PR 7747) -* Add ARM64 to Visual Studio Project (PR 8010) -* Kyber assembly optimizations for ARM32 and Aarch64 (PR 8040,7998) -* Kyber assembly optimizations for ARMv7E-M/ARMv7-M (PR 7706) +* Add a CMake dependency check for pthreads when required. (PR 8162) +* Update OS_Seed declarations for legacy compilers and FIPS modules (boundary + not affected). (PR 8170) +* Enable WOLFSSL_ALWAYS_KEEP_SNI by default when using --enable-jni. (PR 8283) +* Change the default cipher suite preference, prioritizing + TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256. (PR 7771) +* Add SRTP-KDF (FIPS module v6.0.0) to checkout script for release bundling + (PR 8215) +* Make library build when no hardware crypto available for Aarch64 (PR 8293) +* Update assembly code to avoid `uint*_t` types for better compatibility with + older C standards. (PR 8133) +* Add initial documentation for writing ASN template code to decode BER/DER. + (PR 8120) +* Perform full reduction in sc_muladd for EdDSA with Curve448 (PR 8276) +* Allow SHA-3 hardware cryptography instructions to be explicitly not used in + MacOS builds (PR 8282) +* Make Kyber and ML-KEM available individually and together. (PR 8143) +* Update configuration options to include Kyber/ML-KEM and fix defines used in + wolfSSL_get_curve_name. (PR 8183) +* Make GetShortInt available with WOLFSSL_ASN_EXTRA (PR 8149) +* Improved test coverage and minor improvements of X509 (PR 8176) +* Add sanity checks for configuration methods, ensuring the inclusion of + wolfssl/options.h or user_settings.h. (PR 8262) +* Enable support for building without TLS (NO_TLS). Provides reduced code size + option for non-TLS users who want features like the certificate manager or + compatibility layer. (PR 8273) +* Exposed get_verify functions with OPENSSL_EXTRA. (PR 8258) +* ML-DSA/Dilithium: obtain security level from DER when decoding (PR 8177) +* Implementation for using PKCS11 to retrieve certificate for SSL CTX (PR 8267) +* Add support for the RFC822 Mailbox attribute (PR 8280) +* Initialize variables and adjust types resolve warnings with Visual Studio in + Windows builds. (PR 8181) +* Refactors and expansion of opensslcoexist build (PR 8132, 8216, 8230) +* Add DTLS 1.3 interoperability, libspdm and DTLS CID interoperability tests + (PR 8261, 8255, 8245) +* Remove trailing error exit code in wolfSSL install setup script (PR 8189) +* Update Arduino files for wolfssl 5.7.4 (PR 8219) +* Improve Espressif SHA HW/SW mutex messages (PR 8225) +* Apply post-5.7.4 release updates for Espressif Managed Component examples + (PR 8251) +* Expansion of c89 conformance (PR 8164) +* Added configure option for additional sanity checks with --enable-faultharden + (PR 8289) +* Aarch64 ASM additions to check CPU features before hardware crypto instruction + use (PR 8314) ## Fixes -* ECC key load: fixes for certificates with parameters that are not default for - size (PR 7751) -* Fixes for building x86 in Visual Studio for non-windows OS (PR 7884) -* Fix for TLS v1.2 secret callback, incorrectly detecting bad master secret - (PR 7812) -* Fixes for PowerPC assembly use with Darwin and SP math all (PR 7931) -* Fix for detecting older versions of Mac OS when trying to link with - libdispatch (PR 7932) -* Fix for DTLS1.3 downgrade to DTLS1.2 when the server sends multiple handshake - packets combined into a single transmission. (PR 7840) -* Fix for OCSP to save the request if it was stored in ssl->ctx->certOcspRequest - (PR 7779) -* Fix to OCSP for searching for CA by key hash instead of ext. key id (PR 7934) -* Fix for staticmemory and singlethreaded build (PR 7737) -* Fix to not allow Shake128/256 with Xilinx AFALG (PR 7708) -* Fix to support PKCS11 without RSA key generation (PR 7738) -* Fix not calling the signing callback when using PK callbacks + TLS 1.3 - (PR 7761) -* Cortex-M/Thumb2 ASM fix label for IAR compiler (PR 7753) -* Fix with PKCS11 to iterate correctly over slotId (PR 7736) -* Stop stripping out the sequence header on the AltSigAlg extension (PR 7710) -* Fix ParseCRL_AuthKeyIdExt with ASN template to set extAuthKeyIdSet value - (PR 7742) -* Use max key length for PSK encrypt buffer size (PR 7707) -* DTLS 1.3 fix for size check to include headers and CID fixes (PR 7912,7951) -* Fix STM32 Hash FIFO and add support for STM32U5A9xx (PR 7787) -* Fix CMake build error for curl builds (PR 8021) -* SP Maths: PowerPC ASM fix to use XOR instead of LI (PR 8038) -* SSL loading of keys/certs: testing and fixes (PR 7789) -* Misc. fixes for Dilithium and Kyber (PR 7721,7765,7803,8027,7904) -* Fixes for building wolfBoot sources for PQ LMS/XMSS (PR 7868) -* Fixes for building with Kyber enabled using CMake and zephyr port (PR 7773) -* Fix for edge cases with session resumption with TLS 1.2 (PR 8097) -* Fix issue with ARM ASM with AES CFB/OFB not initializing the "left" member - (PR 8099) +* Fix a memory issue when using the compatibility layer with + WOLFSSL_GENERAL_NAME and handling registered ID types. (PR 8155) +* Fix a build issue with signature fault hardening when using public key + callbacks (HAVE_PK_CALLBACKS). (PR 8287) +* Fix for handling heap hint pointer properly when managing multiple WOLFSSL_CTX + objects and free’ing one of them (PR 8180) +* Fix potential memory leak in error case with Aria. (PR 8268) +* Fix Set_Verify flag behaviour on Ada wrapper. (PR 8256) +* Fix a compilation error with the NO_WOLFSSL_DIR flag. (PR 8294) +* Resolve a corner case for Poly1305 assembly code on Aarch64. (PR 8275) +* Fix incorrect version setting in CSRs. (PR 8136) +* Correct debugging output for cryptodev. (PR 8202) +* Fix for benchmark application use with /dev/crypto GMAC auth error due to size + of AAD (PR 8210) +* Add missing checks for the initialization of sp_int/mp_int with DSA to free + memory properly in error cases. (PR 8209) +* Fix return value of wolfSSL_CTX_set_tlsext_use_srtp (8252) +* Check Root CA by Renesas TSIP before adding it to ca-table (PR 8101) +* Prevent adding a certificate to the CA cache for Renesas builds if it does not + set CA:TRUE in basic constraints. (PR 8060) +* Fix attribute certificate holder entityName parsing. (PR 8166) +* Resolve build issues for configurations without any wolfSSL/openssl + compatibility layer headers. (PR 8182) +* Fix for building SP RSA small and RSA public only (PR 8235) +* Fix for Renesas RX TSIP RSA Sign/Verify with wolfCrypt only (PR 8206) +* Fix to ensure all files have settings.h included (like wc_lms.c) and guards + for building all `*.c` files (PR 8257 and PR 8140) +* Fix x86 target build issues in Visual Studio for non-Windows operating + systems. (PR 8098) +* Fix wolfSSL_X509_STORE_get0_objects to handle no CA (PR 8226) +* Properly handle reference counting when adding to the X509 store. (PR 8233) +* Fix for various typos and improper size used with FreeRTOS_bind in the Renesas + example. Thanks to Hongbo for the report on example issues. (PR 7537) +* Fix for potential heap use after free with wolfSSL_PEM_read_bio_PrivateKey. + Thanks to Peter for the issue reported. (PR 8139) + For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/examples/wolfssl_client/wolfssl_client.ino b/examples/wolfssl_client/wolfssl_client.ino index e4727dc..d6ef702 100644 --- a/examples/wolfssl_client/wolfssl_client.ino +++ b/examples/wolfssl_client/wolfssl_client.ino @@ -1,6 +1,6 @@ /* wolfssl_client.ino * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -85,6 +85,15 @@ Tested with: #include #endif +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ #include /* Important: make sure settings.h appears before any other wolfSSL headers */ #include diff --git a/examples/wolfssl_server/wolfssl_server.ino b/examples/wolfssl_server/wolfssl_server.ino index 387052c..c3820df 100644 --- a/examples/wolfssl_server/wolfssl_server.ino +++ b/examples/wolfssl_server/wolfssl_server.ino @@ -85,6 +85,15 @@ Tested with: #include #endif +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ #include /* Important: make sure settings.h appears before any other wolfSSL headers */ #include diff --git a/examples/wolfssl_version/wolfssl_version.ino b/examples/wolfssl_version/wolfssl_version.ino index ba34efb..a2f13fe 100644 --- a/examples/wolfssl_version/wolfssl_version.ino +++ b/examples/wolfssl_version/wolfssl_version.ino @@ -1,24 +1,55 @@ -#include -#include -#include - -/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ -#define SERIAL_BAUD 115200 - -/* Arduino setup */ -void setup() { - Serial.begin(SERIAL_BAUD); - while (!Serial) { - /* wait for serial port to connect. Needed for native USB port only */ - } - Serial.println(F("")); - Serial.println(F("")); - Serial.println(F("wolfSSL setup complete!")); -} - -/* Arduino main application loop. */ -void loop() { - Serial.print("wolfSSL Version: "); - Serial.println(LIBWOLFSSL_VERSION_STRING); - delay(60000); -} +/* wolfssl_server.ino + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + + /* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ +#include +#include + +/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ +#define SERIAL_BAUD 115200 + +/* Arduino setup */ +void setup() { + Serial.begin(SERIAL_BAUD); + while (!Serial) { + /* wait for serial port to connect. Needed for native USB port only */ + } + Serial.println(F("")); + Serial.println(F("")); + Serial.println(F("wolfSSL setup complete!")); +} + +/* Arduino main application loop. */ +void loop() { + Serial.print("wolfSSL Version: "); + Serial.println(LIBWOLFSSL_VERSION_STRING); + delay(60000); +} diff --git a/library.properties b/library.properties index d90b539..1f9456b 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.7.4 +version=5.7.6 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index ac4eb03..b265456 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -146,7 +146,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrSz = bio->wrSzReset; } else { @@ -163,7 +163,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && - !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { + !(bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY)) { /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, @@ -200,6 +200,7 @@ int wolfSSL_BIO_method_type(const WOLFSSL_BIO *b) } #ifndef WOLFCRYPT_ONLY +#ifndef NO_TLS /* Helper function to read from WOLFSSL_BIO_SSL type * * returns the number of bytes read on success @@ -231,10 +232,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return ret; } +#endif /* !NO_TLS */ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { @@ -249,7 +251,7 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) } return sz; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY */ /* Used to read data from a WOLFSSL_BIO structure @@ -331,7 +333,7 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) ret = wolfSSL_BIO_SSL_read(bio, buf, len, front); #else WOLFSSL_MSG("WOLFSSL_BIO_SSL used with WOLFCRYPT_ONLY"); @@ -500,7 +502,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } #endif /* WOLFSSL_BASE64_ENCODE */ -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* Helper function for writing to a WOLFSSL_BIO_SSL type * * returns the amount written in bytes on success @@ -531,7 +533,7 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, } return ret; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY && !NO_TLS */ /* Writes to a WOLFSSL_BIO_BIO type. * @@ -601,7 +603,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("one of input parameters is null"); return WOLFSSL_FAILURE; } - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { return WOLFSSL_FAILURE; } @@ -642,7 +644,7 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; @@ -746,7 +748,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* already got eof, again is error */ if (front->eof) { ret = WOLFSSL_FATAL_ERROR; @@ -823,7 +825,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) bio = bio->next; } -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) exit_chain: #endif @@ -866,23 +868,23 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) } switch(cmd) { - case BIO_CTRL_PENDING: - case BIO_CTRL_WPENDING: + case WOLFSSL_BIO_CTRL_PENDING: + case WOLFSSL_BIO_CTRL_WPENDING: ret = (long)wolfSSL_BIO_ctrl_pending(bio); break; - case BIO_CTRL_INFO: + case WOLFSSL_BIO_CTRL_INFO: ret = (long)wolfSSL_BIO_get_mem_data(bio, parg); break; - case BIO_CTRL_FLUSH: + case WOLFSSL_BIO_CTRL_FLUSH: ret = (long)wolfSSL_BIO_flush(bio); break; - case BIO_CTRL_RESET: + case WOLFSSL_BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; #ifdef WOLFSSL_HAVE_BIO_ADDR - case BIO_CTRL_DGRAM_CONNECT: - case BIO_CTRL_DGRAM_SET_PEER: + case WOLFSSL_BIO_CTRL_DGRAM_CONNECT: + case WOLFSSL_BIO_CTRL_DGRAM_SET_PEER: { socklen_t addr_size; if (parg == NULL) { @@ -899,7 +901,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) break; } - case BIO_CTRL_DGRAM_SET_CONNECTED: + case WOLFSSL_BIO_CTRL_DGRAM_SET_CONNECTED: if (parg == NULL) { wolfSSL_BIO_ADDR_clear(&bio->peer_addr); bio->connected = 0; @@ -916,7 +918,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) ret = WOLFSSL_SUCCESS; break; - case BIO_CTRL_DGRAM_QUERY_MTU: + case WOLFSSL_BIO_CTRL_DGRAM_QUERY_MTU: ret = 0; /* not implemented */ break; @@ -1371,7 +1373,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) int closeFlag) { if (!bio || !bufMem || - (closeFlag != BIO_NOCLOSE && closeFlag != BIO_CLOSE)) + (closeFlag != WOLFSSL_BIO_NOCLOSE && closeFlag != WOLFSSL_BIO_CLOSE)) return BAD_FUNC_ARG; if (bio->mem_buf) @@ -1379,7 +1381,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) wolfSSL_BUF_MEM_free(bio->mem_buf); bio->mem_buf = bufMem; - bio->shutdown = closeFlag; + bio->shutdown = closeFlag ? WOLFSSL_BIO_CLOSE : WOLFSSL_BIO_NOCLOSE; bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; @@ -1717,7 +1719,7 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrIdx = bio->wrSzReset; bio->wrSz = bio->wrSzReset; } @@ -1826,7 +1828,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + if (bio->ptr.fh != XBADFILE && bio->shutdown == WOLFSSL_BIO_CLOSE) { XFCLOSE(bio->ptr.fh); } @@ -1839,7 +1841,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } - bio->shutdown = BIO_CLOSE; + bio->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2201,7 +2203,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio->method != NULL && bio->method->ctrlCb != NULL) { WOLFSSL_MSG("Calling custom BIO flush callback"); - return (int)bio->method->ctrlCb(bio, BIO_CTRL_FLUSH, 0, NULL); + return (int)bio->method->ctrlCb(bio, WOLFSSL_BIO_CTRL_FLUSH, 0, NULL); } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) @@ -2387,7 +2389,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->type = WOLFSSL_BIO_SOCKET; } else { - BIO_free(bio); + wolfSSL_BIO_free(bio); bio = NULL; } } @@ -2477,7 +2479,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2506,7 +2508,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; @@ -2516,7 +2518,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } /* Create a socket BIO for using the accept'ed connection */ - new_bio = wolfSSL_BIO_new_socket(newfd, BIO_CLOSE); + new_bio = wolfSSL_BIO_new_socket(newfd, WOLFSSL_BIO_CLOSE); if (new_bio == NULL) { WOLFSSL_MSG("wolfSSL_BIO_new_socket error"); CloseSocket(newfd); @@ -2560,6 +2562,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return ret; } +#ifndef NO_TLS long wolfSSL_BIO_do_handshake(WOLFSSL_BIO *b) { WOLFSSL_ENTER("wolfSSL_BIO_do_handshake"); @@ -2595,7 +2598,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (b->ptr.ssl != NULL) { int rc = wolfSSL_shutdown(b->ptr.ssl); - if (rc == SSL_SHUTDOWN_NOT_DONE) { + if (rc == WOLFSSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ wolfSSL_shutdown(b->ptr.ssl); @@ -2605,6 +2608,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("BIO has no SSL pointer set."); } } +#endif long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { @@ -2682,7 +2686,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else wolfSSL_set_connect_state(ssl); } - if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, BIO_CLOSE) != + if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to set SSL pointer in BIO."); err = 1; @@ -2831,13 +2835,20 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) #else bio->method = method; #endif - bio->shutdown = BIO_CLOSE; /* default to close things */ + bio->shutdown = WOLFSSL_BIO_CLOSE; /* default to close things */ if ((bio->type == WOLFSSL_BIO_SOCKET) || (bio->type == WOLFSSL_BIO_DGRAM)) { bio->num.fd = SOCKET_INVALID; - } else { + } + else if (bio->type == WOLFSSL_BIO_FILE) { +#ifndef NO_FILESYSTEM + bio->ptr.fh = XBADFILE; +#endif + bio->num.fd = SOCKET_INVALID; + } + else { bio->num.length = 0; } bio->init = 1; @@ -2916,7 +2927,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { XMEMCPY(bio->ptr.mem_buf_data, buf, len); - bio->flags |= BIO_FLAGS_MEM_RDONLY; + bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2994,7 +3005,9 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #ifndef NO_FILESYSTEM - if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { + if (bio->type == WOLFSSL_BIO_FILE && + bio->shutdown == WOLFSSL_BIO_CLOSE) + { if (bio->ptr.fh) { XFCLOSE(bio->ptr.fh); } @@ -3007,7 +3020,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #endif - if (bio->shutdown != BIO_NOCLOSE) { + if (bio->shutdown != WOLFSSL_BIO_NOCLOSE) { if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr.mem_buf_data != NULL) { @@ -3409,7 +3422,7 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) if (fp == XBADFILE) return WOLFSSL_BAD_FILE; - if (wolfSSL_BIO_set_fp(b, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(b, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); return WOLFSSL_BAD_FILE; } @@ -3446,7 +3459,7 @@ WOLFSSL_BIO *wolfSSL_BIO_new_file(const char *filename, const char *mode) return bio; } - if (wolfSSL_BIO_set_fp(bio, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); wolfSSL_BIO_free(bio); bio = NULL; diff --git a/src/src/conf.c b/src/src/conf.c index c9a35c1..b614148 100644 --- a/src/src/conf.c +++ b/src/src/conf.c @@ -202,7 +202,10 @@ long wolfSSL_TXT_DB_write(WOLFSSL_BIO *out, WOLFSSL_TXT_DB *db) return WOLFSSL_FAILURE; } } - idx[-1] = '\n'; + if (idx > buf) + idx[-1] = '\n'; + else + return WOLFSSL_FAILURE; sz = (int)(idx - buf); if (wolfSSL_BIO_write(out, buf, sz) != sz) { @@ -603,7 +606,7 @@ char *wolfSSL_NCONF_get_string(const WOLFSSL_CONF *conf, return NULL; } -int wolfSSL_NCONF_get_number(const CONF *conf, const char *group, +int wolfSSL_NCONF_get_number(const WOLFSSL_CONF *conf, const char *group, const char *name, long *result) { char *str; @@ -1582,7 +1585,7 @@ int wolfSSL_CONF_cmd_value_type(WOLFSSL_CONF_CTX *cctx, const char *cmd) confcmd = wolfssl_conf_find_cmd(cctx, cmd); if (confcmd == NULL) - return SSL_CONF_TYPE_UNKNOWN; + return WOLFSSL_CONF_TYPE_UNKNOWN; return (int)confcmd->data_type; } @@ -1594,21 +1597,21 @@ int wolfSSL_CONF_cmd_value_type(WOLFSSL_CONF_CTX *cctx, const char *cmd) ******************************************************************************/ #if defined(OPENSSL_EXTRA) -OPENSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void) +WOLFSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void) { - OPENSSL_INIT_SETTINGS* init = (OPENSSL_INIT_SETTINGS*)XMALLOC( - sizeof(OPENSSL_INIT_SETTINGS), NULL, DYNAMIC_TYPE_OPENSSL); + WOLFSSL_INIT_SETTINGS* init = (WOLFSSL_INIT_SETTINGS*)XMALLOC( + sizeof(WOLFSSL_INIT_SETTINGS), NULL, DYNAMIC_TYPE_OPENSSL); return init; } -void wolfSSL_OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS* init) +void wolfSSL_OPENSSL_INIT_free(WOLFSSL_INIT_SETTINGS* init) { XFREE(init, NULL, DYNAMIC_TYPE_OPENSSL); } #ifndef NO_WOLFSSL_STUB -int wolfSSL_OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS* init, +int wolfSSL_OPENSSL_INIT_set_config_appname(WOLFSSL_INIT_SETTINGS* init, char* appname) { (void)init; diff --git a/src/src/crl.c b/src/src/crl.c index 5e359c7..b78002c 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -311,7 +311,6 @@ static int FindRevokedSerial(RevokedCert* rc, byte* serial, int serialSz, #else (void)totalCerts; /* search in the linked list*/ - while (rc) { if (serialHash == NULL) { if (rc->serialSz == serialSz && @@ -560,12 +559,45 @@ int CheckCertCRL(WOLFSSL_CRL* crl, DecodedCert* cert) NULL, cert->extCrlInfo, cert->extCrlInfoSz, issuerName); } +#ifdef HAVE_CRL_UPDATE_CB +static void SetCrlInfo(CRL_Entry* entry, CrlInfo *info) +{ + info->issuerHash = (byte *)entry->issuerHash; + info->issuerHashLen = CRL_DIGEST_SIZE; + info->lastDate = (byte *)entry->lastDate; + info->lastDateMaxLen = MAX_DATE_SIZE; + info->lastDateFormat = entry->lastDateFormat; + info->nextDate = (byte *)entry->nextDate; + info->nextDateMaxLen = MAX_DATE_SIZE; + info->nextDateFormat = entry->nextDateFormat; + info->crlNumber = (sword32)entry->crlNumber; +} + +static void SetCrlInfoFromDecoded(DecodedCRL* entry, CrlInfo *info) +{ + info->issuerHash = (byte *)entry->issuerHash; + info->issuerHashLen = SIGNER_DIGEST_SIZE; + info->lastDate = (byte *)entry->lastDate; + info->lastDateMaxLen = MAX_DATE_SIZE; + info->lastDateFormat = entry->lastDateFormat; + info->nextDate = (byte *)entry->nextDate; + info->nextDateMaxLen = MAX_DATE_SIZE; + info->nextDateFormat = entry->nextDateFormat; + info->crlNumber = (sword32)entry->crlNumber; +} +#endif /* Add Decoded CRL, 0 on success */ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, int verified) { CRL_Entry* crle = NULL; + CRL_Entry* curr = NULL; + CRL_Entry* prev = NULL; +#ifdef HAVE_CRL_UPDATE_CB + CrlInfo old; + CrlInfo cnew; +#endif WOLFSSL_ENTER("AddCRL"); @@ -594,8 +626,43 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, return BAD_MUTEX_E; } - crle->next = crl->crlList; - crl->crlList = crle; + for (curr = crl->crlList; curr != NULL; curr = curr->next) { + if (XMEMCMP(curr->issuerHash, crle->issuerHash, CRL_DIGEST_SIZE) == 0) { + if (crle->crlNumber <= curr->crlNumber) { + WOLFSSL_MSG("Same or newer CRL entry already exists"); + CRL_Entry_free(crle, crl->heap); + wc_UnLockRwLock(&crl->crlLock); + return BAD_FUNC_ARG; + } + + crle->next = curr->next; + if (prev != NULL) { + prev->next = crle; + } + else { + crl->crlList = crle; + } + +#ifdef HAVE_CRL_UPDATE_CB + if (crl->cm && crl->cm->cbUpdateCRL != NULL) { + SetCrlInfo(curr, &old); + SetCrlInfo(crle, &cnew); + crl->cm->cbUpdateCRL(&old, &cnew); + } +#endif + + break; + } + prev = curr; + } + + if (curr != NULL) { + CRL_Entry_free(curr, crl->heap); + } + else { + crle->next = crl->crlList; + crl->crlList = crle; + } wc_UnLockRwLock(&crl->crlLock); /* Avoid heap-use-after-free after crl->crlList is released */ crl->currentEntry = NULL; @@ -686,6 +753,87 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, return ret ? ret : WOLFSSL_SUCCESS; /* convert 0 to WOLFSSL_SUCCESS */ } +#ifdef HAVE_CRL_UPDATE_CB +/* Fill out CRL info structure, WOLFSSL_SUCCESS on ok */ +int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, + long sz, int type) +{ + int ret = WOLFSSL_SUCCESS; + const byte* myBuffer = buff; /* if DER ok, otherwise switch */ + DerBuffer* der = NULL; + CRL_Entry* crle = NULL; +#ifdef WOLFSSL_SMALL_STACK + DecodedCRL* dcrl; +#else + DecodedCRL dcrl[1]; +#endif + + WOLFSSL_ENTER("GetCRLInfo"); + + if (crl == NULL || info == NULL || buff == NULL || sz == 0) + return BAD_FUNC_ARG; + + if (type == WOLFSSL_FILETYPE_PEM) { + #ifdef WOLFSSL_PEM_TO_DER + ret = PemToDer(buff, sz, CRL_TYPE, &der, NULL, NULL, NULL); + if (ret == 0) { + myBuffer = der->buffer; + sz = der->length; + } + else { + WOLFSSL_MSG("Pem to Der failed"); + FreeDer(&der); + return -1; + } + #else + ret = NOT_COMPILED_IN; + #endif + } + +#ifdef WOLFSSL_SMALL_STACK + dcrl = (DecodedCRL*)XMALLOC(sizeof(DecodedCRL), NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (dcrl == NULL) { + FreeDer(&der); + return MEMORY_E; + } +#endif + + crle = CRL_Entry_new(crl->heap); + if (crle == NULL) { + WOLFSSL_MSG("alloc CRL Entry failed"); + #ifdef WOLFSSL_SMALL_STACK + XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); + #endif + FreeDer(&der); + return MEMORY_E; + } + + InitDecodedCRL(dcrl, crl->heap); + ret = ParseCRL(crle->certs, dcrl, myBuffer, (word32)sz, + 0, crl->cm); + if (ret != 0 && !(ret == WC_NO_ERR_TRACE(ASN_CRL_NO_SIGNER_E))) { + WOLFSSL_MSG("ParseCRL error"); + CRL_Entry_free(crle, crl->heap); + crle = NULL; + } + else { + SetCrlInfoFromDecoded((DecodedCRL*)dcrl, info); + } + + FreeDecodedCRL(dcrl); + +#ifdef WOLFSSL_SMALL_STACK + XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + FreeDer(&der); + CRL_Entry_free(crle, crl->heap); + + return ret ? ret : WOLFSSL_SUCCESS; /* convert 0 to WOLFSSL_SUCCESS */ +} +#endif + #if defined(OPENSSL_EXTRA) && defined(HAVE_CRL) /* helper function to create a new dynamic WOLFSSL_X509_CRL structure */ static WOLFSSL_X509_CRL* wolfSSL_X509_crl_new(WOLFSSL_CERT_MANAGER* cm) @@ -784,7 +932,7 @@ static CRL_Entry* DupCRL_Entry(const CRL_Entry* ent, void* heap) #endif if (dupl->toBeSigned == NULL || dupl->signature == NULL #ifdef WC_RSA_PSS - /* allow sigParamsSz is zero and malloc(0) to return NULL */ + /* allow sigParamsSz is zero and XMALLOC(0) to return NULL */ || (dupl->sigParams == NULL && dupl->sigParamsSz != 0) #endif ) { @@ -954,7 +1102,7 @@ int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *store, WOLFSSL_X509_CRL *newc } if (crl != newcrl && wc_LockRwLock_Rd(&newcrl->crlLock) != 0) { - WOLFSSL_MSG("wc_LockRwLock_Wr failed"); + WOLFSSL_MSG("wc_LockRwLock_Rd failed"); wc_UnLockRwLock(&crl->crlLock); return BAD_MUTEX_E; } diff --git a/src/src/dtls.c b/src/src/dtls.c index 5b2356a..ae27804 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -101,6 +101,15 @@ void DtlsResetState(WOLFSSL* ssl) ssl->options.tls = 0; ssl->options.tls1_1 = 0; ssl->options.tls1_3 = 0; +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + ssl->buffers.dtlsCtx.processingPendingRecord = 0; + /* Clear the pending peer in case user set */ + XFREE(ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->heap, + DYNAMIC_TYPE_SOCKADDR); + ssl->buffers.dtlsCtx.pendingPeer.sa = NULL; + ssl->buffers.dtlsCtx.pendingPeer.sz = 0; + ssl->buffers.dtlsCtx.pendingPeer.bufSz = 0; +#endif } int DtlsIgnoreError(int err) @@ -221,6 +230,7 @@ static int CreateDtls12Cookie(const WOLFSSL* ssl, const WolfSSL_CH* ch, ssl->buffers.dtlsCookieSecret.buffer, ssl->buffers.dtlsCookieSecret.length); if (ret == 0) { + /* peerLock not necessary. Still in handshake phase. */ ret = wc_HmacUpdate(&cookieHmac, (const byte*)ssl->buffers.dtlsCtx.peer.sa, ssl->buffers.dtlsCtx.peer.sz); @@ -716,9 +726,14 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) * and if they don't match we will error out there anyway. */ byte modes; + /* TLSX_PreSharedKey_Parse_ClientHello uses word16 length */ + if (tlsx.size > WOLFSSL_MAX_16BIT) { + ERROR_OUT(BUFFER_ERROR, dtls13_cleanup); + } + /* Ask the user for the ciphersuite matching this identity */ if (TLSX_PreSharedKey_Parse_ClientHello(&parsedExts, - tlsx.elements, tlsx.size, ssl->heap) == 0) + tlsx.elements, (word16)tlsx.size, ssl->heap) == 0) FindPskSuiteFromExt(ssl, parsedExts, &pskInfo, &suites); /* Revert to full handshake if PSK parsing failed */ @@ -729,8 +744,8 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) goto dtls13_cleanup; if (!tlsxFound) ERROR_OUT(PSK_KEY_ERROR, dtls13_cleanup); - ret = TLSX_PskKeyModes_Parse_Modes(tlsx.elements, tlsx.size, - client_hello, &modes); + ret = TLSX_PskKeyModes_Parse_Modes(tlsx.elements, (word16)tlsx.size, + client_hello, &modes); if (ret != 0) goto dtls13_cleanup; if ((modes & (1 << PSK_DHE_KE)) && @@ -1103,6 +1118,26 @@ static int DtlsCidGet(WOLFSSL* ssl, unsigned char* buf, int bufferSz, int rx) return WOLFSSL_SUCCESS; } +static int DtlsCidGet0(WOLFSSL* ssl, unsigned char** cid, int rx) +{ + ConnectionID* id; + CIDInfo* info; + + if (ssl == NULL || cid == NULL) + return BAD_FUNC_ARG; + + info = DtlsCidGetInfo(ssl); + if (info == NULL) + return WOLFSSL_FAILURE; + + id = rx ? info->rx : info->tx; + if (id == NULL || id->length == 0) + return WOLFSSL_SUCCESS; + + *cid = id->id; + return WOLFSSL_SUCCESS; +} + static CIDInfo* DtlsCidGetInfoFromExt(byte* ext) { WOLFSSL** sslPtr; @@ -1361,6 +1396,11 @@ int wolfSSL_dtls_cid_get_rx(WOLFSSL* ssl, unsigned char* buf, return DtlsCidGet(ssl, buf, bufferSz, 1); } +int wolfSSL_dtls_cid_get0_rx(WOLFSSL* ssl, unsigned char** cid) +{ + return DtlsCidGet0(ssl, cid, 1); +} + int wolfSSL_dtls_cid_get_tx_size(WOLFSSL* ssl, unsigned int* size) { return DtlsCidGetSize(ssl, size, 0); @@ -1372,10 +1412,40 @@ int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buf, return DtlsCidGet(ssl, buf, bufferSz, 0); } +int wolfSSL_dtls_cid_get0_tx(WOLFSSL* ssl, unsigned char** cid) +{ + return DtlsCidGet0(ssl, cid, 0); +} + int wolfSSL_dtls_cid_max_size(void) { return DTLS_CID_MAX_SIZE; } + +const unsigned char* wolfSSL_dtls_cid_parse(const unsigned char* msg, + unsigned int msgSz, unsigned int cidSz) +{ + /* we need at least the first byte to check version */ + if (msg == NULL || cidSz == 0 || msgSz < OPAQUE8_LEN + cidSz) + return NULL; + if (msg[0] == dtls12_cid) { + /* DTLS 1.2 CID packet */ + if (msgSz < DTLS_RECORD_HEADER_SZ + cidSz) + return NULL; + /* content type(1) + version(2) + epoch(2) + sequence(6) */ + return msg + ENUM_LEN + VERSION_SZ + OPAQUE16_LEN + OPAQUE16_LEN + + OPAQUE32_LEN; + } +#ifdef WOLFSSL_DTLS13 + else if (Dtls13UnifiedHeaderCIDPresent(msg[0])) { + /* DTLS 1.3 CID packet */ + if (msgSz < OPAQUE8_LEN + cidSz) + return NULL; + return msg + OPAQUE8_LEN; + } +#endif + return NULL; +} #endif /* WOLFSSL_DTLS_CID */ byte DtlsGetCidTxSize(WOLFSSL* ssl) @@ -1408,6 +1478,11 @@ byte DtlsGetCidRxSize(WOLFSSL* ssl) #endif } +byte wolfSSL_is_stateful(WOLFSSL* ssl) +{ + return (byte)(ssl != NULL ? ssl->options.dtlsStateful : 0); +} + #endif /* WOLFSSL_DTLS */ #endif /* WOLFCRYPT_ONLY */ diff --git a/src/src/dtls13.c b/src/src/dtls13.c index 6f2f014..161ce4f 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -260,7 +260,8 @@ static int Dtls13GetRnMask(WOLFSSL* ssl, const byte* ciphertext, byte* mask, if (c->aes == NULL) return BAD_STATE_E; #if !defined(HAVE_SELFTEST) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) \ + || defined(WOLFSSL_LINUXKM)) return wc_AesEncryptDirect(c->aes, mask, ciphertext); #else wc_AesEncryptDirect(c->aes, mask, ciphertext); @@ -1150,6 +1151,11 @@ static int Dtls13UnifiedHeaderParseCID(WOLFSSL* ssl, byte flags, return 0; } +int Dtls13UnifiedHeaderCIDPresent(byte flags) +{ + return Dtls13IsUnifiedHeader(flags) && (flags & DTLS13_CID_BIT); +} + #else #define Dtls13AddCID(a, b, c, d) 0 #define Dtls13UnifiedHeaderParseCID(a, b, c, d, e) 0 diff --git a/src/src/internal.c b/src/src/internal.c index a152022..666de86 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -92,12 +92,6 @@ * pair */ - -#ifdef EXTERNAL_OPTS_OPENVPN -#error EXTERNAL_OPTS_OPENVPN should not be defined\ - when building wolfSSL -#endif - #ifndef WOLFCRYPT_ONLY #include @@ -197,7 +191,7 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS #else #define SSL_TICKET_CTX(ssl) ssl->ctx->ticketEncCtx #endif - #if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) + #if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_TLS) static int TicketEncCbCtx_Init(WOLFSSL_CTX* ctx, TicketEncCbCtx* keyCtx); static void TicketEncCbCtx_Free(TicketEncCbCtx* keyCtx); @@ -796,16 +790,16 @@ static int ExportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver, ssl->specs.bulk_cipher_algorithm == wolfssl_aes) { byte *pt = (byte*)ssl->encrypt.aes->reg; - if ((idx + 2*AES_BLOCK_SIZE) > len) { + if ((idx + 2*WC_AES_BLOCK_SIZE) > len) { WOLFSSL_MSG("Can not fit AES state into buffer"); return BUFFER_E; } - XMEMCPY(exp + idx, pt, AES_BLOCK_SIZE); - idx += AES_BLOCK_SIZE; + XMEMCPY(exp + idx, pt, WC_AES_BLOCK_SIZE); + idx += WC_AES_BLOCK_SIZE; pt = (byte*)ssl->decrypt.aes->reg; - XMEMCPY(exp + idx, pt, AES_BLOCK_SIZE); - idx += AES_BLOCK_SIZE; + XMEMCPY(exp + idx, pt, WC_AES_BLOCK_SIZE); + idx += WC_AES_BLOCK_SIZE; } WOLFSSL_LEAVE("ExportCipherSpecState", idx); @@ -1048,12 +1042,12 @@ static int ImportCipherSpecState(WOLFSSL* ssl, const byte* exp, word32 len, if (type == WOLFSSL_EXPORT_TLS && ssl->specs.bulk_cipher_algorithm == wolfssl_aes) { byte *pt = (byte*)ssl->encrypt.aes->reg; - XMEMCPY(pt, exp + idx, AES_BLOCK_SIZE); - idx += AES_BLOCK_SIZE; + XMEMCPY(pt, exp + idx, WC_AES_BLOCK_SIZE); + idx += WC_AES_BLOCK_SIZE; pt = (byte*)ssl->decrypt.aes->reg; - XMEMCPY(pt, exp + idx, AES_BLOCK_SIZE); - idx += AES_BLOCK_SIZE; + XMEMCPY(pt, exp + idx, WC_AES_BLOCK_SIZE); + idx += WC_AES_BLOCK_SIZE; } WOLFSSL_LEAVE("ImportCipherSpecState", idx); @@ -2108,7 +2102,7 @@ int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf, word32* sz, /* possible AES state needed */ if (type == WOLFSSL_EXPORT_TLS) { - *sz += AES_BLOCK_SIZE*2; + *sz += WC_AES_BLOCK_SIZE*2; } ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); } @@ -2270,6 +2264,225 @@ int InitSSL_Side(WOLFSSL* ssl, word16 side) } #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) +/* Check the wolfssl method meets minimum requirements for + * the given security level. + * + * Returns 0 if method meets security level. + * Returns CRYPTO_POLICY_FORBIDDEN otherwise. + * */ +static int wolfSSL_crypto_policy_method_allowed(WOLFSSL_METHOD * method, + int level) +{ + if (level == 0) { + /* permissive, no restrictions. */ + return 0; + } + + #ifdef WOLFSSL_DTLS + if (method->version.major == DTLS_MAJOR) { + if (method->version.minor == DTLS_MINOR) { + /* sec level must be 1 or lower. */ + if (level > 1) { + return CRYPTO_POLICY_FORBIDDEN; + } + } + } + else + #endif /* WOLFSSL_DTLS */ + { + if (method->version.minor == SSLv3_MINOR) { + /* sec level must be 0. */ + if (level > 0) { + return CRYPTO_POLICY_FORBIDDEN; + } + } + else if (method->version.minor == TLSv1_MINOR || + method->version.minor == TLSv1_1_MINOR) { + /* sec level must be 1 or lower. */ + if (level > 1) { + return CRYPTO_POLICY_FORBIDDEN; + } + } + } + + /* nothing else to check, all other combinations ok. */ + + return 0; +} + +/* Configure the CTX to conform to the security policy. + * + * Also, check the WOLFSSL_METHOD against the supplied security + * level. + * + * Returns CRYPTO_POLICY_FORBIDDEN if not allowed per policy. + * Returns BAD_FUNC_ARG on null args. + * Returns 0 if ok. + * */ +int wolfSSL_crypto_policy_init_ctx(WOLFSSL_CTX * ctx, + WOLFSSL_METHOD * method) +{ + byte minDowngrade = 0x00; + #ifdef WOLFSSL_DTLS + int dtls = 0; + #endif /* WOLFSSL_DTLS */ + int level = 0; + #if !defined(NO_DH) || !defined(NO_RSA) + word16 minKeySz = 0; /* minimum DH or RSA key size */ + #endif /* !NO_DH || !NO_RSA*/ + #ifdef HAVE_ECC + short minEccKeySz = 0; /* minimum allowed ECC key size */ + #endif /* HAVE_ECC */ + + + if (ctx == NULL || method == NULL) { + return BAD_FUNC_ARG; + } + + #ifdef WOLFSSL_DTLS + dtls = (method->version.major == DTLS_MAJOR); + #endif /* WOLFSSL_DTLS */ + + /* get the crypto policy security level. */ + level = wolfSSL_crypto_policy_get_level(); + + if (level < 0 || level > 5) { + WOLFSSL_MSG_EX("crypto_policy_init_ctx: invalid level: %d", level); + return BAD_FUNC_ARG; + } + + /* Check requested method per security level. */ + if (wolfSSL_crypto_policy_method_allowed(method, level) != 0) { + WOLFSSL_MSG_EX("crypto_policy_init_ctx: " + "method=%d, SECLEVEL=%d combination not allowed", + method->version.minor, level); + return CRYPTO_POLICY_FORBIDDEN; + } + + /* Set appropriate min downgrade per security level. */ + #ifdef WOLFSSL_DTLS + if (dtls) { + switch (level) { + case 1: + minDowngrade = DTLS_MINOR; + break; + case 2: + case 3: + case 4: + case 5: + minDowngrade = DTLSv1_2_MINOR; + break; + case 0: + default: + /* Permissive, no restrictions. Allow defaults. */ + minDowngrade = WOLFSSL_MIN_DTLS_DOWNGRADE; + break; + } + } + else + #endif /* WOLFSSL_DTLS */ + { + switch (level) { + case 1: + /* prohibit SSLv3 and lower. */ + minDowngrade = TLSv1_MINOR; + break; + case 2: + case 3: + case 4: + case 5: + /* prohibit TLSv1_1 and lower. */ + minDowngrade = TLSv1_2_MINOR; + break; + case 0: + default: + ctx->minDowngrade = WOLFSSL_MIN_DOWNGRADE; + break; + } + } + + /* Set min RSA and DH key size. */ + #if !defined(NO_DH) || !defined(NO_RSA) + switch (level) { + case 1: + minKeySz = 128; /* 1024 bits / 8 */ + break; + case 2: + minKeySz = 256; /* 2048 bits / 8 */ + break; + case 3: + minKeySz = 384; /* 3072 bits / 8 */ + break; + case 4: + minKeySz = 960; /* 7680 bits / 8 */ + break; + case 5: + minKeySz = 1920; /* 15360 bits / 8 */ + break; + case 0: + default: + break; + } + #endif /* !NO_DH || !NO_RSA*/ + + /* Set min ECC key size. */ + #ifdef HAVE_ECC + switch (level) { + case 1: + minEccKeySz = 20; /* 160 bits / 8 */ + break; + case 2: + minEccKeySz = 28; /* 224 bits / 8 */ + break; + case 3: + minEccKeySz = 32; /* 256 bits / 8 */ + break; + case 4: + minEccKeySz = 48; /* 384 bits / 8 */ + break; + case 5: + minEccKeySz = 64; /* 512 bits / 8 */ + break; + default: + case 0: + break; + } + #endif /* HAVE_ECC */ + + /* Finally set the ctx values. */ + ctx->minDowngrade = minDowngrade; + ctx->secLevel = level; + ctx->method = method; + + #if !defined(NO_DH) || !defined(NO_RSA) + if (minKeySz > 0) { + #ifndef NO_DH + if (minKeySz > MAX_DHKEY_SZ) { + WOLFSSL_MSG_EX("crypto_policy_init_ctx: minKeySz=%d, " + "but MAX_DHKEY_SZ=%d", + minKeySz, MAX_DHKEY_SZ); + return CRYPTO_POLICY_FORBIDDEN; + } + ctx->minDhKeySz = minKeySz; + ctx->maxDhKeySz = MAX_DHKEY_SZ; + #endif /* NO_DH */ + #ifndef NO_RSA + ctx->minRsaKeySz = minKeySz; + #endif /* NO_RSA */ + } + #endif /* !NO_DH || !NO_RSA*/ + + #ifdef HAVE_ECC + if (minEccKeySz > 0) { + ctx->minEccKeySz = minEccKeySz; + } + #endif /* HAVE_ECC */ + + return 0; +} +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + /* Initialize SSL context, return 0 on success */ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) { @@ -2297,7 +2510,7 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) ctx->minDowngrade = WOLFSSL_MIN_DOWNGRADE; } - wolfSSL_RefInit(&ctx->ref, &ret); + wolfSSL_RefWithMutexInit(&ctx->ref, &ret); #ifdef WOLFSSL_REFCNT_ERROR_RETURN if (ret < 0) { WOLFSSL_MSG("Mutex error on CTX init"); @@ -2323,6 +2536,7 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) #ifndef NO_RSA ctx->minRsaKeySz = MIN_RSAKEY_SZ; #endif + #ifdef HAVE_ECC ctx->minEccKeySz = MIN_ECCKEY_SZ; ctx->eccTempKeySz = ECDHE_SIZE; @@ -2499,7 +2713,7 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */ #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) -#ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB +#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_TLS) ret = TicketEncCbCtx_Init(ctx, &ctx->ticketKeyCtx); if (ret != 0) return ret; ctx->ticketEncCb = DefTicketEncCb; @@ -2547,6 +2761,14 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) ctx->doAppleNativeCertValidationFlag = 0; #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */ +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + ret = wolfSSL_crypto_policy_init_ctx(ctx, method); + if (ret != 0) { + WOLFSSL_MSG_EX("crypto_policy_init_ctx returned %d", ret); + return ret; + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + return ret; } @@ -2620,7 +2842,9 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) wolfEventQueue_Free(&ctx->event_queue); #endif /* HAVE_WOLF_EVENT */ +#ifndef NO_TLS /* its a static global see ssl.c "gNoTlsMethod" */ XFREE(ctx->method, heapAtCTXInit, DYNAMIC_TYPE_METHOD); +#endif ctx->method = NULL; XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES); @@ -2769,25 +2993,6 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) (void)heapAtCTXInit; } -#ifdef WOLFSSL_STATIC_MEMORY -static void SSL_CtxResourceFreeStaticMem(void* heap) -{ -#ifndef SINGLE_THREADED - if (heap != NULL - #ifdef WOLFSSL_HEAP_TEST - /* avoid dereferencing a test value */ - && heap != (void*)WOLFSSL_HEAP_TEST - #endif - ) { - WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap; - WOLFSSL_HEAP* mem = hint->memory; - wc_FreeMutex(&mem->memory_mutex); - } -#else - (void)heap; -#endif -} -#endif /* WOLFSSL_STATIC_MEMORY */ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) { @@ -2801,7 +3006,7 @@ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) #endif /* decrement CTX reference count */ - wolfSSL_RefDec(&ctx->ref, &isZero, &ret); + wolfSSL_RefWithMutexDec(&ctx->ref, &isZero, &ret); #ifdef WOLFSSL_REFCNT_ERROR_RETURN if (ret < 0) { /* check error state, if mutex error code then mutex init failed but @@ -2809,9 +3014,6 @@ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) if (ctx->err == WC_NO_ERR_TRACE(CTX_INIT_MUTEX_E)) { SSL_CtxResourceFree(ctx); XFREE(ctx, heap, DYNAMIC_TYPE_CTX); - #ifdef WOLFSSL_STATIC_MEMORY - SSL_CtxResourceFreeStaticMem(heap); - #endif } return; } @@ -2824,14 +3026,11 @@ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) SSL_CtxResourceFree(ctx); #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) && \ - !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) + !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_TLS) TicketEncCbCtx_Free(&ctx->ticketKeyCtx); #endif wolfSSL_RefFree(&ctx->ref); XFREE(ctx, heap, DYNAMIC_TYPE_CTX); - #ifdef WOLFSSL_STATIC_MEMORY - SSL_CtxResourceFreeStaticMem(heap); - #endif } else { WOLFSSL_MSG("CTX ref count not 0 yet, no free"); @@ -3249,8 +3448,8 @@ int AllocateSuites(WOLFSSL* ssl) void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, word16 havePSK, word16 haveDH, word16 haveECDSAsig, word16 haveECC, word16 haveStaticRSA, word16 haveStaticECC, - word16 haveFalconSig, word16 haveDilithiumSig, word16 haveAnon, - word16 haveNull, int side) + word16 haveAnon, word16 haveNull, word16 haveAES128, + word16 haveSHA1, word16 haveRC4, int side) { word16 idx = 0; int tls = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_MINOR; @@ -3286,8 +3485,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, (void)haveRSAsig; /* non ecc builds won't read */ (void)haveAnon; /* anon ciphers optional */ (void)haveNull; - (void)haveFalconSig; - (void)haveDilithiumSig; + (void)haveAES128; + (void)haveSHA1; + (void)haveRC4; if (suites == NULL) { WOLFSSL_MSG("InitSuites pointer error"); @@ -3298,17 +3498,17 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, return; /* trust user settings, don't override */ #ifdef WOLFSSL_TLS13 -#ifdef BUILD_TLS_AES_128_GCM_SHA256 +#ifdef BUILD_TLS_AES_256_GCM_SHA384 if (tls1_3) { suites->suites[idx++] = TLS13_BYTE; - suites->suites[idx++] = TLS_AES_128_GCM_SHA256; + suites->suites[idx++] = TLS_AES_256_GCM_SHA384; } #endif -#ifdef BUILD_TLS_AES_256_GCM_SHA384 - if (tls1_3) { +#ifdef BUILD_TLS_AES_128_GCM_SHA256 + if (tls1_3 && haveAES128) { suites->suites[idx++] = TLS13_BYTE; - suites->suites[idx++] = TLS_AES_256_GCM_SHA384; + suites->suites[idx++] = TLS_AES_128_GCM_SHA256; } #endif @@ -3320,14 +3520,14 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_AES_128_CCM_SHA256 - if (tls1_3) { + if (tls1_3 && haveAES128) { suites->suites[idx++] = TLS13_BYTE; suites->suites[idx++] = TLS_AES_128_CCM_SHA256; } #endif #ifdef BUILD_TLS_AES_128_CCM_8_SHA256 - if (tls1_3) { + if (tls1_3 && haveAES128) { suites->suites[idx++] = TLS13_BYTE; suites->suites[idx++] = TLS_AES_128_CCM_8_SHA256; } @@ -3394,7 +3594,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveECC) { + if (tls1_2 && haveECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; } @@ -3414,9 +3614,10 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 #ifdef OPENSSL_EXTRA - if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) { + if ((tls1_2 && haveRSA && haveAES128) || + (tls1_2 && haveECDSAsig && haveAES128)) { #else - if (tls1_2 && haveRSA) { + if (tls1_2 && haveRSA && haveAES128) { #endif suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256; @@ -3431,7 +3632,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveDH && haveRSA) { + if (tls1_2 && haveDH && haveRSA && haveAES128) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_GCM_SHA256; } @@ -3445,7 +3646,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveRSA && haveStaticRSA) { + if (tls1_2 && haveRSA && haveStaticRSA && haveAES128) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_AES_128_GCM_SHA256; } @@ -3459,7 +3660,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveECC && haveStaticECC) { + if (tls1_2 && haveECC && haveStaticECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256; } @@ -3473,7 +3674,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveRSAsig && haveStaticECC) { + if (tls1_2 && haveRSAsig && haveStaticECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256; } @@ -3487,7 +3688,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 - if (tls1_2 && haveECC) { + if (tls1_2 && haveECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256; } @@ -3501,7 +3702,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA - if (tls1_2 && haveDH && haveAnon) { + if (tls1_2 && haveDH && haveAnon && haveAES128 && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DH_anon_WITH_AES_128_CBC_SHA; } @@ -3515,7 +3716,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 - if (tls1_2 && haveDH && havePSK) { + if (tls1_2 && haveDH && havePSK && haveAES128) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_GCM_SHA256; } @@ -3529,7 +3730,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256 - if (tls1_2 && havePSK) { + if (tls1_2 && havePSK && haveAES128) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_128_GCM_SHA256; } @@ -3563,7 +3764,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, /* Place as higher priority for MYSQL */ #if defined(WOLFSSL_MYSQL_COMPATIBLE) #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA - if (tls && haveDH && haveRSA) { + if (tls && haveDH && haveRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA; } @@ -3572,9 +3773,10 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 #ifdef OPENSSL_EXTRA - if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) { + if ((tls1_2 && haveRSA && haveAES128) || + (tls1_2 && haveECDSAsig && haveAES128)) { #else - if (tls1_2 && haveRSA) { + if (tls1_2 && haveRSA && haveAES128) { #endif suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256; @@ -3582,21 +3784,21 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - if (tls1_2 && haveECC) { + if (tls1_2 && haveECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256; } #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 - if (tls1_2 && haveRSAsig && haveStaticECC) { + if (tls1_2 && haveRSAsig && haveStaticECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256; } #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 - if (tls1_2 && haveECC && haveStaticECC) { + if (tls1_2 && haveECC && haveStaticECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256; } @@ -3635,56 +3837,56 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - if (tls && haveECC) { + if (tls && haveECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA - if (tls && haveECC && haveStaticECC) { + if (tls && haveECC && haveStaticECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - if (tls && haveECC) { + if (tls && haveECC && haveAES128 && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA - if (tls && haveECC && haveStaticECC) { + if (tls && haveECC && haveStaticECC && haveAES128 && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA - if (!dtls && tls && haveECC) { + if (!dtls && tls && haveECC && haveSHA1 && haveRC4) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_RC4_128_SHA; } #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA - if (!dtls && tls && haveECC && haveStaticECC) { + if (!dtls && tls && haveECC && haveStaticECC && haveSHA1 && haveRC4) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_RC4_128_SHA; } #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA - if (tls && haveECC) { + if (tls && haveECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA - if (tls && haveECC && haveStaticECC) { + if (tls && haveECC && haveStaticECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA; } @@ -3692,9 +3894,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA #ifdef OPENSSL_EXTRA - if ((tls && haveRSA) || (tls && haveECDSAsig)) { + if ((tls && haveRSA && haveSHA1) || (tls && haveECDSAsig && haveSHA1)) { #else - if (tls && haveRSA) { + if (tls && haveRSA && haveSHA1) { #endif suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; @@ -3702,7 +3904,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA - if (tls && haveRSAsig && haveStaticECC) { + if (tls && haveRSAsig && haveStaticECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA; } @@ -3710,9 +3912,10 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA #ifdef OPENSSL_EXTRA - if ((tls && haveRSA) || (tls && haveECDSAsig)) { + if ((tls && haveRSA && haveAES128 && haveSHA1) || + (tls && haveECDSAsig && haveAES128 && haveSHA1)) { #else - if (tls && haveRSA) { + if (tls && haveRSA && haveAES128 && haveSHA1) { #endif suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA; @@ -3720,21 +3923,21 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA - if (tls && haveRSAsig && haveStaticECC) { + if (tls && haveRSAsig && haveStaticECC && haveAES128 && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA - if (!dtls && tls && haveRSA) { + if (!dtls && tls && haveRSA && haveSHA1 && haveRC4) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_RC4_128_SHA; } #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA - if (!dtls && tls && haveRSAsig && haveStaticECC) { + if (!dtls && tls && haveRSAsig && haveStaticECC && haveSHA1 && haveRC4) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_RC4_128_SHA; } @@ -3742,9 +3945,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA #ifdef OPENSSL_EXTRA - if ((tls && haveRSA) || (tls && haveECDSAsig)) { + if ((tls && haveRSA && haveSHA1) || (tls && haveECDSAsig && haveSHA1)) { #else - if (tls && haveRSA) { + if (tls && haveRSA && haveSHA1) { #endif suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA; @@ -3752,21 +3955,21 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA - if (tls && haveRSAsig && haveStaticECC) { + if (tls && haveRSAsig && haveStaticECC && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA; } #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM - if (tls1_2 && haveECC) { + if (tls1_2 && haveECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM; } #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 - if (tls1_2 && haveECC) { + if (tls1_2 && haveECC && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8; } @@ -3780,7 +3983,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8 - if (tls1_2 && haveRSA && haveStaticRSA) { + if (tls1_2 && haveRSA && haveStaticRSA && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_RSA_WITH_AES_128_CCM_8; } @@ -3807,9 +4010,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && haveDH && haveRSA) + if (tls1_2 && haveDH && haveRSA && haveAES128) #else - if (tls && haveDH && haveRSA) + if (tls && haveDH && haveRSA && haveAES128) #endif { suites->suites[idx++] = CIPHER_BYTE; @@ -3820,7 +4023,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, /* Place as higher priority for MYSQL testing */ #if !defined(WOLFSSL_MYSQL_COMPATIBLE) #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA - if (tls && haveDH && haveRSA) { + if (tls && haveDH && haveRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA; } @@ -3828,14 +4031,14 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA - if (tls && haveDH && haveRSA) { + if (tls && haveDH && haveRSA && haveAES128 && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA; } #endif #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA - if (tls && haveDH && haveRSA) { + if (tls && haveDH && haveRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA; } @@ -3855,9 +4058,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && haveRSA && haveStaticRSA) + if (tls1_2 && haveRSA && haveStaticRSA && haveAES128) #else - if (tls && haveRSA && haveStaticRSA) + if (tls && haveRSA && haveStaticRSA && haveAES128) #endif { suites->suites[idx++] = CIPHER_BYTE; @@ -3866,14 +4069,14 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA - if (tls && haveRSA && haveStaticRSA) { + if (tls && haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA; } #endif #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA - if (tls && haveRSA && haveStaticRSA) { + if (tls && haveRSA && haveStaticRSA && haveAES128 && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA; } @@ -3910,7 +4113,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA - if (tls && haveECC && haveNull) { + if (tls && haveECC && haveNull && haveSHA1) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_NULL_SHA; } @@ -3924,7 +4127,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_RSA_WITH_NULL_SHA - if (tls && haveRSA && haveNull && haveStaticRSA) { + if (tls && haveRSA && haveNull && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA; } @@ -3943,7 +4146,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA - if (tls && havePSK) { + if (tls && havePSK && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA; } @@ -3975,9 +4178,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && haveDH && havePSK) + if (tls1_2 && haveDH && havePSK && haveAES128) #else - if (tls && haveDH && havePSK) + if (tls && haveDH && havePSK && haveAES128) #endif { suites->suites[idx++] = CIPHER_BYTE; @@ -3987,9 +4190,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && havePSK) + if (tls1_2 && havePSK && haveAES128) #else - if (tls1 && havePSK) + if (tls1 && havePSK && haveAES128) #endif { suites->suites[idx++] = CIPHER_BYTE; @@ -3998,14 +4201,14 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA - if (tls && havePSK) { + if (tls && havePSK && haveAES128 && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA; } #endif #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM - if (tls && haveDH && havePSK) { + if (tls && haveDH && havePSK && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CCM; } @@ -4056,9 +4259,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && havePSK) + if (tls1_2 && havePSK && haveAES128) #else - if (tls && havePSK) + if (tls && havePSK && haveAES128) #endif { suites->suites[idx++] = ECC_BYTE; @@ -4068,9 +4271,9 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES - if (tls1_2 && havePSK) + if (tls1_2 && havePSK && haveAES128) #else - if (tls && havePSK) + if (tls && havePSK && haveAES128) #endif { suites->suites[idx++] = ECDHE_PSK_BYTE; @@ -4079,7 +4282,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM - if (tls && havePSK) { + if (tls && havePSK && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM; } @@ -4093,7 +4296,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8 - if (tls && havePSK) { + if (tls && havePSK && haveAES128) { suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM_8; } @@ -4174,49 +4377,49 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, #endif #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA - if (!dtls && haveRSA && haveStaticRSA) { + if (!dtls && haveRSA && haveStaticRSA && haveSHA1 && haveRC4) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = SSL_RSA_WITH_RC4_128_SHA; } #endif #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5 - if (!dtls && haveRSA && haveStaticRSA) { + if (!dtls && haveRSA && haveStaticRSA && haveRC4) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = SSL_RSA_WITH_RC4_128_MD5; } #endif #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA - if (haveRSA && haveStaticRSA) { + if (haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA; } #endif #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - if (tls && haveRSA && haveStaticRSA) { + if (tls && haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA; } #endif #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA - if (tls && haveDH && haveRSA && haveStaticRSA) { + if (tls && haveDH && haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA; } #endif #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - if (tls && haveRSA && haveStaticRSA) { + if (tls && haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA; } #endif #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA - if (tls && haveDH && haveRSA && haveStaticRSA) { + if (tls && haveDH && haveRSA && haveStaticRSA && haveSHA1) { suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA; } @@ -4313,8 +4516,6 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, (void)haveRSAsig; /* non ecc builds won't read */ (void)haveAnon; /* anon ciphers optional */ (void)haveNull; - (void)haveFalconSig; - (void)haveDilithiumSig; } #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) || \ @@ -4941,7 +5142,7 @@ int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo, #endif #if defined(WC_RSA_PSS) - if (sigAlgo == rsa_pss_sa_algo) { + if (sigAlgo == rsa_pss_sa_algo || sigAlgo == rsa_pss_pss_algo) { enum wc_HashType hashType = WC_HASH_TYPE_NONE; int mgf = 0; @@ -6422,19 +6623,19 @@ int wolfSSL_CTX_IsPrivatePkSet(WOLFSSL_CTX* ctx) static void InitSuites_EitherSide(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, word16 havePSK, word16 haveDH, word16 haveECDSAsig, word16 haveECC, word16 haveStaticECC, - word16 haveFalconSig, word16 haveDilithiumSig, word16 haveAnon, + word16 haveAnon, int side) { /* make sure server has DH params, and add PSK if there */ if (side == WOLFSSL_SERVER_END) { InitSuites(suites, pv, keySz, haveRSA, havePSK, haveDH, haveECDSAsig, - haveECC, TRUE, haveStaticECC, haveFalconSig, - haveDilithiumSig, haveAnon, TRUE, side); + haveECC, TRUE, haveStaticECC, + haveAnon, TRUE, TRUE, TRUE, TRUE, side); } else { InitSuites(suites, pv, keySz, haveRSA, havePSK, TRUE, haveECDSAsig, - haveECC, TRUE, haveStaticECC, haveFalconSig, - haveDilithiumSig, haveAnon, TRUE, side); + haveECC, TRUE, haveStaticECC, + haveAnon, TRUE, TRUE, TRUE, TRUE, side); } } @@ -6458,7 +6659,7 @@ void InitSSL_CTX_Suites(WOLFSSL_CTX* ctx) #endif InitSuites_EitherSide(ctx->suites, ctx->method->version, keySz, haveRSA, havePSK, ctx->haveDH, ctx->haveECDSAsig, ctx->haveECC, - ctx->haveStaticECC, ctx->haveFalconSig, ctx->haveDilithiumSig, + ctx->haveStaticECC, haveAnon, ctx->method->side); } @@ -6513,7 +6714,6 @@ int InitSSL_Suites(WOLFSSL* ssl) InitSuites_EitherSide(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, ssl->options.useAnon, ssl->options.side); } @@ -6627,7 +6827,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #ifdef OPENSSL_EXTRA #ifdef WOLFSSL_TLS13 if (ssl->version.minor == TLSv1_3_MINOR && - (ssl->options.mask & SSL_OP_NO_TLSv1_3) == SSL_OP_NO_TLSv1_3) { + (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) { if (!ctx->method->downgrade) { WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.3 set but not " "allowed and downgrading disabled."); @@ -6639,7 +6839,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) } #endif if (ssl->version.minor == TLSv1_2_MINOR && - (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) { + (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) { if (!ctx->method->downgrade) { WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.2 set but not " "allowed and downgrading disabled."); @@ -6650,7 +6850,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->version.minor = TLSv1_1_MINOR; } if (ssl->version.minor == TLSv1_1_MINOR && - (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) { + (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) { if (!ctx->method->downgrade) { WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.1 set but not " "allowed and downgrading disabled."); @@ -6662,7 +6862,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->version.minor = TLSv1_MINOR; } if (ssl->version.minor == TLSv1_MINOR && - (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) { + (ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) { if (!ctx->method->downgrade) { WOLFSSL_MSG("\tInconsistent protocol options. TLS 1 set but not " "allowed and downgrading disabled."); @@ -6675,7 +6875,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->version.minor = SSLv3_MINOR; } if (ssl->version.minor == SSLv3_MINOR && - (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) { + (ssl->options.mask & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) { WOLFSSL_MSG("\tError, option set to not allow SSLv3"); WOLFSSL_ERROR_VERBOSE(VERSION_ERROR); return VERSION_ERROR; @@ -7421,6 +7621,11 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->buffers.dtlsCtx.rfd = -1; ssl->buffers.dtlsCtx.wfd = -1; +#ifdef WOLFSSL_RW_THREADED + if (wc_InitRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + return BAD_MUTEX_E; +#endif + ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx; /* prevent invalid pointer access if not */ ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx; /* correctly set */ #else @@ -7754,6 +7959,9 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->response_idx = 0; #endif #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + ssl->secLevel = ctx->secLevel; +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ /* Returns 0 on success, not WOLFSSL_SUCCESS (1) */ WOLFSSL_MSG_EX("InitSSL done. return 0 (success)"); return 0; @@ -8163,7 +8371,7 @@ void FreeSuites(WOLFSSL* ssl) /* In case holding SSL object in array and don't want to free actual ssl */ -void SSL_ResourceFree(WOLFSSL* ssl) +void wolfSSL_ResourceFree(WOLFSSL* ssl) { /* Note: any resources used during the handshake should be released in the * function FreeHandshakeResources(). Be careful with the special cases @@ -8248,10 +8456,12 @@ void SSL_ResourceFree(WOLFSSL* ssl) XFREE(ssl->peerSceTsipEncRsaKeyIndex, ssl->heap, DYNAMIC_TYPE_RSA); Renesas_cmn_Cleanup(ssl); #endif +#ifndef NO_TLS if (ssl->buffers.inputBuffer.dynamicFlag) ShrinkInputBuffer(ssl, FORCED_FREE); if (ssl->buffers.outputBuffer.dynamicFlag) ShrinkOutputBuffer(ssl); +#endif #ifdef WOLFSSL_THREADED_CRYPT { int i; @@ -8288,6 +8498,14 @@ void SSL_ResourceFree(WOLFSSL* ssl) } XFREE(ssl->buffers.dtlsCtx.peer.sa, ssl->heap, DYNAMIC_TYPE_SOCKADDR); ssl->buffers.dtlsCtx.peer.sa = NULL; +#ifdef WOLFSSL_RW_THREADED + wc_FreeRwLock(&ssl->buffers.dtlsCtx.peerLock); +#endif +#ifdef WOLFSSL_DTLS_CID + XFREE(ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->heap, + DYNAMIC_TYPE_SOCKADDR); + ssl->buffers.dtlsCtx.pendingPeer.sa = NULL; +#endif #ifndef NO_WOLFSSL_SERVER if (ssl->buffers.dtlsCookieSecret.buffer != NULL) { ForceZero(ssl->buffers.dtlsCookieSecret.buffer, @@ -8571,9 +8789,11 @@ void FreeHandshakeResources(WOLFSSL* ssl) } #endif +#ifndef NO_TLS /* input buffer */ if (ssl->buffers.inputBuffer.dynamicFlag) ShrinkInputBuffer(ssl, NO_FORCED_FREE); +#endif #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) if (!ssl->options.tls1_3) @@ -8799,7 +9019,7 @@ void FreeHandshakeResources(WOLFSSL* ssl) void FreeSSL(WOLFSSL* ssl, void* heap) { WOLFSSL_CTX* ctx = ssl->ctx; - SSL_ResourceFree(ssl); + wolfSSL_ResourceFree(ssl); XFREE(ssl, heap, DYNAMIC_TYPE_SSL); if (ctx) FreeSSL_Ctx(ctx); /* will decrement and free underlying CTX if 0 */ @@ -10024,6 +10244,8 @@ ProtocolVersion MakeDTLSv1_3(void) */ #endif /* !NO_ASN_TIME */ + +#ifndef NO_TLS #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \ ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \ (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \ @@ -10604,7 +10826,7 @@ static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz) } } #endif - goto retry; + return WOLFSSL_FATAL_ERROR; case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE): ssl->options.isClosed = 1; @@ -11545,15 +11767,14 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, #ifdef WOLFSSL_DTLS_CID if (rh->type == dtls12_cid) { - byte cid[DTLS_CID_MAX_SIZE]; + byte* ourCid = NULL; if (ssl->buffers.inputBuffer.length - *inOutIdx < (word32)cidSz + LENGTH_SZ) return LENGTH_ERROR; - if (cidSz > DTLS_CID_MAX_SIZE || - wolfSSL_dtls_cid_get_rx(ssl, cid, cidSz) != WOLFSSL_SUCCESS) + if (wolfSSL_dtls_cid_get0_rx(ssl, &ourCid) != WOLFSSL_SUCCESS) return DTLS_CID_ERROR; - if (XMEMCMP(ssl->buffers.inputBuffer.buffer + *inOutIdx, - cid, cidSz) != 0) + if (XMEMCMP(ssl->buffers.inputBuffer.buffer + *inOutIdx, ourCid, cidSz) + != 0) return DTLS_CID_ERROR; *inOutIdx += cidSz; } @@ -11763,7 +11984,7 @@ int GetDtlsHandShakeHeader(WOLFSSL* ssl, const byte* input, { word32 idx = *inOutIdx; - *inOutIdx += HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA; + *inOutIdx += DTLS_HANDSHAKE_HEADER_SZ; if (*inOutIdx > totalSz) { WOLFSSL_ERROR(BUFFER_E); return BUFFER_E; @@ -11927,14 +12148,9 @@ static int BuildFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender) if (ssl == NULL) return BAD_FUNC_ARG; -#ifndef NO_TLS if (ssl->options.tls) { ret = BuildTlsFinished(ssl, hashes, sender); } -#else - (void)hashes; - (void)sender; -#endif #ifndef NO_OLD_TLS if (!ssl->options.tls) { ret = BuildMD5(ssl, hashes, sender); @@ -11958,6 +12174,8 @@ int CipherRequires(byte first, byte second, int requirement) { (void)requirement; + (void)first; + (void)second; #ifndef WOLFSSL_NO_TLS12 @@ -12599,7 +12817,7 @@ int CipherRequires(byte first, byte second, int requirement) } #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */ - +#endif /* !NO_TLS */ #ifndef NO_CERTS @@ -12917,7 +13135,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) x509->challengePw[dCert->cPwdLen] = '\0'; #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_pkcs9_challengePassword, + WC_NID_pkcs9_challengePassword, MBSTRING_ASC, (const byte*)dCert->cPwd, dCert->cPwdLen) != WOLFSSL_SUCCESS) { @@ -12939,7 +13157,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_pkcs9_contentType, + WC_NID_pkcs9_contentType, MBSTRING_ASC, (const byte*)dCert->contentType, dCert->contentTypeLen) != @@ -12953,7 +13171,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) if (dCert->sNum) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_serialNumber, + WC_NID_serialNumber, MBSTRING_ASC, (const byte*)dCert->sNum, dCert->sNumLen) != WOLFSSL_SUCCESS) { @@ -12963,7 +13181,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } if (dCert->unstructuredName) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_pkcs9_unstructuredName, + WC_NID_pkcs9_unstructuredName, MBSTRING_ASC, (const byte*)dCert->unstructuredName, dCert->unstructuredNameLen) @@ -12974,7 +13192,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } if (dCert->surname) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_surname, + WC_NID_surname, MBSTRING_ASC, (const byte*)dCert->surname, dCert->surnameLen) != WOLFSSL_SUCCESS) { @@ -12984,7 +13202,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } if (dCert->givenName) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_givenName, + WC_NID_givenName, MBSTRING_ASC, (const byte*)dCert->givenName, dCert->givenNameLen) != WOLFSSL_SUCCESS) { @@ -12994,7 +13212,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } if (dCert->dnQualifier) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_dnQualifier, + WC_NID_dnQualifier, MBSTRING_ASC, (const byte*)dCert->dnQualifier, dCert->dnQualifierLen) != WOLFSSL_SUCCESS) { @@ -13004,7 +13222,7 @@ static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert) } if (dCert->initials) { if (wolfSSL_X509_REQ_add1_attr_by_NID(x509, - NID_initials, + WC_NID_initials, MBSTRING_ASC, (const byte*)dCert->initials, dCert->initialsLen) != WOLFSSL_SUCCESS) { @@ -13528,8 +13746,8 @@ int CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509, DecodedAcert* dAcert) #endif /* WOLFSSL_ACERT */ -#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ - (defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && !defined(WOLFSSL_NO_TLS12)) +#if (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \ + defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)) && !defined(WOLFSSL_NO_TLS12) static int ProcessCSR_ex(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 status_length, int idx) { @@ -13725,7 +13943,6 @@ int InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx) #endif /* HAVE_PK_CALLBACKS */ - #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) void DoCertFatalAlert(WOLFSSL* ssl, int ret) { @@ -13768,12 +13985,15 @@ void DoCertFatalAlert(WOLFSSL* ssl, int ret) } } +#ifndef NO_TLS /* send fatal alert and mark connection closed */ SendAlert(ssl, alert_fatal, alertWhy); /* try to send */ +#else + (void)alertWhy; +#endif ssl->options.isClosed = 1; } - int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args, int cert_err, void* heap, int* x509Free) @@ -14817,7 +15037,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ)) { /* Re-entry after non-blocking OCSP */ #ifdef WOLFSSL_ASYNC_CRYPT - /* if async operationg not pending, reset error code */ + /* if async operations not pending, reset error code */ if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E)) ret = 0; #endif @@ -15232,7 +15452,13 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, else /* skips OCSP and force CRL check */ #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) - if (IsAtLeastTLSv1_3(ssl->version)) { + if (IsAtLeastTLSv1_3(ssl->version) && + ssl->options.side == WOLFSSL_CLIENT_END && + ssl->status_request) { + /* We check CSR in Certificate message sent from + * Server. Server side will check client + * certificates by traditional OCSP if enabled + */ ret = TLSX_CSR_InitRequest_ex(ssl->extensions, args->dCert, ssl->heap, args->certIdx); } @@ -16827,13 +17053,13 @@ int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, if (ssl->options.side == WOLFSSL_CLIENT_END) { ssl->options.serverState = SERVER_FINISHED_COMPLETE; #ifdef OPENSSL_EXTRA - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; ssl->options.clientState = CLIENT_FINISHED_COMPLETE; #endif if (!ssl->options.resuming) { #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); } #endif ssl->options.handShakeState = HANDSHAKE_DONE; @@ -16846,13 +17072,13 @@ int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, else { ssl->options.clientState = CLIENT_FINISHED_COMPLETE; #ifdef OPENSSL_EXTRA - ssl->cbmode = SSL_CB_MODE_READ; + ssl->cbmode = WOLFSSL_CB_MODE_READ; ssl->options.serverState = SERVER_FINISHED_COMPLETE; #endif if (ssl->options.resuming) { #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); } #endif ssl->options.handShakeState = HANDSHAKE_DONE; @@ -17476,7 +17702,7 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* The server's decision to resume isn't known until after the * "server_hello". If subsequent handshake messages like - * "certificate" or "server_key_exchange" are recevied then we + * "certificate" or "server_key_exchange" are received then we * are doing a full handshake */ /* If the server included a session id then we @@ -17513,9 +17739,9 @@ int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL){ - ssl->cbmode = SSL_CB_MODE_READ; + ssl->cbmode = WOLFSSL_CB_MODE_READ; ssl->cbtype = type; - ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); } #endif @@ -18651,6 +18877,7 @@ static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #endif /* WOLFSSL_DTLS13 */ +#ifndef NO_TLS #ifndef WOLFSSL_NO_TLS12 #ifdef HAVE_AEAD @@ -20223,7 +20450,7 @@ static int SanityCheckCipherText(WOLFSSL* ssl, word32 encryptSz) #ifndef WOLFSSL_AEAD_ONLY -#ifdef WOLSSL_OLD_TIMINGPADVERIFY +#ifdef WOLFSSL_OLD_TIMINGPADVERIFY #define COMPRESS_LOWER 64 #define COMPRESS_UPPER 55 #define COMPRESS_CONSTANT 13 @@ -20629,7 +20856,7 @@ int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz, return ret; } #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */ -#endif /* WOLSSL_OLD_TIMINGPADVERIFY */ +#endif /* WOLFSSL_OLD_TIMINGPADVERIFY */ #endif /* WOLFSSL_AEAD_ONLY */ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) @@ -20641,33 +20868,54 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) #ifdef HAVE_LIBZ byte decomp[MAX_RECORD_SIZE + MAX_COMP_EXTRA]; #endif - #ifdef WOLFSSL_EARLY_DATA - if (ssl->options.tls1_3 && ssl->options.handShakeDone == 0) { - int process = 0; + int isEarlyData = ssl->options.tls1_3 && + ssl->options.handShakeDone == 0 && + ssl->options.side == WOLFSSL_SERVER_END; + int acceptEarlyData = ssl->earlyData != no_early_data && + ssl->options.clientState == CLIENT_HELLO_COMPLETE; +#endif - if (ssl->options.side == WOLFSSL_SERVER_END) { - if ((ssl->earlyData != no_early_data) && - (ssl->options.clientState == CLIENT_HELLO_COMPLETE)) { - process = 1; - } - if (!process) { - WOLFSSL_MSG("Ignoring EarlyData!"); - *inOutIdx += ssl->curSize; - if (*inOutIdx > ssl->buffers.inputBuffer.length) - return BUFFER_E; +#if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_DTLS13) + if (ssl->options.tls1_3 && ssl->options.dtls) + isEarlyData = isEarlyData && w64Equal(ssl->keys.curEpoch64, + w64From32(0x0, DTLS13_EPOCH_EARLYDATA)); +#endif - return 0; - } - } - if (!process) { - WOLFSSL_MSG("Received App data before a handshake completed"); - if (sniff == NO_SNIFF) { - SendAlert(ssl, alert_fatal, unexpected_message); - } - WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E); - return OUT_OF_ORDER_E; - } +#ifdef WOLFSSL_EARLY_DATA + if (isEarlyData && acceptEarlyData) { + WOLFSSL_MSG("Processing EarlyData"); + } + else if (isEarlyData && !acceptEarlyData) { + WOLFSSL_MSG("Ignoring EarlyData!"); + *inOutIdx += ssl->curSize; + if (*inOutIdx > ssl->buffers.inputBuffer.length) + return BUFFER_E; +#ifdef WOLFSSL_DTLS13 + /* Receiving app data from the traffic epoch before the handshake is + * done means that there was a disruption. */ + if (ssl->options.dtls && !w64Equal(ssl->keys.curEpoch64, + w64From32(0x0, DTLS13_EPOCH_EARLYDATA))) + ssl->dtls13Rtx.sendAcks = 1; +#endif + return 0; + } + else +#endif +#ifdef WOLFSSL_DTLS + if (ssl->options.handShakeDone == 0 && ssl->options.dtls) { + WOLFSSL_MSG("Dropping app data received before handshake complete"); + *inOutIdx += ssl->curSize; + if (*inOutIdx > ssl->buffers.inputBuffer.length) + return BUFFER_E; +#ifdef WOLFSSL_DTLS13 + /* Receiving app data from the traffic epoch before the handshake is + * done means that there was a disruption. */ + if (ssl->options.tls1_3 && !w64Equal(ssl->keys.curEpoch64, + w64From32(0x0, DTLS13_EPOCH_EARLYDATA))) + ssl->dtls13Rtx.sendAcks = 1; +#endif + return 0; } else #endif @@ -21041,11 +21289,14 @@ static int GetInputData(WOLFSSL *ssl, word32 size) int usedLength; int dtlsExtra = 0; + if (ssl->options.disableRead) + return WC_NO_ERR_TRACE(WANT_READ); /* check max input length */ - usedLength = (int)(ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx); - maxLength = (int)(ssl->buffers.inputBuffer.bufferSize - (word32)usedLength); - inSz = (int)(size - (word32)usedLength); /* from last partial read */ + usedLength = (int)(ssl->buffers.inputBuffer.length - + ssl->buffers.inputBuffer.idx); + maxLength = (int)(ssl->buffers.inputBuffer.bufferSize - + (word32)usedLength); #ifdef WOLFSSL_DTLS if (ssl->options.dtls && IsDtlsNotSctpMode(ssl)) { @@ -21059,11 +21310,20 @@ static int GetInputData(WOLFSSL *ssl, word32 size) if (size < (word32)inSz) dtlsExtra = (int)(inSz - size); } + else #endif + { + /* check that no lengths or size values are negative */ + if (usedLength < 0 || maxLength < 0) { + return BUFFER_ERROR; + } - /* check that no lengths or size values are negative */ - if (usedLength < 0 || maxLength < 0 || inSz <= 0) { - return BUFFER_ERROR; + /* Return if we have enough data already in the buffer */ + if (size <= (word32)usedLength) { + return 0; + } + + inSz = (int)(size - (word32)usedLength); /* from last partial read */ } if (inSz > maxLength) { @@ -21297,7 +21557,8 @@ static int DtlsShouldDrop(WOLFSSL* ssl, int retcode) } #endif /* WOLFSSL_DTLS */ -#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#if defined(WOLFSSL_TLS13) || \ + (defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID)) static int removeMsgInnerPadding(WOLFSSL* ssl) { word32 i = ssl->buffers.inputBuffer.idx + @@ -21329,16 +21590,58 @@ static int removeMsgInnerPadding(WOLFSSL* ssl) } #endif -int ProcessReply(WOLFSSL* ssl) +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +static void dtlsClearPeer(WOLFSSL_SOCKADDR* peer) { - return ProcessReplyEx(ssl, 0); + XFREE(peer->sa, NULL, DYNAMIC_TYPE_SOCKADDR); + peer->sa = NULL; + peer->sz = 0; + peer->bufSz = 0; } + +/** + * @brief Handle pending peer during record processing. + * @param ssl WOLFSSL object. + * @param deprotected 0 when we have not decrypted the record yet + * 1 when we have decrypted and verified the record + */ +static void dtlsProcessPendingPeer(WOLFSSL* ssl, int deprotected) +{ + if (ssl->buffers.dtlsCtx.pendingPeer.sa != NULL) { + if (!deprotected) { + /* Here we have just read an entire record from the network. It is + * still encrypted. If processingPendingRecord is set then that + * means that an error occurred when processing the previous record. + * In that case we should clear the pendingPeer because we only + * want to allow it to be valid for one record. */ + if (ssl->buffers.dtlsCtx.processingPendingRecord) { + /* Clear the pending peer. */ + dtlsClearPeer(&ssl->buffers.dtlsCtx.pendingPeer); + } + ssl->buffers.dtlsCtx.processingPendingRecord = + !ssl->buffers.dtlsCtx.processingPendingRecord; + } + else { + /* Pending peer present and record deprotected. Update the peer. */ + (void)wolfSSL_dtls_set_peer(ssl, + &ssl->buffers.dtlsCtx.pendingPeer.sa, + ssl->buffers.dtlsCtx.pendingPeer.sz); + ssl->buffers.dtlsCtx.processingPendingRecord = 0; + dtlsClearPeer(&ssl->buffers.dtlsCtx.pendingPeer); + } + } + else { + ssl->buffers.dtlsCtx.processingPendingRecord = 0; + } +} +#endif + /* Process input requests. Return 0 is done, 1 is call again to complete, and negative number is error. If allowSocketErr is set, SOCKET_ERROR_E in ssl->error will be whitelisted. This is useful when the connection has been closed and the endpoint wants to check for an alert sent by the other end. */ -int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) +static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) { int ret = 0, type = internal_error, readSz; int atomicUser = 0; @@ -21537,6 +21840,10 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) &ssl->curRL, &ssl->curSize); #ifdef WOLFSSL_DTLS +#ifdef WOLFSSL_DTLS_CID + if (ssl->options.dtls) + dtlsProcessPendingPeer(ssl, 0); +#endif if (ssl->options.dtls && DtlsShouldDrop(ssl, ret)) { ssl->options.processReply = doProcessInit; ssl->buffers.inputBuffer.length = 0; @@ -21916,7 +22223,8 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 1) { -#if defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) +#if defined(WOLFSSL_TLS13) || \ + (defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID)) int removePadding = 0; if (ssl->options.tls1_3) removePadding = 1; @@ -21961,8 +22269,9 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* the record layer is here */ case runProcessingOneRecord: -#ifdef WOLFSSL_DTLS13 +#ifdef WOLFSSL_DTLS if (ssl->options.dtls) { +#ifdef WOLFSSL_DTLS13 if (IsAtLeastTLSv1_3(ssl->version)) { if (!Dtls13CheckWindow(ssl)) { /* drop packet */ @@ -21986,11 +22295,18 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } } } - else if (IsDtlsNotSctpMode(ssl)) { + else +#endif /* WOLFSSL_DTLS13 */ + if (IsDtlsNotSctpMode(ssl)) { DtlsUpdateWindow(ssl); } +#ifdef WOLFSSL_DTLS_CID + /* Update the peer if we were able to de-protect the message */ + if (IsEncryptionOn(ssl, 0)) + dtlsProcessPendingPeer(ssl, 1); +#endif } -#endif /* WOLFSSL_DTLS13 */ +#endif /* WOLFSSL_DTLS */ ssl->options.processReply = runProcessingOneMessage; FALL_THROUGH; @@ -22458,6 +22774,35 @@ int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } } +int ProcessReply(WOLFSSL* ssl) +{ + return ProcessReplyEx(ssl, 0); +} + +int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) +{ + int ret; + + ret = DoProcessReplyEx(ssl, allowSocketErr); + +#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + if (ssl->options.dtls) { + /* Don't clear pending peer if we are going to re-enter + * DoProcessReplyEx */ + if (ret != WC_NO_ERR_TRACE(WANT_READ) +#ifdef WOLFSSL_ASYNC_CRYPT + && ret != WC_NO_ERR_TRACE(WC_PENDING_E) +#endif + ) { + dtlsClearPeer(&ssl->buffers.dtlsCtx.pendingPeer); + ssl->buffers.dtlsCtx.processingPendingRecord = 0; + } + } +#endif + + return ret; +} + #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) || \ (defined(WOLFSSL_TLS13) && defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)) int SendChangeCipher(WOLFSSL* ssl) @@ -22468,17 +22813,17 @@ int SendChangeCipher(WOLFSSL* ssl) int ret; #ifdef OPENSSL_EXTRA - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; if (ssl->options.side == WOLFSSL_SERVER_END){ ssl->options.serverState = SERVER_CHANGECIPHERSPEC_COMPLETE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS); } - else{ + else { ssl->options.clientState = CLIENT_CHANGECIPHERSPEC_COMPLETE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); } #endif @@ -22915,11 +23260,12 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, (void)epochOrder; -#ifndef NO_TLS #if defined(WOLFSSL_NO_TLS12) && defined(WOLFSSL_TLS13) + /* TLS v1.3 only */ return BuildTls13Message(ssl, output, outSz, input, inSz, type, hashOutput, sizeOnly, asyncOkay); #else + /* TLS v1.2 or v1.3 */ #ifdef WOLFSSL_TLS13 if (ssl->options.tls1_3) { return BuildTls13Message(ssl, output, outSz, input, inSz, type, @@ -22927,6 +23273,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, } #endif +#ifndef WOLFSSL_NO_TLS12 #ifdef WOLFSSL_ASYNC_CRYPT ret = WC_NO_PENDING_E; if (asyncOkay) { @@ -23439,9 +23786,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, /* Final cleanup */ FreeBuildMsgArgs(ssl, args); - return ret; -#endif /* !WOLFSSL_NO_TLS12 */ #else (void)outSz; (void)inSz; @@ -23449,8 +23794,8 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, (void)hashOutput; (void)asyncOkay; return NOT_COMPILED_IN; -#endif /* NO_TLS */ - +#endif /* !WOLFSSL_NO_TLS12 */ +#endif } #ifndef WOLFSSL_NO_TLS12 @@ -23557,9 +23902,9 @@ int SendFinished(WOLFSSL* ssl) if (ssl->options.side == WOLFSSL_SERVER_END) { #ifdef OPENSSL_EXTRA ssl->options.serverState = SERVER_FINISHED_COMPLETE; - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS); #endif ssl->options.handShakeState = HANDSHAKE_DONE; ssl->options.handShakeDone = 1; @@ -23572,9 +23917,9 @@ int SendFinished(WOLFSSL* ssl) if (ssl->options.side == WOLFSSL_CLIENT_END) { #ifdef OPENSSL_EXTRA ssl->options.clientState = CLIENT_FINISHED_COMPLETE; - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS); #endif ssl->options.handShakeState = HANDSHAKE_DONE; ssl->options.handShakeDone = 1; @@ -23616,6 +23961,7 @@ int SendFinished(WOLFSSL* ssl) return ret; } #endif /* WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS */ #ifndef NO_WOLFSSL_SERVER #if (!defined(WOLFSSL_NO_TLS12) && \ @@ -24806,6 +25152,8 @@ int SendAsyncData(WOLFSSL* ssl) } #endif +#ifndef NO_TLS + /** * ssl_in_handshake(): * Invoked in wolfSSL_read/wolfSSL_write to check if wolfSSL_negotiate() is @@ -24898,15 +25246,15 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) groupMsgs = 1; #endif } - else if (IsAtLeastTLSv1_3(ssl->version) && + else +#endif + if (IsAtLeastTLSv1_3(ssl->version) && ssl->options.side == WOLFSSL_SERVER_END && ssl->options.acceptState >= TLS13_ACCEPT_FINISHED_SENT) { /* We can send data without waiting on peer finished msg */ WOLFSSL_MSG("server sending data before receiving client finished"); } - else -#endif - if (ssl_in_handshake(ssl, 1)) { + else if (ssl_in_handshake(ssl, 1)) { int err; WOLFSSL_MSG("handshake not complete, trying to finish"); if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) { @@ -25458,7 +25806,7 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_ALERT, type); + ssl->CBIS(ssl, WOLFSSL_CB_ALERT, type); } #endif #ifdef WOLFSSL_DTLS @@ -25596,8 +25944,11 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) return ret; } +#endif /* !NO_TLS */ + int RetrySendAlert(WOLFSSL* ssl) { + int ret = 0; int type; int severity; WOLFSSL_ENTER("RetrySendAlert"); @@ -25615,12 +25966,18 @@ int RetrySendAlert(WOLFSSL* ssl) ssl->pendingAlert.code = 0; ssl->pendingAlert.level = alert_none; - return SendAlert_ex(ssl, severity, type); +#ifndef NO_TLS + ret = SendAlert_ex(ssl, severity, type); +#else + (void)type; +#endif + return ret; } /* send alert message */ int SendAlert(WOLFSSL* ssl, int severity, int type) { + int ret = 0; WOLFSSL_ENTER("SendAlert"); if (ssl == NULL) { @@ -25628,7 +25985,7 @@ int SendAlert(WOLFSSL* ssl, int severity, int type) } if (ssl->pendingAlert.level != alert_none) { - int ret = RetrySendAlert(ssl); + ret = RetrySendAlert(ssl); if (ret != 0) { if (ssl->pendingAlert.level == alert_none || (ssl->pendingAlert.level != alert_fatal && @@ -25641,10 +25998,13 @@ int SendAlert(WOLFSSL* ssl, int severity, int type) return ret; } } - - return SendAlert_ex(ssl, severity, type); +#ifndef NO_TLS + ret = SendAlert_ex(ssl, severity, type); +#endif /* !NO_TLS */ + return ret; } + #ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H #include #endif @@ -25666,7 +26026,9 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) } /* pass to wolfCrypt */ - if (error <= WC_FIRST_E && error >= WC_LAST_E) { + if ((error <= WC_SPAN1_FIRST_E && error >= WC_SPAN1_MIN_CODE_E) || + (error <= WC_SPAN2_FIRST_E && error >= WC_SPAN2_MIN_CODE_E)) + { return wc_GetErrorString(error); } @@ -25678,7 +26040,7 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) #endif } - switch ((enum wolfSSL_ErrorCodes)error) { + switch ((enum wolfSSL_ErrorCodes)error) { /* // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange) */ case UNSUPPORTED_SUITE : return "unsupported cipher suite"; @@ -25865,6 +26227,9 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case CRL_MISSING: return "CRL missing, not loaded"; + case CRYPTO_POLICY_FORBIDDEN: + return "Operation forbidden by system crypto-policy"; + case MONITOR_SETUP_E: return "CRL monitor setup error"; @@ -26189,6 +26554,33 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) case WOLFSSL_FATAL_ERROR: return "fatal error"; + + case WOLFSSL_PEM_R_NO_START_LINE_E: + return "No more matching objects found (PEM)"; + + case WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E: + return "Error getting password (PEM)"; + + case WOLFSSL_PEM_R_BAD_PASSWORD_READ_E: + return "Bad password (PEM)"; + + case WOLFSSL_PEM_R_BAD_DECRYPT_E : + return "Decryption failed (PEM)"; + + case WOLFSSL_ASN1_R_HEADER_TOO_LONG_E: + return "ASN header too long (compat)"; + + case WOLFSSL_EVP_R_BAD_DECRYPT_E : + return "Decryption failed (EVP)"; + + case WOLFSSL_EVP_R_BN_DECODE_ERROR: + return "Bignum decode error (EVP)"; + + case WOLFSSL_EVP_R_DECODE_ERROR : + return "Decode error (EVP)"; + + case WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR: + return "Private key decode error (EVP)"; } #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ @@ -26273,9 +26665,9 @@ const char* wolfSSL_ERR_lib_error_string(unsigned long e) #if defined(OPENSSL_EXTRA) libe = wolfSSL_ERR_GET_LIB(e); switch (libe) { - case ERR_LIB_PEM: + case WOLFSSL_ERR_LIB_PEM: return "wolfSSL PEM routines"; - case ERR_LIB_EVP: + case WOLFSSL_ERR_LIB_EVP: return "wolfSSL digital envelope routines"; default: return ""; @@ -27265,6 +27657,9 @@ static int ParseCipherList(Suites* suites, word16 haveNull = 1; /* allowed by default if compiled in */ int callInitSuites = 0; word16 havePSK = 0; + word16 haveAES128 = 1; /* allowed by default if compiled in */ + word16 haveSHA1 = 1; /* allowed by default if compiled in */ + word16 haveRC4 = 1; /* allowed by default if compiled in */ #endif const int suiteSz = GetCipherNamesSize(); const char* next = list; @@ -27289,8 +27684,8 @@ static int ParseCipherList(Suites* suites, #else 0, #endif - haveRSA, 1, 1, !haveRSA, 1, haveRSA, !haveRSA, 1, 1, 0, 0, - side + haveRSA, 1, 1, !haveRSA, 1, haveRSA, !haveRSA, 0, 0, 1, + 1, 1, side ); return 1; /* wolfSSL default */ } @@ -27491,6 +27886,29 @@ static int ParseCipherList(Suites* suites, continue; } + #if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (XSTRCMP(name, "AES128") == 0) { + haveAES128 = allowing; + callInitSuites = 1; + ret = 1; + continue; + } + + if (XSTRCMP(name, "SHA1") == 0) { + haveSHA1 = allowing; + callInitSuites = 1; + ret = 1; + continue; + } + + if (XSTRCMP(name, "RC4") == 0) { + haveRC4 = allowing; + callInitSuites = 1; + ret = 1; + continue; + } + #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + if (XSTRCMP(name, "LOW") == 0 || XSTRCMP(name, "MEDIUM") == 0) { /* No way to limit or allow low bit sizes */ if (allowing) { @@ -27512,6 +27930,14 @@ static int ParseCipherList(Suites* suites, /* wolfSSL doesn't support "export" ciphers. We can skip this */ continue; } + + #if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (XSTRNCMP(name, WOLFSSL_SECLEVEL_STR, + strlen(WOLFSSL_SECLEVEL_STR)) == 0) { + /* Skip the "@SECLEVEL=N" string, we'll process it elsewhere. */ + continue; + } + #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ #endif /* OPENSSL_EXTRA */ for (i = 0; i < suiteSz; i++) { @@ -27651,10 +28077,9 @@ static int ParseCipherList(Suites* suites, (word16)((haveSig & SIG_ECDSA) != 0), (word16)haveECC, (word16)haveStaticRSA, (word16)haveStaticECC, - (word16)((haveSig & SIG_FALCON) != 0), - (word16)((haveSig & SIG_DILITHIUM) != 0), (word16)((haveSig & SIG_ANON) != 0), - (word16)haveNull, side); + (word16)haveNull, (word16)haveAES128, + (word16)haveSHA1, (word16)haveRC4, side); /* Restore user ciphers ahead of defaults */ XMEMMOVE(suites->suites + idx, suites->suites, min(suites->suiteSz, WOLFSSL_MAX_SUITE_SZ-idx)); @@ -27665,7 +28090,7 @@ static int ParseCipherList(Suites* suites, { suites->suiteSz = (word16)idx; InitSuitesHashSigAlgo(suites->hashSigAlgo, haveSig, 1, keySz, - &suites->hashSigAlgoSz); + &suites->hashSigAlgoSz); } #ifdef HAVE_RENEGOTIATION_INDICATION @@ -29820,11 +30245,9 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->buffers.digest.length = (unsigned int)digest_sz; /* buffer for hash */ - if (!ssl->buffers.digest.buffer) { - if (!ssl->options.dontFreeDigest) { - XFREE(ssl->buffers.digest.buffer, ssl->heap, - DYNAMIC_TYPE_DIGEST); - } + if (!ssl->options.dontFreeDigest) { + XFREE(ssl->buffers.digest.buffer, ssl->heap, + DYNAMIC_TYPE_DIGEST); } ssl->options.dontFreeDigest = 0; @@ -29856,7 +30279,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #endif /* !WOLFSSL_NO_TLS12 */ /* client only parts */ -#ifndef NO_WOLFSSL_CLIENT +#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) int HaveUniqueSessionObj(WOLFSSL* ssl) { @@ -30144,9 +30567,9 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, ssl->options.clientState = CLIENT_HELLO_COMPLETE; #ifdef OPENSSL_EXTRA - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); #endif #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) @@ -30257,8 +30680,10 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #endif ret = ret || - (ssl->options.haveSessionId && XMEMCMP(ssl->arrays->sessionID, - ssl->session->sessionID, ID_LEN) == 0); + (ssl->options.haveSessionId && ssl->arrays->sessionIDSz == ID_LEN + && ssl->session->sessionIDSz == ID_LEN + && XMEMCMP(ssl->arrays->sessionID, + ssl->session->sessionID, ID_LEN) == 0); return ret; } @@ -30282,7 +30707,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_HANDSHAKE_START, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_HANDSHAKE_START, WOLFSSL_SUCCESS); } #endif @@ -31867,6 +32292,13 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, } else #endif + #ifdef WC_RSA_PSS + if (sigAlgo == rsa_pss_pss_algo && + ssl->options.peerSigAlgo == rsa_sa_algo) { + ssl->options.peerSigAlgo = sigAlgo; + } + else + #endif #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (sigAlgo == sm2_sa_algo && ssl->options.peerSigAlgo == ecc_dsa_sa_algo) { @@ -31933,6 +32365,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, #ifndef NO_RSA #ifdef WC_RSA_PSS case rsa_pss_sa_algo: + case rsa_pss_pss_algo: #endif case rsa_sa_algo: { @@ -32033,6 +32466,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, #ifndef NO_RSA #ifdef WC_RSA_PSS case rsa_pss_sa_algo: + case rsa_pss_pss_algo: #endif case rsa_sa_algo: { @@ -32244,6 +32678,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, #ifndef NO_RSA #ifdef WC_RSA_PSS case rsa_pss_sa_algo: + case rsa_pss_pss_algo: #ifdef HAVE_SELFTEST ret = wc_RsaPSS_CheckPadding( ssl->buffers.digest.buffer, @@ -32449,9 +32884,9 @@ int SendClientKeyExchange(WOLFSSL* ssl) #ifdef OPENSSL_EXTRA ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE; - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; if (ssl->CBIS != NULL) - ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); + ssl->CBIS(ssl, WOLFSSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS); #endif #ifdef WOLFSSL_ASYNC_IO @@ -33775,7 +34210,7 @@ int SendCertificateVerify(WOLFSSL* ssl) return 0; /* sent blank cert, can't verify */ } - args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA; + args->sendSz = WC_MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA; if (IsEncryptionOn(ssl, 1)) { args->sendSz += MAX_MSG_EXTRA; } @@ -34054,13 +34489,20 @@ int SendCertificateVerify(WOLFSSL* ssl) #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) if (ssl->buffers.keyType == sm2_sa_algo) { + #ifdef HAVE_PK_CALLBACKS + buffer tmp; + + tmp.length = ssl->buffers.key->length; + tmp.buffer = ssl->buffers.key->buffer; + #endif + ret = Sm3wSm2Verify(ssl, TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ, ssl->buffers.sig.buffer, ssl->buffers.sig.length, ssl->buffers.digest.buffer, ssl->buffers.digest.length, key, #ifdef HAVE_PK_CALLBACKS - ssl->buffers.key + &tmp #else NULL #endif @@ -34069,12 +34511,19 @@ int SendCertificateVerify(WOLFSSL* ssl) else #endif { + #ifdef HAVE_PK_CALLBACKS + buffer tmp; + + tmp.length = ssl->buffers.key->length; + tmp.buffer = ssl->buffers.key->buffer; + #endif + ret = EccVerify(ssl, ssl->buffers.sig.buffer, ssl->buffers.sig.length, ssl->buffers.digest.buffer, ssl->buffers.digest.length, key, #ifdef HAVE_PK_CALLBACKS - ssl->buffers.key + &tmp #else NULL #endif @@ -34339,7 +34788,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif /* HAVE_SESSION_TICKET */ -#endif /* NO_WOLFSSL_CLIENT */ +#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */ +/* end client only parts */ + #ifndef NO_CERTS @@ -34518,7 +34969,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return MATCH_SUITE_ERROR; } -#ifndef NO_WOLFSSL_SERVER +#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS) #ifndef WOLFSSL_NO_TLS12 @@ -34938,7 +35389,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, goto exit_sske; if (ssl->buffers.serverDH_Pub.buffer == NULL) { - /* Free'd in SSL_ResourceFree and + /* Free'd in wolfSSL_ResourceFree and * FreeHandshakeResources */ ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC( pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -34952,7 +35403,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, pSz = wc_DhGetNamedKeyMinSize(ssl->namedGroup); if (ssl->buffers.serverDH_Priv.buffer == NULL) { - /* Free'd in SSL_ResourceFree and + /* Free'd in wolfSSL_ResourceFree and * FreeHandshakeResources */ ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC( pSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); @@ -35021,7 +35472,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } if (ssl->buffers.serverDH_Pub.buffer == NULL) { - /* Free'd in SSL_ResourceFree and FreeHandshakeResources */ + /* Free'd in wolfSSL_ResourceFree + * and FreeHandshakeResources + */ ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC( ssl->buffers.serverDH_P.length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -35033,7 +35486,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } if (ssl->buffers.serverDH_Priv.buffer == NULL) { - /* Free'd in SSL_ResourceFree and FreeHandshakeResources */ + /* Free'd in wolfSSL_ResourceFree + * and FreeHandshakeResources + */ ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC( ssl->buffers.serverDH_P.length, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); @@ -36258,6 +36713,13 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, else #endif /* WOLFSSL_SM2 */ { + #ifdef HAVE_PK_CALLBACKS + buffer tmp; + + tmp.length = ssl->buffers.key->length; + tmp.buffer = ssl->buffers.key->buffer; + #endif + ret = EccVerify(ssl, args->output + LENGTH_SZ + args->idx, args->sigSz, @@ -36265,7 +36727,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->buffers.digest.length, key, #ifdef HAVE_PK_CALLBACKS - ssl->buffers.key + &tmp #else NULL #endif @@ -36277,7 +36739,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, goto exit_sske; } } - #if defined(HAVE_E25519) || defined(HAVE_ED448) + #if defined(HAVE_ED25519) || defined(HAVE_ED448) FALL_THROUGH; #endif #endif /* WOLFSSL_CHECK_SIG_FAULTS */ @@ -36810,9 +37272,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, - TRUE, ssl->options.side); + ssl->options.useAnon, + TRUE, TRUE, TRUE, TRUE, ssl->options.side); } /* suite size */ @@ -36870,7 +37331,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ssl->options.usingCompression = 0; /* turn off */ ssl->options.clientState = CLIENT_HELLO_COMPLETE; - ssl->cbmode = SSL_CB_MODE_WRITE; + ssl->cbmode = WOLFSSL_CB_MODE_WRITE; *inOutIdx = idx; ssl->options.haveSessionId = 1; @@ -37242,9 +37703,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, - TRUE, ssl->options.side); + ssl->options.useAnon, + TRUE, TRUE, TRUE, TRUE, ssl->options.side); } /* check if option is set to not allow the current version @@ -37320,9 +37780,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, - TRUE, ssl->options.side); + ssl->options.useAnon, + TRUE, TRUE, TRUE, TRUE, ssl->options.side); } } @@ -38468,7 +38927,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->ctx->ticketEncCb == NULL #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL) || - /* SSL_OP_NO_TICKET turns off tickets in <= 1.2. Forces + /* WOLFSSL_OP_NO_TICKET turns off tickets in <= 1.2. Forces * "stateful" tickets for 1.3 so just use the regular * stateless ones. */ (!IsAtLeastTLSv1_3(ssl->version) && @@ -38592,7 +39051,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->ctx->ticketEncCb == NULL #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL) || - /* SSL_OP_NO_TICKET turns off tickets in < 1.2. Forces + /* WOLFSSL_OP_NO_TICKET turns off tickets in < 1.2. Forces * "stateful" tickets for 1.3 so just use the regular * stateless ones. */ (!IsAtLeastTLSv1_3(ssl->version) && @@ -39217,7 +39676,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; } -#ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB +#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_TLS) /* Initialize the context for session ticket encryption. * @@ -39519,7 +39978,7 @@ static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz, } if (ret == 0) { ret = wc_AesGcmEncrypt(aes, in, out, inLen, iv, GCM_NONCE_MID_SZ, - tag, AES_BLOCK_SIZE, aad, aadSz); + tag, WC_AES_BLOCK_SIZE, aad, aadSz); } wc_AesFree(aes); } @@ -39530,7 +39989,7 @@ static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz, } if (ret == 0) { ret = wc_AesGcmDecrypt(aes, in, out, inLen, iv, GCM_NONCE_MID_SZ, - tag, AES_BLOCK_SIZE, aad, aadSz); + tag, WC_AES_BLOCK_SIZE, aad, aadSz); } wc_AesFree(aes); } @@ -41303,7 +41762,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], WOLFSSL_EXTRA_ALERTS is defined, indicating user is OK with potential information disclosure from alerts. */ #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_EXTRA_ALERTS) - ad = SSL_AD_UNRECOGNIZED_NAME; + ad = WOLFSSL_AD_UNRECOGNIZED_NAME; #endif /* Stunnel supports a custom sni callback to switch an SSL's ctx * when SNI is received. Call it now if exists */ @@ -41330,7 +41789,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], } #endif /* HAVE_SNI */ -#endif /* NO_WOLFSSL_SERVER */ +#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */ #ifdef WOLFSSL_ASYNC_CRYPT diff --git a/src/src/keys.c b/src/src/keys.c index b5b982c..4ff687e 100644 --- a/src/src/keys.c +++ b/src/src/keys.c @@ -28,7 +28,7 @@ #include -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) #include #include @@ -341,7 +341,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -358,7 +358,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -374,7 +374,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -431,7 +431,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -448,7 +448,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -466,7 +466,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -503,7 +503,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -530,7 +530,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -547,7 +547,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -601,7 +601,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -618,7 +618,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -635,7 +635,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -653,7 +653,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -671,7 +671,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -689,7 +689,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -707,7 +707,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -747,7 +747,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -764,7 +764,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -781,7 +781,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -798,7 +798,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; specs->iv_size = AES_IV_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; break; #endif @@ -814,7 +814,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -907,7 +907,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -924,7 +924,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -941,7 +941,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -958,7 +958,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -976,7 +976,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -994,7 +994,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1012,7 +1012,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 1; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1068,7 +1068,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -1086,7 +1086,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -1104,7 +1104,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -1124,7 +1124,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -1144,7 +1144,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -1164,7 +1164,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -1184,7 +1184,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -1204,7 +1204,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_IMP_IV_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -1273,7 +1273,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_NONCE_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1291,7 +1291,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_NONCE_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1329,7 +1329,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_NONCE_SZ; specs->aead_mac_size = AES_CCM_16_AUTH_SZ; @@ -1347,7 +1347,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESCCM_NONCE_SZ; specs->aead_mac_size = AES_CCM_8_AUTH_SZ; @@ -1375,7 +1375,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1564,7 +1564,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -1581,7 +1581,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -1649,7 +1649,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -1666,7 +1666,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -1683,7 +1683,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1703,7 +1703,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1723,7 +1723,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1743,7 +1743,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1763,7 +1763,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -1783,7 +1783,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1802,7 +1802,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1821,7 +1821,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1840,7 +1840,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1859,7 +1859,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1878,7 +1878,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -1992,7 +1992,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -2026,7 +2026,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -2043,7 +2043,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -2060,7 +2060,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; break; @@ -2077,7 +2077,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -2095,7 +2095,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -2113,7 +2113,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -2131,7 +2131,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_256_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AESGCM_IMP_IV_SZ; specs->aead_mac_size = AES_GCM_AUTH_SZ; @@ -2149,7 +2149,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_128_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2166,7 +2166,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_256_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2183,7 +2183,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_128_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2200,7 +2200,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_256_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2217,7 +2217,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_128_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2234,7 +2234,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_256_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2251,7 +2251,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_128_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2268,7 +2268,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = CAMELLIA_256_KEY_SIZE; - specs->block_size = CAMELLIA_BLOCK_SIZE; + specs->block_size = WC_CAMELLIA_BLOCK_SIZE; specs->iv_size = CAMELLIA_IV_SIZE; break; @@ -2285,7 +2285,7 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, specs->pad_size = PAD_SHA; specs->static_ecdh = 0; specs->key_size = AES_128_KEY_SIZE; - specs->block_size = AES_BLOCK_SIZE; + specs->block_size = WC_AES_BLOCK_SIZE; specs->iv_size = AES_IV_SIZE; if (opts != NULL) @@ -2976,13 +2976,13 @@ int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, CipherSpecs* specs, if (enc && enc->cam == NULL) enc->cam = - (Camellia*)XMALLOC(sizeof(Camellia), heap, DYNAMIC_TYPE_CIPHER); + (wc_Camellia*)XMALLOC(sizeof(wc_Camellia), heap, DYNAMIC_TYPE_CIPHER); if (enc && enc->cam == NULL) return MEMORY_E; if (dec && dec->cam == NULL) dec->cam = - (Camellia*)XMALLOC(sizeof(Camellia), heap, DYNAMIC_TYPE_CIPHER); + (wc_Camellia*)XMALLOC(sizeof(wc_Camellia), heap, DYNAMIC_TYPE_CIPHER); if (dec && dec->cam == NULL) return MEMORY_E; @@ -4109,4 +4109,4 @@ int MakeMasterSecret(WOLFSSL* ssl) #endif } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY && !NO_TLS */ diff --git a/src/src/ocsp.c b/src/src/ocsp.c index 493d826..cf824f6 100644 --- a/src/src/ocsp.c +++ b/src/src/ocsp.c @@ -866,7 +866,7 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, (void)certs; - if (flags & OCSP_NOVERIFY) + if (flags & WOLFSSL_OCSP_NOVERIFY) return WOLFSSL_SUCCESS; #ifdef WOLFSSL_SMALL_STACK @@ -880,7 +880,7 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, if (bs->verifyError != OCSP_VERIFY_ERROR_NONE) goto out; - if (flags & OCSP_TRUSTOTHER) { + if (flags & WOLFSSL_OCSP_TRUSTOTHER) { for (idx = 0; idx < wolfSSL_sk_X509_num(certs); idx++) { WOLFSSL_X509* x = wolfSSL_sk_X509_value(certs, idx); int derSz = 0; @@ -898,7 +898,7 @@ int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, if (ParseCertRelative(cert, CERT_TYPE, VERIFY, st->cm, NULL) < 0) goto out; - if (!(flags & OCSP_NOCHECKS)) { + if (!(flags & WOLFSSL_OCSP_NOCHECKS)) { if (CheckOcspResponder(bs, cert, st->cm) != 0) goto out; } @@ -1634,7 +1634,7 @@ int wolfSSL_OCSP_REQ_CTX_nbio(WOLFSSL_OCSP_REQ_CTX *ctx) case ORIOS_WRITE: { const unsigned char *req; - int reqLen = wolfSSL_BIO_get_mem_data(ctx->reqResp, &req); + int reqLen = wolfSSL_BIO_get_mem_data(ctx->reqResp, (void*)&req); if (reqLen <= 0) { WOLFSSL_MSG("wolfSSL_BIO_get_mem_data error"); return WOLFSSL_FAILURE; @@ -1710,7 +1710,7 @@ int wolfSSL_OCSP_sendreq_nbio(OcspResponse **presp, WOLFSSL_OCSP_REQ_CTX *ctx) if (ret != WOLFSSL_SUCCESS) return ret; - len = wolfSSL_BIO_get_mem_data(ctx->reqResp, &resp); + len = wolfSSL_BIO_get_mem_data(ctx->reqResp, (void*)&resp); if (len <= 0) return WOLFSSL_FAILURE; return wolfSSL_d2i_OCSP_RESPONSE(presp, &resp, len) != NULL diff --git a/src/src/pk.c b/src/src/pk.c index 42468bf..6c55bee 100644 --- a/src/src/pk.c +++ b/src/src/pk.c @@ -165,7 +165,26 @@ static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb, /* Write left over data back to BIO if not a file BIO */ if ((ret > 0) && ((memSz - ret) > 0) && (bio->type != WOLFSSL_BIO_FILE)) { - int res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret); + int res; + if (!alloced) { + /* If wolfssl_read_bio() points mem at the buffer internal to + * bio, we need to dup it before calling wolfSSL_BIO_write(), + * because the latter may reallocate the bio, invalidating the + * mem pointer before reading from it. + */ + char *mem_dup = (char *)XMALLOC((size_t)(memSz - ret), + NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (mem_dup != NULL) { + XMEMCPY(mem_dup, mem + ret, (size_t)(memSz - ret)); + res = wolfSSL_BIO_write(bio, mem_dup, memSz - ret); + mem = mem_dup; + alloced = 1; + } + else + res = MEMORY_E; + } + else + res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret); if (res != memSz - ret) { WOLFSSL_ERROR_MSG("Unable to write back excess data"); if (res < 0) { @@ -348,7 +367,7 @@ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, * @return 1 on success. * @return 0 on error. */ -int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, +int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz) { int ret = 0; @@ -482,8 +501,8 @@ int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, * @return 0 on failure. */ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, - const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type, - void* heap, byte** out, int* outSz) + const WOLFSSL_EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, + int type, void* heap, byte** out, int* outSz) { int ret = 1; byte* tmp = NULL; @@ -2155,8 +2174,9 @@ WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa, * @return 1 on success. * @return 0 on failure. */ -int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher, - unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen) +int wolfSSL_PEM_write_mem_RSAPrivateKey(WOLFSSL_RSA* rsa, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + unsigned char **pem, int *pLen) { int ret = 1; byte* derBuf = NULL; @@ -2261,7 +2281,7 @@ int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, * @return 0 on failure. */ int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa, - const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, + const WOLFSSL_EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, wc_pem_password_cb *cb, void *arg) { int ret = 1; @@ -3542,7 +3562,7 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, unsigned char *em, const WOLFSSL_EVP_MD *mgf1Hash, int saltLen) { int ret = 1; - enum wc_HashType hashType; + enum wc_HashType hashType = WC_HASH_TYPE_NONE; int hashLen = 0; int emLen = 0; int mgf = 0; @@ -3857,15 +3877,15 @@ static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash, ret = 0; } - if ((ret == 1) && (hashAlg != NID_undef) && - (padding == RSA_PKCS1_PADDING)) { + if ((ret == 1) && (hashAlg != WC_NID_undef) && + (padding == WC_RSA_PKCS1_PADDING)) { /* Convert hash algorithm to hash type for PKCS#1.5 padding. */ hType = (int)nid2oid(hashAlg, oidHashType); if (hType == -1) { ret = 0; } } - if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) { + if ((ret == 1) && (padding == WC_RSA_PKCS1_PADDING)) { /* PKCS#1.5 encoding. */ word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType); if (encSz == 0) { @@ -3877,7 +3897,7 @@ static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash, } } /* Other padding schemes require the hash as is. */ - if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) { + if ((ret == 1) && (padding != WC_RSA_PKCS1_PADDING)) { XMEMCPY(enc, hash, hLen); *encLen = hLen; } @@ -3905,7 +3925,7 @@ int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen, } /* flag is 1: output complete signature. */ return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet, - sigLen, rsa, 1, RSA_PKCS1_PADDING); + sigLen, rsa, 1, WC_RSA_PKCS1_PADDING); } /* Sign the message hash using hash algorithm and RSA key. @@ -3935,7 +3955,7 @@ int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash, *sigLen = RSA_MAX_SIZE / CHAR_BIT; } ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet, - sigLen, rsa, flag, RSA_PKCS1_PADDING); + sigLen, rsa, flag, WC_RSA_PKCS1_PADDING); } return ret; @@ -3957,7 +3977,7 @@ int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash, * 0: Output the value that the unpadded signature * should be compared to. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and - * RSA_PKCS1_PADDING are currently supported for + * WC_RSA_PKCS1_PADDING are currently supported for * signing. * @return 1 on success. * @return 0 on failure. @@ -4046,7 +4066,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, if (ret == 1) { switch (padding) { #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT) - case RSA_NO_PADDING: + case WC_RSA_NO_PAD: if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen, (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) { WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad"); @@ -4056,7 +4076,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, #endif #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1)) - case RSA_PKCS1_PSS_PADDING: + case WC_RSA_PKCS1_PSS_PADDING: { enum wc_HashType hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); @@ -4075,14 +4095,14 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, } #endif #ifndef WC_NO_RSA_OAEP - case RSA_PKCS1_OAEP_PADDING: + case WC_RSA_PKCS1_OAEP_PADDING: /* Not a signature padding scheme. */ WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for " "signing"); ret = 0; break; #endif - case RSA_PKCS1_PADDING: + case WC_RSA_PKCS1_PADDING: { /* Sign (private encrypt) PKCS#1 encoded signature. */ if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen, @@ -4135,7 +4155,7 @@ int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash, WOLFSSL_RSA* rsa) { return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa, - RSA_PKCS1_PADDING); + WC_RSA_PKCS1_PADDING); } /** @@ -4150,7 +4170,7 @@ int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash, * @param [in] sigLen Length of signature data. * @param [in] rsa RSA key used to sign the input * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and - * RSA_PKCS1_PADDING are currently supported for + * WC_RSA_PKCS1_PADDING are currently supported for * signing. * @return 1 on success. * @return 0 on failure. @@ -4190,7 +4210,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, } } #ifdef WOLFSSL_SMALL_STACK - if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) { + if ((ret == 1) && (padding != WC_RSA_PKCS1_PSS_PADDING)) { /* Allocate memory for encoded signature. */ encodedSig = (unsigned char *)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -4200,7 +4220,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, } } #endif - if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) { + if ((ret == 1) && (padding != WC_RSA_PKCS1_PSS_PADDING)) { /* Make encoded signature to compare with decrypted signature. */ if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len, padding) <= 0) { @@ -4229,7 +4249,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, if (ret == 1) { #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) - if (padding == RSA_PKCS1_PSS_PADDING) { + if (padding == WC_RSA_PKCS1_PSS_PADDING) { /* Check PSS padding is valid. */ if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen, hType, DEF_PSS_SALT_LEN, @@ -4305,15 +4325,15 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, #if !defined(HAVE_FIPS) /* Convert to wolfCrypt padding, hash and MGF. */ switch (padding) { - case RSA_PKCS1_PADDING: + case WC_RSA_PKCS1_PADDING: pad_type = WC_RSA_PKCSV15_PAD; break; - case RSA_PKCS1_OAEP_PADDING: + case WC_RSA_PKCS1_OAEP_PADDING: pad_type = WC_RSA_OAEP_PAD; hash = WC_HASH_TYPE_SHA; mgf = WC_MGF1SHA1; break; - case RSA_NO_PADDING: + case WC_RSA_NO_PAD: pad_type = WC_RSA_NO_PAD; break; default: @@ -4324,7 +4344,7 @@ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from, #else /* Check for supported padding schemes in FIPS. */ /* TODO: Do we support more schemes in later versions of FIPS? */ - if (padding != RSA_PKCS1_PADDING) { + if (padding != WC_RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in " "FIPS"); ret = WOLFSSL_FATAL_ERROR; @@ -4417,15 +4437,15 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, if (ret == 0) { #if !defined(HAVE_FIPS) switch (padding) { - case RSA_PKCS1_PADDING: + case WC_RSA_PKCS1_PADDING: pad_type = WC_RSA_PKCSV15_PAD; break; - case RSA_PKCS1_OAEP_PADDING: + case WC_RSA_PKCS1_OAEP_PADDING: pad_type = WC_RSA_OAEP_PAD; hash = WC_HASH_TYPE_SHA; mgf = WC_MGF1SHA1; break; - case RSA_NO_PADDING: + case WC_RSA_NO_PAD: pad_type = WC_RSA_NO_PAD; break; default: @@ -4435,7 +4455,7 @@ int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from, #else /* Check for supported padding schemes in FIPS. */ /* TODO: Do we support more schemes in later versions of FIPS? */ - if (padding != RSA_PKCS1_PADDING) { + if (padding != WC_RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in " "FIPS"); ret = WOLFSSL_FATAL_ERROR; @@ -4508,10 +4528,10 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, if (ret == 0) { #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) switch (padding) { - case RSA_PKCS1_PADDING: + case WC_RSA_PKCS1_PADDING: pad_type = WC_RSA_PKCSV15_PAD; break; - case RSA_NO_PADDING: + case WC_RSA_NO_PAD: pad_type = WC_RSA_NO_PAD; break; /* TODO: RSA_X931_PADDING not supported */ @@ -4520,7 +4540,7 @@ int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from, ret = WOLFSSL_FATAL_ERROR; } #else - if (padding != RSA_PKCS1_PADDING) { + if (padding != WC_RSA_PKCS1_PADDING) { WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in " "FIPS"); ret = WOLFSSL_FATAL_ERROR; @@ -4599,9 +4619,9 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, if (ret == 0) { switch (padding) { - case RSA_PKCS1_PADDING: + case WC_RSA_PKCS1_PADDING: #ifdef WC_RSA_NO_PADDING - case RSA_NO_PADDING: + case WC_RSA_NO_PAD: #endif break; /* TODO: RSA_X931_PADDING not supported */ @@ -4627,12 +4647,12 @@ int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from, if (ret == 0) { /* Use wolfCrypt to private-encrypt with RSA key. * Size of output buffer must be size of RSA key. */ - if (padding == RSA_PKCS1_PADDING) { + if (padding == WC_RSA_PKCS1_PADDING) { ret = wc_RsaSSL_Sign(from, (word32)len, to, (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng); } #ifdef WC_RSA_NO_PADDING - else if (padding == RSA_NO_PADDING) { + else if (padding == WC_RSA_NO_PAD) { word32 outLen = (word32)wolfSSL_RSA_size(rsa); ret = wc_RsaFunction(from, (word32)len, to, &outLen, RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng); @@ -5824,7 +5844,7 @@ WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der, * Returns 1 or 0 */ int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa, - const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, wc_pem_password_cb* cb, void* arg) { int ret = 1; @@ -5942,7 +5962,7 @@ int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa) * 1 if success, 0 if error */ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, - const EVP_CIPHER* cipher, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen) { @@ -6062,7 +6082,7 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, * 1 if success, 0 if error */ int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa, - const EVP_CIPHER *enc, + const WOLFSSL_EVP_CIPHER *enc, unsigned char *kstr, int klen, wc_pem_password_cb *cb, void *u) { @@ -6508,17 +6528,17 @@ static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid) * FIPS v2 module */ switch (nid) { #ifdef HAVE_FFDHE_2048 - case NID_ffdhe2048: + case WC_NID_ffdhe2048: params = wc_Dh_ffdhe2048_Get(); break; #endif /* HAVE_FFDHE_2048 */ #ifdef HAVE_FFDHE_3072 - case NID_ffdhe3072: + case WC_NID_ffdhe3072: params = wc_Dh_ffdhe3072_Get(); break; #endif /* HAVE_FFDHE_3072 */ #ifdef HAVE_FFDHE_4096 - case NID_ffdhe4096: + case WC_NID_ffdhe4096: params = wc_Dh_ffdhe4096_Get(); break; #endif /* HAVE_FFDHE_4096 */ @@ -6604,17 +6624,17 @@ static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid) switch (nid) { #ifdef HAVE_FFDHE_2048 - case NID_ffdhe2048: + case WC_NID_ffdhe2048: name = WC_FFDHE_2048; break; #endif /* HAVE_FFDHE_2048 */ #ifdef HAVE_FFDHE_3072 - case NID_ffdhe3072: + case WC_NID_ffdhe3072: name = WC_FFDHE_3072; break; #endif /* HAVE_FFDHE_3072 */ #ifdef HAVE_FFDHE_4096 - case NID_ffdhe4096: + case WC_NID_ffdhe4096: name = WC_FFDHE_4096; break; #endif /* HAVE_FFDHE_4096 */ @@ -7856,7 +7876,7 @@ static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out, int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); int err = 0; byte* der = NULL; - word32 derSz; + word32 derSz = 0; DhKey* key = NULL; (void)heap; @@ -7913,7 +7933,7 @@ static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out, int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh) { int ret = 1; - int derSz; + int derSz = 0; byte* derBuf = NULL; void* heap = NULL; @@ -8763,7 +8783,7 @@ static int _DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub, ret = WOLFSSL_FATAL_ERROR; } /* Get the maximum size of computed DH key. */ - if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) { + if ((ret == 0) && ((keySz = (word32)wolfSSL_DH_size(dh)) == 0)) { WOLFSSL_ERROR_MSG("Bad DH_size"); ret = WOLFSSL_FATAL_ERROR; } @@ -9028,7 +9048,7 @@ int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth) if (meth != NULL) { /* Only field type supported by code base. */ - nid = NID_X9_62_prime_field; + nid = WC_NID_X9_62_prime_field; } return nid; @@ -9052,62 +9072,62 @@ int EccEnumToNID(int n) switch(n) { case ECC_SECP192R1: - return NID_X9_62_prime192v1; + return WC_NID_X9_62_prime192v1; case ECC_PRIME192V2: - return NID_X9_62_prime192v2; + return WC_NID_X9_62_prime192v2; case ECC_PRIME192V3: - return NID_X9_62_prime192v3; + return WC_NID_X9_62_prime192v3; case ECC_PRIME239V1: - return NID_X9_62_prime239v1; + return WC_NID_X9_62_prime239v1; case ECC_PRIME239V2: - return NID_X9_62_prime239v2; + return WC_NID_X9_62_prime239v2; case ECC_PRIME239V3: - return NID_X9_62_prime239v3; + return WC_NID_X9_62_prime239v3; case ECC_SECP256R1: - return NID_X9_62_prime256v1; + return WC_NID_X9_62_prime256v1; case ECC_SECP112R1: - return NID_secp112r1; + return WC_NID_secp112r1; case ECC_SECP112R2: - return NID_secp112r2; + return WC_NID_secp112r2; case ECC_SECP128R1: - return NID_secp128r1; + return WC_NID_secp128r1; case ECC_SECP128R2: - return NID_secp128r2; + return WC_NID_secp128r2; case ECC_SECP160R1: - return NID_secp160r1; + return WC_NID_secp160r1; case ECC_SECP160R2: - return NID_secp160r2; + return WC_NID_secp160r2; case ECC_SECP224R1: - return NID_secp224r1; + return WC_NID_secp224r1; case ECC_SECP384R1: - return NID_secp384r1; + return WC_NID_secp384r1; case ECC_SECP521R1: - return NID_secp521r1; + return WC_NID_secp521r1; case ECC_SECP160K1: - return NID_secp160k1; + return WC_NID_secp160k1; case ECC_SECP192K1: - return NID_secp192k1; + return WC_NID_secp192k1; case ECC_SECP224K1: - return NID_secp224k1; + return WC_NID_secp224k1; case ECC_SECP256K1: - return NID_secp256k1; + return WC_NID_secp256k1; case ECC_BRAINPOOLP160R1: - return NID_brainpoolP160r1; + return WC_NID_brainpoolP160r1; case ECC_BRAINPOOLP192R1: - return NID_brainpoolP192r1; + return WC_NID_brainpoolP192r1; case ECC_BRAINPOOLP224R1: - return NID_brainpoolP224r1; + return WC_NID_brainpoolP224r1; case ECC_BRAINPOOLP256R1: - return NID_brainpoolP256r1; + return WC_NID_brainpoolP256r1; case ECC_BRAINPOOLP320R1: - return NID_brainpoolP320r1; + return WC_NID_brainpoolP320r1; case ECC_BRAINPOOLP384R1: - return NID_brainpoolP384r1; + return WC_NID_brainpoolP384r1; case ECC_BRAINPOOLP512R1: - return NID_brainpoolP512r1; + return WC_NID_brainpoolP512r1; #ifdef WOLFSSL_SM2 case ECC_SM2P256V1: - return NID_sm2; + return WC_NID_sm2; #endif default: WOLFSSL_MSG("NID not found"); @@ -9132,85 +9152,85 @@ int NIDToEccEnum(int nid) WOLFSSL_ENTER("NIDToEccEnum"); switch (nid) { - case NID_X9_62_prime192v1: + case WC_NID_X9_62_prime192v1: id = ECC_SECP192R1; break; - case NID_X9_62_prime192v2: + case WC_NID_X9_62_prime192v2: id = ECC_PRIME192V2; break; - case NID_X9_62_prime192v3: + case WC_NID_X9_62_prime192v3: id = ECC_PRIME192V3; break; - case NID_X9_62_prime239v1: + case WC_NID_X9_62_prime239v1: id = ECC_PRIME239V1; break; - case NID_X9_62_prime239v2: + case WC_NID_X9_62_prime239v2: id = ECC_PRIME239V2; break; - case NID_X9_62_prime239v3: + case WC_NID_X9_62_prime239v3: id = ECC_PRIME239V3; break; - case NID_X9_62_prime256v1: + case WC_NID_X9_62_prime256v1: id = ECC_SECP256R1; break; - case NID_secp112r1: + case WC_NID_secp112r1: id = ECC_SECP112R1; break; - case NID_secp112r2: + case WC_NID_secp112r2: id = ECC_SECP112R2; break; - case NID_secp128r1: + case WC_NID_secp128r1: id = ECC_SECP128R1; break; - case NID_secp128r2: + case WC_NID_secp128r2: id = ECC_SECP128R2; break; - case NID_secp160r1: + case WC_NID_secp160r1: id = ECC_SECP160R1; break; - case NID_secp160r2: + case WC_NID_secp160r2: id = ECC_SECP160R2; break; - case NID_secp224r1: + case WC_NID_secp224r1: id = ECC_SECP224R1; break; - case NID_secp384r1: + case WC_NID_secp384r1: id = ECC_SECP384R1; break; - case NID_secp521r1: + case WC_NID_secp521r1: id = ECC_SECP521R1; break; - case NID_secp160k1: + case WC_NID_secp160k1: id = ECC_SECP160K1; break; - case NID_secp192k1: + case WC_NID_secp192k1: id = ECC_SECP192K1; break; - case NID_secp224k1: + case WC_NID_secp224k1: id = ECC_SECP224K1; break; - case NID_secp256k1: + case WC_NID_secp256k1: id = ECC_SECP256K1; break; - case NID_brainpoolP160r1: + case WC_NID_brainpoolP160r1: id = ECC_BRAINPOOLP160R1; break; - case NID_brainpoolP192r1: + case WC_NID_brainpoolP192r1: id = ECC_BRAINPOOLP192R1; break; - case NID_brainpoolP224r1: + case WC_NID_brainpoolP224r1: id = ECC_BRAINPOOLP224R1; break; - case NID_brainpoolP256r1: + case WC_NID_brainpoolP256r1: id = ECC_BRAINPOOLP256R1; break; - case NID_brainpoolP320r1: + case WC_NID_brainpoolP320r1: id = ECC_BRAINPOOLP320R1; break; - case NID_brainpoolP384r1: + case WC_NID_brainpoolP384r1: id = ECC_BRAINPOOLP384R1; break; - case NID_brainpoolP512r1: + case WC_NID_brainpoolP512r1: id = ECC_BRAINPOOLP512R1; break; default: @@ -9622,53 +9642,53 @@ int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group) } else { switch (group->curve_nid) { - case NID_secp112r1: - case NID_secp112r2: + case WC_NID_secp112r1: + case WC_NID_secp112r2: degree = 112; break; - case NID_secp128r1: - case NID_secp128r2: + case WC_NID_secp128r1: + case WC_NID_secp128r2: degree = 128; break; - case NID_secp160k1: - case NID_secp160r1: - case NID_secp160r2: - case NID_brainpoolP160r1: + case WC_NID_secp160k1: + case WC_NID_secp160r1: + case WC_NID_secp160r2: + case WC_NID_brainpoolP160r1: degree = 160; break; - case NID_secp192k1: - case NID_brainpoolP192r1: - case NID_X9_62_prime192v1: - case NID_X9_62_prime192v2: - case NID_X9_62_prime192v3: + case WC_NID_secp192k1: + case WC_NID_brainpoolP192r1: + case WC_NID_X9_62_prime192v1: + case WC_NID_X9_62_prime192v2: + case WC_NID_X9_62_prime192v3: degree = 192; break; - case NID_secp224k1: - case NID_secp224r1: - case NID_brainpoolP224r1: + case WC_NID_secp224k1: + case WC_NID_secp224r1: + case WC_NID_brainpoolP224r1: degree = 224; break; - case NID_X9_62_prime239v1: - case NID_X9_62_prime239v2: - case NID_X9_62_prime239v3: + case WC_NID_X9_62_prime239v1: + case WC_NID_X9_62_prime239v2: + case WC_NID_X9_62_prime239v3: degree = 239; break; - case NID_secp256k1: - case NID_brainpoolP256r1: - case NID_X9_62_prime256v1: + case WC_NID_secp256k1: + case WC_NID_brainpoolP256r1: + case WC_NID_X9_62_prime256v1: degree = 256; break; - case NID_brainpoolP320r1: + case WC_NID_brainpoolP320r1: degree = 320; break; - case NID_secp384r1: - case NID_brainpoolP384r1: + case WC_NID_secp384r1: + case WC_NID_brainpoolP384r1: degree = 384; break; - case NID_brainpoolP512r1: + case WC_NID_brainpoolP512r1: degree = 512; break; - case NID_secp521r1: + case WC_NID_secp521r1: degree = 521; break; } @@ -10139,7 +10159,7 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, if (!err) { /* [] */ len = sz + 1; - if (form == POINT_CONVERSION_UNCOMPRESSED) { + if (form == WC_POINT_CONVERSION_UNCOMPRESSED) { /* Include y ordinate when uncompressed. */ len += sz; } @@ -10165,7 +10185,7 @@ char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group, } } if (!err) { - if (form == POINT_CONVERSION_COMPRESSED) { + if (form == WC_POINT_CONVERSION_COMPRESSED) { /* Compressed format byte value dependent on whether y-ordinate is * odd. */ @@ -10222,13 +10242,13 @@ static size_t hex_to_bytes(const char *hex, unsigned char *output, size_t sz) return sz; } -WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const EC_GROUP *group, +WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const WOLFSSL_EC_GROUP *group, const char *hex, WOLFSSL_EC_POINT*p, WOLFSSL_BN_CTX *ctx) { /* for uncompressed mode */ size_t str_sz; - BIGNUM *Gx = NULL; - BIGNUM *Gy = NULL; + WOLFSSL_BIGNUM *Gx = NULL; + WOLFSSL_BIGNUM *Gy = NULL; char strGx[MAX_ECC_BYTES * 2 + 1]; /* for compressed mode */ @@ -10295,7 +10315,7 @@ WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const EC_GROUP *group, wolfSSL_BN_free(Gx); wolfSSL_BN_free(Gy); if (p_alloc) { - EC_POINT_free(p); + wolfSSL_EC_POINT_free(p); } return NULL; @@ -10473,7 +10493,7 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, int err = 0; word32 enc_len = (word32)len; #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) - int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0); + int compressed = ((form == WC_POINT_CONVERSION_COMPRESSED) ? 1 : 0); #endif /* !HAVE_SELFTEST */ WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct"); @@ -10498,7 +10518,7 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, if (buf != NULL) { /* Check whether buffer has space. */ if (len < 1) { - ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL); + wolfSSL_ECerr(WOLFSSL_EC_F_EC_GFP_SIMPLE_POINT2OCT, BUFFER_E); err = 1; } else { @@ -10510,9 +10530,9 @@ size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group, /* Not infinity. */ else if (!err) { /* Validate format. */ - if (form != POINT_CONVERSION_UNCOMPRESSED + if (form != WC_POINT_CONVERSION_UNCOMPRESSED #ifndef HAVE_SELFTEST - && form != POINT_CONVERSION_COMPRESSED + && form != WC_POINT_CONVERSION_COMPRESSED #endif /* !HAVE_SELFTEST */ ) { WOLFSSL_MSG("Unsupported point form"); @@ -10593,8 +10613,8 @@ int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group, * @param [in] group EC group. * @param [in] point EC point. * @param [in] form Format of encoding. Valid values: - * POINT_CONVERSION_UNCOMPRESSED, - * POINT_CONVERSION_COMPRESSED. + * WC_POINT_CONVERSION_UNCOMPRESSED, + * WC_POINT_CONVERSION_COMPRESSED. * @param [in, out] bn BN to hold point value. * When NULL a new BN is allocated otherwise this is * returned on success. @@ -10811,10 +10831,10 @@ int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group, } /* Copy the externally set x and y ordinates. */ - if ((ret == 1) && (BN_copy(x, point->X) == NULL)) { + if ((ret == 1) && (wolfSSL_BN_copy(x, point->X) == NULL)) { ret = 0; } - if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) { + if ((ret == 1) && (wolfSSL_BN_copy(y, point->Y) == NULL)) { ret = 0; } @@ -11831,7 +11851,7 @@ WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId) /* Cache heap hint. */ key->heap = heap; /* Initialize fields to defaults. */ - key->form = POINT_CONVERSION_UNCOMPRESSED; + key->form = WC_POINT_CONVERSION_UNCOMPRESSED; /* Initialize reference count. */ wolfSSL_RefInit(&key->ref, &err); @@ -11857,7 +11877,7 @@ WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId) if (!err) { /* Group unknown at creation */ - key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef); + key->group = wolfSSL_EC_GROUP_new_by_curve_name(WC_NID_undef); if (key->group == NULL) { WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure"); err = 1; @@ -12194,7 +12214,7 @@ int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out) { int ret = 1; size_t len = 0; - int form = POINT_CONVERSION_UNCOMPRESSED; + int form = WC_POINT_CONVERSION_UNCOMPRESSED; WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey"); @@ -12214,9 +12234,9 @@ int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out) if (ret == 1) { #ifdef HAVE_COMP_KEY /* Default to compressed form if not set */ - form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ? - POINT_CONVERSION_UNCOMPRESSED : - POINT_CONVERSION_COMPRESSED; + form = (key->form != WC_POINT_CONVERSION_UNCOMPRESSED) ? + WC_POINT_CONVERSION_UNCOMPRESSED : + WC_POINT_CONVERSION_COMPRESSED; #endif /* Calculate length of point encoding. */ @@ -12880,7 +12900,7 @@ int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec) * @return 0 on error. */ int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec, - const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, wc_pem_password_cb* cb, void* arg) { int ret = 1; @@ -12928,7 +12948,7 @@ int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec, * @return 0 on error. */ int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec, - const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen) { #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) @@ -12960,7 +12980,7 @@ int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec, /* Calculate maximum size of DER encoding. * 4 > size of pub, priv + ASN.1 additional information */ der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) + - AES_BLOCK_SIZE; + WC_AES_BLOCK_SIZE; /* Allocate buffer big enough to hold encoding. */ derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, @@ -13017,7 +13037,7 @@ int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec, * @return 0 on error. */ int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec, - const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, + const WOLFSSL_EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, wc_pem_password_cb *cb, void *pass) { int ret = 1; @@ -13120,7 +13140,7 @@ int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent) if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) { /* Get the public key point as one BN. */ WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group, - key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL); + key->pub_key, WC_POINT_CONVERSION_UNCOMPRESSED, NULL, NULL); if (pubBn == NULL) { WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed."); ret = 0; @@ -13311,7 +13331,8 @@ int SetECKeyInternal(WOLFSSL_EC_KEY* eckey) * @return Point conversion format on success. * @return -1 on error. */ -point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key) +wc_point_conversion_form_t wolfSSL_EC_KEY_get_conv_form( + const WOLFSSL_EC_KEY* key) { if (key == NULL) return WOLFSSL_FATAL_ERROR; @@ -13322,17 +13343,17 @@ point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key) * * @param [in, out] key EC key to set format into. * @param [in] form Point conversion format. Valid values: - * POINT_CONVERSION_UNCOMPRESSED, - * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY) + * WC_POINT_CONVERSION_UNCOMPRESSED, + * WC_POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY) */ void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form) { if (key == NULL) { WOLFSSL_MSG("Key passed in NULL"); } - else if (form == POINT_CONVERSION_UNCOMPRESSED + else if (form == WC_POINT_CONVERSION_UNCOMPRESSED #ifdef HAVE_COMP_KEY - || form == POINT_CONVERSION_COMPRESSED + || form == WC_POINT_CONVERSION_COMPRESSED #endif ) { key->form = (unsigned char)form; @@ -14041,7 +14062,7 @@ int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key) { int err = 0; int len = 0; - const EC_GROUP *group = NULL; + const WOLFSSL_EC_GROUP *group = NULL; int bits = 0; /* Validate parameter. */ @@ -15478,24 +15499,24 @@ int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key) if ((bio != NULL) && (key != NULL)) { switch (key->type) { #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: ret = wolfSSL_PEM_write_bio_RSA_PUBKEY(bio, key->rsa); break; #endif /* WOLFSSL_KEY_GEN && !NO_RSA */ #if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && \ (defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN)) - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: ret = wolfSSL_PEM_write_bio_DSA_PUBKEY(bio, key->dsa); break; #endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */ #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && \ defined(WOLFSSL_KEY_GEN) - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: ret = wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key->ecc); break; #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */ #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: /* DH public key not supported. */ WOLFSSL_MSG("Writing DH PUBKEY not supported!"); break; @@ -15546,21 +15567,21 @@ int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key, #ifdef WOLFSSL_KEY_GEN switch (key->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: /* Write using RSA specific API. */ ret = wolfSSL_PEM_write_bio_RSAPrivateKey(bio, key->rsa, cipher, passwd, len, cb, arg); break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: /* Write using DSA specific API. */ ret = wolfSSL_PEM_write_bio_DSAPrivateKey(bio, key->dsa, cipher, passwd, len, cb, arg); break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: #if defined(HAVE_ECC_KEY_EXPORT) /* Write using EC specific API. */ ret = wolfSSL_PEM_write_bio_ECPrivateKey(bio, key->ecc, @@ -15572,7 +15593,7 @@ int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key, break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: /* Write using generic API with DH type. */ ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, key->pkey_sz, bio, DH_PRIVATEKEY_TYPE); @@ -15588,22 +15609,22 @@ int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key, switch (key->type) { #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: type = DSA_PRIVATEKEY_TYPE; break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: type = ECC_PRIVATEKEY_TYPE; break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: type = DH_PRIVATEKEY_TYPE; break; #endif #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: type = PRIVATEKEY_TYPE; break; #endif @@ -15719,16 +15740,16 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, /* No key format set - default to RSA. */ case 0: case RSAk: - type = EVP_PKEY_RSA; + type = WC_EVP_PKEY_RSA; break; case DSAk: - type = EVP_PKEY_DSA; + type = WC_EVP_PKEY_DSA; break; case ECDSAk: - type = EVP_PKEY_EC; + type = WC_EVP_PKEY_EC; break; case DHk: - type = EVP_PKEY_DH; + type = WC_EVP_PKEY_DH; break; default: type = WOLFSSL_FATAL_ERROR; @@ -15761,8 +15782,9 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, } -PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, - PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, void* arg) +WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO( + WOLFSSL_BIO* bio, WOLFSSL_PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, + void* arg) { return wolfSSL_PEM_read_bio_PrivateKey(bio, key, cb, arg); } @@ -15865,16 +15887,16 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key, /* No key format set - default to RSA. */ case 0: case RSAk: - type = EVP_PKEY_RSA; + type = WC_EVP_PKEY_RSA; break; case DSAk: - type = EVP_PKEY_DSA; + type = WC_EVP_PKEY_DSA; break; case ECDSAk: - type = EVP_PKEY_EC; + type = WC_EVP_PKEY_EC; break; case DHk: - type = EVP_PKEY_DH; + type = WC_EVP_PKEY_DH; break; default: type = WOLFSSL_FATAL_ERROR; @@ -16478,13 +16500,13 @@ int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) { int ret = 0; - int algId; - const byte* curveOid; - word32 oidSz; + int algId = 0; + const byte* curveOid = 0; + word32 oidSz = 0; /* Get the details of the private key. */ #ifdef HAVE_ECC - if (pkey->type == EVP_PKEY_EC) { + if (pkey->type == WC_EVP_PKEY_EC) { /* ECC private and get curve OID information. */ algId = ECDSAk; ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid, @@ -16492,19 +16514,20 @@ int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) } else #endif - if (pkey->type == EVP_PKEY_RSA) { + if (pkey->type == WC_EVP_PKEY_RSA) { /* RSA private has no curve information. */ algId = RSAk; curveOid = NULL; oidSz = 0; } - else if (pkey->type == EVP_PKEY_DSA) { + else if (pkey->type == WC_EVP_PKEY_DSA) { /* DSA has no curve information. */ algId = DSAk; curveOid = NULL; oidSz = 0; } - else if (pkey->type == EVP_PKEY_DH) { +#ifndef NO_DH + else if (pkey->type == WC_EVP_PKEY_DH) { if (pkey->dh == NULL) return BAD_FUNC_ARG; @@ -16526,6 +16549,7 @@ int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) curveOid = NULL; oidSz = 0; } +#endif else { ret = NOT_COMPILED_IN; } @@ -16563,7 +16587,7 @@ static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz, int ret = 0; char password[NAME_SZ]; byte* key = NULL; - word32 keySz; + word32 keySz = 0; int type = PKCS8_PRIVATEKEY_TYPE; /* Validate parameters. */ diff --git a/src/src/quic.c b/src/src/quic.c index f709ea6..64cf14f 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -1193,7 +1193,7 @@ int wolfSSL_quic_hkdf_extract(uint8_t* dest, const WOLFSSL_EVP_MD* md, WOLFSSL_ENTER("wolfSSL_quic_hkdf_extract"); - pctx = wolfSSL_EVP_PKEY_CTX_new_id(NID_hkdf, NULL); + pctx = wolfSSL_EVP_PKEY_CTX_new_id(WC_NID_hkdf, NULL); if (pctx == NULL) { ret = WOLFSSL_FAILURE; goto cleanup; @@ -1201,7 +1201,7 @@ int wolfSSL_quic_hkdf_extract(uint8_t* dest, const WOLFSSL_EVP_MD* md, if (wolfSSL_EVP_PKEY_derive_init(pctx) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_hkdf_mode( - pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != WOLFSSL_SUCCESS + pctx, WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set_hkdf_md(pctx, md) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt( pctx, (byte*)salt, (int)saltlen) != WOLFSSL_SUCCESS @@ -1230,7 +1230,7 @@ int wolfSSL_quic_hkdf_expand(uint8_t* dest, size_t destlen, WOLFSSL_ENTER("wolfSSL_quic_hkdf_expand"); - pctx = wolfSSL_EVP_PKEY_CTX_new_id(NID_hkdf, NULL); + pctx = wolfSSL_EVP_PKEY_CTX_new_id(WC_NID_hkdf, NULL); if (pctx == NULL) { ret = WOLFSSL_FAILURE; goto cleanup; @@ -1238,7 +1238,7 @@ int wolfSSL_quic_hkdf_expand(uint8_t* dest, size_t destlen, if (wolfSSL_EVP_PKEY_derive_init(pctx) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_hkdf_mode( - pctx, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) != WOLFSSL_SUCCESS + pctx, WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set_hkdf_md(pctx, md) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt( pctx, (byte*)"", 0) != WOLFSSL_SUCCESS @@ -1253,7 +1253,7 @@ int wolfSSL_quic_hkdf_expand(uint8_t* dest, size_t destlen, cleanup: if (pctx) - EVP_PKEY_CTX_free(pctx); + wolfSSL_EVP_PKEY_CTX_free(pctx); WOLFSSL_LEAVE("wolfSSL_quic_hkdf_expand", ret); return ret; } @@ -1270,7 +1270,7 @@ int wolfSSL_quic_hkdf(uint8_t* dest, size_t destlen, WOLFSSL_ENTER("wolfSSL_quic_hkdf"); - pctx = wolfSSL_EVP_PKEY_CTX_new_id(NID_hkdf, NULL); + pctx = wolfSSL_EVP_PKEY_CTX_new_id(WC_NID_hkdf, NULL); if (pctx == NULL) { ret = WOLFSSL_FAILURE; goto cleanup; @@ -1278,7 +1278,7 @@ int wolfSSL_quic_hkdf(uint8_t* dest, size_t destlen, if (wolfSSL_EVP_PKEY_derive_init(pctx) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_hkdf_mode( - pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) != WOLFSSL_SUCCESS + pctx, WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set_hkdf_md(pctx, md) != WOLFSSL_SUCCESS || wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt( pctx, (byte*)salt, (int)saltlen) != WOLFSSL_SUCCESS @@ -1293,7 +1293,7 @@ int wolfSSL_quic_hkdf(uint8_t* dest, size_t destlen, cleanup: if (pctx) - EVP_PKEY_CTX_free(pctx); + wolfSSL_EVP_PKEY_CTX_free(pctx); WOLFSSL_LEAVE("wolfSSL_quic_hkdf", ret); return ret; } @@ -1346,7 +1346,7 @@ int wolfSSL_quic_aead_encrypt(uint8_t* dest, WOLFSSL_EVP_CIPHER_CTX* ctx, ctx, dest, &len, plain, (int)plainlen) != WOLFSSL_SUCCESS || wolfSSL_EVP_CipherFinal(ctx, dest + len, &len) != WOLFSSL_SUCCESS || wolfSSL_EVP_CIPHER_CTX_ctrl( - ctx, EVP_CTRL_AEAD_GET_TAG, ctx->authTagSz, dest + plainlen) + ctx, WOLFSSL_EVP_CTRL_AEAD_GET_TAG, ctx->authTagSz, dest + plainlen) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -1373,7 +1373,7 @@ int wolfSSL_quic_aead_decrypt(uint8_t* dest, WOLFSSL_EVP_CIPHER_CTX* ctx, if (wolfSSL_EVP_CipherInit(ctx, NULL, NULL, iv, 0) != WOLFSSL_SUCCESS || wolfSSL_EVP_CIPHER_CTX_ctrl( - ctx, EVP_CTRL_AEAD_SET_TAG, ctx->authTagSz, (uint8_t*)tag) + ctx, WOLFSSL_EVP_CTRL_AEAD_SET_TAG, ctx->authTagSz, (uint8_t*)tag) != WOLFSSL_SUCCESS || wolfSSL_EVP_CipherUpdate(ctx, NULL, &len, aad, (int)aadlen) != WOLFSSL_SUCCESS diff --git a/src/src/sniffer.c b/src/src/sniffer.c index 758e7be..a3814a4 100644 --- a/src/src/sniffer.c +++ b/src/src/sniffer.c @@ -227,8 +227,8 @@ BOOL APIENTRY DllMain( HMODULE hModule, #endif /* _WIN32 */ -static WOLFSSL_GLOBAL int TraceOn = 0; /* Trace is off by default */ -static WOLFSSL_GLOBAL XFILE TraceFile = 0; +static WC_THREADSHARED int TraceOn = 0; /* Trace is off by default */ +static WC_THREADSHARED XFILE TraceFile = 0; /* windows uses .rc table for this */ @@ -566,52 +566,52 @@ typedef struct SnifferSession { /* Sniffer Server List and mutex */ -static THREAD_LS_T WOLFSSL_GLOBAL SnifferServer* ServerList = NULL; +static THREAD_LS_T SnifferServer* ServerList = NULL; #ifndef HAVE_C___ATOMIC -static WOLFSSL_GLOBAL wolfSSL_Mutex ServerListMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(ServerListMutex); +static WC_THREADSHARED wolfSSL_Mutex ServerListMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(ServerListMutex); #endif /* Session Hash Table, mutex, and count */ -static THREAD_LS_T WOLFSSL_GLOBAL SnifferSession* SessionTable[HASH_SIZE]; +static THREAD_LS_T SnifferSession* SessionTable[HASH_SIZE]; #ifndef HAVE_C___ATOMIC -static WOLFSSL_GLOBAL wolfSSL_Mutex SessionMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(SessionMutex); +static WC_THREADSHARED wolfSSL_Mutex SessionMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(SessionMutex); #endif -static THREAD_LS_T WOLFSSL_GLOBAL int SessionCount = 0; +static THREAD_LS_T int SessionCount = 0; -static WOLFSSL_GLOBAL int RecoveryEnabled = 0; /* global switch */ -static WOLFSSL_GLOBAL int MaxRecoveryMemory = -1; +static WC_THREADSHARED int RecoveryEnabled = 0; /* global switch */ +static WC_THREADSHARED int MaxRecoveryMemory = -1; /* per session max recovery memory */ #ifndef WOLFSSL_SNIFFER_NO_RECOVERY /* Recovery of missed data switches and stats */ -static WOLFSSL_GLOBAL wolfSSL_Mutex RecoveryMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(RecoveryMutex); /* for stats */ +static WC_THREADSHARED wolfSSL_Mutex RecoveryMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(RecoveryMutex); /* for stats */ /* # of sessions with missed data */ -static WOLFSSL_GLOBAL word32 MissedDataSessions = 0; +static WC_THREADSHARED word32 MissedDataSessions = 0; #endif /* Connection Info Callback */ -static WOLFSSL_GLOBAL SSLConnCb ConnectionCb; -static WOLFSSL_GLOBAL void* ConnectionCbCtx = NULL; +static WC_THREADSHARED SSLConnCb ConnectionCb; +static WC_THREADSHARED void* ConnectionCbCtx = NULL; #ifdef WOLFSSL_SNIFFER_STATS /* Sessions Statistics */ -static WOLFSSL_GLOBAL SSLStats SnifferStats; -static WOLFSSL_GLOBAL wolfSSL_Mutex StatsMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(StatsMutex); +static WC_THREADSHARED SSLStats SnifferStats; +static WC_THREADSHARED wolfSSL_Mutex StatsMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(StatsMutex); #endif #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK -static WOLFSSL_GLOBAL SSLKeyCb KeyCb; -static WOLFSSL_GLOBAL void* KeyCbCtx = NULL; +static WC_THREADSHARED SSLKeyCb KeyCb; +static WC_THREADSHARED void* KeyCbCtx = NULL; #endif #ifdef WOLFSSL_SNIFFER_WATCH /* Watch Key Callback */ -static WOLFSSL_GLOBAL SSLWatchCb WatchCb; -static WOLFSSL_GLOBAL void* WatchCbCtx = NULL; +static WC_THREADSHARED SSLWatchCb WatchCb; +static WC_THREADSHARED void* WatchCbCtx = NULL; #endif #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB /* Store Data Callback */ -static WOLFSSL_GLOBAL SSLStoreDataCb StoreDataCb; +static WC_THREADSHARED SSLStoreDataCb StoreDataCb; #endif @@ -656,7 +656,7 @@ static void UpdateMissedDataSessions(void) #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT) - static WOLFSSL_GLOBAL int CryptoDeviceId = INVALID_DEVID; + static WC_THREADSHARED int CryptoDeviceId = INVALID_DEVID; #endif #if defined(WOLFSSL_SNIFFER_KEYLOGFILE) @@ -3854,8 +3854,10 @@ static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes, #endif if (session->sslServer->options.haveSessionId) { - if (XMEMCMP(session->sslServer->arrays->sessionID, - session->sslClient->arrays->sessionID, ID_LEN) == 0) { + if (session->sslServer->arrays->sessionIDSz == ID_LEN && + session->sslClient->arrays->sessionIDSz == ID_LEN && + XMEMCMP(session->sslServer->arrays->sessionID, + session->sslClient->arrays->sessionID, ID_LEN) == 0) { doResume = 1; } } @@ -4292,8 +4294,8 @@ static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz, char* error) { int ret; - Sha256 sha; - byte digest[SHA256_DIGEST_SIZE]; + wc_Sha256 sha; + byte digest[WC_SHA256_DIGEST_SIZE]; if (WatchCb == NULL) { SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE); @@ -6023,8 +6025,7 @@ static int CheckSequence(IpInfo* ipInfo, TcpInfo* tcpInfo, /* returns 0 on success (continue), -1 on error, 1 on success (end) */ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte** sslFrame, SnifferSession** pSession, - int* sslBytes, const byte** end, - void* vChain, word32 chainSz, char* error) + int* sslBytes, const byte** end, char* error) { word32 length; SnifferSession* session = *pSession; @@ -6094,53 +6095,12 @@ static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo, return WOLFSSL_FATAL_ERROR; } } - if (vChain == NULL) { - XMEMCPY(&ssl->buffers.inputBuffer.buffer[length], - *sslFrame, *sslBytes); - *sslBytes += length; - ssl->buffers.inputBuffer.length = *sslBytes; - *sslFrame = ssl->buffers.inputBuffer.buffer; - *end = *sslFrame + *sslBytes; - } - else { - #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT - struct iovec* chain = (struct iovec*)vChain; - word32 i, offset, headerSz, qty, remainder; - - Trace(CHAIN_INPUT_STR); - headerSz = (word32)((const byte*)*sslFrame - (const byte*)chain[0].iov_base); - remainder = *sslBytes; - - if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) { - if (GrowInputBuffer(ssl, *sslBytes, length) < 0) { - SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE); - return WOLFSSL_FATAL_ERROR; - } - } - - qty = min(*sslBytes, (word32)chain[0].iov_len - headerSz); - XMEMCPY(&ssl->buffers.inputBuffer.buffer[length], - (byte*)chain[0].iov_base + headerSz, qty); - offset = length; - for (i = 1; i < chainSz; i++) { - offset += qty; - remainder -= qty; - - if (chain[i].iov_len > remainder) - qty = remainder; - else - qty = (word32)chain[i].iov_len; - XMEMCPY(ssl->buffers.inputBuffer.buffer + offset, - chain[i].iov_base, qty); - } - - *sslBytes += length; - ssl->buffers.inputBuffer.length = *sslBytes; - *sslFrame = ssl->buffers.inputBuffer.buffer; - *end = *sslFrame + *sslBytes; - #endif - (void)chainSz; - } + XMEMCPY(&ssl->buffers.inputBuffer.buffer[length], + *sslFrame, *sslBytes); + *sslBytes += length; + ssl->buffers.inputBuffer.length = *sslBytes; + *sslFrame = ssl->buffers.inputBuffer.buffer; + *end = *sslFrame + *sslBytes; } if (session->flags.clientHello == 0 && **sslFrame != handshake) { @@ -6616,27 +6576,33 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, { TcpInfo tcpInfo; IpInfo ipInfo; + byte* tmpPacket = NULL; /* Assemble the chain */ const byte* sslFrame; const byte* end; int sslBytes; /* ssl bytes unconsumed */ int ret; SnifferSession* session = NULL; - void* vChain = NULL; - word32 chainSz = 0; if (isChain) { #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT struct iovec* chain; word32 i; - vChain = (void*)packet; - chainSz = (word32)length; + word32 chainSz = (word32)length; - chain = (struct iovec*)vChain; + chain = (struct iovec*)packet; length = 0; - for (i = 0; i < chainSz; i++) + for (i = 0; i < chainSz; i++) length += chain[i].iov_len; + + tmpPacket = (byte*)XMALLOC(length, NULL, DYNAMIC_TYPE_SNIFFER_CHAIN_BUFFER); + if (tmpPacket == NULL) return MEMORY_E; + + length = 0; + for (i = 0; i < chainSz; i++) { + XMEMCPY(tmpPacket+length,chain[i].iov_base,chain[i].iov_len); length += chain[i].iov_len; - packet = (const byte*)chain[0].iov_base; + } + packet = (const byte*)tmpPacket; #else SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); return WOLFSSL_SNIFFER_ERROR; @@ -6645,18 +6611,27 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, if (CheckHeaders(&ipInfo, &tcpInfo, packet, length, &sslFrame, &sslBytes, error, 1, 1) != 0) { - return WOLFSSL_SNIFFER_ERROR; + ret = WOLFSSL_SNIFFER_ERROR; + goto exit_decode; } end = sslFrame + sslBytes; ret = CheckSession(&ipInfo, &tcpInfo, sslBytes, &session, error); - if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) - return WOLFSSL_SNIFFER_FATAL_ERROR; + if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) { + ret = WOLFSSL_SNIFFER_FATAL_ERROR; + goto exit_decode; + } #ifdef WOLFSSL_ASYNC_CRYPT - else if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return WC_PENDING_E; + else if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { + ret = WC_PENDING_E; + goto exit_decode; + } #endif - else if (ret == -1) return WOLFSSL_SNIFFER_ERROR; + else if (ret == -1) { + ret = WOLFSSL_SNIFFER_ERROR; + goto exit_decode; + } else if (ret == 1) { #ifdef WOLFSSL_SNIFFER_STATS if (sslBytes > 0) { @@ -6669,7 +6644,8 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, INC_STAT(SnifferStats.sslDecryptedPackets); } #endif - return 0; /* done for now */ + ret = 0; + goto exit_decode; /* done for now */ } #ifdef WOLFSSL_ASYNC_CRYPT @@ -6677,30 +6653,41 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, #endif ret = CheckSequence(&ipInfo, &tcpInfo, session, &sslBytes, &sslFrame,error); - if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) - return WOLFSSL_SNIFFER_FATAL_ERROR; - else if (ret == -1) return WOLFSSL_SNIFFER_ERROR; + if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) { + ret = WOLFSSL_SNIFFER_FATAL_ERROR; + goto exit_decode; + } + else if (ret == -1) { + ret = WOLFSSL_SNIFFER_ERROR; + goto exit_decode; + } else if (ret == 1) { #ifdef WOLFSSL_SNIFFER_STATS INC_STAT(SnifferStats.sslDecryptedPackets); #endif - return 0; /* done for now */ + ret = 0; + goto exit_decode; /* done for now */ } else if (ret != 0) { - /* return specific error case */ - return ret; + goto exit_decode; /* return specific error case */ } ret = CheckPreRecord(&ipInfo, &tcpInfo, &sslFrame, &session, &sslBytes, - &end, vChain, chainSz, error); - if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) - return WOLFSSL_SNIFFER_FATAL_ERROR; - else if (ret == -1) return WOLFSSL_SNIFFER_ERROR; + &end, error); + if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) { + ret = WOLFSSL_SNIFFER_FATAL_ERROR; + goto exit_decode; + } + else if (ret == -1) { + ret = WOLFSSL_SNIFFER_ERROR; + goto exit_decode; + } else if (ret == 1) { #ifdef WOLFSSL_SNIFFER_STATS INC_STAT(SnifferStats.sslDecryptedPackets); #endif - return 0; /* done for now */ + ret = 0; + goto exit_decode; /* done for now */ } #ifdef WOLFSSL_ASYNC_CRYPT @@ -6708,7 +6695,8 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, if (asyncOkay && session->sslServer->error == WC_NO_ERR_TRACE(WC_PENDING_E) && !session->flags.wasPolled) { - return WC_PENDING_E; + ret = WC_PENDING_E; + goto exit_decode; } #endif @@ -6745,7 +6733,7 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, wolfSSL_AsyncPoll(session->sslServer, WOLF_POLL_FLAG_CHECK_HW); } else { - return ret; /* return to caller */ + goto exit_decode; /* return to caller */ } } else { @@ -6756,12 +6744,18 @@ static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain, (void)asyncOkay; #endif - if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) - return WOLFSSL_SNIFFER_FATAL_ERROR; + if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) { + ret = WOLFSSL_SNIFFER_FATAL_ERROR; + goto exit_decode; + } if (CheckFinCapture(&ipInfo, &tcpInfo, session) == 0) { CopySessionInfo(session, sslInfo); } +exit_decode: + if (isChain) { + XFREE(tmpPacket, NULL, DYNAMIC_TYPE_SNIFFER_CHAIN_BUFFER); + } return ret; } @@ -6868,11 +6862,15 @@ int ssl_Trace(const char* traceFile, char* error) if (traceFile) { /* Don't try to reopen the file */ if (TraceFile == NULL) { - TraceFile = XFOPEN(traceFile, "a"); - if (!TraceFile) { - SetError(BAD_TRACE_FILE_STR, error, NULL, 0); - return WOLFSSL_FATAL_ERROR; - } + if (XSTRCMP(traceFile, "-") == 0) { + TraceFile = stdout; + } else { + TraceFile = XFOPEN(traceFile, "a"); + if (!TraceFile) { + SetError(BAD_TRACE_FILE_STR, error, NULL, 0); + return WOLFSSL_FATAL_ERROR; + } + } TraceOn = 1; } } @@ -7238,11 +7236,11 @@ typedef struct SecretNode { #define WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE HASH_SIZE #endif -static THREAD_LS_T WOLFSSL_GLOBAL +static THREAD_LS_T SecretNode* secretHashTable[WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE] = {NULL}; #ifndef HAVE_C___ATOMIC -static WOLFSSL_GLOBAL wolfSSL_Mutex secretListMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(secretListMutex); +static WC_THREADSHARED wolfSSL_Mutex secretListMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(secretListMutex); #endif static unsigned int secretHashFunction(unsigned char* clientRandom); diff --git a/src/src/ssl.c b/src/src/ssl.c index fe81193..c38fcbf 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -53,7 +53,7 @@ #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \ && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \ && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) - #error "No cipher suites defined because DH disabled, ECC disabled, " + #error "No cipher suites defined because DH disabled, ECC disabled, " \ "and no static suites defined. Please see top of README" #endif #ifdef WOLFSSL_CERT_GEN @@ -208,7 +208,7 @@ * * @param [in] sn Short name of OID. * @return NID corresponding to shortname on success. - * @return NID_undef when not recognized. + * @return WC_NID_undef when not recognized. */ int wc_OBJ_sn2nid(const char *sn) { @@ -217,21 +217,21 @@ int wc_OBJ_sn2nid(const char *sn) int nid; } sn2nid[] = { #ifndef NO_CERTS - {WOLFSSL_COMMON_NAME, NID_commonName}, - {WOLFSSL_COUNTRY_NAME, NID_countryName}, - {WOLFSSL_LOCALITY_NAME, NID_localityName}, - {WOLFSSL_STATE_NAME, NID_stateOrProvinceName}, - {WOLFSSL_ORG_NAME, NID_organizationName}, - {WOLFSSL_ORGUNIT_NAME, NID_organizationalUnitName}, + {WOLFSSL_COMMON_NAME, WC_NID_commonName}, + {WOLFSSL_COUNTRY_NAME, WC_NID_countryName}, + {WOLFSSL_LOCALITY_NAME, WC_NID_localityName}, + {WOLFSSL_STATE_NAME, WC_NID_stateOrProvinceName}, + {WOLFSSL_ORG_NAME, WC_NID_organizationName}, + {WOLFSSL_ORGUNIT_NAME, WC_NID_organizationalUnitName}, #ifdef WOLFSSL_CERT_NAME_ALL - {WOLFSSL_NAME, NID_name}, - {WOLFSSL_INITIALS, NID_initials}, - {WOLFSSL_GIVEN_NAME, NID_givenName}, - {WOLFSSL_DNQUALIFIER, NID_dnQualifier}, + {WOLFSSL_NAME, WC_NID_name}, + {WOLFSSL_INITIALS, WC_NID_initials}, + {WOLFSSL_GIVEN_NAME, WC_NID_givenName}, + {WOLFSSL_DNQUALIFIER, WC_NID_dnQualifier}, #endif - {WOLFSSL_EMAIL_ADDR, NID_emailAddress}, + {WOLFSSL_EMAIL_ADDR, WC_NID_emailAddress}, #endif - {"SHA1", NID_sha1}, + {"SHA1", WC_NID_sha1}, {NULL, -1}}; int i; #ifdef HAVE_ECC @@ -249,7 +249,7 @@ int wc_OBJ_sn2nid(const char *sn) #ifdef HAVE_ECC if (XSTRLEN(sn) > ECC_MAXNAME) - return NID_undef; + return WC_NID_undef; /* Nginx uses this OpenSSL string. */ if (XSTRCMP(sn, "prime256v1") == 0) @@ -275,12 +275,19 @@ int wc_OBJ_sn2nid(const char *sn) } #endif /* HAVE_ECC */ - return NID_undef; + return WC_NID_undef; } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifndef WOLFCRYPT_ONLY + +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) +/* The system wide crypto-policy. Configured by wolfSSL_crypto_policy_enable. + * */ +static struct SystemCryptoPolicy crypto_policy; +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + #if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \ (defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && !defined(NO_DSA)) @@ -1026,18 +1033,26 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) } #endif /* WOLFSSL_TLS13 && HAVE_ECH */ +#ifdef OPENSSL_EXTRA +static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl, + Suites* suites, const char* list); +#endif #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) #include #endif /* prevent multiple mutex initializations */ -static volatile WOLFSSL_GLOBAL int initRefCount = 0; +static volatile WC_THREADSHARED int initRefCount = 0; /* init ref count mutex */ -static WOLFSSL_GLOBAL wolfSSL_Mutex inits_count_mutex +static WC_THREADSHARED wolfSSL_Mutex inits_count_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex); #ifndef WOLFSSL_MUTEX_INITIALIZER -static WOLFSSL_GLOBAL int inits_count_mutex_valid = 0; +static WC_THREADSHARED volatile int inits_count_mutex_valid = 0; +#endif + +#ifdef NO_TLS +static const WOLFSSL_METHOD gNoTlsMethod; #endif /* Create a new WOLFSSL_CTX struct and return the pointer to created struct. @@ -1062,8 +1077,13 @@ WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap) } } +#ifndef NO_TLS if (method == NULL) return ctx; +#else + /* a blank TLS method */ + method = (WOLFSSL_METHOD*)&gNoTlsMethod; +#endif ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX); if (ctx) { @@ -1116,6 +1136,30 @@ WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap) } #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + /* Load the crypto-policy ciphers if configured. */ + if (ctx && wolfSSL_crypto_policy_is_enabled()) { + const char * list = wolfSSL_crypto_policy_get_ciphers(); + int ret = 0; + + if (list != NULL && *list != '\0') { + if (AllocateCtxSuites(ctx) != 0) { + WOLFSSL_MSG("allocate ctx suites failed"); + wolfSSL_CTX_free(ctx); + ctx = NULL; + } + else { + ret = wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("parse cipher list failed"); + wolfSSL_CTX_free(ctx); + ctx = NULL; + } + } + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0); return ctx; } @@ -1136,7 +1180,7 @@ WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method) int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx) { int ret; - wolfSSL_RefInc(&ctx->ref, &ret); + wolfSSL_RefWithMutexInc(&ctx->ref, &ret); #ifdef WOLFSSL_REFCNT_ERROR_RETURN return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE); #else @@ -1723,6 +1767,17 @@ int wolfSSL_get_fd(const WOLFSSL* ssl) return fd; } +int wolfSSL_get_wfd(const WOLFSSL* ssl) +{ + int fd = -1; + WOLFSSL_ENTER("wolfSSL_get_fd"); + if (ssl) { + fd = ssl->wfd; + } + WOLFSSL_LEAVE("wolfSSL_get_fd", fd); + return fd; +} + int wolfSSL_dtls(WOLFSSL* ssl) { @@ -1855,38 +1910,105 @@ int wolfSSL_dtls_free_peer(void* addr) } #endif +#ifdef WOLFSSL_DTLS +static int SockAddrSet(WOLFSSL_SOCKADDR* sockAddr, void* peer, + unsigned int peerSz, void* heap) +{ + if (peer == NULL || peerSz == 0) { + if (sockAddr->sa != NULL) + XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR); + sockAddr->sa = NULL; + sockAddr->sz = 0; + sockAddr->bufSz = 0; + return WOLFSSL_SUCCESS; + } + + if (peerSz > sockAddr->bufSz) { + if (sockAddr->sa != NULL) + XFREE(sockAddr->sa, heap, DYNAMIC_TYPE_SOCKADDR); + sockAddr->sa = + (void*)XMALLOC(peerSz, heap, DYNAMIC_TYPE_SOCKADDR); + if (sockAddr->sa == NULL) { + sockAddr->sz = 0; + sockAddr->bufSz = 0; + return WOLFSSL_FAILURE; + } + sockAddr->bufSz = peerSz; + } + XMEMCPY(sockAddr->sa, peer, peerSz); + sockAddr->sz = peerSz; + return WOLFSSL_SUCCESS; +} +#endif + int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz) { #ifdef WOLFSSL_DTLS - void* sa; + int ret; if (ssl == NULL) return WOLFSSL_FAILURE; - - if (peer == NULL || peerSz == 0) { - if (ssl->buffers.dtlsCtx.peer.sa != NULL) - XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR); - ssl->buffers.dtlsCtx.peer.sa = NULL; - ssl->buffers.dtlsCtx.peer.sz = 0; - ssl->buffers.dtlsCtx.peer.bufSz = 0; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Wr(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_FAILURE; +#endif + ret = SockAddrSet(&ssl->buffers.dtlsCtx.peer, peer, peerSz, ssl->heap); + if (ret == WOLFSSL_SUCCESS && !(peer == NULL || peerSz == 0)) + ssl->buffers.dtlsCtx.userSet = 1; + else ssl->buffers.dtlsCtx.userSet = 0; - return WOLFSSL_SUCCESS; - } +#ifdef WOLFSSL_RW_THREADED + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + ret = WOLFSSL_FAILURE; +#endif + return ret; +#else + (void)ssl; + (void)peer; + (void)peerSz; + return WOLFSSL_NOT_IMPLEMENTED; +#endif +} - sa = (void*)XMALLOC(peerSz, ssl->heap, DYNAMIC_TYPE_SOCKADDR); - if (sa != NULL) { - if (ssl->buffers.dtlsCtx.peer.sa != NULL) { - XFREE(ssl->buffers.dtlsCtx.peer.sa,ssl->heap,DYNAMIC_TYPE_SOCKADDR); - ssl->buffers.dtlsCtx.peer.sa = NULL; +#if defined(WOLFSSL_DTLS_CID) && !defined(WOLFSSL_NO_SOCK) +int wolfSSL_dtls_set_pending_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz) +{ +#ifdef WOLFSSL_DTLS + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + + if (ssl == NULL) + return WOLFSSL_FAILURE; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_FAILURE; +#endif + if (ssl->buffers.dtlsCtx.peer.sa != NULL && + ssl->buffers.dtlsCtx.peer.sz == peerSz && + sockAddrEqual((SOCKADDR_S*)ssl->buffers.dtlsCtx.peer.sa, + (XSOCKLENT)ssl->buffers.dtlsCtx.peer.sz, (SOCKADDR_S*)peer, + (XSOCKLENT)peerSz)) { + /* Already the current peer. */ + if (ssl->buffers.dtlsCtx.pendingPeer.sa != NULL) { + /* Clear any other pendingPeer */ + XFREE(ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->heap, + DYNAMIC_TYPE_SOCKADDR); + ssl->buffers.dtlsCtx.pendingPeer.sa = NULL; + ssl->buffers.dtlsCtx.pendingPeer.sz = 0; + ssl->buffers.dtlsCtx.pendingPeer.bufSz = 0; } - XMEMCPY(sa, peer, peerSz); - ssl->buffers.dtlsCtx.peer.sa = sa; - ssl->buffers.dtlsCtx.peer.sz = peerSz; - ssl->buffers.dtlsCtx.peer.bufSz = peerSz; - ssl->buffers.dtlsCtx.userSet = 1; - return WOLFSSL_SUCCESS; + ret = WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; + else { + ret = SockAddrSet(&ssl->buffers.dtlsCtx.pendingPeer, peer, peerSz, + ssl->heap); + } + if (ret == WOLFSSL_SUCCESS) + ssl->buffers.dtlsCtx.processingPendingRecord = 0; +#ifdef WOLFSSL_RW_THREADED + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + ret = WOLFSSL_FAILURE; +#endif + return ret; #else (void)ssl; (void)peer; @@ -1894,22 +2016,51 @@ int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz) return WOLFSSL_NOT_IMPLEMENTED; #endif } +#endif /* WOLFSSL_DTLS_CID && !WOLFSSL_NO_SOCK */ int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz) { #ifdef WOLFSSL_DTLS - if (ssl == NULL) { + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + if (ssl == NULL) return WOLFSSL_FAILURE; - } - +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_FAILURE; +#endif if (peer != NULL && peerSz != NULL && *peerSz >= ssl->buffers.dtlsCtx.peer.sz && ssl->buffers.dtlsCtx.peer.sa != NULL) { *peerSz = ssl->buffers.dtlsCtx.peer.sz; XMEMCPY(peer, ssl->buffers.dtlsCtx.peer.sa, *peerSz); - return WOLFSSL_SUCCESS; + ret = WOLFSSL_SUCCESS; } - return WOLFSSL_FAILURE; +#ifdef WOLFSSL_RW_THREADED + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + ret = WOLFSSL_FAILURE; +#endif + return ret; +#else + (void)ssl; + (void)peer; + (void)peerSz; + return WOLFSSL_NOT_IMPLEMENTED; +#endif +} + +int wolfSSL_dtls_get0_peer(WOLFSSL* ssl, const void** peer, + unsigned int* peerSz) +{ +#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_RW_THREADED) + if (ssl == NULL) + return WOLFSSL_FAILURE; + + if (peer == NULL || peerSz == NULL) + return WOLFSSL_FAILURE; + + *peer = ssl->buffers.dtlsCtx.peer.sa; + *peerSz = ssl->buffers.dtlsCtx.peer.sz; + return WOLFSSL_SUCCESS; #else (void)ssl; (void)peer; @@ -1976,9 +2127,9 @@ int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu) #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu) { if (wolfSSL_dtls_set_mtu(ssl, mtu) == 0) - return SSL_SUCCESS; + return WOLFSSL_SUCCESS; else - return SSL_FAILURE; + return WOLFSSL_FAILURE; } #endif /* OPENSSL_ALL || OPENSSL_EXTRA */ @@ -2073,6 +2224,13 @@ int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str) if (ctx != NULL) { ret = DtlsSrtpSelProfiles(&ctx->dtlsSrtpProfiles, profile_str); } + + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + ret = 1; + } else { + ret = 0; + } + return ret; } int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str) @@ -2081,6 +2239,13 @@ int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str) if (ssl != NULL) { ret = DtlsSrtpSelProfiles(&ssl->dtlsSrtpProfiles, profile_str); } + + if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + ret = 1; + } else { + ret = 0; + } + return ret; } @@ -2171,7 +2336,7 @@ int wolfSSL_CTX_mcast_set_member_id(WOLFSSL_CTX* ctx, word16 id) WOLFSSL_ENTER("wolfSSL_CTX_mcast_set_member_id"); - if (ctx == NULL || id > 255) + if (ctx == NULL || id > WOLFSSL_MAX_8BIT) ret = BAD_FUNC_ARG; if (ret == 0) { @@ -2306,7 +2471,7 @@ int wolfSSL_mcast_peer_add(WOLFSSL* ssl, word16 peerId, int sub) int i; WOLFSSL_ENTER("wolfSSL_mcast_peer_add"); - if (ssl == NULL || peerId > 255) + if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT) return BAD_FUNC_ARG; if (!sub) { @@ -2362,7 +2527,7 @@ int wolfSSL_mcast_peer_known(WOLFSSL* ssl, unsigned short peerId) WOLFSSL_ENTER("wolfSSL_mcast_peer_known"); - if (ssl == NULL || peerId > 255) { + if (ssl == NULL || peerId > WOLFSSL_MAX_8BIT) { return BAD_FUNC_ARG; } @@ -2418,7 +2583,7 @@ int wolfSSL_mcast_set_highwater_ctx(WOLFSSL* ssl, void* ctx) #endif /* WOLFSSL_LEANPSK */ - +#ifndef NO_TLS /* return underlying connect or accept, WOLFSSL_SUCCESS on ok */ int wolfSSL_negotiate(WOLFSSL* ssl) { @@ -2457,7 +2622,7 @@ int wolfSSL_negotiate(WOLFSSL* ssl) return err; } - +#endif /* !NO_TLS */ WOLFSSL_ABI WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl) @@ -2638,7 +2803,7 @@ int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats) #endif /* WOLFSSL_STATIC_MEMORY */ - +#ifndef NO_TLS /* return max record layer size plaintext input size */ int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl) { @@ -2686,6 +2851,14 @@ int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ctx->minEccKeySz > (keySz / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ctx->minEccKeySz = keySz / 8; #ifndef NO_CERTS ctx->cm->minEccKeySz = keySz / 8; @@ -2702,6 +2875,14 @@ int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ssl->options.minEccKeySz > (keySz / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ssl->options.minEccKeySz = keySz / 8; return WOLFSSL_SUCCESS; } @@ -2716,6 +2897,14 @@ int wolfSSL_CTX_SetMinRsaKey_Sz(WOLFSSL_CTX* ctx, short keySz) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ctx->minRsaKeySz > (keySz / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ctx->minRsaKeySz = keySz / 8; ctx->cm->minRsaKeySz = keySz / 8; return WOLFSSL_SUCCESS; @@ -2729,6 +2918,14 @@ int wolfSSL_SetMinRsaKey_Sz(WOLFSSL* ssl, short keySz) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ssl->options.minRsaKeySz > (keySz / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ssl->options.minRsaKeySz = keySz / 8; return WOLFSSL_SUCCESS; } @@ -2761,6 +2958,14 @@ int wolfSSL_CTX_SetMinDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits) if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0) return BAD_FUNC_ARG; +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ctx->minDhKeySz > (keySz_bits / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ctx->minDhKeySz = keySz_bits / 8; return WOLFSSL_SUCCESS; } @@ -2771,6 +2976,14 @@ int wolfSSL_SetMinDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits) if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0) return BAD_FUNC_ARG; +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ssl->options.minDhKeySz > (keySz_bits / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ssl->options.minDhKeySz = keySz_bits / 8; return WOLFSSL_SUCCESS; } @@ -2781,6 +2994,14 @@ int wolfSSL_CTX_SetMaxDhKey_Sz(WOLFSSL_CTX* ctx, word16 keySz_bits) if (ctx == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0) return BAD_FUNC_ARG; +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ctx->minDhKeySz > (keySz_bits / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ctx->maxDhKeySz = keySz_bits / 8; return WOLFSSL_SUCCESS; } @@ -2791,6 +3012,14 @@ int wolfSSL_SetMaxDhKey_Sz(WOLFSSL* ssl, word16 keySz_bits) if (ssl == NULL || keySz_bits > 16000 || keySz_bits % 8 != 0) return BAD_FUNC_ARG; +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + if (ssl->options.minDhKeySz > (keySz_bits / 8)) { + return CRYPTO_POLICY_FORBIDDEN; + } + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + ssl->options.maxDhKeySz = keySz_bits / 8; return WOLFSSL_SUCCESS; } @@ -2860,8 +3089,8 @@ int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz) #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_WRITE, WOLFSSL_SUCCESS); - ssl->cbmode = SSL_CB_WRITE; + ssl->CBIS(ssl, WOLFSSL_CB_WRITE, WOLFSSL_SUCCESS); + ssl->cbmode = WOLFSSL_CB_WRITE; } #endif ret = SendData(ssl, data, sz); @@ -2874,6 +3103,42 @@ int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz) return ret; } +int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz) +{ + int maxLength; + int usedLength; + + WOLFSSL_ENTER("wolfSSL_inject"); + + if (ssl == NULL || data == NULL || sz <= 0) + return BAD_FUNC_ARG; + + usedLength = (int)(ssl->buffers.inputBuffer.length - + ssl->buffers.inputBuffer.idx); + maxLength = (int)(ssl->buffers.inputBuffer.bufferSize - + (word32)usedLength); + + if (sz > maxLength) { + /* Need to make space */ + int ret; + if (ssl->buffers.clearOutputBuffer.length > 0) { + /* clearOutputBuffer points into so reallocating inputBuffer will + * invalidate clearOutputBuffer and lose app data */ + WOLFSSL_MSG("Can't inject while there is application data to read"); + return APP_DATA_READY; + } + ret = GrowInputBuffer(ssl, sz, usedLength); + if (ret < 0) + return ret; + } + + XMEMCPY(ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx, + data, sz); + ssl->buffers.inputBuffer.length += sz; + + return WOLFSSL_SUCCESS; +} + static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek) { int ret; @@ -2972,8 +3237,8 @@ int wolfSSL_read(WOLFSSL* ssl, void* data, int sz) return BAD_FUNC_ARG; } if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_CB_READ, WOLFSSL_SUCCESS); - ssl->cbmode = SSL_CB_READ; + ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS); + ssl->cbmode = WOLFSSL_CB_READ; } #endif return wolfSSL_read_internal(ssl, data, sz, FALSE); @@ -2998,7 +3263,7 @@ int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz) } #endif /* WOLFSSL_MULTICAST */ - +#endif /* !NO_TLS */ /* helpers to set the device id, WOLFSSL_SUCCESS on ok */ WOLFSSL_ABI @@ -3045,6 +3310,7 @@ void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl) } +#ifndef NO_TLS #ifdef HAVE_SNI WOLFSSL_ABI @@ -3110,7 +3376,7 @@ int wolfSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz, return BAD_FUNC_ARG; } -#endif /* NO_WOLFSSL_SERVER */ +#endif /* !NO_WOLFSSL_SERVER */ #endif /* HAVE_SNI */ @@ -3297,6 +3563,17 @@ static int isValidCurveGroup(word16 name) case WOLFSSL_FFDHE_8192: #ifdef WOLFSSL_HAVE_KYBER +#ifndef WOLFSSL_NO_ML_KEM + case WOLFSSL_ML_KEM_512: + case WOLFSSL_ML_KEM_768: + case WOLFSSL_ML_KEM_1024: + #if defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS) + case WOLFSSL_P256_ML_KEM_512: + case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P521_ML_KEM_1024: + #endif +#endif /* !WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_KYBER_ORIGINAL case WOLFSSL_KYBER_LEVEL1: case WOLFSSL_KYBER_LEVEL3: case WOLFSSL_KYBER_LEVEL5: @@ -3305,6 +3582,7 @@ static int isValidCurveGroup(word16 name) case WOLFSSL_P384_KYBER_LEVEL3: case WOLFSSL_P521_KYBER_LEVEL5: #endif +#endif /* WOLFSSL_KYBER_ORIGINAL */ #endif return 1; @@ -4100,7 +4378,7 @@ int wolfSSL_shutdown(WOLFSSL* ssl) return ret; } - +#endif /* !NO_TLS */ /* get current error state value */ int wolfSSL_state(WOLFSSL* ssl) @@ -4156,12 +4434,12 @@ int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h) /* returns SSL_WRITING, SSL_READING or SSL_NOTHING */ int wolfSSL_want(WOLFSSL* ssl) { - int rw_state = SSL_NOTHING; + int rw_state = WOLFSSL_NOTHING; if (ssl) { if (ssl->error == WC_NO_ERR_TRACE(WANT_READ)) - rw_state = SSL_READING; + rw_state = WOLFSSL_READING; else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) - rw_state = SSL_WRITING; + rw_state = WOLFSSL_WRITING; } return rw_state; } @@ -4177,7 +4455,6 @@ int wolfSSL_want_read(WOLFSSL* ssl) return 0; } - /* return TRUE if current error is want write */ int wolfSSL_want_write(WOLFSSL* ssl) { @@ -4188,7 +4465,6 @@ int wolfSSL_want_write(WOLFSSL* ssl) return 0; } - char* wolfSSL_ERR_error_string(unsigned long errNumber, char* data) { WOLFSSL_ENTER("wolfSSL_ERR_error_string"); @@ -4723,7 +4999,7 @@ int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx) #endif -#ifndef NO_WOLFSSL_CLIENT +#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) /* connect enough to get peer cert chain */ int wolfSSL_connect_cert(WOLFSSL* ssl) { @@ -4757,9 +5033,7 @@ int wolfSSL_set_group_messages(WOLFSSL* ssl) /* make minVersion the internal equivalent SSL version */ static int SetMinVersionHelper(byte* minVersion, int version) { -#ifdef NO_TLS (void)minVersion; -#endif switch (version) { #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS) @@ -4826,6 +5100,12 @@ int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + return CRYPTO_POLICY_FORBIDDEN; + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + return SetMinVersionHelper(&ctx->minDowngrade, version); } @@ -4840,6 +5120,12 @@ int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (crypto_policy.enabled) { + return CRYPTO_POLICY_FORBIDDEN; + } +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + return SetMinVersionHelper(&ssl->options.minDowngrade, version); } @@ -4949,8 +5235,7 @@ int wolfSSL_SetVersion(WOLFSSL* ssl, int version) InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); return WOLFSSL_SUCCESS; } #endif /* !leanpsk */ @@ -5020,8 +5305,13 @@ int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert) return ret; tp = cm->tpTable[row]; while (tp) { - if (XMEMCMP(cert->subjectHash, tp->subjectNameHash, + if ((XMEMCMP(cert->subjectHash, tp->subjectNameHash, SIGNER_DIGEST_SIZE) == 0) + #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER + && (XMEMCMP(cert->issuerHash, tp->issuerHash, + SIGNER_DIGEST_SIZE) == 0) + #endif + ) ret = 1; #ifndef NO_SKID if (cert->extSubjKeyIdSet) { @@ -5061,8 +5351,13 @@ TrustedPeerCert* GetTrustedPeer(void* vp, DecodedCert* cert) tp = cm->tpTable[row]; while (tp) { - if (XMEMCMP(cert->subjectHash, tp->subjectNameHash, + if ((XMEMCMP(cert->subjectHash, tp->subjectNameHash, + SIGNER_DIGEST_SIZE) == 0) + #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER + && (XMEMCMP(cert->issuerHash, tp->issuerHash, SIGNER_DIGEST_SIZE) == 0) + #endif + ) ret = tp; #ifndef NO_SKID if (cert->extSubjKeyIdSet) { @@ -5328,6 +5623,10 @@ int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify) #endif XMEMCPY(peerCert->subjectNameHash, cert->subjectHash, SIGNER_DIGEST_SIZE); + #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER + XMEMCPY(peerCert->issuerHash, cert->issuerHash, + SIGNER_DIGEST_SIZE); + #endif /* If Key Usage not set, all uses valid. */ peerCert->next = NULL; cert->subjectCN = 0; @@ -5569,6 +5868,29 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) row = HashSigner(signer->subjectNameHash); #endif + #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) + /* Verify CA by TSIP so that generated tsip key is going to */ + /* be able to be used for peer's cert verification */ + /* TSIP is only able to handle USER CA, and only one CA. */ + /* Therefore, it doesn't need to call TSIP again if there is already */ + /* verified CA. */ + if ( ret == 0 && signer != NULL ) { + signer->cm_idx = row; + if (type == WOLFSSL_USER_CA) { + if ((ret = wc_Renesas_cmn_RootCertVerify(cert->source, + cert->maxIdx, + cert->sigCtx.CertAtt.pubkey_n_start, + cert->sigCtx.CertAtt.pubkey_n_len - 1, + cert->sigCtx.CertAtt.pubkey_e_start, + cert->sigCtx.CertAtt.pubkey_e_len - 1, + row/* cm index */)) + < 0) + WOLFSSL_MSG("Renesas_RootCertVerify() failed"); + else + WOLFSSL_MSG("Renesas_RootCertVerify() succeed or skipped"); + } + } + #endif /* TSIP or SCE */ if (ret == 0 && wc_LockMutex(&cm->caLock) == 0) { signer->next = cm->caTable[row]; @@ -5582,28 +5904,6 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) ret = BAD_MUTEX_E; } } -#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) - /* Verify CA by TSIP so that generated tsip key is going to be able to */ - /* be used for peer's cert verification */ - /* TSIP is only able to handle USER CA, and only one CA. */ - /* Therefore, it doesn't need to call TSIP again if there is already */ - /* verified CA. */ - if ( ret == 0 && signer != NULL ) { - signer->cm_idx = row; - if (type == WOLFSSL_USER_CA) { - if ((ret = wc_Renesas_cmn_RootCertVerify(cert->source, cert->maxIdx, - cert->sigCtx.CertAtt.pubkey_n_start, - cert->sigCtx.CertAtt.pubkey_n_len - 1, - cert->sigCtx.CertAtt.pubkey_e_start, - cert->sigCtx.CertAtt.pubkey_e_len - 1, - row/* cm index */)) - < 0) - WOLFSSL_MSG("Renesas_RootCertVerify() failed"); - else - WOLFSSL_MSG("Renesas_RootCertVerify() succeed or skipped"); - } - } -#endif /* TSIP or SCE */ WOLFSSL_MSG("\tFreeing Parsed CA"); FreeDecodedCert(cert); @@ -5628,12 +5928,48 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) static int wolfSSL_RAND_InitMutex(void); #endif +/* If we don't have static mutex initializers, but we do have static atomic + * initializers, activate WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS to leverage + * the latter. + * + * See further explanation below in wolfSSL_Init(). + */ +#ifndef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + #if !defined(WOLFSSL_MUTEX_INITIALIZER) && !defined(SINGLE_THREADED) && \ + defined(WOLFSSL_ATOMIC_OPS) && defined(WOLFSSL_ATOMIC_INITIALIZER) + #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 1 + #else + #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0 + #endif +#elif defined(WOLFSSL_MUTEX_INITIALIZER) || defined(SINGLE_THREADED) + #undef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0 +#endif + +#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + #ifndef WOLFSSL_ATOMIC_OPS + #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_OPS + #endif + #ifndef WOLFSSL_ATOMIC_INITIALIZER + #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_INITIALIZER + #endif + static wolfSSL_Atomic_Int inits_count_mutex_atomic_initing_flag = + WOLFSSL_ATOMIC_INITIALIZER(0); +#endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS && !WOLFSSL_MUTEX_INITIALIZER */ + #if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT) static void AtExitCleanup(void) { if (initRefCount > 0) { initRefCount = 1; (void)wolfSSL_Cleanup(); +#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + if (inits_count_mutex_valid == 1) { + (void)wc_FreeMutex(&inits_count_mutex); + inits_count_mutex_valid = 0; + inits_count_mutex_atomic_initing_flag = 0; + } +#endif } } #endif @@ -5650,8 +5986,31 @@ int wolfSSL_Init(void) #ifndef WOLFSSL_MUTEX_INITIALIZER if (inits_count_mutex_valid == 0) { + #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + + /* Without this mitigation, if two threads enter wolfSSL_Init() at the + * same time, and both see zero inits_count_mutex_valid, then both will + * run wc_InitMutex(&inits_count_mutex), leading to process corruption + * or (best case) a resource leak. + * + * When WOLFSSL_ATOMIC_INITIALIZER() is available, we can mitigate this + * by use an atomic counting int as a mutex. + */ + + if (wolfSSL_Atomic_Int_FetchAdd(&inits_count_mutex_atomic_initing_flag, + 1) != 0) + { + (void)wolfSSL_Atomic_Int_FetchSub( + &inits_count_mutex_atomic_initing_flag, 1); + return DEADLOCK_AVERTED_E; + } + #endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS */ if (wc_InitMutex(&inits_count_mutex) != 0) { WOLFSSL_MSG("Bad Init Mutex count"); + #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS + (void)wolfSSL_Atomic_Int_FetchSub( + &inits_count_mutex_atomic_initing_flag, 1); + #endif return BAD_MUTEX_E; } else { @@ -5758,6 +6117,11 @@ int wolfSSL_Init(void) #endif } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + /* System wide crypto policy disabled by default. */ + XMEMSET(&crypto_policy, 0, sizeof(crypto_policy)); +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + if (ret == WOLFSSL_SUCCESS) { initRefCount++; } @@ -5774,6 +6138,286 @@ int wolfSSL_Init(void) return ret; } +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) +/* Helper function for wolfSSL_crypto_policy_enable and + * wolfSSL_crypto_policy_enable_buffer. + * + * Parses the crypto policy string, verifies values, + * and sets in global crypto policy struct. Not thread + * safe. String length has already been verified. + * + * Returns WOLFSSL_SUCCESS on success. + * Returns CRYPTO_POLICY_FORBIDDEN if already enabled. + * Returns < 0 on misc error. + * */ +static int crypto_policy_parse(void) +{ + const char * hdr = WOLFSSL_SECLEVEL_STR; + int sec_level = 0; + size_t i = 0; + + /* All policies should begin with "@SECLEVEL=" (N={0..5}) followed + * by bulk cipher list. */ + if (XMEMCMP(crypto_policy.str, hdr, strlen(hdr)) != 0) { + WOLFSSL_MSG("error: crypto policy: invalid header"); + return WOLFSSL_BAD_FILE; + } + + { + /* Extract the security level. */ + char * policy_mem = crypto_policy.str; + policy_mem += strlen(hdr); + sec_level = (int) (*policy_mem - '0'); + } + + if (sec_level < MIN_WOLFSSL_SEC_LEVEL || + sec_level > MAX_WOLFSSL_SEC_LEVEL) { + WOLFSSL_MSG_EX("error: invalid SECLEVEL: %d", sec_level); + return WOLFSSL_BAD_FILE; + } + + /* Remove trailing '\r' or '\n'. */ + for (i = 0; i < MAX_WOLFSSL_CRYPTO_POLICY_SIZE; ++i) { + if (crypto_policy.str[i] == '\0') { + break; + } + + if (crypto_policy.str[i] == '\r' || crypto_policy.str[i] == '\n') { + crypto_policy.str[i] = '\0'; + break; + } + } + + #if defined(DEBUG_WOLFSSL_VERBOSE) + WOLFSSL_MSG_EX("info: SECLEVEL=%d", sec_level); + WOLFSSL_MSG_EX("info: using crypto-policy file: %s, %ld", policy_file, sz); + #endif /* DEBUG_WOLFSSL_VERBOSE */ + + crypto_policy.secLevel = sec_level; + crypto_policy.enabled = 1; + + return WOLFSSL_SUCCESS; +} + +#ifndef NO_FILESYSTEM +/* Enables wolfSSL system wide crypto-policy, using the given policy + * file arg. If NULL is passed, then the default system crypto-policy + * file that was set at configure time will be used instead. + * + * While enabled: + * - TLS methods, min key sizes, and cipher lists are all configured + * automatically by the policy. + * - Attempting to use lesser strength parameters will fail with + * error CRYPTO_POLICY_FORBIDDEN. + * + * Disable with wolfSSL_crypto_policy_disable. + * + * Note: the wolfSSL_crypto_policy_X API are not thread safe, and should + * only be called at program init time. + * + * Returns WOLFSSL_SUCCESS on success. + * Returns CRYPTO_POLICY_FORBIDDEN if already enabled. + * Returns < 0 on misc error. + * */ +int wolfSSL_crypto_policy_enable(const char * policy_file) +{ + XFILE file; + long sz = 0; + size_t n_read = 0; + + WOLFSSL_ENTER("wolfSSL_crypto_policy_enable"); + + if (wolfSSL_crypto_policy_is_enabled()) { + WOLFSSL_MSG_EX("error: crypto policy already enabled: %s", + policy_file); + return CRYPTO_POLICY_FORBIDDEN; + } + + if (policy_file == NULL) { + /* Use the configure-time default if NULL passed. */ + policy_file = WC_STRINGIFY(WOLFSSL_CRYPTO_POLICY_FILE); + } + + if (policy_file == NULL || *policy_file == '\0') { + WOLFSSL_MSG("error: crypto policy empty file"); + return BAD_FUNC_ARG; + } + + XMEMSET(&crypto_policy, 0, sizeof(crypto_policy)); + + file = XFOPEN(policy_file, "rb"); + + if (file == XBADFILE) { + WOLFSSL_MSG_EX("error: crypto policy file open failed: %s", + policy_file); + return WOLFSSL_BAD_FILE; + } + + if (XFSEEK(file, 0, XSEEK_END) != 0) { + WOLFSSL_MSG_EX("error: crypto policy file seek end failed: %s", + policy_file); + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } + + sz = XFTELL(file); + + if (XFSEEK(file, 0, XSEEK_SET) != 0) { + WOLFSSL_MSG_EX("error: crypto policy file seek failed: %s", + policy_file); + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } + + if (sz <= 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) { + WOLFSSL_MSG_EX("error: crypto policy file %s, invalid size: %ld", + policy_file, sz); + XFCLOSE(file); + return WOLFSSL_BAD_FILE; + } + + n_read = XFREAD(crypto_policy.str, 1, sz, file); + XFCLOSE(file); + + if (n_read != (size_t) sz) { + WOLFSSL_MSG_EX("error: crypto policy file %s: read %zu, " + "expected %ld", policy_file, n_read, sz); + return WOLFSSL_BAD_FILE; + } + + crypto_policy.str[n_read] = '\0'; + + return crypto_policy_parse(); +} +#endif /* ! NO_FILESYSTEM */ + +/* Same behavior as wolfSSL_crypto_policy_enable, but loads + * via memory buf instead of file. + * + * Returns WOLFSSL_SUCCESS on success. + * Returns CRYPTO_POLICY_FORBIDDEN if already enabled. + * Returns < 0 on misc error. + * */ +int wolfSSL_crypto_policy_enable_buffer(const char * buf) +{ + size_t sz = 0; + + WOLFSSL_ENTER("wolfSSL_crypto_policy_enable_buffer"); + + if (wolfSSL_crypto_policy_is_enabled()) { + WOLFSSL_MSG_EX("error: crypto policy already enabled"); + return CRYPTO_POLICY_FORBIDDEN; + } + + if (buf == NULL || *buf == '\0') { + return BAD_FUNC_ARG; + } + + sz = XSTRLEN(buf); + + if (sz == 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) { + return BAD_FUNC_ARG; + } + + XMEMSET(&crypto_policy, 0, sizeof(crypto_policy)); + XMEMCPY(crypto_policy.str, buf, sz); + + return crypto_policy_parse(); +} + +/* Returns whether the system wide crypto-policy is enabled. + * + * Returns 1 if enabled. + * 0 if disabled. + * */ +int wolfSSL_crypto_policy_is_enabled(void) +{ + WOLFSSL_ENTER("wolfSSL_crypto_policy_is_enabled"); + + return crypto_policy.enabled == 1; +} + +/* Disables the system wide crypto-policy. + * note: SSL and CTX structures already instantiated will + * keep their security policy parameters. This will only + * affect new instantiations. + * */ +void wolfSSL_crypto_policy_disable(void) +{ + WOLFSSL_ENTER("wolfSSL_crypto_policy_disable"); + crypto_policy.enabled = 0; + XMEMSET(&crypto_policy, 0, sizeof(crypto_policy)); + return; +} + +/* Get the crypto-policy bulk cipher list string. + * String is not owned by caller, should not be freed. + * + * Returns pointer to bulk cipher list string. + * Returns NULL if NOT enabled, or on error. + * */ +const char * wolfSSL_crypto_policy_get_ciphers(void) +{ + WOLFSSL_ENTER("wolfSSL_crypto_policy_get_ciphers"); + + if (crypto_policy.enabled == 1) { + /* The crypto policy config will have + * this form: + * "@SECLEVEL=2:kEECDH:kRSA..." */ + return crypto_policy.str; + } + + return NULL; +} + +/* Get the configured crypto-policy security level. + * A security level of 0 does not impose any additional + * restrictions. + * + * Returns 1 - 5 if enabled. + * Returns 0 if NOT enabled. + * */ +int wolfSSL_crypto_policy_get_level(void) +{ + if (crypto_policy.enabled == 1) { + return crypto_policy.secLevel; + } + + return 0; +} + +/* Get security level from ssl structure. + * @param ssl a pointer to WOLFSSL structure + */ +int wolfSSL_get_security_level(const WOLFSSL * ssl) +{ + if (ssl == NULL) { + return BAD_FUNC_ARG; + } + + return ssl->secLevel; +} + +#ifndef NO_WOLFSSL_STUB +/* + * Set security level (wolfSSL doesn't support setting the security level). + * + * The security level can only be set through a system wide crypto-policy + * with wolfSSL_crypto_policy_enable(). + * + * @param ssl a pointer to WOLFSSL structure + * @param level security level + */ +void wolfSSL_set_security_level(WOLFSSL * ssl, int level) +{ + WOLFSSL_ENTER("wolfSSL_set_security_level"); + (void)ssl; + (void)level; +} +#endif /* !NO_WOLFSSL_STUB */ + +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + #define WOLFSSL_SSL_LOAD_INCLUDED #include @@ -6511,17 +7155,17 @@ WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx) switch (ctx->privateKeyType) { #ifndef NO_RSA case rsa_sa_algo: - type = EVP_PKEY_RSA; + type = WC_EVP_PKEY_RSA; break; #endif #ifdef HAVE_ECC case ecc_dsa_sa_algo: - type = EVP_PKEY_EC; + type = WC_EVP_PKEY_EC; break; #endif #ifdef WOLFSSL_SM2 case sm2_sa_algo: - type = EVP_PKEY_EC; + type = WC_EVP_PKEY_EC; break; #endif default: @@ -6616,7 +7260,7 @@ static int d2iTryRsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } if (ret == 1) { XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_RSA; + pkey->type = WC_EVP_PKEY_RSA; pkey->ownRsa = 1; pkey->rsa = wolfssl_rsa_d2i(NULL, mem, memSz, @@ -6700,7 +7344,7 @@ static int d2iTryEccKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } if (ret == 1) { XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_EC; + pkey->type = WC_EVP_PKEY_EC; pkey->ownEcc = 1; pkey->ecc = wolfSSL_EC_KEY_new(); @@ -6788,7 +7432,7 @@ static int d2iTryDsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } if (ret == 1) { XMEMCPY(pkey->pkey.ptr, mem, keyIdx); - pkey->type = EVP_PKEY_DSA; + pkey->type = WC_EVP_PKEY_DSA; pkey->ownDsa = 1; pkey->dsa = wolfSSL_DSA_new(); @@ -6872,7 +7516,7 @@ static int d2iTryDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } if (ret == 1) { XMEMCPY(pkey->pkey.ptr, mem, memSz); - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; pkey->ownDh = 1; pkey->dh = wolfSSL_DH_new(); @@ -6947,7 +7591,7 @@ static int d2iTryAltDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } ret = 1; - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; pkey->pkey_sz = (int)memSz; pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, priv ? DYNAMIC_TYPE_PRIVATE_KEY : @@ -7063,7 +7707,7 @@ static int d2iTryFalconKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, return 0; } } - pkey->type = EVP_PKEY_FALCON; + pkey->type = WC_EVP_PKEY_FALCON; pkey->pkey.ptr = NULL; pkey->pkey_sz = 0; @@ -7148,7 +7792,7 @@ static int d2iTryDilithiumKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, return 0; } } - pkey->type = EVP_PKEY_DILITHIUM; + pkey->type = WC_EVP_PKEY_DILITHIUM; pkey->pkey.ptr = NULL; pkey->pkey_sz = 0; @@ -7542,14 +8186,14 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, WOLFSSL_MSG("Found PKCS8 header"); pkcs8HeaderSz = (word16)idx; - if ((type == EVP_PKEY_RSA && algId != RSAk + if ((type == WC_EVP_PKEY_RSA && algId != RSAk #ifdef WC_RSA_PSS && algId != RSAPSSk #endif ) || - (type == EVP_PKEY_EC && algId != ECDSAk) || - (type == EVP_PKEY_DSA && algId != DSAk) || - (type == EVP_PKEY_DH && algId != DHk)) { + (type == WC_EVP_PKEY_EC && algId != ECDSAk) || + (type == WC_EVP_PKEY_DSA && algId != DSAk) || + (type == WC_EVP_PKEY_DH && algId != DHk)) { WOLFSSL_MSG("PKCS8 does not match EVP key type"); return NULL; } @@ -7589,7 +8233,7 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, switch (type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: opt = priv ? WOLFSSL_RSA_LOAD_PRIVATE : WOLFSSL_RSA_LOAD_PUBLIC; local->ownRsa = 1; local->rsa = wolfssl_rsa_d2i(NULL, @@ -7601,7 +8245,7 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, break; #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: local->ownEcc = 1; local->ecc = wolfSSL_EC_KEY_new(); if (local->ecc == NULL) { @@ -7621,7 +8265,7 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, #endif /* HAVE_ECC */ #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: local->ownDsa = 1; local->dsa = wolfSSL_DSA_new(); if (local->dsa == NULL) { @@ -7640,7 +8284,7 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, #endif /* NO_DSA */ #ifndef NO_DH #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: local->ownDh = 1; local->dh = wolfSSL_DH_new(); if (local->dh == NULL) { @@ -7725,7 +8369,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out, switch (type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: { RsaKey* key; local->ownRsa = 1; @@ -7744,7 +8388,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_id(int type, WOLFSSL_EVP_PKEY** out, } #endif /* !NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: { ecc_key* key; local->ownEcc = 1; @@ -9116,7 +9760,13 @@ int wolfSSL_dtls_retransmit(WOLFSSL* ssl) return WOLFSSL_FATAL_ERROR; if (!ssl->options.handShakeDone) { - int result = DtlsMsgPoolSend(ssl, 0); + int result; +#ifdef WOLFSSL_DTLS13 + if (IsAtLeastTLSv1_3(ssl->version)) + result = Dtls13DoScheduledWork(ssl); + else +#endif + result = DtlsMsgPoolSend(ssl, 0); if (result < 0) { ssl->error = result; WOLFSSL_ERROR(result); @@ -9124,7 +9774,7 @@ int wolfSSL_dtls_retransmit(WOLFSSL* ssl) } } - return 0; + return WOLFSSL_SUCCESS; } #endif /* DTLS */ @@ -9198,7 +9848,7 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, /* EITHER SIDE METHODS */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) +#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)) WOLFSSL_METHOD* wolfSSLv23_method(void) { return wolfSSLv23_method_ex(NULL); @@ -9244,10 +9894,10 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, } #endif #endif -#endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ +#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */ /* client only parts */ -#ifndef NO_WOLFSSL_CLIENT +#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) WOLFSSL_METHOD* wolfSSLv2_client_method(void) @@ -9341,8 +9991,8 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { - ssl->CBIS(ssl, SSL_ST_CONNECT, WOLFSSL_SUCCESS); - ssl->cbmode = SSL_CB_WRITE; + ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS); + ssl->cbmode = WOLFSSL_CB_WRITE; } #endif #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ @@ -9747,11 +10397,11 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */ } -#endif /* NO_WOLFSSL_CLIENT */ - +#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */ +/* end client only parts */ /* server only parts */ -#ifndef NO_WOLFSSL_SERVER +#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS) #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS) WOLFSSL_METHOD* wolfSSLv2_server_method(void) @@ -10288,9 +10938,81 @@ int wolfSSL_DTLS_SetCookieSecret(WOLFSSL* ssl, #endif /* !WOLFSSL_NO_TLS12 */ } -#endif /* NO_WOLFSSL_SERVER */ +#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */ +/* end server only parts */ + #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) +struct chGoodDisableReadCbCtx { + ClientHelloGoodCb userCb; + void* userCtx; +}; + +static int chGoodDisableReadCB(WOLFSSL* ssl, void* ctx) +{ + struct chGoodDisableReadCbCtx* cb = (struct chGoodDisableReadCbCtx*)ctx; + int ret = 0; + if (cb->userCb != NULL) + ret = cb->userCb(ssl, cb->userCtx); + if (ret >= 0) + wolfSSL_SSLDisableRead(ssl); + return ret; +} + +/** + * Statelessly listen for a connection + * @param ssl The ssl object to use for listening to connections + * @return WOLFSSL_SUCCESS - ClientHello containing a valid cookie was received + * The connection can be continued with wolfSSL_accept + * WOLFSSL_FAILURE - The I/O layer returned WANT_READ. This is either + * because there is no data to read and we are using + * non-blocking sockets or we sent a cookie request + * and we are waiting for a reply. The user should + * call wolfDTLS_accept_stateless again after data + * becomes available in the I/O layer. + * WOLFSSL_FATAL_ERROR - A fatal error occurred. The ssl object should + * be free'd and allocated again to continue. + */ +int wolfDTLS_accept_stateless(WOLFSSL* ssl) +{ + byte disableRead; + int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); + struct chGoodDisableReadCbCtx cb; + + WOLFSSL_ENTER("wolfDTLS_SetChGoodCb"); + + if (ssl == NULL) + return WOLFSSL_FATAL_ERROR; + + /* Save this to restore it later */ + disableRead = (byte)ssl->options.disableRead; + cb.userCb = ssl->chGoodCb; + cb.userCtx = ssl->chGoodCtx; + + /* Register our own callback so that we can disable reading */ + if (wolfDTLS_SetChGoodCb(ssl, chGoodDisableReadCB, &cb) != WOLFSSL_SUCCESS) + return WOLFSSL_FATAL_ERROR; + + ret = wolfSSL_accept(ssl); + /* restore user options */ + ssl->options.disableRead = disableRead; + (void)wolfDTLS_SetChGoodCb(ssl, cb.userCb, cb.userCtx); + if (ret == WOLFSSL_SUCCESS) { + WOLFSSL_MSG("should not happen. maybe the user called " + "wolfDTLS_accept_stateless instead of wolfSSL_accept"); + } + else if (ssl->error == WC_NO_ERR_TRACE(WANT_READ)) { + if (ssl->options.dtlsStateful) + ret = WOLFSSL_SUCCESS; + else + ret = WOLFSSL_FAILURE; + } + else { + ret = WOLFSSL_FATAL_ERROR; + } + return ret; +} + int wolfDTLS_SetChGoodCb(WOLFSSL* ssl, ClientHelloGoodCb cb, void* user_ctx) { WOLFSSL_ENTER("wolfDTLS_SetChGoodCb"); @@ -10362,6 +11084,10 @@ int wolfSSL_Cleanup(void) if (!release) return ret; +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + wolfSSL_crypto_policy_disable(); +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + #ifdef OPENSSL_EXTRA wolfSSL_BN_free_one(); #endif @@ -10409,7 +11135,8 @@ int wolfSSL_Cleanup(void) #endif #endif /* !NO_SESSION_CACHE */ -#ifndef WOLFSSL_MUTEX_INITIALIZER +#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \ + !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS if ((inits_count_mutex_valid == 1) && (wc_FreeMutex(&inits_count_mutex) != 0)) { if (ret == WOLFSSL_SUCCESS) @@ -10450,11 +11177,7 @@ int wolfSSL_Cleanup(void) #endif #endif -#if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ - defined(WOLFSSL_WPAS_SMALL) +#ifdef HAVE_EX_DATA_CRYPTO crypto_ex_cb_free(crypto_ex_cb_ctx_session); crypto_ex_cb_ctx_session = NULL; #endif @@ -10535,7 +11258,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #ifndef USE_WINDOWS_API - #ifndef NO_WRITEV + #if !defined(NO_WRITEV) && !defined(NO_TLS) /* simulate writev semantics, doesn't actually do block at a time though because of SSL_write behavior and because front adds may be small */ @@ -10810,8 +11533,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); } #ifdef OPENSSL_EXTRA /** @@ -10867,8 +11589,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); } const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl) @@ -11031,18 +11752,30 @@ int wolfSSL_set_compression(WOLFSSL* ssl) int wolfSSL_CTX_UnloadIntermediateCerts(WOLFSSL_CTX* ctx) { + int ret; + WOLFSSL_ENTER("wolfSSL_CTX_UnloadIntermediateCerts"); if (ctx == NULL) return BAD_FUNC_ARG; + ret = wolfSSL_RefWithMutexLock(&ctx->ref); + if (ret < 0) + return ret; + if (ctx->ref.count > 1) { WOLFSSL_MSG("ctx object must have a ref count of 1 before " "unloading intermediate certs"); - return BAD_STATE_E; + ret = BAD_STATE_E; + } + else { + ret = wolfSSL_CertManagerUnloadIntermediateCerts(ctx->cm); } - return wolfSSL_CertManagerUnloadIntermediateCerts(ctx->cm); + if (wolfSSL_RefWithMutexUnlock(&ctx->ref) != 0) + WOLFSSL_MSG("Failed to unlock mutex!"); + + return ret; } @@ -11190,11 +11923,11 @@ int wolfSSL_set_compression(WOLFSSL* ssl) /* User programs should always retry reading from these BIOs */ if (rd) { /* User writes to rd */ - BIO_set_retry_write(rd); + wolfSSL_BIO_set_retry_write(rd); } if (wr) { /* User reads from wr */ - BIO_set_retry_read(wr); + wolfSSL_BIO_set_retry_read(wr); } } @@ -11289,6 +12022,8 @@ int wolfSSL_set_compression(WOLFSSL* ssl) } return WOLFSSL_FAILURE; } + +#ifndef NO_TLS WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first, byte second) { @@ -11304,6 +12039,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK); return info; } +#endif /** * @param first First byte of the hash and signature algorithm @@ -12587,6 +13323,7 @@ int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version) if (ctx == NULL) { return WOLFSSL_FAILURE; } + if (version != 0) { proto = version; ctx->minProto = 0; /* turn min proto flag off */ @@ -13139,7 +13876,11 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, unsigned long wolfSSLeay(void) { +#ifdef SSLEAY_VERSION_NUMBER return SSLEAY_VERSION_NUMBER; +#else + return OPENSSL_VERSION_NUMBER; +#endif } unsigned long wolfSSL_OpenSSL_version_num(void) @@ -13296,7 +14037,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_ENTER("wolfSSL_CTX_set_mode"); switch(mode) { - case SSL_MODE_ENABLE_PARTIAL_WRITE: + case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE: ctx->partialWrite = 1; break; #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) @@ -13304,14 +14045,14 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); break; #endif - case SSL_MODE_AUTO_RETRY: + case WOLFSSL_MODE_AUTO_RETRY: ctx->autoRetry = 1; break; default: WOLFSSL_MSG("Mode Not Implemented"); } - /* SSL_MODE_AUTO_RETRY + /* WOLFSSL_MODE_AUTO_RETRY * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */ return mode; @@ -13323,7 +14064,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_ENTER("wolfSSL_CTX_clear_mode"); switch(mode) { - case SSL_MODE_ENABLE_PARTIAL_WRITE: + case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE: ctx->partialWrite = 0; break; #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) @@ -13331,14 +14072,14 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented."); break; #endif - case SSL_MODE_AUTO_RETRY: + case WOLFSSL_MODE_AUTO_RETRY: ctx->autoRetry = 0; break; default: WOLFSSL_MSG("Mode Not Implemented"); } - /* SSL_MODE_AUTO_RETRY + /* WOLFSSL_MODE_AUTO_RETRY * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */ return 0; @@ -13484,7 +14225,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, * * file output pointer to file where error happened * line output to line number of error - * data output data. Is a string if ERR_TXT_STRING flag is used + * data output data. Is a string if WOLFSSL_ERR_TXT_STRING flag is used * flags output format of output * * Returns the error value or 0 if no errors are in the queue @@ -13498,7 +14239,7 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, WOLFSSL_ENTER("wolfSSL_ERR_get_error_line_data"); if (flags != NULL) - *flags = ERR_TXT_STRING; /* Clear the flags */ + *flags = WOLFSSL_ERR_TXT_STRING; /* Clear the flags */ ret = wc_PullErrorNode(file, data, line); if (ret < 0) { @@ -14540,6 +15281,42 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) * check to override this result in the case of a hybrid. */ if (IsAtLeastTLSv1_3(ssl->version)) { switch (ssl->namedGroup) { +#ifndef WOLFSSL_NO_ML_KEM +#ifdef HAVE_LIBOQS + case WOLFSSL_ML_KEM_512: + return "ML_KEM_512"; + case WOLFSSL_ML_KEM_768: + return "ML_KEM_768"; + case WOLFSSL_ML_KEM_1024: + return "ML_KEM_1024"; + case WOLFSSL_P256_ML_KEM_512: + return "P256_ML_KEM_512"; + case WOLFSSL_P384_ML_KEM_768: + return "P384_ML_KEM_768"; + case WOLFSSL_P521_ML_KEM_1024: + return "P521_ML_KEM_1024"; +#elif defined(WOLFSSL_WC_KYBER) + #ifndef WOLFSSL_NO_ML_KEM_512 + case WOLFSSL_ML_KEM_512: + return "ML_KEM_512"; + case WOLFSSL_P256_ML_KEM_512: + return "P256_ML_KEM_512"; + #endif + #ifndef WOLFSSL_NO_ML_KEM_768 + case WOLFSSL_ML_KEM_768: + return "ML_KEM_768"; + case WOLFSSL_P384_ML_KEM_768: + return "P384_ML_KEM_768"; + #endif + #ifndef WOLFSSL_NO_ML_KEM_1024 + case WOLFSSL_ML_KEM_1024: + return "ML_KEM_1024"; + case WOLFSSL_P521_ML_KEM_1024: + return "P521_ML_KEM_1024"; + #endif +#endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef HAVE_LIBOQS case WOLFSSL_KYBER_LEVEL1: return "KYBER_LEVEL1"; @@ -14554,24 +15331,25 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) case WOLFSSL_P521_KYBER_LEVEL5: return "P521_KYBER_LEVEL5"; #elif defined(WOLFSSL_WC_KYBER) - #ifdef WOLFSSL_KYBER512 + #ifndef WOLFSSL_NO_KYBER512 case WOLFSSL_KYBER_LEVEL1: return "KYBER_LEVEL1"; case WOLFSSL_P256_KYBER_LEVEL1: return "P256_KYBER_LEVEL1"; #endif - #ifdef WOLFSSL_KYBER768 + #ifndef WOLFSSL_NO_KYBER768 case WOLFSSL_KYBER_LEVEL3: return "KYBER_LEVEL3"; case WOLFSSL_P384_KYBER_LEVEL3: return "P384_KYBER_LEVEL3"; #endif - #ifdef WOLFSSL_KYBER1024 + #ifndef WOLFSSL_NO_KYBER1024 case WOLFSSL_KYBER_LEVEL5: return "KYBER_LEVEL5"; case WOLFSSL_P521_KYBER_LEVEL5: return "P521_KYBER_LEVEL5"; #endif +#endif #endif } } @@ -14610,7 +15388,7 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) /* return authentication NID corresponding to cipher suite * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found + * return NID if found, WC_NID_undef if not found */ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) { @@ -14618,12 +15396,12 @@ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) const char* alg_name; const int nid; } authnid_tbl[] = { - {"RSA", NID_auth_rsa}, - {"PSK", NID_auth_psk}, - {"SRP", NID_auth_srp}, - {"ECDSA", NID_auth_ecdsa}, - {"None", NID_auth_null}, - {NULL, NID_undef} + {"RSA", WC_NID_auth_rsa}, + {"PSK", WC_NID_auth_psk}, + {"SRP", WC_NID_auth_srp}, + {"ECDSA", WC_NID_auth_ecdsa}, + {"None", WC_NID_auth_null}, + {NULL, WC_NID_undef} }; const char* authStr; @@ -14631,7 +15409,7 @@ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) if (GetCipherSegment(cipher, n) == NULL) { WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; + return WC_NID_undef; } authStr = GetCipherAuthStr(n); @@ -14645,11 +15423,11 @@ int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher) } } - return NID_undef; + return WC_NID_undef; } /* return cipher NID corresponding to cipher suite * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found + * return NID if found, WC_NID_undef if not found */ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) { @@ -14657,18 +15435,18 @@ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) const char* alg_name; const int nid; } ciphernid_tbl[] = { - {"AESGCM(256)", NID_aes_256_gcm}, - {"AESGCM(128)", NID_aes_128_gcm}, - {"AESCCM(128)", NID_aes_128_ccm}, - {"AES(128)", NID_aes_128_cbc}, - {"AES(256)", NID_aes_256_cbc}, - {"CAMELLIA(256)", NID_camellia_256_cbc}, - {"CAMELLIA(128)", NID_camellia_128_cbc}, - {"RC4", NID_rc4}, - {"3DES", NID_des_ede3_cbc}, - {"CHACHA20/POLY1305(256)", NID_chacha20_poly1305}, - {"None", NID_undef}, - {NULL, NID_undef} + {"AESGCM(256)", WC_NID_aes_256_gcm}, + {"AESGCM(128)", WC_NID_aes_128_gcm}, + {"AESCCM(128)", WC_NID_aes_128_ccm}, + {"AES(128)", WC_NID_aes_128_cbc}, + {"AES(256)", WC_NID_aes_256_cbc}, + {"CAMELLIA(256)", WC_NID_camellia_256_cbc}, + {"CAMELLIA(128)", WC_NID_camellia_128_cbc}, + {"RC4", WC_NID_rc4}, + {"3DES", WC_NID_des_ede3_cbc}, + {"CHACHA20/POLY1305(256)", WC_NID_chacha20_poly1305}, + {"None", WC_NID_undef}, + {NULL, WC_NID_undef} }; const char* encStr; @@ -14678,7 +15456,7 @@ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) if (GetCipherSegment(cipher, n) == NULL) { WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; + return WC_NID_undef; } encStr = GetCipherEncStr(n); @@ -14692,11 +15470,11 @@ int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher) } } - return NID_undef; + return WC_NID_undef; } /* return digest NID corresponding to cipher suite * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found + * return NID if found, WC_NID_undef if not found */ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) { @@ -14704,10 +15482,10 @@ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) const char* alg_name; const int nid; } macnid_tbl[] = { - {"SHA1", NID_sha1}, - {"SHA256", NID_sha256}, - {"SHA384", NID_sha384}, - {NULL, NID_undef} + {"SHA1", WC_NID_sha1}, + {"SHA256", WC_NID_sha256}, + {"SHA384", WC_NID_sha384}, + {NULL, WC_NID_undef} }; const char* name; @@ -14719,12 +15497,12 @@ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) if ((name = GetCipherSegment(cipher, n)) == NULL) { WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; + return WC_NID_undef; } - /* in MD5 case, NID will be NID_md5 */ + /* in MD5 case, NID will be WC_NID_md5 */ if (XSTRSTR(name, "MD5") != NULL) { - return NID_md5; + return WC_NID_md5; } macStr = GetCipherMacStr(n); @@ -14738,11 +15516,11 @@ int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher) } } - return NID_undef; + return WC_NID_undef; } /* return key exchange NID corresponding to cipher suite * @param cipher a pointer to WOLFSSL_CIPHER - * return NID if found, NID_undef if not found + * return NID if found, WC_NID_undef if not found */ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) { @@ -14750,15 +15528,15 @@ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) const char* name; const int nid; } kxnid_table[] = { - {"ECDHEPSK", NID_kx_ecdhe_psk}, - {"ECDH", NID_kx_ecdhe}, - {"DHEPSK", NID_kx_dhe_psk}, - {"DH", NID_kx_dhe}, - {"RSAPSK", NID_kx_rsa_psk}, - {"SRP", NID_kx_srp}, - {"EDH", NID_kx_dhe}, - {"RSA", NID_kx_rsa}, - {NULL, NID_undef} + {"ECDHEPSK", WC_NID_kx_ecdhe_psk}, + {"ECDH", WC_NID_kx_ecdhe}, + {"DHEPSK", WC_NID_kx_dhe_psk}, + {"DH", WC_NID_kx_dhe}, + {"RSAPSK", WC_NID_kx_rsa_psk}, + {"SRP", WC_NID_kx_srp}, + {"EDH", WC_NID_kx_dhe}, + {"RSA", WC_NID_kx_rsa}, + {NULL, WC_NID_undef} }; const char* keaStr; @@ -14768,12 +15546,12 @@ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) if (GetCipherSegment(cipher, n) == NULL) { WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; + return WC_NID_undef; } - /* in TLS 1.3 case, NID will be NID_kx_any */ + /* in TLS 1.3 case, NID will be WC_NID_kx_any */ if (XSTRCMP(n[0], "TLS13") == 0) { - return NID_kx_any; + return WC_NID_kx_any; } keaStr = GetCipherKeaStr(n); @@ -14787,7 +15565,7 @@ int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher) } } - return NID_undef; + return WC_NID_undef; } /* check if cipher suite is AEAD * @param cipher a pointer to WOLFSSL_CIPHER @@ -14801,7 +15579,7 @@ int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher) if (GetCipherSegment(cipher, n) == NULL) { WOLFSSL_MSG("no suitable cipher name found"); - return NID_undef; + return WC_NID_undef; } return IsCipherAEAD(n); @@ -15386,12 +16164,12 @@ int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) } key_type = key->type; - if ((key_type != EVP_PKEY_EC) && (key_type != EVP_PKEY_RSA)) { + if ((key_type != WC_EVP_PKEY_EC) && (key_type != WC_EVP_PKEY_RSA)) { return WOLFSSL_FATAL_ERROR; } #ifndef NO_RSA - if (key_type == EVP_PKEY_RSA) { + if (key_type == WC_EVP_PKEY_RSA) { return wolfSSL_i2d_RSAPublicKey(key->rsa, der); } #endif @@ -15613,32 +16391,40 @@ unsigned long wolfSSL_ERR_peek_error(void) return wolfSSL_ERR_peek_error_line_data(NULL, NULL, NULL, NULL); } +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H +#include +#endif + int wolfSSL_ERR_GET_LIB(unsigned long err) { unsigned long value; value = (err & 0xFFFFFFL); switch (value) { - case -WC_NO_ERR_TRACE(PARSE_ERROR): - return ERR_LIB_SSL; - case -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER): - case PEM_R_NO_START_LINE: - case PEM_R_PROBLEMS_GETTING_PASSWORD: - case PEM_R_BAD_PASSWORD_READ: - case PEM_R_BAD_DECRYPT: - return ERR_LIB_PEM; - case EVP_R_BAD_DECRYPT: - case EVP_R_BN_DECODE_ERROR: - case EVP_R_DECODE_ERROR: - case EVP_R_PRIVATE_KEY_DECODE_ERROR: - return ERR_LIB_EVP; - case ASN1_R_HEADER_TOO_LONG: - return ERR_LIB_ASN1; + case -PARSE_ERROR: + return WOLFSSL_ERR_LIB_SSL; + case -ASN_NO_PEM_HEADER: + case -WOLFSSL_PEM_R_NO_START_LINE_E: + case -WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E: + case -WOLFSSL_PEM_R_BAD_PASSWORD_READ_E: + case -WOLFSSL_PEM_R_BAD_DECRYPT_E: + return WOLFSSL_ERR_LIB_PEM; + case -WOLFSSL_EVP_R_BAD_DECRYPT_E: + case -WOLFSSL_EVP_R_BN_DECODE_ERROR: + case -WOLFSSL_EVP_R_DECODE_ERROR: + case -WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR: + return WOLFSSL_ERR_LIB_EVP; + case -WOLFSSL_ASN1_R_HEADER_TOO_LONG_E: + return WOLFSSL_ERR_LIB_ASN1; default: return 0; } } +#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES +#include +#endif + /* This function is to find global error values that are the same through out * all library version. With wolfSSL having only one set of error codes the * return value is pretty straight forward. The only thing needed is all wolfSSL @@ -15667,11 +16453,11 @@ int wolfSSL_ERR_GET_REASON(unsigned long err) return ASN1_R_HEADER_TOO_LONG; #endif - /* check if error value is in range of wolfSSL errors */ + /* check if error value is in range of wolfCrypt or wolfSSL errors */ ret = 0 - ret; /* setting as negative value */ - /* wolfCrypt range is less than MAX (-100) - wolfSSL range is MIN (-300) and lower */ - if ((ret <= WC_FIRST_E && ret >= WC_LAST_E) || + + if ((ret <= WC_SPAN1_FIRST_E && ret >= WC_SPAN1_LAST_E) || + (ret <= WC_SPAN2_FIRST_E && ret >= WC_SPAN2_LAST_E) || (ret <= WOLFSSL_FIRST_E && ret >= WOLFSSL_LAST_E)) { return ret; @@ -15684,6 +16470,7 @@ int wolfSSL_ERR_GET_REASON(unsigned long err) return ret; } +#ifndef NO_TLS /* returns a string that describes the alert * * alertID the alert value to look up @@ -15695,13 +16482,13 @@ const char* wolfSSL_alert_type_string_long(int alertID) return AlertTypeToString(alertID); } - const char* wolfSSL_alert_desc_string_long(int alertID) { WOLFSSL_ENTER("wolfSSL_alert_desc_string_long"); return AlertTypeToString(alertID); } +#endif /* !NO_TLS */ #define STATE_STRINGS_PROTO(s) \ { \ @@ -15850,10 +16637,10 @@ const char* wolfSSL_state_string_long(const WOLFSSL* ssl) } /* Get state of callback */ - if (ssl->cbmode == SSL_CB_MODE_WRITE) { + if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) { cbmode = SS_WRITE; } - else if (ssl->cbmode == SSL_CB_MODE_READ) { + else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) { cbmode = SS_READ; } else { @@ -15903,7 +16690,7 @@ const char* wolfSSL_state_string_long(const WOLFSSL* ssl) } /* accept process */ - if (ssl->cbmode == SSL_CB_MODE_READ) { + if (ssl->cbmode == WOLFSSL_CB_MODE_READ) { state = ssl->cbtype; switch (state) { case hello_request: @@ -16204,9 +16991,8 @@ long wolfSSL_set_options(WOLFSSL* ssl, long op) InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, - TRUE, ssl->options.side); + ssl->options.useAnon, + TRUE, TRUE, TRUE, TRUE, ssl->options.side); } else { /* Only preserve overlapping suites */ @@ -16227,7 +17013,7 @@ long wolfSSL_set_options(WOLFSSL* ssl, long op) * - haveStaticECC turns off haveRSA * - haveECDSAsig turns off haveRSAsig */ InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1, - haveStaticECC, 1, 1, 1, 1, ssl->options.side); + haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side); for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) { if (FindSuite(&tmpSuites, ssl->suites->suites[in], ssl->suites->suites[in+1]) >= 0) { @@ -16351,7 +17137,7 @@ long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type) return BAD_FUNC_ARG; } - if (type == TLSEXT_STATUSTYPE_ocsp){ + if (type == WOLFSSL_TLSEXT_STATUSTYPE_ocsp){ int r = TLSX_UseCertificateStatusRequest(&s->extensions, (byte)type, 0, s, s->heap, s->devId); return (long)r; @@ -16370,7 +17156,7 @@ long wolfSSL_get_tlsext_status_type(WOLFSSL *s) if (s == NULL) return WOLFSSL_FATAL_ERROR; extension = TLSX_Find(s->extensions, TLSX_STATUS_REQUEST); - return extension != NULL ? TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR; + return extension != NULL ? WOLFSSL_TLSEXT_STATUSTYPE_ocsp : WOLFSSL_FATAL_ERROR; } #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */ @@ -16429,20 +17215,20 @@ WOLFSSL_EVP_PKEY *wolfSSL_get_privatekey(const WOLFSSL *ssl) #ifndef NO_WOLFSSL_STUB /*** TBD ***/ -void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, +void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)) { (void)ctx; (void)dh; - WOLFSSL_STUB("SSL_CTX_set_tmp_dh_callback"); + WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback"); } #endif #ifndef NO_WOLFSSL_STUB /*** TBD ***/ -WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) +WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void) { - WOLFSSL_STUB("SSL_COMP_get_compression_methods"); + WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods"); return NULL; } #endif @@ -16464,7 +17250,7 @@ WOLFSSL_CIPHER* wolfSSL_sk_SSL_CIPHER_value(WOLFSSL_STACK* sk, int i) } #if !defined(NETOS) -void ERR_load_SSL_strings(void) +void wolfSSL_ERR_load_SSL_strings(void) { } @@ -16494,7 +17280,7 @@ long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char *resp, #endif /* HAVE_OCSP */ #ifdef HAVE_MAX_FRAGMENT -#ifndef NO_WOLFSSL_CLIENT +#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) /** * Set max fragment tls extension * @param c a pointer to WOLFSSL_CTX object @@ -16522,7 +17308,7 @@ int wolfSSL_set_tlsext_max_fragment_length(WOLFSSL *s, unsigned char mode) return wolfSSL_UseMaxFragment(s, mode); } -#endif /* NO_WOLFSSL_CLIENT */ +#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */ #endif /* HAVE_MAX_FRAGMENT */ #endif /* OPENSSL_EXTRA */ @@ -17287,48 +18073,49 @@ int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) } #endif #endif /* OPENSSL_EXTRA */ + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #ifndef NO_CERTS /* oidCertExtType */ - { NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints", + { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints", "X509v3 Basic Constraints"}, - { NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName", + { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName", "X509v3 Subject Alternative Name"}, - { NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, + { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, "crlDistributionPoints", "X509v3 CRL Distribution Points"}, - { NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess", + { WC_NID_info_access, AUTH_INFO_OID, oidCertExtType, "authorityInfoAccess", "Authority Information Access"}, - { NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType, + { WC_NID_authority_key_identifier, AUTH_KEY_OID, oidCertExtType, "authorityKeyIdentifier", "X509v3 Authority Key Identifier"}, - { NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType, + { WC_NID_subject_key_identifier, SUBJ_KEY_OID, oidCertExtType, "subjectKeyIdentifier", "X509v3 Subject Key Identifier"}, - { NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage", + { WC_NID_key_usage, KEY_USAGE_OID, oidCertExtType, "keyUsage", "X509v3 Key Usage"}, - { NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType, + { WC_NID_inhibit_any_policy, INHIBIT_ANY_OID, oidCertExtType, "inhibitAnyPolicy", "X509v3 Inhibit Any Policy"}, - { NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType, + { WC_NID_ext_key_usage, EXT_KEY_USAGE_OID, oidCertExtType, "extendedKeyUsage", "X509v3 Extended Key Usage"}, - { NID_name_constraints, NAME_CONS_OID, oidCertExtType, + { WC_NID_name_constraints, NAME_CONS_OID, oidCertExtType, "nameConstraints", "X509v3 Name Constraints"}, - { NID_certificate_policies, CERT_POLICY_OID, oidCertExtType, + { WC_NID_certificate_policies, CERT_POLICY_OID, oidCertExtType, "certificatePolicies", "X509v3 Certificate Policies"}, /* oidCertAuthInfoType */ - { NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP", + { WC_NID_ad_OCSP, AIA_OCSP_OID, oidCertAuthInfoType, "OCSP", "OCSP"}, - { NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType, + { WC_NID_ad_ca_issuers, AIA_CA_ISSUER_OID, oidCertAuthInfoType, "caIssuers", "CA Issuers"}, /* oidCertPolicyType */ - { NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy", + { WC_NID_any_policy, CP_ANY_OID, oidCertPolicyType, "anyPolicy", "X509v3 Any Policy"}, /* oidCertAltNameType */ - { NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""}, + { WC_NID_hw_name_oid, HW_NAME_OID, oidCertAltNameType, "Hardware name",""}, /* oidCertKeyUseType */ - { NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType, + { WC_NID_anyExtendedKeyUsage, EKU_ANY_OID, oidCertKeyUseType, "anyExtendedKeyUsage", "Any Extended Key Usage"}, { EKU_SERVER_AUTH_OID, EKU_SERVER_AUTH_OID, oidCertKeyUseType, "serverAuth", "TLS Web Server Authentication"}, @@ -17338,192 +18125,194 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { "OCSPSigning", "OCSP Signing"}, /* oidCertNameType */ - { NID_commonName, NID_commonName, oidCertNameType, "CN", "commonName"}, + { WC_NID_commonName, WC_NID_commonName, oidCertNameType, "CN", "commonName"}, #if !defined(WOLFSSL_CERT_REQ) - { NID_surname, NID_surname, oidCertNameType, "SN", "surname"}, + { WC_NID_surname, WC_NID_surname, oidCertNameType, "SN", "surname"}, #endif - { NID_serialNumber, NID_serialNumber, oidCertNameType, "serialNumber", + { WC_NID_serialNumber, WC_NID_serialNumber, oidCertNameType, "serialNumber", "serialNumber"}, - { NID_userId, NID_userId, oidCertNameType, "UID", "userid"}, - { NID_countryName, NID_countryName, oidCertNameType, "C", "countryName"}, - { NID_localityName, NID_localityName, oidCertNameType, "L", "localityName"}, - { NID_stateOrProvinceName, NID_stateOrProvinceName, oidCertNameType, "ST", + { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"}, + { WC_NID_countryName, WC_NID_countryName, oidCertNameType, "C", "countryName"}, + { WC_NID_localityName, WC_NID_localityName, oidCertNameType, "L", "localityName"}, + { WC_NID_stateOrProvinceName, WC_NID_stateOrProvinceName, oidCertNameType, "ST", "stateOrProvinceName"}, - { NID_streetAddress, NID_streetAddress, oidCertNameType, "street", + { WC_NID_streetAddress, WC_NID_streetAddress, oidCertNameType, "street", "streetAddress"}, - { NID_organizationName, NID_organizationName, oidCertNameType, "O", + { WC_NID_organizationName, WC_NID_organizationName, oidCertNameType, "O", "organizationName"}, - { NID_organizationalUnitName, NID_organizationalUnitName, oidCertNameType, + { WC_NID_organizationalUnitName, WC_NID_organizationalUnitName, oidCertNameType, "OU", "organizationalUnitName"}, - { NID_emailAddress, NID_emailAddress, oidCertNameType, "emailAddress", + { WC_NID_emailAddress, WC_NID_emailAddress, oidCertNameType, "emailAddress", "emailAddress"}, - { NID_domainComponent, NID_domainComponent, oidCertNameType, "DC", + { WC_NID_domainComponent, WC_NID_domainComponent, oidCertNameType, "DC", "domainComponent"}, - { NID_favouriteDrink, NID_favouriteDrink, oidCertNameType, "favouriteDrink", + { WC_NID_rfc822Mailbox, WC_NID_rfc822Mailbox, oidCertNameType, "rfc822Mailbox", + "rfc822Mailbox"}, + { WC_NID_favouriteDrink, WC_NID_favouriteDrink, oidCertNameType, "favouriteDrink", "favouriteDrink"}, - { NID_businessCategory, NID_businessCategory, oidCertNameType, + { WC_NID_businessCategory, WC_NID_businessCategory, oidCertNameType, "businessCategory", "businessCategory"}, - { NID_jurisdictionCountryName, NID_jurisdictionCountryName, oidCertNameType, + { WC_NID_jurisdictionCountryName, WC_NID_jurisdictionCountryName, oidCertNameType, "jurisdictionC", "jurisdictionCountryName"}, - { NID_jurisdictionStateOrProvinceName, NID_jurisdictionStateOrProvinceName, + { WC_NID_jurisdictionStateOrProvinceName, WC_NID_jurisdictionStateOrProvinceName, oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"}, - { NID_postalCode, NID_postalCode, oidCertNameType, "postalCode", + { WC_NID_postalCode, WC_NID_postalCode, oidCertNameType, "postalCode", "postalCode"}, - { NID_userId, NID_userId, oidCertNameType, "UID", "userId"}, + { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userId"}, #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) - { NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, + { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, oidCsrAttrType, "challengePassword", "challengePassword"}, - { NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID, + { WC_NID_pkcs9_contentType, PKCS9_CONTENT_TYPE_OID, oidCsrAttrType, "contentType", "contentType" }, - { NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID, + { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID, oidCsrAttrType, "unstructuredName", "unstructuredName" }, - { NID_name, NAME_OID, oidCsrAttrType, "name", "name" }, - { NID_surname, SURNAME_OID, + { WC_NID_name, NAME_OID, oidCsrAttrType, "name", "name" }, + { WC_NID_surname, SURNAME_OID, oidCsrAttrType, "surname", "surname" }, - { NID_givenName, GIVEN_NAME_OID, + { WC_NID_givenName, GIVEN_NAME_OID, oidCsrAttrType, "givenName", "givenName" }, - { NID_initials, INITIALS_OID, + { WC_NID_initials, INITIALS_OID, oidCsrAttrType, "initials", "initials" }, - { NID_dnQualifier, DNQUALIFIER_OID, + { WC_NID_dnQualifier, DNQUALIFIER_OID, oidCsrAttrType, "dnQualifer", "dnQualifier" }, #endif #endif #ifdef OPENSSL_EXTRA /* OPENSSL_EXTRA_X509_SMALL only needs the above */ /* oidHashType */ #ifdef WOLFSSL_MD2 - { NID_md2, MD2h, oidHashType, "MD2", "md2"}, + { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"}, #endif - #ifdef WOLFSSL_MD5 - { NID_md5, MD5h, oidHashType, "MD5", "md5"}, + #ifndef NO_MD5 + { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"}, #endif #ifndef NO_SHA - { NID_sha1, SHAh, oidHashType, "SHA1", "sha1"}, + { WC_NID_sha1, SHAh, oidHashType, "SHA1", "sha1"}, #endif #ifdef WOLFSSL_SHA224 - { NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"}, + { WC_NID_sha224, SHA224h, oidHashType, "SHA224", "sha224"}, #endif #ifndef NO_SHA256 - { NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"}, + { WC_NID_sha256, SHA256h, oidHashType, "SHA256", "sha256"}, #endif #ifdef WOLFSSL_SHA384 - { NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"}, + { WC_NID_sha384, SHA384h, oidHashType, "SHA384", "sha384"}, #endif #ifdef WOLFSSL_SHA512 - { NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"}, + { WC_NID_sha512, SHA512h, oidHashType, "SHA512", "sha512"}, #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - { NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"}, + { WC_NID_sha3_224, SHA3_224h, oidHashType, "SHA3-224", "sha3-224"}, #endif #ifndef WOLFSSL_NOSHA3_256 - { NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"}, + { WC_NID_sha3_256, SHA3_256h, oidHashType, "SHA3-256", "sha3-256"}, #endif #ifndef WOLFSSL_NOSHA3_384 - { NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"}, + { WC_NID_sha3_384, SHA3_384h, oidHashType, "SHA3-384", "sha3-384"}, #endif #ifndef WOLFSSL_NOSHA3_512 - { NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"}, + { WC_NID_sha3_512, SHA3_512h, oidHashType, "SHA3-512", "sha3-512"}, #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - { NID_sm3, SM3h, oidHashType, "SM3", "sm3"}, + { WC_NID_sm3, SM3h, oidHashType, "SM3", "sm3"}, #endif /* oidSigType */ #ifndef NO_DSA #ifndef NO_SHA - { NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"}, - { NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256", + { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"}, + { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256", "dsa_with_SHA256"}, #endif #endif /* NO_DSA */ #ifndef NO_RSA #ifdef WOLFSSL_MD2 - { NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2", + { WC_NID_md2WithRSAEncryption, CTC_MD2wRSA, oidSigType, "RSA-MD2", "md2WithRSAEncryption"}, #endif #ifndef NO_MD5 - { NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5", + { WC_NID_md5WithRSAEncryption, CTC_MD5wRSA, oidSigType, "RSA-MD5", "md5WithRSAEncryption"}, #endif #ifndef NO_SHA - { NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1", + { WC_NID_sha1WithRSAEncryption, CTC_SHAwRSA, oidSigType, "RSA-SHA1", "sha1WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA224 - { NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224", + { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224", "sha224WithRSAEncryption"}, #endif #ifndef NO_SHA256 - { NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256", + { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256", "sha256WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA384 - { NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384", + { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384", "sha384WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA512 - { NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512", + { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512", "sha512WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - { NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224", + { WC_NID_RSA_SHA3_224, CTC_SHA3_224wRSA, oidSigType, "RSA-SHA3-224", "sha3-224WithRSAEncryption"}, #endif #ifndef WOLFSSL_NOSHA3_256 - { NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256", + { WC_NID_RSA_SHA3_256, CTC_SHA3_256wRSA, oidSigType, "RSA-SHA3-256", "sha3-256WithRSAEncryption"}, #endif #ifndef WOLFSSL_NOSHA3_384 - { NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384", + { WC_NID_RSA_SHA3_384, CTC_SHA3_384wRSA, oidSigType, "RSA-SHA3-384", "sha3-384WithRSAEncryption"}, #endif #ifndef WOLFSSL_NOSHA3_512 - { NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512", + { WC_NID_RSA_SHA3_512, CTC_SHA3_512wRSA, oidSigType, "RSA-SHA3-512", "sha3-512WithRSAEncryption"}, #endif #endif #ifdef WC_RSA_PSS - { NID_rsassaPss, CTC_RSASSAPSS, oidSigType, "RSASSA-PSS", "rsassaPss" }, + { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType, "RSASSA-PSS", "rsassaPss" }, #endif #endif /* NO_RSA */ #ifdef HAVE_ECC #ifndef NO_SHA - { NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1", + { WC_NID_ecdsa_with_SHA1, CTC_SHAwECDSA, oidSigType, "ecdsa-with-SHA1", "shaWithECDSA"}, #endif #ifdef WOLFSSL_SHA224 - { NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA224, CTC_SHA224wECDSA, oidSigType, "ecdsa-with-SHA224","sha224WithECDSA"}, #endif #ifndef NO_SHA256 - { NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA256, CTC_SHA256wECDSA, oidSigType, "ecdsa-with-SHA256","sha256WithECDSA"}, #endif #ifdef WOLFSSL_SHA384 - { NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA384, CTC_SHA384wECDSA, oidSigType, "ecdsa-with-SHA384","sha384WithECDSA"}, #endif #ifdef WOLFSSL_SHA512 - { NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA512, CTC_SHA512wECDSA, oidSigType, "ecdsa-with-SHA512","sha512WithECDSA"}, #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - { NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA3_224, CTC_SHA3_224wECDSA, oidSigType, "id-ecdsa-with-SHA3-224", "ecdsa_with_SHA3-224"}, #endif #ifndef WOLFSSL_NOSHA3_256 - { NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA3_256, CTC_SHA3_256wECDSA, oidSigType, "id-ecdsa-with-SHA3-256", "ecdsa_with_SHA3-256"}, #endif #ifndef WOLFSSL_NOSHA3_384 - { NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA3_384, CTC_SHA3_384wECDSA, oidSigType, "id-ecdsa-with-SHA3-384", "ecdsa_with_SHA3-384"}, #endif #ifndef WOLFSSL_NOSHA3_512 - { NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType, + { WC_NID_ecdsa_with_SHA3_512, CTC_SHA3_512wECDSA, oidSigType, "id-ecdsa-with-SHA3-512", "ecdsa_with_SHA3-512"}, #endif #endif @@ -17531,28 +18320,28 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { /* oidKeyType */ #ifndef NO_DSA - { NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"}, + { WC_NID_dsa, DSAk, oidKeyType, "DSA", "dsaEncryption"}, #endif /* NO_DSA */ #ifndef NO_RSA - { NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption", + { WC_NID_rsaEncryption, RSAk, oidKeyType, "rsaEncryption", "rsaEncryption"}, #ifdef WC_RSA_PSS - { NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"}, + { WC_NID_rsassaPss, RSAPSSk, oidKeyType, "RSASSA-PSS", "rsassaPss"}, #endif #endif /* NO_RSA */ #ifdef HAVE_ECC - { NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey", + { WC_NID_X9_62_id_ecPublicKey, ECDSAk, oidKeyType, "id-ecPublicKey", "id-ecPublicKey"}, #endif /* HAVE_ECC */ #ifndef NO_DH - { NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement", + { WC_NID_dhKeyAgreement, DHk, oidKeyType, "dhKeyAgreement", "dhKeyAgreement"}, #endif #ifdef HAVE_ED448 - { NID_ED448, ED448k, oidKeyType, "ED448", "ED448"}, + { WC_NID_ED448, ED448k, oidKeyType, "ED448", "ED448"}, #endif #ifdef HAVE_ED25519 - { NID_ED25519, ED25519k, oidKeyType, "ED25519", "ED25519"}, + { WC_NID_ED25519, ED25519k, oidKeyType, "ED25519", "ED25519"}, #endif #ifdef HAVE_FALCON { CTC_FALCON_LEVEL1, FALCON_LEVEL1k, oidKeyType, "Falcon Level 1", @@ -17571,71 +18360,71 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { /* oidCurveType */ #ifdef HAVE_ECC - { NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", + { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", "prime192v1"}, - { NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", + { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", "prime192v2"}, - { NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", + { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", "prime192v3"}, - { NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", + { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", "prime239v1"}, - { NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", + { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", "prime239v2"}, - { NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", + { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", "prime239v3"}, - { NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", + { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", "prime256v1"}, - { NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", + { WC_NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", "secp112r1"}, - { NID_secp112r2, ECC_SECP112R2_OID, oidCurveType, "secp112r2", + { WC_NID_secp112r2, ECC_SECP112R2_OID, oidCurveType, "secp112r2", "secp112r2"}, - { NID_secp128r1, ECC_SECP128R1_OID, oidCurveType, "secp128r1", + { WC_NID_secp128r1, ECC_SECP128R1_OID, oidCurveType, "secp128r1", "secp128r1"}, - { NID_secp128r2, ECC_SECP128R2_OID, oidCurveType, "secp128r2", + { WC_NID_secp128r2, ECC_SECP128R2_OID, oidCurveType, "secp128r2", "secp128r2"}, - { NID_secp160r1, ECC_SECP160R1_OID, oidCurveType, "secp160r1", + { WC_NID_secp160r1, ECC_SECP160R1_OID, oidCurveType, "secp160r1", "secp160r1"}, - { NID_secp160r2, ECC_SECP160R2_OID, oidCurveType, "secp160r2", + { WC_NID_secp160r2, ECC_SECP160R2_OID, oidCurveType, "secp160r2", "secp160r2"}, - { NID_secp224r1, ECC_SECP224R1_OID, oidCurveType, "secp224r1", + { WC_NID_secp224r1, ECC_SECP224R1_OID, oidCurveType, "secp224r1", "secp224r1"}, - { NID_secp384r1, ECC_SECP384R1_OID, oidCurveType, "secp384r1", + { WC_NID_secp384r1, ECC_SECP384R1_OID, oidCurveType, "secp384r1", "secp384r1"}, - { NID_secp521r1, ECC_SECP521R1_OID, oidCurveType, "secp521r1", + { WC_NID_secp521r1, ECC_SECP521R1_OID, oidCurveType, "secp521r1", "secp521r1"}, - { NID_secp160k1, ECC_SECP160K1_OID, oidCurveType, "secp160k1", + { WC_NID_secp160k1, ECC_SECP160K1_OID, oidCurveType, "secp160k1", "secp160k1"}, - { NID_secp192k1, ECC_SECP192K1_OID, oidCurveType, "secp192k1", + { WC_NID_secp192k1, ECC_SECP192K1_OID, oidCurveType, "secp192k1", "secp192k1"}, - { NID_secp224k1, ECC_SECP224K1_OID, oidCurveType, "secp224k1", + { WC_NID_secp224k1, ECC_SECP224K1_OID, oidCurveType, "secp224k1", "secp224k1"}, - { NID_secp256k1, ECC_SECP256K1_OID, oidCurveType, "secp256k1", + { WC_NID_secp256k1, ECC_SECP256K1_OID, oidCurveType, "secp256k1", "secp256k1"}, - { NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID, oidCurveType, + { WC_NID_brainpoolP160r1, ECC_BRAINPOOLP160R1_OID, oidCurveType, "brainpoolP160r1", "brainpoolP160r1"}, - { NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID, oidCurveType, + { WC_NID_brainpoolP192r1, ECC_BRAINPOOLP192R1_OID, oidCurveType, "brainpoolP192r1", "brainpoolP192r1"}, - { NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID, oidCurveType, + { WC_NID_brainpoolP224r1, ECC_BRAINPOOLP224R1_OID, oidCurveType, "brainpoolP224r1", "brainpoolP224r1"}, - { NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID, oidCurveType, + { WC_NID_brainpoolP256r1, ECC_BRAINPOOLP256R1_OID, oidCurveType, "brainpoolP256r1", "brainpoolP256r1"}, - { NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID, oidCurveType, + { WC_NID_brainpoolP320r1, ECC_BRAINPOOLP320R1_OID, oidCurveType, "brainpoolP320r1", "brainpoolP320r1"}, - { NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID, oidCurveType, + { WC_NID_brainpoolP384r1, ECC_BRAINPOOLP384R1_OID, oidCurveType, "brainpoolP384r1", "brainpoolP384r1"}, - { NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID, oidCurveType, + { WC_NID_brainpoolP512r1, ECC_BRAINPOOLP512R1_OID, oidCurveType, "brainpoolP512r1", "brainpoolP512r1"}, #ifdef WOLFSSL_SM2 - { NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"}, + { WC_NID_sm2, ECC_SM2P256V1_OID, oidCurveType, "sm2", "sm2"}, #endif #endif /* HAVE_ECC */ @@ -17650,17 +18439,17 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { { AES256CBCb, AES256CBCb, oidBlkType, "AES-256-CBC", "aes-256-cbc"}, #endif #ifndef NO_DES3 - { NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"}, - { NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"}, + { WC_NID_des, DESb, oidBlkType, "DES-CBC", "des-cbc"}, + { WC_NID_des3, DES3b, oidBlkType, "DES-EDE3-CBC", "des-ede3-cbc"}, #endif /* !NO_DES3 */ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - { NID_chacha20_poly1305, NID_chacha20_poly1305, oidBlkType, + { WC_NID_chacha20_poly1305, WC_NID_chacha20_poly1305, oidBlkType, "ChaCha20-Poly1305", "chacha20-poly1305"}, #endif /* oidOcspType */ #ifdef HAVE_OCSP - { NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType, + { WC_NID_id_pkix_OCSP_basic, OCSP_BASIC_OID, oidOcspType, "basicOCSPResponse", "Basic OCSP Response"}, { OCSP_NONCE_OID, OCSP_NONCE_OID, oidOcspType, "Nonce", "OCSP Nonce"}, #endif /* HAVE_OCSP */ @@ -17728,15 +18517,15 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #endif #if defined(WOLFSSL_APACHE_HTTPD) /* "1.3.6.1.5.5.7.8.7" */ - { NID_id_on_dnsSRV, NID_id_on_dnsSRV, oidCertNameType, + { WC_NID_id_on_dnsSRV, WC_NID_id_on_dnsSRV, oidCertNameType, WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV }, /* "1.3.6.1.4.1.311.20.2.3" */ - { NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN, + { WC_NID_ms_upn, WOLFSSL_MS_UPN_SUM, oidCertExtType, WOLFSSL_SN_MS_UPN, WOLFSSL_LN_MS_UPN }, /* "1.3.6.1.5.5.7.1.24" */ - { NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType, + { WC_NID_tlsfeature, WOLFSSL_TLS_FEATURE_SUM, oidTlsExtType, WOLFSSL_SN_TLS_FEATURE, WOLFSSL_LN_TLS_FEATURE }, #endif #endif /* OPENSSL_EXTRA */ @@ -17745,7 +18534,7 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #define WOLFSSL_OBJECT_INFO_SZ \ (sizeof(wolfssl_object_info) / sizeof(*wolfssl_object_info)) const size_t wolfssl_object_info_sz = WOLFSSL_OBJECT_INFO_SZ; -#endif +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* Free the dynamically allocated data. @@ -17812,7 +18601,7 @@ unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len) return targetBuf; } -int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings) +int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings) { (void)opts; (void)settings; @@ -17820,7 +18609,7 @@ int wolfSSL_OPENSSL_init_ssl(word64 opts, const OPENSSL_INIT_SETTINGS *settings) } int wolfSSL_OPENSSL_init_crypto(word64 opts, - const OPENSSL_INIT_SETTINGS* settings) + const WOLFSSL_INIT_SETTINGS* settings) { (void)opts; (void)settings; @@ -17871,31 +18660,31 @@ static int HashToNid(byte hashAlgo, int* nid) switch ((enum wc_MACAlgorithm)hashAlgo) { case no_mac: case rmd_mac: - *nid = NID_undef; + *nid = WC_NID_undef; break; case md5_mac: - *nid = NID_md5; + *nid = WC_NID_md5; break; case sha_mac: - *nid = NID_sha1; + *nid = WC_NID_sha1; break; case sha224_mac: - *nid = NID_sha224; + *nid = WC_NID_sha224; break; case sha256_mac: - *nid = NID_sha256; + *nid = WC_NID_sha256; break; case sha384_mac: - *nid = NID_sha384; + *nid = WC_NID_sha384; break; case sha512_mac: - *nid = NID_sha512; + *nid = WC_NID_sha512; break; case blake2b_mac: - *nid = NID_blake2b512; + *nid = WC_NID_blake2b512; break; case sm3_mac: - *nid = NID_sm3; + *nid = WC_NID_sm3; break; default: ret = WOLFSSL_FAILURE; @@ -17911,33 +18700,33 @@ static int SaToNid(byte sa, int* nid) /* Cast for compiler to check everything is implemented */ switch ((enum SignatureAlgorithm)sa) { case anonymous_sa_algo: - *nid = NID_undef; + *nid = WC_NID_undef; break; case rsa_sa_algo: - *nid = NID_rsaEncryption; + *nid = WC_NID_rsaEncryption; break; case dsa_sa_algo: - *nid = NID_dsa; + *nid = WC_NID_dsa; break; case ecc_dsa_sa_algo: - *nid = NID_X9_62_id_ecPublicKey; + *nid = WC_NID_X9_62_id_ecPublicKey; break; case rsa_pss_sa_algo: - *nid = NID_rsassaPss; + *nid = WC_NID_rsassaPss; break; case ed25519_sa_algo: #ifdef HAVE_ED25519 - *nid = NID_ED25519; + *nid = WC_NID_ED25519; #else ret = WOLFSSL_FAILURE; #endif break; case rsa_pss_pss_algo: - *nid = NID_rsassaPss; + *nid = WC_NID_rsassaPss; break; case ed448_sa_algo: #ifdef HAVE_ED448 - *nid = NID_ED448; + *nid = WC_NID_ED448; #else ret = WOLFSSL_FAILURE; #endif @@ -17958,7 +18747,7 @@ static int SaToNid(byte sa, int* nid) *nid = CTC_DILITHIUM_LEVEL5; break; case sm2_sa_algo: - *nid = NID_sm2; + *nid = WC_NID_sm2; break; case invalid_sa_algo: default: @@ -19060,8 +19849,8 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) if (bufSz) { XMEMCPY(buf, name, bufSz); } - else if (a->type == GEN_DNS || a->type == GEN_EMAIL || - a->type == GEN_URI) { + else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL || + a->type == WOLFSSL_GEN_URI) { bufSz = (int)XSTRLEN((const char*)a->obj); XMEMCPY(buf, a->obj, min((word32)bufSz, (word32)bufLen)); } @@ -19116,10 +19905,10 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) size_t i; WOLFSSL_ENTER("wolfSSL_OBJ_nid2sn"); - if (n == NID_md5) { - /* NID_surname == NID_md5 and NID_surname comes before NID_md5 in + if (n == WC_NID_md5) { + /* WC_NID_surname == WC_NID_md5 and WC_NID_surname comes before WC_NID_md5 in * wolfssl_object_info. As a result, the loop below will incorrectly - * return "SN" instead of "MD5." NID_surname isn't the true OpenSSL + * return "SN" instead of "MD5." WC_NID_surname isn't the true OpenSSL * NID, but other functions rely on this table and modifying it to * conform with OpenSSL's NIDs isn't trivial. */ return "MD5"; @@ -19137,7 +19926,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) int wolfSSL_OBJ_sn2nid(const char *sn) { WOLFSSL_ENTER("wolfSSL_OBJ_sn2nid"); if (sn == NULL) - return NID_undef; + return WC_NID_undef; return wc_OBJ_sn2nid(sn); } #endif @@ -19217,9 +20006,9 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) #ifdef WOLFSSL_QT if (o->grp == oidCertExtType) { - /* If nid is an unknown extension, return NID_undef */ + /* If nid is an unknown extension, return WC_NID_undef */ if (wolfSSL_OBJ_nid2sn(o->nid) == NULL) - return NID_undef; + return WC_NID_undef; } #endif @@ -19254,7 +20043,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) } /* Return the corresponding NID for the long name - * or NID_undef if NID can't be found. + * or WC_NID_undef if NID can't be found. */ int wolfSSL_OBJ_ln2nid(const char *ln) { @@ -19281,7 +20070,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) } } } - return NID_undef; + return WC_NID_undef; } /* compares two objects, return 0 if equal */ @@ -19333,7 +20122,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) /* Gets the NID value that is related to the OID string passed in. Example * string would be "2.5.29.14" for subject key ID. * - * returns NID value on success and NID_undef on error + * returns NID value on success and WC_NID_undef on error */ int wolfSSL_OBJ_txt2nid(const char* s) { @@ -19348,7 +20137,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid"); if (s == NULL) { - return NID_undef; + return WC_NID_undef; } #ifdef WOLFSSL_CERT_EXT @@ -19387,7 +20176,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) } } - return NID_undef; + return WC_NID_undef; } #endif #if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \ @@ -19406,7 +20195,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) WOLFSSL_ASN1_OBJECT* wolfSSL_OBJ_txt2obj(const char* s, int no_name) { int i, ret; - int nid = NID_undef; + int nid = WC_NID_undef; unsigned int outSz = MAX_OID_SZ; unsigned char out[MAX_OID_SZ]; WOLFSSL_ASN1_OBJECT* obj; @@ -19453,7 +20242,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) } } - if (nid != NID_undef) + if (nid != WC_NID_undef) return wolfSSL_OBJ_nid2obj(nid); return NULL; @@ -19528,11 +20317,7 @@ unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line) #endif /* OPENSSL_EXTRA */ -#if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ - defined(WOLFSSL_WPAS_SMALL) +#ifdef HAVE_EX_DATA_CRYPTO CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL; static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr, @@ -19670,23 +20455,9 @@ int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, return WOLFSSL_FATAL_ERROR; return idx; } -#endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */ - -#if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) -void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx) -{ - WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); -#ifdef HAVE_EX_DATA - if(ctx != NULL) { - return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); - } -#else - (void)ctx; - (void)idx; -#endif - return NULL; -} +#endif /* HAVE_EX_DATA_CRYPTO */ +#ifdef HAVE_EX_DATA_CRYPTO int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, @@ -19712,21 +20483,35 @@ int wolfSSL_get_ex_new_index(long argValue, void* arg, return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue, arg, cb1, cb2, cb3); } +#endif /* HAVE_EX_DATA_CRYPTO */ +#ifdef OPENSSL_EXTRA +void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx) +{ + WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); +#ifdef HAVE_EX_DATA + if (ctx != NULL) { + return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); + } +#else + (void)ctx; + (void)idx; +#endif + return NULL; +} int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data) { WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data"); - #ifdef HAVE_EX_DATA - if (ctx != NULL) - { +#ifdef HAVE_EX_DATA + if (ctx != NULL) { return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data); } - #else +#else (void)ctx; (void)idx; (void)data; - #endif +#endif return WOLFSSL_FAILURE; } @@ -19738,16 +20523,14 @@ int wolfSSL_CTX_set_ex_data_with_cleanup( wolfSSL_ex_data_cleanup_routine_t cleanup_routine) { WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup"); - if (ctx != NULL) - { + if (ctx != NULL) { return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data, cleanup_routine); } return WOLFSSL_FAILURE; } #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - -#endif /* defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) */ +#endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) @@ -19779,15 +20562,11 @@ int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) { #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ -#if defined(HAVE_EX_DATA) || defined(OPENSSL_EXTRA) || \ - defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_WPAS_SMALL) - int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data) { WOLFSSL_ENTER("wolfSSL_set_ex_data"); #ifdef HAVE_EX_DATA - if (ssl != NULL) - { + if (ssl != NULL) { return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data); } #else @@ -19831,8 +20610,6 @@ void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx) return 0; } -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */ - #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \ || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) @@ -20012,10 +20789,10 @@ long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt) if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) { WOLFSSL_MSG("Using Server's Cipher Preference."); - ctx->useClientOrder = FALSE; + ctx->useClientOrder = 0; } else { WOLFSSL_MSG("Using Client's Cipher Preference."); - ctx->useClientOrder = TRUE; + ctx->useClientOrder = 1; } #endif /* WOLFSSL_QT */ @@ -20457,7 +21234,7 @@ WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) InitSSL_CTX_Suites(ctx); } - wolfSSL_RefInc(&ctx->ref, &ret); + wolfSSL_RefWithMutexInc(&ctx->ref, &ret); #ifdef WOLFSSL_REFCNT_ERROR_RETURN if (ret != 0) { /* can only fail on serious stuff, like mutex not working @@ -20701,10 +21478,10 @@ unsigned long wolfSSL_ERR_peek_last_error(void) return 0; } if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) - return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; + return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E); #if defined(WOLFSSL_PYTHON) if (ret == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) - return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; + return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E); #endif return (unsigned long)ret; } @@ -20755,11 +21532,12 @@ WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl) return ssl->ctx; } -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && defined(HAVE_STUNNEL)) \ - || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) /* TODO: Doesn't currently track SSL_VERIFY_CLIENT_ONCE */ -int wolfSSL_get_verify_mode(const WOLFSSL* ssl) { +int wolfSSL_get_verify_mode(const WOLFSSL* ssl) +{ int mode = 0; WOLFSSL_ENTER("wolfSSL_get_verify_mode"); @@ -20907,21 +21685,22 @@ unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line, err = wc_PeekErrorNodeLineData(file, line, data, flags, peek_ignore_err); if (err == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) - return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; + return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E); #ifdef OPENSSL_ALL /* PARSE_ERROR is returned if an HTTP request is detected. */ else if (err == -WC_NO_ERR_TRACE(PARSE_ERROR)) - return (ERR_LIB_SSL << 24) | -SSL_R_HTTP_REQUEST; + return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */; #endif #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) else if (err == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) - return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; + return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E); #endif return err; } #endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ + defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) #if !defined(WOLFSSL_USER_IO) /* converts an IPv6 or IPv4 address into an octet string for use with rfc3280 @@ -21089,11 +21868,9 @@ WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl) } return ssl->suitesStack; } -#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ +#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK) +#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK) long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx) { WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout"); @@ -21133,7 +21910,7 @@ int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh) } #endif #ifndef NO_BIO -BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) +WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) { WOLFSSL_ENTER("wolfSSL_SSL_get_rbio"); /* Nginx sets the buffer size if the read BIO is different to write BIO. @@ -21144,7 +21921,7 @@ BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s) return s->biord; } -BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s) +WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s) { WOLFSSL_ENTER("wolfSSL_SSL_get_wbio"); (void)s; @@ -21158,6 +21935,7 @@ BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s) } #endif /* !NO_BIO */ +#ifndef NO_TLS int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s) { WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal"); @@ -21191,6 +21969,7 @@ int wolfSSL_SSL_do_handshake(WOLFSSL *s) #endif return wolfSSL_SSL_do_handshake_internal(s); } +#endif /* !NO_TLS */ #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L int wolfSSL_SSL_in_init(const WOLFSSL *ssl) @@ -21752,7 +22531,7 @@ int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen, byte lenIn, lenClient; if (out == NULL || outLen == NULL || in == NULL || clientNames == NULL) - return OPENSSL_NPN_UNSUPPORTED; + return WOLFSSL_NPN_UNSUPPORTED; for (i = 0; i < inLen; i += lenIn) { lenIn = in[i++]; @@ -21765,14 +22544,14 @@ int wolfSSL_select_next_proto(unsigned char **out, unsigned char *outLen, if (XMEMCMP(in + i, clientNames + j, lenIn) == 0) { *out = (unsigned char *)(in + i); *outLen = lenIn; - return OPENSSL_NPN_NEGOTIATED; + return WOLFSSL_NPN_NEGOTIATED; } } } *out = (unsigned char *)clientNames + 1; *outLen = clientNames[0]; - return OPENSSL_NPN_NO_OVERLAP; + return WOLFSSL_NPN_NO_OVERLAP; } void wolfSSL_set_alpn_select_cb(WOLFSSL *ssl, @@ -21876,28 +22655,42 @@ int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, word16 curve_id) const WOLF_EC_NIST_NAME kNistCurves[] = { #ifdef HAVE_ECC - {CURVE_NAME("P-160"), NID_secp160r1, WOLFSSL_ECC_SECP160R1}, - {CURVE_NAME("P-160-2"), NID_secp160r2, WOLFSSL_ECC_SECP160R2}, - {CURVE_NAME("P-192"), NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1}, - {CURVE_NAME("P-224"), NID_secp224r1, WOLFSSL_ECC_SECP224R1}, - {CURVE_NAME("P-256"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, - {CURVE_NAME("P-384"), NID_secp384r1, WOLFSSL_ECC_SECP384R1}, - {CURVE_NAME("P-521"), NID_secp521r1, WOLFSSL_ECC_SECP521R1}, - {CURVE_NAME("K-160"), NID_secp160k1, WOLFSSL_ECC_SECP160K1}, - {CURVE_NAME("K-192"), NID_secp192k1, WOLFSSL_ECC_SECP192K1}, - {CURVE_NAME("K-224"), NID_secp224k1, WOLFSSL_ECC_SECP224R1}, - {CURVE_NAME("K-256"), NID_secp256k1, WOLFSSL_ECC_SECP256K1}, - {CURVE_NAME("B-256"), NID_brainpoolP256r1, WOLFSSL_ECC_BRAINPOOLP256R1}, - {CURVE_NAME("B-384"), NID_brainpoolP384r1, WOLFSSL_ECC_BRAINPOOLP384R1}, - {CURVE_NAME("B-512"), NID_brainpoolP512r1, WOLFSSL_ECC_BRAINPOOLP512R1}, + {CURVE_NAME("P-160"), WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1}, + {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2}, + {CURVE_NAME("P-192"), WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1}, + {CURVE_NAME("P-224"), WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1}, + {CURVE_NAME("P-256"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("P-384"), WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1}, + {CURVE_NAME("P-521"), WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1}, + {CURVE_NAME("K-160"), WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1}, + {CURVE_NAME("K-192"), WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1}, + {CURVE_NAME("K-224"), WC_NID_secp224k1, WOLFSSL_ECC_SECP224R1}, + {CURVE_NAME("K-256"), WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1}, + {CURVE_NAME("B-256"), WC_NID_brainpoolP256r1, WOLFSSL_ECC_BRAINPOOLP256R1}, + {CURVE_NAME("B-384"), WC_NID_brainpoolP384r1, WOLFSSL_ECC_BRAINPOOLP384R1}, + {CURVE_NAME("B-512"), WC_NID_brainpoolP512r1, WOLFSSL_ECC_BRAINPOOLP512R1}, #endif #ifdef HAVE_CURVE25519 - {CURVE_NAME("X25519"), NID_X25519, WOLFSSL_ECC_X25519}, + {CURVE_NAME("X25519"), WC_NID_X25519, WOLFSSL_ECC_X25519}, #endif #ifdef HAVE_CURVE448 - {CURVE_NAME("X448"), NID_X448, WOLFSSL_ECC_X448}, + {CURVE_NAME("X448"), WC_NID_X448, WOLFSSL_ECC_X448}, #endif #ifdef WOLFSSL_HAVE_KYBER +#ifndef WOLFSSL_NO_ML_KEM + {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512}, + {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768}, + {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024}, +#if (defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) + {CURVE_NAME("P256_ML_KEM_512"), WOLFSSL_P256_ML_KEM_512, + WOLFSSL_P256_ML_KEM_512}, + {CURVE_NAME("P384_ML_KEM_768"), WOLFSSL_P384_ML_KEM_768, + WOLFSSL_P384_ML_KEM_768}, + {CURVE_NAME("P521_ML_KEM_1024"), WOLFSSL_P521_ML_KEM_1024, + WOLFSSL_P521_ML_KEM_1024}, +#endif +#endif /* !WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_KYBER_ORIGINAL {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1}, {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3}, {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5}, @@ -21906,19 +22699,20 @@ const WOLF_EC_NIST_NAME kNistCurves[] = { {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P384_KYBER_LEVEL3}, {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_P521_KYBER_LEVEL5}, #endif -#endif +#endif /* WOLFSSL_KYBER_ORIGINAL */ +#endif /* WOLFSSL_HAVE_KYBER */ #ifdef WOLFSSL_SM2 - {CURVE_NAME("SM2"), NID_sm2, WOLFSSL_ECC_SM2P256V1}, + {CURVE_NAME("SM2"), WC_NID_sm2, WOLFSSL_ECC_SM2P256V1}, #endif #ifdef HAVE_ECC /* Alternative curve names */ - {CURVE_NAME("prime256v1"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, - {CURVE_NAME("secp256r1"), NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, - {CURVE_NAME("secp384r1"), NID_secp384r1, WOLFSSL_ECC_SECP384R1}, - {CURVE_NAME("secp521r1"), NID_secp521r1, WOLFSSL_ECC_SECP521R1}, + {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("secp256r1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1}, + {CURVE_NAME("secp384r1"), WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1}, + {CURVE_NAME("secp521r1"), WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1}, #endif #ifdef WOLFSSL_SM2 - {CURVE_NAME("sm2p256v1"), NID_sm2, WOLFSSL_ECC_SM2P256V1}, + {CURVE_NAME("sm2p256v1"), WC_NID_sm2, WOLFSSL_ECC_SM2P256V1}, #endif {0, NULL, 0, 0}, }; @@ -22031,7 +22825,7 @@ int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, else { disabled &= ~(1U << curve); } - #ifdef HAVE_SUPPORTED_CURVES + #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS) #if !defined(WOLFSSL_OLD_SET_CURVES_LIST) /* using the wolfSSL API to set the groups, this will populate * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS. @@ -22054,7 +22848,7 @@ int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, goto leave; } #endif - #endif /* HAVE_SUPPORTED_CURVES */ + #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */ } if (ssl != NULL) @@ -22093,6 +22887,7 @@ int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names) #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */ #endif /* OPENSSL_EXTRA || HAVE_CURL */ + #ifdef OPENSSL_EXTRA /* Sets a callback for when sending and receiving protocol messages. * This callback is copied to all WOLFSSL objects created from the ctx. @@ -22174,7 +22969,7 @@ void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file, if (data == NULL || siz >= INT_MAX) return NULL; - ret = OPENSSL_malloc(siz); + ret = wolfSSL_OPENSSL_malloc(siz); if (ret == NULL) { return NULL; } @@ -22329,45 +23124,45 @@ word32 nid2oid(int nid, int grp) case oidHashType: switch (nid) { #ifdef WOLFSSL_MD2 - case NID_md2: + case WC_NID_md2: return MD2h; #endif #ifndef NO_MD5 - case NID_md5: + case WC_NID_md5: return MD5h; #endif #ifndef NO_SHA - case NID_sha1: + case WC_NID_sha1: return SHAh; #endif - case NID_sha224: + case WC_NID_sha224: return SHA224h; #ifndef NO_SHA256 - case NID_sha256: + case WC_NID_sha256: return SHA256h; #endif #ifdef WOLFSSL_SHA384 - case NID_sha384: + case WC_NID_sha384: return SHA384h; #endif #ifdef WOLFSSL_SHA512 - case NID_sha512: + case WC_NID_sha512: return SHA512h; #endif #ifndef WOLFSSL_NOSHA3_224 - case NID_sha3_224: + case WC_NID_sha3_224: return SHA3_224h; #endif #ifndef WOLFSSL_NOSHA3_256 - case NID_sha3_256: + case WC_NID_sha3_256: return SHA3_256h; #endif #ifndef WOLFSSL_NOSHA3_384 - case NID_sha3_384: + case WC_NID_sha3_384: return SHA3_384h; #endif #ifndef WOLFSSL_NOSHA3_512 - case NID_sha3_512: + case WC_NID_sha3_512: return SHA3_512h; #endif } @@ -22377,56 +23172,56 @@ word32 nid2oid(int nid, int grp) case oidSigType: switch (nid) { #ifndef NO_DSA - case NID_dsaWithSHA1: + case WC_NID_dsaWithSHA1: return CTC_SHAwDSA; - case NID_dsa_with_SHA256: + case WC_NID_dsa_with_SHA256: return CTC_SHA256wDSA; #endif /* NO_DSA */ #ifndef NO_RSA - case NID_md2WithRSAEncryption: + case WC_NID_md2WithRSAEncryption: return CTC_MD2wRSA; - case NID_md5WithRSAEncryption: + case WC_NID_md5WithRSAEncryption: return CTC_MD5wRSA; - case NID_sha1WithRSAEncryption: + case WC_NID_sha1WithRSAEncryption: return CTC_SHAwRSA; - case NID_sha224WithRSAEncryption: + case WC_NID_sha224WithRSAEncryption: return CTC_SHA224wRSA; - case NID_sha256WithRSAEncryption: + case WC_NID_sha256WithRSAEncryption: return CTC_SHA256wRSA; - case NID_sha384WithRSAEncryption: + case WC_NID_sha384WithRSAEncryption: return CTC_SHA384wRSA; - case NID_sha512WithRSAEncryption: + case WC_NID_sha512WithRSAEncryption: return CTC_SHA512wRSA; #ifdef WOLFSSL_SHA3 - case NID_RSA_SHA3_224: + case WC_NID_RSA_SHA3_224: return CTC_SHA3_224wRSA; - case NID_RSA_SHA3_256: + case WC_NID_RSA_SHA3_256: return CTC_SHA3_256wRSA; - case NID_RSA_SHA3_384: + case WC_NID_RSA_SHA3_384: return CTC_SHA3_384wRSA; - case NID_RSA_SHA3_512: + case WC_NID_RSA_SHA3_512: return CTC_SHA3_512wRSA; #endif #endif /* NO_RSA */ #ifdef HAVE_ECC - case NID_ecdsa_with_SHA1: + case WC_NID_ecdsa_with_SHA1: return CTC_SHAwECDSA; - case NID_ecdsa_with_SHA224: + case WC_NID_ecdsa_with_SHA224: return CTC_SHA224wECDSA; - case NID_ecdsa_with_SHA256: + case WC_NID_ecdsa_with_SHA256: return CTC_SHA256wECDSA; - case NID_ecdsa_with_SHA384: + case WC_NID_ecdsa_with_SHA384: return CTC_SHA384wECDSA; - case NID_ecdsa_with_SHA512: + case WC_NID_ecdsa_with_SHA512: return CTC_SHA512wECDSA; #ifdef WOLFSSL_SHA3 - case NID_ecdsa_with_SHA3_224: + case WC_NID_ecdsa_with_SHA3_224: return CTC_SHA3_224wECDSA; - case NID_ecdsa_with_SHA3_256: + case WC_NID_ecdsa_with_SHA3_256: return CTC_SHA3_256wECDSA; - case NID_ecdsa_with_SHA3_384: + case WC_NID_ecdsa_with_SHA3_384: return CTC_SHA3_384wECDSA; - case NID_ecdsa_with_SHA3_512: + case WC_NID_ecdsa_with_SHA3_512: return CTC_SHA3_512wECDSA; #endif #endif /* HAVE_ECC */ @@ -22437,15 +23232,15 @@ word32 nid2oid(int nid, int grp) case oidKeyType: switch (nid) { #ifndef NO_DSA - case NID_dsa: + case WC_NID_dsa: return DSAk; #endif /* NO_DSA */ #ifndef NO_RSA - case NID_rsaEncryption: + case WC_NID_rsaEncryption: return RSAk; #endif /* NO_RSA */ #ifdef HAVE_ECC - case NID_X9_62_id_ecPublicKey: + case WC_NID_X9_62_id_ecPublicKey: return ECDSAk; #endif /* HAVE_ECC */ } @@ -22455,59 +23250,59 @@ word32 nid2oid(int nid, int grp) #ifdef HAVE_ECC case oidCurveType: switch (nid) { - case NID_X9_62_prime192v1: + case WC_NID_X9_62_prime192v1: return ECC_SECP192R1_OID; - case NID_X9_62_prime192v2: + case WC_NID_X9_62_prime192v2: return ECC_PRIME192V2_OID; - case NID_X9_62_prime192v3: + case WC_NID_X9_62_prime192v3: return ECC_PRIME192V3_OID; - case NID_X9_62_prime239v1: + case WC_NID_X9_62_prime239v1: return ECC_PRIME239V1_OID; - case NID_X9_62_prime239v2: + case WC_NID_X9_62_prime239v2: return ECC_PRIME239V2_OID; - case NID_X9_62_prime239v3: + case WC_NID_X9_62_prime239v3: return ECC_PRIME239V3_OID; - case NID_X9_62_prime256v1: + case WC_NID_X9_62_prime256v1: return ECC_SECP256R1_OID; - case NID_secp112r1: + case WC_NID_secp112r1: return ECC_SECP112R1_OID; - case NID_secp112r2: + case WC_NID_secp112r2: return ECC_SECP112R2_OID; - case NID_secp128r1: + case WC_NID_secp128r1: return ECC_SECP128R1_OID; - case NID_secp128r2: + case WC_NID_secp128r2: return ECC_SECP128R2_OID; - case NID_secp160r1: + case WC_NID_secp160r1: return ECC_SECP160R1_OID; - case NID_secp160r2: + case WC_NID_secp160r2: return ECC_SECP160R2_OID; - case NID_secp224r1: + case WC_NID_secp224r1: return ECC_SECP224R1_OID; - case NID_secp384r1: + case WC_NID_secp384r1: return ECC_SECP384R1_OID; - case NID_secp521r1: + case WC_NID_secp521r1: return ECC_SECP521R1_OID; - case NID_secp160k1: + case WC_NID_secp160k1: return ECC_SECP160K1_OID; - case NID_secp192k1: + case WC_NID_secp192k1: return ECC_SECP192K1_OID; - case NID_secp224k1: + case WC_NID_secp224k1: return ECC_SECP224K1_OID; - case NID_secp256k1: + case WC_NID_secp256k1: return ECC_SECP256K1_OID; - case NID_brainpoolP160r1: + case WC_NID_brainpoolP160r1: return ECC_BRAINPOOLP160R1_OID; - case NID_brainpoolP192r1: + case WC_NID_brainpoolP192r1: return ECC_BRAINPOOLP192R1_OID; - case NID_brainpoolP224r1: + case WC_NID_brainpoolP224r1: return ECC_BRAINPOOLP224R1_OID; - case NID_brainpoolP256r1: + case WC_NID_brainpoolP256r1: return ECC_BRAINPOOLP256R1_OID; - case NID_brainpoolP320r1: + case WC_NID_brainpoolP320r1: return ECC_BRAINPOOLP320R1_OID; - case NID_brainpoolP384r1: + case WC_NID_brainpoolP384r1: return ECC_BRAINPOOLP384R1_OID; - case NID_brainpoolP512r1: + case WC_NID_brainpoolP512r1: return ECC_BRAINPOOLP512R1_OID; } break; @@ -22529,9 +23324,9 @@ word32 nid2oid(int nid, int grp) return AES256CBCb; #endif #ifndef NO_DES3 - case NID_des: + case WC_NID_des: return DESb; - case NID_des3: + case WC_NID_des3: return DES3b; #endif } @@ -22540,7 +23335,7 @@ word32 nid2oid(int nid, int grp) #ifdef HAVE_OCSP case oidOcspType: switch (nid) { - case NID_id_pkix_OCSP_basic: + case WC_NID_id_pkix_OCSP_basic: return OCSP_BASIC_OID; case OCSP_NONCE_OID: return OCSP_NONCE_OID; @@ -22551,27 +23346,27 @@ word32 nid2oid(int nid, int grp) /* oidCertExtType */ case oidCertExtType: switch (nid) { - case NID_basic_constraints: + case WC_NID_basic_constraints: return BASIC_CA_OID; - case NID_subject_alt_name: + case WC_NID_subject_alt_name: return ALT_NAMES_OID; - case NID_crl_distribution_points: + case WC_NID_crl_distribution_points: return CRL_DIST_OID; - case NID_info_access: + case WC_NID_info_access: return AUTH_INFO_OID; - case NID_authority_key_identifier: + case WC_NID_authority_key_identifier: return AUTH_KEY_OID; - case NID_subject_key_identifier: + case WC_NID_subject_key_identifier: return SUBJ_KEY_OID; - case NID_inhibit_any_policy: + case WC_NID_inhibit_any_policy: return INHIBIT_ANY_OID; - case NID_key_usage: + case WC_NID_key_usage: return KEY_USAGE_OID; - case NID_name_constraints: + case WC_NID_name_constraints: return NAME_CONS_OID; - case NID_certificate_policies: + case WC_NID_certificate_policies: return CERT_POLICY_OID; - case NID_ext_key_usage: + case WC_NID_ext_key_usage: return EXT_KEY_USAGE_OID; } break; @@ -22579,9 +23374,9 @@ word32 nid2oid(int nid, int grp) /* oidCertAuthInfoType */ case oidCertAuthInfoType: switch (nid) { - case NID_ad_OCSP: + case WC_NID_ad_OCSP: return AIA_OCSP_OID; - case NID_ad_ca_issuers: + case WC_NID_ad_ca_issuers: return AIA_CA_ISSUER_OID; } break; @@ -22589,7 +23384,7 @@ word32 nid2oid(int nid, int grp) /* oidCertPolicyType */ case oidCertPolicyType: switch (nid) { - case NID_any_policy: + case WC_NID_any_policy: return CP_ANY_OID; } break; @@ -22597,7 +23392,7 @@ word32 nid2oid(int nid, int grp) /* oidCertAltNameType */ case oidCertAltNameType: switch (nid) { - case NID_hw_name_oid: + case WC_NID_hw_name_oid: return HW_NAME_OID; } break; @@ -22605,7 +23400,7 @@ word32 nid2oid(int nid, int grp) /* oidCertKeyUseType */ case oidCertKeyUseType: switch (nid) { - case NID_anyExtendedKeyUsage: + case WC_NID_anyExtendedKeyUsage: return EKU_ANY_OID; case EKU_SERVER_AUTH_OID: return EKU_SERVER_AUTH_OID; @@ -22684,15 +23479,15 @@ word32 nid2oid(int nid, int grp) #ifdef WOLFSSL_CERT_REQ case oidCsrAttrType: switch (nid) { - case NID_pkcs9_contentType: + case WC_NID_pkcs9_contentType: return PKCS9_CONTENT_TYPE_OID; - case NID_pkcs9_challengePassword: + case WC_NID_pkcs9_challengePassword: return CHALLENGE_PASSWORD_OID; - case NID_serialNumber: + case WC_NID_serialNumber: return SERIAL_NUMBER_OID; - case NID_userId: + case WC_NID_userId: return USER_ID_OID; - case NID_surname: + case WC_NID_surname: return SURNAME_OID; } break; @@ -22718,29 +23513,29 @@ int oid2nid(word32 oid, int grp) switch (oid) { #ifdef WOLFSSL_MD2 case MD2h: - return NID_md2; + return WC_NID_md2; #endif #ifndef NO_MD5 case MD5h: - return NID_md5; + return WC_NID_md5; #endif #ifndef NO_SHA case SHAh: - return NID_sha1; + return WC_NID_sha1; #endif case SHA224h: - return NID_sha224; + return WC_NID_sha224; #ifndef NO_SHA256 case SHA256h: - return NID_sha256; + return WC_NID_sha256; #endif #ifdef WOLFSSL_SHA384 case SHA384h: - return NID_sha384; + return WC_NID_sha384; #endif #ifdef WOLFSSL_SHA512 case SHA512h: - return NID_sha512; + return WC_NID_sha512; #endif } break; @@ -22750,60 +23545,60 @@ int oid2nid(word32 oid, int grp) switch (oid) { #ifndef NO_DSA case CTC_SHAwDSA: - return NID_dsaWithSHA1; + return WC_NID_dsaWithSHA1; case CTC_SHA256wDSA: - return NID_dsa_with_SHA256; + return WC_NID_dsa_with_SHA256; #endif /* NO_DSA */ #ifndef NO_RSA case CTC_MD2wRSA: - return NID_md2WithRSAEncryption; + return WC_NID_md2WithRSAEncryption; case CTC_MD5wRSA: - return NID_md5WithRSAEncryption; + return WC_NID_md5WithRSAEncryption; case CTC_SHAwRSA: - return NID_sha1WithRSAEncryption; + return WC_NID_sha1WithRSAEncryption; case CTC_SHA224wRSA: - return NID_sha224WithRSAEncryption; + return WC_NID_sha224WithRSAEncryption; case CTC_SHA256wRSA: - return NID_sha256WithRSAEncryption; + return WC_NID_sha256WithRSAEncryption; case CTC_SHA384wRSA: - return NID_sha384WithRSAEncryption; + return WC_NID_sha384WithRSAEncryption; case CTC_SHA512wRSA: - return NID_sha512WithRSAEncryption; + return WC_NID_sha512WithRSAEncryption; #ifdef WOLFSSL_SHA3 case CTC_SHA3_224wRSA: - return NID_RSA_SHA3_224; + return WC_NID_RSA_SHA3_224; case CTC_SHA3_256wRSA: - return NID_RSA_SHA3_256; + return WC_NID_RSA_SHA3_256; case CTC_SHA3_384wRSA: - return NID_RSA_SHA3_384; + return WC_NID_RSA_SHA3_384; case CTC_SHA3_512wRSA: - return NID_RSA_SHA3_512; + return WC_NID_RSA_SHA3_512; #endif #ifdef WC_RSA_PSS case CTC_RSASSAPSS: - return NID_rsassaPss; + return WC_NID_rsassaPss; #endif #endif /* NO_RSA */ #ifdef HAVE_ECC case CTC_SHAwECDSA: - return NID_ecdsa_with_SHA1; + return WC_NID_ecdsa_with_SHA1; case CTC_SHA224wECDSA: - return NID_ecdsa_with_SHA224; + return WC_NID_ecdsa_with_SHA224; case CTC_SHA256wECDSA: - return NID_ecdsa_with_SHA256; + return WC_NID_ecdsa_with_SHA256; case CTC_SHA384wECDSA: - return NID_ecdsa_with_SHA384; + return WC_NID_ecdsa_with_SHA384; case CTC_SHA512wECDSA: - return NID_ecdsa_with_SHA512; + return WC_NID_ecdsa_with_SHA512; #ifdef WOLFSSL_SHA3 case CTC_SHA3_224wECDSA: - return NID_ecdsa_with_SHA3_224; + return WC_NID_ecdsa_with_SHA3_224; case CTC_SHA3_256wECDSA: - return NID_ecdsa_with_SHA3_256; + return WC_NID_ecdsa_with_SHA3_256; case CTC_SHA3_384wECDSA: - return NID_ecdsa_with_SHA3_384; + return WC_NID_ecdsa_with_SHA3_384; case CTC_SHA3_512wECDSA: - return NID_ecdsa_with_SHA3_512; + return WC_NID_ecdsa_with_SHA3_512; #endif #endif /* HAVE_ECC */ } @@ -22814,19 +23609,19 @@ int oid2nid(word32 oid, int grp) switch (oid) { #ifndef NO_DSA case DSAk: - return NID_dsa; + return WC_NID_dsa; #endif /* NO_DSA */ #ifndef NO_RSA case RSAk: - return NID_rsaEncryption; + return WC_NID_rsaEncryption; #ifdef WC_RSA_PSS case RSAPSSk: - return NID_rsassaPss; + return WC_NID_rsassaPss; #endif #endif /* NO_RSA */ #ifdef HAVE_ECC case ECDSAk: - return NID_X9_62_id_ecPublicKey; + return WC_NID_X9_62_id_ecPublicKey; #endif /* HAVE_ECC */ } break; @@ -22836,59 +23631,59 @@ int oid2nid(word32 oid, int grp) case oidCurveType: switch (oid) { case ECC_SECP192R1_OID: - return NID_X9_62_prime192v1; + return WC_NID_X9_62_prime192v1; case ECC_PRIME192V2_OID: - return NID_X9_62_prime192v2; + return WC_NID_X9_62_prime192v2; case ECC_PRIME192V3_OID: - return NID_X9_62_prime192v3; + return WC_NID_X9_62_prime192v3; case ECC_PRIME239V1_OID: - return NID_X9_62_prime239v1; + return WC_NID_X9_62_prime239v1; case ECC_PRIME239V2_OID: - return NID_X9_62_prime239v2; + return WC_NID_X9_62_prime239v2; case ECC_PRIME239V3_OID: - return NID_X9_62_prime239v3; + return WC_NID_X9_62_prime239v3; case ECC_SECP256R1_OID: - return NID_X9_62_prime256v1; + return WC_NID_X9_62_prime256v1; case ECC_SECP112R1_OID: - return NID_secp112r1; + return WC_NID_secp112r1; case ECC_SECP112R2_OID: - return NID_secp112r2; + return WC_NID_secp112r2; case ECC_SECP128R1_OID: - return NID_secp128r1; + return WC_NID_secp128r1; case ECC_SECP128R2_OID: - return NID_secp128r2; + return WC_NID_secp128r2; case ECC_SECP160R1_OID: - return NID_secp160r1; + return WC_NID_secp160r1; case ECC_SECP160R2_OID: - return NID_secp160r2; + return WC_NID_secp160r2; case ECC_SECP224R1_OID: - return NID_secp224r1; + return WC_NID_secp224r1; case ECC_SECP384R1_OID: - return NID_secp384r1; + return WC_NID_secp384r1; case ECC_SECP521R1_OID: - return NID_secp521r1; + return WC_NID_secp521r1; case ECC_SECP160K1_OID: - return NID_secp160k1; + return WC_NID_secp160k1; case ECC_SECP192K1_OID: - return NID_secp192k1; + return WC_NID_secp192k1; case ECC_SECP224K1_OID: - return NID_secp224k1; + return WC_NID_secp224k1; case ECC_SECP256K1_OID: - return NID_secp256k1; + return WC_NID_secp256k1; case ECC_BRAINPOOLP160R1_OID: - return NID_brainpoolP160r1; + return WC_NID_brainpoolP160r1; case ECC_BRAINPOOLP192R1_OID: - return NID_brainpoolP192r1; + return WC_NID_brainpoolP192r1; case ECC_BRAINPOOLP224R1_OID: - return NID_brainpoolP224r1; + return WC_NID_brainpoolP224r1; case ECC_BRAINPOOLP256R1_OID: - return NID_brainpoolP256r1; + return WC_NID_brainpoolP256r1; case ECC_BRAINPOOLP320R1_OID: - return NID_brainpoolP320r1; + return WC_NID_brainpoolP320r1; case ECC_BRAINPOOLP384R1_OID: - return NID_brainpoolP384r1; + return WC_NID_brainpoolP384r1; case ECC_BRAINPOOLP512R1_OID: - return NID_brainpoolP512r1; + return WC_NID_brainpoolP512r1; } break; #endif /* HAVE_ECC */ @@ -22910,9 +23705,9 @@ int oid2nid(word32 oid, int grp) #endif #ifndef NO_DES3 case DESb: - return NID_des; + return WC_NID_des; case DES3b: - return NID_des3; + return WC_NID_des3; #endif } break; @@ -22921,7 +23716,7 @@ int oid2nid(word32 oid, int grp) case oidOcspType: switch (oid) { case OCSP_BASIC_OID: - return NID_id_pkix_OCSP_basic; + return WC_NID_id_pkix_OCSP_basic; case OCSP_NONCE_OID: return OCSP_NONCE_OID; } @@ -22932,27 +23727,27 @@ int oid2nid(word32 oid, int grp) case oidCertExtType: switch (oid) { case BASIC_CA_OID: - return NID_basic_constraints; + return WC_NID_basic_constraints; case ALT_NAMES_OID: - return NID_subject_alt_name; + return WC_NID_subject_alt_name; case CRL_DIST_OID: - return NID_crl_distribution_points; + return WC_NID_crl_distribution_points; case AUTH_INFO_OID: - return NID_info_access; + return WC_NID_info_access; case AUTH_KEY_OID: - return NID_authority_key_identifier; + return WC_NID_authority_key_identifier; case SUBJ_KEY_OID: - return NID_subject_key_identifier; + return WC_NID_subject_key_identifier; case INHIBIT_ANY_OID: - return NID_inhibit_any_policy; + return WC_NID_inhibit_any_policy; case KEY_USAGE_OID: - return NID_key_usage; + return WC_NID_key_usage; case NAME_CONS_OID: - return NID_name_constraints; + return WC_NID_name_constraints; case CERT_POLICY_OID: - return NID_certificate_policies; + return WC_NID_certificate_policies; case EXT_KEY_USAGE_OID: - return NID_ext_key_usage; + return WC_NID_ext_key_usage; } break; @@ -22960,9 +23755,9 @@ int oid2nid(word32 oid, int grp) case oidCertAuthInfoType: switch (oid) { case AIA_OCSP_OID: - return NID_ad_OCSP; + return WC_NID_ad_OCSP; case AIA_CA_ISSUER_OID: - return NID_ad_ca_issuers; + return WC_NID_ad_ca_issuers; } break; @@ -22970,7 +23765,7 @@ int oid2nid(word32 oid, int grp) case oidCertPolicyType: switch (oid) { case CP_ANY_OID: - return NID_any_policy; + return WC_NID_any_policy; } break; @@ -22978,7 +23773,7 @@ int oid2nid(word32 oid, int grp) case oidCertAltNameType: switch (oid) { case HW_NAME_OID: - return NID_hw_name_oid; + return WC_NID_hw_name_oid; } break; @@ -22986,7 +23781,7 @@ int oid2nid(word32 oid, int grp) case oidCertKeyUseType: switch (oid) { case EKU_ANY_OID: - return NID_anyExtendedKeyUsage; + return WC_NID_anyExtendedKeyUsage; case EKU_SERVER_AUTH_OID: return EKU_SERVER_AUTH_OID; case EKU_CLIENT_AUTH_OID: @@ -23064,13 +23859,13 @@ int oid2nid(word32 oid, int grp) case oidCsrAttrType: switch (oid) { case PKCS9_CONTENT_TYPE_OID: - return NID_pkcs9_contentType; + return WC_NID_pkcs9_contentType; case CHALLENGE_PASSWORD_OID: - return NID_pkcs9_challengePassword; + return WC_NID_pkcs9_challengePassword; case SERIAL_NUMBER_OID: - return NID_serialNumber; + return WC_NID_serialNumber; case USER_ID_OID: - return NID_userId; + return WC_NID_userId; } break; #endif @@ -23230,9 +24025,9 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, int type; /* ECC includes version, private[, curve][, public key] */ if (cnt >= 2 && cnt <= 4) - type = EVP_PKEY_EC; + type = WC_EVP_PKEY_EC; else - type = EVP_PKEY_RSA; + type = WC_EVP_PKEY_RSA; key = wolfSSL_d2i_PrivateKey(type, pkey, &der, keyLen); *pp = der; @@ -23692,8 +24487,12 @@ int wolfSSL_CTX_set_dh_auto(WOLFSSL_CTX* ctx, int onoff) } /** - * set security level (wolfSSL doesn't support security level) - * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure + * Set security level (wolfSSL doesn't support setting the security level). + * + * The security level can only be set through a system wide crypto-policy + * with wolfSSL_crypto_policy_enable(). + * + * @param ctx a pointer to WOLFSSL_CTX structure * @param level security level */ void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level) @@ -23702,16 +24501,20 @@ void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level) (void)ctx; (void)level; } -/** - * get security level (wolfSSL doesn't support security level) - * @param ctx a pointer to WOLFSSL_EVP_PKEY_CTX structure - * @return always 0(level 0) - */ -int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX* ctx) + +int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx) { WOLFSSL_ENTER("wolfSSL_CTX_get_security_level"); + #if defined(WOLFSSL_SYS_CRYPTO_POLICY) + if (ctx == NULL) { + return BAD_FUNC_ARG; + } + + return ctx->secLevel; + #else (void)ctx; return 0; + #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ } #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK) @@ -23885,21 +24688,17 @@ void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line) /******************************************************************************* * START OF EX_DATA APIs ******************************************************************************/ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ - (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_OPENSSH))) -void wolfSSL_CRYPTO_cleanup_all_ex_data(void){ - WOLFSSL_ENTER("CRYPTO_cleanup_all_ex_data"); +#ifdef HAVE_EX_DATA +void wolfSSL_CRYPTO_cleanup_all_ex_data(void) +{ + WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data"); } -#endif -#ifdef HAVE_EX_DATA void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx) { - WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data"); + WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data"); #ifdef MAX_EX_DATA - if(ex_data && idx < MAX_EX_DATA && idx >= 0) { + if (ex_data && idx < MAX_EX_DATA && idx >= 0) { return ex_data->ex_data[idx]; } #else @@ -23917,6 +24716,8 @@ int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, if (ex_data && idx < MAX_EX_DATA && idx >= 0) { #ifdef HAVE_EX_DATA_CLEANUP_HOOKS if (ex_data->ex_data_cleanup_routines[idx]) { + /* call cleanup then remove cleanup callback, + * since different value is being set */ if (ex_data->ex_data[idx]) ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]); ex_data->ex_data_cleanup_routines[idx] = NULL; @@ -23951,7 +24752,9 @@ int wolfSSL_CRYPTO_set_ex_data_with_cleanup( return WOLFSSL_FAILURE; } #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ +#endif /* HAVE_EX_DATA */ +#ifdef HAVE_EX_DATA_CRYPTO /** * Issues unique index for the class specified by class_index. * Other parameter except class_index are ignored. @@ -23977,7 +24780,7 @@ int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, return wolfssl_get_ex_new_index(class_index, argl, argp, new_func, dup_func, free_func); } -#endif /* HAVE_EX_DATA */ +#endif /* HAVE_EX_DATA_CRYPTO */ /******************************************************************************* * END OF EX_DATA APIs @@ -24801,150 +25604,150 @@ int wolfSSL_RAND_load_file(const char* fname, long len) switch (ctx->cipherType) { #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); break; #endif #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); break; #endif /* HAVE_AESGCM */ #ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : + case WC_AES_128_CCM_TYPE : + case WC_AES_192_CCM_TYPE : + case WC_AES_256_CCM_TYPE : WOLFSSL_MSG("AES CCM"); XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz); break; #endif /* HAVE_AESCCM */ #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : + case WC_AES_128_ECB_TYPE : + case WC_AES_192_ECB_TYPE : + case WC_AES_256_ECB_TYPE : WOLFSSL_MSG("AES ECB"); break; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); - XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); + XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE); break; #endif /* WOLFSSL_AES_COUNTER */ #ifdef WOLFSSL_AES_CFB #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: WOLFSSL_MSG("AES CFB1"); break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: WOLFSSL_MSG("AES CFB8"); break; #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: WOLFSSL_MSG("AES CFB128"); break; #endif /* WOLFSSL_AES_CFB */ #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: WOLFSSL_MSG("AES OFB"); break; #endif /* WOLFSSL_AES_OFB */ #ifdef WOLFSSL_AES_XTS - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: WOLFSSL_MSG("AES XTS"); break; #endif /* WOLFSSL_AES_XTS */ #endif /* NO_AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE); break; #endif /* HAVE_ARIA */ #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE); break; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES EDE3 CBC"); XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : + case WC_DES_ECB_TYPE : WOLFSSL_MSG("DES ECB"); break; - case DES_EDE3_ECB_TYPE : + case WC_DES_EDE3_ECB_TYPE : WOLFSSL_MSG("DES3 ECB"); break; #endif - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: break; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: break; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: break; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: WOLFSSL_MSG("SM4 CBC"); XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: WOLFSSL_MSG("SM4 CTR"); XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: WOLFSSL_MSG("SM4 GCM"); XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: WOLFSSL_MSG("SM4 CCM"); XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE); break; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL"); break; @@ -24971,112 +25774,112 @@ int wolfSSL_RAND_load_file(const char* fname, long len) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE); break; #endif #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE); break; #endif #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : + case WC_AES_128_ECB_TYPE : + case WC_AES_192_ECB_TYPE : + case WC_AES_256_ECB_TYPE : WOLFSSL_MSG("AES ECB"); break; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); - XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, AES_BLOCK_SIZE); + XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE); break; #endif #endif /* NO_AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE); break; #endif /* HAVE_ARIA */ #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE); break; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES EDE3 CBC"); XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : + case WC_DES_ECB_TYPE : WOLFSSL_MSG("DES ECB"); break; - case DES_EDE3_ECB_TYPE : + case WC_DES_EDE3_ECB_TYPE : WOLFSSL_MSG("DES3 ECB"); break; #endif - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: break; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: break; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: break; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: WOLFSSL_MSG("SM4 CBC"); XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); break; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: WOLFSSL_MSG("SM4 CTR"); XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: WOLFSSL_MSG("SM4 GCM"); XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: WOLFSSL_MSG("SM4 CCM"); XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz); break; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL"); break; @@ -25128,7 +25931,7 @@ void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset, if (doset) (void)wc_AesSetIV(&ctx->cipher.aes, iv); /* OpenSSL compat, no ret */ else - XMEMCPY(iv, &ctx->cipher.aes.reg, AES_BLOCK_SIZE); + XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE); } #endif /* NO_AES */ diff --git a/src/src/ssl_asn1.c b/src/src/ssl_asn1.c index 95f9cca..5ebad81 100644 --- a/src/src/ssl_asn1.c +++ b/src/src/ssl_asn1.c @@ -282,10 +282,12 @@ static int wolfssl_i2d_asn1_items(const void* obj, byte* buf, len = 0; break; } + if (buf != NULL && tmp != NULL && !mem->ex && mem->tag >= 0) { - /* Encode the implicit tag */ byte imp[ASN_TAG_SZ + MAX_LENGTH_SZ]; - SetImplicit(tmp[0], mem->tag, 0, imp, 0); + /* Encode the implicit tag; There's other stuff in the upper bits + * of the integer tag, so strip out everything else for value. */ + SetImplicit(tmp[0], (byte)(mem->tag), 0, imp, 0); tmp[0] = imp[0]; } len += ret; @@ -456,7 +458,7 @@ static void* d2i_obj(const WOLFSSL_ASN1_TEMPLATE* mem, const byte** src, mem->free_func(ret); /* never a stack so we can call this directly */ return NULL; } - *len -= (tmp - *src); + *len -= (long)(tmp - *src); *src = tmp; return ret; } @@ -586,7 +588,7 @@ static void* d2i_generic(const WOLFSSL_ASN1_TEMPLATE* mem, WOLFSSL_MSG("ptr not advanced enough"); goto error; } - *len -= tmp - *src; + *len -= (long)(tmp - *src); *src = tmp; return ret; error: @@ -1019,7 +1021,7 @@ static void wolfssl_asn1_integer_reset_data(WOLFSSL_ASN1_INTEGER* a) /* No data, not negative. */ a->negative = 0; /* Set type to positive INTEGER. */ - a->type = V_ASN1_INTEGER; + a->type = WOLFSSL_V_ASN1_INTEGER; } #endif /* OPENSSL_EXTRA */ @@ -1318,7 +1320,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER** a, } if (!err) { /* Set type. */ - ret->type = V_ASN1_INTEGER; + ret->type = WOLFSSL_V_ASN1_INTEGER; /* Copy DER encoding and length. */ XMEMCPY(ret->data, *in, (size_t)(idx + (word32)len)); @@ -1331,7 +1333,7 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_d2i_ASN1_INTEGER(WOLFSSL_ASN1_INTEGER** a, } if ((!err) && ret->negative) { /* Update type if number was negative. */ - ret->type |= V_ASN1_NEG_INTEGER; + ret->type |= WOLFSSL_V_ASN1_NEG_INTEGER; } if (err) { @@ -1490,7 +1492,7 @@ int wolfSSL_a2i_ASN1_INTEGER(WOLFSSL_BIO *bio, WOLFSSL_ASN1_INTEGER *asn1, * @return 0 when bp or a is NULL. * @return 0 DER header in data is invalid. */ -int wolfSSL_i2a_ASN1_INTEGER(BIO *bp, const WOLFSSL_ASN1_INTEGER *a) +int wolfSSL_i2a_ASN1_INTEGER(WOLFSSL_BIO *bp, const WOLFSSL_ASN1_INTEGER *a) { int err = 0; word32 idx = 1; /* Skip ASN.1 INTEGER tag byte. */ @@ -1751,10 +1753,10 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_BN_to_ASN1_INTEGER(const WOLFSSL_BIGNUM *bn, int length; /* Set type and negative. */ - a->type = V_ASN1_INTEGER; + a->type = WOLFSSL_V_ASN1_INTEGER; if (wolfSSL_BN_is_negative(bn) && !wolfSSL_BN_is_zero(bn)) { a->negative = 1; - a->type |= V_ASN1_NEG_INTEGER; + a->type |= WOLFSSL_V_ASN1_NEG_INTEGER; } /* Get length in bytes of encoded number. */ @@ -1883,7 +1885,7 @@ int wolfSSL_ASN1_INTEGER_set(WOLFSSL_ASN1_INTEGER *a, long v) if (v < 0) { /* Set negative and 2's complement the value. */ a->negative = 1; - a->type |= V_ASN1_NEG; + a->type |= WOLFSSL_V_ASN1_NEG; v = -v; } @@ -2345,7 +2347,7 @@ int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a) length = wolfSSL_BIO_write(bp, null_str, (int)XSTRLEN(null_str)); } /* Try getting text version and write it out. */ - else if ((length = i2t_ASN1_OBJECT(buf, sizeof(buf), a)) > 0) { + else if ((length = wolfSSL_i2t_ASN1_OBJECT(buf, sizeof(buf), a)) > 0) { length = wolfSSL_BIO_write(bp, buf, length); } /* Look for DER header. */ @@ -2651,7 +2653,7 @@ int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s) } /* Check type of ASN.1 STRING. */ - if ((ret == 1) && (s->type != V_ASN1_UNIVERSALSTRING)) { + if ((ret == 1) && (s->type != WOLFSSL_V_ASN1_UNIVERSALSTRING)) { WOLFSSL_MSG("Input is not a universal string"); ret = 0; } @@ -2685,7 +2687,7 @@ int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s) *copy = '\0'; /* Update length and type. */ s->length /= 4; - s->type = V_ASN1_PRINTABLESTRING; + s->type = WOLFSSL_V_ASN1_PRINTABLESTRING; } return ret; @@ -2912,7 +2914,7 @@ static WOLFSSL_ASN1_STRING* d2i_ASN1_STRING(WOLFSSL_ASN1_STRING** out, byte tag = 0; int length = 0; - WOLFSSL_ENTER("d2i_ASN1_GENERALSTRING"); + WOLFSSL_ENTER("d2i_ASN1_STRING"); if (src == NULL || *src == NULL || len == 0) return NULL; @@ -3207,10 +3209,10 @@ int wolfSSL_ASN1_STRING_canon(WOLFSSL_ASN1_STRING* asn_out, if (ret == 1) { switch (asn_in->type) { - case MBSTRING_UTF8: - case V_ASN1_PRINTABLESTRING: + case WOLFSSL_MBSTRING_UTF8: + case WOLFSSL_V_ASN1_PRINTABLESTRING: /* Set type to UTF8. */ - asn_out->type = MBSTRING_UTF8; + asn_out->type = WOLFSSL_MBSTRING_UTF8; /* Dispose of any dynamic data already in asn_out. */ if (asn_out->isDynamic) { XFREE(asn_out->data, NULL, DYNAMIC_TYPE_OPENSSL); @@ -3327,8 +3329,8 @@ const char* wolfSSL_ASN1_tag2str(int tag) const char* str = "(unknown)"; /* Clear negative flag. */ - if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED)) { - tag &= ~V_ASN1_NEG; + if ((tag == WOLFSSL_V_ASN1_NEG_INTEGER) || (tag == WOLFSSL_V_ASN1_NEG_ENUMERATED)) { + tag &= ~WOLFSSL_V_ASN1_NEG; } /* Check for known basic types. */ if ((tag >= 0) && (tag <= 30)) { @@ -3514,7 +3516,7 @@ int wolfSSL_ASN1_STRING_print_ex(WOLFSSL_BIO *bio, WOLFSSL_ASN1_STRING *str, err = 1; } /* Check if ASN.1 type is to be printed. */ - if ((!err) && (flags & ASN1_STRFLGS_SHOW_TYPE)) { + if ((!err) && (flags & WOLFSSL_ASN1_STRFLGS_SHOW_TYPE)) { /* Print type and colon to BIO. */ type_len = wolfssl_string_print_type(bio, str); if (type_len == 0) { @@ -3523,12 +3525,12 @@ int wolfSSL_ASN1_STRING_print_ex(WOLFSSL_BIO *bio, WOLFSSL_ASN1_STRING *str, } if (!err) { - if (flags & ASN1_STRFLGS_DUMP_ALL) { + if (flags & WOLFSSL_ASN1_STRFLGS_DUMP_ALL) { /* Dump hex. */ str_len = wolfssl_asn1_string_dump_hex(bio, str, - flags & ASN1_STRFLGS_DUMP_DER); + flags & WOLFSSL_ASN1_STRFLGS_DUMP_DER); } - else if (flags & ASN1_STRFLGS_ESC_2253) { + else if (flags & WOLFSSL_ASN1_STRFLGS_ESC_2253) { /* Print out string with escaping. */ str_len = wolfssl_asn1_string_print_esc_2253(bio, str); } @@ -3621,7 +3623,7 @@ int wolfSSL_ASN1_GENERALIZEDTIME_print(WOLFSSL_BIO* bio, ret = BAD_FUNC_ARG; } /* Check type is GENERALIZED TIME. */ - if ((ret == 1) && (asnTime->type != V_ASN1_GENERALIZEDTIME)) { + if ((ret == 1) && (asnTime->type != WOLFSSL_V_ASN1_GENERALIZEDTIME)) { WOLFSSL_MSG("Error, not GENERALIZED_TIME"); ret = 0; } @@ -4036,8 +4038,8 @@ int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *t, const char *str) /* Do not include NUL terminator in length. */ t->length = slen - 1; /* Set ASN.1 type based on string length. */ - t->type = ((slen == ASN_UTC_TIME_SIZE) ? V_ASN1_UTCTIME : - V_ASN1_GENERALIZEDTIME); + t->type = ((slen == ASN_UTC_TIME_SIZE) ? WOLFSSL_V_ASN1_UTCTIME : + WOLFSSL_V_ASN1_GENERALIZEDTIME); } return ret; @@ -4078,8 +4080,8 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, WOLFSSL_MSG("Invalid ASN_TIME value"); } /* Ensure ASN.1 type is one that is supported. */ - else if ((t->type != V_ASN1_UTCTIME) && - (t->type != V_ASN1_GENERALIZEDTIME)) { + else if ((t->type != WOLFSSL_V_ASN1_UTCTIME) && + (t->type != WOLFSSL_V_ASN1_GENERALIZEDTIME)) { WOLFSSL_MSG("Invalid ASN_TIME type."); } /* Check for ASN.1 GENERALIZED TIME object being passed in. */ @@ -4097,9 +4099,9 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_TIME_to_generalizedtime(WOLFSSL_ASN1_TIME *t, if (ret != NULL) { /* Set the ASN.1 type and length of string. */ - ret->type = V_ASN1_GENERALIZEDTIME; + ret->type = WOLFSSL_V_ASN1_GENERALIZEDTIME; - if (t->type == V_ASN1_GENERALIZEDTIME) { + if (t->type == WOLFSSL_V_ASN1_GENERALIZEDTIME) { ret->length = ASN_GENERALIZED_TIME_SIZE; /* Just copy as data already appropriately formatted. */ @@ -4151,7 +4153,7 @@ WOLFSSL_ASN1_TIME* wolfSSL_ASN1_UTCTIME_set(WOLFSSL_ASN1_TIME *s, time_t t) ret = NULL; } else { - ret->type = V_ASN1_UTCTIME; + ret->type = WOLFSSL_V_ASN1_UTCTIME; } return ret; @@ -4311,7 +4313,7 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, /* Zero out values in broken-down time. */ XMEMSET(tm, 0, sizeof(struct tm)); - if (asnTime->type == V_ASN1_UTCTIME) { + if (asnTime->type == WOLFSSL_V_ASN1_UTCTIME) { /* Get year from UTC TIME string. */ int tm_year; if ((ret = wolfssl_utctime_year(asn1TimeBuf, asn1TimeBufLen, @@ -4321,7 +4323,7 @@ static int wolfssl_asn1_time_to_tm(const WOLFSSL_ASN1_TIME* asnTime, i = 2; } } - else if (asnTime->type == V_ASN1_GENERALIZEDTIME) { + else if (asnTime->type == WOLFSSL_V_ASN1_GENERALIZEDTIME) { /* Get year from GENERALIZED TIME string. */ int tm_year; if ((ret = wolfssl_gentime_year(asn1TimeBuf, asn1TimeBufLen, @@ -4522,7 +4524,7 @@ int wolfSSL_ASN1_UTCTIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_UTCTIME* a) ret = 0; } /* Validate ASN.1 UTC TIME object is of type UTC_TIME. */ - if ((ret == 1) && (a->type != V_ASN1_UTCTIME)) { + if ((ret == 1) && (a->type != WOLFSSL_V_ASN1_UTCTIME)) { WOLFSSL_MSG("Error, not UTC_TIME"); ret = 0; } @@ -4574,28 +4576,28 @@ WOLFSSL_ASN1_TYPE* wolfSSL_ASN1_TYPE_new(void) static void wolfssl_asn1_type_free_value(WOLFSSL_ASN1_TYPE* at) { switch (at->type) { - case V_ASN1_NULL: + case WOLFSSL_V_ASN1_NULL: break; - case V_ASN1_OBJECT: + case WOLFSSL_V_ASN1_OBJECT: wolfSSL_ASN1_OBJECT_free(at->value.object); break; - case V_ASN1_UTCTIME: + case WOLFSSL_V_ASN1_UTCTIME: #if !defined(NO_ASN_TIME) && defined(OPENSSL_EXTRA) wolfSSL_ASN1_TIME_free(at->value.utctime); #endif break; - case V_ASN1_GENERALIZEDTIME: + case WOLFSSL_V_ASN1_GENERALIZEDTIME: #if !defined(NO_ASN_TIME) && defined(OPENSSL_EXTRA) wolfSSL_ASN1_TIME_free(at->value.generalizedtime); #endif break; - case V_ASN1_UTF8STRING: - case V_ASN1_OCTET_STRING: - case V_ASN1_PRINTABLESTRING: - case V_ASN1_T61STRING: - case V_ASN1_IA5STRING: - case V_ASN1_UNIVERSALSTRING: - case V_ASN1_SEQUENCE: + case WOLFSSL_V_ASN1_UTF8STRING: + case WOLFSSL_V_ASN1_OCTET_STRING: + case WOLFSSL_V_ASN1_PRINTABLESTRING: + case WOLFSSL_V_ASN1_T61STRING: + case WOLFSSL_V_ASN1_IA5STRING: + case WOLFSSL_V_ASN1_UNIVERSALSTRING: + case WOLFSSL_V_ASN1_SEQUENCE: wolfSSL_ASN1_STRING_free(at->value.asn1_string); break; default: @@ -4626,25 +4628,25 @@ int wolfSSL_i2d_ASN1_TYPE(WOLFSSL_ASN1_TYPE* at, unsigned char** pp) return WOLFSSL_FATAL_ERROR; switch (at->type) { - case V_ASN1_NULL: + case WOLFSSL_V_ASN1_NULL: break; - case V_ASN1_OBJECT: + case WOLFSSL_V_ASN1_OBJECT: ret = wolfSSL_i2d_ASN1_OBJECT(at->value.object, pp); break; - case V_ASN1_UTF8STRING: + case WOLFSSL_V_ASN1_UTF8STRING: ret = wolfSSL_i2d_ASN1_UTF8STRING(at->value.utf8string, pp); break; - case V_ASN1_GENERALIZEDTIME: + case WOLFSSL_V_ASN1_GENERALIZEDTIME: ret = wolfSSL_i2d_ASN1_GENERALSTRING(at->value.utf8string, pp); break; - case V_ASN1_SEQUENCE: + case WOLFSSL_V_ASN1_SEQUENCE: ret = wolfSSL_i2d_ASN1_SEQUENCE(at->value.sequence, pp); break; - case V_ASN1_UTCTIME: - case V_ASN1_PRINTABLESTRING: - case V_ASN1_T61STRING: - case V_ASN1_IA5STRING: - case V_ASN1_UNIVERSALSTRING: + case WOLFSSL_V_ASN1_UTCTIME: + case WOLFSSL_V_ASN1_PRINTABLESTRING: + case WOLFSSL_V_ASN1_T61STRING: + case WOLFSSL_V_ASN1_IA5STRING: + case WOLFSSL_V_ASN1_UNIVERSALSTRING: default: WOLFSSL_MSG("asn1 i2d type not supported"); break; @@ -4661,16 +4663,16 @@ int wolfSSL_i2d_ASN1_TYPE(WOLFSSL_ASN1_TYPE* at, unsigned char** pp) * Set ASN.1 TYPE object with a type and value. * * Type of value for different types: - * V_ASN1_NULL : Value should be NULL. - * V_ASN1_OBJECT : WOLFSSL_ASN1_OBJECT. - * V_ASN1_UTCTIME : WOLFSSL_ASN1_TIME. - * V_ASN1_GENERALIZEDTIME : WOLFSSL_ASN1_TIME. - * V_ASN1_UTF8STRING : WOLFSSL_ASN1_STRING. - * V_ASN1_PRINTABLESTRING : WOLFSSL_ASN1_STRING. - * V_ASN1_T61STRING : WOLFSSL_ASN1_STRING. - * V_ASN1_IA5STRING : WOLFSSL_ASN1_STRING. - * V_ASN1_UNINVERSALSTRING: WOLFSSL_ASN1_STRING. - * V_ASN1_SEQUENCE : WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_NULL : Value should be NULL. + * WOLFSSL_V_ASN1_OBJECT : WOLFSSL_ASN1_OBJECT. + * WOLFSSL_V_ASN1_UTCTIME : WOLFSSL_ASN1_TIME. + * WOLFSSL_V_ASN1_GENERALIZEDTIME : WOLFSSL_ASN1_TIME. + * WOLFSSL_V_ASN1_UTF8STRING : WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_PRINTABLESTRING : WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_T61STRING : WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_IA5STRING : WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_UNINVERSALSTRING: WOLFSSL_ASN1_STRING. + * WOLFSSL_V_ASN1_SEQUENCE : WOLFSSL_ASN1_STRING. * * @param [in, out] a ASN.1 TYPE object to set. * @param [in] type ASN.1 type of value. @@ -4680,22 +4682,22 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) { if (a != NULL) { switch (type) { - case V_ASN1_NULL: + case WOLFSSL_V_ASN1_NULL: if (value != NULL) { WOLFSSL_MSG("NULL tag meant to be always empty!"); /* No way to return error - value will not be used. */ } FALL_THROUGH; - case V_ASN1_OBJECT: - case V_ASN1_UTCTIME: - case V_ASN1_GENERALIZEDTIME: - case V_ASN1_UTF8STRING: - case V_ASN1_OCTET_STRING: - case V_ASN1_PRINTABLESTRING: - case V_ASN1_T61STRING: - case V_ASN1_IA5STRING: - case V_ASN1_UNIVERSALSTRING: - case V_ASN1_SEQUENCE: + case WOLFSSL_V_ASN1_OBJECT: + case WOLFSSL_V_ASN1_UTCTIME: + case WOLFSSL_V_ASN1_GENERALIZEDTIME: + case WOLFSSL_V_ASN1_UTF8STRING: + case WOLFSSL_V_ASN1_OCTET_STRING: + case WOLFSSL_V_ASN1_PRINTABLESTRING: + case WOLFSSL_V_ASN1_T61STRING: + case WOLFSSL_V_ASN1_IA5STRING: + case WOLFSSL_V_ASN1_UNIVERSALSTRING: + case WOLFSSL_V_ASN1_SEQUENCE: /* Dispose of any value currently set. */ wolfssl_asn1_type_free_value(a); /* Assign anonymously typed input to anonymously typed field. */ @@ -4712,7 +4714,7 @@ void wolfSSL_ASN1_TYPE_set(WOLFSSL_ASN1_TYPE *a, int type, void *value) int wolfSSL_ASN1_TYPE_get(const WOLFSSL_ASN1_TYPE *a) { - if (a != NULL && (a->type == V_ASN1_BOOLEAN || a->type == V_ASN1_NULL + if (a != NULL && (a->type == WOLFSSL_V_ASN1_BOOLEAN || a->type == WOLFSSL_V_ASN1_NULL || a->value.ptr != NULL)) return a->type; return 0; diff --git a/src/src/ssl_bn.c b/src/src/ssl_bn.c index 227fc71..1c05b14 100644 --- a/src/src/ssl_bn.c +++ b/src/src/ssl_bn.c @@ -166,7 +166,7 @@ int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi) /* Dispose of any allocated big number on error. */ if ((ret == -1) && (a != NULL)) { - BN_free(a); + wolfSSL_BN_free(a); *bn = NULL; } return ret; diff --git a/src/src/ssl_certman.c b/src/src/ssl_certman.c index 346904e..6d18db5 100644 --- a/src/src/ssl_certman.c +++ b/src/src/ssl_certman.c @@ -44,6 +44,7 @@ */ static WC_INLINE WOLFSSL_METHOD* cm_pick_method(void* heap) { + (void)heap; #ifndef NO_WOLFSSL_CLIENT #if !defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_SSLV3) return wolfSSLv3_client_method_ex(heap); @@ -624,7 +625,7 @@ void wolfSSL_CertManagerSetVerify(WOLFSSL_CERT_MANAGER* cm, VerifyCallback vc) cm->verifyCallback = vc; } } -#endif /* NO_WOLFSSL_CM_VERIFY */ +#endif /* !NO_WOLFSSL_CM_VERIFY */ #ifdef WC_ASN_UNKNOWN_EXT_CB void wolfSSL_CertManagerSetUnknownExtCallback(WOLFSSL_CERT_MANAGER* cm, @@ -1895,6 +1896,41 @@ int wolfSSL_CertManagerSetCRL_ErrorCb(WOLFSSL_CERT_MANAGER* cm, crlErrorCb cb, return ret; } +#ifdef HAVE_CRL_UPDATE_CB +int wolfSSL_CertManagerGetCRLInfo(WOLFSSL_CERT_MANAGER* cm, CrlInfo* info, + const byte* buff, long sz, int type) +{ + return GetCRLInfo(cm->crl, info, buff, sz, type); +} + +/* Set the callback to be called when a CRL entry has + * been updated (new entry had the same issuer hash and + * a newer CRL number). + * + * @param [in] cm Certificate manager. + * @param [in] cb CRL update callback. + * @return WOLFSSL_SUCCESS on success. + * @return BAD_FUNC_ARG when cm is NULL. + */ +int wolfSSL_CertManagerSetCRLUpdate_Cb(WOLFSSL_CERT_MANAGER* cm, CbUpdateCRL cb) +{ + int ret = WOLFSSL_SUCCESS; + + WOLFSSL_ENTER("wolfSSL_CertManagerSetCRLUpdate_Cb"); + + /* Validate parameters. */ + if (cm == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == WOLFSSL_SUCCESS) { + /* Store callback. */ + cm->cbUpdateCRL = cb; + } + + return ret; +} +#endif + #ifdef HAVE_CRL_IO /* Set the CRL I/O callback. * diff --git a/src/src/ssl_crypto.c b/src/src/ssl_crypto.c index 0730c45..f2ff781 100644 --- a/src/src/ssl_crypto.c +++ b/src/src/ssl_crypto.c @@ -45,12 +45,12 @@ void wolfSSL_MD4_Init(WOLFSSL_MD4_CTX* md4) { /* Ensure WOLFSSL_MD4_CTX is big enough for wolfCrypt Md4. */ - WOLFSSL_ASSERT_SIZEOF_GE(md4->buffer, Md4); + WOLFSSL_ASSERT_SIZEOF_GE(md4->buffer, wc_Md4); WOLFSSL_ENTER("MD4_Init"); /* Initialize wolfCrypt MD4 object. */ - wc_InitMd4((Md4*)md4); + wc_InitMd4((wc_Md4*)md4); } /* Update MD4 hash with data. @@ -65,7 +65,7 @@ void wolfSSL_MD4_Update(WOLFSSL_MD4_CTX* md4, const void* data, WOLFSSL_ENTER("MD4_Update"); /* Update wolfCrypt MD4 object with data. */ - wc_Md4Update((Md4*)md4, (const byte*)data, (word32)len); + wc_Md4Update((wc_Md4*)md4, (const byte*)data, (word32)len); } /* Finalize MD4 hash and return output. @@ -79,7 +79,7 @@ void wolfSSL_MD4_Final(unsigned char* digest, WOLFSSL_MD4_CTX* md4) WOLFSSL_ENTER("MD4_Final"); /* Finalize wolfCrypt MD4 hash into digest. */ - wc_Md4Final((Md4*)md4, digest); + wc_Md4Final((wc_Md4*)md4, digest); } #endif /* NO_MD4 */ @@ -293,7 +293,7 @@ int wolfSSL_SHA1_Init(WOLFSSL_SHA_CTX* sha) { WOLFSSL_ENTER("SHA1_Init"); - return SHA_Init(sha); + return wolfSSL_SHA_Init(sha); } @@ -310,7 +310,7 @@ int wolfSSL_SHA1_Update(WOLFSSL_SHA_CTX* sha, const void* input, { WOLFSSL_ENTER("SHA1_Update"); - return SHA_Update(sha, input, sz); + return wolfSSL_SHA_Update(sha, input, sz); } /* Finalize SHA-1 hash and return output. @@ -325,7 +325,7 @@ int wolfSSL_SHA1_Final(byte* output, WOLFSSL_SHA_CTX* sha) { WOLFSSL_ENTER("SHA1_Final"); - return SHA_Final(output, sha); + return wolfSSL_SHA_Final(output, sha); } #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \ @@ -359,7 +359,7 @@ int wolfSSL_SHA1_Transform(WOLFSSL_SHA_CTX* sha, const unsigned char* data) int wolfSSL_SHA224_Init(WOLFSSL_SHA224_CTX* sha224) { /* Ensure WOLFSSL_SHA224_CTX is big enough for wolfCrypt wc_Sha224. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA224_CTX, wc_Sha224); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA224_CTX, wc_Sha224); WOLFSSL_ENTER("SHA224_Init"); @@ -418,7 +418,7 @@ int wolfSSL_SHA224_Final(byte* output, WOLFSSL_SHA224_CTX* sha224) int wolfSSL_SHA256_Init(WOLFSSL_SHA256_CTX* sha256) { /* Ensure WOLFSSL_SHA256_CTX is big enough for wolfCrypt wc_Sha256. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA256_CTX, wc_Sha256); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA256_CTX, wc_Sha256); WOLFSSL_ENTER("SHA256_Init"); @@ -507,7 +507,7 @@ int wolfSSL_SHA256_Transform(WOLFSSL_SHA256_CTX* sha256, int wolfSSL_SHA384_Init(WOLFSSL_SHA384_CTX* sha384) { /* Ensure WOLFSSL_SHA384_CTX is big enough for wolfCrypt wc_Sha384. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA384_CTX, wc_Sha384); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA384_CTX, wc_Sha384); WOLFSSL_ENTER("SHA384_Init"); @@ -566,7 +566,7 @@ int wolfSSL_SHA384_Final(byte* output, WOLFSSL_SHA384_CTX* sha384) int wolfSSL_SHA512_Init(WOLFSSL_SHA512_CTX* sha512) { /* Ensure WOLFSSL_SHA512_CTX is big enough for wolfCrypt wc_Sha512. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA512_CTX, wc_Sha512); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA512_CTX, wc_Sha512); WOLFSSL_ENTER("SHA512_Init"); @@ -802,7 +802,7 @@ int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512, int wolfSSL_SHA3_224_Init(WOLFSSL_SHA3_224_CTX* sha3_224) { /* Ensure WOLFSSL_SHA3_224_CTX is big enough for wolfCrypt wc_Sha3. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA3_224_CTX, wc_Sha3); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_224_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_224_Init"); @@ -861,7 +861,7 @@ int wolfSSL_SHA3_224_Final(byte* output, WOLFSSL_SHA3_224_CTX* sha3) int wolfSSL_SHA3_256_Init(WOLFSSL_SHA3_256_CTX* sha3_256) { /* Ensure WOLFSSL_SHA3_256_CTX is big enough for wolfCrypt wc_Sha3. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA3_256_CTX, wc_Sha3); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_256_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_256_Init"); @@ -920,7 +920,7 @@ int wolfSSL_SHA3_256_Final(byte* output, WOLFSSL_SHA3_256_CTX* sha3) int wolfSSL_SHA3_384_Init(WOLFSSL_SHA3_384_CTX* sha3_384) { /* Ensure WOLFSSL_SHA3_384_CTX is big enough for wolfCrypt wc_Sha3. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA3_384_CTX, wc_Sha3); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_384_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_384_Init"); @@ -979,7 +979,7 @@ int wolfSSL_SHA3_384_Final(byte* output, WOLFSSL_SHA3_384_CTX* sha3) int wolfSSL_SHA3_512_Init(WOLFSSL_SHA3_512_CTX* sha3_512) { /* Ensure WOLFSSL_SHA3_512_CTX is big enough for wolfCrypt wc_Sha3. */ - WOLFSSL_ASSERT_SIZEOF_GE(SHA3_512_CTX, wc_Sha3); + WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_512_CTX, wc_Sha3); WOLFSSL_ENTER("SHA3_512_Init"); @@ -1722,7 +1722,7 @@ const WOLFSSL_EVP_MD* wolfSSL_HMAC_CTX_get_md(const WOLFSSL_HMAC_CTX* ctx) * @return 0 on failure. */ int wolfSSL_HMAC_Init_ex(WOLFSSL_HMAC_CTX* ctx, const void* key, int keySz, - const EVP_MD* type, WOLFSSL_ENGINE* e) + const WOLFSSL_EVP_MD* type, WOLFSSL_ENGINE* e) { WOLFSSL_ENTER("wolfSSL_HMAC_Init_ex"); @@ -1746,7 +1746,7 @@ int wolfSSL_HMAC_Init_ex(WOLFSSL_HMAC_CTX* ctx, const void* key, int keySz, * @return 0 on failure. */ int wolfSSL_HMAC_Init(WOLFSSL_HMAC_CTX* ctx, const void* key, int keylen, - const EVP_MD* type) + const WOLFSSL_EVP_MD* type) { int ret = 1; void* heap = NULL; @@ -2228,7 +2228,7 @@ int wolfSSL_CMAC_Update(WOLFSSL_CMAC_CTX* ctx, const void* data, size_t len) * * @param [in, out] ctx CMAC context object. * @param [out] out Buffer to place CMAC result into. - * Must be able to hold AES_BLOCK_SIZE bytes. + * Must be able to hold WC_AES_BLOCK_SIZE bytes. * @param [out] len Length of CMAC result. May be NULL. * @return 1 on success. * @return 0 when ctx is NULL. @@ -2248,7 +2248,7 @@ int wolfSSL_CMAC_Final(WOLFSSL_CMAC_CTX* ctx, unsigned char* out, size_t* len) if (ret == 1) { /* Get the expected output size. */ - blockSize = EVP_CIPHER_CTX_block_size(ctx->cctx); + blockSize = wolfSSL_EVP_CIPHER_CTX_block_size(ctx->cctx); /* Check value is valid. */ if (blockSize <= 0) { ret = 0; @@ -2567,7 +2567,7 @@ WOLFSSL_DES_LONG wolfSSL_DES_cbc_cksum(const unsigned char* in, if (!err) { /* Encrypt data into temporary. */ wolfSSL_DES_cbc_encrypt(data, tmp, dataSz, sc, (WOLFSSL_DES_cblock*)iv, - DES_ENCRYPT); + WC_DES_ENCRYPT); /* Copy out last block. */ XMEMCPY((unsigned char*)out, tmp + (dataSz - DES_BLOCK_SIZE), DES_BLOCK_SIZE); @@ -2614,7 +2614,7 @@ void wolfSSL_DES_cbc_encrypt(const unsigned char* input, unsigned char* output, WOLFSSL_ENTER("wolfSSL_DES_cbc_encrypt"); #ifdef WOLFSSL_SMALL_STACK - des = XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_CIPHER); + des = (Des*)XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_CIPHER); if (des == NULL) { WOLFSSL_MSG("Failed to allocate memory for Des object"); } @@ -2631,7 +2631,7 @@ void wolfSSL_DES_cbc_encrypt(const unsigned char* input, unsigned char* output, /* Length of data that is a multiple of a block. */ word32 len = (word32)(length - lb_sz); - if (enc == DES_ENCRYPT) { + if (enc == WC_DES_ENCRYPT) { /* Encrypt full blocks into output. */ wc_Des_CbcEncrypt(des, output, input, len); if (lb_sz != 0) { @@ -2687,7 +2687,7 @@ void wolfSSL_DES_ncbc_encrypt(const unsigned char* input, unsigned char* output, offset = (offset + DES_BLOCK_SIZE - 1) / DES_BLOCK_SIZE; offset *= DES_BLOCK_SIZE; offset -= DES_BLOCK_SIZE; - if (enc == DES_ENCRYPT) { + if (enc == WC_DES_ENCRYPT) { /* Encrypt data. */ wolfSSL_DES_cbc_encrypt(input, output, length, schedule, ivec, enc); /* Use last encrypted block as new IV. */ @@ -2732,7 +2732,7 @@ void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input, WOLFSSL_ENTER("wolfSSL_DES_ede3_cbc_encrypt"); #ifdef WOLFSSL_SMALL_STACK - des3 = XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_CIPHER); + des3 = (Des3*)XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_CIPHER); if (des3 == NULL) { WOLFSSL_MSG("Failed to allocate memory for Des3 object"); sz = 0; @@ -2761,7 +2761,7 @@ void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input, ret = wc_Des3Init(des3, NULL, INVALID_DEVID); (void)ret; - if (enc == DES_ENCRYPT) { + if (enc == WC_DES_ENCRYPT) { /* Initialize wolfCrypt DES3 object. */ if (wc_Des3_SetKey(des3, key, (const byte*)ivec, DES_ENCRYPTION) == 0) { @@ -2858,22 +2858,24 @@ void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* in, WOLFSSL_DES_cblock* out, /* Validate parameters. */ if ((in == NULL) || (out == NULL) || (key == NULL) || - ((enc != DES_ENCRYPT) && (enc != DES_DECRYPT))) { + ((enc != WC_DES_ENCRYPT) && (enc != WC_DES_DECRYPT))) { WOLFSSL_MSG("Bad argument passed to wolfSSL_DES_ecb_encrypt"); } #ifdef WOLFSSL_SMALL_STACK - else if ((des = XMALLOC(sizeof(Des), NULL, DYNAMIC_TYPE_CIPHER)) == NULL) { + else if ((des = (Des*)XMALLOC(sizeof(Des), NULL, DYNAMIC_TYPE_CIPHER)) + == NULL) + { WOLFSSL_MSG("Failed to allocate memory for Des object"); } #endif /* Set key in wolfCrypt DES object for encryption or decryption. - * DES_ENCRYPT = 1, wolfSSL DES_ENCRYPTION = 0. - * DES_DECRYPT = 0, wolfSSL DES_DECRYPTION = 1. + * WC_DES_ENCRYPT = 1, wolfSSL DES_ENCRYPTION = 0. + * WC_DES_DECRYPT = 0, wolfSSL DES_DECRYPTION = 1. */ else if (wc_Des_SetKey(des, (const byte*)key, NULL, !enc) != 0) { WOLFSSL_MSG("wc_Des_SetKey return error."); } - else if (enc == DES_ENCRYPT) { + else if (enc == WC_DES_ENCRYPT) { /* Encrypt a block with wolfCrypt DES object. */ if (wc_Des_EcbEncrypt(des, (byte*)out, (const byte*)in, DES_KEY_SIZE) != 0) { @@ -2915,15 +2917,15 @@ void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* in, WOLFSSL_DES_cblock* out, * @param [in] key Key data. * @param [in] bits Number of bits in key. * @param [out] aes AES key object. - * @param [in] enc Whether to encrypt. AES_ENCRYPT or AES_DECRYPT. + * @param [in] enc Whether to encrypt. AES_ENCRYPTION or AES_DECRYPTION. * @return 0 on success. * @return -1 when key or aes is NULL. * @return -1 when setting key with wolfCrypt fails. */ static int wolfssl_aes_set_key(const unsigned char *key, const int bits, - AES_KEY *aes, int enc) + WOLFSSL_AES_KEY *aes, int enc) { - wc_static_assert(sizeof(AES_KEY) >= sizeof(Aes)); + wc_static_assert(sizeof(WOLFSSL_AES_KEY) >= sizeof(Aes)); /* Validate parameters. */ if ((key == NULL) || (aes == NULL)) { @@ -2931,7 +2933,7 @@ static int wolfssl_aes_set_key(const unsigned char *key, const int bits, return WOLFSSL_FATAL_ERROR; } - XMEMSET(aes, 0, sizeof(AES_KEY)); + XMEMSET(aes, 0, sizeof(WOLFSSL_AES_KEY)); if (wc_AesInit((Aes*)aes, NULL, INVALID_DEVID) != 0) { WOLFSSL_MSG("Error in initting AES key"); @@ -2955,11 +2957,11 @@ static int wolfssl_aes_set_key(const unsigned char *key, const int bits, * @return -1 when setting key with wolfCrypt fails. */ int wolfSSL_AES_set_encrypt_key(const unsigned char *key, const int bits, - AES_KEY *aes) + WOLFSSL_AES_KEY *aes) { WOLFSSL_ENTER("wolfSSL_AES_set_encrypt_key"); - return wolfssl_aes_set_key(key, bits, aes, AES_ENCRYPT); + return wolfssl_aes_set_key(key, bits, aes, AES_ENCRYPTION); } /* Sets the key into the AES key object for decryption. @@ -2972,11 +2974,11 @@ int wolfSSL_AES_set_encrypt_key(const unsigned char *key, const int bits, * @return -1 when setting key with wolfCrypt fails. */ int wolfSSL_AES_set_decrypt_key(const unsigned char *key, const int bits, - AES_KEY *aes) + WOLFSSL_AES_KEY *aes) { WOLFSSL_ENTER("wolfSSL_AES_set_decrypt_key"); - return wolfssl_aes_set_key(key, bits, aes, AES_DECRYPT); + return wolfssl_aes_set_key(key, bits, aes, AES_DECRYPTION); } #ifdef WOLFSSL_AES_DIRECT @@ -2984,15 +2986,15 @@ int wolfSSL_AES_set_decrypt_key(const unsigned char *key, const int bits, * * wolfSSL_AES_set_encrypt_key() must have been called. * - * #input must contain AES_BLOCK_SIZE bytes of data. - * #output must be a buffer at least AES_BLOCK_SIZE bytes in length. + * #input must contain WC_AES_BLOCK_SIZE bytes of data. + * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length. * * @param [in] input Data to encrypt. * @param [out] output Encrypted data. * @param [in] key AES key to use for encryption. */ void wolfSSL_AES_encrypt(const unsigned char* input, unsigned char* output, - AES_KEY *key) + WOLFSSL_AES_KEY *key) { WOLFSSL_ENTER("wolfSSL_AES_encrypt"); @@ -3002,7 +3004,8 @@ void wolfSSL_AES_encrypt(const unsigned char* input, unsigned char* output, } else #if !defined(HAVE_SELFTEST) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) \ + || defined(WOLFSSL_LINUXKM)) /* Encrypt a block with wolfCrypt AES. */ if (wc_AesEncryptDirect((Aes*)key, output, input) != 0) { WOLFSSL_MSG("wc_AesEncryptDirect failed"); @@ -3020,15 +3023,15 @@ void wolfSSL_AES_encrypt(const unsigned char* input, unsigned char* output, * * wolfSSL_AES_set_decrypt_key() must have been called. * - * #input must contain AES_BLOCK_SIZE bytes of data. - * #output must be a buffer at least AES_BLOCK_SIZE bytes in length. + * #input must contain WC_AES_BLOCK_SIZE bytes of data. + * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length. * * @param [in] input Data to decrypt. * @param [out] output Decrypted data. * @param [in] key AES key to use for encryption. */ void wolfSSL_AES_decrypt(const unsigned char* input, unsigned char* output, - AES_KEY *key) + WOLFSSL_AES_KEY *key) { WOLFSSL_ENTER("wolfSSL_AES_decrypt"); @@ -3038,7 +3041,7 @@ void wolfSSL_AES_decrypt(const unsigned char* input, unsigned char* output, } else #if !defined(HAVE_SELFTEST) && \ - (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) + (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION3_GE(5,3,0))) /* Decrypt a block with wolfCrypt AES. */ if (wc_AesDecryptDirect((Aes*)key, output, input) != 0) { WOLFSSL_MSG("wc_AesDecryptDirect failed"); @@ -3060,17 +3063,17 @@ void wolfSSL_AES_decrypt(const unsigned char* input, unsigned char* output, * wolfSSL_AES_set_encrypt_key() or wolfSSL_AES_set_decrypt_key ()must have been * called. * - * #input must contain AES_BLOCK_SIZE bytes of data. - * #output must be a buffer at least AES_BLOCK_SIZE bytes in length. + * #input must contain WC_AES_BLOCK_SIZE bytes of data. + * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length. * * @param [in] in Data to encipher. * @param [out] out Enciphered data. * @param [in] key AES key to use for encryption/decryption. * @param [in] enc Whether to encrypt. - * AES_ENCRPT for encryption, AES_DECRYPT for decryption. + * AES_ENCRPT for encryption, AES_DECRYPTION for decryption. */ void wolfSSL_AES_ecb_encrypt(const unsigned char *in, unsigned char* out, - AES_KEY *key, const int enc) + WOLFSSL_AES_KEY *key, const int enc) { WOLFSSL_ENTER("wolfSSL_AES_ecb_encrypt"); @@ -3078,16 +3081,16 @@ void wolfSSL_AES_ecb_encrypt(const unsigned char *in, unsigned char* out, if ((key == NULL) || (in == NULL) || (out == NULL)) { WOLFSSL_MSG("Error, Null argument passed in"); } - else if (enc == AES_ENCRYPT) { + else if (enc == AES_ENCRYPTION) { /* Encrypt block. */ - if (wc_AesEcbEncrypt((Aes*)key, out, in, AES_BLOCK_SIZE) != 0) { + if (wc_AesEcbEncrypt((Aes*)key, out, in, WC_AES_BLOCK_SIZE) != 0) { WOLFSSL_MSG("Error with AES CBC encrypt"); } } else { #ifdef HAVE_AES_DECRYPT /* Decrypt block. */ - if (wc_AesEcbDecrypt((Aes*)key, out, in, AES_BLOCK_SIZE) != 0) { + if (wc_AesEcbDecrypt((Aes*)key, out, in, WC_AES_BLOCK_SIZE) != 0) { WOLFSSL_MSG("Error with AES CBC decrypt"); } #else @@ -3111,10 +3114,10 @@ void wolfSSL_AES_ecb_encrypt(const unsigned char *in, unsigned char* out, * On in, used with first block. * On out, IV for further operations. * @param [in] enc Whether to encrypt. - * AES_ENCRPT for encryption, AES_DECRYPT for decryption. + * AES_ENCRPT for encryption, AES_DECRYPTION for decryption. */ void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out, - size_t len, AES_KEY *key, unsigned char* iv, const int enc) + size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, const int enc) { WOLFSSL_ENTER("wolfSSL_AES_cbc_encrypt"); @@ -3131,7 +3134,7 @@ void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out, if ((ret = wc_AesSetIV(aes, (const byte*)iv)) != 0) { WOLFSSL_MSG("Error with setting iv"); } - else if (enc == AES_ENCRYPT) { + else if (enc == AES_ENCRYPTION) { /* Encrypt with wolfCrypt AES object. */ if ((ret = wc_AesCbcEncrypt(aes, out, in, (word32)len)) != 0) { WOLFSSL_MSG("Error with AES CBC encrypt"); @@ -3146,7 +3149,7 @@ void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out, if (ret == 0) { /* Get IV for next operation. */ - XMEMCPY(iv, (byte*)(aes->reg), AES_BLOCK_SIZE); + XMEMCPY(iv, (byte*)(aes->reg), WC_AES_BLOCK_SIZE); } } } @@ -3166,10 +3169,10 @@ void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out, * On out, IV for further operations. * @param [out] num Number of bytes used from last incomplete block. * @param [in] enc Whether to encrypt. - * AES_ENCRPT for encryption, AES_DECRYPT for decryption. + * AES_ENCRPT for encryption, AES_DECRYPTION for decryption. */ void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out, - size_t len, AES_KEY *key, unsigned char* iv, int* num, const int enc) + size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, int* num, const int enc) { #ifndef WOLFSSL_AES_CFB WOLFSSL_MSG("CFB mode not enabled please use macro WOLFSSL_AES_CFB"); @@ -3196,9 +3199,9 @@ void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out, * leftover bytes field "left", and this function relies on the leftover * bytes being preserved between calls. */ - XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); - if (enc == AES_ENCRYPT) { + if (enc == AES_ENCRYPTION) { /* Encrypt data with AES-CFB. */ if ((ret = wc_AesCfbEncrypt(aes, out, in, (word32)len)) != 0) { WOLFSSL_MSG("Error with AES CBC encrypt"); @@ -3213,11 +3216,11 @@ void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out, if (ret == 0) { /* Copy IV out after operation. */ - XMEMCPY(iv, (byte*)(aes->reg), AES_BLOCK_SIZE); + XMEMCPY(iv, (byte*)(aes->reg), WC_AES_BLOCK_SIZE); /* Store number of left over bytes to num. */ if (num != NULL) { - *num = (AES_BLOCK_SIZE - aes->left) % AES_BLOCK_SIZE; + *num = (WC_AES_BLOCK_SIZE - aes->left) % WC_AES_BLOCK_SIZE; } } } @@ -3237,7 +3240,7 @@ void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out, * @return 0 when key, iv, out or in is NULL. * @return 0 when key length is not valid. */ -int wolfSSL_AES_wrap_key(AES_KEY *key, const unsigned char *iv, +int wolfSSL_AES_wrap_key(WOLFSSL_AES_KEY *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, unsigned int inSz) { int ret = 0; @@ -3272,7 +3275,7 @@ int wolfSSL_AES_wrap_key(AES_KEY *key, const unsigned char *iv, * @return 0 when key, iv, out or in is NULL. * @return 0 when wrapped key data length is not valid. */ -int wolfSSL_AES_unwrap_key(AES_KEY *key, const unsigned char *iv, +int wolfSSL_AES_unwrap_key(WOLFSSL_AES_KEY *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, unsigned int inSz) { int ret = 0; @@ -3333,7 +3336,7 @@ size_t wolfSSL_CRYPTO_cts128_encrypt(const unsigned char *in, } /* Encrypt data up to last block */ - (*cbc)(in, out, len - lastBlkLen, key, iv, AES_ENCRYPT); + (*cbc)(in, out, len - lastBlkLen, key, iv, AES_ENCRYPTION); /* Move to last block */ in += len - lastBlkLen; @@ -3346,7 +3349,7 @@ size_t wolfSSL_CRYPTO_cts128_encrypt(const unsigned char *in, XMEMCPY(out, out - WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen); /* Encrypt last block. */ (*cbc)(lastBlk, out - WOLFSSL_CTS128_BLOCK_SZ, WOLFSSL_CTS128_BLOCK_SZ, - key, iv, AES_ENCRYPT); + key, iv, AES_ENCRYPTION); } return len; @@ -3401,13 +3404,13 @@ size_t wolfSSL_CRYPTO_cts128_decrypt(const unsigned char *in, * Use 0 buffer as IV to do straight decryption. * This places the Cn-1 block at lastBlk */ XMEMSET(lastBlk, 0, WOLFSSL_CTS128_BLOCK_SZ); - (*cbc)(in, prevBlk, WOLFSSL_CTS128_BLOCK_SZ, key, lastBlk, AES_DECRYPT); + (*cbc)(in, prevBlk, WOLFSSL_CTS128_BLOCK_SZ, key, lastBlk, AES_DECRYPTION); /* RFC2040: Append the tail (BB minus Ln) bytes of Xn to Cn * to create En. */ XMEMCPY(prevBlk, in + WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen); /* Cn and Cn-1 can now be decrypted */ - (*cbc)(prevBlk, out, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPT); - (*cbc)(lastBlk, lastBlk, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPT); + (*cbc)(prevBlk, out, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPTION); + (*cbc)(lastBlk, lastBlk, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPTION); XMEMCPY(out + WOLFSSL_CTS128_BLOCK_SZ, lastBlk, lastBlkLen); } diff --git a/src/src/ssl_load.c b/src/src/ssl_load.c index 0361edb..004cb65 100644 --- a/src/src/ssl_load.c +++ b/src/src/ssl_load.c @@ -1397,7 +1397,7 @@ static int ProcessBufferPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, #ifdef OPENSSL_EXTRA /* Decryption password is probably wrong. */ if (info->passwd_cb) { - EVPerr(0, EVP_R_BAD_DECRYPT); + WOLFSSL_EVPerr(0, -WOLFSSL_EVP_R_BAD_DECRYPT_E); } #endif WOLFSSL_ERROR(WOLFSSL_BAD_FILE); @@ -2201,9 +2201,9 @@ static int ProcessBufferResetSuites(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int type) InitSuites(ssl->suites, ssl->version, ssl->buffers.keySz, WOLFSSL_HAVE_RSA, SSL_HAVE_PSK(ssl), ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, - ssl->options.haveStaticECC, ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, TRUE, - ssl->options.side); + ssl->options.haveStaticECC, + ssl->options.useAnon, TRUE, + TRUE, TRUE, TRUE, ssl->options.side); } } } @@ -2218,8 +2218,8 @@ static int ProcessBufferResetSuites(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int type) InitSuites(ctx->suites, ctx->method->version, ctx->privateKeySz, WOLFSSL_HAVE_RSA, CTX_HAVE_PSK(ctx), ctx->haveDH, ctx->haveECDSAsig, ctx->haveECC, TRUE, ctx->haveStaticECC, - ctx->haveFalconSig, ctx->haveDilithiumSig, CTX_USE_ANON(ctx), - TRUE, ctx->method->side); + CTX_USE_ANON(ctx), + TRUE, TRUE, TRUE, TRUE, ctx->method->side); } } @@ -2332,7 +2332,7 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, #endif } else if (ret == 0) { - /* Processing a cerificate. */ + /* Processing a certificate. */ if (userChain) { /* Take original buffer and add to user chain to send in TLS * handshake. */ @@ -2707,7 +2707,7 @@ static int wolfssl_ctx_load_path(WOLFSSL_CTX* ctx, const char* path, /* Load file. */ ret = wolfssl_ctx_load_path_file(ctx, name, verify, (int)flags, &failCount, &successCount); - /* Get next filenmae. */ + /* Get next filename. */ fileRet = wc_ReadDirNext(readCtx, path, &name); } /* Cleanup directory reading context. */ @@ -4146,6 +4146,77 @@ int wolfSSL_CTX_use_AltPrivateKey_Label(WOLFSSL_CTX* ctx, const char* label, #endif /* WOLFSSL_DUAL_ALG_CERTS */ #endif /* WOLF_PRIVATE_KEY_ID */ +#if defined(WOLF_CRYPTO_CB) && !defined(NO_CERTS) + +static int wolfSSL_CTX_use_certificate_ex(WOLFSSL_CTX* ctx, + const char *label, const unsigned char *id, int idLen, int devId) +{ + int ret; + byte *certData = NULL; + word32 certDataLen = 0; + word32 labelLen = 0; + int certFormat = 0; + + WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_ex"); + + if (label != NULL) { + labelLen = (word32)XSTRLEN(label); + } + + ret = wc_CryptoCb_GetCert(devId, label, labelLen, id, idLen, + &certData, &certDataLen, &certFormat, ctx->heap); + if (ret != 0) { + ret = WOLFSSL_FAILURE; + goto exit; + } + + ret = ProcessBuffer(ctx, certData, certDataLen, certFormat, + CERT_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + +exit: + XFREE(certData, ctx->heap, DYNAMIC_TYPE_CERT); + return ret; +} + +/* Load the label name of a certificate into the SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] label Buffer holding label. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_certificate_label(WOLFSSL_CTX* ctx, + const char *label, int devId) +{ + if ((ctx == NULL) || (label == NULL)) { + return WOLFSSL_FAILURE; + } + + return wolfSSL_CTX_use_certificate_ex(ctx, label, NULL, 0, devId); +} + +/* Load the id of a certificate into SSL context. + * + * @param [in, out] ctx SSL context object. + * @param [in] id Buffer holding id. + * @param [in] idLen Size of data in bytes. + * @param [in] devId Device identifier. + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_CTX_use_certificate_id(WOLFSSL_CTX* ctx, + const unsigned char *id, int idLen, int devId) +{ + if ((ctx == NULL) || (id == NULL) || (idLen <= 0)) { + return WOLFSSL_FAILURE; + } + + return wolfSSL_CTX_use_certificate_ex(ctx, NULL, id, idLen, devId); +} + +#endif /* if defined(WOLF_CRYPTO_CB) && !defined(NO_CERTS) */ + /* Load a certificate chain in a buffer into SSL context. * * @param [in, out] ctx SSL context object. @@ -4791,7 +4862,7 @@ int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) /* Use the certificate. */ ret = wolfSSL_CTX_use_certificate(ctx, x509); } - /* Increate reference count as we will store it. */ + /* Increase reference count as we will store it. */ else if ((ret == 1) && ((ret = wolfSSL_X509_up_ref(x509)) == 1)) { /* Load the DER encoding. */ ret = wolfSSL_CTX_load_verify_buffer(ctx, x509->derCert->buffer, @@ -4946,19 +5017,19 @@ int wolfSSL_CTX_use_PrivateKey(WOLFSSL_CTX *ctx, WOLFSSL_EVP_PKEY *pkey) if (ret == 1) { switch (pkey->type) { #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: WOLFSSL_MSG("populating RSA key"); ret = PopulateRSAEvpPkeyDer(pkey); break; #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */ #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \ defined(WOLFSSL_CERT_GEN)) && !defined(NO_DSA) - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: break; #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) && * !NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: WOLFSSL_MSG("populating ECC key"); ret = ECC_populate_EVP_PKEY(pkey, pkey->ecc); break; @@ -4972,7 +5043,7 @@ int wolfSSL_CTX_use_PrivateKey(WOLFSSL_CTX *ctx, WOLFSSL_EVP_PKEY *pkey) /* ptr for WOLFSSL_EVP_PKEY struct is expected to be DER format */ ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, (const unsigned char*)pkey->pkey.ptr, pkey->pkey_sz, - SSL_FILETYPE_ASN1); + WOLFSSL_FILETYPE_ASN1); } return ret; @@ -5001,7 +5072,7 @@ int wolfSSL_CTX_use_certificate_ASN1(WOLFSSL_CTX *ctx, int derSz, if ((ctx == NULL) || (der == NULL)) { ret = 0; } - /* Load DER encoded cerificate into SSL context. */ + /* Load DER encoded certificate into SSL context. */ if ((ret == 1) && (wolfSSL_CTX_use_certificate_buffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1) != 1)) { ret = 0; @@ -5023,7 +5094,7 @@ int wolfSSL_CTX_use_certificate_ASN1(WOLFSSL_CTX *ctx, int derSz, int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) { int ret = 1; - int derSize; + int derSize = 0; unsigned char* der = NULL; unsigned char* p; @@ -5060,7 +5131,7 @@ int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) } if (ret == 1) { - /* Load DER encoded cerificate into SSL context. */ + /* Load DER encoded certificate into SSL context. */ ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, der, derSize, SSL_FILETYPE_ASN1); if (ret != WOLFSSL_SUCCESS) { @@ -5238,9 +5309,9 @@ static int wolfssl_set_tmp_dh(WOLFSSL* ssl, unsigned char* p, int pSz, InitSuites(ssl->suites, ssl->version, SSL_KEY_SZ(ssl), WOLFSSL_HAVE_RSA, SSL_HAVE_PSK(ssl), ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, - ssl->options.haveStaticECC, ssl->options.haveFalconSig, - ssl->options.haveDilithiumSig, ssl->options.useAnon, TRUE, - ssl->options.side); + ssl->options.haveStaticECC, + ssl->options.useAnon, TRUE, + TRUE, TRUE, TRUE, ssl->options.side); } return ret; diff --git a/src/src/ssl_p7p12.c b/src/src/ssl_p7p12.c index fba2767..12ef33c 100644 --- a/src/src/ssl_p7p12.c +++ b/src/src/ssl_p7p12.c @@ -948,7 +948,7 @@ int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7) int pemSz = -1; enum wc_HashType hashType; byte hashBuf[WC_MAX_DIGEST_SIZE]; - word32 hashSz = -1; + word32 hashSz = 0; WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PKCS7"); @@ -2012,7 +2012,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, #ifndef NO_RSA { const unsigned char* pt = pk; - if (wolfSSL_d2i_PrivateKey(EVP_PKEY_RSA, pkey, &pt, pkSz) != + if (wolfSSL_d2i_PrivateKey(WC_EVP_PKEY_RSA, pkey, &pt, pkSz) != NULL) { ret = 0; } @@ -2022,7 +2022,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, #ifdef HAVE_ECC if (ret != 0) { /* if is in fail state check if ECC key */ const unsigned char* pt = pk; - if (wolfSSL_d2i_PrivateKey(EVP_PKEY_EC, pkey, &pt, pkSz) != + if (wolfSSL_d2i_PrivateKey(WC_EVP_PKEY_EC, pkey, &pt, pkSz) != NULL) { ret = 0; } diff --git a/src/src/ssl_sess.c b/src/src/ssl_sess.c index 91f2c84..1471b9d 100644 --- a/src/src/ssl_sess.c +++ b/src/src/ssl_sess.c @@ -113,10 +113,10 @@ } SessionRow; #define SIZEOF_SESSION_ROW (sizeof(WOLFSSL_SESSION) + (sizeof(int) * 2)) - static WOLFSSL_GLOBAL SessionRow SessionCache[SESSION_ROWS]; + static WC_THREADSHARED SessionRow SessionCache[SESSION_ROWS]; #if defined(WOLFSSL_SESSION_STATS) && defined(WOLFSSL_PEAK_SESSIONS) - static WOLFSSL_GLOBAL word32 PeakSessions; + static WC_THREADSHARED word32 PeakSessions; #endif #ifdef ENABLE_SESSION_CACHE_ROW_LOCK @@ -124,8 +124,8 @@ #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&(row)->row_lock) #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&(row)->row_lock); #else - static WOLFSSL_GLOBAL wolfSSL_RwLock session_lock; /* SessionCache lock */ - static WOLFSSL_GLOBAL int session_lock_valid = 0; + static WC_THREADSHARED wolfSSL_RwLock session_lock; /* SessionCache lock */ + static WC_THREADSHARED int session_lock_valid = 0; #define SESSION_ROW_RD_LOCK(row) wc_LockRwLock_Rd(&session_lock) #define SESSION_ROW_WR_LOCK(row) wc_LockRwLock_Wr(&session_lock) #define SESSION_ROW_UNLOCK(row) wc_UnLockRwLock(&session_lock); @@ -176,22 +176,22 @@ ClientSession Clients[CLIENT_SESSIONS_PER_ROW]; } ClientRow; - static WOLFSSL_GLOBAL ClientRow ClientCache[CLIENT_SESSION_ROWS]; + static WC_THREADSHARED ClientRow ClientCache[CLIENT_SESSION_ROWS]; /* Client Cache */ /* uses session mutex */ /* ClientCache mutex */ - static WOLFSSL_GLOBAL wolfSSL_Mutex clisession_mutex + static WC_THREADSHARED wolfSSL_Mutex clisession_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(clisession_mutex); #ifndef WOLFSSL_MUTEX_INITIALIZER - static WOLFSSL_GLOBAL int clisession_mutex_valid = 0; + static WC_THREADSHARED int clisession_mutex_valid = 0; #endif #endif /* !NO_CLIENT_CACHE */ void EvictSessionFromCache(WOLFSSL_SESSION* session) { #ifdef HAVE_EX_DATA - int save_ownExData = session->ownExData; + byte save_ownExData = session->ownExData; session->ownExData = 1; /* Make sure ex_data access doesn't lead back * into the cache. */ #endif @@ -823,10 +823,8 @@ void wolfSSL_flush_sessions(WOLFSSL_CTX* ctx, long tm) void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm) { int i, j; - byte id[ID_LEN]; (void)ctx; - XMEMSET(id, 0, ID_LEN); WOLFSSL_ENTER("wolfSSL_flush_sessions"); for (i = 0; i < SESSION_ROWS; ++i) { if (SESSION_ROW_WR_LOCK(&SessionCache[i]) != 0) { @@ -843,7 +841,7 @@ void wolfSSL_CTX_flush_sessions(WOLFSSL_CTX* ctx, long tm) #ifdef SESSION_CACHE_DYNAMIC_MEM s != NULL && #endif - XMEMCMP(s->sessionID, id, ID_LEN) != 0 && + s->sessionIDSz > 0 && s->bornOn + s->timeout < (word32)tm ) { @@ -873,7 +871,7 @@ int wolfSSL_set_timeout(WOLFSSL* ssl, unsigned int to) return WOLFSSL_SUCCESS; } - +#ifndef NO_TLS /** * Sets ctx session timeout in seconds. * The timeout value set here should be reflected in the @@ -934,7 +932,7 @@ int wolfSSL_CTX_set_timeout(WOLFSSL_CTX* ctx, unsigned int to) return ret; #endif /* WOLFSSL_ERROR_CODE_OPENSSL */ } - +#endif /* !NO_TLS */ #ifndef NO_CLIENT_CACHE @@ -1120,7 +1118,9 @@ static int TlsSessionCacheGetAndLock(const byte *id, #else s = &sessRow->Sessions[idx]; #endif - if (s && XMEMCMP(s->sessionID, id, ID_LEN) == 0 && s->side == side) { + /* match session ID value and length */ + if (s && s->sessionIDSz == ID_LEN && s->side == side && + XMEMCMP(s->sessionID, id, ID_LEN) == 0) { *sess = s; break; } @@ -1839,7 +1839,7 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, } preallocNonceLen = addSession->ticketNonce.len; } -#endif /* WOLFSSL_TLS13 && WOLFSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */ +#endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ #endif /* HAVE_SESSION_TICKET */ /* Find a position for the new session in cache and use that */ @@ -1916,7 +1916,7 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, cacheSession = &sessRow->Sessions[idx]; #endif -#ifdef HAVE_EX_DATA +#ifdef HAVE_EX_DATA_CRYPTO if (overwrite) { /* Figure out who owns the ex_data */ if (cacheSession->ownExData) { @@ -3108,7 +3108,7 @@ long wolfSSL_SESSION_set_time(WOLFSSL_SESSION *ses, long t) return t; } -#endif /* !NO_SESSION_CACHE && OPENSSL_EXTRA || HAVE_EXT_CACHE */ +#endif /* !NO_SESSION_CACHE && (OPENSSL_EXTRA || HAVE_EXT_CACHE) */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ defined(HAVE_EX_DATA) @@ -3132,6 +3132,10 @@ static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, id = session->sessionID; if (session->haveAltSessionID) id = session->altSessionID; + else if (session->sessionIDSz != ID_LEN) { + WOLFSSL_MSG("Incorrect sessionIDSz"); + return; + } row = (int)(HashObject(id, ID_LEN, &error) % SESSION_ROWS); if (error != 0) { @@ -3156,7 +3160,7 @@ static void SESSION_ex_data_cache_update(WOLFSSL_SESSION* session, int idx, #else cacheSession = &sessRow->Sessions[i]; #endif - if (cacheSession && + if (cacheSession && cacheSession->sessionIDSz == ID_LEN && XMEMCMP(id, cacheSession->sessionID, ID_LEN) == 0 && session->side == cacheSession->side #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) @@ -3682,10 +3686,12 @@ WOLFSSL_SESSION* wolfSSL_NewSession(void* heap) #endif #ifdef HAVE_EX_DATA ret->ownExData = 1; + #ifdef HAVE_EX_DATA_CRYPTO if (crypto_ex_cb_ctx_session != NULL) { crypto_ex_cb_setup_new_data(ret, crypto_ex_cb_ctx_session, &ret->ex_data); } + #endif #endif } return ret; @@ -3739,7 +3745,7 @@ int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session) * @param ticketNonceBuf If not null and @avoidSysCalls is true, the copy of the * ticketNonce will happen in this pre allocated buffer * @param ticketNonceLen @ticketNonceBuf len as input, used length on output - * @param ticketNonceUsed if @ticketNonceBuf was used to copy the ticket noncet + * @param ticketNonceUsed if @ticketNonceBuf was used to copy the ticket nonce * @return WOLFSSL_SUCCESS on success * WOLFSSL_FAILURE on failure */ @@ -3748,7 +3754,7 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, byte* ticketNonceLen, byte* preallocUsed) { #ifdef HAVE_SESSION_TICKET - int ticLenAlloc = 0; + word16 ticLenAlloc = 0; byte *ticBuff = NULL; #endif const size_t copyOffset = OFFSETOF(WOLFSSL_SESSION, heap) + @@ -3964,7 +3970,7 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, #endif /* HAVE_SESSION_TICKET */ -#ifdef HAVE_EX_DATA +#ifdef HAVE_EX_DATA_CRYPTO if (input->type != WOLFSSL_SESSION_TYPE_CACHE && output->type != WOLFSSL_SESSION_TYPE_CACHE) { /* Not called with cache as that passes ownership of ex_data */ @@ -4044,7 +4050,7 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) WOLFSSL_MSG("wolfSSL_FreeSession full free"); -#ifdef HAVE_EX_DATA +#ifdef HAVE_EX_DATA_CRYPTO if (session->ownExData) { crypto_ex_cb_free_data(session, crypto_ex_cb_ctx_session, &session->ex_data); @@ -4164,7 +4170,8 @@ int wolfSSL_SESSION_set1_id(WOLFSSL_SESSION *s, if (sid_len > ID_LEN) { return WOLFSSL_FAILURE; } - s->sessionIDSz = sid_len; + + s->sessionIDSz = (byte)sid_len; if (sid != s->sessionID) { XMEMCPY(s->sessionID, sid, sid_len); } @@ -4180,7 +4187,7 @@ int wolfSSL_SESSION_set1_id_context(WOLFSSL_SESSION *s, if (sid_ctx_len > ID_LEN) { return WOLFSSL_FAILURE; } - s->sessionCtxSz = sid_ctx_len; + s->sessionCtxSz = (byte)sid_ctx_len; if (sid_ctx != s->sessionCtx) { XMEMCPY(s->sessionCtx, sid_ctx, sid_ctx_len); } @@ -4230,8 +4237,7 @@ const byte* wolfSSL_get_sessionID(const WOLFSSL_SESSION* session) #endif -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ - defined(HAVE_EX_DATA) +#ifdef HAVE_EX_DATA int wolfSSL_SESSION_set_ex_data(WOLFSSL_SESSION* session, int idx, void* data) { @@ -4301,13 +4307,8 @@ void* wolfSSL_SESSION_get_ex_data(const WOLFSSL_SESSION* session, int idx) #endif return ret; } -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_EX_DATA */ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ - (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB))) -#ifdef HAVE_EX_DATA +#ifdef HAVE_EX_DATA_CRYPTO int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, WOLFSSL_CRYPTO_EX_free* free_func) @@ -4316,9 +4317,8 @@ int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_SESSION, ctx_l, ctx_ptr, new_func, dup_func, free_func); } -#endif -#endif - +#endif /* HAVE_EX_DATA_CRYPTO */ +#endif /* HAVE_EX_DATA */ #if defined(OPENSSL_ALL) || \ defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ diff --git a/src/src/tls.c b/src/src/tls.c index 8441acf..0e5f43b 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -3649,7 +3649,7 @@ int TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert, request = &csr->request.ocsp[req_cnt]; if (request->serial != NULL) { - /* clear request contents before re-use */ + /* clear request contents before reuse */ FreeOcspRequest(request); if (csr->requests > 0) csr->requests--; @@ -6450,7 +6450,7 @@ static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz) if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == 0 #endif ) { cnt++; @@ -6462,7 +6462,7 @@ static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz) isDtls, ssl->options.minDowngrade, tls12Minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == 0 #endif ) { cnt++; @@ -6473,7 +6473,7 @@ static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz) isDtls, ssl->options.minDowngrade, tls11Minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == 0 #endif ) { cnt++; @@ -6482,7 +6482,7 @@ static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz) if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == 0 #endif ) { cnt++; @@ -6547,7 +6547,7 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == 0 #endif ) { *cnt += OPAQUE16_LEN; @@ -6567,7 +6567,7 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == 0 #endif ) { *cnt += OPAQUE16_LEN; @@ -6580,7 +6580,7 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == 0 #endif ) { *cnt += OPAQUE16_LEN; @@ -6591,7 +6591,7 @@ static int TLSX_SupportedVersions_Write(void* data, byte* output, if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR) #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \ defined(WOLFSSL_WPAS_SMALL) - && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0 + && (ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == 0 #endif ) { *cnt += OPAQUE16_LEN; @@ -7168,15 +7168,16 @@ static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input, return 0; } -#define CAN_GET_SIZE TLSX_CA_Names_GetSize -#define CAN_WRITE TLSX_CA_Names_Write -#define CAN_PARSE TLSX_CA_Names_Parse +#define CAN_GET_SIZE(data) TLSX_CA_Names_GetSize(data) +#define CAN_WRITE(data, output) TLSX_CA_Names_Write(data, output) +#define CAN_PARSE(ssl, input, length, isRequest) \ + TLSX_CA_Names_Parse(ssl, input, length, isRequest) #else -#define CAN_GET_SIZE(...) 0 -#define CAN_WRITE(...) 0 -#define CAN_PARSE(...) 0 +#define CAN_GET_SIZE(data) 0 +#define CAN_WRITE(data, output) 0 +#define CAN_PARSE(ssl, input, length, isRequest) 0 #endif @@ -7982,6 +7983,24 @@ static int kyber_id2type(int id, int *type) int ret = 0; switch (id) { +#ifndef WOLFSSL_NO_ML_KEM + #ifndef WOLFSSL_NO_ML_KEM_512 + case WOLFSSL_ML_KEM_512: + *type = WC_ML_KEM_512; + break; + #endif + #ifndef WOLFSSL_NO_ML_KEM_768 + case WOLFSSL_ML_KEM_768: + *type = WC_ML_KEM_768; + break; + #endif + #ifndef WOLFSSL_NO_ML_KEM_1024 + case WOLFSSL_ML_KEM_1024: + *type = WC_ML_KEM_1024; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: *type = KYBER512; @@ -7997,6 +8016,7 @@ static int kyber_id2type(int id, int *type) *type = KYBER1024; break; #endif +#endif default: ret = NOT_COMPILED_IN; break; @@ -8012,12 +8032,22 @@ typedef struct PqcHybridMapping { } PqcHybridMapping; static const PqcHybridMapping pqc_hybrid_mapping[] = { +#ifndef WOLFSSL_NO_ML_KEM + {.hybrid = WOLFSSL_P256_ML_KEM_512, .ecc = WOLFSSL_ECC_SECP256R1, + .pqc = WOLFSSL_ML_KEM_512}, + {.hybrid = WOLFSSL_P384_ML_KEM_768, .ecc = WOLFSSL_ECC_SECP384R1, + .pqc = WOLFSSL_ML_KEM_768}, + {.hybrid = WOLFSSL_P521_ML_KEM_1024, .ecc = WOLFSSL_ECC_SECP521R1, + .pqc = WOLFSSL_ML_KEM_1024}, +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1, .pqc = WOLFSSL_KYBER_LEVEL1}, {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1, .pqc = WOLFSSL_KYBER_LEVEL3}, {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1, .pqc = WOLFSSL_KYBER_LEVEL5}, +#endif {.hybrid = 0, .ecc = 0, .pqc = 0} }; @@ -9662,6 +9692,45 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) #endif #endif #ifdef WOLFSSL_HAVE_KYBER +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_KYBER + #ifndef WOLFSSL_NO_ML_KEM_512 + case WOLFSSL_ML_KEM_512: + case WOLFSSL_P256_ML_KEM_512: + #endif + #ifndef WOLFSSL_NO_ML_KEM_768 + case WOLFSSL_ML_KEM_768: + case WOLFSSL_P384_ML_KEM_768: + #endif + #ifndef WOLFSSL_NO_ML_KEM_1024 + case WOLFSSL_ML_KEM_1024: + case WOLFSSL_P521_ML_KEM_1024: + #endif + break; + #elif defined(HAVE_LIBOQS) + case WOLFSSL_ML_KEM_512: + case WOLFSSL_ML_KEM_768: + case WOLFSSL_ML_KEM_1024: + case WOLFSSL_P256_ML_KEM_512: + case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P521_ML_KEM_1024: + { + int ret; + int id; + findEccPqc(NULL, &namedGroup, namedGroup); + ret = kyber_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } + + if (! ext_kyber_enabled(id)) { + return 0; + } + break; + } + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: @@ -9699,6 +9768,7 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) } #endif #endif +#endif /* WOLFSSL_HAVE_KYBER */ default: return 0; } @@ -9744,6 +9814,31 @@ static const word16 preferredGroup[] = { #if defined(HAVE_FFDHE_8192) WOLFSSL_FFDHE_8192, #endif +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_KYBER + #ifndef WOLFSSL_NO_ML_KEM_512 + WOLFSSL_ML_KEM_512, + WOLFSSL_P256_ML_KEM_512, + #endif + #ifndef WOLFSSL_NO_ML_KEM_768 + WOLFSSL_ML_KEM_768, + WOLFSSL_P384_ML_KEM_768, + #endif + #ifndef WOLFSSL_NO_ML_KEM_1024 + WOLFSSL_ML_KEM_1024, + WOLFSSL_P521_ML_KEM_1024, + #endif +#elif defined(HAVE_LIBOQS) + /* These require a runtime call to TLSX_KeyShare_IsSupported to use */ + WOLFSSL_ML_KEM_512, + WOLFSSL_ML_KEM_768, + WOLFSSL_ML_KEM_1024, + WOLFSSL_P256_ML_KEM_512, + WOLFSSL_P384_ML_KEM_768, + WOLFSSL_P521_ML_KEM_1024, +#endif +#endif /* !WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 WOLFSSL_KYBER_LEVEL1, @@ -9766,6 +9861,7 @@ static const word16 preferredGroup[] = { WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P521_KYBER_LEVEL5, #endif +#endif /* WOLFSSL_KYBER_ORIGINAL */ WOLFSSL_NAMED_GROUP_INVALID }; @@ -9957,6 +10053,16 @@ int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length, } } + /* This could be a situation where the client tried to start with TLS 1.3 + * when it sent ClientHello and the server down-graded to TLS 1.2. In that + * case, erroring out because it is TLS 1.2 is not a reasonable thing to do. + * In the case of TLS 1.2, the CKS values will be ignored. */ + if (!IsAtLeastTLSv1_3(ssl->version)) { + ssl->sigSpec = NULL; + ssl->sigSpecSz = 0; + return 0; + } + /* Extension data is valid, but if we are the server and we don't have an * alt private key, do not respond with CKS extension. */ if (wolfSSL_is_server(ssl) && ssl->buffers.altKey == NULL) { @@ -12368,7 +12474,7 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, readBuf_p += ech->encLen; ato16(readBuf_p, &ech->innerClientHelloLen); - ech->innerClientHelloLen -= AES_BLOCK_SIZE; + ech->innerClientHelloLen -= WC_AES_BLOCK_SIZE; readBuf_p += 2; ech->outerClientPayload = readBuf_p; @@ -12384,7 +12490,7 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, /* set the ech payload of the copy to zeros */ XMEMSET(aadCopy + (readBuf_p - ech->aad), 0, - ech->innerClientHelloLen + AES_BLOCK_SIZE); + ech->innerClientHelloLen + WC_AES_BLOCK_SIZE); /* allocate the inner payload buffer */ ech->innerClientHello = @@ -13376,6 +13482,52 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) #endif #ifdef WOLFSSL_HAVE_KYBER +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_KYBER +#ifndef WOLFSSL_NO_ML_KEM_512 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_512, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_ML_KEM_512, + ssl->heap); +#endif +#ifndef WOLFSSL_NO_ML_KEM_768 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_768, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_768, + ssl->heap); +#endif +#ifndef WOLFSSL_NO_ML_KEM_1024 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_1024, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_ML_KEM_1024, + ssl->heap); +#endif +#elif defined(HAVE_LIBOQS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_512, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_768, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_1024, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_ML_KEM_512, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_768, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_ML_KEM_1024, + ssl->heap); +#endif /* HAVE_LIBOQS */ +#endif /* !WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_WC_KYBER #ifdef WOLFSSL_KYBER512 if (ret == WOLFSSL_SUCCESS) @@ -13419,6 +13571,7 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5, ssl->heap); #endif /* HAVE_LIBOQS */ +#endif /* WOLFSSL_KYBER_ORIGINAL */ #endif /* WOLFSSL_HAVE_KYBER */ (void)ssl; @@ -13454,7 +13607,8 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) return ret; #endif /* HAVE_RPK */ -#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) +#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) && \ + !defined(WOLFSSL_NO_TLS12) if (!ssl->options.disallowEncThenMac) { ret = TLSX_EncryptThenMac_Use(ssl); if (ret != 0) @@ -13627,11 +13781,6 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) word64 now, milli; #endif - if (sess->ticketLen > MAX_PSK_ID_LEN) { - WOLFSSL_MSG("Session ticket length for PSK ext is too large"); - return BUFFER_ERROR; - } - /* Determine the MAC algorithm for the cipher suite used. */ ssl->options.cipherSuite0 = sess->cipherSuite0; ssl->options.cipherSuite = sess->cipherSuite; @@ -14762,9 +14911,9 @@ static word16 TLSX_GetMinSize_Client(word16* type) return 0; } } - #define TLSX_GET_MIN_SIZE_CLIENT TLSX_GetMinSize_Client + #define TLSX_GET_MIN_SIZE_CLIENT(type) TLSX_GetMinSize_Client(type) #else - #define TLSX_GET_MIN_SIZE_CLIENT(...) 0 + #define TLSX_GET_MIN_SIZE_CLIENT(type) 0 #endif @@ -14831,9 +14980,9 @@ static word16 TLSX_GetMinSize_Server(const word16 *type) return 0; } } - #define TLSX_GET_MIN_SIZE_SERVER TLSX_GetMinSize_Server + #define TLSX_GET_MIN_SIZE_SERVER(type) TLSX_GetMinSize_Server(type) #else - #define TLSX_GET_MIN_SIZE_SERVER(...) 0 + #define TLSX_GET_MIN_SIZE_SERVER(type) 0 #endif @@ -15038,9 +15187,8 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #ifdef WOLFSSL_DUAL_ALG_CERTS case TLSX_CKS: WOLFSSL_MSG("CKS extension received"); - if (!IsAtLeastTLSv1_3(ssl->version) || - (msgType != client_hello && - msgType != encrypted_extensions)) { + if (msgType != client_hello && + msgType != encrypted_extensions) { WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED); return EXT_NOT_ALLOWED; } @@ -15529,7 +15677,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #elif defined(WOLFSSL_ALLOW_TLSV10) InitSSL_Method(method, MakeTLSv1()); #else - #error No TLS version enabled! + #error No TLS version enabled! Consider using NO_TLS or WOLFCRYPT_ONLY. #endif method->downgrade = 1; @@ -15904,7 +16052,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, #elif defined(WOLFSSL_ALLOW_TLSV10) InitSSL_Method(method, MakeTLSv1()); #else - #error No TLS version enabled! + #error No TLS version enabled! Consider using NO_TLS or WOLFCRYPT_ONLY. #endif method->downgrade = 1; diff --git a/src/src/tls13.c b/src/src/tls13.c index e826893..a1a1783 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -2413,6 +2413,9 @@ static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out) if (seq[1] > ssl->keys.sequence_number_lo) ssl->keys.sequence_number_hi++; } +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_MSG_EX("TLS 1.3 Write Sequence %d %d", seq[0], seq[1]); +#endif c32toa(seq[0], out); c32toa(seq[1], out + OPAQUE32_LEN); @@ -2428,14 +2431,11 @@ static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out) static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv, int order) { - int i; - + int seq_offset = AEAD_NONCE_SZ - SEQ_SZ; /* The nonce is the IV with the sequence XORed into the last bytes. */ - WriteSEQTls13(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ); - for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++) - nonce[i] = iv[i]; - for (; i < AEAD_NONCE_SZ; i++) - nonce[i] ^= iv[i]; + WriteSEQTls13(ssl, order, nonce + seq_offset); + XMEMCPY(nonce, iv, seq_offset); + xorbuf(nonce + seq_offset, iv + seq_offset, SEQ_SZ); } #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) @@ -3621,6 +3621,7 @@ int CreateCookieExt(const WOLFSSL* ssl, byte* hash, word16 hashSz, #ifdef WOLFSSL_DTLS13 /* Tie cookie to peer address */ if (ret == 0) { + /* peerLock not necessary. Still in handshake phase. */ if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) { ret = wc_HmacUpdate(&cookieHmac, (byte*)ssl->buffers.dtlsCtx.peer.sa, @@ -4018,6 +4019,10 @@ static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx) WOLFSSL_ENTER("WritePSKBinders"); + if (idx > WOLFSSL_MAX_16BIT) { + return INPUT_SIZE_E; + } + ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY); if (ext == NULL) return SANITY_MSG_E; @@ -4033,7 +4038,7 @@ static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx) #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(ssl, 0), - idx - Dtls13GetRlHeaderLength(ssl, 0)); + (word16)idx - Dtls13GetRlHeaderLength(ssl, 0)); else #endif /* WOLFSSL_DTLS13 */ ret = HashOutput(ssl, output, (int)idx, 0); @@ -5285,7 +5290,9 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, defined(WOLFSSL_WPAS_SMALL) /* Check if client has disabled TLS 1.2 */ if (args->pv.minor == TLSv1_2_MINOR && - (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) { + (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) + == WOLFSSL_OP_NO_TLSv1_2) + { WOLFSSL_MSG("\tOption set to not allow TLSv1.2"); WOLFSSL_ERROR_VERBOSE(VERSION_ERROR); return VERSION_ERROR; @@ -6268,7 +6275,7 @@ static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz, return ret; if (*usingPSK != 0) { - word16 modes; + word32 modes; #ifdef WOLFSSL_EARLY_DATA TLSX* extEarlyData; @@ -6403,6 +6410,7 @@ int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie, word16 cookieSz) #ifdef WOLFSSL_DTLS13 /* Tie cookie to peer address */ if (ret == 0) { + /* peerLock not necessary. Still in handshake phase. */ if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) { ret = wc_HmacUpdate(&cookieHmac, (byte*)ssl->buffers.dtlsCtx.peer.sa, @@ -7930,6 +7938,27 @@ static void EncodeDualSigAlg(byte sigAlg, byte altSigAlg, byte* output) } #endif /* WOLFSSL_DUAL_ALG_CERTS */ +static enum wc_MACAlgorithm GetNewSAHashAlgo(int typeIn) +{ + switch (typeIn) { + case RSA_PSS_RSAE_SHA256_MINOR: + case RSA_PSS_PSS_SHA256_MINOR: + return sha256_mac; + + case RSA_PSS_RSAE_SHA384_MINOR: + case RSA_PSS_PSS_SHA384_MINOR: + return sha384_mac; + + case RSA_PSS_RSAE_SHA512_MINOR: + case RSA_PSS_PSS_SHA512_MINOR: + case ED25519_SA_MINOR: + case ED448_SA_MINOR: + return sha512_mac; + default: + return no_mac; + } +} + /* Decode the signature algorithm. * * input The encoded signature algorithm. @@ -7954,17 +7983,23 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, break; #endif case NEW_SA_MAJOR: - /* PSS signatures: 0x080[4-6] */ - if (input[1] >= sha256_mac && input[1] <= sha512_mac) { + *hashAlgo = GetNewSAHashAlgo(input[1]); + + /* PSS encryption: 0x080[4-6] */ + if (input[1] >= RSA_PSS_RSAE_SHA256_MINOR && + input[1] <= RSA_PSS_RSAE_SHA512_MINOR) { + *hsType = input[0]; + } + /* PSS signature: 0x080[9-B] */ + else if (input[1] >= RSA_PSS_PSS_SHA256_MINOR && + input[1] <= RSA_PSS_PSS_SHA512_MINOR) { *hsType = input[0]; - *hashAlgo = input[1]; } #ifdef HAVE_ED25519 /* ED25519: 0x0807 */ else if (input[1] == ED25519_SA_MINOR) { *hsType = ed25519_sa_algo; /* Hash performed as part of sign/verify operation. */ - *hashAlgo = sha512_mac; } #endif #ifdef HAVE_ED448 @@ -7972,7 +8007,6 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, else if (input[1] == ED448_SA_MINOR) { *hsType = ed448_sa_algo; /* Hash performed as part of sign/verify operation. */ - *hashAlgo = sha512_mac; } #endif else @@ -8998,7 +9032,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) return 0; /* sent blank cert, can't verify */ } - args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA; + args->sendSz = WC_MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA; /* Always encrypted. */ args->sendSz += MAX_MSG_EXTRA; @@ -9590,11 +9624,17 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) else #endif { + #ifdef HAVE_PK_CALLBACKS + buffer tmp; + + tmp.length = ssl->buffers.key->length; + tmp.buffer = ssl->buffers.key->buffer; + #endif ret = EccVerify(ssl, sigOut, args->sigLen, args->sigData, args->sigDataSz, (ecc_key*)ssl->hsKey, #ifdef HAVE_PK_CALLBACKS - ssl->buffers.key + &tmp #else NULL #endif @@ -9655,7 +9695,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) if (ssl->options.dtls) { ssl->options.buildingMsg = 0; ret = Dtls13HandshakeSend(ssl, args->output, - MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA + MAX_MSG_EXTRA, + WC_MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA + MAX_MSG_EXTRA, (word16)args->sendSz, certificate_verify, 1); if (ret != 0) goto exit_scv; @@ -9666,7 +9706,7 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) /* This message is always encrypted. */ ret = BuildTls13Message(ssl, args->output, - MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA, + WC_MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA, args->output + RECORD_HEADER_SZ, args->sendSz - RECORD_HEADER_SZ, handshake, 1, 0, 0); @@ -10853,15 +10893,19 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } if (sniff == NO_SNIFF) { + ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz); #ifdef WOLFSSL_HAVE_TLS_UNIQUE + if (finishedSz > TLS_FINISHED_SZ_MAX) { + return BUFFER_ERROR; + } if (ssl->options.side == WOLFSSL_CLIENT_END) { XMEMCPY(ssl->serverFinished, mac, finishedSz); - ssl->serverFinished_len = finishedSz; + ssl->serverFinished_len = (byte)finishedSz; } else { XMEMCPY(ssl->clientFinished, mac, finishedSz); - ssl->clientFinished_len = finishedSz; + ssl->clientFinished_len = (byte)finishedSz; } #endif /* WOLFSSL_HAVE_TLS_UNIQUE */ if (ret != 0) @@ -10889,6 +10933,7 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Force input exhaustion at ProcessReply by consuming padSz. */ *inOutIdx += size + ssl->keys.padSz; +#ifndef NO_WOLFSSL_SERVER if (ssl->options.side == WOLFSSL_SERVER_END && !ssl->options.handShakeDone) { #ifdef WOLFSSL_EARLY_DATA @@ -10901,6 +10946,7 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) return ret; } +#endif #ifndef NO_WOLFSSL_CLIENT if (ssl->options.side == WOLFSSL_CLIENT_END) @@ -10943,7 +10989,7 @@ int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, */ static int SendTls13Finished(WOLFSSL* ssl) { - int finishedSz = ssl->specs.hash_size; + byte finishedSz = ssl->specs.hash_size; byte* input; byte* output; int ret; @@ -11133,14 +11179,14 @@ static int SendTls13Finished(WOLFSSL* ssl) !ssl->options.handShakeDone) { #ifdef WOLFSSL_EARLY_DATA if (ssl->earlyData != no_early_data) { - if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE, + if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_SIDE_ONLY, 1)) != 0) { return ret; } } #endif /* Setup keys for application data messages. */ - if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0) + if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) return ret; #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) @@ -11803,9 +11849,9 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) { byte* output; int ret; + word32 length; int sendSz; word16 extSz; - word32 length; word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND); @@ -11876,7 +11922,7 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) /* Nonce */ length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ; - sendSz = (int)(idx + length + MAX_MSG_EXTRA); + sendSz = (word16)(idx + length + MAX_MSG_EXTRA); /* Check buffers are big enough and grow if needed. */ if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) @@ -11932,6 +11978,10 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) idx += EXTS_SZ; #endif + if (idx > WOLFSSL_MAX_16BIT) { + return BAD_LENGTH_E; + } + ssl->options.haveSessionId = 1; SetupSession(ssl); @@ -11944,12 +11994,15 @@ static int SendTls13NewSessionTicket(WOLFSSL* ssl) #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) - return Dtls13HandshakeSend(ssl, output, sendSz, idx, session_ticket, 0); + return Dtls13HandshakeSend(ssl, output, (word16)sendSz, + (word16)idx, session_ticket, 0); #endif /* WOLFSSL_DTLS13 */ /* This message is always encrypted. */ - sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, - idx - RECORD_HEADER_SZ, handshake, 0, 0, 0); + sendSz = BuildTls13Message(ssl, output, sendSz, + output + RECORD_HEADER_SZ, + (word16)idx - RECORD_HEADER_SZ, + handshake, 0, 0, 0); if (sendSz < 0) return sendSz; @@ -12797,7 +12850,7 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, #ifdef WOLFSSL_QUIC if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData != no_early_data) { /* QUIC never sends/receives EndOfEarlyData, but having - * early data means the last encrpytion keys had not been + * early data means the last encryption keys had not been * set yet. */ if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) return ret; @@ -12808,12 +12861,21 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->earlyData == no_early_data)) != 0) { return ret; } + if (ssl->earlyData != no_early_data) { + if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, + 1)) != 0) { + return ret; + } + } #else if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) { return ret; } #endif + /* Setup keys for application data messages. */ + if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) + return ret; } #ifdef WOLFSSL_POST_HANDSHAKE_AUTH if (type == certificate_request && @@ -13033,7 +13095,7 @@ int wolfSSL_connect_TLSv13(WOLFSSL* ssl) } /* make sure this wolfSSL object has arrays and rng setup. Protects - * case where the WOLFSSL object is re-used via wolfSSL_clear() */ + * case where the WOLFSSL object is reused via wolfSSL_clear() */ if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { return ret; } @@ -13953,8 +14015,7 @@ void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); } /* Set the PSK callback that returns the cipher suite for a client to use @@ -14006,8 +14067,7 @@ void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); } /* Set the PSK callback that returns the cipher suite for a server to use @@ -14056,8 +14116,7 @@ void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl, InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE, ssl->options.haveDH, ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, ssl->options.haveStaticECC, - ssl->options.haveFalconSig, ssl->options.haveDilithiumSig, - ssl->options.useAnon, TRUE, ssl->options.side); + ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side); } /* Get name of first supported cipher suite that uses the hash indicated. @@ -14134,7 +14193,7 @@ int wolfSSL_accept_TLSv13(WOLFSSL* ssl) } /* make sure this wolfSSL object has arrays and rng setup. Protects - * case where the WOLFSSL object is re-used via wolfSSL_clear() */ + * case where the WOLFSSL object is reused via wolfSSL_clear() */ if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) { return ret; } diff --git a/src/src/wolfio.c b/src/src/wolfio.c index a632ff8..5e62e9f 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -32,6 +32,15 @@ #ifndef WOLFCRYPT_ONLY +#if defined(HAVE_ERRNO_H) && defined(WOLFSSL_NO_SOCK) && \ + (defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT)) + /* error codes are needed for TranslateIoReturnCode() and + * wolfIO_TcpConnect() even if defined(WOLFSSL_NO_SOCK), which inhibits + * inclusion of errno.h by wolfio.h. + */ + #include +#endif + #ifdef _WIN32_WCE /* On WinCE winsock2.h must be included before windows.h for socket stuff */ #include @@ -116,7 +125,7 @@ Possible IO enable options: * * DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER: This flag has effect only if * ASN_NO_TIME is enabled. If enabled invalid peers messages are ignored - * indefinetely. If not enabled EmbedReceiveFrom will return timeout after + * indefinitely. If not enabled EmbedReceiveFrom will return timeout after * DTLS_RECEIVEFROM_MAX_INVALID_PEER number of packets from invalid peers. When * enabled, without a timer, EmbedReceivefrom can't check if the timeout is * expired and it may never return under a continuous flow of invalid packets. @@ -251,7 +260,7 @@ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) NULL); WOLFSSL_MSG(errstr); #else - WOLFSSL_MSG("\tGeneral error"); + WOLFSSL_MSG_EX("\tGeneral error: %d", err); #endif return WOLFSSL_CBIO_ERR_GENERAL; } @@ -260,12 +269,12 @@ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) #ifdef OPENSSL_EXTRA #ifndef NO_BIO -int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) +int wolfSSL_BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx) { return SslBioSend(ssl, buf, sz, ctx); } -int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) +int wolfSSL_BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx) { return SslBioReceive(ssl, buf, sz, ctx); } @@ -560,7 +569,7 @@ STATIC int nucyassl_sendto(INT sd, CHAR *buf, UINT16 sz, INT16 flags, #define DTLS_RECVFROM_FUNCTION recvfrom #endif -static int sockAddrEqual( +int sockAddrEqual( SOCKADDR_S *a, XSOCKLENT aLen, SOCKADDR_S *b, XSOCKLENT bLen) { if (aLen != bLen) @@ -651,8 +660,17 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) word32 invalidPeerPackets = 0; #endif int newPeer = 0; + int ret = 0; WOLFSSL_ENTER("EmbedReceiveFrom"); + (void)ret; /* possibly unused */ + + XMEMSET(&lclPeer, 0, sizeof(lclPeer)); + +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif if (dtlsCtx->connected) { peer = NULL; @@ -661,33 +679,32 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) #ifndef WOLFSSL_IPV6 if (PeerIsIpv6((SOCKADDR_S*)dtlsCtx->peer.sa, dtlsCtx->peer.sz)) { WOLFSSL_MSG("ipv6 dtls peer set but no ipv6 support compiled"); - return NOT_COMPILED_IN; + ret = WOLFSSL_CBIO_ERR_GENERAL; } #endif peer = &lclPeer; - XMEMSET(&lclPeer, 0, sizeof(lclPeer)); peerSz = sizeof(lclPeer); } else { /* Store the peer address. It is used to calculate the DTLS cookie. */ - if (dtlsCtx->peer.sa == NULL) { - dtlsCtx->peer.sa = (void*)XMALLOC(sizeof(SOCKADDR_S), - ssl->heap, DYNAMIC_TYPE_SOCKADDR); - dtlsCtx->peer.sz = 0; - if (dtlsCtx->peer.sa != NULL) - dtlsCtx->peer.bufSz = sizeof(SOCKADDR_S); - else - dtlsCtx->peer.bufSz = 0; - newPeer = 1; - peer = (SOCKADDR_S*)dtlsCtx->peer.sa; - } - else { - peer = &lclPeer; - XMEMCPY(peer, (SOCKADDR_S*)dtlsCtx->peer.sa, sizeof(lclPeer)); + newPeer = dtlsCtx->peer.sa == NULL || !ssl->options.dtlsStateful; + peer = &lclPeer; + if (dtlsCtx->peer.sa != NULL) { + XMEMCPY(peer, (SOCKADDR_S*)dtlsCtx->peer.sa, MIN(sizeof(lclPeer), + dtlsCtx->peer.sz)); } - peerSz = dtlsCtx->peer.bufSz; + peerSz = sizeof(lclPeer); } +#ifdef WOLFSSL_RW_THREADED + /* We make a copy above to avoid holding the lock for the entire function */ + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif + + if (ret != 0) + return ret; + /* Don't use ssl->options.handShakeDone since it is true even if * we are in the process of renegotiation */ doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE; @@ -696,12 +713,9 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) { doDtlsTimeout = doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL; #ifdef WOLFSSL_RW_THREADED - { - int ret = wc_LockMutex(&ssl->dtls13Rtx.mutex); - if (ret < 0) { - return ret; - } - } + ret = wc_LockMutex(&ssl->dtls13Rtx.mutex); + if (ret != 0) + return ret; #endif doDtlsTimeout = doDtlsTimeout || (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL); @@ -772,26 +786,16 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } #endif /* !NO_ASN_TIME */ - recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, ssl->rflags, - (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL); - - /* From the RECV(2) man page - * The returned address is truncated if the buffer provided is too - * small; in this case, addrlen will return a value greater than was - * supplied to the call. - */ - if (dtlsCtx->connected) { - /* No need to sanitize the value of peerSz */ - } - else if (dtlsCtx->userSet) { - /* Truncate peer size */ - if (peerSz > (XSOCKLENT)sizeof(lclPeer)) - peerSz = (XSOCKLENT)sizeof(lclPeer); - } - else { - /* Truncate peer size */ - if (peerSz > (XSOCKLENT)dtlsCtx->peer.bufSz) - peerSz = (XSOCKLENT)dtlsCtx->peer.bufSz; + { + XSOCKLENT inPeerSz = peerSz; + recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, (size_t)sz, + ssl->rflags, (SOCKADDR*)peer, peer != NULL ? &inPeerSz : NULL); + /* Truncate peerSz. From the RECV(2) man page + * The returned address is truncated if the buffer provided is too + * small; in this case, addrlen will return a value greater than was + * supplied to the call. + */ + peerSz = MIN(peerSz, inPeerSz); } recvd = TranslateIoReturnCode(recvd, sd, SOCKET_RECEIVING); @@ -820,11 +824,23 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } else if (dtlsCtx->userSet) { /* Check we received the packet from the correct peer */ + int ignore = 0; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif if (dtlsCtx->peer.sz > 0 && (peerSz != (XSOCKLENT)dtlsCtx->peer.sz || !sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa, dtlsCtx->peer.sz))) { WOLFSSL_MSG(" Ignored packet from invalid peer"); + ignore = 1; + } +#ifdef WOLFSSL_RW_THREADED + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif + if (ignore) { #if defined(NO_ASN_TIME) && \ !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) if (doDtlsTimeout) { @@ -840,13 +856,27 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) } else { if (newPeer) { - /* Store size of saved address */ - dtlsCtx->peer.sz = peerSz; + /* Store size of saved address. Locking handled internally. */ + if (wolfSSL_dtls_set_peer(ssl, peer, peerSz) != WOLFSSL_SUCCESS) + return WOLFSSL_CBIO_ERR_GENERAL; } #ifndef WOLFSSL_PEER_ADDRESS_CHANGES - else if ((dtlsCtx->peer.sz != (unsigned int)peerSz) || - (XMEMCMP(peer, dtlsCtx->peer.sa, peerSz) != 0)) { - return WOLFSSL_CBIO_ERR_GENERAL; + else { + ret = 0; +#ifdef WOLFSSL_RW_THREADED + if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif + if (!sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa, + dtlsCtx->peer.sz)) { + ret = WOLFSSL_CBIO_ERR_GENERAL; + } +#ifdef WOLFSSL_RW_THREADED + if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) + return WOLFSSL_CBIO_ERR_GENERAL; +#endif + if (ret != 0) + return ret; } #endif } @@ -1032,7 +1062,7 @@ int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx) } ((SOCKADDR_IN*)&addr)->sin_port = XHTONS(port); - /* peer sa is free'd in SSL_ResourceFree */ + /* peer sa is free'd in wolfSSL_ResourceFree */ if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN*)&addr, sizeof(SOCKADDR_IN)))!= WOLFSSL_SUCCESS) { WOLFSSL_MSG("Import DTLS peer info error"); @@ -1049,7 +1079,7 @@ int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx) } ((SOCKADDR_IN6*)&addr)->sin6_port = XHTONS(port); - /* peer sa is free'd in SSL_ResourceFree */ + /* peer sa is free'd in wolfSSL_ResourceFree */ if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN6*)&addr, sizeof(SOCKADDR_IN6)))!= WOLFSSL_SUCCESS) { WOLFSSL_MSG("Import DTLS peer info error"); @@ -2342,6 +2372,20 @@ void wolfSSL_SSLSetIOSend(WOLFSSL *ssl, CallbackIOSend CBIOSend) } } +void wolfSSL_SSLDisableRead(WOLFSSL *ssl) +{ + if (ssl) { + ssl->options.disableRead = 1; + } +} + +void wolfSSL_SSLEnableRead(WOLFSSL *ssl) +{ + if (ssl) { + ssl->options.disableRead = 0; + } +} + void wolfSSL_SetIOReadCtx(WOLFSSL* ssl, void *rctx) { diff --git a/src/src/x509.c b/src/src/x509.c index 18feff0..d656815 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -49,10 +49,10 @@ unsigned int wolfSSL_X509_get_extension_flags(WOLFSSL_X509* x509) if (x509 != NULL) { if (x509->keyUsageSet) { - flags |= EXFLAG_KUSAGE; + flags |= WOLFSSL_EXFLAG_KUSAGE; } if (x509->extKeyUsageSrc != NULL) { - flags |= EXFLAG_XKUSAGE; + flags |= WOLFSSL_EXFLAG_XKUSAGE; } } @@ -92,19 +92,19 @@ unsigned int wolfSSL_X509_get_extended_key_usage(WOLFSSL_X509* x509) if (x509 != NULL) { if (x509->extKeyUsage & EXTKEYUSE_OCSP_SIGN) - ret |= XKU_OCSP_SIGN; + ret |= WOLFSSL_XKU_OCSP_SIGN; if (x509->extKeyUsage & EXTKEYUSE_TIMESTAMP) - ret |= XKU_TIMESTAMP; + ret |= WOLFSSL_XKU_TIMESTAMP; if (x509->extKeyUsage & EXTKEYUSE_EMAILPROT) - ret |= XKU_SMIME; + ret |= WOLFSSL_XKU_SMIME; if (x509->extKeyUsage & EXTKEYUSE_CODESIGN) - ret |= XKU_CODE_SIGN; + ret |= WOLFSSL_XKU_CODE_SIGN; if (x509->extKeyUsage & EXTKEYUSE_CLIENT_AUTH) - ret |= XKU_SSL_CLIENT; + ret |= WOLFSSL_XKU_SSL_CLIENT; if (x509->extKeyUsage & EXTKEYUSE_SERVER_AUTH) - ret |= XKU_SSL_SERVER; + ret |= WOLFSSL_XKU_SSL_SERVER; if (x509->extKeyUsage & EXTKEYUSE_ANY) - ret |= XKU_ANYEKU; + ret |= WOLFSSL_XKU_ANYEKU; } WOLFSSL_LEAVE("wolfSSL_X509_get_extended_key_usage", ret); @@ -314,7 +314,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_create_by_OBJ( if (ret == NULL) { err = 1; } - } else { + } + else { /* Prevent potential memory leaks and dangling pointers. */ wolfSSL_ASN1_OBJECT_free(ret->obj); ret->obj = NULL; @@ -360,7 +361,8 @@ WOLFSSL_STACK* wolfSSL_sk_new_x509_ext(void) /* This function does NOT return 1 on success. It returns 0 on fail, and the * number of items in the stack upon success. This is for compatibility with * OpenSSL. */ -int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk,WOLFSSL_X509_EXTENSION* ext) +int wolfSSL_sk_X509_EXTENSION_push(WOLFSSL_STACK* sk, + WOLFSSL_X509_EXTENSION* ext) { WOLFSSL_ENTER("wolfSSL_sk_X509_EXTENSION_push"); @@ -532,7 +534,7 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, goto err; } - tag = V_ASN1_UTF8STRING; + tag = WOLFSSL_V_ASN1_UTF8STRING; } else #endif @@ -555,7 +557,7 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, len -= idx; /* Set the tag to object so that it gets output in raw form */ - tag = V_ASN1_SEQUENCE; + tag = WOLFSSL_V_ASN1_SEQUENCE; } @@ -587,6 +589,76 @@ static int wolfssl_dns_entry_othername_to_gn(DNS_entry* dns, #endif /* OPENSSL_ALL || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) +static int DNS_to_GENERAL_NAME(WOLFSSL_GENERAL_NAME* gn, DNS_entry* dns) +{ + gn->type = dns->type; + switch (gn->type) { + case WOLFSSL_GEN_OTHERNAME: + if (!wolfssl_dns_entry_othername_to_gn(dns, gn)) { + WOLFSSL_MSG("OTHERNAME set failed"); + return WOLFSSL_FAILURE; + } + break; + + case WOLFSSL_GEN_EMAIL: + case WOLFSSL_GEN_DNS: + case WOLFSSL_GEN_URI: + case WOLFSSL_GEN_IPADD: + case WOLFSSL_GEN_IA5: + gn->d.ia5->length = dns->len; + if (wolfSSL_ASN1_STRING_set(gn->d.ia5, dns->name, + gn->d.ia5->length) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ASN1_STRING_set failed"); + return WOLFSSL_FAILURE; + } + break; + + + case WOLFSSL_GEN_DIRNAME: + /* wolfSSL_GENERAL_NAME_new() mallocs this by default */ + wolfSSL_ASN1_STRING_free(gn->d.ia5); + gn->d.ia5 = NULL; + + gn->d.dirn = wolfSSL_X509_NAME_new();; + /* @TODO extract dir name info from DNS_entry */ + break; + +#ifdef WOLFSSL_RID_ALT_NAME + case WOLFSSL_GEN_RID: + /* wolfSSL_GENERAL_NAME_new() mallocs this by default */ + wolfSSL_ASN1_STRING_free(gn->d.ia5); + gn->d.ia5 = NULL; + + gn->d.registeredID = wolfSSL_ASN1_OBJECT_new(); + if (gn->d.registeredID == NULL) { + return WOLFSSL_FAILURE; + } + gn->d.registeredID->obj = (const unsigned char*)XMALLOC(dns->len, + gn->d.registeredID->heap, DYNAMIC_TYPE_ASN1); + if (gn->d.registeredID->obj == NULL) { + /* registeredID gets free'd up by caller after failure */ + return WOLFSSL_FAILURE; + } + gn->d.registeredID->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; + XMEMCPY((byte*)gn->d.registeredID->obj, dns->ridString, dns->len); + gn->d.registeredID->objSz = dns->len; + gn->d.registeredID->grp = oidCertExtType; + gn->d.registeredID->nid = WC_NID_registeredAddress; + break; +#endif + + case WOLFSSL_GEN_X400: + /* Unsupported: fall through */ + case WOLFSSL_GEN_EDIPARTY: + /* Unsupported: fall through */ + default: + WOLFSSL_MSG("Unsupported type conversion"); + return WOLFSSL_FAILURE; + } + return WOLFSSL_SUCCESS; +} + + static int wolfssl_x509_alt_names_to_gn(WOLFSSL_X509* x509, WOLFSSL_X509_EXTENSION* ext) { @@ -624,24 +696,10 @@ static int wolfssl_x509_alt_names_to_gn(WOLFSSL_X509* x509, goto err; } - gn->type = dns->type; - if (gn->type == GEN_OTHERNAME) { - if (!wolfssl_dns_entry_othername_to_gn(dns, gn)) { - WOLFSSL_MSG("OTHERNAME set failed"); - wolfSSL_GENERAL_NAME_free(gn); - wolfSSL_sk_pop_free(sk, NULL); - goto err; - } - } - else { - gn->d.ia5->length = dns->len; - if (wolfSSL_ASN1_STRING_set(gn->d.ia5, dns->name, - gn->d.ia5->length) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("ASN1_STRING_set failed"); - wolfSSL_GENERAL_NAME_free(gn); - wolfSSL_sk_pop_free(sk, NULL); - goto err; - } + if (DNS_to_GENERAL_NAME(gn, dns) != WOLFSSL_SUCCESS) { + wolfSSL_GENERAL_NAME_free(gn); + wolfSSL_sk_pop_free(sk, NULL); + goto err; } if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) <= 0) { @@ -685,12 +743,12 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) WOLFSSL_ENTER("wolfSSL_X509_set_ext"); - if(x509 == NULL){ + if (x509 == NULL) { WOLFSSL_MSG("\tNot passed a certificate"); return NULL; } - if(loc <0 || (loc > wolfSSL_X509_get_ext_count(x509))){ + if (loc < 0 || (loc > wolfSSL_X509_get_ext_count(x509))) { WOLFSSL_MSG("\tBad location argument"); return NULL; } @@ -922,7 +980,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) obj->obj = (byte*)x509->authInfoCaIssuer; obj->objSz = (unsigned int)x509->authInfoCaIssuerSz; obj->grp = oidCertAuthInfoType; - obj->nid = NID_ad_ca_issuers; + obj->nid = WC_NID_ad_ca_issuers; ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj) > 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; @@ -958,7 +1016,7 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) obj->obj = x509->authInfo; obj->objSz = (unsigned int)x509->authInfoSz; obj->grp = oidCertAuthInfoType; - obj->nid = NID_ad_OCSP; + obj->nid = WC_NID_ad_OCSP; ret = wolfSSL_sk_ASN1_OBJECT_push(sk, obj) > 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; @@ -1124,8 +1182,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } ext->obj->objSz = (unsigned int)objSz; - if(((ext->obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || - (ext->obj->obj == NULL)) { + if (((ext->obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || + (ext->obj->obj == NULL)) { ext->obj->obj =(byte*)XREALLOC((byte*)ext->obj->obj, ext->obj->objSz, NULL,DYNAMIC_TYPE_ASN1); @@ -1139,7 +1197,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) return NULL; } ext->obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; - } else { + } + else { ext->obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA; } /* Get OID from input and copy to ASN1_OBJECT buffer */ @@ -1177,7 +1236,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) #endif return NULL; } - ext->value.data = (char*)XMALLOC(length, NULL, DYNAMIC_TYPE_ASN1); + ext->value.data = (char*)XMALLOC(length, NULL, + DYNAMIC_TYPE_ASN1); ext->value.isDynamic = 1; if (ext->value.data == NULL) { WOLFSSL_MSG("Failed to malloc ASN1_STRING data"); @@ -1221,16 +1281,13 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error */ static int asn1_string_copy_to_buffer(WOLFSSL_ASN1_STRING* str, byte** buf, - word32* len, void* heap) { - if (!str || !buf || !len) { - return WOLFSSL_FAILURE; - } + word32* len, void* heap) +{ if (str->data && str->length > 0) { if (*buf) XFREE(*buf, heap, DYNAMIC_TYPE_X509_EXT); *len = 0; - *buf = (byte*)XMALLOC(str->length, heap, - DYNAMIC_TYPE_X509_EXT); + *buf = (byte*)XMALLOC(str->length, heap, DYNAMIC_TYPE_X509_EXT); if (!*buf) { WOLFSSL_MSG("malloc error"); return WOLFSSL_FAILURE; @@ -1243,7 +1300,8 @@ static int asn1_string_copy_to_buffer(WOLFSSL_ASN1_STRING* str, byte** buf, return WOLFSSL_SUCCESS; } -int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int loc) +int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, + int loc) { int nid; @@ -1256,7 +1314,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo nid = (ext->obj != NULL) ? ext->obj->type : ext->value.nid; switch (nid) { - case NID_authority_key_identifier: + case WC_NID_authority_key_identifier: if (x509->authKeyIdSrc != NULL) { /* If authKeyId points into authKeyIdSrc then free it and * revert to old functionality */ @@ -1271,7 +1329,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } x509->authKeyIdCrit = (byte)ext->crit; break; - case NID_subject_key_identifier: + case WC_NID_subject_key_identifier: if (asn1_string_copy_to_buffer(&ext->value, &x509->subjKeyId, &x509->subjKeyIdSz, x509->heap) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("asn1_string_copy_to_buffer error"); @@ -1279,7 +1337,7 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } x509->subjKeyIdCrit = (byte)ext->crit; break; - case NID_subject_alt_name: + case WC_NID_subject_alt_name: { WOLFSSL_GENERAL_NAMES* gns = ext->ext_sk; while (gns) { @@ -1323,11 +1381,14 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo x509->subjAltNameCrit = (byte)ext->crit; break; } - case NID_key_usage: + case WC_NID_key_usage: if (ext && ext->value.data) { if (ext->value.length == sizeof(word16)) { /* if ext->value is already word16, set directly */ x509->keyUsage = *(word16*)ext->value.data; +#ifdef BIG_ENDIAN_ORDER + x509->keyUsage = rotlFixed16(x509->keyUsage, 8U); +#endif x509->keyUsageCrit = (byte)ext->crit; x509->keyUsageSet = 1; } @@ -1345,10 +1406,10 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } } break; - case NID_ext_key_usage: + case WC_NID_ext_key_usage: if (ext && ext->value.data) { if (ext->value.length == sizeof(byte)) { - /* if ext->value is already word16, set directly */ + /* if ext->value is already 1 byte, set directly */ x509->extKeyUsage = *(byte*)ext->value.data; x509->extKeyUsageCrit = (byte)ext->crit; } @@ -1365,12 +1426,14 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo } } break; - case NID_basic_constraints: + case WC_NID_basic_constraints: if (ext->obj) { x509->isCa = (byte)ext->obj->ca; x509->basicConstCrit = (byte)ext->crit; - if (ext->obj->pathlen) + if (ext->obj->pathlen) { x509->pathLength = (word32)ext->obj->pathlen->length; + x509->basicConstPlSet = 1; + } x509->basicConstSet = 1; } break; @@ -1415,9 +1478,16 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo return WOLFSSL_FAILURE; } + /* ext->crit is WOLFSSL_ASN1_BOOLEAN */ + if (ext->crit != 0 && ext->crit != -1) { + XFREE(val, x509->heap, DYNAMIC_TYPE_X509_EXT); + XFREE(oid, x509->heap, DYNAMIC_TYPE_X509_EXT); + return WOLFSSL_FAILURE; + } + /* x509->custom_exts now owns the buffers and they must be managed. */ x509->custom_exts[x509->customExtCount].oid = oid; - x509->custom_exts[x509->customExtCount].crit = ext->crit; + x509->custom_exts[x509->customExtCount].crit = (byte)ext->crit; x509->custom_exts[x509->customExtCount].val = val; x509->custom_exts[x509->customExtCount].valSz = ext->value.length; x509->customExtCount++; @@ -1438,8 +1508,8 @@ int wolfSSL_X509_add_ext(WOLFSSL_X509 *x509, WOLFSSL_X509_EXTENSION *ext, int lo int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, unsigned long flag, int indent) { - ASN1_OBJECT* obj; - ASN1_STRING* str; + WOLFSSL_ASN1_OBJECT* obj; + WOLFSSL_ASN1_STRING* str; int nid; int rc = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); char tmp[CTC_NAME_SIZE*2 + 1]; @@ -1590,13 +1660,13 @@ int wolfSSL_X509_EXTENSION_set_critical(WOLFSSL_X509_EXTENSION* ex, int crit) * not NULL, get the NID of the extension object and populate the * extension type-specific X509V3_EXT_* function(s) in v3_ext_method. * - * Returns NULL on error or pointer to the v3_ext_method populated with extension - * type-specific X509V3_EXT_* function(s). + * Returns NULL on error or pointer to the v3_ext_method populated with + * extension type-specific X509V3_EXT_* function(s). * - * NOTE: NID_subject_key_identifier is currently the only extension implementing + * NOTE: WC_NID_subject_key_identifier is currently the only extension implementing * the X509V3_EXT_* functions, as it is the only type called directly by QT. The - * other extension types return a pointer to a v3_ext_method struct that contains - * only the NID. + * other extension types return a pointer to a v3_ext_method struct that + * contains only the NID. */ #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L const WOLFSSL_v3_ext_method* wolfSSL_X509V3_EXT_get(WOLFSSL_X509_EXTENSION* ex) @@ -1622,30 +1692,31 @@ WOLFSSL_v3_ext_method* wolfSSL_X509V3_EXT_get(WOLFSSL_X509_EXTENSION* ex) } XMEMSET(&method, 0, sizeof(WOLFSSL_v3_ext_method)); switch (nid) { - case NID_basic_constraints: + case WC_NID_basic_constraints: break; - case NID_subject_key_identifier: - method.i2s = (X509V3_EXT_I2S)wolfSSL_i2s_ASN1_STRING; + case WC_NID_subject_key_identifier: + method.i2s = (WOLFSSL_X509V3_EXT_I2S)wolfSSL_i2s_ASN1_STRING; break; - case NID_subject_alt_name: - WOLFSSL_MSG("i2v function not yet implemented for Subject Alternative Name"); + case WC_NID_subject_alt_name: + WOLFSSL_MSG("i2v function not yet implemented for Subject " + "Alternative Name"); break; - case NID_key_usage: + case WC_NID_key_usage: WOLFSSL_MSG("i2v function not yet implemented for Key Usage"); break; - case NID_authority_key_identifier: + case WC_NID_authority_key_identifier: WOLFSSL_MSG("i2v function not yet implemented for Auth Key Id"); break; - case NID_info_access: + case WC_NID_info_access: WOLFSSL_MSG("i2v function not yet implemented for Info Access"); break; - case NID_ext_key_usage: + case WC_NID_ext_key_usage: WOLFSSL_MSG("i2v function not yet implemented for Ext Key Usage"); break; - case NID_certificate_policies: + case WC_NID_certificate_policies: WOLFSSL_MSG("r2i function not yet implemented for Cert Policies"); break; - case NID_crl_distribution_points: + case WC_NID_crl_distribution_points: WOLFSSL_MSG("r2i function not yet implemented for CRL Dist Points"); break; default: @@ -1748,7 +1819,7 @@ static WOLFSSL_AUTHORITY_INFO_ACCESS* wolfssl_x509v3_ext_aia_d2i( } /* Set the type of general name to URI (only type supported). */ - ret = wolfSSL_GENERAL_NAME_set_type(ad->location, GEN_URI); + ret = wolfSSL_GENERAL_NAME_set_type(ad->location, WOLFSSL_GEN_URI); if (ret != WOLFSSL_SUCCESS) { err = 1; break; @@ -1812,27 +1883,27 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) WOLFSSL_ENTER("wolfSSL_X509V3_EXT_d2i"); - if(ext == NULL) { + if (ext == NULL) { WOLFSSL_MSG("Bad function Argument"); return NULL; } + object = wolfSSL_X509_EXTENSION_get_object(ext); + if (object == NULL) { + WOLFSSL_MSG("X509_EXTENSION_get_object failed"); + return NULL; + } /* extract extension info */ method = wolfSSL_X509V3_EXT_get(ext); if (method == NULL) { WOLFSSL_MSG("wolfSSL_X509V3_EXT_get error"); return NULL; } - object = wolfSSL_X509_EXTENSION_get_object(ext); - if (object == NULL) { - WOLFSSL_MSG("X509_EXTENSION_get_object failed"); - return NULL; - } /* Return pointer to proper internal structure based on NID */ switch (object->type) { /* basicConstraints */ - case (NID_basic_constraints): + case WC_NID_basic_constraints: WOLFSSL_MSG("basicConstraints"); /* Allocate new BASIC_CONSTRAINTS structure */ bc = wolfSSL_BASIC_CONSTRAINTS_new(); @@ -1842,7 +1913,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) } /* Copy pathlen and CA into BASIC_CONSTRAINTS from object */ bc->ca = object->ca; - if (object->pathlen->length > 0) { + if (object->pathlen != NULL && object->pathlen->length > 0) { bc->pathlen = wolfSSL_ASN1_INTEGER_dup(object->pathlen); if (bc->pathlen == NULL) { WOLFSSL_MSG("Failed to duplicate ASN1_INTEGER"); @@ -1855,7 +1926,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) return bc; /* subjectKeyIdentifier */ - case (NID_subject_key_identifier): + case WC_NID_subject_key_identifier: WOLFSSL_MSG("subjectKeyIdentifier"); asn1String = wolfSSL_X509_EXTENSION_get_data(ext); if (asn1String == NULL) { @@ -1878,7 +1949,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) return newString; /* authorityKeyIdentifier */ - case (NID_authority_key_identifier): + case WC_NID_authority_key_identifier: WOLFSSL_MSG("AuthorityKeyIdentifier"); akey = (WOLFSSL_AUTHORITY_KEYID*) @@ -1921,7 +1992,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) return akey; /* keyUsage */ - case (NID_key_usage): + case WC_NID_key_usage: WOLFSSL_MSG("keyUsage"); /* This may need to be updated for future use. The i2v method for keyUsage is not currently set. For now, return the ASN1_STRING @@ -1947,21 +2018,21 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) return newString; /* extKeyUsage */ - case (NID_ext_key_usage): + case WC_NID_ext_key_usage: WOLFSSL_MSG("extKeyUsage not supported yet"); return NULL; /* certificatePolicies */ - case (NID_certificate_policies): + case WC_NID_certificate_policies: WOLFSSL_MSG("certificatePolicies not supported yet"); return NULL; /* cRLDistributionPoints */ - case (NID_crl_distribution_points): + case WC_NID_crl_distribution_points: WOLFSSL_MSG("cRLDistributionPoints not supported yet"); return NULL; - case NID_subject_alt_name: + case WC_NID_subject_alt_name: if (ext->ext_sk == NULL) { WOLFSSL_MSG("Subject alt name stack NULL"); return NULL; @@ -1974,7 +2045,7 @@ void* wolfSSL_X509V3_EXT_d2i(WOLFSSL_X509_EXTENSION* ext) return sk; /* authorityInfoAccess */ - case NID_info_access: + case WC_NID_info_access: WOLFSSL_MSG("AuthorityInfoAccess"); return wolfssl_x509v3_ext_aia_d2i(ext); @@ -2009,12 +2080,12 @@ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) WOLFSSL_ENTER("wolfSSL_X509_get_ext_by_NID"); - if(x509 == NULL){ + if (x509 == NULL) { WOLFSSL_MSG("\tNot passed a certificate"); return WOLFSSL_FATAL_ERROR; } - if(lastPos < -1 || (lastPos > (wolfSSL_X509_get_ext_count(x509) - 1))){ + if (lastPos < -1 || (lastPos > (wolfSSL_X509_get_ext_count(x509) - 1))) { WOLFSSL_MSG("\tBad location argument"); return WOLFSSL_FATAL_ERROR; } @@ -2095,8 +2166,8 @@ int wolfSSL_X509_get_ext_by_NID(const WOLFSSL_X509* x509, int nid, int lastPos) if (extCount >= loc) { /* extCount >= loc. Now check if extension has been set */ - isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, (int)foundNID); - + isSet = wolfSSL_X509_ext_isSet_by_NID((WOLFSSL_X509*)x509, + (int)foundNID); if (isSet && ((word32)nid == foundNID)) { found = 1; break; @@ -2258,7 +2329,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, WOLFSSL_MSG("ASN1_STRING_set failed"); goto err; } - gn->d.dNSName->type = V_ASN1_IA5STRING; + gn->d.dNSName->type = WOLFSSL_V_ASN1_IA5STRING; } dns = dns->next; @@ -2296,7 +2367,7 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, goto err; } - if (wolfSSL_GENERAL_NAME_set_type(gn, GEN_URI) != + if (wolfSSL_GENERAL_NAME_set_type(gn, WOLFSSL_GEN_URI) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Error setting GENERAL_NAME type"); goto err; @@ -2362,7 +2433,8 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, if (x509->authKeyIdSet) { WOLFSSL_AUTHORITY_KEYID* akey = wolfSSL_AUTHORITY_KEYID_new(); if (!akey) { - WOLFSSL_MSG("Issue creating WOLFSSL_AUTHORITY_KEYID struct"); + WOLFSSL_MSG( + "Issue creating WOLFSSL_AUTHORITY_KEYID struct"); return NULL; } @@ -2430,7 +2502,8 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, for (i = 0; i < x509->certPoliciesNb - 1; i++) { obj = wolfSSL_ASN1_OBJECT_new(); if (obj == NULL) { - WOLFSSL_MSG("Issue creating WOLFSSL_ASN1_OBJECT struct"); + WOLFSSL_MSG( + "Issue creating WOLFSSL_ASN1_OBJECT struct"); wolfSSL_sk_ASN1_OBJECT_pop_free(sk, NULL); return NULL; } @@ -2743,9 +2816,6 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) { WOLFSSL_X509_EXTENSION* ext; - if (value == NULL) - return NULL; - ext = wolfSSL_X509_EXTENSION_new(); if (ext == NULL) { WOLFSSL_MSG("memory error"); @@ -2754,8 +2824,8 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) ext->value.nid = nid; switch (nid) { - case NID_subject_key_identifier: - case NID_authority_key_identifier: + case WC_NID_subject_key_identifier: + case WC_NID_authority_key_identifier: if (wolfSSL_ASN1_STRING_set(&ext->value, value, -1) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_set error"); @@ -2763,7 +2833,7 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) } ext->value.type = CTC_UTF8; break; - case NID_subject_alt_name: + case WC_NID_subject_alt_name: { WOLFSSL_GENERAL_NAMES* gns; WOLFSSL_GENERAL_NAME* gn; @@ -2802,7 +2872,7 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) gn->type = ASN_DNS_TYPE; break; } - case NID_key_usage: + case WC_NID_key_usage: if (wolfSSL_ASN1_STRING_set(&ext->value, value, -1) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_set error"); @@ -2810,7 +2880,7 @@ static WOLFSSL_X509_EXTENSION* createExtFromStr(int nid, const char *value) } ext->value.type = KEY_USAGE_OID; break; - case NID_ext_key_usage: + case WC_NID_ext_key_usage: if (wolfSSL_ASN1_STRING_set(&ext->value, value, -1) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_set error"); @@ -2901,22 +2971,22 @@ static void wolfSSL_X509V3_EXT_METHOD_populate(WOLFSSL_v3_ext_method *method, WOLFSSL_ENTER("wolfSSL_X509V3_EXT_METHOD_populate"); switch (nid) { - case NID_subject_key_identifier: - method->i2s = (X509V3_EXT_I2S)wolfSSL_i2s_ASN1_STRING; + case WC_NID_subject_key_identifier: + method->i2s = (WOLFSSL_X509V3_EXT_I2S)wolfSSL_i2s_ASN1_STRING; FALL_THROUGH; - case NID_authority_key_identifier: - case NID_key_usage: - case NID_certificate_policies: - case NID_policy_mappings: - case NID_subject_alt_name: - case NID_issuer_alt_name: - case NID_basic_constraints: - case NID_name_constraints: - case NID_policy_constraints: - case NID_ext_key_usage: - case NID_crl_distribution_points: - case NID_inhibit_any_policy: - case NID_info_access: + case WC_NID_authority_key_identifier: + case WC_NID_key_usage: + case WC_NID_certificate_policies: + case WC_NID_policy_mappings: + case WC_NID_subject_alt_name: + case WC_NID_issuer_alt_name: + case WC_NID_basic_constraints: + case WC_NID_name_constraints: + case WC_NID_policy_constraints: + case WC_NID_ext_key_usage: + case WC_NID_crl_distribution_points: + case WC_NID_inhibit_any_policy: + case WC_NID_info_access: WOLFSSL_MSG("Nothing to populate for current NID"); break; default: @@ -2928,7 +2998,7 @@ static void wolfSSL_X509V3_EXT_METHOD_populate(WOLFSSL_v3_ext_method *method, } /** - * @param nid One of the NID_* constants defined in asn.h + * @param nid One of the WC_NID_* constants defined in asn.h * @param crit * @param data This data is copied to the returned extension. * @return @@ -2952,9 +3022,9 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, wolfSSL_X509V3_EXT_METHOD_populate(&ext->ext_method, nid); switch (nid) { - case NID_subject_key_identifier: + case WC_NID_subject_key_identifier: /* WOLFSSL_ASN1_STRING */ - case NID_key_usage: + case WC_NID_key_usage: /* WOLFSSL_ASN1_STRING */ { asn1str = (WOLFSSL_ASN1_STRING*)data; @@ -2981,13 +3051,13 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, break; } - case NID_subject_alt_name: + case WC_NID_subject_alt_name: /* typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES */ - case NID_issuer_alt_name: + case WC_NID_issuer_alt_name: /* typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES */ - case NID_ext_key_usage: + case WC_NID_ext_key_usage: /* typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE */ - case NID_info_access: + case WC_NID_info_access: /* typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS */ { WOLFSSL_STACK* sk = (WOLFSSL_STACK*)data; @@ -3008,7 +3078,7 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, break; } - case NID_basic_constraints: + case WC_NID_basic_constraints: { /* WOLFSSL_BASIC_CONSTRAINTS */ WOLFSSL_BASIC_CONSTRAINTS* bc = (WOLFSSL_BASIC_CONSTRAINTS*)data; @@ -3028,7 +3098,7 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, } break; } - case NID_authority_key_identifier: + case WC_NID_authority_key_identifier: { /* AUTHORITY_KEYID */ WOLFSSL_AUTHORITY_KEYID* akey = (WOLFSSL_AUTHORITY_KEYID*)data; @@ -3055,22 +3125,22 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, } } else { - WOLFSSL_MSG("NID_authority_key_identifier empty data"); + WOLFSSL_MSG("WC_NID_authority_key_identifier empty data"); goto err_cleanup; } break; } - case NID_inhibit_any_policy: + case WC_NID_inhibit_any_policy: /* ASN1_INTEGER */ - case NID_certificate_policies: + case WC_NID_certificate_policies: /* STACK_OF(POLICYINFO) */ - case NID_policy_mappings: + case WC_NID_policy_mappings: /* STACK_OF(POLICY_MAPPING) */ - case NID_name_constraints: + case WC_NID_name_constraints: /* NAME_CONSTRAINTS */ - case NID_policy_constraints: + case WC_NID_policy_constraints: /* POLICY_CONSTRAINTS */ - case NID_crl_distribution_points: + case WC_NID_crl_distribution_points: /* typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS */ default: WOLFSSL_MSG("Unknown or unsupported NID"); @@ -3088,11 +3158,11 @@ WOLFSSL_X509_EXTENSION *wolfSSL_X509V3_EXT_i2d(int nid, int crit, } /* Returns pointer to ASN1_OBJECT from an X509_EXTENSION object */ -WOLFSSL_ASN1_OBJECT* wolfSSL_X509_EXTENSION_get_object \ - (WOLFSSL_X509_EXTENSION* ext) +WOLFSSL_ASN1_OBJECT* wolfSSL_X509_EXTENSION_get_object( + WOLFSSL_X509_EXTENSION* ext) { WOLFSSL_ENTER("wolfSSL_X509_EXTENSION_get_object"); - if(ext == NULL) + if (ext == NULL) return NULL; return ext->obj; } @@ -3121,7 +3191,8 @@ int wolfSSL_X509_EXTENSION_set_object(WOLFSSL_X509_EXTENSION* ext, #endif /* OPENSSL_ALL */ /* Returns pointer to ASN1_STRING in X509_EXTENSION object */ -WOLFSSL_ASN1_STRING* wolfSSL_X509_EXTENSION_get_data(WOLFSSL_X509_EXTENSION* ext) +WOLFSSL_ASN1_STRING* wolfSSL_X509_EXTENSION_get_data( + WOLFSSL_X509_EXTENSION* ext) { WOLFSSL_ENTER("wolfSSL_X509_EXTENSION_get_data"); if (ext == NULL) @@ -3231,6 +3302,7 @@ int wolfSSL_X509_pubkey_digest(const WOLFSSL_X509 *x509, #endif /* OPENSSL_EXTRA */ #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \ + defined(KEEP_OUR_CERT) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* user externally called free X509, if dynamic go ahead with free, otherwise @@ -3253,16 +3325,14 @@ static void ExternalFreeX509(WOLFSSL_X509* x509) if (ret != 0) { WOLFSSL_MSG("Couldn't lock x509 mutex"); } - #endif /* OPENSSL_EXTRA_X509_SMALL || OPENSSL_EXTRA */ - - #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) if (doFree) #endif /* OPENSSL_EXTRA_X509_SMALL || OPENSSL_EXTRA */ { FreeX509(x509); XFREE(x509, x509->heap, DYNAMIC_TYPE_X509); } - } else { + } + else { WOLFSSL_MSG("free called on non dynamic object, not freeing"); } } @@ -3272,10 +3342,13 @@ static void ExternalFreeX509(WOLFSSL_X509* x509) WOLFSSL_ABI void wolfSSL_X509_free(WOLFSSL_X509* x509) { - WOLFSSL_ENTER("wolfSSL_FreeX509"); + WOLFSSL_ENTER("wolfSSL_X509_free"); ExternalFreeX509(x509); } +#endif +#if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \ + defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* copy name into in buffer, at most sz bytes, if buffer is null will malloc buffer, call responsible for freeing */ @@ -3284,15 +3357,15 @@ char* wolfSSL_X509_NAME_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) { int copySz; + WOLFSSL_ENTER("wolfSSL_X509_NAME_oneline"); + if (name == NULL) { WOLFSSL_MSG("WOLFSSL_X509_NAME pointer was NULL"); return NULL; } - copySz = (int)min((word32)sz, (word32)name->sz); - - WOLFSSL_ENTER("wolfSSL_X509_NAME_oneline"); - if (!name->sz) return in; + if (name->sz == 0) + return in; if (!in) { #ifdef WOLFSSL_STATIC_MEMORY @@ -3300,13 +3373,16 @@ char* wolfSSL_X509_NAME_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) return NULL; #else in = (char*)XMALLOC(name->sz, NULL, DYNAMIC_TYPE_OPENSSL); - if (!in ) return in; + if (!in) + return in; copySz = name->sz; #endif } - - if (copySz <= 0) - return in; + else { + copySz = (int)min((word32)sz, (word32)name->sz); + if (copySz <= 0) + return in; + } XMEMCPY(in, name->name, copySz - 1); in[copySz - 1] = 0; @@ -3346,7 +3422,7 @@ static unsigned long X509NameHash(WOLFSSL_X509_NAME* name, return 0; } - rc = wc_Hash(hashType, (const byte*)canonName,(word32)size, digest, + rc = wc_Hash(hashType, (const byte*)canonName, (word32)size, digest, sizeof(digest)); if (rc == 0) { @@ -3511,7 +3587,8 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) WOLFSSL_MSG("Memory error"); return NULL; } - if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s", sn, buf)) >= strSz) { + if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s", sn, + buf)) >= strSz) { WOLFSSL_MSG("buffer overrun"); XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER); return NULL; @@ -3697,7 +3774,7 @@ int wolfSSL_X509_NAME_entry_count(WOLFSSL_X509_NAME* name) #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if defined(OPENSSL_EXTRA) || \ - defined(KEEP_OUR_CERT) || defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) + defined(KEEP_OUR_CERT) || defined(KEEP_PEER_CERT) /* return the next, if any, altname from the peer cert */ WOLFSSL_ABI @@ -3874,7 +3951,8 @@ const byte* wolfSSL_X509_get_der(WOLFSSL_X509* x509, int* outSz) return x509->derCert->buffer; } -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || KEEP_OUR_CERT || KEEP_PEER_CERT || SESSION_CERTS */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || KEEP_OUR_CERT || + * KEEP_PEER_CERT || SESSION_CERTS */ #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_ALL) || defined(KEEP_OUR_CERT) || \ @@ -3892,7 +3970,8 @@ const byte* wolfSSL_X509_notBefore(WOLFSSL_X509* x509) XMEMSET(x509->notBeforeData, 0, sizeof(x509->notBeforeData)); x509->notBeforeData[0] = (byte)x509->notBefore.type; x509->notBeforeData[1] = (byte)x509->notBefore.length; - XMEMCPY(&x509->notBeforeData[2], x509->notBefore.data, x509->notBefore.length); + XMEMCPY(&x509->notBeforeData[2], x509->notBefore.data, + x509->notBefore.length); return x509->notBeforeData; } @@ -3971,6 +4050,7 @@ byte* wolfSSL_X509_get_device_type(WOLFSSL_X509* x509, byte* in, int *inOutSz) int copySz; WOLFSSL_ENTER("wolfSSL_X509_get_dev_type"); + if (x509 == NULL) return NULL; if (inOutSz == NULL) return NULL; if (!x509->deviceTypeSz) return in; @@ -3999,6 +4079,7 @@ byte* wolfSSL_X509_get_hw_type(WOLFSSL_X509* x509, byte* in, int* inOutSz) int copySz; WOLFSSL_ENTER("wolfSSL_X509_get_hw_type"); + if (x509 == NULL) return NULL; if (inOutSz == NULL) return NULL; if (!x509->hwTypeSz) return in; @@ -4028,6 +4109,7 @@ byte* wolfSSL_X509_get_hw_serial_number(WOLFSSL_X509* x509,byte* in, int copySz; WOLFSSL_ENTER("wolfSSL_X509_get_hw_serial_number"); + if (x509 == NULL) return NULL; if (inOutSz == NULL) return NULL; if (!x509->hwTypeSz) return in; @@ -4078,8 +4160,9 @@ WOLFSSL_ASN1_TIME* wolfSSL_X509_get_notAfter(const WOLFSSL_X509* x509) } -/* return 1 on success 0 on fail */ -int wolfSSL_sk_X509_push(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk, WOLFSSL_X509* x509) +/* return number of elements on success 0 on fail */ +int wolfSSL_sk_X509_push(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk, + WOLFSSL_X509* x509) { WOLFSSL_ENTER("wolfSSL_sk_X509_push"); @@ -4114,7 +4197,7 @@ WOLFSSL_X509* wolfSSL_sk_X509_pop(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) } if (sk->num > 0) { - sk->num -= 1; + sk->num--; } return x509; @@ -4128,7 +4211,7 @@ WOLFSSL_X509* wolfSSL_sk_X509_pop(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) * returns a pointer to a WOLFSSL_X509 structure on success and NULL on * fail */ -WOLFSSL_X509* wolfSSL_sk_X509_value(STACK_OF(WOLFSSL_X509)* sk, int i) +WOLFSSL_X509* wolfSSL_sk_X509_value(WOLF_STACK_OF(WOLFSSL_X509)* sk, int i) { WOLFSSL_ENTER("wolfSSL_sk_X509_value"); @@ -4187,7 +4270,7 @@ WOLFSSL_X509* wolfSSL_sk_X509_shift(WOLF_STACK_OF(WOLFSSL_X509)* sk) * sk stack to free nodes in * f X509 free function */ -void wolfSSL_sk_X509_pop_free(STACK_OF(WOLFSSL_X509)* sk, +void wolfSSL_sk_X509_pop_free(WOLF_STACK_OF(WOLFSSL_X509)* sk, void (*f) (WOLFSSL_X509*)) { WOLFSSL_ENTER("wolfSSL_sk_X509_pop_free"); @@ -4222,8 +4305,9 @@ void wolfSSL_sk_X509_CRL_free(WOLF_STACK_OF(WOLFSSL_X509_CRL)* sk) wolfSSL_sk_X509_CRL_pop_free(sk, NULL); } -/* return 1 on success 0 on fail */ -int wolfSSL_sk_X509_CRL_push(WOLF_STACK_OF(WOLFSSL_X509_CRL)* sk, WOLFSSL_X509_CRL* crl) +/* return number of elements on success 0 on fail */ +int wolfSSL_sk_X509_CRL_push(WOLF_STACK_OF(WOLFSSL_X509_CRL)* sk, + WOLFSSL_X509_CRL* crl) { WOLFSSL_ENTER("wolfSSL_sk_X509_CRL_push"); @@ -4255,7 +4339,7 @@ int wolfSSL_sk_X509_CRL_num(WOLF_STACK_OF(WOLFSSL_X509)* sk) #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) -/* return 1 on success 0 on fail */ +/* return number of elements on success 0 on fail */ int wolfSSL_sk_ACCESS_DESCRIPTION_push(WOLF_STACK_OF(ACCESS_DESCRIPTION)* sk, WOLFSSL_ACCESS_DESCRIPTION* a) { @@ -4338,7 +4422,7 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_new(void) wolfSSL_GENERAL_NAME_free(gn); return NULL; } - gn->type = GEN_IA5; + gn->type = WOLFSSL_GEN_IA5; return gn; } @@ -4362,33 +4446,33 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) dupl->d.ia5 = NULL; switch (gn->type) { /* WOLFSSL_ASN1_STRING types */ - case GEN_DNS: + case WOLFSSL_GEN_DNS: if (!(dupl->d.dNSName = wolfSSL_ASN1_STRING_dup(gn->d.dNSName))) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_dup error"); goto error; } break; - case GEN_IPADD: + case WOLFSSL_GEN_IPADD: if (!(dupl->d.iPAddress = wolfSSL_ASN1_STRING_dup(gn->d.iPAddress))) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_dup error"); goto error; } break; - case GEN_EMAIL: + case WOLFSSL_GEN_EMAIL: if (!(dupl->d.rfc822Name = wolfSSL_ASN1_STRING_dup(gn->d.rfc822Name))) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_dup error"); goto error; } break; - case GEN_URI: + case WOLFSSL_GEN_URI: if (!(dupl->d.uniformResourceIdentifier = wolfSSL_ASN1_STRING_dup(gn->d.uniformResourceIdentifier))) { WOLFSSL_MSG("wolfSSL_ASN1_STRING_dup error"); goto error; } break; - case GEN_OTHERNAME: - if (gn->d.otherName->value->type != V_ASN1_UTF8STRING) { + case WOLFSSL_GEN_OTHERNAME: + if (gn->d.otherName->value->type != WOLFSSL_V_ASN1_UTF8STRING) { WOLFSSL_MSG("Unsupported othername value type"); goto error; } @@ -4419,10 +4503,10 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) goto error; } break; - case GEN_X400: - case GEN_DIRNAME: - case GEN_EDIPARTY: - case GEN_RID: + case WOLFSSL_GEN_X400: + case WOLFSSL_GEN_DIRNAME: + case WOLFSSL_GEN_EDIPARTY: + case WOLFSSL_GEN_RID: default: WOLFSSL_MSG("Unrecognized or unsupported GENERAL_NAME type"); goto error; @@ -4431,9 +4515,7 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) return dupl; error: - if (dupl) { - wolfSSL_GENERAL_NAME_free(dupl); - } + wolfSSL_GENERAL_NAME_free(dupl); return NULL; } @@ -4446,7 +4528,7 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) * WOLFSSL_SUCCESS otherwise. */ int wolfSSL_GENERAL_NAME_set0_othername(WOLFSSL_GENERAL_NAME* gen, - ASN1_OBJECT* oid, ASN1_TYPE* value) + WOLFSSL_ASN1_OBJECT* oid, WOLFSSL_ASN1_TYPE* value) { WOLFSSL_ASN1_OBJECT *x = NULL; @@ -4460,13 +4542,13 @@ int wolfSSL_GENERAL_NAME_set0_othername(WOLFSSL_GENERAL_NAME* gen, return WOLFSSL_FAILURE; } - gen->type = GEN_OTHERNAME; + gen->type = WOLFSSL_GEN_OTHERNAME; gen->d.otherName->type_id = x; gen->d.otherName->value = value; return WOLFSSL_SUCCESS; } -/* return 1 on success 0 on fail */ +/* return number of elements on success 0 on fail */ int wolfSSL_sk_GENERAL_NAME_push(WOLFSSL_GENERAL_NAMES* sk, WOLFSSL_GENERAL_NAME* gn) { @@ -4644,7 +4726,7 @@ void wolfSSL_DIST_POINTS_free(WOLFSSL_DIST_POINTS *dps) wolfSSL_sk_free(dps); } -/* return 1 on success 0 on fail */ +/* return number of elements on success 0 on fail */ int wolfSSL_sk_DIST_POINT_push(WOLFSSL_DIST_POINTS* sk, WOLFSSL_DIST_POINT* dp) { WOLFSSL_ENTER("wolfSSL_sk_DIST_POINT_push"); @@ -4742,35 +4824,35 @@ static void wolfSSL_GENERAL_NAME_type_free(WOLFSSL_GENERAL_NAME* name) { if (name != NULL) { switch (name->type) { - case GEN_IA5: + case WOLFSSL_GEN_IA5: wolfSSL_ASN1_STRING_free(name->d.ia5); name->d.ia5 = NULL; break; - case GEN_EMAIL: + case WOLFSSL_GEN_EMAIL: wolfSSL_ASN1_STRING_free(name->d.rfc822Name); name->d.rfc822Name = NULL; break; - case GEN_DNS: + case WOLFSSL_GEN_DNS: wolfSSL_ASN1_STRING_free(name->d.dNSName); name->d.dNSName = NULL; break; - case GEN_DIRNAME: + case WOLFSSL_GEN_DIRNAME: wolfSSL_X509_NAME_free(name->d.dirn); name->d.dirn = NULL; break; - case GEN_URI: + case WOLFSSL_GEN_URI: wolfSSL_ASN1_STRING_free(name->d.uniformResourceIdentifier); name->d.uniformResourceIdentifier = NULL; break; - case GEN_IPADD: + case WOLFSSL_GEN_IPADD: wolfSSL_ASN1_STRING_free(name->d.iPAddress); name->d.iPAddress = NULL; break; - case GEN_RID: + case WOLFSSL_GEN_RID: wolfSSL_ASN1_OBJECT_free(name->d.registeredID); name->d.registeredID = NULL; break; - case GEN_OTHERNAME: + case WOLFSSL_GEN_OTHERNAME: if (name->d.otherName != NULL) { wolfSSL_ASN1_OBJECT_free(name->d.otherName->type_id); wolfSSL_ASN1_TYPE_free(name->d.otherName->value); @@ -4778,9 +4860,9 @@ static void wolfSSL_GENERAL_NAME_type_free(WOLFSSL_GENERAL_NAME* name) name->d.otherName = NULL; } break; - case GEN_X400: + case WOLFSSL_GEN_X400: /* Unsupported: fall through */ - case GEN_EDIPARTY: + case WOLFSSL_GEN_EDIPARTY: /* Unsupported: fall through */ default: WOLFSSL_MSG("wolfSSL_GENERAL_NAME_type_free: possible leak"); @@ -4801,13 +4883,13 @@ int wolfSSL_GENERAL_NAME_set_type(WOLFSSL_GENERAL_NAME* name, int typ) name->type = typ; switch (typ) { - case GEN_URI: + case WOLFSSL_GEN_URI: name->d.uniformResourceIdentifier = wolfSSL_ASN1_STRING_new(); if (name->d.uniformResourceIdentifier == NULL) ret = MEMORY_E; break; default: - name->type = GEN_IA5; + name->type = WOLFSSL_GEN_IA5; name->d.ia5 = wolfSSL_ASN1_STRING_new(); if (name->d.ia5 == NULL) ret = MEMORY_E; @@ -4842,16 +4924,15 @@ void wolfSSL_GENERAL_NAME_set0_value(WOLFSSL_GENERAL_NAME *a, int type, return; } - if (type != GEN_DNS) { - WOLFSSL_MSG("Only GEN_DNS is supported"); + if (type != WOLFSSL_GEN_DNS) { + WOLFSSL_MSG("Only WOLFSSL_GEN_DNS is supported"); return; } wolfSSL_GENERAL_NAME_type_free(a); a->type = type; - if (type == GEN_DNS) { - a->d.dNSName = val; - } + /* Only when WOLFSSL_GEN_DNS. */ + a->d.dNSName = val; } /* Frees GENERAL_NAME objects. @@ -5011,6 +5092,7 @@ int wolfSSL_GENERAL_NAME_print(WOLFSSL_BIO* out, WOLFSSL_GENERAL_NAME* gen) case GEN_RID: ret = wolfSSL_BIO_printf(out, "Registered ID:"); + ret = (ret > 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; if (ret == WOLFSSL_SUCCESS) { ret = wolfSSL_i2a_ASN1_OBJECT(out, gen->d.registeredID); } @@ -5070,7 +5152,8 @@ void wolfSSL_sk_X509_EXTENSION_free(WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk) #endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) +#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) && \ + !defined(NO_STDIO_FILESYSTEM) WOLFSSL_X509* wolfSSL_X509_d2i_fp(WOLFSSL_X509** x509, XFILE file) { @@ -5140,12 +5223,12 @@ WOLFSSL_X509* wolfSSL_X509_load_certificate_file(const char* fname, int format) if (file == XBADFILE) return NULL; - if (XFSEEK(file, 0, XSEEK_END) != 0){ + if (XFSEEK(file, 0, XSEEK_END) != 0) { XFCLOSE(file); return NULL; } sz = XFTELL(file); - if (XFSEEK(file, 0, XSEEK_SET) != 0){ + if (XFSEEK(file, 0, XSEEK_SET) != 0) { XFCLOSE(file); return NULL; } @@ -5279,7 +5362,8 @@ WOLFSSL_X509* wolfSSL_X509_REQ_load_certificate_buffer( } #endif -#endif /* KEEP_PEER_CERT || SESSION_CERTS */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || KEEP_PEER_CERT || \ + SESSION_CERTS */ #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(KEEP_PEER_CERT) || \ defined(SESSION_CERTS) @@ -5358,11 +5442,6 @@ static WOLFSSL_X509_NAME_ENTRY* GetEntryByNID(WOLFSSL_X509_NAME* name, int nid, int i; WOLFSSL_X509_NAME_ENTRY* ret = NULL; - /* and index of less than 0 is assumed to be starting from 0 */ - if (*idx < 0) { - *idx = 0; - } - for (i = *idx; i < MAX_NAME_ENTRIES; i++) { if (name->entry[i].nid == nid) { ret = &name->entry[i]; @@ -5424,14 +5503,15 @@ int wolfSSL_X509_NAME_get_text_by_NID(WOLFSSL_X509_NAME* name, WOLFSSL_MSG("Buffer is NULL, returning buffer size only"); return textSz; } + if (len <= 0) { + return 0; + } - /* buf is not NULL from above */ - if (text != NULL) { - textSz = (int)min((word32)textSz + 1, (word32)len); /* + 1 to account for null char */ - if (textSz > 0) { - XMEMCPY(buf, text, textSz - 1); - buf[textSz - 1] = '\0'; - } + /* + 1 to account for null char */ + textSz = (int)min((word32)textSz + 1, (word32)len); + if (textSz > 0) { + XMEMCPY(buf, text, textSz - 1); + buf[textSz - 1] = '\0'; } WOLFSSL_LEAVE("wolfSSL_X509_NAME_get_text_by_NID", textSz); @@ -5454,13 +5534,13 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) key = wolfSSL_EVP_PKEY_new_ex(x509->heap); if (key != NULL) { if (x509->pubKeyOID == RSAk) { - key->type = EVP_PKEY_RSA; + key->type = WC_EVP_PKEY_RSA; } else if (x509->pubKeyOID == DSAk) { - key->type = EVP_PKEY_DSA; + key->type = WC_EVP_PKEY_DSA; } else { - key->type = EVP_PKEY_EC; + key->type = WC_EVP_PKEY_EC; } key->save_type = 0; key->pkey.ptr = (char*)XMALLOC( @@ -5479,7 +5559,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) /* decode RSA key */ #ifndef NO_RSA - if (key->type == EVP_PKEY_RSA) { + if (key->type == WC_EVP_PKEY_RSA) { key->ownRsa = 1; key->rsa = wolfSSL_RSA_new(); if (key->rsa == NULL) { @@ -5498,7 +5578,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) /* decode ECC key */ #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) - if (key->type == EVP_PKEY_EC) { + if (key->type == WC_EVP_PKEY_EC) { word32 idx = 0; key->ownEcc = 1; @@ -5531,7 +5611,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) #endif /* HAVE_ECC && OPENSSL_EXTRA */ #ifndef NO_DSA - if (key->type == EVP_PKEY_DSA) { + if (key->type == WC_EVP_PKEY_DSA) { key->ownDsa = 1; key->dsa = wolfSSL_DSA_new(); if (key->dsa == NULL) { @@ -5571,17 +5651,17 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) int outSzA = 0; int outSzB = 0; - if (a == NULL || b == NULL){ + if (a == NULL || b == NULL) { return BAD_FUNC_ARG; } derA = wolfSSL_X509_get_der((WOLFSSL_X509*)a, &outSzA); - if (derA == NULL){ + if (derA == NULL) { WOLFSSL_MSG("wolfSSL_X509_get_der - certificate A has failed"); return WOLFSSL_FATAL_ERROR; } derB = wolfSSL_X509_get_der((WOLFSSL_X509*)b, &outSzB); - if (derB == NULL){ + if (derB == NULL) { WOLFSSL_MSG("wolfSSL_X509_get_der - certificate B has failed"); return WOLFSSL_FATAL_ERROR; } @@ -5606,18 +5686,26 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) if (x509 != NULL) { switch (nid) { - case NID_basic_constraints: isSet = x509->basicConstSet; break; - case NID_subject_alt_name: isSet = x509->subjAltNameSet; break; - case NID_authority_key_identifier: isSet = x509->authKeyIdSet; break; - case NID_subject_key_identifier: isSet = x509->subjKeyIdSet; break; - case NID_key_usage: isSet = x509->keyUsageSet; break; - case NID_crl_distribution_points: isSet = x509->CRLdistSet; break; - case NID_ext_key_usage: isSet = ((x509->extKeyUsageSrc) ? 1 : 0); - break; - case NID_info_access: isSet = x509->authInfoSet; break; - #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) - case NID_certificate_policies: isSet = x509->certPolicySet; break; - #endif /* WOLFSSL_SEP || WOLFSSL_QT */ + case WC_NID_basic_constraints: + isSet = x509->basicConstSet; break; + case WC_NID_subject_alt_name: + isSet = x509->subjAltNameSet; break; + case WC_NID_authority_key_identifier: + isSet = x509->authKeyIdSet; break; + case WC_NID_subject_key_identifier: + isSet = x509->subjKeyIdSet; break; + case WC_NID_key_usage: + isSet = x509->keyUsageSet; break; + case WC_NID_crl_distribution_points: + isSet = x509->CRLdistSet; break; + case WC_NID_ext_key_usage: + isSet = ((x509->extKeyUsageSrc) ? 1 : 0); break; + case WC_NID_info_access: + isSet = x509->authInfoSet; break; + #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT) + case WC_NID_certificate_policies: + isSet = x509->certPolicySet; break; + #endif /* WOLFSSL_SEP || WOLFSSL_QT */ default: WOLFSSL_MSG("NID not in table"); } @@ -5637,15 +5725,23 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) if (x509 != NULL) { switch (nid) { - case NID_basic_constraints: crit = x509->basicConstCrit; break; - case NID_subject_alt_name: crit = x509->subjAltNameCrit; break; - case NID_authority_key_identifier: crit = x509->authKeyIdCrit; break; - case NID_subject_key_identifier: crit = x509->subjKeyIdCrit; break; - case NID_key_usage: crit = x509->keyUsageCrit; break; - case NID_crl_distribution_points: crit= x509->CRLdistCrit; break; - case NID_ext_key_usage: crit= x509->extKeyUsageCrit; break; + case WC_NID_basic_constraints: + crit = x509->basicConstCrit; break; + case WC_NID_subject_alt_name: + crit = x509->subjAltNameCrit; break; + case WC_NID_authority_key_identifier: + crit = x509->authKeyIdCrit; break; + case WC_NID_subject_key_identifier: + crit = x509->subjKeyIdCrit; break; + case WC_NID_key_usage: + crit = x509->keyUsageCrit; break; + case WC_NID_crl_distribution_points: + crit= x509->CRLdistCrit; break; + case WC_NID_ext_key_usage: + crit= x509->extKeyUsageCrit; break; #ifdef WOLFSSL_SEP - case NID_certificate_policies: crit = x509->certPolicyCrit; break; + case WC_NID_certificate_policies: + crit = x509->certPolicyCrit; break; #endif /* WOLFSSL_SEP */ } } @@ -5768,7 +5864,6 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) if (x509->subjKeyIdStr != NULL) { if (wolfSSL_ASN1_STRING_set(x509->subjKeyIdStr, x509->subjKeyId, x509->subjKeyIdSz) == 1) { - ret = x509->subjKeyIdStr; } else { wolfSSL_ASN1_STRING_free(x509->subjKeyIdStr); @@ -5776,9 +5871,7 @@ int wolfSSL_X509_cmp(const WOLFSSL_X509 *a, const WOLFSSL_X509 *b) } } } - else { - ret = x509->subjKeyIdStr; - } + ret = x509->subjKeyIdStr; } WOLFSSL_LEAVE("wolfSSL_X509_get0_subject_key_id", ret != NULL); @@ -5926,8 +6019,8 @@ static int X509PrintDirType(char * dst, int max_len, const DNS_entry * entry) /* Copy it in, decrement available space. */ XSTRNCPY(dst, pfx, bytes_left); dst += XSTRLEN(pfx); - total_len += XSTRLEN(pfx); - bytes_left -= XSTRLEN(pfx); + total_len += (int)XSTRLEN(pfx); + bytes_left -= (int)XSTRLEN(pfx); if (fld_len > bytes_left) { /* Not enough space left. */ @@ -6534,11 +6627,11 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) } nid = wolfSSL_OBJ_obj2nid(obj); switch (nid) { - case NID_subject_alt_name: + case WC_NID_subject_alt_name: ret = X509PrintSubjAltName(bio, x509, indent + 8); break; - case NID_subject_key_identifier: + case WC_NID_subject_key_identifier: if (!x509->subjKeyIdSet || x509->subjKeyId == NULL || x509->subjKeyIdSz == 0) { @@ -6583,7 +6676,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) } break; - case NID_authority_key_identifier: + case WC_NID_authority_key_identifier: if (!x509->authKeyIdSet || x509->authKeyId == NULL || x509->authKeyIdSz == 0) { ret = WOLFSSL_FAILURE; @@ -6632,7 +6725,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) } break; - case NID_basic_constraints: + case WC_NID_basic_constraints: if (!x509->basicConstSet) { ret = WOLFSSL_FAILURE; break; @@ -6653,11 +6746,11 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) } break; - case NID_key_usage: + case WC_NID_key_usage: ret = X509PrintKeyUsage(bio, x509, indent + 8); break; - case NID_ext_key_usage: + case WC_NID_ext_key_usage: ret = X509PrintExtendedKeyUsage(bio, x509, indent + 8); break; @@ -6882,7 +6975,8 @@ static int X509PrintPubKey(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) if (bio == NULL || x509 == NULL) return BAD_FUNC_ARG; - len = XSNPRINTF(scratch, MAX_WIDTH, "%*sSubject Public Key Info:\n", indent, ""); + len = XSNPRINTF(scratch, MAX_WIDTH, "%*sSubject Public Key Info:\n", indent, + ""); if (len >= MAX_WIDTH) return WOLFSSL_FAILURE; if (wolfSSL_BIO_write(bio, scratch, len) <= 0) @@ -7067,8 +7161,10 @@ int wolfSSL_X509_REQ_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509) return WOLFSSL_FAILURE; } - /* print version of cert */ - if (X509PrintVersion(bio, wolfSSL_X509_version(x509), 8) + /* print version of cert. Note that we increment by 1 because for REQs, + * the value stored in x509->version is the actual value of the field; not + * the version. */ + if (X509PrintVersion(bio, (int)wolfSSL_X509_REQ_get_version(x509) + 1, 8) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } @@ -7423,7 +7519,7 @@ int wolfSSL_X509_print_fp(XFILE fp, WOLFSSL_X509 *x509) return WOLFSSL_FAILURE; } - if (wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_NOCLOSE) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("wolfSSL_BIO_set_fp error"); wolfSSL_BIO_free(bio); return WOLFSSL_FAILURE; @@ -7546,12 +7642,12 @@ int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, if (fp == XBADFILE) return WS_RETURN_CODE(BAD_FUNC_ARG, (int)WOLFSSL_FAILURE); - if(XFSEEK(fp, 0, XSEEK_END) != 0) { + if (XFSEEK(fp, 0, XSEEK_END) != 0) { XFCLOSE(fp); return WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE); } sz = XFTELL(fp); - if(XFSEEK(fp, 0, XSEEK_SET) != 0) { + if (XFSEEK(fp, 0, XSEEK_SET) != 0) { XFCLOSE(fp); return WS_RETURN_CODE(WOLFSSL_BAD_FILE,WOLFSSL_FAILURE); } @@ -7836,7 +7932,8 @@ static int wolfssl_x509_make_der(WOLFSSL_X509* x509, int req, * * returns WOLFSSL_SUCCESS on success */ -static int loadX509orX509REQFromBio(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int req) +static int loadX509orX509REQFromBio(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, + int req) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); /* Get large buffer to hold cert der */ @@ -8013,7 +8110,7 @@ static WOLFSSL_X509* d2i_X509orX509REQ_bio(WOLFSSL_BIO* bio, size = wolfSSL_BIO_get_len(bio); if (size <= 0) { WOLFSSL_MSG("wolfSSL_BIO_get_len error. Possibly no pending data."); - WOLFSSL_ERROR(ASN1_R_HEADER_TOO_LONG); + WOLFSSL_ERROR(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E); return NULL; } @@ -8071,7 +8168,8 @@ WOLFSSL_X509* wolfSSL_d2i_X509_REQ_bio(WOLFSSL_BIO* bio, WOLFSSL_X509** x509) /* Use the public key to verify the signature. Note: this only verifies * the certificate signature. * returns WOLFSSL_SUCCESS on successful signature verification */ -static int verifyX509orX509REQ(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, int req) +static int verifyX509orX509REQ(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, + int req) { int ret; const byte* der; @@ -8091,15 +8189,15 @@ static int verifyX509orX509REQ(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, int r } switch (pkey->type) { - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: type = RSAk; break; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: type = ECDSAk; break; - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: type = DSAk; break; @@ -8188,7 +8286,8 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type) if ((newx509 = wc_PKCS12_new()) == NULL) { goto err_exit; } - if (wc_d2i_PKCS12(fileBuffer, (word32)sz, (WC_PKCS12*)newx509) < 0) { + if (wc_d2i_PKCS12(fileBuffer, (word32)sz, + (WC_PKCS12*)newx509) < 0) { goto err_exit; } } @@ -8260,16 +8359,19 @@ WOLFSSL_API int wolfSSL_X509_load_cert_crl_file(WOLFSSL_X509_LOOKUP *ctx, if (wolfSSL_X509_STORE_add_cert(ctx->store, x509) == WOLFSSL_SUCCESS) { cnt++; - } else { + } + else { WOLFSSL_MSG("wolfSSL_X509_STORE_add_cert error"); } wolfSSL_X509_free(x509); x509 = NULL; - } else { + } + else { WOLFSSL_MSG("wolfSSL_X509_load_certificate_file error"); } - } else { + } + else { #if defined(OPENSSL_ALL) #if !defined(NO_BIO) STACK_OF(WOLFSSL_X509_INFO) *info; @@ -8277,7 +8379,7 @@ WOLFSSL_API int wolfSSL_X509_load_cert_crl_file(WOLFSSL_X509_LOOKUP *ctx, int i; int num = 0; WOLFSSL_BIO *bio = wolfSSL_BIO_new_file(file, "rb"); - if(!bio) { + if (!bio) { WOLFSSL_MSG("wolfSSL_BIO_new error"); return cnt; } @@ -8295,19 +8397,21 @@ WOLFSSL_API int wolfSSL_X509_load_cert_crl_file(WOLFSSL_X509_LOOKUP *ctx, info_tmp = wolfSSL_sk_X509_INFO_value(info, i); if (info_tmp->x509) { - if(wolfSSL_X509_STORE_add_cert(ctx->store, info_tmp->x509) == + if (wolfSSL_X509_STORE_add_cert(ctx->store, info_tmp->x509) == WOLFSSL_SUCCESS) { cnt ++; - } else { + } + else { WOLFSSL_MSG("wolfSSL_X509_STORE_add_cert failed"); } } #ifdef HAVE_CRL if (info_tmp->crl) { - if(wolfSSL_X509_STORE_add_crl(ctx->store, info_tmp->crl) == + if (wolfSSL_X509_STORE_add_crl(ctx->store, info_tmp->crl) == WOLFSSL_SUCCESS) { cnt ++; - } else { + } + else { WOLFSSL_MSG("wolfSSL_X509_STORE_add_crl failed"); } } @@ -8400,7 +8504,8 @@ WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_bio(WOLFSSL_BIO *bp, WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_fp(XFILE fp, WOLFSSL_X509_CRL **crl) { WOLFSSL_ENTER("wolfSSL_d2i_X509_CRL_fp"); - return (WOLFSSL_X509_CRL *)wolfSSL_d2i_X509_fp_ex(fp, (void **)crl, CRL_TYPE); + return (WOLFSSL_X509_CRL *)wolfSSL_d2i_X509_fp_ex(fp, (void **)crl, + CRL_TYPE); } /* Read CRL file, and add it to store and corresponding cert manager */ @@ -8461,15 +8566,18 @@ WOLFSSL_API int wolfSSL_X509_load_crl_file(WOLFSSL_X509_LOOKUP *ctx, crl = wolfSSL_d2i_X509_CRL_bio(bio, NULL); if (crl == NULL) { WOLFSSL_MSG("Load crl failed"); - } else { + } + else { ret = wolfSSL_X509_STORE_add_crl(ctx->store, crl); if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("Adding crl failed"); - } else { + } + else { ret = 1;/* handled a file */ } } - } else { + } + else { WOLFSSL_MSG("Invalid file type"); } @@ -8554,21 +8662,25 @@ WOLFSSL_X509_CRL* wolfSSL_d2i_X509_CRL(WOLFSSL_X509_CRL** crl, if (in == NULL) { WOLFSSL_MSG("Bad argument value"); - } else { + } + else { newcrl =(WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), NULL, DYNAMIC_TYPE_CRL); - if (newcrl == NULL){ + if (newcrl == NULL) { WOLFSSL_MSG("New CRL allocation failed"); - } else { + } + else { ret = InitCRL(newcrl, NULL); if (ret < 0) { WOLFSSL_MSG("Init tmp CRL failed"); - } else { + } + else { ret = BufferLoadCRL(newcrl, in, len, WOLFSSL_FILETYPE_ASN1, NO_VERIFY); if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Buffer Load CRL failed"); - } else { + } + else { if (crl) { *crl = newcrl; } @@ -8577,7 +8689,7 @@ WOLFSSL_X509_CRL* wolfSSL_d2i_X509_CRL(WOLFSSL_X509_CRL** crl, } } - if((ret != WOLFSSL_SUCCESS) && (newcrl != NULL)) { + if ((ret != WOLFSSL_SUCCESS) && (newcrl != NULL)) { wolfSSL_X509_CRL_free(newcrl); newcrl = NULL; } @@ -8645,8 +8757,15 @@ int wolfSSL_X509_CRL_get_signature(WOLFSSL_X509_CRL* crl, crl->crlList->signature == NULL || bufSz == NULL) return BAD_FUNC_ARG; - if (buf != NULL) - XMEMCPY(buf, crl->crlList->signature, *bufSz); + if (buf != NULL) { + if (*bufSz < (int)crl->crlList->signatureSz) { + WOLFSSL_MSG("Signature buffer too small"); + return BUFFER_E; + } + else { + XMEMCPY(buf, crl->crlList->signature, crl->crlList->signatureSz); + } + } *bufSz = (int)crl->crlList->signatureSz; return WOLFSSL_SUCCESS; @@ -8831,8 +8950,8 @@ static int X509CRLPrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509_CRL* crl, } tmp[0] = '\0'; } - if (XSNPRINTF(val, (size_t)valSz, ":%02X", crl->crlList->extAuthKeyId[i]) - >= valSz) + if (XSNPRINTF(val, (size_t)valSz, ":%02X", + crl->crlList->extAuthKeyId[i]) >= valSz) { WOLFSSL_MSG("buffer overrun"); return WOLFSSL_FAILURE; @@ -9195,10 +9314,16 @@ static const WOLFSSL_X509_VERIFY_PARAM x509_verify_param_builtins[] = { } }; -const WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_VERIFY_PARAM_lookup(const char *name) +const WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_VERIFY_PARAM_lookup( + const char *name) { const WOLFSSL_X509_VERIFY_PARAM *param = &x509_verify_param_builtins[0], - *param_end = &x509_verify_param_builtins[XELEM_CNT(x509_verify_param_builtins)]; + *param_end = &x509_verify_param_builtins[ + XELEM_CNT(x509_verify_param_builtins)]; + + if (name == NULL) { + return NULL; + } while (param < param_end) { if (XSTRCMP(name, param->name) == 0) return param; @@ -9403,6 +9528,10 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, WOLFSSL_MSG("bad function arg"); return ret; } + if (ip == NULL && iplen != 0) { + WOLFSSL_MSG("bad function arg"); + return ret; + } #ifndef NO_FILESYSTEM if (iplen == 4) { /* ipv4 www.xxx.yyy.zzz max 15 length + Null termination */ @@ -9449,7 +9578,7 @@ int wolfSSL_X509_VERIFY_PARAM_set1_ip(WOLFSSL_X509_VERIFY_PARAM* param, p = buf; for (i = 0; i < 16; i += 2) { val = (((word32)(ip[i]<<8)) | (ip[i+1])) & 0xFFFF; - if (val == 0){ + if (val == 0) { if (!write_zero) { *p = ':'; } @@ -9519,7 +9648,8 @@ int wolfSSL_X509_cmp_current_time(const WOLFSSL_ASN1_TIME* asnTime) return wolfSSL_X509_cmp_time(asnTime, NULL); } -/* return WOLFSSL_FATAL_ERROR if asnTime is earlier than or equal to cmpTime, and 1 otherwise +/* return WOLFSSL_FATAL_ERROR if asnTime is earlier than or equal to cmpTime, + * and 1 otherwise * return 0 on error */ int wolfSSL_X509_cmp_time(const WOLFSSL_ASN1_TIME* asnTime, time_t* cmpTime) @@ -9604,7 +9734,7 @@ WOLFSSL_X509_REVOKED* wolfSSL_X509_CRL_get_REVOKED(WOLFSSL_X509_CRL* crl) { (void)crl; WOLFSSL_STUB("X509_CRL_get_REVOKED"); - return 0; + return NULL; } #endif @@ -9615,7 +9745,7 @@ WOLFSSL_X509_REVOKED* wolfSSL_sk_X509_REVOKED_value( (void)revoked; (void)value; WOLFSSL_STUB("sk_X509_REVOKED_value"); - return 0; + return NULL; } #endif @@ -9653,7 +9783,8 @@ WOLFSSL_ASN1_INTEGER* wolfSSL_X509_get_serialNumber(WOLFSSL_X509* x509) } a->dataMax = (unsigned int)x509->serialSz + 2; a->isDynamic = 1; - } else { + } + else { /* Use array instead of dynamic memory */ a->data = a->intData; a->dataMax = WOLFSSL_ASN1_INTEGER_MAX; @@ -9733,8 +9864,8 @@ void wolfSSL_X509_ALGOR_get0(const WOLFSSL_ASN1_OBJECT **paobj, int *pptype, *pptype = algor->parameter->type; } else { - /* Default to V_ASN1_OBJECT */ - *pptype = V_ASN1_OBJECT; + /* Default to WOLFSSL_V_ASN1_OBJECT */ + *pptype = WOLFSSL_V_ASN1_OBJECT; } } } @@ -9749,8 +9880,8 @@ void wolfSSL_X509_ALGOR_get0(const WOLFSSL_ASN1_OBJECT **paobj, int *pptype, * @return WOLFSSL_SUCCESS on success * WOLFSSL_FAILURE on missing parameters or bad malloc */ -int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, WOLFSSL_ASN1_OBJECT *aobj, - int ptype, void *pval) +int wolfSSL_X509_ALGOR_set0(WOLFSSL_X509_ALGOR *algor, + WOLFSSL_ASN1_OBJECT *aobj, int ptype, void *pval) { if (!algor) { return WOLFSSL_FAILURE; @@ -10006,14 +10137,14 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) switch (key->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: pval = NULL; - ptype = V_ASN1_NULL; + ptype = WOLFSSL_V_ASN1_NULL; pk->pubKeyOID = RSAk; break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (!key->dsa->p || !key->dsa->q || !key->dsa->g) goto error; @@ -10030,12 +10161,12 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) str->isDynamic = 1; pval = str; - ptype = V_ASN1_SEQUENCE; + ptype = WOLFSSL_V_ASN1_SEQUENCE; pk->pubKeyOID = DSAk; break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: group = wolfSSL_EC_KEY_get0_group(key->ecc); if (!group) goto error; @@ -10051,7 +10182,7 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) if (!pval) goto error; - ptype = V_ASN1_OBJECT; + ptype = WOLFSSL_V_ASN1_OBJECT; pk->pubKeyOID = ECDSAk; break; #endif @@ -10062,7 +10193,7 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) keyTypeObj = wolfSSL_OBJ_nid2obj(key->type); if (keyTypeObj == NULL) { - if (ptype == V_ASN1_OBJECT) + if (ptype == WOLFSSL_V_ASN1_OBJECT) ASN1_OBJECT_free((WOLFSSL_ASN1_OBJECT *)pval); else ASN1_STRING_free((WOLFSSL_ASN1_STRING *)pval); @@ -10071,7 +10202,7 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) if (!wolfSSL_X509_ALGOR_set0(pk->algor, keyTypeObj, ptype, pval)) { WOLFSSL_MSG("Failed to create algorithm object"); ASN1_OBJECT_free(keyTypeObj); - if (ptype == V_ASN1_OBJECT) + if (ptype == WOLFSSL_V_ASN1_OBJECT) ASN1_OBJECT_free((WOLFSSL_ASN1_OBJECT *)pval); else ASN1_STRING_free((WOLFSSL_ASN1_STRING *)pval); @@ -10094,11 +10225,13 @@ int wolfSSL_X509_PUBKEY_set(WOLFSSL_X509_PUBKEY **x, WOLFSSL_EVP_PKEY *key) return WOLFSSL_FAILURE; } -#endif /* OPENSSL_ALL || WOLFSSL_APACHE_HTTPD || WOLFSSL_HAPROXY || WOLFSSL_WPAS */ +#endif /* OPENSSL_ALL || WOLFSSL_APACHE_HTTPD || WOLFSSL_HAPROXY || + * WOLFSSL_WPAS */ #if !defined(NO_CERTS) && !defined(NO_ASN) && !defined(NO_PWDBASED) -int wolfSSL_i2d_X509_PUBKEY(WOLFSSL_X509_PUBKEY* x509_PubKey, unsigned char** der) +int wolfSSL_i2d_X509_PUBKEY(WOLFSSL_X509_PUBKEY* x509_PubKey, + unsigned char** der) { if (x509_PubKey == NULL) return WOLFSSL_FATAL_ERROR; @@ -10154,7 +10287,7 @@ WOLFSSL_AUTHORITY_KEYID* wolfSSL_AUTHORITY_KEYID_new(void) void wolfSSL_AUTHORITY_KEYID_free(WOLFSSL_AUTHORITY_KEYID *id) { WOLFSSL_ENTER("wolfSSL_AUTHORITY_KEYID_free"); - if(id == NULL) { + if (id == NULL) { WOLFSSL_MSG("Argument is NULL"); return; } @@ -10272,7 +10405,8 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( #ifdef WOLFSSL_CERT_GEN -#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) +#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT) || \ + defined(OPENSSL_EXTRA) /* Helper function to copy cert name from a WOLFSSL_X509_NAME structure to * a Cert structure. * @@ -10347,7 +10481,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( #if defined(OPENSSL_ALL) idx = wolfSSL_X509_REQ_get_attr_by_NID(req, - NID_pkcs9_unstructuredName, -1); + WC_NID_pkcs9_unstructuredName, -1); if (idx != WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { WOLFSSL_X509_ATTRIBUTE *attr; attr = wolfSSL_X509_REQ_get_attr(req, idx); @@ -10405,221 +10539,221 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } #endif /* WOLFSSL_CERT_REQ */ - /* converts WOLFSSL_AN1_TIME to Cert form, returns positive size on - * success */ - static int CertDateFromX509(byte* out, int outSz, WOLFSSL_ASN1_TIME* t) - { - int sz, i; +/* converts WOLFSSL_AN1_TIME to Cert form, returns positive size on + * success */ +static int CertDateFromX509(byte* out, int outSz, WOLFSSL_ASN1_TIME* t) +{ + int sz, i; - if (t->length + 1 >= outSz) { - return BUFFER_E; - } + if (t->length + 1 >= outSz) { + return BUFFER_E; + } - out[0] = (byte) t->type; - sz = (int)SetLength((word32)t->length, out + 1) + 1; /* gen tag */ - for (i = 0; i < t->length; i++) { - out[sz + i] = t->data[i]; - } - return t->length + sz; + out[0] = (byte) t->type; + sz = (int)SetLength((word32)t->length, out + 1) + 1; /* gen tag */ + for (i = 0; i < t->length; i++) { + out[sz + i] = t->data[i]; } + return t->length + sz; +} - /* convert a WOLFSSL_X509 to a Cert structure for writing out */ - static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) - { - int ret; - #ifdef WOLFSSL_CERT_EXT - int i; - #endif +/* convert a WOLFSSL_X509 to a Cert structure for writing out */ +static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) +{ + int ret; +#ifdef WOLFSSL_CERT_EXT + int i; +#endif - WOLFSSL_ENTER("wolfSSL_X509_to_Cert"); + WOLFSSL_ENTER("wolfSSL_X509_to_Cert"); - if (x509 == NULL || cert == NULL) { - return BAD_FUNC_ARG; - } + if (x509 == NULL || cert == NULL) { + return BAD_FUNC_ARG; + } - wc_InitCert(cert); + wc_InitCert(cert); - cert->version = (int)wolfSSL_X509_get_version(x509); + cert->version = (int)wolfSSL_X509_get_version(x509); - if (x509->notBefore.length > 0) { - cert->beforeDateSz = CertDateFromX509(cert->beforeDate, - CTC_DATE_SIZE, &x509->notBefore); - if (cert->beforeDateSz <= 0){ - WOLFSSL_MSG("Error converting WOLFSSL_X509 not before date"); - return WOLFSSL_FAILURE; - } - } - else { - cert->beforeDateSz = 0; + if (x509->notBefore.length > 0) { + cert->beforeDateSz = CertDateFromX509(cert->beforeDate, + CTC_DATE_SIZE, &x509->notBefore); + if (cert->beforeDateSz <= 0) { + WOLFSSL_MSG("Error converting WOLFSSL_X509 not before date"); + return WOLFSSL_FAILURE; } + } + else { + cert->beforeDateSz = 0; + } - if (x509->notAfter.length > 0) { - cert->afterDateSz = CertDateFromX509(cert->afterDate, - CTC_DATE_SIZE, &x509->notAfter); - if (cert->afterDateSz <= 0){ - WOLFSSL_MSG("Error converting WOLFSSL_X509 not after date"); - return WOLFSSL_FAILURE; - } - } - else { - cert->afterDateSz = 0; + if (x509->notAfter.length > 0) { + cert->afterDateSz = CertDateFromX509(cert->afterDate, + CTC_DATE_SIZE, &x509->notAfter); + if (cert->afterDateSz <= 0) { + WOLFSSL_MSG("Error converting WOLFSSL_X509 not after date"); + return WOLFSSL_FAILURE; } + } + else { + cert->afterDateSz = 0; + } - #ifdef WOLFSSL_ALT_NAMES - cert->altNamesSz = FlattenAltNames(cert->altNames, - sizeof(cert->altNames), x509->altNames); - #endif /* WOLFSSL_ALT_NAMES */ +#ifdef WOLFSSL_ALT_NAMES + cert->altNamesSz = FlattenAltNames(cert->altNames, + sizeof(cert->altNames), x509->altNames); +#endif /* WOLFSSL_ALT_NAMES */ - cert->sigType = wolfSSL_X509_get_signature_type(x509); - cert->keyType = x509->pubKeyOID; - cert->isCA = wolfSSL_X509_get_isCA(x509); - cert->basicConstSet = x509->basicConstSet; + cert->sigType = wolfSSL_X509_get_signature_type(x509); + cert->keyType = x509->pubKeyOID; + cert->isCA = wolfSSL_X509_get_isCA(x509); + cert->basicConstSet = x509->basicConstSet; - #ifdef WOLFSSL_CERT_EXT - if (x509->subjKeyIdSz <= CTC_MAX_SKID_SIZE) { - if (x509->subjKeyId) { - XMEMCPY(cert->skid, x509->subjKeyId, x509->subjKeyIdSz); - } - cert->skidSz = (int)x509->subjKeyIdSz; - } - else { - WOLFSSL_MSG("Subject Key ID too large"); - WOLFSSL_ERROR_VERBOSE(BUFFER_E); - return WOLFSSL_FAILURE; +#ifdef WOLFSSL_CERT_EXT + if (x509->subjKeyIdSz <= CTC_MAX_SKID_SIZE) { + if (x509->subjKeyId) { + XMEMCPY(cert->skid, x509->subjKeyId, x509->subjKeyIdSz); } + cert->skidSz = (int)x509->subjKeyIdSz; + } + else { + WOLFSSL_MSG("Subject Key ID too large"); + WOLFSSL_ERROR_VERBOSE(BUFFER_E); + return WOLFSSL_FAILURE; + } - if (x509->authKeyIdSz < sizeof(cert->akid)) { - #ifdef WOLFSSL_AKID_NAME - cert->rawAkid = 0; - if (x509->authKeyIdSrc) { - XMEMCPY(cert->akid, x509->authKeyIdSrc, x509->authKeyIdSrcSz); - cert->akidSz = (int)x509->authKeyIdSrcSz; - cert->rawAkid = 1; - } - else - #endif - if (x509->authKeyId) { - XMEMCPY(cert->akid, x509->authKeyId, x509->authKeyIdSz); - cert->akidSz = (int)x509->authKeyIdSz; - } + if (x509->authKeyIdSz < sizeof(cert->akid)) { + #ifdef WOLFSSL_AKID_NAME + cert->rawAkid = 0; + if (x509->authKeyIdSrc) { + XMEMCPY(cert->akid, x509->authKeyIdSrc, x509->authKeyIdSrcSz); + cert->akidSz = (int)x509->authKeyIdSrcSz; + cert->rawAkid = 1; } - else { - WOLFSSL_MSG("Auth Key ID too large"); - WOLFSSL_ERROR_VERBOSE(BUFFER_E); - return WOLFSSL_FAILURE; + else + #endif + if (x509->authKeyId) { + XMEMCPY(cert->akid, x509->authKeyId, x509->authKeyIdSz); + cert->akidSz = (int)x509->authKeyIdSz; } + } + else { + WOLFSSL_MSG("Auth Key ID too large"); + WOLFSSL_ERROR_VERBOSE(BUFFER_E); + return WOLFSSL_FAILURE; + } - for (i = 0; i < x509->certPoliciesNb; i++) { - /* copy the smaller of MAX macros, by default they are currently equal*/ - if ((int)CTC_MAX_CERTPOL_SZ <= (int)MAX_CERTPOL_SZ) { - XMEMCPY(cert->certPolicies[i], x509->certPolicies[i], - CTC_MAX_CERTPOL_SZ); - } - else { - XMEMCPY(cert->certPolicies[i], x509->certPolicies[i], - MAX_CERTPOL_SZ); - } + for (i = 0; i < x509->certPoliciesNb; i++) { + /* copy the smaller of MAX macros, by default they are currently equal*/ + if ((int)CTC_MAX_CERTPOL_SZ <= (int)MAX_CERTPOL_SZ) { + XMEMCPY(cert->certPolicies[i], x509->certPolicies[i], + CTC_MAX_CERTPOL_SZ); + } + else { + XMEMCPY(cert->certPolicies[i], x509->certPolicies[i], + MAX_CERTPOL_SZ); } - cert->certPoliciesNb = (word16)x509->certPoliciesNb; + } + cert->certPoliciesNb = (word16)x509->certPoliciesNb; - cert->keyUsage = x509->keyUsage; - cert->extKeyUsage = x509->extKeyUsage; - cert->nsCertType = x509->nsCertType; + cert->keyUsage = x509->keyUsage; + cert->extKeyUsage = x509->extKeyUsage; + cert->nsCertType = x509->nsCertType; - if (x509->rawCRLInfo != NULL) { - if (x509->rawCRLInfoSz > CTC_MAX_CRLINFO_SZ) { - WOLFSSL_MSG("CRL Info too large"); - WOLFSSL_ERROR_VERBOSE(BUFFER_E); - return WOLFSSL_FAILURE; - } - XMEMCPY(cert->crlInfo, x509->rawCRLInfo, x509->rawCRLInfoSz); - cert->crlInfoSz = x509->rawCRLInfoSz; + if (x509->rawCRLInfo != NULL) { + if (x509->rawCRLInfoSz > CTC_MAX_CRLINFO_SZ) { + WOLFSSL_MSG("CRL Info too large"); + WOLFSSL_ERROR_VERBOSE(BUFFER_E); + return WOLFSSL_FAILURE; } + XMEMCPY(cert->crlInfo, x509->rawCRLInfo, x509->rawCRLInfoSz); + cert->crlInfoSz = x509->rawCRLInfoSz; + } - #ifdef WOLFSSL_DUAL_ALG_CERTS - /* We point to instance in x509 so DON'T need to be free'd. */ - cert->sapkiDer = x509->sapkiDer; - cert->sapkiLen = x509->sapkiLen; - cert->altSigAlgDer = x509->altSigAlgDer; - cert->altSigAlgLen = x509->altSigAlgLen; - cert->altSigValDer = x509->altSigValDer; - cert->altSigValLen = x509->altSigValLen; - #endif /* WOLFSSL_DUAL_ALG_CERTS */ - #endif /* WOLFSSL_CERT_EXT */ +#ifdef WOLFSSL_DUAL_ALG_CERTS + /* We point to instance in x509 so DON'T need to be free'd. */ + cert->sapkiDer = x509->sapkiDer; + cert->sapkiLen = x509->sapkiLen; + cert->altSigAlgDer = x509->altSigAlgDer; + cert->altSigAlgLen = x509->altSigAlgLen; + cert->altSigValDer = x509->altSigValDer; + cert->altSigValLen = x509->altSigValLen; +#endif /* WOLFSSL_DUAL_ALG_CERTS */ +#endif /* WOLFSSL_CERT_EXT */ - #ifdef WOLFSSL_CERT_REQ - /* copy over challenge password for REQ certs */ - XMEMCPY(cert->challengePw, x509->challengePw, CTC_NAME_SIZE); - #endif +#ifdef WOLFSSL_CERT_REQ + /* copy over challenge password for REQ certs */ + XMEMCPY(cert->challengePw, x509->challengePw, CTC_NAME_SIZE); +#endif - /* Only makes sense to do this for OPENSSL_EXTRA because without - * this define the function will error out below */ - #ifdef OPENSSL_EXTRA - if (x509->serialSz == 0 && x509->serialNumber != NULL && - /* Check if the buffer contains more than just the - * ASN tag and length */ - x509->serialNumber->length > 2) { - if (wolfSSL_X509_set_serialNumber(x509, x509->serialNumber) - != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Failed to set serial number"); - return WOLFSSL_FAILURE; - } + /* Only makes sense to do this for OPENSSL_EXTRA because without + * this define the function will error out below */ + #ifdef OPENSSL_EXTRA + if (x509->serialSz == 0 && x509->serialNumber != NULL && + /* Check if the buffer contains more than just the + * ASN tag and length */ + x509->serialNumber->length > 2) { + if (wolfSSL_X509_set_serialNumber(x509, x509->serialNumber) + != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to set serial number"); + return WOLFSSL_FAILURE; } - #endif + } + #endif - /* set serial number */ - if (x509->serialSz > 0) { - #if defined(OPENSSL_EXTRA) - byte serial[EXTERNAL_SERIAL_SIZE]; - int serialSz = EXTERNAL_SERIAL_SIZE; + /* set serial number */ + if (x509->serialSz > 0) { + #if defined(OPENSSL_EXTRA) + byte serial[EXTERNAL_SERIAL_SIZE]; + int serialSz = EXTERNAL_SERIAL_SIZE; - ret = wolfSSL_X509_get_serial_number(x509, serial, &serialSz); - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Serial size error"); - return WOLFSSL_FAILURE; - } + ret = wolfSSL_X509_get_serial_number(x509, serial, &serialSz); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Serial size error"); + return WOLFSSL_FAILURE; + } - if (serialSz > EXTERNAL_SERIAL_SIZE || - serialSz > CTC_SERIAL_SIZE) { - WOLFSSL_MSG("Serial size too large error"); - WOLFSSL_ERROR_VERBOSE(BUFFER_E); - return WOLFSSL_FAILURE; - } - XMEMCPY(cert->serial, serial, serialSz); - cert->serialSz = serialSz; - #else - WOLFSSL_MSG("Getting X509 serial number not supported"); + if (serialSz > EXTERNAL_SERIAL_SIZE || + serialSz > CTC_SERIAL_SIZE) { + WOLFSSL_MSG("Serial size too large error"); + WOLFSSL_ERROR_VERBOSE(BUFFER_E); return WOLFSSL_FAILURE; - #endif } + XMEMCPY(cert->serial, serial, serialSz); + cert->serialSz = serialSz; + #else + WOLFSSL_MSG("Getting X509 serial number not supported"); + return WOLFSSL_FAILURE; + #endif + } - /* copy over Name structures */ - if (x509->issuerSet) - cert->selfSigned = 0; + /* copy over Name structures */ + if (x509->issuerSet) + cert->selfSigned = 0; - #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) - ret = CopyX509NameToCert(&x509->subject, cert->sbjRaw); +#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) + ret = CopyX509NameToCert(&x509->subject, cert->sbjRaw); + if (ret < 0) { + WOLFSSL_MSG("Subject conversion error"); + return MEMORY_E; + } + if (cert->selfSigned) { + XMEMCPY(cert->issRaw, cert->sbjRaw, sizeof(CertName)); + } + else { + ret = CopyX509NameToCert(&x509->issuer, cert->issRaw); if (ret < 0) { - WOLFSSL_MSG("Subject conversion error"); + WOLFSSL_MSG("Issuer conversion error"); return MEMORY_E; } - if (cert->selfSigned) { - XMEMCPY(cert->issRaw, cert->sbjRaw, sizeof(CertName)); - } - else { - ret = CopyX509NameToCert(&x509->issuer, cert->issRaw); - if (ret < 0) { - WOLFSSL_MSG("Issuer conversion error"); - return MEMORY_E; - } - } - #endif + } +#endif - cert->heap = x509->heap; + cert->heap = x509->heap; - (void)ret; - return WOLFSSL_SUCCESS; - } + (void)ret; + return WOLFSSL_SUCCESS; +} /* returns the sig type to use on success i.e CTC_SHAwRSA and WOLFSSL_FALURE @@ -10638,7 +10772,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( return WOLFSSL_FAILURE; } - if (pkey->type == EVP_PKEY_RSA) { + if (pkey->type == WC_EVP_PKEY_RSA) { switch (hashType) { case WC_HASH_TYPE_SHA: sigType = CTC_SHAwRSA; @@ -10673,7 +10807,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( return WOLFSSL_FAILURE; } } - else if (pkey->type == EVP_PKEY_EC) { + else if (pkey->type == WC_EVP_PKEY_EC) { switch (hashType) { case WC_HASH_TYPE_SHA: sigType = CTC_SHAwECDSA; @@ -11181,13 +11315,13 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( /* Get the private key object and type from pkey. */ #ifndef NO_RSA - if (pkey->type == EVP_PKEY_RSA) { + if (pkey->type == WC_EVP_PKEY_RSA) { type = RSA_TYPE; key = pkey->rsa->internal; } #endif #ifdef HAVE_ECC - if (pkey->type == EVP_PKEY_EC) { + if (pkey->type == WC_EVP_PKEY_EC) { type = ECC_TYPE; key = pkey->ecc->internal; } @@ -11197,7 +11331,8 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( ret = wc_InitRng(&rng); if (ret != 0) return ret; - ret = wc_SignCert_ex(certBodySz, sigType, der, (word32)derSz, type, key, &rng); + ret = wc_SignCert_ex(certBodySz, sigType, der, (word32)derSz, type, key, + &rng); wc_FreeRng(&rng); if (ret < 0) { WOLFSSL_LEAVE("wolfSSL_X509_resign_cert", ret); @@ -11263,70 +11398,71 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } - #ifndef WC_MAX_X509_GEN - /* able to override max size until dynamic buffer created */ - #define WC_MAX_X509_GEN 4096 - #endif +#ifndef WC_MAX_X509_GEN + /* able to override max size until dynamic buffer created */ + #define WC_MAX_X509_GEN 4096 +#endif - /* returns the size of signature on success */ - int wolfSSL_X509_sign(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, - const WOLFSSL_EVP_MD* md) - { - int ret; - /* @TODO dynamic set based on expected cert size */ - byte *der = (byte *)XMALLOC(WC_MAX_X509_GEN, NULL, DYNAMIC_TYPE_TMP_BUFFER); - int derSz = WC_MAX_X509_GEN; +/* returns the size of signature on success */ +int wolfSSL_X509_sign(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey, + const WOLFSSL_EVP_MD* md) +{ + int ret; + /* @TODO dynamic set based on expected cert size */ + byte *der = (byte *)XMALLOC(WC_MAX_X509_GEN, NULL, DYNAMIC_TYPE_TMP_BUFFER); + int derSz = WC_MAX_X509_GEN; - WOLFSSL_ENTER("wolfSSL_X509_sign"); + WOLFSSL_ENTER("wolfSSL_X509_sign"); - if (x509 == NULL || pkey == NULL || md == NULL) { - ret = WOLFSSL_FAILURE; - goto out; - } + if (x509 == NULL || pkey == NULL || md == NULL) { + ret = WOLFSSL_FAILURE; + goto out; + } - x509->sigOID = wolfSSL_sigTypeFromPKEY((WOLFSSL_EVP_MD*)md, pkey); - if ((ret = wolfssl_x509_make_der(x509, 0, der, &derSz, 0)) != - WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Unable to make DER for X509"); - WOLFSSL_LEAVE("wolfSSL_X509_sign", ret); - (void)ret; - ret = WOLFSSL_FAILURE; - goto out; - } + x509->sigOID = wolfSSL_sigTypeFromPKEY((WOLFSSL_EVP_MD*)md, pkey); + if ((ret = wolfssl_x509_make_der(x509, 0, der, &derSz, 0)) != + WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Unable to make DER for X509"); + WOLFSSL_LEAVE("wolfSSL_X509_sign", ret); + (void)ret; + ret = WOLFSSL_FAILURE; + goto out; + } - ret = wolfSSL_X509_resign_cert(x509, 0, der, WC_MAX_X509_GEN, derSz, - (WOLFSSL_EVP_MD*)md, pkey); - if (ret <= 0) { - WOLFSSL_LEAVE("wolfSSL_X509_sign", ret); - ret = WOLFSSL_FAILURE; - goto out; - } + ret = wolfSSL_X509_resign_cert(x509, 0, der, WC_MAX_X509_GEN, derSz, + (WOLFSSL_EVP_MD*)md, pkey); + if (ret <= 0) { + WOLFSSL_LEAVE("wolfSSL_X509_sign", ret); + ret = WOLFSSL_FAILURE; + goto out; + } - out: - XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); +out: + XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return ret; - } + return ret; +} #if defined(OPENSSL_EXTRA) - int wolfSSL_X509_sign_ctx(WOLFSSL_X509 *x509, WOLFSSL_EVP_MD_CTX *ctx) - { - WOLFSSL_ENTER("wolfSSL_X509_sign_ctx"); - - if (!x509 || !ctx || !ctx->pctx || !ctx->pctx->pkey) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } +int wolfSSL_X509_sign_ctx(WOLFSSL_X509 *x509, WOLFSSL_EVP_MD_CTX *ctx) +{ + WOLFSSL_ENTER("wolfSSL_X509_sign_ctx"); - return wolfSSL_X509_sign(x509, ctx->pctx->pkey, wolfSSL_EVP_MD_CTX_md(ctx)); + if (!x509 || !ctx || !ctx->pctx || !ctx->pctx->pkey) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } + + return wolfSSL_X509_sign(x509, ctx->pctx->pkey, + wolfSSL_EVP_MD_CTX_md(ctx)); +} #endif /* OPENSSL_EXTRA */ #endif /* WOLFSSL_CERT_GEN */ #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_WPAS_SMALL) -/* Converts from NID_* value to wolfSSL value if needed. +/* Converts from WC_NID_* value to wolfSSL value if needed. * * @param [in] nid Numeric Id of a domain name component. * @return Domain name tag values - wolfSSL internal values. @@ -11335,28 +11471,29 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( static int ConvertNIDToWolfSSL(int nid) { switch (nid) { - case NID_commonName : return ASN_COMMON_NAME; + case WC_NID_commonName : return ASN_COMMON_NAME; #ifdef WOLFSSL_CERT_NAME_ALL - case NID_name : return ASN_NAME; - case NID_givenName: return ASN_GIVEN_NAME; - case NID_dnQualifier : return ASN_DNQUALIFIER; - case NID_initials: return ASN_INITIALS; + case WC_NID_name : return ASN_NAME; + case WC_NID_givenName: return ASN_GIVEN_NAME; + case WC_NID_dnQualifier : return ASN_DNQUALIFIER; + case WC_NID_initials: return ASN_INITIALS; #endif /* WOLFSSL_CERT_NAME_ALL */ - case NID_surname : return ASN_SUR_NAME; - case NID_countryName: return ASN_COUNTRY_NAME; - case NID_localityName: return ASN_LOCALITY_NAME; - case NID_stateOrProvinceName: return ASN_STATE_NAME; - case NID_streetAddress: return ASN_STREET_ADDR; - case NID_organizationName: return ASN_ORG_NAME; - case NID_organizationalUnitName: return ASN_ORGUNIT_NAME; - case NID_emailAddress: return ASN_EMAIL_NAME; - case NID_pkcs9_contentType: return ASN_CONTENT_TYPE; - case NID_serialNumber: return ASN_SERIAL_NUMBER; - case NID_userId: return ASN_USER_ID; - case NID_businessCategory: return ASN_BUS_CAT; - case NID_domainComponent: return ASN_DOMAIN_COMPONENT; - case NID_postalCode: return ASN_POSTAL_CODE; - case NID_favouriteDrink: return ASN_FAVOURITE_DRINK; + case WC_NID_surname : return ASN_SUR_NAME; + case WC_NID_countryName: return ASN_COUNTRY_NAME; + case WC_NID_localityName: return ASN_LOCALITY_NAME; + case WC_NID_stateOrProvinceName: return ASN_STATE_NAME; + case WC_NID_streetAddress: return ASN_STREET_ADDR; + case WC_NID_organizationName: return ASN_ORG_NAME; + case WC_NID_organizationalUnitName: return ASN_ORGUNIT_NAME; + case WC_NID_emailAddress: return ASN_EMAIL_NAME; + case WC_NID_pkcs9_contentType: return ASN_CONTENT_TYPE; + case WC_NID_serialNumber: return ASN_SERIAL_NUMBER; + case WC_NID_userId: return ASN_USER_ID; + case WC_NID_businessCategory: return ASN_BUS_CAT; + case WC_NID_domainComponent: return ASN_DOMAIN_COMPONENT; + case WC_NID_postalCode: return ASN_POSTAL_CODE; + case WC_NID_rfc822Mailbox: return ASN_RFC822_MAILBOX; + case WC_NID_favouriteDrink: return ASN_FAVOURITE_DRINK; default: WOLFSSL_MSG("Attribute NID not found"); return WOLFSSL_FATAL_ERROR; @@ -11365,7 +11502,8 @@ static int ConvertNIDToWolfSSL(int nid) #endif /* OPENSSL_ALL || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL*/ -#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_EXTRA_X509_SMALL) /* This is to convert the x509 name structure into canonical DER format */ /* , which has the following rules: */ /* convert to UTF8 */ @@ -11555,15 +11693,16 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) type = wolfSSL_ASN1_STRING_type(data); switch (type) { - case MBSTRING_UTF8: + case WOLFSSL_MBSTRING_UTF8: type = CTC_UTF8; break; - case MBSTRING_ASC: - case V_ASN1_PRINTABLESTRING: + case WOLFSSL_MBSTRING_ASC: + case WOLFSSL_V_ASN1_PRINTABLESTRING: type = CTC_PRINTABLE; break; default: - WOLFSSL_MSG("Unknown encoding type conversion UTF8 by default"); + WOLFSSL_MSG( + "Unknown encoding type conversion UTF8 by default"); type = CTC_UTF8; } ret = wc_EncodeName(&names[i], nameStr, (char)type, @@ -11734,96 +11873,96 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) #ifndef NO_BIO - static WOLFSSL_X509 *loadX509orX509REQFromPemBio(WOLFSSL_BIO *bp, - WOLFSSL_X509 **x, wc_pem_password_cb *cb, void *u, int type) - { - WOLFSSL_X509* x509 = NULL; +static WOLFSSL_X509 *loadX509orX509REQFromPemBio(WOLFSSL_BIO *bp, + WOLFSSL_X509 **x, wc_pem_password_cb *cb, void *u, int type) +{ + WOLFSSL_X509* x509 = NULL; #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) - unsigned char* pem = NULL; - int pemSz; - long i = 0, l, footerSz; - const char* footer = NULL; + unsigned char* pem = NULL; + int pemSz; + long i = 0, l, footerSz; + const char* footer = NULL; - WOLFSSL_ENTER("loadX509orX509REQFromPemBio"); + WOLFSSL_ENTER("loadX509orX509REQFromPemBio"); - if (bp == NULL || (type != CERT_TYPE && type != CERTREQ_TYPE)) { - WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_X509", BAD_FUNC_ARG); - return NULL; - } + if (bp == NULL || (type != CERT_TYPE && type != CERTREQ_TYPE)) { + WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_X509", BAD_FUNC_ARG); + return NULL; + } - if ((l = wolfSSL_BIO_get_len(bp)) <= 0) { - /* No certificate in buffer */ + if ((l = wolfSSL_BIO_get_len(bp)) <= 0) { + /* No certificate in buffer */ #if defined (WOLFSSL_HAPROXY) - WOLFSSL_ERROR(PEM_R_NO_START_LINE); + WOLFSSL_ERROR(PEM_R_NO_START_LINE); #else - WOLFSSL_ERROR(ASN_NO_PEM_HEADER); + WOLFSSL_ERROR(ASN_NO_PEM_HEADER); #endif - return NULL; - } + return NULL; + } - pemSz = (int)l; - pem = (unsigned char*)XMALLOC(pemSz, 0, DYNAMIC_TYPE_PEM); - if (pem == NULL) - return NULL; - XMEMSET(pem, 0, pemSz); + pemSz = (int)l; + pem = (unsigned char*)XMALLOC(pemSz, 0, DYNAMIC_TYPE_PEM); + if (pem == NULL) + return NULL; + XMEMSET(pem, 0, pemSz); - i = 0; - if (wc_PemGetHeaderFooter(type, NULL, &footer) != 0) { - XFREE(pem, 0, DYNAMIC_TYPE_PEM); - return NULL; - } - footerSz = (long)XSTRLEN(footer); + i = 0; + if (wc_PemGetHeaderFooter(type, NULL, &footer) != 0) { + XFREE(pem, 0, DYNAMIC_TYPE_PEM); + return NULL; + } + footerSz = (long)XSTRLEN(footer); - /* TODO: Inefficient - * reading in one byte at a time until see the footer - */ - while ((l = wolfSSL_BIO_read(bp, (char *)&pem[i], 1)) == 1) { - i++; - if (i > footerSz && XMEMCMP((char *)&pem[i-footerSz], footer, - footerSz) == 0) { - if (wolfSSL_BIO_read(bp, (char *)&pem[i], 1) == 1) { - /* attempt to read newline following footer */ - i++; - if (pem[i-1] == '\r') { - /* found \r , Windows line ending is \r\n so try to read one - * more byte for \n, ignoring return value */ - (void)wolfSSL_BIO_read(bp, (char *)&pem[i++], 1); - } + /* TODO: Inefficient + * reading in one byte at a time until see the footer + */ + while ((l = wolfSSL_BIO_read(bp, (char *)&pem[i], 1)) == 1) { + i++; + if (i > footerSz && XMEMCMP((char *)&pem[i-footerSz], footer, + footerSz) == 0) { + if (wolfSSL_BIO_read(bp, (char *)&pem[i], 1) == 1) { + /* attempt to read newline following footer */ + i++; + if (pem[i-1] == '\r') { + /* found \r , Windows line ending is \r\n so try to read one + * more byte for \n, ignoring return value */ + (void)wolfSSL_BIO_read(bp, (char *)&pem[i++], 1); } - break; } + break; } - if (l == 0) - WOLFSSL_ERROR(ASN_NO_PEM_HEADER); - if (i > pemSz) { - WOLFSSL_MSG("Error parsing PEM"); - } - else { - pemSz = (int)i; - #ifdef WOLFSSL_CERT_REQ - if (type == CERTREQ_TYPE) - x509 = wolfSSL_X509_REQ_load_certificate_buffer(pem, pemSz, - WOLFSSL_FILETYPE_PEM); - else - #endif - x509 = wolfSSL_X509_load_certificate_buffer(pem, pemSz, - WOLFSSL_FILETYPE_PEM); - } + } + if (l == 0) + WOLFSSL_ERROR(ASN_NO_PEM_HEADER); + if (i > pemSz) { + WOLFSSL_MSG("Error parsing PEM"); + } + else { + pemSz = (int)i; + #ifdef WOLFSSL_CERT_REQ + if (type == CERTREQ_TYPE) + x509 = wolfSSL_X509_REQ_load_certificate_buffer(pem, pemSz, + WOLFSSL_FILETYPE_PEM); + else + #endif + x509 = wolfSSL_X509_load_certificate_buffer(pem, pemSz, + WOLFSSL_FILETYPE_PEM); + } - if (x != NULL) { - *x = x509; - } + if (x != NULL) { + *x = x509; + } - XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */ - (void)bp; - (void)x; - (void)cb; - (void)u; + (void)bp; + (void)x; + (void)cb; + (void)u; - return x509; - } + return x509; +} #if defined(WOLFSSL_ACERT) @@ -11911,11 +12050,11 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } #ifdef WOLFSSL_CERT_REQ - WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_REQ(WOLFSSL_BIO *bp, WOLFSSL_X509 **x, +WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_REQ(WOLFSSL_BIO *bp, WOLFSSL_X509 **x, wc_pem_password_cb *cb, void *u) - { - return loadX509orX509REQFromPemBio(bp, x, cb, u, CERTREQ_TYPE); - } +{ + return loadX509orX509REQFromPemBio(bp, x, cb, u, CERTREQ_TYPE); +} #ifndef NO_FILESYSTEM WOLFSSL_X509* wolfSSL_PEM_read_X509_REQ(XFILE fp, WOLFSSL_X509** x, @@ -11939,7 +12078,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) err = 1; } } - if (err == 0 && wolfSSL_BIO_set_fp(bio, fp, BIO_CLOSE) + if (err == 0 && wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to set BIO file pointer."); err = 1; @@ -11948,9 +12087,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) ret = wolfSSL_PEM_read_bio_X509_REQ(bio, x, cb, u); } - if (bio != NULL) { - wolfSSL_BIO_free(bio); - } + wolfSSL_BIO_free(bio); return ret; } @@ -11980,17 +12117,17 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) goto err; } - if((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) { + if ((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) { goto err; } derSz = (int)der->length; - if((crl = wolfSSL_d2i_X509_CRL(x, der->buffer, derSz)) == NULL) { + if ((crl = wolfSSL_d2i_X509_CRL(x, der->buffer, derSz)) == NULL) { goto err; } err: XFREE(pem, 0, DYNAMIC_TYPE_PEM); - if(der != NULL) { + if (der != NULL) { FreeDer(&der); } @@ -12011,106 +12148,107 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) #endif /* !NO_BIO */ #if !defined(NO_FILESYSTEM) - static void* wolfSSL_PEM_read_X509_ex(XFILE fp, void **x, - wc_pem_password_cb *cb, void *u, int type) - { - unsigned char* pem = NULL; - int pemSz; - long i = 0, l; - void *newx509; - int derSz; - DerBuffer* der = NULL; - - WOLFSSL_ENTER("wolfSSL_PEM_read_X509"); +static void* wolfSSL_PEM_read_X509_ex(XFILE fp, void **x, + wc_pem_password_cb *cb, void *u, int type) +{ + unsigned char* pem = NULL; + int pemSz; + long i = 0, l; + void *newx509; + int derSz; + DerBuffer* der = NULL; - if (fp == XBADFILE) { - WOLFSSL_LEAVE("wolfSSL_PEM_read_X509", BAD_FUNC_ARG); - return NULL; - } - /* Read cert from file */ - i = XFTELL(fp); - if (i < 0) { - WOLFSSL_LEAVE("wolfSSL_PEM_read_X509", BAD_FUNC_ARG); - return NULL; - } + WOLFSSL_ENTER("wolfSSL_PEM_read_X509"); - if (XFSEEK(fp, 0, XSEEK_END) != 0) - return NULL; - l = XFTELL(fp); - if (l < 0) - return NULL; - if (XFSEEK(fp, i, SEEK_SET) != 0) - return NULL; - pemSz = (int)(l - i); + if (fp == XBADFILE) { + WOLFSSL_LEAVE("wolfSSL_PEM_read_X509", BAD_FUNC_ARG); + return NULL; + } + /* Read cert from file */ + i = XFTELL(fp); + if (i < 0) { + WOLFSSL_LEAVE("wolfSSL_PEM_read_X509", BAD_FUNC_ARG); + return NULL; + } - /* check calculated length */ - if (pemSz > MAX_WOLFSSL_FILE_SIZE || pemSz <= 0) { - WOLFSSL_MSG("PEM_read_X509_ex file size error"); - return NULL; - } + if (XFSEEK(fp, 0, XSEEK_END) != 0) + return NULL; + l = XFTELL(fp); + if (l < 0) + return NULL; + if (XFSEEK(fp, i, SEEK_SET) != 0) + return NULL; + pemSz = (int)(l - i); - /* allocate pem buffer */ - pem = (unsigned char*)XMALLOC(pemSz, NULL, DYNAMIC_TYPE_PEM); - if (pem == NULL) - return NULL; + /* check calculated length */ + if (pemSz > MAX_WOLFSSL_FILE_SIZE || pemSz <= 0) { + WOLFSSL_MSG("PEM_read_X509_ex file size error"); + return NULL; + } - if ((int)XFREAD((char *)pem, 1, (size_t)pemSz, fp) != pemSz) - goto err_exit; + /* allocate pem buffer */ + pem = (unsigned char*)XMALLOC(pemSz, NULL, DYNAMIC_TYPE_PEM); + if (pem == NULL) + return NULL; - switch (type) { - case CERT_TYPE: - newx509 = (void *)wolfSSL_X509_load_certificate_buffer(pem, - pemSz, WOLFSSL_FILETYPE_PEM); - break; + if ((int)XFREAD((char *)pem, 1, (size_t)pemSz, fp) != pemSz) + goto err_exit; - #ifdef HAVE_CRL - case CRL_TYPE: - if ((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) - goto err_exit; - derSz = (int)der->length; - newx509 = (void*)wolfSSL_d2i_X509_CRL((WOLFSSL_X509_CRL **)x, - (const unsigned char *)der->buffer, derSz); - if (newx509 == NULL) - goto err_exit; - FreeDer(&der); - break; - #endif + switch (type) { + case CERT_TYPE: + newx509 = (void *)wolfSSL_X509_load_certificate_buffer(pem, + pemSz, WOLFSSL_FILETYPE_PEM); + break; - default: + #ifdef HAVE_CRL + case CRL_TYPE: + if ((PemToDer(pem, pemSz, CRL_TYPE, &der, NULL, NULL, NULL)) < 0) + goto err_exit; + derSz = (int)der->length; + newx509 = (void*)wolfSSL_d2i_X509_CRL((WOLFSSL_X509_CRL **)x, + (const unsigned char *)der->buffer, derSz); + if (newx509 == NULL) goto err_exit; - } - if (x != NULL) { - *x = newx509; - } - XFREE(pem, NULL, DYNAMIC_TYPE_PEM); - return newx509; - - err_exit: - XFREE(pem, NULL, DYNAMIC_TYPE_PEM); - if (der != NULL) FreeDer(&der); + break; + #endif - /* unused */ - (void)cb; - (void)u; - (void)derSz; - - return NULL; + default: + goto err_exit; } - - WOLFSSL_API WOLFSSL_X509* wolfSSL_PEM_read_X509(XFILE fp, WOLFSSL_X509 **x, - wc_pem_password_cb *cb, - void *u) - { - return (WOLFSSL_X509* )wolfSSL_PEM_read_X509_ex(fp, (void **)x, cb, u, CERT_TYPE); + if (x != NULL) { + *x = newx509; } + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + return newx509; + +err_exit: + XFREE(pem, NULL, DYNAMIC_TYPE_PEM); + if (der != NULL) + FreeDer(&der); + + /* unused */ + (void)cb; + (void)u; + (void)derSz; + + return NULL; +} + +WOLFSSL_API WOLFSSL_X509* wolfSSL_PEM_read_X509(XFILE fp, WOLFSSL_X509 **x, + wc_pem_password_cb *cb, void *u) +{ + return (WOLFSSL_X509* )wolfSSL_PEM_read_X509_ex(fp, (void **)x, cb, u, + CERT_TYPE); +} #if defined(HAVE_CRL) - WOLFSSL_API WOLFSSL_X509_CRL* wolfSSL_PEM_read_X509_CRL(XFILE fp, WOLFSSL_X509_CRL **crl, - wc_pem_password_cb *cb, void *u) - { - return (WOLFSSL_X509_CRL* )wolfSSL_PEM_read_X509_ex(fp, (void **)crl, cb, u, CRL_TYPE); - } +WOLFSSL_API WOLFSSL_X509_CRL* wolfSSL_PEM_read_X509_CRL(XFILE fp, + WOLFSSL_X509_CRL **crl, wc_pem_password_cb *cb, void *u) +{ + return (WOLFSSL_X509_CRL* )wolfSSL_PEM_read_X509_ex(fp, (void **)crl, cb, u, + CRL_TYPE); +} #endif #ifdef WOLFSSL_CERT_GEN @@ -12120,14 +12258,14 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) int ret; WOLFSSL_BIO* bio; - if (x == NULL) + if (x == NULL || fp == XBADFILE) return 0; bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file()); if (bio == NULL) return 0; - if (wolfSSL_BIO_set_fp(bio, fp, BIO_NOCLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_NOCLOSE) != WOLFSSL_SUCCESS) { wolfSSL_BIO_free(bio); bio = NULL; } @@ -12302,7 +12440,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) "-----BEGIN X509 CRL-----")) { /* We have a crl */ WOLFSSL_MSG("Parsing crl"); - if((PemToDer((const unsigned char*) header, + if ((PemToDer((const unsigned char*) header, (long)(footerEnd - header), CRL_TYPE, &der, NULL, NULL, NULL)) < 0) { WOLFSSL_MSG("PemToDer error"); @@ -12373,7 +12511,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) XFILE fp, WOLF_STACK_OF(WOLFSSL_X509_INFO)* sk, pem_password_cb* cb, void* u) { - WOLFSSL_BIO* fileBio = wolfSSL_BIO_new_fp(fp, BIO_NOCLOSE); + WOLFSSL_BIO* fileBio = wolfSSL_BIO_new_fp(fp, WOLFSSL_BIO_NOCLOSE); WOLF_STACK_OF(WOLFSSL_X509_INFO)* ret = NULL; WOLFSSL_ENTER("wolfSSL_PEM_X509_INFO_read"); @@ -12536,16 +12674,12 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) static void wolfssl_x509_name_entry_set(WOLFSSL_X509_NAME_ENTRY* ne, int nid, int type, const unsigned char *data, int dataSz) { - WOLFSSL_ASN1_OBJECT* object; - ne->nid = nid; /* Reuse the object if already available. */ - object = wolfSSL_OBJ_nid2obj_ex(nid, ne->object); - if (object != NULL) { - /* Set the object when no error. */ - ne->object = object; + ne->object = wolfSSL_OBJ_nid2obj_ex(nid, ne->object); + if (ne->value == NULL) { + ne->value = wolfSSL_ASN1_STRING_type_new(type); } - ne->value = wolfSSL_ASN1_STRING_type_new(type); if (ne->value != NULL) { if (wolfSSL_ASN1_STRING_set(ne->value, (const void*)data, dataSz) == WOLFSSL_SUCCESS) { @@ -12579,7 +12713,7 @@ int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out) } nid = wolfSSL_OBJ_txt2nid(txt); - if (nid == NID_undef) { + if (nid == WC_NID_undef) { WOLFSSL_MSG("Unable to find text"); ne = NULL; } @@ -12856,7 +12990,7 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( if (name == NULL || field == NULL) return WOLFSSL_FAILURE; - if ((nid = wolfSSL_OBJ_txt2nid(field)) == NID_undef) { + if ((nid = wolfSSL_OBJ_txt2nid(field)) == WC_NID_undef) { WOLFSSL_MSG("Unable convert text to NID"); return WOLFSSL_FAILURE; } @@ -12926,7 +13060,8 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( for (idx++; idx < MAX_NAME_ENTRIES; idx++) { /* Find index of desired name */ if (name->entry[idx].set) { - if (XSTRLEN(obj->sName) == XSTRLEN(name->entry[idx].object->sName) && + if (XSTRLEN(obj->sName) == + XSTRLEN(name->entry[idx].object->sName) && XSTRNCMP((const char*) obj->sName, name->entry[idx].object->sName, obj->objSz - 1) == 0) { return idx; @@ -12977,26 +13112,26 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( #ifdef OPENSSL_EXTRA - int wolfSSL_X509_check_private_key(WOLFSSL_X509 *x509, WOLFSSL_EVP_PKEY *key) - { - WOLFSSL_ENTER("wolfSSL_X509_check_private_key"); - - if (!x509 || !key) { - WOLFSSL_MSG("Bad parameter"); - return WOLFSSL_FAILURE; - } +int wolfSSL_X509_check_private_key(WOLFSSL_X509 *x509, WOLFSSL_EVP_PKEY *key) +{ + WOLFSSL_ENTER("wolfSSL_X509_check_private_key"); - #ifndef NO_CHECK_PRIVATE_KEY - return wc_CheckPrivateKey((byte*)key->pkey.ptr, key->pkey_sz, - x509->pubKey.buffer, x509->pubKey.length, - (enum Key_Sum)x509->pubKeyOID, key->heap) == 1 ? - WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - #else - /* not compiled in */ - return WOLFSSL_SUCCESS; - #endif + if (!x509 || !key) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; } +#ifndef NO_CHECK_PRIVATE_KEY + return wc_CheckPrivateKey((byte*)key->pkey.ptr, key->pkey_sz, + x509->pubKey.buffer, x509->pubKey.length, + (enum Key_Sum)x509->pubKeyOID, key->heap) == 1 ? + WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +#else + /* not compiled in */ + return WOLFSSL_SUCCESS; +#endif +} + #endif /* OPENSSL_EXTRA */ #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \ @@ -13158,9 +13293,10 @@ int wolfSSL_PEM_write_bio_X509(WOLFSSL_BIO *bio, WOLFSSL_X509 *cert) #endif /* !NO_BIO */ #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */ -#if defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB) +#if defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_OPENSSH) || \ + defined(HAVE_SBLIM_SFCB) WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_sk_X509_NAME_new( WOLF_SK_COMPARE_CB(WOLFSSL_X509_NAME, cb)) @@ -13196,14 +13332,15 @@ int wolfSSL_sk_X509_NAME_num(const WOLF_STACK_OF(WOLFSSL_X509_NAME) *sk) * returns a pointer to a WOLFSSL_X509_NAME structure on success and NULL on * fail */ -WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_value(const STACK_OF(WOLFSSL_X509_NAME)* sk, - int i) +WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_value( + const WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk, int i) { WOLFSSL_ENTER("wolfSSL_sk_X509_NAME_value"); return (WOLFSSL_X509_NAME*)wolfSSL_sk_value(sk, i); } -WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_pop(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) +WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_pop( + WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) { WOLFSSL_STACK* node; WOLFSSL_X509_NAME* name; @@ -13296,7 +13433,8 @@ WOLFSSL_X509_NAME_ENTRY* wolfSSL_sk_X509_NAME_ENTRY_value( return (WOLFSSL_X509_NAME_ENTRY*)wolfSSL_sk_value(sk, i); } -int wolfSSL_sk_X509_NAME_ENTRY_num(const WOLF_STACK_OF(WOLFSSL_X509_NAME_ENTRY)* sk) +int wolfSSL_sk_X509_NAME_ENTRY_num( + const WOLF_STACK_OF(WOLFSSL_X509_NAME_ENTRY)* sk) { if (sk == NULL) return BAD_FUNC_ARG; @@ -13421,7 +13559,7 @@ void wolfSSL_sk_X509_INFO_free(WOLF_STACK_OF(WOLFSSL_X509_INFO) *sk) /* Adds the WOLFSSL_X509_INFO to the stack "sk". "sk" takes control of "in" and * tries to free it when the stack is free'd. * - * return 1 on success 0 on fail + * return number of elements on success 0 on fail */ int wolfSSL_sk_X509_INFO_push(WOLF_STACK_OF(WOLFSSL_X509_INFO)* sk, WOLFSSL_X509_INFO* in) @@ -13460,7 +13598,8 @@ WOLF_STACK_OF(WOLFSSL_X509_NAME) *wolfSSL_dup_CA_list( return copy; } -void* wolfSSL_sk_X509_OBJECT_value(WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* sk, int i) +void* wolfSSL_sk_X509_OBJECT_value(WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* sk, + int i) { WOLFSSL_ENTER("wolfSSL_sk_X509_OBJECT_value"); for (; sk != NULL && i > 0; i--) @@ -13476,7 +13615,8 @@ int wolfSSL_sk_X509_OBJECT_num(const WOLF_STACK_OF(WOLFSSL_X509_OBJECT) *s) WOLFSSL_ENTER("wolfSSL_sk_X509_OBJECT_num"); if (s) { return (int)s->num; - } else { + } + else { return 0; } } @@ -13506,82 +13646,86 @@ static int get_dn_attr_by_nid(int n, const char** buf) switch(n) { - case NID_commonName : + case WC_NID_commonName : str = "CN"; len = 2; break; - case NID_countryName: + case WC_NID_countryName: str = "C"; len = 1; break; - case NID_localityName: + case WC_NID_localityName: str = "L"; len = 1; break; - case NID_stateOrProvinceName: + case WC_NID_stateOrProvinceName: str = "ST"; len = 2; break; - case NID_streetAddress: + case WC_NID_streetAddress: str = "street"; len = 6; break; - case NID_organizationName: + case WC_NID_organizationName: str = "O"; len = 1; break; - case NID_organizationalUnitName: + case WC_NID_organizationalUnitName: str = "OU"; len = 2; break; - case NID_postalCode: + case WC_NID_postalCode: str = "postalCode"; len = 10; break; - case NID_emailAddress: + case WC_NID_emailAddress: str = "emailAddress"; len = 12; break; - case NID_surname: + case WC_NID_surname: str = "SN"; len = 2; break; - case NID_givenName: + case WC_NID_givenName: str = "GN"; len = 2; break; - case NID_dnQualifier: + case WC_NID_dnQualifier: str = "dnQualifier"; len = 11; break; - case NID_name: + case WC_NID_name: str = "name"; len = 4; break; - case NID_initials: + case WC_NID_initials: str = "initials"; len = 8; break; - case NID_domainComponent: + case WC_NID_domainComponent: str = "DC"; len = 2; break; - case NID_pkcs9_contentType: + case WC_NID_pkcs9_contentType: str = "contentType"; len = 11; break; - case NID_userId: + case WC_NID_userId: str = "UID"; len = 3; break; - case NID_serialNumber: + case WC_NID_serialNumber: str = "serialNumber"; len = 12; break; - case NID_title: + case WC_NID_title: str = "title"; len = 5; break; + case WC_NID_rfc822Mailbox: + str = "mail"; + len = 4; + break; default: WOLFSSL_MSG("Attribute type not found"); str = NULL; @@ -13684,7 +13828,7 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, return WOLFSSL_FAILURE; XMEMSET(eqStr, 0, sizeof(eqStr)); - if (flags & XN_FLAG_SPC_EQ) { + if (flags & WOLFSSL_XN_FLAG_SPC_EQ) { eqSpace = 2; XSTRNCPY(eqStr, " = ", 4); } @@ -13704,9 +13848,10 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, int tmpSz; /* reverse name order for RFC2253 and DN_REV */ - if ((flags & XN_FLAG_RFC2253) || (flags & XN_FLAG_DN_REV)) { + if ((flags & WOLFSSL_XN_FLAG_RFC2253) || (flags & WOLFSSL_XN_FLAG_DN_REV)) { ne = wolfSSL_X509_NAME_get_entry(name, count - i - 1); - } else { + } + else { ne = wolfSSL_X509_NAME_get_entry(name, i); } if (ne == NULL) @@ -13716,7 +13861,7 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, if (str == NULL) return WOLFSSL_FAILURE; - if (flags & XN_FLAG_RFC2253) { + if (flags & WOLFSSL_XN_FLAG_RFC2253) { /* escape string for RFC 2253, ret sz not counting null term */ escapeSz = wolfSSL_EscapeString_RFC2253(str->data, str->length, escaped, sizeof(escaped)); @@ -13763,10 +13908,12 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, return WOLFSSL_FAILURE; } tmpSz = len + nameStrSz + 1 + eqSpace; /* 1 for '=' */ - if (bio->type != WOLFSSL_BIO_FILE && bio->type != WOLFSSL_BIO_MEMORY) + if (bio->type != WOLFSSL_BIO_FILE && + bio->type != WOLFSSL_BIO_MEMORY) { ++tmpSz; /* include the terminating null when not writing to a * file. */ + } } if (wolfSSL_BIO_write(bio, tmp, tmpSz) != tmpSz) { @@ -13789,7 +13936,7 @@ int wolfSSL_X509_NAME_print_ex_fp(XFILE file, WOLFSSL_X509_NAME* name, WOLFSSL_ENTER("wolfSSL_X509_NAME_print_ex_fp"); - if (!(bio = wolfSSL_BIO_new_fp(file, BIO_NOCLOSE))) { + if (!(bio = wolfSSL_BIO_new_fp(file, WOLFSSL_BIO_NOCLOSE))) { WOLFSSL_MSG("wolfSSL_BIO_new_fp error"); return WOLFSSL_FAILURE; } @@ -13861,7 +14008,8 @@ WOLFSSL_X509_OBJECT *wolfSSL_X509_OBJECT_retrieve_by_subject( return NULL; for (i = 0; i < wolfSSL_sk_X509_OBJECT_num(sk); i++) { - WOLFSSL_X509_OBJECT* obj = (WOLFSSL_X509_OBJECT *)wolfSSL_sk_X509_OBJECT_value(sk, i); + WOLFSSL_X509_OBJECT* obj = (WOLFSSL_X509_OBJECT *) + wolfSSL_sk_X509_OBJECT_value(sk, i); if (obj != NULL && obj->type == type && wolfSSL_X509_NAME_cmp( wolfSSL_X509_get_subject_name(obj->data.x509), name) == 0) @@ -13915,10 +14063,7 @@ int wolfSSL_sk_X509_num(const WOLF_STACK_OF(WOLFSSL_X509) *s) #endif /* OPENSSL_EXTRA */ -#if defined(HAVE_EX_DATA) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) \ - || defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) \ - || defined(HAVE_LIGHTY)) - +#ifdef HAVE_EX_DATA_CRYPTO int wolfSSL_X509_get_ex_new_index(int idx, void *arg, WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, @@ -13926,14 +14071,13 @@ int wolfSSL_X509_get_ex_new_index(int idx, void *arg, { WOLFSSL_ENTER("wolfSSL_X509_get_ex_new_index"); - return wolfssl_get_ex_new_index(CRYPTO_EX_INDEX_X509, idx, arg, + return wolfssl_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_X509, idx, arg, new_func, dup_func, free_func); } #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(WOLFSSL_WPAS_SMALL) -void *wolfSSL_X509_get_ex_data(X509 *x509, int idx) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +void *wolfSSL_X509_get_ex_data(WOLFSSL_X509 *x509, int idx) { WOLFSSL_ENTER("wolfSSL_X509_get_ex_data"); #ifdef HAVE_EX_DATA @@ -13947,12 +14091,11 @@ void *wolfSSL_X509_get_ex_data(X509 *x509, int idx) return NULL; } -int wolfSSL_X509_set_ex_data(X509 *x509, int idx, void *data) +int wolfSSL_X509_set_ex_data(WOLFSSL_X509 *x509, int idx, void *data) { WOLFSSL_ENTER("wolfSSL_X509_set_ex_data"); #ifdef HAVE_EX_DATA - if (x509 != NULL) - { + if (x509 != NULL) { return wolfSSL_CRYPTO_set_ex_data(&x509->ex_data, idx, data); } #else @@ -13965,7 +14108,7 @@ int wolfSSL_X509_set_ex_data(X509 *x509, int idx, void *data) #ifdef HAVE_EX_DATA_CLEANUP_HOOKS int wolfSSL_X509_set_ex_data_with_cleanup( - X509 *x509, + WOLFSSL_X509 *x509, int idx, void *data, wolfSSL_ex_data_cleanup_routine_t cleanup_routine) @@ -13979,8 +14122,7 @@ int wolfSSL_X509_set_ex_data_with_cleanup( return WOLFSSL_FAILURE; } #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */ - -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */ +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifndef NO_ASN @@ -14147,7 +14289,7 @@ int wolfSSL_X509_check_email(WOLFSSL_X509 *x, const char *chk, size_t chkLen, return WOLFSSL_FAILURE; /* Call with NULL buffer to get required length. */ - emailLen = wolfSSL_X509_NAME_get_text_by_NID(subjName, NID_emailAddress, + emailLen = wolfSSL_X509_NAME_get_text_by_NID(subjName, WC_NID_emailAddress, NULL, 0); if (emailLen < 0) return WOLFSSL_FAILURE; @@ -14158,7 +14300,7 @@ int wolfSSL_X509_check_email(WOLFSSL_X509 *x, const char *chk, size_t chkLen, if (emailBuf == NULL) return WOLFSSL_FAILURE; - emailLen = wolfSSL_X509_NAME_get_text_by_NID(subjName, NID_emailAddress, + emailLen = wolfSSL_X509_NAME_get_text_by_NID(subjName, WC_NID_emailAddress, emailBuf, emailLen); if (emailLen < 0) { XFREE(emailBuf, x->heap, DYNAMIC_TYPE_OPENSSL); @@ -14205,81 +14347,6 @@ int wolfSSL_X509_NAME_digest(const WOLFSSL_X509_NAME *name, #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) -#if defined(OPENSSL_EXTRA) && \ - ((defined(SESSION_CERTS) && !defined(WOLFSSL_QT)) || \ - defined(WOLFSSL_SIGNER_DER_CERT)) - -/** - * Find the issuing cert of the input cert. On a self-signed cert this - * function will return an error. - * @param issuer The issuer x509 struct is returned here - * @param cm The cert manager that is queried for the issuer - * @param x This cert's issuer will be queried in cm - * @return WOLFSSL_SUCCESS on success - * WOLFSSL_FAILURE on error - */ -static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, - WOLFSSL_X509 *x) -{ - Signer* ca = NULL; -#ifdef WOLFSSL_SMALL_STACK - DecodedCert* cert = NULL; -#else - DecodedCert cert[1]; -#endif - - if (cm == NULL || x == NULL || x->derCert == NULL) { - WOLFSSL_MSG("No cert DER buffer or NULL cm. Defining " - "WOLFSSL_SIGNER_DER_CERT could solve the issue"); - return WOLFSSL_FAILURE; - } - -#ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT); - if (cert == NULL) - return WOLFSSL_FAILURE; -#endif - - /* Use existing CA retrieval APIs that use DecodedCert. */ - InitDecodedCert(cert, x->derCert->buffer, x->derCert->length, cm->heap); - if (ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL) == 0 - && !cert->selfSigned) { - #ifndef NO_SKID - if (cert->extAuthKeyIdSet) - ca = GetCA(cm, cert->extAuthKeyId); - if (ca == NULL) - ca = GetCAByName(cm, cert->issuerHash); - #else /* NO_SKID */ - ca = GetCA(cm, cert->issuerHash); - #endif /* NO SKID */ - } - FreeDecodedCert(cert); -#ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); -#endif - - if (ca == NULL) - return WOLFSSL_FAILURE; - -#ifdef WOLFSSL_SIGNER_DER_CERT - /* populate issuer with Signer DER */ - if (wolfSSL_X509_d2i_ex(issuer, ca->derCert->buffer, - ca->derCert->length, cm->heap) == NULL) - return WOLFSSL_FAILURE; -#else - /* Create an empty certificate as CA doesn't have a certificate. */ - *issuer = (WOLFSSL_X509 *)XMALLOC(sizeof(WOLFSSL_X509), 0, - DYNAMIC_TYPE_OPENSSL); - if (*issuer == NULL) - return WOLFSSL_FAILURE; - - InitX509((*issuer), 1, NULL); -#endif - - return WOLFSSL_SUCCESS; -} -#endif /* if defined(OPENSSL_EXTRA) && (defined(SESSION_CERTS) || \ - defined(WOLFSSL_SIGNER_DER_CERT)) */ void wolfSSL_X509_email_free(WOLF_STACK_OF(WOLFSSL_STRING) *sk) { @@ -14346,7 +14413,7 @@ int wolfSSL_X509_check_issued(WOLFSSL_X509 *issuer, WOLFSSL_X509 *subject) #endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */ #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ - defined(KEEP_PEER_CERT) + defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) WOLFSSL_X509* wolfSSL_X509_dup(WOLFSSL_X509 *x) { WOLFSSL_ENTER("wolfSSL_X509_dup"); @@ -14364,7 +14431,8 @@ WOLFSSL_X509* wolfSSL_X509_dup(WOLFSSL_X509 *x) return wolfSSL_X509_d2i_ex(NULL, x->derCert->buffer, x->derCert->length, x->heap); } -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ +#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || KEEP_PEER_CERT || \ + SESSION_CERTS */ #if defined(OPENSSL_EXTRA) int wolfSSL_X509_check_ca(WOLFSSL_X509 *x509) @@ -14389,7 +14457,7 @@ long wolfSSL_X509_get_version(const WOLFSSL_X509 *x509) WOLFSSL_ENTER("wolfSSL_X509_get_version"); - if (x509 == NULL){ + if (x509 == NULL) { WOLFSSL_MSG("invalid parameter"); return 0L; } @@ -14633,7 +14701,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) /* Regenerate since pkey->pkey.ptr may contain private key */ switch (pkey->type) { #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: { RsaKey* rsa; @@ -14659,7 +14727,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */ #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \ defined(WOLFSSL_CERT_GEN)) && !defined(NO_DSA) - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: { DsaKey* dsa; @@ -14677,12 +14745,12 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) XFREE(p, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); return WOLFSSL_FAILURE; } - cert->pubKeyOID = RSAk; + cert->pubKeyOID = DSAk; } break; #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) && !NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: { ecc_key* ecc; @@ -14709,6 +14777,7 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) default: return WOLFSSL_FAILURE; } + XFREE(cert->pubKey.buffer, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY); cert->pubKey.buffer = p; cert->pubKey.length = (unsigned int)derSz; @@ -14763,10 +14832,10 @@ void wolfSSL_X509V3_set_ctx(WOLFSSL_X509V3_CTX* ctx, WOLFSSL_X509* issuer, /* Set parameters in ctx as long as ret == WOLFSSL_SUCCESS */ if (ret == WOLFSSL_SUCCESS && issuer) - ret = wolfSSL_X509_set_issuer_name(ctx->x509,&issuer->issuer); + ret = wolfSSL_X509_set_issuer_name(ctx->x509, &issuer->issuer); if (ret == WOLFSSL_SUCCESS && subject) - ret = wolfSSL_X509_set_subject_name(ctx->x509,&subject->subject); + ret = wolfSSL_X509_set_subject_name(ctx->x509, &subject->subject); if (ret == WOLFSSL_SUCCESS && req) { WOLFSSL_MSG("req not implemented."); @@ -14840,6 +14909,25 @@ void wolfSSL_X509_REQ_free(WOLFSSL_X509* req) wolfSSL_X509_free(req); } +int wolfSSL_X509_REQ_set_version(WOLFSSL_X509 *x, long version) +{ + WOLFSSL_ENTER("wolfSSL_X509_REQ_set_version"); + if ((x == NULL) || (version < 0) || (version >= INT_MAX)) { + return WOLFSSL_FAILURE; + } + x->version = (int)version; + return WOLFSSL_SUCCESS; +} + +long wolfSSL_X509_REQ_get_version(const WOLFSSL_X509 *req) +{ + WOLFSSL_ENTER("wolfSSL_X509_REQ_get_version"); + if (req == NULL) { + return 0; /* invalid arg */ + } + return (long)req->version; +} + int wolfSSL_X509_REQ_sign(WOLFSSL_X509 *req, WOLFSSL_EVP_PKEY *pkey, const WOLFSSL_EVP_MD *md) { @@ -14902,20 +14990,22 @@ static int regenX509REQDerBuffer(WOLFSSL_X509* x509) { int derSz = X509_BUFFER_SZ; int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); -#ifdef WOLFSSL_SMALL_STACK +#ifndef WOLFSSL_SMALL_STACK + byte der[X509_BUFFER_SZ]; +#else byte* der; + der = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (!der) { WOLFSSL_MSG("malloc failed"); return WOLFSSL_FAILURE; } -#else - byte der[X509_BUFFER_SZ]; #endif if (wolfssl_x509_make_der(x509, 1, der, &derSz, 0) == WOLFSSL_SUCCESS) { FreeDer(&x509->derCert); - if (AllocDer(&x509->derCert, (word32)derSz, CERT_TYPE, x509->heap) == 0) { + if (AllocDer(&x509->derCert, (word32)derSz, CERT_TYPE, + x509->heap) == 0) { XMEMCPY(x509->derCert->buffer, der, derSz); ret = WOLFSSL_SUCCESS; } @@ -15041,13 +15131,13 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, WOLFSSL_ENTER("wolfSSL_X509_REQ_add1_attr_by_NID"); - if (!req || !bytes || type != MBSTRING_ASC) { + if (!req || !bytes || type != WOLFSSL_MBSTRING_ASC) { WOLFSSL_MSG("Bad parameter"); return WOLFSSL_FAILURE; } switch (nid) { - case NID_pkcs9_challengePassword: + case WC_NID_pkcs9_challengePassword: if (len < 0) len = (int)XSTRLEN((char*)bytes); if (len < CTC_NAME_SIZE) { @@ -15060,7 +15150,7 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, return WOLFSSL_FAILURE; } break; - case NID_serialNumber: + case WC_NID_serialNumber: if (len < 0) len = (int)XSTRLEN((char*)bytes); if (len + 1 > EXTERNAL_SERIAL_SIZE) { @@ -15072,12 +15162,12 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, req->serialSz = len; break; - case NID_pkcs9_unstructuredName: - case NID_pkcs9_contentType: - case NID_surname: - case NID_initials: - case NID_givenName: - case NID_dnQualifier: + case WC_NID_pkcs9_unstructuredName: + case WC_NID_pkcs9_contentType: + case WC_NID_surname: + case WC_NID_initials: + case WC_NID_givenName: + case WC_NID_dnQualifier: break; default: @@ -15087,7 +15177,7 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, attr = wolfSSL_X509_ATTRIBUTE_new(); ret = wolfSSL_X509_ATTRIBUTE_set(attr, (const char*)bytes, len, - V_ASN1_PRINTABLESTRING, nid); + WOLFSSL_V_ASN1_PRINTABLESTRING, nid); if (ret != WOLFSSL_SUCCESS) { wolfSSL_X509_ATTRIBUTE_free(attr); } @@ -15272,7 +15362,9 @@ void wolfSSL_X509_ATTRIBUTE_free(WOLFSSL_X509_ATTRIBUTE* attr) * */ WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new_ex(void* heap) { - WOLFSSL_X509_ACERT* x509; + WOLFSSL_X509_ACERT * x509 = NULL; + + WOLFSSL_ENTER("wolfSSL_X509_ACERT_new"); x509 = (WOLFSSL_X509_ACERT*) XMALLOC(sizeof(WOLFSSL_X509_ACERT), heap, DYNAMIC_TYPE_X509_ACERT); @@ -15302,6 +15394,8 @@ WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_new(void) * */ void wolfSSL_X509_ACERT_init(WOLFSSL_X509_ACERT * x509, int dynamic, void* heap) { + WOLFSSL_ENTER("wolfSSL_X509_ACERT_init"); + if (x509 == NULL) { WOLFSSL_MSG("error: InitX509Acert: null parameter"); return; @@ -15327,6 +15421,8 @@ void wolfSSL_X509_ACERT_free(WOLFSSL_X509_ACERT * x509) int dynamic = 0; void * heap = NULL; + WOLFSSL_ENTER("wolfSSL_X509_ACERT_free"); + if (x509 == NULL) { WOLFSSL_MSG("error: wolfSSL_X509_ACERT_free: null parameter"); return; @@ -15341,6 +15437,11 @@ void wolfSSL_X509_ACERT_free(WOLFSSL_X509_ACERT * x509) x509->holderIssuerName = NULL; } + if (x509->holderEntityName) { + FreeAltNames(x509->holderEntityName, heap); + x509->holderEntityName = NULL; + } + if (x509->AttCertIssuerName) { FreeAltNames(x509->AttCertIssuerName, heap); x509->AttCertIssuerName = NULL; @@ -15512,15 +15613,15 @@ int wolfSSL_X509_ACERT_verify(WOLFSSL_X509_ACERT* x509, WOLFSSL_EVP_PKEY* pkey) } switch (pkey->type) { - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: pkey_type = RSAk; break; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: pkey_type = ECDSAk; break; - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: pkey_type = DSAk; break; diff --git a/src/src/x509_str.c b/src/src/x509_str.c index c3d33b8..894da16 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -114,6 +114,80 @@ void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) #ifdef OPENSSL_EXTRA +#if ((defined(SESSION_CERTS) && !defined(WOLFSSL_QT)) || \ + defined(WOLFSSL_SIGNER_DER_CERT)) + +/** + * Find the issuing cert of the input cert. On a self-signed cert this + * function will return an error. + * @param issuer The issuer x509 struct is returned here + * @param cm The cert manager that is queried for the issuer + * @param x This cert's issuer will be queried in cm + * @return WOLFSSL_SUCCESS on success + * WOLFSSL_FAILURE on error + */ +static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, + WOLFSSL_X509 *x) +{ + Signer* ca = NULL; +#ifdef WOLFSSL_SMALL_STACK + DecodedCert* cert = NULL; +#else + DecodedCert cert[1]; +#endif + + if (cm == NULL || x == NULL || x->derCert == NULL) { + WOLFSSL_MSG("No cert DER buffer or NULL cm. Defining " + "WOLFSSL_SIGNER_DER_CERT could solve the issue"); + return WOLFSSL_FAILURE; + } + +#ifdef WOLFSSL_SMALL_STACK + cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, DYNAMIC_TYPE_DCERT); + if (cert == NULL) + return WOLFSSL_FAILURE; +#endif + + /* Use existing CA retrieval APIs that use DecodedCert. */ + InitDecodedCert(cert, x->derCert->buffer, x->derCert->length, cm->heap); + if (ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL) == 0 + && !cert->selfSigned) { + #ifndef NO_SKID + if (cert->extAuthKeyIdSet) + ca = GetCA(cm, cert->extAuthKeyId); + if (ca == NULL) + ca = GetCAByName(cm, cert->issuerHash); + #else /* NO_SKID */ + ca = GetCA(cm, cert->issuerHash); + #endif /* NO SKID */ + } + FreeDecodedCert(cert); +#ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); +#endif + + if (ca == NULL) + return WOLFSSL_FAILURE; + +#ifdef WOLFSSL_SIGNER_DER_CERT + /* populate issuer with Signer DER */ + if (wolfSSL_X509_d2i_ex(issuer, ca->derCert->buffer, + ca->derCert->length, cm->heap) == NULL) + return WOLFSSL_FAILURE; +#else + /* Create an empty certificate as CA doesn't have a certificate. */ + *issuer = (WOLFSSL_X509 *)XMALLOC(sizeof(WOLFSSL_X509), 0, + DYNAMIC_TYPE_OPENSSL); + if (*issuer == NULL) + return WOLFSSL_FAILURE; + + InitX509((*issuer), 1, NULL); +#endif + + return WOLFSSL_SUCCESS; +} +#endif /* SESSION_CERTS || WOLFSSL_SIGNER_DER_CERT */ + WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void) { WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_new"); @@ -147,7 +221,9 @@ int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, wolfSSL_sk_X509_free(ctx->chain); ctx->chain = NULL; } +#ifdef SESSION_CERTS ctx->sesChain = NULL; +#endif ctx->domain = NULL; #ifdef HAVE_EX_DATA XMEMSET(&ctx->ex_data, 0, sizeof(ctx->ex_data)); @@ -221,11 +297,11 @@ int GetX509Error(int e) /* We can't disambiguate if its the before or after date that caused * the error. Assume expired. */ case WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR): - return X509_V_ERR_CRL_HAS_EXPIRED; + return WOLFSSL_X509_V_ERR_CRL_HAS_EXPIRED; case WC_NO_ERR_TRACE(CRL_CERT_REVOKED): return WOLFSSL_X509_V_ERR_CERT_REVOKED; case WC_NO_ERR_TRACE(CRL_MISSING): - return X509_V_ERR_UNABLE_TO_GET_CRL; + return WOLFSSL_X509_V_ERR_UNABLE_TO_GET_CRL; case 0: case 1: return 0; @@ -239,17 +315,24 @@ int GetX509Error(int e) } } +static void SetupStoreCtxError_ex(WOLFSSL_X509_STORE_CTX* ctx, int ret, + int depth) +{ + int error = GetX509Error(ret); + + wolfSSL_X509_STORE_CTX_set_error(ctx, error); + wolfSSL_X509_STORE_CTX_set_error_depth(ctx, depth); +} + static void SetupStoreCtxError(WOLFSSL_X509_STORE_CTX* ctx, int ret) { int depth = 0; - int error = GetX509Error(ret); /* Set error depth */ if (ctx->chain) depth = (int)ctx->chain->num; - wolfSSL_X509_STORE_CTX_set_error(ctx, error); - wolfSSL_X509_STORE_CTX_set_error_depth(ctx, depth); + SetupStoreCtxError_ex(ctx, ret, depth); } static int X509StoreVerifyCert(WOLFSSL_X509_STORE_CTX* ctx) @@ -265,7 +348,8 @@ static int X509StoreVerifyCert(WOLFSSL_X509_STORE_CTX* ctx) SetupStoreCtxError(ctx, ret); #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) if (ctx->store->verify_cb) - ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, ctx) == 1 ? 0 : ret; + ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, ctx) == 1 ? + WOLFSSL_SUCCESS : ret; #endif #ifndef NO_ASN_TIME @@ -290,7 +374,7 @@ static int X509StoreVerifyCert(WOLFSSL_X509_STORE_CTX* ctx) #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) if (ctx->store->verify_cb) ret = ctx->store->verify_cb(ret >= 0 ? 1 : 0, - ctx) == 1 ? 0 : -1; + ctx) == 1 ? WOLFSSL_SUCCESS : -1; #endif } #endif @@ -393,21 +477,37 @@ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) /* We found our issuer in the non-trusted cert list, add it * to the CM and verify the current cert against it */ + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + /* OpenSSL doesn't allow the cert as CA if it is not CA:TRUE for + * intermediate certs. + */ + if (!issuer->isCa) { + /* error depth is current depth + 1 */ + SetupStoreCtxError_ex(ctx, X509_V_ERR_INVALID_CA, + (ctx->chain) ? (int)(ctx->chain->num + 1) : 1); + if (ctx->store->verify_cb) { + ret = ctx->store->verify_cb(0, ctx); + if (ret != WOLFSSL_SUCCESS) { + goto exit; + } + } + } else { + #endif ret = X509StoreAddCa(ctx->store, issuer, WOLFSSL_TEMP_CA); if (ret != WOLFSSL_SUCCESS) { goto exit; } - added = 1; - ret = X509StoreVerifyCert(ctx); if (ret != WOLFSSL_SUCCESS) { goto exit; } - /* Add it to the current chain and look at the issuer cert next */ wolfSSL_sk_X509_push(ctx->chain, ctx->current_cert); + #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) + } + #endif ctx->current_cert = issuer; } else if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { @@ -1002,11 +1102,9 @@ WOLFSSL_X509_STORE* wolfSSL_X509_STORE_new(void) if ((store->owned = wolfSSL_sk_X509_new_null()) == NULL) goto err_exit; -#if !defined(WOLFSSL_SIGNER_DER_CERT) if ((store->trusted = wolfSSL_sk_X509_new_null()) == NULL) goto err_exit; #endif -#endif #ifdef HAVE_CRL store->crl = store->cm->crl; @@ -1056,8 +1154,11 @@ static void X509StoreFreeObjList(WOLFSSL_X509_STORE* store, WOLFSSL_X509_OBJECT *obj = NULL; int cnt = store->numAdded; + /* -1 here because it is later used as an index value into the object stack. + * With there being the chance that the only object in the stack is one from + * the numAdded to the store >= is used when comparing to 0. */ i = wolfSSL_sk_X509_OBJECT_num(objs) - 1; - while (cnt > 0 && i > 0) { + while (cnt > 0 && i >= 0) { /* The inner X509 is owned by somebody else, NULL out the reference */ obj = (WOLFSSL_X509_OBJECT *)wolfSSL_sk_X509_OBJECT_value(objs, i); if (obj != NULL) { @@ -1096,20 +1197,18 @@ void wolfSSL_X509_STORE_free(WOLFSSL_X509_STORE* store) } #if defined(OPENSSL_EXTRA) if (store->certs != NULL) { - wolfSSL_sk_X509_free(store->certs); + wolfSSL_sk_X509_pop_free(store->certs, NULL); store->certs = NULL; } if (store->owned != NULL) { - wolfSSL_sk_X509_pop_free(store->owned, wolfSSL_X509_free); + wolfSSL_sk_X509_pop_free(store->owned, NULL); store->owned = NULL; } -#if !defined(WOLFSSL_SIGNER_DER_CERT) if (store->trusted != NULL) { - wolfSSL_sk_X509_free(store->trusted); + wolfSSL_sk_X509_pop_free(store->trusted, NULL); store->trusted = NULL; } #endif -#endif #ifdef OPENSSL_ALL if (store->objs != NULL) { X509StoreFreeObjList(store, store->objs); @@ -1306,26 +1405,32 @@ int wolfSSL_X509_STORE_add_cert(WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509) * CA=TRUE */ if (wolfSSL_X509_NAME_cmp(&x509->issuer, &x509->subject) == 0) { result = X509StoreAddCa(store, x509, WOLFSSL_USER_CA); - #if !defined(WOLFSSL_SIGNER_DER_CERT) if (result == WOLFSSL_SUCCESS && store->trusted != NULL) { - result = wolfSSL_sk_X509_push(store->trusted, x509); - if (result > 0) { - result = WOLFSSL_SUCCESS; - } - else { - result = WOLFSSL_FATAL_ERROR; + result = wolfSSL_X509_up_ref(x509); + if (result == WOLFSSL_SUCCESS) { + result = wolfSSL_sk_X509_push(store->trusted, x509); + if (result > 0) { + result = WOLFSSL_SUCCESS; + } + else { + result = WOLFSSL_FATAL_ERROR; + wolfSSL_X509_free(x509); + } } } - #endif } else { if (store->certs != NULL) { - result = wolfSSL_sk_X509_push(store->certs, x509); - if (result > 0) { - result = WOLFSSL_SUCCESS; - } - else { - result = WOLFSSL_FATAL_ERROR; + result = wolfSSL_X509_up_ref(x509); + if (result == WOLFSSL_SUCCESS) { + result = wolfSSL_sk_X509_push(store->certs, x509); + if (result > 0) { + result = WOLFSSL_SUCCESS; + } + else { + result = WOLFSSL_FATAL_ERROR; + wolfSSL_X509_free(x509); + } } } else { @@ -1379,7 +1484,8 @@ int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE* store) int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, byte *buf, word32 bufLen, int type) { - int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + int ret = WOLFSSL_SUCCESS; + WOLFSSL_X509 *x509 = NULL; if (str == NULL || buf == NULL) { @@ -1389,14 +1495,18 @@ int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, /* OpenSSL X509_STORE_load_file fails on DER file, we will as well */ x509 = wolfSSL_X509_load_certificate_buffer(buf, bufLen, type); if (str->owned != NULL) { - wolfSSL_sk_X509_push(str->owned, x509); + if (wolfSSL_sk_X509_push(str->owned, x509) <= 0) { + ret = WOLFSSL_FAILURE; + } + } + if (ret == WOLFSSL_SUCCESS) { + ret = wolfSSL_X509_STORE_add_cert(str, x509); } - ret = wolfSSL_X509_STORE_add_cert(str, x509); if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to load file"); ret = WOLFSSL_FAILURE; } - if (str->owned == NULL) { + if (ret != WOLFSSL_SUCCESS || str->owned == NULL) { wolfSSL_X509_free(x509); } @@ -1745,10 +1855,18 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( #if defined(WOLFSSL_SIGNER_DER_CERT) && !defined(NO_FILESYSTEM) cert_stack = wolfSSL_CertManagerGetCerts(store->cm); store->numAdded = 0; + if (cert_stack == NULL && wolfSSL_sk_X509_num(store->certs) > 0) { + cert_stack = wolfSSL_sk_X509_new_null(); + if (cert_stack == NULL) { + WOLFSSL_MSG("wolfSSL_sk_X509_OBJECT_new error"); + goto err_cleanup; + } + } for (i = 0; i < wolfSSL_sk_X509_num(store->certs); i++) { - wolfSSL_sk_X509_push(cert_stack, - wolfSSL_sk_X509_value(store->certs, i)); - store->numAdded++; + if (wolfSSL_sk_X509_push(cert_stack, + wolfSSL_sk_X509_value(store->certs, i)) > 0) { + store->numAdded++; + } } /* Do not modify stack until after we guarantee success to * simplify cleanup logic handling cert merging above */ diff --git a/src/wolfcrypt/src/aes.c b/src/wolfcrypt/src/aes.c index 1cb9843..cf50064 100644 --- a/src/wolfcrypt/src/aes.c +++ b/src/wolfcrypt/src/aes.c @@ -106,7 +106,8 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #include #endif -#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) +#if (!defined(WOLFSSL_ARMASM) || defined(__aarch64__)) && \ + !defined(WOLFSSL_RISCV_ASM) #ifdef WOLFSSL_IMX6_CAAM_BLOB /* case of possibly not using hardware acceleration for AES but using key @@ -123,7 +124,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #pragma warning(disable: 4127) #endif -#if FIPS_VERSION3_GE(6,0,0) +#if !defined(WOLFSSL_ARMASM) && FIPS_VERSION3_GE(6,0,0) const unsigned int wolfCrypt_FIPS_aes_ro_sanity[2] = { 0x1a2b3c4d, 0x00000002 }; int wolfCrypt_FIPS_AES_sanity(void) @@ -174,13 +175,13 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits HAL_CRYP_Init(&hcryp); #if defined(STM32_HAL_V2) - ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)inBlock, WC_AES_BLOCK_SIZE, (uint32_t*)outBlock, STM32_HAL_TIMEOUT); #elif defined(STM32_CRYPTO_AES_ONLY) - ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, WC_AES_BLOCK_SIZE, outBlock, STM32_HAL_TIMEOUT); #else - ret = HAL_CRYP_AESECB_Encrypt(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYP_AESECB_Encrypt(&hcryp, (uint8_t*)inBlock, WC_AES_BLOCK_SIZE, outBlock, STM32_HAL_TIMEOUT); #endif if (ret != HAL_OK) { @@ -275,13 +276,13 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits HAL_CRYP_Init(&hcryp); #if defined(STM32_HAL_V2) - ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)inBlock, WC_AES_BLOCK_SIZE, (uint32_t*)outBlock, STM32_HAL_TIMEOUT); #elif defined(STM32_CRYPTO_AES_ONLY) - ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, WC_AES_BLOCK_SIZE, outBlock, STM32_HAL_TIMEOUT); #else - ret = HAL_CRYP_AESECB_Decrypt(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE, + ret = HAL_CRYP_AESECB_Decrypt(&hcryp, (uint8_t*)inBlock, WC_AES_BLOCK_SIZE, outBlock, STM32_HAL_TIMEOUT); #endif if (ret != HAL_OK) { @@ -379,7 +380,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #endif if (wolfSSL_CryptHwMutexLock() == 0) { - LTC_AES_EncryptEcb(LTC_BASE, inBlock, outBlock, AES_BLOCK_SIZE, + LTC_AES_EncryptEcb(LTC_BASE, inBlock, outBlock, WC_AES_BLOCK_SIZE, key, keySize); wolfSSL_CryptHwMutexUnLock(); } @@ -402,7 +403,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #endif if (wolfSSL_CryptHwMutexLock() == 0) { - LTC_AES_DecryptEcb(LTC_BASE, inBlock, outBlock, AES_BLOCK_SIZE, + LTC_AES_DecryptEcb(LTC_BASE, inBlock, outBlock, WC_AES_BLOCK_SIZE, key, keySize, kLTC_EncryptKey); wolfSSL_CryptHwMutexUnLock(); } @@ -493,7 +494,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #endif /* Thread mutex protection handled in Pic32Crypto */ return wc_Pic32AesCrypt(aes->key, aes->keylen, NULL, 0, - outBlock, inBlock, AES_BLOCK_SIZE, + outBlock, inBlock, WC_AES_BLOCK_SIZE, PIC32_ENCRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_RECB); } #endif @@ -511,7 +512,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #endif /* Thread mutex protection handled in Pic32Crypto */ return wc_Pic32AesCrypt(aes->key, aes->keylen, NULL, 0, - outBlock, inBlock, AES_BLOCK_SIZE, + outBlock, inBlock, WC_AES_BLOCK_SIZE, PIC32_DECRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_RECB); } #endif @@ -787,6 +788,26 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits } #endif /* HAVE_AES_DECRYPT */ +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + + #define NEED_AES_TABLES + + static int checkedCpuIdFlags = 0; + static word32 cpuid_flags = 0; + + static void Check_CPU_support_HwCrypto(Aes* aes) + { + if (checkedCpuIdFlags == 0) { + cpuid_flags = cpuid_get_flags(); + checkedCpuIdFlags = 1; + } + aes->use_aes_hw_crypto = IS_AARCH64_AES(cpuid_flags); + #ifdef HAVE_AESGCM + aes->use_pmull_hw_crypto = IS_AARCH64_PMULL(cpuid_flags); + #endif + } + #elif (defined(WOLFSSL_IMX6_CAAM) && !defined(NO_IMX6_CAAM_AES) \ && !defined(WOLFSSL_QNX_CAAM)) || \ ((defined(WOLFSSL_AFALG) || defined(WOLFSSL_DEVCRYPTO_AES)) && \ @@ -951,7 +972,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits return ret; } #endif - return AES_ECB_encrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE); + return AES_ECB_encrypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE); } #endif @@ -966,7 +987,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits return ret; } #endif - return AES_ECB_decrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE); + return AES_ECB_decrypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE); } #endif @@ -2229,10 +2250,10 @@ static void AesEncryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz) { word32 i; - for (i = 0; i < sz; i += AES_BLOCK_SIZE) { + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { AesEncrypt_C(aes, in, out, aes->rounds >> 1); - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } } #endif @@ -2692,18 +2713,18 @@ static void bs_set_key(bs_word* rk, const byte* key, word32 keyLen, word32 rounds) { int i; - byte bs_key[15 * AES_BLOCK_SIZE]; - int ksSz = (rounds + 1) * AES_BLOCK_SIZE; + byte bs_key[15 * WC_AES_BLOCK_SIZE]; + int ksSz = (rounds + 1) * WC_AES_BLOCK_SIZE; bs_word block[AES_BLOCK_BITS]; /* Fist round. */ XMEMCPY(bs_key, key, keyLen); bs_expand_key(bs_key, ksSz); - for (i = 0; i < ksSz; i += AES_BLOCK_SIZE) { + for (i = 0; i < ksSz; i += WC_AES_BLOCK_SIZE) { int k; - XMEMCPY(block, bs_key + i, AES_BLOCK_SIZE); + XMEMCPY(block, bs_key + i, WC_AES_BLOCK_SIZE); for (k = BS_BLOCK_WORDS; k < AES_BLOCK_BITS; k += BS_BLOCK_WORDS) { int l; for (l = 0; l < BS_BLOCK_WORDS; l++) { @@ -2751,12 +2772,12 @@ static void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, (void)r; - XMEMCPY(state, inBlock, AES_BLOCK_SIZE); - XMEMSET(((byte*)state) + AES_BLOCK_SIZE, 0, sizeof(state) - AES_BLOCK_SIZE); + XMEMCPY(state, inBlock, WC_AES_BLOCK_SIZE); + XMEMSET(((byte*)state) + WC_AES_BLOCK_SIZE, 0, sizeof(state) - WC_AES_BLOCK_SIZE); bs_encrypt(state, aes->bs_key, aes->rounds); - XMEMCPY(outBlock, state, AES_BLOCK_SIZE); + XMEMCPY(outBlock, state, WC_AES_BLOCK_SIZE); } #if defined(HAVE_AES_ECB) && !(defined(WOLFSSL_IMX6_CAAM) && \ @@ -2838,13 +2859,13 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( printf("out = %p\n", outBlock); printf("aes->key = %p\n", aes->key); printf("aes->rounds = %d\n", aes->rounds); - printf("sz = %d\n", AES_BLOCK_SIZE); + printf("sz = %d\n", WC_AES_BLOCK_SIZE); #endif /* check alignment, decrypt doesn't need alignment */ if ((wc_ptr_t)inBlock % AESNI_ALIGN) { #ifndef NO_WOLFSSL_ALLOC_ALIGN - byte* tmp = (byte*)XMALLOC(AES_BLOCK_SIZE + AESNI_ALIGN, aes->heap, + byte* tmp = (byte*)XMALLOC(WC_AES_BLOCK_SIZE + AESNI_ALIGN, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); byte* tmp_align; if (tmp == NULL) @@ -2852,10 +2873,10 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( tmp_align = tmp + (AESNI_ALIGN - ((wc_ptr_t)tmp % AESNI_ALIGN)); - XMEMCPY(tmp_align, inBlock, AES_BLOCK_SIZE); - AES_ECB_encrypt_AESNI(tmp_align, tmp_align, AES_BLOCK_SIZE, + XMEMCPY(tmp_align, inBlock, WC_AES_BLOCK_SIZE); + AES_ECB_encrypt_AESNI(tmp_align, tmp_align, WC_AES_BLOCK_SIZE, (byte*)aes->key, (int)aes->rounds); - XMEMCPY(outBlock, tmp_align, AES_BLOCK_SIZE); + XMEMCPY(outBlock, tmp_align, WC_AES_BLOCK_SIZE); XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); return 0; #else @@ -2865,7 +2886,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( #endif } - AES_ECB_encrypt_AESNI(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key, + AES_ECB_encrypt_AESNI(inBlock, outBlock, WC_AES_BLOCK_SIZE, (byte*)aes->key, (int)aes->rounds); return 0; @@ -2875,22 +2896,29 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( printf("Skipping AES-NI\n"); #endif } +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_encrypt_AARCH64(inBlock, outBlock, (byte*)aes->key, + (int)aes->rounds); + return 0; + } #endif /* WOLFSSL_AESNI */ #if defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES) - AES_ECB_encrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE); + AES_ECB_encrypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE); return 0; #endif #if defined(WOLFSSL_IMXRT_DCP) if (aes->keylen == 16) { - DCPAesEcbEncrypt(aes, outBlock, inBlock, AES_BLOCK_SIZE); + DCPAesEcbEncrypt(aes, outBlock, inBlock, WC_AES_BLOCK_SIZE); return 0; } #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) if (aes->useSWCrypt == 0) { - return se050_aes_crypt(aes, inBlock, outBlock, AES_BLOCK_SIZE, + return se050_aes_crypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE, AES_ENCRYPTION, kAlgorithm_SSS_AES_ECB); } #endif @@ -2913,7 +2941,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( #if defined(MAX3266X_AES) if (wc_AesGetKeySize(aes, &keySize) == 0) { return wc_MXC_TPU_AesEncrypt(inBlock, (byte*)aes->reg, (byte*)aes->key, - MXC_TPU_MODE_ECB, AES_BLOCK_SIZE, + MXC_TPU_MODE_ECB, WC_AES_BLOCK_SIZE, outBlock, (unsigned int)keySize); } #endif @@ -2923,7 +2951,7 @@ static WARN_UNUSED_RESULT int wc_AesEncrypt( #endif { ret_cb = wc_CryptoCb_AesEcbEncrypt(aes, outBlock, inBlock, - AES_BLOCK_SIZE); + WC_AES_BLOCK_SIZE); if (ret_cb != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret_cb; /* fall-through when unavailable */ @@ -3223,10 +3251,10 @@ static void AesDecryptBlocks_C(Aes* aes, const byte* in, byte* out, word32 sz) { word32 i; - for (i = 0; i < sz; i += AES_BLOCK_SIZE) { + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { AesDecrypt_C(aes, in, out, aes->rounds >> 1); - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } } #endif @@ -3532,12 +3560,12 @@ static void AesDecrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, (void)r; - XMEMCPY(state, inBlock, AES_BLOCK_SIZE); - XMEMSET(((byte*)state) + AES_BLOCK_SIZE, 0, sizeof(state) - AES_BLOCK_SIZE); + XMEMCPY(state, inBlock, WC_AES_BLOCK_SIZE); + XMEMSET(((byte*)state) + WC_AES_BLOCK_SIZE, 0, sizeof(state) - WC_AES_BLOCK_SIZE); bs_decrypt(state, aes->bs_key, aes->rounds); - XMEMCPY(outBlock, state, AES_BLOCK_SIZE); + XMEMCPY(outBlock, state, WC_AES_BLOCK_SIZE); } #endif @@ -3615,13 +3643,13 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( printf("out = %p\n", outBlock); printf("aes->key = %p\n", aes->key); printf("aes->rounds = %d\n", aes->rounds); - printf("sz = %d\n", AES_BLOCK_SIZE); + printf("sz = %d\n", WC_AES_BLOCK_SIZE); #endif /* if input and output same will overwrite input iv */ if ((const byte*)aes->tmp != inBlock) - XMEMCPY(aes->tmp, inBlock, AES_BLOCK_SIZE); - AES_ECB_decrypt_AESNI(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key, + XMEMCPY(aes->tmp, inBlock, WC_AES_BLOCK_SIZE); + AES_ECB_decrypt_AESNI(inBlock, outBlock, WC_AES_BLOCK_SIZE, (byte*)aes->key, (int)aes->rounds); return 0; } @@ -3630,19 +3658,26 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( printf("Skipping AES-NI\n"); #endif } +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_decrypt_AARCH64(inBlock, outBlock, (byte*)aes->key, + (int)aes->rounds); + return 0; + } #endif /* WOLFSSL_AESNI */ #if defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES) - return AES_ECB_decrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE); + return AES_ECB_decrypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE); #endif #if defined(WOLFSSL_IMXRT_DCP) if (aes->keylen == 16) { - DCPAesEcbDecrypt(aes, outBlock, inBlock, AES_BLOCK_SIZE); + DCPAesEcbDecrypt(aes, outBlock, inBlock, WC_AES_BLOCK_SIZE); return 0; } #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) if (aes->useSWCrypt == 0) { - return se050_aes_crypt(aes, inBlock, outBlock, AES_BLOCK_SIZE, + return se050_aes_crypt(aes, inBlock, outBlock, WC_AES_BLOCK_SIZE, AES_DECRYPTION, kAlgorithm_SSS_AES_ECB); } #endif @@ -3663,7 +3698,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( #if defined(MAX3266X_AES) if (wc_AesGetKeySize(aes, &keySize) == 0) { return wc_MXC_TPU_AesDecrypt(inBlock, (byte*)aes->reg, (byte*)aes->key, - MXC_TPU_MODE_ECB, AES_BLOCK_SIZE, + MXC_TPU_MODE_ECB, WC_AES_BLOCK_SIZE, outBlock, (unsigned int)keySize); } #endif @@ -3674,7 +3709,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( #endif { ret_cb = wc_CryptoCb_AesEcbDecrypt(aes, outBlock, inBlock, - AES_BLOCK_SIZE); + WC_AES_BLOCK_SIZE); if (ret_cb != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret_cb; /* fall-through when unavailable */ @@ -3746,7 +3781,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( extern TX_BYTE_POOL mp_ncached; /* Non Cached memory pool */ #endif - #define AES_BUFFER_SIZE (AES_BLOCK_SIZE * 64) + #define AES_BUFFER_SIZE (WC_AES_BLOCK_SIZE * 64) static unsigned char *AESBuffIn = NULL; static unsigned char *AESBuffOut = NULL; static byte *secReg; @@ -3773,9 +3808,9 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( s2 = tx_byte_allocate(&mp_ncached, (void *)&AESBuffOut, AES_BUFFER_SIZE, TX_NO_WAIT); s3 = tx_byte_allocate(&mp_ncached, (void *)&secKey, - AES_BLOCK_SIZE*2, TX_NO_WAIT); + WC_AES_BLOCK_SIZE*2, TX_NO_WAIT); s4 = tx_byte_allocate(&mp_ncached, (void *)&secReg, - AES_BLOCK_SIZE, TX_NO_WAIT); + WC_AES_BLOCK_SIZE, TX_NO_WAIT); if (s1 || s2 || s3 || s4 || s5) return BAD_FUNC_ARG; @@ -3805,7 +3840,7 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( XMEMCPY(aes->key, userKey, keylen); if (iv) - XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) @@ -4103,9 +4138,9 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( ret = wc_AesSetIV(aes, iv); if (iv) - XMEMCPY(iv_aes, iv, AES_BLOCK_SIZE); + XMEMCPY(iv_aes, iv, WC_AES_BLOCK_SIZE); else - XMEMSET(iv_aes, 0, AES_BLOCK_SIZE); + XMEMSET(iv_aes, 0, WC_AES_BLOCK_SIZE); ret = SaSi_AesSetIv(&aes->ctx.user_ctx, iv_aes); @@ -4474,9 +4509,9 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) wc_FreeRng(&rng); if (iv) - XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); else - XMEMSET(aes->reg, 0, AES_BLOCK_SIZE); + XMEMSET(aes->reg, 0, WC_AES_BLOCK_SIZE); switch (keylen) { case AES_128_KEY_SIZE: keyType = CAAM_KEYTYPE_AES128; break; @@ -4580,6 +4615,14 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) } #endif /* WOLFSSL_AESNI */ + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + Check_CPU_support_HwCrypto(aes); + if (aes->use_aes_hw_crypto) { + return AES_set_key_AARCH64(userKey, keylen, aes, dir); + } + #endif + #ifdef WOLFSSL_KCAPI_AES XMEMCPY(aes->devKey, userKey, keylen); if (aes->init != 0) { @@ -4662,8 +4705,6 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) } #endif - ret = wc_AesSetIV(aes, iv); - #if defined(WOLFSSL_DEVCRYPTO) && \ (defined(WOLFSSL_DEVCRYPTO_AES) || defined(WOLFSSL_DEVCRYPTO_CBC)) aes->ctx.cfd = -1; @@ -4743,9 +4784,9 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif if (iv) - XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); else - XMEMSET(aes->reg, 0, AES_BLOCK_SIZE); + XMEMSET(aes->reg, 0, WC_AES_BLOCK_SIZE); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) @@ -4875,10 +4916,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) { int ret = 0; CRYP_HandleTypeDef hcryp; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -4896,7 +4937,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_CBC; - ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE); + ByteReverseWords(aes->reg, aes->reg, WC_AES_BLOCK_SIZE); #elif defined(STM32_CRYPTO_AES_ONLY) hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT; hcryp.Init.ChainingMode = CRYP_CHAINMODE_AES_CBC; @@ -4906,14 +4947,14 @@ int wc_AesSetIV(Aes* aes, const byte* iv) HAL_CRYP_Init(&hcryp); #if defined(STM32_HAL_V2) - ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, blocks * AES_BLOCK_SIZE, + ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, blocks * WC_AES_BLOCK_SIZE, (uint32_t*)out, STM32_HAL_TIMEOUT); #elif defined(STM32_CRYPTO_AES_ONLY) - ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE, + ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #else ret = HAL_CRYP_AESCBC_Encrypt(&hcryp, (uint8_t*)in, - blocks * AES_BLOCK_SIZE, + blocks * WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #endif if (ret != HAL_OK) { @@ -4921,7 +4962,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* store iv for next call */ - XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); HAL_CRYP_DeInit(&hcryp); @@ -4935,10 +4976,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) { int ret = 0; CRYP_HandleTypeDef hcryp; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -4955,11 +4996,11 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* if input and output same will overwrite input iv */ - XMEMCPY(aes->tmp, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->tmp, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_CBC; - ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE); + ByteReverseWords(aes->reg, aes->reg, WC_AES_BLOCK_SIZE); #elif defined(STM32_CRYPTO_AES_ONLY) hcryp.Init.OperatingMode = CRYP_ALGOMODE_KEYDERIVATION_DECRYPT; hcryp.Init.ChainingMode = CRYP_CHAINMODE_AES_CBC; @@ -4970,14 +5011,14 @@ int wc_AesSetIV(Aes* aes, const byte* iv) HAL_CRYP_Init(&hcryp); #if defined(STM32_HAL_V2) - ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, blocks * AES_BLOCK_SIZE, + ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, blocks * WC_AES_BLOCK_SIZE, (uint32_t*)out, STM32_HAL_TIMEOUT); #elif defined(STM32_CRYPTO_AES_ONLY) - ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE, + ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #else ret = HAL_CRYP_AESCBC_Decrypt(&hcryp, (uint8_t*)in, - blocks * AES_BLOCK_SIZE, + blocks * WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #endif if (ret != HAL_OK) { @@ -4985,7 +5026,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* store iv for next call */ - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); HAL_CRYP_DeInit(&hcryp); wolfSSL_CryptHwMutexUnLock(); @@ -5003,10 +5044,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) CRYP_InitTypeDef cryptInit; CRYP_KeyInitTypeDef keyInit; CRYP_IVInitTypeDef ivInit; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5031,7 +5072,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) /* set iv */ iv = aes->reg; CRYP_IVStructInit(&ivInit); - ByteReverseWords(iv, iv, AES_BLOCK_SIZE); + ByteReverseWords(iv, iv, WC_AES_BLOCK_SIZE); ivInit.CRYP_IV0Left = iv[0]; ivInit.CRYP_IV0Right = iv[1]; ivInit.CRYP_IV1Left = iv[2]; @@ -5064,11 +5105,11 @@ int wc_AesSetIV(Aes* aes, const byte* iv) *(uint32_t*)&out[12] = CRYP_DataOut(); /* store iv for next call */ - XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); - sz -= AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } /* disable crypto processor */ @@ -5087,10 +5128,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) CRYP_InitTypeDef cryptInit; CRYP_KeyInitTypeDef keyInit; CRYP_IVInitTypeDef ivInit; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5107,7 +5148,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* if input and output same will overwrite input iv */ - XMEMCPY(aes->tmp, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->tmp, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); /* reset registers to their default values */ CRYP_DeInit(); @@ -5132,7 +5173,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) /* set iv */ iv = aes->reg; CRYP_IVStructInit(&ivInit); - ByteReverseWords(iv, iv, AES_BLOCK_SIZE); + ByteReverseWords(iv, iv, WC_AES_BLOCK_SIZE); ivInit.CRYP_IV0Left = iv[0]; ivInit.CRYP_IV0Right = iv[1]; ivInit.CRYP_IV1Left = iv[2]; @@ -5160,10 +5201,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) *(uint32_t*)&out[12] = CRYP_DataOut(); /* store iv for next call */ - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } /* disable crypto processor */ @@ -5191,7 +5232,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) return BAD_FUNC_ARG; /*wrong pointer*/ #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5202,7 +5243,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) secDesc->length1 = 0x0; secDesc->pointer1 = NULL; - secDesc->length2 = AES_BLOCK_SIZE; + secDesc->length2 = WC_AES_BLOCK_SIZE; secDesc->pointer2 = (byte *)secReg; /* Initial Vector */ switch(aes->rounds) { @@ -5226,7 +5267,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) #endif while (sz) { secDesc->header = descHeader; - XMEMCPY(secReg, aes->reg, AES_BLOCK_SIZE); + XMEMCPY(secReg, aes->reg, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS sz -= AES_BUFFER_SIZE; #else @@ -5244,8 +5285,8 @@ int wc_AesSetIV(Aes* aes, const byte* iv) XMEMCPY(AESBuffIn, pi, size); if(descHeader == SEC_DESC_AES_CBC_DECRYPT) { - XMEMCPY((void*)aes->tmp, (void*)&(pi[size-AES_BLOCK_SIZE]), - AES_BLOCK_SIZE); + XMEMCPY((void*)aes->tmp, (void*)&(pi[size-WC_AES_BLOCK_SIZE]), + WC_AES_BLOCK_SIZE); } /* Point SEC to the location of the descriptor */ @@ -5270,10 +5311,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) XMEMCPY(po, AESBuffOut, size); if (descHeader == SEC_DESC_AES_CBC_ENCRYPT) { - XMEMCPY((void*)aes->reg, (void*)&(po[size-AES_BLOCK_SIZE]), - AES_BLOCK_SIZE); + XMEMCPY((void*)aes->reg, (void*)&(po[size-WC_AES_BLOCK_SIZE]), + WC_AES_BLOCK_SIZE); } else { - XMEMCPY((void*)aes->reg, (void*)aes->tmp, AES_BLOCK_SIZE); + XMEMCPY((void*)aes->reg, (void*)aes->tmp, WC_AES_BLOCK_SIZE); } pi += size; @@ -5302,10 +5343,10 @@ int wc_AesSetIV(Aes* aes, const byte* iv) word32 keySize; status_t status; byte *iv, *enc_key; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5323,13 +5364,13 @@ int wc_AesSetIV(Aes* aes, const byte* iv) status = wolfSSL_CryptHwMutexLock(); if (status != 0) return status; - status = LTC_AES_EncryptCbc(LTC_BASE, in, out, blocks * AES_BLOCK_SIZE, + status = LTC_AES_EncryptCbc(LTC_BASE, in, out, blocks * WC_AES_BLOCK_SIZE, iv, enc_key, keySize); wolfSSL_CryptHwMutexUnLock(); /* store iv for next call */ if (status == kStatus_Success) { - XMEMCPY(iv, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(iv, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } return (status == kStatus_Success) ? 0 : -1; @@ -5341,11 +5382,11 @@ int wc_AesSetIV(Aes* aes, const byte* iv) word32 keySize; status_t status; byte* iv, *dec_key; - byte temp_block[AES_BLOCK_SIZE]; - word32 blocks = (sz / AES_BLOCK_SIZE); + byte temp_block[WC_AES_BLOCK_SIZE]; + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5361,18 +5402,18 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* get IV for next call */ - XMEMCPY(temp_block, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); status = wolfSSL_CryptHwMutexLock(); if (status != 0) return status; - status = LTC_AES_DecryptCbc(LTC_BASE, in, out, blocks * AES_BLOCK_SIZE, + status = LTC_AES_DecryptCbc(LTC_BASE, in, out, blocks * WC_AES_BLOCK_SIZE, iv, dec_key, keySize, kLTC_EncryptKey); wolfSSL_CryptHwMutexUnLock(); /* store IV for next call */ if (status == kStatus_Success) { - XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + XMEMCPY(iv, temp_block, WC_AES_BLOCK_SIZE); } return (status == kStatus_Success) ? 0 : -1; @@ -5384,12 +5425,12 @@ int wc_AesSetIV(Aes* aes, const byte* iv) { int offset = 0; byte *iv; - byte temp_block[AES_BLOCK_SIZE]; - word32 blocks = (sz / AES_BLOCK_SIZE); + byte temp_block[WC_AES_BLOCK_SIZE]; + word32 blocks = (sz / WC_AES_BLOCK_SIZE); int ret; #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5399,19 +5440,19 @@ int wc_AesSetIV(Aes* aes, const byte* iv) iv = (byte*)aes->reg; while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + offset, WC_AES_BLOCK_SIZE); /* XOR block with IV for CBC */ - xorbuf(temp_block, iv, AES_BLOCK_SIZE); + xorbuf(temp_block, iv, WC_AES_BLOCK_SIZE); ret = wc_AesEncrypt(aes, temp_block, out + offset); if (ret != 0) return ret; - offset += AES_BLOCK_SIZE; + offset += WC_AES_BLOCK_SIZE; /* store IV for next block */ - XMEMCPY(iv, out + offset - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(iv, out + offset - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } return 0; @@ -5422,11 +5463,11 @@ int wc_AesSetIV(Aes* aes, const byte* iv) int ret; int offset = 0; byte* iv; - byte temp_block[AES_BLOCK_SIZE]; - word32 blocks = (sz / AES_BLOCK_SIZE); + byte temp_block[WC_AES_BLOCK_SIZE]; + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { return BAD_LENGTH_E; } #endif @@ -5436,19 +5477,19 @@ int wc_AesSetIV(Aes* aes, const byte* iv) iv = (byte*)aes->reg; while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + offset, WC_AES_BLOCK_SIZE); ret = wc_AesDecrypt(aes, in + offset, out + offset); if (ret != 0) return ret; /* XOR block with IV for CBC */ - xorbuf(out + offset, iv, AES_BLOCK_SIZE); + xorbuf(out + offset, iv, WC_AES_BLOCK_SIZE); /* store IV for next block */ - XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + XMEMCPY(iv, temp_block, WC_AES_BLOCK_SIZE); - offset += AES_BLOCK_SIZE; + offset += WC_AES_BLOCK_SIZE; } return 0; @@ -5467,7 +5508,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* Always enforce a length check */ - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS return BAD_LENGTH_E; #else @@ -5489,7 +5530,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) (unsigned int)keySize); /* store iv for next call */ if (status == 0) { - XMEMCPY(iv, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(iv, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } return (status == 0) ? 0 : -1; } @@ -5500,14 +5541,14 @@ int wc_AesSetIV(Aes* aes, const byte* iv) word32 keySize; int status; byte *iv; - byte temp_block[AES_BLOCK_SIZE]; + byte temp_block[WC_AES_BLOCK_SIZE]; if ((in == NULL) || (out == NULL) || (aes == NULL)) { return BAD_FUNC_ARG; } /* Always enforce a length check */ - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS return BAD_LENGTH_E; #else @@ -5525,14 +5566,14 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } /* get IV for next call */ - XMEMCPY(temp_block, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); status = wc_MXC_TPU_AesDecrypt(in, iv, (byte*)aes->key, MXC_TPU_MODE_CBC, sz, out, keySize); /* store iv for next call */ if (status == 0) { - XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + XMEMCPY(iv, temp_block, WC_AES_BLOCK_SIZE); } return (status == 0) ? 0 : -1; } @@ -5550,7 +5591,7 @@ int wc_AesSetIV(Aes* aes, const byte* iv) return 0; /* hardware fails on input that is not a multiple of AES block size */ - if (sz % AES_BLOCK_SIZE != 0) { + if (sz % WC_AES_BLOCK_SIZE != 0) { #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS return BAD_LENGTH_E; #else @@ -5559,13 +5600,13 @@ int wc_AesSetIV(Aes* aes, const byte* iv) } ret = wc_Pic32AesCrypt( - aes->key, aes->keylen, aes->reg, AES_BLOCK_SIZE, + aes->key, aes->keylen, aes->reg, WC_AES_BLOCK_SIZE, out, in, sz, PIC32_ENCRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_RCBC); /* store iv for next call */ if (ret == 0) { - XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } return ret; @@ -5574,29 +5615,29 @@ int wc_AesSetIV(Aes* aes, const byte* iv) int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { int ret; - byte scratch[AES_BLOCK_SIZE]; + byte scratch[WC_AES_BLOCK_SIZE]; if (sz == 0) return 0; /* hardware fails on input that is not a multiple of AES block size */ - if (sz % AES_BLOCK_SIZE != 0) { + if (sz % WC_AES_BLOCK_SIZE != 0) { #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS return BAD_LENGTH_E; #else return BAD_FUNC_ARG; #endif } - XMEMCPY(scratch, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(scratch, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); ret = wc_Pic32AesCrypt( - aes->key, aes->keylen, aes->reg, AES_BLOCK_SIZE, + aes->key, aes->keylen, aes->reg, WC_AES_BLOCK_SIZE, out, in, sz, PIC32_DECRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_RCBC); /* store iv for next call */ if (ret == 0) { - XMEMCPY((byte*)aes->reg, scratch, AES_BLOCK_SIZE); + XMEMCPY((byte*)aes->reg, scratch, WC_AES_BLOCK_SIZE); } return ret; @@ -5661,9 +5702,9 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) return 0; } - blocks = sz / AES_BLOCK_SIZE; + blocks = sz / WC_AES_BLOCK_SIZE; #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS - if (sz % AES_BLOCK_SIZE) { + if (sz % WC_AES_BLOCK_SIZE) { WOLFSSL_ERROR_VERBOSE(BAD_LENGTH_E); return BAD_LENGTH_E; } @@ -5695,7 +5736,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #elif defined(HAVE_INTEL_QA) return IntelQaSymAesCbcEncrypt(&aes->asyncDev, out, in, sz, (const byte*)aes->devKey, aes->keylen, - (byte*)aes->reg, AES_BLOCK_SIZE); + (byte*)aes->reg, WC_AES_BLOCK_SIZE); #elif defined(WOLFSSL_ASYNC_CRYPT_SW) if (wc_AsyncSwInit(&aes->asyncDev, ASYNC_SW_AES_CBC_ENCRYPT)) { WC_ASYNC_SW* sw = &aes->asyncDev.sw; @@ -5745,7 +5786,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) /* check alignment, decrypt doesn't need alignment */ if ((wc_ptr_t)in % AESNI_ALIGN) { #ifndef NO_WOLFSSL_ALLOC_ALIGN - byte* tmp = (byte*)XMALLOC(sz + AES_BLOCK_SIZE + AESNI_ALIGN, + byte* tmp = (byte*)XMALLOC(sz + WC_AES_BLOCK_SIZE + AESNI_ALIGN, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); byte* tmp_align; if (tmp == NULL) @@ -5756,7 +5797,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) AES_CBC_encrypt_AESNI(tmp_align, tmp_align, (byte*)aes->reg, sz, (byte*)aes->key, (int)aes->rounds); /* store iv for next call */ - XMEMCPY(aes->reg, tmp_align + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, tmp_align + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); XMEMCPY(out, tmp_align, sz); XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -5771,24 +5812,32 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) AES_CBC_encrypt_AESNI(in, out, (byte*)aes->reg, sz, (byte*)aes->key, (int)aes->rounds); /* store iv for next call */ - XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); ret = 0; } } else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_CBC_encrypt_AARCH64(in, out, sz, (byte*)aes->reg, + (byte*)aes->key, (int)aes->rounds); + ret = 0; + } + else #endif { ret = 0; while (blocks--) { - xorbuf((byte*)aes->reg, in, AES_BLOCK_SIZE); + xorbuf((byte*)aes->reg, in, WC_AES_BLOCK_SIZE); ret = wc_AesEncrypt(aes, (byte*)aes->reg, (byte*)aes->reg); if (ret != 0) break; - XMEMCPY(out, aes->reg, AES_BLOCK_SIZE); + XMEMCPY(out, aes->reg, WC_AES_BLOCK_SIZE); - out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; } } @@ -5829,8 +5878,8 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) } #endif - blocks = sz / AES_BLOCK_SIZE; - if (sz % AES_BLOCK_SIZE) { + blocks = sz / WC_AES_BLOCK_SIZE; + if (sz % WC_AES_BLOCK_SIZE) { #ifdef WOLFSSL_AES_CBC_LENGTH_CHECKS return BAD_LENGTH_E; #else @@ -5864,7 +5913,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #elif defined(HAVE_INTEL_QA) return IntelQaSymAesCbcDecrypt(&aes->asyncDev, out, in, sz, (const byte*)aes->devKey, aes->keylen, - (byte*)aes->reg, AES_BLOCK_SIZE); + (byte*)aes->reg, WC_AES_BLOCK_SIZE); #elif defined(WOLFSSL_ASYNC_CRYPT_SW) if (wc_AsyncSwInit(&aes->asyncDev, ASYNC_SW_AES_CBC_DECRYPT)) { WC_ASYNC_SW* sw = &aes->asyncDev.sw; @@ -5901,7 +5950,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #endif /* if input and output same will overwrite input iv */ - XMEMCPY(aes->tmp, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(aes->tmp, in + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); #if defined(WOLFSSL_AESNI_BY4) || defined(WOLFSSL_X86_BUILD) AES_CBC_decrypt_AESNI_by4(in, out, (byte*)aes->reg, sz, (byte*)aes->key, aes->rounds); @@ -5913,7 +5962,15 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) (int)aes->rounds); #endif /* WOLFSSL_AESNI_BYx */ /* store iv for next call */ - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); + ret = 0; + } + else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_CBC_decrypt_AARCH64(in, out, sz, (byte*)aes->reg, + (byte*)aes->key, (int)aes->rounds); ret = 0; } else @@ -5922,76 +5979,76 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) ret = 0; #ifdef WC_AES_BITSLICED if (in != out) { - unsigned char dec[AES_BLOCK_SIZE * BS_WORD_SIZE]; + unsigned char dec[WC_AES_BLOCK_SIZE * BS_WORD_SIZE]; while (blocks > BS_WORD_SIZE) { - AesDecryptBlocks_C(aes, in, dec, AES_BLOCK_SIZE * BS_WORD_SIZE); - xorbufout(out, dec, aes->reg, AES_BLOCK_SIZE); - xorbufout(out + AES_BLOCK_SIZE, dec + AES_BLOCK_SIZE, in, - AES_BLOCK_SIZE * (BS_WORD_SIZE - 1)); - XMEMCPY(aes->reg, in + (AES_BLOCK_SIZE * (BS_WORD_SIZE - 1)), - AES_BLOCK_SIZE); - in += AES_BLOCK_SIZE * BS_WORD_SIZE; - out += AES_BLOCK_SIZE * BS_WORD_SIZE; + AesDecryptBlocks_C(aes, in, dec, WC_AES_BLOCK_SIZE * BS_WORD_SIZE); + xorbufout(out, dec, aes->reg, WC_AES_BLOCK_SIZE); + xorbufout(out + WC_AES_BLOCK_SIZE, dec + WC_AES_BLOCK_SIZE, in, + WC_AES_BLOCK_SIZE * (BS_WORD_SIZE - 1)); + XMEMCPY(aes->reg, in + (WC_AES_BLOCK_SIZE * (BS_WORD_SIZE - 1)), + WC_AES_BLOCK_SIZE); + in += WC_AES_BLOCK_SIZE * BS_WORD_SIZE; + out += WC_AES_BLOCK_SIZE * BS_WORD_SIZE; blocks -= BS_WORD_SIZE; } if (blocks > 0) { - AesDecryptBlocks_C(aes, in, dec, blocks * AES_BLOCK_SIZE); - xorbufout(out, dec, aes->reg, AES_BLOCK_SIZE); - xorbufout(out + AES_BLOCK_SIZE, dec + AES_BLOCK_SIZE, in, - AES_BLOCK_SIZE * (blocks - 1)); - XMEMCPY(aes->reg, in + (AES_BLOCK_SIZE * (blocks - 1)), - AES_BLOCK_SIZE); + AesDecryptBlocks_C(aes, in, dec, blocks * WC_AES_BLOCK_SIZE); + xorbufout(out, dec, aes->reg, WC_AES_BLOCK_SIZE); + xorbufout(out + WC_AES_BLOCK_SIZE, dec + WC_AES_BLOCK_SIZE, in, + WC_AES_BLOCK_SIZE * (blocks - 1)); + XMEMCPY(aes->reg, in + (WC_AES_BLOCK_SIZE * (blocks - 1)), + WC_AES_BLOCK_SIZE); blocks = 0; } } else { - unsigned char dec[AES_BLOCK_SIZE * BS_WORD_SIZE]; + unsigned char dec[WC_AES_BLOCK_SIZE * BS_WORD_SIZE]; int i; while (blocks > BS_WORD_SIZE) { - AesDecryptBlocks_C(aes, in, dec, AES_BLOCK_SIZE * BS_WORD_SIZE); - XMEMCPY(aes->tmp, in + (BS_WORD_SIZE - 1) * AES_BLOCK_SIZE, - AES_BLOCK_SIZE); + AesDecryptBlocks_C(aes, in, dec, WC_AES_BLOCK_SIZE * BS_WORD_SIZE); + XMEMCPY(aes->tmp, in + (BS_WORD_SIZE - 1) * WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); for (i = BS_WORD_SIZE-1; i >= 1; i--) { - xorbufout(out + i * AES_BLOCK_SIZE, - dec + i * AES_BLOCK_SIZE, in + (i - 1) * AES_BLOCK_SIZE, - AES_BLOCK_SIZE); + xorbufout(out + i * WC_AES_BLOCK_SIZE, + dec + i * WC_AES_BLOCK_SIZE, in + (i - 1) * WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); } - xorbufout(out, dec, aes->reg, AES_BLOCK_SIZE); - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + xorbufout(out, dec, aes->reg, WC_AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); - in += AES_BLOCK_SIZE * BS_WORD_SIZE; - out += AES_BLOCK_SIZE * BS_WORD_SIZE; + in += WC_AES_BLOCK_SIZE * BS_WORD_SIZE; + out += WC_AES_BLOCK_SIZE * BS_WORD_SIZE; blocks -= BS_WORD_SIZE; } if (blocks > 0) { - AesDecryptBlocks_C(aes, in, dec, blocks * AES_BLOCK_SIZE); - XMEMCPY(aes->tmp, in + (blocks - 1) * AES_BLOCK_SIZE, - AES_BLOCK_SIZE); + AesDecryptBlocks_C(aes, in, dec, blocks * WC_AES_BLOCK_SIZE); + XMEMCPY(aes->tmp, in + (blocks - 1) * WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); for (i = blocks-1; i >= 1; i--) { - xorbufout(out + i * AES_BLOCK_SIZE, - dec + i * AES_BLOCK_SIZE, in + (i - 1) * AES_BLOCK_SIZE, - AES_BLOCK_SIZE); + xorbufout(out + i * WC_AES_BLOCK_SIZE, + dec + i * WC_AES_BLOCK_SIZE, in + (i - 1) * WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); } - xorbufout(out, dec, aes->reg, AES_BLOCK_SIZE); - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + xorbufout(out, dec, aes->reg, WC_AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); blocks = 0; } } #else while (blocks--) { - XMEMCPY(aes->tmp, in, AES_BLOCK_SIZE); + XMEMCPY(aes->tmp, in, WC_AES_BLOCK_SIZE); ret = wc_AesDecrypt(aes, in, out); if (ret != 0) return ret; - xorbuf(out, (byte*)aes->reg, AES_BLOCK_SIZE); + xorbuf(out, (byte*)aes->reg, WC_AES_BLOCK_SIZE); /* store iv for next call */ - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); - out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; } #endif } @@ -6018,7 +6075,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #ifdef WOLFSSL_STM32_CUBEMX CRYP_HandleTypeDef hcryp; #ifdef STM32_HAL_V2 - word32 iv[AES_BLOCK_SIZE/sizeof(word32)]; + word32 iv[WC_AES_BLOCK_SIZE/sizeof(word32)]; #endif #else word32 *iv; @@ -6040,7 +6097,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_CTR; - ByteReverseWords(iv, aes->reg, AES_BLOCK_SIZE); + ByteReverseWords(iv, aes->reg, WC_AES_BLOCK_SIZE); hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)iv; #elif defined(STM32_CRYPTO_AES_ONLY) hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT; @@ -6053,13 +6110,13 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) HAL_CRYP_Init(&hcryp); #if defined(STM32_HAL_V2) - ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, AES_BLOCK_SIZE, + ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, WC_AES_BLOCK_SIZE, (uint32_t*)out, STM32_HAL_TIMEOUT); #elif defined(STM32_CRYPTO_AES_ONLY) - ret = HAL_CRYPEx_AES(&hcryp, (byte*)in, AES_BLOCK_SIZE, + ret = HAL_CRYPEx_AES(&hcryp, (byte*)in, WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #else - ret = HAL_CRYP_AESCTR_Encrypt(&hcryp, (byte*)in, AES_BLOCK_SIZE, + ret = HAL_CRYP_AESCTR_Encrypt(&hcryp, (byte*)in, WC_AES_BLOCK_SIZE, out, STM32_HAL_TIMEOUT); #endif if (ret != HAL_OK) { @@ -6134,11 +6191,11 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) int wc_AesCtrEncryptBlock(Aes* aes, byte* out, const byte* in) { - word32 tmpIv[AES_BLOCK_SIZE / sizeof(word32)]; - XMEMCPY(tmpIv, aes->reg, AES_BLOCK_SIZE); + word32 tmpIv[WC_AES_BLOCK_SIZE / sizeof(word32)]; + XMEMCPY(tmpIv, aes->reg, WC_AES_BLOCK_SIZE); return wc_Pic32AesCrypt( - aes->key, aes->keylen, tmpIv, AES_BLOCK_SIZE, - out, in, AES_BLOCK_SIZE, + aes->key, aes->keylen, tmpIv, WC_AES_BLOCK_SIZE, + out, in, WC_AES_BLOCK_SIZE, PIC32_ENCRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_RCTR); } @@ -6158,7 +6215,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) } /* consume any unused bytes left in aes->tmp */ - tmp = (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left; + tmp = (byte*)aes->tmp + WC_AES_BLOCK_SIZE - aes->left; while (aes->left && sz) { *(out++) = *(in++) ^ *(tmp++); aes->left--; @@ -6215,7 +6272,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { /* in network byte order so start at end and work back */ int i; - for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) { + for (i = WC_AES_BLOCK_SIZE - 1; i >= 0; i--) { if (++inOutCtr[i]) /* we're done unless we overflow */ return; } @@ -6224,7 +6281,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) /* Software AES - CTR Encrypt */ int wc_AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - byte scratch[AES_BLOCK_SIZE]; + byte scratch[WC_AES_BLOCK_SIZE]; int ret = 0; word32 processed; @@ -6248,61 +6305,69 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) /* consume any unused bytes left in aes->tmp */ processed = min(aes->left, sz); - xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, + xorbufout(out, in, (byte*)aes->tmp + WC_AES_BLOCK_SIZE - aes->left, processed); out += processed; in += processed; aes->left -= processed; sz -= processed; + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_CTR_encrypt_AARCH64(aes, out, in, sz); + return 0; + } + #endif + VECTOR_REGISTERS_PUSH; #if defined(HAVE_AES_ECB) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \ !defined(XTRANSFORM_AESCTRBLOCK) - if (in != out && sz >= AES_BLOCK_SIZE) { - word32 blocks = sz / AES_BLOCK_SIZE; + if (in != out && sz >= WC_AES_BLOCK_SIZE) { + word32 blocks = sz / WC_AES_BLOCK_SIZE; byte* counter = (byte*)aes->reg; byte* c = out; while (blocks--) { - XMEMCPY(c, counter, AES_BLOCK_SIZE); - c += AES_BLOCK_SIZE; + XMEMCPY(c, counter, WC_AES_BLOCK_SIZE); + c += WC_AES_BLOCK_SIZE; IncrementAesCounter(counter); } /* reset number of blocks and then do encryption */ - blocks = sz / AES_BLOCK_SIZE; - wc_AesEcbEncrypt(aes, out, out, AES_BLOCK_SIZE * blocks); - xorbuf(out, in, AES_BLOCK_SIZE * blocks); - in += AES_BLOCK_SIZE * blocks; - out += AES_BLOCK_SIZE * blocks; - sz -= blocks * AES_BLOCK_SIZE; + blocks = sz / WC_AES_BLOCK_SIZE; + wc_AesEcbEncrypt(aes, out, out, WC_AES_BLOCK_SIZE * blocks); + xorbuf(out, in, WC_AES_BLOCK_SIZE * blocks); + in += WC_AES_BLOCK_SIZE * blocks; + out += WC_AES_BLOCK_SIZE * blocks; + sz -= blocks * WC_AES_BLOCK_SIZE; } else #endif { #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("wc_AesCtrEncrypt scratch", scratch, - AES_BLOCK_SIZE); + WC_AES_BLOCK_SIZE); #endif /* do as many block size ops as possible */ - while (sz >= AES_BLOCK_SIZE) { + while (sz >= WC_AES_BLOCK_SIZE) { #ifdef XTRANSFORM_AESCTRBLOCK XTRANSFORM_AESCTRBLOCK(aes, out, in); #else ret = wc_AesEncrypt(aes, (byte*)aes->reg, scratch); if (ret != 0) break; - xorbuf(scratch, in, AES_BLOCK_SIZE); - XMEMCPY(out, scratch, AES_BLOCK_SIZE); + xorbuf(scratch, in, WC_AES_BLOCK_SIZE); + XMEMCPY(out, scratch, WC_AES_BLOCK_SIZE); #endif IncrementAesCounter((byte*)aes->reg); - out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; aes->left = 0; } - ForceZero(scratch, AES_BLOCK_SIZE); + ForceZero(scratch, WC_AES_BLOCK_SIZE); } /* handle non block size remaining and store unused byte count in left */ @@ -6310,16 +6375,16 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) ret = wc_AesEncrypt(aes, (byte*)aes->reg, (byte*)aes->tmp); if (ret == 0) { IncrementAesCounter((byte*)aes->reg); - aes->left = AES_BLOCK_SIZE - sz; + aes->left = WC_AES_BLOCK_SIZE - sz; xorbufout(out, in, aes->tmp, sz); } } if (ret < 0) - ForceZero(scratch, AES_BLOCK_SIZE); + ForceZero(scratch, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(scratch, AES_BLOCK_SIZE); + wc_MemZero_Check(scratch, WC_AES_BLOCK_SIZE); #endif VECTOR_REGISTERS_POP; @@ -6343,7 +6408,7 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) #endif /* NEED_AES_CTR_SOFT */ #endif /* WOLFSSL_AES_COUNTER */ -#endif /* !WOLFSSL_ARMASM && ! WOLFSSL_RISCV_ASM */ +#endif /* !WOLFSSL_RISCV_ASM */ /* @@ -6374,15 +6439,15 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) #ifdef WOLFSSL_AESGCM_STREAM /* Access initialization counter data. */ - #define AES_INITCTR(aes) ((aes)->streamData + 0 * AES_BLOCK_SIZE) + #define AES_INITCTR(aes) ((aes)->streamData + 0 * WC_AES_BLOCK_SIZE) /* Access counter data. */ - #define AES_COUNTER(aes) ((aes)->streamData + 1 * AES_BLOCK_SIZE) + #define AES_COUNTER(aes) ((aes)->streamData + 1 * WC_AES_BLOCK_SIZE) /* Access tag data. */ - #define AES_TAG(aes) ((aes)->streamData + 2 * AES_BLOCK_SIZE) + #define AES_TAG(aes) ((aes)->streamData + 2 * WC_AES_BLOCK_SIZE) /* Access last GHASH block. */ - #define AES_LASTGBLOCK(aes) ((aes)->streamData + 3 * AES_BLOCK_SIZE) + #define AES_LASTGBLOCK(aes) ((aes)->streamData + 3 * WC_AES_BLOCK_SIZE) /* Access last encrypted block. */ - #define AES_LASTBLOCK(aes) ((aes)->streamData + 4 * AES_BLOCK_SIZE) + #define AES_LASTBLOCK(aes) ((aes)->streamData + 4 * WC_AES_BLOCK_SIZE) #endif #if defined(HAVE_COLDFIRE_SEC) @@ -6390,8 +6455,8 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) #endif -#ifdef WOLFSSL_ARMASM - /* implementation is located in wolfcrypt/src/port/arm/armv8-aes.c */ +#if defined(WOLFSSL_ARMASM) && !defined(__aarch64__) + /* implemented in wolfcrypt/src/port/arm/rmv8-aes.c */ #elif defined(WOLFSSL_RISCV_ASM) /* implemented in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ @@ -6413,7 +6478,7 @@ static WC_INLINE void IncrementGcmCounter(byte* inOutCtr) int i; /* in network byte order so start at end and work back */ - for (i = AES_BLOCK_SIZE - 1; i >= AES_BLOCK_SIZE - CTR_SZ; i--) { + for (i = WC_AES_BLOCK_SIZE - 1; i >= WC_AES_BLOCK_SIZE - CTR_SZ; i--) { if (++inOutCtr[i]) /* we're done unless we overflow */ return; } @@ -6444,9 +6509,9 @@ static WC_INLINE void RIGHTSHIFTX(byte* x) { int i; int carryIn = 0; - byte borrow = (0x00 - (x[15] & 0x01)) & 0xE1; + byte borrow = (byte)((0x00U - (x[15] & 0x01U)) & 0xE1U); - for (i = 0; i < AES_BLOCK_SIZE; i++) { + for (i = 0; i < WC_AES_BLOCK_SIZE; i++) { int carryOut = (x[i] & 0x01) << 7; x[i] = (byte) ((x[i] >> 1) | carryIn); carryIn = carryOut; @@ -6462,23 +6527,23 @@ static WC_INLINE void RIGHTSHIFTX(byte* x) void GenerateM0(Gcm* gcm) { int i, j; - byte (*m)[AES_BLOCK_SIZE] = gcm->M0; + byte (*m)[WC_AES_BLOCK_SIZE] = gcm->M0; - XMEMCPY(m[128], gcm->H, AES_BLOCK_SIZE); + XMEMCPY(m[128], gcm->H, WC_AES_BLOCK_SIZE); for (i = 64; i > 0; i /= 2) { - XMEMCPY(m[i], m[i*2], AES_BLOCK_SIZE); + XMEMCPY(m[i], m[i*2], WC_AES_BLOCK_SIZE); RIGHTSHIFTX(m[i]); } for (i = 2; i < 256; i *= 2) { for (j = 1; j < i; j++) { - XMEMCPY(m[i+j], m[i], AES_BLOCK_SIZE); - xorbuf(m[i+j], m[j], AES_BLOCK_SIZE); + XMEMCPY(m[i+j], m[i], WC_AES_BLOCK_SIZE); + xorbuf(m[i+j], m[j], WC_AES_BLOCK_SIZE); } } - XMEMSET(m[0], 0, AES_BLOCK_SIZE); + XMEMSET(m[0], 0, WC_AES_BLOCK_SIZE); } #elif defined(GCM_TABLE_4BIT) @@ -6498,49 +6563,49 @@ void GenerateM0(Gcm* gcm) #if !defined(BIG_ENDIAN_ORDER) && !defined(WC_16BIT_CPU) int i; #endif - byte (*m)[AES_BLOCK_SIZE] = gcm->M0; + byte (*m)[WC_AES_BLOCK_SIZE] = gcm->M0; /* 0 times -> 0x0 */ - XMEMSET(m[0x0], 0, AES_BLOCK_SIZE); + XMEMSET(m[0x0], 0, WC_AES_BLOCK_SIZE); /* 1 times -> 0x8 */ - XMEMCPY(m[0x8], gcm->H, AES_BLOCK_SIZE); + XMEMCPY(m[0x8], gcm->H, WC_AES_BLOCK_SIZE); /* 2 times -> 0x4 */ - XMEMCPY(m[0x4], m[0x8], AES_BLOCK_SIZE); + XMEMCPY(m[0x4], m[0x8], WC_AES_BLOCK_SIZE); RIGHTSHIFTX(m[0x4]); /* 4 times -> 0x2 */ - XMEMCPY(m[0x2], m[0x4], AES_BLOCK_SIZE); + XMEMCPY(m[0x2], m[0x4], WC_AES_BLOCK_SIZE); RIGHTSHIFTX(m[0x2]); /* 8 times -> 0x1 */ - XMEMCPY(m[0x1], m[0x2], AES_BLOCK_SIZE); + XMEMCPY(m[0x1], m[0x2], WC_AES_BLOCK_SIZE); RIGHTSHIFTX(m[0x1]); /* 0x3 */ - XMEMCPY(m[0x3], m[0x2], AES_BLOCK_SIZE); - xorbuf (m[0x3], m[0x1], AES_BLOCK_SIZE); + XMEMCPY(m[0x3], m[0x2], WC_AES_BLOCK_SIZE); + xorbuf (m[0x3], m[0x1], WC_AES_BLOCK_SIZE); /* 0x5 -> 0x7 */ - XMEMCPY(m[0x5], m[0x4], AES_BLOCK_SIZE); - xorbuf (m[0x5], m[0x1], AES_BLOCK_SIZE); - XMEMCPY(m[0x6], m[0x4], AES_BLOCK_SIZE); - xorbuf (m[0x6], m[0x2], AES_BLOCK_SIZE); - XMEMCPY(m[0x7], m[0x4], AES_BLOCK_SIZE); - xorbuf (m[0x7], m[0x3], AES_BLOCK_SIZE); + XMEMCPY(m[0x5], m[0x4], WC_AES_BLOCK_SIZE); + xorbuf (m[0x5], m[0x1], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0x6], m[0x4], WC_AES_BLOCK_SIZE); + xorbuf (m[0x6], m[0x2], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0x7], m[0x4], WC_AES_BLOCK_SIZE); + xorbuf (m[0x7], m[0x3], WC_AES_BLOCK_SIZE); /* 0x9 -> 0xf */ - XMEMCPY(m[0x9], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0x9], m[0x1], AES_BLOCK_SIZE); - XMEMCPY(m[0xa], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xa], m[0x2], AES_BLOCK_SIZE); - XMEMCPY(m[0xb], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xb], m[0x3], AES_BLOCK_SIZE); - XMEMCPY(m[0xc], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xc], m[0x4], AES_BLOCK_SIZE); - XMEMCPY(m[0xd], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xd], m[0x5], AES_BLOCK_SIZE); - XMEMCPY(m[0xe], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xe], m[0x6], AES_BLOCK_SIZE); - XMEMCPY(m[0xf], m[0x8], AES_BLOCK_SIZE); - xorbuf (m[0xf], m[0x7], AES_BLOCK_SIZE); + XMEMCPY(m[0x9], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0x9], m[0x1], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xa], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xa], m[0x2], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xb], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xb], m[0x3], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xc], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xc], m[0x4], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xd], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xd], m[0x5], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xe], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xe], m[0x6], WC_AES_BLOCK_SIZE); + XMEMCPY(m[0xf], m[0x8], WC_AES_BLOCK_SIZE); + xorbuf (m[0xf], m[0x7], WC_AES_BLOCK_SIZE); #if !defined(BIG_ENDIAN_ORDER) && !defined(WC_16BIT_CPU) for (i = 0; i < 16; i++) { @@ -6555,7 +6620,7 @@ void GenerateM0(Gcm* gcm) int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) { int ret; - byte iv[AES_BLOCK_SIZE]; + byte iv[WC_AES_BLOCK_SIZE]; #ifdef WOLFSSL_IMX6_CAAM_BLOB byte local[32]; @@ -6587,7 +6652,7 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) XMEMSET(aes->gcm.aadH, 0, sizeof(aes->gcm.aadH)); aes->gcm.aadLen = 0; #endif - XMEMSET(iv, 0, AES_BLOCK_SIZE); + XMEMSET(iv, 0, WC_AES_BLOCK_SIZE); ret = wc_AesSetKey(aes, key, len, iv, AES_ENCRYPTION); #ifdef WOLFSSL_AESGCM_STREAM aes->gcmKeySet = 1; @@ -6603,6 +6668,13 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) return ret; #endif /* WOLFSSL_RENESAS_RSIP && WOLFSSL_RENESAS_FSPSM_CRYPTONLY*/ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (ret == 0 && aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { + AES_GCM_set_key_AARCH64(aes, iv); + } + else +#endif #if !defined(FREESCALE_LTC_AES_GCM) if (ret == 0) { VECTOR_REGISTERS_PUSH; @@ -6698,34 +6770,34 @@ void AES_GCM_decrypt_avx2(const unsigned char *in, unsigned char *out, #if defined(GCM_SMALL) static void GMULT(byte* X, byte* Y) { - byte Z[AES_BLOCK_SIZE]; - byte V[AES_BLOCK_SIZE]; + byte Z[WC_AES_BLOCK_SIZE]; + byte V[WC_AES_BLOCK_SIZE]; int i, j; - XMEMSET(Z, 0, AES_BLOCK_SIZE); - XMEMCPY(V, X, AES_BLOCK_SIZE); - for (i = 0; i < AES_BLOCK_SIZE; i++) + XMEMSET(Z, 0, WC_AES_BLOCK_SIZE); + XMEMCPY(V, X, WC_AES_BLOCK_SIZE); + for (i = 0; i < WC_AES_BLOCK_SIZE; i++) { byte y = Y[i]; for (j = 0; j < 8; j++) { if (y & 0x80) { - xorbuf(Z, V, AES_BLOCK_SIZE); + xorbuf(Z, V, WC_AES_BLOCK_SIZE); } RIGHTSHIFTX(V); y = y << 1; } } - XMEMCPY(X, Z, AES_BLOCK_SIZE); + XMEMCPY(X, Z, WC_AES_BLOCK_SIZE); } void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word32 cSz, byte* s, word32 sSz) { - byte x[AES_BLOCK_SIZE]; - byte scratch[AES_BLOCK_SIZE]; + byte x[WC_AES_BLOCK_SIZE]; + byte scratch[WC_AES_BLOCK_SIZE]; word32 blocks, partial; byte* h; @@ -6734,38 +6806,38 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, } h = gcm->H; - XMEMSET(x, 0, AES_BLOCK_SIZE); + XMEMSET(x, 0, WC_AES_BLOCK_SIZE); /* Hash in A, the Additional Authentication Data */ if (aSz != 0 && a != NULL) { - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, a, AES_BLOCK_SIZE); + xorbuf(x, a, WC_AES_BLOCK_SIZE); GMULT(x, h); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, a, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, h); } } /* Hash in C, the Ciphertext */ if (cSz != 0 && c != NULL) { - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, c, AES_BLOCK_SIZE); + xorbuf(x, c, WC_AES_BLOCK_SIZE); GMULT(x, h); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, c, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, h); } } @@ -6773,7 +6845,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, /* Hash in the lengths of A and C in bits */ FlattenSzInBits(&scratch[0], aSz); FlattenSzInBits(&scratch[8], cSz); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, h); /* Copy the result into s. */ @@ -6796,7 +6868,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_ONE_BLOCK(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, AES_BLOCK_SIZE); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT(AES_TAG(aes), aes->gcm.H); \ } \ while (0) @@ -6871,17 +6943,17 @@ ALIGN16 static const byte R[256][2] = { {0xbc, 0xf8}, {0xbd, 0x3a}, {0xbf, 0x7c}, {0xbe, 0xbe} }; -static void GMULT(byte *x, byte m[256][AES_BLOCK_SIZE]) +static void GMULT(byte *x, byte m[256][WC_AES_BLOCK_SIZE]) { #if !defined(WORD64_AVAILABLE) || defined(BIG_ENDIAN_ORDER) int i, j; - byte Z[AES_BLOCK_SIZE]; + byte Z[WC_AES_BLOCK_SIZE]; byte a; XMEMSET(Z, 0, sizeof(Z)); for (i = 15; i > 0; i--) { - xorbuf(Z, m[x[i]], AES_BLOCK_SIZE); + xorbuf(Z, m[x[i]], WC_AES_BLOCK_SIZE); a = Z[15]; for (j = 15; j > 0; j--) { @@ -6891,11 +6963,11 @@ static void GMULT(byte *x, byte m[256][AES_BLOCK_SIZE]) Z[0] = R[a][0]; Z[1] ^= R[a][1]; } - xorbuf(Z, m[x[0]], AES_BLOCK_SIZE); + xorbuf(Z, m[x[0]], WC_AES_BLOCK_SIZE); - XMEMCPY(x, Z, AES_BLOCK_SIZE); + XMEMCPY(x, Z, WC_AES_BLOCK_SIZE); #elif defined(WC_32BIT_CPU) - byte Z[AES_BLOCK_SIZE + AES_BLOCK_SIZE]; + byte Z[WC_AES_BLOCK_SIZE + WC_AES_BLOCK_SIZE]; byte a; word32* pZ; word32* pm; @@ -6927,7 +6999,7 @@ static void GMULT(byte *x, byte m[256][AES_BLOCK_SIZE]) px[0] = pZ[0] ^ pm[0]; px[1] = pZ[1] ^ pm[1]; px[2] = pZ[2] ^ pm[2]; px[3] = pZ[3] ^ pm[3]; #else - byte Z[AES_BLOCK_SIZE + AES_BLOCK_SIZE]; + byte Z[WC_AES_BLOCK_SIZE + WC_AES_BLOCK_SIZE]; byte a; word64* pZ; word64* pm; @@ -6959,46 +7031,46 @@ static void GMULT(byte *x, byte m[256][AES_BLOCK_SIZE]) void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word32 cSz, byte* s, word32 sSz) { - byte x[AES_BLOCK_SIZE]; - byte scratch[AES_BLOCK_SIZE]; + byte x[WC_AES_BLOCK_SIZE]; + byte scratch[WC_AES_BLOCK_SIZE]; word32 blocks, partial; if (gcm == NULL) { return; } - XMEMSET(x, 0, AES_BLOCK_SIZE); + XMEMSET(x, 0, WC_AES_BLOCK_SIZE); /* Hash in A, the Additional Authentication Data */ if (aSz != 0 && a != NULL) { - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, a, AES_BLOCK_SIZE); + xorbuf(x, a, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, a, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); } } /* Hash in C, the Ciphertext */ if (cSz != 0 && c != NULL) { - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, c, AES_BLOCK_SIZE); + xorbuf(x, c, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, c, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); } } @@ -7006,7 +7078,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, /* Hash in the lengths of A and C in bits */ FlattenSzInBits(&scratch[0], aSz); FlattenSzInBits(&scratch[8], cSz); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); /* Copy the result into s. */ @@ -7029,7 +7101,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_ONE_BLOCK(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, AES_BLOCK_SIZE); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT(AES_TAG(aes), aes->gcm.M0); \ } \ while (0) @@ -7082,10 +7154,10 @@ static const word16 R[32] = { * [0..15] * H */ #if defined(BIG_ENDIAN_ORDER) || defined(WC_16BIT_CPU) -static void GMULT(byte *x, byte m[16][AES_BLOCK_SIZE]) +static void GMULT(byte *x, byte m[16][WC_AES_BLOCK_SIZE]) { int i, j, n; - byte Z[AES_BLOCK_SIZE]; + byte Z[WC_AES_BLOCK_SIZE]; byte a; XMEMSET(Z, 0, sizeof(Z)); @@ -7093,9 +7165,9 @@ static void GMULT(byte *x, byte m[16][AES_BLOCK_SIZE]) for (i = 15; i >= 0; i--) { for (n = 0; n < 2; n++) { if (n == 0) - xorbuf(Z, m[x[i] & 0xf], AES_BLOCK_SIZE); + xorbuf(Z, m[x[i] & 0xf], WC_AES_BLOCK_SIZE); else { - xorbuf(Z, m[x[i] >> 4], AES_BLOCK_SIZE); + xorbuf(Z, m[x[i] >> 4], WC_AES_BLOCK_SIZE); if (i == 0) break; } @@ -7110,10 +7182,10 @@ static void GMULT(byte *x, byte m[16][AES_BLOCK_SIZE]) } } - XMEMCPY(x, Z, AES_BLOCK_SIZE); + XMEMCPY(x, Z, WC_AES_BLOCK_SIZE); } #elif defined(WC_32BIT_CPU) -static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) +static WC_INLINE void GMULT(byte *x, byte m[32][WC_AES_BLOCK_SIZE]) { int i; word32 z8[4] = {0, 0, 0, 0}; @@ -7187,7 +7259,7 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) x8[0] = z8[0]; x8[1] = z8[1]; x8[2] = z8[2]; x8[3] = z8[3]; } #else -static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) +static WC_INLINE void GMULT(byte *x, byte m[32][WC_AES_BLOCK_SIZE]) { int i; word64 z8[2] = {0, 0}; @@ -7259,46 +7331,46 @@ static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE]) void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word32 cSz, byte* s, word32 sSz) { - byte x[AES_BLOCK_SIZE]; - byte scratch[AES_BLOCK_SIZE]; + byte x[WC_AES_BLOCK_SIZE]; + byte scratch[WC_AES_BLOCK_SIZE]; word32 blocks, partial; if (gcm == NULL) { return; } - XMEMSET(x, 0, AES_BLOCK_SIZE); + XMEMSET(x, 0, WC_AES_BLOCK_SIZE); /* Hash in A, the Additional Authentication Data */ if (aSz != 0 && a != NULL) { - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, a, AES_BLOCK_SIZE); + xorbuf(x, a, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, a, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); } } /* Hash in C, the Ciphertext */ if (cSz != 0 && c != NULL) { - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; while (blocks--) { - xorbuf(x, c, AES_BLOCK_SIZE); + xorbuf(x, c, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(scratch, 0, AES_BLOCK_SIZE); + XMEMSET(scratch, 0, WC_AES_BLOCK_SIZE); XMEMCPY(scratch, c, partial); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); } } @@ -7306,7 +7378,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, /* Hash in the lengths of A and C in bits */ FlattenSzInBits(&scratch[0], aSz); FlattenSzInBits(&scratch[8], cSz); - xorbuf(x, scratch, AES_BLOCK_SIZE); + xorbuf(x, scratch, WC_AES_BLOCK_SIZE); GMULT(x, gcm->M0); /* Copy the result into s. */ @@ -7320,6 +7392,8 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_INIT_EXTRA(aes) WC_DO_NOTHING +#if !defined(__aarch64__) || !defined(WOLFSSL_ARMASM) || \ + defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) /* GHASH one block of data.. * * XOR block into tag and GMULT with H using pre-computed table. @@ -7329,10 +7403,11 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_ONE_BLOCK(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, AES_BLOCK_SIZE); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT(AES_TAG(aes), (aes)->gcm.M0); \ } \ while (0) +#endif #endif /* WOLFSSL_AESGCM_STREAM */ #elif defined(WORD64_AVAILABLE) && !defined(GCM_WORD32) @@ -7385,31 +7460,31 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, return; } - XMEMCPY(bigH, gcm->H, AES_BLOCK_SIZE); + XMEMCPY(bigH, gcm->H, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(bigH, bigH, AES_BLOCK_SIZE); + ByteReverseWords64(bigH, bigH, WC_AES_BLOCK_SIZE); #endif /* Hash in A, the Additional Authentication Data */ if (aSz != 0 && a != NULL) { word64 bigA[2]; - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; while (blocks--) { - XMEMCPY(bigA, a, AES_BLOCK_SIZE); + XMEMCPY(bigA, a, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(bigA, bigA, AES_BLOCK_SIZE); + ByteReverseWords64(bigA, bigA, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigA[0]; x[1] ^= bigA[1]; GMULT(x, bigH); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(bigA, 0, AES_BLOCK_SIZE); + XMEMSET(bigA, 0, WC_AES_BLOCK_SIZE); XMEMCPY(bigA, a, partial); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(bigA, bigA, AES_BLOCK_SIZE); + ByteReverseWords64(bigA, bigA, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigA[0]; x[1] ^= bigA[1]; @@ -7427,8 +7502,8 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, /* Hash in C, the Ciphertext */ if (cSz != 0 && c != NULL) { word64 bigC[2]; - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; #ifdef OPENSSL_EXTRA /* Start from last AAD partial tag */ if(gcm->aadLen) { @@ -7437,20 +7512,20 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, } #endif while (blocks--) { - XMEMCPY(bigC, c, AES_BLOCK_SIZE); + XMEMCPY(bigC, c, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(bigC, bigC, AES_BLOCK_SIZE); + ByteReverseWords64(bigC, bigC, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigC[0]; x[1] ^= bigC[1]; GMULT(x, bigH); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(bigC, 0, AES_BLOCK_SIZE); + XMEMSET(bigC, 0, WC_AES_BLOCK_SIZE); XMEMCPY(bigC, c, partial); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(bigC, bigC, AES_BLOCK_SIZE); + ByteReverseWords64(bigC, bigC, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigC[0]; x[1] ^= bigC[1]; @@ -7475,7 +7550,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, GMULT(x, bigH); } #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64(x, x, AES_BLOCK_SIZE); + ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); #endif XMEMCPY(s, x, sSz); } @@ -7490,7 +7565,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in] aes AES GCM object. */ #define GHASH_INIT_EXTRA(aes) \ - ByteReverseWords64((word64*)aes->gcm.H, (word64*)aes->gcm.H, AES_BLOCK_SIZE) + ByteReverseWords64((word64*)aes->gcm.H, (word64*)aes->gcm.H, WC_AES_BLOCK_SIZE) /* GHASH one block of data.. * @@ -7504,8 +7579,8 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word64* x = (word64*)AES_TAG(aes); \ word64* h = (word64*)aes->gcm.H; \ word64 block64[2]; \ - XMEMCPY(block64, block, AES_BLOCK_SIZE); \ - ByteReverseWords64(block64, block64, AES_BLOCK_SIZE); \ + XMEMCPY(block64, block, WC_AES_BLOCK_SIZE); \ + ByteReverseWords64(block64, block64, WC_AES_BLOCK_SIZE); \ x[0] ^= block64[0]; \ x[1] ^= block64[1]; \ GMULT(x, h); \ @@ -7534,7 +7609,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[0] ^= len[0]; \ x[1] ^= len[1]; \ GMULT(x, h); \ - ByteReverseWords64(x, x, AES_BLOCK_SIZE); \ + ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #else @@ -7557,7 +7632,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[0] ^= len[0]; \ x[1] ^= len[1]; \ GMULT(x, h); \ - ByteReverseWords64(x, x, AES_BLOCK_SIZE); \ + ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #endif @@ -7582,7 +7657,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word64* x = (word64*)AES_TAG(aes); \ word64* h = (word64*)aes->gcm.H; \ word64 block64[2]; \ - XMEMCPY(block64, block, AES_BLOCK_SIZE); \ + XMEMCPY(block64, block, WC_AES_BLOCK_SIZE); \ x[0] ^= block64[0]; \ x[1] ^= block64[1]; \ GMULT(x, h); \ @@ -7702,33 +7777,33 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, return; } - XMEMCPY(bigH, gcm->H, AES_BLOCK_SIZE); + XMEMCPY(bigH, gcm->H, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(bigH, bigH, AES_BLOCK_SIZE); + ByteReverseWords(bigH, bigH, WC_AES_BLOCK_SIZE); #endif /* Hash in A, the Additional Authentication Data */ if (aSz != 0 && a != NULL) { word32 bigA[4]; - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; while (blocks--) { - XMEMCPY(bigA, a, AES_BLOCK_SIZE); + XMEMCPY(bigA, a, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(bigA, bigA, AES_BLOCK_SIZE); + ByteReverseWords(bigA, bigA, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigA[0]; x[1] ^= bigA[1]; x[2] ^= bigA[2]; x[3] ^= bigA[3]; GMULT(x, bigH); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(bigA, 0, AES_BLOCK_SIZE); + XMEMSET(bigA, 0, WC_AES_BLOCK_SIZE); XMEMCPY(bigA, a, partial); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(bigA, bigA, AES_BLOCK_SIZE); + ByteReverseWords(bigA, bigA, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigA[0]; x[1] ^= bigA[1]; @@ -7741,25 +7816,25 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, /* Hash in C, the Ciphertext */ if (cSz != 0 && c != NULL) { word32 bigC[4]; - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; while (blocks--) { - XMEMCPY(bigC, c, AES_BLOCK_SIZE); + XMEMCPY(bigC, c, WC_AES_BLOCK_SIZE); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(bigC, bigC, AES_BLOCK_SIZE); + ByteReverseWords(bigC, bigC, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigC[0]; x[1] ^= bigC[1]; x[2] ^= bigC[2]; x[3] ^= bigC[3]; GMULT(x, bigH); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { - XMEMSET(bigC, 0, AES_BLOCK_SIZE); + XMEMSET(bigC, 0, WC_AES_BLOCK_SIZE); XMEMCPY(bigC, c, partial); #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(bigC, bigC, AES_BLOCK_SIZE); + ByteReverseWords(bigC, bigC, WC_AES_BLOCK_SIZE); #endif x[0] ^= bigC[0]; x[1] ^= bigC[1]; @@ -7786,7 +7861,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, GMULT(x, bigH); } #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords(x, x, AES_BLOCK_SIZE); + ByteReverseWords(x, x, WC_AES_BLOCK_SIZE); #endif XMEMCPY(s, x, sSz); } @@ -7800,7 +7875,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. */ #define GHASH_INIT_EXTRA(aes) \ - ByteReverseWords((word32*)aes->gcm.H, (word32*)aes->gcm.H, AES_BLOCK_SIZE) + ByteReverseWords((word32*)aes->gcm.H, (word32*)aes->gcm.H, WC_AES_BLOCK_SIZE) /* GHASH one block of data.. * @@ -7814,8 +7889,8 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word32* x = (word32*)AES_TAG(aes); \ word32* h = (word32*)aes->gcm.H; \ word32 bigEnd[4]; \ - XMEMCPY(bigEnd, block, AES_BLOCK_SIZE); \ - ByteReverseWords(bigEnd, bigEnd, AES_BLOCK_SIZE); \ + XMEMCPY(bigEnd, block, WC_AES_BLOCK_SIZE); \ + ByteReverseWords(bigEnd, bigEnd, WC_AES_BLOCK_SIZE); \ x[0] ^= bigEnd[0]; \ x[1] ^= bigEnd[1]; \ x[2] ^= bigEnd[2]; \ @@ -7844,7 +7919,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[2] ^= len[2]; \ x[3] ^= len[3]; \ GMULT(x, h); \ - ByteReverseWords(x, x, AES_BLOCK_SIZE); \ + ByteReverseWords(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #else @@ -7866,7 +7941,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, word32* x = (word32*)AES_TAG(aes); \ word32* h = (word32*)aes->gcm.H; \ word32 block32[4]; \ - XMEMCPY(block32, block, AES_BLOCK_SIZE); \ + XMEMCPY(block32, block, WC_AES_BLOCK_SIZE); \ x[0] ^= block32[0]; \ x[1] ^= block32[1]; \ x[2] ^= block32[2]; \ @@ -7910,7 +7985,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_LEN_BLOCK(aes) \ do { \ - byte scratch[AES_BLOCK_SIZE]; \ + byte scratch[WC_AES_BLOCK_SIZE]; \ FlattenSzInBits(&scratch[0], (aes)->aSz); \ FlattenSzInBits(&scratch[8], (aes)->cSz); \ GHASH_ONE_BLOCK(aes, scratch); \ @@ -7924,12 +7999,21 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ static void GHASH_INIT(Aes* aes) { /* Set tag to all zeros as initial value. */ - XMEMSET(AES_TAG(aes), 0, AES_BLOCK_SIZE); + XMEMSET(AES_TAG(aes), 0, WC_AES_BLOCK_SIZE); /* Reset counts of AAD and cipher text. */ aes->aOver = 0; aes->cOver = 0; - /* Extra initialization based on implementation. */ - GHASH_INIT_EXTRA(aes); +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { + ; /* Don't do extra initialization. */ + } + else +#endif + { + /* Extra initialization based on implementation. */ + GHASH_INIT_EXTRA(aes); + } } /* Update the GHASH with AAD and/or cipher text. @@ -7953,14 +8037,14 @@ static void GHASH_UPDATE(Aes* aes, const byte* a, word32 aSz, const byte* c, /* Check if we have unprocessed data. */ if (aes->aOver > 0) { /* Calculate amount we can use - fill up the block. */ - byte sz = AES_BLOCK_SIZE - aes->aOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->aOver); if (sz > aSz) { sz = (byte)aSz; } /* Copy extra into last GHASH block array and update count. */ XMEMCPY(AES_LASTGBLOCK(aes) + aes->aOver, a, sz); - aes->aOver += sz; - if (aes->aOver == AES_BLOCK_SIZE) { + aes->aOver = (byte)(aes->aOver + sz); + if (aes->aOver == WC_AES_BLOCK_SIZE) { /* We have filled up the block and can process. */ GHASH_ONE_BLOCK(aes, AES_LASTGBLOCK(aes)); /* Reset count. */ @@ -7972,12 +8056,12 @@ static void GHASH_UPDATE(Aes* aes, const byte* a, word32 aSz, const byte* c, } /* Calculate number of blocks of AAD and the leftover. */ - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; /* GHASH full blocks now. */ while (blocks--) { GHASH_ONE_BLOCK(aes, a); - a += AES_BLOCK_SIZE; + a += WC_AES_BLOCK_SIZE; } if (partial != 0) { /* Cache the partial block. */ @@ -7988,7 +8072,7 @@ static void GHASH_UPDATE(Aes* aes, const byte* a, word32 aSz, const byte* c, if (aes->aOver > 0 && cSz > 0 && c != NULL) { /* No more AAD coming and we have a partial block. */ /* Fill the rest of the block with zeros. */ - byte sz = AES_BLOCK_SIZE - aes->aOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->aOver); XMEMSET(AES_LASTGBLOCK(aes) + aes->aOver, 0, sz); /* GHASH last AAD block. */ GHASH_ONE_BLOCK(aes, AES_LASTGBLOCK(aes)); @@ -8002,14 +8086,14 @@ static void GHASH_UPDATE(Aes* aes, const byte* a, word32 aSz, const byte* c, aes->cSz += cSz; if (aes->cOver > 0) { /* Calculate amount we can use - fill up the block. */ - byte sz = AES_BLOCK_SIZE - aes->cOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->cOver); if (sz > cSz) { sz = (byte)cSz; } XMEMCPY(AES_LASTGBLOCK(aes) + aes->cOver, c, sz); /* Update count of unused encrypted counter. */ - aes->cOver += sz; - if (aes->cOver == AES_BLOCK_SIZE) { + aes->cOver = (byte)(aes->cOver + sz); + if (aes->cOver == WC_AES_BLOCK_SIZE) { /* We have filled up the block and can process. */ GHASH_ONE_BLOCK(aes, AES_LASTGBLOCK(aes)); /* Reset count. */ @@ -8021,12 +8105,12 @@ static void GHASH_UPDATE(Aes* aes, const byte* a, word32 aSz, const byte* c, } /* Calculate number of blocks of cipher text and the leftover. */ - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; /* GHASH full blocks now. */ while (blocks--) { GHASH_ONE_BLOCK(aes, c); - c += AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } if (partial != 0) { /* Cache the partial block. */ @@ -8055,7 +8139,7 @@ static void GHASH_FINAL(Aes* aes, byte* s, word32 sSz) } if (over > 0) { /* Zeroize the unused part of the block. */ - XMEMSET(AES_LASTGBLOCK(aes) + over, 0, AES_BLOCK_SIZE - over); + XMEMSET(AES_LASTGBLOCK(aes) + over, 0, (size_t)WC_AES_BLOCK_SIZE - over); /* Hash the last block of cipher text. */ GHASH_ONE_BLOCK(aes, AES_LASTGBLOCK(aes)); } @@ -8063,7 +8147,7 @@ static void GHASH_FINAL(Aes* aes, byte* s, word32 sSz) GHASH_LEN_BLOCK(aes); /* Copy the result into s. */ XMEMCPY(s, AES_TAG(aes), sSz); - /* reset aes->gcm.H in case of re-use */ + /* reset aes->gcm.H in case of reuse */ GHASH_INIT_EXTRA(aes); } #endif /* WOLFSSL_AESGCM_STREAM */ @@ -8079,7 +8163,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, word32 keySize; /* argument checks */ - if (aes == NULL || authTagSz > AES_BLOCK_SIZE || ivSz == 0) { + if (aes == NULL || authTagSz > WC_AES_BLOCK_SIZE || ivSz == 0) { return BAD_FUNC_ARG; } @@ -8125,16 +8209,16 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( word32 keySize; #ifdef WOLFSSL_STM32_CUBEMX int status = HAL_OK; - word32 blocks = sz / AES_BLOCK_SIZE; - word32 partialBlock[AES_BLOCK_SIZE/sizeof(word32)]; + word32 blocks = sz / WC_AES_BLOCK_SIZE; + word32 partialBlock[WC_AES_BLOCK_SIZE/sizeof(word32)]; #else int status = SUCCESS; #endif - word32 partial = sz % AES_BLOCK_SIZE; - word32 tag[AES_BLOCK_SIZE/sizeof(word32)]; - word32 ctrInit[AES_BLOCK_SIZE/sizeof(word32)]; - word32 ctr[AES_BLOCK_SIZE/sizeof(word32)]; - word32 authhdr[AES_BLOCK_SIZE/sizeof(word32)]; + word32 partial = sz % WC_AES_BLOCK_SIZE; + word32 tag[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 ctrInit[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 ctr[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 authhdr[WC_AES_BLOCK_SIZE/sizeof(word32)]; byte* authInPadded = NULL; int authPadSz, wasAlloc = 0, useSwGhash = 0; @@ -8148,21 +8232,31 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( return ret; #endif - XMEMSET(ctr, 0, AES_BLOCK_SIZE); + XMEMSET(ctr, 0, WC_AES_BLOCK_SIZE); if (ivSz == GCM_NONCE_MID_SZ) { byte* pCtr = (byte*)ctr; XMEMCPY(ctr, iv, ivSz); - pCtr[AES_BLOCK_SIZE - 1] = 1; + pCtr[WC_AES_BLOCK_SIZE - 1] = 1; } else { - GHASH(&aes->gcm, NULL, 0, iv, ivSz, (byte*)ctr, AES_BLOCK_SIZE); + GHASH(&aes->gcm, NULL, 0, iv, ivSz, (byte*)ctr, WC_AES_BLOCK_SIZE); } XMEMCPY(ctrInit, ctr, sizeof(ctr)); /* save off initial counter for GMAC */ /* Authentication buffer - must be 4-byte multiple zero padded */ authPadSz = authInSz % sizeof(word32); +#ifdef WOLFSSL_STM32MP13 + /* STM32MP13 HAL at least v1.2 and lower has a bug with which it needs a + * minimum of 16 bytes for the auth + */ + if ((authInSz > 0) && (authInSz < 16)) { + authPadSz = 16 - authInSz; + } +#endif if (authPadSz != 0) { - authPadSz = authInSz + sizeof(word32) - authPadSz; + if (authPadSz < authInSz + sizeof(word32)) { + authPadSz = authInSz + sizeof(word32) - authPadSz; + } if (authPadSz <= sizeof(authhdr)) { authInPadded = (byte*)authhdr; } @@ -8185,11 +8279,12 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( /* for cases where hardware cannot be used for authTag calculate it */ /* if IV is not 12 calculate GHASH using software */ if (ivSz != GCM_NONCE_MID_SZ - #ifndef CRYP_HEADERWIDTHUNIT_BYTE + #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13) /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(STM32_AESGCM_PARTIAL) + #if (!defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13)) \ + && !defined(STM32_AESGCM_PARTIAL) /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8204,13 +8299,14 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( if (ret != 0) { return ret; } + #ifdef WOLFSSL_STM32_CUBEMX hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr; hcryp.Init.Header = (STM_CRYPT_TYPE*)authInPadded; #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_GCM; - #ifdef CRYP_HEADERWIDTHUNIT_BYTE + #if defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(WOLFSSL_STM32MP13) /* V2 with CRYP_HEADERWIDTHUNIT_BYTE uses byte size for header */ hcryp.Init.HeaderSize = authInSz; #else @@ -8220,27 +8316,27 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( /* allows repeated calls to HAL_CRYP_Encrypt */ hcryp.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE; #endif - ByteReverseWords(ctr, ctr, AES_BLOCK_SIZE); + ByteReverseWords(ctr, ctr, WC_AES_BLOCK_SIZE); hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr; HAL_CRYP_Init(&hcryp); #ifndef CRYP_KEYIVCONFIG_ONCE /* GCM payload phase - can handle partial blocks */ status = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, - (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT); #else /* GCM payload phase - blocks */ if (blocks) { status = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, - (blocks * AES_BLOCK_SIZE), (uint32_t*)out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), (uint32_t*)out, STM32_HAL_TIMEOUT); } /* GCM payload phase - partial remainder */ if (status == HAL_OK && (partial != 0 || blocks == 0)) { XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)partialBlock, partial, (uint32_t*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } #endif if (status == HAL_OK && !useSwGhash) { @@ -8270,16 +8366,16 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( hcryp.Init.GCMCMACPhase = CRYP_PAYLOAD_PHASE; if (blocks) { status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)in, - (blocks * AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); } } if (status == HAL_OK && (partial != 0 || (sz > 0 && blocks == 0))) { /* GCM payload phase - partial remainder */ XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYPEx_AES_Auth(&hcryp, (uint8_t*)partialBlock, partial, (uint8_t*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } if (status == HAL_OK && !useSwGhash) { /* GCM final phase */ @@ -8292,15 +8388,15 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( if (blocks) { /* GCM payload phase - blocks */ status = HAL_CRYPEx_AESGCM_Encrypt(&hcryp, (byte*)in, - (blocks * AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); } if (status == HAL_OK && (partial != 0 || blocks == 0)) { /* GCM payload phase - partial remainder */ XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYPEx_AESGCM_Encrypt(&hcryp, (uint8_t*)partialBlock, partial, (uint8_t*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } if (status == HAL_OK && !useSwGhash) { /* Compute the authTag */ @@ -8369,20 +8465,20 @@ WARN_UNUSED_RESULT int AES_GCM_encrypt_C( const byte* authIn, word32 authInSz) { int ret = 0; - word32 blocks = sz / AES_BLOCK_SIZE; - word32 partial = sz % AES_BLOCK_SIZE; + word32 blocks = sz / WC_AES_BLOCK_SIZE; + word32 partial = sz % WC_AES_BLOCK_SIZE; const byte* p = in; byte* c = out; - ALIGN16 byte counter[AES_BLOCK_SIZE]; - ALIGN16 byte initialCounter[AES_BLOCK_SIZE]; - ALIGN16 byte scratch[AES_BLOCK_SIZE]; + ALIGN16 byte counter[WC_AES_BLOCK_SIZE]; + ALIGN16 byte initialCounter[WC_AES_BLOCK_SIZE]; + ALIGN16 byte scratch[WC_AES_BLOCK_SIZE]; if (ivSz == GCM_NONCE_MID_SZ) { /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */ XMEMCPY(counter, iv, ivSz); XMEMSET(counter + GCM_NONCE_MID_SZ, 0, - AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); - counter[AES_BLOCK_SIZE - 1] = 1; + WC_AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); + counter[WC_AES_BLOCK_SIZE - 1] = 1; } else { /* Counter is GHASH of IV. */ @@ -8390,21 +8486,21 @@ WARN_UNUSED_RESULT int AES_GCM_encrypt_C( word32 aadTemp = aes->gcm.aadLen; aes->gcm.aadLen = 0; #endif - GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, AES_BLOCK_SIZE); + GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, WC_AES_BLOCK_SIZE); #ifdef OPENSSL_EXTRA aes->gcm.aadLen = aadTemp; #endif } - XMEMCPY(initialCounter, counter, AES_BLOCK_SIZE); + XMEMCPY(initialCounter, counter, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_PIC32MZ_CRYPT if (blocks) { /* use initial IV for HW, but don't use it below */ - XMEMCPY(aes->reg, counter, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, counter, WC_AES_BLOCK_SIZE); ret = wc_Pic32AesCrypt( - aes->key, aes->keylen, aes->reg, AES_BLOCK_SIZE, - out, in, (blocks * AES_BLOCK_SIZE), + aes->key, aes->keylen, aes->reg, WC_AES_BLOCK_SIZE, + out, in, (blocks * WC_AES_BLOCK_SIZE), PIC32_ENCRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_AES_GCM); if (ret != 0) return ret; @@ -8418,15 +8514,15 @@ WARN_UNUSED_RESULT int AES_GCM_encrypt_C( if (c != p && blocks > 0) { /* can not handle inline encryption */ while (blocks--) { IncrementGcmCounter(counter); - XMEMCPY(c, counter, AES_BLOCK_SIZE); - c += AES_BLOCK_SIZE; + XMEMCPY(c, counter, WC_AES_BLOCK_SIZE); + c += WC_AES_BLOCK_SIZE; } /* reset number of blocks and then do encryption */ - blocks = sz / AES_BLOCK_SIZE; - wc_AesEcbEncrypt(aes, out, out, AES_BLOCK_SIZE * blocks); - xorbuf(out, p, AES_BLOCK_SIZE * blocks); - p += AES_BLOCK_SIZE * blocks; + blocks = sz / WC_AES_BLOCK_SIZE; + wc_AesEcbEncrypt(aes, out, out, WC_AES_BLOCK_SIZE * blocks); + xorbuf(out, p, WC_AES_BLOCK_SIZE * blocks); + p += WC_AES_BLOCK_SIZE * blocks; } else #endif /* HAVE_AES_ECB && !WOLFSSL_PIC32MZ_CRYPT */ @@ -8437,10 +8533,10 @@ WARN_UNUSED_RESULT int AES_GCM_encrypt_C( ret = wc_AesEncrypt(aes, counter, scratch); if (ret != 0) return ret; - xorbufout(c, scratch, p, AES_BLOCK_SIZE); + xorbufout(c, scratch, p, WC_AES_BLOCK_SIZE); #endif - p += AES_BLOCK_SIZE; - c += AES_BLOCK_SIZE; + p += WC_AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } } @@ -8476,7 +8572,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, int ret; /* argument checks */ - if (aes == NULL || authTagSz > AES_BLOCK_SIZE || ivSz == 0 || + if (aes == NULL || authTagSz > WC_AES_BLOCK_SIZE || ivSz == 0 || ((authTagSz > 0) && (authTag == NULL)) || ((authInSz > 0) && (authIn == NULL))) { @@ -8578,6 +8674,14 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, } } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { + AES_GCM_encrypt_AARCH64(aes, out, in, sz, iv, ivSz, authTag, authTagSz, + authIn, authInSz); + ret = 0; + } + else #endif /* WOLFSSL_AESNI */ { ret = AES_GCM_encrypt_C(aes, out, in, sz, iv, ivSz, authTag, authTagSz, @@ -8607,7 +8711,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, /* If the sz is non-zero, both in and out must be set. If sz is 0, * in and out are don't cares, as this is is the GMAC case. */ if (aes == NULL || iv == NULL || (sz != 0 && (in == NULL || out == NULL)) || - authTag == NULL || authTagSz > AES_BLOCK_SIZE || authTagSz == 0 || + authTag == NULL || authTagSz > WC_AES_BLOCK_SIZE || authTagSz == 0 || ivSz == 0 || ((authInSz > 0) && (authIn == NULL))) { return BAD_FUNC_ARG; @@ -8644,18 +8748,18 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( #ifdef WOLFSSL_STM32_CUBEMX int status = HAL_OK; CRYP_HandleTypeDef hcryp; - word32 blocks = sz / AES_BLOCK_SIZE; + word32 blocks = sz / WC_AES_BLOCK_SIZE; #else int status = SUCCESS; word32 keyCopy[AES_256_KEY_SIZE/sizeof(word32)]; #endif word32 keySize; - word32 partial = sz % AES_BLOCK_SIZE; - word32 tag[AES_BLOCK_SIZE/sizeof(word32)]; - word32 tagExpected[AES_BLOCK_SIZE/sizeof(word32)]; - word32 partialBlock[AES_BLOCK_SIZE/sizeof(word32)]; - word32 ctr[AES_BLOCK_SIZE/sizeof(word32)]; - word32 authhdr[AES_BLOCK_SIZE/sizeof(word32)]; + word32 partial = sz % WC_AES_BLOCK_SIZE; + word32 tag[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 tagExpected[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 partialBlock[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 ctr[WC_AES_BLOCK_SIZE/sizeof(word32)]; + word32 authhdr[WC_AES_BLOCK_SIZE/sizeof(word32)]; byte* authInPadded = NULL; int authPadSz, wasAlloc = 0, tagComputed = 0; @@ -8669,14 +8773,14 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( return ret; #endif - XMEMSET(ctr, 0, AES_BLOCK_SIZE); + XMEMSET(ctr, 0, WC_AES_BLOCK_SIZE); if (ivSz == GCM_NONCE_MID_SZ) { byte* pCtr = (byte*)ctr; XMEMCPY(ctr, iv, ivSz); - pCtr[AES_BLOCK_SIZE - 1] = 1; + pCtr[WC_AES_BLOCK_SIZE - 1] = 1; } else { - GHASH(&aes->gcm, NULL, 0, iv, ivSz, (byte*)ctr, AES_BLOCK_SIZE); + GHASH(&aes->gcm, NULL, 0, iv, ivSz, (byte*)ctr, WC_AES_BLOCK_SIZE); } /* Make copy of expected authTag, which could get corrupted in some @@ -8693,14 +8797,24 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( authPadSz = authInSz; } +#ifdef WOLFSSL_STM32MP13 + /* STM32MP13 HAL at least v1.2 and lower has a bug with which it needs a + * minimum of 16 bytes for the auth + */ + if ((authInSz > 0) && (authInSz < 16)) { + authPadSz = 16 - authInSz; + } +#endif + /* for cases where hardware cannot be used for authTag calculate it */ /* if IV is not 12 calculate GHASH using software */ if (ivSz != GCM_NONCE_MID_SZ - #ifndef CRYP_HEADERWIDTHUNIT_BYTE + #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13) /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(STM32_AESGCM_PARTIAL) + #if (!defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13)) \ + && !defined(STM32_AESGCM_PARTIAL) /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8746,7 +8860,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_GCM; - #ifdef CRYP_HEADERWIDTHUNIT_BYTE + #if defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(WOLFSSL_STM32MP13) /* V2 with CRYP_HEADERWIDTHUNIT_BYTE uses byte size for header */ hcryp.Init.HeaderSize = authInSz; #else @@ -8756,26 +8870,26 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( /* allows repeated calls to HAL_CRYP_Decrypt */ hcryp.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE; #endif - ByteReverseWords(ctr, ctr, AES_BLOCK_SIZE); + ByteReverseWords(ctr, ctr, WC_AES_BLOCK_SIZE); hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr; HAL_CRYP_Init(&hcryp); #ifndef CRYP_KEYIVCONFIG_ONCE status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, - (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT); #else /* GCM payload phase - blocks */ if (blocks) { status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, - (blocks * AES_BLOCK_SIZE), (uint32_t*)out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), (uint32_t*)out, STM32_HAL_TIMEOUT); } /* GCM payload phase - partial remainder */ if (status == HAL_OK && (partial != 0 || blocks == 0)) { XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)partialBlock, partial, (uint32_t*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } #endif if (status == HAL_OK && !tagComputed) { @@ -8805,16 +8919,16 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( hcryp.Init.GCMCMACPhase = CRYP_PAYLOAD_PHASE; if (blocks) { status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)in, - (blocks * AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); } } if (status == HAL_OK && (partial != 0 || (sz > 0 && blocks == 0))) { /* GCM payload phase - partial remainder */ XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)partialBlock, partial, (byte*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } if (status == HAL_OK && tagComputed == 0) { /* GCM final phase */ @@ -8827,15 +8941,15 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( if (blocks) { /* GCM payload phase - blocks */ status = HAL_CRYPEx_AESGCM_Decrypt(&hcryp, (byte*)in, - (blocks * AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); + (blocks * WC_AES_BLOCK_SIZE), out, STM32_HAL_TIMEOUT); } if (status == HAL_OK && (partial != 0 || blocks == 0)) { /* GCM payload phase - partial remainder */ XMEMSET(partialBlock, 0, sizeof(partialBlock)); - XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial); + XMEMCPY(partialBlock, in + (blocks * WC_AES_BLOCK_SIZE), partial); status = HAL_CRYPEx_AESGCM_Decrypt(&hcryp, (byte*)partialBlock, partial, (byte*)partialBlock, STM32_HAL_TIMEOUT); - XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial); + XMEMCPY(out + (blocks * WC_AES_BLOCK_SIZE), partialBlock, partial); } if (status == HAL_OK && tagComputed == 0) { /* Compute the authTag */ @@ -8900,22 +9014,22 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( const byte* authIn, word32 authInSz) { int ret; - word32 blocks = sz / AES_BLOCK_SIZE; - word32 partial = sz % AES_BLOCK_SIZE; + word32 blocks = sz / WC_AES_BLOCK_SIZE; + word32 partial = sz % WC_AES_BLOCK_SIZE; const byte* c = in; byte* p = out; - ALIGN16 byte counter[AES_BLOCK_SIZE]; - ALIGN16 byte scratch[AES_BLOCK_SIZE]; - ALIGN16 byte Tprime[AES_BLOCK_SIZE]; - ALIGN16 byte EKY0[AES_BLOCK_SIZE]; + ALIGN16 byte counter[WC_AES_BLOCK_SIZE]; + ALIGN16 byte scratch[WC_AES_BLOCK_SIZE]; + ALIGN16 byte Tprime[WC_AES_BLOCK_SIZE]; + ALIGN16 byte EKY0[WC_AES_BLOCK_SIZE]; sword32 res; if (ivSz == GCM_NONCE_MID_SZ) { /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */ XMEMCPY(counter, iv, ivSz); XMEMSET(counter + GCM_NONCE_MID_SZ, 0, - AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); - counter[AES_BLOCK_SIZE - 1] = 1; + WC_AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); + counter[WC_AES_BLOCK_SIZE - 1] = 1; } else { /* Counter is GHASH of IV. */ @@ -8923,7 +9037,7 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( word32 aadTemp = aes->gcm.aadLen; aes->gcm.aadLen = 0; #endif - GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, AES_BLOCK_SIZE); + GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, WC_AES_BLOCK_SIZE); #ifdef OPENSSL_EXTRA aes->gcm.aadLen = aadTemp; #endif @@ -8960,11 +9074,11 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( #if defined(WOLFSSL_PIC32MZ_CRYPT) if (blocks) { /* use initial IV for HW, but don't use it below */ - XMEMCPY(aes->reg, counter, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, counter, WC_AES_BLOCK_SIZE); ret = wc_Pic32AesCrypt( - aes->key, aes->keylen, aes->reg, AES_BLOCK_SIZE, - out, in, (blocks * AES_BLOCK_SIZE), + aes->key, aes->keylen, aes->reg, WC_AES_BLOCK_SIZE, + out, in, (blocks * WC_AES_BLOCK_SIZE), PIC32_DECRYPTION, PIC32_ALGO_AES, PIC32_CRYPTOALGO_AES_GCM); if (ret != 0) return ret; @@ -8978,16 +9092,16 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( if (c != p && blocks > 0) { /* can not handle inline decryption */ while (blocks--) { IncrementGcmCounter(counter); - XMEMCPY(p, counter, AES_BLOCK_SIZE); - p += AES_BLOCK_SIZE; + XMEMCPY(p, counter, WC_AES_BLOCK_SIZE); + p += WC_AES_BLOCK_SIZE; } /* reset number of blocks and then do encryption */ - blocks = sz / AES_BLOCK_SIZE; + blocks = sz / WC_AES_BLOCK_SIZE; - wc_AesEcbEncrypt(aes, out, out, AES_BLOCK_SIZE * blocks); - xorbuf(out, c, AES_BLOCK_SIZE * blocks); - c += AES_BLOCK_SIZE * blocks; + wc_AesEcbEncrypt(aes, out, out, WC_AES_BLOCK_SIZE * blocks); + xorbuf(out, c, WC_AES_BLOCK_SIZE * blocks); + c += WC_AES_BLOCK_SIZE * blocks; } else #endif /* HAVE_AES_ECB && !PIC32MZ */ @@ -8998,10 +9112,10 @@ int WARN_UNUSED_RESULT AES_GCM_decrypt_C( ret = wc_AesEncrypt(aes, counter, scratch); if (ret != 0) return ret; - xorbufout(p, scratch, c, AES_BLOCK_SIZE); + xorbufout(p, scratch, c, WC_AES_BLOCK_SIZE); #endif - p += AES_BLOCK_SIZE; - c += AES_BLOCK_SIZE; + p += WC_AES_BLOCK_SIZE; + c += WC_AES_BLOCK_SIZE; } } @@ -9046,7 +9160,7 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, /* If the sz is non-zero, both in and out must be set. If sz is 0, * in and out are don't cares, as this is is the GMAC case. */ if (aes == NULL || iv == NULL || (sz != 0 && (in == NULL || out == NULL)) || - authTag == NULL || authTagSz > AES_BLOCK_SIZE || authTagSz == 0 || + authTag == NULL || authTagSz > WC_AES_BLOCK_SIZE || authTagSz == 0 || ivSz == 0) { return BAD_FUNC_ARG; @@ -9152,6 +9266,13 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, } } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { + ret = AES_GCM_decrypt_AARCH64(aes, out, in, sz, iv, ivSz, authTag, + authTagSz, authIn, authInSz); + } + else #endif /* WOLFSSL_AESNI */ { ret = AES_GCM_decrypt_C(aes, out, in, sz, iv, ivSz, authTag, authTagSz, @@ -9175,15 +9296,15 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, */ static WARN_UNUSED_RESULT int AesGcmInit_C(Aes* aes, const byte* iv, word32 ivSz) { - ALIGN32 byte counter[AES_BLOCK_SIZE]; + ALIGN32 byte counter[WC_AES_BLOCK_SIZE]; int ret; if (ivSz == GCM_NONCE_MID_SZ) { /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */ XMEMCPY(counter, iv, ivSz); XMEMSET(counter + GCM_NONCE_MID_SZ, 0, - AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); - counter[AES_BLOCK_SIZE - 1] = 1; + WC_AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1); + counter[WC_AES_BLOCK_SIZE - 1] = 1; } else { /* Counter is GHASH of IV. */ @@ -9191,14 +9312,14 @@ static WARN_UNUSED_RESULT int AesGcmInit_C(Aes* aes, const byte* iv, word32 ivSz word32 aadTemp = aes->gcm.aadLen; aes->gcm.aadLen = 0; #endif - GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, AES_BLOCK_SIZE); + GHASH(&aes->gcm, NULL, 0, iv, ivSz, counter, WC_AES_BLOCK_SIZE); #ifdef OPENSSL_EXTRA aes->gcm.aadLen = aadTemp; #endif } /* Copy in the counter for use with cipher. */ - XMEMCPY(AES_COUNTER(aes), counter, AES_BLOCK_SIZE); + XMEMCPY(AES_COUNTER(aes), counter, WC_AES_BLOCK_SIZE); /* Encrypt initial counter into a buffer for GCM. */ ret = wc_AesEncrypt(aes, counter, AES_INITCTR(aes)); if (ret != 0) @@ -9231,12 +9352,12 @@ static WARN_UNUSED_RESULT int AesGcmCryptUpdate_C( /* Check if previous encrypted block was not used up. */ if (aes->over > 0) { - byte pSz = AES_BLOCK_SIZE - aes->over; + byte pSz = (byte)(WC_AES_BLOCK_SIZE - aes->over); if (pSz > sz) pSz = (byte)sz; /* Use some/all of last encrypted block. */ xorbufout(out, AES_LASTBLOCK(aes) + aes->over, in, pSz); - aes->over = (aes->over + pSz) & (AES_BLOCK_SIZE - 1); + aes->over = (aes->over + pSz) & (WC_AES_BLOCK_SIZE - 1); /* Some data used. */ sz -= pSz; @@ -9246,8 +9367,8 @@ static WARN_UNUSED_RESULT int AesGcmCryptUpdate_C( /* Calculate the number of blocks needing to be encrypted and any leftover. */ - blocks = sz / AES_BLOCK_SIZE; - partial = sz & (AES_BLOCK_SIZE - 1); + blocks = sz / WC_AES_BLOCK_SIZE; + partial = sz & (WC_AES_BLOCK_SIZE - 1); #if defined(HAVE_AES_ECB) /* Some hardware acceleration can gain performance from doing AES encryption @@ -9259,33 +9380,33 @@ static WARN_UNUSED_RESULT int AesGcmCryptUpdate_C( /* Place incrementing counter blocks into cipher text. */ for (b = 0; b < blocks; b++) { IncrementGcmCounter(AES_COUNTER(aes)); - XMEMCPY(out + b * AES_BLOCK_SIZE, AES_COUNTER(aes), AES_BLOCK_SIZE); + XMEMCPY(out + b * WC_AES_BLOCK_SIZE, AES_COUNTER(aes), WC_AES_BLOCK_SIZE); } /* Encrypt counter blocks. */ - wc_AesEcbEncrypt(aes, out, out, AES_BLOCK_SIZE * blocks); + wc_AesEcbEncrypt(aes, out, out, WC_AES_BLOCK_SIZE * blocks); /* XOR in plaintext. */ - xorbuf(out, in, AES_BLOCK_SIZE * blocks); + xorbuf(out, in, WC_AES_BLOCK_SIZE * blocks); /* Skip over processed data. */ - in += AES_BLOCK_SIZE * blocks; - out += AES_BLOCK_SIZE * blocks; + in += WC_AES_BLOCK_SIZE * blocks; + out += WC_AES_BLOCK_SIZE * blocks; } else #endif /* HAVE_AES_ECB */ { /* Encrypt block by block. */ while (blocks--) { - ALIGN32 byte scratch[AES_BLOCK_SIZE]; + ALIGN32 byte scratch[WC_AES_BLOCK_SIZE]; IncrementGcmCounter(AES_COUNTER(aes)); /* Encrypt counter into a buffer. */ ret = wc_AesEncrypt(aes, AES_COUNTER(aes), scratch); if (ret != 0) return ret; /* XOR plain text into encrypted counter into cipher text buffer. */ - xorbufout(out, scratch, in, AES_BLOCK_SIZE); + xorbufout(out, scratch, in, WC_AES_BLOCK_SIZE); /* Data complete. */ - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } } @@ -9323,7 +9444,7 @@ static WARN_UNUSED_RESULT int AesGcmFinal_C( aes->gcm.aadLen = aes->aSz; #endif /* Zeroize last block to protect sensitive data. */ - ForceZero(AES_LASTBLOCK(aes), AES_BLOCK_SIZE); + ForceZero(AES_LASTBLOCK(aes), WC_AES_BLOCK_SIZE); return 0; } @@ -9408,7 +9529,7 @@ static WARN_UNUSED_RESULT int AesGcmInit_aesni( aes->aSz = 0; aes->cSz = 0; /* Set tag to all zeros as initial value. */ - XMEMSET(AES_TAG(aes), 0, AES_BLOCK_SIZE); + XMEMSET(AES_TAG(aes), 0, WC_AES_BLOCK_SIZE); /* Reset counts of AAD and cipher text. */ aes->aOver = 0; aes->cOver = 0; @@ -9458,14 +9579,14 @@ static WARN_UNUSED_RESULT int AesGcmAadUpdate_aesni( /* Check if we have unprocessed data. */ if (aes->aOver > 0) { /* Calculate amount we can use - fill up the block. */ - byte sz = AES_BLOCK_SIZE - aes->aOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->aOver); if (sz > aSz) { sz = (byte)aSz; } /* Copy extra into last GHASH block array and update count. */ XMEMCPY(AES_LASTGBLOCK(aes) + aes->aOver, a, sz); - aes->aOver += sz; - if (aes->aOver == AES_BLOCK_SIZE) { + aes->aOver = (byte)(aes->aOver + sz); + if (aes->aOver == WC_AES_BLOCK_SIZE) { /* We have filled up the block and can process. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -9494,30 +9615,30 @@ static WARN_UNUSED_RESULT int AesGcmAadUpdate_aesni( } /* Calculate number of blocks of AAD and the leftover. */ - blocks = aSz / AES_BLOCK_SIZE; - partial = aSz % AES_BLOCK_SIZE; + blocks = aSz / WC_AES_BLOCK_SIZE; + partial = aSz % WC_AES_BLOCK_SIZE; if (blocks > 0) { /* GHASH full blocks now. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { - AES_GCM_aad_update_avx2(a, blocks * AES_BLOCK_SIZE, + AES_GCM_aad_update_avx2(a, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H); } else #endif #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { - AES_GCM_aad_update_avx1(a, blocks * AES_BLOCK_SIZE, + AES_GCM_aad_update_avx1(a, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H); } else #endif { - AES_GCM_aad_update_aesni(a, blocks * AES_BLOCK_SIZE, + AES_GCM_aad_update_aesni(a, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H); } /* Skip over to end of AAD blocks. */ - a += blocks * AES_BLOCK_SIZE; + a += blocks * WC_AES_BLOCK_SIZE; } if (partial != 0) { /* Cache the partial block. */ @@ -9529,7 +9650,7 @@ static WARN_UNUSED_RESULT int AesGcmAadUpdate_aesni( /* No more AAD coming and we have a partial block. */ /* Fill the rest of the block with zeros. */ XMEMSET(AES_LASTGBLOCK(aes) + aes->aOver, 0, - AES_BLOCK_SIZE - aes->aOver); + (size_t)WC_AES_BLOCK_SIZE - aes->aOver); /* GHASH last AAD block. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -9587,7 +9708,7 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( aes->cSz += cSz; if (aes->cOver > 0) { /* Calculate amount we can use - fill up the block. */ - byte sz = AES_BLOCK_SIZE - aes->cOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->cOver); if (sz > cSz) { sz = (byte)cSz; } @@ -9595,8 +9716,8 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( xorbuf(AES_LASTGBLOCK(aes) + aes->cOver, p, sz); XMEMCPY(c, AES_LASTGBLOCK(aes) + aes->cOver, sz); /* Update count of unused encrypted counter. */ - aes->cOver += sz; - if (aes->cOver == AES_BLOCK_SIZE) { + aes->cOver = (byte)(aes->cOver + sz); + if (aes->cOver == WC_AES_BLOCK_SIZE) { /* We have filled up the block and can process. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -9626,14 +9747,14 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( } /* Calculate number of blocks of plaintext and the leftover. */ - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; if (blocks > 0) { /* Encrypt and GHASH full blocks now. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { AES_GCM_encrypt_update_avx2((byte*)aes->key, (int)aes->rounds, - c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + c, p, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } else @@ -9641,23 +9762,23 @@ static WARN_UNUSED_RESULT int AesGcmEncryptUpdate_aesni( #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { AES_GCM_encrypt_update_avx1((byte*)aes->key, (int)aes->rounds, - c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + c, p, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } else #endif { AES_GCM_encrypt_update_aesni((byte*)aes->key, (int)aes->rounds, - c, p, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + c, p, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } /* Skip over to end of blocks. */ - p += blocks * AES_BLOCK_SIZE; - c += blocks * AES_BLOCK_SIZE; + p += blocks * WC_AES_BLOCK_SIZE; + c += blocks * WC_AES_BLOCK_SIZE; } if (partial != 0) { /* Encrypt the counter - XOR in zeros as proxy for plaintext. */ - XMEMSET(AES_LASTGBLOCK(aes), 0, AES_BLOCK_SIZE); + XMEMSET(AES_LASTGBLOCK(aes), 0, WC_AES_BLOCK_SIZE); #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { AES_GCM_encrypt_block_avx2((byte*)aes->key, (int)aes->rounds, @@ -9711,7 +9832,7 @@ static WARN_UNUSED_RESULT int AesGcmEncryptFinal_aesni( } if (over > 0) { /* Fill the rest of the block with zeros. */ - XMEMSET(AES_LASTGBLOCK(aes) + over, 0, AES_BLOCK_SIZE - over); + XMEMSET(AES_LASTGBLOCK(aes) + over, 0, (size_t)WC_AES_BLOCK_SIZE - over); /* GHASH last cipher block. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -9818,7 +9939,7 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( aes->cSz += cSz; if (aes->cOver > 0) { /* Calculate amount we can use - fill up the block. */ - byte sz = AES_BLOCK_SIZE - aes->cOver; + byte sz = (byte)(WC_AES_BLOCK_SIZE - aes->cOver); if (sz > cSz) { sz = (byte)cSz; } @@ -9828,8 +9949,8 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( xorbuf(AES_LASTGBLOCK(aes) + aes->cOver, c, sz); XMEMCPY(p, AES_LASTGBLOCK(aes) + aes->cOver, sz); /* Update count of unused encrypted counter. */ - aes->cOver += sz; - if (aes->cOver == AES_BLOCK_SIZE) { + aes->cOver = (byte)(aes->cOver + sz); + if (aes->cOver == WC_AES_BLOCK_SIZE) { /* We have filled up the block and can process. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -9859,14 +9980,14 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( } /* Calculate number of blocks of plaintext and the leftover. */ - blocks = cSz / AES_BLOCK_SIZE; - partial = cSz % AES_BLOCK_SIZE; + blocks = cSz / WC_AES_BLOCK_SIZE; + partial = cSz % WC_AES_BLOCK_SIZE; if (blocks > 0) { /* Decrypt and GHASH full blocks now. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { AES_GCM_decrypt_update_avx2((byte*)aes->key, (int)aes->rounds, - p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + p, c, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } else @@ -9874,23 +9995,23 @@ static WARN_UNUSED_RESULT int AesGcmDecryptUpdate_aesni( #ifdef HAVE_INTEL_AVX1 if (IS_INTEL_AVX1(intel_flags)) { AES_GCM_decrypt_update_avx1((byte*)aes->key, (int)aes->rounds, - p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + p, c, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } else #endif { AES_GCM_decrypt_update_aesni((byte*)aes->key, (int)aes->rounds, - p, c, blocks * AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, + p, c, blocks * WC_AES_BLOCK_SIZE, AES_TAG(aes), aes->gcm.H, AES_COUNTER(aes)); } /* Skip over to end of blocks. */ - c += blocks * AES_BLOCK_SIZE; - p += blocks * AES_BLOCK_SIZE; + c += blocks * WC_AES_BLOCK_SIZE; + p += blocks * WC_AES_BLOCK_SIZE; } if (partial != 0) { /* Encrypt the counter - XOR in zeros as proxy for cipher text. */ - XMEMSET(AES_LASTGBLOCK(aes), 0, AES_BLOCK_SIZE); + XMEMSET(AES_LASTGBLOCK(aes), 0, WC_AES_BLOCK_SIZE); #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { AES_GCM_encrypt_block_avx2((byte*)aes->key, (int)aes->rounds, @@ -9951,7 +10072,7 @@ static WARN_UNUSED_RESULT int AesGcmDecryptFinal_aesni( } if (over > 0) { /* Zeroize the unused part of the block. */ - XMEMSET(lastBlock + over, 0, AES_BLOCK_SIZE - over); + XMEMSET(lastBlock + over, 0, (size_t)WC_AES_BLOCK_SIZE - over); /* Hash the last block of cipher text. */ #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { @@ -10029,7 +10150,7 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_AESNI) if ((ret == 0) && (aes->streamData == NULL)) { /* Allocate buffers for streaming. */ - aes->streamData_sz = 5 * AES_BLOCK_SIZE; + aes->streamData_sz = 5 * WC_AES_BLOCK_SIZE; aes->streamData = (byte*)XMALLOC(aes->streamData_sz, aes->heap, DYNAMIC_TYPE_AES); if (aes->streamData == NULL) { @@ -10045,7 +10166,7 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, if (ret == 0) { /* Set the IV passed in if it is smaller than a block. */ - if ((iv != NULL) && (ivSz <= AES_BLOCK_SIZE)) { + if ((iv != NULL) && (ivSz <= WC_AES_BLOCK_SIZE)) { XMEMMOVE((byte*)aes->reg, iv, ivSz); aes->nonceSz = ivSz; } @@ -10066,7 +10187,20 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, RESTORE_VECTOR_REGISTERS(); } else - #endif + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_GCM_init_AARCH64(aes, iv, ivSz); + + /* Reset state fields. */ + aes->over = 0; + aes->aSz = 0; + aes->cSz = 0; + /* Initialization for GHASH. */ + GHASH_INIT(aes); + } + else + #endif /* WOLFSSL_AESNI */ { ret = AesGcmInit_C(aes, iv, ivSz); } @@ -10192,6 +10326,13 @@ int wc_AesGcmEncryptUpdate(Aes* aes, byte* out, const byte* in, word32 sz, RESTORE_VECTOR_REGISTERS(); } else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_GCM_crypt_update_AARCH64(aes, out, in, sz); + GHASH_UPDATE_AARCH64(aes, authIn, authInSz, out, sz); + } + else #endif { /* Encrypt the plaintext. */ @@ -10222,7 +10363,7 @@ int wc_AesGcmEncryptFinal(Aes* aes, byte* authTag, word32 authTagSz) int ret = 0; /* Check validity of parameters. */ - if ((aes == NULL) || (authTag == NULL) || (authTagSz > AES_BLOCK_SIZE) || + if ((aes == NULL) || (authTag == NULL) || (authTagSz > WC_AES_BLOCK_SIZE) || (authTagSz == 0)) { ret = BAD_FUNC_ARG; } @@ -10245,6 +10386,12 @@ int wc_AesGcmEncryptFinal(Aes* aes, byte* authTag, word32 authTagSz) RESTORE_VECTOR_REGISTERS(); } else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_GCM_final_AARCH64(aes, authTag, authTagSz); + } + else #endif { ret = AesGcmFinal_C(aes, authTag, authTagSz); @@ -10328,6 +10475,13 @@ int wc_AesGcmDecryptUpdate(Aes* aes, byte* out, const byte* in, word32 sz, RESTORE_VECTOR_REGISTERS(); } else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + GHASH_UPDATE_AARCH64(aes, authIn, authInSz, in, sz); + AES_GCM_crypt_update_AARCH64(aes, out, in, sz); + } + else #endif { /* Update the authentication tag with any authentication data and @@ -10356,7 +10510,7 @@ int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, word32 authTagSz) int ret = 0; /* Check validity of parameters. */ - if ((aes == NULL) || (authTag == NULL) || (authTagSz > AES_BLOCK_SIZE) || + if ((aes == NULL) || (authTag == NULL) || (authTagSz > WC_AES_BLOCK_SIZE) || (authTagSz == 0)) { ret = BAD_FUNC_ARG; } @@ -10379,9 +10533,20 @@ int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, word32 authTagSz) RESTORE_VECTOR_REGISTERS(); } else + #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + ALIGN32 byte calcTag[WC_AES_BLOCK_SIZE]; + AES_GCM_final_AARCH64(aes, calcTag, authTagSz); + /* Check calculated tag matches the one passed in. */ + if (ConstantCompare(authTag, calcTag, (int)authTagSz) != 0) { + ret = AES_GCM_AUTH_E; + } + } + else #endif { - ALIGN32 byte calcTag[AES_BLOCK_SIZE]; + ALIGN32 byte calcTag[WC_AES_BLOCK_SIZE]; /* Calculate authentication tag. */ ret = AesGcmFinal_C(aes, calcTag, authTagSz); if (ret == 0) { @@ -10567,7 +10732,7 @@ int wc_GmacVerify(const byte* key, word32 keySz, #endif if (key == NULL || iv == NULL || (authIn == NULL && authInSz != 0) || - authTag == NULL || authTagSz == 0 || authTagSz > AES_BLOCK_SIZE) { + authTag == NULL || authTagSz == 0 || authTagSz > WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } @@ -10655,8 +10820,8 @@ int wc_AesCcmCheckTagSize(int sz) return 0; } -#ifdef WOLFSSL_ARMASM - /* implementation located in wolfcrypt/src/port/arm/armv8-aes.c */ +#if defined(WOLFSSL_ARMASM) && !defined(__aarch64__) + /* implemented in wolfcrypt/src/port/arm/rmv8-aes.c */ #elif defined(WOLFSSL_RISCV_ASM) /* implementation located in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ @@ -10786,10 +10951,10 @@ static WARN_UNUSED_RESULT int roll_x( int ret; /* process the bulk of the data */ - while (inSz >= AES_BLOCK_SIZE) { - xorbuf(out, in, AES_BLOCK_SIZE); - in += AES_BLOCK_SIZE; - inSz -= AES_BLOCK_SIZE; + while (inSz >= WC_AES_BLOCK_SIZE) { + xorbuf(out, in, WC_AES_BLOCK_SIZE); + in += WC_AES_BLOCK_SIZE; + inSz -= WC_AES_BLOCK_SIZE; ret = wc_AesEncrypt(aes, out, out); if (ret != 0) @@ -10835,7 +11000,7 @@ static WARN_UNUSED_RESULT int roll_auth( */ /* start fill out the rest of the first block */ - remainder = AES_BLOCK_SIZE - authLenSz; + remainder = WC_AES_BLOCK_SIZE - authLenSz; if (inSz >= remainder) { /* plenty of bulk data to fill the remainder of this block */ xorbuf(out + authLenSz, in, remainder); @@ -10862,7 +11027,7 @@ static WC_INLINE void AesCcmCtrInc(byte* B, word32 lenSz) word32 i; for (i = 0; i < lenSz; i++) { - if (++B[AES_BLOCK_SIZE - 1 - i] != 0) return; + if (++B[WC_AES_BLOCK_SIZE - 1 - i] != 0) return; } } @@ -10872,23 +11037,23 @@ static WC_INLINE void AesCcmCtrIncSet4(byte* B, word32 lenSz) word32 i; /* B+1 = B */ - XMEMCPY(B + AES_BLOCK_SIZE * 1, B, AES_BLOCK_SIZE); + XMEMCPY(B + WC_AES_BLOCK_SIZE * 1, B, WC_AES_BLOCK_SIZE); /* B+2,B+3 = B,B+1 */ - XMEMCPY(B + AES_BLOCK_SIZE * 2, B, AES_BLOCK_SIZE * 2); + XMEMCPY(B + WC_AES_BLOCK_SIZE * 2, B, WC_AES_BLOCK_SIZE * 2); for (i = 0; i < lenSz; i++) { - if (++B[AES_BLOCK_SIZE * 2 - 1 - i] != 0) break; + if (++B[WC_AES_BLOCK_SIZE * 2 - 1 - i] != 0) break; } - B[AES_BLOCK_SIZE * 3 - 1] += 2; - if (B[AES_BLOCK_SIZE * 3 - 1] < 2) { + B[WC_AES_BLOCK_SIZE * 3 - 1] = (byte)(B[WC_AES_BLOCK_SIZE * 3 - 1] + 2U); + if (B[WC_AES_BLOCK_SIZE * 3 - 1] < 2U) { for (i = 1; i < lenSz; i++) { - if (++B[AES_BLOCK_SIZE * 3 - 1 - i] != 0) break; + if (++B[WC_AES_BLOCK_SIZE * 3 - 1 - i] != 0) break; } } - B[AES_BLOCK_SIZE * 4 - 1] += 3; - if (B[AES_BLOCK_SIZE * 4 - 1] < 3) { + B[WC_AES_BLOCK_SIZE * 4 - 1] = (byte)(B[WC_AES_BLOCK_SIZE * 4 - 1] + 3U); + if (B[WC_AES_BLOCK_SIZE * 4 - 1] < 3U) { for (i = 1; i < lenSz; i++) { - if (++B[AES_BLOCK_SIZE * 4 - 1 - i] != 0) break; + if (++B[WC_AES_BLOCK_SIZE * 4 - 1 - i] != 0) break; } } } @@ -10897,10 +11062,10 @@ static WC_INLINE void AesCcmCtrInc4(byte* B, word32 lenSz) { word32 i; - B[AES_BLOCK_SIZE - 1] += 4; - if (B[AES_BLOCK_SIZE - 1] < 4) { + B[WC_AES_BLOCK_SIZE - 1] = (byte)(B[WC_AES_BLOCK_SIZE - 1] + 4U); + if (B[WC_AES_BLOCK_SIZE - 1] < 4U) { for (i = 1; i < lenSz; i++) { - if (++B[AES_BLOCK_SIZE - 1 - i] != 0) break; + if (++B[WC_AES_BLOCK_SIZE - 1 - i] != 0) break; } } } @@ -10914,11 +11079,11 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, const byte* authIn, word32 authInSz) { #ifdef WOLFSSL_AESNI - ALIGN128 byte A[AES_BLOCK_SIZE * 4]; - ALIGN128 byte B[AES_BLOCK_SIZE * 4]; + ALIGN128 byte A[WC_AES_BLOCK_SIZE * 4]; + ALIGN128 byte B[WC_AES_BLOCK_SIZE * 4]; #else - byte A[AES_BLOCK_SIZE]; - byte B[AES_BLOCK_SIZE]; + byte A[WC_AES_BLOCK_SIZE]; + byte B[WC_AES_BLOCK_SIZE]; #endif byte lenSz; word32 i; @@ -10929,7 +11094,7 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, /* sanity check on arguments */ if (aes == NULL || (inSz != 0 && (in == NULL || out == NULL)) || nonce == NULL || authTag == NULL || nonceSz < 7 || nonceSz > 13 || - authTagSz > AES_BLOCK_SIZE) + authTagSz > WC_AES_BLOCK_SIZE) return BAD_FUNC_ARG; /* Sanity check on authIn to prevent segfault in xorbuf() where @@ -10958,14 +11123,14 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, XMEMSET(A, 0, sizeof(A)); XMEMCPY(B+1, nonce, nonceSz); - lenSz = AES_BLOCK_SIZE - 1 - (byte)nonceSz; + lenSz = (byte)(WC_AES_BLOCK_SIZE - 1U - nonceSz); B[0] = (byte)((authInSz > 0 ? 64 : 0) + (8 * (((byte)authTagSz - 2) / 2)) + (lenSz - 1)); for (i = 0; i < lenSz; i++) { if (mask && i >= wordSz) mask = 0x00; - B[AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); + B[WC_AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); } #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -10988,9 +11153,9 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, if (ret == 0) { XMEMCPY(authTag, A, authTagSz); - B[0] = lenSz - 1; + B[0] = (byte)(lenSz - 1U); for (i = 0; i < lenSz; i++) - B[AES_BLOCK_SIZE - 1 - i] = 0; + B[WC_AES_BLOCK_SIZE - 1 - i] = 0; ret = wc_AesEncrypt(aes, B, A); } @@ -11000,35 +11165,35 @@ int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, } #ifdef WOLFSSL_AESNI if ((ret == 0) && aes->use_aesni) { - while (inSz >= AES_BLOCK_SIZE * 4) { + while (inSz >= WC_AES_BLOCK_SIZE * 4) { AesCcmCtrIncSet4(B, lenSz); - AES_ECB_encrypt_AESNI(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key, + AES_ECB_encrypt_AESNI(B, A, WC_AES_BLOCK_SIZE * 4, (byte*)aes->key, (int)aes->rounds); - xorbuf(A, in, AES_BLOCK_SIZE * 4); - XMEMCPY(out, A, AES_BLOCK_SIZE * 4); + xorbuf(A, in, WC_AES_BLOCK_SIZE * 4); + XMEMCPY(out, A, WC_AES_BLOCK_SIZE * 4); - inSz -= AES_BLOCK_SIZE * 4; - in += AES_BLOCK_SIZE * 4; - out += AES_BLOCK_SIZE * 4; + inSz -= WC_AES_BLOCK_SIZE * 4; + in += WC_AES_BLOCK_SIZE * 4; + out += WC_AES_BLOCK_SIZE * 4; AesCcmCtrInc4(B, lenSz); } } #endif if (ret == 0) { - while (inSz >= AES_BLOCK_SIZE) { + while (inSz >= WC_AES_BLOCK_SIZE) { ret = wc_AesEncrypt(aes, B, A); if (ret != 0) break; - xorbuf(A, in, AES_BLOCK_SIZE); - XMEMCPY(out, A, AES_BLOCK_SIZE); + xorbuf(A, in, WC_AES_BLOCK_SIZE); + XMEMCPY(out, A, WC_AES_BLOCK_SIZE); AesCcmCtrInc(B, lenSz); - inSz -= AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + inSz -= WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } } if ((ret == 0) && (inSz > 0)) { @@ -11060,11 +11225,11 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, const byte* authIn, word32 authInSz) { #ifdef WOLFSSL_AESNI - ALIGN128 byte B[AES_BLOCK_SIZE * 4]; - ALIGN128 byte A[AES_BLOCK_SIZE * 4]; + ALIGN128 byte B[WC_AES_BLOCK_SIZE * 4]; + ALIGN128 byte A[WC_AES_BLOCK_SIZE * 4]; #else - byte A[AES_BLOCK_SIZE]; - byte B[AES_BLOCK_SIZE]; + byte A[WC_AES_BLOCK_SIZE]; + byte B[WC_AES_BLOCK_SIZE]; #endif byte* o; byte lenSz; @@ -11076,7 +11241,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, /* sanity check on arguments */ if (aes == NULL || (inSz != 0 && (in == NULL || out == NULL)) || nonce == NULL || authTag == NULL || nonceSz < 7 || nonceSz > 13 || - authTagSz > AES_BLOCK_SIZE) + authTagSz > WC_AES_BLOCK_SIZE) return BAD_FUNC_ARG; /* Sanity check on authIn to prevent segfault in xorbuf() where @@ -11107,11 +11272,11 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, oSz = inSz; XMEMSET(A, 0, sizeof A); XMEMCPY(B+1, nonce, nonceSz); - lenSz = AES_BLOCK_SIZE - 1 - (byte)nonceSz; + lenSz = (byte)(WC_AES_BLOCK_SIZE - 1U - nonceSz); - B[0] = lenSz - 1; + B[0] = (byte)(lenSz - 1U); for (i = 0; i < lenSz; i++) - B[AES_BLOCK_SIZE - 1 - i] = 0; + B[WC_AES_BLOCK_SIZE - 1 - i] = 0; B[15] = 1; #ifdef WOLFSSL_CHECK_MEM_ZERO @@ -11123,34 +11288,34 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, #ifdef WOLFSSL_AESNI if (aes->use_aesni) { - while (oSz >= AES_BLOCK_SIZE * 4) { + while (oSz >= WC_AES_BLOCK_SIZE * 4) { AesCcmCtrIncSet4(B, lenSz); - AES_ECB_encrypt_AESNI(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key, + AES_ECB_encrypt_AESNI(B, A, WC_AES_BLOCK_SIZE * 4, (byte*)aes->key, (int)aes->rounds); - xorbuf(A, in, AES_BLOCK_SIZE * 4); - XMEMCPY(o, A, AES_BLOCK_SIZE * 4); + xorbuf(A, in, WC_AES_BLOCK_SIZE * 4); + XMEMCPY(o, A, WC_AES_BLOCK_SIZE * 4); - oSz -= AES_BLOCK_SIZE * 4; - in += AES_BLOCK_SIZE * 4; - o += AES_BLOCK_SIZE * 4; + oSz -= WC_AES_BLOCK_SIZE * 4; + in += WC_AES_BLOCK_SIZE * 4; + o += WC_AES_BLOCK_SIZE * 4; AesCcmCtrInc4(B, lenSz); } } #endif - while (oSz >= AES_BLOCK_SIZE) { + while (oSz >= WC_AES_BLOCK_SIZE) { ret = wc_AesEncrypt(aes, B, A); if (ret != 0) break; - xorbuf(A, in, AES_BLOCK_SIZE); - XMEMCPY(o, A, AES_BLOCK_SIZE); + xorbuf(A, in, WC_AES_BLOCK_SIZE); + XMEMCPY(o, A, WC_AES_BLOCK_SIZE); AesCcmCtrInc(B, lenSz); - oSz -= AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - o += AES_BLOCK_SIZE; + oSz -= WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + o += WC_AES_BLOCK_SIZE; } if ((ret == 0) && (inSz > 0)) @@ -11160,7 +11325,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, xorbuf(A, in, oSz); XMEMCPY(o, A, oSz); for (i = 0; i < lenSz; i++) - B[AES_BLOCK_SIZE - 1 - i] = 0; + B[WC_AES_BLOCK_SIZE - 1 - i] = 0; ret = wc_AesEncrypt(aes, B, A); } @@ -11174,7 +11339,7 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, for (i = 0; i < lenSz; i++) { if (mask && i >= wordSz) mask = 0x00; - B[AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); + B[WC_AES_BLOCK_SIZE - 1 - i] = (byte)((inSz >> ((8 * i) & mask)) & mask); } ret = wc_AesEncrypt(aes, B, A); @@ -11188,9 +11353,9 @@ int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, ret = roll_x(aes, o, oSz, A); if (ret == 0) { - B[0] = lenSz - 1; + B[0] = (byte)(lenSz - 1U); for (i = 0; i < lenSz; i++) - B[AES_BLOCK_SIZE - 1 - i] = 0; + B[WC_AES_BLOCK_SIZE - 1 - i] = 0; ret = wc_AesEncrypt(aes, B, B); } @@ -11664,6 +11829,12 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( AES_ECB_encrypt_AESNI(in, out, sz, (byte*)aes->key, (int)aes->rounds); } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_encrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + } + else #endif { #ifdef NEED_AES_TABLES @@ -11671,12 +11842,12 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( #else word32 i; - for (i = 0; i < sz; i += AES_BLOCK_SIZE) { + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { ret = wc_AesEncryptDirect(aes, out, in); if (ret != 0) break; - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } #endif } @@ -11716,6 +11887,12 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( AES_ECB_decrypt_AESNI(in, out, sz, (byte*)aes->key, (int)aes->rounds); } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_decrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + } + else #endif { #ifdef NEED_AES_TABLES @@ -11723,12 +11900,12 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( #else word32 i; - for (i = 0; i < sz; i += AES_BLOCK_SIZE) { + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { ret = wc_AesDecryptDirect(aes, out, in); if (ret != 0) break; - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; } #endif } @@ -11743,7 +11920,7 @@ int wc_AesEcbEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { if ((in == NULL) || (out == NULL) || (aes == NULL)) return BAD_FUNC_ARG; - if ((sz % AES_BLOCK_SIZE) != 0) { + if ((sz % WC_AES_BLOCK_SIZE) != 0) { return BAD_LENGTH_E; } @@ -11755,7 +11932,7 @@ int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { if ((in == NULL) || (out == NULL) || (aes == NULL)) return BAD_FUNC_ARG; - if ((sz % AES_BLOCK_SIZE) != 0) { + if ((sz % WC_AES_BLOCK_SIZE) != 0) { return BAD_LENGTH_E; } @@ -11791,10 +11968,10 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( /* consume any unused bytes left in aes->tmp */ processed = min(aes->left, sz); - xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, processed); + xorbufout(out, in, (byte*)aes->tmp + WC_AES_BLOCK_SIZE - aes->left, processed); #ifdef WOLFSSL_AES_CFB if (mode == AES_CFB_MODE) { - XMEMCPY((byte*)aes->reg + AES_BLOCK_SIZE - aes->left, out, processed); + XMEMCPY((byte*)aes->reg + WC_AES_BLOCK_SIZE - aes->left, out, processed); } #endif aes->left -= processed; @@ -11804,26 +11981,26 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( VECTOR_REGISTERS_PUSH; - while (sz >= AES_BLOCK_SIZE) { + while (sz >= WC_AES_BLOCK_SIZE) { /* Using aes->tmp here for inline case i.e. in=out */ ret = wc_AesEncryptDirect(aes, (byte*)aes->tmp, (byte*)aes->reg); if (ret != 0) break; #ifdef WOLFSSL_AES_OFB if (mode == AES_OFB_MODE) { - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); } #endif - xorbuf((byte*)aes->tmp, in, AES_BLOCK_SIZE); + xorbuf((byte*)aes->tmp, in, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CFB if (mode == AES_CFB_MODE) { - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); } #endif - XMEMCPY(out, aes->tmp, AES_BLOCK_SIZE); - out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + XMEMCPY(out, aes->tmp, WC_AES_BLOCK_SIZE); + out += WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; aes->left = 0; } @@ -11832,11 +12009,11 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackEncrypt( ret = wc_AesEncryptDirect(aes, (byte*)aes->tmp, (byte*)aes->reg); } if ((ret == 0) && sz) { - aes->left = AES_BLOCK_SIZE; + aes->left = WC_AES_BLOCK_SIZE; tmp = (byte*)aes->tmp; #ifdef WOLFSSL_AES_OFB if (mode == AES_OFB_MODE) { - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); } #endif @@ -11881,13 +12058,14 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( /* check if more input needs copied over to aes->reg */ if (aes->left && sz && mode == AES_CFB_MODE) { word32 size = min(aes->left, sz); - XMEMCPY((byte*)aes->reg + AES_BLOCK_SIZE - aes->left, in, size); + XMEMCPY((byte*)aes->reg + WC_AES_BLOCK_SIZE - aes->left, in, size); } #endif /* consume any unused bytes left in aes->tmp */ processed = min(aes->left, sz); - xorbufout(out, in, (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left, processed); + xorbufout(out, in, (byte*)aes->tmp + WC_AES_BLOCK_SIZE - aes->left, + processed); aes->left -= processed; out += processed; in += processed; @@ -11895,26 +12073,26 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( VECTOR_REGISTERS_PUSH; - while (sz > AES_BLOCK_SIZE) { + while (sz > WC_AES_BLOCK_SIZE) { /* Using aes->tmp here for inline case i.e. in=out */ ret = wc_AesEncryptDirect(aes, (byte*)aes->tmp, (byte*)aes->reg); if (ret != 0) break; #ifdef WOLFSSL_AES_OFB if (mode == AES_OFB_MODE) { - XMEMCPY((byte*)aes->reg, (byte*)aes->tmp, AES_BLOCK_SIZE); + XMEMCPY((byte*)aes->reg, (byte*)aes->tmp, WC_AES_BLOCK_SIZE); } #endif - xorbuf((byte*)aes->tmp, in, AES_BLOCK_SIZE); + xorbuf((byte*)aes->tmp, in, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_AES_CFB if (mode == AES_CFB_MODE) { - XMEMCPY(aes->reg, in, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, in, WC_AES_BLOCK_SIZE); } #endif - XMEMCPY(out, (byte*)aes->tmp, AES_BLOCK_SIZE); - out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + XMEMCPY(out, (byte*)aes->tmp, WC_AES_BLOCK_SIZE); + out += WC_AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; aes->left = 0; } @@ -11930,11 +12108,11 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackDecrypt( #endif #ifdef WOLFSSL_AES_OFB if (mode == AES_OFB_MODE) { - XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE); + XMEMCPY(aes->reg, aes->tmp, WC_AES_BLOCK_SIZE); } #endif - aes->left = AES_BLOCK_SIZE - sz; + aes->left = WC_AES_BLOCK_SIZE - sz; xorbufout(out, in, aes->tmp, sz); } @@ -11981,27 +12159,27 @@ int wc_AesCfbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) } #endif /* HAVE_AES_DECRYPT */ - -/* shift the whole AES_BLOCK_SIZE array left by 8 or 1 bits */ +#ifndef WOLFSSL_NO_AES_CFB_1_8 +/* shift the whole WC_AES_BLOCK_SIZE array left by 8 or 1 bits */ static void shiftLeftArray(byte* ary, byte shift) { int i; if (shift == WOLFSSL_BIT_SIZE) { /* shifting over by 8 bits */ - for (i = 0; i < AES_BLOCK_SIZE - 1; i++) { + for (i = 0; i < WC_AES_BLOCK_SIZE - 1; i++) { ary[i] = ary[i+1]; } ary[i] = 0; } else { /* shifting over by 7 or less bits */ - for (i = 0; i < AES_BLOCK_SIZE - 1; i++) { - byte carry = ary[i+1] & (0XFF << (WOLFSSL_BIT_SIZE - shift)); - carry >>= (WOLFSSL_BIT_SIZE - shift); + for (i = 0; i < WC_AES_BLOCK_SIZE - 1; i++) { + byte carry = (byte)(ary[i+1] & (0XFF << (WOLFSSL_BIT_SIZE - shift))); + carry = (byte)(carry >> (WOLFSSL_BIT_SIZE - shift)); ary[i] = (byte)((ary[i] << shift) + carry); } - ary[i] = ary[i] << shift; + ary[i] = (byte)(ary[i] << shift); } } @@ -12032,12 +12210,12 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB8( /* LSB + CAT */ shiftLeftArray(pt, WOLFSSL_BIT_SIZE); - pt[AES_BLOCK_SIZE - 1] = in[0]; + pt[WC_AES_BLOCK_SIZE - 1] = in[0]; } /* MSB + XOR */ #ifdef BIG_ENDIAN_ORDER - ByteReverseWords(aes->tmp, aes->tmp, AES_BLOCK_SIZE); + ByteReverseWords(aes->tmp, aes->tmp, WC_AES_BLOCK_SIZE); #endif out[0] = (byte)(aes->tmp[0] ^ in[0]); if (dir == AES_ENCRYPTION) { @@ -12045,7 +12223,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB8( /* LSB + CAT */ shiftLeftArray(pt, WOLFSSL_BIT_SIZE); - pt[AES_BLOCK_SIZE - 1] = out[0]; + pt[WC_AES_BLOCK_SIZE - 1] = out[0]; } out += 1; @@ -12087,19 +12265,19 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB1( pt = (byte*)aes->reg; /* LSB + CAT */ - tmp = (0X01 << bit) & in[0]; - tmp = tmp >> bit; + tmp = (byte)((0X01U << bit) & in[0]); + tmp = (byte)(tmp >> bit); tmp &= 0x01; shiftLeftArray((byte*)aes->reg, 1); - pt[AES_BLOCK_SIZE - 1] |= tmp; + pt[WC_AES_BLOCK_SIZE - 1] |= tmp; } /* MSB + XOR */ - tmp = (0X01 << bit) & in[0]; + tmp = (byte)((0X01U << bit) & in[0]); pt = (byte*)aes->tmp; - tmp = (pt[0] >> 7) ^ (tmp >> bit); + tmp = (byte)((pt[0] >> 7) ^ (tmp >> bit)); tmp &= 0x01; - cur |= (tmp << bit); + cur = (byte)(cur | (tmp << bit)); if (dir == AES_ENCRYPTION) { @@ -12107,7 +12285,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB1( /* LSB + CAT */ shiftLeftArray((byte*)aes->reg, 1); - pt[AES_BLOCK_SIZE - 1] |= tmp; + pt[WC_AES_BLOCK_SIZE - 1] |= tmp; } bit--; @@ -12116,7 +12294,7 @@ static WARN_UNUSED_RESULT int wc_AesFeedbackCFB1( out += 1; in += 1; sz -= 1; - bit = 7; + bit = 7U; cur = 0; } else { @@ -12199,6 +12377,7 @@ int wc_AesCfb8Decrypt(Aes* aes, byte* out, const byte* in, word32 sz) return wc_AesFeedbackCFB8(aes, out, in, sz, AES_DECRYPTION); } #endif /* HAVE_AES_DECRYPT */ +#endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #endif /* WOLFSSL_AES_CFB */ #ifdef WOLFSSL_AES_OFB @@ -12286,7 +12465,7 @@ int wc_AesKeyWrap_ex(Aes *aes, const byte* in, word32 inSz, byte* out, int ret = 0; byte t[KEYWRAP_BLOCK_SIZE]; - byte tmp[AES_BLOCK_SIZE]; + byte tmp[WC_AES_BLOCK_SIZE]; /* n must be at least 2 64-bit blocks, output size is (n + 1) 8 bytes (64-bit) */ if (aes == NULL || in == NULL || inSz < 2*KEYWRAP_BLOCK_SIZE || @@ -12394,7 +12573,7 @@ int wc_AesKeyUnWrap_ex(Aes *aes, const byte* in, word32 inSz, byte* out, int ret = 0; byte t[KEYWRAP_BLOCK_SIZE]; - byte tmp[AES_BLOCK_SIZE]; + byte tmp[WC_AES_BLOCK_SIZE]; const byte* expIv; const byte defaultIV[] = { @@ -12715,16 +12894,16 @@ int wc_AesXtsEncryptSector(XtsAes* aes, byte* out, const byte* in, word32 sz, word64 sector) { byte* pt; - byte i[AES_BLOCK_SIZE]; + byte i[WC_AES_BLOCK_SIZE]; - XMEMSET(i, 0, AES_BLOCK_SIZE); + XMEMSET(i, 0, WC_AES_BLOCK_SIZE); #ifdef BIG_ENDIAN_ORDER sector = ByteReverseWord64(sector); #endif pt = (byte*)§or; XMEMCPY(i, pt, sizeof(word64)); - return wc_AesXtsEncrypt(aes, out, in, sz, (const byte*)i, AES_BLOCK_SIZE); + return wc_AesXtsEncrypt(aes, out, in, sz, (const byte*)i, WC_AES_BLOCK_SIZE); } @@ -12743,16 +12922,16 @@ int wc_AesXtsDecryptSector(XtsAes* aes, byte* out, const byte* in, word32 sz, word64 sector) { byte* pt; - byte i[AES_BLOCK_SIZE]; + byte i[WC_AES_BLOCK_SIZE]; - XMEMSET(i, 0, AES_BLOCK_SIZE); + XMEMSET(i, 0, WC_AES_BLOCK_SIZE); #ifdef BIG_ENDIAN_ORDER sector = ByteReverseWord64(sector); #endif pt = (byte*)§or; XMEMCPY(i, pt, sizeof(word64)); - return wc_AesXtsDecrypt(aes, out, in, sz, (const byte*)i, AES_BLOCK_SIZE); + return wc_AesXtsDecrypt(aes, out, in, sz, (const byte*)i, WC_AES_BLOCK_SIZE); } #ifdef WOLFSSL_AESNI @@ -12816,35 +12995,36 @@ void AES_XTS_decrypt_update_avx1(const unsigned char *in, unsigned char *out, wo #endif /* WOLFSSL_AESNI */ -#if !defined(WOLFSSL_ARMASM) || defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) +#if !defined(WOLFSSL_ARMASM) || defined(__aarch64__) || \ + defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) #ifdef HAVE_AES_ECB /* helper function for encrypting / decrypting full buffer at once */ static WARN_UNUSED_RESULT int _AesXtsHelper( Aes* aes, byte* out, const byte* in, word32 sz, int dir) { word32 outSz = sz; - word32 totalSz = (sz / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; /* total bytes */ + word32 totalSz = (sz / WC_AES_BLOCK_SIZE) * WC_AES_BLOCK_SIZE; /* total bytes */ byte* pt = out; - outSz -= AES_BLOCK_SIZE; + outSz -= WC_AES_BLOCK_SIZE; while (outSz > 0) { word32 j; byte carry = 0; /* multiply by shift left and propagate carry */ - for (j = 0; j < AES_BLOCK_SIZE && outSz > 0; j++, outSz--) { + for (j = 0; j < WC_AES_BLOCK_SIZE && outSz > 0; j++, outSz--) { byte tmpC; tmpC = (pt[j] >> 7) & 0x01; - pt[j+AES_BLOCK_SIZE] = (byte)((pt[j] << 1) + carry); + pt[j+WC_AES_BLOCK_SIZE] = (byte)((pt[j] << 1) + carry); carry = tmpC; } if (carry) { - pt[AES_BLOCK_SIZE] ^= GF_XTS; + pt[WC_AES_BLOCK_SIZE] ^= GF_XTS; } - pt += AES_BLOCK_SIZE; + pt += WC_AES_BLOCK_SIZE; } xorbuf(out, in, totalSz); @@ -12885,7 +13065,7 @@ static int AesXtsEncrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, const byte* i) { int ret; - byte tweak_block[AES_BLOCK_SIZE]; + byte tweak_block[WC_AES_BLOCK_SIZE]; ret = wc_AesEncryptDirect(&xaes->tweak, tweak_block, i); if (ret != 0) @@ -12927,13 +13107,13 @@ static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, byte *i) { int ret = 0; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); Aes *aes = &xaes->aes; #ifdef HAVE_AES_ECB /* encrypt all of buffer at once when possible */ if (in != out) { /* can not handle inline */ - XMEMCPY(out, i, AES_BLOCK_SIZE); + XMEMCPY(out, i, WC_AES_BLOCK_SIZE); if ((ret = _AesXtsHelper(aes, out, in, sz, AES_ENCRYPTION)) != 0) return ret; } @@ -12947,18 +13127,18 @@ static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, if (in == out) #endif { /* check for if inline */ - byte buf[AES_BLOCK_SIZE]; + byte buf[WC_AES_BLOCK_SIZE]; - XMEMCPY(buf, in, AES_BLOCK_SIZE); - xorbuf(buf, i, AES_BLOCK_SIZE); + XMEMCPY(buf, in, WC_AES_BLOCK_SIZE); + xorbuf(buf, i, WC_AES_BLOCK_SIZE); ret = wc_AesEncryptDirect(aes, out, buf); if (ret != 0) return ret; } - xorbuf(out, i, AES_BLOCK_SIZE); + xorbuf(out, i, WC_AES_BLOCK_SIZE); /* multiply by shift left and propagate carry */ - for (j = 0; j < AES_BLOCK_SIZE; j++) { + for (j = 0; j < WC_AES_BLOCK_SIZE; j++) { byte tmpC; tmpC = (i[j] >> 7) & 0x01; @@ -12969,18 +13149,18 @@ static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, i[0] ^= GF_XTS; } - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; blocks--; } /* stealing operation of XTS to handle left overs */ if (sz > 0) { - byte buf[AES_BLOCK_SIZE]; + byte buf[WC_AES_BLOCK_SIZE]; - XMEMCPY(buf, out - AES_BLOCK_SIZE, AES_BLOCK_SIZE); - if (sz >= AES_BLOCK_SIZE) { /* extra sanity check before copy */ + XMEMCPY(buf, out - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); + if (sz >= WC_AES_BLOCK_SIZE) { /* extra sanity check before copy */ return BUFFER_E; } if (in != out) { @@ -12988,17 +13168,17 @@ static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, XMEMCPY(buf, in, sz); } else { - byte buf2[AES_BLOCK_SIZE]; + byte buf2[WC_AES_BLOCK_SIZE]; XMEMCPY(buf2, buf, sz); XMEMCPY(buf, in, sz); XMEMCPY(out, buf2, sz); } - xorbuf(buf, i, AES_BLOCK_SIZE); - ret = wc_AesEncryptDirect(aes, out - AES_BLOCK_SIZE, buf); + xorbuf(buf, i, WC_AES_BLOCK_SIZE); + ret = wc_AesEncryptDirect(aes, out - WC_AES_BLOCK_SIZE, buf); if (ret == 0) - xorbuf(out - AES_BLOCK_SIZE, i, AES_BLOCK_SIZE); + xorbuf(out - WC_AES_BLOCK_SIZE, i, WC_AES_BLOCK_SIZE); } return ret; @@ -13011,7 +13191,7 @@ static int AesXtsEncryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, * in input plain text buffer to encrypt * sz size of both out and in buffers * i value to use for tweak - * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * iSz size of i buffer, should always be WC_AES_BLOCK_SIZE but having this input * adds a sanity check on how the user calls the function. * * returns 0 on success @@ -13029,8 +13209,8 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, #if FIPS_VERSION3_GE(6,0,0) /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is - * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to - * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + * WC_AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of WC_AES_BLOCK_SIZE (16,777,216 bytes) */ if (sz > FIPS_AES_XTS_MAX_BYTES_PER_TWEAK) { WOLFSSL_MSG("Request exceeds allowed bytes per SP800-38E"); @@ -13045,11 +13225,11 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, return BAD_FUNC_ARG; } - if (iSz < AES_BLOCK_SIZE) { + if (iSz < WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Plain text input too small for encryption"); return BAD_FUNC_ARG; } @@ -13078,6 +13258,13 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, RESTORE_VECTOR_REGISTERS(); } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_XTS_encrypt_AARCH64(xaes, out, in, sz, i); + ret = 0; + } + else #endif { ret = AesXtsEncrypt_sw(xaes, out, in, sz, i); @@ -13093,7 +13280,7 @@ int wc_AesXtsEncrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, * * xaes AES keys to use for block encrypt/decrypt * i readwrite value to use for tweak - * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * iSz size of i buffer, should always be WC_AES_BLOCK_SIZE but having this input * adds a sanity check on how the user calls the function. * * returns 0 on success @@ -13109,7 +13296,7 @@ int wc_AesXtsEncryptInit(XtsAes* xaes, const byte* i, word32 iSz, return BAD_FUNC_ARG; } - if (iSz < AES_BLOCK_SIZE) { + if (iSz < WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } @@ -13120,7 +13307,7 @@ int wc_AesXtsEncryptInit(XtsAes* xaes, const byte* i, word32 iSz, return BAD_FUNC_ARG; } - XMEMCPY(stream->tweak_block, i, AES_BLOCK_SIZE); + XMEMCPY(stream->tweak_block, i, WC_AES_BLOCK_SIZE); stream->bytes_crypted_with_this_tweak = 0; { @@ -13156,16 +13343,16 @@ int wc_AesXtsEncryptInit(XtsAes* xaes, const byte* i, word32 iSz, /* Block-streaming AES-XTS * - * Note that sz must be >= AES_BLOCK_SIZE in each call, and must be a multiple - * of AES_BLOCK_SIZE in each call to wc_AesXtsEncryptUpdate(). - * wc_AesXtsEncryptFinal() can handle any length >= AES_BLOCK_SIZE. + * Note that sz must be >= WC_AES_BLOCK_SIZE in each call, and must be a multiple + * of WC_AES_BLOCK_SIZE in each call to wc_AesXtsEncryptUpdate(). + * wc_AesXtsEncryptFinal() can handle any length >= WC_AES_BLOCK_SIZE. * * xaes AES keys to use for block encrypt/decrypt * out output buffer to hold cipher text * in input plain text buffer to encrypt - * sz size of both out and in buffers -- must be >= AES_BLOCK_SIZE. + * sz size of both out and in buffers -- must be >= WC_AES_BLOCK_SIZE. * i value to use for tweak - * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * iSz size of i buffer, should always be WC_AES_BLOCK_SIZE but having this input * adds a sanity check on how the user calls the function. * * returns 0 on success @@ -13187,12 +13374,12 @@ static int AesXtsEncryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 s aes = &xaes->aes; #endif - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Plain text input too small for encryption"); return BAD_FUNC_ARG; } - if (stream->bytes_crypted_with_this_tweak & ((word32)AES_BLOCK_SIZE - 1U)) + if (stream->bytes_crypted_with_this_tweak & ((word32)WC_AES_BLOCK_SIZE - 1U)) { WOLFSSL_MSG("Call to AesXtsEncryptUpdate after previous finalizing call"); return BAD_FUNC_ARG; @@ -13204,8 +13391,8 @@ static int AesXtsEncryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 s #endif #if FIPS_VERSION3_GE(6,0,0) /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is - * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to - * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + * WC_AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of WC_AES_BLOCK_SIZE (16,777,216 bytes) */ if (stream->bytes_crypted_with_this_tweak > FIPS_AES_XTS_MAX_BYTES_PER_TWEAK) @@ -13252,7 +13439,7 @@ int wc_AesXtsEncryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, { if (stream == NULL) return BAD_FUNC_ARG; - if (sz & ((word32)AES_BLOCK_SIZE - 1U)) + if (sz & ((word32)WC_AES_BLOCK_SIZE - 1U)) return BAD_FUNC_ARG; return AesXtsEncryptUpdate(xaes, out, in, sz, stream); } @@ -13271,9 +13458,9 @@ int wc_AesXtsEncryptFinal(XtsAes* xaes, byte* out, const byte* in, word32 sz, * after finalization. */ stream->bytes_crypted_with_this_tweak |= 1U; - ForceZero(stream->tweak_block, AES_BLOCK_SIZE); + ForceZero(stream->tweak_block, WC_AES_BLOCK_SIZE); #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(stream->tweak_block, AES_BLOCK_SIZE); + wc_MemZero_Check(stream->tweak_block, WC_AES_BLOCK_SIZE); #endif return ret; } @@ -13300,7 +13487,7 @@ static int AesXtsDecrypt_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, const byte* i) { int ret; - byte tweak_block[AES_BLOCK_SIZE]; + byte tweak_block[WC_AES_BLOCK_SIZE]; ret = wc_AesEncryptDirect(&xaes->tweak, tweak_block, i); if (ret != 0) @@ -13329,7 +13516,7 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, word32 sz, byte *i) { int ret = 0; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); #ifdef WC_AES_XTS_SUPPORT_SIMULTANEOUS_ENC_AND_DEC_KEYS Aes *aes = &xaes->aes_decrypt; #else @@ -13337,7 +13524,7 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, #endif word32 j; byte carry = 0; - byte stl = (sz % AES_BLOCK_SIZE); + byte stl = (sz % WC_AES_BLOCK_SIZE); /* if Stealing then break out of loop one block early to handle special * case */ @@ -13348,7 +13535,7 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, #ifdef HAVE_AES_ECB /* decrypt all of buffer at once when possible */ if (in != out) { /* can not handle inline */ - XMEMCPY(out, i, AES_BLOCK_SIZE); + XMEMCPY(out, i, WC_AES_BLOCK_SIZE); if ((ret = _AesXtsHelper(aes, out, in, sz, AES_DECRYPTION)) != 0) return ret; } @@ -13359,18 +13546,18 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, if (in == out) #endif { /* check for if inline */ - byte buf[AES_BLOCK_SIZE]; + byte buf[WC_AES_BLOCK_SIZE]; - XMEMCPY(buf, in, AES_BLOCK_SIZE); - xorbuf(buf, i, AES_BLOCK_SIZE); + XMEMCPY(buf, in, WC_AES_BLOCK_SIZE); + xorbuf(buf, i, WC_AES_BLOCK_SIZE); ret = wc_AesDecryptDirect(aes, out, buf); if (ret != 0) return ret; } - xorbuf(out, i, AES_BLOCK_SIZE); + xorbuf(out, i, WC_AES_BLOCK_SIZE); /* multiply by shift left and propagate carry */ - for (j = 0; j < AES_BLOCK_SIZE; j++) { + for (j = 0; j < WC_AES_BLOCK_SIZE; j++) { byte tmpC; tmpC = (i[j] >> 7) & 0x01; @@ -13382,19 +13569,19 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, } carry = 0; - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; blocks--; } /* stealing operation of XTS to handle left overs */ - if (sz >= AES_BLOCK_SIZE) { - byte buf[AES_BLOCK_SIZE]; - byte tmp2[AES_BLOCK_SIZE]; + if (sz >= WC_AES_BLOCK_SIZE) { + byte buf[WC_AES_BLOCK_SIZE]; + byte tmp2[WC_AES_BLOCK_SIZE]; /* multiply by shift left and propagate carry */ - for (j = 0; j < AES_BLOCK_SIZE; j++) { + for (j = 0; j < WC_AES_BLOCK_SIZE; j++) { byte tmpC; tmpC = (i[j] >> 7) & 0x01; @@ -13405,33 +13592,33 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, tmp2[0] ^= GF_XTS; } - XMEMCPY(buf, in, AES_BLOCK_SIZE); - xorbuf(buf, tmp2, AES_BLOCK_SIZE); + XMEMCPY(buf, in, WC_AES_BLOCK_SIZE); + xorbuf(buf, tmp2, WC_AES_BLOCK_SIZE); ret = wc_AesDecryptDirect(aes, out, buf); if (ret != 0) return ret; - xorbuf(out, tmp2, AES_BLOCK_SIZE); + xorbuf(out, tmp2, WC_AES_BLOCK_SIZE); /* tmp2 holds partial | last */ - XMEMCPY(tmp2, out, AES_BLOCK_SIZE); - in += AES_BLOCK_SIZE; - out += AES_BLOCK_SIZE; - sz -= AES_BLOCK_SIZE; + XMEMCPY(tmp2, out, WC_AES_BLOCK_SIZE); + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + sz -= WC_AES_BLOCK_SIZE; /* Make buffer with end of cipher text | last */ - XMEMCPY(buf, tmp2, AES_BLOCK_SIZE); - if (sz >= AES_BLOCK_SIZE) { /* extra sanity check before copy */ + XMEMCPY(buf, tmp2, WC_AES_BLOCK_SIZE); + if (sz >= WC_AES_BLOCK_SIZE) { /* extra sanity check before copy */ return BUFFER_E; } XMEMCPY(buf, in, sz); XMEMCPY(out, tmp2, sz); - xorbuf(buf, i, AES_BLOCK_SIZE); + xorbuf(buf, i, WC_AES_BLOCK_SIZE); ret = wc_AesDecryptDirect(aes, tmp2, buf); if (ret != 0) return ret; - xorbuf(tmp2, i, AES_BLOCK_SIZE); - XMEMCPY(out - AES_BLOCK_SIZE, tmp2, AES_BLOCK_SIZE); + xorbuf(tmp2, i, WC_AES_BLOCK_SIZE); + XMEMCPY(out - WC_AES_BLOCK_SIZE, tmp2, WC_AES_BLOCK_SIZE); } return ret; @@ -13444,7 +13631,7 @@ static int AesXtsDecryptUpdate_sw(XtsAes* xaes, byte* out, const byte* in, * in input cipher text buffer to decrypt * sz size of both out and in buffers * i value to use for tweak - * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * iSz size of i buffer, should always be WC_AES_BLOCK_SIZE but having this input * adds a sanity check on how the user calls the function. * * returns 0 on success @@ -13466,10 +13653,10 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, #endif /* FIPS TODO: SP800-38E - Restrict data unit to 2^20 blocks per key. A block is - * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to - * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes or + * WC_AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of WC_AES_BLOCK_SIZE (16,777,216 bytes or * 134,217,728-bits) Add helpful printout and message along with BAD_FUNC_ARG - * return whenever sz / AES_BLOCK_SIZE > 1,048,576 or equal to that and sz is + * return whenever sz / WC_AES_BLOCK_SIZE > 1,048,576 or equal to that and sz is * not a sequence of complete blocks. */ @@ -13478,11 +13665,11 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, return BAD_FUNC_ARG; } - if (iSz < AES_BLOCK_SIZE) { + if (iSz < WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Cipher text input too small for decryption"); return BAD_FUNC_ARG; } @@ -13511,6 +13698,13 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, RESTORE_VECTOR_REGISTERS(); } else +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + if (aes->use_aes_hw_crypto) { + AES_XTS_decrypt_AARCH64(xaes, out, in, sz, i); + ret = 0; + } + else #endif { ret = AesXtsDecrypt_sw(xaes, out, in, sz, i); @@ -13526,7 +13720,7 @@ int wc_AesXtsDecrypt(XtsAes* xaes, byte* out, const byte* in, word32 sz, * * xaes AES keys to use for block encrypt/decrypt * i readwrite value to use for tweak - * iSz size of i buffer, should always be AES_BLOCK_SIZE but having this input + * iSz size of i buffer, should always be WC_AES_BLOCK_SIZE but having this input * adds a sanity check on how the user calls the function. * * returns 0 on success @@ -13552,11 +13746,11 @@ int wc_AesXtsDecryptInit(XtsAes* xaes, const byte* i, word32 iSz, return BAD_FUNC_ARG; } - if (iSz < AES_BLOCK_SIZE) { + if (iSz < WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } - XMEMCPY(stream->tweak_block, i, AES_BLOCK_SIZE); + XMEMCPY(stream->tweak_block, i, WC_AES_BLOCK_SIZE); stream->bytes_crypted_with_this_tweak = 0; { @@ -13593,15 +13787,15 @@ int wc_AesXtsDecryptInit(XtsAes* xaes, const byte* i, word32 iSz, /* Block-streaming AES-XTS * - * Note that sz must be >= AES_BLOCK_SIZE in each call, and must be a multiple - * of AES_BLOCK_SIZE in each call to wc_AesXtsDecryptUpdate(). - * wc_AesXtsDecryptFinal() can handle any length >= AES_BLOCK_SIZE. + * Note that sz must be >= WC_AES_BLOCK_SIZE in each call, and must be a multiple + * of WC_AES_BLOCK_SIZE in each call to wc_AesXtsDecryptUpdate(). + * wc_AesXtsDecryptFinal() can handle any length >= WC_AES_BLOCK_SIZE. * * xaes AES keys to use for block encrypt/decrypt * out output buffer to hold plain text * in input cipher text buffer to decrypt * sz size of both out and in buffers - * i tweak buffer of size AES_BLOCK_SIZE. + * i tweak buffer of size WC_AES_BLOCK_SIZE. * * returns 0 on success */ @@ -13625,12 +13819,12 @@ static int AesXtsDecryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 s #endif #endif - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Cipher text input too small for decryption"); return BAD_FUNC_ARG; } - if (stream->bytes_crypted_with_this_tweak & ((word32)AES_BLOCK_SIZE - 1U)) + if (stream->bytes_crypted_with_this_tweak & ((word32)WC_AES_BLOCK_SIZE - 1U)) { WOLFSSL_MSG("Call to AesXtsDecryptUpdate after previous finalizing call"); return BAD_FUNC_ARG; @@ -13680,7 +13874,7 @@ int wc_AesXtsDecryptUpdate(XtsAes* xaes, byte* out, const byte* in, word32 sz, { if (stream == NULL) return BAD_FUNC_ARG; - if (sz & ((word32)AES_BLOCK_SIZE - 1U)) + if (sz & ((word32)WC_AES_BLOCK_SIZE - 1U)) return BAD_FUNC_ARG; return AesXtsDecryptUpdate(xaes, out, in, sz, stream); } @@ -13695,20 +13889,19 @@ int wc_AesXtsDecryptFinal(XtsAes* xaes, byte* out, const byte* in, word32 sz, ret = AesXtsDecryptUpdate(xaes, out, in, sz, stream); else ret = 0; - ForceZero(stream->tweak_block, AES_BLOCK_SIZE); + ForceZero(stream->tweak_block, WC_AES_BLOCK_SIZE); /* force the count odd, to assure error on attempt to AesXtsEncryptUpdate() * after finalization. */ stream->bytes_crypted_with_this_tweak |= 1U; #ifdef WOLFSSL_CHECK_MEM_ZERO - wc_MemZero_Check(stream->tweak_block, AES_BLOCK_SIZE); + wc_MemZero_Check(stream->tweak_block, WC_AES_BLOCK_SIZE); #endif return ret; } #endif /* WOLFSSL_AESXTS_STREAM */ - -#endif /* !WOLFSSL_ARMASM || WOLFSSL_ARMASM_NO_HW_CRYPTO */ +#endif /* Same as wc_AesXtsEncryptSector but the sector gets incremented by one every * sectorSz bytes @@ -13734,7 +13927,7 @@ int wc_AesXtsEncryptConsecutiveSectors(XtsAes* aes, byte* out, const byte* in, return BAD_FUNC_ARG; } - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Cipher text input too small for encryption"); return BAD_FUNC_ARG; } @@ -13783,7 +13976,7 @@ int wc_AesXtsDecryptConsecutiveSectors(XtsAes* aes, byte* out, const byte* in, return BAD_FUNC_ARG; } - if (sz < AES_BLOCK_SIZE) { + if (sz < WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("Cipher text input too small for decryption"); return BAD_FUNC_ARG; } @@ -13825,10 +14018,10 @@ static WARN_UNUSED_RESULT int S2V( int i; Cmac* cmac; #else - byte tmp[3][AES_BLOCK_SIZE]; + byte tmp[3][WC_AES_BLOCK_SIZE]; Cmac cmac[1]; #endif - word32 macSz = AES_BLOCK_SIZE; + word32 macSz = WC_AES_BLOCK_SIZE; int ret = 0; byte tmpi = 0; word32 ai; @@ -13836,7 +14029,7 @@ static WARN_UNUSED_RESULT int S2V( #ifdef WOLFSSL_SMALL_STACK for (i = 0; i < 3; ++i) { - tmp[i] = (byte*)XMALLOC(AES_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); + tmp[i] = (byte*)XMALLOC(WC_AES_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (tmp[i] == NULL) { ret = MEMORY_E; break; @@ -13853,10 +14046,10 @@ static WARN_UNUSED_RESULT int S2V( } if (ret == 0) { - XMEMSET(tmp[1], 0, AES_BLOCK_SIZE); - XMEMSET(tmp[2], 0, AES_BLOCK_SIZE); + XMEMSET(tmp[1], 0, WC_AES_BLOCK_SIZE); + XMEMSET(tmp[2], 0, WC_AES_BLOCK_SIZE); - ret = wc_AesCmacGenerate(tmp[0], &macSz, tmp[1], AES_BLOCK_SIZE, + ret = wc_AesCmacGenerate(tmp[0], &macSz, tmp[1], WC_AES_BLOCK_SIZE, key, keySz); } @@ -13868,8 +14061,8 @@ static WARN_UNUSED_RESULT int S2V( assoc[ai].assocSz, key, keySz); if (ret != 0) break; - xorbuf(tmp[1-tmpi], tmp[tmpi], AES_BLOCK_SIZE); - tmpi = 1 - tmpi; + xorbuf(tmp[1-tmpi], tmp[tmpi], WC_AES_BLOCK_SIZE); + tmpi = (byte)(1 - tmpi); } /* Add nonce as final AD. See RFC 5297 Section 3. */ @@ -13878,20 +14071,20 @@ static WARN_UNUSED_RESULT int S2V( ret = wc_AesCmacGenerate(tmp[tmpi], &macSz, nonce, nonceSz, key, keySz); if (ret == 0) { - xorbuf(tmp[1-tmpi], tmp[tmpi], AES_BLOCK_SIZE); + xorbuf(tmp[1-tmpi], tmp[tmpi], WC_AES_BLOCK_SIZE); } - tmpi = 1 - tmpi; + tmpi = (byte)(1U - tmpi); } /* For simplicity of the remaining code, make sure the "final" result is always in tmp[0]. */ if (tmpi == 1) { - XMEMCPY(tmp[0], tmp[1], AES_BLOCK_SIZE); + XMEMCPY(tmp[0], tmp[1], WC_AES_BLOCK_SIZE); } } if (ret == 0) { - if (dataSz >= AES_BLOCK_SIZE) { + if (dataSz >= WC_AES_BLOCK_SIZE) { #ifdef WOLFSSL_SMALL_STACK cmac = (Cmac*)XMALLOC(sizeof(Cmac), NULL, DYNAMIC_TYPE_CMAC); @@ -13907,14 +14100,14 @@ static WARN_UNUSED_RESULT int S2V( ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes)); #endif - xorbuf(tmp[0], data + (dataSz - AES_BLOCK_SIZE), - AES_BLOCK_SIZE); + xorbuf(tmp[0], data + (dataSz - WC_AES_BLOCK_SIZE), + WC_AES_BLOCK_SIZE); ret = wc_InitCmac(cmac, key, keySz, WC_CMAC_AES, NULL); if (ret == 0) { - ret = wc_CmacUpdate(cmac, data, dataSz - AES_BLOCK_SIZE); + ret = wc_CmacUpdate(cmac, data, dataSz - WC_AES_BLOCK_SIZE); } if (ret == 0) { - ret = wc_CmacUpdate(cmac, tmp[0], AES_BLOCK_SIZE); + ret = wc_CmacUpdate(cmac, tmp[0], WC_AES_BLOCK_SIZE); } if (ret == 0) { ret = wc_CmacFinal(cmac, out, &macSz); @@ -13929,13 +14122,13 @@ static WARN_UNUSED_RESULT int S2V( else { XMEMCPY(tmp[2], data, dataSz); tmp[2][dataSz] |= 0x80; - zeroBytes = AES_BLOCK_SIZE - (dataSz + 1); + zeroBytes = WC_AES_BLOCK_SIZE - (dataSz + 1); if (zeroBytes != 0) { XMEMSET(tmp[2] + dataSz + 1, 0, zeroBytes); } ShiftAndXorRb(tmp[1], tmp[0]); - xorbuf(tmp[1], tmp[2], AES_BLOCK_SIZE); - ret = wc_AesCmacGenerate(out, &macSz, tmp[1], AES_BLOCK_SIZE, key, + xorbuf(tmp[1], tmp[2], WC_AES_BLOCK_SIZE); + ret = wc_AesCmacGenerate(out, &macSz, tmp[1], WC_AES_BLOCK_SIZE, key, keySz); } } @@ -13963,7 +14156,7 @@ static WARN_UNUSED_RESULT int AesSivCipher( #else Aes aes[1]; #endif - byte sivTmp[AES_BLOCK_SIZE]; + byte sivTmp[WC_AES_BLOCK_SIZE]; if (key == NULL || siv == NULL || out == NULL) { WOLFSSL_MSG("Bad parameter"); @@ -13983,11 +14176,11 @@ static WARN_UNUSED_RESULT int AesSivCipher( WOLFSSL_MSG("S2V failed."); } else { - XMEMCPY(siv, sivTmp, AES_BLOCK_SIZE); + XMEMCPY(siv, sivTmp, WC_AES_BLOCK_SIZE); } } else { - XMEMCPY(sivTmp, siv, AES_BLOCK_SIZE); + XMEMCPY(sivTmp, siv, WC_AES_BLOCK_SIZE); } } @@ -14025,7 +14218,7 @@ static WARN_UNUSED_RESULT int AesSivCipher( WOLFSSL_MSG("S2V failed."); } - if (XMEMCMP(siv, sivTmp, AES_BLOCK_SIZE) != 0) { + if (XMEMCMP(siv, sivTmp, WC_AES_BLOCK_SIZE) != 0) { WOLFSSL_MSG("Computed SIV doesn't match received SIV."); ret = AES_SIV_AUTH_E; } @@ -14283,7 +14476,7 @@ int wc_AesEaxInit(AesEax* eax, goto out; } - cmacSize = AES_BLOCK_SIZE; + cmacSize = WC_AES_BLOCK_SIZE; if ((ret = wc_CmacFinal(&eax->nonceCmac, eax->nonceCmacFinal, &cmacSize)) != 0) { @@ -14300,7 +14493,7 @@ int wc_AesEaxInit(AesEax* eax, * provided * H' = OMAC^1_K(H) */ - eax->prefixBuf[AES_BLOCK_SIZE-1] = 1; + eax->prefixBuf[WC_AES_BLOCK_SIZE-1] = 1; if ((ret = wc_InitCmac(&eax->aadCmac, key, keySz, @@ -14327,7 +14520,7 @@ int wc_AesEaxInit(AesEax* eax, * updated in subsequent calls to encrypt/decrypt * C' = OMAC^2_K(C) */ - eax->prefixBuf[AES_BLOCK_SIZE-1] = 2; + eax->prefixBuf[WC_AES_BLOCK_SIZE-1] = 2; if ((ret = wc_InitCmac(&eax->ciphertextCmac, key, keySz, @@ -14475,12 +14668,12 @@ int wc_AesEaxEncryptFinal(AesEax* eax, byte* authTag, word32 authTagSz) int ret; word32 i; - if (eax == NULL || authTag == NULL || authTagSz > AES_BLOCK_SIZE) { + if (eax == NULL || authTag == NULL || authTagSz > WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } /* Complete the OMAC for the ciphertext */ - cmacSize = AES_BLOCK_SIZE; + cmacSize = WC_AES_BLOCK_SIZE; if ((ret = wc_CmacFinalNoFree(&eax->ciphertextCmac, eax->ciphertextCmacFinal, &cmacSize)) != 0) { @@ -14488,7 +14681,7 @@ int wc_AesEaxEncryptFinal(AesEax* eax, byte* authTag, word32 authTagSz) } /* Complete the OMAC for auth data */ - cmacSize = AES_BLOCK_SIZE; + cmacSize = WC_AES_BLOCK_SIZE; if ((ret = wc_CmacFinalNoFree(&eax->aadCmac, eax->aadCmacFinal, &cmacSize)) != 0) { @@ -14529,15 +14722,15 @@ int wc_AesEaxDecryptFinal(AesEax* eax, #if defined(WOLFSSL_SMALL_STACK) byte *authTag; #else - byte authTag[AES_BLOCK_SIZE]; + byte authTag[WC_AES_BLOCK_SIZE]; #endif - if (eax == NULL || authIn == NULL || authInSz > AES_BLOCK_SIZE) { + if (eax == NULL || authIn == NULL || authInSz > WC_AES_BLOCK_SIZE) { return BAD_FUNC_ARG; } /* Complete the OMAC for the ciphertext */ - cmacSize = AES_BLOCK_SIZE; + cmacSize = WC_AES_BLOCK_SIZE; if ((ret = wc_CmacFinalNoFree(&eax->ciphertextCmac, eax->ciphertextCmacFinal, &cmacSize)) != 0) { @@ -14545,7 +14738,7 @@ int wc_AesEaxDecryptFinal(AesEax* eax, } /* Complete the OMAC for auth data */ - cmacSize = AES_BLOCK_SIZE; + cmacSize = WC_AES_BLOCK_SIZE; if ((ret = wc_CmacFinalNoFree(&eax->aadCmac, eax->aadCmacFinal, &cmacSize)) != 0) { @@ -14553,7 +14746,7 @@ int wc_AesEaxDecryptFinal(AesEax* eax, } #if defined(WOLFSSL_SMALL_STACK) - authTag = (byte*)XMALLOC(AES_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); + authTag = (byte*)XMALLOC(WC_AES_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (authTag == NULL) { return MEMORY_E; } diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index 0c52002..6335df3 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -105,6 +105,8 @@ ASN Options: * WOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED: Allows the ECDSA/EdDSA signature * algorithms in certificates to have NULL parameter instead of empty. * DO NOT enable this unless required for interoperability. + * WOLFSSL_ASN_EXTRA: Make more ASN.1 APIs available regardless of internal + * usage. */ #include @@ -1271,8 +1273,8 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, /* Fill number with all of data. */ *data->data.u16 = 0; for (i = 0; i < len; i++) { - *data->data.u16 <<= 8; - *data->data.u16 |= input[idx + (word32)i] ; + *data->data.u16 = (word16)(*data->data.u16 << 8U); + *data->data.u16 = (word16)(*data->data.u16 | input[idx + (word32)i]); } break; case ASN_DATA_TYPE_WORD32: @@ -3176,7 +3178,7 @@ int GetMyVersion(const byte* input, word32* inOutIdx, } -#ifndef NO_PWDBASED +#if !defined(NO_PWDBASED) || defined(WOLFSSL_ASN_EXTRA) /* Decode small integer, 32 bits or less. * * @param [in] input Buffer of BER data. @@ -3241,8 +3243,10 @@ int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx) return ret; #endif } +#endif /* !NO_PWDBASED || WOLFSSL_ASN_EXTRA */ +#ifndef NO_PWDBASED #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \ defined(HAVE_PKCS12) /* Set small integer, 32 bits or less. DER encoding with no leading 0s @@ -4597,6 +4601,7 @@ static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7}; /* Pilot attribute types (0.9.2342.19200300.100.1.*) */ #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num} static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */ +static const byte rfc822Mlbx[] = PLT_ATTR_TYPE_OID_BASE(3); /* RFC822 mailbox */ static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/ #endif @@ -5549,7 +5554,7 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) #ifdef WOLFSSL_APACHE_HTTPD case oidCertNameType: switch (id) { - case NID_id_on_dnsSRV: + case WC_NID_id_on_dnsSRV: oid = dnsSRVOid; *oidSz = sizeof(dnsSRVOid); break; @@ -6412,7 +6417,7 @@ enum { RSAPSSPARAMSASN_IDX_SALTLEN, RSAPSSPARAMSASN_IDX_SALTLENINT, RSAPSSPARAMSASN_IDX_TRAILER, - RSAPSSPARAMSASN_IDX_TRAILERINT, + RSAPSSPARAMSASN_IDX_TRAILERINT }; /* Number of items in ASN.1 template for an algorithm identifier. */ @@ -8146,7 +8151,7 @@ static int CheckAlgoV2(int oid, int* id, int* blockSz) case AES256CBCb: *id = PBE_AES256_CBC; if (blockSz != NULL) { - *blockSz = AES_BLOCK_SIZE; + *blockSz = WC_AES_BLOCK_SIZE; } break; #endif @@ -8154,7 +8159,7 @@ static int CheckAlgoV2(int oid, int* id, int* blockSz) case AES128CBCb: *id = PBE_AES128_CBC; if (blockSz != NULL) { - *blockSz = AES_BLOCK_SIZE; + *blockSz = WC_AES_BLOCK_SIZE; } break; #endif @@ -8635,12 +8640,12 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, pbeOidBuf = pbes2; pbeOidBufSz = sizeof(pbes2); /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */ - kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen; + kdfLen = 2U + (word32)sizeof(pbkdf2Oid) + 2U + innerLen; /* enc = OBJ enc_alg OCT iv */ - encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz; + encLen = 2U + (word32)encOidSz + 2U + (word32)blockSz; /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */ - pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 + - (size_t)encLen); + pbeLen = 2U + (word32)sizeof(pbes2) + 2U + 2U + kdfLen + 2U + + encLen; ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz); } @@ -8710,7 +8715,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, idx += SetSequence(kdfLen, out + idx); idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx); XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid)); - idx += sizeof(pbkdf2Oid); + idx += (word32)sizeof(pbkdf2Oid); } idx += SetSequence(innerLen, out + idx); idx += SetOctetString(saltSz, out + idx); @@ -11969,8 +11974,7 @@ static int SetEccPublicKey(byte* output, ecc_key* key, int outLen, if (ret == 0) { /* Calculate the size of the encoded public point. */ PRIVATE_KEY_UNLOCK(); - #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2) + #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && FIPS_VERSION3_LT(6,0,0) /* in earlier versions of FIPS the get length functionality is not * available with compressed keys */ pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES; @@ -13102,7 +13106,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_commonName + WC_NID_commonName #endif }, /* Surname */ @@ -13119,7 +13123,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_surname + WC_NID_surname #endif }, /* Serial Number */ @@ -13136,7 +13140,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_serialNumber + WC_NID_serialNumber #endif }, /* Country Name */ @@ -13153,7 +13157,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_countryName + WC_NID_countryName #endif }, /* Locality Name */ @@ -13170,7 +13174,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_localityName + WC_NID_localityName #endif }, /* State Name */ @@ -13187,7 +13191,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_stateOrProvinceName + WC_NID_stateOrProvinceName #endif }, /* Street Address */ @@ -13204,7 +13208,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_streetAddress + WC_NID_streetAddress #endif }, /* Organization Name */ @@ -13221,7 +13225,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_organizationName + WC_NID_organizationName #endif }, /* Organization Unit Name */ @@ -13238,7 +13242,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_organizationalUnitName + WC_NID_organizationalUnitName #endif }, /* Title */ @@ -13306,7 +13310,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_businessCategory + WC_NID_businessCategory #endif }, /* Undefined */ @@ -13340,7 +13344,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_postalCode + WC_NID_postalCode #endif }, /* User Id */ @@ -13357,7 +13361,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_userId + WC_NID_userId #endif }, #ifdef WOLFSSL_CERT_NAME_ALL @@ -13375,7 +13379,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_name + WC_NID_name #endif }, /* Given Name, id 42 */ @@ -13392,7 +13396,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_givenName + WC_NID_givenName #endif }, /* initials, id 43 */ @@ -13409,7 +13413,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_initials + WC_NID_initials #endif }, /* DN Qualifier Name, id 46 */ @@ -13426,7 +13430,7 @@ static const CertNameData certNameSubject[] = { #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE - NID_dnQualifier + WC_NID_dnQualifier #endif }, #endif /* WOLFSSL_CERT_NAME_ALL */ @@ -13544,7 +13548,7 @@ static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap) static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) { int i, j, ret = 0; - int nameSz = 0; + word16 nameSz = 0; #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) int nid = 0; #endif @@ -13553,7 +13557,7 @@ static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) word32 idx = 0; word16 tmpName[MAX_OID_SZ]; char oidName[MAX_OID_SZ]; - char* finalName; + char* finalName = NULL; if (entry == NULL || entry->type != ASN_RID_TYPE) { return BAD_FUNC_ARG; @@ -13611,7 +13615,10 @@ static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap) } if (ret == 0) { - nameSz = (int)XSTRLEN((const char*)finalName); + nameSz = (word16)XSTRLEN((const char*)finalName); + if (nameSz > MAX_OID_SZ) { + return BUFFER_E; + } entry->ridString = (char*)XMALLOC((word32)(nameSz + 1), heap, DYNAMIC_TYPE_ALTNAME); @@ -13863,7 +13870,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_EMAIL_ADDR; typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_emailAddress; + *nid = WC_NID_emailAddress; #endif } else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) { @@ -13872,7 +13879,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_USER_ID; typeStrLen = sizeof(WOLFSSL_USER_ID) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_userId; + *nid = WC_NID_userId; #endif } else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) { @@ -13881,7 +13888,16 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_DOMAIN_COMPONENT; typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_domainComponent; + *nid = WC_NID_domainComponent; + #endif + } + else if (oidSz == sizeof(rfc822Mlbx) && XMEMCMP(oid, rfc822Mlbx, oidSz) == 0) { + /* Set the RFC822 mailbox, type string, length and NID. */ + id = ASN_RFC822_MAILBOX; + typeStr = WOLFSSL_RFC822_MAILBOX; + typeStrLen = sizeof(WOLFSSL_RFC822_MAILBOX) - 1; + #ifdef WOLFSSL_X509_NAME_AVAILABLE + *nid = WC_NID_rfc822Mailbox; #endif } else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) { @@ -13890,7 +13906,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_FAVOURITE_DRINK; typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_favouriteDrink; + *nid = WC_NID_favouriteDrink; #endif } #ifdef WOLFSSL_CERT_REQ @@ -13901,7 +13917,7 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_CONTENT_TYPE; typeStrLen = sizeof(WOLFSSL_CONTENT_TYPE) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_pkcs9_contentType; + *nid = WC_NID_pkcs9_contentType; #endif } #endif @@ -13921,14 +13937,14 @@ static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid, typeStr = WOLFSSL_JOI_C; typeStrLen = sizeof(WOLFSSL_JOI_C) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_jurisdictionCountryName; + *nid = WC_NID_jurisdictionCountryName; #endif /* WOLFSSL_X509_NAME_AVAILABLE */ } else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) { typeStr = WOLFSSL_JOI_ST; typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1; #ifdef WOLFSSL_X509_NAME_AVAILABLE - *nid = NID_jurisdictionStateOrProvinceName; + *nid = WC_NID_jurisdictionStateOrProvinceName; #endif /* WOLFSSL_X509_NAME_AVAILABLE */ } else { @@ -14063,7 +14079,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, byte id = 0; #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - int nid = NID_undef; + int nid = WC_NID_undef; int enc; #endif /* OPENSSL_EXTRA */ @@ -14146,7 +14162,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1; #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_commonName; + nid = WC_NID_commonName; #endif /* OPENSSL_EXTRA */ } #ifdef WOLFSSL_CERT_NAME_ALL @@ -14163,7 +14179,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_name; + nid = WC_NID_name; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_INITIALS) { @@ -14179,7 +14195,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_initials; + nid = WC_NID_initials; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_GIVEN_NAME) { @@ -14195,7 +14211,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_givenName; + nid = WC_NID_givenName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_DNQUALIFIER) { @@ -14211,7 +14227,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_dnQualifier; + nid = WC_NID_dnQualifier; #endif /* OPENSSL_EXTRA */ } #endif /* WOLFSSL_CERT_NAME_ALL */ @@ -14235,7 +14251,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_surname; + nid = WC_NID_surname; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_COUNTRY_NAME) { @@ -14258,7 +14274,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_countryName; + nid = WC_NID_countryName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_LOCALITY_NAME) { @@ -14281,7 +14297,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_localityName; + nid = WC_NID_localityName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_STATE_NAME) { @@ -14304,7 +14320,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_stateOrProvinceName; + nid = WC_NID_stateOrProvinceName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_ORG_NAME) { @@ -14327,7 +14343,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_organizationName; + nid = WC_NID_organizationName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_ORGUNIT_NAME) { @@ -14350,7 +14366,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_organizationalUnitName; + nid = WC_NID_organizationalUnitName; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_SERIAL_NUMBER) { @@ -14373,7 +14389,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_serialNumber; + nid = WC_NID_serialNumber; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_USER_ID) { @@ -14389,7 +14405,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_userId; + nid = WC_NID_userId; #endif /* OPENSSL_EXTRA */ } #ifdef WOLFSSL_CERT_EXT @@ -14406,7 +14422,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_streetAddress; + nid = WC_NID_streetAddress; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_BUS_CAT) { @@ -14421,7 +14437,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */ #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_businessCategory; + nid = WC_NID_businessCategory; #endif /* OPENSSL_EXTRA */ } else if (id == ASN_POSTAL_CODE) { @@ -14437,7 +14453,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_postalCode; + nid = WC_NID_postalCode; #endif /* OPENSSL_EXTRA */ } #endif /* WOLFSSL_CERT_EXT */ @@ -14476,7 +14492,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_jurisdictionCountryName; + nid = WC_NID_jurisdictionCountryName; #endif /* OPENSSL_EXTRA */ } @@ -14494,7 +14510,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_jurisdictionStateOrProvinceName; + nid = WC_NID_jurisdictionStateOrProvinceName; #endif /* OPENSSL_EXTRA */ } @@ -14564,7 +14580,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_emailAddress; + nid = WC_NID_emailAddress; #endif /* OPENSSL_EXTRA */ } @@ -14576,7 +14592,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_userId; + nid = WC_NID_userId; #endif /* OPENSSL_EXTRA */ break; case ASN_DOMAIN_COMPONENT: @@ -14585,7 +14601,16 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_domainComponent; + nid = WC_NID_domainComponent; + #endif /* OPENSSL_EXTRA */ + break; + case ASN_RFC822_MAILBOX: + copy = WOLFSSL_RFC822_MAILBOX; + copyLen = sizeof(WOLFSSL_RFC822_MAILBOX) - 1; + #if (defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_EXTRA_X509_SMALL)) \ + && !defined(WOLFCRYPT_ONLY) + nid = WC_NID_rfc822Mailbox; #endif /* OPENSSL_EXTRA */ break; case ASN_FAVOURITE_DRINK: @@ -14594,7 +14619,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_favouriteDrink; + nid = WC_NID_favouriteDrink; #endif /* OPENSSL_EXTRA */ break; case ASN_CONTENT_TYPE: @@ -14603,7 +14628,7 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, #if (defined(OPENSSL_EXTRA) || \ defined(OPENSSL_EXTRA_X509_SMALL)) \ && !defined(WOLFCRYPT_ONLY) - nid = NID_pkcs9_contentType; + nid = WC_NID_pkcs9_contentType; #endif /* OPENSSL_EXTRA */ break; default: @@ -14632,17 +14657,17 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, !defined(WOLFCRYPT_ONLY) switch (b) { case CTC_UTF8: - enc = MBSTRING_UTF8; + enc = WOLFSSL_MBSTRING_UTF8; break; case CTC_PRINTABLE: - enc = V_ASN1_PRINTABLESTRING; + enc = WOLFSSL_V_ASN1_PRINTABLESTRING; break; default: WOLFSSL_MSG("Unknown encoding type, using UTF8 by default"); - enc = MBSTRING_UTF8; + enc = WOLFSSL_MBSTRING_UTF8; } - if (nid != NID_undef) { + if (nid != WC_NID_undef) { if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, &input[srcIdx], strLen, -1, -1) != WOLFSSL_SUCCESS) { @@ -14772,14 +14797,14 @@ static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType, /* Convert BER tag to a OpenSSL type. */ switch (tag) { case CTC_UTF8: - enc = MBSTRING_UTF8; + enc = WOLFSSL_MBSTRING_UTF8; break; case CTC_PRINTABLE: - enc = V_ASN1_PRINTABLESTRING; + enc = WOLFSSL_V_ASN1_PRINTABLESTRING; break; default: WOLFSSL_MSG("Unknown encoding type, default UTF8"); - enc = MBSTRING_UTF8; + enc = WOLFSSL_MBSTRING_UTF8; } if (nid != 0) { /* Add an entry to the X509_NAME. */ @@ -16115,7 +16140,6 @@ word32 SetOthername(void *name, byte *output) WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name; char *nameStr = NULL; word32 nameSz = 0; - word32 len = 0; if ((nm == NULL) || (nm->value == NULL)) { WOLFSSL_MSG("otherName value is NULL"); @@ -16125,11 +16149,13 @@ word32 SetOthername(void *name, byte *output) nameStr = nm->value->value.utf8string->data; nameSz = (word32)nm->value->value.utf8string->length; - len = nm->type_id->objSz + - SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL, 0) + - SetHeader(CTC_UTF8, nameSz, NULL, 0) + nameSz; - - if (output != NULL) { + if (output == NULL) { + return nm->type_id->objSz + + SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL, 0) + + SetHeader(CTC_UTF8, nameSz, NULL, 0) + nameSz; + } + else { + const byte *output_start = output; /* otherName OID */ XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz); output += nm->type_id->objSz; @@ -16137,12 +16163,19 @@ word32 SetOthername(void *name, byte *output) output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, output, 0); + /* work around false positive from -fstack-protector */ + PRAGMA_GCC_DIAG_PUSH + PRAGMA_GCC("GCC diagnostic ignored \"-Wstringop-overflow\"") + output += SetHeader(CTC_UTF8, nameSz, output, 0); + PRAGMA_GCC_DIAG_POP + XMEMCPY(output, nameStr, nameSz); - } - return len; + output += nameSz; + return (word32)(output - output_start); + } } #endif /* OPENSSL_EXTRA */ @@ -16620,7 +16653,7 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, } else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) { *typeH = MD2h; - *digestSz = MD2_DIGEST_SIZE; + *digestSz = WC_MD2_DIGEST_SIZE; } break; #endif @@ -21826,7 +21859,7 @@ enum { #ifdef WC_RSA_PSS RPKCERTASN_IDX_SPUBKEYINFO_ALGO_P_SEQ, #endif - RPKCERTASN_IDX_SPUBKEYINFO_PUBKEY, + RPKCERTASN_IDX_SPUBKEYINFO_PUBKEY }; #endif /* HAVE_RPK */ @@ -24052,7 +24085,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer } } else { - cert->maxPathLen = (byte)min(cert->ca->maxPathLen - 1, + cert->maxPathLen = (byte)min(cert->ca->maxPathLen - 1U, cert->maxPathLen); } } @@ -24158,16 +24191,16 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer if ((ret == 0) && cert->extAltSigAlgSet && cert->extAltSigValSet) { #ifndef WOLFSSL_SMALL_STACK - byte der[MAX_CERT_VERIFY_SZ]; + byte der[WC_MAX_CERT_VERIFY_SZ]; #else - byte *der = (byte*)XMALLOC(MAX_CERT_VERIFY_SZ, cert->heap, + byte *der = (byte*)XMALLOC(WC_MAX_CERT_VERIFY_SZ, cert->heap, DYNAMIC_TYPE_DCERT); if (der == NULL) { ret = MEMORY_E; } else #endif /* ! WOLFSSL_SMALL_STACK */ { - ret = wc_GeneratePreTBS(cert, der, MAX_CERT_VERIFY_SZ); + ret = wc_GeneratePreTBS(cert, der, WC_MAX_CERT_VERIFY_SZ); if (ret > 0) { ret = ConfirmSignature(&cert->sigCtx, der, ret, @@ -24231,16 +24264,16 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer if ((ret == 0) && cert->extAltSigAlgSet && cert->extAltSigValSet) { #ifndef WOLFSSL_SMALL_STACK - byte der[MAX_CERT_VERIFY_SZ]; + byte der[WC_MAX_CERT_VERIFY_SZ]; #else - byte *der = (byte*)XMALLOC(MAX_CERT_VERIFY_SZ, cert->heap, + byte *der = (byte*)XMALLOC(WC_MAX_CERT_VERIFY_SZ, cert->heap, DYNAMIC_TYPE_DCERT); if (der == NULL) { ret = MEMORY_E; } else #endif /* ! WOLFSSL_SMALL_STACK */ { - ret = wc_GeneratePreTBS(cert, der, MAX_CERT_VERIFY_SZ); + ret = wc_GeneratePreTBS(cert, der, WC_MAX_CERT_VERIFY_SZ); if (ret > 0) { ret = ConfirmSignature(&cert->sigCtx, der, ret, @@ -25804,9 +25837,9 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \ defined(HAVE_AES_DECRYPT) if (info->cipherType == WC_CIPHER_AES_CBC) { - if (der->length > AES_BLOCK_SIZE) { + if (der->length > WC_AES_BLOCK_SIZE) { padVal = der->buffer[der->length-1]; - if (padVal <= AES_BLOCK_SIZE) { + if (padVal <= WC_AES_BLOCK_SIZE) { der->length -= (word32)padVal; } } @@ -25817,14 +25850,14 @@ int PemToDer(const unsigned char* buff, long longSz, int type, } #ifdef OPENSSL_EXTRA if (ret) { - PEMerr(0, PEM_R_BAD_DECRYPT); + WOLFSSL_PEMerr(0, WOLFSSL_PEM_R_BAD_DECRYPT_E); } #endif ForceZero(password, (word32)passwordSz); } #ifdef OPENSSL_EXTRA else { - PEMerr(0, PEM_R_BAD_PASSWORD_READ); + WOLFSSL_PEMerr(0, WOLFSSL_PEM_R_BAD_PASSWORD_READ_E); } #endif @@ -26987,7 +27020,7 @@ static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz, #ifndef NO_ASN_TIME static WC_INLINE byte itob(int number) { - return (byte)number + 0x30; + return (byte)(number + 0x30); } @@ -28083,6 +28116,10 @@ static int EncodeName(EncodedName* name, const char* nameStr, thisLen += (int)sizeof(uidOid); firstSz = (int)sizeof(uidOid); break; + case ASN_RFC822_MAILBOX: + thisLen += (int)sizeof(rfc822Mlbx); + firstSz = (int)sizeof(rfc822Mlbx); + break; case ASN_FAVOURITE_DRINK: thisLen += (int)sizeof(fvrtDrk); firstSz = (int)sizeof(fvrtDrk); @@ -28148,6 +28185,12 @@ static int EncodeName(EncodedName* name, const char* nameStr, /* str type */ name->encoded[idx++] = nameTag; break; + case ASN_RFC822_MAILBOX: + XMEMCPY(name->encoded + idx, rfc822Mlbx, sizeof(rfc822Mlbx)); + idx += (int)sizeof(rfc822Mlbx); + /* str type */ + name->encoded[idx++] = nameTag; + break; case ASN_FAVOURITE_DRINK: XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk)); idx += (int)sizeof(fvrtDrk); @@ -28244,6 +28287,10 @@ static int EncodeName(EncodedName* name, const char* nameStr, oid = uidOid; oidSz = sizeof(uidOid); break; + case ASN_RFC822_MAILBOX: + oid = rfc822Mlbx; + oidSz = sizeof(rfc822Mlbx); + break; case ASN_FAVOURITE_DRINK: oid = fvrtDrk; oidSz = sizeof(fvrtDrk); @@ -28567,6 +28614,12 @@ static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN, sizeof(uidOid), (byte)GetNameType(name, i), (const byte*)GetOneCertName(name, i), nameLen[i]); } + else if (type == ASN_RFC822_MAILBOX) { + /* Copy RFC822 mailbox data into dynamic vars. */ + SetRdnItems(namesASN + idx, dataASN + idx, rfc822Mlbx, + sizeof(rfc822Mlbx), (byte)GetNameType(name, i), + (const byte*)GetOneCertName(name, i), nameLen[i]); + } else if (type == ASN_FAVOURITE_DRINK) { /* Copy favourite drink data into dynamic vars. */ SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk, @@ -33379,7 +33432,8 @@ int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap) return BUFFER_E; } - out[idx++] += (byte)val; + out[idx] = (byte)(out[idx] + val); + ++idx; } else { word32 tb = 0; @@ -34320,7 +34374,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, byte version = 0; int ret = 0; int curve_id = ECC_CURVE_DEF; -#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2) +#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(WOLFSSL_SM2) word32 algId = 0; word32 eccOid = 0; #endif @@ -34330,7 +34384,7 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, ret = BAD_FUNC_ARG; } -#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2) +#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(WOLFSSL_SM2) /* if has pkcs8 header skip it */ if (ToTraditionalInline_ex2(input, inOutIdx, inSz, &algId, &eccOid) < 0) { /* ignore error, did not have pkcs8 header */ @@ -35307,9 +35361,10 @@ enum { || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \ || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)) + int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, const byte** privKey, word32* privKeyLen, - const byte** pubKey, word32* pubKeyLen, int keyType) + const byte** pubKey, word32* pubKeyLen, int* inOutKeyType) { #ifndef WOLFSSL_ASN_TEMPLATE word32 oid; @@ -35323,7 +35378,7 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, #endif if (input == NULL || inOutIdx == NULL || inSz == 0 || - privKey == NULL || privKeyLen == NULL) { + privKey == NULL || privKeyLen == NULL || inOutKeyType == NULL) { #ifdef WOLFSSL_ASN_TEMPLATE FREE_ASNGETDATA(dataASN, NULL); #endif @@ -35337,14 +35392,22 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) return ASN_PARSE_E; if (version != 0) { - WOLFSSL_MSG("Unrecognized version of ED25519 private key"); + WOLFSSL_MSG("Unrecognized version of private key"); return ASN_PARSE_E; } if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0) return ASN_PARSE_E; - if (oid != (word32)keyType) + + /* If user supplies ANONk (0) key type, we want to auto-detect from + * DER and copy it back to user */ + if (*inOutKeyType == ANONk) { + *inOutKeyType = oid; + } + /* Otherwise strictly validate against the expected type */ + else if (oid != (word32)*inOutKeyType) { return ASN_PARSE_E; + } if (GetOctetString(input, inOutIdx, &length, inSz) < 0) return ASN_PARSE_E; @@ -35394,10 +35457,21 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, return 0; #else if (ret == 0) { - /* Require OID. */ - word32 oidSz; - const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz); - GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz); + /* If user supplies an expected keyType (algorithm OID sum), attempt to + * process DER accordingly */ + if (*inOutKeyType != ANONk) { + word32 oidSz; + /* Explicit OID check - use expected type */ + const byte* oidDerBytes = OidFromId((word32)*inOutKeyType, + oidKeyType, &oidSz); + GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oidDerBytes, + oidSz); + } + else { + /* Auto-detect OID using template */ + GetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oidKeyType); + } + /* Parse full private key. */ ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input, inOutIdx, inSz); @@ -35410,6 +35484,12 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, ret = ASN_PARSE_E; } } + + /* Store detected OID if requested */ + if (ret == 0 && *inOutKeyType == ANONk) { + *inOutKeyType = + (int)dataASN[EDKEYASN_IDX_PKEYALGO_OID].data.oid.sum; + } } if (ret == 0) { /* Import private value. */ @@ -35450,7 +35530,7 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, if (ret == 0) { ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &privKeyPtr, - &privKeyPtrLen, &pubKeyPtr, &pubKeyPtrLen, keyType); + &privKeyPtrLen, &pubKeyPtr, &pubKeyPtrLen, &keyType); } if ((ret == 0) && (privKeyPtrLen > *privKeyLen)) { ret = BUFFER_E; @@ -35473,7 +35553,7 @@ int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, } int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, - const byte** pubKey, word32* pubKeyLen, int keyType) + const byte** pubKey, word32* pubKeyLen, int *inOutKeyType) { int ret = 0; #ifndef WOLFSSL_ASN_TEMPLATE @@ -35485,7 +35565,7 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, #endif if (input == NULL || inSz == 0 || inOutIdx == NULL || - pubKey == NULL || pubKeyLen == NULL) { + pubKey == NULL || pubKeyLen == NULL || inOutKeyType == NULL) { return BAD_FUNC_ARG; } @@ -35498,8 +35578,16 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0) return ASN_PARSE_E; - if (oid != (word32)keyType) + + /* If user supplies ANONk (0) key type, we want to auto-detect from + * DER and copy it back to user */ + if (*inOutKeyType == ANONk) { + *inOutKeyType = oid; + } + /* Otherwise strictly validate against the expected type */ + else if (oid != (word32)*inOutKeyType) { return ASN_PARSE_E; + } /* key header */ ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL); @@ -35519,12 +35607,21 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, CALLOC_ASNGETDATA(dataASN, publicKeyASN_Length, ret, NULL); if (ret == 0) { - /* Require OID. */ - word32 oidSz; - const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz); - - GetASN_ExpBuffer(&dataASN[PUBKEYASN_IDX_ALGOID_OID], oid, oidSz); - /* Decode Ed25519 private key. */ + /* If user supplies an expected keyType (algorithm OID sum), attempt to + * process DER accordingly */ + if (*inOutKeyType != ANONk) { + word32 oidSz; + /* Explicit OID check - use expected type */ + const byte* oidDerBytes = OidFromId((word32)*inOutKeyType, + oidKeyType, &oidSz); + GetASN_ExpBuffer(&dataASN[PUBKEYASN_IDX_ALGOID_OID], oidDerBytes, + oidSz); + } + else { + /* Auto-detect OID using template */ + GetASN_OID(&dataASN[PUBKEYASN_IDX_ALGOID_OID], oidKeyType); + } + /* Decode public key. */ ret = GetASN_Items(publicKeyASN, dataASN, publicKeyASN_Length, 1, input, inOutIdx, inSz); if (ret != 0) @@ -35532,6 +35629,12 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, /* check that input buffer is exhausted */ if (*inOutIdx != inSz) ret = ASN_PARSE_E; + + /* Store detected OID if requested */ + if (ret == 0 && *inOutKeyType == ANONk) { + *inOutKeyType = + (int)dataASN[PUBKEYASN_IDX_ALGOID_OID].data.oid.sum; + } } /* Check that the all the buffer was used. */ if ((ret == 0) && @@ -35546,6 +35649,7 @@ int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, FREE_ASNGETDATA(dataASN, NULL); #endif /* WOLFSSL_ASN_TEMPLATE */ return ret; + } int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, @@ -35561,7 +35665,7 @@ int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, if (ret == 0) { ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKeyPtr, - &pubKeyPtrLen, keyType); + &pubKeyPtrLen, &keyType); } if ((ret == 0) && (pubKeyPtrLen > *pubKeyLen)) { ret = BUFFER_E; @@ -35661,6 +35765,55 @@ int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx, } return ret; } + +/* Decode Curve25519 key from DER format - can handle private only, + * public only, or private+public key pairs. + * return 0 on success, negative on error */ +int wc_Curve25519KeyDecode(const byte* input, word32* inOutIdx, + curve25519_key* key, word32 inSz) +{ + int ret; + byte privKey[CURVE25519_KEYSIZE]; + byte pubKey[CURVE25519_PUB_KEY_SIZE]; + word32 privKeyLen = CURVE25519_KEYSIZE; + word32 pubKeyLen = CURVE25519_PUB_KEY_SIZE; + + /* sanity check */ + if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) { + return BAD_FUNC_ARG; + } + + /* Try to decode as private key first (may include public) */ + ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen, + pubKey, &pubKeyLen, X25519k); + + if (ret == 0) { + /* Successfully decoded private key */ + if (pubKeyLen > 0) { + /* Have both private and public */ + ret = wc_curve25519_import_private_raw(privKey, privKeyLen, + pubKey, pubKeyLen, key); + } + else { + /* Private only */ + ret = wc_curve25519_import_private(privKey, privKeyLen, key); + } + } + else { + /* Try decoding as public key */ + *inOutIdx = 0; /* Reset index */ + pubKeyLen = CURVE25519_KEYSIZE; + ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, + pubKey, &pubKeyLen, X25519k); + if (ret == 0) { + /* Successfully decoded public key */ + ret = wc_curve25519_import_public(pubKey, pubKeyLen, key); + } + } + + return ret; +} + #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */ @@ -35868,6 +36021,63 @@ int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen, } return ret; } + +/* Export Curve25519 key to DER format - handles private only, public only, + * or private+public key pairs based on what's set in the key structure. + * Returns length written on success, negative on error */ +int wc_Curve25519KeyToDer(curve25519_key* key, byte* output, word32 inLen, int withAlg) +{ + int ret; + byte privKey[CURVE25519_KEYSIZE]; + byte pubKey[CURVE25519_PUB_KEY_SIZE]; + word32 privKeyLen = CURVE25519_KEYSIZE; + word32 pubKeyLen = CURVE25519_PUB_KEY_SIZE; + + if (key == NULL) { + return BAD_FUNC_ARG; + } + + /* Check what we have in the key structure */ + if (key->privSet) { + /* Export private key to buffer */ + ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen); + if (ret != 0) { + return ret; + } + + if (key->pubSet) { + /* Export public key if available */ + ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen); + if (ret != 0) { + return ret; + } + /* Export both private and public */ + ret = SetAsymKeyDer(privKey, privKeyLen, + pubKey, pubKeyLen, + output, inLen, X25519k); + } + else { + /* Export private only */ + ret = SetAsymKeyDer(privKey, privKeyLen, + NULL, 0, + output, inLen, X25519k); + } + } + else if (key->pubSet) { + /* Export public key only */ + ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen); + if (ret == 0) { + ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, + output, inLen, X25519k, withAlg); + } + } + else { + /* Neither public nor private key is set */ + ret = BAD_FUNC_ARG; + } + + return ret; +} #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */ #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) @@ -38547,7 +38757,6 @@ static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl) } #endif - #ifndef WOLFSSL_ASN_TEMPLATE static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32* inOutIdx, word32 sz) @@ -38739,7 +38948,34 @@ static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx, } #endif } - /* TODO: Parse CRL Number extension */ + else if (oid == CRL_NUMBER_OID) { + #ifdef WOLFSSL_SMALL_STACK + mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL, + DYNAMIC_TYPE_BIGINT); + if (m == NULL) { + ret = MEMORY_E; + } + #else + mp_int m[1]; + #endif + + if (ret == 0) { + if (mp_init(m) != MP_OKAY) { + ret = MP_INIT_E; + } + } + if (ret == 0) { + ret = GetInt(m, buf, &idx, maxIdx); + } + if (ret == 0) { + dcrl->crlNumber = (int)m->dp[0]; + } + + mp_free(m); + #ifdef WOLFSSL_SMALL_STACK + XFREE(m, NULL, DYNAMIC_TYPE_BIGINT); + #endif + } /* TODO: check criticality */ /* Move index on to next extension. */ idx += (word32)length; @@ -38839,10 +39075,8 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, int ret = 0; int len; word32 idx = 0; -#ifdef WC_RSA_PSS const byte* sigParams = NULL; int sigParamsSz = 0; -#endif WOLFSSL_MSG("ParseCRL"); @@ -40470,12 +40704,12 @@ int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e, void InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, void* heap) { + WOLFSSL_MSG("InitDecodedAcert"); + if (acert == NULL) { return; } - WOLFSSL_MSG("InitDecodedAcert"); - XMEMSET(acert, 0, sizeof(DecodedAcert)); acert->heap = heap; acert->source = source; /* don't own */ @@ -40493,12 +40727,12 @@ void InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, */ void FreeDecodedAcert(DecodedAcert * acert) { + WOLFSSL_MSG("FreeDecodedAcert"); + if (acert == NULL) { return; } - WOLFSSL_MSG("FreeDecodedAcert"); - if (acert->holderIssuerName) { FreeAltNames(acert->holderIssuerName, acert->heap); acert->holderIssuerName = NULL; @@ -40666,6 +40900,7 @@ static int DecodeAcertGeneralName(const byte* input, word32* inOutIdx, * * @param [in] input Buffer holding encoded data. * @param [in] sz Size of encoded data in bytes. + * @param [in] tag ASN.1 tag value expected in header. * @param [in, out] cert Decoded certificate object. * @param [in, out] entries Linked list of DNS name entries. * @@ -40677,7 +40912,7 @@ static int DecodeAcertGeneralName(const byte* input, word32* inOutIdx, * @return MEMORY_E when dynamic memory allocation fails. */ static int DecodeAcertGeneralNames(const byte* input, word32 sz, - DecodedAcert* acert, + byte tag, DecodedAcert* acert, DNS_entry** entries) { word32 idx = 0; @@ -40685,28 +40920,35 @@ static int DecodeAcertGeneralNames(const byte* input, word32 sz, int ret = 0; word32 numNames = 0; - /* Get SEQUENCE and expect all data to be accounted for. */ - if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) { - WOLFSSL_MSG("\tBad Sequence"); + if (GetASNHeader(input, tag, &idx, &length, sz) <= 0) { + WOLFSSL_MSG("error: acert general names: bad header"); return ASN_PARSE_E; } if (length == 0) { - /* There is supposed to be a non-empty sequence here. */ - WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E); + WOLFSSL_MSG("error: acert general names: zero length"); return ASN_PARSE_E; } if ((word32)length + idx != sz) { + #ifdef DEBUG_WOLFSSL + WOLFSSL_MSG_EX("error: acert general names: got %d, expected %d", + (word32)length + idx, sz); + #endif return ASN_PARSE_E; } while ((ret == 0) && (idx < sz)) { ASNGetData dataASN[altNameASN_Length]; + /* Not sure what a reasonable max would be for attribute certs, + * therefore observing WOLFSSL_MAX_ALT_NAMES limit. */ numNames++; if (numNames > WOLFSSL_MAX_ALT_NAMES) { - WOLFSSL_MSG("error: acert: too many subject alternative names"); + #ifdef DEBUG_WOLFSSL + WOLFSSL_MSG_EX("error: acert general names: too many names, %d", + numNames); + #endif ret = ASN_ALT_NAME_E; break; } @@ -40762,13 +41004,15 @@ static const ASNItem HolderASN[] = /* Holder root sequence. */ /* HOLDER_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* Holder Option 0:*/ + /* baseCertificateID [0] IssuerSerial OPTIONAL */ /* ISSUERSERIAL_SEQ */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 2 }, /* issuer GeneralNames, */ /* GN_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 }, /* serial CertificateSerialNumber */ /* SERIAL_INT */ { 2, ASN_INTEGER, 0, 0, 0 }, - /* Holder Option 1:*/ -/* GN_SEQ */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 }, + /* Holder Option 1: */ + /* entityName [1] GeneralNames OPTIONAL */ +/* ENTITYNAME_SEQ */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 }, }; enum { @@ -40807,6 +41051,10 @@ static int DecodeHolder(const byte* input, word32 len, DecodedAcert* acert) return BUFFER_E; } + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + printf("debug: decode holder: holder len: %d\n", len); + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ + CALLOC_ASNGETDATA(dataASN, HolderASN_Length, ret, acert->heap); if (ret != 0) { @@ -40840,20 +41088,50 @@ static int DecodeHolder(const byte* input, word32 len, DecodedAcert* acert) * Use the HOLDER_IDX_GN_SEQ offset for input. */ const byte * gn_input = NULL; word32 gn_len = 0; - word32 holder_index = HOLDER_IDX_GN_SEQ; + byte tag = 0x00; /* Determine which tag was seen. */ if (dataASN[HOLDER_IDX_GN_SEQ].tag != 0) { - gn_input = input + dataASN[holder_index].offset; - gn_len = dataASN[holder_index].length + 2; - } - else { - gn_input = input; - gn_len = len; + gn_input = input + dataASN[HOLDER_IDX_GN_SEQ].offset; + gn_len = dataASN[HOLDER_IDX_GN_SEQ].length; + tag = dataASN[HOLDER_IDX_GN_SEQ].tag; + + if (gn_len >= ASN_LONG_LENGTH) { + gn_len += 3; + } + else { + gn_len += 2; + } + + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + printf("debug: decode holder: holder index: %d\n", + HOLDER_IDX_GN_SEQ); + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ + + ret = DecodeAcertGeneralNames(gn_input, gn_len, tag, acert, + &acert->holderIssuerName); } - ret = DecodeAcertGeneralNames(gn_input, gn_len, acert, - &acert->holderIssuerName); + if (dataASN[HOLDER_IDX_GN_SEQ_OPT1].tag != 0) { + gn_input = input + dataASN[HOLDER_IDX_GN_SEQ_OPT1].offset; + gn_len = dataASN[HOLDER_IDX_GN_SEQ_OPT1].length; + tag = dataASN[HOLDER_IDX_GN_SEQ_OPT1].tag; + + if (gn_len >= ASN_LONG_LENGTH) { + gn_len += 3; + } + else { + gn_len += 2; + } + + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + printf("debug: decode holder: holder index: %d\n", + HOLDER_IDX_GN_SEQ_OPT1); + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ + + ret = DecodeAcertGeneralNames(gn_input, gn_len, tag, acert, + &acert->holderEntityName); + } if (ret != 0) { WOLFSSL_MSG("error: Holder: DecodeAcertGeneralNames failed"); @@ -40866,7 +41144,14 @@ static int DecodeHolder(const byte* input, word32 len, DecodedAcert* acert) return 0; } -/* From RFC 5755. +/* Note on AttCertIssuer field. ACERTs are supposed to follow + * v2form, but some (acert_bc1.pem) follow v1form. Because + * of the limited set of example ACERTs, the v1form will be + * tolerated for now but the field will not be parsed. + * + * More info from RFC below: + * + * From RFC 5755. * 4.2.3. Issuer * * ACs conforming to this profile MUST use the v2Form choice, which MUST @@ -40907,7 +41192,6 @@ enum { #define AttCertIssuerASN_Length (sizeof(AttCertIssuerASN) / sizeof(ASNItem)) /* Decode the AttCertIssuer Field of an x509 attribute certificate. - * * * @param [in] input Buffer containing encoded AttCertIssuer field. * @param [in] len Length of Holder field. @@ -40928,6 +41212,7 @@ static int DecodeAttCertIssuer(const byte* input, word32 len, word32 idx = 0; const byte * gn_input = NULL; word32 gn_len = 0; + byte tag = 0x00; if (input == NULL || len <= 0 || cert == NULL) { return BUFFER_E; @@ -40951,9 +41236,17 @@ static int DecodeAttCertIssuer(const byte* input, word32 len, /* Now parse the GeneralNames field. * Use the HOLDER_IDX_GN_SEQ offset for input. */ gn_input = input + dataASN[ATTCERTISSUER_IDX_GN_SEQ].offset; - gn_len = dataASN[ATTCERTISSUER_IDX_GN_SEQ].length + 2; + gn_len = dataASN[ATTCERTISSUER_IDX_GN_SEQ].length; + tag = dataASN[ATTCERTISSUER_IDX_GN_SEQ].tag; - ret = DecodeAcertGeneralNames(gn_input, gn_len, cert, + if (gn_len >= ASN_LONG_LENGTH) { + gn_len += 3; + } + else { + gn_len += 2; + } + + ret = DecodeAcertGeneralNames(gn_input, gn_len, tag, cert, &cert->AttCertIssuerName); if (ret != 0) { @@ -40981,8 +41274,10 @@ static const ASNItem AcertASN[] = /* holder Holder */ /* ACINFO_HOLDER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 }, /* issuer AttCertIssuer */ -/* ACINFO_CHOICE_SEQ */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 2 }, -/* ACINFO_ISSUER_SEQ */ { 2, ASN_SEQUENCE | 0, 1, 0, 2 }, + /* v2Form [0] V2Form */ +/* ACINFO_ISSUER_V2FORM */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 2 }, + /* v1Form GeneralNames */ +/* ACINFO_ISSUER_V1FORM */ { 2, ASN_SEQUENCE, 1, 0, 2 }, /* signature AlgorithmIdentifier */ /* AlgorithmIdentifier ::= SEQUENCE */ /* ACINFO_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, @@ -41028,8 +41323,9 @@ enum { ACERT_IDX_ACINFO_VER_INT, /* ACINFO holder and issuer */ ACERT_IDX_ACINFO_HOLDER_SEQ, - ACERT_IDX_ACINFO_CHOICE_SEQ, - ACERT_IDX_ACINFO_ISSUER_SEQ, + /* The issuer should be in V2 form, but tolerate V1 for now. */ + ACERT_IDX_ACINFO_ISSUER_V2, + ACERT_IDX_ACINFO_ISSUER_V1, /* ACINFO sig alg*/ ACERT_IDX_ACINFO_ALGOID_SEQ, ACERT_IDX_ACINFO_ALGOID_OID, @@ -41087,6 +41383,8 @@ int ParseX509Acert(DecodedAcert* acert, int verify) byte version = 0; word32 serialSz = EXTERNAL_SERIAL_SIZE; + WOLFSSL_MSG("ParseX509Acert"); + if (acert == NULL) { return BAD_FUNC_ARG; } @@ -41235,8 +41533,14 @@ int ParseX509Acert(DecodedAcert* acert, int verify) /* Determine which issuer tag was seen. We need this to determine * the holder_input. */ - i_issuer = (dataASN[ACERT_IDX_ACINFO_CHOICE_SEQ].tag != 0) ? - ACERT_IDX_ACINFO_CHOICE_SEQ : ACERT_IDX_ACINFO_ISSUER_SEQ; + i_issuer = (dataASN[ACERT_IDX_ACINFO_ISSUER_V2].tag != 0) ? + ACERT_IDX_ACINFO_ISSUER_V2 : ACERT_IDX_ACINFO_ISSUER_V1; + + #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE + printf("debug: parse acert: issuer index: %d\n", i_issuer); + printf("debug: parse acert: issuer seq offset: %d\n", + dataASN[i_issuer].offset); + #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ holder_input = acert->source + dataASN[i_holder].offset; holder_len = dataASN[i_issuer].offset - dataASN[i_holder].offset; @@ -41248,13 +41552,9 @@ int ParseX509Acert(DecodedAcert* acert, int verify) return ret; } - #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE - printf("debug: parse acert:issuer index: %d\n", i_issuer); - #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */ - GetASN_GetConstRef(&dataASN[i_issuer], &issuer_input, &issuer_len); - if (i_issuer == ACERT_IDX_ACINFO_CHOICE_SEQ && issuer_len > 0) { + if (i_issuer == ACERT_IDX_ACINFO_ISSUER_V2 && issuer_len > 0) { /* Try to decode the AttCertIssuer as well. */ ret = DecodeAttCertIssuer(issuer_input, issuer_len, acert); @@ -41373,6 +41673,8 @@ int VerifyX509Acert(const byte* der, word32 derSz, const byte * sigParams = NULL; word32 sigParamsSz = 0; + WOLFSSL_MSG("ParseX509Acert"); + if (der == NULL || pubKey == NULL || derSz == 0 || pubKeySz == 0) { WOLFSSL_MSG("error: VerifyX509Acert: bad args"); return BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/bio.c b/src/wolfcrypt/src/bio.c index ac4eb03..b265456 100644 --- a/src/wolfcrypt/src/bio.c +++ b/src/wolfcrypt/src/bio.c @@ -146,7 +146,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrSz = bio->wrSzReset; } else { @@ -163,7 +163,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && - !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { + !(bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY)) { /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, @@ -200,6 +200,7 @@ int wolfSSL_BIO_method_type(const WOLFSSL_BIO *b) } #ifndef WOLFCRYPT_ONLY +#ifndef NO_TLS /* Helper function to read from WOLFSSL_BIO_SSL type * * returns the number of bytes read on success @@ -231,10 +232,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return ret; } +#endif /* !NO_TLS */ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { @@ -249,7 +251,7 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) } return sz; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY */ /* Used to read data from a WOLFSSL_BIO structure @@ -331,7 +333,7 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) ret = wolfSSL_BIO_SSL_read(bio, buf, len, front); #else WOLFSSL_MSG("WOLFSSL_BIO_SSL used with WOLFCRYPT_ONLY"); @@ -500,7 +502,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } #endif /* WOLFSSL_BASE64_ENCODE */ -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* Helper function for writing to a WOLFSSL_BIO_SSL type * * returns the amount written in bytes on success @@ -531,7 +533,7 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, } return ret; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY && !NO_TLS */ /* Writes to a WOLFSSL_BIO_BIO type. * @@ -601,7 +603,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("one of input parameters is null"); return WOLFSSL_FAILURE; } - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { return WOLFSSL_FAILURE; } @@ -642,7 +644,7 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; @@ -746,7 +748,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* already got eof, again is error */ if (front->eof) { ret = WOLFSSL_FATAL_ERROR; @@ -823,7 +825,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) bio = bio->next; } -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) exit_chain: #endif @@ -866,23 +868,23 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) } switch(cmd) { - case BIO_CTRL_PENDING: - case BIO_CTRL_WPENDING: + case WOLFSSL_BIO_CTRL_PENDING: + case WOLFSSL_BIO_CTRL_WPENDING: ret = (long)wolfSSL_BIO_ctrl_pending(bio); break; - case BIO_CTRL_INFO: + case WOLFSSL_BIO_CTRL_INFO: ret = (long)wolfSSL_BIO_get_mem_data(bio, parg); break; - case BIO_CTRL_FLUSH: + case WOLFSSL_BIO_CTRL_FLUSH: ret = (long)wolfSSL_BIO_flush(bio); break; - case BIO_CTRL_RESET: + case WOLFSSL_BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; #ifdef WOLFSSL_HAVE_BIO_ADDR - case BIO_CTRL_DGRAM_CONNECT: - case BIO_CTRL_DGRAM_SET_PEER: + case WOLFSSL_BIO_CTRL_DGRAM_CONNECT: + case WOLFSSL_BIO_CTRL_DGRAM_SET_PEER: { socklen_t addr_size; if (parg == NULL) { @@ -899,7 +901,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) break; } - case BIO_CTRL_DGRAM_SET_CONNECTED: + case WOLFSSL_BIO_CTRL_DGRAM_SET_CONNECTED: if (parg == NULL) { wolfSSL_BIO_ADDR_clear(&bio->peer_addr); bio->connected = 0; @@ -916,7 +918,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) ret = WOLFSSL_SUCCESS; break; - case BIO_CTRL_DGRAM_QUERY_MTU: + case WOLFSSL_BIO_CTRL_DGRAM_QUERY_MTU: ret = 0; /* not implemented */ break; @@ -1371,7 +1373,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) int closeFlag) { if (!bio || !bufMem || - (closeFlag != BIO_NOCLOSE && closeFlag != BIO_CLOSE)) + (closeFlag != WOLFSSL_BIO_NOCLOSE && closeFlag != WOLFSSL_BIO_CLOSE)) return BAD_FUNC_ARG; if (bio->mem_buf) @@ -1379,7 +1381,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) wolfSSL_BUF_MEM_free(bio->mem_buf); bio->mem_buf = bufMem; - bio->shutdown = closeFlag; + bio->shutdown = closeFlag ? WOLFSSL_BIO_CLOSE : WOLFSSL_BIO_NOCLOSE; bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; @@ -1717,7 +1719,7 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrIdx = bio->wrSzReset; bio->wrSz = bio->wrSzReset; } @@ -1826,7 +1828,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + if (bio->ptr.fh != XBADFILE && bio->shutdown == WOLFSSL_BIO_CLOSE) { XFCLOSE(bio->ptr.fh); } @@ -1839,7 +1841,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } - bio->shutdown = BIO_CLOSE; + bio->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2201,7 +2203,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio->method != NULL && bio->method->ctrlCb != NULL) { WOLFSSL_MSG("Calling custom BIO flush callback"); - return (int)bio->method->ctrlCb(bio, BIO_CTRL_FLUSH, 0, NULL); + return (int)bio->method->ctrlCb(bio, WOLFSSL_BIO_CTRL_FLUSH, 0, NULL); } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) @@ -2387,7 +2389,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->type = WOLFSSL_BIO_SOCKET; } else { - BIO_free(bio); + wolfSSL_BIO_free(bio); bio = NULL; } } @@ -2477,7 +2479,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2506,7 +2508,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; @@ -2516,7 +2518,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } /* Create a socket BIO for using the accept'ed connection */ - new_bio = wolfSSL_BIO_new_socket(newfd, BIO_CLOSE); + new_bio = wolfSSL_BIO_new_socket(newfd, WOLFSSL_BIO_CLOSE); if (new_bio == NULL) { WOLFSSL_MSG("wolfSSL_BIO_new_socket error"); CloseSocket(newfd); @@ -2560,6 +2562,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return ret; } +#ifndef NO_TLS long wolfSSL_BIO_do_handshake(WOLFSSL_BIO *b) { WOLFSSL_ENTER("wolfSSL_BIO_do_handshake"); @@ -2595,7 +2598,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (b->ptr.ssl != NULL) { int rc = wolfSSL_shutdown(b->ptr.ssl); - if (rc == SSL_SHUTDOWN_NOT_DONE) { + if (rc == WOLFSSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ wolfSSL_shutdown(b->ptr.ssl); @@ -2605,6 +2608,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("BIO has no SSL pointer set."); } } +#endif long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { @@ -2682,7 +2686,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else wolfSSL_set_connect_state(ssl); } - if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, BIO_CLOSE) != + if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to set SSL pointer in BIO."); err = 1; @@ -2831,13 +2835,20 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) #else bio->method = method; #endif - bio->shutdown = BIO_CLOSE; /* default to close things */ + bio->shutdown = WOLFSSL_BIO_CLOSE; /* default to close things */ if ((bio->type == WOLFSSL_BIO_SOCKET) || (bio->type == WOLFSSL_BIO_DGRAM)) { bio->num.fd = SOCKET_INVALID; - } else { + } + else if (bio->type == WOLFSSL_BIO_FILE) { +#ifndef NO_FILESYSTEM + bio->ptr.fh = XBADFILE; +#endif + bio->num.fd = SOCKET_INVALID; + } + else { bio->num.length = 0; } bio->init = 1; @@ -2916,7 +2927,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { XMEMCPY(bio->ptr.mem_buf_data, buf, len); - bio->flags |= BIO_FLAGS_MEM_RDONLY; + bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2994,7 +3005,9 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #ifndef NO_FILESYSTEM - if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { + if (bio->type == WOLFSSL_BIO_FILE && + bio->shutdown == WOLFSSL_BIO_CLOSE) + { if (bio->ptr.fh) { XFCLOSE(bio->ptr.fh); } @@ -3007,7 +3020,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #endif - if (bio->shutdown != BIO_NOCLOSE) { + if (bio->shutdown != WOLFSSL_BIO_NOCLOSE) { if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr.mem_buf_data != NULL) { @@ -3409,7 +3422,7 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) if (fp == XBADFILE) return WOLFSSL_BAD_FILE; - if (wolfSSL_BIO_set_fp(b, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(b, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); return WOLFSSL_BAD_FILE; } @@ -3446,7 +3459,7 @@ WOLFSSL_BIO *wolfSSL_BIO_new_file(const char *filename, const char *mode) return bio; } - if (wolfSSL_BIO_set_fp(bio, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); wolfSSL_BIO_free(bio); bio = NULL; diff --git a/src/wolfcrypt/src/camellia.c b/src/wolfcrypt/src/camellia.c index 3425177..bd9ae1b 100644 --- a/src/wolfcrypt/src/camellia.c +++ b/src/wolfcrypt/src/camellia.c @@ -1466,7 +1466,7 @@ static void camellia_decrypt256(const u32 *subkey, u32 *io) static void Camellia_EncryptBlock(const word32 keyBitLength, const unsigned char *plaintext, - const KEY_TABLE_TYPE keyTable, + const WC_CAMELLIA_KEY_TABLE_TYPE keyTable, unsigned char *ciphertext) { u32 tmp[4]; @@ -1497,7 +1497,7 @@ static void Camellia_EncryptBlock(const word32 keyBitLength, static void Camellia_DecryptBlock(const word32 keyBitLength, const unsigned char *ciphertext, - const KEY_TABLE_TYPE keyTable, + const WC_CAMELLIA_KEY_TABLE_TYPE keyTable, unsigned char *plaintext) { u32 tmp[4]; @@ -1529,13 +1529,13 @@ static void Camellia_DecryptBlock(const word32 keyBitLength, /* wolfCrypt wrappers to the Camellia code */ -int wc_CamelliaSetKey(Camellia* cam, const byte* key, word32 len, const byte* iv) +int wc_CamelliaSetKey(wc_Camellia* cam, const byte* key, word32 len, const byte* iv) { int ret = 0; if (cam == NULL) return BAD_FUNC_ARG; - XMEMSET(cam->key, 0, CAMELLIA_TABLE_BYTE_LEN); + XMEMSET(cam->key, 0, WC_CAMELLIA_TABLE_BYTE_LEN); switch (len) { case 16: @@ -1560,21 +1560,21 @@ int wc_CamelliaSetKey(Camellia* cam, const byte* key, word32 len, const byte* iv } -int wc_CamelliaSetIV(Camellia* cam, const byte* iv) +int wc_CamelliaSetIV(wc_Camellia* cam, const byte* iv) { if (cam == NULL) return BAD_FUNC_ARG; if (iv) - XMEMCPY(cam->reg, iv, CAMELLIA_BLOCK_SIZE); + XMEMCPY(cam->reg, iv, WC_CAMELLIA_BLOCK_SIZE); else - XMEMSET(cam->reg, 0, CAMELLIA_BLOCK_SIZE); + XMEMSET(cam->reg, 0, WC_CAMELLIA_BLOCK_SIZE); return 0; } -int wc_CamelliaEncryptDirect(Camellia* cam, byte* out, const byte* in) +int wc_CamelliaEncryptDirect(wc_Camellia* cam, byte* out, const byte* in) { if (cam == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; @@ -1585,7 +1585,7 @@ int wc_CamelliaEncryptDirect(Camellia* cam, byte* out, const byte* in) } -int wc_CamelliaDecryptDirect(Camellia* cam, byte* out, const byte* in) +int wc_CamelliaDecryptDirect(wc_Camellia* cam, byte* out, const byte* in) { if (cam == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; @@ -1596,44 +1596,44 @@ int wc_CamelliaDecryptDirect(Camellia* cam, byte* out, const byte* in) } -int wc_CamelliaCbcEncrypt(Camellia* cam, byte* out, const byte* in, word32 sz) +int wc_CamelliaCbcEncrypt(wc_Camellia* cam, byte* out, const byte* in, word32 sz) { word32 blocks; if (cam == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; } - blocks = sz / CAMELLIA_BLOCK_SIZE; + blocks = sz / WC_CAMELLIA_BLOCK_SIZE; while (blocks--) { - xorbuf((byte*)cam->reg, in, CAMELLIA_BLOCK_SIZE); + xorbuf((byte*)cam->reg, in, WC_CAMELLIA_BLOCK_SIZE); Camellia_EncryptBlock(cam->keySz, (byte*)cam->reg, cam->key, (byte*)cam->reg); - XMEMCPY(out, cam->reg, CAMELLIA_BLOCK_SIZE); + XMEMCPY(out, cam->reg, WC_CAMELLIA_BLOCK_SIZE); - out += CAMELLIA_BLOCK_SIZE; - in += CAMELLIA_BLOCK_SIZE; + out += WC_CAMELLIA_BLOCK_SIZE; + in += WC_CAMELLIA_BLOCK_SIZE; } return 0; } -int wc_CamelliaCbcDecrypt(Camellia* cam, byte* out, const byte* in, word32 sz) +int wc_CamelliaCbcDecrypt(wc_Camellia* cam, byte* out, const byte* in, word32 sz) { word32 blocks; if (cam == NULL || out == NULL || in == NULL) { return BAD_FUNC_ARG; } - blocks = sz / CAMELLIA_BLOCK_SIZE; + blocks = sz / WC_CAMELLIA_BLOCK_SIZE; while (blocks--) { - XMEMCPY(cam->tmp, in, CAMELLIA_BLOCK_SIZE); + XMEMCPY(cam->tmp, in, WC_CAMELLIA_BLOCK_SIZE); Camellia_DecryptBlock(cam->keySz, (byte*)cam->tmp, cam->key, out); - xorbuf(out, (byte*)cam->reg, CAMELLIA_BLOCK_SIZE); - XMEMCPY(cam->reg, cam->tmp, CAMELLIA_BLOCK_SIZE); + xorbuf(out, (byte*)cam->reg, WC_CAMELLIA_BLOCK_SIZE); + XMEMCPY(cam->reg, cam->tmp, WC_CAMELLIA_BLOCK_SIZE); - out += CAMELLIA_BLOCK_SIZE; - in += CAMELLIA_BLOCK_SIZE; + out += WC_CAMELLIA_BLOCK_SIZE; + in += WC_CAMELLIA_BLOCK_SIZE; } return 0; diff --git a/src/wolfcrypt/src/chacha.c b/src/wolfcrypt/src/chacha.c index 84b26eb..ba9aa53 100644 --- a/src/wolfcrypt/src/chacha.c +++ b/src/wolfcrypt/src/chacha.c @@ -76,7 +76,7 @@ Public domain. /* implementation is located in wolfcrypt/src/port/arm/armv8-chacha.c */ #elif defined(WOLFSSL_RISCV_ASM) - /* implementation located in wolfcrypt/src/port/rsicv/riscv-64-chacha.c */ + /* implementation located in wolfcrypt/src/port/riscv/riscv-64-chacha.c */ #else diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index 52c1d2d..2f5d5d4 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -90,7 +90,7 @@ void ShiftAndXorRb(byte* out, byte* in) xorRb = (in[0] & 0x80) != 0; - for (i = 1, j = AES_BLOCK_SIZE - 1; i <= AES_BLOCK_SIZE; i++, j--) { + for (i = 1, j = WC_AES_BLOCK_SIZE - 1; i <= WC_AES_BLOCK_SIZE; i++, j--) { last = (in[j] & 0x80) ? 1 : 0; out[j] = (byte)((in[j] << 1) | mask); mask = last; @@ -165,14 +165,14 @@ int wc_InitCmac_ex(Cmac* cmac, const byte* key, word32 keySz, } if (ret == 0) { - byte l[AES_BLOCK_SIZE]; + byte l[WC_AES_BLOCK_SIZE]; - XMEMSET(l, 0, AES_BLOCK_SIZE); + XMEMSET(l, 0, WC_AES_BLOCK_SIZE); ret = wc_AesEncryptDirect(&cmac->aes, l, l); if (ret == 0) { ShiftAndXorRb(cmac->k1, l); ShiftAndXorRb(cmac->k2, cmac->k1); - ForceZero(l, AES_BLOCK_SIZE); + ForceZero(l, WC_AES_BLOCK_SIZE); } } break; @@ -227,21 +227,21 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) case WC_CMAC_AES: { while ((ret == 0) && (inSz != 0)) { - word32 add = min(inSz, AES_BLOCK_SIZE - cmac->bufferSz); + word32 add = min(inSz, WC_AES_BLOCK_SIZE - cmac->bufferSz); XMEMCPY(&cmac->buffer[cmac->bufferSz], in, add); cmac->bufferSz += add; in += add; inSz -= add; - if (cmac->bufferSz == AES_BLOCK_SIZE && inSz != 0) { + if (cmac->bufferSz == WC_AES_BLOCK_SIZE && inSz != 0) { if (cmac->totalSz != 0) { - xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); + xorbuf(cmac->buffer, cmac->digest, WC_AES_BLOCK_SIZE); } ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, cmac->buffer); if (ret == 0) { - cmac->totalSz += AES_BLOCK_SIZE; + cmac->totalSz += WC_AES_BLOCK_SIZE; cmac->bufferSz = 0; } } @@ -313,30 +313,30 @@ int wc_CmacFinalNoFree(Cmac* cmac, byte* out, word32* outSz) const byte* subKey; word32 remainder; - if (cmac->bufferSz == AES_BLOCK_SIZE) { + if (cmac->bufferSz == WC_AES_BLOCK_SIZE) { subKey = cmac->k1; } else { /* ensure we will have a valid remainder value */ - if (cmac->bufferSz > AES_BLOCK_SIZE) { + if (cmac->bufferSz > WC_AES_BLOCK_SIZE) { ret = BAD_STATE_E; break; } - remainder = AES_BLOCK_SIZE - cmac->bufferSz; + remainder = WC_AES_BLOCK_SIZE - cmac->bufferSz; if (remainder == 0) { - remainder = AES_BLOCK_SIZE; + remainder = WC_AES_BLOCK_SIZE; } if (remainder > 1) { - XMEMSET(cmac->buffer + AES_BLOCK_SIZE - remainder, 0, + XMEMSET(cmac->buffer + WC_AES_BLOCK_SIZE - remainder, 0, remainder); } - cmac->buffer[AES_BLOCK_SIZE - remainder] = 0x80; + cmac->buffer[WC_AES_BLOCK_SIZE - remainder] = 0x80; subKey = cmac->k2; } - xorbuf(cmac->buffer, cmac->digest, AES_BLOCK_SIZE); - xorbuf(cmac->buffer, subKey, AES_BLOCK_SIZE); + xorbuf(cmac->buffer, cmac->digest, WC_AES_BLOCK_SIZE); + xorbuf(cmac->buffer, subKey, WC_AES_BLOCK_SIZE); ret = wc_AesEncryptDirect(&cmac->aes, cmac->digest, cmac->buffer); if (ret == 0) { XMEMCPY(out, cmac->digest, *outSz); @@ -473,7 +473,7 @@ int wc_AesCmacVerify_ex(Cmac* cmac, void* heap, int devId) { int ret = 0; - byte a[AES_BLOCK_SIZE]; + byte a[WC_AES_BLOCK_SIZE]; word32 aSz = sizeof(a); int compareRet; diff --git a/src/wolfcrypt/src/coding.c b/src/wolfcrypt/src/coding.c index aa87ae7..7071796 100644 --- a/src/wolfcrypt/src/coding.c +++ b/src/wolfcrypt/src/coding.c @@ -99,7 +99,7 @@ static WC_INLINE byte Base64_Char2Val(byte c) byte v; byte mask; - c -= BASE64_MIN; + c = (byte)(c - BASE64_MIN); mask = (byte)((((byte)(0x3f - c)) >> 7) - 1); /* Load a value from the first cache line and use when mask set. */ v = (byte)(base64Decode[ c & 0x3f ] & mask); @@ -297,8 +297,10 @@ static int CEscape(int escaped, byte e, byte* out, word32* i, word32 maxSz, if (raw) basic = e; - else + else if (e < sizeof(base64Encode)) basic = base64Encode[e]; + else + return BAD_FUNC_ARG; /* check whether to escape. Only escape for EncodeEsc */ if (escaped == WC_ESC_NL_ENC) { @@ -507,7 +509,7 @@ int Base16_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) return BAD_FUNC_ARG; if (inLen == 1 && *outLen && in) { - byte b = in[inIdx++] - BASE16_MIN; /* 0 starts at 0x30 */ + byte b = (byte)(in[inIdx++] - BASE16_MIN); /* 0 starts at 0x30 */ /* sanity check */ if (b >= sizeof(hexDecode)/sizeof(hexDecode[0])) @@ -531,8 +533,8 @@ int Base16_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) return BAD_FUNC_ARG; while (inLen) { - byte b = in[inIdx++] - BASE16_MIN; /* 0 starts at 0x30 */ - byte b2 = in[inIdx++] - BASE16_MIN; + byte b = (byte)(in[inIdx++] - BASE16_MIN); /* 0 starts at 0x30 */ + byte b2 = (byte)(in[inIdx++] - BASE16_MIN); /* sanity checks */ if (b >= sizeof(hexDecode)/sizeof(hexDecode[0])) @@ -570,14 +572,14 @@ int Base16_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) byte lb = in[i] & 0x0f; /* ASCII value */ - hb += '0'; + hb = (byte)(hb + '0'); if (hb > '9') - hb += 7; + hb = (byte)(hb + 7U); /* ASCII value */ - lb += '0'; + lb = (byte)(lb + '0'); if (lb>'9') - lb += 7; + lb = (byte)(lb + 7U); out[outIdx++] = hb; out[outIdx++] = lb; diff --git a/src/wolfcrypt/src/cpuid.c b/src/wolfcrypt/src/cpuid.c index 6722386..a9f1533 100644 --- a/src/wolfcrypt/src/cpuid.c +++ b/src/wolfcrypt/src/cpuid.c @@ -28,7 +28,8 @@ #include -#if defined(HAVE_CPUID) || defined(HAVE_CPUID_INTEL) +#if defined(HAVE_CPUID) || defined(HAVE_CPUID_INTEL) || \ + defined(HAVE_CPUID_AARCH64) static word32 cpuid_check = 0; static word32 cpuid_flags = 0; #endif @@ -101,6 +102,210 @@ cpuid_check = 1; } } +#elif defined(HAVE_CPUID_AARCH64) + +#define CPUID_AARCH64_FEAT_AES ((word64)1 << 4) +#define CPUID_AARCH64_FEAT_AES_PMULL ((word64)1 << 5) +#define CPUID_AARCH64_FEAT_SHA256 ((word64)1 << 12) +#define CPUID_AARCH64_FEAT_SHA256_512 ((word64)1 << 13) +#define CPUID_AARCH64_FEAT_RDM ((word64)1 << 28) +#define CPUID_AARCH64_FEAT_SHA3 ((word64)1 << 32) +#define CPUID_AARCH64_FEAT_SM3 ((word64)1 << 36) +#define CPUID_AARCH64_FEAT_SM4 ((word64)1 << 40) + +#ifdef WOLFSSL_AARCH64_PRIVILEGE_MODE + /* https://developer.arm.com/documentation/ddi0601/2024-09/AArch64-Registers + * /ID-AA64ISAR0-EL1--AArch64-Instruction-Set-Attribute-Register-0 */ + + void cpuid_set_flags(void) + { + if (!cpuid_check) { + word64 features; + + __asm__ __volatile ( + "mrs %[feat], ID_AA64ISAR0_EL1\n" + : [feat] "=r" (features) + : + : + ); + + if (features & CPUID_AARCH64_FEAT_AES) + cpuid_flags |= CPUID_AES; + if (features & CPUID_AARCH64_FEAT_AES_PMULL) { + cpuid_flags |= CPUID_AES; + cpuid_flags |= CPUID_PMULL; + } + if (features & CPUID_AARCH64_FEAT_SHA256) + cpuid_flags |= CPUID_SHA256; + if (features & CPUID_AARCH64_FEAT_SHA256_512) + cpuid_flags |= CPUID_SHA256 | CPUID_SHA512; + if (features & CPUID_AARCH64_FEAT_RDM) + cpuid_flags |= CPUID_RDM; + if (features & CPUID_AARCH64_FEAT_SHA3) + cpuid_flags |= CPUID_SHA3; + if (features & CPUID_AARCH64_FEAT_SM3) + cpuid_flags |= CPUID_SM3; + if (features & CPUID_AARCH64_FEAT_SM4) + cpuid_flags |= CPUID_SM4; + + cpuid_check = 1; + } + } +#elif defined(__linux__) + /* https://community.arm.com/arm-community-blogs/b/operating-systems-blog/ + * posts/runtime-detection-of-cpu-features-on-an-armv8-a-cpu */ + + #include + #include + + void cpuid_set_flags(void) + { + if (!cpuid_check) { + word64 hwcaps = getauxval(AT_HWCAP); + + if (hwcaps & HWCAP_AES) + cpuid_flags |= CPUID_AES; + if (hwcaps & HWCAP_PMULL) + cpuid_flags |= CPUID_PMULL; + if (hwcaps & HWCAP_SHA2) + cpuid_flags |= CPUID_SHA256; + if (hwcaps & HWCAP_SHA512) + cpuid_flags |= CPUID_SHA512; + if (hwcaps & HWCAP_ASIMDRDM) + cpuid_flags |= CPUID_RDM; + if (hwcaps & HWCAP_SHA3) + cpuid_flags |= CPUID_SHA3; + if (hwcaps & HWCAP_SM3) + cpuid_flags |= CPUID_SM3; + if (hwcaps & HWCAP_SM4) + cpuid_flags |= CPUID_SM4; + + cpuid_check = 1; + } + } +#elif defined(__ANDROID__) || defined(ANDROID) + /* https://community.arm.com/arm-community-blogs/b/operating-systems-blog/ + * posts/runtime-detection-of-cpu-features-on-an-armv8-a-cpu */ + + #include "cpu-features.h" + + void cpuid_set_flags(void) + { + if (!cpuid_check) { + word64 features = android_getCpuFeatures(); + + if (features & ANDROID_CPU_ARM_FEATURE_AES) + cpuid_flags |= CPUID_AES; + if (features & ANDROID_CPU_ARM_FEATURE_PMULL) + cpuid_flags |= CPUID_PMULL; + if (features & ANDROID_CPU_ARM_FEATURE_SHA2) + cpuid_flags |= CPUID_SHA256; + + cpuid_check = 1; + } + } +#elif defined(__APPLE__) + /* https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/ + * determining_instruction_set_characteristics */ + + #include + + static word64 cpuid_get_sysctlbyname(const char* name) + { + word64 ret = 0; + size_t size = sizeof(ret); + + sysctlbyname(name, &ret, &size, NULL, 0); + + return ret; + } + + void cpuid_set_flags(void) + { + if (!cpuid_check) { + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_AES") != 0) + cpuid_flags |= CPUID_AES; + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_PMULL") != 0) + cpuid_flags |= CPUID_PMULL; + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_SHA256") != 0) + cpuid_flags |= CPUID_SHA256; + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_SHA512") != 0) + cpuid_flags |= CPUID_SHA512; + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_RDM") != 0) + cpuid_flags |= CPUID_RDM; + if (cpuid_get_sysctlbyname("hw.optional.arm.FEAT_SHA3") != 0) + cpuid_flags |= CPUID_SHA3; + #ifdef WOLFSSL_ARMASM_CRYPTO_SM3 + cpuid_flags |= CPUID_SM3; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SM4 + cpuid_flags |= CPUID_SM4; + #endif + + cpuid_check = 1; + } + } +#elif defined(__FreeBSD__) || defined(__OpenBSD__) + /* https://man.freebsd.org/cgi/man.cgi?elf_aux_info(3) */ + + #include + + void cpuid_set_flags(void) + { + if (!cpuid_check) { + word64 features = 0; + + elf_aux_info(AT_HWCAP, &features, sizeof(features)); + + if (features & CPUID_AARCH64_FEAT_AES) + cpuid_flags |= CPUID_AES; + if (features & CPUID_AARCH64_FEAT_PMULL) + cpuid_flags |= CPUID_PMULL; + if (features & CPUID_AARCH64_FEAT_SHA256) + cpuid_flags |= CPUID_SHA256; + if (features & CPUID_AARCH64_FEAT_SHA256_512) + cpuid_flags |= CPUID_SHA256 | CPUID_SHA512; + if (features & CPUID_AARCH64_FEAT_RDM) + cpuid_flags |= CPUID_RDM; + if (features & CPUID_AARCH64_FEAT_SHA3) + cpuid_flags |= CPUID_SHA3; + if (features & CPUID_AARCH64_FEAT_SM3) + cpuid_flags |= CPUID_SM3; + if (features & CPUID_AARCH64_FEAT_SM4) + cpuid_flags |= CPUID_SM4; + + cpuid_check = 1; + } + } +#else + void cpuid_set_flags(void) + { + if (!cpuid_check) { + #ifndef WOLFSSL_ARMASM_NO_HW_CRYPTO + cpuid_flags |= CPUID_AES; + cpuid_flags |= CPUID_PMULL; + cpuid_flags |= CPUID_SHA256; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA512 + cpuid_flags |= CPUID_SHA512; + #endif + #ifndef WOLFSSL_AARCH64_NO_SQRMLSH + cpuid_flags |= CPUID_RDM; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 + cpuid_flags |= CPUID_SHA3; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SM3 + cpuid_flags |= CPUID_SM3; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SM4 + cpuid_flags |= CPUID_SM4; + #endif + + cpuid_check = 1; + } + } +#endif #elif defined(HAVE_CPUID) void cpuid_set_flags(void) { diff --git a/src/wolfcrypt/src/cryptocb.c b/src/wolfcrypt/src/cryptocb.c index 4b903dd..973b4f9 100644 --- a/src/wolfcrypt/src/cryptocb.c +++ b/src/wolfcrypt/src/cryptocb.c @@ -65,7 +65,7 @@ typedef struct CryptoCb { CryptoDevCallbackFunc cb; void* ctx; } CryptoCb; -static WOLFSSL_GLOBAL CryptoCb gCryptoDev[MAX_CRYPTO_DEVID_CALLBACKS]; +static WC_THREADSHARED CryptoCb gCryptoDev[MAX_CRYPTO_DEVID_CALLBACKS]; #ifdef WOLF_CRYPTO_CB_FIND static CryptoDevCallbackFind CryptoCb_FindCb = NULL; @@ -85,6 +85,7 @@ static const char* GetAlgoTypeStr(int algo) case WC_ALGO_TYPE_SEED: return "Seed"; case WC_ALGO_TYPE_HMAC: return "HMAC"; case WC_ALGO_TYPE_CMAC: return "CMAC"; + case WC_ALGO_TYPE_CERT: return "Cert"; } return NULL; } @@ -445,8 +446,8 @@ int wc_CryptoCb_Rsa(const byte* in, word32 inLen, byte* out, #ifdef WOLF_CRYPTO_CB_RSA_PAD int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, - word32* outLen, int type, RsaKey* key, WC_RNG* rng, - RsaPadding *padding) + word32* outLen, int type, RsaKey* key, WC_RNG* rng, + RsaPadding *padding) { int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); CryptoCb* dev; @@ -458,9 +459,8 @@ int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, /* locate registered callback */ dev = wc_CryptoCb_FindDevice(key->devId, WC_ALGO_TYPE_PK); - if (padding) { - switch(padding->pad_type) { -#ifndef NO_PKCS11_RSA_PKCS + if (padding != NULL) { + switch (padding->pad_type) { case WC_RSA_PKCSV15_PAD: pk_type = WC_PK_TYPE_RSA_PKCS; break; @@ -470,7 +470,6 @@ int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, case WC_RSA_OAEP_PAD: pk_type = WC_PK_TYPE_RSA_OAEP; break; -#endif /* NO_PKCS11_RSA_PKCS */ default: pk_type = WC_PK_TYPE_RSA; } @@ -497,7 +496,7 @@ int wc_CryptoCb_RsaPad(const byte* in, word32 inLen, byte* out, return wc_CryptoCb_TranslateErrorCode(ret); } -#endif +#endif /* WOLF_CRYPTO_CB_RSA_PAD */ #ifdef WOLFSSL_KEY_GEN int wc_CryptoCb_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) @@ -1801,6 +1800,37 @@ int wc_CryptoCb_RandomSeed(OS_Seed* os, byte* seed, word32 sz) } #endif /* !WC_NO_RNG */ +#ifndef NO_CERTS +int wc_CryptoCb_GetCert(int devId, const char *label, word32 labelLen, + const byte *id, word32 idLen, byte** out, + word32* outSz, int *format, void *heap) +{ + int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); + CryptoCb* dev; + + /* locate registered callback */ + dev = wc_CryptoCb_FindDevice(devId, WC_ALGO_TYPE_CERT); + if (dev && dev->cb) { + wc_CryptoInfo cryptoInfo; + XMEMSET(&cryptoInfo, 0, sizeof(cryptoInfo)); + cryptoInfo.algo_type = WC_ALGO_TYPE_CERT; + cryptoInfo.cert.label = label; + cryptoInfo.cert.labelLen = labelLen; + cryptoInfo.cert.id = id; + cryptoInfo.cert.idLen = idLen; + cryptoInfo.cert.heap = heap; + cryptoInfo.cert.certDataOut = out; + cryptoInfo.cert.certSz = outSz; + cryptoInfo.cert.certFormatOut = format; + cryptoInfo.cert.heap = heap; + + ret = dev->cb(dev->devId, &cryptoInfo, dev->ctx); + } + + return wc_CryptoCb_TranslateErrorCode(ret); +} +#endif /* ifndef NO_CERTS */ + #if defined(WOLFSSL_CMAC) int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, const byte* in, word32 inSz, byte* out, word32* outSz, int type, diff --git a/src/wolfcrypt/src/curve25519.c b/src/wolfcrypt/src/curve25519.c index 7641055..8f409da 100644 --- a/src/wolfcrypt/src/curve25519.c +++ b/src/wolfcrypt/src/curve25519.c @@ -54,7 +54,7 @@ #if defined(WOLFSSL_LINUXKM) && !defined(USE_INTEL_SPEEDUP) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif diff --git a/src/wolfcrypt/src/des3.c b/src/wolfcrypt/src/des3.c index 93bdde2..d6c3923 100644 --- a/src/wolfcrypt/src/des3.c +++ b/src/wolfcrypt/src/des3.c @@ -163,8 +163,13 @@ STM32_HAL_TIMEOUT); } /* save off IV */ - des->reg[0] = hcryp.Instance->IV0LR; - des->reg[1] = hcryp.Instance->IV0RR; + #ifdef WOLFSSL_STM32MP13 + des->reg[0] = ((CRYP_TypeDef *)(hcryp.Instance))->IV0LR; + des->reg[1] = ((CRYP_TypeDef *)(hcryp.Instance))->IV0RR; + #else + des->reg[0] = hcryp.Instance->IV0LR; + des->reg[1] = hcryp.Instance->IV0RR; + #endif #else while (sz > 0) { /* if input and output same will overwrite input iv */ @@ -324,8 +329,13 @@ STM32_HAL_TIMEOUT); } /* save off IV */ - des->reg[0] = hcryp.Instance->IV0LR; - des->reg[1] = hcryp.Instance->IV0RR; + #ifdef WOLFSSL_STM32MP13 + des->reg[0] = ((CRYP_TypeDef *)(hcryp.Instance))->IV0LR; + des->reg[1] = ((CRYP_TypeDef *)(hcryp.Instance))->IV0RR; + #else + des->reg[0] = hcryp.Instance->IV0LR; + des->reg[1] = hcryp.Instance->IV0RR; + #endif #else while (sz > 0) { if (dir == DES_ENCRYPTION) { diff --git a/src/wolfcrypt/src/dh.c b/src/wolfcrypt/src/dh.c index 610b4b6..5258e82 100644 --- a/src/wolfcrypt/src/dh.c +++ b/src/wolfcrypt/src/dh.c @@ -67,7 +67,7 @@ #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif diff --git a/src/wolfcrypt/src/dilithium.c b/src/wolfcrypt/src/dilithium.c index ce01042..6391da4 100644 --- a/src/wolfcrypt/src/dilithium.c +++ b/src/wolfcrypt/src/dilithium.c @@ -2761,8 +2761,8 @@ static int dilithium_vec_expand_mask(wc_Shake* shake256, byte* seed, word16 n = kappa + r; /* Step 4: Append to seed and squeeze out data. */ - seed[DILITHIUM_PRIV_RAND_SEED_SZ + 0] = n; - seed[DILITHIUM_PRIV_RAND_SEED_SZ + 1] = n >> 8; + seed[DILITHIUM_PRIV_RAND_SEED_SZ + 0] = (byte)n; + seed[DILITHIUM_PRIV_RAND_SEED_SZ + 1] = (byte)(n >> 8); ret = dilithium_squeeze256(shake256, seed, DILITHIUM_Y_SEED_SZ, v, DILITHIUM_MAX_V_BLOCKS); if (ret == 0) { @@ -9501,6 +9501,29 @@ int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, #ifndef WOLFSSL_DILITHIUM_NO_ASN1 +/* Maps ASN.1 OID to wolfCrypt security level macros */ +static int mapOidToSecLevel(word32 oid) +{ + switch (oid) { + case ML_DSA_LEVEL2k: + return WC_ML_DSA_44; + case ML_DSA_LEVEL3k: + return WC_ML_DSA_65; + case ML_DSA_LEVEL5k: + return WC_ML_DSA_87; +#ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + case DILITHIUM_LEVEL2k: + return WC_ML_DSA_44_DRAFT; + case DILITHIUM_LEVEL3k: + return WC_ML_DSA_65_DRAFT; + case DILITHIUM_LEVEL5k: + return WC_ML_DSA_87_DRAFT; +#endif + default: + return ASN_UNKNOWN_OID_E; + } +} + #if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) /* Decode the DER encoded Dilithium key. @@ -9508,11 +9531,19 @@ int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, * @param [in] input Array holding DER encoded data. * @param [in, out] inOutIdx On in, index into array of start of DER encoding. * On out, index into array after DER encoding. - * @param [in, out] key Dilithium key to store key. - * @param [in] inSz Total size of data in array. + * @param [in, out] key Dilithium key structure to hold the decoded key. + * If the security level is set in the key structure + * on input, the DER key will be decoded as such and + * will fail if there is a mismatch. If the level + * and parameters are not set in the key structure on + * input, the level will be detected from the DER + * file based on the algorithm OID, appropriately + * decoded, then updated in the key structure on + * output. Auto-detection of the security level is + * not supported if compiled for FIPS 204 draft mode. + * @param [in] inSz Total size of the input DER buffer array. * @return 0 on success. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL or inSz is 0. - * @return BAD_FUNC_ARG when level not set. * @return Other negative on parse error. */ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, @@ -9557,15 +9588,27 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, keytype = ML_DSA_LEVEL5k; } else { - /* Level not set. */ - ret = BAD_FUNC_ARG; + /* Level not set by caller, decode from DER */ + keytype = ANONk; /* 0, not a valid key type in this situation*/ } } if (ret == 0) { /* Decode the asymmetric key and get out private and public key data. */ - ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &privKey, &privKeyLen, - &pubKey, &pubKeyLen, keytype); + ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, + &privKey, &privKeyLen, + &pubKey, &pubKeyLen, &keytype); + if (ret == 0 +#ifdef WOLFSSL_WC_DILITHIUM + && key->params == NULL +#endif + ) { + /* Set the security level based on the decoded key. */ + ret = mapOidToSecLevel(keytype); + if (ret > 0) { + ret = wc_dilithium_set_level(key, ret); + } + } } if ((ret == 0) && (pubKey == NULL) && (pubKeyLen == 0)) { /* Check if the public key is included in the private key. */ @@ -9756,7 +9799,17 @@ static int dilithium_check_type(const byte* input, word32* inOutIdx, byte type, * @param [in] input Array holding DER encoded data. * @param [in, out] inOutIdx On in, index into array of start of DER encoding. * On out, index into array after DER encoding. - * @param [in, out] key Dilithium key to store key. + * @param [in, out] key Dilithium key structure to hold the decoded key. + * If the security level is set in the key structure + * on input, the DER key will be decoded as such + * and will fail if there is a mismatch. If the level + * and parameters are not set in the key structure on + * input, the level will be detected from the DER + * file based on the algorithm OID, appropriately + * decoded, then updated in the key structure on + * output. Auto-detection of the security level is + * not supported if compiled for FIPS 204 + * draft mode. * @param [in] inSz Total size of data in array. * @return 0 on success. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL or inSz is 0. @@ -9818,13 +9871,25 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, keytype = ML_DSA_LEVEL5k; } else { - /* Level not set. */ - ret = BAD_FUNC_ARG; + /* Level not set by caller, decode from DER */ + keytype = ANONk; /* 0, not a valid key type in this situation*/ } if (ret == 0) { /* Decode the asymmetric key and get out public key data. */ - ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKey, - &pubKeyLen, keytype); + ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, + &pubKey, &pubKeyLen, + &keytype); + if (ret == 0 +#ifdef WOLFSSL_WC_DILITHIUM + && key->params == NULL +#endif + ) { + /* Set the security level based on the decoded key. */ + ret = mapOidToSecLevel(keytype); + if (ret > 0) { + ret = wc_dilithium_set_level(key, ret); + } + } } #else /* Get OID sum for level. */ diff --git a/src/wolfcrypt/src/dsa.c b/src/wolfcrypt/src/dsa.c index 6ed4435..7fb7945 100644 --- a/src/wolfcrypt/src/dsa.c +++ b/src/wolfcrypt/src/dsa.c @@ -45,7 +45,7 @@ #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif @@ -173,7 +173,7 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) return MEMORY_E; } - SAVE_VECTOR_REGISTERS(); + SAVE_VECTOR_REGISTERS(;); #ifdef WOLFSSL_SMALL_STACK if ((tmpQ = (mp_int *)XMALLOC(sizeof(*tmpQ), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) @@ -1112,32 +1112,32 @@ int wc_DsaVerify_ex(const byte* digest, word32 digestSz, const byte* sig, #ifdef WOLFSSL_SMALL_STACK if (s) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(s); XFREE(s, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (r) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(r); XFREE(r, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (u1) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(u1); XFREE(u1, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (u2) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(u2); XFREE(u2, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (w) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(w); XFREE(w, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (v) { - if (ret != WC_NO_ERR_TRACE(MP_INIT_E)) + if (ret != WC_NO_ERR_TRACE(MP_INIT_E) && ret != WC_NO_ERR_TRACE(MEMORY_E)) mp_clear(v); XFREE(v, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index da6505c..f010568 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -104,6 +104,9 @@ Possible ECC enable options: * unmasked copy is computed and stored each time it is * needed. * default: off + * WOLFSSL_CHECK_VER_FAULTS + * Sanity check on verification steps in case of faults. + * default: off */ /* @@ -231,7 +234,7 @@ ECC Curve Sizes: #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif @@ -1642,7 +1645,7 @@ static void wc_ecc_curve_cache_free_spec_item(ecc_curve_spec* curve, mp_int* ite #endif mp_clear(item); } - curve->load_mask &= ~mask; + curve->load_mask = (byte)(curve->load_mask & ~mask); } static void wc_ecc_curve_cache_free_spec(ecc_curve_spec* curve) { @@ -8880,9 +8883,12 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, #endif mp_int* e; mp_int* v = NULL; /* Will be w. */ +#if defined(WOLFSSL_CHECK_VER_FAULTS) && defined(WOLFSSL_NO_MALLOC) + mp_int u1tmp[1]; + mp_int u2tmp[1]; +#endif mp_int* u1 = NULL; /* Will be e. */ mp_int* u2 = NULL; /* Will be w. */ - #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) { @@ -8970,13 +8976,33 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, #endif if (err == MP_OKAY) { +#ifdef WOLFSSL_CHECK_VER_FAULTS + #ifndef WOLFSSL_NO_MALLOC + u1 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + u2 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC); + if (u1 == NULL || u2 == NULL) + err = MEMORY_E; + #else + u1 = u1tmp; + u2 = u2tmp; + #endif +#else u1 = e; u2 = w; +#endif v = w; } if (err == MP_OKAY) { err = INIT_MP_INT_SIZE(w, ECC_KEY_MAX_BITS_NONULLCHECK(key)); } +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(u1, ECC_KEY_MAX_BITS_NONULLCHECK(key)); + } + if (err == MP_OKAY) { + err = INIT_MP_INT_SIZE(u2, ECC_KEY_MAX_BITS_NONULLCHECK(key)); + } +#endif /* allocate points */ if (err == MP_OKAY) { @@ -9000,10 +9026,22 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, if (err == MP_OKAY) err = mp_mulmod(e, w, curve->order, u1); +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY && mp_iszero(e) != MP_YES && mp_cmp(u1, e) == MP_EQ) { + err = BAD_STATE_E; + } +#endif + /* u2 = rw */ if (err == MP_OKAY) err = mp_mulmod(r, w, curve->order, u2); +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY && mp_cmp(u2, w) == MP_EQ) { + err = BAD_STATE_E; + } +#endif + /* find mG and mQ */ if (err == MP_OKAY) err = mp_copy(curve->Gx, mG->x); @@ -9031,16 +9069,35 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, #ifndef ECC_SHAMIR if (err == MP_OKAY) { + #ifdef WOLFSSL_CHECK_VER_FAULTS + ecc_point mG1, mQ1; + wc_ecc_copy_point(mQ, &mQ1); + wc_ecc_copy_point(mG, &mG1); + #endif + mp_digit mp = 0; if (!mp_iszero((MP_INT_SIZE*)u1)) { /* compute u1*mG + u2*mQ = mG */ err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0, key->heap); + #ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY && wc_ecc_cmp_point(mG, &mG1) == MP_EQ) { + err = BAD_STATE_E; + } + + /* store new value for comparing with after add operation */ + wc_ecc_copy_point(mG, &mG1); + #endif if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap); } + #ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY && wc_ecc_cmp_point(mQ, &mQ1) == MP_EQ) { + err = BAD_STATE_E; + } + #endif /* find the montgomery mp */ if (err == MP_OKAY) @@ -9050,6 +9107,14 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, if (err == MP_OKAY) err = ecc_projective_add_point_safe(mQ, mG, mG, curve->Af, curve->prime, mp, NULL); + #ifdef WOLFSSL_CHECK_VER_FAULTS + if (err == MP_OKAY && wc_ecc_cmp_point(mG, &mG1) == MP_EQ) { + err = BAD_STATE_E; + } + if (err == MP_OKAY && wc_ecc_cmp_point(mG, mQ) == MP_EQ) { + err = BAD_STATE_E; + } + #endif } else { /* compute 0*mG + u2*mQ = mG */ @@ -9072,6 +9137,7 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, } #endif /* ECC_SHAMIR */ #endif /* FREESCALE_LTC_ECC */ + /* v = X_x1 mod n */ if (err == MP_OKAY) err = mp_mod(mG->x, curve->order, v); @@ -9080,6 +9146,11 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, if (err == MP_OKAY) { if (mp_cmp(v, r) == MP_EQ) *res = 1; +#ifdef WOLFSSL_CHECK_VER_FAULTS + /* redundant comparison as sanity check that first one happened */ + if (*res == 1 && mp_cmp(r, v) != MP_EQ) + *res = 0; +#endif } /* cleanup */ @@ -9089,6 +9160,14 @@ static int ecc_verify_hash(mp_int *r, mp_int *s, const byte* hash, mp_clear(e); mp_clear(w); FREE_MP_INT_SIZE(w, key->heap, DYNAMIC_TYPE_ECC); +#ifdef WOLFSSL_CHECK_VER_FAULTS + mp_clear(u1); + mp_clear(u2); +#ifndef WOLFSSL_NO_MALLOC + XFREE(u1, key->heap, DYNAMIC_TYPE_ECC); + XFREE(u2, key->heap, DYNAMIC_TYPE_ECC); +#endif +#endif #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) FREE_MP_INT_SIZE(e_lcl, key->heap, DYNAMIC_TYPE_ECC); #endif @@ -12593,20 +12672,22 @@ static int build_lut(int idx, mp_int* a, mp_int* modulus, mp_digit mp, /* make all single bit entries */ for (x = 1; x < FP_LUT; x++) { - if ((mp_copy(fp_cache[idx].LUT[1<<(x-1)]->x, - fp_cache[idx].LUT[1<x) != MP_OKAY) || - (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->y, - fp_cache[idx].LUT[1<y) != MP_OKAY) || - (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->z, - fp_cache[idx].LUT[1<z) != MP_OKAY)){ + if ((mp_copy(fp_cache[idx].LUT[(unsigned int)(1 << (x-1))]->x, + fp_cache[idx].LUT[(unsigned int)(1 << x )]->x) != MP_OKAY) || + (mp_copy(fp_cache[idx].LUT[(unsigned int)(1 << (x-1))]->y, + fp_cache[idx].LUT[(unsigned int)(1 << x )]->y) != MP_OKAY) || + (mp_copy(fp_cache[idx].LUT[(unsigned int)(1 << (x-1))]->z, + fp_cache[idx].LUT[(unsigned int)(1 << x )]->z) != MP_OKAY)) { err = MP_INIT_E; goto errout; } else { /* now double it bitlen/FP_LUT times */ for (y = 0; y < lut_gap; y++) { - if ((err = ecc_projective_dbl_point_safe(fp_cache[idx].LUT[1<>3] >> (bitpos&7)) & 1) << y; + z |= (((word32)kb[bitpos>>3U] >> (bitpos&7U)) & 1U) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } @@ -13062,8 +13143,8 @@ static int accel_fp_mul2add(int idx1, int idx2, offset by x bits from the start */ bitpos = (unsigned)x; for (y = zA = zB = 0; y < FP_LUT; y++) { - zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y; - zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y; + zA |= (((word32)kb[0][bitpos>>3U] >> (bitpos&7U)) & 1U) << y; + zB |= (((word32)kb[1][bitpos>>3U] >> (bitpos&7U)) & 1U) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } @@ -13173,7 +13254,7 @@ int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) { int idx1 = -1, idx2 = -1, err, mpInit = 0; - mp_digit mp; + mp_digit mp = 0; #ifdef WOLFSSL_SMALL_STACK mp_int *mu = (mp_int *)XMALLOC(sizeof *mu, NULL, DYNAMIC_TYPE_ECC_BUFFER); @@ -13321,7 +13402,7 @@ int wc_ecc_mulmod_ex(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, { #if !defined(WOLFSSL_SP_MATH) int idx, err = MP_OKAY; - mp_digit mp; + mp_digit mp = 0; #ifdef WOLFSSL_SMALL_STACK mp_int *mu = NULL; #else @@ -13497,7 +13578,7 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, { #if !defined(WOLFSSL_SP_MATH) int idx, err = MP_OKAY; - mp_digit mp; + mp_digit mp = 0; #ifdef WOLFSSL_SMALL_STACK mp_int *mu = NULL; #else @@ -14073,12 +14154,12 @@ static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz, case ecAES_128_CBC: *encKeySz = KEY_SIZE_128; *ivSz = IV_SIZE_128; - *blockSz = AES_BLOCK_SIZE; + *blockSz = WC_AES_BLOCK_SIZE; break; case ecAES_256_CBC: *encKeySz = KEY_SIZE_256; *ivSz = IV_SIZE_128; - *blockSz = AES_BLOCK_SIZE; + *blockSz = WC_AES_BLOCK_SIZE; break; #endif #if !defined(NO_AES) && defined(WOLFSSL_AES_COUNTER) @@ -14375,7 +14456,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, case ecAES_256_CTR: { #if !defined(NO_AES) && defined(WOLFSSL_AES_COUNTER) - byte ctr_iv[AES_BLOCK_SIZE]; + byte ctr_iv[WC_AES_BLOCK_SIZE]; #ifndef WOLFSSL_SMALL_STACK Aes aes[1]; #else @@ -14390,7 +14471,7 @@ int wc_ecc_encrypt_ex(ecc_key* privKey, ecc_key* pubKey, const byte* msg, /* Include 4 byte counter starting at all zeros. */ XMEMCPY(ctr_iv, encIv, WOLFSSL_ECIES_GEN_IV_SIZE); XMEMSET(ctr_iv + WOLFSSL_ECIES_GEN_IV_SIZE, 0, - AES_BLOCK_SIZE - WOLFSSL_ECIES_GEN_IV_SIZE); + WC_AES_BLOCK_SIZE - WOLFSSL_ECIES_GEN_IV_SIZE); ret = wc_AesInit(aes, NULL, INVALID_DEVID); if (ret == 0) { @@ -14852,11 +14933,11 @@ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, #endif ret = wc_AesInit(aes, NULL, INVALID_DEVID); if (ret == 0) { - byte ctr_iv[AES_BLOCK_SIZE]; + byte ctr_iv[WC_AES_BLOCK_SIZE]; /* Make a 16 byte IV from the bytes passed in. */ XMEMCPY(ctr_iv, encIv, WOLFSSL_ECIES_GEN_IV_SIZE); XMEMSET(ctr_iv + WOLFSSL_ECIES_GEN_IV_SIZE, 0, - AES_BLOCK_SIZE - WOLFSSL_ECIES_GEN_IV_SIZE); + WC_AES_BLOCK_SIZE - WOLFSSL_ECIES_GEN_IV_SIZE); ret = wc_AesSetKey(aes, encKey, (word32)encKeySz, ctr_iv, AES_ENCRYPTION); if (ret == 0) { diff --git a/src/wolfcrypt/src/eccsi.c b/src/wolfcrypt/src/eccsi.c index 2be700f..79b7a65 100644 --- a/src/wolfcrypt/src/eccsi.c +++ b/src/wolfcrypt/src/eccsi.c @@ -46,7 +46,7 @@ #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif diff --git a/src/wolfcrypt/src/ed25519.c b/src/wolfcrypt/src/ed25519.c index 09777dd..fd80f86 100644 --- a/src/wolfcrypt/src/ed25519.c +++ b/src/wolfcrypt/src/ed25519.c @@ -48,6 +48,7 @@ #include #include +#include #include #include #ifdef NO_INLINE @@ -628,6 +629,35 @@ int wc_ed25519ph_sign_msg(const byte* in, word32 inLen, byte* out, #ifdef HAVE_ED25519_VERIFY #ifndef WOLFSSL_SE050 + +#ifdef WOLFSSL_CHECK_VER_FAULTS +static const byte sha512_empty[] = { + 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, + 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, + 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, + 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, + 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, + 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, + 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, + 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e +}; + +/* sanity check that hash operation happened + * returns 0 on success */ +static int ed25519_hash_check(ed25519_key* key, byte* h) +{ + (void)key; /* passing in key in case other hash algroithms are used */ + + if (XMEMCMP(h, sha512_empty, WC_SHA512_DIGEST_SIZE) != 0) { + return 0; + } + else { + return BAD_STATE_E; + } +} +#endif + + /* sig is array of bytes containing the signature sigLen is the length of sig byte array @@ -675,6 +705,22 @@ static int ed25519_verify_msg_init_with_sha(const byte* sig, word32 sigLen, } if (ret == 0) ret = ed25519_hash_update(key, sha, sig, ED25519_SIG_SIZE/2); + +#ifdef WOLFSSL_CHECK_VER_FAULTS + /* sanity check that hash operation happened */ + if (ret == 0) { + byte h[WC_MAX_DIGEST_SIZE]; + + ret = wc_Sha512GetHash(sha, h); + if (ret == 0) { + ret = ed25519_hash_check(key, h); + if (ret != 0) { + WOLFSSL_MSG("Unexpected initial state of hash found"); + } + } + } +#endif + if (ret == 0) ret = ed25519_hash_update(key, sha, key->p, ED25519_PUB_KEY_SIZE); @@ -791,7 +837,16 @@ static int ed25519_verify_msg_final_with_sha(const byte* sig, word32 sigLen, ret = ConstantCompare(rcheck, sig, ED25519_SIG_SIZE/2); if (ret != 0) { ret = SIG_VERIFY_E; - } else { + } + +#ifdef WOLFSSL_CHECK_VER_FAULTS + /* redundant comparison as sanity check that first one happened */ + if (ret == 0 && ConstantCompare(rcheck, sig, ED25519_SIG_SIZE/2) != 0) { + ret = SIG_VERIFY_E; + } +#endif + + if (ret == 0) { /* set the verification status */ *res = 1; } diff --git a/src/wolfcrypt/src/error.c b/src/wolfcrypt/src/error.c index deedcbe..0deb668 100644 --- a/src/wolfcrypt/src/error.c +++ b/src/wolfcrypt/src/error.c @@ -44,6 +44,9 @@ const char* wc_GetErrorString(int error) { switch ((enum wolfCrypt_ErrorCodes)error) { + case WC_FAILURE: + return "wolfCrypt generic failure"; + case MP_MEM : return "MP integer dynamic memory allocation failed"; @@ -642,11 +645,14 @@ const char* wc_GetErrorString(int error) case PBKDF2_KAT_FIPS_E: return "wolfCrypt FIPS PBKDF2 Known Answer Test Failure"; + case DEADLOCK_AVERTED_E: + return "Deadlock averted -- retry the call"; + case MAX_CODE_E: + case WC_SPAN1_MIN_CODE_E: case MIN_CODE_E: default: return "unknown error number"; - } } @@ -660,4 +666,3 @@ void wc_ErrorString(int error, char* buffer) buffer[WOLFSSL_MAX_ERROR_SZ-1] = 0; } #endif /* !NO_ERROR_STRINGS */ - diff --git a/src/wolfcrypt/src/evp.c b/src/wolfcrypt/src/evp.c index 808aa04..c3eb12e 100644 --- a/src/wolfcrypt/src/evp.c +++ b/src/wolfcrypt/src/evp.c @@ -41,7 +41,6 @@ #include #endif - #include #include #include @@ -53,67 +52,67 @@ static const struct s_ent { const char *name; } md_tbl[] = { #ifndef NO_MD4 - {WC_HASH_TYPE_MD4, NID_md4, "MD4"}, + {WC_HASH_TYPE_MD4, WC_NID_md4, "MD4"}, #endif /* NO_MD4 */ #ifndef NO_MD5 - {WC_HASH_TYPE_MD5, NID_md5, "MD5"}, + {WC_HASH_TYPE_MD5, WC_NID_md5, "MD5"}, #endif /* NO_MD5 */ #ifndef NO_SHA - {WC_HASH_TYPE_SHA, NID_sha1, "SHA1"}, - {WC_HASH_TYPE_SHA, NID_sha1, "SHA"}, /* Leave for backwards compatibility */ + {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA1"}, + {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA"}, /* Leave for backwards compatibility */ #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - {WC_HASH_TYPE_SHA224, NID_sha224, "SHA224"}, + {WC_HASH_TYPE_SHA224, WC_NID_sha224, "SHA224"}, #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 - {WC_HASH_TYPE_SHA256, NID_sha256, "SHA256"}, + {WC_HASH_TYPE_SHA256, WC_NID_sha256, "SHA256"}, #endif #ifdef WOLFSSL_SHA384 - {WC_HASH_TYPE_SHA384, NID_sha384, "SHA384"}, + {WC_HASH_TYPE_SHA384, WC_NID_sha384, "SHA384"}, #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 - {WC_HASH_TYPE_SHA512, NID_sha512, "SHA512"}, + {WC_HASH_TYPE_SHA512, WC_NID_sha512, "SHA512"}, #endif /* WOLFSSL_SHA512 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - {WC_HASH_TYPE_SHA512_224, NID_sha512_224, "SHA512_224"}, + {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, "SHA512_224"}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - {WC_HASH_TYPE_SHA512_256, NID_sha512_256, "SHA512_256"}, + {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, "SHA512_256"}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ #ifndef WOLFSSL_NOSHA3_224 - {WC_HASH_TYPE_SHA3_224, NID_sha3_224, "SHA3_224"}, + {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, "SHA3_224"}, #endif #ifndef WOLFSSL_NOSHA3_256 - {WC_HASH_TYPE_SHA3_256, NID_sha3_256, "SHA3_256"}, + {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, "SHA3_256"}, #endif #ifndef WOLFSSL_NOSHA3_384 - {WC_HASH_TYPE_SHA3_384, NID_sha3_384, "SHA3_384"}, + {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, "SHA3_384"}, #endif #ifndef WOLFSSL_NOSHA3_512 - {WC_HASH_TYPE_SHA3_512, NID_sha3_512, "SHA3_512"}, + {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, "SHA3_512"}, #endif #ifdef WOLFSSL_SM3 - {WC_HASH_TYPE_SM3, NID_sm3, "SM3"}, + {WC_HASH_TYPE_SM3, WC_NID_sm3, "SM3"}, #endif /* WOLFSSL_SHA512 */ #ifdef HAVE_BLAKE2 - {WC_HASH_TYPE_BLAKE2B, NID_blake2b512, "BLAKE2B512"}, + {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, "BLAKE2B512"}, #endif #ifdef HAVE_BLAKE2S - {WC_HASH_TYPE_BLAKE2S, NID_blake2s256, "BLAKE2S256"}, + {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, "BLAKE2S256"}, #endif #ifdef WOLFSSL_SHAKE128 - {WC_HASH_TYPE_SHAKE128, NID_shake128, "SHAKE128"}, + {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, "SHAKE128"}, #endif #ifdef WOLFSSL_SHAKE256 - {WC_HASH_TYPE_SHAKE256, NID_shake256, "SHAKE256"}, + {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, "SHAKE256"}, #endif {WC_HASH_TYPE_NONE, 0, NULL} }; @@ -158,6 +157,7 @@ static const struct s_ent { (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 static const char EVP_AES_128_CFB1[] = "AES-128-CFB1"; #endif @@ -177,6 +177,7 @@ static const struct s_ent { #ifdef WOLFSSL_AES_256 static const char EVP_AES_256_CFB8[] = "AES-256-CFB8"; #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 static const char EVP_AES_128_CFB128[] = "AES-128-CFB128"; @@ -287,21 +288,21 @@ static const struct pkey_type_name_ent { int type; const char *name; } pkey_type_names[] = { - { EVP_PKEY_RSA, "RSA" }, - { EVP_PKEY_EC, "EC" }, - { EVP_PKEY_DH, "DH" }, - { EVP_PKEY_DSA, "DSA" } + { WC_EVP_PKEY_RSA, "RSA" }, + { WC_EVP_PKEY_EC, "EC" }, + { WC_EVP_PKEY_DH, "DH" }, + { WC_EVP_PKEY_DSA, "DSA" } }; static int pkey_type_by_name(const char *name) { unsigned int i; if (name == NULL) - return EVP_PKEY_NONE; + return WC_EVP_PKEY_NONE; for (i = 0; i < XELEM_CNT(pkey_type_names); ++i) { if (XSTRCMP(name, pkey_type_names[i].name) == 0) return pkey_type_names[i].type; } - return EVP_PKEY_NONE; + return WC_EVP_PKEY_NONE; } int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { @@ -311,7 +312,7 @@ int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { return WOLFSSL_FAILURE; type = pkey_type_by_name(name); - if (type == EVP_PKEY_NONE) + if (type == WC_EVP_PKEY_NONE) return WOLFSSL_FAILURE; return (pkey->type == type) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; @@ -319,8 +320,8 @@ int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { #define EVP_CIPHER_TYPE_MATCHES(x, y) (XSTRCMP(x,y) == 0) -#define EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 -#define EVP_PKEY_PRINT_DIGITS_PER_LINE 15 +#define WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 +#define WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE 15 static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher); @@ -346,81 +347,81 @@ int wolfSSL_EVP_Cipher_key_length(const WOLFSSL_EVP_CIPHER* c) switch (cipherType(c)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: return 16; - case AES_192_CBC_TYPE: return 24; - case AES_256_CBC_TYPE: return 32; + case WC_AES_128_CBC_TYPE: return 16; + case WC_AES_192_CBC_TYPE: return 24; + case WC_AES_256_CBC_TYPE: return 32; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: return 16; - case AES_192_CFB1_TYPE: return 24; - case AES_256_CFB1_TYPE: return 32; - case AES_128_CFB8_TYPE: return 16; - case AES_192_CFB8_TYPE: return 24; - case AES_256_CFB8_TYPE: return 32; - case AES_128_CFB128_TYPE: return 16; - case AES_192_CFB128_TYPE: return 24; - case AES_256_CFB128_TYPE: return 32; + case WC_AES_128_CFB1_TYPE: return 16; + case WC_AES_192_CFB1_TYPE: return 24; + case WC_AES_256_CFB1_TYPE: return 32; + case WC_AES_128_CFB8_TYPE: return 16; + case WC_AES_192_CFB8_TYPE: return 24; + case WC_AES_256_CFB8_TYPE: return 32; + case WC_AES_128_CFB128_TYPE: return 16; + case WC_AES_192_CFB128_TYPE: return 24; + case WC_AES_256_CFB128_TYPE: return 32; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: return 16; - case AES_192_OFB_TYPE: return 24; - case AES_256_OFB_TYPE: return 32; + case WC_AES_128_OFB_TYPE: return 16; + case WC_AES_192_OFB_TYPE: return 24; + case WC_AES_256_OFB_TYPE: return 32; #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) /* Two keys for XTS. */ - case AES_128_XTS_TYPE: return 16 * 2; - case AES_256_XTS_TYPE: return 32 * 2; + case WC_AES_128_XTS_TYPE: return 16 * 2; + case WC_AES_256_XTS_TYPE: return 32 * 2; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: return 16; - case AES_192_GCM_TYPE: return 24; - case AES_256_GCM_TYPE: return 32; + case WC_AES_128_GCM_TYPE: return 16; + case WC_AES_192_GCM_TYPE: return 24; + case WC_AES_256_GCM_TYPE: return 32; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: return 16; - case AES_192_CCM_TYPE: return 24; - case AES_256_CCM_TYPE: return 32; + case WC_AES_128_CCM_TYPE: return 16; + case WC_AES_192_CCM_TYPE: return 24; + case WC_AES_256_CCM_TYPE: return 32; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: return 16; - case AES_192_CTR_TYPE: return 24; - case AES_256_CTR_TYPE: return 32; + case WC_AES_128_CTR_TYPE: return 16; + case WC_AES_192_CTR_TYPE: return 24; + case WC_AES_256_CTR_TYPE: return 32; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: return 16; - case AES_192_ECB_TYPE: return 24; - case AES_256_ECB_TYPE: return 32; + case WC_AES_128_ECB_TYPE: return 16; + case WC_AES_192_ECB_TYPE: return 24; + case WC_AES_256_ECB_TYPE: return 32; #endif #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: return 8; - case DES_EDE3_CBC_TYPE: return 24; - case DES_ECB_TYPE: return 8; - case DES_EDE3_ECB_TYPE: return 24; + case WC_DES_CBC_TYPE: return 8; + case WC_DES_EDE3_CBC_TYPE: return 24; + case WC_DES_ECB_TYPE: return 8; + case WC_DES_EDE3_ECB_TYPE: return 24; #endif #ifndef NO_RC4 - case ARC4_TYPE: return 16; + case WC_ARC4_TYPE: return 16; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: return 32; + case WC_CHACHA20_POLY1305_TYPE: return 32; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: return CHACHA_MAX_KEY_SZ; + case WC_CHACHA20_TYPE: return CHACHA_MAX_KEY_SZ; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: return 16; + case WC_SM4_ECB_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: return 16; + case WC_SM4_CBC_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: return 16; + case WC_SM4_CTR_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: return 16; + case WC_SM4_GCM_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: return 16; + case WC_SM4_CCM_TYPE: return 16; #endif default: return 0; @@ -603,9 +604,9 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, switch (ctx->cipherType) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: if (ctx->enc) ret = wc_AesCbcEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -613,16 +614,16 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: ret = wc_AesCtrEncrypt(&ctx->cipher.aes, out, in, inl); break; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: if (ctx->enc) ret = wc_AesEcbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -630,9 +631,9 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: if (ctx->enc) ret = wc_AesOfbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -640,10 +641,10 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_CFB) - #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: + #if !defined(WOLFSSL_NO_AES_CFB_1_8) + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: if (ctx->enc) ret = wc_AesCfb1Encrypt(&ctx->cipher.aes, out, in, inl * WOLFSSL_BIT_SIZE); @@ -652,19 +653,19 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, inl * WOLFSSL_BIT_SIZE); break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: if (ctx->enc) ret = wc_AesCfb8Encrypt(&ctx->cipher.aes, out, in, inl); else ret = wc_AesCfb8Decrypt(&ctx->cipher.aes, out, in, inl); break; - #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: if (ctx->enc) ret = wc_AesCfbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -672,8 +673,8 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: if (ctx->enc) ret = wc_AesXtsEncrypt(&ctx->cipher.xts, out, in, inl, ctx->iv, (word32)ctx->ivSz); @@ -684,34 +685,34 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, #endif #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: + case WC_DES_CBC_TYPE: if (ctx->enc) ret = wc_Des_CbcEncrypt(&ctx->cipher.des, out, in, inl); else ret = wc_Des_CbcDecrypt(&ctx->cipher.des, out, in, inl); break; - case DES_EDE3_CBC_TYPE: + case WC_DES_EDE3_CBC_TYPE: if (ctx->enc) ret = wc_Des3_CbcEncrypt(&ctx->cipher.des3, out, in, inl); else ret = wc_Des3_CbcDecrypt(&ctx->cipher.des3, out, in, inl); break; #if defined(WOLFSSL_DES_ECB) - case DES_ECB_TYPE: + case WC_DES_ECB_TYPE: ret = wc_Des_EcbEncrypt(&ctx->cipher.des, out, in, inl); break; - case DES_EDE3_ECB_TYPE: + case WC_DES_EDE3_ECB_TYPE: ret = wc_Des3_EcbEncrypt(&ctx->cipher.des3, out, in, inl); break; #endif #endif #ifndef NO_RC4 - case ARC4_TYPE: + case WC_ARC4_TYPE: wc_Arc4Process(&ctx->cipher.arc4, out, in, inl); break; #endif #if defined(WOLFSSL_SM4_ECB) - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: if (ctx->enc) wc_Sm4EcbEncrypt(&ctx->cipher.sm4, out, in, inl); else @@ -719,7 +720,7 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_SM4_CBC) - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: if (ctx->enc) wc_Sm4CbcEncrypt(&ctx->cipher.sm4, out, in, inl); else @@ -727,7 +728,7 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_SM4_CTR) - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: wc_Sm4CtrEncrypt(&ctx->cipher.sm4, out, in, inl); break; #endif @@ -783,7 +784,7 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, #if defined(WOLFSSL_SM4_GCM) || !defined(WOLFSSL_AESGCM_STREAM) #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_AESGCM_STREAM) - if (ctx->cipherType == SM4_GCM_TYPE) + if (ctx->cipherType == WC_SM4_GCM_TYPE) #endif { int ret = 0; @@ -1059,29 +1060,29 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, switch (ctx->cipherType) { #if !defined(NO_AES) && defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_GCM(ctx, out, outl, in, inl); #endif /* !defined(NO_AES) && defined(HAVE_AESGCM) */ #if !defined(NO_AES) && defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: /* if out == NULL, in/inl contains the * additional auth data */ return wolfSSL_EVP_CipherUpdate_CCM(ctx, out, outl, in, inl); #endif /* !defined(NO_AES) && defined(HAVE_AESCCM) */ #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_AriaGCM(ctx, out, outl, in, inl); #endif /* defined(HAVE_ARIA) */ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: if (out == NULL) { if (wc_ChaCha20Poly1305_UpdateAad(&ctx->cipher.chachaPoly, in, (word32)inl) != 0) { @@ -1106,7 +1107,7 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, } #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: if (wc_Chacha_Process(&ctx->cipher.chacha, out, in, (word32)inl) != 0) { WOLFSSL_MSG("wc_ChaCha_Process failed"); @@ -1116,12 +1117,12 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, return WOLFSSL_SUCCESS; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_GCM(ctx, out, outl, in, inl); #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: /* if out == NULL, in/inl contains the * additional auth data */ return wolfSSL_EVP_CipherUpdate_CCM(ctx, out, outl, in, inl); @@ -1274,9 +1275,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, switch (ctx->cipherType) { #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #ifndef WOLFSSL_AESGCM_STREAM if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { @@ -1347,7 +1348,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, } else { /* Clear IV, since IV reuse is not recommended for AES GCM. */ - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); } if (wolfSSL_StoreExternalIV(ctx) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FAILURE; @@ -1358,9 +1359,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) { @@ -1406,7 +1407,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, else { /* Clear IV, since IV reuse is not recommended * for AES CCM. */ - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); } if (wolfSSL_StoreExternalIV(ctx) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FAILURE; @@ -1417,9 +1418,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_ARIA) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1471,7 +1472,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, #endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: if (wc_ChaCha20Poly1305_Final(&ctx->cipher.chachaPoly, ctx->authTag) != 0) { WOLFSSL_MSG("wc_ChaCha20Poly1305_Final failed"); @@ -1484,7 +1485,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1535,7 +1536,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1660,20 +1661,20 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, */ if (FALSE #ifdef HAVE_AESGCM - || ctx->cipherType == AES_128_GCM_TYPE || - ctx->cipherType == AES_192_GCM_TYPE || - ctx->cipherType == AES_256_GCM_TYPE + || ctx->cipherType == WC_AES_128_GCM_TYPE || + ctx->cipherType == WC_AES_192_GCM_TYPE || + ctx->cipherType == WC_AES_256_GCM_TYPE #endif #ifdef HAVE_AESCCM - || ctx->cipherType == AES_128_CCM_TYPE || - ctx->cipherType == AES_192_CCM_TYPE || - ctx->cipherType == AES_256_CCM_TYPE + || ctx->cipherType == WC_AES_128_CCM_TYPE || + ctx->cipherType == WC_AES_192_CCM_TYPE || + ctx->cipherType == WC_AES_256_CCM_TYPE #endif #ifdef WOLFSSL_SM4_GCM - || ctx->cipherType == SM4_GCM_TYPE + || ctx->cipherType == WC_SM4_GCM_TYPE #endif #ifdef WOLFSSL_SM4_CCM - || ctx->cipherType == SM4_CCM_TYPE + || ctx->cipherType == WC_SM4_CCM_TYPE #endif ) { tmp = ctx->authIvGenEnable; @@ -1688,20 +1689,20 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef HAVE_AESGCM - || ctx->cipherType == AES_128_GCM_TYPE || - ctx->cipherType == AES_192_GCM_TYPE || - ctx->cipherType == AES_256_GCM_TYPE + || ctx->cipherType == WC_AES_128_GCM_TYPE || + ctx->cipherType == WC_AES_192_GCM_TYPE || + ctx->cipherType == WC_AES_256_GCM_TYPE #endif #ifdef HAVE_AESCCM - || ctx->cipherType == AES_128_CCM_TYPE || - ctx->cipherType == AES_192_CCM_TYPE || - ctx->cipherType == AES_256_CCM_TYPE + || ctx->cipherType == WC_AES_128_CCM_TYPE || + ctx->cipherType == WC_AES_192_CCM_TYPE || + ctx->cipherType == WC_AES_256_CCM_TYPE #endif #ifdef WOLFSSL_SM4_GCM - || ctx->cipherType == SM4_GCM_TYPE + || ctx->cipherType == WC_SM4_GCM_TYPE #endif #ifdef WOLFSSL_SM4_CCM - || ctx->cipherType == SM4_CCM_TYPE + || ctx->cipherType == WC_SM4_CCM_TYPE #endif ) { ctx->authIvGenEnable = (tmp == 1); @@ -1769,75 +1770,75 @@ int wolfSSL_EVP_CIPHER_CTX_block_size(const WOLFSSL_EVP_CIPHER_CTX *ctx) #if !defined(NO_AES) || !defined(NO_DES3) || defined(WOLFSSL_SM4) #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: #endif #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: #endif - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: - case DES_ECB_TYPE: - case DES_EDE3_CBC_TYPE: - case DES_EDE3_ECB_TYPE: + case WC_DES_CBC_TYPE: + case WC_DES_ECB_TYPE: + case WC_DES_EDE3_CBC_TYPE: + case WC_DES_EDE3_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: #endif return ctx->block_size; #endif /* !NO_AES || !NO_DES3 || WOLFSSL_SM4 */ @@ -1851,193 +1852,195 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) if (cipher == NULL) return 0; /* dummy for #ifdef */ #ifndef NO_DES3 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_CBC)) - return DES_CBC_TYPE; + return WC_DES_CBC_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_EDE3_CBC)) - return DES_EDE3_CBC_TYPE; + return WC_DES_EDE3_CBC_TYPE; #if !defined(NO_DES3) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_ECB)) - return DES_ECB_TYPE; + return WC_DES_ECB_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_EDE3_ECB)) - return DES_EDE3_ECB_TYPE; + return WC_DES_EDE3_ECB_TYPE; #endif /* NO_DES3 && HAVE_AES_ECB */ #endif #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CBC)) - return AES_128_CBC_TYPE; + return WC_AES_128_CBC_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CBC)) - return AES_192_CBC_TYPE; + return WC_AES_192_CBC_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CBC)) - return AES_256_CBC_TYPE; + return WC_AES_256_CBC_TYPE; #endif #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ #if defined(HAVE_AESGCM) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_GCM)) - return AES_128_GCM_TYPE; + return WC_AES_128_GCM_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_GCM)) - return AES_192_GCM_TYPE; + return WC_AES_192_GCM_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_GCM)) - return AES_256_GCM_TYPE; + return WC_AES_256_GCM_TYPE; #endif #endif /* HAVE_AESGCM */ #if defined(HAVE_AESCCM) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CCM)) - return AES_128_CCM_TYPE; + return WC_AES_128_CCM_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CCM)) - return AES_192_CCM_TYPE; + return WC_AES_192_CCM_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CCM)) - return AES_256_CCM_TYPE; + return WC_AES_256_CCM_TYPE; #endif #endif /* HAVE_AESCCM */ #if defined(WOLFSSL_AES_COUNTER) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CTR)) - return AES_128_CTR_TYPE; + return WC_AES_128_CTR_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CTR)) - return AES_192_CTR_TYPE; + return WC_AES_192_CTR_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CTR)) - return AES_256_CTR_TYPE; + return WC_AES_256_CTR_TYPE; #endif #endif /* HAVE_AES_CBC */ #if defined(HAVE_AES_ECB) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_ECB)) - return AES_128_ECB_TYPE; + return WC_AES_128_ECB_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_ECB)) - return AES_192_ECB_TYPE; + return WC_AES_192_ECB_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_ECB)) - return AES_256_ECB_TYPE; + return WC_AES_256_ECB_TYPE; #endif #endif /*HAVE_AES_CBC */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_XTS)) - return AES_128_XTS_TYPE; + return WC_AES_128_XTS_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_XTS)) - return AES_256_XTS_TYPE; + return WC_AES_256_XTS_TYPE; #endif #endif /* WOLFSSL_AES_XTS */ #if defined(WOLFSSL_AES_CFB) +#ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB1)) - return AES_128_CFB1_TYPE; + return WC_AES_128_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB1)) - return AES_192_CFB1_TYPE; + return WC_AES_192_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB1)) - return AES_256_CFB1_TYPE; + return WC_AES_256_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB8)) - return AES_128_CFB8_TYPE; + return WC_AES_128_CFB8_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB8)) - return AES_192_CFB8_TYPE; + return WC_AES_192_CFB8_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB8)) - return AES_256_CFB8_TYPE; + return WC_AES_256_CFB8_TYPE; #endif +#endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB128)) - return AES_128_CFB128_TYPE; + return WC_AES_128_CFB128_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB128)) - return AES_192_CFB128_TYPE; + return WC_AES_192_CFB128_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB128)) - return AES_256_CFB128_TYPE; + return WC_AES_256_CFB128_TYPE; #endif #endif /*HAVE_AES_CBC */ #if defined(WOLFSSL_AES_OFB) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_OFB)) - return AES_128_OFB_TYPE; + return WC_AES_128_OFB_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_OFB)) - return AES_192_OFB_TYPE; + return WC_AES_192_OFB_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_OFB)) - return AES_256_OFB_TYPE; + return WC_AES_256_OFB_TYPE; #endif #endif #endif /* !NO_AES */ #if defined(HAVE_ARIA) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_128_GCM)) - return ARIA_128_GCM_TYPE; + return WC_ARIA_128_GCM_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_192_GCM)) - return ARIA_192_GCM_TYPE; + return WC_ARIA_192_GCM_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_256_GCM)) - return ARIA_256_GCM_TYPE; + return WC_ARIA_256_GCM_TYPE; #endif /* HAVE_ARIA */ #ifndef NO_RC4 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARC4)) - return ARC4_TYPE; + return WC_ARC4_TYPE; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_CHACHA20_POLY1305)) - return CHACHA20_POLY1305_TYPE; + return WC_CHACHA20_POLY1305_TYPE; #endif #ifdef HAVE_CHACHA else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_CHACHA20)) - return CHACHA20_TYPE; + return WC_CHACHA20_TYPE; #endif #ifdef WOLFSSL_SM4_ECB else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_ECB)) - return SM4_ECB_TYPE; + return WC_SM4_ECB_TYPE; #endif #ifdef WOLFSSL_SM4_CBC else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CBC)) - return SM4_CBC_TYPE; + return WC_SM4_CBC_TYPE; #endif #ifdef WOLFSSL_SM4_CTR else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CTR)) - return SM4_CTR_TYPE; + return WC_SM4_CTR_TYPE; #endif #ifdef WOLFSSL_SM4_GCM else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_GCM)) - return SM4_GCM_TYPE; + return WC_SM4_GCM_TYPE; #endif #ifdef WOLFSSL_SM4_CCM else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CCM)) - return SM4_CCM_TYPE; + return WC_SM4_CCM_TYPE; #endif else return 0; @@ -2051,107 +2054,107 @@ int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) switch (cipherType(cipher)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: - return AES_BLOCK_SIZE; + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: + return WC_AES_BLOCK_SIZE; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: return 1; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: return 1; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: return 1; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: - return AES_BLOCK_SIZE; + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: + return WC_AES_BLOCK_SIZE; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: return 1; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: return 1; #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: return 1; #endif #endif /* NO_AES */ #ifndef NO_RC4 - case ARC4_TYPE: + case WC_ARC4_TYPE: return 1; #endif #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: return 1; #endif #ifndef NO_DES3 - case DES_CBC_TYPE: return 8; - case DES_EDE3_CBC_TYPE: return 8; - case DES_ECB_TYPE: return 8; - case DES_EDE3_ECB_TYPE: return 8; + case WC_DES_CBC_TYPE: return 8; + case WC_DES_EDE3_CBC_TYPE: return 8; + case WC_DES_ECB_TYPE: return 8; + case WC_DES_EDE3_ECB_TYPE: return 8; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: return 1; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: return 1; #endif @@ -2165,107 +2168,107 @@ unsigned long WOLFSSL_CIPHER_mode(const WOLFSSL_EVP_CIPHER *cipher) switch (cipherType(cipher)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: return WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: return WOLFSSL_EVP_CIPH_CTR_MODE; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: return WOLFSSL_EVP_CIPH_CFB_MODE; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: return WOLFSSL_EVP_CIPH_OFB_MODE; #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: return WOLFSSL_EVP_CIPH_XTS_MODE; #endif - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif /* !NO_AES */ #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifndef NO_DES3 - case DES_CBC_TYPE: - case DES_EDE3_CBC_TYPE: + case WC_DES_CBC_TYPE: + case WC_DES_EDE3_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; - case DES_ECB_TYPE: - case DES_EDE3_ECB_TYPE: + case WC_DES_ECB_TYPE: + case WC_DES_EDE3_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif #ifndef NO_RC4 - case ARC4_TYPE: - return EVP_CIPH_STREAM_CIPHER; + case WC_ARC4_TYPE: + return WOLFSSL_EVP_CIPH_STREAM_CIPHER; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: return WOLFSSL_EVP_CIPH_STREAM_CIPHER | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: return WOLFSSL_EVP_CIPH_STREAM_CIPHER; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: return WOLFSSL_EVP_CIPH_CTR_MODE; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: return WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif @@ -2374,7 +2377,7 @@ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_E XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_PKEY_CTX)); ctx->pkey = pkey; #if !defined(NO_RSA) - ctx->padding = RSA_PKCS1_PADDING; + ctx->padding = WC_RSA_PKCS1_PADDING; ctx->md = NULL; #endif #ifdef HAVE_ECC @@ -2416,7 +2419,7 @@ int wolfSSL_EVP_PKEY_CTX_set_rsa_padding(WOLFSSL_EVP_PKEY_CTX *ctx, int padding) * returns WOLFSSL_SUCCESS on success. */ int wolfSSL_EVP_PKEY_CTX_set_signature_md(WOLFSSL_EVP_PKEY_CTX *ctx, - const EVP_MD* md) + const WOLFSSL_EVP_MD* md) { if (ctx == NULL) return 0; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_signature_md"); @@ -2468,7 +2471,7 @@ int wolfSSL_EVP_PKEY_derive_init(WOLFSSL_EVP_PKEY_CTX *ctx) return WOLFSSL_FAILURE; } wolfSSL_EVP_PKEY_free(ctx->peerKey); - ctx->op = EVP_PKEY_OP_DERIVE; + ctx->op = WC_EVP_PKEY_OP_DERIVE; ctx->padding = 0; ctx->nbits = 0; return WOLFSSL_SUCCESS; @@ -2478,7 +2481,7 @@ int wolfSSL_EVP_PKEY_derive_set_peer(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY { WOLFSSL_ENTER("wolfSSL_EVP_PKEY_derive_set_peer"); - if (!ctx || ctx->op != EVP_PKEY_OP_DERIVE) { + if (!ctx || ctx->op != WC_EVP_PKEY_OP_DERIVE) { return WOLFSSL_FAILURE; } wolfSSL_EVP_PKEY_free(ctx->peerKey); @@ -2513,14 +2516,14 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ WOLFSSL_ENTER("wolfSSL_EVP_PKEY_derive"); - if (!ctx || ctx->op != EVP_PKEY_OP_DERIVE || !ctx->pkey || (!ctx->peerKey - && ctx->pkey->type != EVP_PKEY_HKDF) || !keylen || (ctx->pkey->type - != EVP_PKEY_HKDF && ctx->pkey->type != ctx->peerKey->type)) { + if (!ctx || ctx->op != WC_EVP_PKEY_OP_DERIVE || !ctx->pkey || (!ctx->peerKey + && ctx->pkey->type != WC_EVP_PKEY_HKDF) || !keylen || (ctx->pkey->type + != WC_EVP_PKEY_HKDF && ctx->pkey->type != ctx->peerKey->type)) { return WOLFSSL_FAILURE; } switch (ctx->pkey->type) { #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: /* Use DH */ if (!ctx->pkey->dh || !ctx->peerKey->dh) { return WOLFSSL_FAILURE; @@ -2553,7 +2556,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ break; #endif #if defined(HAVE_ECC) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: /* Use ECDH */ if (!ctx->pkey->ecc || !ctx->peerKey->ecc) { return WOLFSSL_FAILURE; @@ -2621,7 +2624,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ break; #endif #ifdef HAVE_HKDF - case EVP_PKEY_HKDF: + case WC_EVP_PKEY_HKDF: (void)len; hkdfHashType = EvpMd2MacType(ctx->pkey->hkdfMd); @@ -2629,7 +2632,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ WOLFSSL_MSG("Invalid hash type for HKDF."); return WOLFSSL_FAILURE; } - if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { + if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { if (wc_HKDF(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, @@ -2638,7 +2641,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ return WOLFSSL_FAILURE; } } - else if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { + else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { if (wc_HKDF_Extract(hkdfHashType, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, key) != 0) { @@ -2655,7 +2658,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ *keylen = (size_t)hkdfHashSz; } } - else if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { + else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { if (wc_HKDF_Expand(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, @@ -2711,7 +2714,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2746,7 +2749,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_key(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2781,7 +2784,7 @@ int wolfSSL_EVP_PKEY_CTX_add1_hkdf_info(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2831,9 +2834,10 @@ int wolfSSL_EVP_PKEY_CTX_hkdf_mode(WOLFSSL_EVP_PKEY_CTX* ctx, int mode) } if (ret == WOLFSSL_SUCCESS && - mode != EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND && - mode != EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY && - mode != EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND && + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY && + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) + { WOLFSSL_MSG("Invalid HKDF mode."); ret = WOLFSSL_FAILURE; } @@ -2881,7 +2885,7 @@ int wolfSSL_EVP_PKEY_decrypt(WOLFSSL_EVP_PKEY_CTX *ctx, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (out == NULL) { if (ctx->pkey->rsa == NULL) { WOLFSSL_MSG("Internal wolfCrypt RSA object is NULL."); @@ -2910,8 +2914,8 @@ int wolfSSL_EVP_PKEY_decrypt(WOLFSSL_EVP_PKEY_CTX *ctx, } #endif /* NO_RSA */ - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not implemented."); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not implemented."); FALL_THROUGH; default: break; @@ -2932,10 +2936,10 @@ int wolfSSL_EVP_PKEY_decrypt_init(WOLFSSL_EVP_PKEY_CTX *ctx) if (ctx == NULL) return WOLFSSL_FAILURE; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_decrypt_init"); switch (ctx->pkey->type) { - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_DECRYPT; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_DECRYPT; return WOLFSSL_SUCCESS; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -2970,8 +2974,8 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, return 0; } - if (ctx->op != EVP_PKEY_OP_ENCRYPT) { - WOLFSSL_MSG("ctx->op must be set to EVP_PKEY_OP_ENCRYPT. Use " + if (ctx->op != WC_EVP_PKEY_OP_ENCRYPT) { + WOLFSSL_MSG("ctx->op must be set to WC_EVP_PKEY_OP_ENCRYPT. Use " "wolfSSL_EVP_PKEY_encrypt_init."); return WOLFSSL_FAILURE; } @@ -2984,7 +2988,7 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (out == NULL) { if (ctx->pkey->rsa == NULL) { WOLFSSL_MSG("Internal wolfCrypt RSA object is NULL."); @@ -3014,8 +3018,8 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, } #endif /* NO_RSA */ - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not implemented"); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not implemented"); FALL_THROUGH; default: break; @@ -3037,10 +3041,10 @@ int wolfSSL_EVP_PKEY_encrypt_init(WOLFSSL_EVP_PKEY_CTX *ctx) WOLFSSL_ENTER("wolfSSL_EVP_PKEY_encrypt_init"); switch (ctx->pkey->type) { - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_ENCRYPT; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_ENCRYPT; return WOLFSSL_SUCCESS; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -3065,22 +3069,22 @@ int wolfSSL_EVP_PKEY_sign_init(WOLFSSL_EVP_PKEY_CTX *ctx) switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_DSA: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_EC: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* HAVE_ECC */ @@ -3103,7 +3107,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, { WOLFSSL_MSG("wolfSSL_EVP_PKEY_sign"); - if (!ctx || ctx->op != EVP_PKEY_OP_SIGN || !ctx->pkey || !siglen) + if (!ctx || ctx->op != WC_EVP_PKEY_OP_SIGN || !ctx->pkey || !siglen) return WOLFSSL_FAILURE; (void)sig; @@ -3113,7 +3117,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { unsigned int usiglen = (unsigned int)*siglen; if (!sig) { int len; @@ -3138,7 +3142,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int bytes; int ret; if (!ctx->pkey->dsa) @@ -3165,7 +3169,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig; if (!sig) { @@ -3227,20 +3231,20 @@ int wolfSSL_EVP_PKEY_verify_init(WOLFSSL_EVP_PKEY_CTX *ctx) switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_DSA: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_EC: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* HAVE_ECC */ @@ -3264,19 +3268,19 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, { WOLFSSL_MSG("wolfSSL_EVP_PKEY_verify"); - if (!ctx || ctx->op != EVP_PKEY_OP_VERIFY || !ctx->pkey) + if (!ctx || ctx->op != WC_EVP_PKEY_OP_VERIFY || !ctx->pkey) return WOLFSSL_FAILURE; switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: return wolfSSL_RSA_verify_ex(WC_HASH_TYPE_NONE, tbs, (unsigned int)tbslen, sig, (unsigned int)siglen, ctx->pkey->rsa, ctx->padding); #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int dsacheck = 0; if (wolfSSL_DSA_do_verify(tbs, (unsigned char *)sig, ctx->pkey->dsa, &dsacheck) != WOLFSSL_SUCCESS || dsacheck != 1) @@ -3286,7 +3290,7 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( NULL, (const unsigned char **)&sig, (long)siglen); @@ -3334,7 +3338,7 @@ int wolfSSL_EVP_PKEY_CTX_set_ec_paramgen_curve_nid(WOLFSSL_EVP_PKEY_CTX *ctx, { WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_ec_paramgen_curve_nid"); #ifdef HAVE_ECC - if (ctx != NULL && ctx->pkey != NULL && ctx->pkey->type == EVP_PKEY_EC) { + if (ctx != NULL && ctx->pkey != NULL && ctx->pkey->type == WC_EVP_PKEY_EC) { ctx->curveNID = nid; return WOLFSSL_SUCCESS; } @@ -3367,7 +3371,7 @@ int wolfSSL_EVP_PKEY_paramgen(WOLFSSL_EVP_PKEY_CTX* ctx, if (ret == WOLFSSL_SUCCESS && *pkey == NULL) { /* Only ECC is supported currently. */ - if (ctx->pkey == NULL || ctx->pkey->type != EVP_PKEY_EC) { + if (ctx->pkey == NULL || ctx->pkey->type != WC_EVP_PKEY_EC) { WOLFSSL_MSG("Key not set or key type not supported."); ret = WOLFSSL_FAILURE; } @@ -3388,7 +3392,7 @@ int wolfSSL_EVP_PKEY_paramgen(WOLFSSL_EVP_PKEY_CTX* ctx, #ifdef HAVE_ECC /* For ECC parameter generation we just need to set the group, which * wolfSSL_EC_KEY_new_by_curve_name will do. */ - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: (*pkey)->ecc = wolfSSL_EC_KEY_new_by_curve_name(ctx->curveNID); if ((*pkey)->ecc == NULL) { WOLFSSL_MSG("Failed to create WOLFSSL_EC_KEY."); @@ -3451,9 +3455,9 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, pkey = *ppkey; if (pkey == NULL) { if (ctx->pkey == NULL || - (ctx->pkey->type != EVP_PKEY_EC && - ctx->pkey->type != EVP_PKEY_RSA && - ctx->pkey->type != EVP_PKEY_DH)) { + (ctx->pkey->type != WC_EVP_PKEY_EC && + ctx->pkey->type != WC_EVP_PKEY_RSA && + ctx->pkey->type != WC_EVP_PKEY_DH)) { WOLFSSL_MSG("Key not set or key type not supported"); return WOLFSSL_FAILURE; } @@ -3467,7 +3471,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, switch (pkey->type) { #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: pkey->rsa = wolfSSL_RSA_generate_key(ctx->nbits, WC_RSA_EXPONENT, NULL, NULL); if (pkey->rsa) { @@ -3479,7 +3483,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: /* pkey->ecc may not be NULL, if, for example, it was populated by a * prior call to wolfSSL_EVP_PKEY_paramgen. */ if (pkey->ecc == NULL) { @@ -3494,7 +3498,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, break; #endif #if !defined(NO_DH) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: pkey->dh = wolfSSL_DH_new(); if (pkey->dh) { pkey->ownDh = 1; @@ -3540,12 +3544,12 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) switch (pkey->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: return (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(pkey->rsa)); #endif /* !NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (pkey->dsa == NULL || (!pkey->dsa->exSet && SetDsaExternal(pkey->dsa) != WOLFSSL_SUCCESS)) @@ -3554,7 +3558,7 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (pkey->ecc == NULL || pkey->ecc->internal == NULL) { WOLFSSL_MSG("No ECC key has been set"); break; @@ -3579,7 +3583,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, return WOLFSSL_FAILURE; } - if (to->type == EVP_PKEY_NONE) { + if (to->type == WC_EVP_PKEY_NONE) { to->type = from->type; } else if (to->type != from->type) { @@ -3589,7 +3593,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, switch(from->type) { #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (from->ecc) { if (!to->ecc) { if ((to->ecc = wolfSSL_EC_KEY_new()) == NULL) { @@ -3609,7 +3613,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (from->dsa) { WOLFSSL_BIGNUM* cpy; if (!to->dsa) { @@ -3651,7 +3655,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: if (from->dh) { WOLFSSL_BIGNUM* cpy; if (!to->dh) { @@ -3693,7 +3697,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #endif default: WOLFSSL_MSG("Copy parameters not available for this key type"); @@ -3740,13 +3744,13 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) /* get size based on key type */ switch (a->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: a_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)); b_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)); break; #endif /* !NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (a->ecc == NULL || a->ecc->internal == NULL || b->ecc == NULL || b->ecc->internal == NULL) { return ret; @@ -3885,23 +3889,23 @@ int wolfSSL_EVP_PKEY_param_check(WOLFSSL_EVP_PKEY_CTX* ctx) type = wolfSSL_EVP_PKEY_type(wolfSSL_EVP_PKEY_base_id(ctx->pkey)); switch (type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - WOLFSSL_MSG("EVP_PKEY_RSA not yet implemented"); + case WC_EVP_PKEY_RSA: + WOLFSSL_MSG("WC_EVP_PKEY_RSA not yet implemented"); return WOLFSSL_FAILURE; #endif #if defined(HAVE_ECC) - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not yet implemented"); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not yet implemented"); return WOLFSSL_FAILURE; #endif #if !defined(NO_DSA) - case EVP_PKEY_DSA: - WOLFSSL_MSG("EVP_PKEY_DSA not yet implemented"); + case WC_EVP_PKEY_DSA: + WOLFSSL_MSG("WC_EVP_PKEY_DSA not yet implemented"); return WOLFSSL_FAILURE; #endif #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || defined(WOLFSSL_OPENSSH) #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: dh_key = wolfSSL_EVP_PKEY_get1_DH(ctx->pkey); if (dh_key != NULL) { ret = DH_param_check(dh_key); @@ -4001,7 +4005,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, switch (pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *ctxmd; @@ -4017,7 +4021,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, } #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int bytes; ret = wolfSSL_DSA_do_sign(md, sigret, pkey->dsa); /* wolfSSL_DSA_do_sign() can return WOLFSSL_FATAL_ERROR */ @@ -4034,7 +4038,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, } #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_ECDSA_do_sign(md, (int)mdsize, pkey->ecc); if (ecdsaSig == NULL) @@ -4115,7 +4119,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, switch (pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *ctxmd = wolfSSL_EVP_MD_CTX_md(ctx); if (ctxmd == NULL) break; @@ -4126,7 +4130,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, } #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( NULL, (const unsigned char **)&sig, (long)siglen); if (ecdsaSig == NULL) @@ -4137,7 +4141,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, return ret; } #endif - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -4162,7 +4166,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_mac_key(int type, WOLFSSL_ENGINE* e, (void)e; - if (type != EVP_PKEY_HMAC || (key == NULL && keylen != 0)) + if (type != WC_EVP_PKEY_HMAC || (key == NULL && keylen != 0)) return NULL; pkey = wolfSSL_EVP_PKEY_new(); @@ -4228,7 +4232,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_CMAC_key(WOLFSSL_ENGINE* e, XMEMCPY(pkey->pkey.ptr, priv, (size_t)len); } pkey->pkey_sz = (int)len; - pkey->type = pkey->save_type = EVP_PKEY_CMAC; + pkey->type = pkey->save_type = WC_EVP_PKEY_CMAC; pkey->cmacCtx = ctx; } } @@ -4354,7 +4358,7 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, } } - if (pkey->type == EVP_PKEY_HMAC) { + if (pkey->type == WC_EVP_PKEY_HMAC) { int hashType; int ret; size_t keySz = 0; @@ -4581,7 +4585,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, } } #ifndef NO_RSA - else if (ctx->pctx->pkey->type == EVP_PKEY_RSA) { + else if (ctx->pctx->pkey->type == WC_EVP_PKEY_RSA) { if (sig == NULL) { *siglen = (size_t)wolfSSL_RSA_size(ctx->pctx->pkey->rsa); return WOLFSSL_SUCCESS; @@ -4589,7 +4593,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, } #endif /* !NO_RSA */ #ifdef HAVE_ECC - else if (ctx->pctx->pkey->type == EVP_PKEY_EC) { + else if (ctx->pctx->pkey->type == WC_EVP_PKEY_EC) { if (sig == NULL) { /* SEQ + INT + INT */ *siglen = (size_t)ecc_sets[ctx->pctx->pkey->ecc->group->curve_idx]. @@ -4615,7 +4619,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, /* Sign the digest. */ switch (ctx->pctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { unsigned int sigSz = (unsigned int)*siglen; int nid; const WOLFSSL_EVP_MD *md = wolfSSL_EVP_MD_CTX_md(ctx); @@ -4633,7 +4637,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int len; WOLFSSL_ECDSA_SIG *ecdsaSig; ecdsaSig = wolfSSL_ECDSA_do_sign(digest, (int)hashLen, @@ -4718,7 +4722,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, /* Verify the signature with the digest. */ switch (ctx->pctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *md = wolfSSL_EVP_MD_CTX_md(ctx); if (md == NULL) @@ -4733,7 +4737,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig; ecdsaSig = wolfSSL_d2i_ECDSA_SIG(NULL, &sig, (long)siglen); @@ -4955,159 +4959,161 @@ static const struct cipher{ #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - {AES_128_CBC_TYPE, EVP_AES_128_CBC, NID_aes_128_cbc}, + {WC_AES_128_CBC_TYPE, EVP_AES_128_CBC, WC_NID_aes_128_cbc}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CBC_TYPE, EVP_AES_192_CBC, NID_aes_192_cbc}, + {WC_AES_192_CBC_TYPE, EVP_AES_192_CBC, WC_NID_aes_192_cbc}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CBC_TYPE, EVP_AES_256_CBC, NID_aes_256_cbc}, + {WC_AES_256_CBC_TYPE, EVP_AES_256_CBC, WC_NID_aes_256_cbc}, #endif #endif #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 - {AES_128_CFB1_TYPE, EVP_AES_128_CFB1, NID_aes_128_cfb1}, + {WC_AES_128_CFB1_TYPE, EVP_AES_128_CFB1, WC_NID_aes_128_cfb1}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB1_TYPE, EVP_AES_192_CFB1, NID_aes_192_cfb1}, + {WC_AES_192_CFB1_TYPE, EVP_AES_192_CFB1, WC_NID_aes_192_cfb1}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB1_TYPE, EVP_AES_256_CFB1, NID_aes_256_cfb1}, + {WC_AES_256_CFB1_TYPE, EVP_AES_256_CFB1, WC_NID_aes_256_cfb1}, #endif #ifdef WOLFSSL_AES_128 - {AES_128_CFB8_TYPE, EVP_AES_128_CFB8, NID_aes_128_cfb8}, + {WC_AES_128_CFB8_TYPE, EVP_AES_128_CFB8, WC_NID_aes_128_cfb8}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB8_TYPE, EVP_AES_192_CFB8, NID_aes_192_cfb8}, + {WC_AES_192_CFB8_TYPE, EVP_AES_192_CFB8, WC_NID_aes_192_cfb8}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB8_TYPE, EVP_AES_256_CFB8, NID_aes_256_cfb8}, + {WC_AES_256_CFB8_TYPE, EVP_AES_256_CFB8, WC_NID_aes_256_cfb8}, #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 - {AES_128_CFB128_TYPE, EVP_AES_128_CFB128, NID_aes_128_cfb128}, + {WC_AES_128_CFB128_TYPE, EVP_AES_128_CFB128, WC_NID_aes_128_cfb128}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB128_TYPE, EVP_AES_192_CFB128, NID_aes_192_cfb128}, + {WC_AES_192_CFB128_TYPE, EVP_AES_192_CFB128, WC_NID_aes_192_cfb128}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB128_TYPE, EVP_AES_256_CFB128, NID_aes_256_cfb128}, - #endif + {WC_AES_256_CFB128_TYPE, EVP_AES_256_CFB128, WC_NID_aes_256_cfb128}, #endif + #endif /* WOLFSSL_AES_CFB */ #ifdef WOLFSSL_AES_OFB #ifdef WOLFSSL_AES_128 - {AES_128_OFB_TYPE, EVP_AES_128_OFB, NID_aes_128_ofb}, + {WC_AES_128_OFB_TYPE, EVP_AES_128_OFB, WC_NID_aes_128_ofb}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_OFB_TYPE, EVP_AES_192_OFB, NID_aes_192_ofb}, + {WC_AES_192_OFB_TYPE, EVP_AES_192_OFB, WC_NID_aes_192_ofb}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_OFB_TYPE, EVP_AES_256_OFB, NID_aes_256_ofb}, + {WC_AES_256_OFB_TYPE, EVP_AES_256_OFB, WC_NID_aes_256_ofb}, #endif #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 - {AES_128_XTS_TYPE, EVP_AES_128_XTS, NID_aes_128_xts}, + {WC_AES_128_XTS_TYPE, EVP_AES_128_XTS, WC_NID_aes_128_xts}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_XTS_TYPE, EVP_AES_256_XTS, NID_aes_256_xts}, + {WC_AES_256_XTS_TYPE, EVP_AES_256_XTS, WC_NID_aes_256_xts}, #endif #endif #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 - {AES_128_GCM_TYPE, EVP_AES_128_GCM, NID_aes_128_gcm}, + {WC_AES_128_GCM_TYPE, EVP_AES_128_GCM, WC_NID_aes_128_gcm}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_GCM_TYPE, EVP_AES_192_GCM, NID_aes_192_gcm}, + {WC_AES_192_GCM_TYPE, EVP_AES_192_GCM, WC_NID_aes_192_gcm}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_GCM_TYPE, EVP_AES_256_GCM, NID_aes_256_gcm}, + {WC_AES_256_GCM_TYPE, EVP_AES_256_GCM, WC_NID_aes_256_gcm}, #endif #endif #ifdef HAVE_AESCCM #ifdef WOLFSSL_AES_128 - {AES_128_CCM_TYPE, EVP_AES_128_CCM, NID_aes_128_ccm}, + {WC_AES_128_CCM_TYPE, EVP_AES_128_CCM, WC_NID_aes_128_ccm}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CCM_TYPE, EVP_AES_192_CCM, NID_aes_192_ccm}, + {WC_AES_192_CCM_TYPE, EVP_AES_192_CCM, WC_NID_aes_192_ccm}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CCM_TYPE, EVP_AES_256_CCM, NID_aes_256_ccm}, + {WC_AES_256_CCM_TYPE, EVP_AES_256_CCM, WC_NID_aes_256_ccm}, #endif #endif #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - {AES_128_CTR_TYPE, EVP_AES_128_CTR, NID_aes_128_ctr}, + {WC_AES_128_CTR_TYPE, EVP_AES_128_CTR, WC_NID_aes_128_ctr}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CTR_TYPE, EVP_AES_192_CTR, NID_aes_192_ctr}, + {WC_AES_192_CTR_TYPE, EVP_AES_192_CTR, WC_NID_aes_192_ctr}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CTR_TYPE, EVP_AES_256_CTR, NID_aes_256_ctr}, + {WC_AES_256_CTR_TYPE, EVP_AES_256_CTR, WC_NID_aes_256_ctr}, #endif #endif #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - {AES_128_ECB_TYPE, EVP_AES_128_ECB, NID_aes_128_ecb}, + {WC_AES_128_ECB_TYPE, EVP_AES_128_ECB, WC_NID_aes_128_ecb}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_ECB_TYPE, EVP_AES_192_ECB, NID_aes_192_ecb}, + {WC_AES_192_ECB_TYPE, EVP_AES_192_ECB, WC_NID_aes_192_ecb}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_ECB_TYPE, EVP_AES_256_ECB, NID_aes_256_ecb}, + {WC_AES_256_ECB_TYPE, EVP_AES_256_ECB, WC_NID_aes_256_ecb}, #endif #endif #endif #ifdef HAVE_ARIA - {ARIA_128_GCM_TYPE, EVP_ARIA_128_GCM, NID_aria_128_gcm}, - {ARIA_192_GCM_TYPE, EVP_ARIA_192_GCM, NID_aria_192_gcm}, - {ARIA_256_GCM_TYPE, EVP_ARIA_256_GCM, NID_aria_256_gcm}, + {WC_ARIA_128_GCM_TYPE, EVP_ARIA_128_GCM, WC_NID_aria_128_gcm}, + {WC_ARIA_192_GCM_TYPE, EVP_ARIA_192_GCM, WC_NID_aria_192_gcm}, + {WC_ARIA_256_GCM_TYPE, EVP_ARIA_256_GCM, WC_NID_aria_256_gcm}, #endif #ifndef NO_DES3 - {DES_CBC_TYPE, EVP_DES_CBC, NID_des_cbc}, - {DES_ECB_TYPE, EVP_DES_ECB, NID_des_ecb}, + {WC_DES_CBC_TYPE, EVP_DES_CBC, WC_NID_des_cbc}, + {WC_DES_ECB_TYPE, EVP_DES_ECB, WC_NID_des_ecb}, - {DES_EDE3_CBC_TYPE, EVP_DES_EDE3_CBC, NID_des_ede3_cbc}, - {DES_EDE3_ECB_TYPE, EVP_DES_EDE3_ECB, NID_des_ede3_ecb}, + {WC_DES_EDE3_CBC_TYPE, EVP_DES_EDE3_CBC, WC_NID_des_ede3_cbc}, + {WC_DES_EDE3_ECB_TYPE, EVP_DES_EDE3_ECB, WC_NID_des_ede3_ecb}, #endif #ifndef NO_RC4 - {ARC4_TYPE, EVP_ARC4, NID_undef}, + {WC_ARC4_TYPE, EVP_ARC4, WC_NID_undef}, #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - {CHACHA20_POLY1305_TYPE, EVP_CHACHA20_POLY1305, NID_chacha20_poly1305}, + {WC_CHACHA20_POLY1305_TYPE, EVP_CHACHA20_POLY1305, WC_NID_chacha20_poly1305}, #endif #ifdef HAVE_CHACHA - {CHACHA20_TYPE, EVP_CHACHA20, NID_chacha20}, + {WC_CHACHA20_TYPE, EVP_CHACHA20, WC_NID_chacha20}, #endif #ifdef WOLFSSL_SM4_ECB - {SM4_ECB_TYPE, EVP_SM4_ECB, NID_sm4_ecb}, + {WC_SM4_ECB_TYPE, EVP_SM4_ECB, WC_NID_sm4_ecb}, #endif #ifdef WOLFSSL_SM4_CBC - {SM4_CBC_TYPE, EVP_SM4_CBC, NID_sm4_cbc}, + {WC_SM4_CBC_TYPE, EVP_SM4_CBC, WC_NID_sm4_cbc}, #endif #ifdef WOLFSSL_SM4_CTR - {SM4_CTR_TYPE, EVP_SM4_CTR, NID_sm4_ctr}, + {WC_SM4_CTR_TYPE, EVP_SM4_CTR, WC_NID_sm4_ctr}, #endif #ifdef WOLFSSL_SM4_GCM - {SM4_GCM_TYPE, EVP_SM4_GCM, NID_sm4_gcm}, + {WC_SM4_GCM_TYPE, EVP_SM4_GCM, WC_NID_sm4_gcm}, #endif #ifdef WOLFSSL_SM4_CCM - {SM4_CCM_TYPE, EVP_SM4_CCM, NID_sm4_ccm}, + {WC_SM4_CCM_TYPE, EVP_SM4_CCM, WC_NID_sm4_ccm}, #endif { 0, NULL, 0} @@ -5293,128 +5299,128 @@ const WOLFSSL_EVP_CIPHER *wolfSSL_EVP_get_cipherbynid(int id) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - case NID_aes_128_cbc: + case WC_NID_aes_128_cbc: return wolfSSL_EVP_aes_128_cbc(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_cbc: + case WC_NID_aes_192_cbc: return wolfSSL_EVP_aes_192_cbc(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_cbc: + case WC_NID_aes_256_cbc: return wolfSSL_EVP_aes_256_cbc(); #endif #endif #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - case NID_aes_128_ctr: + case WC_NID_aes_128_ctr: return wolfSSL_EVP_aes_128_ctr(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ctr: + case WC_NID_aes_192_ctr: return wolfSSL_EVP_aes_192_ctr(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ctr: + case WC_NID_aes_256_ctr: return wolfSSL_EVP_aes_256_ctr(); #endif #endif /* WOLFSSL_AES_COUNTER */ #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - case NID_aes_128_ecb: + case WC_NID_aes_128_ecb: return wolfSSL_EVP_aes_128_ecb(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ecb: + case WC_NID_aes_192_ecb: return wolfSSL_EVP_aes_192_ecb(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ecb: + case WC_NID_aes_256_ecb: return wolfSSL_EVP_aes_256_ecb(); #endif #endif /* HAVE_AES_ECB */ #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 - case NID_aes_128_gcm: + case WC_NID_aes_128_gcm: return wolfSSL_EVP_aes_128_gcm(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_gcm: + case WC_NID_aes_192_gcm: return wolfSSL_EVP_aes_192_gcm(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_gcm: + case WC_NID_aes_256_gcm: return wolfSSL_EVP_aes_256_gcm(); #endif #endif #ifdef HAVE_AESCCM #ifdef WOLFSSL_AES_128 - case NID_aes_128_ccm: + case WC_NID_aes_128_ccm: return wolfSSL_EVP_aes_128_ccm(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ccm: + case WC_NID_aes_192_ccm: return wolfSSL_EVP_aes_192_ccm(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ccm: + case WC_NID_aes_256_ccm: return wolfSSL_EVP_aes_256_ccm(); #endif #endif #endif #ifdef HAVE_ARIA - case NID_aria_128_gcm: + case WC_NID_aria_128_gcm: return wolfSSL_EVP_aria_128_gcm(); - case NID_aria_192_gcm: + case WC_NID_aria_192_gcm: return wolfSSL_EVP_aria_192_gcm(); - case NID_aria_256_gcm: + case WC_NID_aria_256_gcm: return wolfSSL_EVP_aria_256_gcm(); #endif #ifndef NO_DES3 - case NID_des_cbc: + case WC_NID_des_cbc: return wolfSSL_EVP_des_cbc(); #ifdef WOLFSSL_DES_ECB - case NID_des_ecb: + case WC_NID_des_ecb: return wolfSSL_EVP_des_ecb(); #endif - case NID_des_ede3_cbc: + case WC_NID_des_ede3_cbc: return wolfSSL_EVP_des_ede3_cbc(); #ifdef WOLFSSL_DES_ECB - case NID_des_ede3_ecb: + case WC_NID_des_ede3_ecb: return wolfSSL_EVP_des_ede3_ecb(); #endif #endif /*NO_DES3*/ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case NID_chacha20_poly1305: + case WC_NID_chacha20_poly1305: return wolfSSL_EVP_chacha20_poly1305(); #endif #ifdef HAVE_CHACHA - case NID_chacha20: + case WC_NID_chacha20: return wolfSSL_EVP_chacha20(); #endif #ifdef WOLFSSL_SM4_ECB - case NID_sm4_ecb: + case WC_NID_sm4_ecb: return wolfSSL_EVP_sm4_ecb(); #endif #ifdef WOLFSSL_SM4_CBC - case NID_sm4_cbc: + case WC_NID_sm4_cbc: return wolfSSL_EVP_sm4_cbc(); #endif #ifdef WOLFSSL_SM4_CTR - case NID_sm4_ctr: + case WC_NID_sm4_ctr: return wolfSSL_EVP_sm4_ctr(); #endif #ifdef WOLFSSL_SM4_GCM - case NID_sm4_gcm: + case WC_NID_sm4_gcm: return wolfSSL_EVP_sm4_gcm(); #endif #ifdef WOLFSSL_SM4_CCM - case NID_sm4_ccm: + case WC_NID_sm4_ccm: return wolfSSL_EVP_sm4_ccm(); #endif @@ -5622,7 +5628,7 @@ void wolfSSL_EVP_init(void) #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0)) + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) { @@ -5670,7 +5676,7 @@ void wolfSSL_EVP_init(void) return EVP_AES_256_CFB8; } #endif /* WOLFSSL_AES_256 */ -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb128(void) @@ -5992,22 +5998,22 @@ void wolfSSL_EVP_init(void) WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_ctrl"); switch(type) { - case EVP_CTRL_INIT: + case WOLFSSL_EVP_CTRL_INIT: wolfSSL_EVP_CIPHER_CTX_init(ctx); if(ctx) ret = WOLFSSL_SUCCESS; break; - case EVP_CTRL_SET_KEY_LENGTH: + case WOLFSSL_EVP_CTRL_SET_KEY_LENGTH: ret = wolfSSL_EVP_CIPHER_CTX_set_key_length(ctx, arg); break; #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA) || \ defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) || \ (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IVLEN: + case WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_IV_SIZE) { break; } @@ -6015,7 +6021,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6023,7 +6029,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6031,7 +6037,7 @@ void wolfSSL_EVP_init(void) else #endif { - if (arg <= 0 || arg > AES_BLOCK_SIZE) + if (arg <= 0 || arg > WC_AES_BLOCK_SIZE) break; } ret = wolfSSL_EVP_CIPHER_CTX_set_iv_length(ctx, arg); @@ -6039,7 +6045,7 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_AESGCM) || defined(WOLFSSL_SM4_GCM) || \ (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IV_FIXED: + case WOLFSSL_EVP_CTRL_AEAD_SET_IV_FIXED: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; if (arg == -1) { @@ -6098,7 +6104,7 @@ void wolfSSL_EVP_init(void) * EVP_CipherInit between each iteration. The IV is incremented for * each subsequent EVP_Cipher call to prevent IV reuse. */ - case EVP_CTRL_GCM_IV_GEN: + case WOLFSSL_EVP_CTRL_GCM_IV_GEN: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; if (!ctx->authIvGenEnable) { @@ -6134,11 +6140,11 @@ void wolfSSL_EVP_init(void) break; #endif /* (HAVE_AESGCM || WOLFSSL_SM4_GCM) && !_WIN32 && !HAVE_SELFTEST && * !HAVE_FIPS || FIPS_VERSION >= 2)*/ - case EVP_CTRL_AEAD_SET_TAG: + case WOLFSSL_EVP_CTRL_AEAD_SET_TAG: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { break; } @@ -6152,7 +6158,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if ((arg <= 0) || (arg > SM4_BLOCK_SIZE) || (ptr == NULL)) { break; } @@ -6165,7 +6171,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if ((arg <= 0) || (arg > SM4_BLOCK_SIZE) || (ptr == NULL)) { break; } @@ -6186,12 +6192,12 @@ void wolfSSL_EVP_init(void) ret = WOLFSSL_SUCCESS; break; } - case EVP_CTRL_AEAD_GET_TAG: + case WOLFSSL_EVP_CTRL_AEAD_GET_TAG: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { break; } @@ -6199,7 +6205,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6207,7 +6213,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6215,7 +6221,7 @@ void wolfSSL_EVP_init(void) else #endif { - if (arg <= 0 || arg > AES_BLOCK_SIZE) + if (arg <= 0 || arg > WC_AES_BLOCK_SIZE) break; } @@ -6252,62 +6258,62 @@ void wolfSSL_EVP_init(void) defined(WOLFSSL_AES_XTS) #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #endif /* HAVE_AESGCM */ #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: #endif /* HAVE_AESCCM */ #ifdef HAVE_AES_CBC - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: #endif #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: #endif #ifdef WOLFSSL_AES_CFB - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: #endif #ifdef WOLFSSL_AES_OFB - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: #endif wc_AesFree(&ctx->cipher.aes); ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: wc_AesXtsFree(&ctx->cipher.xts); ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #endif #endif /* AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: { int result = wc_AriaFreeCrypt(&ctx->cipher.aria); if (result != 0) { @@ -6324,19 +6330,19 @@ void wolfSSL_EVP_init(void) #ifdef WOLFSSL_SM4 switch (ctx->cipherType) { #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: #endif wc_Sm4Free(&ctx->cipher.sm4); } @@ -6462,7 +6468,7 @@ void wolfSSL_EVP_init(void) /* wc_AesSetKey clear aes.reg if iv == NULL. Keep IV for openSSL compatibility */ if (iv == NULL) - XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, AES_BLOCK_SIZE); + XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, WC_AES_BLOCK_SIZE); if (direct) { #if defined(WOLFSSL_AES_DIRECT) ret = wc_AesSetKeyDirect(aes, key, len, iv, dir); @@ -6474,7 +6480,7 @@ void wolfSSL_EVP_init(void) ret = wc_AesSetKey(aes, key, len, iv, dir); } if (iv == NULL) - XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, AES_BLOCK_SIZE); + XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, WC_AES_BLOCK_SIZE); return ret; } #endif /* AES_ANY_SIZE && AES_SET_KEY */ @@ -6492,8 +6498,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6505,26 +6511,26 @@ void wolfSSL_EVP_init(void) } #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_GCM_TYPE || + if (ctx->cipherType == WC_AES_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM))) { WOLFSSL_MSG("EVP_AES_128_GCM"); - ctx->cipherType = AES_128_GCM_TYPE; + ctx->cipherType = WC_AES_128_GCM_TYPE; ctx->keyLen = AES_128_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_GCM_TYPE || + if (ctx->cipherType == WC_AES_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM))) { WOLFSSL_MSG("EVP_AES_192_GCM"); - ctx->cipherType = AES_192_GCM_TYPE; + ctx->cipherType = WC_AES_192_GCM_TYPE; ctx->keyLen = AES_192_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_GCM_TYPE || + if (ctx->cipherType == WC_AES_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM))) { WOLFSSL_MSG("EVP_AES_256_GCM"); - ctx->cipherType = AES_256_GCM_TYPE; + ctx->cipherType = WC_AES_256_GCM_TYPE; ctx->keyLen = AES_256_KEY_SIZE; } #endif @@ -6697,8 +6703,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6710,26 +6716,26 @@ void wolfSSL_EVP_init(void) } #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CCM_TYPE || + if (ctx->cipherType == WC_AES_128_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM))) { WOLFSSL_MSG("EVP_AES_128_CCM"); - ctx->cipherType = AES_128_CCM_TYPE; + ctx->cipherType = WC_AES_128_CCM_TYPE; ctx->keyLen = AES_128_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CCM_TYPE || + if (ctx->cipherType == WC_AES_192_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM))) { WOLFSSL_MSG("EVP_AES_192_CCM"); - ctx->cipherType = AES_192_CCM_TYPE; + ctx->cipherType = WC_AES_192_CCM_TYPE; ctx->keyLen = AES_192_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CCM_TYPE || + if (ctx->cipherType == WC_AES_256_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM))) { WOLFSSL_MSG("EVP_AES_256_CCM"); - ctx->cipherType = AES_256_CCM_TYPE; + ctx->cipherType = WC_AES_256_CCM_TYPE; ctx->keyLen = AES_256_KEY_SIZE; } #endif @@ -6822,20 +6828,20 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->cipherType == ARIA_128_GCM_TYPE || + if (ctx->cipherType == WC_ARIA_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_128_GCM))) { WOLFSSL_MSG("EVP_ARIA_128_GCM"); - ctx->cipherType = ARIA_128_GCM_TYPE; + ctx->cipherType = WC_ARIA_128_GCM_TYPE; ctx->keyLen = ARIA_128_KEY_SIZE; - } else if (ctx->cipherType == ARIA_192_GCM_TYPE || + } else if (ctx->cipherType == WC_ARIA_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_192_GCM))) { WOLFSSL_MSG("EVP_ARIA_192_GCM"); - ctx->cipherType = ARIA_192_GCM_TYPE; + ctx->cipherType = WC_ARIA_192_GCM_TYPE; ctx->keyLen = ARIA_192_KEY_SIZE; - } else if (ctx->cipherType == ARIA_256_GCM_TYPE || + } else if (ctx->cipherType == WC_ARIA_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_256_GCM))) { WOLFSSL_MSG("EVP_ARIA_256_GCM"); - ctx->cipherType = ARIA_256_GCM_TYPE; + ctx->cipherType = WC_ARIA_256_GCM_TYPE; ctx->keyLen = ARIA_256_KEY_SIZE; } else { WOLFSSL_MSG("Unrecognized cipher type"); @@ -6846,8 +6852,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6859,13 +6865,13 @@ void wolfSSL_EVP_init(void) } switch(ctx->cipherType) { - case ARIA_128_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_128BITKEY); break; - case ARIA_192_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_192BITKEY); break; - case ARIA_256_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_256BITKEY); break; default: @@ -6931,15 +6937,15 @@ void wolfSSL_EVP_init(void) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CBC_TYPE || + if (ctx->cipherType == WC_AES_128_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CBC))) { WOLFSSL_MSG("EVP_AES_128_CBC"); - ctx->cipherType = AES_128_CBC_TYPE; + ctx->cipherType = WC_AES_128_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 16; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -6961,15 +6967,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CBC_TYPE || + if (ctx->cipherType == WC_AES_192_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CBC))) { WOLFSSL_MSG("EVP_AES_192_CBC"); - ctx->cipherType = AES_192_CBC_TYPE; + ctx->cipherType = WC_AES_192_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 24; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -6991,15 +6997,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CBC_TYPE || + if (ctx->cipherType == WC_AES_256_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CBC))) { WOLFSSL_MSG("EVP_AES_256_CBC"); - ctx->cipherType = AES_256_CBC_TYPE; + ctx->cipherType = WC_AES_256_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 32; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7029,15 +7035,15 @@ void wolfSSL_EVP_init(void) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_GCM_TYPE || + || ctx->cipherType == WC_AES_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM)) #endif #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_GCM_TYPE || + || ctx->cipherType == WC_AES_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM)) #endif #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_GCM_TYPE || + || ctx->cipherType == WC_AES_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM)) #endif ) { @@ -7053,15 +7059,15 @@ void wolfSSL_EVP_init(void) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_CCM_TYPE || + || ctx->cipherType == WC_AES_128_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM)) #endif #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_CCM_TYPE || + || ctx->cipherType == WC_AES_192_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM)) #endif #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_CCM_TYPE || + || ctx->cipherType == WC_AES_256_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM)) #endif ) @@ -7075,15 +7081,15 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CTR_TYPE || + if (ctx->cipherType == WC_AES_128_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CTR))) { WOLFSSL_MSG("EVP_AES_128_CTR"); ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; - ctx->cipherType = AES_128_CTR_TYPE; + ctx->cipherType = WC_AES_128_CTR_TYPE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 16; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7108,15 +7114,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CTR_TYPE || + if (ctx->cipherType == WC_AES_192_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CTR))) { WOLFSSL_MSG("EVP_AES_192_CTR"); - ctx->cipherType = AES_192_CTR_TYPE; + ctx->cipherType = WC_AES_192_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 24; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7141,15 +7147,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CTR_TYPE || + if (ctx->cipherType == WC_AES_256_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CTR))) { WOLFSSL_MSG("EVP_AES_256_CTR"); - ctx->cipherType = AES_256_CTR_TYPE; + ctx->cipherType = WC_AES_256_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 32; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7176,14 +7182,14 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_COUNTER */ #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_ECB_TYPE || + if (ctx->cipherType == WC_AES_128_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_ECB))) { WOLFSSL_MSG("EVP_AES_128_ECB"); - ctx->cipherType = AES_128_ECB_TYPE; + ctx->cipherType = WC_AES_128_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 16; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7200,14 +7206,14 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_ECB_TYPE || + if (ctx->cipherType == WC_AES_192_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_ECB))) { WOLFSSL_MSG("EVP_AES_192_ECB"); - ctx->cipherType = AES_192_ECB_TYPE; + ctx->cipherType = WC_AES_192_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 24; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7224,14 +7230,14 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_ECB_TYPE || + if (ctx->cipherType == WC_AES_256_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_ECB))) { WOLFSSL_MSG("EVP_AES_256_ECB"); - ctx->cipherType = AES_256_ECB_TYPE; + ctx->cipherType = WC_AES_256_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 32; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7249,11 +7255,12 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_256 */ #endif /* HAVE_AES_ECB */ #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB1_TYPE || + if (ctx->cipherType == WC_AES_128_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB1))) { WOLFSSL_MSG("EVP_AES_128_CFB1"); - ctx->cipherType = AES_128_CFB1_TYPE; + ctx->cipherType = WC_AES_128_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7279,10 +7286,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB1_TYPE || + if (ctx->cipherType == WC_AES_192_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB1))) { WOLFSSL_MSG("EVP_AES_192_CFB1"); - ctx->cipherType = AES_192_CFB1_TYPE; + ctx->cipherType = WC_AES_192_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7308,10 +7315,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB1_TYPE || + if (ctx->cipherType == WC_AES_256_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB1))) { WOLFSSL_MSG("EVP_AES_256_CFB1"); - ctx->cipherType = AES_256_CFB1_TYPE; + ctx->cipherType = WC_AES_256_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7341,10 +7348,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_256 */ #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB8_TYPE || + if (ctx->cipherType == WC_AES_128_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB8))) { WOLFSSL_MSG("EVP_AES_128_CFB8"); - ctx->cipherType = AES_128_CFB8_TYPE; + ctx->cipherType = WC_AES_128_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7370,10 +7377,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB8_TYPE || + if (ctx->cipherType == WC_AES_192_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB8))) { WOLFSSL_MSG("EVP_AES_192_CFB8"); - ctx->cipherType = AES_192_CFB8_TYPE; + ctx->cipherType = WC_AES_192_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7399,10 +7406,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB8_TYPE || + if (ctx->cipherType == WC_AES_256_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB8))) { WOLFSSL_MSG("EVP_AES_256_CFB8"); - ctx->cipherType = AES_256_CFB8_TYPE; + ctx->cipherType = WC_AES_256_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7431,11 +7438,12 @@ void wolfSSL_EVP_init(void) } } #endif /* WOLFSSL_AES_256 */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB128_TYPE || + if (ctx->cipherType == WC_AES_128_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB128))) { WOLFSSL_MSG("EVP_AES_128_CFB128"); - ctx->cipherType = AES_128_CFB128_TYPE; + ctx->cipherType = WC_AES_128_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7461,10 +7469,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB128_TYPE || + if (ctx->cipherType == WC_AES_192_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB128))) { WOLFSSL_MSG("EVP_AES_192_CFB128"); - ctx->cipherType = AES_192_CFB128_TYPE; + ctx->cipherType = WC_AES_192_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7490,10 +7498,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB128_TYPE || + if (ctx->cipherType == WC_AES_256_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB128))) { WOLFSSL_MSG("EVP_AES_256_CFB128"); - ctx->cipherType = AES_256_CFB128_TYPE; + ctx->cipherType = WC_AES_256_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7525,10 +7533,10 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_CFB */ #ifdef WOLFSSL_AES_OFB #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_OFB_TYPE || + if (ctx->cipherType == WC_AES_128_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_OFB))) { WOLFSSL_MSG("EVP_AES_128_OFB"); - ctx->cipherType = AES_128_OFB_TYPE; + ctx->cipherType = WC_AES_128_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 16; @@ -7554,10 +7562,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_OFB_TYPE || + if (ctx->cipherType == WC_AES_192_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_OFB))) { WOLFSSL_MSG("EVP_AES_192_OFB"); - ctx->cipherType = AES_192_OFB_TYPE; + ctx->cipherType = WC_AES_192_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 24; @@ -7583,10 +7591,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_OFB_TYPE || + if (ctx->cipherType == WC_AES_256_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_OFB))) { WOLFSSL_MSG("EVP_AES_256_OFB"); - ctx->cipherType = AES_256_OFB_TYPE; + ctx->cipherType = WC_AES_256_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 32; @@ -7619,22 +7627,22 @@ void wolfSSL_EVP_init(void) #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_XTS_TYPE || + if (ctx->cipherType == WC_AES_128_XTS_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_XTS))) { WOLFSSL_MSG("EVP_AES_128_XTS"); - ctx->cipherType = AES_128_XTS_TYPE; + ctx->cipherType = WC_AES_128_XTS_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_XTS_MODE; ctx->keyLen = 32; ctx->block_size = 1; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (iv != NULL) { if (iv != ctx->iv) /* Valgrind error when src == dst */ XMEMCPY(ctx->iv, iv, (size_t)ctx->ivSz); } else - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7660,22 +7668,22 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_XTS_TYPE || + if (ctx->cipherType == WC_AES_256_XTS_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_XTS))) { WOLFSSL_MSG("EVP_AES_256_XTS"); - ctx->cipherType = AES_256_XTS_TYPE; + ctx->cipherType = WC_AES_256_XTS_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_XTS_MODE; ctx->keyLen = 64; ctx->block_size = 1; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (iv != NULL) { if (iv != ctx->iv) /* Valgrind error when src == dst */ XMEMCPY(ctx->iv, iv, (size_t)ctx->ivSz); } else - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7704,11 +7712,11 @@ void wolfSSL_EVP_init(void) (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #endif /* NO_AES */ #if defined(HAVE_ARIA) - if (ctx->cipherType == ARIA_128_GCM_TYPE || + if (ctx->cipherType == WC_ARIA_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_128_GCM)) - || ctx->cipherType == ARIA_192_GCM_TYPE || + || ctx->cipherType == WC_ARIA_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_192_GCM)) - || ctx->cipherType == ARIA_256_GCM_TYPE || + || ctx->cipherType == WC_ARIA_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_256_GCM)) ) { if (EvpCipherInitAriaGCM(ctx, type, key, iv, enc) @@ -7721,10 +7729,10 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE || + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_CHACHA20_POLY1305))) { WOLFSSL_MSG("EVP_CHACHA20_POLY1305"); - ctx->cipherType = CHACHA20_POLY1305_TYPE; + ctx->cipherType = WC_CHACHA20_POLY1305_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; ctx->keyLen = CHACHA20_POLY1305_AEAD_KEYSIZE; @@ -7758,10 +7766,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef HAVE_CHACHA - if (ctx->cipherType == CHACHA20_TYPE || + if (ctx->cipherType == WC_CHACHA20_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_CHACHA20))) { WOLFSSL_MSG("EVP_CHACHA20"); - ctx->cipherType = CHACHA20_TYPE; + ctx->cipherType = WC_CHACHA20_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->keyLen = CHACHA_MAX_KEY_SZ; ctx->block_size = 1; @@ -7791,10 +7799,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_ECB - if (ctx->cipherType == SM4_ECB_TYPE || + if (ctx->cipherType == WC_SM4_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_ECB))) { WOLFSSL_MSG("EVP_SM4_ECB"); - ctx->cipherType = SM4_ECB_TYPE; + ctx->cipherType = WC_SM4_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = SM4_KEY_SIZE; @@ -7810,10 +7818,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CBC - if (ctx->cipherType == SM4_CBC_TYPE || + if (ctx->cipherType == WC_SM4_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CBC))) { WOLFSSL_MSG("EVP_SM4_CBC"); - ctx->cipherType = SM4_CBC_TYPE; + ctx->cipherType = WC_SM4_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = SM4_KEY_SIZE; @@ -7836,14 +7844,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CTR - if (ctx->cipherType == SM4_CTR_TYPE || + if (ctx->cipherType == WC_SM4_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CTR))) { WOLFSSL_MSG("EVP_SM4_CTR"); - ctx->cipherType = SM4_CTR_TYPE; + ctx->cipherType = WC_SM4_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = SM4_KEY_SIZE; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->ivSz = SM4_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7862,14 +7870,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_GCM - if (ctx->cipherType == SM4_GCM_TYPE || + if (ctx->cipherType == WC_SM4_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_GCM))) { WOLFSSL_MSG("EVP_SM4_GCM"); - ctx->cipherType = SM4_GCM_TYPE; + ctx->cipherType = WC_SM4_GCM_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->keyLen = SM4_KEY_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; @@ -7892,14 +7900,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CCM - if (ctx->cipherType == SM4_CCM_TYPE || + if (ctx->cipherType == WC_SM4_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CCM))) { WOLFSSL_MSG("EVP_SM4_CCM"); - ctx->cipherType = SM4_CCM_TYPE; + ctx->cipherType = WC_SM4_CCM_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->keyLen = SM4_KEY_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; @@ -7922,10 +7930,10 @@ void wolfSSL_EVP_init(void) } #endif #ifndef NO_DES3 - if (ctx->cipherType == DES_CBC_TYPE || + if (ctx->cipherType == WC_DES_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_CBC))) { WOLFSSL_MSG("EVP_DES_CBC"); - ctx->cipherType = DES_CBC_TYPE; + ctx->cipherType = WC_DES_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 8; @@ -7944,10 +7952,10 @@ void wolfSSL_EVP_init(void) wc_Des_SetIV(&ctx->cipher.des, iv); } #ifdef WOLFSSL_DES_ECB - else if (ctx->cipherType == DES_ECB_TYPE || + else if (ctx->cipherType == WC_DES_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_ECB))) { WOLFSSL_MSG("EVP_DES_ECB"); - ctx->cipherType = DES_ECB_TYPE; + ctx->cipherType = WC_DES_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 8; @@ -7963,11 +7971,11 @@ void wolfSSL_EVP_init(void) } } #endif - else if (ctx->cipherType == DES_EDE3_CBC_TYPE || + else if (ctx->cipherType == WC_DES_EDE3_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_EDE3_CBC))) { WOLFSSL_MSG("EVP_DES_EDE3_CBC"); - ctx->cipherType = DES_EDE3_CBC_TYPE; + ctx->cipherType = WC_DES_EDE3_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 24; @@ -7988,11 +7996,11 @@ void wolfSSL_EVP_init(void) return WOLFSSL_FAILURE; } } - else if (ctx->cipherType == DES_EDE3_ECB_TYPE || + else if (ctx->cipherType == WC_DES_EDE3_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_EDE3_ECB))) { WOLFSSL_MSG("EVP_DES_EDE3_ECB"); - ctx->cipherType = DES_EDE3_ECB_TYPE; + ctx->cipherType = WC_DES_EDE3_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 24; @@ -8008,10 +8016,10 @@ void wolfSSL_EVP_init(void) } #endif /* NO_DES3 */ #ifndef NO_RC4 - if (ctx->cipherType == ARC4_TYPE || + if (ctx->cipherType == WC_ARC4_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARC4))) { WOLFSSL_MSG("ARC4"); - ctx->cipherType = ARC4_TYPE; + ctx->cipherType = WC_ARC4_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_STREAM_CIPHER; ctx->block_size = 1; @@ -8021,10 +8029,10 @@ void wolfSSL_EVP_init(void) wc_Arc4SetKey(&ctx->cipher.arc4, key, (word32)ctx->keyLen); } #endif /* NO_RC4 */ - if (ctx->cipherType == NULL_CIPHER_TYPE || + if (ctx->cipherType == WC_NULL_CIPHER_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_NULL))) { WOLFSSL_MSG("NULL cipher"); - ctx->cipherType = NULL_CIPHER_TYPE; + ctx->cipherType = WC_NULL_CIPHER_TYPE; ctx->keyLen = 0; ctx->block_size = 16; } @@ -8045,120 +8053,120 @@ void wolfSSL_EVP_init(void) WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_nid"); if (ctx == NULL) { WOLFSSL_ERROR_MSG("Bad parameters"); - return NID_undef; + return WC_NID_undef; } switch (ctx->cipherType) { #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - return NID_aes_128_cbc; - case AES_192_CBC_TYPE : - return NID_aes_192_cbc; - case AES_256_CBC_TYPE : - return NID_aes_256_cbc; + case WC_AES_128_CBC_TYPE : + return WC_NID_aes_128_cbc; + case WC_AES_192_CBC_TYPE : + return WC_NID_aes_192_cbc; + case WC_AES_256_CBC_TYPE : + return WC_NID_aes_256_cbc; #endif #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - return NID_aes_128_gcm; - case AES_192_GCM_TYPE : - return NID_aes_192_gcm; - case AES_256_GCM_TYPE : - return NID_aes_256_gcm; + case WC_AES_128_GCM_TYPE : + return WC_NID_aes_128_gcm; + case WC_AES_192_GCM_TYPE : + return WC_NID_aes_192_gcm; + case WC_AES_256_GCM_TYPE : + return WC_NID_aes_256_gcm; #endif #ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - return NID_aes_128_ccm; - case AES_192_CCM_TYPE : - return NID_aes_192_ccm; - case AES_256_CCM_TYPE : - return NID_aes_256_ccm; + case WC_AES_128_CCM_TYPE : + return WC_NID_aes_128_ccm; + case WC_AES_192_CCM_TYPE : + return WC_NID_aes_192_ccm; + case WC_AES_256_CCM_TYPE : + return WC_NID_aes_256_ccm; #endif #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - return NID_aes_128_ecb; - case AES_192_ECB_TYPE : - return NID_aes_192_ecb; - case AES_256_ECB_TYPE : - return NID_aes_256_ecb; + case WC_AES_128_ECB_TYPE : + return WC_NID_aes_128_ecb; + case WC_AES_192_ECB_TYPE : + return WC_NID_aes_192_ecb; + case WC_AES_256_ECB_TYPE : + return WC_NID_aes_256_ecb; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - return NID_aes_128_ctr; - case AES_192_CTR_TYPE : - return NID_aes_192_ctr; - case AES_256_CTR_TYPE : - return NID_aes_256_ctr; + case WC_AES_128_CTR_TYPE : + return WC_NID_aes_128_ctr; + case WC_AES_192_CTR_TYPE : + return WC_NID_aes_192_ctr; + case WC_AES_256_CTR_TYPE : + return WC_NID_aes_256_ctr; #endif #endif /* NO_AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - return NID_aria_128_gcm; - case ARIA_192_GCM_TYPE : - return NID_aria_192_gcm; - case ARIA_256_GCM_TYPE : - return NID_aria_256_gcm; + case WC_ARIA_128_GCM_TYPE : + return WC_NID_aria_128_gcm; + case WC_ARIA_192_GCM_TYPE : + return WC_NID_aria_192_gcm; + case WC_ARIA_256_GCM_TYPE : + return WC_NID_aria_256_gcm; #endif #ifndef NO_DES3 - case DES_CBC_TYPE : - return NID_des_cbc; + case WC_DES_CBC_TYPE : + return WC_NID_des_cbc; - case DES_EDE3_CBC_TYPE : - return NID_des_ede3_cbc; + case WC_DES_EDE3_CBC_TYPE : + return WC_NID_des_ede3_cbc; #endif #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : - return NID_des_ecb; - case DES_EDE3_ECB_TYPE : - return NID_des_ede3_ecb; + case WC_DES_ECB_TYPE : + return WC_NID_des_ecb; + case WC_DES_EDE3_ECB_TYPE : + return WC_NID_des_ede3_ecb; #endif - case ARC4_TYPE : - return NID_rc4; + case WC_ARC4_TYPE : + return WC_NID_rc4; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: - return NID_chacha20_poly1305; + case WC_CHACHA20_POLY1305_TYPE: + return WC_NID_chacha20_poly1305; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: - return NID_chacha20; + case WC_CHACHA20_TYPE: + return WC_NID_chacha20; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: - return NID_sm4_ecb; + case WC_SM4_ECB_TYPE: + return WC_NID_sm4_ecb; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: - return NID_sm4_cbc; + case WC_SM4_CBC_TYPE: + return WC_NID_sm4_cbc; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: - return NID_sm4_ctr; + case WC_SM4_CTR_TYPE: + return WC_NID_sm4_ctr; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: - return NID_sm4_gcm; + case WC_SM4_GCM_TYPE: + return WC_NID_sm4_gcm; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: - return NID_sm4_ccm; + case WC_SM4_CCM_TYPE: + return WC_NID_sm4_ccm; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_ERROR_MSG("Null cipher has no NID"); FALL_THROUGH; default: - return NID_undef; + return WC_NID_undef; } } @@ -8253,17 +8261,17 @@ void wolfSSL_EVP_init(void) static int IsCipherTypeAEAD(unsigned char cipherType) { switch (cipherType) { - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: - case SM4_GCM_TYPE: - case SM4_CCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: + case WC_SM4_GCM_TYPE: + case WC_SM4_CCM_TYPE: return 1; default: return 0; @@ -8303,24 +8311,24 @@ void wolfSSL_EVP_init(void) #ifndef NO_AES #ifdef HAVE_AES_CBC - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); if (ctx->enc) ret = wc_AesCbcEncrypt(&ctx->cipher.aes, dst, src, len); else ret = wc_AesCbcDecrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) - ret = (int)((len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE); + ret = (int)((len / WC_AES_BLOCK_SIZE) * WC_AES_BLOCK_SIZE); break; #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: +#if !defined(WOLFSSL_NO_AES_CFB_1_8) + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: WOLFSSL_MSG("AES CFB1"); if (ctx->enc) ret = wc_AesCfb1Encrypt(&ctx->cipher.aes, dst, src, len); @@ -8329,9 +8337,9 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)len; break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: WOLFSSL_MSG("AES CFB8"); if (ctx->enc) ret = wc_AesCfb8Encrypt(&ctx->cipher.aes, dst, src, len); @@ -8340,10 +8348,10 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)len; break; -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: +#endif /* !WOLFSSL_NO_AES_CFB_1_8 */ + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: WOLFSSL_MSG("AES CFB128"); if (ctx->enc) ret = wc_AesCfbEncrypt(&ctx->cipher.aes, dst, src, len); @@ -8354,9 +8362,9 @@ void wolfSSL_EVP_init(void) break; #endif /* WOLFSSL_AES_CFB */ #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: WOLFSSL_MSG("AES OFB"); if (ctx->enc) ret = wc_AesOfbEncrypt(&ctx->cipher.aes, dst, src, len); @@ -8367,8 +8375,8 @@ void wolfSSL_EVP_init(void) break; #endif /* WOLFSSL_AES_OFB */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: WOLFSSL_MSG("AES XTS"); if (ctx->enc) ret = wc_AesXtsEncrypt(&ctx->cipher.xts, dst, src, len, @@ -8383,9 +8391,9 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); ret = EvpCipherAesGCM(ctx, dst, src, len); break; @@ -8393,31 +8401,31 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : + case WC_AES_128_CCM_TYPE : + case WC_AES_192_CCM_TYPE : + case WC_AES_256_CCM_TYPE : WOLFSSL_MSG("AES CCM"); ret = EvpCipherAesCCM(ctx, dst, src, len); break; #endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || * HAVE_FIPS_VERSION >= 2 */ #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : + case WC_AES_128_ECB_TYPE : + case WC_AES_192_ECB_TYPE : + case WC_AES_256_ECB_TYPE : WOLFSSL_MSG("AES ECB"); if (ctx->enc) ret = wc_AesEcbEncrypt(&ctx->cipher.aes, dst, src, len); else ret = wc_AesEcbDecrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) - ret = (int)((len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE); + ret = (int)((len / WC_AES_BLOCK_SIZE) * WC_AES_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); ret = wc_AesCtrEncrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) @@ -8428,9 +8436,9 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_ARIA) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); if (ctx->enc) { ret = wc_AriaEncrypt(&ctx->cipher.aria, dst, src, len, @@ -8447,7 +8455,7 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); if (ctx->enc) wc_Des_CbcEncrypt(&ctx->cipher.des, dst, src, len); @@ -8456,7 +8464,7 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES3 CBC"); if (ctx->enc) ret = wc_Des3_CbcEncrypt(&ctx->cipher.des3, dst, src, len); @@ -8466,13 +8474,13 @@ void wolfSSL_EVP_init(void) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : + case WC_DES_ECB_TYPE : WOLFSSL_MSG("DES ECB"); ret = wc_Des_EcbEncrypt(&ctx->cipher.des, dst, src, len); if (ret == 0) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; - case DES_EDE3_ECB_TYPE : + case WC_DES_EDE3_ECB_TYPE : WOLFSSL_MSG("DES3 ECB"); ret = wc_Des3_EcbEncrypt(&ctx->cipher.des3, dst, src, len); if (ret == 0) @@ -8482,7 +8490,7 @@ void wolfSSL_EVP_init(void) #endif /* !NO_DES3 */ #ifndef NO_RC4 - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); wc_Arc4Process(&ctx->cipher.arc4, dst, src, len); if (ret == 0) @@ -8493,7 +8501,7 @@ void wolfSSL_EVP_init(void) /* TODO: Chacha??? */ #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE : + case WC_SM4_ECB_TYPE : WOLFSSL_MSG("Sm4 ECB"); if (ctx->enc) ret = wc_Sm4EcbEncrypt(&ctx->cipher.sm4, dst, src, len); @@ -8504,7 +8512,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE : + case WC_SM4_CBC_TYPE : WOLFSSL_MSG("Sm4 CBC"); if (ctx->enc) ret = wc_Sm4CbcEncrypt(&ctx->cipher.sm4, dst, src, len); @@ -8515,7 +8523,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE : + case WC_SM4_CTR_TYPE : WOLFSSL_MSG("AES CTR"); ret = wc_Sm4CtrEncrypt(&ctx->cipher.sm4, dst, src, len); if (ret == 0) @@ -8523,7 +8531,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE : + case WC_SM4_GCM_TYPE : WOLFSSL_MSG("SM4 GCM"); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -8551,7 +8559,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE : + case WC_SM4_CCM_TYPE : WOLFSSL_MSG("SM4 CCM"); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -8592,7 +8600,7 @@ void wolfSSL_EVP_init(void) break; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL CIPHER"); XMEMCPY(dst, src, (size_t)len); ret = (int)len; @@ -8805,7 +8813,7 @@ int wolfSSL_EVP_PKEY_set1_RSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_RSA *key) clearEVPPkeyKeys(pkey); pkey->rsa = key; pkey->ownRsa = 1; /* pkey does not own RSA but needs to call free on it */ - pkey->type = EVP_PKEY_RSA; + pkey->type = WC_EVP_PKEY_RSA; pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; if (key->inSet == 0) { if (SetRsaInternal(key) != WOLFSSL_SUCCESS) { @@ -8851,7 +8859,7 @@ int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) clearEVPPkeyKeys(pkey); pkey->dsa = key; pkey->ownDsa = 0; /* pkey does not own DSA */ - pkey->type = EVP_PKEY_DSA; + pkey->type = WC_EVP_PKEY_DSA; if (key->inSet == 0) { if (SetDsaInternal(key) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("SetDsaInternal failed"); @@ -8861,7 +8869,7 @@ int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) dsa = (DsaKey*)key->internal; /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ - derMax = 4 * wolfSSL_BN_num_bytes(key->g) + AES_BLOCK_SIZE; + derMax = 4 * wolfSSL_BN_num_bytes(key->g) + WC_AES_BLOCK_SIZE; derBuf = (byte*)XMALLOC((size_t)derMax, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -8929,13 +8937,13 @@ WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) return NULL; } - if (key->type == EVP_PKEY_DSA) { + if (key->type == WC_EVP_PKEY_DSA) { if (wolfSSL_DSA_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { + key->pkey_sz) != WOLFSSL_SUCCESS) { /* now try public key */ if (wolfSSL_DSA_LoadDer_ex(local, (const unsigned char*)key->pkey.ptr, key->pkey_sz, - WOLFSSL_DSA_LOAD_PUBLIC) != SSL_SUCCESS) { + WOLFSSL_DSA_LOAD_PUBLIC) != WOLFSSL_SUCCESS) { wolfSSL_DSA_free(local); local = NULL; } @@ -8954,7 +8962,7 @@ WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) WOLFSSL_EC_KEY *wolfSSL_EVP_PKEY_get0_EC_KEY(WOLFSSL_EVP_PKEY *pkey) { WOLFSSL_EC_KEY *eckey = NULL; - if (pkey && pkey->type == EVP_PKEY_EC) { + if (pkey && pkey->type == WC_EVP_PKEY_EC) { #ifdef HAVE_ECC eckey = pkey->ecc; #endif @@ -8967,10 +8975,10 @@ WOLFSSL_EC_KEY* wolfSSL_EVP_PKEY_get1_EC_KEY(WOLFSSL_EVP_PKEY* key) WOLFSSL_EC_KEY* local = NULL; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_EC_KEY"); - if (key == NULL || key->type != EVP_PKEY_EC) { + if (key == NULL || key->type != WC_EVP_PKEY_EC) { return NULL; } - if (key->type == EVP_PKEY_EC) { + if (key->type == WC_EVP_PKEY_EC) { if (key->ecc != NULL) { if (wolfSSL_EC_KEY_up_ref(key->ecc) != WOLFSSL_SUCCESS) { return NULL; @@ -9035,7 +9043,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) pkey->dh = key; pkey->ownDh = 1; /* pkey does not own DH but needs to call free on it */ - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; if (key->inSet == 0) { if (SetDhInternal(key) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("SetDhInternal failed"); @@ -9109,7 +9117,7 @@ WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) return NULL; } - if (key->type == EVP_PKEY_DH) { + if (key->type == WC_EVP_PKEY_DH) { /* if key->dh already exists copy instead of re-importing from DER */ if (key->dh != NULL) { if (wolfSSL_DH_up_ref(key->dh) != WOLFSSL_SUCCESS) { @@ -9126,7 +9134,7 @@ WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) return NULL; } if (wolfSSL_DH_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { + key->pkey_sz) != WOLFSSL_SUCCESS) { wolfSSL_DH_free(local); WOLFSSL_MSG("Error wolfSSL_DH_LoadDer"); local = NULL; @@ -9156,22 +9164,22 @@ int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) /* pkey and key checked if NULL in subsequent assign functions */ switch(type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: ret = wolfSSL_EVP_PKEY_assign_RSA(pkey, (WOLFSSL_RSA*)key); break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: ret = wolfSSL_EVP_PKEY_assign_DSA(pkey, (WOLFSSL_DSA*)key); break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: ret = wolfSSL_EVP_PKEY_assign_EC_KEY(pkey, (WOLFSSL_EC_KEY*)key); break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: ret = wolfSSL_EVP_PKEY_assign_DH(pkey, (WOLFSSL_DH*)key); break; #endif @@ -9186,7 +9194,7 @@ int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) #if defined(HAVE_ECC) /* try and populate public pkey_sz and pkey.ptr */ -static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) +static int ECC_populate_EVP_PKEY(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) { int derSz = 0; byte* derBuf = NULL; @@ -9295,7 +9303,7 @@ int wolfSSL_EVP_PKEY_set1_EC_KEY(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_EC_KEY *key) } pkey->ecc = key; pkey->ownEcc = 1; /* pkey needs to call free on key */ - pkey->type = EVP_PKEY_EC; + pkey->type = WC_EVP_PKEY_EC; return ECC_populate_EVP_PKEY(pkey, key); #else (void)pkey; @@ -9310,7 +9318,7 @@ void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) if (ctx) { switch (ctx->cipherType) { - case ARC4_TYPE: + case WC_ARC4_TYPE: WOLFSSL_MSG("returning arc4 state"); return (void*)&ctx->cipher.arc4.x; @@ -9322,7 +9330,7 @@ void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) return NULL; } -int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) +int wolfSSL_EVP_PKEY_assign_EC_KEY(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) { int ret; @@ -9334,7 +9342,7 @@ int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) if (ret == WOLFSSL_SUCCESS) { /* take ownership of key if can be used */ clearEVPPkeyKeys(pkey); /* clear out any previous keys */ - pkey->type = EVP_PKEY_EC; + pkey->type = WC_EVP_PKEY_EC; pkey->ecc = key; pkey->ownEcc = 1; } @@ -9360,22 +9368,22 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) if (type != NULL) { if (XSTRCMP(type, "MD5") == 0) { - ret = NID_md5WithRSAEncryption; + ret = WC_NID_md5WithRSAEncryption; } else if (XSTRCMP(type, "SHA1") == 0) { - ret = NID_sha1WithRSAEncryption; + ret = WC_NID_sha1WithRSAEncryption; } else if (XSTRCMP(type, "SHA224") == 0) { - ret = NID_sha224WithRSAEncryption; + ret = WC_NID_sha224WithRSAEncryption; } else if (XSTRCMP(type, "SHA256") == 0) { - ret = NID_sha256WithRSAEncryption; + ret = WC_NID_sha256WithRSAEncryption; } else if (XSTRCMP(type, "SHA384") == 0) { - ret = NID_sha384WithRSAEncryption; + ret = WC_NID_sha384WithRSAEncryption; } else if (XSTRCMP(type, "SHA512") == 0) { - ret = NID_sha512WithRSAEncryption; + ret = WC_NID_sha512WithRSAEncryption; } } else { @@ -9401,18 +9409,18 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) switch (ctx->cipherType) { #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9420,9 +9428,9 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : + case WC_AES_128_CCM_TYPE : + case WC_AES_192_CCM_TYPE : + case WC_AES_256_CCM_TYPE : WOLFSSL_MSG("AES CCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9431,62 +9439,62 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) #endif #endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); return DES_BLOCK_SIZE; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES EDE3 CBC"); return DES_BLOCK_SIZE; #endif #ifndef NO_RC4 - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); return 0; #endif #ifdef WOLFSSL_AES_CFB #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: WOLFSSL_MSG("AES CFB1"); - return AES_BLOCK_SIZE; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + return WC_AES_BLOCK_SIZE; + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: WOLFSSL_MSG("AES CFB8"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: WOLFSSL_MSG("AES CFB128"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_CFB */ #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: WOLFSSL_MSG("AES OFB"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_OFB */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: WOLFSSL_MSG("AES XTS"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9494,27 +9502,27 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: WOLFSSL_MSG("CHACHA20 POLY1305"); return CHACHA20_POLY1305_AEAD_IV_SIZE; #endif /* HAVE_CHACHA HAVE_POLY1305 */ #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: WOLFSSL_MSG("CHACHA20"); return WOLFSSL_EVP_CHACHA_IV_BYTES; #endif /* HAVE_CHACHA */ #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE : + case WC_SM4_CBC_TYPE : WOLFSSL_MSG("SM4 CBC"); return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE : + case WC_SM4_CTR_TYPE : WOLFSSL_MSG("SM4 CTR"); return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE : + case WC_SM4_GCM_TYPE : WOLFSSL_MSG("SM4 GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9522,7 +9530,7 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE : + case WC_SM4_CCM_TYPE : WOLFSSL_MSG("SM4 CCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9530,7 +9538,7 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return CCM_NONCE_MIN_SZ; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL"); return 0; @@ -9550,15 +9558,15 @@ int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_192 if (XSTRCMP(name, EVP_AES_192_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ #if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ @@ -9595,26 +9603,26 @@ int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_192 if (XSTRCMP(name, EVP_AES_192_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_XTS) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_XTS) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_256 */ #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ @@ -9674,7 +9682,7 @@ int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) if (ctx) { switch (ctx->cipherType) { - case ARC4_TYPE: + case WC_ARC4_TYPE: WOLFSSL_MSG("returning arc4 state size"); return sizeof(Arc4); @@ -9688,27 +9696,27 @@ int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) } -/* return of pkey->type which will be EVP_PKEY_RSA for example. +/* return of pkey->type which will be WC_EVP_PKEY_RSA for example. * * type type of EVP_PKEY * - * returns type or if type is not found then NID_undef + * returns type or if type is not found then WC_NID_undef */ int wolfSSL_EVP_PKEY_type(int type) { WOLFSSL_MSG("wolfSSL_EVP_PKEY_type"); switch (type) { - case EVP_PKEY_RSA: - return EVP_PKEY_RSA; - case EVP_PKEY_DSA: - return EVP_PKEY_DSA; - case EVP_PKEY_EC: - return EVP_PKEY_EC; - case EVP_PKEY_DH: - return EVP_PKEY_DH; + case WC_EVP_PKEY_RSA: + return WC_EVP_PKEY_RSA; + case WC_EVP_PKEY_DSA: + return WC_EVP_PKEY_DSA; + case WC_EVP_PKEY_EC: + return WC_EVP_PKEY_EC; + case WC_EVP_PKEY_DH: + return WC_EVP_PKEY_DH; default: - return NID_undef; + return WC_NID_undef; } } @@ -9724,7 +9732,7 @@ int wolfSSL_EVP_PKEY_id(const WOLFSSL_EVP_PKEY *pkey) int wolfSSL_EVP_PKEY_base_id(const WOLFSSL_EVP_PKEY *pkey) { if (pkey == NULL) - return NID_undef; + return WC_NID_undef; return wolfSSL_EVP_PKEY_type(pkey->type); } @@ -9738,17 +9746,17 @@ int wolfSSL_EVP_PKEY_get_default_digest_nid(WOLFSSL_EVP_PKEY *pkey, int *pnid) } switch (pkey->type) { - case EVP_PKEY_HMAC: + case WC_EVP_PKEY_HMAC: #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: #endif #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: #endif - *pnid = NID_sha256; + *pnid = WC_NID_sha256; return WOLFSSL_SUCCESS; default: return WOLFSSL_FAILURE; @@ -9800,13 +9808,13 @@ int wolfSSL_EVP_PKEY_up_ref(WOLFSSL_EVP_PKEY* pkey) } #ifndef NO_RSA -int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) +int wolfSSL_EVP_PKEY_assign_RSA(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_RSA* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_RSA; + pkey->type = WC_EVP_PKEY_RSA; pkey->rsa = key; pkey->ownRsa = 1; @@ -9837,13 +9845,13 @@ int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) #endif /* !NO_RSA */ #ifndef NO_DSA -int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) +int wolfSSL_EVP_PKEY_assign_DSA(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_DSA* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DSA; + pkey->type = WC_EVP_PKEY_DSA; pkey->dsa = key; pkey->ownDsa = 1; @@ -9852,13 +9860,13 @@ int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) #endif /* !NO_DSA */ #ifndef NO_DH -int wolfSSL_EVP_PKEY_assign_DH(EVP_PKEY* pkey, WOLFSSL_DH* key) +int wolfSSL_EVP_PKEY_assign_DH(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_DH* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; pkey->dh = key; pkey->ownDh = 1; @@ -9974,7 +9982,7 @@ const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) for (ent = md_tbl; ent->name != NULL; ent++) if(XSTRCMP(name, ent->name) == 0) { - return (EVP_MD *)ent->name; + return (WOLFSSL_EVP_MD *)ent->name; } return NULL; } @@ -9983,7 +9991,7 @@ const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) * * type - pointer to WOLFSSL_EVP_MD for which to return NID value * - * Returns NID on success, or NID_undef if none exists. + * Returns NID on success, or WC_NID_undef if none exists. */ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) { @@ -9992,7 +10000,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("MD type arg is NULL"); - return NID_undef; + return WC_NID_undef; } for( ent = md_tbl; ent->name != NULL; ent++){ @@ -10000,7 +10008,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return ent->nid; } } - return NID_undef; + return WC_NID_undef; } #ifndef NO_MD4 @@ -10009,7 +10017,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) { WOLFSSL_ENTER("EVP_md4"); - return EVP_get_digestbyname("MD4"); + return wolfSSL_EVP_get_digestbyname("MD4"); } #endif /* !NO_MD4 */ @@ -10020,7 +10028,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) { WOLFSSL_ENTER("EVP_md5"); - return EVP_get_digestbyname("MD5"); + return wolfSSL_EVP_get_digestbyname("MD5"); } #endif /* !NO_MD5 */ @@ -10033,7 +10041,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) { WOLFSSL_ENTER("EVP_blake2b512"); - return EVP_get_digestbyname("BLAKE2b512"); + return wolfSSL_EVP_get_digestbyname("BLAKE2b512"); } #endif @@ -10046,7 +10054,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2s256(void) { WOLFSSL_ENTER("EVP_blake2s256"); - return EVP_get_digestbyname("BLAKE2s256"); + return wolfSSL_EVP_get_digestbyname("BLAKE2s256"); } #endif @@ -10072,7 +10080,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) { WOLFSSL_ENTER("EVP_sha1"); - return EVP_get_digestbyname("SHA1"); + return wolfSSL_EVP_get_digestbyname("SHA1"); } #endif /* NO_SHA */ @@ -10081,7 +10089,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) { WOLFSSL_ENTER("EVP_sha224"); - return EVP_get_digestbyname("SHA224"); + return wolfSSL_EVP_get_digestbyname("SHA224"); } #endif /* WOLFSSL_SHA224 */ @@ -10090,7 +10098,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) { WOLFSSL_ENTER("EVP_sha256"); - return EVP_get_digestbyname("SHA256"); + return wolfSSL_EVP_get_digestbyname("SHA256"); } #ifdef WOLFSSL_SHA384 @@ -10098,7 +10106,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) { WOLFSSL_ENTER("EVP_sha384"); - return EVP_get_digestbyname("SHA384"); + return wolfSSL_EVP_get_digestbyname("SHA384"); } #endif /* WOLFSSL_SHA384 */ @@ -10108,7 +10116,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) { WOLFSSL_ENTER("EVP_sha512"); - return EVP_get_digestbyname("SHA512"); + return wolfSSL_EVP_get_digestbyname("SHA512"); } #ifndef WOLFSSL_NOSHA512_224 @@ -10116,7 +10124,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) { WOLFSSL_ENTER("EVP_sha512_224"); - return EVP_get_digestbyname("SHA512_224"); + return wolfSSL_EVP_get_digestbyname("SHA512_224"); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10125,7 +10133,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) { WOLFSSL_ENTER("EVP_sha512_256"); - return EVP_get_digestbyname("SHA512_256"); + return wolfSSL_EVP_get_digestbyname("SHA512_256"); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10137,7 +10145,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) { WOLFSSL_ENTER("EVP_sha3_224"); - return EVP_get_digestbyname("SHA3_224"); + return wolfSSL_EVP_get_digestbyname("SHA3_224"); } #endif /* WOLFSSL_NOSHA3_224 */ @@ -10146,7 +10154,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) { WOLFSSL_ENTER("EVP_sha3_256"); - return EVP_get_digestbyname("SHA3_256"); + return wolfSSL_EVP_get_digestbyname("SHA3_256"); } #endif /* WOLFSSL_NOSHA3_256 */ @@ -10154,7 +10162,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) { WOLFSSL_ENTER("EVP_sha3_384"); - return EVP_get_digestbyname("SHA3_384"); + return wolfSSL_EVP_get_digestbyname("SHA3_384"); } #endif /* WOLFSSL_NOSHA3_384 */ @@ -10162,7 +10170,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) { WOLFSSL_ENTER("EVP_sha3_512"); - return EVP_get_digestbyname("SHA3_512"); + return wolfSSL_EVP_get_digestbyname("SHA3_512"); } #endif /* WOLFSSL_NOSHA3_512 */ @@ -10170,7 +10178,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_shake128(void) { WOLFSSL_ENTER("EVP_shake128"); - return EVP_get_digestbyname("SHAKE128"); + return wolfSSL_EVP_get_digestbyname("SHAKE128"); } #endif /* WOLFSSL_SHAKE128 */ @@ -10178,7 +10186,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_shake256(void) { WOLFSSL_ENTER("EVP_shake256"); - return EVP_get_digestbyname("SHAKE256"); + return wolfSSL_EVP_get_digestbyname("SHAKE256"); } #endif /* WOLFSSL_SHAKE256 */ @@ -10188,7 +10196,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sm3(void) { WOLFSSL_ENTER("EVP_sm3"); - return EVP_get_digestbyname("SM3"); + return wolfSSL_EVP_get_digestbyname("SM3"); } #endif /* WOLFSSL_SM3 */ @@ -10223,7 +10231,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const struct s_ent *ent; if (ctx->isHMAC) { - return NID_hmac; + return WC_NID_hmac; } for(ent = md_tbl; ent->name != NULL; ent++) { @@ -10313,7 +10321,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (nm->alias) md->fn(NULL, nm->name, nm->data, md->arg); else - md->fn((const EVP_MD *)nm->data, nm->name, NULL, md->arg); + md->fn((const WOLFSSL_EVP_MD *)nm->data, nm->name, NULL, md->arg); } /* call md_do_all function to do all md algorithm via a callback function @@ -10614,48 +10622,48 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) WOLFSSL_ENTER("EVP_DigestUpdate"); - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - wolfSSL_MD4_Update((MD4_CTX*)&ctx->hash, data, + wolfSSL_MD4_Update((WOLFSSL_MD4_CTX*)&ctx->hash, data, (unsigned long)sz); ret = WOLFSSL_SUCCESS; #endif break; case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data, + ret = wolfSSL_MD5_Update((WOLFSSL_MD5_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA_Update((WOLFSSL_SHA_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA224_Update((WOLFSSL_SHA224_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA256_Update((WOLFSSL_SHA256_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* !NO_SHA256 */ break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA384_Update((WOLFSSL_SHA384_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* WOLFSSL_SHA512 */ break; @@ -10664,7 +10672,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_224_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; @@ -10674,7 +10682,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_256_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* WOLFSSL_SHA512 */ break; @@ -10682,25 +10690,25 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_224_Update((WOLFSSL_SHA3_224_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_256_Update((WOLFSSL_SHA3_256_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_384_Update((WOLFSSL_SHA3_384_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_512_Update((WOLFSSL_SHA3_512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; @@ -10741,48 +10749,48 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestFinal"); - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - wolfSSL_MD4_Final(md, (MD4_CTX*)&ctx->hash); - if (s) *s = MD4_DIGEST_SIZE; + wolfSSL_MD4_Final(md, (WOLFSSL_MD4_CTX*)&ctx->hash); + if (s) *s = WC_MD4_DIGEST_SIZE; ret = WOLFSSL_SUCCESS; #endif break; case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash); + ret = wolfSSL_MD5_Final(md, (WOLFSSL_MD5_CTX*)&ctx->hash); if (s) *s = WC_MD5_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash); + ret = wolfSSL_SHA_Final(md, (WOLFSSL_SHA_CTX*)&ctx->hash); if (s) *s = WC_SHA_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash); + ret = wolfSSL_SHA224_Final(md, (WOLFSSL_SHA224_CTX*)&ctx->hash); if (s) *s = WC_SHA224_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash); + ret = wolfSSL_SHA256_Final(md, (WOLFSSL_SHA256_CTX*)&ctx->hash); if (s) *s = WC_SHA256_DIGEST_SIZE; #endif /* !NO_SHA256 */ break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash); + ret = wolfSSL_SHA384_Final(md, (WOLFSSL_SHA384_CTX*)&ctx->hash); if (s) *s = WC_SHA384_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_DIGEST_SIZE; #endif /* WOLFSSL_SHA512 */ break; @@ -10790,7 +10798,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_224_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_224_DIGEST_SIZE; #endif break; @@ -10799,32 +10807,32 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_256_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_256_DIGEST_SIZE; #endif break; #endif /* !WOLFSSL_NOSHA512_256 */ case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_224_Final(md, (WOLFSSL_SHA3_224_CTX*)&ctx->hash); if (s) *s = WC_SHA3_224_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_256_Final(md, (WOLFSSL_SHA3_256_CTX*)&ctx->hash); if (s) *s = WC_SHA3_256_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_384_Final(md, (WOLFSSL_SHA3_384_CTX*)&ctx->hash); if (s) *s = WC_SHA3_384_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_512_Final(md, (WOLFSSL_SHA3_512_CTX*)&ctx->hash); if (s) *s = WC_SHA3_512_DIGEST_SIZE; #endif break; @@ -10863,7 +10871,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) unsigned int* s) { WOLFSSL_ENTER("EVP_DigestFinal_ex"); - return EVP_DigestFinal(ctx, md, s); + return wolfSSL_EVP_DigestFinal(ctx, md, s); } void wolfSSL_EVP_cleanup(void) @@ -10877,31 +10885,31 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) switch(id) { #ifndef NO_MD5 - case NID_md5: + case WC_NID_md5: return wolfSSL_EVP_md5(); #endif #ifndef NO_SHA - case NID_sha1: + case WC_NID_sha1: return wolfSSL_EVP_sha1(); #endif #ifdef WOLFSSL_SHA224 - case NID_sha224: + case WC_NID_sha224: return wolfSSL_EVP_sha224(); #endif #ifndef NO_SHA256 - case NID_sha256: + case WC_NID_sha256: return wolfSSL_EVP_sha256(); #endif #ifdef WOLFSSL_SHA384 - case NID_sha384: + case WC_NID_sha384: return wolfSSL_EVP_sha384(); #endif #ifdef WOLFSSL_SHA512 - case NID_sha512: + case WC_NID_sha512: return wolfSSL_EVP_sha512(); #endif #ifdef WOLFSSL_SM3 - case NID_sm3: + case WC_NID_sm3: return wolfSSL_EVP_sm3(); #endif default: @@ -10931,7 +10939,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) #endif #ifndef NO_MD4 if (XSTRCMP(type, "MD4") == 0) { - return MD4_BLOCK_SIZE; + return WC_MD4_BLOCK_SIZE; } else #endif #ifndef NO_MD5 @@ -11006,7 +11014,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) #endif #ifndef NO_MD4 if (XSTRCMP(type, "MD4") == 0) { - return MD4_DIGEST_SIZE; + return WC_MD4_DIGEST_SIZE; } else #endif #ifndef NO_MD5 @@ -11147,7 +11155,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) switch(key->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (key->rsa != NULL && key->ownRsa == 1) { wolfSSL_RSA_free(key->rsa); key->rsa = NULL; @@ -11156,7 +11164,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* NO_RSA */ #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (key->ecc != NULL && key->ownEcc == 1) { wolfSSL_EC_KEY_free(key->ecc); key->ecc = NULL; @@ -11165,7 +11173,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* HAVE_ECC && OPENSSL_EXTRA */ #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (key->dsa != NULL && key->ownDsa == 1) { wolfSSL_DSA_free(key->dsa); key->dsa = NULL; @@ -11175,7 +11183,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #if !defined(NO_DH) && (defined(WOLFSSL_QT) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: if (key->dh != NULL && key->ownDh == 1) { wolfSSL_DH_free(key->dh); key->dh = NULL; @@ -11184,7 +11192,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* ! NO_DH ... */ #ifdef HAVE_HKDF - case EVP_PKEY_HKDF: + case WC_EVP_PKEY_HKDF: XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); key->hkdfSalt = NULL; XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); @@ -11199,7 +11207,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_AES_DIRECT) - case EVP_PKEY_CMAC: + case WC_EVP_PKEY_CMAC: if (key->cmacCtx != NULL) { wolfSSL_CMAC_CTX_free(key->cmacCtx); key->cmacCtx = NULL; @@ -11230,8 +11238,8 @@ static int Indent(WOLFSSL_BIO* out, int indents) if (out == NULL) { return 0; } - if (indents > EVP_PKEY_PRINT_INDENT_MAX) { - indents = EVP_PKEY_PRINT_INDENT_MAX; + if (indents > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indents = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } for (i = 0; i < indents; i++) { if (wolfSSL_BIO_write(out, &space, 1) < 0) { @@ -11259,7 +11267,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, #ifdef WOLFSSL_SMALL_STACK byte* buff = NULL; #else - byte buff[EVP_PKEY_PRINT_LINE_WIDTH_MAX] = { 0 }; + byte buff[WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX] = { 0 }; #endif /* WOLFSSL_SMALL_STACK */ int ret = WOLFSSL_SUCCESS; word32 in = 0; @@ -11276,14 +11284,14 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } data = input; #ifdef WOLFSSL_SMALL_STACK - buff = (byte*)XMALLOC(EVP_PKEY_PRINT_LINE_WIDTH_MAX, NULL, + buff = (byte*)XMALLOC(WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (!buff) { return WOLFSSL_FAILURE; @@ -11294,9 +11302,9 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, idx = 0; for (in = 0; in < (word32)inlen && ret == WOLFSSL_SUCCESS; in += - EVP_PKEY_PRINT_DIGITS_PER_LINE ) { + WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE ) { Indent(out, indent); - for (i = 0; (i < EVP_PKEY_PRINT_DIGITS_PER_LINE) && + for (i = 0; (i < WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE) && (in + i < (word32)inlen); i++) { if (ret == WOLFSSL_SUCCESS) { @@ -11325,7 +11333,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, ret = wolfSSL_BIO_write(out, "\n", 1) > 0; } if (ret == WOLFSSL_SUCCESS) { - XMEMSET(buff, 0, EVP_PKEY_PRINT_LINE_WIDTH_MAX); + XMEMSET(buff, 0, WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX); idx = 0; } } @@ -11347,7 +11355,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); @@ -11383,8 +11391,8 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -11501,7 +11509,7 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte* pub = NULL; word32 pubSz = 0; @@ -11563,8 +11571,8 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - else if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + else if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } if (res == WOLFSSL_SUCCESS) { @@ -11697,7 +11705,7 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; @@ -11733,8 +11741,8 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -11916,7 +11924,7 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; @@ -11957,8 +11965,8 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -12147,7 +12155,7 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Can handle RSA, ECC, DSA and DH public keys. */ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, - const WOLFSSL_EVP_PKEY* pkey, int indent, ASN1_PCTX* pctx) + const WOLFSSL_EVP_PKEY* pkey, int indent, WOLFSSL_ASN1_PCTX* pctx) { int res; #if !defined(NO_RSA) || defined(HAVE_ECC) || !defined(NO_DSA) || \ @@ -12165,13 +12173,13 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } #endif switch (pkey->type) { - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #if !defined(NO_RSA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12187,7 +12195,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: #if defined(HAVE_ECC) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12203,7 +12211,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: #if !defined(NO_DSA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12219,7 +12227,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: #if defined(WOLFSSL_DH_EXTRA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; diff --git a/src/wolfcrypt/src/ext_kyber.c b/src/wolfcrypt/src/ext_kyber.c index 0c2cb2b..44ec893 100644 --- a/src/wolfcrypt/src/ext_kyber.c +++ b/src/wolfcrypt/src/ext_kyber.c @@ -43,9 +43,16 @@ static const char* OQS_ID2name(int id) { switch (id) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: return OQS_KEM_alg_ml_kem_512; + case WC_ML_KEM_768: return OQS_KEM_alg_ml_kem_768; + case WC_ML_KEM_1024: return OQS_KEM_alg_ml_kem_1024; + #endif + #ifdef WOLFSSL_KYBER_ORIGINAL case KYBER_LEVEL1: return OQS_KEM_alg_kyber_512; case KYBER_LEVEL3: return OQS_KEM_alg_kyber_768; case KYBER_LEVEL5: return OQS_KEM_alg_kyber_1024; + #endif default: break; } return NULL; @@ -83,11 +90,20 @@ int wc_KyberKey_Init(int type, KyberKey* key, void* heap, int devId) if (ret == 0) { /* Validate type. */ switch (type) { +#ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + #ifdef HAVE_LIBOQS + case WC_ML_KEM_768: + case WC_ML_KEM_1024: + #endif /* HAVE_LIBOQS */ +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL case KYBER_LEVEL1: -#ifdef HAVE_LIBOQS + #ifdef HAVE_LIBOQS case KYBER_LEVEL3: case KYBER_LEVEL5: -#endif /* HAVE_LIBOQS */ + #endif /* HAVE_LIBOQS */ +#endif break; default: /* No other values supported. */ @@ -152,6 +168,18 @@ int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) /* NOTE: SHAKE and AES variants have the same length private key. */ if (ret == 0) { switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_secret_key; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_secret_key; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_secret_key; + break; + #endif + #ifdef WOLFSSL_KYBER_ORIGINAL case KYBER_LEVEL1: *len = OQS_KEM_kyber_512_length_secret_key; break; @@ -161,6 +189,7 @@ int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) case KYBER_LEVEL5: *len = OQS_KEM_kyber_1024_length_secret_key; break; + #endif default: /* No other values supported. */ ret = BAD_FUNC_ARG; @@ -194,6 +223,18 @@ int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) /* NOTE: SHAKE and AES variants have the same length public key. */ if (ret == 0) { switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_public_key; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_public_key; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_public_key; + break; + #endif + #ifdef WOLFSSL_KYBER_ORIGINAL case KYBER_LEVEL1: *len = OQS_KEM_kyber_512_length_public_key; break; @@ -203,6 +244,7 @@ int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) case KYBER_LEVEL5: *len = OQS_KEM_kyber_1024_length_public_key; break; + #endif default: /* No other values supported. */ ret = BAD_FUNC_ARG; @@ -236,6 +278,18 @@ int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) /* NOTE: SHAKE and AES variants have the same length ciphertext. */ if (ret == 0) { switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_ciphertext; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_ciphertext; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_ciphertext; + break; + #endif + #ifdef WOLFSSL_KYBER_ORIGINAL case KYBER_LEVEL1: *len = OQS_KEM_kyber_512_length_ciphertext; break; @@ -245,6 +299,7 @@ int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) case KYBER_LEVEL5: *len = OQS_KEM_kyber_1024_length_ciphertext; break; + #endif default: /* No other values supported. */ ret = BAD_FUNC_ARG; diff --git a/src/wolfcrypt/src/fe_448.c b/src/wolfcrypt/src/fe_448.c index ede162a..bbf31f6 100644 --- a/src/wolfcrypt/src/fe_448.c +++ b/src/wolfcrypt/src/fe_448.c @@ -1437,56 +1437,56 @@ void fe448_to_bytes(unsigned char* b, const sword32* a) b[ 0] = (byte)(in0 >> 0); b[ 1] = (byte)(in0 >> 8); b[ 2] = (byte)(in0 >> 16); - b[ 3] = (byte)((in0 >> 24) + ((in1 >> 0) << 4)); + b[ 3] = (byte)(in0 >> 24) + (byte)((in1 >> 0) << 4); b[ 4] = (byte)(in1 >> 4); b[ 5] = (byte)(in1 >> 12); b[ 6] = (byte)(in1 >> 20); b[ 7] = (byte)(in2 >> 0); b[ 8] = (byte)(in2 >> 8); b[ 9] = (byte)(in2 >> 16); - b[10] = (byte)((in2 >> 24) + ((in3 >> 0) << 4)); + b[10] = (byte)(in2 >> 24) + (byte)((in3 >> 0) << 4); b[11] = (byte)(in3 >> 4); b[12] = (byte)(in3 >> 12); b[13] = (byte)(in3 >> 20); b[14] = (byte)(in4 >> 0); b[15] = (byte)(in4 >> 8); b[16] = (byte)(in4 >> 16); - b[17] = (byte)((in4 >> 24) + ((in5 >> 0) << 4)); + b[17] = (byte)(in4 >> 24) + (byte)((in5 >> 0) << 4); b[18] = (byte)(in5 >> 4); b[19] = (byte)(in5 >> 12); b[20] = (byte)(in5 >> 20); b[21] = (byte)(in6 >> 0); b[22] = (byte)(in6 >> 8); b[23] = (byte)(in6 >> 16); - b[24] = (byte)((in6 >> 24) + ((in7 >> 0) << 4)); + b[24] = (byte)(in6 >> 24) + (byte)((in7 >> 0) << 4); b[25] = (byte)(in7 >> 4); b[26] = (byte)(in7 >> 12); b[27] = (byte)(in7 >> 20); b[28] = (byte)(in8 >> 0); b[29] = (byte)(in8 >> 8); b[30] = (byte)(in8 >> 16); - b[31] = (byte)((in8 >> 24) + ((in9 >> 0) << 4)); + b[31] = (byte)(in8 >> 24) + (byte)((in9 >> 0) << 4); b[32] = (byte)(in9 >> 4); b[33] = (byte)(in9 >> 12); b[34] = (byte)(in9 >> 20); b[35] = (byte)(in10 >> 0); b[36] = (byte)(in10 >> 8); b[37] = (byte)(in10 >> 16); - b[38] = (byte)((in10 >> 24) + ((in11 >> 0) << 4)); + b[38] = (byte)(in10 >> 24) + (byte)((in11 >> 0) << 4); b[39] = (byte)(in11 >> 4); b[40] = (byte)(in11 >> 12); b[41] = (byte)(in11 >> 20); b[42] = (byte)(in12 >> 0); b[43] = (byte)(in12 >> 8); b[44] = (byte)(in12 >> 16); - b[45] = (byte)((in12 >> 24) + ((in13 >> 0) << 4)); + b[45] = (byte)(in12 >> 24) + (byte)((in13 >> 0) << 4); b[46] = (byte)(in13 >> 4); b[47] = (byte)(in13 >> 12); b[48] = (byte)(in13 >> 20); b[49] = (byte)(in14 >> 0); b[50] = (byte)(in14 >> 8); b[51] = (byte)(in14 >> 16); - b[52] = (byte)((in14 >> 24) + ((in15 >> 0) << 4)); + b[52] = (byte)(in14 >> 24) + (byte)((in15 >> 0) << 4); b[53] = (byte)(in15 >> 4); b[54] = (byte)(in15 >> 12); b[55] = (byte)(in15 >> 20); @@ -1770,6 +1770,8 @@ void fe448_mul39081(sword32* r, const sword32* a) static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b) { sword64 t; + sword64 o; + sword64 t15; sword64 t0 = (sword64)a[ 0] * b[ 0]; sword64 t1 = (sword64)a[ 0] * b[ 1]; sword64 t101 = (sword64)a[ 1] * b[ 0]; @@ -1834,7 +1836,6 @@ static WC_INLINE void fe448_mul_8(sword32* r, const sword32* a, const sword32* b sword64 t13 = (sword64)a[ 6] * b[ 7]; sword64 t113 = (sword64)a[ 7] * b[ 6]; sword64 t14 = (sword64)a[ 7] * b[ 7]; - sword64 o, t15; t1 += t101; t2 += t102; t2 += t202; t3 += t103; t3 += t203; t3 += t303; diff --git a/src/wolfcrypt/src/ge_448.c b/src/wolfcrypt/src/ge_448.c index 415928f..81f9c57 100644 --- a/src/wolfcrypt/src/ge_448.c +++ b/src/wolfcrypt/src/ge_448.c @@ -77,6 +77,14 @@ static const ge448_p2 ed448_base = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; +static const word8 ed448_order[56] = { + 0xf3, 0x44, 0x58, 0xab, 0x92, 0xc2, 0x78, 0x23, 0x55, 0x8f, 0xc5, 0x8d, + 0x72, 0xc2, 0x6c, 0x21, 0x90, 0x36, 0xd6, 0xae, 0x49, 0xdb, 0x4e, 0xc4, + 0xe9, 0x23, 0xca, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, +}; + /* Part of order of ed448 that needs tp be multiplied when reducing */ static const word8 ed448_order_mul[56] = { 0x0d, 0xbb, 0xa7, 0x54, 0x6d, 0x3d, 0x87, 0xdc, 0xaa, 0x70, 0x3a, 0x72, @@ -87,6 +95,8 @@ static const word8 ed448_order_mul[56] = { /* Reduce scalar mod the order of the curve. * Scalar Will be 114 bytes. * + * Only performs a weak reduce. + * * b [in] Scalar to reduce. */ void sc448_reduce(byte* b) @@ -149,6 +159,7 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) int i, j; word32 t[112]; word8 o; + sword16 u; /* a * b + d */ for (i = 0; i < 56; i++) @@ -200,6 +211,16 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) } r[i] = t[i] & 0xff; r[i+1] = 0; + /* Reduce to mod order. */ + u = 0; + for (i = 0; i < 56; i++) { + u += r[i] - ed448_order[i]; u >>= 8; + } + o = 0 - (u >= 0); + u = 0; + for (i = 0; i < 56; i++) { + u += r[i] - (ed448_order[i] & o); r[i] = u & 0xff; u >>= 8; + } } /* Double the point on the Twisted Edwards curve. r = 2.p @@ -431,6 +452,8 @@ int ge448_from_bytes_negate_vartime(ge448_p2 *r, const byte *b) /* Reduce scalar mod the order of the curve. * Scalar Will be 114 bytes. * + * Only performs a weak reduce. + * * b [in] Scalar to reduce. */ void sc448_reduce(byte* b) @@ -441,120 +464,120 @@ void sc448_reduce(byte* b) word64 o; /* Load from bytes */ - t[ 0] = ((sword64) (b[ 0]) << 0) - | ((sword64) (b[ 1]) << 8) - | ((sword64) (b[ 2]) << 16) - | ((sword64) (b[ 3]) << 24) - | ((sword64) (b[ 4]) << 32) - | ((sword64) (b[ 5]) << 40) - | ((sword64) (b[ 6]) << 48); - t[ 1] = ((sword64) (b[ 7]) << 0) - | ((sword64) (b[ 8]) << 8) - | ((sword64) (b[ 9]) << 16) - | ((sword64) (b[10]) << 24) - | ((sword64) (b[11]) << 32) - | ((sword64) (b[12]) << 40) - | ((sword64) (b[13]) << 48); - t[ 2] = ((sword64) (b[14]) << 0) - | ((sword64) (b[15]) << 8) - | ((sword64) (b[16]) << 16) - | ((sword64) (b[17]) << 24) - | ((sword64) (b[18]) << 32) - | ((sword64) (b[19]) << 40) - | ((sword64) (b[20]) << 48); - t[ 3] = ((sword64) (b[21]) << 0) - | ((sword64) (b[22]) << 8) - | ((sword64) (b[23]) << 16) - | ((sword64) (b[24]) << 24) - | ((sword64) (b[25]) << 32) - | ((sword64) (b[26]) << 40) - | ((sword64) (b[27]) << 48); - t[ 4] = ((sword64) (b[28]) << 0) - | ((sword64) (b[29]) << 8) - | ((sword64) (b[30]) << 16) - | ((sword64) (b[31]) << 24) - | ((sword64) (b[32]) << 32) - | ((sword64) (b[33]) << 40) - | ((sword64) (b[34]) << 48); - t[ 5] = ((sword64) (b[35]) << 0) - | ((sword64) (b[36]) << 8) - | ((sword64) (b[37]) << 16) - | ((sword64) (b[38]) << 24) - | ((sword64) (b[39]) << 32) - | ((sword64) (b[40]) << 40) - | ((sword64) (b[41]) << 48); - t[ 6] = ((sword64) (b[42]) << 0) - | ((sword64) (b[43]) << 8) - | ((sword64) (b[44]) << 16) - | ((sword64) (b[45]) << 24) - | ((sword64) (b[46]) << 32) - | ((sword64) (b[47]) << 40) - | ((sword64) (b[48]) << 48); - t[ 7] = ((sword64) (b[49]) << 0) - | ((sword64) (b[50]) << 8) - | ((sword64) (b[51]) << 16) - | ((sword64) (b[52]) << 24) - | ((sword64) (b[53]) << 32) - | ((sword64) (b[54]) << 40) - | ((sword64) (b[55]) << 48); - t[ 8] = ((sword64) (b[56]) << 0) - | ((sword64) (b[57]) << 8) - | ((sword64) (b[58]) << 16) - | ((sword64) (b[59]) << 24) - | ((sword64) (b[60]) << 32) - | ((sword64) (b[61]) << 40) - | ((sword64) (b[62]) << 48); - t[ 9] = ((sword64) (b[63]) << 0) - | ((sword64) (b[64]) << 8) - | ((sword64) (b[65]) << 16) - | ((sword64) (b[66]) << 24) - | ((sword64) (b[67]) << 32) - | ((sword64) (b[68]) << 40) - | ((sword64) (b[69]) << 48); - t[10] = ((sword64) (b[70]) << 0) - | ((sword64) (b[71]) << 8) - | ((sword64) (b[72]) << 16) - | ((sword64) (b[73]) << 24) - | ((sword64) (b[74]) << 32) - | ((sword64) (b[75]) << 40) - | ((sword64) (b[76]) << 48); - t[11] = ((sword64) (b[77]) << 0) - | ((sword64) (b[78]) << 8) - | ((sword64) (b[79]) << 16) - | ((sword64) (b[80]) << 24) - | ((sword64) (b[81]) << 32) - | ((sword64) (b[82]) << 40) - | ((sword64) (b[83]) << 48); - t[12] = ((sword64) (b[84]) << 0) - | ((sword64) (b[85]) << 8) - | ((sword64) (b[86]) << 16) - | ((sword64) (b[87]) << 24) - | ((sword64) (b[88]) << 32) - | ((sword64) (b[89]) << 40) - | ((sword64) (b[90]) << 48); - t[13] = ((sword64) (b[91]) << 0) - | ((sword64) (b[92]) << 8) - | ((sword64) (b[93]) << 16) - | ((sword64) (b[94]) << 24) - | ((sword64) (b[95]) << 32) - | ((sword64) (b[96]) << 40) - | ((sword64) (b[97]) << 48); - t[14] = ((sword64) (b[98]) << 0) - | ((sword64) (b[99]) << 8) - | ((sword64) (b[100]) << 16) - | ((sword64) (b[101]) << 24) - | ((sword64) (b[102]) << 32) - | ((sword64) (b[103]) << 40) - | ((sword64) (b[104]) << 48); - t[15] = ((sword64) (b[105]) << 0) - | ((sword64) (b[106]) << 8) - | ((sword64) (b[107]) << 16) - | ((sword64) (b[108]) << 24) - | ((sword64) (b[109]) << 32) - | ((sword64) (b[110]) << 40) - | ((sword64) (b[111]) << 48); - t[16] = ((sword64) (b[112]) << 0) - | ((sword64) (b[113]) << 8); + t[ 0] = (word64)((sword64) (b[ 0]) << 0) + | (word64)((sword64) (b[ 1]) << 8) + | (word64)((sword64) (b[ 2]) << 16) + | (word64)((sword64) (b[ 3]) << 24) + | (word64)((sword64) (b[ 4]) << 32) + | (word64)((sword64) (b[ 5]) << 40) + | (word64)((sword64) (b[ 6]) << 48); + t[ 1] = (word64)((sword64) (b[ 7]) << 0) + | (word64)((sword64) (b[ 8]) << 8) + | (word64)((sword64) (b[ 9]) << 16) + | (word64)((sword64) (b[10]) << 24) + | (word64)((sword64) (b[11]) << 32) + | (word64)((sword64) (b[12]) << 40) + | (word64)((sword64) (b[13]) << 48); + t[ 2] = (word64)((sword64) (b[14]) << 0) + | (word64)((sword64) (b[15]) << 8) + | (word64)((sword64) (b[16]) << 16) + | (word64)((sword64) (b[17]) << 24) + | (word64)((sword64) (b[18]) << 32) + | (word64)((sword64) (b[19]) << 40) + | (word64)((sword64) (b[20]) << 48); + t[ 3] = (word64)((sword64) (b[21]) << 0) + | (word64)((sword64) (b[22]) << 8) + | (word64)((sword64) (b[23]) << 16) + | (word64)((sword64) (b[24]) << 24) + | (word64)((sword64) (b[25]) << 32) + | (word64)((sword64) (b[26]) << 40) + | (word64)((sword64) (b[27]) << 48); + t[ 4] = (word64)((sword64) (b[28]) << 0) + | (word64)((sword64) (b[29]) << 8) + | (word64)((sword64) (b[30]) << 16) + | (word64)((sword64) (b[31]) << 24) + | (word64)((sword64) (b[32]) << 32) + | (word64)((sword64) (b[33]) << 40) + | (word64)((sword64) (b[34]) << 48); + t[ 5] = (word64)((sword64) (b[35]) << 0) + | (word64)((sword64) (b[36]) << 8) + | (word64)((sword64) (b[37]) << 16) + | (word64)((sword64) (b[38]) << 24) + | (word64)((sword64) (b[39]) << 32) + | (word64)((sword64) (b[40]) << 40) + | (word64)((sword64) (b[41]) << 48); + t[ 6] = (word64)((sword64) (b[42]) << 0) + | (word64)((sword64) (b[43]) << 8) + | (word64)((sword64) (b[44]) << 16) + | (word64)((sword64) (b[45]) << 24) + | (word64)((sword64) (b[46]) << 32) + | (word64)((sword64) (b[47]) << 40) + | (word64)((sword64) (b[48]) << 48); + t[ 7] = (word64)((sword64) (b[49]) << 0) + | (word64)((sword64) (b[50]) << 8) + | (word64)((sword64) (b[51]) << 16) + | (word64)((sword64) (b[52]) << 24) + | (word64)((sword64) (b[53]) << 32) + | (word64)((sword64) (b[54]) << 40) + | (word64)((sword64) (b[55]) << 48); + t[ 8] = (word64)((sword64) (b[56]) << 0) + | (word64)((sword64) (b[57]) << 8) + | (word64)((sword64) (b[58]) << 16) + | (word64)((sword64) (b[59]) << 24) + | (word64)((sword64) (b[60]) << 32) + | (word64)((sword64) (b[61]) << 40) + | (word64)((sword64) (b[62]) << 48); + t[ 9] = (word64)((sword64) (b[63]) << 0) + | (word64)((sword64) (b[64]) << 8) + | (word64)((sword64) (b[65]) << 16) + | (word64)((sword64) (b[66]) << 24) + | (word64)((sword64) (b[67]) << 32) + | (word64)((sword64) (b[68]) << 40) + | (word64)((sword64) (b[69]) << 48); + t[10] = (word64)((sword64) (b[70]) << 0) + | (word64)((sword64) (b[71]) << 8) + | (word64)((sword64) (b[72]) << 16) + | (word64)((sword64) (b[73]) << 24) + | (word64)((sword64) (b[74]) << 32) + | (word64)((sword64) (b[75]) << 40) + | (word64)((sword64) (b[76]) << 48); + t[11] = (word64)((sword64) (b[77]) << 0) + | (word64)((sword64) (b[78]) << 8) + | (word64)((sword64) (b[79]) << 16) + | (word64)((sword64) (b[80]) << 24) + | (word64)((sword64) (b[81]) << 32) + | (word64)((sword64) (b[82]) << 40) + | (word64)((sword64) (b[83]) << 48); + t[12] = (word64)((sword64) (b[84]) << 0) + | (word64)((sword64) (b[85]) << 8) + | (word64)((sword64) (b[86]) << 16) + | (word64)((sword64) (b[87]) << 24) + | (word64)((sword64) (b[88]) << 32) + | (word64)((sword64) (b[89]) << 40) + | (word64)((sword64) (b[90]) << 48); + t[13] = (word64)((sword64) (b[91]) << 0) + | (word64)((sword64) (b[92]) << 8) + | (word64)((sword64) (b[93]) << 16) + | (word64)((sword64) (b[94]) << 24) + | (word64)((sword64) (b[95]) << 32) + | (word64)((sword64) (b[96]) << 40) + | (word64)((sword64) (b[97]) << 48); + t[14] = (word64)((sword64) (b[98]) << 0) + | (word64)((sword64) (b[99]) << 8) + | (word64)((sword64) (b[100]) << 16) + | (word64)((sword64) (b[101]) << 24) + | (word64)((sword64) (b[102]) << 32) + | (word64)((sword64) (b[103]) << 40) + | (word64)((sword64) (b[104]) << 48); + t[15] = (word64)((sword64) (b[105]) << 0) + | (word64)((sword64) (b[106]) << 8) + | (word64)((sword64) (b[107]) << 16) + | (word64)((sword64) (b[108]) << 24) + | (word64)((sword64) (b[109]) << 32) + | (word64)((sword64) (b[110]) << 40) + | (word64)((sword64) (b[111]) << 48); + t[16] = (word64)((sword64) (b[112]) << 0) + | (word64)((sword64) (b[113]) << 8); /* Mod curve order */ /* 2^446 - 0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d */ @@ -721,243 +744,244 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) word128 t[16]; word128 c; word64 o; + sword64 u; /* Load from bytes */ - ad[ 0] = ((sword64) (a[ 0]) << 0) - | ((sword64) (a[ 1]) << 8) - | ((sword64) (a[ 2]) << 16) - | ((sword64) (a[ 3]) << 24) - | ((sword64) (a[ 4]) << 32) - | ((sword64) (a[ 5]) << 40) - | ((sword64) (a[ 6]) << 48); - ad[ 1] = ((sword64) (a[ 7]) << 0) - | ((sword64) (a[ 8]) << 8) - | ((sword64) (a[ 9]) << 16) - | ((sword64) (a[10]) << 24) - | ((sword64) (a[11]) << 32) - | ((sword64) (a[12]) << 40) - | ((sword64) (a[13]) << 48); - ad[ 2] = ((sword64) (a[14]) << 0) - | ((sword64) (a[15]) << 8) - | ((sword64) (a[16]) << 16) - | ((sword64) (a[17]) << 24) - | ((sword64) (a[18]) << 32) - | ((sword64) (a[19]) << 40) - | ((sword64) (a[20]) << 48); - ad[ 3] = ((sword64) (a[21]) << 0) - | ((sword64) (a[22]) << 8) - | ((sword64) (a[23]) << 16) - | ((sword64) (a[24]) << 24) - | ((sword64) (a[25]) << 32) - | ((sword64) (a[26]) << 40) - | ((sword64) (a[27]) << 48); - ad[ 4] = ((sword64) (a[28]) << 0) - | ((sword64) (a[29]) << 8) - | ((sword64) (a[30]) << 16) - | ((sword64) (a[31]) << 24) - | ((sword64) (a[32]) << 32) - | ((sword64) (a[33]) << 40) - | ((sword64) (a[34]) << 48); - ad[ 5] = ((sword64) (a[35]) << 0) - | ((sword64) (a[36]) << 8) - | ((sword64) (a[37]) << 16) - | ((sword64) (a[38]) << 24) - | ((sword64) (a[39]) << 32) - | ((sword64) (a[40]) << 40) - | ((sword64) (a[41]) << 48); - ad[ 6] = ((sword64) (a[42]) << 0) - | ((sword64) (a[43]) << 8) - | ((sword64) (a[44]) << 16) - | ((sword64) (a[45]) << 24) - | ((sword64) (a[46]) << 32) - | ((sword64) (a[47]) << 40) - | ((sword64) (a[48]) << 48); - ad[ 7] = ((sword64) (a[49]) << 0) - | ((sword64) (a[50]) << 8) - | ((sword64) (a[51]) << 16) - | ((sword64) (a[52]) << 24) - | ((sword64) (a[53]) << 32) - | ((sword64) (a[54]) << 40) - | ((sword64) (a[55]) << 48); + ad[ 0] = (word64)((sword64) (a[ 0]) << 0) + | (word64)((sword64) (a[ 1]) << 8) + | (word64)((sword64) (a[ 2]) << 16) + | (word64)((sword64) (a[ 3]) << 24) + | (word64)((sword64) (a[ 4]) << 32) + | (word64)((sword64) (a[ 5]) << 40) + | (word64)((sword64) (a[ 6]) << 48); + ad[ 1] = (word64)((sword64) (a[ 7]) << 0) + | (word64)((sword64) (a[ 8]) << 8) + | (word64)((sword64) (a[ 9]) << 16) + | (word64)((sword64) (a[10]) << 24) + | (word64)((sword64) (a[11]) << 32) + | (word64)((sword64) (a[12]) << 40) + | (word64)((sword64) (a[13]) << 48); + ad[ 2] = (word64)((sword64) (a[14]) << 0) + | (word64)((sword64) (a[15]) << 8) + | (word64)((sword64) (a[16]) << 16) + | (word64)((sword64) (a[17]) << 24) + | (word64)((sword64) (a[18]) << 32) + | (word64)((sword64) (a[19]) << 40) + | (word64)((sword64) (a[20]) << 48); + ad[ 3] = (word64)((sword64) (a[21]) << 0) + | (word64)((sword64) (a[22]) << 8) + | (word64)((sword64) (a[23]) << 16) + | (word64)((sword64) (a[24]) << 24) + | (word64)((sword64) (a[25]) << 32) + | (word64)((sword64) (a[26]) << 40) + | (word64)((sword64) (a[27]) << 48); + ad[ 4] = (word64)((sword64) (a[28]) << 0) + | (word64)((sword64) (a[29]) << 8) + | (word64)((sword64) (a[30]) << 16) + | (word64)((sword64) (a[31]) << 24) + | (word64)((sword64) (a[32]) << 32) + | (word64)((sword64) (a[33]) << 40) + | (word64)((sword64) (a[34]) << 48); + ad[ 5] = (word64)((sword64) (a[35]) << 0) + | (word64)((sword64) (a[36]) << 8) + | (word64)((sword64) (a[37]) << 16) + | (word64)((sword64) (a[38]) << 24) + | (word64)((sword64) (a[39]) << 32) + | (word64)((sword64) (a[40]) << 40) + | (word64)((sword64) (a[41]) << 48); + ad[ 6] = (word64)((sword64) (a[42]) << 0) + | (word64)((sword64) (a[43]) << 8) + | (word64)((sword64) (a[44]) << 16) + | (word64)((sword64) (a[45]) << 24) + | (word64)((sword64) (a[46]) << 32) + | (word64)((sword64) (a[47]) << 40) + | (word64)((sword64) (a[48]) << 48); + ad[ 7] = (word64)((sword64) (a[49]) << 0) + | (word64)((sword64) (a[50]) << 8) + | (word64)((sword64) (a[51]) << 16) + | (word64)((sword64) (a[52]) << 24) + | (word64)((sword64) (a[53]) << 32) + | (word64)((sword64) (a[54]) << 40) + | (word64)((sword64) (a[55]) << 48); /* Load from bytes */ - bd[ 0] = ((sword64) (b[ 0]) << 0) - | ((sword64) (b[ 1]) << 8) - | ((sword64) (b[ 2]) << 16) - | ((sword64) (b[ 3]) << 24) - | ((sword64) (b[ 4]) << 32) - | ((sword64) (b[ 5]) << 40) - | ((sword64) (b[ 6]) << 48); - bd[ 1] = ((sword64) (b[ 7]) << 0) - | ((sword64) (b[ 8]) << 8) - | ((sword64) (b[ 9]) << 16) - | ((sword64) (b[10]) << 24) - | ((sword64) (b[11]) << 32) - | ((sword64) (b[12]) << 40) - | ((sword64) (b[13]) << 48); - bd[ 2] = ((sword64) (b[14]) << 0) - | ((sword64) (b[15]) << 8) - | ((sword64) (b[16]) << 16) - | ((sword64) (b[17]) << 24) - | ((sword64) (b[18]) << 32) - | ((sword64) (b[19]) << 40) - | ((sword64) (b[20]) << 48); - bd[ 3] = ((sword64) (b[21]) << 0) - | ((sword64) (b[22]) << 8) - | ((sword64) (b[23]) << 16) - | ((sword64) (b[24]) << 24) - | ((sword64) (b[25]) << 32) - | ((sword64) (b[26]) << 40) - | ((sword64) (b[27]) << 48); - bd[ 4] = ((sword64) (b[28]) << 0) - | ((sword64) (b[29]) << 8) - | ((sword64) (b[30]) << 16) - | ((sword64) (b[31]) << 24) - | ((sword64) (b[32]) << 32) - | ((sword64) (b[33]) << 40) - | ((sword64) (b[34]) << 48); - bd[ 5] = ((sword64) (b[35]) << 0) - | ((sword64) (b[36]) << 8) - | ((sword64) (b[37]) << 16) - | ((sword64) (b[38]) << 24) - | ((sword64) (b[39]) << 32) - | ((sword64) (b[40]) << 40) - | ((sword64) (b[41]) << 48); - bd[ 6] = ((sword64) (b[42]) << 0) - | ((sword64) (b[43]) << 8) - | ((sword64) (b[44]) << 16) - | ((sword64) (b[45]) << 24) - | ((sword64) (b[46]) << 32) - | ((sword64) (b[47]) << 40) - | ((sword64) (b[48]) << 48); - bd[ 7] = ((sword64) (b[49]) << 0) - | ((sword64) (b[50]) << 8) - | ((sword64) (b[51]) << 16) - | ((sword64) (b[52]) << 24) - | ((sword64) (b[53]) << 32) - | ((sword64) (b[54]) << 40) - | ((sword64) (b[55]) << 48); + bd[ 0] = (word64)((sword64) (b[ 0]) << 0) + | (word64)((sword64) (b[ 1]) << 8) + | (word64)((sword64) (b[ 2]) << 16) + | (word64)((sword64) (b[ 3]) << 24) + | (word64)((sword64) (b[ 4]) << 32) + | (word64)((sword64) (b[ 5]) << 40) + | (word64)((sword64) (b[ 6]) << 48); + bd[ 1] = (word64)((sword64) (b[ 7]) << 0) + | (word64)((sword64) (b[ 8]) << 8) + | (word64)((sword64) (b[ 9]) << 16) + | (word64)((sword64) (b[10]) << 24) + | (word64)((sword64) (b[11]) << 32) + | (word64)((sword64) (b[12]) << 40) + | (word64)((sword64) (b[13]) << 48); + bd[ 2] = (word64)((sword64) (b[14]) << 0) + | (word64)((sword64) (b[15]) << 8) + | (word64)((sword64) (b[16]) << 16) + | (word64)((sword64) (b[17]) << 24) + | (word64)((sword64) (b[18]) << 32) + | (word64)((sword64) (b[19]) << 40) + | (word64)((sword64) (b[20]) << 48); + bd[ 3] = (word64)((sword64) (b[21]) << 0) + | (word64)((sword64) (b[22]) << 8) + | (word64)((sword64) (b[23]) << 16) + | (word64)((sword64) (b[24]) << 24) + | (word64)((sword64) (b[25]) << 32) + | (word64)((sword64) (b[26]) << 40) + | (word64)((sword64) (b[27]) << 48); + bd[ 4] = (word64)((sword64) (b[28]) << 0) + | (word64)((sword64) (b[29]) << 8) + | (word64)((sword64) (b[30]) << 16) + | (word64)((sword64) (b[31]) << 24) + | (word64)((sword64) (b[32]) << 32) + | (word64)((sword64) (b[33]) << 40) + | (word64)((sword64) (b[34]) << 48); + bd[ 5] = (word64)((sword64) (b[35]) << 0) + | (word64)((sword64) (b[36]) << 8) + | (word64)((sword64) (b[37]) << 16) + | (word64)((sword64) (b[38]) << 24) + | (word64)((sword64) (b[39]) << 32) + | (word64)((sword64) (b[40]) << 40) + | (word64)((sword64) (b[41]) << 48); + bd[ 6] = (word64)((sword64) (b[42]) << 0) + | (word64)((sword64) (b[43]) << 8) + | (word64)((sword64) (b[44]) << 16) + | (word64)((sword64) (b[45]) << 24) + | (word64)((sword64) (b[46]) << 32) + | (word64)((sword64) (b[47]) << 40) + | (word64)((sword64) (b[48]) << 48); + bd[ 7] = (word64)((sword64) (b[49]) << 0) + | (word64)((sword64) (b[50]) << 8) + | (word64)((sword64) (b[51]) << 16) + | (word64)((sword64) (b[52]) << 24) + | (word64)((sword64) (b[53]) << 32) + | (word64)((sword64) (b[54]) << 40) + | (word64)((sword64) (b[55]) << 48); /* Load from bytes */ - dd[ 0] = ((sword64) (d[ 0]) << 0) - | ((sword64) (d[ 1]) << 8) - | ((sword64) (d[ 2]) << 16) - | ((sword64) (d[ 3]) << 24) - | ((sword64) (d[ 4]) << 32) - | ((sword64) (d[ 5]) << 40) - | ((sword64) (d[ 6]) << 48); - dd[ 1] = ((sword64) (d[ 7]) << 0) - | ((sword64) (d[ 8]) << 8) - | ((sword64) (d[ 9]) << 16) - | ((sword64) (d[10]) << 24) - | ((sword64) (d[11]) << 32) - | ((sword64) (d[12]) << 40) - | ((sword64) (d[13]) << 48); - dd[ 2] = ((sword64) (d[14]) << 0) - | ((sword64) (d[15]) << 8) - | ((sword64) (d[16]) << 16) - | ((sword64) (d[17]) << 24) - | ((sword64) (d[18]) << 32) - | ((sword64) (d[19]) << 40) - | ((sword64) (d[20]) << 48); - dd[ 3] = ((sword64) (d[21]) << 0) - | ((sword64) (d[22]) << 8) - | ((sword64) (d[23]) << 16) - | ((sword64) (d[24]) << 24) - | ((sword64) (d[25]) << 32) - | ((sword64) (d[26]) << 40) - | ((sword64) (d[27]) << 48); - dd[ 4] = ((sword64) (d[28]) << 0) - | ((sword64) (d[29]) << 8) - | ((sword64) (d[30]) << 16) - | ((sword64) (d[31]) << 24) - | ((sword64) (d[32]) << 32) - | ((sword64) (d[33]) << 40) - | ((sword64) (d[34]) << 48); - dd[ 5] = ((sword64) (d[35]) << 0) - | ((sword64) (d[36]) << 8) - | ((sword64) (d[37]) << 16) - | ((sword64) (d[38]) << 24) - | ((sword64) (d[39]) << 32) - | ((sword64) (d[40]) << 40) - | ((sword64) (d[41]) << 48); - dd[ 6] = ((sword64) (d[42]) << 0) - | ((sword64) (d[43]) << 8) - | ((sword64) (d[44]) << 16) - | ((sword64) (d[45]) << 24) - | ((sword64) (d[46]) << 32) - | ((sword64) (d[47]) << 40) - | ((sword64) (d[48]) << 48); - dd[ 7] = ((sword64) (d[49]) << 0) - | ((sword64) (d[50]) << 8) - | ((sword64) (d[51]) << 16) - | ((sword64) (d[52]) << 24) - | ((sword64) (d[53]) << 32) - | ((sword64) (d[54]) << 40) - | ((sword64) (d[55]) << 48); + dd[ 0] = (word64)((sword64) (d[ 0]) << 0) + | (word64)((sword64) (d[ 1]) << 8) + | (word64)((sword64) (d[ 2]) << 16) + | (word64)((sword64) (d[ 3]) << 24) + | (word64)((sword64) (d[ 4]) << 32) + | (word64)((sword64) (d[ 5]) << 40) + | (word64)((sword64) (d[ 6]) << 48); + dd[ 1] = (word64)((sword64) (d[ 7]) << 0) + | (word64)((sword64) (d[ 8]) << 8) + | (word64)((sword64) (d[ 9]) << 16) + | (word64)((sword64) (d[10]) << 24) + | (word64)((sword64) (d[11]) << 32) + | (word64)((sword64) (d[12]) << 40) + | (word64)((sword64) (d[13]) << 48); + dd[ 2] = (word64)((sword64) (d[14]) << 0) + | (word64)((sword64) (d[15]) << 8) + | (word64)((sword64) (d[16]) << 16) + | (word64)((sword64) (d[17]) << 24) + | (word64)((sword64) (d[18]) << 32) + | (word64)((sword64) (d[19]) << 40) + | (word64)((sword64) (d[20]) << 48); + dd[ 3] = (word64)((sword64) (d[21]) << 0) + | (word64)((sword64) (d[22]) << 8) + | (word64)((sword64) (d[23]) << 16) + | (word64)((sword64) (d[24]) << 24) + | (word64)((sword64) (d[25]) << 32) + | (word64)((sword64) (d[26]) << 40) + | (word64)((sword64) (d[27]) << 48); + dd[ 4] = (word64)((sword64) (d[28]) << 0) + | (word64)((sword64) (d[29]) << 8) + | (word64)((sword64) (d[30]) << 16) + | (word64)((sword64) (d[31]) << 24) + | (word64)((sword64) (d[32]) << 32) + | (word64)((sword64) (d[33]) << 40) + | (word64)((sword64) (d[34]) << 48); + dd[ 5] = (word64)((sword64) (d[35]) << 0) + | (word64)((sword64) (d[36]) << 8) + | (word64)((sword64) (d[37]) << 16) + | (word64)((sword64) (d[38]) << 24) + | (word64)((sword64) (d[39]) << 32) + | (word64)((sword64) (d[40]) << 40) + | (word64)((sword64) (d[41]) << 48); + dd[ 6] = (word64)((sword64) (d[42]) << 0) + | (word64)((sword64) (d[43]) << 8) + | (word64)((sword64) (d[44]) << 16) + | (word64)((sword64) (d[45]) << 24) + | (word64)((sword64) (d[46]) << 32) + | (word64)((sword64) (d[47]) << 40) + | (word64)((sword64) (d[48]) << 48); + dd[ 7] = (word64)((sword64) (d[49]) << 0) + | (word64)((sword64) (d[50]) << 8) + | (word64)((sword64) (d[51]) << 16) + | (word64)((sword64) (d[52]) << 24) + | (word64)((sword64) (d[53]) << 32) + | (word64)((sword64) (d[54]) << 40) + | (word64)((sword64) (d[55]) << 48); /* a * b + d */ - t[ 0] = (word128)dd[ 0] + (sword128)ad[ 0] * bd[ 0]; - t[ 1] = (word128)dd[ 1] + (sword128)ad[ 0] * bd[ 1] - + (sword128)ad[ 1] * bd[ 0]; - t[ 2] = (word128)dd[ 2] + (sword128)ad[ 0] * bd[ 2] - + (sword128)ad[ 1] * bd[ 1] - + (sword128)ad[ 2] * bd[ 0]; - t[ 3] = (word128)dd[ 3] + (sword128)ad[ 0] * bd[ 3] - + (sword128)ad[ 1] * bd[ 2] - + (sword128)ad[ 2] * bd[ 1] - + (sword128)ad[ 3] * bd[ 0]; - t[ 4] = (word128)dd[ 4] + (sword128)ad[ 0] * bd[ 4] + t[ 0] = (word128)dd[ 0] + (word128)((sword128)ad[ 0] * bd[ 0]); + t[ 1] = (word128)dd[ 1] + (word128)((sword128)ad[ 0] * bd[ 1] + + (sword128)ad[ 1] * bd[ 0]); + t[ 2] = (word128)dd[ 2] + (word128)((sword128)ad[ 0] * bd[ 2] + + (sword128)ad[ 1] * bd[ 1] + + (sword128)ad[ 2] * bd[ 0]); + t[ 3] = (word128)dd[ 3] + (word128)((sword128)ad[ 0] * bd[ 3] + + (sword128)ad[ 1] * bd[ 2] + + (sword128)ad[ 2] * bd[ 1] + + (sword128)ad[ 3] * bd[ 0]); + t[ 4] = (word128)dd[ 4] + (word128)((sword128)ad[ 0] * bd[ 4] + (sword128)ad[ 1] * bd[ 3] + (sword128)ad[ 2] * bd[ 2] + (sword128)ad[ 3] * bd[ 1] - + (sword128)ad[ 4] * bd[ 0]; - t[ 5] = (word128)dd[ 5] + (sword128)ad[ 0] * bd[ 5] + + (sword128)ad[ 4] * bd[ 0]); + t[ 5] = (word128)dd[ 5] + (word128)((sword128)ad[ 0] * bd[ 5] + (sword128)ad[ 1] * bd[ 4] + (sword128)ad[ 2] * bd[ 3] + (sword128)ad[ 3] * bd[ 2] + (sword128)ad[ 4] * bd[ 1] - + (sword128)ad[ 5] * bd[ 0]; - t[ 6] = (word128)dd[ 6] + (sword128)ad[ 0] * bd[ 6] + + (sword128)ad[ 5] * bd[ 0]); + t[ 6] = (word128)dd[ 6] + (word128)((sword128)ad[ 0] * bd[ 6] + (sword128)ad[ 1] * bd[ 5] + (sword128)ad[ 2] * bd[ 4] + (sword128)ad[ 3] * bd[ 3] + (sword128)ad[ 4] * bd[ 2] + (sword128)ad[ 5] * bd[ 1] - + (sword128)ad[ 6] * bd[ 0]; - t[ 7] = (word128)dd[ 7] + (sword128)ad[ 0] * bd[ 7] + + (sword128)ad[ 6] * bd[ 0]); + t[ 7] = (word128)dd[ 7] + (word128)((sword128)ad[ 0] * bd[ 7] + (sword128)ad[ 1] * bd[ 6] + (sword128)ad[ 2] * bd[ 5] + (sword128)ad[ 3] * bd[ 4] + (sword128)ad[ 4] * bd[ 3] + (sword128)ad[ 5] * bd[ 2] + (sword128)ad[ 6] * bd[ 1] - + (sword128)ad[ 7] * bd[ 0]; - t[ 8] = (word128) (sword128)ad[ 1] * bd[ 7] + + (sword128)ad[ 7] * bd[ 0]); + t[ 8] = (word128) ((sword128)ad[ 1] * bd[ 7] + (sword128)ad[ 2] * bd[ 6] + (sword128)ad[ 3] * bd[ 5] + (sword128)ad[ 4] * bd[ 4] + (sword128)ad[ 5] * bd[ 3] + (sword128)ad[ 6] * bd[ 2] - + (sword128)ad[ 7] * bd[ 1]; - t[ 9] = (word128) (sword128)ad[ 2] * bd[ 7] + + (sword128)ad[ 7] * bd[ 1]); + t[ 9] = (word128) ((sword128)ad[ 2] * bd[ 7] + (sword128)ad[ 3] * bd[ 6] + (sword128)ad[ 4] * bd[ 5] + (sword128)ad[ 5] * bd[ 4] + (sword128)ad[ 6] * bd[ 3] - + (sword128)ad[ 7] * bd[ 2]; - t[10] = (word128) (sword128)ad[ 3] * bd[ 7] + + (sword128)ad[ 7] * bd[ 2]); + t[10] = (word128) ((sword128)ad[ 3] * bd[ 7] + (sword128)ad[ 4] * bd[ 6] + (sword128)ad[ 5] * bd[ 5] + (sword128)ad[ 6] * bd[ 4] - + (sword128)ad[ 7] * bd[ 3]; - t[11] = (word128) (sword128)ad[ 4] * bd[ 7] + + (sword128)ad[ 7] * bd[ 3]); + t[11] = (word128) ((sword128)ad[ 4] * bd[ 7] + (sword128)ad[ 5] * bd[ 6] + (sword128)ad[ 6] * bd[ 5] - + (sword128)ad[ 7] * bd[ 4]; - t[12] = (word128) (sword128)ad[ 5] * bd[ 7] + + (sword128)ad[ 7] * bd[ 4]); + t[12] = (word128) ((sword128)ad[ 5] * bd[ 7] + (sword128)ad[ 6] * bd[ 6] - + (sword128)ad[ 7] * bd[ 5]; - t[13] = (word128) (sword128)ad[ 6] * bd[ 7] - + (sword128)ad[ 7] * bd[ 6]; + + (sword128)ad[ 7] * bd[ 5]); + t[13] = (word128) ((sword128)ad[ 6] * bd[ 7] + + (sword128)ad[ 7] * bd[ 6]); t[14] = (word128) (sword128)ad[ 7] * bd[ 7]; t[15] = 0; @@ -1044,6 +1068,41 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) o = rd[ 4] >> 56; rd[ 5] += o; rd[ 4] = rd[ 4] & 0xffffffffffffff; o = rd[ 5] >> 56; rd[ 6] += o; rd[ 5] = rd[ 5] & 0xffffffffffffff; o = rd[ 6] >> 56; rd[ 7] += o; rd[ 6] = rd[ 6] & 0xffffffffffffff; + /* Reduce to mod order. */ + u = 0; + u += (sword64)rd[0] - (sword64)0x078c292ab5844f3L; u >>= 56; + u += (sword64)rd[1] - (sword64)0x0c2728dc58f5523L; u >>= 56; + u += (sword64)rd[2] - (sword64)0x049aed63690216cL; u >>= 56; + u += (sword64)rd[3] - (sword64)0x07cca23e9c44edbL; u >>= 56; + u += (sword64)rd[4] - (sword64)0x0ffffffffffffffL; u >>= 56; + u += (sword64)rd[5] - (sword64)0x0ffffffffffffffL; u >>= 56; + u += (sword64)rd[6] - (sword64)0x0ffffffffffffffL; u >>= 56; + u += (sword64)rd[7] - (sword64)0x03fffffffffffffL; u >>= 56; + o = (word64)0 - (u >= 0); + u = 0; + u += (sword64)rd[0] - (sword64)((word64)0x078c292ab5844f3L & o); + rd[0] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[1] - (sword64)((word64)0x0c2728dc58f5523L & o); + rd[1] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[2] - (sword64)((word64)0x049aed63690216cL & o); + rd[2] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[3] - (sword64)((word64)0x07cca23e9c44edbL & o); + rd[3] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[4] - (sword64)((word64)0x0ffffffffffffffL & o); + rd[4] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[5] - (sword64)((word64)0x0ffffffffffffffL & o); + rd[5] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[6] - (sword64)((word64)0x0ffffffffffffffL & o); + rd[6] = u & 0xffffffffffffff; + u >>= 56; + u += (sword64)rd[7] - (sword64)((word64)0x03fffffffffffffL & o); + rd[7] = u & 0xffffffffffffff; /* Convert to bytes */ r[ 0] = (byte)(rd[0 ] >> 0); @@ -5072,6 +5131,8 @@ static const ge448_precomp base_i[16] = { /* Reduce scalar mod the order of the curve. * Scalar Will be 114 bytes. * + * Only performs a weak reduce. + * * b [in] Scalar to reduce. */ void sc448_reduce(byte* b) @@ -5453,56 +5514,56 @@ void sc448_reduce(byte* b) b[ 0] = (byte)(d[0 ] >> 0); b[ 1] = (byte)(d[0 ] >> 8); b[ 2] = (byte)(d[0 ] >> 16); - b[ 3] = (byte)((d[0 ] >> 24) + ((d[1 ] >> 0) << 4)); + b[ 3] = (byte)(d[0 ] >> 24) + (byte)((d[1 ] >> 0) << 4); b[ 4] = (byte)(d[1 ] >> 4); b[ 5] = (byte)(d[1 ] >> 12); b[ 6] = (byte)(d[1 ] >> 20); b[ 7] = (byte)(d[2 ] >> 0); b[ 8] = (byte)(d[2 ] >> 8); b[ 9] = (byte)(d[2 ] >> 16); - b[10] = (byte)((d[2 ] >> 24) + ((d[3 ] >> 0) << 4)); + b[10] = (byte)(d[2 ] >> 24) + (byte)((d[3 ] >> 0) << 4); b[11] = (byte)(d[3 ] >> 4); b[12] = (byte)(d[3 ] >> 12); b[13] = (byte)(d[3 ] >> 20); b[14] = (byte)(d[4 ] >> 0); b[15] = (byte)(d[4 ] >> 8); b[16] = (byte)(d[4 ] >> 16); - b[17] = (byte)((d[4 ] >> 24) + ((d[5 ] >> 0) << 4)); + b[17] = (byte)(d[4 ] >> 24) + (byte)((d[5 ] >> 0) << 4); b[18] = (byte)(d[5 ] >> 4); b[19] = (byte)(d[5 ] >> 12); b[20] = (byte)(d[5 ] >> 20); b[21] = (byte)(d[6 ] >> 0); b[22] = (byte)(d[6 ] >> 8); b[23] = (byte)(d[6 ] >> 16); - b[24] = (byte)((d[6 ] >> 24) + ((d[7 ] >> 0) << 4)); + b[24] = (byte)(d[6 ] >> 24) + (byte)((d[7 ] >> 0) << 4); b[25] = (byte)(d[7 ] >> 4); b[26] = (byte)(d[7 ] >> 12); b[27] = (byte)(d[7 ] >> 20); b[28] = (byte)(d[8 ] >> 0); b[29] = (byte)(d[8 ] >> 8); b[30] = (byte)(d[8 ] >> 16); - b[31] = (byte)((d[8 ] >> 24) + ((d[9 ] >> 0) << 4)); + b[31] = (byte)(d[8 ] >> 24) + (byte)((d[9 ] >> 0) << 4); b[32] = (byte)(d[9 ] >> 4); b[33] = (byte)(d[9 ] >> 12); b[34] = (byte)(d[9 ] >> 20); b[35] = (byte)(d[10] >> 0); b[36] = (byte)(d[10] >> 8); b[37] = (byte)(d[10] >> 16); - b[38] = (byte)((d[10] >> 24) + ((d[11] >> 0) << 4)); + b[38] = (byte)(d[10] >> 24) + (byte)((d[11] >> 0) << 4); b[39] = (byte)(d[11] >> 4); b[40] = (byte)(d[11] >> 12); b[41] = (byte)(d[11] >> 20); b[42] = (byte)(d[12] >> 0); b[43] = (byte)(d[12] >> 8); b[44] = (byte)(d[12] >> 16); - b[45] = (byte)((d[12] >> 24) + ((d[13] >> 0) << 4)); + b[45] = (byte)(d[12] >> 24) + (byte)((d[13] >> 0) << 4); b[46] = (byte)(d[13] >> 4); b[47] = (byte)(d[13] >> 12); b[48] = (byte)(d[13] >> 20); b[49] = (byte)(d[14] >> 0); b[50] = (byte)(d[14] >> 8); b[51] = (byte)(d[14] >> 16); - b[52] = (byte)((d[14] >> 24) + ((d[15] >> 0) << 4)); + b[52] = (byte)(d[14] >> 24) + (byte)((d[15] >> 0) << 4); b[53] = (byte)(d[15] >> 4); b[54] = (byte)(d[15] >> 12); b[55] = (byte)(d[15] >> 20); @@ -5522,6 +5583,7 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) word64 t[32]; word64 c; word32 o; + sword32 u; /* Load from bytes */ ad[ 0] = (((sword32)((a[ 0] ) >> 0)) << 0) @@ -6201,61 +6263,112 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) o = rd[12] >> 28; rd[13] += o; rd[12] = rd[12] & 0xfffffff; o = rd[13] >> 28; rd[14] += o; rd[13] = rd[13] & 0xfffffff; o = rd[14] >> 28; rd[15] += o; rd[14] = rd[14] & 0xfffffff; + /* Reduce to mod order. */ + u = 0; + u += (sword32)(rd[0] - (sword32)0x0b5844f3L); u >>= 28; + u += (sword32)(rd[1] - (sword32)0x078c292aL); u >>= 28; + u += (sword32)(rd[2] - (sword32)0x058f5523L); u >>= 28; + u += (sword32)(rd[3] - (sword32)0x0c2728dcL); u >>= 28; + u += (sword32)(rd[4] - (sword32)0x0690216cL); u >>= 28; + u += (sword32)(rd[5] - (sword32)0x049aed63L); u >>= 28; + u += (sword32)(rd[6] - (sword32)0x09c44edbL); u >>= 28; + u += (sword32)(rd[7] - (sword32)0x07cca23eL); u >>= 28; + u += (sword32)(rd[8] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[9] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[10] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[11] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[12] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[13] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[14] - (sword32)0x0fffffffL); u >>= 28; + u += (sword32)(rd[15] - (sword32)0x03ffffffL); u >>= 28; + o = (word32)0 - (u >= 0); + u = 0; + u += (sword32)(rd[0] - ((word32)0x0b5844f3L & o)); rd[0] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[1] - ((word32)0x078c292aL & o)); rd[1] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[2] - ((word32)0x058f5523L & o)); rd[2] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[3] - ((word32)0x0c2728dcL & o)); rd[3] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[4] - ((word32)0x0690216cL & o)); rd[4] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[5] - ((word32)0x049aed63L & o)); rd[5] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[6] - ((word32)0x09c44edbL & o)); rd[6] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[7] - ((word32)0x07cca23eL & o)); rd[7] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[8] - ((word32)0x0fffffffL & o)); rd[8] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[9] - ((word32)0x0fffffffL & o)); rd[9] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[10] - ((word32)0x0fffffffL & o)); rd[10] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[11] - ((word32)0x0fffffffL & o)); rd[11] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[12] - ((word32)0x0fffffffL & o)); rd[12] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[13] - ((word32)0x0fffffffL & o)); rd[13] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[14] - ((word32)0x0fffffffL & o)); rd[14] = u & 0xfffffff; + u >>= 28; + u += (sword32)(rd[15] - ((word32)0x03ffffffL & o)); rd[15] = u & 0xfffffff; /* Convert to bytes */ r[ 0] = (byte)(rd[0 ] >> 0); r[ 1] = (byte)(rd[0 ] >> 8); r[ 2] = (byte)(rd[0 ] >> 16); - r[ 3] = (byte)((rd[0 ] >> 24) + ((rd[1 ] >> 0) << 4)); + r[ 3] = (byte)(rd[0 ] >> 24) + (byte)((rd[1 ] >> 0) << 4); r[ 4] = (byte)(rd[1 ] >> 4); r[ 5] = (byte)(rd[1 ] >> 12); r[ 6] = (byte)(rd[1 ] >> 20); r[ 7] = (byte)(rd[2 ] >> 0); r[ 8] = (byte)(rd[2 ] >> 8); r[ 9] = (byte)(rd[2 ] >> 16); - r[10] = (byte)((rd[2 ] >> 24) + ((rd[3 ] >> 0) << 4)); + r[10] = (byte)(rd[2 ] >> 24) + (byte)((rd[3 ] >> 0) << 4); r[11] = (byte)(rd[3 ] >> 4); r[12] = (byte)(rd[3 ] >> 12); r[13] = (byte)(rd[3 ] >> 20); r[14] = (byte)(rd[4 ] >> 0); r[15] = (byte)(rd[4 ] >> 8); r[16] = (byte)(rd[4 ] >> 16); - r[17] = (byte)((rd[4 ] >> 24) + ((rd[5 ] >> 0) << 4)); + r[17] = (byte)(rd[4 ] >> 24) + (byte)((rd[5 ] >> 0) << 4); r[18] = (byte)(rd[5 ] >> 4); r[19] = (byte)(rd[5 ] >> 12); r[20] = (byte)(rd[5 ] >> 20); r[21] = (byte)(rd[6 ] >> 0); r[22] = (byte)(rd[6 ] >> 8); r[23] = (byte)(rd[6 ] >> 16); - r[24] = (byte)((rd[6 ] >> 24) + ((rd[7 ] >> 0) << 4)); + r[24] = (byte)(rd[6 ] >> 24) + (byte)((rd[7 ] >> 0) << 4); r[25] = (byte)(rd[7 ] >> 4); r[26] = (byte)(rd[7 ] >> 12); r[27] = (byte)(rd[7 ] >> 20); r[28] = (byte)(rd[8 ] >> 0); r[29] = (byte)(rd[8 ] >> 8); r[30] = (byte)(rd[8 ] >> 16); - r[31] = (byte)((rd[8 ] >> 24) + ((rd[9 ] >> 0) << 4)); + r[31] = (byte)(rd[8 ] >> 24) + (byte)((rd[9 ] >> 0) << 4); r[32] = (byte)(rd[9 ] >> 4); r[33] = (byte)(rd[9 ] >> 12); r[34] = (byte)(rd[9 ] >> 20); r[35] = (byte)(rd[10] >> 0); r[36] = (byte)(rd[10] >> 8); r[37] = (byte)(rd[10] >> 16); - r[38] = (byte)((rd[10] >> 24) + ((rd[11] >> 0) << 4)); + r[38] = (byte)(rd[10] >> 24) + (byte)((rd[11] >> 0) << 4); r[39] = (byte)(rd[11] >> 4); r[40] = (byte)(rd[11] >> 12); r[41] = (byte)(rd[11] >> 20); r[42] = (byte)(rd[12] >> 0); r[43] = (byte)(rd[12] >> 8); r[44] = (byte)(rd[12] >> 16); - r[45] = (byte)((rd[12] >> 24) + ((rd[13] >> 0) << 4)); + r[45] = (byte)(rd[12] >> 24) + (byte)((rd[13] >> 0) << 4); r[46] = (byte)(rd[13] >> 4); r[47] = (byte)(rd[13] >> 12); r[48] = (byte)(rd[13] >> 20); r[49] = (byte)(rd[14] >> 0); r[50] = (byte)(rd[14] >> 8); r[51] = (byte)(rd[14] >> 16); - r[52] = (byte)((rd[14] >> 24) + ((rd[15] >> 0) << 4)); + r[52] = (byte)(rd[14] >> 24) + (byte)((rd[15] >> 0) << 4); r[53] = (byte)(rd[15] >> 4); r[54] = (byte)(rd[15] >> 12); r[55] = (byte)(rd[15] >> 20); @@ -10456,7 +10569,7 @@ void ge448_to_bytes(byte *b, const ge448_p2 *p) fe448_mul(x, p->X, recip); fe448_mul(y, p->Y, recip); fe448_to_bytes(b, y); - b[56] = (byte)fe448_isnegative(x) << 7; + b[56] = (byte)((byte)fe448_isnegative(x) << 7); } /* Convert point to byte array assuming z is 1. @@ -10467,7 +10580,7 @@ void ge448_to_bytes(byte *b, const ge448_p2 *p) static void ge448_p2z1_to_bytes(byte *b, const ge448_p2 *p) { fe448_to_bytes(b, p->Y); - b[56] = (byte)fe448_isnegative(p->X) << 7; + b[56] = (byte)((byte)fe448_isnegative(p->X) << 7); } /* Compress the point to y-ordinate and negative bit. @@ -10589,20 +10702,20 @@ int ge448_scalarmult_base(ge448_p2* r, const byte* a) carry = 0; for (i = 0; i < 56; ++i) { - e[2 * i + 0] = ((a[i] >> 0) & 0xf) + carry; - carry = e[2 * i + 0] + 8; + e[2 * i + 0] = (byte)(((a[i] >> 0) & 0xf) + carry); + carry = (byte)(e[2 * i + 0] + 8); carry >>= 4; - e[2 * i + 0] -= (byte)(carry << 4); + e[2 * i + 0] = (byte)(e[2 * i + 0] - (byte)(carry << 4)); - e[2 * i + 1] = ((a[i] >> 4) & 0xf) + carry; - carry = e[2 * i + 1] + 8; - carry >>= 4; - e[2 * i + 1] -= (byte)(carry << 4); + e[2 * i + 1] = (byte)(((a[i] >> 4) & 0xf) + carry); + carry = (byte)(e[2 * i + 1] + 8); + carry = (byte)(carry >> 4); + e[2 * i + 1] = (byte)(e[2 * i + 1] - (carry << 4)); } e[112] = carry; /* each e[i] is between -8 and 8 */ - /* Odd indeces first - sum based on even index so multiply by 16 */ + /* Odd indices first - sum based on even index so multiply by 16 */ ge448_select(t, 0, e[1]); fe448_copy(r->X, t->x); fe448_copy(r->Y, t->y); @@ -10617,7 +10730,7 @@ int ge448_scalarmult_base(ge448_p2* r, const byte* a) ge448_dbl(r, r); ge448_dbl(r, r); - /* Add even indeces */ + /* Add even indices */ for (i = 0; i <= 112; i += 2) { ge448_select(t, i / 2, e[i]); ge448_madd(r, r, t); @@ -10633,7 +10746,7 @@ int ge448_scalarmult_base(ge448_p2* r, const byte* a) /* Create to a sliding window for the scalar multiplicaton. * - * r [in] Array of indeces. + * r [in] Array of indices. * a [in] Scalar to break up. */ static void slide(sword8 *r, const byte *a) @@ -10657,11 +10770,11 @@ static void slide(sword8 *r, const byte *a) } if (r[i] + (r[i + b] << b) <= 31) { - r[i] += (sword8)(r[i + b] << b); + r[i] = (sword8)(r[i] + (r[i + b] << b)); r[i + b] = 0; } else if (r[i] - (r[i + b] << b) >= -31) { - r[i] -= (sword8)(r[i + b] << b); + r[i] = (sword8)(r[i] - (r[i + b] << b)); for (k = i + b; k < 448; ++k) { if (!r[k]) { r[k] = 1; diff --git a/src/wolfcrypt/src/ge_low_mem.c b/src/wolfcrypt/src/ge_low_mem.c index df747a1..cb505af 100644 --- a/src/wolfcrypt/src/ge_low_mem.c +++ b/src/wolfcrypt/src/ge_low_mem.c @@ -512,6 +512,33 @@ int ge_frombytes_negate_vartime(ge_p3 *p,const unsigned char *s) return ret; } +#ifdef WOLFSSL_CHECK_VER_FAULTS +/* return 0 if equal and -1 if not equal */ +static int ge_equal(ge a, ge b) +{ + if (XMEMCMP(a, b, sizeof(ge)) == 0) { + return 0; + } + else { + return -1; + } +} + +/* returns 0 if a == b */ +static int ge_p3_equal(ge_p3* a, ge_p3* b) +{ + int ret = 0; + + ret |= ge_equal(a->X, b->X); + ret |= ge_equal(a->Y, b->Y); + ret |= ge_equal(a->Z, b->Z); + ret |= ge_equal(a->T, b->T); + + return ret; +} +#endif + + int ge_double_scalarmult_vartime(ge_p2* R, const unsigned char *h, const ge_p3 *inA,const unsigned char *sig) @@ -526,9 +553,19 @@ int ge_double_scalarmult_vartime(ge_p2* R, const unsigned char *h, /* find H(R,A,M) * -A */ ed25519_smult(&A, &A, h); +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (ge_p3_equal(&A, (ge_p3*)inA) == 0) { + ret = BAD_STATE_E; + } +#endif /* SB + -H(R,A,M)A */ ed25519_add(&A, &p, &A); +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (ge_p3_equal(&A, &p) == 0) { + ret = BAD_STATE_E; + } +#endif lm_copy(R->X, A.X); lm_copy(R->Y, A.Y); diff --git a/src/wolfcrypt/src/ge_operations.c b/src/wolfcrypt/src/ge_operations.c index bcf9d35..4a50d46 100644 --- a/src/wolfcrypt/src/ge_operations.c +++ b/src/wolfcrypt/src/ge_operations.c @@ -9125,12 +9125,12 @@ void ge_scalarmult_base(ge_p3 *h,const unsigned char *a) carry = 0; for (i = 0;i < 63;++i) { - e[i] += carry; - carry = e[i] + 8; - carry >>= 4; - e[i] -= (signed char)(carry << 4); + e[i] = (signed char)(e[i] + carry); + carry = (signed char)(e[i] + 8); + carry = (signed char)(carry >> 4); + e[i] = (signed char)(e[i] - (carry << 4)); } - e[63] += carry; + e[63] = (signed char)(e[63] + carry); /* each e[i] is between -8 and 8 */ #ifndef CURVED25519_ASM @@ -9190,9 +9190,10 @@ static void slide(signed char *r,const unsigned char *a) for (b = 1;b <= 6 && i + b < SLIDE_SIZE;++b) { if (r[i + b]) { if (r[i] + (r[i + b] << b) <= 15) { - r[i] += (signed char)(r[i + b] << b); r[i + b] = 0; + r[i] = (signed char)(r[i] + (r[i + b] << b)); + r[i + b] = 0; } else if (r[i] - (r[i + b] << b) >= -15) { - r[i] -= (signed char)(r[i + b] << b); + r[i] = (signed char)(r[i] - (r[i + b] << b)); for (k = i + b;k < SLIDE_SIZE;++k) { if (!r[k]) { r[k] = 1; @@ -9467,6 +9468,13 @@ int ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, ge_p1p1_to_p2(r,t); } +#ifdef WOLFSSL_CHECK_VER_FAULTS + if (i != -1) { + /* did not go through whole loop */ + return BAD_STATE_E; + } +#endif + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) out: diff --git a/src/wolfcrypt/src/hash.c b/src/wolfcrypt/src/hash.c index b16c47d..4850a84 100644 --- a/src/wolfcrypt/src/hash.c +++ b/src/wolfcrypt/src/hash.c @@ -322,12 +322,12 @@ int wc_HashGetDigestSize(enum wc_HashType hash_type) { case WC_HASH_TYPE_MD2: #ifdef WOLFSSL_MD2 - dig_size = MD2_DIGEST_SIZE; + dig_size = WC_MD2_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - dig_size = MD4_DIGEST_SIZE; + dig_size = WC_MD4_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_MD5: @@ -441,12 +441,12 @@ int wc_HashGetBlockSize(enum wc_HashType hash_type) { case WC_HASH_TYPE_MD2: #ifdef WOLFSSL_MD2 - block_size = MD2_BLOCK_SIZE; + block_size = WC_MD2_BLOCK_SIZE; #endif break; case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - block_size = MD4_BLOCK_SIZE; + block_size = WC_MD4_BLOCK_SIZE; #endif break; case WC_HASH_TYPE_MD5: diff --git a/src/wolfcrypt/src/hmac.c b/src/wolfcrypt/src/hmac.c index 47f8f13..65dbf66 100644 --- a/src/wolfcrypt/src/hmac.c +++ b/src/wolfcrypt/src/hmac.c @@ -24,6 +24,7 @@ #include #endif +#include #include #include #include @@ -266,6 +267,7 @@ int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, return BAD_FUNC_ARG; } + heap = hmac->heap; #if !defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0) /* if set key has already been run then make sure and free existing */ /* This is for async and PIC32MZ situations, and just normally OK, @@ -273,7 +275,13 @@ int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, available in FIPS builds. In current FIPS builds, the hashes are not allocating resources. */ if (hmac->macType != WC_HASH_TYPE_NONE) { + #ifdef WOLF_CRYPTO_CB + int devId = hmac->devId; + #endif wc_HmacFree(hmac); + #ifdef WOLF_CRYPTO_CB + hmac->devId = devId; + #endif } #endif diff --git a/src/wolfcrypt/src/hpke.c b/src/wolfcrypt/src/hpke.c index 450ee73..02e189b 100644 --- a/src/wolfcrypt/src/hpke.c +++ b/src/wolfcrypt/src/hpke.c @@ -256,13 +256,13 @@ int wc_HpkeInit(Hpke* hpke, int kem, int kdf, int aead, void* heap) case HPKE_AES_128_GCM: hpke->Nk = AES_128_KEY_SIZE; hpke->Nn = GCM_NONCE_MID_SZ; - hpke->Nt = AES_BLOCK_SIZE; + hpke->Nt = WC_AES_BLOCK_SIZE; break; case HPKE_AES_256_GCM: hpke->Nk = AES_256_KEY_SIZE; hpke->Nn = GCM_NONCE_MID_SZ; - hpke->Nt = AES_BLOCK_SIZE; + hpke->Nt = WC_AES_BLOCK_SIZE; break; default: diff --git a/src/wolfcrypt/src/kdf.c b/src/wolfcrypt/src/kdf.c index 1bb338e..c45c635 100644 --- a/src/wolfcrypt/src/kdf.c +++ b/src/wolfcrypt/src/kdf.c @@ -24,6 +24,7 @@ #include #endif +#include #include #include #include @@ -941,11 +942,11 @@ static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx, } else { /* XOR in as bit shifted index. */ - block[WC_SRTP_MAX_SALT - indexSz] ^= index[0] >> bits; + block[WC_SRTP_MAX_SALT - indexSz] ^= (byte)(index[0] >> bits); for (i = 1; i < indexSz; i++) { block[i + WC_SRTP_MAX_SALT - indexSz] ^= - (index[i-1] << (8 - bits)) | - (index[i+0] >> bits ); + (byte)((index[i-1] << (8 - bits)) | + (index[i+0] >> bits )); } } } @@ -968,7 +969,7 @@ static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, int i; int ret = 0; /* Calculate the number of full blocks needed for derived key. */ - int blocks = (int)(keySz / AES_BLOCK_SIZE); + int blocks = (int)(keySz / WC_AES_BLOCK_SIZE); /* XOR in label. */ block[WC_SRTP_MAX_SALT - indexSz - 1] ^= label; @@ -976,19 +977,19 @@ static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, /* Set counter. */ block[15] = (byte)i; /* Encrypt block into key buffer. */ - ret = wc_AesEcbEncrypt(aes, key, block, AES_BLOCK_SIZE); + ret = wc_AesEcbEncrypt(aes, key, block, WC_AES_BLOCK_SIZE); /* Reposition for more derived key. */ - key += AES_BLOCK_SIZE; + key += WC_AES_BLOCK_SIZE; /* Reduce the count of key bytes required. */ - keySz -= AES_BLOCK_SIZE; + keySz -= WC_AES_BLOCK_SIZE; } /* Do any partial blocks. */ if ((ret == 0) && (keySz > 0)) { - byte enc[AES_BLOCK_SIZE]; + byte enc[WC_AES_BLOCK_SIZE]; /* Set counter. */ block[15] = (byte)i; /* Encrypt block into temporary. */ - ret = wc_AesEcbEncrypt(aes, enc, block, AES_BLOCK_SIZE); + ret = wc_AesEcbEncrypt(aes, enc, block, WC_AES_BLOCK_SIZE); if (ret == 0) { /* Copy into key required amount. */ XMEMCPY(key, enc, keySz); @@ -1029,7 +1030,7 @@ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, word32 key2Sz, byte* key3, word32 key3Sz) { int ret = 0; - byte block[AES_BLOCK_SIZE]; + byte block[WC_AES_BLOCK_SIZE]; #ifdef WOLFSSL_SMALL_STACK Aes* aes = NULL; #else @@ -1124,7 +1125,7 @@ int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 salt word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator) { int ret = 0; - byte block[AES_BLOCK_SIZE]; + byte block[WC_AES_BLOCK_SIZE]; #ifdef WOLFSSL_SMALL_STACK Aes* aes = NULL; #else @@ -1233,7 +1234,7 @@ int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, word32 outKeySz) { int ret = 0; - byte block[AES_BLOCK_SIZE]; + byte block[WC_AES_BLOCK_SIZE]; #ifdef WOLFSSL_SMALL_STACK Aes* aes = NULL; #else @@ -1316,7 +1317,7 @@ int wc_SRTCP_KDF_label(const byte* key, word32 keySz, const byte* salt, word32 outKeySz) { int ret = 0; - byte block[AES_BLOCK_SIZE]; + byte block[WC_AES_BLOCK_SIZE]; #ifdef WOLFSSL_SMALL_STACK Aes* aes = NULL; #else diff --git a/src/wolfcrypt/src/md2.c b/src/wolfcrypt/src/md2.c index c28a049..07ad963 100644 --- a/src/wolfcrypt/src/md2.c +++ b/src/wolfcrypt/src/md2.c @@ -40,16 +40,16 @@ #endif -void wc_InitMd2(Md2* md2) +void wc_InitMd2(wc_Md2* md2) { - XMEMSET(md2->X, 0, MD2_X_SIZE); - XMEMSET(md2->C, 0, MD2_BLOCK_SIZE); - XMEMSET(md2->buffer, 0, MD2_BLOCK_SIZE); + XMEMSET(md2->X, 0, WC_MD2_X_SIZE); + XMEMSET(md2->C, 0, WC_MD2_BLOCK_SIZE); + XMEMSET(md2->buffer, 0, WC_MD2_BLOCK_SIZE); md2->count = 0; } -void wc_Md2Update(Md2* md2, const byte* data, word32 len) +void wc_Md2Update(wc_Md2* md2, const byte* data, word32 len) { static const byte S[256] = { @@ -74,30 +74,30 @@ void wc_Md2Update(Md2* md2, const byte* data, word32 len) }; while (len) { - word32 L = (MD2_PAD_SIZE - md2->count) < len ? - (MD2_PAD_SIZE - md2->count) : len; + word32 L = (WC_MD2_PAD_SIZE - md2->count) < len ? + (WC_MD2_PAD_SIZE - md2->count) : len; XMEMCPY(md2->buffer + md2->count, data, L); md2->count += L; data += L; len -= L; - if (md2->count == MD2_PAD_SIZE) { + if (md2->count == WC_MD2_PAD_SIZE) { int i; byte t; md2->count = 0; - XMEMCPY(md2->X + MD2_PAD_SIZE, md2->buffer, MD2_PAD_SIZE); + XMEMCPY(md2->X + WC_MD2_PAD_SIZE, md2->buffer, WC_MD2_PAD_SIZE); t = md2->C[15]; - for(i = 0; i < MD2_PAD_SIZE; i++) { - md2->X[32 + i] = md2->X[MD2_PAD_SIZE + i] ^ md2->X[i]; + for(i = 0; i < WC_MD2_PAD_SIZE; i++) { + md2->X[32 + i] = md2->X[WC_MD2_PAD_SIZE + i] ^ md2->X[i]; t = md2->C[i] ^= S[md2->buffer[i] ^ t]; } t=0; for(i = 0; i < 18; i++) { int j; - for(j = 0; j < MD2_X_SIZE; j += 8) { + for(j = 0; j < WC_MD2_X_SIZE; j += 8) { t = md2->X[j+0] ^= S[t]; t = md2->X[j+1] ^= S[t]; t = md2->X[j+2] ^= S[t]; @@ -114,19 +114,19 @@ void wc_Md2Update(Md2* md2, const byte* data, word32 len) } -void wc_Md2Final(Md2* md2, byte* hash) +void wc_Md2Final(wc_Md2* md2, byte* hash) { - byte padding[MD2_BLOCK_SIZE]; - word32 padLen = MD2_PAD_SIZE - md2->count; + byte padding[WC_MD2_BLOCK_SIZE]; + word32 padLen = WC_MD2_PAD_SIZE - md2->count; word32 i; for (i = 0; i < padLen; i++) padding[i] = (byte)padLen; wc_Md2Update(md2, padding, padLen); /* cppcheck-suppress uninitvar */ - wc_Md2Update(md2, md2->C, MD2_BLOCK_SIZE); + wc_Md2Update(md2, md2->C, WC_MD2_BLOCK_SIZE); - XMEMCPY(hash, md2->X, MD2_DIGEST_SIZE); + XMEMCPY(hash, md2->X, WC_MD2_DIGEST_SIZE); wc_InitMd2(md2); } @@ -135,13 +135,13 @@ void wc_Md2Final(Md2* md2, byte* hash) int wc_Md2Hash(const byte* data, word32 len, byte* hash) { #ifdef WOLFSSL_SMALL_STACK - Md2* md2; + wc_Md2* md2; #else - Md2 md2[1]; + wc_Md2 md2[1]; #endif #ifdef WOLFSSL_SMALL_STACK - md2 = (Md2*)XMALLOC(sizeof(Md2), NULL, DYNAMIC_TYPE_TMP_BUFFER); + md2 = (wc_Md2*)XMALLOC(sizeof(wc_Md2), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (md2 == NULL) return MEMORY_E; #endif diff --git a/src/wolfcrypt/src/md4.c b/src/wolfcrypt/src/md4.c index 65b4dc2..592a0a3 100644 --- a/src/wolfcrypt/src/md4.c +++ b/src/wolfcrypt/src/md4.c @@ -37,7 +37,7 @@ #endif -void wc_InitMd4(Md4* md4) +void wc_InitMd4(wc_Md4* md4) { md4->digest[0] = 0x67452301L; md4->digest[1] = 0xefcdab89L; @@ -50,7 +50,7 @@ void wc_InitMd4(Md4* md4) } -static void Transform(Md4* md4) +static void Transform(wc_Md4* md4) { #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) @@ -130,7 +130,7 @@ static void Transform(Md4* md4) } -static WC_INLINE void AddLength(Md4* md4, word32 len) +static WC_INLINE void AddLength(wc_Md4* md4, word32 len) { word32 tmp = md4->loLen; if ( (md4->loLen += len) < tmp) @@ -138,32 +138,32 @@ static WC_INLINE void AddLength(Md4* md4, word32 len) } -void wc_Md4Update(Md4* md4, const byte* data, word32 len) +void wc_Md4Update(wc_Md4* md4, const byte* data, word32 len) { /* do block size increments */ byte* local = (byte*)md4->buffer; while (len) { - word32 add = min(len, MD4_BLOCK_SIZE - md4->buffLen); + word32 add = min(len, WC_MD4_BLOCK_SIZE - md4->buffLen); XMEMCPY(&local[md4->buffLen], data, add); md4->buffLen += add; data += add; len -= add; - if (md4->buffLen == MD4_BLOCK_SIZE) { + if (md4->buffLen == WC_MD4_BLOCK_SIZE) { #ifdef BIG_ENDIAN_ORDER - ByteReverseWords(md4->buffer, md4->buffer, MD4_BLOCK_SIZE); + ByteReverseWords(md4->buffer, md4->buffer, WC_MD4_BLOCK_SIZE); #endif Transform(md4); - AddLength(md4, MD4_BLOCK_SIZE); + AddLength(md4, WC_MD4_BLOCK_SIZE); md4->buffLen = 0; } } } -void wc_Md4Final(Md4* md4, byte* hash) +void wc_Md4Final(wc_Md4* md4, byte* hash) { byte* local = (byte*)md4->buffer; @@ -172,17 +172,17 @@ void wc_Md4Final(Md4* md4, byte* hash) local[md4->buffLen++] = 0x80; /* add 1 */ /* pad with zeros */ - if (md4->buffLen > MD4_PAD_SIZE) { - XMEMSET(&local[md4->buffLen], 0, MD4_BLOCK_SIZE - md4->buffLen); - md4->buffLen += MD4_BLOCK_SIZE - md4->buffLen; + if (md4->buffLen > WC_MD4_PAD_SIZE) { + XMEMSET(&local[md4->buffLen], 0, WC_MD4_BLOCK_SIZE - md4->buffLen); + md4->buffLen += WC_MD4_BLOCK_SIZE - md4->buffLen; #ifdef BIG_ENDIAN_ORDER - ByteReverseWords(md4->buffer, md4->buffer, MD4_BLOCK_SIZE); + ByteReverseWords(md4->buffer, md4->buffer, WC_MD4_BLOCK_SIZE); #endif Transform(md4); md4->buffLen = 0; } - XMEMSET(&local[md4->buffLen], 0, MD4_PAD_SIZE - md4->buffLen); + XMEMSET(&local[md4->buffLen], 0, WC_MD4_PAD_SIZE - md4->buffLen); /* put lengths in bits */ md4->hiLen = (md4->loLen >> (8*sizeof(md4->loLen) - 3)) + @@ -191,17 +191,17 @@ void wc_Md4Final(Md4* md4, byte* hash) /* store lengths */ #ifdef BIG_ENDIAN_ORDER - ByteReverseWords(md4->buffer, md4->buffer, MD4_BLOCK_SIZE); + ByteReverseWords(md4->buffer, md4->buffer, WC_MD4_BLOCK_SIZE); #endif /* ! length ordering dependent on digest endian type ! */ - XMEMCPY(&local[MD4_PAD_SIZE], &md4->loLen, sizeof(word32)); - XMEMCPY(&local[MD4_PAD_SIZE + sizeof(word32)], &md4->hiLen, sizeof(word32)); + XMEMCPY(&local[WC_MD4_PAD_SIZE], &md4->loLen, sizeof(word32)); + XMEMCPY(&local[WC_MD4_PAD_SIZE + sizeof(word32)], &md4->hiLen, sizeof(word32)); Transform(md4); #ifdef BIG_ENDIAN_ORDER - ByteReverseWords(md4->digest, md4->digest, MD4_DIGEST_SIZE); + ByteReverseWords(md4->digest, md4->digest, WC_MD4_DIGEST_SIZE); #endif - XMEMCPY(hash, md4->digest, MD4_DIGEST_SIZE); + XMEMCPY(hash, md4->digest, WC_MD4_DIGEST_SIZE); wc_InitMd4(md4); /* reset state */ } diff --git a/src/wolfcrypt/src/md5.c b/src/wolfcrypt/src/md5.c index f6ca240..557de7c 100644 --- a/src/wolfcrypt/src/md5.c +++ b/src/wolfcrypt/src/md5.c @@ -48,7 +48,7 @@ /* Hardware Acceleration */ -#if defined(STM32_HASH) +#if defined(STM32_HASH) && !defined(STM32_NOMD5) /* Supports CubeMX HAL or Standard Peripheral Library */ #define HAVE_MD5_CUST_API diff --git a/src/wolfcrypt/src/memory.c b/src/wolfcrypt/src/memory.c index 75d0389..4fd648a 100644 --- a/src/wolfcrypt/src/memory.c +++ b/src/wolfcrypt/src/memory.c @@ -69,9 +69,9 @@ Possible memory options: void *z_realloc(void *ptr, size_t size) { if (ptr == NULL) - ptr = malloc(size); + ptr = malloc(size); /* native heap */ else - ptr = realloc(ptr, size); + ptr = realloc(ptr, size); /* native heap */ return ptr; } @@ -360,7 +360,7 @@ void* wolfSSL_Malloc(size_t size) } #endif - res = malloc(size); + res = malloc(size); /* native heap */ #else WOLFSSL_MSG("No malloc available"); #endif @@ -401,7 +401,7 @@ void* wolfSSL_Malloc(size_t size) #endif } else { - free(res); /* clear */ + free(res); /* native heap */ } gMemFailCount = gMemFailCountSeed; /* reset */ return NULL; @@ -445,7 +445,7 @@ void wolfSSL_Free(void *ptr) } else { #ifndef WOLFSSL_NO_MALLOC - free(ptr); + free(ptr); /* native heap */ #else WOLFSSL_MSG("No free available"); #endif @@ -503,7 +503,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size) } else { #ifndef WOLFSSL_NO_MALLOC - res = realloc(ptr, size); + res = realloc(ptr, size); /* native heap */ #else WOLFSSL_MSG("No realloc available"); #endif @@ -669,7 +669,7 @@ static int wc_partition_static_memory(byte* buffer, word32 sz, int flag, } static int wc_init_memory_heap(WOLFSSL_HEAP* heap, unsigned int listSz, - const unsigned int* sizeList, const unsigned int* distList) + const word32 *sizeList, const word32 *distList) { unsigned int i; @@ -695,8 +695,8 @@ static int wc_init_memory_heap(WOLFSSL_HEAP* heap, unsigned int listSz, } int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint, - unsigned int listSz, const unsigned int* sizeList, - const unsigned int* distList, unsigned char* buf, + unsigned int listSz, const word32 *sizeList, + const word32 *distList, unsigned char *buf, unsigned int sz, int flag, int maxSz) { WOLFSSL_HEAP* heap = NULL; @@ -773,13 +773,8 @@ int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint, int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint, unsigned char* buf, unsigned int sz, int flag, int maxSz) { -#ifdef WOLFSSL_LEAN_STATIC_PSK - word16 sizeList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS }; - byte distList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST }; -#else word32 sizeList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS }; word32 distList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST }; -#endif int ret = 0; WOLFSSL_ENTER("wc_LoadStaticMemory"); @@ -817,7 +812,7 @@ int wolfSSL_MemoryPaddingSz(void) /* Used to calculate memory size for optimum use with buckets. returns the suggested size rounded down to the nearest bucket. */ int wolfSSL_StaticBufferSz_ex(unsigned int listSz, - const unsigned int *sizeList, const unsigned int *distList, + const word32 *sizeList, const word32 *distList, byte* buffer, word32 sz, int flag) { word32 ava = sz; @@ -1002,7 +997,7 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) /* check for testing heap hint was set */ #ifdef WOLFSSL_HEAP_TEST if (heap == (void*)WOLFSSL_HEAP_TEST) { - return malloc(size); + return malloc(size); /* native heap */ } #endif @@ -1013,7 +1008,7 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD || type == DYNAMIC_TYPE_CERT_MANAGER) { WOLFSSL_MSG("ERROR allowing null heap hint for ctx/method"); - res = malloc(size); + res = malloc(size); /* native heap */ } else { WOLFSSL_MSG("ERROR null heap hint passed into XMALLOC"); @@ -1022,15 +1017,16 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) #else #ifndef WOLFSSL_NO_MALLOC #ifdef FREERTOS - res = pvPortMalloc(size); + res = pvPortMalloc(size); /* native heap */ #elif defined(WOLFSSL_EMBOS) res = OS_HEAP_malloc(size); #else - res = malloc(size); + res = malloc(size); /* native heap */ #endif #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Alloc: %p -> %u at %s:%d\n", res, (word32)size, func, line); + fprintf(stderr, "[HEAP %p] Alloc: %p -> %u at %s:%d\n", heap, + res, (word32)size, func, line); #endif #else WOLFSSL_MSG("No heap hint found to use and no malloc"); @@ -1097,8 +1093,8 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) } #ifdef WOLFSSL_DEBUG_STATIC_MEMORY else { - fprintf(stderr, "Size: %lu, Empty: %d\n", (unsigned long) size, - mem->sizeList[i]); + fprintf(stderr, "Size: %lu, Empty: %d\n", + (unsigned long) size, mem->sizeList[i]); } #endif } @@ -1114,7 +1110,8 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) #ifdef WOLFSSL_DEBUG_MEMORY pt->szUsed = size; - fprintf(stderr, "Alloc: %p -> %lu at %s:%d\n", pt->buffer, size, func, line); + fprintf(stderr, "[HEAP %p] Alloc: %p -> %lu at %s:%d\n", heap, + pt->buffer, size, func, line); #endif #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK if (DebugCb) { @@ -1143,8 +1140,8 @@ void* wolfSSL_Malloc(size_t size, void* heap, int type) WOLFSSL_MSG("ERROR ran out of static memory"); res = NULL; #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Looking for %lu bytes at %s:%d\n", (unsigned long) size, func, - line); + fprintf(stderr, "Looking for %lu bytes at %s:%d\n", + (unsigned long) size, func, line); #endif #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK if (DebugCb) { @@ -1187,9 +1184,10 @@ void wolfSSL_Free(void *ptr, void* heap, int type) #ifdef WOLFSSL_HEAP_TEST if (heap == (void*)WOLFSSL_HEAP_TEST) { #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Free: %p at %s:%d\n", pt, func, line); + fprintf(stderr, "[HEAP %p] Free: %p at %s:%d\n", heap, pt, func, + line); #endif - return free(ptr); + return free(ptr); /* native heap */ } #endif @@ -1205,15 +1203,16 @@ void wolfSSL_Free(void *ptr, void* heap, int type) } #endif #ifndef WOLFSSL_NO_MALLOC + #ifdef WOLFSSL_DEBUG_MEMORY + fprintf(stderr, "[HEAP %p] Free: %p at %s:%d\n", heap, pt, func, + line); + #endif #ifdef FREERTOS - vPortFree(ptr); + vPortFree(ptr); /* native heap */ #elif defined(WOLFSSL_EMBOS) - OS_HEAP_free(ptr); + OS_HEAP_free(ptr); /* native heap */ #else - free(ptr); - #endif - #ifdef WOLFSSL_DEBUG_MEMORY - fprintf(stderr, "Free: %p at %s:%d\n", ptr, func, line); + free(ptr); /* native heap */ #endif #else WOLFSSL_MSG("Error trying to call free when turned off"); @@ -1286,8 +1285,8 @@ void wolfSSL_Free(void *ptr, void* heap, int type) #endif #ifdef WOLFSSL_DEBUG_MEMORY - fprintf (stderr, "Free: %p -> %u at %s:%d\n", pt->buffer, - pt->szUsed, func, line); + fprintf(stderr, "[HEAP %p] Free: %p -> %u at %s:%d\n", heap, + pt->buffer, pt->szUsed, func, line); #endif #ifndef WOLFSSL_STATIC_MEMORY_LEAN @@ -1335,7 +1334,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) /* check for testing heap hint was set */ #ifdef WOLFSSL_HEAP_TEST if (heap == (void*)WOLFSSL_HEAP_TEST) { - return realloc(ptr, size); + return realloc(ptr, size); /* native heap */ } #endif @@ -1344,7 +1343,7 @@ void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type) WOLFSSL_MSG("ERROR null heap hint passed in to XREALLOC"); #endif #ifndef WOLFSSL_NO_MALLOC - res = realloc(ptr, size); + res = realloc(ptr, size); /* native heap */ #else WOLFSSL_MSG("NO heap found to use for realloc"); #endif /* WOLFSSL_NO_MALLOC */ @@ -1493,7 +1492,7 @@ void* XMALLOC(size_t n, void* heap, int type) return NULL; } - return malloc(n); + return malloc(n); /* native heap */ } void* XREALLOC(void *p, size_t n, void* heap, int type) @@ -1514,7 +1513,7 @@ void* XREALLOC(void *p, size_t n, void* heap, int type) return NULL; } - return realloc(p, n); + return realloc(p, n); /* native heap */ } void XFREE(void *p, void* heap, int type) @@ -1527,7 +1526,7 @@ void XFREE(void *p, void* heap, int type) if (type == DYNAMIC_TYPE_OUT_BUFFER) return; /* do nothing, static pool */ - free(p); + free(p); /* native heap */ } #endif /* HAVE_IO_POOL */ @@ -1554,7 +1553,7 @@ void *xmalloc(size_t n, void* heap, int type, const char* func, #endif } else - p32 = malloc(n + sizeof(word32) * 4); + p32 = malloc(n + sizeof(word32) * 4); /* native heap */ if (p32 != NULL) { p32[0] = (word32)n; @@ -1597,7 +1596,7 @@ void *xrealloc(void *p, size_t n, void* heap, int type, const char* func, #endif } else - p32 = realloc(oldp32, n + sizeof(word32) * 4); + p32 = realloc(oldp32, n + sizeof(word32) * 4); /* native heap */ if (p32 != NULL) { p32[0] = (word32)n; @@ -1643,7 +1642,7 @@ void xfree(void *p, void* heap, int type, const char* func, const char* file, #endif } else - free(p32); + free(p32); /* native heap */ } (void)heap; diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index e4b53d9..c37e2dc 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -115,23 +115,19 @@ masking and clearing memory logic. #endif -#ifdef WC_RC2 - /* This routine performs a left circular arithmetic shift of by value */ WC_MISC_STATIC WC_INLINE word16 rotlFixed16(word16 x, word16 y) { - return (x << y) | (x >> (sizeof(x) * 8 - y)); + return (word16)((x << y) | (x >> (sizeof(x) * 8U - y))); } /* This routine performs a right circular arithmetic shift of by value */ WC_MISC_STATIC WC_INLINE word16 rotrFixed16(word16 x, word16 y) { - return (x >> y) | (x << (sizeof(x) * 8 - y)); + return (word16)((x >> y) | (x << (sizeof(x) * 8U - y))); } -#endif /* WC_RC2 */ - /* This routine performs a byte swap of 32-bit word value. */ #if defined(__CCRX__) && !defined(NO_INLINE) /* shortest version for CC-RX */ #define ByteReverseWord32(value) _builtin_revl(value) @@ -200,7 +196,7 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in, byteCount &= ~0x3U; - for (i = 0; i < byteCount; i += sizeof(word32)) { + for (i = 0; i < byteCount; i += (word32)sizeof(word32)) { XMEMCPY(&scratch, in_bytes + i, sizeof(scratch)); scratch = ByteReverseWord32(scratch); XMEMCPY(out_bytes + i, &scratch, sizeof(scratch)); @@ -209,6 +205,53 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in, #endif } +WC_MISC_STATIC WC_INLINE word32 readUnalignedWord32(const byte *in) +{ + if (((wc_ptr_t)in & (wc_ptr_t)(sizeof(word32) - 1U)) == (wc_ptr_t)0) + return *(word32 *)in; + else { + word32 out = 0; /* else CONFIG_FORTIFY_SOURCE -Wmaybe-uninitialized */ + XMEMCPY(&out, in, sizeof(out)); + return out; + } +} + +WC_MISC_STATIC WC_INLINE word32 writeUnalignedWord32(void *out, word32 in) +{ + if (((wc_ptr_t)out & (wc_ptr_t)(sizeof(word32) - 1U)) == (wc_ptr_t)0) + *(word32 *)out = in; + else { + XMEMCPY(out, &in, sizeof(in)); + } + return in; +} + +WC_MISC_STATIC WC_INLINE void readUnalignedWords32(word32 *out, const byte *in, + size_t count) +{ + if (((wc_ptr_t)in & (wc_ptr_t)(sizeof(word32) - 1U)) == (wc_ptr_t)0) { + const word32 *in_word32 = (const word32 *)in; + while (count-- > 0) + *out++ = *in_word32++; + } + else { + XMEMCPY(out, in, count * sizeof(*out)); + } +} + +WC_MISC_STATIC WC_INLINE void writeUnalignedWords32(byte *out, const word32 *in, + size_t count) +{ + if (((wc_ptr_t)out & (wc_ptr_t)(sizeof(word32) - 1U)) == (wc_ptr_t)0) { + word32 *out_word32 = (word32 *)out; + while (count-- > 0) + *out_word32++ = *in++; + } + else { + XMEMCPY(out, in, count * sizeof(*in)); + } +} + #if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_NO_WORD64_OPS) WC_MISC_STATIC WC_INLINE word64 readUnalignedWord64(const byte *in) @@ -216,8 +259,8 @@ WC_MISC_STATIC WC_INLINE word64 readUnalignedWord64(const byte *in) if (((wc_ptr_t)in & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) return *(word64 *)in; else { - word64 out; - XMEMCPY(&out, in, sizeof(word64)); + word64 out = 0; /* else CONFIG_FORTIFY_SOURCE -Wmaybe-uninitialized */ + XMEMCPY(&out, in, sizeof(out)); return out; } } @@ -227,7 +270,7 @@ WC_MISC_STATIC WC_INLINE word64 writeUnalignedWord64(void *out, word64 in) if (((wc_ptr_t)out & (wc_ptr_t)(sizeof(word64) - 1U)) == (wc_ptr_t)0) *(word64 *)out = in; else { - XMEMCPY(out, &in, sizeof(word64)); + XMEMCPY(out, &in, sizeof(in)); } return in; } @@ -241,7 +284,7 @@ WC_MISC_STATIC WC_INLINE void readUnalignedWords64(word64 *out, const byte *in, *out++ = *in_word64++; } else { - XMEMCPY(out, in, count * sizeof(word64)); + XMEMCPY(out, in, count * sizeof(*out)); } } @@ -254,7 +297,7 @@ WC_MISC_STATIC WC_INLINE void writeUnalignedWords64(byte *out, const word64 *in, *out_word64++ = *in++; } else { - XMEMCPY(out, in, count * sizeof(word64)); + XMEMCPY(out, in, count * sizeof(*in)); } } @@ -576,11 +619,11 @@ WC_MISC_STATIC WC_INLINE signed char HexCharToByte(char ch) { signed char ret = (signed char)ch; if (ret >= '0' && ret <= '9') - ret -= '0'; + ret = (signed char)(ret - '0'); else if (ret >= 'A' && ret <= 'F') - ret -= 'A' - 10; + ret = (signed char)(ret - ('A' - 10)); else if (ret >= 'a' && ret <= 'f') - ret -= 'a' - 10; + ret = (signed char)(ret - ('a' - 10)); else ret = -1; /* error case - return code must be signed */ return ret; diff --git a/src/wolfcrypt/src/pkcs12.c b/src/wolfcrypt/src/pkcs12.c index e8cc11e..07ff1ad 100644 --- a/src/wolfcrypt/src/pkcs12.c +++ b/src/wolfcrypt/src/pkcs12.c @@ -978,7 +978,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) totalSz += 4; /* Element */ - totalSz += 2 + sizeof(WC_PKCS12_DATA_OID); + totalSz += 2U + (word32)sizeof(WC_PKCS12_DATA_OID); totalSz += 4; /* Seq */ @@ -1037,7 +1037,7 @@ int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz) /* OID */ idx += (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), &buf[idx]); XMEMCPY(&buf[idx], WC_PKCS12_DATA_OID, sizeof(WC_PKCS12_DATA_OID)); - idx += sizeof(WC_PKCS12_DATA_OID); + idx += (word32)sizeof(WC_PKCS12_DATA_OID); /* Element */ buf[idx++] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC; @@ -2080,12 +2080,12 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, /* calculate size */ totalSz = (word32)SetObjectId(sizeof(WC_PKCS12_ENCRYPTED_OID), seq); - totalSz += sizeof(WC_PKCS12_ENCRYPTED_OID); + totalSz += (word32)sizeof(WC_PKCS12_ENCRYPTED_OID); totalSz += ASN_TAG_SZ; length = (word32)SetMyVersion(0, seq, 0); tmpSz = (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); - tmpSz += sizeof(WC_PKCS12_DATA_OID); + tmpSz += (word32)sizeof(WC_PKCS12_DATA_OID); tmpSz += encSz; length += SetSequence(tmpSz, seq) + tmpSz; outerSz = SetSequence(length, seq) + length; @@ -2108,7 +2108,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, } XMEMCPY(out + idx, WC_PKCS12_ENCRYPTED_OID, sizeof(WC_PKCS12_ENCRYPTED_OID)); - idx += sizeof(WC_PKCS12_ENCRYPTED_OID); + idx += (word32)sizeof(WC_PKCS12_ENCRYPTED_OID); if (idx + 1 > *outSz){ return BUFFER_E; @@ -2149,7 +2149,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, return BUFFER_E; } XMEMCPY(out + idx, WC_PKCS12_DATA_OID, sizeof(WC_PKCS12_DATA_OID)); - idx += sizeof(WC_PKCS12_DATA_OID); + idx += (word32)sizeof(WC_PKCS12_DATA_OID); /* copy over encrypted data */ if (idx + encSz > *outSz){ @@ -2171,7 +2171,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, if (type == WC_PKCS12_DATA) { /* calculate size */ totalSz = (word32)SetObjectId(sizeof(WC_PKCS12_DATA_OID), seq); - totalSz += sizeof(WC_PKCS12_DATA_OID); + totalSz += (word32)sizeof(WC_PKCS12_DATA_OID); totalSz += ASN_TAG_SZ; length = SetOctetString(contentSz, seq); @@ -2197,7 +2197,7 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, return BUFFER_E; } XMEMCPY(out + idx, WC_PKCS12_DATA_OID, sizeof(WC_PKCS12_DATA_OID)); - idx += sizeof(WC_PKCS12_DATA_OID); + idx += (word32)sizeof(WC_PKCS12_DATA_OID); if (idx + 1 > *outSz){ return BUFFER_E; diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index bb37054..a96f537 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -128,7 +128,7 @@ struct PKCS7State { /* creates a PKCS7State structure and returns 0 on success */ -static int wc_PKCS7_CreateStream(PKCS7* pkcs7) +static int wc_PKCS7_CreateStream(wc_PKCS7* pkcs7) { WOLFSSL_MSG("creating PKCS7 stream structure"); pkcs7->stream = (PKCS7State*)XMALLOC(sizeof(PKCS7State), pkcs7->heap, @@ -144,7 +144,7 @@ static int wc_PKCS7_CreateStream(PKCS7* pkcs7) } -static void wc_PKCS7_ResetStream(PKCS7* pkcs7) +static void wc_PKCS7_ResetStream(wc_PKCS7* pkcs7) { if (pkcs7 != NULL && pkcs7->stream != NULL) { #ifdef WC_PKCS7_STREAM_DEBUG @@ -211,7 +211,7 @@ static void wc_PKCS7_ResetStream(PKCS7* pkcs7) } -static void wc_PKCS7_FreeStream(PKCS7* pkcs7) +static void wc_PKCS7_FreeStream(wc_PKCS7* pkcs7) { if (pkcs7 != NULL && pkcs7->stream != NULL) { wc_PKCS7_ResetStream(pkcs7); @@ -228,7 +228,7 @@ static void wc_PKCS7_FreeStream(PKCS7* pkcs7) /* used to increase the max size for internal buffer * returns 0 on success */ -static int wc_PKCS7_GrowStream(PKCS7* pkcs7, word32 newSz) +static int wc_PKCS7_GrowStream(wc_PKCS7* pkcs7, word32 newSz) { byte* pt; pt = (byte*)XMALLOC(newSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -257,7 +257,7 @@ static int wc_PKCS7_GrowStream(PKCS7* pkcs7, word32 newSz) * Sets idx to be the current offset into "pt" buffer * returns 0 on success */ -static int wc_PKCS7_AddDataToStream(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_AddDataToStream(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32 expected, byte** pt, word32* idx) { word32 rdSz = pkcs7->stream->idx; @@ -335,7 +335,7 @@ static int wc_PKCS7_AddDataToStream(PKCS7* pkcs7, byte* in, word32 inSz, /* setter function for stored variables */ -static void wc_PKCS7_StreamStoreVar(PKCS7* pkcs7, word32 var1, int var2, +static void wc_PKCS7_StreamStoreVar(wc_PKCS7* pkcs7, word32 var1, int var2, int var3) { if (pkcs7 != NULL && pkcs7->stream != NULL) { @@ -348,7 +348,7 @@ static void wc_PKCS7_StreamStoreVar(PKCS7* pkcs7, word32 var1, int var2, /* Tries to peek at the SEQ and get the length * returns 0 on success */ -static int wc_PKCS7_SetMaxStream(PKCS7* pkcs7, byte* in, word32 defSz) +static int wc_PKCS7_SetMaxStream(wc_PKCS7* pkcs7, byte* in, word32 defSz) { /* check there is a buffer to read from */ if (pkcs7) { @@ -397,7 +397,7 @@ static int wc_PKCS7_SetMaxStream(PKCS7* pkcs7, byte* in, word32 defSz) /* getter function for stored variables */ -static void wc_PKCS7_StreamGetVar(PKCS7* pkcs7, word32* var1, int* var2, +static void wc_PKCS7_StreamGetVar(wc_PKCS7* pkcs7, word32* var1, int* var2, int* var3) { if (pkcs7 != NULL && pkcs7->stream != NULL) { @@ -410,7 +410,7 @@ static void wc_PKCS7_StreamGetVar(PKCS7* pkcs7, word32* var1, int* var2, /* common update of index and total read after section complete * returns 0 on success */ -static int wc_PKCS7_StreamEndCase(PKCS7* pkcs7, word32* tmpIdx, word32* idx) +static int wc_PKCS7_StreamEndCase(wc_PKCS7* pkcs7, word32* tmpIdx, word32* idx) { int ret = 0; @@ -497,7 +497,7 @@ static const char* wc_PKCS7_GetStateName(int in) /* Used to change the PKCS7 state. Having state change as a function allows * for easier debugging */ -static void wc_PKCS7_ChangeState(PKCS7* pkcs7, int newState) +static void wc_PKCS7_ChangeState(wc_PKCS7* pkcs7, int newState) { #ifdef WC_PKCS7_STREAM_DEBUG printf("\tChanging from state [%02d] %s to [%02d] %s\n", @@ -695,7 +695,7 @@ static int wc_PKCS7_GetOIDBlockSize(int oid) case AES256CCMb: #endif #endif - blockSz = AES_BLOCK_SIZE; + blockSz = WC_AES_BLOCK_SIZE; break; #endif /* !NO_AES */ @@ -782,11 +782,11 @@ static int wc_PKCS7_GetOIDKeySize(int oid) } -PKCS7* wc_PKCS7_New(void* heap, int devId) +wc_PKCS7* wc_PKCS7_New(void* heap, int devId) { - PKCS7* pkcs7 = (PKCS7*)XMALLOC(sizeof(PKCS7), heap, DYNAMIC_TYPE_PKCS7); + wc_PKCS7* pkcs7 = (wc_PKCS7*)XMALLOC(sizeof(wc_PKCS7), heap, DYNAMIC_TYPE_PKCS7); if (pkcs7) { - XMEMSET(pkcs7, 0, sizeof(PKCS7)); + XMEMSET(pkcs7, 0, sizeof(wc_PKCS7)); if (wc_PKCS7_Init(pkcs7, heap, devId) == 0) { pkcs7->isDynamic = 1; } @@ -807,7 +807,7 @@ PKCS7* wc_PKCS7_New(void* heap, int devId) * * returns 0 on success or a negative value for failure */ -int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId) +int wc_PKCS7_Init(wc_PKCS7* pkcs7, void* heap, int devId) { word16 isDynamic; @@ -818,7 +818,7 @@ int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId) } isDynamic = pkcs7->isDynamic; - XMEMSET(pkcs7, 0, sizeof(PKCS7)); + XMEMSET(pkcs7, 0, sizeof(wc_PKCS7)); pkcs7->isDynamic = (isDynamic != 0); #ifdef WOLFSSL_HEAP_TEST pkcs7->heap = (void*)WOLFSSL_HEAP_TEST; @@ -831,7 +831,7 @@ int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId) } #ifdef WC_ASN_UNKNOWN_EXT_CB -void wc_PKCS7_SetUnknownExtCallback(PKCS7* pkcs7, wc_UnknownExtCallback cb) +void wc_PKCS7_SetUnknownExtCallback(wc_PKCS7* pkcs7, wc_UnknownExtCallback cb) { if (pkcs7 != NULL) { pkcs7->unknownExtCallback = cb; @@ -860,7 +860,7 @@ struct Pkcs7EncodedRecip { /* free all members of Pkcs7Cert linked list */ -static void wc_PKCS7_FreeCertSet(PKCS7* pkcs7) +static void wc_PKCS7_FreeCertSet(wc_PKCS7* pkcs7) { Pkcs7Cert* curr = NULL; Pkcs7Cert* next = NULL; @@ -885,7 +885,7 @@ static void wc_PKCS7_FreeCertSet(PKCS7* pkcs7) /* Get total size of all recipients in recipient list. * * Returns total size of recipients, or negative upon error */ -static int wc_PKCS7_GetRecipientListSize(PKCS7* pkcs7) +static int wc_PKCS7_GetRecipientListSize(wc_PKCS7* pkcs7) { word32 totalSz = 0; Pkcs7EncodedRecip* tmp = NULL; @@ -905,7 +905,7 @@ static int wc_PKCS7_GetRecipientListSize(PKCS7* pkcs7) /* free all members of Pkcs7EncodedRecip linked list */ -static void wc_PKCS7_FreeEncodedRecipientSet(PKCS7* pkcs7) +static void wc_PKCS7_FreeEncodedRecipientSet(wc_PKCS7* pkcs7) { Pkcs7EncodedRecip* curr = NULL; Pkcs7EncodedRecip* next = NULL; @@ -930,7 +930,7 @@ static void wc_PKCS7_FreeEncodedRecipientSet(PKCS7* pkcs7) /* search through RecipientInfo list for specific type. * return 1 if ANY recipient of type specified is present, otherwise * return 0 */ -static int wc_PKCS7_RecipientListIncludesType(PKCS7* pkcs7, int type) +static int wc_PKCS7_RecipientListIncludesType(wc_PKCS7* pkcs7, int type) { Pkcs7EncodedRecip* tmp = NULL; @@ -952,7 +952,7 @@ static int wc_PKCS7_RecipientListIncludesType(PKCS7* pkcs7, int type) /* searches through RecipientInfo list, returns 1 if all structure * versions are set to 0, otherwise returns 0 */ -static int wc_PKCS7_RecipientListVersionsAllZero(PKCS7* pkcs7) +static int wc_PKCS7_RecipientListVersionsAllZero(wc_PKCS7* pkcs7) { Pkcs7EncodedRecip* tmp = NULL; @@ -979,7 +979,7 @@ static int wc_PKCS7_RecipientListVersionsAllZero(PKCS7* pkcs7) * keySz - size of key, octets * * Returns 0 on success, negative on error */ -static int wc_PKCS7_CheckPublicKeyDer(PKCS7* pkcs7, int keyOID, +static int wc_PKCS7_CheckPublicKeyDer(wc_PKCS7* pkcs7, int keyOID, const byte* key, word32 keySz) { int ret = 0; @@ -1075,7 +1075,7 @@ static int wc_PKCS7_CheckPublicKeyDer(PKCS7* pkcs7, int keyOID, /* Init PKCS7 struct with recipient cert, decode into DecodedCert * NOTE: keeps previously set pkcs7 heap hint, devId and isDynamic */ -int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) +int wc_PKCS7_InitWithCert(wc_PKCS7* pkcs7, byte* derCert, word32 derCertSz) { int ret = 0; void* heap; @@ -1226,7 +1226,7 @@ int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* derCert, word32 derCertSz) * This API does not currently validate certificates. * * Returns 0 on success, negative upon error */ -int wc_PKCS7_AddCertificate(PKCS7* pkcs7, byte* derCert, word32 derCertSz) +int wc_PKCS7_AddCertificate(wc_PKCS7* pkcs7, byte* derCert, word32 derCertSz) { Pkcs7Cert* cert; @@ -1276,7 +1276,7 @@ static void wc_PKCS7_FreeDecodedAttrib(PKCS7DecodedAttrib* attrib, void* heap) /* return 0 on success */ -static int wc_PKCS7_SignerInfoNew(PKCS7* pkcs7) +static int wc_PKCS7_SignerInfoNew(wc_PKCS7* pkcs7) { XFREE(pkcs7->signerInfo, pkcs7->heap, DYNAMIC_TYPE_PKCS7); pkcs7->signerInfo = NULL; @@ -1292,7 +1292,7 @@ static int wc_PKCS7_SignerInfoNew(PKCS7* pkcs7) } -static void wc_PKCS7_SignerInfoFree(PKCS7* pkcs7) +static void wc_PKCS7_SignerInfoFree(wc_PKCS7* pkcs7) { if (pkcs7->signerInfo != NULL) { XFREE(pkcs7->signerInfo->sid, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -1306,7 +1306,7 @@ static void wc_PKCS7_SignerInfoFree(PKCS7* pkcs7) /* free's any current SID and sets it to "in" * returns 0 on success */ -static int wc_PKCS7_SignerInfoSetSID(PKCS7* pkcs7, byte* in, int inSz) +static int wc_PKCS7_SignerInfoSetSID(wc_PKCS7* pkcs7, byte* in, int inSz) { if (pkcs7 == NULL || in == NULL || inSz < 0) { return BAD_FUNC_ARG; @@ -1326,7 +1326,7 @@ static int wc_PKCS7_SignerInfoSetSID(PKCS7* pkcs7, byte* in, int inSz) /* releases any memory allocated by a PKCS7 initializer */ -void wc_PKCS7_Free(PKCS7* pkcs7) +void wc_PKCS7_Free(wc_PKCS7* pkcs7) { if (pkcs7 == NULL) return; @@ -1391,7 +1391,7 @@ void wc_PKCS7_Free(PKCS7* pkcs7) /* helper function for parsing through attributes and finding a specific one. * returns PKCS7DecodedAttrib pointer on success */ -static PKCS7DecodedAttrib* findAttrib(PKCS7* pkcs7, const byte* oid, word32 oidSz) +static PKCS7DecodedAttrib* findAttrib(wc_PKCS7* pkcs7, const byte* oid, word32 oidSz) { PKCS7DecodedAttrib* list; @@ -1446,7 +1446,7 @@ static PKCS7DecodedAttrib* findAttrib(PKCS7* pkcs7, const byte* oid, word32 oidS * * returns size of value on success */ -int wc_PKCS7_GetAttributeValue(PKCS7* pkcs7, const byte* oid, word32 oidSz, +int wc_PKCS7_GetAttributeValue(wc_PKCS7* pkcs7, const byte* oid, word32 oidSz, byte* out, word32* outSz) { PKCS7DecodedAttrib* attrib; @@ -1475,7 +1475,7 @@ int wc_PKCS7_GetAttributeValue(PKCS7* pkcs7, const byte* oid, word32 oidSz, /* build PKCS#7 data content type */ -int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { static const byte oid[] = { ASN_OBJECT_ID, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, @@ -1615,7 +1615,7 @@ static FlatAttrib* NewAttrib(void* heap) } /* Free FlatAttrib array and memory allocated to internal struct members */ -static void FreeAttribArray(PKCS7* pkcs7, FlatAttrib** arr, int rows) +static void FreeAttribArray(wc_PKCS7* pkcs7, FlatAttrib** arr, int rows) { int i; @@ -1675,7 +1675,7 @@ static int SortAttribArray(FlatAttrib** arr, int rows) /* Build up array of FlatAttrib structs from EncodedAttrib ones. FlatAttrib * holds flattened DER encoding of each attribute */ -static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, +static int FlattenEncodedAttribs(wc_PKCS7* pkcs7, FlatAttrib** derArr, int rows, EncodedAttrib* ea, int eaSz) { int i; @@ -1720,7 +1720,7 @@ static int FlattenEncodedAttribs(PKCS7* pkcs7, FlatAttrib** derArr, int rows, /* Sort and Flatten EncodedAttrib attributes into output buffer */ -static int FlattenAttributes(PKCS7* pkcs7, byte* output, EncodedAttrib* ea, +static int FlattenAttributes(wc_PKCS7* pkcs7, byte* output, EncodedAttrib* ea, int eaSz) { int i, ret; @@ -1779,7 +1779,7 @@ static int FlattenAttributes(PKCS7* pkcs7, byte* output, EncodedAttrib* ea, #ifndef NO_RSA -static int wc_PKCS7_ImportRSA(PKCS7* pkcs7, RsaKey* privKey) +static int wc_PKCS7_ImportRSA(wc_PKCS7* pkcs7, RsaKey* privKey) { int ret; word32 idx; @@ -1822,7 +1822,7 @@ static int wc_PKCS7_ImportRSA(PKCS7* pkcs7, RsaKey* privKey) /* returns size of signature put into out, negative on error */ -static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +static int wc_PKCS7_RsaSign(wc_PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) { int ret; #ifdef WOLFSSL_SMALL_STACK @@ -1873,7 +1873,7 @@ static int wc_PKCS7_RsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) #ifdef HAVE_ECC -static int wc_PKCS7_ImportECC(PKCS7* pkcs7, ecc_key* privKey) +static int wc_PKCS7_ImportECC(wc_PKCS7* pkcs7, ecc_key* privKey) { int ret; word32 idx; @@ -1912,7 +1912,7 @@ static int wc_PKCS7_ImportECC(PKCS7* pkcs7, ecc_key* privKey) /* returns size of signature put into out, negative on error */ -static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) +static int wc_PKCS7_EcdsaSign(wc_PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) { int ret; word32 outSz; @@ -1964,7 +1964,7 @@ static int wc_PKCS7_EcdsaSign(PKCS7* pkcs7, byte* in, word32 inSz, ESD* esd) #endif /* HAVE_ECC */ /* returns encContentDigestSz based on the signature set to be used */ -static int wc_PKCS7_GetSignSize(PKCS7* pkcs7) +static int wc_PKCS7_GetSignSize(wc_PKCS7* pkcs7) { int ret = 0; @@ -2031,7 +2031,7 @@ static int wc_PKCS7_GetSignSize(PKCS7* pkcs7) * esd - pointer to initialized ESD structure, used for output * * return 0 on success, negative on error */ -static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, +static int wc_PKCS7_BuildSignedAttributes(wc_PKCS7* pkcs7, ESD* esd, const byte* contentType, word32 contentTypeSz, const byte* contentTypeOid, word32 contentTypeOidSz, const byte* messageDigestOid, word32 messageDigestOidSz, @@ -2138,7 +2138,7 @@ static int wc_PKCS7_BuildSignedAttributes(PKCS7* pkcs7, ESD* esd, * digEncAlgoType - [OUT] output for algo ID type * * return 0 on success, negative on error */ -static int wc_PKCS7_SignedDataGetEncAlgoId(PKCS7* pkcs7, int* digEncAlgoId, +static int wc_PKCS7_SignedDataGetEncAlgoId(wc_PKCS7* pkcs7, int* digEncAlgoId, int* digEncAlgoType) { int algoId = 0; @@ -2281,7 +2281,7 @@ static int wc_PKCS7_SignedDataGetEncAlgoId(PKCS7* pkcs7, int* digEncAlgoId, * digestInfoSz - [IN/OUT] - input size of array, size of digestInfo * * return 0 on success, negative on error */ -static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, +static int wc_PKCS7_BuildDigestInfo(wc_PKCS7* pkcs7, byte* flatSignedAttribs, word32 flatSignedAttribsSz, ESD* esd, byte* digestInfo, word32* digestInfoSz) { @@ -2367,7 +2367,7 @@ static int wc_PKCS7_BuildDigestInfo(PKCS7* pkcs7, byte* flatSignedAttribs, * esd - pointer to initialized ESD struct * * returns length of signature on success, negative on error */ -static int wc_PKCS7_SignedDataBuildSignature(PKCS7* pkcs7, +static int wc_PKCS7_SignedDataBuildSignature(wc_PKCS7* pkcs7, byte* flatSignedAttribs, word32 flatSignedAttribsSz, ESD* esd) @@ -2487,7 +2487,7 @@ static int wc_PKCS7_SignedDataBuildSignature(PKCS7* pkcs7, * @param esd Pointer to an ESD structure for digest calculation. * @return Returns 0 on success, and a negative value on failure. */ -static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, +static int wc_PKCS7_EncodeContentStreamHelper(wc_PKCS7* pkcs7, int cipherType, Aes* aes, byte* encContentOut, byte* contentData, int contentDataSz, byte* out, word32* outIdx, ESD* esd) { @@ -2553,10 +2553,10 @@ static int wc_PKCS7_EncodeContentStreamHelper(PKCS7* pkcs7, int cipherType, * * Returns 0 on success */ #ifndef NO_AES -static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, Aes* aes, +static int wc_PKCS7_EncodeContentStream(wc_PKCS7* pkcs7, ESD* esd, Aes* aes, byte* in, int inSz, byte* out, int cipherType) #else -static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, +static int wc_PKCS7_EncodeContentStream(wc_PKCS7* pkcs7, ESD* esd, void* aes, byte* in, int inSz, byte* out, int cipherType) #endif { @@ -2749,7 +2749,7 @@ static int wc_PKCS7_EncodeContentStream(PKCS7* pkcs7, ESD* esd, void* aes, /* build PKCS#7 signedData content type */ /* To get the output size then set output = 0 and *outputSz = 0 */ -static int PKCS7_EncodeSigned(PKCS7* pkcs7, +static int PKCS7_EncodeSigned(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* output, word32* outputSz, byte* output2, word32* output2Sz) { @@ -3413,7 +3413,7 @@ static int PKCS7_EncodeSigned(PKCS7* pkcs7, * pkcs7->contentSz: Must be provided as actual sign of raw data * return codes: 0=success, negative=error */ -int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, +int wc_PKCS7_EncodeSignedData_ex(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* outputHead, word32* outputHeadSz, byte* outputFoot, word32* outputFootSz) { @@ -3443,7 +3443,7 @@ int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, /* Sets a custom SKID in PKCS7 struct, used before calling an encode operation * Returns 0 on success, negative upon error. */ -int wc_PKCS7_SetCustomSKID(PKCS7* pkcs7, const byte* in, word16 inSz) +int wc_PKCS7_SetCustomSKID(wc_PKCS7* pkcs7, const byte* in, word16 inSz) { int ret = 0; @@ -3487,7 +3487,7 @@ int wc_PKCS7_SetCustomSKID(PKCS7* pkcs7, const byte* in, word16 inSz) * flag - turn on/off detached signature generation (1 or 0) * * Returns 0 on success, negative upon error. */ -int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag) +int wc_PKCS7_SetDetached(wc_PKCS7* pkcs7, word16 flag) { if (pkcs7 == NULL || (flag != 0 && flag != 1)) return BAD_FUNC_ARG; @@ -3508,7 +3508,7 @@ int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag) * pkcs7 - pointer to initialized PKCS7 structure * * Returns 0 on success, negative upon error. */ -int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7) +int wc_PKCS7_NoDefaultSignedAttribs(wc_PKCS7* pkcs7) { return wc_PKCS7_SetDefaultSignedAttribs(pkcs7, WOLFSSL_NO_ATTRIBUTES); } @@ -3525,7 +3525,7 @@ int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7) * pkcs7 - pointer to initialized PKCS7 structure * * Returns 0 on success, negative upon error. */ -int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag) +int wc_PKCS7_SetDefaultSignedAttribs(wc_PKCS7* pkcs7, word16 flag) { if (pkcs7 == NULL) { return BAD_FUNC_ARG; @@ -3554,7 +3554,7 @@ int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag) /* return codes: >0: Size of signed PKCS7 output buffer, negative: error */ -int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeSignedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { int ret; @@ -3623,7 +3623,7 @@ int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) * outputSz - size of output buffer, octets * * Returns length of generated bundle on success, negative upon error. */ -int wc_PKCS7_EncodeSignedFPD(PKCS7* pkcs7, byte* privateKey, +int wc_PKCS7_EncodeSignedFPD(wc_PKCS7* pkcs7, byte* privateKey, word32 privateKeySz, int signOID, int hashOID, byte* content, word32 contentSz, PKCS7Attrib* signedAttribs, word32 signedAttribsSz, @@ -3692,7 +3692,7 @@ int wc_PKCS7_EncodeSignedFPD(PKCS7* pkcs7, byte* privateKey, * outputSz - size of output buffer, octets * * Returns length of generated bundle on success, negative upon error. */ -int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, +int wc_PKCS7_EncodeSignedEncryptedFPD(wc_PKCS7* pkcs7, byte* encryptKey, word32 encryptKeySz, byte* privateKey, word32 privateKeySz, int encryptOID, int signOID, int hashOID, @@ -3800,7 +3800,7 @@ int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, byte* encryptKey, * outputSz - size of output buffer, octets * * Returns length of generated bundle on success, negative upon error. */ -int wc_PKCS7_EncodeSignedCompressedFPD(PKCS7* pkcs7, byte* privateKey, +int wc_PKCS7_EncodeSignedCompressedFPD(wc_PKCS7* pkcs7, byte* privateKey, word32 privateKeySz, int signOID, int hashOID, byte* content, word32 contentSz, @@ -3904,7 +3904,7 @@ int wc_PKCS7_EncodeSignedCompressedFPD(PKCS7* pkcs7, byte* privateKey, * outputSz - size of output buffer, octets * * Returns length of generated bundle on success, negative upon error. */ -int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(PKCS7* pkcs7, byte* encryptKey, +int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(wc_PKCS7* pkcs7, byte* encryptKey, word32 encryptKeySz, byte* privateKey, word32 privateKeySz, int encryptOID, int signOID, int hashOID, byte* content, @@ -4018,7 +4018,7 @@ int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(PKCS7* pkcs7, byte* encryptKey, #ifdef HAVE_PKCS7_RSA_RAW_SIGN_CALLBACK /* register raw RSA sign digest callback */ -int wc_PKCS7_SetRsaSignRawDigestCb(PKCS7* pkcs7, CallbackRsaSignRawDigest cb) +int wc_PKCS7_SetRsaSignRawDigestCb(wc_PKCS7* pkcs7, CallbackRsaSignRawDigest cb) { if (pkcs7 == NULL || cb == NULL) { return BAD_FUNC_ARG; @@ -4031,7 +4031,7 @@ int wc_PKCS7_SetRsaSignRawDigestCb(PKCS7* pkcs7, CallbackRsaSignRawDigest cb) #endif /* returns size of signature put into out, negative on error */ -static int wc_PKCS7_RsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, +static int wc_PKCS7_RsaVerify(wc_PKCS7* pkcs7, byte* sig, int sigSz, byte* hash, word32 hashSz) { int ret = 0, i; @@ -4163,7 +4163,7 @@ static int wc_PKCS7_RsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, #ifdef HAVE_ECC /* returns size of signature put into out, negative on error */ -static int wc_PKCS7_EcdsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, +static int wc_PKCS7_EcdsaVerify(wc_PKCS7* pkcs7, byte* sig, int sigSz, byte* hash, word32 hashSz) { int ret = 0, i; @@ -4302,7 +4302,7 @@ static int wc_PKCS7_EcdsaVerify(PKCS7* pkcs7, byte* sig, int sigSz, * plainDigestSz - [OUT] size of digest at plainDigest * * returns 0 on success, negative on error */ -static int wc_PKCS7_BuildSignedDataDigest(PKCS7* pkcs7, byte* signedAttrib, +static int wc_PKCS7_BuildSignedDataDigest(wc_PKCS7* pkcs7, byte* signedAttrib, word32 signedAttribSz, byte* pkcs7Digest, word32* pkcs7DigestSz, byte** plainDigest, word32* plainDigestSz, @@ -4441,7 +4441,7 @@ static int wc_PKCS7_BuildSignedDataDigest(PKCS7* pkcs7, byte* signedAttrib, * hashBufSz - size of hashBuf, octets * * return 0 on success, negative on error */ -static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, +static int wc_PKCS7_VerifyContentMessageDigest(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz) { @@ -4586,7 +4586,7 @@ static int wc_PKCS7_VerifyContentMessageDigest(PKCS7* pkcs7, * signedAttribSz - size of signedAttributes * * return 0 on success, negative on error */ -static int wc_PKCS7_SignedDataVerifySignature(PKCS7* pkcs7, byte* sig, +static int wc_PKCS7_SignedDataVerifySignature(wc_PKCS7* pkcs7, byte* sig, word32 sigSz, byte* signedAttrib, word32 signedAttribSz, const byte* hashBuf, word32 hashSz) @@ -4742,7 +4742,7 @@ static int wc_PKCS7_SignedDataVerifySignature(PKCS7* pkcs7, byte* sig, /* set correct public key OID based on signature OID, stores in * pkcs7->publicKeyOID and returns same value */ -static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) +static int wc_PKCS7_SetPublicKeyOID(wc_PKCS7* pkcs7, int sigOID) { if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -4830,7 +4830,7 @@ static int wc_PKCS7_SetPublicKeyOID(PKCS7* pkcs7, int sigOID) * * returns the number of attributes parsed on success */ -static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) +static int wc_PKCS7_ParseAttribs(wc_PKCS7* pkcs7, byte* in, int inSz) { int found = 0; word32 idx = 0; @@ -4914,7 +4914,7 @@ static int wc_PKCS7_ParseAttribs(PKCS7* pkcs7, byte* in, int inSz) * * by default support for SignedData degenerate cases is on */ -void wc_PKCS7_AllowDegenerate(PKCS7* pkcs7, word16 flag) +void wc_PKCS7_AllowDegenerate(wc_PKCS7* pkcs7, word16 flag) { if (pkcs7) { if (flag) { /* flag of 1 turns on support for degenerate */ @@ -4936,7 +4936,7 @@ void wc_PKCS7_AllowDegenerate(PKCS7* pkcs7, word16 flag) * * returns 0 on success */ -static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_ParseSignerInfo(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idxIn, int degenerate, byte** signedAttrib, int* signedAttribSz) { int ret = 0; @@ -5110,10 +5110,10 @@ static int wc_PKCS7_ParseSignerInfo(PKCS7* pkcs7, byte* in, word32 inSz, * pkcs7->stream->content and stores its size in pkcs7->stream->contentSz. */ #ifndef NO_PKCS7_STREAM -static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_HandleOctetStrings(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* tmpIdx, word32* idx, int keepContent) { - int ret, length; + int ret, length = 0; word32 msgSz, i, contBufSz; byte tag; byte* msg = NULL; @@ -5341,11 +5341,11 @@ static int wc_PKCS7_HandleOctetStrings(PKCS7* pkcs7, byte* in, word32 inSz, * When adding support for the case of SignedAndEnvelopedData content types a * signer is required. In this case the PKCS7 flag noDegenerate could be set. */ -static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, +static int PKCS7_VerifySignedData(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* in, word32 inSz, byte* in2, word32 in2Sz) { - word32 idx, maxIdx = inSz, outerContentType, contentTypeSz = 0, totalSz = 0; + word32 idx, maxIdx = inSz, outerContentType = 0, contentTypeSz = 0, totalSz = 0; int length = 0, version = 0, ret = 0; byte* content = NULL; byte* contentDynamic = NULL; @@ -6630,7 +6630,7 @@ static int PKCS7_VerifySignedData(PKCS7* pkcs7, const byte* hashBuf, * return 0 on success and LENGTH_ONLY_E if just setting "outSz" for buffer * length needed. */ -int wc_PKCS7_GetSignerSID(PKCS7* pkcs7, byte* out, word32* outSz) +int wc_PKCS7_GetSignerSID(wc_PKCS7* pkcs7, byte* out, word32* outSz) { if (outSz == NULL || pkcs7 == NULL) { return BAD_FUNC_ARG; @@ -6683,7 +6683,7 @@ int wc_PKCS7_GetSignerSID(PKCS7* pkcs7, byte* out, word32* outSz) * Returns 0 on success, negative upon error. * */ -int wc_PKCS7_VerifySignedData_ex(PKCS7* pkcs7, const byte* hashBuf, +int wc_PKCS7_VerifySignedData_ex(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* pkiMsgHead, word32 pkiMsgHeadSz, byte* pkiMsgFoot, word32 pkiMsgFootSz) { @@ -6691,7 +6691,7 @@ int wc_PKCS7_VerifySignedData_ex(PKCS7* pkcs7, const byte* hashBuf, pkiMsgHead, pkiMsgHeadSz, pkiMsgFoot, pkiMsgFootSz); } -int wc_PKCS7_VerifySignedData(PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz) +int wc_PKCS7_VerifySignedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz) { return PKCS7_VerifySignedData(pkcs7, NULL, 0, pkiMsg, pkiMsgSz, NULL, 0); } @@ -6704,7 +6704,7 @@ int wc_PKCS7_VerifySignedData(PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz) * len - length of key to be generated * * Returns 0 on success, negative upon error */ -static int PKCS7_GenerateContentEncryptionKey(PKCS7* pkcs7, word32 len) +static int PKCS7_GenerateContentEncryptionKey(wc_PKCS7* pkcs7, word32 len) { int ret; WC_RNG rng; @@ -6837,7 +6837,7 @@ typedef struct WC_PKCS7_KARI { /* allocate and create new WC_PKCS7_KARI struct, * returns struct pointer on success, NULL on failure */ -static WC_PKCS7_KARI* wc_PKCS7_KariNew(PKCS7* pkcs7, byte direction) +static WC_PKCS7_KARI* wc_PKCS7_KariNew(wc_PKCS7* pkcs7, byte direction) { WC_PKCS7_KARI* kari = NULL; @@ -7127,7 +7127,7 @@ static int wc_PKCS7_KariGenerateSharedInfo(WC_PKCS7_KARI* kari, int keyWrapOID) /* suppPubInfo */ suppPubInfoSeqSz = (int)SetImplicit(ASN_SEQUENCE, 2, - (word32)kekOctetSz + sizeof(word32), + (word32)kekOctetSz + (word32)sizeof(word32), suppPubInfoSeq, 0); sharedInfoSz += suppPubInfoSeqSz; @@ -7312,7 +7312,7 @@ static int wc_PKCS7_KariGenerateKEK(WC_PKCS7_KARI* kari, WC_RNG* rng, * to CMS/PKCS#7 EnvelopedData structure. * * Returns 0 on success, negative upon error */ -int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, +int wc_PKCS7_AddRecipient_KARI(wc_PKCS7* pkcs7, const byte* cert, word32 certSz, int keyWrapOID, int keyAgreeOID, byte* ukm, word32 ukmSz, int options) { @@ -7682,7 +7682,7 @@ int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, word32 certSz, * to CMS/PKCS#7 EnvelopedData structure. * * Returns 0 on success, negative upon error */ -int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, +int wc_PKCS7_AddRecipient_KTRI(wc_PKCS7* pkcs7, const byte* cert, word32 certSz, int options) { Pkcs7EncodedRecip* recip = NULL; @@ -8119,7 +8119,7 @@ int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, word32 certSz, /* abstraction for writing out PKCS7 bundle during creation returns 0 on success */ -int wc_PKCS7_WriteOut(PKCS7* pkcs7, byte* output, const byte* input, +int wc_PKCS7_WriteOut(wc_PKCS7* pkcs7, byte* output, const byte* input, word32 inputSz) { int ret = 0; @@ -8157,7 +8157,7 @@ int wc_PKCS7_WriteOut(PKCS7* pkcs7, byte* output, const byte* input, /* encrypt content using encryptOID algo */ -static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, +static int wc_PKCS7_EncryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, int keySz, byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, word32 authTagSz, byte* in, @@ -8214,7 +8214,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #ifdef WOLFSSL_AES_256 (encryptOID == AES256CBCb && keySz != 32 ) || #endif - (ivSz != AES_BLOCK_SIZE) ) + (ivSz != WC_AES_BLOCK_SIZE) ) return BAD_FUNC_ARG; #ifdef WOLFSSL_SMALL_STACK @@ -8402,7 +8402,7 @@ static int wc_PKCS7_EncryptContent(PKCS7* pkcs7, int encryptOID, byte* key, /* decrypt content using encryptOID algo * returns 0 on success */ -static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, +static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, int keySz, byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, word32 authTagSz, byte* in, int inSz, byte* out, int devId, void* heap) { @@ -8453,7 +8453,7 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, #ifdef WOLFSSL_AES_256 (encryptOID == AES256CBCb && keySz != 32 ) || #endif - (ivSz != AES_BLOCK_SIZE) ) + (ivSz != WC_AES_BLOCK_SIZE) ) return BAD_FUNC_ARG; #ifdef WOLFSSL_SMALL_STACK if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, @@ -8605,7 +8605,7 @@ static int wc_PKCS7_DecryptContent(PKCS7* pkcs7, int encryptOID, byte* key, /* Generate random block, place in out, return 0 on success negative on error. * Used for generation of IV, nonce, etc */ -static int wc_PKCS7_GenerateBlock(PKCS7* pkcs7, WC_RNG* rng, byte* out, +static int wc_PKCS7_GenerateBlock(wc_PKCS7* pkcs7, WC_RNG* rng, byte* out, word32 outSz) { int ret; @@ -8653,7 +8653,7 @@ static int wc_PKCS7_GenerateBlock(PKCS7* pkcs7, WC_RNG* rng, byte* out, * type - either CMS_ISSUER_AND_SERIAL_NUMBER, CMS_SKID or DEGENERATE_SID * * return 0 on success, negative upon error */ -int wc_PKCS7_SetSignerIdentifierType(PKCS7* pkcs7, int type) +int wc_PKCS7_SetSignerIdentifierType(wc_PKCS7* pkcs7, int type) { if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -8677,7 +8677,7 @@ int wc_PKCS7_SetSignerIdentifierType(PKCS7* pkcs7, int type) * sz - length of contentType array, octets * * return 0 on success, negative upon error */ -int wc_PKCS7_SetContentType(PKCS7* pkcs7, byte* contentType, word32 sz) +int wc_PKCS7_SetContentType(wc_PKCS7* pkcs7, byte* contentType, word32 sz) { if (pkcs7 == NULL || contentType == NULL || sz == 0) return BAD_FUNC_ARG; @@ -8742,7 +8742,7 @@ int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, * to CMS/PKCS#7 EnvelopedData structure. * * Return 0 on success, negative upon error */ -int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, +int wc_PKCS7_AddRecipient_ORI(wc_PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, int options) { int oriTypeLenSz, blockKeySz, ret; @@ -8836,7 +8836,7 @@ int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt oriEncryptCb, #if !defined(NO_PWDBASED) && !defined(NO_SHA) -static int wc_PKCS7_GenerateKEK_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, +static int wc_PKCS7_GenerateKEK_PWRI(wc_PKCS7* pkcs7, byte* passwd, word32 pLen, byte* salt, word32 saltSz, int kdfOID, int prfOID, int iterations, byte* out, word32 outSz) @@ -8870,7 +8870,7 @@ static int wc_PKCS7_GenerateKEK_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, /* RFC3211 (Section 2.3.1) key wrap algorithm (id-alg-PWRI-KEK). * * Returns output size on success, negative upon error */ -static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, +static int wc_PKCS7_PwriKek_KeyWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kekSz, const byte* cek, word32 cekSz, byte* out, word32 *outSz, const byte* iv, word32 ivSz, int algID) @@ -8911,9 +8911,9 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, return BUFFER_E; out[0] = (byte)cekSz; - out[1] = ~cek[0]; - out[2] = ~cek[1]; - out[3] = ~cek[2]; + out[1] = (byte)~cek[0]; + out[2] = (byte)~cek[1]; + out[3] = (byte)~cek[2]; XMEMCPY(out + 4, cek, cekSz); /* random padding of size padSz */ @@ -8953,7 +8953,7 @@ static int wc_PKCS7_PwriKek_KeyWrap(PKCS7* pkcs7, const byte* kek, word32 kekSz, /* RFC3211 (Section 2.3.2) key unwrap algorithm (id-alg-PWRI-KEK). * * Returns cek size on success, negative upon error */ -static int wc_PKCS7_PwriKek_KeyUnWrap(PKCS7* pkcs7, const byte* kek, +static int wc_PKCS7_PwriKek_KeyUnWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kekSz, const byte* in, word32 inSz, byte* out, word32 outSz, const byte* iv, word32 ivSz, int algID) @@ -9056,7 +9056,7 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(PKCS7* pkcs7, const byte* kek, * to CMS/PKCS#7 EnvelopedData structure. * * Return 0 on success, negative upon error */ -int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, +int wc_PKCS7_AddRecipient_PWRI(wc_PKCS7* pkcs7, byte* passwd, word32 pLen, byte* salt, word32 saltSz, int kdfOID, int hashOID, int iterations, int kekEncryptOID, int options) @@ -9327,7 +9327,7 @@ int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, word32 pLen, * the password info for decryption a EnvelopedData PWRI RecipientInfo. * * Returns 0 on success, negative upon error */ -int wc_PKCS7_SetPassword(PKCS7* pkcs7, byte* passwd, word32 pLen) +int wc_PKCS7_SetPassword(wc_PKCS7* pkcs7, byte* passwd, word32 pLen) { if (pkcs7 == NULL || passwd == NULL || pLen == 0) return BAD_FUNC_ARG; @@ -9357,7 +9357,7 @@ int wc_PKCS7_SetPassword(PKCS7* pkcs7, byte* passwd, word32 pLen) * otherSz - size of other (OPTIONAL) * * Returns 0 on success, negative upon error */ -int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, +int wc_PKCS7_AddRecipient_KEKRI(wc_PKCS7* pkcs7, int keyWrapOID, byte* kek, word32 kekSz, byte* keyId, word32 keyIdSz, void* timePtr, byte* otherOID, word32 otherOIDSz, byte* other, word32 otherSz, @@ -9564,7 +9564,7 @@ int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, byte* kek, } -static int wc_PKCS7_GetCMSVersion(PKCS7* pkcs7, int cmsContentType) +static int wc_PKCS7_GetCMSVersion(wc_PKCS7* pkcs7, int cmsContentType) { int version = -1; @@ -9606,7 +9606,7 @@ static int wc_PKCS7_GetCMSVersion(PKCS7* pkcs7, int cmsContentType) /* build PKCS#7 envelopedData content type, return enveloped size */ -int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { int ret, idx = 0; int totalSz, padSz, encryptedOutSz; @@ -10013,7 +10013,7 @@ int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) #ifndef NO_RSA /* decode KeyTransRecipientInfo (ktri), return 0 on success, <0 on error */ -static int wc_PKCS7_DecryptKtri(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_DecryptKtri(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -10841,7 +10841,7 @@ static int wc_PKCS7_KariGetRecipientEncryptedKeys(WC_PKCS7_KARI* kari, #endif /* HAVE_ECC */ -int wc_PKCS7_SetOriEncryptCtx(PKCS7* pkcs7, void* ctx) +int wc_PKCS7_SetOriEncryptCtx(wc_PKCS7* pkcs7, void* ctx) { if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -10852,7 +10852,7 @@ int wc_PKCS7_SetOriEncryptCtx(PKCS7* pkcs7, void* ctx) } -int wc_PKCS7_SetOriDecryptCtx(PKCS7* pkcs7, void* ctx) +int wc_PKCS7_SetOriDecryptCtx(wc_PKCS7* pkcs7, void* ctx) { if (pkcs7 == NULL) @@ -10864,7 +10864,7 @@ int wc_PKCS7_SetOriDecryptCtx(PKCS7* pkcs7, void* ctx) } -int wc_PKCS7_SetOriDecryptCb(PKCS7* pkcs7, CallbackOriDecrypt cb) +int wc_PKCS7_SetOriDecryptCb(wc_PKCS7* pkcs7, CallbackOriDecrypt cb) { if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -10876,7 +10876,7 @@ int wc_PKCS7_SetOriDecryptCb(PKCS7* pkcs7, CallbackOriDecrypt cb) /* return 0 on success */ -int wc_PKCS7_SetWrapCEKCb(PKCS7* pkcs7, CallbackWrapCEK cb) +int wc_PKCS7_SetWrapCEKCb(wc_PKCS7* pkcs7, CallbackWrapCEK cb) { if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -10902,7 +10902,7 @@ int wc_PKCS7_SetWrapCEKCb(PKCS7* pkcs7, CallbackWrapCEK cb) * * Return 0 on success, negative upon error. */ -static int wc_PKCS7_DecryptOri(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_DecryptOri(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -10988,7 +10988,7 @@ static int wc_PKCS7_DecryptOri(PKCS7* pkcs7, byte* in, word32 inSz, /* decode ASN.1 PasswordRecipientInfo (pwri), return 0 on success, * < 0 on error */ -static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_DecryptPwri(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -11222,7 +11222,7 @@ static int wc_PKCS7_DecryptPwri(PKCS7* pkcs7, byte* in, word32 inSz, /* decode ASN.1 KEKRecipientInfo (kekri), return 0 on success, * < 0 on error */ -static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_DecryptKekri(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -11364,7 +11364,7 @@ static int wc_PKCS7_DecryptKekri(PKCS7* pkcs7, byte* in, word32 inSz, /* decode ASN.1 KeyAgreeRecipientInfo (kari), return 0 on success, * < 0 on error */ -static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, +static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -11631,7 +11631,7 @@ static int wc_PKCS7_DecryptKari(PKCS7* pkcs7, byte* in, word32 inSz, /* decode ASN.1 RecipientInfos SET, return 0 on success, < 0 on error */ -static int wc_PKCS7_DecryptRecipientInfos(PKCS7* pkcs7, byte* in, +static int wc_PKCS7_DecryptRecipientInfos(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, byte* decryptedKey, word32* decryptedKeySz, int* recipFound) { @@ -11868,15 +11868,15 @@ static int wc_PKCS7_DecryptRecipientInfos(PKCS7* pkcs7, byte* in, /* Parse encoded EnvelopedData bundle up to RecipientInfo set. * * return size of RecipientInfo SET on success, negative upon error */ -static int wc_PKCS7_ParseToRecipientInfoSet(PKCS7* pkcs7, byte* in, +static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, word32 inSz, word32* idx, int type) { - int version = 0, length, ret = 0; - word32 contentType; - byte* pkiMsg = in; + int version = 0, length = 0, ret = 0; + word32 contentType= 0; word32 pkiMsgSz = inSz; - byte tag; + byte* pkiMsg = in; + byte tag = 0; #ifndef NO_PKCS7_STREAM word32 tmpIdx = 0; #endif @@ -12125,7 +12125,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(PKCS7* pkcs7, byte* in, * the secret key for decryption a EnvelopedData KEKRI RecipientInfo. * * Returns 0 on success, negative upon error */ -WOLFSSL_API int wc_PKCS7_SetKey(PKCS7* pkcs7, byte* key, word32 keySz) +WOLFSSL_API int wc_PKCS7_SetKey(wc_PKCS7* pkcs7, byte* key, word32 keySz) { if (pkcs7 == NULL || key == NULL || keySz == 0) return BAD_FUNC_ARG; @@ -12139,7 +12139,7 @@ WOLFSSL_API int wc_PKCS7_SetKey(PKCS7* pkcs7, byte* key, word32 keySz) /* append data to encrypted content cache in PKCS7 structure * return 0 on success, negative on error */ -static int PKCS7_CacheEncryptedContent(PKCS7* pkcs7, byte* in, word32 inSz) +static int PKCS7_CacheEncryptedContent(wc_PKCS7* pkcs7, byte* in, word32 inSz) { byte* oldCache; word32 oldCacheSz; @@ -12173,7 +12173,7 @@ static int PKCS7_CacheEncryptedContent(PKCS7* pkcs7, byte* in, word32 inSz) /* unwrap and decrypt PKCS#7 envelopedData object, return decoded size */ -WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, +WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, byte* output, word32 outputSz) { @@ -12566,7 +12566,7 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* in, /* build PKCS#7 authEnvelopedData content type, return enveloped size */ -int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, +int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) @@ -12600,7 +12600,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, byte encContentOctet[MAX_OCTET_STR_SZ]; byte macOctetString[MAX_OCTET_STR_SZ]; - byte authTag[AES_BLOCK_SIZE]; + byte authTag[WC_AES_BLOCK_SIZE]; byte nonce[GCM_NONCE_MID_SZ]; /* GCM nonce is larger than CCM */ byte macInt[MAX_VERSION_SZ]; byte algoParamSeq[MAX_SEQ_SZ]; @@ -13118,7 +13118,7 @@ int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, byte* output, /* unwrap and decrypt PKCS#7 AuthEnvelopedData object, return decoded size */ -WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, +WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, byte* output, word32 outputSz) { @@ -13135,7 +13135,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, word32 pkiMsgSz = inSz; int expBlockSz = 0, blockKeySz = 0; - byte authTag[AES_BLOCK_SIZE]; + byte authTag[WC_AES_BLOCK_SIZE]; byte nonce[GCM_NONCE_MID_SZ]; /* GCM nonce is larger than CCM */ int nonceSz = 0, authTagSz = 0, macSz = 0; @@ -13155,7 +13155,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, byte* authAttrib = NULL; int authAttribSz = 0; word32 localIdx; - byte tag; + byte tag = 0; if (pkcs7 == NULL) return BAD_FUNC_ARG; @@ -13653,7 +13653,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, if (pkcs7->stream->tagSz > 0) { authTagSz = (int)pkcs7->stream->tagSz; - if (authTagSz > AES_BLOCK_SIZE) { + if (authTagSz > WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("PKCS7 saved tag is too large"); ret = BUFFER_E; break; @@ -13760,7 +13760,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* in, #ifndef NO_PKCS7_ENCRYPTED_DATA /* build PKCS#7 encryptedData content type, return encrypted size */ -int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeEncryptedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { int ret, idx = 0; int totalSz, padSz, encryptedOutSz; @@ -14022,7 +14022,7 @@ int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* decode and store unprotected attributes in PKCS7->decodedAttrib. Return * 0 on success, negative on error. User must call wc_PKCS7_Free(). */ -static int wc_PKCS7_DecodeUnprotectedAttributes(PKCS7* pkcs7, byte* pkiMsg, +static int wc_PKCS7_DecodeUnprotectedAttributes(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, word32* inOutIdx) { int ret, attribLen; @@ -14056,10 +14056,10 @@ static int wc_PKCS7_DecodeUnprotectedAttributes(PKCS7* pkcs7, byte* pkiMsg, /* unwrap and decrypt PKCS#7/CMS encrypted-data object, returned decoded size */ -int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, +int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, byte* output, word32 outputSz) { - int ret = 0, version, length = 0, haveAttribs = 0; + int ret = 0, version = 0, length = 0, haveAttribs = 0; word32 idx = 0; #ifndef NO_PKCS7_STREAM @@ -14077,7 +14077,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, byte* pkiMsg = in; word32 pkiMsgSz = inSz; - byte tag; + byte tag = 0; if (pkcs7 == NULL || ((pkcs7->encryptionKey == NULL || pkcs7->encryptionKeySz == 0) && @@ -14427,7 +14427,7 @@ int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* in, word32 inSz, * on the parsed bundle so far. * returns 0 on success */ -int wc_PKCS7_SetDecodeEncryptedCb(PKCS7* pkcs7, +int wc_PKCS7_SetDecodeEncryptedCb(wc_PKCS7* pkcs7, CallbackDecryptContent decryptionCb) { if (pkcs7 != NULL) { @@ -14440,7 +14440,7 @@ int wc_PKCS7_SetDecodeEncryptedCb(PKCS7* pkcs7, /* Set an optional user context that gets passed to callback * returns 0 on success */ -int wc_PKCS7_SetDecodeEncryptedCtx(PKCS7* pkcs7, void* ctx) +int wc_PKCS7_SetDecodeEncryptedCtx(wc_PKCS7* pkcs7, void* ctx) { if (pkcs7 != NULL) { pkcs7->decryptionCtx = ctx; @@ -14452,7 +14452,7 @@ int wc_PKCS7_SetDecodeEncryptedCtx(PKCS7* pkcs7, void* ctx) /* set stream mode for encoding and signing * returns 0 on success */ -int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, +int wc_PKCS7_SetStreamMode(wc_PKCS7* pkcs7, byte flag, CallbackGetContent getContentCb, CallbackStreamOut streamOutCb, void* ctx) { @@ -14476,7 +14476,7 @@ int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, /* returns to current stream mode flag on success, negative values on fail */ -int wc_PKCS7_GetStreamMode(PKCS7* pkcs7) +int wc_PKCS7_GetStreamMode(wc_PKCS7* pkcs7) { if (pkcs7 == NULL) { return BAD_FUNC_ARG; @@ -14491,7 +14491,7 @@ int wc_PKCS7_GetStreamMode(PKCS7* pkcs7) /* set option to not include certificates when creating a bundle * returns 0 on success */ -int wc_PKCS7_SetNoCerts(PKCS7* pkcs7, byte flag) +int wc_PKCS7_SetNoCerts(wc_PKCS7* pkcs7, byte flag) { if (pkcs7 == NULL) { return BAD_FUNC_ARG; @@ -14502,7 +14502,7 @@ int wc_PKCS7_SetNoCerts(PKCS7* pkcs7, byte flag) /* returns the current noCerts flag value on success, negative values on fail */ -int wc_PKCS7_GetNoCerts(PKCS7* pkcs7) +int wc_PKCS7_GetNoCerts(wc_PKCS7* pkcs7) { if (pkcs7 == NULL) { return BAD_FUNC_ARG; @@ -14514,7 +14514,7 @@ int wc_PKCS7_GetNoCerts(PKCS7* pkcs7) #if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) /* build PKCS#7 compressedData content type, return encrypted size */ -int wc_PKCS7_EncodeCompressedData(PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) { byte contentInfoSeq[MAX_SEQ_SZ]; byte contentInfoTypeOid[MAX_OID_SZ]; @@ -14686,7 +14686,7 @@ int wc_PKCS7_EncodeCompressedData(PKCS7* pkcs7, byte* output, word32 outputSz) /* unwrap and decompress PKCS#7/CMS compressedData object, * Handles content wrapped compressed data and raw compressed data packet * returned decoded size */ -int wc_PKCS7_DecodeCompressedData(PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, +int wc_PKCS7_DecodeCompressedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, byte* output, word32 outputSz) { int length, version, ret; diff --git a/src/wolfcrypt/src/port/Espressif/esp32_aes.c b/src/wolfcrypt/src/port/Espressif/esp32_aes.c index f85343e..fc0fd7f 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -514,9 +514,9 @@ int wc_esp32AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) int ret; int i; int offset = 0; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); byte *iv; - byte temp_block[AES_BLOCK_SIZE]; + byte temp_block[WC_AES_BLOCK_SIZE]; ESP_LOGV(TAG, "enter wc_esp32AesCbcEncrypt"); @@ -533,19 +533,19 @@ int wc_esp32AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) if (ret == ESP_OK) { while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + offset, WC_AES_BLOCK_SIZE); /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) { + for (i = 0; i < WC_AES_BLOCK_SIZE; i++) { temp_block[i] ^= iv[i]; } esp_aes_bk(temp_block, (out + offset)); - offset += AES_BLOCK_SIZE; + offset += WC_AES_BLOCK_SIZE; /* store IV for next block */ - XMEMCPY(iv, out + offset - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + XMEMCPY(iv, out + offset - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } /* while (blocks--) */ } /* if Set Mode successful (ret == ESP_OK) */ @@ -573,9 +573,9 @@ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) int i; int offset = 0; - word32 blocks = (sz / AES_BLOCK_SIZE); + word32 blocks = (sz / WC_AES_BLOCK_SIZE); byte* iv; - byte temp_block[AES_BLOCK_SIZE]; + byte temp_block[WC_AES_BLOCK_SIZE]; ESP_LOGV(TAG, "enter wc_esp32AesCbcDecrypt"); @@ -592,19 +592,19 @@ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) if (ret == ESP_OK) { while (blocks--) { - XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + XMEMCPY(temp_block, in + offset, WC_AES_BLOCK_SIZE); esp_aes_bk((in + offset), (out + offset)); /* XOR block with IV for CBC */ - for (i = 0; i < AES_BLOCK_SIZE; i++) { + for (i = 0; i < WC_AES_BLOCK_SIZE; i++) { (out + offset)[i] ^= iv[i]; } /* store IV for next block */ - XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + XMEMCPY(iv, temp_block, WC_AES_BLOCK_SIZE); - offset += AES_BLOCK_SIZE; + offset += WC_AES_BLOCK_SIZE; } /* while (blocks--) */ esp_aes_hw_Leave(); } /* if Set Mode was successful (ret == ESP_OK) */ diff --git a/src/wolfcrypt/src/port/Espressif/esp32_mp.c b/src/wolfcrypt/src/port/Espressif/esp32_mp.c index 458719d..6d9d2ab 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -3172,7 +3172,7 @@ int esp_mp_exptmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #endif /* !NO_RSA || HAVE_ECC */ -/* Some optional metrics when using RSA HW Accleration */ +/* Some optional metrics when using RSA HW Acceleration */ #if defined(WOLFSSL_ESP32_CRYPT_RSA_PRI) && defined(WOLFSSL_HW_METRICS) int esp_hw_show_mp_metrics(void) { diff --git a/src/wolfcrypt/src/port/Espressif/esp32_sha.c b/src/wolfcrypt/src/port/Espressif/esp32_sha.c index 6fa955a..65d635d 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -141,14 +141,27 @@ static const char* TAG = "wolf_hw_sha"; static portMUX_TYPE sha_crit_sect = portMUX_INITIALIZER_UNLOCKED; #endif -#if defined(ESP_MONITOR_HW_TASK_LOCK) +#if defined(ESP_MONITOR_HW_TASK_LOCK) || !defined(SINGLE_THREADED) #ifdef SINGLE_THREADED uintptr_t esp_sha_mutex_ctx_owner(void) { return mutex_ctx_owner; } + + uintptr_t esp_sha_mutex_ctx_owner_set(uintptr_t new_mutex_ctx_owner) { + mutex_ctx_owner = new_mutex_ctx_owner; + return new_mutex_ctx_owner; + } + + uintptr_t esp_sha_mutex_ctx_owner_clear(void) { + return esp_sha_mutex_ctx_owner_set(NULLPTR); + } #else - static TaskHandle_t mutex_ctx_task = NULL; + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) + + static TaskHandle_t mutex_ctx_task = NULL; + #endif + uintptr_t esp_sha_mutex_ctx_owner(void) { uintptr_t ret = 0; @@ -159,7 +172,22 @@ static const char* TAG = "wolf_hw_sha"; taskEXIT_CRITICAL(&sha_crit_sect); return ret; }; - #endif + + uintptr_t esp_sha_mutex_ctx_owner_set(uintptr_t new_mutex_ctx_owner) + { + taskENTER_CRITICAL(&sha_crit_sect); + { + mutex_ctx_owner = new_mutex_ctx_owner; + } + taskEXIT_CRITICAL(&sha_crit_sect); + return new_mutex_ctx_owner; + }; + + uintptr_t esp_sha_mutex_ctx_owner_clear(void) { + return esp_sha_mutex_ctx_owner_set(NULLPTR); + } + #endif /* ! SINGLE_THREADED */ + #ifdef WOLFSSL_DEBUG_MUTEX WC_ESP32SHA* stray_ctx; @@ -192,7 +220,11 @@ int esp_set_hw(WC_ESP32SHA* ctx) ESP_LOGV(TAG, "esp_set_hw already locked: 0x%x", (intptr_t)ctx); } ctx->mode = ESP32_SHA_HW; +#if defined(ESP_MONITOR_HW_TASK_LOCK) || !defined(SINGLE_THREADED) + mutex_ctx_owner = esp_sha_mutex_ctx_owner_set((uintptr_t)ctx); +#else mutex_ctx_owner = (uintptr_t)ctx; +#endif ret = ESP_OK; } else { @@ -413,7 +445,7 @@ int esp_sha_init_ctx(WC_ESP32SHA* ctx) if (esp_sha_hw_islocked(ctx)) { esp_sha_hw_unlock(ctx); } - mutex_ctx_owner = (uintptr_t)ctx; + mutex_ctx_owner = esp_sha_mutex_ctx_owner_set((uintptr_t)ctx); } else { ESP_LOGI(TAG, "MUTEX_DURING_INIT esp_sha_init_ctx for non-owner: " @@ -990,28 +1022,26 @@ int esp_sha_hw_in_use() uintptr_t esp_sha_hw_islocked(WC_ESP32SHA* ctx) { uintptr_t ret = 0; - #ifndef SINGLE_THREADED + #if !defined(WOLFSSL_DEBUG_MUTEX) && !defined(SINGLE_THREADED) TaskHandle_t mutexHolder; #endif CTX_STACK_CHECK(ctx); #ifdef WOLFSSL_DEBUG_MUTEX - taskENTER_CRITICAL(&sha_crit_sect); - { - ret = (uintptr_t)mutex_ctx_owner; - if (ctx == 0) { - /* we are not checking if a given ctx has the lock */ + ret = esp_sha_mutex_ctx_owner(); + if (ctx == 0) { + ESP_LOGV(TAG, "ctx == 0; Not checking if a given ctx has the lock"); + } + else { + if (ret == (uintptr_t)ctx->initializer) { + ESP_LOGV(TAG, "confirmed this object is the owner"); } else { - if (ret == (uintptr_t)ctx->initializer) { - /* confirmed this object is the owner */ - } - else { - /* this object is not the lock owner */ - } + ESP_LOGV(TAG, "this object is not the lock owner"); + } - } - taskEXIT_CRITICAL(&sha_crit_sect); + } /* ctx != 0 */ + #else #ifdef SINGLE_THREADED { @@ -1092,17 +1122,27 @@ uintptr_t esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) ESP_LOGW(TAG, "New mutex_ctx_owner = NULL"); #ifdef ESP_MONITOR_HW_TASK_LOCK { - mutex_ctx_owner = NULLPTR; + esp_sha_mutex_ctx_owner_clear(); } #endif } else { - /* the only mismatch expected may be in a multi-thread RTOS */ - ESP_LOGE(TAG, "ERROR: Release unfinished lock for %x but " - "found %x", ret, ctx->initializer); - } + #if defined(WOLFSSL_DEBUG_MUTEX) || defined(WOLFSSL_ESP32_HW_LOCK_DEBUG) + if (ctx->initializer == 0) { + /* A zero likely indicates prior cleanup for abandoned hash. + * Check the calling code to confirm this is the case. */ + ESP_LOGW(TAG, "Release already finished lock for %x ?", + ctx->initializer); + } + else { + /* Mismatch expected may be in a multi-thread RTOS. */ + ESP_LOGW(TAG, "ERROR: Release unfinished lock for %x but " + "found %x", ret, ctx->initializer); + } + #endif + } /* ret != ctx->initializer */ #ifdef WOLFSSL_DEBUG_MUTEX - ESP_LOGE(TAG, "\n>>>> esp_sha_release_unfinished_lock %x\n", ret); + ESP_LOGW(TAG, "\n>>>> esp_sha_release_unfinished_lock %x\n", ret); #endif /* unlock only if this ctx is the initializer of the lock */ @@ -1153,11 +1193,22 @@ uintptr_t esp_sha_release_unfinished_lock(WC_ESP32SHA* ctx) int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) { int ret = 0; + +#if defined(SINGLE_THREADED) + /* no mutex monitoring available in single thread mode */ +#else + /* thread safe get of global static mutex_ctx_owner: */ + uintptr_t this_mutex_owner; + + /* mutex_ctx_owner could change in multiple threads, assign once here: */ + this_mutex_owner = esp_sha_mutex_ctx_owner(); +#endif + CTX_STACK_CHECK(ctx); #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - ESP_LOGI(TAG, "enter esp_sha_hw_lock for %x", - (uintptr_t)ctx->initializer); + ESP_LOGI(TAG, "enter esp_sha_hw_lock for %x, initializer %x", + (uintptr_t)ctx, (uintptr_t)ctx->initializer); #endif #ifdef WOLFSSL_DEBUG_MUTEX @@ -1226,7 +1277,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) ret = esp_CryptHwMutexInit(&sha_mutex); if (ret == 0) { ESP_LOGV(TAG, "esp_CryptHwMutexInit sha_mutex init success."); - mutex_ctx_owner = NULLPTR; /* No one has the mutex yet.*/ + esp_sha_mutex_ctx_owner_clear(); /* No one has the mutex yet. */ #ifdef WOLFSSL_DEBUG_MUTEX { /* Take mutex for lock/unlock test drive to ensure it works: */ @@ -1247,8 +1298,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) ESP_LOGE(TAG, "esp_CryptHwMutexInit sha_mutex failed."); #ifdef WOLFSSL_DEBUG_MUTEX { - ESP_LOGV(TAG, "Current mutext owner = %x", - (int)esp_sha_mutex_ctx_owner()); + ESP_LOGV(TAG, "Current mutext owner = %x", this_mutex_owner); } #endif @@ -1272,8 +1322,8 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) if (((WC_ESP32SHA*)mutex_ctx_owner)->mode == ESP32_SHA_FREED) { ESP_LOGW(TAG, "ESP32_SHA_FREED unlocking mutex_ctx_task = %x" " for mutex_ctx_owner = %x", - (int)mutex_ctx_task, - (int)mutex_ctx_owner); + (uintptr_t)mutex_ctx_task, + (uintptr_t)this_mutex_owner); } else { if (ctx->mode == ESP32_SHA_FREED) { @@ -1286,7 +1336,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* Not very interesting during init. */ if (ctx->mode == ESP32_SHA_INIT) { ESP_LOGV(TAG, "mutex_ctx_owner = 0x%x", - mutex_ctx_owner); + this_mutex_owner); ESP_LOGV(TAG, "This ctx = 0x%x is ESP32_SHA_INIT", (uintptr_t)ctx); } @@ -1297,7 +1347,10 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } /* mutex owner ESP32_SHA_FREED check */ } /* mutex_ctx_task is current task */ else { - ESP_LOGW(TAG, "Warning: sha mutex unlock from unexpected task"); + ESP_LOGW(TAG, "Warning: sha mutex unlock from unexpected task."); + ESP_LOGW(TAG, "Locking task: 0x%x", (word32)mutex_ctx_task); + ESP_LOGW(TAG, "This xTaskGetCurrentTaskHandle: 0x%x", + (word32)xTaskGetCurrentTaskHandle()); } } #endif /* ESP_MONITOR_HW_TASK_LOCK */ @@ -1306,7 +1359,8 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) if (ctx->mode == ESP32_SHA_INIT) { /* try to lock the HW engine */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG - ESP_LOGI(TAG, "ESP32_SHA_INIT for %x\n", (uintptr_t)ctx->initializer); + ESP_LOGI(TAG, "ESP32_SHA_INIT for %x, initializer %x\n", + (uintptr_t)ctx, (uintptr_t)ctx->initializer); #endif ESP_LOGV(TAG, "Init; release unfinished ESP32_SHA_INIT lock " "for ctx 0x%x", (uintptr_t)ctx); @@ -1324,8 +1378,9 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) if ((mutex_ctx_owner == NULLPTR) && esp_CryptHwMutexLock(&sha_mutex, (TickType_t)0) == ESP_OK) { /* we've successfully locked */ - mutex_ctx_owner = (uintptr_t)ctx; - ESP_LOGV(TAG, "Assigned mutex_ctx_owner to 0x%x", mutex_ctx_owner); + this_mutex_owner = (uintptr_t)ctx; + esp_sha_mutex_ctx_owner_set(this_mutex_owner); + ESP_LOGV(TAG, "Assigned mutex_ctx_owner to 0x%x", this_mutex_owner); #ifdef ESP_MONITOR_HW_TASK_LOCK mutex_ctx_task = xTaskGetCurrentTaskHandle(); #endif @@ -1344,6 +1399,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) else { stray_ctx->initializer = (intptr_t)stray_ctx; mutex_ctx_owner = (intptr_t)stray_ctx->initializer; + this_mutex_owner = mutex_ctx_owner; } } taskEXIT_CRITICAL(&sha_crit_sect); @@ -1359,8 +1415,11 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) "\n\nLocking with stray\n\n" "WOLFSSL_DEBUG_MUTEX call count 8, " "ctx->mode = ESP32_SHA_SW %x\n\n", - (int)mutex_ctx_owner); + this_mutex_owner); + #if defined(ESP_MONITOR_HW_TASK_LOCK) && !defined(SINGLE_THREADED) + /* ctx->task_owner is only available for multi-threaded */ ctx->task_owner = xTaskGetCurrentTaskHandle(); + #endif ctx->mode = ESP32_SHA_SW; return ESP_OK; /* success, but revert to SW */ } @@ -1370,7 +1429,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) /* check to see if we had a prior fail and need to unroll enables */ #ifdef WOLFSSL_ESP32_HW_LOCK_DEBUG ESP_LOGW(TAG, "Locking for ctx %x, current mutex_ctx_owner = %x", - (uintptr_t)&ctx, esp_sha_mutex_ctx_owner()); + (uintptr_t)&ctx, this_mutex_owner); ESP_LOGI(TAG, "ctx->lockDepth = %d", ctx->lockDepth); #endif if (ctx->mode == ESP32_SHA_INIT) { @@ -1402,7 +1461,7 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) } else { /* When the lock is already in use: is it for this ctx? */ - if ((uintptr_t)ctx == esp_sha_mutex_ctx_owner()) { + if ((uintptr_t)ctx == this_mutex_owner) { ESP_LOGV(TAG, "I'm the owner! 0x%x", (uintptr_t)ctx); ctx->mode = ESP32_SHA_SW; } @@ -1410,20 +1469,20 @@ int esp_sha_try_hw_lock(WC_ESP32SHA* ctx) #ifdef WOLFSSL_DEBUG_MUTEX ESP_LOGW(TAG, "\nHardware in use by %x; " "Mode REVERT to ESP32_SHA_SW for %x\n", - esp_sha_mutex_ctx_owner(), + this_mutex_owner, (uintptr_t)ctx->initializer); ESP_LOGI(TAG, "Software Mode, lock depth = %d, for this %x", ctx->lockDepth, (uintptr_t)ctx->initializer); ESP_LOGI(TAG, "Current mutext owner = %x", - esp_sha_mutex_ctx_owner()); + this_mutex_owner); #endif ESP_LOGV(TAG, "I'm not owner! 0x%x; owner = 0x%x", (uintptr_t)ctx, mutex_ctx_owner); - if (mutex_ctx_owner) { + if (this_mutex_owner) { #ifdef WOLFSSL_DEBUG_MUTEX ESP_LOGW(TAG, "revert to SW since mutex_ctx_owner = %x" " but we are currently ctx = %x", - mutex_ctx_owner, (intptr_t)ctx); + this_mutex_owner, (intptr_t)ctx); #endif } else { diff --git a/src/wolfcrypt/src/port/Espressif/esp32_util.c b/src/wolfcrypt/src/port/Espressif/esp32_util.c index d5d77ed..f133875 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_util.c @@ -100,7 +100,7 @@ int esp_CryptHwMutexInit(wolfSSL_Mutex* mutex) { /* * Call the ESP-IDF mutex lock; xSemaphoreTake * this is a general mutex locker, used for different mutex objects for - * different HW acclerators or other single-use HW features. + * different HW accelerators or other single-use HW features. * * We should already have known if the resource is in use or not. * @@ -988,7 +988,7 @@ int hexToBinary(byte* toVar, const char* fromHexString, size_t szHexString ) { sscanf(&fromHexString[i], "%2x", &decimalValue); size_t index = i / 2; #if (0) - /* Optionall peek at new values */ + /* Optionally peek at new values */ byte new_val = (decimalValue & 0x0F) << ((i % 2) * 4); ESP_LOGI("hex", "Current char = %d", toVar[index]); ESP_LOGI("hex", "New val = %d", decimalValue); diff --git a/src/wolfcrypt/src/pwdbased.c b/src/wolfcrypt/src/pwdbased.c index fb06dce..208f667 100644 --- a/src/wolfcrypt/src/pwdbased.c +++ b/src/wolfcrypt/src/pwdbased.c @@ -826,7 +826,7 @@ int wc_scrypt(byte* output, const byte* passwd, int passLen, goto end; } /* Temporary for scryptROMix. */ - v = (byte*)XMALLOC((size_t)((1 << cost) * bSz), NULL, + v = (byte*)XMALLOC((size_t)((1U << cost) * bSz), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (v == NULL) { ret = MEMORY_E; @@ -848,7 +848,7 @@ int wc_scrypt(byte* output, const byte* passwd, int passLen, /* Step 2. */ for (i = 0; i < parallel; i++) - scryptROMix(blocks + i * (int)bSz, v, y, (int)blockSize, 1 << cost); + scryptROMix(blocks + i * (int)bSz, v, y, (int)blockSize, 1U << cost); /* Step 3. */ ret = wc_PBKDF2(output, passwd, passLen, blocks, (int)blocksSz, 1, dkLen, diff --git a/src/wolfcrypt/src/random.c b/src/wolfcrypt/src/random.c index 278e2d7..febc292 100644 --- a/src/wolfcrypt/src/random.c +++ b/src/wolfcrypt/src/random.c @@ -111,6 +111,8 @@ This library contains implementation for the random number generator. #include #elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) #include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h" +#elif defined(WOLFSSL_RPIPICO) + #include "wolfssl/wolfcrypt/port/rpi_pico/pico.h" #elif defined(NO_DEV_RANDOM) #elif defined(CUSTOM_RAND_GENERATE) #elif defined(CUSTOM_RAND_GENERATE_BLOCK) @@ -596,14 +598,14 @@ static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen dIdx = (int)dLen - 1; for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) { - carry += (word16)((word16)d[dIdx] + (word16)s[sIdx]); + carry = (word16)(carry + d[dIdx] + s[sIdx]); d[dIdx] = (byte)carry; carry >>= 8; dIdx--; } for (; dIdx >= 0; dIdx--) { - carry += (word16)d[dIdx]; + carry = (word16)(carry + d[dIdx]); d[dIdx] = (byte)carry; carry >>= 8; } @@ -1702,7 +1704,7 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, if (ret != 0) { #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG_EX("_InitRng failed. err = ", ret); + WOLFSSL_MSG_EX("_InitRng failed. err = %d", ret); #endif } else { @@ -2968,7 +2970,6 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } return RAN_BLOCK_E; } - #elif !defined(WOLFSSL_CAAM) && \ (defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \ defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS)) diff --git a/src/wolfcrypt/src/rsa.c b/src/wolfcrypt/src/rsa.c index 9e34599..a3c0292 100644 --- a/src/wolfcrypt/src/rsa.c +++ b/src/wolfcrypt/src/rsa.c @@ -63,7 +63,7 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif @@ -277,7 +277,6 @@ int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) key->handle = NULL; #endif - #if defined(WOLFSSL_RENESAS_FSPSM) key->ctx.wrapped_pri1024_key = NULL; key->ctx.wrapped_pub1024_key = NULL; @@ -285,6 +284,7 @@ int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) key->ctx.wrapped_pub2048_key = NULL; key->ctx.keySz = 0; #endif + return ret; } @@ -2801,7 +2801,9 @@ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, ret = wc_RsaEncryptSize(key); if (ret < 0) { +#ifdef DEBUG_WOLFSSL WOLFSSL_MSG_EX("wc_RsaEncryptSize failed err = %d", ret); +#endif return ret; } keyLen = (word32)ret; @@ -2924,7 +2926,7 @@ static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out, } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */ -#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) +#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* Performs direct RSA computation without padding. The input and output must * match the key size (ex: 2048-bits = 256 bytes). Returns the size of the * output on success or negative value on failure. */ @@ -3010,7 +3012,7 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, return ret; } -#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */ +#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if defined(WOLFSSL_CRYPTOCELL) static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, @@ -3108,7 +3110,8 @@ int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig, #endif /* WOLFSSL_CRYPTOCELL */ #ifndef WOLF_CRYPTO_CB_ONLY_RSA -#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(TEST_UNPAD_CONSTANT_TIME) && !defined(NO_RSA_BOUNDS_CHECK) +#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(TEST_UNPAD_CONSTANT_TIME) && \ + !defined(NO_RSA_BOUNDS_CHECK) /* Check that 1 < in < n-1. (Requirement of 800-56B.) */ int RsaFunctionCheckIn(const byte* in, word32 inLen, RsaKey* key, int checkSmallCt) @@ -3374,24 +3377,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, pad_value, pad_type, hash, mgf, label, labelSz, sz); } - #elif defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY) || \ - (!defined(WOLFSSL_RENESAS_TSIP_TLS) && \ - defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)) - /* SCE needs wrapped key which is passed via - * user ctx object of crypt-call back. - */ - #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - /* SCE supports 1024 and 2048 bits */ - ret = wc_CryptoCb_Rsa(in, inLen, out, - &outLen, rsa_type, key, rng); - if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) - return ret; - /* fall-through when unavailable */ - ret = 0; /* reset error code and try using software */ - } - #endif - #endif /* WOLFSSL_SE050 */ + #endif /* RSA CRYPTO HW */ #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) if (key->devId != INVALID_DEVID) { @@ -3561,21 +3547,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, } return ret; } - #elif defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY) || \ - (!defined(WOLFSSL_RENESAS_TSIP_TLS) && \ - defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)) - #ifdef WOLF_CRYPTO_CB - if (key->devId != INVALID_DEVID) { - ret = wc_CryptoCb_Rsa(in, inLen, out, - &outLen, rsa_type, key, rng); - if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) - return ret; - /* fall-through when unavailable */ - ret = 0; /* reset error code and try using software */ - } - #endif - - #endif /* WOLFSSL_CRYPTOCELL */ + #endif /* RSA CRYPTO HW */ #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \ @@ -3609,7 +3581,12 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, case RSA_STATE_DECRYPT_EXPTMOD: #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) - if ((key->devId != INVALID_DEVID) && (rsa_type != RSA_PUBLIC_DECRYPT)) { + if ((key->devId != INVALID_DEVID) + #if !defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY) && \ + !defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY) + && (rsa_type != RSA_PUBLIC_DECRYPT) + #endif + ) { /* Everything except verify goes to crypto cb if * WOLF_CRYPTO_CB_RSA_PAD defined */ XMEMSET(&padding, 0, sizeof(RsaPadding)); diff --git a/src/wolfcrypt/src/sakke.c b/src/wolfcrypt/src/sakke.c index 962299f..fab1067 100644 --- a/src/wolfcrypt/src/sakke.c +++ b/src/wolfcrypt/src/sakke.c @@ -47,7 +47,7 @@ #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #undef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif diff --git a/src/wolfcrypt/src/sha3.c b/src/wolfcrypt/src/sha3.c index 1a3596a..4ced66e 100644 --- a/src/wolfcrypt/src/sha3.c +++ b/src/wolfcrypt/src/sha3.c @@ -62,9 +62,9 @@ } #endif -#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) -#ifdef USE_INTEL_SPEEDUP +#if defined(USE_INTEL_SPEEDUP) || (defined(__aarch64__) && \ + defined(WOLFSSL_ARMASM)) #include word32 cpuid_flags; @@ -81,6 +81,8 @@ #endif #endif +#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) + #ifdef WOLFSSL_SHA3_SMALL /* Rotate a 64-bit value left. * @@ -299,7 +301,7 @@ void BlockSha3(word64* s) */ #define ROTL64(a, n) (((a)<<(n))|((a)>>(64-(n)))) - +#if !defined(STM32_HASH_SHA3) /* An array of values to XOR for block operation. */ static const word64 hash_keccak_r[24] = { @@ -316,6 +318,7 @@ static const word64 hash_keccak_r[24] = W64LIT(0x8000000080008081), W64LIT(0x8000000000008080), W64LIT(0x0000000080000001), W64LIT(0x8000000080008008) }; +#endif /* Indices used in swap and rotate operation. */ #define KI_0 6 @@ -533,6 +536,7 @@ do { \ while (0) #endif /* SHA3_BY_SPEC */ +#if !defined(STM32_HASH_SHA3) /* The block operation performed on the state. * * s The state. @@ -548,7 +552,7 @@ void BlockSha3(word64* s) #ifndef SHA3_BY_SPEC word64 t1; #endif - byte i; + word32 i; for (i = 0; i < 24; i += 2) { @@ -562,8 +566,10 @@ void BlockSha3(word64* s) } } #endif /* WOLFSSL_SHA3_SMALL */ +#endif /* STM32_HASH_SHA3 */ #endif /* !WOLFSSL_ARMASM && !WOLFSSL_RISCV_ASM */ +#if !defined(STM32_HASH_SHA3) static WC_INLINE word64 Load64Unaligned(const unsigned char *a) { return ((word64)a[0] << 0) | @@ -617,6 +623,7 @@ static word64 Load64BitBigEndian(const byte* a) * sha3 wc_Sha3 object holding state. * returns 0 on success. */ + static int InitSha3(wc_Sha3* sha3) { int i; @@ -654,11 +661,37 @@ static int InitSha3(wc_Sha3* sha3) SHA3_BLOCK_N = NULL; } } +#define SHA3_FUNC_PTR +#endif +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + if (!cpuid_flags_set) { + cpuid_flags = cpuid_get_flags(); + cpuid_flags_set = 1; + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 + if (IS_AARCH64_SHA3(cpuid_flags)) { + SHA3_BLOCK = BlockSha3_crypto; + SHA3_BLOCK_N = NULL; + } + else + #endif + { + SHA3_BLOCK = BlockSha3_base; + SHA3_BLOCK_N = NULL; + } + } +#define SHA3_FUNC_PTR #endif return 0; } +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) +void BlockSha3(word64* s) +{ + (*SHA3_BLOCK)(s); +} +#endif + /* Update the SHA-3 hash state with message data. * * sha3 wc_Sha3 object holding state. @@ -689,13 +722,13 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) } data += i; len -= i; - sha3->i += (byte) i; + sha3->i = (byte)(sha3->i + i); if (sha3->i == p * 8) { for (i = 0; i < p; i++) { sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); } - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); @@ -703,12 +736,12 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) sha3->i = 0; } } - blocks = len / (p * 8); - #ifdef USE_INTEL_SPEEDUP + blocks = len / (p * 8U); + #ifdef SHA3_FUNC_PTR if ((SHA3_BLOCK_N != NULL) && (blocks > 0)) { - (*SHA3_BLOCK_N)(sha3->s, data, blocks, p * 8); - len -= blocks * (p * 8); - data += blocks * (p * 8); + (*SHA3_BLOCK_N)(sha3->s, data, blocks, p * 8U); + len -= blocks * (p * 8U); + data += blocks * (p * 8U); blocks = 0; } #endif @@ -716,20 +749,20 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) for (i = 0; i < p; i++) { sha3->s[i] ^= Load64Unaligned(data + 8 * i); } - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); #endif - len -= p * 8; - data += p * 8; + len -= p * 8U; + data += p * 8U; } #if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) if (SHA3_BLOCK == sha3_block_avx2) RESTORE_VECTOR_REGISTERS(); #endif XMEMCPY(sha3->t, data, len); - sha3->i += (byte)len; + sha3->i = (byte)(sha3->i + len); return 0; } @@ -744,7 +777,7 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) */ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) { - word32 rate = p * 8; + word32 rate = p * 8U; word32 j; word32 i; @@ -756,7 +789,7 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) sha3->t[sha3->i ] = padChar; sha3->t[rate - 1] |= 0x80; if (rate - 1 > (word32)sha3->i + 1) { - XMEMSET(sha3->t + sha3->i + 1, 0, rate - 1 - (sha3->i + 1)); + XMEMSET(sha3->t + sha3->i + 1, 0, rate - 1U - (sha3->i + 1U)); } for (i = 0; i < p; i++) { sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); @@ -768,7 +801,7 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) #endif for (j = 0; l - j >= rate; j += rate) { - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); @@ -780,7 +813,7 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) #endif } if (j != l) { - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(sha3->s); #else BlockSha3(sha3->s); @@ -797,6 +830,84 @@ static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, byte p, word32 l) return 0; } +#endif +#if defined(STM32_HASH_SHA3) + + /* Supports CubeMX HAL or Standard Peripheral Library */ + + static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId) + { + if (sha3 == NULL) + return BAD_FUNC_ARG; + + (void)devId; + (void)heap; + + XMEMSET(sha3, 0, sizeof(wc_Sha3)); + wc_Stm32_Hash_Init(&sha3->stmCtx); + return 0; + } + + static int Stm32GetAlgo(byte p) + { + switch(p) { + case WC_SHA3_224_COUNT: + return HASH_ALGOSELECTION_SHA3_224; + case WC_SHA3_256_COUNT: + return HASH_ALGOSELECTION_SHA3_256; + case WC_SHA3_384_COUNT: + return HASH_ALGOSELECTION_SHA3_384; + case WC_SHA3_512_COUNT: + return HASH_ALGOSELECTION_SHA3_512; + } + /* Should never get here */ + return WC_SHA3_224_COUNT; + } + + static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) + { + int ret = 0; + + if (sha3 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Update(&sha3->stmCtx, + Stm32GetAlgo(p), data, len, p * 8); + wolfSSL_CryptHwMutexUnLock(); + } + return ret; + } + + static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, byte p, byte len) + { + int ret = 0; + + if (sha3 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Final(&sha3->stmCtx, + Stm32GetAlgo(p), hash, len); + wolfSSL_CryptHwMutexUnLock(); + } + + (void)wc_InitSha3(sha3, NULL, 0); /* reset state */ + + return ret; + } +#else /* Initialize the state for a SHA-3 hash operation. * @@ -820,10 +931,10 @@ static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId) #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) ret = wolfAsync_DevCtxInit(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3, sha3->heap, devId); -#elif defined(WOLF_CRYPTO_CB) +#endif +#if defined(WOLF_CRYPTO_CB) sha3->devId = devId; -#endif /* WOLFSSL_ASYNC_CRYPT */ - +#endif (void)devId; return ret; @@ -944,7 +1055,7 @@ static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, byte p, byte len) return InitSha3(sha3); /* reset state */ } - +#endif /* Dispose of any dynamically allocated data from the SHA3-384 operation. * (Required for async ops.) * @@ -1420,7 +1531,7 @@ int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) SAVE_VECTOR_REGISTERS(return _svr_ret;); #endif for (; (blockCnt > 0); blockCnt--) { - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(shake->s); #else BlockSha3(shake->s); @@ -1558,7 +1669,7 @@ int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) SAVE_VECTOR_REGISTERS(return _svr_ret;); #endif for (; (blockCnt > 0); blockCnt--) { - #ifdef USE_INTEL_SPEEDUP + #ifdef SHA3_FUNC_PTR (*SHA3_BLOCK)(shake->s); #else BlockSha3(shake->s); diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index 7f3e745..16c3c0f 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -219,6 +219,66 @@ { se050_hash_free(&sha512->se050Ctx); } +#elif defined(STM32_HASH_SHA512) + + /* Supports CubeMX HAL or Standard Peripheral Library */ + + int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) + { + if (sha512 == NULL) + return BAD_FUNC_ARG; + + (void)devId; + (void)heap; + + XMEMSET(sha512, 0, sizeof(wc_Sha512)); + wc_Stm32_Hash_Init(&sha512->stmCtx); + return 0; + } + + int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) + { + int ret = 0; + + if (sha512 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Update(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512, data, len, WC_SHA512_BLOCK_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + return ret; + } + + int wc_Sha512Final(wc_Sha512* sha512, byte* hash) + { + int ret = 0; + + if (sha512 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Final(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512, hash, WC_SHA512_DIGEST_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + + (void)wc_InitSha512(sha512); /* reset state */ + + return ret; + } #else @@ -1174,7 +1234,7 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ - +#elif defined(STM32_HASH_SHA512) #else static WC_INLINE int Sha512Final(wc_Sha512* sha512) @@ -1337,7 +1397,7 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ - +#elif defined(STM32_HASH_SHA512) #else static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, size_t digestSz) @@ -1407,10 +1467,12 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, return initfp(sha512); } +#ifndef STM32_HASH_SHA512 int wc_Sha512Final(wc_Sha512* sha512, byte* hash) { return Sha512_Family_Final(sha512, hash, WC_SHA512_DIGEST_SIZE, InitSha512); } +#endif #endif /* WOLFSSL_KCAPI_HASH */ @@ -1592,6 +1654,64 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ +#elif defined(STM32_HASH_SHA384) + + int wc_InitSha384_ex(wc_Sha384* sha384, void* heap, int devId) + { + if (sha384 == NULL) + return BAD_FUNC_ARG; + + (void)devId; + (void)heap; + + XMEMSET(sha384, 0, sizeof(wc_Sha384)); + wc_Stm32_Hash_Init(&sha384->stmCtx); + return 0; + } + + int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) + { + int ret = 0; + + if (sha384 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Update(&sha384->stmCtx, + HASH_ALGOSELECTION_SHA384, data, len, WC_SHA384_BLOCK_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + return ret; + } + + int wc_Sha384Final(wc_Sha384* sha384, byte* hash) + { + int ret = 0; + + if (sha384 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Final(&sha384->stmCtx, + HASH_ALGOSELECTION_SHA384, hash, WC_SHA384_DIGEST_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + + (void)wc_InitSha384(sha384); /* reset state */ + + return ret; + } #else @@ -2011,17 +2131,75 @@ int wc_Sha512GetFlags(wc_Sha512* sha512, word32* flags) #if !defined(WOLFSSL_NOSHA512_224) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) +#if defined(STM32_HASH_SHA512_224) +int wc_InitSha512_224_ex(wc_Sha512* sha512, void* heap, int devId) +{ + if (sha512 == NULL) + return BAD_FUNC_ARG; + + (void)devId; + (void)heap; + + XMEMSET(sha512, 0, sizeof(wc_Sha512)); + wc_Stm32_Hash_Init(&sha512->stmCtx); + return 0; +} + +int wc_Sha512_224Update(wc_Sha512* sha512, const byte* data, word32 len) +{ + int ret = 0; + + if (sha512 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Update(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512_224, data, len, WC_SHA512_224_BLOCK_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + return ret; +} + +int wc_Sha512_224Final(wc_Sha512* sha512, byte* hash) +{ + int ret = 0; + + if (sha512 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Final(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512_224, hash, WC_SHA512_224_DIGEST_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + + (void)wc_InitSha512_224(sha512); /* reset state */ + + return ret; +} +#endif int wc_InitSha512_224(wc_Sha512* sha) { return wc_InitSha512_224_ex(sha, NULL, INVALID_DEVID); } - +#if !defined(STM32_HASH_SHA512_224) int wc_Sha512_224Update(wc_Sha512* sha, const byte* data, word32 len) { return wc_Sha512Update(sha, data, len); } - +#endif #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ #elif defined(WOLFSSL_RENESAS_RSIP) && \ @@ -2029,6 +2207,7 @@ int wc_Sha512_224Update(wc_Sha512* sha, const byte* data, word32 len) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ #elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) +#elif defined(STM32_HASH_SHA512_224) #else int wc_Sha512_224FinalRaw(wc_Sha512* sha, byte* hash) @@ -2091,16 +2270,75 @@ int wc_Sha512_224Transform(wc_Sha512* sha, const unsigned char* data) #if !defined(WOLFSSL_NOSHA512_256) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST) +#if defined(STM32_HASH_SHA512_256) + int wc_InitSha512_256_ex(wc_Sha512* sha512, void* heap, int devId) + { + if (sha512 == NULL) + return BAD_FUNC_ARG; + + (void)devId; + (void)heap; + + XMEMSET(sha512, 0, sizeof(wc_Sha512)); + wc_Stm32_Hash_Init(&sha512->stmCtx); + return 0; + } + + int wc_Sha512_256Update(wc_Sha512* sha512, const byte* data, word32 len) + { + int ret = 0; + + if (sha512 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Update(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512_256, data, len, WC_SHA512_256_BLOCK_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + return ret; + } + + int wc_Sha512_256Final(wc_Sha512* sha512, byte* hash) + { + int ret = 0; + + if (sha512 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + ret = wolfSSL_CryptHwMutexLock(); + if (ret == 0) { + ret = wc_Stm32_Hash_Final(&sha512->stmCtx, + HASH_ALGOSELECTION_SHA512_256, hash, WC_SHA512_256_DIGEST_SIZE); + wolfSSL_CryptHwMutexUnLock(); + } + + (void)wc_InitSha512_256(sha512); /* reset state */ + + return ret; + } +#endif int wc_InitSha512_256(wc_Sha512* sha) { return wc_InitSha512_256_ex(sha, NULL, INVALID_DEVID); } - +#if !defined(STM32_HASH_SHA512_256) int wc_Sha512_256Update(wc_Sha512* sha, const byte* data, word32 len) { return wc_Sha512Update(sha, data, len); } +#endif #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ #elif defined(WOLFSSL_RENESAS_RSIP) && \ @@ -2108,7 +2346,7 @@ int wc_Sha512_256Update(wc_Sha512* sha, const byte* data, word32 len) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ #elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - +#elif defined(STM32_HASH_SHA512_256) #else int wc_Sha512_256FinalRaw(wc_Sha512* sha, byte* hash) { @@ -2176,6 +2414,7 @@ int wc_Sha512_256Transform(wc_Sha512* sha, const unsigned char* data) /* functions defined in wolfcrypt/src/port/renesas/renesas_fspsm_sha.c */ #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ + #else int wc_Sha384GetHash(wc_Sha384* sha384, byte* hash) diff --git a/src/wolfcrypt/src/signature.c b/src/wolfcrypt/src/signature.c index 09ae526..83c92d8 100644 --- a/src/wolfcrypt/src/signature.c +++ b/src/wolfcrypt/src/signature.c @@ -48,6 +48,16 @@ /* Signature wrapper disabled check */ #ifndef NO_SIG_WRAPPER +#if !defined(NO_RSA) && defined(NO_ASN) + #ifndef MAX_DER_DIGEST_ASN_SZ + #define MAX_DER_DIGEST_ASN_SZ 36 + #endif + #ifndef MAX_ENCODED_SIG_SZ + #define MAX_ENCODED_SIG_SZ 1024 /* Supports 8192 bit keys */ + #endif +#endif + + #if !defined(NO_RSA) && defined(WOLFSSL_CRYPTOCELL) extern int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode); @@ -225,7 +235,8 @@ int wc_SignatureVerifyHash( WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) - ret = wc_RsaSSL_VerifyInline(plain_data, sig_len, &plain_ptr, (RsaKey*)key); + ret = wc_RsaSSL_VerifyInline(plain_data, sig_len, + &plain_ptr, (RsaKey*)key); } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E)); if (ret >= 0 && plain_ptr) { if ((word32)ret == hash_len && diff --git a/src/wolfcrypt/src/siphash.c b/src/wolfcrypt/src/siphash.c index 54c02f6..b7c63c3 100644 --- a/src/wolfcrypt/src/siphash.c +++ b/src/wolfcrypt/src/siphash.c @@ -69,14 +69,14 @@ * @param [in] a Little-endian byte array. * @return 64-bit number. */ -#define GET_U64(a) (*(word64*)(a)) +#define GET_U64(a) readUnalignedWord64(a) /** * Decode little-endian byte array to 32-bit number. * * @param [in] a Little-endian byte array. * @return 32-bit number. */ -#define GET_U32(a) (*(word32*)(a)) +#define GET_U32(a) readUnalignedWord32(a) /** * Decode little-endian byte array to 16-bit number. * @@ -90,7 +90,7 @@ * @param [out] a Byte array to write into. * @param [in] n Number to encode. */ -#define SET_U64(a, n) ((*(word64*)(a)) = (n)) +#define SET_U64(a, n) writeUnalignedWord64(a, n) #else /** * Decode little-endian byte array to 64-bit number. @@ -112,7 +112,7 @@ * @param [in] a Little-endian byte array. * @return 32-bit number. */ -#define GET_U32(a) (((word64)((a)[3]) << 24) | \ +#define GET_U32(a) (((word32)((a)[3]) << 24) | \ ((word32)((a)[2]) << 16) | \ ((word32)((a)[1]) << 8) | \ ((word32)((a)[0]) )) @@ -256,14 +256,14 @@ int wc_SipHashUpdate(SipHash* sipHash, const unsigned char* in, word32 inSz) if ((ret == 0) && (inSz > 0)) { /* Add to cache if already started. */ if (sipHash->cacheCnt > 0) { - byte len = SIPHASH_BLOCK_SIZE - sipHash->cacheCnt; + byte len = (byte)(SIPHASH_BLOCK_SIZE - sipHash->cacheCnt); if (len > inSz) { len = (byte)inSz; } XMEMCPY(sipHash->cache + sipHash->cacheCnt, in, len); in += len; inSz -= len; - sipHash->cacheCnt += len; + sipHash->cacheCnt = (byte)(sipHash->cacheCnt + len); if (sipHash->cacheCnt == SIPHASH_BLOCK_SIZE) { /* Compress the block from the cache. */ @@ -331,7 +331,7 @@ int wc_SipHashFinal(SipHash* sipHash, unsigned char* out, unsigned char outSz) if (ret == 0) { /* Put in remaining cached message bytes. */ - XMEMSET(sipHash->cache + sipHash->cacheCnt, 0, 7 - sipHash->cacheCnt); + XMEMSET(sipHash->cache + sipHash->cacheCnt, 0, 7U - sipHash->cacheCnt); sipHash->cache[7] = (byte)(sipHash->inCnt + sipHash->cacheCnt); SipHashCompress(sipHash, sipHash->cache); diff --git a/src/wolfcrypt/src/sp_arm32.c b/src/wolfcrypt/src/sp_arm32.c index 68449be..13f5578 100644 --- a/src/wolfcrypt/src/sp_arm32.c +++ b/src/wolfcrypt/src/sp_arm32.c @@ -93,7 +93,8 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -104,12 +105,20 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -2756,7 +2765,7 @@ static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -2803,7 +2812,7 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -2853,7 +2862,7 @@ static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -2993,7 +3002,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -3071,7 +3080,7 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -3271,7 +3280,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -3405,7 +3414,7 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -5082,7 +5091,7 @@ static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -5167,7 +5176,7 @@ static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -5280,7 +5289,7 @@ static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -5356,7 +5365,7 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -5393,7 +5402,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -5811,7 +5820,7 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -5848,7 +5857,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -8451,7 +8460,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -8590,7 +8599,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -11304,7 +11313,7 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -11442,7 +11451,7 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -11841,7 +11850,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -12277,7 +12286,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -12528,7 +12537,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -15425,7 +15434,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -15559,7 +15568,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -15619,7 +15628,7 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -15757,7 +15766,7 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -16612,7 +16621,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -17170,7 +17179,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -17309,7 +17318,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -18287,7 +18296,8 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -18298,12 +18308,20 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -23971,7 +23989,7 @@ static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -24032,7 +24050,7 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -24096,7 +24114,7 @@ static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -24268,7 +24286,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -24374,7 +24392,7 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -24630,7 +24648,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -24820,7 +24838,7 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -27994,7 +28012,7 @@ static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -28093,7 +28111,7 @@ static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -28234,7 +28252,7 @@ static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -28310,7 +28328,7 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -28347,7 +28365,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -28765,7 +28783,7 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -28802,7 +28820,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -32429,7 +32447,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -32624,7 +32642,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -36522,7 +36540,7 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -36660,7 +36678,7 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -37235,7 +37253,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -37671,7 +37689,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -38034,7 +38052,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -42275,7 +42293,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -42465,7 +42483,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -42525,7 +42543,7 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -42663,7 +42681,7 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -43876,7 +43894,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -44434,7 +44452,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -44629,7 +44647,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -45799,7 +45817,8 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -45810,12 +45829,20 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -46186,7 +46213,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -46433,7 +46460,7 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Multiply a and b into r. (r = a * b) @@ -46549,7 +46576,7 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -46586,7 +46613,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -51236,7 +51263,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -51711,7 +51738,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -57297,7 +57324,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -57544,7 +57571,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -57604,7 +57631,7 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -57742,7 +57769,7 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -59307,7 +59334,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -59865,7 +59892,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -60116,7 +60143,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -65953,7 +65980,7 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -65990,7 +66017,7 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -66229,7 +66256,7 @@ static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, "lr", "r10" ); (void)m_p; - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Convert an mp_int to an array of sp_digit. @@ -71117,7 +71144,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_8(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint32_t p256_mod_minus_2[8] = { +static const word32 p256_mod_minus_2[8] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0x00000000U,0x00000000U,0x00000000U, 0x00000001U,0xffffffffU }; @@ -71323,7 +71350,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -71370,7 +71397,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -71425,7 +71452,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -74152,7 +74179,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -74180,7 +74207,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -76454,12 +76482,20 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -76833,7 +76869,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -76867,7 +76903,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -77299,7 +77335,7 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -77437,7 +77473,7 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -77540,7 +77576,7 @@ static void sp_256_mont_mul_order_8(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P256 curve. */ -static const uint32_t p256_order_minus_2[8] = { +static const word32 p256_order_minus_2[8] = { 0xfc63254fU,0xf3b9cac2U,0xa7179e84U,0xbce6faadU,0xffffffffU,0xffffffffU, 0x00000000U,0xffffffffU }; @@ -78122,7 +78158,7 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -78158,7 +78194,7 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -78329,7 +78365,7 @@ static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit } #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) -static const unsigned char L_sp_256_num_bits_8_table[] = { +static const byte L_sp_256_num_bits_8_table[] = { 0x00, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, @@ -78367,8 +78403,8 @@ static const unsigned char L_sp_256_num_bits_8_table[] = { static int sp_256_num_bits_8(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_256_num_bits_8_table_c asm ("r1") = - (unsigned char*)&L_sp_256_num_bits_8_table; + register byte* L_sp_256_num_bits_8_table_c asm ("r1") = + (byte*)&L_sp_256_num_bits_8_table; __asm__ __volatile__ ( "mov lr, %[L_sp_256_num_bits_8_table]\n\t" @@ -78685,7 +78721,7 @@ static int sp_256_num_bits_8(const sp_digit* a_p) : : "memory", "cc", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -78774,7 +78810,7 @@ static int sp_256_num_bits_8(const sp_digit* a_p) : : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_ARM_ARCH && (WOLFSSL_ARM_ARCH < 7) */ @@ -88809,7 +88845,7 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -88853,7 +88889,7 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -89191,7 +89227,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -89260,7 +89296,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -89961,7 +89997,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_12(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint32_t p384_mod_minus_2[12] = { +static const word32 p384_mod_minus_2[12] = { 0xfffffffdU,0x00000000U,0x00000000U,0xffffffffU,0xfffffffeU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; @@ -90227,7 +90263,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -90370,7 +90406,7 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -90413,7 +90449,7 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -90455,7 +90491,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -90524,7 +90560,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -91914,7 +91950,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -91942,7 +91978,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -94238,12 +94275,20 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -94617,7 +94662,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -94658,7 +94703,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -95218,7 +95263,7 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -95356,7 +95401,7 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -95463,13 +95508,13 @@ static void sp_384_mont_mul_order_12(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P384 curve. */ -static const uint32_t p384_order_minus_2[12] = { +static const word32 p384_order_minus_2[12] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; #else /* The low half of the order-2 of the P384 curve. */ -static const uint32_t p384_order_low[6] = { +static const word32 p384_order_low[6] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U }; #endif /* WOLFSSL_SP_SMALL */ @@ -96088,7 +96133,7 @@ static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi } #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) -static const unsigned char L_sp_384_num_bits_12_table[] = { +static const byte L_sp_384_num_bits_12_table[] = { 0x00, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, @@ -96126,8 +96171,8 @@ static const unsigned char L_sp_384_num_bits_12_table[] = { static int sp_384_num_bits_12(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_384_num_bits_12_table_c asm ("r1") = - (unsigned char*)&L_sp_384_num_bits_12_table; + register byte* L_sp_384_num_bits_12_table_c asm ("r1") = + (byte*)&L_sp_384_num_bits_12_table; __asm__ __volatile__ ( "mov lr, %[L_sp_384_num_bits_12_table]\n\t" @@ -96696,7 +96741,7 @@ static int sp_384_num_bits_12(const sp_digit* a_p) : : "memory", "cc", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -96845,7 +96890,7 @@ static int sp_384_num_bits_12(const sp_digit* a_p) : : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_ARM_ARCH && (WOLFSSL_ARM_ARCH < 7) */ @@ -115266,7 +115311,7 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -115321,7 +115366,7 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -115576,7 +115621,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -115664,7 +115709,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -116954,7 +116999,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_17(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint32_t p521_mod_minus_2[17] = { +static const word32 p521_mod_minus_2[17] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU @@ -117272,7 +117317,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -119114,7 +119159,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -119142,7 +119187,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -122011,12 +122057,20 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -122837,7 +122891,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -122889,7 +122943,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -123609,7 +123663,7 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -123747,7 +123801,7 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -123861,14 +123915,14 @@ static void sp_521_mont_mul_order_17(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P521 curve. */ -static const uint32_t p521_order_minus_2[17] = { +static const word32 p521_order_minus_2[17] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU }; #else /* The low half of the order-2 of the P521 curve. */ -static const uint32_t p521_order_low[9] = { +static const word32 p521_order_low[9] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU }; @@ -124438,7 +124492,7 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -124492,7 +124546,7 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -124642,7 +124696,7 @@ static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi } #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) -static const unsigned char L_sp_521_num_bits_17_table[] = { +static const byte L_sp_521_num_bits_17_table[] = { 0x00, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, @@ -124680,8 +124734,8 @@ static const unsigned char L_sp_521_num_bits_17_table[] = { static int sp_521_num_bits_17(const sp_digit* a_p) { register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; - register unsigned char* L_sp_521_num_bits_17_table_c asm ("r1") = - (unsigned char*)&L_sp_521_num_bits_17_table; + register byte* L_sp_521_num_bits_17_table_c asm ("r1") = + (byte*)&L_sp_521_num_bits_17_table; __asm__ __volatile__ ( "mov lr, %[L_sp_521_num_bits_17_table]\n\t" @@ -125565,7 +125619,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) : : "memory", "cc", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -125789,7 +125843,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) : : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_ARM_ARCH && (WOLFSSL_ARM_ARCH < 7) */ @@ -126664,7 +126718,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint32_t p521_sqrt_power[17] = { +static const word32 p521_sqrt_power[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000080 @@ -141833,7 +141887,7 @@ static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -141908,7 +141962,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -141986,7 +142040,7 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -142104,7 +142158,7 @@ static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi : : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -142621,7 +142675,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -142663,7 +142717,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -142802,7 +142856,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -142842,7 +142896,7 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -144042,7 +144096,7 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -144180,7 +144234,7 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) : : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -144609,7 +144663,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) : : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -146471,7 +146525,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_32(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -147428,7 +147482,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -147567,7 +147621,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, : : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -148805,7 +148859,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -148833,7 +148887,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -156661,12 +156716,20 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } diff --git a/src/wolfcrypt/src/sp_arm64.c b/src/wolfcrypt/src/sp_arm64.c index 0a465f4..2825042 100644 --- a/src/wolfcrypt/src/sp_arm64.c +++ b/src/wolfcrypt/src/sp_arm64.c @@ -22738,7 +22738,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_4(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint64_t p256_mod_minus_2[4] = { +static const word64 p256_mod_minus_2[4] = { 0xfffffffffffffffdU,0x00000000ffffffffU,0x0000000000000000U, 0xffffffff00000001U }; @@ -24197,13 +24197,13 @@ static void sp_256_proj_point_add_sub_4(sp_point_256* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_256 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_256; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_4_6[66] = { +static const word8 recode_index_4_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -24212,7 +24212,7 @@ static const uint8_t recode_index_4_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_4_6[66] = { +static const word8 recode_neg_4_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -24230,7 +24230,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -24239,7 +24239,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -24253,12 +24253,12 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) } else if (++j < 4) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_4_6[y]; v[i].neg = recode_neg_4_6[y]; carry = (y >> 6) + v[i].neg; @@ -24905,7 +24905,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -24933,7 +24933,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i>= 7; @@ -27336,12 +27336,12 @@ static void sp_256_ecc_recode_7_4(const sp_digit* k, ecc_recode_256* v) } else if (++j < 4) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_4_7[y]; v[i].neg = recode_neg_4_7[y]; carry = (y >> 7) + v[i].neg; @@ -39445,7 +39445,7 @@ static int sp_256_ecc_mulmod_add_only_4(sp_point_256* r, const sp_point_256* g, p->infinity = !v[i].i; sp_256_sub_4(negy, p256_mod, p->y); sp_256_norm_4(negy); - sp_256_cond_copy_4(p->y, negy, 0 - v[i].neg); + sp_256_cond_copy_4(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_256_proj_point_add_qz1_4(rt, rt, p, tmp); } if (map != 0) { @@ -40519,7 +40519,7 @@ SP_NOINLINE static void sp_256_mont_mul_order_4(sp_digit* r, #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P256 curve. */ -static const uint64_t p256_order_minus_2[4] = { +static const word64 p256_order_minus_2[4] = { 0xf3b9cac2fc63254fU,0xbce6faada7179e84U,0xffffffffffffffffU, 0xffffffff00000000U }; @@ -43944,7 +43944,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_6(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint64_t p384_mod_minus_2[6] = { +static const word64 p384_mod_minus_2[6] = { 0x00000000fffffffdU,0xffffffff00000000U,0xfffffffffffffffeU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU }; @@ -45159,13 +45159,13 @@ static void sp_384_proj_point_add_sub_6(sp_point_384* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_384 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_384; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_6_6[66] = { +static const word8 recode_index_6_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -45174,7 +45174,7 @@ static const uint8_t recode_index_6_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_6_6[66] = { +static const word8 recode_neg_6_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -45192,7 +45192,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -45201,7 +45201,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -45215,12 +45215,12 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) } else if (++j < 6) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_6_6[y]; v[i].neg = recode_neg_6_6[y]; carry = (y >> 6) + v[i].neg; @@ -45831,7 +45831,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -45859,7 +45859,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i>= 7; @@ -48262,12 +48262,12 @@ static void sp_384_ecc_recode_7_6(const sp_digit* k, ecc_recode_384* v) } else if (++j < 6) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_6_7[y]; v[i].neg = recode_neg_6_7[y]; carry = (y >> 7) + v[i].neg; @@ -66185,7 +66185,7 @@ static int sp_384_ecc_mulmod_add_only_6(sp_point_384* r, const sp_point_384* g, p->infinity = !v[i].i; sp_384_sub_6(negy, p384_mod, p->y); sp_384_norm_6(negy); - sp_384_cond_copy_6(p->y, negy, 0 - v[i].neg); + sp_384_cond_copy_6(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_384_proj_point_add_qz1_6(rt, rt, p, tmp); } if (map != 0) { @@ -67122,13 +67122,13 @@ static void sp_384_mont_mul_order_6(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P384 curve. */ -static const uint64_t p384_order_minus_2[6] = { +static const word64 p384_order_minus_2[6] = { 0xecec196accc52971U,0x581a0db248b0a77aU,0xc7634d81f4372ddfU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU }; #else /* The low half of the order-2 of the P384 curve. */ -static const uint64_t p384_order_low[3] = { +static const word64 p384_order_low[3] = { 0xecec196accc52971U,0x581a0db248b0a77aU,0xc7634d81f4372ddfU }; #endif /* WOLFSSL_SP_SMALL */ @@ -72112,7 +72112,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_9(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint64_t p521_mod_minus_2[9] = { +static const word64 p521_mod_minus_2[9] = { 0xfffffffffffffffdU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0x00000000000001ffU @@ -73516,13 +73516,13 @@ static void sp_521_proj_point_add_sub_9(sp_point_521* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_521 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_521; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_9_6[66] = { +static const word8 recode_index_9_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -73531,7 +73531,7 @@ static const uint8_t recode_index_9_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_9_6[66] = { +static const word8 recode_neg_9_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -73549,7 +73549,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -73558,7 +73558,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -73572,12 +73572,12 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_6[y]; v[i].neg = recode_neg_9_6[y]; carry = (y >> 6) + v[i].neg; @@ -74233,7 +74233,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -74261,7 +74261,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i>= 7; @@ -77318,12 +77318,12 @@ static void sp_521_ecc_recode_7_9(const sp_digit* k, ecc_recode_521* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_7[y]; v[i].neg = recode_neg_9_7[y]; carry = (y >> 7) + v[i].neg; @@ -111319,7 +111319,7 @@ static int sp_521_ecc_mulmod_add_only_9(sp_point_521* r, const sp_point_521* g, p->infinity = !v[i].i; sp_521_sub_9(negy, p521_mod, p->y); sp_521_norm_9(negy); - sp_521_cond_copy_9(p->y, negy, 0 - v[i].neg); + sp_521_cond_copy_9(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_521_proj_point_add_qz1_9(rt, rt, p, tmp); } if (map != 0) { @@ -111996,14 +111996,14 @@ static void sp_521_mont_mul_order_9(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P521 curve. */ -static const uint64_t p521_order_minus_2[9] = { +static const word64 p521_order_minus_2[9] = { 0xbb6fb71e91386407U,0x3bb5c9b8899c47aeU,0x7fcc0148f709a5d0U, 0x51868783bf2f966bU,0xfffffffffffffffaU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0x00000000000001ffU }; #else /* The low half of the order-2 of the P521 curve. */ -static const uint64_t p521_order_low[5] = { +static const word64 p521_order_low[5] = { 0xbb6fb71e91386407U,0x3bb5c9b8899c47aeU,0x7fcc0148f709a5d0U, 0x51868783bf2f966bU,0xfffffffffffffffaU }; @@ -113493,7 +113493,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint64_t p521_sqrt_power[9] = { +static const word64 p521_sqrt_power[9] = { 0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000080 @@ -116078,7 +116078,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_16(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -117595,13 +117595,13 @@ static void sp_1024_proj_point_add_sub_16(sp_point_1024* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_1024 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_1024; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_16_7[130] = { +static const word8 recode_index_16_7[130] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -117614,7 +117614,7 @@ static const uint8_t recode_index_16_7[130] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_16_7[130] = { +static const word8 recode_neg_16_7[130] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -117636,7 +117636,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -117645,7 +117645,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -117659,12 +117659,12 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) } else if (++j < 16) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_16_7[y]; v[i].neg = recode_neg_16_7[y]; carry = (y >> 7) + v[i].neg; @@ -118133,7 +118133,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -118161,7 +118161,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -104,12 +105,20 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -9528,7 +9537,7 @@ SP_NOINLINE static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Add b to a into r. (r = a + b) @@ -9616,7 +9625,7 @@ SP_NOINLINE static sp_digit sp_2048_add_word_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -9781,7 +9790,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_in_place_16(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -9940,7 +9949,7 @@ SP_NOINLINE static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -10155,7 +10164,7 @@ SP_NOINLINE static sp_digit sp_2048_add_word_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -10464,7 +10473,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_in_place_32(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -10759,7 +10768,7 @@ SP_NOINLINE static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -11106,7 +11115,7 @@ SP_NOINLINE static sp_digit sp_2048_add_word_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -11703,7 +11712,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_in_place_64(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -12270,7 +12279,7 @@ SP_NOINLINE static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -19367,7 +19376,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -19560,7 +19569,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -19889,7 +19898,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -20005,7 +20014,7 @@ SP_NOINLINE static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -20084,7 +20093,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_in_place_64(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -20881,7 +20890,7 @@ SP_NOINLINE static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -20954,7 +20963,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_in_place_32(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -21925,7 +21934,7 @@ SP_NOINLINE static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_2048_mont_reduce_order_64 sp_2048_mont_reduce_64 @@ -23824,7 +23833,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* Compare a with b in constant time. @@ -23933,7 +23942,7 @@ SP_NOINLINE static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -24397,7 +24406,7 @@ SP_NOINLINE static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_2048_mont_reduce_order_64 sp_2048_mont_reduce_64 @@ -26122,7 +26131,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -26689,7 +26698,7 @@ SP_NOINLINE static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -27306,7 +27315,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -27519,7 +27528,7 @@ SP_NOINLINE static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -28105,7 +28114,7 @@ SP_NOINLINE static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* RSA private key operation. @@ -30275,7 +30284,8 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -30286,12 +30296,20 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -50970,7 +50988,7 @@ SP_NOINLINE static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Add b to a into r. (r = a + b) @@ -51090,7 +51108,7 @@ SP_NOINLINE static sp_digit sp_3072_add_word_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -51327,7 +51345,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_in_place_24(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -51554,7 +51572,7 @@ SP_NOINLINE static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -51837,7 +51855,7 @@ SP_NOINLINE static sp_digit sp_3072_add_word_24(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -52290,7 +52308,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_in_place_48(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -52721,7 +52739,7 @@ SP_NOINLINE static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -53196,7 +53214,7 @@ SP_NOINLINE static sp_digit sp_3072_add_word_48(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -54081,7 +54099,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_in_place_96(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -54920,7 +54938,7 @@ SP_NOINLINE static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -70307,7 +70325,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -70568,7 +70586,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -71033,7 +71051,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -71149,7 +71167,7 @@ SP_NOINLINE static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -71228,7 +71246,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_in_place_96(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -72050,7 +72068,7 @@ SP_NOINLINE static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -72123,7 +72141,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_in_place_48(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -73109,7 +73127,7 @@ SP_NOINLINE static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_3072_mont_reduce_order_96 sp_3072_mont_reduce_96 @@ -75280,7 +75298,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* Compare a with b in constant time. @@ -75389,7 +75407,7 @@ SP_NOINLINE static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -75853,7 +75871,7 @@ SP_NOINLINE static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_3072_mont_reduce_order_96 sp_3072_mont_reduce_96 @@ -78132,7 +78150,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -78971,7 +78989,7 @@ SP_NOINLINE static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -79588,7 +79606,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -79806,7 +79824,7 @@ SP_NOINLINE static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -80392,7 +80410,7 @@ SP_NOINLINE static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* RSA private key operation. @@ -83360,7 +83378,8 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -83371,12 +83390,20 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -84040,7 +84067,7 @@ SP_NOINLINE static sp_digit sp_4096_add_word_64(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -85213,7 +85240,7 @@ SP_NOINLINE static sp_digit sp_4096_sub_in_place_128(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -86324,7 +86351,7 @@ SP_NOINLINE static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Multiply a and b into r. (r = a * b) @@ -86477,7 +86504,7 @@ SP_NOINLINE static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -86556,7 +86583,7 @@ SP_NOINLINE static sp_digit sp_4096_sub_in_place_128(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -87581,7 +87608,7 @@ SP_NOINLINE static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_4096_mont_reduce_order_128 sp_4096_mont_reduce_128 @@ -90404,7 +90431,7 @@ SP_NOINLINE static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -91515,7 +91542,7 @@ SP_NOINLINE static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -92132,7 +92159,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -92351,7 +92378,7 @@ SP_NOINLINE static sp_int32 sp_4096_cmp_128(const sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -92942,7 +92969,7 @@ SP_NOINLINE static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* RSA private key operation. @@ -97455,7 +97482,7 @@ SP_NOINLINE static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -97547,7 +97574,7 @@ SP_NOINLINE static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -98858,7 +98885,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_8(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint32_t p256_mod_minus_2[8] = { +static const word32 p256_mod_minus_2[8] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0x00000000U,0x00000000U,0x00000000U, 0x00000001U,0xffffffffU }; @@ -99039,7 +99066,7 @@ SP_NOINLINE static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -99108,7 +99135,7 @@ SP_NOINLINE static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Map the Montgomery form projective coordinate point to an affine point. @@ -101546,7 +101573,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -101574,7 +101601,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -103906,12 +103934,20 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -104321,7 +104357,7 @@ SP_NOINLINE static sp_digit sp_256_sub_in_place_8(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -104415,7 +104451,7 @@ SP_NOINLINE static sp_digit sp_256_sub_in_place_8(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -105218,7 +105254,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* AND m into each word of a and store in r. @@ -105321,7 +105357,7 @@ static void sp_256_mont_mul_order_8(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P256 curve. */ -static const uint32_t p256_order_minus_2[8] = { +static const word32 p256_order_minus_2[8] = { 0xfc63254fU,0xf3b9cac2U,0xa7179e84U,0xbce6faadU,0xffffffffU,0xffffffffU, 0x00000000U,0xffffffffU }; @@ -105933,7 +105969,7 @@ SP_NOINLINE static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -106024,7 +106060,7 @@ SP_NOINLINE static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -107206,7 +107242,7 @@ static int sp_256_num_bits_8(sp_digit* a) : : "memory", "r2", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -109018,7 +109054,7 @@ SP_NOINLINE static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -109144,7 +109180,7 @@ SP_NOINLINE static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -109504,7 +109540,7 @@ SP_NOINLINE static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #define sp_384_mont_reduce_order_12 sp_384_mont_reduce_12 @@ -110286,7 +110322,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_12(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint32_t p384_mod_minus_2[12] = { +static const word32 p384_mod_minus_2[12] = { 0xfffffffdU,0x00000000U,0x00000000U,0xffffffffU,0xfffffffeU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; @@ -110483,7 +110519,7 @@ SP_NOINLINE static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -110645,7 +110681,7 @@ SP_NOINLINE static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -110770,7 +110806,7 @@ SP_NOINLINE static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -110840,7 +110876,7 @@ SP_NOINLINE static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Subtract two Montgomery form numbers (r = a - b % m). @@ -112394,7 +112430,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -112422,7 +112458,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -114806,12 +114843,20 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -115221,7 +115266,7 @@ SP_NOINLINE static sp_digit sp_384_sub_in_place_12(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -115351,7 +115396,7 @@ SP_NOINLINE static sp_digit sp_384_sub_in_place_12(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -116154,7 +116199,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* AND m into each word of a and store in r. @@ -116261,13 +116306,13 @@ static void sp_384_mont_mul_order_12(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P384 curve. */ -static const uint32_t p384_order_minus_2[12] = { +static const word32 p384_order_minus_2[12] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; #else /* The low half of the order-2 of the P384 curve. */ -static const uint32_t p384_order_low[6] = { +static const word32 p384_order_low[6] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U }; #endif /* WOLFSSL_SP_SMALL */ @@ -118378,7 +118423,7 @@ static int sp_384_num_bits_12(sp_digit* a) : : "memory", "r2", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -120236,7 +120281,7 @@ SP_NOINLINE static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -120406,7 +120451,7 @@ SP_NOINLINE static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -120683,7 +120728,7 @@ SP_NOINLINE static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Reduce the number back to 521 bits using Montgomery reduction. @@ -122551,7 +122596,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_17(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint32_t p521_mod_minus_2[17] = { +static const word32 p521_mod_minus_2[17] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU @@ -122745,7 +122790,7 @@ SP_NOINLINE static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -124328,7 +124373,7 @@ SP_NOINLINE static sp_digit sp_521_cond_add_17(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Right shift a by 1 bit into r. (r = a >> 1) @@ -126018,7 +126063,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -126046,7 +126091,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -129039,12 +129085,20 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -131093,7 +131147,7 @@ SP_NOINLINE static sp_digit sp_521_sub_in_place_17(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -131269,7 +131323,7 @@ SP_NOINLINE static sp_digit sp_521_sub_in_place_17(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -132072,7 +132126,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* AND m into each word of a and store in r. @@ -132186,14 +132240,14 @@ static void sp_521_mont_mul_order_17(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P521 curve. */ -static const uint32_t p521_order_minus_2[17] = { +static const word32 p521_order_minus_2[17] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU }; #else /* The low half of the order-2 of the P521 curve. */ -static const uint32_t p521_order_low[9] = { +static const word32 p521_order_low[9] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU }; @@ -132788,7 +132842,7 @@ SP_NOINLINE static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -132957,7 +133011,7 @@ SP_NOINLINE static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -135289,7 +135343,7 @@ static int sp_521_num_bits_17(sp_digit* a) : : "memory", "r2", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -136163,7 +136217,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint32_t p521_sqrt_power[17] = { +static const word32 p521_sqrt_power[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000080 @@ -199361,7 +199415,7 @@ SP_NOINLINE static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Add b to a into r. (r = a + b) @@ -199513,7 +199567,7 @@ SP_NOINLINE static sp_digit sp_1024_add_word_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -199822,7 +199876,7 @@ SP_NOINLINE static sp_digit sp_1024_sub_in_place_32(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -200117,7 +200171,7 @@ SP_NOINLINE static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -200342,7 +200396,7 @@ SP_NOINLINE static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -201213,7 +201267,7 @@ SP_NOINLINE static sp_digit sp_1024_sub_in_place_32(sp_digit* a, : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -201277,7 +201331,7 @@ SP_NOINLINE static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #ifdef WOLFSSL_SP_SMALL @@ -201351,7 +201405,7 @@ SP_NOINLINE static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -202154,7 +202208,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } /* AND m into each word of a and store in r. @@ -202293,7 +202347,7 @@ SP_NOINLINE static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -203744,7 +203798,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_32(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -208907,7 +208961,7 @@ SP_NOINLINE static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Right shift a by 1 bit into r. (r = a >> 1) @@ -210617,7 +210671,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -210645,7 +210699,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -218473,12 +218528,20 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } diff --git a/src/wolfcrypt/src/sp_c32.c b/src/wolfcrypt/src/sp_c32.c index 9520f86..a1f0eb2 100644 --- a/src/wolfcrypt/src/sp_c32.c +++ b/src/wolfcrypt/src/sp_c32.c @@ -20945,7 +20945,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_9(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint32_t p256_mod_minus_2[8] = { +static const word32 p256_mod_minus_2[8] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0x00000000U,0x00000000U,0x00000000U, 0x00000001U,0xffffffffU }; @@ -22385,13 +22385,13 @@ static void sp_256_proj_point_add_sub_9(sp_point_256* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_256 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_256; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_9_6[66] = { +static const word8 recode_index_9_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -22400,7 +22400,7 @@ static const uint8_t recode_index_9_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_9_6[66] = { +static const word8 recode_neg_9_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -22418,7 +22418,7 @@ static void sp_256_ecc_recode_6_9(const sp_digit* k, ecc_recode_256* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -22427,7 +22427,7 @@ static void sp_256_ecc_recode_6_9(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 29) { y &= 0x3f; n >>= 6; @@ -22441,12 +22441,12 @@ static void sp_256_ecc_recode_6_9(const sp_digit* k, ecc_recode_256* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (29 - o)) & 0x3f); + y |= (word8)((n << (29 - o)) & 0x3f); o -= 23; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_6[y]; v[i].neg = recode_neg_9_6[y]; carry = (y >> 6) + v[i].neg; @@ -23046,7 +23046,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -23074,7 +23074,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i> 4; v |= v >> 8; v |= v >> 16; - return sp_256_tab32_9[(uint32_t)(v*0x07C4ACDD) >> 27]; + return sp_256_tab32_9[(word32)(v*0x07C4ACDD) >> 27]; } static int sp_256_num_bits_9(const sp_digit* a) @@ -28328,7 +28328,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_15(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint32_t p384_mod_minus_2[12] = { +static const word32 p384_mod_minus_2[12] = { 0xfffffffdU,0x00000000U,0x00000000U,0xffffffffU,0xfffffffeU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; @@ -29854,13 +29854,13 @@ static void sp_384_proj_point_add_sub_15(sp_point_384* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_384 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_384; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_15_6[66] = { +static const word8 recode_index_15_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -29869,7 +29869,7 @@ static const uint8_t recode_index_15_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_15_6[66] = { +static const word8 recode_neg_15_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -29887,7 +29887,7 @@ static void sp_384_ecc_recode_6_15(const sp_digit* k, ecc_recode_384* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -29896,7 +29896,7 @@ static void sp_384_ecc_recode_6_15(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 26) { y &= 0x3f; n >>= 6; @@ -29910,12 +29910,12 @@ static void sp_384_ecc_recode_6_15(const sp_digit* k, ecc_recode_384* v) } else if (++j < 15) { n = k[j]; - y |= (uint8_t)((n << (26 - o)) & 0x3f); + y |= (word8)((n << (26 - o)) & 0x3f); o -= 20; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_15_6[y]; v[i].neg = recode_neg_15_6[y]; carry = (y >> 6) + v[i].neg; @@ -30575,7 +30575,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -30603,7 +30603,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i> 4; v |= v >> 8; v |= v >> 16; - return sp_384_tab32_15[(uint32_t)(v*0x07C4ACDD) >> 27]; + return sp_384_tab32_15[(word32)(v*0x07C4ACDD) >> 27]; } static int sp_384_num_bits_15(const sp_digit* a) @@ -35976,7 +35976,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_21(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint32_t p521_mod_minus_2[17] = { +static const word32 p521_mod_minus_2[17] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU @@ -37373,13 +37373,13 @@ static void sp_521_proj_point_add_sub_21(sp_point_521* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_521 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_521; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_21_6[66] = { +static const word8 recode_index_21_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -37388,7 +37388,7 @@ static const uint8_t recode_index_21_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_21_6[66] = { +static const word8 recode_neg_21_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -37406,7 +37406,7 @@ static void sp_521_ecc_recode_6_21(const sp_digit* k, ecc_recode_521* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -37415,7 +37415,7 @@ static void sp_521_ecc_recode_6_21(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 25) { y &= 0x3f; n >>= 6; @@ -37429,12 +37429,12 @@ static void sp_521_ecc_recode_6_21(const sp_digit* k, ecc_recode_521* v) } else if (++j < 21) { n = k[j]; - y |= (uint8_t)((n << (25 - o)) & 0x3f); + y |= (word8)((n << (25 - o)) & 0x3f); o -= 19; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_21_6[y]; v[i].neg = recode_neg_21_6[y]; carry = (y >> 6) + v[i].neg; @@ -38154,7 +38154,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -38182,7 +38182,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i> 4; v |= v >> 8; v |= v >> 16; - return sp_521_tab32_21[(uint32_t)(v*0x07C4ACDD) >> 27]; + return sp_521_tab32_21[(word32)(v*0x07C4ACDD) >> 27]; } static int sp_521_num_bits_21(const sp_digit* a) @@ -43092,7 +43092,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint32_t p521_sqrt_power[17] = { +static const word32 p521_sqrt_power[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000080 @@ -44810,7 +44810,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_42(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -46182,13 +46182,13 @@ static void sp_1024_proj_point_add_sub_42(sp_point_1024* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_1024 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_1024; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_42_7[130] = { +static const word8 recode_index_42_7[130] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -46201,7 +46201,7 @@ static const uint8_t recode_index_42_7[130] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_42_7[130] = { +static const word8 recode_neg_42_7[130] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -46223,7 +46223,7 @@ static void sp_1024_ecc_recode_7_42(const sp_digit* k, ecc_recode_1024* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -46232,7 +46232,7 @@ static void sp_1024_ecc_recode_7_42(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 7 < 25) { y &= 0x7f; n >>= 7; @@ -46246,12 +46246,12 @@ static void sp_1024_ecc_recode_7_42(const sp_digit* k, ecc_recode_1024* v) } else if (++j < 42) { n = k[j]; - y |= (uint8_t)((n << (25 - o)) & 0x7f); + y |= (word8)((n << (25 - o)) & 0x7f); o -= 18; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_42_7[y]; v[i].neg = recode_neg_42_7[y]; carry = (y >> 7) + v[i].neg; @@ -46714,7 +46714,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -46742,7 +46742,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i>= 6; @@ -23377,12 +23377,12 @@ static void sp_256_ecc_recode_6_5(const sp_digit* k, ecc_recode_256* v) } else if (++j < 5) { n = k[j]; - y |= (uint8_t)((n << (52 - o)) & 0x3f); + y |= (word8)((n << (52 - o)) & 0x3f); o -= 46; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_5_6[y]; v[i].neg = recode_neg_5_6[y]; carry = (y >> 6) + v[i].neg; @@ -23942,7 +23942,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -23970,7 +23970,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i> 8; v |= v >> 16; v |= v >> 32; - return sp_256_tab64_5[((uint64_t)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; + return sp_256_tab64_5[((word64)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; } static int sp_256_num_bits_5(const sp_digit* a) @@ -28793,7 +28793,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_7(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint64_t p384_mod_minus_2[6] = { +static const word64 p384_mod_minus_2[6] = { 0x00000000fffffffdU,0xffffffff00000000U,0xfffffffffffffffeU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU }; @@ -30257,13 +30257,13 @@ static void sp_384_proj_point_add_sub_7(sp_point_384* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_384 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_384; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_7_6[66] = { +static const word8 recode_index_7_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -30272,7 +30272,7 @@ static const uint8_t recode_index_7_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_7_6[66] = { +static const word8 recode_neg_7_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -30290,7 +30290,7 @@ static void sp_384_ecc_recode_6_7(const sp_digit* k, ecc_recode_384* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -30299,7 +30299,7 @@ static void sp_384_ecc_recode_6_7(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 55) { y &= 0x3f; n >>= 6; @@ -30313,12 +30313,12 @@ static void sp_384_ecc_recode_6_7(const sp_digit* k, ecc_recode_384* v) } else if (++j < 7) { n = k[j]; - y |= (uint8_t)((n << (55 - o)) & 0x3f); + y |= (word8)((n << (55 - o)) & 0x3f); o -= 49; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_7_6[y]; v[i].neg = recode_neg_7_6[y]; carry = (y >> 6) + v[i].neg; @@ -30898,7 +30898,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -30926,7 +30926,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i> 8; v |= v >> 16; v |= v >> 32; - return sp_384_tab64_7[((uint64_t)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; + return sp_384_tab64_7[((word64)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; } static int sp_384_num_bits_7(const sp_digit* a) @@ -36306,7 +36306,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_9(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint64_t p521_mod_minus_2[9] = { +static const word64 p521_mod_minus_2[9] = { 0xfffffffffffffffdU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0x00000000000001ffU @@ -37654,13 +37654,13 @@ static void sp_521_proj_point_add_sub_9(sp_point_521* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_521 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_521; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_9_6[66] = { +static const word8 recode_index_9_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -37669,7 +37669,7 @@ static const uint8_t recode_index_9_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_9_6[66] = { +static const word8 recode_neg_9_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -37687,7 +37687,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -37696,7 +37696,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 58) { y &= 0x3f; n >>= 6; @@ -37710,12 +37710,12 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (58 - o)) & 0x3f); + y |= (word8)((n << (58 - o)) & 0x3f); o -= 52; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_6[y]; v[i].neg = recode_neg_9_6[y]; carry = (y >> 6) + v[i].neg; @@ -38315,7 +38315,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -38343,7 +38343,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i> 8; v |= v >> 16; v |= v >> 32; - return sp_521_tab64_9[((uint64_t)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; + return sp_521_tab64_9[((word64)((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58]; } static int sp_521_num_bits_9(const sp_digit* a) @@ -42672,7 +42672,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint64_t p521_sqrt_power[9] = { +static const word64 p521_sqrt_power[9] = { 0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000080 @@ -44236,7 +44236,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_18(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -45525,13 +45525,13 @@ static void sp_1024_proj_point_add_sub_18(sp_point_1024* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_1024 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_1024; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_18_7[130] = { +static const word8 recode_index_18_7[130] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -45544,7 +45544,7 @@ static const uint8_t recode_index_18_7[130] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_18_7[130] = { +static const word8 recode_neg_18_7[130] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -45566,7 +45566,7 @@ static void sp_1024_ecc_recode_7_18(const sp_digit* k, ecc_recode_1024* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -45575,7 +45575,7 @@ static void sp_1024_ecc_recode_7_18(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 7 < 57) { y &= 0x7f; n >>= 7; @@ -45589,12 +45589,12 @@ static void sp_1024_ecc_recode_7_18(const sp_digit* k, ecc_recode_1024* v) } else if (++j < 18) { n = k[j]; - y |= (uint8_t)((n << (57 - o)) & 0x7f); + y |= (word8)((n << (57 - o)) & 0x7f); o -= 50; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_18_7[y]; v[i].neg = recode_neg_18_7[y]; carry = (y >> 7) + v[i].neg; @@ -46057,7 +46057,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -46085,7 +46085,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -104,12 +105,20 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -776,7 +785,7 @@ static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -829,7 +838,7 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -885,7 +894,7 @@ static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -1031,7 +1040,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -1115,7 +1124,7 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -1321,7 +1330,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -1461,7 +1470,7 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -1938,7 +1947,7 @@ static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -2029,7 +2038,7 @@ static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -2148,7 +2157,7 @@ static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -2239,7 +2248,7 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -2291,7 +2300,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -2608,7 +2617,7 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -2660,7 +2669,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -3404,7 +3413,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -3548,7 +3557,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -4651,7 +4660,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -4733,7 +4742,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -5146,7 +5155,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -5596,7 +5605,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -5852,7 +5861,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -7113,7 +7122,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -7253,7 +7262,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -7319,7 +7328,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -7401,7 +7410,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -8269,7 +8278,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -8841,7 +8850,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -8985,7 +8994,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -9969,7 +9978,8 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -9980,12 +9990,20 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -11189,7 +11207,7 @@ static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -11256,7 +11274,7 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -11326,7 +11344,7 @@ static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -11504,7 +11522,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -11616,7 +11634,7 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -11878,7 +11896,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -12074,7 +12092,7 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -12891,7 +12909,7 @@ static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -12996,7 +13014,7 @@ static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -13143,7 +13161,7 @@ static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -13234,7 +13252,7 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -13286,7 +13304,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -13603,7 +13621,7 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -13655,7 +13673,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -14559,7 +14577,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -14759,7 +14777,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -16150,7 +16168,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -16232,7 +16250,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -16821,7 +16839,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -17271,7 +17289,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -17639,7 +17657,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -19316,7 +19334,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -19512,7 +19530,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -19578,7 +19596,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -19660,7 +19678,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -20880,7 +20898,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -21452,7 +21470,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -21652,7 +21670,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -22828,7 +22846,8 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) int j; byte* d; - for (i = n - 1,j = 0; i >= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -22839,12 +22858,20 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -23221,7 +23248,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -23473,7 +23500,7 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Multiply a and b into r. (r = a * b) @@ -23603,7 +23630,7 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -23655,7 +23682,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -24718,7 +24745,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -25198,7 +25225,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -27291,7 +27318,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -27543,7 +27570,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -27609,7 +27636,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -27691,7 +27718,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -29263,7 +29290,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -29835,7 +29862,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -30091,7 +30118,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -32641,7 +32668,7 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -32684,7 +32711,7 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -32931,7 +32958,7 @@ static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, const sp_digit* #else (void)m; #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Convert an mp_int to an array of sp_digit. @@ -34541,7 +34568,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_8(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint32_t p256_mod_minus_2[8] = { +static const word32 p256_mod_minus_2[8] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0x00000000U,0x00000000U,0x00000000U, 0x00000001U,0xffffffffU }; @@ -34761,7 +34788,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -34823,7 +34850,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -34883,7 +34910,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -37129,7 +37156,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -37157,7 +37184,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -39437,12 +39465,20 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -39831,7 +39867,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -39871,7 +39907,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -40063,7 +40099,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -40145,7 +40181,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -40247,7 +40283,7 @@ static void sp_256_mont_mul_order_8(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P256 curve. */ -static const uint32_t p256_order_minus_2[8] = { +static const word32 p256_order_minus_2[8] = { 0xfc63254fU,0xf3b9cac2U,0xa7179e84U,0xbce6faadU,0xffffffffU,0xffffffffU, 0x00000000U,0xffffffffU }; @@ -40844,7 +40880,7 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -40886,7 +40922,7 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -41227,7 +41263,7 @@ static int sp_256_num_bits_8(const sp_digit* a) : : "memory", "r1", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -44327,7 +44363,7 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -44377,7 +44413,7 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -44730,7 +44766,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -44804,7 +44840,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -45134,7 +45170,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_12(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint32_t p384_mod_minus_2[12] = { +static const word32 p384_mod_minus_2[12] = { 0xfffffffdU,0x00000000U,0x00000000U,0xffffffffU,0xfffffffeU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; @@ -45414,7 +45450,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -45589,7 +45625,7 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -45638,7 +45674,7 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -45695,7 +45731,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -45769,7 +45805,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -47170,7 +47206,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -47198,7 +47234,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -49500,12 +49537,20 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } @@ -49894,7 +49939,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -49941,7 +49986,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -50153,7 +50198,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -50235,7 +50280,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -50341,13 +50386,13 @@ static void sp_384_mont_mul_order_12(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P384 curve. */ -static const uint32_t p384_order_minus_2[12] = { +static const word32 p384_order_minus_2[12] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU }; #else /* The low half of the order-2 of the P384 curve. */ -static const uint32_t p384_order_low[6] = { +static const word32 p384_order_low[6] = { 0xccc52971U,0xecec196aU,0x48b0a77aU,0x581a0db2U,0xf4372ddfU,0xc7634d81U }; #endif /* WOLFSSL_SP_SMALL */ @@ -51286,7 +51331,7 @@ static int sp_384_num_bits_12(const sp_digit* a) : : "memory", "r1", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -56042,7 +56087,7 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -56103,7 +56148,7 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -56373,7 +56418,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -56466,7 +56511,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -57169,7 +57214,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_17(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint32_t p521_mod_minus_2[17] = { +static const word32 p521_mod_minus_2[17] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU @@ -57501,7 +57546,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Normalize the values in each word to 32. @@ -59359,7 +59404,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -59387,7 +59432,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -62262,12 +62308,20 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER + switch (i) { + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough + } +#else switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough } +#endif j++; } @@ -63111,7 +63165,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #else @@ -63169,7 +63223,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -63406,7 +63460,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -63488,7 +63542,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -63601,14 +63655,14 @@ static void sp_521_mont_mul_order_17(sp_digit* r, const sp_digit* a, const sp_di #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P521 curve. */ -static const uint32_t p521_order_minus_2[17] = { +static const word32 p521_order_minus_2[17] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU,0xffffffffU,0xffffffffU,0xffffffffU, 0xffffffffU,0xffffffffU,0xffffffffU,0xffffffffU,0x000001ffU }; #else /* The low half of the order-2 of the P521 curve. */ -static const uint32_t p521_order_low[9] = { +static const word32 p521_order_low[9] = { 0x91386407U,0xbb6fb71eU,0x899c47aeU,0x3bb5c9b8U,0xf709a5d0U,0x7fcc0148U, 0xbf2f966bU,0x51868783U,0xfffffffaU }; @@ -64193,7 +64247,7 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -64253,7 +64307,7 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -64848,7 +64902,7 @@ static int sp_521_num_bits_17(const sp_digit* a) : : "memory", "r1", "r2", "r3", "r4", "r5", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Non-constant time modular inversion. @@ -65722,7 +65776,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint32_t p521_sqrt_power[17] = { +static const word32 p521_sqrt_power[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000080 @@ -68866,7 +68920,7 @@ static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Sub b from a into a. (a -= b) @@ -68947,7 +69001,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Add b to a into r. (r = a + b) @@ -69031,7 +69085,7 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* AND m into each word of a and store in r. @@ -69155,7 +69209,7 @@ static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } /* Square a and put result in r. (r = a * a) @@ -69571,7 +69625,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } #endif /* WOLFSSL_SP_SMALL */ @@ -69628,7 +69682,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -69772,7 +69826,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -69827,7 +69881,7 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -70139,7 +70193,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #else @@ -70221,7 +70275,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit : : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)d1; + return (word32)(size_t)d1; } #endif @@ -70664,7 +70718,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) : : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)a; + return (word32)(size_t)a; } /* Divide d in a and put remainder into r (m*d + r = a) @@ -71569,7 +71623,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_32(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -72557,7 +72611,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #else @@ -72701,7 +72755,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig : : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" ); - return (uint32_t)(size_t)r; + return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ @@ -73945,7 +73999,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[16]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -73973,7 +74027,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; i= 3; i -= 4) { + j = 0; + for (i = n - 1; i >= 3; i -= 4) { r[j] = ((sp_digit)a[i - 0] << 0) | ((sp_digit)a[i - 1] << 8) | ((sp_digit)a[i - 2] << 16) | @@ -81801,12 +81856,20 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) if (i >= 0) { r[j] = 0; - d = (byte*)r; + d = (byte*)(r + j); +#ifdef BIG_ENDIAN_ORDER switch (i) { - case 2: d[n - 1 - 2] = a[2]; //fallthrough - case 1: d[n - 1 - 1] = a[1]; //fallthrough - case 0: d[n - 1 - 0] = a[0]; //fallthrough + case 2: d[1] = *(a++); //fallthrough + case 1: d[2] = *(a++); //fallthrough + case 0: d[3] = *a ; //fallthrough } +#else + switch (i) { + case 2: d[2] = a[2]; //fallthrough + case 1: d[1] = a[1]; //fallthrough + case 0: d[0] = a[0]; //fallthrough + } +#endif j++; } diff --git a/src/wolfcrypt/src/sp_dsp32.c b/src/wolfcrypt/src/sp_dsp32.c index f14e1ab..e65862d 100644 --- a/src/wolfcrypt/src/sp_dsp32.c +++ b/src/wolfcrypt/src/sp_dsp32.c @@ -1309,7 +1309,7 @@ static void sp_256_mont_sqr_n_10(sp_digit* r, const sp_digit* a, int n, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint32_t p256_mod_2[8] = { +static const word32 p256_mod_2[8] = { 0xfffffffdU,0xffffffffU,0xffffffffU,0x00000000U,0x00000000U,0x00000000U, 0x00000001U,0xffffffffU }; @@ -1390,10 +1390,10 @@ static void sp_256_mont_inv_10(sp_digit* r, const sp_digit* a, sp_digit* td) } -/* Map the Montgomery form projective co-ordinate point to an affine point. +/* Map the Montgomery form projective coordinate point to an affine point. * - * r Resulting affine co-ordinate point. - * p Montgomery form projective co-ordinate point. + * r Resulting affine coordinate point. + * p Montgomery form projective coordinate point. * t Temporary ordinate data. */ static void sp_256_map_10(sp_point* r, const sp_point* p, sp_digit* t) @@ -1910,7 +1910,7 @@ static void sp_256_proj_point_add_10(sp_point* r, const sp_point* p, const sp_po #ifdef WOLFSSL_SP_SMALL /* Multiply the point by the scalar and return the result. - * If map is true then convert result to affine co-ordinates. + * If map is true then convert result to affine coordinates. * * r Resulting point. * g Point to multiply. @@ -2006,7 +2006,7 @@ static int sp_256_ecc_mulmod_10(sp_point* r, const sp_point* g, const sp_digit* #elif !defined(WC_NO_CACHE_RESISTANT) /* Multiply the point by the scalar and return the result. - * If map is true then convert result to affine co-ordinates. + * If map is true then convert result to affine coordinates. * * r Resulting point. * g Point to multiply. @@ -2119,7 +2119,7 @@ typedef struct sp_table_entry { } sp_table_entry; /* Multiply the point by the scalar and return the result. - * If map is true then convert result to affine co-ordinates. + * If map is true then convert result to affine coordinates. * * r Resulting point. * g Point to multiply. @@ -2517,7 +2517,7 @@ static int sp_256_gen_stripe_table_10(const sp_point* a, #endif /* FP_ECC */ /* Multiply the point by the scalar and return the result. - * If map is true then convert result to affine co-ordinates. + * If map is true then convert result to affine coordinates. * * r Resulting point. * k Scalar to multiply by. @@ -2607,7 +2607,7 @@ typedef struct sp_cache_t { sp_digit x[10] __attribute__((aligned(128))); sp_digit y[10] __attribute__((aligned(128))); sp_table_entry table[256] __attribute__((aligned(128))); - uint32_t cnt; + word32 cnt; int set; } sp_cache_t; @@ -2625,7 +2625,7 @@ static THREAD_LS_T int sp_cache_inited = 0; static void sp_ecc_get_cache(const sp_point* g, sp_cache_t** cache) { int i, j; - uint32_t least; + word32 least; if (sp_cache_inited == 0) { for (i=0; i SP_INT_DIGITS)) { \ + if (((err) == MP_OKAY) && ((s) > (int)SP_INT_DIGITS)) { \ (err) = MP_VAL; \ } \ } \ @@ -3458,7 +3458,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, : : "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" ); - return (uint32_t)(size_t)hi; + return (sp_uint32)(size_t)hi; } #define SP_ASM_DIV_WORD @@ -5087,52 +5087,6 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct); static void _sp_mont_setup(const sp_int* m, sp_int_digit* rho); #endif -/* Determine when mp_add_d is required. */ -#if !defined(NO_PWDBASED) || defined(WOLFSSL_KEY_GEN) || !defined(NO_DH) || \ - !defined(NO_DSA) || defined(HAVE_ECC) || \ - (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ - defined(OPENSSL_EXTRA) -#define WOLFSSL_SP_ADD_D -#endif -/* Determine when mp_sub_d is required. */ -#if (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ - !defined(NO_DH) || defined(HAVE_ECC) || !defined(NO_DSA) -#define WOLFSSL_SP_SUB_D -#endif -/* Determine when mp_read_radix with a radix of 10 is required. */ -#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_RSA) && \ - !defined(WOLFSSL_RSA_VERIFY_ONLY)) || defined(HAVE_ECC) || \ - !defined(NO_DSA) || defined(OPENSSL_EXTRA) -#define WOLFSSL_SP_READ_RADIX_16 -#endif -/* Determine when mp_read_radix with a radix of 10 is required. */ -#if defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_RSA) && \ - !defined(WOLFSSL_RSA_VERIFY_ONLY) -#define WOLFSSL_SP_READ_RADIX_10 -#endif -/* Determine when mp_invmod is required. */ -#if defined(HAVE_ECC) || !defined(NO_DSA) || defined(OPENSSL_EXTRA) || \ - (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ - !defined(WOLFSSL_RSA_PUBLIC_ONLY)) -#define WOLFSSL_SP_INVMOD -#endif -/* Determine when mp_invmod_mont_ct is required. */ -#if defined(WOLFSSL_SP_MATH_ALL) && defined(HAVE_ECC) -#define WOLFSSL_SP_INVMOD_MONT_CT -#endif - -/* Determine when mp_prime_gen is required. */ -#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ - !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || !defined(NO_DH) || \ - (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) -#define WOLFSSL_SP_PRIME_GEN -#endif - -#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ - (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || defined(OPENSSL_EXTRA) -/* Determine when mp_mul_d is required */ -#define WOLFSSL_SP_MUL_D -#endif /* Set the multi-precision number to zero. * @@ -5352,7 +5306,7 @@ void sp_forcezero(sp_int* a) /* Zeroize when a vald pointer passed in. */ if (a != NULL) { /* Ensure all data zeroized - data not zeroed when used decreases. */ - ForceZero(a->dp, a->size * SP_WORD_SIZEOF); + ForceZero(a->dp, a->size * (word32)SP_WORD_SIZEOF); /* Set back to zero. */ #ifdef HAVE_WOLF_BIGINT /* Zeroize the raw data as well. */ @@ -5379,7 +5333,7 @@ static void _sp_copy(const sp_int* a, sp_int* r) r->dp[0] = 0; } else { - XMEMCPY(r->dp, a->dp, a->used * SP_WORD_SIZEOF); + XMEMCPY(r->dp, a->dp, a->used * (word32)SP_WORD_SIZEOF); } /* Set number of used words in result. */ r->used = a->used; @@ -6118,7 +6072,7 @@ int sp_set_bit(sp_int* a, int i) a->dp[w] |= (sp_int_digit)1 << s; /* Update used if necessary */ if (a->used <= w) { - a->used = w + 1; + a->used = (sp_size_t)(w + 1U); } } @@ -7363,7 +7317,7 @@ static void _sp_div_2(const sp_int* a, sp_int* r) /* Last word only needs to be shifted down. */ r->dp[i] = a->dp[i] >> 1; /* Set used to be all words seen. */ - r->used = (sp_size_t)i + 1; + r->used = (sp_size_t)(i + 1); /* Remove leading zeros. */ sp_clamp(r); #ifdef WOLFSSL_SP_INT_NEGATIVE @@ -7484,7 +7438,7 @@ int sp_div_2_mod_ct(const sp_int* a, const sp_int* m, sp_int* r) r->dp[i] = l; #endif /* Used includes carry - set or not. */ - r->used = i + 1; + r->used = (sp_size_t)(i + 1); #ifdef WOLFSSL_SP_INT_NEGATIVE r->sign = MP_ZPOS; #endif @@ -7872,7 +7826,7 @@ static int _sp_addmod(const sp_int* a, const sp_int* b, const sp_int* m, { int err = MP_OKAY; /* Calculate used based on digits used in a and b. */ - sp_size_t used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); + sp_size_t used = (sp_size_t)(((a->used >= b->used) ? a->used + 1U : b->used + 1U)); DECL_SP_INT(t, used); /* Allocate a temporary SP int to hold sum. */ @@ -7960,8 +7914,8 @@ static int _sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, int err = MP_OKAY; #ifndef WOLFSSL_SP_INT_NEGATIVE unsigned int used = ((a->used >= m->used) ? - ((a->used >= b->used) ? (a->used + 1) : (b->used + 1)) : - ((b->used >= m->used)) ? (b->used + 1) : (m->used + 1)); + ((a->used >= b->used) ? (a->used + 1U) : (b->used + 1U)) : + ((b->used >= m->used)) ? (b->used + 1U) : (m->used + 1U)); DECL_SP_INT_ARRAY(t, used, 2); ALLOC_SP_INT_ARRAY(t, used, 2, err, NULL); @@ -8452,11 +8406,11 @@ int sp_lshd(sp_int* a, int s) } if (err == MP_OKAY) { /* Move up digits. */ - XMEMMOVE(a->dp + s, a->dp, a->used * SP_WORD_SIZEOF); + XMEMMOVE(a->dp + s, a->dp, a->used * (word32)SP_WORD_SIZEOF); /* Back fill with zeros. */ XMEMSET(a->dp, 0, (size_t)s * SP_WORD_SIZEOF); /* Update used. */ - a->used += (sp_size_t)s; + a->used = (sp_size_t)(a->used + s); /* Remove leading zeros. */ sp_clamp(a); } @@ -8493,7 +8447,7 @@ static int sp_lshb(sp_int* a, int n) } if (err == MP_OKAY) { /* Get count of bits to move in digit. */ - n &= SP_WORD_MASK; + n &= (int)SP_WORD_MASK; /* Check whether this is a complicated case. */ if (n != 0) { unsigned int i; @@ -8502,7 +8456,7 @@ static int sp_lshb(sp_int* a, int n) /* Get new most significant digit. */ sp_int_digit v = a->dp[a->used - 1] >> (SP_WORD_SIZE - n); /* Shift up each digit. */ - for (i = a->used - 1; i >= 1; i--) { + for (i = a->used - 1U; i >= 1U; i--) { a->dp[i + s] = (a->dp[i] << n) | (a->dp[i - 1] >> (SP_WORD_SIZE - n)); } @@ -8517,13 +8471,13 @@ static int sp_lshb(sp_int* a, int n) /* Only digits to move and ensure not zero. */ else if (s > 0) { /* Move up digits. */ - XMEMMOVE(a->dp + s, a->dp, a->used * SP_WORD_SIZEOF); + XMEMMOVE(a->dp + s, a->dp, a->used * (word32)SP_WORD_SIZEOF); } /* Update used digit count. */ - a->used += s; + a->used = (sp_size_t)(a->used + s); /* Back fill with zeros. */ - XMEMSET(a->dp, 0, SP_WORD_SIZEOF * s); + XMEMSET(a->dp, 0, (word32)SP_WORD_SIZEOF * s); } } @@ -8550,7 +8504,7 @@ void sp_rshd(sp_int* a, int c) sp_size_t i; /* Update used digits count. */ - a->used -= (sp_size_t)c; + a->used = (sp_size_t)(a->used - c); /* Move digits down. */ for (i = 0; i < a->used; i++, c++) { a->dp[i] = a->dp[c]; @@ -8594,13 +8548,13 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) /* Handle simple case. */ if (n == 0) { /* Set the count of used digits. */ - r->used = a->used - i; + r->used = (sp_size_t)(a->used - i); /* Move digits down. */ if (r == a) { - XMEMMOVE(r->dp, r->dp + i, SP_WORD_SIZEOF * r->used); + XMEMMOVE(r->dp, r->dp + i, (word32)SP_WORD_SIZEOF * r->used); } else { - XMEMCPY(r->dp, a->dp + i, SP_WORD_SIZEOF * r->used); + XMEMCPY(r->dp, a->dp + i, (word32)SP_WORD_SIZEOF * r->used); } } else { @@ -8637,7 +8591,7 @@ static void _sp_div_same_size(sp_int* a, const sp_int* d, sp_int* r) sp_size_t i; /* Compare top digits of dividend with those of divisor up to last. */ - for (i = d->used - 1; i > 0; i--) { + for (i = (sp_size_t)(d->used - 1U); i > 0; i--) { /* Break if top divisor is not equal to dividend. */ if (a->dp[a->used - d->used + i] != d->dp[i]) { break; @@ -8650,7 +8604,7 @@ static void _sp_div_same_size(sp_int* a, const sp_int* d, sp_int* r) /* Get 'used' to restore - ensure zeros put into quotient. */ i = a->used; /* Subtract d from top of a. */ - _sp_sub_off(a, d, a, a->used - d->used); + _sp_sub_off(a, d, a, (sp_size_t)(a->used - d->used)); /* Restore 'used' on remainder. */ a->used = i; } @@ -8707,7 +8661,7 @@ static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) /* Keep subtracting multiples of d as long as the digit count of a is * greater than equal to d. */ - for (i = a->used - 1; i >= d->used; i--) { + for (i = (sp_size_t)(a->used - 1U); i >= d->used; i--) { /* When top digits equal, guestimate maximum multiplier. * Worst case, multiplier is actually SP_DIGIT_MAX - 1. * That is, for w (word size in bits) > 1, n > 1, let: @@ -8761,7 +8715,7 @@ static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) } #else /* Index of lowest digit trial is subtracted from. */ - o = i - d->used; + o = (sp_size_t)(i - d->used); do { #ifndef SQR_MUL_ASM sp_int_word tw = 0; @@ -8830,7 +8784,7 @@ static int _sp_div_impl(sp_int* a, const sp_int* d, sp_int* r, sp_int* trial) #endif /* WOLFSSL_SP_SMALL */ } /* Update used. */ - a->used = i + 1; + a->used = (sp_size_t)(i + 1U); if (a->used == d->used) { /* Finish div now that length of dividend is same as divisor. */ _sp_div_same_size(a, d, r); @@ -8964,12 +8918,12 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, trial = td[1]; /* Initialize sizes to minimal values. */ - _sp_init_size(sd, d->used + 1); + _sp_init_size(sd, (sp_size_t)(d->used + 1U)); _sp_init_size(trial, used); /* Move divisor to top of word. Adjust dividend as well. */ s = sp_count_bits(d); - s = SP_WORD_SIZE - (s & SP_WORD_MASK); + s = SP_WORD_SIZE - (s & (int)SP_WORD_MASK); _sp_copy(a, sa); /* Only shift if top bit of divisor no set. */ if (s != SP_WORD_SIZE) { @@ -9058,7 +9012,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) /* May need to shift number being divided left into a new word. */ int bits = SP_WORD_SIZE - (sp_count_bits(d) % SP_WORD_SIZE); if ((bits != SP_WORD_SIZE) && - (sp_count_bits(a) + bits > SP_INT_DIGITS * SP_WORD_SIZE)) { + (sp_count_bits(a) + bits > (int)(SP_INT_DIGITS * SP_WORD_SIZE))) { err = MP_VAL; } else { @@ -9066,7 +9020,7 @@ int sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem) } } else { - used = a->used + 1; + used = (sp_size_t)(a->used + 1U); } } @@ -9328,7 +9282,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) } for (; k <= (sp_size_t)((a->used - 1) + (b->used - 1)); k++) { j = (int)(b->used - 1); - i = k - (sp_size_t)j; + i = (sp_size_t)(k - (sp_size_t)j); for (; (i < a->used) && (j >= 0); i++, j--) { SP_ASM_MUL_ADD(l, h, o, a->dp[i], b->dp[j]); } @@ -9396,7 +9350,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) o = 0; #endif for (k = 1; (int)k <= ((int)a->used - 1) + ((int)b->used - 1); k++) { - i = k - (sp_size_t)(b->used - 1); + i = (sp_size_t)(k - (b->used - 1)); i &= (sp_size_t)(((unsigned int)i >> (sizeof(i) * 8 - 1)) - 1U); j = (int)(k - i); for (; (i < a->used) && (j >= 0); i++, j--) { @@ -12198,7 +12152,7 @@ static int _sp_mulmod_tmp(const sp_int* a, const sp_int* b, const sp_int* m, ALLOC_SP_INT(t, a->used + b->used, err, NULL); if (err == MP_OKAY) { - err = sp_init_size(t, a->used + b->used); + err = sp_init_size(t, (sp_size_t)(a->used + b->used)); } /* Multiply and reduce. */ @@ -12434,7 +12388,7 @@ static int _sp_invmod_div(const sp_int* a, const sp_int* m, sp_int* x, ALLOC_SP_INT(d, m->used + 1, err, NULL); if (err == MP_OKAY) { - err = sp_init_size(d, m->used + 1); + err = sp_init_size(d, (sp_size_t)(m->used + 1U)); } if (err == MP_OKAY) { @@ -12578,7 +12532,7 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) * - x3 one word larger than modulus * - x1 one word longer than twice modulus used */ - ALLOC_SP_INT_ARRAY(t, m->used + 1, 3, err, NULL); + ALLOC_SP_INT_ARRAY(t, m->used + 1U, 3, err, NULL); ALLOC_SP_INT(c, 2 * m->used + 1, err, NULL); if (err == MP_OKAY) { u = t[0]; @@ -12589,16 +12543,16 @@ static int _sp_invmod(const sp_int* a, const sp_int* m, sp_int* r) /* Initialize intermediate values with minimal sizes. */ if (err == MP_OKAY) { - err = sp_init_size(u, m->used + 1); + err = sp_init_size(u, (sp_size_t)(m->used + 1U)); } if (err == MP_OKAY) { - err = sp_init_size(v, m->used + 1); + err = sp_init_size(v, (sp_size_t)(m->used + 1U)); } if (err == MP_OKAY) { - err = sp_init_size(b, m->used + 1); + err = sp_init_size(b, (sp_size_t)(m->used + 1U)); } if (err == MP_OKAY) { - err = sp_init_size(c, (sp_size_t)(2 * m->used + 1)); + err = sp_init_size(c, (sp_size_t)(2U * m->used + 1U)); } if (err == MP_OKAY) { @@ -12793,10 +12747,10 @@ static int _sp_invmod_mont_ct(const sp_int* a, const sp_int* m, sp_int* r, #endif #ifndef WOLFSSL_SP_NO_MALLOC - ALLOC_DYN_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2, err, + ALLOC_DYN_SP_INT_ARRAY(pre, m->used * 2U + 1U, CT_INV_MOD_PRE_CNT + 2, err, NULL); #else - ALLOC_SP_INT_ARRAY(pre, m->used * 2 + 1, CT_INV_MOD_PRE_CNT + 2, err, NULL); + ALLOC_SP_INT_ARRAY(pre, m->used * 2U + 1U, CT_INV_MOD_PRE_CNT + 2, err, NULL); #endif if (err == MP_OKAY) { t = pre[CT_INV_MOD_PRE_CNT + 0]; @@ -13040,7 +12994,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, ALLOC_SP_INT_ARRAY(t, 2 * m->used + 1, 2, err, NULL); #else /* Working SP int needed when cache resistant. */ - ALLOC_SP_INT_ARRAY(t, 2 * m->used + 1, 3, err, NULL); + ALLOC_SP_INT_ARRAY(t, 2U * m->used + 1U, 3, err, NULL); #endif if (err == MP_OKAY) { /* Initialize temporaries. */ @@ -13100,7 +13054,7 @@ static int _sp_exptmod_ex(const sp_int* b, const sp_int* e, int bits, if (err == MP_OKAY) { /* 4.2. y = e[i] */ - int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1); + int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & (int)SP_WORD_MASK)) & 1); /* 4.3. j = y & s */ int j = y & s; /* 4.4 s = s | y */ @@ -13272,7 +13226,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, DECL_SP_INT_ARRAY(t, m->used * 2 + 1, 4); /* Allocate temporaries. */ - ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, 4, err, NULL); + ALLOC_SP_INT_ARRAY(t, m->used * 2U + 1U, 4, err, NULL); if (err == MP_OKAY) { /* Initialize temporaries. */ _sp_init_size(t[0], (sp_size_t)(m->used * 2 + 1)); @@ -13312,7 +13266,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, } if (err == MP_OKAY) { /* t[0] = t[0] mod m, temporary size has to be bigger than t[0]. */ - err = _sp_div(t[0], m, NULL, t[0], t[0]->used + 1); + err = _sp_div(t[0], m, NULL, t[0], t[0]->used + 1U); } if (err == MP_OKAY) { /* 4. t[1] = t[0] @@ -13339,7 +13293,7 @@ static int _sp_exptmod_mont_ex(const sp_int* b, const sp_int* e, int bits, if (err == MP_OKAY) { /* 6.2. y = e[i] */ - int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & SP_WORD_MASK)) & 1); + int y = (int)((e->dp[i >> SP_WORD_SHIFT] >> (i & (int)SP_WORD_MASK)) & 1); /* 6.3 j = y & s */ int j = y & s; /* 6.4 s = s | y */ @@ -13807,10 +13761,10 @@ static int _sp_exptmod_base_2(const sp_int* e, int digits, const sp_int* m, * - constant time add value for mod operation * - temporary result */ - ALLOC_SP_INT_ARRAY(d, m->used * 2 + 1, 2, err, NULL); + ALLOC_SP_INT_ARRAY(d, m->used * 2U + 1U, 2, err, NULL); #else /* Allocate sp_int for temporary result. */ - ALLOC_SP_INT(tr, m->used * 2 + 1, err, NULL); + ALLOC_SP_INT(tr, m->used * 2U + 1U, err, NULL); #endif if (err == MP_OKAY) { #ifndef WC_NO_HARDEN @@ -14058,7 +14012,8 @@ int sp_exptmod_ex(const sp_int* b, const sp_int* e, int digits, const sp_int* m, if ((!done) && (err == MP_OKAY)) { /* Use code optimized for specific sizes if possible */ #if (defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)) && \ - (defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)) + ((defined(WOLFSSL_HAVE_SP_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || \ + defined(WOLFSSL_HAVE_SP_DH)) #ifndef WOLFSSL_SP_NO_2048 if ((mBits == 1024) && sp_isodd(m) && (bBits <= 1024) && (eBits <= 1024)) { @@ -14268,9 +14223,9 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, * - Montgomery form of base */ #ifndef WOLFSSL_SP_NO_MALLOC - ALLOC_DYN_SP_INT_ARRAY(t, m->used * 2 + 1, (size_t)preCnt + 2, err, NULL); + ALLOC_DYN_SP_INT_ARRAY(t, m->used * 2U + 1U, (size_t)preCnt + 2, err, NULL); #else - ALLOC_SP_INT_ARRAY(t, m->used * 2 + 1, (size_t)preCnt + 2, err, NULL); + ALLOC_SP_INT_ARRAY(t, m->used * 2U + 1U, (size_t)preCnt + 2, err, NULL); #endif if (err == MP_OKAY) { /* Set variables to use allocate memory. */ @@ -14314,7 +14269,7 @@ static int _sp_exptmod_nct(const sp_int* b, const sp_int* e, const sp_int* m, } if (err == MP_OKAY) { /* bm = bm mod m, temporary size has to be bigger than bm->used. */ - err = _sp_div(bm, m, NULL, bm, bm->used + 1); + err = _sp_div(bm, m, NULL, bm, bm->used + 1U); } if (err == MP_OKAY) { /* Copy Montgomery form of base into first element of table. */ @@ -14784,7 +14739,7 @@ int sp_mod_2d(const sp_int* a, int e, sp_int* r) if (err == MP_OKAY) { /* Copy a into r if not same pointer. */ if (a != r) { - XMEMCPY(r->dp, a->dp, digits * SP_WORD_SIZEOF); + XMEMCPY(r->dp, a->dp, digits * (word32)SP_WORD_SIZEOF); r->used = a->used; #ifdef WOLFSSL_SP_INT_NEGATIVE r->sign = a->sign; @@ -14998,7 +14953,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) } if (err == MP_OKAY) { - r->used = a->used * 2; + r->used = (sp_size_t)(a->used * 2U); sp_clamp(r); } @@ -17341,7 +17296,7 @@ static int _sp_sqrmod(const sp_int* a, const sp_int* m, sp_int* r) ALLOC_SP_INT(t, a->used * 2, err, NULL); if (err == MP_OKAY) { - err = sp_init_size(t, a->used * 2); + err = sp_init_size(t, a->used * 2U); } /* Square and reduce. */ @@ -17556,7 +17511,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) /* 4. a = a mod m * Always subtract but at a too high offset if a is less than m. */ - _sp_submod_ct(a, m, m, m->used + 1, a); + _sp_submod_ct(a, m, m, m->used + 1U, a); } @@ -17887,7 +17842,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) /* Constant time clamping. */ sp_clamp_ct(a); - _sp_submod_ct(a, m, m, m->used + 1, a); + _sp_submod_ct(a, m, m, m->used + 1U, a); } #if 0 @@ -18304,7 +18259,7 @@ int sp_to_unsigned_bin_len_ct(const sp_int* a, byte* out, int outSz) /* Put each digit in. */ i = 0; for (j = outSz - 1; j >= 0; ) { - int b; + unsigned int b; d = a->dp[i]; /* Place each byte of a digit into the buffer. */ for (b = 0; (j >= 0) && (b < SP_WORD_SIZEOF); b++) { @@ -18431,7 +18386,7 @@ static int _sp_read_radix_16(sp_int* a, const char* in) a->dp[j] = d; } /* Update used count. */ - a->used = j + 1; + a->used = (sp_size_t)(j + 1U); /* Remove leading zeros. */ sp_clamp(a); } @@ -18469,7 +18424,7 @@ static int _sp_read_radix_10(sp_int* a, const char* in) /* Check character is valid. */ if ((ch >= '0') && (ch <= '9')) { /* Assume '0'..'9' are continuous values as characters. */ - ch -= '0'; + ch = (char)(ch - '0'); } else { if (CharIsWhiteSpace(ch)) @@ -19325,9 +19280,9 @@ static int _sp_prime_trials(const sp_int* a, int trials, int* result) n1 = t[0]; r = t[1]; - _sp_init_size(n1, a->used + 1); - _sp_init_size(r, a->used + 1); - _sp_init_size(b, (sp_size_t)(a->used * 2 + 1)); + _sp_init_size(n1, a->used + 1U); + _sp_init_size(r, a->used + 1U); + _sp_init_size(b, (sp_size_t)(a->used * 2U + 1U)); /* Do requested number of trials of Miller-Rabin test. */ for (i = 0; i < trials; i++) { @@ -19449,10 +19404,10 @@ static int _sp_prime_random_trials(const sp_int* a, int trials, int* result, sp_int* b = d[0]; sp_int* r = d[1]; - _sp_init_size(c , a->used + 1); - _sp_init_size(n1, a->used + 1); - _sp_init_size(b , (sp_size_t)(a->used * 2 + 1)); - _sp_init_size(r , (sp_size_t)(a->used * 2 + 1)); + _sp_init_size(c , a->used + 1U); + _sp_init_size(n1, a->used + 1U); + _sp_init_size(b , (sp_size_t)(a->used * 2U + 1U)); + _sp_init_size(r , (sp_size_t)(a->used * 2U + 1U)); _sp_sub_d(a, 2, c); @@ -19619,7 +19574,7 @@ static WC_INLINE int _sp_gcd(const sp_int* a, const sp_int* b, sp_int* r) /* Used for swapping sp_ints. */ sp_int* s; /* Determine maximum digit length numbers will reach. */ - unsigned int used = (a->used >= b->used) ? a->used + 1 : b->used + 1; + unsigned int used = (a->used >= b->used) ? a->used + 1U : b->used + 1U; DECL_SP_INT_ARRAY(d, used, 3); SAVE_VECTOR_REGISTERS(err = _svr_ret;); diff --git a/src/wolfcrypt/src/sp_x86_64.c b/src/wolfcrypt/src/sp_x86_64.c index 2529432..039820d 100644 --- a/src/wolfcrypt/src/sp_x86_64.c +++ b/src/wolfcrypt/src/sp_x86_64.c @@ -8438,7 +8438,7 @@ SP_NOINLINE static void sp_256_mont_sqr_n_4(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P256 curve. */ -static const uint64_t p256_mod_minus_2[4] = { +static const word64 p256_mod_minus_2[4] = { 0xfffffffffffffffdU,0x00000000ffffffffU,0x0000000000000000U, 0xffffffff00000001U }; @@ -9374,13 +9374,13 @@ static void sp_256_proj_point_add_sub_4(sp_point_256* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_256 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_256; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_4_6[66] = { +static const word8 recode_index_4_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -9389,7 +9389,7 @@ static const uint8_t recode_index_4_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_4_6[66] = { +static const word8 recode_neg_4_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -9407,7 +9407,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -9416,7 +9416,7 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) n = k[j]; o = 0; for (i=0; i<43; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -9430,12 +9430,12 @@ static void sp_256_ecc_recode_6_4(const sp_digit* k, ecc_recode_256* v) } else if (++j < 4) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_4_6[y]; v[i].neg = recode_neg_4_6[y]; carry = (y >> 6) + v[i].neg; @@ -10976,7 +10976,7 @@ typedef struct sp_cache_256_t { /* Precomputation table for point. */ sp_table_entry_256 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_256_t; @@ -11004,7 +11004,7 @@ static void sp_ecc_get_cache_256(const sp_point_256* g, sp_cache_256_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_256_inited == 0) { for (i=0; i>= 7; @@ -12105,12 +12105,12 @@ static void sp_256_ecc_recode_7_4(const sp_digit* k, ecc_recode_256* v) } else if (++j < 4) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_4_7[y]; v[i].neg = recode_neg_4_7[y]; carry = (y >> 7) + v[i].neg; @@ -24173,7 +24173,7 @@ static int sp_256_ecc_mulmod_add_only_4(sp_point_256* r, const sp_point_256* g, p->infinity = !v[i].i; sp_256_sub_4(negy, p256_mod, p->y); sp_256_norm_4(negy); - sp_256_cond_copy_4(p->y, negy, 0 - v[i].neg); + sp_256_cond_copy_4(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_256_proj_point_add_qz1_4(rt, rt, p, tmp); } if (map != 0) { @@ -24306,7 +24306,7 @@ static int sp_256_ecc_mulmod_add_only_avx2_4(sp_point_256* r, const sp_point_256 p->infinity = !v[i].i; sp_256_sub_4(negy, p256_mod, p->y); sp_256_norm_4(negy); - sp_256_cond_copy_4(p->y, negy, 0 - v[i].neg); + sp_256_cond_copy_4(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_256_proj_point_add_qz1_avx2_4(rt, rt, p, tmp); } if (map != 0) { @@ -25121,13 +25121,13 @@ static void sp_256_mont_mul_order_4(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P256 curve. */ -static const uint64_t p256_order_minus_2[4] = { +static const word64 p256_order_minus_2[4] = { 0xf3b9cac2fc63254fU,0xbce6faada7179e84U,0xffffffffffffffffU, 0xffffffff00000000U }; #else /* The low half of the order-2 of the P256 curve. */ -static const uint64_t p256_order_low[2] = { +static const word64 p256_order_low[2] = { 0xf3b9cac2fc63254fU,0xbce6faada7179e84U }; #endif /* WOLFSSL_SP_SMALL */ @@ -27593,7 +27593,7 @@ SP_NOINLINE static void sp_384_mont_sqr_n_6(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL || HAVE_COMP_KEY */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P384 curve. */ -static const uint64_t p384_mod_minus_2[6] = { +static const word64 p384_mod_minus_2[6] = { 0x00000000fffffffdU,0xffffffff00000000U,0xfffffffffffffffeU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU }; @@ -28535,13 +28535,13 @@ static void sp_384_proj_point_add_sub_6(sp_point_384* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_384 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_384; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_6_6[66] = { +static const word8 recode_index_6_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -28550,7 +28550,7 @@ static const uint8_t recode_index_6_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_6_6[66] = { +static const word8 recode_neg_6_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -28568,7 +28568,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -28577,7 +28577,7 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) n = k[j]; o = 0; for (i=0; i<65; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -28591,12 +28591,12 @@ static void sp_384_ecc_recode_6_6(const sp_digit* k, ecc_recode_384* v) } else if (++j < 6) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_6_6[y]; v[i].neg = recode_neg_6_6[y]; carry = (y >> 6) + v[i].neg; @@ -30193,7 +30193,7 @@ typedef struct sp_cache_384_t { /* Precomputation table for point. */ sp_table_entry_384 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_384_t; @@ -30221,7 +30221,7 @@ static void sp_ecc_get_cache_384(const sp_point_384* g, sp_cache_384_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_384_inited == 0) { for (i=0; i>= 7; @@ -31325,12 +31325,12 @@ static void sp_384_ecc_recode_7_6(const sp_digit* k, ecc_recode_384* v) } else if (++j < 6) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_6_7[y]; v[i].neg = recode_neg_6_7[y]; carry = (y >> 7) + v[i].neg; @@ -49207,7 +49207,7 @@ static int sp_384_ecc_mulmod_add_only_6(sp_point_384* r, const sp_point_384* g, p->infinity = !v[i].i; sp_384_sub_6(negy, p384_mod, p->y); sp_384_norm_6(negy); - sp_384_cond_copy_6(p->y, negy, 0 - v[i].neg); + sp_384_cond_copy_6(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_384_proj_point_add_qz1_6(rt, rt, p, tmp); } if (map != 0) { @@ -49340,7 +49340,7 @@ static int sp_384_ecc_mulmod_add_only_avx2_6(sp_point_384* r, const sp_point_384 p->infinity = !v[i].i; sp_384_sub_6(negy, p384_mod, p->y); sp_384_norm_6(negy); - sp_384_cond_copy_6(p->y, negy, 0 - v[i].neg); + sp_384_cond_copy_6(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_384_proj_point_add_qz1_avx2_6(rt, rt, p, tmp); } if (map != 0) { @@ -50156,13 +50156,13 @@ static void sp_384_mont_mul_order_6(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P384 curve. */ -static const uint64_t p384_order_minus_2[6] = { +static const word64 p384_order_minus_2[6] = { 0xecec196accc52971U,0x581a0db248b0a77aU,0xc7634d81f4372ddfU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU }; #else /* The low half of the order-2 of the P384 curve. */ -static const uint64_t p384_order_low[3] = { +static const word64 p384_order_low[3] = { 0xecec196accc52971U,0x581a0db248b0a77aU,0xc7634d81f4372ddfU }; #endif /* WOLFSSL_SP_SMALL */ @@ -52503,7 +52503,7 @@ SP_NOINLINE static void sp_521_mont_sqr_n_9(sp_digit* r, #endif /* !WOLFSSL_SP_SMALL */ #ifdef WOLFSSL_SP_SMALL /* Mod-2 for the P521 curve. */ -static const uint64_t p521_mod_minus_2[9] = { +static const word64 p521_mod_minus_2[9] = { 0xfffffffffffffffdU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0x00000000000001ffU @@ -53465,13 +53465,13 @@ static void sp_521_proj_point_add_sub_9(sp_point_521* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_521 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_521; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_9_6[66] = { +static const word8 recode_index_9_6[66] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, @@ -53480,7 +53480,7 @@ static const uint8_t recode_index_9_6[66] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_9_6[66] = { +static const word8 recode_neg_9_6[66] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -53498,7 +53498,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -53507,7 +53507,7 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) n = k[j]; o = 0; for (i=0; i<87; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 6 < 64) { y &= 0x3f; n >>= 6; @@ -53521,12 +53521,12 @@ static void sp_521_ecc_recode_6_9(const sp_digit* k, ecc_recode_521* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x3f); + y |= (word8)((n << (64 - o)) & 0x3f); o -= 58; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_6[y]; v[i].neg = recode_neg_9_6[y]; carry = (y >> 6) + v[i].neg; @@ -55100,7 +55100,7 @@ typedef struct sp_cache_521_t { /* Precomputation table for point. */ sp_table_entry_521 table[64]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_521_t; @@ -55128,7 +55128,7 @@ static void sp_ecc_get_cache_521(const sp_point_521* g, sp_cache_521_t** cache) { int i; int j; - uint32_t least; + word32 least; if (sp_cache_521_inited == 0) { for (i=0; i>= 7; @@ -56358,12 +56358,12 @@ static void sp_521_ecc_recode_7_9(const sp_digit* k, ecc_recode_521* v) } else if (++j < 9) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_9_7[y]; v[i].neg = recode_neg_9_7[y]; carry = (y >> 7) + v[i].neg; @@ -90300,7 +90300,7 @@ static int sp_521_ecc_mulmod_add_only_9(sp_point_521* r, const sp_point_521* g, p->infinity = !v[i].i; sp_521_sub_9(negy, p521_mod, p->y); sp_521_norm_9(negy); - sp_521_cond_copy_9(p->y, negy, 0 - v[i].neg); + sp_521_cond_copy_9(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_521_proj_point_add_qz1_9(rt, rt, p, tmp); } if (map != 0) { @@ -90433,7 +90433,7 @@ static int sp_521_ecc_mulmod_add_only_avx2_9(sp_point_521* r, const sp_point_521 p->infinity = !v[i].i; sp_521_sub_9(negy, p521_mod, p->y); sp_521_norm_9(negy); - sp_521_cond_copy_9(p->y, negy, 0 - v[i].neg); + sp_521_cond_copy_9(p->y, negy, (sp_digit)(0 - v[i].neg)); sp_521_proj_point_add_qz1_avx2_9(rt, rt, p, tmp); } if (map != 0) { @@ -91277,14 +91277,14 @@ static void sp_521_mont_mul_order_9(sp_digit* r, const sp_digit* a, const sp_dig #if defined(HAVE_ECC_SIGN) || (defined(HAVE_ECC_VERIFY) && defined(WOLFSSL_SP_SMALL)) #ifdef WOLFSSL_SP_SMALL /* Order-2 for the P521 curve. */ -static const uint64_t p521_order_minus_2[9] = { +static const word64 p521_order_minus_2[9] = { 0xbb6fb71e91386407U,0x3bb5c9b8899c47aeU,0x7fcc0148f709a5d0U, 0x51868783bf2f966bU,0xfffffffffffffffaU,0xffffffffffffffffU, 0xffffffffffffffffU,0xffffffffffffffffU,0x00000000000001ffU }; #else /* The low half of the order-2 of the P521 curve. */ -static const uint64_t p521_order_low[5] = { +static const word64 p521_order_low[5] = { 0xbb6fb71e91386407U,0x3bb5c9b8899c47aeU,0x7fcc0148f709a5d0U, 0x51868783bf2f966bU,0xfffffffffffffffaU }; @@ -93041,7 +93041,7 @@ int sp_ecc_map_521(mp_int* pX, mp_int* pY, mp_int* pZ) #endif /* WOLFSSL_PUBLIC_ECC_ADD_DBL */ #ifdef HAVE_COMP_KEY /* Square root power for the P521 curve. */ -static const uint64_t p521_sqrt_power[9] = { +static const word64 p521_sqrt_power[9] = { 0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000, 0x0000000000000080 @@ -93842,7 +93842,7 @@ SP_NOINLINE static void sp_1024_mont_sqr_16(sp_digit* r, const sp_digit* a, } /* Mod-2 for the P1024 curve. */ -static const uint8_t p1024_mod_minus_2[] = { +static const word8 p1024_mod_minus_2[] = { 6,0x06, 7,0x0f, 7,0x0b, 6,0x0c, 7,0x1e, 9,0x09, 7,0x0c, 7,0x1f, 6,0x16, 6,0x06, 7,0x0e, 8,0x10, 6,0x03, 8,0x11, 6,0x0d, 7,0x14, 9,0x12, 6,0x0f, 7,0x04, 9,0x0d, 6,0x00, 7,0x13, 6,0x01, 6,0x07, @@ -94751,13 +94751,13 @@ static void sp_1024_proj_point_add_sub_16(sp_point_1024* ra, /* Structure used to describe recoding of scalar multiplication. */ typedef struct ecc_recode_1024 { /* Index into pre-computation table. */ - uint8_t i; + word8 i; /* Use the negative of the point. */ - uint8_t neg; + word8 neg; } ecc_recode_1024; /* The index into pre-computation table to use. */ -static const uint8_t recode_index_16_7[130] = { +static const word8 recode_index_16_7[130] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -94770,7 +94770,7 @@ static const uint8_t recode_index_16_7[130] = { }; /* Whether to negate y-ordinate. */ -static const uint8_t recode_neg_16_7[130] = { +static const word8 recode_neg_16_7[130] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -94792,7 +94792,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) { int i; int j; - uint8_t y; + word8 y; int carry = 0; int o; sp_digit n; @@ -94801,7 +94801,7 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) n = k[j]; o = 0; for (i=0; i<147; i++) { - y = (uint8_t)(int8_t)n; + y = (word8)(int8_t)n; if (o + 7 < 64) { y &= 0x7f; n >>= 7; @@ -94815,12 +94815,12 @@ static void sp_1024_ecc_recode_7_16(const sp_digit* k, ecc_recode_1024* v) } else if (++j < 16) { n = k[j]; - y |= (uint8_t)((n << (64 - o)) & 0x7f); + y |= (word8)((n << (64 - o)) & 0x7f); o -= 57; n >>= o; } - y += (uint8_t)carry; + y = (word8)(y + carry); v[i].i = recode_index_16_7[y]; v[i].neg = recode_neg_16_7[y]; carry = (y >> 7) + v[i].neg; @@ -96329,7 +96329,7 @@ typedef struct sp_cache_1024_t { /* Precomputation table for point. */ sp_table_entry_1024 table[256]; /* Count of entries in table. */ - uint32_t cnt; + word32 cnt; /* Point and table set in entry. */ int set; } sp_cache_1024_t; @@ -96357,7 +96357,7 @@ static void sp_ecc_get_cache_1024(const sp_point_1024* g, sp_cache_1024_t** cach { int i; int j; - uint32_t least; + word32 least; if (sp_cache_1024_inited == 0) { for (i=0; idp[0] & 1); + mask = (fp_digit)0 - (a->dp[0] & 1); for (i = 0; i < b->used; i++) { - fp_digit mask_a = 0 - (i < a->used); + fp_digit mask_a = (fp_digit)0 - (i < a->used); w += b->dp[i] & mask; w += a->dp[i] & mask_a; diff --git a/src/wolfcrypt/src/wc_kyber.c b/src/wolfcrypt/src/wc_kyber.c index bca5e1f..040c4f0 100644 --- a/src/wolfcrypt/src/wc_kyber.c +++ b/src/wolfcrypt/src/wc_kyber.c @@ -68,7 +68,9 @@ volatile sword16 kyber_opt_blocker = 0; /** * Initialize the Kyber key. * - * @param [in] type Type of key: KYBER512, KYBER768, KYBER1024. + * @param [in] type Type of key: + * WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024, + * KYBER512, KYBER768, KYBER1024. * @param [out] key Kyber key object to initialize. * @param [in] heap Dynamic memory hint. * @param [in] devId Device Id. @@ -87,6 +89,27 @@ int wc_KyberKey_Init(int type, KyberKey* key, void* heap, int devId) if (ret == 0) { /* Validate type. */ switch (type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + #ifndef WOLFSSL_WC_ML_KEM_512 + /* Code not compiled in for Kyber-512. */ + ret = NOT_COMPILED_IN; + #endif + break; + case WC_ML_KEM_768: + #ifndef WOLFSSL_WC_ML_KEM_768 + /* Code not compiled in for Kyber-768. */ + ret = NOT_COMPILED_IN; + #endif + break; + case WC_ML_KEM_1024: + #ifndef WOLFSSL_WC_ML_KEM_1024 + /* Code not compiled in for Kyber-1024. */ + ret = NOT_COMPILED_IN; + #endif + break; + #endif + #ifdef WOLFSSL_KYBER_ORIGINAL case KYBER512: #ifndef WOLFSSL_KYBER512 /* Code not compiled in for Kyber-512. */ @@ -105,6 +128,7 @@ int wc_KyberKey_Init(int type, KyberKey* key, void* heap, int devId) ret = NOT_COMPILED_IN; #endif break; + #endif default: /* No other values supported. */ ret = BAD_FUNC_ARG; @@ -230,6 +254,24 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + kp = WC_ML_KEM_512_K; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + kp = WC_ML_KEM_768_K; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + kp = WC_ML_KEM_1024_K; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: kp = KYBER512_K; @@ -245,6 +287,7 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, kp = KYBER1024_K; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -266,13 +309,24 @@ int wc_KyberKey_MakeKeyWithRandom(KyberKey* key, const unsigned char* rand, /* Error vector allocated at end of a. */ e = a + (kp * kp * KYBER_N); +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & KYBER_ORIGINAL) +#endif #ifdef WOLFSSL_KYBER_ORIGINAL - /* Expand 32 bytes of random to 32. */ - ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, NULL, 0, buf); -#else - buf[0] = kp; - /* Expand 33 bytes of random to 32. */ - ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, buf, 1, buf); + { + /* Expand 32 bytes of random to 32. */ + ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, NULL, 0, buf); + } +#endif +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + buf[0] = kp; + /* Expand 33 bytes of random to 32. */ + ret = KYBER_HASH_G(&key->hash, d, KYBER_SYM_SZ, buf, 1, buf); + } #endif } if (ret == 0) { @@ -333,6 +387,24 @@ int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) if (ret == 0) { /* Return in 'len' size of the cipher text for the type of this key. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: *len = KYBER512_CIPHER_TEXT_SIZE; @@ -348,6 +420,7 @@ int wc_KyberKey_CipherTextSize(KyberKey* key, word32* len) *len = KYBER1024_CIPHER_TEXT_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -398,6 +471,27 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + kp = WC_ML_KEM_512_K; + compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + kp = WC_ML_KEM_768_K; + compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + kp = WC_ML_KEM_1024_K; + compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: kp = KYBER512_K; @@ -415,6 +509,7 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, kp = KYBER1024_K; compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; break; +#endif #endif default: /* No other values supported. */ @@ -463,19 +558,19 @@ static int kyberkey_encapsulate(KyberKey* key, const byte* msg, byte* coins, /* Perform encapsulation maths. */ kyber_encapsulate(key->pub, bp, v, at, sp, ep, epp, k, kp); - #ifdef WOLFSSL_KYBER512 + #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) if (kp == KYBER512_K) { kyber_vec_compress_10(ct, bp, kp); kyber_compress_4(ct + compVecSz, v); } #endif - #ifdef WOLFSSL_KYBER768 + #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) if (kp == KYBER768_K) { kyber_vec_compress_10(ct, bp, kp); kyber_compress_4(ct + compVecSz, v); } #endif - #ifdef WOLFSSL_KYBER1024 + #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) if (kp == KYBER1024_K) { kyber_vec_compress_11(ct, bp); kyber_compress_5(ct + compVecSz, v); @@ -562,6 +657,18 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + #endif + break; +#endif #ifdef WOLFSSL_KYBER512 case KYBER512: ctSz = KYBER512_CIPHER_TEXT_SIZE; @@ -614,42 +721,80 @@ int wc_KyberKey_EncapsulateWithRandom(KyberKey* key, unsigned char* ct, #ifdef WOLFSSL_KYBER_ORIGINAL if (ret == 0) { - /* Hash random to anonymize as seed data. */ - ret = KYBER_HASH_H(&key->hash, rand, KYBER_SYM_SZ, msg); +#ifndef WOLFSSL_NO_ML_KEM + if (key->type & KYBER_ORIGINAL) +#endif + { + /* Hash random to anonymize as seed data. */ + ret = KYBER_HASH_H(&key->hash, rand, KYBER_SYM_SZ, msg); + } } #endif if (ret == 0) { /* Hash message into seed buffer. */ +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & KYBER_ORIGINAL) +#endif #ifdef WOLFSSL_KYBER_ORIGINAL - ret = KYBER_HASH_G(&key->hash, msg, KYBER_SYM_SZ, key->h, KYBER_SYM_SZ, - kr); -#else - ret = KYBER_HASH_G(&key->hash, rand, KYBER_SYM_SZ, key->h, KYBER_SYM_SZ, - kr); + { + ret = KYBER_HASH_G(&key->hash, msg, KYBER_SYM_SZ, key->h, + KYBER_SYM_SZ, kr); + } +#endif +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + ret = KYBER_HASH_G(&key->hash, rand, KYBER_SYM_SZ, key->h, + KYBER_SYM_SZ, kr); + } #endif } if (ret == 0) { /* Encapsulate the message using the key and the seed (coins). */ +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & KYBER_ORIGINAL) +#endif #ifdef WOLFSSL_KYBER_ORIGINAL - ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, ct); -#else - ret = kyberkey_encapsulate(key, rand, kr + KYBER_SYM_SZ, ct); + { + ret = kyberkey_encapsulate(key, msg, kr + KYBER_SYM_SZ, ct); + } +#endif +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + ret = kyberkey_encapsulate(key, rand, kr + KYBER_SYM_SZ, ct); + } #endif } +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & KYBER_ORIGINAL) +#endif #ifdef WOLFSSL_KYBER_ORIGINAL - if (ret == 0) { - /* Hash the cipher text after the seed. */ - ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); - } - if (ret == 0) { - /* Derive the secret from the seed and hash of cipher text. */ - ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); + { + if (ret == 0) { + /* Hash the cipher text after the seed. */ + ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); + } + if (ret == 0) { + /* Derive the secret from the seed and hash of cipher text. */ + ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); + } } -#else - if (ret == 0) { - XMEMCPY(ss, kr, KYBER_SS_SZ); +#endif +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + if (ret == 0) { + XMEMCPY(ss, kr, KYBER_SS_SZ); + } } #endif @@ -683,6 +828,27 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + kp = WC_ML_KEM_512_K; + compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + kp = WC_ML_KEM_768_K; + compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + kp = WC_ML_KEM_1024_K; + compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: kp = KYBER512_K; @@ -700,6 +866,7 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, kp = KYBER1024_K; compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; break; +#endif #endif default: /* No other values supported. */ @@ -723,19 +890,19 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, v = bp + kp * KYBER_N; mp = v + KYBER_N; - #ifdef WOLFSSL_KYBER512 + #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) if (kp == KYBER512_K) { kyber_vec_decompress_10(bp, ct, kp); kyber_decompress_4(v, ct + compVecSz); } #endif - #ifdef WOLFSSL_KYBER768 + #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) if (kp == KYBER768_K) { kyber_vec_decompress_10(bp, ct, kp); kyber_decompress_4(v, ct + compVecSz); } #endif - #ifdef WOLFSSL_KYBER1024 + #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) if (kp == KYBER1024_K) { kyber_vec_decompress_11(bp, ct); kyber_decompress_5(v, ct + compVecSz); @@ -757,7 +924,7 @@ static KYBER_NOINLINE int kyberkey_decapsulate(KyberKey* key, return ret; } -#ifndef WOLFSSL_KYBER_ORIGINAL +#ifndef WOLFSSL_NO_ML_KEM /* Derive the secret from z and cipher text. * * @param [in] z Implicit rejection value. @@ -828,6 +995,24 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, if (ret == 0) { /* Establish cipher text size based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + ctSz = WC_ML_KEM_512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + ctSz = WC_ML_KEM_768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + ctSz = WC_ML_KEM_1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: ctSz = KYBER512_CIPHER_TEXT_SIZE; @@ -843,6 +1028,7 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, ctSz = KYBER1024_CIPHER_TEXT_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -882,25 +1068,36 @@ int wc_KyberKey_Decapsulate(KyberKey* key, unsigned char* ss, /* Compare generated cipher text with that passed in. */ fail = kyber_cmp(ct, cmp, ctSz); +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & KYBER_ORIGINAL) +#endif #ifdef WOLFSSL_KYBER_ORIGINAL - /* Hash the cipher text after the seed. */ - ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); - } - if (ret == 0) { - /* Change seed to z on comparison failure. */ - for (i = 0; i < KYBER_SYM_SZ; i++) { - kr[i] ^= (kr[i] ^ key->z[i]) & fail; + { + /* Hash the cipher text after the seed. */ + ret = KYBER_HASH_H(&key->hash, ct, ctSz, kr + KYBER_SYM_SZ); + if (ret == 0) { + /* Change seed to z on comparison failure. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + kr[i] ^= (kr[i] ^ key->z[i]) & fail; + } + + /* Derive the secret from the seed and hash of cipher text. */ + ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); + } } - - /* Derive the secret from the seed and hash of cipher text. */ - ret = KYBER_KDF(kr, 2 * KYBER_SYM_SZ, ss, KYBER_SS_SZ); -#else - ret = kyber_derive_secret(key->z, ct, ctSz, msg); - } - if (ret == 0) { - /* Change seed to z on comparison failure. */ - for (i = 0; i < KYBER_SYM_SZ; i++) { - ss[i] = kr[i] ^ ((kr[i] ^ msg[i]) & fail); +#endif +#if defined(WOLFSSL_KYBER_ORIGINAL) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + ret = kyber_derive_secret(key->z, ct, ctSz, msg); + if (ret == 0) { + /* Change seed to z on comparison failure. */ + for (i = 0; i < KYBER_SYM_SZ; i++) { + ss[i] = kr[i] ^ ((kr[i] ^ msg[i]) & fail); + } + } } #endif } @@ -947,6 +1144,30 @@ int wc_KyberKey_DecodePrivateKey(KyberKey* key, const unsigned char* in, if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: k = KYBER512_K; @@ -968,6 +1189,7 @@ int wc_KyberKey_DecodePrivateKey(KyberKey* key, const unsigned char* in, pubLen = KYBER1024_PUBLIC_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -1030,6 +1252,27 @@ int wc_KyberKey_DecodePublicKey(KyberKey* key, const unsigned char* in, if (ret == 0) { /* Establish parameters based on key type. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: k = KYBER512_K; @@ -1048,6 +1291,7 @@ int wc_KyberKey_DecodePublicKey(KyberKey* key, const unsigned char* in, pubLen = KYBER1024_PUBLIC_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -1103,6 +1347,24 @@ int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) /* Return in 'len' size of the encoded private key for the type of this * key. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: *len = KYBER512_PRIVATE_KEY_SIZE; @@ -1118,6 +1380,7 @@ int wc_KyberKey_PrivateKeySize(KyberKey* key, word32* len) *len = KYBER1024_PRIVATE_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -1150,6 +1413,24 @@ int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) /* Return in 'len' size of the encoded public key for the type of this * key. */ switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: *len = KYBER512_PUBLIC_KEY_SIZE; @@ -1165,6 +1446,7 @@ int wc_KyberKey_PublicKeySize(KyberKey* key, word32* len) *len = KYBER1024_PUBLIC_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -1206,6 +1488,30 @@ int wc_KyberKey_EncodePrivateKey(KyberKey* key, unsigned char* out, word32 len) if (ret == 0) { switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: k = KYBER512_K; @@ -1227,6 +1533,7 @@ int wc_KyberKey_EncodePrivateKey(KyberKey* key, unsigned char* out, word32 len) privLen = KYBER1024_PRIVATE_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; @@ -1293,6 +1600,27 @@ int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len) if (ret == 0) { switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_KYBER_ORIGINAL #ifdef WOLFSSL_KYBER512 case KYBER512: k = KYBER512_K; @@ -1311,6 +1639,7 @@ int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, word32 len) pubLen = KYBER1024_PUBLIC_KEY_SIZE; break; #endif +#endif default: /* No other values supported. */ ret = NOT_COMPILED_IN; diff --git a/src/wolfcrypt/src/wc_kyber_poly.c b/src/wolfcrypt/src/wc_kyber_poly.c index 52c8af3..76b5cd5 100644 --- a/src/wolfcrypt/src/wc_kyber_poly.c +++ b/src/wolfcrypt/src/wc_kyber_poly.c @@ -33,6 +33,12 @@ * WOLFSSL_WC_KYBER Default: OFF * Enables this code, wolfSSL implementation, to be built. * + * WOLFSSL_WC_ML_KEM_512 Default: OFF + * Enables the ML-KEM 512 parameter implementations. + * WOLFSSL_WC_ML_KEM_768 Default: OFF + * Enables the ML-KEM 768 parameter implementations. + * WOLFSSL_WC_ML_KEM_1024 Default: OFF + * Enables the ML-KEM 1024 parameter implementations. * WOLFSSL_KYBER512 Default: OFF * Enables the KYBER512 parameter implementations. * WOLFSSL_KYBER768 Default: OFF @@ -49,7 +55,7 @@ * WOLFSSL_SMALL_STACK Default: OFF * Use less stack by dynamically allocating local variables. * - * WOLFSSL_KYBER_NTT_UNROLL Defualt: OFF + * WOLFSSL_KYBER_NTT_UNROLL Default: OFF * Enable an alternative NTT implementation that may be faster on some * platforms and is smaller in code size. * WOLFSSL_KYBER_INVNTT_UNROLL Default: OFF @@ -61,6 +67,7 @@ #include #endif +#include #include #include #include @@ -1133,7 +1140,7 @@ void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, } } -/* Encapsuluate message. +/* Encapsulate message. * * @param [in] pub Public key vector of polynomials. * @param [out] bp Vector of polynomials. @@ -1266,7 +1273,7 @@ void kyber_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, } } -/* Encapsuluate message. +/* Encapsulate message. * * @param [in] pub Public key vector of polynomials. * @param [out] bp Vector of polynomials. @@ -1402,7 +1409,7 @@ void kyber_decapsulate(const sword16* priv, sword16* mp, sword16* bp, /******************************************************************************/ #ifdef USE_INTEL_SPEEDUP -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1492,7 +1499,7 @@ static int kyber_gen_matrix_k2_avx2(sword16* a, byte* seed, int transposed) } #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1617,7 +1624,7 @@ static int kyber_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) return 0; } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1706,9 +1713,9 @@ static int kyber_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) return 0; } -#endif /* KYBER1024 */ +#endif /* WOLFSSL_KYBER1024 || WOLFSSL_WC_ML_KEM_1024 */ #elif defined(WOLFSSL_ARMASM) && defined(__aarch64__) -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1782,7 +1789,7 @@ static int kyber_gen_matrix_k2_aarch64(sword16* a, byte* seed, int transposed) } #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -1848,7 +1855,7 @@ static int kyber_gen_matrix_k3_aarch64(sword16* a, byte* seed, int transposed) } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Deterministically generate a matrix (or transpose) of uniform integers mod q. * * Seed used with XOF to generate random bytes. @@ -2067,17 +2074,24 @@ static int kyber_prf(wc_Shake* shake256, byte* out, unsigned int outLen, (25 - KYBER_SYM_SZ / 8 - 1) * sizeof(word64)); state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); - if (IS_INTEL_BMI2(cpuid_flags)) { - sha3_block_bmi2(state); - } - else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { - sha3_block_avx2(state); - RESTORE_VECTOR_REGISTERS(); - } - else { - BlockSha3(state); + while (outLen > 0) { + unsigned int len = min(outLen, WC_SHA3_256_BLOCK_SIZE); + + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && + (SAVE_VECTOR_REGISTERS2() == 0)) { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + XMEMCPY(out, state, len); + out += len; + outLen -= len; } - XMEMCPY(out, state, outLen); return 0; #else @@ -2381,7 +2395,7 @@ int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, { int ret; -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) if (kp == KYBER512_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_gen_matrix_k2_aarch64(a, seed, transposed); @@ -2400,7 +2414,7 @@ int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, } else #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) if (kp == KYBER768_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_gen_matrix_k3_aarch64(a, seed, transposed); @@ -2419,7 +2433,7 @@ int kyber_gen_matrix(KYBER_PRF_T* prf, sword16* a, int kp, byte* seed, } else #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) if (kp == KYBER1024_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_gen_matrix_k4_aarch64(a, seed, transposed); @@ -2556,7 +2570,7 @@ static void kyber_cbd_eta2(sword16* p, const byte* r) #endif } -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) /* Subtract one 3 bit value from another out of a larger number. * * @param [in] d Value containing sequential 3 bit values. @@ -2713,7 +2727,7 @@ static void kyber_cbd_eta3(sword16* p, const byte* r) /* Get noise/error by calculating random bytes and sampling to a binomial * distribution. * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [out] p Polynomial. * @param [in] seed Seed to use when calculating random. * @param [in] eta1 Size of noise/error integers. @@ -2726,7 +2740,7 @@ static int kyber_get_noise_eta1_c(KYBER_PRF_T* prf, sword16* p, (void)eta1; -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) if (eta1 == KYBER_CBD_ETA3) { byte rand[ETA3_RAND_SIZE]; @@ -2756,7 +2770,7 @@ static int kyber_get_noise_eta1_c(KYBER_PRF_T* prf, sword16* p, /* Get noise/error by calculating random bytes and sampling to a binomial * distribution. Values -2..2 * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [out] p Polynomial. * @param [in] seed Seed to use when calculating random. * @return 0 on success. @@ -2781,7 +2795,8 @@ static int kyber_get_noise_eta2_c(KYBER_PRF_T* prf, sword16* p, #ifdef USE_INTEL_SPEEDUP #define PRF_RAND_SZ (2 * SHA3_256_BYTES) -#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_KYBER1024) +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) || \ + defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Get the noise/error by calculating random bytes. * * @param [out] rand Random number byte array. @@ -2804,7 +2819,7 @@ static void kyber_get_noise_x4_eta2_avx2(byte* rand, byte* seed, byte o) } #endif -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) /* Get the noise/error by calculating random bytes. * * @param [out] rand Random number byte array. @@ -2835,7 +2850,7 @@ static void kyber_get_noise_x4_eta3_avx2(byte* rand, byte* seed) /* Get noise/error by calculating random bytes and sampling to a binomial * distribution. Values -2..2 * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [out] p Polynomial. * @param [in] seed Seed to use when calculating random. * @return 0 on success. @@ -2858,7 +2873,7 @@ static int kyber_get_noise_eta2_avx2(KYBER_PRF_T* prf, sword16* p, /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [out] vec1 First Vector of polynomials. * @param [out] vec2 Second Vector of polynomials. * @param [out] poly Polynomial. @@ -2890,7 +2905,7 @@ static int kyber_get_noise_k2_avx2(KYBER_PRF_T* prf, sword16* vec1, } #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * @@ -2921,11 +2936,11 @@ static int kyber_get_noise_k3_avx2(sword16* vec1, sword16* vec2, sword16* poly, } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [out] vec1 First Vector of polynomials. * @param [out] vec2 Second Vector of polynomials. * @param [out] poly Polynomial. @@ -2981,7 +2996,7 @@ static void kyber_get_noise_x3_eta2_aarch64(byte* rand, byte* seed, byte o) kyber_shake256_blocksx3_seed_neon(state, seed); } -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) /* Get the noise/error by calculating random bytes. * * @param [out] rand Random number byte array. @@ -3068,7 +3083,7 @@ static int kyber_get_noise_k2_aarch64(sword16* vec1, sword16* vec2, } #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Get the noise/error by calculating random bytes. * * @param [out] rand Random number byte array. @@ -3122,7 +3137,7 @@ static int kyber_get_noise_k3_aarch64(sword16* vec1, sword16* vec2, } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * @@ -3163,7 +3178,7 @@ static int kyber_get_noise_k4_aarch64(sword16* vec1, sword16* vec2, /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [in] kp Number of polynomials in vector. * @param [out] vec1 First Vector of polynomials. * @param [in] eta1 Size of noise/error integers with first vector. @@ -3208,7 +3223,7 @@ static int kyber_get_noise_c(KYBER_PRF_T* prf, int kp, sword16* vec1, int eta1, /* Get the noise/error by calculating random bytes and sampling to a binomial * distribution. * - * @param [in, out] prf Psuedo-random function object. + * @param [in, out] prf Pseudo-random function object. * @param [in] kp Number of polynomials in vector. * @param [out] vec1 First Vector of polynomials. * @param [out] vec2 Second Vector of polynomials. @@ -3221,7 +3236,7 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, { int ret; -#ifdef WOLFSSL_KYBER512 +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) if (kp == KYBER512_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_get_noise_k2_aarch64(vec1, vec2, poly, seed); @@ -3245,7 +3260,7 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, } else #endif -#ifdef WOLFSSL_KYBER768 +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) if (kp == KYBER768_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_get_noise_k3_aarch64(vec1, vec2, poly, seed); @@ -3265,7 +3280,7 @@ int kyber_get_noise(KYBER_PRF_T* prf, int kp, sword16* vec1, } else #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) if (kp == KYBER1024_K) { #if defined(WOLFSSL_ARMASM) && defined(__aarch64__) ret = kyber_get_noise_k4_aarch64(vec1, vec2, poly, seed); @@ -3475,7 +3490,8 @@ static KYBER_NOINLINE void kyber_csubq_c(sword16* p) #endif /* CONV_WITH_DIV */ -#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Compress the vector of polynomials into a byte array with 10 bits each. * * @param [out] b Array of bytes. @@ -3593,7 +3609,7 @@ void kyber_vec_compress_10(byte* r, sword16* v, unsigned int kp) } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Compress the vector of polynomials into a byte array with 11 bits each. * * @param [out] b Array of bytes. @@ -3713,7 +3729,8 @@ void kyber_vec_compress_11(byte* r, sword16* v) v[(i) * KYBER_N + 8 * (j) + (k)] = \ (word16)((((word32)((t) & 0x7ff) * KYBER_Q) + 1024) >> 11) -#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Decompress the byte array of packed 10 bits into vector of polynomials. * * @param [out] v Vector of polynomials. @@ -3785,7 +3802,7 @@ void kyber_vec_decompress_10(sword16* v, const unsigned char* b, } } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Decompress the byte array of packed 11 bits into vector of polynomials. * * @param [out] v Vector of polynomials. @@ -3948,7 +3965,8 @@ void kyber_vec_decompress_11(sword16* v, const unsigned char* b) #endif /* CONV_WITH_DIV */ -#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Compress a polynomial into byte array - on coefficients into 4 bits. * * @param [out] b Array of bytes. @@ -4020,7 +4038,7 @@ void kyber_compress_4(byte* b, sword16* p) } } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Compress a polynomial into byte array - on coefficients into 5 bits. * * @param [out] b Array of bytes. @@ -4117,7 +4135,8 @@ void kyber_compress_5(byte* b, sword16* p) #define DECOMP_5(p, i, j, t) \ p[(i) + (j)] = (((word32)((t) & 0x1f) * KYBER_Q) + 16) >> 5 -#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_KYBER768) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) /* Decompress the byte array of packed 4 bits into polynomial. * * @param [out] p Polynomial. @@ -4155,7 +4174,7 @@ void kyber_decompress_4(sword16* p, const unsigned char* b) } } #endif -#ifdef WOLFSSL_KYBER1024 +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) /* Decompress the byte array of packed 5 bits into polynomial. * * @param [out] p Polynomial. diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index 4559001..b2a3bf8 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -765,7 +765,7 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -880,7 +880,7 @@ int wc_LmsKey_Reload(LmsKey* key) #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -978,7 +978,7 @@ int wc_LmsKey_Sign(LmsKey* key, byte* sig, word32* sigSz, const byte* msg, #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -1239,7 +1239,7 @@ int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c index bb9345c..44bff83 100644 --- a/src/wolfcrypt/src/wc_lms_impl.c +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -41,6 +41,7 @@ #include #endif +#include #include #include @@ -103,7 +104,7 @@ #ifdef WC_LMS_DEBUG_PRINT_DATA -/* Print data when dubgging implementation. +/* Print data when debugging implementation. * * @param [in] name String to print before data. * @param [in] data Array of bytes. @@ -858,7 +859,7 @@ static int wc_lmots_msg_hash(LmsState* state, const byte* msg, word32 msgSz, * } * y[i] = tmp * } - * x[i] can be calculated on the fly using psueodo key generation in Appendix A. + * x[i] can be calculated on the fly using pseudo key generation in Appendix A. * Appendix A, The elements of the LM-OTS private keys are computed as: * x_q[i] = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). * @@ -874,7 +875,7 @@ static int wc_lmots_compute_y_from_seed(LmsState* state, const byte* seed, const byte* msg, word32 msgSz, const byte* c, byte* y) { const LmsParams* params = state->params; - int ret = 0; + int ret; word16 i; byte q[LMS_MAX_NODE_LEN + LMS_CKSM_LEN]; #ifdef WOLFSSL_SMALL_STACK @@ -891,8 +892,8 @@ static int wc_lmots_compute_y_from_seed(LmsState* state, const byte* seed, ret = wc_lmots_msg_hash(state, msg, msgSz, c, q); if (ret == 0) { /* Calculate checksum list all coefficients. */ - ret = wc_lmots_q_expand(q, params->hash_len, params->width, params->ls, - a); + ret = wc_lmots_q_expand(q, (word8)params->hash_len, params->width, + params->ls, a); } #ifndef WC_LMS_FULL_HASH if (ret == 0) { @@ -1062,8 +1063,8 @@ static int wc_lmots_compute_kc_from_sig(LmsState* state, const byte* msg, } if (ret == 0) { /* Calculate checksum list all coefficients. */ - ret = wc_lmots_q_expand(q, params->hash_len, params->width, params->ls, - a); + ret = wc_lmots_q_expand(q, (word8)params->hash_len, params->width, + params->ls, a); } #ifndef WC_LMS_FULL_HASH if (ret == 0) { @@ -1177,7 +1178,7 @@ static int wc_lmots_compute_kc_from_sig(LmsState* state, const byte* msg, * } * K = H(I || u32str(q) || u16str(D_PBLC) || y[0] || ... || y[p-1]) * ... - * x[i] can be calculated on the fly using psueodo key generation in Appendix A. + * x[i] can be calculated on the fly using pseudo key generation in Appendix A. * Appendix A, The elements of the LM-OTS private keys are computed as: * x_q[i] = H(I || u32str(q) || u16str(i) || u8str(0xff) || SEED). * @@ -1962,7 +1963,7 @@ static int wc_lms_treehash_init(LmsState* state, LmsPrivState* privState, #ifdef WOLFSSL_SMALL_STACK /* Allocate stack of left side hashes. */ - stack = XMALLOC((params->height + 1) * params->hash_len, NULL, + stack = (byte*)XMALLOC((params->height + 1) * params->hash_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (stack == NULL) { ret = MEMORY_E; @@ -2088,7 +2089,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, #ifdef WOLFSSL_SMALL_STACK /* Allocate stack of left side hashes. */ - stack = XMALLOC((params->height + 1) * params->hash_len, NULL, + stack = (byte*)XMALLOC((params->height + 1) * params->hash_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (stack == NULL) { ret = MEMORY_E; @@ -3678,11 +3679,11 @@ int wc_hss_sigsleft(const LmsParams* params, const byte* priv_raw) * * @param [in, out] state LMS state. * @param [in] pub HSS public key. - * @param [in] msg Message to rifyn. + * @param [in] msg Message to verify. * @param [in] msgSz Length of message in bytes. * @param [in] sig Signature of message. * @return 0 on success. - * @return SIG_VERFIY_E on failure. + * @return SIG_VERIFY_E on failure. */ int wc_hss_verify(LmsState* state, const byte* pub, const byte* msg, word32 msgSz, const byte* sig) diff --git a/src/wolfcrypt/src/wc_pkcs11.c b/src/wolfcrypt/src/wc_pkcs11.c index 4a3b28a..b3df75c 100644 --- a/src/wolfcrypt/src/wc_pkcs11.c +++ b/src/wolfcrypt/src/wc_pkcs11.c @@ -108,6 +108,8 @@ static CK_OBJECT_CLASS privKeyClass = CKO_PRIVATE_KEY; static CK_OBJECT_CLASS secretKeyClass = CKO_SECRET_KEY; #endif +static CK_OBJECT_CLASS certClass = CKO_CERTIFICATE; + #ifdef WOLFSSL_DEBUG_PKCS11 /* Enable logging of PKCS#11 calls and return value. */ #define PKCS11_RV(op, rv) pkcs11_rv(op, rv) @@ -240,6 +242,10 @@ static void pkcs11_dump_template(const char* name, CK_ATTRIBUTE* templ, XSNPRINTF(line, sizeof(line), "%25s: SECRET", type); WOLFSSL_MSG(line); } + else if (keyClass == CKO_CERTIFICATE) { + XSNPRINTF(line, sizeof(line), "%25s: CERTIFICATE", type); + WOLFSSL_MSG(line); + } else { XSNPRINTF(line, sizeof(line), "%25s: UNKNOWN (%p)", type, @@ -1463,7 +1469,8 @@ int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key) } #if !defined(NO_RSA) || defined(HAVE_ECC) || (!defined(NO_AES) && \ - (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || !defined(NO_HMAC) + (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || \ + !defined(NO_HMAC) || !defined(NO_CERTS) /** * Find the PKCS#11 object containing key data using template. @@ -2198,7 +2205,7 @@ static int Pkcs11Rsa(Pkcs11Session* session, wc_CryptoInfo* info) case WC_PK_TYPE_RSA_OAEP: mechanism = CKM_RSA_PKCS_OAEP; break; -#endif /* NO_PKCS11_RSA_PKCS */ +#endif /* !NO_PKCS11_RSA_PKCS */ case WC_PK_TYPE_RSA: mechanism = CKM_RSA_X_509; break; @@ -3671,7 +3678,7 @@ static int Pkcs11AesCbcEncrypt(Pkcs11Session* session, wc_CryptoInfo* info) if (ret == 0) { mech.mechanism = CKM_AES_CBC; - mech.ulParameterLen = AES_BLOCK_SIZE; + mech.ulParameterLen = WC_AES_BLOCK_SIZE; mech.pParameter = (CK_BYTE_PTR)info->cipher.aescbc.aes->reg; rv = session->func->C_EncryptInit(session->handle, &mech, key); @@ -3747,7 +3754,7 @@ static int Pkcs11AesCbcDecrypt(Pkcs11Session* session, wc_CryptoInfo* info) if (ret == 0) { mech.mechanism = CKM_AES_CBC; - mech.ulParameterLen = AES_BLOCK_SIZE; + mech.ulParameterLen = WC_AES_BLOCK_SIZE; mech.pParameter = (CK_BYTE_PTR)info->cipher.aescbc.aes->reg; rv = session->func->C_DecryptInit(session->handle, &mech, key); @@ -3965,6 +3972,90 @@ static int Pkcs11RandomSeed(Pkcs11Session* session, wc_CryptoInfo* info) } #endif +#ifndef NO_CERTS + +static int Pkcs11GetCert(Pkcs11Session* session, wc_CryptoInfo* info) { + int ret = 0; + CK_RV rv = 0; + CK_ULONG count = 0; + CK_OBJECT_HANDLE certHandle = CK_INVALID_HANDLE; + byte *certData = NULL; + CK_ATTRIBUTE certTemplate[2] = { + { CKA_CLASS, &certClass, sizeof(certClass) } + }; + CK_ATTRIBUTE tmpl[] = { + { CKA_VALUE, NULL_PTR, 0 } + }; + CK_ULONG certTmplCnt = sizeof(certTemplate) / sizeof(*certTemplate); + CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl); + + WOLFSSL_MSG("PKCS#11: Retrieve certificate"); + if (info->cert.labelLen > 0) { + certTemplate[1].type = CKA_LABEL; + certTemplate[1].pValue = (CK_VOID_PTR)info->cert.label; + certTemplate[1].ulValueLen = info->cert.labelLen; + } + else if (info->cert.idLen > 0) { + certTemplate[1].type = CKA_ID; + certTemplate[1].pValue = (CK_VOID_PTR)info->cert.id; + certTemplate[1].ulValueLen = info->cert.idLen; + } + else { + ret = BAD_FUNC_ARG; + goto exit; + } + + ret = Pkcs11FindKeyByTemplate( + &certHandle, session, certTemplate, certTmplCnt, &count); + if (ret == 0 && count == 0) { + ret = WC_HW_E; + goto exit; + } + + PKCS11_DUMP_TEMPLATE("Get Certificate Length", tmpl, tmplCnt); + rv = session->func->C_GetAttributeValue( + session->handle, certHandle, tmpl, tmplCnt); + PKCS11_RV("C_GetAttributeValue", rv); + if (rv != CKR_OK) { + ret = WC_HW_E; + goto exit; + } + + if (tmpl[0].ulValueLen <= 0) { + ret = WC_HW_E; + goto exit; + } + + certData = (byte *)XMALLOC( + (int)tmpl[0].ulValueLen, info->cert.heap, DYNAMIC_TYPE_CERT); + if (certData == NULL) { + ret = MEMORY_E; + goto exit; + } + + tmpl[0].pValue = certData; + rv = session->func->C_GetAttributeValue( + session->handle, certHandle, tmpl, tmplCnt); + PKCS11_RV("C_GetAttributeValue", rv); + if (rv != CKR_OK) { + ret = WC_HW_E; + goto exit; + } + + *info->cert.certDataOut = certData; + *info->cert.certSz = (word32)tmpl[0].ulValueLen; + if (info->cert.certFormatOut != NULL) { + *info->cert.certFormatOut = CTC_FILETYPE_ASN1; + } + certData = NULL; + +exit: + XFREE(certData, info->cert.heap, DYNAMIC_TYPE_CERT); + return ret; +} + +#endif /* !NO_CERTS */ + /** * Perform a cryptographic operation using PKCS#11 device. * @@ -4157,6 +4248,17 @@ int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx) } #else ret = NOT_COMPILED_IN; + #endif + } + else if (info->algo_type == WC_ALGO_TYPE_CERT) { + #ifndef NO_CERTS + ret = Pkcs11OpenSession(token, &session, readWrite); + if (ret == 0) { + ret = Pkcs11GetCert(&session, info); + Pkcs11CloseSession(token, &session); + } + #else + ret = NOT_COMPILED_IN; #endif } else diff --git a/src/wolfcrypt/src/wc_port.c b/src/wolfcrypt/src/wc_port.c index 7fe2d35..2ee85e3 100644 --- a/src/wolfcrypt/src/wc_port.c +++ b/src/wolfcrypt/src/wc_port.c @@ -1186,10 +1186,10 @@ int wc_strcasecmp(const char *s1, const char *s2) for (;;++s1, ++s2) { c1 = *s1; if ((c1 >= 'a') && (c1 <= 'z')) - c1 -= ('a' - 'A'); + c1 = (char)(c1 - ('a' - 'A')); c2 = *s2; if ((c2 >= 'a') && (c2 <= 'z')) - c2 -= ('a' - 'A'); + c2 = (char)(c2 - ('a' - 'A')); if ((c1 != c2) || (c1 == 0)) break; } @@ -1204,10 +1204,10 @@ int wc_strncasecmp(const char *s1, const char *s2, size_t n) for (c1 = 0, c2 = 0; n > 0; --n, ++s1, ++s2) { c1 = *s1; if ((c1 >= 'a') && (c1 <= 'z')) - c1 -= ('a' - 'A'); + c1 = (char)(c1 - ('a' - 'A')); c2 = *s2; if ((c2 >= 'a') && (c2 <= 'z')) - c2 -= ('a' - 'A'); + c2 = (char)(c2 - ('a' - 'A')); if ((c1 != c2) || (c1 == 0)) break; } @@ -1232,7 +1232,7 @@ char* wc_strdup_ex(const char *src, int memType) { } #endif -#ifdef WOLFSSL_ATOMIC_OPS +#if defined(WOLFSSL_ATOMIC_OPS) && !defined(SINGLE_THREADED) #ifdef HAVE_C___ATOMIC /* Atomic ops using standard C lib */ @@ -1292,8 +1292,9 @@ int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i) #endif /* WOLFSSL_ATOMIC_OPS */ -#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_ATOMIC_OPS) -void wolfSSL_RefInit(wolfSSL_Ref* ref, int* err) +#if !defined(SINGLE_THREADED) + +void wolfSSL_RefWithMutexInit(wolfSSL_RefWithMutex* ref, int* err) { int ret = wc_InitMutex(&ref->mutex); if (ret != 0) { @@ -1304,14 +1305,14 @@ void wolfSSL_RefInit(wolfSSL_Ref* ref, int* err) *err = ret; } -void wolfSSL_RefFree(wolfSSL_Ref* ref) +void wolfSSL_RefWithMutexFree(wolfSSL_RefWithMutex* ref) { if (wc_FreeMutex(&ref->mutex) != 0) { WOLFSSL_MSG("Failed to free mutex of reference counting!"); } } -void wolfSSL_RefInc(wolfSSL_Ref* ref, int* err) +void wolfSSL_RefWithMutexInc(wolfSSL_RefWithMutex* ref, int* err) { int ret = wc_LockMutex(&ref->mutex); if (ret != 0) { @@ -1324,7 +1325,17 @@ void wolfSSL_RefInc(wolfSSL_Ref* ref, int* err) *err = ret; } -void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err) +int wolfSSL_RefWithMutexLock(wolfSSL_RefWithMutex* ref) +{ + return wc_LockMutex(&ref->mutex); +} + +int wolfSSL_RefWithMutexUnlock(wolfSSL_RefWithMutex* ref) +{ + return wc_UnLockMutex(&ref->mutex); +} + +void wolfSSL_RefWithMutexDec(wolfSSL_RefWithMutex* ref, int* isZero, int* err) { int ret = wc_LockMutex(&ref->mutex); if (ret != 0) { @@ -1341,7 +1352,7 @@ void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err) } *err = ret; } -#endif +#endif /* ! SINGLE_THREADED */ #if WOLFSSL_CRYPT_HW_MUTEX /* Mutex for protection of cryptography hardware */ @@ -1782,7 +1793,7 @@ int wolfSSL_HwPkMutexUnLock(void) static void destruct_key(void *buf) { if (buf != NULL) { - free(buf); + XFREE(buf, NULL, DYNAMIC_TYPE_OS_BUF); } } @@ -1911,7 +1922,7 @@ int wolfSSL_HwPkMutexUnLock(void) key_ptr = pthread_getspecific(key_own_hw_mutex); if (key_ptr == NULL) { - key_ptr = malloc(sizeof(int)); + key_ptr = XMALLOC(sizeof(int), NULL, DYNAMIC_TYPE_OS_BUF); if (key_ptr == NULL) { return MEMORY_E; } @@ -3604,7 +3615,8 @@ time_t stm32_hal_time(time_t *t1) #endif /* !NO_ASN_TIME */ -#if !defined(WOLFSSL_LEANPSK) && !defined(STRING_USER) +#if (!defined(WOLFSSL_LEANPSK) && !defined(STRING_USER)) || \ + defined(USE_WOLF_STRNSTR) char* mystrnstr(const char* s1, const char* s2, unsigned int n) { unsigned int s2_len = (unsigned int)XSTRLEN(s2); @@ -3900,7 +3912,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) XMEMSET(thread, 0, sizeof(*thread)); thread->threadStack = (void *)XMALLOC(WOLFSSL_NETOS_STACK_SZ, NULL, - DYNAMIC_TYPE_TMP_BUFFER); + DYNAMIC_TYPE_OS_BUF); if (thread->threadStack == NULL) return MEMORY_E; @@ -3922,7 +3934,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) 2, 2, 1, TX_AUTO_START); if (result != TX_SUCCESS) { - free(thread->threadStack); + XFREE(thread->threadStack, NULL, DYNAMIC_TYPE_OS_BUF); thread->threadStack = NULL; return MEMORY_E; } @@ -3933,7 +3945,7 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) int wolfSSL_JoinThread(THREAD_TYPE thread) { /* TODO: maybe have to use tx_thread_delete? */ - free(thread.threadStack); + XFREE(thread.threadStack, NULL, DYNAMIC_TYPE_OS_BUF); thread.threadStack = NULL; return 0; } @@ -3954,6 +3966,14 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) XMEMSET(thread, 0, sizeof(*thread)); + thread->tid = (struct k_thread*)XMALLOC( + Z_KERNEL_STACK_SIZE_ADJUST(sizeof(struct k_thread)), + wolfsslThreadHeapHint, DYNAMIC_TYPE_TMP_BUFFER); + if (thread->tid == NULL) { + WOLFSSL_MSG("error: XMALLOC thread->tid failed"); + return MEMORY_E; + } + /* TODO: Use the following once k_thread_stack_alloc makes it into a * release. * thread->threadStack = k_thread_stack_alloc(WOLFSSL_ZEPHYR_STACK_SZ, @@ -3963,14 +3983,18 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) Z_KERNEL_STACK_SIZE_ADJUST(WOLFSSL_ZEPHYR_STACK_SZ), wolfsslThreadHeapHint, DYNAMIC_TYPE_TMP_BUFFER); if (thread->threadStack == NULL) { - WOLFSSL_MSG("error: XMALLOC failed"); + XFREE(thread->tid, wolfsslThreadHeapHint, + DYNAMIC_TYPE_TMP_BUFFER); + thread->tid = NULL; + + WOLFSSL_MSG("error: XMALLOC thread->threadStack failed"); return MEMORY_E; } /* k_thread_create does not return any error codes */ /* Casting to k_thread_entry_t should be fine since we just ignore the * extra arguments being passed in */ - k_thread_create(&thread->tid, thread->threadStack, + k_thread_create(thread->tid, thread->threadStack, WOLFSSL_ZEPHYR_STACK_SZ, (k_thread_entry_t)cb, arg, NULL, NULL, 5, 0, K_NO_WAIT); @@ -3982,10 +4006,14 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) int ret = 0; int err; - err = k_thread_join(&thread.tid, K_FOREVER); + err = k_thread_join(thread.tid, K_FOREVER); if (err != 0) ret = MEMORY_E; + XFREE(thread.tid, wolfsslThreadHeapHint, + DYNAMIC_TYPE_TMP_BUFFER); + thread.tid = NULL; + /* TODO: Use the following once k_thread_stack_free makes it into a * release. * err = k_thread_stack_free(thread.threadStack); @@ -4226,3 +4254,13 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) #endif /* Environment check */ #endif /* not SINGLE_THREADED */ + +#if defined(WOLFSSL_LINUXKM) && defined(CONFIG_ARM64) && \ + defined(USE_WOLFSSL_LINUXKM_PIE_REDIRECT_TABLE) +noinstr void my__alt_cb_patch_nops(struct alt_instr *alt, __le32 *origptr, + __le32 *updptr, int nr_inst) +{ + return (wolfssl_linuxkm_get_pie_redirect_table()-> + alt_cb_patch_nops)(alt, origptr, updptr, nr_inst); +} +#endif diff --git a/src/wolfcrypt/src/wc_xmss.c b/src/wolfcrypt/src/wc_xmss.c index 5c016db..6546597 100644 --- a/src/wolfcrypt/src/wc_xmss.c +++ b/src/wolfcrypt/src/wc_xmss.c @@ -738,7 +738,7 @@ static WC_INLINE int wc_xmsskey_signupdate(XmssKey* key, byte* sig, #endif #ifdef WOLFSSL_SMALL_STACK - state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (XmssState*)XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -1109,7 +1109,7 @@ int wc_XmssKey_MakeKey(XmssKey* key, WC_RNG* rng) #endif #ifdef WOLFSSL_SMALL_STACK - state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (XmssState*)XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -1645,7 +1645,7 @@ int wc_XmssKey_Verify(XmssKey* key, const byte* sig, word32 sigLen, #endif #ifdef WOLFSSL_SMALL_STACK - state = XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (XmssState*)XMALLOC(sizeof(XmssState), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } diff --git a/src/wolfcrypt/src/wolfmath.c b/src/wolfcrypt/src/wolfmath.c index ce36b60..9a6e312 100644 --- a/src/wolfcrypt/src/wolfmath.c +++ b/src/wolfcrypt/src/wolfmath.c @@ -149,10 +149,10 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) for (; i < b->used; i++) { b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; } - b->used ^= (a->used ^ b->used) & (mp_size_t)mask; + b->used ^= (a->used ^ b->used) & (wc_mp_size_t)mask; #if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \ defined(WOLFSSL_SP_INT_NEGATIVE) - b->sign ^= (mp_sign_t)(a->sign ^ b->sign) & (mp_sign_t)mask; + b->sign ^= (wc_mp_sign_t)(a->sign ^ b->sign) & (wc_mp_sign_t)mask; #endif } @@ -167,8 +167,6 @@ int get_rand_digit(WC_RNG* rng, mp_digit* d) return wc_RNG_GenerateBlock(rng, (byte*)d, sizeof(mp_digit)); } -#if defined(WC_RSA_BLINDING) || defined(WOLFCRYPT_HAVE_SAKKE) || \ - defined(WOLFSSL_ECC_BLIND_K) int mp_rand(mp_int* a, int digits, WC_RNG* rng) { int ret = 0; @@ -196,7 +194,7 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) ret = BAD_FUNC_ARG; } if (ret == MP_OKAY) { - a->used = (mp_size_t)digits; + a->used = (wc_mp_size_t)digits; } #endif /* fill the data with random bytes */ @@ -222,7 +220,6 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) return ret; } -#endif /* WC_RSA_BLINDING || WOLFCRYPT_HAVE_SAKKE || WOLFSSL_ECC_BLIND_K */ #endif /* !WC_NO_RNG */ #if defined(HAVE_ECC) || defined(WOLFSSL_EXPORT_INT) @@ -474,14 +471,16 @@ const char *wc_GetMathInfo(void) #elif defined(WOLFSSL_HAVE_SP_DH) " dh" #endif - #ifndef WOLFSSL_SP_NO_2048 - " 2048" - #endif - #ifndef WOLFSSL_SP_NO_3072 - " 3072" - #endif - #ifdef WOLFSSL_SP_4096 - " 4096" + #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) + #ifndef WOLFSSL_SP_NO_2048 + " 2048" + #endif + #ifndef WOLFSSL_SP_NO_3072 + " 3072" + #endif + #ifdef WOLFSSL_SP_4096 + " 4096" + #endif #endif #ifdef WOLFSSL_SP_ASM " asm" diff --git a/src/wolfssl.h b/src/wolfssl.h index 46ef50d..c7e39d4 100644 --- a/src/wolfssl.h +++ b/src/wolfssl.h @@ -27,7 +27,15 @@ #include -/* wolfSSL user_settings.h must be included from settings.h */ +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must be listed before any other wolfSSL include. + */ #include #include diff --git a/src/wolfssl/bio.c b/src/wolfssl/bio.c index ac4eb03..b265456 100644 --- a/src/wolfssl/bio.c +++ b/src/wolfssl/bio.c @@ -146,7 +146,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrSz = bio->wrSzReset; } else { @@ -163,7 +163,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; } else if (bio->rdIdx >= WOLFSSL_BIO_RESIZE_THRESHOLD && - !(bio->flags & BIO_FLAGS_MEM_RDONLY)) { + !(bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY)) { /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, @@ -200,6 +200,7 @@ int wolfSSL_BIO_method_type(const WOLFSSL_BIO *b) } #ifndef WOLFCRYPT_ONLY +#ifndef NO_TLS /* Helper function to read from WOLFSSL_BIO_SSL type * * returns the number of bytes read on success @@ -231,10 +232,11 @@ static int wolfSSL_BIO_SSL_read(WOLFSSL_BIO* bio, void* buf, return ret; } +#endif /* !NO_TLS */ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) { - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, buf, (unsigned int)sz) != WOLFSSL_SUCCESS) { @@ -249,7 +251,7 @@ static int wolfSSL_BIO_MD_read(WOLFSSL_BIO* bio, void* buf, int sz) } return sz; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY */ /* Used to read data from a WOLFSSL_BIO structure @@ -331,7 +333,7 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) ret = wolfSSL_BIO_SSL_read(bio, buf, len, front); #else WOLFSSL_MSG("WOLFSSL_BIO_SSL used with WOLFCRYPT_ONLY"); @@ -500,7 +502,7 @@ static int wolfSSL_BIO_BASE64_write(WOLFSSL_BIO* bio, const void* data, } #endif /* WOLFSSL_BASE64_ENCODE */ -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* Helper function for writing to a WOLFSSL_BIO_SSL type * * returns the amount written in bytes on success @@ -531,7 +533,7 @@ static int wolfSSL_BIO_SSL_write(WOLFSSL_BIO* bio, const void* data, } return ret; } -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY && !NO_TLS */ /* Writes to a WOLFSSL_BIO_BIO type. * @@ -601,7 +603,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("one of input parameters is null"); return WOLFSSL_FAILURE; } - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { return WOLFSSL_FAILURE; } @@ -642,7 +644,7 @@ static int wolfSSL_BIO_MD_write(WOLFSSL_BIO* bio, const void* data, int len) return BAD_FUNC_ARG; } - if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == NID_hmac) { + if (wolfSSL_EVP_MD_CTX_type(bio->ptr.md_ctx) == WC_NID_hmac) { if (wolfSSL_EVP_DigestSignUpdate(bio->ptr.md_ctx, data, (unsigned int)len) != WOLFSSL_SUCCESS) { ret = WOLFSSL_BIO_ERROR; @@ -746,7 +748,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif /* !NO_FILESYSTEM */ break; case WOLFSSL_BIO_SSL: - #ifndef WOLFCRYPT_ONLY + #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) /* already got eof, again is error */ if (front->eof) { ret = WOLFSSL_FATAL_ERROR; @@ -823,7 +825,7 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) bio = bio->next; } -#ifndef WOLFCRYPT_ONLY +#if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) exit_chain: #endif @@ -866,23 +868,23 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) } switch(cmd) { - case BIO_CTRL_PENDING: - case BIO_CTRL_WPENDING: + case WOLFSSL_BIO_CTRL_PENDING: + case WOLFSSL_BIO_CTRL_WPENDING: ret = (long)wolfSSL_BIO_ctrl_pending(bio); break; - case BIO_CTRL_INFO: + case WOLFSSL_BIO_CTRL_INFO: ret = (long)wolfSSL_BIO_get_mem_data(bio, parg); break; - case BIO_CTRL_FLUSH: + case WOLFSSL_BIO_CTRL_FLUSH: ret = (long)wolfSSL_BIO_flush(bio); break; - case BIO_CTRL_RESET: + case WOLFSSL_BIO_CTRL_RESET: ret = (long)wolfSSL_BIO_reset(bio); break; #ifdef WOLFSSL_HAVE_BIO_ADDR - case BIO_CTRL_DGRAM_CONNECT: - case BIO_CTRL_DGRAM_SET_PEER: + case WOLFSSL_BIO_CTRL_DGRAM_CONNECT: + case WOLFSSL_BIO_CTRL_DGRAM_SET_PEER: { socklen_t addr_size; if (parg == NULL) { @@ -899,7 +901,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) break; } - case BIO_CTRL_DGRAM_SET_CONNECTED: + case WOLFSSL_BIO_CTRL_DGRAM_SET_CONNECTED: if (parg == NULL) { wolfSSL_BIO_ADDR_clear(&bio->peer_addr); bio->connected = 0; @@ -916,7 +918,7 @@ long wolfSSL_BIO_ctrl(WOLFSSL_BIO *bio, int cmd, long larg, void *parg) ret = WOLFSSL_SUCCESS; break; - case BIO_CTRL_DGRAM_QUERY_MTU: + case WOLFSSL_BIO_CTRL_DGRAM_QUERY_MTU: ret = 0; /* not implemented */ break; @@ -1371,7 +1373,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) int closeFlag) { if (!bio || !bufMem || - (closeFlag != BIO_NOCLOSE && closeFlag != BIO_CLOSE)) + (closeFlag != WOLFSSL_BIO_NOCLOSE && closeFlag != WOLFSSL_BIO_CLOSE)) return BAD_FUNC_ARG; if (bio->mem_buf) @@ -1379,7 +1381,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) wolfSSL_BUF_MEM_free(bio->mem_buf); bio->mem_buf = bufMem; - bio->shutdown = closeFlag; + bio->shutdown = closeFlag ? WOLFSSL_BIO_CLOSE : WOLFSSL_BIO_NOCLOSE; bio->wrSz = (int)bio->mem_buf->length; bio->wrSzReset = bio->wrSz; @@ -1717,7 +1719,7 @@ int wolfSSL_BIO_reset(WOLFSSL_BIO *bio) case WOLFSSL_BIO_MEMORY: bio->rdIdx = 0; - if (bio->flags & BIO_FLAGS_MEM_RDONLY) { + if (bio->flags & WOLFSSL_BIO_FLAG_MEM_RDONLY) { bio->wrIdx = bio->wrSzReset; bio->wrSz = bio->wrSzReset; } @@ -1826,7 +1828,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) } if (bio->type == WOLFSSL_BIO_FILE) { - if (bio->ptr.fh != XBADFILE && bio->shutdown == BIO_CLOSE) { + if (bio->ptr.fh != XBADFILE && bio->shutdown == WOLFSSL_BIO_CLOSE) { XFCLOSE(bio->ptr.fh); } @@ -1839,7 +1841,7 @@ int wolfSSL_BIO_write_filename(WOLFSSL_BIO *bio, char *name) if (bio->ptr.fh == XBADFILE) { return WOLFSSL_FAILURE; } - bio->shutdown = BIO_CLOSE; + bio->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2201,7 +2203,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (bio->method != NULL && bio->method->ctrlCb != NULL) { WOLFSSL_MSG("Calling custom BIO flush callback"); - return (int)bio->method->ctrlCb(bio, BIO_CTRL_FLUSH, 0, NULL); + return (int)bio->method->ctrlCb(bio, WOLFSSL_BIO_CTRL_FLUSH, 0, NULL); } else if (bio->type == WOLFSSL_BIO_FILE) { #if !defined(NO_FILESYSTEM) && defined(XFFLUSH) @@ -2387,7 +2389,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->type = WOLFSSL_BIO_SOCKET; } else { - BIO_free(bio); + wolfSSL_BIO_free(bio); bio = NULL; } } @@ -2477,7 +2479,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; return WOLFSSL_SUCCESS; } @@ -2506,7 +2508,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } b->num.fd = sfd; - b->shutdown = BIO_CLOSE; + b->shutdown = WOLFSSL_BIO_CLOSE; } else { WOLFSSL_BIO* new_bio; @@ -2516,7 +2518,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return WOLFSSL_FAILURE; } /* Create a socket BIO for using the accept'ed connection */ - new_bio = wolfSSL_BIO_new_socket(newfd, BIO_CLOSE); + new_bio = wolfSSL_BIO_new_socket(newfd, WOLFSSL_BIO_CLOSE); if (new_bio == NULL) { WOLFSSL_MSG("wolfSSL_BIO_new_socket error"); CloseSocket(newfd); @@ -2560,6 +2562,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return ret; } +#ifndef NO_TLS long wolfSSL_BIO_do_handshake(WOLFSSL_BIO *b) { WOLFSSL_ENTER("wolfSSL_BIO_do_handshake"); @@ -2595,7 +2598,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) if (b->ptr.ssl != NULL) { int rc = wolfSSL_shutdown(b->ptr.ssl); - if (rc == SSL_SHUTDOWN_NOT_DONE) { + if (rc == WOLFSSL_SHUTDOWN_NOT_DONE) { /* In this case, call again to give us a chance to read the * close notify alert from the other end. */ wolfSSL_shutdown(b->ptr.ssl); @@ -2605,6 +2608,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_MSG("BIO has no SSL pointer set."); } } +#endif long wolfSSL_BIO_set_ssl(WOLFSSL_BIO* b, WOLFSSL* ssl, int closeF) { @@ -2682,7 +2686,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else wolfSSL_set_connect_state(ssl); } - if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, BIO_CLOSE) != + if (err == 0 && wolfSSL_BIO_set_ssl(sslBio, ssl, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to set SSL pointer in BIO."); err = 1; @@ -2831,13 +2835,20 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) #else bio->method = method; #endif - bio->shutdown = BIO_CLOSE; /* default to close things */ + bio->shutdown = WOLFSSL_BIO_CLOSE; /* default to close things */ if ((bio->type == WOLFSSL_BIO_SOCKET) || (bio->type == WOLFSSL_BIO_DGRAM)) { bio->num.fd = SOCKET_INVALID; - } else { + } + else if (bio->type == WOLFSSL_BIO_FILE) { +#ifndef NO_FILESYSTEM + bio->ptr.fh = XBADFILE; +#endif + bio->num.fd = SOCKET_INVALID; + } + else { bio->num.length = 0; } bio->init = 1; @@ -2916,7 +2927,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { XMEMCPY(bio->ptr.mem_buf_data, buf, len); - bio->flags |= BIO_FLAGS_MEM_RDONLY; + bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -2994,7 +3005,9 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #ifndef NO_FILESYSTEM - if (bio->type == WOLFSSL_BIO_FILE && bio->shutdown == BIO_CLOSE) { + if (bio->type == WOLFSSL_BIO_FILE && + bio->shutdown == WOLFSSL_BIO_CLOSE) + { if (bio->ptr.fh) { XFCLOSE(bio->ptr.fh); } @@ -3007,7 +3020,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } #endif - if (bio->shutdown != BIO_NOCLOSE) { + if (bio->shutdown != WOLFSSL_BIO_NOCLOSE) { if (bio->type == WOLFSSL_BIO_MEMORY && bio->ptr.mem_buf_data != NULL) { @@ -3409,7 +3422,7 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) if (fp == XBADFILE) return WOLFSSL_BAD_FILE; - if (wolfSSL_BIO_set_fp(b, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(b, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); return WOLFSSL_BAD_FILE; } @@ -3446,7 +3459,7 @@ WOLFSSL_BIO *wolfSSL_BIO_new_file(const char *filename, const char *mode) return bio; } - if (wolfSSL_BIO_set_fp(bio, fp, BIO_CLOSE) != WOLFSSL_SUCCESS) { + if (wolfSSL_BIO_set_fp(bio, fp, WOLFSSL_BIO_CLOSE) != WOLFSSL_SUCCESS) { XFCLOSE(fp); wolfSSL_BIO_free(bio); bio = NULL; diff --git a/src/wolfssl/callbacks.h b/src/wolfssl/callbacks.h index 1010eca..dc3ad89 100644 --- a/src/wolfssl/callbacks.h +++ b/src/wolfssl/callbacks.h @@ -36,7 +36,7 @@ enum { /* CALLBACK CONSTANTS */ MAX_CIPHERNAME_SZ = 24, MAX_TIMEOUT_NAME_SZ = 24, MAX_PACKETS_HANDSHAKE = 14, /* 12 for client auth plus 2 alerts */ - MAX_VALUE_SZ = 128, /* all handshake packets but Cert should + MAX_VALUE_SZ = 128 /* all handshake packets but Cert should fit here */ }; diff --git a/src/wolfssl/certs_test.h b/src/wolfssl/certs_test.h index 013b374..37e8da8 100644 --- a/src/wolfssl/certs_test.h +++ b/src/wolfssl/certs_test.h @@ -100,9 +100,9 @@ static const int sizeof_client_keypub_der_1024 = sizeof(client_keypub_der_1024); static const unsigned char client_cert_der_1024[] = { 0x30, 0x82, 0x04, 0x18, 0x30, 0x82, 0x03, 0x81, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x59, 0xF2, 0xEA, 0x44, 0x08, - 0xB5, 0x12, 0x30, 0xA0, 0x96, 0x93, 0xD1, 0xD1, 0x7F, 0xE1, - 0xEC, 0x49, 0x75, 0x9B, 0xA2, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x09, 0x1D, 0x03, 0x41, 0x8B, + 0x92, 0xBD, 0x2A, 0x2A, 0x1C, 0x77, 0xE0, 0x13, 0xA8, 0x3D, + 0xF0, 0x33, 0xDA, 0x7F, 0x72, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -120,10 +120,10 @@ static const unsigned char client_cert_der_1024[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -180,8 +180,8 @@ static const unsigned char client_cert_der_1024[] = 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, - 0x59, 0xF2, 0xEA, 0x44, 0x08, 0xB5, 0x12, 0x30, 0xA0, 0x96, - 0x93, 0xD1, 0xD1, 0x7F, 0xE1, 0xEC, 0x49, 0x75, 0x9B, 0xA2, + 0x09, 0x1D, 0x03, 0x41, 0x8B, 0x92, 0xBD, 0x2A, 0x2A, 0x1C, + 0x77, 0xE0, 0x13, 0xA8, 0x3D, 0xF0, 0x33, 0xDA, 0x7F, 0x72, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, @@ -191,20 +191,20 @@ static const unsigned char client_cert_der_1024[] = 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, - 0x03, 0x81, 0x81, 0x00, 0x45, 0x63, 0x6F, 0xF9, 0xED, 0xF4, - 0x12, 0x3C, 0x3C, 0xC5, 0x2C, 0x51, 0x08, 0x94, 0x61, 0x7E, - 0x08, 0xE8, 0x32, 0x46, 0x2B, 0x22, 0x02, 0xD0, 0xE8, 0x2B, - 0xA4, 0x23, 0x15, 0x48, 0x47, 0x87, 0x5D, 0x72, 0xAB, 0x38, - 0xD5, 0x34, 0xB9, 0xFC, 0xF4, 0x86, 0x93, 0x49, 0x95, 0xD8, - 0x81, 0x32, 0x1C, 0x21, 0xE3, 0xEF, 0xB8, 0x40, 0xC5, 0x87, - 0x02, 0xE8, 0x28, 0xAA, 0x54, 0x93, 0x2D, 0x8A, 0xE9, 0x1E, - 0xDD, 0x5D, 0x11, 0xF8, 0xBF, 0xCA, 0x4E, 0x33, 0x20, 0x56, - 0x4E, 0x6F, 0x53, 0xBB, 0x79, 0xB0, 0xDA, 0x65, 0xA1, 0x4B, - 0x9F, 0xC8, 0x55, 0xFA, 0x53, 0x26, 0x84, 0xC6, 0x1E, 0x0A, - 0x5E, 0x7A, 0x6E, 0xF2, 0x2D, 0x2A, 0x81, 0xA5, 0xD0, 0x2B, - 0xEC, 0xD5, 0x8E, 0xB9, 0xF0, 0xC7, 0x57, 0xD7, 0xD6, 0x14, - 0x1A, 0x3B, 0xDC, 0x09, 0x41, 0xB4, 0x9D, 0x0D, 0x72, 0x20, - 0x44, 0x79 + 0x03, 0x81, 0x81, 0x00, 0x9A, 0x1C, 0x8F, 0xC4, 0xBD, 0x54, + 0xDA, 0x63, 0xA7, 0xF8, 0xBA, 0x39, 0xB6, 0x64, 0x60, 0x9D, + 0xBA, 0xA5, 0xFC, 0x43, 0xF5, 0x57, 0x28, 0x31, 0x43, 0x09, + 0x4C, 0x03, 0x4C, 0xB8, 0xC3, 0x49, 0x2B, 0x4E, 0xBF, 0xF2, + 0x9B, 0x13, 0x4E, 0x37, 0x1E, 0xA1, 0x57, 0xC6, 0x0C, 0x7B, + 0x2C, 0x25, 0x19, 0x37, 0x9F, 0x06, 0x53, 0xEF, 0x8D, 0xD1, + 0xBA, 0xC0, 0x73, 0x6E, 0x7F, 0xC2, 0x0B, 0x46, 0x5F, 0x9B, + 0x56, 0xBB, 0x59, 0x19, 0x5C, 0xC9, 0xEE, 0xEA, 0x02, 0xDA, + 0x03, 0x2C, 0xFB, 0x29, 0xB6, 0x07, 0xDD, 0x55, 0xB7, 0xE9, + 0xCE, 0x60, 0x47, 0xE0, 0x6B, 0x44, 0x5A, 0x61, 0x74, 0x5C, + 0x96, 0xF6, 0x30, 0xD8, 0x1B, 0xA4, 0x15, 0x5E, 0x06, 0xC5, + 0x73, 0x4B, 0x8A, 0x4D, 0x94, 0x23, 0x13, 0x1B, 0x3F, 0xDB, + 0x67, 0xCA, 0xA7, 0xA6, 0x41, 0xC5, 0x28, 0x0F, 0xFD, 0x2E, + 0x0E, 0xF0 }; static const int sizeof_client_cert_der_1024 = sizeof(client_cert_der_1024); @@ -418,9 +418,9 @@ static const int sizeof_ca_key_der_1024 = sizeof(ca_key_der_1024); static const unsigned char ca_cert_der_1024[] = { 0x30, 0x82, 0x04, 0x09, 0x30, 0x82, 0x03, 0x72, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x5C, 0x44, 0x2B, 0xBF, 0xD3, - 0xA8, 0x2A, 0xD8, 0xFD, 0x54, 0xC9, 0xCD, 0xAA, 0x7F, 0xF7, - 0xD4, 0x59, 0x07, 0xAA, 0xDD, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x59, 0x52, 0x6B, 0x92, 0x1A, + 0x25, 0x8F, 0x1B, 0xEE, 0x4C, 0x51, 0x9C, 0x47, 0x2F, 0xFF, + 0xFF, 0x9D, 0x43, 0x29, 0x47, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x99, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -438,9 +438,9 @@ static const unsigned char ca_cert_der_1024[] = 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, - 0x32, 0x33, 0x31, 0x32, 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x17, 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, - 0x38, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x30, 0x81, + 0x32, 0x34, 0x31, 0x32, 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x17, 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, + 0x34, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x30, 0x81, 0x99, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, @@ -496,9 +496,9 @@ static const unsigned char ca_cert_der_1024[] = 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, - 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x5C, 0x44, 0x2B, 0xBF, 0xD3, - 0xA8, 0x2A, 0xD8, 0xFD, 0x54, 0xC9, 0xCD, 0xAA, 0x7F, 0xF7, - 0xD4, 0x59, 0x07, 0xAA, 0xDD, 0x30, 0x0C, 0x06, 0x03, 0x55, + 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x59, 0x52, 0x6B, 0x92, 0x1A, + 0x25, 0x8F, 0x1B, 0xEE, 0x4C, 0x51, 0x9C, 0x47, 0x2F, 0xFF, + 0xFF, 0x9D, 0x43, 0x29, 0x47, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, @@ -507,20 +507,20 @@ static const unsigned char ca_cert_der_1024[] = 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, - 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x70, - 0x7D, 0x83, 0x94, 0xD0, 0xEE, 0xE1, 0x19, 0x8B, 0x17, 0xCA, - 0x79, 0x87, 0x12, 0x5B, 0x7F, 0x70, 0xA3, 0x51, 0x20, 0x4F, - 0x21, 0x99, 0x71, 0x69, 0x21, 0x28, 0x55, 0x61, 0x70, 0x85, - 0x54, 0x21, 0xA9, 0x70, 0xA2, 0xA9, 0x12, 0xDB, 0x44, 0x11, - 0x44, 0xE7, 0x41, 0x00, 0x70, 0x80, 0xB5, 0x37, 0x0C, 0x7E, - 0x78, 0x8F, 0x88, 0x64, 0xBC, 0xE5, 0xC0, 0x44, 0xA7, 0xA5, - 0x3D, 0xDB, 0x62, 0xC4, 0xD6, 0xCD, 0xAA, 0x4B, 0xAC, 0xFB, - 0x01, 0x46, 0xBB, 0xEC, 0xCB, 0x6F, 0x01, 0x67, 0xB4, 0x65, - 0xF3, 0x5E, 0x53, 0x39, 0x64, 0x99, 0x9B, 0x68, 0x80, 0x14, - 0x91, 0xA4, 0xA4, 0xEB, 0x04, 0xF3, 0x76, 0x9A, 0x7D, 0xB4, - 0x38, 0x05, 0x9C, 0xA5, 0xE0, 0xBC, 0x7E, 0xD9, 0xD2, 0xD3, - 0xD4, 0xE8, 0xC3, 0x9F, 0x38, 0x4B, 0x6C, 0x29, 0x94, 0xBE, - 0x35, 0xBD, 0x30, 0x1F, 0xB5, 0xB7, 0x3D + 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x09, + 0xC6, 0xDA, 0xFE, 0x2A, 0x45, 0x83, 0x9E, 0x8B, 0x66, 0xCF, + 0x63, 0x1F, 0x11, 0xCB, 0xD9, 0xB4, 0xEB, 0xB0, 0x97, 0x3D, + 0x33, 0xD4, 0xB9, 0x27, 0x56, 0x46, 0x14, 0x3C, 0xFE, 0x2B, + 0xB2, 0x36, 0x6E, 0x38, 0x7F, 0x08, 0xF5, 0x37, 0x3C, 0xF2, + 0xA2, 0x6A, 0x8A, 0xC7, 0xA0, 0xBE, 0x0F, 0xAC, 0xDD, 0xF4, + 0xF0, 0x97, 0xB3, 0x03, 0xA6, 0x70, 0x48, 0x44, 0xFC, 0xEF, + 0xEF, 0x7A, 0xC6, 0x1A, 0x8D, 0x3F, 0x19, 0xF6, 0x71, 0x92, + 0x7E, 0x3A, 0x00, 0x95, 0xF2, 0xB6, 0x57, 0x40, 0x77, 0xC2, + 0x80, 0x4E, 0x61, 0xF2, 0x71, 0x56, 0x22, 0xA0, 0x1E, 0xA9, + 0xDD, 0x5C, 0x54, 0x80, 0xAD, 0xE4, 0x27, 0xF2, 0x17, 0x20, + 0x9B, 0x5B, 0x89, 0x30, 0x6E, 0x6A, 0x31, 0x2A, 0x4E, 0x43, + 0x52, 0xF8, 0x8A, 0x51, 0xB7, 0xED, 0x3A, 0xAA, 0x78, 0x41, + 0x90, 0x95, 0xE8, 0x40, 0x2E, 0x66, 0xFC }; static const int sizeof_ca_cert_der_1024 = sizeof(ca_cert_der_1024); @@ -613,9 +613,9 @@ static const unsigned char server_cert_der_1024[] = 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x30, 0x1E, 0x17, - 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, 0x33, 0x32, 0x32, 0x31, - 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, 0x32, 0x36, 0x30, 0x39, - 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x30, + 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, 0x38, 0x32, 0x31, 0x32, + 0x35, 0x33, 0x30, 0x5A, 0x17, 0x0D, 0x32, 0x37, 0x30, 0x39, + 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0x95, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, @@ -671,9 +671,9 @@ static const unsigned char server_cert_der_1024[] = 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, - 0x82, 0x14, 0x5C, 0x44, 0x2B, 0xBF, 0xD3, 0xA8, 0x2A, 0xD8, - 0xFD, 0x54, 0xC9, 0xCD, 0xAA, 0x7F, 0xF7, 0xD4, 0x59, 0x07, - 0xAA, 0xDD, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, + 0x82, 0x14, 0x59, 0x52, 0x6B, 0x92, 0x1A, 0x25, 0x8F, 0x1B, + 0xEE, 0x4C, 0x51, 0x9C, 0x47, 0x2F, 0xFF, 0xFF, 0x9D, 0x43, + 0x29, 0x47, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, @@ -682,20 +682,20 @@ static const unsigned char server_cert_der_1024[] = 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, - 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x35, 0x2E, 0x7B, 0x57, - 0x7B, 0x64, 0x70, 0x53, 0xE0, 0x81, 0xED, 0xF4, 0xAC, 0xB3, - 0x3A, 0x3B, 0xBA, 0x82, 0x8D, 0xA2, 0x31, 0xD9, 0xD4, 0xAC, - 0xD1, 0x8A, 0x6D, 0x35, 0x41, 0x15, 0xB3, 0xE8, 0x06, 0x91, - 0xCA, 0x2A, 0xF7, 0xFF, 0x28, 0x0E, 0x3D, 0xCD, 0xE7, 0x28, - 0xF0, 0x07, 0xC0, 0x78, 0x62, 0x9E, 0x88, 0x3D, 0xDC, 0x98, - 0xF0, 0x8C, 0x89, 0xA7, 0x1C, 0x5B, 0x77, 0x37, 0xB2, 0x55, - 0x38, 0xB2, 0x60, 0x42, 0xE8, 0x02, 0x81, 0xBF, 0x7C, 0xC3, - 0x54, 0x86, 0x7E, 0xE4, 0x2F, 0x7D, 0x74, 0x74, 0x27, 0xF7, - 0x9A, 0xE2, 0x8D, 0xA9, 0x2F, 0x7C, 0x82, 0x31, 0x41, 0xF1, - 0xCB, 0x48, 0xA0, 0x05, 0x00, 0x26, 0x3D, 0xA4, 0x6B, 0x27, - 0x43, 0x4C, 0x3F, 0x6F, 0x2F, 0x41, 0x2E, 0xEE, 0xBA, 0x0D, - 0x8F, 0x39, 0x42, 0x0D, 0x2D, 0x76, 0x00, 0x12, 0x4C, 0xF9, - 0x49, 0x2D, 0x7F, 0xED + 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x94, 0x67, 0x03, 0x63, + 0x2A, 0x3E, 0xE4, 0x56, 0xA5, 0x9F, 0x84, 0x89, 0x68, 0x8C, + 0xED, 0xEF, 0xA4, 0xFE, 0x1F, 0xDC, 0x03, 0x04, 0x1E, 0xD0, + 0x87, 0x90, 0x14, 0x7C, 0x82, 0x3F, 0x36, 0xA8, 0x7C, 0x14, + 0x64, 0xAB, 0x88, 0xD4, 0x9D, 0x81, 0xE8, 0xF6, 0xA7, 0xEC, + 0x12, 0x51, 0xEA, 0x25, 0xFD, 0xA4, 0xD1, 0x9C, 0x9B, 0x71, + 0x3D, 0xC8, 0xD0, 0xB3, 0xD2, 0x6D, 0xEB, 0x56, 0x11, 0x66, + 0x05, 0x4E, 0x92, 0x27, 0x0A, 0x76, 0x8C, 0x3A, 0x8B, 0xBD, + 0xE2, 0x46, 0xF5, 0x7B, 0x8E, 0xFF, 0x03, 0xF3, 0x89, 0x92, + 0xDC, 0x9B, 0x46, 0x79, 0xF4, 0xB8, 0x95, 0x7D, 0xB6, 0x29, + 0x79, 0xF3, 0x55, 0xC8, 0x70, 0xDE, 0xF7, 0x9F, 0x59, 0xE1, + 0xE2, 0x8D, 0xA7, 0x73, 0x1F, 0x97, 0x1C, 0x52, 0x64, 0x48, + 0x77, 0xCF, 0x6D, 0xA0, 0x27, 0xAD, 0xC0, 0x16, 0x56, 0x55, + 0x46, 0xB2, 0xBF, 0xF1 }; static const int sizeof_server_cert_der_1024 = sizeof(server_cert_der_1024); @@ -869,9 +869,9 @@ static const int sizeof_client_keypub_der_2048 = sizeof(client_keypub_der_2048); static const unsigned char client_cert_der_2048[] = { 0x30, 0x82, 0x05, 0x1D, 0x30, 0x82, 0x04, 0x05, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x08, 0xB0, 0x54, 0x7A, 0x03, - 0x5A, 0xEC, 0x55, 0x8A, 0x12, 0xE8, 0xF9, 0x8E, 0x34, 0xB6, - 0x13, 0xD9, 0x59, 0xB8, 0xE8, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x4F, 0x0D, 0x8C, 0xC5, 0xFA, + 0xEE, 0xA2, 0x9B, 0xB7, 0x35, 0x9E, 0xE9, 0x4A, 0x17, 0x99, + 0xF0, 0xCC, 0x23, 0xF2, 0xEC, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -889,10 +889,10 @@ static const unsigned char client_cert_der_2048[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -962,9 +962,9 @@ static const unsigned char client_cert_der_2048[] = 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, - 0x82, 0x14, 0x08, 0xB0, 0x54, 0x7A, 0x03, 0x5A, 0xEC, 0x55, - 0x8A, 0x12, 0xE8, 0xF9, 0x8E, 0x34, 0xB6, 0x13, 0xD9, 0x59, - 0xB8, 0xE8, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, + 0x82, 0x14, 0x4F, 0x0D, 0x8C, 0xC5, 0xFA, 0xEE, 0xA2, 0x9B, + 0xB7, 0x35, 0x9E, 0xE9, 0x4A, 0x17, 0x99, 0xF0, 0xCC, 0x23, + 0xF2, 0xEC, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, @@ -973,33 +973,33 @@ static const unsigned char client_cert_der_2048[] = 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, - 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x89, 0x84, 0xEB, - 0x6A, 0x70, 0x3B, 0x2A, 0x6E, 0xA8, 0x8B, 0xF2, 0x92, 0x79, - 0x97, 0x5C, 0xBD, 0x98, 0x8B, 0x71, 0xDB, 0xDB, 0x7C, 0xDF, - 0xDB, 0xA4, 0x2C, 0x59, 0xD3, 0xA6, 0x75, 0x41, 0xC2, 0x06, - 0xB6, 0x17, 0x1E, 0x0C, 0x1F, 0x7D, 0x0B, 0x7F, 0x58, 0x3E, - 0xC1, 0xE7, 0x0C, 0xF0, 0x62, 0x92, 0x77, 0xAB, 0x99, 0x79, - 0x7B, 0x85, 0xF4, 0xD9, 0x6C, 0xD0, 0x0E, 0xE5, 0x8B, 0x13, - 0x35, 0x65, 0x9E, 0xD7, 0x9A, 0x51, 0x98, 0xE4, 0x49, 0x44, - 0x51, 0xC8, 0xE3, 0xE0, 0x9A, 0xFF, 0xC2, 0xCB, 0x3D, 0x81, - 0xEB, 0xEE, 0xF4, 0x1A, 0xD1, 0x96, 0x4B, 0xE9, 0x7D, 0xDE, - 0x5B, 0xF2, 0x64, 0x40, 0xAD, 0xE1, 0xD9, 0xD6, 0xB7, 0xE1, - 0xEB, 0xA9, 0x3A, 0x52, 0x29, 0x89, 0xAA, 0x07, 0x37, 0x96, - 0x44, 0xE3, 0x23, 0x49, 0xF3, 0xBE, 0xF3, 0x0D, 0x70, 0xD1, - 0xA2, 0xCE, 0x78, 0x86, 0x22, 0xFC, 0x76, 0x00, 0x84, 0x1D, - 0xFA, 0x8B, 0x8A, 0xD2, 0x43, 0x93, 0x88, 0xFA, 0xEE, 0x22, - 0xCC, 0xA6, 0x86, 0xF5, 0x3F, 0x24, 0xF1, 0xD4, 0x70, 0x05, - 0x4F, 0x3B, 0x18, 0x32, 0x50, 0x67, 0xC1, 0x80, 0x77, 0x0D, - 0x3C, 0x78, 0x75, 0x35, 0xD0, 0xFD, 0x60, 0xF3, 0xED, 0xA1, - 0x30, 0xD0, 0x62, 0x25, 0x99, 0x6B, 0x80, 0x56, 0x17, 0x3D, - 0xB4, 0xAF, 0x1D, 0xDF, 0xAB, 0x48, 0x21, 0xC1, 0xD2, 0x0B, - 0x6B, 0x94, 0xA7, 0x33, 0xD1, 0xD0, 0x82, 0xB7, 0x3B, 0x92, - 0xEB, 0x9D, 0xD6, 0x6C, 0x32, 0x81, 0x5E, 0x07, 0x3C, 0x46, - 0x34, 0x32, 0x7B, 0xEA, 0x22, 0xDB, 0xA6, 0xA3, 0x18, 0x69, - 0x7C, 0xAD, 0x17, 0xE4, 0xC8, 0xA9, 0x8F, 0xA8, 0xBA, 0x67, - 0xAF, 0x99, 0x39, 0xEF, 0x6E, 0x0C, 0xF8, 0xA9, 0xB3, 0xBD, - 0xAB, 0x71, 0x94, 0xE0, 0x41, 0xAA, 0xA4, 0x2D, 0x72, 0x60, - 0x51, 0xD1, 0x5C + 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x46, 0xAB, 0xE4, + 0x6D, 0xAE, 0x49, 0x5B, 0x6A, 0x0B, 0xA9, 0x87, 0xE1, 0x95, + 0x32, 0xA6, 0xD7, 0xAE, 0xDE, 0x28, 0xDC, 0xC7, 0x99, 0x68, + 0xE2, 0x5F, 0xC9, 0x5A, 0x4C, 0x64, 0xB8, 0xF5, 0x28, 0x42, + 0x5A, 0xE8, 0x5C, 0x59, 0x32, 0xFE, 0xD0, 0x1F, 0x0B, 0x55, + 0x89, 0xDB, 0x67, 0xE7, 0x78, 0xF3, 0x70, 0xCF, 0x18, 0x51, + 0x57, 0x8B, 0xF3, 0x2B, 0xA4, 0x66, 0x0B, 0xF6, 0x03, 0x6E, + 0x11, 0xAC, 0x83, 0x52, 0x16, 0x7E, 0xA2, 0x7C, 0x36, 0x77, + 0xF6, 0xBB, 0x13, 0x19, 0x40, 0x2C, 0xB8, 0x8C, 0xCA, 0xD6, + 0x7E, 0x79, 0x7D, 0xF4, 0x14, 0x8D, 0xB5, 0xA4, 0x09, 0xF6, + 0x2D, 0x4C, 0xE7, 0xF9, 0xB8, 0x25, 0x41, 0x15, 0x78, 0xF4, + 0xCA, 0x80, 0x41, 0xEA, 0x3A, 0x05, 0x08, 0xF6, 0xB5, 0x5B, + 0xA1, 0x3B, 0x5B, 0x48, 0xA8, 0x4B, 0x8C, 0x19, 0x8D, 0x6C, + 0x87, 0x31, 0x76, 0x74, 0x02, 0x16, 0x8B, 0xDD, 0x7F, 0xD1, + 0x11, 0x62, 0x27, 0x42, 0x39, 0xE0, 0x9A, 0x63, 0x26, 0x31, + 0x19, 0xCE, 0x3D, 0x41, 0xD5, 0x24, 0x47, 0x32, 0x0F, 0x76, + 0xD6, 0x41, 0x37, 0x44, 0xAD, 0x73, 0xF1, 0xB8, 0xEC, 0x2B, + 0x6E, 0x9C, 0x4F, 0x84, 0xC4, 0x4E, 0xD7, 0x92, 0x10, 0x7E, + 0x23, 0x32, 0xA0, 0x75, 0x6A, 0xE7, 0xFE, 0x55, 0x95, 0x9F, + 0x0A, 0xAD, 0xDF, 0xF9, 0x2A, 0xA2, 0x1A, 0x59, 0xD5, 0x82, + 0x63, 0xD6, 0x5D, 0x7D, 0x79, 0xF4, 0xA7, 0x2D, 0xDC, 0x8C, + 0x04, 0xCD, 0x98, 0xB0, 0x42, 0x0E, 0x84, 0xFA, 0x86, 0x50, + 0x10, 0x61, 0xAC, 0x73, 0xCD, 0x79, 0x45, 0x30, 0xE8, 0x42, + 0xA1, 0x6A, 0xF6, 0x77, 0x55, 0xEC, 0x07, 0xDB, 0x52, 0x29, + 0xCA, 0x7A, 0xC8, 0xA2, 0xDA, 0xE9, 0xF5, 0x98, 0x33, 0x6A, + 0xE8, 0xBC, 0x89, 0xED, 0x01, 0xE2, 0xFE, 0x44, 0x86, 0x86, + 0x80, 0x39, 0xEC }; static const int sizeof_client_cert_der_2048 = sizeof(client_cert_der_2048); @@ -1636,9 +1636,9 @@ static const int sizeof_ca_key_der_2048 = sizeof(ca_key_der_2048); static const unsigned char ca_cert_der_2048[] = { 0x30, 0x82, 0x04, 0xFF, 0x30, 0x82, 0x03, 0xE7, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x33, 0x44, 0x1A, 0xA8, 0x6C, - 0x01, 0xEC, 0xF6, 0x60, 0xF2, 0x70, 0x51, 0x0A, 0x4C, 0xD1, - 0x14, 0xFA, 0xBC, 0xE9, 0x44, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x6B, 0x9B, 0x70, 0xC6, 0xF1, + 0xA3, 0x94, 0x65, 0x19, 0xA1, 0x08, 0x58, 0xEF, 0xA7, 0x8D, + 0x2B, 0x7A, 0x83, 0xC1, 0xDA, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -1655,10 +1655,10 @@ static const unsigned char ca_cert_der_2048[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -1726,9 +1726,9 @@ static const unsigned char ca_cert_der_2048[] = 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, - 0x82, 0x14, 0x33, 0x44, 0x1A, 0xA8, 0x6C, 0x01, 0xEC, 0xF6, - 0x60, 0xF2, 0x70, 0x51, 0x0A, 0x4C, 0xD1, 0x14, 0xFA, 0xBC, - 0xE9, 0x44, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, + 0x82, 0x14, 0x6B, 0x9B, 0x70, 0xC6, 0xF1, 0xA3, 0x94, 0x65, + 0x19, 0xA1, 0x08, 0x58, 0xEF, 0xA7, 0x8D, 0x2B, 0x7A, 0x83, + 0xC1, 0xDA, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, @@ -1737,33 +1737,33 @@ static const unsigned char ca_cert_der_2048[] = 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, - 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x2D, 0xFC, 0xF9, - 0x32, 0x5A, 0xBE, 0xD6, 0x9D, 0x42, 0x8B, 0x86, 0x4E, 0x67, - 0x22, 0xC3, 0x50, 0x2D, 0xCB, 0x14, 0x27, 0x1D, 0x94, 0xF3, - 0xCD, 0x88, 0x42, 0xDA, 0x41, 0x1C, 0x39, 0x24, 0x67, 0xA7, - 0x92, 0x4D, 0x27, 0xEA, 0x56, 0x82, 0x19, 0xBF, 0x11, 0xB2, - 0x43, 0xA4, 0x8D, 0x5D, 0x87, 0xB2, 0x27, 0x64, 0x66, 0x82, - 0x81, 0xDF, 0xC4, 0xFD, 0x5B, 0x62, 0xB0, 0xC2, 0x4D, 0x9D, - 0x29, 0xF2, 0x41, 0x32, 0xCC, 0x2E, 0xB5, 0xDA, 0x38, 0x06, - 0x1B, 0xE8, 0x7F, 0x8C, 0x6E, 0x3D, 0x80, 0x1E, 0x00, 0x56, - 0x49, 0xBF, 0x39, 0xE0, 0xDA, 0x68, 0x2F, 0xC4, 0xFD, 0x00, - 0xE6, 0xD1, 0x81, 0x1A, 0xD1, 0x4A, 0xBB, 0x76, 0x52, 0xCE, - 0x4D, 0x24, 0x9D, 0xC4, 0xA3, 0xA7, 0xF1, 0x65, 0x14, 0x2F, - 0x1F, 0xA8, 0x2D, 0xC6, 0xCB, 0xCE, 0xB1, 0xA7, 0x89, 0x74, - 0x26, 0x27, 0xC3, 0xF3, 0xA3, 0x84, 0x4C, 0x34, 0x01, 0x14, - 0x03, 0x7D, 0x16, 0x3A, 0xC8, 0x8B, 0x25, 0x2E, 0x7B, 0x90, - 0xCC, 0x46, 0xB1, 0x52, 0x34, 0xBA, 0x93, 0x6E, 0xEF, 0xFE, - 0x43, 0xA3, 0xAD, 0xC6, 0x6F, 0x51, 0xFB, 0xBA, 0xEA, 0x38, - 0xE3, 0x6F, 0xD6, 0xEE, 0x63, 0x62, 0x36, 0xEA, 0x5E, 0x08, - 0xB4, 0xE2, 0x2A, 0x46, 0x89, 0xE3, 0xAE, 0xB3, 0xB4, 0x06, - 0xEF, 0x63, 0x7A, 0x6E, 0x5D, 0xDD, 0xC9, 0xEC, 0x02, 0x4F, - 0xF7, 0x64, 0xC0, 0x27, 0x07, 0xB4, 0x6F, 0x4A, 0x18, 0x72, - 0x5B, 0x34, 0x74, 0x7C, 0xD0, 0xA9, 0x04, 0x8F, 0x40, 0x8B, - 0x6A, 0x39, 0xD2, 0x6B, 0x1A, 0x01, 0xF2, 0x01, 0xA8, 0x81, - 0x34, 0x3A, 0xE5, 0xB0, 0x55, 0xD1, 0x3C, 0x95, 0xCA, 0xB0, - 0x82, 0xD6, 0xED, 0x98, 0x28, 0x15, 0x59, 0x7E, 0x95, 0xA7, - 0x69, 0xC7, 0xB5, 0x7B, 0xEC, 0x01, 0xA7, 0x4D, 0xE6, 0xB9, - 0xA2, 0xFE, 0x35 + 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x77, 0x3B, 0x3D, + 0x66, 0x74, 0xBC, 0x97, 0xFE, 0x40, 0x16, 0xE6, 0xBA, 0xA5, + 0xD5, 0xD1, 0x84, 0x08, 0x89, 0x69, 0x4F, 0x88, 0x0D, 0x57, + 0xA9, 0xEF, 0x8C, 0xC3, 0x97, 0x52, 0xC8, 0xBD, 0x8B, 0xA2, + 0x49, 0x3B, 0xB7, 0xF7, 0x5D, 0x1E, 0xD6, 0x14, 0x7F, 0xB2, + 0x80, 0x33, 0xDA, 0xA0, 0x8A, 0xD3, 0xE1, 0x2F, 0xD5, 0xBC, + 0x33, 0x9F, 0xEA, 0x5A, 0x72, 0x24, 0xE5, 0xF8, 0xB8, 0x4B, + 0xB3, 0xDF, 0x62, 0x90, 0x3B, 0xA8, 0x21, 0xEF, 0x27, 0x42, + 0x75, 0xBC, 0x60, 0x02, 0x8E, 0x37, 0x35, 0x99, 0xEB, 0xA3, + 0x28, 0xF2, 0x65, 0x4C, 0xFF, 0x7A, 0xF8, 0x8E, 0xCC, 0x23, + 0x6D, 0xE5, 0x6A, 0xFE, 0x22, 0x5A, 0xD9, 0xB2, 0x4F, 0x47, + 0xC7, 0xE0, 0xAE, 0x98, 0xEF, 0x94, 0xAC, 0xB6, 0x4F, 0x61, + 0x81, 0x29, 0x8E, 0xE1, 0x79, 0x2C, 0x46, 0xFC, 0xE9, 0x1A, + 0xC3, 0x96, 0x1F, 0x19, 0x93, 0x64, 0x2E, 0x9F, 0x37, 0x72, + 0xC5, 0xE4, 0x93, 0x4E, 0x61, 0x5F, 0x38, 0x8E, 0xAE, 0xE8, + 0x39, 0x19, 0xE6, 0x97, 0xA8, 0x91, 0xD4, 0x23, 0x7E, 0x1E, + 0xD2, 0xD0, 0x53, 0xEC, 0xCC, 0xAC, 0xA0, 0x1D, 0xD0, 0xB7, + 0xDD, 0xB1, 0xB7, 0x01, 0x2E, 0x96, 0xCD, 0x85, 0x27, 0xE0, + 0xE7, 0x47, 0xE2, 0xC1, 0xC1, 0x00, 0xF6, 0x94, 0xDF, 0x77, + 0xE7, 0xFA, 0xC6, 0xEF, 0x8A, 0xC0, 0x7C, 0x67, 0xBC, 0xFF, + 0xA0, 0x7C, 0x94, 0x3B, 0x7D, 0x86, 0x42, 0xAF, 0x3D, 0x83, + 0x31, 0xEE, 0x2A, 0x3B, 0x7B, 0xF0, 0x2C, 0x9E, 0x6F, 0xE9, + 0xC4, 0x07, 0x81, 0x24, 0xDA, 0x05, 0x70, 0x4D, 0xDD, 0x09, + 0xAE, 0x9E, 0x72, 0xB8, 0x21, 0x0E, 0x8C, 0xB2, 0xAB, 0xAA, + 0x4C, 0x49, 0x10, 0xF7, 0x76, 0xF9, 0xB5, 0x0D, 0x6C, 0x20, + 0xD3, 0xDF, 0x7A, 0x06, 0x32, 0x8D, 0x29, 0x1F, 0x28, 0x1D, + 0x8D, 0x26, 0x33 }; static const int sizeof_ca_cert_der_2048 = sizeof(ca_cert_der_2048); @@ -1771,9 +1771,9 @@ static const int sizeof_ca_cert_der_2048 = sizeof(ca_cert_der_2048); static const unsigned char ca_cert_chain_der[] = { 0x30, 0x82, 0x03, 0xFA, 0x30, 0x82, 0x03, 0x63, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x5D, 0x82, 0xE6, 0x32, 0x61, - 0xE7, 0x3B, 0x5E, 0x77, 0x3D, 0xDA, 0xA6, 0xF3, 0xFC, 0x54, - 0xB5, 0x04, 0xD4, 0x10, 0x4E, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x22, 0x3E, 0x28, 0x4D, 0xF0, + 0xF6, 0xC5, 0x97, 0x06, 0xB3, 0xAD, 0x8A, 0x59, 0x4D, 0xA0, + 0x87, 0x3F, 0xB3, 0xCE, 0x8C, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -1790,10 +1790,10 @@ static const unsigned char ca_cert_chain_der[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x94, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -1848,8 +1848,8 @@ static const unsigned char ca_cert_chain_der[] = 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, - 0x5D, 0x82, 0xE6, 0x32, 0x61, 0xE7, 0x3B, 0x5E, 0x77, 0x3D, - 0xDA, 0xA6, 0xF3, 0xFC, 0x54, 0xB5, 0x04, 0xD4, 0x10, 0x4E, + 0x22, 0x3E, 0x28, 0x4D, 0xF0, 0xF6, 0xC5, 0x97, 0x06, 0xB3, + 0xAD, 0x8A, 0x59, 0x4D, 0xA0, 0x87, 0x3F, 0xB3, 0xCE, 0x8C, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, @@ -1859,20 +1859,20 @@ static const unsigned char ca_cert_chain_der[] = 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, - 0x03, 0x81, 0x81, 0x00, 0x23, 0x19, 0xF7, 0x04, 0xB7, 0x99, - 0x84, 0x86, 0xCE, 0x45, 0x9E, 0xA4, 0x55, 0x2D, 0x14, 0xAC, - 0xC5, 0x1C, 0x2D, 0x2F, 0x8D, 0xD3, 0x14, 0x81, 0x91, 0x27, - 0x1C, 0x0C, 0x3C, 0x44, 0x14, 0x8B, 0x99, 0x46, 0xF2, 0x43, - 0xB3, 0x51, 0x33, 0x1B, 0xFA, 0x77, 0x95, 0x07, 0x5C, 0xE4, - 0x3C, 0x11, 0x17, 0x55, 0x57, 0xBF, 0x9D, 0xF4, 0xB5, 0xD4, - 0xAD, 0x7C, 0xB1, 0x82, 0x62, 0x77, 0xC8, 0xAA, 0x02, 0xEE, - 0x73, 0xEE, 0x77, 0x67, 0xD5, 0xB5, 0x58, 0xD7, 0x19, 0x6F, - 0x0F, 0xFD, 0x8B, 0xFC, 0xD4, 0x32, 0xFF, 0x86, 0x48, 0xF8, - 0x49, 0x5B, 0xD8, 0xF1, 0xFB, 0x36, 0x28, 0x27, 0xC1, 0x7D, - 0xDD, 0x0F, 0xFF, 0x7F, 0x95, 0x16, 0x5B, 0x85, 0xCA, 0x3E, - 0x9B, 0xDC, 0x78, 0xB7, 0x6B, 0xB1, 0xF1, 0x75, 0xFA, 0x61, - 0xDA, 0xCE, 0x8A, 0x4E, 0x5F, 0x90, 0x7C, 0x38, 0x9E, 0x31, - 0x00, 0x66 + 0x03, 0x81, 0x81, 0x00, 0x4E, 0x35, 0x89, 0x4C, 0x99, 0xC8, + 0x51, 0x46, 0x5B, 0x86, 0x21, 0xF3, 0x92, 0x13, 0x2D, 0x0E, + 0x73, 0x78, 0x85, 0xBC, 0x81, 0xBB, 0xD1, 0x4B, 0xC3, 0x1B, + 0x65, 0xB5, 0x39, 0x71, 0xA7, 0x04, 0x39, 0x8D, 0x57, 0x20, + 0x02, 0xA0, 0x33, 0x8C, 0xFF, 0xD5, 0xFC, 0x2E, 0x94, 0x56, + 0x48, 0xFC, 0x08, 0x4A, 0x37, 0x19, 0x98, 0x81, 0xAF, 0x51, + 0x3F, 0xB7, 0x91, 0x0A, 0x86, 0x4E, 0x97, 0xE2, 0x39, 0x92, + 0xF5, 0x3E, 0x99, 0xB2, 0x88, 0x1B, 0xAA, 0x97, 0x95, 0x77, + 0x2E, 0xDA, 0x41, 0x11, 0xD7, 0x8F, 0x74, 0x9D, 0x34, 0xD0, + 0x70, 0xCA, 0x37, 0xAA, 0xF7, 0xD7, 0x39, 0xD6, 0xA8, 0x48, + 0x34, 0x06, 0x3A, 0x6A, 0xDA, 0xDE, 0x8A, 0x1D, 0x3C, 0x41, + 0x56, 0xA3, 0x4E, 0xAE, 0x9F, 0x50, 0xB4, 0x8E, 0x10, 0x39, + 0xD9, 0xA2, 0x38, 0xD0, 0x22, 0x04, 0xCA, 0x31, 0x1C, 0xAC, + 0x3C, 0xF2 }; static const int sizeof_ca_cert_chain_der = sizeof(ca_cert_chain_der); @@ -2023,10 +2023,10 @@ static const unsigned char server_cert_der_2048[] = 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, - 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, - 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, - 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, - 0x39, 0x32, 0x38, 0x5A, 0x30, 0x81, 0x90, 0x31, 0x0B, 0x30, + 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, + 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, + 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, + 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0x90, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, @@ -2093,9 +2093,9 @@ static const unsigned char server_cert_der_2048[] = 0x2E, 0x63, 0x6F, 0x6D, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, - 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x33, - 0x44, 0x1A, 0xA8, 0x6C, 0x01, 0xEC, 0xF6, 0x60, 0xF2, 0x70, - 0x51, 0x0A, 0x4C, 0xD1, 0x14, 0xFA, 0xBC, 0xE9, 0x44, 0x30, + 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x6B, + 0x9B, 0x70, 0xC6, 0xF1, 0xA3, 0x94, 0x65, 0x19, 0xA1, 0x08, + 0x58, 0xEF, 0xA7, 0x8D, 0x2B, 0x7A, 0x83, 0xC1, 0xDA, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, @@ -2105,32 +2105,32 @@ static const unsigned char server_cert_der_2048[] = 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, - 0x82, 0x01, 0x01, 0x00, 0x4A, 0xFF, 0xB9, 0xE5, 0x85, 0x9B, - 0xDA, 0x53, 0x66, 0x7F, 0x07, 0x22, 0xBF, 0xB6, 0x19, 0xEA, - 0x42, 0xEB, 0xA4, 0x11, 0x07, 0x62, 0xFF, 0x39, 0x5F, 0x33, - 0x37, 0x3A, 0x87, 0x26, 0x71, 0x3D, 0x13, 0xB2, 0xCA, 0xB8, - 0x64, 0x38, 0x7B, 0x8A, 0x99, 0x48, 0x0E, 0xA5, 0xA4, 0x6B, - 0xB1, 0x99, 0x6E, 0xE0, 0x46, 0x51, 0xBD, 0x19, 0x52, 0xAD, - 0xBC, 0xA6, 0x7E, 0x2A, 0x7A, 0x7C, 0x23, 0xA7, 0xCC, 0xDB, - 0x5E, 0x43, 0x7D, 0x6B, 0x04, 0xC8, 0xB7, 0xDD, 0x95, 0xAD, - 0xF0, 0x91, 0x80, 0x59, 0xC5, 0x19, 0x91, 0x26, 0x27, 0x91, - 0xB8, 0x48, 0x1C, 0xEB, 0x55, 0xB6, 0xAA, 0x7D, 0xA4, 0x38, - 0xF1, 0x03, 0xBC, 0x6C, 0x8B, 0xAA, 0x94, 0xD6, 0x3C, 0x05, - 0x7A, 0x96, 0xC5, 0x06, 0xF1, 0x26, 0x14, 0x2E, 0x75, 0xFB, - 0xDD, 0xE5, 0x35, 0xB3, 0x01, 0x2C, 0xB3, 0xAD, 0x62, 0x5A, - 0x21, 0x9A, 0x08, 0xBE, 0x56, 0xFC, 0xF9, 0xA2, 0x42, 0x87, - 0x86, 0xE5, 0xA9, 0xC5, 0x99, 0xCF, 0xAE, 0x14, 0xBE, 0xE0, - 0xB9, 0x08, 0x24, 0x0D, 0x1D, 0x5C, 0xD6, 0x14, 0xE1, 0x4C, - 0x9F, 0x40, 0xB3, 0xA9, 0xE9, 0x2D, 0x52, 0x8B, 0x4C, 0xBF, - 0xAC, 0x44, 0x31, 0x67, 0xC1, 0x8D, 0x06, 0x85, 0xEC, 0x0F, - 0xE4, 0x99, 0xD7, 0x4B, 0x7B, 0x21, 0x06, 0x66, 0xD4, 0xE4, - 0xF5, 0x9D, 0xFF, 0x8E, 0xF0, 0x86, 0x39, 0x58, 0x1D, 0xA4, - 0x5B, 0xE2, 0x63, 0xEF, 0x7C, 0xC9, 0x18, 0x87, 0xA8, 0x02, - 0x25, 0x10, 0x3E, 0x87, 0x28, 0xF9, 0xF5, 0xEF, 0x47, 0x9E, - 0xA5, 0x80, 0x08, 0x11, 0x90, 0x68, 0xFE, 0xD1, 0xA3, 0xA8, - 0x51, 0xB9, 0x37, 0xFF, 0xD5, 0xCA, 0x7C, 0x87, 0x7F, 0x6B, - 0xBC, 0x2C, 0x12, 0xC8, 0xC5, 0x85, 0x8B, 0xFC, 0x0C, 0xC6, - 0xB9, 0x86, 0xB8, 0xC9, 0x04, 0xC3, 0x51, 0x37, 0xD2, 0x4F + 0x82, 0x01, 0x01, 0x00, 0x8A, 0xF1, 0x4E, 0xE8, 0x9F, 0x59, + 0xB2, 0xD9, 0x13, 0xAC, 0xFC, 0x42, 0xC4, 0x81, 0x34, 0x9F, + 0x6B, 0x39, 0x57, 0x9C, 0xE9, 0x92, 0x5D, 0x41, 0xAC, 0x05, + 0x35, 0xB1, 0x26, 0x93, 0x4D, 0x4A, 0xDA, 0xF8, 0x51, 0x82, + 0xD2, 0x8D, 0x7F, 0xD3, 0x5C, 0x6E, 0x29, 0x80, 0x8D, 0x9B, + 0x02, 0x10, 0x2B, 0x64, 0xF5, 0xD1, 0x31, 0x06, 0xFA, 0x85, + 0x2B, 0x8F, 0x63, 0x32, 0x14, 0x76, 0x7A, 0x39, 0x15, 0xF3, + 0x4E, 0xDD, 0xFD, 0xE2, 0x2C, 0x90, 0x15, 0xD1, 0x6F, 0x73, + 0x87, 0xEE, 0xE6, 0xC8, 0xEB, 0xAD, 0x40, 0xD5, 0xE8, 0x94, + 0x1F, 0xA6, 0x7E, 0x26, 0x5B, 0x87, 0xBA, 0x0F, 0x06, 0x5A, + 0x4D, 0x55, 0x7A, 0xAA, 0xC4, 0x09, 0x34, 0x8B, 0xF7, 0xE5, + 0xCC, 0xD6, 0xB7, 0x6C, 0x46, 0x6D, 0xA1, 0xE6, 0x66, 0x66, + 0x4C, 0x4B, 0xE5, 0x12, 0x31, 0x37, 0x54, 0x49, 0x64, 0xA5, + 0x66, 0xEB, 0xE0, 0xC6, 0xA1, 0x49, 0xF8, 0x4D, 0xC3, 0xD3, + 0x55, 0xA4, 0x05, 0xD2, 0xAC, 0xFB, 0xE1, 0xC8, 0x69, 0x30, + 0x4B, 0x98, 0xFD, 0x72, 0x1A, 0xAB, 0x9F, 0x86, 0xEB, 0x0D, + 0xBD, 0x7C, 0xA6, 0x3D, 0x81, 0xD9, 0x01, 0xA7, 0x8A, 0x79, + 0xAB, 0x3C, 0xCE, 0xE5, 0xB6, 0xC3, 0x1B, 0xEF, 0x7D, 0x5E, + 0x37, 0x7B, 0x37, 0x7C, 0x91, 0x89, 0x59, 0x11, 0x21, 0x11, + 0x7C, 0x05, 0x80, 0xE1, 0xA8, 0xD6, 0xF9, 0x35, 0xDA, 0x1B, + 0x86, 0x06, 0x5A, 0x32, 0x67, 0x6C, 0xA9, 0x2B, 0xE0, 0x31, + 0x7B, 0x89, 0x53, 0x37, 0x42, 0xAF, 0x34, 0xA4, 0x53, 0xD2, + 0x7C, 0x91, 0x50, 0x63, 0x3A, 0x8E, 0x4A, 0x1F, 0xA3, 0x90, + 0x4E, 0x7C, 0x41, 0x59, 0x1D, 0xEB, 0x7B, 0xA2, 0x14, 0x87, + 0xBA, 0x76, 0x36, 0xA4, 0x77, 0x46, 0x34, 0xF2, 0x55, 0x50, + 0xF0, 0x24, 0x9F, 0x83, 0x83, 0xDA, 0xA6, 0xAA, 0x3C, 0xC8 }; static const int sizeof_server_cert_der_2048 = sizeof(server_cert_der_2048); @@ -2502,183 +2502,186 @@ static const int sizeof_rsa_key_der_3072 = sizeof(rsa_key_der_3072); /* ./certs/3072/client-key.der, 3072-bit */ static const unsigned char client_key_der_3072[] = { - 0x30, 0x82, 0x06, 0xE4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, - 0x81, 0x00, 0xAC, 0x39, 0x50, 0x68, 0x8F, 0x78, 0xF8, 0x10, - 0x9B, 0x68, 0x96, 0xD3, 0xE1, 0x9C, 0x56, 0x68, 0x5A, 0x41, - 0x62, 0xE3, 0xB3, 0x41, 0xB0, 0x55, 0x80, 0x17, 0xB0, 0x88, - 0x16, 0x9B, 0xE0, 0x97, 0x74, 0x5F, 0x42, 0x79, 0x73, 0x42, - 0xDF, 0x93, 0xF3, 0xAA, 0x9D, 0xEE, 0x2D, 0x6F, 0xAA, 0xBC, - 0x27, 0x90, 0x84, 0xC0, 0x5D, 0xC7, 0xEC, 0x49, 0xEA, 0x5C, - 0x66, 0x1D, 0x70, 0x9C, 0x53, 0x5C, 0xBA, 0xA1, 0xB3, 0x58, - 0xC9, 0x3E, 0x8E, 0x9B, 0x72, 0x3D, 0x6E, 0x02, 0x02, 0x00, - 0x9C, 0x65, 0x56, 0x82, 0xA3, 0x22, 0xB4, 0x08, 0x5F, 0x2A, - 0xEF, 0xDF, 0x9A, 0xD0, 0xE7, 0x31, 0x59, 0x26, 0x5B, 0x0B, - 0x1C, 0x63, 0x61, 0xFF, 0xD5, 0x69, 0x32, 0x19, 0x06, 0x7E, - 0x0F, 0x40, 0x3C, 0x7A, 0x1E, 0xC8, 0xFC, 0x58, 0x6C, 0x64, - 0xAE, 0x10, 0x3D, 0xA8, 0x23, 0xFF, 0x8E, 0x1A, 0xCA, 0x6A, - 0x82, 0xE2, 0xF9, 0x01, 0x64, 0x2C, 0x97, 0xA0, 0x1A, 0x89, - 0xA0, 0x74, 0xD3, 0xB6, 0x05, 0x11, 0xF2, 0x62, 0x06, 0x48, - 0x2A, 0xF7, 0x66, 0xCE, 0xC1, 0x85, 0xE1, 0xD2, 0x27, 0xEA, - 0xCA, 0x12, 0xA5, 0x91, 0x97, 0x3E, 0xFC, 0x94, 0x06, 0x59, - 0x51, 0xC0, 0xE7, 0x13, 0xB6, 0x87, 0x7B, 0x5F, 0xD2, 0xC0, - 0x56, 0x2F, 0x5E, 0x1D, 0x02, 0xC3, 0x11, 0x2C, 0xDF, 0xF7, - 0x01, 0xDA, 0xBD, 0x85, 0x54, 0x35, 0x32, 0x5F, 0xC5, 0xC8, - 0xF9, 0x7A, 0x9F, 0x89, 0xF7, 0x03, 0x0E, 0x7E, 0x79, 0x5D, - 0x04, 0x82, 0x35, 0x10, 0xFE, 0x6D, 0x9B, 0xBF, 0xB8, 0xEE, - 0xE2, 0x62, 0x87, 0x26, 0x5E, 0x2F, 0x50, 0x2F, 0x78, 0x0C, - 0xE8, 0x73, 0x4F, 0x88, 0x6A, 0xD6, 0x26, 0xA4, 0xC9, 0xFC, - 0xFA, 0x1E, 0x8A, 0xB0, 0xF4, 0x32, 0xCF, 0x57, 0xCD, 0xA1, - 0x58, 0x8A, 0x49, 0x0F, 0xBB, 0xA9, 0x1D, 0x86, 0xAB, 0xB9, - 0x8F, 0x8D, 0x57, 0x19, 0xB2, 0x5A, 0x7E, 0xA4, 0xEA, 0xCC, - 0xB7, 0x96, 0x7A, 0x3B, 0x38, 0xCD, 0xDE, 0xE0, 0x61, 0xFC, - 0xC9, 0x06, 0x8F, 0x93, 0x5A, 0xCE, 0xAD, 0x2A, 0xE3, 0x2D, - 0x3E, 0x39, 0x5D, 0x41, 0x83, 0x01, 0x1F, 0x0F, 0xE1, 0x7F, - 0x76, 0xC7, 0x28, 0xDA, 0x56, 0xEF, 0xBF, 0xDC, 0x26, 0x35, - 0x40, 0xBE, 0xAD, 0xC7, 0x38, 0xAD, 0xA4, 0x06, 0xAC, 0xCA, - 0xE8, 0x51, 0xEB, 0xC0, 0xF8, 0x68, 0x02, 0x2C, 0x9B, 0xA1, - 0x14, 0xBC, 0xF8, 0x61, 0x86, 0xD7, 0x56, 0xD7, 0x73, 0xF4, - 0xAB, 0xBB, 0x6A, 0x21, 0xD3, 0x88, 0x22, 0xB4, 0xE7, 0x6F, - 0x7F, 0x91, 0xE5, 0x0E, 0xC6, 0x08, 0x49, 0xDE, 0xEA, 0x13, - 0x58, 0x72, 0xA0, 0xAA, 0x3A, 0xF9, 0x36, 0x03, 0x45, 0x57, - 0x5E, 0x87, 0xD2, 0x73, 0x65, 0xC4, 0x8C, 0xA3, 0xEE, 0xC9, - 0xD6, 0x73, 0x7C, 0x96, 0x41, 0x93, 0x02, 0x03, 0x01, 0x00, - 0x01, 0x02, 0x82, 0x01, 0x80, 0x40, 0x19, 0x74, 0xDB, 0xF5, - 0xCA, 0x48, 0x49, 0xA6, 0x0D, 0xDF, 0x55, 0x2C, 0xFB, 0x4B, - 0x0D, 0xBB, 0xC9, 0xEA, 0x4C, 0x65, 0x43, 0x65, 0xA5, 0xEC, - 0xEE, 0xE4, 0x3D, 0x42, 0x6C, 0xF1, 0xC2, 0x6D, 0x05, 0xA7, - 0x70, 0x1C, 0x7E, 0x1F, 0x48, 0xA9, 0xC0, 0x2E, 0xD7, 0x9F, - 0x01, 0x98, 0xC2, 0x3E, 0xD7, 0x83, 0x11, 0x35, 0xD6, 0x5B, - 0x13, 0x87, 0xAE, 0xAC, 0x32, 0xF8, 0xDE, 0xB6, 0x08, 0x25, - 0x4E, 0x59, 0xBA, 0x09, 0xEC, 0xC6, 0x97, 0x04, 0x85, 0xE8, - 0x93, 0xC6, 0xBB, 0x03, 0x7A, 0x94, 0x20, 0x3B, 0x27, 0x87, - 0x6A, 0x36, 0x41, 0x7C, 0xD5, 0xF4, 0x81, 0x1C, 0x0B, 0x39, - 0xEB, 0x14, 0xA7, 0xA6, 0x01, 0x37, 0x50, 0x48, 0xD5, 0xC6, - 0x57, 0x9A, 0x1B, 0x01, 0x02, 0x1F, 0x80, 0x34, 0x45, 0x09, - 0xE6, 0xBF, 0x31, 0x19, 0xB7, 0xE1, 0xBA, 0xDA, 0xEB, 0x1A, - 0xB0, 0xCD, 0xF5, 0xA6, 0x91, 0x63, 0xAC, 0x28, 0xE4, 0x8F, - 0xEA, 0x7E, 0xF6, 0x0A, 0x4A, 0x71, 0x21, 0xA5, 0xF1, 0x70, - 0x0D, 0x1B, 0xD9, 0x70, 0x64, 0x74, 0x57, 0x2F, 0x9F, 0xEC, - 0xD4, 0x93, 0x16, 0xC7, 0xEE, 0xF8, 0xC0, 0x9F, 0x52, 0x4A, - 0x1F, 0xAD, 0xDD, 0x40, 0x98, 0x53, 0x68, 0xFA, 0xDE, 0xA2, - 0x04, 0xA0, 0x24, 0x05, 0xEF, 0xCB, 0x4F, 0x70, 0xDF, 0xB9, - 0x5C, 0xC2, 0x5E, 0xE4, 0xC9, 0xCD, 0x0F, 0x5E, 0x4B, 0x77, - 0xBB, 0x84, 0x69, 0x54, 0x98, 0x41, 0xB7, 0x9C, 0x0E, 0x38, - 0xD8, 0xF7, 0xF3, 0x9F, 0xEF, 0xE5, 0x9B, 0xB6, 0x4B, 0xD6, - 0x7A, 0x65, 0xF5, 0x69, 0xFA, 0xC2, 0x13, 0x70, 0x6C, 0x28, - 0xA4, 0x29, 0xAC, 0xD9, 0xBF, 0xEC, 0x6A, 0x2E, 0xED, 0xE4, - 0xBA, 0xDF, 0xD0, 0xF1, 0xF3, 0x3C, 0x6C, 0x84, 0xDF, 0xB7, - 0x5A, 0x94, 0xCF, 0xD9, 0x2D, 0xEA, 0xEA, 0xB4, 0xD0, 0x91, - 0x2E, 0x77, 0x15, 0x18, 0x0D, 0x6B, 0xBA, 0x2A, 0x0C, 0xF1, - 0x92, 0x9D, 0xD6, 0x04, 0x05, 0xB6, 0x38, 0xC2, 0xE0, 0xA7, - 0x2D, 0x64, 0xF8, 0xDF, 0x0C, 0x3A, 0x93, 0x83, 0xE1, 0x88, - 0x83, 0x5F, 0x67, 0x90, 0x9F, 0x2B, 0xE0, 0x60, 0x8E, 0xCA, - 0x30, 0x13, 0xCA, 0x9F, 0xCF, 0x7B, 0x6D, 0xD8, 0xCD, 0xEE, - 0xF9, 0x96, 0xDD, 0x5E, 0xF4, 0x47, 0xC9, 0x4C, 0xE6, 0x8F, - 0x7F, 0x33, 0x2A, 0x38, 0x30, 0xAF, 0xD5, 0x4A, 0x79, 0x47, - 0x06, 0xCC, 0x96, 0x44, 0x29, 0x8C, 0x60, 0x2B, 0x08, 0xC7, - 0xD0, 0xD3, 0xC3, 0xC5, 0x2C, 0x63, 0x6C, 0x87, 0xD2, 0xAE, - 0x2A, 0xA4, 0x86, 0xE7, 0x76, 0x74, 0x90, 0xD1, 0x04, 0x37, - 0x64, 0x1A, 0xED, 0x08, 0xD9, 0x98, 0x07, 0x1A, 0x98, 0x0B, - 0x89, 0x99, 0xA4, 0xB0, 0x8C, 0x1A, 0x10, 0xEB, 0xEC, 0xF4, - 0xEE, 0x3C, 0xC4, 0x00, 0xCC, 0x30, 0x9C, 0x43, 0x01, 0x02, - 0x81, 0xC1, 0x00, 0xD9, 0x43, 0xF6, 0x2C, 0x78, 0x26, 0xD2, - 0xE7, 0x15, 0xA7, 0x0A, 0x88, 0x5E, 0xDB, 0x2D, 0xAF, 0xC6, - 0xA9, 0x6F, 0x73, 0x88, 0x3B, 0x6A, 0x08, 0x1F, 0xF5, 0x80, - 0xB5, 0x2E, 0x29, 0x8B, 0x72, 0xF8, 0x35, 0xC8, 0x23, 0x18, - 0x1C, 0x0D, 0x0E, 0x38, 0x82, 0xBB, 0x5B, 0x2F, 0xB4, 0x5C, - 0x4E, 0x24, 0x05, 0xA7, 0x4C, 0x79, 0x48, 0x89, 0x8D, 0x1C, - 0x1D, 0x0A, 0x2C, 0xFE, 0xD9, 0x99, 0xDF, 0x25, 0x8A, 0x2D, - 0xF8, 0xEB, 0x2F, 0xDA, 0x1B, 0x63, 0xE1, 0xCD, 0x09, 0x97, - 0x64, 0x14, 0xAB, 0xEA, 0x0B, 0xD8, 0xE2, 0xA8, 0x2A, 0x63, - 0x35, 0x90, 0xEE, 0x7F, 0xEA, 0xCE, 0xA5, 0xEF, 0x7F, 0xAB, - 0x87, 0x47, 0x9B, 0x45, 0x35, 0x9A, 0xDA, 0x8C, 0xF4, 0xD3, - 0x8A, 0x0B, 0x9B, 0xE6, 0xEA, 0x92, 0xBB, 0x05, 0xE1, 0xAC, - 0x3E, 0x35, 0xDB, 0xED, 0x65, 0x1D, 0xB6, 0x92, 0xEB, 0x29, - 0x79, 0xF8, 0x3F, 0xC2, 0x58, 0x40, 0x32, 0x66, 0x87, 0x56, - 0x50, 0xFF, 0xBF, 0x3E, 0xBD, 0xE9, 0x94, 0xBF, 0x31, 0xBE, - 0x87, 0x2D, 0xEF, 0x64, 0x1E, 0x0E, 0x67, 0x3A, 0x9C, 0x94, - 0xDA, 0x5B, 0x0C, 0x8C, 0x3D, 0xEE, 0x9D, 0xCD, 0x92, 0xDE, - 0x40, 0x02, 0x65, 0x36, 0xC9, 0x1B, 0xF5, 0x7E, 0x4E, 0x07, - 0xB4, 0x7F, 0x14, 0x0E, 0x03, 0x2E, 0x86, 0xF0, 0x45, 0x5F, - 0xDC, 0xA2, 0xE8, 0xC7, 0x83, 0x02, 0x81, 0xC1, 0x00, 0xCA, - 0xED, 0xA5, 0x3F, 0x59, 0xAC, 0x4C, 0xAD, 0xAB, 0x23, 0x02, - 0x95, 0x80, 0xA0, 0xAF, 0x35, 0x17, 0xDB, 0xE7, 0x7F, 0x72, - 0x41, 0x2C, 0x5C, 0xB4, 0x43, 0x85, 0x46, 0x73, 0x9F, 0x58, - 0xE9, 0x40, 0x8B, 0xEC, 0xB0, 0xEF, 0x86, 0x4C, 0x31, 0xDE, - 0xC8, 0x6C, 0x74, 0x75, 0xA2, 0xDB, 0x65, 0xF4, 0x50, 0xC6, - 0x99, 0xA2, 0x70, 0xDE, 0xB6, 0x22, 0xC2, 0x01, 0x15, 0x49, - 0x13, 0xA0, 0xE2, 0x20, 0x78, 0x44, 0xEC, 0x1F, 0x42, 0xB3, - 0x25, 0x09, 0xCE, 0x75, 0x13, 0x75, 0x36, 0x11, 0x47, 0x2C, - 0x3C, 0x15, 0x1F, 0xF0, 0x54, 0xD5, 0x18, 0xAE, 0x61, 0x07, - 0xAC, 0x3D, 0x83, 0x46, 0x03, 0x8C, 0xBF, 0x63, 0x26, 0xA8, - 0x19, 0x7C, 0xFF, 0xDE, 0x20, 0x78, 0xD0, 0xDA, 0x70, 0x2E, - 0xBD, 0xFA, 0x96, 0xDD, 0x15, 0x78, 0x9B, 0xEF, 0xED, 0x17, - 0x90, 0x6F, 0x14, 0x35, 0x50, 0x8E, 0x1D, 0x78, 0xB0, 0x8A, - 0xA0, 0x53, 0x10, 0x15, 0x64, 0xCC, 0x47, 0x05, 0xB6, 0xC6, - 0x48, 0xC0, 0x5D, 0xB4, 0x4B, 0x1A, 0x5F, 0xB8, 0x9E, 0x75, - 0xCD, 0xC3, 0x64, 0x66, 0x88, 0x10, 0x9C, 0x8B, 0x87, 0x14, - 0x34, 0xE6, 0x60, 0x3C, 0xA5, 0xB7, 0x81, 0x1D, 0x0B, 0x79, - 0x93, 0x5D, 0x4A, 0x42, 0x7A, 0x7F, 0x33, 0xF0, 0x3E, 0x9E, - 0x63, 0xBD, 0xB6, 0x5F, 0xF9, 0x47, 0xA7, 0x0A, 0x49, 0x70, - 0xB1, 0x02, 0x81, 0xC0, 0x6F, 0xC6, 0xF4, 0x3E, 0xDA, 0xAD, - 0xF6, 0xB1, 0x66, 0xC5, 0x62, 0xB8, 0xD8, 0x3C, 0x61, 0x1B, - 0xDE, 0xD4, 0x4A, 0xFF, 0xA0, 0x66, 0x18, 0xDE, 0x07, 0x3B, - 0x32, 0x35, 0x84, 0x83, 0x61, 0x38, 0x0C, 0x14, 0xF7, 0x5B, - 0x7E, 0xCA, 0xE7, 0xB8, 0x9A, 0x40, 0x40, 0x0D, 0xE0, 0xD4, - 0x24, 0xED, 0x1A, 0xC1, 0x41, 0xDA, 0x29, 0x47, 0xB5, 0x64, - 0xC0, 0xC2, 0xFB, 0xFA, 0x3C, 0x3F, 0x4D, 0x57, 0xAD, 0xA3, - 0x92, 0x95, 0x4E, 0xC2, 0x76, 0xAE, 0xC2, 0xCB, 0x67, 0xC6, - 0x78, 0x79, 0xC7, 0xDC, 0xCE, 0x73, 0xBB, 0xE8, 0x98, 0x65, - 0xFE, 0x56, 0x8F, 0xB2, 0xF4, 0x62, 0xA4, 0x60, 0x60, 0x80, - 0x49, 0x8A, 0x36, 0xBF, 0xDE, 0x72, 0x7E, 0xB1, 0xD3, 0xF5, - 0x1D, 0x64, 0x17, 0x26, 0xE5, 0x3D, 0x67, 0xB2, 0x0A, 0x8B, - 0x99, 0x27, 0x04, 0x64, 0x9A, 0x94, 0xFC, 0x1D, 0x73, 0x26, - 0xC3, 0x56, 0xF9, 0xEE, 0x2B, 0x99, 0x65, 0xA5, 0xC8, 0x73, - 0xF6, 0x67, 0x83, 0xBC, 0x2B, 0x96, 0x5F, 0x36, 0xE4, 0xCA, - 0xBD, 0xE0, 0x24, 0x34, 0xD6, 0x48, 0x54, 0x56, 0xAD, 0xA3, - 0xE3, 0x3D, 0x17, 0xBC, 0xB3, 0xE6, 0x24, 0xFE, 0x50, 0xC6, - 0x2F, 0xCB, 0xB4, 0xAF, 0xC7, 0xE8, 0xDD, 0x96, 0x86, 0x9D, - 0xB4, 0x7F, 0x1B, 0x26, 0x01, 0x33, 0x87, 0xDB, 0x6A, 0x7F, - 0xF6, 0x9A, 0xB7, 0xC1, 0x94, 0xEB, 0x02, 0x81, 0xC1, 0x00, - 0xB0, 0x6D, 0x20, 0x68, 0x0D, 0x7C, 0x81, 0x45, 0xD4, 0x2E, - 0x22, 0x06, 0xFC, 0xC7, 0xB6, 0xCC, 0x40, 0x2C, 0x0D, 0xFE, - 0x7D, 0xC5, 0x2F, 0xDE, 0x81, 0x52, 0xDA, 0xC2, 0x3F, 0xAF, - 0xE0, 0x4B, 0x1A, 0xB5, 0x0C, 0x59, 0x60, 0x45, 0xB0, 0x65, - 0x03, 0x3D, 0xD9, 0x1C, 0xFF, 0x51, 0x51, 0xD2, 0x38, 0x31, - 0x2A, 0x19, 0x54, 0x63, 0x31, 0x1D, 0xC4, 0xE6, 0x4A, 0xAE, - 0xC8, 0xD3, 0xE9, 0xE1, 0xEF, 0x3C, 0xE1, 0x1F, 0x30, 0xA6, - 0x7A, 0xBD, 0xCE, 0xE2, 0xD2, 0x62, 0xD2, 0x5A, 0xE9, 0x76, - 0xA9, 0x7C, 0xAB, 0x19, 0x13, 0x87, 0x8D, 0xA5, 0x61, 0xA6, - 0x36, 0x57, 0x87, 0x3B, 0x64, 0x59, 0x9D, 0xBA, 0x9F, 0x67, - 0x72, 0x6A, 0x86, 0x84, 0xA6, 0x08, 0x31, 0x41, 0xD3, 0x48, - 0x09, 0x3B, 0x5E, 0x6C, 0x5F, 0x56, 0x55, 0x7F, 0xAD, 0x7E, - 0xC2, 0x27, 0xEE, 0x8A, 0xF1, 0x37, 0x51, 0xF7, 0x49, 0x80, - 0xA3, 0x65, 0x74, 0x11, 0xDD, 0xA7, 0xBE, 0xFA, 0x58, 0x7B, - 0x69, 0xB4, 0xC2, 0x9A, 0x35, 0x2F, 0xBE, 0x84, 0x4E, 0x2C, - 0x66, 0x5B, 0x38, 0x6F, 0x47, 0xBD, 0x30, 0x44, 0x0A, 0x02, - 0xAC, 0x8C, 0xB9, 0x66, 0x1E, 0x14, 0x2D, 0x90, 0x71, 0x42, - 0x12, 0xB7, 0x0E, 0x3A, 0x8B, 0xC5, 0x98, 0x65, 0xFD, 0x8F, - 0x53, 0x81, 0x7F, 0xE4, 0xD9, 0x58, 0x0E, 0xF5, 0xA9, 0x39, - 0xE4, 0x61, 0x02, 0x81, 0xC1, 0x00, 0xB3, 0x94, 0x8F, 0x2B, - 0xFD, 0x84, 0x2E, 0x83, 0x42, 0x86, 0x56, 0x7E, 0xB5, 0xF8, - 0x3C, 0xC5, 0x0C, 0xCB, 0xBD, 0x32, 0x0C, 0xD7, 0xAA, 0xA7, - 0xB0, 0xE9, 0xA4, 0x6A, 0xD1, 0x01, 0xDB, 0x87, 0x2A, 0xF7, - 0xDF, 0xEC, 0xC2, 0x03, 0x5D, 0x55, 0xA8, 0x66, 0x73, 0x79, - 0xA9, 0xAB, 0xBD, 0xAF, 0x69, 0x37, 0xFE, 0x41, 0xB5, 0x53, - 0xB3, 0xB2, 0xC0, 0xB1, 0x80, 0x34, 0xE6, 0xE1, 0x7B, 0xAE, - 0x67, 0xC7, 0xF3, 0x57, 0xFE, 0x12, 0xBC, 0x78, 0xAA, 0x75, - 0x0D, 0xAC, 0x79, 0x90, 0x14, 0x49, 0xFE, 0x6B, 0x51, 0xE3, - 0xE4, 0x46, 0xB2, 0x10, 0x4D, 0x05, 0x6A, 0x12, 0x80, 0x2A, - 0x8F, 0x39, 0x42, 0x0E, 0x3B, 0x24, 0x2B, 0x50, 0x5D, 0xF3, - 0xA7, 0x7F, 0x2F, 0x82, 0x89, 0x87, 0x9F, 0xF8, 0x7B, 0x1E, - 0x05, 0x6E, 0x75, 0x83, 0x04, 0x35, 0x66, 0x4A, 0x06, 0x57, - 0x39, 0xAB, 0x21, 0x0B, 0x94, 0x41, 0x6A, 0x2A, 0xC7, 0xDE, - 0x98, 0x45, 0x8F, 0x96, 0x1C, 0xF2, 0xD8, 0xFB, 0x9C, 0x10, - 0x8E, 0x41, 0x7A, 0xDD, 0xDD, 0x1D, 0xEF, 0xA5, 0x67, 0xEC, - 0xFE, 0xA3, 0x2D, 0xA9, 0xFD, 0xF3, 0xEE, 0x35, 0xF4, 0xA7, - 0xBC, 0xF9, 0x71, 0xCC, 0xB9, 0xC0, 0x5F, 0x58, 0x5B, 0xBD, - 0x1A, 0x9E, 0xC7, 0x08, 0x67, 0x7C, 0xC7, 0x51, 0x5B, 0xBE, - 0xE3, 0xF8, 0xBE, 0x1E, 0xC7, 0xD2, 0x28, 0x97 + 0x30, 0x82, 0x06, 0xFE, 0x02, 0x01, 0x00, 0x30, 0x0D, 0x06, + 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x04, 0x82, 0x06, 0xE8, 0x30, 0x82, 0x06, 0xE4, + 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x81, 0x00, 0xAC, 0x39, + 0x50, 0x68, 0x8F, 0x78, 0xF8, 0x10, 0x9B, 0x68, 0x96, 0xD3, + 0xE1, 0x9C, 0x56, 0x68, 0x5A, 0x41, 0x62, 0xE3, 0xB3, 0x41, + 0xB0, 0x55, 0x80, 0x17, 0xB0, 0x88, 0x16, 0x9B, 0xE0, 0x97, + 0x74, 0x5F, 0x42, 0x79, 0x73, 0x42, 0xDF, 0x93, 0xF3, 0xAA, + 0x9D, 0xEE, 0x2D, 0x6F, 0xAA, 0xBC, 0x27, 0x90, 0x84, 0xC0, + 0x5D, 0xC7, 0xEC, 0x49, 0xEA, 0x5C, 0x66, 0x1D, 0x70, 0x9C, + 0x53, 0x5C, 0xBA, 0xA1, 0xB3, 0x58, 0xC9, 0x3E, 0x8E, 0x9B, + 0x72, 0x3D, 0x6E, 0x02, 0x02, 0x00, 0x9C, 0x65, 0x56, 0x82, + 0xA3, 0x22, 0xB4, 0x08, 0x5F, 0x2A, 0xEF, 0xDF, 0x9A, 0xD0, + 0xE7, 0x31, 0x59, 0x26, 0x5B, 0x0B, 0x1C, 0x63, 0x61, 0xFF, + 0xD5, 0x69, 0x32, 0x19, 0x06, 0x7E, 0x0F, 0x40, 0x3C, 0x7A, + 0x1E, 0xC8, 0xFC, 0x58, 0x6C, 0x64, 0xAE, 0x10, 0x3D, 0xA8, + 0x23, 0xFF, 0x8E, 0x1A, 0xCA, 0x6A, 0x82, 0xE2, 0xF9, 0x01, + 0x64, 0x2C, 0x97, 0xA0, 0x1A, 0x89, 0xA0, 0x74, 0xD3, 0xB6, + 0x05, 0x11, 0xF2, 0x62, 0x06, 0x48, 0x2A, 0xF7, 0x66, 0xCE, + 0xC1, 0x85, 0xE1, 0xD2, 0x27, 0xEA, 0xCA, 0x12, 0xA5, 0x91, + 0x97, 0x3E, 0xFC, 0x94, 0x06, 0x59, 0x51, 0xC0, 0xE7, 0x13, + 0xB6, 0x87, 0x7B, 0x5F, 0xD2, 0xC0, 0x56, 0x2F, 0x5E, 0x1D, + 0x02, 0xC3, 0x11, 0x2C, 0xDF, 0xF7, 0x01, 0xDA, 0xBD, 0x85, + 0x54, 0x35, 0x32, 0x5F, 0xC5, 0xC8, 0xF9, 0x7A, 0x9F, 0x89, + 0xF7, 0x03, 0x0E, 0x7E, 0x79, 0x5D, 0x04, 0x82, 0x35, 0x10, + 0xFE, 0x6D, 0x9B, 0xBF, 0xB8, 0xEE, 0xE2, 0x62, 0x87, 0x26, + 0x5E, 0x2F, 0x50, 0x2F, 0x78, 0x0C, 0xE8, 0x73, 0x4F, 0x88, + 0x6A, 0xD6, 0x26, 0xA4, 0xC9, 0xFC, 0xFA, 0x1E, 0x8A, 0xB0, + 0xF4, 0x32, 0xCF, 0x57, 0xCD, 0xA1, 0x58, 0x8A, 0x49, 0x0F, + 0xBB, 0xA9, 0x1D, 0x86, 0xAB, 0xB9, 0x8F, 0x8D, 0x57, 0x19, + 0xB2, 0x5A, 0x7E, 0xA4, 0xEA, 0xCC, 0xB7, 0x96, 0x7A, 0x3B, + 0x38, 0xCD, 0xDE, 0xE0, 0x61, 0xFC, 0xC9, 0x06, 0x8F, 0x93, + 0x5A, 0xCE, 0xAD, 0x2A, 0xE3, 0x2D, 0x3E, 0x39, 0x5D, 0x41, + 0x83, 0x01, 0x1F, 0x0F, 0xE1, 0x7F, 0x76, 0xC7, 0x28, 0xDA, + 0x56, 0xEF, 0xBF, 0xDC, 0x26, 0x35, 0x40, 0xBE, 0xAD, 0xC7, + 0x38, 0xAD, 0xA4, 0x06, 0xAC, 0xCA, 0xE8, 0x51, 0xEB, 0xC0, + 0xF8, 0x68, 0x02, 0x2C, 0x9B, 0xA1, 0x14, 0xBC, 0xF8, 0x61, + 0x86, 0xD7, 0x56, 0xD7, 0x73, 0xF4, 0xAB, 0xBB, 0x6A, 0x21, + 0xD3, 0x88, 0x22, 0xB4, 0xE7, 0x6F, 0x7F, 0x91, 0xE5, 0x0E, + 0xC6, 0x08, 0x49, 0xDE, 0xEA, 0x13, 0x58, 0x72, 0xA0, 0xAA, + 0x3A, 0xF9, 0x36, 0x03, 0x45, 0x57, 0x5E, 0x87, 0xD2, 0x73, + 0x65, 0xC4, 0x8C, 0xA3, 0xEE, 0xC9, 0xD6, 0x73, 0x7C, 0x96, + 0x41, 0x93, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, + 0x80, 0x40, 0x19, 0x74, 0xDB, 0xF5, 0xCA, 0x48, 0x49, 0xA6, + 0x0D, 0xDF, 0x55, 0x2C, 0xFB, 0x4B, 0x0D, 0xBB, 0xC9, 0xEA, + 0x4C, 0x65, 0x43, 0x65, 0xA5, 0xEC, 0xEE, 0xE4, 0x3D, 0x42, + 0x6C, 0xF1, 0xC2, 0x6D, 0x05, 0xA7, 0x70, 0x1C, 0x7E, 0x1F, + 0x48, 0xA9, 0xC0, 0x2E, 0xD7, 0x9F, 0x01, 0x98, 0xC2, 0x3E, + 0xD7, 0x83, 0x11, 0x35, 0xD6, 0x5B, 0x13, 0x87, 0xAE, 0xAC, + 0x32, 0xF8, 0xDE, 0xB6, 0x08, 0x25, 0x4E, 0x59, 0xBA, 0x09, + 0xEC, 0xC6, 0x97, 0x04, 0x85, 0xE8, 0x93, 0xC6, 0xBB, 0x03, + 0x7A, 0x94, 0x20, 0x3B, 0x27, 0x87, 0x6A, 0x36, 0x41, 0x7C, + 0xD5, 0xF4, 0x81, 0x1C, 0x0B, 0x39, 0xEB, 0x14, 0xA7, 0xA6, + 0x01, 0x37, 0x50, 0x48, 0xD5, 0xC6, 0x57, 0x9A, 0x1B, 0x01, + 0x02, 0x1F, 0x80, 0x34, 0x45, 0x09, 0xE6, 0xBF, 0x31, 0x19, + 0xB7, 0xE1, 0xBA, 0xDA, 0xEB, 0x1A, 0xB0, 0xCD, 0xF5, 0xA6, + 0x91, 0x63, 0xAC, 0x28, 0xE4, 0x8F, 0xEA, 0x7E, 0xF6, 0x0A, + 0x4A, 0x71, 0x21, 0xA5, 0xF1, 0x70, 0x0D, 0x1B, 0xD9, 0x70, + 0x64, 0x74, 0x57, 0x2F, 0x9F, 0xEC, 0xD4, 0x93, 0x16, 0xC7, + 0xEE, 0xF8, 0xC0, 0x9F, 0x52, 0x4A, 0x1F, 0xAD, 0xDD, 0x40, + 0x98, 0x53, 0x68, 0xFA, 0xDE, 0xA2, 0x04, 0xA0, 0x24, 0x05, + 0xEF, 0xCB, 0x4F, 0x70, 0xDF, 0xB9, 0x5C, 0xC2, 0x5E, 0xE4, + 0xC9, 0xCD, 0x0F, 0x5E, 0x4B, 0x77, 0xBB, 0x84, 0x69, 0x54, + 0x98, 0x41, 0xB7, 0x9C, 0x0E, 0x38, 0xD8, 0xF7, 0xF3, 0x9F, + 0xEF, 0xE5, 0x9B, 0xB6, 0x4B, 0xD6, 0x7A, 0x65, 0xF5, 0x69, + 0xFA, 0xC2, 0x13, 0x70, 0x6C, 0x28, 0xA4, 0x29, 0xAC, 0xD9, + 0xBF, 0xEC, 0x6A, 0x2E, 0xED, 0xE4, 0xBA, 0xDF, 0xD0, 0xF1, + 0xF3, 0x3C, 0x6C, 0x84, 0xDF, 0xB7, 0x5A, 0x94, 0xCF, 0xD9, + 0x2D, 0xEA, 0xEA, 0xB4, 0xD0, 0x91, 0x2E, 0x77, 0x15, 0x18, + 0x0D, 0x6B, 0xBA, 0x2A, 0x0C, 0xF1, 0x92, 0x9D, 0xD6, 0x04, + 0x05, 0xB6, 0x38, 0xC2, 0xE0, 0xA7, 0x2D, 0x64, 0xF8, 0xDF, + 0x0C, 0x3A, 0x93, 0x83, 0xE1, 0x88, 0x83, 0x5F, 0x67, 0x90, + 0x9F, 0x2B, 0xE0, 0x60, 0x8E, 0xCA, 0x30, 0x13, 0xCA, 0x9F, + 0xCF, 0x7B, 0x6D, 0xD8, 0xCD, 0xEE, 0xF9, 0x96, 0xDD, 0x5E, + 0xF4, 0x47, 0xC9, 0x4C, 0xE6, 0x8F, 0x7F, 0x33, 0x2A, 0x38, + 0x30, 0xAF, 0xD5, 0x4A, 0x79, 0x47, 0x06, 0xCC, 0x96, 0x44, + 0x29, 0x8C, 0x60, 0x2B, 0x08, 0xC7, 0xD0, 0xD3, 0xC3, 0xC5, + 0x2C, 0x63, 0x6C, 0x87, 0xD2, 0xAE, 0x2A, 0xA4, 0x86, 0xE7, + 0x76, 0x74, 0x90, 0xD1, 0x04, 0x37, 0x64, 0x1A, 0xED, 0x08, + 0xD9, 0x98, 0x07, 0x1A, 0x98, 0x0B, 0x89, 0x99, 0xA4, 0xB0, + 0x8C, 0x1A, 0x10, 0xEB, 0xEC, 0xF4, 0xEE, 0x3C, 0xC4, 0x00, + 0xCC, 0x30, 0x9C, 0x43, 0x01, 0x02, 0x81, 0xC1, 0x00, 0xD9, + 0x43, 0xF6, 0x2C, 0x78, 0x26, 0xD2, 0xE7, 0x15, 0xA7, 0x0A, + 0x88, 0x5E, 0xDB, 0x2D, 0xAF, 0xC6, 0xA9, 0x6F, 0x73, 0x88, + 0x3B, 0x6A, 0x08, 0x1F, 0xF5, 0x80, 0xB5, 0x2E, 0x29, 0x8B, + 0x72, 0xF8, 0x35, 0xC8, 0x23, 0x18, 0x1C, 0x0D, 0x0E, 0x38, + 0x82, 0xBB, 0x5B, 0x2F, 0xB4, 0x5C, 0x4E, 0x24, 0x05, 0xA7, + 0x4C, 0x79, 0x48, 0x89, 0x8D, 0x1C, 0x1D, 0x0A, 0x2C, 0xFE, + 0xD9, 0x99, 0xDF, 0x25, 0x8A, 0x2D, 0xF8, 0xEB, 0x2F, 0xDA, + 0x1B, 0x63, 0xE1, 0xCD, 0x09, 0x97, 0x64, 0x14, 0xAB, 0xEA, + 0x0B, 0xD8, 0xE2, 0xA8, 0x2A, 0x63, 0x35, 0x90, 0xEE, 0x7F, + 0xEA, 0xCE, 0xA5, 0xEF, 0x7F, 0xAB, 0x87, 0x47, 0x9B, 0x45, + 0x35, 0x9A, 0xDA, 0x8C, 0xF4, 0xD3, 0x8A, 0x0B, 0x9B, 0xE6, + 0xEA, 0x92, 0xBB, 0x05, 0xE1, 0xAC, 0x3E, 0x35, 0xDB, 0xED, + 0x65, 0x1D, 0xB6, 0x92, 0xEB, 0x29, 0x79, 0xF8, 0x3F, 0xC2, + 0x58, 0x40, 0x32, 0x66, 0x87, 0x56, 0x50, 0xFF, 0xBF, 0x3E, + 0xBD, 0xE9, 0x94, 0xBF, 0x31, 0xBE, 0x87, 0x2D, 0xEF, 0x64, + 0x1E, 0x0E, 0x67, 0x3A, 0x9C, 0x94, 0xDA, 0x5B, 0x0C, 0x8C, + 0x3D, 0xEE, 0x9D, 0xCD, 0x92, 0xDE, 0x40, 0x02, 0x65, 0x36, + 0xC9, 0x1B, 0xF5, 0x7E, 0x4E, 0x07, 0xB4, 0x7F, 0x14, 0x0E, + 0x03, 0x2E, 0x86, 0xF0, 0x45, 0x5F, 0xDC, 0xA2, 0xE8, 0xC7, + 0x83, 0x02, 0x81, 0xC1, 0x00, 0xCA, 0xED, 0xA5, 0x3F, 0x59, + 0xAC, 0x4C, 0xAD, 0xAB, 0x23, 0x02, 0x95, 0x80, 0xA0, 0xAF, + 0x35, 0x17, 0xDB, 0xE7, 0x7F, 0x72, 0x41, 0x2C, 0x5C, 0xB4, + 0x43, 0x85, 0x46, 0x73, 0x9F, 0x58, 0xE9, 0x40, 0x8B, 0xEC, + 0xB0, 0xEF, 0x86, 0x4C, 0x31, 0xDE, 0xC8, 0x6C, 0x74, 0x75, + 0xA2, 0xDB, 0x65, 0xF4, 0x50, 0xC6, 0x99, 0xA2, 0x70, 0xDE, + 0xB6, 0x22, 0xC2, 0x01, 0x15, 0x49, 0x13, 0xA0, 0xE2, 0x20, + 0x78, 0x44, 0xEC, 0x1F, 0x42, 0xB3, 0x25, 0x09, 0xCE, 0x75, + 0x13, 0x75, 0x36, 0x11, 0x47, 0x2C, 0x3C, 0x15, 0x1F, 0xF0, + 0x54, 0xD5, 0x18, 0xAE, 0x61, 0x07, 0xAC, 0x3D, 0x83, 0x46, + 0x03, 0x8C, 0xBF, 0x63, 0x26, 0xA8, 0x19, 0x7C, 0xFF, 0xDE, + 0x20, 0x78, 0xD0, 0xDA, 0x70, 0x2E, 0xBD, 0xFA, 0x96, 0xDD, + 0x15, 0x78, 0x9B, 0xEF, 0xED, 0x17, 0x90, 0x6F, 0x14, 0x35, + 0x50, 0x8E, 0x1D, 0x78, 0xB0, 0x8A, 0xA0, 0x53, 0x10, 0x15, + 0x64, 0xCC, 0x47, 0x05, 0xB6, 0xC6, 0x48, 0xC0, 0x5D, 0xB4, + 0x4B, 0x1A, 0x5F, 0xB8, 0x9E, 0x75, 0xCD, 0xC3, 0x64, 0x66, + 0x88, 0x10, 0x9C, 0x8B, 0x87, 0x14, 0x34, 0xE6, 0x60, 0x3C, + 0xA5, 0xB7, 0x81, 0x1D, 0x0B, 0x79, 0x93, 0x5D, 0x4A, 0x42, + 0x7A, 0x7F, 0x33, 0xF0, 0x3E, 0x9E, 0x63, 0xBD, 0xB6, 0x5F, + 0xF9, 0x47, 0xA7, 0x0A, 0x49, 0x70, 0xB1, 0x02, 0x81, 0xC0, + 0x6F, 0xC6, 0xF4, 0x3E, 0xDA, 0xAD, 0xF6, 0xB1, 0x66, 0xC5, + 0x62, 0xB8, 0xD8, 0x3C, 0x61, 0x1B, 0xDE, 0xD4, 0x4A, 0xFF, + 0xA0, 0x66, 0x18, 0xDE, 0x07, 0x3B, 0x32, 0x35, 0x84, 0x83, + 0x61, 0x38, 0x0C, 0x14, 0xF7, 0x5B, 0x7E, 0xCA, 0xE7, 0xB8, + 0x9A, 0x40, 0x40, 0x0D, 0xE0, 0xD4, 0x24, 0xED, 0x1A, 0xC1, + 0x41, 0xDA, 0x29, 0x47, 0xB5, 0x64, 0xC0, 0xC2, 0xFB, 0xFA, + 0x3C, 0x3F, 0x4D, 0x57, 0xAD, 0xA3, 0x92, 0x95, 0x4E, 0xC2, + 0x76, 0xAE, 0xC2, 0xCB, 0x67, 0xC6, 0x78, 0x79, 0xC7, 0xDC, + 0xCE, 0x73, 0xBB, 0xE8, 0x98, 0x65, 0xFE, 0x56, 0x8F, 0xB2, + 0xF4, 0x62, 0xA4, 0x60, 0x60, 0x80, 0x49, 0x8A, 0x36, 0xBF, + 0xDE, 0x72, 0x7E, 0xB1, 0xD3, 0xF5, 0x1D, 0x64, 0x17, 0x26, + 0xE5, 0x3D, 0x67, 0xB2, 0x0A, 0x8B, 0x99, 0x27, 0x04, 0x64, + 0x9A, 0x94, 0xFC, 0x1D, 0x73, 0x26, 0xC3, 0x56, 0xF9, 0xEE, + 0x2B, 0x99, 0x65, 0xA5, 0xC8, 0x73, 0xF6, 0x67, 0x83, 0xBC, + 0x2B, 0x96, 0x5F, 0x36, 0xE4, 0xCA, 0xBD, 0xE0, 0x24, 0x34, + 0xD6, 0x48, 0x54, 0x56, 0xAD, 0xA3, 0xE3, 0x3D, 0x17, 0xBC, + 0xB3, 0xE6, 0x24, 0xFE, 0x50, 0xC6, 0x2F, 0xCB, 0xB4, 0xAF, + 0xC7, 0xE8, 0xDD, 0x96, 0x86, 0x9D, 0xB4, 0x7F, 0x1B, 0x26, + 0x01, 0x33, 0x87, 0xDB, 0x6A, 0x7F, 0xF6, 0x9A, 0xB7, 0xC1, + 0x94, 0xEB, 0x02, 0x81, 0xC1, 0x00, 0xB0, 0x6D, 0x20, 0x68, + 0x0D, 0x7C, 0x81, 0x45, 0xD4, 0x2E, 0x22, 0x06, 0xFC, 0xC7, + 0xB6, 0xCC, 0x40, 0x2C, 0x0D, 0xFE, 0x7D, 0xC5, 0x2F, 0xDE, + 0x81, 0x52, 0xDA, 0xC2, 0x3F, 0xAF, 0xE0, 0x4B, 0x1A, 0xB5, + 0x0C, 0x59, 0x60, 0x45, 0xB0, 0x65, 0x03, 0x3D, 0xD9, 0x1C, + 0xFF, 0x51, 0x51, 0xD2, 0x38, 0x31, 0x2A, 0x19, 0x54, 0x63, + 0x31, 0x1D, 0xC4, 0xE6, 0x4A, 0xAE, 0xC8, 0xD3, 0xE9, 0xE1, + 0xEF, 0x3C, 0xE1, 0x1F, 0x30, 0xA6, 0x7A, 0xBD, 0xCE, 0xE2, + 0xD2, 0x62, 0xD2, 0x5A, 0xE9, 0x76, 0xA9, 0x7C, 0xAB, 0x19, + 0x13, 0x87, 0x8D, 0xA5, 0x61, 0xA6, 0x36, 0x57, 0x87, 0x3B, + 0x64, 0x59, 0x9D, 0xBA, 0x9F, 0x67, 0x72, 0x6A, 0x86, 0x84, + 0xA6, 0x08, 0x31, 0x41, 0xD3, 0x48, 0x09, 0x3B, 0x5E, 0x6C, + 0x5F, 0x56, 0x55, 0x7F, 0xAD, 0x7E, 0xC2, 0x27, 0xEE, 0x8A, + 0xF1, 0x37, 0x51, 0xF7, 0x49, 0x80, 0xA3, 0x65, 0x74, 0x11, + 0xDD, 0xA7, 0xBE, 0xFA, 0x58, 0x7B, 0x69, 0xB4, 0xC2, 0x9A, + 0x35, 0x2F, 0xBE, 0x84, 0x4E, 0x2C, 0x66, 0x5B, 0x38, 0x6F, + 0x47, 0xBD, 0x30, 0x44, 0x0A, 0x02, 0xAC, 0x8C, 0xB9, 0x66, + 0x1E, 0x14, 0x2D, 0x90, 0x71, 0x42, 0x12, 0xB7, 0x0E, 0x3A, + 0x8B, 0xC5, 0x98, 0x65, 0xFD, 0x8F, 0x53, 0x81, 0x7F, 0xE4, + 0xD9, 0x58, 0x0E, 0xF5, 0xA9, 0x39, 0xE4, 0x61, 0x02, 0x81, + 0xC1, 0x00, 0xB3, 0x94, 0x8F, 0x2B, 0xFD, 0x84, 0x2E, 0x83, + 0x42, 0x86, 0x56, 0x7E, 0xB5, 0xF8, 0x3C, 0xC5, 0x0C, 0xCB, + 0xBD, 0x32, 0x0C, 0xD7, 0xAA, 0xA7, 0xB0, 0xE9, 0xA4, 0x6A, + 0xD1, 0x01, 0xDB, 0x87, 0x2A, 0xF7, 0xDF, 0xEC, 0xC2, 0x03, + 0x5D, 0x55, 0xA8, 0x66, 0x73, 0x79, 0xA9, 0xAB, 0xBD, 0xAF, + 0x69, 0x37, 0xFE, 0x41, 0xB5, 0x53, 0xB3, 0xB2, 0xC0, 0xB1, + 0x80, 0x34, 0xE6, 0xE1, 0x7B, 0xAE, 0x67, 0xC7, 0xF3, 0x57, + 0xFE, 0x12, 0xBC, 0x78, 0xAA, 0x75, 0x0D, 0xAC, 0x79, 0x90, + 0x14, 0x49, 0xFE, 0x6B, 0x51, 0xE3, 0xE4, 0x46, 0xB2, 0x10, + 0x4D, 0x05, 0x6A, 0x12, 0x80, 0x2A, 0x8F, 0x39, 0x42, 0x0E, + 0x3B, 0x24, 0x2B, 0x50, 0x5D, 0xF3, 0xA7, 0x7F, 0x2F, 0x82, + 0x89, 0x87, 0x9F, 0xF8, 0x7B, 0x1E, 0x05, 0x6E, 0x75, 0x83, + 0x04, 0x35, 0x66, 0x4A, 0x06, 0x57, 0x39, 0xAB, 0x21, 0x0B, + 0x94, 0x41, 0x6A, 0x2A, 0xC7, 0xDE, 0x98, 0x45, 0x8F, 0x96, + 0x1C, 0xF2, 0xD8, 0xFB, 0x9C, 0x10, 0x8E, 0x41, 0x7A, 0xDD, + 0xDD, 0x1D, 0xEF, 0xA5, 0x67, 0xEC, 0xFE, 0xA3, 0x2D, 0xA9, + 0xFD, 0xF3, 0xEE, 0x35, 0xF4, 0xA7, 0xBC, 0xF9, 0x71, 0xCC, + 0xB9, 0xC0, 0x5F, 0x58, 0x5B, 0xBD, 0x1A, 0x9E, 0xC7, 0x08, + 0x67, 0x7C, 0xC7, 0x51, 0x5B, 0xBE, 0xE3, 0xF8, 0xBE, 0x1E, + 0xC7, 0xD2, 0x28, 0x97 }; static const int sizeof_client_key_der_3072 = sizeof(client_key_der_3072); @@ -2735,9 +2738,9 @@ static const int sizeof_client_keypub_der_3072 = sizeof(client_keypub_der_3072); static const unsigned char client_cert_der_3072[] = { 0x30, 0x82, 0x06, 0x1D, 0x30, 0x82, 0x04, 0x85, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x0B, 0x5C, 0x9F, 0x12, 0x25, - 0x90, 0xAA, 0x52, 0xC0, 0xDF, 0xE1, 0xE1, 0x1F, 0xED, 0xA9, - 0x31, 0x01, 0x0A, 0x09, 0x8B, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x1E, 0xD5, 0xB7, 0x66, 0x40, + 0x3A, 0xE9, 0x9B, 0xDD, 0x58, 0xE4, 0xE4, 0x9A, 0xC0, 0xDA, + 0x1E, 0xD7, 0xB9, 0x5A, 0x1F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -2755,10 +2758,10 @@ static const unsigned char client_cert_der_3072[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -2841,8 +2844,8 @@ static const unsigned char client_cert_der_3072[] = 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, - 0x0B, 0x5C, 0x9F, 0x12, 0x25, 0x90, 0xAA, 0x52, 0xC0, 0xDF, - 0xE1, 0xE1, 0x1F, 0xED, 0xA9, 0x31, 0x01, 0x0A, 0x09, 0x8B, + 0x1E, 0xD5, 0xB7, 0x66, 0x40, 0x3A, 0xE9, 0x9B, 0xDD, 0x58, + 0xE4, 0xE4, 0x9A, 0xC0, 0xDA, 0x1E, 0xD7, 0xB9, 0x5A, 0x1F, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, @@ -2852,45 +2855,45 @@ static const unsigned char client_cert_der_3072[] = 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, - 0x03, 0x82, 0x01, 0x81, 0x00, 0x14, 0x27, 0x57, 0x47, 0x12, - 0xA4, 0x78, 0xA2, 0xC9, 0xDC, 0x93, 0xF8, 0x47, 0xEE, 0xF4, - 0xFD, 0x66, 0x80, 0x13, 0x43, 0x9E, 0xDE, 0x23, 0x8C, 0xF7, - 0x3F, 0xFE, 0x46, 0x9C, 0x85, 0x58, 0x2A, 0x6F, 0x8D, 0x22, - 0x92, 0x8C, 0xD6, 0x36, 0xCA, 0x90, 0x4F, 0x45, 0xC3, 0xAB, - 0x78, 0xCA, 0x3C, 0xFE, 0xD0, 0xF5, 0x0F, 0x6D, 0x00, 0xFE, - 0x3B, 0x42, 0xB0, 0x86, 0x0B, 0x75, 0xF2, 0x7C, 0xD3, 0xC7, - 0xDB, 0x0B, 0x70, 0xE8, 0xEC, 0xB7, 0xBF, 0x26, 0x30, 0xA8, - 0x19, 0x67, 0xBD, 0x74, 0x03, 0xCF, 0xD1, 0x08, 0x8E, 0x9C, - 0xD5, 0x1B, 0x45, 0x28, 0xB2, 0x67, 0x8E, 0x3A, 0xA5, 0x27, - 0xC9, 0x1B, 0x6A, 0xE9, 0x93, 0xCE, 0x94, 0xC0, 0x00, 0x0C, - 0xE8, 0xF1, 0x76, 0x02, 0xA4, 0x30, 0x72, 0xA8, 0xFD, 0x55, - 0x1C, 0xD1, 0xB8, 0x25, 0xF1, 0x62, 0xF6, 0xBA, 0x28, 0xFD, - 0x30, 0xB1, 0x11, 0x63, 0xF7, 0xB3, 0x78, 0x54, 0x09, 0x04, - 0xC1, 0x66, 0x12, 0xC7, 0x01, 0xAE, 0x99, 0xE3, 0x55, 0xC4, - 0x29, 0xBD, 0x1B, 0x1A, 0xDA, 0xB9, 0x77, 0xFD, 0x04, 0xDB, - 0xB1, 0x68, 0x56, 0x35, 0x65, 0xE1, 0xAA, 0x67, 0xC8, 0xAC, - 0xBE, 0xE5, 0xF8, 0x27, 0xFB, 0xB4, 0x51, 0x4F, 0x38, 0xE5, - 0xDE, 0x09, 0xA6, 0x81, 0xA9, 0xEF, 0xDC, 0xD6, 0x4A, 0x96, - 0x47, 0xB8, 0x38, 0x14, 0xF8, 0x25, 0x5D, 0xAC, 0xF3, 0xE5, - 0x3B, 0xF2, 0x1B, 0x70, 0x32, 0x3B, 0x2D, 0xFA, 0x20, 0xCA, - 0x2E, 0xA5, 0xCA, 0x13, 0x9D, 0x84, 0xD2, 0xD4, 0x35, 0x16, - 0x58, 0x6E, 0x52, 0x5E, 0x09, 0x61, 0x83, 0xC2, 0xE2, 0x56, - 0x2C, 0xAB, 0x52, 0xBF, 0x54, 0xDC, 0xBD, 0xF3, 0xBF, 0xA7, - 0x16, 0x6E, 0x0E, 0xCA, 0x68, 0x54, 0xD1, 0x5C, 0x4D, 0x06, - 0x7A, 0x93, 0x47, 0x1C, 0xCC, 0xA9, 0x66, 0xDA, 0x69, 0x0F, - 0xF9, 0x1F, 0x25, 0x64, 0x29, 0x40, 0x97, 0x50, 0x3B, 0xCF, - 0x0C, 0x50, 0x9B, 0x4D, 0xFF, 0x60, 0xBC, 0xD3, 0xE4, 0xA0, - 0xB7, 0x64, 0xC6, 0x66, 0x2A, 0xF6, 0x02, 0xE2, 0x3F, 0x92, - 0x31, 0x3B, 0xD7, 0xEA, 0x1A, 0xC3, 0x1A, 0x0C, 0x19, 0x88, - 0xAB, 0x5F, 0x74, 0xB7, 0x9D, 0x7B, 0x8D, 0x4D, 0x3A, 0x84, - 0x43, 0xF2, 0x67, 0xB1, 0xBE, 0xA0, 0x9E, 0xFD, 0x3D, 0xAA, - 0xC1, 0x38, 0x1A, 0xDF, 0xAC, 0x30, 0xFE, 0x63, 0x69, 0xAF, - 0xD6, 0xF2, 0x21, 0x63, 0x11, 0x63, 0x29, 0xAC, 0x63, 0x9E, - 0x9F, 0x9F, 0xC4, 0x53, 0xB3, 0xDB, 0x78, 0xC0, 0x2D, 0x79, - 0x68, 0x1F, 0xD2, 0xD1, 0x36, 0xD1, 0xFB, 0xE3, 0xC0, 0xA7, - 0x31, 0xEB, 0x15, 0x63, 0x99, 0x0B, 0x93, 0x9D, 0x87, 0xC7, - 0xFE, 0x56, 0x5D, 0xFC, 0xE7, 0x29, 0x2A, 0x9E, 0x15, 0xBE, - 0xEF, 0x54, 0xE7, 0x0F, 0x6D, 0x9B, 0x36, 0xB6, 0x17 + 0x03, 0x82, 0x01, 0x81, 0x00, 0x5E, 0xB0, 0xED, 0x38, 0x36, + 0xB8, 0xF7, 0xE4, 0x0C, 0xB0, 0xC3, 0x6A, 0xBB, 0x7A, 0xB9, + 0x61, 0x05, 0x9D, 0xB9, 0x82, 0x12, 0x2D, 0x9C, 0x9E, 0x91, + 0x7B, 0xEC, 0xD0, 0x9B, 0x81, 0xCA, 0x51, 0xE8, 0xD4, 0x55, + 0x2D, 0x1A, 0xFF, 0x88, 0x5A, 0xC3, 0xE1, 0xD8, 0x82, 0x17, + 0xC5, 0x4A, 0x7A, 0xD4, 0x17, 0xC8, 0xA2, 0x1C, 0x97, 0x61, + 0xA7, 0xCF, 0xDE, 0x12, 0xF9, 0x5A, 0xD8, 0xB0, 0x63, 0x63, + 0x84, 0xD4, 0x7B, 0xB9, 0x81, 0x37, 0xA0, 0x49, 0xF3, 0x68, + 0x30, 0x0C, 0x84, 0xF8, 0x6C, 0x18, 0x54, 0x34, 0x6F, 0x8D, + 0xA3, 0x22, 0xD3, 0xD2, 0x3B, 0x42, 0xBC, 0x3B, 0x28, 0x0F, + 0x95, 0x35, 0xF4, 0x9F, 0xDC, 0x18, 0x9D, 0x4F, 0xC5, 0x5F, + 0x0D, 0xD2, 0xBD, 0x88, 0xB8, 0xA7, 0x88, 0x82, 0xD3, 0x74, + 0x5B, 0xA6, 0xAD, 0xB0, 0x2B, 0x70, 0x33, 0xC9, 0x08, 0x7E, + 0x5F, 0x9B, 0x99, 0x3C, 0x61, 0xF0, 0x1B, 0x3C, 0x1C, 0x4A, + 0x2A, 0x05, 0x84, 0xF1, 0x47, 0x17, 0xA2, 0xEA, 0x06, 0x3A, + 0xDC, 0xF6, 0xB3, 0x83, 0x30, 0x9C, 0x12, 0xB1, 0x4C, 0xE9, + 0xBE, 0x40, 0x86, 0x3E, 0x72, 0x58, 0x4E, 0x44, 0xB8, 0x99, + 0x59, 0xC3, 0x58, 0x0F, 0xD7, 0xCF, 0x02, 0x60, 0x77, 0xAD, + 0x6F, 0x9C, 0x41, 0x58, 0xEF, 0x78, 0x63, 0xC0, 0xF7, 0x7D, + 0xA7, 0xED, 0x67, 0xC2, 0x49, 0xAE, 0x06, 0xFC, 0x46, 0xF7, + 0x70, 0x53, 0x88, 0xEB, 0x53, 0x2F, 0x25, 0x8D, 0x7A, 0xAC, + 0xAB, 0xC4, 0xB5, 0xB0, 0x27, 0x90, 0x57, 0xD0, 0x31, 0x79, + 0x2F, 0xAD, 0xDA, 0x20, 0xC1, 0x6A, 0x00, 0xCC, 0xD9, 0xB4, + 0x36, 0x5A, 0x90, 0x99, 0x3D, 0xE3, 0xE2, 0xF4, 0xB6, 0xE7, + 0x85, 0x16, 0x77, 0x3D, 0x69, 0xBB, 0x42, 0x6C, 0xA5, 0x83, + 0x45, 0x9F, 0x53, 0xC4, 0x43, 0x78, 0x17, 0x43, 0xBD, 0x27, + 0xC0, 0x6E, 0x4B, 0x40, 0x0F, 0x64, 0x0B, 0xAC, 0x38, 0x1E, + 0x09, 0x6D, 0x62, 0x5A, 0x54, 0x8A, 0x2C, 0x96, 0x99, 0x23, + 0xDB, 0xF5, 0x4B, 0x4A, 0xAA, 0x69, 0xBE, 0x6E, 0x8A, 0x9A, + 0x3E, 0xD5, 0xE6, 0xA3, 0xA9, 0xA9, 0xE9, 0xE8, 0xA9, 0x28, + 0x28, 0x3B, 0xF9, 0x9D, 0xD9, 0x5F, 0xE3, 0xCB, 0x2B, 0x2B, + 0x38, 0xBA, 0xF1, 0xBC, 0x45, 0xD8, 0x4A, 0x5A, 0xB1, 0xB3, + 0x8A, 0x48, 0x64, 0x78, 0x33, 0x21, 0x55, 0xCD, 0x04, 0x14, + 0xE7, 0x7B, 0x73, 0xC2, 0xB6, 0xF2, 0xDE, 0x81, 0x01, 0xD8, + 0x8D, 0xC6, 0xCF, 0xF2, 0x85, 0x0F, 0x32, 0x72, 0x0F, 0x6C, + 0x60, 0xBE, 0xF5, 0x31, 0x75, 0x39, 0x4B, 0xE3, 0xAE, 0xED, + 0x0C, 0x1E, 0x15, 0x83, 0xAC, 0xF9, 0x4C, 0x86, 0xCF, 0xDF, + 0x54, 0xB0, 0x7C, 0x6F, 0xF5, 0xDE, 0x26, 0x66, 0xC0, 0xBA, + 0x85, 0x38, 0xD0, 0x25, 0xFE, 0xB9, 0xBF, 0x12, 0x98 }; static const int sizeof_client_cert_der_3072 = sizeof(client_cert_der_3072); @@ -2901,241 +2904,244 @@ static const int sizeof_client_cert_der_3072 = sizeof(client_cert_der_3072); /* ./certs/4096/client-key.der, 4096-bit */ static const unsigned char client_key_der_4096[] = { - 0x30, 0x82, 0x09, 0x28, 0x02, 0x01, 0x00, 0x02, 0x82, 0x02, - 0x01, 0x00, 0xF5, 0xD0, 0x31, 0xE4, 0x71, 0x59, 0x58, 0xB3, - 0x07, 0x50, 0xDD, 0x16, 0x79, 0xFC, 0xC6, 0x95, 0x50, 0xFC, - 0x46, 0x0E, 0x57, 0x12, 0x86, 0x71, 0x8D, 0xE3, 0x9B, 0x4A, - 0x33, 0xEA, 0x4F, 0xD9, 0x17, 0x13, 0x6D, 0x48, 0x69, 0xDF, - 0x59, 0x11, 0x08, 0x02, 0x9D, 0xAF, 0x2B, 0xC7, 0x30, 0xBE, - 0x0C, 0xDC, 0x87, 0xD4, 0x5A, 0x12, 0x09, 0x23, 0x5D, 0xE1, - 0x76, 0x5A, 0x62, 0x37, 0x46, 0x74, 0xEF, 0x03, 0x05, 0xBB, - 0x1E, 0x6D, 0x29, 0x75, 0x6C, 0x2E, 0x9D, 0x87, 0x0D, 0x8F, - 0x87, 0xCB, 0x14, 0x95, 0x9B, 0xBE, 0x17, 0x6B, 0x51, 0xD1, - 0x4C, 0xDA, 0xD7, 0x91, 0x66, 0xC5, 0x36, 0xEB, 0xE0, 0x07, - 0x1A, 0x76, 0x4D, 0xB0, 0xFB, 0xC1, 0xF5, 0x5E, 0x05, 0xDB, - 0xBA, 0xCB, 0x25, 0xD9, 0x99, 0x13, 0x1C, 0xC0, 0x35, 0xDC, - 0x40, 0xE9, 0x36, 0xCD, 0xC4, 0xD5, 0x7A, 0x41, 0x70, 0x0F, - 0x36, 0xEB, 0xA5, 0x4E, 0x17, 0x05, 0xD5, 0x75, 0x1B, 0x64, - 0x62, 0x7A, 0x3F, 0x0D, 0x28, 0x48, 0x6A, 0xE3, 0xAC, 0x9C, - 0xA8, 0x8F, 0xE9, 0xED, 0xF7, 0xCD, 0x24, 0xA0, 0xB1, 0xA0, - 0x03, 0xAC, 0xE3, 0x03, 0xF5, 0x3F, 0xD1, 0x96, 0xFF, 0x2A, - 0x7E, 0x08, 0xB1, 0xD3, 0xE0, 0x18, 0x14, 0xEC, 0x65, 0x37, - 0x50, 0x43, 0xC2, 0x6A, 0x8C, 0xF4, 0x5B, 0xFE, 0xC4, 0xCB, - 0x8D, 0x3F, 0x81, 0x02, 0xF7, 0xC2, 0xDD, 0xE4, 0xC1, 0x8E, - 0x80, 0x0C, 0x04, 0x25, 0x2D, 0x80, 0x5A, 0x2E, 0x0F, 0x22, - 0x35, 0x4A, 0xF4, 0x85, 0xED, 0x51, 0xD8, 0xAB, 0x6D, 0x8F, - 0xA2, 0x3B, 0x24, 0x00, 0x6E, 0x81, 0xE2, 0x1E, 0x76, 0xD6, - 0xAC, 0x31, 0x12, 0xDB, 0xF3, 0x8E, 0x07, 0xA1, 0xDE, 0x89, - 0x4A, 0x39, 0x60, 0x77, 0xC5, 0xAA, 0xF1, 0x51, 0xE6, 0x06, - 0xF1, 0x95, 0x56, 0x2A, 0xE1, 0x8E, 0x92, 0x30, 0x9F, 0xFE, - 0x58, 0x44, 0xAC, 0x46, 0xF2, 0xFD, 0x9A, 0xFC, 0xA8, 0x1D, - 0xA1, 0xD3, 0x55, 0x37, 0x4A, 0x8B, 0xFC, 0x9C, 0x33, 0xF8, - 0xA7, 0x61, 0x48, 0x41, 0x7C, 0x9C, 0x77, 0x3F, 0xF5, 0x80, - 0x23, 0x7D, 0x43, 0xB4, 0xD5, 0x88, 0x0A, 0xC9, 0x75, 0xD7, - 0x44, 0x19, 0x4D, 0x77, 0x6C, 0x0B, 0x0A, 0x49, 0xAA, 0x1C, - 0x2F, 0xD6, 0x5A, 0x44, 0xA6, 0x47, 0x4D, 0xE5, 0x36, 0x96, - 0x40, 0x99, 0x2C, 0x56, 0x26, 0xB1, 0xF2, 0x92, 0x31, 0x59, - 0xD7, 0x2C, 0xD4, 0xB4, 0x21, 0xD6, 0x65, 0x13, 0x0B, 0x3E, - 0xFB, 0xFF, 0x04, 0xEB, 0xB9, 0x85, 0xB9, 0xD8, 0xD8, 0x28, - 0x4F, 0x5C, 0x17, 0x96, 0xA3, 0x51, 0xBE, 0xFE, 0x7D, 0x0B, - 0x1B, 0x48, 0x40, 0x25, 0x76, 0x94, 0xDC, 0x41, 0xFB, 0xBF, - 0x73, 0x76, 0xDA, 0xEB, 0xB3, 0x62, 0xE7, 0xC1, 0xC8, 0x54, - 0x6A, 0x93, 0xE1, 0x8D, 0x31, 0xE8, 0x3E, 0x3E, 0xDF, 0xBC, - 0x87, 0x02, 0x30, 0x22, 0x57, 0xC4, 0xE0, 0x18, 0x7A, 0xD3, - 0xAE, 0xE4, 0x02, 0x9B, 0xAA, 0xBD, 0x4E, 0x49, 0x47, 0x72, - 0xE9, 0x8D, 0x13, 0x2D, 0x54, 0x9B, 0x00, 0xA7, 0x91, 0x61, - 0x71, 0xC9, 0xCC, 0x48, 0x4F, 0xEE, 0xDF, 0x5E, 0x1B, 0x1A, - 0xDF, 0x67, 0xD3, 0x20, 0xE6, 0x44, 0x45, 0x98, 0x7E, 0xE7, - 0x0E, 0x63, 0x16, 0x83, 0xC9, 0x26, 0x5D, 0x90, 0xC1, 0xE5, - 0x2A, 0x5C, 0x45, 0x54, 0x13, 0xB2, 0x81, 0x18, 0x06, 0x20, - 0x2E, 0x2E, 0x66, 0x5A, 0xB5, 0x7B, 0x6E, 0xD6, 0x0C, 0x4E, - 0x89, 0x01, 0x56, 0x70, 0xBB, 0xAE, 0xDE, 0xE9, 0x99, 0x5E, - 0xD1, 0xB9, 0x3A, 0xB7, 0x6C, 0x17, 0xB6, 0x03, 0xA9, 0x08, - 0xDD, 0x9C, 0xF4, 0x14, 0xC9, 0xC9, 0x59, 0x39, 0x72, 0xD4, - 0x7E, 0x02, 0x37, 0x31, 0xCD, 0x0E, 0xA7, 0x3D, 0xF8, 0xF2, - 0xCF, 0x6B, 0x15, 0xAB, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, - 0x82, 0x02, 0x01, 0x00, 0xC5, 0x76, 0x57, 0x7D, 0xF1, 0x68, - 0x1A, 0x8E, 0xC6, 0x63, 0xB9, 0x16, 0xA3, 0x2B, 0xE1, 0xC2, - 0x74, 0xEA, 0x12, 0xC4, 0xD6, 0x41, 0x75, 0x6A, 0xA6, 0xD6, - 0x9E, 0x1A, 0x7F, 0x95, 0xCC, 0x4A, 0xD1, 0xF4, 0xB3, 0x27, - 0x26, 0x95, 0x5A, 0x91, 0x09, 0xE4, 0x40, 0x13, 0x45, 0x91, - 0x9F, 0xA0, 0x2B, 0xE8, 0xC3, 0xDC, 0x5B, 0xF6, 0x7D, 0x0C, - 0xC2, 0x0F, 0xA9, 0xE9, 0x75, 0x58, 0x7D, 0xEA, 0xD5, 0x4D, - 0x92, 0x3E, 0xFC, 0x74, 0x28, 0x87, 0xC1, 0x3D, 0xB9, 0x21, - 0x92, 0x4D, 0x28, 0x82, 0x84, 0xA8, 0xA2, 0x11, 0x93, 0xF2, - 0x8C, 0x29, 0x1C, 0x19, 0xF8, 0x6D, 0x3F, 0x27, 0x51, 0xB5, - 0x2D, 0xA3, 0xC7, 0x28, 0x1D, 0xC4, 0xFC, 0x98, 0x94, 0xA8, - 0xD0, 0xFF, 0xF0, 0x0F, 0xDC, 0xF9, 0xED, 0xB3, 0xA2, 0xB6, - 0xED, 0x0D, 0x5F, 0xBF, 0x78, 0x5C, 0xD7, 0xAF, 0xBD, 0xA3, - 0xEF, 0x86, 0xE9, 0x51, 0x66, 0xDB, 0x52, 0x37, 0x47, 0x7F, - 0xE9, 0x5F, 0x3C, 0x94, 0x83, 0x2D, 0xE8, 0x9C, 0x33, 0xF1, - 0x6C, 0xE9, 0xF3, 0xA6, 0x97, 0xFE, 0xA7, 0xBF, 0x4D, 0x9B, - 0x20, 0xD5, 0x2F, 0xDE, 0xA4, 0x06, 0xBB, 0xEE, 0x66, 0x49, - 0x6B, 0xF5, 0x10, 0x85, 0x9F, 0x84, 0x5A, 0x52, 0x3E, 0x0C, - 0xA0, 0x4A, 0x4C, 0xDA, 0x01, 0xC5, 0x62, 0x31, 0xB1, 0xEC, - 0xF8, 0xDD, 0xA3, 0x3B, 0xCE, 0x41, 0x3A, 0x12, 0x79, 0xF9, - 0x97, 0x5B, 0x07, 0x95, 0x9F, 0x86, 0xD6, 0x04, 0x73, 0x6C, - 0xE8, 0x8F, 0x4C, 0x4C, 0x48, 0x1D, 0x85, 0xC4, 0xE7, 0xCE, - 0xDE, 0x16, 0x31, 0xF6, 0x5C, 0x37, 0x54, 0x8E, 0x55, 0xBC, - 0xAF, 0x2E, 0x47, 0xE8, 0xAC, 0x03, 0xB0, 0xA4, 0xF9, 0x90, - 0x98, 0x99, 0xA4, 0xDC, 0x6E, 0x98, 0x08, 0x5C, 0x07, 0xBB, - 0x08, 0x93, 0xAF, 0x61, 0x8D, 0x74, 0xA8, 0xF8, 0xC4, 0x89, - 0x64, 0x10, 0xE1, 0xE6, 0xC0, 0xCD, 0x1D, 0x39, 0x20, 0xD6, - 0x5A, 0x89, 0x83, 0xFC, 0x37, 0xE2, 0x12, 0x66, 0xA8, 0x12, - 0xCC, 0x72, 0xBB, 0x1E, 0xFB, 0x6A, 0xE3, 0x7C, 0x71, 0x7E, - 0xB9, 0x2E, 0x8E, 0x84, 0x66, 0xE1, 0xB9, 0xD0, 0x25, 0x9A, - 0x6F, 0x9D, 0x19, 0xE6, 0x7E, 0xE8, 0xD8, 0xF0, 0xC5, 0x23, - 0x16, 0x9A, 0x68, 0x2C, 0x1D, 0x55, 0xAE, 0x8E, 0x90, 0xEE, - 0x8E, 0xEC, 0x5E, 0x46, 0x9D, 0x60, 0x52, 0x32, 0x17, 0x28, - 0x59, 0xC4, 0x49, 0x2A, 0x20, 0x3E, 0x95, 0xC5, 0xDF, 0xF6, - 0x3D, 0xF7, 0xC5, 0xCF, 0xB1, 0xC2, 0xC9, 0x76, 0xF8, 0x3D, - 0xBE, 0xF4, 0x63, 0xFC, 0x2A, 0x00, 0x6F, 0x99, 0xA6, 0xB6, - 0xAD, 0x35, 0xEE, 0xDE, 0xC5, 0xE0, 0x97, 0xC6, 0x73, 0xEE, - 0x33, 0xA0, 0xA8, 0xFC, 0x4C, 0x8F, 0xF2, 0x8C, 0x61, 0xFB, - 0x03, 0x19, 0xA1, 0xE8, 0x17, 0x4E, 0xE3, 0x21, 0x58, 0xCE, - 0xFE, 0xF2, 0x5F, 0xBB, 0xDD, 0x4F, 0xF7, 0x18, 0xCB, 0x35, - 0x57, 0xDD, 0xE5, 0x50, 0x2A, 0x7B, 0x1A, 0xE9, 0x12, 0xF2, - 0x7A, 0x11, 0xB1, 0x43, 0xB9, 0x70, 0x07, 0x0C, 0x8F, 0x69, - 0xB9, 0xE5, 0xA5, 0xC9, 0xE2, 0x1B, 0x96, 0x74, 0x11, 0xF5, - 0x95, 0xB9, 0x58, 0xC0, 0xBD, 0x37, 0xFB, 0x28, 0x2A, 0xBD, - 0x84, 0xB1, 0x2B, 0x67, 0x42, 0x82, 0xC3, 0x95, 0x55, 0x45, - 0xD5, 0xEA, 0xC3, 0x8A, 0x42, 0x3A, 0x43, 0x17, 0x5E, 0xCD, - 0xD2, 0xEA, 0xFC, 0xDF, 0x67, 0xEC, 0xE1, 0x6C, 0xA8, 0x03, - 0x19, 0xB2, 0x1D, 0x4A, 0x5F, 0x4F, 0xE7, 0xD3, 0xE0, 0x86, - 0xC5, 0x1A, 0x10, 0xC3, 0x08, 0xD2, 0xED, 0x85, 0x93, 0x08, - 0x51, 0x05, 0xA6, 0x37, 0x15, 0x32, 0xBD, 0x6C, 0x73, 0x63, - 0x01, 0x5D, 0x5B, 0x4F, 0x6A, 0xDC, 0x6D, 0x1D, 0x55, 0x91, - 0x21, 0xE4, 0x8E, 0xB7, 0xF0, 0x81, 0x02, 0x82, 0x01, 0x01, - 0x00, 0xFD, 0x27, 0xC8, 0xFE, 0x76, 0x5C, 0x89, 0x32, 0xCB, - 0x8A, 0x22, 0x87, 0x61, 0x48, 0x91, 0x4A, 0x05, 0xAD, 0xA4, - 0x5C, 0x8A, 0xCA, 0x5C, 0x02, 0x88, 0x7E, 0x51, 0xC5, 0x66, - 0x90, 0x2C, 0xA3, 0xED, 0xA7, 0x43, 0x19, 0x0B, 0xA2, 0x42, - 0xB4, 0xE0, 0xE0, 0x45, 0xBF, 0xFE, 0xA0, 0xF2, 0x75, 0x0B, - 0x8E, 0x7D, 0x9D, 0x73, 0x67, 0xD3, 0x10, 0x09, 0xC5, 0xD9, - 0x8C, 0xAD, 0x3A, 0x64, 0x72, 0xAD, 0x96, 0x35, 0x91, 0x0F, - 0x4B, 0xC9, 0xBD, 0x4F, 0x65, 0x47, 0xA6, 0x2D, 0xEB, 0x3F, - 0xE2, 0x99, 0x72, 0x66, 0x12, 0xED, 0xEB, 0xD2, 0x7C, 0xFF, - 0x3A, 0x20, 0x37, 0x2A, 0xD3, 0x65, 0x51, 0x9B, 0xC3, 0xAA, - 0x18, 0xB1, 0x1F, 0x6E, 0x9D, 0x40, 0x47, 0xA4, 0x1F, 0x82, - 0x9B, 0xDB, 0x50, 0x6B, 0x86, 0x2F, 0xFB, 0x3F, 0x31, 0xB9, - 0x81, 0x11, 0x04, 0x14, 0x63, 0x86, 0x4F, 0x40, 0x2A, 0xF5, - 0xF9, 0x7C, 0xA1, 0x78, 0x19, 0x13, 0xD0, 0x51, 0x51, 0x0F, - 0x79, 0x88, 0x8D, 0x14, 0xA3, 0xDE, 0xB6, 0x33, 0x29, 0x42, - 0xB9, 0xE8, 0x59, 0x76, 0xF7, 0x43, 0x1A, 0xB6, 0xA6, 0xDF, - 0x0A, 0xC1, 0x42, 0xC7, 0x3F, 0x1C, 0x7E, 0x5C, 0x2C, 0x91, - 0x4B, 0x1E, 0xF8, 0x46, 0x91, 0x1F, 0xEE, 0x56, 0xB3, 0x0E, - 0xC8, 0xD0, 0x31, 0xD3, 0x3D, 0xED, 0x3D, 0xD9, 0xC5, 0x30, - 0x0C, 0x58, 0xD8, 0xB7, 0xB5, 0xEC, 0x14, 0xAC, 0x41, 0x64, - 0x6D, 0xE4, 0xC6, 0x59, 0xFD, 0x14, 0x05, 0x60, 0x65, 0xD8, - 0xC4, 0x84, 0x44, 0x7E, 0x1B, 0xB4, 0xA4, 0x16, 0x75, 0xC1, - 0x27, 0x96, 0xB2, 0x19, 0xD6, 0x39, 0x54, 0xC0, 0x93, 0xF3, - 0xD7, 0x1F, 0xCD, 0x1B, 0xDF, 0xF8, 0x12, 0x88, 0x14, 0x9F, - 0x98, 0x05, 0x47, 0x46, 0x71, 0x81, 0x6C, 0xDF, 0x91, 0xEF, - 0x53, 0xE3, 0xC5, 0xB1, 0x89, 0x2F, 0xE1, 0x02, 0x82, 0x01, - 0x01, 0x00, 0xF8, 0x93, 0x4A, 0x28, 0x77, 0x94, 0xEF, 0xE9, - 0xC4, 0x0A, 0xC3, 0xE8, 0x52, 0x59, 0xB6, 0x1D, 0x8D, 0xCE, - 0x14, 0xE7, 0x43, 0xC6, 0xED, 0x09, 0x27, 0x5D, 0xF3, 0x8E, - 0x08, 0x6A, 0x19, 0x6B, 0x2C, 0x97, 0x9B, 0x88, 0x53, 0x2B, - 0xDA, 0xFE, 0x4B, 0x94, 0x66, 0x84, 0xD5, 0xA9, 0xCE, 0xA5, - 0x43, 0x70, 0xFB, 0x01, 0x5A, 0x6F, 0xCD, 0xF7, 0xD1, 0x9D, - 0x51, 0xEE, 0xA0, 0xDC, 0x46, 0xF5, 0x7D, 0xA7, 0xEE, 0xA0, - 0x86, 0xB7, 0x83, 0xFF, 0x21, 0x8B, 0x76, 0x05, 0x7D, 0xDE, - 0xC4, 0x26, 0x36, 0xBC, 0xB4, 0x8A, 0x48, 0xC3, 0x06, 0x90, - 0x97, 0xE5, 0xA6, 0x38, 0xC3, 0xE6, 0x7C, 0xD0, 0xF8, 0x23, - 0xD2, 0x33, 0x1F, 0x81, 0xC3, 0xE3, 0x7D, 0x85, 0x5A, 0x38, - 0x10, 0x03, 0xE6, 0x88, 0xDB, 0xC8, 0x4C, 0xD0, 0xF7, 0xB2, - 0x4D, 0x27, 0x33, 0x85, 0xCD, 0x3A, 0x74, 0x83, 0x6B, 0x82, - 0x58, 0xD9, 0xDF, 0xEE, 0xF5, 0xD3, 0xE9, 0xFE, 0x1C, 0xEF, - 0x06, 0x12, 0x16, 0xD1, 0x4C, 0xAE, 0x54, 0x4B, 0x0D, 0x1A, - 0xBD, 0xE2, 0xCF, 0x56, 0xB3, 0x74, 0xBE, 0x44, 0x4F, 0xA4, - 0x73, 0x0A, 0x98, 0x8D, 0x61, 0x84, 0x38, 0x46, 0xDC, 0x95, - 0xCF, 0x3F, 0x6B, 0xE7, 0x65, 0x87, 0x02, 0xBF, 0x4B, 0x57, - 0xE2, 0x3D, 0xC4, 0x2B, 0x1C, 0x82, 0x1D, 0xCC, 0x13, 0x7F, - 0xC0, 0x06, 0x12, 0x8C, 0x6F, 0x97, 0x50, 0x7B, 0x8C, 0x81, - 0xC3, 0x23, 0x15, 0xEB, 0x70, 0x07, 0x8E, 0xA1, 0x07, 0x1E, - 0x59, 0xFA, 0x10, 0xCA, 0x7E, 0x0F, 0xE2, 0xBB, 0xEE, 0x86, - 0x26, 0x1E, 0x55, 0xB9, 0x98, 0x66, 0x85, 0xEC, 0x27, 0xC5, - 0xD9, 0x63, 0x8D, 0x51, 0x77, 0xAA, 0xA0, 0x36, 0x55, 0x33, - 0x10, 0x21, 0x5E, 0xEC, 0x47, 0x67, 0x71, 0xD1, 0xAF, 0xFC, - 0x3E, 0x50, 0xF5, 0xBE, 0xD6, 0x92, 0xE7, 0x0B, 0x02, 0x82, - 0x01, 0x00, 0x21, 0x7C, 0x8A, 0xC4, 0xC6, 0x29, 0x55, 0x68, - 0xA7, 0xAD, 0xDD, 0x05, 0x65, 0x63, 0xF0, 0xFC, 0x06, 0xA6, - 0x42, 0x70, 0x8F, 0x57, 0x57, 0x36, 0x6A, 0x91, 0xB3, 0x05, - 0x56, 0x9C, 0xC9, 0x9A, 0xE1, 0x8B, 0xD7, 0x7F, 0x4F, 0x9F, - 0xA6, 0x0D, 0x41, 0x15, 0xC9, 0x84, 0x2D, 0x0D, 0x63, 0x25, - 0x02, 0x63, 0x55, 0xD0, 0x66, 0xFC, 0x9B, 0xD9, 0xAA, 0x41, - 0x46, 0x96, 0xAA, 0x2F, 0x68, 0x2C, 0x17, 0x34, 0x20, 0x5F, - 0xD0, 0xD3, 0x28, 0x9B, 0x67, 0x0E, 0x31, 0x9D, 0x14, 0xC3, - 0xE2, 0x8E, 0x79, 0xD7, 0xBD, 0x12, 0xD1, 0xEF, 0xF8, 0xC6, - 0xDA, 0x07, 0xF9, 0x4C, 0xF2, 0xD8, 0x45, 0xB5, 0xB6, 0xD1, - 0xFA, 0x05, 0x0C, 0x20, 0xE9, 0x43, 0xD9, 0xC5, 0xE0, 0x3A, - 0xDE, 0xCE, 0xF9, 0x02, 0xB9, 0x46, 0x65, 0xC0, 0x69, 0x4A, - 0x8D, 0x8C, 0x3A, 0x10, 0xFD, 0x15, 0x71, 0x25, 0xB8, 0x8A, - 0x36, 0x41, 0x4B, 0x30, 0x1C, 0xAF, 0xCC, 0x84, 0x28, 0xCD, - 0x7D, 0x2B, 0x89, 0x59, 0x88, 0x1A, 0x69, 0x12, 0x56, 0xD0, - 0x25, 0x68, 0x6C, 0x08, 0xB1, 0x88, 0xE1, 0x92, 0x7E, 0x08, - 0xB2, 0xC6, 0x3C, 0x6C, 0x35, 0xE8, 0xEE, 0x3E, 0xF4, 0xB8, - 0x5C, 0x7B, 0xC0, 0x5B, 0xFD, 0x11, 0xA3, 0x54, 0xA6, 0x99, - 0x46, 0xE2, 0x5F, 0x4F, 0xC7, 0xEE, 0x90, 0x1C, 0x37, 0x5B, - 0x33, 0x10, 0xDF, 0x0B, 0xC3, 0xB9, 0x47, 0xC2, 0x30, 0x4A, - 0xF2, 0x1A, 0xEB, 0x41, 0x25, 0x94, 0x29, 0x7A, 0xD0, 0x96, - 0x88, 0x46, 0xEE, 0x6C, 0x14, 0xF6, 0x5B, 0x3D, 0xBD, 0x4E, - 0xD4, 0x3F, 0x05, 0x5B, 0x07, 0xB9, 0xE3, 0x99, 0x87, 0x63, - 0xCA, 0xC4, 0x71, 0x0B, 0x73, 0x9D, 0x7B, 0xB6, 0x0F, 0xD4, - 0x12, 0x8C, 0x4C, 0x5E, 0x72, 0x3D, 0xFF, 0x6D, 0xC4, 0x61, - 0x0C, 0x74, 0x5F, 0x53, 0xBE, 0x39, 0x34, 0x61, 0x02, 0x82, - 0x01, 0x00, 0x5F, 0xF2, 0xF2, 0xB0, 0x16, 0x20, 0x8E, 0x4E, - 0xCC, 0x96, 0x5F, 0x32, 0x80, 0xFF, 0x11, 0xF5, 0xEC, 0x73, - 0xBC, 0xCB, 0xDB, 0xF4, 0xA0, 0x30, 0x65, 0x5A, 0xB5, 0x95, - 0x80, 0x97, 0xFB, 0xC1, 0xCB, 0xCF, 0xA5, 0x80, 0x84, 0xA2, - 0x2C, 0x00, 0xF6, 0x89, 0x8C, 0xDC, 0xFF, 0x60, 0x71, 0x5C, - 0x87, 0x60, 0xC7, 0xF2, 0xA8, 0xC6, 0xF9, 0x59, 0x0C, 0x37, - 0x4E, 0x95, 0xEE, 0xCF, 0xB8, 0x30, 0x30, 0x55, 0xAF, 0x1D, - 0x95, 0x82, 0xA6, 0xD7, 0xC7, 0x49, 0xFE, 0xBF, 0x75, 0xEB, - 0x94, 0x09, 0x30, 0x1D, 0xBD, 0x0E, 0x97, 0xB1, 0x78, 0x0A, - 0x3E, 0x27, 0xAD, 0xF6, 0xC1, 0x5F, 0x69, 0x94, 0x7C, 0x03, - 0xCF, 0xB2, 0x5E, 0x1A, 0x07, 0xD3, 0xFA, 0xF2, 0x8B, 0x75, - 0x92, 0x70, 0xFE, 0xFE, 0x9A, 0xDF, 0x81, 0x0F, 0x34, 0x5D, - 0x45, 0xBC, 0xB8, 0xFD, 0x8F, 0xCF, 0x5D, 0x84, 0x10, 0xEE, - 0x9A, 0x7F, 0x57, 0x19, 0xF5, 0x17, 0xDC, 0x7D, 0x73, 0x0B, - 0xAC, 0x6B, 0x35, 0x15, 0x8B, 0x24, 0xCB, 0x72, 0xC0, 0xD7, - 0x2E, 0xAE, 0xAA, 0xDB, 0xCB, 0x9F, 0x67, 0x86, 0x14, 0xBB, - 0xE4, 0x90, 0x15, 0x7C, 0x95, 0x44, 0xA5, 0x38, 0x6D, 0x13, - 0x02, 0x91, 0x77, 0x84, 0x35, 0x43, 0x5D, 0x03, 0x1C, 0x01, - 0x0B, 0x5A, 0x4E, 0x2B, 0x59, 0xF0, 0xBB, 0xB1, 0xB7, 0x61, - 0x1B, 0x6C, 0xFC, 0xA1, 0xEA, 0xBD, 0x1C, 0x9A, 0xE4, 0x0C, - 0x7E, 0x97, 0x3F, 0x71, 0xC6, 0xA7, 0x94, 0x1D, 0x82, 0x12, - 0xEC, 0x26, 0x43, 0x6E, 0xF6, 0x24, 0x09, 0xA0, 0x03, 0x1D, - 0x12, 0xFF, 0xA8, 0x95, 0x60, 0x47, 0x4A, 0xB0, 0x72, 0x55, - 0xC3, 0x68, 0xD2, 0xF6, 0xBC, 0x5B, 0x47, 0x46, 0x51, 0xB2, - 0xC9, 0x2A, 0x28, 0x6A, 0xC9, 0xD1, 0x1B, 0x35, 0x16, 0x5A, - 0x26, 0x6F, 0xB7, 0xBB, 0xF7, 0x35, 0x73, 0x2B, 0x02, 0x82, - 0x01, 0x00, 0x56, 0xBA, 0xD8, 0x02, 0xD7, 0x4B, 0x30, 0x5E, - 0x1B, 0x1E, 0x2F, 0xF3, 0x0D, 0xBC, 0xF1, 0x05, 0x6A, 0x68, - 0x4A, 0xE1, 0xEA, 0xB3, 0xDE, 0x61, 0x8C, 0x89, 0x44, 0xBA, - 0x63, 0x5E, 0xDF, 0x05, 0x24, 0x32, 0x71, 0x65, 0x1A, 0x36, - 0x2F, 0xBC, 0x07, 0x75, 0xA3, 0xCE, 0x9E, 0x52, 0x92, 0x95, - 0x4D, 0x3F, 0xC9, 0x06, 0xBC, 0xA1, 0x14, 0x33, 0x37, 0x95, - 0xAB, 0x9A, 0xEB, 0x04, 0xF6, 0x15, 0xC3, 0x9B, 0x10, 0x56, - 0x53, 0xA2, 0x28, 0xF2, 0x68, 0xDA, 0x7D, 0x97, 0x52, 0x63, - 0xAC, 0x9B, 0x56, 0xA9, 0xAB, 0x2E, 0x1E, 0x9E, 0x01, 0x70, - 0xFF, 0x2B, 0x6D, 0x0C, 0x4B, 0xA6, 0xC3, 0x3A, 0xB3, 0xD1, - 0xA7, 0x4B, 0x5E, 0x49, 0x2E, 0x95, 0xD6, 0x6A, 0xAE, 0x58, - 0x13, 0x66, 0x8F, 0x2F, 0x93, 0xE4, 0x6E, 0x8B, 0xFA, 0x94, - 0x30, 0x3E, 0xEC, 0x96, 0xAB, 0x46, 0x20, 0x3E, 0xC5, 0x30, - 0xB4, 0xEB, 0x41, 0x00, 0x39, 0x60, 0x1D, 0xE1, 0x20, 0xCE, - 0x31, 0x70, 0x17, 0x39, 0xCB, 0x76, 0x56, 0x6C, 0x55, 0x7B, - 0x90, 0x20, 0xBC, 0x39, 0xB2, 0x5B, 0xD1, 0x28, 0x6F, 0x0C, - 0x4F, 0x45, 0x6B, 0x82, 0xC4, 0x57, 0x23, 0x0C, 0x3F, 0x3F, - 0x2D, 0x83, 0xB3, 0x3D, 0x8E, 0xF9, 0x1A, 0xDA, 0x77, 0x54, - 0x2E, 0xFE, 0x16, 0x2E, 0xBA, 0x99, 0xDD, 0xCA, 0xB3, 0xD1, - 0xD8, 0xBB, 0x87, 0xE1, 0xD0, 0xA9, 0xD4, 0xE6, 0x8F, 0xE8, - 0x00, 0x3E, 0x49, 0x8A, 0xDD, 0xA6, 0x32, 0x91, 0x00, 0x31, - 0x31, 0x21, 0x98, 0x18, 0x94, 0xC9, 0x2D, 0x27, 0x05, 0xB7, - 0x9B, 0x09, 0x2E, 0xBB, 0x5D, 0xBF, 0x67, 0xE8, 0x0E, 0xD1, - 0x44, 0x75, 0x80, 0x1D, 0x0A, 0x21, 0x8F, 0x95, 0x76, 0xB0, - 0xFC, 0x19, 0x3C, 0xFF, 0x92, 0xEA, 0x01, 0x45, 0x89, 0xD1, - 0x4E, 0xFE, 0x4D, 0x2B, 0x4B, 0x18, 0xE6, 0xCE + 0x30, 0x82, 0x09, 0x42, 0x02, 0x01, 0x00, 0x30, 0x0D, 0x06, + 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x04, 0x82, 0x09, 0x2C, 0x30, 0x82, 0x09, 0x28, + 0x02, 0x01, 0x00, 0x02, 0x82, 0x02, 0x01, 0x00, 0xF5, 0xD0, + 0x31, 0xE4, 0x71, 0x59, 0x58, 0xB3, 0x07, 0x50, 0xDD, 0x16, + 0x79, 0xFC, 0xC6, 0x95, 0x50, 0xFC, 0x46, 0x0E, 0x57, 0x12, + 0x86, 0x71, 0x8D, 0xE3, 0x9B, 0x4A, 0x33, 0xEA, 0x4F, 0xD9, + 0x17, 0x13, 0x6D, 0x48, 0x69, 0xDF, 0x59, 0x11, 0x08, 0x02, + 0x9D, 0xAF, 0x2B, 0xC7, 0x30, 0xBE, 0x0C, 0xDC, 0x87, 0xD4, + 0x5A, 0x12, 0x09, 0x23, 0x5D, 0xE1, 0x76, 0x5A, 0x62, 0x37, + 0x46, 0x74, 0xEF, 0x03, 0x05, 0xBB, 0x1E, 0x6D, 0x29, 0x75, + 0x6C, 0x2E, 0x9D, 0x87, 0x0D, 0x8F, 0x87, 0xCB, 0x14, 0x95, + 0x9B, 0xBE, 0x17, 0x6B, 0x51, 0xD1, 0x4C, 0xDA, 0xD7, 0x91, + 0x66, 0xC5, 0x36, 0xEB, 0xE0, 0x07, 0x1A, 0x76, 0x4D, 0xB0, + 0xFB, 0xC1, 0xF5, 0x5E, 0x05, 0xDB, 0xBA, 0xCB, 0x25, 0xD9, + 0x99, 0x13, 0x1C, 0xC0, 0x35, 0xDC, 0x40, 0xE9, 0x36, 0xCD, + 0xC4, 0xD5, 0x7A, 0x41, 0x70, 0x0F, 0x36, 0xEB, 0xA5, 0x4E, + 0x17, 0x05, 0xD5, 0x75, 0x1B, 0x64, 0x62, 0x7A, 0x3F, 0x0D, + 0x28, 0x48, 0x6A, 0xE3, 0xAC, 0x9C, 0xA8, 0x8F, 0xE9, 0xED, + 0xF7, 0xCD, 0x24, 0xA0, 0xB1, 0xA0, 0x03, 0xAC, 0xE3, 0x03, + 0xF5, 0x3F, 0xD1, 0x96, 0xFF, 0x2A, 0x7E, 0x08, 0xB1, 0xD3, + 0xE0, 0x18, 0x14, 0xEC, 0x65, 0x37, 0x50, 0x43, 0xC2, 0x6A, + 0x8C, 0xF4, 0x5B, 0xFE, 0xC4, 0xCB, 0x8D, 0x3F, 0x81, 0x02, + 0xF7, 0xC2, 0xDD, 0xE4, 0xC1, 0x8E, 0x80, 0x0C, 0x04, 0x25, + 0x2D, 0x80, 0x5A, 0x2E, 0x0F, 0x22, 0x35, 0x4A, 0xF4, 0x85, + 0xED, 0x51, 0xD8, 0xAB, 0x6D, 0x8F, 0xA2, 0x3B, 0x24, 0x00, + 0x6E, 0x81, 0xE2, 0x1E, 0x76, 0xD6, 0xAC, 0x31, 0x12, 0xDB, + 0xF3, 0x8E, 0x07, 0xA1, 0xDE, 0x89, 0x4A, 0x39, 0x60, 0x77, + 0xC5, 0xAA, 0xF1, 0x51, 0xE6, 0x06, 0xF1, 0x95, 0x56, 0x2A, + 0xE1, 0x8E, 0x92, 0x30, 0x9F, 0xFE, 0x58, 0x44, 0xAC, 0x46, + 0xF2, 0xFD, 0x9A, 0xFC, 0xA8, 0x1D, 0xA1, 0xD3, 0x55, 0x37, + 0x4A, 0x8B, 0xFC, 0x9C, 0x33, 0xF8, 0xA7, 0x61, 0x48, 0x41, + 0x7C, 0x9C, 0x77, 0x3F, 0xF5, 0x80, 0x23, 0x7D, 0x43, 0xB4, + 0xD5, 0x88, 0x0A, 0xC9, 0x75, 0xD7, 0x44, 0x19, 0x4D, 0x77, + 0x6C, 0x0B, 0x0A, 0x49, 0xAA, 0x1C, 0x2F, 0xD6, 0x5A, 0x44, + 0xA6, 0x47, 0x4D, 0xE5, 0x36, 0x96, 0x40, 0x99, 0x2C, 0x56, + 0x26, 0xB1, 0xF2, 0x92, 0x31, 0x59, 0xD7, 0x2C, 0xD4, 0xB4, + 0x21, 0xD6, 0x65, 0x13, 0x0B, 0x3E, 0xFB, 0xFF, 0x04, 0xEB, + 0xB9, 0x85, 0xB9, 0xD8, 0xD8, 0x28, 0x4F, 0x5C, 0x17, 0x96, + 0xA3, 0x51, 0xBE, 0xFE, 0x7D, 0x0B, 0x1B, 0x48, 0x40, 0x25, + 0x76, 0x94, 0xDC, 0x41, 0xFB, 0xBF, 0x73, 0x76, 0xDA, 0xEB, + 0xB3, 0x62, 0xE7, 0xC1, 0xC8, 0x54, 0x6A, 0x93, 0xE1, 0x8D, + 0x31, 0xE8, 0x3E, 0x3E, 0xDF, 0xBC, 0x87, 0x02, 0x30, 0x22, + 0x57, 0xC4, 0xE0, 0x18, 0x7A, 0xD3, 0xAE, 0xE4, 0x02, 0x9B, + 0xAA, 0xBD, 0x4E, 0x49, 0x47, 0x72, 0xE9, 0x8D, 0x13, 0x2D, + 0x54, 0x9B, 0x00, 0xA7, 0x91, 0x61, 0x71, 0xC9, 0xCC, 0x48, + 0x4F, 0xEE, 0xDF, 0x5E, 0x1B, 0x1A, 0xDF, 0x67, 0xD3, 0x20, + 0xE6, 0x44, 0x45, 0x98, 0x7E, 0xE7, 0x0E, 0x63, 0x16, 0x83, + 0xC9, 0x26, 0x5D, 0x90, 0xC1, 0xE5, 0x2A, 0x5C, 0x45, 0x54, + 0x13, 0xB2, 0x81, 0x18, 0x06, 0x20, 0x2E, 0x2E, 0x66, 0x5A, + 0xB5, 0x7B, 0x6E, 0xD6, 0x0C, 0x4E, 0x89, 0x01, 0x56, 0x70, + 0xBB, 0xAE, 0xDE, 0xE9, 0x99, 0x5E, 0xD1, 0xB9, 0x3A, 0xB7, + 0x6C, 0x17, 0xB6, 0x03, 0xA9, 0x08, 0xDD, 0x9C, 0xF4, 0x14, + 0xC9, 0xC9, 0x59, 0x39, 0x72, 0xD4, 0x7E, 0x02, 0x37, 0x31, + 0xCD, 0x0E, 0xA7, 0x3D, 0xF8, 0xF2, 0xCF, 0x6B, 0x15, 0xAB, + 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x02, 0x01, 0x00, + 0xC5, 0x76, 0x57, 0x7D, 0xF1, 0x68, 0x1A, 0x8E, 0xC6, 0x63, + 0xB9, 0x16, 0xA3, 0x2B, 0xE1, 0xC2, 0x74, 0xEA, 0x12, 0xC4, + 0xD6, 0x41, 0x75, 0x6A, 0xA6, 0xD6, 0x9E, 0x1A, 0x7F, 0x95, + 0xCC, 0x4A, 0xD1, 0xF4, 0xB3, 0x27, 0x26, 0x95, 0x5A, 0x91, + 0x09, 0xE4, 0x40, 0x13, 0x45, 0x91, 0x9F, 0xA0, 0x2B, 0xE8, + 0xC3, 0xDC, 0x5B, 0xF6, 0x7D, 0x0C, 0xC2, 0x0F, 0xA9, 0xE9, + 0x75, 0x58, 0x7D, 0xEA, 0xD5, 0x4D, 0x92, 0x3E, 0xFC, 0x74, + 0x28, 0x87, 0xC1, 0x3D, 0xB9, 0x21, 0x92, 0x4D, 0x28, 0x82, + 0x84, 0xA8, 0xA2, 0x11, 0x93, 0xF2, 0x8C, 0x29, 0x1C, 0x19, + 0xF8, 0x6D, 0x3F, 0x27, 0x51, 0xB5, 0x2D, 0xA3, 0xC7, 0x28, + 0x1D, 0xC4, 0xFC, 0x98, 0x94, 0xA8, 0xD0, 0xFF, 0xF0, 0x0F, + 0xDC, 0xF9, 0xED, 0xB3, 0xA2, 0xB6, 0xED, 0x0D, 0x5F, 0xBF, + 0x78, 0x5C, 0xD7, 0xAF, 0xBD, 0xA3, 0xEF, 0x86, 0xE9, 0x51, + 0x66, 0xDB, 0x52, 0x37, 0x47, 0x7F, 0xE9, 0x5F, 0x3C, 0x94, + 0x83, 0x2D, 0xE8, 0x9C, 0x33, 0xF1, 0x6C, 0xE9, 0xF3, 0xA6, + 0x97, 0xFE, 0xA7, 0xBF, 0x4D, 0x9B, 0x20, 0xD5, 0x2F, 0xDE, + 0xA4, 0x06, 0xBB, 0xEE, 0x66, 0x49, 0x6B, 0xF5, 0x10, 0x85, + 0x9F, 0x84, 0x5A, 0x52, 0x3E, 0x0C, 0xA0, 0x4A, 0x4C, 0xDA, + 0x01, 0xC5, 0x62, 0x31, 0xB1, 0xEC, 0xF8, 0xDD, 0xA3, 0x3B, + 0xCE, 0x41, 0x3A, 0x12, 0x79, 0xF9, 0x97, 0x5B, 0x07, 0x95, + 0x9F, 0x86, 0xD6, 0x04, 0x73, 0x6C, 0xE8, 0x8F, 0x4C, 0x4C, + 0x48, 0x1D, 0x85, 0xC4, 0xE7, 0xCE, 0xDE, 0x16, 0x31, 0xF6, + 0x5C, 0x37, 0x54, 0x8E, 0x55, 0xBC, 0xAF, 0x2E, 0x47, 0xE8, + 0xAC, 0x03, 0xB0, 0xA4, 0xF9, 0x90, 0x98, 0x99, 0xA4, 0xDC, + 0x6E, 0x98, 0x08, 0x5C, 0x07, 0xBB, 0x08, 0x93, 0xAF, 0x61, + 0x8D, 0x74, 0xA8, 0xF8, 0xC4, 0x89, 0x64, 0x10, 0xE1, 0xE6, + 0xC0, 0xCD, 0x1D, 0x39, 0x20, 0xD6, 0x5A, 0x89, 0x83, 0xFC, + 0x37, 0xE2, 0x12, 0x66, 0xA8, 0x12, 0xCC, 0x72, 0xBB, 0x1E, + 0xFB, 0x6A, 0xE3, 0x7C, 0x71, 0x7E, 0xB9, 0x2E, 0x8E, 0x84, + 0x66, 0xE1, 0xB9, 0xD0, 0x25, 0x9A, 0x6F, 0x9D, 0x19, 0xE6, + 0x7E, 0xE8, 0xD8, 0xF0, 0xC5, 0x23, 0x16, 0x9A, 0x68, 0x2C, + 0x1D, 0x55, 0xAE, 0x8E, 0x90, 0xEE, 0x8E, 0xEC, 0x5E, 0x46, + 0x9D, 0x60, 0x52, 0x32, 0x17, 0x28, 0x59, 0xC4, 0x49, 0x2A, + 0x20, 0x3E, 0x95, 0xC5, 0xDF, 0xF6, 0x3D, 0xF7, 0xC5, 0xCF, + 0xB1, 0xC2, 0xC9, 0x76, 0xF8, 0x3D, 0xBE, 0xF4, 0x63, 0xFC, + 0x2A, 0x00, 0x6F, 0x99, 0xA6, 0xB6, 0xAD, 0x35, 0xEE, 0xDE, + 0xC5, 0xE0, 0x97, 0xC6, 0x73, 0xEE, 0x33, 0xA0, 0xA8, 0xFC, + 0x4C, 0x8F, 0xF2, 0x8C, 0x61, 0xFB, 0x03, 0x19, 0xA1, 0xE8, + 0x17, 0x4E, 0xE3, 0x21, 0x58, 0xCE, 0xFE, 0xF2, 0x5F, 0xBB, + 0xDD, 0x4F, 0xF7, 0x18, 0xCB, 0x35, 0x57, 0xDD, 0xE5, 0x50, + 0x2A, 0x7B, 0x1A, 0xE9, 0x12, 0xF2, 0x7A, 0x11, 0xB1, 0x43, + 0xB9, 0x70, 0x07, 0x0C, 0x8F, 0x69, 0xB9, 0xE5, 0xA5, 0xC9, + 0xE2, 0x1B, 0x96, 0x74, 0x11, 0xF5, 0x95, 0xB9, 0x58, 0xC0, + 0xBD, 0x37, 0xFB, 0x28, 0x2A, 0xBD, 0x84, 0xB1, 0x2B, 0x67, + 0x42, 0x82, 0xC3, 0x95, 0x55, 0x45, 0xD5, 0xEA, 0xC3, 0x8A, + 0x42, 0x3A, 0x43, 0x17, 0x5E, 0xCD, 0xD2, 0xEA, 0xFC, 0xDF, + 0x67, 0xEC, 0xE1, 0x6C, 0xA8, 0x03, 0x19, 0xB2, 0x1D, 0x4A, + 0x5F, 0x4F, 0xE7, 0xD3, 0xE0, 0x86, 0xC5, 0x1A, 0x10, 0xC3, + 0x08, 0xD2, 0xED, 0x85, 0x93, 0x08, 0x51, 0x05, 0xA6, 0x37, + 0x15, 0x32, 0xBD, 0x6C, 0x73, 0x63, 0x01, 0x5D, 0x5B, 0x4F, + 0x6A, 0xDC, 0x6D, 0x1D, 0x55, 0x91, 0x21, 0xE4, 0x8E, 0xB7, + 0xF0, 0x81, 0x02, 0x82, 0x01, 0x01, 0x00, 0xFD, 0x27, 0xC8, + 0xFE, 0x76, 0x5C, 0x89, 0x32, 0xCB, 0x8A, 0x22, 0x87, 0x61, + 0x48, 0x91, 0x4A, 0x05, 0xAD, 0xA4, 0x5C, 0x8A, 0xCA, 0x5C, + 0x02, 0x88, 0x7E, 0x51, 0xC5, 0x66, 0x90, 0x2C, 0xA3, 0xED, + 0xA7, 0x43, 0x19, 0x0B, 0xA2, 0x42, 0xB4, 0xE0, 0xE0, 0x45, + 0xBF, 0xFE, 0xA0, 0xF2, 0x75, 0x0B, 0x8E, 0x7D, 0x9D, 0x73, + 0x67, 0xD3, 0x10, 0x09, 0xC5, 0xD9, 0x8C, 0xAD, 0x3A, 0x64, + 0x72, 0xAD, 0x96, 0x35, 0x91, 0x0F, 0x4B, 0xC9, 0xBD, 0x4F, + 0x65, 0x47, 0xA6, 0x2D, 0xEB, 0x3F, 0xE2, 0x99, 0x72, 0x66, + 0x12, 0xED, 0xEB, 0xD2, 0x7C, 0xFF, 0x3A, 0x20, 0x37, 0x2A, + 0xD3, 0x65, 0x51, 0x9B, 0xC3, 0xAA, 0x18, 0xB1, 0x1F, 0x6E, + 0x9D, 0x40, 0x47, 0xA4, 0x1F, 0x82, 0x9B, 0xDB, 0x50, 0x6B, + 0x86, 0x2F, 0xFB, 0x3F, 0x31, 0xB9, 0x81, 0x11, 0x04, 0x14, + 0x63, 0x86, 0x4F, 0x40, 0x2A, 0xF5, 0xF9, 0x7C, 0xA1, 0x78, + 0x19, 0x13, 0xD0, 0x51, 0x51, 0x0F, 0x79, 0x88, 0x8D, 0x14, + 0xA3, 0xDE, 0xB6, 0x33, 0x29, 0x42, 0xB9, 0xE8, 0x59, 0x76, + 0xF7, 0x43, 0x1A, 0xB6, 0xA6, 0xDF, 0x0A, 0xC1, 0x42, 0xC7, + 0x3F, 0x1C, 0x7E, 0x5C, 0x2C, 0x91, 0x4B, 0x1E, 0xF8, 0x46, + 0x91, 0x1F, 0xEE, 0x56, 0xB3, 0x0E, 0xC8, 0xD0, 0x31, 0xD3, + 0x3D, 0xED, 0x3D, 0xD9, 0xC5, 0x30, 0x0C, 0x58, 0xD8, 0xB7, + 0xB5, 0xEC, 0x14, 0xAC, 0x41, 0x64, 0x6D, 0xE4, 0xC6, 0x59, + 0xFD, 0x14, 0x05, 0x60, 0x65, 0xD8, 0xC4, 0x84, 0x44, 0x7E, + 0x1B, 0xB4, 0xA4, 0x16, 0x75, 0xC1, 0x27, 0x96, 0xB2, 0x19, + 0xD6, 0x39, 0x54, 0xC0, 0x93, 0xF3, 0xD7, 0x1F, 0xCD, 0x1B, + 0xDF, 0xF8, 0x12, 0x88, 0x14, 0x9F, 0x98, 0x05, 0x47, 0x46, + 0x71, 0x81, 0x6C, 0xDF, 0x91, 0xEF, 0x53, 0xE3, 0xC5, 0xB1, + 0x89, 0x2F, 0xE1, 0x02, 0x82, 0x01, 0x01, 0x00, 0xF8, 0x93, + 0x4A, 0x28, 0x77, 0x94, 0xEF, 0xE9, 0xC4, 0x0A, 0xC3, 0xE8, + 0x52, 0x59, 0xB6, 0x1D, 0x8D, 0xCE, 0x14, 0xE7, 0x43, 0xC6, + 0xED, 0x09, 0x27, 0x5D, 0xF3, 0x8E, 0x08, 0x6A, 0x19, 0x6B, + 0x2C, 0x97, 0x9B, 0x88, 0x53, 0x2B, 0xDA, 0xFE, 0x4B, 0x94, + 0x66, 0x84, 0xD5, 0xA9, 0xCE, 0xA5, 0x43, 0x70, 0xFB, 0x01, + 0x5A, 0x6F, 0xCD, 0xF7, 0xD1, 0x9D, 0x51, 0xEE, 0xA0, 0xDC, + 0x46, 0xF5, 0x7D, 0xA7, 0xEE, 0xA0, 0x86, 0xB7, 0x83, 0xFF, + 0x21, 0x8B, 0x76, 0x05, 0x7D, 0xDE, 0xC4, 0x26, 0x36, 0xBC, + 0xB4, 0x8A, 0x48, 0xC3, 0x06, 0x90, 0x97, 0xE5, 0xA6, 0x38, + 0xC3, 0xE6, 0x7C, 0xD0, 0xF8, 0x23, 0xD2, 0x33, 0x1F, 0x81, + 0xC3, 0xE3, 0x7D, 0x85, 0x5A, 0x38, 0x10, 0x03, 0xE6, 0x88, + 0xDB, 0xC8, 0x4C, 0xD0, 0xF7, 0xB2, 0x4D, 0x27, 0x33, 0x85, + 0xCD, 0x3A, 0x74, 0x83, 0x6B, 0x82, 0x58, 0xD9, 0xDF, 0xEE, + 0xF5, 0xD3, 0xE9, 0xFE, 0x1C, 0xEF, 0x06, 0x12, 0x16, 0xD1, + 0x4C, 0xAE, 0x54, 0x4B, 0x0D, 0x1A, 0xBD, 0xE2, 0xCF, 0x56, + 0xB3, 0x74, 0xBE, 0x44, 0x4F, 0xA4, 0x73, 0x0A, 0x98, 0x8D, + 0x61, 0x84, 0x38, 0x46, 0xDC, 0x95, 0xCF, 0x3F, 0x6B, 0xE7, + 0x65, 0x87, 0x02, 0xBF, 0x4B, 0x57, 0xE2, 0x3D, 0xC4, 0x2B, + 0x1C, 0x82, 0x1D, 0xCC, 0x13, 0x7F, 0xC0, 0x06, 0x12, 0x8C, + 0x6F, 0x97, 0x50, 0x7B, 0x8C, 0x81, 0xC3, 0x23, 0x15, 0xEB, + 0x70, 0x07, 0x8E, 0xA1, 0x07, 0x1E, 0x59, 0xFA, 0x10, 0xCA, + 0x7E, 0x0F, 0xE2, 0xBB, 0xEE, 0x86, 0x26, 0x1E, 0x55, 0xB9, + 0x98, 0x66, 0x85, 0xEC, 0x27, 0xC5, 0xD9, 0x63, 0x8D, 0x51, + 0x77, 0xAA, 0xA0, 0x36, 0x55, 0x33, 0x10, 0x21, 0x5E, 0xEC, + 0x47, 0x67, 0x71, 0xD1, 0xAF, 0xFC, 0x3E, 0x50, 0xF5, 0xBE, + 0xD6, 0x92, 0xE7, 0x0B, 0x02, 0x82, 0x01, 0x00, 0x21, 0x7C, + 0x8A, 0xC4, 0xC6, 0x29, 0x55, 0x68, 0xA7, 0xAD, 0xDD, 0x05, + 0x65, 0x63, 0xF0, 0xFC, 0x06, 0xA6, 0x42, 0x70, 0x8F, 0x57, + 0x57, 0x36, 0x6A, 0x91, 0xB3, 0x05, 0x56, 0x9C, 0xC9, 0x9A, + 0xE1, 0x8B, 0xD7, 0x7F, 0x4F, 0x9F, 0xA6, 0x0D, 0x41, 0x15, + 0xC9, 0x84, 0x2D, 0x0D, 0x63, 0x25, 0x02, 0x63, 0x55, 0xD0, + 0x66, 0xFC, 0x9B, 0xD9, 0xAA, 0x41, 0x46, 0x96, 0xAA, 0x2F, + 0x68, 0x2C, 0x17, 0x34, 0x20, 0x5F, 0xD0, 0xD3, 0x28, 0x9B, + 0x67, 0x0E, 0x31, 0x9D, 0x14, 0xC3, 0xE2, 0x8E, 0x79, 0xD7, + 0xBD, 0x12, 0xD1, 0xEF, 0xF8, 0xC6, 0xDA, 0x07, 0xF9, 0x4C, + 0xF2, 0xD8, 0x45, 0xB5, 0xB6, 0xD1, 0xFA, 0x05, 0x0C, 0x20, + 0xE9, 0x43, 0xD9, 0xC5, 0xE0, 0x3A, 0xDE, 0xCE, 0xF9, 0x02, + 0xB9, 0x46, 0x65, 0xC0, 0x69, 0x4A, 0x8D, 0x8C, 0x3A, 0x10, + 0xFD, 0x15, 0x71, 0x25, 0xB8, 0x8A, 0x36, 0x41, 0x4B, 0x30, + 0x1C, 0xAF, 0xCC, 0x84, 0x28, 0xCD, 0x7D, 0x2B, 0x89, 0x59, + 0x88, 0x1A, 0x69, 0x12, 0x56, 0xD0, 0x25, 0x68, 0x6C, 0x08, + 0xB1, 0x88, 0xE1, 0x92, 0x7E, 0x08, 0xB2, 0xC6, 0x3C, 0x6C, + 0x35, 0xE8, 0xEE, 0x3E, 0xF4, 0xB8, 0x5C, 0x7B, 0xC0, 0x5B, + 0xFD, 0x11, 0xA3, 0x54, 0xA6, 0x99, 0x46, 0xE2, 0x5F, 0x4F, + 0xC7, 0xEE, 0x90, 0x1C, 0x37, 0x5B, 0x33, 0x10, 0xDF, 0x0B, + 0xC3, 0xB9, 0x47, 0xC2, 0x30, 0x4A, 0xF2, 0x1A, 0xEB, 0x41, + 0x25, 0x94, 0x29, 0x7A, 0xD0, 0x96, 0x88, 0x46, 0xEE, 0x6C, + 0x14, 0xF6, 0x5B, 0x3D, 0xBD, 0x4E, 0xD4, 0x3F, 0x05, 0x5B, + 0x07, 0xB9, 0xE3, 0x99, 0x87, 0x63, 0xCA, 0xC4, 0x71, 0x0B, + 0x73, 0x9D, 0x7B, 0xB6, 0x0F, 0xD4, 0x12, 0x8C, 0x4C, 0x5E, + 0x72, 0x3D, 0xFF, 0x6D, 0xC4, 0x61, 0x0C, 0x74, 0x5F, 0x53, + 0xBE, 0x39, 0x34, 0x61, 0x02, 0x82, 0x01, 0x00, 0x5F, 0xF2, + 0xF2, 0xB0, 0x16, 0x20, 0x8E, 0x4E, 0xCC, 0x96, 0x5F, 0x32, + 0x80, 0xFF, 0x11, 0xF5, 0xEC, 0x73, 0xBC, 0xCB, 0xDB, 0xF4, + 0xA0, 0x30, 0x65, 0x5A, 0xB5, 0x95, 0x80, 0x97, 0xFB, 0xC1, + 0xCB, 0xCF, 0xA5, 0x80, 0x84, 0xA2, 0x2C, 0x00, 0xF6, 0x89, + 0x8C, 0xDC, 0xFF, 0x60, 0x71, 0x5C, 0x87, 0x60, 0xC7, 0xF2, + 0xA8, 0xC6, 0xF9, 0x59, 0x0C, 0x37, 0x4E, 0x95, 0xEE, 0xCF, + 0xB8, 0x30, 0x30, 0x55, 0xAF, 0x1D, 0x95, 0x82, 0xA6, 0xD7, + 0xC7, 0x49, 0xFE, 0xBF, 0x75, 0xEB, 0x94, 0x09, 0x30, 0x1D, + 0xBD, 0x0E, 0x97, 0xB1, 0x78, 0x0A, 0x3E, 0x27, 0xAD, 0xF6, + 0xC1, 0x5F, 0x69, 0x94, 0x7C, 0x03, 0xCF, 0xB2, 0x5E, 0x1A, + 0x07, 0xD3, 0xFA, 0xF2, 0x8B, 0x75, 0x92, 0x70, 0xFE, 0xFE, + 0x9A, 0xDF, 0x81, 0x0F, 0x34, 0x5D, 0x45, 0xBC, 0xB8, 0xFD, + 0x8F, 0xCF, 0x5D, 0x84, 0x10, 0xEE, 0x9A, 0x7F, 0x57, 0x19, + 0xF5, 0x17, 0xDC, 0x7D, 0x73, 0x0B, 0xAC, 0x6B, 0x35, 0x15, + 0x8B, 0x24, 0xCB, 0x72, 0xC0, 0xD7, 0x2E, 0xAE, 0xAA, 0xDB, + 0xCB, 0x9F, 0x67, 0x86, 0x14, 0xBB, 0xE4, 0x90, 0x15, 0x7C, + 0x95, 0x44, 0xA5, 0x38, 0x6D, 0x13, 0x02, 0x91, 0x77, 0x84, + 0x35, 0x43, 0x5D, 0x03, 0x1C, 0x01, 0x0B, 0x5A, 0x4E, 0x2B, + 0x59, 0xF0, 0xBB, 0xB1, 0xB7, 0x61, 0x1B, 0x6C, 0xFC, 0xA1, + 0xEA, 0xBD, 0x1C, 0x9A, 0xE4, 0x0C, 0x7E, 0x97, 0x3F, 0x71, + 0xC6, 0xA7, 0x94, 0x1D, 0x82, 0x12, 0xEC, 0x26, 0x43, 0x6E, + 0xF6, 0x24, 0x09, 0xA0, 0x03, 0x1D, 0x12, 0xFF, 0xA8, 0x95, + 0x60, 0x47, 0x4A, 0xB0, 0x72, 0x55, 0xC3, 0x68, 0xD2, 0xF6, + 0xBC, 0x5B, 0x47, 0x46, 0x51, 0xB2, 0xC9, 0x2A, 0x28, 0x6A, + 0xC9, 0xD1, 0x1B, 0x35, 0x16, 0x5A, 0x26, 0x6F, 0xB7, 0xBB, + 0xF7, 0x35, 0x73, 0x2B, 0x02, 0x82, 0x01, 0x00, 0x56, 0xBA, + 0xD8, 0x02, 0xD7, 0x4B, 0x30, 0x5E, 0x1B, 0x1E, 0x2F, 0xF3, + 0x0D, 0xBC, 0xF1, 0x05, 0x6A, 0x68, 0x4A, 0xE1, 0xEA, 0xB3, + 0xDE, 0x61, 0x8C, 0x89, 0x44, 0xBA, 0x63, 0x5E, 0xDF, 0x05, + 0x24, 0x32, 0x71, 0x65, 0x1A, 0x36, 0x2F, 0xBC, 0x07, 0x75, + 0xA3, 0xCE, 0x9E, 0x52, 0x92, 0x95, 0x4D, 0x3F, 0xC9, 0x06, + 0xBC, 0xA1, 0x14, 0x33, 0x37, 0x95, 0xAB, 0x9A, 0xEB, 0x04, + 0xF6, 0x15, 0xC3, 0x9B, 0x10, 0x56, 0x53, 0xA2, 0x28, 0xF2, + 0x68, 0xDA, 0x7D, 0x97, 0x52, 0x63, 0xAC, 0x9B, 0x56, 0xA9, + 0xAB, 0x2E, 0x1E, 0x9E, 0x01, 0x70, 0xFF, 0x2B, 0x6D, 0x0C, + 0x4B, 0xA6, 0xC3, 0x3A, 0xB3, 0xD1, 0xA7, 0x4B, 0x5E, 0x49, + 0x2E, 0x95, 0xD6, 0x6A, 0xAE, 0x58, 0x13, 0x66, 0x8F, 0x2F, + 0x93, 0xE4, 0x6E, 0x8B, 0xFA, 0x94, 0x30, 0x3E, 0xEC, 0x96, + 0xAB, 0x46, 0x20, 0x3E, 0xC5, 0x30, 0xB4, 0xEB, 0x41, 0x00, + 0x39, 0x60, 0x1D, 0xE1, 0x20, 0xCE, 0x31, 0x70, 0x17, 0x39, + 0xCB, 0x76, 0x56, 0x6C, 0x55, 0x7B, 0x90, 0x20, 0xBC, 0x39, + 0xB2, 0x5B, 0xD1, 0x28, 0x6F, 0x0C, 0x4F, 0x45, 0x6B, 0x82, + 0xC4, 0x57, 0x23, 0x0C, 0x3F, 0x3F, 0x2D, 0x83, 0xB3, 0x3D, + 0x8E, 0xF9, 0x1A, 0xDA, 0x77, 0x54, 0x2E, 0xFE, 0x16, 0x2E, + 0xBA, 0x99, 0xDD, 0xCA, 0xB3, 0xD1, 0xD8, 0xBB, 0x87, 0xE1, + 0xD0, 0xA9, 0xD4, 0xE6, 0x8F, 0xE8, 0x00, 0x3E, 0x49, 0x8A, + 0xDD, 0xA6, 0x32, 0x91, 0x00, 0x31, 0x31, 0x21, 0x98, 0x18, + 0x94, 0xC9, 0x2D, 0x27, 0x05, 0xB7, 0x9B, 0x09, 0x2E, 0xBB, + 0x5D, 0xBF, 0x67, 0xE8, 0x0E, 0xD1, 0x44, 0x75, 0x80, 0x1D, + 0x0A, 0x21, 0x8F, 0x95, 0x76, 0xB0, 0xFC, 0x19, 0x3C, 0xFF, + 0x92, 0xEA, 0x01, 0x45, 0x89, 0xD1, 0x4E, 0xFE, 0x4D, 0x2B, + 0x4B, 0x18, 0xE6, 0xCE }; static const int sizeof_client_key_der_4096 = sizeof(client_key_der_4096); @@ -3205,9 +3211,9 @@ static const int sizeof_client_keypub_der_4096 = sizeof(client_keypub_der_4096); static const unsigned char client_cert_der_4096[] = { 0x30, 0x82, 0x07, 0x1D, 0x30, 0x82, 0x05, 0x05, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x2F, 0x36, 0x54, 0x05, 0x64, - 0x52, 0xDD, 0x0E, 0x75, 0x75, 0x33, 0x7C, 0xB2, 0xCE, 0x9F, - 0x5C, 0x48, 0x9B, 0xAB, 0x0E, 0x30, 0x0D, 0x06, 0x09, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x12, 0x66, 0xC3, 0xA2, 0x08, + 0x5C, 0xF7, 0xD0, 0x6E, 0xE9, 0xA8, 0x82, 0xA2, 0xAB, 0x9C, + 0x0F, 0x76, 0x9E, 0x96, 0xF4, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, @@ -3225,10 +3231,10 @@ static const unsigned char client_cert_der_4096[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x9E, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, @@ -3323,9 +3329,9 @@ static const unsigned char client_cert_der_4096[] = 0x63, 0x6F, 0x6D, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, - 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x2F, 0x36, - 0x54, 0x05, 0x64, 0x52, 0xDD, 0x0E, 0x75, 0x75, 0x33, 0x7C, - 0xB2, 0xCE, 0x9F, 0x5C, 0x48, 0x9B, 0xAB, 0x0E, 0x30, 0x0C, + 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x12, 0x66, + 0xC3, 0xA2, 0x08, 0x5C, 0xF7, 0xD0, 0x6E, 0xE9, 0xA8, 0x82, + 0xA2, 0xAB, 0x9C, 0x0F, 0x76, 0x9E, 0x96, 0xF4, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, @@ -3335,58 +3341,58 @@ static const unsigned char client_cert_der_4096[] = 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, 0x82, - 0x02, 0x01, 0x00, 0xC2, 0x72, 0x38, 0x27, 0xF0, 0x5C, 0x45, - 0x04, 0x4B, 0x09, 0x0E, 0x5D, 0x98, 0x6E, 0x38, 0x6A, 0xBC, - 0xFB, 0xA8, 0x85, 0x4F, 0xF2, 0x04, 0x38, 0x63, 0x4F, 0x86, - 0x4F, 0x3C, 0xF5, 0xFD, 0xF8, 0xCD, 0x89, 0x09, 0x76, 0x72, - 0x47, 0x97, 0xDF, 0xF8, 0x17, 0x6A, 0x81, 0x3A, 0xB2, 0xB4, - 0xFC, 0xAC, 0xE9, 0xFC, 0xE2, 0x47, 0x9B, 0x07, 0x6D, 0x9C, - 0x53, 0xED, 0xD8, 0x64, 0xBC, 0x6C, 0x4D, 0xA9, 0xBD, 0x3E, - 0x5E, 0xCD, 0x61, 0xBC, 0x8E, 0x82, 0x20, 0xB2, 0x50, 0xBC, - 0x9E, 0x72, 0xE6, 0x9F, 0x40, 0xFF, 0x6C, 0x4B, 0x38, 0xF8, - 0x4B, 0x82, 0x0F, 0x7E, 0x49, 0xCD, 0x45, 0x5C, 0xCD, 0x44, - 0xDE, 0x47, 0x25, 0xB3, 0x57, 0xD0, 0x1A, 0x0D, 0x8D, 0x4D, - 0xC7, 0xEA, 0x23, 0xFA, 0x03, 0xE8, 0x86, 0xD8, 0x37, 0x89, - 0x84, 0x2E, 0xE8, 0x53, 0x7A, 0x77, 0xBE, 0x94, 0xEC, 0x70, - 0xE7, 0xC4, 0x7B, 0x8F, 0x6F, 0x28, 0x67, 0x33, 0x89, 0xEC, - 0xC9, 0xDF, 0x98, 0x6D, 0x4A, 0xD9, 0xC6, 0x7B, 0xD3, 0xB5, - 0x82, 0xD0, 0x8A, 0xCE, 0x8F, 0x06, 0xBF, 0xA2, 0xF7, 0xDE, - 0x4A, 0x45, 0x22, 0x6F, 0xFF, 0x41, 0x6F, 0x08, 0xF5, 0xC3, - 0x65, 0x25, 0x27, 0xFB, 0x43, 0x3E, 0xCC, 0x25, 0x0A, 0xD3, - 0x3D, 0xD2, 0x34, 0x9F, 0x89, 0x6B, 0xE2, 0x97, 0x9C, 0x42, - 0xD9, 0x3E, 0x64, 0x03, 0x45, 0x5F, 0x07, 0x95, 0xED, 0x1A, - 0x70, 0x6A, 0xBE, 0x3E, 0x7F, 0x7F, 0x16, 0xBE, 0x47, 0xA6, - 0x6D, 0x3B, 0x0D, 0x27, 0xB3, 0x89, 0xB1, 0xF1, 0xF6, 0xCE, - 0x99, 0x71, 0x18, 0xB6, 0xC0, 0xC5, 0x9E, 0x76, 0x7A, 0x8E, - 0xFB, 0x4A, 0xBE, 0x4F, 0xCD, 0xBC, 0x21, 0xA9, 0x4E, 0x9C, - 0xFC, 0x48, 0x86, 0xFF, 0xE4, 0x63, 0x14, 0x96, 0x3A, 0xEB, - 0xC8, 0x48, 0xAE, 0x27, 0xBD, 0x43, 0x0C, 0x27, 0x85, 0xE1, - 0x25, 0x1A, 0x69, 0x48, 0x6C, 0xE7, 0x11, 0xF8, 0xF3, 0x68, - 0x9D, 0xEE, 0x15, 0x1A, 0xBE, 0xAD, 0x46, 0x33, 0x24, 0x3D, - 0xBE, 0xB8, 0x0E, 0x6E, 0x4D, 0xEF, 0x12, 0xB6, 0xAE, 0x1B, - 0x88, 0xBD, 0x0E, 0xA6, 0xFF, 0x91, 0x08, 0xDC, 0xED, 0xAF, - 0xFA, 0x13, 0x2B, 0xF2, 0xB4, 0x2C, 0xEA, 0x72, 0xC2, 0x85, - 0xD6, 0xEE, 0x64, 0x09, 0xE1, 0x4E, 0x1A, 0x5A, 0xBD, 0xC2, - 0x44, 0xC2, 0x95, 0x82, 0x59, 0x0A, 0xD8, 0x27, 0xBC, 0x48, - 0x4A, 0x8A, 0xA3, 0xC3, 0x77, 0xAC, 0x92, 0xB6, 0x8B, 0x0B, - 0x13, 0xE2, 0x87, 0xEC, 0x21, 0x7E, 0x7E, 0x52, 0x29, 0x51, - 0x5C, 0x59, 0xE1, 0xC8, 0xDB, 0x05, 0xCE, 0x9E, 0xF4, 0x36, - 0xD8, 0x63, 0x42, 0x45, 0x71, 0x9A, 0xEE, 0x0E, 0x24, 0xB0, - 0xBA, 0xA5, 0xA5, 0xAA, 0xC9, 0xEE, 0x9E, 0xA3, 0xE3, 0xE9, - 0x7F, 0xC6, 0x64, 0x6C, 0x9E, 0x65, 0x78, 0x88, 0xF2, 0x61, - 0x6F, 0xD3, 0x3B, 0x9E, 0x0D, 0x16, 0xFA, 0xAD, 0xC2, 0x58, - 0xAC, 0xBC, 0x14, 0xB1, 0xF7, 0x6F, 0xDB, 0xB9, 0x7E, 0x79, - 0x81, 0xF1, 0xF8, 0xE9, 0x41, 0x5B, 0xFE, 0xD9, 0xE2, 0x89, - 0x86, 0x5C, 0x01, 0x03, 0x5D, 0x0C, 0xD9, 0xA9, 0xD6, 0xDF, - 0x4B, 0x26, 0x5C, 0xAE, 0xE6, 0xDF, 0xB5, 0xC9, 0xF0, 0x86, - 0xCA, 0x7B, 0x80, 0xDB, 0x6A, 0x86, 0xFD, 0xA9, 0x00, 0x46, - 0x32, 0x39, 0x5A, 0x72, 0xC4, 0x67, 0x20, 0xDB, 0xD8, 0x7A, - 0x5D, 0x2D, 0x78, 0xB9, 0xA7, 0xDE, 0x7F, 0xF4, 0x7A, 0x5B, - 0x0F, 0x38, 0xB0, 0x9E, 0x1A, 0xAE, 0xC5, 0xCC, 0xFF, 0x61, - 0x5E, 0xEC, 0xF1, 0x0D, 0xF7, 0x0A, 0x22, 0xBB, 0xCB, 0x08, - 0x2B, 0x91, 0x58, 0x77, 0x1F, 0x90, 0x2B, 0xA3, 0x78, 0xBE, - 0xEF, 0x4D, 0xD8, 0x8D, 0xE8, 0xF7, 0x31, 0xF8, 0x92, 0x84, - 0xE5, 0xB2, 0x2A, 0xE8, 0x3A + 0x02, 0x01, 0x00, 0xB0, 0x00, 0x28, 0x7B, 0xC8, 0x3F, 0xAE, + 0x93, 0xF5, 0x16, 0x87, 0x30, 0xD6, 0x07, 0x2B, 0x71, 0x16, + 0x34, 0x1E, 0x5C, 0x48, 0x0F, 0x4A, 0xE7, 0x50, 0x07, 0x9D, + 0xF4, 0x75, 0x5B, 0x90, 0x53, 0x72, 0x87, 0x2A, 0xBB, 0xEF, + 0x04, 0xBC, 0x52, 0xD2, 0xBF, 0xFF, 0x27, 0x58, 0x2F, 0x5C, + 0xAF, 0xBE, 0xF3, 0xF6, 0x00, 0xA2, 0x37, 0x8B, 0xEC, 0x2C, + 0xD7, 0xB7, 0xE7, 0xBB, 0x3B, 0xCA, 0x6F, 0x9D, 0x42, 0xB7, + 0x00, 0xB8, 0xC2, 0xA2, 0x8E, 0x8E, 0xE4, 0x57, 0xFD, 0x83, + 0x4B, 0xB8, 0x47, 0xAA, 0xA1, 0x28, 0xAC, 0xBD, 0xC1, 0x59, + 0x04, 0x90, 0x17, 0x40, 0x40, 0x35, 0x04, 0xC6, 0x40, 0xA9, + 0x21, 0xD3, 0x79, 0x45, 0x0E, 0x22, 0xC8, 0x6F, 0xEC, 0xAE, + 0x58, 0xA5, 0xC2, 0xD8, 0x1B, 0x11, 0x49, 0x94, 0x58, 0xC2, + 0x11, 0x7D, 0xF8, 0x0A, 0xBB, 0x47, 0xFD, 0xAC, 0xCF, 0xF7, + 0x23, 0x05, 0x3F, 0xAB, 0x1D, 0x0E, 0x30, 0xC5, 0x98, 0x29, + 0x13, 0x1A, 0x90, 0x6F, 0xF9, 0x3F, 0xF2, 0xD6, 0xDF, 0x03, + 0xCC, 0xF1, 0x48, 0xE7, 0x71, 0xE6, 0xC4, 0xCE, 0xF3, 0xF9, + 0xBF, 0x07, 0xC9, 0xCF, 0xDD, 0x63, 0x0E, 0xFE, 0xBC, 0x93, + 0x1C, 0x9A, 0x52, 0x7D, 0x63, 0xF9, 0x6D, 0xA5, 0x50, 0xF3, + 0xEF, 0x54, 0xD7, 0xDA, 0x42, 0x74, 0x85, 0xB1, 0xB4, 0x7C, + 0xD5, 0x03, 0xCC, 0xB8, 0xC3, 0xBA, 0x1F, 0xB8, 0x4F, 0x5A, + 0xF9, 0x05, 0xBA, 0x4B, 0x0D, 0x57, 0x8D, 0x05, 0xCF, 0x4F, + 0xB7, 0xC4, 0x64, 0x2E, 0x2C, 0x10, 0xF3, 0xFA, 0x79, 0x0C, + 0x8C, 0x1F, 0xCC, 0x84, 0x33, 0x88, 0xFB, 0x77, 0xB5, 0x6E, + 0x45, 0x35, 0x15, 0xCC, 0x28, 0x80, 0x2B, 0x2D, 0x6B, 0x3F, + 0xD0, 0xA3, 0x10, 0xD1, 0x53, 0xC0, 0xBB, 0x70, 0x43, 0x79, + 0x2F, 0xFF, 0x3F, 0x63, 0x26, 0xC5, 0x60, 0x9B, 0x87, 0xE9, + 0xA2, 0x5B, 0x40, 0x13, 0x41, 0x25, 0xD2, 0x9C, 0x3E, 0x42, + 0x79, 0x00, 0xE1, 0x12, 0x0E, 0xAA, 0x06, 0xE0, 0x65, 0x59, + 0xA1, 0xFA, 0xDB, 0xC4, 0xC2, 0x97, 0xA8, 0x87, 0x35, 0x96, + 0x1C, 0x8E, 0xFF, 0xEB, 0x91, 0xE0, 0x8B, 0xE3, 0x3E, 0xC8, + 0xB2, 0x8C, 0xD3, 0x84, 0x5E, 0x76, 0x80, 0xD7, 0x29, 0x0A, + 0x59, 0xCC, 0x71, 0xD5, 0xE5, 0x65, 0x3C, 0x30, 0x38, 0x6E, + 0xF5, 0x3F, 0x7E, 0x28, 0x0F, 0x3D, 0x15, 0x10, 0x86, 0x30, + 0x39, 0x56, 0x23, 0x13, 0x30, 0xB4, 0x70, 0xF7, 0x7B, 0xC3, + 0x0D, 0x51, 0xAD, 0x18, 0xB1, 0x87, 0xB3, 0x3F, 0x1C, 0x69, + 0xF5, 0xD4, 0x1E, 0x72, 0x66, 0x5E, 0x44, 0xB9, 0x53, 0xBA, + 0x9E, 0xF0, 0xB8, 0x4A, 0xB1, 0x34, 0x50, 0x98, 0xD8, 0xF2, + 0xB9, 0xB2, 0xC5, 0xED, 0x73, 0xC9, 0xEE, 0xDD, 0x33, 0x8C, + 0xCF, 0x72, 0x35, 0xE0, 0x3D, 0x0F, 0x45, 0x2A, 0x89, 0xF9, + 0xA3, 0x76, 0x40, 0x07, 0x0F, 0xF6, 0x48, 0x6C, 0xF1, 0x8C, + 0x30, 0x3A, 0xC2, 0x51, 0x06, 0xC2, 0x51, 0x5E, 0x75, 0x98, + 0x06, 0xE0, 0x1E, 0x29, 0xF7, 0x12, 0x9A, 0x56, 0xA4, 0x38, + 0x83, 0xB1, 0x8B, 0x86, 0xB6, 0xAB, 0x87, 0xAA, 0x3C, 0x39, + 0x9D, 0x4D, 0x0C, 0xE8, 0x78, 0x9F, 0x52, 0x47, 0x66, 0x69, + 0xC8, 0x66, 0x0C, 0xFE, 0xD9, 0x74, 0x1D, 0x78, 0x0B, 0x51, + 0xE4, 0xD9, 0xC8, 0x35, 0x97, 0x95, 0xC7, 0x31, 0x97, 0x13, + 0x49, 0xED, 0xAA, 0x9E, 0x9C, 0xFD, 0x66, 0x04, 0x79, 0xD2, + 0x24, 0x4D, 0x64, 0x8D, 0x3F, 0xCD, 0x94, 0xB0, 0x05, 0x0A, + 0x30, 0x3B, 0x1C, 0x96, 0xE7, 0x79, 0x00, 0x03, 0x47, 0x55, + 0x34, 0x51, 0x1F, 0x46, 0x3A, 0x24, 0x47, 0xE6, 0xDD, 0x78, + 0x89, 0x18, 0x29, 0x32, 0xC5, 0xAD, 0xFB, 0x9C, 0xF7, 0x26, + 0xAC, 0x56, 0x3E, 0xF7, 0x73 }; static const int sizeof_client_cert_der_4096 = sizeof(client_cert_der_4096); @@ -4102,9 +4108,10 @@ static const int sizeof_bench_falcon_level5_key = sizeof(bench_falcon_level5_key #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) - #ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* raw private key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level2_key.der */ static const unsigned char bench_dilithium_level2_key[] = { 0xea, 0x05, 0x24, 0x0d, 0x80, 0x72, 0x25, 0x55, 0xf4, 0x5b, 0xc2, 0x13, 0x8b, 0x87, 0x5d, 0x31, 0x99, 0x2f, 0x1d, 0xa9, @@ -4369,6 +4376,8 @@ static const int sizeof_bench_dilithium_level2_key = sizeof(bench_dilithium_leve #ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* raw public key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level2_key.der */ static const unsigned char bench_dilithium_level2_pubkey[] = { 0xea, 0x05, 0x24, 0x0d, 0x80, 0x72, 0x25, 0x55, 0xf4, 0x5b, 0xc2, 0x13, 0x8b, 0x87, 0x5d, 0x31, 0x99, 0x2f, 0x1d, 0xa9, @@ -4510,6 +4519,8 @@ static const int sizeof_bench_dilithium_level2_pubkey = #ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* raw private key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level3_key.der */ static const unsigned char bench_dilithium_level3_key[] = { 0x15, 0xc9, 0xe5, 0x53, 0x2f, 0xd8, 0x1f, 0xb4, 0xa3, 0x9f, 0xae, 0xad, 0xb3, 0x10, 0xd0, 0x72, 0x69, 0xd3, 0x02, 0xf3, @@ -4922,6 +4933,8 @@ static const int sizeof_bench_dilithium_level3_key = sizeof(bench_dilithium_leve #ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* raw public key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level3_key.der */ static const unsigned char bench_dilithium_level3_pubkey[] = { 0x15, 0xc9, 0xe5, 0x53, 0x2f, 0xd8, 0x1f, 0xb4, 0xa3, 0x9f, 0xae, 0xad, 0xb3, 0x10, 0xd0, 0x72, 0x69, 0xd3, 0x02, 0xf3, @@ -5127,6 +5140,8 @@ static const int sizeof_bench_dilithium_level3_pubkey = #ifndef WOLFSSL_DILITHIUM_NO_SIGN +/* raw private key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level5_key.der */ static const unsigned char bench_dilithium_level5_key[] = { 0xef, 0x49, 0x79, 0x47, 0x15, 0xc4, 0x8a, 0xa9, 0x74, 0x2a, 0xf0, 0x36, 0x94, 0x5c, 0x91, 0x1c, 0x5d, 0xff, 0x2c, 0x83, @@ -5625,6 +5640,8 @@ static const int sizeof_bench_dilithium_level5_key = sizeof(bench_dilithium_leve #ifndef WOLFSSL_DILITHIUM_NO_VERIFY +/* raw public key without ASN1 syntax from + * ./certs/dilithium/bench_dilithium_level5_key.der */ static const unsigned char bench_dilithium_level5_pubkey[] = { 0xef, 0x49, 0x79, 0x47, 0x15, 0xc4, 0x8a, 0xa9, 0x74, 0x2a, 0xf0, 0x36, 0x94, 0x5c, 0x91, 0x1c, 0x5d, 0xff, 0x2c, 0x83, @@ -6076,10 +6093,10 @@ static const int sizeof_ecc_clikeypub_der_256 = sizeof(ecc_clikeypub_der_256); /* ./certs/client-ecc-cert.der, ECC */ static const unsigned char cliecc_cert_der_256[] = { - 0x30, 0x82, 0x03, 0x5D, 0x30, 0x82, 0x03, 0x04, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x37, 0x67, 0x2A, 0x05, 0x24, - 0xB5, 0x2B, 0xB6, 0xAE, 0x40, 0x6B, 0xE1, 0x75, 0xE0, 0x97, - 0xCC, 0x1D, 0x12, 0x8B, 0x2A, 0x30, 0x0A, 0x06, 0x08, 0x2A, + 0x30, 0x82, 0x03, 0x5E, 0x30, 0x82, 0x03, 0x04, 0xA0, 0x03, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x75, 0x99, 0xDB, 0x38, 0xED, + 0x32, 0xB1, 0xC2, 0xD1, 0x2C, 0x5E, 0x6F, 0x6F, 0x9D, 0x47, + 0x17, 0x58, 0xDD, 0xEE, 0x26, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x30, 0x81, 0x8D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x0F, 0x30, 0x0D, 0x06, 0x03, 0x55, @@ -6095,10 +6112,10 @@ static const unsigned char cliecc_cert_der_256[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x8D, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x33, 0x30, 0x5A, 0x30, 0x81, 0x8D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x0F, 0x30, 0x0D, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x06, 0x4F, 0x72, 0x65, 0x67, 0x6F, 0x6E, 0x31, 0x0E, 0x30, 0x0C, @@ -6144,9 +6161,9 @@ static const unsigned char cliecc_cert_der_256[] = 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, - 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x37, 0x67, 0x2A, 0x05, 0x24, - 0xB5, 0x2B, 0xB6, 0xAE, 0x40, 0x6B, 0xE1, 0x75, 0xE0, 0x97, - 0xCC, 0x1D, 0x12, 0x8B, 0x2A, 0x30, 0x0C, 0x06, 0x03, 0x55, + 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x75, 0x99, 0xDB, 0x38, 0xED, + 0x32, 0xB1, 0xC2, 0xD1, 0x2C, 0x5E, 0x6F, 0x6F, 0x9D, 0x47, + 0x17, 0x58, 0xDD, 0xEE, 0x26, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, @@ -6155,14 +6172,14 @@ static const unsigned char cliecc_cert_der_256[] = 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, - 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x7A, - 0x6D, 0xC5, 0xBD, 0x6F, 0x9D, 0x54, 0x4F, 0xC5, 0x4C, 0xD0, - 0x12, 0x8C, 0x31, 0x3B, 0xB6, 0x17, 0x80, 0x9E, 0xC7, 0x34, - 0xF8, 0xC5, 0xDA, 0xFB, 0x61, 0x23, 0x35, 0xE6, 0x93, 0x35, - 0xB4, 0x02, 0x20, 0x1B, 0x6A, 0x86, 0xC4, 0x11, 0xBE, 0x7C, - 0x15, 0xA7, 0x5E, 0xAB, 0x85, 0xEE, 0xB7, 0x8C, 0x20, 0xDC, - 0xEB, 0x17, 0xA3, 0xF2, 0x66, 0x63, 0xAA, 0x6B, 0x67, 0xE0, - 0x62, 0x1F, 0x17, 0x3E, 0xAC + 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x03, + 0x69, 0x31, 0x45, 0x6F, 0x01, 0x88, 0x6B, 0x63, 0xC6, 0x1C, + 0xEB, 0x39, 0xE4, 0x9A, 0xA8, 0xE2, 0xE0, 0x34, 0xAC, 0xAC, + 0xE6, 0xA1, 0xD6, 0xFE, 0xCE, 0x85, 0x98, 0x1E, 0xB0, 0x0D, + 0xA9, 0x02, 0x21, 0x00, 0xA3, 0xDD, 0x84, 0x5D, 0x08, 0x28, + 0x4B, 0x8B, 0x58, 0xFB, 0x0D, 0x33, 0xDB, 0x02, 0xEA, 0xC8, + 0x0C, 0xDA, 0x34, 0x0B, 0x4E, 0x83, 0xA2, 0x10, 0x67, 0x99, + 0x19, 0x1C, 0x93, 0x91, 0xC8, 0xC7 }; static const int sizeof_cliecc_cert_der_256 = sizeof(cliecc_cert_der_256); @@ -6224,9 +6241,9 @@ static const int sizeof_ecc_secp_r1_statickey_der_256 = sizeof(ecc_secp_r1_stati static const unsigned char serv_ecc_comp_der_256[] = { 0x30, 0x82, 0x03, 0x77, 0x30, 0x82, 0x03, 0x1D, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x21, 0xD7, 0x53, 0x80, 0x24, - 0x5C, 0xEB, 0xBF, 0xC0, 0xA4, 0x40, 0xF4, 0x42, 0x19, 0x3B, - 0x83, 0xFD, 0x58, 0xC5, 0xA6, 0x30, 0x0A, 0x06, 0x08, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x0C, 0x33, 0x75, 0x68, 0xFF, + 0x2E, 0x13, 0x4A, 0x2A, 0x30, 0x56, 0xB4, 0xA8, 0x79, 0x14, + 0xE2, 0xC4, 0xCA, 0x61, 0x54, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x30, 0x81, 0xA0, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, @@ -6244,10 +6261,10 @@ static const unsigned char serv_ecc_comp_der_256[] = 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, - 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, 0x33, - 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, 0x32, - 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, 0x32, - 0x38, 0x5A, 0x30, 0x81, 0xA0, 0x31, 0x0B, 0x30, 0x09, 0x06, + 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, 0x38, + 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, 0x0D, 0x32, + 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, 0x33, + 0x30, 0x5A, 0x30, 0x81, 0xA0, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, 0x30, 0x0E, @@ -6294,8 +6311,8 @@ static const unsigned char serv_ecc_comp_der_256[] = 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, - 0x21, 0xD7, 0x53, 0x80, 0x24, 0x5C, 0xEB, 0xBF, 0xC0, 0xA4, - 0x40, 0xF4, 0x42, 0x19, 0x3B, 0x83, 0xFD, 0x58, 0xC5, 0xA6, + 0x0C, 0x33, 0x75, 0x68, 0xFF, 0x2E, 0x13, 0x4A, 0x2A, 0x30, + 0x56, 0xB4, 0xA8, 0x79, 0x14, 0xE2, 0xC4, 0xCA, 0x61, 0x54, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, @@ -6305,14 +6322,14 @@ static const unsigned char serv_ecc_comp_der_256[] = 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, - 0x30, 0x45, 0x02, 0x20, 0x57, 0x1A, 0x59, 0xBC, 0xC9, 0x45, - 0x0A, 0x46, 0xE6, 0x16, 0xDA, 0x17, 0xCE, 0xC3, 0x0A, 0x57, - 0x57, 0xF2, 0x3D, 0x15, 0xCD, 0xCA, 0x1B, 0xA7, 0xA8, 0x39, - 0x2E, 0x9D, 0x09, 0xF3, 0x3E, 0xA0, 0x02, 0x21, 0x00, 0xDE, - 0xA3, 0x3A, 0x4D, 0x88, 0x38, 0x2B, 0x3A, 0x84, 0xDE, 0x2F, - 0x0A, 0x81, 0x14, 0x57, 0x7F, 0x7F, 0x2E, 0xD6, 0xA5, 0x4D, - 0x61, 0x10, 0x69, 0xB9, 0xA2, 0xC6, 0x51, 0xCD, 0x80, 0x4A, - 0x63 + 0x30, 0x45, 0x02, 0x20, 0x23, 0xD1, 0xF6, 0x8F, 0xD4, 0x29, + 0x83, 0x27, 0x8F, 0x4A, 0x8E, 0x49, 0x44, 0x49, 0x32, 0x1C, + 0x12, 0xE4, 0xC1, 0x33, 0xB1, 0x97, 0x2B, 0x31, 0xCD, 0x62, + 0x47, 0xCB, 0xB6, 0xD0, 0xEB, 0x4D, 0x02, 0x21, 0x00, 0xE0, + 0x6E, 0xDC, 0x48, 0x70, 0xAA, 0x10, 0xB2, 0x74, 0xD1, 0x88, + 0xDA, 0xF1, 0x3F, 0xD9, 0xD7, 0xE9, 0xE4, 0x88, 0xE5, 0x91, + 0x00, 0x03, 0xC1, 0x0C, 0x1F, 0x54, 0xA0, 0xCA, 0x4D, 0x99, + 0x6A }; static const int sizeof_serv_ecc_comp_der_256 = sizeof(serv_ecc_comp_der_256); @@ -6337,10 +6354,10 @@ static const unsigned char serv_ecc_rsa_der_256[] = 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, - 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, - 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, - 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, - 0x39, 0x32, 0x38, 0x5A, 0x30, 0x81, 0x9D, 0x31, 0x0B, 0x30, + 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, + 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, + 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, + 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0x9D, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, 0x10, @@ -6388,9 +6405,9 @@ static const unsigned char serv_ecc_rsa_der_256[] = 0x2E, 0x63, 0x6F, 0x6D, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, - 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x33, - 0x44, 0x1A, 0xA8, 0x6C, 0x01, 0xEC, 0xF6, 0x60, 0xF2, 0x70, - 0x51, 0x0A, 0x4C, 0xD1, 0x14, 0xFA, 0xBC, 0xE9, 0x44, 0x30, + 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x6B, + 0x9B, 0x70, 0xC6, 0xF1, 0xA3, 0x94, 0x65, 0x19, 0xA1, 0x08, + 0x58, 0xEF, 0xA7, 0x8D, 0x2B, 0x7A, 0x83, 0xC1, 0xDA, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, @@ -6400,32 +6417,32 @@ static const unsigned char serv_ecc_rsa_der_256[] = 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, - 0x82, 0x01, 0x01, 0x00, 0x16, 0xB7, 0xD3, 0x9C, 0x7C, 0x6E, - 0xD2, 0xB7, 0x79, 0xAA, 0x5A, 0x16, 0x0B, 0x1E, 0xDA, 0xD0, - 0xF7, 0xDF, 0x64, 0xC9, 0x3C, 0xB8, 0x41, 0x24, 0x4B, 0x1B, - 0xC2, 0x83, 0x5E, 0xDF, 0xDE, 0xA8, 0x8A, 0x7C, 0xEB, 0x07, - 0x75, 0x20, 0xF6, 0xF3, 0x4C, 0xBD, 0x3F, 0x2E, 0xF0, 0xF0, - 0xDA, 0x4B, 0xC5, 0xD2, 0xC4, 0xF8, 0xDB, 0x34, 0x75, 0xE2, - 0x32, 0xB4, 0x34, 0x92, 0x8A, 0x7F, 0xD7, 0x84, 0xEA, 0xDF, - 0x99, 0xCA, 0x64, 0xE6, 0x7C, 0x68, 0x05, 0x1C, 0x75, 0xDE, - 0x3F, 0x06, 0x65, 0x5D, 0xFC, 0x29, 0xC9, 0x73, 0x0F, 0x4A, - 0xAD, 0xFD, 0xBC, 0x0D, 0x91, 0x37, 0x67, 0x63, 0x55, 0x65, - 0x93, 0x99, 0x56, 0x84, 0x25, 0x1B, 0xF1, 0x50, 0x03, 0x31, - 0x2D, 0x48, 0xAD, 0xA3, 0x38, 0x91, 0x29, 0x88, 0xB8, 0x72, - 0x08, 0x4C, 0x11, 0x36, 0x35, 0x20, 0x13, 0x78, 0x98, 0xD8, - 0x84, 0x30, 0xC5, 0x7B, 0x70, 0x24, 0x45, 0x8C, 0xE1, 0x55, - 0x80, 0x06, 0x5F, 0x19, 0x57, 0x89, 0x58, 0x1C, 0x2A, 0x40, - 0xFB, 0xF3, 0xA6, 0xBF, 0xEA, 0x41, 0x7A, 0x79, 0x2C, 0xAB, - 0xFE, 0xB6, 0x16, 0x5D, 0xD5, 0xFA, 0x32, 0x50, 0x9D, 0x89, - 0xF2, 0xCC, 0x87, 0x7A, 0x57, 0xCF, 0x4D, 0x38, 0xC4, 0xD5, - 0x33, 0x9A, 0x4D, 0x83, 0xC9, 0x00, 0xB8, 0x36, 0x66, 0x14, - 0x76, 0x20, 0xC1, 0x7A, 0xC7, 0xF7, 0x0A, 0x94, 0x69, 0xCE, - 0x0A, 0x0F, 0x81, 0x04, 0x12, 0x5F, 0x71, 0xD0, 0xD1, 0xFF, - 0x08, 0xD0, 0x89, 0x6F, 0xAC, 0x45, 0xD3, 0x06, 0x23, 0xA0, - 0x76, 0x88, 0xAD, 0x5D, 0x9A, 0x7A, 0x8C, 0x1F, 0x61, 0xD4, - 0xD8, 0x21, 0x1D, 0x8E, 0x05, 0x89, 0xD1, 0xD4, 0xD6, 0x86, - 0x5B, 0x4B, 0x43, 0xE6, 0x03, 0x4A, 0x10, 0x48, 0xF4, 0x1B, - 0x9D, 0x3B, 0x76, 0xD8, 0x2C, 0xAD, 0xFA, 0x33, 0xA5, 0x70 + 0x82, 0x01, 0x01, 0x00, 0x38, 0xE8, 0x66, 0xC3, 0x74, 0xE0, + 0x5C, 0x59, 0xA9, 0x12, 0x46, 0xAD, 0x84, 0xE3, 0xB3, 0xFA, + 0x3E, 0x68, 0x90, 0xD0, 0x06, 0xA4, 0x2C, 0xAB, 0xF7, 0xB3, + 0xB9, 0x7C, 0x89, 0x62, 0xFB, 0x88, 0xEB, 0x88, 0x04, 0xD9, + 0x4B, 0xAC, 0x7E, 0x4B, 0x4B, 0x7C, 0x7C, 0x0F, 0xE1, 0xDD, + 0x73, 0xEE, 0x88, 0xB3, 0xE7, 0x1E, 0x00, 0x7B, 0xFE, 0xAA, + 0x24, 0x50, 0xD7, 0x3C, 0xC4, 0x03, 0xF2, 0xBA, 0xFD, 0x81, + 0xCE, 0x7A, 0x0C, 0x1C, 0x48, 0x6A, 0x33, 0xAD, 0xA7, 0xF8, + 0xF7, 0xCA, 0xF7, 0x00, 0x47, 0x5C, 0xFC, 0xF8, 0x05, 0x98, + 0x5F, 0xEC, 0xC3, 0xAA, 0x75, 0x93, 0x03, 0xA1, 0x4E, 0x7A, + 0x37, 0xEC, 0x8B, 0xA9, 0x99, 0xFA, 0x76, 0x85, 0xCB, 0xC3, + 0x99, 0x29, 0x70, 0x1E, 0x9C, 0x41, 0xF1, 0x49, 0xFD, 0xE8, + 0xC0, 0x75, 0x0A, 0xDD, 0xA0, 0xE0, 0xD3, 0x6E, 0x7F, 0x93, + 0x7E, 0x4D, 0x2E, 0xEE, 0xA1, 0xC9, 0xDB, 0xFC, 0x98, 0x86, + 0xBB, 0x67, 0x7D, 0x2F, 0x74, 0x00, 0x10, 0x7C, 0x24, 0x5B, + 0x58, 0xF3, 0x5A, 0xED, 0x96, 0x6E, 0x8F, 0x34, 0xEE, 0x47, + 0x46, 0xBE, 0x3E, 0x96, 0x25, 0x2B, 0x7C, 0x90, 0x5B, 0x65, + 0x24, 0x48, 0x66, 0x5A, 0x79, 0xA6, 0x6A, 0xF5, 0xED, 0x31, + 0xCF, 0x0B, 0x29, 0xC3, 0xF1, 0xAB, 0x91, 0x21, 0x9C, 0x79, + 0x99, 0xC9, 0x5C, 0x4C, 0x2B, 0xAC, 0xF1, 0x21, 0x5C, 0x44, + 0x07, 0x14, 0x45, 0xE5, 0xE0, 0x84, 0xCE, 0xA3, 0x49, 0x59, + 0x8D, 0x94, 0x4A, 0x9D, 0x11, 0x20, 0xC3, 0xD3, 0xFC, 0xCE, + 0x8F, 0x2C, 0x38, 0x5B, 0x38, 0xE7, 0xB2, 0xD0, 0x71, 0x9F, + 0x3F, 0xDE, 0x4E, 0x08, 0x03, 0xF9, 0x11, 0x58, 0x7C, 0x46, + 0x04, 0x0A, 0x73, 0x28, 0x68, 0xB8, 0x17, 0x17, 0x02, 0x45, + 0x9C, 0x65, 0x96, 0x1A, 0xB3, 0x98, 0x4D, 0x3B, 0xFB, 0xC7 }; static const int sizeof_serv_ecc_rsa_der_256 = sizeof(serv_ecc_rsa_der_256); @@ -6451,10 +6468,10 @@ static const unsigned char serv_ecc_der_256[] = 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, - 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, - 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, - 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, - 0x39, 0x32, 0x38, 0x5A, 0x30, 0x81, 0x90, 0x31, 0x0B, 0x30, + 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, + 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, + 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, + 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0x90, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x57, 0x61, 0x73, 0x68, 0x69, 0x6E, 0x67, 0x74, 0x6F, @@ -6494,13 +6511,13 @@ static const unsigned char serv_ecc_der_256[] = 0x01, 0x86, 0xF8, 0x42, 0x01, 0x01, 0x04, 0x04, 0x03, 0x02, 0x06, 0x40, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, - 0x21, 0x00, 0x86, 0xBD, 0x87, 0x16, 0xD2, 0x9C, 0x66, 0xE7, - 0x5E, 0x5C, 0x28, 0x0E, 0x5F, 0xEF, 0x94, 0x61, 0x2F, 0xD4, - 0x21, 0x6D, 0x8E, 0xC3, 0x94, 0x0A, 0x1E, 0xB5, 0x6A, 0x1D, - 0xC6, 0x04, 0x87, 0xC6, 0x02, 0x20, 0x66, 0x46, 0xC4, 0x29, - 0xD9, 0x8E, 0xEB, 0x0B, 0xF7, 0x5B, 0x32, 0x13, 0xEB, 0x0A, - 0xEA, 0x47, 0x99, 0x4B, 0x74, 0x56, 0xBA, 0x21, 0x97, 0xB1, - 0x67, 0x75, 0x5C, 0xF3, 0xF3, 0xC0, 0x88, 0xAA + 0x21, 0x00, 0x8B, 0x82, 0xA5, 0xD2, 0xF6, 0xCA, 0x84, 0xBA, + 0xAD, 0x2D, 0xDE, 0x36, 0xE9, 0x2A, 0x4D, 0xEE, 0x4B, 0x20, + 0x46, 0xBA, 0xAB, 0x4E, 0xD0, 0x10, 0x6E, 0xEB, 0x30, 0xB6, + 0x7E, 0xD8, 0xAF, 0x8C, 0x02, 0x20, 0x06, 0x74, 0x40, 0x6A, + 0xA9, 0x31, 0x54, 0xFE, 0x20, 0x9D, 0xC6, 0x6D, 0x2B, 0xDF, + 0x1D, 0xAA, 0x63, 0xDA, 0xFC, 0x97, 0x50, 0x87, 0x92, 0x69, + 0xEE, 0x63, 0x57, 0xB6, 0xEC, 0xE2, 0xE9, 0xFA }; static const int sizeof_serv_ecc_der_256 = sizeof(serv_ecc_der_256); @@ -6527,9 +6544,9 @@ static const int sizeof_ca_ecc_key_der_256 = sizeof(ca_ecc_key_der_256); static const unsigned char ca_ecc_cert_der_256[] = { 0x30, 0x82, 0x02, 0x95, 0x30, 0x82, 0x02, 0x3B, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x0F, 0x17, 0x46, 0x70, 0xFD, - 0xC2, 0x70, 0xD1, 0xF9, 0x42, 0x49, 0x9C, 0x1A, 0xC3, 0x5D, - 0xDD, 0x30, 0xC8, 0x5F, 0x85, 0x30, 0x0A, 0x06, 0x08, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x30, 0xB9, 0x30, 0x50, 0xF8, + 0x1A, 0x0D, 0xFF, 0xAD, 0x68, 0xD1, 0x6D, 0xE8, 0xA3, 0x6B, + 0x58, 0x23, 0x33, 0x7A, 0x84, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, @@ -6546,10 +6563,10 @@ static const unsigned char ca_ecc_cert_der_256[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x57, 0x61, 0x73, 0x68, 0x69, 0x6E, 0x67, 0x74, 0x6F, 0x6E, @@ -6585,14 +6602,14 @@ static const unsigned char ca_ecc_cert_der_256[] = 0x01, 0x01, 0xFF, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, 0x03, 0x02, 0x01, 0x86, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, - 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0xC8, - 0x64, 0x7F, 0xEE, 0x4B, 0xBE, 0x83, 0x48, 0x13, 0xEA, 0x92, - 0xF8, 0x1A, 0x82, 0x1E, 0x85, 0xB1, 0x5A, 0xA4, 0x1C, 0xE3, - 0xE8, 0xEA, 0x25, 0x44, 0x6F, 0xE7, 0x70, 0xFD, 0xEB, 0xF3, - 0x76, 0x02, 0x20, 0x44, 0x02, 0xA2, 0xEC, 0xC5, 0xA1, 0xAE, - 0xE2, 0xA4, 0x8A, 0xD9, 0x13, 0x95, 0x2B, 0xA6, 0x5B, 0x09, - 0x57, 0x86, 0x61, 0x42, 0x96, 0x97, 0xF0, 0x95, 0x62, 0x0C, - 0x03, 0xE6, 0x53, 0x04, 0x25 + 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0x88, + 0xCC, 0x7F, 0x00, 0xF5, 0xA9, 0x4E, 0xC0, 0x69, 0x6E, 0x36, + 0x39, 0x24, 0x8F, 0x83, 0x45, 0x4D, 0xFA, 0xD0, 0x39, 0x14, + 0xB8, 0xC8, 0x7F, 0x95, 0x51, 0xF2, 0xC5, 0x98, 0xC0, 0xB7, + 0xE2, 0x02, 0x20, 0x2A, 0x93, 0x61, 0xB0, 0x06, 0xDE, 0xEB, + 0xDA, 0xFD, 0xAF, 0x6B, 0x39, 0xBF, 0x88, 0x17, 0xF1, 0xBA, + 0x2A, 0x7D, 0x59, 0xA8, 0xDE, 0xE7, 0x0A, 0x11, 0x83, 0x4F, + 0x92, 0x77, 0x8D, 0x92, 0x3B }; static const int sizeof_ca_ecc_cert_der_256 = sizeof(ca_ecc_cert_der_256); @@ -6623,9 +6640,9 @@ static const int sizeof_ca_ecc_key_der_384 = sizeof(ca_ecc_key_der_384); static const unsigned char ca_ecc_cert_der_384[] = { 0x30, 0x82, 0x02, 0xD2, 0x30, 0x82, 0x02, 0x58, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x2E, 0xEA, 0xF0, 0x11, 0x40, - 0x1E, 0xAD, 0xFA, 0xA7, 0x85, 0x68, 0x65, 0x7A, 0x25, 0x2B, - 0x13, 0xB7, 0x61, 0xD7, 0x80, 0x30, 0x0A, 0x06, 0x08, 0x2A, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x4E, 0x08, 0x67, 0x9D, 0x29, + 0x61, 0x47, 0x3E, 0x2A, 0x23, 0x82, 0xCD, 0xCF, 0xCB, 0x53, + 0x2A, 0xB8, 0x02, 0x22, 0x57, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, @@ -6642,10 +6659,10 @@ static const unsigned char ca_ecc_cert_der_384[] = 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, 0x63, 0x6F, - 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, - 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x38, 0x5A, 0x17, 0x0D, - 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x38, 0x5A, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, + 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, + 0x38, 0x32, 0x31, 0x32, 0x35, 0x32, 0x39, 0x5A, 0x17, 0x0D, + 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, + 0x32, 0x39, 0x5A, 0x30, 0x81, 0x97, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x57, 0x61, 0x73, 0x68, 0x69, 0x6E, 0x67, 0x74, 0x6F, 0x6E, @@ -6684,17 +6701,17 @@ static const unsigned char ca_ecc_cert_der_384[] = 0x01, 0xFF, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, 0x03, 0x02, 0x01, 0x86, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, - 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, 0x31, 0x00, 0xBD, 0x2E, - 0x67, 0x71, 0x54, 0xBE, 0xB8, 0x5E, 0x29, 0x19, 0xD3, 0x18, - 0xF7, 0xE1, 0xAE, 0x79, 0xF0, 0xCC, 0x09, 0xC3, 0x91, 0xC0, - 0x81, 0xAB, 0xD7, 0xB7, 0x21, 0xF8, 0x4F, 0xDA, 0xBC, 0xAD, - 0x0E, 0xFC, 0x3D, 0x54, 0x32, 0x21, 0x3A, 0x67, 0xC5, 0x26, - 0x35, 0xE9, 0x33, 0xB2, 0x58, 0xD2, 0x02, 0x30, 0x64, 0x2F, - 0xFB, 0x10, 0xD0, 0x65, 0xB5, 0xAC, 0xBB, 0xB3, 0x41, 0x64, - 0x24, 0xEB, 0x0A, 0x6B, 0xAE, 0xA4, 0xED, 0x3E, 0xC8, 0x62, - 0x81, 0x45, 0x97, 0x92, 0xAD, 0x61, 0xEB, 0x69, 0x54, 0xCE, - 0x42, 0x83, 0xBB, 0x68, 0x23, 0x20, 0xF7, 0xB2, 0x5A, 0x55, - 0x0C, 0xD4, 0xE6, 0x13, 0x42, 0x61 + 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, 0x30, 0x1D, 0x3F, 0x92, + 0x02, 0xB2, 0x46, 0x54, 0xEE, 0x9E, 0x0D, 0x90, 0x03, 0x73, + 0x6A, 0xAB, 0x04, 0x5A, 0x41, 0xFE, 0xF4, 0x1B, 0xFD, 0xD6, + 0x99, 0xCC, 0x7A, 0x6C, 0xFD, 0x52, 0xDA, 0x2E, 0x4E, 0x78, + 0xFE, 0xEF, 0x79, 0x74, 0x12, 0x5E, 0x04, 0x9D, 0x2C, 0xE4, + 0xE7, 0x1A, 0x4D, 0xD3, 0x1E, 0x02, 0x31, 0x00, 0xB7, 0x34, + 0xE8, 0x4C, 0x69, 0x70, 0xDB, 0xFD, 0x1A, 0x48, 0xC5, 0xDC, + 0x8E, 0xEF, 0x15, 0xCA, 0x13, 0xEE, 0xF8, 0x4F, 0x27, 0x5F, + 0xD2, 0x3A, 0x6A, 0x06, 0x7D, 0xF3, 0x32, 0xA7, 0x75, 0x97, + 0x27, 0x6D, 0x60, 0xED, 0xA2, 0x9F, 0x9F, 0x7E, 0x66, 0x43, + 0xF9, 0x15, 0x1D, 0x65, 0x5D, 0x49 }; static const int sizeof_ca_ecc_cert_der_384 = sizeof(ca_ecc_cert_der_384); @@ -6783,9 +6800,9 @@ static const unsigned char server_ed25519_cert[] = 0x6D, 0x31, 0x17, 0x30, 0x15, 0x06, 0x0A, 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01, 0x0C, 0x07, 0x77, 0x6F, 0x6C, 0x66, 0x53, 0x53, 0x4C, 0x30, 0x1E, 0x17, 0x0D, - 0x32, 0x33, 0x31, 0x32, 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, - 0x32, 0x39, 0x5A, 0x17, 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, - 0x38, 0x32, 0x32, 0x31, 0x39, 0x32, 0x39, 0x5A, 0x30, 0x81, + 0x32, 0x34, 0x31, 0x32, 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, + 0x33, 0x30, 0x5A, 0x17, 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, + 0x34, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0xB8, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, @@ -6823,14 +6840,14 @@ static const unsigned char server_ed25519_cert[] = 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x11, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x42, 0x01, 0x01, 0x04, 0x04, 0x03, 0x02, 0x06, 0x40, 0x30, - 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x03, 0x41, 0x00, 0x22, - 0xD7, 0x34, 0xAC, 0x33, 0x65, 0x8B, 0x18, 0xA4, 0x34, 0xF9, - 0x3A, 0xE6, 0xCE, 0xC1, 0x77, 0xA6, 0x3D, 0x2A, 0x2A, 0xEE, - 0x22, 0xAD, 0x6E, 0xFC, 0x36, 0xFC, 0x98, 0x8D, 0x8A, 0xFD, - 0x3F, 0xCB, 0xA9, 0x74, 0x01, 0x25, 0x96, 0x05, 0xE1, 0x39, - 0x13, 0x8B, 0xD9, 0x05, 0x6D, 0xC9, 0xBA, 0x0E, 0x5D, 0x36, - 0xBF, 0x39, 0x03, 0x57, 0x2A, 0x55, 0xFC, 0xE3, 0x53, 0xC3, - 0x1B, 0xE1, 0x0B + 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x03, 0x41, 0x00, 0x04, + 0x19, 0x32, 0xE4, 0x24, 0xE5, 0xDF, 0x5A, 0xA4, 0x19, 0xC4, + 0x31, 0x15, 0x81, 0x05, 0x4C, 0x45, 0x0A, 0x40, 0x4A, 0x5D, + 0x6A, 0x8B, 0x0A, 0x77, 0x02, 0xFE, 0x48, 0x82, 0xD2, 0x83, + 0x8D, 0xDE, 0x42, 0xB8, 0xCF, 0x02, 0xDC, 0x64, 0x2C, 0xBD, + 0x8C, 0x9D, 0x22, 0x16, 0xD8, 0x7A, 0x23, 0x65, 0x5D, 0xB0, + 0x25, 0x92, 0xAC, 0xA8, 0x6C, 0xDE, 0xDF, 0x1D, 0xEB, 0x64, + 0xE4, 0x8A, 0x06 }; static const int sizeof_server_ed25519_cert = sizeof(server_ed25519_cert); @@ -6866,10 +6883,10 @@ static const unsigned char ca_ed25519_cert[] = 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x10, 0x69, 0x6E, 0x66, 0x6F, 0x40, 0x77, 0x6F, 0x6C, 0x66, 0x73, 0x73, 0x6C, 0x2E, - 0x63, 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, - 0x32, 0x31, 0x33, 0x32, 0x32, 0x31, 0x39, 0x32, 0x39, 0x5A, - 0x17, 0x0D, 0x32, 0x36, 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, - 0x31, 0x39, 0x32, 0x39, 0x5A, 0x30, 0x81, 0xB4, 0x31, 0x0B, + 0x63, 0x6F, 0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, + 0x32, 0x31, 0x38, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, + 0x17, 0x0D, 0x32, 0x37, 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, + 0x32, 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0xB4, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, 0x6E, 0x74, 0x61, 0x6E, 0x61, 0x31, @@ -6903,13 +6920,13 @@ static const unsigned char ca_ed25519_cert[] = 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, 0x03, 0x02, 0x01, 0x86, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, - 0x03, 0x41, 0x00, 0xE6, 0x71, 0xA0, 0x59, 0x63, 0xB4, 0x31, - 0x31, 0x1F, 0x75, 0x06, 0xCE, 0xF1, 0x89, 0xF0, 0xE7, 0xA2, - 0xDB, 0xA8, 0xC1, 0xE4, 0xC8, 0x61, 0x38, 0x0C, 0xE6, 0xE9, - 0xE7, 0xB9, 0x9F, 0xCE, 0xE2, 0xF5, 0x49, 0xA3, 0xF5, 0x04, - 0x1E, 0x85, 0xF7, 0x7D, 0x10, 0xFB, 0x1D, 0xEE, 0xB6, 0xDC, - 0x5E, 0x51, 0xF1, 0x82, 0x33, 0xA4, 0xED, 0xE0, 0x0A, 0x65, - 0x09, 0x2B, 0x0E, 0x1E, 0xB2, 0xAF, 0x0B + 0x03, 0x41, 0x00, 0x44, 0xEB, 0x38, 0xC6, 0x27, 0xD4, 0x70, + 0x42, 0x3F, 0x9B, 0xA0, 0xD7, 0x90, 0x96, 0xD6, 0x6E, 0x42, + 0x38, 0x5B, 0x38, 0x38, 0x9F, 0x21, 0xCA, 0xB0, 0xFA, 0x5E, + 0x7C, 0x17, 0xB4, 0x32, 0x5C, 0xB3, 0x08, 0xA2, 0x65, 0x50, + 0xD7, 0x65, 0x6B, 0xF8, 0xA9, 0xEF, 0x0D, 0xD1, 0x54, 0x2D, + 0x4D, 0xB6, 0x0F, 0x42, 0x9E, 0x51, 0xF7, 0xDB, 0xA7, 0xBF, + 0x16, 0x23, 0xC4, 0xBD, 0x7D, 0xC9, 0x03 }; static const int sizeof_ca_ed25519_cert = sizeof(ca_ed25519_cert); @@ -6917,9 +6934,9 @@ static const int sizeof_ca_ed25519_cert = sizeof(ca_ed25519_cert); static const unsigned char client_ed25519_cert[] = { 0x30, 0x82, 0x03, 0x9F, 0x30, 0x82, 0x03, 0x51, 0xA0, 0x03, - 0x02, 0x01, 0x02, 0x02, 0x14, 0x31, 0xE6, 0x4A, 0xB1, 0x6B, - 0x4E, 0x2E, 0x77, 0x7B, 0xD6, 0xE3, 0x94, 0x8A, 0xCF, 0x02, - 0xB7, 0x58, 0x5A, 0xFB, 0xAB, 0x30, 0x05, 0x06, 0x03, 0x2B, + 0x02, 0x01, 0x02, 0x02, 0x14, 0x33, 0x8B, 0x57, 0xD5, 0x8E, + 0x84, 0x67, 0x6A, 0xE1, 0xED, 0xF2, 0xB9, 0x11, 0x16, 0x5E, + 0x12, 0xE5, 0x0C, 0x78, 0x8A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x30, 0x81, 0xB8, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, @@ -6939,9 +6956,9 @@ static const unsigned char client_ed25519_cert[] = 0x2E, 0x63, 0x6F, 0x6D, 0x31, 0x17, 0x30, 0x15, 0x06, 0x0A, 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01, 0x0C, 0x07, 0x77, 0x6F, 0x6C, 0x66, 0x53, 0x53, 0x4C, 0x30, - 0x1E, 0x17, 0x0D, 0x32, 0x33, 0x31, 0x32, 0x31, 0x33, 0x32, - 0x32, 0x31, 0x39, 0x32, 0x39, 0x5A, 0x17, 0x0D, 0x32, 0x36, - 0x30, 0x39, 0x30, 0x38, 0x32, 0x32, 0x31, 0x39, 0x32, 0x39, + 0x1E, 0x17, 0x0D, 0x32, 0x34, 0x31, 0x32, 0x31, 0x38, 0x32, + 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x17, 0x0D, 0x32, 0x37, + 0x30, 0x39, 0x31, 0x34, 0x32, 0x31, 0x32, 0x35, 0x33, 0x30, 0x5A, 0x30, 0x81, 0xB8, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x4D, 0x6F, @@ -6992,9 +7009,9 @@ static const unsigned char client_ed25519_cert[] = 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x31, 0x17, 0x30, 0x15, 0x06, 0x0A, 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01, 0x0C, 0x07, 0x77, 0x6F, 0x6C, 0x66, 0x53, 0x53, 0x4C, - 0x82, 0x14, 0x31, 0xE6, 0x4A, 0xB1, 0x6B, 0x4E, 0x2E, 0x77, - 0x7B, 0xD6, 0xE3, 0x94, 0x8A, 0xCF, 0x02, 0xB7, 0x58, 0x5A, - 0xFB, 0xAB, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, + 0x82, 0x14, 0x33, 0x8B, 0x57, 0xD5, 0x8E, 0x84, 0x67, 0x6A, + 0xE1, 0xED, 0xF2, 0xB9, 0x11, 0x16, 0x5E, 0x12, 0xE5, 0x0C, + 0x78, 0x8A, 0x30, 0x0C, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x1C, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x15, 0x30, 0x13, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, @@ -7002,14 +7019,14 @@ static const unsigned char client_ed25519_cert[] = 0x55, 0x1D, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x05, 0x06, - 0x03, 0x2B, 0x65, 0x70, 0x03, 0x41, 0x00, 0x92, 0xAC, 0x52, - 0xCF, 0x34, 0xC2, 0x76, 0x8A, 0x78, 0xF7, 0xEF, 0xDA, 0x3F, - 0x79, 0xE9, 0x66, 0xD1, 0xDE, 0xE1, 0xD7, 0x56, 0xB5, 0x4B, - 0xCF, 0xA7, 0xC2, 0x03, 0xAF, 0xCC, 0x23, 0x11, 0x4B, 0x44, - 0x0C, 0x33, 0xCE, 0x45, 0xE0, 0x33, 0xEB, 0xCC, 0xC9, 0xF8, - 0x38, 0x5B, 0x19, 0x6F, 0x86, 0x4D, 0x97, 0x30, 0xD1, 0x55, - 0x6E, 0xCB, 0x5F, 0x39, 0xC9, 0xA3, 0x22, 0x16, 0x66, 0x5F, - 0x07 + 0x03, 0x2B, 0x65, 0x70, 0x03, 0x41, 0x00, 0xAA, 0xC7, 0xBD, + 0x8E, 0x56, 0x40, 0xAB, 0x7D, 0x9C, 0x55, 0xF0, 0x4D, 0x1D, + 0x97, 0xE9, 0x03, 0x62, 0x11, 0xCA, 0x51, 0xAD, 0x80, 0xCF, + 0x1A, 0x2C, 0x2C, 0x5B, 0x2D, 0x71, 0xFE, 0xDB, 0x1D, 0x4B, + 0xCD, 0x4B, 0x8B, 0x2D, 0x12, 0xF7, 0x01, 0xEE, 0xFB, 0x7D, + 0x2E, 0x21, 0xFC, 0x81, 0xDE, 0x84, 0x59, 0xC8, 0xA5, 0x1E, + 0x92, 0xE3, 0x21, 0x58, 0xD1, 0x3E, 0x8A, 0x71, 0x91, 0x2D, + 0x0E }; static const int sizeof_client_ed25519_cert = sizeof(client_ed25519_cert); diff --git a/src/wolfssl/crl.h b/src/wolfssl/crl.h index 5e5205e..cdf52f3 100644 --- a/src/wolfssl/crl.h +++ b/src/wolfssl/crl.h @@ -45,7 +45,10 @@ WOLFSSL_LOCAL int CheckCertCRL(WOLFSSL_CRL* crl, DecodedCert* cert); WOLFSSL_LOCAL int CheckCertCRL_ex(WOLFSSL_CRL* crl, byte* issuerHash, byte* serial, int serialSz, byte* serialHash, const byte* extCrlInfo, int extCrlInfoSz, void* issuerName); - +#ifdef HAVE_CRL_UPDATE_CB +WOLFSSL_LOCAL int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, + long sz, int type); +#endif #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/error-ssl.h b/src/wolfssl/error-ssl.h index 3130780..2d4d802 100644 --- a/src/wolfssl/error-ssl.h +++ b/src/wolfssl/error-ssl.h @@ -221,9 +221,28 @@ enum wolfSSL_ErrorCodes { HRR_COOKIE_ERROR = -505, /* HRR msg cookie mismatch */ UNSUPPORTED_CERTIFICATE = -506, /* unsupported certificate type */ - WOLFSSL_LAST_E = -506 + /* PEM and EVP errors */ + WOLFSSL_PEM_R_NO_START_LINE_E = -507, + WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E = -508, + WOLFSSL_PEM_R_BAD_PASSWORD_READ_E = -509, + WOLFSSL_PEM_R_BAD_DECRYPT_E = -510, + WOLFSSL_ASN1_R_HEADER_TOO_LONG_E = -511, + + WOLFSSL_EVP_R_BAD_DECRYPT_E = -512, + WOLFSSL_EVP_R_BN_DECODE_ERROR = -513, + WOLFSSL_EVP_R_DECODE_ERROR = -514, + WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR = -515, + + CRYPTO_POLICY_FORBIDDEN = -516, /* operation forbidden by system + * crypto-policy */ + + WOLFSSL_LAST_E = -516 + + /* codes -1000 to -1999 are reserved for wolfCrypt. */ }; +wc_static_assert((int)WC_LAST_E <= (int)WOLFSSL_LAST_E); + /* I/O Callback default errors */ enum IOerrors { WOLFSSL_CBIO_ERR_GENERAL = -1, /* general unexpected err */ diff --git a/src/wolfssl/evp.c b/src/wolfssl/evp.c index 808aa04..c3eb12e 100644 --- a/src/wolfssl/evp.c +++ b/src/wolfssl/evp.c @@ -41,7 +41,6 @@ #include #endif - #include #include #include @@ -53,67 +52,67 @@ static const struct s_ent { const char *name; } md_tbl[] = { #ifndef NO_MD4 - {WC_HASH_TYPE_MD4, NID_md4, "MD4"}, + {WC_HASH_TYPE_MD4, WC_NID_md4, "MD4"}, #endif /* NO_MD4 */ #ifndef NO_MD5 - {WC_HASH_TYPE_MD5, NID_md5, "MD5"}, + {WC_HASH_TYPE_MD5, WC_NID_md5, "MD5"}, #endif /* NO_MD5 */ #ifndef NO_SHA - {WC_HASH_TYPE_SHA, NID_sha1, "SHA1"}, - {WC_HASH_TYPE_SHA, NID_sha1, "SHA"}, /* Leave for backwards compatibility */ + {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA1"}, + {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA"}, /* Leave for backwards compatibility */ #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - {WC_HASH_TYPE_SHA224, NID_sha224, "SHA224"}, + {WC_HASH_TYPE_SHA224, WC_NID_sha224, "SHA224"}, #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 - {WC_HASH_TYPE_SHA256, NID_sha256, "SHA256"}, + {WC_HASH_TYPE_SHA256, WC_NID_sha256, "SHA256"}, #endif #ifdef WOLFSSL_SHA384 - {WC_HASH_TYPE_SHA384, NID_sha384, "SHA384"}, + {WC_HASH_TYPE_SHA384, WC_NID_sha384, "SHA384"}, #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 - {WC_HASH_TYPE_SHA512, NID_sha512, "SHA512"}, + {WC_HASH_TYPE_SHA512, WC_NID_sha512, "SHA512"}, #endif /* WOLFSSL_SHA512 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - {WC_HASH_TYPE_SHA512_224, NID_sha512_224, "SHA512_224"}, + {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, "SHA512_224"}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - {WC_HASH_TYPE_SHA512_256, NID_sha512_256, "SHA512_256"}, + {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, "SHA512_256"}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ #ifndef WOLFSSL_NOSHA3_224 - {WC_HASH_TYPE_SHA3_224, NID_sha3_224, "SHA3_224"}, + {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, "SHA3_224"}, #endif #ifndef WOLFSSL_NOSHA3_256 - {WC_HASH_TYPE_SHA3_256, NID_sha3_256, "SHA3_256"}, + {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, "SHA3_256"}, #endif #ifndef WOLFSSL_NOSHA3_384 - {WC_HASH_TYPE_SHA3_384, NID_sha3_384, "SHA3_384"}, + {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, "SHA3_384"}, #endif #ifndef WOLFSSL_NOSHA3_512 - {WC_HASH_TYPE_SHA3_512, NID_sha3_512, "SHA3_512"}, + {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, "SHA3_512"}, #endif #ifdef WOLFSSL_SM3 - {WC_HASH_TYPE_SM3, NID_sm3, "SM3"}, + {WC_HASH_TYPE_SM3, WC_NID_sm3, "SM3"}, #endif /* WOLFSSL_SHA512 */ #ifdef HAVE_BLAKE2 - {WC_HASH_TYPE_BLAKE2B, NID_blake2b512, "BLAKE2B512"}, + {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, "BLAKE2B512"}, #endif #ifdef HAVE_BLAKE2S - {WC_HASH_TYPE_BLAKE2S, NID_blake2s256, "BLAKE2S256"}, + {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, "BLAKE2S256"}, #endif #ifdef WOLFSSL_SHAKE128 - {WC_HASH_TYPE_SHAKE128, NID_shake128, "SHAKE128"}, + {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, "SHAKE128"}, #endif #ifdef WOLFSSL_SHAKE256 - {WC_HASH_TYPE_SHAKE256, NID_shake256, "SHAKE256"}, + {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, "SHAKE256"}, #endif {WC_HASH_TYPE_NONE, 0, NULL} }; @@ -158,6 +157,7 @@ static const struct s_ent { (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 static const char EVP_AES_128_CFB1[] = "AES-128-CFB1"; #endif @@ -177,6 +177,7 @@ static const struct s_ent { #ifdef WOLFSSL_AES_256 static const char EVP_AES_256_CFB8[] = "AES-256-CFB8"; #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 static const char EVP_AES_128_CFB128[] = "AES-128-CFB128"; @@ -287,21 +288,21 @@ static const struct pkey_type_name_ent { int type; const char *name; } pkey_type_names[] = { - { EVP_PKEY_RSA, "RSA" }, - { EVP_PKEY_EC, "EC" }, - { EVP_PKEY_DH, "DH" }, - { EVP_PKEY_DSA, "DSA" } + { WC_EVP_PKEY_RSA, "RSA" }, + { WC_EVP_PKEY_EC, "EC" }, + { WC_EVP_PKEY_DH, "DH" }, + { WC_EVP_PKEY_DSA, "DSA" } }; static int pkey_type_by_name(const char *name) { unsigned int i; if (name == NULL) - return EVP_PKEY_NONE; + return WC_EVP_PKEY_NONE; for (i = 0; i < XELEM_CNT(pkey_type_names); ++i) { if (XSTRCMP(name, pkey_type_names[i].name) == 0) return pkey_type_names[i].type; } - return EVP_PKEY_NONE; + return WC_EVP_PKEY_NONE; } int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { @@ -311,7 +312,7 @@ int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { return WOLFSSL_FAILURE; type = pkey_type_by_name(name); - if (type == EVP_PKEY_NONE) + if (type == WC_EVP_PKEY_NONE) return WOLFSSL_FAILURE; return (pkey->type == type) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; @@ -319,8 +320,8 @@ int wolfSSL_EVP_PKEY_is_a(const WOLFSSL_EVP_PKEY *pkey, const char *name) { #define EVP_CIPHER_TYPE_MATCHES(x, y) (XSTRCMP(x,y) == 0) -#define EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 -#define EVP_PKEY_PRINT_DIGITS_PER_LINE 15 +#define WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX 80 +#define WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE 15 static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher); @@ -346,81 +347,81 @@ int wolfSSL_EVP_Cipher_key_length(const WOLFSSL_EVP_CIPHER* c) switch (cipherType(c)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: return 16; - case AES_192_CBC_TYPE: return 24; - case AES_256_CBC_TYPE: return 32; + case WC_AES_128_CBC_TYPE: return 16; + case WC_AES_192_CBC_TYPE: return 24; + case WC_AES_256_CBC_TYPE: return 32; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: return 16; - case AES_192_CFB1_TYPE: return 24; - case AES_256_CFB1_TYPE: return 32; - case AES_128_CFB8_TYPE: return 16; - case AES_192_CFB8_TYPE: return 24; - case AES_256_CFB8_TYPE: return 32; - case AES_128_CFB128_TYPE: return 16; - case AES_192_CFB128_TYPE: return 24; - case AES_256_CFB128_TYPE: return 32; + case WC_AES_128_CFB1_TYPE: return 16; + case WC_AES_192_CFB1_TYPE: return 24; + case WC_AES_256_CFB1_TYPE: return 32; + case WC_AES_128_CFB8_TYPE: return 16; + case WC_AES_192_CFB8_TYPE: return 24; + case WC_AES_256_CFB8_TYPE: return 32; + case WC_AES_128_CFB128_TYPE: return 16; + case WC_AES_192_CFB128_TYPE: return 24; + case WC_AES_256_CFB128_TYPE: return 32; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: return 16; - case AES_192_OFB_TYPE: return 24; - case AES_256_OFB_TYPE: return 32; + case WC_AES_128_OFB_TYPE: return 16; + case WC_AES_192_OFB_TYPE: return 24; + case WC_AES_256_OFB_TYPE: return 32; #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) /* Two keys for XTS. */ - case AES_128_XTS_TYPE: return 16 * 2; - case AES_256_XTS_TYPE: return 32 * 2; + case WC_AES_128_XTS_TYPE: return 16 * 2; + case WC_AES_256_XTS_TYPE: return 32 * 2; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: return 16; - case AES_192_GCM_TYPE: return 24; - case AES_256_GCM_TYPE: return 32; + case WC_AES_128_GCM_TYPE: return 16; + case WC_AES_192_GCM_TYPE: return 24; + case WC_AES_256_GCM_TYPE: return 32; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: return 16; - case AES_192_CCM_TYPE: return 24; - case AES_256_CCM_TYPE: return 32; + case WC_AES_128_CCM_TYPE: return 16; + case WC_AES_192_CCM_TYPE: return 24; + case WC_AES_256_CCM_TYPE: return 32; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: return 16; - case AES_192_CTR_TYPE: return 24; - case AES_256_CTR_TYPE: return 32; + case WC_AES_128_CTR_TYPE: return 16; + case WC_AES_192_CTR_TYPE: return 24; + case WC_AES_256_CTR_TYPE: return 32; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: return 16; - case AES_192_ECB_TYPE: return 24; - case AES_256_ECB_TYPE: return 32; + case WC_AES_128_ECB_TYPE: return 16; + case WC_AES_192_ECB_TYPE: return 24; + case WC_AES_256_ECB_TYPE: return 32; #endif #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: return 8; - case DES_EDE3_CBC_TYPE: return 24; - case DES_ECB_TYPE: return 8; - case DES_EDE3_ECB_TYPE: return 24; + case WC_DES_CBC_TYPE: return 8; + case WC_DES_EDE3_CBC_TYPE: return 24; + case WC_DES_ECB_TYPE: return 8; + case WC_DES_EDE3_ECB_TYPE: return 24; #endif #ifndef NO_RC4 - case ARC4_TYPE: return 16; + case WC_ARC4_TYPE: return 16; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: return 32; + case WC_CHACHA20_POLY1305_TYPE: return 32; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: return CHACHA_MAX_KEY_SZ; + case WC_CHACHA20_TYPE: return CHACHA_MAX_KEY_SZ; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: return 16; + case WC_SM4_ECB_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: return 16; + case WC_SM4_CBC_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: return 16; + case WC_SM4_CTR_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: return 16; + case WC_SM4_GCM_TYPE: return 16; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: return 16; + case WC_SM4_CCM_TYPE: return 16; #endif default: return 0; @@ -603,9 +604,9 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, switch (ctx->cipherType) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: if (ctx->enc) ret = wc_AesCbcEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -613,16 +614,16 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: ret = wc_AesCtrEncrypt(&ctx->cipher.aes, out, in, inl); break; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: if (ctx->enc) ret = wc_AesEcbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -630,9 +631,9 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: if (ctx->enc) ret = wc_AesOfbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -640,10 +641,10 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_CFB) - #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: + #if !defined(WOLFSSL_NO_AES_CFB_1_8) + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: if (ctx->enc) ret = wc_AesCfb1Encrypt(&ctx->cipher.aes, out, in, inl * WOLFSSL_BIT_SIZE); @@ -652,19 +653,19 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, inl * WOLFSSL_BIT_SIZE); break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: if (ctx->enc) ret = wc_AesCfb8Encrypt(&ctx->cipher.aes, out, in, inl); else ret = wc_AesCfb8Decrypt(&ctx->cipher.aes, out, in, inl); break; - #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: if (ctx->enc) ret = wc_AesCfbEncrypt(&ctx->cipher.aes, out, in, inl); else @@ -672,8 +673,8 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: if (ctx->enc) ret = wc_AesXtsEncrypt(&ctx->cipher.xts, out, in, inl, ctx->iv, (word32)ctx->ivSz); @@ -684,34 +685,34 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, #endif #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: + case WC_DES_CBC_TYPE: if (ctx->enc) ret = wc_Des_CbcEncrypt(&ctx->cipher.des, out, in, inl); else ret = wc_Des_CbcDecrypt(&ctx->cipher.des, out, in, inl); break; - case DES_EDE3_CBC_TYPE: + case WC_DES_EDE3_CBC_TYPE: if (ctx->enc) ret = wc_Des3_CbcEncrypt(&ctx->cipher.des3, out, in, inl); else ret = wc_Des3_CbcDecrypt(&ctx->cipher.des3, out, in, inl); break; #if defined(WOLFSSL_DES_ECB) - case DES_ECB_TYPE: + case WC_DES_ECB_TYPE: ret = wc_Des_EcbEncrypt(&ctx->cipher.des, out, in, inl); break; - case DES_EDE3_ECB_TYPE: + case WC_DES_EDE3_ECB_TYPE: ret = wc_Des3_EcbEncrypt(&ctx->cipher.des3, out, in, inl); break; #endif #endif #ifndef NO_RC4 - case ARC4_TYPE: + case WC_ARC4_TYPE: wc_Arc4Process(&ctx->cipher.arc4, out, in, inl); break; #endif #if defined(WOLFSSL_SM4_ECB) - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: if (ctx->enc) wc_Sm4EcbEncrypt(&ctx->cipher.sm4, out, in, inl); else @@ -719,7 +720,7 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_SM4_CBC) - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: if (ctx->enc) wc_Sm4CbcEncrypt(&ctx->cipher.sm4, out, in, inl); else @@ -727,7 +728,7 @@ static int evpCipherBlock(WOLFSSL_EVP_CIPHER_CTX *ctx, break; #endif #if defined(WOLFSSL_SM4_CTR) - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: wc_Sm4CtrEncrypt(&ctx->cipher.sm4, out, in, inl); break; #endif @@ -783,7 +784,7 @@ static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx, #if defined(WOLFSSL_SM4_GCM) || !defined(WOLFSSL_AESGCM_STREAM) #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_AESGCM_STREAM) - if (ctx->cipherType == SM4_GCM_TYPE) + if (ctx->cipherType == WC_SM4_GCM_TYPE) #endif { int ret = 0; @@ -1059,29 +1060,29 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, switch (ctx->cipherType) { #if !defined(NO_AES) && defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_GCM(ctx, out, outl, in, inl); #endif /* !defined(NO_AES) && defined(HAVE_AESGCM) */ #if !defined(NO_AES) && defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: /* if out == NULL, in/inl contains the * additional auth data */ return wolfSSL_EVP_CipherUpdate_CCM(ctx, out, outl, in, inl); #endif /* !defined(NO_AES) && defined(HAVE_AESCCM) */ #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_AriaGCM(ctx, out, outl, in, inl); #endif /* defined(HAVE_ARIA) */ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: if (out == NULL) { if (wc_ChaCha20Poly1305_UpdateAad(&ctx->cipher.chachaPoly, in, (word32)inl) != 0) { @@ -1106,7 +1107,7 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, } #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: if (wc_Chacha_Process(&ctx->cipher.chacha, out, in, (word32)inl) != 0) { WOLFSSL_MSG("wc_ChaCha_Process failed"); @@ -1116,12 +1117,12 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, return WOLFSSL_SUCCESS; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: /* if out == NULL, in/inl contains the additional auth data */ return wolfSSL_EVP_CipherUpdate_GCM(ctx, out, outl, in, inl); #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: /* if out == NULL, in/inl contains the * additional auth data */ return wolfSSL_EVP_CipherUpdate_CCM(ctx, out, outl, in, inl); @@ -1274,9 +1275,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, switch (ctx->cipherType) { #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #ifndef WOLFSSL_AESGCM_STREAM if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { @@ -1347,7 +1348,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, } else { /* Clear IV, since IV reuse is not recommended for AES GCM. */ - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); } if (wolfSSL_StoreExternalIV(ctx) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FAILURE; @@ -1358,9 +1359,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) { @@ -1406,7 +1407,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, else { /* Clear IV, since IV reuse is not recommended * for AES CCM. */ - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); } if (wolfSSL_StoreExternalIV(ctx) != WOLFSSL_SUCCESS) { ret = WOLFSSL_FAILURE; @@ -1417,9 +1418,9 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_ARIA) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1471,7 +1472,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, #endif /* HAVE_AESGCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: if (wc_ChaCha20Poly1305_Final(&ctx->cipher.chachaPoly, ctx->authTag) != 0) { WOLFSSL_MSG("wc_ChaCha20Poly1305_Final failed"); @@ -1484,7 +1485,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1535,7 +1536,7 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: if ((ctx->authBuffer && ctx->authBufferLen > 0) || (ctx->authBufferLen == 0)) { if (ctx->enc) @@ -1660,20 +1661,20 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, */ if (FALSE #ifdef HAVE_AESGCM - || ctx->cipherType == AES_128_GCM_TYPE || - ctx->cipherType == AES_192_GCM_TYPE || - ctx->cipherType == AES_256_GCM_TYPE + || ctx->cipherType == WC_AES_128_GCM_TYPE || + ctx->cipherType == WC_AES_192_GCM_TYPE || + ctx->cipherType == WC_AES_256_GCM_TYPE #endif #ifdef HAVE_AESCCM - || ctx->cipherType == AES_128_CCM_TYPE || - ctx->cipherType == AES_192_CCM_TYPE || - ctx->cipherType == AES_256_CCM_TYPE + || ctx->cipherType == WC_AES_128_CCM_TYPE || + ctx->cipherType == WC_AES_192_CCM_TYPE || + ctx->cipherType == WC_AES_256_CCM_TYPE #endif #ifdef WOLFSSL_SM4_GCM - || ctx->cipherType == SM4_GCM_TYPE + || ctx->cipherType == WC_SM4_GCM_TYPE #endif #ifdef WOLFSSL_SM4_CCM - || ctx->cipherType == SM4_CCM_TYPE + || ctx->cipherType == WC_SM4_CCM_TYPE #endif ) { tmp = ctx->authIvGenEnable; @@ -1688,20 +1689,20 @@ int wolfSSL_EVP_CipherFinal(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *out, ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef HAVE_AESGCM - || ctx->cipherType == AES_128_GCM_TYPE || - ctx->cipherType == AES_192_GCM_TYPE || - ctx->cipherType == AES_256_GCM_TYPE + || ctx->cipherType == WC_AES_128_GCM_TYPE || + ctx->cipherType == WC_AES_192_GCM_TYPE || + ctx->cipherType == WC_AES_256_GCM_TYPE #endif #ifdef HAVE_AESCCM - || ctx->cipherType == AES_128_CCM_TYPE || - ctx->cipherType == AES_192_CCM_TYPE || - ctx->cipherType == AES_256_CCM_TYPE + || ctx->cipherType == WC_AES_128_CCM_TYPE || + ctx->cipherType == WC_AES_192_CCM_TYPE || + ctx->cipherType == WC_AES_256_CCM_TYPE #endif #ifdef WOLFSSL_SM4_GCM - || ctx->cipherType == SM4_GCM_TYPE + || ctx->cipherType == WC_SM4_GCM_TYPE #endif #ifdef WOLFSSL_SM4_CCM - || ctx->cipherType == SM4_CCM_TYPE + || ctx->cipherType == WC_SM4_CCM_TYPE #endif ) { ctx->authIvGenEnable = (tmp == 1); @@ -1769,75 +1770,75 @@ int wolfSSL_EVP_CIPHER_CTX_block_size(const WOLFSSL_EVP_CIPHER_CTX *ctx) #if !defined(NO_AES) || !defined(NO_DES3) || defined(WOLFSSL_SM4) #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: #endif #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: #endif - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: #endif /* !NO_AES */ #ifndef NO_DES3 - case DES_CBC_TYPE: - case DES_ECB_TYPE: - case DES_EDE3_CBC_TYPE: - case DES_EDE3_ECB_TYPE: + case WC_DES_CBC_TYPE: + case WC_DES_ECB_TYPE: + case WC_DES_EDE3_CBC_TYPE: + case WC_DES_EDE3_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: #endif return ctx->block_size; #endif /* !NO_AES || !NO_DES3 || WOLFSSL_SM4 */ @@ -1851,193 +1852,195 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) if (cipher == NULL) return 0; /* dummy for #ifdef */ #ifndef NO_DES3 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_CBC)) - return DES_CBC_TYPE; + return WC_DES_CBC_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_EDE3_CBC)) - return DES_EDE3_CBC_TYPE; + return WC_DES_EDE3_CBC_TYPE; #if !defined(NO_DES3) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_ECB)) - return DES_ECB_TYPE; + return WC_DES_ECB_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_DES_EDE3_ECB)) - return DES_EDE3_ECB_TYPE; + return WC_DES_EDE3_ECB_TYPE; #endif /* NO_DES3 && HAVE_AES_ECB */ #endif #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CBC)) - return AES_128_CBC_TYPE; + return WC_AES_128_CBC_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CBC)) - return AES_192_CBC_TYPE; + return WC_AES_192_CBC_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CBC)) - return AES_256_CBC_TYPE; + return WC_AES_256_CBC_TYPE; #endif #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ #if defined(HAVE_AESGCM) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_GCM)) - return AES_128_GCM_TYPE; + return WC_AES_128_GCM_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_GCM)) - return AES_192_GCM_TYPE; + return WC_AES_192_GCM_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_GCM)) - return AES_256_GCM_TYPE; + return WC_AES_256_GCM_TYPE; #endif #endif /* HAVE_AESGCM */ #if defined(HAVE_AESCCM) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CCM)) - return AES_128_CCM_TYPE; + return WC_AES_128_CCM_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CCM)) - return AES_192_CCM_TYPE; + return WC_AES_192_CCM_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CCM)) - return AES_256_CCM_TYPE; + return WC_AES_256_CCM_TYPE; #endif #endif /* HAVE_AESCCM */ #if defined(WOLFSSL_AES_COUNTER) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CTR)) - return AES_128_CTR_TYPE; + return WC_AES_128_CTR_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CTR)) - return AES_192_CTR_TYPE; + return WC_AES_192_CTR_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CTR)) - return AES_256_CTR_TYPE; + return WC_AES_256_CTR_TYPE; #endif #endif /* HAVE_AES_CBC */ #if defined(HAVE_AES_ECB) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_ECB)) - return AES_128_ECB_TYPE; + return WC_AES_128_ECB_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_ECB)) - return AES_192_ECB_TYPE; + return WC_AES_192_ECB_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_ECB)) - return AES_256_ECB_TYPE; + return WC_AES_256_ECB_TYPE; #endif #endif /*HAVE_AES_CBC */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_XTS)) - return AES_128_XTS_TYPE; + return WC_AES_128_XTS_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_XTS)) - return AES_256_XTS_TYPE; + return WC_AES_256_XTS_TYPE; #endif #endif /* WOLFSSL_AES_XTS */ #if defined(WOLFSSL_AES_CFB) +#ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB1)) - return AES_128_CFB1_TYPE; + return WC_AES_128_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB1)) - return AES_192_CFB1_TYPE; + return WC_AES_192_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB1)) - return AES_256_CFB1_TYPE; + return WC_AES_256_CFB1_TYPE; #endif #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB8)) - return AES_128_CFB8_TYPE; + return WC_AES_128_CFB8_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB8)) - return AES_192_CFB8_TYPE; + return WC_AES_192_CFB8_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB8)) - return AES_256_CFB8_TYPE; + return WC_AES_256_CFB8_TYPE; #endif +#endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_CFB128)) - return AES_128_CFB128_TYPE; + return WC_AES_128_CFB128_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_CFB128)) - return AES_192_CFB128_TYPE; + return WC_AES_192_CFB128_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_CFB128)) - return AES_256_CFB128_TYPE; + return WC_AES_256_CFB128_TYPE; #endif #endif /*HAVE_AES_CBC */ #if defined(WOLFSSL_AES_OFB) #ifdef WOLFSSL_AES_128 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_128_OFB)) - return AES_128_OFB_TYPE; + return WC_AES_128_OFB_TYPE; #endif #ifdef WOLFSSL_AES_192 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_192_OFB)) - return AES_192_OFB_TYPE; + return WC_AES_192_OFB_TYPE; #endif #ifdef WOLFSSL_AES_256 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_AES_256_OFB)) - return AES_256_OFB_TYPE; + return WC_AES_256_OFB_TYPE; #endif #endif #endif /* !NO_AES */ #if defined(HAVE_ARIA) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_128_GCM)) - return ARIA_128_GCM_TYPE; + return WC_ARIA_128_GCM_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_192_GCM)) - return ARIA_192_GCM_TYPE; + return WC_ARIA_192_GCM_TYPE; else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARIA_256_GCM)) - return ARIA_256_GCM_TYPE; + return WC_ARIA_256_GCM_TYPE; #endif /* HAVE_ARIA */ #ifndef NO_RC4 else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_ARC4)) - return ARC4_TYPE; + return WC_ARC4_TYPE; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_CHACHA20_POLY1305)) - return CHACHA20_POLY1305_TYPE; + return WC_CHACHA20_POLY1305_TYPE; #endif #ifdef HAVE_CHACHA else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_CHACHA20)) - return CHACHA20_TYPE; + return WC_CHACHA20_TYPE; #endif #ifdef WOLFSSL_SM4_ECB else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_ECB)) - return SM4_ECB_TYPE; + return WC_SM4_ECB_TYPE; #endif #ifdef WOLFSSL_SM4_CBC else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CBC)) - return SM4_CBC_TYPE; + return WC_SM4_CBC_TYPE; #endif #ifdef WOLFSSL_SM4_CTR else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CTR)) - return SM4_CTR_TYPE; + return WC_SM4_CTR_TYPE; #endif #ifdef WOLFSSL_SM4_GCM else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_GCM)) - return SM4_GCM_TYPE; + return WC_SM4_GCM_TYPE; #endif #ifdef WOLFSSL_SM4_CCM else if (EVP_CIPHER_TYPE_MATCHES(cipher, EVP_SM4_CCM)) - return SM4_CCM_TYPE; + return WC_SM4_CCM_TYPE; #endif else return 0; @@ -2051,107 +2054,107 @@ int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) switch (cipherType(cipher)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: - return AES_BLOCK_SIZE; + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: + return WC_AES_BLOCK_SIZE; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: return 1; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: return 1; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: return 1; #endif #if defined(HAVE_AES_ECB) - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: - return AES_BLOCK_SIZE; + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: + return WC_AES_BLOCK_SIZE; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: return 1; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: return 1; #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: return 1; #endif #endif /* NO_AES */ #ifndef NO_RC4 - case ARC4_TYPE: + case WC_ARC4_TYPE: return 1; #endif #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: return 1; #endif #ifndef NO_DES3 - case DES_CBC_TYPE: return 8; - case DES_EDE3_CBC_TYPE: return 8; - case DES_ECB_TYPE: return 8; - case DES_EDE3_ECB_TYPE: return 8; + case WC_DES_CBC_TYPE: return 8; + case WC_DES_EDE3_CBC_TYPE: return 8; + case WC_DES_ECB_TYPE: return 8; + case WC_DES_EDE3_ECB_TYPE: return 8; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: return 1; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: return 1; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: return 1; #endif @@ -2165,107 +2168,107 @@ unsigned long WOLFSSL_CIPHER_mode(const WOLFSSL_EVP_CIPHER *cipher) switch (cipherType(cipher)) { #if !defined(NO_AES) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; #endif #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: return WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #if defined(WOLFSSL_AES_COUNTER) - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: return WOLFSSL_EVP_CIPH_CTR_MODE; #endif #if defined(WOLFSSL_AES_CFB) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: return WOLFSSL_EVP_CIPH_CFB_MODE; #endif #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: return WOLFSSL_EVP_CIPH_OFB_MODE; #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: return WOLFSSL_EVP_CIPH_XTS_MODE; #endif - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif /* !NO_AES */ #if defined(HAVE_ARIA) - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifndef NO_DES3 - case DES_CBC_TYPE: - case DES_EDE3_CBC_TYPE: + case WC_DES_CBC_TYPE: + case WC_DES_EDE3_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; - case DES_ECB_TYPE: - case DES_EDE3_ECB_TYPE: + case WC_DES_ECB_TYPE: + case WC_DES_EDE3_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif #ifndef NO_RC4 - case ARC4_TYPE: - return EVP_CIPH_STREAM_CIPHER; + case WC_ARC4_TYPE: + return WOLFSSL_EVP_CIPH_STREAM_CIPHER; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: return WOLFSSL_EVP_CIPH_STREAM_CIPHER | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: return WOLFSSL_EVP_CIPH_STREAM_CIPHER; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: return WOLFSSL_EVP_CIPH_ECB_MODE; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: return WOLFSSL_EVP_CIPH_CBC_MODE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: return WOLFSSL_EVP_CIPH_CTR_MODE; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: return WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: return WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; #endif @@ -2374,7 +2377,7 @@ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_E XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_PKEY_CTX)); ctx->pkey = pkey; #if !defined(NO_RSA) - ctx->padding = RSA_PKCS1_PADDING; + ctx->padding = WC_RSA_PKCS1_PADDING; ctx->md = NULL; #endif #ifdef HAVE_ECC @@ -2416,7 +2419,7 @@ int wolfSSL_EVP_PKEY_CTX_set_rsa_padding(WOLFSSL_EVP_PKEY_CTX *ctx, int padding) * returns WOLFSSL_SUCCESS on success. */ int wolfSSL_EVP_PKEY_CTX_set_signature_md(WOLFSSL_EVP_PKEY_CTX *ctx, - const EVP_MD* md) + const WOLFSSL_EVP_MD* md) { if (ctx == NULL) return 0; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_signature_md"); @@ -2468,7 +2471,7 @@ int wolfSSL_EVP_PKEY_derive_init(WOLFSSL_EVP_PKEY_CTX *ctx) return WOLFSSL_FAILURE; } wolfSSL_EVP_PKEY_free(ctx->peerKey); - ctx->op = EVP_PKEY_OP_DERIVE; + ctx->op = WC_EVP_PKEY_OP_DERIVE; ctx->padding = 0; ctx->nbits = 0; return WOLFSSL_SUCCESS; @@ -2478,7 +2481,7 @@ int wolfSSL_EVP_PKEY_derive_set_peer(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY { WOLFSSL_ENTER("wolfSSL_EVP_PKEY_derive_set_peer"); - if (!ctx || ctx->op != EVP_PKEY_OP_DERIVE) { + if (!ctx || ctx->op != WC_EVP_PKEY_OP_DERIVE) { return WOLFSSL_FAILURE; } wolfSSL_EVP_PKEY_free(ctx->peerKey); @@ -2513,14 +2516,14 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ WOLFSSL_ENTER("wolfSSL_EVP_PKEY_derive"); - if (!ctx || ctx->op != EVP_PKEY_OP_DERIVE || !ctx->pkey || (!ctx->peerKey - && ctx->pkey->type != EVP_PKEY_HKDF) || !keylen || (ctx->pkey->type - != EVP_PKEY_HKDF && ctx->pkey->type != ctx->peerKey->type)) { + if (!ctx || ctx->op != WC_EVP_PKEY_OP_DERIVE || !ctx->pkey || (!ctx->peerKey + && ctx->pkey->type != WC_EVP_PKEY_HKDF) || !keylen || (ctx->pkey->type + != WC_EVP_PKEY_HKDF && ctx->pkey->type != ctx->peerKey->type)) { return WOLFSSL_FAILURE; } switch (ctx->pkey->type) { #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: /* Use DH */ if (!ctx->pkey->dh || !ctx->peerKey->dh) { return WOLFSSL_FAILURE; @@ -2553,7 +2556,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ break; #endif #if defined(HAVE_ECC) && !defined(WOLF_CRYPTO_CB_ONLY_ECC) - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: /* Use ECDH */ if (!ctx->pkey->ecc || !ctx->peerKey->ecc) { return WOLFSSL_FAILURE; @@ -2621,7 +2624,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ break; #endif #ifdef HAVE_HKDF - case EVP_PKEY_HKDF: + case WC_EVP_PKEY_HKDF: (void)len; hkdfHashType = EvpMd2MacType(ctx->pkey->hkdfMd); @@ -2629,7 +2632,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ WOLFSSL_MSG("Invalid hash type for HKDF."); return WOLFSSL_FAILURE; } - if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { + if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { if (wc_HKDF(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, @@ -2638,7 +2641,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ return WOLFSSL_FAILURE; } } - else if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { + else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { if (wc_HKDF_Extract(hkdfHashType, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, key) != 0) { @@ -2655,7 +2658,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ *keylen = (size_t)hkdfHashSz; } } - else if (ctx->pkey->hkdfMode == EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { + else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { if (wc_HKDF_Expand(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, @@ -2711,7 +2714,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_salt(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2746,7 +2749,7 @@ int wolfSSL_EVP_PKEY_CTX_set1_hkdf_key(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2781,7 +2784,7 @@ int wolfSSL_EVP_PKEY_CTX_add1_hkdf_info(WOLFSSL_EVP_PKEY_CTX* ctx, WOLFSSL_MSG("Bad argument."); ret = WOLFSSL_FAILURE; } - if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != EVP_PKEY_HKDF) { + if (ret == WOLFSSL_SUCCESS && ctx->pkey->type != WC_EVP_PKEY_HKDF) { WOLFSSL_MSG("WOLFSSL_EVP_PKEY type is not HKDF."); ret = WOLFSSL_FAILURE; } @@ -2831,9 +2834,10 @@ int wolfSSL_EVP_PKEY_CTX_hkdf_mode(WOLFSSL_EVP_PKEY_CTX* ctx, int mode) } if (ret == WOLFSSL_SUCCESS && - mode != EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND && - mode != EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY && - mode != EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND && + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY && + mode != WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) + { WOLFSSL_MSG("Invalid HKDF mode."); ret = WOLFSSL_FAILURE; } @@ -2881,7 +2885,7 @@ int wolfSSL_EVP_PKEY_decrypt(WOLFSSL_EVP_PKEY_CTX *ctx, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (out == NULL) { if (ctx->pkey->rsa == NULL) { WOLFSSL_MSG("Internal wolfCrypt RSA object is NULL."); @@ -2910,8 +2914,8 @@ int wolfSSL_EVP_PKEY_decrypt(WOLFSSL_EVP_PKEY_CTX *ctx, } #endif /* NO_RSA */ - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not implemented."); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not implemented."); FALL_THROUGH; default: break; @@ -2932,10 +2936,10 @@ int wolfSSL_EVP_PKEY_decrypt_init(WOLFSSL_EVP_PKEY_CTX *ctx) if (ctx == NULL) return WOLFSSL_FAILURE; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_decrypt_init"); switch (ctx->pkey->type) { - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_DECRYPT; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_DECRYPT; return WOLFSSL_SUCCESS; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -2970,8 +2974,8 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, return 0; } - if (ctx->op != EVP_PKEY_OP_ENCRYPT) { - WOLFSSL_MSG("ctx->op must be set to EVP_PKEY_OP_ENCRYPT. Use " + if (ctx->op != WC_EVP_PKEY_OP_ENCRYPT) { + WOLFSSL_MSG("ctx->op must be set to WC_EVP_PKEY_OP_ENCRYPT. Use " "wolfSSL_EVP_PKEY_encrypt_init."); return WOLFSSL_FAILURE; } @@ -2984,7 +2988,7 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (out == NULL) { if (ctx->pkey->rsa == NULL) { WOLFSSL_MSG("Internal wolfCrypt RSA object is NULL."); @@ -3014,8 +3018,8 @@ int wolfSSL_EVP_PKEY_encrypt(WOLFSSL_EVP_PKEY_CTX *ctx, } #endif /* NO_RSA */ - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not implemented"); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not implemented"); FALL_THROUGH; default: break; @@ -3037,10 +3041,10 @@ int wolfSSL_EVP_PKEY_encrypt_init(WOLFSSL_EVP_PKEY_CTX *ctx) WOLFSSL_ENTER("wolfSSL_EVP_PKEY_encrypt_init"); switch (ctx->pkey->type) { - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_ENCRYPT; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_ENCRYPT; return WOLFSSL_SUCCESS; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -3065,22 +3069,22 @@ int wolfSSL_EVP_PKEY_sign_init(WOLFSSL_EVP_PKEY_CTX *ctx) switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_DSA: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: - ctx->op = EVP_PKEY_OP_SIGN; + case WC_EVP_PKEY_EC: + ctx->op = WC_EVP_PKEY_OP_SIGN; ret = WOLFSSL_SUCCESS; break; #endif /* HAVE_ECC */ @@ -3103,7 +3107,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, { WOLFSSL_MSG("wolfSSL_EVP_PKEY_sign"); - if (!ctx || ctx->op != EVP_PKEY_OP_SIGN || !ctx->pkey || !siglen) + if (!ctx || ctx->op != WC_EVP_PKEY_OP_SIGN || !ctx->pkey || !siglen) return WOLFSSL_FAILURE; (void)sig; @@ -3113,7 +3117,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { unsigned int usiglen = (unsigned int)*siglen; if (!sig) { int len; @@ -3138,7 +3142,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int bytes; int ret; if (!ctx->pkey->dsa) @@ -3165,7 +3169,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig; if (!sig) { @@ -3227,20 +3231,20 @@ int wolfSSL_EVP_PKEY_verify_init(WOLFSSL_EVP_PKEY_CTX *ctx) switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_RSA: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_DSA: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: - ctx->op = EVP_PKEY_OP_VERIFY; + case WC_EVP_PKEY_EC: + ctx->op = WC_EVP_PKEY_OP_VERIFY; return WOLFSSL_SUCCESS; #endif /* HAVE_ECC */ @@ -3264,19 +3268,19 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, { WOLFSSL_MSG("wolfSSL_EVP_PKEY_verify"); - if (!ctx || ctx->op != EVP_PKEY_OP_VERIFY || !ctx->pkey) + if (!ctx || ctx->op != WC_EVP_PKEY_OP_VERIFY || !ctx->pkey) return WOLFSSL_FAILURE; switch (ctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: return wolfSSL_RSA_verify_ex(WC_HASH_TYPE_NONE, tbs, (unsigned int)tbslen, sig, (unsigned int)siglen, ctx->pkey->rsa, ctx->padding); #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int dsacheck = 0; if (wolfSSL_DSA_do_verify(tbs, (unsigned char *)sig, ctx->pkey->dsa, &dsacheck) != WOLFSSL_SUCCESS || dsacheck != 1) @@ -3286,7 +3290,7 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, #endif /* NO_DSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( NULL, (const unsigned char **)&sig, (long)siglen); @@ -3334,7 +3338,7 @@ int wolfSSL_EVP_PKEY_CTX_set_ec_paramgen_curve_nid(WOLFSSL_EVP_PKEY_CTX *ctx, { WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_ec_paramgen_curve_nid"); #ifdef HAVE_ECC - if (ctx != NULL && ctx->pkey != NULL && ctx->pkey->type == EVP_PKEY_EC) { + if (ctx != NULL && ctx->pkey != NULL && ctx->pkey->type == WC_EVP_PKEY_EC) { ctx->curveNID = nid; return WOLFSSL_SUCCESS; } @@ -3367,7 +3371,7 @@ int wolfSSL_EVP_PKEY_paramgen(WOLFSSL_EVP_PKEY_CTX* ctx, if (ret == WOLFSSL_SUCCESS && *pkey == NULL) { /* Only ECC is supported currently. */ - if (ctx->pkey == NULL || ctx->pkey->type != EVP_PKEY_EC) { + if (ctx->pkey == NULL || ctx->pkey->type != WC_EVP_PKEY_EC) { WOLFSSL_MSG("Key not set or key type not supported."); ret = WOLFSSL_FAILURE; } @@ -3388,7 +3392,7 @@ int wolfSSL_EVP_PKEY_paramgen(WOLFSSL_EVP_PKEY_CTX* ctx, #ifdef HAVE_ECC /* For ECC parameter generation we just need to set the group, which * wolfSSL_EC_KEY_new_by_curve_name will do. */ - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: (*pkey)->ecc = wolfSSL_EC_KEY_new_by_curve_name(ctx->curveNID); if ((*pkey)->ecc == NULL) { WOLFSSL_MSG("Failed to create WOLFSSL_EC_KEY."); @@ -3451,9 +3455,9 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, pkey = *ppkey; if (pkey == NULL) { if (ctx->pkey == NULL || - (ctx->pkey->type != EVP_PKEY_EC && - ctx->pkey->type != EVP_PKEY_RSA && - ctx->pkey->type != EVP_PKEY_DH)) { + (ctx->pkey->type != WC_EVP_PKEY_EC && + ctx->pkey->type != WC_EVP_PKEY_RSA && + ctx->pkey->type != WC_EVP_PKEY_DH)) { WOLFSSL_MSG("Key not set or key type not supported"); return WOLFSSL_FAILURE; } @@ -3467,7 +3471,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, switch (pkey->type) { #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: pkey->rsa = wolfSSL_RSA_generate_key(ctx->nbits, WC_RSA_EXPONENT, NULL, NULL); if (pkey->rsa) { @@ -3479,7 +3483,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: /* pkey->ecc may not be NULL, if, for example, it was populated by a * prior call to wolfSSL_EVP_PKEY_paramgen. */ if (pkey->ecc == NULL) { @@ -3494,7 +3498,7 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, break; #endif #if !defined(NO_DH) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: pkey->dh = wolfSSL_DH_new(); if (pkey->dh) { pkey->ownDh = 1; @@ -3540,12 +3544,12 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) switch (pkey->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: return (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(pkey->rsa)); #endif /* !NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (pkey->dsa == NULL || (!pkey->dsa->exSet && SetDsaExternal(pkey->dsa) != WOLFSSL_SUCCESS)) @@ -3554,7 +3558,7 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (pkey->ecc == NULL || pkey->ecc->internal == NULL) { WOLFSSL_MSG("No ECC key has been set"); break; @@ -3579,7 +3583,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, return WOLFSSL_FAILURE; } - if (to->type == EVP_PKEY_NONE) { + if (to->type == WC_EVP_PKEY_NONE) { to->type = from->type; } else if (to->type != from->type) { @@ -3589,7 +3593,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, switch(from->type) { #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (from->ecc) { if (!to->ecc) { if ((to->ecc = wolfSSL_EC_KEY_new()) == NULL) { @@ -3609,7 +3613,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (from->dsa) { WOLFSSL_BIGNUM* cpy; if (!to->dsa) { @@ -3651,7 +3655,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: if (from->dh) { WOLFSSL_BIGNUM* cpy; if (!to->dh) { @@ -3693,7 +3697,7 @@ int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to, break; #endif #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #endif default: WOLFSSL_MSG("Copy parameters not available for this key type"); @@ -3740,13 +3744,13 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) /* get size based on key type */ switch (a->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: a_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)); b_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)); break; #endif /* !NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (a->ecc == NULL || a->ecc->internal == NULL || b->ecc == NULL || b->ecc->internal == NULL) { return ret; @@ -3885,23 +3889,23 @@ int wolfSSL_EVP_PKEY_param_check(WOLFSSL_EVP_PKEY_CTX* ctx) type = wolfSSL_EVP_PKEY_type(wolfSSL_EVP_PKEY_base_id(ctx->pkey)); switch (type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: - WOLFSSL_MSG("EVP_PKEY_RSA not yet implemented"); + case WC_EVP_PKEY_RSA: + WOLFSSL_MSG("WC_EVP_PKEY_RSA not yet implemented"); return WOLFSSL_FAILURE; #endif #if defined(HAVE_ECC) - case EVP_PKEY_EC: - WOLFSSL_MSG("EVP_PKEY_EC not yet implemented"); + case WC_EVP_PKEY_EC: + WOLFSSL_MSG("WC_EVP_PKEY_EC not yet implemented"); return WOLFSSL_FAILURE; #endif #if !defined(NO_DSA) - case EVP_PKEY_DSA: - WOLFSSL_MSG("EVP_PKEY_DSA not yet implemented"); + case WC_EVP_PKEY_DSA: + WOLFSSL_MSG("WC_EVP_PKEY_DSA not yet implemented"); return WOLFSSL_FAILURE; #endif #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || defined(WOLFSSL_OPENSSH) #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: dh_key = wolfSSL_EVP_PKEY_get1_DH(ctx->pkey); if (dh_key != NULL) { ret = DH_param_check(dh_key); @@ -4001,7 +4005,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, switch (pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *ctxmd; @@ -4017,7 +4021,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, } #endif /* NO_RSA */ #ifndef NO_DSA - case EVP_PKEY_DSA: { + case WC_EVP_PKEY_DSA: { int bytes; ret = wolfSSL_DSA_do_sign(md, sigret, pkey->dsa); /* wolfSSL_DSA_do_sign() can return WOLFSSL_FATAL_ERROR */ @@ -4034,7 +4038,7 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, } #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_ECDSA_do_sign(md, (int)mdsize, pkey->ecc); if (ecdsaSig == NULL) @@ -4115,7 +4119,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, switch (pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *ctxmd = wolfSSL_EVP_MD_CTX_md(ctx); if (ctxmd == NULL) break; @@ -4126,7 +4130,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, } #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { WOLFSSL_ECDSA_SIG *ecdsaSig = wolfSSL_d2i_ECDSA_SIG( NULL, (const unsigned char **)&sig, (long)siglen); if (ecdsaSig == NULL) @@ -4137,7 +4141,7 @@ int wolfSSL_EVP_VerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, return ret; } #endif - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: WOLFSSL_MSG("not implemented"); FALL_THROUGH; default: @@ -4162,7 +4166,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_mac_key(int type, WOLFSSL_ENGINE* e, (void)e; - if (type != EVP_PKEY_HMAC || (key == NULL && keylen != 0)) + if (type != WC_EVP_PKEY_HMAC || (key == NULL && keylen != 0)) return NULL; pkey = wolfSSL_EVP_PKEY_new(); @@ -4228,7 +4232,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_EVP_PKEY_new_CMAC_key(WOLFSSL_ENGINE* e, XMEMCPY(pkey->pkey.ptr, priv, (size_t)len); } pkey->pkey_sz = (int)len; - pkey->type = pkey->save_type = EVP_PKEY_CMAC; + pkey->type = pkey->save_type = WC_EVP_PKEY_CMAC; pkey->cmacCtx = ctx; } } @@ -4354,7 +4358,7 @@ static int wolfSSL_evp_digest_pk_init(WOLFSSL_EVP_MD_CTX *ctx, } } - if (pkey->type == EVP_PKEY_HMAC) { + if (pkey->type == WC_EVP_PKEY_HMAC) { int hashType; int ret; size_t keySz = 0; @@ -4581,7 +4585,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, } } #ifndef NO_RSA - else if (ctx->pctx->pkey->type == EVP_PKEY_RSA) { + else if (ctx->pctx->pkey->type == WC_EVP_PKEY_RSA) { if (sig == NULL) { *siglen = (size_t)wolfSSL_RSA_size(ctx->pctx->pkey->rsa); return WOLFSSL_SUCCESS; @@ -4589,7 +4593,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, } #endif /* !NO_RSA */ #ifdef HAVE_ECC - else if (ctx->pctx->pkey->type == EVP_PKEY_EC) { + else if (ctx->pctx->pkey->type == WC_EVP_PKEY_EC) { if (sig == NULL) { /* SEQ + INT + INT */ *siglen = (size_t)ecc_sets[ctx->pctx->pkey->ecc->group->curve_idx]. @@ -4615,7 +4619,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, /* Sign the digest. */ switch (ctx->pctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { unsigned int sigSz = (unsigned int)*siglen; int nid; const WOLFSSL_EVP_MD *md = wolfSSL_EVP_MD_CTX_md(ctx); @@ -4633,7 +4637,7 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int len; WOLFSSL_ECDSA_SIG *ecdsaSig; ecdsaSig = wolfSSL_ECDSA_do_sign(digest, (int)hashLen, @@ -4718,7 +4722,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, /* Verify the signature with the digest. */ switch (ctx->pctx->pkey->type) { #if !defined(NO_RSA) - case EVP_PKEY_RSA: { + case WC_EVP_PKEY_RSA: { int nid; const WOLFSSL_EVP_MD *md = wolfSSL_EVP_MD_CTX_md(ctx); if (md == NULL) @@ -4733,7 +4737,7 @@ int wolfSSL_EVP_DigestVerifyFinal(WOLFSSL_EVP_MD_CTX *ctx, #endif /* NO_RSA */ #ifdef HAVE_ECC - case EVP_PKEY_EC: { + case WC_EVP_PKEY_EC: { int ret; WOLFSSL_ECDSA_SIG *ecdsaSig; ecdsaSig = wolfSSL_d2i_ECDSA_SIG(NULL, &sig, (long)siglen); @@ -4955,159 +4959,161 @@ static const struct cipher{ #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - {AES_128_CBC_TYPE, EVP_AES_128_CBC, NID_aes_128_cbc}, + {WC_AES_128_CBC_TYPE, EVP_AES_128_CBC, WC_NID_aes_128_cbc}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CBC_TYPE, EVP_AES_192_CBC, NID_aes_192_cbc}, + {WC_AES_192_CBC_TYPE, EVP_AES_192_CBC, WC_NID_aes_192_cbc}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CBC_TYPE, EVP_AES_256_CBC, NID_aes_256_cbc}, + {WC_AES_256_CBC_TYPE, EVP_AES_256_CBC, WC_NID_aes_256_cbc}, #endif #endif #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 - {AES_128_CFB1_TYPE, EVP_AES_128_CFB1, NID_aes_128_cfb1}, + {WC_AES_128_CFB1_TYPE, EVP_AES_128_CFB1, WC_NID_aes_128_cfb1}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB1_TYPE, EVP_AES_192_CFB1, NID_aes_192_cfb1}, + {WC_AES_192_CFB1_TYPE, EVP_AES_192_CFB1, WC_NID_aes_192_cfb1}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB1_TYPE, EVP_AES_256_CFB1, NID_aes_256_cfb1}, + {WC_AES_256_CFB1_TYPE, EVP_AES_256_CFB1, WC_NID_aes_256_cfb1}, #endif #ifdef WOLFSSL_AES_128 - {AES_128_CFB8_TYPE, EVP_AES_128_CFB8, NID_aes_128_cfb8}, + {WC_AES_128_CFB8_TYPE, EVP_AES_128_CFB8, WC_NID_aes_128_cfb8}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB8_TYPE, EVP_AES_192_CFB8, NID_aes_192_cfb8}, + {WC_AES_192_CFB8_TYPE, EVP_AES_192_CFB8, WC_NID_aes_192_cfb8}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB8_TYPE, EVP_AES_256_CFB8, NID_aes_256_cfb8}, + {WC_AES_256_CFB8_TYPE, EVP_AES_256_CFB8, WC_NID_aes_256_cfb8}, #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 - {AES_128_CFB128_TYPE, EVP_AES_128_CFB128, NID_aes_128_cfb128}, + {WC_AES_128_CFB128_TYPE, EVP_AES_128_CFB128, WC_NID_aes_128_cfb128}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CFB128_TYPE, EVP_AES_192_CFB128, NID_aes_192_cfb128}, + {WC_AES_192_CFB128_TYPE, EVP_AES_192_CFB128, WC_NID_aes_192_cfb128}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CFB128_TYPE, EVP_AES_256_CFB128, NID_aes_256_cfb128}, - #endif + {WC_AES_256_CFB128_TYPE, EVP_AES_256_CFB128, WC_NID_aes_256_cfb128}, #endif + #endif /* WOLFSSL_AES_CFB */ #ifdef WOLFSSL_AES_OFB #ifdef WOLFSSL_AES_128 - {AES_128_OFB_TYPE, EVP_AES_128_OFB, NID_aes_128_ofb}, + {WC_AES_128_OFB_TYPE, EVP_AES_128_OFB, WC_NID_aes_128_ofb}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_OFB_TYPE, EVP_AES_192_OFB, NID_aes_192_ofb}, + {WC_AES_192_OFB_TYPE, EVP_AES_192_OFB, WC_NID_aes_192_ofb}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_OFB_TYPE, EVP_AES_256_OFB, NID_aes_256_ofb}, + {WC_AES_256_OFB_TYPE, EVP_AES_256_OFB, WC_NID_aes_256_ofb}, #endif #endif #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 - {AES_128_XTS_TYPE, EVP_AES_128_XTS, NID_aes_128_xts}, + {WC_AES_128_XTS_TYPE, EVP_AES_128_XTS, WC_NID_aes_128_xts}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_XTS_TYPE, EVP_AES_256_XTS, NID_aes_256_xts}, + {WC_AES_256_XTS_TYPE, EVP_AES_256_XTS, WC_NID_aes_256_xts}, #endif #endif #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 - {AES_128_GCM_TYPE, EVP_AES_128_GCM, NID_aes_128_gcm}, + {WC_AES_128_GCM_TYPE, EVP_AES_128_GCM, WC_NID_aes_128_gcm}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_GCM_TYPE, EVP_AES_192_GCM, NID_aes_192_gcm}, + {WC_AES_192_GCM_TYPE, EVP_AES_192_GCM, WC_NID_aes_192_gcm}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_GCM_TYPE, EVP_AES_256_GCM, NID_aes_256_gcm}, + {WC_AES_256_GCM_TYPE, EVP_AES_256_GCM, WC_NID_aes_256_gcm}, #endif #endif #ifdef HAVE_AESCCM #ifdef WOLFSSL_AES_128 - {AES_128_CCM_TYPE, EVP_AES_128_CCM, NID_aes_128_ccm}, + {WC_AES_128_CCM_TYPE, EVP_AES_128_CCM, WC_NID_aes_128_ccm}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CCM_TYPE, EVP_AES_192_CCM, NID_aes_192_ccm}, + {WC_AES_192_CCM_TYPE, EVP_AES_192_CCM, WC_NID_aes_192_ccm}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CCM_TYPE, EVP_AES_256_CCM, NID_aes_256_ccm}, + {WC_AES_256_CCM_TYPE, EVP_AES_256_CCM, WC_NID_aes_256_ccm}, #endif #endif #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - {AES_128_CTR_TYPE, EVP_AES_128_CTR, NID_aes_128_ctr}, + {WC_AES_128_CTR_TYPE, EVP_AES_128_CTR, WC_NID_aes_128_ctr}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_CTR_TYPE, EVP_AES_192_CTR, NID_aes_192_ctr}, + {WC_AES_192_CTR_TYPE, EVP_AES_192_CTR, WC_NID_aes_192_ctr}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_CTR_TYPE, EVP_AES_256_CTR, NID_aes_256_ctr}, + {WC_AES_256_CTR_TYPE, EVP_AES_256_CTR, WC_NID_aes_256_ctr}, #endif #endif #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - {AES_128_ECB_TYPE, EVP_AES_128_ECB, NID_aes_128_ecb}, + {WC_AES_128_ECB_TYPE, EVP_AES_128_ECB, WC_NID_aes_128_ecb}, #endif #ifdef WOLFSSL_AES_192 - {AES_192_ECB_TYPE, EVP_AES_192_ECB, NID_aes_192_ecb}, + {WC_AES_192_ECB_TYPE, EVP_AES_192_ECB, WC_NID_aes_192_ecb}, #endif #ifdef WOLFSSL_AES_256 - {AES_256_ECB_TYPE, EVP_AES_256_ECB, NID_aes_256_ecb}, + {WC_AES_256_ECB_TYPE, EVP_AES_256_ECB, WC_NID_aes_256_ecb}, #endif #endif #endif #ifdef HAVE_ARIA - {ARIA_128_GCM_TYPE, EVP_ARIA_128_GCM, NID_aria_128_gcm}, - {ARIA_192_GCM_TYPE, EVP_ARIA_192_GCM, NID_aria_192_gcm}, - {ARIA_256_GCM_TYPE, EVP_ARIA_256_GCM, NID_aria_256_gcm}, + {WC_ARIA_128_GCM_TYPE, EVP_ARIA_128_GCM, WC_NID_aria_128_gcm}, + {WC_ARIA_192_GCM_TYPE, EVP_ARIA_192_GCM, WC_NID_aria_192_gcm}, + {WC_ARIA_256_GCM_TYPE, EVP_ARIA_256_GCM, WC_NID_aria_256_gcm}, #endif #ifndef NO_DES3 - {DES_CBC_TYPE, EVP_DES_CBC, NID_des_cbc}, - {DES_ECB_TYPE, EVP_DES_ECB, NID_des_ecb}, + {WC_DES_CBC_TYPE, EVP_DES_CBC, WC_NID_des_cbc}, + {WC_DES_ECB_TYPE, EVP_DES_ECB, WC_NID_des_ecb}, - {DES_EDE3_CBC_TYPE, EVP_DES_EDE3_CBC, NID_des_ede3_cbc}, - {DES_EDE3_ECB_TYPE, EVP_DES_EDE3_ECB, NID_des_ede3_ecb}, + {WC_DES_EDE3_CBC_TYPE, EVP_DES_EDE3_CBC, WC_NID_des_ede3_cbc}, + {WC_DES_EDE3_ECB_TYPE, EVP_DES_EDE3_ECB, WC_NID_des_ede3_ecb}, #endif #ifndef NO_RC4 - {ARC4_TYPE, EVP_ARC4, NID_undef}, + {WC_ARC4_TYPE, EVP_ARC4, WC_NID_undef}, #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - {CHACHA20_POLY1305_TYPE, EVP_CHACHA20_POLY1305, NID_chacha20_poly1305}, + {WC_CHACHA20_POLY1305_TYPE, EVP_CHACHA20_POLY1305, WC_NID_chacha20_poly1305}, #endif #ifdef HAVE_CHACHA - {CHACHA20_TYPE, EVP_CHACHA20, NID_chacha20}, + {WC_CHACHA20_TYPE, EVP_CHACHA20, WC_NID_chacha20}, #endif #ifdef WOLFSSL_SM4_ECB - {SM4_ECB_TYPE, EVP_SM4_ECB, NID_sm4_ecb}, + {WC_SM4_ECB_TYPE, EVP_SM4_ECB, WC_NID_sm4_ecb}, #endif #ifdef WOLFSSL_SM4_CBC - {SM4_CBC_TYPE, EVP_SM4_CBC, NID_sm4_cbc}, + {WC_SM4_CBC_TYPE, EVP_SM4_CBC, WC_NID_sm4_cbc}, #endif #ifdef WOLFSSL_SM4_CTR - {SM4_CTR_TYPE, EVP_SM4_CTR, NID_sm4_ctr}, + {WC_SM4_CTR_TYPE, EVP_SM4_CTR, WC_NID_sm4_ctr}, #endif #ifdef WOLFSSL_SM4_GCM - {SM4_GCM_TYPE, EVP_SM4_GCM, NID_sm4_gcm}, + {WC_SM4_GCM_TYPE, EVP_SM4_GCM, WC_NID_sm4_gcm}, #endif #ifdef WOLFSSL_SM4_CCM - {SM4_CCM_TYPE, EVP_SM4_CCM, NID_sm4_ccm}, + {WC_SM4_CCM_TYPE, EVP_SM4_CCM, WC_NID_sm4_ccm}, #endif { 0, NULL, 0} @@ -5293,128 +5299,128 @@ const WOLFSSL_EVP_CIPHER *wolfSSL_EVP_get_cipherbynid(int id) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - case NID_aes_128_cbc: + case WC_NID_aes_128_cbc: return wolfSSL_EVP_aes_128_cbc(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_cbc: + case WC_NID_aes_192_cbc: return wolfSSL_EVP_aes_192_cbc(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_cbc: + case WC_NID_aes_256_cbc: return wolfSSL_EVP_aes_256_cbc(); #endif #endif #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - case NID_aes_128_ctr: + case WC_NID_aes_128_ctr: return wolfSSL_EVP_aes_128_ctr(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ctr: + case WC_NID_aes_192_ctr: return wolfSSL_EVP_aes_192_ctr(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ctr: + case WC_NID_aes_256_ctr: return wolfSSL_EVP_aes_256_ctr(); #endif #endif /* WOLFSSL_AES_COUNTER */ #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - case NID_aes_128_ecb: + case WC_NID_aes_128_ecb: return wolfSSL_EVP_aes_128_ecb(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ecb: + case WC_NID_aes_192_ecb: return wolfSSL_EVP_aes_192_ecb(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ecb: + case WC_NID_aes_256_ecb: return wolfSSL_EVP_aes_256_ecb(); #endif #endif /* HAVE_AES_ECB */ #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 - case NID_aes_128_gcm: + case WC_NID_aes_128_gcm: return wolfSSL_EVP_aes_128_gcm(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_gcm: + case WC_NID_aes_192_gcm: return wolfSSL_EVP_aes_192_gcm(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_gcm: + case WC_NID_aes_256_gcm: return wolfSSL_EVP_aes_256_gcm(); #endif #endif #ifdef HAVE_AESCCM #ifdef WOLFSSL_AES_128 - case NID_aes_128_ccm: + case WC_NID_aes_128_ccm: return wolfSSL_EVP_aes_128_ccm(); #endif #ifdef WOLFSSL_AES_192 - case NID_aes_192_ccm: + case WC_NID_aes_192_ccm: return wolfSSL_EVP_aes_192_ccm(); #endif #ifdef WOLFSSL_AES_256 - case NID_aes_256_ccm: + case WC_NID_aes_256_ccm: return wolfSSL_EVP_aes_256_ccm(); #endif #endif #endif #ifdef HAVE_ARIA - case NID_aria_128_gcm: + case WC_NID_aria_128_gcm: return wolfSSL_EVP_aria_128_gcm(); - case NID_aria_192_gcm: + case WC_NID_aria_192_gcm: return wolfSSL_EVP_aria_192_gcm(); - case NID_aria_256_gcm: + case WC_NID_aria_256_gcm: return wolfSSL_EVP_aria_256_gcm(); #endif #ifndef NO_DES3 - case NID_des_cbc: + case WC_NID_des_cbc: return wolfSSL_EVP_des_cbc(); #ifdef WOLFSSL_DES_ECB - case NID_des_ecb: + case WC_NID_des_ecb: return wolfSSL_EVP_des_ecb(); #endif - case NID_des_ede3_cbc: + case WC_NID_des_ede3_cbc: return wolfSSL_EVP_des_ede3_cbc(); #ifdef WOLFSSL_DES_ECB - case NID_des_ede3_ecb: + case WC_NID_des_ede3_ecb: return wolfSSL_EVP_des_ede3_ecb(); #endif #endif /*NO_DES3*/ #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case NID_chacha20_poly1305: + case WC_NID_chacha20_poly1305: return wolfSSL_EVP_chacha20_poly1305(); #endif #ifdef HAVE_CHACHA - case NID_chacha20: + case WC_NID_chacha20: return wolfSSL_EVP_chacha20(); #endif #ifdef WOLFSSL_SM4_ECB - case NID_sm4_ecb: + case WC_NID_sm4_ecb: return wolfSSL_EVP_sm4_ecb(); #endif #ifdef WOLFSSL_SM4_CBC - case NID_sm4_cbc: + case WC_NID_sm4_cbc: return wolfSSL_EVP_sm4_cbc(); #endif #ifdef WOLFSSL_SM4_CTR - case NID_sm4_ctr: + case WC_NID_sm4_ctr: return wolfSSL_EVP_sm4_ctr(); #endif #ifdef WOLFSSL_SM4_GCM - case NID_sm4_gcm: + case WC_NID_sm4_gcm: return wolfSSL_EVP_sm4_gcm(); #endif #ifdef WOLFSSL_SM4_CCM - case NID_sm4_ccm: + case WC_NID_sm4_ccm: return wolfSSL_EVP_sm4_ccm(); #endif @@ -5622,7 +5628,7 @@ void wolfSSL_EVP_init(void) #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION3_GE(6,0,0)) + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb1(void) { @@ -5670,7 +5676,7 @@ void wolfSSL_EVP_init(void) return EVP_AES_256_CFB8; } #endif /* WOLFSSL_AES_256 */ -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_cfb128(void) @@ -5992,22 +5998,22 @@ void wolfSSL_EVP_init(void) WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_ctrl"); switch(type) { - case EVP_CTRL_INIT: + case WOLFSSL_EVP_CTRL_INIT: wolfSSL_EVP_CIPHER_CTX_init(ctx); if(ctx) ret = WOLFSSL_SUCCESS; break; - case EVP_CTRL_SET_KEY_LENGTH: + case WOLFSSL_EVP_CTRL_SET_KEY_LENGTH: ret = wolfSSL_EVP_CIPHER_CTX_set_key_length(ctx, arg); break; #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA) || \ defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) || \ (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IVLEN: + case WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_IV_SIZE) { break; } @@ -6015,7 +6021,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6023,7 +6029,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6031,7 +6037,7 @@ void wolfSSL_EVP_init(void) else #endif { - if (arg <= 0 || arg > AES_BLOCK_SIZE) + if (arg <= 0 || arg > WC_AES_BLOCK_SIZE) break; } ret = wolfSSL_EVP_CIPHER_CTX_set_iv_length(ctx, arg); @@ -6039,7 +6045,7 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_AESGCM) || defined(WOLFSSL_SM4_GCM) || \ (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) - case EVP_CTRL_AEAD_SET_IV_FIXED: + case WOLFSSL_EVP_CTRL_AEAD_SET_IV_FIXED: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; if (arg == -1) { @@ -6098,7 +6104,7 @@ void wolfSSL_EVP_init(void) * EVP_CipherInit between each iteration. The IV is incremented for * each subsequent EVP_Cipher call to prevent IV reuse. */ - case EVP_CTRL_GCM_IV_GEN: + case WOLFSSL_EVP_CTRL_GCM_IV_GEN: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; if (!ctx->authIvGenEnable) { @@ -6134,11 +6140,11 @@ void wolfSSL_EVP_init(void) break; #endif /* (HAVE_AESGCM || WOLFSSL_SM4_GCM) && !_WIN32 && !HAVE_SELFTEST && * !HAVE_FIPS || FIPS_VERSION >= 2)*/ - case EVP_CTRL_AEAD_SET_TAG: + case WOLFSSL_EVP_CTRL_AEAD_SET_TAG: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { break; } @@ -6152,7 +6158,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if ((arg <= 0) || (arg > SM4_BLOCK_SIZE) || (ptr == NULL)) { break; } @@ -6165,7 +6171,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if ((arg <= 0) || (arg > SM4_BLOCK_SIZE) || (ptr == NULL)) { break; } @@ -6186,12 +6192,12 @@ void wolfSSL_EVP_init(void) ret = WOLFSSL_SUCCESS; break; } - case EVP_CTRL_AEAD_GET_TAG: + case WOLFSSL_EVP_CTRL_AEAD_GET_TAG: if ((ctx->flags & WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER) == 0) break; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE) { + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE) { if (arg != CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE) { break; } @@ -6199,7 +6205,7 @@ void wolfSSL_EVP_init(void) else #endif /* HAVE_CHACHA && HAVE_POLY1305 */ #if defined(WOLFSSL_SM4_GCM) - if (ctx->cipherType == SM4_GCM_TYPE) { + if (ctx->cipherType == WC_SM4_GCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6207,7 +6213,7 @@ void wolfSSL_EVP_init(void) else #endif #if defined(WOLFSSL_SM4_CCM) - if (ctx->cipherType == SM4_CCM_TYPE) { + if (ctx->cipherType == WC_SM4_CCM_TYPE) { if (arg <= 0 || arg > SM4_BLOCK_SIZE) { break; } @@ -6215,7 +6221,7 @@ void wolfSSL_EVP_init(void) else #endif { - if (arg <= 0 || arg > AES_BLOCK_SIZE) + if (arg <= 0 || arg > WC_AES_BLOCK_SIZE) break; } @@ -6252,62 +6258,62 @@ void wolfSSL_EVP_init(void) defined(WOLFSSL_AES_XTS) #if defined(HAVE_AESGCM) - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: #endif /* HAVE_AESGCM */ #if defined(HAVE_AESCCM) - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: #endif /* HAVE_AESCCM */ #ifdef HAVE_AES_CBC - case AES_128_CBC_TYPE: - case AES_192_CBC_TYPE: - case AES_256_CBC_TYPE: + case WC_AES_128_CBC_TYPE: + case WC_AES_192_CBC_TYPE: + case WC_AES_256_CBC_TYPE: #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE: - case AES_192_CTR_TYPE: - case AES_256_CTR_TYPE: + case WC_AES_128_CTR_TYPE: + case WC_AES_192_CTR_TYPE: + case WC_AES_256_CTR_TYPE: #endif #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE: - case AES_192_ECB_TYPE: - case AES_256_ECB_TYPE: + case WC_AES_128_ECB_TYPE: + case WC_AES_192_ECB_TYPE: + case WC_AES_256_ECB_TYPE: #endif #ifdef WOLFSSL_AES_CFB - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: #endif #ifdef WOLFSSL_AES_OFB - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: #endif wc_AesFree(&ctx->cipher.aes); ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: wc_AesXtsFree(&ctx->cipher.xts); ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #endif #endif /* AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: { int result = wc_AriaFreeCrypt(&ctx->cipher.aria); if (result != 0) { @@ -6324,19 +6330,19 @@ void wolfSSL_EVP_init(void) #ifdef WOLFSSL_SM4 switch (ctx->cipherType) { #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: + case WC_SM4_ECB_TYPE: #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: + case WC_SM4_CBC_TYPE: #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: + case WC_SM4_CTR_TYPE: #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: + case WC_SM4_GCM_TYPE: #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: + case WC_SM4_CCM_TYPE: #endif wc_Sm4Free(&ctx->cipher.sm4); } @@ -6462,7 +6468,7 @@ void wolfSSL_EVP_init(void) /* wc_AesSetKey clear aes.reg if iv == NULL. Keep IV for openSSL compatibility */ if (iv == NULL) - XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, AES_BLOCK_SIZE); + XMEMCPY((byte *)aes->tmp, (byte *)aes->reg, WC_AES_BLOCK_SIZE); if (direct) { #if defined(WOLFSSL_AES_DIRECT) ret = wc_AesSetKeyDirect(aes, key, len, iv, dir); @@ -6474,7 +6480,7 @@ void wolfSSL_EVP_init(void) ret = wc_AesSetKey(aes, key, len, iv, dir); } if (iv == NULL) - XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, AES_BLOCK_SIZE); + XMEMCPY((byte *)aes->reg, (byte *)aes->tmp, WC_AES_BLOCK_SIZE); return ret; } #endif /* AES_ANY_SIZE && AES_SET_KEY */ @@ -6492,8 +6498,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6505,26 +6511,26 @@ void wolfSSL_EVP_init(void) } #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_GCM_TYPE || + if (ctx->cipherType == WC_AES_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM))) { WOLFSSL_MSG("EVP_AES_128_GCM"); - ctx->cipherType = AES_128_GCM_TYPE; + ctx->cipherType = WC_AES_128_GCM_TYPE; ctx->keyLen = AES_128_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_GCM_TYPE || + if (ctx->cipherType == WC_AES_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM))) { WOLFSSL_MSG("EVP_AES_192_GCM"); - ctx->cipherType = AES_192_GCM_TYPE; + ctx->cipherType = WC_AES_192_GCM_TYPE; ctx->keyLen = AES_192_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_GCM_TYPE || + if (ctx->cipherType == WC_AES_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM))) { WOLFSSL_MSG("EVP_AES_256_GCM"); - ctx->cipherType = AES_256_GCM_TYPE; + ctx->cipherType = WC_AES_256_GCM_TYPE; ctx->keyLen = AES_256_KEY_SIZE; } #endif @@ -6697,8 +6703,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6710,26 +6716,26 @@ void wolfSSL_EVP_init(void) } #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CCM_TYPE || + if (ctx->cipherType == WC_AES_128_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM))) { WOLFSSL_MSG("EVP_AES_128_CCM"); - ctx->cipherType = AES_128_CCM_TYPE; + ctx->cipherType = WC_AES_128_CCM_TYPE; ctx->keyLen = AES_128_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CCM_TYPE || + if (ctx->cipherType == WC_AES_192_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM))) { WOLFSSL_MSG("EVP_AES_192_CCM"); - ctx->cipherType = AES_192_CCM_TYPE; + ctx->cipherType = WC_AES_192_CCM_TYPE; ctx->keyLen = AES_192_KEY_SIZE; } #endif #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CCM_TYPE || + if (ctx->cipherType == WC_AES_256_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM))) { WOLFSSL_MSG("EVP_AES_256_CCM"); - ctx->cipherType = AES_256_CCM_TYPE; + ctx->cipherType = WC_AES_256_CCM_TYPE; ctx->keyLen = AES_256_KEY_SIZE; } #endif @@ -6822,20 +6828,20 @@ void wolfSSL_EVP_init(void) { int ret = WOLFSSL_SUCCESS; - if (ctx->cipherType == ARIA_128_GCM_TYPE || + if (ctx->cipherType == WC_ARIA_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_128_GCM))) { WOLFSSL_MSG("EVP_ARIA_128_GCM"); - ctx->cipherType = ARIA_128_GCM_TYPE; + ctx->cipherType = WC_ARIA_128_GCM_TYPE; ctx->keyLen = ARIA_128_KEY_SIZE; - } else if (ctx->cipherType == ARIA_192_GCM_TYPE || + } else if (ctx->cipherType == WC_ARIA_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_192_GCM))) { WOLFSSL_MSG("EVP_ARIA_192_GCM"); - ctx->cipherType = ARIA_192_GCM_TYPE; + ctx->cipherType = WC_ARIA_192_GCM_TYPE; ctx->keyLen = ARIA_192_KEY_SIZE; - } else if (ctx->cipherType == ARIA_256_GCM_TYPE || + } else if (ctx->cipherType == WC_ARIA_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_256_GCM))) { WOLFSSL_MSG("EVP_ARIA_256_GCM"); - ctx->cipherType = ARIA_256_GCM_TYPE; + ctx->cipherType = WC_ARIA_256_GCM_TYPE; ctx->keyLen = ARIA_256_KEY_SIZE; } else { WOLFSSL_MSG("Unrecognized cipher type"); @@ -6846,8 +6852,8 @@ void wolfSSL_EVP_init(void) ctx->authIn = NULL; ctx->authInSz = 0; - ctx->block_size = AES_BLOCK_SIZE; - ctx->authTagSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->authTagSz = WC_AES_BLOCK_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; } @@ -6859,13 +6865,13 @@ void wolfSSL_EVP_init(void) } switch(ctx->cipherType) { - case ARIA_128_GCM_TYPE: + case WC_ARIA_128_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_128BITKEY); break; - case ARIA_192_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_192BITKEY); break; - case ARIA_256_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_256BITKEY); break; default: @@ -6931,15 +6937,15 @@ void wolfSSL_EVP_init(void) #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CBC_TYPE || + if (ctx->cipherType == WC_AES_128_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CBC))) { WOLFSSL_MSG("EVP_AES_128_CBC"); - ctx->cipherType = AES_128_CBC_TYPE; + ctx->cipherType = WC_AES_128_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 16; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -6961,15 +6967,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CBC_TYPE || + if (ctx->cipherType == WC_AES_192_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CBC))) { WOLFSSL_MSG("EVP_AES_192_CBC"); - ctx->cipherType = AES_192_CBC_TYPE; + ctx->cipherType = WC_AES_192_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 24; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -6991,15 +6997,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CBC_TYPE || + if (ctx->cipherType == WC_AES_256_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CBC))) { WOLFSSL_MSG("EVP_AES_256_CBC"); - ctx->cipherType = AES_256_CBC_TYPE; + ctx->cipherType = WC_AES_256_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 32; - ctx->block_size = AES_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7029,15 +7035,15 @@ void wolfSSL_EVP_init(void) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_GCM_TYPE || + || ctx->cipherType == WC_AES_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_GCM)) #endif #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_GCM_TYPE || + || ctx->cipherType == WC_AES_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_GCM)) #endif #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_GCM_TYPE || + || ctx->cipherType == WC_AES_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_GCM)) #endif ) { @@ -7053,15 +7059,15 @@ void wolfSSL_EVP_init(void) || FIPS_VERSION_GE(2,0)) if (FALSE #ifdef WOLFSSL_AES_128 - || ctx->cipherType == AES_128_CCM_TYPE || + || ctx->cipherType == WC_AES_128_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CCM)) #endif #ifdef WOLFSSL_AES_192 - || ctx->cipherType == AES_192_CCM_TYPE || + || ctx->cipherType == WC_AES_192_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CCM)) #endif #ifdef WOLFSSL_AES_256 - || ctx->cipherType == AES_256_CCM_TYPE || + || ctx->cipherType == WC_AES_256_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CCM)) #endif ) @@ -7075,15 +7081,15 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CTR_TYPE || + if (ctx->cipherType == WC_AES_128_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CTR))) { WOLFSSL_MSG("EVP_AES_128_CTR"); ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; - ctx->cipherType = AES_128_CTR_TYPE; + ctx->cipherType = WC_AES_128_CTR_TYPE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 16; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7108,15 +7114,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CTR_TYPE || + if (ctx->cipherType == WC_AES_192_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CTR))) { WOLFSSL_MSG("EVP_AES_192_CTR"); - ctx->cipherType = AES_192_CTR_TYPE; + ctx->cipherType = WC_AES_192_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 24; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7141,15 +7147,15 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CTR_TYPE || + if (ctx->cipherType == WC_AES_256_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CTR))) { WOLFSSL_MSG("EVP_AES_256_CTR"); - ctx->cipherType = AES_256_CTR_TYPE; + ctx->cipherType = WC_AES_256_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = 32; - ctx->block_size = NO_PADDING_BLOCK_SIZE; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) ctx->cipher.aes.left = 0; #endif @@ -7176,14 +7182,14 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_COUNTER */ #ifdef HAVE_AES_ECB #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_ECB_TYPE || + if (ctx->cipherType == WC_AES_128_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_ECB))) { WOLFSSL_MSG("EVP_AES_128_ECB"); - ctx->cipherType = AES_128_ECB_TYPE; + ctx->cipherType = WC_AES_128_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 16; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7200,14 +7206,14 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_ECB_TYPE || + if (ctx->cipherType == WC_AES_192_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_ECB))) { WOLFSSL_MSG("EVP_AES_192_ECB"); - ctx->cipherType = AES_192_ECB_TYPE; + ctx->cipherType = WC_AES_192_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 24; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7224,14 +7230,14 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_ECB_TYPE || + if (ctx->cipherType == WC_AES_256_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_ECB))) { WOLFSSL_MSG("EVP_AES_256_ECB"); - ctx->cipherType = AES_256_ECB_TYPE; + ctx->cipherType = WC_AES_256_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 32; - ctx->block_size = AES_BLOCK_SIZE; + ctx->block_size = WC_AES_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; if (! (ctx->flags & WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED)) { @@ -7249,11 +7255,12 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_256 */ #endif /* HAVE_AES_ECB */ #ifdef WOLFSSL_AES_CFB + #ifndef WOLFSSL_NO_AES_CFB_1_8 #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB1_TYPE || + if (ctx->cipherType == WC_AES_128_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB1))) { WOLFSSL_MSG("EVP_AES_128_CFB1"); - ctx->cipherType = AES_128_CFB1_TYPE; + ctx->cipherType = WC_AES_128_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7279,10 +7286,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB1_TYPE || + if (ctx->cipherType == WC_AES_192_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB1))) { WOLFSSL_MSG("EVP_AES_192_CFB1"); - ctx->cipherType = AES_192_CFB1_TYPE; + ctx->cipherType = WC_AES_192_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7308,10 +7315,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB1_TYPE || + if (ctx->cipherType == WC_AES_256_CFB1_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB1))) { WOLFSSL_MSG("EVP_AES_256_CFB1"); - ctx->cipherType = AES_256_CFB1_TYPE; + ctx->cipherType = WC_AES_256_CFB1_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7341,10 +7348,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_256 */ #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB8_TYPE || + if (ctx->cipherType == WC_AES_128_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB8))) { WOLFSSL_MSG("EVP_AES_128_CFB8"); - ctx->cipherType = AES_128_CFB8_TYPE; + ctx->cipherType = WC_AES_128_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7370,10 +7377,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB8_TYPE || + if (ctx->cipherType == WC_AES_192_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB8))) { WOLFSSL_MSG("EVP_AES_192_CFB8"); - ctx->cipherType = AES_192_CFB8_TYPE; + ctx->cipherType = WC_AES_192_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7399,10 +7406,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB8_TYPE || + if (ctx->cipherType == WC_AES_256_CFB8_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB8))) { WOLFSSL_MSG("EVP_AES_256_CFB8"); - ctx->cipherType = AES_256_CFB8_TYPE; + ctx->cipherType = WC_AES_256_CFB8_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7431,11 +7438,12 @@ void wolfSSL_EVP_init(void) } } #endif /* WOLFSSL_AES_256 */ + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_CFB128_TYPE || + if (ctx->cipherType == WC_AES_128_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_CFB128))) { WOLFSSL_MSG("EVP_AES_128_CFB128"); - ctx->cipherType = AES_128_CFB128_TYPE; + ctx->cipherType = WC_AES_128_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 16; @@ -7461,10 +7469,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_CFB128_TYPE || + if (ctx->cipherType == WC_AES_192_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_CFB128))) { WOLFSSL_MSG("EVP_AES_192_CFB128"); - ctx->cipherType = AES_192_CFB128_TYPE; + ctx->cipherType = WC_AES_192_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 24; @@ -7490,10 +7498,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_CFB128_TYPE || + if (ctx->cipherType == WC_AES_256_CFB128_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_CFB128))) { WOLFSSL_MSG("EVP_AES_256_CFB128"); - ctx->cipherType = AES_256_CFB128_TYPE; + ctx->cipherType = WC_AES_256_CFB128_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CFB_MODE; ctx->keyLen = 32; @@ -7525,10 +7533,10 @@ void wolfSSL_EVP_init(void) #endif /* WOLFSSL_AES_CFB */ #ifdef WOLFSSL_AES_OFB #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_OFB_TYPE || + if (ctx->cipherType == WC_AES_128_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_OFB))) { WOLFSSL_MSG("EVP_AES_128_OFB"); - ctx->cipherType = AES_128_OFB_TYPE; + ctx->cipherType = WC_AES_128_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 16; @@ -7554,10 +7562,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_192 - if (ctx->cipherType == AES_192_OFB_TYPE || + if (ctx->cipherType == WC_AES_192_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_192_OFB))) { WOLFSSL_MSG("EVP_AES_192_OFB"); - ctx->cipherType = AES_192_OFB_TYPE; + ctx->cipherType = WC_AES_192_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 24; @@ -7583,10 +7591,10 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_192 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_OFB_TYPE || + if (ctx->cipherType == WC_AES_256_OFB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_OFB))) { WOLFSSL_MSG("EVP_AES_256_OFB"); - ctx->cipherType = AES_256_OFB_TYPE; + ctx->cipherType = WC_AES_256_OFB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_OFB_MODE; ctx->keyLen = 32; @@ -7619,22 +7627,22 @@ void wolfSSL_EVP_init(void) #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 - if (ctx->cipherType == AES_128_XTS_TYPE || + if (ctx->cipherType == WC_AES_128_XTS_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_128_XTS))) { WOLFSSL_MSG("EVP_AES_128_XTS"); - ctx->cipherType = AES_128_XTS_TYPE; + ctx->cipherType = WC_AES_128_XTS_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_XTS_MODE; ctx->keyLen = 32; ctx->block_size = 1; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (iv != NULL) { if (iv != ctx->iv) /* Valgrind error when src == dst */ XMEMCPY(ctx->iv, iv, (size_t)ctx->ivSz); } else - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7660,22 +7668,22 @@ void wolfSSL_EVP_init(void) } #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_256 - if (ctx->cipherType == AES_256_XTS_TYPE || + if (ctx->cipherType == WC_AES_256_XTS_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_AES_256_XTS))) { WOLFSSL_MSG("EVP_AES_256_XTS"); - ctx->cipherType = AES_256_XTS_TYPE; + ctx->cipherType = WC_AES_256_XTS_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_XTS_MODE; ctx->keyLen = 64; ctx->block_size = 1; - ctx->ivSz = AES_BLOCK_SIZE; + ctx->ivSz = WC_AES_BLOCK_SIZE; if (iv != NULL) { if (iv != ctx->iv) /* Valgrind error when src == dst */ XMEMCPY(ctx->iv, iv, (size_t)ctx->ivSz); } else - XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE); + XMEMSET(ctx->iv, 0, WC_AES_BLOCK_SIZE); if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7704,11 +7712,11 @@ void wolfSSL_EVP_init(void) (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #endif /* NO_AES */ #if defined(HAVE_ARIA) - if (ctx->cipherType == ARIA_128_GCM_TYPE || + if (ctx->cipherType == WC_ARIA_128_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_128_GCM)) - || ctx->cipherType == ARIA_192_GCM_TYPE || + || ctx->cipherType == WC_ARIA_192_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_192_GCM)) - || ctx->cipherType == ARIA_256_GCM_TYPE || + || ctx->cipherType == WC_ARIA_256_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARIA_256_GCM)) ) { if (EvpCipherInitAriaGCM(ctx, type, key, iv, enc) @@ -7721,10 +7729,10 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - if (ctx->cipherType == CHACHA20_POLY1305_TYPE || + if (ctx->cipherType == WC_CHACHA20_POLY1305_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_CHACHA20_POLY1305))) { WOLFSSL_MSG("EVP_CHACHA20_POLY1305"); - ctx->cipherType = CHACHA20_POLY1305_TYPE; + ctx->cipherType = WC_CHACHA20_POLY1305_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; ctx->keyLen = CHACHA20_POLY1305_AEAD_KEYSIZE; @@ -7758,10 +7766,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef HAVE_CHACHA - if (ctx->cipherType == CHACHA20_TYPE || + if (ctx->cipherType == WC_CHACHA20_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_CHACHA20))) { WOLFSSL_MSG("EVP_CHACHA20"); - ctx->cipherType = CHACHA20_TYPE; + ctx->cipherType = WC_CHACHA20_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->keyLen = CHACHA_MAX_KEY_SZ; ctx->block_size = 1; @@ -7791,10 +7799,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_ECB - if (ctx->cipherType == SM4_ECB_TYPE || + if (ctx->cipherType == WC_SM4_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_ECB))) { WOLFSSL_MSG("EVP_SM4_ECB"); - ctx->cipherType = SM4_ECB_TYPE; + ctx->cipherType = WC_SM4_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = SM4_KEY_SIZE; @@ -7810,10 +7818,10 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CBC - if (ctx->cipherType == SM4_CBC_TYPE || + if (ctx->cipherType == WC_SM4_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CBC))) { WOLFSSL_MSG("EVP_SM4_CBC"); - ctx->cipherType = SM4_CBC_TYPE; + ctx->cipherType = WC_SM4_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = SM4_KEY_SIZE; @@ -7836,14 +7844,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CTR - if (ctx->cipherType == SM4_CTR_TYPE || + if (ctx->cipherType == WC_SM4_CTR_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CTR))) { WOLFSSL_MSG("EVP_SM4_CTR"); - ctx->cipherType = SM4_CTR_TYPE; + ctx->cipherType = WC_SM4_CTR_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CTR_MODE; ctx->keyLen = SM4_KEY_SIZE; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->ivSz = SM4_BLOCK_SIZE; if (enc == 0 || enc == 1) ctx->enc = enc ? 1 : 0; @@ -7862,14 +7870,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_GCM - if (ctx->cipherType == SM4_GCM_TYPE || + if (ctx->cipherType == WC_SM4_GCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_GCM))) { WOLFSSL_MSG("EVP_SM4_GCM"); - ctx->cipherType = SM4_GCM_TYPE; + ctx->cipherType = WC_SM4_GCM_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_GCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->keyLen = SM4_KEY_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; @@ -7892,14 +7900,14 @@ void wolfSSL_EVP_init(void) } #endif #ifdef WOLFSSL_SM4_CCM - if (ctx->cipherType == SM4_CCM_TYPE || + if (ctx->cipherType == WC_SM4_CCM_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_SM4_CCM))) { WOLFSSL_MSG("EVP_SM4_CCM"); - ctx->cipherType = SM4_CCM_TYPE; + ctx->cipherType = WC_SM4_CCM_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CCM_MODE | WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER; - ctx->block_size = NO_PADDING_BLOCK_SIZE; + ctx->block_size = WOLFSSL_NO_PADDING_BLOCK_SIZE; ctx->keyLen = SM4_KEY_SIZE; if (ctx->ivSz == 0) { ctx->ivSz = GCM_NONCE_MID_SZ; @@ -7922,10 +7930,10 @@ void wolfSSL_EVP_init(void) } #endif #ifndef NO_DES3 - if (ctx->cipherType == DES_CBC_TYPE || + if (ctx->cipherType == WC_DES_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_CBC))) { WOLFSSL_MSG("EVP_DES_CBC"); - ctx->cipherType = DES_CBC_TYPE; + ctx->cipherType = WC_DES_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 8; @@ -7944,10 +7952,10 @@ void wolfSSL_EVP_init(void) wc_Des_SetIV(&ctx->cipher.des, iv); } #ifdef WOLFSSL_DES_ECB - else if (ctx->cipherType == DES_ECB_TYPE || + else if (ctx->cipherType == WC_DES_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_ECB))) { WOLFSSL_MSG("EVP_DES_ECB"); - ctx->cipherType = DES_ECB_TYPE; + ctx->cipherType = WC_DES_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 8; @@ -7963,11 +7971,11 @@ void wolfSSL_EVP_init(void) } } #endif - else if (ctx->cipherType == DES_EDE3_CBC_TYPE || + else if (ctx->cipherType == WC_DES_EDE3_CBC_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_EDE3_CBC))) { WOLFSSL_MSG("EVP_DES_EDE3_CBC"); - ctx->cipherType = DES_EDE3_CBC_TYPE; + ctx->cipherType = WC_DES_EDE3_CBC_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_CBC_MODE; ctx->keyLen = 24; @@ -7988,11 +7996,11 @@ void wolfSSL_EVP_init(void) return WOLFSSL_FAILURE; } } - else if (ctx->cipherType == DES_EDE3_ECB_TYPE || + else if (ctx->cipherType == WC_DES_EDE3_ECB_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_DES_EDE3_ECB))) { WOLFSSL_MSG("EVP_DES_EDE3_ECB"); - ctx->cipherType = DES_EDE3_ECB_TYPE; + ctx->cipherType = WC_DES_EDE3_ECB_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_ECB_MODE; ctx->keyLen = 24; @@ -8008,10 +8016,10 @@ void wolfSSL_EVP_init(void) } #endif /* NO_DES3 */ #ifndef NO_RC4 - if (ctx->cipherType == ARC4_TYPE || + if (ctx->cipherType == WC_ARC4_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_ARC4))) { WOLFSSL_MSG("ARC4"); - ctx->cipherType = ARC4_TYPE; + ctx->cipherType = WC_ARC4_TYPE; ctx->flags &= (unsigned long)~WOLFSSL_EVP_CIPH_MODE; ctx->flags |= WOLFSSL_EVP_CIPH_STREAM_CIPHER; ctx->block_size = 1; @@ -8021,10 +8029,10 @@ void wolfSSL_EVP_init(void) wc_Arc4SetKey(&ctx->cipher.arc4, key, (word32)ctx->keyLen); } #endif /* NO_RC4 */ - if (ctx->cipherType == NULL_CIPHER_TYPE || + if (ctx->cipherType == WC_NULL_CIPHER_TYPE || (type && EVP_CIPHER_TYPE_MATCHES(type, EVP_NULL))) { WOLFSSL_MSG("NULL cipher"); - ctx->cipherType = NULL_CIPHER_TYPE; + ctx->cipherType = WC_NULL_CIPHER_TYPE; ctx->keyLen = 0; ctx->block_size = 16; } @@ -8045,120 +8053,120 @@ void wolfSSL_EVP_init(void) WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_CTX_nid"); if (ctx == NULL) { WOLFSSL_ERROR_MSG("Bad parameters"); - return NID_undef; + return WC_NID_undef; } switch (ctx->cipherType) { #ifndef NO_AES #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - return NID_aes_128_cbc; - case AES_192_CBC_TYPE : - return NID_aes_192_cbc; - case AES_256_CBC_TYPE : - return NID_aes_256_cbc; + case WC_AES_128_CBC_TYPE : + return WC_NID_aes_128_cbc; + case WC_AES_192_CBC_TYPE : + return WC_NID_aes_192_cbc; + case WC_AES_256_CBC_TYPE : + return WC_NID_aes_256_cbc; #endif #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - return NID_aes_128_gcm; - case AES_192_GCM_TYPE : - return NID_aes_192_gcm; - case AES_256_GCM_TYPE : - return NID_aes_256_gcm; + case WC_AES_128_GCM_TYPE : + return WC_NID_aes_128_gcm; + case WC_AES_192_GCM_TYPE : + return WC_NID_aes_192_gcm; + case WC_AES_256_GCM_TYPE : + return WC_NID_aes_256_gcm; #endif #ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - return NID_aes_128_ccm; - case AES_192_CCM_TYPE : - return NID_aes_192_ccm; - case AES_256_CCM_TYPE : - return NID_aes_256_ccm; + case WC_AES_128_CCM_TYPE : + return WC_NID_aes_128_ccm; + case WC_AES_192_CCM_TYPE : + return WC_NID_aes_192_ccm; + case WC_AES_256_CCM_TYPE : + return WC_NID_aes_256_ccm; #endif #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - return NID_aes_128_ecb; - case AES_192_ECB_TYPE : - return NID_aes_192_ecb; - case AES_256_ECB_TYPE : - return NID_aes_256_ecb; + case WC_AES_128_ECB_TYPE : + return WC_NID_aes_128_ecb; + case WC_AES_192_ECB_TYPE : + return WC_NID_aes_192_ecb; + case WC_AES_256_ECB_TYPE : + return WC_NID_aes_256_ecb; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - return NID_aes_128_ctr; - case AES_192_CTR_TYPE : - return NID_aes_192_ctr; - case AES_256_CTR_TYPE : - return NID_aes_256_ctr; + case WC_AES_128_CTR_TYPE : + return WC_NID_aes_128_ctr; + case WC_AES_192_CTR_TYPE : + return WC_NID_aes_192_ctr; + case WC_AES_256_CTR_TYPE : + return WC_NID_aes_256_ctr; #endif #endif /* NO_AES */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - return NID_aria_128_gcm; - case ARIA_192_GCM_TYPE : - return NID_aria_192_gcm; - case ARIA_256_GCM_TYPE : - return NID_aria_256_gcm; + case WC_ARIA_128_GCM_TYPE : + return WC_NID_aria_128_gcm; + case WC_ARIA_192_GCM_TYPE : + return WC_NID_aria_192_gcm; + case WC_ARIA_256_GCM_TYPE : + return WC_NID_aria_256_gcm; #endif #ifndef NO_DES3 - case DES_CBC_TYPE : - return NID_des_cbc; + case WC_DES_CBC_TYPE : + return WC_NID_des_cbc; - case DES_EDE3_CBC_TYPE : - return NID_des_ede3_cbc; + case WC_DES_EDE3_CBC_TYPE : + return WC_NID_des_ede3_cbc; #endif #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : - return NID_des_ecb; - case DES_EDE3_ECB_TYPE : - return NID_des_ede3_ecb; + case WC_DES_ECB_TYPE : + return WC_NID_des_ecb; + case WC_DES_EDE3_ECB_TYPE : + return WC_NID_des_ede3_ecb; #endif - case ARC4_TYPE : - return NID_rc4; + case WC_ARC4_TYPE : + return WC_NID_rc4; #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: - return NID_chacha20_poly1305; + case WC_CHACHA20_POLY1305_TYPE: + return WC_NID_chacha20_poly1305; #endif #ifdef HAVE_CHACHA - case CHACHA20_TYPE: - return NID_chacha20; + case WC_CHACHA20_TYPE: + return WC_NID_chacha20; #endif #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE: - return NID_sm4_ecb; + case WC_SM4_ECB_TYPE: + return WC_NID_sm4_ecb; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE: - return NID_sm4_cbc; + case WC_SM4_CBC_TYPE: + return WC_NID_sm4_cbc; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE: - return NID_sm4_ctr; + case WC_SM4_CTR_TYPE: + return WC_NID_sm4_ctr; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE: - return NID_sm4_gcm; + case WC_SM4_GCM_TYPE: + return WC_NID_sm4_gcm; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE: - return NID_sm4_ccm; + case WC_SM4_CCM_TYPE: + return WC_NID_sm4_ccm; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_ERROR_MSG("Null cipher has no NID"); FALL_THROUGH; default: - return NID_undef; + return WC_NID_undef; } } @@ -8253,17 +8261,17 @@ void wolfSSL_EVP_init(void) static int IsCipherTypeAEAD(unsigned char cipherType) { switch (cipherType) { - case AES_128_GCM_TYPE: - case AES_192_GCM_TYPE: - case AES_256_GCM_TYPE: - case AES_128_CCM_TYPE: - case AES_192_CCM_TYPE: - case AES_256_CCM_TYPE: - case ARIA_128_GCM_TYPE: - case ARIA_192_GCM_TYPE: - case ARIA_256_GCM_TYPE: - case SM4_GCM_TYPE: - case SM4_CCM_TYPE: + case WC_AES_128_GCM_TYPE: + case WC_AES_192_GCM_TYPE: + case WC_AES_256_GCM_TYPE: + case WC_AES_128_CCM_TYPE: + case WC_AES_192_CCM_TYPE: + case WC_AES_256_CCM_TYPE: + case WC_ARIA_128_GCM_TYPE: + case WC_ARIA_192_GCM_TYPE: + case WC_ARIA_256_GCM_TYPE: + case WC_SM4_GCM_TYPE: + case WC_SM4_CCM_TYPE: return 1; default: return 0; @@ -8303,24 +8311,24 @@ void wolfSSL_EVP_init(void) #ifndef NO_AES #ifdef HAVE_AES_CBC - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); if (ctx->enc) ret = wc_AesCbcEncrypt(&ctx->cipher.aes, dst, src, len); else ret = wc_AesCbcDecrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) - ret = (int)((len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE); + ret = (int)((len / WC_AES_BLOCK_SIZE) * WC_AES_BLOCK_SIZE); break; #endif /* HAVE_AES_CBC */ #ifdef WOLFSSL_AES_CFB -#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: +#if !defined(WOLFSSL_NO_AES_CFB_1_8) + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: WOLFSSL_MSG("AES CFB1"); if (ctx->enc) ret = wc_AesCfb1Encrypt(&ctx->cipher.aes, dst, src, len); @@ -8329,9 +8337,9 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)len; break; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: WOLFSSL_MSG("AES CFB8"); if (ctx->enc) ret = wc_AesCfb8Encrypt(&ctx->cipher.aes, dst, src, len); @@ -8340,10 +8348,10 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)len; break; -#endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: +#endif /* !WOLFSSL_NO_AES_CFB_1_8 */ + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: WOLFSSL_MSG("AES CFB128"); if (ctx->enc) ret = wc_AesCfbEncrypt(&ctx->cipher.aes, dst, src, len); @@ -8354,9 +8362,9 @@ void wolfSSL_EVP_init(void) break; #endif /* WOLFSSL_AES_CFB */ #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: WOLFSSL_MSG("AES OFB"); if (ctx->enc) ret = wc_AesOfbEncrypt(&ctx->cipher.aes, dst, src, len); @@ -8367,8 +8375,8 @@ void wolfSSL_EVP_init(void) break; #endif /* WOLFSSL_AES_OFB */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: WOLFSSL_MSG("AES XTS"); if (ctx->enc) ret = wc_AesXtsEncrypt(&ctx->cipher.xts, dst, src, len, @@ -8383,9 +8391,9 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_AESGCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); ret = EvpCipherAesGCM(ctx, dst, src, len); break; @@ -8393,31 +8401,31 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #if defined(HAVE_AESCCM) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : + case WC_AES_128_CCM_TYPE : + case WC_AES_192_CCM_TYPE : + case WC_AES_256_CCM_TYPE : WOLFSSL_MSG("AES CCM"); ret = EvpCipherAesCCM(ctx, dst, src, len); break; #endif /* HAVE_AESCCM && ((!HAVE_FIPS && !HAVE_SELFTEST) || * HAVE_FIPS_VERSION >= 2 */ #ifdef HAVE_AES_ECB - case AES_128_ECB_TYPE : - case AES_192_ECB_TYPE : - case AES_256_ECB_TYPE : + case WC_AES_128_ECB_TYPE : + case WC_AES_192_ECB_TYPE : + case WC_AES_256_ECB_TYPE : WOLFSSL_MSG("AES ECB"); if (ctx->enc) ret = wc_AesEcbEncrypt(&ctx->cipher.aes, dst, src, len); else ret = wc_AesEcbDecrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) - ret = (int)((len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE); + ret = (int)((len / WC_AES_BLOCK_SIZE) * WC_AES_BLOCK_SIZE); break; #endif #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); ret = wc_AesCtrEncrypt(&ctx->cipher.aes, dst, src, len); if (ret == 0) @@ -8428,9 +8436,9 @@ void wolfSSL_EVP_init(void) #if defined(HAVE_ARIA) && ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) \ || FIPS_VERSION_GE(2,0)) - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); if (ctx->enc) { ret = wc_AriaEncrypt(&ctx->cipher.aria, dst, src, len, @@ -8447,7 +8455,7 @@ void wolfSSL_EVP_init(void) * HAVE_FIPS_VERSION >= 2 */ #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); if (ctx->enc) wc_Des_CbcEncrypt(&ctx->cipher.des, dst, src, len); @@ -8456,7 +8464,7 @@ void wolfSSL_EVP_init(void) if (ret == 0) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES3 CBC"); if (ctx->enc) ret = wc_Des3_CbcEncrypt(&ctx->cipher.des3, dst, src, len); @@ -8466,13 +8474,13 @@ void wolfSSL_EVP_init(void) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; #ifdef WOLFSSL_DES_ECB - case DES_ECB_TYPE : + case WC_DES_ECB_TYPE : WOLFSSL_MSG("DES ECB"); ret = wc_Des_EcbEncrypt(&ctx->cipher.des, dst, src, len); if (ret == 0) ret = (int)((len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE); break; - case DES_EDE3_ECB_TYPE : + case WC_DES_EDE3_ECB_TYPE : WOLFSSL_MSG("DES3 ECB"); ret = wc_Des3_EcbEncrypt(&ctx->cipher.des3, dst, src, len); if (ret == 0) @@ -8482,7 +8490,7 @@ void wolfSSL_EVP_init(void) #endif /* !NO_DES3 */ #ifndef NO_RC4 - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); wc_Arc4Process(&ctx->cipher.arc4, dst, src, len); if (ret == 0) @@ -8493,7 +8501,7 @@ void wolfSSL_EVP_init(void) /* TODO: Chacha??? */ #ifdef WOLFSSL_SM4_ECB - case SM4_ECB_TYPE : + case WC_SM4_ECB_TYPE : WOLFSSL_MSG("Sm4 ECB"); if (ctx->enc) ret = wc_Sm4EcbEncrypt(&ctx->cipher.sm4, dst, src, len); @@ -8504,7 +8512,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE : + case WC_SM4_CBC_TYPE : WOLFSSL_MSG("Sm4 CBC"); if (ctx->enc) ret = wc_Sm4CbcEncrypt(&ctx->cipher.sm4, dst, src, len); @@ -8515,7 +8523,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE : + case WC_SM4_CTR_TYPE : WOLFSSL_MSG("AES CTR"); ret = wc_Sm4CtrEncrypt(&ctx->cipher.sm4, dst, src, len); if (ret == 0) @@ -8523,7 +8531,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE : + case WC_SM4_GCM_TYPE : WOLFSSL_MSG("SM4 GCM"); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -8551,7 +8559,7 @@ void wolfSSL_EVP_init(void) break; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE : + case WC_SM4_CCM_TYPE : WOLFSSL_MSG("SM4 CCM"); /* No destination means only AAD. */ if (src != NULL && dst == NULL) { @@ -8592,7 +8600,7 @@ void wolfSSL_EVP_init(void) break; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL CIPHER"); XMEMCPY(dst, src, (size_t)len); ret = (int)len; @@ -8805,7 +8813,7 @@ int wolfSSL_EVP_PKEY_set1_RSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_RSA *key) clearEVPPkeyKeys(pkey); pkey->rsa = key; pkey->ownRsa = 1; /* pkey does not own RSA but needs to call free on it */ - pkey->type = EVP_PKEY_RSA; + pkey->type = WC_EVP_PKEY_RSA; pkey->pkcs8HeaderSz = key->pkcs8HeaderSz; if (key->inSet == 0) { if (SetRsaInternal(key) != WOLFSSL_SUCCESS) { @@ -8851,7 +8859,7 @@ int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) clearEVPPkeyKeys(pkey); pkey->dsa = key; pkey->ownDsa = 0; /* pkey does not own DSA */ - pkey->type = EVP_PKEY_DSA; + pkey->type = WC_EVP_PKEY_DSA; if (key->inSet == 0) { if (SetDsaInternal(key) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("SetDsaInternal failed"); @@ -8861,7 +8869,7 @@ int wolfSSL_EVP_PKEY_set1_DSA(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DSA *key) dsa = (DsaKey*)key->internal; /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */ - derMax = 4 * wolfSSL_BN_num_bytes(key->g) + AES_BLOCK_SIZE; + derMax = 4 * wolfSSL_BN_num_bytes(key->g) + WC_AES_BLOCK_SIZE; derBuf = (byte*)XMALLOC((size_t)derMax, pkey->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -8929,13 +8937,13 @@ WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) return NULL; } - if (key->type == EVP_PKEY_DSA) { + if (key->type == WC_EVP_PKEY_DSA) { if (wolfSSL_DSA_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { + key->pkey_sz) != WOLFSSL_SUCCESS) { /* now try public key */ if (wolfSSL_DSA_LoadDer_ex(local, (const unsigned char*)key->pkey.ptr, key->pkey_sz, - WOLFSSL_DSA_LOAD_PUBLIC) != SSL_SUCCESS) { + WOLFSSL_DSA_LOAD_PUBLIC) != WOLFSSL_SUCCESS) { wolfSSL_DSA_free(local); local = NULL; } @@ -8954,7 +8962,7 @@ WOLFSSL_DSA* wolfSSL_EVP_PKEY_get1_DSA(WOLFSSL_EVP_PKEY* key) WOLFSSL_EC_KEY *wolfSSL_EVP_PKEY_get0_EC_KEY(WOLFSSL_EVP_PKEY *pkey) { WOLFSSL_EC_KEY *eckey = NULL; - if (pkey && pkey->type == EVP_PKEY_EC) { + if (pkey && pkey->type == WC_EVP_PKEY_EC) { #ifdef HAVE_ECC eckey = pkey->ecc; #endif @@ -8967,10 +8975,10 @@ WOLFSSL_EC_KEY* wolfSSL_EVP_PKEY_get1_EC_KEY(WOLFSSL_EVP_PKEY* key) WOLFSSL_EC_KEY* local = NULL; WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get1_EC_KEY"); - if (key == NULL || key->type != EVP_PKEY_EC) { + if (key == NULL || key->type != WC_EVP_PKEY_EC) { return NULL; } - if (key->type == EVP_PKEY_EC) { + if (key->type == WC_EVP_PKEY_EC) { if (key->ecc != NULL) { if (wolfSSL_EC_KEY_up_ref(key->ecc) != WOLFSSL_SUCCESS) { return NULL; @@ -9035,7 +9043,7 @@ int wolfSSL_EVP_PKEY_set1_DH(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_DH *key) pkey->dh = key; pkey->ownDh = 1; /* pkey does not own DH but needs to call free on it */ - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; if (key->inSet == 0) { if (SetDhInternal(key) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("SetDhInternal failed"); @@ -9109,7 +9117,7 @@ WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) return NULL; } - if (key->type == EVP_PKEY_DH) { + if (key->type == WC_EVP_PKEY_DH) { /* if key->dh already exists copy instead of re-importing from DER */ if (key->dh != NULL) { if (wolfSSL_DH_up_ref(key->dh) != WOLFSSL_SUCCESS) { @@ -9126,7 +9134,7 @@ WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key) return NULL; } if (wolfSSL_DH_LoadDer(local, (const unsigned char*)key->pkey.ptr, - key->pkey_sz) != SSL_SUCCESS) { + key->pkey_sz) != WOLFSSL_SUCCESS) { wolfSSL_DH_free(local); WOLFSSL_MSG("Error wolfSSL_DH_LoadDer"); local = NULL; @@ -9156,22 +9164,22 @@ int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) /* pkey and key checked if NULL in subsequent assign functions */ switch(type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: ret = wolfSSL_EVP_PKEY_assign_RSA(pkey, (WOLFSSL_RSA*)key); break; #endif #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: ret = wolfSSL_EVP_PKEY_assign_DSA(pkey, (WOLFSSL_DSA*)key); break; #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: ret = wolfSSL_EVP_PKEY_assign_EC_KEY(pkey, (WOLFSSL_EC_KEY*)key); break; #endif #ifndef NO_DH - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: ret = wolfSSL_EVP_PKEY_assign_DH(pkey, (WOLFSSL_DH*)key); break; #endif @@ -9186,7 +9194,7 @@ int wolfSSL_EVP_PKEY_assign(WOLFSSL_EVP_PKEY *pkey, int type, void *key) #if defined(HAVE_ECC) /* try and populate public pkey_sz and pkey.ptr */ -static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) +static int ECC_populate_EVP_PKEY(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_EC_KEY *key) { int derSz = 0; byte* derBuf = NULL; @@ -9295,7 +9303,7 @@ int wolfSSL_EVP_PKEY_set1_EC_KEY(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_EC_KEY *key) } pkey->ecc = key; pkey->ownEcc = 1; /* pkey needs to call free on key */ - pkey->type = EVP_PKEY_EC; + pkey->type = WC_EVP_PKEY_EC; return ECC_populate_EVP_PKEY(pkey, key); #else (void)pkey; @@ -9310,7 +9318,7 @@ void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) if (ctx) { switch (ctx->cipherType) { - case ARC4_TYPE: + case WC_ARC4_TYPE: WOLFSSL_MSG("returning arc4 state"); return (void*)&ctx->cipher.arc4.x; @@ -9322,7 +9330,7 @@ void* wolfSSL_EVP_X_STATE(const WOLFSSL_EVP_CIPHER_CTX* ctx) return NULL; } -int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) +int wolfSSL_EVP_PKEY_assign_EC_KEY(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) { int ret; @@ -9334,7 +9342,7 @@ int wolfSSL_EVP_PKEY_assign_EC_KEY(EVP_PKEY* pkey, WOLFSSL_EC_KEY* key) if (ret == WOLFSSL_SUCCESS) { /* take ownership of key if can be used */ clearEVPPkeyKeys(pkey); /* clear out any previous keys */ - pkey->type = EVP_PKEY_EC; + pkey->type = WC_EVP_PKEY_EC; pkey->ecc = key; pkey->ownEcc = 1; } @@ -9360,22 +9368,22 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) if (type != NULL) { if (XSTRCMP(type, "MD5") == 0) { - ret = NID_md5WithRSAEncryption; + ret = WC_NID_md5WithRSAEncryption; } else if (XSTRCMP(type, "SHA1") == 0) { - ret = NID_sha1WithRSAEncryption; + ret = WC_NID_sha1WithRSAEncryption; } else if (XSTRCMP(type, "SHA224") == 0) { - ret = NID_sha224WithRSAEncryption; + ret = WC_NID_sha224WithRSAEncryption; } else if (XSTRCMP(type, "SHA256") == 0) { - ret = NID_sha256WithRSAEncryption; + ret = WC_NID_sha256WithRSAEncryption; } else if (XSTRCMP(type, "SHA384") == 0) { - ret = NID_sha384WithRSAEncryption; + ret = WC_NID_sha384WithRSAEncryption; } else if (XSTRCMP(type, "SHA512") == 0) { - ret = NID_sha512WithRSAEncryption; + ret = WC_NID_sha512WithRSAEncryption; } } else { @@ -9401,18 +9409,18 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) switch (ctx->cipherType) { #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) - case AES_128_CBC_TYPE : - case AES_192_CBC_TYPE : - case AES_256_CBC_TYPE : + case WC_AES_128_CBC_TYPE : + case WC_AES_192_CBC_TYPE : + case WC_AES_256_CBC_TYPE : WOLFSSL_MSG("AES CBC"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) #ifdef HAVE_AESGCM - case AES_128_GCM_TYPE : - case AES_192_GCM_TYPE : - case AES_256_GCM_TYPE : + case WC_AES_128_GCM_TYPE : + case WC_AES_192_GCM_TYPE : + case WC_AES_256_GCM_TYPE : WOLFSSL_MSG("AES GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9420,9 +9428,9 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #ifdef HAVE_AESCCM - case AES_128_CCM_TYPE : - case AES_192_CCM_TYPE : - case AES_256_CCM_TYPE : + case WC_AES_128_CCM_TYPE : + case WC_AES_192_CCM_TYPE : + case WC_AES_256_CCM_TYPE : WOLFSSL_MSG("AES CCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9431,62 +9439,62 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) #endif #endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION >= 2 */ #ifdef WOLFSSL_AES_COUNTER - case AES_128_CTR_TYPE : - case AES_192_CTR_TYPE : - case AES_256_CTR_TYPE : + case WC_AES_128_CTR_TYPE : + case WC_AES_192_CTR_TYPE : + case WC_AES_256_CTR_TYPE : WOLFSSL_MSG("AES CTR"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifndef NO_DES3 - case DES_CBC_TYPE : + case WC_DES_CBC_TYPE : WOLFSSL_MSG("DES CBC"); return DES_BLOCK_SIZE; - case DES_EDE3_CBC_TYPE : + case WC_DES_EDE3_CBC_TYPE : WOLFSSL_MSG("DES EDE3 CBC"); return DES_BLOCK_SIZE; #endif #ifndef NO_RC4 - case ARC4_TYPE : + case WC_ARC4_TYPE : WOLFSSL_MSG("ARC4"); return 0; #endif #ifdef WOLFSSL_AES_CFB #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) - case AES_128_CFB1_TYPE: - case AES_192_CFB1_TYPE: - case AES_256_CFB1_TYPE: + case WC_AES_128_CFB1_TYPE: + case WC_AES_192_CFB1_TYPE: + case WC_AES_256_CFB1_TYPE: WOLFSSL_MSG("AES CFB1"); - return AES_BLOCK_SIZE; - case AES_128_CFB8_TYPE: - case AES_192_CFB8_TYPE: - case AES_256_CFB8_TYPE: + return WC_AES_BLOCK_SIZE; + case WC_AES_128_CFB8_TYPE: + case WC_AES_192_CFB8_TYPE: + case WC_AES_256_CFB8_TYPE: WOLFSSL_MSG("AES CFB8"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* !HAVE_SELFTEST && !HAVE_FIPS */ - case AES_128_CFB128_TYPE: - case AES_192_CFB128_TYPE: - case AES_256_CFB128_TYPE: + case WC_AES_128_CFB128_TYPE: + case WC_AES_192_CFB128_TYPE: + case WC_AES_256_CFB128_TYPE: WOLFSSL_MSG("AES CFB128"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_CFB */ #if defined(WOLFSSL_AES_OFB) - case AES_128_OFB_TYPE: - case AES_192_OFB_TYPE: - case AES_256_OFB_TYPE: + case WC_AES_128_OFB_TYPE: + case WC_AES_192_OFB_TYPE: + case WC_AES_256_OFB_TYPE: WOLFSSL_MSG("AES OFB"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_OFB */ #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) - case AES_128_XTS_TYPE: - case AES_256_XTS_TYPE: + case WC_AES_128_XTS_TYPE: + case WC_AES_256_XTS_TYPE: WOLFSSL_MSG("AES XTS"); - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ #ifdef HAVE_ARIA - case ARIA_128_GCM_TYPE : - case ARIA_192_GCM_TYPE : - case ARIA_256_GCM_TYPE : + case WC_ARIA_128_GCM_TYPE : + case WC_ARIA_192_GCM_TYPE : + case WC_ARIA_256_GCM_TYPE : WOLFSSL_MSG("ARIA GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9494,27 +9502,27 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) - case CHACHA20_POLY1305_TYPE: + case WC_CHACHA20_POLY1305_TYPE: WOLFSSL_MSG("CHACHA20 POLY1305"); return CHACHA20_POLY1305_AEAD_IV_SIZE; #endif /* HAVE_CHACHA HAVE_POLY1305 */ #ifdef HAVE_CHACHA - case CHACHA20_TYPE: + case WC_CHACHA20_TYPE: WOLFSSL_MSG("CHACHA20"); return WOLFSSL_EVP_CHACHA_IV_BYTES; #endif /* HAVE_CHACHA */ #ifdef WOLFSSL_SM4_CBC - case SM4_CBC_TYPE : + case WC_SM4_CBC_TYPE : WOLFSSL_MSG("SM4 CBC"); return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_CTR - case SM4_CTR_TYPE : + case WC_SM4_CTR_TYPE : WOLFSSL_MSG("SM4 CTR"); return SM4_BLOCK_SIZE; #endif #ifdef WOLFSSL_SM4_GCM - case SM4_GCM_TYPE : + case WC_SM4_GCM_TYPE : WOLFSSL_MSG("SM4 GCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9522,7 +9530,7 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return GCM_NONCE_MID_SZ; #endif #ifdef WOLFSSL_SM4_CCM - case SM4_CCM_TYPE : + case WC_SM4_CCM_TYPE : WOLFSSL_MSG("SM4 CCM"); if (ctx->ivSz != 0) { return ctx->ivSz; @@ -9530,7 +9538,7 @@ int wolfSSL_EVP_CIPHER_CTX_iv_length(const WOLFSSL_EVP_CIPHER_CTX* ctx) return CCM_NONCE_MIN_SZ; #endif - case NULL_CIPHER_TYPE : + case WC_NULL_CIPHER_TYPE : WOLFSSL_MSG("NULL"); return 0; @@ -9550,15 +9558,15 @@ int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_192 if (XSTRCMP(name, EVP_AES_192_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_CBC) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ #if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \ @@ -9595,26 +9603,26 @@ int wolfSSL_EVP_CIPHER_iv_length(const WOLFSSL_EVP_CIPHER* cipher) #ifdef WOLFSSL_AES_COUNTER #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_192 if (XSTRCMP(name, EVP_AES_192_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_CTR) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif #endif #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) #ifdef WOLFSSL_AES_128 if (XSTRCMP(name, EVP_AES_128_XTS) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_128 */ #ifdef WOLFSSL_AES_256 if (XSTRCMP(name, EVP_AES_256_XTS) == 0) - return AES_BLOCK_SIZE; + return WC_AES_BLOCK_SIZE; #endif /* WOLFSSL_AES_256 */ #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ @@ -9674,7 +9682,7 @@ int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) if (ctx) { switch (ctx->cipherType) { - case ARC4_TYPE: + case WC_ARC4_TYPE: WOLFSSL_MSG("returning arc4 state size"); return sizeof(Arc4); @@ -9688,27 +9696,27 @@ int wolfSSL_EVP_X_STATE_LEN(const WOLFSSL_EVP_CIPHER_CTX* ctx) } -/* return of pkey->type which will be EVP_PKEY_RSA for example. +/* return of pkey->type which will be WC_EVP_PKEY_RSA for example. * * type type of EVP_PKEY * - * returns type or if type is not found then NID_undef + * returns type or if type is not found then WC_NID_undef */ int wolfSSL_EVP_PKEY_type(int type) { WOLFSSL_MSG("wolfSSL_EVP_PKEY_type"); switch (type) { - case EVP_PKEY_RSA: - return EVP_PKEY_RSA; - case EVP_PKEY_DSA: - return EVP_PKEY_DSA; - case EVP_PKEY_EC: - return EVP_PKEY_EC; - case EVP_PKEY_DH: - return EVP_PKEY_DH; + case WC_EVP_PKEY_RSA: + return WC_EVP_PKEY_RSA; + case WC_EVP_PKEY_DSA: + return WC_EVP_PKEY_DSA; + case WC_EVP_PKEY_EC: + return WC_EVP_PKEY_EC; + case WC_EVP_PKEY_DH: + return WC_EVP_PKEY_DH; default: - return NID_undef; + return WC_NID_undef; } } @@ -9724,7 +9732,7 @@ int wolfSSL_EVP_PKEY_id(const WOLFSSL_EVP_PKEY *pkey) int wolfSSL_EVP_PKEY_base_id(const WOLFSSL_EVP_PKEY *pkey) { if (pkey == NULL) - return NID_undef; + return WC_NID_undef; return wolfSSL_EVP_PKEY_type(pkey->type); } @@ -9738,17 +9746,17 @@ int wolfSSL_EVP_PKEY_get_default_digest_nid(WOLFSSL_EVP_PKEY *pkey, int *pnid) } switch (pkey->type) { - case EVP_PKEY_HMAC: + case WC_EVP_PKEY_HMAC: #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: #endif #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #endif #ifdef HAVE_ECC - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: #endif - *pnid = NID_sha256; + *pnid = WC_NID_sha256; return WOLFSSL_SUCCESS; default: return WOLFSSL_FAILURE; @@ -9800,13 +9808,13 @@ int wolfSSL_EVP_PKEY_up_ref(WOLFSSL_EVP_PKEY* pkey) } #ifndef NO_RSA -int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) +int wolfSSL_EVP_PKEY_assign_RSA(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_RSA* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_RSA; + pkey->type = WC_EVP_PKEY_RSA; pkey->rsa = key; pkey->ownRsa = 1; @@ -9837,13 +9845,13 @@ int wolfSSL_EVP_PKEY_assign_RSA(EVP_PKEY* pkey, WOLFSSL_RSA* key) #endif /* !NO_RSA */ #ifndef NO_DSA -int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) +int wolfSSL_EVP_PKEY_assign_DSA(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_DSA* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DSA; + pkey->type = WC_EVP_PKEY_DSA; pkey->dsa = key; pkey->ownDsa = 1; @@ -9852,13 +9860,13 @@ int wolfSSL_EVP_PKEY_assign_DSA(EVP_PKEY* pkey, WOLFSSL_DSA* key) #endif /* !NO_DSA */ #ifndef NO_DH -int wolfSSL_EVP_PKEY_assign_DH(EVP_PKEY* pkey, WOLFSSL_DH* key) +int wolfSSL_EVP_PKEY_assign_DH(WOLFSSL_EVP_PKEY* pkey, WOLFSSL_DH* key) { if (pkey == NULL || key == NULL) return WOLFSSL_FAILURE; clearEVPPkeyKeys(pkey); - pkey->type = EVP_PKEY_DH; + pkey->type = WC_EVP_PKEY_DH; pkey->dh = key; pkey->ownDh = 1; @@ -9974,7 +9982,7 @@ const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) for (ent = md_tbl; ent->name != NULL; ent++) if(XSTRCMP(name, ent->name) == 0) { - return (EVP_MD *)ent->name; + return (WOLFSSL_EVP_MD *)ent->name; } return NULL; } @@ -9983,7 +9991,7 @@ const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) * * type - pointer to WOLFSSL_EVP_MD for which to return NID value * - * Returns NID on success, or NID_undef if none exists. + * Returns NID on success, or WC_NID_undef if none exists. */ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) { @@ -9992,7 +10000,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (type == NULL) { WOLFSSL_MSG("MD type arg is NULL"); - return NID_undef; + return WC_NID_undef; } for( ent = md_tbl; ent->name != NULL; ent++){ @@ -10000,7 +10008,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return ent->nid; } } - return NID_undef; + return WC_NID_undef; } #ifndef NO_MD4 @@ -10009,7 +10017,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) { WOLFSSL_ENTER("EVP_md4"); - return EVP_get_digestbyname("MD4"); + return wolfSSL_EVP_get_digestbyname("MD4"); } #endif /* !NO_MD4 */ @@ -10020,7 +10028,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) { WOLFSSL_ENTER("EVP_md5"); - return EVP_get_digestbyname("MD5"); + return wolfSSL_EVP_get_digestbyname("MD5"); } #endif /* !NO_MD5 */ @@ -10033,7 +10041,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) { WOLFSSL_ENTER("EVP_blake2b512"); - return EVP_get_digestbyname("BLAKE2b512"); + return wolfSSL_EVP_get_digestbyname("BLAKE2b512"); } #endif @@ -10046,7 +10054,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2s256(void) { WOLFSSL_ENTER("EVP_blake2s256"); - return EVP_get_digestbyname("BLAKE2s256"); + return wolfSSL_EVP_get_digestbyname("BLAKE2s256"); } #endif @@ -10072,7 +10080,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) { WOLFSSL_ENTER("EVP_sha1"); - return EVP_get_digestbyname("SHA1"); + return wolfSSL_EVP_get_digestbyname("SHA1"); } #endif /* NO_SHA */ @@ -10081,7 +10089,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) { WOLFSSL_ENTER("EVP_sha224"); - return EVP_get_digestbyname("SHA224"); + return wolfSSL_EVP_get_digestbyname("SHA224"); } #endif /* WOLFSSL_SHA224 */ @@ -10090,7 +10098,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) { WOLFSSL_ENTER("EVP_sha256"); - return EVP_get_digestbyname("SHA256"); + return wolfSSL_EVP_get_digestbyname("SHA256"); } #ifdef WOLFSSL_SHA384 @@ -10098,7 +10106,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) { WOLFSSL_ENTER("EVP_sha384"); - return EVP_get_digestbyname("SHA384"); + return wolfSSL_EVP_get_digestbyname("SHA384"); } #endif /* WOLFSSL_SHA384 */ @@ -10108,7 +10116,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) { WOLFSSL_ENTER("EVP_sha512"); - return EVP_get_digestbyname("SHA512"); + return wolfSSL_EVP_get_digestbyname("SHA512"); } #ifndef WOLFSSL_NOSHA512_224 @@ -10116,7 +10124,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) { WOLFSSL_ENTER("EVP_sha512_224"); - return EVP_get_digestbyname("SHA512_224"); + return wolfSSL_EVP_get_digestbyname("SHA512_224"); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10125,7 +10133,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) { WOLFSSL_ENTER("EVP_sha512_256"); - return EVP_get_digestbyname("SHA512_256"); + return wolfSSL_EVP_get_digestbyname("SHA512_256"); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10137,7 +10145,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) { WOLFSSL_ENTER("EVP_sha3_224"); - return EVP_get_digestbyname("SHA3_224"); + return wolfSSL_EVP_get_digestbyname("SHA3_224"); } #endif /* WOLFSSL_NOSHA3_224 */ @@ -10146,7 +10154,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) { WOLFSSL_ENTER("EVP_sha3_256"); - return EVP_get_digestbyname("SHA3_256"); + return wolfSSL_EVP_get_digestbyname("SHA3_256"); } #endif /* WOLFSSL_NOSHA3_256 */ @@ -10154,7 +10162,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) { WOLFSSL_ENTER("EVP_sha3_384"); - return EVP_get_digestbyname("SHA3_384"); + return wolfSSL_EVP_get_digestbyname("SHA3_384"); } #endif /* WOLFSSL_NOSHA3_384 */ @@ -10162,7 +10170,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) { WOLFSSL_ENTER("EVP_sha3_512"); - return EVP_get_digestbyname("SHA3_512"); + return wolfSSL_EVP_get_digestbyname("SHA3_512"); } #endif /* WOLFSSL_NOSHA3_512 */ @@ -10170,7 +10178,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_shake128(void) { WOLFSSL_ENTER("EVP_shake128"); - return EVP_get_digestbyname("SHAKE128"); + return wolfSSL_EVP_get_digestbyname("SHAKE128"); } #endif /* WOLFSSL_SHAKE128 */ @@ -10178,7 +10186,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_shake256(void) { WOLFSSL_ENTER("EVP_shake256"); - return EVP_get_digestbyname("SHAKE256"); + return wolfSSL_EVP_get_digestbyname("SHAKE256"); } #endif /* WOLFSSL_SHAKE256 */ @@ -10188,7 +10196,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sm3(void) { WOLFSSL_ENTER("EVP_sm3"); - return EVP_get_digestbyname("SM3"); + return wolfSSL_EVP_get_digestbyname("SM3"); } #endif /* WOLFSSL_SM3 */ @@ -10223,7 +10231,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const struct s_ent *ent; if (ctx->isHMAC) { - return NID_hmac; + return WC_NID_hmac; } for(ent = md_tbl; ent->name != NULL; ent++) { @@ -10313,7 +10321,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) if (nm->alias) md->fn(NULL, nm->name, nm->data, md->arg); else - md->fn((const EVP_MD *)nm->data, nm->name, NULL, md->arg); + md->fn((const WOLFSSL_EVP_MD *)nm->data, nm->name, NULL, md->arg); } /* call md_do_all function to do all md algorithm via a callback function @@ -10614,48 +10622,48 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) WOLFSSL_ENTER("EVP_DigestUpdate"); - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - wolfSSL_MD4_Update((MD4_CTX*)&ctx->hash, data, + wolfSSL_MD4_Update((WOLFSSL_MD4_CTX*)&ctx->hash, data, (unsigned long)sz); ret = WOLFSSL_SUCCESS; #endif break; case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data, + ret = wolfSSL_MD5_Update((WOLFSSL_MD5_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA_Update((WOLFSSL_SHA_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA224_Update((WOLFSSL_SHA224_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA256_Update((WOLFSSL_SHA256_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* !NO_SHA256 */ break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA384_Update((WOLFSSL_SHA384_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* WOLFSSL_SHA512 */ break; @@ -10664,7 +10672,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_224_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; @@ -10674,7 +10682,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Update((SHA512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA512_256_Update((WOLFSSL_SHA512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif /* WOLFSSL_SHA512 */ break; @@ -10682,25 +10690,25 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_224_Update((WOLFSSL_SHA3_224_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_256_Update((WOLFSSL_SHA3_256_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_384_Update((WOLFSSL_SHA3_384_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data, + ret = wolfSSL_SHA3_512_Update((WOLFSSL_SHA3_512_CTX*)&ctx->hash, data, (unsigned long)sz); #endif break; @@ -10741,48 +10749,48 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) enum wc_HashType macType; WOLFSSL_ENTER("EVP_DigestFinal"); - macType = EvpMd2MacType(EVP_MD_CTX_md(ctx)); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 - wolfSSL_MD4_Final(md, (MD4_CTX*)&ctx->hash); - if (s) *s = MD4_DIGEST_SIZE; + wolfSSL_MD4_Final(md, (WOLFSSL_MD4_CTX*)&ctx->hash); + if (s) *s = WC_MD4_DIGEST_SIZE; ret = WOLFSSL_SUCCESS; #endif break; case WC_HASH_TYPE_MD5: #ifndef NO_MD5 - ret = wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash); + ret = wolfSSL_MD5_Final(md, (WOLFSSL_MD5_CTX*)&ctx->hash); if (s) *s = WC_MD5_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA: #ifndef NO_SHA - ret = wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash); + ret = wolfSSL_SHA_Final(md, (WOLFSSL_SHA_CTX*)&ctx->hash); if (s) *s = WC_SHA_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA224: #ifdef WOLFSSL_SHA224 - ret = wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash); + ret = wolfSSL_SHA224_Final(md, (WOLFSSL_SHA224_CTX*)&ctx->hash); if (s) *s = WC_SHA224_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA256: #ifndef NO_SHA256 - ret = wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash); + ret = wolfSSL_SHA256_Final(md, (WOLFSSL_SHA256_CTX*)&ctx->hash); if (s) *s = WC_SHA256_DIGEST_SIZE; #endif /* !NO_SHA256 */ break; case WC_HASH_TYPE_SHA384: #ifdef WOLFSSL_SHA384 - ret = wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash); + ret = wolfSSL_SHA384_Final(md, (WOLFSSL_SHA384_CTX*)&ctx->hash); if (s) *s = WC_SHA384_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA512: #ifdef WOLFSSL_SHA512 - ret = wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_DIGEST_SIZE; #endif /* WOLFSSL_SHA512 */ break; @@ -10790,7 +10798,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_224: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_224_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_224_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_224_DIGEST_SIZE; #endif break; @@ -10799,32 +10807,32 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) case WC_HASH_TYPE_SHA512_256: #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) - ret = wolfSSL_SHA512_256_Final(md, (SHA512_CTX*)&ctx->hash); + ret = wolfSSL_SHA512_256_Final(md, (WOLFSSL_SHA512_CTX*)&ctx->hash); if (s) *s = WC_SHA512_256_DIGEST_SIZE; #endif break; #endif /* !WOLFSSL_NOSHA512_256 */ case WC_HASH_TYPE_SHA3_224: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224) - ret = wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_224_Final(md, (WOLFSSL_SHA3_224_CTX*)&ctx->hash); if (s) *s = WC_SHA3_224_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_256: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256) - ret = wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_256_Final(md, (WOLFSSL_SHA3_256_CTX*)&ctx->hash); if (s) *s = WC_SHA3_256_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_384: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384) - ret = wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_384_Final(md, (WOLFSSL_SHA3_384_CTX*)&ctx->hash); if (s) *s = WC_SHA3_384_DIGEST_SIZE; #endif break; case WC_HASH_TYPE_SHA3_512: #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512) - ret = wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash); + ret = wolfSSL_SHA3_512_Final(md, (WOLFSSL_SHA3_512_CTX*)&ctx->hash); if (s) *s = WC_SHA3_512_DIGEST_SIZE; #endif break; @@ -10863,7 +10871,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) unsigned int* s) { WOLFSSL_ENTER("EVP_DigestFinal_ex"); - return EVP_DigestFinal(ctx, md, s); + return wolfSSL_EVP_DigestFinal(ctx, md, s); } void wolfSSL_EVP_cleanup(void) @@ -10877,31 +10885,31 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) switch(id) { #ifndef NO_MD5 - case NID_md5: + case WC_NID_md5: return wolfSSL_EVP_md5(); #endif #ifndef NO_SHA - case NID_sha1: + case WC_NID_sha1: return wolfSSL_EVP_sha1(); #endif #ifdef WOLFSSL_SHA224 - case NID_sha224: + case WC_NID_sha224: return wolfSSL_EVP_sha224(); #endif #ifndef NO_SHA256 - case NID_sha256: + case WC_NID_sha256: return wolfSSL_EVP_sha256(); #endif #ifdef WOLFSSL_SHA384 - case NID_sha384: + case WC_NID_sha384: return wolfSSL_EVP_sha384(); #endif #ifdef WOLFSSL_SHA512 - case NID_sha512: + case WC_NID_sha512: return wolfSSL_EVP_sha512(); #endif #ifdef WOLFSSL_SM3 - case NID_sm3: + case WC_NID_sm3: return wolfSSL_EVP_sm3(); #endif default: @@ -10931,7 +10939,7 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) #endif #ifndef NO_MD4 if (XSTRCMP(type, "MD4") == 0) { - return MD4_BLOCK_SIZE; + return WC_MD4_BLOCK_SIZE; } else #endif #ifndef NO_MD5 @@ -11006,7 +11014,7 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) #endif #ifndef NO_MD4 if (XSTRCMP(type, "MD4") == 0) { - return MD4_DIGEST_SIZE; + return WC_MD4_DIGEST_SIZE; } else #endif #ifndef NO_MD5 @@ -11147,7 +11155,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) switch(key->type) { #ifndef NO_RSA - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: if (key->rsa != NULL && key->ownRsa == 1) { wolfSSL_RSA_free(key->rsa); key->rsa = NULL; @@ -11156,7 +11164,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* NO_RSA */ #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA) - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: if (key->ecc != NULL && key->ownEcc == 1) { wolfSSL_EC_KEY_free(key->ecc); key->ecc = NULL; @@ -11165,7 +11173,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* HAVE_ECC && OPENSSL_EXTRA */ #ifndef NO_DSA - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: if (key->dsa != NULL && key->ownDsa == 1) { wolfSSL_DSA_free(key->dsa); key->dsa = NULL; @@ -11175,7 +11183,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #if !defined(NO_DH) && (defined(WOLFSSL_QT) || \ defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: if (key->dh != NULL && key->ownDh == 1) { wolfSSL_DH_free(key->dh); key->dh = NULL; @@ -11184,7 +11192,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #endif /* ! NO_DH ... */ #ifdef HAVE_HKDF - case EVP_PKEY_HKDF: + case WC_EVP_PKEY_HKDF: XFREE(key->hkdfSalt, NULL, DYNAMIC_TYPE_SALT); key->hkdfSalt = NULL; XFREE(key->hkdfKey, NULL, DYNAMIC_TYPE_KEY); @@ -11199,7 +11207,7 @@ void wolfSSL_EVP_PKEY_free(WOLFSSL_EVP_PKEY* key) #if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \ defined(WOLFSSL_AES_DIRECT) - case EVP_PKEY_CMAC: + case WC_EVP_PKEY_CMAC: if (key->cmacCtx != NULL) { wolfSSL_CMAC_CTX_free(key->cmacCtx); key->cmacCtx = NULL; @@ -11230,8 +11238,8 @@ static int Indent(WOLFSSL_BIO* out, int indents) if (out == NULL) { return 0; } - if (indents > EVP_PKEY_PRINT_INDENT_MAX) { - indents = EVP_PKEY_PRINT_INDENT_MAX; + if (indents > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indents = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } for (i = 0; i < indents; i++) { if (wolfSSL_BIO_write(out, &space, 1) < 0) { @@ -11259,7 +11267,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, #ifdef WOLFSSL_SMALL_STACK byte* buff = NULL; #else - byte buff[EVP_PKEY_PRINT_LINE_WIDTH_MAX] = { 0 }; + byte buff[WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX] = { 0 }; #endif /* WOLFSSL_SMALL_STACK */ int ret = WOLFSSL_SUCCESS; word32 in = 0; @@ -11276,14 +11284,14 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } data = input; #ifdef WOLFSSL_SMALL_STACK - buff = (byte*)XMALLOC(EVP_PKEY_PRINT_LINE_WIDTH_MAX, NULL, + buff = (byte*)XMALLOC(WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (!buff) { return WOLFSSL_FAILURE; @@ -11294,9 +11302,9 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, idx = 0; for (in = 0; in < (word32)inlen && ret == WOLFSSL_SUCCESS; in += - EVP_PKEY_PRINT_DIGITS_PER_LINE ) { + WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE ) { Indent(out, indent); - for (i = 0; (i < EVP_PKEY_PRINT_DIGITS_PER_LINE) && + for (i = 0; (i < WOLFSSL_EVP_PKEY_PRINT_DIGITS_PER_LINE) && (in + i < (word32)inlen); i++) { if (ret == WOLFSSL_SUCCESS) { @@ -11325,7 +11333,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, ret = wolfSSL_BIO_write(out, "\n", 1) > 0; } if (ret == WOLFSSL_SUCCESS) { - XMEMSET(buff, 0, EVP_PKEY_PRINT_LINE_WIDTH_MAX); + XMEMSET(buff, 0, WOLFSSL_EVP_PKEY_PRINT_LINE_WIDTH_MAX); idx = 0; } } @@ -11347,7 +11355,7 @@ static int PrintHexWithColon(WOLFSSL_BIO* out, const byte* input, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; int res = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); @@ -11383,8 +11391,8 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -11501,7 +11509,7 @@ static int PrintPubKeyRSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte* pub = NULL; word32 pubSz = 0; @@ -11563,8 +11571,8 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - else if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + else if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } if (res == WOLFSSL_SUCCESS) { @@ -11697,7 +11705,7 @@ static int PrintPubKeyEC(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; @@ -11733,8 +11741,8 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -11916,7 +11924,7 @@ static int PrintPubKeyDSA(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Returns 1 on success, 0 on failure. */ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, - int indent, int bitlen, ASN1_PCTX* pctx) + int indent, int bitlen, WOLFSSL_ASN1_PCTX* pctx) { byte buff[8] = { 0 }; @@ -11957,8 +11965,8 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } do { @@ -12147,7 +12155,7 @@ static int PrintPubKeyDH(WOLFSSL_BIO* out, const byte* pkey, int pkeySz, * Can handle RSA, ECC, DSA and DH public keys. */ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, - const WOLFSSL_EVP_PKEY* pkey, int indent, ASN1_PCTX* pctx) + const WOLFSSL_EVP_PKEY* pkey, int indent, WOLFSSL_ASN1_PCTX* pctx) { int res; #if !defined(NO_RSA) || defined(HAVE_ECC) || !defined(NO_DSA) || \ @@ -12165,13 +12173,13 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, if (indent < 0) { indent = 0; } - if (indent > EVP_PKEY_PRINT_INDENT_MAX) { - indent = EVP_PKEY_PRINT_INDENT_MAX; + if (indent > WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX) { + indent = WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX; } #endif switch (pkey->type) { - case EVP_PKEY_RSA: + case WC_EVP_PKEY_RSA: #if !defined(NO_RSA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12187,7 +12195,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_EC: + case WC_EVP_PKEY_EC: #if defined(HAVE_ECC) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12203,7 +12211,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_DSA: + case WC_EVP_PKEY_DSA: #if !defined(NO_DSA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; @@ -12219,7 +12227,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, #endif break; - case EVP_PKEY_DH: + case WC_EVP_PKEY_DH: #if defined(WOLFSSL_DH_EXTRA) keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index c62ef35..37a381a 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -973,6 +973,25 @@ #define NO_AESGCM_AEAD #endif +#if defined(BUILD_TLS_RSA_WITH_AES_128_CCM_8) || \ + defined(BUILD_TLS_RSA_WITH_AES_256_CCM_8) || \ + defined(BUILD_TLS_PSK_WITH_AES_128_CCM_8) || \ + defined(BUILD_TLS_PSK_WITH_AES_128_CCM) || \ + defined(BUILD_TLS_PSK_WITH_AES_256_CCM_8) || \ + defined(BUILD_TLS_PSK_WITH_AES_256_CCM) || \ + defined(BUILD_TLS_DHE_PSK_WITH_AES_128_CCM) || \ + defined(BUILD_TLS_DHE_PSK_WITH_AES_256_CCM) || \ + defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM) || \ + defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8) || \ + defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8) || \ + defined(BUILD_TLS_AES_128_CCM_SHA256) || \ + defined(BUILD_TLS_AES_128_CCM_8_SHA256) + #define BUILD_AESCCM +#else + /* No AES-CCM cipher suites available with build */ + #define NO_AESCCM_AEAD +#endif + #if defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256) || \ defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384) #define BUILD_ARIA @@ -1002,7 +1021,8 @@ #endif #if defined(NO_AES) || !defined(HAVE_AES_DECRYPT) - #define AES_BLOCK_SIZE 16 + #undef WC_AES_BLOCK_SIZE + #define WC_AES_BLOCK_SIZE 16 #undef BUILD_AES #else #undef BUILD_AES @@ -1338,24 +1358,6 @@ enum { #define MAX_EARLY_DATA_SZ 4096 #endif -#ifndef NO_RSA - #ifndef WOLFSSL_MAX_RSA_BITS - #ifdef USE_FAST_MATH - /* FP implementation support numbers up to FP_MAX_BITS / 2 bits. */ - #define WOLFSSL_MAX_RSA_BITS (FP_MAX_BITS / 2) - #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) - /* SP implementation supports numbers of SP_INT_BITS bits. */ - #define WOLFSSL_MAX_RSA_BITS (((SP_INT_BITS + 7) / 8) * 8) - #else - /* Integer maths is dynamic but we only go up to 4096 bits. */ - #define WOLFSSL_MAX_RSA_BITS 4096 - #endif - #endif - #if (WOLFSSL_MAX_RSA_BITS % 8) - #error RSA maximum bit size must be multiple of 8 - #endif -#endif - #if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) /* MySQL wants to be able to use 8192-bit numbers. */ @@ -1383,9 +1385,9 @@ enum { #error "MySQL needs FP_MAX_BITS at least at 16384" #endif - #if !defined(NO_RSA) && defined(WOLFSSL_MAX_RSA_BITS) && \ - WOLFSSL_MAX_RSA_BITS > ENCRYPT_BASE_BITS - #error "FP_MAX_BITS too small for WOLFSSL_MAX_RSA_BITS" + #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \ + WC_MAX_RSA_BITS > ENCRYPT_BASE_BITS + #error "FP_MAX_BITS too small for WC_MAX_RSA_BITS" #endif #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) /* Use the SP size up to 8192-bit and down to a min of 1024-bit. */ @@ -1411,9 +1413,9 @@ enum { #error "MySQL needs SP_INT_BITS at least at 8192" #endif - #if !defined(NO_RSA) && defined(WOLFSSL_MAX_RSA_BITS) && \ - WOLFSSL_MAX_RSA_BITS > SP_INT_BITS - #error "SP_INT_BITS too small for WOLFSSL_MAX_RSA_BITS" + #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \ + WC_MAX_RSA_BITS > SP_INT_BITS + #error "SP_INT_BITS too small for WC_MAX_RSA_BITS" #endif #else /* Integer/heap maths - support 4096-bit. */ @@ -1754,7 +1756,7 @@ enum Misc { #endif #endif - MAX_IV_SZ = AES_BLOCK_SIZE, + MAX_IV_SZ = WC_AES_BLOCK_SIZE, AEAD_SEQ_OFFSET = 4, /* Auth Data: Sequence number */ AEAD_TYPE_OFFSET = 8, /* Auth Data: Type */ @@ -1811,6 +1813,13 @@ enum Misc { MAX_CURVE_NAME_SZ = 18, /* Maximum size of curve name string */ NEW_SA_MAJOR = 8, /* Most significant byte used with new sig algos */ + RSA_PSS_RSAE_SHA256_MINOR = 0x04, + RSA_PSS_RSAE_SHA384_MINOR = 0x05, + RSA_PSS_RSAE_SHA512_MINOR = 0x06, + RSA_PSS_PSS_SHA256_MINOR = 0x09, + RSA_PSS_PSS_SHA384_MINOR = 0x0A, + RSA_PSS_PSS_SHA512_MINOR = 0x0B, + ED25519_SA_MAJOR = 8, /* Most significant byte for ED25519 */ ED25519_SA_MINOR = 7, /* Least significant byte for ED25519 */ ED448_SA_MAJOR = 8, /* Most significant byte for ED448 */ @@ -1836,21 +1845,6 @@ enum Misc { MIN_RSA_SHA512_PSS_BITS = 512 * 2 + 8 * 8, /* Min key size */ MIN_RSA_SHA384_PSS_BITS = 384 * 2 + 8 * 8, /* Min key size */ -#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - MAX_CERT_VERIFY_SZ = 6000, /* For Dilithium */ -#elif defined(WOLFSSL_CERT_EXT) - MAX_CERT_VERIFY_SZ = 2048, /* For larger extensions */ -#elif !defined(NO_RSA) && defined(WOLFSSL_MAX_RSA_BITS) - MAX_CERT_VERIFY_SZ = WOLFSSL_MAX_RSA_BITS / 8, /* max RSA bytes */ -#elif defined(HAVE_ECC) - MAX_CERT_VERIFY_SZ = ECC_MAX_SIG_SIZE, /* max ECC */ -#elif defined(HAVE_ED448) - MAX_CERT_VERIFY_SZ = ED448_SIG_SIZE, /* max Ed448 */ -#elif defined(HAVE_ED25519) - MAX_CERT_VERIFY_SZ = ED25519_SIG_SIZE, /* max Ed25519 */ -#else - MAX_CERT_VERIFY_SZ = 1024, /* max default */ -#endif CLIENT_HELLO_FIRST = 35, /* Protocol + RAN_LEN + sizeof(id_len) */ MAX_SUITE_NAME = 48, /* maximum length of cipher suite string */ @@ -1865,6 +1859,12 @@ enum Misc { #ifndef MAX_WOLFSSL_FILE_SIZE MAX_WOLFSSL_FILE_SIZE = 1024UL * 1024UL * 4, /* 4 mb file size alloc limit */ #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + MAX_WOLFSSL_CRYPTO_POLICY_SIZE = 1024UL, /* Crypto-policy file is one line. + * It should not be large. */ + MIN_WOLFSSL_SEC_LEVEL = 0, + MAX_WOLFSSL_SEC_LEVEL = 5, +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ CERT_MIN_SIZE = 256, /* min PEM cert size with header/footer */ @@ -2422,16 +2422,16 @@ typedef struct CipherSuite { /* use wolfSSL_API visibility to be able to test in tests/api.c */ WOLFSSL_API void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have, - int tls1_2, int keySz, - word16* len); + int tls1_2, int keySz, word16* len); WOLFSSL_LOCAL int AllocateCtxSuites(WOLFSSL_CTX* ctx); WOLFSSL_LOCAL int AllocateSuites(WOLFSSL* ssl); WOLFSSL_LOCAL void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, word16 havePSK, word16 haveDH, word16 haveECDSAsig, word16 haveECC, word16 haveStaticRSA, word16 haveStaticECC, - word16 haveFalconSig, word16 haveDilithiumSig, - word16 haveAnon, word16 haveNull, int side); + word16 haveAnon, word16 haveNull, + word16 haveAES128, word16 haveSHA1, + word16 haveRC4, int side); typedef struct TLSX TLSX; WOLFSSL_LOCAL int MatchSuite_ex(const WOLFSSL* ssl, Suites* peerSuites, @@ -2701,6 +2701,9 @@ struct WOLFSSL_CERT_MANAGER { #ifdef WC_ASN_UNKNOWN_EXT_CB wc_UnknownExtCallback unknownExtCallback; #endif +#ifdef HAVE_CRL_UPDATE_CB + CbUpdateCRL cbUpdateCRL; /* notify thru cb that crl has updated */ +#endif }; WOLFSSL_LOCAL int CM_SaveCertCache(WOLFSSL_CERT_MANAGER* cm, @@ -2768,7 +2771,16 @@ struct WOLFSSL_SOCKADDR { }; typedef struct WOLFSSL_DTLS_CTX { +#ifdef WOLFSSL_RW_THREADED + /* Protect peer access after the handshake */ + wolfSSL_RwLock peerLock; +#endif WOLFSSL_SOCKADDR peer; +#ifdef WOLFSSL_DTLS_CID + WOLFSSL_SOCKADDR pendingPeer; /* When using CID's, we don't want to update + * the peer's address until we successfully + * de-protect the record. */ +#endif int rfd; int wfd; byte userSet:1; @@ -2776,6 +2788,9 @@ typedef struct WOLFSSL_DTLS_CTX { * connected (connect() and bind() both called). * This means that sendto and recvfrom do not need to * specify and store the peer address. */ +#ifdef WOLFSSL_DTLS_CID + byte processingPendingRecord:1; +#endif } WOLFSSL_DTLS_CTX; @@ -2797,6 +2812,7 @@ typedef struct WOLFSSL_DTLS_PEERSEQ { #endif } WOLFSSL_DTLS_PEERSEQ; +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) struct WOLFSSL_BIO { WOLFSSL_BUF_MEM* mem_buf; WOLFSSL_BIO_METHOD* method; @@ -2857,6 +2873,7 @@ struct WOLFSSL_BIO { wolfSSL_Ref ref; #endif }; +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(OPENSSL_EXTRA) WOLFSSL_LOCAL socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr); @@ -3572,7 +3589,7 @@ typedef struct KeyShareEntry { word32 keyLen; /* Key size (bytes) */ byte* pubKey; /* Public key */ word32 pubKeyLen; /* Public key length */ -#if !defined(NO_DH) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) +#if !defined(NO_DH) || defined(WOLFSSL_HAVE_KYBER) byte* privKey; /* Private key - DH and PQ KEMs only */ word32 privKeyLen;/* Only for PQ KEMs. */ #endif @@ -3720,6 +3737,7 @@ WOLFSSL_LOCAL int TLSX_ConnectionID_Parse(WOLFSSL* ssl, const byte* input, WOLFSSL_LOCAL void DtlsCIDOnExtensionsParsed(WOLFSSL* ssl); WOLFSSL_LOCAL byte DtlsCIDCheck(WOLFSSL* ssl, const byte* input, word16 inputSize); +WOLFSSL_LOCAL int Dtls13UnifiedHeaderCIDPresent(byte flags); #endif /* WOLFSSL_DTLS_CID */ WOLFSSL_LOCAL byte DtlsGetCidTxSize(WOLFSSL* ssl); WOLFSSL_LOCAL byte DtlsGetCidRxSize(WOLFSSL* ssl); @@ -3757,7 +3775,7 @@ struct WOLFSSL_CTX { #ifdef SINGLE_THREADED WC_RNG* rng; /* to be shared with WOLFSSL w/o locking */ #endif - wolfSSL_Ref ref; + wolfSSL_RefWithMutex ref; int err; /* error code in case of mutex not created */ #ifndef NO_DH buffer serverDH_P; @@ -4185,6 +4203,9 @@ struct WOLFSSL_CTX { byte *sigSpec; word16 sigSpecSz; #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + int secLevel; /* The security level of system-wide crypto policy. */ +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ }; WOLFSSL_LOCAL @@ -4381,7 +4402,7 @@ typedef struct Ciphers { byte* nonce; #endif #ifdef HAVE_CAMELLIA - Camellia* cam; + wc_Camellia* cam; #endif #ifdef HAVE_CHACHA ChaCha* chacha; @@ -5060,6 +5081,7 @@ struct Options { #if defined(HAVE_DANE) word16 useDANE:1; #endif /* HAVE_DANE */ + word16 disableRead:1; #ifdef WOLFSSL_DTLS byte haveMcast; /* using multicast ? */ #endif @@ -5204,6 +5226,8 @@ typedef enum { STACK_TYPE_X509_REQ_ATTR = 18, } WOLF_STACK_TYPE; +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + struct WOLFSSL_STACK { unsigned long num; /* number of nodes in stack * (safety measure for freeing and shortcut for count) */ @@ -5239,6 +5263,8 @@ struct WOLFSSL_STACK { WOLF_STACK_TYPE type; /* Identifies type of stack. */ }; +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + struct WOLFSSL_X509_NAME { char *name; int dynamicName; @@ -5329,7 +5355,7 @@ struct WOLFSSL_X509 { byte* rawCRLInfo; byte* CRLInfo; byte* authInfo; -#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) +#ifdef WOLFSSL_ASN_CA_ISSUER byte* authInfoCaIssuer; int authInfoCaIssuerSz; #endif @@ -5760,7 +5786,8 @@ struct WOLFSSL { #ifdef OPENSSL_EXTRA const Suites* clSuites; #endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ + defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) WOLF_STACK_OF(WOLFSSL_CIPHER)* suitesStack; /* stack of available cipher * suites */ #endif @@ -6261,7 +6288,19 @@ struct WOLFSSL { byte *peerSigSpec; /* This pointer always owns the memory. */ word16 peerSigSpecSz; #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + int secLevel; /* The security level of system-wide crypto policy. */ +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ +}; + +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) +#define WOLFSSL_SECLEVEL_STR "@SECLEVEL=" +struct SystemCryptoPolicy { + int enabled; + int secLevel; + char str[MAX_WOLFSSL_CRYPTO_POLICY_SIZE + 1]; /* + 1 for null term */ }; +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ /* * wolfSSL_PEM_read_bio_X509 pushes an ASN_NO_PEM_HEADER error @@ -6271,8 +6310,8 @@ struct WOLFSSL { #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_HAVE_ERROR_QUEUE) #define CLEAR_ASN_NO_PEM_HEADER_ERROR(err) \ (err) = wolfSSL_ERR_peek_last_error(); \ - if (ERR_GET_LIB(err) == ERR_LIB_PEM && \ - ERR_GET_REASON(err) == PEM_R_NO_START_LINE) { \ + if (wolfSSL_ERR_GET_LIB(err) == WOLFSSL_ERR_LIB_PEM && \ + wolfSSL_ERR_GET_REASON(err) == -WOLFSSL_PEM_R_NO_START_LINE_E) { \ wc_RemoveErrorNode(-1); \ } #else @@ -6308,7 +6347,10 @@ WOLFSSL_LOCAL int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL int ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL void FreeSSL(WOLFSSL* ssl, void* heap); -WOLFSSL_API void SSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ +WOLFSSL_API void wolfSSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ +#ifndef OPENSSL_COEXIST +#define SSL_ResourceFree wolfSSL_ResourceFree +#endif #ifndef NO_CERTS @@ -6535,8 +6577,10 @@ static WC_INLINE int wolfSSL_curve_is_disabled(const WOLFSSL* ssl, } #endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_LOCAL WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA *rsa, WC_RNG **tmpRNG, int *initTmpRng); +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifndef NO_CERTS #ifndef NO_RSA @@ -6706,6 +6750,10 @@ WOLFSSL_LOCAL word32 MacSize(const WOLFSSL* ssl); WOLFSSL_LOCAL int DoClientHelloStateless(WOLFSSL* ssl, const byte* input, word32 helloSz, byte isFirstCHFrag, byte* tls13); #endif /* !defined(NO_WOLFSSL_SERVER) */ +#if !defined(WOLFCRYPT_ONLY) && defined(USE_WOLFSSL_IO) + WOLFSSL_LOCAL int sockAddrEqual(SOCKADDR_S *a, XSOCKLENT aLen, + SOCKADDR_S *b, XSOCKLENT bLen); +#endif #endif /* WOLFSSL_DTLS */ #if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS) @@ -6818,6 +6866,7 @@ WOLFSSL_LOCAL int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys, WOLFSSL_LOCAL int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side); /* Set*Internal and Set*External functions */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_LOCAL int SetDsaInternal(WOLFSSL_DSA* dsa); WOLFSSL_LOCAL int SetDsaExternal(WOLFSSL_DSA* dsa); WOLFSSL_LOCAL int SetRsaExternal(WOLFSSL_RSA* rsa); @@ -6833,6 +6882,7 @@ typedef enum elem_set { WOLFSSL_LOCAL int SetDhExternal_ex(WOLFSSL_DH *dh, int elm ); WOLFSSL_LOCAL int SetDhInternal(WOLFSSL_DH* dh); WOLFSSL_LOCAL int SetDhExternal(WOLFSSL_DH *dh); +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK)) WOLFSSL_LOCAL int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey, @@ -7013,11 +7063,7 @@ WOLFSSL_LOCAL int GetX509Error(int e); #endif #endif -#if defined(HAVE_EX_DATA) && \ - (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ - defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_LIGHTY)) || defined(HAVE_EX_DATA) || \ - defined(WOLFSSL_WPAS_SMALL) +#ifdef HAVE_EX_DATA_CRYPTO typedef struct CRYPTO_EX_cb_ctx { long ctx_l; void *ctx_ptr; @@ -7026,6 +7072,7 @@ typedef struct CRYPTO_EX_cb_ctx { WOLFSSL_CRYPTO_EX_dup* dup_func; struct CRYPTO_EX_cb_ctx* next; } CRYPTO_EX_cb_ctx; + /* use wolfSSL_API visibility to be able to clear in tests/api.c */ WOLFSSL_API extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session; WOLFSSL_API void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx); @@ -7038,19 +7085,19 @@ WOLFSSL_LOCAL int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in, WOLFSSL_LOCAL int wolfssl_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr, WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, WOLFSSL_CRYPTO_EX_free* free_func); -#endif +#endif /* HAVE_EX_DATA_CRYPTO */ WOLFSSL_LOCAL WC_RNG* wolfssl_get_global_rng(void); WOLFSSL_LOCAL WC_RNG* wolfssl_make_global_rng(void); #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER) -WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher, +WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz); #endif #endif -#if !defined(NO_RSA) +#if !defined(NO_RSA) && defined(OPENSSL_EXTRA) WOLFSSL_LOCAL int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey, void* heap); #endif @@ -7116,11 +7163,13 @@ WOLFSSL_LOCAL int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj, const byte* der, word32 len, int addHdr); #endif +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_LOCAL int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz); WOLFSSL_LOCAL int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key, word32* keySz); +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/openssl/aes.h b/src/wolfssl/openssl/aes.h index 2991ff0..25110c8 100644 --- a/src/wolfssl/openssl/aes.h +++ b/src/wolfssl/openssl/aes.h @@ -53,27 +53,37 @@ typedef struct WOLFSSL_AES_KEY { ALIGN16 void *buf[(sizeof(Aes) / sizeof(void *)) + 1]; } WOLFSSL_AES_KEY; -typedef WOLFSSL_AES_KEY AES_KEY; WOLFSSL_API int wolfSSL_AES_set_encrypt_key( - const unsigned char *key, const int bits, AES_KEY *aes); + const unsigned char *key, const int bits, WOLFSSL_AES_KEY *aes); WOLFSSL_API int wolfSSL_AES_set_decrypt_key( - const unsigned char *key, const int bits, AES_KEY *aes); + const unsigned char *key, const int bits, WOLFSSL_AES_KEY *aes); WOLFSSL_API void wolfSSL_AES_cbc_encrypt( - const unsigned char *in, unsigned char* out, size_t len, AES_KEY *key, + const unsigned char *in, unsigned char* out, size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, const int enc); WOLFSSL_API void wolfSSL_AES_ecb_encrypt( - const unsigned char *in, unsigned char* out, AES_KEY *key, const int enc); + const unsigned char *in, unsigned char* out, WOLFSSL_AES_KEY *key, const int enc); WOLFSSL_API void wolfSSL_AES_cfb128_encrypt( - const unsigned char *in, unsigned char* out, size_t len, AES_KEY *key, + const unsigned char *in, unsigned char* out, size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, int* num, const int enc); WOLFSSL_API int wolfSSL_AES_wrap_key( - AES_KEY *key, const unsigned char *iv, unsigned char *out, + WOLFSSL_AES_KEY *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, unsigned int inlen); WOLFSSL_API int wolfSSL_AES_unwrap_key( - AES_KEY *key, const unsigned char *iv, unsigned char *out, + WOLFSSL_AES_KEY *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, unsigned int inlen); +#ifdef WOLFSSL_AES_DIRECT +WOLFSSL_API void wolfSSL_AES_encrypt( + const unsigned char* input, unsigned char* output, WOLFSSL_AES_KEY *key); +WOLFSSL_API void wolfSSL_AES_decrypt( + const unsigned char* input, unsigned char* output, WOLFSSL_AES_KEY *key); +#endif /* WOLFSSL_AES_DIRECT */ + +#ifndef OPENSSL_COEXIST + +typedef WOLFSSL_AES_KEY AES_KEY; + #define AES_cbc_encrypt wolfSSL_AES_cbc_encrypt #define AES_ecb_encrypt wolfSSL_AES_ecb_encrypt #define AES_cfb128_encrypt wolfSSL_AES_cfb128_encrypt @@ -83,11 +93,6 @@ WOLFSSL_API int wolfSSL_AES_unwrap_key( #define AES_unwrap_key wolfSSL_AES_unwrap_key #ifdef WOLFSSL_AES_DIRECT -WOLFSSL_API void wolfSSL_AES_encrypt( - const unsigned char* input, unsigned char* output, AES_KEY *key); -WOLFSSL_API void wolfSSL_AES_decrypt( - const unsigned char* input, unsigned char* output, AES_KEY *key); - #define AES_encrypt wolfSSL_AES_encrypt #define AES_decrypt wolfSSL_AES_decrypt #endif /* WOLFSSL_AES_DIRECT */ @@ -99,6 +104,8 @@ WOLFSSL_API void wolfSSL_AES_decrypt( #define AES_DECRYPT AES_DECRYPTION #endif +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/asn1.h b/src/wolfssl/openssl/asn1.h index 5fbb726..5b4f25a 100644 --- a/src/wolfssl/openssl/asn1.h +++ b/src/wolfssl/openssl/asn1.h @@ -26,6 +26,8 @@ #include +#ifndef OPENSSL_COEXIST + #define ASN1_STRING_new wolfSSL_ASN1_STRING_new #define ASN1_STRING_type_new wolfSSL_ASN1_STRING_type_new #define ASN1_STRING_type wolfSSL_ASN1_STRING_type @@ -37,33 +39,28 @@ #define d2i_ASN1_OBJECT wolfSSL_d2i_ASN1_OBJECT #define c2i_ASN1_OBJECT wolfSSL_c2i_ASN1_OBJECT -#define V_ASN1_INTEGER 0x02 -#define V_ASN1_NEG 0x100 -#define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG) -#define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG) +#define V_ASN1_INTEGER WOLFSSL_V_ASN1_INTEGER +#define V_ASN1_NEG WOLFSSL_V_ASN1_NEG +#define V_ASN1_NEG_INTEGER WOLFSSL_V_ASN1_NEG_INTEGER +#define V_ASN1_NEG_ENUMERATED WOLFSSL_V_ASN1_NEG_ENUMERATED /* Type for ASN1_print_ex */ -# define ASN1_STRFLGS_ESC_2253 1 -# define ASN1_STRFLGS_ESC_CTRL 2 -# define ASN1_STRFLGS_ESC_MSB 4 -# define ASN1_STRFLGS_ESC_QUOTE 8 -# define ASN1_STRFLGS_UTF8_CONVERT 0x10 -# define ASN1_STRFLGS_IGNORE_TYPE 0x20 -# define ASN1_STRFLGS_SHOW_TYPE 0x40 -# define ASN1_STRFLGS_DUMP_ALL 0x80 -# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100 -# define ASN1_STRFLGS_DUMP_DER 0x200 -# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \ - ASN1_STRFLGS_ESC_CTRL | \ - ASN1_STRFLGS_ESC_MSB | \ - ASN1_STRFLGS_UTF8_CONVERT | \ - ASN1_STRFLGS_DUMP_UNKNOWN | \ - ASN1_STRFLGS_DUMP_DER) - -#define MBSTRING_UTF8 0x1000 -#define MBSTRING_ASC 0x1001 -#define MBSTRING_BMP 0x1002 -#define MBSTRING_UNIV 0x1004 +#define ASN1_STRFLGS_ESC_2253 WOLFSSL_ASN1_STRFLGS_ESC_2253 +#define ASN1_STRFLGS_ESC_CTRL WOLFSSL_ASN1_STRFLGS_ESC_CTRL +#define ASN1_STRFLGS_ESC_MSB WOLFSSL_ASN1_STRFLGS_ESC_MSB +#define ASN1_STRFLGS_ESC_QUOTE WOLFSSL_ASN1_STRFLGS_ESC_QUOTE +#define ASN1_STRFLGS_UTF8_CONVERT WOLFSSL_ASN1_STRFLGS_UTF8_CONVERT +#define ASN1_STRFLGS_IGNORE_TYPE WOLFSSL_ASN1_STRFLGS_IGNORE_TYPE +#define ASN1_STRFLGS_SHOW_TYPE WOLFSSL_ASN1_STRFLGS_SHOW_TYPE +#define ASN1_STRFLGS_DUMP_ALL WOLFSSL_ASN1_STRFLGS_DUMP_ALL +#define ASN1_STRFLGS_DUMP_UNKNOWN WOLFSSL_ASN1_STRFLGS_DUMP_UNKNOWN +#define ASN1_STRFLGS_DUMP_DER WOLFSSL_ASN1_STRFLGS_DUMP_DER +#define ASN1_STRFLGS_RFC2253 WOLFSSL_ASN1_STRFLGS_RFC2253 + +#define MBSTRING_UTF8 WOLFSSL_MBSTRING_UTF8 +#define MBSTRING_ASC WOLFSSL_MBSTRING_ASC +#define MBSTRING_BMP WOLFSSL_MBSTRING_BMP +#define MBSTRING_UNIV WOLFSSL_MBSTRING_UNIV #define ASN1_UTCTIME_print wolfSSL_ASN1_UTCTIME_print #define ASN1_TIME_check wolfSSL_ASN1_TIME_check @@ -71,42 +68,42 @@ #define ASN1_TIME_compare wolfSSL_ASN1_TIME_compare #define ASN1_TIME_set wolfSSL_ASN1_TIME_set -#define V_ASN1_EOC 0 -#define V_ASN1_BOOLEAN 1 -#define V_ASN1_OCTET_STRING 4 -#define V_ASN1_NULL 5 -#define V_ASN1_OBJECT 6 -#define V_ASN1_UTF8STRING 12 -#define V_ASN1_SEQUENCE 16 -#define V_ASN1_SET 17 -#define V_ASN1_PRINTABLESTRING 19 -#define V_ASN1_T61STRING 20 -#define V_ASN1_IA5STRING 22 -#define V_ASN1_UTCTIME 23 -#define V_ASN1_GENERALIZEDTIME 24 -#define V_ASN1_UNIVERSALSTRING 28 -#define V_ASN1_BMPSTRING 30 - - -#define V_ASN1_CONSTRUCTED 0x20 - -#define ASN1_STRING_FLAG_BITS_LEFT 0x008 -#define ASN1_STRING_FLAG_NDEF 0x010 -#define ASN1_STRING_FLAG_CONT 0x020 -#define ASN1_STRING_FLAG_MSTRING 0x040 -#define ASN1_STRING_FLAG_EMBED 0x080 +#define V_ASN1_EOC WOLFSSL_V_ASN1_EOC +#define V_ASN1_BOOLEAN WOLFSSL_V_ASN1_BOOLEAN +#define V_ASN1_OCTET_STRING WOLFSSL_V_ASN1_OCTET_STRING +#define V_ASN1_NULL WOLFSSL_V_ASN1_NULL +#define V_ASN1_OBJECT WOLFSSL_V_ASN1_OBJECT +#define V_ASN1_UTF8STRING WOLFSSL_V_ASN1_UTF8STRING +#define V_ASN1_SEQUENCE WOLFSSL_V_ASN1_SEQUENCE +#define V_ASN1_SET WOLFSSL_V_ASN1_SET +#define V_ASN1_PRINTABLESTRING WOLFSSL_V_ASN1_PRINTABLESTRING +#define V_ASN1_T61STRING WOLFSSL_V_ASN1_T61STRING +#define V_ASN1_IA5STRING WOLFSSL_V_ASN1_IA5STRING +#define V_ASN1_UTCTIME WOLFSSL_V_ASN1_UTCTIME +#define V_ASN1_GENERALIZEDTIME WOLFSSL_V_ASN1_GENERALIZEDTIME +#define V_ASN1_UNIVERSALSTRING WOLFSSL_V_ASN1_UNIVERSALSTRING +#define V_ASN1_BMPSTRING WOLFSSL_V_ASN1_BMPSTRING + +#define V_ASN1_CONSTRUCTED WOLFSSL_V_ASN1_CONSTRUCTED + +#define ASN1_STRING_FLAG_BITS_LEFT WOLFSSL_ASN1_STRING_FLAG_BITS_LEFT +#define ASN1_STRING_FLAG_NDEF WOLFSSL_ASN1_STRING_FLAG_NDEF +#define ASN1_STRING_FLAG_CONT WOLFSSL_ASN1_STRING_FLAG_CONT +#define ASN1_STRING_FLAG_MSTRING WOLFSSL_ASN1_STRING_FLAG_MSTRING +#define ASN1_STRING_FLAG_EMBED WOLFSSL_ASN1_STRING_FLAG_EMBED /* X.509 PKI size limits from RFC2459 (appendix A) */ /* internally our limit is CTC_NAME_SIZE (64) - overridden with WC_CTC_NAME_SIZE */ -#define ub_name CTC_NAME_SIZE /* 32768 */ -#define ub_common_name CTC_NAME_SIZE /* 64 */ -#define ub_locality_name CTC_NAME_SIZE /* 128 */ -#define ub_state_name CTC_NAME_SIZE /* 128 */ -#define ub_organization_name CTC_NAME_SIZE /* 64 */ -#define ub_organization_unit_name CTC_NAME_SIZE /* 64 */ -#define ub_title CTC_NAME_SIZE /* 64 */ -#define ub_email_address CTC_NAME_SIZE /* 128 */ - +#define ub_name WOLFSSL_ub_name +#define ub_common_name WOLFSSL_ub_common_name +#define ub_locality_name WOLFSSL_ub_locality_name +#define ub_state_name WOLFSSL_ub_state_name +#define ub_organization_name WOLFSSL_ub_organization_name +#define ub_organization_unit_name WOLFSSL_ub_organization_unit_name +#define ub_title WOLFSSL_ub_title +#define ub_email_address WOLFSSL_ub_email_address + +#endif /* !OPENSSL_COEXIST */ WOLFSSL_API WOLFSSL_ASN1_INTEGER *wolfSSL_BN_to_ASN1_INTEGER( const WOLFSSL_BIGNUM *bn, WOLFSSL_ASN1_INTEGER *ai); diff --git a/src/wolfssl/openssl/bio.h b/src/wolfssl/openssl/bio.h index 198ca4e..cf6571b 100644 --- a/src/wolfssl/openssl/bio.h +++ b/src/wolfssl/openssl/bio.h @@ -33,11 +33,57 @@ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +/* helper to set specific retry/read flags */ +#define wolfSSL_BIO_set_retry_read(bio)\ + wolfSSL_BIO_set_flags((bio), WOLFSSL_BIO_FLAG_RETRY | WOLFSSL_BIO_FLAG_READ) +#define wolfSSL_BIO_set_retry_write(bio)\ + wolfSSL_BIO_set_flags((bio), WOLFSSL_BIO_FLAG_RETRY | WOLFSSL_BIO_FLAG_WRITE) + +/* BIO CTRL */ +#define WOLFSSL_BIO_CTRL_RESET 1 +#define WOLFSSL_BIO_CTRL_EOF 2 +#define WOLFSSL_BIO_CTRL_INFO 3 +#define WOLFSSL_BIO_CTRL_SET 4 +#define WOLFSSL_BIO_CTRL_GET 5 +#define WOLFSSL_BIO_CTRL_PUSH 6 +#define WOLFSSL_BIO_CTRL_POP 7 +#define WOLFSSL_BIO_CTRL_GET_CLOSE 8 +#define WOLFSSL_BIO_CTRL_SET_CLOSE 9 +#define WOLFSSL_BIO_CTRL_PENDING 10 +#define WOLFSSL_BIO_CTRL_FLUSH 11 +#define WOLFSSL_BIO_CTRL_DUP 12 +#define WOLFSSL_BIO_CTRL_WPENDING 13 + +#define WOLFSSL_BIO_C_SET_FILE_PTR 106 +#define WOLFSSL_BIO_C_GET_FILE_PTR 107 +#define WOLFSSL_BIO_C_SET_FILENAME 108 +#define WOLFSSL_BIO_C_SET_BUF_MEM 114 +#define WOLFSSL_BIO_C_GET_BUF_MEM_PTR 115 +#define WOLFSSL_BIO_C_FILE_SEEK 128 +#define WOLFSSL_BIO_C_SET_BUF_MEM_EOF_RETURN 130 +#define WOLFSSL_BIO_C_SET_WRITE_BUF_SIZE 136 +#define WOLFSSL_BIO_C_MAKE_WOLFSSL_BIO_PAIR 138 + +#define WOLFSSL_BIO_CTRL_DGRAM_CONNECT 31 +#define WOLFSSL_BIO_CTRL_DGRAM_SET_CONNECTED 32 +#define WOLFSSL_BIO_CTRL_DGRAM_QUERY_MTU 40 +#define WOLFSSL_BIO_CTRL_DGRAM_SET_PEER 44 + +#define WOLFSSL_BIO_FP_TEXT 0x00 +#define WOLFSSL_BIO_NOCLOSE 0x00 +#define WOLFSSL_BIO_CLOSE 0x01 + +#define WOLFSSL_BIO_FP_WRITE 0x04 + +#ifndef OPENSSL_COEXIST + #define BIO_FLAGS_BASE64_NO_NL WOLFSSL_BIO_FLAG_BASE64_NO_NL #define BIO_FLAGS_READ WOLFSSL_BIO_FLAG_READ #define BIO_FLAGS_WRITE WOLFSSL_BIO_FLAG_WRITE #define BIO_FLAGS_IO_SPECIAL WOLFSSL_BIO_FLAG_IO_SPECIAL #define BIO_FLAGS_SHOULD_RETRY WOLFSSL_BIO_FLAG_RETRY +/* You shouldn't free up or change the data if BIO_FLAGS_MEM_RDONLY is set */ +#define BIO_FLAGS_MEM_RDONLY WOLFSSL_BIO_FLAG_MEM_RDONLY #define BIO_new_fp wolfSSL_BIO_new_fp #if defined(OPENSSL_ALL) \ @@ -124,10 +170,8 @@ #define BIO_get_ex_data wolfSSL_BIO_get_ex_data /* helper to set specific retry/read flags */ -#define BIO_set_retry_read(bio)\ - wolfSSL_BIO_set_flags((bio), WOLFSSL_BIO_FLAG_RETRY | WOLFSSL_BIO_FLAG_READ) -#define BIO_set_retry_write(bio)\ - wolfSSL_BIO_set_flags((bio), WOLFSSL_BIO_FLAG_RETRY | WOLFSSL_BIO_FLAG_WRITE) +#define BIO_set_retry_read(bio) wolfSSL_BIO_set_retry_read(bio) +#define BIO_set_retry_write(bio) wolfSSL_BIO_set_retry_write(bio) #define BIO_clear_retry_flags wolfSSL_BIO_clear_retry_flags @@ -145,43 +189,42 @@ #define BIO_snprintf XSNPRINTF /* BIO CTRL */ -#define BIO_CTRL_RESET 1 -#define BIO_CTRL_EOF 2 -#define BIO_CTRL_INFO 3 -#define BIO_CTRL_SET 4 -#define BIO_CTRL_GET 5 -#define BIO_CTRL_PUSH 6 -#define BIO_CTRL_POP 7 -#define BIO_CTRL_GET_CLOSE 8 -#define BIO_CTRL_SET_CLOSE 9 -#define BIO_CTRL_PENDING 10 -#define BIO_CTRL_FLUSH 11 -#define BIO_CTRL_DUP 12 -#define BIO_CTRL_WPENDING 13 - -#define BIO_C_SET_FILE_PTR 106 -#define BIO_C_GET_FILE_PTR 107 -#define BIO_C_SET_FILENAME 108 -#define BIO_C_SET_BUF_MEM 114 -#define BIO_C_GET_BUF_MEM_PTR 115 -#define BIO_C_FILE_SEEK 128 -#define BIO_C_SET_BUF_MEM_EOF_RETURN 130 -#define BIO_C_SET_WRITE_BUF_SIZE 136 -#define BIO_C_MAKE_BIO_PAIR 138 - -#define BIO_CTRL_DGRAM_CONNECT 31 -#define BIO_CTRL_DGRAM_SET_CONNECTED 32 -#define BIO_CTRL_DGRAM_QUERY_MTU 40 -#define BIO_CTRL_DGRAM_SET_PEER 44 - -#define BIO_FP_TEXT 0x00 -#define BIO_NOCLOSE 0x00 -#define BIO_CLOSE 0x01 - -#define BIO_FP_WRITE 0x04 - -/* You shouldn't free up or change the data if BIO_FLAGS_MEM_RDONLY is set */ -#define BIO_FLAGS_MEM_RDONLY 0x200 +#define BIO_CTRL_RESET WOLFSSL_BIO_CTRL_RESET +#define BIO_CTRL_EOF WOLFSSL_BIO_CTRL_EOF +#define BIO_CTRL_INFO WOLFSSL_BIO_CTRL_INFO +#define BIO_CTRL_SET WOLFSSL_BIO_CTRL_SET +#define BIO_CTRL_GET WOLFSSL_BIO_CTRL_GET +#define BIO_CTRL_PUSH WOLFSSL_BIO_CTRL_PUSH +#define BIO_CTRL_POP WOLFSSL_BIO_CTRL_POP +#define BIO_CTRL_GET_CLOSE WOLFSSL_BIO_CTRL_GET_CLOSE +#define BIO_CTRL_SET_CLOSE WOLFSSL_BIO_CTRL_SET_CLOSE +#define BIO_CTRL_PENDING WOLFSSL_BIO_CTRL_PENDING +#define BIO_CTRL_FLUSH WOLFSSL_BIO_CTRL_FLUSH +#define BIO_CTRL_DUP WOLFSSL_BIO_CTRL_DUP +#define BIO_CTRL_WPENDING WOLFSSL_BIO_CTRL_WPENDING + +#define BIO_C_SET_FILE_PTR WOLFSSL_BIO_C_SET_FILE_PTR +#define BIO_C_GET_FILE_PTR WOLFSSL_BIO_C_GET_FILE_PTR +#define BIO_C_SET_FILENAME WOLFSSL_BIO_C_SET_FILENAME +#define BIO_C_SET_BUF_MEM WOLFSSL_BIO_C_SET_BUF_MEM +#define BIO_C_GET_BUF_MEM_PTR WOLFSSL_BIO_C_GET_BUF_MEM_PTR +#define BIO_C_FILE_SEEK WOLFSSL_BIO_C_FILE_SEEK +#define BIO_C_SET_BUF_MEM_EOF_RETURN WOLFSSL_BIO_C_SET_BUF_MEM_EOF_RETURN +#define BIO_C_SET_WRITE_BUF_SIZE WOLFSSL_BIO_C_SET_WRITE_BUF_SIZE +#define BIO_C_MAKE_BIO_PAIR WOLFSSL_BIO_C_MAKE_BIO_PAIR + +#define BIO_CTRL_DGRAM_CONNECT WOLFSSL_BIO_CTRL_DGRAM_CONNECT +#define BIO_CTRL_DGRAM_SET_CONNECTED WOLFSSL_BIO_CTRL_DGRAM_SET_CONNECTED +#define BIO_CTRL_DGRAM_QUERY_MTU WOLFSSL_BIO_CTRL_DGRAM_QUERY_MTU +#define BIO_CTRL_DGRAM_SET_PEER WOLFSSL_BIO_CTRL_DGRAM_SET_PEER + +#define BIO_FP_TEXT WOLFSSL_BIO_FP_TEXT +#define BIO_NOCLOSE WOLFSSL_BIO_NOCLOSE +#define BIO_CLOSE WOLFSSL_BIO_CLOSE + +#define BIO_FP_WRITE WOLFSSL_BIO_FP_WRITE + +#endif /* !OPENSSL_COEXIST */ #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ diff --git a/src/wolfssl/openssl/bn.h b/src/wolfssl/openssl/bn.h index a3afd61..ed8ae43 100644 --- a/src/wolfssl/openssl/bn.h +++ b/src/wolfssl/openssl/bn.h @@ -185,7 +185,7 @@ WOLFSSL_API WOLFSSL_BIGNUM *wolfSSL_BN_mod_inverse( WOLFSSL_BN_CTX *ctx); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) #define BN_RAND_TOP_ANY WOLFSSL_BN_RAND_TOP_ANY #define BN_RAND_TOP_ONE WOLFSSL_BN_RAND_TOP_ONE @@ -290,7 +290,7 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_prime_checks 0 -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/buffer.h b/src/wolfssl/openssl/buffer.h index c9f2790..c4195cf 100644 --- a/src/wolfssl/openssl/buffer.h +++ b/src/wolfssl/openssl/buffer.h @@ -38,6 +38,7 @@ WOLFSSL_API int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len, WOLFSSL_API int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len); WOLFSSL_API void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf); +#ifndef OPENSSL_COEXIST #define BUF_MEM_new wolfSSL_BUF_MEM_new #define BUF_MEM_grow wolfSSL_BUF_MEM_grow @@ -47,6 +48,8 @@ WOLFSSL_API void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf); #define BUF_strlcpy wc_strlcpy #define BUF_strlcat wc_strlcat +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/cmac.h b/src/wolfssl/openssl/cmac.h index dd08497..120fd1d 100644 --- a/src/wolfssl/openssl/cmac.h +++ b/src/wolfssl/openssl/cmac.h @@ -34,8 +34,6 @@ typedef struct WOLFSSL_CMAC_CTX { WOLFSSL_EVP_CIPHER_CTX* cctx; } WOLFSSL_CMAC_CTX; -typedef WOLFSSL_CMAC_CTX CMAC_CTX; - WOLFSSL_API WOLFSSL_CMAC_CTX* wolfSSL_CMAC_CTX_new(void); WOLFSSL_API void wolfSSL_CMAC_CTX_free(WOLFSSL_CMAC_CTX *ctx); WOLFSSL_API WOLFSSL_EVP_CIPHER_CTX* wolfSSL_CMAC_CTX_get0_cipher_ctx( @@ -48,6 +46,10 @@ WOLFSSL_API int wolfSSL_CMAC_Update( WOLFSSL_API int wolfSSL_CMAC_Final( WOLFSSL_CMAC_CTX* ctx, unsigned char* out, size_t* len); +#ifndef OPENSSL_COEXIST + +typedef WOLFSSL_CMAC_CTX CMAC_CTX; + #define CMAC_CTX_new wolfSSL_CMAC_CTX_new #define CMAC_CTX_free wolfSSL_CMAC_CTX_free #define CMAC_CTX_get0_cipher_ctx wolfSSL_CMAC_CTX_get0_cipher_ctx @@ -55,6 +57,8 @@ WOLFSSL_API int wolfSSL_CMAC_Final( #define CMAC_Update wolfSSL_CMAC_Update #define CMAC_Final wolfSSL_CMAC_Final +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/compat_types.h b/src/wolfssl/openssl/compat_types.h index 61cc80a..00bfde1 100644 --- a/src/wolfssl/openssl/compat_types.h +++ b/src/wolfssl/openssl/compat_types.h @@ -52,7 +52,7 @@ typedef struct WOLFSSL_ASN1_PCTX WOLFSSL_ASN1_PCTX; typedef struct WOLFSSL_BIO WOLFSSL_BIO; -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) typedef WOLFSSL_EVP_MD EVP_MD; typedef WOLFSSL_EVP_MD_CTX EVP_MD_CTX; typedef WOLFSSL_EVP_CIPHER EVP_CIPHER; @@ -63,7 +63,7 @@ typedef WOLFSSL_EVP_PKEY PKCS8_PRIV_KEY_INFO; typedef WOLFSSL_ENGINE ENGINE; typedef WOLFSSL_EVP_PKEY_CTX EVP_PKEY_CTX; -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ typedef unsigned long (*wolf_sk_hash_cb) (const void *v); diff --git a/src/wolfssl/openssl/conf.h b/src/wolfssl/openssl/conf.h index 4e9115f..411a3e0 100644 --- a/src/wolfssl/openssl/conf.h +++ b/src/wolfssl/openssl/conf.h @@ -45,8 +45,10 @@ typedef struct WOLFSSL_CONF { WOLF_LHASH_OF(WOLFSSL_CONF_VALUE) *data; } WOLFSSL_CONF; +#ifndef OPENSSL_COEXIST typedef WOLFSSL_CONF CONF; typedef WOLFSSL_CONF_VALUE CONF_VALUE; +#endif #ifdef OPENSSL_EXTRA @@ -58,7 +60,7 @@ WOLFSSL_API void wolfSSL_X509V3_conf_free(WOLFSSL_CONF_VALUE *val); WOLFSSL_API WOLFSSL_CONF *wolfSSL_NCONF_new(void *meth); WOLFSSL_API char *wolfSSL_NCONF_get_string(const WOLFSSL_CONF *conf, const char *group, const char *name); -WOLFSSL_API int wolfSSL_NCONF_get_number(const CONF *conf, const char *group, +WOLFSSL_API int wolfSSL_NCONF_get_number(const WOLFSSL_CONF *conf, const char *group, const char *name, long *result); WOLFSSL_API WOLFSSL_STACK *wolfSSL_NCONF_get_section( const WOLFSSL_CONF *conf, const char *section); @@ -80,6 +82,7 @@ WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509V3_EXT_nconf_nid(WOLFSSL_CONF* c WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509V3_EXT_nconf(WOLFSSL_CONF *conf, WOLFSSL_X509V3_CTX *ctx, const char *sName, const char *value); +#ifndef OPENSSL_COEXIST #define sk_CONF_VALUE_new wolfSSL_sk_CONF_VALUE_new #define sk_CONF_VALUE_free wolfSSL_sk_CONF_VALUE_free #define sk_CONF_VALUE_pop_free(a,b) wolfSSL_sk_CONF_VALUE_free(a) @@ -103,6 +106,7 @@ WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509V3_EXT_nconf(WOLFSSL_CONF *conf, #define X509V3_EXT_nconf_nid wolfSSL_X509V3_EXT_nconf_nid #define X509V3_EXT_nconf wolfSSL_X509V3_EXT_nconf #define X509V3_conf_free wolfSSL_X509V3_conf_free +#endif /* !OPENSSL_COEXIST */ #endif /* OPENSSL_EXTRA */ diff --git a/src/wolfssl/openssl/crypto.h b/src/wolfssl/openssl/crypto.h index e436e93..33a279a 100644 --- a/src/wolfssl/openssl/crypto.h +++ b/src/wolfssl/openssl/crypto.h @@ -29,14 +29,20 @@ typedef struct WOLFSSL_INIT_SETTINGS { char* appname; } WOLFSSL_INIT_SETTINGS; -typedef WOLFSSL_INIT_SETTINGS OPENSSL_INIT_SETTINGS; +#ifndef OPENSSL_COEXIST +#define OPENSSL_INIT_SETTINGS WOLFSSL_INIT_SETTINGS +#endif typedef struct WOLFSSL_CRYPTO_THREADID { int dummy; } WOLFSSL_CRYPTO_THREADID; +#ifndef OPENSSL_COEXIST typedef struct crypto_threadid_st CRYPTO_THREADID; +#endif +#ifndef OPENSSL_COEXIST typedef struct CRYPTO_EX_DATA CRYPTO_EX_DATA; +#endif #ifdef HAVE_EX_DATA typedef WOLFSSL_CRYPTO_EX_new CRYPTO_new_func; @@ -68,10 +74,13 @@ WOLFSSL_API void *wolfSSL_OPENSSL_malloc(size_t a); WOLFSSL_API int wolfSSL_OPENSSL_hexchar2int(unsigned char c); WOLFSSL_API unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len); -WOLFSSL_API int wolfSSL_OPENSSL_init_crypto(word64 opts, const OPENSSL_INIT_SETTINGS *settings); +WOLFSSL_API int wolfSSL_OPENSSL_init_crypto(word64 opts, const WOLFSSL_INIT_SETTINGS *settings); #endif /* class index for wolfSSL_CRYPTO_get_ex_new_index */ + +#ifndef OPENSSL_COEXIST + #define CRYPTO_EX_INDEX_SSL WOLF_CRYPTO_EX_INDEX_SSL #define CRYPTO_EX_INDEX_SSL_CTX WOLF_CRYPTO_EX_INDEX_SSL_CTX #define CRYPTO_EX_INDEX_SSL_SESSION WOLF_CRYPTO_EX_INDEX_SSL_SESSION @@ -153,6 +162,8 @@ WOLFSSL_API int wolfSSL_OPENSSL_init_crypto(word64 opts, const OPENSSL_INIT_SETT #endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY || HAVE_EX_DATA */ +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/des.h b/src/wolfssl/openssl/des.h index 0f385a6..6db0df7 100644 --- a/src/wolfssl/openssl/des.h +++ b/src/wolfssl/openssl/des.h @@ -49,8 +49,8 @@ typedef unsigned int WOLFSSL_DES_LONG; enum { - DES_ENCRYPT = 1, - DES_DECRYPT = 0 + WC_DES_ENCRYPT = 1, + WC_DES_DECRYPT = 0 }; @@ -87,6 +87,13 @@ WOLFSSL_API void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* desa, WOLFSSL_API int wolfSSL_DES_check_key_parity(WOLFSSL_DES_cblock *myDes); +#ifndef OPENSSL_COEXIST + +enum { + DES_ENCRYPT = WC_DES_ENCRYPT, + DES_DECRYPT = WC_DES_DECRYPT +}; + typedef WOLFSSL_DES_cblock DES_cblock; typedef WOLFSSL_const_DES_cblock const_DES_cblock; typedef WOLFSSL_DES_key_schedule DES_key_schedule; @@ -106,6 +113,8 @@ typedef WOLFSSL_DES_LONG DES_LONG; #define DES_cbc_cksum wolfSSL_DES_cbc_cksum #define DES_check_key_parity wolfSSL_DES_check_key_parity +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/dh.h b/src/wolfssl/openssl/dh.h index 7ea0f62..60fe59f 100644 --- a/src/wolfssl/openssl/dh.h +++ b/src/wolfssl/openssl/dh.h @@ -79,7 +79,7 @@ WOLFSSL_API int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p, WOLFSSL_API WOLFSSL_DH* wolfSSL_DH_get_2048_256(void); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) typedef WOLFSSL_DH DH; @@ -135,7 +135,7 @@ typedef WOLFSSL_DH DH; #define DH_GENERATOR_2 2 #define DH_GENERATOR_5 5 -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/openssl/dsa.h b/src/wolfssl/openssl/dsa.h index 6acb59e..1d24ceb 100644 --- a/src/wolfssl/openssl/dsa.h +++ b/src/wolfssl/openssl/dsa.h @@ -118,13 +118,15 @@ WOLFSSL_API WOLFSSL_DSA* wolfSSL_d2i_DSAparams( #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#define WOLFSSL_DSA_LOAD_PRIVATE 1 +#define WOLFSSL_DSA_LOAD_PUBLIC 2 + +#ifndef OPENSSL_COEXIST + typedef WOLFSSL_DSA DSA; #define OPENSSL_DSA_MAX_MODULUS_BITS 3072 -#define WOLFSSL_DSA_LOAD_PRIVATE 1 -#define WOLFSSL_DSA_LOAD_PUBLIC 2 - #define DSA_new wolfSSL_DSA_new #define DSA_free wolfSSL_DSA_free #define DSA_print_fp wolfSSL_DSA_print_fp @@ -151,6 +153,8 @@ typedef WOLFSSL_DSA DSA; #define DSA_SIG WOLFSSL_DSA_SIG +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/ec.h b/src/wolfssl/openssl/ec.h index bd81894..4067cff 100644 --- a/src/wolfssl/openssl/ec.h +++ b/src/wolfssl/openssl/ec.h @@ -36,59 +36,114 @@ extern "C" { #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + /* Map OpenSSL NID value */ enum { - POINT_CONVERSION_COMPRESSED = 2, - POINT_CONVERSION_UNCOMPRESSED = 4, + WC_POINT_CONVERSION_COMPRESSED = 2, + WC_POINT_CONVERSION_UNCOMPRESSED = 4, #ifdef HAVE_ECC /* Use OpenSSL NIDs. NIDs can be mapped to ecc_curve_id enum values by calling NIDToEccEnum() in ssl.c */ - NID_X9_62_prime192v1 = 409, - NID_X9_62_prime192v2 = 410, - NID_X9_62_prime192v3 = 411, - NID_X9_62_prime239v1 = 412, - NID_X9_62_prime239v2 = 413, - NID_X9_62_prime239v3 = 418, /* Previous value conflicted with AES128CBCb */ - NID_X9_62_prime256v1 = 415, - NID_secp112r1 = 704, - NID_secp112r2 = 705, - NID_secp128r1 = 706, - NID_secp128r2 = 707, - NID_secp160r1 = 709, - NID_secp160r2 = 710, - NID_secp224r1 = 713, - NID_secp384r1 = 715, - NID_secp521r1 = 716, - NID_secp160k1 = 708, - NID_secp192k1 = 711, - NID_secp224k1 = 712, - NID_secp256k1 = 714, - NID_brainpoolP160r1 = 921, - NID_brainpoolP192r1 = 923, - NID_brainpoolP224r1 = 925, - NID_brainpoolP256r1 = 927, - NID_brainpoolP320r1 = 929, - NID_brainpoolP384r1 = 931, - NID_brainpoolP512r1 = 933, + WC_NID_X9_62_prime192v1 = 409, + WC_NID_X9_62_prime192v2 = 410, + WC_NID_X9_62_prime192v3 = 411, + WC_NID_X9_62_prime239v1 = 412, + WC_NID_X9_62_prime239v2 = 413, + WC_NID_X9_62_prime239v3 = 418, /* Previous value conflicted with AES128CBCb */ + WC_NID_X9_62_prime256v1 = 415, + WC_NID_secp112r1 = 704, + WC_NID_secp112r2 = 705, + WC_NID_secp128r1 = 706, + WC_NID_secp128r2 = 707, + WC_NID_secp160r1 = 709, + WC_NID_secp160r2 = 710, + WC_NID_secp224r1 = 713, + WC_NID_secp384r1 = 715, + WC_NID_secp521r1 = 716, + WC_NID_secp160k1 = 708, + WC_NID_secp192k1 = 711, + WC_NID_secp224k1 = 712, + WC_NID_secp256k1 = 714, + WC_NID_brainpoolP160r1 = 921, + WC_NID_brainpoolP192r1 = 923, + WC_NID_brainpoolP224r1 = 925, + WC_NID_brainpoolP256r1 = 927, + WC_NID_brainpoolP320r1 = 929, + WC_NID_brainpoolP384r1 = 931, + WC_NID_brainpoolP512r1 = 933, #endif #ifdef HAVE_ED448 - NID_ED448 = ED448k, + WC_NID_ED448 = ED448k, #endif #ifdef HAVE_CURVE448 - NID_X448 = X448k, + WC_NID_X448 = X448k, #endif #ifdef HAVE_ED25519 - NID_ED25519 = ED25519k, + WC_NID_ED25519 = ED25519k, #endif #ifdef HAVE_CURVE25519 - NID_X25519 = X25519k, + WC_NID_X25519 = X25519k, #endif - OPENSSL_EC_EXPLICIT_CURVE = 0x000, - OPENSSL_EC_NAMED_CURVE = 0x001, + WOLFSSL_EC_EXPLICIT_CURVE = 0x000, + WOLFSSL_EC_NAMED_CURVE = 0x001 }; + +#ifndef OPENSSL_COEXIST + +#define POINT_CONVERSION_COMPRESSED WC_POINT_CONVERSION_COMPRESSED +#define POINT_CONVERSION_UNCOMPRESSED WC_POINT_CONVERSION_UNCOMPRESSED + +#ifdef HAVE_ECC +#define NID_X9_62_prime192v1 WC_NID_X9_62_prime192v1 +#define NID_X9_62_prime192v2 WC_NID_X9_62_prime192v2 +#define NID_X9_62_prime192v3 WC_NID_X9_62_prime192v3 +#define NID_X9_62_prime239v1 WC_NID_X9_62_prime239v1 +#define NID_X9_62_prime239v2 WC_NID_X9_62_prime239v2 +#define NID_X9_62_prime239v3 WC_NID_X9_62_prime239v3 +#define NID_X9_62_prime256v1 WC_NID_X9_62_prime256v1 +#define NID_secp112r1 WC_NID_secp112r1 +#define NID_secp112r2 WC_NID_secp112r2 +#define NID_secp128r1 WC_NID_secp128r1 +#define NID_secp128r2 WC_NID_secp128r2 +#define NID_secp160r1 WC_NID_secp160r1 +#define NID_secp160r2 WC_NID_secp160r2 +#define NID_secp224r1 WC_NID_secp224r1 +#define NID_secp384r1 WC_NID_secp384r1 +#define NID_secp521r1 WC_NID_secp521r1 +#define NID_secp160k1 WC_NID_secp160k1 +#define NID_secp192k1 WC_NID_secp192k1 +#define NID_secp224k1 WC_NID_secp224k1 +#define NID_secp256k1 WC_NID_secp256k1 +#define NID_brainpoolP160r1 WC_NID_brainpoolP160r1 +#define NID_brainpoolP192r1 WC_NID_brainpoolP192r1 +#define NID_brainpoolP224r1 WC_NID_brainpoolP224r1 +#define NID_brainpoolP256r1 WC_NID_brainpoolP256r1 +#define NID_brainpoolP320r1 WC_NID_brainpoolP320r1 +#define NID_brainpoolP384r1 WC_NID_brainpoolP384r1 +#define NID_brainpoolP512r1 WC_NID_brainpoolP512r1 +#endif + +#ifdef HAVE_ED448 +#define NID_ED448 WC_NID_ED448 +#endif +#ifdef HAVE_CURVE448 +#define NID_X448 WC_NID_X448 +#endif +#ifdef HAVE_ED25519 +#define NID_ED25519 WC_NID_ED25519 +#endif +#ifdef HAVE_CURVE25519 +#define NID_X25519 WC_NID_X25519 +#endif + +#define OPENSSL_EC_EXPLICIT_CURVE WOLFSSL_EC_EXPLICIT_CURVE +#define OPENSSL_EC_NAMED_CURVE WOLFSSL_EC_NAMED_CURVE + +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifndef WOLFSSL_EC_TYPE_DEFINED /* guard on redeclaration */ @@ -130,8 +185,8 @@ struct WOLFSSL_EC_KEY { word16 pkcs8HeaderSz; /* option bits */ - byte inSet:1; /* internal set from external ? */ - byte exSet:1; /* external set from internal ? */ + WC_BITFIELD inSet:1; /* internal set from external ? */ + WC_BITFIELD exSet:1; /* external set from internal ? */ wolfSSL_Ref ref; /* Reference count information. */ }; @@ -144,7 +199,10 @@ struct WOLFSSL_EC_BUILTIN_CURVE { #define WOLFSSL_EC_KEY_LOAD_PRIVATE 1 #define WOLFSSL_EC_KEY_LOAD_PUBLIC 2 -typedef int point_conversion_form_t; +typedef int wc_point_conversion_form_t; +#ifndef OPENSSL_COEXIST +#define point_conversion_form_t wc_point_conversion_form_t +#endif typedef struct WOLFSSL_EC_KEY_METHOD { /* Not implemented */ @@ -189,7 +247,7 @@ int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *in, unsigned char **out); WOLFSSL_API void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *eckey, int form); WOLFSSL_API -point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key); +wc_point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key); WOLFSSL_API WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP *group, const WOLFSSL_EC_POINT *p, @@ -347,7 +405,7 @@ WOLFSSL_API const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_get_method( WOLFSSL_API int wolfSSL_EC_KEY_set_method(WOLFSSL_EC_KEY *key, const WOLFSSL_EC_KEY_METHOD *meth); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) typedef WOLFSSL_EC_KEY EC_KEY; typedef WOLFSSL_EC_GROUP EC_GROUP; @@ -393,7 +451,11 @@ typedef WOLFSSL_EC_KEY_METHOD EC_KEY_METHOD; #define EC_GROUP_order_bits wolfSSL_EC_GROUP_order_bits #define EC_GROUP_method_of wolfSSL_EC_GROUP_method_of #ifndef NO_WOLFSSL_STUB -#define EC_GROUP_set_point_conversion_form(...) WC_DO_NOTHING +#ifdef WOLF_NO_VARIADIC_MACROS + #define EC_GROUP_set_point_conversion_form() WC_DO_NOTHING +#else + #define EC_GROUP_set_point_conversion_form(...) WC_DO_NOTHING +#endif #endif #define EC_METHOD_get_field_type wolfSSL_EC_METHOD_get_field_type @@ -451,7 +513,7 @@ typedef WOLFSSL_EC_KEY_METHOD EC_KEY_METHOD; #define EC_KEY_get_method wolfSSL_EC_KEY_get_method #define EC_KEY_set_method wolfSSL_EC_KEY_set_method -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/openssl/ecdsa.h b/src/wolfssl/openssl/ecdsa.h index 704f56d..f9ba1ec 100644 --- a/src/wolfssl/openssl/ecdsa.h +++ b/src/wolfssl/openssl/ecdsa.h @@ -37,7 +37,9 @@ typedef struct WOLFSSL_ECDSA_SIG WOLFSSL_ECDSA_SIG; #define WOLFSSL_ECDSA_TYPE_DEFINED #endif +#ifndef OPENSSL_COEXIST typedef WOLFSSL_ECDSA_SIG ECDSA_SIG; +#endif struct WOLFSSL_ECDSA_SIG { WOLFSSL_BIGNUM *r; @@ -64,6 +66,8 @@ WOLFSSL_API WOLFSSL_ECDSA_SIG *wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG **sig, WOLFSSL_API int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp); +#ifndef OPENSSL_COEXIST + #define ECDSA_SIG_free wolfSSL_ECDSA_SIG_free #define ECDSA_SIG_new wolfSSL_ECDSA_SIG_new #define ECDSA_SIG_get0 wolfSSL_ECDSA_SIG_get0 @@ -73,6 +77,8 @@ WOLFSSL_API int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, #define d2i_ECDSA_SIG wolfSSL_d2i_ECDSA_SIG #define i2d_ECDSA_SIG wolfSSL_i2d_ECDSA_SIG +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/err.h b/src/wolfssl/openssl/err.h index 2af6407..708498a 100644 --- a/src/wolfssl/openssl/err.h +++ b/src/wolfssl/openssl/err.h @@ -25,6 +25,26 @@ #include #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + +#define wolfSSL_RSAerr(f,r) wolfSSL_ERR_put_error(0,(f),(r),__FILE__,__LINE__) +#define wolfSSL_SSLerr(f,r) wolfSSL_ERR_put_error(0,(f),(r),__FILE__,__LINE__) +#define wolfSSL_ECerr(f,r) wolfSSL_ERR_put_error(0,(f),(r),__FILE__,__LINE__) + +#define WOLFSSL_ERR_TXT_MALLOCED 1 + +/* SSL function codes */ +#define WOLFSSL_RSA_F_RSA_PADDING_ADD_SSLV23 0 +#define WOLFSSL_RSA_F_RSA_OSSL_PRIVATE_ENCRYPT 1 +#define WOLFSSL_SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 2 +#define WOLFSSL_SSL_F_SSL_USE_PRIVATEKEY 3 +#define WOLFSSL_EC_F_EC_GFP_SIMPLE_POINT2OCT 4 + +/* reasons */ +#define WOLFSSL_ERR_R_SYS_LIB 1 +#define WOLFSSL_PKCS12_R_MAC_VERIFY_FAILURE 2 + +#ifndef OPENSSL_COEXIST + /* err.h for openssl */ #define ERR_load_ERR_strings wolfSSL_ERR_load_ERR_strings #define ERR_load_crypto_strings wolfSSL_ERR_load_crypto_strings @@ -40,24 +60,25 @@ #define RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE WC_KEY_SIZE_E #define EC_R_BUFFER_TOO_SMALL BUFFER_E -#define ERR_TXT_MALLOCED 1 +#define ERR_TXT_MALLOCED WOLFSSL_ERR_TXT_MALLOCED /* SSL function codes */ -#define RSA_F_RSA_PADDING_ADD_SSLV23 0 -#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT 1 -#define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 2 -#define SSL_F_SSL_USE_PRIVATEKEY 3 -#define EC_F_EC_GFP_SIMPLE_POINT2OCT 4 +#define RSA_F_RSA_PADDING_ADD_SSLV23 WOLFSSL_RSA_F_RSA_PADDING_ADD_SSLV23 +#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT WOLFSSL_RSA_F_RSA_OSSL_PRIVATE_ENCRYPT +#define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE WOLFSSL_SSL_F_SSL_CTX_USE_CERTIFICATE_FILE +#define SSL_F_SSL_USE_PRIVATEKEY WOLFSSL_SSL_F_SSL_USE_PRIVATEKEY +#define EC_F_EC_GFP_SIMPLE_POINT2OCT WOLFSSL_EC_F_EC_GFP_SIMPLE_POINT2OCT /* reasons */ -#define ERR_R_SYS_LIB 1 -#define PKCS12_R_MAC_VERIFY_FAILURE 2 +#define ERR_R_SYS_LIB WOLFSSL_ERR_R_SYS_LIB +#define PKCS12_R_MAC_VERIFY_FAILURE WOLFSSL_PKCS12_R_MAC_VERIFY_FAILURE -#define RSAerr(f,r) ERR_put_error(0,(f),(r),__FILE__,__LINE__) -#define SSLerr(f,r) ERR_put_error(0,(f),(r),__FILE__,__LINE__) -#define ECerr(f,r) ERR_put_error(0,(f),(r),__FILE__,__LINE__) +#define RSAerr(f,r) wolfSSL_RSAerr(f,r) +#define SSLerr(f,r) wolfSSL_SSLerr(f,r) +#define ECerr(f,r) wolfSSL_ECerr(f,r) + +#endif /* !OPENSSL_COEXIST */ #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #endif /* WOLFSSL_OPENSSL_ERR_ */ - diff --git a/src/wolfssl/openssl/evp.h b/src/wolfssl/openssl/evp.h index fbfea20..02b5c8b 100644 --- a/src/wolfssl/openssl/evp.h +++ b/src/wolfssl/openssl/evp.h @@ -270,205 +270,413 @@ typedef union { #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -#define NID_aes_128_cbc 419 -#define NID_aes_192_cbc 423 -#define NID_aes_256_cbc 427 -#define NID_aes_128_ccm 896 -#define NID_aes_192_ccm 899 -#define NID_aes_256_ccm 902 -#define NID_aes_128_gcm 895 -#define NID_aes_192_gcm 898 -#define NID_aes_256_gcm 901 -#define NID_aes_128_ctr 904 -#define NID_aes_192_ctr 905 -#define NID_aes_256_ctr 906 -#define NID_aes_128_ecb 418 -#define NID_aes_192_ecb 422 -#define NID_aes_256_ecb 426 -#define NID_des_cbc 31 -#define NID_des_ecb 29 -#define NID_des_ede3_cbc 44 -#define NID_des_ede3_ecb 33 -#define NID_aes_128_cfb1 650 -#define NID_aes_192_cfb1 651 -#define NID_aes_256_cfb1 652 -#define NID_aes_128_cfb8 653 -#define NID_aes_192_cfb8 654 -#define NID_aes_256_cfb8 655 -#define NID_aes_128_cfb128 421 -#define NID_aes_192_cfb128 425 -#define NID_aes_256_cfb128 429 -#define NID_aes_128_ofb 420 -#define NID_aes_192_ofb 424 -#define NID_aes_256_ofb 428 -#define NID_aes_128_xts 913 -#define NID_aes_256_xts 914 -#define NID_camellia_128_cbc 751 -#define NID_camellia_256_cbc 753 -#define NID_chacha20_poly1305 1018 -#define NID_chacha20 1019 -#define NID_sm4_ecb 1133 -#define NID_sm4_cbc 1134 -#define NID_sm4_ctr 1139 -#define NID_sm4_gcm 1248 -#define NID_sm4_ccm 1249 -#define NID_md5WithRSA 104 -#define NID_md2WithRSAEncryption 9 -#define NID_md5WithRSAEncryption 99 -#define NID_dsaWithSHA1 113 -#define NID_dsaWithSHA1_2 70 -#define NID_sha1WithRSA 115 -#define NID_sha1WithRSAEncryption 65 -#define NID_sha224WithRSAEncryption 671 -#define NID_sha256WithRSAEncryption 668 -#define NID_sha384WithRSAEncryption 669 -#define NID_sha512WithRSAEncryption 670 -#define NID_RSA_SHA3_224 1116 -#define NID_RSA_SHA3_256 1117 -#define NID_RSA_SHA3_384 1118 -#define NID_RSA_SHA3_512 1119 -#define NID_rsassaPss 912 -#define NID_ecdsa_with_SHA1 416 -#define NID_ecdsa_with_SHA224 793 -#define NID_ecdsa_with_SHA256 794 -#define NID_ecdsa_with_SHA384 795 -#define NID_ecdsa_with_SHA512 796 -#define NID_ecdsa_with_SHA3_224 1112 -#define NID_ecdsa_with_SHA3_256 1113 -#define NID_ecdsa_with_SHA3_384 1114 -#define NID_ecdsa_with_SHA3_512 1115 -#define NID_dsa_with_SHA224 802 -#define NID_dsa_with_SHA256 803 -#define NID_sha3_224 1096 -#define NID_sha3_256 1097 -#define NID_sha3_384 1098 -#define NID_sha3_512 1099 -#define NID_blake2b512 1056 -#define NID_blake2s256 1057 -#define NID_shake128 1100 -#define NID_shake256 1101 -#define NID_sha1 64 -#define NID_sha224 675 -#define NID_sm3 1143 -#define NID_md2 77 -#define NID_md4 257 -#define NID_md5 40 -#define NID_hmac 855 -#define NID_hmacWithSHA1 163 -#define NID_hmacWithSHA224 798 -#define NID_hmacWithSHA256 799 -#define NID_hmacWithSHA384 800 -#define NID_hmacWithSHA512 801 -#define NID_hkdf 1036 -#define NID_cmac 894 -#define NID_dhKeyAgreement 28 -#define NID_ffdhe2048 1126 -#define NID_ffdhe3072 1127 -#define NID_ffdhe4096 1128 -#define NID_rc4 5 -#define NID_bf_cbc 91 -#define NID_bf_ecb 92 -#define NID_bf_cfb64 93 -#define NID_bf_ofb64 94 -#define NID_cast5_cbc 108 -#define NID_cast5_ecb 109 -#define NID_cast5_cfb64 110 -#define NID_cast5_ofb64 111 +/* note, this WC_NID_undef definition duplicates the definition in + * wolfcrypt/asn.h, which is gated out when -DNO_ASN. + */ +#define WC_NID_undef 0 + +#define WC_NID_aes_128_cbc 419 +#define WC_NID_aes_192_cbc 423 +#define WC_NID_aes_256_cbc 427 +#define WC_NID_aes_128_ccm 896 +#define WC_NID_aes_192_ccm 899 +#define WC_NID_aes_256_ccm 902 +#define WC_NID_aes_128_gcm 895 +#define WC_NID_aes_192_gcm 898 +#define WC_NID_aes_256_gcm 901 +#define WC_NID_aes_128_ctr 904 +#define WC_NID_aes_192_ctr 905 +#define WC_NID_aes_256_ctr 906 +#define WC_NID_aes_128_ecb 418 +#define WC_NID_aes_192_ecb 422 +#define WC_NID_aes_256_ecb 426 +#define WC_NID_des_cbc 31 +#define WC_NID_des_ecb 29 +#define WC_NID_des_ede3_cbc 44 +#define WC_NID_des_ede3_ecb 33 +#define WC_NID_aes_128_cfb1 650 +#define WC_NID_aes_192_cfb1 651 +#define WC_NID_aes_256_cfb1 652 +#define WC_NID_aes_128_cfb8 653 +#define WC_NID_aes_192_cfb8 654 +#define WC_NID_aes_256_cfb8 655 +#define WC_NID_aes_128_cfb128 421 +#define WC_NID_aes_192_cfb128 425 +#define WC_NID_aes_256_cfb128 429 +#define WC_NID_aes_128_ofb 420 +#define WC_NID_aes_192_ofb 424 +#define WC_NID_aes_256_ofb 428 +#define WC_NID_aes_128_xts 913 +#define WC_NID_aes_256_xts 914 +#define WC_NID_camellia_128_cbc 751 +#define WC_NID_camellia_256_cbc 753 +#define WC_NID_chacha20_poly1305 1018 +#define WC_NID_chacha20 1019 +#define WC_NID_sm4_ecb 1133 +#define WC_NID_sm4_cbc 1134 +#define WC_NID_sm4_ctr 1139 +#define WC_NID_sm4_gcm 1248 +#define WC_NID_sm4_ccm 1249 +#define WC_NID_md5WithRSA 104 +#define WC_NID_md2WithRSAEncryption 9 +#define WC_NID_md5WithRSAEncryption 99 +#define WC_NID_dsaWithSHA1 113 +#define WC_NID_dsaWithSHA1_2 70 +#define WC_NID_sha1WithRSA 115 +#define WC_NID_sha1WithRSAEncryption 65 +#define WC_NID_sha224WithRSAEncryption 671 +#define WC_NID_sha256WithRSAEncryption 668 +#define WC_NID_sha384WithRSAEncryption 669 +#define WC_NID_sha512WithRSAEncryption 670 +#define WC_NID_RSA_SHA3_224 1116 +#define WC_NID_RSA_SHA3_256 1117 +#define WC_NID_RSA_SHA3_384 1118 +#define WC_NID_RSA_SHA3_512 1119 +#define WC_NID_rsassaPss 912 +#define WC_NID_ecdsa_with_SHA1 416 +#define WC_NID_ecdsa_with_SHA224 793 +#define WC_NID_ecdsa_with_SHA256 794 +#define WC_NID_ecdsa_with_SHA384 795 +#define WC_NID_ecdsa_with_SHA512 796 +#define WC_NID_ecdsa_with_SHA3_224 1112 +#define WC_NID_ecdsa_with_SHA3_256 1113 +#define WC_NID_ecdsa_with_SHA3_384 1114 +#define WC_NID_ecdsa_with_SHA3_512 1115 +#define WC_NID_dsa_with_SHA224 802 +#define WC_NID_dsa_with_SHA256 803 +#define WC_NID_sha3_224 1096 +#define WC_NID_sha3_256 1097 +#define WC_NID_sha3_384 1098 +#define WC_NID_sha3_512 1099 +#define WC_NID_blake2b512 1056 +#define WC_NID_blake2s256 1057 +#define WC_NID_shake128 1100 +#define WC_NID_shake256 1101 +#define WC_NID_sha1 64 +#define WC_NID_sha224 675 +#define WC_NID_sm3 1143 +#define WC_NID_md2 77 +#define WC_NID_md4 257 +#define WC_NID_md5 40 +#define WC_NID_hmac 855 +#define WC_NID_hmacWithSHA1 163 +#define WC_NID_hmacWithSHA224 798 +#define WC_NID_hmacWithSHA256 799 +#define WC_NID_hmacWithSHA384 800 +#define WC_NID_hmacWithSHA512 801 +#define WC_NID_hkdf 1036 +#define WC_NID_cmac 894 +#define WC_NID_dhKeyAgreement 28 +#define WC_NID_ffdhe2048 1126 +#define WC_NID_ffdhe3072 1127 +#define WC_NID_ffdhe4096 1128 +#define WC_NID_rc4 5 +#define WC_NID_bf_cbc 91 +#define WC_NID_bf_ecb 92 +#define WC_NID_bf_cfb64 93 +#define WC_NID_bf_ofb64 94 +#define WC_NID_cast5_cbc 108 +#define WC_NID_cast5_ecb 109 +#define WC_NID_cast5_cfb64 110 +#define WC_NID_cast5_ofb64 111 /* key exchange */ -#define NID_kx_rsa 1037 -#define NID_kx_ecdhe 1038 -#define NID_kx_dhe 1039 -#define NID_kx_ecdhe_psk 1040 -#define NID_kx_dhe_psk 1041 -#define NID_kx_rsa_psk 1042 -#define NID_kx_psk 1043 -#define NID_kx_srp 1044 -#define NID_kx_gost 1045 -#define NID_kx_any 1063 +#define WC_NID_kx_rsa 1037 +#define WC_NID_kx_ecdhe 1038 +#define WC_NID_kx_dhe 1039 +#define WC_NID_kx_ecdhe_psk 1040 +#define WC_NID_kx_dhe_psk 1041 +#define WC_NID_kx_rsa_psk 1042 +#define WC_NID_kx_psk 1043 +#define WC_NID_kx_srp 1044 +#define WC_NID_kx_gost 1045 +#define WC_NID_kx_any 1063 /* server authentication */ -#define NID_auth_rsa 1046 -#define NID_auth_ecdsa 1047 -#define NID_auth_psk 1048 -#define NID_auth_dss 1049 -#define NID_auth_srp 1052 -#define NID_auth_null 1054 -#define NID_auth_any 1055 +#define WC_NID_auth_rsa 1046 +#define WC_NID_auth_ecdsa 1047 +#define WC_NID_auth_psk 1048 +#define WC_NID_auth_dss 1049 +#define WC_NID_auth_srp 1052 +#define WC_NID_auth_null 1054 +#define WC_NID_auth_any 1055 /* Curve */ -#define NID_aria_128_gcm 1123 -#define NID_aria_192_gcm 1124 -#define NID_aria_256_gcm 1125 -#define NID_sm2 1172 - -#define NID_X9_62_id_ecPublicKey EVP_PKEY_EC -#define NID_rsaEncryption EVP_PKEY_RSA -#define NID_rsa EVP_PKEY_RSA -#define NID_dsa EVP_PKEY_DSA +#define WC_NID_aria_128_gcm 1123 +#define WC_NID_aria_192_gcm 1124 +#define WC_NID_aria_256_gcm 1125 +#define WC_NID_sm2 1172 -#define EVP_PKEY_OP_SIGN (1 << 3) -#define EVP_PKEY_OP_VERIFY (1 << 5) -#define EVP_PKEY_OP_ENCRYPT (1 << 6) -#define EVP_PKEY_OP_DECRYPT (1 << 7) -#define EVP_PKEY_OP_DERIVE (1 << 8) - -#define EVP_PKEY_PRINT_INDENT_MAX 128 +#define WC_NID_X9_62_id_ecPublicKey WC_EVP_PKEY_EC +#define WC_NID_rsaEncryption WC_EVP_PKEY_RSA +#define WC_NID_rsa WC_EVP_PKEY_RSA +#define WC_NID_dsa WC_EVP_PKEY_DSA enum { - AES_128_CBC_TYPE = 1, - AES_192_CBC_TYPE = 2, - AES_256_CBC_TYPE = 3, - AES_128_CTR_TYPE = 4, - AES_192_CTR_TYPE = 5, - AES_256_CTR_TYPE = 6, - AES_128_ECB_TYPE = 7, - AES_192_ECB_TYPE = 8, - AES_256_ECB_TYPE = 9, - DES_CBC_TYPE = 10, - DES_ECB_TYPE = 11, - DES_EDE3_CBC_TYPE = 12, - DES_EDE3_ECB_TYPE = 13, - ARC4_TYPE = 14, - NULL_CIPHER_TYPE = 15, - EVP_PKEY_RSA = 16, - EVP_PKEY_DSA = 17, - EVP_PKEY_EC = 18, - AES_128_GCM_TYPE = 21, - AES_192_GCM_TYPE = 22, - AES_256_GCM_TYPE = 23, - EVP_PKEY_DH = NID_dhKeyAgreement, - EVP_PKEY_HMAC = NID_hmac, - EVP_PKEY_CMAC = NID_cmac, - EVP_PKEY_HKDF = NID_hkdf, - EVP_PKEY_FALCON = 300, /* Randomly picked value. */ - EVP_PKEY_DILITHIUM = 301, /* Randomly picked value. */ - AES_128_CFB1_TYPE = 24, - AES_192_CFB1_TYPE = 25, - AES_256_CFB1_TYPE = 26, - AES_128_CFB8_TYPE = 27, - AES_192_CFB8_TYPE = 28, - AES_256_CFB8_TYPE = 29, - AES_128_CFB128_TYPE = 30, - AES_192_CFB128_TYPE = 31, - AES_256_CFB128_TYPE = 32, - AES_128_OFB_TYPE = 33, - AES_192_OFB_TYPE = 34, - AES_256_OFB_TYPE = 35, - AES_128_XTS_TYPE = 36, - AES_256_XTS_TYPE = 37, - CHACHA20_POLY1305_TYPE = 38, - CHACHA20_TYPE = 39, - AES_128_CCM_TYPE = 40, - AES_192_CCM_TYPE = 41, - AES_256_CCM_TYPE = 42, - SM4_ECB_TYPE = 43, - SM4_CBC_TYPE = 44, - SM4_CTR_TYPE = 45, - SM4_GCM_TYPE = 46, - SM4_CCM_TYPE = 47, - ARIA_128_GCM_TYPE = 48, - ARIA_192_GCM_TYPE = 49, - ARIA_256_GCM_TYPE = 50 + WC_EVP_PKEY_NONE = WC_NID_undef, + WC_AES_128_CBC_TYPE = 1, + WC_AES_192_CBC_TYPE = 2, + WC_AES_256_CBC_TYPE = 3, + WC_AES_128_CTR_TYPE = 4, + WC_AES_192_CTR_TYPE = 5, + WC_AES_256_CTR_TYPE = 6, + WC_AES_128_ECB_TYPE = 7, + WC_AES_192_ECB_TYPE = 8, + WC_AES_256_ECB_TYPE = 9, + WC_DES_CBC_TYPE = 10, + WC_DES_ECB_TYPE = 11, + WC_DES_EDE3_CBC_TYPE = 12, + WC_DES_EDE3_ECB_TYPE = 13, + WC_ARC4_TYPE = 14, + WC_NULL_CIPHER_TYPE = 15, + WC_EVP_PKEY_RSA = 16, + WC_EVP_PKEY_DSA = 17, + WC_EVP_PKEY_EC = 18, + WC_AES_128_GCM_TYPE = 21, + WC_AES_192_GCM_TYPE = 22, + WC_AES_256_GCM_TYPE = 23, + WC_EVP_PKEY_DH = WC_NID_dhKeyAgreement, + WC_EVP_PKEY_HMAC = WC_NID_hmac, + WC_EVP_PKEY_CMAC = WC_NID_cmac, + WC_EVP_PKEY_HKDF = WC_NID_hkdf, + WC_EVP_PKEY_FALCON = 300, /* Randomly picked value. */ + WC_EVP_PKEY_DILITHIUM = 301, /* Randomly picked value. */ + WC_AES_128_CFB1_TYPE = 24, + WC_AES_192_CFB1_TYPE = 25, + WC_AES_256_CFB1_TYPE = 26, + WC_AES_128_CFB8_TYPE = 27, + WC_AES_192_CFB8_TYPE = 28, + WC_AES_256_CFB8_TYPE = 29, + WC_AES_128_CFB128_TYPE = 30, + WC_AES_192_CFB128_TYPE = 31, + WC_AES_256_CFB128_TYPE = 32, + WC_AES_128_OFB_TYPE = 33, + WC_AES_192_OFB_TYPE = 34, + WC_AES_256_OFB_TYPE = 35, + WC_AES_128_XTS_TYPE = 36, + WC_AES_256_XTS_TYPE = 37, + WC_CHACHA20_POLY1305_TYPE = 38, + WC_CHACHA20_TYPE = 39, + WC_AES_128_CCM_TYPE = 40, + WC_AES_192_CCM_TYPE = 41, + WC_AES_256_CCM_TYPE = 42, + WC_SM4_ECB_TYPE = 43, + WC_SM4_CBC_TYPE = 44, + WC_SM4_CTR_TYPE = 45, + WC_SM4_GCM_TYPE = 46, + WC_SM4_CCM_TYPE = 47, + WC_ARIA_128_GCM_TYPE = 48, + WC_ARIA_192_GCM_TYPE = 49, + WC_ARIA_256_GCM_TYPE = 50 }; +#define WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX 128 + +#define WC_EVP_PKEY_OP_SIGN (1 << 3) +#define WC_EVP_PKEY_OP_VERIFY (1 << 5) +#define WC_EVP_PKEY_OP_ENCRYPT (1 << 6) +#define WC_EVP_PKEY_OP_DECRYPT (1 << 7) +#define WC_EVP_PKEY_OP_DERIVE (1 << 8) + +#ifndef OPENSSL_COEXIST + +#define EVP_PKEY_NONE WC_EVP_PKEY_NONE +#define AES_128_CBC_TYPE WC_AES_128_CBC_TYPE +#define AES_192_CBC_TYPE WC_AES_192_CBC_TYPE +#define AES_256_CBC_TYPE WC_AES_256_CBC_TYPE +#define AES_128_CTR_TYPE WC_AES_128_CTR_TYPE +#define AES_192_CTR_TYPE WC_AES_192_CTR_TYPE +#define AES_256_CTR_TYPE WC_AES_256_CTR_TYPE +#define AES_128_ECB_TYPE WC_AES_128_ECB_TYPE +#define AES_192_ECB_TYPE WC_AES_192_ECB_TYPE +#define AES_256_ECB_TYPE WC_AES_256_ECB_TYPE +#define DES_CBC_TYPE WC_DES_CBC_TYPE +#define DES_ECB_TYPE WC_DES_ECB_TYPE +#define DES_EDE3_CBC_TYPE WC_DES_EDE3_CBC_TYPE +#define DES_EDE3_ECB_TYPE WC_DES_EDE3_ECB_TYPE +#define ARC4_TYPE WC_ARC4_TYPE +#define NULL_CIPHER_TYPE WC_NULL_CIPHER_TYPE +#define EVP_PKEY_RSA WC_EVP_PKEY_RSA +#define EVP_PKEY_DSA WC_EVP_PKEY_DSA +#define EVP_PKEY_EC WC_EVP_PKEY_EC +#define AES_128_GCM_TYPE WC_AES_128_GCM_TYPE +#define AES_192_GCM_TYPE WC_AES_192_GCM_TYPE +#define AES_256_GCM_TYPE WC_AES_256_GCM_TYPE +#define EVP_PKEY_DH WC_EVP_PKEY_DH +#define EVP_PKEY_HMAC WC_EVP_PKEY_HMAC +#define EVP_PKEY_CMAC WC_EVP_PKEY_CMAC +#define EVP_PKEY_HKDF WC_EVP_PKEY_HKDF +#define EVP_PKEY_FALCON WC_EVP_PKEY_FALCON +#define EVP_PKEY_DILITHIUM WC_EVP_PKEY_DILITHIUM +#define AES_128_CFB1_TYPE WC_AES_128_CFB1_TYPE +#define AES_192_CFB1_TYPE WC_AES_192_CFB1_TYPE +#define AES_256_CFB1_TYPE WC_AES_256_CFB1_TYPE +#define AES_128_CFB8_TYPE WC_AES_128_CFB8_TYPE +#define AES_192_CFB8_TYPE WC_AES_192_CFB8_TYPE +#define AES_256_CFB8_TYPE WC_AES_256_CFB8_TYPE +#define AES_128_CFB128_TYPE WC_AES_128_CFB128_TYPE +#define AES_192_CFB128_TYPE WC_AES_192_CFB128_TYPE +#define AES_256_CFB128_TYPE WC_AES_256_CFB128_TYPE +#define AES_128_OFB_TYPE WC_AES_128_OFB_TYPE +#define AES_192_OFB_TYPE WC_AES_192_OFB_TYPE +#define AES_256_OFB_TYPE WC_AES_256_OFB_TYPE +#define AES_128_XTS_TYPE WC_AES_128_XTS_TYPE +#define AES_256_XTS_TYPE WC_AES_256_XTS_TYPE +#define CHACHA20_POLY1305_TYPE WC_CHACHA20_POLY1305_TYPE +#define CHACHA20_TYPE WC_CHACHA20_TYPE +#define AES_128_CCM_TYPE WC_AES_128_CCM_TYPE +#define AES_192_CCM_TYPE WC_AES_192_CCM_TYPE +#define AES_256_CCM_TYPE WC_AES_256_CCM_TYPE +#define SM4_ECB_TYPE WC_SM4_ECB_TYPE +#define SM4_CBC_TYPE WC_SM4_CBC_TYPE +#define SM4_CTR_TYPE WC_SM4_CTR_TYPE +#define SM4_GCM_TYPE WC_SM4_GCM_TYPE +#define SM4_CCM_TYPE WC_SM4_CCM_TYPE +#define ARIA_128_GCM_TYPE WC_ARIA_128_GCM_TYPE +#define ARIA_192_GCM_TYPE WC_ARIA_192_GCM_TYPE +#define ARIA_256_GCM_TYPE WC_ARIA_256_GCM_TYPE + +#define NID_aes_128_cbc WC_NID_aes_128_cbc +#define NID_aes_192_cbc WC_NID_aes_192_cbc +#define NID_aes_256_cbc WC_NID_aes_256_cbc +#define NID_aes_128_ccm WC_NID_aes_128_ccm +#define NID_aes_192_ccm WC_NID_aes_192_ccm +#define NID_aes_256_ccm WC_NID_aes_256_ccm +#define NID_aes_128_gcm WC_NID_aes_128_gcm +#define NID_aes_192_gcm WC_NID_aes_192_gcm +#define NID_aes_256_gcm WC_NID_aes_256_gcm +#define NID_aes_128_ctr WC_NID_aes_128_ctr +#define NID_aes_192_ctr WC_NID_aes_192_ctr +#define NID_aes_256_ctr WC_NID_aes_256_ctr +#define NID_aes_128_ecb WC_NID_aes_128_ecb +#define NID_aes_192_ecb WC_NID_aes_192_ecb +#define NID_aes_256_ecb WC_NID_aes_256_ecb +#define NID_des_cbc WC_NID_des_cbc +#define NID_des_ecb WC_NID_des_ecb +#define NID_des_ede3_cbc WC_NID_des_ede3_cbc +#define NID_des_ede3_ecb WC_NID_des_ede3_ecb +#define NID_aes_128_cfb1 WC_NID_aes_128_cfb1 +#define NID_aes_192_cfb1 WC_NID_aes_192_cfb1 +#define NID_aes_256_cfb1 WC_NID_aes_256_cfb1 +#define NID_aes_128_cfb8 WC_NID_aes_128_cfb8 +#define NID_aes_192_cfb8 WC_NID_aes_192_cfb8 +#define NID_aes_256_cfb8 WC_NID_aes_256_cfb8 +#define NID_aes_128_cfb128 WC_NID_aes_128_cfb128 +#define NID_aes_192_cfb128 WC_NID_aes_192_cfb128 +#define NID_aes_256_cfb128 WC_NID_aes_256_cfb128 +#define NID_aes_128_ofb WC_NID_aes_128_ofb +#define NID_aes_192_ofb WC_NID_aes_192_ofb +#define NID_aes_256_ofb WC_NID_aes_256_ofb +#define NID_aes_128_xts WC_NID_aes_128_xts +#define NID_aes_256_xts WC_NID_aes_256_xts +#define NID_camellia_128_cbc WC_NID_camellia_128_cbc +#define NID_camellia_256_cbc WC_NID_camellia_256_cbc +#define NID_chacha20_poly1305 WC_NID_chacha20_poly1305 +#define NID_chacha20 WC_NID_chacha20 +#define NID_sm4_ecb WC_NID_sm4_ecb +#define NID_sm4_cbc WC_NID_sm4_cbc +#define NID_sm4_ctr WC_NID_sm4_ctr +#define NID_sm4_gcm WC_NID_sm4_gcm +#define NID_sm4_ccm WC_NID_sm4_ccm +#define NID_md5WithRSA WC_NID_md5WithRSA +#define NID_md2WithRSAEncryption WC_NID_md2WithRSAEncryption +#define NID_md5WithRSAEncryption WC_NID_md5WithRSAEncryption +#define NID_dsaWithSHA1 WC_NID_dsaWithSHA1 +#define NID_dsaWithSHA1_2 WC_NID_dsaWithSHA1_2 +#define NID_sha1WithRSA WC_NID_sha1WithRSA +#define NID_sha1WithRSAEncryption WC_NID_sha1WithRSAEncryption +#define NID_sha224WithRSAEncryption WC_NID_sha224WithRSAEncryption +#define NID_sha256WithRSAEncryption WC_NID_sha256WithRSAEncryption +#define NID_sha384WithRSAEncryption WC_NID_sha384WithRSAEncryption +#define NID_sha512WithRSAEncryption WC_NID_sha512WithRSAEncryption +#define NID_RSA_SHA3_224 WC_NID_RSA_SHA3_224 +#define NID_RSA_SHA3_256 WC_NID_RSA_SHA3_256 +#define NID_RSA_SHA3_384 WC_NID_RSA_SHA3_384 +#define NID_RSA_SHA3_512 WC_NID_RSA_SHA3_512 +#define NID_rsassaPss WC_NID_rsassaPss +#define NID_ecdsa_with_SHA1 WC_NID_ecdsa_with_SHA1 +#define NID_ecdsa_with_SHA224 WC_NID_ecdsa_with_SHA224 +#define NID_ecdsa_with_SHA256 WC_NID_ecdsa_with_SHA256 +#define NID_ecdsa_with_SHA384 WC_NID_ecdsa_with_SHA384 +#define NID_ecdsa_with_SHA512 WC_NID_ecdsa_with_SHA512 +#define NID_ecdsa_with_SHA3_224 WC_NID_ecdsa_with_SHA3_224 +#define NID_ecdsa_with_SHA3_256 WC_NID_ecdsa_with_SHA3_256 +#define NID_ecdsa_with_SHA3_384 WC_NID_ecdsa_with_SHA3_384 +#define NID_ecdsa_with_SHA3_512 WC_NID_ecdsa_with_SHA3_512 +#define NID_dsa_with_SHA224 WC_NID_dsa_with_SHA224 +#define NID_dsa_with_SHA256 WC_NID_dsa_with_SHA256 +#define NID_sha3_224 WC_NID_sha3_224 +#define NID_sha3_256 WC_NID_sha3_256 +#define NID_sha3_384 WC_NID_sha3_384 +#define NID_sha3_512 WC_NID_sha3_512 +#define NID_blake2b512 WC_NID_blake2b512 +#define NID_blake2s256 WC_NID_blake2s256 +#define NID_shake128 WC_NID_shake128 +#define NID_shake256 WC_NID_shake256 +#define NID_sha1 WC_NID_sha1 +#define NID_sha224 WC_NID_sha224 +#define NID_sm3 WC_NID_sm3 +#define NID_md2 WC_NID_md2 +#define NID_md4 WC_NID_md4 +#define NID_md5 WC_NID_md5 +#define NID_hmac WC_NID_hmac +#define NID_hmacWithSHA1 WC_NID_hmacWithSHA1 +#define NID_hmacWithSHA224 WC_NID_hmacWithSHA224 +#define NID_hmacWithSHA256 WC_NID_hmacWithSHA256 +#define NID_hmacWithSHA384 WC_NID_hmacWithSHA384 +#define NID_hmacWithSHA512 WC_NID_hmacWithSHA512 +#define NID_hkdf WC_NID_hkdf +#define NID_cmac WC_NID_cmac +#define NID_dhKeyAgreement WC_NID_dhKeyAgreement +#define NID_ffdhe2048 WC_NID_ffdhe2048 +#define NID_ffdhe3072 WC_NID_ffdhe3072 +#define NID_ffdhe4096 WC_NID_ffdhe4096 +#define NID_rc4 WC_NID_rc4 +#define NID_bf_cbc WC_NID_bf_cbc +#define NID_bf_ecb WC_NID_bf_ecb +#define NID_bf_cfb64 WC_NID_bf_cfb64 +#define NID_bf_ofb64 WC_NID_bf_ofb64 +#define NID_cast5_cbc WC_NID_cast5_cbc +#define NID_cast5_ecb WC_NID_cast5_ecb +#define NID_cast5_cfb64 WC_NID_cast5_cfb64 +#define NID_cast5_ofb64 WC_NID_cast5_ofb64 +/* key exchange */ +#define NID_kx_rsa WC_NID_kx_rsa +#define NID_kx_ecdhe WC_NID_kx_ecdhe +#define NID_kx_dhe WC_NID_kx_dhe +#define NID_kx_ecdhe_psk WC_NID_kx_ecdhe_psk +#define NID_kx_dhe_psk WC_NID_kx_dhe_psk +#define NID_kx_rsa_psk WC_NID_kx_rsa_psk +#define NID_kx_psk WC_NID_kx_psk +#define NID_kx_srp WC_NID_kx_srp +#define NID_kx_gost WC_NID_kx_gost +#define NID_kx_any WC_NID_kx_any +/* server authentication */ +#define NID_auth_rsa WC_NID_auth_rsa +#define NID_auth_ecdsa WC_NID_auth_ecdsa +#define NID_auth_psk WC_NID_auth_psk +#define NID_auth_dss WC_NID_auth_dss +#define NID_auth_srp WC_NID_auth_srp +#define NID_auth_null WC_NID_auth_null +#define NID_auth_any WC_NID_auth_any +/* Curve */ +#define NID_aria_128_gcm WC_NID_aria_128_gcm +#define NID_aria_192_gcm WC_NID_aria_192_gcm +#define NID_aria_256_gcm WC_NID_aria_256_gcm +#define NID_sm2 WC_NID_sm2 + +#define NID_X9_62_id_ecPublicKey WC_NID_X9_62_id_ecPublicKey +#define NID_rsaEncryption WC_NID_rsaEncryption +#define NID_rsa WC_NID_rsa +#define NID_dsa WC_NID_dsa + +#define EVP_PKEY_OP_SIGN WC_EVP_PKEY_OP_SIGN +#define EVP_PKEY_OP_VERIFY WC_EVP_PKEY_OP_VERIFY +#define EVP_PKEY_OP_ENCRYPT WC_EVP_PKEY_OP_ENCRYPT +#define EVP_PKEY_OP_DECRYPT WC_EVP_PKEY_OP_DECRYPT +#define EVP_PKEY_OP_DERIVE WC_EVP_PKEY_OP_DERIVE + +#define EVP_PKEY_PRINT_INDENT_MAX WOLFSSL_EVP_PKEY_PRINT_INDENT_MAX + +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ @@ -481,7 +689,7 @@ struct WOLFSSL_EVP_CIPHER_CTX { unsigned char cipherType; #if !defined(NO_AES) /* working iv pointer into cipher */ - ALIGN16 unsigned char iv[AES_BLOCK_SIZE]; + ALIGN16 unsigned char iv[WC_AES_BLOCK_SIZE]; #elif defined(WOLFSSL_SM4) ALIGN16 unsigned char iv[SM4_BLOCK_SIZE]; #elif defined(HAVE_CHACHA) && defined(HAVE_POLY1305) @@ -514,7 +722,7 @@ struct WOLFSSL_EVP_CIPHER_CTX { defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) || \ (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA) - ALIGN16 unsigned char authTag[AES_BLOCK_SIZE]; + ALIGN16 unsigned char authTag[WC_AES_BLOCK_SIZE]; #elif defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) ALIGN16 unsigned char authTag[SM4_BLOCK_SIZE]; #else @@ -524,8 +732,8 @@ struct WOLFSSL_EVP_CIPHER_CTX { #endif #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || \ defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) - byte authIvGenEnable:1; - byte authIncIv:1; + WC_BITFIELD authIvGenEnable:1; + WC_BITFIELD authIncIv:1; #endif #endif }; @@ -918,6 +1126,29 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, const WOLFSSL_EVP_MD* type, WOLFSSL_ENGINE *impl); +#define WOLFSSL_EVP_CTRL_INIT 0x0 +#define WOLFSSL_EVP_CTRL_SET_KEY_LENGTH 0x1 +#define WOLFSSL_EVP_CTRL_SET_RC2_KEY_BITS 0x3 /* needed for qt compilation */ + +#define WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN 0x9 +#define WOLFSSL_EVP_CTRL_AEAD_GET_TAG 0x10 +#define WOLFSSL_EVP_CTRL_AEAD_SET_TAG 0x11 +#define WOLFSSL_EVP_CTRL_AEAD_SET_IV_FIXED 0x12 +#define WOLFSSL_EVP_CTRL_GCM_IV_GEN 0x13 +#define WOLFSSL_EVP_CTRL_GCM_SET_IVLEN WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN +#define WOLFSSL_EVP_CTRL_GCM_GET_TAG WOLFSSL_EVP_CTRL_AEAD_GET_TAG +#define WOLFSSL_EVP_CTRL_GCM_SET_TAG WOLFSSL_EVP_CTRL_AEAD_SET_TAG +#define WOLFSSL_EVP_CTRL_GCM_SET_IV_FIXED WOLFSSL_EVP_CTRL_AEAD_SET_IV_FIXED +#define WOLFSSL_EVP_CTRL_CCM_SET_IVLEN WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN +#define WOLFSSL_EVP_CTRL_CCM_GET_TAG WOLFSSL_EVP_CTRL_AEAD_GET_TAG +#define WOLFSSL_EVP_CTRL_CCM_SET_TAG WOLFSSL_EVP_CTRL_AEAD_SET_TAG +#define WOLFSSL_EVP_CTRL_CCM_SET_L 0x14 +#define WOLFSSL_EVP_CTRL_CCM_SET_MSGLEN 0x15 + +#define WOLFSSL_NO_PADDING_BLOCK_SIZE 1 + +#ifndef OPENSSL_COEXIST + #define EVP_CIPH_STREAM_CIPHER WOLFSSL_EVP_CIPH_STREAM_CIPHER #define EVP_CIPH_VARIABLE_LENGTH WOLFSSL_EVP_CIPH_VARIABLE_LENGTH #define EVP_CIPH_ECB_MODE WOLFSSL_EVP_CIPH_ECB_MODE @@ -1022,7 +1253,7 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_MD_block_size wolfSSL_EVP_MD_block_size #define EVP_MD_type wolfSSL_EVP_MD_type #ifndef NO_WOLFSSL_STUB -#define EVP_MD_CTX_set_flags(...) WC_DO_NOTHING +#define EVP_MD_CTX_set_flags(ctx, flags) WC_DO_NOTHING #endif #define EVP_Digest wolfSSL_EVP_Digest @@ -1179,7 +1410,7 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define OPENSSL_add_all_algorithms_noconf OpenSSL_add_all_algorithms_noconf #define OPENSSL_add_all_algorithms_conf OpenSSL_add_all_algorithms_conf -#define NO_PADDING_BLOCK_SIZE 1 +#define NO_PADDING_BLOCK_SIZE WOLFSSL_NO_PADDING_BLOCK_SIZE #define PKCS5_PBKDF2_HMAC_SHA1 wolfSSL_PKCS5_PBKDF2_HMAC_SHA1 #define PKCS5_PBKDF2_HMAC wolfSSL_PKCS5_PBKDF2_HMAC @@ -1190,20 +1421,20 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_CTRL_SET_KEY_LENGTH 0x1 #define EVP_CTRL_SET_RC2_KEY_BITS 0x3 /* needed for qt compilation */ -#define EVP_CTRL_AEAD_SET_IVLEN 0x9 -#define EVP_CTRL_AEAD_GET_TAG 0x10 -#define EVP_CTRL_AEAD_SET_TAG 0x11 -#define EVP_CTRL_AEAD_SET_IV_FIXED 0x12 -#define EVP_CTRL_GCM_IV_GEN 0x13 -#define EVP_CTRL_GCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -#define EVP_CTRL_GCM_GET_TAG EVP_CTRL_AEAD_GET_TAG -#define EVP_CTRL_GCM_SET_TAG EVP_CTRL_AEAD_SET_TAG -#define EVP_CTRL_GCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED -#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_AEAD_GET_TAG -#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_AEAD_SET_TAG -#define EVP_CTRL_CCM_SET_L 0x14 -#define EVP_CTRL_CCM_SET_MSGLEN 0x15 +#define EVP_CTRL_AEAD_SET_IVLEN WOLFSSL_EVP_CTRL_AEAD_SET_IVLEN +#define EVP_CTRL_AEAD_GET_TAG WOLFSSL_EVP_CTRL_AEAD_GET_TAG +#define EVP_CTRL_AEAD_SET_TAG WOLFSSL_EVP_CTRL_AEAD_SET_TAG +#define EVP_CTRL_AEAD_SET_IV_FIXED WOLFSSL_EVP_CTRL_AEAD_SET_IV_FIXED +#define EVP_CTRL_GCM_IV_GEN WOLFSSL_EVP_CTRL_GCM_IV_GEN +#define EVP_CTRL_GCM_SET_IVLEN WOLFSSL_EVP_CTRL_GCM_SET_IVLEN +#define EVP_CTRL_GCM_GET_TAG WOLFSSL_EVP_CTRL_GCM_GET_TAG +#define EVP_CTRL_GCM_SET_TAG WOLFSSL_EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_GCM_SET_IV_FIXED WOLFSSL_EVP_CTRL_GCM_SET_IV_FIXED +#define EVP_CTRL_CCM_SET_IVLEN WOLFSSL_EVP_CTRL_CCM_SET_IVLEN +#define EVP_CTRL_CCM_GET_TAG WOLFSSL_EVP_CTRL_CCM_GET_TAG +#define EVP_CTRL_CCM_SET_TAG WOLFSSL_EVP_CTRL_CCM_SET_TAG +#define EVP_CTRL_CCM_SET_L WOLFSSL_EVP_CTRL_CCM_SET_L +#define EVP_CTRL_CCM_SET_MSGLEN WOLFSSL_EVP_CTRL_CCM_SET_MSGLEN #define EVP_PKEY_print_public wolfSSL_EVP_PKEY_print_public #define EVP_PKEY_print_private(arg1, arg2, arg3, arg4) WC_DO_NOTHING @@ -1230,13 +1461,11 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #endif -#define EVP_R_BAD_DECRYPT (-MIN_CODE_E + 100 + 1) -#define EVP_R_BN_DECODE_ERROR (-MIN_CODE_E + 100 + 2) -#define EVP_R_DECODE_ERROR (-MIN_CODE_E + 100 + 3) -#define EVP_R_PRIVATE_KEY_DECODE_ERROR (-MIN_CODE_E + 100 + 4) +#define EVP_R_BAD_DECRYPT (-WOLFSSL_EVP_R_BAD_DECRYPT_E) +#define EVP_R_BN_DECODE_ERROR (-WOLFSSL_EVP_R_BN_DECODE_ERROR) +#define EVP_R_DECODE_ERROR (-WOLFSSL_EVP_R_DECODE_ERROR) +#define EVP_R_PRIVATE_KEY_DECODE_ERROR (-WOLFSSL_EVP_R_PRIVATE_KEY_DECODE_ERROR) -#define EVP_PKEY_NONE NID_undef -#define EVP_PKEY_DH 28 #define EVP_CIPHER_mode WOLFSSL_EVP_CIPHER_mode /* WOLFSSL_EVP_CIPHER is just the string name of the cipher */ #define EVP_CIPHER_name(x) x @@ -1278,6 +1507,8 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, WOLFSSL_API void printPKEY(WOLFSSL_EVP_PKEY *k); +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/hmac.h b/src/wolfssl/openssl/hmac.h index 71a473b..1a2c304 100644 --- a/src/wolfssl/openssl/hmac.h +++ b/src/wolfssl/openssl/hmac.h @@ -67,6 +67,8 @@ WOLFSSL_API void wolfSSL_HMAC_CTX_free(WOLFSSL_HMAC_CTX* ctx); WOLFSSL_API size_t wolfSSL_HMAC_size(const WOLFSSL_HMAC_CTX *ctx); WOLFSSL_API const WOLFSSL_EVP_MD *wolfSSL_HMAC_CTX_get_md(const WOLFSSL_HMAC_CTX *ctx); +#ifndef OPENSSL_COEXIST + typedef struct WOLFSSL_HMAC_CTX HMAC_CTX; #define HMAC wolfSSL_HMAC @@ -85,6 +87,7 @@ typedef struct WOLFSSL_HMAC_CTX HMAC_CTX; #define HMAC_size wolfSSL_HMAC_size #define HMAC_CTX_get_md wolfSSL_HMAC_CTX_get_md +#endif /* !OPENSSL_COEXIST */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/openssl/kdf.h b/src/wolfssl/openssl/kdf.h index 08d8327..295c99f 100644 --- a/src/wolfssl/openssl/kdf.h +++ b/src/wolfssl/openssl/kdf.h @@ -26,9 +26,17 @@ extern "C" { #endif -#define EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND 0 -#define EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY 1 -#define EVP_PKEY_HKDEF_MODE_EXPAND_ONLY 2 +#define WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND 0 +#define WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY 1 +#define WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY 2 + +#ifndef OPENSSL_COEXIST + +#define EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND +#define EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY +#define EVP_PKEY_HKDEF_MODE_EXPAND_ONLY WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY + +#endif /* !OPENSSL_COEXIST */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/openssl/md4.h b/src/wolfssl/openssl/md4.h index d478e96..9181e8d 100644 --- a/src/wolfssl/openssl/md4.h +++ b/src/wolfssl/openssl/md4.h @@ -46,6 +46,7 @@ WOLFSSL_API void wolfSSL_MD4_Update(WOLFSSL_MD4_CTX* md4, const void* data, unsigned long len); WOLFSSL_API void wolfSSL_MD4_Final(unsigned char* digest, WOLFSSL_MD4_CTX* md4); +#ifndef OPENSSL_COEXIST typedef WOLFSSL_MD4_CTX MD4_CTX; @@ -53,6 +54,8 @@ typedef WOLFSSL_MD4_CTX MD4_CTX; #define MD4_Update wolfSSL_MD4_Update #define MD4_Final wolfSSL_MD4_Final +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/md5.h b/src/wolfssl/openssl/md5.h index 62533a9..452b6a4 100644 --- a/src/wolfssl/openssl/md5.h +++ b/src/wolfssl/openssl/md5.h @@ -58,6 +58,8 @@ WOLFSSL_API int wolfSSL_MD5_Transform(WOLFSSL_MD5_CTX* md5, const unsigned char* WOLFSSL_API unsigned char *wolfSSL_MD5(const unsigned char* data, size_t len, unsigned char* hash); +#ifndef OPENSSL_COEXIST + typedef WOLFSSL_MD5_CTX MD5_CTX; #define MD5_Init wolfSSL_MD5_Init @@ -95,6 +97,8 @@ typedef WOLFSSL_MD5_CTX MD5_CTX; #define MD5_DIGEST_LENGTH MD5_DIGEST_SIZE #endif +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/obj_mac.h b/src/wolfssl/openssl/obj_mac.h index b083f04..b4d4013 100644 --- a/src/wolfssl/openssl/obj_mac.h +++ b/src/wolfssl/openssl/obj_mac.h @@ -27,20 +27,39 @@ extern "C" { #endif -#define NID_sect163k1 721 -#define NID_sect163r1 722 -#define NID_sect163r2 723 -#define NID_sect193r1 724 -#define NID_sect193r2 725 -#define NID_sect233k1 726 -#define NID_sect233r1 727 -#define NID_sect239k1 728 -#define NID_sect283k1 729 -#define NID_sect283r1 730 -#define NID_sect409k1 731 -#define NID_sect409r1 732 -#define NID_sect571k1 733 -#define NID_sect571r1 734 +#define WC_NID_sect163k1 721 +#define WC_NID_sect163r1 722 +#define WC_NID_sect163r2 723 +#define WC_NID_sect193r1 724 +#define WC_NID_sect193r2 725 +#define WC_NID_sect233k1 726 +#define WC_NID_sect233r1 727 +#define WC_NID_sect239k1 728 +#define WC_NID_sect283k1 729 +#define WC_NID_sect283r1 730 +#define WC_NID_sect409k1 731 +#define WC_NID_sect409r1 732 +#define WC_NID_sect571k1 733 +#define WC_NID_sect571r1 734 + +#ifndef OPENSSL_COEXIST + +#define NID_sect163k1 WC_NID_sect163k1 +#define NID_sect163r1 WC_NID_sect163r1 +#define NID_sect163r2 WC_NID_sect163r2 +#define NID_sect193r1 WC_NID_sect193r1 +#define NID_sect193r2 WC_NID_sect193r2 +#define NID_sect233k1 WC_NID_sect233k1 +#define NID_sect233r1 WC_NID_sect233r1 +#define NID_sect239k1 WC_NID_sect239k1 +#define NID_sect283k1 WC_NID_sect283k1 +#define NID_sect283r1 WC_NID_sect283r1 +#define NID_sect409k1 WC_NID_sect409k1 +#define NID_sect409r1 WC_NID_sect409r1 +#define NID_sect571k1 WC_NID_sect571k1 +#define NID_sect571r1 WC_NID_sect571r1 + +#endif /* !OPENSSL_COEXIST */ /* the definition is for Qt Unit test */ #define SN_jurisdictionCountryName "jurisdictionC" diff --git a/src/wolfssl/openssl/objects.h b/src/wolfssl/openssl/objects.h index 08640fb..1b6ce80 100644 --- a/src/wolfssl/openssl/objects.h +++ b/src/wolfssl/openssl/objects.h @@ -35,6 +35,11 @@ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#define WC_NID_ad_OCSP 178 +#define WC_NID_ad_ca_issuers 179 + +#ifndef OPENSSL_COEXIST + #define OBJ_NAME_TYPE_UNDEF WOLFSSL_OBJ_NAME_TYPE_UNDEF #define OBJ_NAME_TYPE_MD_METH WOLFSSL_OBJ_NAME_TYPE_MD_METH #define OBJ_NAME_TYPE_CIPHER_METH WOLFSSL_OBJ_NAME_TYPE_CIPHER_METH @@ -64,9 +69,10 @@ /* not required for wolfSSL */ #define OPENSSL_load_builtin_modules() WC_DO_NOTHING +#define NID_ad_OCSP WC_NID_ad_OCSP +#define NID_ad_ca_issuers WC_NID_ad_ca_issuers -#define NID_ad_OCSP 178 -#define NID_ad_ca_issuers 179 +#endif /* !OPENSSL_COEXIST */ #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ diff --git a/src/wolfssl/openssl/ocsp.h b/src/wolfssl/openssl/ocsp.h index 28eb159..a6bae66 100644 --- a/src/wolfssl/openssl/ocsp.h +++ b/src/wolfssl/openssl/ocsp.h @@ -27,6 +27,8 @@ #ifdef HAVE_OCSP #include +#ifndef OPENSSL_COEXIST + #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) ||\ defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) typedef OcspRequest OCSP_REQUEST; @@ -98,6 +100,8 @@ typedef WOLFSSL_OCSP_REQ_CTX OCSP_REQ_CTX; #define OCSP_REQ_CTX_nbio wolfSSL_OCSP_REQ_CTX_nbio #define OCSP_sendreq_nbio wolfSSL_OCSP_sendreq_nbio +#endif /* !OPENSSL_COEXIST */ + #endif /* HAVE_OCSP */ #endif /* WOLFSSL_OCSP_H_ */ diff --git a/src/wolfssl/openssl/pem.h b/src/wolfssl/openssl/pem.h index 8ecc02c..3666ab5 100644 --- a/src/wolfssl/openssl/pem.h +++ b/src/wolfssl/openssl/pem.h @@ -183,8 +183,8 @@ WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio, void* pass); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_API -PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, - PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, void* arg); +WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, + WOLFSSL_PKCS8_PRIV_KEY_INFO** key, wc_pem_password_cb* cb, void* arg); #endif WOLFSSL_API WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio, @@ -233,6 +233,8 @@ WOLFSSL_API int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #endif /* NO_FILESYSTEM */ +#ifndef OPENSSL_COEXIST + #define PEM_BUFSIZE WOLF_PEM_BUFSIZE #define PEM_read wolfSSL_PEM_read @@ -278,7 +280,7 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #define PEM_read_bio_EC_PUBKEY wolfSSL_PEM_read_bio_EC_PUBKEY #define PEM_read_bio_ECPKParameters wolfSSL_PEM_read_bio_ECPKParameters #ifndef NO_WOLFSSL_STUB -#define PEM_write_bio_ECPKParameters(...) 0 +#define PEM_write_bio_ECPKParameters(out, x) 0 #endif /* EVP_KEY */ #define PEM_read_bio_PrivateKey wolfSSL_PEM_read_bio_PrivateKey @@ -289,6 +291,8 @@ int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh); #define PEM_write_bio_PKCS8_PRIV_KEY_INFO wolfSSL_PEM_write_bio_PKCS8_PRIV_KEY_INFO #define PEM_read_bio_PKCS8_PRIV_KEY_INFO wolfSSL_PEM_read_bio_PKCS8_PRIV_KEY_INFO +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/pkcs12.h b/src/wolfssl/openssl/pkcs12.h index d82954d..7da2b98 100644 --- a/src/wolfssl/openssl/pkcs12.h +++ b/src/wolfssl/openssl/pkcs12.h @@ -28,9 +28,15 @@ #ifndef WOLFSSL_PKCS12_COMPAT_H_ #define WOLFSSL_PKCS12_COMPAT_H_ -#define NID_pbe_WithSHA1AndDES_CBC 2 -#define NID_pbe_WithSHA1And3_Key_TripleDES_CBC 3 -#define NID_pbe_WithSHA1And128BitRC4 1 +#define WC_NID_pbe_WithSHA1AndDES_CBC 2 +#define WC_NID_pbe_WithSHA1And3_Key_TripleDES_CBC 3 +#define WC_NID_pbe_WithSHA1And128BitRC4 1 + +#ifndef OPENSSL_COEXIST + +#define NID_pbe_WithSHA1AndDES_CBC WC_NID_pbe_WithSHA1AndDES_CBC +#define NID_pbe_WithSHA1And3_Key_TripleDES_CBC WC_NID_pbe_WithSHA1And3_Key_TripleDES_CBC +#define NID_pbe_WithSHA1And128BitRC4 WC_NID_pbe_WithSHA1And128BitRC4 #define PKCS12_DEFAULT_ITER WC_PKCS12_ITT_DEFAULT @@ -46,5 +52,6 @@ #define PKCS12_create wolfSSL_PKCS12_create #define PKCS12_PBE_add wolfSSL_PKCS12_PBE_add -#endif /* WOLFSSL_PKCS12_COMPAT_H_ */ +#endif /* !OPENSSL_COEXIST */ +#endif /* WOLFSSL_PKCS12_COMPAT_H_ */ diff --git a/src/wolfssl/openssl/rand.h b/src/wolfssl/openssl/rand.h index c88cd12..71d6810 100644 --- a/src/wolfssl/openssl/rand.h +++ b/src/wolfssl/openssl/rand.h @@ -21,9 +21,18 @@ /* rand.h for openSSL */ +#ifndef WOLFSSL_RAND_COMPAT_H_ +#define WOLFSSL_RAND_COMPAT_H_ + #include #include +#ifndef OPENSSL_COEXIST + typedef WOLFSSL_RAND_METHOD RAND_METHOD; #define RAND_set_rand_method wolfSSL_RAND_set_rand_method + +#endif /* !OPENSSL_COEXIST */ + +#endif /* WOLFSSL_RAND_COMPAT_H_ */ diff --git a/src/wolfssl/openssl/rc4.h b/src/wolfssl/openssl/rc4.h index cef9330..fb51128 100644 --- a/src/wolfssl/openssl/rc4.h +++ b/src/wolfssl/openssl/rc4.h @@ -41,16 +41,21 @@ typedef struct WOLFSSL_RC4_KEY { /* big enough for Arc4 from wolfssl/wolfcrypt/arc4.h */ void* holder[(272 + WC_ASYNC_DEV_SIZE) / sizeof(void*)]; } WOLFSSL_RC4_KEY; -typedef WOLFSSL_RC4_KEY RC4_KEY; WOLFSSL_API void wolfSSL_RC4_set_key(WOLFSSL_RC4_KEY* key, int len, const unsigned char* data); WOLFSSL_API void wolfSSL_RC4(WOLFSSL_RC4_KEY* key, size_t len, const unsigned char* in, unsigned char* out); +#ifndef OPENSSL_COEXIST + +typedef WOLFSSL_RC4_KEY RC4_KEY; + #define RC4 wolfSSL_RC4 #define RC4_set_key wolfSSL_RC4_set_key +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/openssl/rsa.h b/src/wolfssl/openssl/rsa.h index 9311283..c414fdf 100644 --- a/src/wolfssl/openssl/rsa.h +++ b/src/wolfssl/openssl/rsa.h @@ -36,11 +36,19 @@ #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + +/* Padding types */ +#define WC_RSA_PKCS1_PADDING 0 +#define WC_RSA_PKCS1_OAEP_PADDING 1 +#define WC_RSA_PKCS1_PSS_PADDING 2 + +#ifndef OPENSSL_COEXIST + /* Padding types */ -#define RSA_PKCS1_PADDING 0 -#define RSA_PKCS1_OAEP_PADDING 1 -#define RSA_PKCS1_PSS_PADDING 2 -#define RSA_NO_PADDING 3 +#define RSA_PKCS1_PADDING WC_RSA_PKCS1_PADDING +#define RSA_PKCS1_OAEP_PADDING WC_RSA_PKCS1_OAEP_PADDING +#define RSA_PKCS1_PSS_PADDING WC_RSA_PKCS1_PSS_PADDING +#define RSA_NO_PADDING WC_RSA_NO_PAD /* Emulate OpenSSL flags */ #define RSA_METHOD_FLAG_NO_CHECK (1 << 1) @@ -62,13 +70,15 @@ #define RSA_PSS_SALTLEN_MAX (-3) #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST */ + typedef struct WOLFSSL_RSA_METHOD { /* Flags of RSA key implementation. */ int flags; /* Name of RSA key implementation. */ char *name; /* RSA method dynamically allocated. */ - word16 dynamic:1; + WC_BITFIELD dynamic:1; } WOLFSSL_RSA_METHOD; #ifndef WOLFSSL_RSA_TYPE_DEFINED /* guard on redeclaration */ @@ -96,16 +106,16 @@ typedef struct WOLFSSL_RSA { int flags; /* Flags of implementation. */ /* bits */ - byte inSet:1; /* Internal set from external. */ - byte exSet:1; /* External set from internal. */ - byte ownRng:1; /* Rng needs to be free'd. */ + WC_BITFIELD inSet:1; /* Internal set from external. */ + WC_BITFIELD exSet:1; /* External set from internal. */ + WC_BITFIELD ownRng:1; /* Rng needs to be free'd. */ } WOLFSSL_RSA; #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) typedef WOLFSSL_RSA RSA; typedef WOLFSSL_RSA_METHOD RSA_METHOD; -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ WOLFSSL_API WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId); WOLFSSL_API WOLFSSL_RSA* wolfSSL_RSA_new(void); @@ -191,12 +201,15 @@ WOLFSSL_API int wolfSSL_RSA_set_ex_data_with_cleanup( #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -#define OPENSSL_RSA_MAX_MODULUS_BITS RSA_MAX_SIZE #define WOLFSSL_RSA_LOAD_PRIVATE 1 #define WOLFSSL_RSA_LOAD_PUBLIC 2 #define WOLFSSL_RSA_F4 0x10001L +#ifndef OPENSSL_COEXIST + +#define OPENSSL_RSA_MAX_MODULUS_BITS RSA_MAX_SIZE + #define RSA_new wolfSSL_RSA_new #define RSA_free wolfSSL_RSA_free @@ -247,6 +260,8 @@ WOLFSSL_API int wolfSSL_RSA_set_ex_data_with_cleanup( #define OPENSSL_RSA_MAX_MODULUS_BITS RSA_MAX_SIZE #define OPENSSL_RSA_MAX_PUBEXP_BITS RSA_MAX_SIZE +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/openssl/sha.h b/src/wolfssl/openssl/sha.h index f9bc1a5..34a1962 100644 --- a/src/wolfssl/openssl/sha.h +++ b/src/wolfssl/openssl/sha.h @@ -74,7 +74,7 @@ WOLFSSL_API int wolfSSL_SHA1_Update(WOLFSSL_SHA_CTX* sha, const void* input, WOLFSSL_API int wolfSSL_SHA1_Final(byte* output, WOLFSSL_SHA_CTX* sha); WOLFSSL_API int wolfSSL_SHA1_Transform(WOLFSSL_SHA_CTX* sha, const unsigned char *data); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) enum { SHA_DIGEST_LENGTH = 20 }; @@ -99,7 +99,7 @@ typedef WOLFSSL_SHA_CTX SHA_CTX; #define SHA1_Final wolfSSL_SHA1_Final #define SHA1_Transform wolfSSL_SHA1_Transform -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* !NO_SHA */ @@ -125,7 +125,7 @@ WOLFSSL_API int wolfSSL_SHA224_Init(WOLFSSL_SHA224_CTX* sha); WOLFSSL_API int wolfSSL_SHA224_Update(WOLFSSL_SHA224_CTX* sha, const void* input, unsigned long sz); WOLFSSL_API int wolfSSL_SHA224_Final(byte* output, WOLFSSL_SHA224_CTX* sha); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) enum { SHA224_DIGEST_LENGTH = 28 }; @@ -142,7 +142,7 @@ typedef WOLFSSL_SHA224_CTX SHA224_CTX; * because of SHA224 enum in FIPS build. */ #define SHA224 wolfSSL_SHA224 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 @@ -168,7 +168,7 @@ WOLFSSL_API int wolfSSL_SHA256_Update(WOLFSSL_SHA256_CTX* sha, const void* input WOLFSSL_API int wolfSSL_SHA256_Final(byte* output, WOLFSSL_SHA256_CTX* sha); WOLFSSL_API int wolfSSL_SHA256_Transform(WOLFSSL_SHA256_CTX* sha256, const unsigned char *data); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) enum { SHA256_DIGEST_LENGTH = 32 }; @@ -196,7 +196,7 @@ typedef WOLFSSL_SHA256_CTX SHA256_CTX; #define SHA256 wolfSSL_SHA256 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 @@ -215,7 +215,7 @@ WOLFSSL_API int wolfSSL_SHA384_Init(WOLFSSL_SHA384_CTX* sha); WOLFSSL_API int wolfSSL_SHA384_Update(WOLFSSL_SHA384_CTX* sha, const void* input, unsigned long sz); WOLFSSL_API int wolfSSL_SHA384_Final(byte* output, WOLFSSL_SHA384_CTX* sha); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) enum { SHA384_DIGEST_LENGTH = 48 }; @@ -230,7 +230,7 @@ typedef WOLFSSL_SHA384_CTX SHA384_CTX; * build. */ #define SHA384 wolfSSL_SHA384 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* WOLFSSL_SHA384 */ @@ -252,7 +252,7 @@ WOLFSSL_API int wolfSSL_SHA512_Update(WOLFSSL_SHA512_CTX* sha, WOLFSSL_API int wolfSSL_SHA512_Final(byte* output, WOLFSSL_SHA512_CTX* sha); WOLFSSL_API int wolfSSL_SHA512_Transform(WOLFSSL_SHA512_CTX* sha512, const unsigned char* data); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) enum { SHA512_DIGEST_LENGTH = 64 }; @@ -268,7 +268,7 @@ typedef WOLFSSL_SHA512_CTX SHA512_CTX; * build. */ #define SHA512 wolfSSL_SHA512 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #if !defined(WOLFSSL_NOSHA512_224) typedef struct WOLFSSL_SHA512_CTX WOLFSSL_SHA512_224_CTX; @@ -282,7 +282,7 @@ WOLFSSL_API int wolfSSL_SHA512_224_Final(byte* output, WOLFSSL_API int wolfSSL_SHA512_224_Transform(WOLFSSL_SHA512_CTX* sha512, const unsigned char* data); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) #define SHA512_224_Init wolfSSL_SHA512_224_Init #define SHA512_224_Update wolfSSL_SHA512_224_Update #define SHA512_224_Final wolfSSL_SHA512_224_Final @@ -291,7 +291,7 @@ WOLFSSL_API int wolfSSL_SHA512_224_Transform(WOLFSSL_SHA512_CTX* sha512, #if defined(NO_OLD_SHA_NAMES) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #define SHA512_224 wolfSSL_SHA512_224 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* !WOLFSSL_NOSHA512_224 */ #if !defined(WOLFSSL_NOSHA512_256) @@ -305,7 +305,7 @@ WOLFSSL_API int wolfSSL_SHA512_256_Final(byte* output, WOLFSSL_SHA512_256_CTX* s WOLFSSL_API int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512, const unsigned char* data); -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) #define SHA512_256_Init wolfSSL_SHA512_256_Init #define SHA512_256_Update wolfSSL_SHA512_256_Update #define SHA512_256_Final wolfSSL_SHA512_256_Final @@ -314,7 +314,7 @@ WOLFSSL_API int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512, #if defined(NO_OLD_SHA_NAMES) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) #define SHA512_256 wolfSSL_SHA512_256 #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #endif /* !WOLFSSL_NOSHA512_256 */ diff --git a/src/wolfssl/openssl/srp.h b/src/wolfssl/openssl/srp.h index 097cf51..d0e6123 100644 --- a/src/wolfssl/openssl/srp.h +++ b/src/wolfssl/openssl/srp.h @@ -24,6 +24,10 @@ #include +#ifndef OPENSSL_COEXIST + #define SRP_MINIMAL_N SRP_MODULUS_MIN_BITS +#endif /* !OPENSSL_COEXIST */ + #endif /* WOLFSSL_SRP_H_ */ diff --git a/src/wolfssl/openssl/ssl.h b/src/wolfssl/openssl/ssl.h index f6d29f0..959d1e6 100644 --- a/src/wolfssl/openssl/ssl.h +++ b/src/wolfssl/openssl/ssl.h @@ -31,6 +31,8 @@ #include +#include + /* wolfssl_openssl compatibility layer */ #ifndef OPENSSL_EXTRA_SSL_GUARD #define OPENSSL_EXTRA_SSL_GUARD @@ -75,6 +77,61 @@ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#ifndef WOLFCRYPT_ONLY + +#define WOLFSSL_ERR_LIB_SYS 2 +#define WOLFSSL_ERR_LIB_RSA 4 +#define WOLFSSL_ERR_LIB_PEM 9 +#define WOLFSSL_ERR_LIB_X509 10 +#define WOLFSSL_ERR_LIB_EVP 11 +#define WOLFSSL_ERR_LIB_ASN1 12 +#define WOLFSSL_ERR_LIB_DIGEST 13 +#define WOLFSSL_ERR_LIB_CIPHER 14 +#define WOLFSSL_ERR_LIB_USER 15 +#define WOLFSSL_ERR_LIB_EC 16 +#define WOLFSSL_ERR_LIB_SSL 20 +#define WOLFSSL_ERR_LIB_PKCS12 35 + +#endif + +#ifndef WOLFCRYPT_ONLY +#define WOLFSSL_PEMerr(func, reason) wolfSSL_ERR_put_error(WOLFSSL_ERR_LIB_PEM, \ + (func), (reason), __FILE__, __LINE__) +#else +#define WOLFSSL_PEMerr(func, reason) WOLFSSL_ERROR_LINE((reason), \ + NULL, __LINE__, __FILE__, NULL) +#endif +#ifndef WOLFCRYPT_ONLY +#define WOLFSSL_EVPerr(func, reason) wolfSSL_ERR_put_error(WOLFSSL_ERR_LIB_EVP, \ + (func), (reason), __FILE__, __LINE__) +#else +#define WOLFSSL_EVPerr(func, reason) WOLFSSL_ERROR_LINE((reason), \ + NULL, __LINE__, __FILE__, NULL) +#endif + +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#define WOLFSSL_AD_UNRECOGNIZED_NAME unrecognized_name + +#define WOLFSSL_TLSEXT_STATUSTYPE_ocsp 1 + +#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) || \ + defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_WPAS_SMALL) + +#define WOLFSSL_NPN_UNSUPPORTED 0 +#define WOLFSSL_NPN_NEGOTIATED 1 +#define WOLFSSL_NPN_NO_OVERLAP 2 + +#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || \ + WOLFSSL_MYSQL_COMPATIBLE || OPENSSL_EXTRA || \ + HAVE_LIGHTY || HAVE_STUNNEL || \ + WOLFSSL_WPAS_SMALL */ + +#if !defined(OPENSSL_COEXIST) && \ + (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) + typedef WOLFSSL SSL; typedef WOLFSSL_SESSION SSL_SESSION; typedef WOLFSSL_METHOD SSL_METHOD; @@ -159,11 +216,11 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define CRYPTO_set_mem_functions wolfSSL_CRYPTO_set_mem_functions -/* depreciated */ +/* deprecated */ #define CRYPTO_thread_id wolfSSL_thread_id #define CRYPTO_set_id_callback wolfSSL_set_id_callback -#define CRYPTO_LOCK 0x01 +/* compat CRYPTO_LOCK is defined in wolfssl/ssl.h */ #define CRYPTO_UNLOCK 0x02 #define CRYPTO_READ 0x04 #define CRYPTO_WRITE 0x08 @@ -400,7 +457,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_SESSION_get_max_early_data wolfSSL_SESSION_get_max_early_data #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) - #define SSL_MODE_RELEASE_BUFFERS 0x00000010U + /* compat SSL_MODE_RELEASE_BUFFERS is defined in wolfssl/ssl.h */ #define ASN1_BOOLEAN WOLFSSL_ASN1_BOOLEAN #define X509_get_ext wolfSSL_X509_get_ext #define X509_get_ext_by_OBJ wolfSSL_X509_get_ext_by_OBJ @@ -509,11 +566,12 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define X509_set1_notBefore wolfSSL_X509_set1_notBefore #define X509_set_serialNumber wolfSSL_X509_set_serialNumber #define X509_set_version wolfSSL_X509_set_version -#define X509_REQ_set_version wolfSSL_X509_set_version +#define X509_REQ_set_version wolfSSL_X509_REQ_set_version +#define X509_REQ_get_version wolfSSL_X509_REQ_get_version #define X509_sign wolfSSL_X509_sign #define X509_sign_ctx wolfSSL_X509_sign_ctx #define X509_print wolfSSL_X509_print -#define X509_REQ_print wolfSSL_X509_print +#define X509_REQ_print wolfSSL_X509_REQ_print #define X509_print_ex wolfSSL_X509_print_ex #define X509_print_fp wolfSSL_X509_print_fp #define X509_CRL_print wolfSSL_X509_CRL_print @@ -746,6 +804,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_CRL_get_version wolfSSL_X509_CRL_version #define X509_load_crl_file wolfSSL_X509_load_crl_file +#define X509_ACERT_new wolfSSL_X509_ACERT_new #define X509_ACERT_free wolfSSL_X509_ACERT_free #define X509_ACERT_get_version wolfSSL_X509_ACERT_get_version #define X509_ACERT_get_signature_nid wolfSSL_X509_ACERT_get_signature_nid @@ -781,7 +840,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_REVOKED_get0_serialNumber wolfSSL_X509_REVOKED_get0_serial_number #define X509_REVOKED_get0_revocationDate wolfSSL_X509_REVOKED_get0_revocation_date -#define X509_check_purpose(...) 0 +#define X509_check_purpose(x, id, ca) 0 #define OCSP_parse_url wolfSSL_OCSP_parse_url @@ -926,7 +985,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ASN1_STRING_print(x, y) wolfSSL_ASN1_STRING_print ((WOLFSSL_BIO*)(x), (WOLFSSL_ASN1_STRING*)(y)) #define d2i_DISPLAYTEXT wolfSSL_d2i_DISPLAYTEXT #ifndef NO_WOLFSSL_STUB -#define ASN1_STRING_set_default_mask_asc(...) 1 +#define ASN1_STRING_set_default_mask_asc(p) 1 #endif #define ASN1_GENERALSTRING WOLFSSL_ASN1_STRING @@ -960,7 +1019,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ASN1_IA5STRING_free wolfSSL_ASN1_STRING_free #define ASN1_IA5STRING_set wolfSSL_ASN1_STRING_set -#define ASN1_PRINTABLE_type(...) V_ASN1_PRINTABLESTRING +#define ASN1_PRINTABLE_type(s, max) V_ASN1_PRINTABLESTRING #define ASN1_UTCTIME_pr wolfSSL_ASN1_UTCTIME_pr @@ -1089,20 +1148,8 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define ERR_lib_error_string wolfSSL_ERR_lib_error_string #define ERR_load_BIO_strings wolfSSL_ERR_load_BIO_strings -#ifndef WOLFCRYPT_ONLY -#define PEMerr(func, reason) wolfSSL_ERR_put_error(ERR_LIB_PEM, \ - (func), (reason), __FILE__, __LINE__) -#else -#define PEMerr(func, reason) WOLFSSL_ERROR_LINE((reason), \ - NULL, __LINE__, __FILE__, NULL) -#endif -#ifndef WOLFCRYPT_ONLY -#define EVPerr(func, reason) wolfSSL_ERR_put_error(ERR_LIB_EVP, \ - (func), (reason), __FILE__, __LINE__) -#else -#define EVPerr(func, reason) WOLFSSL_ERROR_LINE((reason), \ - NULL, __LINE__, __FILE__, NULL) -#endif +#define PEMerr(func, reason) WOLFSSL_PEMerr(func, reason) +#define EVPerr(func, reason) WOLFSSL_EVPerr(func, reason) #define SSLv23_server_method wolfSSLv23_server_method #define SSL_CTX_set_options wolfSSL_CTX_set_options @@ -1280,7 +1327,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL_CTX_set_dh_auto wolfSSL_CTX_set_dh_auto #define SSL_CTX_set_tmp_dh wolfSSL_CTX_set_tmp_dh -#define TLSEXT_STATUSTYPE_ocsp 1 +#define TLSEXT_STATUSTYPE_ocsp WOLFSSL_TLSEXT_STATUSTYPE_ocsp #define TLSEXT_max_fragment_length_DISABLED WOLFSSL_MFL_DISABLED #define TLSEXT_max_fragment_length_512 WOLFSSL_MFL_2_9 @@ -1420,14 +1467,12 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL3_AD_BAD_CERTIFICATE bad_certificate #define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE -#define SSL_AD_UNRECOGNIZED_NAME unrecognized_name +#define SSL_AD_UNRECOGNIZED_NAME WOLFSSL_AD_UNRECOGNIZED_NAME #define SSL_AD_NO_RENEGOTIATION no_renegotiation #define SSL_AD_INTERNAL_ERROR 80 #define SSL_AD_NO_APPLICATION_PROTOCOL no_application_protocol #define SSL_AD_MISSING_EXTENSION missing_extension -#define ASN1_STRFLGS_ESC_MSB 4 - #define SSL_MAX_MASTER_KEY_LENGTH WOLFSSL_MAX_MASTER_KEY_LENGTH #define SSL_alert_desc_string_long wolfSSL_alert_desc_string_long @@ -1525,7 +1570,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define PSK_MAX_IDENTITY_LEN 128 #define SSL_CTX_clear_options wolfSSL_CTX_clear_options -#define SSL_CTX_add_server_custom_ext(...) 0 +#define SSL_CTX_add_server_custom_ext(ctx, ext_type, add_cb, free_cb, add_arg, parse_cb, parse_arg) 0 #define SSL_get0_verified_chain wolfSSL_get0_verified_chain #define X509_chain_up_ref wolfSSL_X509_chain_up_ref @@ -1533,8 +1578,8 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #endif /* HAVE_STUNNEL || WOLFSSL_NGINX */ #ifndef NO_WOLFSSL_STUB -#define b2i_PrivateKey_bio(...) NULL -#define b2i_PVK_bio(...) NULL +#define b2i_PrivateKey_bio(in) NULL +#define b2i_PVK_bio(in, cb, u) NULL #endif #define SSL_CTX_get_default_passwd_cb wolfSSL_CTX_get_default_passwd_cb @@ -1557,42 +1602,41 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define PEM_F_PEM_DEF_CALLBACK 100 -/* Avoid wolfSSL error code range */ -#define PEM_R_NO_START_LINE (-MIN_CODE_E + 1) -#define PEM_R_PROBLEMS_GETTING_PASSWORD (-MIN_CODE_E + 2) -#define PEM_R_BAD_PASSWORD_READ (-MIN_CODE_E + 3) -#define PEM_R_BAD_DECRYPT (-MIN_CODE_E + 4) -#define ASN1_R_HEADER_TOO_LONG (-MIN_CODE_E + 5) - -#define ERR_LIB_SYS 2 -#define ERR_LIB_RSA 4 -#define ERR_LIB_PEM 9 -#define ERR_LIB_X509 10 -#define ERR_LIB_EVP 11 -#define ERR_LIB_ASN1 12 -#define ERR_LIB_DIGEST 13 -#define ERR_LIB_CIPHER 14 -#define ERR_LIB_USER 15 -#define ERR_LIB_EC 16 -#define ERR_LIB_SSL 20 -#define ERR_LIB_PKCS12 35 +#include + +#define PEM_R_NO_START_LINE (-WOLFSSL_PEM_R_NO_START_LINE_E) +#define PEM_R_PROBLEMS_GETTING_PASSWORD (-WOLFSSL_PEM_R_PROBLEMS_GETTING_PASSWORD_E) +#define PEM_R_BAD_PASSWORD_READ (-WOLFSSL_PEM_R_BAD_PASSWORD_READ_E) +#define PEM_R_BAD_DECRYPT (-WOLFSSL_PEM_R_BAD_DECRYPT_E) +#define ASN1_R_HEADER_TOO_LONG (-WOLFSSL_ASN1_R_HEADER_TOO_LONG_E) + +#define ERR_LIB_SYS WOLFSSL_ERR_LIB_SYS +#define ERR_LIB_RSA WOLFSSL_ERR_LIB_RSA +#define ERR_LIB_PEM WOLFSSL_ERR_LIB_PEM +#define ERR_LIB_X509 WOLFSSL_ERR_LIB_X509 +#define ERR_LIB_EVP WOLFSSL_ERR_LIB_EVP +#define ERR_LIB_ASN1 WOLFSSL_ERR_LIB_ASN1 +#define ERR_LIB_DIGEST WOLFSSL_ERR_LIB_DIGEST +#define ERR_LIB_CIPHER WOLFSSL_ERR_LIB_CIPHER +#define ERR_LIB_USER WOLFSSL_ERR_LIB_USER +#define ERR_LIB_EC WOLFSSL_ERR_LIB_EC +#define ERR_LIB_SSL WOLFSSL_ERR_LIB_SSL +#define ERR_LIB_PKCS12 WOLFSSL_ERR_LIB_PKCS12 #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) || \ defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \ defined(WOLFSSL_WPAS_SMALL) -#include - #define OPENSSL_STRING WOLFSSL_STRING #define OPENSSL_CSTRING WOLFSSL_STRING #define TLSEXT_TYPE_application_layer_protocol_negotiation \ TLSXT_APPLICATION_LAYER_PROTOCOL -#define OPENSSL_NPN_UNSUPPORTED 0 -#define OPENSSL_NPN_NEGOTIATED 1 -#define OPENSSL_NPN_NO_OVERLAP 2 +#define OPENSSL_NPN_UNSUPPORTED WOLFSSL_NPN_UNSUPPORTED +#define OPENSSL_NPN_NEGOTIATED WOLFSSL_NPN_NEGOTIATED +#define OPENSSL_NPN_NO_OVERLAP WOLFSSL_NPN_NO_OVERLAP /* Nginx checks these to see if the error was a handshake error. */ #define SSL_R_BAD_CHANGE_CIPHER_SPEC LENGTH_ERROR @@ -1689,7 +1733,7 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define ERR_NUM_ERRORS 16 #define SN_pkcs9_emailAddress "Email" #define LN_pkcs9_emailAddress "emailAddress" -#define NID_pkcs9_emailAddress 48 +#define NID_pkcs9_emailAddress WC_NID_pkcs9_emailAddress #define OBJ_pkcs9_emailAddress 1L,2L,840L,113539L,1L,9L,1L #define LN_basic_constraints "X509v3 Basic Constraints" @@ -1745,8 +1789,8 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define X509_OBJECT_retrieve_by_subject wolfSSL_X509_OBJECT_retrieve_by_subject #ifndef NO_WOLFSSL_STUB -#define OBJ_create_objects(...) WC_DO_NOTHING -#define sk_SSL_COMP_free(...) WC_DO_NOTHING +#define OBJ_create_objects(in) WC_DO_NOTHING +#define sk_SSL_COMP_free(sk) WC_DO_NOTHING #endif #define ASN1_OBJECT_new wolfSSL_ASN1_OBJECT_new @@ -1766,7 +1810,7 @@ typedef WOLFSSL_CONF_CTX SSL_CONF_CTX; #define SSL_CONF_cmd wolfSSL_CONF_cmd #define SSL_CONF_cmd_value_type wolfSSL_CONF_cmd_value_type -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ #ifdef WOLFSSL_QUIC @@ -1781,11 +1825,19 @@ typedef WOLFSSL_CONF_CTX SSL_CONF_CTX; * SSL_CIPHER_get_id(cipher) * used by QUIC implementations, such as HAProxy */ -#define TLS1_3_CK_AES_128_GCM_SHA256 0x1301 -#define TLS1_3_CK_AES_256_GCM_SHA384 0x1302 -#define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x1303 -#define TLS1_3_CK_AES_128_CCM_SHA256 0x1304 -#define TLS1_3_CK_AES_128_CCM_8_SHA256 0x1305 +#define WOLF_TLS1_3_CK_AES_128_GCM_SHA256 0x1301 +#define WOLF_TLS1_3_CK_AES_256_GCM_SHA384 0x1302 +#define WOLF_TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x1303 +#define WOLF_TLS1_3_CK_AES_128_CCM_SHA256 0x1304 +#define WOLF_TLS1_3_CK_AES_128_CCM_8_SHA256 0x1305 + +#ifndef OPENSSL_COEXIST + +#define TLS1_3_CK_AES_128_GCM_SHA256 WOLF_TLS1_3_CK_AES_128_GCM_SHA256 +#define TLS1_3_CK_AES_256_GCM_SHA384 WOLF_TLS1_3_CK_AES_256_GCM_SHA384 +#define TLS1_3_CK_CHACHA20_POLY1305_SHA256 WOLF_TLS1_3_CK_CHACHA20_POLY1305_SHA256 +#define TLS1_3_CK_AES_128_CCM_SHA256 WOLF_TLS1_3_CK_AES_128_CCM_SHA256 +#define TLS1_3_CK_AES_128_CCM_8_SHA256 WOLF_TLS1_3_CK_AES_128_CCM_8_SHA256 #define SSL_R_MISSING_QUIC_TRANSPORT_PARAMETERS_EXTENSION QUIC_TP_MISSING_E #define SSL_R_WRONG_ENCRYPTION_LEVEL_RECEIVED QUIC_WRONG_ENC_LEVEL @@ -1827,6 +1879,8 @@ typedef WOLFSSL_ENCRYPTION_LEVEL OSSL_ENCRYPTION_LEVEL; int SSL_CIPHER_get_prf_nid(const SSL_CIPHER *c); */ +#endif /* !OPENSSL_COEXIST */ + #endif /* WOLFSSL_QUIC */ diff --git a/src/wolfssl/openssl/tls1.h b/src/wolfssl/openssl/tls1.h index 933ed5d..1f8895c 100644 --- a/src/wolfssl/openssl/tls1.h +++ b/src/wolfssl/openssl/tls1.h @@ -45,10 +45,20 @@ #ifdef WOLFSSL_QUIC /* from rfc9001 */ +#define WOLFSSL_TLSEXT_TYPE_quic_transport_parameters_draft \ + TLSXT_KEY_QUIC_TP_PARAMS_DRAFT +#define WOLFSSL_TLSEXT_TYPE_quic_transport_parameters \ + TLSXT_KEY_QUIC_TP_PARAMS + +#ifndef OPENSSL_COEXIST + #define TLSEXT_TYPE_quic_transport_parameters_draft \ TLSXT_KEY_QUIC_TP_PARAMS_DRAFT #define TLSEXT_TYPE_quic_transport_parameters \ TLSXT_KEY_QUIC_TP_PARAMS -#endif + +#endif /* !OPENSSL_COEXIST */ + +#endif /* WOLFSSL_QUIC */ #endif /* WOLFSSL_OPENSSL_TLS1_H_ */ diff --git a/src/wolfssl/openssl/x509.h b/src/wolfssl/openssl/x509.h index eb03578..f2bfb1b 100644 --- a/src/wolfssl/openssl/x509.h +++ b/src/wolfssl/openssl/x509.h @@ -33,167 +33,192 @@ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#define WOLFSSL_X509_FLAG_COMPAT (0UL) +#define WOLFSSL_X509_FLAG_NO_HEADER (1UL << 0) +#define WOLFSSL_X509_FLAG_NO_VERSION (1UL << 1) +#define WOLFSSL_X509_FLAG_NO_SERIAL (1UL << 2) +#define WOLFSSL_X509_FLAG_NO_SIGNAME (1UL << 3) +#define WOLFSSL_X509_FLAG_NO_ISSUER (1UL << 4) +#define WOLFSSL_X509_FLAG_NO_VALIDITY (1UL << 5) +#define WOLFSSL_X509_FLAG_NO_SUBJECT (1UL << 6) +#define WOLFSSL_X509_FLAG_NO_PUBKEY (1UL << 7) +#define WOLFSSL_X509_FLAG_NO_EXTENSIONS (1UL << 8) +#define WOLFSSL_X509_FLAG_NO_SIGDUMP (1UL << 9) +#define WOLFSSL_X509_FLAG_NO_AUX (1UL << 10) +#define WOLFSSL_X509_FLAG_NO_ATTRIBUTES (1UL << 11) +#define WOLFSSL_X509_FLAG_NO_IDS (1UL << 12) + +#define WOLFSSL_XN_FLAG_FN_SN 0 +#define WOLFSSL_XN_FLAG_COMPAT 0 +#define WOLFSSL_XN_FLAG_RFC2253 1 +#define WOLFSSL_XN_FLAG_SEP_COMMA_PLUS (1 << 16) +#define WOLFSSL_XN_FLAG_SEP_CPLUS_SPC (2 << 16) +#define WOLFSSL_XN_FLAG_SEP_SPLUS_SPC (3 << 16) +#define WOLFSSL_XN_FLAG_SEP_MULTILINE (4 << 16) +#define WOLFSSL_XN_FLAG_SEP_MASK (0xF << 16) +#define WOLFSSL_XN_FLAG_DN_REV (1 << 20) +#define WOLFSSL_XN_FLAG_FN_LN (1 << 21) +#define WOLFSSL_XN_FLAG_FN_OID (2 << 21) +#define WOLFSSL_XN_FLAG_FN_NONE (3 << 21) +#define WOLFSSL_XN_FLAG_FN_MASK (3 << 21) +#define WOLFSSL_XN_FLAG_SPC_EQ (1 << 23) +#define WOLFSSL_XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24) +#define WOLFSSL_XN_FLAG_FN_ALIGN (1 << 25) + +#define WOLFSSL_XN_FLAG_MULTILINE 0xFFFF +#define WOLFSSL_XN_FLAG_ONELINE (WOLFSSL_XN_FLAG_SEP_CPLUS_SPC | WOLFSSL_XN_FLAG_SPC_EQ | WOLFSSL_XN_FLAG_FN_SN) + +#define WOLFSSL_X509_V_ERR_CRL_HAS_EXPIRED 12 +#define WOLFSSL_X509_V_ERR_UNABLE_TO_GET_CRL 3 + +#ifndef OPENSSL_COEXIST + /* wolfSSL_X509_print_ex flags */ -#define X509_FLAG_COMPAT (0UL) -#define X509_FLAG_NO_HEADER (1UL << 0) -#define X509_FLAG_NO_VERSION (1UL << 1) -#define X509_FLAG_NO_SERIAL (1UL << 2) -#define X509_FLAG_NO_SIGNAME (1UL << 3) -#define X509_FLAG_NO_ISSUER (1UL << 4) -#define X509_FLAG_NO_VALIDITY (1UL << 5) -#define X509_FLAG_NO_SUBJECT (1UL << 6) -#define X509_FLAG_NO_PUBKEY (1UL << 7) -#define X509_FLAG_NO_EXTENSIONS (1UL << 8) -#define X509_FLAG_NO_SIGDUMP (1UL << 9) -#define X509_FLAG_NO_AUX (1UL << 10) -#define X509_FLAG_NO_ATTRIBUTES (1UL << 11) -#define X509_FLAG_NO_IDS (1UL << 12) - -#define XN_FLAG_FN_SN 0 -#define XN_FLAG_COMPAT 0 -#define XN_FLAG_RFC2253 1 -#define XN_FLAG_SEP_COMMA_PLUS (1 << 16) -#define XN_FLAG_SEP_CPLUS_SPC (2 << 16) -#define XN_FLAG_SEP_SPLUS_SPC (3 << 16) -#define XN_FLAG_SEP_MULTILINE (4 << 16) -#define XN_FLAG_SEP_MASK (0xF << 16) -#define XN_FLAG_DN_REV (1 << 20) -#define XN_FLAG_FN_LN (1 << 21) -#define XN_FLAG_FN_OID (2 << 21) -#define XN_FLAG_FN_NONE (3 << 21) -#define XN_FLAG_FN_MASK (3 << 21) -#define XN_FLAG_SPC_EQ (1 << 23) -#define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24) -#define XN_FLAG_FN_ALIGN (1 << 25) - -#define XN_FLAG_MULTILINE 0xFFFF -#define XN_FLAG_ONELINE (XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_SPC_EQ | XN_FLAG_FN_SN) +#define X509_FLAG_COMPAT WOLFSSL_X509_FLAG_COMPAT +#define X509_FLAG_NO_HEADER WOLFSSL_X509_FLAG_NO_HEADER +#define X509_FLAG_NO_VERSION WOLFSSL_X509_FLAG_NO_VERSION +#define X509_FLAG_NO_SERIAL WOLFSSL_X509_FLAG_NO_SERIAL +#define X509_FLAG_NO_SIGNAME WOLFSSL_X509_FLAG_NO_SIGNAME +#define X509_FLAG_NO_ISSUER WOLFSSL_X509_FLAG_NO_ISSUER +#define X509_FLAG_NO_VALIDITY WOLFSSL_X509_FLAG_NO_VALIDITY +#define X509_FLAG_NO_SUBJECT WOLFSSL_X509_FLAG_NO_SUBJECT +#define X509_FLAG_NO_PUBKEY WOLFSSL_X509_FLAG_NO_PUBKEY +#define X509_FLAG_NO_EXTENSIONS WOLFSSL_X509_FLAG_NO_EXTENSIONS +#define X509_FLAG_NO_SIGDUMP WOLFSSL_X509_FLAG_NO_SIGDUMP +#define X509_FLAG_NO_AUX WOLFSSL_X509_FLAG_NO_AUX +#define X509_FLAG_NO_ATTRIBUTES WOLFSSL_X509_FLAG_NO_ATTRIBUTES +#define X509_FLAG_NO_IDS WOLFSSL_X509_FLAG_NO_IDS + +#define XN_FLAG_FN_SN WOLFSSL_XN_FLAG_FN_SN +#define XN_FLAG_COMPAT WOLFSSL_XN_FLAG_COMPAT +#define XN_FLAG_RFC2253 WOLFSSL_XN_FLAG_RFC2253 +#define XN_FLAG_SEP_COMMA_PLUS WOLFSSL_XN_FLAG_SEP_COMMA_PLUS +#define XN_FLAG_SEP_CPLUS_SPC WOLFSSL_XN_FLAG_SEP_CPLUS_SPC +#define XN_FLAG_SEP_SPLUS_SPC WOLFSSL_XN_FLAG_SEP_SPLUS_SPC +#define XN_FLAG_SEP_MULTILINE WOLFSSL_XN_FLAG_SEP_MULTILINE +#define XN_FLAG_SEP_MASK WOLFSSL_XN_FLAG_SEP_MASK +#define XN_FLAG_DN_REV WOLFSSL_XN_FLAG_DN_REV +#define XN_FLAG_FN_LN WOLFSSL_XN_FLAG_FN_LN +#define XN_FLAG_FN_OID WOLFSSL_XN_FLAG_FN_OID +#define XN_FLAG_FN_NONE WOLFSSL_XN_FLAG_FN_NONE +#define XN_FLAG_FN_MASK WOLFSSL_XN_FLAG_FN_MASK +#define XN_FLAG_SPC_EQ WOLFSSL_XN_FLAG_SPC_EQ +#define XN_FLAG_DUMP_UNKNOWN_FIELDS WOLFSSL_XN_FLAG_DUMP_UNKNOWN_FIELDS +#define XN_FLAG_FN_ALIGN WOLFSSL_XN_FLAG_FN_ALIGN + +#define XN_FLAG_MULTILINE WOLFSSL_XN_FLAG_MULTILINE +#define XN_FLAG_ONELINE WOLFSSL_XN_FLAG_ONELINE + +#define X509_V_ERR_UNABLE_TO_GET_CRL WOLFSSL_X509_V_ERR_UNABLE_TO_GET_CRL +#define X509_V_ERR_CRL_HAS_EXPIRED WOLFSSL_X509_V_ERR_CRL_HAS_EXPIRED /* - * All of these aren't actually used in wolfSSL. Some are included to - * satisfy OpenSSL compatibility consumers to prevent compilation errors. - * The list was taken from - * https://github.com/openssl/openssl/blob/master/include/openssl/x509_vfy.h.in - * One requirement for HAProxy is that the values should be literal constants. + * Not all of these X509_V_ERR values are used in wolfSSL. Some are included to + * satisfy OpenSSL compatibility compilation errors. + * For HAProxy the values should be literal constants. */ -#define X509_V_OK 0 -#define X509_V_ERR_UNSPECIFIED 1 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 -#define X509_V_ERR_UNABLE_TO_GET_CRL 3 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 -#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 -#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 -#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 -#define X509_V_ERR_CERT_NOT_YET_VALID 9 -#define X509_V_ERR_CERT_HAS_EXPIRED 10 -#define X509_V_ERR_CRL_NOT_YET_VALID 11 -#define X509_V_ERR_CRL_HAS_EXPIRED 12 -#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 -#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 -#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 -#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 -#define X509_V_ERR_OUT_OF_MEM 17 -#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 -#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 -#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 -#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 -#define X509_V_ERR_CERT_REVOKED 23 -#define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24 -#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 -#define X509_V_ERR_INVALID_PURPOSE 26 -#define X509_V_ERR_CERT_UNTRUSTED 27 -#define X509_V_ERR_CERT_REJECTED 28 - -/* These are 'informational' when looking for issuer cert */ -#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 -#define X509_V_ERR_AKID_SKID_MISMATCH 30 -#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 -#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 -#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 -#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 -#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 -#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 -#define X509_V_ERR_INVALID_NON_CA 37 -#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 -#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 -#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 -#define X509_V_ERR_INVALID_EXTENSION 41 -#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 -#define X509_V_ERR_NO_EXPLICIT_POLICY 43 -#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 -#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 -#define X509_V_ERR_UNNESTED_RESOURCE 46 -#define X509_V_ERR_PERMITTED_VIOLATION 47 -#define X509_V_ERR_EXCLUDED_VIOLATION 48 -#define X509_V_ERR_SUBTREE_MINMAX 49 -/* The application is not happy */ -#define X509_V_ERR_APPLICATION_VERIFICATION 50 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 -#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 -#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 -/* Another issuer check debug option */ -#define X509_V_ERR_PATH_LOOP 55 -/* Suite B mode algorithm violation */ -#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 -#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 -#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 -#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 -#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 +#define X509_V_OK 0 +#define X509_V_ERR_UNSPECIFIED 1 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 +#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 +#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 +#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 +#define X509_V_ERR_CERT_NOT_YET_VALID 9 +#define X509_V_ERR_CERT_HAS_EXPIRED 10 +#define X509_V_ERR_CRL_NOT_YET_VALID 11 +#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 +#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 +#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 +#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 +#define X509_V_ERR_OUT_OF_MEM 17 +#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 +#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 +#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 +#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 +#define X509_V_ERR_CERT_REVOKED 23 +#define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24 +#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 +#define X509_V_ERR_INVALID_PURPOSE 26 +#define X509_V_ERR_CERT_UNTRUSTED 27 +#define X509_V_ERR_CERT_REJECTED 28 +#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 +#define X509_V_ERR_AKID_SKID_MISMATCH 30 +#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 +#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 +#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 +#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 +#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 +#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 +#define X509_V_ERR_INVALID_NON_CA 37 +#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 +#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 +#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 +#define X509_V_ERR_INVALID_EXTENSION 41 +#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 +#define X509_V_ERR_NO_EXPLICIT_POLICY 43 +#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 +#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 +#define X509_V_ERR_UNNESTED_RESOURCE 46 +#define X509_V_ERR_PERMITTED_VIOLATION 47 +#define X509_V_ERR_EXCLUDED_VIOLATION 48 +#define X509_V_ERR_SUBTREE_MINMAX 49 +#define X509_V_ERR_APPLICATION_VERIFICATION 50 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 +#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 +#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 +#define X509_V_ERR_PATH_LOOP 55 +#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 +#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 +#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 +#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 +#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 #define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 -/* Host, email and IP check errors */ -#define X509_V_ERR_HOSTNAME_MISMATCH 62 -#define X509_V_ERR_EMAIL_MISMATCH 63 -#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 -/* DANE TLSA errors */ -#define X509_V_ERR_DANE_NO_MATCH 65 -/* security level errors */ -#define X509_V_ERR_EE_KEY_TOO_SMALL 66 -#define X509_V_ERR_CA_KEY_TOO_SMALL 67 -#define X509_V_ERR_CA_MD_TOO_WEAK 68 -/* Caller error */ -#define X509_V_ERR_INVALID_CALL 69 -/* Issuer lookup error */ -#define X509_V_ERR_STORE_LOOKUP 70 -/* Certificate transparency */ -#define X509_V_ERR_NO_VALID_SCTS 71 - -#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 -/* OCSP status errors */ -#define X509_V_ERR_OCSP_VERIFY_NEEDED 73 -#define X509_V_ERR_OCSP_VERIFY_FAILED 74 -#define X509_V_ERR_OCSP_CERT_UNKNOWN 75 - -#define X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM 76 -#define X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH 77 - -/* Errors in case a check in X509_V_FLAG_X509_STRICT mode fails */ -#define X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY 78 -#define X509_V_ERR_INVALID_CA 79 -#define X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA 80 -#define X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN 81 -#define X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA 82 -#define X509_V_ERR_ISSUER_NAME_EMPTY 83 -#define X509_V_ERR_SUBJECT_NAME_EMPTY 84 -#define X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER 85 -#define X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER 86 -#define X509_V_ERR_EMPTY_SUBJECT_ALT_NAME 87 -#define X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL 88 -#define X509_V_ERR_CA_BCONS_NOT_CRITICAL 89 -#define X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL 90 -#define X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL 91 -#define X509_V_ERR_CA_CERT_MISSING_KEY_USAGE 92 -#define X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 93 -#define X509_V_ERR_EC_KEY_EXPLICIT_PARAMS 94 -#define X509_R_CERT_ALREADY_IN_HASH_TABLE 101 +#define X509_V_ERR_HOSTNAME_MISMATCH 62 +#define X509_V_ERR_EMAIL_MISMATCH 63 +#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 +#define X509_V_ERR_DANE_NO_MATCH 65 +#define X509_V_ERR_EE_KEY_TOO_SMALL 66 +#define X509_V_ERR_CA_KEY_TOO_SMALL 67 +#define X509_V_ERR_CA_MD_TOO_WEAK 68 +#define X509_V_ERR_INVALID_CALL 69 +#define X509_V_ERR_STORE_LOOKUP 70 +#define X509_V_ERR_NO_VALID_SCTS 71 +#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 +#define X509_V_ERR_OCSP_VERIFY_NEEDED 73 +#define X509_V_ERR_OCSP_VERIFY_FAILED 74 +#define X509_V_ERR_OCSP_CERT_UNKNOWN 75 +#define X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM 76 +#define X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH 77 +#define X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY 78 +#define X509_V_ERR_INVALID_CA 79 +#define X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA 80 +#define X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN 81 +#define X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA 82 +#define X509_V_ERR_ISSUER_NAME_EMPTY 83 +#define X509_V_ERR_SUBJECT_NAME_EMPTY 84 +#define X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER 85 +#define X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER 86 +#define X509_V_ERR_EMPTY_SUBJECT_ALT_NAME 87 +#define X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL 88 +#define X509_V_ERR_CA_BCONS_NOT_CRITICAL 89 +#define X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL 90 +#define X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL 91 +#define X509_V_ERR_CA_CERT_MISSING_KEY_USAGE 92 +#define X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 93 +#define X509_V_ERR_EC_KEY_EXPLICIT_PARAMS 94 +#define X509_R_CERT_ALREADY_IN_HASH_TABLE 101 #define X509_EXTENSION_set_critical wolfSSL_X509_EXTENSION_set_critical #define X509_EXTENSION_set_object wolfSSL_X509_EXTENSION_set_object #define X509_EXTENSION_set_data wolfSSL_X509_EXTENSION_set_data +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #endif /* WOLFSSL_OPENSSL_509_H_ */ diff --git a/src/wolfssl/openssl/x509v3.h b/src/wolfssl/openssl/x509v3.h index 401f8e8..a84077d 100644 --- a/src/wolfssl/openssl/x509v3.h +++ b/src/wolfssl/openssl/x509v3.h @@ -36,91 +36,68 @@ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) -#define EXFLAG_KUSAGE 0x2 -#define EXFLAG_XKUSAGE 0x4 - -#define KU_DIGITAL_SIGNATURE KEYUSE_DIGITAL_SIG -#define KU_NON_REPUDIATION KEYUSE_CONTENT_COMMIT -#define KU_KEY_ENCIPHERMENT KEYUSE_KEY_ENCIPHER -#define KU_DATA_ENCIPHERMENT KEYUSE_DATA_ENCIPHER -#define KU_KEY_AGREEMENT KEYUSE_KEY_AGREE -#define KU_KEY_CERT_SIGN KEYUSE_KEY_CERT_SIGN -#define KU_CRL_SIGN KEYUSE_CRL_SIGN -#define KU_ENCIPHER_ONLY KEYUSE_ENCIPHER_ONLY -#define KU_DECIPHER_ONLY KEYUSE_DECIPHER_ONLY - -#define XKU_SSL_SERVER 0x1 -#define XKU_SSL_CLIENT 0x2 -#define XKU_SMIME 0x4 -#define XKU_CODE_SIGN 0x8 -#define XKU_SGC 0x10 -#define XKU_OCSP_SIGN 0x20 -#define XKU_TIMESTAMP 0x40 -#define XKU_DVCS 0x80 -#define XKU_ANYEKU 0x100 - -#define X509_PURPOSE_SSL_CLIENT 0 -#define X509_PURPOSE_SSL_SERVER 1 - -#define NS_SSL_CLIENT WC_NS_SSL_CLIENT -#define NS_SSL_SERVER WC_NS_SSL_SERVER - -/* Forward reference */ +#define WOLFSSL_EXFLAG_KUSAGE 0x2 +#define WOLFSSL_EXFLAG_XKUSAGE 0x4 + +#define WOLFSSL_XKU_SSL_SERVER 0x1 +#define WOLFSSL_XKU_SSL_CLIENT 0x2 +#define WOLFSSL_XKU_SMIME 0x4 +#define WOLFSSL_XKU_CODE_SIGN 0x8 +#define WOLFSSL_XKU_SGC 0x10 +#define WOLFSSL_XKU_OCSP_SIGN 0x20 +#define WOLFSSL_XKU_TIMESTAMP 0x40 +#define WOLFSSL_XKU_DVCS 0x80 +#define WOLFSSL_XKU_ANYEKU 0x100 + +#define WOLFSSL_X509_PURPOSE_SSL_CLIENT 0 +#define WOLFSSL_X509_PURPOSE_SSL_SERVER 1 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x0090801fL -typedef void *(*X509V3_EXT_D2I)(void *, const unsigned char **, long); +typedef void *(*WOLFSSL_X509V3_EXT_D2I)(void *, const unsigned char **, long); #else -typedef void *(*X509V3_EXT_D2I)(void *, unsigned char **, long); +typedef void *(*WOLFSSL_X509V3_EXT_D2I)(void *, unsigned char **, long); #endif -typedef int (*X509V3_EXT_I2D) (void *, unsigned char **); -typedef STACK_OF(CONF_VALUE) *(*X509V3_EXT_I2V) ( +typedef int (*WOLFSSL_X509V3_EXT_I2D) (void *, unsigned char **); +typedef WOLF_STACK_OF(CONF_VALUE) *(*WOLFSSL_X509V3_EXT_I2V) ( struct WOLFSSL_v3_ext_method *method, - void *ext, STACK_OF(CONF_VALUE) *extlist); -typedef char *(*X509V3_EXT_I2S)(struct WOLFSSL_v3_ext_method *method, void *ext); -typedef int (*X509V3_EXT_I2R) (struct WOLFSSL_v3_ext_method *method, - void *ext, BIO *out, int indent); -typedef struct WOLFSSL_v3_ext_method X509V3_EXT_METHOD; + void *ext, WOLF_STACK_OF(CONF_VALUE) *extlist); +typedef char *(*WOLFSSL_X509V3_EXT_I2S)(struct WOLFSSL_v3_ext_method *method, void *ext); +typedef int (*WOLFSSL_X509V3_EXT_I2R) (struct WOLFSSL_v3_ext_method *method, + void *ext, WOLFSSL_BIO *out, int indent); +typedef struct WOLFSSL_v3_ext_method WOLFSSL_X509V3_EXT_METHOD; struct WOLFSSL_v3_ext_method { int ext_nid; int ext_flags; void *usr_data; - X509V3_EXT_D2I d2i; - X509V3_EXT_I2D i2d; - X509V3_EXT_I2V i2v; - X509V3_EXT_I2S i2s; - X509V3_EXT_I2R i2r; + WOLFSSL_X509V3_EXT_D2I d2i; + WOLFSSL_X509V3_EXT_I2D i2d; + WOLFSSL_X509V3_EXT_I2V i2v; + WOLFSSL_X509V3_EXT_I2S i2s; + WOLFSSL_X509V3_EXT_I2R i2r; }; struct WOLFSSL_X509_EXTENSION { WOLFSSL_ASN1_OBJECT *obj; WOLFSSL_ASN1_BOOLEAN crit; - ASN1_OCTET_STRING value; /* DER format of extension */ + WOLFSSL_ASN1_STRING value; /* DER format of extension */ WOLFSSL_v3_ext_method ext_method; WOLFSSL_STACK* ext_sk; /* For extension specific data */ }; #define WOLFSSL_ASN1_BOOLEAN int -#define GEN_OTHERNAME 0 -#define GEN_EMAIL 1 -#define GEN_DNS 2 -#define GEN_X400 3 -#define GEN_DIRNAME 4 -#define GEN_EDIPARTY 5 -#define GEN_URI 6 -#define GEN_IPADD 7 -#define GEN_RID 8 -#define GEN_IA5 9 - -#define GENERAL_NAME WOLFSSL_GENERAL_NAME - -#define X509V3_CTX WOLFSSL_X509V3_CTX -#define CTX_TEST 0x1 +#define WOLFSSL_GEN_OTHERNAME 0 +#define WOLFSSL_GEN_EMAIL 1 +#define WOLFSSL_GEN_DNS 2 +#define WOLFSSL_GEN_X400 3 +#define WOLFSSL_GEN_DIRNAME 4 +#define WOLFSSL_GEN_EDIPARTY 5 +#define WOLFSSL_GEN_URI 6 +#define WOLFSSL_GEN_IPADD 7 +#define WOLFSSL_GEN_RID 8 +#define WOLFSSL_GEN_IA5 9 -typedef struct WOLFSSL_AUTHORITY_KEYID AUTHORITY_KEYID; -typedef struct WOLFSSL_BASIC_CONSTRAINTS BASIC_CONSTRAINTS; -typedef struct WOLFSSL_ACCESS_DESCRIPTION ACCESS_DESCRIPTION; typedef WOLF_STACK_OF(WOLFSSL_ACCESS_DESCRIPTION) WOLFSSL_AUTHORITY_INFO_ACCESS; WOLFSSL_API WOLFSSL_BASIC_CONSTRAINTS* wolfSSL_BASIC_CONSTRAINTS_new(void); @@ -157,6 +134,67 @@ WOLFSSL_API int wolfSSL_X509V3_EXT_add_nconf(WOLFSSL_CONF *conf, WOLFSSL_X509V3_CTX *ctx, const char *section, WOLFSSL_X509 *cert); WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); +#ifndef OPENSSL_COEXIST + +#define EXFLAG_KUSAGE WOLFSSL_EXFLAG_KUSAGE +#define EXFLAG_XKUSAGE WOLFSSL_EXFLAG_XKUSAGE + +#define KU_DIGITAL_SIGNATURE KEYUSE_DIGITAL_SIG +#define KU_NON_REPUDIATION KEYUSE_CONTENT_COMMIT +#define KU_KEY_ENCIPHERMENT KEYUSE_KEY_ENCIPHER +#define KU_DATA_ENCIPHERMENT KEYUSE_DATA_ENCIPHER +#define KU_KEY_AGREEMENT KEYUSE_KEY_AGREE +#define KU_KEY_CERT_SIGN KEYUSE_KEY_CERT_SIGN +#define KU_CRL_SIGN KEYUSE_CRL_SIGN +#define KU_ENCIPHER_ONLY KEYUSE_ENCIPHER_ONLY +#define KU_DECIPHER_ONLY KEYUSE_DECIPHER_ONLY + +#define XKU_SSL_SERVER WOLFSSL_XKU_SSL_SERVER +#define XKU_SSL_CLIENT WOLFSSL_XKU_SSL_CLIENT +#define XKU_SMIME WOLFSSL_XKU_SMIME +#define XKU_CODE_SIGN WOLFSSL_XKU_CODE_SIGN +#define XKU_SGC WOLFSSL_XKU_SGC +#define XKU_OCSP_SIGN WOLFSSL_XKU_OCSP_SIGN +#define XKU_TIMESTAMP WOLFSSL_XKU_TIMESTAMP +#define XKU_DVCS WOLFSSL_XKU_DVCS +#define XKU_ANYEKU WOLFSSL_XKU_ANYEKU + +#define X509_PURPOSE_SSL_CLIENT WOLFSSL_X509_PURPOSE_SSL_CLIENT +#define X509_PURPOSE_SSL_SERVER WOLFSSL_X509_PURPOSE_SSL_SERVER + +#define NS_SSL_CLIENT WC_NS_SSL_CLIENT +#define NS_SSL_SERVER WC_NS_SSL_SERVER + +/* Forward reference */ + +#define X509V3_EXT_D2I WOLFSSL_X509V3_EXT_D2I +#define X509V3_EXT_I2D WOLFSSL_X509V3_EXT_I2D +#define X509V3_EXT_I2V WOLFSSL_X509V3_EXT_I2V +#define X509V3_EXT_I2S WOLFSSL_X509V3_EXT_I2S +#define X509V3_EXT_I2R WOLFSSL_X509V3_EXT_I2R +typedef struct WOLFSSL_v3_ext_method X509V3_EXT_METHOD; + +#define GEN_OTHERNAME WOLFSSL_GEN_OTHERNAME +#define GEN_EMAIL WOLFSSL_GEN_EMAIL +#define GEN_DNS WOLFSSL_GEN_DNS +#define GEN_X400 WOLFSSL_GEN_X400 +#define GEN_DIRNAME WOLFSSL_GEN_DIRNAME +#define GEN_EDIPARTY WOLFSSL_GEN_EDIPARTY +#define GEN_URI WOLFSSL_GEN_URI +#define GEN_IPADD WOLFSSL_GEN_IPADD +#define GEN_RID WOLFSSL_GEN_RID +#define GEN_IA5 WOLFSSL_GEN_IA5 + +#define GENERAL_NAME WOLFSSL_GENERAL_NAME + +#define X509V3_CTX WOLFSSL_X509V3_CTX + +#define CTX_TEST 0x1 + +typedef struct WOLFSSL_AUTHORITY_KEYID AUTHORITY_KEYID; +typedef struct WOLFSSL_BASIC_CONSTRAINTS BASIC_CONSTRAINTS; +typedef struct WOLFSSL_ACCESS_DESCRIPTION ACCESS_DESCRIPTION; + #define BASIC_CONSTRAINTS_free wolfSSL_BASIC_CONSTRAINTS_free #define AUTHORITY_KEYID_free wolfSSL_AUTHORITY_KEYID_free #define SSL_CTX_get_cert_store(x) wolfSSL_CTX_get_cert_store ((x)) @@ -166,7 +204,7 @@ WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); #define X509V3_EXT_d2i wolfSSL_X509V3_EXT_d2i #define X509V3_EXT_add_nconf wolfSSL_X509V3_EXT_add_nconf #ifndef NO_WOLFSSL_STUB -#define X509V3_parse_list(...) NULL +#define X509V3_parse_list(line) NULL #endif #define i2s_ASN1_OCTET_STRING wolfSSL_i2s_ASN1_STRING #define a2i_IPADDRESS wolfSSL_a2i_IPADDRESS @@ -174,13 +212,15 @@ WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); #define X509V3_EXT_conf_nid wolfSSL_X509V3_EXT_conf_nid #define X509V3_set_ctx wolfSSL_X509V3_set_ctx #ifndef NO_WOLFSSL_STUB -#define X509V3_set_nconf(...) WC_DO_NOTHING -#define X509V3_EXT_cleanup(...) WC_DO_NOTHING +#define X509V3_set_nconf(ctx, conf) WC_DO_NOTHING +#define X509V3_EXT_cleanup() WC_DO_NOTHING #endif #define X509V3_set_ctx_test(ctx) wolfSSL_X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, CTX_TEST) #define X509V3_set_ctx_nodb wolfSSL_X509V3_set_ctx_nodb #define X509v3_get_ext_count wolfSSL_sk_num +#endif /* !OPENSSL_COEXIST */ + #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #ifdef __cplusplus diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index 4bbdf65..8b7ebed 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -39,8 +39,16 @@ #include #include +#if defined(HAVE_OCSP) || defined(HAVE_CRL) || (defined(WOLFSSL_CUSTOM_OID) && \ + defined(WOLFSSL_ASN_TEMPLATE) && defined(HAVE_OID_DECODING)) || \ + defined(WC_ASN_UNKNOWN_EXT_CB) +#include "wolfssl/wolfcrypt/asn.h" +#endif + /* For the types */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #include +#endif #ifdef HAVE_WOLF_EVENT #include @@ -76,8 +84,26 @@ #endif #endif +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) + #include + #ifndef WOLFCRYPT_ONLY + #include + #endif + #if defined(WOLFSSL_CMAC) && !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) + #include + #endif +#endif + #ifdef OPENSSL_COEXIST - /* mode to allow wolfSSL and OpenSSL to exist together */ + /* mode to allow wolfSSL and OpenSSL to coexist without symbol conflicts */ + + #ifndef NO_OLD_SSL_NAMES + #define NO_OLD_SSL_NAMES + #endif + #ifndef NO_OLD_WC_NAMES + #define NO_OLD_WC_NAMES + #endif + #ifdef TEST_OPENSSL_COEXIST /* ./configure --enable-opensslcoexist \ @@ -91,23 +117,81 @@ #include #include #include + + #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \ + FIPS_VERSION3_GE(5,2,0)) + #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 + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #if defined(HAVE_FIPS_VERSION) && FIPS_VERSION3_LT(7,0,0) + /* clear conflicting name */ + #undef RSA_PKCS1_PADDING_SIZE + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #endif /* !HAVE_SELFTEST && (!HAVE_FIPS || FIPS_VERSION3_GE(5,2,0)) */ + #endif #elif (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) - #include #include - #ifndef WOLFCRYPT_ONLY - #include - #endif - #if defined(WOLFSSL_CMAC) && !defined(NO_AES) && defined(WOLFSSL_AES_DIRECT) - #include - #endif /* We need the old SSL names */ - #ifdef NO_OLD_SSL_NAMES + #if defined(NO_OLD_SSL_NAMES) && !defined(OPENSSL_COEXIST) #undef NO_OLD_SSL_NAMES #endif - #ifdef NO_OLD_WC_NAMES + #if defined(NO_OLD_WC_NAMES) && !defined(OPENSSL_COEXIST) #undef NO_OLD_WC_NAMES #endif #endif @@ -136,14 +220,14 @@ typedef struct WOLFSSL_STACK WOLFSSL_LHASH; #define DECLARE_STACK_OF(x) WOLF_STACK_OF(x); #endif -#ifndef WOLFSSL_WOLFSSL_TYPE_DEFINED -#define WOLFSSL_WOLFSSL_TYPE_DEFINED +#ifndef WOLFSSL_TYPE_DEFINED +#define WOLFSSL_TYPE_DEFINED typedef struct WOLFSSL WOLFSSL; #endif typedef struct WOLFSSL_SESSION WOLFSSL_SESSION; typedef struct WOLFSSL_METHOD WOLFSSL_METHOD; -#ifndef WOLFSSL_WOLFSSL_CTX_TYPE_DEFINED -#define WOLFSSL_WOLFSSL_CTX_TYPE_DEFINED +#ifndef WOLFSSL_CTX_TYPE_DEFINED +#define WOLFSSL_CTX_TYPE_DEFINED typedef struct WOLFSSL_CTX WOLFSSL_CTX; #endif @@ -172,10 +256,9 @@ typedef struct WOLFSSL_BY_DIR WOLFSSL_BY_DIR; #include - -#ifndef WOLFSSL_RSA_TYPE_DEFINED /* guard on redeclaration */ -typedef struct WOLFSSL_RSA WOLFSSL_RSA; -#define WOLFSSL_RSA_TYPE_DEFINED +/* The WOLFSSL_RSA type is required in all build configurations. */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#include #endif #ifndef WC_RNG_TYPE_DEFINED /* guard on redeclaration */ @@ -213,7 +296,9 @@ typedef struct WOLFSSL_BIO_METHOD WOLFSSL_BIO_METHOD; typedef struct WOLFSSL_X509_EXTENSION WOLFSSL_X509_EXTENSION; typedef struct WOLFSSL_ASN1_OBJECT WOLFSSL_ASN1_OBJECT; typedef struct WOLFSSL_ASN1_OTHERNAME WOLFSSL_ASN1_OTHERNAME; +#ifndef OPENSSL_COEXIST typedef struct WOLFSSL_ASN1_OTHERNAME OTHERNAME; +#endif typedef struct WOLFSSL_X509V3_CTX WOLFSSL_X509V3_CTX; typedef struct WOLFSSL_v3_ext_method WOLFSSL_v3_ext_method; typedef struct WOLFSSL_OBJ_NAME WOLFSSL_OBJ_NAME; @@ -237,12 +322,75 @@ typedef struct WOLFSSL_DIST_POINT WOLFSSL_DIST_POINT; typedef struct WOLFSSL_CONF_CTX WOLFSSL_CONF_CTX; -typedef int (*WOLFSSL_X509_STORE_CTX_verify_cb)(int, WOLFSSL_X509_STORE_CTX *); typedef int (*WOLFSSL_X509_STORE_CTX_get_crl_cb)(WOLFSSL_X509_STORE_CTX *, WOLFSSL_X509_CRL **, WOLFSSL_X509 *); typedef int (*WOLFSSL_X509_STORE_CTX_check_crl_cb)(WOLFSSL_X509_STORE_CTX *, WOLFSSL_X509_CRL *); +#define WOLFSSL_V_ASN1_INTEGER 0x02 +#define WOLFSSL_V_ASN1_NEG 0x100 +#define WOLFSSL_V_ASN1_NEG_INTEGER (2 | WOLFSSL_V_ASN1_NEG) +#define WOLFSSL_V_ASN1_NEG_ENUMERATED (10 | WOLFSSL_V_ASN1_NEG) + +/* Type for ASN1_print_ex */ +#define WOLFSSL_ASN1_STRFLGS_ESC_2253 1 +#define WOLFSSL_ASN1_STRFLGS_ESC_CTRL 2 +#define WOLFSSL_ASN1_STRFLGS_ESC_MSB 4 +#define WOLFSSL_ASN1_STRFLGS_ESC_QUOTE 8 +#define WOLFSSL_ASN1_STRFLGS_UTF8_CONVERT 0x10 +#define WOLFSSL_ASN1_STRFLGS_IGNORE_TYPE 0x20 +#define WOLFSSL_ASN1_STRFLGS_SHOW_TYPE 0x40 +#define WOLFSSL_ASN1_STRFLGS_DUMP_ALL 0x80 +#define WOLFSSL_ASN1_STRFLGS_DUMP_UNKNOWN 0x100 +#define WOLFSSL_ASN1_STRFLGS_DUMP_DER 0x200 +#define WOLFSSL_ASN1_STRFLGS_RFC2253 (WOLFSSL_ASN1_STRFLGS_ESC_2253 | \ + WOLFSSL_ASN1_STRFLGS_ESC_CTRL | \ + WOLFSSL_ASN1_STRFLGS_ESC_MSB | \ + WOLFSSL_ASN1_STRFLGS_UTF8_CONVERT | \ + WOLFSSL_ASN1_STRFLGS_DUMP_UNKNOWN | \ + WOLFSSL_ASN1_STRFLGS_DUMP_DER) + +#define WOLFSSL_MBSTRING_UTF8 0x1000 +#define WOLFSSL_MBSTRING_ASC 0x1001 +#define WOLFSSL_MBSTRING_BMP 0x1002 +#define WOLFSSL_MBSTRING_UNIV 0x1004 + +#define WOLFSSL_V_ASN1_EOC 0 +#define WOLFSSL_V_ASN1_BOOLEAN 1 +#define WOLFSSL_V_ASN1_OCTET_STRING 4 +#define WOLFSSL_V_ASN1_NULL 5 +#define WOLFSSL_V_ASN1_OBJECT 6 +#define WOLFSSL_V_ASN1_UTF8STRING 12 +#define WOLFSSL_V_ASN1_SEQUENCE 16 +#define WOLFSSL_V_ASN1_SET 17 +#define WOLFSSL_V_ASN1_PRINTABLESTRING 19 +#define WOLFSSL_V_ASN1_T61STRING 20 +#define WOLFSSL_V_ASN1_IA5STRING 22 +#define WOLFSSL_V_ASN1_UTCTIME 23 +#define WOLFSSL_V_ASN1_GENERALIZEDTIME 24 +#define WOLFSSL_V_ASN1_UNIVERSALSTRING 28 +#define WOLFSSL_V_ASN1_BMPSTRING 30 + + +#define WOLFSSL_V_ASN1_CONSTRUCTED 0x20 + +#define WOLFSSL_ASN1_STRING_FLAG_BITS_LEFT 0x008 +#define WOLFSSL_ASN1_STRING_FLAG_NDEF 0x010 +#define WOLFSSL_ASN1_STRING_FLAG_CONT 0x020 +#define WOLFSSL_ASN1_STRING_FLAG_MSTRING 0x040 +#define WOLFSSL_ASN1_STRING_FLAG_EMBED 0x080 + +/* X.509 PKI size limits from RFC2459 (appendix A) */ +/* internally our limit is CTC_NAME_SIZE (64) - overridden with WC_CTC_NAME_SIZE */ +#define WOLFSSL_ub_name CTC_NAME_SIZE /* 32768 */ +#define WOLFSSL_ub_common_name CTC_NAME_SIZE /* 64 */ +#define WOLFSSL_ub_locality_name CTC_NAME_SIZE /* 128 */ +#define WOLFSSL_ub_state_name CTC_NAME_SIZE /* 128 */ +#define WOLFSSL_ub_organization_name CTC_NAME_SIZE /* 64 */ +#define WOLFSSL_ub_organization_unit_name CTC_NAME_SIZE /* 64 */ +#define WOLFSSL_ub_title CTC_NAME_SIZE /* 64 */ +#define WOLFSSL_ub_email_address CTC_NAME_SIZE /* 128 */ + #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || defined(HAVE_CURL) struct WOLFSSL_OBJ_NAME { @@ -404,7 +552,7 @@ struct WOLFSSL_EVP_PKEY { union { char* ptr; /* der format of key */ } pkey; -#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #ifndef NO_RSA WOLFSSL_RSA* rsa; #endif @@ -438,12 +586,82 @@ struct WOLFSSL_EVP_PKEY { word16 pkcs8HeaderSz; /* option bits */ - byte ownDh:1; /* if struct owns DH and should free it */ - byte ownEcc:1; /* if struct owns ECC and should free it */ - byte ownDsa:1; /* if struct owns DSA and should free it */ - byte ownRsa:1; /* if struct owns RSA and should free it */ + WC_BITFIELD ownDh:1; /* if struct owns DH and should free it */ + WC_BITFIELD ownEcc:1; /* if struct owns ECC and should free it */ + WC_BITFIELD ownDsa:1; /* if struct owns DSA and should free it */ + WC_BITFIELD ownRsa:1; /* if struct owns RSA and should free it */ +}; + + +#define WOLFSSL_ALWAYS_CHECK_SUBJECT 0x1 +#define WOLFSSL_NO_WILDCARDS 0x2 +#define WOLFSSL_NO_PARTIAL_WILDCARDS 0x4 +#define WOLFSSL_MULTI_LABEL_WILDCARDS 0x8 +/* Custom to wolfSSL, OpenSSL compat goes up to 0x20 */ +#define WOLFSSL_LEFT_MOST_WILDCARD_ONLY 0x40 + + +typedef struct WOLFSSL_BUFFER_INFO { + unsigned char* buffer; + unsigned int length; +} WOLFSSL_BUFFER_INFO; + +typedef struct WOLFSSL_BUF_MEM { + char* data; /* dereferenced */ + size_t length; /* current length */ + size_t max; /* maximum length */ +} WOLFSSL_BUF_MEM; + + +typedef int (*VerifyCallback)(int, WOLFSSL_X509_STORE_CTX*); +typedef int (*WOLFSSL_X509_STORE_CTX_verify_cb)(int, WOLFSSL_X509_STORE_CTX *); + +struct WOLFSSL_X509_STORE_CTX { +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_X509_STORE* store; /* Store full of a CA cert chain */ + WOLFSSL_X509* current_cert; /* current X509 (OPENSSL_EXTRA) */ + #if defined(WOLFSSL_ASIO) || defined(OPENSSL_EXTRA) + WOLFSSL_X509* current_issuer; /* asio dereference */ + #endif +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + WOLFSSL_X509_CHAIN* sesChain; /* pointer to WOLFSSL_SESSION peer chain */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_STACK* chain; + #ifdef OPENSSL_EXTRA + WOLFSSL_X509_VERIFY_PARAM* param; /* certificate validation parameter */ + #endif +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + + char* domain; /* subject CN domain name */ +#ifdef HAVE_EX_DATA + WOLFSSL_CRYPTO_EX_DATA ex_data; /* external data */ +#endif +#if defined(WOLFSSL_APACHE_HTTPD) || defined(OPENSSL_EXTRA) + int depth; /* used in X509_STORE_CTX_*_depth */ +#endif + void* userCtx; /* user ctx */ + int error; /* current error */ + int error_depth; /* index of cert depth for this error */ + int discardSessionCerts; /* so verify callback can flag for discard */ + int totalCerts; /* number of peer cert buffers */ + WOLFSSL_BUFFER_INFO* certs; /* peer certs */ + WOLFSSL_X509_STORE_CTX_verify_cb verify_cb; /* verify callback */ + void* heap; + int flags; + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + WOLF_STACK_OF(WOLFSSL_X509)* owned; /* Certs owned by this CTX */ + WOLF_STACK_OF(WOLFSSL_X509)* ctxIntermediates; /* Intermediates specified + * on store ctx init */ + WOLF_STACK_OF(WOLFSSL_X509)* setTrustedSk;/* A trusted stack override + * set with + * X509_STORE_CTX_trusted_stack */ +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ }; + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + struct WOLFSSL_X509_PKEY { WOLFSSL_EVP_PKEY* dec_pkey; /* dereferenced by Apache */ void* heap; @@ -460,7 +678,7 @@ struct WOLFSSL_X509_INFO { int num; }; -#define WOLFSSL_EVP_PKEY_DEFAULT EVP_PKEY_RSA /* default key type */ +#define WOLFSSL_EVP_PKEY_DEFAULT WC_EVP_PKEY_RSA /* default key type */ #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) #define wolfSSL_SSL_MODE_RELEASE_BUFFERS 0x00000010U @@ -496,7 +714,8 @@ enum BIO_FLAGS { WOLFSSL_BIO_FLAG_READ = 0x02, WOLFSSL_BIO_FLAG_WRITE = 0x04, WOLFSSL_BIO_FLAG_IO_SPECIAL = 0x08, - WOLFSSL_BIO_FLAG_RETRY = 0x10 + WOLFSSL_BIO_FLAG_RETRY = 0x10, + WOLFSSL_BIO_FLAG_MEM_RDONLY = 0x200 }; enum BIO_CB_OPS { @@ -509,12 +728,6 @@ enum BIO_CB_OPS { WOLFSSL_BIO_CB_RETURN = 0x80 }; -typedef struct WOLFSSL_BUF_MEM { - char* data; /* dereferenced */ - size_t length; /* current length */ - size_t max; /* maximum length */ -} WOLFSSL_BUF_MEM; - /* custom method with user set callbacks */ typedef int (*wolfSSL_BIO_meth_write_cb)(WOLFSSL_BIO*, const char*, int); typedef int (*wolfSSL_BIO_meth_read_cb)(WOLFSSL_BIO *, char *, int); @@ -606,13 +819,6 @@ struct WOLFSSL_X509_STORE { word32 numAdded; /* Number of objs in objs that are in certs sk */ }; -#define WOLFSSL_ALWAYS_CHECK_SUBJECT 0x1 -#define WOLFSSL_NO_WILDCARDS 0x2 -#define WOLFSSL_NO_PARTIAL_WILDCARDS 0x4 -#define WOLFSSL_MULTI_LABEL_WILDCARDS 0x8 -/* Custom to wolfSSL, OpenSSL compat goes up to 0x20 */ -#define WOLFSSL_LEFT_MOST_WILDCARD_ONLY 0x40 - #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) #define WOLFSSL_USE_CHECK_TIME 0x2 #define WOLFSSL_NO_CHECK_TIME 0x200000 @@ -640,16 +846,6 @@ struct WOLFSSL_X509_VERIFY_PARAM { }; #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -typedef struct WOLFSSL_ALERT { - int code; - int level; -} WOLFSSL_ALERT; - -typedef struct WOLFSSL_ALERT_HISTORY { - WOLFSSL_ALERT last_rx; - WOLFSSL_ALERT last_tx; -} WOLFSSL_ALERT_HISTORY; - typedef struct WOLFSSL_X509_REVOKED { WOLFSSL_ASN1_INTEGER* serialNumber; /* stunnel dereference */ } WOLFSSL_X509_REVOKED; @@ -671,46 +867,6 @@ typedef struct WOLFSSL_X509_OBJECT { #define WOLFSSL_ASN1_BOOLEAN int -typedef struct WOLFSSL_BUFFER_INFO { - unsigned char* buffer; - unsigned int length; -} WOLFSSL_BUFFER_INFO; - -struct WOLFSSL_X509_STORE_CTX { - WOLFSSL_X509_STORE* store; /* Store full of a CA cert chain */ - WOLFSSL_X509* current_cert; /* current X509 (OPENSSL_EXTRA) */ -#if defined(WOLFSSL_ASIO) || defined(OPENSSL_EXTRA) - WOLFSSL_X509* current_issuer; /* asio dereference */ -#endif - WOLFSSL_X509_CHAIN* sesChain; /* pointer to WOLFSSL_SESSION peer chain */ - WOLFSSL_STACK* chain; -#ifdef OPENSSL_EXTRA - WOLFSSL_X509_VERIFY_PARAM* param; /* certificate validation parameter */ -#endif - char* domain; /* subject CN domain name */ -#ifdef HAVE_EX_DATA - WOLFSSL_CRYPTO_EX_DATA ex_data; /* external data */ -#endif -#if defined(WOLFSSL_APACHE_HTTPD) || defined(OPENSSL_EXTRA) - int depth; /* used in X509_STORE_CTX_*_depth */ -#endif - void* userCtx; /* user ctx */ - int error; /* current error */ - int error_depth; /* index of cert depth for this error */ - int discardSessionCerts; /* so verify callback can flag for discard */ - int totalCerts; /* number of peer cert buffers */ - WOLFSSL_BUFFER_INFO* certs; /* peer certs */ - WOLFSSL_X509_STORE_CTX_verify_cb verify_cb; /* verify callback */ - void* heap; - int flags; - WOLF_STACK_OF(WOLFSSL_X509)* owned; /* Certs owned by this CTX */ - WOLF_STACK_OF(WOLFSSL_X509)* ctxIntermediates; /* Intermediates specified - * on store ctx init */ - WOLF_STACK_OF(WOLFSSL_X509)* setTrustedSk;/* A trusted stack override - * set with - * X509_STORE_CTX_trusted_stack*/ -}; - typedef char* WOLFSSL_STRING; typedef struct WOLFSSL_RAND_METHOD { @@ -732,6 +888,20 @@ typedef struct WOLFSSL_RAND_METHOD { int (*status)(void); } WOLFSSL_RAND_METHOD; +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + + +typedef struct WOLFSSL_ALERT { + int code; + int level; +} WOLFSSL_ALERT; + +typedef struct WOLFSSL_ALERT_HISTORY { + WOLFSSL_ALERT last_rx; + WOLFSSL_ALERT last_tx; +} WOLFSSL_ALERT_HISTORY; + + /* Valid Alert types from page 16/17 * Add alert string to the function wolfSSL_alert_type_string_long in src/ssl.c */ @@ -789,7 +959,7 @@ enum AlertLevel { enum SNICbReturn { warning_return = alert_warning, fatal_return = alert_fatal, - noack_return, + noack_return }; /* WS_RETURN_CODE macro @@ -1189,6 +1359,7 @@ WOLFSSL_API const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len); WOLFSSL_API const char* wolfSSL_get_curve_name(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_get_fd(const WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_get_wfd(const WOLFSSL* ssl); /* please see note at top of README if you get an error from connect */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_connect(WOLFSSL* ssl); WOLFSSL_ABI WOLFSSL_API int wolfSSL_write( @@ -1196,6 +1367,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfSSL_write( WOLFSSL_ABI WOLFSSL_API int wolfSSL_read(WOLFSSL* ssl, void* data, int sz); WOLFSSL_API int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz); WOLFSSL_ABI WOLFSSL_API int wolfSSL_accept(WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz); WOLFSSL_API int wolfSSL_CTX_mutual_auth(WOLFSSL_CTX* ctx, int req); WOLFSSL_API int wolfSSL_mutual_auth(WOLFSSL* ssl, int req); @@ -1266,7 +1438,6 @@ WOLFSSL_API void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode); WOLFSSL_API void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode); WOLFSSL_ABI WOLFSSL_API int wolfSSL_get_error(WOLFSSL* ssl, int ret); -WOLFSSL_API int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h); WOLFSSL_ABI WOLFSSL_API int wolfSSL_set_session(WOLFSSL* ssl, WOLFSSL_SESSION* session); WOLFSSL_API long wolfSSL_SSL_SESSION_set_timeout(WOLFSSL_SESSION* ses, long t); @@ -1308,15 +1479,38 @@ WOLFSSL_API int wolfSSL_GetSessionIndex(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_GetSessionAtIndex(int index, WOLFSSL_SESSION* session); #endif /* SESSION_INDEX */ -#if defined(SESSION_CERTS) -WOLFSSL_API - WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session); -WOLFSSL_API WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session); -#endif /* SESSION_INDEX && SESSION_CERTS */ -typedef int (*VerifyCallback)(int, WOLFSSL_X509_STORE_CTX*); -typedef void (CallbackInfoState)(const WOLFSSL* ssl, int, int); +#ifdef OPENSSL_EXTRA +/* compatibility callback for TLS state */ +typedef void (CallbackInfoState)(const WOLFSSL* ssl, int state, int err); +#endif + + +/* ----- EX DATA BEGIN ----- */ +WOLFSSL_API void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx); +WOLFSSL_API int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data); + +#ifdef HAVE_EX_DATA +WOLFSSL_API void wolfSSL_CRYPTO_cleanup_all_ex_data(void); +WOLFSSL_API void* wolfSSL_CRYPTO_get_ex_data( + const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx); +WOLFSSL_API int wolfSSL_CRYPTO_set_ex_data( + WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, void *data); + +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +WOLFSSL_API int wolfSSL_CRYPTO_set_ex_data_with_cleanup( + WOLFSSL_CRYPTO_EX_DATA* ex_data, + int idx, + void *data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine); +WOLFSSL_API int wolfSSL_set_ex_data_with_cleanup( + WOLFSSL* ssl, + int idx, + void* data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine); +#endif +#ifdef HAVE_EX_DATA_CRYPTO /* class index for wolfSSL_CRYPTO_get_ex_new_index */ #define WOLF_CRYPTO_EX_INDEX_SSL 0 #define WOLF_CRYPTO_EX_INDEX_SSL_CTX 1 @@ -1336,8 +1530,6 @@ typedef void (CallbackInfoState)(const WOLFSSL* ssl, int, int); #define WOLF_CRYPTO_EX_INDEX_DRBG 15 #define WOLF_CRYPTO_EX_INDEX__COUNT 16 -#ifdef HAVE_EX_DATA - /* Helper macro to log that input arguments should not be used */ #define WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(a1, a2, a3, a4, a5) \ (void)(a1); \ @@ -1352,12 +1544,60 @@ typedef void (CallbackInfoState)(const WOLFSSL* ssl, int, int); } \ } while(0) -WOLFSSL_API int wolfSSL_get_ex_new_index(long argValue, void* arg, - WOLFSSL_CRYPTO_EX_new* a, WOLFSSL_CRYPTO_EX_dup* b, - WOLFSSL_CRYPTO_EX_free* c); +WOLFSSL_API int wolfSSL_get_ex_new_index( + long argValue, void* arg, + WOLFSSL_CRYPTO_EX_new* a, WOLFSSL_CRYPTO_EX_dup* b, + WOLFSSL_CRYPTO_EX_free* c); +WOLFSSL_API int wolfSSL_CTX_get_ex_new_index( + long idx, void* arg, + WOLFSSL_CRYPTO_EX_new* new_func, + WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func); +WOLFSSL_API int wolfSSL_CRYPTO_get_ex_new_index( + int class_index, long argl, void *argp, + WOLFSSL_CRYPTO_EX_new* new_func, + WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func); +WOLFSSL_API int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, + WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func); +#endif /* HAVE_EX_DATA_CRYPTO */ +#endif /* HAVE_EX_DATA */ +/* Exposed EX data API's, guarded internally by HAVE_EX_DATA */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +WOLFSSL_API void *wolfSSL_X509_get_ex_data(WOLFSSL_X509 *x509, int idx); +WOLFSSL_API int wolfSSL_X509_set_ex_data(WOLFSSL_X509 *x509, int idx, + void *data); +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +WOLFSSL_API int wolfSSL_X509_set_ex_data_with_cleanup( + WOLFSSL_X509 *x509, + int idx, + void *data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine); #endif +#ifdef HAVE_EX_DATA_CRYPTO +WOLFSSL_API int wolfSSL_X509_get_ex_new_index(int idx, void *arg, + WOLFSSL_CRYPTO_EX_new* new_func, + WOLFSSL_CRYPTO_EX_dup* dup_func, + WOLFSSL_CRYPTO_EX_free* free_func); +#endif +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#ifdef OPENSSL_EXTRA +WOLFSSL_API void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx); +WOLFSSL_API int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data); +#ifdef HAVE_EX_DATA_CLEANUP_HOOKS +WOLFSSL_API int wolfSSL_CTX_set_ex_data_with_cleanup( + WOLFSSL_CTX* ctx, + int idx, + void* data, + wolfSSL_ex_data_cleanup_routine_t cleanup_routine); +#endif +#endif /* OPENSSL_EXTRA */ +/* ----- EX DATA END ----- */ + WOLFSSL_ABI WOLFSSL_API void wolfSSL_CTX_set_verify(WOLFSSL_CTX* ctx, int mode, VerifyCallback verify_callback); @@ -1495,8 +1735,16 @@ WOLFSSL_API int wolfSSL_dtls(WOLFSSL* ssl); WOLFSSL_API void* wolfSSL_dtls_create_peer(int port, char* ip); WOLFSSL_API int wolfSSL_dtls_free_peer(void* addr); -WOLFSSL_API int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, unsigned int peerSz); -WOLFSSL_API int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, unsigned int* peerSz); +WOLFSSL_API int wolfSSL_dtls_set_peer(WOLFSSL* ssl, void* peer, + unsigned int peerSz); +WOLFSSL_API int wolfSSL_dtls_set_pending_peer(WOLFSSL* ssl, void* peer, + unsigned int peerSz); +WOLFSSL_API int wolfSSL_dtls_get_peer(WOLFSSL* ssl, void* peer, + unsigned int* peerSz); +WOLFSSL_API int wolfSSL_dtls_get0_peer(WOLFSSL* ssl, const void** peer, + unsigned int* peerSz); + +WOLFSSL_API byte wolfSSL_is_stateful(WOLFSSL* ssl); #if defined(WOLFSSL_SCTP) && defined(WOLFSSL_DTLS) WOLFSSL_API int wolfSSL_CTX_dtls_set_sctp(WOLFSSL_CTX* ctx); @@ -1576,7 +1824,9 @@ WOLFSSL_API const char* wolfSSL_ERR_reason_error_string(unsigned long e); WOLFSSL_API const char* wolfSSL_ERR_func_error_string(unsigned long e); WOLFSSL_API const char* wolfSSL_ERR_lib_error_string(unsigned long e); -/* extras */ +/* -------- EXTRAS BEGIN -------- */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +WOLFSSL_API void wolfSSL_ERR_print_errors(WOLFSSL_BIO *bio); WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_new_node(void* heap); WOLFSSL_API void wolfSSL_sk_free(WOLFSSL_STACK* sk); @@ -1588,16 +1838,11 @@ WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx); WOLFSSL_API int wolfSSL_sk_push(WOLFSSL_STACK *st, const void *data); WOLFSSL_API int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx); -#if defined(HAVE_OCSP) || defined(HAVE_CRL) || (defined(WOLFSSL_CUSTOM_OID) && \ - defined(WOLFSSL_ASN_TEMPLATE) && defined(HAVE_OID_DECODING)) -#include "wolfssl/wolfcrypt/asn.h" -#endif - #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) WOLFSSL_API int wolfSSL_sk_ACCESS_DESCRIPTION_push( WOLF_STACK_OF(ACCESS_DESCRIPTION)* sk, WOLFSSL_ACCESS_DESCRIPTION* a); -#endif /* defined(OPENSSL_ALL) || OPENSSL_EXTRA || defined(WOLFSSL_QT) */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA || WOLFSSL_QT */ typedef WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) WOLFSSL_GENERAL_NAMES; typedef WOLF_STACK_OF(WOLFSSL_DIST_POINT) WOLFSSL_DIST_POINTS; @@ -1692,61 +1937,7 @@ WOLFSSL_API int wolfSSL_ASN1_UNIVERSALSTRING_to_string(WOLFSSL_ASN1_STRING *s); WOLFSSL_API int wolfSSL_sk_X509_EXTENSION_num(WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_sk_X509_EXTENSION_value( const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int idx); -WOLFSSL_API int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data); -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -WOLFSSL_API int wolfSSL_set_ex_data_with_cleanup( - WOLFSSL* ssl, - int idx, - void* data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine); -#endif -WOLFSSL_API int wolfSSL_get_shutdown(const WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd); -WOLFSSL_API int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd); -WOLFSSL_API void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt); -WOLFSSL_API int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id, - unsigned int len); -WOLFSSL_API void wolfSSL_set_connect_state(WOLFSSL* ssl); -WOLFSSL_API void wolfSSL_set_accept_state(WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_session_reused(WOLFSSL* ssl); -#ifdef OPENSSL_EXTRA -/* using unsigned char instead of uint8_t here to avoid stdint include */ -WOLFSSL_API unsigned char wolfSSL_SESSION_get_max_fragment_length( - WOLFSSL_SESSION* session); -#endif -WOLFSSL_API int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session); -WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session); -WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_new(void); -WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap); -WOLFSSL_API void wolfSSL_SESSION_free(WOLFSSL_SESSION* session); -WOLFSSL_API int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, - WOLFSSL_SESSION* session); -WOLFSSL_API int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session, - const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_is_init_finished(const WOLFSSL* ssl); -WOLFSSL_API const char* wolfSSL_get_version(const WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl); -WOLFSSL_API WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl); -WOLFSSL_API char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, int len); -WOLFSSL_API const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API const char* wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher); -WOLFSSL_API const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value); -WOLFSSL_API const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session); -WOLFSSL_API const char* wolfSSL_get_cipher(WOLFSSL* ssl); -WOLFSSL_API void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk); -WOLFSSL_API WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl); -WOLFSSL_API int wolfSSL_SessionIsSetup(WOLFSSL_SESSION* session); - -WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new(void); -WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new_ex(void* heap); -WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_dup(WOLFSSL_X509* x); #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) WOLFSSL_API int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa); WOLFSSL_API int wolfSSL_X509_up_ref(WOLFSSL_X509* x509); @@ -1972,22 +2163,15 @@ WOLFSSL_API void wolfSSL_X509_get0_signature(const WOLFSSL_ASN1_BIT_STRING **psi const WOLFSSL_X509_ALGOR **palg, const WOLFSSL_X509 *x509); WOLFSSL_API int wolfSSL_X509_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_X509_REQ_print(WOLFSSL_BIO* bio, WOLFSSL_X509* x509); -WOLFSSL_ABI WOLFSSL_API char* wolfSSL_X509_NAME_oneline(WOLFSSL_X509_NAME* name, - char* in, int sz); WOLFSSL_API unsigned long wolfSSL_X509_NAME_hash(WOLFSSL_X509_NAME* name); #if defined(OPENSSL_EXTRA) && defined(XSNPRINTF) WOLFSSL_API char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz); #endif -WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_get_issuer_name( - WOLFSSL_X509* cert); WOLFSSL_API unsigned long wolfSSL_X509_issuer_name_hash(const WOLFSSL_X509* x509); -WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_get_subject_name( - WOLFSSL_X509* cert); WOLFSSL_API unsigned long wolfSSL_X509_subject_name_hash(const WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_X509_ext_isSet_by_NID(WOLFSSL_X509* x509, int nid); WOLFSSL_API int wolfSSL_X509_ext_get_critical_by_NID(WOLFSSL_X509* x509, int nid); WOLFSSL_API int wolfSSL_X509_EXTENSION_set_critical(WOLFSSL_X509_EXTENSION* ex, int crit); -WOLFSSL_API int wolfSSL_X509_get_isCA(WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_X509_get_isSet_pathLength(WOLFSSL_X509* x509); WOLFSSL_API unsigned int wolfSSL_X509_get_pathLength(WOLFSSL_X509* x509); WOLFSSL_API unsigned int wolfSSL_X509_get_keyUsage(WOLFSSL_X509* x509); @@ -2050,11 +2234,6 @@ WOLFSSL_API int wolfSSL_ASN1_STRING_copy(WOLFSSL_ASN1_STRING* dst, const WOLFSSL_ASN1_STRING* src); WOLFSSL_API int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx); WOLFSSL_API const char* wolfSSL_X509_verify_cert_error_string(long err); -WOLFSSL_API int wolfSSL_X509_get_signature_type(WOLFSSL_X509* x509); -WOLFSSL_API int wolfSSL_X509_get_signature(WOLFSSL_X509* x509, unsigned char* buf, int* bufSz); -WOLFSSL_API int wolfSSL_X509_get_pubkey_buffer(WOLFSSL_X509* x509, unsigned char* buf, - int* bufSz); -WOLFSSL_API int wolfSSL_X509_get_pubkey_type(WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_X509_LOOKUP_add_dir(WOLFSSL_X509_LOOKUP* lookup,const char* dir,long type); WOLFSSL_API int wolfSSL_X509_LOOKUP_load_file(WOLFSSL_X509_LOOKUP* lookup, const char* file, @@ -2088,11 +2267,8 @@ WOLFSSL_API int wolfSSL_X509_STORE_get_by_subject(WOLFSSL_X509_STORE_CT int idx, WOLFSSL_X509_NAME* name, WOLFSSL_X509_OBJECT* obj); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_CTX_get0_param( WOLFSSL_X509_STORE_CTX *ctx); -WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void); -WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new_ex(void* heap); WOLFSSL_API int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509, WOLF_STACK_OF(WOLFSSL_X509)*); -WOLFSSL_API void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx); WOLFSSL_API void wolfSSL_X509_STORE_CTX_cleanup(WOLFSSL_X509_STORE_CTX* ctx); WOLFSSL_API void wolfSSL_X509_STORE_CTX_trusted_stack(WOLFSSL_X509_STORE_CTX *ctx, WOLF_STACK_OF(WOLFSSL_X509) *sk); @@ -2237,10 +2413,10 @@ WOLFSSL_API int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl, const byte** suites, word16* suiteSz, const byte** hashSigAlgo, word16* hashSigAlgoSz); typedef struct WOLFSSL_CIPHERSUITE_INFO { - byte rsaAuth:1; - byte eccAuth:1; - byte eccStatic:1; - byte psk:1; + WC_BITFIELD rsaAuth:1; + WC_BITFIELD eccAuth:1; + WC_BITFIELD eccStatic:1; + WC_BITFIELD psk:1; } WOLFSSL_CIPHERSUITE_INFO; WOLFSSL_API WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first, byte second); @@ -2283,14 +2459,6 @@ WOLFSSL_API void wolfSSL_X509_STORE_CTX_set_error( WOLFSSL_X509_STORE_CTX* ctx, int er); void wolfSSL_X509_STORE_CTX_set_error_depth(WOLFSSL_X509_STORE_CTX* ctx, int depth); -WOLFSSL_API void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx); - -WOLFSSL_API void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx, - void* userdata); -WOLFSSL_API void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, - wc_pem_password_cb* cb); -WOLFSSL_API wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX* ctx); -WOLFSSL_API void *wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx); WOLFSSL_API void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx, void (*f)(const WOLFSSL* ssl, int type, int val)); @@ -2349,13 +2517,7 @@ WOLFSSL_API int wolfSSL_CTX_set_srp_strength(WOLFSSL_CTX *ctx, int strength); WOLFSSL_API char* wolfSSL_get_srp_username(WOLFSSL *ssl); -WOLFSSL_API long wolfSSL_set_options(WOLFSSL *s, long op); -WOLFSSL_API long wolfSSL_get_options(const WOLFSSL *s); WOLFSSL_API long wolfSSL_clear_options(WOLFSSL *s, long op); -WOLFSSL_API long wolfSSL_clear_num_renegotiations(WOLFSSL *s); -WOLFSSL_API long wolfSSL_total_renegotiations(WOLFSSL *s); -WOLFSSL_API long wolfSSL_num_renegotiations(WOLFSSL* s); -WOLFSSL_API int wolfSSL_SSL_renegotiate_pending(WOLFSSL *s); WOLFSSL_API long wolfSSL_set_tmp_dh(WOLFSSL *s, WOLFSSL_DH *dh); WOLFSSL_API long wolfSSL_set_tlsext_debug_arg(WOLFSSL *s, void *arg); WOLFSSL_API long wolfSSL_set_tlsext_status_type(WOLFSSL *s, int type); @@ -2374,6 +2536,186 @@ WOLFSSL_API char* wolfSSL_CONF_get1_default_config_file(void); WOLFSSL_API long wolfSSL_get_tlsext_status_exts(WOLFSSL *s, void *arg); WOLFSSL_API long wolfSSL_get_verify_result(const WOLFSSL *ssl); +WOLFSSL_API void* wolfSSL_get_app_data( const WOLFSSL *ssl); +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) + + /* Errors used in wolfSSL. utilize the values from the defines in + * wolfssl/openssl/x509.h, but without the WOLFSSL_ prefix. + */ +enum { + WOLFSSL_X509_V_OK = 0, + WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, + WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID = 9, + WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED = 10, + WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, + WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, + WOLFSSL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, + WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, + WOLFSSL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, + WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, + WOLFSSL_X509_V_ERR_CERT_REVOKED = 23, + WOLFSSL_X509_V_ERR_INVALID_CA = 24, + WOLFSSL_X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, + WOLFSSL_X509_V_ERR_CERT_REJECTED = 28, + WOLFSSL_X509_V_ERR_SUBJECT_ISSUER_MISMATCH = 29, + +#ifdef HAVE_OCSP + /* OCSP Flags */ + WOLFSSL_OCSP_NOCERTS = 1, + WOLFSSL_OCSP_NOINTERN = 2, + WOLFSSL_OCSP_NOSIGS = 4, + WOLFSSL_OCSP_NOCHAIN = 8, + WOLFSSL_OCSP_NOVERIFY = 16, + WOLFSSL_OCSP_NOEXPLICIT = 32, + WOLFSSL_OCSP_NOCASIGN = 64, + WOLFSSL_OCSP_NODELEGATED = 128, + WOLFSSL_OCSP_NOCHECKS = 256, + WOLFSSL_OCSP_TRUSTOTHER = 512, + WOLFSSL_OCSP_RESPID_KEY = 1024, + WOLFSSL_OCSP_NOTIME = 2048, +#endif + + WOLFSSL_ST_CONNECT = 0x1000, + WOLFSSL_ST_ACCEPT = 0x2000, + WOLFSSL_ST_MASK = 0x0FFF, + + WOLFSSL_CB_LOOP = 0x01, + WOLFSSL_CB_EXIT = 0x02, + WOLFSSL_CB_READ = 0x04, + WOLFSSL_CB_WRITE = 0x08, + WOLFSSL_CB_HANDSHAKE_START = 0x10, + WOLFSSL_CB_HANDSHAKE_DONE = 0x20, + WOLFSSL_CB_ALERT = 0x4000, + WOLFSSL_CB_READ_ALERT = (WOLFSSL_CB_ALERT | WOLFSSL_CB_READ), + WOLFSSL_CB_WRITE_ALERT = (WOLFSSL_CB_ALERT | WOLFSSL_CB_WRITE), + WOLFSSL_CB_ACCEPT_LOOP = (WOLFSSL_ST_ACCEPT | WOLFSSL_CB_LOOP), + WOLFSSL_CB_ACCEPT_EXIT = (WOLFSSL_ST_ACCEPT | WOLFSSL_CB_EXIT), + WOLFSSL_CB_CONNECT_LOOP = (WOLFSSL_ST_CONNECT | WOLFSSL_CB_LOOP), + WOLFSSL_CB_CONNECT_EXIT = (WOLFSSL_ST_CONNECT | WOLFSSL_CB_EXIT), + WOLFSSL_CB_MODE_READ = 1, + WOLFSSL_CB_MODE_WRITE = 2, + + WOLFSSL_MODE_ENABLE_PARTIAL_WRITE = 2, + WOLFSSL_MODE_AUTO_RETRY = 3, /* wolfSSL default is to return WANT_{READ|WRITE} + * to the user. This is set by default with + * OPENWOLFSSL_COMPATIBLE_DEFAULTS. The macro + * WOLFWOLFSSL_MODE_AUTO_RETRY_ATTEMPTS is used to + * limit the possibility of an infinite retry loop + */ + WOLFSSL_MODE_RELEASE_BUFFERS = -1, /* For libwebsockets build. No current use. */ + + WOLFSSL_CRYPTO_LOCK = 1, + WOLFSSL_CRYPTO_NUM_LOCKS = 10 +}; + +#define WOLFSSL_NOTHING 1 +#define WOLFSSL_WRITING 2 +#define WOLFSSL_READING 3 +#define WOLFSSL_MAX_SSL_SESSION_ID_LENGTH 32 /* = ID_LEN */ + +#ifndef OPENSSL_COEXIST + +/* for compatibility these must be macros */ + +#define SSL_OP_MICROSOFT_SESS_ID_BUG WOLFSSL_OP_MICROSOFT_SESS_ID_BUG +#define SSL_OP_NETSCAPE_CHALLENGE_BUG WOLFSSL_OP_NETSCAPE_CHALLENGE_BUG +#define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG WOLFSSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG +#define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG WOLFSSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG +#define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER WOLFSSL_OP_MICROSOFT_BIG_SSLV3_BUFFER +#define SSL_OP_MSIE_SSLV2_RSA_PADDING WOLFSSL_OP_MSIE_SSLV2_RSA_PADDING +#define SSL_OP_SSLEAY_080_CLIENT_DH_BUG WOLFSSL_OP_SSLEAY_080_CLIENT_DH_BUG +#define SSL_OP_TLS_D5_BUG WOLFSSL_OP_TLS_D5_BUG +#define SSL_OP_TLS_BLOCK_PADDING_BUG WOLFSSL_OP_TLS_BLOCK_PADDING_BUG +#define SSL_OP_TLS_ROLLBACK_BUG WOLFSSL_OP_TLS_ROLLBACK_BUG +#define SSL_OP_EPHEMERAL_RSA WOLFSSL_OP_EPHEMERAL_RSA +#define SSL_OP_PKCS1_CHECK_1 WOLFSSL_OP_PKCS1_CHECK_1 +#define SSL_OP_PKCS1_CHECK_2 WOLFSSL_OP_PKCS1_CHECK_2 +#define SSL_OP_NETSCAPE_CA_DN_BUG WOLFSSL_OP_NETSCAPE_CA_DN_BUG +#define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG WOLFSSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG +#define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS WOLFSSL_OP_DONT_INSERT_EMPTY_FRAGMENTS +#define SSL_OP_NO_QUERY_MTU WOLFSSL_OP_NO_QUERY_MTU +#define SSL_OP_COOKIE_EXCHANGE WOLFSSL_OP_COOKIE_EXCHANGE +#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION \ + WOLFSSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION +#define SSL_OP_ALL WOLFSSL_OP_ALL + +#define SSL_OP_NO_SSLv2 WOLFSSL_OP_NO_SSLv2 +#define SSL_OP_NO_SSLv3 WOLFSSL_OP_NO_SSLv3 +#define SSL_OP_NO_TLSv1 WOLFSSL_OP_NO_TLSv1 +#define SSL_OP_NO_TLSv1_1 WOLFSSL_OP_NO_TLSv1_1 +#define SSL_OP_NO_TLSv1_2 WOLFSSL_OP_NO_TLSv1_2 +#define SSL_OP_NO_COMPRESSION WOLFSSL_OP_NO_COMPRESSION + +/* apache uses SSL_OP_NO_TLSv1_3 to determine if TLS 1.3 is enabled */ +#if !(!defined(WOLFSSL_TLS13) && defined(WOLFSSL_APACHE_HTTPD)) +#define SSL_OP_NO_TLSv1_3 WOLFSSL_OP_NO_TLSv1_3 +#endif + +#ifdef HAVE_SESSION_TICKET +#define SSL_OP_NO_TICKET WOLFSSL_OP_NO_TICKET +#endif + +#define SSL_OP_NO_SSL_MASK (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | \ + SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3) + + +#define SSL_NOTHING WOLFSSL_NOTHING +#define SSL_WRITING WOLFSSL_WRITING +#define SSL_READING WOLFSSL_READING +#define SSL_MAX_SSL_SESSION_ID_LENGTH WOLFSSL_MAX_SSL_SESSION_ID_LENGTH + +#ifdef HAVE_OCSP + /* OCSP Flags */ +#define OCSP_NOCERTS WOLFSSL_OCSP_NOCERTS +#define OCSP_NOINTERN WOLFSSL_OCSP_NOINTERN +#define OCSP_NOSIGS WOLFSSL_OCSP_NOSIGS +#define OCSP_NOCHAIN WOLFSSL_OCSP_NOCHAIN +#define OCSP_NOVERIFY WOLFSSL_OCSP_NOVERIFY +#define OCSP_NOEXPLICIT WOLFSSL_OCSP_NOEXPLICIT +#define OCSP_NOCASIGN WOLFSSL_OCSP_NOCASIGN +#define OCSP_NODELEGATED WOLFSSL_OCSP_NODELEGATED +#define OCSP_NOCHECKS WOLFSSL_OCSP_NOCHECKS +#define OCSP_TRUSTOTHER WOLFSSL_OCSP_TRUSTOTHER +#define OCSP_RESPID_KEY WOLFSSL_OCSP_RESPID_KEY +#define OCSP_NOTIME WOLFSSL_OCSP_NOTIME +#endif + +#define SSL_ST_CONNECT WOLFSSL_ST_CONNECT +#define SSL_ST_ACCEPT WOLFSSL_ST_ACCEPT +#define SSL_ST_MASK WOLFSSL_ST_MASK + +#define SSL_CB_LOOP WOLFSSL_CB_LOOP +#define SSL_CB_EXIT WOLFSSL_CB_EXIT +#define SSL_CB_READ WOLFSSL_CB_READ +#define SSL_CB_WRITE WOLFSSL_CB_WRITE +#define SSL_CB_HANDSHAKE_START WOLFSSL_CB_HANDSHAKE_START +#define SSL_CB_HANDSHAKE_DONE WOLFSSL_CB_HANDSHAKE_DONE +#define SSL_CB_ALERT WOLFSSL_CB_ALERT +#define SSL_CB_READ_ALERT WOLFSSL_CB_READ_ALERT +#define SSL_CB_WRITE_ALERT WOLFSSL_CB_WRITE_ALERT +#define SSL_CB_ACCEPT_LOOP WOLFSSL_CB_ACCEPT_LOOP +#define SSL_CB_ACCEPT_EXIT WOLFSSL_CB_ACCEPT_EXIT +#define SSL_CB_CONNECT_LOOP WOLFSSL_CB_CONNECT_LOOP +#define SSL_CB_CONNECT_EXIT WOLFSSL_CB_CONNECT_EXIT +#define SSL_CB_MODE_READ WOLFSSL_CB_MODE_READ +#define SSL_CB_MODE_WRITE WOLFSSL_CB_MODE_WRITE + +#define SSL_MODE_ENABLE_PARTIAL_WRITE WOLFSSL_MODE_ENABLE_PARTIAL_WRITE +#define SSL_MODE_AUTO_RETRY WOLFSSL_MODE_AUTO_RETRY +#define SSL_MODE_RELEASE_BUFFERS WOLFSSL_MODE_RELEASE_BUFFERS + +#define CRYPTO_LOCK WOLFSSL_CRYPTO_LOCK +#define CRYPTO_NUM_LOCKS WOLFSSL_CRYPTO_NUM_LOCKS + +#endif /* !OPENSSL_COEXIST */ + +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || HAVE_WEBSERVER || HAVE_MEMCACHED */ +/* -------- EXTRAS END -------- */ + + #define WOLFSSL_DEFAULT_CIPHER_LIST "" /* default all */ /* These are bit-masks */ @@ -2383,7 +2725,7 @@ enum { WOLFSSL_OCSP_CHECKALL = 4, WOLFSSL_CRL_CHECKALL = 1, - WOLFSSL_CRL_CHECK = 2, + WOLFSSL_CRL_CHECK = 2 }; /* Separated out from other enums because of size */ @@ -2430,132 +2772,75 @@ enum { | WOLFSSL_OP_TLS_D5_BUG | WOLFSSL_OP_TLS_BLOCK_PADDING_BUG | WOLFSSL_OP_DONT_INSERT_EMPTY_FRAGMENTS - | WOLFSSL_OP_TLS_ROLLBACK_BUG), + | WOLFSSL_OP_TLS_ROLLBACK_BUG) }; -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED) -/* for compatibility these must be macros */ - -#define SSL_OP_MICROSOFT_SESS_ID_BUG WOLFSSL_OP_MICROSOFT_SESS_ID_BUG -#define SSL_OP_NETSCAPE_CHALLENGE_BUG WOLFSSL_OP_NETSCAPE_CHALLENGE_BUG -#define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG WOLFSSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG -#define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG WOLFSSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG -#define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER WOLFSSL_OP_MICROSOFT_BIG_SSLV3_BUFFER -#define SSL_OP_MSIE_SSLV2_RSA_PADDING WOLFSSL_OP_MSIE_SSLV2_RSA_PADDING -#define SSL_OP_SSLEAY_080_CLIENT_DH_BUG WOLFSSL_OP_SSLEAY_080_CLIENT_DH_BUG -#define SSL_OP_TLS_D5_BUG WOLFSSL_OP_TLS_D5_BUG -#define SSL_OP_TLS_BLOCK_PADDING_BUG WOLFSSL_OP_TLS_BLOCK_PADDING_BUG -#define SSL_OP_TLS_ROLLBACK_BUG WOLFSSL_OP_TLS_ROLLBACK_BUG -#define SSL_OP_EPHEMERAL_RSA WOLFSSL_OP_EPHEMERAL_RSA -#define SSL_OP_PKCS1_CHECK_1 WOLFSSL_OP_PKCS1_CHECK_1 -#define SSL_OP_PKCS1_CHECK_2 WOLFSSL_OP_PKCS1_CHECK_2 -#define SSL_OP_NETSCAPE_CA_DN_BUG WOLFSSL_OP_NETSCAPE_CA_DN_BUG -#define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG WOLFSSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG -#define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS WOLFSSL_OP_DONT_INSERT_EMPTY_FRAGMENTS -#define SSL_OP_NO_QUERY_MTU WOLFSSL_OP_NO_QUERY_MTU -#define SSL_OP_COOKIE_EXCHANGE WOLFSSL_OP_COOKIE_EXCHANGE -#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION \ - WOLFSSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION -#define SSL_OP_ALL WOLFSSL_OP_ALL - -#define SSL_OP_NO_SSLv2 WOLFSSL_OP_NO_SSLv2 -#define SSL_OP_NO_SSLv3 WOLFSSL_OP_NO_SSLv3 -#define SSL_OP_NO_TLSv1 WOLFSSL_OP_NO_TLSv1 -#define SSL_OP_NO_TLSv1_1 WOLFSSL_OP_NO_TLSv1_1 -#define SSL_OP_NO_TLSv1_2 WOLFSSL_OP_NO_TLSv1_2 -#define SSL_OP_NO_COMPRESSION WOLFSSL_OP_NO_COMPRESSION - -/* apache uses SSL_OP_NO_TLSv1_3 to determine if TLS 1.3 is enabled */ -#if !(!defined(WOLFSSL_TLS13) && defined(WOLFSSL_APACHE_HTTPD)) -#define SSL_OP_NO_TLSv1_3 WOLFSSL_OP_NO_TLSv1_3 -#endif +WOLFSSL_API void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx, + void* userdata); +WOLFSSL_API void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, + wc_pem_password_cb* cb); +WOLFSSL_API wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX* ctx); +WOLFSSL_API void *wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx); -#ifdef HAVE_SESSION_TICKET -#define SSL_OP_NO_TICKET WOLFSSL_OP_NO_TICKET +WOLFSSL_API int wolfSSL_SSL_renegotiate_pending(WOLFSSL *s); +WOLFSSL_API long wolfSSL_total_renegotiations(WOLFSSL *s); +WOLFSSL_API long wolfSSL_num_renegotiations(WOLFSSL* s); +WOLFSSL_API long wolfSSL_clear_num_renegotiations(WOLFSSL *s); +WOLFSSL_API int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h); +WOLFSSL_API int wolfSSL_get_shutdown(const WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd); +WOLFSSL_API int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd); +WOLFSSL_API void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt); +WOLFSSL_API int wolfSSL_set_session_id_context(WOLFSSL* ssl, const unsigned char* id, + unsigned int len); +WOLFSSL_API void wolfSSL_set_connect_state(WOLFSSL* ssl); +WOLFSSL_API void wolfSSL_set_accept_state(WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_session_reused(WOLFSSL* ssl); +#ifdef OPENSSL_EXTRA +/* using unsigned char instead of uint8_t here to avoid stdint include */ +WOLFSSL_API unsigned char wolfSSL_SESSION_get_max_fragment_length( + WOLFSSL_SESSION* session); #endif +WOLFSSL_API int wolfSSL_SESSION_up_ref(WOLFSSL_SESSION* session); -#define SSL_OP_NO_SSL_MASK (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | \ - SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3) - - -#define SSL_NOTHING 1 -#define SSL_WRITING 2 -#define SSL_READING 3 -#define SSL_MAX_SSL_SESSION_ID_LENGTH 32 /* = ID_LEN */ +WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_dup(WOLFSSL_SESSION* session); +WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_new(void); +WOLFSSL_API WOLFSSL_SESSION* wolfSSL_SESSION_new_ex(void* heap); +WOLFSSL_API void wolfSSL_SESSION_free(WOLFSSL_SESSION* session); +WOLFSSL_API int wolfSSL_CTX_add_session(WOLFSSL_CTX* ctx, + WOLFSSL_SESSION* session); +WOLFSSL_API int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session, + const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_is_init_finished(const WOLFSSL* ssl); -enum { -#ifdef HAVE_OCSP - /* OCSP Flags */ - OCSP_NOCERTS = 1, - OCSP_NOINTERN = 2, - OCSP_NOSIGS = 4, - OCSP_NOCHAIN = 8, - OCSP_NOVERIFY = 16, - OCSP_NOEXPLICIT = 32, - OCSP_NOCASIGN = 64, - OCSP_NODELEGATED = 128, - OCSP_NOCHECKS = 256, - OCSP_TRUSTOTHER = 512, - OCSP_RESPID_KEY = 1024, - OCSP_NOTIME = 2048, -#endif - - SSL_ST_CONNECT = 0x1000, - SSL_ST_ACCEPT = 0x2000, - SSL_ST_MASK = 0x0FFF, - - SSL_CB_LOOP = 0x01, - SSL_CB_EXIT = 0x02, - SSL_CB_READ = 0x04, - SSL_CB_WRITE = 0x08, - SSL_CB_HANDSHAKE_START = 0x10, - SSL_CB_HANDSHAKE_DONE = 0x20, - SSL_CB_ALERT = 0x4000, - SSL_CB_READ_ALERT = (SSL_CB_ALERT | SSL_CB_READ), - SSL_CB_WRITE_ALERT = (SSL_CB_ALERT | SSL_CB_WRITE), - SSL_CB_ACCEPT_LOOP = (SSL_ST_ACCEPT | SSL_CB_LOOP), - SSL_CB_ACCEPT_EXIT = (SSL_ST_ACCEPT | SSL_CB_EXIT), - SSL_CB_CONNECT_LOOP = (SSL_ST_CONNECT | SSL_CB_LOOP), - SSL_CB_CONNECT_EXIT = (SSL_ST_CONNECT | SSL_CB_EXIT), - SSL_CB_MODE_READ = 1, - SSL_CB_MODE_WRITE = 2, - - SSL_MODE_ENABLE_PARTIAL_WRITE = 2, - SSL_MODE_AUTO_RETRY = 3, /* wolfSSL default is to return WANT_{READ|WRITE} - * to the user. This is set by default with - * OPENSSL_COMPATIBLE_DEFAULTS. The macro - * WOLFSSL_MODE_AUTO_RETRY_ATTEMPTS is used to - * limit the possibility of an infinite retry loop - */ - SSL_MODE_RELEASE_BUFFERS = -1, /* For libwebsockets build. No current use. */ - /* Errors used in wolfSSL. utilize the values from the defines in - * wolfssl/openssl/x509.h, but without the WOLFSSL_ prefix. - */ - WOLFSSL_X509_V_OK = 0, - WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, - WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID = 9, - WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED = 10, - WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, - WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, - WOLFSSL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, - WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, - WOLFSSL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, - WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, - WOLFSSL_X509_V_ERR_CERT_REVOKED = 23, - WOLFSSL_X509_V_ERR_INVALID_CA = 24, - WOLFSSL_X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, - WOLFSSL_X509_V_ERR_CERT_REJECTED = 28, - WOLFSSL_X509_V_ERR_SUBJECT_ISSUER_MISMATCH = 29, +WOLFSSL_API const char* wolfSSL_get_version(const WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl); +WOLFSSL_API WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl); +WOLFSSL_API char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, int len); +WOLFSSL_API const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API const char* wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher); +WOLFSSL_API const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value); +WOLFSSL_API const char* wolfSSL_SESSION_CIPHER_get_name(const WOLFSSL_SESSION* session); +WOLFSSL_API const char* wolfSSL_get_cipher(WOLFSSL* ssl); +WOLFSSL_API void wolfSSL_sk_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk); +WOLFSSL_API WOLFSSL_SESSION* wolfSSL_get1_session(WOLFSSL* ssl); +WOLFSSL_API int wolfSSL_SessionIsSetup(WOLFSSL_SESSION* session); - CRYPTO_LOCK = 1, - CRYPTO_NUM_LOCKS = 10, +WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new(void); +WOLFSSL_API WOLFSSL_X509_STORE_CTX* wolfSSL_X509_STORE_CTX_new_ex(void* heap); +WOLFSSL_API void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx); - ASN1_STRFLGS_ESC_MSB = 4 -}; -#endif +WOLFSSL_API long wolfSSL_set_options(WOLFSSL *s, long op); +WOLFSSL_API long wolfSSL_get_options(const WOLFSSL *s); -/* extras end */ +WOLFSSL_ABI WOLFSSL_API char* wolfSSL_X509_NAME_oneline(WOLFSSL_X509_NAME* name, + char* in, int sz); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) /* wolfSSL extension, provide last error from SSL_get_error @@ -2572,8 +2857,6 @@ WOLFSSL_API void wolfSSL_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u), void *u); #endif #endif -WOLFSSL_API void wolfSSL_ERR_print_errors(WOLFSSL_BIO *bio); - #ifndef NO_OLD_SSL_NAMES #define SSL_ERROR_NONE WOLFSSL_ERROR_NONE @@ -2633,16 +2916,20 @@ WOLFSSL_API void wolfSSL_ERR_print_errors(WOLFSSL_BIO *bio); enum { /* ssl Constants */ WOLFSSL_ERROR_NONE = 0, /* for most functions */ WOLFSSL_FAILURE = 0, /* for some functions */ + WOLFSSL_SUCCESS = 1, #if defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES) && \ (defined(BUILDING_WOLFSSL) || \ defined(WOLFSSL_DEBUG_TRACE_ERROR_CODES_ALWAYS)) #define WOLFSSL_FAILURE WC_ERR_TRACE(WOLFSSL_FAILURE) #define CONST_NUM_ERR_WOLFSSL_FAILURE 0 + /* include CONST_NUM_ERR_ variants of the success codes, so that they + * can be harmlessly wrapped in WC_NO_ERR_TRACE(). + */ + #define CONST_NUM_ERR_WOLFSSL_ERROR_NONE 0 + #define CONST_NUM_ERR_WOLFSSL_SUCCESS 1 #endif - WOLFSSL_SUCCESS = 1, - /* WOLFSSL_SHUTDOWN_NOT_DONE is returned by wolfSSL_shutdown and * wolfSSL_SendUserCanceled when the other end * of the connection has yet to send its close notify alert as part of the @@ -2776,8 +3063,11 @@ enum { /* ssl Constants */ /* extra begins */ #if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) enum { /* ERR Constants */ - ERR_TXT_STRING = 1 + WOLFSSL_ERR_TXT_STRING = 1 }; +#ifndef OPENSSL_COEXIST +#define ERR_TXT_STRING WOLFSSL_ERR_TXT_STRING +#endif #endif #ifdef OPENSSL_EXTRA /* bio misc */ @@ -2808,7 +3098,6 @@ WOLFSSL_API long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt); #if !defined(NO_CHECK_PRIVATE_KEY) WOLFSSL_API int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx); #endif -WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx); WOLFSSL_API void wolfSSL_ERR_free_strings(void); WOLFSSL_API void wolfSSL_ERR_remove_state(unsigned long id); @@ -2836,16 +3125,21 @@ WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFS WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl); #endif -#ifdef OPENSSL_EXTRA -WOLFSSL_API int wolfSSL_want(WOLFSSL* ssl); -#endif WOLFSSL_API int wolfSSL_want_read(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_want_write(WOLFSSL* ssl); + +#ifdef OPENSSL_EXTRA +WOLFSSL_API int wolfSSL_want(WOLFSSL* ssl); + +WOLFSSL_API WOLFSSL_EVP_PKEY* wolfSSL_CTX_get0_privatekey(const WOLFSSL_CTX* ctx); + #include /* var_arg */ WOLFSSL_API int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args); WOLFSSL_API int wolfSSL_BIO_printf(WOLFSSL_BIO* bio, const char* format, ...); + + WOLFSSL_API int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char* buf, int length); WOLFSSL_API int wolfSSL_ASN1_UTCTIME_print(WOLFSSL_BIO* bio, const WOLFSSL_ASN1_UTCTIME* a); @@ -2857,41 +3151,20 @@ WOLFSSL_API int wolfSSL_ASN1_TIME_diff(int* days, int* secs, const WOLFSSL_ASN1_ const WOLFSSL_ASN1_TIME* to); WOLFSSL_API int wolfSSL_ASN1_TIME_compare(const WOLFSSL_ASN1_TIME *a, const WOLFSSL_ASN1_TIME *b); -#ifdef OPENSSL_EXTRA WOLFSSL_API WOLFSSL_ASN1_TIME *wolfSSL_ASN1_TIME_set(WOLFSSL_ASN1_TIME *s, time_t t); WOLFSSL_API int wolfSSL_ASN1_TIME_set_string(WOLFSSL_ASN1_TIME *s, const char *str); WOLFSSL_API int wolfSSL_ASN1_TIME_set_string_X509(WOLFSSL_ASN1_TIME *t, const char *str); -#endif +#endif /* OPENSSL_EXTRA */ + +#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) WOLFSSL_API int wolfSSL_sk_num(const WOLFSSL_STACK* sk); WOLFSSL_API void* wolfSSL_sk_value(const WOLFSSL_STACK* sk, int i); - -#if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) - -WOLFSSL_API void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, - int idx); -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -WOLFSSL_API int wolfSSL_CRYPTO_set_ex_data_with_cleanup( - WOLFSSL_CRYPTO_EX_DATA* ex_data, - int idx, - void *data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine); -#endif -WOLFSSL_API int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx, - void *data); #endif + /* stunnel 4.28 needs */ -WOLFSSL_API void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx); -WOLFSSL_API int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data); -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -WOLFSSL_API int wolfSSL_CTX_set_ex_data_with_cleanup( - WOLFSSL_CTX* ctx, - int idx, - void* data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine); -#endif WOLFSSL_API void wolfSSL_CTX_sess_set_get_cb(WOLFSSL_CTX* ctx, WOLFSSL_SESSION*(*f)(WOLFSSL* ssl, const unsigned char*, int, int*)); WOLFSSL_API void wolfSSL_CTX_sess_set_new_cb(WOLFSSL_CTX* ctx, @@ -2908,13 +3181,21 @@ WOLFSSL_API unsigned long wolfSSL_SESSION_get_ticket_lifetime_hint( const WOLFSSL_SESSION* sess); WOLFSSL_API long wolfSSL_SESSION_get_timeout(const WOLFSSL_SESSION* session); WOLFSSL_API long wolfSSL_SESSION_get_time(const WOLFSSL_SESSION* session); -#ifdef HAVE_EX_DATA -WOLFSSL_API int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, - WOLFSSL_CRYPTO_EX_new* new_func, - WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func); + + +#ifdef SESSION_CERTS +#ifdef OPENSSL_EXTRA +WOLFSSL_API const char *wolfSSL_get0_peername(WOLFSSL *ssl); #endif +WOLFSSL_API + WOLFSSL_X509_CHAIN* wolfSSL_SESSION_get_peer_chain(WOLFSSL_SESSION* session); +WOLFSSL_API WOLFSSL_X509* wolfSSL_SESSION_get0_peer(WOLFSSL_SESSION* session); + +WOLFSSL_API int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, + unsigned char* buf, int inLen, int* outLen); +#endif /* SESSION_CERTS */ + /* extra ends */ @@ -2925,15 +3206,30 @@ WOLFSSL_API int wolfSSL_CTX_get_ex_new_index(long idx, void* arg, date check and signature check */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn); -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) -WOLFSSL_API const char *wolfSSL_get0_peername(WOLFSSL *ssl); -#endif /* need to call once to load library (session cache) */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_Init(void); /* call when done to cleanup/free session cache mutex / resources */ WOLFSSL_ABI WOLFSSL_API int wolfSSL_Cleanup(void); +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) +#ifndef NO_FILESYSTEM +WOLFSSL_API int wolfSSL_crypto_policy_enable(const char * policy); +#endif /* ! NO_FILESYSTEM */ +WOLFSSL_API int wolfSSL_crypto_policy_enable_buffer(const char * buf); +WOLFSSL_API void wolfSSL_crypto_policy_disable(void); +WOLFSSL_API int wolfSSL_crypto_policy_is_enabled(void); +WOLFSSL_API const char * wolfSSL_crypto_policy_get_ciphers(void); +WOLFSSL_API int wolfSSL_crypto_policy_get_level(void); +WOLFSSL_LOCAL int wolfSSL_crypto_policy_init_ctx(WOLFSSL_CTX * ctx, + WOLFSSL_METHOD * method); +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ +/* compat functions. */ +WOLFSSL_API int wolfSSL_get_security_level(const WOLFSSL * ssl); +#ifndef NO_WOLFSSL_STUB +WOLFSSL_API void wolfSSL_set_security_level(WOLFSSL * ssl, int level); +#endif /* !NO_WOLFSSL_STUB */ + /* which library version do we have */ WOLFSSL_API const char* wolfSSL_lib_version(void); #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L @@ -2969,13 +3265,49 @@ WOLFSSL_API int wolfSSL_get_chain_length(WOLFSSL_X509_CHAIN* chain, int idx); WOLFSSL_API unsigned char* wolfSSL_get_chain_cert(WOLFSSL_X509_CHAIN* chain, int idx); /* index cert in X509 */ WOLFSSL_API WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx); + + +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(KEEP_PEER_CERT) || defined(KEEP_OUR_CERT) || defined(SESSION_CERTS) + +WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new(void); +WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_new_ex(void* heap); +WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_dup(WOLFSSL_X509* x); + +WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_get_issuer_name( + WOLFSSL_X509* cert); +WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_get_subject_name( + WOLFSSL_X509* cert); + +WOLFSSL_API int wolfSSL_X509_get_signature_type(WOLFSSL_X509* x509); +WOLFSSL_API int wolfSSL_X509_get_isCA(WOLFSSL_X509* x509); +WOLFSSL_API int wolfSSL_X509_get_signature(WOLFSSL_X509* x509, + unsigned char* buf, int* bufSz); +WOLFSSL_API int wolfSSL_X509_get_pubkey_buffer(WOLFSSL_X509* x509, + unsigned char* buf, int* bufSz); +WOLFSSL_API int wolfSSL_X509_get_pubkey_type(WOLFSSL_X509* x509); + +#ifndef NO_FILESYSTEM +WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509* + wolfSSL_X509_load_certificate_file(const char* fname, int format); +#endif +WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_load_certificate_buffer( + const unsigned char* buf, int sz, int format); +#ifdef WOLFSSL_CERT_REQ +WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_REQ_load_certificate_buffer( + const unsigned char* buf, int sz, int format); +#endif + /* free X509 */ #define wolfSSL_FreeX509(x509) wolfSSL_X509_free((x509)) WOLFSSL_ABI WOLFSSL_API void wolfSSL_X509_free(WOLFSSL_X509* x509); +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || KEEP_PEER_CERT || \ + KEEP_OUR_CERT || SESSION_CERTS */ + + /* get index cert in PEM */ -WOLFSSL_API int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, - unsigned char* buf, int inLen, int* outLen); + WOLFSSL_ABI WOLFSSL_API const unsigned char* wolfSSL_get_sessionID( const WOLFSSL_SESSION* s); WOLFSSL_API int wolfSSL_X509_get_serial_number(WOLFSSL_X509* x509,unsigned char* in,int* inOutSz); @@ -3008,12 +3340,12 @@ WOLFSSL_API WOLFSSL_X509* wolfSSL_d2i_X509_REQ_INFO(WOLFSSL_X509** req, WOLFSSL_API int wolfSSL_i2d_X509(WOLFSSL_X509* x509, unsigned char** out); WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL(WOLFSSL_X509_CRL **crl, const unsigned char *in, int len); -WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_bio(WOLFSSL_BIO *bp, - WOLFSSL_X509_CRL **crl); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_fp(XFILE file, WOLFSSL_X509_CRL **crl); #endif #if defined(HAVE_CRL) && defined(OPENSSL_EXTRA) +WOLFSSL_API WOLFSSL_X509_CRL *wolfSSL_d2i_X509_CRL_bio(WOLFSSL_BIO *bp, + WOLFSSL_X509_CRL **crl); WOLFSSL_API int wolfSSL_X509_CRL_version(WOLFSSL_X509_CRL *crl); WOLFSSL_API int wolfSSL_X509_CRL_get_signature_type(WOLFSSL_X509_CRL* crl); WOLFSSL_API int wolfSSL_X509_CRL_get_signature_nid( @@ -3071,6 +3403,7 @@ WOLFSSL_API WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer( const unsigned char* buf, int sz, int format); #endif /* WOLFSSL_ACERT && (OPENSSL_EXTRA_X509_SMALL || OPENSSL_EXTRA) */ +#ifdef OPENSSL_EXTRA WOLFSSL_API const WOLFSSL_ASN1_INTEGER* wolfSSL_X509_REVOKED_get0_serial_number(const WOLFSSL_X509_REVOKED *rev); @@ -3083,14 +3416,6 @@ const WOLFSSL_ASN1_TIME* wolfSSL_X509_REVOKED_get0_revocation_date(const WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_d2i_fp(WOLFSSL_X509** x509, XFILE file); #endif -WOLFSSL_ABI WOLFSSL_API WOLFSSL_X509* - wolfSSL_X509_load_certificate_file(const char* fname, int format); -#endif -WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_load_certificate_buffer( - const unsigned char* buf, int sz, int format); -#ifdef WOLFSSL_CERT_REQ -WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_REQ_load_certificate_buffer( - const unsigned char* buf, int sz, int format); #endif #ifdef WOLFSSL_SEP @@ -3102,19 +3427,25 @@ WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_REQ_load_certificate_buffer( wolfSSL_X509_get_hw_serial_number(WOLFSSL_X509* x509, unsigned char* in, int* inOutSz); #endif +#endif /* OPENSSL_EXTRA */ + /* connect enough to get peer cert */ WOLFSSL_API int wolfSSL_connect_cert(WOLFSSL* ssl); - +#ifdef OPENSSL_EXTRA /* PKCS12 compatibility */ -WOLFSSL_API WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, - WC_PKCS12** pkcs12); -WOLFSSL_API int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12); +WOLFSSL_API void wolfSSL_PKCS12_PBE_add(void); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) WOLFSSL_API WOLFSSL_X509_PKCS12* wolfSSL_d2i_PKCS12_fp(XFILE fp, WOLFSSL_X509_PKCS12** pkcs12); #endif + +#ifdef HAVE_PKCS12 +WOLFSSL_API WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, + WC_PKCS12** pkcs12); +WOLFSSL_API int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12); + WOLFSSL_API int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, WOLFSSL_EVP_PKEY** pkey, WOLFSSL_X509** cert, WOLF_STACK_OF(WOLFSSL_X509)** ca); @@ -3124,8 +3455,8 @@ WOLFSSL_API WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey, WOLFSSL_X509* cert, WOLF_STACK_OF(WOLFSSL_X509)* ca, int keyNID, int certNID, int itt, int macItt, int keytype); -WOLFSSL_API void wolfSSL_PKCS12_PBE_add(void); - +#endif /* HAVE_PKCS12 */ +#endif /* OPENSSL_EXTRA */ #ifndef NO_DH @@ -3242,6 +3573,12 @@ WOLFSSL_API int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* key, unsigned int len, const unsigned char* in, long sz, int format); WOLFSSL_API int wolfSSL_CTX_use_certificate_chain_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, long sz); +#if defined(WOLF_CRYPTO_CB) + WOLFSSL_API int wolfSSL_CTX_use_certificate_label(WOLFSSL_CTX* ctx, + const char *label, int devId); + WOLFSSL_API int wolfSSL_CTX_use_certificate_id(WOLFSSL_CTX* ctx, + const unsigned char *id, int idLen, int devId); +#endif #ifdef WOLFSSL_DUAL_ALG_CERTS WOLFSSL_API int wolfSSL_CTX_use_AltPrivateKey_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, long sz, int format); @@ -3362,6 +3699,22 @@ typedef void (*CbOCSPRespFree)(void*,unsigned char*); typedef int (*CbCrlIO)(WOLFSSL_CRL* crl, const char* url, int urlSz); #endif +#ifdef HAVE_CRL_UPDATE_CB +typedef struct CrlInfo { + byte *issuerHash; + word32 issuerHashLen; + byte *lastDate; + word32 lastDateMaxLen; + byte lastDateFormat; + byte *nextDate; + word32 nextDateMaxLen; + byte nextDateFormat; + sword32 crlNumber; +} CrlInfo; + +typedef void (*CbUpdateCRL)(CrlInfo* old, CrlInfo* cnew); +#endif + /* User Atomic Record Layer CallBacks */ typedef int (*CallbackMacEncrypt)(WOLFSSL* ssl, unsigned char* macOut, const unsigned char* macIn, unsigned int macInSz, int macContent, @@ -3442,7 +3795,7 @@ enum { WOLFSSL_BLOCK_TYPE = 2, WOLFSSL_STREAM_TYPE = 3, WOLFSSL_AEAD_TYPE = 4, - WOLFSSL_TLS_HMAC_INNER_SZ = 13, /* SEQ_SZ + ENUM + VERSION_SZ + LEN_SZ */ + WOLFSSL_TLS_HMAC_INNER_SZ = 13 /* SEQ_SZ + ENUM + VERSION_SZ + LEN_SZ */ }; /* for GetBulkCipher and internal use @@ -3807,8 +4160,10 @@ WOLFSSL_API void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, WOLFSSL_API int wolfSSL_CertManagerEnableCRL(WOLFSSL_CERT_MANAGER* cm, int options); WOLFSSL_API int wolfSSL_CertManagerDisableCRL(WOLFSSL_CERT_MANAGER* cm); +#ifndef NO_WOLFSSL_CM_VERIFY WOLFSSL_API void wolfSSL_CertManagerSetVerify(WOLFSSL_CERT_MANAGER* cm, VerifyCallback vc); +#endif WOLFSSL_API int wolfSSL_CertManagerLoadCRL(WOLFSSL_CERT_MANAGER* cm, const char* path, int type, int monitor); WOLFSSL_API int wolfSSL_CertManagerLoadCRLFile(WOLFSSL_CERT_MANAGER* cm, @@ -3824,6 +4179,12 @@ WOLFSSL_API void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx, WOLFSSL_API int wolfSSL_CertManagerSetCRL_IOCb(WOLFSSL_CERT_MANAGER* cm, CbCrlIO cb); #endif +#ifdef HAVE_CRL_UPDATE_CB + WOLFSSL_API int wolfSSL_CertManagerGetCRLInfo(WOLFSSL_CERT_MANAGER* cm, CrlInfo* info, + const byte* buff, long sz, int type); + WOLFSSL_API int wolfSSL_CertManagerSetCRLUpdate_Cb(WOLFSSL_CERT_MANAGER* cm, + CbUpdateCRL cb); +#endif #if defined(HAVE_OCSP) WOLFSSL_API int wolfSSL_CertManagerCheckOCSPResponse( WOLFSSL_CERT_MANAGER* cm, unsigned char *response, int responseSz, @@ -3932,7 +4293,7 @@ WOLFSSL_API void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl); /* SNI types */ enum { - WOLFSSL_SNI_HOST_NAME = 0, + WOLFSSL_SNI_HOST_NAME = 0 }; WOLFSSL_ABI WOLFSSL_API int wolfSSL_UseSNI(WOLFSSL* ssl, unsigned char type, @@ -3952,7 +4313,7 @@ enum { WOLFSSL_SNI_ANSWER_ON_MISMATCH = 0x02, /* Abort the handshake if the client didn't send a SNI request. */ - WOLFSSL_SNI_ABORT_ON_ABSENCE = 0x04, + WOLFSSL_SNI_ABORT_ON_ABSENCE = 0x04 }; WOLFSSL_API void wolfSSL_SNI_SetOptions(WOLFSSL* ssl, unsigned char type, @@ -4003,7 +4364,7 @@ enum { WOLFSSL_ALPN_NO_MATCH = 0, WOLFSSL_ALPN_MATCH = 1, WOLFSSL_ALPN_CONTINUE_ON_MISMATCH = 2, - WOLFSSL_ALPN_FAILED_ON_MISMATCH = 4, + WOLFSSL_ALPN_FAILED_ON_MISMATCH = 4 }; enum { @@ -4045,7 +4406,7 @@ enum { WOLFSSL_MFL_2_13 = 5, /* 8192 bytes *//* wolfSSL ONLY!!! */ WOLFSSL_MFL_2_8 = 6, /* 256 bytes *//* wolfSSL ONLY!!! */ WOLFSSL_MFL_MIN = WOLFSSL_MFL_2_9, - WOLFSSL_MFL_MAX = WOLFSSL_MFL_2_8, + WOLFSSL_MFL_MAX = WOLFSSL_MFL_2_8 }; #ifndef NO_WOLFSSL_CLIENT @@ -4177,36 +4538,46 @@ enum { * algorithms have LEVEL2 and LEVEL4 because none of these submissions * included them. */ -#ifndef WOLFSSL_ML_KEM +#ifdef WOLFSSL_KYBER_ORIGINAL WOLFSSL_PQC_MIN = 570, WOLFSSL_PQC_SIMPLE_MIN = 570, WOLFSSL_KYBER_LEVEL1 = 570, /* KYBER_512 */ WOLFSSL_KYBER_LEVEL3 = 572, /* KYBER_768 */ WOLFSSL_KYBER_LEVEL5 = 573, /* KYBER_1024 */ +#ifdef WOLFSSL_NO_ML_KEM WOLFSSL_PQC_SIMPLE_MAX = 573, +#endif WOLFSSL_PQC_HYBRID_MIN = 12090, WOLFSSL_P256_KYBER_LEVEL1 = 12090, WOLFSSL_P384_KYBER_LEVEL3 = 12092, WOLFSSL_P521_KYBER_LEVEL5 = 12093, +#ifdef WOLFSSL_NO_ML_KEM WOLFSSL_PQC_HYBRID_MAX = 12093, WOLFSSL_PQC_MAX = 12093, -#else +#endif +#endif +#ifndef WOLFSSL_NO_ML_KEM +#ifndef WOLFSSL_KYBER_ORIGINAL WOLFSSL_PQC_MIN = 583, WOLFSSL_PQC_SIMPLE_MIN = 583, - WOLFSSL_KYBER_LEVEL1 = 583, /* ML-KEM 512 */ - WOLFSSL_KYBER_LEVEL3 = 584, /* ML-KEM 768 */ - WOLFSSL_KYBER_LEVEL5 = 585, /* ML-KEM 1024 */ +#endif + WOLFSSL_ML_KEM_512 = 583, /* ML-KEM 512 */ + WOLFSSL_ML_KEM_768 = 584, /* ML-KEM 768 */ + WOLFSSL_ML_KEM_1024 = 585, /* ML-KEM 1024 */ WOLFSSL_PQC_SIMPLE_MAX = 585, +#ifndef WOLFSSL_KYBER_ORIGINAL WOLFSSL_PQC_HYBRID_MIN = 12103, - WOLFSSL_P256_KYBER_LEVEL1 = 12103, - WOLFSSL_P384_KYBER_LEVEL3 = 12104, - WOLFSSL_P521_KYBER_LEVEL5 = 12105, +#endif + WOLFSSL_P256_ML_KEM_512 = 12103, + WOLFSSL_P384_ML_KEM_768 = 12104, + WOLFSSL_P521_ML_KEM_1024 = 12105, WOLFSSL_PQC_HYBRID_MAX = 12105, WOLFSSL_PQC_MAX = 12105, -#endif /* WOLFSSL_ML_KEM */ +#endif /* !WOLFSSL_NO_ML_KEM */ #endif /* HAVE_PQC */ + WOLF_ENUM_DUMMY_LAST_ELEMENT(SSL_H) }; enum { @@ -4215,6 +4586,7 @@ enum { WOLFSSL_EC_PF_X962_COMP_PRIME = 1, WOLFSSL_EC_PF_X962_COMP_CHAR2 = 2, #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(SSL_H) }; #ifdef HAVE_SUPPORTED_CURVES @@ -4365,6 +4737,7 @@ WOLFSSL_API int wolfSSL_CTX_DisableExtendedMasterSecret(WOLFSSL_CTX* ctx); #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) +WOLFSSL_API int wolfDTLS_accept_stateless(WOLFSSL* ssl); /* notify user we parsed a verified ClientHello is done. This only has an effect * on the server end. */ typedef int (*ClientHelloGoodCb)(WOLFSSL* ssl, void*); @@ -4525,15 +4898,19 @@ WOLFSSL_API int wolfSSL_X509_NAME_add_entry(WOLFSSL_X509_NAME* name, WOLFSSL_API int wolfSSL_X509_NAME_add_entry_by_txt(WOLFSSL_X509_NAME *name, const char *field, int type, const unsigned char *bytes, int len, int loc, int set); +#ifndef wolfSSL_X509_NAME_add_entry_by_NID WOLFSSL_API int wolfSSL_X509_NAME_add_entry_by_NID(WOLFSSL_X509_NAME *name, int nid, int type, const unsigned char *bytes, int len, int loc, int set); +#endif WOLFSSL_API WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_delete_entry( WOLFSSL_X509_NAME *name, int loc); WOLFSSL_API int wolfSSL_X509_NAME_cmp(const WOLFSSL_X509_NAME* x, const WOLFSSL_X509_NAME* y); WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_NAME_new(void); +#ifndef wolfSSL_X509_NAME_new_ex WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_NAME_new_ex(void *heap); +#endif WOLFSSL_API WOLFSSL_X509_NAME* wolfSSL_X509_NAME_dup(WOLFSSL_X509_NAME* name); WOLFSSL_API int wolfSSL_X509_NAME_copy(WOLFSSL_X509_NAME* from, WOLFSSL_X509_NAME* to); WOLFSSL_API int wolfSSL_check_private_key(const WOLFSSL* ssl); @@ -4698,7 +5075,7 @@ WOLFSSL_API WOLFSSL_X509 *wolfSSL_PEM_read_bio_X509_AUX #ifndef NO_FILESYSTEM WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_INFO)* wolfSSL_PEM_X509_INFO_read( XFILE fp, WOLF_STACK_OF(WOLFSSL_X509_INFO)* sk, - pem_password_cb* cb, void* u); + wc_pem_password_cb* cb, void* u); #endif WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_INFO)* wolfSSL_PEM_X509_INFO_read_bio( WOLFSSL_BIO* bio, WOLF_STACK_OF(WOLFSSL_X509_INFO)* sk, @@ -4734,9 +5111,6 @@ struct WOLFSSL_CONF_CTX { WOLFSSL_API WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_get_entry(WOLFSSL_X509_NAME *name, int loc); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)|| \ - defined(OPENSSL_EXTRA_X509_SMALL) - #if defined(OPENSSL_EXTRA) \ || defined(OPENSSL_ALL) \ || defined(HAVE_LIGHTY) \ @@ -4747,7 +5121,9 @@ WOLFSSL_API WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_get_entry(WOLFSSL_X509_NA || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_API void wolfSSL_X509_NAME_ENTRY_free(WOLFSSL_X509_NAME_ENTRY* ne); WOLFSSL_API WOLFSSL_X509_NAME_ENTRY* wolfSSL_X509_NAME_ENTRY_new(void); +#ifndef wolfSSL_X509_NAME_free WOLFSSL_API void wolfSSL_X509_NAME_free(WOLFSSL_X509_NAME* name); +#endif WOLFSSL_API int wolfSSL_CTX_use_certificate(WOLFSSL_CTX* ctx, WOLFSSL_X509* x); WOLFSSL_API int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509); @@ -4756,7 +5132,6 @@ WOLFSSL_API int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509); WOLFSSL_API int wolfSSL_BIO_read_filename(WOLFSSL_BIO *b, const char *name); /* These are to be merged shortly */ WOLFSSL_API void wolfSSL_set_verify_depth(WOLFSSL *ssl,int depth); -WOLFSSL_API void* wolfSSL_get_app_data( const WOLFSSL *ssl); WOLFSSL_API int wolfSSL_set_app_data(WOLFSSL *ssl, void *arg); WOLFSSL_API WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object(WOLFSSL_X509_NAME_ENTRY *ne); WOLFSSL_API unsigned char *wolfSSL_SHA1(const unsigned char *d, size_t n, unsigned char *md); @@ -4773,9 +5148,9 @@ WOLFSSL_API long wolfSSL_BIO_set_fp(WOLFSSL_BIO *bio, XFILE fp, int c); WOLFSSL_API long wolfSSL_BIO_get_fp(WOLFSSL_BIO *bio, XFILE* fp); #endif -#endif /* OPENSSL_EXTRA || OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ - -#endif /* OPENSSL_EXTRA || OPENSSL_ALL */ +#endif /* OPENSSL_EXTRA || OPENSSL_ALL || HAVE_LIGHTY || \ + WOLFSSL_MYSQL_COMPATIBLE || HAVE_STUNNEL || WOLFSSL_NGINX || \ + WOLFSSL_HAPROXY */ #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \ || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) @@ -4815,6 +5190,8 @@ WOLFSSL_API int wolfSSL_PEM_write_bio_X509(WOLFSSL_BIO *bp, WOLFSSL_X509 *x); WOLFSSL_API int wolfSSL_i2d_X509_REQ(WOLFSSL_X509* req, unsigned char** out); WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_REQ_new(void); WOLFSSL_API void wolfSSL_X509_REQ_free(WOLFSSL_X509* req); +WOLFSSL_API long wolfSSL_X509_REQ_get_version(const WOLFSSL_X509 *req); +WOLFSSL_API int wolfSSL_X509_REQ_set_version(WOLFSSL_X509 *x, long version); WOLFSSL_API int wolfSSL_X509_REQ_sign(WOLFSSL_X509 *req, WOLFSSL_EVP_PKEY *pkey, const WOLFSSL_EVP_MD *md); WOLFSSL_API int wolfSSL_X509_REQ_sign_ctx(WOLFSSL_X509 *req, @@ -4861,8 +5238,6 @@ WOLFSSL_API int wolfSSL_CRYPTO_set_mem_functions( WOLFSSL_API int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int), void *(*r) (void *, size_t, const char *, int), void (*f) (void *)); -WOLFSSL_API void wolfSSL_CRYPTO_cleanup_all_ex_data(void); - WOLFSSL_API int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size); WOLFSSL_API WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn); @@ -5007,12 +5382,6 @@ WOLFSSL_API int wolfSSL_SESSION_set_ex_data_with_cleanup( #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) \ || defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) -#ifdef HAVE_EX_DATA -WOLFSSL_API int wolfSSL_SESSION_get_ex_new_index(long ctx_l,void* ctx_ptr, - WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func); -#endif - WOLFSSL_API const unsigned char* wolfSSL_SESSION_get_id( const WOLFSSL_SESSION* sess, unsigned int* idLen); @@ -5093,13 +5462,10 @@ WOLFSSL_API int wolfSSL_CTX_set1_curves_list(WOLFSSL_CTX* ctx, const char* names WOLFSSL_API int wolfSSL_set1_curves_list(WOLFSSL* ssl, const char* names); #endif -#if defined(OPENSSL_ALL) || \ - defined(HAVE_STUNNEL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ - defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(HAVE_STUNNEL) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) WOLFSSL_API int wolfSSL_get_verify_mode(const WOLFSSL* ssl); WOLFSSL_API int wolfSSL_CTX_get_verify_mode(const WOLFSSL_CTX* ctx); - #endif #ifdef WOLFSSL_JNI @@ -5179,34 +5545,16 @@ WOLFSSL_LOCAL char* wolfSSL_get_ocsp_url(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_set_ocsp_url(WOLFSSL* ssl, char* url); #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) \ - || defined(WOLFSSL_WPAS_SMALL) -WOLFSSL_API void *wolfSSL_X509_get_ex_data(WOLFSSL_X509 *x509, int idx); -WOLFSSL_API int wolfSSL_X509_set_ex_data(WOLFSSL_X509 *x509, int idx, - void *data); -#ifdef HAVE_EX_DATA_CLEANUP_HOOKS -WOLFSSL_API int wolfSSL_X509_set_ex_data_with_cleanup( - WOLFSSL_X509 *x509, - int idx, - void *data, - wolfSSL_ex_data_cleanup_routine_t cleanup_routine); +#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK) +WOLFSSL_API long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx); +WOLFSSL_API long wolfSSL_get_timeout(WOLFSSL* ssl); #endif -#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ - || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK) + || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) WOLFSSL_API WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl); -#ifdef HAVE_EX_DATA -WOLFSSL_API int wolfSSL_X509_get_ex_new_index(int idx, void *arg, - WOLFSSL_CRYPTO_EX_new* new_func, - WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func); -#endif WOLFSSL_API int wolfSSL_X509_NAME_digest(const WOLFSSL_X509_NAME *data, const WOLFSSL_EVP_MD *type, unsigned char *md, unsigned int *len); - -WOLFSSL_API long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx); -WOLFSSL_API long wolfSSL_get_timeout(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_SSL_CTX_set_tmp_ecdh(WOLFSSL_CTX *ctx, WOLFSSL_EC_KEY *ecdh); WOLFSSL_API WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s); @@ -5214,11 +5562,11 @@ WOLFSSL_API WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s); WOLFSSL_API int wolfSSL_SSL_do_handshake(WOLFSSL *s); #ifdef OPENSSL_EXTRA WOLFSSL_API int wolfSSL_OPENSSL_init_ssl(word64 opts, - const OPENSSL_INIT_SETTINGS *settings); -WOLFSSL_API OPENSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void); -WOLFSSL_API void wolfSSL_OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS* init); + const WOLFSSL_INIT_SETTINGS *settings); +WOLFSSL_API WOLFSSL_INIT_SETTINGS* wolfSSL_OPENSSL_INIT_new(void); +WOLFSSL_API void wolfSSL_OPENSSL_INIT_free(WOLFSSL_INIT_SETTINGS* init); WOLFSSL_API int wolfSSL_OPENSSL_INIT_set_config_appname( - OPENSSL_INIT_SETTINGS* init, char* appname); + WOLFSSL_INIT_SETTINGS* init, char* appname); #endif #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L WOLFSSL_API int wolfSSL_SSL_in_init(const WOLFSSL* ssl); @@ -5372,8 +5720,14 @@ WOLFSSL_API WOLFSSL_ASN1_OBJECT *wolfSSL_d2i_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT **a long length); WOLFSSL_API int wolfSSL_i2a_ASN1_OBJECT(WOLFSSL_BIO *bp, WOLFSSL_ASN1_OBJECT *a); WOLFSSL_API int wolfSSL_i2d_ASN1_OBJECT(WOLFSSL_ASN1_OBJECT *a, unsigned char **pp); -WOLFSSL_API void SSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)); -WOLFSSL_API WOLF_STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); +WOLFSSL_API void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx, WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength)); +#ifndef OPENSSL_COEXIST +#define SSL_CTX_set_tmp_dh_callback WOLFSSL_CTX_set_tmp_dh_callback +#endif +WOLFSSL_API WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void); +#ifndef OPENSSL_COEXIST +#define SSL_COMP_get_compression_methods WOLFSSL_COMP_get_compression_methods +#endif WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, const char *file, const char *dir); WOLFSSL_API int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *ctx, WOLFSSL_X509_CRL *x); WOLFSSL_API int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p); @@ -5383,7 +5737,10 @@ WOLFSSL_API void wolfSSL_sk_SSL_CIPHER_free(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk); WOLFSSL_API int wolfSSL_sk_SSL_COMP_zero(WOLFSSL_STACK* st); WOLFSSL_API int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk); WOLFSSL_API WOLFSSL_CIPHER* wolfSSL_sk_SSL_CIPHER_value(WOLFSSL_STACK* sk, int i); -WOLFSSL_API void ERR_load_SSL_strings(void); +WOLFSSL_API void wolfSSL_ERR_load_SSL_strings(void); +#ifndef OPENSSL_COEXIST +#define ERR_load_SSL_strings wolfSSL_ERR_load_SSL_strings +#endif WOLFSSL_API void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *p); WOLFSSL_API const char *wolfSSL_ASN1_tag2str(int tag); @@ -5406,7 +5763,7 @@ WOLFSSL_API int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, wc_pem_password_cb* cb, void* ctx); WOLFSSL_API int wolfSSL_PEM_write_bio_PKCS8_PRIV_KEY_INFO(WOLFSSL_BIO* bio, - PKCS8_PRIV_KEY_INFO* keyInfo); + WOLFSSL_PKCS8_PRIV_KEY_INFO* keyInfo); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) WOLFSSL_API int wolfSSL_PEM_write_PKCS8PrivateKey( XFILE fp, WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, @@ -5455,7 +5812,7 @@ WOLFSSL_API int wolfSSL_get_ephemeral_key(WOLFSSL* ssl, int keyAlgo, enum { WOLFSSL_CERT_TYPE_UNKNOWN = -1, WOLFSSL_CERT_TYPE_X509 = 0, - WOLFSSL_CERT_TYPE_RPK = 2, + WOLFSSL_CERT_TYPE_RPK = 2 }; #define MAX_CLIENT_CERT_TYPE_CNT 2 #define MAX_SERVER_CERT_TYPE_CNT 2 @@ -5479,7 +5836,6 @@ WOLFSSL_API int wolfSSL_EVP_PKEY_param_check(WOLFSSL_EVP_PKEY_CTX* ctx); #endif WOLFSSL_API void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level); WOLFSSL_API int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX* ctx); - WOLFSSL_API int wolfSSL_SESSION_is_resumable(const WOLFSSL_SESSION *s); WOLFSSL_API void wolfSSL_CRYPTO_free(void *str, const char *file, int line); @@ -5506,12 +5862,6 @@ WOLFSSL_API int wolfSSL_CONF_CTX_finish(WOLFSSL_CONF_CTX* cctx); WOLFSSL_API int wolfSSL_CONF_cmd(WOLFSSL_CONF_CTX* cctx, const char* cmd, const char* value); WOLFSSL_API int wolfSSL_CONF_cmd_value_type(WOLFSSL_CONF_CTX *cctx, const char *cmd); #endif /* OPENSSL_EXTRA */ -#if defined(HAVE_EX_DATA) || defined(WOLFSSL_WPAS_SMALL) -WOLFSSL_API int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, - WOLFSSL_CRYPTO_EX_new* new_func, - WOLFSSL_CRYPTO_EX_dup* dup_func, - WOLFSSL_CRYPTO_EX_free* free_func); -#endif /* HAVE_EX_DATA || WOLFSSL_WPAS_SMALL */ #if defined(WOLFSSL_DTLS_CID) WOLFSSL_API int wolfSSL_dtls_cid_use(WOLFSSL* ssl); @@ -5522,11 +5872,15 @@ WOLFSSL_API int wolfSSL_dtls_cid_get_rx_size(WOLFSSL* ssl, unsigned int* size); WOLFSSL_API int wolfSSL_dtls_cid_get_rx(WOLFSSL* ssl, unsigned char* buffer, unsigned int bufferSz); +WOLFSSL_API int wolfSSL_dtls_cid_get0_rx(WOLFSSL* ssl, unsigned char** cid); WOLFSSL_API int wolfSSL_dtls_cid_get_tx_size(WOLFSSL* ssl, unsigned int* size); WOLFSSL_API int wolfSSL_dtls_cid_get_tx(WOLFSSL* ssl, unsigned char* buffer, unsigned int bufferSz); +WOLFSSL_API int wolfSSL_dtls_cid_get0_tx(WOLFSSL* ssl, unsigned char** cid); WOLFSSL_API int wolfSSL_dtls_cid_max_size(void); +WOLFSSL_API const unsigned char* wolfSSL_dtls_cid_parse(const unsigned char* msg, + unsigned int msgSz, unsigned int cidSz); #endif /* defined(WOLFSSL_DTLS_CID) */ #ifdef WOLFSSL_DTLS_CH_FRAG diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index bbe7d0f..478a905 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -29,6 +29,12 @@ #define wolfSSL_TEST_H #include + +#undef TEST_OPENSSL_COEXIST /* can't use this option with this example */ +#if defined(OPENSSL_EXTRA) && defined(OPENSSL_COEXIST) + #error "Example apps built with OPENSSL_EXTRA can't also be built with OPENSSL_COEXIST." +#endif + #include #ifdef FUSION_RTOS @@ -1952,7 +1958,11 @@ static WC_INLINE unsigned int my_psk_client_tls13_cb(WOLFSSL* ssl, key[i] = (unsigned char) b; } +#if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) + *ciphersuite = userCipher ? userCipher : "TLS13-AES256-GCM-SHA384"; +#else *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; +#endif ret = 32; /* length of key in octets or 0 for error */ @@ -1991,7 +2001,11 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, key[i] = (unsigned char) b; } +#if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) + *ciphersuite = userCipher ? userCipher : "TLS13-AES256-GCM-SHA384"; +#else *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256"; +#endif ret = 32; /* length of key in octets or 0 for error */ @@ -2005,16 +2019,13 @@ static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl, } #endif -#if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) -static unsigned char local_psk[32]; -#endif +#ifdef OPENSSL_EXTRA static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, const WOLFSSL_EVP_MD* md, const unsigned char **id, size_t* idlen, WOLFSSL_SESSION **sess) { -#if defined(OPENSSL_ALL) && !defined(NO_CERTS) && \ - !defined(NO_FILESYSTEM) +#if defined(OPENSSL_ALL) && !defined(NO_CERTS) && !defined(NO_FILESYSTEM) + static unsigned char local_psk[32]; int i; WOLFSSL_SESSION* lsess; char buf[256]; @@ -2077,6 +2088,7 @@ static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, return 0; #endif } +#endif /* OPENSSL_EXTRA */ static WC_INLINE unsigned int my_psk_client_cs_cb(WOLFSSL* ssl, const char* hint, char* identity, unsigned int id_max_len, @@ -2397,7 +2409,7 @@ static WC_INLINE void OCSPRespFreeCb(void* ioCtx, unsigned char* response) enum { VERIFY_OVERRIDE_ERROR, VERIFY_FORCE_FAIL, - VERIFY_USE_PREVERFIY, + VERIFY_USE_PREVERIFY, VERIFY_OVERRIDE_DATE_ERR, }; static THREAD_LS_T int myVerifyAction = VERIFY_OVERRIDE_ERROR; @@ -2563,7 +2575,7 @@ static WC_INLINE void CRL_CallBack(const char* url) #endif #ifndef NO_DH -#if defined(WOLFSSL_SP_MATH) && !defined(WOLFSS_SP_MATH_ALL) +#if defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL) /* dh2048 p */ static const unsigned char test_dh_p[] = { @@ -4685,7 +4697,7 @@ static WC_INLINE int myTicketEncCb(WOLFSSL* ssl, mac); #elif defined(HAVE_AESGCM) ret = wc_AesGcmEncrypt(&tickCtx->aes, ticket, ticket, inLen, - iv, GCM_NONCE_MID_SZ, mac, AES_BLOCK_SIZE, + iv, GCM_NONCE_MID_SZ, mac, WC_AES_BLOCK_SIZE, tickCtx->aad, aadSz); #endif } @@ -4699,7 +4711,7 @@ static WC_INLINE int myTicketEncCb(WOLFSSL* ssl, ticket); #elif defined(HAVE_AESGCM) ret = wc_AesGcmDecrypt(&tickCtx->aes, ticket, ticket, inLen, - iv, GCM_NONCE_MID_SZ, mac, AES_BLOCK_SIZE, + iv, GCM_NONCE_MID_SZ, mac, WC_AES_BLOCK_SIZE, tickCtx->aad, aadSz); #endif } diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index b494238..d7a1985 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.7.4" -#define LIBWOLFSSL_VERSION_HEX 0x05007004 +#define LIBWOLFSSL_VERSION_STRING "5.7.6" +#define LIBWOLFSSL_VERSION_HEX 0x05007006 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/aes.h b/src/wolfssl/wolfcrypt/aes.h index eaa0c47..d1b71e5 100644 --- a/src/wolfssl/wolfcrypt/aes.h +++ b/src/wolfssl/wolfcrypt/aes.h @@ -61,7 +61,7 @@ typedef struct Gcm { #endif WOLFSSL_LOCAL void GenerateM0(Gcm* gcm); -#ifdef WOLFSSL_ARMASM +#if !defined(__aarch64__) && defined(WOLFSSL_ARMASM) WOLFSSL_LOCAL void GMULT(byte* X, byte* Y); #endif WOLFSSL_LOCAL void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, @@ -188,7 +188,18 @@ enum { AES_ENCRYPTION_AND_DECRYPTION = 2, #endif - AES_BLOCK_SIZE = 16, + WC_AES_BLOCK_SIZE = 16, +#ifdef OPENSSL_COEXIST + /* allow OPENSSL_COEXIST applications to detect absence of AES_BLOCK_SIZE + * and presence of WC_AES_BLOCK_SIZE. + * + * if WC_NO_COMPAT_AES_BLOCK_SIZE is defined, WC_AES_BLOCK_SIZE is + * available, otherwise AES_BLOCK_SIZE is available. + */ + #define WC_NO_COMPAT_AES_BLOCK_SIZE +#else + #define AES_BLOCK_SIZE WC_AES_BLOCK_SIZE +#endif KEYWRAP_BLOCK_SIZE = 8, @@ -227,9 +238,9 @@ enum { #endif /* Number of bits to a block. */ - #define AES_BLOCK_BITS (AES_BLOCK_SIZE * 8) + #define AES_BLOCK_BITS (WC_AES_BLOCK_SIZE * 8) /* Number of bytes of input that can be processed in one call. */ - #define BS_BLOCK_SIZE (AES_BLOCK_SIZE * BS_WORD_SIZE) + #define BS_BLOCK_SIZE (WC_AES_BLOCK_SIZE * BS_WORD_SIZE) /* Number of words in a block. */ #define BS_BLOCK_WORDS (AES_BLOCK_BITS / BS_WORD_SIZE) @@ -258,7 +269,7 @@ struct Aes { ALIGN16 word32 key[60]; #ifdef WC_AES_BITSLICED /* Extra key schedule space required for bit-slicing technique. */ - ALIGN16 bs_word bs_key[15 * AES_BLOCK_SIZE * BS_WORD_SIZE]; + ALIGN16 bs_word bs_key[15 * WC_AES_BLOCK_SIZE * BS_WORD_SIZE]; #endif word32 rounds; #ifdef WC_C_DYNAMIC_FALLBACK @@ -266,8 +277,8 @@ struct Aes { #endif int keylen; - ALIGN16 word32 reg[AES_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ - ALIGN16 word32 tmp[AES_BLOCK_SIZE / sizeof(word32)]; /* same */ + ALIGN16 word32 reg[WC_AES_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ + ALIGN16 word32 tmp[WC_AES_BLOCK_SIZE / sizeof(word32)]; /* same */ #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) word32 invokeCtr[2]; @@ -293,6 +304,13 @@ struct Aes { #ifdef WOLFSSL_AESNI byte use_aesni; #endif /* WOLFSSL_AESNI */ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + byte use_aes_hw_crypto; +#ifdef HAVE_AESGCM + byte use_pmull_hw_crypto; +#endif +#endif /* __aarch64__ && WOLFSSL_ARMASM && !WOLFSSL_ARMASM_NO_HW_CRYPTO */ #ifdef WOLF_CRYPTO_CB int devId; void* devCtx; @@ -379,7 +397,7 @@ struct Aes { void* heap; /* memory hint to use */ #ifdef WOLFSSL_AESGCM_STREAM #if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_AESNI) - ALIGN16 byte streamData[5 * AES_BLOCK_SIZE]; + ALIGN16 byte streamData[5 * WC_AES_BLOCK_SIZE]; #else byte* streamData; word32 streamData_sz; @@ -408,8 +426,8 @@ struct Aes { #ifdef WOLFSSL_AES_XTS #if FIPS_VERSION3_GE(6,0,0) /* SP800-38E - Restrict data unit to 2^20 blocks per key. A block is - * AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to - * protect up to 1,048,576 blocks of AES_BLOCK_SIZE (16,777,216 bytes) + * WC_AES_BLOCK_SIZE or 16-bytes (128-bits). So each key may only be used to + * protect up to 1,048,576 blocks of WC_AES_BLOCK_SIZE (16,777,216 bytes) */ #define FIPS_AES_XTS_MAX_BYTES_PER_TWEAK 16777216 #endif @@ -423,7 +441,7 @@ struct Aes { #ifdef WOLFSSL_AESXTS_STREAM struct XtsAesStreamData { - byte tweak_block[AES_BLOCK_SIZE]; + byte tweak_block[WC_AES_BLOCK_SIZE]; word32 bytes_crypted_with_this_tweak; }; #endif @@ -768,10 +786,10 @@ struct AesEax { Cmac nonceCmac; Cmac aadCmac; Cmac ciphertextCmac; - byte nonceCmacFinal[AES_BLOCK_SIZE]; - byte aadCmacFinal[AES_BLOCK_SIZE]; - byte ciphertextCmacFinal[AES_BLOCK_SIZE]; - byte prefixBuf[AES_BLOCK_SIZE]; + byte nonceCmacFinal[WC_AES_BLOCK_SIZE]; + byte aadCmacFinal[WC_AES_BLOCK_SIZE]; + byte ciphertextCmacFinal[WC_AES_BLOCK_SIZE]; + byte prefixBuf[WC_AES_BLOCK_SIZE]; }; #endif /* !defined(WOLF_CRYPT_CMAC_H) */ @@ -821,6 +839,59 @@ WOLFSSL_API int wc_AesEaxFree(AesEax* eax); #endif /* WOLFSSL_AES_EAX */ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) +/* GHASH one block of data. + * + * XOR block into tag and GMULT with H. + * + * @param [in, out] aes AES GCM object. + * @param [in] block Block of AAD or cipher text. + */ +#define GHASH_ONE_BLOCK(aes, block) \ + do { \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ + GMULT_AARCH64(AES_TAG(aes), aes->gcm.H); \ + } \ + while (0) + +WOLFSSL_LOCAL int AES_set_key_AARCH64(const unsigned char *userKey, + const int keylen, Aes* aes, int dir); +WOLFSSL_LOCAL void AES_encrypt_AARCH64(const byte* inBlock, byte* outBlock, + byte* key, int nr); +WOLFSSL_LOCAL void AES_decrypt_AARCH64(const byte* inBlock, byte* outBlock, + byte* key, int nr); +WOLFSSL_LOCAL void AES_CBC_encrypt_AARCH64(const byte* in, byte* out, word32 sz, + byte* reg, byte* key, int rounds); +WOLFSSL_LOCAL void AES_CBC_decrypt_AARCH64(const byte* in, byte* out, word32 sz, + byte* reg, byte* key, int rounds); +WOLFSSL_LOCAL void AES_CTR_encrypt_AARCH64(Aes* aes, byte* out, const byte* in, + word32 sz); +WOLFSSL_LOCAL void GMULT_AARCH64(byte* X, byte* Y); +#ifdef WOLFSSL_AESGCM_STREAM +WOLFSSL_LOCAL void GHASH_UPDATE_AARCH64(Aes* aes, const byte* a, word32 aSz, + const byte* c, word32 cSz); +WOLFSSL_LOCAL void AES_GCM_init_AARCH64(Aes* aes, const byte* iv, word32 ivSz); +WOLFSSL_LOCAL void AES_GCM_crypt_update_AARCH64(Aes* aes, byte* out, + const byte* in, word32 sz); +WOLFSSL_LOCAL void AES_GCM_final_AARCH64(Aes* aes, byte* authTag, + word32 authTagSz); +#endif +WOLFSSL_LOCAL void AES_GCM_set_key_AARCH64(Aes* aes, byte* iv); +WOLFSSL_LOCAL void AES_GCM_encrypt_AARCH64(Aes* aes, byte* out, const byte* in, + word32 sz, const byte* iv, word32 ivSz, byte* authTag, word32 authTagSz, + const byte* authIn, word32 authInSz); +WOLFSSL_LOCAL int AES_GCM_decrypt_AARCH64(Aes* aes, byte* out, const byte* in, + word32 sz, const byte* iv, word32 ivSz, const byte* authTag, + word32 authTagSz, const byte* authIn, word32 authInSz); + +#ifdef WOLFSSL_AES_XTS +WOLFSSL_LOCAL void AES_XTS_encrypt_AARCH64(XtsAes* xaes, byte* out, + const byte* in, word32 sz, const byte* i); +WOLFSSL_LOCAL void AES_XTS_decrypt_AARCH64(XtsAes* xaes, byte* out, + const byte* in, word32 sz, const byte* i); +#endif /* WOLFSSL_AES_XTS */ +#endif /* __aarch64__ && WOLFSSL_ARMASM && !WOLFSSL_ARMASM_NO_HW_CRYPTO */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/asn.h b/src/wolfssl/wolfcrypt/asn.h index 11803d6..12a6023 100644 --- a/src/wolfssl/wolfcrypt/asn.h +++ b/src/wolfssl/wolfcrypt/asn.h @@ -36,8 +36,7 @@ that can be serialized and deserialized in a cross-platform way. #include -#ifndef NO_ASN - +#if !defined(NO_ASN) || !defined(NO_PWDBASED) #if !defined(NO_ASN_TIME) && defined(NO_TIME_H) #define NO_ASN_TIME /* backwards compatibility with NO_TIME_H */ @@ -71,6 +70,8 @@ that can be serialized and deserialized in a cross-platform way. extern "C" { #endif +#ifndef NO_ASN + #ifndef EXTERNAL_SERIAL_SIZE #define EXTERNAL_SERIAL_SIZE 32 #endif @@ -728,6 +729,7 @@ enum DN_Tags { /* pilot attribute types * OID values of 0.9.2342.19200300.100.1.* */ ASN_FAVOURITE_DRINK = 0x13, /* favouriteDrink */ + ASN_RFC822_MAILBOX = 0x14, /* rfc822Mailbox */ ASN_DOMAIN_COMPONENT = 0x19 /* DC */ }; @@ -744,7 +746,7 @@ typedef struct WOLFSSL_ObjectInfo { } WOLFSSL_ObjectInfo; extern const size_t wolfssl_object_info_sz; extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; -#endif /* defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) */ +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ /* DN Tag Strings */ #define WOLFSSL_COMMON_NAME "/CN=" @@ -779,6 +781,7 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WOLFSSL_USER_ID "/UID=" #define WOLFSSL_DOMAIN_COMPONENT "/DC=" +#define WOLFSSL_RFC822_MAILBOX "/rfc822Mailbox=" #define WOLFSSL_FAVOURITE_DRINK "/favouriteDrink=" #define WOLFSSL_CONTENT_TYPE "/contentType=" @@ -809,79 +812,198 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WOLFSSL_MAX_NAME_CONSTRAINTS 128 #endif +#define WC_NID_undef 0 + +/* Setup for WC_MAX_RSA_BITS needs to be here, rather than rsa.h, because + * FIPS headers don't have it. And it needs to be here, rather than internal.h, + * so that setup occurs even in cryptonly builds. + */ +#ifndef NO_RSA + #ifndef WC_MAX_RSA_BITS + #ifdef USE_FAST_MATH + /* FP implementation support numbers up to FP_MAX_BITS / 2 bits. */ + #define WC_MAX_RSA_BITS (FP_MAX_BITS / 2) + #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) + /* SP implementation supports numbers of SP_INT_BITS bits. */ + #define WC_MAX_RSA_BITS (((SP_INT_BITS + 7) / 8) * 8) + #else + /* Integer maths is dynamic but we only go up to 4096 bits. */ + #define WC_MAX_RSA_BITS 4096 + #endif + #endif + #if (WC_MAX_RSA_BITS % 8) + #error RSA maximum bit size must be multiple of 8 + #endif +#endif + +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + #define WC_MAX_CERT_VERIFY_SZ 6000 /* For Dilithium */ +#elif defined(WOLFSSL_CERT_EXT) + #define WC_MAX_CERT_VERIFY_SZ 2048 /* For larger extensions */ +#elif !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) + #define WC_MAX_CERT_VERIFY_SZ (WC_MAX_RSA_BITS / 8) /* max RSA bytes */ +#elif defined(HAVE_ECC) + #define WC_MAX_CERT_VERIFY_SZ ECC_MAX_SIG_SIZE /* max ECC */ +#elif defined(HAVE_ED448) + #define WC_MAX_CERT_VERIFY_SZ ED448_SIG_SIZE /* max Ed448 */ +#elif defined(HAVE_ED25519) + #define WC_MAX_CERT_VERIFY_SZ ED25519_SIG_SIZE /* max Ed25519 */ +#else + #define WC_MAX_CERT_VERIFY_SZ 1024 /* max default */ +#endif + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + /* NIDs */ -#define NID_undef 0 -#define NID_netscape_cert_type NID_undef -#define NID_des 66 -#define NID_des3 67 -#define NID_sha256 672 -#define NID_sha384 673 -#define NID_sha512 674 -#define NID_sha512_224 1094 -#define NID_sha512_256 1095 -#define NID_pkcs7_signed 22 -#define NID_pkcs7_enveloped 23 -#define NID_pkcs7_signedAndEnveloped 24 -#define NID_pkcs9_unstructuredName 49 -#define NID_pkcs9_contentType 50 /* 1.2.840.113549.1.9.3 */ -#define NID_pkcs9_challengePassword 54 -#define NID_hw_name_oid 73 -#define NID_id_pkix_OCSP_basic 74 -#define NID_any_policy 75 -#define NID_anyExtendedKeyUsage 76 -#define NID_givenName 100 /* 2.5.4.42 */ -#define NID_initials 101 /* 2.5.4.43 */ -#define NID_title 106 -#define NID_description 107 -#define NID_basic_constraints 133 -#define NID_key_usage 129 /* 2.5.29.15 */ -#define NID_ext_key_usage 151 /* 2.5.29.37 */ -#define NID_subject_key_identifier 128 -#define NID_authority_key_identifier 149 -#define NID_private_key_usage_period 130 /* 2.5.29.16 */ -#define NID_subject_alt_name 131 -#define NID_issuer_alt_name 132 -#define NID_info_access 69 -#define NID_sinfo_access 79 /* id-pe 11 */ -#define NID_name_constraints 144 /* 2.5.29.30 */ -#define NID_crl_distribution_points 145 /* 2.5.29.31 */ -#define NID_certificate_policies 146 -#define NID_policy_mappings 147 -#define NID_policy_constraints 150 -#define NID_inhibit_any_policy 168 /* 2.5.29.54 */ -#define NID_tlsfeature 1020 /* id-pe 24 */ -#define NID_buildingName 1494 - -#define NID_dnQualifier 174 /* 2.5.4.46 */ -#define NID_commonName 14 /* CN Changed to not conflict +#define WC_NID_netscape_cert_type WC_NID_undef +#define WC_NID_des 66 +#define WC_NID_des3 67 +#define WC_NID_sha256 672 +#define WC_NID_sha384 673 +#define WC_NID_sha512 674 +#define WC_NID_sha512_224 1094 +#define WC_NID_sha512_256 1095 +#define WC_NID_pkcs7_signed 22 +#define WC_NID_pkcs7_enveloped 23 +#define WC_NID_pkcs7_signedAndEnveloped 24 +#define WC_NID_pkcs9_emailAddress 48 +#define WC_NID_pkcs9_unstructuredName 49 +#define WC_NID_pkcs9_contentType 50 /* 1.2.840.113549.1.9.3 */ +#define WC_NID_pkcs9_challengePassword 54 +#define WC_NID_hw_name_oid 73 +#define WC_NID_id_pkix_OCSP_basic 74 +#define WC_NID_any_policy 75 +#define WC_NID_anyExtendedKeyUsage 76 +#define WC_NID_givenName 100 /* 2.5.4.42 */ +#define WC_NID_initials 101 /* 2.5.4.43 */ +#define WC_NID_title 106 +#define WC_NID_description 107 +#define WC_NID_basic_constraints 133 +#define WC_NID_key_usage 129 /* 2.5.29.15 */ +#define WC_NID_ext_key_usage 151 /* 2.5.29.37 */ +#define WC_NID_subject_key_identifier 128 +#define WC_NID_authority_key_identifier 149 +#define WC_NID_private_key_usage_period 130 /* 2.5.29.16 */ +#define WC_NID_subject_alt_name 131 +#define WC_NID_issuer_alt_name 132 +#define WC_NID_info_access 69 +#define WC_NID_sinfo_access 79 /* id-pe 11 */ +#define WC_NID_name_constraints 144 /* 2.5.29.30 */ +#define WC_NID_crl_distribution_points 145 /* 2.5.29.31 */ +#define WC_NID_certificate_policies 146 +#define WC_NID_policy_mappings 147 +#define WC_NID_policy_constraints 150 +#define WC_NID_inhibit_any_policy 168 /* 2.5.29.54 */ +#define WC_NID_tlsfeature 1020 /* id-pe 24 */ +#define WC_NID_buildingName 1494 + +#define WC_NID_dnQualifier 174 /* 2.5.4.46 */ +#define WC_NID_commonName 14 /* CN Changed to not conflict * with PBE_SHA1_DES3 */ -#define NID_name 173 /* N , OID = 2.5.4.41 */ -#define NID_surname 0x04 /* SN */ -#define NID_serialNumber 0x05 /* serialNumber */ -#define NID_countryName 0x06 /* C */ -#define NID_localityName 0x07 /* L */ -#define NID_stateOrProvinceName 0x08 /* ST */ -#define NID_streetAddress ASN_STREET_ADDR /* street */ -#define NID_organizationName 0x0a /* O */ -#define NID_organizationalUnitName 0x0b /* OU */ -#define NID_jurisdictionCountryName 0xc -#define NID_jurisdictionStateOrProvinceName 0xd -#define NID_businessCategory ASN_BUS_CAT -#define NID_domainComponent ASN_DOMAIN_COMPONENT -#define NID_postalCode ASN_POSTAL_CODE /* postalCode */ -#define NID_favouriteDrink 462 -#define NID_userId 458 -#define NID_emailAddress 0x30 /* emailAddress */ -#define NID_id_on_dnsSRV 82 /* 1.3.6.1.5.5.7.8.7 */ -#define NID_ms_upn 265 /* 1.3.6.1.4.1.311.20.2.3 */ - -#define NID_X9_62_prime_field 406 /* 1.2.840.10045.1.1 */ -#endif /* OPENSSL_EXTRA */ - -#define NID_id_GostR3410_2001 811 -#define NID_id_GostR3410_2012_256 979 -#define NID_id_GostR3410_2012_512 980 +#define WC_NID_name 173 /* N , OID = 2.5.4.41 */ +#define WC_NID_surname 0x04 /* SN */ +#define WC_NID_serialNumber 0x05 /* serialNumber */ +#define WC_NID_countryName 0x06 /* C */ +#define WC_NID_localityName 0x07 /* L */ +#define WC_NID_stateOrProvinceName 0x08 /* ST */ +#define WC_NID_streetAddress ASN_STREET_ADDR /* street */ +#define WC_NID_organizationName 0x0a /* O */ +#define WC_NID_organizationalUnitName 0x0b /* OU */ +#define WC_NID_jurisdictionCountryName 0xc +#define WC_NID_jurisdictionStateOrProvinceName 0xd +#define WC_NID_businessCategory ASN_BUS_CAT +#define WC_NID_domainComponent ASN_DOMAIN_COMPONENT +#define WC_NID_postalCode ASN_POSTAL_CODE /* postalCode */ +#define WC_NID_rfc822Mailbox 460 +#define WC_NID_favouriteDrink 462 +#define WC_NID_userId 458 +#define WC_NID_registeredAddress 870 +#define WC_NID_emailAddress 0x30 /* emailAddress */ +#define WC_NID_id_on_dnsSRV 82 /* 1.3.6.1.5.5.7.8.7 */ +#define WC_NID_ms_upn 265 /* 1.3.6.1.4.1.311.20.2.3 */ + +#define WC_NID_X9_62_prime_field 406 /* 1.2.840.10045.1.1 */ + +#define WC_NID_id_GostR3410_2001 811 +#define WC_NID_id_GostR3410_2012_256 979 +#define WC_NID_id_GostR3410_2012_512 980 + +#ifndef OPENSSL_COEXIST + +#define NID_undef WC_NID_undef +#define NID_netscape_cert_type WC_NID_netscape_cert_type +#define NID_des WC_NID_des +#define NID_des3 WC_NID_des3 +#define NID_sha256 WC_NID_sha256 +#define NID_sha384 WC_NID_sha384 +#define NID_sha512 WC_NID_sha512 +#define NID_sha512_224 WC_NID_sha512_224 +#define NID_sha512_256 WC_NID_sha512_256 +#define NID_pkcs7_signed WC_NID_pkcs7_signed +#define NID_pkcs7_enveloped WC_NID_pkcs7_enveloped +#define NID_pkcs7_signedAndEnveloped WC_NID_pkcs7_signedAndEnveloped +#define NID_pkcs9_unstructuredName WC_NID_pkcs9_unstructuredName +#define NID_pkcs9_contentType WC_NID_pkcs9_contentType +#define NID_pkcs9_challengePassword WC_NID_pkcs9_challengePassword +#define NID_hw_name_oid WC_NID_hw_name_oid +#define NID_id_pkix_OCSP_basic WC_NID_id_pkix_OCSP_basic +#define NID_any_policy WC_NID_any_policy +#define NID_anyExtendedKeyUsage WC_NID_anyExtendedKeyUsage +#define NID_givenName WC_NID_givenName +#define NID_initials WC_NID_initials +#define NID_title WC_NID_title +#define NID_description WC_NID_description +#define NID_basic_constraints WC_NID_basic_constraints +#define NID_key_usage WC_NID_key_usage +#define NID_ext_key_usage WC_NID_ext_key_usage +#define NID_subject_key_identifier WC_NID_subject_key_identifier +#define NID_authority_key_identifier WC_NID_authority_key_identifier +#define NID_private_key_usage_period WC_NID_private_key_usage_period +#define NID_subject_alt_name WC_NID_subject_alt_name +#define NID_issuer_alt_name WC_NID_issuer_alt_name +#define NID_info_access WC_NID_info_access +#define NID_sinfo_access WC_NID_sinfo_access +#define NID_name_constraints WC_NID_name_constraints +#define NID_crl_distribution_points WC_NID_crl_distribution_points +#define NID_certificate_policies WC_NID_certificate_policies +#define NID_policy_mappings WC_NID_policy_mappings +#define NID_policy_constraints WC_NID_policy_constraints +#define NID_inhibit_any_policy WC_NID_inhibit_any_policy +#define NID_tlsfeature WC_NID_tlsfeature +#define NID_buildingName WC_NID_buildingName + +#define NID_dnQualifier WC_NID_dnQualifier +#define NID_commonName WC_NID_commonName +#define NID_name WC_NID_name +#define NID_surname WC_NID_surname +#define NID_serialNumber WC_NID_serialNumber +#define NID_countryName WC_NID_countryName +#define NID_localityName WC_NID_localityName +#define NID_stateOrProvinceName WC_NID_stateOrProvinceName +#define NID_streetAddress WC_NID_streetAddress +#define NID_organizationName WC_NID_organizationName +#define NID_organizationalUnitName WC_NID_organizationalUnitName +#define NID_jurisdictionCountryName WC_NID_jurisdictionCountryName +#define NID_jurisdictionStateOrProvinceName WC_NID_jurisdictionStateOrProvinceName +#define NID_businessCategory WC_NID_businessCategory +#define NID_domainComponent WC_NID_domainComponent +#define NID_postalCode WC_NID_postalCode +#define NID_rfc822Mailbox WC_NID_rfc822Mailbox +#define NID_favouriteDrink WC_NID_favouriteDrink +#define NID_userId WC_NID_userId +#define NID_emailAddress WC_NID_emailAddress +#define NID_id_on_dnsSRV WC_NID_id_on_dnsSRV +#define NID_ms_upn WC_NID_ms_upn + +#define NID_X9_62_prime_field WC_NID_X9_62_prime_field + +#define NID_id_GostR3410_2001 WC_NID_id_GostR3410_2001 +#define NID_id_GostR3410_2012_256 WC_NID_id_GostR3410_2012_256 +#define NID_id_GostR3410_2012_512 WC_NID_id_GostR3410_2012_512 + +#endif /* !OPENSSL_COEXIST */ + +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ enum ECC_TYPES { @@ -1502,7 +1624,8 @@ struct SignatureCtx { byte* sigCpy; #endif #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ - !defined(NO_DSA) + !defined(NO_DSA) || defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) || \ + defined(HAVE_SPHINCS) int verify; #endif union { @@ -1780,12 +1903,14 @@ struct DecodedCert { #endif #endif /* WOLFSSL_SUBJ_INFO_ACC */ -#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) +#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ + defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) || defined(HAVE_SPHINCS) word32 pkCurveOID; /* Public Key's curve OID */ #ifdef WOLFSSL_CUSTOM_CURVES int pkCurveSize; /* Public Key's curve size */ #endif -#endif /* HAVE_ECC */ +#endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 || HAVE_DILITHIUM || + * HAVE_FALCON || HAVE_SPHINCS */ const byte* beforeDate; int beforeDateLen; const byte* afterDate; @@ -2090,6 +2215,10 @@ struct TrustedPeerCert { #endif /* IGNORE_NAME_CONSTRAINTS */ byte subjectNameHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ + #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER + byte issuerHash[SIGNER_DIGEST_SIZE]; + /* sha hash of issuer name in certificate */ + #endif #ifndef NO_SKID byte subjectKeyIdHash[SIGNER_DIGEST_SIZE]; /* sha hash of SKID in certificate */ @@ -2426,7 +2555,8 @@ WOLFSSL_LOCAL int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen, byte* output, word32 outLen, int keyType, int withHeader); WOLFSSL_LOCAL int DecodeAsymKeyPublic_Assign(const byte* input, word32* inOutIdx, word32 inSz, const byte** pubKey, word32* pubKeyLen, - int keyType); + int* keyType); + WOLFSSL_LOCAL int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz, byte* pubKey, word32* pubKeyLen, int keyType); @@ -2767,12 +2897,6 @@ WOLFSSL_LOCAL int VerifyX509Acert(const byte* cert, word32 certSz, int pubKeyOID, void * heap); #endif /* WOLFSSL_ACERT */ -#ifdef __cplusplus - } /* extern "C" */ -#endif - -#endif /* !NO_ASN */ - #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \ || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \ @@ -2781,7 +2905,8 @@ WOLFSSL_LOCAL int VerifyX509Acert(const byte* cert, word32 certSz, || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS)) WOLFSSL_LOCAL int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, const byte** privKey, word32* privKeyLen, const byte** pubKey, - word32* pubKeyLen, int keyType); + word32* pubKeyLen, int* inOutKeyType); + WOLFSSL_LOCAL int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz, byte* privKey, word32* privKeyLen, byte* pubKey, word32* pubKeyLen, int keyType); @@ -2793,6 +2918,7 @@ WOLFSSL_LOCAL int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, int keyType); #endif +#endif /* !NO_ASN */ #if !defined(NO_ASN) || !defined(NO_PWDBASED) @@ -2842,4 +2968,10 @@ enum PKCSTypes { #endif /* !NO_ASN || !NO_PWDBASED */ +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* !NO_ASN || !NO_PWDBASED */ + #endif /* WOLF_CRYPT_ASN_H */ diff --git a/src/wolfssl/wolfcrypt/asn_public.h b/src/wolfssl/wolfcrypt/asn_public.h index b8bbce4..1196c6a 100644 --- a/src/wolfssl/wolfcrypt/asn_public.h +++ b/src/wolfssl/wolfcrypt/asn_public.h @@ -841,12 +841,16 @@ WOLFSSL_API int wc_Curve25519PrivateKeyDecode( const byte* input, word32* inOutIdx, curve25519_key* key, word32 inSz); WOLFSSL_API int wc_Curve25519PublicKeyDecode( const byte* input, word32* inOutIdx, curve25519_key* key, word32 inSz); +WOLFSSL_API int wc_Curve25519KeyDecode(const byte *input, word32 *inOutIdx, + curve25519_key *key, word32 inSz); #endif #ifdef HAVE_CURVE25519_KEY_EXPORT WOLFSSL_API int wc_Curve25519PrivateKeyToDer( curve25519_key* key, byte* output, word32 inLen); WOLFSSL_API int wc_Curve25519PublicKeyToDer( curve25519_key* key, byte* output, word32 inLen, int withAlg); +WOLFSSL_API int wc_Curve25519KeyToDer(curve25519_key* key, byte* output, + word32 inLen, int withAlg); #endif #endif /* HAVE_CURVE25519 */ diff --git a/src/wolfssl/wolfcrypt/camellia.h b/src/wolfssl/wolfcrypt/camellia.h index bdba23b..efd187e 100644 --- a/src/wolfssl/wolfcrypt/camellia.h +++ b/src/wolfssl/wolfcrypt/camellia.h @@ -63,34 +63,49 @@ #endif enum { - CAMELLIA_BLOCK_SIZE = 16 + WC_CAMELLIA_BLOCK_SIZE = 16 }; -#define CAMELLIA_TABLE_BYTE_LEN 272 -#define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / sizeof(word32)) +#define WC_CAMELLIA_TABLE_BYTE_LEN 272 +#define WC_CAMELLIA_TABLE_WORD_LEN (WC_CAMELLIA_TABLE_BYTE_LEN / sizeof(word32)) -typedef word32 KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN]; +typedef word32 WC_CAMELLIA_KEY_TABLE_TYPE[WC_CAMELLIA_TABLE_WORD_LEN]; -typedef struct Camellia { +typedef struct wc_Camellia { word32 keySz; - KEY_TABLE_TYPE key; - word32 reg[CAMELLIA_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ - word32 tmp[CAMELLIA_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ -} Camellia; + WC_CAMELLIA_KEY_TABLE_TYPE key; + word32 reg[WC_CAMELLIA_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ + word32 tmp[WC_CAMELLIA_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ +} wc_Camellia; -WOLFSSL_API int wc_CamelliaSetKey(Camellia* cam, +WOLFSSL_API int wc_CamelliaSetKey(wc_Camellia* cam, const byte* key, word32 len, const byte* iv); -WOLFSSL_API int wc_CamelliaSetIV(Camellia* cam, const byte* iv); -WOLFSSL_API int wc_CamelliaEncryptDirect(Camellia* cam, byte* out, +WOLFSSL_API int wc_CamelliaSetIV(wc_Camellia* cam, const byte* iv); +WOLFSSL_API int wc_CamelliaEncryptDirect(wc_Camellia* cam, byte* out, const byte* in); -WOLFSSL_API int wc_CamelliaDecryptDirect(Camellia* cam, byte* out, +WOLFSSL_API int wc_CamelliaDecryptDirect(wc_Camellia* cam, byte* out, const byte* in); -WOLFSSL_API int wc_CamelliaCbcEncrypt(Camellia* cam, +WOLFSSL_API int wc_CamelliaCbcEncrypt(wc_Camellia* cam, byte* out, const byte* in, word32 sz); -WOLFSSL_API int wc_CamelliaCbcDecrypt(Camellia* cam, +WOLFSSL_API int wc_CamelliaCbcDecrypt(wc_Camellia* cam, byte* out, const byte* in, word32 sz); +#ifndef OPENSSL_COEXIST + +enum { + CAMELLIA_BLOCK_SIZE = WC_CAMELLIA_BLOCK_SIZE +}; + +#define CAMELLIA_TABLE_BYTE_LEN WC_CAMELLIA_TABLE_BYTE_LEN +#define CAMELLIA_TABLE_WORD_LEN WC_CAMELLIA_TABLE_WORD_LEN + +typedef word32 KEY_TABLE_TYPE[WC_CAMELLIA_TABLE_WORD_LEN]; + +typedef struct wc_Camellia Camellia; + +#endif /* !OPENSSL_COEXIST */ + #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/cmac.h b/src/wolfssl/wolfcrypt/cmac.h index a1c05f9..3dc6d9c 100644 --- a/src/wolfssl/wolfcrypt/cmac.h +++ b/src/wolfssl/wolfcrypt/cmac.h @@ -54,10 +54,10 @@ typedef enum CmacType { struct Cmac { #ifndef NO_AES Aes aes; - byte buffer[AES_BLOCK_SIZE]; /* partially stored block */ - byte digest[AES_BLOCK_SIZE]; /* running digest */ - byte k1[AES_BLOCK_SIZE]; - byte k2[AES_BLOCK_SIZE]; + byte buffer[WC_AES_BLOCK_SIZE]; /* partially stored block */ + byte digest[WC_AES_BLOCK_SIZE]; /* running digest */ + byte k1[WC_AES_BLOCK_SIZE]; + byte k2[WC_AES_BLOCK_SIZE]; #endif word32 bufferSz; word32 totalSz; @@ -86,8 +86,8 @@ struct Cmac { #ifndef NO_AES -#define WC_CMAC_TAG_MAX_SZ AES_BLOCK_SIZE -#define WC_CMAC_TAG_MIN_SZ (AES_BLOCK_SIZE/4) +#define WC_CMAC_TAG_MAX_SZ WC_AES_BLOCK_SIZE +#define WC_CMAC_TAG_MIN_SZ (WC_AES_BLOCK_SIZE/4) #else /* Reasonable defaults */ #define WC_CMAC_TAG_MAX_SZ 16 diff --git a/src/wolfssl/wolfcrypt/cpuid.h b/src/wolfssl/wolfcrypt/cpuid.h index c91b628..b7a5714 100644 --- a/src/wolfssl/wolfcrypt/cpuid.h +++ b/src/wolfssl/wolfcrypt/cpuid.h @@ -38,6 +38,11 @@ #define HAVE_CPUID #define HAVE_CPUID_INTEL #endif +#if (defined(WOLFSSL_AARCH64_BUILD) || (defined(__aarch64__) && \ + defined(WOLFSSL_ARMASM))) && !defined(WOLFSSL_NO_ASM) + #define HAVE_CPUID + #define HAVE_CPUID_AARCH64 +#endif #ifdef HAVE_CPUID_INTEL @@ -63,6 +68,26 @@ #define IS_INTEL_BMI1(f) ((f) & CPUID_BMI1) #define IS_INTEL_SHA(f) ((f) & CPUID_SHA) +#elif defined(HAVE_CPUID_AARCH64) + + #define CPUID_AES 0x0001 + #define CPUID_PMULL 0x0002 + #define CPUID_SHA256 0x0004 + #define CPUID_SHA512 0x0008 + #define CPUID_RDM 0x0010 + #define CPUID_SHA3 0x0020 + #define CPUID_SM3 0x0040 + #define CPUID_SM4 0x0080 + + #define IS_AARCH64_AES(f) ((f) & CPUID_AES) + #define IS_AARCH64_PMULL(f) ((f) & CPUID_PMULL) + #define IS_AARCH64_SHA256(f) ((f) & CPUID_SHA256) + #define IS_AARCH64_SHA512(f) ((f) & CPUID_SHA512) + #define IS_AARCH64_RDM(f) ((f) & CPUID_RDM) + #define IS_AARCH64_SHA3(f) ((f) & CPUID_SHA3) + #define IS_AARCH64_SM3(f) ((f) & CPUID_SM3) + #define IS_AARCH64_SM4(f) ((f) & CPUID_SM4) + #endif #ifdef HAVE_CPUID diff --git a/src/wolfssl/wolfcrypt/cryptocb.h b/src/wolfssl/wolfcrypt/cryptocb.h index 4ec42ec..976332f 100644 --- a/src/wolfssl/wolfcrypt/cryptocb.h +++ b/src/wolfssl/wolfcrypt/cryptocb.h @@ -50,6 +50,9 @@ #ifndef NO_SHA256 #include #endif +#ifdef WOLFSSL_SHA3 + #include +#endif #ifndef NO_HMAC #include #endif @@ -101,12 +104,12 @@ enum wc_CryptoCbCmdType { /* Crypto Information Structure for callbacks */ typedef struct wc_CryptoInfo { int algo_type; /* enum wc_AlgoType */ -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES union { #endif struct { int type; /* enum wc_PkType */ -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES union { #endif #ifndef NO_RSA @@ -276,7 +279,7 @@ typedef struct wc_CryptoInfo { int type; /* enum wc_PqcSignatureType */ } pqc_sig_check; #endif -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES }; #endif } pk; @@ -284,7 +287,7 @@ typedef struct wc_CryptoInfo { struct { int type; /* enum wc_CipherType */ int enc; -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES union { #endif #ifdef HAVE_AESGCM @@ -372,7 +375,7 @@ typedef struct wc_CryptoInfo { } des3; #endif void* ctx; -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES }; #endif } cipher; @@ -384,7 +387,7 @@ typedef struct wc_CryptoInfo { const byte* in; word32 inSz; byte* digest; -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES union { #endif #ifndef NO_SHA @@ -406,7 +409,7 @@ typedef struct wc_CryptoInfo { wc_Sha3* sha3; #endif void* ctx; -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES }; #endif } hash; @@ -445,13 +448,25 @@ typedef struct wc_CryptoInfo { int type; } cmac; #endif +#ifndef NO_CERTS + struct { + const byte *id; + word32 idLen; + const char *label; + word32 labelLen; + byte **certDataOut; + word32 *certSz; + int *certFormatOut; + void *heap; + } cert; +#endif #ifdef WOLF_CRYPTO_CB_CMD struct { /* uses wc_AlgoType=ALGO_NONE */ int type; /* enum wc_CryptoCbCmdType */ void *ctx; } cmd; #endif -#if HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifdef HAVE_ANONYMOUS_INLINE_AGGREGATES }; #endif } wc_CryptoInfo; @@ -654,6 +669,12 @@ WOLFSSL_LOCAL int wc_CryptoCb_Cmac(Cmac* cmac, const byte* key, word32 keySz, void* ctx); #endif +#ifndef NO_CERTS +WOLFSSL_LOCAL int wc_CryptoCb_GetCert(int devId, const char *label, + word32 labelLen, const byte *id, word32 idLen, byte** out, + word32* outSz, int *format, void *heap); +#endif + #endif /* WOLF_CRYPTO_CB */ #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/dilithium.h b/src/wolfssl/wolfcrypt/dilithium.h index 6e9cfb6..c43bc7e 100644 --- a/src/wolfssl/wolfcrypt/dilithium.h +++ b/src/wolfssl/wolfcrypt/dilithium.h @@ -114,37 +114,55 @@ #define DILITHIUM_LEVEL2_PUB_KEY_SIZE 1312 #define DILITHIUM_LEVEL2_PRV_KEY_SIZE \ (DILITHIUM_LEVEL2_PUB_KEY_SIZE + DILITHIUM_LEVEL2_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE 1334 +#define DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE 2588 #define DILITHIUM_LEVEL3_KEY_SIZE 4032 #define DILITHIUM_LEVEL3_SIG_SIZE 3309 #define DILITHIUM_LEVEL3_PUB_KEY_SIZE 1952 #define DILITHIUM_LEVEL3_PRV_KEY_SIZE \ (DILITHIUM_LEVEL3_PUB_KEY_SIZE + DILITHIUM_LEVEL3_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE 1974 +#define DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE 4060 + #define DILITHIUM_LEVEL5_KEY_SIZE 4896 #define DILITHIUM_LEVEL5_SIG_SIZE 4627 #define DILITHIUM_LEVEL5_PUB_KEY_SIZE 2592 #define DILITHIUM_LEVEL5_PRV_KEY_SIZE \ (DILITHIUM_LEVEL5_PUB_KEY_SIZE + DILITHIUM_LEVEL5_KEY_SIZE) - +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 +#define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 #define ML_DSA_LEVEL2_KEY_SIZE 2560 #define ML_DSA_LEVEL2_SIG_SIZE 2420 #define ML_DSA_LEVEL2_PUB_KEY_SIZE 1312 #define ML_DSA_LEVEL2_PRV_KEY_SIZE \ (ML_DSA_LEVEL2_PUB_KEY_SIZE + ML_DSA_LEVEL2_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL2_PUB_KEY_DER_SIZE DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL2_PRV_KEY_DER_SIZE DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL3_KEY_SIZE 4032 #define ML_DSA_LEVEL3_SIG_SIZE 3309 #define ML_DSA_LEVEL3_PUB_KEY_SIZE 1952 #define ML_DSA_LEVEL3_PRV_KEY_SIZE \ (ML_DSA_LEVEL3_PUB_KEY_SIZE + ML_DSA_LEVEL3_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL3_PUB_KEY_DER_SIZE DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL3_PRV_KEY_DER_SIZE DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL5_KEY_SIZE 4896 #define ML_DSA_LEVEL5_SIG_SIZE 4627 #define ML_DSA_LEVEL5_PUB_KEY_SIZE 2592 #define ML_DSA_LEVEL5_PRV_KEY_SIZE \ (ML_DSA_LEVEL5_PUB_KEY_SIZE + ML_DSA_LEVEL5_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE @@ -503,18 +521,27 @@ #define DILITHIUM_LEVEL2_PUB_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_public_key #define DILITHIUM_LEVEL2_PRV_KEY_SIZE \ (DILITHIUM_LEVEL2_PUB_KEY_SIZE+DILITHIUM_LEVEL2_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE 1334 +#define DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE 2588 #define DILITHIUM_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key #define DILITHIUM_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature #define DILITHIUM_LEVEL3_PUB_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_public_key #define DILITHIUM_LEVEL3_PRV_KEY_SIZE \ (DILITHIUM_LEVEL3_PUB_KEY_SIZE+DILITHIUM_LEVEL3_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE 1974 +#define DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE 4060 #define DILITHIUM_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key #define DILITHIUM_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature #define DILITHIUM_LEVEL5_PUB_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_public_key #define DILITHIUM_LEVEL5_PRV_KEY_SIZE \ (DILITHIUM_LEVEL5_PUB_KEY_SIZE+DILITHIUM_LEVEL5_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 +#define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 #define ML_DSA_LEVEL2_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_secret_key @@ -522,18 +549,27 @@ #define ML_DSA_LEVEL2_PUB_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_public_key #define ML_DSA_LEVEL2_PRV_KEY_SIZE \ (ML_DSA_LEVEL2_PUB_KEY_SIZE+ML_DSA_LEVEL2_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL2_PUB_KEY_DER_SIZE DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL2_PRV_KEY_DER_SIZE DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key #define ML_DSA_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature #define ML_DSA_LEVEL3_PUB_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_public_key #define ML_DSA_LEVEL3_PRV_KEY_SIZE \ (ML_DSA_LEVEL3_PUB_KEY_SIZE+ML_DSA_LEVEL3_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL3_PUB_KEY_DER_SIZE DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL3_PRV_KEY_DER_SIZE DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key #define ML_DSA_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature #define ML_DSA_LEVEL5_PUB_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_public_key #define ML_DSA_LEVEL5_PRV_KEY_SIZE \ (ML_DSA_LEVEL5_PUB_KEY_SIZE+ML_DSA_LEVEL5_KEY_SIZE) +/* Buffer sizes large enough to store exported DER encoded keys */ +#define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE +#define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE #endif @@ -541,6 +577,10 @@ #define DILITHIUM_MAX_SIG_SIZE DILITHIUM_LEVEL5_SIG_SIZE #define DILITHIUM_MAX_PUB_KEY_SIZE DILITHIUM_LEVEL5_PUB_KEY_SIZE #define DILITHIUM_MAX_PRV_KEY_SIZE DILITHIUM_LEVEL5_PRV_KEY_SIZE +/* Buffer sizes large enough to store exported DER encoded keys */ +#define DILITHIUM_MAX_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE +#define DILITHIUM_MAX_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE + #ifdef WOLF_PRIVATE_KEY_ID #define DILITHIUM_MAX_ID_LEN 32 @@ -854,9 +894,9 @@ WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, #define wc_MlDsaKey_Verify(key, sig, sigSz, msg, msgSz, res) \ wc_dilithium_verify_msg(sig, sigSz, msg, msgSz, res, key) -int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len); -int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len); -int wc_MlDsaKey_GetSigLen(MlDsaKey* key, int* len); +WOLFSSL_API int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len); +WOLFSSL_API int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len); +WOLFSSL_API int wc_MlDsaKey_GetSigLen(MlDsaKey* key, int* len); #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/error-crypt.h b/src/wolfssl/wolfcrypt/error-crypt.h index 3f188f7..5668783 100644 --- a/src/wolfssl/wolfcrypt/error-crypt.h +++ b/src/wolfssl/wolfcrypt/error-crypt.h @@ -46,9 +46,15 @@ enum wolfCrypt_ErrorCodes { /* note that WOLFSSL_FATAL_ERROR is defined as -1 in error-ssl.h, for * reasons of backward compatibility. */ + WC_FAILURE = -1, /* Generic but traceable back compat errcode. + * Note, not reflected in MAX_CODE_E or + * WC_FIRST_E. + */ - MAX_CODE_E = -96, /* errors -97 - -299 */ - WC_FIRST_E = -97, /* errors -97 - -299 */ + MAX_CODE_E = -96, /* WC_FIRST_E + 1, for backward compat. */ + WC_FIRST_E = -97, /* First code used for wolfCrypt */ + + WC_SPAN1_FIRST_E = -97, /* errors -97 - -300 */ MP_MEM = -97, /* MP dynamic memory allocation failed. */ MP_VAL = -98, /* MP value passed is not able to be used. */ @@ -290,13 +296,32 @@ enum wolfCrypt_ErrorCodes { SM4_GCM_AUTH_E = -298, /* SM4-GCM Authentication check failure */ SM4_CCM_AUTH_E = -299, /* SM4-CCM Authentication check failure */ - WC_LAST_E = -299, /* Update this to indicate last error */ - MIN_CODE_E = -300 /* errors -2 - -299 */ + WC_SPAN1_LAST_E = -299, /* Last used code in span 1 */ + WC_SPAN1_MIN_CODE_E = -300, /* Last usable code in span 1 */ + + WC_SPAN2_FIRST_E = -1000, + + DEADLOCK_AVERTED_E = -1000, /* Deadlock averted -- retry the call */ + + WC_SPAN2_LAST_E = -1000, /* Update to indicate last used error code */ + WC_SPAN2_MIN_CODE_E = -1999, /* Last usable code in span 2 */ + + WC_LAST_E = -1000, /* the last code used either here or in + * error-ssl.h + */ + + MIN_CODE_E = -1999 /* the last code allocated either here or in + * error-ssl.h + */ /* add new companion error id strings for any new error codes wolfcrypt/src/error.c !!! */ }; +wc_static_assert((int)WC_LAST_E <= (int)WC_SPAN2_LAST_E); +wc_static_assert((int)MIN_CODE_E <= (int)WC_LAST_E); +wc_static_assert((int)MIN_CODE_E <= (int)WC_SPAN2_MIN_CODE_E); + #ifdef NO_ERROR_STRINGS #define wc_GetErrorString(error) "no support for error strings built in" #define wc_ErrorString(err, buf) \ diff --git a/src/wolfssl/wolfcrypt/ge_448.h b/src/wolfssl/wolfcrypt/ge_448.h index bbdb067..a9d4d47 100644 --- a/src/wolfssl/wolfcrypt/ge_448.h +++ b/src/wolfssl/wolfcrypt/ge_448.h @@ -65,6 +65,7 @@ WOLFSSL_LOCAL int ge448_from_bytes_negate_vartime(ge448_p2 *r, const byte *b); WOLFSSL_LOCAL int ge448_double_scalarmult_vartime(ge448_p2 *r, const byte *a, const ge448_p2 *A, const byte *b); WOLFSSL_LOCAL int ge448_scalarmult_base(ge448_p2* h, const byte* a); +/* Only performs a weak reduce. */ WOLFSSL_LOCAL void sc448_reduce(byte* b); WOLFSSL_LOCAL void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d); WOLFSSL_LOCAL void ge448_to_bytes(byte *s, const ge448_p2 *h); diff --git a/src/wolfssl/wolfcrypt/hash.h b/src/wolfssl/wolfcrypt/hash.h index edbc949..ee001a9 100644 --- a/src/wolfssl/wolfcrypt/hash.h +++ b/src/wolfssl/wolfcrypt/hash.h @@ -119,6 +119,7 @@ typedef union { #ifdef WOLFSSL_SM3 wc_Sm3 sm3; #endif + WOLF_AGG_DUMMY_MEMBER; } wc_Hashes; #ifndef NO_HASH_WRAPPER diff --git a/src/wolfssl/wolfcrypt/hpke.h b/src/wolfssl/wolfcrypt/hpke.h index 6e406ba..3bf61e5 100644 --- a/src/wolfssl/wolfcrypt/hpke.h +++ b/src/wolfssl/wolfcrypt/hpke.h @@ -42,7 +42,7 @@ enum { DHKEM_P384_HKDF_SHA384 = 0x0011, DHKEM_P521_HKDF_SHA512 = 0x0012, DHKEM_X25519_HKDF_SHA256 = 0x0020, - DHKEM_X448_HKDF_SHA512 = 0x0021, + DHKEM_X448_HKDF_SHA512 = 0x0021 }; #define DHKEM_P256_ENC_LEN 65 @@ -55,13 +55,13 @@ enum { enum { HKDF_SHA256 = 0x0001, HKDF_SHA384 = 0x0002, - HKDF_SHA512 = 0x0003, + HKDF_SHA512 = 0x0003 }; /* AEAD enum */ enum { HPKE_AES_128_GCM = 0x0001, - HPKE_AES_256_GCM = 0x0002, + HPKE_AES_256_GCM = 0x0002 }; /* TODO better way of doing this */ diff --git a/src/wolfssl/wolfcrypt/integer.h b/src/wolfssl/wolfcrypt/integer.h index 927a1f6..e98cd35 100644 --- a/src/wolfssl/wolfcrypt/integer.h +++ b/src/wolfssl/wolfcrypt/integer.h @@ -222,8 +222,8 @@ typedef int mp_err; #define WOLF_BIGINT_DEFINED #endif -#define mp_size_t int -#define mp_sign_t int +#define wc_mp_size_t int +#define wc_mp_sign_t int /* the mp_int structure */ typedef struct mp_int { diff --git a/src/wolfssl/wolfcrypt/kyber.h b/src/wolfssl/wolfcrypt/kyber.h index 93b5022..3fb1a23 100644 --- a/src/wolfssl/wolfcrypt/kyber.h +++ b/src/wolfssl/wolfcrypt/kyber.h @@ -153,9 +153,14 @@ enum { /* Types of Kyber keys. */ - KYBER512 = 0, - KYBER768 = 1, - KYBER1024 = 2, + WC_ML_KEM_512 = 0, + WC_ML_KEM_768 = 1, + WC_ML_KEM_1024 = 2, + + KYBER_ORIGINAL = 0x10, + KYBER512 = 0 | KYBER_ORIGINAL, + KYBER768 = 1 | KYBER_ORIGINAL, + KYBER1024 = 2 | KYBER_ORIGINAL, KYBER_LEVEL1 = KYBER512, KYBER_LEVEL3 = KYBER768, @@ -215,30 +220,48 @@ WOLFSSL_API int wc_KyberKey_EncodePublicKey(KyberKey* key, unsigned char* out, +#if !defined(WOLFSSL_NO_ML_KEM_512) && !defined(WOLFSSL_NO_ML_KEM) +#define WOLFSSL_WC_ML_KEM_512 +#endif +#if !defined(WOLFSSL_NO_ML_KEM_768) && !defined(WOLFSSL_NO_ML_KEM) +#define WOLFSSL_WC_ML_KEM_768 +#endif +#if !defined(WOLFSSL_NO_ML_KEM_1024) && !defined(WOLFSSL_NO_ML_KEM) +#define WOLFSSL_WC_ML_KEM_1024 +#endif + +#ifdef WOLFSSL_WC_ML_KEM_512 #define WC_ML_KEM_512_K KYBER512_K #define WC_ML_KEM_512_PUBLIC_KEY_SIZE KYBER512_PUBLIC_KEY_SIZE -#define wC_ML_KEM_512_PRIVATE_KEY_SIZE KYBER512_PRIVATE_KEY_SIZE -#define wC_ML_KEM_512_CIPHER_TEXT_SIZE KYBER512_CIPHER_TEXT_SIZE +#define WC_ML_KEM_512_PRIVATE_KEY_SIZE KYBER512_PRIVATE_KEY_SIZE +#define WC_ML_KEM_512_CIPHER_TEXT_SIZE KYBER512_CIPHER_TEXT_SIZE +#define WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ \ + KYBER512_POLY_VEC_COMPRESSED_SZ +#endif +#ifdef WOLFSSL_WC_ML_KEM_768 #define WC_ML_KEM_768_K KYBER768_K #define WC_ML_KEM_768_PUBLIC_KEY_SIZE KYBER768_PUBLIC_KEY_SIZE -#define wC_ML_KEM_768_PRIVATE_KEY_SIZE KYBER768_PRIVATE_KEY_SIZE -#define wC_ML_KEM_768_CIPHER_TEXT_SIZE KYBER768_CIPHER_TEXT_SIZE +#define WC_ML_KEM_768_PRIVATE_KEY_SIZE KYBER768_PRIVATE_KEY_SIZE +#define WC_ML_KEM_768_CIPHER_TEXT_SIZE KYBER768_CIPHER_TEXT_SIZE +#define WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ \ + KYBER768_POLY_VEC_COMPRESSED_SZ +#endif +#ifdef WOLFSSL_WC_ML_KEM_1024 #define WC_ML_KEM_1024_K KYBER1024_K #define WC_ML_KEM_1024_PUBLIC_KEY_SIZE KYBER1024_PUBLIC_KEY_SIZE -#define wC_ML_KEM_1024_PRIVATE_KEY_SIZE KYBER1024_PRIVATE_KEY_SIZE -#define wC_ML_KEM_1024_CIPHER_TEXT_SIZE KYBER1024_CIPHER_TEXT_SIZE +#define WC_ML_KEM_1024_PRIVATE_KEY_SIZE KYBER1024_PRIVATE_KEY_SIZE +#define WC_ML_KEM_1024_CIPHER_TEXT_SIZE KYBER1024_CIPHER_TEXT_SIZE +#define WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ \ + KYBER1024_POLY_VEC_COMPRESSED_SZ +#endif #define WC_ML_KEM_MAX_K KYBER_MAX_K #define WC_ML_KEM_MAX_PRIVATE_KEY_SIZE KYBER_MAX_PRIVATE_KEY_SIZE #define WC_ML_KEM_MAX_PUBLIC_KEY_SIZE KYBER_MAX_PUBLIC_KEY_SIZE #define WC_ML_KEM_MAX_CIPHER_TEXT_SIZE KYBER_MAX_CIPHER_TEXT_SIZE -#define WC_ML_KEM_512 KYBER512 -#define WC_ML_KEM_768 KYBER768 -#define WC_ML_KEM_1024 KYBER1024 - #define WC_ML_KEM_SYM_SZ KYBER_SYM_SZ #define WC_ML_KEM_SS_SZ KYBER_SS_SZ #define WC_ML_KEM_MAKEKEY_RAND_SZ KYBER_MAKEKEY_RAND_SZ diff --git a/src/wolfssl/wolfcrypt/logging.h b/src/wolfssl/wolfcrypt/logging.h index 7d349fe..a60f70b 100644 --- a/src/wolfssl/wolfcrypt/logging.h +++ b/src/wolfssl/wolfcrypt/logging.h @@ -178,7 +178,11 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); WOLFSSL_API void WOLFSSL_MSG_EX(const char* fmt, ...); #define HAVE_WOLFSSL_MSG_EX #else - #define WOLFSSL_MSG_EX(...) WC_DO_NOTHING + #ifdef WOLF_NO_VARIADIC_MACROS + #define WOLFSSL_MSG_EX() WC_DO_NOTHING + #else + #define WOLFSSL_MSG_EX(...) WC_DO_NOTHING + #endif #endif WOLFSSL_API void WOLFSSL_MSG(const char* msg); #ifdef WOLFSSL_DEBUG_CODEPOINTS @@ -197,7 +201,11 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); #define WOLFSSL_MSG_EX(fmt, args...) \ WOLFSSL_MSG_EX2(__FILE__, __LINE__, fmt, ## args) #else - #define WOLFSSL_MSG_EX2(...) WC_DO_NOTHING + #ifdef WOLF_NO_VARIADIC_MACROS + #define WOLFSSL_MSG_EX2() WC_DO_NOTHING + #else + #define WOLFSSL_MSG_EX2(...) WC_DO_NOTHING + #endif #endif #endif WOLFSSL_API void WOLFSSL_BUFFER(const byte* buffer, word32 length); @@ -209,7 +217,14 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); #define WOLFSSL_STUB(m) WC_DO_NOTHING #define WOLFSSL_IS_DEBUG_ON() 0 - #define WOLFSSL_MSG_EX(...) WC_DO_NOTHING + #ifdef WOLF_NO_VARIADIC_MACROS + /* note, modern preprocessors will generate errors with this definition. + * "error: macro "WOLFSSL_MSG_EX" passed 2 arguments, but takes just 0" + */ + #define WOLFSSL_MSG_EX() WC_DO_NOTHING + #else + #define WOLFSSL_MSG_EX(...) WC_DO_NOTHING + #endif #define WOLFSSL_MSG(m) WC_DO_NOTHING #define WOLFSSL_BUFFER(b, l) WC_DO_NOTHING @@ -221,8 +236,13 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); #ifdef WOLFSSL_HAVE_ERROR_QUEUE WOLFSSL_API void WOLFSSL_ERROR_LINE(int err, const char* func, unsigned int line, const char* file, void* ctx); - #define WOLFSSL_ERROR(x) \ - WOLFSSL_ERROR_LINE((x), __func__, __LINE__, __FILE__, NULL) + #ifdef WOLF_C89 + #define WOLFSSL_ERROR(x) \ + WOLFSSL_ERROR_LINE((x), __FILE__, __LINE__, __FILE__, NULL) + #else + #define WOLFSSL_ERROR(x) \ + WOLFSSL_ERROR_LINE((x), __func__, __LINE__, __FILE__, NULL) + #endif #else WOLFSSL_API void WOLFSSL_ERROR(int err); #endif /* WOLFSSL_HAVE_ERROR_QUEUE */ diff --git a/src/wolfssl/wolfcrypt/md2.h b/src/wolfssl/wolfcrypt/md2.h index fe92756..73be110 100644 --- a/src/wolfssl/wolfcrypt/md2.h +++ b/src/wolfssl/wolfcrypt/md2.h @@ -37,28 +37,42 @@ /* in bytes */ enum { - MD2 = WC_HASH_TYPE_MD2, - MD2_BLOCK_SIZE = 16, - MD2_DIGEST_SIZE = 16, - MD2_PAD_SIZE = 16, - MD2_X_SIZE = 48 + WC_MD2_BLOCK_SIZE = 16, + WC_MD2_DIGEST_SIZE = 16, + WC_MD2_PAD_SIZE = 16, + WC_MD2_X_SIZE = 48 }; /* Md2 digest */ -typedef struct Md2 { +typedef struct wc_Md2 { word32 count; /* bytes % PAD_SIZE */ - byte X[MD2_X_SIZE]; - byte C[MD2_BLOCK_SIZE]; - byte buffer[MD2_BLOCK_SIZE]; -} Md2; + byte X[WC_MD2_X_SIZE]; + byte C[WC_MD2_BLOCK_SIZE]; + byte buffer[WC_MD2_BLOCK_SIZE]; +} wc_Md2; -WOLFSSL_API void wc_InitMd2(Md2* md2); -WOLFSSL_API void wc_Md2Update(Md2* md2, const byte* data, word32 len); -WOLFSSL_API void wc_Md2Final(Md2* md2, byte* hash); +WOLFSSL_API void wc_InitMd2(wc_Md2* md2); +WOLFSSL_API void wc_Md2Update(wc_Md2* md2, const byte* data, word32 len); +WOLFSSL_API void wc_Md2Final(wc_Md2* md2, byte* hash); WOLFSSL_API int wc_Md2Hash(const byte* data, word32 len, byte* hash); +#ifndef OPENSSL_COEXIST + +enum { + MD2 = WC_HASH_TYPE_MD2, + MD2_BLOCK_SIZE = WC_MD2_BLOCK_SIZE, + MD2_DIGEST_SIZE = WC_MD2_DIGEST_SIZE, + MD2_PAD_SIZE = WC_MD2_PAD_SIZE, + MD2_X_SIZE = WC_MD2_X_SIZE +}; + + +/* Md2 digest */ +typedef struct wc_Md2 Md2; + +#endif /* !OPENSSL_COEXIST */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/wolfcrypt/md4.h b/src/wolfssl/wolfcrypt/md4.h index c4bd266..b253f8d 100644 --- a/src/wolfssl/wolfcrypt/md4.h +++ b/src/wolfssl/wolfcrypt/md4.h @@ -36,26 +36,36 @@ /* in bytes */ enum { - MD4 = WC_HASH_TYPE_MD4, - MD4_BLOCK_SIZE = 64, - MD4_DIGEST_SIZE = 16, - MD4_PAD_SIZE = 56 + WC_MD4_BLOCK_SIZE = 64, + WC_MD4_DIGEST_SIZE = 16, + WC_MD4_PAD_SIZE = 56 }; - /* MD4 digest */ -typedef struct Md4 { +typedef struct wc_Md4 { word32 buffLen; /* in bytes */ word32 loLen; /* length in bytes */ word32 hiLen; /* length in bytes */ - word32 digest[MD4_DIGEST_SIZE / sizeof(word32)]; - word32 buffer[MD4_BLOCK_SIZE / sizeof(word32)]; -} Md4; + word32 digest[WC_MD4_DIGEST_SIZE / sizeof(word32)]; + word32 buffer[WC_MD4_BLOCK_SIZE / sizeof(word32)]; +} wc_Md4; + +WOLFSSL_API void wc_InitMd4(wc_Md4* md4); +WOLFSSL_API void wc_Md4Update(wc_Md4* md4, const byte* data, word32 len); +WOLFSSL_API void wc_Md4Final(wc_Md4* md4, byte* hash); + +#ifndef OPENSSL_COEXIST + +enum { + MD4 = WC_HASH_TYPE_MD4, + MD4_BLOCK_SIZE = WC_MD4_BLOCK_SIZE, + MD4_DIGEST_SIZE = WC_MD4_DIGEST_SIZE, + MD4_PAD_SIZE = WC_MD4_PAD_SIZE +}; +typedef struct wc_Md4 Md4; -WOLFSSL_API void wc_InitMd4(Md4* md4); -WOLFSSL_API void wc_Md4Update(Md4* md4, const byte* data, word32 len); -WOLFSSL_API void wc_Md4Final(Md4* md4, byte* hash); +#endif /* !OPENSSL_COEXIST */ #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/md5.h b/src/wolfssl/wolfcrypt/md5.h index c19f6c1..59d1f8d 100644 --- a/src/wolfssl/wolfcrypt/md5.h +++ b/src/wolfssl/wolfcrypt/md5.h @@ -65,7 +65,7 @@ enum { #ifdef WOLFSSL_MICROCHIP_PIC32MZ #include #endif -#ifdef STM32_HASH +#if defined(STM32_HASH) && !defined(STM32_NOMD5) #include #endif #ifdef WOLFSSL_ASYNC_CRYPT @@ -80,7 +80,7 @@ enum { /* MD5 digest */ typedef struct wc_Md5 { -#ifdef STM32_HASH +#if defined(STM32_HASH) && !defined(STM32_NOMD5) STM32_HASH_Context stmCtx; #else word32 buffLen; /* in bytes */ diff --git a/src/wolfssl/wolfcrypt/mem_track.h b/src/wolfssl/wolfcrypt/mem_track.h index b45bf23..a69d1f0 100644 --- a/src/wolfssl/wolfcrypt/mem_track.h +++ b/src/wolfssl/wolfcrypt/mem_track.h @@ -157,9 +157,9 @@ static WC_INLINE void* TrackMalloc(size_t sz) return NULL; #ifdef FREERTOS - mt = (memoryTrack*)pvPortMalloc(sizeof(memoryTrack) + sz); + mt = (memoryTrack*)pvPortMalloc(sizeof(memoryTrack) + sz); /* native heap */ #else - mt = (memoryTrack*)malloc(sizeof(memoryTrack) + sz); + mt = (memoryTrack*)malloc(sizeof(memoryTrack) + sz); /* native heap */ #endif if (mt == NULL) return NULL; @@ -300,9 +300,9 @@ static WC_INLINE void TrackFree(void* ptr) (void)sz; #ifdef FREERTOS - vPortFree(mt); + vPortFree(mt); /* native heap */ #else - free(mt); + free(mt); /* native heap */ #endif } @@ -600,7 +600,7 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) stackSize = PTHREAD_STACK_MIN; #endif - ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); + ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); /* native heap */ if (ret != 0 || myStack == NULL) { wc_mem_printf("posix_memalign failed\n"); return -1; @@ -650,7 +650,7 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) } } - free(myStack); + free(myStack); /* native heap */ #ifdef HAVE_STACK_SIZE_VERBOSE printf("stack used = %lu\n", StackSizeCheck_stackSizeHWM > (stackSize - i) ? (unsigned long)StackSizeCheck_stackSizeHWM @@ -681,16 +681,16 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, stackSize = PTHREAD_STACK_MIN; #endif - shim_args = (struct stack_size_debug_context *)malloc(sizeof *shim_args); + shim_args = (struct stack_size_debug_context *)malloc(sizeof *shim_args); /* native heap */ if (shim_args == NULL) { perror("malloc"); return -1; } - ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); + ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize); /* native heap */ if (ret != 0 || myStack == NULL) { wc_mem_printf("posix_memalign failed\n"); - free(shim_args); + free(shim_args); /* native heap */ return -1; } @@ -699,8 +699,8 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, ret = pthread_attr_init(&myAttr); if (ret != 0) { wc_mem_printf("attr_init failed\n"); - free(shim_args); - free(myStack); + free(shim_args); /* native heap */ + free(myStack); /* native heap */ return ret; } @@ -749,7 +749,7 @@ static WC_INLINE int StackSizeCheck_reap(pthread_t threadId, } } - free(shim_args->myStack); + free(shim_args->myStack); /* native heap */ #ifdef HAVE_STACK_SIZE_VERBOSE printf("stack used = %lu\n", *shim_args->stackSizeHWM_ptr > (shim_args->stackSize - i) @@ -761,7 +761,7 @@ static WC_INLINE int StackSizeCheck_reap(pthread_t threadId, printf("stack used = %lu\n", (unsigned long)used); } #endif - free(shim_args); + free(shim_args); /* native heap */ return (int)((size_t)status); } diff --git a/src/wolfssl/wolfcrypt/memory.h b/src/wolfssl/wolfcrypt/memory.h index 481f8aa..179a8fd 100644 --- a/src/wolfssl/wolfcrypt/memory.h +++ b/src/wolfssl/wolfcrypt/memory.h @@ -219,8 +219,8 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, #endif #ifdef WOLFSSL_STATIC_MEMORY_LEAN - word16 sizeList[WOLFMEM_MAX_BUCKETS];/* memory sizes in ava list */ - byte distList[WOLFMEM_MAX_BUCKETS];/* general distribution */ + word32 sizeList[WOLFMEM_MAX_BUCKETS];/* memory sizes in ava list */ + word32 distList[WOLFMEM_MAX_BUCKETS];/* general distribution */ #else word32 maxHa; /* max concurrent handshakes */ word32 curHa; @@ -258,8 +258,8 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, WOLFSSL_API void* wolfSSL_SetGlobalHeapHint(void* heap); WOLFSSL_API void* wolfSSL_GetGlobalHeapHint(void); WOLFSSL_API int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint, - unsigned int listSz, const unsigned int *sizeList, - const unsigned int *distList, unsigned char* buf, unsigned int sz, + unsigned int listSz, const word32 *sizeList, + const word32 *distList, unsigned char* buf, unsigned int sz, int flag, int max); #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK #define WOLFSSL_DEBUG_MEMORY_ALLOC 0 @@ -281,7 +281,7 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, WOLFSSL_LOCAL int FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io); WOLFSSL_API int wolfSSL_StaticBufferSz_ex(unsigned int listSz, - const unsigned int *sizeList, const unsigned int *distList, + const word32 *sizeList, const word32 *distList, byte* buffer, word32 sz, int flag); WOLFSSL_API int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag); WOLFSSL_API int wolfSSL_MemoryPaddingSz(void); @@ -449,7 +449,7 @@ WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(void **CipherLifecycleTag, #endif - #define ASSERT_SAVED_VECTOR_REGISTERS(fail_clause) do { \ + #define ASSERT_SAVED_VECTOR_REGISTERS() do { \ if (wc_svr_count <= 0) { \ fprintf(stderr, \ ("ASSERT_SAVED_VECTOR_REGISTERS : %s @ L%d : " \ @@ -460,7 +460,6 @@ WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(void **CipherLifecycleTag, wc_svr_last_file, \ wc_svr_last_line); \ DEBUG_VECTOR_REGISTERS_EXTRA_FAIL_CLAUSE \ - { fail_clause } \ } \ } while (0) #define ASSERT_RESTORED_VECTOR_REGISTERS(fail_clause) do { \ @@ -477,7 +476,7 @@ WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(void **CipherLifecycleTag, { fail_clause } \ } \ } while (0) - #define RESTORE_VECTOR_REGISTERS(...) do { \ + #define RESTORE_VECTOR_REGISTERS() do { \ --wc_svr_count; \ if ((wc_svr_count > 4) || (wc_svr_count < 0)) { \ fprintf(stderr, \ diff --git a/src/wolfssl/wolfcrypt/misc.h b/src/wolfssl/wolfcrypt/misc.h index 9acc31b..579c536 100644 --- a/src/wolfssl/wolfcrypt/misc.h +++ b/src/wolfssl/wolfcrypt/misc.h @@ -46,12 +46,10 @@ word32 rotlFixed(word32 x, word32 y); WOLFSSL_LOCAL word32 rotrFixed(word32 x, word32 y); -#ifdef WC_RC2 WOLFSSL_LOCAL word16 rotlFixed16(word16 x, word16 y); WOLFSSL_LOCAL word16 rotrFixed16(word16 x, word16 y); -#endif WOLFSSL_LOCAL word32 ByteReverseWord32(word32 value); @@ -74,6 +72,15 @@ void ForceZero(void* mem, word32 len); WOLFSSL_LOCAL int ConstantCompare(const byte* a, const byte* b, int length); +WOLFSSL_LOCAL +word32 readUnalignedWord32(const byte *in); +WOLFSSL_LOCAL +word32 writeUnalignedWord32(void *out, word32 in); +WOLFSSL_LOCAL +void readUnalignedWords32(word32 *out, const byte *in, size_t count); +WOLFSSL_LOCAL +void writeUnalignedWords32(byte *out, const word32 *in, size_t count); + #ifdef WORD64_AVAILABLE WOLFSSL_LOCAL word64 readUnalignedWord64(const byte *in); diff --git a/src/wolfssl/wolfcrypt/pkcs11.h b/src/wolfssl/wolfcrypt/pkcs11.h index 7a53710..f252a00 100644 --- a/src/wolfssl/wolfcrypt/pkcs11.h +++ b/src/wolfssl/wolfcrypt/pkcs11.h @@ -71,10 +71,12 @@ extern "C" { #define CKF_RW_SESSION 0x00000002UL #define CKF_SERIAL_SESSION 0x00000004UL +#define CKO_CERTIFICATE 0x00000001UL #define CKO_PUBLIC_KEY 0x00000002UL #define CKO_PRIVATE_KEY 0x00000003UL #define CKO_SECRET_KEY 0x00000004UL + #define CKK_RSA 0x00000000UL #define CKK_DH 0x00000002UL #define CKK_EC 0x00000003UL diff --git a/src/wolfssl/wolfcrypt/pkcs7.h b/src/wolfssl/wolfcrypt/pkcs7.h index 80c687b..bc34147 100644 --- a/src/wolfssl/wolfcrypt/pkcs7.h +++ b/src/wolfssl/wolfcrypt/pkcs7.h @@ -158,7 +158,7 @@ enum Pkcs7_Misc { MAX_CONTENT_KEY_LEN = 32, /* highest current cipher is AES-256-CBC */ MAX_CONTENT_IV_SIZE = 16, /* highest current is AES128 */ #ifndef NO_AES - MAX_CONTENT_BLOCK_LEN = AES_BLOCK_SIZE, + MAX_CONTENT_BLOCK_LEN = WC_AES_BLOCK_SIZE, #else MAX_CONTENT_BLOCK_LEN = DES_BLOCK_SIZE, #endif @@ -202,37 +202,42 @@ typedef struct PKCS7DecodedAttrib { typedef struct PKCS7State PKCS7State; typedef struct Pkcs7Cert Pkcs7Cert; typedef struct Pkcs7EncodedRecip Pkcs7EncodedRecip; -typedef struct PKCS7 PKCS7; -typedef struct PKCS7 PKCS7_SIGNED; typedef struct PKCS7SignerInfo PKCS7SignerInfo; +typedef struct wc_PKCS7 wc_PKCS7; +typedef struct wc_PKCS7 wc_PKCS7_SIGNED; + +#ifndef OPENSSL_COEXIST +#define PKCS7 wc_PKCS7 +#define PKCS7_SIGNED wc_PKCS7_SIGNED +#endif /* OtherRecipientInfo decrypt callback prototype */ -typedef int (*CallbackOriDecrypt)(PKCS7* pkcs7, byte* oriType, word32 oriTypeSz, +typedef int (*CallbackOriDecrypt)(wc_PKCS7* pkcs7, byte* oriType, word32 oriTypeSz, byte* oriValue, word32 oriValueSz, byte* decryptedKey, word32* decryptedKeySz, void* ctx); -typedef int (*CallbackOriEncrypt)(PKCS7* pkcs7, byte* cek, word32 cekSz, +typedef int (*CallbackOriEncrypt)(wc_PKCS7* pkcs7, byte* cek, word32 cekSz, byte* oriType, word32* oriTypeSz, byte* oriValue, word32* oriValueSz, void* ctx); -typedef int (*CallbackDecryptContent)(PKCS7* pkcs7, int encryptOID, +typedef int (*CallbackDecryptContent)(wc_PKCS7* pkcs7, int encryptOID, byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, word32 authTagSz, byte* in, int inSz, byte* out, void* ctx); -typedef int (*CallbackWrapCEK)(PKCS7* pkcs7, byte* cek, word32 cekSz, +typedef int (*CallbackWrapCEK)(wc_PKCS7* pkcs7, byte* cek, word32 cekSz, byte* keyId, word32 keyIdSz, byte* originKey, word32 originKeySz, byte* out, word32 outSz, int keyWrapAlgo, int type, int dir); /* Callbacks for supporting different stream cases */ -typedef int (*CallbackGetContent)(PKCS7* pkcs7, byte** content, void* ctx); -typedef int (*CallbackStreamOut)(PKCS7* pkcs7, const byte* output, +typedef int (*CallbackGetContent)(wc_PKCS7* pkcs7, byte** content, void* ctx); +typedef int (*CallbackStreamOut)(wc_PKCS7* pkcs7, const byte* output, word32 outputSz, void* ctx); #if defined(HAVE_PKCS7_RSA_RAW_SIGN_CALLBACK) && !defined(NO_RSA) /* RSA sign raw digest callback, user builds DigestInfo */ -typedef int (*CallbackRsaSignRawDigest)(PKCS7* pkcs7, byte* digest, +typedef int (*CallbackRsaSignRawDigest)(wc_PKCS7* pkcs7, byte* digest, word32 digestSz, byte* out, word32 outSz, byte* privateKey, word32 privateKeySz, int devId, int hashOID); @@ -241,7 +246,7 @@ typedef int (*CallbackRsaSignRawDigest)(PKCS7* pkcs7, byte* digest, /* Public Structure Warning: * Existing members must not be changed to maintain backwards compatibility! */ -struct PKCS7 { +struct wc_PKCS7 { WC_RNG* rng; PKCS7Attrib* signedAttribs; byte* content; /* inner content, not owner */ @@ -370,55 +375,55 @@ struct PKCS7 { /* !! NEW DATA MEMBERS MUST BE ADDED AT END !! */ }; -WOLFSSL_API PKCS7* wc_PKCS7_New(void* heap, int devId); +WOLFSSL_API wc_PKCS7* wc_PKCS7_New(void* heap, int devId); #ifdef WC_ASN_UNKNOWN_EXT_CB - WOLFSSL_API void wc_PKCS7_SetUnknownExtCallback(PKCS7* pkcs7, + WOLFSSL_API void wc_PKCS7_SetUnknownExtCallback(wc_PKCS7* pkcs7, wc_UnknownExtCallback cb); #endif -WOLFSSL_API int wc_PKCS7_Init(PKCS7* pkcs7, void* heap, int devId); -WOLFSSL_API int wc_PKCS7_InitWithCert(PKCS7* pkcs7, byte* der, word32 derSz); -WOLFSSL_API int wc_PKCS7_AddCertificate(PKCS7* pkcs7, byte* der, word32 derSz); -WOLFSSL_API void wc_PKCS7_Free(PKCS7* pkcs7); +WOLFSSL_API int wc_PKCS7_Init(wc_PKCS7* pkcs7, void* heap, int devId); +WOLFSSL_API int wc_PKCS7_InitWithCert(wc_PKCS7* pkcs7, byte* der, word32 derSz); +WOLFSSL_API int wc_PKCS7_AddCertificate(wc_PKCS7* pkcs7, byte* der, word32 derSz); +WOLFSSL_API void wc_PKCS7_Free(wc_PKCS7* pkcs7); -WOLFSSL_API int wc_PKCS7_GetAttributeValue(PKCS7* pkcs7, const byte* oid, +WOLFSSL_API int wc_PKCS7_GetAttributeValue(wc_PKCS7* pkcs7, const byte* oid, word32 oidSz, byte* out, word32* outSz); -WOLFSSL_API int wc_PKCS7_SetSignerIdentifierType(PKCS7* pkcs7, int type); -WOLFSSL_API int wc_PKCS7_SetContentType(PKCS7* pkcs7, byte* contentType, +WOLFSSL_API int wc_PKCS7_SetSignerIdentifierType(wc_PKCS7* pkcs7, int type); +WOLFSSL_API int wc_PKCS7_SetContentType(wc_PKCS7* pkcs7, byte* contentType, word32 sz); WOLFSSL_API int wc_PKCS7_GetPadSize(word32 inputSz, word32 blockSz); WOLFSSL_API int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, word32 blockSz); /* CMS/PKCS#7 Data */ -WOLFSSL_API int wc_PKCS7_EncodeData(PKCS7* pkcs7, byte* output, +WOLFSSL_API int wc_PKCS7_EncodeData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); /* CMS/PKCS#7 SignedData */ -WOLFSSL_API int wc_PKCS7_SetCustomSKID(PKCS7* pkcs7, const byte* in, +WOLFSSL_API int wc_PKCS7_SetCustomSKID(wc_PKCS7* pkcs7, const byte* in, word16 inSz); -WOLFSSL_API int wc_PKCS7_SetDetached(PKCS7* pkcs7, word16 flag); -WOLFSSL_API int wc_PKCS7_NoDefaultSignedAttribs(PKCS7* pkcs7); -WOLFSSL_API int wc_PKCS7_SetDefaultSignedAttribs(PKCS7* pkcs7, word16 flag); -WOLFSSL_API int wc_PKCS7_EncodeSignedData(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_SetDetached(wc_PKCS7* pkcs7, word16 flag); +WOLFSSL_API int wc_PKCS7_NoDefaultSignedAttribs(wc_PKCS7* pkcs7); +WOLFSSL_API int wc_PKCS7_SetDefaultSignedAttribs(wc_PKCS7* pkcs7, word16 flag); +WOLFSSL_API int wc_PKCS7_EncodeSignedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_EncodeSignedData_ex(PKCS7* pkcs7, const byte* hashBuf, +WOLFSSL_API int wc_PKCS7_EncodeSignedData_ex(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* outputHead, word32* outputHeadSz, byte* outputFoot, word32* outputFootSz); -WOLFSSL_API void wc_PKCS7_AllowDegenerate(PKCS7* pkcs7, word16 flag); -WOLFSSL_API int wc_PKCS7_VerifySignedData(PKCS7* pkcs7, +WOLFSSL_API void wc_PKCS7_AllowDegenerate(wc_PKCS7* pkcs7, word16 flag); +WOLFSSL_API int wc_PKCS7_VerifySignedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz); -WOLFSSL_API int wc_PKCS7_VerifySignedData_ex(PKCS7* pkcs7, const byte* hashBuf, +WOLFSSL_API int wc_PKCS7_VerifySignedData_ex(wc_PKCS7* pkcs7, const byte* hashBuf, word32 hashSz, byte* pkiMsgHead, word32 pkiMsgHeadSz, byte* pkiMsgFoot, word32 pkiMsgFootSz); -WOLFSSL_API int wc_PKCS7_GetSignerSID(PKCS7* pkcs7, byte* out, word32* outSz); +WOLFSSL_API int wc_PKCS7_GetSignerSID(wc_PKCS7* pkcs7, byte* out, word32* outSz); /* CMS single-shot API for Signed FirmwarePkgData */ -WOLFSSL_API int wc_PKCS7_EncodeSignedFPD(PKCS7* pkcs7, byte* privateKey, +WOLFSSL_API int wc_PKCS7_EncodeSignedFPD(wc_PKCS7* pkcs7, byte* privateKey, word32 privateKeySz, int signOID, int hashOID, byte* content, word32 contentSz, @@ -427,7 +432,7 @@ WOLFSSL_API int wc_PKCS7_EncodeSignedFPD(PKCS7* pkcs7, byte* privateKey, word32 outputSz); #ifndef NO_PKCS7_ENCRYPTED_DATA /* CMS single-shot API for Signed Encrypted FirmwarePkgData */ -WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedFPD(wc_PKCS7* pkcs7, byte* encryptKey, word32 encryptKeySz, byte* privateKey, word32 privateKeySz, int encryptOID, int signOID, @@ -441,7 +446,7 @@ WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedFPD(PKCS7* pkcs7, #endif /* NO_PKCS7_ENCRYPTED_DATA */ #if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) /* CMS single-shot API for Signed Compressed FirmwarePkgData */ -WOLFSSL_API int wc_PKCS7_EncodeSignedCompressedFPD(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeSignedCompressedFPD(wc_PKCS7* pkcs7, byte* privateKey, word32 privateKeySz, int signOID, int hashOID, byte* content, word32 contentSz, @@ -451,7 +456,7 @@ WOLFSSL_API int wc_PKCS7_EncodeSignedCompressedFPD(PKCS7* pkcs7, #ifndef NO_PKCS7_ENCRYPTED_DATA /* CMS single-shot API for Signed Encrypted Compressed FirmwarePkgData */ -WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(wc_PKCS7* pkcs7, byte* encryptKey, word32 encryptKeySz, byte* privateKey, word32 privateKeySz, int encryptOID, int signOID, @@ -466,80 +471,80 @@ WOLFSSL_API int wc_PKCS7_EncodeSignedEncryptedCompressedFPD(PKCS7* pkcs7, #endif /* HAVE_LIBZ && !NO_PKCS7_COMPRESSED_DATA */ /* EnvelopedData and AuthEnvelopedData RecipientInfo functions */ -WOLFSSL_API int wc_PKCS7_AddRecipient_KTRI(PKCS7* pkcs7, const byte* cert, +WOLFSSL_API int wc_PKCS7_AddRecipient_KTRI(wc_PKCS7* pkcs7, const byte* cert, word32 certSz, int options); -WOLFSSL_API int wc_PKCS7_AddRecipient_KARI(PKCS7* pkcs7, const byte* cert, +WOLFSSL_API int wc_PKCS7_AddRecipient_KARI(wc_PKCS7* pkcs7, const byte* cert, word32 certSz, int keyWrapOID, int keyAgreeOID, byte* ukm, word32 ukmSz, int options); -WOLFSSL_API int wc_PKCS7_SetKey(PKCS7* pkcs7, byte* key, word32 keySz); -WOLFSSL_API int wc_PKCS7_AddRecipient_KEKRI(PKCS7* pkcs7, int keyWrapOID, +WOLFSSL_API int wc_PKCS7_SetKey(wc_PKCS7* pkcs7, byte* key, word32 keySz); +WOLFSSL_API int wc_PKCS7_AddRecipient_KEKRI(wc_PKCS7* pkcs7, int keyWrapOID, byte* kek, word32 kekSz, byte* keyID, word32 keyIdSz, void* timePtr, byte* otherOID, word32 otherOIDSz, byte* other, word32 otherSz, int options); -WOLFSSL_API int wc_PKCS7_SetPassword(PKCS7* pkcs7, byte* passwd, word32 pLen); -WOLFSSL_API int wc_PKCS7_AddRecipient_PWRI(PKCS7* pkcs7, byte* passwd, +WOLFSSL_API int wc_PKCS7_SetPassword(wc_PKCS7* pkcs7, byte* passwd, word32 pLen); +WOLFSSL_API int wc_PKCS7_AddRecipient_PWRI(wc_PKCS7* pkcs7, byte* passwd, word32 pLen, byte* salt, word32 saltSz, int kdfOID, int prfOID, int iterations, int kekEncryptOID, int options); -WOLFSSL_API int wc_PKCS7_SetOriEncryptCtx(PKCS7* pkcs7, void* ctx); -WOLFSSL_API int wc_PKCS7_SetOriDecryptCtx(PKCS7* pkcs7, void* ctx); -WOLFSSL_API int wc_PKCS7_SetOriDecryptCb(PKCS7* pkcs7, CallbackOriDecrypt cb); -WOLFSSL_API int wc_PKCS7_AddRecipient_ORI(PKCS7* pkcs7, CallbackOriEncrypt cb, +WOLFSSL_API int wc_PKCS7_SetOriEncryptCtx(wc_PKCS7* pkcs7, void* ctx); +WOLFSSL_API int wc_PKCS7_SetOriDecryptCtx(wc_PKCS7* pkcs7, void* ctx); +WOLFSSL_API int wc_PKCS7_SetOriDecryptCb(wc_PKCS7* pkcs7, CallbackOriDecrypt cb); +WOLFSSL_API int wc_PKCS7_AddRecipient_ORI(wc_PKCS7* pkcs7, CallbackOriEncrypt cb, int options); -WOLFSSL_API int wc_PKCS7_SetWrapCEKCb(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_SetWrapCEKCb(wc_PKCS7* pkcs7, CallbackWrapCEK wrapCEKCb); #if defined(HAVE_PKCS7_RSA_RAW_SIGN_CALLBACK) && !defined(NO_RSA) -WOLFSSL_API int wc_PKCS7_SetRsaSignRawDigestCb(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_SetRsaSignRawDigestCb(wc_PKCS7* pkcs7, CallbackRsaSignRawDigest cb); #endif /* CMS/PKCS#7 EnvelopedData */ -WOLFSSL_API int wc_PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* pkiMsg, +WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, byte* output, word32 outputSz); /* CMS/PKCS#7 AuthEnvelopedData */ -WOLFSSL_API int wc_PKCS7_EncodeAuthEnvelopedData(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(PKCS7* pkcs7, byte* pkiMsg, +WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, byte* output, word32 outputSz); /* CMS/PKCS#7 EncryptedData */ #ifndef NO_PKCS7_ENCRYPTED_DATA -WOLFSSL_API int wc_PKCS7_EncodeEncryptedData(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_EncodeEncryptedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_DecodeEncryptedData(PKCS7* pkcs7, byte* pkiMsg, +WOLFSSL_API int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCb(PKCS7* pkcs7, +WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCb(wc_PKCS7* pkcs7, CallbackDecryptContent decryptionCb); -WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCtx(PKCS7* pkcs7, void* ctx); +WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCtx(wc_PKCS7* pkcs7, void* ctx); #endif /* NO_PKCS7_ENCRYPTED_DATA */ /* stream and certs */ -WOLFSSL_LOCAL int wc_PKCS7_WriteOut(PKCS7* pkcs7, byte* output, +WOLFSSL_LOCAL int wc_PKCS7_WriteOut(wc_PKCS7* pkcs7, byte* output, const byte* input, word32 inputSz); -WOLFSSL_API int wc_PKCS7_SetStreamMode(PKCS7* pkcs7, byte flag, +WOLFSSL_API int wc_PKCS7_SetStreamMode(wc_PKCS7* pkcs7, byte flag, CallbackGetContent getContentCb, CallbackStreamOut streamOutCb, void* ctx); -WOLFSSL_API int wc_PKCS7_GetStreamMode(PKCS7* pkcs7); -WOLFSSL_API int wc_PKCS7_SetNoCerts(PKCS7* pkcs7, byte flag); -WOLFSSL_API int wc_PKCS7_GetNoCerts(PKCS7* pkcs7); +WOLFSSL_API int wc_PKCS7_GetStreamMode(wc_PKCS7* pkcs7); +WOLFSSL_API int wc_PKCS7_SetNoCerts(wc_PKCS7* pkcs7, byte flag); +WOLFSSL_API int wc_PKCS7_GetNoCerts(wc_PKCS7* pkcs7); /* CMS/PKCS#7 CompressedData */ #if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) -WOLFSSL_API int wc_PKCS7_EncodeCompressedData(PKCS7* pkcs7, byte* output, +WOLFSSL_API int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz); -WOLFSSL_API int wc_PKCS7_DecodeCompressedData(PKCS7* pkcs7, byte* pkiMsg, +WOLFSSL_API int wc_PKCS7_DecodeCompressedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, byte* output, word32 outputSz); #endif /* HAVE_LIBZ && !NO_PKCS7_COMPRESSED_DATA */ diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h index 85b4ed1..de37936 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h @@ -31,7 +31,7 @@ /* WOLFSSL_USER_SETTINGS must be defined, typically in the CMakeLists.txt: */ /* set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DWOLFSSL_USER_SETTINGS") */ #ifndef WOLFSSL_USER_SETTINGS - #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targts" + #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targets" #endif /* FreeRTOS */ diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index 99d2ca2..d49ef3e 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -30,7 +30,7 @@ #if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ #ifndef WOLFSSL_USER_SETTINGS - #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targts" + #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targets" #endif #include "sdkconfig.h" /* ensure ESP-IDF settings are available everywhere */ diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h index afeb352..6f6e203 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h @@ -76,7 +76,7 @@ #if defined(WOLFSSL_ESPIDF) /* Entire file is only for Espressif EDP-IDF */ #ifndef WOLFSSL_USER_SETTINGS - #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targts" + #error "WOLFSSL_USER_SETTINGS must be defined for Espressif targets" #endif #if defined(CONFIG_ESP_TLS_USING_WOLFSSL) || \ diff --git a/src/wolfssl/wolfcrypt/rsa.h b/src/wolfssl/wolfcrypt/rsa.h index 3f39d5b..dc23839 100644 --- a/src/wolfssl/wolfcrypt/rsa.h +++ b/src/wolfssl/wolfcrypt/rsa.h @@ -169,8 +169,12 @@ enum { RSA_PSS_SALT_MAX_SZ = 62, #ifdef OPENSSL_EXTRA - RSA_PKCS1_PADDING_SIZE = 11, - RSA_PKCS1_OAEP_PADDING_SIZE = 42, /* (2 * hashlen(SHA-1)) + 2 */ + WC_RSA_PKCS1_PADDING_SIZE = 11, + WC_RSA_PKCS1_OAEP_PADDING_SIZE = 42, /* (2 * hashlen(SHA-1)) + 2 */ + #ifndef OPENSSL_COEXIST + #define RSA_PKCS1_PADDING_SIZE WC_RSA_PKCS1_PADDING_SIZE + #define RSA_PKCS1_OAEP_PADDING_SIZE WC_RSA_PKCS1_OAEP_PADDING_SIZE + #endif #endif #ifdef WC_RSA_PSS RSA_PSS_PAD_TERM = 0xBC, @@ -436,7 +440,7 @@ WOLFSSL_API int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, WOLFSSL_API int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out, RsaKey* key, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz); -#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) +#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_API int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, RsaKey* key, int type, WC_RNG* rng); #endif diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index e02870c..50eb0cb 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -28,6 +28,8 @@ * * ./configure CFLAGS="-DFEATURE_FLAG_TO_DEFINE -UFEATURE_FLAG_TO_CLEAR [...]" * + * To build using a custom configuration method, define WOLFSSL_CUSTOM_CONFIG + * * For more information see: * * https://www.wolfssl.com/how-do-i-manage-the-build-configuration-of-wolfssl/ @@ -45,11 +47,14 @@ extern "C" { #endif -/* This flag allows wolfSSL to include options.h instead of having client - * projects do it themselves. This should *NEVER* be defined when building - * wolfSSL as it can cause hard to debug problems. */ -#if defined(EXTERNAL_OPTS_OPENVPN) || defined(WOLFSSL_USE_OPTIONS_H) -#include +/* WOLFSSL_USE_OPTIONS_H directs wolfSSL to include options.h on behalf of + * application code, rather than the application including it directly. This is + * not defined when compiling wolfSSL library objects, which are configured + * through CFLAGS. + */ +#if (defined(EXTERNAL_OPTS_OPENVPN) || defined(WOLFSSL_USE_OPTIONS_H)) && \ + !defined(WOLFSSL_NO_OPTIONS_H) + #include #endif /* Uncomment next line if using IPHONE */ @@ -264,6 +269,9 @@ /* Uncomment next line if using MAXQ108x */ /* #define WOLFSSL_MAXQ108X */ +/* Uncomment next line if using Raspberry Pi RP2040 or RP2350 */ +/* #define WOLFSSL_RPIPICO */ + /* Check PLATFORMIO first, as it may define other known environments. */ #ifdef PLATFORMIO #ifdef ESP_PLATFORM @@ -314,6 +322,13 @@ #endif #endif +#if !defined(WOLFSSL_CUSTOM_CONFIG) && \ + ((defined(BUILDING_WOLFSSL) && defined(WOLFSSL_USE_OPTIONS_H)) || \ + (defined(BUILDING_WOLFSSL) && defined(WOLFSSL_OPTIONS_H) && \ + !defined(EXTERNAL_OPTS_OPENVPN))) + #warning wolfssl/options.h included in compiled wolfssl library object. +#endif + #ifdef WOLFSSL_USER_SETTINGS #include "user_settings.h" #elif defined(USE_HAL_DRIVER) && !defined(HAVE_CONFIG_H) @@ -323,6 +338,15 @@ /* NOTE: cyassl_nucleus_defs.h is akin to user_settings.h */ #include "nucleus.h" #include "os/networking/ssl/lite/cyassl_nucleus_defs.h" +#elif !defined(BUILDING_WOLFSSL) && !defined(WOLFSSL_OPTIONS_H) && \ + !defined(WOLFSSL_NO_OPTIONS_H) && !defined(WOLFSSL_CUSTOM_CONFIG) + /* This warning indicates that wolfSSL features may not have been properly + * configured before other wolfSSL headers were included. If you are using + * an alternative configuration method -- e.g. custom header, or CFLAGS in + * an application build -- then your application can avoid this warning by + * defining WOLFSSL_NO_OPTIONS_H or WOLFSSL_CUSTOM_CONFIG as appropriate. + */ + #warning "No configuration for wolfSSL detected, check header order" #endif #include @@ -412,6 +436,11 @@ #undef WC_RSA_BLINDING #endif +/* old FIPS has only AES_BLOCK_SIZE. */ +#if !defined(NO_AES) && (defined(HAVE_SELFTEST) || \ + (defined(HAVE_FIPS) && FIPS_VERSION3_LT(7,0,0))) + #define WC_AES_BLOCK_SIZE AES_BLOCK_SIZE +#endif /* !NO_AES && (HAVE_SELFTEST || FIPS_VERSION3_LT(7,0,0)) */ #ifdef WOLFSSL_HARDEN_TLS #if WOLFSSL_HARDEN_TLS != 112 && WOLFSSL_HARDEN_TLS != 128 @@ -994,6 +1023,11 @@ #define TSIP_TLS_HMAC_KEY_INDEX_WORDSIZE 64 #define TSIP_TLS_MASTERSECRET_SIZE 80 /* 20 words */ #define TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY 560 /* in byte */ + + #ifdef WOLF_CRYPTO_CB + /* make sure RSA padding callbacks are enabled */ + #define WOLF_CRYPTO_CB_RSA_PAD + #endif #endif /* WOLFSSL_RENESAS_TSIP */ #if !defined(WOLFSSL_NO_HASH_RAW) && defined(WOLFSSL_RENESAS_RX64_HASH) @@ -1291,8 +1325,8 @@ #define XSTRNCMP(s1,s2,n) strncmp((s1),(s2),(n)) #define XSTRNCAT(s1,s2,n) strncat((s1),(s2),(n)) #define XSTRNCASECMP(s1,s2,n) _strnicmp((s1),(s2),(n)) - #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) \ - || defined(HAVE_ALPN) + #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \ + defined(OPENSSL_ALL) || defined(HAVE_ALPN) #define XSTRTOK strtok_r #endif #endif @@ -1358,10 +1392,13 @@ #define NO_SESSION_CACHE #endif -/* Micrium will use Visual Studio for compilation but not the Win32 API */ +/* For platforms where the target OS is not Windows, but compilation is + * done on Windows/Visual Studio, enable a way to disable USE_WINDOWS_API. + * Examples: Micrium, TenAsus INtime, uTasker, FreeRTOS simulator */ #if defined(_WIN32) && !defined(MICRIUM) && !defined(FREERTOS) && \ !defined(FREERTOS_TCP) && !defined(EBSNET) && !defined(WOLFSSL_EROAD) && \ - !defined(WOLFSSL_UTASKER) && !defined(INTIME_RTOS) + !defined(WOLFSSL_UTASKER) && !defined(INTIME_RTOS) && \ + !defined(WOLFSSL_NOT_WINDOWS_API) #define USE_WINDOWS_API #endif @@ -1419,9 +1456,9 @@ extern void uITRON4_free(void *p) ; #if defined(WOLFSSL_LEANPSK) && !defined(XMALLOC_USER) && \ !defined(NO_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) #include - #define XMALLOC(s, h, type) ((void)(h), (void)(type), malloc((s))) - #define XFREE(p, h, type) ((void)(h), (void)(type), free((p))) - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) + #define XMALLOC(s, h, type) ((void)(h), (void)(type), malloc((s))) /* native heap */ + #define XFREE(p, h, type) ((void)(h), (void)(type), free((p))) /* native heap */ + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) /* native heap */ #endif #if defined(XMALLOC_USER) && defined(SSN_BUILDING_LIBYASSL) @@ -1456,18 +1493,18 @@ extern void uITRON4_free(void *p) ; (s), (__FILE__), (__LINE__), (__FUNCTION__) )) #else #define XMALLOC(s, h, type) \ - ((void)(h), (void)(type), pvPortMalloc((s))) + ((void)(h), (void)(type), pvPortMalloc((s))) /* native heap */ #endif /* XFREE */ - #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) + #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) /* native heap */ /* XREALLOC */ #if defined(WOLFSSL_ESPIDF) /* In the Espressif EDP-IDF, realloc(p, n) is equivalent to * heap_caps_realloc(p, s, MALLOC_CAP_8BIT) * There's no pvPortRealloc available: */ - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), realloc((p), (n))) /* native heap */ #elif defined(USE_INTEGER_HEAP_MATH) || defined(OPENSSL_EXTRA) || \ defined(OPENSSL_ALL) /* FreeRTOS pvPortRealloc() implementation can be found here: @@ -1509,8 +1546,12 @@ extern void uITRON4_free(void *p) ; #ifdef FREERTOS_TCP #if !defined(NO_WOLFSSL_MEMORY) && !defined(XMALLOC_USER) && \ !defined(WOLFSSL_STATIC_MEMORY) - #define XMALLOC(s, h, type) pvPortMalloc((s)) - #define XFREE(p, h, type) vPortFree((p)) + #ifndef XMALLOC + #define XMALLOC(s, h, type) pvPortMalloc((s)) /* native heap */ + #endif + #ifndef XFREE + #define XFREE(p, h, type) vPortFree((p)) /* native heap */ + #endif #endif #define WOLFSSL_GENSEED_FORTEST @@ -1678,8 +1719,8 @@ extern void uITRON4_free(void *p) ; #endif #if !defined(XMALLOC_USER) && !defined(NO_WOLFSSL_MEMORY) && \ !defined(WOLFSSL_STATIC_MEMORY) - #define XMALLOC(s, h, type) ((void)(h), (void)(type), pvPortMalloc((s))) - #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) + #define XMALLOC(s, h, type) ((void)(h), (void)(type), pvPortMalloc((s))) /* native heap */ + #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) /* native heap */ /* FreeRTOS pvPortRealloc() implementation can be found here: https://github.com/wolfSSL/wolfssl-freertos/pull/3/files */ @@ -1797,8 +1838,8 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_CRYPT_HW_MUTEX 1 #if !defined(XMALLOC_USER) && !defined(NO_WOLFSSL_MEMORY) - #define XMALLOC(s, h, type) ((void)(h), (void)(type), pvPortMalloc((s))) - #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) + #define XMALLOC(s, h, type) ((void)(h), (void)(type), pvPortMalloc((s))) /* native heap */ + #define XFREE(p, h, type) ((void)(h), (void)(type), vPortFree((p))) /* native heap */ #endif /* #define USER_TICKS */ @@ -2055,7 +2096,7 @@ extern void uITRON4_free(void *p) ; defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32H7) || \ defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) || \ - defined(WOLFSSL_STM32G4) + defined(WOLFSSL_STM32G4) || defined(WOLFSSL_STM32MP13) #define SIZEOF_LONG_LONG 8 #ifndef CHAR_BIT @@ -2117,6 +2158,12 @@ extern void uITRON4_free(void *p) ; #include "stm32u5xx_hal.h" #elif defined(WOLFSSL_STM32H5) #include "stm32h5xx_hal.h" + #elif defined(WOLFSSL_STM32MP13) + /* HAL headers error on our ASM files */ + #ifndef __ASSEMBLER__ + #include "stm32mp13xx_hal.h" + #include "stm32mp13xx_hal_conf.h" + #endif #endif #if defined(WOLFSSL_CUBEMX_USE_LL) && defined(WOLFSSL_STM32L4) #include "stm32l4xx_ll_rng.h" @@ -2642,11 +2689,6 @@ extern void uITRON4_free(void *p) ; #endif #endif -#if defined(OPENSSL_EXTRA) && !defined(NO_CERTS) - #undef KEEP_PEER_CERT - #define KEEP_PEER_CERT -#endif - /* stream ciphers except arc4 need 32bit alignment, intel ok without */ #ifndef XSTREAM_ALIGN @@ -2743,10 +2785,18 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_SP_INT_DIGIT_ALIGN #define WOLFSSL_SP_INT_DIGIT_ALIGN #endif +#if defined(__sparc) + #undef WOLFSSL_SP_INT_DIGIT_ALIGN + #define WOLFSSL_SP_INT_DIGIT_ALIGN +#endif #if defined(__APPLE__) || defined(WOLF_C89) #define WOLFSSL_SP_NO_DYN_STACK #endif +#if defined(__WATCOMC__) && !defined(WOLF_NO_VARIADIC_MACROS) + #define WOLF_NO_VARIADIC_MACROS +#endif + #ifdef __INTEL_COMPILER #pragma warning(disable:2259) /* explicit casts to smaller sizes, disable */ #endif @@ -2810,6 +2860,58 @@ extern void uITRON4_free(void *p) ; #endif /*----------------------------------------------------------------------------*/ +/* SP Math specific options */ +/* Determine when mp_add_d is required. */ +#if !defined(NO_PWDBASED) || defined(WOLFSSL_KEY_GEN) || !defined(NO_DH) || \ + !defined(NO_DSA) || defined(HAVE_ECC) || \ + (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + defined(OPENSSL_EXTRA) + #define WOLFSSL_SP_ADD_D +#endif + +/* Determine when mp_sub_d is required. */ +#if (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + !defined(NO_DH) || defined(HAVE_ECC) || !defined(NO_DSA) + #define WOLFSSL_SP_SUB_D +#endif + +/* Determine when mp_read_radix with a radix of 10 is required. */ +#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_RSA) && \ + !defined(WOLFSSL_RSA_VERIFY_ONLY)) || defined(HAVE_ECC) || \ + !defined(NO_DSA) || defined(OPENSSL_EXTRA) + #define WOLFSSL_SP_READ_RADIX_16 +#endif + +/* Determine when mp_read_radix with a radix of 10 is required. */ +#if defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_RSA) && \ + !defined(WOLFSSL_RSA_VERIFY_ONLY) + #define WOLFSSL_SP_READ_RADIX_10 +#endif + +/* Determine when mp_invmod is required. */ +#if defined(HAVE_ECC) || !defined(NO_DSA) || defined(OPENSSL_EXTRA) || \ + (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ + !defined(WOLFSSL_RSA_PUBLIC_ONLY)) + #define WOLFSSL_SP_INVMOD +#endif + +/* Determine when mp_invmod_mont_ct is required. */ +#if defined(WOLFSSL_SP_MATH_ALL) && defined(HAVE_ECC) + #define WOLFSSL_SP_INVMOD_MONT_CT +#endif + +/* Determine when mp_prime_gen is required. */ +#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ + !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || !defined(NO_DH) || \ + (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) + #define WOLFSSL_SP_PRIME_GEN +#endif + +#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || defined(OPENSSL_EXTRA) + /* Determine when mp_mul_d is required */ + #define WOLFSSL_SP_MUL_D +#endif /* user can specify what curves they want with ECC_USER_CURVES otherwise @@ -2900,7 +3002,7 @@ extern void uITRON4_free(void *p) ; #endif #endif /* HAVE_ECC */ -#if defined(OPENSSL_EXTRA) && defined(HAVE_ECC) && \ +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && defined(HAVE_ECC) && \ !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SE050) && \ !defined(WOLF_CRYPTO_CB_ONLY_ECC) && !defined(WOLFSSL_STM32_PKA) @@ -2999,6 +3101,13 @@ extern void uITRON4_free(void *p) ; #endif #endif /* HAVE_ED448 */ +/* FIPS does not support CFB1 or CFB8 */ +#if !defined(WOLFSSL_NO_AES_CFB_1_8) && \ + (defined(HAVE_SELFTEST) || \ + (defined(HAVE_FIPS) && FIPS_VERSION3_LT(6,0,0))) + #define WOLFSSL_NO_AES_CFB_1_8 +#endif + /* AES Config */ #ifndef NO_AES /* By default enable all AES key sizes, decryption and CBC */ @@ -3168,6 +3277,14 @@ extern void uITRON4_free(void *p) ; #undef NO_DH #endif +/* CryptoCell defines */ +#ifdef WOLFSSL_CRYPTOCELL + #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) + /* Don't attempt to sign/verify an all-zero digest in wolfCrypt tests */ + #define WC_TEST_NO_ECC_SIGN_VERIFY_ZERO_DIGEST + #endif /* HAVE_ECC && HAVE_ECC_SIGN */ +#endif + /* Asynchronous Crypto */ #ifdef WOLFSSL_ASYNC_CRYPT #if !defined(HAVE_CAVIUM) && !defined(HAVE_INTEL_QA) && \ @@ -3192,6 +3309,12 @@ extern void uITRON4_free(void *p) ; * but not required */ #define ECC_CACHE_CURVE #endif + + #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) + /* Don't attempt to sign/verify an all-zero digest in wolfCrypt tests */ + #define WC_TEST_NO_ECC_SIGN_VERIFY_ZERO_DIGEST + #endif /* HAVE_ECC && HAVE_ECC_SIGN */ + #endif /* WOLFSSL_ASYNC_CRYPT */ #ifndef WC_ASYNC_DEV_SIZE #define WC_ASYNC_DEV_SIZE 0 @@ -3387,8 +3510,9 @@ extern void uITRON4_free(void *p) ; #endif #endif -#if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \ - defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ + defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) #undef WOLFSSL_ASN_TIME_STRING #define WOLFSSL_ASN_TIME_STRING #endif @@ -3407,13 +3531,14 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_OCSP_PARSE_STATUS #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ - defined(WOLFSSL_CERT_GEN) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ + defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_CERT_GEN) #undef WOLFSSL_MULTI_ATTRIB #define WOLFSSL_MULTI_ATTRIB #endif -#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ + defined(OPENSSL_EXTRA_X509_SMALL) #undef WOLFSSL_EKU_OID #define WOLFSSL_EKU_OID #endif @@ -3477,6 +3602,7 @@ extern void uITRON4_free(void *p) ; #undef HAVE_STRINGS_H #undef HAVE_ERRNO_H #undef HAVE_THREAD_LS + #undef HAVE_ATEXIT #undef WOLFSSL_HAVE_MIN #undef WOLFSSL_HAVE_MAX #define SIZEOF_LONG 8 @@ -3501,12 +3627,10 @@ extern void uITRON4_free(void *p) ; #undef HAVE_GMTIME_R /* don't trust macro with windows */ #endif /* WOLFSSL_MYSQL_COMPATIBLE */ -#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ - || defined(HAVE_LIGHTY)) && !defined(NO_TLS) +#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)) && !defined(NO_TLS) #define OPENSSL_NO_ENGINE - #ifndef OPENSSL_EXTRA - #define OPENSSL_EXTRA - #endif + /* Session Tickets will be enabled when --enable-opensslall is used. * Time is required for ticket expiration checking */ #if !defined(HAVE_SESSION_TICKET) && !defined(NO_ASN_TIME) @@ -3533,11 +3657,18 @@ extern void uITRON4_free(void *p) ; #define OPENSSL_EXTRA #endif + +#if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT)) && \ + !defined(WOLFSSL_ASN_CA_ISSUER) + #define WOLFSSL_ASN_CA_ISSUER +#endif + + /* --------------------------------------------------------------------------- * OpenSSL compat layer * --------------------------------------------------------------------------- */ -#if defined(OPENSSL_EXTRA) && !defined(OPENSSL_COEXIST) +#ifdef OPENSSL_EXTRA #undef WOLFSSL_ALWAYS_VERIFY_CB #define WOLFSSL_ALWAYS_VERIFY_CB @@ -3561,7 +3692,7 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_SESSION_ID_CTX #define WOLFSSL_SESSION_ID_CTX -#endif /* OPENSSL_EXTRA && !OPENSSL_COEXIST */ +#endif /* OPENSSL_EXTRA */ #ifdef OPENSSL_EXTRA_X509_SMALL #undef WOLFSSL_NO_OPENSSL_RAND_CB @@ -3613,6 +3744,11 @@ extern void uITRON4_free(void *p) ; #ifndef NO_OLD_WC_NAMES #define NO_OLD_WC_NAMES #endif + #if defined(HAVE_SELFTEST) || \ + (defined(HAVE_FIPS) && FIPS_VERSION3_LT(5,0,0)) + /* old FIPS needs this remapping. */ + #define Sha3 wc_Sha3 + #endif #endif #if defined(NO_OLD_WC_NAMES) || defined(OPENSSL_EXTRA) @@ -3656,8 +3792,9 @@ extern void uITRON4_free(void *p) ; #endif /* Parts of the openssl compatibility layer require peer certs */ -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \ - || defined(HAVE_LIGHTY) +#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ + defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ + defined(HAVE_LIGHTY)) && !defined(NO_CERTS) #undef KEEP_PEER_CERT #define KEEP_PEER_CERT #endif @@ -3688,6 +3825,37 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_HAVE_TLS_UNIQUE #endif +/* WPAS Small option requires OPENSSL_EXTRA_X509_SMALL */ +#if defined(WOLFSSL_WPAS_SMALL) && !defined(OPENSSL_EXTRA_X509_SMALL) + #define OPENSSL_EXTRA_X509_SMALL +#endif + +/* Web Server needs to enable OPENSSL_EXTRA_X509_SMALL */ +#if defined(HAVE_WEBSERVER) && !defined(OPENSSL_EXTRA_X509_SMALL) + #define OPENSSL_EXTRA_X509_SMALL +#endif + +/* The EX data CRYPTO API's used with compatibility */ +#if !defined(HAVE_EX_DATA_CRYPTO) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_WPAS_SMALL) || \ + defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ + defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ + defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB) || \ + defined(WOLFSSL_WOLFSENTRY_HOOKS)) + #define HAVE_EX_DATA_CRYPTO +#endif + +#if defined(WOLFSSL_WOLFSENTRY_HOOKS) && !defined(HAVE_EX_DATA_CLEANUP_HOOKS) + #define HAVE_EX_DATA_CLEANUP_HOOKS +#endif + +/* Enable EX Data support if required */ +#if (defined(HAVE_EX_DATA_CRYPTO) || defined(HAVE_EX_DATA_CLEANUP_HOOKS)) && \ + !defined(HAVE_EX_DATA) + #define HAVE_EX_DATA +#endif + + /* RAW hash function APIs are not implemented */ #if defined(WOLFSSL_ARMASM) || defined(WOLFSSL_AFALG_HASH) #undef WOLFSSL_NO_HASH_RAW @@ -3754,15 +3922,17 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_BASE64_DECODE #endif -#if defined(HAVE_EX_DATA) || defined(FORTRESS) - #if defined(FORTRESS) && !defined(HAVE_EX_DATA) - #define HAVE_EX_DATA - #endif +#if defined(FORTRESS) && !defined(HAVE_EX_DATA) + #define HAVE_EX_DATA +#endif + +#ifdef HAVE_EX_DATA #ifndef MAX_EX_DATA #define MAX_EX_DATA 5 /* allow for five items of ex_data */ #endif #endif + #ifdef NO_WOLFSSL_SMALL_STACK #undef WOLFSSL_SMALL_STACK #endif @@ -4000,10 +4170,6 @@ extern void uITRON4_free(void *p) ; #error "DTLS v1.3 requires both WOLFSSL_TLS13 and WOLFSSL_DTLS" #endif -#if defined(WOLFSSL_DTLS_CID) && !defined(WOLFSSL_DTLS13) -#error "ConnectionID is supported for DTLSv1.3 only" -#endif - #if defined(WOLFSSL_QUIC) && defined(WOLFSSL_CALLBACKS) #error WOLFSSL_QUIC is incompatible with WOLFSSL_CALLBACKS. #endif @@ -4163,15 +4329,24 @@ extern void uITRON4_free(void *p) ; #endif #endif -#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && \ - defined(OPENSSL_COEXIST) - #error "OPENSSL_EXTRA can not be defined with OPENSSL_COEXIST" +#if defined(OPENSSL_ALL) && defined(OPENSSL_COEXIST) + #error "OPENSSL_ALL can not be defined with OPENSSL_COEXIST" #endif #if !defined(NO_DSA) && defined(NO_SHA) #error "Please disable DSA if disabling SHA-1" #endif +#if defined(WOLFSSL_SYS_CRYPTO_POLICY) + #if !defined(WOLFSSL_CRYPTO_POLICY_FILE) + #error "WOLFSSL_SYS_CRYPTO_POLICY requires a crypto policy file" + #endif /* ! WOLFSSL_CRYPTO_POLICY_FILE */ + + #if !defined(OPENSSL_EXTRA) + #error "WOLFSSL_SYS_CRYPTO_POLICY requires OPENSSL_EXTRA" + #endif /* ! OPENSSL_EXTRA */ +#endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + /* if configure.ac turned on this feature, HAVE_ENTROPY_MEMUSE will be set, * also define HAVE_WOLFENTROPY */ #ifdef HAVE_ENTROPY_MEMUSE diff --git a/src/wolfssl/wolfcrypt/sha3.h b/src/wolfssl/wolfcrypt/sha3.h index f65c41d..2491acd 100644 --- a/src/wolfssl/wolfcrypt/sha3.h +++ b/src/wolfssl/wolfcrypt/sha3.h @@ -45,6 +45,10 @@ #include #endif +#ifdef STM32_HASH + #include +#endif + /* in bytes */ enum { /* SHAKE-128 */ @@ -140,6 +144,9 @@ struct wc_Sha3 { #ifdef WOLFSSL_HASH_FLAGS word32 flags; /* enum wc_HashFlags in hash.h */ #endif +#if defined(STM32_HASH_SHA3) + STM32_HASH_Context stmCtx; +#endif }; #ifndef WC_SHA3_TYPE_DEFINED @@ -219,8 +226,13 @@ WOLFSSL_LOCAL void sha3_block_n_bmi2(word64* s, const byte* data, word32 n, WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); WOLFSSL_LOCAL void sha3_block_avx2(word64* s); WOLFSSL_LOCAL void BlockSha3(word64 *s); +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) +#ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 +WOLFSSL_LOCAL void BlockSha3_crypto(word64 *s); #endif -#if defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) +WOLFSSL_LOCAL void BlockSha3_base(word64 *s); +WOLFSSL_LOCAL void BlockSha3(word64 *s); +#elif defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) WOLFSSL_LOCAL void BlockSha3(word64 *s); #endif diff --git a/src/wolfssl/wolfcrypt/sha512.h b/src/wolfssl/wolfcrypt/sha512.h index e971a8d..5033a2c 100644 --- a/src/wolfssl/wolfcrypt/sha512.h +++ b/src/wolfssl/wolfcrypt/sha512.h @@ -73,6 +73,10 @@ #include "fsl_caam.h" #endif +#ifdef STM32_HASH + #include +#endif + #if defined(_MSC_VER) #define SHA512_NOINLINE __declspec(noinline) #elif defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) @@ -202,6 +206,9 @@ struct wc_Sha512 { #ifdef HAVE_ARIA MC_HSESSION hSession; #endif +#if defined(STM32_HASH_SHA512) + STM32_HASH_Context stmCtx; +#endif #endif /* WOLFSSL_PSOC6_CRYPTO */ }; @@ -221,14 +228,11 @@ struct wc_Sha512 { #ifdef WOLFSSL_ARMASM #ifdef __aarch64__ -#ifndef WOLFSSL_ARMASM_CRYPTO_SHA512 void Transform_Sha512_Len_neon(wc_Sha512* sha512, const byte* data, word32 len); - #define Transform_Sha512_Len Transform_Sha512_Len_neon -#else +#ifdef WOLFSSL_ARMASM_CRYPTO_SHA512 void Transform_Sha512_Len_crypto(wc_Sha512* sha512, const byte* data, word32 len); - #define Transform_Sha512_Len Transform_Sha512_Len_crypto #endif #else extern void Transform_Sha512_Len(wc_Sha512* sha512, const byte* data, diff --git a/src/wolfssl/wolfcrypt/sp_int.h b/src/wolfssl/wolfcrypt/sp_int.h index 2a9a880..dc707d2 100644 --- a/src/wolfssl/wolfcrypt/sp_int.h +++ b/src/wolfssl/wolfcrypt/sp_int.h @@ -30,8 +30,9 @@ This library provides single precision (SP) integer math functions. #ifndef WOLFSSL_LINUXKM #include #endif -#include -#include +#include +#include +#include #ifdef __cplusplus extern "C" { @@ -100,6 +101,15 @@ extern "C" { #error "Size of unsigned int not detected" #endif +#if defined(__WATCOMC__) && defined(__WATCOM_INT64__) + /* For older Watcom C compiler force types */ + #define SP_ULLONG_BITS 64 + typedef unsigned __int64 sp_uint64; + typedef __int64 sp_int64; + +#else + +/* 32-bit type */ #if defined(WOLF_C89) && !defined(NO_64BIT) && \ ULONG_MAX == 18446744073709551615UL #define SP_ULONG_BITS 64 @@ -108,8 +118,8 @@ extern "C" { typedef long sp_int64; #elif !defined(WOLF_C89) && !defined(NO_64BIT) && \ ULONG_MAX == 18446744073709551615ULL && \ - 4294967295UL != 18446744073709551615ULL /* verify pre-processor supports - * 64-bit ULL types */ + /* sanity check pre-processor supports 64-bit ULL types */ \ + 4294967295UL != 18446744073709551615ULL #define SP_ULONG_BITS 64 typedef unsigned long sp_uint64; @@ -132,6 +142,7 @@ extern "C" { #error "Size of unsigned long not detected" #endif +/* 64-bit type */ #ifdef ULLONG_MAX #if defined(WOLF_C89) && ULLONG_MAX == 18446744073709551615UL #define SP_ULLONG_BITS 64 @@ -165,6 +176,7 @@ extern "C" { #error "Size of unsigned long long not detected" #endif #elif (SP_ULONG_BITS == 32) && !defined(NO_64BIT) + #define SP_ULLONG_BITS 64 /* Speculatively use long long as the 64-bit type as we don't have one * otherwise. */ typedef unsigned long long sp_uint64; @@ -173,6 +185,7 @@ extern "C" { #define SP_ULLONG_BITS 0 #endif +#endif /* __WATCOMC__ */ #ifdef WOLFSSL_SP_DIV_32 #define WOLFSSL_SP_DIV_WORD_HALF @@ -691,7 +704,7 @@ typedef struct sp_ecc_ctx { if ((a)->used > 0) { \ for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ } \ - (a)->used = (mp_size_t)(ii + 1); \ + (a)->used = (wc_mp_size_t)(ii + 1); \ } \ } while (0) @@ -867,10 +880,10 @@ typedef unsigned int sp_size_t; #endif /* Type for number of digits. */ -#define mp_size_t sp_size_t +#define wc_mp_size_t sp_size_t #ifdef WOLFSSL_SP_INT_NEGATIVE typedef sp_uint8 sp_sign_t; - #define mp_sign_t sp_sign_t + #define wc_mp_sign_t sp_sign_t #endif /** diff --git a/src/wolfssl/wolfcrypt/tfm.h b/src/wolfssl/wolfcrypt/tfm.h index a9b0df2..80b7f0f 100644 --- a/src/wolfssl/wolfcrypt/tfm.h +++ b/src/wolfssl/wolfcrypt/tfm.h @@ -379,8 +379,8 @@ while (0) #define WOLF_BIGINT_DEFINED #endif -#define mp_size_t int -#define mp_sign_t int +#define wc_mp_size_t int +#define wc_mp_sign_t int /* a FP type */ typedef struct fp_int { diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index 1b437c1..f8042cf 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -34,6 +34,10 @@ decouple library dependencies with standard string, memory and so on. #include #include + #if defined(EXTERNAL_OPTS_OPENVPN) && defined(BUILDING_WOLFSSL) + #error EXTERNAL_OPTS_OPENVPN should not be defined in compiled wolfssl library files. + #endif + #ifdef __APPLE__ #include #endif @@ -77,6 +81,7 @@ decouple library dependencies with standard string, memory and so on. #endif #ifndef WOLFSSL_TYPES + #define WOLFSSL_TYPES #ifndef byte /* If using C++ C17 or later and getting: * "error: reference to 'byte' is ambiguous", this is caused by @@ -113,23 +118,84 @@ decouple library dependencies with standard string, memory and so on. #endif #ifndef WC_BITFIELD - #define WC_BITFIELD byte + #ifdef WOLF_C89 + #define WC_BITFIELD unsigned + #else + #define WC_BITFIELD byte + #endif #endif #ifndef HAVE_ANONYMOUS_INLINE_AGGREGATES /* if a version is available, pivot on the version, otherwise guess it's - * allowed, subject to override. + * disallowed, subject to override. */ #if !defined(WOLF_C89) && (!defined(__STDC__) \ || (!defined(__STDC_VERSION__) && !defined(__cplusplus)) \ || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201101L)) \ || (defined(__cplusplus) && (__cplusplus >= 201103L))) #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 - #else - #define HAVE_ANONYMOUS_INLINE_AGGREGATES 0 #endif + #elif ~(~HAVE_ANONYMOUS_INLINE_AGGREGATES + 1) == 1 + /* forced on with empty value -- remap to 1 */ + #undef HAVE_ANONYMOUS_INLINE_AGGREGATES + #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 + #elif HAVE_ANONYMOUS_INLINE_AGGREGATES + /* forced on with explicit nonzero value -- leave as-is. */ + #else + /* forced off with explicit zero value -- remap to undef. */ + #undef HAVE_ANONYMOUS_INLINE_AGGREGATES + #endif + + #ifndef HAVE_EMPTY_AGGREGATES + /* The C standards don't define empty aggregates, but gcc and clang do. + * We need to accommodate them for one of the same reasons C++ does -- + * conditionally empty aggregates, e.g. in hash.h. + */ + #if !defined(WOLF_C89) && defined(__GNUC__) && \ + !defined(__STRICT_ANSI__) && \ + defined(HAVE_ANONYMOUS_INLINE_AGGREGATES) + #define HAVE_EMPTY_AGGREGATES 1 + #endif + #elif ~(~HAVE_EMPTY_AGGREGATES + 1) == 1 + /* forced on with empty value -- remap to 1 */ + #undef HAVE_EMPTY_AGGREGATES + #define HAVE_EMPTY_AGGREGATES 1 + #elif HAVE_EMPTY_AGGREGATES + /* forced on with explicit nonzero value -- leave as-is. */ + #else + /* forced off with explicit zero value -- remap to undef. */ + #undef HAVE_EMPTY_AGGREGATES #endif + #define _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) a ## b ## c + #define _WOLF_AGG_DUMMY_MEMBER_HELPER(a, b, c) _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) + #ifdef HAVE_EMPTY_AGGREGATES + /* swallow the semicolon with a zero-sized array (language extension + * specific to gcc/clang). + */ + #define WOLF_AGG_DUMMY_MEMBER \ + struct { \ + PRAGMA_GCC_DIAG_PUSH \ + PRAGMA_GCC("GCC diagnostic ignored \"-Wpedantic\"") \ + PRAGMA_CLANG_DIAG_PUSH \ + PRAGMA_CLANG("clang diagnostic ignored \"-Wzero-length-array\"") \ + byte _WOLF_AGG_DUMMY_MEMBER_HELPER(_wolf_L, __LINE__, _agg_dummy_member)[0]; \ + PRAGMA_CLANG_DIAG_POP \ + PRAGMA_GCC_DIAG_POP \ + } + #else + /* Use a single byte with a constructed name as a dummy member -- these + * are the standard semantics of an empty structure in C++. + */ + #define WOLF_AGG_DUMMY_MEMBER char _WOLF_AGG_DUMMY_MEMBER_HELPER(_wolf_L, __LINE__, _agg_dummy_member) + #endif + + /* helpers for stringifying the expanded value of a macro argument rather + * than its literal text: + */ + #define _WC_STRINGIFY_L2(str) #str + #define WC_STRINGIFY(str) _WC_STRINGIFY_L2(str) + /* With a true C89-dialect compiler (simulate with gcc -std=c89 -Wall * -Wextra -pedantic), a trailing comma on the last value in an enum * definition is a syntax error. We use this macro to accommodate that @@ -137,17 +203,13 @@ decouple library dependencies with standard string, memory and so on. * preprocessor-gated. */ #if defined(WOLF_C89) || defined(WOLF_NO_TRAILING_ENUM_COMMAS) - #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) _wolf_ ## prefix ## _enum_dummy_last_element + #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) a ## b ## c ## d ## e + #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(a, b, c, d, e) _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) + #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(_wolf_, prefix, _L, __LINE__, _enum_dummy_last_element) #else #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) /* null expansion */ #endif - /* helpers for stringifying the expanded value of a macro argument rather - * than its literal text: - */ - #define _WC_STRINGIFY_L2(str) #str - #define WC_STRINGIFY(str) _WC_STRINGIFY_L2(str) - /* try to set SIZEOF_LONG or SIZEOF_LONG_LONG if user didn't */ #if defined(_WIN32) || defined(HAVE_LIMITS_H) /* make sure both SIZEOF_LONG_LONG and SIZEOF_LONG are set, @@ -182,7 +244,10 @@ decouple library dependencies with standard string, memory and so on. #endif #endif - #if defined(_MSC_VER) || defined(__BCPLUSPLUS__) + #if (defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ + defined(__BCPLUSPLUS__) || \ + (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) + /* windows types */ #define WORD64_AVAILABLE #define W64LIT(x) x##ui64 #define SW64LIT(x) x##i64 @@ -305,28 +370,10 @@ typedef struct w64wrapper { WOLFSSL_WORD_BITS = WOLFSSL_WORD_SIZE * WOLFSSL_BIT_SIZE }; + #define WOLFSSL_MAX_8BIT 0xffU #define WOLFSSL_MAX_16BIT 0xffffU #define WOLFSSL_MAX_32BIT 0xffffffffU - #ifndef WARN_UNUSED_RESULT - #if defined(WOLFSSL_LINUXKM) && defined(__must_check) - #define WARN_UNUSED_RESULT __must_check - #elif (defined(__GNUC__) && (__GNUC__ >= 4)) || \ - (defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001)) - #define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) - #else - #define WARN_UNUSED_RESULT - #endif - #endif /* WARN_UNUSED_RESULT */ - - #ifndef WC_MAYBE_UNUSED - #if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) - #define WC_MAYBE_UNUSED __attribute__((unused)) - #else - #define WC_MAYBE_UNUSED - #endif - #endif /* WC_MAYBE_UNUSED */ - #ifndef WC_DO_NOTHING #define WC_DO_NOTHING do {} while (0) #ifdef _MSC_VER @@ -337,50 +384,13 @@ typedef struct w64wrapper { #endif #endif - /* use inlining if compiler allows */ - #ifndef WC_INLINE - #ifndef NO_INLINE - #ifdef _MSC_VER - #define WC_INLINE __inline - #elif defined(__GNUC__) - #ifdef WOLFSSL_VXWORKS - #define WC_INLINE __inline__ - #else - #define WC_INLINE inline - #endif - #elif defined(__IAR_SYSTEMS_ICC__) - #define WC_INLINE inline - #elif defined(THREADX) - #define WC_INLINE _Inline - #elif defined(__ghc__) - #ifndef __cplusplus - #define WC_INLINE __inline - #else - #define WC_INLINE inline - #endif - #elif defined(__CCRX__) - #define WC_INLINE inline - #elif defined(__DCC__) - #ifndef __cplusplus - #define WC_INLINE __inline__ - #else - #define WC_INLINE inline - #endif - #else - #define WC_INLINE WC_MAYBE_UNUSED - #endif - #else - #define WC_INLINE WC_MAYBE_UNUSED - #endif - #endif - #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) #define INLINE WC_INLINE #endif /* set up rotate style */ - #if (defined(_MSC_VER) || defined(__BCPLUSPLUS__)) && \ - !defined(WOLFSSL_SGX) && !defined(INTIME_RTOS) + #if ((defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ + defined(__BCPLUSPLUS__)) && !defined(WOLFSSL_SGX) && !defined(INTIME_RTOS) #define INTEL_INTRINSICS #define FAST_ROTATE #elif defined(__MWERKS__) && TARGET_CPU_PPC @@ -428,16 +438,6 @@ typedef struct w64wrapper { #define FALL_THROUGH #endif - /* For platforms where the target OS is not Windows, but compilation is - * done on Windows/Visual Studio, enable a way to disable USE_WINDOWS_API. - * Examples: Micrium, TenAsus INtime, uTasker, FreeRTOS simulator */ - #if defined(_WIN32) && !defined(MICRIUM) && !defined(FREERTOS) && \ - !defined(FREERTOS_TCP) && !defined(EBSNET) && \ - !defined(WOLFSSL_UTASKER) && !defined(INTIME_RTOS) && \ - !defined(WOLFSSL_NOT_WINDOWS_API) - #define USE_WINDOWS_API - #endif - #define XSTR_SIZEOF(x) (sizeof(x) - 1) /* -1 to not count the null char */ #define XELEM_CNT(x) (sizeof((x))/sizeof(*(x))) @@ -445,16 +445,6 @@ typedef struct w64wrapper { #define WC_SAFE_SUM_WORD32(in1, in2, out) ((in2) <= 0xffffffffU - (in1) ? \ ((out) = (in1) + (in2), 1) : ((out) = 0xffffffffU, 0)) - /* idea to add global alloc override by Moises Guimaraes */ - /* default to libc stuff */ - /* XREALLOC is used once in normal math lib, not in fast math lib */ - /* XFREE on some embedded systems doesn't like free(0) so test for NULL - * explicitly. - * - * For example: - * #define XFREE(p, h, t) \ - * {void* xp = (p); if (xp != NULL) free(xp, h, t);} - */ #if defined(HAVE_IO_POOL) WOLFSSL_API void* XMALLOC(size_t n, void* heap, int type); WOLFSSL_API void* XREALLOC(void *p, size_t n, void* heap, int type); @@ -547,14 +537,14 @@ typedef struct w64wrapper { #else /* just use plain C stdlib stuff if desired */ #include - #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc((size_t)(s))) + #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc((size_t)(s))) /* native heap */ #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) do { (void)(h); (void)(t); free(p); } while (0) + #define XFREE(p, h, t) do { (void)(h); (void)(t); free(p); } while (0) /* native heap */ #else - #define XFREE(p, h, t) do { void* xp = (p); (void)(h); if (xp) free(xp); } while (0) + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); if (xp) free(xp); } while (0) /* native heap */ #endif #define XREALLOC(p, n, h, t) \ - ((void)(h), (void)(t), realloc((p), (size_t)(n))) + ((void)(h), (void)(t), realloc((p), (size_t)(n))) /* native heap */ #endif #elif defined(WOLFSSL_LINUXKM) @@ -833,7 +823,7 @@ typedef struct w64wrapper { #ifndef USE_WINDOWS_API #if defined(WOLFSSL_ESPIDF) && \ (!defined(NO_ASN_TIME) && defined(HAVE_PKCS7)) - #include + #include /* later gcc than 7.1 introduces -Wformat-truncation */ /* In cases when truncation is expected the caller needs*/ /* to check the return value from the function so that */ @@ -869,7 +859,11 @@ typedef struct w64wrapper { #endif #define XSPRINTF sprintf /* snprintf not available for C89, so remap using macro */ - #define XSNPRINTF(f, len, ...) sprintf(f, __VA_ARGS__) + #ifdef WOLF_NO_VARIADIC_MACROS + #error WOLF_NO_VARIADIC_MACROS requires user-supplied binding for XSNPRINTF + #else + #define XSNPRINTF(f, len, ...) sprintf(f, __VA_ARGS__) + #endif #else #ifndef NO_STDIO_FILESYSTEM #include @@ -880,17 +874,18 @@ typedef struct w64wrapper { #if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) #if defined(_MSC_VER) && (_MSC_VER >= 1900) /* Beginning with the UCRT in Visual Studio 2015 and - Windows 10, snprintf is no longer identical to - _snprintf. The snprintf function behavior is now - C99 standard compliant. */ + * Windows 10, snprintf is no longer identical to + * _snprintf. The snprintf function behavior is now + * C99 standard compliant. */ #include #define XSNPRINTF snprintf #else /* 4996 warning to use MS extensions e.g., _sprintf_s - instead of _snprintf */ + * instead of _snprintf */ #if !defined(__MINGW32__) #pragma warning(disable: 4996) #endif + #include static WC_INLINE int xsnprintf(char *buffer, size_t bufsize, const char *format, ...) { @@ -1114,15 +1109,17 @@ typedef struct w64wrapper { DYNAMIC_TYPE_LMS = 101, DYNAMIC_TYPE_BIO = 102, DYNAMIC_TYPE_X509_ACERT = 103, - DYNAMIC_TYPE_SNIFFER_SERVER = 1000, - DYNAMIC_TYPE_SNIFFER_SESSION = 1001, - DYNAMIC_TYPE_SNIFFER_PB = 1002, - DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, - DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, - DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, - DYNAMIC_TYPE_SNIFFER_KEY = 1006, - DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE = 1007, - DYNAMIC_TYPE_AES_EAX = 1008 + DYNAMIC_TYPE_OS_BUF = 104, + DYNAMIC_TYPE_SNIFFER_SERVER = 1000, + DYNAMIC_TYPE_SNIFFER_SESSION = 1001, + DYNAMIC_TYPE_SNIFFER_PB = 1002, + DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, + DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, + DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, + DYNAMIC_TYPE_SNIFFER_KEY = 1006, + DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE = 1007, + DYNAMIC_TYPE_SNIFFER_CHAIN_BUFFER = 1008, + DYNAMIC_TYPE_AES_EAX = 1009 }; /* max error buffer string size */ @@ -1146,8 +1143,9 @@ typedef struct w64wrapper { WC_ALGO_TYPE_SEED = 5, WC_ALGO_TYPE_HMAC = 6, WC_ALGO_TYPE_CMAC = 7, + WC_ALGO_TYPE_CERT = 8, - WC_ALGO_TYPE_MAX = WC_ALGO_TYPE_CMAC + WC_ALGO_TYPE_MAX = WC_ALGO_TYPE_CERT }; /* hash types */ @@ -1456,7 +1454,7 @@ typedef struct w64wrapper { #endif #ifdef SINGLE_THREADED - #if defined(WC_32BIT_CPU) + #if defined(WC_32BIT_CPU) || defined(HAVE_STACK_SIZE) typedef void* THREAD_RETURN; #else typedef unsigned int THREAD_RETURN; @@ -1495,7 +1493,8 @@ typedef struct w64wrapper { typedef void THREAD_RETURN; #define WOLFSSL_THREAD_VOID_RETURN typedef struct { - struct k_thread tid; + /* Zephyr k_thread can be large, > 128 bytes. */ + struct k_thread* tid; k_thread_stack_t* threadStack; } THREAD_TYPE; #define WOLFSSL_THREAD @@ -1556,6 +1555,10 @@ typedef struct w64wrapper { #if !defined(__MINGW32__) #define WOLFSSL_THREAD_NO_JOIN __cdecl #endif + #elif defined(THREADX) + typedef unsigned int THREAD_RETURN; + typedef TX_THREAD THREAD_TYPE; + #define WOLFSSL_THREAD #else typedef unsigned int THREAD_RETURN; typedef size_t THREAD_TYPE; @@ -1757,7 +1760,7 @@ typedef struct w64wrapper { #endif #ifndef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #endif #ifndef SAVE_VECTOR_REGISTERS2 #define SAVE_VECTOR_REGISTERS2() 0 @@ -1771,10 +1774,10 @@ typedef struct w64wrapper { #define WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL(x) WC_DO_NOTHING #endif #ifndef ASSERT_SAVED_VECTOR_REGISTERS - #define ASSERT_SAVED_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define ASSERT_SAVED_VECTOR_REGISTERS() WC_DO_NOTHING #endif #ifndef ASSERT_RESTORED_VECTOR_REGISTERS - #define ASSERT_RESTORED_VECTOR_REGISTERS(...) WC_DO_NOTHING + #define ASSERT_RESTORED_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING #endif #ifndef RESTORE_VECTOR_REGISTERS #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index 0f31696..d7317ea 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -88,6 +88,8 @@ #ifndef WC_LMS_H #define WC_LMS_H +#include + #if defined(WOLFSSL_HAVE_LMS) && defined(WOLFSSL_WC_LMS) #include diff --git a/src/wolfssl/wolfcrypt/wc_port.h b/src/wolfssl/wolfcrypt/wc_port.h index 6dc7d2c..4be0502 100644 --- a/src/wolfssl/wolfcrypt/wc_port.h +++ b/src/wolfssl/wolfcrypt/wc_port.h @@ -62,6 +62,63 @@ #include "../../linuxkm/linuxkm_wc_port.h" #endif /* WOLFSSL_LINUXKM */ +#ifndef WARN_UNUSED_RESULT + #if defined(WOLFSSL_LINUXKM) && defined(__must_check) + #define WARN_UNUSED_RESULT __must_check + #elif (defined(__GNUC__) && (__GNUC__ >= 4)) || \ + (defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001)) + #define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) + #else + #define WARN_UNUSED_RESULT + #endif +#endif /* !WARN_UNUSED_RESULT */ + +#ifndef WC_MAYBE_UNUSED + #if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__) + #define WC_MAYBE_UNUSED __attribute__((unused)) + #else + #define WC_MAYBE_UNUSED + #endif +#endif /* !WC_MAYBE_UNUSED */ + +/* use inlining if compiler allows */ +#ifndef WC_INLINE +#ifndef NO_INLINE + #ifdef _MSC_VER + #define WC_INLINE __inline + #elif defined(__GNUC__) + #ifdef WOLFSSL_VXWORKS + #define WC_INLINE __inline__ + #else + #define WC_INLINE inline + #endif + #elif defined(__IAR_SYSTEMS_ICC__) + #define WC_INLINE inline + #elif defined(THREADX) + #define WC_INLINE _Inline + #elif defined(__ghc__) + #ifndef __cplusplus + #define WC_INLINE __inline + #else + #define WC_INLINE inline + #endif + #elif defined(__CCRX__) + #define WC_INLINE inline + #elif defined(__DCC__) + #ifndef __cplusplus + #define WC_INLINE __inline__ + #else + #define WC_INLINE inline + #endif + #else + #define WC_INLINE WC_MAYBE_UNUSED + #endif +#else + #define WC_INLINE WC_MAYBE_UNUSED +#endif +#endif + /* THREADING/MUTEX SECTION */ #if defined(SINGLE_THREADED) && defined(NO_FILESYSTEM) /* No system headers required for build. */ @@ -75,7 +132,7 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif - #ifndef WOLFSSL_SGX + #if !defined(WOLFSSL_SGX) && !defined(WOLFSSL_NOT_WINDOWS_API) #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN) /* On WinCE winsock2.h must be included before windows.h */ #include @@ -320,6 +377,10 @@ #endif /* SINGLE_THREADED */ +#ifdef WOLFSSL_TEST_NO_MUTEX_INITIALIZER + #undef WOLFSSL_MUTEX_INITIALIZER +#endif + #ifdef WOLFSSL_MUTEX_INITIALIZER #define WOLFSSL_MUTEX_INITIALIZER_CLAUSE(lockname) = WOLFSSL_MUTEX_INITIALIZER(lockname) #else @@ -331,11 +392,16 @@ #endif #ifndef WOLFSSL_NO_ATOMICS -#ifdef HAVE_C___ATOMIC +#ifdef SINGLE_THREADED + typedef int wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) + #define WOLFSSL_ATOMIC_OPS +#elif defined(HAVE_C___ATOMIC) #ifdef __cplusplus #if defined(__GNUC__) && defined(__ATOMIC_RELAXED) /* C++ using direct calls to compiler built-in functions */ typedef volatile int wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) #define WOLFSSL_ATOMIC_OPS #endif #else @@ -343,10 +409,11 @@ /* Default C Implementation */ #include typedef atomic_int wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) #define WOLFSSL_ATOMIC_OPS #endif /* WOLFSSL_HAVE_ATOMIC_H */ #endif -#elif defined(_MSC_VER) +#elif defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API) /* Use MSVC compiler intrinsics for atomic ops */ #ifdef _WIN32_WCE #include @@ -354,38 +421,52 @@ #include #endif typedef volatile long wolfSSL_Atomic_Int; + #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) #define WOLFSSL_ATOMIC_OPS #endif #endif /* WOLFSSL_NO_ATOMICS */ -#ifdef WOLFSSL_ATOMIC_OPS +#if defined(WOLFSSL_ATOMIC_OPS) && !defined(SINGLE_THREADED) WOLFSSL_API void wolfSSL_Atomic_Int_Init(wolfSSL_Atomic_Int* c, int i); /* Fetch* functions return the value of the counter immediately preceding * the effects of the function. */ WOLFSSL_API int wolfSSL_Atomic_Int_FetchAdd(wolfSSL_Atomic_Int* c, int i); WOLFSSL_API int wolfSSL_Atomic_Int_FetchSub(wolfSSL_Atomic_Int* c, int i); #else - /* Code using these fallback macros needs to arrange its own fallback for - * wolfSSL_Atomic_Int, which is never defined if - * !defined(WOLFSSL_ATOMIC_OPS). This forces local awareness of - * thread-unsafe semantics. + /* Code using these fallback implementations in non-SINGLE_THREADED builds + * needs to arrange its own explicit fallback to int for wolfSSL_Atomic_Int, + * which is not defined if !defined(WOLFSSL_ATOMIC_OPS) && + * !defined(SINGLE_THREADED). This forces local awareness of thread-unsafe + * semantics. */ #define wolfSSL_Atomic_Int_Init(c, i) (*(c) = (i)) - #define wolfSSL_Atomic_Int_FetchAdd(c, i) (*(c) += (i), *(c) - (i)) - #define wolfSSL_Atomic_Int_FetchSub(c, i) (*(c) -= (i), *(c) + (i)) + static WC_INLINE int wolfSSL_Atomic_Int_FetchAdd(int *c, int i) { + int ret = *c; + *c += i; + return ret; + } + static WC_INLINE int wolfSSL_Atomic_Int_FetchSub(int *c, int i) { + int ret = *c; + *c -= i; + return ret; + } #endif /* Reference counting. */ -typedef struct wolfSSL_Ref { -#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_ATOMIC_OPS) +typedef struct wolfSSL_RefWithMutex { +#if !defined(SINGLE_THREADED) wolfSSL_Mutex mutex; #endif -#ifdef WOLFSSL_ATOMIC_OPS + int count; +} wolfSSL_RefWithMutex; + +#if defined(WOLFSSL_ATOMIC_OPS) && !defined(SINGLE_THREADED) +typedef struct wolfSSL_Ref { wolfSSL_Atomic_Int count; +} wolfSSL_Ref; #else - int count; +typedef struct wolfSSL_RefWithMutex wolfSSL_Ref; #endif -} wolfSSL_Ref; #if defined(SINGLE_THREADED) || defined(WOLFSSL_ATOMIC_OPS) @@ -412,10 +493,33 @@ typedef struct wolfSSL_Ref { #define WOLFSSL_REFCNT_ERROR_RETURN -WOLFSSL_LOCAL void wolfSSL_RefInit(wolfSSL_Ref* ref, int* err); -WOLFSSL_LOCAL void wolfSSL_RefFree(wolfSSL_Ref* ref); -WOLFSSL_LOCAL void wolfSSL_RefInc(wolfSSL_Ref* ref, int* err); -WOLFSSL_LOCAL void wolfSSL_RefDec(wolfSSL_Ref* ref, int* isZero, int* err); +#define wolfSSL_RefInit wolfSSL_RefWithMutexInit +#define wolfSSL_RefFree wolfSSL_RefWithMutexFree +#define wolfSSL_RefInc wolfSSL_RefWithMutexInc +#define wolfSSL_RefDec wolfSSL_RefWithMutexDec + +#endif + +#if defined(SINGLE_THREADED) + +#define wolfSSL_RefWithMutexInit wolfSSL_RefInit +#define wolfSSL_RefWithMutexFree wolfSSL_RefFree +#define wolfSSL_RefWithMutexInc wolfSSL_RefInc +#define wolfSSL_RefWithMutexLock(ref) 0 +#define wolfSSL_RefWithMutexUnlock(ref) 0 +#define wolfSSL_RefWithMutexDec wolfSSL_RefDec + +#else + +WOLFSSL_LOCAL void wolfSSL_RefWithMutexInit(wolfSSL_RefWithMutex* ref, + int* err); +WOLFSSL_LOCAL void wolfSSL_RefWithMutexFree(wolfSSL_RefWithMutex* ref); +WOLFSSL_LOCAL void wolfSSL_RefWithMutexInc(wolfSSL_RefWithMutex* ref, + int* err); +WOLFSSL_LOCAL int wolfSSL_RefWithMutexLock(wolfSSL_RefWithMutex* ref); +WOLFSSL_LOCAL int wolfSSL_RefWithMutexUnlock(wolfSSL_RefWithMutex* ref); +WOLFSSL_LOCAL void wolfSSL_RefWithMutexDec(wolfSSL_RefWithMutex* ref, + int* isZero, int* err); #endif @@ -947,9 +1051,11 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); /* Windows API defines its own min() macro. */ #if defined(USE_WINDOWS_API) #if defined(min) || defined(WOLFSSL_MYSQL_COMPATIBLE) + #undef WOLFSSL_HAVE_MIN #define WOLFSSL_HAVE_MIN #endif /* min */ #if defined(max) || defined(WOLFSSL_MYSQL_COMPATIBLE) + #undef WOLFSSL_HAVE_MAX #define WOLFSSL_HAVE_MAX #endif /* max */ #endif /* USE_WINDOWS_API */ @@ -1273,7 +1379,8 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #endif /* !NO_ASN_TIME */ -#ifndef WOLFSSL_LEANPSK +#if (!defined(WOLFSSL_LEANPSK) && !defined(STRING_USER)) || \ + defined(USE_WOLF_STRNSTR) char* mystrnstr(const char* s1, const char* s2, unsigned int n); #endif @@ -1291,9 +1398,9 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); /* By default, the OCTEON's global variables are all thread local. This * tag allows them to be shared between threads. */ #include "cvmx-platform.h" - #define WOLFSSL_GLOBAL CVMX_SHARED + #define WC_THREADSHARED CVMX_SHARED #else - #define WOLFSSL_GLOBAL + #define WC_THREADSHARED #endif #ifdef WOLFSSL_DSP @@ -1331,10 +1438,13 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) #include #define XFENCE() atomic_thread_fence(memory_order_seq_cst) - #elif defined(__GNUC__) && (__GNUC__ >= 4) && (__GNUC__ < 5) + #elif defined(__GNUC__) && (__GNUC__ == 4) && \ + defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 1) #define XFENCE() __sync_synchronize() #elif (defined(__GNUC__) && (__GNUC__ >= 5)) || defined (__clang__) #define XFENCE() __atomic_thread_fence(__ATOMIC_SEQ_CST) + #elif defined(WOLFSSL_NO_ASM) + #define XFENCE() WC_DO_NOTHING #elif defined (__i386__) || defined(__x86_64__) #define XFENCE() XASM_VOLATILE("lfence") #elif (defined (__arm__) && (__ARM_ARCH > 6)) || defined(__aarch64__) diff --git a/src/wolfssl/wolfio.h b/src/wolfssl/wolfio.h index 2cd43c7..4d1145b 100644 --- a/src/wolfssl/wolfio.h +++ b/src/wolfssl/wolfio.h @@ -416,7 +416,7 @@ #endif #endif #ifndef XSOCKOPT_TYPE_OPTVAL_TYPE - #ifdef USE_WINDOWS_API + #ifndef USE_WINDOWS_API #define XSOCKOPT_TYPE_OPTVAL_TYPE void* #else #define XSOCKOPT_TYPE_OPTVAL_TYPE char* @@ -520,13 +520,19 @@ WOLFSSL_API int wolfIO_RecvFrom(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, #endif #endif /* WOLFSSL_NO_SOCK */ +WOLFSSL_API int wolfSSL_BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx); +WOLFSSL_API int wolfSSL_BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); +#ifndef OPENSSL_COEXIST /* Preserve API previously exposed */ -WOLFSSL_API int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx); -WOLFSSL_API int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); +#define BioSend wolfSSL_BioSend +#define BioReceive wolfSSL_BioReceive +#endif WOLFSSL_LOCAL int SslBioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx); +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_LOCAL int BioReceiveInternal(WOLFSSL_BIO* biord, WOLFSSL_BIO* biowr, char* buf, int sz); +#endif WOLFSSL_LOCAL int SslBioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx); #if defined(USE_WOLFSSL_IO) /* default IO callbacks */ @@ -605,6 +611,8 @@ WOLFSSL_API void wolfSSL_CTX_SetIORecv(WOLFSSL_CTX *ctx, CallbackIORecv CBIORecv WOLFSSL_API void wolfSSL_CTX_SetIOSend(WOLFSSL_CTX *ctx, CallbackIOSend CBIOSend); WOLFSSL_API void wolfSSL_SSLSetIORecv(WOLFSSL *ssl, CallbackIORecv CBIORecv); WOLFSSL_API void wolfSSL_SSLSetIOSend(WOLFSSL *ssl, CallbackIOSend CBIOSend); +WOLFSSL_API void wolfSSL_SSLDisableRead(WOLFSSL *ssl); +WOLFSSL_API void wolfSSL_SSLEnableRead(WOLFSSL *ssl); /* deprecated old name */ #define wolfSSL_SetIORecv wolfSSL_CTX_SetIORecv #define wolfSSL_SetIOSend wolfSSL_CTX_SetIOSend From cccc88420fd2fc9a42fdeb95d52d16728bb7cccb Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Wed, 7 May 2025 11:00:01 +0200 Subject: [PATCH 07/13] wolfssl 5.8.0 Release for Arduino --- ChangeLog.md | 210 + README | 300 +- README.md | 305 +- examples/template/README.md | 34 + examples/template/template.ino | 143 + examples/template/wolfssl_helper.c | 52 + examples/template/wolfssl_helper.h | 37 + .../wolfssl_library/src/wolfssl_library.cpp | 42 + .../wolfssl_library/wolfssl_library.h | 46 + examples/wolfssl_AES_CTR/README.md | 34 + examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino | 268 + examples/wolfssl_client/README.md | 6 + examples/wolfssl_client/wolfssl_client.ino | 13 +- examples/wolfssl_server/README.md | 6 + examples/wolfssl_server/wolfssl_server.ino | 14 +- examples/wolfssl_version/wolfssl_version.ino | 23 +- library.properties | 2 +- src/src/bio.c | 105 +- src/src/conf.c | 40 +- src/src/crl.c | 49 +- src/src/dtls.c | 19 +- src/src/dtls13.c | 147 +- src/src/internal.c | 965 ++- src/src/keys.c | 23 +- src/src/ocsp.c | 460 +- src/src/pk.c | 111 +- src/src/quic.c | 34 +- src/src/sniffer.c | 11 +- src/src/ssl.c | 1847 +++-- src/src/ssl_asn1.c | 75 +- src/src/ssl_bn.c | 468 +- src/src/ssl_certman.c | 9 +- src/src/ssl_crypto.c | 29 +- src/src/ssl_load.c | 254 +- src/src/ssl_misc.c | 10 +- src/src/ssl_p7p12.c | 14 +- src/src/ssl_sess.c | 42 +- src/src/tls.c | 2190 ++++-- src/src/tls13.c | 559 +- src/src/wolfio.c | 65 +- src/src/x509.c | 386 +- src/src/x509_str.c | 125 +- src/user_settings.h | 34 +- src/wolfcrypt/src/aes.c | 596 +- src/wolfcrypt/src/arc4.c | 10 +- src/wolfcrypt/src/ascon.c | 521 ++ src/wolfcrypt/src/asm.c | 9 +- src/wolfcrypt/src/asn.c | 2203 ++++-- src/wolfcrypt/src/bio.c | 105 +- src/wolfcrypt/src/blake2b.c | 33 +- src/wolfcrypt/src/blake2s.c | 33 +- src/wolfcrypt/src/camellia.c | 11 +- src/wolfcrypt/src/chacha.c | 14 +- src/wolfcrypt/src/chacha20_poly1305.c | 10 +- src/wolfcrypt/src/cmac.c | 15 +- src/wolfcrypt/src/coding.c | 198 +- src/wolfcrypt/src/compress.c | 12 +- src/wolfcrypt/src/cpuid.c | 31 +- src/wolfcrypt/src/cryptocb.c | 38 +- src/wolfcrypt/src/curve25519.c | 214 +- src/wolfcrypt/src/curve448.c | 9 +- src/wolfcrypt/src/des3.c | 14 +- src/wolfcrypt/src/dh.c | 117 +- src/wolfcrypt/src/dilithium.c | 158 +- src/wolfcrypt/src/dsa.c | 11 +- src/wolfcrypt/src/ecc.c | 112 +- src/wolfcrypt/src/eccsi.c | 11 +- src/wolfcrypt/src/ed25519.c | 14 +- src/wolfcrypt/src/ed448.c | 10 +- src/wolfcrypt/src/error.c | 17 +- src/wolfcrypt/src/evp.c | 761 ++- src/wolfcrypt/src/ext_lms.c | 18 +- src/wolfcrypt/src/ext_mlkem.c | 762 +++ src/wolfcrypt/src/ext_xmss.c | 9 +- src/wolfcrypt/src/falcon.c | 38 +- src/wolfcrypt/src/fe_448.c | 24 +- src/wolfcrypt/src/fe_low_mem.c | 9 +- src/wolfcrypt/src/fe_operations.c | 98 +- src/wolfcrypt/src/ge_448.c | 1168 ++-- src/wolfcrypt/src/ge_low_mem.c | 10 +- src/wolfcrypt/src/ge_operations.c | 16 +- src/wolfcrypt/src/hash.c | 10 +- src/wolfcrypt/src/hmac.c | 424 +- src/wolfcrypt/src/hpke.c | 108 +- src/wolfcrypt/src/integer.c | 57 +- src/wolfcrypt/src/kdf.c | 30 +- src/wolfcrypt/src/logging.c | 28 +- src/wolfcrypt/src/md2.c | 23 +- src/wolfcrypt/src/md4.c | 24 +- src/wolfcrypt/src/md5.c | 12 +- src/wolfcrypt/src/memory.c | 26 +- src/wolfcrypt/src/misc.c | 522 +- src/wolfcrypt/src/pkcs12.c | 79 +- src/wolfcrypt/src/pkcs7.c | 1419 ++-- src/wolfcrypt/src/poly1305.c | 58 +- src/wolfcrypt/src/port/Espressif/esp32_aes.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 31 +- .../src/port/Espressif/esp_sdk_mem_lib.c | 2 +- .../src/port/Espressif/esp_sdk_time_lib.c | 2 +- .../src/port/Espressif/esp_sdk_wifi_lib.c | 2 +- src/wolfcrypt/src/port/atmel/atmel.c | 2 +- src/wolfcrypt/src/pwdbased.c | 15 +- src/wolfcrypt/src/random.c | 91 +- src/wolfcrypt/src/rc2.c | 10 +- src/wolfcrypt/src/ripemd.c | 12 +- src/wolfcrypt/src/rsa.c | 60 +- src/wolfcrypt/src/sakke.c | 11 +- src/wolfcrypt/src/sha.c | 13 +- src/wolfcrypt/src/sha256.c | 20 +- src/wolfcrypt/src/sha3.c | 28 +- src/wolfcrypt/src/sha512.c | 36 +- src/wolfcrypt/src/signature.c | 10 +- src/wolfcrypt/src/siphash.c | 13 +- src/wolfcrypt/src/sm2.c | 8 +- src/wolfcrypt/src/sm3.c | 8 +- src/wolfcrypt/src/sm4.c | 8 +- src/wolfcrypt/src/sp_arm32.c | 3782 +++++++++-- src/wolfcrypt/src/sp_arm64.c | 9 +- src/wolfcrypt/src/sp_armthumb.c | 51 +- src/wolfcrypt/src/sp_c32.c | 9 +- src/wolfcrypt/src/sp_c64.c | 9 +- src/wolfcrypt/src/sp_cortexm.c | 1527 +++-- src/wolfcrypt/src/sp_dsp32.c | 10 +- src/wolfcrypt/src/sp_int.c | 212 +- src/wolfcrypt/src/sp_sm2_arm32.c | 8 +- src/wolfcrypt/src/sp_sm2_arm64.c | 8 +- src/wolfcrypt/src/sp_sm2_armthumb.c | 8 +- src/wolfcrypt/src/sp_sm2_c32.c | 8 +- src/wolfcrypt/src/sp_sm2_c64.c | 8 +- src/wolfcrypt/src/sp_sm2_cortexm.c | 8 +- src/wolfcrypt/src/sp_sm2_x86_64.c | 8 +- src/wolfcrypt/src/sp_x86_64.c | 9 +- src/wolfcrypt/src/sphincs.c | 12 +- src/wolfcrypt/src/srp.c | 95 +- src/wolfcrypt/src/tfm.c | 15 +- src/wolfcrypt/src/wc_dsp.c | 9 +- src/wolfcrypt/src/wc_encrypt.c | 14 +- src/wolfcrypt/src/wc_lms.c | 49 +- src/wolfcrypt/src/wc_lms_impl.c | 38 +- src/wolfcrypt/src/wc_mlkem.c | 2070 ++++++ src/wolfcrypt/src/wc_mlkem_poly.c | 5986 +++++++++++++++++ src/wolfcrypt/src/wc_pkcs11.c | 10 +- src/wolfcrypt/src/wc_port.c | 366 +- src/wolfcrypt/src/wc_xmss.c | 10 +- src/wolfcrypt/src/wc_xmss_impl.c | 100 +- src/wolfcrypt/src/wolfevent.c | 10 +- src/wolfcrypt/src/wolfmath.c | 10 +- src/wolfssl-arduino.cpp | 33 + src/wolfssl.h | 16 +- src/wolfssl/bio.c | 105 +- src/wolfssl/callbacks.h | 2 +- src/wolfssl/crl.h | 2 +- src/wolfssl/error-ssl.h | 2 +- src/wolfssl/evp.c | 761 ++- src/wolfssl/internal.h | 157 +- src/wolfssl/ocsp.h | 2 +- src/wolfssl/openssl/aes.h | 2 +- src/wolfssl/openssl/asn1.h | 7 +- src/wolfssl/openssl/asn1t.h | 2 +- src/wolfssl/openssl/bio.h | 3 +- src/wolfssl/openssl/bn.h | 43 +- src/wolfssl/openssl/buffer.h | 2 +- src/wolfssl/openssl/camellia.h | 2 +- src/wolfssl/openssl/cmac.h | 2 +- src/wolfssl/openssl/cms.h | 2 +- src/wolfssl/openssl/compat_types.h | 2 +- src/wolfssl/openssl/conf.h | 2 +- src/wolfssl/openssl/crypto.h | 2 +- src/wolfssl/openssl/des.h | 2 +- src/wolfssl/openssl/dh.h | 2 +- src/wolfssl/openssl/dsa.h | 2 +- src/wolfssl/openssl/ec.h | 2 +- src/wolfssl/openssl/ec25519.h | 2 +- src/wolfssl/openssl/ec448.h | 2 +- src/wolfssl/openssl/ecdh.h | 2 +- src/wolfssl/openssl/ecdsa.h | 2 +- src/wolfssl/openssl/ed25519.h | 2 +- src/wolfssl/openssl/ed448.h | 2 +- src/wolfssl/openssl/err.h | 2 +- src/wolfssl/openssl/evp.h | 14 +- src/wolfssl/openssl/fips_rand.h | 2 +- src/wolfssl/openssl/hmac.h | 2 +- src/wolfssl/openssl/kdf.h | 2 +- src/wolfssl/openssl/lhash.h | 2 +- src/wolfssl/openssl/md4.h | 2 +- src/wolfssl/openssl/md5.h | 2 +- src/wolfssl/openssl/modes.h | 2 +- src/wolfssl/openssl/obj_mac.h | 23 +- src/wolfssl/openssl/objects.h | 4 +- src/wolfssl/openssl/ocsp.h | 2 +- src/wolfssl/openssl/opensslv.h | 2 +- src/wolfssl/openssl/ossl_typ.h | 2 +- src/wolfssl/openssl/pem.h | 2 +- src/wolfssl/openssl/pkcs12.h | 2 +- src/wolfssl/openssl/pkcs7.h | 2 +- src/wolfssl/openssl/rand.h | 2 +- src/wolfssl/openssl/rc4.h | 2 +- src/wolfssl/openssl/ripemd.h | 2 +- src/wolfssl/openssl/rsa.h | 2 +- src/wolfssl/openssl/safestack.h | 2 +- src/wolfssl/openssl/sha.h | 2 +- src/wolfssl/openssl/sha3.h | 2 +- src/wolfssl/openssl/srp.h | 2 +- src/wolfssl/openssl/ssl.h | 25 +- src/wolfssl/openssl/stack.h | 2 +- src/wolfssl/openssl/tls1.h | 2 +- src/wolfssl/openssl/txt_db.h | 2 +- src/wolfssl/openssl/x509.h | 5 +- src/wolfssl/openssl/x509_vfy.h | 2 +- src/wolfssl/openssl/x509v3.h | 2 +- src/wolfssl/quic.h | 2 +- src/wolfssl/sniffer.h | 2 +- src/wolfssl/sniffer_error.h | 2 +- src/wolfssl/ssl.h | 199 +- src/wolfssl/test.h | 113 +- src/wolfssl/version.h | 6 +- src/wolfssl/wolfcrypt/aes.h | 59 +- src/wolfssl/wolfcrypt/arc4.h | 2 +- src/wolfssl/wolfcrypt/ascon.h | 109 + src/wolfssl/wolfcrypt/asn.h | 248 +- src/wolfssl/wolfcrypt/asn_public.h | 11 +- src/wolfssl/wolfcrypt/blake2-impl.h | 2 +- src/wolfssl/wolfcrypt/blake2-int.h | 2 +- src/wolfssl/wolfcrypt/blake2.h | 6 +- src/wolfssl/wolfcrypt/camellia.h | 2 +- src/wolfssl/wolfcrypt/chacha.h | 2 +- src/wolfssl/wolfcrypt/chacha20_poly1305.h | 10 +- src/wolfssl/wolfcrypt/cmac.h | 2 +- src/wolfssl/wolfcrypt/coding.h | 5 +- src/wolfssl/wolfcrypt/compress.h | 2 +- src/wolfssl/wolfcrypt/cpuid.h | 2 +- src/wolfssl/wolfcrypt/cryptocb.h | 116 +- src/wolfssl/wolfcrypt/curve25519.h | 24 +- src/wolfssl/wolfcrypt/curve448.h | 2 +- src/wolfssl/wolfcrypt/des3.h | 2 +- src/wolfssl/wolfcrypt/dh.h | 2 +- src/wolfssl/wolfcrypt/dilithium.h | 67 +- src/wolfssl/wolfcrypt/dsa.h | 2 +- src/wolfssl/wolfcrypt/ecc.h | 5 +- src/wolfssl/wolfcrypt/eccsi.h | 2 +- src/wolfssl/wolfcrypt/ed25519.h | 3 +- src/wolfssl/wolfcrypt/ed448.h | 2 +- src/wolfssl/wolfcrypt/error-crypt.h | 12 +- src/wolfssl/wolfcrypt/ext_lms.h | 2 +- src/wolfssl/wolfcrypt/ext_mlkem.h | 74 + src/wolfssl/wolfcrypt/ext_xmss.h | 2 +- src/wolfssl/wolfcrypt/falcon.h | 2 +- src/wolfssl/wolfcrypt/fe_448.h | 5 +- src/wolfssl/wolfcrypt/fe_operations.h | 6 +- src/wolfssl/wolfcrypt/fips_test.h | 6 +- src/wolfssl/wolfcrypt/ge_448.h | 2 +- src/wolfssl/wolfcrypt/ge_operations.h | 2 +- src/wolfssl/wolfcrypt/hash.h | 12 +- src/wolfssl/wolfcrypt/hmac.h | 6 +- src/wolfssl/wolfcrypt/hpke.h | 11 +- src/wolfssl/wolfcrypt/integer.h | 2 +- src/wolfssl/wolfcrypt/kdf.h | 2 +- src/wolfssl/wolfcrypt/libwolfssl_sources.h | 50 + .../wolfcrypt/libwolfssl_sources_asm.h | 48 + src/wolfssl/wolfcrypt/lms.h | 8 +- src/wolfssl/wolfcrypt/logging.h | 6 +- src/wolfssl/wolfcrypt/md2.h | 2 +- src/wolfssl/wolfcrypt/md4.h | 2 +- src/wolfssl/wolfcrypt/md5.h | 2 +- src/wolfssl/wolfcrypt/mem_track.h | 6 +- src/wolfssl/wolfcrypt/memory.h | 2 +- src/wolfssl/wolfcrypt/misc.h | 5 +- src/wolfssl/wolfcrypt/mlkem.h | 374 + src/wolfssl/wolfcrypt/mpi_class.h | 2 +- src/wolfssl/wolfcrypt/mpi_superclass.h | 2 +- src/wolfssl/wolfcrypt/pkcs11.h | 2 +- src/wolfssl/wolfcrypt/pkcs12.h | 5 +- src/wolfssl/wolfcrypt/pkcs7.h | 17 +- src/wolfssl/wolfcrypt/poly1305.h | 16 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 2 +- .../wolfcrypt/port/Espressif/esp32-crypt.h | 48 +- .../wolfcrypt/port/Espressif/esp_crt_bundle.h | 2 +- src/wolfssl/wolfcrypt/port/atmel/atmel.h | 2 +- src/wolfssl/wolfcrypt/pwdbased.h | 2 +- src/wolfssl/wolfcrypt/random.h | 2 +- src/wolfssl/wolfcrypt/rc2.h | 2 +- src/wolfssl/wolfcrypt/ripemd.h | 2 +- src/wolfssl/wolfcrypt/rsa.h | 2 +- src/wolfssl/wolfcrypt/sakke.h | 2 +- src/wolfssl/wolfcrypt/selftest.h | 2 +- src/wolfssl/wolfcrypt/settings.h | 137 +- src/wolfssl/wolfcrypt/sha.h | 2 +- src/wolfssl/wolfcrypt/sha256.h | 8 +- src/wolfssl/wolfcrypt/sha3.h | 3 +- src/wolfssl/wolfcrypt/sha512.h | 4 +- src/wolfssl/wolfcrypt/signature.h | 2 +- src/wolfssl/wolfcrypt/siphash.h | 2 +- src/wolfssl/wolfcrypt/sm2.h | 2 +- src/wolfssl/wolfcrypt/sm3.h | 2 +- src/wolfssl/wolfcrypt/sm4.h | 2 +- src/wolfssl/wolfcrypt/sp.h | 2 +- src/wolfssl/wolfcrypt/sp_int.h | 21 +- src/wolfssl/wolfcrypt/sphincs.h | 2 +- src/wolfssl/wolfcrypt/srp.h | 2 +- src/wolfssl/wolfcrypt/tfm.h | 2 +- src/wolfssl/wolfcrypt/types.h | 173 +- src/wolfssl/wolfcrypt/visibility.h | 33 +- src/wolfssl/wolfcrypt/wc_encrypt.h | 2 +- src/wolfssl/wolfcrypt/wc_lms.h | 28 +- src/wolfssl/wolfcrypt/wc_mlkem.h | 378 ++ src/wolfssl/wolfcrypt/wc_pkcs11.h | 2 +- src/wolfssl/wolfcrypt/wc_port.h | 107 +- src/wolfssl/wolfcrypt/wc_xmss.h | 2 +- src/wolfssl/wolfcrypt/wolfevent.h | 2 +- src/wolfssl/wolfcrypt/wolfmath.h | 17 +- src/wolfssl/wolfcrypt/xmss.h | 2 +- src/wolfssl/wolfio.h | 91 +- 314 files changed, 30464 insertions(+), 8361 deletions(-) create mode 100644 examples/template/README.md create mode 100644 examples/template/template.ino create mode 100644 examples/template/wolfssl_helper.c create mode 100644 examples/template/wolfssl_helper.h create mode 100644 examples/template/wolfssl_library/src/wolfssl_library.cpp create mode 100644 examples/template/wolfssl_library/wolfssl_library.h create mode 100644 examples/wolfssl_AES_CTR/README.md create mode 100644 examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino create mode 100644 src/wolfcrypt/src/ascon.c create mode 100644 src/wolfcrypt/src/ext_mlkem.c create mode 100644 src/wolfcrypt/src/wc_mlkem.c create mode 100644 src/wolfcrypt/src/wc_mlkem_poly.c create mode 100644 src/wolfssl-arduino.cpp create mode 100644 src/wolfssl/wolfcrypt/ascon.h create mode 100644 src/wolfssl/wolfcrypt/ext_mlkem.h create mode 100644 src/wolfssl/wolfcrypt/libwolfssl_sources.h create mode 100644 src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h create mode 100644 src/wolfssl/wolfcrypt/mlkem.h create mode 100644 src/wolfssl/wolfcrypt/wc_mlkem.h diff --git a/ChangeLog.md b/ChangeLog.md index 0b32346..a9cdff9 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,213 @@ +# wolfSSL Release 5.8.0 (Apr 24, 2025) + +Release 5.8.0 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is deprecated + +PR stands for Pull Request, and PR references a GitHub pull request + number where the code change was added. + + +## New Feature Additions +* Algorithm registration in the Linux kernel module for all supported FIPS AES, + SHA, HMAC, ECDSA, ECDH, and RSA modes, key sizes, and digest sizes. +* Implemented various fixes to support building for Open Watcom including OS/2 + support and Open Watcom 1.9 compatibility (PR 8505, 8484) +* Added support for STM32H7S (tested on NUCLEO-H7S3L8) (PR 8488) +* Added support for STM32WBA (PR 8550) +* Added Extended Master Secret Generation Callback to the --enable-pkcallbacks + build (PR 8303) +* Implement AES-CTS (configure flag --enable-aescts) in wolfCrypt (PR 8594) +* Added support for libimobiledevice commit 860ffb (PR 8373) +* Initial ASCON hash256 and AEAD128 support based on NIST SP 800-232 IPD + (PR 8307) +* Added blinding option when using a Curve25519 private key by defining the + macro WOLFSSL_CURVE25519_BLINDING (PR 8392) + + +## Linux Kernel Module +* Production-ready LKCAPI registration for cbc(aes), cfb(aes), gcm(aes), + rfc4106 (gcm(aes)), ctr(aes), ofb(aes), and ecb(aes), ECDSA with P192, P256, + P384, and P521 curves, ECDH with P192, P256, and P384 curves, and RSA with + bare and PKCS1 padding +* Various fixes for LKCAPI wrapper for AES-CBC and AES-CFB (PR 8534, 8552) +* Adds support for the legacy one-shot AES-GCM back end (PR 8614, 8567) for + compatibility with FIPS 140-3 Cert #4718. +* On kernel >=6.8, for CONFIG_FORTIFY_SOURCE, use 5-arg fortify_panic() override + macro (PR 8654) +* Update calls to scatterwalk_map() and scatterwalk_unmap() for linux commit + 7450ebd29c (merged for Linux 6.15) (PR 8667) +* Inhibit LINUXKM_LKCAPI_REGISTER_ECDH on kernel <5.13 (PR 8673) +* Fix for uninitialized build error with fedora (PR 8569) +* Register ecdsa, ecdh, and rsa for use with linux kernel crypto (PR 8637, 8663, + 8646) +* Added force zero shared secret buffer, and clear of old key with ecdh + (PR 8685) +* Update fips-check.sh script to pickup XTS streaming support on aarch64 and + disable XTS-384 as an allowed use in FIPS mode (PR 8509, 8546) + + +## Enhancements and Optimizations + +### Security & Cryptography +* Add constant-time implementation improvements for encoding functions. We thank + Zhiyuan and Gilles for sharing a new constant-time analysis tool (CT-LLVM) and + reporting several non-constant-time implementations. (PR 8396, 8617) +* Additional support for PKCS7 verify and decode with indefinite lengths + (PR 8520, 834, 8645) +* Add more PQC hybrid key exchange algorithms such as support for combinations + with X25519 and X448 enabling compatibility with the PQC key exchange support + in Chromium browsers and Mozilla Firefox (PR 7821) +* Add short-circuit comparisons to DH key validation for RFC 7919 parameters + (PR 8335) +* Improve FIPS compatibility with various build configurations for more resource + constrained builds (PR 8370) +* Added option to disable ECC public key order checking (PR 8581) +* Allow critical alt and basic constraints extensions (PR 8542) +* New codepoint for MLDSA to help with interoperability (PR 8393) +* Add support for parsing trusted PEM certs having the header + “BEGIN_TRUSTED_CERT” (PR 8400) +* Add support for parsing only of DoD certificate policy and Comodo Ltd PKI OIDs + (PR 8599, 8686) +* Update ssl code in `src/*.c` to be consistent with wolfcrypt/src/asn.c + handling of ML_DSA vs Dilithium and add dual alg. test (PR 8360, 8425) + +### Build System, Configuration, CI & Protocols +* Internal refactor for include of config.h and when building with + BUILDING_WOLFSSL macro. This refactor will give a warning of “deprecated + function” when trying to improperly use an internal API of wolfSSL in an + external application. (PR 8640, 8647, 8660, 8662, 8664) +* Add WOLFSSL_CLU option to CMakeLists.txt (PR 8548) +* Add CMake and Zephyr support for XMSS and LMS (PR 8494) +* Added GitHub CI for CMake builds (PR 8439) +* Added necessary macros when building wolfTPM Zephyr with wolfSSL (PR 8382) +* Add MSYS2 build continuous integration test (PR 8504) +* Update DevKitPro doc to list calico dependency with build commands (PR 8607) +* Conversion compiler warning fixes and additional continuous integration test + added (PR 8538) +* Enable DTLS 1.3 by default in --enable-jni builds (PR 8481) +* Enabled TLS 1.3 middlebox compatibility by default for --enable-jni builds + (PR 8526) + +### Performance Improvements +* Performance improvements AES-GCM and HMAC (in/out hash copy) (PR 8429) +* LMS fixes and improvements adding API to get Key ID from raw private key, + change to identifiers to match standard, and fix for when + WOLFSSL_LMS_MAX_LEVELS is 1 (PR 8390, 8684, 8613, 8623) +* ML-KEM/Kyber improvements and fixes; no malloc builds, small memory usage, + performance improvement, fix for big-endian (PR 8397, 8412, 8436, 8467, 8619, + 8622, 8588) +* Performance improvements for AES-GCM and when doing multiple HMAC operations + (PR 8445) + +### Assembly and Platform-Specific Enhancements +* Poly1305 arm assembly changes adding ARM32 NEON implementation and fix for + Aarch64 use (PR 8344, 8561, 8671) +* Aarch64 assembly enhancement to use more CPU features, fix for FreeBSD/OpenBSD + (PR 8325, 8348) +* Only perform ARM assembly CPUID checks if support was enabled at build time + (PR 8566) +* Optimizations for ARM32 assembly instructions on platforms less than ARMv7 + (PR 8395) +* Improve MSVC feature detection for static assert macros (PR 8440) +* Improve Espressif make and CMake for ESP8266 and ESP32 series (PR 8402) +* Espressif updates for Kconfig, ESP32P4 and adding a sample user_settings.h + (PR 8422, PR 8641) + +### OpenSSL Compatibility Layer +* Modification to the push/pop to/from in OpenSSL compatibility layer. This is + a pretty major API change in the OpenSSL compatibility stack functions. + Previously the API would push/pop from the beginning of the list but now they + operate on the tail of the list. This matters when using the sk_value with + index values. (PR 8616) +* OpenSSL Compat Layer: OCSP response improvements (PR 8408, 8498) +* Expand the OpenSSL compatibility layer to include an implementation of + BN_CTX_get (PR 8388) + +### API Additions and Modifications +* Refactor Hpke to allow multiple uses of a context instead of just one shot + mode (PR 6805) +* Add support for PSK client callback with Ada and use with Alire (thanks + @mgrojo, PR 8332, 8606) +* Change wolfSSL_CTX_GenerateEchConfig to generate multiple configs and add + functions wolfSSL_CTX_SetEchConfigs and wolfSSL_CTX_SetEchConfigsBase64 to + rotate the server's echConfigs (PR 8556) +* Added the public API wc_PkcsPad to do PKCS padding (PR 8502) +* Add NULL_CIPHER_TYPE support to wolfSSL_EVP_CipherUpdate (PR 8518) +* Update Kyber APIs to ML-KEM APIs (PR 8536) +* Add option to disallow automatic use of "default" devId using the macro + WC_NO_DEFAULT_DEVID (PR 8555) +* Detect unknown key format on ProcessBufferTryDecode() and handle RSA-PSSk + format (PR 8630) + +### Porting and Language Support +* Update Python port to support version 3.12.6 (PR 8345) +* New additions for MAXQ with wolfPKCS11 (PR 8343) +* Port to ntp 4.2.8p17 additions (PR 8324) +* Add version 0.9.14 to tested libvncserver builds (PR 8337) + +### General Improvements and Cleanups +* Cleanups for STM32 AES GCM (PR 8584) +* Improvements to isascii() and the CMake key log option (PR 8596) +* Arduino documentation updates, comments and spelling corrections (PR 8381, + 8384, 8514) +* Expanding builds with WOLFSSL_NO_REALLOC for use with --enable-opensslall and + --enable-all builds (PR 8369, 8371) + + +## Fixes +* Fix a use after free caused by an early free on error in the X509 store + (PR 8449) +* Fix to account for existing PKCS8 header with + wolfSSL_PEM_write_PKCS8PrivateKey (PR 8612) +* Fixed failing CMake build issue when standard threads support is not found in + the system (PR 8485) +* Fix segmentation fault in SHA-512 implementation for AVX512 targets built with + gcc -march=native -O2 (PR 8329) +* Fix Windows socket API compatibility warning with mingw32 build (PR 8424) +* Fix potential null pointer increments in cipher list parsing (PR 8420) +* Fix for possible stack buffer overflow read with wolfSSL_SMIME_write_PKCS7. + Thanks to the team at Code Intelligence for the report. (PR 8466) +* Fix AES ECB implementation for Aarch64 ARM assembly (PR 8379) +* Fixed building with VS2008 and .NET 3.5 (PR 8621) +* Fixed possible error case memory leaks in CRL and EVP_Sign_Final (PR 8447) +* Fixed SSL_set_mtu compatibility function return code (PR 8330) +* Fixed Renesas RX TSIP (PR 8595) +* Fixed ECC non-blocking tests (PR 8533) +* Fixed CMake on MINGW and MSYS (PR 8377) +* Fixed Watcom compiler and added new CI test (PR 8391) +* Fixed STM32 PKA ECC 521-bit support (PR 8450) +* Fixed STM32 PKA with P521 and shared secret (PR 8601) +* Fixed crypto callback macro guards with `DEBUG_CRYPTOCB` (PR 8602) +* Fix outlen return for RSA private decrypt with WOLF_CRYPTO_CB_RSA_PAD + (PR 8575) +* Additional sanity check on r and s lengths in DecodeECC_DSA_Sig_Bin (PR 8350) +* Fix compat. layer ASN1_TIME_diff to accept NULL output params (PR 8407) +* Fix CMake lean_tls build (PR 8460) +* Fix for QUIC callback failure (PR 8475) +* Fix missing alert types in AlertTypeToString for print out with debugging + enabled (PR 8572) +* Fixes for MSVS build issues with PQC configure (PR 8568) +* Fix for SE050 port and minor improvements (PR 8431, 8437) +* Fix for missing rewind function in zephyr and add missing files for compiling + with assembly optimizations (PR 8531, 8541) +* Fix for quic_record_append to return the correct code (PR 8340, 8358) +* Fixes for Bind 9.18.28 port (PR 8331) +* Fix to adhere more closely with RFC8446 Appendix D and set haveEMS when + negotiating TLS 1.3 (PR 8487) +* Fix to properly check for signature_algorithms from the client in a TLS 1.3 + server (PR 8356) +* Fix for when BIO data is less than seq buffer size. Thanks to the team at Code + Intelligence for the report (PR 8426) +* ARM32/Thumb2 fixes for WOLFSSL_NO_VAR_ASSIGN_REG and td4 variable declarations + (PR 8590, 8635) +* Fix for Intel AVX1/SSE2 assembly to not use vzeroupper instructions unless ymm + or zmm registers are used (PR 8479) +* Entropy MemUse fix for when block size less than update bits (PR 8675) + + # wolfSSL Release 5.7.6 (Dec 31, 2024) Release 5.7.6 has been developed according to wolfSSL's development and QA diff --git a/README b/README index 47579ee..582977d 100644 --- a/README +++ b/README @@ -70,130 +70,214 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.7.6 (Dec 31, 2024) +# wolfSSL Release 5.8.0 (Apr 24, 2025) -Release 5.7.6 has been developed according to wolfSSL's development and QA +Release 5.8.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: - * --enable-heapmath is deprecated. - * In this release, the default cipher suite preference is updated to prioritize - TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256 when enabled. - * This release adds a sanity check for including wolfssl/options.h or - user_settings.h. - +NOTE: * --enable-heapmath is deprecated PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. -## Vulnerabilities -* [Med] An OCSP (non stapling) issue was introduced in wolfSSL version 5.7.4 - when performing OCSP requests for intermediate certificates in a certificate - chain. This affects only TLS 1.3 connections on the server side. It would not - impact other TLS protocol versions or connections that are not using the - traditional OCSP implementation. (Fix in pull request 8115) - - ## New Feature Additions -* Add support for RP2350 and improve RP2040 support, both with RNG optimizations - (PR 8153) -* Add support for STM32MP135F, including STM32CubeIDE support and HAL support - for SHA2/SHA3/AES/RNG/ECC optimizations. (PR 8223, 8231, 8241) -* Implement Renesas TSIP RSA Public Enc/Private support (PR 8122) -* Add support for Fedora/RedHat system-wide crypto-policies (PR 8205) -* Curve25519 generic keyparsing API added with wc_Curve25519KeyToDer and - wc_Curve25519KeyDecode (PR 8129) -* CRL improvements and update callback, added the functions - wolfSSL_CertManagerGetCRLInfo and wolfSSL_CertManagerSetCRLUpdate_Cb (PR 8006) -* For DTLS, add server-side stateless and CID quality-of-life API. (PR 8224) +* Algorithm registration in the Linux kernel module for all supported FIPS AES, + SHA, HMAC, ECDSA, ECDH, and RSA modes, key sizes, and digest sizes. +* Implemented various fixes to support building for Open Watcom including OS/2 + support and Open Watcom 1.9 compatibility (PR 8505, 8484) +* Added support for STM32H7S (tested on NUCLEO-H7S3L8) (PR 8488) +* Added support for STM32WBA (PR 8550) +* Added Extended Master Secret Generation Callback to the --enable-pkcallbacks + build (PR 8303) +* Implement AES-CTS (configure flag --enable-aescts) in wolfCrypt (PR 8594) +* Added support for libimobiledevice commit 860ffb (PR 8373) +* Initial ASCON hash256 and AEAD128 support based on NIST SP 800-232 IPD + (PR 8307) +* Added blinding option when using a Curve25519 private key by defining the + macro WOLFSSL_CURVE25519_BLINDING (PR 8392) + + +## Linux Kernel Module +* Production-ready LKCAPI registration for cbc(aes), cfb(aes), gcm(aes), + rfc4106 (gcm(aes)), ctr(aes), ofb(aes), and ecb(aes), ECDSA with P192, P256, + P384, and P521 curves, ECDH with P192, P256, and P384 curves, and RSA with + bare and PKCS1 padding +* Various fixes for LKCAPI wrapper for AES-CBC and AES-CFB (PR 8534, 8552) +* Adds support for the legacy one-shot AES-GCM back end (PR 8614, 8567) for + compatibility with FIPS 140-3 Cert #4718. +* On kernel >=6.8, for CONFIG_FORTIFY_SOURCE, use 5-arg fortify_panic() override + macro (PR 8654) +* Update calls to scatterwalk_map() and scatterwalk_unmap() for linux commit + 7450ebd29c (merged for Linux 6.15) (PR 8667) +* Inhibit LINUXKM_LKCAPI_REGISTER_ECDH on kernel <5.13 (PR 8673) +* Fix for uninitialized build error with fedora (PR 8569) +* Register ecdsa, ecdh, and rsa for use with linux kernel crypto (PR 8637, 8663, + 8646) +* Added force zero shared secret buffer, and clear of old key with ecdh + (PR 8685) +* Update fips-check.sh script to pickup XTS streaming support on aarch64 and + disable XTS-384 as an allowed use in FIPS mode (PR 8509, 8546) ## Enhancements and Optimizations -* Add a CMake dependency check for pthreads when required. (PR 8162) -* Update OS_Seed declarations for legacy compilers and FIPS modules (boundary - not affected). (PR 8170) -* Enable WOLFSSL_ALWAYS_KEEP_SNI by default when using --enable-jni. (PR 8283) -* Change the default cipher suite preference, prioritizing - TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256. (PR 7771) -* Add SRTP-KDF (FIPS module v6.0.0) to checkout script for release bundling - (PR 8215) -* Make library build when no hardware crypto available for Aarch64 (PR 8293) -* Update assembly code to avoid `uint*_t` types for better compatibility with - older C standards. (PR 8133) -* Add initial documentation for writing ASN template code to decode BER/DER. - (PR 8120) -* Perform full reduction in sc_muladd for EdDSA with Curve448 (PR 8276) -* Allow SHA-3 hardware cryptography instructions to be explicitly not used in - MacOS builds (PR 8282) -* Make Kyber and ML-KEM available individually and together. (PR 8143) -* Update configuration options to include Kyber/ML-KEM and fix defines used in - wolfSSL_get_curve_name. (PR 8183) -* Make GetShortInt available with WOLFSSL_ASN_EXTRA (PR 8149) -* Improved test coverage and minor improvements of X509 (PR 8176) -* Add sanity checks for configuration methods, ensuring the inclusion of - wolfssl/options.h or user_settings.h. (PR 8262) -* Enable support for building without TLS (NO_TLS). Provides reduced code size - option for non-TLS users who want features like the certificate manager or - compatibility layer. (PR 8273) -* Exposed get_verify functions with OPENSSL_EXTRA. (PR 8258) -* ML-DSA/Dilithium: obtain security level from DER when decoding (PR 8177) -* Implementation for using PKCS11 to retrieve certificate for SSL CTX (PR 8267) -* Add support for the RFC822 Mailbox attribute (PR 8280) -* Initialize variables and adjust types resolve warnings with Visual Studio in - Windows builds. (PR 8181) -* Refactors and expansion of opensslcoexist build (PR 8132, 8216, 8230) -* Add DTLS 1.3 interoperability, libspdm and DTLS CID interoperability tests - (PR 8261, 8255, 8245) -* Remove trailing error exit code in wolfSSL install setup script (PR 8189) -* Update Arduino files for wolfssl 5.7.4 (PR 8219) -* Improve Espressif SHA HW/SW mutex messages (PR 8225) -* Apply post-5.7.4 release updates for Espressif Managed Component examples - (PR 8251) -* Expansion of c89 conformance (PR 8164) -* Added configure option for additional sanity checks with --enable-faultharden - (PR 8289) -* Aarch64 ASM additions to check CPU features before hardware crypto instruction - use (PR 8314) + +### Security & Cryptography +* Add constant-time implementation improvements for encoding functions. We thank + Zhiyuan and Gilles for sharing a new constant-time analysis tool (CT-LLVM) and + reporting several non-constant-time implementations. (PR 8396, 8617) +* Additional support for PKCS7 verify and decode with indefinite lengths + (PR 8520, 834, 8645) +* Add more PQC hybrid key exchange algorithms such as support for combinations + with X25519 and X448 enabling compatibility with the PQC key exchange support + in Chromium browsers and Mozilla Firefox (PR 7821) +* Add short-circuit comparisons to DH key validation for RFC 7919 parameters + (PR 8335) +* Improve FIPS compatibility with various build configurations for more resource + constrained builds (PR 8370) +* Added option to disable ECC public key order checking (PR 8581) +* Allow critical alt and basic constraints extensions (PR 8542) +* New codepoint for MLDSA to help with interoperability (PR 8393) +* Add support for parsing trusted PEM certs having the header + “BEGIN_TRUSTED_CERT” (PR 8400) +* Add support for parsing only of DoD certificate policy and Comodo Ltd PKI OIDs + (PR 8599, 8686) +* Update ssl code in `src/*.c` to be consistent with wolfcrypt/src/asn.c + handling of ML_DSA vs Dilithium and add dual alg. test (PR 8360, 8425) + +### Build System, Configuration, CI & Protocols +* Internal refactor for include of config.h and when building with + BUILDING_WOLFSSL macro. This refactor will give a warning of “deprecated + function” when trying to improperly use an internal API of wolfSSL in an + external application. (PR 8640, 8647, 8660, 8662, 8664) +* Add WOLFSSL_CLU option to CMakeLists.txt (PR 8548) +* Add CMake and Zephyr support for XMSS and LMS (PR 8494) +* Added GitHub CI for CMake builds (PR 8439) +* Added necessary macros when building wolfTPM Zephyr with wolfSSL (PR 8382) +* Add MSYS2 build continuous integration test (PR 8504) +* Update DevKitPro doc to list calico dependency with build commands (PR 8607) +* Conversion compiler warning fixes and additional continuous integration test + added (PR 8538) +* Enable DTLS 1.3 by default in --enable-jni builds (PR 8481) +* Enabled TLS 1.3 middlebox compatibility by default for --enable-jni builds + (PR 8526) + +### Performance Improvements +* Performance improvements AES-GCM and HMAC (in/out hash copy) (PR 8429) +* LMS fixes and improvements adding API to get Key ID from raw private key, + change to identifiers to match standard, and fix for when + WOLFSSL_LMS_MAX_LEVELS is 1 (PR 8390, 8684, 8613, 8623) +* ML-KEM/Kyber improvements and fixes; no malloc builds, small memory usage, + performance improvement, fix for big-endian (PR 8397, 8412, 8436, 8467, 8619, + 8622, 8588) +* Performance improvements for AES-GCM and when doing multiple HMAC operations + (PR 8445) + +### Assembly and Platform-Specific Enhancements +* Poly1305 arm assembly changes adding ARM32 NEON implementation and fix for + Aarch64 use (PR 8344, 8561, 8671) +* Aarch64 assembly enhancement to use more CPU features, fix for FreeBSD/OpenBSD + (PR 8325, 8348) +* Only perform ARM assembly CPUID checks if support was enabled at build time + (PR 8566) +* Optimizations for ARM32 assembly instructions on platforms less than ARMv7 + (PR 8395) +* Improve MSVC feature detection for static assert macros (PR 8440) +* Improve Espressif make and CMake for ESP8266 and ESP32 series (PR 8402) +* Espressif updates for Kconfig, ESP32P4 and adding a sample user_settings.h + (PR 8422, PR 8641) + +### OpenSSL Compatibility Layer +* Modification to the push/pop to/from in OpenSSL compatibility layer. This is + a pretty major API change in the OpenSSL compatibility stack functions. + Previously the API would push/pop from the beginning of the list but now they + operate on the tail of the list. This matters when using the sk_value with + index values. (PR 8616) +* OpenSSL Compat Layer: OCSP response improvements (PR 8408, 8498) +* Expand the OpenSSL compatibility layer to include an implementation of + BN_CTX_get (PR 8388) + +### API Additions and Modifications +* Refactor Hpke to allow multiple uses of a context instead of just one shot + mode (PR 6805) +* Add support for PSK client callback with Ada and use with Alire (thanks + @mgrojo, PR 8332, 8606) +* Change wolfSSL_CTX_GenerateEchConfig to generate multiple configs and add + functions wolfSSL_CTX_SetEchConfigs and wolfSSL_CTX_SetEchConfigsBase64 to + rotate the server's echConfigs (PR 8556) +* Added the public API wc_PkcsPad to do PKCS padding (PR 8502) +* Add NULL_CIPHER_TYPE support to wolfSSL_EVP_CipherUpdate (PR 8518) +* Update Kyber APIs to ML-KEM APIs (PR 8536) +* Add option to disallow automatic use of "default" devId using the macro + WC_NO_DEFAULT_DEVID (PR 8555) +* Detect unknown key format on ProcessBufferTryDecode() and handle RSA-PSSk + format (PR 8630) + +### Porting and Language Support +* Update Python port to support version 3.12.6 (PR 8345) +* New additions for MAXQ with wolfPKCS11 (PR 8343) +* Port to ntp 4.2.8p17 additions (PR 8324) +* Add version 0.9.14 to tested libvncserver builds (PR 8337) + +### General Improvements and Cleanups +* Cleanups for STM32 AES GCM (PR 8584) +* Improvements to isascii() and the CMake key log option (PR 8596) +* Arduino documentation updates, comments and spelling corrections (PR 8381, + 8384, 8514) +* Expanding builds with WOLFSSL_NO_REALLOC for use with --enable-opensslall and + --enable-all builds (PR 8369, 8371) ## Fixes -* Fix a memory issue when using the compatibility layer with - WOLFSSL_GENERAL_NAME and handling registered ID types. (PR 8155) -* Fix a build issue with signature fault hardening when using public key - callbacks (HAVE_PK_CALLBACKS). (PR 8287) -* Fix for handling heap hint pointer properly when managing multiple WOLFSSL_CTX - objects and free’ing one of them (PR 8180) -* Fix potential memory leak in error case with Aria. (PR 8268) -* Fix Set_Verify flag behaviour on Ada wrapper. (PR 8256) -* Fix a compilation error with the NO_WOLFSSL_DIR flag. (PR 8294) -* Resolve a corner case for Poly1305 assembly code on Aarch64. (PR 8275) -* Fix incorrect version setting in CSRs. (PR 8136) -* Correct debugging output for cryptodev. (PR 8202) -* Fix for benchmark application use with /dev/crypto GMAC auth error due to size - of AAD (PR 8210) -* Add missing checks for the initialization of sp_int/mp_int with DSA to free - memory properly in error cases. (PR 8209) -* Fix return value of wolfSSL_CTX_set_tlsext_use_srtp (8252) -* Check Root CA by Renesas TSIP before adding it to ca-table (PR 8101) -* Prevent adding a certificate to the CA cache for Renesas builds if it does not - set CA:TRUE in basic constraints. (PR 8060) -* Fix attribute certificate holder entityName parsing. (PR 8166) -* Resolve build issues for configurations without any wolfSSL/openssl - compatibility layer headers. (PR 8182) -* Fix for building SP RSA small and RSA public only (PR 8235) -* Fix for Renesas RX TSIP RSA Sign/Verify with wolfCrypt only (PR 8206) -* Fix to ensure all files have settings.h included (like wc_lms.c) and guards - for building all `*.c` files (PR 8257 and PR 8140) -* Fix x86 target build issues in Visual Studio for non-Windows operating - systems. (PR 8098) -* Fix wolfSSL_X509_STORE_get0_objects to handle no CA (PR 8226) -* Properly handle reference counting when adding to the X509 store. (PR 8233) -* Fix for various typos and improper size used with FreeRTOS_bind in the Renesas - example. Thanks to Hongbo for the report on example issues. (PR 7537) -* Fix for potential heap use after free with wolfSSL_PEM_read_bio_PrivateKey. - Thanks to Peter for the issue reported. (PR 8139) +* Fix a use after free caused by an early free on error in the X509 store + (PR 8449) +* Fix to account for existing PKCS8 header with + wolfSSL_PEM_write_PKCS8PrivateKey (PR 8612) +* Fixed failing CMake build issue when standard threads support is not found in + the system (PR 8485) +* Fix segmentation fault in SHA-512 implementation for AVX512 targets built with + gcc -march=native -O2 (PR 8329) +* Fix Windows socket API compatibility warning with mingw32 build (PR 8424) +* Fix potential null pointer increments in cipher list parsing (PR 8420) +* Fix for possible stack buffer overflow read with wolfSSL_SMIME_write_PKCS7. + Thanks to the team at Code Intelligence for the report. (PR 8466) +* Fix AES ECB implementation for Aarch64 ARM assembly (PR 8379) +* Fixed building with VS2008 and .NET 3.5 (PR 8621) +* Fixed possible error case memory leaks in CRL and EVP_Sign_Final (PR 8447) +* Fixed SSL_set_mtu compatibility function return code (PR 8330) +* Fixed Renesas RX TSIP (PR 8595) +* Fixed ECC non-blocking tests (PR 8533) +* Fixed CMake on MINGW and MSYS (PR 8377) +* Fixed Watcom compiler and added new CI test (PR 8391) +* Fixed STM32 PKA ECC 521-bit support (PR 8450) +* Fixed STM32 PKA with P521 and shared secret (PR 8601) +* Fixed crypto callback macro guards with `DEBUG_CRYPTOCB` (PR 8602) +* Fix outlen return for RSA private decrypt with WOLF_CRYPTO_CB_RSA_PAD + (PR 8575) +* Additional sanity check on r and s lengths in DecodeECC_DSA_Sig_Bin (PR 8350) +* Fix compat. layer ASN1_TIME_diff to accept NULL output params (PR 8407) +* Fix CMake lean_tls build (PR 8460) +* Fix for QUIC callback failure (PR 8475) +* Fix missing alert types in AlertTypeToString for print out with debugging + enabled (PR 8572) +* Fixes for MSVS build issues with PQC configure (PR 8568) +* Fix for SE050 port and minor improvements (PR 8431, 8437) +* Fix for missing rewind function in zephyr and add missing files for compiling + with assembly optimizations (PR 8531, 8541) +* Fix for quic_record_append to return the correct code (PR 8340, 8358) +* Fixes for Bind 9.18.28 port (PR 8331) +* Fix to adhere more closely with RFC8446 Appendix D and set haveEMS when + negotiating TLS 1.3 (PR 8487) +* Fix to properly check for signature_algorithms from the client in a TLS 1.3 + server (PR 8356) +* Fix for when BIO data is less than seq buffer size. Thanks to the team at Code + Intelligence for the report (PR 8426) +* ARM32/Thumb2 fixes for WOLFSSL_NO_VAR_ASSIGN_REG and td4 variable declarations + (PR 8590, 8635) +* Fix for Intel AVX1/SSE2 assembly to not use vzeroupper instructions unless ymm + or zmm registers are used (PR 8479) +* Entropy MemUse fix for when block size less than update bits (PR 8675) For additional vulnerability information visit the vulnerability page at: diff --git a/README.md b/README.md index b75d0d5..7c0fd06 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.7.6 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.8.0 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -63,7 +63,7 @@ OpenSSL. wolfSSL is powered by the wolfCrypt cryptography library. Two versions of wolfCrypt have been FIPS 140-2 validated (Certificate #2425 and -certificate #3389). FIPS 140-3 validation is in progress. For additional +certificate #3389). FIPS 140-3 validated (Certificate #4718). For additional information, visit the [wolfCrypt FIPS FAQ](https://www.wolfssl.com/license/fips/) or contact fips@wolfssl.com. @@ -124,131 +124,214 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.7.6 (Dec 31, 2024) +# wolfSSL Release 5.8.0 (Apr 24, 2025) -Release 5.7.6 has been developed according to wolfSSL's development and QA +Release 5.8.0 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: - * --enable-heapmath is deprecated. - * In this release, the default cipher suite preference is updated to prioritize - TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256 when enabled. - * This release adds a sanity check for including wolfssl/options.h or - user_settings.h. - +NOTE: * --enable-heapmath is deprecated PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. -## Vulnerabilities -* [Med] An OCSP (non stapling) issue was introduced in wolfSSL version 5.7.4 - when performing OCSP requests for intermediate certificates in a certificate - chain. This affects only TLS 1.3 connections on the server side. It would not - impact other TLS protocol versions or connections that are not using the - traditional OCSP implementation. (Fix in pull request 8115) - - ## New Feature Additions -* Add support for RP2350 and improve RP2040 support, both with RNG optimizations - (PR 8153) -* Add support for STM32MP135F, including STM32CubeIDE support and HAL support - for SHA2/SHA3/AES/RNG/ECC optimizations. (PR 8223, 8231, 8241) -* Implement Renesas TSIP RSA Public Enc/Private support (PR 8122) -* Add support for Fedora/RedHat system-wide crypto-policies (PR 8205) -* Curve25519 generic keyparsing API added with wc_Curve25519KeyToDer and - wc_Curve25519KeyDecode (PR 8129) -* CRL improvements and update callback, added the functions - wolfSSL_CertManagerGetCRLInfo and wolfSSL_CertManagerSetCRLUpdate_Cb (PR 8006) -* For DTLS, add server-side stateless and CID quality-of-life API. (PR 8224) +* Algorithm registration in the Linux kernel module for all supported FIPS AES, + SHA, HMAC, ECDSA, ECDH, and RSA modes, key sizes, and digest sizes. +* Implemented various fixes to support building for Open Watcom including OS/2 + support and Open Watcom 1.9 compatibility (PR 8505, 8484) +* Added support for STM32H7S (tested on NUCLEO-H7S3L8) (PR 8488) +* Added support for STM32WBA (PR 8550) +* Added Extended Master Secret Generation Callback to the --enable-pkcallbacks + build (PR 8303) +* Implement AES-CTS (configure flag --enable-aescts) in wolfCrypt (PR 8594) +* Added support for libimobiledevice commit 860ffb (PR 8373) +* Initial ASCON hash256 and AEAD128 support based on NIST SP 800-232 IPD + (PR 8307) +* Added blinding option when using a Curve25519 private key by defining the + macro WOLFSSL_CURVE25519_BLINDING (PR 8392) + + +## Linux Kernel Module +* Production-ready LKCAPI registration for cbc(aes), cfb(aes), gcm(aes), + rfc4106 (gcm(aes)), ctr(aes), ofb(aes), and ecb(aes), ECDSA with P192, P256, + P384, and P521 curves, ECDH with P192, P256, and P384 curves, and RSA with + bare and PKCS1 padding +* Various fixes for LKCAPI wrapper for AES-CBC and AES-CFB (PR 8534, 8552) +* Adds support for the legacy one-shot AES-GCM back end (PR 8614, 8567) for + compatibility with FIPS 140-3 Cert #4718. +* On kernel >=6.8, for CONFIG_FORTIFY_SOURCE, use 5-arg fortify_panic() override + macro (PR 8654) +* Update calls to scatterwalk_map() and scatterwalk_unmap() for linux commit + 7450ebd29c (merged for Linux 6.15) (PR 8667) +* Inhibit LINUXKM_LKCAPI_REGISTER_ECDH on kernel <5.13 (PR 8673) +* Fix for uninitialized build error with fedora (PR 8569) +* Register ecdsa, ecdh, and rsa for use with linux kernel crypto (PR 8637, 8663, + 8646) +* Added force zero shared secret buffer, and clear of old key with ecdh + (PR 8685) +* Update fips-check.sh script to pickup XTS streaming support on aarch64 and + disable XTS-384 as an allowed use in FIPS mode (PR 8509, 8546) ## Enhancements and Optimizations -* Add a CMake dependency check for pthreads when required. (PR 8162) -* Update OS_Seed declarations for legacy compilers and FIPS modules (boundary - not affected). (PR 8170) -* Enable WOLFSSL_ALWAYS_KEEP_SNI by default when using --enable-jni. (PR 8283) -* Change the default cipher suite preference, prioritizing - TLS_AES_256_GCM_SHA384 over TLS_AES_128_GCM_SHA256. (PR 7771) -* Add SRTP-KDF (FIPS module v6.0.0) to checkout script for release bundling - (PR 8215) -* Make library build when no hardware crypto available for Aarch64 (PR 8293) -* Update assembly code to avoid `uint*_t` types for better compatibility with - older C standards. (PR 8133) -* Add initial documentation for writing ASN template code to decode BER/DER. - (PR 8120) -* Perform full reduction in sc_muladd for EdDSA with Curve448 (PR 8276) -* Allow SHA-3 hardware cryptography instructions to be explicitly not used in - MacOS builds (PR 8282) -* Make Kyber and ML-KEM available individually and together. (PR 8143) -* Update configuration options to include Kyber/ML-KEM and fix defines used in - wolfSSL_get_curve_name. (PR 8183) -* Make GetShortInt available with WOLFSSL_ASN_EXTRA (PR 8149) -* Improved test coverage and minor improvements of X509 (PR 8176) -* Add sanity checks for configuration methods, ensuring the inclusion of - wolfssl/options.h or user_settings.h. (PR 8262) -* Enable support for building without TLS (NO_TLS). Provides reduced code size - option for non-TLS users who want features like the certificate manager or - compatibility layer. (PR 8273) -* Exposed get_verify functions with OPENSSL_EXTRA. (PR 8258) -* ML-DSA/Dilithium: obtain security level from DER when decoding (PR 8177) -* Implementation for using PKCS11 to retrieve certificate for SSL CTX (PR 8267) -* Add support for the RFC822 Mailbox attribute (PR 8280) -* Initialize variables and adjust types resolve warnings with Visual Studio in - Windows builds. (PR 8181) -* Refactors and expansion of opensslcoexist build (PR 8132, 8216, 8230) -* Add DTLS 1.3 interoperability, libspdm and DTLS CID interoperability tests - (PR 8261, 8255, 8245) -* Remove trailing error exit code in wolfSSL install setup script (PR 8189) -* Update Arduino files for wolfssl 5.7.4 (PR 8219) -* Improve Espressif SHA HW/SW mutex messages (PR 8225) -* Apply post-5.7.4 release updates for Espressif Managed Component examples - (PR 8251) -* Expansion of c89 conformance (PR 8164) -* Added configure option for additional sanity checks with --enable-faultharden - (PR 8289) -* Aarch64 ASM additions to check CPU features before hardware crypto instruction - use (PR 8314) +### Security & Cryptography +* Add constant-time implementation improvements for encoding functions. We thank + Zhiyuan and Gilles for sharing a new constant-time analysis tool (CT-LLVM) and + reporting several non-constant-time implementations. (PR 8396, 8617) +* Additional support for PKCS7 verify and decode with indefinite lengths + (PR 8520, 834, 8645) +* Add more PQC hybrid key exchange algorithms such as support for combinations + with X25519 and X448 enabling compatibility with the PQC key exchange support + in Chromium browsers and Mozilla Firefox (PR 7821) +* Add short-circuit comparisons to DH key validation for RFC 7919 parameters + (PR 8335) +* Improve FIPS compatibility with various build configurations for more resource + constrained builds (PR 8370) +* Added option to disable ECC public key order checking (PR 8581) +* Allow critical alt and basic constraints extensions (PR 8542) +* New codepoint for MLDSA to help with interoperability (PR 8393) +* Add support for parsing trusted PEM certs having the header + “BEGIN_TRUSTED_CERT” (PR 8400) +* Add support for parsing only of DoD certificate policy and Comodo Ltd PKI OIDs + (PR 8599, 8686) +* Update ssl code in `src/*.c` to be consistent with wolfcrypt/src/asn.c + handling of ML_DSA vs Dilithium and add dual alg. test (PR 8360, 8425) + +### Build System, Configuration, CI & Protocols +* Internal refactor for include of config.h and when building with + BUILDING_WOLFSSL macro. This refactor will give a warning of “deprecated + function” when trying to improperly use an internal API of wolfSSL in an + external application. (PR 8640, 8647, 8660, 8662, 8664) +* Add WOLFSSL_CLU option to CMakeLists.txt (PR 8548) +* Add CMake and Zephyr support for XMSS and LMS (PR 8494) +* Added GitHub CI for CMake builds (PR 8439) +* Added necessary macros when building wolfTPM Zephyr with wolfSSL (PR 8382) +* Add MSYS2 build continuous integration test (PR 8504) +* Update DevKitPro doc to list calico dependency with build commands (PR 8607) +* Conversion compiler warning fixes and additional continuous integration test + added (PR 8538) +* Enable DTLS 1.3 by default in --enable-jni builds (PR 8481) +* Enabled TLS 1.3 middlebox compatibility by default for --enable-jni builds + (PR 8526) + +### Performance Improvements +* Performance improvements AES-GCM and HMAC (in/out hash copy) (PR 8429) +* LMS fixes and improvements adding API to get Key ID from raw private key, + change to identifiers to match standard, and fix for when + WOLFSSL_LMS_MAX_LEVELS is 1 (PR 8390, 8684, 8613, 8623) +* ML-KEM/Kyber improvements and fixes; no malloc builds, small memory usage, + performance improvement, fix for big-endian (PR 8397, 8412, 8436, 8467, 8619, + 8622, 8588) +* Performance improvements for AES-GCM and when doing multiple HMAC operations + (PR 8445) + +### Assembly and Platform-Specific Enhancements +* Poly1305 arm assembly changes adding ARM32 NEON implementation and fix for + Aarch64 use (PR 8344, 8561, 8671) +* Aarch64 assembly enhancement to use more CPU features, fix for FreeBSD/OpenBSD + (PR 8325, 8348) +* Only perform ARM assembly CPUID checks if support was enabled at build time + (PR 8566) +* Optimizations for ARM32 assembly instructions on platforms less than ARMv7 + (PR 8395) +* Improve MSVC feature detection for static assert macros (PR 8440) +* Improve Espressif make and CMake for ESP8266 and ESP32 series (PR 8402) +* Espressif updates for Kconfig, ESP32P4 and adding a sample user_settings.h + (PR 8422, PR 8641) + +### OpenSSL Compatibility Layer +* Modification to the push/pop to/from in OpenSSL compatibility layer. This is + a pretty major API change in the OpenSSL compatibility stack functions. + Previously the API would push/pop from the beginning of the list but now they + operate on the tail of the list. This matters when using the sk_value with + index values. (PR 8616) +* OpenSSL Compat Layer: OCSP response improvements (PR 8408, 8498) +* Expand the OpenSSL compatibility layer to include an implementation of + BN_CTX_get (PR 8388) + +### API Additions and Modifications +* Refactor Hpke to allow multiple uses of a context instead of just one shot + mode (PR 6805) +* Add support for PSK client callback with Ada and use with Alire (thanks + @mgrojo, PR 8332, 8606) +* Change wolfSSL_CTX_GenerateEchConfig to generate multiple configs and add + functions wolfSSL_CTX_SetEchConfigs and wolfSSL_CTX_SetEchConfigsBase64 to + rotate the server's echConfigs (PR 8556) +* Added the public API wc_PkcsPad to do PKCS padding (PR 8502) +* Add NULL_CIPHER_TYPE support to wolfSSL_EVP_CipherUpdate (PR 8518) +* Update Kyber APIs to ML-KEM APIs (PR 8536) +* Add option to disallow automatic use of "default" devId using the macro + WC_NO_DEFAULT_DEVID (PR 8555) +* Detect unknown key format on ProcessBufferTryDecode() and handle RSA-PSSk + format (PR 8630) + +### Porting and Language Support +* Update Python port to support version 3.12.6 (PR 8345) +* New additions for MAXQ with wolfPKCS11 (PR 8343) +* Port to ntp 4.2.8p17 additions (PR 8324) +* Add version 0.9.14 to tested libvncserver builds (PR 8337) + +### General Improvements and Cleanups +* Cleanups for STM32 AES GCM (PR 8584) +* Improvements to isascii() and the CMake key log option (PR 8596) +* Arduino documentation updates, comments and spelling corrections (PR 8381, + 8384, 8514) +* Expanding builds with WOLFSSL_NO_REALLOC for use with --enable-opensslall and + --enable-all builds (PR 8369, 8371) -## Fixes -* Fix a memory issue when using the compatibility layer with - WOLFSSL_GENERAL_NAME and handling registered ID types. (PR 8155) -* Fix a build issue with signature fault hardening when using public key - callbacks (HAVE_PK_CALLBACKS). (PR 8287) -* Fix for handling heap hint pointer properly when managing multiple WOLFSSL_CTX - objects and free’ing one of them (PR 8180) -* Fix potential memory leak in error case with Aria. (PR 8268) -* Fix Set_Verify flag behaviour on Ada wrapper. (PR 8256) -* Fix a compilation error with the NO_WOLFSSL_DIR flag. (PR 8294) -* Resolve a corner case for Poly1305 assembly code on Aarch64. (PR 8275) -* Fix incorrect version setting in CSRs. (PR 8136) -* Correct debugging output for cryptodev. (PR 8202) -* Fix for benchmark application use with /dev/crypto GMAC auth error due to size - of AAD (PR 8210) -* Add missing checks for the initialization of sp_int/mp_int with DSA to free - memory properly in error cases. (PR 8209) -* Fix return value of wolfSSL_CTX_set_tlsext_use_srtp (8252) -* Check Root CA by Renesas TSIP before adding it to ca-table (PR 8101) -* Prevent adding a certificate to the CA cache for Renesas builds if it does not - set CA:TRUE in basic constraints. (PR 8060) -* Fix attribute certificate holder entityName parsing. (PR 8166) -* Resolve build issues for configurations without any wolfSSL/openssl - compatibility layer headers. (PR 8182) -* Fix for building SP RSA small and RSA public only (PR 8235) -* Fix for Renesas RX TSIP RSA Sign/Verify with wolfCrypt only (PR 8206) -* Fix to ensure all files have settings.h included (like wc_lms.c) and guards - for building all `*.c` files (PR 8257 and PR 8140) -* Fix x86 target build issues in Visual Studio for non-Windows operating - systems. (PR 8098) -* Fix wolfSSL_X509_STORE_get0_objects to handle no CA (PR 8226) -* Properly handle reference counting when adding to the X509 store. (PR 8233) -* Fix for various typos and improper size used with FreeRTOS_bind in the Renesas - example. Thanks to Hongbo for the report on example issues. (PR 7537) -* Fix for potential heap use after free with wolfSSL_PEM_read_bio_PrivateKey. - Thanks to Peter for the issue reported. (PR 8139) +## Fixes +* Fix a use after free caused by an early free on error in the X509 store + (PR 8449) +* Fix to account for existing PKCS8 header with + wolfSSL_PEM_write_PKCS8PrivateKey (PR 8612) +* Fixed failing CMake build issue when standard threads support is not found in + the system (PR 8485) +* Fix segmentation fault in SHA-512 implementation for AVX512 targets built with + gcc -march=native -O2 (PR 8329) +* Fix Windows socket API compatibility warning with mingw32 build (PR 8424) +* Fix potential null pointer increments in cipher list parsing (PR 8420) +* Fix for possible stack buffer overflow read with wolfSSL_SMIME_write_PKCS7. + Thanks to the team at Code Intelligence for the report. (PR 8466) +* Fix AES ECB implementation for Aarch64 ARM assembly (PR 8379) +* Fixed building with VS2008 and .NET 3.5 (PR 8621) +* Fixed possible error case memory leaks in CRL and EVP_Sign_Final (PR 8447) +* Fixed SSL_set_mtu compatibility function return code (PR 8330) +* Fixed Renesas RX TSIP (PR 8595) +* Fixed ECC non-blocking tests (PR 8533) +* Fixed CMake on MINGW and MSYS (PR 8377) +* Fixed Watcom compiler and added new CI test (PR 8391) +* Fixed STM32 PKA ECC 521-bit support (PR 8450) +* Fixed STM32 PKA with P521 and shared secret (PR 8601) +* Fixed crypto callback macro guards with `DEBUG_CRYPTOCB` (PR 8602) +* Fix outlen return for RSA private decrypt with WOLF_CRYPTO_CB_RSA_PAD + (PR 8575) +* Additional sanity check on r and s lengths in DecodeECC_DSA_Sig_Bin (PR 8350) +* Fix compat. layer ASN1_TIME_diff to accept NULL output params (PR 8407) +* Fix CMake lean_tls build (PR 8460) +* Fix for QUIC callback failure (PR 8475) +* Fix missing alert types in AlertTypeToString for print out with debugging + enabled (PR 8572) +* Fixes for MSVS build issues with PQC configure (PR 8568) +* Fix for SE050 port and minor improvements (PR 8431, 8437) +* Fix for missing rewind function in zephyr and add missing files for compiling + with assembly optimizations (PR 8531, 8541) +* Fix for quic_record_append to return the correct code (PR 8340, 8358) +* Fixes for Bind 9.18.28 port (PR 8331) +* Fix to adhere more closely with RFC8446 Appendix D and set haveEMS when + negotiating TLS 1.3 (PR 8487) +* Fix to properly check for signature_algorithms from the client in a TLS 1.3 + server (PR 8356) +* Fix for when BIO data is less than seq buffer size. Thanks to the team at Code + Intelligence for the report (PR 8426) +* ARM32/Thumb2 fixes for WOLFSSL_NO_VAR_ASSIGN_REG and td4 variable declarations + (PR 8590, 8635) +* Fix for Intel AVX1/SSE2 assembly to not use vzeroupper instructions unless ymm + or zmm registers are used (PR 8479) +* Entropy MemUse fix for when block size less than update bits (PR 8675) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/examples/template/README.md b/examples/template/README.md new file mode 100644 index 0000000..5ce0cbf --- /dev/null +++ b/examples/template/README.md @@ -0,0 +1,34 @@ +# Template Example + +Open the [template.ino](./template.ino) file in the Arduino IDE. + +Other IDE products are also supported, such as: + +- [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) +- [VisualGDB](https://visualgdb.com/tutorials/arduino/) +- [VisualMicro](https://www.visualmicro.com/) + +For examples on other platforms, see the [IDE directory](https://github.com/wolfssl/wolfssl/tree/master/IDE). +Additional examples can be found on [wolfSSL/wolfssl-examples](https://github.com/wolfSSL/wolfssl-examples/). + + +### Troubleshooting + +When encountering odd errors such as `undefined reference to ``_impure_ptr'`, such as this: + +```text +c:/users/gojimmypi/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: C:\Users\gojimmypi\AppData\Local\Temp\arduino\sketches\EAB8D79A02D1ECF107884802D893914E\libraries\wolfSSL\wolfcrypt\src\logging.c.o:(.literal.wolfssl_log+0x8): undefined reference to `_impure_ptr' +collect2.exe: error: ld returned 1 exit status + +exit status 1 + +Compilation error: exit status 1 +``` + +Try cleaning the Arduino cache directories. For Windows, that's typically in: + +```text +C:\Users\%USERNAME%\AppData\Local\Temp\arduino\sketches +``` + +Remove all other boards from other serial ports, leaving one the one being programmed. diff --git a/examples/template/template.ino b/examples/template/template.ino new file mode 100644 index 0000000..8998976 --- /dev/null +++ b/examples/template/template.ino @@ -0,0 +1,143 @@ +/* template.ino + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ + +/* This is Arduino reference sketch example 2 of 2: multiple file .ino */ +/* See also template.ino project example using a single file project. */ + +/* Do not insert attempts at appending wolfssl user_settings.h here. + * All wolfssl settings needed by wolfSSL must be in the user_settings.h */ +#include + +/* settings.h is included from Arduino `wolfssl.h`, but a good practice to + * include before any other wolfssl headers. As a reminder here: */ +#include + +/* Include a simple wolfSSL header to this example: */ +#include + +/* There's a wolfSSL_Arduino_Serial_Print() for logging messages in wolfssl. */ +#include + +/* Include files (.c, .cpp, .h) typically in the same directory as the sketch; + * The wolfssl_helper is an example of this: */ +#include "wolfssl_helper.h" + +/* Arduino library header files are typically not in an `include` directory; + * The wolfssl_library is an example of a library directory: */ +#include "wolfssl_library/wolfssl_library.h" +#include "wolfssl_library/src/wolfssl_library.cpp" /* Force compilation */ + +/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ +#define SERIAL_BAUD 115200 + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino setup() */ +/*****************************************************************************/ +/*****************************************************************************/ +void setup() { + Serial.begin(SERIAL_BAUD); + while (!Serial) { + /* wait for serial port to connect. Needed for native USB port only */ + delay(10); + } + /* See https://github.com/wolfSSL/wolfssl/blob/master/examples/configs/user_settings_arduino.h */ + /* Various historical versions have differing features enabled. */ +#ifdef WOLFSSL_USER_SETTINGS_ID + /* Print the release version at runtime for reference. */ + Serial.println(WOLFSSL_USER_SETTINGS_ID); +#else + /* Introduced after v5.7.6, or otherwise missing from user_settings.h */ + Serial.println("A WOLFSSL_USER_SETTINGS_ID not found."); +#endif + + Serial.println(F("wolfSSL setup complete!!")); + Serial.println(F("")); + Serial.println(F("")); +} + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino loop() */ +/*****************************************************************************/ +/*****************************************************************************/ +void loop() { + int ret; + Serial.println("\nLOOP!\n\n"); + + Serial.print("wolfSSL Version: "); + Serial.println(LIBWOLFSSL_VERSION_STRING); + + /* A project-level include. + * These files typically WILL be visible automatically in the Arduino IDE */ + ret = wolfssl_helper_sample(); + Serial.print("- wolfssl_helper_sample ret = "); + Serial.println(ret); + + /* A local library directory. + * These files typically WILL NOT be visible in the Arduino IDE */ + ret = wolfssl_library_sample(); + Serial.print("- wolfssl_library_sample ret = "); + Serial.println(ret); + + /* This next section demonstrates wolfSSL logging. Logging is toggled + * on or off for each Arduino loop() iteration. WOLFSSL_MSG() only + * prints messages when debugging is turned on. */ + + /* Internal wolfssl_log() uses wolfSSL_Arduino_Serial_Print() */ + Serial.println(""); + Serial.println("Example wolfSSL_Arduino_Serial_Print():"); + wolfSSL_Arduino_Serial_Print("Hello from wolfSSL_Arduino_Serial_Print"); + + /* WOLFSSL_MSG uses wolfssl_log() for conditional messages. */ + Serial.println("The next line is conditional depending on debug state:"); + WOLFSSL_MSG("Hello from wolfssl_log"); + Serial.println(""); + + ret = WOLFSSL_IS_DEBUG_ON(); + if (ret == 0) { + Serial.println(""); /* nothing would have printed in WOLFSSL_MSG */ + Serial.println("WOLFSSL_IS_DEBUG_ON is not set (debugging off)"); + + Serial.println("Calling wolfSSL_Debugging_ON()"); + wolfSSL_Debugging_ON(); + } + else { + Serial.println("WOLFSSL_IS_DEBUG_ON is set (debugging on)"); + + Serial.println("Calling wolfSSL_Debugging_OFF()"); + wolfSSL_Debugging_OFF(); + } + + delay(60000); +} diff --git a/examples/template/wolfssl_helper.c b/examples/template/wolfssl_helper.c new file mode 100644 index 0000000..f4eeb57 --- /dev/null +++ b/examples/template/wolfssl_helper.c @@ -0,0 +1,52 @@ +/* my_library.cpp + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* This is a sample include directory library using wolfSSL. + * + * Do not explicitly include wolfSSL user_settings.h here. + * + * Be sure to include these files in all libraries that reference + * wolfssl in this order: */ + +#include +/* settings.h is typically included in wolfssl.h, but here as a reminder: */ +#include +#include + +#include "wolfssl_helper.h" + +int wolfssl_helper_sample() +{ + /* We cannot use Serial.print in a "c" file */ + /* Serial.print("Hello world!"); */ + int ret; + printf("Hello wolfssl_helper_sample!\r\n"); + + printf("- Calling wolfSSL_Init()\r\n"); + ret = wolfSSL_Init(); + if (ret == WOLFSSL_SUCCESS) { + printf("- Success wolfssl_helper!\r\n"); + } + else { + printf("- Error initializing wolfSSL!\r\n"); + } + return ret; +} diff --git a/examples/template/wolfssl_helper.h b/examples/template/wolfssl_helper.h new file mode 100644 index 0000000..844f022 --- /dev/null +++ b/examples/template/wolfssl_helper.h @@ -0,0 +1,37 @@ +/* wolfssl_helper.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +#ifndef _WOLFSSL_HELPER_H_ +#define _WOLFSSL_HELPER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Sample source code is C, but Arduino is compiling with C++ */ +int wolfssl_helper_sample(); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/examples/template/wolfssl_library/src/wolfssl_library.cpp b/examples/template/wolfssl_library/src/wolfssl_library.cpp new file mode 100644 index 0000000..e4d9685 --- /dev/null +++ b/examples/template/wolfssl_library/src/wolfssl_library.cpp @@ -0,0 +1,42 @@ +/* wolfssl_library.cpp + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ +#include +#include +#include + +/* Arduino source is typically in a `src` directory, with header in parent: */ +#include "../wolfssl_library.h" + +int wolfssl_library_sample() +{ + int ret = 0; + Serial.println("\nHello wolfssl_library!"); + + printf("- Calling wolfSSL_Init()\r\n"); + ret = wolfSSL_Init(); + if (ret == WOLFSSL_SUCCESS) { + printf("- Success wolfssl_library!\r\n"); + } + else { + printf("- Error initializing wolfSSL!\r\n"); + } + return ret; +} diff --git a/examples/template/wolfssl_library/wolfssl_library.h b/examples/template/wolfssl_library/wolfssl_library.h new file mode 100644 index 0000000..98f5dfd --- /dev/null +++ b/examples/template/wolfssl_library/wolfssl_library.h @@ -0,0 +1,46 @@ +/* wolfssl_library.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +/* This is a sample include directory library using wolfSSL. + * + * Do not explicitly include wolfSSL user_settings.h here. + * + * Be sure to include these files in all libraries that reference + * wolfssl in this order: */ + +#include +#include "wolfssl.h" + + #ifndef _WOLFSSL_LIBRARY_H_ + #define _WOLFSSL_LIBRARY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +int wolfssl_library_sample(); + +#ifdef __cplusplus +} +#endif + +#endif /* _WOLFSSL_LIBRARY_H_ */ diff --git a/examples/wolfssl_AES_CTR/README.md b/examples/wolfssl_AES_CTR/README.md new file mode 100644 index 0000000..c9b26d6 --- /dev/null +++ b/examples/wolfssl_AES_CTR/README.md @@ -0,0 +1,34 @@ +# Arduino AES CTR Example + +Open the [wolfssl_AES_CTR.ino](./wolfssl_AES_CTR.ino) file in the Arduino IDE. + +Other IDE products are also supported, such as: + +- [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) +- [VisualGDB](https://visualgdb.com/tutorials/arduino/) +- [VisualMicro](https://www.visualmicro.com/) + +For examples on other platforms, see the [IDE directory](https://github.com/wolfssl/wolfssl/tree/master/IDE). +Additional examples can be found on [wolfSSL/wolfssl-examples](https://github.com/wolfSSL/wolfssl-examples/). + + +### Troubleshooting + +When encountering odd errors such as `undefined reference to ``_impure_ptr'`, such as this: + +```text +c:/users/gojimmypi/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: C:\Users\gojimmypi\AppData\Local\Temp\arduino\sketches\EAB8D79A02D1ECF107884802D893914E\libraries\wolfSSL\wolfcrypt\src\logging.c.o:(.literal.wolfssl_log+0x8): undefined reference to `_impure_ptr' +collect2.exe: error: ld returned 1 exit status + +exit status 1 + +Compilation error: exit status 1 +``` + +Try cleaning the Arduino cache directories. For Windows, that's typically in: + +```text +C:\Users\%USERNAME%\AppData\Local\Temp\arduino\sketches +``` + +Remove all other boards from other serial ports, leaving one the one being programmed. diff --git a/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino b/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino new file mode 100644 index 0000000..31ef797 --- /dev/null +++ b/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino @@ -0,0 +1,268 @@ +/* wolfssl_AES_CTR.ino + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* +The Advanced Encryption Standard (AES) is a specification for the encryption of electronic +data established by the U.S. National Institute of Standards and Technology (NIST) in 2001. + +AES Counter mode (AES-CTR) is a "Block Cipher Mode of Operation" that +turns a block cipher into a stream cipher, as explained here: +https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR) + +The wolfSSL AES algorithms in this sketch (e.g wc_AesCtrEncrypt) are just some of +many algorithms in the wolfSSL library. All are documented in the wolfSSL Manual at +https://www.wolfssl.com/documentation/manuals/wolfssl/group__AES.html + +This sketch example demonstrates AES-CTR usage by first encrypting the input +data producing the cipher, then decrypt the cipher to reveal the original data. + +Required user inputs +-------------------- +1) Encryption Key +2) Initialization Vector ("iv") +3) The input data to be encrypted + +Tested on +--------- +Arduino UNO R4 WiFi (Renesas ARM Cortex M4) +Sparkfun MicroMod WiFi Function Board (ESP32-WROOM-32E) +Wemos D1 R32 Development Board (ESP32-WROOM-32) +Teensy 4.1 (ARM Cortex M7) + +*/ + +#define WOLFSSL_AES_CTR_EXAMPLE +#include +#include + +#if defined(NO_AES) or !defined(WOLFSSL_AES_COUNTER) or !defined(WOLFSSL_AES_128) + /* edit user_settings.h in ~\Arduino\libraries\wolfssl\src + * e.g. for Windows: + * C:\Users\%USERNAME%\Documents\Arduino\libraries\wolfssl\src + */ + #error "Missing AES, WOLFSSL_AES_COUNTER or WOLFSSL_AES_128" +#endif + +/* macro to check for expected results */ +#define ExpectIntEQ(p1, p2) if (p1 == p2) { \ + Serial.println(F("OK")); \ + } \ + else { \ + Serial.println(F("FAIL")); \ + } + + +/* USER INPUTS: + * The Encryption Key (encKey) is confidential and must only be shared with + * the intended recipient of the data. Length must be 16, 24, 32 or larger + * multiples of AES_BLOCK_SIZE + * + * The initialization Vector (iv) is a nonce/counter (or 'salt') that is + * incremented between each encryption to ensures no two ciphers are identical, + * even if the input data is unchanged. Can be any length. + * + * The input data ("input") provides the bytes to be encrypted. + * Must be 16, 24, 32 bytes, or larger multiples of AES_BLOCK_SIZE + */ + +/* Choose one of these data sets, or provide your own. */ +/* Example data set 1 */ +byte encKey[] = {0x33,0x9a,0x28,0x9d,0x08,0x61,0xe8,0x34, + 0x16,0xe5,0x8d,0xb7,0x58,0x33,0xdc,0x0a}; /* 16 bytes */ +byte iv[] = {0x43,0x05, 0, 0, 0, 0, 0, 0, /* Padded to */ + 0, 0, 0, 0, 0, 0, 0, 0}; /* 16 bytes */ +byte input[] = {0x05,0x00,0x8c,0x0a,0x21,0x00,0x6a,0x00, + 0x5c,0x00,0xff,0xff,0xc1,0xfc,0x25,0xc4}; /* 16 bytes */ + +/* + * Example data set 2 +byte encKey[] = {0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, + 0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66, + 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, + 0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66}; // 32 bytes + +byte iv[] = "1234567890abcdef"; + +byte input[] = { // Now is the time for all w/o trailing 0 + 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74, + 0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x20, + 0x66,0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20}; // 24 bytes +*/ + +/* create aes objects for encryption & decryption */ +Aes aesEnc; +Aes aesDec; + +/* Print out the data as HEX bytes with breaks every 8 bytes */ +void reportData(byte * data, int sz) { + int i; + for (i = 0; i < sz; i++) { + if (data[i] < 0x10) { + Serial.print(F("0")); + } + Serial.print(data[i], HEX); + if (i < sz - 1) { + if (((i + 1) % 8) == 0) { + Serial.print(F(" | ")); + } + else { + Serial.print(F(" ")); + } + } + } + Serial.println(); +} + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino setup() */ +/*****************************************************************************/ +/*****************************************************************************/ +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 1000) ; /* wait for serial, up to 1 sec */ + + Serial.println(); + Serial.println(); + Serial.println(F("===== wolfSSL example: AES Counter mode =====")); + Serial.print(F("wolfSSL library version: ")); + Serial.println(LIBWOLFSSL_VERSION_STRING); + Serial.println(); +} + + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino loop() */ +/*****************************************************************************/ +/*****************************************************************************/ +void loop() { + memset(&aesEnc, 0, sizeof(Aes)); /* fill aesEnc with zeros */ + memset(&aesDec, 0, sizeof(Aes)); /* ditto aesDec */ + + /* --------------------------------------------------------------------- */ + /* Choose blkSize of be 16, 24, 32 or larger multiples of 8, based */ + /* on sizeof(input) data. Uncomment the relevant lines from following: */ + + Serial.print(F("data set 1 [")); + uint32_t blkSize = AES_BLOCK_SIZE * 1; /* 16 bytes (for data set 1) */ + + /* Serial.print(F("data set 2 - ")); */ + /* uint32_t blkSize = AES_BLOCK_SIZE * 1.5; // 24 bytes (for data set 2) */ + + /* Serial.print(F("my data set - ")); */ + /* uint32_t blkSize = AES_BLOCK_SIZE * n; // choose an appropriate n */ + + Serial.print(F("blkSize: ")); + Serial.print(blkSize); + Serial.println(F(" bytes]")); + Serial.println(); + /* ----------------------------------------------------------------------*/ + + byte cipher[blkSize]; /* for the encrypted data (or "cipher") */ + byte output[blkSize]; /* for the deciphered data */ + memset(cipher, 0, blkSize); /* fill with zeros */ + memset(output, 0, blkSize); /* fill with zeros */ + + /* initialize structures for encryption and decryption. */ + Serial.println(F("--- Encryption ...")); + Serial.print(F("init aes (enc) : ")); + + /* init aesEnc structure, with NULL heap hint, dev id not used. */ + ExpectIntEQ(wc_AesInit(&aesEnc, NULL, INVALID_DEVID), 0); + + /* set up the key + salt in the AES encryption structure. */ + Serial.print(F("load key (enc) : ")); + ExpectIntEQ(wc_AesSetKey(&aesEnc, encKey, blkSize, iv, AES_ENCRYPTION), 0); + + /* encrypt */ + Serial.print(F("encryption done: ")); + ExpectIntEQ(wc_AesCtrEncrypt(&aesEnc, cipher, + input, sizeof(input) / sizeof(byte) ), 0); + + Serial.println(); + Serial.println(F("--- Decryption ...")); + /* set up the key + salt in the AES decryption structure. */ + Serial.print(F("init aes (dec) : ")); + + /* init aesDec structure, with NULL heap hint, dev id not used. */ + ExpectIntEQ(wc_AesInit(&aesDec, NULL, INVALID_DEVID), 0); + + /* set up the key + salt in an AES decryption structure. */ + Serial.print(F("load key (dec) : ")); + ExpectIntEQ(wc_AesSetKey(&aesDec, encKey, blkSize, iv, AES_ENCRYPTION), 0); + + /* decrypt */ + Serial.print(F("decryption done: ")); + ExpectIntEQ(wc_AesCtrEncrypt(&aesDec, output, + cipher, sizeof(cipher) / sizeof(byte)), 0); + Serial.println(); + + /* Test for bad args */ + Serial.println(F("--- Check for bad arguments ...")); + Serial.print(F("Bad arguments 1: ")); + ExpectIntEQ(wc_AesCtrEncrypt(NULL, output, + cipher, sizeof(cipher) / sizeof(byte)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + Serial.print(F("Bad arguments 2: ")); + ExpectIntEQ(wc_AesCtrEncrypt(&aesDec, NULL, + cipher, sizeof(cipher) / sizeof(byte)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + Serial.print(F("Bad arguments 3: ")); + ExpectIntEQ(wc_AesCtrEncrypt(&aesDec, output, + NULL, sizeof(cipher) / sizeof(byte)), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + /* Display data and results. */ + Serial.println(); + Serial.println(F("--- Inputs ...")); + Serial.print(F("key : ")); reportData(encKey, sizeof(encKey)); + Serial.print(F("salt/iv : ")); reportData(iv, sizeof(iv)); + Serial.print(F("data in : ")); reportData(input, sizeof(input)); + + Serial.println(); + Serial.println(F("--- Outputs ...")); + Serial.print(F("cipher : ")); + reportData(cipher, sizeof(cipher)); + Serial.print(F("decipher: ")); + reportData(output, sizeof(output)); + Serial.println(); + + if (memcmp(input, output, sizeof(input)) == 0) { + Serial.println(F("** SUCCESS ** deciphered data matches input data.")); + } + else { + Serial.print(F("*** FAILED *** deciphered & input data DO NOT MATCH.")); + } + Serial.println(); + + /* Free up resources associated with the aes structures. */ + wc_AesFree(&aesEnc); + wc_AesFree(&aesDec); + + Serial.println(F("===== end =====")); + + while (1) { + /* nothing */ + } +} diff --git a/examples/wolfssl_client/README.md b/examples/wolfssl_client/README.md index caf83c5..3068931 100644 --- a/examples/wolfssl_client/README.md +++ b/examples/wolfssl_client/README.md @@ -2,6 +2,12 @@ Open the [wolfssl_client.ino](./wolfssl_client.ino) file in the Arduino IDE. +If using WiFi, be sure to set `ssid` and `password` values. + +May need "Ethernet by Various" library to be installed. Tested with v2.0.2 and v2.8.1. + +See the `#define WOLFSSL_TLS_SERVER_HOST` to set your own server address. + Other IDE products are also supported, such as: - [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) diff --git a/examples/wolfssl_client/wolfssl_client.ino b/examples/wolfssl_client/wolfssl_client.ino index d6ef702..8af1eaf 100644 --- a/examples/wolfssl_client/wolfssl_client.ino +++ b/examples/wolfssl_client/wolfssl_client.ino @@ -37,7 +37,7 @@ Tested with: */ /* If you have a private include, define it here, otherwise edit WiFi params */ -#define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" +/* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ /* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ #define REPEAT_CONNECTION 0 @@ -68,12 +68,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - static const char* ssid PROGMEM = MY_ARDUINO_WIFI_SSID; - static const char* password PROGMEM = MY_ARDUINO_WIFI_PASSWORD; + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - static const char* ssid PROGMEM = "your_SSID"; - static const char* password PROGMEM = "your_PASSWORD"; + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -166,9 +166,10 @@ Tested with: #elif defined(OTHER_BOARD) */ #else + /* assume all other boards using WiFi library. Edit as needed: */ + #include #define USING_WIFI WiFiClient client; - #endif /* Only for syntax highlighters to show interesting options enabled: */ diff --git a/examples/wolfssl_server/README.md b/examples/wolfssl_server/README.md index a707357..e961d71 100644 --- a/examples/wolfssl_server/README.md +++ b/examples/wolfssl_server/README.md @@ -2,6 +2,12 @@ Open the [wolfssl_server.ino](./wolfssl_server.ino) file in the Arduino IDE. +If using WiFi, be sure to set `ssid` and `password` values. + +May need "Ethernet by Various" library to be installed. Tested with v2.0.2 and v2.8.1. + +See the `#define WOLFSSL_TLS_SERVER_HOST` to set your own server address. + Other IDE products are also supported, such as: - [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) diff --git a/examples/wolfssl_server/wolfssl_server.ino b/examples/wolfssl_server/wolfssl_server.ino index c3820df..1b9d4ed 100644 --- a/examples/wolfssl_server/wolfssl_server.ino +++ b/examples/wolfssl_server/wolfssl_server.ino @@ -1,6 +1,6 @@ /* wolfssl_server.ino * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -37,7 +37,7 @@ Tested with: */ /* If you have a private include, define it here, otherwise edit WiFi params */ -#define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" +/* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ /* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ #define REPEAT_CONNECTION 1 @@ -68,12 +68,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - static const char* ssid PROGMEM = MY_ARDUINO_WIFI_SSID; - static const char* password PROGMEM = MY_ARDUINO_WIFI_PASSWORD; + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - static const char* ssid PROGMEM = "your_SSID"; - static const char* password PROGMEM = "your_PASSWORD"; + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -166,6 +166,8 @@ Tested with: #elif defined(OTHER_BOARD) */ #else + /* assume all other boards using WiFi library. Edit as needed: */ + #include #define USING_WIFI WiFiClient client; WiFiServer server(WOLFSSL_PORT); diff --git a/examples/wolfssl_version/wolfssl_version.ino b/examples/wolfssl_version/wolfssl_version.ino index a2f13fe..12be948 100644 --- a/examples/wolfssl_version/wolfssl_version.ino +++ b/examples/wolfssl_version/wolfssl_version.ino @@ -30,13 +30,21 @@ * The wolfSSL "settings.h" must be included in each source file using wolfSSL. * The wolfSSL "settings.h" must appear before any other wolfSSL include. */ + +/* This is Arduino sketch example 1 of 2: single file .ino compile. */ +/* See also template.ino project example using multiple files. */ + #include #include /* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ #define SERIAL_BAUD 115200 -/* Arduino setup */ +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino setup() */ +/*****************************************************************************/ +/*****************************************************************************/ void setup() { Serial.begin(SERIAL_BAUD); while (!Serial) { @@ -45,9 +53,20 @@ void setup() { Serial.println(F("")); Serial.println(F("")); Serial.println(F("wolfSSL setup complete!")); + + /* See https://github.com/wolfSSL/wolfssl/blob/master/examples/configs/user_settings_arduino.h */ + /* Various historical versions have differing features enabled. */ +#ifdef WOLFSSL_USER_SETTINGS_ID + /* Print the release version at runtime for reference. */ + Serial.println(WOLFSSL_USER_SETTINGS_ID); +#endif } -/* Arduino main application loop. */ +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino loop() */ +/*****************************************************************************/ +/*****************************************************************************/ void loop() { Serial.print("wolfSSL Version: "); Serial.println(LIBWOLFSSL_VERSION_STRING); diff --git a/library.properties b/library.properties index 1f9456b..16c905a 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.7.6 +version=5.8.0 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index b265456..0b52a6c 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include #if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ #define _GNU_SOURCE 1 @@ -142,7 +139,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } - XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, sz); + XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, (size_t)sz); bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { @@ -167,14 +164,14 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, - bio->wrSz - bio->rdIdx); + (long unsigned int)bio->wrSz - (size_t)bio->rdIdx); bio->wrSz -= bio->rdIdx; bio->rdIdx = 0; /* Resize down to WOLFSSL_BIO_RESIZE_THRESHOLD for fewer * allocations. */ if (wolfSSL_BUF_MEM_resize(bio->mem_buf, - bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? bio->wrSz : - WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { + bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? + (size_t)bio->wrSz : WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } @@ -389,6 +386,10 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = 0; + break; + } /* switch */ } @@ -564,7 +565,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("Error in wolfSSL_BIO_nwrite"); return sz1; } - XMEMCPY(buf, data, sz1); + XMEMCPY(buf, data, (size_t)sz1); data = (char*)data + sz1; len -= sz1; @@ -572,7 +573,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, /* try again to see if maybe we wrapped around the ring buffer */ sz2 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz2 > 0) { - XMEMCPY(buf, data, sz2); + XMEMCPY(buf, data, (size_t)sz2); sz1 += sz2; if (len > sz2) bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; @@ -610,8 +611,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, if (len == 0) return WOLFSSL_SUCCESS; /* Return early to make logic simpler */ - if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, bio->wrSz + len, 0) - == 0) { + if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, ((size_t)bio->wrSz) + + ((size_t)len), 0) == 0) { WOLFSSL_MSG("Error growing memory area"); return WOLFSSL_FAILURE; } @@ -621,7 +622,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, return WOLFSSL_FAILURE; } - XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); + XMEMCPY(bio->mem_buf->data + bio->wrSz, data, (size_t)len); bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->num.length = bio->mem_buf->max; bio->wrSz += len; @@ -813,6 +814,10 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = len; + break; + } /* switch */ } @@ -1138,7 +1143,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_BIO_nread(bio, &c, cSz); if (ret > 0 && ret < sz) { - XMEMCPY(buf, c, ret); + XMEMCPY(buf, c, (size_t)ret); } break; } @@ -1161,6 +1166,10 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) break; #endif /* WOLFCRYPT_ONLY */ + case WOLFSSL_BIO_NULL: + ret = 0; + break; + default: WOLFSSL_MSG("BIO type not supported yet with wolfSSL_BIO_gets"); } @@ -1256,13 +1265,13 @@ size_t wolfSSL_BIO_wpending(const WOLFSSL_BIO *bio) return 0; if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz; + return (size_t)bio->wrSz; } /* type BIO_BIO then check paired buffer */ if (bio->type == WOLFSSL_BIO_BIO && bio->pair != NULL) { WOLFSSL_BIO* pair = bio->pair; - return pair->wrIdx; + return (size_t)pair->wrIdx; } return 0; @@ -1308,12 +1317,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) #ifndef WOLFCRYPT_ONLY if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { - return (long)wolfSSL_pending(bio->ptr.ssl); + return (size_t)wolfSSL_pending(bio->ptr.ssl); } #endif if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz - bio->rdIdx; + return (size_t)(bio->wrSz - bio->rdIdx); } /* type BIO_BIO then check paired buffer */ @@ -1322,11 +1331,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) if (pair->wrIdx > 0 && pair->wrIdx <= pair->rdIdx) { /* in wrap around state where beginning of buffer is being * overwritten */ - return pair->wrSz - pair->rdIdx + pair->wrIdx; + return ((size_t)pair->wrSz) - ((size_t)pair->rdIdx) + + ((size_t)pair->wrIdx); } else { /* simple case where has not wrapped around */ - return pair->wrIdx - pair->rdIdx; + return (size_t)(pair->wrIdx - pair->rdIdx); } } return 0; @@ -1423,7 +1433,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + bio->ptr.mem_buf_data = (byte*)XMALLOC((size_t)size, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); @@ -1439,7 +1449,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num.length = size; + bio->num.length = (size_t)size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1908,7 +1918,7 @@ long wolfSSL_BIO_set_mem_eof_return(WOLFSSL_BIO *bio, int v) int wolfSSL_BIO_get_len(WOLFSSL_BIO *bio) { - int len; + int len = 0; #ifndef NO_FILESYSTEM long memSz = 0; XFILE file; @@ -2309,6 +2319,15 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return &meth; } + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_null(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_NULL); + + WOLFSSL_ENTER("wolfSSL_BIO_s_null"); + + return &meth; + } WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_socket(void) { @@ -2353,7 +2372,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); if (bio) { - bio->type = WOLFSSL_BIO_DGRAM; bio->shutdown = (byte)closeF; bio->num.fd = (SOCKET_T)fd; } @@ -2381,10 +2399,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else port = str + XSTRLEN(str); /* point to null terminator */ - bio->ip = (char*)XMALLOC((port - str) + 1, /* +1 for null char */ + bio->ip = (char*)XMALLOC( + (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ip != NULL) { - XMEMCPY(bio->ip, str, port - str); + XMEMCPY(bio->ip, str, (size_t)(port - str)); bio->ip[port - str] = '\0'; bio->type = WOLFSSL_BIO_SOCKET; } @@ -2770,9 +2789,23 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else { size_t currLen = XSTRLEN(b->ip); + #ifdef WOLFSSL_NO_REALLOC + char* tmp = NULL; + #endif + if (currLen != newLen) { + #ifdef WOLFSSL_NO_REALLOC + tmp = b->ip; + b->ip = (char*)XMALLOC(newLen+1, b->heap, DYNAMIC_TYPE_OPENSSL); + if (b->ip != NULL && tmp != NULL) { + XMEMCPY(b->ip, tmp, newLen); + XFREE(tmp, b->heap, DYNAMIC_TYPE_OPENSSL); + tmp = NULL; + } + #else b->ip = (char*)XREALLOC(b->ip, newLen + 1, b->heap, DYNAMIC_TYPE_OPENSSL); + #endif if (b->ip == NULL) { WOLFSSL_MSG("Hostname realloc failed."); return WOLFSSL_FAILURE; @@ -2926,7 +2959,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->wrSz = len; bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { - XMEMCPY(bio->ptr.mem_buf_data, buf, len); + XMEMCPY(bio->ptr.mem_buf_data, buf, (size_t)len); bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -3295,11 +3328,11 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) count = XVSNPRINTF(NULL, 0, format, args); if (count >= 0) { - pt = (char*)XMALLOC(count + 1, bio->heap, + pt = (char*)XMALLOC((size_t)count + 1, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); if (pt != NULL) { - count = XVSNPRINTF(pt, count + 1, format, copy); + count = XVSNPRINTF(pt, (size_t)count + 1, format, copy); if (count >= 0) { ret = wolfSSL_BIO_write(bio, pt, count); @@ -3369,18 +3402,20 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%02x ", (unsigned char)buf[i]); else - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), + " "); if (i == 7) - (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); + (void)XSNPRINTF(line + o + 2, (size_t)((int)sizeof(line) - + (o + 2)), "-"); o += 3; } - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/src/conf.c b/src/src/conf.c index b614148..a30be38 100644 --- a/src/src/conf.c +++ b/src/src/conf.c @@ -1,6 +1,6 @@ /* conf.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_CONF_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -773,8 +768,18 @@ static char* expandValue(WOLFSSL_CONF *conf, const char* section, /* This will allocate slightly more memory than necessary * but better be safe */ strLen += valueLen; + #ifdef WOLFSSL_NO_REALLOC + newRet = (char*)XMALLOC(strLen + 1, NULL, + DYNAMIC_TYPE_OPENSSL); + if (newRet != NULL && ret != NULL) { + XMEMCPY(newRet, ret, (strLen - valueLen) + 1); + XFREE(ret, NULL, DYNAMIC_TYPE_OPENSSL); + ret = NULL; + } + #else newRet = (char*)XREALLOC(ret, strLen + 1, NULL, DYNAMIC_TYPE_OPENSSL); + #endif if (!newRet) { WOLFSSL_MSG("realloc error"); goto expand_cleanup; @@ -979,8 +984,6 @@ void wolfSSL_NCONF_free(WOLFSSL_CONF *conf) void wolfSSL_X509V3_conf_free(WOLFSSL_CONF_VALUE *val) { - WOLF_STACK_OF(WOLFSSL_CONF_VALUE) *sk = NULL; - if (val) { if (val->name) { /* Not a section. Don't free section as it is a shared pointer. */ @@ -992,12 +995,7 @@ void wolfSSL_X509V3_conf_free(WOLFSSL_CONF_VALUE *val) XFREE(val->section, NULL, DYNAMIC_TYPE_OPENSSL); /* Only free the stack structures. The contained conf values * will be freed in wolfSSL_NCONF_free */ - sk = (WOLF_STACK_OF(WOLFSSL_CONF_VALUE)*)val->value; - while (sk) { - WOLF_STACK_OF(WOLFSSL_CONF_VALUE) *tmp = sk->next; - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); - sk = tmp; - } + wolfSSL_sk_free((WOLF_STACK_OF(WOLFSSL_CONF_VALUE)*)val->value); } XFREE(val, NULL, DYNAMIC_TYPE_OPENSSL); } @@ -1023,19 +1021,9 @@ WOLFSSL_STACK *wolfSSL_sk_CONF_VALUE_new( */ void wolfSSL_sk_CONF_VALUE_free(WOLF_STACK_OF(WOLFSSL_CONF_VALUE)* sk) { - WOLFSSL_STACK* tmp; WOLFSSL_ENTER("wolfSSL_sk_CONF_VALUE_free"); - if (sk == NULL) - return; - - /* parse through stack freeing each node */ - while (sk) { - tmp = sk->next; - wolfSSL_X509V3_conf_free(sk->data.conf); - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); - sk = tmp; - } + wolfSSL_sk_pop_free(sk, NULL); } int wolfSSL_sk_CONF_VALUE_num(const WOLFSSL_STACK *sk) diff --git a/src/src/crl.c b/src/src/crl.c index b78002c..437342c 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -1,6 +1,6 @@ /* crl.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,6 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* CRL Options: @@ -32,11 +33,6 @@ CRL Options: * Return any errors encountered during loading CRL * from a directory. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #ifndef WOLFCRYPT_ONLY #ifdef HAVE_CRL @@ -87,6 +83,13 @@ int InitCRL(WOLFSSL_CRL* crl, WOLFSSL_CERT_MANAGER* cm) WOLFSSL_MSG("Init Mutex failed"); return BAD_MUTEX_E; } +#ifdef OPENSSL_ALL + { + int ret; + wolfSSL_RefInit(&crl->ref, &ret); + (void)ret; + } +#endif return 0; } @@ -213,7 +216,7 @@ static void CRL_Entry_free(CRL_Entry* crle, void* heap) WOLFSSL_ENTER("FreeCRL_Entry"); - while (tmp) { + while (tmp != NULL) { next = tmp->next; XFREE(tmp, heap, DYNAMIC_TYPE_REVOKED); tmp = next; @@ -241,11 +244,24 @@ void FreeCRL(WOLFSSL_CRL* crl, int dynamic) { CRL_Entry* tmp; + WOLFSSL_ENTER("FreeCRL"); + if (crl == NULL) return; +#ifdef OPENSSL_ALL + { + int ret; + int doFree = 0; + wolfSSL_RefDec(&crl->ref, &doFree, &ret); + if (ret != 0) + WOLFSSL_MSG("Couldn't lock x509 mutex"); + if (!doFree) + return; + } +#endif + tmp = crl->crlList; - WOLFSSL_ENTER("FreeCRL"); #ifdef HAVE_CRL_MONITOR if (crl->monitors[0].path) XFREE(crl->monitors[0].path, crl->heap, DYNAMIC_TYPE_CRL_MONITOR); @@ -898,7 +914,7 @@ static RevokedCert *DupRevokedCertList(RevokedCert* in, void* heap) static CRL_Entry* DupCRL_Entry(const CRL_Entry* ent, void* heap) { CRL_Entry *dupl; - const size_t copyOffset = OFFSETOF(CRL_Entry, verifyMutex) + + const size_t copyOffset = WC_OFFSETOF(CRL_Entry, verifyMutex) + sizeof(ent->verifyMutex); #ifdef CRL_STATIC_REVOKED_LIST if (ent->totalCerts > CRL_MAX_REVOKED_CERTS) { @@ -916,9 +932,17 @@ static CRL_Entry* DupCRL_Entry(const CRL_Entry* ent, void* heap) #ifndef CRL_STATIC_REVOKED_LIST dupl->certs = DupRevokedCertList(ent->certs, heap); + if (ent->certs != NULL && dupl->certs == NULL) { + CRL_Entry_free(dupl, heap); + return NULL; + } #endif #ifdef OPENSSL_EXTRA dupl->issuer = wolfSSL_X509_NAME_dup(ent->issuer); + if (ent->issuer != NULL && dupl->issuer == NULL) { + CRL_Entry_free(dupl, heap); + return NULL; + } #endif if (!ent->verified) { @@ -1027,6 +1051,7 @@ static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl) if (dupl->monitors[0].path != NULL) { XFREE(dupl->monitors[0].path, dupl->heap, DYNAMIC_TYPE_CRL_MONITOR); + dupl->monitors[0].path = NULL; } return MEMORY_E; } @@ -1034,6 +1059,8 @@ static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl) #endif dupl->crlList = DupCRL_list(crl->crlList, dupl->heap); + if (dupl->crlList == NULL) + return MEMORY_E; #ifdef HAVE_CRL_IO dupl->crlIOCb = crl->crlIOCb; #endif @@ -1775,6 +1802,10 @@ int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor) ret = ProcessFile(NULL, name, type, CRL_TYPE, NULL, 0, crl, VERIFY); if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("CRL file load failed"); + wc_ReadDirClose(readCtx); + #ifdef WOLFSSL_SMALL_STACK + XFREE(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif return ret; } } diff --git a/src/src/dtls.c b/src/src/dtls.c index ae27804..2d3c38b 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -1,6 +1,6 @@ /* dtls.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,6 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include + /* * WOLFSSL_DTLS_NO_HVR_ON_RESUME * WOLFSSL_DTLS13_NO_HRR_ON_RESUME @@ -46,12 +48,6 @@ * to explicitly enable this during runtime. */ -#ifdef HAVE_CONFIG_H -#include -#endif - -#include - #ifndef WOLFCRYPT_ONLY #include @@ -365,7 +361,8 @@ static int FindExtByType(WolfSSL_ConstVector* ret, word16 extType, ato16(exts.elements + idx, &type); idx += OPAQUE16_LEN; idx += ReadVector16(exts.elements + idx, &ext); - if (idx > exts.size) + if (idx > exts.size || + ext.elements + ext.size > exts.elements + exts.size) return BUFFER_ERROR; if (type == extType) { XMEMCPY(ret, &ext, sizeof(ext)); @@ -498,7 +495,7 @@ static int TlsCheckSupportedVersion(const WOLFSSL* ssl, ch->extension, &tlsxFound); if (ret != 0) return ret; - if (!tlsxFound) { + if (!tlsxFound || tlsxSupportedVersions.elements == NULL) { *isTls13 = 0; return 0; } @@ -847,8 +844,6 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) WOLFSSL* nonConstSSL = (WOLFSSL*)ssl; TLSX* sslExts = nonConstSSL->extensions; - if (ret != 0) - goto dtls13_cleanup; nonConstSSL->options.tls = 1; nonConstSSL->options.tls1_1 = 1; nonConstSSL->options.tls1_3 = 1; @@ -1221,7 +1216,7 @@ int TLSX_ConnectionID_Use(WOLFSSL* ssl) info = (CIDInfo*)XMALLOC(sizeof(CIDInfo), ssl->heap, DYNAMIC_TYPE_TLSX); if (info == NULL) return MEMORY_ERROR; - ext = (WOLFSSL**)XMALLOC(sizeof(WOLFSSL**), ssl->heap, DYNAMIC_TYPE_TLSX); + ext = (WOLFSSL**)XMALLOC(sizeof(WOLFSSL*), ssl->heap, DYNAMIC_TYPE_TLSX); if (ext == NULL) { XFREE(info, ssl->heap, DYNAMIC_TYPE_TLSX); return MEMORY_ERROR; diff --git a/src/src/dtls13.c b/src/src/dtls13.c index 161ce4f..5a9b6dc 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -1,6 +1,6 @@ /* dtls13.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H -#include -#endif - -#include +#include #ifdef WOLFSSL_DTLS13 @@ -31,10 +27,7 @@ #include #include #include -#include #include -#include -#include #ifdef NO_INLINE #include @@ -185,7 +178,8 @@ int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out, /* seq[0] combines the epoch and 16 MSB of sequence number. We write on the epoch field and will overflow to the first two bytes of the sequence number */ - c32toa(seq[0], hdr->epoch); + c16toa((word16)(seq[0] >> 16), hdr->epoch); + c16toa((word16)seq[0], hdr->sequenceNumber); c32toa(seq[1], &hdr->sequenceNumber[2]); c16toa(length, hdr->length); @@ -724,7 +718,7 @@ static Dtls13RecordNumber* Dtls13NewRecordNumber(w64wrapper epoch, return rn; } -static int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq) +int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq) { Dtls13RecordNumber* rn; @@ -734,12 +728,28 @@ static int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq) if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0) #endif { + /* Find location to insert new record */ + Dtls13RecordNumber** prevNext = &ssl->dtls13Rtx.seenRecords; + Dtls13RecordNumber* cur = ssl->dtls13Rtx.seenRecords; + + for (; cur != NULL; prevNext = &cur->next, cur = cur->next) { + if (w64Equal(cur->epoch, epoch) && w64Equal(cur->seq, seq)) { + /* already in list. no duplicates. */ + return 0; + } + else if (w64LT(epoch, cur->epoch) + || (w64Equal(epoch, cur->epoch) + && w64LT(seq, cur->seq))) { + break; + } + } + rn = Dtls13NewRecordNumber(epoch, seq, ssl->heap); if (rn == NULL) return MEMORY_E; - rn->next = ssl->dtls13Rtx.seenRecords; - ssl->dtls13Rtx.seenRecords = rn; + *prevNext = rn; + rn->next = cur; #ifdef WOLFSSL_RW_THREADED wc_UnLockMutex(&ssl->dtls13Rtx.mutex); #endif @@ -1551,11 +1561,14 @@ static int Dtls13RtxSendBuffered(WOLFSSL* ssl) byte* output; int isLast; int sendSz; +#ifndef NO_ASN_TIME word32 now; +#endif int ret; WOLFSSL_ENTER("Dtls13RtxSendBuffered"); +#ifndef NO_ASN_TIME now = LowResTimer(); if (now - ssl->dtls13Rtx.lastRtx < DTLS13_MIN_RTX_INTERVAL) { #ifdef WOLFSSL_DEBUG_TLS @@ -1565,6 +1578,7 @@ static int Dtls13RtxSendBuffered(WOLFSSL* ssl) } ssl->dtls13Rtx.lastRtx = now; +#endif r = ssl->dtls13Rtx.rtxRecords; prevNext = &ssl->dtls13Rtx.rtxRecords; @@ -1639,6 +1653,102 @@ static int Dtls13AcceptFragmented(WOLFSSL *ssl, enum HandShakeType type) #endif return 0; } + +int Dtls13CheckEpoch(WOLFSSL* ssl, enum HandShakeType type) +{ + w64wrapper plainEpoch = w64From32(0x0, 0x0); + w64wrapper hsEpoch = w64From32(0x0, DTLS13_EPOCH_HANDSHAKE); + w64wrapper t0Epoch = w64From32(0x0, DTLS13_EPOCH_TRAFFIC0); + + if (IsAtLeastTLSv1_3(ssl->version)) { + switch (type) { + case client_hello: + case server_hello: + case hello_verify_request: + case hello_retry_request: + case hello_request: + if (!w64Equal(ssl->keys.curEpoch64, plainEpoch)) { + WOLFSSL_MSG("Msg should be epoch 0"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + break; + case encrypted_extensions: + case server_key_exchange: + case server_hello_done: + case client_key_exchange: + if (!w64Equal(ssl->keys.curEpoch64, hsEpoch)) { + if (ssl->options.side == WOLFSSL_CLIENT_END && + ssl->options.serverState < SERVER_HELLO_COMPLETE) { + /* before processing SH we don't know which version + * will be negotiated. */ + if (!w64Equal(ssl->keys.curEpoch64, plainEpoch)) { + WOLFSSL_MSG("Msg should be epoch 2 or 0"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + else { + WOLFSSL_MSG("Msg should be epoch 2"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + break; + case certificate_request: + case certificate: + case certificate_verify: + case finished: + if (!ssl->options.handShakeDone) { + if (!w64Equal(ssl->keys.curEpoch64, hsEpoch)) { + if (ssl->options.side == WOLFSSL_CLIENT_END && + ssl->options.serverState < SERVER_HELLO_COMPLETE) { + /* before processing SH we don't know which version + * will be negotiated. */ + if (!w64Equal(ssl->keys.curEpoch64, plainEpoch)) { + WOLFSSL_MSG("Msg should be epoch 2 or 0"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + else { + WOLFSSL_MSG("Msg should be epoch 2"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + } + else { + /* Allow epoch 2 in case of rtx */ + if (!w64GTE(ssl->keys.curEpoch64, hsEpoch)) { + WOLFSSL_MSG("Msg should be epoch 2+"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + break; + case certificate_status: + case change_cipher_hs: + case key_update: + case session_ticket: + if (!w64GTE(ssl->keys.curEpoch64, t0Epoch)) { + WOLFSSL_MSG("Msg should be epoch 3+"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + break; + case end_of_early_data: + case message_hash: + case no_shake: + default: + WOLFSSL_MSG("Unknown message type"); + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } + } + return 0; +} + /** * Dtls13HandshakeRecv() - process an handshake message. Deal with fragmentation if needed @@ -1674,6 +1784,12 @@ static int _Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32 size, return ret; } + ret = Dtls13CheckEpoch(ssl, (enum HandShakeType)handshakeType); + if (ret != 0) { + WOLFSSL_ERROR(ret); + return ret; + } + if (ssl->options.side == WOLFSSL_SERVER_END && ssl->options.acceptState < TLS13_ACCEPT_FIRST_REPLY_DONE) { if (handshakeType != client_hello) { @@ -1961,6 +2077,9 @@ int Dtls13DeriveSnKeys(WOLFSSL* ssl, int provision) end: ForceZero(key_dig, MAX_PRF_DIG); +#ifdef WOLFSSL_CHECK_MEM_ZERO + wc_MemZero_Check(key_dig, sizeof(key_dig)); +#endif return ret; } @@ -2419,7 +2538,7 @@ static int Dtls13GetAckListLength(Dtls13RecordNumber* list, word16* length) return 0; } -static int Dtls13WriteAckMessage(WOLFSSL* ssl, +int Dtls13WriteAckMessage(WOLFSSL* ssl, Dtls13RecordNumber* recordNumberList, word32* length) { word16 msgSz, headerLength; diff --git a/src/src/internal.c b/src/src/internal.c index 666de86..eb2f16d 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -1,6 +1,6 @@ /* internal.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include /* * WOLFSSL_SMALL_CERT_VERIFY: @@ -157,7 +153,7 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS #error Cannot use both secure-renegotiation and renegotiation-indication #endif -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) #ifndef NO_WOLFSSL_CLIENT static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, @@ -170,7 +166,7 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size); #endif -#endif +#endif /* !NO_WOLFSSL_CLIENT */ #ifndef NO_WOLFSSL_SERVER @@ -183,7 +179,7 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS #endif #endif /* !NO_WOLFSSL_SERVER */ -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ #if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET) #if defined(WOLFSSL_HAPROXY) @@ -202,7 +198,7 @@ WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS int enc, byte* ticket, int inLen, int* outLen, void* userCtx); #endif -#endif +#endif /* !NO_WOLFSSL_SERVER && HAVE_SESSION_TICKET */ int writeAeadAuthData(WOLFSSL* ssl, word16 sz, byte type, byte* additional, byte dec, byte** seq, int verifyOrder); @@ -240,13 +236,14 @@ enum processReply { }; -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT) /* Server random bytes for TLS v1.3 described downgrade protection mechanism. */ static const byte tls13Downgrade[7] = { 0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44 }; + #define TLS13_DOWNGRADE_SZ sizeof(tls13Downgrade) #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */ @@ -257,7 +254,7 @@ static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, #endif -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ #if !defined(NO_CERT) && defined(WOLFSSL_BLIND_PRIVATE_KEY) @@ -300,7 +297,7 @@ void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) xorbuf(key->buffer, mask->buffer, mask->length); } } -#endif +#endif /* !NO_CERT && WOLFSSL_BLIND_PRIVATE_KEY */ #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS) @@ -605,24 +602,24 @@ int IsAtLeastTLSv1_3(const ProtocolVersion pv) int IsEncryptionOn(const WOLFSSL* ssl, int isSend) { - #ifdef WOLFSSL_DTLS +#ifdef WOLFSSL_DTLS /* For DTLS, epoch 0 is always not encrypted. */ if (ssl->options.dtls && !isSend) { if (!IsAtLeastTLSv1_3(ssl->version) && ssl->keys.curEpoch == 0) return 0; -#ifdef WOLFSSL_DTLS13 + #ifdef WOLFSSL_DTLS13 else if (IsAtLeastTLSv1_3(ssl->version) && w64IsZero(ssl->keys.curEpoch64)) return 0; -#endif /* WOLFSSL_DTLS13 */ + #endif /* WOLFSSL_DTLS13 */ } - #endif /* WOLFSSL_DTLS */ - #ifdef WOLFSSL_QUIC +#endif /* WOLFSSL_DTLS */ +#ifdef WOLFSSL_QUIC if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) { return 0; } - #endif +#endif /* WOLFSSL_QUIC */ return ssl->keys.encryptionOn && (isSend ? ssl->encrypt.setup : ssl->decrypt.setup); } @@ -2262,7 +2259,8 @@ int InitSSL_Side(WOLFSSL* ssl, word16 side) return InitSSL_Suites(ssl); } -#endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */ +#endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE || + * WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #if defined(WOLFSSL_SYS_CRYPTO_POLICY) /* Check the wolfssl method meets minimum requirements for @@ -2812,7 +2810,7 @@ void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap) (void)heap; } -#endif +#endif /* WOLFSSL_TLS13 && HAVE_ECH */ /* In case contexts are held in array and don't want to free actual ctx. */ @@ -3023,7 +3021,16 @@ void FreeSSL_Ctx(WOLFSSL_CTX* ctx) if (isZero) { WOLFSSL_MSG("CTX ref count down to 0, doing full free"); - +#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && \ + !defined(NO_SHA256) && !defined(WC_NO_RNG) + if (ctx->srp != NULL) { + XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); + ctx->srp_password = NULL; + wc_SrpTerm(ctx->srp); + XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP); + ctx->srp = NULL; + } +#endif SSL_CtxResourceFree(ctx); #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) && \ !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_TLS) @@ -3469,7 +3476,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, (void) tls; tls1_2 = pv.minor <= DTLSv1_2_MINOR; } -#endif +#endif /* WOLFSSL_DTLS */ (void)tls; /* shut up compiler */ (void)tls1_2; @@ -3539,6 +3546,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = TLS_SM4_GCM_SM3; } #endif + #ifdef BUILD_TLS_SM4_CCM_SM3 if (tls1_3) { suites->suites[idx++] = CIPHER_BYTE; @@ -3769,7 +3777,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA; } #endif -#endif +#endif /* WOLFSSL_MYSQL_COMPATIBLE */ #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 #ifdef OPENSSL_EXTRA @@ -4006,7 +4014,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 */ #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4018,7 +4026,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 */ /* Place as higher priority for MYSQL testing */ #if !defined(WOLFSSL_MYSQL_COMPATIBLE) @@ -4028,7 +4036,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA; } #endif -#endif +#endif /* !WOLFSSL_MYSQL_COMPATIBLE */ #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA if (tls && haveDH && haveRSA && haveAES128 && haveSHA1) { @@ -4110,7 +4118,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CHACHA_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 */ #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA if (tls && haveECC && haveNull && haveSHA1) { @@ -4143,7 +4151,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA256; } -#endif +#endif /* BUILD_TLS_RSA_WITH_NULL_SHA256 */ #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA if (tls && havePSK && haveSHA1) { @@ -4162,7 +4170,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CBC_SHA384; } -#endif +#endif /* BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 */ #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4174,7 +4182,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA384; } -#endif +#endif /* BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384 */ #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4186,7 +4194,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 */ #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4231,7 +4239,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CHACHA_BYTE; suites->suites[idx++] = TLS_PSK_WITH_CHACHA20_POLY1305_SHA256; } -#endif +#endif /* BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 */ #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4243,7 +4251,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CHACHA_BYTE; suites->suites[idx++] = TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256; } -#endif +#endif /* BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 */ #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4255,7 +4263,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CHACHA_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 */ #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4267,7 +4275,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 */ #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4279,7 +4287,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = ECDHE_PSK_BYTE; suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256; } -#endif +#endif /* BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 */ #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM if (tls && havePSK && haveAES128) { @@ -4319,7 +4327,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA384; } -#endif +#endif /* BUILD_TLS_DHE_PSK_WITH_NULL_SHA384 */ #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4331,7 +4339,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA384; } -#endif +#endif /* BUILD_TLS_PSK_WITH_NULL_SHA384 */ #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4343,7 +4351,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = ECC_BYTE; suites->suites[idx++] = TLS_ECDHE_PSK_WITH_NULL_SHA256; } -#endif +#endif /* BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256 */ #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4355,7 +4363,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_PSK_WITH_NULL_SHA256 */ #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4367,7 +4375,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA256; } -#endif +#endif /* BUILD_TLS_PSK_WITH_NULL_SHA256 */ #ifdef BUILD_TLS_PSK_WITH_NULL_SHA if (tls && havePSK && haveNull) { @@ -4435,7 +4443,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 */ #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4447,7 +4455,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 */ #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4459,7 +4467,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 */ #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES @@ -4471,7 +4479,7 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = CIPHER_BYTE; suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256; } -#endif +#endif /* BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 */ #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 if (tls && haveECC) { @@ -4479,12 +4487,14 @@ void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA, suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3; } #endif + #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3 if (tls && haveECC) { suites->suites[idx++] = SM_BYTE; suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3; } #endif + #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3 if (tls && haveECC) { suites->suites[idx++] = SM_BYTE; @@ -4573,14 +4583,11 @@ void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType) } break; #endif -#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - case PQC_SA_MAJOR: - /* Hash performed as part of sign/verify operation. - * However, if we want a dual alg signature with a - * classic algorithm as alternative, we need an explicit - * hash algo here. - */ + /* Hash performed as part of sign/verify operation. + * However, if we want a dual alg signature with a classic algorithm as + * alternative, we need an explicit hash algo here. */ #ifdef HAVE_FALCON + case FALCON_SA_MAJOR: if (input[1] == FALCON_LEVEL1_SA_MINOR) { *hsType = falcon_level1_sa_algo; *hashAlgo = sha256_mac; @@ -4589,8 +4596,10 @@ void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType) *hsType = falcon_level5_sa_algo; *hashAlgo = sha512_mac; } + break; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + case DILITHIUM_SA_MAJOR: if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) { *hsType = dilithium_level2_sa_algo; *hashAlgo = sha256_mac; @@ -4603,16 +4612,16 @@ void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType) *hsType = dilithium_level5_sa_algo; *hashAlgo = sha512_mac; } - #endif /* HAVE_DILITHIUM */ break; -#endif + #endif /* HAVE_DILITHIUM */ default: *hashAlgo = input[0]; *hsType = input[1]; break; } } -#endif /* !NO_WOLFSSL_SERVER || !NO_CERTS */ +#endif /* !NO_WOLFSSL_SERVER || !NO_CERTS || + * ( !NO_WOLFSSL_CLIENT && (!NO_DH || HAVE_ECC) ) */ #ifndef WOLFSSL_NO_TLS12 #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT) @@ -4897,7 +4906,8 @@ static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) } #endif -#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_NO_CLIENT_AUTH) +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) && \ + !defined(WOLFSSL_NO_CLIENT_AUTH) static void SetDigest(WOLFSSL* ssl, int hashAlgo) { switch (hashAlgo) { @@ -4958,7 +4968,7 @@ word32 MacSize(const WOLFSSL* ssl) } #ifndef NO_RSA -#if !defined(WOLFSSL_NO_TLS12) || \ +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) || \ (defined(WC_RSA_PSS) && defined(HAVE_PK_CALLBACKS)) #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT) static int TypeHash(int hashAlgo) @@ -5784,7 +5794,7 @@ int Sm2wSm3Verify(WOLFSSL* ssl, const byte* id, word32 idSz, const byte* sig, return ret; } -#endif /* WOLFSSL_SM2 */ +#endif /* WOLFSSL_SM2 && WOLFSSL_SM3 */ #ifdef HAVE_ED25519 /* Check whether the key contains a public key. @@ -5971,7 +5981,7 @@ int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg, } #endif /* HAVE_ED25519 */ -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) #ifdef HAVE_CURVE25519 #ifdef HAVE_PK_CALLBACKS @@ -6045,8 +6055,14 @@ static int X25519SharedSecret(WOLFSSL* ssl, curve25519_key* priv_key, else #endif { - ret = wc_curve25519_shared_secret_ex(priv_key, pub_key, out, outlen, - EC25519_LITTLE_ENDIAN); + #ifdef WOLFSSL_CURVE25519_BLINDING + ret = wc_curve25519_set_rng(priv_key, ssl->rng); + if (ret == 0) + #endif + { + ret = wc_curve25519_shared_secret_ex(priv_key, pub_key, out, outlen, + EC25519_LITTLE_ENDIAN); + } } /* Handle async pending response */ @@ -6108,7 +6124,7 @@ static int X25519MakeKey(WOLFSSL* ssl, curve25519_key* key, } #endif /* HAVE_CURVE25519 */ -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ #ifdef HAVE_ED448 /* Check whether the key contains a public key. @@ -6905,8 +6921,8 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) * then we possibly already have a side defined. Don't overwrite unless * the context has a well defined role. */ if (newSSL || ctx->method->side != WOLFSSL_NEITHER_END) - ssl->options.side = ctx->method->side; - ssl->options.downgrade = ctx->method->downgrade; + ssl->options.side = (word16)(ctx->method->side); + ssl->options.downgrade = (word16)(ctx->method->downgrade); ssl->options.minDowngrade = ctx->minDowngrade; ssl->options.haveRSA = ctx->haveRSA; @@ -6918,7 +6934,7 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->options.haveDilithiumSig = ctx->haveDilithiumSig; #ifndef NO_PSK - ssl->options.havePSK = ctx->havePSK; + ssl->options.havePSK = (word16)(ctx->havePSK); ssl->options.client_psk_cb = ctx->client_psk_cb; ssl->options.server_psk_cb = ctx->server_psk_cb; ssl->options.psk_ctx = ctx->psk_ctx; @@ -7262,7 +7278,7 @@ void FreeHandshakeHashes(WOLFSSL* ssl) (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \ !defined(WOLFSSL_NO_CLIENT_AUTH) if (ssl->hsHashes->messages != NULL) { - ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length); + ForceZero(ssl->hsHashes->messages, (word32)ssl->hsHashes->length); XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES); ssl->hsHashes->messages = NULL; } @@ -7285,11 +7301,13 @@ int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, /* save the original so we can put it back afterward */ tmpHashes = ssl->hsHashes; - ssl->hsHashes = NULL; + ssl->hsHashes = *destination; ret = InitHandshakeHashes(ssl); if (ret != 0) { WOLFSSL_MSG_EX("InitHandshakeHashes failed. err = %d", ret); + ssl->hsHashes = tmpHashes; /* restore hsHashes pointer to original + * before returning */ return ret; } @@ -7330,8 +7348,9 @@ int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \ !defined(WOLFSSL_NO_CLIENT_AUTH) if (ret == 0 && source->messages != NULL) { - (*destination)->messages = (byte*)XMALLOC(source->length, ssl->heap, - DYNAMIC_TYPE_HASHES); + (*destination)->messages = (byte*)XMALLOC((size_t)source->length, + ssl->heap, + (int)DYNAMIC_TYPE_HASHES); (*destination)->length = source->length; (*destination)->prevLen = source->prevLen; @@ -7340,7 +7359,7 @@ int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source, } else { XMEMCPY((*destination)->messages, source->messages, - source->length); + (size_t)source->length); } } #endif @@ -7446,7 +7465,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) wc_MemZero_Add("ServerFinished hash", &ssl->serverFinished, TLS_FINISHED_SZ_MAX); #endif -#endif +#endif /* WOLFSSL_CHECK_MEM_ZERO */ #if defined(WOLFSSL_STATIC_MEMORY) if (ctx->heap != NULL) { @@ -7602,7 +7621,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) !defined(HAVE_SELFTEST) ssl->options.dhDoKeyTest = 1; #endif -#endif +#endif /* !NO_DH */ #ifdef WOLFSSL_DTLS #ifdef WOLFSSL_SCTP @@ -7646,7 +7665,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->IOCB_ReadCtx = &ssl->rfd; /* prevent invalid pointer access if not */ ssl->IOCB_WriteCtx = &ssl->wfd; /* correctly set */ #endif -#endif +#endif /* WOLFSSL_DTLS */ #ifndef WOLFSSL_AEAD_ONLY @@ -7660,7 +7679,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->hmac = Renesas_cmn_TLS_hmac; #endif #endif -#endif +#endif /* WOLFSSL_AEAD_ONLY */ #if defined(WOLFSSL_OPENVPN) && defined(HAVE_KEYING_MATERIAL) /* Save arrays by default for OpenVPN */ @@ -7701,7 +7720,7 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT ssl->options.tls13MiddleBoxCompat = 1; #endif -#endif +#endif /* WOLFSSL_TLS13 */ #ifdef HAVE_TLS_EXTENSIONS #ifdef HAVE_MAX_FRAGMENT @@ -7785,6 +7804,14 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) return MEMORY_E; } XMEMSET(ssl->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM)); + + /* pass on PARAM flags value from ctx to ssl */ + if (wolfSSL_X509_VERIFY_PARAM_set_flags(wolfSSL_get0_param(ssl), + (unsigned long)wolfSSL_X509_VERIFY_PARAM_get_flags( + wolfSSL_CTX_get0_param(ctx))) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ssl->param set flags error"); + return WOLFSSL_FAILURE; + } #endif if (ctx->suites == NULL) { @@ -8357,13 +8384,21 @@ void FreeKeyExchange(WOLFSSL* ssl) /* Free up all memory used by Suites structure from WOLFSSL */ void FreeSuites(WOLFSSL* ssl) { -#ifdef OPENSSL_ALL +#ifdef OPENSSL_EXTRA if (ssl->suitesStack != NULL) { /* Enough to free stack structure since WOLFSSL_CIPHER * isn't allocated separately. */ wolfSSL_sk_SSL_CIPHER_free(ssl->suitesStack); ssl->suitesStack = NULL; } + if (ssl->clSuitesStack != NULL) { + /* Enough to free stack structure since WOLFSSL_CIPHER + * isn't allocated separately. */ + wolfSSL_sk_SSL_CIPHER_free(ssl->clSuitesStack); + ssl->clSuitesStack = NULL; + } + XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); + ssl->clSuites = NULL; #endif XFREE(ssl->suites, ssl->heap, DYNAMIC_TYPE_SUITES); ssl->suites = NULL; @@ -8405,6 +8440,13 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl) } FreeSuites(ssl); FreeHandshakeHashes(ssl); +#ifdef HAVE_ECH + /* try to free the ech hashes in case we errored out */ + ssl->hsHashes = ssl->hsHashesEch; + FreeHandshakeHashes(ssl); + ssl->hsHashes = ssl->hsHashesEchInner; + FreeHandshakeHashes(ssl); +#endif XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN); /* clear keys struct after session */ @@ -8418,9 +8460,6 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl) if (ssl->options.useEch == 1) { FreeEchConfigs(ssl->echConfigs, ssl->heap); ssl->echConfigs = NULL; - /* free the ech specific hashes */ - ssl->hsHashes = ssl->hsHashesEch; - FreeHandshakeHashes(ssl); ssl->options.useEch = 0; } #endif /* HAVE_ECH */ @@ -8659,6 +8698,13 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl) #ifdef OPENSSL_EXTRA XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL); #endif +#if defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) + if (ssl->ocspResp) { + XFREE(ssl->ocspResp, NULL, 0); + ssl->ocspResp = NULL; + ssl->ocspRespSz = 0; + } +#endif /* defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) */ #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) while (ssl->certReqCtx != NULL) { CertReqCtx* curr = ssl->certReqCtx; @@ -8731,6 +8777,7 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl) * isn't allocated separately. */ wolfSSL_sk_CIPHER_free(ssl->supportedCiphers); wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL); + wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL); #ifdef KEEP_OUR_CERT wolfSSL_sk_X509_pop_free(ssl->ourCertChain, NULL); #endif @@ -8866,6 +8913,10 @@ void FreeHandshakeResources(WOLFSSL* ssl) FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; #endif /* HAVE_FALCON */ +#if defined(HAVE_DILITHIUM) + FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM, (void**)&ssl->peerDilithiumKey); + ssl->peerDilithiumKeyPresent = 0; +#endif /* HAVE_DILITHIUM */ } #ifdef HAVE_ECC @@ -8982,6 +9033,14 @@ void FreeHandshakeResources(WOLFSSL* ssl) * !WOLFSSL_POST_HANDSHAKE_AUTH */ #endif /* HAVE_TLS_EXTENSIONS && !NO_TLS */ +#if defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) + if (ssl->ocspResp != NULL) { + XFREE(ssl->ocspResp, NULL, 0); + ssl->ocspResp = NULL; + ssl->ocspRespSz = 0; + } +#endif /* defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) */ + #ifdef WOLFSSL_STATIC_MEMORY /* when done with handshake decrement current handshake count */ if (ssl->heap != NULL) { @@ -9424,7 +9483,7 @@ static void DtlsMsgAssembleCompleteMessage(DtlsMsg* msg) * alignment of char. */ dtls = (DtlsHandShakeHeader*)(void *)((char *)msg->fragBucketList - + OFFSETOF(DtlsFragBucket,buf) + + WC_OFFSETOF(DtlsFragBucket,buf) - DTLS_HANDSHAKE_HEADER_SZ); msg->fragBucketList = NULL; @@ -9843,7 +9902,7 @@ int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket) WriteSEQ(ssl, epochOrder, dtls->sequence_number); DtlsSEQIncrement(ssl, epochOrder); - if ((ret = CheckAvailableSize(ssl, pool->sz)) != 0) { + if ((ret = CheckAvailableSize(ssl, (int)pool->sz)) != 0) { WOLFSSL_ERROR(ret); return ret; } @@ -10316,10 +10375,10 @@ int HashRaw(WOLFSSL* ssl, const byte* data, int sz) #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \ defined(WOLFSSL_ALLOW_TLS_SHA1)) - wc_ShaUpdate(&ssl->hsHashes->hashSha, data, sz); + wc_ShaUpdate(&ssl->hsHashes->hashSha, data, (word32)(sz)); #endif #if !defined(NO_MD5) && !defined(NO_OLD_TLS) - wc_Md5Update(&ssl->hsHashes->hashMd5, data, sz); + wc_Md5Update(&ssl->hsHashes->hashMd5, data, (word32)(sz)); #endif if (IsAtLeastTLSv1_2(ssl)) { @@ -10639,7 +10698,7 @@ static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz, if (!ssl->options.buildingMsg) { /* Hash it before the loop as we modify the input with * encryption on */ - ret = HashRaw(ssl, input + rHdrSz, inputSz + hsHdrSz); + ret = HashRaw(ssl, input + rHdrSz, (int)(inputSz) + hsHdrSz); if (ret != 0) return ret; #ifdef WOLFSSL_DTLS @@ -10899,7 +10958,7 @@ void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree) if (!forcedFree && usedLength > 0) { XMEMCPY(ssl->buffers.inputBuffer.staticBuffer, ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx, - usedLength); + (size_t)(usedLength)); } ForceZero(ssl->buffers.inputBuffer.buffer, @@ -11207,7 +11266,7 @@ int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength) if (usedLength) XMEMCPY(tmp, ssl->buffers.inputBuffer.buffer + - ssl->buffers.inputBuffer.idx, usedLength); + ssl->buffers.inputBuffer.idx, (size_t)(usedLength)); if (ssl->buffers.inputBuffer.dynamicFlag) { if (IsEncryptionOn(ssl, 1)) { @@ -11888,7 +11947,7 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, (!ssl->options.dtls && rh->pvMinor < ssl->version.minor)) #else - rh->pvMinor < ssl->version.minor + (rh->pvMinor < ssl->version.minor) #endif )) { WOLFSSL_MSG("SSL version error"); @@ -13427,7 +13486,9 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) x509->isCa = dCert->isCA; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + x509->basicConstCrit = dCert->extBasicConstCrit; x509->pathLength = dCert->pathLength; + x509->pathLengthSet = dCert->pathLengthSet; x509->keyUsage = dCert->extKeyUsage; x509->CRLdistSet = dCert->extCRLdistSet; @@ -13481,7 +13542,6 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) } #endif x509->basicConstSet = dCert->extBasicConstSet; - x509->basicConstCrit = dCert->extBasicConstCrit; x509->basicConstPlSet = dCert->pathLengthSet; x509->subjAltNameSet = dCert->extSubjAltNameSet; x509->subjAltNameCrit = dCert->extSubjAltNameCrit; @@ -13594,6 +13654,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) if (x509->sapkiDer != NULL) { XMEMCPY(x509->sapkiDer, dCert->sapkiDer, dCert->sapkiLen); x509->sapkiLen = dCert->sapkiLen; + x509->sapkiCrit = dCert->extSapkiCrit; } else { ret = MEMORY_E; @@ -13606,6 +13667,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) XMEMCPY(x509->altSigAlgDer, dCert->altSigAlgDer, dCert->altSigAlgLen); x509->altSigAlgLen = dCert->altSigAlgLen; + x509->altSigAlgCrit = dCert->extAltSigAlgCrit; } else { ret = MEMORY_E; @@ -13618,6 +13680,7 @@ int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert) XMEMCPY(x509->altSigValDer, dCert->altSigValDer, dCert->altSigValLen); x509->altSigValLen = dCert->altSigValLen; + x509->altSigValCrit = dCert->extAltSigValCrit; } else { ret = MEMORY_E; @@ -13756,8 +13819,6 @@ static int ProcessCSR_ex(WOLFSSL* ssl, byte* input, word32* inOutIdx, #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) TLSX* ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST); CertificateStatusRequest* csr; -#else - (void)idx; #endif #ifdef WOLFSSL_SMALL_STACK CertStatus* status; @@ -13786,6 +13847,8 @@ static int ProcessCSR_ex(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->status_request = 0; break; } + #else + (void)idx; #endif #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2 @@ -13829,7 +13892,7 @@ static int ProcessCSR_ex(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* InitOcspResponse sets single and status to response struct. */ InitOcspResponse(response, single, status, input +*inOutIdx, status_length, ssl->heap); - if (OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, 0) != 0) + if (OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, 0, 0) != 0) ret = BAD_CERTIFICATE_STATUS_ERROR; else if (CompareOcspReqResp(request, response) != 0) ret = BAD_CERTIFICATE_STATUS_ERROR; @@ -14021,7 +14084,7 @@ int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, if (subjectCNLen > ASN_NAME_MAX-1) subjectCNLen = ASN_NAME_MAX-1; if (subjectCNLen > 0) { - XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen); + XMEMCPY(domain, args->dCert->subjectCN, (size_t)(subjectCNLen)); domain[subjectCNLen] = '\0'; } } @@ -14117,8 +14180,10 @@ int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt, if (store != NULL) wolfSSL_X509_STORE_CTX_free(store); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - if (x509 != NULL) + if (x509 != NULL) { wolfSSL_X509_free(x509); + x509 = NULL; + } #endif XFREE(domain, heap, DYNAMIC_TYPE_STRING); return MEMORY_E; @@ -14544,6 +14609,7 @@ int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type) if (x509 != NULL) { ret = wolfSSL_X509_STORE_add_cert(store, x509); wolfSSL_X509_free(x509); + x509 = NULL; } else { WOLFSSL_MSG("failed to load certificate"); ret = WOLFSSL_FAILURE; @@ -14889,6 +14955,7 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: if (ssl->options.minDilithiumKeySz < 0 || DILITHIUM_LEVEL2_KEY_SIZE @@ -14913,6 +14980,31 @@ static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args) ret = DILITHIUM_KEY_SIZE_E; } break; + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + case ML_DSA_LEVEL2k: + if (ssl->options.minDilithiumKeySz < 0 || + ML_DSA_LEVEL2_KEY_SIZE + < (word16)ssl->options.minDilithiumKeySz) { + WOLFSSL_MSG("Dilithium key size in cert chain error"); + ret = DILITHIUM_KEY_SIZE_E; + } + break; + case ML_DSA_LEVEL3k: + if (ssl->options.minDilithiumKeySz < 0 || + ML_DSA_LEVEL3_KEY_SIZE + < (word16)ssl->options.minDilithiumKeySz) { + WOLFSSL_MSG( "Dilithium key size in cert chain error"); + ret = DILITHIUM_KEY_SIZE_E; + } + break; + case ML_DSA_LEVEL5k: + if (ssl->options.minDilithiumKeySz < 0 || + ML_DSA_LEVEL5_KEY_SIZE + < (word16)ssl->options.minDilithiumKeySz) { + WOLFSSL_MSG("Dilithium key size in cert chain error"); + ret = DILITHIUM_KEY_SIZE_E; + } + break; #endif /* HAVE_DILITHIUM */ default: WOLFSSL_MSG("Key size not checked"); @@ -14995,6 +15087,25 @@ static int ProcessPeerCertsChainCRLCheck(WOLFSSL* ssl, ProcPeerCertArgs* args) } #endif +#ifdef OPENSSL_EXTRA +/* account for verify params flag set */ +static int AdjustCMForParams(WOLFSSL* ssl) +{ + int flags; + WOLFSSL_X509_VERIFY_PARAM* param; + + param = wolfSSL_get0_param(ssl); + flags = wolfSSL_X509_VERIFY_PARAM_get_flags(param); + + /* For now there is a possible contradiction of PARAM flags and store flags. + * Do not disable CRL support if it has already been enabled with store. */ + if (flags == 0) { + return WOLFSSL_SUCCESS; + } + return wolfSSL_X509_STORE_set_flags(SSL_STORE(ssl), flags); +} +#endif + int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz) { @@ -15063,6 +15174,14 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif } +#ifdef OPENSSL_EXTRA + /* account for verify params flag set */ + if (AdjustCMForParams(ssl) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Issue with updating store flags from PARAMS set"); + ERROR_OUT(WOLFSSL_FAILURE, exit_ppc); + } +#endif + switch (ssl->options.asyncState) { case TLS_ASYNC_BEGIN: @@ -15867,7 +15986,8 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, WOLFSSL_MSG( "\tCallback override available, will continue"); /* check if fatal error */ - args->fatal = (args->verifyErr) ? 1 : 0; + args->fatal = (args->verifyErr) ? (word16)(1) + : (word16)(0); if (args->fatal) DoCertFatalAlert(ssl, ret); } @@ -16541,9 +16661,14 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && \ !defined(WOLFSSL_DILITHIUM_NO_VERIFY) + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: + #endif { int keyRet = 0; if (ssl->peerDilithiumKey == NULL) { @@ -16557,18 +16682,32 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } if (keyRet == 0) { - if (args->dCert->keyOID == DILITHIUM_LEVEL2k) { + if (args->dCert->keyOID == ML_DSA_LEVEL2k) { keyRet = wc_dilithium_set_level( - ssl->peerDilithiumKey, 2); + ssl->peerDilithiumKey, WC_ML_DSA_44); + } + else if (args->dCert->keyOID == ML_DSA_LEVEL3k) { + keyRet = wc_dilithium_set_level( + ssl->peerDilithiumKey, WC_ML_DSA_65); + } + else if (args->dCert->keyOID == ML_DSA_LEVEL5k) { + keyRet = wc_dilithium_set_level( + ssl->peerDilithiumKey, WC_ML_DSA_87); + } + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if (args->dCert->keyOID == DILITHIUM_LEVEL2k) { + keyRet = wc_dilithium_set_level( + ssl->peerDilithiumKey, WC_ML_DSA_44_DRAFT); } else if (args->dCert->keyOID == DILITHIUM_LEVEL3k) { keyRet = wc_dilithium_set_level( - ssl->peerDilithiumKey, 3); + ssl->peerDilithiumKey, WC_ML_DSA_65_DRAFT); } else if (args->dCert->keyOID == DILITHIUM_LEVEL5k) { keyRet = wc_dilithium_set_level( - ssl->peerDilithiumKey, 5); + ssl->peerDilithiumKey, WC_ML_DSA_87_DRAFT); } + #endif } if (keyRet != 0 || @@ -16726,7 +16865,7 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #endif -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) /* handle processing of certificate (11) */ @@ -16863,7 +17002,7 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, status_length, ssl->heap); response->pendingCAs = pendingCAs; if ((OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, - 0) != 0) + 0, 0) != 0) || (response->responseStatus != OCSP_SUCCESSFUL) || (response->single->status->status != CERT_GOOD)) ret = BAD_CERTIFICATE_STATUS_ERROR; @@ -16943,11 +17082,11 @@ static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx, #endif -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ #endif /* !NO_CERTS */ -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) static int DoHelloRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, word32 totalSz) @@ -17556,7 +17695,7 @@ static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type) } #endif } -#endif +#endif /* !NO_WOLFSSL_SERVER */ if (ssl->options.dtls) ssl->msgsReceived.got_change_cipher = 1; break; @@ -17570,7 +17709,6 @@ static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type) return 0; } - int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, byte type, word32 size, word32 totalSz) { @@ -18083,8 +18221,7 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, WOLFSSL_LEAVE("DoHandShakeMsg()", ret); return ret; } - -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ #ifdef WOLFSSL_EXTRA_ALERTS int SendFatalAlertOnly(WOLFSSL *ssl, int error) @@ -19524,7 +19661,7 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, additionalSz = writeAeadAuthData(ssl, /* Length of the plain text minus the explicit * IV length minus the authentication tag size. */ - sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, type, + sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, type, ssl->encrypt.additional, 0, NULL, CUR_ORDER); if (additionalSz < 0) { ret = additionalSz; @@ -19548,19 +19685,19 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, ssl->encrypt.nonce, AESGCM_NONCE_SZ, out + sz - ssl->specs.aead_mac_size, ssl->specs.aead_mac_size, - ssl->encrypt.additional, additionalSz); + ssl->encrypt.additional, (word32)(additionalSz)); } if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif /* HAVE_PK_CALLBACKS */ { ret = aes_auth_fn(ssl->encrypt.aes, - out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ, - sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->encrypt.nonce, AESGCM_NONCE_SZ, - out + sz - ssl->specs.aead_mac_size, - ssl->specs.aead_mac_size, - ssl->encrypt.additional, additionalSz); + out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ, + sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, + ssl->encrypt.nonce, AESGCM_NONCE_SZ, + out + sz - ssl->specs.aead_mac_size, + ssl->specs.aead_mac_size, + ssl->encrypt.additional, (word32)(additionalSz)); } #ifdef WOLFSSL_ASYNC_CRYPT @@ -20016,24 +20153,24 @@ static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input, ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0, plain + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ, - sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, + sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, ssl->decrypt.nonce, AESGCM_NONCE_SZ, (byte *)(input + sz - ssl->specs.aead_mac_size), ssl->specs.aead_mac_size, - ssl->decrypt.additional, additionalSz); + ssl->decrypt.additional, (word32)(additionalSz)); } if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) #endif /* HAVE_PK_CALLBACKS */ { if ((ret = aes_auth_fn(ssl->decrypt.aes, - plain + AESGCM_EXP_IV_SZ, - input + AESGCM_EXP_IV_SZ, - sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size, - ssl->decrypt.nonce, AESGCM_NONCE_SZ, - input + sz - ssl->specs.aead_mac_size, - ssl->specs.aead_mac_size, - ssl->decrypt.additional, additionalSz)) < 0) { + plain + AESGCM_EXP_IV_SZ, + input + AESGCM_EXP_IV_SZ, + sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, + ssl->decrypt.nonce, AESGCM_NONCE_SZ, + input + sz - ssl->specs.aead_mac_size, + ssl->specs.aead_mac_size, + ssl->decrypt.additional, (word32)(additionalSz))) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) { ret = wolfSSL_AsyncPush(ssl, @@ -20794,7 +20931,7 @@ static byte MaskMac(const byte* data, int sz, int macSz, byte* expMac) r = (macSz - (scanStart - macStart)) % WC_SHA384_DIGEST_SIZE; #endif - XMEMSET(mac, 0, macSz); + XMEMSET(mac, 0, (size_t)(macSz)); for (i = scanStart; i < sz; i += macSz) { for (j = 0; j < macSz && j + i < sz; j++) { started = ctMaskGTE(i + j, macStart); @@ -20881,6 +21018,16 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) isEarlyData = isEarlyData && w64Equal(ssl->keys.curEpoch64, w64From32(0x0, DTLS13_EPOCH_EARLYDATA)); #endif +#ifdef WOLFSSL_DTLS13 + /* Application data should never appear in epoch 0 or 2 */ + if (ssl->options.tls1_3 && ssl->options.dtls && + (w64Equal(ssl->keys.curEpoch64, w64From32(0x0, DTLS13_EPOCH_HANDSHAKE)) + || w64Equal(ssl->keys.curEpoch64, w64From32(0x0, 0x0)))) + { + WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E); + return SANITY_MSG_E; + } +#endif #ifdef WOLFSSL_EARLY_DATA if (isEarlyData && acceptEarlyData) { @@ -20945,7 +21092,7 @@ int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff) } #endif - dataSz = msgSz - ssl->keys.padSz; + dataSz = (int)(msgSz - ssl->keys.padSz); if (dataSz < 0) { WOLFSSL_MSG("App data buffer error, malicious input?"); if (sniff == NO_SNIFF) { @@ -21150,6 +21297,13 @@ const char* AlertTypeToString(int type) return internal_error_str; } + case inappropriate_fallback: + { + static const char inappropriate_fallback_str[] = + "inappropriate_fallback"; + return inappropriate_fallback_str; + } + case user_canceled: { static const char user_canceled_str[] = @@ -21164,6 +21318,20 @@ const char* AlertTypeToString(int type) return no_renegotiation_str; } + case missing_extension: + { + static const char missing_extension_str[] = + "missing_extension"; + return missing_extension_str; + } + + case unsupported_extension: + { + static const char unsupported_extension_str[] = + "unsupported_extension"; + return unsupported_extension_str; + } + case unrecognized_name: { static const char unrecognized_name_str[] = @@ -21178,6 +21346,20 @@ const char* AlertTypeToString(int type) return bad_certificate_status_response_str; } + case unknown_psk_identity: + { + static const char unknown_psk_identity_str[] = + "unknown_psk_identity"; + return unknown_psk_identity_str; + } + + case certificate_required: + { + static const char certificate_required_str[] = + "certificate_required"; + return certificate_required_str; + } + case no_application_protocol: { static const char no_application_protocol_str[] = @@ -21335,7 +21517,7 @@ static int GetInputData(WOLFSSL *ssl, word32 size) if (usedLength > 0 && ssl->buffers.inputBuffer.idx != 0) XMEMMOVE(ssl->buffers.inputBuffer.buffer, ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx, - usedLength); + (size_t)(usedLength)); /* remove processed data */ ssl->buffers.inputBuffer.idx = 0; @@ -21395,6 +21577,7 @@ static WC_INLINE int VerifyMacEnc(WOLFSSL* ssl, const byte* input, word32 msgSz, WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR); return VERIFY_MAC_ERROR; } + XMEMSET(verify, 0, WC_MAX_DIGEST_SIZE); ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1, PEER_ORDER); ret |= ConstantCompare(verify, input + msgSz - digestSz, (int)digestSz); @@ -21417,7 +21600,7 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, word32 digestSz = MacSize(ssl); byte verify[WC_MAX_DIGEST_SIZE]; - + XMEMSET(verify, 0, WC_MAX_DIGEST_SIZE); if (ssl->specs.cipher_type == block) { pad = input[msgSz - 1]; padByte = 1; @@ -22918,7 +23101,8 @@ int SendChangeCipher(WOLFSSL* ssl) else return SendBuffered(ssl); } -#endif +#endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || + * (WOLFSSL_TLS13 && WOLFSSL_TLS13_MIDDLEBOX_COMPAT) */ #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY) @@ -23481,7 +23665,7 @@ int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input, min(args->ivSz, MAX_IV_SZ)); args->idx += min(args->ivSz, MAX_IV_SZ); } - XMEMCPY(output + args->idx, input, inSz); + XMEMCPY(output + args->idx, input, (size_t)(inSz)); args->idx += (word32)inSz; #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) if (ssl->options.dtls && DtlsGetCidTxSize(ssl) > 0) { @@ -23995,7 +24179,7 @@ int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request, ret = InitOcspRequest(request, cert, 0, ssl->heap); if (ret == 0) { /* make sure ctx OCSP request is updated */ - if (!ssl->buffers.weOwnCert) { + if (!ssl->buffers.weOwnCert && SSL_CM(ssl) != NULL) { wolfSSL_Mutex* ocspLock = &SSL_CM(ssl)->ocsp_stapling->ocspLock; if (wc_LockMutex(ocspLock) == 0) { if (ssl->ctx->certOcspRequest == NULL) { @@ -24143,7 +24327,9 @@ int cipherExtraData(WOLFSSL* ssl) #ifndef WOLFSSL_NO_TLS12 #ifndef NO_CERTS -#if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH) + +#if (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)) && \ + !defined(NO_TLS) /* handle generation of certificate (11) */ int SendCertificate(WOLFSSL* ssl) { @@ -24250,12 +24436,12 @@ int SendCertificate(WOLFSSL* ssl) else { fragSz = maxFragment - HANDSHAKE_HEADER_SZ; } - sendSz += fragSz + HANDSHAKE_HEADER_SZ; + sendSz += (int)(fragSz) + HANDSHAKE_HEADER_SZ; i += HANDSHAKE_HEADER_SZ; } else { fragSz = min(length, maxFragment); - sendSz += fragSz; + sendSz += (int)(fragSz); } if (IsEncryptionOn(ssl, 1)) @@ -24384,7 +24570,7 @@ int SendCertificate(WOLFSSL* ssl) DYNAMIC_TYPE_IN_BUFFER); if (input == NULL) return MEMORY_E; - XMEMCPY(input, output + recordHeaderSz, inputSz); + XMEMCPY(input, output + recordHeaderSz, (size_t)(inputSz)); } #ifndef WOLFSSL_DTLS @@ -24456,8 +24642,9 @@ int SendCertificate(WOLFSSL* ssl) return ret; } -#endif /* !NO_WOLFSSL_SERVER || !WOLFSSL_NO_CLIENT_AUTH */ +#endif /* !NO_TLS && (!NO_WOLFSSL_SERVER || !WOLFSSL_NO_CLIENT_AUTH) */ +#if !defined(NO_TLS) /* handle generation of certificate_request (13) */ int SendCertificateRequest(WOLFSSL* ssl) { @@ -24611,7 +24798,7 @@ int SendCertificateRequest(WOLFSSL* ssl) if (input == NULL) return MEMORY_E; - XMEMCPY(input, output + recordHeaderSz, inputSz); + XMEMCPY(input, output + recordHeaderSz, (size_t)(inputSz)); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, @@ -24665,8 +24852,11 @@ int SendCertificateRequest(WOLFSSL* ssl) return ret; } +#endif /* !NO_TLS */ + #ifndef NO_WOLFSSL_SERVER + #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status, @@ -24736,6 +24926,53 @@ static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status, return ret; } #endif + +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY)) +static int BuildCertificateStatusWithStatusCB(WOLFSSL* ssl) +{ + WOLFSSL_OCSP *ocsp; + void *ioCtx = NULL; + buffer response; + int ret; + + if (ssl == NULL) { + return BAD_FUNC_ARG; + } + + ocsp = SSL_CM(ssl)->ocsp_stapling; + if (ocsp == NULL || ocsp->statusCb == NULL) + return BAD_FUNC_ARG; + ioCtx = (ssl->ocspIOCtx != NULL) ? ssl->ocspIOCtx : ocsp->cm->ocspIOCtx; + XMEMSET(&response, 0, sizeof(response)); + WOLFSSL_MSG("Calling ocsp->statusCb"); + ret = ocsp->statusCb(ssl, ioCtx); + switch (ret) { + case SSL_TLSEXT_ERR_OK: + if (ssl->ocspResp == NULL || ssl->ocspRespSz == 0) { + ret = 0; + break; + } + response.buffer = ssl->ocspResp; + response.length = ssl->ocspRespSz; + ret = BuildCertificateStatus(ssl, WOLFSSL_CSR_OCSP, &response, 1); + break; + case SSL_TLSEXT_ERR_NOACK: + /* No OCSP response to send */ + ret = 0; + break; + case SSL_TLSEXT_ERR_ALERT_FATAL: + /* fall through */ + default: + ret = WOLFSSL_FATAL_ERROR; + break; + } + return ret; +} +#endif /* HAVE_CERTIFICATE_STATUS_REQUEST && (defined(OPENSSL_ALL) || + defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) */ + #endif /* NO_WOLFSSL_SERVER */ /* handle generation of certificate_status (22) */ @@ -24747,7 +24984,10 @@ int SendCertificateStatus(WOLFSSL* ssl) WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_SEND); WOLFSSL_ENTER("SendCertificateStatus"); - (void) ssl; + if (ssl == NULL || SSL_CM(ssl) == NULL) { + WOLFSSL_MSG("SendCertificateStatus bad args"); + return BAD_FUNC_ARG; + } #ifdef HAVE_CERTIFICATE_STATUS_REQUEST status_type = ssl->status_request; @@ -24757,6 +24997,16 @@ int SendCertificateStatus(WOLFSSL* ssl) status_type = status_type ? status_type : ssl->status_request_v2; #endif +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \ + (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \ + defined(WOLFSSL_HAPROXY)) + if (SSL_CM(ssl)->ocsp_stapling != NULL && + SSL_CM(ssl)->ocsp_stapling->statusCb != NULL) { + if (ssl->status_request == WOLFSSL_CSR_OCSP) + return BuildCertificateStatusWithStatusCB(ssl); + } +#endif + switch (status_type) { #ifndef NO_WOLFSSL_SERVER @@ -25032,7 +25282,8 @@ static int ModifyForMTU(WOLFSSL* ssl, int buffSz, int outputSz, int mtuSz) } #endif /* WOLFSSL_DTLS */ -#if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS) +#if !defined(NO_TLS) && defined(WOLFSSL_TLS13) && \ + !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS) /* * Enforce limits specified in * https://www.rfc-editor.org/rfc/rfc8446#section-5.5 @@ -25164,10 +25415,12 @@ int SendAsyncData(WOLFSSL* ssl) * 2 in SCR and we have plain data ready * Early data logic may bypass this logic in TLSv1.3 when appropriate. */ -static int ssl_in_handshake(WOLFSSL *ssl, int send) +static int ssl_in_handshake(WOLFSSL *ssl, int sending_data) { +int SendAsyncData = 1; +(void)SendAsyncData; if (IsSCR(ssl)) { - if (send) { + if (sending_data) { /* allow sending data in SCR */ return 0; } else { @@ -25200,16 +25453,21 @@ static int ssl_in_handshake(WOLFSSL *ssl, int send) return 0; } -int SendData(WOLFSSL* ssl, const void* data, int sz) +int SendData(WOLFSSL* ssl, const void* data, size_t sz) { - int sent = 0, /* plainText size */ - sendSz, + word32 sent = 0; /* plainText size */ + int sendSz, ret; #if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_EARLY_DATA_GROUP) int groupMsgs = 0; #endif int error = ssl->error; + if (sz > INT_MAX) { + WOLFSSL_MSG("SendData sz overflow"); + return WOLFSSL_FATAL_ERROR; + } + if (error == WC_NO_ERR_TRACE(WANT_WRITE) #ifdef WOLFSSL_ASYNC_CRYPT || error == WC_NO_ERR_TRACE(WC_PENDING_E) @@ -25314,7 +25572,7 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) sent = ssl->buffers.prevSent + ssl->buffers.plainSz; WOLFSSL_MSG("sent write buffered data"); - if (sent > sz) { + if (sent > (word32)sz) { WOLFSSL_MSG("error: write() after WANT_WRITE with short size"); return (ssl->error = BAD_FUNC_ARG); } @@ -25403,19 +25661,19 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) #ifdef WOLFSSL_DTLS if (ssl->options.dtls) { - buffSz = wolfSSL_GetMaxFragSize(ssl, sz - sent); + buffSz = wolfSSL_GetMaxFragSize(ssl, (word32)sz - sent); } else #endif { - buffSz = wolfSSL_GetMaxFragSize(ssl, sz - sent); + buffSz = wolfSSL_GetMaxFragSize(ssl, (word32)sz - sent); } - if (sent == sz) break; + if (sent == (word32)sz) break; #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_DTLS_SIZE_CHECK) - if (ssl->options.dtls && (buffSz < sz - sent)) { + if (ssl->options.dtls && ((size_t)buffSz < (word32)sz - sent)) { error = DTLS_SIZE_ERROR; ssl->error = error; WOLFSSL_ERROR(error); @@ -25571,6 +25829,9 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) } return error; } + else { + ssl->error = 0; /* Clear any previous errors */ + } sent += buffSz; @@ -25586,13 +25847,18 @@ int SendData(WOLFSSL* ssl, const void* data, int sz) } /* process input data */ -int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) +int ReceiveData(WOLFSSL* ssl, byte* output, size_t sz, int peek) { int size; int error = ssl->error; WOLFSSL_ENTER("ReceiveData"); + if (sz > INT_MAX) { + WOLFSSL_MSG("ReceiveData sz overflow"); + return WOLFSSL_FATAL_ERROR; + } + /* reset error state */ if (error == WC_NO_ERR_TRACE(WANT_READ) || error == WOLFSSL_ERROR_WANT_READ) { @@ -25742,9 +26008,10 @@ int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek) #endif } - size = (int)min((word32)sz, ssl->buffers.clearOutputBuffer.length); + size = (sz < (size_t)ssl->buffers.clearOutputBuffer.length) ? + (int)sz : (int)ssl->buffers.clearOutputBuffer.length; - XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, size); + XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, (size_t)(size)); if (peek == 0) { ssl->buffers.clearOutputBuffer.length -= (word32)size; @@ -25766,10 +26033,19 @@ static int SendAlert_ex(WOLFSSL* ssl, int severity, int type) int ret; int outputSz; int dtlsExtra = 0; + const char* alert_str = NULL; WOLFSSL_ENTER("SendAlert"); - WOLFSSL_MSG_EX("SendAlert: %d %s", type, AlertTypeToString(type)); + alert_str = AlertTypeToString(type); + if (alert_str != NULL) + { + WOLFSSL_MSG_EX("SendAlert: %d %s", type, alert_str); + } + else + { + WOLFSSL_MSG_EX("SendAlert: %d", type); + } #ifdef WOLFSSL_QUIC if (WOLFSSL_IS_QUIC(ssl)) { @@ -27708,6 +27984,7 @@ static int ParseCipherList(Suites* suites, } if (currLen == 0) break; + ++next; /* increment to skip ':' */ } #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) @@ -28059,8 +28336,7 @@ static int ParseCipherList(Suites* suites, break; } } - } - while (next++); /* increment to skip ':' */ + } while (next); if (ret) { int keySz = 0; @@ -28294,7 +28570,7 @@ int SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites, const byte* list, return ret; } -#endif /* OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */ #ifdef OPENSSL_EXTRA @@ -28487,6 +28763,7 @@ static int MatchSigAlgo(WOLFSSL* ssl, int sigAlgo) } #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL2) { /* Certificate has Dilithium level 2 key, only match with it. */ return sigAlgo == dilithium_level2_sa_algo; @@ -28499,6 +28776,19 @@ static int MatchSigAlgo(WOLFSSL* ssl, int sigAlgo) /* Certificate has Dilithium level 5 key, only match with it. */ return sigAlgo == dilithium_level5_sa_algo; } + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + if (ssl->pkCurveOID == CTC_ML_DSA_LEVEL2) { + /* Certificate has ML-DSA level 2 key, only match with it. */ + return sigAlgo == dilithium_level2_sa_algo; + } + if (ssl->pkCurveOID == CTC_ML_DSA_LEVEL3) { + /* Certificate has ML-DSA level 3 key, only match with it. */ + return sigAlgo == dilithium_level3_sa_algo; + } + if (ssl->pkCurveOID == CTC_ML_DSA_LEVEL5) { + /* Certificate has ML-DSA level 5 key, only match with it. */ + return sigAlgo == dilithium_level5_sa_algo; + } #endif /* HAVE_DILITHIUM */ #ifdef WC_RSA_PSS /* RSA certificate and PSS sig alg. */ @@ -28661,10 +28951,16 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz, } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) - if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL2 || - ssl->pkCurveOID == CTC_DILITHIUM_LEVEL3 || - ssl->pkCurveOID == CTC_DILITHIUM_LEVEL5) { - /* Matched Dilithium - set chosen and finished. */ + if (ssl->pkCurveOID == CTC_ML_DSA_LEVEL2 || + ssl->pkCurveOID == CTC_ML_DSA_LEVEL3 || + ssl->pkCurveOID == CTC_ML_DSA_LEVEL5 + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || ssl->pkCurveOID == CTC_DILITHIUM_LEVEL2 + || ssl->pkCurveOID == CTC_DILITHIUM_LEVEL3 + || ssl->pkCurveOID == CTC_DILITHIUM_LEVEL5 + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + ) { + /* Matched ML-DSA or Dilithium - set chosen and finished. */ ssl->options.sigAlgo = sigAlgo; ssl->options.hashAlgo = hashAlgo; ret = 0; @@ -29010,7 +29306,7 @@ int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz, return 0; } -#endif /* WOLFSSL_CALLBACKS */ +#endif /* WOLFSSL_CALLBACKS || OPENSSL_EXTRA */ #if !defined(NO_CERTS) @@ -29183,7 +29479,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) (ssl->buffers.keyType == dilithium_level3_sa_algo) || (ssl->buffers.keyType == dilithium_level5_sa_algo)) ssl->hsType = DYNAMIC_TYPE_DILITHIUM; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)(ssl->hsType), &ssl->hsKey); if (ret != 0) { goto exit_dpk; } @@ -29197,9 +29493,10 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) } else if (ssl->buffers.keyId) { ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsKey, - ssl->buffers.key->buffer, - ssl->buffers.key->length, ssl->heap, - ssl->buffers.keyDevId); + (ssl->buffers.key->buffer), + (int)(ssl->buffers.key->length), + ssl->heap, + ssl->buffers.keyDevId); } if (ret == 0) { if (ssl->buffers.keySz < ssl->options.minRsaKeySz) { @@ -29223,7 +29520,7 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) } else if (ssl->buffers.keyId) { ret = wc_ecc_init_id((ecc_key*)ssl->hsKey, - ssl->buffers.key->buffer, + (ssl->buffers.key->buffer), ssl->buffers.key->length, ssl->heap, ssl->buffers.keyDevId); } @@ -29292,13 +29589,13 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) } if (ret == 0) { if (ssl->buffers.keyType == dilithium_level2_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 2); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_44); } else if (ssl->buffers.keyType == dilithium_level3_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 3); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_65); } else if (ssl->buffers.keyType == dilithium_level5_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 5); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_87); } } if (ret == 0) { @@ -29632,13 +29929,13 @@ int DecodePrivateKey(WOLFSSL *ssl, word32* length) } if (ssl->buffers.keyType == dilithium_level2_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 2); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_44); } else if (ssl->buffers.keyType == dilithium_level3_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 3); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_65); } else if (ssl->buffers.keyType == dilithium_level5_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 5); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, WC_ML_DSA_87); } else { /* What if ssl->buffers.keyType is 0? We might want to do something @@ -29845,15 +30142,15 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length) if (ret == 0) { if (ssl->buffers.altKeyType == dilithium_level2_sa_algo) { ret = wc_dilithium_set_level( - (dilithium_key*)ssl->hsAltKey, 2); + (dilithium_key*)ssl->hsAltKey, WC_ML_DSA_44); } else if (ssl->buffers.altKeyType == dilithium_level3_sa_algo) { ret = wc_dilithium_set_level( - (dilithium_key*)ssl->hsAltKey, 3); + (dilithium_key*)ssl->hsAltKey, WC_ML_DSA_65); } else if (ssl->buffers.altKeyType == dilithium_level5_sa_algo) { ret = wc_dilithium_set_level( - (dilithium_key*)ssl->hsAltKey, 5); + (dilithium_key*)ssl->hsAltKey, WC_ML_DSA_87); } } if (ret == 0) { @@ -30064,13 +30361,13 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length) } if (ssl->buffers.altKeyType == dilithium_level2_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 2); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, WC_ML_DSA_44); } else if (ssl->buffers.altKeyType == dilithium_level3_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 3); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, WC_ML_DSA_65); } else if (ssl->buffers.altKeyType == dilithium_level5_sa_algo) { - ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 5); + ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, WC_ML_DSA_87); } else { /* What if ssl->buffers.keyType is 0? We might want to do something @@ -30139,7 +30436,8 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length) return ret; } #endif /* WOLFSSL_DUAL_ALG_CERTS */ -#endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */ + +#endif /* !NO_CERTS */ #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_TLS12) /* returns 1 if able to do TLS 1.3 otherwise 0 */ @@ -30164,7 +30462,7 @@ int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length) } #endif /* WOLFSSL_TLS13 */ -#ifndef WOLFSSL_NO_TLS12 +#if !defined(NO_TLS) && !defined(WOLFSSL_NO_TLS12) #if (!defined(NO_WOLFSSL_CLIENT) && (!defined(NO_DH) || defined(HAVE_ECC) || \ defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))) || \ (!defined(NO_WOLFSSL_SERVER) && (defined(HAVE_ECC) || \ @@ -30275,8 +30573,8 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, return ret; } -#endif -#endif /* !WOLFSSL_NO_TLS12 */ +#endif /* !NO_WOLFSSL_CLIENT [...etc] || !NO_WOLFSSL_SERVER [...etc] */ +#endif /* !NO_TLS && !WOLFSSL_NO_TLS12 */ /* client only parts */ #if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) @@ -30352,7 +30650,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, idSz = 0; } -#endif +#endif /* HAVE_SESSION_TICKET */ length = VERSION_SZ + RAN_LEN + (word32)idSz + ENUM_LEN + SUITE_LEN @@ -30383,7 +30681,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #endif if (extSz != 0) length += extSz + HELLO_EXT_SZ_SZ; -#endif +#endif /* HAVE_TLS_EXTENSIONS */ sendSz = (int)length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; if (ssl->arrays == NULL) { @@ -30455,7 +30753,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, idx += cookieSz; } } -#endif +#endif /* WOLFSSL_DTLS */ #ifndef NO_FORCE_SCR_SAME_SUITE if (IsSCR(ssl)) { @@ -30465,7 +30763,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, output[idx++] = ssl->options.cipherSuite; } else -#endif +#endif /* NO_FORCE_SCR_SAME_SUITE */ { /* then cipher suites */ c16toa(suites->suiteSz, output + idx); @@ -30491,7 +30789,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, (void)idx; /* suppress analyzer warning, keep idx current */ #else if (extSz != 0) { - c16toa(extSz, output + idx); + c16toa((word16)(extSz), output + idx); idx += HELLO_EXT_SZ_SZ; if (IsAtLeastTLSv1_2(ssl)) { @@ -30521,7 +30819,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } #endif } -#endif +#endif /* HAVE_TLS_EXTENSIONS */ if (IsEncryptionOn(ssl, 1)) { byte* input; @@ -30536,7 +30834,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (input == NULL) return MEMORY_E; - XMEMCPY(input, output + recordHeaderSz, inputSz); + XMEMCPY(input, output + recordHeaderSz, (size_t)(inputSz)); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, @@ -30671,7 +30969,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, && ssl->session->ticketLen > 0 #endif ); -#endif +#endif /* HAVE_SECRET_CALLBACK */ #ifdef HAVE_SESSION_TICKET /* server may send blank ticket which may not be expected to indicate @@ -30705,11 +31003,11 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } #endif - #ifdef OPENSSL_EXTRA + #ifdef OPENSSL_EXTRA if (ssl->CBIS != NULL) { ssl->CBIS(ssl, WOLFSSL_CB_HANDSHAKE_START, WOLFSSL_SUCCESS); } - #endif + #endif if (ssl->options.dtls) { if (pv.major != DTLS_MAJOR || pv.minor == DTLS_BOGUS_MINOR) { @@ -30757,7 +31055,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, WOLFSSL_ERROR_VERBOSE(VERSION_ERROR); return VERSION_ERROR; } - #endif + #endif /* HAVE_SECURE_RENEGOTIATION */ /* Checks made - OK to downgrade. */ ssl->version.minor = pv.minor; @@ -30921,7 +31219,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } } else -#endif +#endif /* HAVE_SECURE_RENEGOTIATION && !NO_FORCE_SCR_SAME_SUITE */ { word32 idx, found = 0; const Suites* suites = WOLFSSL_SUITES(ssl); @@ -30991,6 +31289,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, else ssl->options.haveEMS = 0; /* If no extensions, no EMS */ #else + /* !HAVE_TLS_EXTENSIONS */ { byte pendingEMS = 0; @@ -31038,7 +31337,9 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, else i += extSz; - totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz; + totalExtSz -= (word16)(OPAQUE16_LEN) + + (word16)(OPAQUE16_LEN) + + extSz; } *inOutIdx = i; @@ -31050,7 +31351,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, if (!pendingEMS && ssl->options.haveEMS) ssl->options.haveEMS = 0; } -#endif +#endif /* HAVE_TLS_EXTENSIONS */ #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK) if (ssl->secure_renegotiation == NULL || @@ -31115,7 +31416,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, } } else - #endif + #endif /* WOLFSSL_TLS13 */ if (ssl->ctx->method->version.major == SSLv3_MAJOR && ssl->ctx->method->version.minor == TLSv1_2_MINOR && (wolfSSL_get_options(ssl) & WOLFSSL_OP_NO_TLSv1_2) == 0) { @@ -31350,7 +31651,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, #endif *inOutIdx += dnSz; - len -= OPAQUE16_LEN + dnSz; + len -= (word16)(OPAQUE16_LEN) + dnSz; } #ifdef OPENSSL_EXTRA @@ -31366,6 +31667,7 @@ static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType, return CLIENT_CERT_CB_ERROR; } wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_EVP_PKEY_free(pkey); } @@ -31862,7 +32164,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, /* get PSK server hint from the wire */ srvHintLen = (int)min(length, MAX_PSK_ID_LEN); XMEMCPY(ssl->arrays->server_hint, input + args->idx, - srvHintLen); + (size_t)(srvHintLen)); ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */ args->idx += length; break; @@ -32082,7 +32384,7 @@ static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, /* get PSK server hint from the wire */ srvHintLen = (int)min(length, MAX_PSK_ID_LEN); XMEMCPY(ssl->arrays->server_hint, input + args->idx, - srvHintLen); + (size_t)(srvHintLen)); ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */ args->idx += length; @@ -32998,7 +33300,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) /* create private key */ ssl->hsType = DYNAMIC_TYPE_CURVE25519; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)(ssl->hsType), &ssl->hsKey); if (ret != 0) { goto exit_scke; } @@ -33049,7 +33351,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) /* create ephemeral private key */ ssl->hsType = DYNAMIC_TYPE_ECC; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)(ssl->hsType), &ssl->hsKey); if (ret != 0) { goto exit_scke; } @@ -33100,7 +33402,7 @@ int SendClientKeyExchange(WOLFSSL* ssl) /* create private key */ ssl->hsType = DYNAMIC_TYPE_CURVE25519; - ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey); + ret = AllocKey(ssl, (int)(ssl->hsType), &ssl->hsKey); if (ret != 0) { goto exit_scke; } @@ -34837,7 +35139,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* WOLF_PRIVATE_KEY_ID || HAVE_PK_CALLBACKS */ -#endif /* NO_CERTS */ +#endif /* !NO_CERTS */ #ifdef HAVE_ECC /* returns the WOLFSSL_* version of the curve from the OID sum */ @@ -34924,6 +35226,57 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* HAVE_ECC */ +#ifdef WOLFSSL_HAVE_MLKEM + /* Returns 1 when the given group is a PQC group, 0 otherwise. */ + int NamedGroupIsPqc(int group) + { + switch (group) { + #ifndef WOLFSSL_NO_ML_KEM + case WOLFSSL_ML_KEM_512: + case WOLFSSL_ML_KEM_768: + case WOLFSSL_ML_KEM_1024: + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case WOLFSSL_KYBER_LEVEL1: + case WOLFSSL_KYBER_LEVEL3: + case WOLFSSL_KYBER_LEVEL5: + #endif + return 1; + default: + return 0; + } + } + + /* Returns 1 when the given group is a PQC hybrid group, 0 otherwise. */ + int NamedGroupIsPqcHybrid(int group) + { + switch (group) { + #ifndef WOLFSSL_NO_ML_KEM + case WOLFSSL_P256_ML_KEM_768: + case WOLFSSL_X25519_ML_KEM_768: + case WOLFSSL_P384_ML_KEM_1024: + case WOLFSSL_P256_ML_KEM_512: + case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_X25519_ML_KEM_512: + case WOLFSSL_X448_ML_KEM_768: + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case WOLFSSL_P256_KYBER_LEVEL3: + case WOLFSSL_X25519_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL1: + case WOLFSSL_P384_KYBER_LEVEL3: + case WOLFSSL_P521_KYBER_LEVEL5: + case WOLFSSL_X25519_KYBER_LEVEL1: + case WOLFSSL_X448_KYBER_LEVEL3: + #endif + return 1; + default: + return 0; + } + } +#endif /* WOLFSSL_HAVE_MLKEM */ + int TranslateErrorToAlert(int err) { switch (err) { @@ -35164,7 +35517,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (input == NULL) return MEMORY_E; - XMEMCPY(input, output + recordHeaderSz, inputSz); + XMEMCPY(input, output + recordHeaderSz, (size_t)(inputSz)); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello)) != 0) { @@ -37553,11 +37906,6 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, { byte b; ProtocolVersion pv; -#ifdef WOLFSSL_SMALL_STACK - Suites* clSuites = NULL; -#else - Suites clSuites[1]; -#endif word32 i = *inOutIdx; word32 begin = i; int ret = 0; @@ -37625,8 +37973,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR) pv.minor = TLSv1_2_MINOR; - lesserVersion = !ssl->options.dtls && ssl->version.minor > pv.minor; - lesserVersion |= ssl->options.dtls && ssl->version.minor < pv.minor; + lesserVersion = (byte)(!ssl->options.dtls && + ssl->version.minor > pv.minor); + lesserVersion |= ssl->options.dtls &&ssl->version.minor < pv.minor; if (lesserVersion) { byte belowMinDowngrade; @@ -37855,40 +38204,40 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, goto out; } -#ifdef WOLFSSL_SMALL_STACK - clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap, + XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); + ssl->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap, DYNAMIC_TYPE_SUITES); - if (clSuites == NULL) { + if (ssl->clSuites == NULL) { ret = MEMORY_E; goto out; } -#endif - XMEMSET(clSuites, 0, sizeof(Suites)); - ato16(&input[i], &clSuites->suiteSz); + XMEMSET(ssl->clSuites, 0, sizeof(Suites)); + ato16(&input[i], &ssl->clSuites->suiteSz); i += OPAQUE16_LEN; /* Cipher suite lists are always multiples of two in length. */ - if (clSuites->suiteSz % 2 != 0) { + if (ssl->clSuites->suiteSz % 2 != 0) { ret = BUFFER_ERROR; goto out; } /* suites and compression length check */ - if ((i - begin) + clSuites->suiteSz + OPAQUE8_LEN > helloSz) { + if ((i - begin) + ssl->clSuites->suiteSz + OPAQUE8_LEN > helloSz) { ret = BUFFER_ERROR; goto out; } - if (clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ) { + if (ssl->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ) { ret = BUFFER_ERROR; goto out; } - XMEMCPY(clSuites->suites, input + i, clSuites->suiteSz); + XMEMCPY(ssl->clSuites->suites, input + i, ssl->clSuites->suiteSz); #ifdef HAVE_SERVER_RENEGOTIATION_INFO /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */ - if (FindSuite(clSuites, 0, TLS_EMPTY_RENEGOTIATION_INFO_SCSV) >= 0) { + if (FindSuite(ssl->clSuites, 0, TLS_EMPTY_RENEGOTIATION_INFO_SCSV) >= + 0) { TLSX* extension; /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */ @@ -37910,7 +38259,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif /* HAVE_SERVER_RENEGOTIATION_INFO */ #if defined(HAVE_FALLBACK_SCSV) || defined(OPENSSL_ALL) /* check for TLS_FALLBACK_SCSV suite */ - if (FindSuite(clSuites, TLS_FALLBACK_SCSV, 0) >= 0) { + if (FindSuite(ssl->clSuites, TLS_FALLBACK_SCSV, 0) >= 0) { WOLFSSL_MSG("Found Fallback SCSV"); if (ssl->ctx->method->version.minor > pv.minor) { WOLFSSL_MSG("Client trying to connect with lesser version"); @@ -37921,8 +38270,8 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif - i += clSuites->suiteSz; - clSuites->hashSigAlgoSz = 0; + i += ssl->clSuites->suiteSz; + ssl->clSuites->hashSigAlgoSz = 0; /* compression length */ b = input[i++]; @@ -38009,7 +38358,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #ifdef HAVE_TLS_EXTENSIONS /* tls extensions */ if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, client_hello, - clSuites))) + ssl->clSuites))) goto out; #ifdef WOLFSSL_TLS13 if (TLSX_Find(ssl->extensions, @@ -38065,15 +38414,16 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, goto out; } - clSuites->hashSigAlgoSz = hashSigAlgoSz; - if (clSuites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) { + ssl->clSuites->hashSigAlgoSz = hashSigAlgoSz; + if (ssl->clSuites->hashSigAlgoSz > + WOLFSSL_MAX_SIGALGO) { WOLFSSL_MSG("ClientHello SigAlgo list exceeds max, " "truncating"); - clSuites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO; + ssl->clSuites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO; } - XMEMCPY(clSuites->hashSigAlgo, &input[i], - clSuites->hashSigAlgoSz); + XMEMCPY(ssl->clSuites->hashSigAlgo, &input[i], + ssl->clSuites->hashSigAlgoSz); i += hashSigAlgoSz; } @@ -38084,7 +38434,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, else i += extSz; - totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz; + totalExtSz -= (word16)(OPAQUE16_LEN + OPAQUE16_LEN) + extSz; } #endif *inOutIdx = i; @@ -38104,7 +38454,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* ProcessOld uses same resume code */ WOLFSSL_MSG_EX("ssl->options.resuming %d", ssl->options.resuming); if (ssl->options.resuming) { - ret = HandleTlsResumption(ssl, clSuites); + ret = HandleTlsResumption(ssl, ssl->clSuites); if (ret != 0) goto out; @@ -38140,19 +38490,12 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif #ifdef OPENSSL_EXTRA - ssl->clSuites = clSuites; /* cppcheck-suppress autoVariables - * - * (suppress warning that ssl, a persistent - * non-local allocation, has its ->clSuites - * set to clSuites, a local stack allocation. - * we clear this assignment before returning.) - */ /* Give user last chance to provide a cert for cipher selection */ if (ret == 0 && ssl->ctx->certSetupCb != NULL) ret = CertSetupCbWrapper(ssl); #endif if (ret == 0) - ret = MatchSuite(ssl, clSuites); + ret = MatchSuite(ssl, ssl->clSuites); #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_ENCRYPT_THEN_MAC) && \ !defined(WOLFSSL_AEAD_ONLY) @@ -38170,11 +38513,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif out: -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) +#if !defined(OPENSSL_EXTRA) + XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); ssl->clSuites = NULL; -#endif -#ifdef WOLFSSL_SMALL_STACK - XFREE(clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); #endif WOLFSSL_LEAVE("DoClientHello", ret); WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO); @@ -38709,7 +39050,7 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (input == NULL) return MEMORY_E; - XMEMCPY(input, output + recordHeaderSz, inputSz); + XMEMCPY(input, output + recordHeaderSz, (size_t)(inputSz)); #ifdef WOLFSSL_DTLS if (IsDtlsNotSctpMode(ssl) && (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello_done)) != 0) { @@ -39404,8 +39745,19 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_MSG("Found session matching the session id" " found in the ticket"); /* Allocate and populate an InternalTicket */ + #ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC(sizeof(InternalTicket), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (tmp != NULL && psk->identity != NULL) + { + XMEMCPY(tmp, psk->identity, psk->identityLen); + XFREE(psk->identity, ssl->heap, DYNAMIC_TYPE_TLSX); + psk->identity = NULL; + } + #else tmp = (byte*)XREALLOC(psk->identity, sizeof(InternalTicket), ssl->heap, DYNAMIC_TYPE_TLSX); + #endif if (tmp != NULL) { XMEMSET(tmp, 0, sizeof(InternalTicket)); psk->identity = tmp; @@ -41522,8 +41874,7 @@ static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ], ret = args->lastErr; args->lastErr = 0; /* reset */ /* On error 'ret' will be negative */ - mask = ((unsigned int)ret >> - ((sizeof(ret) * 8) - 1)) - 1; + mask = (byte)(((unsigned int)ret >> ((sizeof(ret) * 8) - 1)) - 1); /* build PreMasterSecret */ ssl->arrays->preMasterSecret[0] = ssl->chVersion.major; @@ -41962,7 +42313,7 @@ int wolfSSL_set_iotsafe_ctx(WOLFSSL *ssl, IOTSAFE *iotsafe) return 0; } -#endif +#endif /* WOLFSSL_IOTSAFE && HAVE_PK_CALLBACKS */ #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) /* create an instance of WOLFSSL_BY_DIR_HASH structure */ @@ -42051,32 +42402,7 @@ WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_value( WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_pop( WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_BY_DIR_HASH* hash; - - WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_pop"); - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - hash = sk->data.dir_hash; - - if (node != NULL) { /* update sk and remove node from stack */ - sk->data.dir_hash = node->data.dir_hash; - sk->next = node->next; - wolfSSL_sk_free_node(node); - } - else { /* last x509 in stack */ - sk->data.dir_hash = NULL; - } - - if (sk->num > 0) { - sk->num -= 1; - } - - return hash; + return (WOLFSSL_BY_DIR_HASH *)wolfSSL_sk_pop(sk); } /* release all contents in stack, and then release stack itself. */ /* Second argument is a function pointer to release resources. */ @@ -42131,39 +42457,13 @@ void wolfSSL_sk_BY_DIR_HASH_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk) int wolfSSL_sk_BY_DIR_HASH_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk, WOLFSSL_BY_DIR_HASH* in) { - WOLFSSL_STACK* node; - WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_push"); if (sk == NULL || in == NULL) { return WOLFSSL_FAILURE; } - /* no previous values in stack */ - if (sk->data.dir_hash == NULL) { - sk->data.dir_hash = in; - sk->num += 1; - return WOLFSSL_SUCCESS; - } - - /* stack already has value(s) create a new node and add more */ - node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, - DYNAMIC_TYPE_OPENSSL); - if (node == NULL) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; - } - XMEMSET(node, 0, sizeof(WOLFSSL_STACK)); - - /* push new obj onto head of stack */ - node->data.dir_hash = sk->data.dir_hash; - node->next = sk->next; - node->type = sk->type; - sk->next = node; - sk->data.dir_hash = in; - sk->num += 1; - - return WOLFSSL_SUCCESS; + return wolfSSL_sk_push(sk, in); } /* create an instance of WOLFSSL_BY_DIR_entry structure */ WOLFSSL_BY_DIR_entry* wolfSSL_BY_DIR_entry_new(void) @@ -42234,32 +42534,7 @@ WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_value( WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_pop( WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_BY_DIR_entry* entry; - - WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_pop"); - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - entry = sk->data.dir_entry; - - if (node != NULL) { /* update sk and remove node from stack */ - sk->data.dir_entry = node->data.dir_entry; - sk->next = node->next; - wolfSSL_sk_free_node(node); - } - else { /* last x509 in stack */ - sk->data.dir_entry = NULL; - } - - if (sk->num > 0) { - sk->num -= 1; - } - - return entry; + return (WOLFSSL_BY_DIR_entry *)wolfSSL_sk_pop(sk); } /* release all contents in stack, and then release stack itself. */ /* Second argument is a function pointer to release resources. */ @@ -42315,40 +42590,16 @@ void wolfSSL_sk_BY_DIR_entry_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry) *sk) int wolfSSL_sk_BY_DIR_entry_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk, WOLFSSL_BY_DIR_entry* in) { - WOLFSSL_STACK* node; + WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_push"); if (sk == NULL || in == NULL) { return WOLFSSL_FAILURE; } - /* no previous values in stack */ - if (sk->data.dir_entry == NULL) { - sk->data.dir_entry = in; - sk->num += 1; - return WOLFSSL_SUCCESS; - } - - /* stack already has value(s) create a new node and add more */ - node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL, - DYNAMIC_TYPE_OPENSSL); - if (node == NULL) { - WOLFSSL_MSG("Memory error"); - return WOLFSSL_FAILURE; - } - XMEMSET(node, 0, sizeof(WOLFSSL_STACK)); - - /* push new obj onto head of stack */ - node->data.dir_entry = sk->data.dir_entry; - node->next = sk->next; - node->type = sk->type; - sk->next = node; - sk->data.dir_entry = in; - sk->num += 1; - - return WOLFSSL_SUCCESS; + return wolfSSL_sk_push(sk, in); } -#endif /* OPENSSL_ALL */ +#endif /* OPENSSL_ALL && !NO_FILESYSTEM && !NO_FILESYSTEM */ #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) @@ -42487,4 +42738,4 @@ static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, #undef ERROR_OUT -#endif /* WOLFCRYPT_ONLY */ +#endif /* !WOLFCRYPT_ONLY */ diff --git a/src/src/keys.c b/src/src/keys.c index 4ff687e..8f8d2eb 100644 --- a/src/src/keys.c +++ b/src/src/keys.c @@ -1,6 +1,6 @@ /* keys.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,11 +22,7 @@ /* Name change compatibility layer no longer needs to be included here */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) @@ -128,6 +124,9 @@ int GetCipherSpec(word16 side, byte cipherSuite0, byte cipherSuite, } #endif /* NO_WOLFSSL_CLIENT */ + /* Initialize specs */ + XMEMSET(specs, 0, sizeof(CipherSpecs)); + /* Chacha extensions, 0xcc */ if (cipherSuite0 == CHACHA_BYTE) { @@ -3908,7 +3907,8 @@ int DeriveKeys(WOLFSSL* ssl) XMEMCPY(shaInput + idx, ssl->arrays->clientRandom, RAN_LEN); if (ret == 0) { ret = wc_ShaUpdate(sha, shaInput, - (KEY_PREFIX + SECRET_LEN + 2 * RAN_LEN) - KEY_PREFIX + j); + (KEY_PREFIX + SECRET_LEN + 2 * RAN_LEN) - KEY_PREFIX + + (word32)(j)); } if (ret == 0) { ret = wc_ShaFinal(sha, shaOutput); @@ -3942,12 +3942,13 @@ int DeriveKeys(WOLFSSL* ssl) static int CleanPreMaster(WOLFSSL* ssl) { - int i, ret, sz = ssl->arrays->preMasterSz; + int i, ret, sz = (int)(ssl->arrays->preMasterSz); for (i = 0; i < sz; i++) ssl->arrays->preMasterSecret[i] = 0; - ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->preMasterSecret, sz); + ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->preMasterSecret, + (word32)(sz)); if (ret != 0) return ret; @@ -4035,8 +4036,8 @@ static int MakeSslMasterSecret(WOLFSSL* ssl) } idx = 0; - XMEMCPY(shaInput, prefix, i + 1); - idx += i + 1; + XMEMCPY(shaInput, prefix, (size_t)(i + 1)); + idx += (word32)(i + 1); XMEMCPY(shaInput + idx, ssl->arrays->preMasterSecret, pmsSz); idx += pmsSz; diff --git a/src/src/ocsp.c b/src/src/ocsp.c index cf824f6..c90936a 100644 --- a/src/src/ocsp.c +++ b/src/src/ocsp.c @@ -1,6 +1,6 @@ /* ocsp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* Name change compatibility layer no longer needs to be included here */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - /* * WOLFSSL_NO_OCSP_ISSUER_CHAIN_CHECK: * Disable looking for an authorized responder in the verification path of @@ -333,7 +328,7 @@ int CheckOcspResponse(WOLFSSL_OCSP *ocsp, byte *response, int responseSz, ocspResponse->pendingCAs = TLSX_CSR2_GetPendingSigners(((WOLFSSL*)ocspRequest->ssl)->extensions); } #endif - ret = OcspResponseDecode(ocspResponse, ocsp->cm, ocsp->cm->heap, 0); + ret = OcspResponseDecode(ocspResponse, ocsp->cm, ocsp->cm->heap, 0, 0); if (ret != 0) { ocsp->error = ret; WOLFSSL_LEAVE("OcspResponseDecode failed", ocsp->error); @@ -480,31 +475,6 @@ int CheckOcspRequest(WOLFSSL_OCSP* ocsp, OcspRequest* ocspRequest, ioCtx = (ssl && ssl->ocspIOCtx != NULL) ? ssl->ocspIOCtx : ocsp->cm->ocspIOCtx; -#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - if (ocsp->statusCb != NULL && ssl != NULL) { - WOLFSSL_MSG("Calling ocsp->statusCb"); - ret = ocsp->statusCb(ssl, ioCtx); - switch (ret) { - case SSL_TLSEXT_ERR_OK: - ret = wolfSSL_get_ocsp_response(ssl, &response); - ret = CheckOcspResponse(ocsp, response, ret, responseBuffer, - status, entry, NULL, heap); - XFREE(response, NULL, DYNAMIC_TYPE_OPENSSL); - break; - case SSL_TLSEXT_ERR_NOACK: - ret = OCSP_LOOKUP_FAIL; - break; - case SSL_TLSEXT_ERR_ALERT_FATAL: - default: - WOLFSSL_LEAVE("CheckOcspRequest", ocsp->error); - ret = WOLFSSL_FATAL_ERROR; - break; - } - WOLFSSL_LEAVE("CheckOcspRequest", ret); - return ret; - } -#endif - if (ocsp->cm->ocspUseOverrideURL) { url = ocsp->cm->ocspOverrideURL; if (url != NULL && url[0] != '\0') @@ -656,9 +626,6 @@ int CheckOcspResponder(OcspResponse *bs, DecodedCert *cert, void* vp) if (!passed) { WOLFSSL_MSG("\tOCSP Responder not authorized"); -#ifdef OPENSSL_EXTRA - bs->verifyError = OCSP_BAD_ISSUER; -#endif ret = BAD_OCSP_RESPONDER; break; } @@ -755,13 +722,23 @@ WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_cert_to_id( WOLFSSL_CERT_MANAGER* cm = NULL; int ret = -1; DerBuffer* derCert = NULL; + int dgstType; #ifdef WOLFSSL_SMALL_STACK DecodedCert *cert = NULL; #else DecodedCert cert[1]; #endif - (void)dgst; + if (dgst == NULL) { + dgstType = WC_HASH_TYPE_SHA; + } + else if (wolfSSL_EVP_get_hashinfo(dgst, &dgstType, NULL) != + WOLFSSL_SUCCESS) { + return NULL; + } + + if (dgstType != OCSP_DIGEST) + return NULL; cm = wolfSSL_CertManagerNew(); if (cm == NULL @@ -813,6 +790,7 @@ WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_cert_to_id( goto out; } else { + certId->hashAlgoOID = wc_HashGetOID(OCSP_DIGEST); XMEMCPY(certId->issuerHash, cert->issuerHash, OCSP_DIGEST_SIZE); XMEMCPY(certId->issuerKeyHash, cert->issuerKeyHash, OCSP_DIGEST_SIZE); XMEMCPY(certId->status->serial, cert->serial, (size_t)cert->serialSz); @@ -850,79 +828,246 @@ void wolfSSL_OCSP_BASICRESP_free(WOLFSSL_OCSP_BASICRESP* basicResponse) wolfSSL_OCSP_RESPONSE_free(basicResponse); } -/* Signature verified in DecodeBasicOcspResponse. - * But no store available to verify certificate. */ -int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP *bs, - WOLF_STACK_OF(WOLFSSL_X509) *certs, WOLFSSL_X509_STORE *st, unsigned long flags) +/* Calculate ancode CertID DER encoding following RFC 6960: + CertID ::= SEQUENCE { + hashAlgorithm AlgorithmIdentifier, + issuerNameHash OCTET STRING, + issuerKeyHash OCTET STRING, + serialNumber CertificateSerialNumber } +*/ +static int OcspEncodeCertID(WOLFSSL_OCSP_CERTID* id, byte* output, + word32* totalSz, word32* intSize) { - int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); -#ifdef WOLFSSL_SMALL_STACK - DecodedCert *cert; -#else - DecodedCert cert[1]; -#endif - byte certInit = 0; - int idx; + word32 idx = 0; + int ret; - (void)certs; + if (id == NULL || totalSz == NULL || intSize == NULL || + (output != NULL && (*totalSz == 0 || *totalSz <= *intSize))) + return BAD_FUNC_ARG; - if (flags & WOLFSSL_OCSP_NOVERIFY) - return WOLFSSL_SUCCESS; + if (output != NULL) { + ret = SetSequence(*intSize, output); + if (ret < 0) + return ret; + idx += ret; + } -#ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert *) - XMALLOC(sizeof(*cert), (st && st->cm) ? st->cm->heap : NULL, - DYNAMIC_TYPE_DCERT); - if (cert == NULL) - return WOLFSSL_FAILURE; -#endif + ret = SetAlgoID(id->hashAlgoOID, ((output != NULL) ? output + idx : output), + oidHashType, 0); + if (ret <= 0) + return -1; + idx += ret; - if (bs->verifyError != OCSP_VERIFY_ERROR_NONE) - goto out; + /* issuerNameHash */ + ret = SetOctetString(OCSP_DIGEST_SIZE, ((output != NULL) ? output + idx : output)); + if (ret < 0) + return ret; + idx += ret; + if (output != NULL) + XMEMCPY(output + idx, id->issuerHash, OCSP_DIGEST_SIZE); + idx += OCSP_DIGEST_SIZE; + + /* issuerKeyHash */ + ret = SetOctetString(OCSP_DIGEST_SIZE, ((output != NULL) ? output + idx : output)); + if (ret < 0) + return ret; + idx += ret; + if (output != NULL) + XMEMCPY(output + idx, id->issuerKeyHash, OCSP_DIGEST_SIZE); + idx += OCSP_DIGEST_SIZE; + + /* serialNumber */ + ret = SetASNInt(id->status->serialSz, id->status->serial[0], ((output != NULL) ? output + idx : output)); + if (ret < 0) + return ret; + idx += ret; + if (output != NULL) + XMEMCPY(output + idx, id->status->serial, id->status->serialSz); + idx += id->status->serialSz; - if (flags & WOLFSSL_OCSP_TRUSTOTHER) { - for (idx = 0; idx < wolfSSL_sk_X509_num(certs); idx++) { - WOLFSSL_X509* x = wolfSSL_sk_X509_value(certs, idx); - int derSz = 0; - const byte* der = wolfSSL_X509_get_der(x, &derSz); - if (der != NULL && derSz == (int)bs->certSz && - XMEMCMP(bs->cert, der, (size_t)derSz) == 0) { - ret = WOLFSSL_SUCCESS; - goto out; - } + if (output == NULL) { + *intSize = idx; + ret = SetSequence(idx, NULL); + if (ret < 0) + return ret; + idx += ret; + *totalSz = idx; + } + else if (idx != *totalSz) { + return BUFFER_E; + } + + return 0; +} + +static int OcspRespIdMatches(OcspResponse* resp, const byte* NameHash, + const byte* keyHash) +{ + if (resp->responderIdType == OCSP_RESPONDER_ID_NAME) { + return XMEMCMP(NameHash, resp->responderId.nameHash, + SIGNER_DIGEST_SIZE) == 0; + } + else if (resp->responderIdType == OCSP_RESPONDER_ID_KEY) { + return XMEMCMP(keyHash, resp->responderId.keyHash, KEYID_SIZE) == 0; + } + + return 0; +} + +static int OcspFindSigner(WOLFSSL_OCSP_BASICRESP *resp, + WOLF_STACK_OF(WOLFSSL_X509) *certs, DecodedCert **signer, int *embedded, + unsigned long flags) +{ + WOLFSSL_X509 *signer_x509 = NULL; + DecodedCert *certDecoded; + int i; + + certDecoded = (DecodedCert *)XMALLOC(sizeof(*certDecoded), resp->heap, + DYNAMIC_TYPE_DCERT); + if (certDecoded == NULL) + return MEMORY_E; + + for (i = 0; i < wolfSSL_sk_X509_num(certs); i++) { + signer_x509 = wolfSSL_sk_X509_value(certs, i); + if (signer_x509 == NULL) + continue; + + InitDecodedCert(certDecoded, signer_x509->derCert->buffer, + signer_x509->derCert->length, resp->heap); + if (ParseCertRelative(certDecoded, CERT_TYPE, NO_VERIFY, + NULL, NULL) == 0) { + if (OcspRespIdMatches(resp, certDecoded->subjectHash, + certDecoded->subjectKeyHash)) { + *signer = certDecoded; + *embedded = 0; + return 0; + } } + FreeDecodedCert(certDecoded); } - InitDecodedCert(cert, bs->cert, bs->certSz, NULL); - certInit = 1; - if (ParseCertRelative(cert, CERT_TYPE, VERIFY, st->cm, NULL) < 0) - goto out; + if (flags & WOLFSSL_OCSP_NOINTERN) { + XFREE(certDecoded, resp->heap, DYNAMIC_TYPE_DCERT); + return ASN_NO_SIGNER_E; + } - if (!(flags & WOLFSSL_OCSP_NOCHECKS)) { - if (CheckOcspResponder(bs, cert, st->cm) != 0) - goto out; + /* not found in certs, search the cert embedded in the response */ + InitDecodedCert(certDecoded, resp->cert, resp->certSz, resp->heap); + if (ParseCertRelative(certDecoded, CERT_TYPE, NO_VERIFY, NULL, NULL) == 0) { + if (OcspRespIdMatches(resp, certDecoded->subjectHash, + certDecoded->subjectKeyHash)) { + *signer = certDecoded; + *embedded = 1; + return 0; + } } + FreeDecodedCert(certDecoded); - ret = WOLFSSL_SUCCESS; -out: - if (certInit) - FreeDecodedCert(cert); + XFREE(certDecoded, resp->heap, DYNAMIC_TYPE_DCERT); + return ASN_NO_SIGNER_E; +} +static int OcspVerifySigner(WOLFSSL_OCSP_BASICRESP *resp, DecodedCert *cert, + WOLFSSL_X509_STORE *st, unsigned long flags) +{ #ifdef WOLFSSL_SMALL_STACK - XFREE(cert, (st && st->cm) ? st->cm->heap : NULL, DYNAMIC_TYPE_DCERT); + DecodedCert *c = NULL; +#else + DecodedCert c[1]; +#endif + + int ret = -1; + if (st == NULL) + return ASN_OCSP_CONFIRM_E; + +#ifdef WOLFSSL_SMALL_STACK + c = (DecodedCert *)XMALLOC(sizeof(*c), NULL, DYNAMIC_TYPE_DCERT); + if (c == NULL) + return MEMORY_E; #endif + InitDecodedCert(c, cert->source, cert->maxIdx, NULL); + if (ParseCertRelative(c, CERT_TYPE, VERIFY, st->cm, NULL) != 0) { + ret = ASN_OCSP_CONFIRM_E; + goto err; + } +#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK + if ((flags & WOLFSSL_OCSP_NOCHECKS) == 0) { + ret = CheckOcspResponder(resp, c, st->cm); + } + else { + ret = 0; + } +#else + (void)resp; + (void)flags; + ret = 0; +#endif + +err: + FreeDecodedCert(c); +#ifdef WOLFSSL_SMALL_STACK + XFREE(c, NULL, DYNAMIC_TYPE_DCERT); +#endif return ret; } +/* Signature verified in DecodeBasicOcspResponse. + * But no store available to verify certificate. */ +int wolfSSL_OCSP_basic_verify(WOLFSSL_OCSP_BASICRESP* bs, + WOLF_STACK_OF(WOLFSSL_X509) * certs, WOLFSSL_X509_STORE* st, + unsigned long flags) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + int embedded; + DecodedCert *cert = NULL; + + ret = OcspFindSigner(bs, certs, &cert, &embedded, flags); + if (ret != 0) { + WOLFSSL_MSG("OCSP no signer found"); + return WOLFSSL_FAILURE; + } + + /* skip certificate verification if cert in certs and TRUST_OTHER is true */ + if (!embedded && (flags & WOLFSSL_OCSP_TRUSTOTHER) != 0) + flags |= WOLFSSL_OCSP_NOVERIFY; + + /* verify response signature */ + ret = ConfirmSignature( + &cert->sigCtx, + bs->response, bs->responseSz, + cert->publicKey, cert->pubKeySize, cert->keyOID, + bs->sig, bs->sigSz, bs->sigOID, bs->sigParams, bs->sigParamsSz, + NULL); + + if (ret != 0) { + WOLFSSL_MSG("OCSP signature verification failed"); + ret = -1; + goto err; + } + + if ((flags & WOLFSSL_OCSP_NOVERIFY) == 0) { + ret = OcspVerifySigner(bs, cert, st, flags); + } + +err: + FreeDecodedCert(cert); + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; +} void wolfSSL_OCSP_RESPONSE_free(OcspResponse* response) { + OcspEntry *s, *sNext; if (response == NULL) return; - if (response->single != NULL) { - FreeOcspEntry(response->single, NULL); - XFREE(response->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); + + s = response->single; + while (s != NULL) { + sNext = s->next; + FreeOcspEntry(s, NULL); + XFREE(s, NULL, DYNAMIC_TYPE_OCSP_ENTRY); + s = sNext; } XFREE(response->source, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -1045,7 +1190,7 @@ OcspResponse* wolfSSL_d2i_OCSP_RESPONSE(OcspResponse** response, XMEMCPY(resp->source, *data, (size_t)len); resp->maxIdx = (word32)len; - ret = OcspResponseDecode(resp, NULL, NULL, 1); + ret = OcspResponseDecode(resp, NULL, NULL, 1, 1); if (ret != 0 && ret != WC_NO_ERR_TRACE(ASN_OCSP_CONFIRM_E)) { /* for just converting from a DER to an internal structure the CA may * not yet be known to this function for signature verification */ @@ -1100,27 +1245,9 @@ const char *wolfSSL_OCSP_response_status_str(long s) WOLFSSL_OCSP_BASICRESP* wolfSSL_OCSP_response_get1_basic(OcspResponse* response) { WOLFSSL_OCSP_BASICRESP* bs; + const unsigned char *ptr = response->source; - bs = (WOLFSSL_OCSP_BASICRESP*)XMALLOC(sizeof(WOLFSSL_OCSP_BASICRESP), NULL, - DYNAMIC_TYPE_OCSP_REQUEST); - if (bs == NULL) - return NULL; - - XMEMCPY(bs, response, sizeof(OcspResponse)); - bs->single = (OcspEntry*)XMALLOC(sizeof(OcspEntry), NULL, - DYNAMIC_TYPE_OCSP_ENTRY); - bs->source = (byte*)XMALLOC(bs->maxIdx, NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (bs->single == NULL || bs->source == NULL) { - XFREE(bs->single, NULL, DYNAMIC_TYPE_OCSP_ENTRY); - bs->single = NULL; - wolfSSL_OCSP_RESPONSE_free(bs); - bs = NULL; - } - else { - XMEMCPY(bs->single, response->single, sizeof(OcspEntry)); - XMEMCPY(bs->source, response->source, response->maxIdx); - bs->single->ownStatus = 0; - } + bs = wolfSSL_d2i_OCSP_RESPONSE(NULL, &ptr, response->maxIdx); return bs; } @@ -1235,22 +1362,59 @@ int wolfSSL_i2d_OCSP_REQUEST_bio(WOLFSSL_BIO* out, int wolfSSL_i2d_OCSP_CERTID(WOLFSSL_OCSP_CERTID* id, unsigned char** data) { - if (id == NULL || data == NULL) - return WOLFSSL_FAILURE; + int allocated = 0; + word32 derSz = 0; + word32 intSz = 0; + int ret; + WOLFSSL_ENTER("wolfSSL_i2d_OCSP_CERTID"); - if (*data != NULL) { - XMEMCPY(*data, id->rawCertId, (size_t)id->rawCertIdSize); - *data = *data + id->rawCertIdSize; + if (id == NULL) + return -1; + + if (id->rawCertId != NULL) { + derSz = id->rawCertIdSize; } else { - *data = (unsigned char*)XMALLOC((size_t)id->rawCertIdSize, NULL, DYNAMIC_TYPE_OPENSSL); + ret = OcspEncodeCertID(id, NULL, &derSz, &intSz); + if (ret != 0) { + WOLFSSL_MSG("Failed to calculate CertID size"); + return -1; + } + } + + if (data == NULL) { + return derSz; + } + + if (*data == NULL) { + /* Allocate buffer for DER encoding */ + *data = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_OPENSSL); if (*data == NULL) { - return WOLFSSL_FAILURE; + WOLFSSL_MSG("Failed to allocate memory for CertID DER encoding"); + return -1; } - XMEMCPY(*data, id->rawCertId, (size_t)id->rawCertIdSize); + allocated = 1; } - return id->rawCertIdSize; + if (id->rawCertId != NULL) { + XMEMCPY(*data, id->rawCertId, id->rawCertIdSize); + } + else { + ret = OcspEncodeCertID(id, *data, &derSz, &intSz); + if (ret < 0) { + WOLFSSL_MSG("Failed to encode CertID"); + if (allocated) { + XFREE(*data, NULL, DYNAMIC_TYPE_OPENSSL); + *data = NULL; + } + return -1; + } + } + + if (!allocated) + *data += derSz; + + return derSz; } WOLFSSL_OCSP_CERTID* wolfSSL_d2i_OCSP_CERTID(WOLFSSL_OCSP_CERTID** cidOut, @@ -1258,44 +1422,50 @@ WOLFSSL_OCSP_CERTID* wolfSSL_d2i_OCSP_CERTID(WOLFSSL_OCSP_CERTID** cidOut, int length) { WOLFSSL_OCSP_CERTID *cid = NULL; + int isAllocated = 0; + word32 idx = 0; + int ret; - if ((cidOut != NULL) && (derIn != NULL) && (*derIn != NULL) && - (length > 0)) { + if (derIn == NULL || *derIn == NULL || length <= 0) + return NULL; + if (cidOut != NULL && *cidOut != NULL) { cid = *cidOut; + FreeOcspEntry(cid, NULL); + } + else { + cid = (WOLFSSL_OCSP_CERTID*)XMALLOC(sizeof(WOLFSSL_OCSP_CERTID), NULL, + DYNAMIC_TYPE_OPENSSL); + if (cid == NULL) + return NULL; + isAllocated = 1; + } - /* If a NULL is passed we allocate the memory for the caller. */ - if (cid == NULL) { - cid = (WOLFSSL_OCSP_CERTID*)XMALLOC(sizeof(*cid), NULL, - DYNAMIC_TYPE_OPENSSL); - } - else if (cid->rawCertId != NULL) { - XFREE(cid->rawCertId, NULL, DYNAMIC_TYPE_OPENSSL); - cid->rawCertId = NULL; - cid->rawCertIdSize = 0; - } - - if (cid != NULL) { - cid->rawCertId = (byte*)XMALLOC((size_t)length + 1, NULL, DYNAMIC_TYPE_OPENSSL); - if (cid->rawCertId != NULL) { - XMEMCPY(cid->rawCertId, *derIn, (size_t)length); - cid->rawCertIdSize = length; - - /* Per spec. advance past the data that is being returned - * to the caller. */ - *cidOut = cid; - *derIn = *derIn + length; + XMEMSET(cid, 0, sizeof(WOLFSSL_OCSP_CERTID)); + cid->status = (CertStatus*)XMALLOC(sizeof(CertStatus), NULL, + DYNAMIC_TYPE_OCSP_STATUS); + if (cid->status == NULL) { + XFREE(cid, NULL, DYNAMIC_TYPE_OPENSSL); + return NULL; + } + XMEMSET(cid->status, 0, sizeof(CertStatus)); + cid->ownStatus = 1; - return cid; - } + ret = OcspDecodeCertID(*derIn, &idx, length, cid); + if (ret != 0) { + FreeOcspEntry(cid, NULL); + if (isAllocated) { + XFREE(cid, NULL, DYNAMIC_TYPE_OPENSSL); } + return NULL; } - if ((cid != NULL) && ((cidOut == NULL) || (cid != *cidOut))) { - XFREE(cid, NULL, DYNAMIC_TYPE_OPENSSL); - } + *derIn += idx; - return NULL; + if (isAllocated && cidOut != NULL) + *cidOut = cid; + + return cid; } const WOLFSSL_OCSP_CERTID* wolfSSL_OCSP_SINGLERESP_get0_id( diff --git a/src/src/pk.c b/src/src/pk.c index 6c55bee..3136cf9 100644 --- a/src/src/pk.c +++ b/src/src/pk.c @@ -1,6 +1,6 @@ /* pk.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #include #ifndef WC_NO_RNG @@ -414,7 +410,7 @@ int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, if (ret == 0) { /* Generate a random salt. */ - if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) { + if (wolfSSL_RAND_bytes(info->iv, (int)info->ivSz) != 1) { WOLFSSL_MSG("generate iv failed"); ret = WOLFSSL_FATAL_ERROR; } @@ -422,7 +418,7 @@ int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, if (ret == 0) { /* Calculate padding size - always a padding block. */ - paddingSz = info->ivSz - ((*derSz) % info->ivSz); + paddingSz = (int)info->ivSz - ((*derSz) % (int)info->ivSz); /* Check der is big enough. */ if (maxDerSz < (*derSz) + paddingSz) { WOLFSSL_MSG("not enough DER buffer allocated"); @@ -431,7 +427,7 @@ int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, } if (ret == 0) { /* Set padding bytes to padding length. */ - XMEMSET(der + (*derSz), (byte)paddingSz, paddingSz); + XMEMSET(der + (*derSz), (byte)paddingSz, (size_t)paddingSz); /* Add padding to DER size. */ (*derSz) += (int)paddingSz; @@ -518,8 +514,19 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, byte *tmpBuf; /* Add space for padding. */ + #ifdef WOLFSSL_NO_REALLOC + tmpBuf = (byte*)XMALLOC((size_t)(derSz + blockSz), heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (tmpBuf != NULL && der != NULL) + { + XMEMCPY(tmpBuf, der, (size_t)(derSz)); + XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER); + der = NULL; + } + #else tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif if (tmpBuf == NULL) { WOLFSSL_ERROR_MSG("Extending DER buffer failed"); ret = 0; /* der buffer is free'd at the end of the function */ @@ -724,7 +731,7 @@ static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen, if (indent > 0) { /* Print indent spaces. */ int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " "); - if (len_wanted >= lineLen) { + if ((len_wanted < 0) || (len_wanted >= lineLen)) { WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation"); ret = 0; } @@ -1547,7 +1554,11 @@ static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out) WOLFSSL_ERROR_MSG("Malloc failure"); err = 1; } - if (!err) { + if ((!err) && (derLen <= (int)sizeof(seq))) { + /* Copy the previously read data into the buffer. */ + XMEMCPY(der, seq, derLen); + } + else if (!err) { /* Calculate the unread amount. */ int len = derLen - (int)sizeof(seq); /* Copy the previously read data into the buffer. */ @@ -5630,7 +5641,8 @@ static int dsa_do_verify(const unsigned char* d, int dLen, unsigned char* sig, ret = dLen == WC_SHA_DIGEST_SIZE ? wc_DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck) : BAD_FUNC_ARG; #else - ret = wc_DsaVerify_ex(d, dLen, sig, (DsaKey*)dsa->internal, dsacheck); + ret = wc_DsaVerify_ex(d, (word32)dLen, sig, (DsaKey*)dsa->internal, + dsacheck); #endif if (ret != 0) { WOLFSSL_MSG("DsaVerify failed"); @@ -9475,16 +9487,16 @@ int wolfSSL_i2d_ECPKParameters(const WOLFSSL_EC_GROUP* grp, unsigned char** pp) /* Get the actual DER encoding of the OID. ecc_sets[grp->curve_idx].oid * is just the numerical representation. */ - if (wc_ecc_get_oid(grp->curve_oid, &oid, &oidSz) < 0) + if (wc_ecc_get_oid((word32)grp->curve_oid, &oid, &oidSz) < 0) return WOLFSSL_FATAL_ERROR; - len = SetObjectId(oidSz, NULL) + oidSz; + len = SetObjectId((int)oidSz, NULL) + (int)oidSz; if (pp == NULL) return len; if (*pp == NULL) { - out = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + out = (unsigned char*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); if (out == NULL) return WOLFSSL_FATAL_ERROR; } @@ -9492,7 +9504,7 @@ int wolfSSL_i2d_ECPKParameters(const WOLFSSL_EC_GROUP* grp, unsigned char** pp) out = *pp; } - idx = SetObjectId(oidSz, out); + idx = SetObjectId((int)oidSz, out); XMEMCPY(out + idx, oid, oidSz); if (*pp == NULL) *pp = out; @@ -10273,7 +10285,7 @@ WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const WOLFSSL_EC_GROUP *group, key_sz = (wolfSSL_EC_GROUP_get_degree(group) + 7) / 8; if (hex[0] == '0' && hex[1] == '4') { /* uncompressed mode */ - str_sz = key_sz * 2; + str_sz = (size_t)key_sz * 2; XMEMSET(strGx, 0x0, str_sz + 1); XMEMCPY(strGx, hex + 2, str_sz); @@ -10299,7 +10311,7 @@ WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const WOLFSSL_EC_GROUP *group, if (hex_to_bytes(hex + 2, octGx + 1, sz) != sz) { goto err; } - if (wolfSSL_ECPoint_d2i(octGx, key_sz + 1, group, p) + if (wolfSSL_ECPoint_d2i(octGx, (word32)key_sz + 1, group, p) != WOLFSSL_SUCCESS) { goto err; } @@ -12234,7 +12246,7 @@ int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out) if (ret == 1) { #ifdef HAVE_COMP_KEY /* Default to compressed form if not set */ - form = (key->form != WC_POINT_CONVERSION_UNCOMPRESSED) ? + form = (key->form == WC_POINT_CONVERSION_UNCOMPRESSED) ? WC_POINT_CONVERSION_UNCOMPRESSED : WC_POINT_CONVERSION_COMPRESSED; #endif @@ -12361,7 +12373,7 @@ WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key, * * @param [in] key EC key to encode. * @param [in, out] out On in, reference to buffer to place DER encoding into. - * On out, reference to buffer adter the encoding. + * On out, reference to buffer after the encoding. * May be NULL. * @return Length of DER encoding on success. * @return 0 on error. @@ -14652,6 +14664,13 @@ int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz, res = 0; } if (res) { + #ifdef WOLFSSL_CURVE25519_BLINDING + /* An RNG is needed. */ + if (wc_curve25519_set_rng(&privkey, wolfssl_make_global_rng()) != 0) { + res = 0; + } + else + #endif /* Initialize public key object. */ if (wc_curve25519_init(&pubkey) != MP_OKAY) { WOLFSSL_MSG("wc_curve25519_init pubkey failed"); @@ -15473,7 +15492,7 @@ int wolfSSL_PEM_def_callback(char* buf, int num, int rwFlag, void* userData) if ((buf != NULL) && (userData != NULL)) { sz = (int)XSTRLEN((const char*)userData); sz = (int)min((word32)sz, (word32)num); - XMEMCPY(buf, userData, sz); + XMEMCPY(buf, userData, (size_t)sz); } else { WOLFSSL_MSG("Error, default password cannot be created."); @@ -15967,7 +15986,7 @@ static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix, /* Find prefix part. */ for (; idx < pemLen - prefixLen; idx++) { if ((pem[idx] == prefix[0]) && - (XMEMCMP(pem + idx, prefix, prefixLen) == 0)) { + (XMEMCMP(pem + idx, prefix, (size_t)prefixLen) == 0)) { idx += prefixLen; *start = idx; break; @@ -15976,7 +15995,7 @@ static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix, /* Find postfix part. */ for (; idx < pemLen - postfixLen; idx++) { if ((pem[idx] == postfix[0]) && - (XMEMCMP(pem + idx, postfix, postfixLen) == 0)) { + (XMEMCMP(pem + idx, postfix, (size_t)postfixLen) == 0)) { *len = idx - *start; break; } @@ -16012,7 +16031,7 @@ static int pem_read_data(char* pem, int pemLen, char **name, char **header, /* Find header. */ pem_find_pattern(pem, pemLen, 0, PEM_BEGIN, PEM_HDR_FIN, &start, &nameLen); /* Allocate memory for header name. */ - *name = (char*)XMALLOC(nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + *name = (char*)XMALLOC((size_t)nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (*name == NULL) { ret = MEMORY_E; } @@ -16023,7 +16042,7 @@ static int pem_read_data(char* pem, int pemLen, char **name, char **header, ret = ASN_NO_PEM_HEADER; } else { - XMEMCPY(*name, pem + start, nameLen); + XMEMCPY(*name, pem + start, (size_t)nameLen); } } if (ret == 0) { @@ -16035,7 +16054,8 @@ static int pem_read_data(char* pem, int pemLen, char **name, char **header, hdrLen++; } /* Allocate memory for encryption header string. */ - *header = (char*)XMALLOC(hdrLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER); + *header = (char*)XMALLOC((size_t)hdrLen + 1, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (*header == NULL) { ret = MEMORY_E; } @@ -16044,7 +16064,7 @@ static int pem_read_data(char* pem, int pemLen, char **name, char **header, /* Put in encryption header string. */ (*header)[hdrLen] = '\0'; if (hdrLen > 0) { - XMEMCPY(*header, pem + startHdr, hdrLen); + XMEMCPY(*header, pem + startHdr, (size_t)hdrLen); start = startHdr + hdrLen + 1; } @@ -16053,7 +16073,7 @@ static int pem_read_data(char* pem, int pemLen, char **name, char **header, &endLen); /* Validate header name and footer name are the same. */ if ((endLen != nameLen) || - (XMEMCMP(*name, pem + startEnd, nameLen) != 0)) { + (XMEMCMP(*name, pem + startEnd, (size_t)nameLen) != 0)) { ret = ASN_NO_PEM_HEADER; } } @@ -16103,13 +16123,13 @@ static int pem_write_data(const char *name, const char *header, pemLen = (derLen + 2) / 3 * 4; pemLen += (pemLen + 63) / 64; /* Header */ - pemLen += PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ; + pemLen += (word32)(PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ); if (headerLen > 0) { /* Encryption lines plus extra carriage return. */ - pemLen += headerLen + 1; + pemLen += (word32)headerLen + 1; } /* Trailer */ - pemLen += PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ; + pemLen += (word32)(PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ); pem = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (pem == NULL) { @@ -16121,14 +16141,14 @@ static int pem_write_data(const char *name, const char *header, /* Add header. */ XMEMCPY(p, PEM_BEGIN, PEM_BEGIN_SZ); p += PEM_BEGIN_SZ; - XMEMCPY(p, name, nameLen); + XMEMCPY(p, name, (size_t)nameLen); p += nameLen; XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ); p += PEM_HDR_FIN_EOL_SZ; if (headerLen > 0) { /* Add encryption header. */ - XMEMCPY(p, header, headerLen); + XMEMCPY(p, header, (size_t)headerLen); p += headerLen; /* Blank line after a header and before body. */ *(p++) = '\n'; @@ -16144,7 +16164,7 @@ static int pem_write_data(const char *name, const char *header, /* Add trailer. */ XMEMCPY(p, PEM_END, PEM_END_SZ); p += PEM_END_SZ; - XMEMCPY(p, name, nameLen); + XMEMCPY(p, name, (size_t)nameLen); p += nameLen; XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ); p += PEM_HDR_FIN_EOL_SZ; @@ -16153,6 +16173,11 @@ static int pem_write_data(const char *name, const char *header, *pemOut = pem; *pemOutLen = (word32)((size_t)p - (size_t)pem); } + else { + /* Dispose of any allocated memory. */ + XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); + pem = NULL; + } return ret; } @@ -16192,13 +16217,13 @@ int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header, } if ((res == 1) && (!memAlloced)) { /* Need to return allocated memory - make sure it is allocated. */ - char* p = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + char* p = (char*)XMALLOC((size_t)pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (p == NULL) { res = 0; } else { /* Copy the data into new buffer. */ - XMEMCPY(p, pem, pemLen); + XMEMCPY(p, pem, (size_t)pemLen); pem = p; } } @@ -16250,7 +16275,7 @@ int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name, } XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER); - return (!err) ? pemLen : 0; + return (!err) ? (int)pemLen : 0; } #endif /* !NO_BIO */ @@ -16475,7 +16500,8 @@ int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey, if (ret == 0) { /* Encrypt private into buffer. */ - ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz, + ret = TraditionalEnc((byte*)pkey->pkey.ptr + pkey->pkcs8HeaderSz, + (word32)pkey->pkey_sz - pkey->pkcs8HeaderSz, key, keySz, passwd, passwdSz, PKCS5, PBES2, encAlgId, NULL, 0, WC_PKCS12_ITT_DEFAULT, &rng, NULL); if (ret > 0) { @@ -16509,7 +16535,7 @@ int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) if (pkey->type == WC_EVP_PKEY_EC) { /* ECC private and get curve OID information. */ algId = ECDSAk; - ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid, + ret = wc_ecc_get_oid((word32)pkey->ecc->group->curve_oid, &curveOid, &oidSz); } else @@ -16536,7 +16562,7 @@ int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) if (keySz == NULL) return BAD_FUNC_ARG; - *keySz = pkey->pkey_sz; + *keySz = (word32)pkey->pkey_sz; if (key == NULL) return LENGTH_ONLY_E; @@ -16556,8 +16582,9 @@ int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz) if (ret >= 0) { /* Encode private key in PKCS#8 format. */ - ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr, - pkey->pkey_sz, algId, curveOid, oidSz); + ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr + + pkey->pkcs8HeaderSz, (word32)pkey->pkey_sz - pkey->pkcs8HeaderSz, + algId, curveOid, oidSz); } return ret; diff --git a/src/src/quic.c b/src/src/quic.c index 64cf14f..5791a7d 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -1,6 +1,6 @@ /* quic.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* Name change compatibility layer no longer needs to be included here */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #ifdef NO_INLINE #include #else @@ -154,17 +150,15 @@ static int quic_record_append(WOLFSSL *ssl, QuicRecord *qr, const uint8_t *data, } } - if (quic_record_complete(qr) || len == 0) { - return 0; - } - - missing = qr->len - qr->end; - if (len > missing) { - len = missing; + if (!quic_record_complete(qr) && len != 0) { + missing = qr->len - qr->end; + if (len > missing) { + len = missing; + } + XMEMCPY(qr->data + qr->end, data, len); + qr->end += (word32)len; + consumed += len; } - XMEMCPY(qr->data + qr->end, data, len); - qr->end += (word32)len; - consumed += len; cleanup: *pconsumed = (ret == WOLFSSL_SUCCESS) ? consumed : 0; @@ -927,8 +921,12 @@ int wolfSSL_quic_forward_secrets(WOLFSSL* ssl, int ktype, int side) goto cleanup; } - ret = !ssl->quic.method->set_encryption_secrets( - ssl, level, rx_secret, tx_secret, ssl->specs.hash_size); + if(!ssl->quic.method->set_encryption_secrets( + ssl, level, rx_secret, tx_secret, ssl->specs.hash_size)) { + WOLFSSL_MSG("WOLFSSL_QUIC_FORWARD_SECRETS failed"); + ret = WOLFSSL_FATAL_ERROR; + goto cleanup; + } /* Having installed the secrets, any future read/write will happen * at the level. Except early data, which is detected on the record diff --git a/src/src/sniffer.c b/src/src/sniffer.c index a3814a4..4d0c8e1 100644 --- a/src/src/sniffer.c +++ b/src/src/sniffer.c @@ -1,6 +1,6 @@ /* sniffer.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #ifdef WOLFSSL_ASYNC_CRYPT #include diff --git a/src/src/ssl.c b/src/src/ssl.c index c38fcbf..0b74065 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -1,6 +1,6 @@ /* ssl.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XISASCII */ #define _GNU_SOURCE 1 @@ -202,79 +198,20 @@ * * For OpenSSL compatibility. * - * This function shouldn't exist! - * Uses defines in wolfssl/openssl/evp.h. - * Uses EccEnumToNID which uses defines in wolfssl/openssl/ec.h. - * * @param [in] sn Short name of OID. * @return NID corresponding to shortname on success. * @return WC_NID_undef when not recognized. */ int wc_OBJ_sn2nid(const char *sn) { - const struct { - const char *sn; - int nid; - } sn2nid[] = { -#ifndef NO_CERTS - {WOLFSSL_COMMON_NAME, WC_NID_commonName}, - {WOLFSSL_COUNTRY_NAME, WC_NID_countryName}, - {WOLFSSL_LOCALITY_NAME, WC_NID_localityName}, - {WOLFSSL_STATE_NAME, WC_NID_stateOrProvinceName}, - {WOLFSSL_ORG_NAME, WC_NID_organizationName}, - {WOLFSSL_ORGUNIT_NAME, WC_NID_organizationalUnitName}, - #ifdef WOLFSSL_CERT_NAME_ALL - {WOLFSSL_NAME, WC_NID_name}, - {WOLFSSL_INITIALS, WC_NID_initials}, - {WOLFSSL_GIVEN_NAME, WC_NID_givenName}, - {WOLFSSL_DNQUALIFIER, WC_NID_dnQualifier}, - #endif - {WOLFSSL_EMAIL_ADDR, WC_NID_emailAddress}, -#endif - {"SHA1", WC_NID_sha1}, - {NULL, -1}}; - int i; -#ifdef HAVE_ECC - char curveName[ECC_MAXNAME + 1]; - int eccEnum; -#endif - + const WOLFSSL_ObjectInfo *obj_info = wolfssl_object_info; + size_t i; WOLFSSL_ENTER("wc_OBJ_sn2nid"); - - for(i=0; sn2nid[i].sn != NULL; i++) { - if (XSTRCMP(sn, sn2nid[i].sn) == 0) { - return sn2nid[i].nid; - } + for (i = 0; i < wolfssl_object_info_sz; i++, obj_info++) { + if (XSTRCMP(sn, obj_info->sName) == 0) + return obj_info->nid; } - -#ifdef HAVE_ECC - if (XSTRLEN(sn) > ECC_MAXNAME) - return WC_NID_undef; - - /* Nginx uses this OpenSSL string. */ - if (XSTRCMP(sn, "prime256v1") == 0) - sn = "SECP256R1"; - /* OpenSSL allows lowercase curve names */ - for (i = 0; i < (int)(sizeof(curveName) - 1) && *sn; i++) { - curveName[i] = (char)XTOUPPER((unsigned char) *sn++); - } - curveName[i] = '\0'; - /* find based on name and return NID */ - for (i = 0; -#ifndef WOLFSSL_ECC_CURVE_STATIC - ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; -#else - ecc_sets[i].size != 0; -#endif - i++) { - if (XSTRCMP(curveName, ecc_sets[i].name) == 0) { - eccEnum = ecc_sets[i].id; - /* Convert enum value in ecc_curve_id to OpenSSL NID */ - return EccEnumToNID(eccEnum); - } - } -#endif /* HAVE_ECC */ - + WOLFSSL_MSG("short name not found in table"); return WC_NID_undef; } #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ @@ -423,6 +360,8 @@ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, { int ret = 0; word16 encLen = DHKEM_X25519_ENC_LEN; + WOLFSSL_EchConfig* newConfig; + WOLFSSL_EchConfig* parentConfig; #ifdef WOLFSSL_SMALL_STACK Hpke* hpke = NULL; WC_RNG* rng; @@ -447,16 +386,16 @@ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, return ret; } - ctx->echConfigs = (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), + newConfig = (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ctx->echConfigs == NULL) + if (newConfig == NULL) ret = MEMORY_E; else - XMEMSET(ctx->echConfigs, 0, sizeof(WOLFSSL_EchConfig)); + XMEMSET(newConfig, 0, sizeof(WOLFSSL_EchConfig)); /* set random config id */ if (ret == 0) - ret = wc_RNG_GenerateByte(rng, &ctx->echConfigs->configId); + ret = wc_RNG_GenerateByte(rng, &newConfig->configId); /* if 0 is selected for algorithms use default, may change with draft */ if (kemId == 0) @@ -470,19 +409,20 @@ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, if (ret == 0) { /* set the kem id */ - ctx->echConfigs->kemId = kemId; + newConfig->kemId = kemId; /* set the cipher suite, only 1 for now */ - ctx->echConfigs->numCipherSuites = 1; - ctx->echConfigs->cipherSuites = (EchCipherSuite*)XMALLOC( - sizeof(EchCipherSuite), ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + newConfig->numCipherSuites = 1; + newConfig->cipherSuites = + (EchCipherSuite*)XMALLOC(sizeof(EchCipherSuite), ctx->heap, + DYNAMIC_TYPE_TMP_BUFFER); - if (ctx->echConfigs->cipherSuites == NULL) { + if (newConfig->cipherSuites == NULL) { ret = MEMORY_E; } else { - ctx->echConfigs->cipherSuites[0].kdfId = kdfId; - ctx->echConfigs->cipherSuites[0].aeadId = aeadId; + newConfig->cipherSuites[0].kdfId = kdfId; + newConfig->cipherSuites[0].aeadId = aeadId; } } @@ -499,38 +439,47 @@ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, /* generate the receiver private key */ if (ret == 0) - ret = wc_HpkeGenerateKeyPair(hpke, &ctx->echConfigs->receiverPrivkey, - rng); + ret = wc_HpkeGenerateKeyPair(hpke, &newConfig->receiverPrivkey, rng); /* done with RNG */ wc_FreeRng(rng); /* serialize the receiver key */ if (ret == 0) - ret = wc_HpkeSerializePublicKey(hpke, ctx->echConfigs->receiverPrivkey, - ctx->echConfigs->receiverPubkey, &encLen); + ret = wc_HpkeSerializePublicKey(hpke, newConfig->receiverPrivkey, + newConfig->receiverPubkey, &encLen); if (ret == 0) { - ctx->echConfigs->publicName = (char*)XMALLOC(XSTRLEN(publicName) + 1, + newConfig->publicName = (char*)XMALLOC(XSTRLEN(publicName) + 1, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ctx->echConfigs->publicName == NULL) { + if (newConfig->publicName == NULL) { ret = MEMORY_E; } else { - XMEMCPY(ctx->echConfigs->publicName, publicName, + XMEMCPY(newConfig->publicName, publicName, XSTRLEN(publicName) + 1); } } if (ret != 0) { - if (ctx->echConfigs) { - XFREE(ctx->echConfigs->cipherSuites, ctx->heap, - DYNAMIC_TYPE_TMP_BUFFER); - XFREE(ctx->echConfigs->publicName, ctx->heap, - DYNAMIC_TYPE_TMP_BUFFER); - XFREE(ctx->echConfigs, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); - /* set to null to avoid double free in cleanup */ - ctx->echConfigs = NULL; + if (newConfig) { + XFREE(newConfig->cipherSuites, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(newConfig->publicName, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(newConfig, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + } + else { + parentConfig = ctx->echConfigs; + + if (parentConfig == NULL) { + ctx->echConfigs = newConfig; + } + else { + while (parentConfig->next != NULL) { + parentConfig = parentConfig->next; + } + + parentConfig->next = newConfig; } } @@ -545,6 +494,59 @@ int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, return ret; } +int wolfSSL_CTX_SetEchConfigsBase64(WOLFSSL_CTX* ctx, const char* echConfigs64, + word32 echConfigs64Len) +{ + int ret = 0; + word32 decodedLen = echConfigs64Len * 3 / 4 + 1; + byte* decodedConfigs; + + if (ctx == NULL || echConfigs64 == NULL || echConfigs64Len == 0) + return BAD_FUNC_ARG; + + decodedConfigs = (byte*)XMALLOC(decodedLen, ctx->heap, + DYNAMIC_TYPE_TMP_BUFFER); + + if (decodedConfigs == NULL) + return MEMORY_E; + + decodedConfigs[decodedLen - 1] = 0; + + /* decode the echConfigs */ + ret = Base64_Decode((const byte*)echConfigs64, echConfigs64Len, + decodedConfigs, &decodedLen); + + if (ret != 0) { + XFREE(decodedConfigs, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + return ret; + } + + ret = wolfSSL_CTX_SetEchConfigs(ctx, decodedConfigs, decodedLen); + + XFREE(decodedConfigs, ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} + +int wolfSSL_CTX_SetEchConfigs(WOLFSSL_CTX* ctx, const byte* echConfigs, + word32 echConfigsLen) +{ + int ret; + + if (ctx == NULL || echConfigs == NULL || echConfigsLen == 0) + return BAD_FUNC_ARG; + + FreeEchConfigs(ctx->echConfigs, ctx->heap); + ctx->echConfigs = NULL; + ret = SetEchConfigsEx(&ctx->echConfigs, ctx->heap, echConfigs, + echConfigsLen); + + if (ret == 0) + return WOLFSSL_SUCCESS; + + return ret; +} + /* get the ech configs that the server context is using */ int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output, word32* outputLen) { @@ -552,9 +554,8 @@ int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output, return BAD_FUNC_ARG; /* if we don't have ech configs */ - if (ctx->echConfigs == NULL) { + if (ctx->echConfigs == NULL) return WOLFSSL_FATAL_ERROR; - } return GetEchConfigsEx(ctx->echConfigs, output, outputLen); } @@ -615,7 +616,202 @@ int wolfSSL_SetEchConfigsBase64(WOLFSSL* ssl, char* echConfigs64, /* set the ech config from a raw buffer, this is the format ech configs are * sent using retry_configs from the ech server */ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, - word32 echConfigsLen) + word32 echConfigsLen) +{ + int ret; + + if (ssl == NULL || echConfigs == NULL || echConfigsLen == 0) + return BAD_FUNC_ARG; + + /* already have ech configs */ + if (ssl->options.useEch == 1) { + return WOLFSSL_FATAL_ERROR; + } + + ret = SetEchConfigsEx(&ssl->echConfigs, ssl->heap, echConfigs, + echConfigsLen); + + /* if we found valid configs */ + if (ret == 0) { + ssl->options.useEch = 1; + return WOLFSSL_SUCCESS; + } + + return ret; +} + +/* get the raw ech config from our struct */ +int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, word32* outputLen) +{ + int i; + word16 totalLen = 0; + + if (config == NULL || (output == NULL && outputLen == NULL)) + return BAD_FUNC_ARG; + + /* 2 for version */ + totalLen += 2; + /* 2 for length */ + totalLen += 2; + /* 1 for configId */ + totalLen += 1; + /* 2 for kemId */ + totalLen += 2; + /* 2 for hpke_len */ + totalLen += 2; + + /* hpke_pub_key */ + switch (config->kemId) { + case DHKEM_P256_HKDF_SHA256: + totalLen += DHKEM_P256_ENC_LEN; + break; + case DHKEM_P384_HKDF_SHA384: + totalLen += DHKEM_P384_ENC_LEN; + break; + case DHKEM_P521_HKDF_SHA512: + totalLen += DHKEM_P521_ENC_LEN; + break; + case DHKEM_X25519_HKDF_SHA256: + totalLen += DHKEM_X25519_ENC_LEN; + break; + case DHKEM_X448_HKDF_SHA512: + totalLen += DHKEM_X448_ENC_LEN; + break; + } + + /* cipherSuitesLen */ + totalLen += 2; + /* cipherSuites */ + totalLen += config->numCipherSuites * 4; + /* public name len */ + totalLen += 2; + + /* public name */ + totalLen += XSTRLEN(config->publicName); + /* trailing zeros */ + totalLen += 2; + + if (output == NULL) { + *outputLen = totalLen; + return WC_NO_ERR_TRACE(LENGTH_ONLY_E); + } + + if (totalLen > *outputLen) { + *outputLen = totalLen; + return INPUT_SIZE_E; + } + + /* version */ + c16toa(TLSX_ECH, output); + output += 2; + + /* length - 4 for version and length itself */ + c16toa(totalLen - 4, output); + output += 2; + + /* configId */ + *output = config->configId; + output++; + /* kemId */ + c16toa(config->kemId, output); + output += 2; + + /* length and key itself */ + switch (config->kemId) { + case DHKEM_P256_HKDF_SHA256: + c16toa(DHKEM_P256_ENC_LEN, output); + output += 2; + XMEMCPY(output, config->receiverPubkey, DHKEM_P256_ENC_LEN); + output += DHKEM_P256_ENC_LEN; + break; + case DHKEM_P384_HKDF_SHA384: + c16toa(DHKEM_P384_ENC_LEN, output); + output += 2; + XMEMCPY(output, config->receiverPubkey, DHKEM_P384_ENC_LEN); + output += DHKEM_P384_ENC_LEN; + break; + case DHKEM_P521_HKDF_SHA512: + c16toa(DHKEM_P521_ENC_LEN, output); + output += 2; + XMEMCPY(output, config->receiverPubkey, DHKEM_P521_ENC_LEN); + output += DHKEM_P521_ENC_LEN; + break; + case DHKEM_X25519_HKDF_SHA256: + c16toa(DHKEM_X25519_ENC_LEN, output); + output += 2; + XMEMCPY(output, config->receiverPubkey, DHKEM_X25519_ENC_LEN); + output += DHKEM_X25519_ENC_LEN; + break; + case DHKEM_X448_HKDF_SHA512: + c16toa(DHKEM_X448_ENC_LEN, output); + output += 2; + XMEMCPY(output, config->receiverPubkey, DHKEM_X448_ENC_LEN); + output += DHKEM_X448_ENC_LEN; + break; + } + + /* cipherSuites len */ + c16toa(config->numCipherSuites * 4, output); + output += 2; + + /* cipherSuites */ + for (i = 0; i < config->numCipherSuites; i++) { + c16toa(config->cipherSuites[i].kdfId, output); + output += 2; + c16toa(config->cipherSuites[i].aeadId, output); + output += 2; + } + + /* set maximum name length to 0 */ + *output = 0; + output++; + + /* publicName len */ + *output = XSTRLEN(config->publicName); + output++; + + /* publicName */ + XMEMCPY(output, config->publicName, + XSTRLEN(config->publicName)); + output += XSTRLEN(config->publicName); + + /* terminating zeros */ + c16toa(0, output); + /* output += 2; */ + + *outputLen = totalLen; + + return 0; +} + +/* wrapper function to get ech configs from application code */ +int wolfSSL_GetEchConfigs(WOLFSSL* ssl, byte* output, word32* outputLen) +{ + if (ssl == NULL || outputLen == NULL) + return BAD_FUNC_ARG; + + /* if we don't have ech configs */ + if (ssl->options.useEch != 1) { + return WOLFSSL_FATAL_ERROR; + } + + return GetEchConfigsEx(ssl->echConfigs, output, outputLen); +} + +void wolfSSL_SetEchEnable(WOLFSSL* ssl, byte enable) +{ + if (ssl != NULL) { + ssl->options.disableECH = !enable; + if (ssl->options.disableECH) { + TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap); + FreeEchConfigs(ssl->echConfigs, ssl->heap); + ssl->echConfigs = NULL; + } + } +} + +int SetEchConfigsEx(WOLFSSL_EchConfig** outputConfigs, void* heap, + const byte* echConfigs, word32 echConfigsLen) { int ret = 0; int i; @@ -631,14 +827,9 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, WOLFSSL_EchConfig* lastConfig = NULL; byte* echConfig = NULL; - if (ssl == NULL || echConfigs == NULL || echConfigsLen == 0) + if (outputConfigs == NULL || echConfigs == NULL || echConfigsLen == 0) return BAD_FUNC_ARG; - /* already have ech configs */ - if (ssl->options.useEch == 1) { - return WOLFSSL_FATAL_ERROR; - } - /* check that the total length is well formed */ ato16(echConfigs, &totalLength); @@ -673,8 +864,8 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, if (workingConfig == NULL) { workingConfig = - (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), - ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), heap, + DYNAMIC_TYPE_TMP_BUFFER); configList = workingConfig; if (workingConfig != NULL) { workingConfig->next = NULL; @@ -684,7 +875,7 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, lastConfig = workingConfig; workingConfig->next = (WOLFSSL_EchConfig*)XMALLOC(sizeof(WOLFSSL_EchConfig), - ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + heap, DYNAMIC_TYPE_TMP_BUFFER); workingConfig = workingConfig->next; } @@ -700,7 +891,7 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, /* raw body */ workingConfig->raw = (byte*)XMALLOC(workingConfig->rawLen, - ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + heap, DYNAMIC_TYPE_TMP_BUFFER); if (workingConfig->raw == NULL) { ret = MEMORY_E; break; @@ -727,7 +918,7 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, ato16(echConfig, &cipherSuitesLen); workingConfig->cipherSuites = (EchCipherSuite*)XMALLOC(cipherSuitesLen, - ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + heap, DYNAMIC_TYPE_TMP_BUFFER); if (workingConfig->cipherSuites == NULL) { ret = MEMORY_E; break; @@ -742,16 +933,17 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, &workingConfig->cipherSuites[j].aeadId); } echConfig += cipherSuitesLen; + /* ignore the maximum name length */ + echConfig++; /* publicNameLen */ - ato16(echConfig, &publicNameLen); + publicNameLen = *(echConfig); workingConfig->publicName = (char*)XMALLOC(publicNameLen + 1, - ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + heap, DYNAMIC_TYPE_TMP_BUFFER); if (workingConfig->publicName == NULL) { ret = MEMORY_E; break; } - - echConfig += 2; + echConfig++; /* publicName */ XMEMCPY(workingConfig->publicName, echConfig, publicNameLen); /* null terminated */ @@ -770,206 +962,39 @@ int wolfSSL_SetEchConfigs(WOLFSSL* ssl, const byte* echConfigs, if (j >= HPKE_SUPPORTED_KEM_LEN || EchConfigGetSupportedCipherSuite(workingConfig) < 0) { - XFREE(workingConfig->cipherSuites, ssl->heap, + XFREE(workingConfig->cipherSuites, heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(workingConfig->publicName, ssl->heap, + XFREE(workingConfig->publicName, heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(workingConfig->raw, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(workingConfig->raw, heap, DYNAMIC_TYPE_TMP_BUFFER); workingConfig = lastConfig; } } while ((word32)i < echConfigsLen); - /* if we found valid configs */ - if (ret == 0 && configList != NULL) { - ssl->options.useEch = 1; - ssl->echConfigs = configList; - - return WOLFSSL_SUCCESS; - } - - workingConfig = configList; - - while (workingConfig != NULL) { - lastConfig = workingConfig; - workingConfig = workingConfig->next; - - XFREE(lastConfig->cipherSuites, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(lastConfig->publicName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(lastConfig->raw, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - - XFREE(lastConfig, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - - if (ret == 0) - return WOLFSSL_FATAL_ERROR; - - return ret; -} - -/* get the raw ech config from our struct */ -int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, word32* outputLen) -{ - int i; - word16 totalLen = 0; - - if (config == NULL || (output == NULL && outputLen == NULL)) - return BAD_FUNC_ARG; - - /* 2 for version */ - totalLen += 2; - /* 2 for length */ - totalLen += 2; - /* 1 for configId */ - totalLen += 1; - /* 2 for kemId */ - totalLen += 2; - /* 2 for hpke_len */ - totalLen += 2; - - /* hpke_pub_key */ - switch (config->kemId) { - case DHKEM_P256_HKDF_SHA256: - totalLen += DHKEM_P256_ENC_LEN; - break; - case DHKEM_P384_HKDF_SHA384: - totalLen += DHKEM_P384_ENC_LEN; - break; - case DHKEM_P521_HKDF_SHA512: - totalLen += DHKEM_P521_ENC_LEN; - break; - case DHKEM_X25519_HKDF_SHA256: - totalLen += DHKEM_X25519_ENC_LEN; - break; - case DHKEM_X448_HKDF_SHA512: - totalLen += DHKEM_X448_ENC_LEN; - break; - } - - /* cipherSuitesLen */ - totalLen += 2; - /* cipherSuites */ - totalLen += config->numCipherSuites * 4; - /* public name len */ - totalLen += 2; - - /* public name */ - totalLen += XSTRLEN(config->publicName); - /* trailing zeros */ - totalLen += 2; - - if (output == NULL) { - *outputLen = totalLen; - return WC_NO_ERR_TRACE(LENGTH_ONLY_E); - } - - if (totalLen > *outputLen) { - *outputLen = totalLen; - return INPUT_SIZE_E; - } - - /* version */ - c16toa(TLSX_ECH, output); - output += 2; - - /* length - 4 for version and length itself */ - c16toa(totalLen - 4, output); - output += 2; - - /* configId */ - *output = config->configId; - output++; - /* kemId */ - c16toa(config->kemId, output); - output += 2; - - /* length and key itself */ - switch (config->kemId) { - case DHKEM_P256_HKDF_SHA256: - c16toa(DHKEM_P256_ENC_LEN, output); - output += 2; - XMEMCPY(output, config->receiverPubkey, DHKEM_P256_ENC_LEN); - output += DHKEM_P256_ENC_LEN; - break; - case DHKEM_P384_HKDF_SHA384: - c16toa(DHKEM_P384_ENC_LEN, output); - output += 2; - XMEMCPY(output, config->receiverPubkey, DHKEM_P384_ENC_LEN); - output += DHKEM_P384_ENC_LEN; - break; - case DHKEM_P521_HKDF_SHA512: - c16toa(DHKEM_P521_ENC_LEN, output); - output += 2; - XMEMCPY(output, config->receiverPubkey, DHKEM_P521_ENC_LEN); - output += DHKEM_P521_ENC_LEN; - break; - case DHKEM_X25519_HKDF_SHA256: - c16toa(DHKEM_X25519_ENC_LEN, output); - output += 2; - XMEMCPY(output, config->receiverPubkey, DHKEM_X25519_ENC_LEN); - output += DHKEM_X25519_ENC_LEN; - break; - case DHKEM_X448_HKDF_SHA512: - c16toa(DHKEM_X448_ENC_LEN, output); - output += 2; - XMEMCPY(output, config->receiverPubkey, DHKEM_X448_ENC_LEN); - output += DHKEM_X448_ENC_LEN; - break; - } - - /* cipherSuites len */ - c16toa(config->numCipherSuites * 4, output); - output += 2; - - /* cipherSuites */ - for (i = 0; i < config->numCipherSuites; i++) { - c16toa(config->cipherSuites[i].kdfId, output); - output += 2; - c16toa(config->cipherSuites[i].aeadId, output); - output += 2; - } - - /* publicName len */ - c16toa(XSTRLEN(config->publicName), output); - output += 2; - - /* publicName */ - XMEMCPY(output, config->publicName, - XSTRLEN(config->publicName)); - output += XSTRLEN(config->publicName); + /* if we found valid configs */ + if (ret == 0 && configList != NULL) { + *outputConfigs = configList; - /* terminating zeros */ - c16toa(0, output); - /* output += 2; */ + return ret; + } - *outputLen = totalLen; + workingConfig = configList; - return 0; -} + while (workingConfig != NULL) { + lastConfig = workingConfig; + workingConfig = workingConfig->next; -/* wrapper function to get ech configs from application code */ -int wolfSSL_GetEchConfigs(WOLFSSL* ssl, byte* output, word32* outputLen) -{ - if (ssl == NULL || outputLen == NULL) - return BAD_FUNC_ARG; + XFREE(lastConfig->cipherSuites, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(lastConfig->publicName, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(lastConfig->raw, heap, DYNAMIC_TYPE_TMP_BUFFER); - /* if we don't have ech configs */ - if (ssl->options.useEch != 1) { - return WOLFSSL_FATAL_ERROR; + XFREE(lastConfig, heap, DYNAMIC_TYPE_TMP_BUFFER); } - return GetEchConfigsEx(ssl->echConfigs, output, outputLen); -} + if (ret == 0) + return WOLFSSL_FATAL_ERROR; -void wolfSSL_SetEchEnable(WOLFSSL* ssl, byte enable) -{ - if (ssl != NULL) { - ssl->options.disableECH = !enable; - if (ssl->options.disableECH) { - TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap); - FreeEchConfigs(ssl->echConfigs, ssl->heap); - ssl->echConfigs = NULL; - } - } + return ret; } /* get the raw ech configs from our linked list of ech config structs */ @@ -981,7 +1006,7 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) word32 totalLen = 2; word32 workingOutputLen; - if (configs == NULL || outputLen == NULL) + if (configs == NULL || outputLen == NULL || *outputLen < totalLen) return BAD_FUNC_ARG; workingOutputLen = *outputLen - totalLen; @@ -1194,16 +1219,6 @@ void wolfSSL_CTX_free(WOLFSSL_CTX* ctx) { WOLFSSL_ENTER("wolfSSL_CTX_free"); if (ctx) { -#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \ -&& !defined(NO_SHA256) && !defined(WC_NO_RNG) - if (ctx->srp != NULL) { - XFREE(ctx->srp_password, ctx->heap, DYNAMIC_TYPE_SRP); - ctx->srp_password = NULL; - wc_SrpTerm(ctx->srp); - XFREE(ctx->srp, ctx->heap, DYNAMIC_TYPE_SRP); - ctx->srp = NULL; - } -#endif FreeSSL_Ctx(ctx); } @@ -1689,7 +1704,7 @@ int wolfSSL_get_ciphers(char* buf, int len) for (i = 0; i < ciphersSz; i++) { int cipherNameSz = (int)XSTRLEN(ciphers[i].name); if (cipherNameSz + 1 < len) { - XSTRNCPY(buf, ciphers[i].name, len); + XSTRNCPY(buf, ciphers[i].name, (size_t)len); buf += cipherNameSz; if (i < ciphersSz - 1) @@ -1726,7 +1741,7 @@ int wolfSSL_get_ciphers_iana(char* buf, int len) #endif cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana); if (cipherNameSz + 1 < len) { - XSTRNCPY(buf, ciphers[i].name_iana, len); + XSTRNCPY(buf, ciphers[i].name_iana, (size_t)len); buf += cipherNameSz; if (i < ciphersSz - 1) @@ -1752,7 +1767,7 @@ const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len) cipher = wolfSSL_get_cipher_name_iana(ssl); len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1)); - XMEMCPY(buf, cipher, len); + XMEMCPY(buf, cipher, (size_t)len); return buf; } @@ -2124,14 +2139,17 @@ int wolfSSL_dtls_set_mtu(WOLFSSL* ssl, word16 newMtu) return WOLFSSL_SUCCESS; } -#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) -int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu) { - if (wolfSSL_dtls_set_mtu(ssl, mtu) == 0) +#ifdef OPENSSL_EXTRA +/* Maps to compatibility API SSL_set_mtu and is same as wolfSSL_dtls_set_mtu, + * but expects only success or failure returns. */ +int wolfSSL_set_mtu_compat(WOLFSSL* ssl, unsigned short mtu) +{ + if (wolfSSL_dtls_set_mtu(ssl, mtu) == WOLFSSL_SUCCESS) return WOLFSSL_SUCCESS; else return WOLFSSL_FAILURE; } -#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ +#endif /* OPENSSL_EXTRA */ #endif /* WOLFSSL_DTLS && (WOLFSSL_SCTP || WOLFSSL_DTLS_MTU) */ @@ -2218,6 +2236,15 @@ static int DtlsSrtpSelProfiles(word16* id, const char* profile_str) return WOLFSSL_SUCCESS; } +/** + * @brief Set the SRTP protection profiles for DTLS. + * + * @param ctx Pointer to the WOLFSSL_CTX structure representing the SSL/TLS + * context. + * @param profile_str A colon-separated string of SRTP profile names. + * @return 0 on success to match OpenSSL + * @return 1 on error to match OpenSSL + */ int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); @@ -2233,6 +2260,16 @@ int wolfSSL_CTX_set_tlsext_use_srtp(WOLFSSL_CTX* ctx, const char* profile_str) return ret; } + +/** + * @brief Set the SRTP protection profiles for DTLS. + * + * @param ssl Pointer to the WOLFSSL structure representing the SSL/TLS + * session. + * @param profile_str A colon-separated string of SRTP profile names. + * @return 0 on success to match OpenSSL + * @return 1 on error to match OpenSSL + */ int wolfSSL_set_tlsext_use_srtp(WOLFSSL* ssl, const char* profile_str) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); @@ -2294,7 +2331,7 @@ int wolfSSL_export_dtls_srtp_keying_material(WOLFSSL* ssl, return BUFFER_E; } - return wolfSSL_export_keying_material(ssl, out, profile->kdfBits, + return wolfSSL_export_keying_material(ssl, out, (size_t)profile->kdfBits, DTLS_SRTP_KEYING_MATERIAL_LABEL, XSTR_SIZEOF(DTLS_SRTP_KEYING_MATERIAL_LABEL), NULL, 0, 0); } @@ -2845,23 +2882,32 @@ int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz) #ifdef HAVE_ECC int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz) { + short keySzBytes; + WOLFSSL_ENTER("wolfSSL_CTX_SetMinEccKey_Sz"); - if (ctx == NULL || keySz < 0 || keySz % 8 != 0) { - WOLFSSL_MSG("Key size must be divisible by 8 or ctx was null"); + if (ctx == NULL || keySz < 0) { + WOLFSSL_MSG("Key size must be positive value or ctx was null"); return BAD_FUNC_ARG; } + if (keySz % 8 == 0) { + keySzBytes = keySz / 8; + } + else { + keySzBytes = (keySz / 8) + 1; + } + #if defined(WOLFSSL_SYS_CRYPTO_POLICY) if (crypto_policy.enabled) { - if (ctx->minEccKeySz > (keySz / 8)) { + if (ctx->minEccKeySz > (keySzBytes)) { return CRYPTO_POLICY_FORBIDDEN; } } #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ - ctx->minEccKeySz = keySz / 8; + ctx->minEccKeySz = keySzBytes; #ifndef NO_CERTS - ctx->cm->minEccKeySz = keySz / 8; + ctx->cm->minEccKeySz = keySzBytes; #endif return WOLFSSL_SUCCESS; } @@ -2869,21 +2915,30 @@ int wolfSSL_CTX_SetMinEccKey_Sz(WOLFSSL_CTX* ctx, short keySz) int wolfSSL_SetMinEccKey_Sz(WOLFSSL* ssl, short keySz) { + short keySzBytes; + WOLFSSL_ENTER("wolfSSL_SetMinEccKey_Sz"); - if (ssl == NULL || keySz < 0 || keySz % 8 != 0) { - WOLFSSL_MSG("Key size must be divisible by 8 or ssl was null"); + if (ssl == NULL || keySz < 0) { + WOLFSSL_MSG("Key size must be positive value or ctx was null"); return BAD_FUNC_ARG; } + if (keySz % 8 == 0) { + keySzBytes = keySz / 8; + } + else { + keySzBytes = (keySz / 8) + 1; + } + #if defined(WOLFSSL_SYS_CRYPTO_POLICY) if (crypto_policy.enabled) { - if (ssl->options.minEccKeySz > (keySz / 8)) { + if (ssl->options.minEccKeySz > (keySzBytes)) { return CRYPTO_POLICY_FORBIDDEN; } } #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ - ssl->options.minEccKeySz = keySz / 8; + ssl->options.minEccKeySz = keySzBytes; return WOLFSSL_SUCCESS; } @@ -3036,14 +3091,13 @@ int wolfSSL_GetDhKey_Sz(WOLFSSL* ssl) #endif /* !NO_DH */ -WOLFSSL_ABI -int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz) +static int wolfSSL_write_internal(WOLFSSL* ssl, const void* data, size_t sz) { int ret; WOLFSSL_ENTER("wolfSSL_write"); - if (ssl == NULL || data == NULL || sz < 0) + if (ssl == NULL || data == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_QUIC @@ -3103,6 +3157,17 @@ int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz) return ret; } +WOLFSSL_ABI +int wolfSSL_write(WOLFSSL* ssl, const void* data, int sz) +{ + WOLFSSL_ENTER("wolfSSL_write"); + + if (sz < 0) + return BAD_FUNC_ARG; + + return wolfSSL_write_internal(ssl, data, (size_t)sz); +} + int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz) { int maxLength; @@ -3139,13 +3204,50 @@ int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz) return WOLFSSL_SUCCESS; } -static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, int sz, int peek) + +int wolfSSL_write_ex(WOLFSSL* ssl, const void* data, size_t sz, size_t* wr) +{ + int ret; + + if (wr != NULL) { + *wr = 0; + } + + ret = wolfSSL_write_internal(ssl, data, sz); + if (ret >= 0) { + if (wr != NULL) { + *wr = (size_t)ret; + } + + /* handle partial write cases, if not set then a partial write is + * considered a failure case, or if set and ret is 0 then is a fail */ + if (ret == 0 && ssl->options.partialWrite) { + ret = 0; + } + else if ((size_t)ret < sz && !ssl->options.partialWrite) { + ret = 0; + } + else { + /* wrote out all application data, or wrote out 1 byte or more with + * partial write flag set */ + ret = 1; + } + } + else { + ret = 0; + } + + return ret; +} + + +static int wolfSSL_read_internal(WOLFSSL* ssl, void* data, size_t sz, int peek) { int ret; WOLFSSL_ENTER("wolfSSL_read_internal"); - if (ssl == NULL || data == NULL || sz < 0) + if (ssl == NULL || data == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_QUIC @@ -3223,7 +3325,10 @@ int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz) { WOLFSSL_ENTER("wolfSSL_peek"); - return wolfSSL_read_internal(ssl, data, sz, TRUE); + if (sz < 0) + return BAD_FUNC_ARG; + + return wolfSSL_read_internal(ssl, data, (size_t)sz, TRUE); } @@ -3232,6 +3337,9 @@ int wolfSSL_read(WOLFSSL* ssl, void* data, int sz) { WOLFSSL_ENTER("wolfSSL_read"); + if (sz < 0) + return BAD_FUNC_ARG; + #ifdef OPENSSL_EXTRA if (ssl == NULL) { return BAD_FUNC_ARG; @@ -3241,10 +3349,34 @@ int wolfSSL_read(WOLFSSL* ssl, void* data, int sz) ssl->cbmode = WOLFSSL_CB_READ; } #endif - return wolfSSL_read_internal(ssl, data, sz, FALSE); + return wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE); } +/* returns 0 on failure and on no read */ +int wolfSSL_read_ex(WOLFSSL* ssl, void* data, size_t sz, size_t* rd) +{ + int ret; + + #ifdef OPENSSL_EXTRA + if (ssl == NULL) { + return BAD_FUNC_ARG; + } + if (ssl->CBIS != NULL) { + ssl->CBIS(ssl, WOLFSSL_CB_READ, WOLFSSL_SUCCESS); + ssl->cbmode = WOLFSSL_CB_READ; + } + #endif + ret = wolfSSL_read_internal(ssl, data, sz, FALSE); + + if (ret > 0 && rd != NULL) { + *rd = (size_t)ret; + } + + if (ret <= 0) ret = 0; + return ret; +} + #ifdef WOLFSSL_MULTICAST int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz) @@ -3253,10 +3385,10 @@ int wolfSSL_mcast_read(WOLFSSL* ssl, word16* id, void* data, int sz) WOLFSSL_ENTER("wolfSSL_mcast_read"); - if (ssl == NULL) + if ((ssl == NULL) || (sz < 0)) return BAD_FUNC_ARG; - ret = wolfSSL_read_internal(ssl, data, sz, FALSE); + ret = wolfSSL_read_internal(ssl, data, (size_t)sz, FALSE); if (ssl->options.dtls && ssl->options.haveMcast && id != NULL) *id = ssl->keys.curPeerId; return ret; @@ -3562,27 +3694,36 @@ static int isValidCurveGroup(word16 name) case WOLFSSL_FFDHE_6144: case WOLFSSL_FFDHE_8192: -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM #ifndef WOLFSSL_NO_ML_KEM case WOLFSSL_ML_KEM_512: case WOLFSSL_ML_KEM_768: case WOLFSSL_ML_KEM_1024: - #if defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS) + #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS) case WOLFSSL_P256_ML_KEM_512: case WOLFSSL_P384_ML_KEM_768: case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_P384_ML_KEM_1024: + case WOLFSSL_X25519_ML_KEM_512: + case WOLFSSL_X448_ML_KEM_768: + case WOLFSSL_X25519_ML_KEM_768: + case WOLFSSL_P256_ML_KEM_768: #endif #endif /* !WOLFSSL_NO_ML_KEM */ -#ifdef WOLFSSL_KYBER_ORIGINAL +#ifdef WOLFSSL_MLKEM_KYBER case WOLFSSL_KYBER_LEVEL1: case WOLFSSL_KYBER_LEVEL3: case WOLFSSL_KYBER_LEVEL5: - #if defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS) + #if defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS) case WOLFSSL_P256_KYBER_LEVEL1: case WOLFSSL_P384_KYBER_LEVEL3: case WOLFSSL_P521_KYBER_LEVEL5: + case WOLFSSL_X25519_KYBER_LEVEL1: + case WOLFSSL_X448_KYBER_LEVEL3: + case WOLFSSL_X25519_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL3: #endif -#endif /* WOLFSSL_KYBER_ORIGINAL */ +#endif /* WOLFSSL_MLKEM_KYBER */ #endif return 1; @@ -3808,7 +3949,7 @@ int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, word16 *listSz) *list = NULL; return WOLFSSL_FAILURE; } - XMEMCPY(p, s + i, len); + XMEMCPY(p, s + i, (size_t)len); } *p = 0; @@ -5805,6 +5946,7 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: if (cm->minDilithiumKeySz < 0 || DILITHIUM_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) { @@ -5826,6 +5968,28 @@ int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify) WOLFSSL_MSG("\tCA Dilithium level 5 key size error"); } break; + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + case ML_DSA_LEVEL2k: + if (cm->minDilithiumKeySz < 0 || + ML_DSA_LEVEL2_KEY_SIZE < (word16)cm->minDilithiumKeySz) { + ret = DILITHIUM_KEY_SIZE_E; + WOLFSSL_MSG("\tCA Dilithium level 2 key size error"); + } + break; + case ML_DSA_LEVEL3k: + if (cm->minDilithiumKeySz < 0 || + ML_DSA_LEVEL3_KEY_SIZE < (word16)cm->minDilithiumKeySz) { + ret = DILITHIUM_KEY_SIZE_E; + WOLFSSL_MSG("\tCA Dilithium level 3 key size error"); + } + break; + case ML_DSA_LEVEL5k: + if (cm->minDilithiumKeySz < 0 || + ML_DSA_LEVEL5_KEY_SIZE < (word16)cm->minDilithiumKeySz) { + ret = DILITHIUM_KEY_SIZE_E; + WOLFSSL_MSG("\tCA Dilithium level 5 key size error"); + } + break; #endif /* HAVE_DILITHIUM */ default: @@ -6844,9 +7008,15 @@ static int check_cert_key_dev(word32 keyOID, byte* privKey, word32 privSz, } #endif #if defined(HAVE_DILITHIUM) - if ((keyOID == DILITHIUM_LEVEL2k) || - (keyOID == DILITHIUM_LEVEL3k) || - (keyOID == DILITHIUM_LEVEL5k)) { + if ((keyOID == ML_DSA_LEVEL2k) || + (keyOID == ML_DSA_LEVEL3k) || + (keyOID == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (keyOID == DILITHIUM_LEVEL2k) + || (keyOID == DILITHIUM_LEVEL3k) + || (keyOID == DILITHIUM_LEVEL5k) + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + ) { type = DYNAMIC_TYPE_DILITHIUM; } #endif @@ -6876,9 +7046,15 @@ static int check_cert_key_dev(word32 keyOID, byte* privKey, word32 privSz, } #endif #if defined(HAVE_DILITHIUM) - if ((keyOID == DILITHIUM_LEVEL2k) || - (keyOID == DILITHIUM_LEVEL3k) || - (keyOID == DILITHIUM_LEVEL5k)) { + if ((keyOID == ML_DSA_LEVEL2k) || + (keyOID == ML_DSA_LEVEL3k) || + (keyOID == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (keyOID == DILITHIUM_LEVEL2k) + || (keyOID == DILITHIUM_LEVEL3k) + || (keyOID == DILITHIUM_LEVEL5k) + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + ) { ret = wc_CryptoCb_PqcSignatureCheckPrivKey(pkey, WC_PQC_SIG_TYPE_DILITHIUM, pubKey, pubSz); @@ -6915,9 +7091,15 @@ static int check_cert_key_dev(word32 keyOID, byte* privKey, word32 privSz, } #endif #if defined(HAVE_DILITHIUM) - if ((keyOID == DILITHIUM_LEVEL2k) || - (keyOID == DILITHIUM_LEVEL3k) || - (keyOID == DILITHIUM_LEVEL5k)) { + if ((keyOID == ML_DSA_LEVEL2k) || + (keyOID == ML_DSA_LEVEL3k) || + (keyOID == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (keyOID == DILITHIUM_LEVEL2k) + || (keyOID == DILITHIUM_LEVEL3k) + || (keyOID == DILITHIUM_LEVEL5k) + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + ) { wc_dilithium_free((dilithium_key*)pkey); } #endif @@ -7129,6 +7311,11 @@ int wolfSSL_CTX_check_private_key(const WOLFSSL_CTX* ctx) #endif #endif + /* placing error into error queue for Python port */ + if (res != WOLFSSL_SUCCESS) { + WOLFSSL_ERROR(WC_KEY_MISMATCH_E); + } + return res; } #endif /* !NO_CHECK_PRIVATE_KEY */ @@ -7252,7 +7439,7 @@ static int d2iTryRsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } pkey->pkey_sz = (int)keyIdx; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL, priv ? DYNAMIC_TYPE_PRIVATE_KEY : DYNAMIC_TYPE_PUBLIC_KEY); if (pkey->pkey.ptr == NULL) { @@ -7424,7 +7611,7 @@ static int d2iTryDsaKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } pkey->pkey_sz = (int)keyIdx; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL, priv ? DYNAMIC_TYPE_PRIVATE_KEY : DYNAMIC_TYPE_PUBLIC_KEY); if (pkey->pkey.ptr == NULL) { @@ -7508,14 +7695,14 @@ static int d2iTryDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, } pkey->pkey_sz = (int)memSz; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL, priv ? DYNAMIC_TYPE_PRIVATE_KEY : DYNAMIC_TYPE_PUBLIC_KEY); if (pkey->pkey.ptr == NULL) { ret = 0; } if (ret == 1) { - XMEMCPY(pkey->pkey.ptr, mem, memSz); + XMEMCPY(pkey->pkey.ptr, mem, (size_t)memSz); pkey->type = WC_EVP_PKEY_DH; pkey->ownDh = 1; @@ -7593,14 +7780,14 @@ static int d2iTryAltDhKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, ret = 1; pkey->type = WC_EVP_PKEY_DH; pkey->pkey_sz = (int)memSz; - pkey->pkey.ptr = (char*)XMALLOC(memSz, NULL, + pkey->pkey.ptr = (char*)XMALLOC((size_t)memSz, NULL, priv ? DYNAMIC_TYPE_PRIVATE_KEY : DYNAMIC_TYPE_PUBLIC_KEY); if (pkey->pkey.ptr == NULL) { ret = 0; } if (ret == 1) { - XMEMCPY(pkey->pkey.ptr, mem, memSz); + XMEMCPY(pkey->pkey.ptr, mem, (size_t)memSz); pkey->ownDh = 1; pkey->dh = wolfSSL_DH_new(); if (pkey->dh == NULL) { @@ -7742,31 +7929,31 @@ static int d2iTryDilithiumKey(WOLFSSL_EVP_PKEY** out, const unsigned char* mem, /* Test if Dilithium key. Try all levels. */ if (priv) { - isDilithium = ((wc_dilithium_set_level(dilithium, 2) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) && (wc_dilithium_import_private(mem, (word32)memSz, dilithium) == 0)); if (!isDilithium) { - isDilithium = ((wc_dilithium_set_level(dilithium, 3) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) && (wc_dilithium_import_private(mem, (word32)memSz, dilithium) == 0)); } if (!isDilithium) { - isDilithium = ((wc_dilithium_set_level(dilithium, 5) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) && (wc_dilithium_import_private(mem, (word32)memSz, dilithium) == 0)); } } else { - isDilithium = ((wc_dilithium_set_level(dilithium, 2) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) && (wc_dilithium_import_public(mem, (word32)memSz, dilithium) == 0)); if (!isDilithium) { - isDilithium = ((wc_dilithium_set_level(dilithium, 3) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) && (wc_dilithium_import_public(mem, (word32)memSz, dilithium) == 0)); } if (!isDilithium) { - isDilithium = ((wc_dilithium_set_level(dilithium, 5) == 0) && + isDilithium = ((wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) && (wc_dilithium_import_public(mem, (word32)memSz, dilithium) == 0)); } @@ -7921,16 +8108,16 @@ WOLFSSL_PKCS8_PRIV_KEY_INFO* wolfSSL_d2i_PKCS8_PKEY( pkcs8Der->length, &algId); if (ret >= 0) { if (advanceLen == 0) /* Set only if not PEM */ - advanceLen = inOutIdx + ret; + advanceLen = (int)inOutIdx + ret; if (algId == DHk) { /* Special case for DH as we expect the DER buffer to be always * be in PKCS8 format */ rawDer.buffer = pkcs8Der->buffer; - rawDer.length = inOutIdx + ret; + rawDer.length = inOutIdx + (word32)ret; } else { rawDer.buffer = pkcs8Der->buffer + inOutIdx; - rawDer.length = ret; + rawDer.length = (word32)ret; } ret = 0; /* good DER */ } @@ -7988,11 +8175,11 @@ int wolfSSL_i2d_PKCS8_PKEY(WOLFSSL_PKCS8_PRIV_KEY_INFO* key, unsigned char** pp) return WOLFSSL_FATAL_ERROR; len = (int)keySz; - if (pp == NULL) + if ((pp == NULL) || (len == 0)) return len; if (*pp == NULL) { - out = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_ASN1); + out = (unsigned char*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_ASN1); if (out == NULL) return WOLFSSL_FATAL_ERROR; } @@ -8082,7 +8269,8 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PUBKEY_bio(WOLFSSL_BIO* bio, return NULL; } - mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + mem = (unsigned char*)XMALLOC((size_t)memSz, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); if (mem == NULL) { return NULL; } @@ -8141,15 +8329,16 @@ static int wolfSSL_EVP_PKEY_get_der(const WOLFSSL_EVP_PKEY* key, if (*der) { /* since this function signature has no size value passed in it is * assumed that the user has allocated a large enough buffer */ - XMEMCPY(*der, pt + pkcs8HeaderSz, sz); + XMEMCPY(*der, pt + pkcs8HeaderSz, (size_t)sz); *der += sz; } else { - *der = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL); + *der = (unsigned char*)XMALLOC((size_t)sz, NULL, + DYNAMIC_TYPE_OPENSSL); if (*der == NULL) { return WOLFSSL_FATAL_ERROR; } - XMEMCPY(*der, pt + pkcs8HeaderSz, sz); + XMEMCPY(*der, pt + pkcs8HeaderSz, (size_t)sz); } } return sz; @@ -8221,14 +8410,15 @@ static WOLFSSL_EVP_PKEY* _d2i_PublicKey(int type, WOLFSSL_EVP_PKEY** out, local->type = type; local->pkey_sz = (int)inSz; local->pkcs8HeaderSz = pkcs8HeaderSz; - local->pkey.ptr = (char*)XMALLOC(inSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY); + local->pkey.ptr = (char*)XMALLOC((size_t)inSz, NULL, + DYNAMIC_TYPE_PUBLIC_KEY); if (local->pkey.ptr == NULL) { wolfSSL_EVP_PKEY_free(local); local = NULL; return NULL; } else { - XMEMCPY(local->pkey.ptr, *in, inSz); + XMEMCPY(local->pkey.ptr, *in, (size_t)inSz); } switch (type) { @@ -9164,8 +9354,14 @@ static int CheckcipherList(const char* list) next = XSTRSTR(next, ":"); - current_length = (!next) ? (word32)XSTRLEN(current) - : (word32)(next - current); + if (next) { + current_length = (word32)(next - current); + ++next; /* increment to skip ':' */ + } + else { + current_length = (word32)XSTRLEN(current); + } + if (current_length == 0) { break; } @@ -9222,8 +9418,7 @@ static int CheckcipherList(const char* list) /* list has mixed suites */ return 0; } - } - while (next++); /* increment to skip ':' */ + } while (next); if (findTLSv13Suites == 0 && findbeforeSuites == 1) { ret = 1;/* only before TLSv13 suites */ @@ -11271,7 +11466,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #endif byte* myBuffer = staticBuffer; int dynamic = 0; - int sending = 0; + word32 sending = 0; int idx = 0; int i; int ret; @@ -11279,11 +11474,11 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_writev"); for (i = 0; i < iovcnt; i++) - sending += (int)iov[i].iov_len; + sending += iov[i].iov_len; - if (sending > (int)sizeof(staticBuffer)) { - myBuffer = (byte*)XMALLOC((size_t)sending, ssl->heap, - DYNAMIC_TYPE_WRITEV); + if (sending > sizeof(staticBuffer)) { + myBuffer = (byte*)XMALLOC(sending, ssl->heap, + DYNAMIC_TYPE_WRITEV); if (!myBuffer) return MEMORY_ERROR; @@ -11300,7 +11495,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) */ PRAGMA_GCC_DIAG_PUSH PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") - ret = wolfSSL_write(ssl, myBuffer, sending); + ret = wolfSSL_write_internal(ssl, myBuffer, sending); PRAGMA_GCC_DIAG_POP if (dynamic) @@ -12094,13 +12289,13 @@ int wolfSSL_set_compression(WOLFSSL* ssl) *sigAlgo = FALCON_LEVEL5k; break; case dilithium_level2_sa_algo: - *sigAlgo = DILITHIUM_LEVEL2k; + *sigAlgo = ML_DSA_LEVEL2k; break; case dilithium_level3_sa_algo: - *sigAlgo = DILITHIUM_LEVEL3k; + *sigAlgo = ML_DSA_LEVEL3k; break; case dilithium_level5_sa_algo: - *sigAlgo = DILITHIUM_LEVEL5k; + *sigAlgo = ML_DSA_LEVEL5k; break; case sm2_sa_algo: *sigAlgo = SM2k; @@ -12316,6 +12511,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) err = WOLFSSL_SUCCESS; cleanup: wolfSSL_X509_free(cert); + cert = NULL; wolfSSL_BIO_free(bio); if (err != WOLFSSL_SUCCESS) { /* We failed so return NULL */ @@ -12596,6 +12792,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */ /* return true if connection established */ + /* this works for TLS and DTLS */ int wolfSSL_is_init_finished(const WOLFSSL* ssl) { if (ssl == NULL) @@ -12713,63 +12910,6 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #if !defined(NO_CERTS) && (defined(OPENSSL_EXTRA) || \ defined(WOLFSSL_WPAS_SMALL)) -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - /** - * Implemented in a similar way that ngx_ssl_ocsp_validate does it when - * SSL_get0_verified_chain is not available. - * @param ssl WOLFSSL object to extract certs from - * @return Stack of verified certs - */ - WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl) - { - WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL; - WOLFSSL_X509_STORE_CTX* storeCtx = NULL; - WOLFSSL_X509* peerCert = NULL; - - WOLFSSL_ENTER("wolfSSL_get0_verified_chain"); - - if (ssl == NULL || ssl->ctx == NULL) { - WOLFSSL_MSG("Bad parameter"); - return NULL; - } - - peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl); - if (peerCert == NULL) { - WOLFSSL_MSG("wolfSSL_get_peer_certificate error"); - return NULL; - } - /* wolfSSL_get_peer_certificate returns a copy. We want the internal - * member so that we don't have to worry about free'ing it. We call - * wolfSSL_get_peer_certificate so that we don't have to worry about - * setting up the internal pointer. */ - wolfSSL_X509_free(peerCert); - peerCert = (WOLFSSL_X509*)&ssl->peerCert; - chain = wolfSSL_get_peer_cert_chain(ssl); - if (chain == NULL) { - WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error"); - return NULL; - } - storeCtx = wolfSSL_X509_STORE_CTX_new(); - if (storeCtx == NULL) { - WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error"); - return NULL; - } - if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl), - peerCert, chain) != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error"); - wolfSSL_X509_STORE_CTX_free(storeCtx); - return NULL; - } - if (wolfSSL_X509_verify_cert(storeCtx) <= 0) { - WOLFSSL_MSG("wolfSSL_X509_verify_cert error"); - wolfSSL_X509_STORE_CTX_free(storeCtx); - return NULL; - } - wolfSSL_X509_STORE_CTX_free(storeCtx); - return chain; - } -#endif /* SESSION_CERTS && OPENSSL_EXTRA */ - WOLFSSL_X509_STORE* wolfSSL_CTX_get_cert_store(const WOLFSSL_CTX* ctx) { if (ctx == NULL) { @@ -12937,7 +13077,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) { WOLFSSL_ENTER("wolfSSL_ERR_get_error"); #ifdef WOLFSSL_HAVE_ERROR_QUEUE - return wc_GetErrorNodeErr(); + return (unsigned long)wc_GetErrorNodeErr(); #else return (unsigned long)(0 - NOT_COMPILED_IN); #endif @@ -13008,7 +13148,8 @@ int wolfSSL_set_compression(WOLFSSL* ssl) do { ret = wc_PeekErrorNode(0, &file, &reason, &line); if (ret >= 0) { - const char* r = wolfSSL_ERR_reason_error_string(0 - ret); + const char* r = wolfSSL_ERR_reason_error_string( + (unsigned long)(0 - ret)); if (XSNPRINTF(buf, sizeof(buf), "error:%d:wolfSSL library:%s:%s:%d\n", ret, r, file, line) @@ -14353,12 +14494,13 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_get_peer_cert_chain(const WOLFSSL* ssl) /* Try to populate if NULL or empty */ if (ssl->peerCertChain == NULL || - wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) + wolfSSL_sk_X509_num(ssl->peerCertChain) == 0) { wolfSSL_set_peer_cert_chain((WOLFSSL*) ssl); + } return ssl->peerCertChain; } -#ifndef WOLFSSL_QT + static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, WOLFSSL_X509 *x); /** @@ -14366,84 +14508,66 @@ static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm, * @param cm The cert manager that is queried for the issuer * @param x This cert's issuer will be queried in cm * @param sk The issuer is pushed onto this stack - * @return WOLFSSL_SUCCESS on success - * WOLFSSL_FAILURE on no issuer found + * @return 0 on success or no issuer found * WOLFSSL_FATAL_ERROR on a fatal error */ static int PushCAx509Chain(WOLFSSL_CERT_MANAGER* cm, WOLFSSL_X509 *x, WOLFSSL_STACK* sk) { - WOLFSSL_X509* issuer[MAX_CHAIN_DEPTH]; int i; - int push = 1; - int ret = WOLFSSL_SUCCESS; - for (i = 0; i < MAX_CHAIN_DEPTH; i++) { - if (x509GetIssuerFromCM(&issuer[i], cm, x) - != WOLFSSL_SUCCESS) + WOLFSSL_X509* issuer = NULL; + if (x509GetIssuerFromCM(&issuer, cm, x) != WOLFSSL_SUCCESS) break; - x = issuer[i]; - } - if (i == 0) /* No further chain found */ - return WOLFSSL_FAILURE; - i--; - for (; i >= 0; i--) { - if (push) { - if (wolfSSL_sk_X509_push(sk, issuer[i]) <= 0) { - wolfSSL_X509_free(issuer[i]); - ret = WOLFSSL_FATAL_ERROR; - push = 0; /* Free the rest of the unpushed certs */ - } - } - else { - wolfSSL_X509_free(issuer[i]); + if (wolfSSL_sk_X509_push(sk, issuer) <= 0) { + wolfSSL_X509_free(issuer); + issuer = NULL; + return WOLFSSL_FATAL_ERROR; } + x = issuer; } - return ret; + return 0; } -#endif /* !WOLFSSL_QT */ + /* Builds up and creates a stack of peer certificates for ssl->peerCertChain - based off of the ssl session chain. Attempts to place CA certificates - at the bottom of the stack. Returns stack of WOLFSSL_X509 certs or - NULL on failure */ -WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) + or ssl->verifiedChain based off of the ssl session chain. Attempts to place + CA certificates at the bottom of the stack for a verified chain. Returns + stack of WOLFSSL_X509 certs or NULL on failure */ +static WOLF_STACK_OF(WOLFSSL_X509)* CreatePeerCertChain(const WOLFSSL* ssl, + int verifiedFlag) { WOLFSSL_STACK* sk; WOLFSSL_X509* x509; int i = 0; - int ret; + int err; WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain"); if ((ssl == NULL) || (ssl->session->chain.count == 0)) return NULL; sk = wolfSSL_sk_X509_new_null(); - i = ssl->session->chain.count-1; - for (; i >= 0; i--) { + for (i = 0; i < ssl->session->chain.count; i++) { x509 = wolfSSL_X509_new_ex(ssl->heap); if (x509 == NULL) { WOLFSSL_MSG("Error Creating X509"); wolfSSL_sk_X509_pop_free(sk, NULL); return NULL; } - ret = DecodeToX509(x509, ssl->session->chain.certs[i].buffer, + err = DecodeToX509(x509, ssl->session->chain.certs[i].buffer, ssl->session->chain.certs[i].length); -#if !defined(WOLFSSL_QT) - if (ret == 0 && i == ssl->session->chain.count-1) { - /* On the last element in the chain try to add the CA chain - * first if we have one for this cert */ + if (err == 0 && wolfSSL_sk_X509_push(sk, x509) <= 0) + err = WOLFSSL_FATAL_ERROR; + if (err == 0 && i == ssl->session->chain.count-1 && verifiedFlag) { + /* On the last element in the verified chain try to add the CA chain + * if we have one for this cert */ SSL_CM_WARNING(ssl); - if (PushCAx509Chain(SSL_CM(ssl), x509, sk) - == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) { - ret = WOLFSSL_FATAL_ERROR; - } + err = PushCAx509Chain(SSL_CM(ssl), x509, sk); } -#endif - - if (ret != 0 || wolfSSL_sk_X509_push(sk, x509) <= 0) { + if (err != 0) { WOLFSSL_MSG("Error decoding cert"); wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_sk_X509_pop_free(sk, NULL); return NULL; } @@ -14452,18 +14576,98 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) if (sk == NULL) { WOLFSSL_MSG("Null session chain"); } -#if defined(OPENSSL_ALL) - else if (ssl->options.side == WOLFSSL_SERVER_END) { - /* to be compliant with openssl - first element is kept as peer cert on server side.*/ - wolfSSL_sk_X509_pop(sk); + return sk; +} + + +/* Builds up and creates a stack of peer certificates for ssl->peerCertChain + returns the stack on success and NULL on failure */ +WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) +{ + WOLFSSL_STACK* sk; + + WOLFSSL_ENTER("wolfSSL_set_peer_cert_chain"); + if ((ssl == NULL) || (ssl->session->chain.count == 0)) + return NULL; + + sk = CreatePeerCertChain(ssl, 0); + + if (sk != NULL) { + if (ssl->options.side == WOLFSSL_SERVER_END) { + if (ssl->session->peer) + wolfSSL_X509_free(ssl->session->peer); + + ssl->session->peer = wolfSSL_sk_X509_shift(sk); + ssl->session->peerVerifyRet = ssl->peerVerifyRet; + } + if (ssl->peerCertChain != NULL) + wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL); + /* This is Free'd when ssl is Free'd */ + ssl->peerCertChain = sk; + } + return sk; +} + + +/** + * Implemented in a similar way that ngx_ssl_ocsp_validate does it when + * SSL_get0_verified_chain is not available. + * @param ssl WOLFSSL object to extract certs from + * @return Stack of verified certs + */ +WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl) +{ + WOLF_STACK_OF(WOLFSSL_X509)* chain = NULL; + WOLFSSL_X509_STORE_CTX* storeCtx = NULL; + WOLFSSL_X509* peerCert = NULL; + + WOLFSSL_ENTER("wolfSSL_get0_verified_chain"); + + if (ssl == NULL || ssl->ctx == NULL) { + WOLFSSL_MSG("Bad parameter"); + return NULL; + } + + peerCert = wolfSSL_get_peer_certificate((WOLFSSL*)ssl); + if (peerCert == NULL) { + WOLFSSL_MSG("wolfSSL_get_peer_certificate error"); + return NULL; + } + /* wolfSSL_get_peer_certificate returns a copy. We want the internal + * member so that we don't have to worry about free'ing it. We call + * wolfSSL_get_peer_certificate so that we don't have to worry about + * setting up the internal pointer. */ + wolfSSL_X509_free(peerCert); + peerCert = (WOLFSSL_X509*)&ssl->peerCert; + chain = CreatePeerCertChain((WOLFSSL*)ssl, 1); + if (chain == NULL) { + WOLFSSL_MSG("wolfSSL_get_peer_cert_chain error"); + return NULL; + } + + if (ssl->verifiedChain != NULL) { + wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL); + } + ((WOLFSSL*)ssl)->verifiedChain = chain; + + storeCtx = wolfSSL_X509_STORE_CTX_new(); + if (storeCtx == NULL) { + WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_new error"); + return NULL; + } + if (wolfSSL_X509_STORE_CTX_init(storeCtx, SSL_STORE(ssl), + peerCert, chain) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("wolfSSL_X509_STORE_CTX_init error"); + wolfSSL_X509_STORE_CTX_free(storeCtx); + return NULL; + } + if (wolfSSL_X509_verify_cert(storeCtx) <= 0) { + WOLFSSL_MSG("wolfSSL_X509_verify_cert error"); + wolfSSL_X509_STORE_CTX_free(storeCtx); + return NULL; } -#endif - if (ssl->peerCertChain != NULL) - wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL); - /* This is Free'd when ssl is Free'd */ - ssl->peerCertChain = sk; - return sk; + wolfSSL_X509_STORE_CTX_free(storeCtx); + return chain; } #endif /* SESSION_CERTS && OPENSSL_EXTRA */ @@ -14541,7 +14745,14 @@ int wolfSSL_sk_push(WOLFSSL_STACK* sk, const void *data) { WOLFSSL_ENTER("wolfSSL_sk_push"); - return wolfSSL_sk_insert(sk, data, 0); + return wolfSSL_sk_insert(sk, data, -1); +} + +void* wolfSSL_sk_pop(WOLFSSL_STACK* sk) +{ + WOLFSSL_ENTER("wolfSSL_sk_pop"); + + return wolfSSL_sk_pop_node(sk, -1); } /* return number of elements on success 0 on fail */ @@ -14715,10 +14926,8 @@ int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx) { /* insert node into stack. not using sk since we return sk->num after */ WOLFSSL_STACK* prev_node = sk; - while (idx != 0 && prev_node->next != NULL) { + while (--idx != 0 && prev_node->next != NULL) prev_node = prev_node->next; - idx--; - } node->next = prev_node->next; prev_node->next = node; } @@ -14726,6 +14935,93 @@ int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx) return (int)sk->num; } +void* wolfSSL_sk_pop_node(WOLFSSL_STACK* sk, int idx) +{ + void* ret = NULL; + WOLFSSL_STACK* tmp = NULL; + + if (!sk) + return NULL; + if (sk->num == 0) + return NULL; + + sk->num--; + if (idx == 0 || sk->next == NULL) { + switch (sk->type) { + case STACK_TYPE_CIPHER: + /* Can't return cipher type */ + break; + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + ret = sk->data.generic; + sk->data.generic = NULL; + break; + } + if (sk->next) { + tmp = sk->next; + sk->next = tmp->next; + XMEMCPY(&sk->data, &tmp->data, sizeof(sk->data)); + wolfSSL_sk_free_node(tmp); + } + return ret; + } + + { + WOLFSSL_STACK* prev_node = sk; + tmp = sk->next; + while (--idx != 0 && tmp->next != NULL) { + prev_node = tmp; + tmp = tmp->next; + } + prev_node->next = tmp->next; + switch (sk->type) { + case STACK_TYPE_CIPHER: + /* Can't return cipher type */ + break; + case STACK_TYPE_X509: + case STACK_TYPE_GEN_NAME: + case STACK_TYPE_BIO: + case STACK_TYPE_OBJ: + case STACK_TYPE_STRING: + case STACK_TYPE_ACCESS_DESCRIPTION: + case STACK_TYPE_X509_EXT: + case STACK_TYPE_X509_REQ_ATTR: + case STACK_TYPE_NULL: + case STACK_TYPE_X509_NAME: + case STACK_TYPE_X509_NAME_ENTRY: + case STACK_TYPE_CONF_VALUE: + case STACK_TYPE_X509_INFO: + case STACK_TYPE_BY_DIR_entry: + case STACK_TYPE_BY_DIR_hash: + case STACK_TYPE_X509_OBJ: + case STACK_TYPE_DIST_POINT: + case STACK_TYPE_X509_CRL: + default: + ret = tmp->data.generic; + break; + } + wolfSSL_sk_free_node(tmp); + } + return ret; +} + #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #ifdef OPENSSL_EXTRA @@ -14857,9 +15153,9 @@ WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl) } #ifndef WOLFSSL_X509_STORE_CERTS ssl->ourCert = wolfSSL_X509_d2i_ex(NULL, - ssl->buffers.certificate->buffer, - ssl->buffers.certificate->length, - ssl->heap); + ssl->buffers.certificate->buffer, + (int)ssl->buffers.certificate->length, + ssl->heap); #endif } return ssl->ourCert; @@ -14873,9 +15169,9 @@ WOLFSSL_X509* wolfSSL_get_certificate(WOLFSSL* ssl) } #ifndef WOLFSSL_X509_STORE_CERTS ssl->ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, - ssl->ctx->certificate->buffer, - ssl->ctx->certificate->length, - ssl->heap); + ssl->ctx->certificate->buffer, + (int)ssl->ctx->certificate->length, + ssl->heap); #endif ssl->ctx->ownOurCert = 1; } @@ -14897,7 +15193,8 @@ WOLFSSL_X509* wolfSSL_CTX_get0_certificate(WOLFSSL_CTX* ctx) #ifndef WOLFSSL_X509_STORE_CERTS ctx->ourCert = wolfSSL_X509_d2i_ex(NULL, ctx->certificate->buffer, - ctx->certificate->length, ctx->heap); + (int)ctx->certificate->length, + ctx->heap); #endif ctx->ownOurCert = 1; } @@ -15172,7 +15469,7 @@ WOLFSSL_STACK* wolfSSL_sk_new_cipher(void) return sk; } -/* return 1 on success 0 on fail */ +/* returns the number of elements in stack on success, 0 on fail */ int wolfSSL_sk_CIPHER_push(WOLF_STACK_OF(WOLFSSL_CIPHER)* sk, WOLFSSL_CIPHER* cipher) { @@ -15276,72 +15573,103 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) if (ssl == NULL) return NULL; -#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM) /* Check for post-quantum groups. Return now because we do not want the ECC * check to override this result in the case of a hybrid. */ if (IsAtLeastTLSv1_3(ssl->version)) { switch (ssl->namedGroup) { #ifndef WOLFSSL_NO_ML_KEM -#ifdef HAVE_LIBOQS - case WOLFSSL_ML_KEM_512: - return "ML_KEM_512"; - case WOLFSSL_ML_KEM_768: - return "ML_KEM_768"; - case WOLFSSL_ML_KEM_1024: - return "ML_KEM_1024"; - case WOLFSSL_P256_ML_KEM_512: - return "P256_ML_KEM_512"; - case WOLFSSL_P384_ML_KEM_768: - return "P384_ML_KEM_768"; - case WOLFSSL_P521_ML_KEM_1024: - return "P521_ML_KEM_1024"; -#elif defined(WOLFSSL_WC_KYBER) +#if defined(WOLFSSL_WC_MLKEM) #ifndef WOLFSSL_NO_ML_KEM_512 case WOLFSSL_ML_KEM_512: return "ML_KEM_512"; case WOLFSSL_P256_ML_KEM_512: return "P256_ML_KEM_512"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_ML_KEM_512: + return "X25519_ML_KEM_512"; + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_768 case WOLFSSL_ML_KEM_768: return "ML_KEM_768"; case WOLFSSL_P384_ML_KEM_768: return "P384_ML_KEM_768"; + case WOLFSSL_P256_ML_KEM_768: + return "P256_ML_KEM_768"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_ML_KEM_768: + return "X25519_ML_KEM_768"; + #endif + #ifdef HAVE_CURVE448 + case WOLFSSL_X448_ML_KEM_768: + return "X448_ML_KEM_768"; + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_1024 case WOLFSSL_ML_KEM_1024: return "ML_KEM_1024"; case WOLFSSL_P521_ML_KEM_1024: return "P521_ML_KEM_1024"; + case WOLFSSL_P384_ML_KEM_1024: + return "P384_ML_KEM_1024"; #endif -#endif -#endif -#ifdef WOLFSSL_KYBER_ORIGINAL -#ifdef HAVE_LIBOQS - case WOLFSSL_KYBER_LEVEL1: - return "KYBER_LEVEL1"; - case WOLFSSL_KYBER_LEVEL3: - return "KYBER_LEVEL3"; - case WOLFSSL_KYBER_LEVEL5: - return "KYBER_LEVEL5"; - case WOLFSSL_P256_KYBER_LEVEL1: - return "P256_KYBER_LEVEL1"; - case WOLFSSL_P384_KYBER_LEVEL3: - return "P384_KYBER_LEVEL3"; - case WOLFSSL_P521_KYBER_LEVEL5: - return "P521_KYBER_LEVEL5"; -#elif defined(WOLFSSL_WC_KYBER) +#elif defined(HAVE_LIBOQS) + case WOLFSSL_ML_KEM_512: + return "ML_KEM_512"; + case WOLFSSL_ML_KEM_768: + return "ML_KEM_768"; + case WOLFSSL_ML_KEM_1024: + return "ML_KEM_1024"; + case WOLFSSL_P256_ML_KEM_512: + return "P256_ML_KEM_512"; + case WOLFSSL_P384_ML_KEM_768: + return "P384_ML_KEM_768"; + case WOLFSSL_P256_ML_KEM_768: + return "P256_ML_KEM_768"; + case WOLFSSL_P521_ML_KEM_1024: + return "P521_ML_KEM_1024"; + case WOLFSSL_P384_ML_KEM_1024: + return "P384_ML_KEM_1024"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_ML_KEM_512: + return "X25519_ML_KEM_512"; + case WOLFSSL_X25519_ML_KEM_768: + return "X25519_ML_KEM_768"; + #endif + #ifdef HAVE_CURVE448 + case WOLFSSL_X448_ML_KEM_768: + return "X448_ML_KEM_768"; + #endif +#endif /* WOLFSSL_WC_MLKEM */ +#endif /* WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_MLKEM_KYBER +#if defined(WOLFSSL_WC_MLKEM) #ifndef WOLFSSL_NO_KYBER512 case WOLFSSL_KYBER_LEVEL1: return "KYBER_LEVEL1"; case WOLFSSL_P256_KYBER_LEVEL1: return "P256_KYBER_LEVEL1"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_KYBER_LEVEL1: + return "X25519_KYBER_LEVEL1"; + #endif #endif #ifndef WOLFSSL_NO_KYBER768 case WOLFSSL_KYBER_LEVEL3: return "KYBER_LEVEL3"; case WOLFSSL_P384_KYBER_LEVEL3: return "P384_KYBER_LEVEL3"; + case WOLFSSL_P256_KYBER_LEVEL3: + return "P256_KYBER_LEVEL3"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_KYBER_LEVEL3: + return "X25519_KYBER_LEVEL3"; + #endif + #ifdef HAVE_CURVE448 + case WOLFSSL_X448_KYBER_LEVEL3: + return "X448_KYBER_LEVEL3"; + #endif #endif #ifndef WOLFSSL_NO_KYBER1024 case WOLFSSL_KYBER_LEVEL5: @@ -15349,11 +15677,36 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) case WOLFSSL_P521_KYBER_LEVEL5: return "P521_KYBER_LEVEL5"; #endif -#endif -#endif +#elif defined (HAVE_LIBOQS) + case WOLFSSL_KYBER_LEVEL1: + return "KYBER_LEVEL1"; + case WOLFSSL_KYBER_LEVEL3: + return "KYBER_LEVEL3"; + case WOLFSSL_KYBER_LEVEL5: + return "KYBER_LEVEL5"; + case WOLFSSL_P256_KYBER_LEVEL1: + return "P256_KYBER_LEVEL1"; + case WOLFSSL_P384_KYBER_LEVEL3: + return "P384_KYBER_LEVEL3"; + case WOLFSSL_P256_KYBER_LEVEL3: + return "P256_KYBER_LEVEL3"; + case WOLFSSL_P521_KYBER_LEVEL5: + return "P521_KYBER_LEVEL5"; + #ifdef HAVE_CURVE25519 + case WOLFSSL_X25519_KYBER_LEVEL1: + return "X25519_KYBER_LEVEL1"; + case WOLFSSL_X25519_KYBER_LEVEL3: + return "X25519_KYBER_LEVEL3"; + #endif + #ifdef HAVE_CURVE448 + case WOLFSSL_X448_KYBER_LEVEL3: + return "X448_KYBER_LEVEL3"; + #endif +#endif /* WOLFSSL_WC_MLKEM */ +#endif /* WOLFSSL_MLKEM_KYBER */ } } -#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */ #ifdef HAVE_FFDHE if (ssl->namedGroup != 0) { @@ -15640,42 +15993,42 @@ int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher) /* Build up the string by copying onto the end. */ - XSTRNCPY(dp, name, len); + XSTRNCPY(dp, name, (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, " ", len); + XSTRNCPY(dp, " ", (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, protocol, len); + XSTRNCPY(dp, protocol, (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, " Kx=", len); + XSTRNCPY(dp, " Kx=", (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, keaStr, len); + XSTRNCPY(dp, keaStr, (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, " Au=", len); + XSTRNCPY(dp, " Au=", (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, authStr, len); + XSTRNCPY(dp, authStr, (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, " Enc=", len); + XSTRNCPY(dp, " Enc=", (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, encStr, len); + XSTRNCPY(dp, encStr, (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); len -= strLen; dp += strLen; - XSTRNCPY(dp, " Mac=", len); + XSTRNCPY(dp, " Mac=", (size_t)len); dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp); - len -= strLen; dp += strLen; - XSTRNCPY(dp, macStr, len); + len -= strLen; dp += (size_t)strLen; + XSTRNCPY(dp, macStr, (size_t)len); dp[len-1] = '\0'; return WOLFSSL_SUCCESS; @@ -15933,7 +16286,7 @@ char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, */ if (cipher->in_stack == TRUE) { wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher); - XSTRNCPY(in,cipher->description,len); + XSTRNCPY(in,cipher->description,(size_t)len); return ret; } #endif @@ -15946,32 +16299,32 @@ char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm); /* Build up the string by copying onto the end. */ - XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), len); + XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, " ", len); + XSTRNCPY(in, " ", (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), len); + XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, " Kx=", len); + XSTRNCPY(in, " Kx=", (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, keaStr, len); + XSTRNCPY(in, keaStr, (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, " Au=", len); + XSTRNCPY(in, " Au=", (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, authStr, len); + XSTRNCPY(in, authStr, (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, " Enc=", len); + XSTRNCPY(in, " Enc=", (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, encStr, len); + XSTRNCPY(in, encStr, (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, " Mac=", len); + XSTRNCPY(in, " Mac=", (size_t)len); in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen; - XSTRNCPY(in, macStr, len); + XSTRNCPY(in, macStr, (size_t)len); in[len-1] = '\0'; return ret; @@ -17101,8 +17454,8 @@ long wolfSSL_clear_options(WOLFSSL* ssl, long opt) WOLFSSL_ENTER("wolfSSL_clear_options"); if(ssl == NULL) return WOLFSSL_FAILURE; - ssl->options.mask &= ~opt; - return ssl->options.mask; + ssl->options.mask &= (unsigned long)~opt; + return (long)ssl->options.mask; } #ifdef HAVE_PK_CALLBACKS @@ -17256,7 +17609,7 @@ void wolfSSL_ERR_load_SSL_strings(void) } #endif -#ifdef HAVE_OCSP +#if defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) long wolfSSL_get_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char **resp) { if (s == NULL || resp == NULL) @@ -17272,12 +17625,13 @@ long wolfSSL_set_tlsext_status_ocsp_resp(WOLFSSL *s, unsigned char *resp, if (s == NULL) return WOLFSSL_FAILURE; + XFREE(s->ocspResp, NULL, 0); s->ocspResp = resp; s->ocspRespSz = len; return WOLFSSL_SUCCESS; } -#endif /* HAVE_OCSP */ +#endif /* defined(HAVE_OCSP) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) */ #ifdef HAVE_MAX_FRAGMENT #if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS) @@ -17367,7 +17721,7 @@ long wolfSSL_get_verify_result(const WOLFSSL *ssl) return WOLFSSL_FAILURE; } - return ssl->peerVerifyRet; + return (long)ssl->peerVerifyRet; } #endif @@ -17633,6 +17987,33 @@ static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out) *out = *in; } + +#if defined(OPENSSL_ALL) +static WOLFSSL_X509_OBJECT* wolfSSL_X509_OBJECT_dup(WOLFSSL_X509_OBJECT* obj) +{ + WOLFSSL_X509_OBJECT* ret = NULL; + if (obj) { + ret = wolfSSL_X509_OBJECT_new(); + if (ret) { + ret->type = obj->type; + switch (ret->type) { + case WOLFSSL_X509_LU_NONE: + break; + case WOLFSSL_X509_LU_X509: + ret->data.x509 = wolfSSL_X509_dup(obj->data.x509); + break; + case WOLFSSL_X509_LU_CRL: + #if defined(HAVE_CRL) + ret->data.crl = wolfSSL_X509_CRL_dup(obj->data.crl); + #endif + break; + } + } + } + return ret; +} +#endif /* OPENSSL_ALL */ + WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk) { @@ -17695,6 +18076,17 @@ WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk) goto error; } break; + case STACK_TYPE_X509_OBJ: + #if defined(OPENSSL_ALL) + if (!sk->data.x509_obj) + break; + cur->data.x509_obj = wolfSSL_X509_OBJECT_dup(sk->data.x509_obj); + if (!cur->data.x509_obj) { + WOLFSSL_MSG("wolfSSL_X509_OBJECT_dup error"); + goto error; + } + break; + #endif case STACK_TYPE_BIO: case STACK_TYPE_STRING: case STACK_TYPE_ACCESS_DESCRIPTION: @@ -17707,7 +18099,6 @@ WOLFSSL_STACK* wolfSSL_sk_dup(WOLFSSL_STACK* sk) case STACK_TYPE_X509_INFO: case STACK_TYPE_BY_DIR_entry: case STACK_TYPE_BY_DIR_hash: - case STACK_TYPE_X509_OBJ: case STACK_TYPE_DIST_POINT: case STACK_TYPE_X509_CRL: default: @@ -17766,7 +18157,7 @@ void wolfSSL_sk_free(WOLFSSL_STACK* sk) while (sk != NULL) { WOLFSSL_STACK* next = sk->next; - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); + wolfSSL_sk_free_node(sk); sk = next; } } @@ -17780,7 +18171,7 @@ void wolfSSL_sk_GENERIC_pop_free(WOLFSSL_STACK* sk, wolfSSL_sk_pop_free(sk, (wolfSSL_sk_freefunc)f); } -/* return 1 on success 0 on fail */ +/* returns the number of elements in stack on success, 0 on fail */ int wolfSSL_sk_GENERIC_push(WOLFSSL_STACK* sk, void* generic) { WOLFSSL_ENTER("wolfSSL_sk_GENERIC_push"); @@ -17801,34 +18192,11 @@ void wolfSSL_sk_GENERIC_free(WOLFSSL_STACK* sk) */ void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, WOLF_STACK_TYPE type) { - WOLFSSL_STACK* node; void* data = NULL; /* Check we have a stack passed in of the right type. */ - if ((sk != NULL) && (sk->type == type)) { - /* Get the next node to become the new first node. */ - node = sk->next; - /* Get the ASN.1 OBJECT_ID object in the first node. */ - data = sk->data.generic; - - /* Check whether there is a next node. */ - if (node != NULL) { - /* Move content out of next node into current node. */ - sk->data.obj = node->data.obj; - sk->next = node->next; - /* Dispose of node. */ - XFREE(node, NULL, DYNAMIC_TYPE_ASN1); - } - else { - /* No more nodes - clear out data. */ - sk->data.obj = NULL; - } - - /* Decrement count as long as we thought we had nodes. */ - if (sk->num > 0) { - sk->num -= 1; - } - } + if ((sk != NULL) && (sk->type == type)) + data = wolfSSL_sk_pop(sk); return data; } @@ -17952,7 +18320,7 @@ void wolfSSL_sk_pop_free(WOLF_STACK_OF(WOLFSSL_ASN1_OBJECT)* sk, if (sk->type != STACK_TYPE_CIPHER) func(sk->data.generic); } - XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL); + XFREE(sk, sk->heap, DYNAMIC_TYPE_OPENSSL); sk = next; } } @@ -18044,7 +18412,7 @@ int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) if (sz > (long)sizeof(staticBuffer)) { WOLFSSL_MSG("Getting dynamic buffer"); - myBuffer = (byte*)XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE); + myBuffer = (byte*)XMALLOC((size_t)sz, ctx->heap, DYNAMIC_TYPE_FILE); dynamic = 1; } @@ -18183,6 +18551,9 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #ifdef WOLFSSL_MD2 { WC_NID_md2, MD2h, oidHashType, "MD2", "md2"}, #endif + #ifndef NO_MD4 + { WC_NID_md4, MD4h, oidHashType, "MD4", "md4"}, + #endif #ifndef NO_MD5 { WC_NID_md5, MD5h, oidHashType, "MD5", "md5"}, #endif @@ -18350,12 +18721,20 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { "Falcon Level 5"}, #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT { CTC_DILITHIUM_LEVEL2, DILITHIUM_LEVEL2k, oidKeyType, "Dilithium Level 2", "Dilithium Level 2"}, { CTC_DILITHIUM_LEVEL3, DILITHIUM_LEVEL3k, oidKeyType, "Dilithium Level 3", "Dilithium Level 3"}, { CTC_DILITHIUM_LEVEL5, DILITHIUM_LEVEL5k, oidKeyType, "Dilithium Level 5", "Dilithium Level 5"}, + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + { CTC_ML_DSA_LEVEL2, ML_DSA_LEVEL2k, oidKeyType, + "ML-DSA 44", "ML-DSA 44"}, + { CTC_ML_DSA_LEVEL3, ML_DSA_LEVEL3k, oidKeyType, + "ML-DSA 65", "ML-DSA 65"}, + { CTC_ML_DSA_LEVEL5, ML_DSA_LEVEL5k, oidKeyType, + "ML-DSA 87", "ML-DSA 87"}, #endif /* HAVE_DILITHIUM */ /* oidCurveType */ @@ -18738,13 +19117,13 @@ static int SaToNid(byte sa, int* nid) *nid = CTC_FALCON_LEVEL5; break; case dilithium_level2_sa_algo: - *nid = CTC_DILITHIUM_LEVEL2; + *nid = CTC_ML_DSA_LEVEL2; break; case dilithium_level3_sa_algo: - *nid = CTC_DILITHIUM_LEVEL3; + *nid = CTC_ML_DSA_LEVEL3; break; case dilithium_level5_sa_algo: - *nid = CTC_DILITHIUM_LEVEL5; + *nid = CTC_ML_DSA_LEVEL5; break; case sm2_sa_algo: *nid = WC_NID_sm2; @@ -18923,7 +19302,7 @@ WOLFSSL_X509* wolfSSL_get_chain_X509(WOLFSSL_X509_CHAIN* chain, int idx) #endif { InitDecodedCert(cert, chain->certs[idx].buffer, - chain->certs[idx].length, NULL); + (word32)chain->certs[idx].length, NULL); if ((ret = ParseCertRelative(cert, CERT_TYPE, 0, NULL, NULL)) != 0) { WOLFSSL_MSG("Failed to parse cert"); @@ -18985,10 +19364,11 @@ int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, /* Null output buffer return size needed in outLen */ if(!buf) { - if(Base64_Encode(chain->certs[idx].buffer, chain->certs[idx].length, + if(Base64_Encode(chain->certs[idx].buffer, + (word32)chain->certs[idx].length, NULL, &szNeeded) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return WOLFSSL_FAILURE; - *outLen = szNeeded + headerLen + footerLen; + *outLen = (int)szNeeded + headerLen + footerLen; return WC_NO_ERR_TRACE(LENGTH_ONLY_E); } @@ -18997,7 +19377,7 @@ int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, return BAD_FUNC_ARG; /* header */ - if (XMEMCPY(buf, header, headerLen) == NULL) + if (XMEMCPY(buf, header, (size_t)headerLen) == NULL) return WOLFSSL_FATAL_ERROR; i = headerLen; @@ -19005,14 +19385,15 @@ int wolfSSL_get_chain_cert_pem(WOLFSSL_X509_CHAIN* chain, int idx, /* body */ *outLen = inLen; /* input to Base64_Encode */ if ( (err = Base64_Encode(chain->certs[idx].buffer, - chain->certs[idx].length, buf + i, (word32*)outLen)) < 0) + (word32)chain->certs[idx].length, buf + i, + (word32*)outLen)) < 0) return err; i += *outLen; /* footer */ if ( (i + footerLen) > inLen) return BAD_FUNC_ARG; - if (XMEMCPY(buf + i, footer, footerLen) == NULL) + if (XMEMCPY(buf + i, footer, (size_t)footerLen) == NULL) return WOLFSSL_FATAL_ERROR; *outLen += headerLen + footerLen; @@ -19453,6 +19834,29 @@ void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl) return NULL; } +/* callback for extended master secret generation */ +void wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx, + CallbackGenExtMasterSecret cb) +{ + if (ctx) + ctx->GenExtMasterCb = cb; +} +/* Set extended master secret generation callback context */ +void wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx) +{ + if (ssl) + ssl->GenExtMasterCtx = ctx; +} +/* Get extended master secret generation callback context */ +void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl) +{ + if (ssl) + return ssl->GenExtMasterCtx; + + return NULL; +} + + /* callback for session key generation */ void wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb) { @@ -19732,7 +20136,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; } else { - obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA; + obj->dynamic &= (unsigned char)~WOLFSSL_ASN1_DYNAMIC_DATA; } } XMEMCPY((byte*)obj->obj, objBuf, obj->objSz); @@ -19847,7 +20251,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) bufSz = bufLen - 1; } if (bufSz) { - XMEMCPY(buf, name, bufSz); + XMEMCPY(buf, name, (size_t)bufSz); } else if (a->type == WOLFSSL_GEN_DNS || a->type == WOLFSSL_GEN_EMAIL || a->type == WOLFSSL_GEN_URI) { @@ -19858,7 +20262,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) if ((desc = oid_translate_num_to_str(buf))) { bufSz = (int)XSTRLEN(desc); bufSz = (int)min((word32)bufSz,(word32) bufLen - 1); - XMEMCPY(buf, desc, bufSz); + XMEMCPY(buf, desc, (size_t)bufSz); } } else { @@ -20014,19 +20418,21 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) if (o->nid > 0) return o->nid; - if ((ret = GetObjectId(o->obj, &idx, &oid, o->grp, o->objSz)) < 0) { + if ((ret = GetObjectId(o->obj, &idx, &oid, + (word32)o->grp, o->objSz)) < 0) { if (ret == WC_NO_ERR_TRACE(ASN_OBJECT_ID_E)) { /* Put ASN object tag in front and try again */ - int len = SetObjectId(o->objSz, NULL) + o->objSz; - byte* buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + int len = SetObjectId((int)o->objSz, NULL) + (int)o->objSz; + byte* buf = (byte*)XMALLOC((size_t)len, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (!buf) { WOLFSSL_MSG("malloc error"); return WOLFSSL_FATAL_ERROR; } - idx = SetObjectId(o->objSz, buf); + idx = (word32)SetObjectId((int)o->objSz, buf); XMEMCPY(buf + idx, o->obj, o->objSz); idx = 0; - ret = GetObjectId(buf, &idx, &oid, o->grp, len); + ret = GetObjectId(buf, &idx, &oid, (word32)o->grp, (word32)len); XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (ret < 0) { WOLFSSL_MSG("Issue getting OID of object"); @@ -20165,13 +20571,13 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) /* try as a short name */ len = (int)XSTRLEN(s); if ((int)XSTRLEN(wolfssl_object_info[i].sName) == len && - XSTRNCMP(wolfssl_object_info[i].sName, s, len) == 0) { + XSTRNCMP(wolfssl_object_info[i].sName, s, (word32)len) == 0) { return wolfssl_object_info[i].nid; } /* try as a long name */ if ((int)XSTRLEN(wolfssl_object_info[i].lName) == len && - XSTRNCMP(wolfssl_object_info[i].lName, s, len) == 0) { + XSTRNCMP(wolfssl_object_info[i].lName, s, (word32)len) == 0) { return wolfssl_object_info[i].nid; } } @@ -20226,7 +20632,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) obj->dynamic |= WOLFSSL_ASN1_DYNAMIC_DATA; i = SetObjectId((int)outSz, (byte*)obj->obj); XMEMCPY((byte*)obj->obj + i, out, outSz); - obj->objSz = i + outSz; + obj->objSz = (word32)i + outSz; return obj; } @@ -20304,7 +20710,7 @@ unsigned long wolfSSL_ERR_peek_last_error_line(const char **file, int *line) return (ERR_LIB_PEM << 24) | PEM_R_NO_START_LINE; #endif #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - if (ret == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) { + if (ret == ASN1_R_HEADER_TOO_LONG) { return (ERR_LIB_ASN1 << 24) | ASN1_R_HEADER_TOO_LONG; } #endif @@ -20756,6 +21162,7 @@ long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt) WOLFSSL_MSG("Error adding certificate to context"); /* Decrease reference count on failure */ wolfSSL_X509_free(x509); + x509 = NULL; } } } @@ -20912,7 +21319,8 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, return NULL; } - mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); + mem = (unsigned char*)XMALLOC((size_t)memSz, bio->heap, + DYNAMIC_TYPE_TMP_BUFFER); if (mem == NULL) { WOLFSSL_MSG("Malloc failure"); return NULL; @@ -20937,7 +21345,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_PrivateKey_bio(WOLFSSL_BIO* bio, int i; int j = 0; - extraBioMem = (unsigned char *)XMALLOC(extraBioMemSz, NULL, + extraBioMem = (unsigned char *)XMALLOC((size_t)extraBioMemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (extraBioMem == NULL) { WOLFSSL_MSG("Malloc failure"); @@ -21018,10 +21426,7 @@ void wolfSSL_print_all_errors_fp(XFILE fp) /* Note: This is a huge section of API's - through * wolfSSL_X509_OBJECT_get0_X509_CRL */ -#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \ - (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \ - defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \ - defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB))) +#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) #if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \ !defined(WOLFSSL_STATIC_MEMORY) @@ -21189,6 +21594,7 @@ int wolfSSL_set_tlsext_host_name(WOLFSSL* ssl, const char* host_name) return ret; } +#ifndef NO_WOLFSSL_SERVER /* May be called by server to get the requested accepted name and by the client * to get the requested name. */ const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type) @@ -21200,6 +21606,8 @@ const char * wolfSSL_get_servername(WOLFSSL* ssl, byte type) !wolfSSL_is_server(ssl)); return (const char *)serverName; } +#endif + #endif /* HAVE_SNI */ WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx) @@ -21430,9 +21838,7 @@ void wolfSSL_THREADID_set_numeric(void* id, unsigned long val) } #endif -#endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX || - * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH || - * HAVE_SBLIM_SFCB)) */ +#endif /* OPENSSL_ALL || OPENSSL_EXTRA */ #ifdef HAVE_SNI @@ -21480,7 +21886,7 @@ unsigned long wolfSSL_ERR_peek_last_error(void) if (ret == -WC_NO_ERR_TRACE(ASN_NO_PEM_HEADER)) return (WOLFSSL_ERR_LIB_PEM << 24) | -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E); #if defined(WOLFSSL_PYTHON) - if (ret == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) + if (ret == ASN1_R_HEADER_TOO_LONG) return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E); #endif return (unsigned long)ret; @@ -21692,7 +22098,7 @@ unsigned long wolfSSL_ERR_peek_error_line_data(const char **file, int *line, return (WOLFSSL_ERR_LIB_SSL << 24) | -WC_NO_ERR_TRACE(PARSE_ERROR) /* SSL_R_HTTP_REQUEST */; #endif #if defined(OPENSSL_ALL) && defined(WOLFSSL_PYTHON) - else if (err == WC_NO_ERR_TRACE(ASN1_R_HEADER_TOO_LONG)) + else if (err == ASN1_R_HEADER_TOO_LONG) return (WOLFSSL_ERR_LIB_ASN1 << 24) | -WC_NO_ERR_TRACE(WOLFSSL_ASN1_R_HEADER_TOO_LONG_E); #endif return err; @@ -21869,6 +22275,83 @@ WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl) return ssl->suitesStack; } #endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ +#ifdef OPENSSL_ALL +/* returned pointer is to an internal element in WOLFSSL struct and should not + * be free'd. It gets free'd when the WOLFSSL struct is free'd. */ +WOLF_STACK_OF(WOLFSSL_CIPHER)* wolfSSL_get_client_ciphers(WOLFSSL* ssl) +{ + WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL; + const CipherSuiteInfo* cipher_names = GetCipherNames(); + int cipherSz = GetCipherNamesSize(); + const Suites* suites; + + WOLFSSL_ENTER("wolfSSL_get_client_ciphers"); + + if (ssl == NULL) { + return NULL; + } + + /* return NULL if is client side */ + if (wolfSSL_is_server(ssl) == 0) { + return NULL; + } + + suites = ssl->clSuites; + if (suites == NULL) { + WOLFSSL_MSG("No client suites stored"); + } + else if (ssl->clSuitesStack != NULL) { + ret = ssl->clSuitesStack; + } + else { /* generate cipher suites stack if not already done */ + int i; + int j; + + ret = wolfSSL_sk_new_node(ssl->heap); + if (ret != NULL) { + ret->type = STACK_TYPE_CIPHER; + + /* higher priority of cipher suite will be on top of stack */ + for (i = suites->suiteSz - 2; i >= 0; i -= 2) { + WOLFSSL_CIPHER cipher; + + /* A couple of suites are placeholders for special options, + * skip those. */ + if (SCSV_Check(suites->suites[i], suites->suites[i+1]) + || sslCipherMinMaxCheck(ssl, suites->suites[i], + suites->suites[i+1])) { + continue; + } + + cipher.cipherSuite0 = suites->suites[i]; + cipher.cipherSuite = suites->suites[i+1]; + cipher.ssl = ssl; + for (j = 0; j < cipherSz; j++) { + if (cipher_names[j].cipherSuite0 == + cipher.cipherSuite0 && + cipher_names[j].cipherSuite == + cipher.cipherSuite) { + cipher.offset = (unsigned long)j; + break; + } + } + + /* in_stack is checked in wolfSSL_CIPHER_description */ + cipher.in_stack = 1; + + if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) { + WOLFSSL_MSG("Error pushing client cipher onto stack"); + wolfSSL_sk_CIPHER_free(ret); + ret = NULL; + break; + } + } + } + ssl->clSuitesStack = ret; + } + return ret; +} +#endif /* OPENSSL_ALL */ #if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK) long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx) @@ -22514,7 +22997,7 @@ int wolfSSL_sk_WOLFSSL_STRING_num(WOLF_STACK_OF(WOLFSSL_STRING)* strings) void wolfSSL_get0_alpn_selected(const WOLFSSL *ssl, const unsigned char **data, unsigned int *len) { - word16 nameLen; + word16 nameLen = 0; if (ssl != NULL && data != NULL && len != NULL) { TLSX_ALPN_GetRequest(ssl->extensions, (void **)data, &nameLen); @@ -22676,31 +23159,52 @@ const WOLF_EC_NIST_NAME kNistCurves[] = { #ifdef HAVE_CURVE448 {CURVE_NAME("X448"), WC_NID_X448, WOLFSSL_ECC_X448}, #endif -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM #ifndef WOLFSSL_NO_ML_KEM {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512}, {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768}, {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024}, -#if (defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) +#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) {CURVE_NAME("P256_ML_KEM_512"), WOLFSSL_P256_ML_KEM_512, WOLFSSL_P256_ML_KEM_512}, {CURVE_NAME("P384_ML_KEM_768"), WOLFSSL_P384_ML_KEM_768, WOLFSSL_P384_ML_KEM_768}, + {CURVE_NAME("P256_ML_KEM_768"), WOLFSSL_P256_ML_KEM_768, + WOLFSSL_P256_ML_KEM_768}, {CURVE_NAME("P521_ML_KEM_1024"), WOLFSSL_P521_ML_KEM_1024, WOLFSSL_P521_ML_KEM_1024}, + {CURVE_NAME("P384_ML_KEM_1024"), WOLFSSL_P384_ML_KEM_1024, + WOLFSSL_P384_ML_KEM_1024}, + {CURVE_NAME("X25519_ML_KEM_512"), WOLFSSL_X25519_ML_KEM_512, + WOLFSSL_X25519_ML_KEM_512}, + {CURVE_NAME("X448_ML_KEM_768"), WOLFSSL_X448_ML_KEM_768, + WOLFSSL_X448_ML_KEM_768}, + {CURVE_NAME("X25519_ML_KEM_768"), WOLFSSL_X25519_ML_KEM_768, + WOLFSSL_X25519_ML_KEM_768}, #endif #endif /* !WOLFSSL_NO_ML_KEM */ -#ifdef WOLFSSL_KYBER_ORIGINAL +#ifdef WOLFSSL_MLKEM_KYBER {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1}, {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3}, {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5}, -#if (defined(WOLFSSL_WC_KYBER) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) - {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_P256_KYBER_LEVEL1}, - {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_P384_KYBER_LEVEL3}, - {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_P521_KYBER_LEVEL5}, -#endif -#endif /* WOLFSSL_KYBER_ORIGINAL */ -#endif /* WOLFSSL_HAVE_KYBER */ +#if (defined(WOLFSSL_WC_MLKEM) || defined(HAVE_LIBOQS)) && defined(HAVE_ECC) + {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1, + WOLFSSL_P256_KYBER_LEVEL1}, + {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3, + WOLFSSL_P384_KYBER_LEVEL3}, + {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3, + WOLFSSL_P256_KYBER_LEVEL3}, + {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5, + WOLFSSL_P521_KYBER_LEVEL5}, + {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1, + WOLFSSL_X25519_KYBER_LEVEL1}, + {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3, + WOLFSSL_X448_KYBER_LEVEL3}, + {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3, + WOLFSSL_X25519_KYBER_LEVEL3}, +#endif +#endif /* WOLFSSL_MLKEM_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM */ #ifdef WOLFSSL_SM2 {CURVE_NAME("SM2"), WC_NID_sm2, WOLFSSL_ECC_SM2P256V1}, #endif @@ -22750,13 +23254,13 @@ int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, if (len > MAX_CURVE_NAME_SZ - 1) goto leave; - XMEMCPY(name, names + start, len); + XMEMCPY(name, names + start, (size_t)len); name[len] = 0; curve = WOLFSSL_NAMED_GROUP_INVALID; for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) { if (len == nist_name->name_len && - XSTRNCMP(name, nist_name->name, len) == 0) { + XSTRNCMP(name, nist_name->name, (size_t)len) == 0) { curve = nist_name->curve; break; } @@ -22779,7 +23283,7 @@ int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names, goto leave; } - curve = GetCurveByOID(eccSet->oidSum); + curve = GetCurveByOID((int)eccSet->oidSum); #else WOLFSSL_MSG("API not present to search farther using name"); goto leave; @@ -23910,7 +24414,7 @@ static int bio_get_data(WOLFSSL_BIO* bio, byte** data) ret = wolfSSL_BIO_get_len(bio); if (ret > 0) { - mem = (byte*)XMALLOC(ret, bio->heap, DYNAMIC_TYPE_OPENSSL); + mem = (byte*)XMALLOC((size_t)ret, bio->heap, DYNAMIC_TYPE_OPENSSL); if (mem == NULL) { WOLFSSL_MSG("Memory error"); ret = MEMORY_E; @@ -24003,7 +24507,7 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, */ ret = GetSequence(der, &idx, &len, keyLen); if (ret >= 0) { - word32 end = idx + len; + word32 end = idx + (word32)len; while (ret >= 0 && idx < end) { /* Skip type */ idx++; @@ -24011,10 +24515,10 @@ WOLFSSL_EVP_PKEY* wolfSSL_d2i_AutoPrivateKey(WOLFSSL_EVP_PKEY** pkey, len = 0; ret = GetLength(der, &idx, &len, keyLen); if (ret >= 0) { - if (idx + len > end) + if (idx + (word32)len > end) ret = ASN_PARSE_E; else { - idx += len; + idx += (word32)len; cnt++; } } @@ -24836,8 +25340,18 @@ int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len, /* expand size, to handle growth */ mx = (len_int + 3) / 3 * 4; +#ifdef WOLFSSL_NO_REALLOC + tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL && buf->data != NULL) { + XMEMCPY(tmp, buf->data, len_int); + XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL); + buf->data = NULL; + } +#else /* use realloc */ tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); +#endif + if (tmp == NULL) { return 0; /* ERR_R_MALLOC_FAILURE; */ } @@ -24879,7 +25393,18 @@ int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len) mx = ((int)len + 3) / 3 * 4; /* We want to shrink the internal buffer */ +#ifdef WOLFSSL_NO_REALLOC + tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL && buf->data != NULL) + { + XMEMCPY(tmp, buf->data, len); + XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL); + buf->data = NULL; + } +#else tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL); +#endif + if (tmp == NULL) return 0; diff --git a/src/src/ssl_asn1.c b/src/src/ssl_asn1.c index 5ebad81..535c672 100644 --- a/src/src/ssl_asn1.c +++ b/src/src/ssl_asn1.c @@ -1,6 +1,6 @@ /* ssl_asn1.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include - #include +#include #ifndef WC_NO_RNG #include #endif @@ -797,9 +793,18 @@ static int wolfssl_asn1_bit_string_grow(WOLFSSL_ASN1_BIT_STRING* bitStr, int ret = 1; byte* tmp; +#ifdef WOLFSSL_NO_REALLOC + tmp = (byte*)XMALLOC((size_t)len, NULL, DYNAMIC_TYPE_OPENSSL); + if (tmp != NULL && bitStr->data != NULL) { + XMEMCPY(tmp, bitStr->data, bitStr->length); + XFREE(bitStr->data, NULL, DYNAMIC_TYPE_OPENSSL); + bitStr->data = NULL; + } +#else /* Realloc to length required. */ tmp = (byte*)XREALLOC(bitStr->data, (size_t)len, NULL, DYNAMIC_TYPE_OPENSSL); +#endif if (tmp == NULL) { ret = 0; } @@ -1084,36 +1089,36 @@ static int wolfssl_asn1_integer_require_len(WOLFSSL_ASN1_INTEGER* a, int len, */ WOLFSSL_ASN1_INTEGER* wolfSSL_ASN1_INTEGER_dup(const WOLFSSL_ASN1_INTEGER* src) { - WOLFSSL_ASN1_INTEGER* dup = NULL; + WOLFSSL_ASN1_INTEGER* dst = NULL; WOLFSSL_ENTER("wolfSSL_ASN1_INTEGER_dup"); /* Check for object to duplicate. */ if (src != NULL) { /* Create a new ASN.1 INTEGER object to be copied into. */ - dup = wolfSSL_ASN1_INTEGER_new(); + dst = wolfSSL_ASN1_INTEGER_new(); } /* Check for object to copy into. */ - if (dup != NULL) { + if (dst != NULL) { /* Copy simple fields. */ - dup->length = src->length; - dup->negative = src->negative; - dup->type = src->type; + dst->length = src->length; + dst->negative = src->negative; + dst->type = src->type; if (!src->isDynamic) { /* Copy over data from/to fixed buffer. */ - XMEMCPY(dup->intData, src->intData, WOLFSSL_ASN1_INTEGER_MAX); + XMEMCPY(dst->intData, src->intData, WOLFSSL_ASN1_INTEGER_MAX); } - else if (wolfssl_asn1_integer_require_len(dup, src->length, 0) == 0) { - wolfSSL_ASN1_INTEGER_free(dup); - dup = NULL; + else if (wolfssl_asn1_integer_require_len(dst, src->length, 0) == 0) { + wolfSSL_ASN1_INTEGER_free(dst); + dst = NULL; } else { - XMEMCPY(dup->data, src->data, (size_t)src->length); + XMEMCPY(dst->data, src->data, (size_t)src->length); } } - return dup; + return dst; } #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ @@ -3814,7 +3819,6 @@ static int wolfssl_asn1_time_to_secs(const WOLFSSL_ASN1_TIME* t, * @param [in] from ASN.1 TIME object as start time. * @param [in] to ASN.1 TIME object as end time. * @return 1 on success. - * @return 0 when days or secs is NULL. * @return 0 when conversion of time fails. */ int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from, @@ -3824,21 +3828,15 @@ int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from, WOLFSSL_ENTER("wolfSSL_ASN1_TIME_diff"); - /* Validate parameters. */ - if (days == NULL) { - WOLFSSL_MSG("days is NULL"); - ret = 0; - } - if ((ret == 1) && (secs == NULL)) { - WOLFSSL_MSG("secs is NULL"); - ret = 0; - } - - if ((ret == 1) && ((from == NULL) && (to == NULL))) { - *days = 0; - *secs = 0; + if ((from == NULL) && (to == NULL)) { + if (days != NULL) { + *days = 0; + } + if (secs != NULL) { + *secs = 0; + } } - else if (ret == 1) { + else { const long long SECS_PER_DAY = 24 * 60 * 60; long long fromSecs; long long toSecs = 0; @@ -3849,8 +3847,13 @@ int wolfSSL_ASN1_TIME_diff(int *days, int *secs, const WOLFSSL_ASN1_TIME *from, } if (ret == 1) { long long diffSecs = toSecs - fromSecs; - *days = (int) (diffSecs / SECS_PER_DAY); - *secs = (int) (diffSecs - ((long long)*days * SECS_PER_DAY)); + if (days != NULL) { + *days = (int) (diffSecs / SECS_PER_DAY); + } + if (secs != NULL) { + *secs = (int) (diffSecs - + ((long long)(diffSecs / SECS_PER_DAY) * SECS_PER_DAY)); + } } } diff --git a/src/src/ssl_bn.c b/src/src/ssl_bn.c index 1c05b14..0d947a8 100644 --- a/src/src/ssl_bn.c +++ b/src/src/ssl_bn.c @@ -1,6 +1,6 @@ /* ssl_bn.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #include #ifndef WC_NO_RNG @@ -1273,43 +1269,29 @@ int wolfSSL_BN_is_word(const WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w) * Word operation APIs. ******************************************************************************/ -/* Add/subtract a word to/from a big number. - * - * Internal function for adding/subtracting an unsigned long from a - * WOLFSSL_BIGNUM. To add, pass "sub" as 0. To subtract, pass it as 1. +enum BN_WORD_OP { + BN_WORD_ADD = 0, + BN_WORD_SUB = 1, + BN_WORD_MUL = 2, + BN_WORD_DIV = 3, + BN_WORD_MOD = 4 +}; + +/* Helper function for word operations. * - * @param [in, out] bn Big number to operate on. - * @param [in] w Word to operate with. - * @param [in] sub Indicates whether operation to perform is a subtract. + * @param [in, out] bn Big number to operate on. + * @param [in] w Word to operate with. + * @param [in] op Operation to perform. See BN_WORD_OP for valid values. + * @param [out] mod_res Result of the modulo operation. * @return 1 on success. - * @return 0 in failure. + * @return 0 on failure. */ -static int wolfssl_bn_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, - int sub) +static int bn_word_helper(const WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, + enum BN_WORD_OP op, WOLFSSL_BN_ULONG* mod_res) { int ret = 1; -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) -#ifdef WOLFSSL_SMALL_STACK - mp_int* w_mp = NULL; -#else - mp_int w_mp[1]; -#endif /* WOLFSSL_SMALL_STACK */ -#endif -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) -#ifdef WOLFSSL_SMALL_STACK - /* Allocate temporary MP integer. */ - w_mp = (mp_int*)XMALLOC(sizeof(*w_mp), NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (w_mp == NULL) { - ret = 0; - } - else -#endif /* WOLFSSL_SMALL_STACK */ - { - /* Clear out MP integer so it can be freed. */ - XMEMSET(w_mp, 0, sizeof(*w_mp)); - } -#endif + WOLFSSL_ENTER("bn_word_helper"); /* Validate parameters. */ if (ret == 1 && BN_IS_NULL(bn)) { @@ -1318,60 +1300,108 @@ static int wolfssl_bn_add_word_int(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w, } if (ret == 1) { - int rc = 0; + int rc = MP_OKAY; #if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) + /* When input 'w' is greater than what can be stored in one digit */ if (w > (WOLFSSL_BN_ULONG)MP_MASK) { - /* Initialize temporary MP integer. */ - if (mp_init(w_mp) != MP_OKAY) { + DECL_MP_INT_SIZE_DYN(w_mp, sizeof(WOLFSSL_BN_ULONG) * CHAR_BIT, + sizeof(WOLFSSL_BN_ULONG) * CHAR_BIT); + NEW_MP_INT_SIZE(w_mp, sizeof(WOLFSSL_BN_ULONG) * CHAR_BIT, NULL, + DYNAMIC_TYPE_TMP_BUFFER); +#ifdef MP_INT_SIZE_CHECK_NULL + if (w_mp == NULL) { + WOLFSSL_MSG("NEW_MP_INT_SIZE error"); ret = 0; } - /* Set value into temporary MP integer. */ - if ((ret == 1) && (mp_set_int(w_mp, w) != MP_OKAY)) { +#endif + if (ret == 1 && mp_set_int(w_mp, w) != MP_OKAY) { + WOLFSSL_MSG("mp_set_int error"); ret = 0; } if (ret == 1) { - if (sub) { - /* Subtract as MP integer. */ - rc = mp_sub((mp_int *)bn->internal, w_mp, - (mp_int *)bn->internal); - } - else { - /* Add as MP integer. */ - rc = mp_add((mp_int *)bn->internal, w_mp, - (mp_int *)bn->internal); - } - if (rc != MP_OKAY) { - WOLFSSL_MSG("mp_add/sub error"); - ret = 0; + switch (op) { + case BN_WORD_ADD: + rc = mp_add((mp_int*)bn->internal, w_mp, + (mp_int*)bn->internal); + break; + case BN_WORD_SUB: + rc = mp_sub((mp_int*)bn->internal, w_mp, + (mp_int*)bn->internal); + break; + case BN_WORD_MUL: + rc = mp_mul((mp_int*)bn->internal, w_mp, + (mp_int*)bn->internal); + break; + case BN_WORD_DIV: + rc = mp_div((mp_int*)bn->internal, w_mp, + (mp_int*)bn->internal, NULL); + break; + case BN_WORD_MOD: + rc = mp_mod((mp_int*) bn->internal, w_mp, + w_mp); + if (rc == MP_OKAY && mod_res != NULL) + *mod_res = wolfssl_bn_get_word_1(w_mp); + break; + default: + rc = WOLFSSL_NOT_IMPLEMENTED; + break; } } + FREE_MP_INT_SIZE(w_mp, NULL, DYNAMIC_TYPE_RSA); } else #endif { - if (sub) { - /* Subtract word from MP integer. */ - rc = mp_sub_d((mp_int*)bn->internal, (mp_digit)w, - (mp_int*)bn->internal); - } - else { - /* Add word from MP integer. */ - rc = mp_add_d((mp_int*)bn->internal, (mp_digit)w, - (mp_int*)bn->internal); - } - if (rc != MP_OKAY) { - WOLFSSL_MSG("mp_add/sub_d error"); - ret = 0; + switch (op) { + case BN_WORD_ADD: + rc = mp_add_d((mp_int*)bn->internal, (mp_digit)w, + (mp_int*)bn->internal); + break; + case BN_WORD_SUB: + rc = mp_sub_d((mp_int*)bn->internal, (mp_digit)w, + (mp_int*)bn->internal); + break; + case BN_WORD_MUL: + rc = mp_mul_d((mp_int*)bn->internal, (mp_digit)w, + (mp_int*)bn->internal); + break; + case BN_WORD_DIV: +#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) +/* copied from sp_int.h */ +#if (defined(WOLFSSL_SP_MATH_ALL) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ + defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) || \ + defined(WC_MP_TO_RADIX) + rc = mp_div_d((mp_int*)bn->internal, (mp_digit)w, + (mp_int*)bn->internal, NULL); +#else + rc = WOLFSSL_NOT_IMPLEMENTED; +#endif +#else + rc = WOLFSSL_NOT_IMPLEMENTED; +#endif + break; + case BN_WORD_MOD: + { + mp_digit _mod_res; + rc = mp_mod_d((mp_int*) bn->internal, (mp_digit) w, + &_mod_res); + if (rc == MP_OKAY && mod_res != NULL) + *mod_res = (WOLFSSL_BN_ULONG)_mod_res; + } + break; + default: + rc = WOLFSSL_NOT_IMPLEMENTED; + break; } } + if (ret == 1 && rc != MP_OKAY) { + WOLFSSL_MSG("mp word operation error or not implemented"); + ret = 0; + } } -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) - mp_free(w_mp); -#ifdef WOLFSSL_SMALL_STACK - XFREE(w_mp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif /* WOLFSSL_SMALL_STACK */ -#endif + WOLFSSL_LEAVE("bn_word_helper", ret); + return ret; } @@ -1390,7 +1420,7 @@ int wolfSSL_BN_add_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) WOLFSSL_ENTER("wolfSSL_BN_add_word"); - ret = wolfssl_bn_add_word_int(bn, w, 0); + ret = bn_word_helper(bn, w, BN_WORD_ADD, NULL); WOLFSSL_LEAVE("wolfSSL_BN_add_word", ret); @@ -1412,7 +1442,7 @@ int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w) WOLFSSL_ENTER("wolfSSL_BN_sub_word"); - ret = wolfssl_bn_add_word_int(bn, w, 1); + ret = bn_word_helper(bn, w, BN_WORD_SUB, NULL); WOLFSSL_LEAVE("wolfSSL_BN_sub_word", ret); @@ -1421,79 +1451,27 @@ int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w) int wolfSSL_BN_mul_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) { - int ret = 1; -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) -#ifdef WOLFSSL_SMALL_STACK - mp_int* w_mp = NULL; -#else - mp_int w_mp[1]; -#endif /* WOLFSSL_SMALL_STACK */ -#endif + int ret; WOLFSSL_ENTER("wolfSSL_BN_mul_word"); -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) -#ifdef WOLFSSL_SMALL_STACK - /* Allocate temporary MP integer. */ - w_mp = (mp_int*)XMALLOC(sizeof(*w_mp), NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (w_mp == NULL) { - ret = 0; - } - else -#endif /* WOLFSSL_SMALL_STACK */ - { - /* Clear out MP integer so it can be freed. */ - XMEMSET(w_mp, 0, sizeof(*w_mp)); - } -#endif + ret = bn_word_helper(bn, w, BN_WORD_MUL, NULL); - /* Validate parameters. */ - if (ret == 1 && BN_IS_NULL(bn)) { - WOLFSSL_MSG("bn NULL error"); - ret = 0; - } + WOLFSSL_LEAVE("wolfSSL_BN_mul_word", ret); - if (ret == 1) { - int rc = 0; -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) - if (w > (WOLFSSL_BN_ULONG)MP_MASK) { - /* Initialize temporary MP integer. */ - if (mp_init(w_mp) != MP_OKAY) { - ret = 0; - } - /* Set value into temporary MP integer. */ - if ((ret == 1) && (mp_set_int(w_mp, w) != MP_OKAY)) { - ret = 0; - } - if (ret == 1) { - rc = mp_mul((mp_int*)bn->internal, w_mp, - (mp_int*)bn->internal); - if (rc != MP_OKAY) { - WOLFSSL_MSG("mp_mul error"); - ret = 0; - } - } - } - else -#endif - { - rc = mp_mul_d((mp_int*)bn->internal, (mp_digit)w, - (mp_int*)bn->internal); - if (rc != MP_OKAY) { - WOLFSSL_MSG("mp_mul_d error"); - ret = 0; - } - } - } + return ret; +} -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) - mp_free(w_mp); -#ifdef WOLFSSL_SMALL_STACK - XFREE(w_mp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif /* WOLFSSL_SMALL_STACK */ -#endif - WOLFSSL_LEAVE("wolfSSL_BN_mul_word", ret); +int wolfSSL_BN_div_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) +{ + int ret; + + WOLFSSL_ENTER("wolfSSL_BN_div_word"); + + ret = bn_word_helper(bn, w, BN_WORD_DIV, NULL); + + WOLFSSL_LEAVE("wolfSSL_BN_div_word", ret); return ret; } @@ -1510,70 +1488,16 @@ int wolfSSL_BN_mul_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) WOLFSSL_BN_ULONG wolfSSL_BN_mod_word(const WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w) { - WOLFSSL_BN_ULONG ret = 0; + int ret; + WOLFSSL_BN_ULONG res = 0; WOLFSSL_ENTER("wolfSSL_BN_mod_word"); - /* Validate parameters. */ - if (BN_IS_NULL(bn)) { - WOLFSSL_MSG("bn NULL error"); - ret = (WOLFSSL_BN_ULONG)-1; - } - -#if DIGIT_BIT < (SIZEOF_LONG * CHAR_BIT) - if ((ret == 0) && (w > (WOLFSSL_BN_ULONG)MP_MASK)) { - /* TODO: small stack */ - mp_int w_mp; - mp_int r_mp; - - /* Memset MP integers to be safe to free. */ - XMEMSET(&w_mp, 0, sizeof(w_mp)); - XMEMSET(&r_mp, 0, sizeof(r_mp)); - - /* Initialize MP integer to hold word. */ - if (mp_init(&w_mp) != MP_OKAY) { - ret = (WOLFSSL_BN_ULONG)-1; - } - /* Initialize MP integer to hold result word. */ - if ((ret == 0) && (mp_init(&r_mp) != MP_OKAY)) { - ret = (WOLFSSL_BN_ULONG)-1; - } - /* Set modulus word into MP integer. */ - if ((ret == 0) && (mp_set_int(&w_mp, w) != MP_OKAY)) { - ret = (WOLFSSL_BN_ULONG)-1; - } - /* Calculate modulus result. */ - if ((ret == 0) && (mp_mod((mp_int *)bn->internal, &w_mp, &r_mp) != - MP_OKAY)) { - WOLFSSL_MSG("mp_mod error"); - ret = (WOLFSSL_BN_ULONG)-1; - } - if (ret == 0) { - /* Get modulus result into an unsigned long. */ - ret = wolfssl_bn_get_word_1(&r_mp); - } - - /* Dispose of dynamically allocated data. */ - mp_free(&r_mp); - mp_free(&w_mp); - } - else -#endif - if (ret == 0) { - mp_digit mp_ret; + ret = bn_word_helper(bn, w, BN_WORD_MOD, &res); - /* Calculate modulus result using wolfCrypt. */ - if (mp_mod_d((mp_int*)bn->internal, (mp_digit)w, &mp_ret) != MP_OKAY) { - WOLFSSL_MSG("mp_add_d error"); - ret = (WOLFSSL_BN_ULONG)-1; - } - else { - /* Return result. */ - ret = (WOLFSSL_BN_ULONG)mp_ret; - } - } + WOLFSSL_LEAVE("wolfSSL_BN_mod_word", ret); - return ret; + return ret == 1 ? res : (WOLFSSL_BN_ULONG)-1; } #endif /* WOLFSSL_KEY_GEN && (!NO_RSA || !NO_DH || !NO_DSA) */ @@ -2434,27 +2358,38 @@ int wolfSSL_BN_print_fp(XFILE fp, const WOLFSSL_BIGNUM *bn) } #endif /* !NO_FILESYSTEM && XFPRINTF */ +#ifndef NO_WOLFSSL_BN_CTX /******************************************************************************* * BN_CTX APIs ******************************************************************************/ -/* Allocate and return a new BN context object. - * - * BN context not needed for operations. +/* Create a new BN context object. * - * @return Pointer to dummy object. + * @return BN context object on success. + * @return NULL on failure. */ WOLFSSL_BN_CTX* wolfSSL_BN_CTX_new(void) { - /* wolfcrypt doesn't need BN context. */ - static int ctx; + WOLFSSL_BN_CTX* ctx = NULL; + WOLFSSL_ENTER("wolfSSL_BN_CTX_new"); - return (WOLFSSL_BN_CTX*)&ctx; + ctx = (WOLFSSL_BN_CTX*)XMALLOC(sizeof(WOLFSSL_BN_CTX), NULL, + DYNAMIC_TYPE_OPENSSL); + if (ctx != NULL) { + XMEMSET(ctx, 0, sizeof(WOLFSSL_BN_CTX)); + } + + return ctx; } -/* Initialize a BN context object. + +#ifndef NO_WOLFSSL_STUB +/* deprecated * - * BN context not needed for operations. + * Initialize a BN context object. + * This function was removed in OpenSSL 1.1.0 and later. + * Keeping a stub function here for older applications that have BN_CTX_init() + * calls. * * @param [in] ctx Dummy BN context. */ @@ -2462,37 +2397,59 @@ void wolfSSL_BN_CTX_init(WOLFSSL_BN_CTX* ctx) { (void)ctx; WOLFSSL_ENTER("wolfSSL_BN_CTX_init"); + WOLFSSL_STUB("wolfSSL_BN_CTX_init"); + WOLFSSL_MSG("wolfSSL_BN_CTX_init is deprecated"); } +#endif /* Free a BN context object. * - * BN context not needed for operations. - * - * @param [in] ctx Dummy BN context. + * @param [in] ctx BN context object. */ void wolfSSL_BN_CTX_free(WOLFSSL_BN_CTX* ctx) { - (void)ctx; WOLFSSL_ENTER("wolfSSL_BN_CTX_free"); - /* Don't do anything since using dummy, static BN context. */ + if (ctx != NULL) { + while (ctx->list != NULL) { + struct WOLFSSL_BN_CTX_LIST* tmp = ctx->list; + ctx->list = ctx->list->next; + wolfSSL_BN_free(tmp->bn); + XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL); + } + XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL); + } } -/* Get a big number based on the BN context. +/* Get a big number from the BN context. * - * @param [in] ctx BN context. Not used. + * @param [in] ctx BN context object. * @return Big number on success. * @return NULL on failure. */ WOLFSSL_BIGNUM *wolfSSL_BN_CTX_get(WOLFSSL_BN_CTX *ctx) { - /* ctx is not used - returning a new big number. */ - (void)ctx; + WOLFSSL_BIGNUM* bn = NULL; WOLFSSL_ENTER("wolfSSL_BN_CTX_get"); + if (ctx != NULL) { + struct WOLFSSL_BN_CTX_LIST* node = (struct WOLFSSL_BN_CTX_LIST*)XMALLOC( + sizeof(struct WOLFSSL_BN_CTX_LIST), NULL, DYNAMIC_TYPE_OPENSSL); + if (node != NULL) { + XMEMSET(node, 0, sizeof(struct WOLFSSL_BN_CTX_LIST)); + bn = node->bn = wolfSSL_BN_new(); + if (node->bn != NULL) { + node->next = ctx->list; + ctx->list = node; + } + else { + XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL); + node = NULL; + } + } + } - /* Return a new big number. */ - return wolfSSL_BN_new(); + return bn; } #ifndef NO_WOLFSSL_STUB @@ -2512,6 +2469,75 @@ void wolfSSL_BN_CTX_start(WOLFSSL_BN_CTX *ctx) } #endif +#endif /* NO_WOLFSSL_BN_CTX */ + +/******************************************************************************* + * BN_MONT_CTX APIs + ******************************************************************************/ + +WOLFSSL_BN_MONT_CTX* wolfSSL_BN_MONT_CTX_new(void) +{ + /* wolfcrypt doesn't need BN MONT context. */ + static int mont; + WOLFSSL_ENTER("wolfSSL_BN_MONT_CTX_new"); + return (WOLFSSL_BN_MONT_CTX*)&mont; +} + +void wolfSSL_BN_MONT_CTX_free(WOLFSSL_BN_MONT_CTX *mont) +{ + (void)mont; + WOLFSSL_ENTER("wolfSSL_BN_MONT_CTX_free"); + /* Don't do anything since using dummy, static BN context. */ +} + +int wolfSSL_BN_MONT_CTX_set(WOLFSSL_BN_MONT_CTX *mont, + const WOLFSSL_BIGNUM *mod, WOLFSSL_BN_CTX *ctx) +{ + (void) mont; + (void) mod; + (void) ctx; + WOLFSSL_ENTER("wolfSSL_BN_MONT_CTX_set"); + return WOLFSSL_SUCCESS; +} + +/* Calculate r = a ^ p % m. + * + * @param [out] r Big number to store the result. + * @param [in] a Base as an unsigned long. + * @param [in] p Exponent as a big number. + * @param [in] m Modulus as a big number. + * @param [in] ctx BN context object. Unused. + * @param [in] mont Montgomery context object. Unused. + * + * @return 1 on success. + * @return 0 on failure. + */ +int wolfSSL_BN_mod_exp_mont_word(WOLFSSL_BIGNUM *r, WOLFSSL_BN_ULONG a, + const WOLFSSL_BIGNUM *p, const WOLFSSL_BIGNUM *m, WOLFSSL_BN_CTX *ctx, + WOLFSSL_BN_MONT_CTX *mont) +{ + WOLFSSL_BIGNUM* tmp = NULL; + int ret = WOLFSSL_SUCCESS; + + (void)mont; + WOLFSSL_ENTER("wolfSSL_BN_mod_exp_mont_word"); + + if (ret == WOLFSSL_SUCCESS && (tmp = wolfSSL_BN_new()) == NULL) { + WOLFSSL_MSG("wolfSSL_BN_new failed"); + ret = WOLFSSL_FAILURE; + } + if (ret == WOLFSSL_SUCCESS && (wolfSSL_BN_set_word(tmp, (unsigned long)a)) + == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { + WOLFSSL_MSG("wolfSSL_BN_set_word failed"); + ret = WOLFSSL_FAILURE; + } + if (ret == WOLFSSL_SUCCESS) + ret = wolfSSL_BN_mod_exp(r, tmp, p, m, ctx); + + wolfSSL_BN_free(tmp); + return ret; +} + #endif /* OPENSSL_EXTRA */ #endif /* !WOLFSSL_SSL_BN_INCLUDED */ diff --git a/src/src/ssl_certman.c b/src/src/ssl_certman.c index 6d18db5..df88acd 100644 --- a/src/src/ssl_certman.c +++ b/src/src/ssl_certman.c @@ -1,6 +1,6 @@ /* ssl_certman.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #include @@ -401,6 +397,7 @@ WOLFSSL_STACK* wolfSSL_CertManagerGetCerts(WOLFSSL_CERT_MANAGER* cm) /* Decode certificate. */ if ((!err) && (wolfSSL_sk_X509_push(sk, x509) <= 0)) { wolfSSL_X509_free(x509); + x509 = NULL; err = 1; } } diff --git a/src/src/ssl_crypto.c b/src/src/ssl_crypto.c index f2ff781..4744304 100644 --- a/src/src/ssl_crypto.c +++ b/src/src/ssl_crypto.c @@ -1,6 +1,6 @@ /* ssl_crypto.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef WOLFSSL_SSL_CRYPTO_INCLUDED #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -2543,21 +2538,23 @@ WOLFSSL_DES_LONG wolfSSL_DES_cbc_cksum(const unsigned char* in, if ((!err) && (dataSz % DES_BLOCK_SIZE)) { /* Allocate a buffer big enough to hold padded input. */ dataSz += DES_BLOCK_SIZE - (dataSz % DES_BLOCK_SIZE); - data = (unsigned char*)XMALLOC(dataSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + data = (unsigned char*)XMALLOC((size_t)dataSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (data == NULL) { WOLFSSL_MSG("Issue creating temporary buffer"); err = 1; } else { /* Copy input and pad with 0s. */ - XMEMCPY(data, in, length); - XMEMSET(data + length, 0, dataSz - length); + XMEMCPY(data, in, (size_t)length); + XMEMSET(data + length, 0, (size_t)(dataSz - length)); } } if (!err) { /* Allocate buffer to hold encrypted data. */ - tmp = (unsigned char*)XMALLOC(dataSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + tmp = (unsigned char*)XMALLOC((size_t)dataSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { WOLFSSL_MSG("Issue creating temporary buffer"); err = 1; @@ -2637,7 +2634,7 @@ void wolfSSL_DES_cbc_encrypt(const unsigned char* input, unsigned char* output, if (lb_sz != 0) { /* Create a 0 padded block from remaining bytes. */ XMEMSET(lastBlock, 0, DES_BLOCK_SIZE); - XMEMCPY(lastBlock, input + len, lb_sz); + XMEMCPY(lastBlock, input + len, (size_t)lb_sz); /* Encrypt last block into output. */ wc_Des_CbcEncrypt(des, output + len, lastBlock, (word32)DES_BLOCK_SIZE); @@ -2651,7 +2648,7 @@ void wolfSSL_DES_cbc_encrypt(const unsigned char* input, unsigned char* output, wc_Des_CbcDecrypt(des, lastBlock, input + len, (word32)DES_BLOCK_SIZE); /* Copy out the required amount of the decrypted block. */ - XMEMCPY(output + len, lastBlock, lb_sz); + XMEMCPY(output + len, lastBlock, (size_t)lb_sz); } } } @@ -2775,7 +2772,7 @@ void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input, if (lb_sz != 0) { /* Create a 0 padded block from remaining bytes. */ XMEMSET(lastBlock, 0, DES_BLOCK_SIZE); - XMEMCPY(lastBlock, input + len, lb_sz); + XMEMCPY(lastBlock, input + len, (size_t)lb_sz); /* Encrypt last block into output. */ ret = wc_Des3_CbcEncrypt(des3, output + len, lastBlock, (word32)DES_BLOCK_SIZE); @@ -2825,7 +2822,7 @@ void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input, (void)ret; #endif /* Copy out the required amount of the decrypted block. */ - XMEMCPY(output + len, lastBlock, lb_sz); + XMEMCPY(output + len, lastBlock, (size_t)lb_sz); } } } @@ -2940,7 +2937,7 @@ static int wolfssl_aes_set_key(const unsigned char *key, const int bits, return WOLFSSL_FATAL_ERROR; } - if (wc_AesSetKey((Aes*)aes, key, ((bits)/8), NULL, enc) != 0) { + if (wc_AesSetKey((Aes*)aes, key, (word32)((bits)/8), NULL, enc) != 0) { WOLFSSL_MSG("Error in setting AES key"); return WOLFSSL_FATAL_ERROR; } diff --git a/src/src/ssl_load.c b/src/src/ssl_load.c index 004cb65..24c8af1 100644 --- a/src/src/ssl_load.c +++ b/src/src/ssl_load.c @@ -1,6 +1,6 @@ /* ssl_load.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include /* * WOLFSSL_SYS_CA_CERTS @@ -35,8 +30,10 @@ #ifdef WOLFSSL_SYS_CA_CERTS #ifdef _WIN32 + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ #include #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ /* mingw gcc does not support pragma comment, and the * linking with crypt32 is handled in configure.ac */ @@ -132,7 +129,7 @@ static int DataToDerBuffer(const unsigned char* buff, word32 len, int format, /* Data in buffer has PEM format - extract DER data. */ if (format == WOLFSSL_FILETYPE_PEM) { #ifdef WOLFSSL_PEM_TO_DER - ret = PemToDer(buff, len, type, der, heap, info, algId); + ret = PemToDer(buff, (long)(len), type, der, heap, info, algId); if (ret != 0) { FreeDer(der); } @@ -949,6 +946,9 @@ static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int ret; word32 idx; dilithium_key* key; + int keyFormatTemp = 0; + int keyTypeTemp; + int keySizeTemp; /* Allocate a Dilithium key to parse into. */ key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, @@ -959,74 +959,74 @@ static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, /* Initialize Dilithium key. */ ret = wc_dilithium_init(key); - if (ret == 0) { - /* Set up key to parse the format specified. */ - if ((*keyFormat == DILITHIUM_LEVEL2k) || ((*keyFormat == 0) && - ((der->length == DILITHIUM_LEVEL2_KEY_SIZE) || - (der->length == DILITHIUM_LEVEL2_PRV_KEY_SIZE)))) { - ret = wc_dilithium_set_level(key, 2); - } - else if ((*keyFormat == DILITHIUM_LEVEL3k) || ((*keyFormat == 0) && - ((der->length == DILITHIUM_LEVEL3_KEY_SIZE) || - (der->length == DILITHIUM_LEVEL3_PRV_KEY_SIZE)))) { - ret = wc_dilithium_set_level(key, 3); - } - else if ((*keyFormat == DILITHIUM_LEVEL5k) || ((*keyFormat == 0) && - ((der->length == DILITHIUM_LEVEL5_KEY_SIZE) || - (der->length == DILITHIUM_LEVEL5_PRV_KEY_SIZE)))) { - ret = wc_dilithium_set_level(key, 5); - } - else { - wc_dilithium_free(key); - ret = ALGO_ID_E; - } - } - if (ret == 0) { /* Decode as a Dilithium private key. */ idx = 0; ret = wc_Dilithium_PrivateKeyDecode(der->buffer, &idx, key, der->length); if (ret == 0) { - /* Get the minimum Dilithium key size from SSL or SSL context - * object. */ - int minKeySz = ssl ? ssl->options.minDilithiumKeySz : - ctx->minDilithiumKeySz; - - /* Format is known. */ - if (*keyFormat == DILITHIUM_LEVEL2k) { - *keyType = dilithium_level2_sa_algo; - *keySize = DILITHIUM_LEVEL2_KEY_SIZE; - } - else if (*keyFormat == DILITHIUM_LEVEL3k) { - *keyType = dilithium_level3_sa_algo; - *keySize = DILITHIUM_LEVEL3_KEY_SIZE; + ret = dilithium_get_oid_sum(key, &keyFormatTemp); + if (ret == 0) { + /* Format is known. */ + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (keyFormatTemp == DILITHIUM_LEVEL2k) { + keyTypeTemp = dilithium_level2_sa_algo; + keySizeTemp = DILITHIUM_LEVEL2_KEY_SIZE; + } + else if (keyFormatTemp == DILITHIUM_LEVEL3k) { + keyTypeTemp = dilithium_level3_sa_algo; + keySizeTemp = DILITHIUM_LEVEL3_KEY_SIZE; + } + else if (keyFormatTemp == DILITHIUM_LEVEL5k) { + keyTypeTemp = dilithium_level5_sa_algo; + keySizeTemp = DILITHIUM_LEVEL5_KEY_SIZE; + } + else + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + if (keyFormatTemp == ML_DSA_LEVEL2k) { + keyTypeTemp = dilithium_level2_sa_algo; + keySizeTemp = ML_DSA_LEVEL2_KEY_SIZE; + } + else if (keyFormatTemp == ML_DSA_LEVEL3k) { + keyTypeTemp = dilithium_level3_sa_algo; + keySizeTemp = ML_DSA_LEVEL3_KEY_SIZE; + } + else if (keyFormatTemp == ML_DSA_LEVEL5k) { + keyTypeTemp = dilithium_level5_sa_algo; + keySizeTemp = ML_DSA_LEVEL5_KEY_SIZE; + } + else { + ret = ALGO_ID_E; + } } - else if (*keyFormat == DILITHIUM_LEVEL5k) { - *keyType = dilithium_level5_sa_algo; - *keySize = DILITHIUM_LEVEL5_KEY_SIZE; + + if (ret == 0) { + /* Get the minimum Dilithium key size from SSL or SSL context + * object. */ + int minKeySz = ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz; + + /* Check that the size of the Dilithium key is enough. */ + if (keySizeTemp < minKeySz) { + WOLFSSL_MSG("Dilithium private key too small"); + ret = DILITHIUM_KEY_SIZE_E; + } } - /* Check that the size of the Dilithium key is enough. */ - if (*keySize < minKeySz) { - WOLFSSL_MSG("Dilithium private key too small"); - ret = DILITHIUM_KEY_SIZE_E; + if (ret == 0) { + *keyFormat = keyFormatTemp; + *keyType = keyTypeTemp; + *keySize = keySizeTemp; } } - /* Not a Dilithium key but check whether we know what it is. */ else if (*keyFormat == 0) { WOLFSSL_MSG("Not a Dilithium key"); - /* Format unknown so keep trying. */ + /* Unknown format wasn't dilithium, so keep trying other formats. */ ret = 0; } /* Free dynamically allocated data in key. */ wc_dilithium_free(key); } - else if ((ret == WC_NO_ERR_TRACE(ALGO_ID_E)) && (*keyFormat == 0)) { - WOLFSSL_MSG("Not a Dilithium key"); - /* Format unknown so keep trying. */ - ret = 0; - } /* Dispose of allocated key. */ XFREE(key, heap, DYNAMIC_TYPE_DILITHIUM); @@ -1057,6 +1057,7 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int devId = wolfSSL_CTX_GetDevId(ctx, ssl); byte* keyType = NULL; int* keySz = NULL; + int matchAnyKey = 0; (void)heap; (void)devId; @@ -1108,8 +1109,19 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, ret = ProcessBufferTryDecodeRsa(ctx, ssl, der, keyFormat, heap, devId, keyType, keySz); #endif + matchAnyKey = 1; } -#endif +#ifdef WC_RSA_PSS + if((ret == 0) && (*keyFormat == RSAPSSk)) { + /* + Require logic to verify that the der is RSAPSSk (when *keyFormat == RSAPSSK), + and to detect that the der is RSAPSSk (when *keyFormat == 0). + */ + + matchAnyKey = 1; + } +#endif /* WC_RSA_PSS */ +#endif /* NO_RSA */ #ifdef HAVE_ECC /* Try ECC if key format is ECDSA or SM2, or yet unknown. */ if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == ECDSAk) @@ -1119,6 +1131,7 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, )) { ret = ProcessBufferTryDecodeEcc(ctx, ssl, der, keyFormat, heap, devId, keyType, keySz); + matchAnyKey = 1; } #endif /* HAVE_ECC */ #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) @@ -1126,6 +1139,7 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, if ((ret == 0) && ((*keyFormat == 0 || *keyFormat == ED25519k))) { ret = ProcessBufferTryDecodeEd25519(ctx, ssl, der, keyFormat, heap, devId, keyType, keySz); + matchAnyKey = 1; } #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */ #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) @@ -1133,6 +1147,7 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, if ((ret == 0) && ((*keyFormat == 0 || *keyFormat == ED448k))) { ret = ProcessBufferTryDecodeEd448(ctx, ssl, der, keyFormat, heap, devId, keyType, keySz); + matchAnyKey = 1; } #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */ #if defined(HAVE_FALCON) @@ -1141,22 +1156,33 @@ static int ProcessBufferTryDecode(WOLFSSL_CTX* ctx, WOLFSSL* ssl, (*keyFormat == FALCON_LEVEL5k))) { ret = ProcessBufferTryDecodeFalcon(ctx, ssl, der, keyFormat, heap, keyType, keySz); + matchAnyKey = 1; } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \ !defined(WOLFSSL_DILITHIUM_NO_ASN1) /* Try Falcon if key format is Dilithium level 2k, 3k or 5k or yet unknown. */ - if ((ret == 0) && ((*keyFormat == 0) || (*keyFormat == DILITHIUM_LEVEL2k) || - (*keyFormat == DILITHIUM_LEVEL3k) || - (*keyFormat == DILITHIUM_LEVEL5k))) { + if ((ret == 0) && + ((*keyFormat == 0) || + (*keyFormat == ML_DSA_LEVEL2k) || + (*keyFormat == ML_DSA_LEVEL3k) || + (*keyFormat == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (*keyFormat == DILITHIUM_LEVEL2k) + || (*keyFormat == DILITHIUM_LEVEL3k) + || (*keyFormat == DILITHIUM_LEVEL5k) + #endif + )) { ret = ProcessBufferTryDecodeDilithium(ctx, ssl, der, keyFormat, heap, keyType, keySz); + matchAnyKey = 1; } #endif /* HAVE_DILITHIUM */ /* Check we know the format. */ - if ((ret == 0) && (*keyFormat == 0)) { + if ((ret == 0) && + ((*keyFormat == 0) || ((*keyFormat != 0) && (matchAnyKey == 0)))) { WOLFSSL_MSG("Not a supported key type"); /* Not supported key format. */ ret = WOLFSSL_BAD_FILE; @@ -1213,7 +1239,7 @@ static int ProcessBufferPrivPkcs8Dec(EncryptedInfo* info, DerBuffer* der, } if (ret >= 0) { /* Zero out encrypted data not overwritten. */ - ForceZero(der->buffer + ret, der->length - ret); + ForceZero(der->buffer + ret, der->length - (word32)ret); /* Set decrypted data length. */ der->length = (word32)ret; } @@ -1461,9 +1487,14 @@ static void wolfssl_set_have_from_key_oid(WOLFSSL_CTX* ctx, WOLFSSL* ssl, break; #endif /* HAVE_FALCON */ #ifdef HAVE_DILITHIUM + case ML_DSA_LEVEL2k: + case ML_DSA_LEVEL3k: + case ML_DSA_LEVEL5k: + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: + #endif if (ssl != NULL) { ssl->options.haveDilithiumSig = 1; } @@ -1532,9 +1563,14 @@ static void ProcessBufferCertSetHave(WOLFSSL_CTX* ctx, WOLFSSL* ssl, break; #endif #ifdef HAVE_DILITHIUM + case CTC_ML_DSA_LEVEL2: + case CTC_ML_DSA_LEVEL3: + case CTC_ML_DSA_LEVEL5: + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case CTC_DILITHIUM_LEVEL2: case CTC_DILITHIUM_LEVEL3: case CTC_DILITHIUM_LEVEL5: + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ WOLFSSL_MSG("Dilithium cert signature"); if (ssl) { ssl->options.haveDilithiumSig = 1; @@ -1705,6 +1741,7 @@ static int ProcessBufferCertPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: keyType = dilithium_level2_sa_algo; /* Dilithium is fixed key size */ @@ -1735,6 +1772,37 @@ static int ProcessBufferCertPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DILITHIUM_KEY_SIZE_E); } break; + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + case ML_DSA_LEVEL2k: + keyType = dilithium_level2_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL2_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case ML_DSA_LEVEL3k: + keyType = dilithium_level3_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL3_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case ML_DSA_LEVEL5k: + keyType = dilithium_level5_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; #endif /* HAVE_DILITHIUM */ default: @@ -1894,6 +1962,7 @@ static int ProcessBufferCertAltPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT case DILITHIUM_LEVEL2k: keyType = dilithium_level2_sa_algo; /* Dilithium is fixed key size */ @@ -1924,6 +1993,37 @@ static int ProcessBufferCertAltPublicKey(WOLFSSL_CTX* ctx, WOLFSSL* ssl, DILITHIUM_KEY_SIZE_E); } break; + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + case ML_DSA_LEVEL2k: + keyType = dilithium_level2_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL2_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case ML_DSA_LEVEL3k: + keyType = dilithium_level3_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL3_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; + case ML_DSA_LEVEL5k: + keyType = dilithium_level5_sa_algo; + /* Dilithium is fixed key size */ + keySz = ML_DSA_LEVEL5_KEY_SIZE; + if (checkKeySz) { + ret = CHECK_KEY_SZ(ssl ? ssl->options.minDilithiumKeySz : + ctx->minDilithiumKeySz, DILITHIUM_MAX_KEY_SIZE, keySz, + DILITHIUM_KEY_SIZE_E); + } + break; #endif /* HAVE_DILITHIUM */ default: @@ -2803,7 +2903,7 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, } if (file != NULL) { - /* Load the PEM formatted CA file. */ + /* Load the PEM formatted CA file */ ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0, NULL, verify); #ifndef NO_WOLFSSL_DIR @@ -4739,6 +4839,7 @@ long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) if (ret == 1) { /* On success WOLFSSL_X509 memory is responsibility of SSL context. */ wolfSSL_X509_free(x509); + x509 = NULL; } WOLFSSL_LEAVE("wolfSSL_CTX_add_extra_chain_cert", ret); @@ -4832,6 +4933,7 @@ int wolfSSL_CTX_add0_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) if (ret == 1) { /* Down reference or free original now as we own certificate. */ wolfSSL_X509_free(x509); + x509 = NULL; } return ret; @@ -4890,6 +4992,7 @@ int wolfSSL_CTX_add1_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) if (ret != 1) { /* Decrease reference count on error as we didn't store it. */ wolfSSL_X509_free(x509); + x509 = NULL; } } @@ -4953,6 +5056,7 @@ int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) if (ret != 1) { /* Free it now on error. */ wolfSSL_X509_free(x509); + x509 = NULL; } } } @@ -4985,6 +5089,7 @@ int wolfSSL_add1_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) if ((ret = wolfSSL_add0_chain_cert(ssl, x509)) != 1) { /* Decrease reference count on error as not stored. */ wolfSSL_X509_free(x509); + x509 = NULL; } } @@ -5113,7 +5218,8 @@ int wolfSSL_CTX_use_RSAPrivateKey(WOLFSSL_CTX* ctx, WOLFSSL_RSA* rsa) if (ret == 1) { /* Allocate memory to hold DER encoding.. */ - der = (unsigned char*)XMALLOC(derSize, NULL, DYNAMIC_TYPE_TMP_BUFFER); + der = (unsigned char*)XMALLOC((size_t)derSize, NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (der == NULL) { WOLFSSL_MSG("Malloc failure"); ret = MEMORY_E; @@ -5355,8 +5461,8 @@ int wolfSSL_SetTmpDH(WOLFSSL* ssl, const unsigned char* p, int pSz, } if (ret == 1) { /* Copy p and g into allocated buffers. */ - XMEMCPY(pAlloc, p, pSz); - XMEMCPY(gAlloc, g, gSz); + XMEMCPY(pAlloc, p, (size_t)pSz); + XMEMCPY(gAlloc, g, (size_t)gSz); /* Set the buffers into SSL. */ ret = wolfssl_set_tmp_dh(ssl, pAlloc, pSz, gAlloc, gSz); } @@ -5514,8 +5620,8 @@ int wolfSSL_CTX_SetTmpDH(WOLFSSL_CTX* ctx, const unsigned char* p, int pSz, if (ret == 1) { /* Copy p and g into allocated buffers. */ - XMEMCPY(pAlloc, p, pSz); - XMEMCPY(gAlloc, g, gSz); + XMEMCPY(pAlloc, p, (size_t)pSz); + XMEMCPY(gAlloc, g, (size_t)gSz); /* Set the buffers into SSL context. */ ret = wolfssl_ctx_set_tmp_dh(ctx, pAlloc, pSz, gAlloc, gSz); } @@ -5567,8 +5673,8 @@ long wolfSSL_set_tmp_dh(WOLFSSL *ssl, WOLFSSL_DH *dh) if (ret == 1) { /* Allocate buffers for p and g to be assigned into SSL. */ - p = (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - g = (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + p = (byte*)XMALLOC((size_t)pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + g = (byte*)XMALLOC((size_t)gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); if ((p == NULL) || (g == NULL)) { ret = MEMORY_E; } @@ -5633,8 +5739,8 @@ long wolfSSL_CTX_set_tmp_dh(WOLFSSL_CTX* ctx, WOLFSSL_DH* dh) if (ret == 1) { /* Allocate buffers for p and g to be assigned into SSL. */ - p = (byte*)XMALLOC(pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); - g = (byte*)XMALLOC(gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + p = (byte*)XMALLOC((size_t)pSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); + g = (byte*)XMALLOC((size_t)gSz, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY); if ((p == NULL) || (g == NULL)) { ret = MEMORY_E; } diff --git a/src/src/ssl_misc.c b/src/src/ssl_misc.c index 9a5f4b0..56a71e8 100644 --- a/src/src/ssl_misc.c +++ b/src/src/ssl_misc.c @@ -1,6 +1,6 @@ /* ssl_misc.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #if !defined(WOLFSSL_SSL_MISC_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN diff --git a/src/src/ssl_p7p12.c b/src/src/ssl_p7p12.c index 12ef33c..00395c9 100644 --- a/src/src/ssl_p7p12.c +++ b/src/src/ssl_p7p12.c @@ -1,6 +1,6 @@ /* ssl_p7p12.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(OPENSSL_EXTRA) && (defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) #include @@ -231,6 +227,7 @@ WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7) if (x509) { if (wolfSSL_sk_X509_push(ret, x509) <= 0) { wolfSSL_X509_free(x509); + x509 = NULL; WOLFSSL_MSG("wolfSSL_sk_X509_push error"); goto error; } @@ -1180,6 +1177,8 @@ PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, DYNAMIC_TYPE_PKCS7); if (canonSection == NULL) { goto error; + } else { + XMEMSET(canonSection, 0, (word32)canonSize); } lineLen = wolfSSL_BIO_gets(in, section, remainLen); @@ -1912,12 +1911,14 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, WOLFSSL_MSG("Issue with parsing certificate"); FreeDecodedCert(DeCert); wolfSSL_X509_free(x509); + x509 = NULL; } else { if (CopyDecodedToX509(x509, DeCert) != 0) { WOLFSSL_MSG("Failed to copy decoded cert"); FreeDecodedCert(DeCert); wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); XFREE(certData, heap, DYNAMIC_TYPE_PKCS); @@ -1937,6 +1938,7 @@ int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, if (wolfSSL_sk_X509_push(*ca, x509) <= 0) { WOLFSSL_MSG("Failed to push x509 onto stack"); wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL; XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY); XFREE(certData, heap, DYNAMIC_TYPE_PKCS); diff --git a/src/src/ssl_sess.c b/src/src/ssl_sess.c index 1471b9d..c5e0e68 100644 --- a/src/src/ssl_sess.c +++ b/src/src/ssl_sess.c @@ -1,6 +1,6 @@ /* ssl_sess.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_SSL_SESS_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -375,7 +370,7 @@ int wolfSSL_SetServerID(WOLFSSL* ssl, const byte* id, int len, int newSession) WOLFSSL_MSG("Valid ServerID not cached already"); ssl->session->idLen = (word16)len; - XMEMCPY(ssl->session->serverID, id, len); + XMEMCPY(ssl->session->serverID, id, (size_t)len); } #ifdef HAVE_EXT_CACHE else { @@ -1457,6 +1452,7 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) if (peer != NULL) { wolfSSL_X509_free(peer); + peer = NULL; } #endif @@ -1819,7 +1815,7 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, ticLen = addSession->ticketLen; /* Alloc Memory here to avoid syscalls during lock */ if (ticLen > SESSION_TICKET_LEN) { - ticBuff = (byte*)XMALLOC(ticLen, NULL, + ticBuff = (byte*)XMALLOC((size_t)ticLen, NULL, DYNAMIC_TYPE_SESSION_TICK); if (ticBuff == NULL) { return MEMORY_E; @@ -1978,7 +1974,7 @@ int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, /* Copy in the certs from the session */ addSession->chain.count = cacheSession->chain.count; XMEMCPY(addSession->chain.certs, cacheSession->chain.certs, - sizeof(x509_buffer) * cacheSession->chain.count); + sizeof(x509_buffer) * (size_t)cacheSession->chain.count); } #endif /* SESSION_CERTS */ #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) @@ -2669,7 +2665,8 @@ int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) unsigned char *data; if (*p == NULL) - *p = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_OPENSSL); + *p = (unsigned char*)XMALLOC((size_t)size, NULL, + DYNAMIC_TYPE_OPENSSL); if (*p == NULL) return 0; data = *p; @@ -2693,7 +2690,7 @@ int wolfSSL_i2d_SSL_SESSION(WOLFSSL_SESSION* sess, unsigned char** p) c16toa((word16)sess->chain.certs[i].length, data + idx); idx += OPAQUE16_LEN; XMEMCPY(data + idx, sess->chain.certs[i].buffer, - sess->chain.certs[i].length); + (size_t)sess->chain.certs[i].length); idx += sess->chain.certs[i].length; } #endif @@ -3524,7 +3521,7 @@ int wolfSSL_SESSION_get_master_key(const WOLFSSL_SESSION* ses, size = outSz; } - XMEMCPY(out, ses->masterSecret, size); + XMEMCPY(out, ses->masterSecret, (size_t)size); return size; } @@ -3538,6 +3535,10 @@ int wolfSSL_SESSION_get_master_key_length(const WOLFSSL_SESSION* ses) #ifdef WOLFSSL_EARLY_DATA unsigned int wolfSSL_SESSION_get_max_early_data(const WOLFSSL_SESSION *session) { + if (session == NULL) { + return BAD_FUNC_ARG; + } + return session->maxEarlyDataSz; } #endif /* WOLFSSL_EARLY_DATA */ @@ -3565,7 +3566,16 @@ void SetupSession(WOLFSSL* ssl) session->side = (byte)ssl->options.side; if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) XMEMCPY(session->masterSecret, ssl->arrays->masterSecret, SECRET_LEN); - session->haveEMS = ssl->options.haveEMS; + /* RFC8446 Appendix D. + * implementations which support both TLS 1.3 and earlier versions SHOULD + * indicate the use of the Extended Master Secret extension in their APIs + * whenever TLS 1.3 is used. + * Set haveEMS so that we send the extension in subsequent connections that + * offer downgrades. */ + if (IsAtLeastTLSv1_3(ssl->version)) + session->haveEMS = 1; + else + session->haveEMS = ssl->options.haveEMS; #ifdef WOLFSSL_SESSION_ID_CTX /* If using compatibility layer then check for and copy over session context * id. */ @@ -3757,7 +3767,7 @@ static int wolfSSL_DupSessionEx(const WOLFSSL_SESSION* input, word16 ticLenAlloc = 0; byte *ticBuff = NULL; #endif - const size_t copyOffset = OFFSETOF(WOLFSSL_SESSION, heap) + + const size_t copyOffset = WC_OFFSETOF(WOLFSSL_SESSION, heap) + sizeof(input->heap); int ret = WOLFSSL_SUCCESS; @@ -4096,7 +4106,7 @@ void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session) ForceZero(session->sessionID, ID_LEN); if (session->type == WOLFSSL_SESSION_TYPE_HEAP) { - XFREE(session, session->heap, DYNAMIC_TYPE_SESSION); + XFREE(session, session->heap, DYNAMIC_TYPE_SESSION); /* // NOLINT(clang-analyzer-unix.Malloc) */ } } diff --git a/src/src/tls.c b/src/src/tls.c index 0e5f43b..6ad21c9 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -1,6 +1,6 @@ /* tls.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef WOLFCRYPT_ONLY @@ -48,12 +42,12 @@ #ifdef HAVE_CURVE448 #include #endif -#ifdef WOLFSSL_HAVE_KYBER - #include -#ifdef WOLFSSL_WC_KYBER - #include +#ifdef WOLFSSL_HAVE_MLKEM + #include +#ifdef WOLFSSL_WC_MLKEM + #include #elif defined(HAVE_LIBOQS) - #include + #include #endif #endif @@ -645,12 +639,24 @@ int MakeTlsMasterSecret(WOLFSSL* ssl) XMEMSET(handshake_hash, 0, HSHASH_SZ); ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz); if (ret == 0) { - ret = _MakeTlsExtendedMasterSecret( - ssl->arrays->masterSecret, SECRET_LEN, - ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz, - handshake_hash, hashSz, - IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, - ssl->heap, ssl->devId); + #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS) + ret = PROTOCOLCB_UNAVAILABLE; + if (ssl->ctx->GenExtMasterCb) { + void* ctx = wolfSSL_GetGenExtMasterSecretCtx(ssl); + ret = ssl->ctx->GenExtMasterCb(ssl, handshake_hash, hashSz, + ctx); + } + if (!ssl->ctx->GenExtMasterCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) + #endif /* (HAVE_SECRET_CALLBACK) && (HAVE_EXT_SECRET_CALLBACK) */ + { + ret = _MakeTlsExtendedMasterSecret( + ssl->arrays->masterSecret, SECRET_LEN, + ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz, + handshake_hash, hashSz, + IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, + ssl->heap, ssl->devId); + } ForceZero(handshake_hash, hashSz); } @@ -1024,7 +1030,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, if (ret != 0) return ret; - XMEMSET(hmac->innerHash, 0, macLen); + XMEMSET(hmac->innerHash, 0, (size_t)macLen); if (safeBlocks > 0) { ret = Hmac_HashUpdate(hmac, header, headerSz); @@ -1039,7 +1045,7 @@ static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in, else safeBlocks = 0; - XMEMSET(digest, 0, macLen); + XMEMSET(digest, 0, (size_t)macLen); k = (unsigned int)(safeBlocks * blockSz); for (i = safeBlocks; i < blocks; i++) { unsigned char hashBlock[WC_MAX_BLOCK_SIZE]; @@ -1190,8 +1196,8 @@ static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in, ret = wc_HmacUpdate(hmac, header, headerSz); if (ret == 0) { /* Fill the rest of the block with any available data. */ - word32 currSz = ctMaskLT((int)msgSz, blockSz) & msgSz; - currSz |= ctMaskGTE((int)msgSz, blockSz) & blockSz; + word32 currSz = ctMaskLT((int)msgSz, (int)blockSz) & msgSz; + currSz |= ctMaskGTE((int)msgSz, (int)blockSz) & blockSz; currSz -= WOLFSSL_TLS_HMAC_INNER_SZ; currSz &= ~(0 - (currSz >> 31)); ret = wc_HmacUpdate(hmac, in, currSz); @@ -1338,7 +1344,7 @@ int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, #ifdef HAVE_BLAKE2 if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) { ret = Hmac_UpdateFinal(&hmac, digest, in, - sz + hashSz + padSz + 1, myInner, innerSz); + sz + hashSz + (word32)padSz + 1, myInner, innerSz); } else #endif @@ -1349,8 +1355,9 @@ int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz, } #else - ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1, - myInner, innerSz); + ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + + (word32)(padSz) + 1, + myInner, innerSz); #endif } else { @@ -2964,7 +2971,10 @@ static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest) (void)ssl; if (!isRequest) { - #ifndef NO_WOLFSSL_CLIENT + /* RFC 6066 section 6 states that the server responding + * to trusted_ca_keys is optional. Do not error out unless + * opted into with the define WOLFSSL_REQUIRE_TCA. */ + #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_REQUIRE_TCA) TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS); if (extension && !extension->resp) { @@ -2972,7 +2982,9 @@ static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest) WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR); return TCA_ABSENT_ERROR; } - #endif /* NO_WOLFSSL_CLIENT */ + #else + WOLFSSL_MSG("No response received for trusted_ca_keys. Continuing."); + #endif /* !NO_WOLFSSL_CLIENT && WOLFSSL_REQUIRE_TCA */ } return 0; @@ -3226,6 +3238,14 @@ word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr, byte isRequest, #endif #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) if (!isRequest && IsAtLeastTLSv1_3(csr->ssl->version)) { +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + if (csr->ssl != NULL && SSL_CM(csr->ssl) != NULL && + SSL_CM(csr->ssl)->ocsp_stapling != NULL && + SSL_CM(csr->ssl)->ocsp_stapling->statusCb != NULL && + idx == 0) { + return OPAQUE8_LEN + OPAQUE24_LEN + csr->ssl->ocspRespSz; + } +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ return (word16)(OPAQUE8_LEN + OPAQUE24_LEN + csr->responses[idx].length); } @@ -3235,6 +3255,70 @@ word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr, byte isRequest, return size; } +#if (defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)) && \ +(defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)) +static int TLSX_CSR_SetResponseWithStatusCB(WOLFSSL *ssl) +{ + void *ioCtx = NULL; + WOLFSSL_OCSP *ocsp; + int ret; + + if (ssl == NULL || SSL_CM(ssl) == NULL) + return BAD_FUNC_ARG; + ocsp = SSL_CM(ssl)->ocsp_stapling; + if (ocsp == NULL || ocsp->statusCb == NULL) + return BAD_FUNC_ARG; + ioCtx = (ssl->ocspIOCtx != NULL) ? ssl->ocspIOCtx : ocsp->cm->ocspIOCtx; + ret = ocsp->statusCb(ssl, ioCtx); + switch (ret) { + case SSL_TLSEXT_ERR_OK: + if (ssl->ocspRespSz > 0) { + /* ack the extension, status cb provided the response in + * ssl->ocspResp */ + TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST); + ssl->status_request = WOLFSSL_CSR_OCSP; + } + ret = 0; + break; + case SSL_TLSEXT_ERR_NOACK: + /* suppressing as not critical */ + ret = 0; + break; + case SSL_TLSEXT_ERR_ALERT_FATAL: + default: + ret = WOLFSSL_FATAL_ERROR; + break; + } + return ret; +} + +static int TLSX_CSR_WriteWithStatusCB(CertificateStatusRequest* csr, + byte* output) +{ + WOLFSSL *ssl = csr->ssl; + WOLFSSL_OCSP *ocsp; + word16 offset = 0; + byte *response; + int respSz; + + if (ssl == NULL || SSL_CM(ssl) == NULL) + return BAD_FUNC_ARG; + ocsp = SSL_CM(ssl)->ocsp_stapling; + if (ocsp == NULL || ocsp->statusCb == NULL) + return BAD_FUNC_ARG; + response = ssl->ocspResp; + respSz = ssl->ocspRespSz; + if (response == NULL || respSz == 0) + return BAD_FUNC_ARG; + output[offset++] = WOLFSSL_CSR_OCSP; + c32to24(respSz, output + offset); + offset += OPAQUE24_LEN; + XMEMCPY(output + offset, response, respSz); + return offset + respSz; +} +#endif /* (TLS13 && !NO_WOLFSLL_SERVER) && (OPENSSL_ALL || WOLFSSL_NGINX || +WOLFSSL_HAPROXY) */ + static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest) { return TLSX_CSR_GetSize_ex(csr, isRequest, 0); @@ -3287,6 +3371,14 @@ int TLSX_CSR_Write_ex(CertificateStatusRequest* csr, byte* output, #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) if (!isRequest && IsAtLeastTLSv1_3(csr->ssl->version)) { word16 offset = 0; +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + if (csr->ssl != NULL && SSL_CM(csr->ssl) != NULL && + SSL_CM(csr->ssl)->ocsp_stapling != NULL && + SSL_CM(csr->ssl)->ocsp_stapling->statusCb != NULL && + idx == 0) { + return TLSX_CSR_WriteWithStatusCB(csr, output); + } +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ output[offset++] = csr->status_type; c32to24(csr->responses[idx].length, output + offset); offset += OPAQUE24_LEN; @@ -3451,7 +3543,7 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, if (request) { XMEMCPY(request->nonce, csr->request.ocsp[0].nonce, - csr->request.ocsp[0].nonceSz); + (size_t)csr->request.ocsp[0].nonceSz); request->nonceSz = csr->request.ocsp[0].nonceSz; } } @@ -3562,7 +3654,13 @@ static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length, #if defined(WOLFSSL_TLS13) if (ssl->options.tls1_3) { - +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + if (ssl != NULL && SSL_CM(ssl) != NULL && + SSL_CM(ssl)->ocsp_stapling != NULL && + SSL_CM(ssl)->ocsp_stapling->statusCb != NULL) { + return TLSX_CSR_SetResponseWithStatusCB(ssl); +} +#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */ if (ssl->buffers.certificate == NULL) { WOLFSSL_MSG("Certificate buffer not set!"); return BUFFER_ERROR; @@ -3655,14 +3753,14 @@ int TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert, csr->requests--; } /* preserve nonce */ - XMEMCPY(nonce, request->nonce, nonceSz); + XMEMCPY(nonce, csr->request.ocsp->nonce, (size_t)nonceSz); if (req_cnt < MAX_CERT_EXTENSIONS) { if ((ret = InitOcspRequest(request, cert, 0, heap)) != 0) return ret; /* restore nonce */ - XMEMCPY(request->nonce, nonce, nonceSz); + XMEMCPY(csr->request.ocsp->nonce, nonce, (size_t)nonceSz); request->nonceSz = nonceSz; csr->requests++; } @@ -3977,7 +4075,7 @@ static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length, if (request) { XMEMCPY(request->nonce, csr2->request.ocsp[0].nonce, - csr2->request.ocsp[0].nonceSz); + (size_t)csr2->request.ocsp[0].nonceSz); request->nonceSz = csr2->request.ocsp[0].nonceSz; @@ -4059,6 +4157,14 @@ static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length, continue; } +#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) + /* OpenSSL status CB supports only CERTIFICATE STATUS REQ V1 */ + if (ssl != NULL && SSL_CM(ssl) != NULL && + SSL_CM(ssl)->ocsp_stapling != NULL && + SSL_CM(ssl)->ocsp_stapling->statusCb != NULL) { + return 0; + } +#endif /* if using status_request and already sending it, remove it * and prefer to use the v2 version */ #ifdef HAVE_CERTIFICATE_STATUS_REQUEST @@ -4189,7 +4295,8 @@ int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer, int nonceSz = csr2->request.ocsp[0].nonceSz; /* preserve nonce, replicating nonce of ocsp[0] */ - XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz); + XMEMCPY(nonce, csr2->request.ocsp[0].nonce, + (size_t)nonceSz); if ((ret = InitOcspRequest( &csr2->request.ocsp[csr2->requests], cert, @@ -4198,7 +4305,7 @@ int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer, /* restore nonce */ XMEMCPY(csr2->request.ocsp[csr2->requests].nonce, - nonce, nonceSz); + nonce, (size_t)nonceSz); csr2->request.ocsp[csr2->requests].nonceSz = nonceSz; csr2->requests++; } @@ -4316,6 +4423,11 @@ int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type, CertificateStatusRequestItemV2* last = (CertificateStatusRequestItemV2*)extension->data; + if (last == NULL) { + XFREE(csr2, heap, DYNAMIC_TYPE_TLSX); + return BAD_FUNC_ARG; + } + for (; last->next; last = last->next); last->next = csr2; @@ -4349,7 +4461,7 @@ int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type, #ifdef HAVE_SUPPORTED_CURVES #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \ - && !defined(HAVE_FFDHE) && !defined(WOLFSSL_HAVE_KYBER) + && !defined(HAVE_FFDHE) && !defined(WOLFSSL_HAVE_MLKEM) #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \ Use --enable-ecc and/or --enable-liboqs in the configure script or \ define HAVE_ECC. Alternatively use FFDHE for DH cipher suites. @@ -4809,7 +4921,7 @@ static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup, const DhParams* params = NULL; for (; serverGroup != NULL; serverGroup = serverGroup->next) { - if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name)) + if (!WOLFSSL_NAMED_GROUP_IS_FFDHE(serverGroup->name)) continue; for (group = clientGroup; group != NULL; group = group->next) { @@ -4886,7 +4998,7 @@ static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup, word32 p_len; for (; serverGroup != NULL; serverGroup = serverGroup->next) { - if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name)) + if (!WOLFSSL_NAMED_GROUP_IS_FFDHE(serverGroup->name)) continue; for (group = clientGroup; group != NULL; group = group->next) { @@ -4990,7 +5102,7 @@ int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl) return 0; clientGroup = (SupportedCurve*)extension->data; for (group = clientGroup; group != NULL; group = group->next) { - if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) { + if (WOLFSSL_NAMED_GROUP_IS_FFDHE(group->name)) { found = 1; break; } @@ -7675,6 +7787,7 @@ static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse) if (ret == 0) { /* setting "key" means okay to call wc_curve25519_free */ key = (curve25519_key*)kse->key; + kse->keyLen = CURVE25519_KEYSIZE; #ifdef WOLFSSL_STATIC_EPHEMERAL ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key); @@ -7760,6 +7873,7 @@ static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse) ret = wc_curve448_init((curve448_key*)kse->key); if (ret == 0) { key = (curve448_key*)kse->key; + kse->keyLen = CURVE448_KEY_SIZE; #ifdef WOLFSSL_STATIC_EPHEMERAL ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key); @@ -7899,7 +8013,7 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) #ifdef WOLFSSL_STATIC_EPHEMERAL ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key); - if (ret != 0) + if (ret != 0 || eccKey->dp->id != curveId) #endif { /* set curve info for EccMakeKey "peer" info */ @@ -7977,8 +8091,24 @@ static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse) return ret; } -#ifdef WOLFSSL_HAVE_KYBER -static int kyber_id2type(int id, int *type) +#ifdef WOLFSSL_HAVE_MLKEM +#if defined(WOLFSSL_MLKEM_CACHE_A) && \ + !defined(WOLFSSL_TLSX_PQC_MLKEM_STORE_PRIV_KEY) + /* Store KyberKey object rather than private key bytes in key share entry. + * Improves performance at cost of more dynamic memory being used. */ + #define WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ +#endif +#if defined(WOLFSSL_TLSX_PQC_MLKEM_STORE_PRIV_KEY) && \ + defined(WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ) + #error "Choose WOLFSSL_TLSX_PQC_MLKEM_STORE_PRIV_KEY or " + "WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ" +#endif + +#if !defined(WOLFSSL_MLKEM_NO_MAKE_KEY) || \ + !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + (!defined(WOLFSSL_MLKEM_NO_DECAPSULATE) && \ + !defined(WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ)) +static int mlkem_id2type(int id, int *type) { int ret = 0; @@ -8000,7 +8130,7 @@ static int kyber_id2type(int id, int *type) break; #endif #endif -#ifdef WOLFSSL_KYBER_ORIGINAL +#ifdef WOLFSSL_MLKEM_KYBER #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: *type = KYBER512; @@ -8024,82 +8154,92 @@ static int kyber_id2type(int id, int *type) return ret; } +#endif +/* Structures and objects needed for hybrid key exchanges using both classic + * ECDHE and PQC KEM key material. */ typedef struct PqcHybridMapping { int hybrid; int ecc; int pqc; + int pqc_first; } PqcHybridMapping; static const PqcHybridMapping pqc_hybrid_mapping[] = { #ifndef WOLFSSL_NO_ML_KEM - {.hybrid = WOLFSSL_P256_ML_KEM_512, .ecc = WOLFSSL_ECC_SECP256R1, - .pqc = WOLFSSL_ML_KEM_512}, - {.hybrid = WOLFSSL_P384_ML_KEM_768, .ecc = WOLFSSL_ECC_SECP384R1, - .pqc = WOLFSSL_ML_KEM_768}, - {.hybrid = WOLFSSL_P521_ML_KEM_1024, .ecc = WOLFSSL_ECC_SECP521R1, - .pqc = WOLFSSL_ML_KEM_1024}, -#endif -#ifdef WOLFSSL_KYBER_ORIGINAL - {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1, - .pqc = WOLFSSL_KYBER_LEVEL1}, - {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1, - .pqc = WOLFSSL_KYBER_LEVEL3}, - {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1, - .pqc = WOLFSSL_KYBER_LEVEL5}, -#endif - {.hybrid = 0, .ecc = 0, .pqc = 0} + {WOLFSSL_P256_ML_KEM_512, WOLFSSL_ECC_SECP256R1, WOLFSSL_ML_KEM_512, 0}, + {WOLFSSL_P384_ML_KEM_768, WOLFSSL_ECC_SECP384R1, WOLFSSL_ML_KEM_768, 0}, + {WOLFSSL_P256_ML_KEM_768, WOLFSSL_ECC_SECP256R1, WOLFSSL_ML_KEM_768, 0}, + {WOLFSSL_P521_ML_KEM_1024, WOLFSSL_ECC_SECP521R1, WOLFSSL_ML_KEM_1024, 0}, + {WOLFSSL_P384_ML_KEM_1024, WOLFSSL_ECC_SECP384R1, WOLFSSL_ML_KEM_1024, 0}, +#ifdef HAVE_CURVE25519 + {WOLFSSL_X25519_ML_KEM_512, WOLFSSL_ECC_X25519, WOLFSSL_ML_KEM_512, 1}, + {WOLFSSL_X25519_ML_KEM_768, WOLFSSL_ECC_X25519, WOLFSSL_ML_KEM_768, 1}, +#endif +#ifdef HAVE_CURVE448 + {WOLFSSL_X448_ML_KEM_768, WOLFSSL_ECC_X448, WOLFSSL_ML_KEM_768, 1}, +#endif +#endif /* WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_MLKEM_KYBER + {WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_ECC_SECP256R1, WOLFSSL_KYBER_LEVEL1, 0}, + {WOLFSSL_P384_KYBER_LEVEL3, WOLFSSL_ECC_SECP384R1, WOLFSSL_KYBER_LEVEL3, 0}, + {WOLFSSL_P256_KYBER_LEVEL3, WOLFSSL_ECC_SECP256R1, WOLFSSL_KYBER_LEVEL3, 0}, + {WOLFSSL_P521_KYBER_LEVEL5, WOLFSSL_ECC_SECP521R1, WOLFSSL_KYBER_LEVEL5, 0}, +#ifdef HAVE_CURVE25519 + {WOLFSSL_X25519_KYBER_LEVEL1, WOLFSSL_ECC_X25519, WOLFSSL_KYBER_LEVEL1, 0}, + {WOLFSSL_X25519_KYBER_LEVEL3, WOLFSSL_ECC_X25519, WOLFSSL_KYBER_LEVEL3, 0}, +#endif +#ifdef HAVE_CURVE448 + {WOLFSSL_X448_KYBER_LEVEL3, WOLFSSL_ECC_X448, WOLFSSL_KYBER_LEVEL3, 0}, +#endif +#endif /* WOLFSSL_MLKEM_KYBER */ + {0, 0, 0, 0} }; -/* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group. - * If it cannot find a mapping then *pqc is set to group. ecc is optional. */ -static void findEccPqc(int *ecc, int *pqc, int group) +/* Map an ecc-pqc hybrid group into its ecc group and pqc kem group. */ +static void findEccPqc(int *ecc, int *pqc, int *pqc_first, int group) { int i; - if (pqc == NULL) { - return; - } - *pqc = 0; - if (ecc != NULL) { + if (pqc != NULL) + *pqc = 0; + if (ecc != NULL) *ecc = 0; - } + if (pqc_first != NULL) + *pqc_first = 0; for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) { if (pqc_hybrid_mapping[i].hybrid == group) { - *pqc = pqc_hybrid_mapping[i].pqc; - if (ecc != NULL) { + if (pqc != NULL) + *pqc = pqc_hybrid_mapping[i].pqc; + if (ecc != NULL) *ecc = pqc_hybrid_mapping[i].ecc; - } + if (pqc_first != NULL) + *pqc_first = pqc_hybrid_mapping[i].pqc_first; break; } } - - if (*pqc == 0) { - /* It is not a hybrid, so maybe its simple. */ - *pqc = group; - } } -/* Create a key share entry using liboqs parameters group. +#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY +/* Create a key share entry using pqc parameters group on the client side. * Generates a key pair. * * ssl The SSL/TLS object. * kse The key share entry object. * returns 0 on success, otherwise failure. */ -static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) +static int TLSX_KeyShare_GenPqcKeyClient(WOLFSSL *ssl, KeyShareEntry* kse) { int ret = 0; int type = 0; +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ KyberKey kem[1]; - byte* pubKey = NULL; byte* privKey = NULL; - KeyShareEntry *ecc_kse = NULL; - int oqs_group = 0; - int ecc_group = 0; word32 privSz = 0; - word32 pubSz = 0; +#else + KyberKey* kem = NULL; +#endif /* This gets called twice. Once during parsing of the key share and once * during the population of the extension. No need to do work the second @@ -8108,13 +8248,14 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) return ret; } - findEccPqc(&ecc_group, &oqs_group, kse->group); - ret = kyber_id2type(oqs_group, &type); + /* Get the type of key we need from the key share group. */ + ret = mlkem_id2type(kse->group, &type); if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { WOLFSSL_MSG("Invalid Kyber algorithm specified."); ret = BAD_FUNC_ARG; } +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ if (ret == 0) { ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId); if (ret != 0) { @@ -8123,75 +8264,222 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) } if (ret == 0) { - ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap, - DYNAMIC_TYPE_TLSX); - if (ecc_kse == NULL) { - WOLFSSL_MSG("ecc_kse memory allocation failure"); + ret = wc_KyberKey_PrivateKeySize(kem, &privSz); + } + if (ret == 0) { + ret = wc_KyberKey_PublicKeySize(kem, &kse->pubKeyLen); + } + + if (ret == 0) { + privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + if (privKey == NULL) { + WOLFSSL_MSG("privkey memory allocation failure"); + ret = MEMORY_ERROR; + } + } +#else + if (ret == 0) { + /* Allocate a Kyber key to hold private key. */ + kem = (KyberKey*)XMALLOC(sizeof(KyberKey), ssl->heap, + DYNAMIC_TYPE_PRIVATE_KEY); + if (kem == NULL) { + WOLFSSL_MSG("KEM memory allocation failure"); ret = MEMORY_ERROR; } } + if (ret == 0) { + ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId); + if (ret != 0) { + WOLFSSL_MSG("Failed to initialize Kyber Key."); + } + } + if (ret == 0) { + ret = wc_KyberKey_PublicKeySize(kem, &kse->pubKeyLen); + } +#endif if (ret == 0) { - XMEMSET(ecc_kse, 0, sizeof(*ecc_kse)); + kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (kse->pubKey == NULL) { + WOLFSSL_MSG("pubkey memory allocation failure"); + ret = MEMORY_ERROR; + } + } - ret = wc_KyberKey_PrivateKeySize(kem, &privSz); + if (ret == 0) { + ret = wc_KyberKey_MakeKey(kem, ssl->rng); + if (ret != 0) { + WOLFSSL_MSG("Kyber keygen failure"); + } } if (ret == 0) { - ret = wc_KyberKey_PublicKeySize(kem, &pubSz); + ret = wc_KyberKey_EncodePublicKey(kem, kse->pubKey, + kse->pubKeyLen); } - if (ret == 0 && ecc_group != 0) { - ecc_kse->group = ecc_group; - ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse); - /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */ +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + if (ret == 0) { + ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz); + } +#endif + +#ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_MSG("Public Kyber Key"); + WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen ); +#endif + + if (ret != 0) { + /* Data owned by key share entry otherwise. */ + wc_KyberKey_Free(kem); + XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + kse->pubKey = NULL; + #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + #else + XFREE(kem, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->key = NULL; + #endif + } + else { + #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + wc_KyberKey_Free(kem); + kse->privKey = (byte*)privKey; + kse->privKeyLen = privSz; + #else + kse->key = kem; + #endif + } + + return ret; +} + +/* Create a key share entry using both ecdhe and pqc parameters groups. + * Generates two key pairs on the client side. + * + * ssl The SSL/TLS object. + * kse The key share entry object. + * returns 0 on success, otherwise failure. + */ +static int TLSX_KeyShare_GenPqcHybridKeyClient(WOLFSSL *ssl, KeyShareEntry* kse) +{ + int ret = 0; + KeyShareEntry *ecc_kse = NULL; + KeyShareEntry *pqc_kse = NULL; + int pqc_group = 0; + int ecc_group = 0; + int pqc_first = 0; + + /* This gets called twice. Once during parsing of the key share and once + * during the population of the extension. No need to do work the second + * time. Just return success if its already been done. */ + if (kse->pubKey != NULL) { + return ret; + } + + /* Determine the ECC and PQC group of the hybrid combination */ + findEccPqc(&ecc_group, &pqc_group, &pqc_first, kse->group); + if (ecc_group == 0 || pqc_group == 0) { + WOLFSSL_MSG("Invalid hybrid group"); + ret = BAD_FUNC_ARG; } if (ret == 0) { - pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - if (pubKey == NULL) { - WOLFSSL_MSG("pubkey memory allocation failure"); + ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (ecc_kse == NULL) { + WOLFSSL_MSG("kse memory allocation failure"); ret = MEMORY_ERROR; } + else { + XMEMSET(ecc_kse, 0, sizeof(*ecc_kse)); + } } - if (ret == 0) { - privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - if (privKey == NULL) { - WOLFSSL_MSG("privkey memory allocation failure"); + pqc_kse = (KeyShareEntry*)XMALLOC(sizeof(*pqc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (pqc_kse == NULL) { + WOLFSSL_MSG("kse memory allocation failure"); ret = MEMORY_ERROR; } + else { + XMEMSET(pqc_kse, 0, sizeof(*pqc_kse)); + } } + /* Generate ECC key share part */ if (ret == 0) { - ret = wc_KyberKey_MakeKey(kem, ssl->rng); - if (ret != 0) { - WOLFSSL_MSG("Kyber keygen failure"); + ecc_kse->group = ecc_group; + #ifdef HAVE_CURVE25519 + if (ecc_group == WOLFSSL_ECC_X25519) { + ret = TLSX_KeyShare_GenX25519Key(ssl, ecc_kse); + } + else + #endif + #ifdef HAVE_CURVE448 + if (ecc_group == WOLFSSL_ECC_X448) { + ret = TLSX_KeyShare_GenX448Key(ssl, ecc_kse); + } + else + #endif + { + ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse); } + /* No error message, TLSX_KeyShare_Gen*Key will do it. */ } + + /* Generate PQC key share part */ if (ret == 0) { - ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen, - pubSz); + pqc_kse->group = pqc_group; + ret = TLSX_KeyShare_GenPqcKeyClient(ssl, pqc_kse); + /* No error message, TLSX_KeyShare_GenPqcKeyClient will do it. */ } + + /* Allocate memory for combined public key */ if (ret == 0) { - ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz); + kse->pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pqc_kse->pubKeyLen, + ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + if (kse->pubKey == NULL) { + WOLFSSL_MSG("pubkey memory allocation failure"); + ret = MEMORY_ERROR; + } } + + /* Create combined public key. The order of classic/pqc key material is + * indicated by the pqc_first variable. */ if (ret == 0) { - if (ecc_kse->pubKeyLen > 0) - XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen); - kse->pubKey = pubKey; - kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz; - pubKey = NULL; - - /* Note we are saving the OQS private key and ECC private key - * separately. That's because the ECC private key is not simply a - * buffer. Its is an ecc_key struct. Typically do not need the private - * key size, but will need to zero it out upon freeing. */ - kse->privKey = privKey; - privKey = NULL; - kse->privKeyLen = privSz; + if (pqc_first) { + XMEMCPY(kse->pubKey, pqc_kse->pubKey, pqc_kse->pubKeyLen); + XMEMCPY(kse->pubKey + pqc_kse->pubKeyLen, ecc_kse->pubKey, + ecc_kse->pubKeyLen); + } + else { + XMEMCPY(kse->pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen); + XMEMCPY(kse->pubKey + ecc_kse->pubKeyLen, pqc_kse->pubKey, + pqc_kse->pubKeyLen); + } + kse->pubKeyLen = ecc_kse->pubKeyLen + pqc_kse->pubKeyLen; + } + /* Store the private keys. + * Note we are saving the PQC private key and ECC private key + * separately. That's because the ECC private key is not simply a + * buffer. Its is an ecc_key struct. */ + if (ret == 0) { + #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + /* PQC private key is an encoded byte array */ + kse->privKey = pqc_kse->privKey; + kse->privKeyLen = pqc_kse->privKeyLen; + pqc_kse->privKey = NULL; + #else + /* PQC private key is a pointer to KyberKey object */ + kse->privKey = (byte*)pqc_kse->key; + kse->privKeyLen = 0; + pqc_kse->key = NULL; + #endif + /* ECC private key is a pointer to ecc_key object */ kse->key = ecc_kse->key; + kse->keyLen = ecc_kse->keyLen; ecc_kse->key = NULL; } @@ -8200,14 +8488,13 @@ static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse) WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen ); #endif - wc_KyberKey_Free(kem); TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); - XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + TLSX_KeyShare_FreeAll(pqc_kse, ssl->heap); return ret; } -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* !WOLFSSL_MLKEM_NO_MAKE_KEY */ +#endif /* WOLFSSL_HAVE_MLKEM */ /* Generate a secret/key using the key share entry. * @@ -8218,15 +8505,17 @@ int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse) { int ret; /* Named FFDHE groups have a bit set to identify them. */ - if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group)) + if (WOLFSSL_NAMED_GROUP_IS_FFDHE(kse->group)) ret = TLSX_KeyShare_GenDhKey(ssl, kse); else if (kse->group == WOLFSSL_ECC_X25519) ret = TLSX_KeyShare_GenX25519Key(ssl, kse); else if (kse->group == WOLFSSL_ECC_X448) ret = TLSX_KeyShare_GenX448Key(ssl, kse); -#ifdef WOLFSSL_HAVE_KYBER +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_MAKE_KEY) else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group)) - ret = TLSX_KeyShare_GenPqcKey(ssl, kse); + ret = TLSX_KeyShare_GenPqcKeyClient(ssl, kse); + else if (WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(kse->group)) + ret = TLSX_KeyShare_GenPqcHybridKeyClient(ssl, kse); #endif else ret = TLSX_KeyShare_GenEccKey(ssl, kse); @@ -8247,7 +8536,7 @@ static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap) while ((current = list) != NULL) { list = current->next; - if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) { + if (WOLFSSL_NAMED_GROUP_IS_FFDHE(current->group)) { #ifndef NO_DH wc_FreeDhKey((DhKey*)current->key); #endif @@ -8262,17 +8551,43 @@ static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap) wc_curve448_free((curve448_key*)current->key); #endif } -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group)) { - if (current->key != NULL) { - ForceZero((byte*)current->key, current->keyLen); + wc_KyberKey_Free((KyberKey*)current->key); + #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + if (current->privKey != NULL) { + ForceZero(current->privKey, current->privKeyLen); } - XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); - current->pubKey = NULL; + #endif + } + else if (WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(current->group)) { + int ecc_group = 0; + findEccPqc(&ecc_group, NULL, NULL, current->group); + + /* Free PQC private key */ + #ifdef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + wc_KyberKey_Free((KyberKey*)current->privKey); + #else if (current->privKey != NULL) { ForceZero(current->privKey, current->privKeyLen); - XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY); - current->privKey = NULL; + } + #endif + + /* Free ECC private key */ + if (ecc_group == WOLFSSL_ECC_X25519) { + #ifdef HAVE_CURVE25519 + wc_curve25519_free((curve25519_key*)current->key); + #endif + } + else if (ecc_group == WOLFSSL_ECC_X448) { + #ifdef HAVE_CURVE448 + wc_curve448_free((curve448_key*)current->key); + #endif + } + else { + #ifdef HAVE_ECC + wc_ecc_free((ecc_key*)current->key); + #endif } } #endif @@ -8282,7 +8597,7 @@ static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap) #endif } XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY); - #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK)) + #if !defined(NO_DH) || defined(WOLFSSL_HAVE_MLKEM) XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY); #endif XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -8508,10 +8823,15 @@ static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) * * ssl The SSL/TLS object. * keyShareEntry The key share entry object to use to calculate shared secret. + * ssOutput The destination buffer for the shared secret. + * ssOutSz The size of the generated shared secret. + * * returns 0 on success and other values indicate failure. */ -static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, - KeyShareEntry* keyShareEntry) +static int TLSX_KeyShare_ProcessX25519_ex(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, + unsigned char* ssOutput, + word32* ssOutSz) { int ret; @@ -8560,11 +8880,13 @@ static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, if (ret == 0) { ssl->ecdhCurveOID = ECC_X25519_OID; - + #ifdef WOLFSSL_CURVE25519_BLINDING + ret = wc_curve25519_set_rng(key, ssl->rng); + } + if (ret == 0) { + #endif ret = wc_curve25519_shared_secret_ex(key, peerX25519Key, - ssl->arrays->preMasterSecret, - &ssl->arrays->preMasterSz, - EC25519_LITTLE_ENDIAN); + ssOutput, ssOutSz, EC25519_LITTLE_ENDIAN); } wc_curve25519_free(peerX25519Key); @@ -8572,9 +8894,13 @@ static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, wc_curve25519_free((curve25519_key*)keyShareEntry->key); XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); keyShareEntry->key = NULL; + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + keyShareEntry->ke = NULL; #else (void)ssl; (void)keyShareEntry; + (void)ssOutput; + (void)ssOutSz; ret = PEER_KEY_ERROR; WOLFSSL_ERROR_VERBOSE(ret); @@ -8583,13 +8909,33 @@ static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, return ret; } +/* Process the X25519 key share extension on the client side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to use to calculate shared secret. + * + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry) +{ + return TLSX_KeyShare_ProcessX25519_ex(ssl, keyShareEntry, + ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz); +} + /* Process the X448 key share extension on the client side. * * ssl The SSL/TLS object. * keyShareEntry The key share entry object to use to calculate shared secret. + * ssOutput The destination buffer for the shared secret. + * ssOutSz The size of the generated shared secret. + * * returns 0 on success and other values indicate failure. */ -static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) +static int TLSX_KeyShare_ProcessX448_ex(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, + unsigned char* ssOutput, + word32* ssOutSz) { int ret; @@ -8640,9 +8986,7 @@ static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) ssl->ecdhCurveOID = ECC_X448_OID; ret = wc_curve448_shared_secret_ex(key, peerX448Key, - ssl->arrays->preMasterSecret, - &ssl->arrays->preMasterSz, - EC448_LITTLE_ENDIAN); + ssOutput, ssOutSz, EC448_LITTLE_ENDIAN); } wc_curve448_free(peerX448Key); @@ -8650,9 +8994,13 @@ static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) wc_curve448_free((curve448_key*)keyShareEntry->key); XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); keyShareEntry->key = NULL; + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + keyShareEntry->ke = NULL; #else (void)ssl; (void)keyShareEntry; + (void)ssOutput; + (void)ssOutSz; ret = PEER_KEY_ERROR; WOLFSSL_ERROR_VERBOSE(ret); @@ -8661,13 +9009,31 @@ static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) return ret; } +/* Process the X448 key share extension on the client side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to use to calculate shared secret. + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) +{ + return TLSX_KeyShare_ProcessX448_ex(ssl, keyShareEntry, + ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz); +} + /* Process the ECC key share extension on the client side. * * ssl The SSL/TLS object. * keyShareEntry The key share entry object to use to calculate shared secret. + * ssOutput The destination buffer for the shared secret. + * ssOutSz The size of the generated shared secret. + * * returns 0 on success and other values indicate failure. */ -static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) +static int TLSX_KeyShare_ProcessEcc_ex(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, + unsigned char* ssOutput, + word32* ssOutSz) { int ret = 0; #ifdef HAVE_ECC @@ -8767,9 +9133,7 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) if (ret == 0) { ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey, keyShareEntry->ke, &keyShareEntry->keLen, - ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, - ssl->options.side - ); + ssOutput, ssOutSz, ssl->options.side); #ifdef WOLFSSL_ASYNC_CRYPT if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; @@ -8797,6 +9161,8 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) #else (void)ssl; (void)keyShareEntry; + (void)ssOutput; + (void)ssOutSz; ret = PEER_KEY_ERROR; WOLFSSL_ERROR_VERBOSE(ret); @@ -8805,174 +9171,364 @@ static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) return ret; } -#ifdef WOLFSSL_HAVE_KYBER -/* Process the Kyber key share extension on the client side. +/* Process the ECC key share extension on the client side. * * ssl The SSL/TLS object. * keyShareEntry The key share entry object to use to calculate shared secret. * returns 0 on success and other values indicate failure. */ -static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) +static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) { - int ret = 0; - int type; - KyberKey kem[1]; - byte* sharedSecret = NULL; - word32 sharedSecretLen = 0; - int oqs_group = 0; - int ecc_group = 0; - ecc_key eccpubkey; - word32 outlen = 0; - word32 privSz = 0; - word32 ctSz = 0; - word32 ssSz = 0; + return TLSX_KeyShare_ProcessEcc_ex(ssl, keyShareEntry, + ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz); +} - if (keyShareEntry->ke == NULL) { - WOLFSSL_MSG("Invalid OQS algorithm specified."); - return BAD_FUNC_ARG; - } +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Process the Kyber key share extension on the client side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to use to calculate shared secret. + * ssOutput The destination buffer for the shared secret. + * ssOutSz The size of the generated shared secret. + * + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_ProcessPqcClient_ex(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, + unsigned char* ssOutput, + word32* ssOutSz) +{ + int ret = 0; + KyberKey* kem = (KyberKey*)keyShareEntry->key; +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + word32 privSz = 0; +#endif + word32 ctSz = 0; + word32 ssSz = 0; if (ssl->options.side == WOLFSSL_SERVER_END) { /* I am the server, the shared secret has already been generated and - * is in keyShareEntry->ke; copy it to the pre-master secret - * pre-allocated buffer. */ - if (keyShareEntry->keLen > ENCRYPT_LEN) { - WOLFSSL_MSG("shared secret is too long."); - return LENGTH_ERROR; - } - - XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke, - keyShareEntry->keLen); - ssl->arrays->preMasterSz = keyShareEntry->keLen; - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET); - keyShareEntry->ke = NULL; - keyShareEntry->keLen = 0; + * is in ssl->arrays->preMasterSecret, so nothing really to do here. */ return 0; } - /* I am the client, the ciphertext is in keyShareEntry->ke */ - findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group); - - ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId); - if (ret != 0) { - WOLFSSL_MSG("Memory allocation error."); - return MEMORY_E; - } - - ret = kyber_id2type(oqs_group, &type); - if (ret != 0) { - wc_ecc_free(&eccpubkey); - WOLFSSL_MSG("Invalid OQS algorithm specified."); + if (keyShareEntry->ke == NULL) { + WOLFSSL_MSG("Invalid PQC algorithm specified."); return BAD_FUNC_ARG; } + if (ssOutSz == NULL) + return BAD_FUNC_ARG; - ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId); - if (ret != 0) { - wc_ecc_free(&eccpubkey); - WOLFSSL_MSG("Error creating Kyber KEM"); - return MEMORY_E; - } +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + if (kem == NULL) { + int type = 0; - if (ret == 0) { - ret = wc_KyberKey_SharedSecretSize(kem, &ssSz); - } - if (ret == 0) { - sharedSecretLen = ssSz; - switch (ecc_group) { - case WOLFSSL_ECC_SECP256R1: - sharedSecretLen += 32; - outlen = 32; - break; - case WOLFSSL_ECC_SECP384R1: - sharedSecretLen += 48; - outlen = 48; - break; - case WOLFSSL_ECC_SECP521R1: - sharedSecretLen += 66; - outlen = 66; - break; - default: - break; + /* Allocate a Kyber key to hold private key. */ + kem = (KyberKey*) XMALLOC(sizeof(KyberKey), ssl->heap, + DYNAMIC_TYPE_PRIVATE_KEY); + if (kem == NULL) { + WOLFSSL_MSG("GenPqcKey memory error"); + ret = MEMORY_E; + } + if (ret == 0) { + ret = mlkem_id2type(keyShareEntry->group, &type); + } + if (ret != 0) { + WOLFSSL_MSG("Invalid PQC algorithm specified."); + ret = BAD_FUNC_ARG; } + if (ret == 0) { + ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId); + if (ret != 0) { + WOLFSSL_MSG("Error creating Kyber KEM"); + } + } + } +#else + if (kem == NULL || keyShareEntry->privKeyLen != 0) { + WOLFSSL_MSG("Invalid Kyber key."); + ret = BAD_FUNC_ARG; } +#endif + if (ret == 0) { - sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap, - DYNAMIC_TYPE_TLSX); - if (sharedSecret == NULL) { - WOLFSSL_MSG("Memory allocation error."); - ret = MEMORY_E; - } + ret = wc_KyberKey_SharedSecretSize(kem, &ssSz); } if (ret == 0) { ret = wc_KyberKey_CipherTextSize(kem, &ctSz); } + +#ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ if (ret == 0) { ret = wc_KyberKey_PrivateKeySize(kem, &privSz); } + if (ret == 0 && privSz != keyShareEntry->privKeyLen) { + WOLFSSL_MSG("Invalid private key size."); + ret = BAD_FUNC_ARG; + } if (ret == 0) { ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz); } +#endif + if (ret == 0) { - ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen, - keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz); + ret = wc_KyberKey_Decapsulate(kem, ssOutput, + keyShareEntry->ke, ctSz); if (ret != 0) { WOLFSSL_MSG("wc_KyberKey decapsulation failure."); ret = BAD_FUNC_ARG; } } + if (ret == 0) { + *ssOutSz = ssSz; + } + + wc_KyberKey_Free(kem); + + XFREE(kem, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->key = NULL; + + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + keyShareEntry->ke = NULL; + + return ret; +} + +/* Process the Kyber key share extension on the client side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to use to calculate shared secret. + * + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_ProcessPqcClient(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry) +{ + return TLSX_KeyShare_ProcessPqcClient_ex(ssl, keyShareEntry, + ssl->arrays->preMasterSecret, + &ssl->arrays->preMasterSz); +} + +/* Process the hybrid key share extension on the client side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to use to calculate shared secret. + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_ProcessPqcHybridClient(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry) +{ + int ret = 0; + int pqc_group = 0; + int ecc_group = 0; + int pqc_first = 0; + KeyShareEntry* pqc_kse = NULL; + KeyShareEntry *ecc_kse = NULL; + word32 ctSz = 0; + word32 ssSzPqc = 0; + word32 ssSzEcc = 0; + + if (ssl->options.side == WOLFSSL_SERVER_END) { + /* I am the server, the shared secret has already been generated and + * is in ssl->arrays->preMasterSecret, so nothing really to do here. */ + return 0; + } + + if (keyShareEntry->ke == NULL) { + WOLFSSL_MSG("Invalid PQC algorithm specified."); + return BAD_FUNC_ARG; + } + + /* I am the client, both the PQC ciphertext and the ECHD public key are in + * keyShareEntry->ke */ + + /* Determine the ECC and PQC group of the hybrid combination */ + findEccPqc(&ecc_group, &pqc_group, &pqc_first, keyShareEntry->group); + if (ecc_group == 0 || pqc_group == 0) { + WOLFSSL_MSG("Invalid hybrid group"); + ret = BAD_FUNC_ARG; + } - if (ecc_group != 0) { + if (ret == 0) { + ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (ecc_kse == NULL) { + WOLFSSL_MSG("kse memory allocation failure"); + ret = MEMORY_ERROR; + } + else { + XMEMSET(ecc_kse, 0, sizeof(*ecc_kse)); + } + } + if (ret == 0) { + pqc_kse = (KeyShareEntry*)XMALLOC(sizeof(*pqc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (pqc_kse == NULL) { + WOLFSSL_MSG("kse memory allocation failure"); + ret = MEMORY_ERROR; + } + else { + XMEMSET(pqc_kse, 0, sizeof(*pqc_kse)); + } + } + + /* The ciphertext and shared secret sizes of a KEM are fixed. Hence, we + * decode these sizes to separate the KEM ciphertext from the ECDH public + * key. */ + if (ret == 0) { + #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ + int type; + + pqc_kse->privKey = keyShareEntry->privKey; + + ret = mlkem_id2type(pqc_group, &type); + if (ret != 0) { + WOLFSSL_MSG("Invalid Kyber algorithm specified."); + ret = BAD_FUNC_ARG; + } if (ret == 0) { - /* Point is validated by import function. */ - ret = wc_ecc_import_x963(keyShareEntry->ke, - keyShareEntry->keLen - ctSz, - &eccpubkey); - if (ret != 0) { - WOLFSSL_MSG("ECC Public key import error."); + pqc_kse->key = XMALLOC(sizeof(KyberKey), ssl->heap, + DYNAMIC_TYPE_PRIVATE_KEY); + if (pqc_kse->key == NULL) { + WOLFSSL_MSG("GenPqcKey memory error"); + ret = MEMORY_E; } } - -#if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \ - (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ - !defined(HAVE_SELFTEST) if (ret == 0) { - ret = wc_ecc_set_rng((ecc_key *)keyShareEntry->key, ssl->rng); + ret = wc_KyberKey_Init(type, (KyberKey*)pqc_kse->key, + ssl->heap, ssl->devId); if (ret != 0) { - WOLFSSL_MSG("Failure to set the ECC private key RNG."); + WOLFSSL_MSG("Error creating Kyber KEM"); } } -#endif + #else + pqc_kse->key = keyShareEntry->privKey; + #endif + + pqc_kse->group = pqc_group; + pqc_kse->privKeyLen = keyShareEntry->privKeyLen; if (ret == 0) { - PRIVATE_KEY_UNLOCK(); - ret = wc_ecc_shared_secret((ecc_key *)keyShareEntry->key, - &eccpubkey, sharedSecret, &outlen); - PRIVATE_KEY_LOCK(); - if (outlen != sharedSecretLen - ssSz) { - WOLFSSL_MSG("ECC shared secret derivation error."); + ret = wc_KyberKey_SharedSecretSize((KyberKey*)pqc_kse->key, + &ssSzPqc); + } + if (ret == 0) { + ret = wc_KyberKey_CipherTextSize((KyberKey*)pqc_kse->key, + &ctSz); + if (ret == 0 && keyShareEntry->keLen <= ctSz) { + WOLFSSL_MSG("Invalid ciphertext size."); ret = BAD_FUNC_ARG; } } + if (ret == 0) { + pqc_kse->keLen = ctSz; + pqc_kse->ke = (byte*)XMALLOC(pqc_kse->keLen, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (pqc_kse->ke == NULL) { + WOLFSSL_MSG("pqc_kse memory allocation failure"); + ret = MEMORY_ERROR; + } + /* Copy the PQC KEM ciphertext. Depending on the pqc_first flag, + * the KEM ciphertext comes before or after the ECDH public key. */ + if (ret == 0) { + int offset = keyShareEntry->keLen - ctSz; + + if (pqc_first) + offset = 0; + + XMEMCPY(pqc_kse->ke, keyShareEntry->ke + offset, ctSz); + } + } } - if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) { - WOLFSSL_MSG("shared secret is too long."); - ret = LENGTH_ERROR; + + if (ret == 0) { + ecc_kse->group = ecc_group; + ecc_kse->keLen = keyShareEntry->keLen - ctSz; + ecc_kse->key = keyShareEntry->key; + ecc_kse->ke = (byte*)XMALLOC(ecc_kse->keLen, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (ecc_kse->ke == NULL) { + WOLFSSL_MSG("ecc_kse memory allocation failure"); + ret = MEMORY_ERROR; + } + /* Copy the ECDH public key. Depending on the pqc_first flag, the + * KEM ciphertext comes before or after the ECDH public key. */ + if (ret == 0) { + int offset = 0; + + if (pqc_first) + offset = ctSz; + + XMEMCPY(ecc_kse->ke, keyShareEntry->ke + offset, ecc_kse->keLen); + } + } + + /* Process ECDH key share part. The generated shared secret is directly + * stored in the ssl->arrays->preMasterSecret buffer. Depending on the + * pqc_first flag, the ECDH shared secret part goes before or after the + * KEM part. */ + if (ret == 0) { + int offset = 0; + + /* Set the ECC size variable to the initial buffer size */ + ssSzEcc = ssl->arrays->preMasterSz; + + if (pqc_first) + offset = ssSzPqc; + + #ifdef HAVE_CURVE25519 + if (ecc_group == WOLFSSL_ECC_X25519) { + ret = TLSX_KeyShare_ProcessX25519_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + offset, &ssSzEcc); + } + else + #endif + #ifdef HAVE_CURVE448 + if (ecc_group == WOLFSSL_ECC_X448) { + ret = TLSX_KeyShare_ProcessX448_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + offset, &ssSzEcc); + } + else + #endif + { + ret = TLSX_KeyShare_ProcessEcc_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + offset, &ssSzEcc); + } + } + + if (ret == 0) { + keyShareEntry->key = ecc_kse->key; + + if ((ret == 0) && ((ssSzEcc + ssSzPqc) > ENCRYPT_LEN)) { + WOLFSSL_MSG("shared secret is too long."); + ret = LENGTH_ERROR; + } + } + + /* Process PQC KEM key share part. Depending on the pqc_first flag, the + * KEM shared secret part goes before or after the ECDH part. */ + if (ret == 0) { + int offset = ssSzEcc; + + if (pqc_first) + offset = 0; + + ret = TLSX_KeyShare_ProcessPqcClient_ex(ssl, pqc_kse, + ssl->arrays->preMasterSecret + offset, &ssSzPqc); } if (ret == 0) { - /* Copy the shared secret to the pre-master secret pre-allocated - * buffer. */ - XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen); - ssl->arrays->preMasterSz = (word32) sharedSecretLen; + keyShareEntry->privKey = (byte*)pqc_kse->key; + + ssl->arrays->preMasterSz = ssSzEcc + ssSzPqc; } - XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); + TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); + TLSX_KeyShare_FreeAll(pqc_kse, ssl->heap); - wc_ecc_free(&eccpubkey); - wc_KyberKey_Free(kem); return ret; } -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_MLKEM_NO_DECAPSULATE */ /* Process the key share extension on the client side. * @@ -8992,15 +9548,17 @@ static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) ssl->arrays->preMasterSz = ENCRYPT_LEN; /* Use Key Share Data from server. */ - if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group)) + if (WOLFSSL_NAMED_GROUP_IS_FFDHE(keyShareEntry->group)) ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry); else if (keyShareEntry->group == WOLFSSL_ECC_X25519) ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry); else if (keyShareEntry->group == WOLFSSL_ECC_X448) ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry); -#ifdef WOLFSSL_HAVE_KYBER +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group)) - ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry); + ret = TLSX_KeyShare_ProcessPqcClient(ssl, keyShareEntry); + else if (WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(keyShareEntry->group)) + ret = TLSX_KeyShare_ProcessPqcHybridClient(ssl, keyShareEntry); #endif else ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry); @@ -9049,11 +9607,18 @@ static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input, if (keLen > length - offset) return BUFFER_ERROR; -#ifdef WOLFSSL_HAVE_KYBER - if (WOLFSSL_NAMED_GROUP_IS_PQC(group) && +#ifdef WOLFSSL_HAVE_MLKEM + if ((WOLFSSL_NAMED_GROUP_IS_PQC(group) || + WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) && ssl->options.side == WOLFSSL_SERVER_END) { - /* For KEMs, the public key is not stored. Casting away const because - * we know for KEMs, it will be read-only.*/ + /* When handling a key share containing a KEM public key on the server + * end, we have to perform the encapsulation immediately in order to + * send the resulting ciphertext back to the client in the ServerHello + * message. As the public key is not stored and we do not modify it, we + * don't have to create a copy of it. + * In case of a hybrid key exchange, the ECDH part is also performed + * immediately (to not split the generation of the master secret). + * Hence, we also don't have to store this public key either. */ ke = (byte *)&input[offset]; } else #endif @@ -9228,7 +9793,7 @@ int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length, /* Not in list sent if there isn't a private key. */ if (keyShareEntry == NULL || (keyShareEntry->key == NULL - #if !defined(NO_DH) || defined(WOLFSSL_HAVE_KYBER) + #if !defined(NO_DH) || defined(WOLFSSL_HAVE_MLKEM) && keyShareEntry->privKey == NULL #endif )) { @@ -9253,13 +9818,15 @@ int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length, if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif { - /* Check the selected group was supported by ClientHello extensions. */ + /* Check the selected group was supported by ClientHello extensions. + */ if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) { WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA); return BAD_KEY_SHARE_DATA; } - /* Check if the group was sent. */ + /* Make sure KeyShare for server requested group was not sent in + * ClientHello. */ if (TLSX_KeyShare_Find(ssl, group)) { WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA); return BAD_KEY_SHARE_DATA; @@ -9320,76 +9887,228 @@ static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap, return 0; } -#ifdef WOLFSSL_HAVE_KYBER -static int server_generate_pqc_ciphertext(WOLFSSL* ssl, - KeyShareEntry* keyShareEntry, byte* data, word16 len) -{ - /* I am the server. The data parameter is the client's public key. I need - * to generate the public information (AKA ciphertext) and shared secret - * here. Note the "public information" is equivalent to a the public key in - * key exchange parlance. That's why it is being assigned to pubKey. - */ - int type; - KyberKey kem[1]; - byte* sharedSecret = NULL; +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) +/* Process the Kyber key share extension on the server side. + * + * ssl The SSL/TLS object. + * keyShareEntry The key share entry object to be sent to the client. + * data The key share data received from the client. + * len The length of the key share data from the client. + * ssOutput The destination buffer for the shared secret. + * ssOutSz The size of the generated shared secret. + * + * returns 0 on success and other values indicate failure. + */ +static int TLSX_KeyShare_HandlePqcKeyServer(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, byte* clientData, word16 clientLen, + unsigned char* ssOutput, word32* ssOutSz) +{ + /* We are on the server side. The key share contains a PQC KEM public key + * that we are using for an encapsulate operation. The resulting ciphertext + * is stored in the server key share. */ + KyberKey* kemKey = (KyberKey*)keyShareEntry->key; byte* ciphertext = NULL; int ret = 0; - int oqs_group = 0; - int ecc_group = 0; - KeyShareEntry *ecc_kse = NULL; - ecc_key eccpubkey; - word32 outlen = 0; word32 pubSz = 0; word32 ctSz = 0; word32 ssSz = 0; - findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group); - ret = kyber_id2type(oqs_group, &type); - if (ret != 0) { - WOLFSSL_MSG("Invalid Kyber algorithm specified."); + if (clientData == NULL) { + WOLFSSL_MSG("No KEM public key from the client."); return BAD_FUNC_ARG; } - ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId); - if (ret != 0) { - WOLFSSL_MSG("Could not do ECC public key initialization."); - return MEMORY_E; + if (kemKey == NULL) { + int type = 0; + + /* Allocate a Kyber key to hold private key. */ + kemKey = (KyberKey*) XMALLOC(sizeof(KyberKey), ssl->heap, + DYNAMIC_TYPE_PRIVATE_KEY); + if (kemKey == NULL) { + WOLFSSL_MSG("GenPqcKey memory error"); + ret = MEMORY_E; + } + if (ret == 0) { + ret = mlkem_id2type(keyShareEntry->group, &type); + } + if (ret != 0) { + WOLFSSL_MSG("Invalid PQC algorithm specified."); + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + ret = wc_KyberKey_Init(type, kemKey, ssl->heap, ssl->devId); + if (ret != 0) { + WOLFSSL_MSG("Error creating Kyber KEM"); + } + } } - ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId); - if (ret != 0) { - wc_ecc_free(&eccpubkey); - WOLFSSL_MSG("Error creating Kyber KEM"); - return MEMORY_E; + if (ret == 0) { + ret = wc_KyberKey_PublicKeySize(kemKey, &pubSz); + } + if (ret == 0) { + ret = wc_KyberKey_CipherTextSize(kemKey, &ctSz); + } + if (ret == 0) { + ret = wc_KyberKey_SharedSecretSize(kemKey, &ssSz); + } + + if (ret == 0 && clientLen != pubSz) { + WOLFSSL_MSG("Invalid public key."); + ret = BAD_FUNC_ARG; } if (ret == 0) { - ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap, - DYNAMIC_TYPE_TLSX); - if (ecc_kse == NULL) { - WOLFSSL_MSG("ecc_kse memory allocation failure"); - ret = MEMORY_ERROR; + ciphertext = (byte*)XMALLOC(ctSz, ssl->heap, DYNAMIC_TYPE_TLSX); + + if (ciphertext == NULL) { + WOLFSSL_MSG("Ciphertext memory allocation failure."); + ret = MEMORY_E; } } if (ret == 0) { - XMEMSET(ecc_kse, 0, sizeof(*ecc_kse)); + ret = wc_KyberKey_DecodePublicKey(kemKey, clientData, pubSz); } - - if (ret == 0 && ecc_group != 0) { - ecc_kse->group = ecc_group; - ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse); - /* No message, TLSX_KeyShare_GenEccKey() will do it. */ + if (ret == 0) { + ret = wc_KyberKey_Encapsulate(kemKey, ciphertext, + ssOutput, ssl->rng); + if (ret != 0) { + WOLFSSL_MSG("wc_KyberKey encapsulation failure."); + } } if (ret == 0) { - ret = wc_KyberKey_PublicKeySize(kem, &pubSz); + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + + *ssOutSz = ssSz; + keyShareEntry->ke = NULL; + keyShareEntry->keLen = 0; + + keyShareEntry->pubKey = ciphertext; + keyShareEntry->pubKeyLen = ctSz; + ciphertext = NULL; + + /* Set namedGroup so wolfSSL_get_curve_name() can function properly on + * the server side. */ + ssl->namedGroup = keyShareEntry->group; + } + + XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); + + wc_KyberKey_Free(kemKey); + XFREE(kemKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->key = NULL; + return ret; +} + +static int TLSX_KeyShare_HandlePqcHybridKeyServer(WOLFSSL* ssl, + KeyShareEntry* keyShareEntry, byte* data, word16 len) +{ + /* I am the server. The data parameter is the concatenation of the client's + * ECDH public key and the KEM public key. I need to generate a matching + * public key for ECDH and encapsulate a shared secret using the KEM public + * key. We send the ECDH public key and the KEM ciphertext back to the + * client. Additionally, we create the ECDH shared secret here already. + */ + int type; + byte* ciphertext = NULL; + int ret = 0; + int pqc_group = 0; + int ecc_group = 0; + int pqc_first = 0; + KeyShareEntry *ecc_kse = NULL; + KeyShareEntry *pqc_kse = NULL; + word32 pubSz = 0; + word32 ctSz = 0; + word32 ssSzPqc = 0; + word32 ssSzEcc = 0; + + if (data == NULL) { + WOLFSSL_MSG("No hybrid key share data from the client."); + return BAD_FUNC_ARG; + } + + /* Determine the ECC and PQC group of the hybrid combination */ + findEccPqc(&ecc_group, &pqc_group, &pqc_first, keyShareEntry->group); + if (ecc_group == 0 || pqc_group == 0) { + WOLFSSL_MSG("Invalid hybrid group"); + ret = BAD_FUNC_ARG; } + if (ret == 0) { - ret = wc_KyberKey_CipherTextSize(kem, &ctSz); + ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + pqc_kse = (KeyShareEntry*)XMALLOC(sizeof(*pqc_kse), ssl->heap, + DYNAMIC_TYPE_TLSX); + if (ecc_kse == NULL || pqc_kse == NULL) { + WOLFSSL_MSG("kse memory allocation failure"); + ret = MEMORY_ERROR; + } } + + /* The ciphertext and shared secret sizes of a KEM are fixed. Hence, we + * decode these sizes to properly concatenate the KEM ciphertext with the + * ECDH public key. */ if (ret == 0) { - ret = wc_KyberKey_SharedSecretSize(kem, &ssSz); + XMEMSET(pqc_kse, 0, sizeof(*pqc_kse)); + pqc_kse->group = pqc_group; + + /* Allocate a Kyber key to hold private key. */ + pqc_kse->key = (KyberKey*) XMALLOC(sizeof(KyberKey), ssl->heap, + DYNAMIC_TYPE_PRIVATE_KEY); + if (pqc_kse->key == NULL) { + WOLFSSL_MSG("GenPqcKey memory error"); + ret = MEMORY_E; + } + if (ret == 0) { + ret = mlkem_id2type(pqc_kse->group, &type); + } + if (ret != 0) { + WOLFSSL_MSG("Invalid PQC algorithm specified."); + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + ret = wc_KyberKey_Init(type, (KyberKey*)pqc_kse->key, + ssl->heap, ssl->devId); + if (ret != 0) { + WOLFSSL_MSG("Error creating Kyber KEM"); + } + } + if (ret == 0) { + ret = wc_KyberKey_SharedSecretSize((KyberKey*)pqc_kse->key, + &ssSzPqc); + } + if (ret == 0) { + ret = wc_KyberKey_CipherTextSize((KyberKey*)pqc_kse->key, + &ctSz); + } + if (ret == 0) { + ret = wc_KyberKey_PublicKeySize((KyberKey*)pqc_kse->key, + &pubSz); + } + } + + /* Generate the ECDH key share part to be sent to the client */ + if (ret == 0 && ecc_group != 0) { + XMEMSET(ecc_kse, 0, sizeof(*ecc_kse)); + ecc_kse->group = ecc_group; + #ifdef HAVE_CURVE25519 + if (ecc_group == WOLFSSL_ECC_X25519) { + ret = TLSX_KeyShare_GenX25519Key(ssl, ecc_kse); + } + else + #endif + #ifdef HAVE_CURVE448 + if (ecc_group == WOLFSSL_ECC_X448) { + ret = TLSX_KeyShare_GenX448Key(ssl, ecc_kse); + } + else + #endif + { + ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse); + } + /* No error message, TLSX_KeyShare_GenKey will do it. */ } if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) { @@ -9397,72 +10116,113 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, ret = BAD_FUNC_ARG; } + /* Allocate buffer for the concatenated client key share data + * (PQC KEM ciphertext + ECDH public key) */ if (ret == 0) { - sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap, - DYNAMIC_TYPE_SECRET); ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap, DYNAMIC_TYPE_TLSX); - if (sharedSecret == NULL || ciphertext == NULL) { - WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure."); + if (ciphertext == NULL) { + WOLFSSL_MSG("Ciphertext memory allocation failure."); ret = MEMORY_E; } } - if (ecc_group != 0) { + /* Process ECDH key share part. The generated shared secret is directly + * stored in the ssl->arrays->preMasterSecret buffer. Depending on the + * pqc_first flag, the ECDH shared secret part goes before or after the + * KEM part. */ + if (ret == 0) { + ecc_kse->keLen = len - pubSz; + ecc_kse->ke = (byte*)XMALLOC(ecc_kse->keLen, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (ecc_kse->ke == NULL) { + WOLFSSL_MSG("ecc_kse memory allocation failure"); + ret = MEMORY_ERROR; + } if (ret == 0) { - /* Point is validated by import function. */ - ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey); - if (ret != 0) { - WOLFSSL_MSG("Bad ECC public key."); + int pubOffset = 0; + int ssOffset = 0; + + /* Set the ECC size variable to the initial buffer size */ + ssSzEcc = ssl->arrays->preMasterSz; + + if (pqc_first) { + pubOffset = pubSz; + ssOffset = ssSzPqc; } - } -#if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \ - (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \ - !defined(HAVE_SELFTEST) - if (ret == 0) { - ret = wc_ecc_set_rng((ecc_key *)ecc_kse->key, ssl->rng); - } -#endif + XMEMCPY(ecc_kse->ke, data + pubOffset, ecc_kse->keLen); + #ifdef HAVE_CURVE25519 + if (ecc_group == WOLFSSL_ECC_X25519) { + ret = TLSX_KeyShare_ProcessX25519_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); + } + else + #endif + #ifdef HAVE_CURVE448 + if (ecc_group == WOLFSSL_ECC_X448) { + ret = TLSX_KeyShare_ProcessX448_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); + } + else + #endif + { + ret = TLSX_KeyShare_ProcessEcc_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); + } + } if (ret == 0) { - outlen = ecc_kse->keyLen; - PRIVATE_KEY_UNLOCK(); - ret = wc_ecc_shared_secret((ecc_key *)ecc_kse->key, &eccpubkey, - sharedSecret, - &outlen); - PRIVATE_KEY_LOCK(); - if (outlen != ecc_kse->keyLen) { + if (ssSzEcc != ecc_kse->keyLen) { WOLFSSL_MSG("Data length mismatch."); ret = BAD_FUNC_ARG; } } } - if (ret == 0) { - ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen, - pubSz); + if (ret == 0 && ssSzEcc + ssSzPqc > ENCRYPT_LEN) { + WOLFSSL_MSG("shared secret is too long."); + ret = LENGTH_ERROR; } + + /* Process PQC KEM key share part. Depending on the pqc_first flag, the + * KEM shared secret part goes before or after the ECDH part. */ if (ret == 0) { - ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen, - sharedSecret + outlen, ssl->rng); - if (ret != 0) { - WOLFSSL_MSG("wc_KyberKey encapsulation failure."); + int input_offset = ecc_kse->keLen; + int output_offset = ssSzEcc; + + if (pqc_first) { + input_offset = 0; + output_offset = 0; } + + ret = TLSX_KeyShare_HandlePqcKeyServer(ssl, pqc_kse, + data + input_offset, pubSz, + ssl->arrays->preMasterSecret + output_offset, &ssSzPqc); } if (ret == 0) { XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - keyShareEntry->ke = sharedSecret; - keyShareEntry->keLen = outlen + ssSz; - sharedSecret = NULL; + ssl->arrays->preMasterSz = ssSzEcc + ssSzPqc; + keyShareEntry->ke = NULL; + keyShareEntry->keLen = 0; - if (ecc_kse->pubKeyLen > 0) + /* Concatenate the ECDH public key and the PQC KEM ciphertext. Based on + * the pqc_first flag, the ECDH public key goes before or after the KEM + * ciphertext. */ + if (pqc_first) { + XMEMCPY(ciphertext, pqc_kse->pubKey, ctSz); + XMEMCPY(ciphertext + ctSz, ecc_kse->pubKey, ecc_kse->pubKeyLen); + } + else { XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen); + XMEMCPY(ciphertext + ecc_kse->pubKeyLen, pqc_kse->pubKey, ctSz); + } + keyShareEntry->pubKey = ciphertext; - keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz); + keyShareEntry->pubKeyLen = ecc_kse->pubKeyLen + ctSz; ciphertext = NULL; /* Set namedGroup so wolfSSL_get_curve_name() can function properly on @@ -9471,13 +10231,11 @@ static int server_generate_pqc_ciphertext(WOLFSSL* ssl, } TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); - XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET); + TLSX_KeyShare_FreeAll(pqc_kse, ssl->heap); XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); - wc_ecc_free(&eccpubkey); - wc_KyberKey_Free(kem); return ret; } -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_MLKEM_NO_ENCAPSULATE */ /* Use the data to create a new key share object in the extensions. * @@ -9526,11 +10284,22 @@ int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data, } -#ifdef WOLFSSL_HAVE_KYBER - if (WOLFSSL_NAMED_GROUP_IS_PQC(group) && - ssl->options.side == WOLFSSL_SERVER_END) { - ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data, - len); +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) + if (ssl->options.side == WOLFSSL_SERVER_END && + WOLFSSL_NAMED_GROUP_IS_PQC(group)) { + ret = TLSX_KeyShare_HandlePqcKeyServer((WOLFSSL*)ssl, + keyShareEntry, + data, len, + ssl->arrays->preMasterSecret, + &ssl->arrays->preMasterSz); + if (ret != 0) + return ret; + } + else if (ssl->options.side == WOLFSSL_SERVER_END && + WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) { + ret = TLSX_KeyShare_HandlePqcHybridKeyServer((WOLFSSL*)ssl, + keyShareEntry, + data, len); if (ret != 0) return ret; } @@ -9691,54 +10460,93 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) break; #endif #endif -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM #ifndef WOLFSSL_NO_ML_KEM - #ifdef WOLFSSL_WC_KYBER + #ifdef WOLFSSL_WC_MLKEM #ifndef WOLFSSL_NO_ML_KEM_512 case WOLFSSL_ML_KEM_512: case WOLFSSL_P256_ML_KEM_512: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_ML_KEM_512: + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_768 case WOLFSSL_ML_KEM_768: case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P256_ML_KEM_768: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_ML_KEM_768: + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + case WOLFSSL_X448_ML_KEM_768: + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_1024 case WOLFSSL_ML_KEM_1024: case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_P384_ML_KEM_1024: #endif break; #elif defined(HAVE_LIBOQS) case WOLFSSL_ML_KEM_512: case WOLFSSL_ML_KEM_768: case WOLFSSL_ML_KEM_1024: + { + int ret; + int id; + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } + + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } case WOLFSSL_P256_ML_KEM_512: case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P256_ML_KEM_768: case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_P384_ML_KEM_1024: + case WOLFSSL_X25519_ML_KEM_512: + case WOLFSSL_X448_ML_KEM_768: + case WOLFSSL_X25519_ML_KEM_768: { int ret; int id; - findEccPqc(NULL, &namedGroup, namedGroup); - ret = kyber_id2type(namedGroup, &id); + findEccPqc(NULL, &namedGroup, NULL, namedGroup); + ret = mlkem_id2type(namedGroup, &id); if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { return 0; } - if (! ext_kyber_enabled(id)) { + if (! ext_mlkem_enabled(id)) { return 0; } break; } #endif -#endif -#ifdef WOLFSSL_KYBER_ORIGINAL - #ifdef WOLFSSL_WC_KYBER +#endif /* WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_WC_MLKEM #ifdef WOLFSSL_KYBER512 case WOLFSSL_KYBER_LEVEL1: case WOLFSSL_P256_KYBER_LEVEL1: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_KYBER_LEVEL1: + #endif #endif #ifdef WOLFSSL_KYBER768 case WOLFSSL_KYBER_LEVEL3: case WOLFSSL_P384_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL3: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_KYBER_LEVEL3: + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + case WOLFSSL_X448_KYBER_LEVEL3: + #endif #endif #ifdef WOLFSSL_KYBER1024 case WOLFSSL_KYBER_LEVEL5: @@ -9749,26 +10557,43 @@ static int TLSX_KeyShare_IsSupported(int namedGroup) case WOLFSSL_KYBER_LEVEL1: case WOLFSSL_KYBER_LEVEL3: case WOLFSSL_KYBER_LEVEL5: + { + int ret; + int id; + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } + + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } case WOLFSSL_P256_KYBER_LEVEL1: case WOLFSSL_P384_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL3: case WOLFSSL_P521_KYBER_LEVEL5: + case WOLFSSL_X25519_KYBER_LEVEL1: + case WOLFSSL_X448_KYBER_LEVEL3: + case WOLFSSL_X25519_KYBER_LEVEL3: { int ret; int id; - findEccPqc(NULL, &namedGroup, namedGroup); - ret = kyber_id2type(namedGroup, &id); + findEccPqc(NULL, &namedGroup, NULL, namedGroup); + ret = mlkem_id2type(namedGroup, &id); if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { return 0; } - if (! ext_kyber_enabled(id)) { + if (! ext_mlkem_enabled(id)) { return 0; } break; } #endif #endif -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM */ default: return 0; } @@ -9815,18 +10640,29 @@ static const word16 preferredGroup[] = { WOLFSSL_FFDHE_8192, #endif #ifndef WOLFSSL_NO_ML_KEM -#ifdef WOLFSSL_WC_KYBER +#ifdef WOLFSSL_WC_MLKEM #ifndef WOLFSSL_NO_ML_KEM_512 WOLFSSL_ML_KEM_512, WOLFSSL_P256_ML_KEM_512, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_ML_KEM_512, + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_768 WOLFSSL_ML_KEM_768, WOLFSSL_P384_ML_KEM_768, + WOLFSSL_P256_ML_KEM_768, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_ML_KEM_768, + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + WOLFSSL_X448_ML_KEM_768, + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_1024 WOLFSSL_ML_KEM_1024, WOLFSSL_P521_ML_KEM_1024, + WOLFSSL_P384_ML_KEM_1024, #endif #elif defined(HAVE_LIBOQS) /* These require a runtime call to TLSX_KeyShare_IsSupported to use */ @@ -9835,18 +10671,37 @@ static const word16 preferredGroup[] = { WOLFSSL_ML_KEM_1024, WOLFSSL_P256_ML_KEM_512, WOLFSSL_P384_ML_KEM_768, + WOLFSSL_P256_ML_KEM_768, WOLFSSL_P521_ML_KEM_1024, + WOLFSSL_P384_ML_KEM_1024, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_ML_KEM_512, + WOLFSSL_X25519_ML_KEM_768, + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + WOLFSSL_X448_ML_KEM_768, + #endif #endif #endif /* !WOLFSSL_NO_ML_KEM */ -#ifdef WOLFSSL_KYBER_ORIGINAL -#ifdef WOLFSSL_WC_KYBER +#ifdef WOLFSSL_MLKEM_KYBER +#ifdef WOLFSSL_WC_MLKEM #ifdef WOLFSSL_KYBER512 WOLFSSL_KYBER_LEVEL1, WOLFSSL_P256_KYBER_LEVEL1, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_KYBER_LEVEL1, + #endif #endif #ifdef WOLFSSL_KYBER768 WOLFSSL_KYBER_LEVEL3, WOLFSSL_P384_KYBER_LEVEL3, + WOLFSSL_P256_KYBER_LEVEL3, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_KYBER_LEVEL3, + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + WOLFSSL_X448_KYBER_LEVEL3, + #endif #endif #ifdef WOLFSSL_KYBER1024 WOLFSSL_KYBER_LEVEL5, @@ -9859,9 +10714,17 @@ static const word16 preferredGroup[] = { WOLFSSL_KYBER_LEVEL5, WOLFSSL_P256_KYBER_LEVEL1, WOLFSSL_P384_KYBER_LEVEL3, + WOLFSSL_P256_KYBER_LEVEL3, WOLFSSL_P521_KYBER_LEVEL5, + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + WOLFSSL_X25519_KYBER_LEVEL1, + WOLFSSL_X25519_KYBER_LEVEL3, + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + WOLFSSL_X448_KYBER_LEVEL3, + #endif #endif -#endif /* WOLFSSL_KYBER_ORIGINAL */ +#endif /* WOLFSSL_MLKEM_KYBER */ WOLFSSL_NAMED_GROUP_INVALID }; @@ -9884,8 +10747,7 @@ static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group) byte numGroups; if (ssl->numGroups == 0) { - groups = preferredGroup; - numGroups = PREFERRED_GROUP_SZ; + return 0; } else { groups = ssl->group; @@ -10031,10 +10893,11 @@ int TLSX_CKS_Set(WOLFSSL* ssl, TLSX** extensions) int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length, TLSX** extensions) { - (void) extensions; int ret; int i, j; + (void) extensions; + /* Validating the input. */ if (length == 0) return BUFFER_ERROR; @@ -10154,7 +11017,9 @@ int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions, /* Use server's preference order. */ for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) { - if (clientKSE->ke == NULL) + if ((clientKSE->ke == NULL) && + (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) && + (!WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(clientKSE->group))) continue; #ifdef WOLFSSL_SM2 @@ -10174,11 +11039,12 @@ int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions, if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions)) continue; - if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) { + if (!WOLFSSL_NAMED_GROUP_IS_FFDHE(clientKSE->group)) { /* Check max value supported. */ if (clientKSE->group > WOLFSSL_ECC_MAX) { -#ifdef WOLFSSL_HAVE_KYBER - if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) +#ifdef WOLFSSL_HAVE_MLKEM + if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group) && + !WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(clientKSE->group)) #endif continue; } @@ -10233,7 +11099,7 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) return BAD_FUNC_ARG; } - /* Generate a new key pair except in the case of OQS KEM because we + /* Generate a new key pair except in the case of PQC KEM because we * are going to encapsulate and that does not require us to generate a * key pair. */ @@ -10242,8 +11108,9 @@ int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE) return ret; if (clientKSE->key == NULL) { -#ifdef WOLFSSL_HAVE_KYBER - if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) { +#ifdef WOLFSSL_HAVE_MLKEM + if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group) || + WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(clientKSE->group)) { /* Going to need the public key (AKA ciphertext). */ serverKSE->pubKey = clientKSE->pubKey; clientKSE->pubKey = NULL; @@ -12004,41 +12871,35 @@ static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions, { int ret = 0; int suiteIndex; + TLSX* echX; WOLFSSL_ECH* ech; - if (extensions == NULL) return BAD_FUNC_ARG; - + /* skip if we already have an ech extension, we will for hrr */ + echX = TLSX_Find(*extensions, TLSX_ECH); + if (echX != NULL) + return 0; /* find a supported cipher suite */ suiteIndex = EchConfigGetSupportedCipherSuite(echConfig); - if (suiteIndex < 0) return suiteIndex; - ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ech == NULL) return MEMORY_E; - ForceZero(ech, sizeof(WOLFSSL_ECH)); - ech->state = ECH_WRITE_REAL; - ech->echConfig = echConfig; - /* 0 for outer */ ech->type = ECH_TYPE_OUTER; /* kemId */ ech->kemId = echConfig->kemId; - /* cipherSuite kdf */ ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId; /* cipherSuite aead */ ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId; /* configId */ ech->configId = echConfig->configId; - /* encLen */ switch (echConfig->kemId) { @@ -12058,30 +12919,23 @@ static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions, ech->encLen = DHKEM_X448_ENC_LEN; break; } - /* setup hpke */ ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ech->hpke == NULL) { XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER); return MEMORY_E; } - ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId, ech->cipherSuite.aeadId, heap); - /* setup the ephemeralKey */ if (ret == 0) ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng); - if (ret == 0) ret = TLSX_Push(extensions, TLSX_ECH, ech, heap); - if (ret != 0) { XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER); } - return ret; } @@ -12092,41 +12946,31 @@ static int TLSX_ServerECH_Use(TLSX** extensions, void* heap, int ret; WOLFSSL_ECH* ech; TLSX* echX; - if (extensions == NULL) return BAD_FUNC_ARG; - /* if we already have ech don't override it */ echX = TLSX_Find(*extensions, TLSX_ECH); if (echX != NULL) return 0; - ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ech == NULL) return MEMORY_E; - ForceZero(ech, sizeof(WOLFSSL_ECH)); - ech->state = ECH_WRITE_NONE; - /* 0 for outer */ ech->type = ECH_TYPE_OUTER; - ech->echConfig = configs; - /* setup the rest of the settings when we receive ech from the client */ ret = TLSX_Push(extensions, TLSX_ECH, ech, heap); - if (ret != 0) XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER); - return ret; } -/* return length after writing the ech */ -static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset) +/* return status after writing the ech and updating offset */ +static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte msgType, byte* writeBuf, + word16* offset) { int ret = 0; int rngRet = -1; @@ -12140,84 +12984,75 @@ static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset) Hpke hpke[1]; WC_RNG rng[1]; #endif - WOLFSSL_MSG("TLSX_ECH_Write"); - + if (msgType == hello_retry_request) { + /* reserve space to write the confirmation to */ + *offset += ECH_ACCEPT_CONFIRMATION_SZ; + /* set confBuf */ + ech->confBuf = writeBuf; + return 0; + } if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL) return 0; - if (ech->state == ECH_WRITE_RETRY_CONFIGS) { /* get size then write */ ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen); - if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) return ret; - ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen); - if (ret != WOLFSSL_SUCCESS) return ret; - *offset += configsLen; - return 0; } - -#ifdef WOLFSSL_SMALL_STACK - hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER); - - if (hpke == NULL) - return MEMORY_E; - - rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); - - if (rng == NULL) { - XFREE(hpke, NULL, DYNAMIC_TYPE_RNG); - return MEMORY_E; - } -#endif - /* type */ *writeBuf_p = ech->type; writeBuf_p += sizeof(ech->type); - /* outer has body, inner does not */ if (ech->type == ECH_TYPE_OUTER) { /* kdfId */ c16toa(ech->cipherSuite.kdfId, writeBuf_p); writeBuf_p += sizeof(ech->cipherSuite.kdfId); - /* aeadId */ c16toa(ech->cipherSuite.aeadId, writeBuf_p); writeBuf_p += sizeof(ech->cipherSuite.aeadId); - /* configId */ *writeBuf_p = ech->configId; writeBuf_p += sizeof(ech->configId); - /* encLen */ - c16toa(ech->encLen, writeBuf_p); + if (ech->hpkeContext == NULL) { + c16toa(ech->encLen, writeBuf_p); + } + else { + /* set to 0 if this is clientInner 2 */ + c16toa(0, writeBuf_p); + } writeBuf_p += 2; - if (ech->state == ECH_WRITE_GREASE) { +#ifdef WOLFSSL_SMALL_STACK + hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (hpke == NULL) + return MEMORY_E; + rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); + if (rng == NULL) { + XFREE(hpke, NULL, DYNAMIC_TYPE_RNG); + return MEMORY_E; + } +#endif /* hpke init */ ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId, ech->cipherSuite.aeadId, NULL); - if (ret == 0) rngRet = ret = wc_InitRng(rng); - /* create the ephemeralKey */ if (ret == 0) ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng); - /* enc */ if (ret == 0) { ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p, &ech->encLen); writeBuf_p += ech->encLen; } - if (ret == 0) { /* innerClientHelloLen */ c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32), @@ -12229,45 +13064,40 @@ static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset) ((writeBuf_p - writeBuf) % 32)); writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32); } - if (rngRet == 0) wc_FreeRng(rng); - if (ephemeralKey != NULL) wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap); +#ifdef WOLFSSL_SMALL_STACK + XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); +#endif } else { - /* write enc to writeBuf_p */ - ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey, - writeBuf_p, &ech->encLen); - writeBuf_p += ech->encLen; - + /* only write enc if this is our first ech, no hpke context */ + if (ech->hpkeContext == NULL) { + /* write enc to writeBuf_p */ + ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey, + writeBuf_p, &ech->encLen); + writeBuf_p += ech->encLen; + } /* innerClientHelloLen */ c16toa(ech->innerClientHelloLen, writeBuf_p); writeBuf_p += 2; - /* set payload offset for when we finalize */ ech->outerClientPayload = writeBuf_p; - /* write zeros for payload */ XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen); writeBuf_p += ech->innerClientHelloLen; } } - -#ifdef WOLFSSL_SMALL_STACK - XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(rng, NULL, DYNAMIC_TYPE_RNG); -#endif - if (ret == 0) *offset += (writeBuf_p - writeBuf); - return ret; } /* return the size needed for the ech extension */ -static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech) +static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech, byte msgType) { int ret; word32 size; @@ -12279,6 +13109,9 @@ static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech) size += GREASE_ECH_SIZE + (size % 32); } + else if (msgType == hello_retry_request) { + size = ECH_ACCEPT_CONFIRMATION_SZ; + } else if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL) { size = 0; @@ -12297,8 +13130,11 @@ static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech) else { size = sizeof(ech->type) + sizeof(ech->cipherSuite) + - sizeof(ech->configId) + sizeof(word16) + ech->encLen + - sizeof(word16) + ech->innerClientHelloLen; + sizeof(ech->configId) + sizeof(word16) + sizeof(word16) + + ech->innerClientHelloLen; + /* only set encLen if this is inner hello 1 */ + if (ech->hpkeContext == NULL) + size += ech->encLen; } return (int)size; @@ -12316,10 +13152,8 @@ static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig, word32 rawConfigLen = 0; byte* info = NULL; word32 infoLen = 0; - if (ech == NULL || echConfig == NULL || aad == NULL) return BAD_FUNC_ARG; - /* verify the kem and key len */ switch (echConfig->kemId) { @@ -12342,10 +13176,8 @@ static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig, expectedEncLen = 0; break; } - if (expectedEncLen != ech->encLen) return BAD_FUNC_ARG; - /* verify the cipher suite */ for (i = 0; i < echConfig->numCipherSuites; i++) { if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId && @@ -12353,54 +13185,69 @@ static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig, break; } } - if (i >= echConfig->numCipherSuites) { return BAD_FUNC_ARG; } - - ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER); - - if (ech->hpke == NULL) - return MEMORY_E; - - ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId, - ech->cipherSuite.aeadId, heap); - - /* get the rawConfigLen */ - if (ret == 0) - ret = GetEchConfig(echConfig, NULL, &rawConfigLen); - - if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) - ret = 0; - - /* create info */ - if (ret == 0) { - infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen; - info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER); - - if (info == NULL) + /* check if hpke already exists, may if HelloRetryRequest */ + if (ech->hpke == NULL) { + ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ech->hpke == NULL) ret = MEMORY_E; - else { - XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, - TLS_INFO_CONST_STRING_SZ + 1); - ret = GetEchConfig(echConfig, info + - TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen); + /* init the hpke struct */ + if (ret == 0) { + ret = wc_HpkeInit(ech->hpke, echConfig->kemId, + ech->cipherSuite.kdfId, ech->cipherSuite.aeadId, heap); } - } + if (ret == 0) { + /* allocate hpkeContext */ + ech->hpkeContext = + (HpkeBaseContext*)XMALLOC(sizeof(HpkeBaseContext), + ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ech->hpkeContext == NULL) + ret = MEMORY_E; + } + /* get the rawConfigLen */ + if (ret == 0) + ret = GetEchConfig(echConfig, NULL, &rawConfigLen); + if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) + ret = 0; + /* create info */ + if (ret == 0) { + infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen; + info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (info == NULL) + ret = MEMORY_E; + else { + XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, + TLS_INFO_CONST_STRING_SZ + 1); + ret = GetEchConfig(echConfig, info + + TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen); + } + } + /* init the context for opening */ + if (ret == 0) { + ret = wc_HpkeInitOpenContext(ech->hpke, ech->hpkeContext, + echConfig->receiverPrivkey, ech->enc, ech->encLen, info, + infoLen); + } + } /* decrypt the ech payload */ - if (ret == 0) - ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc, - ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload, - ech->innerClientHelloLen, + if (ret == 0) { + ret = wc_HpkeContextOpenBase(ech->hpke, ech->hpkeContext, aad, aadLen, + ech->outerClientPayload, ech->innerClientHelloLen, ech->innerClientHello + HANDSHAKE_HEADER_SZ); - + } + /* free the hpke and context on failure */ if (ret != 0) { XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); ech->hpke = NULL; + XFREE(ech->hpkeContext, heap, DYNAMIC_TYPE_TMP_BUFFER); + ech->hpkeContext = NULL; } - XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (info != NULL) + XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -12417,94 +13264,98 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, WOLFSSL_EchConfig* echConfig; byte* aadCopy; byte* readBuf_p = (byte*)readBuf; - WOLFSSL_MSG("TLSX_ECH_Parse"); - if (size == 0) return BAD_FUNC_ARG; - if (ssl->options.disableECH) { WOLFSSL_MSG("TLSX_ECH_Parse: ECH disabled. Ignoring."); return 0; } - + /* retry configs */ if (msgType == encrypted_extensions) { ret = wolfSSL_SetEchConfigs(ssl, readBuf, size); if (ret == WOLFSSL_SUCCESS) ret = 0; } + /* HRR with special confirmation */ + else if (msgType == hello_retry_request && ssl->options.useEch) { + /* length must be 8 */ + if (size != ECH_ACCEPT_CONFIRMATION_SZ) + return BAD_FUNC_ARG; + /* get extension */ + echX = TLSX_Find(ssl->extensions, TLSX_ECH); + if (echX == NULL) + return BAD_FUNC_ARG; + ech = (WOLFSSL_ECH*)echX->data; + ech->confBuf = (byte*)readBuf; + } else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) { + /* get extension */ echX = TLSX_Find(ssl->extensions, TLSX_ECH); - if (echX == NULL) return BAD_FUNC_ARG; - ech = (WOLFSSL_ECH*)echX->data; - /* read the ech parameters before the payload */ ech->type = *readBuf_p; readBuf_p++; - if (ech->type == ECH_TYPE_INNER) { ech->state = ECH_PARSED_INTERNAL; return 0; } - /* technically the payload would only be 1 byte at this length */ if (size < 11 + ech->encLen) return BAD_FUNC_ARG; - + /* read kdfId */ ato16(readBuf_p, &ech->cipherSuite.kdfId); readBuf_p += 2; - + /* read aeadId */ ato16(readBuf_p, &ech->cipherSuite.aeadId); readBuf_p += 2; - + /* read configId */ ech->configId = *readBuf_p; readBuf_p++; - - ato16(readBuf_p, &ech->encLen); - readBuf_p += 2; - - if (ech->encLen > HPKE_Npk_MAX) - return BAD_FUNC_ARG; - - XMEMCPY(ech->enc, readBuf_p, ech->encLen); - readBuf_p += ech->encLen; - + /* only get enc if we don't already have the hpke context */ + if (ech->hpkeContext == NULL) { + /* read encLen */ + ato16(readBuf_p, &ech->encLen); + readBuf_p += 2; + if (ech->encLen > HPKE_Npk_MAX) + return BAD_FUNC_ARG; + /* read enc */ + XMEMCPY(ech->enc, readBuf_p, ech->encLen); + readBuf_p += ech->encLen; + } + else { + readBuf_p += 2; + } + /* read hello inner len */ ato16(readBuf_p, &ech->innerClientHelloLen); ech->innerClientHelloLen -= WC_AES_BLOCK_SIZE; readBuf_p += 2; - ech->outerClientPayload = readBuf_p; - /* make a copy of the aad */ aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (aadCopy == NULL) return MEMORY_E; - XMEMCPY(aadCopy, ech->aad, ech->aadLen); - /* set the ech payload of the copy to zeros */ XMEMSET(aadCopy + (readBuf_p - ech->aad), 0, ech->innerClientHelloLen + WC_AES_BLOCK_SIZE); - + /* free the old ech in case this is our second client hello */ + if (ech->innerClientHello != NULL) + XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); /* allocate the inner payload buffer */ ech->innerClientHello = (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (ech->innerClientHello == NULL) { XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); return MEMORY_E; } - /* first check if the config id matches */ echConfig = ssl->ctx->echConfigs; - while (echConfig != NULL) { /* decrypt with this config */ if (echConfig->configId == ech->configId) { @@ -12512,26 +13363,20 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, ssl->heap); break; } - echConfig = echConfig->next; } - /* try to decrypt with all configs */ if (echConfig == NULL || ret != 0) { echConfig = ssl->ctx->echConfigs; - while (echConfig != NULL) { ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen, ssl->heap); - if (ret== 0) break; - echConfig = echConfig->next; } } - - /* if we failed to extract */ + /* if we failed to extract, set state to retry configs */ if (ret != 0) { XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); ech->innerClientHello = NULL; @@ -12539,19 +13384,15 @@ static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size, } else { i = 0; - /* decrement until before the padding */ while (ech->innerClientHello[ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) { i++; } - /* subtract the length of the padding from the length */ ech->innerClientHelloLen -= i; } - XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); - return 0; } @@ -12565,7 +13406,10 @@ static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap) if (ech->ephemeralKey != NULL) wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey, ech->hpke->heap); - XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ech->hpke != NULL) + XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ech->hpkeContext != NULL) + XFREE(ech->hpkeContext, heap, DYNAMIC_TYPE_TMP_BUFFER); XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER); (void)heap; @@ -12575,58 +13419,65 @@ static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap) * status */ int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen) { - int ret; + int ret = 0; void* receiverPubkey = NULL; - byte* info; - int infoLen; - byte* aadCopy; - - /* import the server public key */ - ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey, - ech->echConfig->receiverPubkey, ech->encLen); - - if (ret == 0) { - /* create info */ - infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen; - info = (byte*)XMALLOC(infoLen, ech->hpke->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (info == NULL) - ret = MEMORY_E; - + byte* info = NULL; + int infoLen = 0; + byte* aadCopy = NULL; + /* setup hpke context to seal, should be done at most once per connection */ + if (ech->hpkeContext == NULL) { + /* import the server public key */ + ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey, + ech->echConfig->receiverPubkey, ech->encLen); if (ret == 0) { - /* puts the null byte in for me */ - XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ - + 1); - XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw, - ech->echConfig->rawLen); - - /* make a copy of the aad since we overwrite it */ - aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap, + /* allocate hpke context */ + ech->hpkeContext = + (HpkeBaseContext*)XMALLOC(sizeof(HpkeBaseContext), + ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (ech->hpkeContext == NULL) + ret = MEMORY_E; + } + if (ret == 0) { + /* create info */ + infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen; + info = (byte*)XMALLOC(infoLen, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (aadCopy == NULL) { - XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (info == NULL) ret = MEMORY_E; - } } - if (ret == 0) { - XMEMCPY(aadCopy, aad, aadLen); - - /* seal the payload */ - ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey, - info, (word32)infoLen, aadCopy, aadLen, ech->innerClientHello, - ech->innerClientHelloLen - ech->hpke->Nt, - ech->outerClientPayload); - - XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); + /* puts the null byte in for me */ + XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, + TLS_INFO_CONST_STRING_SZ + 1); + XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, + ech->echConfig->raw, ech->echConfig->rawLen); + /* init the context for seal with info and keys */ + ret = wc_HpkeInitSealContext(ech->hpke, ech->hpkeContext, + ech->ephemeralKey, receiverPubkey, info, infoLen); } } - + if (ret == 0) { + /* make a copy of the aad since we overwrite it */ + aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (aadCopy == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + XMEMCPY(aadCopy, aad, aadLen); + /* seal the payload with context */ + ret = wc_HpkeContextSealBase(ech->hpke, ech->hpkeContext, aadCopy, + aadLen, ech->innerClientHello, + ech->innerClientHelloLen - ech->hpke->Nt, ech->outerClientPayload); + } + if (info != NULL) + XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (aadCopy != NULL) + XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER); if (receiverPubkey != NULL) wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey, ech->hpke->heap); - return ret; } @@ -13014,7 +13865,7 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, #endif /* WOLFSSL_DTLS_CID */ #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) case TLSX_ECH: - length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data); + length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data, msgType); break; #endif default: @@ -13264,7 +14115,7 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) case TLSX_ECH: WOLFSSL_MSG("ECH extension to write"); - ret = ECH_WRITE((WOLFSSL_ECH*)extension->data, + ret = ECH_WRITE((WOLFSSL_ECH*)extension->data, msgType, output + offset, &offset); break; #endif @@ -13481,9 +14332,9 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) #endif #endif -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM #ifndef WOLFSSL_NO_ML_KEM -#ifdef WOLFSSL_WC_KYBER +#ifdef WOLFSSL_WC_MLKEM #ifndef WOLFSSL_NO_ML_KEM_512 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_512, @@ -13491,6 +14342,11 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_ML_KEM_512, ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_ML_KEM_512, + ssl->heap); + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_768 if (ret == WOLFSSL_SUCCESS) @@ -13499,6 +14355,19 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_768, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_ML_KEM_768, + ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_ML_KEM_768, + ssl->heap); + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X448_ML_KEM_768, + ssl->heap); + #endif #endif #ifndef WOLFSSL_NO_ML_KEM_1024 if (ret == WOLFSSL_SUCCESS) @@ -13507,6 +14376,9 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_ML_KEM_1024, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_1024, + ssl->heap); #endif #elif defined(HAVE_LIBOQS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_ML_KEM_512, ssl->heap); @@ -13522,13 +14394,32 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_768, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_ML_KEM_768, + ssl->heap); if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_ML_KEM_1024, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_ML_KEM_1024, + ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_ML_KEM_512, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_ML_KEM_768, + ssl->heap); + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X448_ML_KEM_768, + ssl->heap); + #endif #endif /* HAVE_LIBOQS */ #endif /* !WOLFSSL_NO_ML_KEM */ -#ifdef WOLFSSL_KYBER_ORIGINAL -#ifdef WOLFSSL_WC_KYBER +#ifdef WOLFSSL_MLKEM_KYBER +#ifdef WOLFSSL_WC_MLKEM #ifdef WOLFSSL_KYBER512 if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, @@ -13536,6 +14427,11 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1, ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_KYBER_LEVEL1, + ssl->heap); + #endif #endif #ifdef WOLFSSL_KYBER768 if (ret == WOLFSSL_SUCCESS) @@ -13544,6 +14440,19 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL3, + ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_KYBER_LEVEL3, + ssl->heap); + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X448_KYBER_LEVEL3, + ssl->heap); + #endif #endif #ifdef WOLFSSL_KYBER1024 if (ret == WOLFSSL_SUCCESS) @@ -13567,12 +14476,28 @@ static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions) if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3, ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL3, + ssl->heap); if (ret == WOLFSSL_SUCCESS) ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5, ssl->heap); + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_KYBER_LEVEL1, + ssl->heap); + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X25519_KYBER_LEVEL3, + ssl->heap); + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + if (ret == WOLFSSL_SUCCESS) + ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_X448_KYBER_LEVEL3, + ssl->heap); + #endif #endif /* HAVE_LIBOQS */ -#endif /* WOLFSSL_KYBER_ORIGINAL */ -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_MLKEM_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM */ (void)ssl; (void)extensions; @@ -14048,7 +14973,9 @@ static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType, echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH); /* if type is outer change sni to public name */ - if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER && + (ssl->options.echAccepted || + ((WOLFSSL_ECH*)echX->data)->innerCount == 0)) { if (ssl->extensions) { serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME); @@ -14255,7 +15182,9 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, } /* if type is outer change sni to public name */ - if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) { + if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER && + (ssl->options.echAccepted || + ((WOLFSSL_ECH*)echX->data)->innerCount == 0)) { if (ssl->extensions) { serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME); @@ -14315,31 +15244,36 @@ static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore, msgType, pOffset); } - if (echX != NULL) { - /* turn off and write it last */ - TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type)); - } + /* only write if have a shot at acceptance */ + if (echX != NULL && + (ssl->options.echAccepted || + ((WOLFSSL_ECH*)echX->data)->innerCount == 0)) { + if (echX != NULL) { + /* turn off and write it last */ + TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type)); + } - if (ret == 0 && ssl->extensions) { - ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore, - msgType, pOffset); - } + if (ret == 0 && ssl->extensions) { + ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore, + msgType, pOffset); + } - if (ret == 0 && ssl->ctx && ssl->ctx->extensions) { - ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore, - msgType, pOffset); - } + if (ret == 0 && ssl->ctx && ssl->ctx->extensions) { + ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore, + msgType, pOffset); + } - if (serverNameX != NULL) { - /* remove the public name SNI */ - TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap); + if (serverNameX != NULL) { + /* remove the public name SNI */ + TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap); - ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName, - XSTRLEN(tmpServerName), ssl->heap); + ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName, + XSTRLEN(tmpServerName), ssl->heap); - /* restore the inner server name */ - if (ret == WOLFSSL_SUCCESS) - ret = 0; + /* restore the inner server name */ + if (ret == WOLFSSL_SUCCESS) + ret = 0; + } } #ifdef WOLFSSL_SMALL_STACK @@ -14557,6 +15491,10 @@ int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength) #ifdef WOLFSSL_SEND_HRR_COOKIE TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE)); #endif +#ifdef HAVE_ECH + /* send the special confirmation */ + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ECH)); +#endif break; #endif @@ -14700,6 +15638,10 @@ int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE)); } #endif +#ifdef HAVE_ECH + /* send the special confirmation */ + TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_ECH)); +#endif /* Cookie is written below as last extension. */ break; #endif diff --git a/src/src/tls13.c b/src/src/tls13.c index a1a1783..6efe446 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -1,6 +1,6 @@ /* tls13.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,6 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* * BUILD_GCM @@ -88,16 +89,7 @@ * Default behavior is to return a signed 64-bit value. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - -#ifdef WOLFSSL_TLS13 -#ifdef HAVE_SESSION_TICKET - #include -#endif +#if !defined(NO_TLS) && defined(WOLFSSL_TLS13) #ifndef WOLFCRYPT_ONLY @@ -180,11 +172,14 @@ static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13"; #endif /* WOLFSSL_DTLS13 */ #if defined(HAVE_ECH) -#define ECH_ACCEPT_CONFIRMATION_SZ 8 #define ECH_ACCEPT_CONFIRMATION_LABEL_SZ 23 +#define ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ 27 static const byte echAcceptConfirmationLabel[ECH_ACCEPT_CONFIRMATION_LABEL_SZ + 1] = "ech accept confirmation"; +static const byte + echHrrAcceptConfirmationLabel[ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ + 1] = + "hrr ech accept confirmation"; #endif #ifndef NO_CERTS @@ -1024,7 +1019,7 @@ int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen, ret = Tls13HKDFExpandLabel(ssl, firstExpand, hashLen, ssl->arrays->exporterSecret, hashLen, protocol, protocolLen, (byte*)label, (word32)labelLen, - emptyHash, hashLen, hashType); + emptyHash, hashLen, (int)hashType); if (ret != 0) return ret; @@ -1035,7 +1030,7 @@ int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen, ret = Tls13HKDFExpandLabel(ssl, out, (word32)outLen, firstExpand, hashLen, protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ, - hashOut, hashLen, hashType); + hashOut, hashLen, (int)hashType); return ret; } @@ -4166,7 +4161,8 @@ int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config) /* returns status after we hash the ech inner */ static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech) { - int ret; + int ret = 0; + word32 realSz; HS_Hashes* tmpHashes; #ifdef WOLFSSL_DTLS13 byte falseHeader[DTLS13_HANDSHAKE_HEADER_SZ]; @@ -4176,29 +4172,51 @@ static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech) if (ssl == NULL || ech == NULL) return BAD_FUNC_ARG; - - /* switch hsHashes to the ech version */ - InitHandshakeHashesAndCopy(ssl, ssl->hsHashes, &ssl->hsHashesEch); - - /* swap hsHashes so the regular hash functions work */ + realSz = ech->innerClientHelloLen - ech->paddingLen - ech->hpke->Nt; tmpHashes = ssl->hsHashes; - ssl->hsHashes = ssl->hsHashesEch; - - /* do the handshake header then the body */ - AddTls13HandShakeHeader(falseHeader, - ech->innerClientHelloLen - ech->paddingLen - ech->hpke->Nt, 0, 0, - client_hello, ssl); - ret = HashRaw(ssl, falseHeader, HANDSHAKE_HEADER_SZ); + ssl->hsHashes = NULL; + /* init the ech hashes */ + ret = InitHandshakeHashes(ssl); + if (ret == 0) { + ssl->hsHashesEch = ssl->hsHashes; + /* do the handshake header then the body */ + AddTls13HandShakeHeader(falseHeader, realSz, 0, 0, client_hello, ssl); + ret = HashRaw(ssl, falseHeader, HANDSHAKE_HEADER_SZ); + /* hash with inner */ + if (ret == 0) { + /* init hsHashesEchInner */ + if (ech->innerCount == 0) { + ssl->hsHashes = ssl->hsHashesEchInner; + ret = InitHandshakeHashes(ssl); + if (ret == 0) { + ssl->hsHashesEchInner = ssl->hsHashes; + ech->innerCount = 1; + } + } + else { + /* switch back to hsHashes so we have hrr -> echInner2 */ + ssl->hsHashes = tmpHashes; + ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashes, + &ssl->hsHashesEchInner); + } + if (ret == 0) { + ssl->hsHashes = ssl->hsHashesEchInner; + ret = HashRaw(ssl, falseHeader, HANDSHAKE_HEADER_SZ); + ssl->hsHashes = ssl->hsHashesEch; + } + } + } /* hash the body */ + if (ret == 0) + ret = HashRaw(ssl, ech->innerClientHello, realSz); + /* hash with inner */ if (ret == 0) { - ret = HashRaw(ssl, ech->innerClientHello, - (int)(ech->innerClientHelloLen - ech->paddingLen - ech->hpke->Nt)); + ssl->hsHashes = ssl->hsHashesEchInner; + ret = HashRaw(ssl, ech->innerClientHello, realSz); } - /* swap hsHashes back */ ssl->hsHashes = tmpHashes; - return ret; } #endif @@ -4443,23 +4461,26 @@ int SendTls13ClientHello(WOLFSSL* ssl) if (args->ech == NULL) return WOLFSSL_FATAL_ERROR; - /* set the type to inner */ - args->ech->type = ECH_TYPE_INNER; - args->preXLength = (int)args->length; + /* only prepare if we have a chance at acceptance */ + if (ssl->options.echAccepted || args->ech->innerCount == 0) { + /* set the type to inner */ + args->ech->type = ECH_TYPE_INNER; + args->preXLength = (int)args->length; - /* get size for inner */ - ret = TLSX_GetRequestSize(ssl, client_hello, &args->length); - if (ret != 0) - return ret; + /* get size for inner */ + ret = TLSX_GetRequestSize(ssl, client_hello, &args->length); + if (ret != 0) + return ret; - /* set the type to outer */ - args->ech->type = 0; - /* set innerClientHelloLen to ClientHelloInner + padding + tag */ - args->ech->paddingLen = 31 - ((args->length - 1) % 32); - args->ech->innerClientHelloLen = (word16)(args->length + - args->ech->paddingLen + args->ech->hpke->Nt); - /* set the length back to before we computed ClientHelloInner size */ - args->length = (word32)args->preXLength; + /* set the type to outer */ + args->ech->type = 0; + /* set innerClientHelloLen to ClientHelloInner + padding + tag */ + args->ech->paddingLen = 31 - ((args->length - 1) % 32); + args->ech->innerClientHelloLen = (word16)(args->length + + args->ech->paddingLen + args->ech->hpke->Nt); + /* set the length back to before we computed ClientHelloInner size */ + args->length = (word32)args->preXLength; + } } #endif @@ -4585,42 +4606,41 @@ int SendTls13ClientHello(WOLFSSL* ssl) #if defined(HAVE_ECH) /* write inner then outer */ - if (ssl->options.useEch == 1 && !ssl->options.disableECH) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH && + (ssl->options.echAccepted || args->ech->innerCount == 0)) { /* set the type to inner */ args->ech->type = ECH_TYPE_INNER; - + /* innerClientHello may already exist from hrr, free if it does */ + if (args->ech->innerClientHello != NULL) { + XFREE(args->ech->innerClientHello, ssl->heap, + DYNAMIC_TYPE_TMP_BUFFER); + } /* allocate the inner */ args->ech->innerClientHello = (byte*)XMALLOC(args->ech->innerClientHelloLen - args->ech->hpke->Nt, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); if (args->ech->innerClientHello == NULL) return MEMORY_E; - /* set the padding bytes to 0 */ XMEMSET(args->ech->innerClientHello + args->ech->innerClientHelloLen - args->ech->hpke->Nt - args->ech->paddingLen, 0, args->ech->paddingLen); - /* copy the client hello to the ech innerClientHello, exclude record */ /* and handshake headers */ XMEMCPY(args->ech->innerClientHello, args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ, args->idx - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ)); - /* copy the client random to inner */ XMEMCPY(ssl->arrays->clientRandomInner, ssl->arrays->clientRandom, RAN_LEN); - /* change the outer client random */ ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->clientRandomOffset, RAN_LEN); if (ret != 0) return ret; - /* copy the new client random */ XMEMCPY(ssl->arrays->clientRandom, args->output + args->clientRandomOffset, RAN_LEN); - /* write the extensions for inner */ args->length = 0; ret = TLSX_WriteRequest(ssl, args->ech->innerClientHello + args->idx - @@ -4628,7 +4648,6 @@ int SendTls13ClientHello(WOLFSSL* ssl) &args->length); if (ret != 0) return ret; - /* set the type to outer */ args->ech->type = 0; } @@ -4645,7 +4664,8 @@ int SendTls13ClientHello(WOLFSSL* ssl) #if defined(HAVE_ECH) /* encrypt and pack the ech innerClientHello */ - if (ssl->options.useEch == 1 && !ssl->options.disableECH) { + if (ssl->options.useEch == 1 && !ssl->options.disableECH && + (ssl->options.echAccepted || args->ech->innerCount == 0)) { ret = TLSX_FinalizeEch(args->ech, args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ, (word32)(args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ))); @@ -4675,7 +4695,8 @@ int SendTls13ClientHello(WOLFSSL* ssl) { #if defined(HAVE_ECH) /* compute the inner hash */ - if (ssl->options.useEch == 1 && !ssl->options.disableECH) + if (ssl->options.useEch == 1 && !ssl->options.disableECH && + (ssl->options.echAccepted || args->ech->innerCount == 0)) ret = EchHashHelloInner(ssl, args->ech); #endif /* compute the outer hash */ @@ -4768,15 +4789,15 @@ static int Dtls13ClientDoDowngrade(WOLFSSL* ssl) #endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT*/ #if defined(HAVE_ECH) -/* check if the server accepted ech or not */ -static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, - int serverRandomOffset, int helloSz) +/* check if the server accepted ech or not, must be run after an hsHashes + * restart */ +static int EchCheckAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz, + const byte* input, int acceptOffset, int helloSz) { int ret = 0; int digestType = 0; int digestSize = 0; HS_Hashes* tmpHashes; - HS_Hashes* acceptHashes; byte zeros[WC_MAX_DIGEST_SIZE]; byte transcriptEchConf[WC_MAX_DIGEST_SIZE]; byte expandLabelPrk[WC_MAX_DIGEST_SIZE]; @@ -4785,22 +4806,20 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, XMEMSET(transcriptEchConf, 0, sizeof(transcriptEchConf)); XMEMSET(expandLabelPrk, 0, sizeof(expandLabelPrk)); XMEMSET(acceptConfirmation, 0, sizeof(acceptConfirmation)); - /* copy ech hashes to accept */ - ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashesEch, &acceptHashes); - /* swap hsHashes to acceptHashes */ + /* store so we can restore regardless of the outcome */ tmpHashes = ssl->hsHashes; - ssl->hsHashes = acceptHashes; + /* swap hsHashes to hsHashesEch */ + ssl->hsHashes = ssl->hsHashesEch; /* hash up to the last 8 bytes */ - if (ret == 0) - ret = HashRaw(ssl, input, serverRandomOffset + RAN_LEN - - ECH_ACCEPT_CONFIRMATION_SZ); + ret = HashRaw(ssl, input, acceptOffset); /* hash 8 zeros */ if (ret == 0) ret = HashRaw(ssl, zeros, ECH_ACCEPT_CONFIRMATION_SZ); /* hash the rest of the hello */ if (ret == 0) { - ret = HashRaw(ssl, input + serverRandomOffset + RAN_LEN, - helloSz + HANDSHAKE_HEADER_SZ - (serverRandomOffset + RAN_LEN)); + ret = HashRaw(ssl, input + acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ, + helloSz + HANDSHAKE_HEADER_SZ - + (acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ)); } /* get the modified transcript hash */ if (ret == 0) @@ -4856,97 +4875,83 @@ static int EchCheckAcceptance(WOLFSSL* ssl, const byte* input, /* tls expand with the confirmation label */ if (ret == 0) { PRIVATE_KEY_UNLOCK(); - ret = Tls13HKDFExpandKeyLabel(ssl, - acceptConfirmation, ECH_ACCEPT_CONFIRMATION_SZ, - expandLabelPrk, (word32)digestSize, - tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, - echAcceptConfirmationLabel, ECH_ACCEPT_CONFIRMATION_LABEL_SZ, - transcriptEchConf, (word32)digestSize, digestType, WOLFSSL_SERVER_END); + ret = Tls13HKDFExpandKeyLabel(ssl, acceptConfirmation, + ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize, + tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, label, labelSz, + transcriptEchConf, (word32)digestSize, digestType, + WOLFSSL_SERVER_END); PRIVATE_KEY_LOCK(); } if (ret == 0) { /* last 8 bytes should match our expand output */ - ret = XMEMCMP(acceptConfirmation, - ssl->arrays->serverRandom + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ, + ret = XMEMCMP(acceptConfirmation, input + acceptOffset, ECH_ACCEPT_CONFIRMATION_SZ); /* ech accepted */ if (ret == 0) { - /* use the inner random for client random */ - XMEMCPY(ssl->arrays->clientRandom, ssl->arrays->clientRandomInner, - RAN_LEN); - /* switch back to original hsHashes to free */ + /* set echAccepted to 1 */ + ssl->options.echAccepted = 1; + /* free hsHashes and go with inner */ ssl->hsHashes = tmpHashes; - /* set the final hsHashes to the ech hashes */ - tmpHashes = ssl->hsHashesEch; + FreeHandshakeHashes(ssl); + ssl->hsHashes = ssl->hsHashesEch; + tmpHashes = ssl->hsHashesEchInner; + ssl->hsHashesEchInner = NULL; } /* ech rejected */ else { - /* switch to hsHashesEch to free */ - ssl->hsHashes = ssl->hsHashesEch; + /* set echAccepted to 0, needed in case HRR */ + ssl->options.echAccepted = 0; + /* free inner since we're continuing with outer */ + ssl->hsHashes = ssl->hsHashesEchInner; + FreeHandshakeHashes(ssl); + ssl->hsHashesEchInner = NULL; } - /* free hsHashes */ - FreeHandshakeHashes(ssl); - /* set hsHashesEch to NULL to avoid double free */ - ssl->hsHashesEch = NULL; /* continue with outer if we failed to verify ech was accepted */ ret = 0; } - /* switch to acceptHashes */ - ssl->hsHashes = acceptHashes; - /* free acceptHashes */ FreeHandshakeHashes(ssl); - /* swap to tmp, will ech if accepted, hsHashes if rejected */ + /* set hsHashesEch to NULL to avoid double free */ + ssl->hsHashesEch = NULL; + /* swap to tmp, will be inner if accepted, hsHashes if rejected */ ssl->hsHashes = tmpHashes; return ret; } -/* replace the last 8 bytes of the server random with the ech acceptance - * parameter, return status */ -static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, - int serverRandomOffset, int helloSz) +/* replace the last acceptance field for either sever hello or hrr with the ech + * acceptance parameter, return status */ +static int EchWriteAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz, + byte* output, int acceptOffset, int helloSz, byte msgType) { int ret = 0; int digestType = 0; int digestSize = 0; HS_Hashes* tmpHashes = NULL; - HS_Hashes* acceptHashes = NULL; byte zeros[WC_MAX_DIGEST_SIZE]; byte transcriptEchConf[WC_MAX_DIGEST_SIZE]; byte expandLabelPrk[WC_MAX_DIGEST_SIZE]; XMEMSET(zeros, 0, sizeof(zeros)); XMEMSET(transcriptEchConf, 0, sizeof(transcriptEchConf)); XMEMSET(expandLabelPrk, 0, sizeof(expandLabelPrk)); - - /* copy ech hashes to accept */ - ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashes, &acceptHashes); - - /* swap hsHashes to acceptHashes */ + /* store so we can restore regardless of the outcome */ tmpHashes = ssl->hsHashes; - ssl->hsHashes = acceptHashes; - - /* hash up to the last 8 bytes */ - if (ret == 0) - ret = HashRaw(ssl, output, serverRandomOffset + RAN_LEN - - ECH_ACCEPT_CONFIRMATION_SZ); - + ssl->hsHashes = ssl->hsHashesEch; + /* hash up to the acceptOffset */ + ret = HashRaw(ssl, output, acceptOffset); /* hash 8 zeros */ if (ret == 0) - ret = HashRaw(ssl, zeros, ECH_ACCEPT_CONFIRMATION_SZ); - + ret = HashRaw(ssl, zeros, ECH_ACCEPT_CONFIRMATION_SZ); /* hash the rest of the hello */ - if (ret == 0) - ret = HashRaw(ssl, output + serverRandomOffset + RAN_LEN, - helloSz - (serverRandomOffset + RAN_LEN)); - + if (ret == 0) { + ret = HashRaw(ssl, output + acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ, + helloSz - (acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ)); + } /* get the modified transcript hash */ if (ret == 0) ret = GetMsgHash(ssl, transcriptEchConf); - if (ret > 0) ret = 0; - /* pick the right type and size based on mac_algorithm */ - if (ret == 0) + if (ret == 0) { switch (ssl->specs.mac_algorithm) { #ifndef NO_SHA256 case sha256_mac: @@ -4976,7 +4981,7 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, ret = WOLFSSL_FATAL_ERROR; break; } - + } /* extract clientRandom with a key of all zeros */ if (ret == 0) { PRIVATE_KEY_UNLOCK(); @@ -4991,29 +4996,23 @@ static int EchWriteAcceptance(WOLFSSL* ssl, byte* output, #endif PRIVATE_KEY_LOCK(); } - /* tls expand with the confirmation label */ if (ret == 0) { PRIVATE_KEY_UNLOCK(); - ret = Tls13HKDFExpandKeyLabel(ssl, - output + serverRandomOffset + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ, - ECH_ACCEPT_CONFIRMATION_SZ, - expandLabelPrk, (word32)digestSize, - tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, - echAcceptConfirmationLabel, ECH_ACCEPT_CONFIRMATION_LABEL_SZ, - transcriptEchConf, (word32)digestSize, digestType, WOLFSSL_SERVER_END); + ret = Tls13HKDFExpandKeyLabel(ssl, output + acceptOffset, + ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize, + tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, label, labelSz, + transcriptEchConf, (word32)digestSize, digestType, + WOLFSSL_SERVER_END); PRIVATE_KEY_LOCK(); } - - if (ret == 0) - XMEMCPY(ssl->arrays->serverRandom, output + serverRandomOffset, - RAN_LEN); - - /* free acceptHashes */ + /* mark that ech was accepted */ + if (ret == 0 && msgType != hello_retry_request) + ssl->options.echAccepted = 1; + /* free hsHashesEch, if this is an HRR we will start at client hello 2*/ FreeHandshakeHashes(ssl); - + ssl->hsHashesEch = NULL; ssl->hsHashes = tmpHashes; - return ret; } #endif @@ -5039,7 +5038,10 @@ typedef struct Dsh13Args { byte sessIdSz; byte extMsgType; #if defined(HAVE_ECH) - int serverRandomOffset; + TLSX* echX; + byte* acceptLabel; + word32 acceptOffset; + word16 acceptLabelSz; #endif } Dsh13Args; @@ -5196,7 +5198,8 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Server random - keep for debugging. */ XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN); #if defined(HAVE_ECH) - args->serverRandomOffset = (int)args->idx; + /* last 8 bytes of server random */ + args->acceptOffset = args->idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ; #endif args->idx += RAN_LEN; @@ -5492,15 +5495,6 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ret != 0) return ret; -#if defined(HAVE_ECH) - /* check for acceptConfirmation and HashInput with 8 0 bytes */ - if (ssl->options.useEch == 1 && !ssl->options.disableECH) { - ret = EchCheckAcceptance(ssl, input, args->serverRandomOffset, (int)helloSz); - if (ret != 0) - return ret; - } -#endif - #ifdef HAVE_NULL_CIPHER if (ssl->options.cipherSuite0 == ECC_BYTE && (ssl->options.cipherSuite == TLS_SHA256_SHA256 || @@ -5538,6 +5532,36 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return MATCH_SUITE_ERROR; } +#if defined(HAVE_ECH) + /* check for acceptConfirmation, must be done after hashes restart */ + if (ssl->options.useEch == 1) { + args->echX = TLSX_Find(ssl->extensions, TLSX_ECH); + /* account for hrr extension instead of server random */ + if (args->extMsgType == hello_retry_request) { + args->acceptOffset = + (word32)(((WOLFSSL_ECH*)args->echX->data)->confBuf - input); + args->acceptLabel = (byte*)echHrrAcceptConfirmationLabel; + args->acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ; + } + else { + args->acceptLabel = (byte*)echAcceptConfirmationLabel; + args->acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ; + } + /* check acceptance */ + if (ret == 0) { + ret = EchCheckAcceptance(ssl, args->acceptLabel, + args->acceptLabelSz, input, args->acceptOffset, helloSz); + } + if (ret != 0) + return ret; + /* use the inner random for client random */ + if (args->extMsgType != hello_retry_request) { + XMEMCPY(ssl->arrays->clientRandom, ssl->arrays->clientRandomInner, + RAN_LEN); + } + } +#endif /* HAVE_ECH */ + if (*extMsgType == server_hello) { #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) PreSharedKey* psk = NULL; @@ -5556,6 +5580,9 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return ret; ssl->options.pskNegotiated = 1; } +#else + /* no resumption possible */ + ssl->options.resuming = 0; #endif /* sanity check on PSK / KSE */ @@ -6674,7 +6701,6 @@ static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i, typedef struct Dch13Args { ProtocolVersion pv; - Suites* clSuites; word32 idx; word32 begin; int usingPSK; @@ -6682,17 +6708,17 @@ typedef struct Dch13Args { static void FreeDch13Args(WOLFSSL* ssl, void* pArgs) { - Dch13Args* args = (Dch13Args*)pArgs; - - (void)ssl; - - if (args && args->clSuites) { - XFREE(args->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); - args->clSuites = NULL; + /* openssl compat builds hang on to the client suites until WOLFSSL object + * is destroyed */ +#ifndef OPENSSL_EXTRA + if (ssl->clSuites) { + XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); + ssl->clSuites = NULL; } -#ifdef OPENSSL_EXTRA - ssl->clSuites = NULL; #endif + (void)ssl; + (void)pArgs; + } int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, @@ -6707,6 +6733,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif #if defined(HAVE_ECH) TLSX* echX = NULL; + HS_Hashes* tmpHashes; #endif WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO); @@ -6902,28 +6929,31 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif /* WOLFSSL_DTLS13 */ - args->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap, + XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES); + ssl->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap, DYNAMIC_TYPE_SUITES); - if (args->clSuites == NULL) { + if (ssl->clSuites == NULL) { ERROR_OUT(MEMORY_E, exit_dch); } /* Cipher suites */ if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) ERROR_OUT(BUFFER_ERROR, exit_dch); - ato16(&input[args->idx], &args->clSuites->suiteSz); + ato16(&input[args->idx], &ssl->clSuites->suiteSz); args->idx += OPAQUE16_LEN; - if ((args->clSuites->suiteSz % 2) != 0) { + if ((ssl->clSuites->suiteSz % 2) != 0) { ERROR_OUT(INVALID_PARAMETER, exit_dch); } /* suites and compression length check */ - if ((args->idx - args->begin) + args->clSuites->suiteSz + OPAQUE8_LEN > helloSz) + if ((args->idx - args->begin) + ssl->clSuites->suiteSz + OPAQUE8_LEN > + helloSz) { ERROR_OUT(BUFFER_ERROR, exit_dch); - if (args->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ) + } + if (ssl->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ) ERROR_OUT(BUFFER_ERROR, exit_dch); - XMEMCPY(args->clSuites->suites, input + args->idx, args->clSuites->suiteSz); - args->idx += args->clSuites->suiteSz; - args->clSuites->hashSigAlgoSz = 0; + XMEMCPY(ssl->clSuites->suites, input + args->idx, ssl->clSuites->suiteSz); + args->idx += ssl->clSuites->suiteSz; + ssl->clSuites->hashSigAlgoSz = 0; /* Compression */ b = input[args->idx++]; @@ -6960,7 +6990,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, echX = TLSX_Find(ssl->extensions, TLSX_ECH); if (echX == NULL) - return WOLFSSL_FATAL_ERROR; + ERROR_OUT(WOLFSSL_FATAL_ERROR, exit_dch); ((WOLFSSL_ECH*)echX->data)->aad = input + HANDSHAKE_HEADER_SZ; ((WOLFSSL_ECH*)echX->data)->aadLen = helloSz; @@ -6969,7 +6999,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Parse extensions */ if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello, - args->clSuites))) { + ssl->clSuites))) { goto exit_dch; } @@ -7027,9 +7057,25 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, } #endif +#if defined(HAVE_ECH) + /* hash clientHelloInner to hsHashesEch independently since it can't include + * the HRR */ + if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) { + tmpHashes = ssl->hsHashes; + ssl->hsHashes = NULL; + ret = InitHandshakeHashes(ssl); + if (ret != 0) + goto exit_dch; + if ((ret = HashInput(ssl, input + args->begin, (int)helloSz)) != 0) + goto exit_dch; + ssl->hsHashesEch = ssl->hsHashes; + ssl->hsHashes = tmpHashes; + } +#endif + #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \ defined(HAVE_TLS_EXTENSIONS) - ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, args->clSuites, + ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, ssl->clSuites, &args->usingPSK); if (ret != 0) goto exit_dch; @@ -7053,7 +7099,9 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_MSG("Client did not send a KeyShare extension"); ERROR_OUT(INCOMPLETE_DATA, exit_dch); } - if (TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS) == NULL) { + /* Can't check ssl->extensions here as SigAlgs are unconditionally + set by TLSX_PopulateExtensions */ + if (ssl->clSuites->hashSigAlgoSz == 0) { WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension"); ERROR_OUT(INCOMPLETE_DATA, exit_dch); } @@ -7079,13 +7127,12 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, case TLS_ASYNC_DO: { #ifdef OPENSSL_EXTRA - ssl->clSuites = args->clSuites; if ((ret = CertSetupCbWrapper(ssl)) != 0) goto exit_dch; #endif #ifndef NO_CERTS if (!args->usingPSK) { - if ((ret = MatchSuite(ssl, args->clSuites)) < 0) { + if ((ret = MatchSuite(ssl, ssl->clSuites)) < 0) { #ifdef WOLFSSL_ASYNC_CRYPT if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) #endif @@ -7178,7 +7225,7 @@ int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, ERROR_OUT(MATCH_SUITE_ERROR, exit_dch); } - #ifdef HAVE_SESSION_TICKET + #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) if (ssl->options.resuming) { ssl->options.resuming = 0; ssl->arrays->psk_keySz = 0; @@ -7306,7 +7353,9 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) int sendSz; #if defined(HAVE_ECH) TLSX* echX = NULL; - word32 serverRandomOffset; + byte* acceptLabel = (byte*)echAcceptConfirmationLabel; + word32 acceptOffset; + word16 acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ; #endif WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND); @@ -7365,7 +7414,8 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) } #if defined(HAVE_ECH) - serverRandomOffset = idx; + /* last 8 bytes of server random */ + acceptOffset = idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ; #endif /* Store in SSL for debugging. */ @@ -7429,18 +7479,37 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) #if defined(HAVE_ECH) if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) { echX = TLSX_Find(ssl->extensions, TLSX_ECH); - if (echX == NULL) return WOLFSSL_FATAL_ERROR; - + /* use hrr offset */ + if (extMsgType == hello_retry_request) { + acceptOffset = + (word32)(((WOLFSSL_ECH*)echX->data)->confBuf - output); + acceptLabel = (byte*)echHrrAcceptConfirmationLabel; + acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ; + } /* replace the last 8 bytes of server random with the accept */ if (((WOLFSSL_ECH*)echX->data)->state == ECH_PARSED_INTERNAL) { - ret = EchWriteAcceptance(ssl, output + RECORD_HEADER_SZ, - serverRandomOffset - RECORD_HEADER_SZ, - sendSz - RECORD_HEADER_SZ); - - /* remove ech so we don't keep sending it in write */ - TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap); + if (ret == 0) { + ret = EchWriteAcceptance(ssl, acceptLabel, + acceptLabelSz, output + RECORD_HEADER_SZ, + acceptOffset - RECORD_HEADER_SZ, + sendSz - RECORD_HEADER_SZ, extMsgType); + } + if (extMsgType == hello_retry_request) { + /* reset the ech state for round 2 */ + ((WOLFSSL_ECH*)echX->data)->state = ECH_WRITE_NONE; + } + else { + if (ret == 0) { + /* update serverRandom on success */ + XMEMCPY(ssl->arrays->serverRandom, + output + acceptOffset - + (RAN_LEN -ECH_ACCEPT_CONFIRMATION_SZ), RAN_LEN); + } + /* remove ech so we don't keep sending it in write */ + TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap); + } } } #endif @@ -8012,9 +8081,8 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, else ret = INVALID_PARAMETER; break; -#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - case PQC_SA_MAJOR: #if defined(HAVE_FALCON) + case FALCON_SA_MAJOR: if (input[1] == FALCON_LEVEL1_SA_MINOR) { *hsType = falcon_level1_sa_algo; /* Hash performed as part of sign/verify operation. */ @@ -8025,8 +8093,11 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, *hashAlgo = sha512_mac; } else + ret = INVALID_PARAMETER; + break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) + case DILITHIUM_SA_MAJOR: if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) { *hsType = dilithium_level2_sa_algo; /* Hash performed as part of sign/verify operation. */ @@ -8041,12 +8112,11 @@ static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo, *hashAlgo = sha512_mac; } else -#endif /* HAVE_DILITHIUM */ { ret = INVALID_PARAMETER; } break; -#endif +#endif /* HAVE_DILITHIUM */ default: *hashAlgo = input[0]; *hsType = input[1]; @@ -8466,7 +8536,7 @@ static word32 NextCert(byte* data, word32 length, word32* idx) * offset index offset * returns Total number of bytes written. */ -static word32 WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts, +static int WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts, word16* extSz, word16 extSz_num) { int ret = 0; @@ -8484,7 +8554,7 @@ static word32 WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts, if (csr) { for (extIdx = 0; extIdx < (word16)(extSz_num); extIdx++) { - tmpSz = TLSX_CSR_GetSize_ex(csr, 0, extIdx); + tmpSz = TLSX_CSR_GetSize_ex(csr, 0, (int)extIdx); if (tmpSz > (OPAQUE8_LEN + OPAQUE24_LEN) && certExts[extIdx] == NULL) { @@ -8519,7 +8589,7 @@ static word32 WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts, /* chain cert empty extension size */ totalSz += OPAQUE16_LEN * extSz_num; } - return totalSz; + return (int)totalSz; } #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */ /* Add certificate data and empty extension to output up to the fragment size. @@ -8622,6 +8692,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) ssl->options.sendVerify = SEND_CERT; } wolfSSL_X509_free(x509); + x509 = NULL; wolfSSL_EVP_PKEY_free(pkey); } } @@ -9141,41 +9212,12 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif #if defined(HAVE_FALCON) else if (ssl->hsType == DYNAMIC_TYPE_FALCON) { - falcon_key* fkey = (falcon_key*)ssl->hsKey; - byte level = 0; - if (wc_falcon_get_level(fkey, &level) != 0) { - ERROR_OUT(ALGO_ID_E, exit_scv); - } - if (level == 1) { - args->sigAlgo = falcon_level1_sa_algo; - } - else if (level == 5) { - args->sigAlgo = falcon_level5_sa_algo; - } - else { - ERROR_OUT(ALGO_ID_E, exit_scv); - } + args->sigAlgo = ssl->buffers.keyType; } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) else if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) { - dilithium_key* fkey = (dilithium_key*)ssl->hsKey; - byte level = 0; - if (wc_dilithium_get_level(fkey, &level) != 0) { - ERROR_OUT(ALGO_ID_E, exit_scv); - } - if (level == 2) { - args->sigAlgo = dilithium_level2_sa_algo; - } - else if (level == 3) { - args->sigAlgo = dilithium_level3_sa_algo; - } - else if (level == 5) { - args->sigAlgo = dilithium_level5_sa_algo; - } - else { - ERROR_OUT(ALGO_ID_E, exit_scv); - } + args->sigAlgo = ssl->buffers.keyType; } #endif /* HAVE_DILITHIUM */ else { @@ -9459,9 +9501,11 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) { - ret = wc_dilithium_sign_msg(args->sigData, args->sigDataSz, - sigOut, &args->sigLen, - (dilithium_key*)ssl->hsKey, ssl->rng); + ret = wc_dilithium_sign_ctx_msg(NULL, 0, args->sigData, + args->sigDataSz, sigOut, + &args->sigLen, + (dilithium_key*)ssl->hsKey, + ssl->rng); args->length = (word16)args->sigLen; } #endif /* HAVE_DILITHIUM */ @@ -9553,11 +9597,9 @@ static int SendTls13CertificateVerify(WOLFSSL* ssl) #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) if (ssl->hsAltType == DYNAMIC_TYPE_DILITHIUM) { - ret = wc_dilithium_sign_msg(args->altSigData, - args->altSigDataSz, sigOut, - &args->altSigLen, - (dilithium_key*)ssl->hsAltKey, - ssl->rng); + ret = wc_dilithium_sign_ctx_msg(NULL, 0, args->altSigData, + args->altSigDataSz, sigOut, &args->altSigLen, + (dilithium_key*)ssl->hsAltKey, ssl->rng); } #endif /* HAVE_DILITHIUM */ @@ -10147,13 +10189,13 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, #endif #ifdef HAVE_DILITHIUM case dilithium_level2_sa_algo: - ret = decodeDilithiumKey(ssl, 2); + ret = decodeDilithiumKey(ssl, WC_ML_DSA_44); break; case dilithium_level3_sa_algo: - ret = decodeDilithiumKey(ssl, 3); + ret = decodeDilithiumKey(ssl, WC_ML_DSA_65); break; case dilithium_level5_sa_algo: - ret = decodeDilithiumKey(ssl, 5); + ret = decodeDilithiumKey(ssl, WC_ML_DSA_87); break; #endif #ifdef HAVE_FALCON @@ -10542,6 +10584,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; } + else if ((ret >= 0) && (res == 0)) { + WOLFSSL_MSG("Falcon signature verification failed"); + ret = SIG_VERIFY_E; + } } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) @@ -10551,9 +10597,9 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (ssl->peerDilithiumKeyPresent)) { int res = 0; WOLFSSL_MSG("Doing Dilithium peer cert verify"); - ret = wc_dilithium_verify_msg(sig, args->sigSz, - args->sigData, args->sigDataSz, - &res, ssl->peerDilithiumKey); + ret = wc_dilithium_verify_ctx_msg(sig, args->sigSz, NULL, 0, + args->sigData, args->sigDataSz, + &res, ssl->peerDilithiumKey); if ((ret >= 0) && (res == 1)) { /* CLIENT/SERVER: data verified with public key from @@ -10564,6 +10610,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (void**)&ssl->peerDilithiumKey); ssl->peerDilithiumKeyPresent = 0; } + else if ((ret >= 0) && (res == 0)) { + WOLFSSL_MSG("Dilithium signature verification failed"); + ret = SIG_VERIFY_E; + } } #endif /* HAVE_DILITHIUM */ @@ -10644,6 +10694,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (void**)&ssl->peerFalconKey); ssl->peerFalconKeyPresent = 0; } + else if ((ret >= 0) && (res == 0)) { + WOLFSSL_MSG("Falcon signature verification failed"); + ret = SIG_VERIFY_E; + } } #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_VERIFY) @@ -10653,9 +10707,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (ssl->peerDilithiumKeyPresent)) { int res = 0; WOLFSSL_MSG("Doing Dilithium peer cert alt verify"); - ret = wc_dilithium_verify_msg(sig, args->altSignatureSz, - args->altSigData, args->altSigDataSz, - &res, ssl->peerDilithiumKey); + ret = wc_dilithium_verify_ctx_msg(sig, args->altSignatureSz, + NULL, 0, args->altSigData, + args->altSigDataSz, &res, + ssl->peerDilithiumKey); if ((ret >= 0) && (res == 1)) { /* CLIENT/SERVER: data verified with public key from @@ -10666,6 +10721,10 @@ static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, (void**)&ssl->peerDilithiumKey); ssl->peerDilithiumKeyPresent = 0; } + else if ((ret >= 0) && (res == 0)) { + WOLFSSL_MSG("Dilithium signature verification failed"); + ret = SIG_VERIFY_E; + } } #endif /* HAVE_DILITHIUM */ @@ -12692,16 +12751,15 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE) { - /* reset the inOutIdx to the outer start */ *inOutIdx = echInOutIdx; - /* call again with the inner hello */ - ret = DoTls13ClientHello(ssl, - ((WOLFSSL_ECH*)echX->data)->innerClientHello, - &echInOutIdx, - ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen); - + if (ret == 0) { + ret = DoTls13ClientHello(ssl, + ((WOLFSSL_ECH*)echX->data)->innerClientHello, + &echInOutIdx, + ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen); + } /* if the inner ech parsed successfully we have successfully * handled the hello and can skip the whole message */ if (ret == 0) @@ -13602,8 +13660,9 @@ int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group) } #endif -#if defined(WOLFSSL_HAVE_KYBER) - if (WOLFSSL_NAMED_GROUP_IS_PQC(group)) { +#if defined(WOLFSSL_HAVE_MLKEM) + if (WOLFSSL_NAMED_GROUP_IS_PQC(group) || + WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) { if (ssl->ctx != NULL && ssl->ctx->method != NULL && !IsAtLeastTLSv1_3(ssl->version)) { @@ -14884,7 +14943,7 @@ int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz) return WOLFSSL_FATAL_ERROR; } if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) { - ret = ReceiveData(ssl, (byte*)data, sz, FALSE); + ret = ReceiveData(ssl, (byte*)data, (size_t)sz, FALSE); if (ret > 0) *outSz = ret; if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN)) { @@ -15022,4 +15081,4 @@ int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret, #endif /* !WOLFCRYPT_ONLY */ -#endif /* WOLFSSL_TLS13 */ +#endif /* !NO_TLS && WOLFSSL_TLS13 */ diff --git a/src/src/wolfio.c b/src/src/wolfio.c index 5e62e9f..0809734 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -1,6 +1,6 @@ /* wolfio.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,11 +24,7 @@ #define WOLFSSL_STRERROR_BUFFER_SIZE 256 #endif -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef WOLFCRYPT_ONLY @@ -41,11 +37,6 @@ #include #endif -#ifdef _WIN32_WCE - /* On WinCE winsock2.h must be included before windows.h for socket stuff */ - #include -#endif - #include #include #include @@ -56,7 +47,9 @@ int Nucleus_Net_Errno; #endif #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT) - #ifndef USE_WINDOWS_API + #ifdef USE_WINDOWS_API + #include + #else #if defined(WOLFSSL_LWIP) && !defined(WOLFSSL_APACHE_MYNEWT) #elif defined(ARDUINO) #elif defined(FREESCALE_MQX) @@ -229,7 +222,7 @@ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) else return WOLFSSL_CBIO_ERR_TIMEOUT; } -#endif +#endif /* SOCKET_ETIMEDOUT */ else if (err == SOCKET_ECONNRESET) { WOLFSSL_MSG("\tConnection reset"); @@ -248,7 +241,7 @@ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) return WOLFSSL_CBIO_ERR_CONN_CLOSE; } -#if defined(_WIN32) +#if defined(_WIN32) && !defined(__WATCOMC__) strcpy_s(errstr, sizeof(errstr), "\tGeneral error: "); errstr_offset = strlen(errstr); FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, @@ -766,7 +759,7 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) else #endif /* WOLFSSL_DTLS13 */ timeout.tv_sec = dtls_timeout; - #endif + #endif /* USE_WINDOWS_API */ if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) != 0) { WOLFSSL_MSG("setsockopt rcvtimeo failed"); @@ -863,22 +856,22 @@ int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx) #ifndef WOLFSSL_PEER_ADDRESS_CHANGES else { ret = 0; -#ifdef WOLFSSL_RW_THREADED + #ifdef WOLFSSL_RW_THREADED if (wc_LockRwLock_Rd(&ssl->buffers.dtlsCtx.peerLock) != 0) return WOLFSSL_CBIO_ERR_GENERAL; -#endif + #endif /* WOLFSSL_RW_THREADED */ if (!sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa, dtlsCtx->peer.sz)) { ret = WOLFSSL_CBIO_ERR_GENERAL; } -#ifdef WOLFSSL_RW_THREADED + #ifdef WOLFSSL_RW_THREADED if (wc_UnLockRwLock(&ssl->buffers.dtlsCtx.peerLock) != 0) return WOLFSSL_CBIO_ERR_GENERAL; -#endif + #endif /* WOLFSSL_RW_THREADED */ if (ret != 0) return ret; } -#endif +#endif /* !WOLFSSL_PEER_ADDRESS_CHANGES */ } #ifndef NO_ASN_TIME ssl->dtls_start_timeout = 0; @@ -1095,7 +1088,7 @@ int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx) return WOLFSSL_SUCCESS; } -#endif +#endif /* WOLFSSL_DTLS */ /* get the peer information in human readable form (ip, port, family) * default function assumes BSD sockets @@ -1254,6 +1247,9 @@ int wolfIO_SendTo(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int wr ret = ioctlsocket(sockfd, FIONBIO, &blocking); if (ret == SOCKET_ERROR) ret = WOLFSSL_FATAL_ERROR; + #elif defined(__WATCOMC__) && defined(__OS2__) + if (ioctl(sockfd, FIONBIO, &non_blocking) == -1) + ret = WOLFSSL_FATAL_ERROR; #else ret = fcntl(sockfd, F_GETFL, 0); if (ret >= 0) { @@ -1293,9 +1289,9 @@ int wolfIO_SendTo(SOCKET_T sd, WOLFSSL_BIO_ADDR *addr, char *buf, int sz, int wr ret = select(nfds, &rfds, &wfds, NULL, &timeout); if (ret == 0) { - #ifdef DEBUG_HTTP + #ifdef DEBUG_HTTP fprintf(stderr, "Timeout: %d\n", ret); - #endif + #endif return HTTP_TIMEOUT; } else if (ret > 0) { @@ -1360,13 +1356,13 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) #else HOSTENT *entry; #endif -#endif +#endif /* !WOLFSSL_USE_POPEN_HOST */ #ifdef WOLFSSL_IPV6 SOCKADDR_IN6 *sin; #else SOCKADDR_IN *sin; -#endif -#endif /* HAVE_SOCKADDR */ +#endif /* WOLFSSL_IPV6 */ +#endif /* HAVE_GETADDRINFO */ if (sockfd == NULL || ip == NULL) { return WOLFSSL_FATAL_ERROR; @@ -1377,8 +1373,8 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) sockaddr_len = sizeof(SOCKADDR_IN6); #else sockaddr_len = sizeof(SOCKADDR_IN); -#endif -#endif +#endif /* WOLFSSL_IPV6 */ +#endif /* !HAVE_GETADDRINFO */ XMEMSET(&addr, 0, sizeof(addr)); #ifdef WOLFIO_DEBUG @@ -1496,7 +1492,8 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) sin = (SOCKADDR_IN *)&addr; sin->sin_family = AF_INET; sin->sin_port = XHTONS(port); - XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], entry->h_length); + XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], + (size_t)entry->h_length); #endif } @@ -1530,7 +1527,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) } #else (void)to_sec; -#endif +#endif /* HAVE_IO_TIMEOUT */ ret = connect(*sockfd, (SOCKADDR *)&addr, sockaddr_len); #ifdef HAVE_IO_TIMEOUT @@ -1549,7 +1546,7 @@ int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec) wolfIO_SetBlockingMode(*sockfd, 0); } } -#endif +#endif /* HAVE_IO_TIMEOUT */ if (ret != 0) { WOLFSSL_MSG("Responder tcp connect failed"); CloseSocket(*sockfd); @@ -2671,7 +2668,7 @@ int MicriumReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx) } } } - #endif + #endif /* WOLFSSL_DTLS */ ret = NetSock_RxData(sd, buf, sz, ssl->rflags, &err); if (ret < 0) { @@ -3423,7 +3420,7 @@ int wolfSSL_SetIO_LwIP(WOLFSSL* ssl, void* pcb, return ERR_OK; } -#endif +#endif /* WOLFSSL_LWIP_NATIVE */ #ifdef WOLFSSL_ISOTP static int isotp_send_single_frame(struct isotp_wolfssl_ctx *ctx, char *buf, @@ -3808,5 +3805,5 @@ int wolfSSL_SetIO_ISOTP(WOLFSSL *ssl, isotp_wolfssl_ctx *ctx, } return 0; } -#endif +#endif /* WOLFSSL_ISOTP */ #endif /* WOLFCRYPT_ONLY */ diff --git a/src/src/x509.c b/src/src/x509.c index d656815..62e3774 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -1,6 +1,6 @@ /* x509.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_X509_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -481,6 +476,24 @@ int wolfSSL_X509_get_ext_by_OBJ(const WOLFSSL_X509 *x, return WOLFSSL_FATAL_ERROR; } + +int wolfSSL_X509_OBJECT_set1_X509(WOLFSSL_X509_OBJECT *a, WOLFSSL_X509 *obj) +{ + WOLFSSL_STUB("wolfSSL_X509_OBJECT_set1_X509"); + (void)a; + (void)obj; + return 0; +} + +int wolfSSL_X509_OBJECT_set1_X509_CRL(WOLFSSL_X509_OBJECT *a, + WOLFSSL_X509_CRL *obj) +{ + WOLFSSL_STUB("wolfSSL_X509_OBJECT_set1_X509_CRL"); + (void)a; + (void)obj; + return 0; +} + #endif /* OPENSSL_ALL || OPENSSL_EXTRA */ #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \ @@ -1181,12 +1194,24 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) } } - ext->obj->objSz = (unsigned int)objSz; if (((ext->obj->dynamic & WOLFSSL_ASN1_DYNAMIC_DATA) != 0) || (ext->obj->obj == NULL)) { - ext->obj->obj =(byte*)XREALLOC((byte*)ext->obj->obj, - ext->obj->objSz, - NULL,DYNAMIC_TYPE_ASN1); + #ifdef WOLFSSL_NO_REALLOC + byte* tmp = NULL; + + tmp = (byte*)XMALLOC(objSz, NULL, DYNAMIC_TYPE_ASN1); + if (tmp != NULL && ext->obj->obj != NULL) { + XMEMCPY(tmp, ext->obj->obj, ext->obj->objSz); + XFREE((byte*)ext->obj->obj, NULL, DYNAMIC_TYPE_ASN1); + } + else if (tmp == NULL) { + ext->obj->obj = tmp; + } + ext->obj->obj = tmp; + #else + ext->obj->obj = (byte*)XREALLOC((byte*)ext->obj->obj, objSz, + NULL, DYNAMIC_TYPE_ASN1); + #endif if (ext->obj->obj == NULL) { wolfSSL_X509_EXTENSION_free(ext); FreeDecodedCert(cert); @@ -1201,6 +1226,8 @@ WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x509, int loc) else { ext->obj->dynamic &= ~WOLFSSL_ASN1_DYNAMIC_DATA; } + ext->obj->objSz = (unsigned int)objSz; + /* Get OID from input and copy to ASN1_OBJECT buffer */ XMEMCPY(oidBuf+2, input+idx, length); XMEMCPY((byte*)ext->obj->obj, oidBuf, ext->obj->objSz); @@ -1663,10 +1690,10 @@ int wolfSSL_X509_EXTENSION_set_critical(WOLFSSL_X509_EXTENSION* ex, int crit) * Returns NULL on error or pointer to the v3_ext_method populated with * extension type-specific X509V3_EXT_* function(s). * - * NOTE: WC_NID_subject_key_identifier is currently the only extension implementing - * the X509V3_EXT_* functions, as it is the only type called directly by QT. The - * other extension types return a pointer to a v3_ext_method struct that - * contains only the NID. + * NOTE: WC_NID_subject_key_identifier is currently the only extension + * implementing the X509V3_EXT_* functions, as it is the only type called + * directly by QT. The other extension types return a pointer to a + * v3_ext_method struct that contains only the NID. */ #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L const WOLFSSL_v3_ext_method* wolfSSL_X509V3_EXT_get(WOLFSSL_X509_EXTENSION* ex) @@ -1690,7 +1717,6 @@ WOLFSSL_v3_ext_method* wolfSSL_X509V3_EXT_get(WOLFSSL_X509_EXTENSION* ex) WOLFSSL_MSG("Failed to get nid from passed extension object"); return NULL; } - XMEMSET(&method, 0, sizeof(WOLFSSL_v3_ext_method)); switch (nid) { case WC_NID_basic_constraints: break; @@ -2333,7 +2359,11 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } dns = dns->next; - if (wolfSSL_sk_GENERAL_NAME_push(sk, gn) <= 0) { + /* Using wolfSSL_sk_insert to maintain backwards + * compatibility with earlier versions of _push API that + * pushed items to the start of the list instead of the + * end. */ + if (wolfSSL_sk_insert(sk, gn, 0) <= 0) { WOLFSSL_MSG("Error pushing ASN1 object onto stack"); goto err; } @@ -3569,9 +3599,8 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) WOLFSSL_MSG("Memory error"); return NULL; } - if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s, ", sn, buf)) - >= strSz) - { + strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s, ", sn, buf); + if ((strLen < 0) || (strLen >= strSz)) { WOLFSSL_MSG("buffer overrun"); XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER); return NULL; @@ -3587,8 +3616,8 @@ char* wolfSSL_X509_get_name_oneline(WOLFSSL_X509_NAME* name, char* in, int sz) WOLFSSL_MSG("Memory error"); return NULL; } - if ((strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s", sn, - buf)) >= strSz) { + strLen = XSNPRINTF(str, (size_t)strSz, "%s=%s", sn, buf); + if ((strLen < 0) || (strLen >= strSz)) { WOLFSSL_MSG("buffer overrun"); XFREE(str, NULL, DYNAMIC_TYPE_TMP_BUFFER); return NULL; @@ -4177,30 +4206,7 @@ int wolfSSL_sk_X509_push(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk, /* Return and remove the last x509 pushed on stack */ WOLFSSL_X509* wolfSSL_sk_X509_pop(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_X509* x509; - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - x509 = sk->data.x509; - - if (node != NULL) { /* update sk and remove node from stack */ - sk->data.x509 = node->data.x509; - sk->next = node->next; - XFREE(node, NULL, DYNAMIC_TYPE_X509); - } - else { /* last x509 in stack */ - sk->data.x509 = NULL; - } - - if (sk->num > 0) { - sk->num--; - } - - return x509; + return (WOLFSSL_X509*)wolfSSL_sk_pop(sk); } /* Getter function for WOLFSSL_X509 pointer @@ -4227,38 +4233,7 @@ WOLFSSL_X509* wolfSSL_sk_X509_value(WOLF_STACK_OF(WOLFSSL_X509)* sk, int i) /* Return and remove the first x509 pushed on stack */ WOLFSSL_X509* wolfSSL_sk_X509_shift(WOLF_STACK_OF(WOLFSSL_X509)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_X509* x509; - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - x509 = sk->data.x509; - - if (node != NULL) { - /* walk to end of stack to first node pushed, and remove it */ - WOLFSSL_STACK* prevNode = sk; - - while (node->next != NULL) { - prevNode = node; - node = node->next; - } - - x509 = node->data.x509; - prevNode->next = NULL; - XFREE(node, NULL, DYNAMIC_TYPE_X509); - } - else { /* only one x509 in stack */ - sk->data.x509 = NULL; - } - - if (sk->num > 0) { - sk->num -= 1; - } - - return x509; + return (WOLFSSL_X509*)wolfSSL_sk_pop_node(sk, 0); } #endif /* OPENSSL_EXTRA */ @@ -4528,7 +4503,8 @@ WOLFSSL_GENERAL_NAME* wolfSSL_GENERAL_NAME_dup(WOLFSSL_GENERAL_NAME* gn) * WOLFSSL_SUCCESS otherwise. */ int wolfSSL_GENERAL_NAME_set0_othername(WOLFSSL_GENERAL_NAME* gen, - WOLFSSL_ASN1_OBJECT* oid, WOLFSSL_ASN1_TYPE* value) + WOLFSSL_ASN1_OBJECT* oid, + WOLFSSL_ASN1_TYPE* value) { WOLFSSL_ASN1_OBJECT *x = NULL; @@ -4570,17 +4546,7 @@ int wolfSSL_sk_GENERAL_NAME_push(WOLFSSL_GENERAL_NAMES* sk, */ WOLFSSL_GENERAL_NAME* wolfSSL_sk_GENERAL_NAME_value(WOLFSSL_STACK* sk, int idx) { - WOLFSSL_STACK* ret; - - if (sk == NULL) { - return NULL; - } - - ret = wolfSSL_sk_get_node(sk, idx); - if (ret != NULL) { - return ret->data.gn; - } - return NULL; + return (WOLFSSL_GENERAL_NAME*)wolfSSL_sk_value(sk, idx); } /* Gets the number of nodes in the stack @@ -4593,11 +4559,7 @@ int wolfSSL_sk_GENERAL_NAME_num(WOLFSSL_STACK* sk) { WOLFSSL_ENTER("wolfSSL_sk_GENERAL_NAME_num"); - if (sk == NULL) { - return WOLFSSL_FATAL_ERROR; - } - - return (int)sk->num; + return wolfSSL_sk_num(sk); } /* Allocates an empty GENERAL NAME stack */ @@ -5268,7 +5230,8 @@ WOLFSSL_X509* wolfSSL_X509_load_certificate_file(const char* fname, int format) #endif /* !NO_FILESYSTEM */ static WOLFSSL_X509* loadX509orX509REQFromBuffer( - const unsigned char* buf, int sz, int format, int type) + const unsigned char* buf, int sz, int format, int type, + wc_pem_password_cb *cb, void *u) { int ret = 0; @@ -5278,8 +5241,15 @@ static WOLFSSL_X509* loadX509orX509REQFromBuffer( WOLFSSL_ENTER("wolfSSL_X509_load_certificate_ex"); if (format == WOLFSSL_FILETYPE_PEM) { + EncryptedInfo info; + XMEMSET(&info, 0, sizeof(EncryptedInfo)); + #ifdef WOLFSSL_ENCRYPTED_KEYS + info.passwd_cb = cb; + info.passwd_userdata = u; + #endif + #ifdef WOLFSSL_PEM_TO_DER - ret = PemToDer(buf, sz, type, &der, NULL, NULL, NULL); + ret = PemToDer(buf, sz, type, &der, NULL, &info, NULL); if (ret != 0) { FreeDer(&der); } @@ -5343,6 +5313,9 @@ static WOLFSSL_X509* loadX509orX509REQFromBuffer( WOLFSSL_ERROR(ret); } + /* unused parameter when built without WOLFSSL_ENCRYPTED_KEYS */ + (void)cb; + (void)u; return x509; } @@ -5350,7 +5323,7 @@ WOLFSSL_X509* wolfSSL_X509_load_certificate_buffer( const unsigned char* buf, int sz, int format) { return loadX509orX509REQFromBuffer(buf, sz, - format, CERT_TYPE); + format, CERT_TYPE, NULL, NULL); } #ifdef WOLFSSL_CERT_REQ @@ -5358,7 +5331,7 @@ WOLFSSL_X509* wolfSSL_X509_REQ_load_certificate_buffer( const unsigned char* buf, int sz, int format) { return loadX509orX509REQFromBuffer(buf, sz, - format, CERTREQ_TYPE); + format, CERTREQ_TYPE, NULL, NULL); } #endif @@ -6997,7 +6970,7 @@ static int X509PrintPubKey(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) case ECDSAk: len = XSNPRINTF(scratch, MAX_WIDTH, "%*sPublic Key Algorithm: EC\n", indent + 4, ""); - if (len >= MAX_WIDTH) + if ((len < 0) || (len >= MAX_WIDTH)) return WOLFSSL_FAILURE; if (wolfSSL_BIO_write(bio, scratch, len) <= 0) return WOLFSSL_FAILURE; @@ -7059,22 +7032,21 @@ static int X509PrintVersion(WOLFSSL_BIO* bio, int version, int indent) char scratch[MAX_WIDTH]; int scratchLen; - if ((scratchLen = XSNPRINTF(scratch, MAX_WIDTH, - "%*s%s", indent, "", "Version:")) - >= MAX_WIDTH) - { + scratchLen = XSNPRINTF(scratch, MAX_WIDTH, "%*s%s", indent, "", "Version:"); + if ((scratchLen < 0) || (scratchLen >= MAX_WIDTH)) { return WOLFSSL_FAILURE; } + if (wolfSSL_BIO_write(bio, scratch, scratchLen) <= 0) { return WOLFSSL_FAILURE; } - if ((scratchLen = XSNPRINTF(scratch, MAX_WIDTH, - " %d (0x%x)\n", version, (byte)version-1)) - >= MAX_WIDTH) - { + scratchLen = XSNPRINTF(scratch, MAX_WIDTH, " %d (0x%x)\n", + version, (byte)version-1); + if ((scratchLen < 0) || (scratchLen >= MAX_WIDTH)) { return WOLFSSL_FAILURE; } + if (wolfSSL_BIO_write(bio, scratch, scratchLen) <= 0) { return WOLFSSL_FAILURE; } @@ -8042,11 +8014,22 @@ int wolfSSL_i2d_X509(WOLFSSL_X509* x509, unsigned char** out) } #ifdef WOLFSSL_DUAL_ALG_CERTS +/* Generate a der preTBS from a decoded cert, and write + * to buffer. + * + * @param [in] cert The decoded cert to parse. + * @param [out] der The der buffer to write in. + * @param [in] derSz The der buffer size. + * + * @return preTBS der size on success. + * */ int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { int ret = 0; WOLFSSL_X509 *x = NULL; byte certIsCSR = 0; + WOLFSSL_ENTER("wc_GeneratePreTBS"); + if ((cert == NULL) || (der == NULL) || (derSz <= 0)) { return BAD_FUNC_ARG; } @@ -8079,6 +8062,7 @@ int wc_GeneratePreTBS(DecodedCert* cert, byte *der, int derSz) { if (x != NULL) { wolfSSL_X509_free(x); + x = NULL; } return ret; @@ -10343,6 +10327,19 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_chain_up_ref( } #endif +#if defined(OPENSSL_EXTRA) + +WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_sk_X509_OBJECT_deep_copy( + const WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* sk, + WOLFSSL_X509_OBJECT* (*c)(const WOLFSSL_X509_OBJECT*), + void (*f)(WOLFSSL_X509_OBJECT*)) +{ + (void)f; /* free function */ + (void)c; /* copy function */ + return wolfSSL_sk_dup((WOLFSSL_STACK*)sk); +} +#endif + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) void wolfSSL_X509_NAME_free(WOLFSSL_X509_NAME *name) { @@ -10607,7 +10604,10 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) cert->sigType = wolfSSL_X509_get_signature_type(x509); cert->keyType = x509->pubKeyOID; cert->isCA = wolfSSL_X509_get_isCA(x509); + cert->basicConstCrit = x509->basicConstCrit; cert->basicConstSet = x509->basicConstSet; + cert->pathLen = x509->pathLength; + cert->pathLenSet = x509->pathLengthSet; #ifdef WOLFSSL_CERT_EXT if (x509->subjKeyIdSz <= CTC_MAX_SKID_SIZE) { @@ -10674,10 +10674,13 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) /* We point to instance in x509 so DON'T need to be free'd. */ cert->sapkiDer = x509->sapkiDer; cert->sapkiLen = x509->sapkiLen; + cert->sapkiCrit = x509->sapkiCrit; cert->altSigAlgDer = x509->altSigAlgDer; - cert->altSigAlgLen = x509->altSigAlgLen; + cert->altSigAlgLen = x509->altSigAlgLen; + cert->altSigAlgCrit = x509->altSigAlgCrit; cert->altSigValDer = x509->altSigValDer; cert->altSigValLen = x509->altSigValLen; + cert->altSigValCrit = x509->altSigValCrit; #endif /* WOLFSSL_DUAL_ALG_CERTS */ #endif /* WOLFSSL_CERT_EXT */ @@ -11052,9 +11055,15 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) } #endif #if defined(HAVE_DILITHIUM) - if ((x509->pubKeyOID == DILITHIUM_LEVEL2k) || - (x509->pubKeyOID == DILITHIUM_LEVEL3k) || - (x509->pubKeyOID == DILITHIUM_LEVEL5k)) { + if ((x509->pubKeyOID == ML_DSA_LEVEL2k) || + (x509->pubKeyOID == ML_DSA_LEVEL3k) || + (x509->pubKeyOID == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (x509->pubKeyOID == DILITHIUM_LEVEL2k) + || (x509->pubKeyOID == DILITHIUM_LEVEL3k) + || (x509->pubKeyOID == DILITHIUM_LEVEL5k) + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + ) { dilithium = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL, DYNAMIC_TYPE_DILITHIUM); if (dilithium == NULL) { @@ -11070,18 +11079,32 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) return ret; } - if (x509->pubKeyOID == DILITHIUM_LEVEL2k) { + if (x509->pubKeyOID == ML_DSA_LEVEL2k) { + type = ML_DSA_LEVEL2_TYPE; + wc_dilithium_set_level(dilithium, WC_ML_DSA_44); + } + else if (x509->pubKeyOID == ML_DSA_LEVEL3k) { + type = ML_DSA_LEVEL3_TYPE; + wc_dilithium_set_level(dilithium, WC_ML_DSA_65); + } + else if (x509->pubKeyOID == ML_DSA_LEVEL5k) { + type = ML_DSA_LEVEL5_TYPE; + wc_dilithium_set_level(dilithium, WC_ML_DSA_87); + } + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + else if (x509->pubKeyOID == DILITHIUM_LEVEL2k) { type = DILITHIUM_LEVEL2_TYPE; - wc_dilithium_set_level(dilithium, 2); + wc_dilithium_set_level(dilithium, WC_ML_DSA_44_DRAFT); } else if (x509->pubKeyOID == DILITHIUM_LEVEL3k) { type = DILITHIUM_LEVEL3_TYPE; - wc_dilithium_set_level(dilithium, 3); + wc_dilithium_set_level(dilithium, WC_ML_DSA_65_DRAFT); } else if (x509->pubKeyOID == DILITHIUM_LEVEL5k) { type = DILITHIUM_LEVEL5_TYPE; - wc_dilithium_set_level(dilithium, 5); + wc_dilithium_set_level(dilithium, WC_ML_DSA_87_DRAFT); } + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ ret = wc_Dilithium_PublicKeyDecode(x509->pubKey.buffer, &idx, dilithium, x509->pubKey.length); @@ -11262,9 +11285,15 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) } #endif #if defined(HAVE_DILITHIUM) - if ((x509->pubKeyOID == DILITHIUM_LEVEL2k) || - (x509->pubKeyOID == DILITHIUM_LEVEL3k) || - (x509->pubKeyOID == DILITHIUM_LEVEL5k)) { + if ((x509->pubKeyOID == ML_DSA_LEVEL2k) || + (x509->pubKeyOID == ML_DSA_LEVEL3k) || + (x509->pubKeyOID == ML_DSA_LEVEL5k) + #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT + || (x509->pubKeyOID == DILITHIUM_LEVEL2k) + || (x509->pubKeyOID == DILITHIUM_LEVEL3k) + || (x509->pubKeyOID == DILITHIUM_LEVEL5k) + #endif + ) { wc_dilithium_free(dilithium); XFREE(dilithium, NULL, DYNAMIC_TYPE_DILITHIUM); } @@ -11941,12 +11970,12 @@ static WOLFSSL_X509 *loadX509orX509REQFromPemBio(WOLFSSL_BIO *bp, pemSz = (int)i; #ifdef WOLFSSL_CERT_REQ if (type == CERTREQ_TYPE) - x509 = wolfSSL_X509_REQ_load_certificate_buffer(pem, pemSz, - WOLFSSL_FILETYPE_PEM); + x509 = loadX509orX509REQFromBuffer(pem, pemSz, WOLFSSL_FILETYPE_PEM, + CERTREQ_TYPE, cb, u); else #endif - x509 = wolfSSL_X509_load_certificate_buffer(pem, pemSz, - WOLFSSL_FILETYPE_PEM); + x509 = loadX509orX509REQFromBuffer(pem, pemSz, WOLFSSL_FILETYPE_PEM, + CERT_TYPE, cb, u); } if (x != NULL) { @@ -12671,6 +12700,7 @@ WOLFSSL_API WOLFSSL_X509_CRL* wolfSSL_PEM_read_X509_CRL(XFILE fp, return ne; } + static void wolfssl_x509_name_entry_set(WOLFSSL_X509_NAME_ENTRY* ne, int nid, int type, const unsigned char *data, int dataSz) { @@ -13075,6 +13105,17 @@ WOLFSSL_ASN1_OBJECT* wolfSSL_X509_NAME_ENTRY_get_object( #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \ defined(OPENSSL_EXTRA_X509_SMALL) +#ifdef OPENSSL_EXTRA + int wolfSSL_X509_NAME_ENTRY_set(const WOLFSSL_X509_NAME_ENTRY *ne) + { + if (ne != NULL) { + return ne->set; + } + return 0; + } +#endif + + /* returns a pointer to the internal entry at location 'loc' on success, * a null pointer is returned in fail cases */ WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_get_entry( @@ -13342,30 +13383,7 @@ WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_value( WOLFSSL_X509_NAME* wolfSSL_sk_X509_NAME_pop( WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_X509_NAME* name; - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - name = sk->data.name; - - if (node != NULL) { /* update sk and remove node from stack */ - sk->data.name = node->data.name; - sk->next = node->next; - XFREE(node, NULL, DYNAMIC_TYPE_OPENSSL); - } - else { /* last x509 in stack */ - sk->data.name = NULL; - } - - if (sk->num > 0) { - sk->num -= 1; - } - - return name; + return (WOLFSSL_X509_NAME*)wolfSSL_sk_pop(sk); } void wolfSSL_sk_X509_NAME_pop_free(WOLF_STACK_OF(WOLFSSL_X509_NAME)* sk, @@ -13516,30 +13534,7 @@ WOLFSSL_X509_INFO* wolfSSL_sk_X509_INFO_value( WOLFSSL_X509_INFO* wolfSSL_sk_X509_INFO_pop( WOLF_STACK_OF(WOLFSSL_X509_INFO)* sk) { - WOLFSSL_STACK* node; - WOLFSSL_X509_INFO* info; - - if (sk == NULL) { - return NULL; - } - - node = sk->next; - info = sk->data.info; - - if (node != NULL) { /* update sk and remove node from stack */ - sk->data.info = node->data.info; - sk->next = node->next; - wolfSSL_sk_free_node(node); - } - else { /* last x509 in stack */ - sk->data.info = NULL; - } - - if (sk->num > 0) { - sk->num -= 1; - } - - return info; + return (WOLFSSL_X509_INFO*)wolfSSL_sk_pop(sk); } #if defined(OPENSSL_ALL) @@ -13848,7 +13843,8 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, int tmpSz; /* reverse name order for RFC2253 and DN_REV */ - if ((flags & WOLFSSL_XN_FLAG_RFC2253) || (flags & WOLFSSL_XN_FLAG_DN_REV)) { + if ((flags & WOLFSSL_XN_FLAG_RFC2253) || + (flags & WOLFSSL_XN_FLAG_DN_REV)) { ne = wolfSSL_X509_NAME_get_entry(name, count - i - 1); } else { @@ -13986,6 +13982,11 @@ void wolfSSL_X509_OBJECT_free(WOLFSSL_X509_OBJECT *obj) if (obj->type == WOLFSSL_X509_LU_X509) { wolfSSL_X509_free(obj->data.x509); } + #ifdef HAVE_CRL + else if (obj->type == WOLFSSL_X509_LU_CRL) { + wolfSSL_X509_CRL_free(obj->data.crl); + } + #endif else { /* We don't free as this will point to * store->cm->crl which we don't own */ @@ -15190,7 +15191,10 @@ int wolfSSL_X509_REQ_add1_attr_by_NID(WOLFSSL_X509 *req, } if ((req->reqAttributes != NULL) && (req->reqAttributes->type == STACK_TYPE_X509_REQ_ATTR)) { - ret = wolfSSL_sk_push(req->reqAttributes, attr) > 0 + /* Using wolfSSL_sk_insert to maintain backwards compatibility with + * earlier versions of _push API that pushed items to the start of + * the list instead of the end. */ + ret = wolfSSL_sk_insert(req->reqAttributes, attr, 0) > 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } else { @@ -15275,7 +15279,6 @@ WOLFSSL_X509_ATTRIBUTE *wolfSSL_X509_REQ_get_attr( int wolfSSL_X509_REQ_get_attr_by_NID(const WOLFSSL_X509 *req, int nid, int lastpos) { - WOLFSSL_STACK* sk; int idx; WOLFSSL_ENTER("wolfSSL_X509_REQ_get_attr_by_NID"); @@ -15286,26 +15289,14 @@ int wolfSSL_X509_REQ_get_attr_by_NID(const WOLFSSL_X509 *req, } /* search through stack for first matching nid */ - idx = lastpos + 1; - do { - sk = wolfSSL_sk_get_node(req->reqAttributes, idx); - if (sk != NULL) { - WOLFSSL_X509_ATTRIBUTE* attr; - attr = (WOLFSSL_X509_ATTRIBUTE*)sk->data.generic; - if (nid == attr->object->nid) { - /* found a match */ - break; - } - } - idx++; - } while (sk != NULL); - - /* no matches found */ - if (sk == NULL) { - idx = WOLFSSL_FATAL_ERROR; + for (idx = lastpos + 1; idx < wolfSSL_sk_num(req->reqAttributes); idx++) { + WOLFSSL_X509_ATTRIBUTE* attr = + (WOLFSSL_X509_ATTRIBUTE*)wolfSSL_sk_value(req->reqAttributes, idx); + if (attr != NULL && attr->object != NULL && attr->object->nid == nid) + return idx; } - return idx; + return WOLFSSL_FATAL_ERROR; } WOLFSSL_X509_ATTRIBUTE* wolfSSL_X509_ATTRIBUTE_new(void) @@ -15638,6 +15629,17 @@ int wolfSSL_X509_ACERT_verify(WOLFSSL_X509_ACERT* x509, WOLFSSL_EVP_PKEY* pkey) return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; } +/* Loads an x509 attribute certificate from buffer, and returns + * pointer to new WOLFSSL_X509_ACERT struct on success. + * + * @param [in] buf The acert buffer to load. + * @param [in] sz The size of the buffer. + * @param [in] format The format of the buffer data. + * @param [in] heap Dynamic memory allocation hint. + * + * @return pointer to WOLFSSL_X509_ACERT on success. + * @return NULL on error. + * */ WOLFSSL_X509_ACERT * wolfSSL_X509_ACERT_load_certificate_buffer_ex( const unsigned char* buf, int sz, int format, void * heap) { diff --git a/src/src/x509_str.c b/src/src/x509_str.c index 894da16..fedf4a0 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -1,6 +1,6 @@ /* x509_str.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_X509_STORE_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -105,6 +100,7 @@ void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) if (ctx->current_issuer != NULL) { wolfSSL_X509_free(ctx->current_issuer); + ctx->current_issuer = NULL; } #endif @@ -114,8 +110,7 @@ void wolfSSL_X509_STORE_CTX_free(WOLFSSL_X509_STORE_CTX* ctx) #ifdef OPENSSL_EXTRA -#if ((defined(SESSION_CERTS) && !defined(WOLFSSL_QT)) || \ - defined(WOLFSSL_SIGNER_DER_CERT)) +#if defined(SESSION_CERTS) || defined(WOLFSSL_SIGNER_DER_CERT) /** * Find the issuing cert of the input cert. On a self-signed cert this @@ -809,10 +804,28 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) if (sk == NULL) return NULL; + for (i = 0; i < c->count; i++) { + WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, i); + + if (x509 == NULL) { + WOLFSSL_MSG("Unable to get x509 from chain"); + error = 1; + break; + } + + if (wolfSSL_sk_X509_push(sk, x509) <= 0) { + WOLFSSL_MSG("Unable to load x509 into stack"); + wolfSSL_X509_free(x509); + x509 = NULL; + error = 1; + break; + } + } + #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ defined(OPENSSL_EXTRA) /* add CA used to verify top of chain to the list */ - if (c->count > 0) { + if (!error && c->count > 0) { WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, c->count - 1); WOLFSSL_X509* issuer = NULL; if (x509 != NULL) { @@ -825,11 +838,14 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) if (wolfSSL_sk_X509_push(sk, issuer) <= 0) { WOLFSSL_MSG("Unable to load CA x509 into stack"); error = 1; + wolfSSL_X509_free(issuer); + issuer = NULL; } } else { WOLFSSL_MSG("Certificate is self signed"); wolfSSL_X509_free(issuer); + issuer = NULL; } } else { @@ -837,30 +853,9 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_CTX_get_chain(WOLFSSL_X509_STORE_CTX* ctx) } } wolfSSL_X509_free(x509); - if (error) { - wolfSSL_sk_X509_pop_free(sk, NULL); - wolfSSL_X509_free(issuer); - return NULL; - } + x509 = NULL; } #endif - - for (i = c->count - 1; i >= 0; i--) { - WOLFSSL_X509* x509 = wolfSSL_get_chain_X509(c, i); - - if (x509 == NULL) { - WOLFSSL_MSG("Unable to get x509 from chain"); - error = 1; - break; - } - - if (wolfSSL_sk_X509_push(sk, x509) <= 0) { - WOLFSSL_MSG("Unable to load x509 into stack"); - wolfSSL_X509_free(x509); - error = 1; - break; - } - } if (error) { wolfSSL_sk_X509_pop_free(sk, NULL); return NULL; @@ -978,6 +973,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_X509_STORE_get1_certs( <= 0) { err = 1; wolfSSL_X509_free(filteredCert); + filteredCert = NULL; break; } } @@ -1415,6 +1411,7 @@ int wolfSSL_X509_STORE_add_cert(WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509) else { result = WOLFSSL_FATAL_ERROR; wolfSSL_X509_free(x509); + x509 = NULL; } } } @@ -1430,6 +1427,7 @@ int wolfSSL_X509_STORE_add_cert(WOLFSSL_X509_STORE* store, WOLFSSL_X509* x509) else { result = WOLFSSL_FATAL_ERROR; wolfSSL_X509_free(x509); + x509 = NULL; } } } @@ -1474,18 +1472,10 @@ int wolfSSL_X509_STORE_set_flags(WOLFSSL_X509_STORE* store, unsigned long flag) return ret; } - -int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE* store) -{ - (void)store; - return WOLFSSL_SUCCESS; -} - int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, byte *buf, word32 bufLen, int type) { int ret = WOLFSSL_SUCCESS; - WOLFSSL_X509 *x509 = NULL; if (str == NULL || buf == NULL) { @@ -1494,21 +1484,26 @@ int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str, /* OpenSSL X509_STORE_load_file fails on DER file, we will as well */ x509 = wolfSSL_X509_load_certificate_buffer(buf, bufLen, type); - if (str->owned != NULL) { - if (wolfSSL_sk_X509_push(str->owned, x509) <= 0) { + if (x509 != NULL) { + ret = wolfSSL_X509_STORE_add_cert(str, x509); + if (ret != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to load file"); ret = WOLFSSL_FAILURE; } + if (ret == WOLFSSL_SUCCESS && str->owned != NULL) { + if (wolfSSL_sk_X509_push(str->owned, x509) <= 0) { + ret = WOLFSSL_FAILURE; + } + else { + x509 = NULL; + } + } + wolfSSL_X509_free(x509); + x509 = NULL; } - if (ret == WOLFSSL_SUCCESS) { - ret = wolfSSL_X509_STORE_add_cert(str, x509); - } - if (ret != WOLFSSL_SUCCESS) { - WOLFSSL_MSG("Failed to load file"); + else { ret = WOLFSSL_FAILURE; } - if (ret != WOLFSSL_SUCCESS || str->owned == NULL) { - wolfSSL_X509_free(x509); - } return ret; } @@ -1560,6 +1555,8 @@ static int X509StoreLoadFile(WOLFSSL_X509_STORE *str, static_buffer_init(&content, stackBuffer, FILE_BUFFER_SIZE); #endif + WOLFSSL_MSG_EX("X509StoreLoadFile: Loading file: %s", fname); + ret = X509StoreReadFile(fname, &content, &contentLen, &type); if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to load file"); @@ -1681,6 +1678,27 @@ WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, return ret; } + +#if defined(XGETENV) && !defined(NO_GETENV) +int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE *str) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + char* certDir = NULL; + char* certFile = NULL; + + WOLFSSL_ENTER("wolfSSL_X509_STORE_set_default_paths"); + + certFile = wc_strdup_ex(XGETENV("SSL_CERT_FILE"), DYNAMIC_TYPE_TMP_BUFFER); + certDir = wc_strdup_ex(XGETENV("SSL_CERT_DIR"), DYNAMIC_TYPE_TMP_BUFFER); + + ret = wolfSSL_X509_STORE_load_locations(str, certFile, certDir); + + XFREE(certFile, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(certDir, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return ret; +} +#endif /* XGETENV && !NO_GETENV */ + #endif /* !NO_FILESYSTEM && !NO_WOLFSSL_DIR */ int wolfSSL_X509_CA_num(WOLFSSL_X509_STORE* store) @@ -1778,6 +1796,7 @@ WOLFSSL_STACK* wolfSSL_X509_STORE_GetCerts(WOLFSSL_X509_STORE_CTX* s) if (wolfSSL_sk_X509_push(sk, x509) <= 0) { WOLFSSL_MSG("Unable to load x509 into stack"); wolfSSL_X509_free(x509); + x509 = NULL; goto error; } } @@ -1893,6 +1912,7 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( #ifdef HAVE_CRL if (store->cm->crl != NULL) { + int res; obj = wolfSSL_X509_OBJECT_new(); if (obj == NULL) { WOLFSSL_MSG("wolfSSL_X509_OBJECT_new error"); @@ -1904,6 +1924,11 @@ WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* wolfSSL_X509_STORE_get0_objects( goto err_cleanup; } obj->type = WOLFSSL_X509_LU_CRL; + wolfSSL_RefInc(&store->cm->crl->ref, &res); + if (res != 0) { + WOLFSSL_MSG("Failed to lock crl mutex"); + goto err_cleanup; + } obj->data.crl = store->cm->crl; } #endif diff --git a/src/user_settings.h b/src/user_settings.h index 15bc03b..e2a0196 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -1,6 +1,6 @@ /* examples/configs/user_settings_arduino.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -23,7 +23,14 @@ */ /* Define a macro to display user settings version in example code: */ -#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.4" +#define WOLFSSL_USER_SETTINGS_ID "Arduino user_settings.h v5.7.6" + +/* Disable wolfcrypt cryptographic security hardening. Comment out to enable: */ +/* #define WC_NO_HARDEN */ + +/* Instead, we harden ECC and RSA */ +#define ECC_TIMING_RESISTANT +#define WC_RSA_BLINDING /* Due to limited build control, we'll ignore file warnings. */ /* See https://github.com/arduino/arduino-cli/issues/631 */ @@ -37,6 +44,7 @@ #undef WOLFSSL_ESPIDF #define HAVE_ECC + #define WOLFSSL_SMALL_STACK /* #define WOLFSSL_SMALL_STACK_EXTRA */ /* #define WOLFSSL_SMALL_STACK_CIPHERS */ @@ -74,17 +82,27 @@ * WOLFSSL_CLIENT_EXAMPLE * WOLFSSL_SERVER_EXAMPLE */ + +/* The examples must be manually selected here: */ + #if defined(WOLFSSL_CLIENT_EXAMPLE) #define NO_WOLFSSL_SERVER #elif defined(WOLFSSL_SERVER_EXAMPLE) #define NO_WOLFSSL_CLIENT +#elif defined(WOLFSSL_TEMPLATE_EXAMPLE) + #define NO_WOLFSSL_SERVER + #define NO_WOLFSSL_CLIENT +#elif defined(WOLFSSL_AES_CTR_EXAMPLE) + #define NO_WOLFSSL_SERVER + #define NO_WOLFSSL_CLIENT + #define WOLFSSL_AES + #define WOLFSSL_AES_COUNTER #else /* Provide a hint to application that neither WOLFSSL_CLIENT_EXAMPLE * or WOLFSSL_SERVER_EXAMPLE macro hint was desired but not found. */ #define NO_WOLFSSL_SERVER_CLIENT_MISSING - #warning "Define WOLFSSL_CLIENT_EXAMPLE or WOLFSSL_SERVER_EXAMPLE to" \ - " optimize memory for small embedded devices." - /* Both can be disabled in wolfssl test & benchmark */ + + /* By default all examples are enabled; no specific optimizations */ #endif @@ -112,8 +130,8 @@ /* #define HAVE_PKCS7 */ /* when you want to use AES counter mode */ -/* #define WOLFSSL_AES_DIRECT */ -/* #define WOLFSSL_AES_COUNTER */ +#define WOLFSSL_AES_DIRECT +#define WOLFSSL_AES_COUNTER /* esp32-wroom-32se specific definition */ #if defined(WOLFSSL_ESPWROOM32SE) @@ -352,7 +370,7 @@ */ /* optional SM4 Ciphers. See https://github.com/wolfSSL/wolfsm -/* The section below defines macros used in typically all of the wolfSSL + * The section below defines macros used in typically all of the wolfSSL * examples such as the client and server for certs stored in header files. * * There are various certificate examples in this header file: diff --git a/src/wolfcrypt/src/aes.c b/src/wolfcrypt/src/aes.c index cf50064..6e7f104 100644 --- a/src/wolfcrypt/src/aes.c +++ b/src/wolfcrypt/src/aes.c @@ -1,6 +1,6 @@ /* aes.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,12 +28,8 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits 192-bits, and 256-bits of key sizes. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include -#include +#include #if !defined(NO_AES) @@ -97,8 +93,6 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #include #else -#include - #ifdef NO_INLINE #include #else @@ -239,7 +233,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits #endif /* WOLFSSL_AES_DIRECT || HAVE_AESGCM || HAVE_AESCCM */ #ifdef HAVE_AES_DECRYPT - #if defined(WOLFSSL_AES_DIRECT) || defined(HAVE_AESCCM) + #if defined(WOLFSSL_AES_DIRECT) static WARN_UNUSED_RESULT int wc_AesDecrypt( Aes* aes, const byte* inBlock, byte* outBlock) { @@ -346,13 +340,12 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits return ret; } - #endif /* WOLFSSL_AES_DIRECT || HAVE_AESCCM */ + #endif /* WOLFSSL_AES_DIRECT */ #endif /* HAVE_AES_DECRYPT */ #elif defined(HAVE_COLDFIRE_SEC) /* Freescale Coldfire SEC support for CBC mode. * NOTE: no support for AES-CTR/GCM/CCM/Direct */ - #include #include "sec.h" #include "mcf5475_sec.h" #include "mcf5475_siu.h" @@ -805,6 +798,7 @@ block cipher mechanism that uses n-bit binary string parameter key with 128-bits aes->use_aes_hw_crypto = IS_AARCH64_AES(cpuid_flags); #ifdef HAVE_AESGCM aes->use_pmull_hw_crypto = IS_AARCH64_PMULL(cpuid_flags); + aes->use_sha3_hw_crypto = IS_AARCH64_SHA3(cpuid_flags); #endif } @@ -1966,8 +1960,8 @@ static word32 GetTable8_4(const byte* t, byte o0, byte o1, byte o2, byte o3) static void AesEncrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, word32 r) { - word32 s0, s1, s2, s3; - word32 t0, t1, t2, t3; + word32 s0 = 0, s1 = 0, s2 = 0, s3 = 0; + word32 t0 = 0, t1 = 0, t2 = 0, t3 = 0; const word32* rk; #ifdef WC_C_DYNAMIC_FALLBACK @@ -3015,8 +3009,8 @@ static WARN_UNUSED_RESULT WC_INLINE word32 PreFetchTd4(void) static void AesDecrypt_C(Aes* aes, const byte* inBlock, byte* outBlock, word32 r) { - word32 s0, s1, s2, s3; - word32 t0, t1, t2, t3; + word32 s0 = 0, s1 = 0, s2 = 0, s3 = 0; + word32 t0 = 0, t1 = 0, t2 = 0, t3 = 0; const word32* rk; #ifdef WC_C_DYNAMIC_FALLBACK @@ -3762,7 +3756,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( ByteReverseWords(rk, rk, keylen); #endif #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif return wc_AesSetIV(aes, iv); @@ -3843,7 +3838,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif @@ -3874,7 +3870,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( XMEMCPY(aes->key, userKey, keylen); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif @@ -3926,7 +3923,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( return BAD_FUNC_ARG; #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif @@ -4007,7 +4005,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( ret = nrf51_aes_set_key(userKey); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif @@ -4064,7 +4063,8 @@ static WARN_UNUSED_RESULT int wc_AesDecrypt( XMEMCPY(aes->key, userKey, keylen); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif return wc_AesSetIV(aes, iv); @@ -4557,7 +4557,8 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) } #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) aes->left = 0; #endif @@ -4574,12 +4575,53 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) #endif /* WC_C_DYNAMIC_FALLBACK */ #ifdef WOLFSSL_AESNI - aes->use_aesni = 0; + + /* The dynamics for determining whether AES-NI will be used are tricky. + * + * First, we check for CPU support and cache the result -- if AES-NI is + * missing, we always shortcut to the AesSetKey_C() path. + * + * Second, if the CPU supports AES-NI, we confirm on a per-call basis + * that it's safe to use in the caller context, using + * SAVE_VECTOR_REGISTERS2(). This is an always-true no-op in user-space + * builds, but has substantive logic behind it in kernel module builds. + * + * The outcome when SAVE_VECTOR_REGISTERS2() fails depends on + * WC_C_DYNAMIC_FALLBACK -- if that's defined, we return immediately with + * success but with AES-NI disabled (the earlier AesSetKey_C() allows + * future encrypt/decrypt calls to succeed), otherwise we fail. + * + * Upon successful return, aes->use_aesni will have a zero value if + * AES-NI is disabled, and a nonzero value if it's enabled. + * + * An additional, optional semantic is available via + * WC_FLAG_DONT_USE_AESNI, and is used in some kernel module builds to + * let the caller inhibit AES-NI. When this macro is defined, + * wc_AesInit() before wc_AesSetKey() is imperative, to avoid a read of + * uninitialized data in aes->use_aesni. That's why support for + * WC_FLAG_DONT_USE_AESNI must remain optional -- wc_AesInit() was only + * added in release 3.11.0, so legacy applications inevitably call + * wc_AesSetKey() on uninitialized Aes contexts. This must continue to + * function correctly with default build settings. + */ + if (checkedAESNI == 0) { haveAESNI = Check_CPU_support_AES(); checkedAESNI = 1; } - if (haveAESNI) { + if (haveAESNI +#if defined(WC_FLAG_DONT_USE_AESNI) && !defined(WC_C_DYNAMIC_FALLBACK) + && (aes->use_aesni != WC_FLAG_DONT_USE_AESNI) +#endif + ) + { +#if defined(WC_FLAG_DONT_USE_AESNI) + if (aes->use_aesni == WC_FLAG_DONT_USE_AESNI) { + aes->use_aesni = 0; + return 0; + } +#endif + aes->use_aesni = 0; #ifdef WOLFSSL_LINUXKM /* runtime alignment check */ if ((wc_ptr_t)&aes->key & (wc_ptr_t)0xf) { @@ -4613,6 +4655,15 @@ static void AesSetKey_C(Aes* aes, const byte* key, word32 keySz, int dir) #endif } } + else { + aes->use_aesni = 0; +#ifdef WC_C_DYNAMIC_FALLBACK + /* If WC_C_DYNAMIC_FALLBACK, we already called AesSetKey_C() + * above. + */ + return 0; +#endif + } #endif /* WOLFSSL_AESNI */ #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ @@ -4789,7 +4840,8 @@ int wc_AesSetIV(Aes* aes, const byte* iv) XMEMSET(aes->reg, 0, WC_AES_BLOCK_SIZE); #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) /* Clear any unused bytes from last cipher op. */ aes->left = 0; #endif @@ -6448,6 +6500,22 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) #define AES_LASTGBLOCK(aes) ((aes)->streamData + 3 * WC_AES_BLOCK_SIZE) /* Access last encrypted block. */ #define AES_LASTBLOCK(aes) ((aes)->streamData + 4 * WC_AES_BLOCK_SIZE) + + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ + !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + #define GHASH_ONE_BLOCK(aes, block) \ + do { \ + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { \ + GHASH_ONE_BLOCK_AARCH64(aes, block); \ + } \ + else { \ + GHASH_ONE_BLOCK_SW(aes, block); \ + } \ + } \ + while (0) + #else + #define GHASH_ONE_BLOCK GHASH_ONE_BLOCK_SW + #endif #endif #if defined(HAVE_COLDFIRE_SEC) @@ -6456,7 +6524,7 @@ static WC_INLINE void IncCtr(byte* ctr, word32 ctrSz) #endif #if defined(WOLFSSL_ARMASM) && !defined(__aarch64__) - /* implemented in wolfcrypt/src/port/arm/rmv8-aes.c */ + /* implemented in wolfcrypt/src/port/arm/armv8-aes.c */ #elif defined(WOLFSSL_RISCV_ASM) /* implemented in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ @@ -6616,6 +6684,25 @@ void GenerateM0(Gcm* gcm) #endif /* GCM_TABLE */ +#if defined(WOLFSSL_AESNI) && defined(USE_INTEL_SPEEDUP) + #define HAVE_INTEL_AVX1 + #define HAVE_INTEL_AVX2 +#endif + +#if defined(WOLFSSL_AESNI) && defined(GCM_TABLE_4BIT) && \ + defined(WC_C_DYNAMIC_FALLBACK) +void GCM_generate_m0_aesni(const unsigned char *h, unsigned char *m) + XASM_LINK("GCM_generate_m0_aesni"); +#ifdef HAVE_INTEL_AVX1 +void GCM_generate_m0_avx1(const unsigned char *h, unsigned char *m) + XASM_LINK("GCM_generate_m0_avx1"); +#endif +#ifdef HAVE_INTEL_AVX2 +void GCM_generate_m0_avx2(const unsigned char *h, unsigned char *m) + XASM_LINK("GCM_generate_m0_avx2"); +#endif +#endif /* WOLFSSL_AESNI && GCM_TABLE_4BIT && WC_C_DYNAMIC_FALLBACK */ + /* Software AES - GCM SetKey */ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) { @@ -6685,9 +6772,33 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) VECTOR_REGISTERS_POP; } if (ret == 0) { - #if defined(GCM_TABLE) || defined(GCM_TABLE_4BIT) - GenerateM0(&aes->gcm); - #endif /* GCM_TABLE */ +#if defined(GCM_TABLE) || defined(GCM_TABLE_4BIT) +#if defined(WOLFSSL_AESNI) && defined(GCM_TABLE_4BIT) + if (aes->use_aesni) { + #if defined(WC_C_DYNAMIC_FALLBACK) + #ifdef HAVE_INTEL_AVX2 + if (IS_INTEL_AVX2(intel_flags)) { + GCM_generate_m0_avx2(aes->gcm.H, (byte*)aes->gcm.M0); + } + else + #endif + #if defined(HAVE_INTEL_AVX1) + if (IS_INTEL_AVX1(intel_flags)) { + GCM_generate_m0_avx1(aes->gcm.H, (byte*)aes->gcm.M0); + } + else + #endif + { + GCM_generate_m0_aesni(aes->gcm.H, (byte*)aes->gcm.M0); + } + #endif + } + else +#endif + { + GenerateM0(&aes->gcm); + } +#endif /* GCM_TABLE || GCM_TABLE_4BIT */ } #endif /* FREESCALE_LTC_AES_GCM */ @@ -6710,11 +6821,6 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) #ifdef WOLFSSL_AESNI -#if defined(USE_INTEL_SPEEDUP) - #define HAVE_INTEL_AVX1 - #define HAVE_INTEL_AVX2 -#endif /* USE_INTEL_SPEEDUP */ - void AES_GCM_encrypt_aesni(const unsigned char *in, unsigned char *out, const unsigned char* addt, const unsigned char* ivec, unsigned char *tag, word32 nbytes, @@ -6866,10 +6972,10 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ - GMULT(AES_TAG(aes), aes->gcm.H); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ + GMULT(AES_TAG(aes), (aes)->gcm.H); \ } \ while (0) #endif /* WOLFSSL_AESGCM_STREAM */ @@ -7099,9 +7205,9 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT(AES_TAG(aes), aes->gcm.M0); \ } \ while (0) @@ -7392,8 +7498,6 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_INIT_EXTRA(aes) WC_DO_NOTHING -#if !defined(__aarch64__) || !defined(WOLFSSL_ARMASM) || \ - defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) /* GHASH one block of data.. * * XOR block into tag and GMULT with H using pre-computed table. @@ -7401,13 +7505,12 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ do { \ - xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ + xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT(AES_TAG(aes), (aes)->gcm.M0); \ } \ while (0) -#endif #endif /* WOLFSSL_AESGCM_STREAM */ #elif defined(WORD64_AVAILABLE) && !defined(GCM_WORD32) @@ -7574,17 +7677,17 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ - do { \ - word64* x = (word64*)AES_TAG(aes); \ - word64* h = (word64*)aes->gcm.H; \ - word64 block64[2]; \ - XMEMCPY(block64, block, WC_AES_BLOCK_SIZE); \ - ByteReverseWords64(block64, block64, WC_AES_BLOCK_SIZE); \ - x[0] ^= block64[0]; \ - x[1] ^= block64[1]; \ - GMULT(x, h); \ - } \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ + do { \ + word64* x = (word64*)AES_TAG(aes); \ + word64* h = (word64*)aes->gcm.H; \ + word64 block64[2]; \ + XMEMCPY(block64, block, WC_AES_BLOCK_SIZE); \ + ByteReverseWords64(block64, block64, WC_AES_BLOCK_SIZE); \ + x[0] ^= block64[0]; \ + x[1] ^= block64[1]; \ + GMULT(x, h); \ + } \ while (0) #ifdef OPENSSL_EXTRA @@ -7609,7 +7712,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[0] ^= len[0]; \ x[1] ^= len[1]; \ GMULT(x, h); \ - ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ + ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #else @@ -7632,7 +7735,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[0] ^= len[0]; \ x[1] ^= len[1]; \ GMULT(x, h); \ - ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ + ByteReverseWords64(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #endif @@ -7652,7 +7755,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ do { \ word64* x = (word64*)AES_TAG(aes); \ word64* h = (word64*)aes->gcm.H; \ @@ -7884,19 +7987,19 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ - do { \ - word32* x = (word32*)AES_TAG(aes); \ - word32* h = (word32*)aes->gcm.H; \ - word32 bigEnd[4]; \ - XMEMCPY(bigEnd, block, WC_AES_BLOCK_SIZE); \ - ByteReverseWords(bigEnd, bigEnd, WC_AES_BLOCK_SIZE); \ - x[0] ^= bigEnd[0]; \ - x[1] ^= bigEnd[1]; \ - x[2] ^= bigEnd[2]; \ - x[3] ^= bigEnd[3]; \ - GMULT(x, h); \ - } \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ + do { \ + word32* x = (word32*)AES_TAG(aes); \ + word32* h = (word32*)aes->gcm.H; \ + word32 bigEnd[4]; \ + XMEMCPY(bigEnd, block, WC_AES_BLOCK_SIZE); \ + ByteReverseWords(bigEnd, bigEnd, WC_AES_BLOCK_SIZE); \ + x[0] ^= bigEnd[0]; \ + x[1] ^= bigEnd[1]; \ + x[2] ^= bigEnd[2]; \ + x[3] ^= bigEnd[3]; \ + GMULT(x, h); \ + } \ while (0) /* GHASH in AAD and cipher text lengths in bits. @@ -7919,7 +8022,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, x[2] ^= len[2]; \ x[3] ^= len[3]; \ GMULT(x, h); \ - ByteReverseWords(x, x, WC_AES_BLOCK_SIZE); \ + ByteReverseWords(x, x, WC_AES_BLOCK_SIZE); \ } \ while (0) #else @@ -7936,12 +8039,12 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_SW(aes, block) \ do { \ word32* x = (word32*)AES_TAG(aes); \ word32* h = (word32*)aes->gcm.H; \ word32 block32[4]; \ - XMEMCPY(block32, block, WC_AES_BLOCK_SIZE); \ + XMEMCPY(block32, block, WC_AES_BLOCK_SIZE); \ x[0] ^= block32[0]; \ x[1] ^= block32[1]; \ x[2] ^= block32[2]; \ @@ -7985,7 +8088,7 @@ void GHASH(Gcm* gcm, const byte* a, word32 aSz, const byte* c, */ #define GHASH_LEN_BLOCK(aes) \ do { \ - byte scratch[WC_AES_BLOCK_SIZE]; \ + byte scratch[WC_AES_BLOCK_SIZE]; \ FlattenSzInBits(&scratch[0], (aes)->aSz); \ FlattenSzInBits(&scratch[8], (aes)->cSz); \ GHASH_ONE_BLOCK(aes, scratch); \ @@ -8139,7 +8242,8 @@ static void GHASH_FINAL(Aes* aes, byte* s, word32 sSz) } if (over > 0) { /* Zeroize the unused part of the block. */ - XMEMSET(AES_LASTGBLOCK(aes) + over, 0, (size_t)WC_AES_BLOCK_SIZE - over); + XMEMSET(AES_LASTGBLOCK(aes) + over, 0, + (size_t)WC_AES_BLOCK_SIZE - over); /* Hash the last block of cipher text. */ GHASH_ONE_BLOCK(aes, AES_LASTGBLOCK(aes)); } @@ -8192,8 +8296,6 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, #ifdef STM32_CRYPTO_AES_GCM /* this function supports inline encrypt */ -/* define STM32_AESGCM_PARTIAL for STM HW that does not support authentication - * on byte multiples (see CRYP_HEADERWIDTHUNIT_BYTE) */ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( Aes* aes, byte* out, const byte* in, word32 sz, const byte* iv, word32 ivSz, @@ -8279,12 +8381,11 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( /* for cases where hardware cannot be used for authTag calculate it */ /* if IV is not 12 calculate GHASH using software */ if (ivSz != GCM_NONCE_MID_SZ - #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13) + #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if (!defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13)) \ - && !defined(STM32_AESGCM_PARTIAL) + #if !defined(STM_CRYPT_HEADER_WIDTH) || STM_CRYPT_HEADER_WIDTH == 4 /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8306,12 +8407,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_GCM; - #if defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(WOLFSSL_STM32MP13) - /* V2 with CRYP_HEADERWIDTHUNIT_BYTE uses byte size for header */ - hcryp.Init.HeaderSize = authInSz; - #else - hcryp.Init.HeaderSize = authPadSz/sizeof(word32); - #endif + hcryp.Init.HeaderSize = authPadSz / STM_CRYPT_HEADER_WIDTH; #ifdef CRYP_KEYIVCONFIG_ONCE /* allows repeated calls to HAL_CRYP_Encrypt */ hcryp.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE; @@ -8809,12 +8905,11 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( /* for cases where hardware cannot be used for authTag calculate it */ /* if IV is not 12 calculate GHASH using software */ if (ivSz != GCM_NONCE_MID_SZ - #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13) + #if !defined(CRYP_HEADERWIDTHUNIT_BYTE) /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if (!defined(CRYP_HEADERWIDTHUNIT_BYTE) || defined(WOLFSSL_STM32MP13)) \ - && !defined(STM32_AESGCM_PARTIAL) + #if !defined(STM_CRYPT_HEADER_WIDTH) || STM_CRYPT_HEADER_WIDTH == 4 /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8860,12 +8955,8 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_GCM; - #if defined(CRYP_HEADERWIDTHUNIT_BYTE) && !defined(WOLFSSL_STM32MP13) - /* V2 with CRYP_HEADERWIDTHUNIT_BYTE uses byte size for header */ - hcryp.Init.HeaderSize = authInSz; - #else - hcryp.Init.HeaderSize = authPadSz/sizeof(word32); - #endif + hcryp.Init.HeaderSize = authPadSz / STM_CRYPT_HEADER_WIDTH; + #ifdef CRYP_KEYIVCONFIG_ONCE /* allows repeated calls to HAL_CRYP_Decrypt */ hcryp.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE; @@ -10189,7 +10280,7 @@ int wc_AesGcmInit(Aes* aes, const byte* key, word32 len, const byte* iv, else #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) - if (aes->use_aes_hw_crypto) { + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { AES_GCM_init_AARCH64(aes, iv, ivSz); /* Reset state fields. */ @@ -10328,7 +10419,7 @@ int wc_AesGcmEncryptUpdate(Aes* aes, byte* out, const byte* in, word32 sz, else #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) - if (aes->use_aes_hw_crypto) { + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { AES_GCM_crypt_update_AARCH64(aes, out, in, sz); GHASH_UPDATE_AARCH64(aes, authIn, authInSz, out, sz); } @@ -10388,7 +10479,7 @@ int wc_AesGcmEncryptFinal(Aes* aes, byte* authTag, word32 authTagSz) else #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) - if (aes->use_aes_hw_crypto) { + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { AES_GCM_final_AARCH64(aes, authTag, authTagSz); } else @@ -10477,7 +10568,7 @@ int wc_AesGcmDecryptUpdate(Aes* aes, byte* out, const byte* in, word32 sz, else #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) - if (aes->use_aes_hw_crypto) { + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { GHASH_UPDATE_AARCH64(aes, authIn, authInSz, in, sz); AES_GCM_crypt_update_AARCH64(aes, out, in, sz); } @@ -10535,7 +10626,7 @@ int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, word32 authTagSz) else #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) - if (aes->use_aes_hw_crypto) { + if (aes->use_aes_hw_crypto && aes->use_pmull_hw_crypto) { ALIGN32 byte calcTag[WC_AES_BLOCK_SIZE]; AES_GCM_final_AARCH64(aes, calcTag, authTagSz); /* Check calculated tag matches the one passed in. */ @@ -10771,7 +10862,7 @@ int wc_GmacVerify(const byte* key, word32 keySz, #endif /* WC_NO_RNG */ -WOLFSSL_API int wc_GmacSetKey(Gmac* gmac, const byte* key, word32 len) +int wc_GmacSetKey(Gmac* gmac, const byte* key, word32 len) { if (gmac == NULL || key == NULL) { return BAD_FUNC_ARG; @@ -10780,7 +10871,7 @@ WOLFSSL_API int wc_GmacSetKey(Gmac* gmac, const byte* key, word32 len) } -WOLFSSL_API int wc_GmacUpdate(Gmac* gmac, const byte* iv, word32 ivSz, +int wc_GmacUpdate(Gmac* gmac, const byte* iv, word32 ivSz, const byte* authIn, word32 authInSz, byte* authTag, word32 authTagSz) { @@ -10821,7 +10912,7 @@ int wc_AesCcmCheckTagSize(int sz) } #if defined(WOLFSSL_ARMASM) && !defined(__aarch64__) - /* implemented in wolfcrypt/src/port/arm/rmv8-aes.c */ + /* implemented in wolfcrypt/src/port/arm/armv8-aes.c */ #elif defined(WOLFSSL_RISCV_ASM) /* implementation located in wolfcrypt/src/port/risc-v/riscv-64-aes.c */ @@ -11832,7 +11923,13 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) if (aes->use_aes_hw_crypto) { - AES_encrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + word32 i; + + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { + AES_encrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + } } else #endif @@ -11890,7 +11987,13 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) if (aes->use_aes_hw_crypto) { - AES_decrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + word32 i; + + for (i = 0; i < sz; i += WC_AES_BLOCK_SIZE) { + AES_decrypt_AARCH64(in, out, (byte*)aes->key, (int)aes->rounds); + in += WC_AES_BLOCK_SIZE; + out += WC_AES_BLOCK_SIZE; + } } else #endif @@ -12753,7 +12856,12 @@ int wc_AesXtsSetKeyNoInit(XtsAes* aes, const byte* key, word32 len, int dir) } if ((len != (AES_128_KEY_SIZE*2)) && +#ifndef HAVE_FIPS + /* XTS-384 not allowed by FIPS and can not be treated like + * RSA-4096 bit keys back in the day, can not vendor affirm + * the use of 2 concatenated 192-bit keys (XTS-384) */ (len != (AES_192_KEY_SIZE*2)) && +#endif (len != (AES_256_KEY_SIZE*2))) { WOLFSSL_MSG("Unsupported key size"); @@ -12936,6 +13044,10 @@ int wc_AesXtsDecryptSector(XtsAes* aes, byte* out, const byte* in, word32 sz, #ifdef WOLFSSL_AESNI +#if defined(USE_INTEL_SPEEDUP_FOR_AES) && !defined(USE_INTEL_SPEEDUP) + #define USE_INTEL_SPEEDUP +#endif + #if defined(USE_INTEL_SPEEDUP) #define HAVE_INTEL_AVX1 #define HAVE_INTEL_AVX2 @@ -14799,4 +14911,276 @@ int wc_AesEaxFree(AesEax* eax) #endif /* WOLFSSL_AES_EAX */ +#ifdef WOLFSSL_AES_CTS + + +/* One-shot API */ +int wc_AesCtsEncrypt(const byte* key, word32 keySz, byte* out, + const byte* in, word32 inSz, + const byte* iv) +{ +#ifdef WOLFSSL_SMALL_STACK + Aes *aes = NULL; +#else + Aes aes[1]; +#endif + int ret = 0; + word32 outSz = inSz; + + if (key == NULL || out == NULL || in == NULL || iv == NULL) + return BAD_FUNC_ARG; + +#ifdef WOLFSSL_SMALL_STACK + aes = wc_AesNew(NULL, INVALID_DEVID, &ret); +#else + ret = wc_AesInit(aes, NULL, INVALID_DEVID); +#endif + if (ret == 0) + ret = wc_AesSetKey(aes, key, keySz, iv, AES_ENCRYPTION); + if (ret == 0) + ret = wc_AesCtsEncryptUpdate(aes, out, &outSz, in, inSz); + if (ret == 0) { + out += outSz; + outSz = inSz - outSz; + ret = wc_AesCtsEncryptFinal(aes, out, &outSz); + } + +#ifdef WOLFSSL_SMALL_STACK + wc_AesDelete(aes, NULL); +#else + wc_AesFree(aes); +#endif + return ret; +} + +int wc_AesCtsDecrypt(const byte* key, word32 keySz, byte* out, + const byte* in, word32 inSz, + const byte* iv) +{ +#ifdef WOLFSSL_SMALL_STACK + Aes *aes = NULL; +#else + Aes aes[1]; +#endif + int ret = 0; + word32 outSz = inSz; + + if (key == NULL || out == NULL || in == NULL || iv == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + aes = wc_AesNew(NULL, INVALID_DEVID, &ret); +#else + ret = wc_AesInit(aes, NULL, INVALID_DEVID); +#endif + if (ret == 0) + ret = wc_AesSetKey(aes, key, keySz, iv, AES_DECRYPTION); + if (ret == 0) + ret = wc_AesCtsDecryptUpdate(aes, out, &outSz, in, inSz); + if (ret == 0) { + out += outSz; + outSz = inSz - outSz; + ret = wc_AesCtsDecryptFinal(aes, out, &outSz); + } + +#ifdef WOLFSSL_SMALL_STACK + wc_AesDelete(aes, NULL); +#else + wc_AesFree(aes); +#endif + return ret; +} + +static int AesCtsUpdate(Aes* aes, byte* out, word32* outSz, + const byte* in, word32 inSz, int enc) +{ + word32 blocks = 0; + int ret = 0; + word32 writtenSz = 0; + word32 tmpOutSz; + + if (aes == NULL || out == NULL || in == NULL || outSz == NULL) + return BAD_FUNC_ARG; + + /* Error out early for easy sanity check */ + if (*outSz < inSz) + return BUFFER_E; + tmpOutSz = *outSz; + + /* We need to store last two blocks of plaintext */ + if (aes->left > 0) { + word32 copySz = min(inSz, (WC_AES_BLOCK_SIZE * 2) - aes->left); + XMEMCPY(aes->ctsBlock + aes->left, in, copySz); + aes->left += copySz; + in += copySz; + inSz -= copySz; + + if (aes->left == WC_AES_BLOCK_SIZE * 2) { + if (inSz > WC_AES_BLOCK_SIZE) { + if (tmpOutSz < WC_AES_BLOCK_SIZE * 2) + return BUFFER_E; + if (enc) { + ret = wc_AesCbcEncrypt(aes, out, aes->ctsBlock, + WC_AES_BLOCK_SIZE * 2); + } + else { + ret = wc_AesCbcDecrypt(aes, out, aes->ctsBlock, + WC_AES_BLOCK_SIZE * 2); + } + if (ret != 0) + return ret; + out += WC_AES_BLOCK_SIZE * 2; + writtenSz += WC_AES_BLOCK_SIZE * 2; + tmpOutSz -= WC_AES_BLOCK_SIZE * 2; + aes->left = 0; + } + else if (inSz > 0) { + if (tmpOutSz < WC_AES_BLOCK_SIZE) + return BUFFER_E; + if (enc) { + ret = wc_AesCbcEncrypt(aes, out, aes->ctsBlock, + WC_AES_BLOCK_SIZE); + } + else { + ret = wc_AesCbcDecrypt(aes, out, aes->ctsBlock, + WC_AES_BLOCK_SIZE); + } + if (ret != 0) + return ret; + out += WC_AES_BLOCK_SIZE; + writtenSz += WC_AES_BLOCK_SIZE; + tmpOutSz -= WC_AES_BLOCK_SIZE; + /* Move the last block in ctsBlock to the beginning for + * next operation */ + XMEMCPY(aes->ctsBlock, aes->ctsBlock + WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); + XMEMCPY(aes->ctsBlock + WC_AES_BLOCK_SIZE, in, inSz); + aes->left = WC_AES_BLOCK_SIZE + inSz; + *outSz = writtenSz; + return ret; /* Return the result of encryption */ + } + else { + /* Can't output data as we need > 1 block for Final call */ + *outSz = writtenSz; + return 0; + } + } + else { + /* All input has been absorbed into aes->ctsBlock */ + *outSz = 0; + return 0; + } + } + if (inSz > WC_AES_BLOCK_SIZE) { + /* We need to store the last two full or partial blocks */ + blocks = (inSz + (WC_AES_BLOCK_SIZE - 1)) / WC_AES_BLOCK_SIZE; + blocks -= 2; + } + if (tmpOutSz < blocks * WC_AES_BLOCK_SIZE) + return BUFFER_E; + if (enc) + ret = wc_AesCbcEncrypt(aes, out, in, blocks * WC_AES_BLOCK_SIZE); + else + ret = wc_AesCbcDecrypt(aes, out, in, blocks * WC_AES_BLOCK_SIZE); + in += blocks * WC_AES_BLOCK_SIZE; + inSz -= blocks * WC_AES_BLOCK_SIZE; + XMEMCPY(aes->ctsBlock, in, inSz); + aes->left = inSz; + writtenSz += blocks * WC_AES_BLOCK_SIZE; + *outSz = writtenSz; + return ret; +} + +/* Incremental API */ +int wc_AesCtsEncryptUpdate(Aes* aes, byte* out, word32* outSz, + const byte* in, word32 inSz) +{ + return AesCtsUpdate(aes, out, outSz, in, inSz, 1); +} + +int wc_AesCtsEncryptFinal(Aes* aes, byte* out, word32* outSz) +{ + int ret = 0; + + if (aes == NULL || out == NULL || outSz == NULL) + return BAD_FUNC_ARG; + if (*outSz < aes->left) + return BUFFER_E; + + /* Input must be at least two complete or partial blocks */ + if (aes->left <= WC_AES_BLOCK_SIZE) + return BAD_FUNC_ARG; + + /* Zero padding */ + XMEMSET(aes->ctsBlock + aes->left, 0, (WC_AES_BLOCK_SIZE * 2) - aes->left); + + ret = wc_AesCbcEncrypt(aes, aes->ctsBlock, aes->ctsBlock, + WC_AES_BLOCK_SIZE * 2); + if (ret != 0) + return ret; + + XMEMCPY(out, aes->ctsBlock + WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); + XMEMCPY(out + WC_AES_BLOCK_SIZE, aes->ctsBlock, + aes->left - WC_AES_BLOCK_SIZE); + *outSz = aes->left; + return ret; +} + +int wc_AesCtsDecryptUpdate(Aes* aes, byte* out, word32* outSz, + const byte* in, word32 inSz) +{ + return AesCtsUpdate(aes, out, outSz, in, inSz, 0); +} + +int wc_AesCtsDecryptFinal(Aes* aes, byte* out, word32* outSz) +{ + int ret = 0; + byte iv[WC_AES_BLOCK_SIZE]; + byte tmp[WC_AES_BLOCK_SIZE]; + word32 partialSz; + word32 padSz; + + if (aes == NULL || out == NULL || outSz == NULL) + return BAD_FUNC_ARG; + if (*outSz < aes->left) + return BUFFER_E; + + /* Input must be at least two complete or partial blocks */ + if (aes->left <= WC_AES_BLOCK_SIZE) + return BAD_FUNC_ARG; + + partialSz = aes->left - WC_AES_BLOCK_SIZE; + padSz = 2 * WC_AES_BLOCK_SIZE - aes->left; + /* Zero pad */ + XMEMSET(aes->ctsBlock + aes->left, 0, padSz); + + /* Store IV */ + XMEMCPY(iv, aes->reg, WC_AES_BLOCK_SIZE); + /* Load IV */ + XMEMCPY(aes->reg, aes->ctsBlock + WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); + + ret = wc_AesCbcDecrypt(aes, tmp, aes->ctsBlock, WC_AES_BLOCK_SIZE); + if (ret != 0) + return ret; + + /* Write out partial block */ + XMEMCPY(out + WC_AES_BLOCK_SIZE, tmp, partialSz); + /* Retrieve the padding */ + XMEMCPY(aes->ctsBlock + aes->left, tmp + partialSz, padSz); + /* Restore IV */ + XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE); + + ret = wc_AesCbcDecrypt(aes, out, aes->ctsBlock + WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); + if (ret != 0) + return ret; + + *outSz = aes->left; + return ret; +} + +#endif /* WOLFSSL_AES_CTS */ + + #endif /* !NO_AES */ diff --git a/src/wolfcrypt/src/arc4.c b/src/wolfcrypt/src/arc4.c index 649d52f..a877d8b 100644 --- a/src/wolfcrypt/src/arc4.c +++ b/src/wolfcrypt/src/arc4.c @@ -1,6 +1,6 @@ /* arc4.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,16 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_RC4 -#include #include diff --git a/src/wolfcrypt/src/ascon.c b/src/wolfcrypt/src/ascon.c new file mode 100644 index 0000000..248d06a --- /dev/null +++ b/src/wolfcrypt/src/ascon.c @@ -0,0 +1,521 @@ +/* ascon.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + +#ifdef HAVE_ASCON + +#include +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +/* + * Implementation of the ASCON AEAD and HASH algorithms. Based on the NIST + * Initial Public Draft "NIST SP 800-232 ipd" and reference implementation found + * at https://github.com/ascon/ascon-c. + */ + +/* + * TODO + * - Add support for big-endian systems + * - Add support for 32-bit and smaller systems */ + +#ifndef WORD64_AVAILABLE + #error "Ascon implementation requires a 64-bit word" +#endif + +/* Data block size in bytes */ +#define ASCON_HASH256_RATE 8 +#define ASCON_HASH256_ROUNDS 12 +#define ASCON_HASH256_IV 0x0000080100CC0002ULL + +#define ASCON_AEAD128_ROUNDS_PA 12 +#define ASCON_AEAD128_ROUNDS_PB 8 +#define ASCON_AEAD128_IV 0x00001000808C0001ULL +#define ASCON_AEAD128_RATE 16 + +#define MAX_ROUNDS 12 + +#ifndef WOLFSSL_ASCON_UNROLL + +/* Table 5 */ +static const byte round_constants[MAX_ROUNDS] = { + 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b +}; + +static byte start_index(byte rounds) +{ + switch (rounds) { + case 8: + return 4; + case 12: + return 0; + default: + WOLFSSL_MSG("Something went wrong in wolfCrypt logic. Wrong ASCON " + "rounds value."); + return MAX_ROUNDS; + } +} + +static WC_INLINE void ascon_round(AsconState* a, byte round) +{ + word64 tmp0, tmp1, tmp2, tmp3, tmp4; + /* 3.2 Constant-Addition Layer */ + a->s64[2] ^= round_constants[round]; + /* 3.3 Substitution Layer */ + a->s64[0] ^= a->s64[4]; + a->s64[4] ^= a->s64[3]; + a->s64[2] ^= a->s64[1]; + tmp0 = a->s64[0] ^ (~a->s64[1] & a->s64[2]); + tmp2 = a->s64[2] ^ (~a->s64[3] & a->s64[4]); + tmp4 = a->s64[4] ^ (~a->s64[0] & a->s64[1]); + tmp1 = a->s64[1] ^ (~a->s64[2] & a->s64[3]); + tmp3 = a->s64[3] ^ (~a->s64[4] & a->s64[0]); + tmp1 ^= tmp0; + tmp3 ^= tmp2; + tmp0 ^= tmp4; + tmp2 = ~tmp2; + /* 3.4 Linear Diffusion Layer */ + a->s64[4] = tmp4 ^ rotrFixed64(tmp4, 7) ^ rotrFixed64(tmp4, 41); + a->s64[1] = tmp1 ^ rotrFixed64(tmp1, 61) ^ rotrFixed64(tmp1, 39); + a->s64[3] = tmp3 ^ rotrFixed64(tmp3, 10) ^ rotrFixed64(tmp3, 17); + a->s64[0] = tmp0 ^ rotrFixed64(tmp0, 19) ^ rotrFixed64(tmp0, 28); + a->s64[2] = tmp2 ^ rotrFixed64(tmp2, 1) ^ rotrFixed64(tmp2, 6); +} + +static void permutation(AsconState* a, byte rounds) +{ + byte i = start_index(rounds); + for (; i < MAX_ROUNDS; i++) { + ascon_round(a, i); + } +} + +#else + +#define p(a, c) do { \ + word64 tmp0, tmp1, tmp2, tmp3, tmp4; \ + /* 3.2 Constant-Addition Layer */ \ + (a)->s64[2] ^= c; \ + /* 3.3 Substitution Layer */ \ + (a)->s64[0] ^= (a)->s64[4]; \ + (a)->s64[4] ^= (a)->s64[3]; \ + (a)->s64[2] ^= (a)->s64[1]; \ + tmp0 = (a)->s64[0] ^ (~(a)->s64[1] & (a)->s64[2]); \ + tmp2 = (a)->s64[2] ^ (~(a)->s64[3] & (a)->s64[4]); \ + tmp4 = (a)->s64[4] ^ (~(a)->s64[0] & (a)->s64[1]); \ + tmp1 = (a)->s64[1] ^ (~(a)->s64[2] & (a)->s64[3]); \ + tmp3 = (a)->s64[3] ^ (~(a)->s64[4] & (a)->s64[0]); \ + tmp1 ^= tmp0; \ + tmp3 ^= tmp2; \ + tmp0 ^= tmp4; \ + tmp2 = ~tmp2; \ + /* 3.4 Linear Diffusion Layer */ \ + (a)->s64[4] = tmp4 ^ rotrFixed64(tmp4, 7) ^ rotrFixed64(tmp4, 41); \ + (a)->s64[1] = tmp1 ^ rotrFixed64(tmp1, 61) ^ rotrFixed64(tmp1, 39); \ + (a)->s64[3] = tmp3 ^ rotrFixed64(tmp3, 10) ^ rotrFixed64(tmp3, 17); \ + (a)->s64[0] = tmp0 ^ rotrFixed64(tmp0, 19) ^ rotrFixed64(tmp0, 28); \ + (a)->s64[2] = tmp2 ^ rotrFixed64(tmp2, 1) ^ rotrFixed64(tmp2, 6); \ +} while (0) + +#define p8(a) \ + p(a, 0xb4); \ + p(a, 0xa5); \ + p(a, 0x96); \ + p(a, 0x87); \ + p(a, 0x78); \ + p(a, 0x69); \ + p(a, 0x5a); \ + p(a, 0x4b) + +#define p12(a) \ + p(a, 0xf0); \ + p(a, 0xe1); \ + p(a, 0xd2); \ + p(a, 0xc3); \ + p8(a) + +/* Needed layer to evaluate the macro values */ +#define _permutation(a, rounds) \ + p ## rounds(a) + +#define permutation(a, rounds) \ + _permutation(a, rounds) + +#endif + +/* AsconHash API */ + +wc_AsconHash256* wc_AsconHash256_New(void) +{ + wc_AsconHash256* ret = (wc_AsconHash256*)XMALLOC(sizeof(wc_AsconHash256), + NULL, DYNAMIC_TYPE_ASCON); + if (ret != NULL) { + if (wc_AsconHash256_Init(ret) != 0) { + wc_AsconHash256_Free(ret); + ret = NULL; + } + } + return ret; +} + +void wc_AsconHash256_Free(wc_AsconHash256* a) +{ + if (a != NULL) { + wc_AsconHash256_Clear(a); + XFREE(a, NULL, DYNAMIC_TYPE_ASCON); + } +} + +int wc_AsconHash256_Init(wc_AsconHash256* a) +{ + if (a == NULL) + return BAD_FUNC_ARG; + + XMEMSET(a, 0, sizeof(*a)); + + a->state.s64[0] = ASCON_HASH256_IV; + permutation(&a->state, ASCON_HASH256_ROUNDS); + + return 0; +} + +void wc_AsconHash256_Clear(wc_AsconHash256* a) +{ + if (a != NULL) { + ForceZero(a, sizeof(*a)); + } +} + +int wc_AsconHash256_Update(wc_AsconHash256* a, const byte* data, word32 dataSz) +{ + if (a == NULL || (data == NULL && dataSz != 0)) + return BAD_FUNC_ARG; + + if (dataSz == 0) + return 0; + + /* Process leftover block */ + if (a->lastBlkSz != 0) { + word32 toProcess = min(ASCON_HASH256_RATE - a->lastBlkSz, dataSz); + xorbuf(a->state.s8 + a->lastBlkSz, data, toProcess); + data += toProcess; + dataSz -= toProcess; + a->lastBlkSz += toProcess; + + if (a->lastBlkSz < ASCON_HASH256_RATE) + return 0; + + permutation(&a->state, ASCON_HASH256_ROUNDS); + /* Reset the counter */ + a->lastBlkSz = 0; + } + + while (dataSz >= ASCON_HASH256_RATE) { + /* Read in input as little endian numbers */ + xorbuf(a->state.s64, data, ASCON_HASH256_RATE); + permutation(&a->state, ASCON_HASH256_ROUNDS); + data += ASCON_HASH256_RATE; + dataSz -= ASCON_HASH256_RATE; + } + + xorbuf(a->state.s64, data, dataSz); + a->lastBlkSz = dataSz; + + return 0; +} + +int wc_AsconHash256_Final(wc_AsconHash256* a, byte* hash) +{ + byte i; + + if (a == NULL || hash == NULL) + return BAD_FUNC_ARG; + + /* Process last block */ + a->state.s8[a->lastBlkSz] ^= 1; + + for (i = 0; i < ASCON_HASH256_SZ; i += ASCON_HASH256_RATE) { + permutation(&a->state, ASCON_HASH256_ROUNDS); + XMEMCPY(hash, a->state.s64, ASCON_HASH256_RATE); + hash += ASCON_HASH256_RATE; + } + + /* Clear state as soon as possible */ + wc_AsconHash256_Clear(a); + return 0; +} + +/* AsconAEAD API */ + +wc_AsconAEAD128* wc_AsconAEAD128_New(void) +{ + wc_AsconAEAD128 *ret = (wc_AsconAEAD128*) XMALLOC(sizeof(wc_AsconAEAD128), + NULL, DYNAMIC_TYPE_ASCON); + if (ret != NULL) { + if (wc_AsconAEAD128_Init(ret) != 0) { + wc_AsconAEAD128_Free(ret); + ret = NULL; + } + } + return ret; +} + +void wc_AsconAEAD128_Free(wc_AsconAEAD128 *a) +{ + if (a != NULL) { + wc_AsconAEAD128_Clear(a); + XFREE(a, NULL, DYNAMIC_TYPE_ASCON); + } +} + +int wc_AsconAEAD128_Init(wc_AsconAEAD128 *a) +{ + if (a == NULL) + return BAD_FUNC_ARG; + + XMEMSET(a, 0, sizeof(*a)); + a->state.s64[0] = ASCON_AEAD128_IV; + + return 0; +} + +void wc_AsconAEAD128_Clear(wc_AsconAEAD128 *a) +{ + if (a != NULL) { + ForceZero(a, sizeof(*a)); + } +} + +int wc_AsconAEAD128_SetKey(wc_AsconAEAD128* a, const byte* key) +{ + if (a == NULL || key == NULL) + return BAD_FUNC_ARG; + if (a->keySet) + return BAD_STATE_E; + + XMEMCPY(a->key, key, ASCON_AEAD128_KEY_SZ); + a->state.s64[1] = a->key[0]; + a->state.s64[2] = a->key[1]; + a->keySet = 1; + + return 0; +} + +int wc_AsconAEAD128_SetNonce(wc_AsconAEAD128* a, const byte* nonce) +{ + if (a == NULL || nonce == NULL) + return BAD_FUNC_ARG; + if (a->nonceSet) + return BAD_STATE_E; + + XMEMCPY(&a->state.s64[3], nonce, ASCON_AEAD128_NONCE_SZ); + a->nonceSet = 1; + + return 0; +} + +int wc_AsconAEAD128_SetAD(wc_AsconAEAD128* a, const byte* ad, + word32 adSz) +{ + if (a == NULL || (ad == NULL && adSz > 0)) + return BAD_FUNC_ARG; + if (!a->keySet || !a->nonceSet) /* key and nonce must be set before */ + return BAD_STATE_E; + + permutation(&a->state, ASCON_AEAD128_ROUNDS_PA); + a->state.s64[3] ^= a->key[0]; + a->state.s64[4] ^= a->key[1]; + + if (adSz > 0) { + while (adSz >= ASCON_AEAD128_RATE) { + xorbuf(a->state.s64, ad, ASCON_AEAD128_RATE); + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + ad += ASCON_AEAD128_RATE; + adSz -= ASCON_AEAD128_RATE; + } + xorbuf(a->state.s64, ad, adSz); + /* Pad the last block */ + a->state.s8[adSz] ^= 1; + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + } + a->state.s64[4] ^= 1ULL << 63; + + a->adSet = 1; + return 0; +} + +int wc_AsconAEAD128_EncryptUpdate(wc_AsconAEAD128* a, byte* out, + const byte* in, word32 inSz) +{ + if (a == NULL || (in == NULL && inSz > 0)) + return BAD_FUNC_ARG; + if (!a->keySet || !a->nonceSet || !a->adSet) + return BAD_STATE_E; + + if (a->op == ASCON_AEAD128_NOTSET) + a->op = ASCON_AEAD128_ENCRYPT; + else if (a->op != ASCON_AEAD128_ENCRYPT) + return BAD_STATE_E; + + /* Process leftover from last block */ + if (a->lastBlkSz != 0) { + word32 toProcess = min(ASCON_AEAD128_RATE - a->lastBlkSz, inSz); + xorbuf(&a->state.s8[a->lastBlkSz], in, toProcess); + XMEMCPY(out, &a->state.s8[a->lastBlkSz], toProcess); + a->lastBlkSz += toProcess; + in += toProcess; + out += toProcess; + inSz -= toProcess; + + if (a->lastBlkSz < ASCON_AEAD128_RATE) + return 0; + + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + a->lastBlkSz = 0; + } + + while (inSz >= ASCON_AEAD128_RATE) { + xorbuf(a->state.s64, in, ASCON_AEAD128_RATE); + XMEMCPY(out, a->state.s64, ASCON_AEAD128_RATE); + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + in += ASCON_AEAD128_RATE; + out += ASCON_AEAD128_RATE; + inSz -= ASCON_AEAD128_RATE; + } + /* Store leftover */ + xorbuf(a->state.s64, in, inSz); + XMEMCPY(out, a->state.s64, inSz); + a->lastBlkSz = inSz; + + return 0; +} + + +int wc_AsconAEAD128_EncryptFinal(wc_AsconAEAD128* a, byte* tag) +{ + if (a == NULL || tag == NULL) + return BAD_FUNC_ARG; + if (!a->keySet || !a->nonceSet || !a->adSet) + return BAD_STATE_E; + + if (a->op != ASCON_AEAD128_ENCRYPT) + return BAD_STATE_E; + + /* Process leftover from last block */ + a->state.s8[a->lastBlkSz] ^= 1; + + a->state.s64[2] ^= a->key[0]; + a->state.s64[3] ^= a->key[1]; + permutation(&a->state, ASCON_AEAD128_ROUNDS_PA); + a->state.s64[3] ^= a->key[0]; + a->state.s64[4] ^= a->key[1]; + + XMEMCPY(tag, &a->state.s64[3], ASCON_AEAD128_TAG_SZ); + + /* Clear state as soon as possible */ + wc_AsconAEAD128_Clear(a); + + return 0; + +} + + +int wc_AsconAEAD128_DecryptUpdate(wc_AsconAEAD128* a, byte* out, + const byte* in, word32 inSz) +{ + if (a == NULL || (in == NULL && inSz > 0)) + return BAD_FUNC_ARG; + if (!a->keySet || !a->nonceSet || !a->adSet) + return BAD_STATE_E; + + if (a->op == ASCON_AEAD128_NOTSET) + a->op = ASCON_AEAD128_DECRYPT; + else if (a->op != ASCON_AEAD128_DECRYPT) + return BAD_STATE_E; + + /* Process leftover block */ + if (a->lastBlkSz != 0) { + word32 toProcess = min(ASCON_AEAD128_RATE - a->lastBlkSz, inSz); + xorbufout(out, a->state.s8 + a->lastBlkSz, in, toProcess); + XMEMCPY(a->state.s8 + a->lastBlkSz, in, toProcess); + in += toProcess; + out += toProcess; + inSz -= toProcess; + a->lastBlkSz += toProcess; + + if (a->lastBlkSz < ASCON_AEAD128_RATE) + return 0; + + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + a->lastBlkSz = 0; + } + + while (inSz >= ASCON_AEAD128_RATE) { + xorbufout(out, a->state.s64, in, ASCON_AEAD128_RATE); + XMEMCPY(a->state.s64, in, ASCON_AEAD128_RATE); + permutation(&a->state, ASCON_AEAD128_ROUNDS_PB); + in += ASCON_AEAD128_RATE; + out += ASCON_AEAD128_RATE; + inSz -= ASCON_AEAD128_RATE; + } + /* Store leftover */ + xorbufout(out, a->state.s64, in, inSz); + XMEMCPY(a->state.s64, in, inSz); + a->lastBlkSz = inSz; + + return 0; +} + +int wc_AsconAEAD128_DecryptFinal(wc_AsconAEAD128* a, const byte* tag) +{ + if (a == NULL || tag == NULL) + return BAD_FUNC_ARG; + if (!a->keySet || !a->nonceSet || !a->adSet) + return BAD_STATE_E; + + if (a->op != ASCON_AEAD128_DECRYPT) + return BAD_STATE_E; + + /* Pad last block */ + a->state.s8[a->lastBlkSz] ^= 1; + + a->state.s64[2] ^= a->key[0]; + a->state.s64[3] ^= a->key[1]; + permutation(&a->state, ASCON_AEAD128_ROUNDS_PA); + a->state.s64[3] ^= a->key[0]; + a->state.s64[4] ^= a->key[1]; + + if (ConstantCompare(tag, (const byte*)&a->state.s64[3], + ASCON_AEAD128_TAG_SZ) != 0) + return ASCON_AUTH_E; + + /* Clear state as soon as possible */ + wc_AsconAEAD128_Clear(a); + + return 0; +} + +#endif /* HAVE_ASCON */ diff --git a/src/wolfcrypt/src/asm.c b/src/wolfcrypt/src/asm.c index 2096ae9..a724114 100644 --- a/src/wolfcrypt/src/asm.c +++ b/src/wolfcrypt/src/asm.c @@ -1,6 +1,6 @@ /* asm.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include /* * Based on public domain TomsFastMath 0.10 by Tom St Denis, tomstdenis@iahu.ca, diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index 6335df3..af74678 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -1,6 +1,6 @@ /* asn.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -34,11 +34,8 @@ * Provides routines to convert BER into DER. Replaces indefinite length * encoded items with explicit lengths. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include +#include /* ASN Options: @@ -109,7 +106,6 @@ ASN Options: * usage. */ -#include #ifndef NO_RSA #include #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) @@ -128,7 +124,6 @@ ASN Options: #include #include #include -#include #include #include @@ -1300,7 +1295,7 @@ static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data, WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len, *data->data.buffer.length); #endif - return ASN_PARSE_E; + return BUFFER_E; } /* Copy in data and record actual length seen. */ XMEMCPY(data->data.buffer.data, input + idx, (size_t)len); @@ -2451,8 +2446,9 @@ static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx, ret = ASN_PARSE_E; } else if ((input[(int)idx + length - 1] & 0x80) == 0x80) { - /* Last octet of a sub-identifier has bit 8 clear. Last octet must be - * last of a subidentifier. Ensure last octet hasn't got top bit set. */ + /* Last octet of a sub-identifier has bit 8 clear. Last octet must + * be last of a subidentifier. Ensure last octet hasn't got top bit + * set. */ WOLFSSL_MSG("OID last octet has top bit set"); ret = ASN_PARSE_E; } @@ -3629,8 +3625,8 @@ word32 SetIndefEnd(byte* output) /* Breaks an octet string up into chunks for use with streaming * returns 0 on success and updates idx */ -int StreamOctetString(const byte* inBuf, word32 inBufSz, byte* out, word32* outSz, - word32* idx) +int StreamOctetString(const byte* inBuf, word32 inBufSz, byte* out, + word32* outSz, word32* idx) { word32 i = 0; word32 outIdx = *idx; @@ -4495,16 +4491,295 @@ static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2}; /* certPolicyType */ static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0}; +static const byte extCertPolicyIsrgDomainValid[] = + {43, 6, 1, 4, 1, 130, 223, 19, 1, 1, 1}; #ifdef WOLFSSL_FPKI #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num} + static const byte extCertPolicyFpkiHighAssuranceOid[] = + CERT_POLICY_TYPE_OID_BASE(4); + static const byte extCertPolicyFpkiCommonHardwareOid[] = + CERT_POLICY_TYPE_OID_BASE(7); + static const byte extCertPolicyFpkiMediumHardwareOid[] = + CERT_POLICY_TYPE_OID_BASE(12); static const byte extCertPolicyFpkiCommonAuthOid[] = CERT_POLICY_TYPE_OID_BASE(13); + static const byte extCertPolicyFpkiCommonHighOid[] = + CERT_POLICY_TYPE_OID_BASE(16); + static const byte extCertPolicyFpkiCommonDevicesHardwareOid[] = + CERT_POLICY_TYPE_OID_BASE(36); + static const byte extCertPolicyFpkiCommonPivContentSigningOid[] = + CERT_POLICY_TYPE_OID_BASE(39); static const byte extCertPolicyFpkiPivAuthOid[] = CERT_POLICY_TYPE_OID_BASE(40); static const byte extCertPolicyFpkiPivAuthHwOid[] = CERT_POLICY_TYPE_OID_BASE(41); static const byte extCertPolicyFpkiPiviAuthOid[] = CERT_POLICY_TYPE_OID_BASE(45); + + /* Federal PKI Test OIDs - 2.16.840.1.101.3.2.1.48.x */ + #define TEST_CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 48, num} + static const byte extCertPolicyFpkiAuthTestOid[] = + TEST_CERT_POLICY_TYPE_OID_BASE(11); + static const byte extCertPolicyFpkiCardauthTestOid[] = + TEST_CERT_POLICY_TYPE_OID_BASE(13); + static const byte extCertPolicyFpkiPivContentTestOid[] = + TEST_CERT_POLICY_TYPE_OID_BASE(86); + static const byte extCertPolicyFpkiAuthDerivedTestOid[] = + TEST_CERT_POLICY_TYPE_OID_BASE(109); + static const byte extCertPolicyFpkiAuthDerivedHwTestOid[] = + TEST_CERT_POLICY_TYPE_OID_BASE(110); + + /* DoD PKI OIDs - 2.16.840.1.101.2.1.11.X */ + #define DOD_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 2, 1, 11, num} + static const byte extCertPolicyDodMediumOid[] = + DOD_POLICY_TYPE_OID_BASE(5); + static const byte extCertPolicyDodMediumHardwareOid[] = + DOD_POLICY_TYPE_OID_BASE(9); + static const byte extCertPolicyDodPivAuthOid[] = + DOD_POLICY_TYPE_OID_BASE(10); + static const byte extCertPolicyDodMediumNpeOid[] = + DOD_POLICY_TYPE_OID_BASE(17); + static const byte extCertPolicyDodMedium2048Oid[] = + DOD_POLICY_TYPE_OID_BASE(18); + static const byte extCertPolicyDodMediumHardware2048Oid[] = + DOD_POLICY_TYPE_OID_BASE(19); + static const byte extCertPolicyDodPivAuth2048Oid[] = + DOD_POLICY_TYPE_OID_BASE(20); + static const byte extCertPolicyDodPeerInteropOid[] = + DOD_POLICY_TYPE_OID_BASE(31); + static const byte extCertPolicyDodMediumNpe112Oid[] = + DOD_POLICY_TYPE_OID_BASE(36); + static const byte extCertPolicyDodMediumNpe128Oid[] = + DOD_POLICY_TYPE_OID_BASE(37); + static const byte extCertPolicyDodMediumNpe192Oid[] = + DOD_POLICY_TYPE_OID_BASE(38); + static const byte extCertPolicyDodMedium112Oid[] = + DOD_POLICY_TYPE_OID_BASE(39); + static const byte extCertPolicyDodMedium128Oid[] = + DOD_POLICY_TYPE_OID_BASE(40); + static const byte extCertPolicyDodMedium192Oid[] = + DOD_POLICY_TYPE_OID_BASE(41); + static const byte extCertPolicyDodMediumHardware112Oid[] = + DOD_POLICY_TYPE_OID_BASE(42); + static const byte extCertPolicyDodMediumHardware128Oid[] = + DOD_POLICY_TYPE_OID_BASE(43); + static const byte extCertPolicyDodMediumHardware192Oid[] = + DOD_POLICY_TYPE_OID_BASE(44); + static const byte extCertPolicyDodAdminOid[] = + DOD_POLICY_TYPE_OID_BASE(59); + static const byte extCertPolicyDodInternalNpe112Oid[] = + DOD_POLICY_TYPE_OID_BASE(60); + static const byte extCertPolicyDodInternalNpe128Oid[] = + DOD_POLICY_TYPE_OID_BASE(61); + static const byte extCertPolicyDodInternalNpe192Oid[] = + DOD_POLICY_TYPE_OID_BASE(62); + + /* ECA PKI OIDs - 2.16.840.1.101.3.2.1.12.X */ + #define ECA_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 12, num} + static const byte extCertPolicyEcaMediumOid[] = + ECA_POLICY_TYPE_OID_BASE(1); + static const byte extCertPolicyEcaMediumHardwareOid[] = + ECA_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyEcaMediumTokenOid[] = + ECA_POLICY_TYPE_OID_BASE(3); + static const byte extCertPolicyEcaMediumSha256Oid[] = + ECA_POLICY_TYPE_OID_BASE(4); + static const byte extCertPolicyEcaMediumTokenSha256Oid[] = + ECA_POLICY_TYPE_OID_BASE(5); + static const byte extCertPolicyEcaMediumHardwarePiviOid[] = + ECA_POLICY_TYPE_OID_BASE(6); + static const byte extCertPolicyEcaContentSigningPiviOid[] = + ECA_POLICY_TYPE_OID_BASE(8); + static const byte extCertPolicyEcaMediumDeviceSha256Oid[] = + ECA_POLICY_TYPE_OID_BASE(9); + static const byte extCertPolicyEcaMediumHardwareSha256Oid[] = + ECA_POLICY_TYPE_OID_BASE(10); + + /* Department of State PKI OIDs - 2.16.840.1.101.3.2.1.6.X */ + #define STATE_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 6, num} + static const byte extCertPolicyStateBasicOid[] = + STATE_POLICY_TYPE_OID_BASE(1); + static const byte extCertPolicyStateLowOid[] = + STATE_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyStateModerateOid[] = + STATE_POLICY_TYPE_OID_BASE(3); + static const byte extCertPolicyStateHighOid[] = + STATE_POLICY_TYPE_OID_BASE(4); + static const byte extCertPolicyStateMedHwOid[] = + STATE_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyStateMediumDeviceHardwareOid[] = + STATE_POLICY_TYPE_OID_BASE(38); + + /* U.S. Treasury SSP PKI OIDs - 2.16.840.1.101.3.2.1.5.X */ + #define TREASURY_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 5, num} + static const byte extCertPolicyTreasuryMediumHardwareOid[] = + TREASURY_POLICY_TYPE_OID_BASE(4); + static const byte extCertPolicyTreasuryHighOid[] = + TREASURY_POLICY_TYPE_OID_BASE(5); + static const byte extCertPolicyTreasuryPiviHardwareOid[] = + TREASURY_POLICY_TYPE_OID_BASE(10); + static const byte extCertPolicyTreasuryPiviContentSigningOid[] = + TREASURY_POLICY_TYPE_OID_BASE(12); + + /* Boeing PKI OIDs - 1.3.6.1.4.1.73.15.3.1.X */ + #define BOEING_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 73, 15, 3, 1, num} + static const byte extCertPolicyBoeingMediumHardwareSha256Oid[] = + BOEING_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyBoeingMediumHardwareContentSigningSha256Oid[] = + BOEING_POLICY_TYPE_OID_BASE(17); + + /* Carillon Federal Services OIDs - 1.3.6.1.4.1.45606.3.1.X */ + #define CARILLON_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 130, 228, 38, 3, 1, num} + static const byte extCertPolicyCarillonMediumhw256Oid[] = + CARILLON_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyCarillonAivhwOid[] = + CARILLON_POLICY_TYPE_OID_BASE(20); + static const byte extCertPolicyCarillonAivcontentOid[] = + CARILLON_POLICY_TYPE_OID_BASE(22); + + /* Carillon Information Security OIDs - 1.3.6.1.4.1.25054.3.1.X */ + #define CIS_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 129, 195, 94, 3, 1, num} + static const byte extCertPolicyCisMediumhw256Oid[] = + CIS_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyCisMeddevhw256Oid[] = + CIS_POLICY_TYPE_OID_BASE(14); + static const byte extCertPolicyCisIcecapHwOid[] = + CIS_POLICY_TYPE_OID_BASE(20); + static const byte extCertPolicyCisIcecapContentOid[] = + CIS_POLICY_TYPE_OID_BASE(22); + + /* CertiPath Bridge OIDs - 1.3.6.1.4.1.24019.1.1.1.X */ + #define CERTIPATH_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 129, 187, 83, 1, 1, 1, num} + static const byte extCertPolicyCertipathMediumhwOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyCertipathHighhwOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(3); + static const byte extCertPolicyCertipathIcecapHwOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(7); + static const byte extCertPolicyCertipathIcecapContentOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(9); + static const byte extCertPolicyCertipathVarMediumhwOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(18); + static const byte extCertPolicyCertipathVarHighhwOid[] = + CERTIPATH_POLICY_TYPE_OID_BASE(19); + + /* TSCP Bridge OIDs - 1.3.6.1.4.1.38099.1.1.1.X */ + #define TSCP_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 130, 169, 83, 1, 1, 1, num} + static const byte extCertPolicyTscpMediumhwOid[] = + TSCP_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyTscpPiviOid[] = + TSCP_POLICY_TYPE_OID_BASE(5); + static const byte extCertPolicyTscpPiviContentOid[] = + TSCP_POLICY_TYPE_OID_BASE(7); + + /* DigiCert NFI PKI OIDs - 2.16.840.1.113733.1.7.23.3.1.X */ + #define DIGICERT_NFI_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 134, 248, 69, 1, 7, 23, 3, 1, num} + static const byte extCertPolicyDigicertNfiMediumHardwareOid[] = + DIGICERT_NFI_POLICY_TYPE_OID_BASE(7); + static const byte extCertPolicyDigicertNfiAuthOid[] = + DIGICERT_NFI_POLICY_TYPE_OID_BASE(13); + static const byte extCertPolicyDigicertNfiPiviHardwareOid[] = + DIGICERT_NFI_POLICY_TYPE_OID_BASE(18); + static const byte extCertPolicyDigicertNfiPiviContentSigningOid[] = + DIGICERT_NFI_POLICY_TYPE_OID_BASE(20); + static const byte extCertPolicyDigicertNfiMediumDevicesHardwareOid[] = + DIGICERT_NFI_POLICY_TYPE_OID_BASE(36); + + /* Entrust Managed Services NFI PKI OIDs - 2.16.840.1.114027.200.3.10.7.X */ + #define ENTRUST_NFI_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 134, 250, 107, 129, 72, 3, 10, 7, num} + static const byte extCertPolicyEntrustNfiMediumHardwareOid[] = + ENTRUST_NFI_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyEntrustNfiMediumAuthenticationOid[] = + ENTRUST_NFI_POLICY_TYPE_OID_BASE(4); + static const byte extCertPolicyEntrustNfiPiviHardwareOid[] = + ENTRUST_NFI_POLICY_TYPE_OID_BASE(6); + static const byte extCertPolicyEntrustNfiPiviContentSigningOid[] = + ENTRUST_NFI_POLICY_TYPE_OID_BASE(9); + static const byte extCertPolicyEntrustNfiMediumDevicesHwOid[] = + ENTRUST_NFI_POLICY_TYPE_OID_BASE(16); + + /* Exostar LLC PKI OIDs - 1.3.6.1.4.1.13948.1.1.1.X */ + #define EXOSTAR_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 236, 124, 1, 1, 1, num} + static const byte extCertPolicyExostarMediumHardwareSha2Oid[] = + EXOSTAR_POLICY_TYPE_OID_BASE(6); + + /* IdenTrust NFI OIDs - 2.16.840.1.113839.0.100.X.Y */ + #define IDENTRUST_POLICY_TYPE_OID_BASE(num1, num2) {96, 134, 72, 1, 134, 249, 47, 0, 100, num1, num2} + static const byte extCertPolicyIdentrustMediumhwSignOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(12, 1); + static const byte extCertPolicyIdentrustMediumhwEncOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(12, 2); + static const byte extCertPolicyIdentrustPiviHwIdOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(18, 0); + static const byte extCertPolicyIdentrustPiviHwSignOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(18, 1); + static const byte extCertPolicyIdentrustPiviHwEncOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(18, 2); + static const byte extCertPolicyIdentrustPiviContentOid[] = + IDENTRUST_POLICY_TYPE_OID_BASE(20, 1); + + /* Lockheed Martin PKI OIDs - 1.3.6.1.4.1.103.100.1.1.3.X */ + #define LOCKHEED_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 103, 100, 1, 1, 3, num} + static const byte extCertPolicyLockheedMediumAssuranceHardwareOid[] = + LOCKHEED_POLICY_TYPE_OID_BASE(3); + + /* Northrop Grumman PKI OIDs - 1.3.6.1.4.1.16334.509.2.X */ + #define NORTHROP_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 255, 78, 131, 125, 2, num} + static const byte extCertPolicyNorthropMediumAssurance256HardwareTokenOid[] = + NORTHROP_POLICY_TYPE_OID_BASE(8); + static const byte extCertPolicyNorthropPiviAssurance256HardwareTokenOid[] = + NORTHROP_POLICY_TYPE_OID_BASE(9); + static const byte extCertPolicyNorthropPiviAssurance256ContentSigningOid[] = + NORTHROP_POLICY_TYPE_OID_BASE(11); + static const byte extCertPolicyNorthropMediumAssurance384HardwareTokenOid[] = + NORTHROP_POLICY_TYPE_OID_BASE(14); + + /* Raytheon PKI OIDs - 1.3.6.1.4.1.1569.10.1.X and 1.3.6.1.4.1.26769.10.1.X */ + #define RAYTHEON_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 140, 33, 10, 1, num} + static const byte extCertPolicyRaytheonMediumHardwareOid[] = + RAYTHEON_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyRaytheonMediumDeviceHardwareOid[] = + RAYTHEON_POLICY_TYPE_OID_BASE(18); + + #define RAYTHEON_SHA2_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 129, 209, 17, 10, 1, num} + static const byte extCertPolicyRaytheonSha2MediumHardwareOid[] = + RAYTHEON_SHA2_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyRaytheonSha2MediumDeviceHardwareOid[] = + RAYTHEON_SHA2_POLICY_TYPE_OID_BASE(18); + + /* WidePoint NFI PKI OIDs - 1.3.6.1.4.1.3922.1.1.1.X */ + #define WIDEPOINT_NFI_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 158, 82, 1, 1, 1, num} + static const byte extCertPolicyWidepointNfiMediumHardwareOid[] = + WIDEPOINT_NFI_POLICY_TYPE_OID_BASE(12); + static const byte extCertPolicyWidepointNfiPiviHardwareOid[] = + WIDEPOINT_NFI_POLICY_TYPE_OID_BASE(18); + static const byte extCertPolicyWidepointNfiPiviContentSigningOid[] = + WIDEPOINT_NFI_POLICY_TYPE_OID_BASE(20); + static const byte extCertPolicyWidepointNfiMediumDevicesHardwareOid[] = + WIDEPOINT_NFI_POLICY_TYPE_OID_BASE(38); + + /* Australian Defence Organisation PKI OIDs - 1.2.36.1.334.1.2.X.X */ + #define ADO_POLICY_TYPE_OID_BASE(type, num) {42, 36, 1, 130, 78, 1, 2, type, num} + static const byte extCertPolicyAdoIndividualMediumAssuranceOid[] = + ADO_POLICY_TYPE_OID_BASE(1, 2); + static const byte extCertPolicyAdoIndividualHighAssuranceOid[] = + ADO_POLICY_TYPE_OID_BASE(1, 3); + static const byte extCertPolicyAdoResourceMediumAssuranceOid[] = + ADO_POLICY_TYPE_OID_BASE(2, 2); + + /* Comodo Ltd PKI OID 1.3.6.1.4.1.6449.1.2.1.3.4 */ + #define COMODO_POLICY_TYPE_OID_BASE(num) {43, 6, 1, 4, 1, 178, 49, 1, 2, 1, 3, num} + static const byte extCertPolicyComodoLtdOid[] = + COMODO_POLICY_TYPE_OID_BASE(4); + + /* Netherlands Ministry of Defence PKI OIDs - 2.16.528.1.1003.1.2.5.X */ + #define NL_MOD_POLICY_TYPE_OID_BASE(num) {96, 132, 16, 1, 135, 107, 1, 2, 5, num} + static const byte extCertPolicyNlModAuthenticityOid[] = + NL_MOD_POLICY_TYPE_OID_BASE(1); + static const byte extCertPolicyNlModIrrefutabilityOid[] = + NL_MOD_POLICY_TYPE_OID_BASE(2); + static const byte extCertPolicyNlModConfidentialityOid[] = + NL_MOD_POLICY_TYPE_OID_BASE(3); #endif /* WOLFSSL_FPKI */ /* certAltNameType */ @@ -4619,6 +4894,11 @@ static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* doma * * Use oidIgnoreType to autofail. * + * Note that while this function currently handles a large + * number of FPKI certificate policy OIDs, these OIDs are not + * currently being handled in the code, they are just recognized + * as valid OIDs. + * * @param [in] id OID id. * @param [in] type Type of OID (enum Oid_Types). * @param [out] oidSz Length of OID byte array returned. @@ -5295,7 +5575,35 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) oid = extCertPolicyAnyOid; *oidSz = sizeof(extCertPolicyAnyOid); break; + case CP_ISRG_DOMAIN_VALID: + oid = extCertPolicyIsrgDomainValid; + *oidSz = sizeof(extCertPolicyIsrgDomainValid); + break; #if defined(WOLFSSL_FPKI) + case CP_FPKI_HIGH_ASSURANCE_OID: + oid = extCertPolicyFpkiHighAssuranceOid; + *oidSz = sizeof(extCertPolicyFpkiHighAssuranceOid); + break; + case CP_FPKI_COMMON_HARDWARE_OID: + oid = extCertPolicyFpkiCommonHardwareOid; + *oidSz = sizeof(extCertPolicyFpkiCommonHardwareOid); + break; + case CP_FPKI_MEDIUM_HARDWARE_OID: + oid = extCertPolicyFpkiMediumHardwareOid; + *oidSz = sizeof(extCertPolicyFpkiMediumHardwareOid); + break; + case CP_FPKI_COMMON_HIGH_OID: + oid = extCertPolicyFpkiCommonHighOid; + *oidSz = sizeof(extCertPolicyFpkiCommonHighOid); + break; + case CP_FPKI_COMMON_DEVICES_HARDWARE_OID: + oid = extCertPolicyFpkiCommonDevicesHardwareOid; + *oidSz = sizeof(extCertPolicyFpkiCommonDevicesHardwareOid); + break; + case CP_FPKI_COMMON_PIV_CONTENT_SIGNING_OID: + oid = extCertPolicyFpkiCommonPivContentSigningOid; + *oidSz = sizeof(extCertPolicyFpkiCommonPivContentSigningOid); + break; case CP_FPKI_COMMON_AUTH_OID: oid = extCertPolicyFpkiCommonAuthOid; *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid); @@ -5312,6 +5620,441 @@ const byte* OidFromId(word32 id, word32 type, word32* oidSz) oid = extCertPolicyFpkiPiviAuthOid; *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid); break; + case CP_FPKI_AUTH_TEST_OID: + oid = extCertPolicyFpkiAuthTestOid; + *oidSz = sizeof(extCertPolicyFpkiAuthTestOid); + break; + case CP_FPKI_CARDAUTH_TEST_OID: + oid = extCertPolicyFpkiCardauthTestOid; + *oidSz = sizeof(extCertPolicyFpkiCardauthTestOid); + break; + case CP_FPKI_PIV_CONTENT_TEST_OID: + oid = extCertPolicyFpkiPivContentTestOid; + *oidSz = sizeof(extCertPolicyFpkiPivContentTestOid); + break; + case CP_FPKI_PIV_AUTH_DERIVED_TEST_OID: + oid = extCertPolicyFpkiAuthDerivedTestOid; + *oidSz = sizeof(extCertPolicyFpkiAuthDerivedTestOid); + break; + case CP_FPKI_PIV_AUTH_DERIVED_HW_TEST_OID: + oid = extCertPolicyFpkiAuthDerivedHwTestOid; + *oidSz = sizeof(extCertPolicyFpkiAuthDerivedHwTestOid); + break; + case CP_DOD_MEDIUM_OID: + oid = extCertPolicyDodMediumOid; + *oidSz = sizeof(extCertPolicyDodMediumOid); + break; + case CP_DOD_MEDIUM_HARDWARE_OID: + oid = extCertPolicyDodMediumHardwareOid; + *oidSz = sizeof(extCertPolicyDodMediumHardwareOid); + break; + case CP_DOD_PIV_AUTH_OID: + oid = extCertPolicyDodPivAuthOid; + *oidSz = sizeof(extCertPolicyDodPivAuthOid); + break; + case CP_DOD_MEDIUM_NPE_OID: + oid = extCertPolicyDodMediumNpeOid; + *oidSz = sizeof(extCertPolicyDodMediumNpeOid); + break; + case CP_DOD_MEDIUM_2048_OID: + oid = extCertPolicyDodMedium2048Oid; + *oidSz = sizeof(extCertPolicyDodMedium2048Oid); + break; + case CP_DOD_MEDIUM_HARDWARE_2048_OID: + oid = extCertPolicyDodMediumHardware2048Oid; + *oidSz = sizeof(extCertPolicyDodMediumHardware2048Oid); + break; + case CP_DOD_PIV_AUTH_2048_OID: + oid = extCertPolicyDodPivAuth2048Oid; + *oidSz = sizeof(extCertPolicyDodPivAuth2048Oid); + break; + case CP_DOD_PEER_INTEROP_OID: + oid = extCertPolicyDodPeerInteropOid; + *oidSz = sizeof(extCertPolicyDodPeerInteropOid); + break; + case CP_DOD_MEDIUM_NPE_112_OID: + oid = extCertPolicyDodMediumNpe112Oid; + *oidSz = sizeof(extCertPolicyDodMediumNpe112Oid); + break; + case CP_DOD_MEDIUM_NPE_128_OID: + oid = extCertPolicyDodMediumNpe128Oid; + *oidSz = sizeof(extCertPolicyDodMediumNpe128Oid); + break; + case CP_DOD_MEDIUM_NPE_192_OID: + oid = extCertPolicyDodMediumNpe192Oid; + *oidSz = sizeof(extCertPolicyDodMediumNpe192Oid); + break; + case CP_DOD_MEDIUM_112_OID: + oid = extCertPolicyDodMedium112Oid; + *oidSz = sizeof(extCertPolicyDodMedium112Oid); + break; + case CP_DOD_MEDIUM_128_OID: + oid = extCertPolicyDodMedium128Oid; + *oidSz = sizeof(extCertPolicyDodMedium128Oid); + break; + case CP_DOD_MEDIUM_192_OID: + oid = extCertPolicyDodMedium192Oid; + *oidSz = sizeof(extCertPolicyDodMedium192Oid); + break; + case CP_DOD_MEDIUM_HARDWARE_112_OID: + oid = extCertPolicyDodMediumHardware112Oid; + *oidSz = sizeof(extCertPolicyDodMediumHardware112Oid); + break; + case CP_DOD_MEDIUM_HARDWARE_128_OID: + oid = extCertPolicyDodMediumHardware128Oid; + *oidSz = sizeof(extCertPolicyDodMediumHardware128Oid); + break; + case CP_DOD_MEDIUM_HARDWARE_192_OID: + oid = extCertPolicyDodMediumHardware192Oid; + *oidSz = sizeof(extCertPolicyDodMediumHardware192Oid); + break; + case CP_DOD_ADMIN_OID: + oid = extCertPolicyDodAdminOid; + *oidSz = sizeof(extCertPolicyDodAdminOid); + break; + case CP_DOD_INTERNAL_NPE_112_OID: + oid = extCertPolicyDodInternalNpe112Oid; + *oidSz = sizeof(extCertPolicyDodInternalNpe112Oid); + break; + case CP_DOD_INTERNAL_NPE_128_OID: + oid = extCertPolicyDodInternalNpe128Oid; + *oidSz = sizeof(extCertPolicyDodInternalNpe128Oid); + break; + case CP_DOD_INTERNAL_NPE_192_OID: + oid = extCertPolicyDodInternalNpe192Oid; + *oidSz = sizeof(extCertPolicyDodInternalNpe192Oid); + break; + case CP_ECA_MEDIUM_OID: + oid = extCertPolicyEcaMediumOid; + *oidSz = sizeof(extCertPolicyEcaMediumOid); + break; + case CP_ECA_MEDIUM_HARDWARE_OID: + oid = extCertPolicyEcaMediumHardwareOid; + *oidSz = sizeof(extCertPolicyEcaMediumHardwareOid); + break; + case CP_ECA_MEDIUM_TOKEN_OID: + oid = extCertPolicyEcaMediumTokenOid; + *oidSz = sizeof(extCertPolicyEcaMediumTokenOid); + break; + case CP_ECA_MEDIUM_SHA256_OID: + oid = extCertPolicyEcaMediumSha256Oid; + *oidSz = sizeof(extCertPolicyEcaMediumSha256Oid); + break; + case CP_ECA_MEDIUM_TOKEN_SHA256_OID: + oid = extCertPolicyEcaMediumTokenSha256Oid; + *oidSz = sizeof(extCertPolicyEcaMediumTokenSha256Oid); + break; + case CP_ECA_MEDIUM_HARDWARE_PIVI_OID: + oid = extCertPolicyEcaMediumHardwarePiviOid; + *oidSz = sizeof(extCertPolicyEcaMediumHardwarePiviOid); + break; + case CP_ECA_CONTENT_SIGNING_PIVI_OID: + oid = extCertPolicyEcaContentSigningPiviOid; + *oidSz = sizeof(extCertPolicyEcaContentSigningPiviOid); + break; + case CP_ECA_MEDIUM_DEVICE_SHA256_OID: + oid = extCertPolicyEcaMediumDeviceSha256Oid; + *oidSz = sizeof(extCertPolicyEcaMediumDeviceSha256Oid); + break; + case CP_ECA_MEDIUM_HARDWARE_SHA256_OID: + oid = extCertPolicyEcaMediumHardwareSha256Oid; + *oidSz = sizeof(extCertPolicyEcaMediumHardwareSha256Oid); + break; + + /* Department of State PKI OIDs */ + case CP_STATE_BASIC_OID: + oid = extCertPolicyStateBasicOid; + *oidSz = sizeof(extCertPolicyStateBasicOid); + break; + case CP_STATE_LOW_OID: + oid = extCertPolicyStateLowOid; + *oidSz = sizeof(extCertPolicyStateLowOid); + break; + case CP_STATE_MODERATE_OID: + oid = extCertPolicyStateModerateOid; + *oidSz = sizeof(extCertPolicyStateModerateOid); + break; + case CP_STATE_HIGH_OID: + oid = extCertPolicyStateHighOid; + *oidSz = sizeof(extCertPolicyStateHighOid); + break; + case CP_STATE_MEDHW_OID: + oid = extCertPolicyStateMedHwOid; + *oidSz = sizeof(extCertPolicyStateMedHwOid); + break; + case CP_STATE_MEDDEVHW_OID: + oid = extCertPolicyStateMediumDeviceHardwareOid; + *oidSz = sizeof(extCertPolicyStateMediumDeviceHardwareOid); + break; + + /* U.S. Treasury SSP PKI OIDs */ + case CP_TREAS_MEDIUMHW_OID: + oid = extCertPolicyTreasuryMediumHardwareOid; + *oidSz = sizeof(extCertPolicyTreasuryMediumHardwareOid); + break; + case CP_TREAS_HIGH_OID: + oid = extCertPolicyTreasuryHighOid; + *oidSz = sizeof(extCertPolicyTreasuryHighOid); + break; + case CP_TREAS_PIVI_HW_OID: + oid = extCertPolicyTreasuryPiviHardwareOid; + *oidSz = sizeof(extCertPolicyTreasuryPiviHardwareOid); + break; + case CP_TREAS_PIVI_CONTENT_OID: + oid = extCertPolicyTreasuryPiviContentSigningOid; + *oidSz = sizeof(extCertPolicyTreasuryPiviContentSigningOid); + break; + + /* Boeing PKI OIDs */ + case CP_BOEING_MEDIUMHW_SHA256_OID: + oid = extCertPolicyBoeingMediumHardwareSha256Oid; + *oidSz = sizeof(extCertPolicyBoeingMediumHardwareSha256Oid); + break; + case CP_BOEING_MEDIUMHW_CONTENT_SHA256_OID: + oid = extCertPolicyBoeingMediumHardwareContentSigningSha256Oid; + *oidSz = sizeof(extCertPolicyBoeingMediumHardwareContentSigningSha256Oid); + break; + + /* DigiCert NFI PKI OIDs */ + case CP_DIGICERT_NFSSP_MEDIUMHW_OID: + oid = extCertPolicyDigicertNfiMediumHardwareOid; + *oidSz = sizeof(extCertPolicyDigicertNfiMediumHardwareOid); + break; + case CP_DIGICERT_NFSSP_AUTH_OID: + oid = extCertPolicyDigicertNfiAuthOid; + *oidSz = sizeof(extCertPolicyDigicertNfiAuthOid); + break; + case CP_DIGICERT_NFSSP_PIVI_HW_OID: + oid = extCertPolicyDigicertNfiPiviHardwareOid; + *oidSz = sizeof(extCertPolicyDigicertNfiPiviHardwareOid); + break; + case CP_DIGICERT_NFSSP_PIVI_CONTENT_OID: + oid = extCertPolicyDigicertNfiPiviContentSigningOid; + *oidSz = sizeof(extCertPolicyDigicertNfiPiviContentSigningOid); + break; + case CP_DIGICERT_NFSSP_MEDDEVHW_OID: + oid = extCertPolicyDigicertNfiMediumDevicesHardwareOid; + *oidSz = sizeof(extCertPolicyDigicertNfiMediumDevicesHardwareOid); + break; + + /* Entrust Managed Services NFI PKI OIDs */ + case CP_ENTRUST_NFSSP_MEDIUMHW_OID: + oid = extCertPolicyEntrustNfiMediumHardwareOid; + *oidSz = sizeof(extCertPolicyEntrustNfiMediumHardwareOid); + break; + case CP_ENTRUST_NFSSP_MEDAUTH_OID: + oid = extCertPolicyEntrustNfiMediumAuthenticationOid; + *oidSz = sizeof(extCertPolicyEntrustNfiMediumAuthenticationOid); + break; + case CP_ENTRUST_NFSSP_PIVI_HW_OID: + oid = extCertPolicyEntrustNfiPiviHardwareOid; + *oidSz = sizeof(extCertPolicyEntrustNfiPiviHardwareOid); + break; + case CP_ENTRUST_NFSSP_PIVI_CONTENT_OID: + oid = extCertPolicyEntrustNfiPiviContentSigningOid; + *oidSz = sizeof(extCertPolicyEntrustNfiPiviContentSigningOid); + break; + case CP_ENTRUST_NFSSP_MEDDEVHW_OID: + oid = extCertPolicyEntrustNfiMediumDevicesHwOid; + *oidSz = sizeof(extCertPolicyEntrustNfiMediumDevicesHwOid); + break; + + /* Exostar LLC PKI OIDs */ + case CP_EXOSTAR_MEDIUMHW_SHA2_OID: + oid = extCertPolicyExostarMediumHardwareSha2Oid; + *oidSz = sizeof(extCertPolicyExostarMediumHardwareSha2Oid); + break; + + /* Lockheed Martin PKI OIDs */ + case CP_LOCKHEED_MEDIUMHW_OID: + oid = extCertPolicyLockheedMediumAssuranceHardwareOid; + *oidSz = sizeof(extCertPolicyLockheedMediumAssuranceHardwareOid); + break; + + /* Northrop Grumman PKI OIDs */ + case CP_NORTHROP_MEDIUM_256_HW_OID: + oid = extCertPolicyNorthropMediumAssurance256HardwareTokenOid; + *oidSz = sizeof(extCertPolicyNorthropMediumAssurance256HardwareTokenOid); + break; + case CP_NORTHROP_PIVI_256_HW_OID: + oid = extCertPolicyNorthropPiviAssurance256HardwareTokenOid; + *oidSz = sizeof(extCertPolicyNorthropPiviAssurance256HardwareTokenOid); + break; + case CP_NORTHROP_PIVI_256_CONTENT_OID: + oid = extCertPolicyNorthropPiviAssurance256ContentSigningOid; + *oidSz = sizeof(extCertPolicyNorthropPiviAssurance256ContentSigningOid); + break; + case CP_NORTHROP_MEDIUM_384_HW_OID: + oid = extCertPolicyNorthropMediumAssurance384HardwareTokenOid; + *oidSz = sizeof(extCertPolicyNorthropMediumAssurance384HardwareTokenOid); + break; + + /* Raytheon PKI OIDs */ + case CP_RAYTHEON_MEDIUMHW_OID: + oid = extCertPolicyRaytheonMediumHardwareOid; + *oidSz = sizeof(extCertPolicyRaytheonMediumHardwareOid); + break; + case CP_RAYTHEON_MEDDEVHW_OID: + oid = extCertPolicyRaytheonMediumDeviceHardwareOid; + *oidSz = sizeof(extCertPolicyRaytheonMediumDeviceHardwareOid); + break; + case CP_RAYTHEON_SHA2_MEDIUMHW_OID: + oid = extCertPolicyRaytheonSha2MediumHardwareOid; + *oidSz = sizeof(extCertPolicyRaytheonSha2MediumHardwareOid); + break; + case CP_RAYTHEON_SHA2_MEDDEVHW_OID: + oid = extCertPolicyRaytheonSha2MediumDeviceHardwareOid; + *oidSz = sizeof(extCertPolicyRaytheonSha2MediumDeviceHardwareOid); + break; + + /* WidePoint NFI PKI OIDs */ + case CP_WIDEPOINT_MEDIUMHW_OID: + oid = extCertPolicyWidepointNfiMediumHardwareOid; + *oidSz = sizeof(extCertPolicyWidepointNfiMediumHardwareOid); + break; + case CP_WIDEPOINT_PIVI_HW_OID: + oid = extCertPolicyWidepointNfiPiviHardwareOid; + *oidSz = sizeof(extCertPolicyWidepointNfiPiviHardwareOid); + break; + case CP_WIDEPOINT_PIVI_CONTENT_OID: + oid = extCertPolicyWidepointNfiPiviContentSigningOid; + *oidSz = sizeof(extCertPolicyWidepointNfiPiviContentSigningOid); + break; + case CP_WIDEPOINT_MEDDEVHW_OID: + oid = extCertPolicyWidepointNfiMediumDevicesHardwareOid; + *oidSz = sizeof(extCertPolicyWidepointNfiMediumDevicesHardwareOid); + break; + + /* Australian Defence Organisation PKI OIDs */ + case CP_ADO_MEDIUM_OID: + oid = extCertPolicyAdoIndividualMediumAssuranceOid; + *oidSz = sizeof(extCertPolicyAdoIndividualMediumAssuranceOid); + break; + case CP_ADO_HIGH_OID: + oid = extCertPolicyAdoIndividualHighAssuranceOid; + *oidSz = sizeof(extCertPolicyAdoIndividualHighAssuranceOid); + break; + case CP_ADO_RESOURCE_MEDIUM_OID: + oid = extCertPolicyAdoResourceMediumAssuranceOid; + *oidSz = sizeof(extCertPolicyAdoResourceMediumAssuranceOid); + break; + + /* Netherlands Ministry of Defence PKI OIDs */ + case CP_NL_MOD_AUTH_OID: + oid = extCertPolicyNlModAuthenticityOid; + *oidSz = sizeof(extCertPolicyNlModAuthenticityOid); + break; + case CP_NL_MOD_IRREFUT_OID: + oid = extCertPolicyNlModIrrefutabilityOid; + *oidSz = sizeof(extCertPolicyNlModIrrefutabilityOid); + break; + case CP_NL_MOD_CONFID_OID: + oid = extCertPolicyNlModConfidentialityOid; + *oidSz = sizeof(extCertPolicyNlModConfidentialityOid); + break; + + /* IdenTrust NFI OIDs */ + case CP_IDENTRUST_MEDIUMHW_SIGN_OID: + oid = extCertPolicyIdentrustMediumhwSignOid; + *oidSz = sizeof(extCertPolicyIdentrustMediumhwSignOid); + break; + case CP_IDENTRUST_MEDIUMHW_ENC_OID: + oid = extCertPolicyIdentrustMediumhwEncOid; + *oidSz = sizeof(extCertPolicyIdentrustMediumhwEncOid); + break; + case CP_IDENTRUST_PIVI_HW_ID_OID: + oid = extCertPolicyIdentrustPiviHwIdOid; + *oidSz = sizeof(extCertPolicyIdentrustPiviHwIdOid); + break; + case CP_IDENTRUST_PIVI_HW_SIGN_OID: + oid = extCertPolicyIdentrustPiviHwSignOid; + *oidSz = sizeof(extCertPolicyIdentrustPiviHwSignOid); + break; + case CP_IDENTRUST_PIVI_HW_ENC_OID: + oid = extCertPolicyIdentrustPiviHwEncOid; + *oidSz = sizeof(extCertPolicyIdentrustPiviHwEncOid); + break; + case CP_IDENTRUST_PIVI_CONTENT_OID: + oid = extCertPolicyIdentrustPiviContentOid; + *oidSz = sizeof(extCertPolicyIdentrustPiviContentOid); + break; + + /* TSCP Bridge OIDs */ + case CP_TSCP_MEDIUMHW_OID: + oid = extCertPolicyTscpMediumhwOid; + *oidSz = sizeof(extCertPolicyTscpMediumhwOid); + break; + case CP_TSCP_PIVI_OID: + oid = extCertPolicyTscpPiviOid; + *oidSz = sizeof(extCertPolicyTscpPiviOid); + break; + case CP_TSCP_PIVI_CONTENT_OID: + oid = extCertPolicyTscpPiviContentOid; + *oidSz = sizeof(extCertPolicyTscpPiviContentOid); + break; + + /* Carillon Federal Services OIDs */ + case CP_CARILLON_MEDIUMHW_256_OID: + oid = extCertPolicyCarillonMediumhw256Oid; + *oidSz = sizeof(extCertPolicyCarillonMediumhw256Oid); + break; + case CP_CARILLON_AIVHW_OID: + oid = extCertPolicyCarillonAivhwOid; + *oidSz = sizeof(extCertPolicyCarillonAivhwOid); + break; + case CP_CARILLON_AIVCONTENT_OID: + oid = extCertPolicyCarillonAivcontentOid; + *oidSz = sizeof(extCertPolicyCarillonAivcontentOid); + break; + + /* Carillon Information Security OIDs */ + case CP_CIS_MEDIUMHW_256_OID: + oid = extCertPolicyCisMediumhw256Oid; + *oidSz = sizeof(extCertPolicyCisMediumhw256Oid); + break; + case CP_CIS_MEDDEVHW_256_OID: + oid = extCertPolicyCisMeddevhw256Oid; + *oidSz = sizeof(extCertPolicyCisMeddevhw256Oid); + break; + case CP_CIS_ICECAP_HW_OID: + oid = extCertPolicyCisIcecapHwOid; + *oidSz = sizeof(extCertPolicyCisIcecapHwOid); + break; + case CP_CIS_ICECAP_CONTENT_OID: + oid = extCertPolicyCisIcecapContentOid; + *oidSz = sizeof(extCertPolicyCisIcecapContentOid); + break; + + /* CertiPath Bridge OIDs */ + case CP_CERTIPATH_MEDIUMHW_OID: + oid = extCertPolicyCertipathMediumhwOid; + *oidSz = sizeof(extCertPolicyCertipathMediumhwOid); + break; + case CP_CERTIPATH_HIGHHW_OID: + oid = extCertPolicyCertipathHighhwOid; + *oidSz = sizeof(extCertPolicyCertipathHighhwOid); + break; + case CP_CERTIPATH_ICECAP_HW_OID: + oid = extCertPolicyCertipathIcecapHwOid; + *oidSz = sizeof(extCertPolicyCertipathIcecapHwOid); + break; + case CP_CERTIPATH_ICECAP_CONTENT_OID: + oid = extCertPolicyCertipathIcecapContentOid; + *oidSz = sizeof(extCertPolicyCertipathIcecapContentOid); + break; + case CP_CERTIPATH_VAR_MEDIUMHW_OID: + oid = extCertPolicyCertipathVarMediumhwOid; + *oidSz = sizeof(extCertPolicyCertipathVarMediumhwOid); + break; + case CP_CERTIPATH_VAR_HIGHHW_OID: + oid = extCertPolicyCertipathVarHighhwOid; + *oidSz = sizeof(extCertPolicyCertipathVarHighhwOid); + break; + case CP_COMODO_OID: + oid = extCertPolicyComodoLtdOid; + *oidSz = sizeof(extCertPolicyComodoLtdOid); + break; + /* FPKI OIDs */ #endif /* WOLFSSL_FPKI */ default: break; @@ -5927,6 +6670,169 @@ static int DumpOID(const byte* oidData, word32 oidSz, word32 oid, } #endif /* ASN_DUMP_OID */ +#ifdef WOLFSSL_FPKI +/* Handles the large number of collisions from FPKI certificate policy + * OID sums. Returns a special value (100000 + actual sum) if a + * collision is detected. + * @param [in] oid Buffer holding OID. + * @param [in] oidSz Length of OID data in buffer. + * @param [in] oidSum The sum of the OID being passed in. + */ +static word32 fpkiCertPolOid(const byte* oid, word32 oidSz, word32 oidSum) { + + switch (oidSum) { + case CP_ADO_MEDIUM_OID: + if ((word32)sizeof(extCertPolicyComodoLtdOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyComodoLtdOid, + sizeof(extCertPolicyComodoLtdOid)) == 0) + return CP_COMODO_OID; + break; + case CP_FPKI_HIGH_ASSURANCE_OID: + if ((word32)sizeof(extCertPolicyStateBasicOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyStateBasicOid, + sizeof(extCertPolicyStateBasicOid)) == 0) + return CP_STATE_BASIC_OID; + break; + case CP_FPKI_COMMON_DEVICES_HARDWARE_OID: + if ((word32)sizeof(extCertPolicyDodPeerInteropOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyDodPeerInteropOid, + sizeof(extCertPolicyDodPeerInteropOid)) == 0) + return CP_DOD_PEER_INTEROP_OID; + break; + case CP_FPKI_PIV_AUTH_HW_OID: + if ((word32)sizeof(extCertPolicyDodMediumNpe112Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyDodMediumNpe112Oid, + sizeof(extCertPolicyDodMediumNpe112Oid)) == 0) + return CP_DOD_MEDIUM_NPE_112_OID; + else if ((word32)sizeof(extCertPolicyStateMediumDeviceHardwareOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyStateMediumDeviceHardwareOid, + sizeof(extCertPolicyStateMediumDeviceHardwareOid)) == 0) + return CP_STATE_MEDDEVHW_OID; + break; + case CP_FPKI_PIVI_AUTH_OID: + if ((word32)sizeof(extCertPolicyDodMedium128Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyDodMedium128Oid, + sizeof(extCertPolicyDodMedium128Oid)) == 0) + return CP_DOD_MEDIUM_128_OID; + break; + case CP_FPKI_COMMON_PIVI_CONTENT_SIGNING_OID: + if ((word32)sizeof(extCertPolicyDodMediumHardware112Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyDodMediumHardware112Oid, + sizeof(extCertPolicyDodMediumHardware112Oid)) == 0) + return CP_DOD_MEDIUM_HARDWARE_112_OID; + else if ((word32)sizeof(extCertPolicyCertipathHighhwOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyCertipathHighhwOid, + sizeof(extCertPolicyCertipathHighhwOid)) == 0) + return CP_CERTIPATH_HIGHHW_OID; + break; + case CP_DOD_MEDIUM_OID: + if ((word32)sizeof(extCertPolicyEcaMediumOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaMediumOid, + sizeof(extCertPolicyEcaMediumOid)) == 0) + return CP_ECA_MEDIUM_OID; + break; + case CP_FPKI_COMMON_AUTH_OID: + if ((word32)sizeof(extCertPolicyEcaMediumSha256Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaMediumSha256Oid, + sizeof(extCertPolicyEcaMediumSha256Oid)) == 0) + return CP_ECA_MEDIUM_SHA256_OID; + break; + case CP_FPKI_MEDIUM_HARDWARE_OID: + if ((word32)sizeof(extCertPolicyEcaMediumTokenOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaMediumTokenOid, + sizeof(extCertPolicyEcaMediumTokenOid)) == 0) + return CP_ECA_MEDIUM_TOKEN_OID; + else if ((word32)sizeof(extCertPolicyTreasuryPiviHardwareOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyTreasuryPiviHardwareOid, + sizeof(extCertPolicyTreasuryPiviHardwareOid)) == 0) + return CP_TREAS_PIVI_HW_OID; + break; + case CP_DOD_MEDIUM_HARDWARE_OID: + if ((word32)sizeof(extCertPolicyEcaMediumTokenSha256Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaMediumTokenSha256Oid, + sizeof(extCertPolicyEcaMediumTokenSha256Oid)) == 0) + return CP_ECA_MEDIUM_TOKEN_SHA256_OID; + else if ((word32)sizeof(extCertPolicyTreasuryPiviContentSigningOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyTreasuryPiviContentSigningOid, + sizeof(extCertPolicyTreasuryPiviContentSigningOid)) == 0) + return CP_TREAS_PIVI_CONTENT_OID; + break; + case CP_DOD_PIV_AUTH_OID: + if ((word32)sizeof(extCertPolicyEcaMediumHardwarePiviOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaMediumHardwarePiviOid, + sizeof(extCertPolicyEcaMediumHardwarePiviOid)) == 0) + return CP_ECA_MEDIUM_HARDWARE_PIVI_OID; + else if ((word32)sizeof(extCertPolicyStateMedHwOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyStateMedHwOid, + sizeof(extCertPolicyStateMedHwOid)) == 0) + return CP_STATE_MEDHW_OID; + break; + case CP_FPKI_COMMON_HARDWARE_OID: + if ((word32)sizeof(extCertPolicyStateHighOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyStateHighOid, + sizeof(extCertPolicyStateHighOid)) == 0) + return CP_STATE_HIGH_OID; + else if ((word32)sizeof(extCertPolicyTreasuryHighOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyTreasuryHighOid, + sizeof(extCertPolicyTreasuryHighOid)) == 0) + return CP_TREAS_HIGH_OID; + break; + case CP_ECA_MEDIUM_HARDWARE_OID: + if ((word32)sizeof(extCertPolicyExostarMediumHardwareSha2Oid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyExostarMediumHardwareSha2Oid, + sizeof(extCertPolicyExostarMediumHardwareSha2Oid)) == 0) + return CP_EXOSTAR_MEDIUMHW_SHA2_OID; + break; + case CP_ADO_HIGH_OID: + if ((word32)sizeof(extCertPolicyAdoResourceMediumAssuranceOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyAdoResourceMediumAssuranceOid, + sizeof(extCertPolicyAdoResourceMediumAssuranceOid)) == 0) + return CP_ADO_RESOURCE_MEDIUM_OID; + break; + case CP_DOD_ADMIN_OID: + if ((word32)sizeof(extCertPolicyCarillonAivcontentOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyCarillonAivcontentOid, + sizeof(extCertPolicyCarillonAivcontentOid)) == 0) + return CP_CARILLON_AIVCONTENT_OID; + break; + case CP_TREAS_MEDIUMHW_OID: + if ((word32)sizeof(extCertPolicyStateModerateOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyStateModerateOid, + sizeof(extCertPolicyStateModerateOid)) == 0) + return CP_STATE_MODERATE_OID; + break; + case CP_CIS_ICECAP_HW_OID: + if ((word32)sizeof(extCertPolicyNlModIrrefutabilityOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyNlModIrrefutabilityOid, + sizeof(extCertPolicyNlModIrrefutabilityOid)) == 0) + return CP_NL_MOD_IRREFUT_OID; + break; + case CP_DOD_MEDIUM_192_OID: + if ((word32)sizeof(extCertPolicyCertipathMediumhwOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyCertipathMediumhwOid, + sizeof(extCertPolicyCertipathMediumhwOid)) == 0) + return CP_CERTIPATH_MEDIUMHW_OID; + break; + case CP_CARILLON_AIVHW_OID: + if ((word32)sizeof(extCertPolicyCertipathVarMediumhwOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyCertipathVarMediumhwOid, + sizeof(extCertPolicyCertipathVarMediumhwOid)) == 0) + return CP_CERTIPATH_VAR_MEDIUMHW_OID; + break; + case CP_ISRG_DOMAIN_VALID: + if ((word32)sizeof(extCertPolicyEcaContentSigningPiviOid) == (word32)oidSz && + XMEMCMP(oid, extCertPolicyEcaContentSigningPiviOid, + sizeof(extCertPolicyEcaContentSigningPiviOid)) == 0) + return CP_ECA_CONTENT_SIGNING_PIVI_OID; + break; + default: + break; + } + + return 0; +} +#endif + /* Get the OID data and verify it is of the type specified when compiled in. * * @param [in] input Buffer holding OID. @@ -5952,13 +6858,13 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, const byte* checkOid = NULL; word32 checkOidSz; #endif /* NO_VERIFY_OID */ -#if defined(HAVE_SPHINCS) +#if defined(HAVE_SPHINCS) || defined(WOLFSSL_FPKI) word32 found_collision = 0; #endif (void)oidType; *oid = 0; -#ifndef NO_VERIFY_OID +#if !defined(NO_VERIFY_OID) || defined(WOLFSSL_FPKI) /* Keep references to OID data and length for check. */ actualOid = &input[idx]; actualOidSz = (word32)length; @@ -5987,7 +6893,16 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, idx++; } -#ifdef HAVE_SPHINCS +#ifdef WOLFSSL_FPKI + /* Due to the large number of OIDs for FPKI certificate policy, there + are multiple collsisions. Handle them in a dedicated function, + if a collision is detected, the OID is adjusted. */ + if (oidType == oidCertPolicyType) { + found_collision = fpkiCertPolOid(actualOid, actualOidSz, *oid); + } +#endif + +#if defined(HAVE_SPHINCS) || defined(WOLFSSL_FPKI) if (found_collision) { *oid = found_collision; } @@ -6593,16 +7508,16 @@ static int DecodeRsaPssParams(const byte* params, word32 sz, defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050))) /* Byte offset of numbers in RSA key. */ size_t rsaIntOffset[] = { - OFFSETOF(RsaKey, n), - OFFSETOF(RsaKey, e), + WC_OFFSETOF(RsaKey, n), + WC_OFFSETOF(RsaKey, e), #ifndef WOLFSSL_RSA_PUBLIC_ONLY - OFFSETOF(RsaKey, d), - OFFSETOF(RsaKey, p), - OFFSETOF(RsaKey, q), + WC_OFFSETOF(RsaKey, d), + WC_OFFSETOF(RsaKey, p), + WC_OFFSETOF(RsaKey, q), #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) - OFFSETOF(RsaKey, dP), - OFFSETOF(RsaKey, dQ), - OFFSETOF(RsaKey, u) + WC_OFFSETOF(RsaKey, dP), + WC_OFFSETOF(RsaKey, dQ), + WC_OFFSETOF(RsaKey, u) #endif #endif }; @@ -7429,7 +8344,7 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, /* Get the size of the DER encoding. */ ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length-1, &sz); } - if (ret == 0) { + if ((ret == 0) || (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E))) { /* Always return the calculated size. */ *outSz = (word32)sz; } @@ -8319,9 +9234,12 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, if (dilithium == NULL) return MEMORY_E; - if (wc_dilithium_init(dilithium) != 0) { - tmpIdx = 0; - if (wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0) { + /* wc_dilithium_init() returns 0 on success and a non-zero value on + * failure. */ + if (wc_dilithium_init(dilithium) == 0) { + if ((*algoID == 0) && + (wc_dilithium_set_level(dilithium, WC_ML_DSA_44) == 0)) { + tmpIdx = 0; if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, keySz) == 0) { *algoID = ML_DSA_LEVEL2k; @@ -8330,7 +9248,9 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, WOLFSSL_MSG("Not Dilithium Level 2 DER key"); } } - else if (wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0) { + if ((*algoID == 0) && + (wc_dilithium_set_level(dilithium, WC_ML_DSA_65) == 0)) { + tmpIdx = 0; if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, keySz) == 0) { *algoID = ML_DSA_LEVEL3k; @@ -8339,7 +9259,9 @@ int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, WOLFSSL_MSG("Not Dilithium Level 3 DER key"); } } - else if (wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0) { + if ((*algoID == 0) && + (wc_dilithium_set_level(dilithium, WC_ML_DSA_87) == 0)) { + tmpIdx = 0; if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium, keySz) == 0) { *algoID = ML_DSA_LEVEL5k; @@ -9209,26 +10131,6 @@ int ToTraditionalEnc(byte* input, word32 sz, const char* password, #ifdef HAVE_PKCS12 -#define PKCS8_MIN_BLOCK_SIZE 8 -static int Pkcs8Pad(byte* buf, int sz, int blockSz) -{ - int padSz; - - /* calculate pad size */ - padSz = blockSz - (sz & (blockSz - 1)); - - /* pad with padSz value */ - if (buf) { - int i; - for (i = 0; i < padSz; i++) { - buf[sz+i] = (byte)(padSz & 0xFF); - } - } - - /* return adjusted length */ - return sz + padSz; -} - #ifdef WOLFSSL_ASN_TEMPLATE /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo @@ -9338,7 +10240,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, /* calculate size */ /* size of constructed string at end */ - sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); + sz = wc_PkcsPad(NULL, inputSz, (word32)blockSz); totalSz = ASN_TAG_SZ; totalSz += SetLength(sz, seq); totalSz += sz; @@ -9434,7 +10336,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0; /* get pad size and verify buffer room */ - sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); + sz = wc_PkcsPad(NULL, inputSz, (word32)blockSz); if (sz + inOutIdx > *outSz) { #ifdef WOLFSSL_SMALL_STACK XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -9445,7 +10347,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, /* copy input to output buffer and pad end */ XMEMCPY(out + inOutIdx, input, inputSz); - sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz); + sz = wc_PkcsPad(out + inOutIdx, inputSz, (word32)blockSz); #ifdef WOLFSSL_SMALL_STACK cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER); if (cbcIv == NULL) { @@ -9519,7 +10421,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, salt, saltSz); SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER], (word16)itt); - pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz); + pkcs8Sz = wc_PkcsPad(NULL, inputSz, (word32)blockSz); SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz); /* Calculate size of encoding. */ @@ -9557,7 +10459,7 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, byte* pkcs8 = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data; XMEMCPY(pkcs8, input, inputSz); - Pkcs8Pad(pkcs8, (int)inputSz, blockSz); + (void)wc_PkcsPad(pkcs8, inputSz, (word32)blockSz); /* Encrypt PKCS#8 key inline. */ ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id, @@ -9577,6 +10479,36 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, #endif /* HAVE_PKCS12 */ #endif /* NO_PWDBASED */ +/* Block padding used for PKCS#5, PKCS#7, PKCS#8 and PKCS#12. + * + * The length of padding is the value of each padding byte. + * + * When buf is NULL, the padded size is returned. + * + * @param [in, out] buf Buffer of data to be padded. May be NULL. + * @param [in] sz Size of data in bytes. + * @param [in] blockSz Size of block, in bytes, which buffer size must be + * a multiple of. Assumed to be less than 256 and + * a power of 2. + * @return Size of padded buffer in bytes. + */ +word32 wc_PkcsPad(byte* buf, word32 sz, word32 blockSz) +{ + /* Calculate number of padding bytes. */ + word32 padSz = blockSz - (sz & (blockSz - 1)); + + /* Pad with padSz byte. */ + if (buf != NULL) { + word32 i; + for (i = 0; i < padSz; i++) { + buf[sz+i] = (byte)(padSz & 0xFF); + } + } + + /* Return padded buffer size in bytes. */ + return sz + padSz; +} + #ifndef NO_RSA #ifdef WOLFSSL_ASN_TEMPLATE /* ASN.1 template for an RSA public key. @@ -11477,8 +12409,8 @@ int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen) } /* This version of the function allows output to be NULL. In that case, the - DsaKeyIntsToDer will return WC_NO_ERR_TRACE(LENGTH_ONLY_E) and the required output buffer - size will be pointed to by inLen. */ + DsaKeyIntsToDer will return WC_NO_ERR_TRACE(LENGTH_ONLY_E) and the required + output buffer size will be pointed to by inLen. */ int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen) { if (!key || !inLen) @@ -13096,13 +14028,13 @@ static const CertNameData certNameSubject[] = { { "/CN=", 4, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectCN), - OFFSETOF(DecodedCert, subjectCNLen), - OFFSETOF(DecodedCert, subjectCNEnc), + WC_OFFSETOF(DecodedCert, subjectCN), + WC_OFFSETOF(DecodedCert, subjectCNLen), + WC_OFFSETOF(DecodedCert, subjectCNEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerCN), - OFFSETOF(DecodedCert, issuerCNLen), - OFFSETOF(DecodedCert, issuerCNEnc), + WC_OFFSETOF(DecodedCert, issuerCN), + WC_OFFSETOF(DecodedCert, issuerCNLen), + WC_OFFSETOF(DecodedCert, issuerCNEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13113,13 +14045,13 @@ static const CertNameData certNameSubject[] = { { "/SN=", 4, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectSN), - OFFSETOF(DecodedCert, subjectSNLen), - OFFSETOF(DecodedCert, subjectSNEnc), + WC_OFFSETOF(DecodedCert, subjectSN), + WC_OFFSETOF(DecodedCert, subjectSNLen), + WC_OFFSETOF(DecodedCert, subjectSNEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerSN), - OFFSETOF(DecodedCert, issuerSNLen), - OFFSETOF(DecodedCert, issuerSNEnc), + WC_OFFSETOF(DecodedCert, issuerSN), + WC_OFFSETOF(DecodedCert, issuerSNLen), + WC_OFFSETOF(DecodedCert, issuerSNEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13130,13 +14062,13 @@ static const CertNameData certNameSubject[] = { { "/serialNumber=", 14, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectSND), - OFFSETOF(DecodedCert, subjectSNDLen), - OFFSETOF(DecodedCert, subjectSNDEnc), + WC_OFFSETOF(DecodedCert, subjectSND), + WC_OFFSETOF(DecodedCert, subjectSNDLen), + WC_OFFSETOF(DecodedCert, subjectSNDEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerSND), - OFFSETOF(DecodedCert, issuerSNDLen), - OFFSETOF(DecodedCert, issuerSNDEnc), + WC_OFFSETOF(DecodedCert, issuerSND), + WC_OFFSETOF(DecodedCert, issuerSNDLen), + WC_OFFSETOF(DecodedCert, issuerSNDEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13147,13 +14079,13 @@ static const CertNameData certNameSubject[] = { { "/C=", 3, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectC), - OFFSETOF(DecodedCert, subjectCLen), - OFFSETOF(DecodedCert, subjectCEnc), + WC_OFFSETOF(DecodedCert, subjectC), + WC_OFFSETOF(DecodedCert, subjectCLen), + WC_OFFSETOF(DecodedCert, subjectCEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerC), - OFFSETOF(DecodedCert, issuerCLen), - OFFSETOF(DecodedCert, issuerCEnc), + WC_OFFSETOF(DecodedCert, issuerC), + WC_OFFSETOF(DecodedCert, issuerCLen), + WC_OFFSETOF(DecodedCert, issuerCEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13164,13 +14096,13 @@ static const CertNameData certNameSubject[] = { { "/L=", 3, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectL), - OFFSETOF(DecodedCert, subjectLLen), - OFFSETOF(DecodedCert, subjectLEnc), + WC_OFFSETOF(DecodedCert, subjectL), + WC_OFFSETOF(DecodedCert, subjectLLen), + WC_OFFSETOF(DecodedCert, subjectLEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerL), - OFFSETOF(DecodedCert, issuerLLen), - OFFSETOF(DecodedCert, issuerLEnc), + WC_OFFSETOF(DecodedCert, issuerL), + WC_OFFSETOF(DecodedCert, issuerLLen), + WC_OFFSETOF(DecodedCert, issuerLEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13181,13 +14113,13 @@ static const CertNameData certNameSubject[] = { { "/ST=", 4, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectST), - OFFSETOF(DecodedCert, subjectSTLen), - OFFSETOF(DecodedCert, subjectSTEnc), + WC_OFFSETOF(DecodedCert, subjectST), + WC_OFFSETOF(DecodedCert, subjectSTLen), + WC_OFFSETOF(DecodedCert, subjectSTEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerST), - OFFSETOF(DecodedCert, issuerSTLen), - OFFSETOF(DecodedCert, issuerSTEnc), + WC_OFFSETOF(DecodedCert, issuerST), + WC_OFFSETOF(DecodedCert, issuerSTLen), + WC_OFFSETOF(DecodedCert, issuerSTEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13198,9 +14130,9 @@ static const CertNameData certNameSubject[] = { { "/street=", 8, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectStreet), - OFFSETOF(DecodedCert, subjectStreetLen), - OFFSETOF(DecodedCert, subjectStreetEnc), + WC_OFFSETOF(DecodedCert, subjectStreet), + WC_OFFSETOF(DecodedCert, subjectStreetLen), + WC_OFFSETOF(DecodedCert, subjectStreetEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13215,13 +14147,13 @@ static const CertNameData certNameSubject[] = { { "/O=", 3, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectO), - OFFSETOF(DecodedCert, subjectOLen), - OFFSETOF(DecodedCert, subjectOEnc), + WC_OFFSETOF(DecodedCert, subjectO), + WC_OFFSETOF(DecodedCert, subjectOLen), + WC_OFFSETOF(DecodedCert, subjectOEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerO), - OFFSETOF(DecodedCert, issuerOLen), - OFFSETOF(DecodedCert, issuerOEnc), + WC_OFFSETOF(DecodedCert, issuerO), + WC_OFFSETOF(DecodedCert, issuerOLen), + WC_OFFSETOF(DecodedCert, issuerOEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13232,13 +14164,13 @@ static const CertNameData certNameSubject[] = { { "/OU=", 4, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectOU), - OFFSETOF(DecodedCert, subjectOULen), - OFFSETOF(DecodedCert, subjectOUEnc), + WC_OFFSETOF(DecodedCert, subjectOU), + WC_OFFSETOF(DecodedCert, subjectOULen), + WC_OFFSETOF(DecodedCert, subjectOUEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES - OFFSETOF(DecodedCert, issuerOU), - OFFSETOF(DecodedCert, issuerOULen), - OFFSETOF(DecodedCert, issuerOUEnc), + WC_OFFSETOF(DecodedCert, issuerOU), + WC_OFFSETOF(DecodedCert, issuerOULen), + WC_OFFSETOF(DecodedCert, issuerOUEnc), #endif #endif #ifdef WOLFSSL_X509_NAME_AVAILABLE @@ -13300,9 +14232,9 @@ static const CertNameData certNameSubject[] = { { "/businessCategory=", 18, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectBC), - OFFSETOF(DecodedCert, subjectBCLen), - OFFSETOF(DecodedCert, subjectBCEnc), + WC_OFFSETOF(DecodedCert, subjectBC), + WC_OFFSETOF(DecodedCert, subjectBCLen), + WC_OFFSETOF(DecodedCert, subjectBCEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13334,9 +14266,9 @@ static const CertNameData certNameSubject[] = { { "/postalCode=", 12, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectPC), - OFFSETOF(DecodedCert, subjectPCLen), - OFFSETOF(DecodedCert, subjectPCEnc), + WC_OFFSETOF(DecodedCert, subjectPC), + WC_OFFSETOF(DecodedCert, subjectPCLen), + WC_OFFSETOF(DecodedCert, subjectPCEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13351,9 +14283,9 @@ static const CertNameData certNameSubject[] = { { "/userid=", 8, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectUID), - OFFSETOF(DecodedCert, subjectUIDLen), - OFFSETOF(DecodedCert, subjectUIDEnc), + WC_OFFSETOF(DecodedCert, subjectUID), + WC_OFFSETOF(DecodedCert, subjectUIDLen), + WC_OFFSETOF(DecodedCert, subjectUIDEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13369,9 +14301,9 @@ static const CertNameData certNameSubject[] = { { "/N=", 3, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectN), - OFFSETOF(DecodedCert, subjectNLen), - OFFSETOF(DecodedCert, subjectNEnc), + WC_OFFSETOF(DecodedCert, subjectN), + WC_OFFSETOF(DecodedCert, subjectNLen), + WC_OFFSETOF(DecodedCert, subjectNEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13386,9 +14318,9 @@ static const CertNameData certNameSubject[] = { { "/GN=", 4, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectGN), - OFFSETOF(DecodedCert, subjectGNLen), - OFFSETOF(DecodedCert, subjectGNEnc), + WC_OFFSETOF(DecodedCert, subjectGN), + WC_OFFSETOF(DecodedCert, subjectGNLen), + WC_OFFSETOF(DecodedCert, subjectGNEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13403,9 +14335,9 @@ static const CertNameData certNameSubject[] = { { "/initials=", 10, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectI), - OFFSETOF(DecodedCert, subjectILen), - OFFSETOF(DecodedCert, subjectIEnc), + WC_OFFSETOF(DecodedCert, subjectI), + WC_OFFSETOF(DecodedCert, subjectILen), + WC_OFFSETOF(DecodedCert, subjectIEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -13420,9 +14352,9 @@ static const CertNameData certNameSubject[] = { { "/dnQualifier=", 13, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) - OFFSETOF(DecodedCert, subjectDNQ), - OFFSETOF(DecodedCert, subjectDNQLen), - OFFSETOF(DecodedCert, subjectDNQEnc), + WC_OFFSETOF(DecodedCert, subjectDNQ), + WC_OFFSETOF(DecodedCert, subjectDNQLen), + WC_OFFSETOF(DecodedCert, subjectDNQEnc), #ifdef WOLFSSL_HAVE_ISSUER_NAMES 0, 0, @@ -16265,7 +17197,8 @@ static WC_INLINE int IsSigAlgoECC(word32 algoOID) * @return Encoded data size on success. * @return 0 when dynamic memory allocation fails. */ -static word32 SetAlgoIDImpl(int algoOID, byte* output, int type, int curveSz, byte absentParams) +static word32 SetAlgoIDImpl(int algoOID, byte* output, int type, int curveSz, + byte absentParams) { #ifndef WOLFSSL_ASN_TEMPLATE word32 tagSz, idSz, seqSz, algoSz = 0; @@ -16395,7 +17328,8 @@ word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) return SetAlgoIDImpl(algoOID, output, type, curveSz, FALSE); } -word32 SetAlgoIDEx(int algoOID, byte* output, int type, int curveSz, byte absentParams) +word32 SetAlgoIDEx(int algoOID, byte* output, int type, int curveSz, + byte absentParams) { return SetAlgoIDImpl(algoOID, output, type, curveSz, absentParams); } @@ -16819,7 +17753,7 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */ /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */ -static int ConfirmSignature(SignatureCtx* sigCtx, +int ConfirmSignature(SignatureCtx* sigCtx, const byte* buf, word32 bufSz, const byte* key, word32 keySz, word32 keyOID, const byte* sig, word32 sigSz, word32 sigOID, @@ -17269,6 +18203,10 @@ static int ConfirmSignature(SignatureCtx* sigCtx, level = WC_ML_DSA_87_DRAFT; } #endif + else { + WOLFSSL_MSG("Invalid Dilithium key OID"); + goto exit_cs; + } sigCtx->verify = 0; sigCtx->key.dilithium = (dilithium_key*)XMALLOC( sizeof(dilithium_key), sigCtx->heap, @@ -17833,7 +18771,7 @@ static int ConfirmSignature(SignatureCtx* sigCtx, case DILITHIUM_LEVEL2k: case DILITHIUM_LEVEL3k: case DILITHIUM_LEVEL5k: - #endif + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ case ML_DSA_LEVEL2k: case ML_DSA_LEVEL3k: case ML_DSA_LEVEL5k: @@ -17947,41 +18885,6 @@ static int ConfirmSignature(SignatureCtx* sigCtx, return ret; } -#ifdef WOLFSSL_DUAL_ALG_CERTS -int wc_ConfirmAltSignature( - const byte* buf, word32 bufSz, - const byte* key, word32 keySz, word32 keyOID, - const byte* sig, word32 sigSz, word32 sigOID, - void *heap) -{ - int ret = 0; -#ifdef WOLFSSL_SMALL_STACK - SignatureCtx* sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, - DYNAMIC_TYPE_SIGNATURE); - if (sigCtx == NULL) { - ret = MEMORY_E; - } -#else - SignatureCtx sigCtx[1]; - (void)heap; -#endif - - if (ret == 0) { - InitSignatureCtx(sigCtx, heap, INVALID_DEVID); - - ret = ConfirmSignature(sigCtx, buf, bufSz, key, keySz, - keyOID, sig, sigSz, sigOID, NULL, 0, NULL); - - FreeSignatureCtx(sigCtx); - } - -#ifdef WOLFSSL_SMALL_STACK - XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE); -#endif - return ret; -} -#endif /* WOLFSSL_DUAL_ALG_CERTS */ - #ifndef IGNORE_NAME_CONSTRAINTS static int MatchBaseName(int type, const char* name, int nameSz, @@ -21254,11 +22157,12 @@ static int DecodeAltSigAlg(const byte* input, int sz, DecodedCert* cert) * like a traditional signature in the certificate. */ static int DecodeAltSigVal(const byte* input, int sz, DecodedCert* cert) { - (void)cert; int ret = 0; word32 idx = 0; int len = 0; + (void)cert; + WOLFSSL_ENTER("DecodeAltSigVal"); if (ret == 0) { @@ -21527,16 +22431,19 @@ static int DecodeExtensionType(const byte* input, word32 length, word32 oid, #ifdef WOLFSSL_DUAL_ALG_CERTS case SUBJ_ALT_PUB_KEY_INFO_OID: VERIFY_AND_SET_OID(cert->extSapkiSet); + cert->extSapkiCrit = critical ? 1 : 0; if (DecodeSubjAltPubKeyInfo(&input[idx], length, cert) < 0) return ASN_PARSE_E; break; case ALT_SIG_ALG_OID: VERIFY_AND_SET_OID(cert->extAltSigAlgSet); + cert->extAltSigAlgCrit = critical ? 1 : 0; if (DecodeAltSigAlg(&input[idx], length, cert) < 0) return ASN_PARSE_E; break; case ALT_SIG_VAL_OID: VERIFY_AND_SET_OID(cert->extAltSigValSet); + cert->extAltSigValCrit = critical ? 1 : 0; if (DecodeAltSigVal(&input[idx], length, cert) < 0) return ASN_PARSE_E; break; @@ -23666,6 +24573,19 @@ int wc_CertGetPubKey(const byte* cert, word32 certSz, return ret; } #endif +#ifdef HAVE_OCSP +Signer* findSignerByKeyHash(Signer *list, byte *hash) +{ + Signer *s; + for (s = list; s != NULL; s = s->next) { + if (XMEMCMP(s->subjectKeyHash, hash, KEYID_SIZE) == 0) { + return s; + } + } + return NULL; +} +#endif /* WOLFSSL_OCSP */ + Signer* findSignerByName(Signer *list, byte *hash) { Signer *s; @@ -23677,7 +24597,8 @@ Signer* findSignerByName(Signer *list, byte *hash) return NULL; } -int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, Signer *extraCAList) +int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, + Signer *extraCAList) { int ret = 0; #ifndef WOLFSSL_ASN_TEMPLATE @@ -24611,7 +25532,8 @@ int SetSerialNumber(const byte* sn, word32 snSz, byte* output, #endif /* !NO_CERTS */ #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \ - (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)) + (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)) || \ + (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) int SetMyVersion(word32 version, byte* output, int header) { int i = 0; @@ -24777,6 +25699,8 @@ wcchar END_CERT = "-----END CERTIFICATE-----"; #endif wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----"; wcchar END_X509_CRL = "-----END X509 CRL-----"; +wcchar BEGIN_TRUSTED_CERT = "-----BEGIN TRUSTED CERTIFICATE-----"; +wcchar END_TRUSTED_CERT = "-----END TRUSTED CERTIFICATE-----"; wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----"; wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----"; wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----"; @@ -25073,6 +25997,11 @@ int wc_PemGetHeaderFooter(int type, const char** header, const char** footer) if (footer) *footer = END_ENC_PRIV_KEY; ret = 0; break; + case TRUSTED_CERT_TYPE: + if (header) *header = BEGIN_TRUSTED_CERT; + if (footer) *footer = END_TRUSTED_CERT; + ret = 0; + break; default: ret = BAD_FUNC_ARG; break; @@ -25318,8 +26247,8 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE]; char footer[MAX_X509_HEADER_SZ]; #endif - int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE; - int footerLen = MAX_X509_HEADER_SZ; + size_t headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE; + size_t footerLen = MAX_X509_HEADER_SZ; int i; int err; int outLen; /* return length or error */ @@ -25346,9 +26275,9 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, #endif /* build header and footer based on type */ - XSTRNCPY(header, headerStr, (size_t)headerLen - 1); + XSTRNCPY(header, headerStr, headerLen - 1); header[headerLen - 2] = 0; - XSTRNCPY(footer, footerStr, (size_t)footerLen - 1); + XSTRNCPY(footer, footerStr, footerLen - 1); footer[footerLen - 2] = 0; /* add new line to end */ @@ -25356,7 +26285,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, XSTRNCAT(footer, "\n", 2); #ifdef WOLFSSL_ENCRYPTED_KEYS - err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info); + err = wc_EncryptedInfoAppend(header, (int)headerLen, (char*)cipher_info); if (err != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -25366,8 +26295,8 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, } #endif - headerLen = (int)XSTRLEN(header); - footerLen = (int)XSTRLEN(footer); + headerLen = XSTRLEN(header); + footerLen = XSTRLEN(footer); /* if null output and 0 size passed in then return size needed */ if (!output && outSz == 0) { @@ -25381,7 +26310,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, WOLFSSL_ERROR_VERBOSE(err); return err; } - return headerLen + footerLen + outLen; + return (int)headerLen + (int)footerLen + outLen; } if (!der || !output) { @@ -25403,14 +26332,14 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, /* header */ XMEMCPY(output, header, (size_t)headerLen); - i = headerLen; + i = (int)headerLen; #ifdef WOLFSSL_SMALL_STACK XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif /* body */ - outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */ + outLen = (int)outSz - (int)(headerLen + footerLen); /* input to Base64_Encode */ if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -25421,7 +26350,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, i += outLen; /* footer */ - if ( (i + footerLen) > (int)outSz) { + if ( (i + (int)footerLen) > (int)outSz) { #ifdef WOLFSSL_SMALL_STACK XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -25433,7 +26362,7 @@ int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz, XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif - return outLen + headerLen + footerLen; + return outLen + (int)headerLen + (int)footerLen; } #endif /* WOLFSSL_DER_TO_PEM */ @@ -25709,10 +26638,27 @@ int PemToDer(const unsigned char* buff, long longSz, int type, } der = *pDer; - if (Base64_Decode((byte*)headerEnd, (word32)neededSz, - der->buffer, &der->length) < 0) { - WOLFSSL_ERROR(BUFFER_E); - return BUFFER_E; + switch (type) { + case PUBLICKEY_TYPE: + case ECC_PUBLICKEY_TYPE: + case RSA_PUBLICKEY_TYPE: + case CERT_TYPE: + case TRUSTED_CERT_TYPE: + case CRL_TYPE: + if (Base64_Decode_nonCT((byte*)headerEnd, (word32)neededSz, + der->buffer, &der->length) < 0) + { + WOLFSSL_ERROR(BUFFER_E); + return BUFFER_E; + } + break; + default: + if (Base64_Decode((byte*)headerEnd, (word32)neededSz, + der->buffer, &der->length) < 0) { + WOLFSSL_ERROR(BUFFER_E); + return BUFFER_E; + } + break; } if ((header == BEGIN_PRIV_KEY @@ -25754,7 +26700,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, } #ifdef WOLFSSL_SMALL_STACK - password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING); + password = (char*)XMALLOC((size_t)passwordSz, heap, DYNAMIC_TYPE_STRING); if (password == NULL) { return MEMORY_E; } @@ -28804,6 +29750,13 @@ int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap) ret = 0; } + if (items == 0) { + /* if zero items, short-circuit return to avoid frivolous zero-size + * allocations. + */ + return 0; + } + /* Allocate dynamic data items. */ dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -28972,6 +29925,7 @@ static const ASNItem static_certExtsASN[] = { /* Basic Constraints Extension - 4.2.1.9 */ /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 }, +/* BC_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 }, /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 }, /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, /* cA */ @@ -29020,12 +29974,15 @@ static const ASNItem static_certExtsASN[] = { #ifdef WOLFSSL_DUAL_ALG_CERTS /* SAPKI_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* SAPKI_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 }, +/* SAPKI_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 }, /* SAPKI_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 }, /* ALTSIGALG_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* ALTSIGALG_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALTSIGALG_CRIT*/ { 1, ASN_BOOLEAN, 0, 0, 0 }, /* ALTSIGALG_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 }, /* ALTSIGVAL_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* ALTSIGVAL_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALTSIGVAL_CRIT*/ { 1, ASN_BOOLEAN, 0, 0, 0 }, /* ALTSIGVAL_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 }, #endif /* WOLFSSL_DUAL_ALG_CERTS */ /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, @@ -29035,6 +29992,7 @@ static const ASNItem static_certExtsASN[] = { enum { CERTEXTSASN_IDX_BC_SEQ = 0, CERTEXTSASN_IDX_BC_OID, + CERTEXTSASN_IDX_BC_CRIT, CERTEXTSASN_IDX_BC_STR, CERTEXTSASN_IDX_BC_STR_SEQ, CERTEXTSASN_IDX_BC_CA, @@ -29074,12 +30032,15 @@ enum { #ifdef WOLFSSL_DUAL_ALG_CERTS CERTEXTSASN_IDX_SAPKI_SEQ, CERTEXTSASN_IDX_SAPKI_OID, + CERTEXTSASN_IDX_SAPKI_CRIT, CERTEXTSASN_IDX_SAPKI_STR, CERTEXTSASN_IDX_ALTSIGALG_SEQ, CERTEXTSASN_IDX_ALTSIGALG_OID, + CERTEXTSASN_IDX_ALTSIGALG_CRIT, CERTEXTSASN_IDX_ALTSIGALG_STR, CERTEXTSASN_IDX_ALTSIGVAL_SEQ, CERTEXTSASN_IDX_ALTSIGVAL_OID, + CERTEXTSASN_IDX_ALTSIGVAL_CRIT, CERTEXTSASN_IDX_ALTSIGVAL_STR, #endif /* WOLFSSL_DUAL_ALG_CERTS */ CERTEXTSASN_IDX_CUSTOM_SEQ, @@ -29171,6 +30132,12 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, /* Set Basic Constraints to be a Certificate Authority. */ SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1); SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID)); + if (cert->basicConstCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_BC_CRIT].noOut = 1; + } if (cert->pathLenSet #ifdef WOLFSSL_CERT_EXT && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage)) @@ -29187,12 +30154,24 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, else if (cert->isCaSet) { SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 0); SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID)); + if (cert->basicConstCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_BC_CRIT].noOut = 1; + } dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1; } #endif else if (cert->basicConstSet) { /* Set Basic Constraints to be a non Certificate Authority. */ SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID)); + if (cert->basicConstCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_BC_CRIT].noOut = 1; + } dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1; dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1; } @@ -29359,9 +30338,16 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, #ifdef WOLFSSL_DUAL_ALG_CERTS if (cert->sapkiDer != NULL) { - /* Set subject alternative public key info OID and data. */ + /* Set subject alternative public key info OID, criticality and + * data. */ SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAPKI_OID], sapkiOID, sizeof(sapkiOID)); + if (cert->sapkiCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAPKI_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_SAPKI_CRIT].noOut = 1; + } SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAPKI_STR], cert->sapkiDer, cert->sapkiLen); } @@ -29372,9 +30358,15 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, } if (cert->altSigAlgDer != NULL) { - /* Set alternative signature algorithm OID and data. */ + /* Set alternative signature algorithm OID, criticality and data. */ SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGALG_OID], altSigAlgOID, sizeof(altSigAlgOID)); + if (cert->altSigAlgCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_ALTSIGALG_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_ALTSIGALG_CRIT].noOut = 1; + } SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGALG_STR], cert->altSigAlgDer, cert->altSigAlgLen); } @@ -29385,9 +30377,15 @@ static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz, } if (cert->altSigValDer != NULL) { - /* Set alternative signature value OID and data. */ + /* Set alternative signature value OID, criticality and data. */ SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGVAL_OID], altSigValOID, sizeof(altSigValOID)); + if (cert->altSigValCrit) { + SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_ALTSIGVAL_CRIT], 1); + } + else { + dataASN[CERTEXTSASN_IDX_ALTSIGVAL_CRIT].noOut = 1; + } SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGVAL_STR], cert->altSigValDer, cert->altSigValLen); } @@ -30976,8 +31974,18 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, #endif } - -/* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */ +/* Make an x509 Certificate v3 from cert input using any + * key type, and write to buffer. + * + * @param [in, out] cert Certificate object. + * @param [out] derBuffer Buffer to write der in. + * @param [in] derSz Der buffer size. + * @param [in] keyType The type of key. + * @param [in] key Key data. + * @param [in] rng Random number generator. + * @return Size of encoded data in bytes on success. + * @return < 0 on error + * */ int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType, void* key, WC_RNG* rng) { @@ -32145,6 +33153,21 @@ static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz, } #ifdef WOLFSSL_DUAL_ALG_CERTS +/* Generate a signature from input buffer using + * any key type. + * + * @param [out] sig The signature buffer to write in. + * @param [out] sigsz The signature buffer size. + * @param [in] sType The signature type. + * @param [in] buf The input buf to sign. + * @param [in] bufSz The buffer size + * @param [in] keyType The key type. + * @param [in] key Key data. + * @param [in] rng Random number generator. + * + * @return Size of signature on success. + * @return < 0 on error. + * */ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, word32 bufSz, int keyType, void* key, WC_RNG* rng) { @@ -32155,13 +33178,14 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, falcon_key* falconKey = NULL; dilithium_key* dilithiumKey = NULL; sphincs_key* sphincsKey = NULL; - int ret = 0; int headerSz; void* heap = NULL; CertSignCtx certSignCtx_lcl; CertSignCtx* certSignCtx = &certSignCtx_lcl; + WOLFSSL_ENTER("wc_MakeSigWithBitStr"); + if ((sig == NULL) || (sigSz <= 0)) { return BAD_FUNC_ARG; } @@ -32271,6 +33295,20 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, } #endif /* WOLFSSL_DUAL_ALG_CERTS */ +/* Sign an x509 Certificate v3 from cert input using any + * key type, and write to buffer. + * + * @param [in] requestSz Size of requested data to sign. + * @param [in] sType The signature type. + * @param [in,out] buf Der buffer to sign. + * @param [in] buffSz Der buffer size. + * @param [in] keyType The type of key. + * @param [in] key Key data. + * @param [in] rng Random number generator. + * + * @return Size of signature on success. + * @return < 0 on error + * */ int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz, int keyType, void* key, WC_RNG* rng) { @@ -33779,8 +34817,14 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, ret = GetASNInt(sig, &idx, &len, sigLen); if (ret != 0) return ret; - if (rLen) - *rLen = (word32)len; + if (rLen) { + if (*rLen >= (word32)len) + *rLen = (word32)len; + else { + /* Buffer too small to hold r value */ + return BUFFER_E; + } + } if (r) XMEMCPY(r, (byte*)sig + idx, (size_t)len); idx += (word32)len; @@ -33788,8 +34832,14 @@ int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen, ret = GetASNInt(sig, &idx, &len, sigLen); if (ret != 0) return ret; - if (sLen) - *sLen = (word32)len; + if (sLen) { + if (*sLen >= (word32)len) + *sLen = (word32)len; + else { + /* Buffer too small to hold s value */ + return BUFFER_E; + } + } if (s) XMEMCPY(s, (byte*)sig + idx, (size_t)len); @@ -34171,23 +35221,26 @@ static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz, } #endif /* WOLFSSL_ECC_CURVE_STATIC */ + if ((ret == 0) && (curveSz)) { + *curveSz = curve->size; + } + if (key) { /* Store parameter set in key. */ - if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) { - ret = ASN_PARSE_E; - } if (ret == 0) { - /* The parameter set was allocated.. */ - key->deallocSet = 1; + if (wc_ecc_set_custom_curve(key, curve) < 0) { + ret = ASN_PARSE_E; + } + else { + /* The parameter set was allocated.. */ + key->deallocSet = 1; + /* Don't deallocate below. */ + curve = NULL; + } } } - if ((ret == 0) && (curveSz)) { - *curveSz = curve->size; - } - - if ((ret != 0) && (curve != NULL)) { - /* Failed to set parameters so free parameter set. */ + if (curve != NULL) { /* NOLINT(clang-analyzer-unix.Malloc) */ wc_ecc_free_curve(curve, heap); } @@ -34343,7 +35396,8 @@ int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key, ret = BUFFER_E; else { #ifdef WOLFSSL_SMALL_STACK - pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + pub = (byte*)XMALLOC(pubSz, key->heap, + DYNAMIC_TYPE_TMP_BUFFER); if (pub == NULL) ret = MEMORY_E; else @@ -35718,6 +36772,9 @@ int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx, return BAD_FUNC_ARG; } + /* init pubKey */ + XMEMSET(pubKey, 0, sizeof(pubKey)); + ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, pubKey, &pubKeyLen, ED25519k); if (ret == 0) { @@ -35758,6 +36815,9 @@ int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx, return BAD_FUNC_ARG; } + /* init pubKey */ + XMEMSET(pubKey, 0, sizeof(pubKey)); + ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, pubKey, &pubKeyLen, X25519k); if (ret == 0) { @@ -35983,7 +37043,8 @@ int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen) #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT) /* Write only private Curve25519 key to DER format, * length on success else < 0 */ -int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen) +int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, + word32 inLen) { int ret; byte privKey[CURVE25519_KEYSIZE]; @@ -36025,7 +37086,8 @@ int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen, /* Export Curve25519 key to DER format - handles private only, public only, * or private+public key pairs based on what's set in the key structure. * Returns length written on success, negative on error */ -int wc_Curve25519KeyToDer(curve25519_key* key, byte* output, word32 inLen, int withAlg) +int wc_Curve25519KeyToDer(curve25519_key* key, byte* output, word32 inLen, + int withAlg) { int ret; byte privKey[CURVE25519_KEYSIZE]; @@ -36158,6 +37220,9 @@ int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx, return BAD_FUNC_ARG; } + /* init pubKey */ + XMEMSET(pubKey, 0, sizeof(pubKey)); + ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, pubKey, &pubKeyLen, X448k); if (ret == 0) { @@ -36305,17 +37370,7 @@ static int GetEnumerated(const byte* input, word32* inOutIdx, int *value, static const ASNItem singleResponseASN[] = { /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, /* certId */ -/* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, - /* hashAlgorithm */ -/* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, -/* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 }, -/* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 }, - /* issuerNameHash */ -/* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 }, - /* issuerKeyHash */ -/* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 }, - /* serialNumber */ -/* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 }, +/* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 }, /* certStatus - CHOICE */ /* good [0] IMPLICIT NULL */ /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 }, @@ -36341,12 +37396,6 @@ static const ASNItem singleResponseASN[] = { enum { SINGLERESPONSEASN_IDX_SEQ = 0, SINGLERESPONSEASN_IDX_CID_SEQ, - SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ, - SINGLERESPONSEASN_IDX_CID_HASHALGO_OID, - SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL, - SINGLERESPONSEASN_IDX_CID_ISSUERHASH, - SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH, - SINGLERESPONSEASN_IDX_CID_SERIAL, SINGLERESPONSEASN_IDX_CS_GOOD, SINGLERESPONSEASN_IDX_CS_REVOKED, SINGLERESPONSEASN_IDX_CS_REVOKED_TIME, @@ -36361,13 +37410,139 @@ enum { /* Number of items in ASN.1 template for OCSP single response. */ #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem)) + +static const ASNItem certIDASNItems[] = { + /* hashAlgorithm */ +/* CID_HASHALGO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, +/* CID_HASHALGO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 }, +/* CID_HASHALGO_NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 }, + /* issuerNameHash */ +/* CID_ISSUERHASH */ { 0, ASN_OCTET_STRING, 0, 0, 0 }, + /* issuerKeyHash */ +/* CID_ISSUERKEYHASH */ { 0, ASN_OCTET_STRING, 0, 0, 0 }, + /* serialNumber */ +/* CID_SERIAL */ { 0, ASN_INTEGER, 0, 0, 0 }, +}; + +enum { + CERTIDASN_IDX_CID_HASHALGO_SEQ, + CERTIDASN_IDX_CID_HASHALGO_OID, + CERTIDASN_IDX_CID_HASHALGO_NULL, + CERTIDASN_IDX_CID_ISSUERHASH, + CERTIDASN_IDX_CID_ISSUERKEYHASH, + CERTIDASN_IDX_CID_SERIAL, +}; + +#define certidasn_Length (sizeof(certIDASNItems) / sizeof(ASNItem)) +#endif + +#ifndef WOLFSSL_ASN_TEMPLATE +static int OcspDecodeCertIDInt(const byte* input, word32* inOutIdx, word32 inSz, + OcspEntry* entry) +{ + int length; + word32 oid; + int ret; + /* Hash algorithm */ + ret = GetAlgoId(input, inOutIdx, &oid, oidHashType, inSz); + if (ret < 0) + return ret; + entry->hashAlgoOID = oid; + /* Save reference to the hash of CN */ + ret = GetOctetString(input, inOutIdx, &length, inSz); + if (ret < 0) + return ret; + if (length != OCSP_DIGEST_SIZE) + return ASN_PARSE_E; + XMEMCPY(entry->issuerHash, input + *inOutIdx, length); + *inOutIdx += length; + /* Save reference to the hash of the issuer public key */ + ret = GetOctetString(input, inOutIdx, &length, inSz); + if (ret < 0) + return ret; + if (length != OCSP_DIGEST_SIZE) + return ASN_PARSE_E; + XMEMCPY(entry->issuerKeyHash, input + *inOutIdx, length); + *inOutIdx += length; + + /* Get serial number */ + if (wc_GetSerialNumber(input, inOutIdx, entry->status->serial, + &entry->status->serialSz, inSz) < 0) + return ASN_PARSE_E; + return 0; +} +#else +static int OcspDecodeCertIDInt(const byte* input, word32* inOutIdx, word32 inSz, + OcspEntry* entry) +{ + DECL_ASNGETDATA(dataASN, certidasn_Length); + word32 issuerKeyHashLen = OCSP_DIGEST_SIZE; + word32 issuerHashLen = OCSP_DIGEST_SIZE; + word32 serialSz = EXTERNAL_SERIAL_SIZE; + word32 digestSz; + int ret = 0; + + WOLFSSL_ENTER("DecodeCertIdTemplate"); + CALLOC_ASNGETDATA(dataASN, certidasn_Length, ret, NULL); + if (ret != 0) + return ret; + + GetASN_OID(&dataASN[CERTIDASN_IDX_CID_HASHALGO_OID], oidHashType); + GetASN_Buffer(&dataASN[CERTIDASN_IDX_CID_ISSUERHASH], entry->issuerHash, + &issuerHashLen); + GetASN_Buffer(&dataASN[CERTIDASN_IDX_CID_ISSUERKEYHASH], + entry->issuerKeyHash, &issuerKeyHashLen); + GetASN_Buffer(&dataASN[CERTIDASN_IDX_CID_SERIAL], entry->status->serial, + &serialSz); + ret = GetASN_Items(certIDASNItems, dataASN, certidasn_Length, + 1, input, inOutIdx, inSz); + if (ret != 0) { + goto out; + } + entry->status->serialSz = serialSz; + entry->hashAlgoOID = + dataASN[CERTIDASN_IDX_CID_HASHALGO_OID].data.oid.sum; + digestSz = wc_HashGetDigestSize(wc_OidGetHash(entry->hashAlgoOID)); + if (issuerKeyHashLen != digestSz || issuerHashLen != digestSz) { + ret = ASN_PARSE_E; + goto out; + } +out: + FREE_ASNGETDATA(dataASN, NULL); + return ret; +} #endif +int OcspDecodeCertID(const byte *input, word32 *inOutIdx, word32 inSz, + OcspEntry *entry) +{ + word32 seqIdx = 0; + int len = inSz; + int ret; + +#ifndef WOLFSSL_ASN_TEMPLATE + ret = GetSequence(input, inOutIdx, &len, inSz); +#else + ret = GetASN_Sequence(input, inOutIdx, &len, inSz, 0); +#endif + if (ret < 0) + return ASN_PARSE_E; + ret = OcspDecodeCertIDInt(input + *inOutIdx, &seqIdx, len, entry); + if (ret < 0) + return ASN_PARSE_E; + if (seqIdx != (word32)len) + return ASN_PARSE_E; + *inOutIdx += len; + + return 0; +} + + static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, int wrapperSz, OcspEntry* single) { #ifndef WOLFSSL_ASN_TEMPLATE - word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx; + word32 idx = *ioIndex, prevIndex, localIdx, certIdIdx; int length; int ret; byte tag; @@ -36385,31 +37560,8 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, if (GetSequence(source, &idx, &length, size) < 0) return ASN_PARSE_E; single->rawCertId = source + certIdIdx; - /* Hash algorithm */ - ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size); - if (ret < 0) - return ret; - single->hashAlgoOID = oid; - /* Save reference to the hash of CN */ - ret = GetOctetString(source, &idx, &length, size); - if (ret < 0) - return ret; - if (length > (int)sizeof(single->issuerHash)) - return BUFFER_E; - XMEMCPY(single->issuerHash, source + idx, length); - idx += length; - /* Save reference to the hash of the issuer public key */ - ret = GetOctetString(source, &idx, &length, size); + ret = OcspDecodeCertIDInt(source, &idx, size, single); if (ret < 0) - return ret; - if (length > (int)sizeof(single->issuerKeyHash)) - return BUFFER_E; - XMEMCPY(single->issuerKeyHash, source + idx, length); - idx += length; - - /* Get serial number */ - if (wc_GetSerialNumber(source, &idx, single->status->serial, - &single->status->serialSz, size) < 0) return ASN_PARSE_E; single->rawCertIdSize = idx - certIdIdx; @@ -36456,12 +37608,13 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, single->status->thisDateParsed.length); #endif if (GetBasicDate(source, &idx, single->status->thisDate, - &single->status->thisDateFormat, size) < 0) + &single->status->thisDateFormat, size) < 0) return ASN_PARSE_E; #ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK - if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, ASN_BEFORE)) + if (!XVALIDATE_DATE(single->status->thisDate, + single->status->thisDateFormat, ASN_BEFORE)) return ASN_BEFORE_DATE_E; #endif #endif @@ -36492,7 +37645,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, single->status->nextDateParsed.length); #endif if (GetBasicDate(source, &idx, single->status->nextDate, - &single->status->nextDateFormat, size) < 0) + &single->status->nextDateFormat, size) < 0) return ASN_PARSE_E; #ifndef NO_ASN_TIME_CHECK @@ -36521,13 +37674,10 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, #else /* WOLFSSL_ASN_TEMPLATE */ DECL_ASNGETDATA(dataASN, singleResponseASN_Length); int ret = 0; - word32 ocspDigestSize = OCSP_DIGEST_SIZE; CertStatus* cs = NULL; - word32 serialSz; - word32 issuerHashLen; - word32 issuerKeyHashLen; word32 thisDateLen; word32 nextDateLen; + word32 certIdSeqIdx; (void)wrapperSz; @@ -36536,25 +37686,12 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL); if (ret == 0) { - /* Certificate Status field. */ cs = single->status; - /* Set maximum lengths for data. */ - issuerHashLen = OCSP_DIGEST_SIZE; - issuerKeyHashLen = OCSP_DIGEST_SIZE; - serialSz = EXTERNAL_SERIAL_SIZE; thisDateLen = MAX_DATE_SIZE; nextDateLen = MAX_DATE_SIZE; /* Set OID type, buffers to hold data and variables to hold size. */ - GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID], - oidHashType); - GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH], - single->issuerHash, &issuerHashLen); - GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH], - single->issuerKeyHash, &issuerKeyHashLen); - GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial, - &serialSz); GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], cs->thisDate, &thisDateLen); GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], @@ -36565,27 +37702,11 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, 1, source, ioIndex, size); } if (ret == 0) { - single->hashAlgoOID = - dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum; - ocspDigestSize = (word32)wc_HashGetDigestSize( - wc_OidGetHash((int)single->hashAlgoOID)); - } - /* Validate the issuer hash length is the size required. */ - if ((ret == 0) && (issuerHashLen != ocspDigestSize)) { - ret = ASN_PARSE_E; - } - /* Validate the issuer key hash length is the size required. */ - if (ret == 0) { - if (issuerKeyHashLen != ocspDigestSize) { - ret = ASN_PARSE_E; - } + certIdSeqIdx = 0; + ret = OcspDecodeCertIDInt(dataASN[SINGLERESPONSEASN_IDX_CID_SEQ].data.ref.data, + &certIdSeqIdx, dataASN[SINGLERESPONSEASN_IDX_CID_SEQ].data.ref.length, single); } if (ret == 0) { - /* Store serial size. */ - cs->serialSz = (int)serialSz; - /* Set the hash algorithm OID */ - single->hashAlgoOID = - dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum; /* Determine status by which item was found. */ if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) { @@ -36821,7 +37942,8 @@ static const ASNItem ocspRespDataASN[] = { /* byName */ /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 }, /* byKey */ -/* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 }, +/* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 1, 2 }, +/* BYKEY_OCT */ { 2, ASN_OCTET_STRING, 0, 0, 0 }, /* producedAt */ /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, }, /* responses */ @@ -36835,6 +37957,7 @@ enum { OCSPRESPDATAASN_IDX_VER, OCSPRESPDATAASN_IDX_BYNAME, OCSPRESPDATAASN_IDX_BYKEY, + OCSPRESPDATAASN_IDX_BYKEY_OCT, OCSPRESPDATAASN_IDX_PA, OCSPRESPDATAASN_IDX_RESP, OCSPRESPDATAASN_IDX_RESPEXT, @@ -36879,16 +38002,40 @@ static int DecodeResponseData(byte* source, word32* ioIndex, version = 0; localIdx = idx; - if (GetASNTag(source, &localIdx, &tag, size) == 0 && - ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) || - tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) )) + if (GetASNTag(source, &localIdx, &tag, size) != 0) + return ASN_PARSE_E; + + resp->responderIdType = OCSP_RESPONDER_ID_INVALID; + /* parse byName */ + if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) { idx++; /* advance past ASN tag */ if (GetLength(source, &idx, &length, size) < 0) return ASN_PARSE_E; + /* compute the hash of the name */ + resp->responderIdType = OCSP_RESPONDER_ID_NAME; + ret = CalcHashId_ex(source + idx, length, + resp->responderId.nameHash, OCSP_RESPONDER_ID_HASH_TYPE); + if (ret != 0) + return ret; idx += length; } - else + else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) + { + idx++; /* advance past ASN tag */ + if (GetLength(source, &idx, &length, size) < 0) + return ASN_PARSE_E; + + if (GetOctetString(source, &idx, &length, size) < 0) + return ASN_PARSE_E; + + if (length != OCSP_RESPONDER_ID_KEY_SZ) + return ASN_PARSE_E; + resp->responderIdType = OCSP_RESPONDER_ID_KEY; + XMEMCPY(resp->responderId.keyHash, source + idx, length); + idx += length; + } + if (resp->responderIdType == OCSP_RESPONDER_ID_INVALID) return ASN_PARSE_E; /* save pointer to the producedAt time */ @@ -36924,6 +38071,7 @@ static int DecodeResponseData(byte* source, word32* ioIndex, XMEMSET(single->next->status, 0, sizeof(CertStatus)); single->next->isDynamic = 1; + single->next->ownStatus = 1; single = single->next; } @@ -36944,6 +38092,7 @@ static int DecodeResponseData(byte* source, word32* ioIndex, int ret = 0; byte version; word32 dateSz = 0; + word32 responderByKeySz = OCSP_RESPONDER_ID_KEY_SZ; word32 idx = *ioIndex; OcspEntry* single = NULL; @@ -36962,6 +38111,8 @@ static int DecodeResponseData(byte* source, word32* ioIndex, GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version); GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate, &dateSz); + GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_BYKEY_OCT], + resp->responderId.keyHash, &responderByKeySz); /* Decode the ResponseData. */ ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length, 1, source, ioIndex, size); @@ -36979,7 +38130,23 @@ static int DecodeResponseData(byte* source, word32* ioIndex, } } if (ret == 0) { - /* TODO: use byName/byKey fields. */ + if (dataASN[OCSPRESPDATAASN_IDX_BYNAME].tag != 0) { + resp->responderIdType = OCSP_RESPONDER_ID_NAME; + ret = CalcHashId_ex( + dataASN[OCSPRESPDATAASN_IDX_BYNAME].data.ref.data, + dataASN[OCSPRESPDATAASN_IDX_BYNAME].data.ref.length, + resp->responderId.nameHash, OCSP_RESPONDER_ID_HASH_TYPE); + } else { + resp->responderIdType = OCSP_RESPONDER_ID_KEY; + if (dataASN[OCSPRESPDATAASN_IDX_BYKEY_OCT].length + != OCSP_RESPONDER_ID_KEY_SZ) { + ret = ASN_PARSE_E; + } else { + resp->responderIdType = OCSP_RESPONDER_ID_KEY; + } + } + } + if (ret == 0) { /* Store size of response. */ resp->responseSz = *ioIndex - idx; /* Store date format/tag. */ @@ -37013,6 +38180,7 @@ static int DecodeResponseData(byte* source, word32* ioIndex, /* Entry to be freed. */ single->next->isDynamic = 1; + single->next->ownStatus = 1; /* used will be 0 (false) */ single = single->next; @@ -37121,8 +38289,139 @@ enum { #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem)) #endif /* WOLFSSL_ASN_TEMPLATE */ +static int OcspRespIdMatch(OcspResponse *resp, const byte *NameHash, + const byte *keyHash) +{ + if (resp->responderIdType == OCSP_RESPONDER_ID_INVALID) + return 0; + if (resp->responderIdType == OCSP_RESPONDER_ID_NAME) + return XMEMCMP(NameHash, resp->responderId.nameHash, + SIGNER_DIGEST_SIZE) == 0; + /* OCSP_RESPONDER_ID_KEY */ + return ((int)KEYID_SIZE == OCSP_RESPONDER_ID_KEY_SZ) && + XMEMCMP(keyHash, resp->responderId.keyHash, KEYID_SIZE) == 0; +} + +#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK +static int OcspRespCheck(OcspResponse *resp, Signer *responder) +{ + OcspEntry *s; + + s = resp->single; + if (s == NULL) + return -1; + + /* singles responses must have the same issuer */ + for (; s != NULL; s = s->next) { + if (XMEMCMP(s->issuerKeyHash, responder->subjectKeyHash, + KEYID_SIZE) != 0) + return -1; + } + + return 0; +} +#endif + +static Signer *OcspFindSigner(OcspResponse *resp, WOLFSSL_CERT_MANAGER *cm) +{ + Signer *s; + + if (cm == NULL) + return NULL; + + if (resp->responderIdType == OCSP_RESPONDER_ID_NAME) { +#ifndef NO_SKID + s = GetCAByName(cm, resp->responderId.nameHash); +#else + s = GetCA(cm, resp->responderId.nameHash); +#endif + if (s) + return s; + } + else if ((int)KEYID_SIZE == OCSP_RESPONDER_ID_KEY_SZ) { + s = GetCAByKeyHash(cm, resp->responderId.keyHash); + if (s) + return s; + } +#if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) + if (resp->pendingCAs == NULL) + return NULL; + + if (resp->responderIdType == OCSP_RESPONDER_ID_NAME) { + s = findSignerByName(resp->pendingCAs, resp->responderId.nameHash); + if (s) + return s; + } + else { + s = findSignerByKeyHash(resp->pendingCAs, resp->responderId.keyHash); + if (s) + return s; + } +#endif + return NULL; +} + +static int OcspCheckCert(OcspResponse *resp, int noVerify, + int noVerifySignature, WOLFSSL_CERT_MANAGER *cm, void *heap) +{ + int ret = 0; +#ifdef WOLFSSL_SMALL_STACK + DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (cert == NULL) + return MEMORY_E; +#else + DecodedCert cert[1]; +#endif + + InitDecodedCert(cert, resp->cert, resp->certSz, heap); + ret = ParseCertRelative(cert, CERT_TYPE, + noVerify ? NO_VERIFY : VERIFY_OCSP_CERT, + cm, resp->pendingCAs); + if (ret < 0) { + WOLFSSL_MSG("\tOCSP Responder certificate parsing failed"); + } + + if (ret == 0 && + OcspRespIdMatch(resp, + cert->subjectHash, cert->subjectKeyHash) == 0) { + WOLFSSL_MSG("\tInternal check doesn't match responder ID, ignoring\n"); + ret = BAD_OCSP_RESPONDER; + goto err; + } + +#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK + if (ret == 0 && !noVerify) { + ret = CheckOcspResponder(resp, cert, cm); + if (ret != 0) { + WOLFSSL_MSG("\tOCSP Responder certificate issuer check failed"); + goto err; + } + } +#endif /* WOLFSSL_NO_OCSP_ISSUER_CHECK */ + if (ret == 0 && !noVerifySignature) { + ret = ConfirmSignature( + &cert->sigCtx, + resp->response, resp->responseSz, + cert->publicKey, cert->pubKeySize, cert->keyOID, + resp->sig, resp->sigSz, resp->sigOID, resp->sigParams, + resp->sigParamsSz, NULL); + } +err: + FreeDecodedCert(cert); + +#ifdef WOLFSSL_SMALL_STACK + if (cert != NULL) { + XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif + + return ret; +} + static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, - OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify) + OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify, + int noVerifySignature) { #ifndef WOLFSSL_ASN_TEMPLATE int length; @@ -37132,8 +38431,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, #endif int ret; int sigLength; - const byte* sigParams = NULL; - word32 sigParamsSz = 0; + int sigValid = 0; WOLFSSL_ENTER("DecodeBasicOcspResponse"); (void)heap; @@ -37157,16 +38455,16 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, else if (resp->sigOID == CTC_RSASSAPSS) { word32 sz; int len; - const byte* params; + byte* params; sz = idx; params = source + idx; if (GetSequence(source, &idx, &len, size) < 0) - ret = ASN_PARSE_E; + return ASN_PARSE_E; if (ret == 0) { idx += len; - sigParams = params; - sigParamsSz = idx - sz; + resp->sigParams = params; + resp->sigParamsSz = idx - sz; } } #endif @@ -37186,107 +38484,44 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS if (idx < end_index) { - int cert_inited = 0; -#ifdef WOLFSSL_SMALL_STACK - DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL, - DYNAMIC_TYPE_TMP_BUFFER); - if (cert == NULL) - return MEMORY_E; -#else - DecodedCert cert[1]; -#endif - - do { - if (DecodeCerts(source, &idx, resp, size) < 0) { - ret = ASN_PARSE_E; - break; - } - - InitDecodedCert(cert, resp->cert, resp->certSz, heap); - cert_inited = 1; - - /* Don't verify if we don't have access to Cert Manager. */ - ret = ParseCertRelative(cert, CERT_TYPE, - noVerify ? NO_VERIFY : VERIFY_OCSP_CERT, - cm, resp->pendingCAs); - if (ret < 0) { - WOLFSSL_MSG("\tOCSP Responder certificate parsing failed"); - break; - } - -#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK - if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) { - if (XMEMCMP(cert->subjectHash, - resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) { - WOLFSSL_MSG("\tOCSP Response signed by issuer"); - } - else { - WOLFSSL_MSG("\tOCSP Responder key usage check failed"); - #ifdef OPENSSL_EXTRA - resp->verifyError = OCSP_BAD_ISSUER; - #else - ret = BAD_OCSP_RESPONDER; - break; - #endif - } - } -#endif - - /* ConfirmSignature is blocking here */ - ret = ConfirmSignature( - &cert->sigCtx, - resp->response, resp->responseSz, - cert->publicKey, cert->pubKeySize, cert->keyOID, - resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz, - NULL); - - if (ret != 0) { - WOLFSSL_MSG("\tOCSP Confirm signature failed"); - ret = ASN_OCSP_CONFIRM_E; - break; - } - } while(0); - - if (cert_inited) - FreeDecodedCert(cert); -#ifdef WOLFSSL_SMALL_STACK - XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + if (DecodeCerts(source, &idx, resp, size) < 0) + return ASN_PARSE_E; - if (ret != 0) - return ret; + ret = OcspCheckCert(resp, noVerify, noVerifySignature, + (WOLFSSL_CERT_MANAGER*)cm, heap); + if (ret == 0) { + sigValid = 1; + } + else { + WOLFSSL_MSG("OCSP Internal cert can't verify the response\n"); + /* try to verify the OCSP response with CA certs */ + ret = 0; + } } else #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */ - { + if (!noVerifySignature && !sigValid) { Signer* ca; - int sigValid = -1; + SignatureCtx sigCtx; + ca = OcspFindSigner(resp, (WOLFSSL_CERT_MANAGER*)cm); + if (ca == NULL) + return ASN_NO_SIGNER_E; - #ifndef NO_SKID - ca = GetCAByKeyHash(cm, resp->single->issuerKeyHash); - #else - ca = GetCA(cm, resp->single->issuerHash); - #endif -#if defined(HAVE_CERTIFICATE_STATUS_V2) - if (ca == NULL && resp->pendingCAs != NULL) { - ca = findSignerByName(resp->pendingCAs, resp->single->issuerHash); - } +#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK + if (OcspRespCheck(resp, ca) != 0) + return BAD_OCSP_RESPONDER; #endif - if (ca) { - SignatureCtx sigCtx; - InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); + InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); - /* ConfirmSignature is blocking here */ - sigValid = ConfirmSignature(&sigCtx, resp->response, - resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID, - resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz, - NULL); - } - if (ca == NULL || sigValid != 0) { + /* ConfirmSignature is blocking here */ + sigValid = ConfirmSignature(&sigCtx, resp->response, + resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID, + resp->sig, resp->sigSz, resp->sigOID, resp->sigParams, + resp->sigParamsSz, NULL); + if (sigValid != 0) { WOLFSSL_MSG("\tOCSP Confirm signature failed"); return ASN_OCSP_CONFIRM_E; } - (void)noVerify; } @@ -37296,16 +38531,8 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length); int ret = 0; word32 idx = *ioIndex; - const byte* sigParams = NULL; - word32 sigParamsSz = 0; -#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS - #ifdef WOLFSSL_SMALL_STACK - DecodedCert* cert = NULL; - #else - DecodedCert cert[1]; - #endif - int certInit = 0; -#endif + Signer* ca = NULL; + int sigValid = 0; WOLFSSL_ENTER("DecodeBasicOcspResponse"); (void)heap; @@ -37330,10 +38557,10 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, } #ifdef WC_RSA_PSS if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) { - sigParams = GetASNItem_Addr( + resp->sigParams = GetASNItem_Addr( dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS], source); - sigParamsSz = + resp->sigParamsSz = GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS], source); } @@ -37344,6 +38571,7 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig, &resp->sigSz); } + resp->certSz = 0; #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS if ((ret == 0) && (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) { @@ -37351,106 +38579,52 @@ static int DecodeBasicOcspResponse(byte* source, word32* ioIndex, /* Store reference to certificate BER data. */ GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert, &resp->certSz); + } - /* Allocate a certificate object to decode cert into. */ - #ifdef WOLFSSL_SMALL_STACK - cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (cert == NULL) { - ret = MEMORY_E; + if ((ret == 0) && resp->certSz > 0) { + ret = OcspCheckCert(resp, noVerify, noVerifySignature, + (WOLFSSL_CERT_MANAGER*)cm, heap); + if (ret == 0) { + sigValid = 1; } + ret = 0; /* try to verify the OCSP response with CA certs */ } - if ((ret == 0) && - (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) { - #endif - /* Initialize the certificate object. */ - InitDecodedCert(cert, resp->cert, resp->certSz, heap); - certInit = 1; - /* Parse the certificate and don't verify if we don't have access to - * Cert Manager. */ - ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY, - cm, resp->pendingCAs); - if (ret < 0) { - WOLFSSL_MSG("\tOCSP Responder certificate parsing failed"); - } +#endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */ + /* try to verify using cm certs */ + if (ret == 0 && !noVerifySignature && !sigValid) + { + ca = OcspFindSigner(resp, (WOLFSSL_CERT_MANAGER*)cm); + if (ca == NULL) + ret = ASN_NO_SIGNER_E; } #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK - if ((ret == 0) && - (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL) && - !noVerify) { - ret = CheckOcspResponder(resp, cert, cm); - } -#endif /* WOLFSSL_NO_OCSP_ISSUER_CHECK */ - if ((ret == 0) && - (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) { - /* TODO: ConfirmSignature is blocking here */ - /* Check the signature of the response. */ - ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz, - cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig, - resp->sigSz, resp->sigOID, NULL, 0, NULL); - if (ret != 0) { - WOLFSSL_MSG("\tOCSP Confirm signature failed"); - ret = ASN_OCSP_CONFIRM_E; + if (ret == 0 && !noVerifySignature && !sigValid) { + if (OcspRespCheck(resp, ca) != 0) { + ret = BAD_OCSP_RESPONDER; } } - if ((ret == 0) && - (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL)) -#else - if (ret == 0) -#endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */ - { - Signer* ca; - int sigValid = -1; - - /* Response didn't have a certificate - lookup CA. */ - #ifndef NO_SKID - ca = GetCAByKeyHash(cm, resp->single->issuerKeyHash); - #else - ca = GetCA(cm, resp->single->issuerHash); - #endif - - #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) - if (ca == NULL && resp->pendingCAs != NULL) { - ca = findSignerByName(resp->pendingCAs, resp->single->issuerHash); - } - #endif - - if (ca) { - SignatureCtx sigCtx; - - /* Initialize he signature context. */ - InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); +#endif + if (ret == 0 && !noVerifySignature && !sigValid) { + SignatureCtx sigCtx; + /* Initialize the signature context. */ + InitSignatureCtx(&sigCtx, heap, INVALID_DEVID); - /* TODO: ConfirmSignature is blocking here */ - /* Check the signature of the response CA public key. */ - sigValid = ConfirmSignature(&sigCtx, resp->response, - resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID, - resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz, - NULL); - } - if ((ca == NULL) || (sigValid != 0)) { - /* Didn't find certificate or signature verificate failed. */ + /* TODO: ConfirmSignature is blocking here */ + /* Check the signature of the response CA public key. */ + sigValid = ConfirmSignature(&sigCtx, resp->response, + resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID, + resp->sig, resp->sigSz, resp->sigOID, resp->sigParams, + resp->sigParamsSz, NULL); + if (sigValid != 0) { WOLFSSL_MSG("\tOCSP Confirm signature failed"); ret = ASN_OCSP_CONFIRM_E; } } - if (ret == 0) { /* Update the position to after response data. */ *ioIndex = idx; } -#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS - if (certInit) { - FreeDecodedCert(cert); - } - #ifdef WOLFSSL_SMALL_STACK - if (cert != NULL) { - /* Dispose of certificate object. */ - XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER); - } - #endif -#endif FREE_ASNGETDATA(dataASN, heap); return ret; #endif /* WOLFSSL_ASN_TEMPLATE */ @@ -37473,6 +38647,9 @@ void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status, resp->maxIdx = inSz; resp->heap = heap; resp->pendingCAs = NULL; + resp->sigParams = NULL; + resp->sigParamsSz = 0; + resp->responderIdType = OCSP_RESPONDER_ID_INVALID; } void FreeOcspResponse(OcspResponse* resp) @@ -37526,7 +38703,8 @@ enum { #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem)) #endif /* WOLFSSL_ASN_TEMPLATE */ -int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify) +int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, + int noVerifyCert, int noVerifySignature) { #ifndef WOLFSSL_ASN_TEMPLATE int ret; @@ -37595,7 +38773,8 @@ int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify) return ret; } - ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify); + ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, + noVerifyCert, noVerifySignature); if (ret < 0) { WOLFSSL_LEAVE("OcspResponseDecode", ret); return ret; @@ -37635,7 +38814,7 @@ int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify) idx = 0; /* Decode BasicOCSPResponse. */ ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap, - noVerify); + noVerifyCert, noVerifySignature); } /* Only support BasicOCSPResponse. */ else { @@ -38653,7 +39832,7 @@ static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl, { #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK) if (verify != NO_VERIFY && - !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { + !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL after date is no longer valid"); WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR); return CRL_CERT_DATE_ERR; @@ -39758,8 +40937,8 @@ int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end) } /***************************************************************************** -* wc_MIME_find_header_name - Searches through all given headers until a header with -* a name matching the provided name is found. +* wc_MIME_find_header_name - Searches through all given headers until a header +* with a name matching the provided name is found. * * RETURNS: * returns a pointer to the found header, if no match was found, returns NULL. @@ -39837,8 +41016,8 @@ char* wc_MIME_single_canonicalize(const char* line, word32* len) } /***************************************************************************** -* wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from -* the provided header pointer. +* wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting +* from the provided header pointer. * * RETURNS: * returns zero on success, non-zero on error. @@ -40694,9 +41873,9 @@ int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e, #endif /* !NO_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */ #if defined(WOLFSSL_ACERT) && defined(WOLFSSL_ASN_TEMPLATE) -/* Initialize decoded certificate object with buffer of DER encoding. +/* Initialize decoded attribute certificate object with buffer of DER encoding. * - * @param [in, out] cert Decoded certificate object. + * @param [in, out] acert Decoded attribute certificate object. * @param [in] source Buffer containing DER encoded certificate. * @param [in] inSz Size of DER data in buffer in bytes. * @param [in] heap Dynamic memory hint. @@ -40723,7 +41902,7 @@ void InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, /* Free the decoded attribute cert object's dynamic data. * - * @param [in, out] acert Attribute Decoded certificate object. + * @param [in, out] acert Decoded attribute certificate object. */ void FreeDecodedAcert(DecodedAcert * acert) { @@ -40760,7 +41939,7 @@ void FreeDecodedAcert(DecodedAcert * acert) * @param [in, out] inOutIdx On in, the index of the start of the OtherName. * On out, index after OtherName. * @param [in] len Length of data in buffer. - * @param [in] cert Decoded attribute certificate object. + * @param [in] acert Decoded attribute certificate object. * @param [in, out] entries Linked list of DNS name entries. * * @return 0 on success. @@ -40901,7 +42080,7 @@ static int DecodeAcertGeneralName(const byte* input, word32* inOutIdx, * @param [in] input Buffer holding encoded data. * @param [in] sz Size of encoded data in bytes. * @param [in] tag ASN.1 tag value expected in header. - * @param [in, out] cert Decoded certificate object. + * @param [in, out] acert Decoded attribute certificate object. * @param [in, out] entries Linked list of DNS name entries. * * @return 0 on success. @@ -41027,11 +42206,10 @@ enum { #define HolderASN_Length (sizeof(HolderASN) / sizeof(ASNItem)) /* Decode the Holder field of an x509 attribute certificate. - * * * @param [in] input Buffer containing encoded Holder field. * @param [in] len Length of Holder field. - * @param [in] cert Decoded certificate object. + * @param [in, out] acert Decoded attribute certificate object. * * @return 0 on success. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or @@ -41195,7 +42373,7 @@ enum { * * @param [in] input Buffer containing encoded AttCertIssuer field. * @param [in] len Length of Holder field. - * @param [in] cert Decoded certificate object. + * @param [in,out] acert Decoded attribute certificate object. * * @return 0 on success. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or @@ -41371,8 +42549,10 @@ enum { * - extensions * - attributes * - * Returns 0 on success. - * Returns negative error code on error/failure. + * @param [in, out] acert Decoded attribute certificate object. + * @param [in] verify Whether to verify dates. + * @return 0 on success. + * @return negative error code on error/fail. * */ int ParseX509Acert(DecodedAcert* acert, int verify) { @@ -41582,7 +42762,6 @@ int ParseX509Acert(DecodedAcert* acert, int verify) } /* Given the parsed attribute cert info, verify the signature. - * * The sigCtx is alloced and freed here. * * @param [in] acinfo the parsed acinfo sequence @@ -41673,7 +42852,7 @@ int VerifyX509Acert(const byte* der, word32 derSz, const byte * sigParams = NULL; word32 sigParamsSz = 0; - WOLFSSL_MSG("ParseX509Acert"); + WOLFSSL_MSG("VerifyX509Acert"); if (der == NULL || pubKey == NULL || derSz == 0 || pubKeySz == 0) { WOLFSSL_MSG("error: VerifyX509Acert: bad args"); @@ -41762,6 +42941,10 @@ int VerifyX509Acert(const byte* der, word32 derSz, return ret; } +/** + * Wrapper API to expose Acert ASN functions. See Acert ASN functions + * for comments. + * */ void wc_InitDecodedAcert(DecodedAcert* acert, const byte* source, word32 inSz, void* heap) { diff --git a/src/wolfcrypt/src/bio.c b/src/wolfcrypt/src/bio.c index b265456..0b52a6c 100644 --- a/src/wolfcrypt/src/bio.c +++ b/src/wolfcrypt/src/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include #if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ #define _GNU_SOURCE 1 @@ -142,7 +139,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } - XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, sz); + XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, (size_t)sz); bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { @@ -167,14 +164,14 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, - bio->wrSz - bio->rdIdx); + (long unsigned int)bio->wrSz - (size_t)bio->rdIdx); bio->wrSz -= bio->rdIdx; bio->rdIdx = 0; /* Resize down to WOLFSSL_BIO_RESIZE_THRESHOLD for fewer * allocations. */ if (wolfSSL_BUF_MEM_resize(bio->mem_buf, - bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? bio->wrSz : - WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { + bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? + (size_t)bio->wrSz : WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } @@ -389,6 +386,10 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = 0; + break; + } /* switch */ } @@ -564,7 +565,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("Error in wolfSSL_BIO_nwrite"); return sz1; } - XMEMCPY(buf, data, sz1); + XMEMCPY(buf, data, (size_t)sz1); data = (char*)data + sz1; len -= sz1; @@ -572,7 +573,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, /* try again to see if maybe we wrapped around the ring buffer */ sz2 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz2 > 0) { - XMEMCPY(buf, data, sz2); + XMEMCPY(buf, data, (size_t)sz2); sz1 += sz2; if (len > sz2) bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; @@ -610,8 +611,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, if (len == 0) return WOLFSSL_SUCCESS; /* Return early to make logic simpler */ - if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, bio->wrSz + len, 0) - == 0) { + if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, ((size_t)bio->wrSz) + + ((size_t)len), 0) == 0) { WOLFSSL_MSG("Error growing memory area"); return WOLFSSL_FAILURE; } @@ -621,7 +622,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, return WOLFSSL_FAILURE; } - XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); + XMEMCPY(bio->mem_buf->data + bio->wrSz, data, (size_t)len); bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->num.length = bio->mem_buf->max; bio->wrSz += len; @@ -813,6 +814,10 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = len; + break; + } /* switch */ } @@ -1138,7 +1143,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_BIO_nread(bio, &c, cSz); if (ret > 0 && ret < sz) { - XMEMCPY(buf, c, ret); + XMEMCPY(buf, c, (size_t)ret); } break; } @@ -1161,6 +1166,10 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) break; #endif /* WOLFCRYPT_ONLY */ + case WOLFSSL_BIO_NULL: + ret = 0; + break; + default: WOLFSSL_MSG("BIO type not supported yet with wolfSSL_BIO_gets"); } @@ -1256,13 +1265,13 @@ size_t wolfSSL_BIO_wpending(const WOLFSSL_BIO *bio) return 0; if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz; + return (size_t)bio->wrSz; } /* type BIO_BIO then check paired buffer */ if (bio->type == WOLFSSL_BIO_BIO && bio->pair != NULL) { WOLFSSL_BIO* pair = bio->pair; - return pair->wrIdx; + return (size_t)pair->wrIdx; } return 0; @@ -1308,12 +1317,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) #ifndef WOLFCRYPT_ONLY if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { - return (long)wolfSSL_pending(bio->ptr.ssl); + return (size_t)wolfSSL_pending(bio->ptr.ssl); } #endif if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz - bio->rdIdx; + return (size_t)(bio->wrSz - bio->rdIdx); } /* type BIO_BIO then check paired buffer */ @@ -1322,11 +1331,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) if (pair->wrIdx > 0 && pair->wrIdx <= pair->rdIdx) { /* in wrap around state where beginning of buffer is being * overwritten */ - return pair->wrSz - pair->rdIdx + pair->wrIdx; + return ((size_t)pair->wrSz) - ((size_t)pair->rdIdx) + + ((size_t)pair->wrIdx); } else { /* simple case where has not wrapped around */ - return pair->wrIdx - pair->rdIdx; + return (size_t)(pair->wrIdx - pair->rdIdx); } } return 0; @@ -1423,7 +1433,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + bio->ptr.mem_buf_data = (byte*)XMALLOC((size_t)size, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); @@ -1439,7 +1449,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num.length = size; + bio->num.length = (size_t)size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1908,7 +1918,7 @@ long wolfSSL_BIO_set_mem_eof_return(WOLFSSL_BIO *bio, int v) int wolfSSL_BIO_get_len(WOLFSSL_BIO *bio) { - int len; + int len = 0; #ifndef NO_FILESYSTEM long memSz = 0; XFILE file; @@ -2309,6 +2319,15 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return &meth; } + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_null(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_NULL); + + WOLFSSL_ENTER("wolfSSL_BIO_s_null"); + + return &meth; + } WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_socket(void) { @@ -2353,7 +2372,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); if (bio) { - bio->type = WOLFSSL_BIO_DGRAM; bio->shutdown = (byte)closeF; bio->num.fd = (SOCKET_T)fd; } @@ -2381,10 +2399,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else port = str + XSTRLEN(str); /* point to null terminator */ - bio->ip = (char*)XMALLOC((port - str) + 1, /* +1 for null char */ + bio->ip = (char*)XMALLOC( + (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ip != NULL) { - XMEMCPY(bio->ip, str, port - str); + XMEMCPY(bio->ip, str, (size_t)(port - str)); bio->ip[port - str] = '\0'; bio->type = WOLFSSL_BIO_SOCKET; } @@ -2770,9 +2789,23 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else { size_t currLen = XSTRLEN(b->ip); + #ifdef WOLFSSL_NO_REALLOC + char* tmp = NULL; + #endif + if (currLen != newLen) { + #ifdef WOLFSSL_NO_REALLOC + tmp = b->ip; + b->ip = (char*)XMALLOC(newLen+1, b->heap, DYNAMIC_TYPE_OPENSSL); + if (b->ip != NULL && tmp != NULL) { + XMEMCPY(b->ip, tmp, newLen); + XFREE(tmp, b->heap, DYNAMIC_TYPE_OPENSSL); + tmp = NULL; + } + #else b->ip = (char*)XREALLOC(b->ip, newLen + 1, b->heap, DYNAMIC_TYPE_OPENSSL); + #endif if (b->ip == NULL) { WOLFSSL_MSG("Hostname realloc failed."); return WOLFSSL_FAILURE; @@ -2926,7 +2959,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->wrSz = len; bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { - XMEMCPY(bio->ptr.mem_buf_data, buf, len); + XMEMCPY(bio->ptr.mem_buf_data, buf, (size_t)len); bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -3295,11 +3328,11 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) count = XVSNPRINTF(NULL, 0, format, args); if (count >= 0) { - pt = (char*)XMALLOC(count + 1, bio->heap, + pt = (char*)XMALLOC((size_t)count + 1, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); if (pt != NULL) { - count = XVSNPRINTF(pt, count + 1, format, copy); + count = XVSNPRINTF(pt, (size_t)count + 1, format, copy); if (count >= 0) { ret = wolfSSL_BIO_write(bio, pt, count); @@ -3369,18 +3402,20 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%02x ", (unsigned char)buf[i]); else - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), + " "); if (i == 7) - (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); + (void)XSNPRINTF(line + o + 2, (size_t)((int)sizeof(line) - + (o + 2)), "-"); o += 3; } - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/wolfcrypt/src/blake2b.c b/src/wolfcrypt/src/blake2b.c index bce74b3..c1f3e7a 100644 --- a/src/wolfcrypt/src/blake2b.c +++ b/src/wolfcrypt/src/blake2b.c @@ -12,7 +12,7 @@ */ /* blake2b.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -31,20 +31,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_BLAKE2 #include #include -#include - static const word64 blake2b_IV[8] = { @@ -491,6 +483,16 @@ int wc_InitBlake2b_WithKey(Blake2b* b2b, word32 digestSz, const byte *key, word3 /* Blake2b Update */ int wc_Blake2bUpdate(Blake2b* b2b, const byte* data, word32 sz) { + if (b2b == NULL){ + return BAD_FUNC_ARG; + } + if (data == NULL && sz != 0){ + return BAD_FUNC_ARG; + } + if (sz == 0){ + return 0; + } + return blake2b_update(b2b->S, data, sz); } @@ -498,7 +500,16 @@ int wc_Blake2bUpdate(Blake2b* b2b, const byte* data, word32 sz) /* Blake2b Final, if pass in zero size we use init digestSz */ int wc_Blake2bFinal(Blake2b* b2b, byte* final, word32 requestSz) { - word32 sz = requestSz ? requestSz : b2b->digestSz; + word32 sz; + + if (b2b == NULL){ + return BAD_FUNC_ARG; + } + if (final == NULL){ + return BAD_FUNC_ARG; + } + + sz = requestSz ? requestSz : b2b->digestSz; return blake2b_final(b2b->S, final, (byte)sz); } diff --git a/src/wolfcrypt/src/blake2s.c b/src/wolfcrypt/src/blake2s.c index 7e36d6e..7f9d3ff 100644 --- a/src/wolfcrypt/src/blake2s.c +++ b/src/wolfcrypt/src/blake2s.c @@ -12,7 +12,7 @@ */ /* blake2s.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -31,20 +31,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_BLAKE2S #include #include -#include - static const word32 blake2s_IV[8] = { @@ -487,6 +479,16 @@ int wc_InitBlake2s_WithKey(Blake2s* b2s, word32 digestSz, const byte *key, word3 /* Blake2s Update */ int wc_Blake2sUpdate(Blake2s* b2s, const byte* data, word32 sz) { + if (b2s == NULL){ + return BAD_FUNC_ARG; + } + if (data == NULL && sz != 0){ + return BAD_FUNC_ARG; + } + if (sz == 0){ + return 0; + } + return blake2s_update(b2s->S, data, sz); } @@ -494,7 +496,16 @@ int wc_Blake2sUpdate(Blake2s* b2s, const byte* data, word32 sz) /* Blake2s Final, if pass in zero size we use init digestSz */ int wc_Blake2sFinal(Blake2s* b2s, byte* final, word32 requestSz) { - word32 sz = requestSz ? requestSz : b2s->digestSz; + word32 sz; + + if (b2s == NULL){ + return BAD_FUNC_ARG; + } + if (final == NULL){ + return BAD_FUNC_ARG; + } + + sz = requestSz ? requestSz : b2s->digestSz; return blake2s_final(b2s->S, final, (byte)sz); } diff --git a/src/wolfcrypt/src/camellia.c b/src/wolfcrypt/src/camellia.c index bd9ae1b..c1ff47e 100644 --- a/src/wolfcrypt/src/camellia.c +++ b/src/wolfcrypt/src/camellia.c @@ -27,7 +27,7 @@ /* camellia.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -52,18 +52,11 @@ * http://info.isl.ntt.co.jp/crypt/eng/camellia/specifications.html */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_CAMELLIA #include -#include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/chacha.c b/src/wolfcrypt/src/chacha.c index ba9aa53..1a1d676 100644 --- a/src/wolfcrypt/src/chacha.c +++ b/src/wolfcrypt/src/chacha.c @@ -1,6 +1,6 @@ /* chacha.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,15 +29,10 @@ Public domain. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_CHACHA #include - #include #ifdef NO_INLINE #include @@ -72,10 +67,10 @@ Public domain. #endif /* HAVE_CHACHA */ -#if defined(WOLFSSL_ARMASM) +#if defined(WOLFSSL_ARMASM) && !defined(NO_CHACHA_ASM) /* implementation is located in wolfcrypt/src/port/arm/armv8-chacha.c */ -#elif defined(WOLFSSL_RISCV_ASM) +#elif defined(WOLFSSL_RISCV_ASM) && !defined(NO_CHACHA_ASM) /* implementation located in wolfcrypt/src/port/riscv/riscv-64-chacha.c */ #else @@ -83,7 +78,6 @@ Public domain. /* BEGIN ChaCha C implementation */ #if defined(HAVE_CHACHA) -#include #include #ifdef CHACHA_AEAD_TEST diff --git a/src/wolfcrypt/src/chacha20_poly1305.c b/src/wolfcrypt/src/chacha20_poly1305.c index a29a18f..09d522d 100644 --- a/src/wolfcrypt/src/chacha20_poly1305.c +++ b/src/wolfcrypt/src/chacha20_poly1305.c @@ -1,6 +1,6 @@ /* chacha.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -27,17 +27,11 @@ or Authenticated Encryption with Additional Data (AEAD) algorithm. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) #include -#include -#include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index 2f5d5d4..b83214c 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -1,6 +1,6 @@ /* cmac.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #ifdef WOLFSSL_QNX_CAAM #include #endif @@ -51,7 +47,6 @@ #include #endif -#include #include #include @@ -212,7 +207,7 @@ int wc_CmacUpdate(Cmac* cmac, const byte* in, word32 inSz) #endif { ret = wc_CryptoCb_Cmac(cmac, NULL, 0, in, inSz, - NULL, NULL, cmac->type, NULL); + NULL, NULL, (int)cmac->type, NULL); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -294,8 +289,8 @@ int wc_CmacFinalNoFree(Cmac* cmac, byte* out, word32* outSz) if (cmac->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, cmac->type, - NULL); + ret = wc_CryptoCb_Cmac(cmac, NULL, 0, NULL, 0, out, outSz, + (int)cmac->type, NULL); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; diff --git a/src/wolfcrypt/src/coding.c b/src/wolfcrypt/src/coding.c index 7071796..739fde5 100644 --- a/src/wolfcrypt/src/coding.c +++ b/src/wolfcrypt/src/coding.c @@ -1,6 +1,6 @@ /* coding.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,11 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_CODING #include -#include -#include #ifndef NO_ASN #include /* For PEM_LINE_SZ */ #endif @@ -59,23 +52,33 @@ enum { #ifdef WOLFSSL_BASE64_DECODE -#ifdef BASE64_NO_TABLE -static WC_INLINE byte Base64_Char2Val(byte c) +static WC_INLINE byte Base64_Char2Val_CT(byte c) { - word16 v = 0x0000; + int v; + int smallEnd = (int)c - 0x7b; + int smallStart = (int)c - 0x61; + int bigEnd = (int)c - 0x5b; + int bigStart = (int)c - 0x41; + int numEnd = (int)c - 0x3a; + int numStart = (int)c - 0x30; + int slashEnd = (int)c - 0x30; + int slashStart = (int)c - 0x2f; + int plusEnd = (int)c - 0x2c; + int plusStart = (int)c - 0x2b; + + v = ((smallStart >> 8) ^ (smallEnd >> 8)) & (smallStart + 26 + 1); + v |= ((bigStart >> 8) ^ (bigEnd >> 8)) & (bigStart + 0 + 1); + v |= ((numStart >> 8) ^ (numEnd >> 8)) & (numStart + 52 + 1); + v |= ((slashStart >> 8) ^ (slashEnd >> 8)) & (slashStart + 63 + 1); + v |= ((plusStart >> 8) ^ (plusEnd >> 8)) & (plusStart + 62 + 1); + + return (byte)(v - 1); +} - v |= 0xff3E & ctMask16Eq(c, 0x2b); - v |= 0xff3F & ctMask16Eq(c, 0x2f); - v |= (c + 0xff04) & ctMask16GTE(c, 0x30) & ctMask16LTE(c, 0x39); - v |= (0xff00 + c - 0x41) & ctMask16GTE(c, 0x41) & ctMask16LTE(c, 0x5a); - v |= (0xff00 + c - 0x47) & ctMask16GTE(c, 0x61) & ctMask16LTE(c, 0x7a); - v |= ~(v >> 8); +#ifndef BASE64_NO_TABLE - return (byte)v; -} -#else static -ALIGN64 const byte base64Decode[] = { /* + starts at 0x2B */ +ALIGN64 const byte base64Decode_table[] = { /* + starts at 0x2B */ /* 0x28: + , - . / */ 62, BAD, BAD, BAD, 63, /* 0x30: 0 1 2 3 4 5 6 7 */ 52, 53, 54, 55, 56, 57, 58, 59, /* 0x38: 8 9 : ; < = > ? */ 60, 61, BAD, BAD, BAD, BAD, BAD, BAD, @@ -88,11 +91,11 @@ ALIGN64 const byte base64Decode[] = { /* + starts at 0x2B */ /* 0x70: p q r s t u v w */ 41, 42, 43, 44, 45, 46, 47, 48, /* 0x78: x y z */ 49, 50, 51 }; -#define BASE64DECODE_SZ (byte)(sizeof(base64Decode)) +#define BASE64DECODE_TABLE_SZ (byte)(sizeof(base64Decode_table)) -static WC_INLINE byte Base64_Char2Val(byte c) +static WC_INLINE byte Base64_Char2Val_by_table(byte c) { -#ifndef WC_NO_CACHE_RESISTANT +#ifdef WC_CACHE_RESISTANT_BASE64_TABLE /* 80 characters in table. * 64 bytes in a cache line - first line has 64, second has 16 */ @@ -102,16 +105,17 @@ static WC_INLINE byte Base64_Char2Val(byte c) c = (byte)(c - BASE64_MIN); mask = (byte)((((byte)(0x3f - c)) >> 7) - 1); /* Load a value from the first cache line and use when mask set. */ - v = (byte)(base64Decode[ c & 0x3f ] & mask); + v = (byte)(base64Decode_table[ c & 0x3f ] & mask); /* Load a value from the second cache line and use when mask not set. */ - v |= (byte)(base64Decode[(c & 0x0f) | 0x40] & (~mask)); + v |= (byte)(base64Decode_table[(c & 0x0f) | 0x40] & (~mask)); return v; #else - return base64Decode[c - BASE64_MIN]; + return base64Decode_table[c - BASE64_MIN]; #endif } -#endif + +#endif /* !BASE64_NO_TABLE */ int Base64_SkipNewline(const byte* in, word32 *inLen, word32 *outJ) @@ -161,15 +165,15 @@ int Base64_SkipNewline(const byte* in, word32 *inLen, return 0; } -int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) +#ifndef BASE64_NO_TABLE + +int Base64_Decode_nonCT(const byte* in, word32 inLen, byte* out, word32* outLen) { word32 i = 0; word32 j = 0; word32 plainSz = inLen - ((inLen + (BASE64_LINE_SZ - 1)) / BASE64_LINE_SZ ); int ret; -#ifndef BASE64_NO_TABLE - const byte maxIdx = BASE64DECODE_SZ + BASE64_MIN - 1; -#endif + const byte maxIdx = BASE64DECODE_TABLE_SZ + BASE64_MIN - 1; plainSz = (plainSz * 3 + 3) / 4; if (plainSz > *outLen) return BAD_FUNC_ARG; @@ -216,7 +220,6 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) if (pad3 && !pad4) return ASN_INPUT_E; -#ifndef BASE64_NO_TABLE if (e1 < BASE64_MIN || e2 < BASE64_MIN || e3 < BASE64_MIN || e4 < BASE64_MIN) { WOLFSSL_MSG("Bad Base64 Decode data, too small"); @@ -227,17 +230,16 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) WOLFSSL_MSG("Bad Base64 Decode data, too big"); return ASN_INPUT_E; } -#endif if (i + 1 + !pad3 + !pad4 > *outLen) { WOLFSSL_MSG("Bad Base64 Decode out buffer, too small"); return BAD_FUNC_ARG; } - e1 = Base64_Char2Val(e1); - e2 = Base64_Char2Val(e2); - e3 = (byte)((e3 == PAD) ? 0 : Base64_Char2Val(e3)); - e4 = (byte)((e4 == PAD) ? 0 : Base64_Char2Val(e4)); + e1 = Base64_Char2Val_by_table(e1); + e2 = Base64_Char2Val_by_table(e2); + e3 = (byte)((e3 == PAD) ? 0 : Base64_Char2Val_by_table(e3)); + e4 = (byte)((e4 == PAD) ? 0 : Base64_Char2Val_by_table(e4)); if (e1 == BAD || e2 == BAD || e3 == BAD || e4 == BAD) { WOLFSSL_MSG("Bad Base64 Decode bad character"); @@ -256,7 +258,8 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) else break; } -/* If the output buffer has a room for an extra byte, add a null terminator */ + + /* If the output buffer has a room for an extra byte, add a null terminator */ if (out && *outLen > i) out[i]= '\0'; @@ -265,6 +268,103 @@ int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) return 0; } +#endif /* !BASE64_NO_TABLE */ + +int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) +{ + word32 i = 0; + word32 j = 0; + word32 plainSz = inLen - ((inLen + (BASE64_LINE_SZ - 1)) / BASE64_LINE_SZ ); + int ret; + + plainSz = (plainSz * 3 + 3) / 4; + if (plainSz > *outLen) return BAD_FUNC_ARG; + + while (inLen > 3) { + int pad3 = 0; + int pad4 = 0; + byte b1, b2, b3; + byte e1, e2, e3, e4; + + if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) { + if (ret == WC_NO_ERR_TRACE(BUFFER_E)) { + /* Running out of buffer here is not an error */ + break; + } + return ret; + } + e1 = in[j++]; + if (e1 == '\0') { + break; + } + inLen--; + if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) { + return ret; + } + e2 = in[j++]; + inLen--; + if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) { + return ret; + } + e3 = in[j++]; + inLen--; + if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) { + return ret; + } + e4 = in[j++]; + inLen--; + + if (e3 == PAD) + pad3 = 1; + if (e4 == PAD) + pad4 = 1; + + if (pad3 && !pad4) + return ASN_INPUT_E; + + if (i + 1 + !pad3 + !pad4 > *outLen) { + WOLFSSL_MSG("Bad Base64 Decode out buffer, too small"); + return BAD_FUNC_ARG; + } + + e1 = Base64_Char2Val_CT(e1); + e2 = Base64_Char2Val_CT(e2); + e3 = (byte)((e3 == PAD) ? 0 : Base64_Char2Val_CT(e3)); + e4 = (byte)((e4 == PAD) ? 0 : Base64_Char2Val_CT(e4)); + + if (e1 == BAD || e2 == BAD || e3 == BAD || e4 == BAD) { + WOLFSSL_MSG("Bad Base64 Decode bad character"); + return ASN_INPUT_E; + } + + b1 = (byte)((e1 << 2) | (e2 >> 4)); + b2 = (byte)(((e2 & 0xF) << 4) | (e3 >> 2)); + b3 = (byte)(((e3 & 0x3) << 6) | e4); + + out[i++] = b1; + if (!pad3) + out[i++] = b2; + if (!pad4) + out[i++] = b3; + else + break; + } + + /* If the output buffer has a room for an extra byte, add a null terminator */ + if (out && *outLen > i) + out[i]= '\0'; + + *outLen = i; + + return 0; +} + +#ifdef BASE64_NO_TABLE +int Base64_Decode_nonCT(const byte* in, word32 inLen, byte* out, word32* outLen) { + return Base64_Decode(in, inLen, out, outLen); +} +#endif /* BASE64_NO_TABLE */ + #endif /* WOLFSSL_BASE64_DECODE */ #if defined(WOLFSSL_BASE64_ENCODE) @@ -490,7 +590,7 @@ int Base64_Encode_NoNl(const byte* in, word32 inLen, byte* out, word32* outLen) #ifdef WOLFSSL_BASE16 static -const byte hexDecode[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +const ALIGN64 byte hexDecode[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, BAD, BAD, BAD, BAD, BAD, BAD, BAD, 10, 11, 12, 13, 14, 15, /* upper case A-F */ BAD, BAD, BAD, BAD, BAD, BAD, BAD, BAD, @@ -556,6 +656,11 @@ int Base16_Decode(const byte* in, word32 inLen, byte* out, word32* outLen) return 0; } +static +const ALIGN64 byte hexEncode[] = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' +}; + int Base16_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) { word32 outIdx = 0; @@ -571,15 +676,8 @@ int Base16_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) byte hb = in[i] >> 4; byte lb = in[i] & 0x0f; - /* ASCII value */ - hb = (byte)(hb + '0'); - if (hb > '9') - hb = (byte)(hb + 7U); - - /* ASCII value */ - lb = (byte)(lb + '0'); - if (lb>'9') - lb = (byte)(lb + 7U); + hb = hexEncode[hb]; + lb = hexEncode[lb]; out[outIdx++] = hb; out[outIdx++] = lb; diff --git a/src/wolfcrypt/src/compress.c b/src/wolfcrypt/src/compress.c index 941596e..e3c42cc 100644 --- a/src/wolfcrypt/src/compress.c +++ b/src/wolfcrypt/src/compress.c @@ -1,6 +1,6 @@ /* compress.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,20 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_LIBZ #include -#include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/cpuid.c b/src/wolfcrypt/src/cpuid.c index a9f1533..37fe855 100644 --- a/src/wolfcrypt/src/cpuid.c +++ b/src/wolfcrypt/src/cpuid.c @@ -1,6 +1,6 @@ /* cpuid.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #include @@ -60,7 +55,8 @@ int got_intel_cpu = 0; int got_amd_cpu = 0; unsigned int reg[5]; - reg[4] = '\0'; + + XMEMSET(reg, '\0', sizeof(reg)); cpuid(reg, 0, 0); /* check for Intel cpu */ @@ -163,23 +159,36 @@ if (!cpuid_check) { word64 hwcaps = getauxval(AT_HWCAP); + #ifndef WOLFSSL_ARMASM_NO_HW_CRYPTO if (hwcaps & HWCAP_AES) cpuid_flags |= CPUID_AES; if (hwcaps & HWCAP_PMULL) cpuid_flags |= CPUID_PMULL; if (hwcaps & HWCAP_SHA2) cpuid_flags |= CPUID_SHA256; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA512 if (hwcaps & HWCAP_SHA512) cpuid_flags |= CPUID_SHA512; + #endif + #if defined(HWCAP_ASIMDRDM) && !defined(WOLFSSL_AARCH64_NO_SQRDMLSH) if (hwcaps & HWCAP_ASIMDRDM) cpuid_flags |= CPUID_RDM; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 if (hwcaps & HWCAP_SHA3) cpuid_flags |= CPUID_SHA3; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SM3 if (hwcaps & HWCAP_SM3) cpuid_flags |= CPUID_SM3; + #endif + #ifdef WOLFSSL_ARMASM_CRYPTO_SM4 if (hwcaps & HWCAP_SM4) cpuid_flags |= CPUID_SM4; + #endif + (void)hwcaps; cpuid_check = 1; } } @@ -259,8 +268,10 @@ if (features & CPUID_AARCH64_FEAT_AES) cpuid_flags |= CPUID_AES; - if (features & CPUID_AARCH64_FEAT_PMULL) + if (features & CPUID_AARCH64_FEAT_AES_PMULL) { + cpuid_flags |= CPUID_AES; cpuid_flags |= CPUID_PMULL; + } if (features & CPUID_AARCH64_FEAT_SHA256) cpuid_flags |= CPUID_SHA256; if (features & CPUID_AARCH64_FEAT_SHA256_512) @@ -289,7 +300,7 @@ #ifdef WOLFSSL_ARMASM_CRYPTO_SHA512 cpuid_flags |= CPUID_SHA512; #endif - #ifndef WOLFSSL_AARCH64_NO_SQRMLSH + #ifndef WOLFSSL_AARCH64_NO_SQRDMLSH cpuid_flags |= CPUID_RDM; #endif #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 diff --git a/src/wolfcrypt/src/cryptocb.c b/src/wolfcrypt/src/cryptocb.c index 973b4f9..a83e529 100644 --- a/src/wolfcrypt/src/cryptocb.c +++ b/src/wolfcrypt/src/cryptocb.c @@ -1,6 +1,6 @@ /* cryptocb.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -36,17 +36,11 @@ * DEBUG_CRYPTOCB */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLF_CRYPTO_CB #include -#include -#include #ifdef HAVE_ARIA #include @@ -207,6 +201,8 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) info->cipher.type, info->cipher.ctx); } #endif /* !NO_AES || !NO_DES3 */ +#if !defined(NO_SHA) || !defined(NO_SHA256) || \ + defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA3) else if (info->algo_type == WC_ALGO_TYPE_HASH) { printf("Crypto CB: %s %s (%d) (%p ctx) %s\n", GetAlgoTypeStr(info->algo_type), @@ -214,6 +210,8 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) info->hash.type, info->hash.ctx, (info->hash.in != NULL) ? "Update" : "Final"); } +#endif +#ifndef NO_HMAC else if (info->algo_type == WC_ALGO_TYPE_HMAC) { printf("Crypto CB: %s %s (%d) (%p ctx) %s\n", GetAlgoTypeStr(info->algo_type), @@ -221,6 +219,7 @@ WOLFSSL_API void wc_CryptoCb_InfoString(wc_CryptoInfo* info) info->hmac.macType, info->hmac.hmac, (info->hmac.in != NULL) ? "Update" : "Final"); } +#endif #ifdef WOLFSSL_CMAC else if (info->algo_type == WC_ALGO_TYPE_CMAC) { printf("Crypto CB: %s %s (%d) (%p ctx) %s %s %s\n", @@ -865,7 +864,7 @@ int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, } #endif /* HAVE_ED25519 */ -#if defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_HAVE_MLKEM) int wc_CryptoCb_PqcKemGetDevId(int type, void* key) { int devId = INVALID_DEVID; @@ -984,7 +983,7 @@ int wc_CryptoCb_PqcDecapsulate(const byte* ciphertext, word32 ciphertextLen, return wc_CryptoCb_TranslateErrorCode(ret); } -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM */ #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) int wc_CryptoCb_PqcSigGetDevId(int type, void* key) @@ -1043,7 +1042,8 @@ int wc_CryptoCb_MakePqcSignatureKey(WC_RNG* rng, int type, int keySize, } int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, word32 *outlen, - WC_RNG* rng, int type, void* key) + const byte* context, byte contextLen, word32 preHashType, WC_RNG* rng, + int type, void* key) { int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; @@ -1068,6 +1068,9 @@ int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, word32 *outlen, cryptoInfo.pk.pqc_sign.inlen = inlen; cryptoInfo.pk.pqc_sign.out = out; cryptoInfo.pk.pqc_sign.outlen = outlen; + cryptoInfo.pk.pqc_sign.context = context; + cryptoInfo.pk.pqc_sign.contextLen = contextLen; + cryptoInfo.pk.pqc_sign.preHashType = preHashType; cryptoInfo.pk.pqc_sign.rng = rng; cryptoInfo.pk.pqc_sign.key = key; cryptoInfo.pk.pqc_sign.type = type; @@ -1079,7 +1082,8 @@ int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, word32 *outlen, } int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, const byte* msg, - word32 msglen, int* res, int type, void* key) + word32 msglen, const byte* context, byte contextLen, word32 preHashType, + int* res, int type, void* key) { int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); int devId = INVALID_DEVID; @@ -1104,6 +1108,9 @@ int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, const byte* msg, cryptoInfo.pk.pqc_verify.siglen = siglen; cryptoInfo.pk.pqc_verify.msg = msg; cryptoInfo.pk.pqc_verify.msglen = msglen; + cryptoInfo.pk.pqc_verify.context = context; + cryptoInfo.pk.pqc_verify.contextLen = contextLen; + cryptoInfo.pk.pqc_verify.preHashType = preHashType; cryptoInfo.pk.pqc_verify.res = res; cryptoInfo.pk.pqc_verify.key = key; cryptoInfo.pk.pqc_verify.type = type; @@ -1874,6 +1881,12 @@ int wc_CryptoCb_DefaultDevID(void) { int ret; +/* Explicitly disable the "default devId" behavior. Ensures that any devId + * will only be used if explicitly passed as an argument to crypto functions, + * and never automatically selected. */ +#ifdef WC_NO_DEFAULT_DEVID + ret = INVALID_DEVID; +#else /* conditional macro selection based on build */ #ifdef WOLFSSL_CAAM_DEVID ret = WOLFSSL_CAAM_DEVID; @@ -1885,6 +1898,7 @@ int wc_CryptoCb_DefaultDevID(void) /* try first available */ ret = wc_CryptoCb_GetDevIdAtIndex(0); #endif +#endif /* WC_NO_DEFAULT_DEVID */ return ret; } diff --git a/src/wolfcrypt/src/curve25519.c b/src/wolfcrypt/src/curve25519.c index 8f409da..ae2a6b4 100644 --- a/src/wolfcrypt/src/curve25519.c +++ b/src/wolfcrypt/src/curve25519.c @@ -1,6 +1,6 @@ /* curve25519.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,17 +22,11 @@ /* Based On Daniel J Bernstein's curve25519 Public Domain ref10 work. */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_CURVE25519 #include -#include #ifdef NO_INLINE #include #else @@ -51,6 +45,14 @@ #include #endif +#if defined(WOLFSSL_CURVE25519_BLINDING) + #if defined(CURVE25519_SMALL) + #error "Blinding not needed nor available for small implementation" + #elif defined(USE_INTEL_SPEEDUP) || defined(WOLFSSL_ARMASM) + #error "Blinding not needed nor available for assembly implementation" + #endif +#endif + #if defined(WOLFSSL_LINUXKM) && !defined(USE_INTEL_SPEEDUP) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS @@ -143,6 +145,7 @@ int wc_curve25519_make_pub(int public_size, byte* pub, int private_size, XMEMCPY(pub, wc_pub.point, CURVE25519_KEYSIZE); } #else +#ifndef WOLFSSL_CURVE25519_BLINDING fe_init(); SAVE_VECTOR_REGISTERS(return _svr_ret;); @@ -150,10 +153,119 @@ int wc_curve25519_make_pub(int public_size, byte* pub, int private_size, ret = curve25519(pub, priv, (byte*)kCurve25519BasePoint); RESTORE_VECTOR_REGISTERS(); +#else + { + WC_RNG rng; + + ret = wc_InitRng(&rng); + if (ret == 0) { + ret = wc_curve25519_make_pub_blind(public_size, pub, private_size, + priv, &rng); + + wc_FreeRng(&rng); + } + } +#endif /* !WOLFSSL_CURVE25519_BLINDING */ +#endif /* FREESCALE_LTC_ECC */ + + return ret; +} + +#ifdef WOLFSSL_CURVE25519_BLINDING +#ifndef FREESCALE_LTC_ECC +#ifndef WOLFSSL_CURVE25519_BLINDING_RAND_CNT + #define WOLFSSL_CURVE25519_BLINDING_RAND_CNT 10 +#endif +static int curve25519_smul_blind(byte* rp, const byte* n, const byte* p, + WC_RNG* rng) +{ + int ret; + byte a[CURVE25519_KEYSIZE]; + byte n_a[CURVE25519_KEYSIZE]; + byte rz[CURVE25519_KEYSIZE]; + int i; + int cnt; + + SAVE_VECTOR_REGISTERS(return _svr_ret;); + + /* Generate random z. */ + for (cnt = 0; cnt < WOLFSSL_CURVE25519_BLINDING_RAND_CNT; cnt++) { + ret = wc_RNG_GenerateBlock(rng, rz, sizeof(rz)); + if (ret < 0) { + return ret; + } + for (i = CURVE25519_KEYSIZE; i > 0; i--) { + if (rz[i] != 0xff) + break; + } + if ((i != 0) || (rz[0] <= 0xec)) { + break; + } + } + if (cnt == WOLFSSL_CURVE25519_BLINDING_RAND_CNT) { + return RNG_FAILURE_E; + } + + /* Generate 253 random bits. */ + ret = wc_RNG_GenerateBlock(rng, a, sizeof(a)); + if (ret != 0) + return ret; + a[CURVE25519_KEYSIZE-1] &= 0x7f; + /* k' = k ^ 2k ^ a */ + n_a[0] = n[0] ^ (n[0] << 1) ^ a[0]; + for (i = 1; i < CURVE25519_KEYSIZE; i++) { + byte b1, b2, b3; + b1 = n[i] ^ a[i]; + b2 = (n[i] << 1) ^ a[i]; + b3 = (n[i-1] >> 7) ^ a[i]; + n_a[i] = b1 ^ b2 ^ b3; + } + /* Scalar multiple blinded scalar with blinding value. */ + ret = curve25519_blind(rp, n_a, a, p, rz); + + RESTORE_VECTOR_REGISTERS(); + + return ret; +} +#endif + +int wc_curve25519_make_pub_blind(int public_size, byte* pub, int private_size, + const byte* priv, WC_RNG* rng) +{ + int ret; +#ifdef FREESCALE_LTC_ECC + const ECPoint* basepoint = nxp_ltc_curve25519_GetBasePoint(); + ECPoint wc_pub; +#endif + + if ( (public_size != CURVE25519_KEYSIZE) || + (private_size != CURVE25519_KEYSIZE)) { + return ECC_BAD_ARG_E; + } + if ((pub == NULL) || (priv == NULL)) { + return ECC_BAD_ARG_E; + } + + /* check clamping */ + ret = curve25519_priv_clamp_check(priv); + if (ret != 0) + return ret; + +#ifdef FREESCALE_LTC_ECC + /* input basepoint on Weierstrass curve */ + ret = nxp_ltc_curve25519(&wc_pub, priv, basepoint, kLTC_Weierstrass); + if (ret == 0) { + XMEMCPY(pub, wc_pub.point, CURVE25519_KEYSIZE); + } +#else + fe_init(); + + ret = curve25519_smul_blind(pub, priv, (byte*)kCurve25519BasePoint, rng); #endif return ret; } +#endif /* compute the public key from an existing private key, with supplied basepoint, * using bare vectors. @@ -170,6 +282,7 @@ int wc_curve25519_generic(int public_size, byte* pub, * nxp_ltc_curve25519_GetBasePoint() */ return WC_HW_E; #else +#ifndef WOLFSSL_CURVE25519_BLINDING int ret; if ((public_size != CURVE25519_KEYSIZE) || @@ -194,9 +307,64 @@ int wc_curve25519_generic(int public_size, byte* pub, RESTORE_VECTOR_REGISTERS(); return ret; +#else + WC_RNG rng; + int ret; + + ret = wc_InitRng(&rng); + if (ret == 0) { + ret = wc_curve25519_generic_blind(public_size, pub, private_size, priv, + basepoint_size, basepoint, &rng); + + wc_FreeRng(&rng); + } + + return ret; +#endif #endif /* FREESCALE_LTC_ECC */ } +#ifdef WOLFSSL_CURVE25519_BLINDING +/* compute the public key from an existing private key, with supplied basepoint, + * using bare vectors. + * + * return value is propagated from curve25519() (0 on success), + * and the byte vectors are little endian. + */ +int wc_curve25519_generic_blind(int public_size, byte* pub, + int private_size, const byte* priv, + int basepoint_size, const byte* basepoint, + WC_RNG* rng) +{ +#ifdef FREESCALE_LTC_ECC + /* unsupported with NXP LTC, only supports single basepoint with + * nxp_ltc_curve25519_GetBasePoint() */ + return WC_HW_E; +#else + int ret; + + if ((public_size != CURVE25519_KEYSIZE) || + (private_size != CURVE25519_KEYSIZE) || + (basepoint_size != CURVE25519_KEYSIZE)) { + return ECC_BAD_ARG_E; + } + if ((pub == NULL) || (priv == NULL) || (basepoint == NULL)) + return ECC_BAD_ARG_E; + + /* check clamping */ + ret = curve25519_priv_clamp_check(priv); + if (ret != 0) + return ret; + + fe_init(); + + ret = curve25519_smul_blind(pub, priv, basepoint, rng); + + return ret; +#endif /* FREESCALE_LTC_ECC */ +} +#endif + /* generate a new private key, as a bare vector. * * return value is propagated from wc_RNG_GenerateBlock(() (0 on success), @@ -250,8 +418,14 @@ int wc_curve25519_make_key(WC_RNG* rng, int keysize, curve25519_key* key) ret = wc_curve25519_make_priv(rng, keysize, key->k); if (ret == 0) { key->privSet = 1; +#ifdef WOLFSSL_CURVE25519_BLINDING + ret = wc_curve25519_make_pub_blind((int)sizeof(key->p.point), + key->p.point, (int)sizeof(key->k), + key->k, rng); +#else ret = wc_curve25519_make_pub((int)sizeof(key->p.point), key->p.point, (int)sizeof(key->k), key->k); +#endif key->pubSet = (ret == 0); } #endif @@ -320,11 +494,16 @@ int wc_curve25519_shared_secret_ex(curve25519_key* private_key, else #endif { +#ifndef WOLFSSL_CURVE25519_BLINDING SAVE_VECTOR_REGISTERS(return _svr_ret;); ret = curve25519(o.point, private_key->k, public_key->p.point); RESTORE_VECTOR_REGISTERS(); +#else + ret = curve25519_smul_blind(o.point, private_key->k, public_key->p.point, + private_key->rng); +#endif } #endif #ifdef WOLFSSL_ECDHX_SHARED_NOT_ZERO @@ -379,8 +558,14 @@ int wc_curve25519_export_public_ex(curve25519_key* key, byte* out, /* calculate public if missing */ if (!key->pubSet) { +#ifdef WOLFSSL_CURVE25519_BLINDING + ret = wc_curve25519_make_pub_blind((int)sizeof(key->p.point), + key->p.point, (int)sizeof(key->k), + key->k, key->rng); +#else ret = wc_curve25519_make_pub((int)sizeof(key->p.point), key->p.point, (int)sizeof(key->k), key->k); +#endif key->pubSet = (ret == 0); } /* export public point with endianness */ @@ -639,6 +824,9 @@ int wc_curve25519_import_private_ex(const byte* priv, word32 privSz, } #ifdef WOLFSSL_SE050 +#ifdef WOLFSSL_SE050_AUTO_ERASE + wc_se050_erase_object(key->keyId); +#endif /* release NXP resources if set */ se050_curve25519_free_key(key); #endif @@ -739,6 +927,16 @@ void wc_curve25519_free(curve25519_key* key) #endif } +#ifdef WOLFSSL_CURVE25519_BLINDING +int wc_curve25519_set_rng(curve25519_key* key, WC_RNG* rng) +{ + if (key == NULL) + return BAD_FUNC_ARG; + key->rng = rng; + return 0; +} +#endif + /* get key size */ int wc_curve25519_size(curve25519_key* key) { diff --git a/src/wolfcrypt/src/curve448.c b/src/wolfcrypt/src/curve448.c index 3cbf577..f3cf9f3 100644 --- a/src/wolfcrypt/src/curve448.c +++ b/src/wolfcrypt/src/curve448.c @@ -1,6 +1,6 @@ /* curve448.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -25,16 +25,11 @@ * Reworked for curve448 by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_CURVE448 #include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/des3.c b/src/wolfcrypt/src/des3.c index d6c3923..7a9ba3b 100644 --- a/src/wolfcrypt/src/des3.c +++ b/src/wolfcrypt/src/des3.c @@ -1,6 +1,6 @@ /* des3.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include - +#include #ifndef NO_DES3 @@ -448,8 +440,6 @@ #elif defined(HAVE_COLDFIRE_SEC) - #include - #include "sec.h" #include "mcf5475_sec.h" #include "mcf5475_siu.h" diff --git a/src/wolfcrypt/src/dh.c b/src/wolfcrypt/src/dh.c index 5258e82..8869c03 100644 --- a/src/wolfcrypt/src/dh.c +++ b/src/wolfcrypt/src/dh.c @@ -1,6 +1,6 @@ /* dh.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_DH @@ -41,8 +36,6 @@ #endif #include -#include -#include #ifdef WOLFSSL_HAVE_SP_DH #include @@ -2036,19 +2029,21 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #ifndef WOLFSSL_SP_NO_2048 if (mp_count_bits(&key->p) == 2048) { if (mp_init(y) != MP_OKAY) - return MP_INIT_E; + ret = MP_INIT_E; - SAVE_VECTOR_REGISTERS(ret = _svr_ret;); + if (ret == 0) { + SAVE_VECTOR_REGISTERS(ret = _svr_ret;); - if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) - ret = MP_READ_E; + if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) + ret = MP_READ_E; - if (ret == 0) - ret = sp_DhExp_2048(y, priv, privSz, &key->p, agree, agreeSz); + if (ret == 0) + ret = sp_DhExp_2048(y, priv, privSz, &key->p, agree, agreeSz); - mp_clear(y); + mp_clear(y); - RESTORE_VECTOR_REGISTERS(); + RESTORE_VECTOR_REGISTERS(); + } /* make sure agree is > 1 (SP800-56A, 5.7.1.1) */ if ((ret == 0) && @@ -2070,19 +2065,21 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #ifndef WOLFSSL_SP_NO_3072 if (mp_count_bits(&key->p) == 3072) { if (mp_init(y) != MP_OKAY) - return MP_INIT_E; + ret = MP_INIT_E; - SAVE_VECTOR_REGISTERS(ret = _svr_ret;); + if (ret == 0) { + SAVE_VECTOR_REGISTERS(ret = _svr_ret;); - if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) - ret = MP_READ_E; + if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) + ret = MP_READ_E; - if (ret == 0) - ret = sp_DhExp_3072(y, priv, privSz, &key->p, agree, agreeSz); + if (ret == 0) + ret = sp_DhExp_3072(y, priv, privSz, &key->p, agree, agreeSz); - mp_clear(y); + mp_clear(y); - RESTORE_VECTOR_REGISTERS(); + RESTORE_VECTOR_REGISTERS(); + } /* make sure agree is > 1 (SP800-56A, 5.7.1.1) */ if ((ret == 0) && @@ -2104,19 +2101,21 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #ifdef WOLFSSL_SP_4096 if (mp_count_bits(&key->p) == 4096) { if (mp_init(y) != MP_OKAY) - return MP_INIT_E; + ret = MP_INIT_E; - SAVE_VECTOR_REGISTERS(ret = _svr_ret;); + if (ret == 0) { + SAVE_VECTOR_REGISTERS(ret = _svr_ret;); - if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) - ret = MP_READ_E; + if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) + ret = MP_READ_E; - if (ret == 0) - ret = sp_DhExp_4096(y, priv, privSz, &key->p, agree, agreeSz); + if (ret == 0) + ret = sp_DhExp_4096(y, priv, privSz, &key->p, agree, agreeSz); - mp_clear(y); + mp_clear(y); - RESTORE_VECTOR_REGISTERS(); + RESTORE_VECTOR_REGISTERS(); + } /* make sure agree is > 1 (SP800-56A, 5.7.1.1) */ if ((ret == 0) && @@ -2544,10 +2543,56 @@ static int _DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, if (ret == 0 && !trusted) { int isPrime = 0; - if (rng != NULL) - ret = mp_prime_is_prime_ex(keyP, 8, &isPrime, rng); + + /* Short-circuit the primality check for p if it is one of the named + * public moduli (known primes) from RFC 7919. + */ + #ifdef HAVE_FFDHE_2048 + if ((pSz == sizeof(dh_ffdhe2048_p)) && + (XMEMCMP(p, dh_ffdhe2048_p, sizeof(dh_ffdhe2048_p)) == 0)) + { + isPrime = 1; + } + else + #endif + #ifdef HAVE_FFDHE_3072 + if ((pSz == sizeof(dh_ffdhe3072_p)) && + (XMEMCMP(p, dh_ffdhe3072_p, sizeof(dh_ffdhe3072_p)) == 0)) + { + isPrime = 1; + } + else + #endif + #ifdef HAVE_FFDHE_4096 + if ((pSz == sizeof(dh_ffdhe4096_p)) && + (XMEMCMP(p, dh_ffdhe4096_p, sizeof(dh_ffdhe4096_p)) == 0)) + { + isPrime = 1; + } + else + #endif + #ifdef HAVE_FFDHE_6144 + if ((pSz == sizeof(dh_ffdhe6144_p)) && + (XMEMCMP(p, dh_ffdhe6144_p, sizeof(dh_ffdhe6144_p)) == 0)) + { + isPrime = 1; + } else - ret = mp_prime_is_prime(keyP, 8, &isPrime); + #endif + #ifdef HAVE_FFDHE_8192 + if ((pSz == sizeof(dh_ffdhe8192_p)) && + (XMEMCMP(p, dh_ffdhe8192_p, sizeof(dh_ffdhe8192_p)) == 0)) + { + isPrime = 1; + } + else + #endif + { + if (rng != NULL) + ret = mp_prime_is_prime_ex(keyP, 8, &isPrime, rng); + else + ret = mp_prime_is_prime(keyP, 8, &isPrime); + } if (ret == 0 && isPrime == 0) ret = DH_CHECK_PUB_E; diff --git a/src/wolfcrypt/src/dilithium.c b/src/wolfcrypt/src/dilithium.c index 6391da4..1aa2750 100644 --- a/src/wolfcrypt/src/dilithium.c +++ b/src/wolfcrypt/src/dilithium.c @@ -1,6 +1,6 @@ /* dilithium.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -130,13 +130,7 @@ * shift equivalent. */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set HAVE_PQC there */ -#include +#include #ifndef WOLFSSL_DILITHIUM_NO_ASN1 #include @@ -151,7 +145,6 @@ #include #include #include -#include #ifdef NO_INLINE #include #else @@ -2195,7 +2188,7 @@ static int dilithium_rej_ntt_poly_ex(wc_Shake* shake128, byte* seed, sword32* a, static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, void* heap) { - int ret; + int ret = 0; #if defined(WOLFSSL_SMALL_STACK) byte* h = NULL; #else @@ -2212,7 +2205,8 @@ static int dilithium_rej_ntt_poly(wc_Shake* shake128, byte* seed, sword32* a, } #endif - ret = dilithium_rej_ntt_poly_ex(shake128, seed, a, h); + if (ret == 0) + ret = dilithium_rej_ntt_poly_ex(shake128, seed, a, h); #if defined(WOLFSSL_SMALL_STACK) XFREE(h, heap, DYNAMIC_TYPE_DILITHIUM); @@ -6076,6 +6070,7 @@ static int dilithium_sign_with_seed_mu(dilithium_key* key, ret = MEMORY_E; } else { + XMEMSET(key->s1, 0, params->aSz); key->s2 = key->s1 + params->s1Sz / sizeof(*s1); key->t0 = key->s2 + params->s2Sz / sizeof(*s2); } @@ -7223,6 +7218,9 @@ static int dilithium_verify_mu(dilithium_key* key, const byte* mu, if (key->a == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->a, 0, params->aSz); + } } #endif if (ret == 0) { @@ -7237,6 +7235,9 @@ static int dilithium_verify_mu(dilithium_key* key, const byte* mu, if (key->t1 == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->t1, 0, params->s2Sz); + } } #endif if (ret == 0) { @@ -7259,6 +7260,7 @@ static int dilithium_verify_mu(dilithium_key* key, const byte* mu, ret = MEMORY_E; } else { + XMEMSET(z, 0, allocSz); c = z + params->s1Sz / sizeof(*z); w = c + DILITHIUM_N; #ifndef WC_DILITHIUM_CACHE_PUB_VECTORS @@ -7387,6 +7389,7 @@ static int dilithium_verify_mu(dilithium_key* key, const byte* mu, ret = MEMORY_E; } else { + XMEMSET(z, 0, allocSz); c = z + params->s1Sz / sizeof(*t1); w = c + DILITHIUM_N; t1 = w + DILITHIUM_N; @@ -8014,8 +8017,8 @@ int wc_dilithium_sign_ctx_msg(const byte* ctx, byte ctxLen, const byte* msg, if (key->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, rng, - WC_PQC_SIG_TYPE_DILITHIUM, key); + ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, ctx, ctxLen, + WC_HASH_TYPE_NONE, rng, WC_PQC_SIG_TYPE_DILITHIUM, key); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -8065,8 +8068,8 @@ int wc_dilithium_sign_msg(const byte* msg, word32 msgLen, byte* sig, if (key->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, rng, - WC_PQC_SIG_TYPE_DILITHIUM, key); + ret = wc_CryptoCb_PqcSign(msg, msgLen, sig, sigLen, NULL, 0, + WC_HASH_TYPE_NONE, rng, WC_PQC_SIG_TYPE_DILITHIUM, key); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -8117,6 +8120,22 @@ int wc_dilithium_sign_ctx_hash(const byte* ctx, byte ctxLen, int hashAlg, ret = BAD_FUNC_ARG; } +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcSign(hash, hashLen, sig, sigLen, ctx, ctxLen, + hashAlg, rng, WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + if (ret == 0) { /* Sign message. */ #ifdef WOLFSSL_WC_DILITHIUM @@ -8291,6 +8310,22 @@ int wc_dilithium_verify_ctx_msg(const byte* sig, word32 sigLen, const byte* ctx, ret = BAD_FUNC_ARG; } +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, ctx, ctxLen, + WC_HASH_TYPE_NONE, res, WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + if (ret == 0) { /* Verify message with signature. */ #ifdef WOLFSSL_WC_DILITHIUM @@ -8329,21 +8364,21 @@ int wc_dilithium_verify_msg(const byte* sig, word32 sigLen, const byte* msg, ret = BAD_FUNC_ARG; } - #ifdef WOLF_CRYPTO_CB +#ifdef WOLF_CRYPTO_CB if (ret == 0) { - #ifndef WOLF_CRYPTO_CB_FIND + #ifndef WOLF_CRYPTO_CB_FIND if (key->devId != INVALID_DEVID) - #endif + #endif { - ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, res, - WC_PQC_SIG_TYPE_DILITHIUM, key); + ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, NULL, 0, + WC_HASH_TYPE_NONE, res, WC_PQC_SIG_TYPE_DILITHIUM, key); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ ret = 0; } } - #endif +#endif if (ret == 0) { /* Verify message with signature. */ @@ -8387,6 +8422,22 @@ int wc_dilithium_verify_ctx_hash(const byte* sig, word32 sigLen, ret = BAD_FUNC_ARG; } +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_PqcVerify(sig, sigLen, hash, hashLen, ctx, ctxLen, + hashAlg, res, WC_PQC_SIG_TYPE_DILITHIUM, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } + } +#endif + if (ret == 0) { /* Verify message with signature. */ #ifdef WOLFSSL_WC_DILITHIUM @@ -8892,9 +8943,10 @@ int wc_dilithium_check_key(dilithium_key* key) */ if (ret == 0) { - params = key->params; unsigned int allocSz; + params = key->params; + /* s1-L, s2-K, t0-K, t-K, t1-K */ allocSz = params->s1Sz + 4 * params->s2Sz; #if !defined(WC_DILITHIUM_CACHE_MATRIX_A) @@ -8908,6 +8960,7 @@ int wc_dilithium_check_key(dilithium_key* key) ret = MEMORY_E; } else { + XMEMSET(s1, 0, allocSz); s2 = s1 + params->s1Sz / sizeof(*s1); t0 = s2 + params->s2Sz / sizeof(*s2); t = t0 + params->s2Sz / sizeof(*t0); @@ -9197,6 +9250,9 @@ int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key) if (key->t1 == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->t1, 0, key->params->s2Sz); + } } #endif } @@ -9213,6 +9269,9 @@ int wc_dilithium_import_public(const byte* in, word32 inLen, dilithium_key* key) if (key->a == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->a, 0, key->params->aSz); + } } #endif } @@ -9282,6 +9341,9 @@ static int dilithium_set_priv_key(const byte* priv, word32 privSz, if (key->a == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->a, 0, params->aSz); + } } } #endif @@ -9303,6 +9365,9 @@ static int dilithium_set_priv_key(const byte* priv, word32 privSz, if (key->s1 == NULL) { ret = MEMORY_E; } + else { + XMEMSET(key->s1, 0, params->s1Sz + params->s2Sz + params->s2Sz); + } if (ret == 0) { /* Set pointers into allocated memory. */ key->s2 = key->s1 + params->s1Sz / sizeof(*key->s1); @@ -9524,6 +9589,42 @@ static int mapOidToSecLevel(word32 oid) } } +/* Get OID sum from dilithium key */ +int dilithium_get_oid_sum(dilithium_key* key, int* keyFormat) { + int ret = 0; + + #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) + if (key->params == NULL) { + ret = BAD_FUNC_ARG; + } + else if (key->params->level == WC_ML_DSA_44_DRAFT) { + *keyFormat = DILITHIUM_LEVEL2k; + } + else if (key->params->level == WC_ML_DSA_65_DRAFT) { + *keyFormat = DILITHIUM_LEVEL3k; + } + else if (key->params->level == WC_ML_DSA_87_DRAFT) { + *keyFormat = DILITHIUM_LEVEL5k; + } + else + #endif /* WOLFSSL_DILITHIUM_FIPS204_DRAFT */ + if (key->level == WC_ML_DSA_44) { + *keyFormat = ML_DSA_LEVEL2k; + } + else if (key->level == WC_ML_DSA_65) { + *keyFormat = ML_DSA_LEVEL3k; + } + else if (key->level == WC_ML_DSA_87) { + *keyFormat = ML_DSA_LEVEL5k; + } + else { + /* Level is not set */ + ret = ALGO_ID_E; + } + + return ret; +} + #if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) /* Decode the DER encoded Dilithium key. @@ -9563,8 +9664,13 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, if (ret == 0) { /* Get OID sum for level. */ + if (key->level == 0) { /* Check first, because key->params will be NULL + * when key->level = 0 */ + /* Level not set by caller, decode from DER */ + keytype = ANONk; + } #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) - if (key->params == NULL) { + else if (key->params == NULL) { ret = BAD_FUNC_ARG; } else if (key->params->level == WC_ML_DSA_44_DRAFT) { @@ -9576,9 +9682,8 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, else if (key->params->level == WC_ML_DSA_87_DRAFT) { keytype = DILITHIUM_LEVEL5k; } - else #endif - if (key->level == WC_ML_DSA_44) { + else if (key->level == WC_ML_DSA_44) { keytype = ML_DSA_LEVEL2k; } else if (key->level == WC_ML_DSA_65) { @@ -9588,8 +9693,7 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, keytype = ML_DSA_LEVEL5k; } else { - /* Level not set by caller, decode from DER */ - keytype = ANONk; /* 0, not a valid key type in this situation*/ + ret = BAD_FUNC_ARG; } } diff --git a/src/wolfcrypt/src/dsa.c b/src/wolfcrypt/src/dsa.c index 7fb7945..5be431a 100644 --- a/src/wolfcrypt/src/dsa.c +++ b/src/wolfcrypt/src/dsa.c @@ -1,6 +1,6 @@ /* dsa.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,19 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_DSA #include #include -#include -#include #include #include diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index f010568..6d4cd4d 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -1,6 +1,6 @@ /* ecc.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set HAVE_ECC there */ -#include +#include #ifdef WOLFSSL_ECC_NO_SMALL_STACK #undef WOLFSSL_SMALL_STACK @@ -161,9 +154,6 @@ ECC Curve Sizes: #include #include -#include -#include -#include #ifdef WOLFSSL_HAVE_SP_ECC #include @@ -257,12 +247,12 @@ ECC Curve Sizes: /* macro guard for ecc_check_pubkey_order functionality */ -#if !defined(WOLFSSL_SP_MATH) && \ - !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ - !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ - !defined(WOLFSSL_SE050) && !defined(WOLFSSL_STM32_PKA) && \ - (!defined(WOLF_CRYPTO_CB_ONLY_ECC) || defined(WOLFSSL_IMXRT1170_CAAM) || \ - defined(WOLFSSL_QNX_CAAM)) +#if (!defined(NO_ECC_CHECK_PUBKEY_ORDER) && \ + !defined(WOLF_CRYPTO_CB_ONLY_ECC) && \ + !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ + !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ + !defined(WOLFSSL_SE050) && !defined(WOLFSSL_STM32_PKA)) || \ + defined(WOLFSSL_IMXRT1170_CAAM) || defined(WOLFSSL_QNX_CAAM) /* CAAM builds use public key validation as a means to check if an * imported private key is an encrypted black key or not */ @@ -1441,7 +1431,7 @@ size_t wc_ecc_get_sets_count(void) { #if defined(HAVE_COMP_KEY) && defined(HAVE_ECC_KEY_EXPORT) static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen); #endif -#ifdef HAVE_ECC_CHECK_PUBKEY_ORDER +#if defined(HAVE_ECC_CHECK_PUBKEY_ORDER) && !defined(WOLFSSL_SP_MATH) static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order); #endif @@ -1576,7 +1566,7 @@ static int xil_mpi_import(mp_int *mpi, #endif #define DECLARE_CURVE_SPECS(intcount) ecc_curve_spec* curve = NULL - #define ALLOC_CURVE_SPECS(intcount, err) WC_DO_NOTHING + #define ALLOC_CURVE_SPECS(intcount, err) (err) = MP_OKAY #define FREE_CURVE_SPECS() WC_DO_NOTHING #elif defined(WOLFSSL_SMALL_STACK) #ifdef WOLFSSL_SP_MATH_ALL @@ -1588,13 +1578,17 @@ static int xil_mpi_import(mp_int *mpi, curve->spec_count = intcount #define ALLOC_CURVE_SPECS(intcount, err) \ + do { \ spec_ints = (unsigned char*)XMALLOC(MP_INT_SIZEOF(MP_BITS_CNT( \ MAX_ECC_BITS_USE)) * (intcount), NULL, \ DYNAMIC_TYPE_ECC); \ if (spec_ints == NULL) \ (err) = MEMORY_E; \ - else \ - curve->spec_ints = spec_ints + else { \ + curve->spec_ints = spec_ints; \ + (err) = MP_OKAY; \ + } \ + } while (0) #else #define DECLARE_CURVE_SPECS(intcount) \ mp_int* spec_ints = NULL; \ @@ -1604,12 +1598,16 @@ static int xil_mpi_import(mp_int *mpi, curve->spec_count = intcount #define ALLOC_CURVE_SPECS(intcount, err) \ + do { \ spec_ints = (mp_int*)XMALLOC(sizeof(mp_int) * (intcount), NULL, \ DYNAMIC_TYPE_ECC); \ if (spec_ints == NULL) \ (err) = MEMORY_E; \ - else \ - curve->spec_ints = spec_ints + else { \ + curve->spec_ints = spec_ints; \ + (err) = MP_OKAY; \ + } \ + } while (0) #endif #define FREE_CURVE_SPECS() \ XFREE(spec_ints, NULL, DYNAMIC_TYPE_ECC) @@ -1632,7 +1630,7 @@ static int xil_mpi_import(mp_int *mpi, curve->spec_ints = spec_ints; \ curve->spec_count = (intcount) #endif - #define ALLOC_CURVE_SPECS(intcount, err) WC_DO_NOTHING + #define ALLOC_CURVE_SPECS(intcount, err) (err) = MP_OKAY #define FREE_CURVE_SPECS() WC_DO_NOTHING #endif /* ECC_CACHE_CURVE */ @@ -6653,6 +6651,10 @@ static int wc_ecc_sign_hash_async(const byte* in, word32 inlen, byte* out, #if !defined(WOLFSSL_ASYNC_CRYPT_SW) && defined(HAVE_ECC_CDH) DECLARE_CURVE_SPECS(1); ALLOC_CURVE_SPECS(1, err); + if (err != MP_OKAY) { + WOLFSSL_MSG("ALLOC_CURVE_SPECS failed"); + break; + } /* get curve order */ err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER); @@ -7508,7 +7510,7 @@ static int _HMAC_K(byte* K, word32 KSz, byte* V, word32 VSz, ret = init = wc_HmacInit(&hmac, heap, INVALID_DEVID); if (ret == 0) - ret = wc_HmacSetKey(&hmac, hashType, K, KSz); + ret = wc_HmacSetKey(&hmac, (int)hashType, K, KSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, V, VSz); @@ -7938,6 +7940,9 @@ int wc_ecc_free(ecc_key* key) #endif #ifdef WOLFSSL_SE050 +#ifdef WOLFSSL_SE050_AUTO_ERASE + wc_se050_erase_object(key->keyId); +#endif se050_ecc_free_key(key); #endif @@ -9213,6 +9218,7 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, #elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2]; byte hashcopy[ECC_MAX_CRYPTO_HW_SIZE] = {0}; +#elif defined(WOLFSSL_SE050) #else int curveLoaded = 0; DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT); @@ -9380,7 +9386,6 @@ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, #if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC) if (!curveLoaded) { - err = 0; /* potential for NOT_COMPILED_IN error from SP attempt */ ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT, err); if (err != 0) { return err; @@ -9929,11 +9934,7 @@ int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen, #endif /* HAVE_ECC_KEY_EXPORT */ -#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \ - !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SE050) && \ - !defined(WOLFSSL_STM32_PKA) && \ - (!defined(WOLF_CRYPTO_CB_ONLY_ECC) || defined(WOLFSSL_QNX_CAAM) || \ - defined(WOLFSSL_IMXRT1170_CAAM)) +#ifdef HAVE_ECC_CHECK_PUBKEY_ORDER /* is ecc point on curve described by dp ? */ static int _ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) @@ -10134,6 +10135,10 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) return BAD_FUNC_ARG; ALLOC_CURVE_SPECS(3, err); + if (err != MP_OKAY) { + WOLFSSL_MSG("ALLOC_CURVE_SPECS failed"); + return err; + } #ifdef WOLFSSL_NO_MALLOC res = &lcl_res; @@ -10275,7 +10280,6 @@ static int ecc_check_privkey_gen_helper(ecc_key* key) /* Hardware based private key, so this operation is not supported */ err = MP_OKAY; /* just report success */ #else - err = MP_OKAY; ALLOC_CURVE_SPECS(2, err); /* load curve info */ @@ -10367,9 +10371,10 @@ static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) return err; } -#endif /* (FIPS v5 or later || WOLFSSL_VALIDATE_ECC_KEYGEN) &&!WOLFSSL_KCAPI_ECC */ +#endif /* (FIPS v5 or later || WOLFSSL_VALIDATE_ECC_KEYGEN) && \ + !WOLFSSL_KCAPI_ECC */ -#ifdef HAVE_ECC_CHECK_PUBKEY_ORDER +#ifndef WOLFSSL_SP_MATH /* validate order * pubkey = point at infinity, 0 on success */ static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order) @@ -10442,12 +10447,8 @@ static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, return err; } #endif /* !WOLFSSL_SP_MATH */ +#endif /* HAVE_ECC_CHECK_PUBKEY_ORDER */ -#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && - !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 && !WOLFSSL_STM32_PKA && - (!WOLF_CRYPTO_CB_ONLY_ECC || WOLFSSL_QNX_CAAM || - WOLFSSL_IMXRT1170_CAAM) - */ #ifdef OPENSSL_EXTRA int wc_ecc_get_generator(ecc_point* ecp, int curve_idx) @@ -10475,7 +10476,7 @@ int wc_ecc_get_generator(ecc_point* ecp, int curve_idx) return err; } -#endif /* OPENSSLALL */ +#endif /* OPENSSL_EXTRA */ /* Validate the public key per SP 800-56Ar3 section 5.6.2.3.3, @@ -10487,7 +10488,7 @@ int wc_ecc_get_generator(ecc_point* ecp, int curve_idx) static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) { int err = MP_OKAY; -#ifdef HAVE_ECC_CHECK_PUBKEY_ORDER +#if defined(HAVE_ECC_CHECK_PUBKEY_ORDER) && !defined(WOLFSSL_SP_MATH) mp_int* b = NULL; #ifdef USE_ECC_B_PARAM DECLARE_CURVE_SPECS(4); @@ -10497,13 +10498,23 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) #endif DECLARE_CURVE_SPECS(3); #endif /* USE_ECC_B_PARAM */ -#endif /* HAVE_ECC_CHECK_PUBKEY_ORDER */ +#endif ASSERT_SAVED_VECTOR_REGISTERS(); if (key == NULL) return BAD_FUNC_ARG; +#ifndef HAVE_ECC_CHECK_PUBKEY_ORDER + /* consider key check success on HW crypto + * ex: ATECC508/608A, CryptoCell and Silabs + * + * consider key check success on most Crypt Cb only builds + */ + err = MP_OKAY; + +#else + #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { @@ -10538,15 +10549,6 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) #endif #ifndef WOLFSSL_SP_MATH -#ifndef HAVE_ECC_CHECK_PUBKEY_ORDER - /* consider key check success on HW crypto - * ex: ATECC508/608A, CryptoCell and Silabs - * - * consider key check success on most Crypt Cb only builds - */ - err = MP_OKAY; - -#else #ifdef USE_ECC_B_PARAM ALLOC_CURVE_SPECS(4, err); #else @@ -10670,11 +10672,13 @@ static int _ecc_validate_public_key(ecc_key* key, int partial, int priv) #endif FREE_CURVE_SPECS(); -#endif /* HAVE_ECC_CHECK_PUBKEY_ORDER */ #else + /* The single precision math curve is not available */ err = WC_KEY_SIZE_E; #endif /* !WOLFSSL_SP_MATH */ +#endif /* HAVE_ECC_CHECK_PUBKEY_ORDER */ + (void)partial; (void)priv; return err; @@ -11352,7 +11356,7 @@ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, #endif #ifdef WOLFSSL_MAXQ10XX_CRYPTO - if (ret == 0) { + if ((ret == 0) && (key->devId != INVALID_DEVID)) { ret = wc_MAXQ10XX_EccSetKey(key, key->dp->size); } #elif defined(WOLFSSL_SILABS_SE_ACCEL) diff --git a/src/wolfcrypt/src/eccsi.c b/src/wolfcrypt/src/eccsi.c index 79b7a65..537e64c 100644 --- a/src/wolfcrypt/src/eccsi.c +++ b/src/wolfcrypt/src/eccsi.c @@ -1,6 +1,6 @@ /* eccsi.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef NO_INLINE #include @@ -36,7 +30,6 @@ #ifdef WOLFCRYPT_HAVE_ECCSI -#include #include #include #ifdef WOLFSSL_HAVE_SP_ECC diff --git a/src/wolfcrypt/src/ed25519.c b/src/wolfcrypt/src/ed25519.c index fd80f86..85f7f8a 100644 --- a/src/wolfcrypt/src/ed25519.c +++ b/src/wolfcrypt/src/ed25519.c @@ -1,6 +1,6 @@ /* ed25519.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,12 +28,7 @@ * Check that the private key didn't change during the signing operations. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set HAVE_ED25519 there */ -#include +#include #ifdef HAVE_ED25519 #if FIPS_VERSION3_GE(6,0,0) @@ -48,8 +43,6 @@ #include #include -#include -#include #include #ifdef NO_INLINE #include @@ -1104,6 +1097,9 @@ void wc_ed25519_free(ed25519_key* key) #endif #ifdef WOLFSSL_SE050 +#ifdef WOLFSSL_SE050_AUTO_ERASE + wc_se050_erase_object(key->keyId); +#endif se050_ed25519_free_key(key); #endif diff --git a/src/wolfcrypt/src/ed448.c b/src/wolfcrypt/src/ed448.c index 1598c9c..a5e63a1 100644 --- a/src/wolfcrypt/src/ed448.c +++ b/src/wolfcrypt/src/ed448.c @@ -1,6 +1,6 @@ /* ed448.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -30,12 +30,7 @@ * Check that the private key didn't change during the signing operations. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set HAVE_ED448 there */ -#include +#include #ifdef HAVE_ED448 #if FIPS_VERSION3_GE(6,0,0) @@ -49,7 +44,6 @@ #endif #include -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/error.c b/src/wolfcrypt/src/error.c index 0deb668..af5ba36 100644 --- a/src/wolfcrypt/src/error.c +++ b/src/wolfcrypt/src/error.c @@ -1,6 +1,6 @@ /* error.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - -#include +#include #ifdef _MSC_VER /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */ @@ -645,9 +638,15 @@ const char* wc_GetErrorString(int error) case PBKDF2_KAT_FIPS_E: return "wolfCrypt FIPS PBKDF2 Known Answer Test Failure"; + case WC_KEY_MISMATCH_E: + return "key values mismatch"; + case DEADLOCK_AVERTED_E: return "Deadlock averted -- retry the call"; + case ASCON_AUTH_E: + return "ASCON Authentication check fail"; + case MAX_CODE_E: case WC_SPAN1_MIN_CODE_E: case MIN_CODE_E: diff --git a/src/wolfcrypt/src/evp.c b/src/wolfcrypt/src/evp.c index c3eb12e..7054f80 100644 --- a/src/wolfcrypt/src/evp.c +++ b/src/wolfcrypt/src/evp.c @@ -1,6 +1,6 @@ /* evp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_EVP_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -52,67 +47,67 @@ static const struct s_ent { const char *name; } md_tbl[] = { #ifndef NO_MD4 - {WC_HASH_TYPE_MD4, WC_NID_md4, "MD4"}, + {WC_HASH_TYPE_MD4, WC_NID_md4, WC_SN_md4}, #endif /* NO_MD4 */ #ifndef NO_MD5 - {WC_HASH_TYPE_MD5, WC_NID_md5, "MD5"}, + {WC_HASH_TYPE_MD5, WC_NID_md5, WC_SN_md5}, #endif /* NO_MD5 */ #ifndef NO_SHA - {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA1"}, + {WC_HASH_TYPE_SHA, WC_NID_sha1, WC_SN_sha1}, {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA"}, /* Leave for backwards compatibility */ #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - {WC_HASH_TYPE_SHA224, WC_NID_sha224, "SHA224"}, + {WC_HASH_TYPE_SHA224, WC_NID_sha224, WC_SN_sha224}, #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 - {WC_HASH_TYPE_SHA256, WC_NID_sha256, "SHA256"}, + {WC_HASH_TYPE_SHA256, WC_NID_sha256, WC_SN_sha256}, #endif #ifdef WOLFSSL_SHA384 - {WC_HASH_TYPE_SHA384, WC_NID_sha384, "SHA384"}, + {WC_HASH_TYPE_SHA384, WC_NID_sha384, WC_SN_sha384}, #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 - {WC_HASH_TYPE_SHA512, WC_NID_sha512, "SHA512"}, + {WC_HASH_TYPE_SHA512, WC_NID_sha512, WC_SN_sha512}, #endif /* WOLFSSL_SHA512 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, "SHA512_224"}, + {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, WC_SN_sha512_224}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, "SHA512_256"}, + {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, WC_SN_sha512_256}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ #ifndef WOLFSSL_NOSHA3_224 - {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, "SHA3_224"}, + {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, WC_SN_sha3_224}, #endif #ifndef WOLFSSL_NOSHA3_256 - {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, "SHA3_256"}, + {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, WC_SN_sha3_256}, #endif #ifndef WOLFSSL_NOSHA3_384 - {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, "SHA3_384"}, + {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, WC_SN_sha3_384}, #endif #ifndef WOLFSSL_NOSHA3_512 - {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, "SHA3_512"}, + {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, WC_SN_sha3_512}, #endif #ifdef WOLFSSL_SM3 - {WC_HASH_TYPE_SM3, WC_NID_sm3, "SM3"}, + {WC_HASH_TYPE_SM3, WC_NID_sm3, WC_SN_sm3}, #endif /* WOLFSSL_SHA512 */ #ifdef HAVE_BLAKE2 - {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, "BLAKE2B512"}, + {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, WC_SN_blake2b512}, #endif #ifdef HAVE_BLAKE2S - {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, "BLAKE2S256"}, + {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, WC_SN_blake2s256}, #endif #ifdef WOLFSSL_SHAKE128 - {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, "SHAKE128"}, + {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, WC_SN_shake128}, #endif #ifdef WOLFSSL_SHAKE256 - {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, "SHAKE256"}, + {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, WC_SN_shake256}, #endif {WC_HASH_TYPE_NONE, 0, NULL} }; @@ -1059,6 +1054,14 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, } switch (ctx->cipherType) { + case WC_NULL_CIPHER_TYPE: + if (out == NULL) { + WOLFSSL_MSG("Bad argument"); + return WOLFSSL_FAILURE; + } + XMEMMOVE(out, in, inl); + *outl = inl; + return WOLFSSL_SUCCESS; #if !defined(NO_AES) && defined(HAVE_AESGCM) case WC_AES_128_GCM_TYPE: case WC_AES_192_GCM_TYPE: @@ -2046,6 +2049,165 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) else return 0; } +/* Getter function for cipher type string + * + * cipherType cipherType enum value to get string for + * + * Returns string representation of the cipher type or NULL if not found + */ +const char* wolfSSL_EVP_CIPHER_type_string(unsigned int cipherType) +{ + WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_type_string"); + + switch (cipherType) { +#ifndef NO_DES3 + case WC_DES_CBC_TYPE: return EVP_DES_CBC; + case WC_DES_EDE3_CBC_TYPE: return EVP_DES_EDE3_CBC; + case WC_DES_ECB_TYPE: return EVP_DES_ECB; + case WC_DES_EDE3_ECB_TYPE: return EVP_DES_EDE3_ECB; +#endif +#if !defined(NO_AES) + #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CBC_TYPE: return EVP_AES_128_CBC; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CBC_TYPE: return EVP_AES_192_CBC; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CBC_TYPE: return EVP_AES_256_CBC; + #endif + #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ + #if defined(WOLFSSL_AES_CFB) + #ifndef WOLFSSL_NO_AES_CFB_1_8 + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB1_TYPE: return EVP_AES_128_CFB1; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB1_TYPE: return EVP_AES_192_CFB1; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB1_TYPE: return EVP_AES_256_CFB1; + #endif + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB8_TYPE: return EVP_AES_128_CFB8; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB8_TYPE: return EVP_AES_192_CFB8; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB8_TYPE: return EVP_AES_256_CFB8; + #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB128_TYPE: return EVP_AES_128_CFB128; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB128_TYPE: return EVP_AES_192_CFB128; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB128_TYPE: return EVP_AES_256_CFB128; + #endif + #endif /* WOLFSSL_AES_CFB */ + #if defined(WOLFSSL_AES_OFB) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_OFB_TYPE: return EVP_AES_128_OFB; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_OFB_TYPE: return EVP_AES_192_OFB; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_OFB_TYPE: return EVP_AES_256_OFB; + #endif + #endif /* WOLFSSL_AES_OFB */ + #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_XTS_TYPE: return EVP_AES_128_XTS; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_XTS_TYPE: return EVP_AES_256_XTS; + #endif + #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ + #if defined(HAVE_AESGCM) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_GCM_TYPE: return EVP_AES_128_GCM; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_GCM_TYPE: return EVP_AES_192_GCM; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_GCM_TYPE: return EVP_AES_256_GCM; + #endif + #endif /* HAVE_AESGCM */ + #if defined(HAVE_AESCCM) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CCM_TYPE: return EVP_AES_128_CCM; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CCM_TYPE: return EVP_AES_192_CCM; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CCM_TYPE: return EVP_AES_256_CCM; + #endif + #endif /* HAVE_AESCCM */ + #if defined(WOLFSSL_AES_COUNTER) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CTR_TYPE: return EVP_AES_128_CTR; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CTR_TYPE: return EVP_AES_192_CTR; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CTR_TYPE: return EVP_AES_256_CTR; + #endif + #endif /* WOLFSSL_AES_COUNTER */ + #if defined(HAVE_AES_ECB) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_ECB_TYPE: return EVP_AES_128_ECB; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_ECB_TYPE: return EVP_AES_192_ECB; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_ECB_TYPE: return EVP_AES_256_ECB; + #endif + #endif /* HAVE_AES_ECB */ +#endif /* !NO_AES */ +#if defined(HAVE_ARIA) + case WC_ARIA_128_GCM_TYPE: return EVP_ARIA_128_GCM; + case WC_ARIA_192_GCM_TYPE: return EVP_ARIA_192_GCM; + case WC_ARIA_256_GCM_TYPE: return EVP_ARIA_256_GCM; +#endif /* HAVE_ARIA */ +#ifndef NO_RC4 + case WC_ARC4_TYPE: return EVP_ARC4; +#endif +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + case WC_CHACHA20_POLY1305_TYPE: return EVP_CHACHA20_POLY1305; +#endif +#ifdef HAVE_CHACHA + case WC_CHACHA20_TYPE: return EVP_CHACHA20; +#endif +#ifdef WOLFSSL_SM4_ECB + case WC_SM4_ECB_TYPE: return EVP_SM4_ECB; +#endif +#ifdef WOLFSSL_SM4_CBC + case WC_SM4_CBC_TYPE: return EVP_SM4_CBC; +#endif +#ifdef WOLFSSL_SM4_CTR + case WC_SM4_CTR_TYPE: return EVP_SM4_CTR; +#endif +#ifdef WOLFSSL_SM4_GCM + case WC_SM4_GCM_TYPE: return EVP_SM4_GCM; +#endif +#ifdef WOLFSSL_SM4_CCM + case WC_SM4_CCM_TYPE: return EVP_SM4_CCM; +#endif + case WC_NULL_CIPHER_TYPE: return EVP_NULL; + default: + return NULL; + } +} + int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) { if (cipher == NULL) @@ -2633,7 +2795,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ return WOLFSSL_FAILURE; } if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { - if (wc_HKDF(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, + if (wc_HKDF((int)hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, (word32)*keylen) != 0) { @@ -2642,7 +2804,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ } } else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { - if (wc_HKDF_Extract(hkdfHashType, ctx->pkey->hkdfSalt, + if (wc_HKDF_Extract((int)hkdfHashType, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, key) != 0) { WOLFSSL_MSG("wc_HKDF_Extract failed."); @@ -2659,7 +2821,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ } } else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { - if (wc_HKDF_Expand(hkdfHashType, ctx->pkey->hkdfKey, + if (wc_HKDF_Expand((int)hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, (word32)*keylen) != 0) { @@ -3316,14 +3478,44 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, */ int wolfSSL_EVP_PKEY_bits(const WOLFSSL_EVP_PKEY *pkey) { - int bytes; + int ret = 0; - if (pkey == NULL) return 0; - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); - if ((bytes = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey)) ==0) return 0; - if (bytes < 0) + if (pkey == NULL) return 0; - return bytes*8; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); + + switch (pkey->type) { +#ifndef NO_RSA + case WC_EVP_PKEY_RSA: + ret = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(pkey->rsa)); + break; +#endif /* !NO_RSA */ + +#ifndef NO_DSA + case WC_EVP_PKEY_DSA: + if (pkey->dsa == NULL || + (!pkey->dsa->exSet && + SetDsaExternal(pkey->dsa) != WOLFSSL_SUCCESS)) + break; + ret = wolfSSL_BN_num_bytes(pkey->dsa->p); + break; +#endif + +#ifdef HAVE_ECC + case WC_EVP_PKEY_EC: + if (pkey->ecc == NULL || pkey->ecc->internal == NULL) { + WOLFSSL_MSG("No ECC key has been set"); + break; + } + ret = wc_ecc_size((ecc_key*)(pkey->ecc->internal)); + break; +#endif /* HAVE_ECC */ + + default: + break; + } + return ret > 0 ? ret * 8 : 0; } @@ -3530,12 +3722,11 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, return ret; } -/* Get the size in bytes for WOLFSSL_EVP_PKEY key +/* Get the maximum suitable size for the operations that can be done with pkey * * pkey WOLFSSL_EVP_PKEY structure to get key size of * - * returns the size of a key on success which is the maximum size of a - * signature + * returns the recommended size of buffers */ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) { @@ -3563,7 +3754,7 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) WOLFSSL_MSG("No ECC key has been set"); break; } - return wc_ecc_size((ecc_key*)(pkey->ecc->internal)); + return wc_ecc_sig_size((ecc_key*)(pkey->ecc->internal)); #endif /* HAVE_ECC */ default: @@ -3732,7 +3923,6 @@ int wolfSSL_EVP_PKEY_missing_parameters(WOLFSSL_EVP_PKEY *pkey) int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) { int ret = -1; /* failure */ - int a_sz = 0, b_sz = 0; if (a == NULL || b == NULL) return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); @@ -3745,40 +3935,47 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) switch (a->type) { #ifndef NO_RSA case WC_EVP_PKEY_RSA: - a_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)); - b_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)); + if (wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)) <= 0 || + wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)) <= 0) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (mp_cmp(&((RsaKey*)a->rsa->internal)->n, + &((RsaKey*)b->rsa->internal)->n) != MP_EQ) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (mp_cmp(&((RsaKey*)a->rsa->internal)->e, + &((RsaKey*)b->rsa->internal)->e) != MP_EQ) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } break; #endif /* !NO_RSA */ #ifdef HAVE_ECC case WC_EVP_PKEY_EC: if (a->ecc == NULL || a->ecc->internal == NULL || - b->ecc == NULL || b->ecc->internal == NULL) { + b->ecc == NULL || b->ecc->internal == NULL || + wc_ecc_size((ecc_key*)a->ecc->internal) <= 0 || + wc_ecc_size((ecc_key*)b->ecc->internal) <= 0 || + a->ecc->group == NULL || b->ecc->group == NULL) { return ret; } - a_sz = wc_ecc_size((ecc_key*)(a->ecc->internal)); - b_sz = wc_ecc_size((ecc_key*)(b->ecc->internal)); + + /* check curve */ + if (a->ecc->group->curve_idx != b->ecc->group->curve_idx) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (wc_ecc_cmp_point(&((ecc_key*)a->ecc->internal)->pubkey, + &((ecc_key*)b->ecc->internal)->pubkey) != 0) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } break; #endif /* HAVE_ECC */ default: return WS_RETURN_CODE(ret, -2); } /* switch (a->type) */ - /* check size */ - if (a_sz <= 0 || b_sz <= 0 || a_sz != b_sz) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - - /* check public key size */ - if (a->pkey_sz > 0 && b->pkey_sz > 0 && a->pkey_sz != b->pkey_sz) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - - /* check public key */ - if (a->pkey.ptr && b->pkey.ptr) { - if (XMEMCMP(a->pkey.ptr, b->pkey.ptr, (size_t)a->pkey_sz) != 0) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - } #if defined(WOLFSSL_ERROR_CODE_OPENSSL) ret = 1; /* the keys match */ #else @@ -3795,18 +3992,11 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) static int DH_param_check(WOLFSSL_DH* dh_key) { int ret = WOLFSSL_SUCCESS; - WOLFSSL_BN_CTX* ctx = NULL; WOLFSSL_BIGNUM *num1 = NULL; WOLFSSL_BIGNUM *num2 = NULL; WOLFSSL_ENTER("DH_param_check"); - ctx = wolfSSL_BN_CTX_new(); - if (ctx == NULL) { - WOLFSSL_MSG("failed to allocate memory"); - return WOLFSSL_FAILURE; - } - num1 = wolfSSL_BN_new(); num2 = wolfSSL_BN_new(); if (num1 == NULL || num2 == NULL) { @@ -3840,7 +4030,7 @@ static int DH_param_check(WOLFSSL_DH* dh_key) dh_key->q != NULL) { if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) + wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, NULL) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("BN_mod_exp failed"); @@ -3855,7 +4045,7 @@ static int DH_param_check(WOLFSSL_DH* dh_key) #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) /* test if the number q is prime. */ if (ret == WOLFSSL_SUCCESS && - (wolfSSL_BN_is_prime_ex(dh_key->q, 64, ctx, NULL) <= 0)) { + (wolfSSL_BN_is_prime_ex(dh_key->q, 64, NULL, NULL) <= 0)) { WOLFSSL_MSG("dh_key->q is not prime or error during check."); ret = WOLFSSL_FAILURE; } /* else TODO check q div q - 1. need BN_div */ @@ -3863,7 +4053,6 @@ static int DH_param_check(WOLFSSL_DH* dh_key) } /* clean up */ - wolfSSL_BN_CTX_free(ctx); wolfSSL_BN_free(num1); wolfSSL_BN_free(num2); @@ -4043,9 +4232,13 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, pkey->ecc); if (ecdsaSig == NULL) return WOLFSSL_FAILURE; + /* get signature length only */ ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); - if (ret <= 0 || ret > (int)*siglen) + if (ret <= 0 || ret > (int)*siglen) { + wolfSSL_ECDSA_SIG_free(ecdsaSig); return WOLFSSL_FAILURE; + } + /* perform validation of signature */ ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sigret); wolfSSL_ECDSA_SIG_free(ecdsaSig); if (ret <= 0 || ret > (int)*siglen) @@ -4262,69 +4455,69 @@ static int wolfssl_evp_md_to_hash_type(const WOLFSSL_EVP_MD *type, int ret = 0; #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { *hashType = WC_SHA256; } else #endif #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { *hashType = WC_SHA; } else #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { *hashType = WC_SHA224; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { *hashType = WC_SHA384; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { *hashType = WC_SHA512; } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { *hashType = WC_SHA3_224; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { *hashType = WC_SHA3_256; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { *hashType = WC_SHA3_384; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { *hashType = WC_SHA3_512; } else #endif #endif #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { *hashType = WC_SM3; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { *hashType = WC_MD5; } else @@ -4644,7 +4837,9 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, ctx->pctx->pkey->ecc); if (ecdsaSig == NULL) break; - len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sig); + len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); + if (len > 0 && (size_t)len <= *siglen) + len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sig); wolfSSL_ECDSA_SIG_free(ecdsaSig); if (len == 0) break; @@ -4867,6 +5062,7 @@ int wolfSSL_PKCS5_PBKDF2_HMAC(const char *pass, int passlen, { const char *nostring = ""; int ret = 0; + enum wc_HashType pbkdf2HashType; if (pass == NULL) { passlen = 0; @@ -4875,8 +5071,10 @@ int wolfSSL_PKCS5_PBKDF2_HMAC(const char *pass, int passlen, passlen = (int)XSTRLEN(pass); } + pbkdf2HashType = EvpMd2MacType(digest); + ret = wc_PBKDF2((byte*)out, (byte*)pass, passlen, (byte*)salt, saltlen, - iter, keylen, EvpMd2MacType(digest)); + iter, keylen, pbkdf2HashType); if (ret == 0) return WOLFSSL_SUCCESS; else @@ -6299,14 +6497,16 @@ void wolfSSL_EVP_init(void) case WC_AES_256_OFB_TYPE: #endif wc_AesFree(&ctx->cipher.aes); - ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; + ctx->flags &= + (unsigned long)~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) case WC_AES_128_XTS_TYPE: case WC_AES_256_XTS_TYPE: wc_AesXtsFree(&ctx->cipher.xts); - ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; + ctx->flags &= + (unsigned long)~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #endif #endif /* AES */ @@ -6875,7 +7075,7 @@ void wolfSSL_EVP_init(void) ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_256BITKEY); break; default: - WOLFSSL_MSG("Not implemented cipherType"); + WOLFSSL_MSG("Unimplemented cipherType"); return WOLFSSL_NOT_IMPLEMENTED; /* This should never happen */ } if (ret != 0) { @@ -8258,9 +8458,9 @@ void wolfSSL_EVP_init(void) } #endif /* !NO_AES || !NO_DES3 */ - static int IsCipherTypeAEAD(unsigned char cipherType) + static int IsCipherTypeAEAD(unsigned int type) { - switch (cipherType) { + switch (type) { case WC_AES_128_GCM_TYPE: case WC_AES_192_GCM_TYPE: case WC_AES_256_GCM_TYPE: @@ -9367,22 +9567,22 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); if (type != NULL) { - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { ret = WC_NID_md5WithRSAEncryption; } - else if (XSTRCMP(type, "SHA1") == 0) { + else if (XSTRCMP(type, WC_SN_sha1) == 0) { ret = WC_NID_sha1WithRSAEncryption; } - else if (XSTRCMP(type, "SHA224") == 0) { + else if (XSTRCMP(type, WC_SN_sha224) == 0) { ret = WC_NID_sha224WithRSAEncryption; } - else if (XSTRCMP(type, "SHA256") == 0) { + else if (XSTRCMP(type, WC_SN_sha256) == 0) { ret = WC_NID_sha256WithRSAEncryption; } - else if (XSTRCMP(type, "SHA384") == 0) { + else if (XSTRCMP(type, WC_SN_sha384) == 0) { ret = WC_NID_sha384WithRSAEncryption; } - else if (XSTRCMP(type, "SHA512") == 0) { + else if (XSTRCMP(type, WC_SN_sha512) == 0) { ret = WC_NID_sha512WithRSAEncryption; } } @@ -9936,54 +10136,44 @@ static const struct alias { const char *alias; } digest_alias_tbl[] = { - {"MD4", "md4"}, - {"MD5", "md5"}, - {"SHA1", "sha1"}, - {"SHA1", "SHA"}, - {"SHA224", "sha224"}, - {"SHA256", "sha256"}, - {"SHA384", "sha384"}, - {"SHA512", "sha512"}, - {"SHA512_224", "sha512_224"}, - {"SHA3_224", "sha3_224"}, - {"SHA3_256", "sha3_256"}, - {"SHA3_384", "sha3_384"}, - {"SHA3_512", "sha3_512"}, - {"SM3", "sm3"}, - {"BLAKE2B512", "blake2b512"}, - {"BLAKE2S256", "blake2s256"}, - {"SHAKE128", "shake128"}, - {"SHAKE256", "shake256"}, + {WC_SN_md4, "md4"}, + {WC_SN_md5, "md5"}, + {WC_SN_sha1, "sha1"}, + {WC_SN_sha1, "SHA"}, + {WC_SN_sha224, "sha224"}, + {WC_SN_sha256, "sha256"}, + {WC_SN_sha384, "sha384"}, + {WC_SN_sha512, "sha512"}, + {WC_SN_sha512_224, "sha512_224"}, + {WC_SN_sha3_224, "sha3_224"}, + {WC_SN_sha3_256, "sha3_256"}, + {WC_SN_sha3_384, "sha3_384"}, + {WC_SN_sha3_512, "sha3_512"}, + {WC_SN_sm3, "sm3"}, + {WC_SN_blake2b512, "blake2b512"}, + {WC_SN_blake2s256, "blake2s256"}, + {WC_SN_shake128, "shake128"}, + {WC_SN_shake256, "shake256"}, { NULL, NULL} }; const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) { - char nameUpper[15]; /* 15 bytes should be enough for any name */ - size_t i; - const struct alias *al; const struct s_ent *ent; - for (i = 0; i < sizeof(nameUpper) && name[i] != '\0'; i++) { - nameUpper[i] = (char)XTOUPPER((unsigned char) name[i]); - } - if (i < sizeof(nameUpper)) - nameUpper[i] = '\0'; - else - return NULL; - - name = nameUpper; - for (al = digest_alias_tbl; al->name != NULL; al++) + for (al = digest_alias_tbl; al->name != NULL; al++) { if(XSTRCMP(name, al->alias) == 0) { name = al->name; break; } + } - for (ent = md_tbl; ent->name != NULL; ent++) + for (ent = md_tbl; ent->name != NULL; ent++) { if(XSTRCMP(name, ent->name) == 0) { return (WOLFSSL_EVP_MD *)ent->name; } + } return NULL; } @@ -10017,7 +10207,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) { WOLFSSL_ENTER("EVP_md4"); - return wolfSSL_EVP_get_digestbyname("MD4"); + return wolfSSL_EVP_get_digestbyname(WC_SN_md4); } #endif /* !NO_MD4 */ @@ -10028,7 +10218,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) { WOLFSSL_ENTER("EVP_md5"); - return wolfSSL_EVP_get_digestbyname("MD5"); + return wolfSSL_EVP_get_digestbyname(WC_SN_md5); } #endif /* !NO_MD5 */ @@ -10040,8 +10230,8 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) */ const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) { - WOLFSSL_ENTER("EVP_blake2b512"); - return wolfSSL_EVP_get_digestbyname("BLAKE2b512"); + WOLFSSL_ENTER("wolfSSL_EVP_blake2b512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_blake2b512); } #endif @@ -10080,7 +10270,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) { WOLFSSL_ENTER("EVP_sha1"); - return wolfSSL_EVP_get_digestbyname("SHA1"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha1); } #endif /* NO_SHA */ @@ -10089,7 +10279,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) { WOLFSSL_ENTER("EVP_sha224"); - return wolfSSL_EVP_get_digestbyname("SHA224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha224); } #endif /* WOLFSSL_SHA224 */ @@ -10098,7 +10288,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) { WOLFSSL_ENTER("EVP_sha256"); - return wolfSSL_EVP_get_digestbyname("SHA256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha256); } #ifdef WOLFSSL_SHA384 @@ -10106,7 +10296,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) { WOLFSSL_ENTER("EVP_sha384"); - return wolfSSL_EVP_get_digestbyname("SHA384"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha384); } #endif /* WOLFSSL_SHA384 */ @@ -10116,7 +10306,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) { WOLFSSL_ENTER("EVP_sha512"); - return wolfSSL_EVP_get_digestbyname("SHA512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512); } #ifndef WOLFSSL_NOSHA512_224 @@ -10124,7 +10314,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) { WOLFSSL_ENTER("EVP_sha512_224"); - return wolfSSL_EVP_get_digestbyname("SHA512_224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512_224); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10133,7 +10323,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) { WOLFSSL_ENTER("EVP_sha512_256"); - return wolfSSL_EVP_get_digestbyname("SHA512_256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512_256); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10145,7 +10335,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) { WOLFSSL_ENTER("EVP_sha3_224"); - return wolfSSL_EVP_get_digestbyname("SHA3_224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_224); } #endif /* WOLFSSL_NOSHA3_224 */ @@ -10154,7 +10344,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) { WOLFSSL_ENTER("EVP_sha3_256"); - return wolfSSL_EVP_get_digestbyname("SHA3_256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_256); } #endif /* WOLFSSL_NOSHA3_256 */ @@ -10162,7 +10352,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) { WOLFSSL_ENTER("EVP_sha3_384"); - return wolfSSL_EVP_get_digestbyname("SHA3_384"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_384); } #endif /* WOLFSSL_NOSHA3_384 */ @@ -10170,7 +10360,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) { WOLFSSL_ENTER("EVP_sha3_512"); - return wolfSSL_EVP_get_digestbyname("SHA3_512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_512); } #endif /* WOLFSSL_NOSHA3_512 */ @@ -10196,7 +10386,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sm3(void) { WOLFSSL_ENTER("EVP_sm3"); - return wolfSSL_EVP_get_digestbyname("SM3"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sm3); } #endif /* WOLFSSL_SM3 */ @@ -10482,17 +10672,21 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) /* Not an error since an unused struct could be free'd or * reset. */ break; - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD4: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + wc_Shake128_Free(&ctx->hash.digest.shake); + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + wc_Shake256_Free(&ctx->hash.digest.shake); + break; #endif + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: default: ret = WOLFSSL_FAILURE; break; @@ -10526,76 +10720,92 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) XMEMSET(&ctx->hash.digest, 0, sizeof(WOLFSSL_Hasher)); } else #ifndef NO_SHA - if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, "SHA1") == 0)) { + if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, WC_SN_sha1) == 0)) { ret = wolfSSL_SHA_Init(&(ctx->hash.digest.sha)); } else #endif #ifndef NO_SHA256 - if (XSTRCMP(md, "SHA256") == 0) { + if (XSTRCMP(md, WC_SN_sha256) == 0) { ret = wolfSSL_SHA256_Init(&(ctx->hash.digest.sha256)); } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(md, "SHA224") == 0) { + if (XSTRCMP(md, WC_SN_sha224) == 0) { ret = wolfSSL_SHA224_Init(&(ctx->hash.digest.sha224)); } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(md, "SHA384") == 0) { + if (XSTRCMP(md, WC_SN_sha384) == 0) { ret = wolfSSL_SHA384_Init(&(ctx->hash.digest.sha384)); } else #endif #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - if (XSTRCMP(md, "SHA512_224") == 0) { + if (XSTRCMP(md, WC_SN_sha512_224) == 0) { ret = wolfSSL_SHA512_224_Init(&(ctx->hash.digest.sha512)); } else #endif #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - if (XSTRCMP(md, "SHA512_256") == 0) { + if (XSTRCMP(md, WC_SN_sha512_256) == 0) { ret = wolfSSL_SHA512_256_Init(&(ctx->hash.digest.sha512)); } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(md, "SHA512") == 0) { + if (XSTRCMP(md, WC_SN_sha512) == 0) { ret = wolfSSL_SHA512_Init(&(ctx->hash.digest.sha512)); } else #endif #ifndef NO_MD4 - if (XSTRCMP(md, "MD4") == 0) { + if (XSTRCMP(md, WC_SN_md4) == 0) { wolfSSL_MD4_Init(&(ctx->hash.digest.md4)); } else #endif #ifndef NO_MD5 - if (XSTRCMP(md, "MD5") == 0) { + if (XSTRCMP(md, WC_SN_md5) == 0) { ret = wolfSSL_MD5_Init(&(ctx->hash.digest.md5)); } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(md, "SHA3_224") == 0) { + if (XSTRCMP(md, WC_SN_sha3_224) == 0) { ret = wolfSSL_SHA3_224_Init(&(ctx->hash.digest.sha3_224)); } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(md, "SHA3_256") == 0) { + if (XSTRCMP(md, WC_SN_sha3_256) == 0) { ret = wolfSSL_SHA3_256_Init(&(ctx->hash.digest.sha3_256)); } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(md, "SHA3_384") == 0) { + if (XSTRCMP(md, WC_SN_sha3_384) == 0) { ret = wolfSSL_SHA3_384_Init(&(ctx->hash.digest.sha3_384)); } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(md, "SHA3_512") == 0) { + if (XSTRCMP(md, WC_SN_sha3_512) == 0) { ret = wolfSSL_SHA3_512_Init(&(ctx->hash.digest.sha3_512)); } else #endif + #ifdef WOLFSSL_SHAKE128 + if (XSTRCMP(md, WC_SN_shake128) == 0) { + if (wc_InitShake128(&(ctx->hash.digest.shake), NULL, + INVALID_DEVID) != 0) { + ret = WOLFSSL_FAILURE; + } + } else + #endif + #ifdef WOLFSSL_SHAKE256 + if (XSTRCMP(md, WC_SN_shake256) == 0) { + if (wc_InitShake256(&(ctx->hash.digest.shake), NULL, + INVALID_DEVID) != 0) { + ret = WOLFSSL_FAILURE; + } + } else + #endif #endif #ifdef WOLFSSL_SM3 - if (XSTRCMP(md, "SM3") == 0) { + if (XSTRCMP(md, WC_SN_sm3) == 0) { ret = wc_InitSm3(&ctx->hash.digest.sm3, NULL, INVALID_DEVID); if (ret == 0) { ret = WOLFSSL_SUCCESS; @@ -10723,17 +10933,28 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } break; #endif - case WC_HASH_TYPE_NONE: - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + if (wc_Shake128_Update(&ctx->hash.digest.shake, + (const byte*)data, (word32)sz) == 0) { + + ret = WOLFSSL_SUCCESS; + } + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + if (wc_Shake256_Update(&ctx->hash.digest.shake, + (const byte*)data, (word32)sz) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; #endif + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: default: return WOLFSSL_FAILURE; } @@ -10742,14 +10963,11 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, - unsigned int* s) + static int wolfSSL_EVP_DigestFinal_Common(WOLFSSL_EVP_MD_CTX* ctx, + unsigned char* md, unsigned int* s, enum wc_HashType macType) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); - enum wc_HashType macType; - WOLFSSL_ENTER("EVP_DigestFinal"); - macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 @@ -10847,23 +11065,84 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } if (s) *s = WC_SM3_DIGEST_SIZE; break; + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + if (wc_Shake128_Final(&ctx->hash.digest.shake, md, *s) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + if (wc_Shake256_Final(&ctx->hash.digest.shake, md, *s) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; #endif case WC_HASH_TYPE_NONE: case WC_HASH_TYPE_MD2: case WC_HASH_TYPE_MD5_SHA: case WC_HASH_TYPE_BLAKE2B: case WC_HASH_TYPE_BLAKE2S: + default: + return WOLFSSL_FAILURE; + } + + return ret; + } + + int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, + unsigned int* s) + { + enum wc_HashType macType; + + WOLFSSL_ENTER("wolfSSL_EVP_DigestFinal"); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); + switch (macType) { + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5: + case WC_HASH_TYPE_SHA: + case WC_HASH_TYPE_SHA224: + case WC_HASH_TYPE_SHA256: + case WC_HASH_TYPE_SHA384: + case WC_HASH_TYPE_SHA512: + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #endif /* !WOLFSSL_NOSHA512_224 */ + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + case WC_HASH_TYPE_SHA3_256: + case WC_HASH_TYPE_SHA3_384: + case WC_HASH_TYPE_SHA3_512: + #ifdef WOLFSSL_SM3 + case WC_HASH_TYPE_SM3: + #endif + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + break; + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + *s = 16; /* if mixing up XOF with plain digest 128 bit is + * default for SHAKE128 */ + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + *s = 32; /* if mixing up XOF with plain digest 256 bit is + * default for SHAKE256 */ + break; #endif default: return WOLFSSL_FAILURE; } - - return ret; + return wolfSSL_EVP_DigestFinal_Common(ctx, md, s, macType); } /* WOLFSSL_SUCCESS on ok */ @@ -10874,6 +11153,46 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return wolfSSL_EVP_DigestFinal(ctx, md, s); } + + /* XOF stands for extendable-output functions. This is used for algos such + * as SHAKE256. + * + * returns 1 (WOLFSSL_SUCCESS) on success and 0 (WOLFSSL_FAILURE) on fail */ + int wolfSSL_EVP_DigestFinalXOF(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *md, + size_t sz) + { + unsigned int len; + enum wc_HashType macType; + + WOLFSSL_ENTER("wolfSSL_EVP_DigestFinalXOF"); + len = (unsigned int)sz; + + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); + return wolfSSL_EVP_DigestFinal_Common(ctx, md, &len, macType); + } + + + unsigned long wolfSSL_EVP_MD_flags(const WOLFSSL_EVP_MD *md) + { + enum wc_HashType macType; + + macType = EvpMd2MacType(md); + switch ((int)macType) { + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif + return WOLFSSL_EVP_MD_FLAG_XOF; + default: + return 0; + } + } + + void wolfSSL_EVP_cleanup(void) { /* nothing to do here */ @@ -10884,6 +11203,10 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) WOLFSSL_MSG("wolfSSL_get_digestbynid"); switch(id) { +#ifndef NO_MD4 + case WC_NID_md4: + return wolfSSL_EVP_md4(); +#endif #ifndef NO_MD5 case WC_NID_md5: return wolfSSL_EVP_md5(); @@ -10928,64 +11251,64 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) } #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { return WC_SHA_BLOCK_SIZE; } else #endif #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { return WC_SHA256_BLOCK_SIZE; } else #endif #ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { + if (XSTRCMP(type, WC_SN_md4) == 0) { return WC_MD4_BLOCK_SIZE; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { return WC_MD5_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { return WC_SHA224_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { return WC_SHA384_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { return WC_SHA512_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { return WC_SHA3_224_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { return WC_SHA3_256_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { return WC_SHA3_384_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { return WC_SHA3_512_BLOCK_SIZE; - } + } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { return WC_SM3_BLOCK_SIZE; } else #endif @@ -11003,74 +11326,74 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) } #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { return WC_SHA_DIGEST_SIZE; } else #endif #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { return WC_SHA256_DIGEST_SIZE; } else #endif #ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { + if (XSTRCMP(type, WC_SN_md4) == 0) { return WC_MD4_DIGEST_SIZE; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { return WC_MD5_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { return WC_SHA224_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { return WC_SHA384_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { return WC_SHA512_DIGEST_SIZE; } else #ifndef WOLFSSL_NOSHA512_224 - if (XSTRCMP(type, "SHA512_224") == 0) { + if (XSTRCMP(type, WC_SN_sha512_224) == 0) { return WC_SHA512_224_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA512_256 - if (XSTRCMP(type, "SHA512_256") == 0) { + if (XSTRCMP(type, WC_SN_sha512_256) == 0) { return WC_SHA512_256_DIGEST_SIZE; } else #endif #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { return WC_SHA3_224_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { return WC_SHA3_256_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { return WC_SHA3_384_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { return WC_SHA3_512_DIGEST_SIZE; } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { return WC_SM3_DIGEST_SIZE; } #endif @@ -12182,7 +12505,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_RSA: #if !defined(NO_RSA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyRSA( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12198,7 +12521,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_EC: #if defined(HAVE_ECC) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyEC( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12214,7 +12537,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_DSA: #if !defined(NO_DSA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyDSA( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12230,7 +12553,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_DH: #if defined(WOLFSSL_DH_EXTRA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyDH( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12263,64 +12586,64 @@ int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp, } #ifndef NO_SHA - if ((XSTRCMP("SHA", evp) == 0) || (XSTRCMP("SHA1", evp) == 0)) { + if ((XSTRCMP("SHA", evp) == 0) || (XSTRCMP(WC_SN_sha1, evp) == 0)) { hash = WC_HASH_TYPE_SHA; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP("SHA224", evp) == 0) { + if (XSTRCMP(WC_SN_sha224, evp) == 0) { hash = WC_HASH_TYPE_SHA224; } else #endif #ifndef NO_SHA256 - if (XSTRCMP("SHA256", evp) == 0) { + if (XSTRCMP(WC_SN_sha256, evp) == 0) { hash = WC_HASH_TYPE_SHA256; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP("SHA384", evp) == 0) { + if (XSTRCMP(WC_SN_sha384, evp) == 0) { hash = WC_HASH_TYPE_SHA384; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP("SHA512", evp) == 0) { + if (XSTRCMP(WC_SN_sha512, evp) == 0) { hash = WC_HASH_TYPE_SHA512; } else #ifndef WOLFSSL_NOSHA512_224 - if (XSTRCMP("SHA512_224", evp) == 0) { + if (XSTRCMP(WC_SN_sha512_224, evp) == 0) { hash = WC_HASH_TYPE_SHA512_224; } else #endif #ifndef WOLFSSL_NOSHA512_256 - if (XSTRCMP("SHA512_256", evp) == 0) { + if (XSTRCMP(WC_SN_sha512_256, evp) == 0) { hash = WC_HASH_TYPE_SHA512_256; } else #endif #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP("SHA3_224", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_224, evp) == 0) { hash = WC_HASH_TYPE_SHA3_224; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP("SHA3_256", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_256, evp) == 0) { hash = WC_HASH_TYPE_SHA3_256; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP("SHA3_384", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_384, evp) == 0) { hash = WC_HASH_TYPE_SHA3_384; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP("SHA3_512", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_512, evp) == 0) { hash = WC_HASH_TYPE_SHA3_512; } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP("SM3", evp) == 0) { + if (XSTRCMP(WC_SN_sm3, evp) == 0) { hash = WC_HASH_TYPE_SM3; } else #endif @@ -12330,12 +12653,12 @@ int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp, } else #endif #ifndef NO_MD4 - if (XSTRCMP("MD4", evp) == 0) { + if (XSTRCMP(WC_SN_md4, evp) == 0) { hash = WC_HASH_TYPE_MD4; } else #endif #ifndef NO_MD5 - if (XSTRCMP("MD5", evp) == 0) { + if (XSTRCMP(WC_SN_md5, evp) == 0) { hash = WC_HASH_TYPE_MD5; } else #endif diff --git a/src/wolfcrypt/src/ext_lms.c b/src/wolfcrypt/src/ext_lms.c index 70dfa5b..00a3e55 100644 --- a/src/wolfcrypt/src/ext_lms.c +++ b/src/wolfcrypt/src/ext_lms.c @@ -1,6 +1,6 @@ /* ext_lms.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #if defined(WOLFSSL_HAVE_LMS) && defined(HAVE_LIBLMS) @@ -1049,4 +1043,12 @@ int wc_LmsKey_Verify(LmsKey * key, const byte * sig, word32 sigSz, return 0; } +const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz) +{ + if ((priv == NULL) || (privSz < 16)) { + return NULL; + } + return priv - 16; +} + #endif /* WOLFSSL_HAVE_LMS && HAVE_LIBLMS */ diff --git a/src/wolfcrypt/src/ext_mlkem.c b/src/wolfcrypt/src/ext_mlkem.c new file mode 100644 index 0000000..3a9ccee --- /dev/null +++ b/src/wolfcrypt/src/ext_mlkem.c @@ -0,0 +1,762 @@ +/* ext_mlkem.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_WC_MLKEM) +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#if defined (HAVE_LIBOQS) + +#include + +static const char* OQS_ID2name(int id) { + switch (id) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: return OQS_KEM_alg_ml_kem_512; + case WC_ML_KEM_768: return OQS_KEM_alg_ml_kem_768; + case WC_ML_KEM_1024: return OQS_KEM_alg_ml_kem_1024; + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case KYBER_LEVEL1: return OQS_KEM_alg_kyber_512; + case KYBER_LEVEL3: return OQS_KEM_alg_kyber_768; + case KYBER_LEVEL5: return OQS_KEM_alg_kyber_1024; + #endif + default: break; + } + return NULL; +} + +int ext_mlkem_enabled(int id) +{ + const char * name = OQS_ID2name(id); + return OQS_KEM_alg_is_enabled(name); +} +#endif + +/******************************************************************************/ +/* Initializer and cleanup functions. */ + +/** + * Initialize the Kyber key. + * + * @param [out] key Kyber key object to initialize. + * @param [in] type Type of key: KYBER512, KYBER768, KYBER1024. + * @param [in] heap Dynamic memory hint. + * @param [in] devId Device Id. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or type is unrecognized. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_Init(MlKemKey* key, int type, void* heap, int devId) +{ + int ret = 0; + + /* Validate key. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Validate type. */ + switch (type) { +#ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + #ifdef HAVE_LIBOQS + case WC_ML_KEM_768: + case WC_ML_KEM_1024: + #endif /* HAVE_LIBOQS */ +#endif +#ifdef WOLFSSL_MLKEM_KYBER + case KYBER_LEVEL1: + #ifdef HAVE_LIBOQS + case KYBER_LEVEL3: + case KYBER_LEVEL5: + #endif /* HAVE_LIBOQS */ +#endif + break; + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } + if (ret == 0) { + /* Zero out all data. */ + XMEMSET(key, 0, sizeof(*key)); + + /* Keep type for parameters. */ + key->type = type; + +#ifdef WOLF_CRYPTO_CB + key->devCtx = NULL; + key->devId = devId; +#endif + } + + (void)heap; + (void)devId; + + return ret; +} + +/** + * Free the Kyber key object. + * + * @param [in, out] key Kyber key object to dispose of. + */ +int wc_MlKemKey_Free(MlKemKey* key) +{ + if (key != NULL) { + /* Ensure all private data is zeroed. */ + ForceZero(key, sizeof(*key)); + } + + return 0; +} + +/******************************************************************************/ +/* Data size getters. */ + +/** + * Get the size in bytes of encoded private key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded private key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_PrivateKeySize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef HAVE_LIBOQS + /* NOTE: SHAKE and AES variants have the same length private key. */ + if (ret == 0) { + switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_secret_key; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_secret_key; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_secret_key; + break; + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case KYBER_LEVEL1: + *len = OQS_KEM_kyber_512_length_secret_key; + break; + case KYBER_LEVEL3: + *len = OQS_KEM_kyber_768_length_secret_key; + break; + case KYBER_LEVEL5: + *len = OQS_KEM_kyber_1024_length_secret_key; + break; + #endif + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } +#endif /* HAVE_LIBOQS */ + + return ret; +} + +/** + * Get the size in bytes of encoded public key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded public key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_PublicKeySize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef HAVE_LIBOQS + /* NOTE: SHAKE and AES variants have the same length public key. */ + if (ret == 0) { + switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_public_key; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_public_key; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_public_key; + break; + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case KYBER_LEVEL1: + *len = OQS_KEM_kyber_512_length_public_key; + break; + case KYBER_LEVEL3: + *len = OQS_KEM_kyber_768_length_public_key; + break; + case KYBER_LEVEL5: + *len = OQS_KEM_kyber_1024_length_public_key; + break; + #endif + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } +#endif /* HAVE_LIBOQS */ + + return ret; +} + +/** + * Get the size in bytes of cipher text for key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of cipher text in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_CipherTextSize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef HAVE_LIBOQS + /* NOTE: SHAKE and AES variants have the same length ciphertext. */ + if (ret == 0) { + switch (key->type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + *len = OQS_KEM_ml_kem_512_length_ciphertext; + break; + case WC_ML_KEM_768: + *len = OQS_KEM_ml_kem_768_length_ciphertext; + break; + case WC_ML_KEM_1024: + *len = OQS_KEM_ml_kem_1024_length_ciphertext; + break; + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case KYBER_LEVEL1: + *len = OQS_KEM_kyber_512_length_ciphertext; + break; + case KYBER_LEVEL3: + *len = OQS_KEM_kyber_768_length_ciphertext; + break; + case KYBER_LEVEL5: + *len = OQS_KEM_kyber_1024_length_ciphertext; + break; + #endif + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } +#endif /* HAVE_LIBOQS */ + + return ret; +} + +/** + * Size of a shared secret in bytes. Always KYBER_SS_SZ. + * + * @param [in] key Kyber key object. Not used. + * @param [out] Size of the shared secret created with a Kyber key. + * @return 0 on success. + * @return 0 to indicate success. + */ +int wc_MlKemKey_SharedSecretSize(MlKemKey* key, word32* len) +{ + (void)key; + /* Validate parameters. */ + if (len == NULL) { + return BAD_FUNC_ARG; + } + + *len = KYBER_SS_SZ; + + return 0; +} + +/******************************************************************************/ +/* Cryptographic operations. */ + +/** + * Make a Kyber key object using a random number generator. + * + * NOTE: rng is ignored. OQS doesn't use our RNG. + * + * @param [in, out] key Kyber key ovject. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rng is NULL. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_MakeKey(MlKemKey* key, WC_RNG* rng) +{ + int ret = 0; +#ifdef HAVE_LIBOQS + const char* algName = NULL; + OQS_KEM *kem = NULL; +#endif + + /* Validate parameter. */ + if (key == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLF_CRYPTO_CB + #ifndef WOLF_CRYPTO_CB_FIND + if (key->devId != INVALID_DEVID) + #endif + { + ret = wc_CryptoCb_MakePqcKemKey(rng, WC_PQC_KEM_TYPE_KYBER, + key->type, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } +#endif + +#ifdef HAVE_LIBOQS + if (ret == 0) { + algName = OQS_ID2name(key->type); + if (algName == NULL) { + ret = BAD_FUNC_ARG; + } + } + + if (ret == 0) { + kem = OQS_KEM_new(algName); + if (kem == NULL) { + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + ret = wolfSSL_liboqsRngMutexLock(rng); + } + if (ret == 0) { + if (OQS_KEM_keypair(kem, key->pub, key->priv) != + OQS_SUCCESS) { + ret = BAD_FUNC_ARG; + } + } + wolfSSL_liboqsRngMutexUnlock(); + OQS_KEM_free(kem); +#endif /* HAVE_LIBOQS */ + + if (ret != 0) { + ForceZero(key, sizeof(*key)); + } + + return ret; +} + +/** + * Make a Kyber key object using random data. + * + * @param [in, out] key Kyber key ovject. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rand is NULL. + * @return BUFFER_E when length is not KYBER_MAKEKEY_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_MakeKeyWithRandom(MlKemKey* key, const unsigned char* rand, + int len) +{ + (void)rand; + (void)len; + /* OQS doesn't support external randomness. */ + return wc_MlKemKey_MakeKey(key, NULL); +} + +/** + * Encapsulate with random number generator and derive secret. + * + * @param [in] key Kyber key object. + * @param [out] ct Cipher text. + * @param [out] ss Shared secret generated. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ct, ss or RNG is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_Encapsulate(MlKemKey* key, unsigned char* ct, unsigned char* ss, + WC_RNG* rng) +{ + int ret = 0; +#ifdef WOLF_CRYPTO_CB + word32 ctlen = 0; +#endif +#ifdef HAVE_LIBOQS + const char * algName = NULL; + OQS_KEM *kem = NULL; +#endif + + (void)rng; + + /* Validate parameters. */ + if ((key == NULL) || (ct == NULL) || (ss == NULL)) { + ret = BAD_FUNC_ARG; + } + +#ifdef WOLF_CRYPTO_CB + if (ret == 0) { + ret = wc_MlKemKey_CipherTextSize(key, &ctlen); + } + if ((ret == 0) + #ifndef WOLF_CRYPTO_CB_FIND + && (key->devId != INVALID_DEVID) + #endif + ) { + ret = wc_CryptoCb_PqcEncapsulate(ct, ctlen, ss, KYBER_SS_SZ, rng, + WC_PQC_KEM_TYPE_KYBER, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } +#endif + +#ifdef HAVE_LIBOQS + if (ret == 0) { + algName = OQS_ID2name(key->type); + if (algName == NULL) { + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + kem = OQS_KEM_new(algName); + if (kem == NULL) { + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + ret = wolfSSL_liboqsRngMutexLock(rng); + } + if (ret == 0) { + if (OQS_KEM_encaps(kem, ct, ss, key->pub) != OQS_SUCCESS) { + ret = BAD_FUNC_ARG; + } + } + wolfSSL_liboqsRngMutexUnlock(); + OQS_KEM_free(kem); +#endif /* HAVE_LIBOQS */ + + return ret; +} + +/** + * Encapsulate with random data and derive secret. + * + * @param [out] ct Cipher text. + * @param [out] ss Shared secret generated. + * @param [in] rand Random data. + * @param [in] len Random data. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ct, ss or RNG is NULL. + * @return BUFFER_E when len is not KYBER_ENC_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_EncapsulateWithRandom(MlKemKey* key, unsigned char* ct, + unsigned char* ss, const unsigned char* rand, int len) +{ + (void)rand; + (void)len; + /* OQS doesn't support external randomness. */ + return wc_MlKemKey_Encapsulate(key, ct, ss, NULL); +} + +/** + * Decapsulate the cipher text to calculate the shared secret. + * + * Validates the cipher text by encapsulating and comparing with data passed in. + * + * @param [in] key Kyber key object. + * @param [out] ss Shared secret. + * @param [in] ct Cipher text. + * @param [in] len Length of cipher text. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ss or cr are NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the length of cipher text for the key type. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_Decapsulate(MlKemKey* key, unsigned char* ss, + const unsigned char* ct, word32 len) +{ + int ret = 0; + word32 ctlen = 0; +#ifdef HAVE_LIBOQS + const char * algName = NULL; + OQS_KEM *kem = NULL; +#endif + + /* Validate parameters. */ + if ((key == NULL) || (ss == NULL) || (ct == NULL)) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + ret = wc_MlKemKey_CipherTextSize(key, &ctlen); + } + if ((ret == 0) && (len != ctlen)) { + ret = BUFFER_E; + } + +#ifdef WOLF_CRYPTO_CB + if ((ret == 0) + #ifndef WOLF_CRYPTO_CB_FIND + && (key->devId != INVALID_DEVID) + #endif + ) { + ret = wc_CryptoCb_PqcDecapsulate(ct, ctlen, ss, KYBER_SS_SZ, + WC_PQC_KEM_TYPE_KYBER, key); + if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + return ret; + /* fall-through when unavailable */ + ret = 0; + } +#endif + +#ifdef HAVE_LIBOQS + if (ret == 0) { + algName = OQS_ID2name(key->type); + if (algName == NULL) { + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + kem = OQS_KEM_new(algName); + if (kem == NULL) { + ret = BAD_FUNC_ARG; + } + } + if (ret == 0) { + if (OQS_KEM_decaps(kem, ss, ct, key->priv) != OQS_SUCCESS) { + ret = BAD_FUNC_ARG; + } + } + + OQS_KEM_free(kem); +#endif /* HAVE_LIBOQS */ + + return ret; + +} + +/******************************************************************************/ +/* Encoding and decoding functions. */ + +/** + * Decode the private key. + * + * We store the whole thing in the private key buffer. Note this means we cannot + * do the encapsulation operation with the private key. But generally speaking + * this is never done. + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_MlKemKey_DecodePrivateKey(MlKemKey* key, const unsigned char* in, + word32 len) +{ + int ret = 0; + word32 privLen = 0; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = wc_MlKemKey_PrivateKeySize(key, &privLen); + } + + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(key->priv, in, privLen); + } + + return ret; +} + +/** + * Decode public key. + * + * We store the whole thing in the public key buffer. + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_MlKemKey_DecodePublicKey(MlKemKey* key, const unsigned char* in, + word32 len) +{ + int ret = 0; + word32 pubLen = 0; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = wc_MlKemKey_PublicKeySize(key, &pubLen); + } + + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(key->pub, in, pubLen); + } + + return ret; +} + +/** + * Encode the private key. + * + * We stored it as a blob so we can just copy it over. + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or private/public key not + * available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_EncodePrivateKey(MlKemKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int privLen = 0; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = wc_MlKemKey_PrivateKeySize(key, &privLen); + } + + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(out, key->priv, privLen); + } + + return ret; +} + +/** + * Encode the public key. + * + * We stored it as a blob so we can just copy it over. + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or public key not available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_EncodePublicKey(MlKemKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int pubLen = 0; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + ret = wc_MlKemKey_PublicKeySize(key, &pubLen); + } + + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + XMEMCPY(out, key->pub, pubLen); + } + + return ret; +} + +#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_WC_MLKEM */ diff --git a/src/wolfcrypt/src/ext_xmss.c b/src/wolfcrypt/src/ext_xmss.c index 938d513..48912a3 100644 --- a/src/wolfcrypt/src/ext_xmss.c +++ b/src/wolfcrypt/src/ext_xmss.c @@ -1,6 +1,6 @@ /* ext_xmss.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include -#include -#include #include #if defined(WOLFSSL_HAVE_XMSS) && defined(HAVE_LIBXMSS) diff --git a/src/wolfcrypt/src/falcon.c b/src/wolfcrypt/src/falcon.c index b1aabb1..6562a80 100644 --- a/src/wolfcrypt/src/falcon.c +++ b/src/wolfcrypt/src/falcon.c @@ -1,6 +1,6 @@ /* falcon.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,25 +19,19 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* Based on ed448.c and Reworked for Falcon by Anthony Hu. */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif +/* Based on ed448.c and Reworked for Falcon by Anthony Hu. */ -/* in case user set HAVE_PQC there */ -#include +#if defined(HAVE_PQC) && defined(HAVE_FALCON) #include -#if defined(HAVE_PQC) && defined(HAVE_FALCON) - #ifdef HAVE_LIBOQS #include #endif #include -#include #ifdef NO_INLINE #include #else @@ -62,6 +56,10 @@ int wc_falcon_sign_msg(const byte* in, word32 inLen, falcon_key* key, WC_RNG* rng) { int ret = 0; +#ifdef HAVE_LIBOQS + OQS_SIG *oqssig = NULL; + size_t localOutLen = 0; +#endif /* sanity check on arguments */ if ((in == NULL) || (out == NULL) || (outLen == NULL) || (key == NULL)) { @@ -73,8 +71,8 @@ int wc_falcon_sign_msg(const byte* in, word32 inLen, if (key->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_PqcSign(in, inLen, out, outLen, rng, - WC_PQC_SIG_TYPE_FALCON, key); + ret = wc_CryptoCb_PqcSign(in, inLen, out, outLen, NULL, 0, + WC_HASH_TYPE_NONE, rng, WC_PQC_SIG_TYPE_FALCON, key); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -83,9 +81,6 @@ int wc_falcon_sign_msg(const byte* in, word32 inLen, #endif #ifdef HAVE_LIBOQS - OQS_SIG *oqssig = NULL; - size_t localOutLen = 0; - if ((ret == 0) && (!key->prvKeySet)) { ret = BAD_FUNC_ARG; } @@ -161,6 +156,9 @@ int wc_falcon_verify_msg(const byte* sig, word32 sigLen, const byte* msg, word32 msgLen, int* res, falcon_key* key) { int ret = 0; +#ifdef HAVE_LIBOQS + OQS_SIG *oqssig = NULL; +#endif if (key == NULL || sig == NULL || msg == NULL || res == NULL) { return BAD_FUNC_ARG; @@ -171,8 +169,8 @@ int wc_falcon_verify_msg(const byte* sig, word32 sigLen, const byte* msg, if (key->devId != INVALID_DEVID) #endif { - ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, res, - WC_PQC_SIG_TYPE_FALCON, key); + ret = wc_CryptoCb_PqcVerify(sig, sigLen, msg, msgLen, NULL, 0, + WC_HASH_TYPE_NONE, res, WC_PQC_SIG_TYPE_FALCON, key); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) return ret; /* fall-through when unavailable */ @@ -181,8 +179,6 @@ int wc_falcon_verify_msg(const byte* sig, word32 sigLen, const byte* msg, #endif #ifdef HAVE_LIBOQS - OQS_SIG *oqssig = NULL; - if ((ret == 0) && (!key->pubKeySet)) { ret = BAD_FUNC_ARG; } @@ -708,12 +704,12 @@ int wc_falcon_export_key(falcon_key* key, byte* priv, word32 *privSz, */ int wc_falcon_check_key(falcon_key* key) { + int ret = 0; + if (key == NULL) { return BAD_FUNC_ARG; } - int ret = 0; - /* The public key is also decoded and stored within the private key buffer * behind the private key. Hence, we can compare both stored public keys. */ if (key->level == 1) { diff --git a/src/wolfcrypt/src/fe_448.c b/src/wolfcrypt/src/fe_448.c index bbf31f6..8cf0245 100644 --- a/src/wolfcrypt/src/fe_448.c +++ b/src/wolfcrypt/src/fe_448.c @@ -1,6 +1,6 @@ /* fe_448.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,11 +24,7 @@ * Reworked for curve448 by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(HAVE_CURVE448) || defined(HAVE_ED448) @@ -1437,56 +1433,56 @@ void fe448_to_bytes(unsigned char* b, const sword32* a) b[ 0] = (byte)(in0 >> 0); b[ 1] = (byte)(in0 >> 8); b[ 2] = (byte)(in0 >> 16); - b[ 3] = (byte)(in0 >> 24) + (byte)((in1 >> 0) << 4); + b[ 3] = (byte)((byte)(in0 >> 24) + (byte)((in1 >> 0) << 4)); b[ 4] = (byte)(in1 >> 4); b[ 5] = (byte)(in1 >> 12); b[ 6] = (byte)(in1 >> 20); b[ 7] = (byte)(in2 >> 0); b[ 8] = (byte)(in2 >> 8); b[ 9] = (byte)(in2 >> 16); - b[10] = (byte)(in2 >> 24) + (byte)((in3 >> 0) << 4); + b[10] = (byte)((byte)(in2 >> 24) + (byte)((in3 >> 0) << 4)); b[11] = (byte)(in3 >> 4); b[12] = (byte)(in3 >> 12); b[13] = (byte)(in3 >> 20); b[14] = (byte)(in4 >> 0); b[15] = (byte)(in4 >> 8); b[16] = (byte)(in4 >> 16); - b[17] = (byte)(in4 >> 24) + (byte)((in5 >> 0) << 4); + b[17] = (byte)((byte)(in4 >> 24) + (byte)((in5 >> 0) << 4)); b[18] = (byte)(in5 >> 4); b[19] = (byte)(in5 >> 12); b[20] = (byte)(in5 >> 20); b[21] = (byte)(in6 >> 0); b[22] = (byte)(in6 >> 8); b[23] = (byte)(in6 >> 16); - b[24] = (byte)(in6 >> 24) + (byte)((in7 >> 0) << 4); + b[24] = (byte)((byte)(in6 >> 24) + (byte)((in7 >> 0) << 4)); b[25] = (byte)(in7 >> 4); b[26] = (byte)(in7 >> 12); b[27] = (byte)(in7 >> 20); b[28] = (byte)(in8 >> 0); b[29] = (byte)(in8 >> 8); b[30] = (byte)(in8 >> 16); - b[31] = (byte)(in8 >> 24) + (byte)((in9 >> 0) << 4); + b[31] = (byte)((byte)(in8 >> 24) + (byte)((in9 >> 0) << 4)); b[32] = (byte)(in9 >> 4); b[33] = (byte)(in9 >> 12); b[34] = (byte)(in9 >> 20); b[35] = (byte)(in10 >> 0); b[36] = (byte)(in10 >> 8); b[37] = (byte)(in10 >> 16); - b[38] = (byte)(in10 >> 24) + (byte)((in11 >> 0) << 4); + b[38] = (byte)((byte)(in10 >> 24) + (byte)((in11 >> 0) << 4)); b[39] = (byte)(in11 >> 4); b[40] = (byte)(in11 >> 12); b[41] = (byte)(in11 >> 20); b[42] = (byte)(in12 >> 0); b[43] = (byte)(in12 >> 8); b[44] = (byte)(in12 >> 16); - b[45] = (byte)(in12 >> 24) + (byte)((in13 >> 0) << 4); + b[45] = (byte)((byte)(in12 >> 24) + (byte)((in13 >> 0) << 4)); b[46] = (byte)(in13 >> 4); b[47] = (byte)(in13 >> 12); b[48] = (byte)(in13 >> 20); b[49] = (byte)(in14 >> 0); b[50] = (byte)(in14 >> 8); b[51] = (byte)(in14 >> 16); - b[52] = (byte)(in14 >> 24) + (byte)((in15 >> 0) << 4); + b[52] = (byte)((byte)(in14 >> 24) + (byte)((in15 >> 0) << 4)); b[53] = (byte)(in15 >> 4); b[54] = (byte)(in15 >> 12); b[55] = (byte)(in15 >> 20); diff --git a/src/wolfcrypt/src/fe_low_mem.c b/src/wolfcrypt/src/fe_low_mem.c index ad10a0e..febc123 100644 --- a/src/wolfcrypt/src/fe_low_mem.c +++ b/src/wolfcrypt/src/fe_low_mem.c @@ -1,6 +1,6 @@ /* fe_low_mem.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* Based from Daniel Beer's public domain work. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - #if defined(HAVE_CURVE25519) || defined(HAVE_ED25519) #if defined(CURVE25519_SMALL) || defined(ED25519_SMALL) /* use slower code that takes less memory */ diff --git a/src/wolfcrypt/src/fe_operations.c b/src/wolfcrypt/src/fe_operations.c index 2910151..135d703 100644 --- a/src/wolfcrypt/src/fe_operations.c +++ b/src/wolfcrypt/src/fe_operations.c @@ -1,6 +1,6 @@ /* fe_operations.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* Based On Daniel J Bernstein's curve25519 Public Domain ref10 work. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - #if defined(HAVE_CURVE25519) || defined(HAVE_ED25519) #if !defined(CURVE25519_SMALL) || !defined(ED25519_SMALL) /* run when not defined to use small memory math */ @@ -128,11 +123,9 @@ void fe_init(void) #if defined(HAVE_CURVE25519) && !defined(CURVE25519_SMALL) && \ !defined(FREESCALE_LTC_ECC) +#ifndef WOLFSSL_CURVE25519_BLINDING int curve25519(byte* q, const byte* n, const byte* p) { -#if 0 - unsigned char e[32]; -#endif fe x1 = {0}; fe x2 = {0}; fe z2 = {0}; @@ -143,17 +136,6 @@ int curve25519(byte* q, const byte* n, const byte* p) int pos = 0; unsigned int swap = 0; - /* Clamp already done during key generation and import */ -#if 0 - { - unsigned int i; - for (i = 0;i < 32;++i) e[i] = n[i]; - e[0] &= 248; - e[31] &= 127; - e[31] |= 64; - } -#endif - fe_frombytes(x1,p); fe_1(x2); fe_0(z2); @@ -163,11 +145,7 @@ int curve25519(byte* q, const byte* n, const byte* p) swap = 0; for (pos = 254;pos >= 0;--pos) { unsigned int b; -#if 0 - b = e[pos / 8] >> (pos & 7); -#else - b = n[pos / 8] >> (pos & 7); -#endif + b = (unsigned int)(n[pos / 8]) >> (pos & 7); b &= 1; swap ^= b; fe_cswap(x2,x3,(int)swap); @@ -203,6 +181,74 @@ int curve25519(byte* q, const byte* n, const byte* p) return 0; } +#else +int curve25519_blind(byte* q, const byte* n, const byte* mask, const byte* p, + const byte* rz) +{ + fe x1 = {0}; + fe x2 = {0}; + fe z2 = {0}; + fe x3 = {0}; + fe z3 = {0}; + fe tmp0 = {0}; + fe tmp1 = {0}; + int pos = 0; + unsigned int b; + + fe_frombytes(x1,p); + fe_1(x2); + fe_0(z2); + fe_copy(x3,x1); + fe_frombytes(z3, rz); + fe_mul(x3, x3, z3); + + /* mask_bits[252] */ + b = mask[31] >> 7; + b &= 1; + fe_cswap(x2,x3,(int)b); + fe_cswap(z2,z3,(int)b); + for (pos = 255;pos >= 1;--pos) { + b = n[pos / 8] >> (pos & 7); + b &= 1; + fe_cswap(x2,x3,(int)b); + fe_cswap(z2,z3,(int)b); + + /* montgomery */ + fe_sub(tmp0,x3,z3); + fe_sub(tmp1,x2,z2); + fe_add(x2,x2,z2); + fe_add(z2,x3,z3); + fe_mul(z3,tmp0,x2); + fe_mul(z2,z2,tmp1); + fe_sq(tmp0,tmp1); + fe_sq(tmp1,x2); + fe_add(x3,z3,z2); + fe_sub(z2,z3,z2); + fe_mul(x2,tmp1,tmp0); + fe_sub(tmp1,tmp1,tmp0); + fe_sq(z2,z2); + fe_mul121666(z3,tmp1); + fe_sq(x3,x3); + fe_add(tmp0,tmp0,z3); + fe_mul(z3,x1,z2); + fe_mul(z2,tmp1,tmp0); + + b = mask[(pos-1) / 8] >> ((pos-1) & 7); + b &= 1; + fe_cswap(x2,x3,(int)b); + fe_cswap(z2,z3,(int)b); + } + b = n[0] & 1; + fe_cswap(x2,x3,(int)b); + fe_cswap(z2,z3,(int)b); + + fe_invert(z2,z2); + fe_mul(x2,x2,z2); + fe_tobytes(q,x2); + + return 0; +} +#endif #endif /* HAVE_CURVE25519 && !CURVE25519_SMALL && !FREESCALE_LTC_ECC */ diff --git a/src/wolfcrypt/src/ge_448.c b/src/wolfcrypt/src/ge_448.c index 81f9c57..a09a92d 100644 --- a/src/wolfcrypt/src/ge_448.c +++ b/src/wolfcrypt/src/ge_448.c @@ -1,6 +1,6 @@ /* ge_448.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -24,17 +24,12 @@ * Reworked for ed448 by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_ED448 #include #include -#include #ifdef NO_INLINE #include #else @@ -369,7 +364,7 @@ int ge448_scalarmult_base(ge448_p2* h, const byte* a) return 0; } -/* Perform a scalar multplication of the base point and public point. +/* Perform a scalar multiplication of the base point and public point. * r = a * p + b * base * Uses a sliding window of 5 bits. * Not constant time. @@ -919,70 +914,70 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) | (word64)((sword64) (d[55]) << 48); /* a * b + d */ - t[ 0] = (word128)dd[ 0] + (word128)((sword128)ad[ 0] * bd[ 0]); - t[ 1] = (word128)dd[ 1] + (word128)((sword128)ad[ 0] * bd[ 1] - + (sword128)ad[ 1] * bd[ 0]); - t[ 2] = (word128)dd[ 2] + (word128)((sword128)ad[ 0] * bd[ 2] - + (sword128)ad[ 1] * bd[ 1] - + (sword128)ad[ 2] * bd[ 0]); - t[ 3] = (word128)dd[ 3] + (word128)((sword128)ad[ 0] * bd[ 3] - + (sword128)ad[ 1] * bd[ 2] - + (sword128)ad[ 2] * bd[ 1] - + (sword128)ad[ 3] * bd[ 0]); - t[ 4] = (word128)dd[ 4] + (word128)((sword128)ad[ 0] * bd[ 4] - + (sword128)ad[ 1] * bd[ 3] - + (sword128)ad[ 2] * bd[ 2] - + (sword128)ad[ 3] * bd[ 1] - + (sword128)ad[ 4] * bd[ 0]); - t[ 5] = (word128)dd[ 5] + (word128)((sword128)ad[ 0] * bd[ 5] - + (sword128)ad[ 1] * bd[ 4] - + (sword128)ad[ 2] * bd[ 3] - + (sword128)ad[ 3] * bd[ 2] - + (sword128)ad[ 4] * bd[ 1] - + (sword128)ad[ 5] * bd[ 0]); - t[ 6] = (word128)dd[ 6] + (word128)((sword128)ad[ 0] * bd[ 6] - + (sword128)ad[ 1] * bd[ 5] - + (sword128)ad[ 2] * bd[ 4] - + (sword128)ad[ 3] * bd[ 3] - + (sword128)ad[ 4] * bd[ 2] - + (sword128)ad[ 5] * bd[ 1] - + (sword128)ad[ 6] * bd[ 0]); - t[ 7] = (word128)dd[ 7] + (word128)((sword128)ad[ 0] * bd[ 7] - + (sword128)ad[ 1] * bd[ 6] - + (sword128)ad[ 2] * bd[ 5] - + (sword128)ad[ 3] * bd[ 4] - + (sword128)ad[ 4] * bd[ 3] - + (sword128)ad[ 5] * bd[ 2] - + (sword128)ad[ 6] * bd[ 1] - + (sword128)ad[ 7] * bd[ 0]); - t[ 8] = (word128) ((sword128)ad[ 1] * bd[ 7] - + (sword128)ad[ 2] * bd[ 6] - + (sword128)ad[ 3] * bd[ 5] - + (sword128)ad[ 4] * bd[ 4] - + (sword128)ad[ 5] * bd[ 3] - + (sword128)ad[ 6] * bd[ 2] - + (sword128)ad[ 7] * bd[ 1]); - t[ 9] = (word128) ((sword128)ad[ 2] * bd[ 7] - + (sword128)ad[ 3] * bd[ 6] - + (sword128)ad[ 4] * bd[ 5] - + (sword128)ad[ 5] * bd[ 4] - + (sword128)ad[ 6] * bd[ 3] - + (sword128)ad[ 7] * bd[ 2]); - t[10] = (word128) ((sword128)ad[ 3] * bd[ 7] - + (sword128)ad[ 4] * bd[ 6] - + (sword128)ad[ 5] * bd[ 5] - + (sword128)ad[ 6] * bd[ 4] - + (sword128)ad[ 7] * bd[ 3]); - t[11] = (word128) ((sword128)ad[ 4] * bd[ 7] - + (sword128)ad[ 5] * bd[ 6] - + (sword128)ad[ 6] * bd[ 5] - + (sword128)ad[ 7] * bd[ 4]); - t[12] = (word128) ((sword128)ad[ 5] * bd[ 7] - + (sword128)ad[ 6] * bd[ 6] - + (sword128)ad[ 7] * bd[ 5]); - t[13] = (word128) ((sword128)ad[ 6] * bd[ 7] - + (sword128)ad[ 7] * bd[ 6]); - t[14] = (word128) (sword128)ad[ 7] * bd[ 7]; + t[ 0] = (word128)(dd[ 0] + (word128)((sword128)ad[ 0] * bd[ 0])); + t[ 1] = (word128)(dd[ 1] + (word128)((sword128)ad[ 0] * bd[ 1] + + (sword128)ad[ 1] * bd[ 0])); + t[ 2] = (word128)(dd[ 2] + (word128)((sword128)ad[ 0] * bd[ 2] + + (sword128)ad[ 1] * bd[ 1] + + (sword128)ad[ 2] * bd[ 0])); + t[ 3] = (word128)(dd[ 3] + (word128)((sword128)ad[ 0] * bd[ 3] + + (sword128)ad[ 1] * bd[ 2] + + (sword128)ad[ 2] * bd[ 1] + + (sword128)ad[ 3] * bd[ 0])); + t[ 4] = (word128)(dd[ 4] + (word128)((sword128)ad[ 0] * bd[ 4] + + (sword128)ad[ 1] * bd[ 3] + + (sword128)ad[ 2] * bd[ 2] + + (sword128)ad[ 3] * bd[ 1] + + (sword128)ad[ 4] * bd[ 0])); + t[ 5] = (word128)(dd[ 5] + (word128)((sword128)ad[ 0] * bd[ 5] + + (sword128)ad[ 1] * bd[ 4] + + (sword128)ad[ 2] * bd[ 3] + + (sword128)ad[ 3] * bd[ 2] + + (sword128)ad[ 4] * bd[ 1] + + (sword128)ad[ 5] * bd[ 0])); + t[ 6] = (word128)(dd[ 6] + (word128)((sword128)ad[ 0] * bd[ 6] + + (sword128)ad[ 1] * bd[ 5] + + (sword128)ad[ 2] * bd[ 4] + + (sword128)ad[ 3] * bd[ 3] + + (sword128)ad[ 4] * bd[ 2] + + (sword128)ad[ 5] * bd[ 1] + + (sword128)ad[ 6] * bd[ 0])); + t[ 7] = (word128)(dd[ 7] + (word128)((sword128)ad[ 0] * bd[ 7] + + (sword128)ad[ 1] * bd[ 6] + + (sword128)ad[ 2] * bd[ 5] + + (sword128)ad[ 3] * bd[ 4] + + (sword128)ad[ 4] * bd[ 3] + + (sword128)ad[ 5] * bd[ 2] + + (sword128)ad[ 6] * bd[ 1] + + (sword128)ad[ 7] * bd[ 0])); + t[ 8] = (word128)( (sword128)ad[ 1] * bd[ 7] + + (sword128)ad[ 2] * bd[ 6] + + (sword128)ad[ 3] * bd[ 5] + + (sword128)ad[ 4] * bd[ 4] + + (sword128)ad[ 5] * bd[ 3] + + (sword128)ad[ 6] * bd[ 2] + + (sword128)ad[ 7] * bd[ 1]); + t[ 9] = (word128)( (sword128)ad[ 2] * bd[ 7] + + (sword128)ad[ 3] * bd[ 6] + + (sword128)ad[ 4] * bd[ 5] + + (sword128)ad[ 5] * bd[ 4] + + (sword128)ad[ 6] * bd[ 3] + + (sword128)ad[ 7] * bd[ 2]); + t[10] = (word128)( (sword128)ad[ 3] * bd[ 7] + + (sword128)ad[ 4] * bd[ 6] + + (sword128)ad[ 5] * bd[ 5] + + (sword128)ad[ 6] * bd[ 4] + + (sword128)ad[ 7] * bd[ 3]); + t[11] = (word128)( (sword128)ad[ 4] * bd[ 7] + + (sword128)ad[ 5] * bd[ 6] + + (sword128)ad[ 6] * bd[ 5] + + (sword128)ad[ 7] * bd[ 4]); + t[12] = (word128)( (sword128)ad[ 5] * bd[ 7] + + (sword128)ad[ 6] * bd[ 6] + + (sword128)ad[ 7] * bd[ 5]); + t[13] = (word128)( (sword128)ad[ 6] * bd[ 7] + + (sword128)ad[ 7] * bd[ 6]); + t[14] = (word128)( (sword128)ad[ 7] * bd[ 7]); t[15] = 0; /* Mod curve order */ @@ -5143,136 +5138,169 @@ void sc448_reduce(byte* b) word32 o; /* Load from bytes */ - t[ 0] = (((sword32)((b[ 0] ) >> 0)) << 0) + t[ 0] = (word64)( + (((sword32)((b[ 0] ) >> 0)) << 0) | (((sword32)((b[ 1] ) >> 0)) << 8) | (((sword32)((b[ 2] ) >> 0)) << 16) - | ((((sword32)((b[ 3] & 0xf )) >> 0)) << 24); - t[ 1] = (((sword32)((b[ 3] ) >> 4)) << 0) + | ((((sword32)((b[ 3] & 0xf )) >> 0)) << 24)); + t[ 1] = (word64)( + (((sword32)((b[ 3] ) >> 4)) << 0) | (((sword32)((b[ 4] ) >> 0)) << 4) | (((sword32)((b[ 5] ) >> 0)) << 12) - | (((sword32)((b[ 6] ) >> 0)) << 20); - t[ 2] = (((sword32)((b[ 7] ) >> 0)) << 0) + | (((sword32)((b[ 6] ) >> 0)) << 20)); + t[ 2] = (word64)( + (((sword32)((b[ 7] ) >> 0)) << 0) | (((sword32)((b[ 8] ) >> 0)) << 8) | (((sword32)((b[ 9] ) >> 0)) << 16) - | ((((sword32)((b[10] & 0xf )) >> 0)) << 24); - t[ 3] = (((sword32)((b[10] ) >> 4)) << 0) + | ((((sword32)((b[10] & 0xf )) >> 0)) << 24)); + t[ 3] = (word64)( + (((sword32)((b[10] ) >> 4)) << 0) | (((sword32)((b[11] ) >> 0)) << 4) | (((sword32)((b[12] ) >> 0)) << 12) - | (((sword32)((b[13] ) >> 0)) << 20); - t[ 4] = (((sword32)((b[14] ) >> 0)) << 0) + | (((sword32)((b[13] ) >> 0)) << 20)); + t[ 4] = (word64)( + (((sword32)((b[14] ) >> 0)) << 0) | (((sword32)((b[15] ) >> 0)) << 8) | (((sword32)((b[16] ) >> 0)) << 16) - | ((((sword32)((b[17] & 0xf )) >> 0)) << 24); - t[ 5] = (((sword32)((b[17] ) >> 4)) << 0) + | ((((sword32)((b[17] & 0xf )) >> 0)) << 24)); + t[ 5] = (word64)( + (((sword32)((b[17] ) >> 4)) << 0) | (((sword32)((b[18] ) >> 0)) << 4) | (((sword32)((b[19] ) >> 0)) << 12) - | (((sword32)((b[20] ) >> 0)) << 20); - t[ 6] = (((sword32)((b[21] ) >> 0)) << 0) + | (((sword32)((b[20] ) >> 0)) << 20)); + t[ 6] = (word64)( + (((sword32)((b[21] ) >> 0)) << 0) | (((sword32)((b[22] ) >> 0)) << 8) | (((sword32)((b[23] ) >> 0)) << 16) - | ((((sword32)((b[24] & 0xf )) >> 0)) << 24); - t[ 7] = (((sword32)((b[24] ) >> 4)) << 0) + | ((((sword32)((b[24] & 0xf )) >> 0)) << 24)); + t[ 7] = (word64)( + (((sword32)((b[24] ) >> 4)) << 0) | (((sword32)((b[25] ) >> 0)) << 4) | (((sword32)((b[26] ) >> 0)) << 12) - | (((sword32)((b[27] ) >> 0)) << 20); - t[ 8] = (((sword32)((b[28] ) >> 0)) << 0) + | (((sword32)((b[27] ) >> 0)) << 20)); + t[ 8] = (word64)( + (((sword32)((b[28] ) >> 0)) << 0) | (((sword32)((b[29] ) >> 0)) << 8) | (((sword32)((b[30] ) >> 0)) << 16) - | ((((sword32)((b[31] & 0xf )) >> 0)) << 24); - t[ 9] = (((sword32)((b[31] ) >> 4)) << 0) + | ((((sword32)((b[31] & 0xf )) >> 0)) << 24)); + t[ 9] = (word64)( + (((sword32)((b[31] ) >> 4)) << 0) | (((sword32)((b[32] ) >> 0)) << 4) | (((sword32)((b[33] ) >> 0)) << 12) - | (((sword32)((b[34] ) >> 0)) << 20); - t[10] = (((sword32)((b[35] ) >> 0)) << 0) + | (((sword32)((b[34] ) >> 0)) << 20)); + t[10] = (word64)( + (((sword32)((b[35] ) >> 0)) << 0) | (((sword32)((b[36] ) >> 0)) << 8) | (((sword32)((b[37] ) >> 0)) << 16) - | ((((sword32)((b[38] & 0xf )) >> 0)) << 24); - t[11] = (((sword32)((b[38] ) >> 4)) << 0) + | ((((sword32)((b[38] & 0xf )) >> 0)) << 24)); + t[11] = (word64)( + (((sword32)((b[38] ) >> 4)) << 0) | (((sword32)((b[39] ) >> 0)) << 4) | (((sword32)((b[40] ) >> 0)) << 12) - | (((sword32)((b[41] ) >> 0)) << 20); - t[12] = (((sword32)((b[42] ) >> 0)) << 0) + | (((sword32)((b[41] ) >> 0)) << 20)); + t[12] = (word64)( + (((sword32)((b[42] ) >> 0)) << 0) | (((sword32)((b[43] ) >> 0)) << 8) | (((sword32)((b[44] ) >> 0)) << 16) - | ((((sword32)((b[45] & 0xf )) >> 0)) << 24); - t[13] = (((sword32)((b[45] ) >> 4)) << 0) + | ((((sword32)((b[45] & 0xf )) >> 0)) << 24)); + t[13] = (word64)( + (((sword32)((b[45] ) >> 4)) << 0) | (((sword32)((b[46] ) >> 0)) << 4) | (((sword32)((b[47] ) >> 0)) << 12) - | (((sword32)((b[48] ) >> 0)) << 20); - t[14] = (((sword32)((b[49] ) >> 0)) << 0) + | (((sword32)((b[48] ) >> 0)) << 20)); + t[14] = (word64)( + (((sword32)((b[49] ) >> 0)) << 0) | (((sword32)((b[50] ) >> 0)) << 8) | (((sword32)((b[51] ) >> 0)) << 16) - | ((((sword32)((b[52] & 0xf )) >> 0)) << 24); - t[15] = (((sword32)((b[52] ) >> 4)) << 0) + | ((((sword32)((b[52] & 0xf )) >> 0)) << 24)); + t[15] = (word64)( + (((sword32)((b[52] ) >> 4)) << 0) | (((sword32)((b[53] ) >> 0)) << 4) | (((sword32)((b[54] ) >> 0)) << 12) - | (((sword32)((b[55] ) >> 0)) << 20); - t[16] = (((sword32)((b[56] ) >> 0)) << 0) + | (((sword32)((b[55] ) >> 0)) << 20)); + t[16] = (word64)( + (((sword32)((b[56] ) >> 0)) << 0) | (((sword32)((b[57] ) >> 0)) << 8) | (((sword32)((b[58] ) >> 0)) << 16) - | ((((sword32)((b[59] & 0xf )) >> 0)) << 24); - t[17] = (((sword32)((b[59] ) >> 4)) << 0) + | ((((sword32)((b[59] & 0xf )) >> 0)) << 24)); + t[17] = (word64)( + (((sword32)((b[59] ) >> 4)) << 0) | (((sword32)((b[60] ) >> 0)) << 4) | (((sword32)((b[61] ) >> 0)) << 12) - | (((sword32)((b[62] ) >> 0)) << 20); - t[18] = (((sword32)((b[63] ) >> 0)) << 0) + | (((sword32)((b[62] ) >> 0)) << 20)); + t[18] = (word64)( + (((sword32)((b[63] ) >> 0)) << 0) | (((sword32)((b[64] ) >> 0)) << 8) | (((sword32)((b[65] ) >> 0)) << 16) - | ((((sword32)((b[66] & 0xf )) >> 0)) << 24); - t[19] = (((sword32)((b[66] ) >> 4)) << 0) + | ((((sword32)((b[66] & 0xf )) >> 0)) << 24)); + t[19] = (word64)( + (((sword32)((b[66] ) >> 4)) << 0) | (((sword32)((b[67] ) >> 0)) << 4) | (((sword32)((b[68] ) >> 0)) << 12) - | (((sword32)((b[69] ) >> 0)) << 20); - t[20] = (((sword32)((b[70] ) >> 0)) << 0) + | (((sword32)((b[69] ) >> 0)) << 20)); + t[20] = (word64)( + (((sword32)((b[70] ) >> 0)) << 0) | (((sword32)((b[71] ) >> 0)) << 8) | (((sword32)((b[72] ) >> 0)) << 16) - | ((((sword32)((b[73] & 0xf )) >> 0)) << 24); - t[21] = (((sword32)((b[73] ) >> 4)) << 0) + | ((((sword32)((b[73] & 0xf )) >> 0)) << 24)); + t[21] = (word64)( + (((sword32)((b[73] ) >> 4)) << 0) | (((sword32)((b[74] ) >> 0)) << 4) | (((sword32)((b[75] ) >> 0)) << 12) - | (((sword32)((b[76] ) >> 0)) << 20); - t[22] = (((sword32)((b[77] ) >> 0)) << 0) + | (((sword32)((b[76] ) >> 0)) << 20)); + t[22] = (word64)( + (((sword32)((b[77] ) >> 0)) << 0) | (((sword32)((b[78] ) >> 0)) << 8) | (((sword32)((b[79] ) >> 0)) << 16) - | ((((sword32)((b[80] & 0xf )) >> 0)) << 24); - t[23] = (((sword32)((b[80] ) >> 4)) << 0) + | ((((sword32)((b[80] & 0xf )) >> 0)) << 24)); + t[23] = (word64)( + (((sword32)((b[80] ) >> 4)) << 0) | (((sword32)((b[81] ) >> 0)) << 4) | (((sword32)((b[82] ) >> 0)) << 12) - | (((sword32)((b[83] ) >> 0)) << 20); - t[24] = (((sword32)((b[84] ) >> 0)) << 0) + | (((sword32)((b[83] ) >> 0)) << 20)); + t[24] = (word64)( + (((sword32)((b[84] ) >> 0)) << 0) | (((sword32)((b[85] ) >> 0)) << 8) | (((sword32)((b[86] ) >> 0)) << 16) - | ((((sword32)((b[87] & 0xf )) >> 0)) << 24); - t[25] = (((sword32)((b[87] ) >> 4)) << 0) + | ((((sword32)((b[87] & 0xf )) >> 0)) << 24)); + t[25] = (word64)( + (((sword32)((b[87] ) >> 4)) << 0) | (((sword32)((b[88] ) >> 0)) << 4) | (((sword32)((b[89] ) >> 0)) << 12) - | (((sword32)((b[90] ) >> 0)) << 20); - t[26] = (((sword32)((b[91] ) >> 0)) << 0) + | (((sword32)((b[90] ) >> 0)) << 20)); + t[26] = (word64)( + (((sword32)((b[91] ) >> 0)) << 0) | (((sword32)((b[92] ) >> 0)) << 8) | (((sword32)((b[93] ) >> 0)) << 16) - | ((((sword32)((b[94] & 0xf )) >> 0)) << 24); - t[27] = (((sword32)((b[94] ) >> 4)) << 0) + | ((((sword32)((b[94] & 0xf )) >> 0)) << 24)); + t[27] = (word64)( + (((sword32)((b[94] ) >> 4)) << 0) | (((sword32)((b[95] ) >> 0)) << 4) | (((sword32)((b[96] ) >> 0)) << 12) - | (((sword32)((b[97] ) >> 0)) << 20); - t[28] = (((sword32)((b[98] ) >> 0)) << 0) + | (((sword32)((b[97] ) >> 0)) << 20)); + t[28] = (word64)( + (((sword32)((b[98] ) >> 0)) << 0) | (((sword32)((b[99] ) >> 0)) << 8) | (((sword32)((b[100] ) >> 0)) << 16) - | ((((sword32)((b[101] & 0xf )) >> 0)) << 24); - t[29] = (((sword32)((b[101] ) >> 4)) << 0) + | ((((sword32)((b[101] & 0xf )) >> 0)) << 24)); + t[29] = (word64)( + (((sword32)((b[101] ) >> 4)) << 0) | (((sword32)((b[102] ) >> 0)) << 4) | (((sword32)((b[103] ) >> 0)) << 12) - | (((sword32)((b[104] ) >> 0)) << 20); - t[30] = (((sword32)((b[105] ) >> 0)) << 0) + | (((sword32)((b[104] ) >> 0)) << 20)); + t[30] = (word64)( + (((sword32)((b[105] ) >> 0)) << 0) | (((sword32)((b[106] ) >> 0)) << 8) | (((sword32)((b[107] ) >> 0)) << 16) - | ((((sword32)((b[108] & 0xf )) >> 0)) << 24); - t[31] = (((sword32)((b[108] ) >> 4)) << 0) + | ((((sword32)((b[108] & 0xf )) >> 0)) << 24)); + t[31] = (word64)( + (((sword32)((b[108] ) >> 4)) << 0) | (((sword32)((b[109] ) >> 0)) << 4) | (((sword32)((b[110] ) >> 0)) << 12) - | (((sword32)((b[111] ) >> 0)) << 20); - t[32] = (((sword32)((b[112] ) >> 0)) << 0) - | (((sword32)((b[113] ) >> 0)) << 8); + | (((sword32)((b[111] ) >> 0)) << 20)); + t[32] = (word64)( + (((sword32)((b[112] ) >> 0)) << 0) + | (((sword32)((b[113] ) >> 0)) << 8)); /* Mod curve order */ /* 2^446 - 0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d */ @@ -5514,56 +5542,56 @@ void sc448_reduce(byte* b) b[ 0] = (byte)(d[0 ] >> 0); b[ 1] = (byte)(d[0 ] >> 8); b[ 2] = (byte)(d[0 ] >> 16); - b[ 3] = (byte)(d[0 ] >> 24) + (byte)((d[1 ] >> 0) << 4); + b[ 3] = (byte)((byte)(d[0 ] >> 24) + (byte)((d[1 ] >> 0) << 4)); b[ 4] = (byte)(d[1 ] >> 4); b[ 5] = (byte)(d[1 ] >> 12); b[ 6] = (byte)(d[1 ] >> 20); b[ 7] = (byte)(d[2 ] >> 0); b[ 8] = (byte)(d[2 ] >> 8); b[ 9] = (byte)(d[2 ] >> 16); - b[10] = (byte)(d[2 ] >> 24) + (byte)((d[3 ] >> 0) << 4); + b[10] = (byte)((byte)(d[2 ] >> 24) + (byte)((d[3 ] >> 0) << 4)); b[11] = (byte)(d[3 ] >> 4); b[12] = (byte)(d[3 ] >> 12); b[13] = (byte)(d[3 ] >> 20); b[14] = (byte)(d[4 ] >> 0); b[15] = (byte)(d[4 ] >> 8); b[16] = (byte)(d[4 ] >> 16); - b[17] = (byte)(d[4 ] >> 24) + (byte)((d[5 ] >> 0) << 4); + b[17] = (byte)((byte)(d[4 ] >> 24) + (byte)((d[5 ] >> 0) << 4)); b[18] = (byte)(d[5 ] >> 4); b[19] = (byte)(d[5 ] >> 12); b[20] = (byte)(d[5 ] >> 20); b[21] = (byte)(d[6 ] >> 0); b[22] = (byte)(d[6 ] >> 8); b[23] = (byte)(d[6 ] >> 16); - b[24] = (byte)(d[6 ] >> 24) + (byte)((d[7 ] >> 0) << 4); + b[24] = (byte)((byte)(d[6 ] >> 24) + (byte)((d[7 ] >> 0) << 4)); b[25] = (byte)(d[7 ] >> 4); b[26] = (byte)(d[7 ] >> 12); b[27] = (byte)(d[7 ] >> 20); b[28] = (byte)(d[8 ] >> 0); b[29] = (byte)(d[8 ] >> 8); b[30] = (byte)(d[8 ] >> 16); - b[31] = (byte)(d[8 ] >> 24) + (byte)((d[9 ] >> 0) << 4); + b[31] = (byte)((byte)(d[8 ] >> 24) + (byte)((d[9 ] >> 0) << 4)); b[32] = (byte)(d[9 ] >> 4); b[33] = (byte)(d[9 ] >> 12); b[34] = (byte)(d[9 ] >> 20); b[35] = (byte)(d[10] >> 0); b[36] = (byte)(d[10] >> 8); b[37] = (byte)(d[10] >> 16); - b[38] = (byte)(d[10] >> 24) + (byte)((d[11] >> 0) << 4); + b[38] = (byte)((byte)(d[10] >> 24) + (byte)((d[11] >> 0) << 4)); b[39] = (byte)(d[11] >> 4); b[40] = (byte)(d[11] >> 12); b[41] = (byte)(d[11] >> 20); b[42] = (byte)(d[12] >> 0); b[43] = (byte)(d[12] >> 8); b[44] = (byte)(d[12] >> 16); - b[45] = (byte)(d[12] >> 24) + (byte)((d[13] >> 0) << 4); + b[45] = (byte)((byte)(d[12] >> 24) + (byte)((d[13] >> 0) << 4)); b[46] = (byte)(d[13] >> 4); b[47] = (byte)(d[13] >> 12); b[48] = (byte)(d[13] >> 20); b[49] = (byte)(d[14] >> 0); b[50] = (byte)(d[14] >> 8); b[51] = (byte)(d[14] >> 16); - b[52] = (byte)(d[14] >> 24) + (byte)((d[15] >> 0) << 4); + b[52] = (byte)((byte)(d[14] >> 24) + (byte)((d[15] >> 0) << 4)); b[53] = (byte)(d[15] >> 4); b[54] = (byte)(d[15] >> 12); b[55] = (byte)(d[15] >> 20); @@ -5586,458 +5614,506 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) sword32 u; /* Load from bytes */ - ad[ 0] = (((sword32)((a[ 0] ) >> 0)) << 0) + ad[ 0] = (word32)( + (((sword32)((a[ 0] ) >> 0)) << 0) | (((sword32)((a[ 1] ) >> 0)) << 8) | (((sword32)((a[ 2] ) >> 0)) << 16) - | ((((sword32)((a[ 3] & 0xf )) >> 0)) << 24); - ad[ 1] = (((sword32)((a[ 3] ) >> 4)) << 0) + | ((((sword32)((a[ 3] & 0xf )) >> 0)) << 24)); + ad[ 1] = (word32)( + (((sword32)((a[ 3] ) >> 4)) << 0) | (((sword32)((a[ 4] ) >> 0)) << 4) | (((sword32)((a[ 5] ) >> 0)) << 12) - | (((sword32)((a[ 6] ) >> 0)) << 20); - ad[ 2] = (((sword32)((a[ 7] ) >> 0)) << 0) + | (((sword32)((a[ 6] ) >> 0)) << 20)); + ad[ 2] = (word32)( + (((sword32)((a[ 7] ) >> 0)) << 0) | (((sword32)((a[ 8] ) >> 0)) << 8) | (((sword32)((a[ 9] ) >> 0)) << 16) - | ((((sword32)((a[10] & 0xf )) >> 0)) << 24); - ad[ 3] = (((sword32)((a[10] ) >> 4)) << 0) + | ((((sword32)((a[10] & 0xf )) >> 0)) << 24)); + ad[ 3] = (word32)( + (((sword32)((a[10] ) >> 4)) << 0) | (((sword32)((a[11] ) >> 0)) << 4) | (((sword32)((a[12] ) >> 0)) << 12) - | (((sword32)((a[13] ) >> 0)) << 20); - ad[ 4] = (((sword32)((a[14] ) >> 0)) << 0) + | (((sword32)((a[13] ) >> 0)) << 20)); + ad[ 4] = (word32)( + (((sword32)((a[14] ) >> 0)) << 0) | (((sword32)((a[15] ) >> 0)) << 8) | (((sword32)((a[16] ) >> 0)) << 16) - | ((((sword32)((a[17] & 0xf )) >> 0)) << 24); - ad[ 5] = (((sword32)((a[17] ) >> 4)) << 0) + | ((((sword32)((a[17] & 0xf )) >> 0)) << 24)); + ad[ 5] = (word32)( + (((sword32)((a[17] ) >> 4)) << 0) | (((sword32)((a[18] ) >> 0)) << 4) | (((sword32)((a[19] ) >> 0)) << 12) - | (((sword32)((a[20] ) >> 0)) << 20); - ad[ 6] = (((sword32)((a[21] ) >> 0)) << 0) + | (((sword32)((a[20] ) >> 0)) << 20)); + ad[ 6] = (word32)( + (((sword32)((a[21] ) >> 0)) << 0) | (((sword32)((a[22] ) >> 0)) << 8) | (((sword32)((a[23] ) >> 0)) << 16) - | ((((sword32)((a[24] & 0xf )) >> 0)) << 24); - ad[ 7] = (((sword32)((a[24] ) >> 4)) << 0) + | ((((sword32)((a[24] & 0xf )) >> 0)) << 24)); + ad[ 7] = (word32)( + (((sword32)((a[24] ) >> 4)) << 0) | (((sword32)((a[25] ) >> 0)) << 4) | (((sword32)((a[26] ) >> 0)) << 12) - | (((sword32)((a[27] ) >> 0)) << 20); - ad[ 8] = (((sword32)((a[28] ) >> 0)) << 0) + | (((sword32)((a[27] ) >> 0)) << 20)); + ad[ 8] = (word32)( + (((sword32)((a[28] ) >> 0)) << 0) | (((sword32)((a[29] ) >> 0)) << 8) | (((sword32)((a[30] ) >> 0)) << 16) - | ((((sword32)((a[31] & 0xf )) >> 0)) << 24); - ad[ 9] = (((sword32)((a[31] ) >> 4)) << 0) + | ((((sword32)((a[31] & 0xf )) >> 0)) << 24)); + ad[ 9] = (word32)( + (((sword32)((a[31] ) >> 4)) << 0) | (((sword32)((a[32] ) >> 0)) << 4) | (((sword32)((a[33] ) >> 0)) << 12) - | (((sword32)((a[34] ) >> 0)) << 20); - ad[10] = (((sword32)((a[35] ) >> 0)) << 0) + | (((sword32)((a[34] ) >> 0)) << 20)); + ad[10] = (word32)( + (((sword32)((a[35] ) >> 0)) << 0) | (((sword32)((a[36] ) >> 0)) << 8) | (((sword32)((a[37] ) >> 0)) << 16) - | ((((sword32)((a[38] & 0xf )) >> 0)) << 24); - ad[11] = (((sword32)((a[38] ) >> 4)) << 0) + | ((((sword32)((a[38] & 0xf )) >> 0)) << 24)); + ad[11] = (word32)( + (((sword32)((a[38] ) >> 4)) << 0) | (((sword32)((a[39] ) >> 0)) << 4) | (((sword32)((a[40] ) >> 0)) << 12) - | (((sword32)((a[41] ) >> 0)) << 20); - ad[12] = (((sword32)((a[42] ) >> 0)) << 0) + | (((sword32)((a[41] ) >> 0)) << 20)); + ad[12] = (word32)( + (((sword32)((a[42] ) >> 0)) << 0) | (((sword32)((a[43] ) >> 0)) << 8) | (((sword32)((a[44] ) >> 0)) << 16) - | ((((sword32)((a[45] & 0xf )) >> 0)) << 24); - ad[13] = (((sword32)((a[45] ) >> 4)) << 0) + | ((((sword32)((a[45] & 0xf )) >> 0)) << 24)); + ad[13] = (word32)( + (((sword32)((a[45] ) >> 4)) << 0) | (((sword32)((a[46] ) >> 0)) << 4) | (((sword32)((a[47] ) >> 0)) << 12) - | (((sword32)((a[48] ) >> 0)) << 20); - ad[14] = (((sword32)((a[49] ) >> 0)) << 0) + | (((sword32)((a[48] ) >> 0)) << 20)); + ad[14] = (word32)( + (((sword32)((a[49] ) >> 0)) << 0) | (((sword32)((a[50] ) >> 0)) << 8) | (((sword32)((a[51] ) >> 0)) << 16) - | ((((sword32)((a[52] & 0xf )) >> 0)) << 24); - ad[15] = (((sword32)((a[52] ) >> 4)) << 0) + | ((((sword32)((a[52] & 0xf )) >> 0)) << 24)); + ad[15] = (word32)( + (((sword32)((a[52] ) >> 4)) << 0) | (((sword32)((a[53] ) >> 0)) << 4) | (((sword32)((a[54] ) >> 0)) << 12) - | (((sword32)((a[55] ) >> 0)) << 20); + | (((sword32)((a[55] ) >> 0)) << 20)); /* Load from bytes */ - bd[ 0] = (((sword32)((b[ 0] ) >> 0)) << 0) + bd[ 0] = (word32)( + (((sword32)((b[ 0] ) >> 0)) << 0) | (((sword32)((b[ 1] ) >> 0)) << 8) | (((sword32)((b[ 2] ) >> 0)) << 16) - | ((((sword32)((b[ 3] & 0xf )) >> 0)) << 24); - bd[ 1] = (((sword32)((b[ 3] ) >> 4)) << 0) + | ((((sword32)((b[ 3] & 0xf )) >> 0)) << 24)); + bd[ 1] = (word32)( + (((sword32)((b[ 3] ) >> 4)) << 0) | (((sword32)((b[ 4] ) >> 0)) << 4) | (((sword32)((b[ 5] ) >> 0)) << 12) - | (((sword32)((b[ 6] ) >> 0)) << 20); - bd[ 2] = (((sword32)((b[ 7] ) >> 0)) << 0) + | (((sword32)((b[ 6] ) >> 0)) << 20)); + bd[ 2] = (word32)( + (((sword32)((b[ 7] ) >> 0)) << 0) | (((sword32)((b[ 8] ) >> 0)) << 8) | (((sword32)((b[ 9] ) >> 0)) << 16) - | ((((sword32)((b[10] & 0xf )) >> 0)) << 24); - bd[ 3] = (((sword32)((b[10] ) >> 4)) << 0) + | ((((sword32)((b[10] & 0xf )) >> 0)) << 24)); + bd[ 3] = (word32)( + (((sword32)((b[10] ) >> 4)) << 0) | (((sword32)((b[11] ) >> 0)) << 4) | (((sword32)((b[12] ) >> 0)) << 12) - | (((sword32)((b[13] ) >> 0)) << 20); - bd[ 4] = (((sword32)((b[14] ) >> 0)) << 0) + | (((sword32)((b[13] ) >> 0)) << 20)); + bd[ 4] = (word32)( + (((sword32)((b[14] ) >> 0)) << 0) | (((sword32)((b[15] ) >> 0)) << 8) | (((sword32)((b[16] ) >> 0)) << 16) - | ((((sword32)((b[17] & 0xf )) >> 0)) << 24); - bd[ 5] = (((sword32)((b[17] ) >> 4)) << 0) + | ((((sword32)((b[17] & 0xf )) >> 0)) << 24)); + bd[ 5] = (word32)( + (((sword32)((b[17] ) >> 4)) << 0) | (((sword32)((b[18] ) >> 0)) << 4) | (((sword32)((b[19] ) >> 0)) << 12) - | (((sword32)((b[20] ) >> 0)) << 20); - bd[ 6] = (((sword32)((b[21] ) >> 0)) << 0) + | (((sword32)((b[20] ) >> 0)) << 20)); + bd[ 6] = (word32)( + (((sword32)((b[21] ) >> 0)) << 0) | (((sword32)((b[22] ) >> 0)) << 8) | (((sword32)((b[23] ) >> 0)) << 16) - | ((((sword32)((b[24] & 0xf )) >> 0)) << 24); - bd[ 7] = (((sword32)((b[24] ) >> 4)) << 0) + | ((((sword32)((b[24] & 0xf )) >> 0)) << 24)); + bd[ 7] = (word32)( + (((sword32)((b[24] ) >> 4)) << 0) | (((sword32)((b[25] ) >> 0)) << 4) | (((sword32)((b[26] ) >> 0)) << 12) - | (((sword32)((b[27] ) >> 0)) << 20); - bd[ 8] = (((sword32)((b[28] ) >> 0)) << 0) + | (((sword32)((b[27] ) >> 0)) << 20)); + bd[ 8] = (word32)( + (((sword32)((b[28] ) >> 0)) << 0) | (((sword32)((b[29] ) >> 0)) << 8) | (((sword32)((b[30] ) >> 0)) << 16) - | ((((sword32)((b[31] & 0xf )) >> 0)) << 24); - bd[ 9] = (((sword32)((b[31] ) >> 4)) << 0) + | ((((sword32)((b[31] & 0xf )) >> 0)) << 24)); + bd[ 9] = (word32)( + (((sword32)((b[31] ) >> 4)) << 0) | (((sword32)((b[32] ) >> 0)) << 4) | (((sword32)((b[33] ) >> 0)) << 12) - | (((sword32)((b[34] ) >> 0)) << 20); - bd[10] = (((sword32)((b[35] ) >> 0)) << 0) + | (((sword32)((b[34] ) >> 0)) << 20)); + bd[10] = (word32)( + (((sword32)((b[35] ) >> 0)) << 0) | (((sword32)((b[36] ) >> 0)) << 8) | (((sword32)((b[37] ) >> 0)) << 16) - | ((((sword32)((b[38] & 0xf )) >> 0)) << 24); - bd[11] = (((sword32)((b[38] ) >> 4)) << 0) + | ((((sword32)((b[38] & 0xf )) >> 0)) << 24)); + bd[11] = (word32)( + (((sword32)((b[38] ) >> 4)) << 0) | (((sword32)((b[39] ) >> 0)) << 4) | (((sword32)((b[40] ) >> 0)) << 12) - | (((sword32)((b[41] ) >> 0)) << 20); - bd[12] = (((sword32)((b[42] ) >> 0)) << 0) + | (((sword32)((b[41] ) >> 0)) << 20)); + bd[12] = (word32)( + (((sword32)((b[42] ) >> 0)) << 0) | (((sword32)((b[43] ) >> 0)) << 8) | (((sword32)((b[44] ) >> 0)) << 16) - | ((((sword32)((b[45] & 0xf )) >> 0)) << 24); - bd[13] = (((sword32)((b[45] ) >> 4)) << 0) + | ((((sword32)((b[45] & 0xf )) >> 0)) << 24)); + bd[13] = (word32)( + (((sword32)((b[45] ) >> 4)) << 0) | (((sword32)((b[46] ) >> 0)) << 4) | (((sword32)((b[47] ) >> 0)) << 12) - | (((sword32)((b[48] ) >> 0)) << 20); - bd[14] = (((sword32)((b[49] ) >> 0)) << 0) + | (((sword32)((b[48] ) >> 0)) << 20)); + bd[14] = (word32)( + (((sword32)((b[49] ) >> 0)) << 0) | (((sword32)((b[50] ) >> 0)) << 8) | (((sword32)((b[51] ) >> 0)) << 16) - | ((((sword32)((b[52] & 0xf )) >> 0)) << 24); - bd[15] = (((sword32)((b[52] ) >> 4)) << 0) + | ((((sword32)((b[52] & 0xf )) >> 0)) << 24)); + bd[15] = (word32)( + (((sword32)((b[52] ) >> 4)) << 0) | (((sword32)((b[53] ) >> 0)) << 4) | (((sword32)((b[54] ) >> 0)) << 12) - | (((sword32)((b[55] ) >> 0)) << 20); + | (((sword32)((b[55] ) >> 0)) << 20)); /* Load from bytes */ - dd[ 0] = (((sword32)((d[ 0] ) >> 0)) << 0) + dd[ 0] = (word32)( + (((sword32)((d[ 0] ) >> 0)) << 0) | (((sword32)((d[ 1] ) >> 0)) << 8) | (((sword32)((d[ 2] ) >> 0)) << 16) - | ((((sword32)((d[ 3] & 0xf )) >> 0)) << 24); - dd[ 1] = (((sword32)((d[ 3] ) >> 4)) << 0) + | ((((sword32)((d[ 3] & 0xf )) >> 0)) << 24)); + dd[ 1] = (word32)( + (((sword32)((d[ 3] ) >> 4)) << 0) | (((sword32)((d[ 4] ) >> 0)) << 4) | (((sword32)((d[ 5] ) >> 0)) << 12) - | (((sword32)((d[ 6] ) >> 0)) << 20); - dd[ 2] = (((sword32)((d[ 7] ) >> 0)) << 0) + | (((sword32)((d[ 6] ) >> 0)) << 20)); + dd[ 2] = (word32)( + (((sword32)((d[ 7] ) >> 0)) << 0) | (((sword32)((d[ 8] ) >> 0)) << 8) | (((sword32)((d[ 9] ) >> 0)) << 16) - | ((((sword32)((d[10] & 0xf )) >> 0)) << 24); - dd[ 3] = (((sword32)((d[10] ) >> 4)) << 0) + | ((((sword32)((d[10] & 0xf )) >> 0)) << 24)); + dd[ 3] = (word32)( + (((sword32)((d[10] ) >> 4)) << 0) | (((sword32)((d[11] ) >> 0)) << 4) | (((sword32)((d[12] ) >> 0)) << 12) - | (((sword32)((d[13] ) >> 0)) << 20); - dd[ 4] = (((sword32)((d[14] ) >> 0)) << 0) + | (((sword32)((d[13] ) >> 0)) << 20)); + dd[ 4] = (word32)( + (((sword32)((d[14] ) >> 0)) << 0) | (((sword32)((d[15] ) >> 0)) << 8) | (((sword32)((d[16] ) >> 0)) << 16) - | ((((sword32)((d[17] & 0xf )) >> 0)) << 24); - dd[ 5] = (((sword32)((d[17] ) >> 4)) << 0) + | ((((sword32)((d[17] & 0xf )) >> 0)) << 24)); + dd[ 5] = (word32)( + (((sword32)((d[17] ) >> 4)) << 0) | (((sword32)((d[18] ) >> 0)) << 4) | (((sword32)((d[19] ) >> 0)) << 12) - | (((sword32)((d[20] ) >> 0)) << 20); - dd[ 6] = (((sword32)((d[21] ) >> 0)) << 0) + | (((sword32)((d[20] ) >> 0)) << 20)); + dd[ 6] = (word32)( + (((sword32)((d[21] ) >> 0)) << 0) | (((sword32)((d[22] ) >> 0)) << 8) | (((sword32)((d[23] ) >> 0)) << 16) - | ((((sword32)((d[24] & 0xf )) >> 0)) << 24); - dd[ 7] = (((sword32)((d[24] ) >> 4)) << 0) + | ((((sword32)((d[24] & 0xf )) >> 0)) << 24)); + dd[ 7] = (word32)( + (((sword32)((d[24] ) >> 4)) << 0) | (((sword32)((d[25] ) >> 0)) << 4) | (((sword32)((d[26] ) >> 0)) << 12) - | (((sword32)((d[27] ) >> 0)) << 20); - dd[ 8] = (((sword32)((d[28] ) >> 0)) << 0) + | (((sword32)((d[27] ) >> 0)) << 20)); + dd[ 8] = (word32)( + (((sword32)((d[28] ) >> 0)) << 0) | (((sword32)((d[29] ) >> 0)) << 8) | (((sword32)((d[30] ) >> 0)) << 16) - | ((((sword32)((d[31] & 0xf )) >> 0)) << 24); - dd[ 9] = (((sword32)((d[31] ) >> 4)) << 0) + | ((((sword32)((d[31] & 0xf )) >> 0)) << 24)); + dd[ 9] = (word32)( + (((sword32)((d[31] ) >> 4)) << 0) | (((sword32)((d[32] ) >> 0)) << 4) | (((sword32)((d[33] ) >> 0)) << 12) - | (((sword32)((d[34] ) >> 0)) << 20); - dd[10] = (((sword32)((d[35] ) >> 0)) << 0) + | (((sword32)((d[34] ) >> 0)) << 20)); + dd[10] = (word32)( + (((sword32)((d[35] ) >> 0)) << 0) | (((sword32)((d[36] ) >> 0)) << 8) | (((sword32)((d[37] ) >> 0)) << 16) - | ((((sword32)((d[38] & 0xf )) >> 0)) << 24); - dd[11] = (((sword32)((d[38] ) >> 4)) << 0) + | ((((sword32)((d[38] & 0xf )) >> 0)) << 24)); + dd[11] = (word32)( + (((sword32)((d[38] ) >> 4)) << 0) | (((sword32)((d[39] ) >> 0)) << 4) | (((sword32)((d[40] ) >> 0)) << 12) - | (((sword32)((d[41] ) >> 0)) << 20); - dd[12] = (((sword32)((d[42] ) >> 0)) << 0) + | (((sword32)((d[41] ) >> 0)) << 20)); + dd[12] = (word32)( + (((sword32)((d[42] ) >> 0)) << 0) | (((sword32)((d[43] ) >> 0)) << 8) | (((sword32)((d[44] ) >> 0)) << 16) - | ((((sword32)((d[45] & 0xf )) >> 0)) << 24); - dd[13] = (((sword32)((d[45] ) >> 4)) << 0) + | ((((sword32)((d[45] & 0xf )) >> 0)) << 24)); + dd[13] = (word32)( + (((sword32)((d[45] ) >> 4)) << 0) | (((sword32)((d[46] ) >> 0)) << 4) | (((sword32)((d[47] ) >> 0)) << 12) - | (((sword32)((d[48] ) >> 0)) << 20); - dd[14] = (((sword32)((d[49] ) >> 0)) << 0) + | (((sword32)((d[48] ) >> 0)) << 20)); + dd[14] = (word32)( + (((sword32)((d[49] ) >> 0)) << 0) | (((sword32)((d[50] ) >> 0)) << 8) | (((sword32)((d[51] ) >> 0)) << 16) - | ((((sword32)((d[52] & 0xf )) >> 0)) << 24); - dd[15] = (((sword32)((d[52] ) >> 4)) << 0) + | ((((sword32)((d[52] & 0xf )) >> 0)) << 24)); + dd[15] = (word32)( + (((sword32)((d[52] ) >> 4)) << 0) | (((sword32)((d[53] ) >> 0)) << 4) | (((sword32)((d[54] ) >> 0)) << 12) - | (((sword32)((d[55] ) >> 0)) << 20); + | (((sword32)((d[55] ) >> 0)) << 20)); /* a * b + d */ - t[ 0] = (word64)dd[ 0] + (sword64)ad[ 0] * bd[ 0]; - t[ 1] = (word64)dd[ 1] + (sword64)ad[ 0] * bd[ 1] - + (sword64)ad[ 1] * bd[ 0]; - t[ 2] = (word64)dd[ 2] + (sword64)ad[ 0] * bd[ 2] - + (sword64)ad[ 1] * bd[ 1] - + (sword64)ad[ 2] * bd[ 0]; - t[ 3] = (word64)dd[ 3] + (sword64)ad[ 0] * bd[ 3] - + (sword64)ad[ 1] * bd[ 2] - + (sword64)ad[ 2] * bd[ 1] - + (sword64)ad[ 3] * bd[ 0]; - t[ 4] = (word64)dd[ 4] + (sword64)ad[ 0] * bd[ 4] - + (sword64)ad[ 1] * bd[ 3] - + (sword64)ad[ 2] * bd[ 2] - + (sword64)ad[ 3] * bd[ 1] - + (sword64)ad[ 4] * bd[ 0]; - t[ 5] = (word64)dd[ 5] + (sword64)ad[ 0] * bd[ 5] - + (sword64)ad[ 1] * bd[ 4] - + (sword64)ad[ 2] * bd[ 3] - + (sword64)ad[ 3] * bd[ 2] - + (sword64)ad[ 4] * bd[ 1] - + (sword64)ad[ 5] * bd[ 0]; - t[ 6] = (word64)dd[ 6] + (sword64)ad[ 0] * bd[ 6] - + (sword64)ad[ 1] * bd[ 5] - + (sword64)ad[ 2] * bd[ 4] - + (sword64)ad[ 3] * bd[ 3] - + (sword64)ad[ 4] * bd[ 2] - + (sword64)ad[ 5] * bd[ 1] - + (sword64)ad[ 6] * bd[ 0]; - t[ 7] = (word64)dd[ 7] + (sword64)ad[ 0] * bd[ 7] - + (sword64)ad[ 1] * bd[ 6] - + (sword64)ad[ 2] * bd[ 5] - + (sword64)ad[ 3] * bd[ 4] - + (sword64)ad[ 4] * bd[ 3] - + (sword64)ad[ 5] * bd[ 2] - + (sword64)ad[ 6] * bd[ 1] - + (sword64)ad[ 7] * bd[ 0]; - t[ 8] = (word64)dd[ 8] + (sword64)ad[ 0] * bd[ 8] - + (sword64)ad[ 1] * bd[ 7] - + (sword64)ad[ 2] * bd[ 6] - + (sword64)ad[ 3] * bd[ 5] - + (sword64)ad[ 4] * bd[ 4] - + (sword64)ad[ 5] * bd[ 3] - + (sword64)ad[ 6] * bd[ 2] - + (sword64)ad[ 7] * bd[ 1] - + (sword64)ad[ 8] * bd[ 0]; - t[ 9] = (word64)dd[ 9] + (sword64)ad[ 0] * bd[ 9] - + (sword64)ad[ 1] * bd[ 8] - + (sword64)ad[ 2] * bd[ 7] - + (sword64)ad[ 3] * bd[ 6] - + (sword64)ad[ 4] * bd[ 5] - + (sword64)ad[ 5] * bd[ 4] - + (sword64)ad[ 6] * bd[ 3] - + (sword64)ad[ 7] * bd[ 2] - + (sword64)ad[ 8] * bd[ 1] - + (sword64)ad[ 9] * bd[ 0]; - t[10] = (word64)dd[10] + (sword64)ad[ 0] * bd[10] - + (sword64)ad[ 1] * bd[ 9] - + (sword64)ad[ 2] * bd[ 8] - + (sword64)ad[ 3] * bd[ 7] - + (sword64)ad[ 4] * bd[ 6] - + (sword64)ad[ 5] * bd[ 5] - + (sword64)ad[ 6] * bd[ 4] - + (sword64)ad[ 7] * bd[ 3] - + (sword64)ad[ 8] * bd[ 2] - + (sword64)ad[ 9] * bd[ 1] - + (sword64)ad[10] * bd[ 0]; - t[11] = (word64)dd[11] + (sword64)ad[ 0] * bd[11] - + (sword64)ad[ 1] * bd[10] - + (sword64)ad[ 2] * bd[ 9] - + (sword64)ad[ 3] * bd[ 8] - + (sword64)ad[ 4] * bd[ 7] - + (sword64)ad[ 5] * bd[ 6] - + (sword64)ad[ 6] * bd[ 5] - + (sword64)ad[ 7] * bd[ 4] - + (sword64)ad[ 8] * bd[ 3] - + (sword64)ad[ 9] * bd[ 2] - + (sword64)ad[10] * bd[ 1] - + (sword64)ad[11] * bd[ 0]; - t[12] = (word64)dd[12] + (sword64)ad[ 0] * bd[12] - + (sword64)ad[ 1] * bd[11] - + (sword64)ad[ 2] * bd[10] - + (sword64)ad[ 3] * bd[ 9] - + (sword64)ad[ 4] * bd[ 8] - + (sword64)ad[ 5] * bd[ 7] - + (sword64)ad[ 6] * bd[ 6] - + (sword64)ad[ 7] * bd[ 5] - + (sword64)ad[ 8] * bd[ 4] - + (sword64)ad[ 9] * bd[ 3] - + (sword64)ad[10] * bd[ 2] - + (sword64)ad[11] * bd[ 1] - + (sword64)ad[12] * bd[ 0]; - t[13] = (word64)dd[13] + (sword64)ad[ 0] * bd[13] - + (sword64)ad[ 1] * bd[12] - + (sword64)ad[ 2] * bd[11] - + (sword64)ad[ 3] * bd[10] - + (sword64)ad[ 4] * bd[ 9] - + (sword64)ad[ 5] * bd[ 8] - + (sword64)ad[ 6] * bd[ 7] - + (sword64)ad[ 7] * bd[ 6] - + (sword64)ad[ 8] * bd[ 5] - + (sword64)ad[ 9] * bd[ 4] - + (sword64)ad[10] * bd[ 3] - + (sword64)ad[11] * bd[ 2] - + (sword64)ad[12] * bd[ 1] - + (sword64)ad[13] * bd[ 0]; - t[14] = (word64)dd[14] + (sword64)ad[ 0] * bd[14] - + (sword64)ad[ 1] * bd[13] - + (sword64)ad[ 2] * bd[12] - + (sword64)ad[ 3] * bd[11] - + (sword64)ad[ 4] * bd[10] - + (sword64)ad[ 5] * bd[ 9] - + (sword64)ad[ 6] * bd[ 8] - + (sword64)ad[ 7] * bd[ 7] - + (sword64)ad[ 8] * bd[ 6] - + (sword64)ad[ 9] * bd[ 5] - + (sword64)ad[10] * bd[ 4] - + (sword64)ad[11] * bd[ 3] - + (sword64)ad[12] * bd[ 2] - + (sword64)ad[13] * bd[ 1] - + (sword64)ad[14] * bd[ 0]; - t[15] = (word64)dd[15] + (sword64)ad[ 0] * bd[15] - + (sword64)ad[ 1] * bd[14] - + (sword64)ad[ 2] * bd[13] - + (sword64)ad[ 3] * bd[12] - + (sword64)ad[ 4] * bd[11] - + (sword64)ad[ 5] * bd[10] - + (sword64)ad[ 6] * bd[ 9] - + (sword64)ad[ 7] * bd[ 8] - + (sword64)ad[ 8] * bd[ 7] - + (sword64)ad[ 9] * bd[ 6] - + (sword64)ad[10] * bd[ 5] - + (sword64)ad[11] * bd[ 4] - + (sword64)ad[12] * bd[ 3] - + (sword64)ad[13] * bd[ 2] - + (sword64)ad[14] * bd[ 1] - + (sword64)ad[15] * bd[ 0]; - t[16] = (word64) (sword64)ad[ 1] * bd[15] - + (sword64)ad[ 2] * bd[14] - + (sword64)ad[ 3] * bd[13] - + (sword64)ad[ 4] * bd[12] - + (sword64)ad[ 5] * bd[11] - + (sword64)ad[ 6] * bd[10] - + (sword64)ad[ 7] * bd[ 9] - + (sword64)ad[ 8] * bd[ 8] - + (sword64)ad[ 9] * bd[ 7] - + (sword64)ad[10] * bd[ 6] - + (sword64)ad[11] * bd[ 5] - + (sword64)ad[12] * bd[ 4] - + (sword64)ad[13] * bd[ 3] - + (sword64)ad[14] * bd[ 2] - + (sword64)ad[15] * bd[ 1]; - t[17] = (word64) (sword64)ad[ 2] * bd[15] - + (sword64)ad[ 3] * bd[14] - + (sword64)ad[ 4] * bd[13] - + (sword64)ad[ 5] * bd[12] - + (sword64)ad[ 6] * bd[11] - + (sword64)ad[ 7] * bd[10] - + (sword64)ad[ 8] * bd[ 9] - + (sword64)ad[ 9] * bd[ 8] - + (sword64)ad[10] * bd[ 7] - + (sword64)ad[11] * bd[ 6] - + (sword64)ad[12] * bd[ 5] - + (sword64)ad[13] * bd[ 4] - + (sword64)ad[14] * bd[ 3] - + (sword64)ad[15] * bd[ 2]; - t[18] = (word64) (sword64)ad[ 3] * bd[15] - + (sword64)ad[ 4] * bd[14] - + (sword64)ad[ 5] * bd[13] - + (sword64)ad[ 6] * bd[12] - + (sword64)ad[ 7] * bd[11] - + (sword64)ad[ 8] * bd[10] - + (sword64)ad[ 9] * bd[ 9] - + (sword64)ad[10] * bd[ 8] - + (sword64)ad[11] * bd[ 7] - + (sword64)ad[12] * bd[ 6] - + (sword64)ad[13] * bd[ 5] - + (sword64)ad[14] * bd[ 4] - + (sword64)ad[15] * bd[ 3]; - t[19] = (word64) (sword64)ad[ 4] * bd[15] - + (sword64)ad[ 5] * bd[14] - + (sword64)ad[ 6] * bd[13] - + (sword64)ad[ 7] * bd[12] - + (sword64)ad[ 8] * bd[11] - + (sword64)ad[ 9] * bd[10] - + (sword64)ad[10] * bd[ 9] - + (sword64)ad[11] * bd[ 8] - + (sword64)ad[12] * bd[ 7] - + (sword64)ad[13] * bd[ 6] - + (sword64)ad[14] * bd[ 5] - + (sword64)ad[15] * bd[ 4]; - t[20] = (word64) (sword64)ad[ 5] * bd[15] - + (sword64)ad[ 6] * bd[14] - + (sword64)ad[ 7] * bd[13] - + (sword64)ad[ 8] * bd[12] - + (sword64)ad[ 9] * bd[11] - + (sword64)ad[10] * bd[10] - + (sword64)ad[11] * bd[ 9] - + (sword64)ad[12] * bd[ 8] - + (sword64)ad[13] * bd[ 7] - + (sword64)ad[14] * bd[ 6] - + (sword64)ad[15] * bd[ 5]; - t[21] = (word64) (sword64)ad[ 6] * bd[15] - + (sword64)ad[ 7] * bd[14] - + (sword64)ad[ 8] * bd[13] - + (sword64)ad[ 9] * bd[12] - + (sword64)ad[10] * bd[11] - + (sword64)ad[11] * bd[10] - + (sword64)ad[12] * bd[ 9] - + (sword64)ad[13] * bd[ 8] - + (sword64)ad[14] * bd[ 7] - + (sword64)ad[15] * bd[ 6]; - t[22] = (word64) (sword64)ad[ 7] * bd[15] - + (sword64)ad[ 8] * bd[14] - + (sword64)ad[ 9] * bd[13] - + (sword64)ad[10] * bd[12] - + (sword64)ad[11] * bd[11] - + (sword64)ad[12] * bd[10] - + (sword64)ad[13] * bd[ 9] - + (sword64)ad[14] * bd[ 8] - + (sword64)ad[15] * bd[ 7]; - t[23] = (word64) (sword64)ad[ 8] * bd[15] - + (sword64)ad[ 9] * bd[14] - + (sword64)ad[10] * bd[13] - + (sword64)ad[11] * bd[12] - + (sword64)ad[12] * bd[11] - + (sword64)ad[13] * bd[10] - + (sword64)ad[14] * bd[ 9] - + (sword64)ad[15] * bd[ 8]; - t[24] = (word64) (sword64)ad[ 9] * bd[15] - + (sword64)ad[10] * bd[14] - + (sword64)ad[11] * bd[13] - + (sword64)ad[12] * bd[12] - + (sword64)ad[13] * bd[11] - + (sword64)ad[14] * bd[10] - + (sword64)ad[15] * bd[ 9]; - t[25] = (word64) (sword64)ad[10] * bd[15] - + (sword64)ad[11] * bd[14] - + (sword64)ad[12] * bd[13] - + (sword64)ad[13] * bd[12] - + (sword64)ad[14] * bd[11] - + (sword64)ad[15] * bd[10]; - t[26] = (word64) (sword64)ad[11] * bd[15] - + (sword64)ad[12] * bd[14] - + (sword64)ad[13] * bd[13] - + (sword64)ad[14] * bd[12] - + (sword64)ad[15] * bd[11]; - t[27] = (word64) (sword64)ad[12] * bd[15] - + (sword64)ad[13] * bd[14] - + (sword64)ad[14] * bd[13] - + (sword64)ad[15] * bd[12]; - t[28] = (word64) (sword64)ad[13] * bd[15] - + (sword64)ad[14] * bd[14] - + (sword64)ad[15] * bd[13]; - t[29] = (word64) (sword64)ad[14] * bd[15] - + (sword64)ad[15] * bd[14]; - t[30] = (word64) (sword64)ad[15] * bd[15]; + t[ 0] = (word64)(dd[ 0] + (word64)((sword64)ad[ 0] * bd[ 0])); + t[ 1] = (word64)(dd[ 1] + (word64)((sword64)ad[ 0] * bd[ 1] + + (sword64)ad[ 1] * bd[ 0])); + t[ 2] = (word64)(dd[ 2] + (word64)((sword64)ad[ 0] * bd[ 2] + + (sword64)ad[ 1] * bd[ 1] + + (sword64)ad[ 2] * bd[ 0])); + t[ 3] = (word64)(dd[ 3] + (word64)((sword64)ad[ 0] * bd[ 3] + + (sword64)ad[ 1] * bd[ 2] + + (sword64)ad[ 2] * bd[ 1] + + (sword64)ad[ 3] * bd[ 0])); + t[ 4] = (word64)(dd[ 4] + (word64)((sword64)ad[ 0] * bd[ 4] + + (sword64)ad[ 1] * bd[ 3] + + (sword64)ad[ 2] * bd[ 2] + + (sword64)ad[ 3] * bd[ 1] + + (sword64)ad[ 4] * bd[ 0])); + t[ 5] = (word64)(dd[ 5] + (word64)((sword64)ad[ 0] * bd[ 5] + + (sword64)ad[ 1] * bd[ 4] + + (sword64)ad[ 2] * bd[ 3] + + (sword64)ad[ 3] * bd[ 2] + + (sword64)ad[ 4] * bd[ 1] + + (sword64)ad[ 5] * bd[ 0])); + t[ 6] = (word64)(dd[ 6] + (word64)((sword64)ad[ 0] * bd[ 6] + + (sword64)ad[ 1] * bd[ 5] + + (sword64)ad[ 2] * bd[ 4] + + (sword64)ad[ 3] * bd[ 3] + + (sword64)ad[ 4] * bd[ 2] + + (sword64)ad[ 5] * bd[ 1] + + (sword64)ad[ 6] * bd[ 0])); + t[ 7] = (word64)(dd[ 7] + (word64)((sword64)ad[ 0] * bd[ 7] + + (sword64)ad[ 1] * bd[ 6] + + (sword64)ad[ 2] * bd[ 5] + + (sword64)ad[ 3] * bd[ 4] + + (sword64)ad[ 4] * bd[ 3] + + (sword64)ad[ 5] * bd[ 2] + + (sword64)ad[ 6] * bd[ 1] + + (sword64)ad[ 7] * bd[ 0])); + t[ 8] = (word64)(dd[ 8] + (word64)((sword64)ad[ 0] * bd[ 8] + + (sword64)ad[ 1] * bd[ 7] + + (sword64)ad[ 2] * bd[ 6] + + (sword64)ad[ 3] * bd[ 5] + + (sword64)ad[ 4] * bd[ 4] + + (sword64)ad[ 5] * bd[ 3] + + (sword64)ad[ 6] * bd[ 2] + + (sword64)ad[ 7] * bd[ 1] + + (sword64)ad[ 8] * bd[ 0])); + t[ 9] = (word64)(dd[ 9] + (word64)((sword64)ad[ 0] * bd[ 9] + + (sword64)ad[ 1] * bd[ 8] + + (sword64)ad[ 2] * bd[ 7] + + (sword64)ad[ 3] * bd[ 6] + + (sword64)ad[ 4] * bd[ 5] + + (sword64)ad[ 5] * bd[ 4] + + (sword64)ad[ 6] * bd[ 3] + + (sword64)ad[ 7] * bd[ 2] + + (sword64)ad[ 8] * bd[ 1] + + (sword64)ad[ 9] * bd[ 0])); + t[10] = (word64)(dd[10] + (word64)((sword64)ad[ 0] * bd[10] + + (sword64)ad[ 1] * bd[ 9] + + (sword64)ad[ 2] * bd[ 8] + + (sword64)ad[ 3] * bd[ 7] + + (sword64)ad[ 4] * bd[ 6] + + (sword64)ad[ 5] * bd[ 5] + + (sword64)ad[ 6] * bd[ 4] + + (sword64)ad[ 7] * bd[ 3] + + (sword64)ad[ 8] * bd[ 2] + + (sword64)ad[ 9] * bd[ 1] + + (sword64)ad[10] * bd[ 0])); + t[11] = (word64)(dd[11] + (word64)((sword64)ad[ 0] * bd[11] + + (sword64)ad[ 1] * bd[10] + + (sword64)ad[ 2] * bd[ 9] + + (sword64)ad[ 3] * bd[ 8] + + (sword64)ad[ 4] * bd[ 7] + + (sword64)ad[ 5] * bd[ 6] + + (sword64)ad[ 6] * bd[ 5] + + (sword64)ad[ 7] * bd[ 4] + + (sword64)ad[ 8] * bd[ 3] + + (sword64)ad[ 9] * bd[ 2] + + (sword64)ad[10] * bd[ 1] + + (sword64)ad[11] * bd[ 0])); + t[12] = (word64)(dd[12] + (word64)((sword64)ad[ 0] * bd[12] + + (sword64)ad[ 1] * bd[11] + + (sword64)ad[ 2] * bd[10] + + (sword64)ad[ 3] * bd[ 9] + + (sword64)ad[ 4] * bd[ 8] + + (sword64)ad[ 5] * bd[ 7] + + (sword64)ad[ 6] * bd[ 6] + + (sword64)ad[ 7] * bd[ 5] + + (sword64)ad[ 8] * bd[ 4] + + (sword64)ad[ 9] * bd[ 3] + + (sword64)ad[10] * bd[ 2] + + (sword64)ad[11] * bd[ 1] + + (sword64)ad[12] * bd[ 0])); + t[13] = (word64)(dd[13] + (word64)((sword64)ad[ 0] * bd[13] + + (sword64)ad[ 1] * bd[12] + + (sword64)ad[ 2] * bd[11] + + (sword64)ad[ 3] * bd[10] + + (sword64)ad[ 4] * bd[ 9] + + (sword64)ad[ 5] * bd[ 8] + + (sword64)ad[ 6] * bd[ 7] + + (sword64)ad[ 7] * bd[ 6] + + (sword64)ad[ 8] * bd[ 5] + + (sword64)ad[ 9] * bd[ 4] + + (sword64)ad[10] * bd[ 3] + + (sword64)ad[11] * bd[ 2] + + (sword64)ad[12] * bd[ 1] + + (sword64)ad[13] * bd[ 0])); + t[14] = (word64)(dd[14] + (word64)((sword64)ad[ 0] * bd[14] + + (sword64)ad[ 1] * bd[13] + + (sword64)ad[ 2] * bd[12] + + (sword64)ad[ 3] * bd[11] + + (sword64)ad[ 4] * bd[10] + + (sword64)ad[ 5] * bd[ 9] + + (sword64)ad[ 6] * bd[ 8] + + (sword64)ad[ 7] * bd[ 7] + + (sword64)ad[ 8] * bd[ 6] + + (sword64)ad[ 9] * bd[ 5] + + (sword64)ad[10] * bd[ 4] + + (sword64)ad[11] * bd[ 3] + + (sword64)ad[12] * bd[ 2] + + (sword64)ad[13] * bd[ 1] + + (sword64)ad[14] * bd[ 0])); + t[15] = (word64)(dd[15] + (word64)((sword64)ad[ 0] * bd[15] + + (sword64)ad[ 1] * bd[14] + + (sword64)ad[ 2] * bd[13] + + (sword64)ad[ 3] * bd[12] + + (sword64)ad[ 4] * bd[11] + + (sword64)ad[ 5] * bd[10] + + (sword64)ad[ 6] * bd[ 9] + + (sword64)ad[ 7] * bd[ 8] + + (sword64)ad[ 8] * bd[ 7] + + (sword64)ad[ 9] * bd[ 6] + + (sword64)ad[10] * bd[ 5] + + (sword64)ad[11] * bd[ 4] + + (sword64)ad[12] * bd[ 3] + + (sword64)ad[13] * bd[ 2] + + (sword64)ad[14] * bd[ 1] + + (sword64)ad[15] * bd[ 0])); + t[16] = (word64)( (sword64)ad[ 1] * bd[15] + + (sword64)ad[ 2] * bd[14] + + (sword64)ad[ 3] * bd[13] + + (sword64)ad[ 4] * bd[12] + + (sword64)ad[ 5] * bd[11] + + (sword64)ad[ 6] * bd[10] + + (sword64)ad[ 7] * bd[ 9] + + (sword64)ad[ 8] * bd[ 8] + + (sword64)ad[ 9] * bd[ 7] + + (sword64)ad[10] * bd[ 6] + + (sword64)ad[11] * bd[ 5] + + (sword64)ad[12] * bd[ 4] + + (sword64)ad[13] * bd[ 3] + + (sword64)ad[14] * bd[ 2] + + (sword64)ad[15] * bd[ 1]); + t[17] = (word64)( (sword64)ad[ 2] * bd[15] + + (sword64)ad[ 3] * bd[14] + + (sword64)ad[ 4] * bd[13] + + (sword64)ad[ 5] * bd[12] + + (sword64)ad[ 6] * bd[11] + + (sword64)ad[ 7] * bd[10] + + (sword64)ad[ 8] * bd[ 9] + + (sword64)ad[ 9] * bd[ 8] + + (sword64)ad[10] * bd[ 7] + + (sword64)ad[11] * bd[ 6] + + (sword64)ad[12] * bd[ 5] + + (sword64)ad[13] * bd[ 4] + + (sword64)ad[14] * bd[ 3] + + (sword64)ad[15] * bd[ 2]); + t[18] = (word64)( (sword64)ad[ 3] * bd[15] + + (sword64)ad[ 4] * bd[14] + + (sword64)ad[ 5] * bd[13] + + (sword64)ad[ 6] * bd[12] + + (sword64)ad[ 7] * bd[11] + + (sword64)ad[ 8] * bd[10] + + (sword64)ad[ 9] * bd[ 9] + + (sword64)ad[10] * bd[ 8] + + (sword64)ad[11] * bd[ 7] + + (sword64)ad[12] * bd[ 6] + + (sword64)ad[13] * bd[ 5] + + (sword64)ad[14] * bd[ 4] + + (sword64)ad[15] * bd[ 3]); + t[19] = (word64)( (sword64)ad[ 4] * bd[15] + + (sword64)ad[ 5] * bd[14] + + (sword64)ad[ 6] * bd[13] + + (sword64)ad[ 7] * bd[12] + + (sword64)ad[ 8] * bd[11] + + (sword64)ad[ 9] * bd[10] + + (sword64)ad[10] * bd[ 9] + + (sword64)ad[11] * bd[ 8] + + (sword64)ad[12] * bd[ 7] + + (sword64)ad[13] * bd[ 6] + + (sword64)ad[14] * bd[ 5] + + (sword64)ad[15] * bd[ 4]); + t[20] = (word64)( (sword64)ad[ 5] * bd[15] + + (sword64)ad[ 6] * bd[14] + + (sword64)ad[ 7] * bd[13] + + (sword64)ad[ 8] * bd[12] + + (sword64)ad[ 9] * bd[11] + + (sword64)ad[10] * bd[10] + + (sword64)ad[11] * bd[ 9] + + (sword64)ad[12] * bd[ 8] + + (sword64)ad[13] * bd[ 7] + + (sword64)ad[14] * bd[ 6] + + (sword64)ad[15] * bd[ 5]); + t[21] = (word64)( (sword64)ad[ 6] * bd[15] + + (sword64)ad[ 7] * bd[14] + + (sword64)ad[ 8] * bd[13] + + (sword64)ad[ 9] * bd[12] + + (sword64)ad[10] * bd[11] + + (sword64)ad[11] * bd[10] + + (sword64)ad[12] * bd[ 9] + + (sword64)ad[13] * bd[ 8] + + (sword64)ad[14] * bd[ 7] + + (sword64)ad[15] * bd[ 6]); + t[22] = (word64)( (sword64)ad[ 7] * bd[15] + + (sword64)ad[ 8] * bd[14] + + (sword64)ad[ 9] * bd[13] + + (sword64)ad[10] * bd[12] + + (sword64)ad[11] * bd[11] + + (sword64)ad[12] * bd[10] + + (sword64)ad[13] * bd[ 9] + + (sword64)ad[14] * bd[ 8] + + (sword64)ad[15] * bd[ 7]); + t[23] = (word64)( (sword64)ad[ 8] * bd[15] + + (sword64)ad[ 9] * bd[14] + + (sword64)ad[10] * bd[13] + + (sword64)ad[11] * bd[12] + + (sword64)ad[12] * bd[11] + + (sword64)ad[13] * bd[10] + + (sword64)ad[14] * bd[ 9] + + (sword64)ad[15] * bd[ 8]); + t[24] = (word64)( (sword64)ad[ 9] * bd[15] + + (sword64)ad[10] * bd[14] + + (sword64)ad[11] * bd[13] + + (sword64)ad[12] * bd[12] + + (sword64)ad[13] * bd[11] + + (sword64)ad[14] * bd[10] + + (sword64)ad[15] * bd[ 9]); + t[25] = (word64)( (sword64)ad[10] * bd[15] + + (sword64)ad[11] * bd[14] + + (sword64)ad[12] * bd[13] + + (sword64)ad[13] * bd[12] + + (sword64)ad[14] * bd[11] + + (sword64)ad[15] * bd[10]); + t[26] = (word64)( (sword64)ad[11] * bd[15] + + (sword64)ad[12] * bd[14] + + (sword64)ad[13] * bd[13] + + (sword64)ad[14] * bd[12] + + (sword64)ad[15] * bd[11]); + t[27] = (word64)( (sword64)ad[12] * bd[15] + + (sword64)ad[13] * bd[14] + + (sword64)ad[14] * bd[13] + + (sword64)ad[15] * bd[12]); + t[28] = (word64)( (sword64)ad[13] * bd[15] + + (sword64)ad[14] * bd[14] + + (sword64)ad[15] * bd[13]); + t[29] = (word64)( (sword64)ad[14] * bd[15] + + (sword64)ad[15] * bd[14]); + t[30] = (word64)( (sword64)ad[15] * bd[15]); t[31] = 0; /* Mod curve order */ @@ -6265,110 +6341,126 @@ void sc448_muladd(byte* r, const byte* a, const byte* b, const byte* d) o = rd[14] >> 28; rd[15] += o; rd[14] = rd[14] & 0xfffffff; /* Reduce to mod order. */ u = 0; - u += (sword32)(rd[0] - (sword32)0x0b5844f3L); u >>= 28; - u += (sword32)(rd[1] - (sword32)0x078c292aL); u >>= 28; - u += (sword32)(rd[2] - (sword32)0x058f5523L); u >>= 28; - u += (sword32)(rd[3] - (sword32)0x0c2728dcL); u >>= 28; - u += (sword32)(rd[4] - (sword32)0x0690216cL); u >>= 28; - u += (sword32)(rd[5] - (sword32)0x049aed63L); u >>= 28; - u += (sword32)(rd[6] - (sword32)0x09c44edbL); u >>= 28; - u += (sword32)(rd[7] - (sword32)0x07cca23eL); u >>= 28; - u += (sword32)(rd[8] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[9] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[10] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[11] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[12] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[13] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[14] - (sword32)0x0fffffffL); u >>= 28; - u += (sword32)(rd[15] - (sword32)0x03ffffffL); u >>= 28; + u += (sword32)rd[0] - (sword32)0x0b5844f3L; u >>= 28; + u += (sword32)rd[1] - (sword32)0x078c292aL; u >>= 28; + u += (sword32)rd[2] - (sword32)0x058f5523L; u >>= 28; + u += (sword32)rd[3] - (sword32)0x0c2728dcL; u >>= 28; + u += (sword32)rd[4] - (sword32)0x0690216cL; u >>= 28; + u += (sword32)rd[5] - (sword32)0x049aed63L; u >>= 28; + u += (sword32)rd[6] - (sword32)0x09c44edbL; u >>= 28; + u += (sword32)rd[7] - (sword32)0x07cca23eL; u >>= 28; + u += (sword32)rd[8] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[9] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[10] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[11] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[12] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[13] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[14] - (sword32)0x0fffffffL; u >>= 28; + u += (sword32)rd[15] - (sword32)0x03ffffffL; u >>= 28; o = (word32)0 - (u >= 0); u = 0; - u += (sword32)(rd[0] - ((word32)0x0b5844f3L & o)); rd[0] = u & 0xfffffff; + u += (sword32)rd[0] - (sword32)((word32)0x0b5844f3L & o); + rd[0] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[1] - ((word32)0x078c292aL & o)); rd[1] = u & 0xfffffff; + u += (sword32)rd[1] - (sword32)((word32)0x078c292aL & o); + rd[1] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[2] - ((word32)0x058f5523L & o)); rd[2] = u & 0xfffffff; + u += (sword32)rd[2] - (sword32)((word32)0x058f5523L & o); + rd[2] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[3] - ((word32)0x0c2728dcL & o)); rd[3] = u & 0xfffffff; + u += (sword32)rd[3] - (sword32)((word32)0x0c2728dcL & o); + rd[3] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[4] - ((word32)0x0690216cL & o)); rd[4] = u & 0xfffffff; + u += (sword32)rd[4] - (sword32)((word32)0x0690216cL & o); + rd[4] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[5] - ((word32)0x049aed63L & o)); rd[5] = u & 0xfffffff; + u += (sword32)rd[5] - (sword32)((word32)0x049aed63L & o); + rd[5] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[6] - ((word32)0x09c44edbL & o)); rd[6] = u & 0xfffffff; + u += (sword32)rd[6] - (sword32)((word32)0x09c44edbL & o); + rd[6] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[7] - ((word32)0x07cca23eL & o)); rd[7] = u & 0xfffffff; + u += (sword32)rd[7] - (sword32)((word32)0x07cca23eL & o); + rd[7] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[8] - ((word32)0x0fffffffL & o)); rd[8] = u & 0xfffffff; + u += (sword32)rd[8] - (sword32)((word32)0x0fffffffL & o); + rd[8] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[9] - ((word32)0x0fffffffL & o)); rd[9] = u & 0xfffffff; + u += (sword32)rd[9] - (sword32)((word32)0x0fffffffL & o); + rd[9] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[10] - ((word32)0x0fffffffL & o)); rd[10] = u & 0xfffffff; + u += (sword32)rd[10] - (sword32)((word32)0x0fffffffL & o); + rd[10] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[11] - ((word32)0x0fffffffL & o)); rd[11] = u & 0xfffffff; + u += (sword32)rd[11] - (sword32)((word32)0x0fffffffL & o); + rd[11] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[12] - ((word32)0x0fffffffL & o)); rd[12] = u & 0xfffffff; + u += (sword32)rd[12] - (sword32)((word32)0x0fffffffL & o); + rd[12] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[13] - ((word32)0x0fffffffL & o)); rd[13] = u & 0xfffffff; + u += (sword32)rd[13] - (sword32)((word32)0x0fffffffL & o); + rd[13] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[14] - ((word32)0x0fffffffL & o)); rd[14] = u & 0xfffffff; + u += (sword32)rd[14] - (sword32)((word32)0x0fffffffL & o); + rd[14] = u & 0xfffffff; u >>= 28; - u += (sword32)(rd[15] - ((word32)0x03ffffffL & o)); rd[15] = u & 0xfffffff; + u += (sword32)rd[15] - (sword32)((word32)0x03ffffffL & o); + rd[15] = u & 0xfffffff; /* Convert to bytes */ r[ 0] = (byte)(rd[0 ] >> 0); r[ 1] = (byte)(rd[0 ] >> 8); r[ 2] = (byte)(rd[0 ] >> 16); - r[ 3] = (byte)(rd[0 ] >> 24) + (byte)((rd[1 ] >> 0) << 4); + r[ 3] = (byte)((byte)(rd[0 ] >> 24) + (byte)((rd[1 ] >> 0) << 4)); r[ 4] = (byte)(rd[1 ] >> 4); r[ 5] = (byte)(rd[1 ] >> 12); r[ 6] = (byte)(rd[1 ] >> 20); r[ 7] = (byte)(rd[2 ] >> 0); r[ 8] = (byte)(rd[2 ] >> 8); r[ 9] = (byte)(rd[2 ] >> 16); - r[10] = (byte)(rd[2 ] >> 24) + (byte)((rd[3 ] >> 0) << 4); + r[10] = (byte)((byte)(rd[2 ] >> 24) + (byte)((rd[3 ] >> 0) << 4)); r[11] = (byte)(rd[3 ] >> 4); r[12] = (byte)(rd[3 ] >> 12); r[13] = (byte)(rd[3 ] >> 20); r[14] = (byte)(rd[4 ] >> 0); r[15] = (byte)(rd[4 ] >> 8); r[16] = (byte)(rd[4 ] >> 16); - r[17] = (byte)(rd[4 ] >> 24) + (byte)((rd[5 ] >> 0) << 4); + r[17] = (byte)((byte)(rd[4 ] >> 24) + (byte)((rd[5 ] >> 0) << 4)); r[18] = (byte)(rd[5 ] >> 4); r[19] = (byte)(rd[5 ] >> 12); r[20] = (byte)(rd[5 ] >> 20); r[21] = (byte)(rd[6 ] >> 0); r[22] = (byte)(rd[6 ] >> 8); r[23] = (byte)(rd[6 ] >> 16); - r[24] = (byte)(rd[6 ] >> 24) + (byte)((rd[7 ] >> 0) << 4); + r[24] = (byte)((byte)(rd[6 ] >> 24) + (byte)((rd[7 ] >> 0) << 4)); r[25] = (byte)(rd[7 ] >> 4); r[26] = (byte)(rd[7 ] >> 12); r[27] = (byte)(rd[7 ] >> 20); r[28] = (byte)(rd[8 ] >> 0); r[29] = (byte)(rd[8 ] >> 8); r[30] = (byte)(rd[8 ] >> 16); - r[31] = (byte)(rd[8 ] >> 24) + (byte)((rd[9 ] >> 0) << 4); + r[31] = (byte)((byte)(rd[8 ] >> 24) + (byte)((rd[9 ] >> 0) << 4)); r[32] = (byte)(rd[9 ] >> 4); r[33] = (byte)(rd[9 ] >> 12); r[34] = (byte)(rd[9 ] >> 20); r[35] = (byte)(rd[10] >> 0); r[36] = (byte)(rd[10] >> 8); r[37] = (byte)(rd[10] >> 16); - r[38] = (byte)(rd[10] >> 24) + (byte)((rd[11] >> 0) << 4); + r[38] = (byte)((byte)(rd[10] >> 24) + (byte)((rd[11] >> 0) << 4)); r[39] = (byte)(rd[11] >> 4); r[40] = (byte)(rd[11] >> 12); r[41] = (byte)(rd[11] >> 20); r[42] = (byte)(rd[12] >> 0); r[43] = (byte)(rd[12] >> 8); r[44] = (byte)(rd[12] >> 16); - r[45] = (byte)(rd[12] >> 24) + (byte)((rd[13] >> 0) << 4); + r[45] = (byte)((byte)(rd[12] >> 24) + (byte)((rd[13] >> 0) << 4)); r[46] = (byte)(rd[13] >> 4); r[47] = (byte)(rd[13] >> 12); r[48] = (byte)(rd[13] >> 20); r[49] = (byte)(rd[14] >> 0); r[50] = (byte)(rd[14] >> 8); r[51] = (byte)(rd[14] >> 16); - r[52] = (byte)(rd[14] >> 24) + (byte)((rd[15] >> 0) << 4); + r[52] = (byte)((byte)(rd[14] >> 24) + (byte)((rd[15] >> 0) << 4)); r[53] = (byte)(rd[15] >> 4); r[54] = (byte)(rd[15] >> 12); r[55] = (byte)(rd[15] >> 20); diff --git a/src/wolfcrypt/src/ge_low_mem.c b/src/wolfcrypt/src/ge_low_mem.c index cb505af..c0a952b 100644 --- a/src/wolfcrypt/src/ge_low_mem.c +++ b/src/wolfcrypt/src/ge_low_mem.c @@ -1,6 +1,6 @@ /* ge_low_mem.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,20 +19,14 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include /* Based from Daniel Beer's public domain work. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - #ifdef HAVE_ED25519 #ifdef ED25519_SMALL /* use slower code that takes less memory */ #include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/ge_operations.c b/src/wolfcrypt/src/ge_operations.c index 4a50d46..bde5a06 100644 --- a/src/wolfcrypt/src/ge_operations.c +++ b/src/wolfcrypt/src/ge_operations.c @@ -1,6 +1,6 @@ /* ge_operations.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,19 +22,13 @@ /* Based On Daniel J Bernstein's ed25519 Public Domain ref10 work. */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_ED25519 #ifndef ED25519_SMALL /* run when not defined to use small memory math */ #include #include -#include #ifdef NO_INLINE #include #else @@ -9392,7 +9386,7 @@ B is the Ed25519 base point (x,4/5) with x positive. int ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, const ge_p3 *A, const unsigned char *b) { -#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) signed char *aslide = NULL; signed char *bslide = NULL; ge_cached *Ai = NULL; /* A,3A,5A,7A,9A,11A,13A,15A */ @@ -9413,7 +9407,7 @@ int ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, #endif int i; -#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) if (((aslide = (signed char *)XMALLOC(SLIDE_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER))== NULL) || ((bslide = (signed char *)XMALLOC(SLIDE_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER))== NULL) || ((Ai = (ge_cached *)XMALLOC(8 * sizeof(*Ai), NULL, DYNAMIC_TYPE_TMP_BUFFER))== NULL) || @@ -9475,7 +9469,7 @@ int ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, } #endif -#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) out: XFREE(aslide, NULL, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/src/wolfcrypt/src/hash.c b/src/wolfcrypt/src/hash.c index 4850a84..c709fa3 100644 --- a/src/wolfcrypt/src/hash.c +++ b/src/wolfcrypt/src/hash.c @@ -1,6 +1,6 @@ /* hash.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include #ifndef NO_ASN #include #endif diff --git a/src/wolfcrypt/src/hmac.c b/src/wolfcrypt/src/hmac.c index 65dbf66..912b26d 100644 --- a/src/wolfcrypt/src/hmac.c +++ b/src/wolfcrypt/src/hmac.c @@ -1,6 +1,6 @@ /* hmac.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -20,14 +20,7 @@ */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include -#include +#include #ifndef NO_HMAC @@ -155,76 +148,72 @@ int wc_HmacSizeByType(int type) return ret; } -int _InitHmac(Hmac* hmac, int type, void* heap) +static int HmacKeyInitHash(wc_HmacHash* hash, int type, void* heap, int devId) { int ret = 0; -#ifdef WOLF_CRYPTO_CB - int devId = hmac->devId; -#else - int devId = INVALID_DEVID; -#endif + switch (type) { #ifndef NO_MD5 case WC_MD5: - ret = wc_InitMd5_ex(&hmac->hash.md5, heap, devId); + ret = wc_InitMd5_ex(&hash->md5, heap, devId); break; #endif /* !NO_MD5 */ #ifndef NO_SHA case WC_SHA: - ret = wc_InitSha_ex(&hmac->hash.sha, heap, devId); + ret = wc_InitSha_ex(&hash->sha, heap, devId); break; #endif /* !NO_SHA */ #ifdef WOLFSSL_SHA224 case WC_SHA224: - ret = wc_InitSha224_ex(&hmac->hash.sha224, heap, devId); + ret = wc_InitSha224_ex(&hash->sha224, heap, devId); break; #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 case WC_SHA256: - ret = wc_InitSha256_ex(&hmac->hash.sha256, heap, devId); + ret = wc_InitSha256_ex(&hash->sha256, heap, devId); break; #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 case WC_SHA384: - ret = wc_InitSha384_ex(&hmac->hash.sha384, heap, devId); + ret = wc_InitSha384_ex(&hash->sha384, heap, devId); break; #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 case WC_SHA512: - ret = wc_InitSha512_ex(&hmac->hash.sha512, heap, devId); + ret = wc_InitSha512_ex(&hash->sha512, heap, devId); break; #endif /* WOLFSSL_SHA512 */ #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 case WC_SHA3_224: - ret = wc_InitSha3_224(&hmac->hash.sha3, heap, devId); + ret = wc_InitSha3_224(&hash->sha3, heap, devId); break; #endif #ifndef WOLFSSL_NOSHA3_256 case WC_SHA3_256: - ret = wc_InitSha3_256(&hmac->hash.sha3, heap, devId); + ret = wc_InitSha3_256(&hash->sha3, heap, devId); break; #endif #ifndef WOLFSSL_NOSHA3_384 case WC_SHA3_384: - ret = wc_InitSha3_384(&hmac->hash.sha3, heap, devId); + ret = wc_InitSha3_384(&hash->sha3, heap, devId); break; #endif #ifndef WOLFSSL_NOSHA3_512 case WC_SHA3_512: - ret = wc_InitSha3_512(&hmac->hash.sha3, heap, devId); + ret = wc_InitSha3_512(&hash->sha3, heap, devId); break; #endif #endif #ifdef WOLFSSL_SM3 case WC_SM3: - ret = wc_InitSm3(&hmac->hash.sm3, heap, devId); + ret = wc_InitSm3(&hash->sm3, heap, devId); break; #endif @@ -233,6 +222,22 @@ int _InitHmac(Hmac* hmac, int type, void* heap) break; } + return ret; +} + +int _InitHmac(Hmac* hmac, int type, void* heap) +{ + int ret; +#ifdef WOLF_CRYPTO_CB + int devId = hmac->devId; +#else + int devId = INVALID_DEVID; +#endif + + ret = HmacKeyInitHash(&hmac->hash, type, heap, devId); + if (ret != 0) + return ret; + /* default to NULL heap hint or test value */ #ifdef WOLFSSL_HEAP_TEST hmac->heap = (void*)WOLFSSL_HEAP_TEST; @@ -243,6 +248,158 @@ int _InitHmac(Hmac* hmac, int type, void* heap) return ret; } +#ifdef WOLFSSL_HMAC_COPY_HASH +static int HmacKeyCopyHash(byte macType, wc_HmacHash* src, wc_HmacHash* dst) +{ + int ret = 0; + + switch (macType) { + #ifndef NO_MD5 + case WC_MD5: + ret = wc_Md5Copy(&src->md5, &dst->md5); + break; + #endif /* !NO_MD5 */ + + #ifndef NO_SHA + case WC_SHA: + ret = wc_ShaCopy(&src->sha, &dst->sha); + break; + #endif /* !NO_SHA */ + + #ifdef WOLFSSL_SHA224 + case WC_SHA224: + ret = wc_Sha224Copy(&src->sha224, &dst->sha224); + break; + #endif /* WOLFSSL_SHA224 */ + #ifndef NO_SHA256 + case WC_SHA256: + ret = wc_Sha256Copy(&src->sha256, &dst->sha256); + break; + #endif /* !NO_SHA256 */ + + #ifdef WOLFSSL_SHA384 + case WC_SHA384: + ret = wc_Sha384Copy(&src->sha384, &dst->sha384); + break; + #endif /* WOLFSSL_SHA384 */ + #ifdef WOLFSSL_SHA512 + case WC_SHA512: + ret = wc_Sha512Copy(&src->sha512, &dst->sha512); + break; + #endif /* WOLFSSL_SHA512 */ + + #ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + case WC_SHA3_224: + ret = wc_Sha3_224_Copy(&src->sha3, &dst->sha3); + break; + #endif + #ifndef WOLFSSL_NOSHA3_256 + case WC_SHA3_256: + ret = wc_Sha3_256_Copy(&src->sha3, &dst->sha3); + break; + #endif + #ifndef WOLFSSL_NOSHA3_384 + case WC_SHA3_384: + ret = wc_Sha3_384_Copy(&src->sha3, &dst->sha3); + break; + #endif + #ifndef WOLFSSL_NOSHA3_512 + case WC_SHA3_512: + ret = wc_Sha3_512_Copy(&src->sha3, &dst->sha3); + break; + #endif + #endif /* WOLFSSL_SHA3 */ + + #ifdef WOLFSSL_SM3 + case WC_SM3: + ret = wc_Sm3Copy(&src->sm3, &dst->sm3); + break; + #endif + + default: + break; + } + + return ret; +} +#endif + +static int HmacKeyHashUpdate(byte macType, wc_HmacHash* hash, byte* pad) +{ + int ret = 0; + + switch (macType) { + #ifndef NO_MD5 + case WC_MD5: + ret = wc_Md5Update(&hash->md5, pad, WC_MD5_BLOCK_SIZE); + break; + #endif /* !NO_MD5 */ + + #ifndef NO_SHA + case WC_SHA: + ret = wc_ShaUpdate(&hash->sha, pad, WC_SHA_BLOCK_SIZE); + break; + #endif /* !NO_SHA */ + + #ifdef WOLFSSL_SHA224 + case WC_SHA224: + ret = wc_Sha224Update(&hash->sha224, pad, WC_SHA224_BLOCK_SIZE); + break; + #endif /* WOLFSSL_SHA224 */ + #ifndef NO_SHA256 + case WC_SHA256: + ret = wc_Sha256Update(&hash->sha256, pad, WC_SHA256_BLOCK_SIZE); + break; + #endif /* !NO_SHA256 */ + + #ifdef WOLFSSL_SHA384 + case WC_SHA384: + ret = wc_Sha384Update(&hash->sha384, pad, WC_SHA384_BLOCK_SIZE); + break; + #endif /* WOLFSSL_SHA384 */ + #ifdef WOLFSSL_SHA512 + case WC_SHA512: + ret = wc_Sha512Update(&hash->sha512, pad, WC_SHA512_BLOCK_SIZE); + break; + #endif /* WOLFSSL_SHA512 */ + + #ifdef WOLFSSL_SHA3 + #ifndef WOLFSSL_NOSHA3_224 + case WC_SHA3_224: + ret = wc_Sha3_224_Update(&hash->sha3, pad, WC_SHA3_224_BLOCK_SIZE); + break; + #endif + #ifndef WOLFSSL_NOSHA3_256 + case WC_SHA3_256: + ret = wc_Sha3_256_Update(&hash->sha3, pad, WC_SHA3_256_BLOCK_SIZE); + break; + #endif + #ifndef WOLFSSL_NOSHA3_384 + case WC_SHA3_384: + ret = wc_Sha3_384_Update(&hash->sha3, pad, WC_SHA3_384_BLOCK_SIZE); + break; + #endif + #ifndef WOLFSSL_NOSHA3_512 + case WC_SHA3_512: + ret = wc_Sha3_512_Update(&hash->sha3, pad, WC_SHA3_512_BLOCK_SIZE); + break; + #endif + #endif /* WOLFSSL_SHA3 */ + + #ifdef WOLFSSL_SM3 + case WC_SM3: + ret = wc_Sm3Update(&hash->sm3, pad, WC_SM3_BLOCK_SIZE); + break; + #endif + + default: + break; + } + + return ret; +} + int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, int allowFlag) @@ -603,6 +760,29 @@ int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, } } +#ifdef WOLFSSL_HMAC_COPY_HASH + if ( ret == 0) { + #ifdef WOLF_CRYPTO_CB + int devId = hmac->devId; + #else + int devId = INVALID_DEVID; + #endif + + ret = HmacKeyInitHash(&hmac->i_hash, hmac->macType, heap, devId); + if (ret != 0) + return ret; + ret = HmacKeyInitHash(&hmac->o_hash, hmac->macType, heap, devId); + if (ret != 0) + return ret; + ret = HmacKeyHashUpdate(hmac->macType, &hmac->i_hash, ip); + if (ret != 0) + return ret; + ret = HmacKeyHashUpdate(hmac->macType, &hmac->o_hash, op); + if (ret != 0) + return ret; + } +#endif + return ret; #endif /* WOLFSSL_MAXQ108X */ } @@ -618,96 +798,6 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) return wc_HmacSetKey_ex(hmac, type, key, length, allowFlag); } -static int HmacKeyInnerHash(Hmac* hmac) -{ - int ret = 0; - - switch (hmac->macType) { - #ifndef NO_MD5 - case WC_MD5: - ret = wc_Md5Update(&hmac->hash.md5, (byte*)hmac->ipad, - WC_MD5_BLOCK_SIZE); - break; - #endif /* !NO_MD5 */ - - #ifndef NO_SHA - case WC_SHA: - ret = wc_ShaUpdate(&hmac->hash.sha, (byte*)hmac->ipad, - WC_SHA_BLOCK_SIZE); - break; - #endif /* !NO_SHA */ - - #ifdef WOLFSSL_SHA224 - case WC_SHA224: - ret = wc_Sha224Update(&hmac->hash.sha224, (byte*)hmac->ipad, - WC_SHA224_BLOCK_SIZE); - break; - #endif /* WOLFSSL_SHA224 */ - #ifndef NO_SHA256 - case WC_SHA256: - ret = wc_Sha256Update(&hmac->hash.sha256, (byte*)hmac->ipad, - WC_SHA256_BLOCK_SIZE); - break; - #endif /* !NO_SHA256 */ - - #ifdef WOLFSSL_SHA384 - case WC_SHA384: - ret = wc_Sha384Update(&hmac->hash.sha384, (byte*)hmac->ipad, - WC_SHA384_BLOCK_SIZE); - break; - #endif /* WOLFSSL_SHA384 */ - #ifdef WOLFSSL_SHA512 - case WC_SHA512: - ret = wc_Sha512Update(&hmac->hash.sha512, (byte*)hmac->ipad, - WC_SHA512_BLOCK_SIZE); - break; - #endif /* WOLFSSL_SHA512 */ - - #ifdef WOLFSSL_SHA3 - #ifndef WOLFSSL_NOSHA3_224 - case WC_SHA3_224: - ret = wc_Sha3_224_Update(&hmac->hash.sha3, (byte*)hmac->ipad, - WC_SHA3_224_BLOCK_SIZE); - break; - #endif - #ifndef WOLFSSL_NOSHA3_256 - case WC_SHA3_256: - ret = wc_Sha3_256_Update(&hmac->hash.sha3, (byte*)hmac->ipad, - WC_SHA3_256_BLOCK_SIZE); - break; - #endif - #ifndef WOLFSSL_NOSHA3_384 - case WC_SHA3_384: - ret = wc_Sha3_384_Update(&hmac->hash.sha3, (byte*)hmac->ipad, - WC_SHA3_384_BLOCK_SIZE); - break; - #endif - #ifndef WOLFSSL_NOSHA3_512 - case WC_SHA3_512: - ret = wc_Sha3_512_Update(&hmac->hash.sha3, (byte*)hmac->ipad, - WC_SHA3_512_BLOCK_SIZE); - break; - #endif - #endif /* WOLFSSL_SHA3 */ - - #ifdef WOLFSSL_SM3 - case WC_SM3: - ret = wc_Sm3Update(&hmac->hash.sm3, (byte*)hmac->ipad, - WC_SM3_BLOCK_SIZE); - break; - #endif - - default: - break; - } - - if (ret == 0) - hmac->innerHashKeyed = WC_HMAC_INNER_HASH_KEYED_SW; - - return ret; -} - - int wc_HmacUpdate(Hmac* hmac, const byte* msg, word32 length) { int ret = 0; @@ -739,9 +829,14 @@ int wc_HmacUpdate(Hmac* hmac, const byte* msg, word32 length) #endif /* WOLFSSL_ASYNC_CRYPT */ if (!hmac->innerHashKeyed) { - ret = HmacKeyInnerHash(hmac); +#ifndef WOLFSSL_HMAC_COPY_HASH + ret = HmacKeyHashUpdate(hmac->macType, &hmac->hash, (byte*)hmac->ipad); +#else + ret = HmacKeyCopyHash(hmac->macType, &hmac->i_hash, &hmac->hash); +#endif if (ret != 0) return ret; + hmac->innerHashKeyed = WC_HMAC_INNER_HASH_KEYED_SW; } switch (hmac->macType) { @@ -851,9 +946,14 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) #endif /* WOLFSSL_ASYNC_CRYPT */ if (!hmac->innerHashKeyed) { - ret = HmacKeyInnerHash(hmac); +#ifndef WOLFSSL_HMAC_COPY_HASH + ret = HmacKeyHashUpdate(hmac->macType, &hmac->hash, (byte*)hmac->ipad); +#else + ret = HmacKeyCopyHash(hmac->macType, &hmac->i_hash, &hmac->hash); +#endif if (ret != 0) return ret; + hmac->innerHashKeyed = WC_HMAC_INNER_HASH_KEYED_SW; } switch (hmac->macType) { @@ -862,8 +962,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Md5Final(&hmac->hash.md5, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Md5Update(&hmac->hash.md5, (byte*)hmac->opad, WC_MD5_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_MD5, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Md5Update(&hmac->hash.md5, (byte*)hmac->innerHash, @@ -879,8 +983,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_ShaFinal(&hmac->hash.sha, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_ShaUpdate(&hmac->hash.sha, (byte*)hmac->opad, WC_SHA_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_ShaUpdate(&hmac->hash.sha, (byte*)hmac->innerHash, @@ -896,8 +1004,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha224Final(&hmac->hash.sha224, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha224Update(&hmac->hash.sha224, (byte*)hmac->opad, WC_SHA224_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA224, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha224Update(&hmac->hash.sha224, (byte*)hmac->innerHash, @@ -914,8 +1026,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha256Final(&hmac->hash.sha256, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha256Update(&hmac->hash.sha256, (byte*)hmac->opad, WC_SHA256_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA256, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha256Update(&hmac->hash.sha256, (byte*)hmac->innerHash, @@ -931,8 +1047,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha384Final(&hmac->hash.sha384, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha384Update(&hmac->hash.sha384, (byte*)hmac->opad, WC_SHA384_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA384, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha384Update(&hmac->hash.sha384, (byte*)hmac->innerHash, @@ -947,8 +1067,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha512Final(&hmac->hash.sha512, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha512Update(&hmac->hash.sha512, (byte*)hmac->opad, WC_SHA512_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA512, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha512Update(&hmac->hash.sha512, (byte*)hmac->innerHash, @@ -965,8 +1089,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha3_224_Final(&hmac->hash.sha3, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha3_224_Update(&hmac->hash.sha3, (byte*)hmac->opad, WC_SHA3_224_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA3_224, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha3_224_Update(&hmac->hash.sha3, (byte*)hmac->innerHash, @@ -981,8 +1109,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha3_256_Final(&hmac->hash.sha3, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha3_256_Update(&hmac->hash.sha3, (byte*)hmac->opad, WC_SHA3_256_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA3_256, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha3_256_Update(&hmac->hash.sha3, (byte*)hmac->innerHash, @@ -997,8 +1129,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha3_384_Final(&hmac->hash.sha3, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha3_384_Update(&hmac->hash.sha3, (byte*)hmac->opad, WC_SHA3_384_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA3_384, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha3_384_Update(&hmac->hash.sha3, (byte*)hmac->innerHash, @@ -1013,8 +1149,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sha3_512_Final(&hmac->hash.sha3, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sha3_512_Update(&hmac->hash.sha3, (byte*)hmac->opad, WC_SHA3_512_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SHA3_512, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sha3_512_Update(&hmac->hash.sha3, (byte*)hmac->innerHash, @@ -1031,8 +1171,12 @@ int wc_HmacFinal(Hmac* hmac, byte* hash) ret = wc_Sm3Final(&hmac->hash.sm3, (byte*)hmac->innerHash); if (ret != 0) break; + #ifndef WOLFSSL_HMAC_COPY_HASH ret = wc_Sm3Update(&hmac->hash.sm3, (byte*)hmac->opad, WC_SM3_BLOCK_SIZE); + #else + ret = HmacKeyCopyHash(WC_SM3, &hmac->o_hash, &hmac->hash); + #endif if (ret != 0) break; ret = wc_Sm3Update(&hmac->hash.sm3, (byte*)hmac->innerHash, @@ -1163,34 +1307,58 @@ void wc_HmacFree(Hmac* hmac) #ifndef NO_MD5 case WC_MD5: wc_Md5Free(&hmac->hash.md5); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Md5Free(&hmac->i_hash.md5); + wc_Md5Free(&hmac->o_hash.md5); + #endif break; #endif /* !NO_MD5 */ #ifndef NO_SHA case WC_SHA: wc_ShaFree(&hmac->hash.sha); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_ShaFree(&hmac->i_hash.sha); + wc_ShaFree(&hmac->o_hash.sha); + #endif break; #endif /* !NO_SHA */ #ifdef WOLFSSL_SHA224 case WC_SHA224: wc_Sha224Free(&hmac->hash.sha224); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha224Free(&hmac->i_hash.sha224); + wc_Sha224Free(&hmac->o_hash.sha224); + #endif break; #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 case WC_SHA256: wc_Sha256Free(&hmac->hash.sha256); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha256Free(&hmac->i_hash.sha256); + wc_Sha256Free(&hmac->o_hash.sha256); + #endif break; #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 case WC_SHA384: wc_Sha384Free(&hmac->hash.sha384); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha384Free(&hmac->i_hash.sha384); + wc_Sha384Free(&hmac->o_hash.sha384); + #endif break; #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 case WC_SHA512: wc_Sha512Free(&hmac->hash.sha512); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha512Free(&hmac->i_hash.sha512); + wc_Sha512Free(&hmac->o_hash.sha512); + #endif break; #endif /* WOLFSSL_SHA512 */ @@ -1198,21 +1366,37 @@ void wc_HmacFree(Hmac* hmac) #ifndef WOLFSSL_NOSHA3_224 case WC_SHA3_224: wc_Sha3_224_Free(&hmac->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha3_224_Free(&hmac->i_hash.sha3); + wc_Sha3_224_Free(&hmac->o_hash.sha3); + #endif break; #endif #ifndef WOLFSSL_NOSHA3_256 case WC_SHA3_256: wc_Sha3_256_Free(&hmac->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha3_256_Free(&hmac->i_hash.sha3); + wc_Sha3_256_Free(&hmac->o_hash.sha3); + #endif break; #endif #ifndef WOLFSSL_NOSHA3_384 case WC_SHA3_384: wc_Sha3_384_Free(&hmac->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha3_384_Free(&hmac->i_hash.sha3); + wc_Sha3_384_Free(&hmac->o_hash.sha3); + #endif break; #endif #ifndef WOLFSSL_NOSHA3_512 case WC_SHA3_512: wc_Sha3_512_Free(&hmac->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sha3_512_Free(&hmac->i_hash.sha3); + wc_Sha3_512_Free(&hmac->o_hash.sha3); + #endif break; #endif #endif /* WOLFSSL_SHA3 */ @@ -1220,6 +1404,10 @@ void wc_HmacFree(Hmac* hmac) #ifdef WOLFSSL_SM3 case WC_SM3: wc_Sm3Free(&hmac->hash.sm3); + #ifdef WOLFSSL_HMAC_COPY_HASH + wc_Sm3Free(&hmac->i_hash.sm3); + wc_Sm3Free(&hmac->i_hash.sm3); + #endif break; #endif diff --git a/src/wolfcrypt/src/hpke.c b/src/wolfcrypt/src/hpke.c index 02e189b..8ce209f 100644 --- a/src/wolfcrypt/src/hpke.c +++ b/src/wolfcrypt/src/hpke.c @@ -1,6 +1,6 @@ /* hpke.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -23,16 +23,11 @@ * TODO: Add X448 and ChaCha20 */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(HAVE_HPKE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519)) && \ defined(HAVE_AESGCM) -#include #include #include #include @@ -591,6 +586,10 @@ static int wc_HpkeContextComputeNonce(Hpke* hpke, HpkeBaseContext* context, int ret; byte seq_bytes[HPKE_Nn_MAX]; + if (hpke == NULL || context == NULL) { + return BAD_FUNC_ARG; + } + /* convert the sequence into a byte string with the same length as the * nonce */ ret = I2OSP(context->seq, (int)hpke->Nn, seq_bytes); @@ -875,49 +874,63 @@ static int wc_HpkeSetupBaseSender(Hpke* hpke, HpkeBaseContext* context, return ret; } +/* give SetupBaseSender a more intuitive and wolfCrypt friendly name */ +int wc_HpkeInitSealContext(Hpke* hpke, HpkeBaseContext* context, + void* ephemeralKey, void* receiverKey, byte* info, word32 infoSz) +{ + if (hpke == NULL || context == NULL || ephemeralKey == NULL || + receiverKey == NULL || (info == NULL && infoSz > 0)) { + return BAD_FUNC_ARG; + } + + /* zero out all fields */ + XMEMSET(context, 0, sizeof(HpkeBaseContext)); + + return wc_HpkeSetupBaseSender(hpke, context, ephemeralKey, receiverKey, + info, infoSz); +} + /* encrypt a message using an hpke base context, return 0 or error */ -static int wc_HpkeContextSealBase(Hpke* hpke, HpkeBaseContext* context, +int wc_HpkeContextSealBase(Hpke* hpke, HpkeBaseContext* context, byte* aad, word32 aadSz, byte* plaintext, word32 ptSz, byte* out) { int ret; byte nonce[HPKE_Nn_MAX]; #ifndef WOLFSSL_SMALL_STACK - Aes aes_key[1]; + Aes aes[1]; #else - Aes* aes_key; + Aes* aes; #endif - - if (hpke == NULL) { + if (hpke == NULL || context == NULL || (aad == NULL && aadSz > 0) || + plaintext == NULL || out == NULL) { return BAD_FUNC_ARG; } - #ifdef WOLFSSL_SMALL_STACK - aes_key = (Aes*)XMALLOC(sizeof(Aes), hpke->heap, DYNAMIC_TYPE_AES); - if (aes_key == NULL) { + aes = (Aes*)XMALLOC(sizeof(Aes), hpke->heap, DYNAMIC_TYPE_AES); + if (aes == NULL) { return MEMORY_E; } #endif - - ret = wc_AesInit(aes_key, hpke->heap, INVALID_DEVID); + ret = wc_AesInit(aes, hpke->heap, INVALID_DEVID); if (ret == 0) { + /* compute nonce */ ret = wc_HpkeContextComputeNonce(hpke, context, nonce); if (ret == 0) { - ret = wc_AesGcmSetKey(aes_key, context->key, hpke->Nk); + ret = wc_AesGcmSetKey(aes, context->key, hpke->Nk); } if (ret == 0) { - ret = wc_AesGcmEncrypt(aes_key, out, plaintext, ptSz, nonce, + ret = wc_AesGcmEncrypt(aes, out, plaintext, ptSz, nonce, hpke->Nn, out + ptSz, hpke->Nt, aad, aadSz); } + /* increment sequence for non one shot */ if (ret == 0) { context->seq++; } - wc_AesFree(aes_key); + wc_AesFree(aes); } - #ifdef WOLFSSL_SMALL_STACK - XFREE(aes_key, hpke->heap, DYNAMIC_TYPE_AES); + XFREE(aes, hpke->heap, DYNAMIC_TYPE_AES); #endif - return ret; } @@ -1021,8 +1034,10 @@ static int wc_HpkeDecap(Hpke* hpke, void* receiverKey, const byte* pubKey, #ifdef ECC_TIMING_RESISTANT rng = wc_rng_new(NULL, 0, hpke->heap); - if (rng == NULL) - return RNG_FAILURE_E; + if (rng == NULL) { + ret = RNG_FAILURE_E; + break; + } wc_ecc_set_rng((ecc_key*)receiverKey, rng); #endif @@ -1111,49 +1126,60 @@ static int wc_HpkeSetupBaseReceiver(Hpke* hpke, HpkeBaseContext* context, return ret; } +/* give SetupBaseReceiver a more intuitive and wolfCrypt friendly name */ +int wc_HpkeInitOpenContext(Hpke* hpke, HpkeBaseContext* context, + void* receiverKey, const byte* pubKey, word16 pubKeySz, byte* info, + word32 infoSz) +{ + if (hpke == NULL || context == NULL || receiverKey == NULL || pubKey == NULL + || (info == NULL && infoSz > 0)) { + return BAD_FUNC_ARG; + } + + return wc_HpkeSetupBaseReceiver(hpke, context, receiverKey, pubKey, + pubKeySz, info, infoSz); +} + /* decrypt a message using a setup hpke context, return 0 or error */ -static int wc_HpkeContextOpenBase(Hpke* hpke, HpkeBaseContext* context, - byte* aad, word32 aadSz, byte* ciphertext, word32 ctSz, byte* out) +int wc_HpkeContextOpenBase(Hpke* hpke, HpkeBaseContext* context, byte* aad, + word32 aadSz, byte* ciphertext, word32 ctSz, byte* out) { int ret; byte nonce[HPKE_Nn_MAX]; #ifndef WOLFSSL_SMALL_STACK - Aes aes_key[1]; + Aes aes[1]; #else - Aes* aes_key; + Aes* aes; #endif - if (hpke == NULL) { return BAD_FUNC_ARG; } - XMEMSET(nonce, 0, sizeof(nonce)); #ifdef WOLFSSL_SMALL_STACK - aes_key = (Aes*)XMALLOC(sizeof(Aes), hpke->heap, DYNAMIC_TYPE_AES); - if (aes_key == NULL) { + aes = (Aes*)XMALLOC(sizeof(Aes), hpke->heap, DYNAMIC_TYPE_AES); + if (aes == NULL) { return MEMORY_E; } #endif - + /* compute nonce */ ret = wc_HpkeContextComputeNonce(hpke, context, nonce); if (ret == 0) - ret = wc_AesInit(aes_key, hpke->heap, INVALID_DEVID); + ret = wc_AesInit(aes, hpke->heap, INVALID_DEVID); if (ret == 0) { - ret = wc_AesGcmSetKey(aes_key, context->key, hpke->Nk); + ret = wc_AesGcmSetKey(aes, context->key, hpke->Nk); if (ret == 0) { - ret = wc_AesGcmDecrypt(aes_key, out, ciphertext, ctSz, nonce, + ret = wc_AesGcmDecrypt(aes, out, ciphertext, ctSz, nonce, hpke->Nn, ciphertext + ctSz, hpke->Nt, aad, aadSz); } + /* increment sequence for non one shot */ if (ret == 0) { context->seq++; } - wc_AesFree(aes_key); + wc_AesFree(aes); } - #ifdef WOLFSSL_SMALL_STACK - XFREE(aes_key, hpke->heap, DYNAMIC_TYPE_AES); + XFREE(aes, hpke->heap, DYNAMIC_TYPE_AES); #endif - return ret; } diff --git a/src/wolfcrypt/src/integer.c b/src/wolfcrypt/src/integer.c index 3deeaeb..341d99d 100644 --- a/src/wolfcrypt/src/integer.c +++ b/src/wolfcrypt/src/integer.c @@ -1,6 +1,6 @@ /* integer.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,21 +19,13 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - +#include /* * Based on public domain LibTomMath 0.38 by Tom St Denis, tomstdenis@iahu.ca, * http://math.libtomcrypt.com */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set USE_FAST_MATH there */ -#include - #ifndef NO_BIG_INT #if !defined(USE_FAST_MATH) && defined(USE_INTEGER_HEAP_MATH) @@ -177,6 +169,9 @@ int mp_init (mp_int * a) /* clear one (frees) */ void mp_clear (mp_int * a) { +#ifdef HAVE_FIPS + mp_forcezero(a); +#else int i; if (a == NULL) @@ -202,6 +197,7 @@ void mp_clear (mp_int * a) a->alloc = a->used = 0; a->sign = MP_ZPOS; } +#endif } void mp_free (mp_int * a) @@ -409,11 +405,10 @@ int mp_copy (const mp_int * a, mp_int * b) /* grow as required */ int mp_grow (mp_int * a, int size) { - int i; mp_digit *tmp; /* if the alloc size is smaller alloc more ram */ - if (a->alloc < size || size == 0) { + if ((a->alloc < size) || (size == 0) || (a->alloc == 0)) { /* ensure there are always at least MP_PREC digits extra on top */ size += (MP_PREC * 2) - (size % MP_PREC); @@ -434,11 +429,12 @@ int mp_grow (mp_int * a, int size) a->dp = tmp; /* zero excess digits */ - i = a->alloc; + XMEMSET(&a->dp[a->alloc], 0, sizeof (mp_digit) * (size - a->alloc)); a->alloc = size; - for (; i < a->alloc; i++) { - a->dp[i] = 0; - } + } + else if (a->dp == NULL) { + /* opportunistic sanity check for null a->dp with nonzero a->alloc */ + return MP_VAL; } return MP_OKAY; } @@ -1758,6 +1754,13 @@ int s_mp_add (mp_int * a, mp_int * b, mp_int * c) /* destination */ tmpc = c->dp; + /* sanity-check dp pointers. */ + if ((min_ab > 0) && + ((tmpa == NULL) || (tmpb == NULL) || (tmpc == NULL))) + { + return MP_VAL; + } + /* zero the carry */ u = 0; for (i = 0; i < min_ab; i++) { @@ -1833,6 +1836,13 @@ int s_mp_sub (mp_int * a, mp_int * b, mp_int * c) tmpb = b->dp; tmpc = c->dp; + /* sanity-check dp pointers from a and b. */ + if ((min_b > 0) && + ((tmpa == NULL) || (tmpb == NULL))) + { + return MP_VAL; + } + /* set carry to zero */ u = 0; for (i = 0; i < min_b; i++) { @@ -3290,6 +3300,10 @@ int mp_div_3 (mp_int * a, mp_int *c, mp_digit * d) q.used = a->used; q.sign = a->sign; w = 0; + + if (a->used == 0) + return MP_VAL; + for (ix = a->used - 1; ix >= 0; ix--) { w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); @@ -3332,8 +3346,6 @@ int mp_div_3 (mp_int * a, mp_int *c, mp_digit * d) /* init an mp_init for a given size */ int mp_init_size (mp_int * a, int size) { - int x; - /* pad size so there are always extra digits */ size += (MP_PREC * 2) - (size % MP_PREC); @@ -3353,9 +3365,7 @@ int mp_init_size (mp_int * a, int size) #endif /* zero the digits */ - for (x = 0; x < size; x++) { - a->dp[x] = 0; - } + XMEMSET(a->dp, 0, sizeof (mp_digit) * size); return MP_OKAY; } @@ -4681,8 +4691,11 @@ static int mp_div_d (mp_int * a, mp_digit b, mp_int * c, mp_digit * d) } } - w = 0; + + if (a->used == 0) + return MP_VAL; + for (ix = a->used - 1; ix >= 0; ix--) { w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); diff --git a/src/wolfcrypt/src/kdf.c b/src/wolfcrypt/src/kdf.c index c45c635..0e092dd 100644 --- a/src/wolfcrypt/src/kdf.c +++ b/src/wolfcrypt/src/kdf.c @@ -1,6 +1,6 @@ /* kdf.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include -#include +#include #ifndef NO_KDF @@ -814,7 +806,7 @@ int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz, return BAD_FUNC_ARG; } - ret = wc_HmacSizeByType(enmhashId); + ret = wc_HmacSizeByType((int)enmhashId); if (ret <= 0) { return BAD_FUNC_ARG; } @@ -1051,11 +1043,7 @@ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, ret = MEMORY_E; } } - if (aes != NULL) #endif - { - XMEMSET(aes, 0, sizeof(Aes)); - } /* Setup AES object. */ if (ret == 0) { @@ -1155,11 +1143,7 @@ int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 salt ret = MEMORY_E; } } - if (aes != NULL) #endif - { - XMEMSET(aes, 0, sizeof(Aes)); - } /* Setup AES object. */ if (ret == 0) { @@ -1256,11 +1240,7 @@ int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, ret = MEMORY_E; } } - if (aes != NULL) #endif - { - XMEMSET(aes, 0, sizeof(Aes)); - } /* Setup AES object. */ if (ret == 0) { @@ -1339,11 +1319,7 @@ int wc_SRTCP_KDF_label(const byte* key, word32 keySz, const byte* salt, ret = MEMORY_E; } } - if (aes != NULL) #endif - { - XMEMSET(aes, 0, sizeof(Aes)); - } /* Setup AES object. */ if (ret == 0) { diff --git a/src/wolfcrypt/src/logging.c b/src/wolfcrypt/src/logging.c index d548cd6..29b9221 100644 --- a/src/wolfcrypt/src/logging.c +++ b/src/wolfcrypt/src/logging.c @@ -1,6 +1,6 @@ /* logging.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - -#include -#include #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) /* avoid adding WANT_READ and WANT_WRITE to error queue */ #include @@ -265,7 +258,6 @@ void WOLFSSL_TIME(int count) /* the requisite linux/kernel.h is included in wc_port.h, with incompatible warnings masked out. */ #elif defined(FUSION_RTOS) #include - #include #define fprintf FCL_FPRINTF #else #include /* for default printf stuff */ @@ -904,7 +896,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, * Get the error value at the HEAD of the ERR queue or 0 if the queue * is empty. The HEAD entry is removed by this call. */ -unsigned long wc_GetErrorNodeErr(void) +int wc_GetErrorNodeErr(void) { int ret; @@ -923,7 +915,7 @@ unsigned long wc_GetErrorNodeErr(void) wc_ClearErrorNodes(); } } - return (unsigned long)ret; + return ret; } #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) @@ -1171,7 +1163,7 @@ int wc_AddErrorNode(int error, int line, char* buf, char* file) sz = WOLFSSL_MAX_ERROR_SZ - 1; } if (sz > 0) { - XMEMCPY(err->error, buf, sz); + XMEMCPY(err->error, buf, (size_t)sz); } sz = (int)XSTRLEN(file); @@ -1179,7 +1171,7 @@ int wc_AddErrorNode(int error, int line, char* buf, char* file) sz = WOLFSSL_MAX_ERROR_SZ - 1; } if (sz > 0) { - XMEMCPY(err->file, file, sz); + XMEMCPY(err->file, file, (size_t)sz); } err->value = error; @@ -1420,7 +1412,7 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, } } -unsigned long wc_GetErrorNodeErr(void) +int wc_GetErrorNodeErr(void) { int ret; @@ -1428,7 +1420,7 @@ unsigned long wc_GetErrorNodeErr(void) if (ERRQ_LOCK() != 0) { WOLFSSL_MSG("Lock debug mutex failed"); - return (unsigned long)(0 - BAD_MUTEX_E); + return (0 - BAD_MUTEX_E); } ret = pullErrorNode(NULL, NULL, NULL); @@ -1595,10 +1587,10 @@ unsigned long wc_PeekErrorNodeLineData(const char **file, int *line, return (unsigned long)(0 - NOT_COMPILED_IN); } -unsigned long wc_GetErrorNodeErr(void) +int wc_GetErrorNodeErr(void) { WOLFSSL_ENTER("wc_GetErrorNodeErr"); - return (unsigned long)(0 - NOT_COMPILED_IN); + return (0 - NOT_COMPILED_IN); } #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) diff --git a/src/wolfcrypt/src/md2.c b/src/wolfcrypt/src/md2.c index 07ad963..89cec62 100644 --- a/src/wolfcrypt/src/md2.c +++ b/src/wolfcrypt/src/md2.c @@ -1,6 +1,6 @@ /* md2.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,11 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_MD2 #include -#include #ifdef NO_INLINE #include @@ -42,6 +35,9 @@ void wc_InitMd2(wc_Md2* md2) { + if (md2 == NULL) + return; + XMEMSET(md2->X, 0, WC_MD2_X_SIZE); XMEMSET(md2->C, 0, WC_MD2_BLOCK_SIZE); XMEMSET(md2->buffer, 0, WC_MD2_BLOCK_SIZE); @@ -73,6 +69,9 @@ void wc_Md2Update(wc_Md2* md2, const byte* data, word32 len) 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 }; + if (md2 == NULL || (data == NULL && len != 0)) + return; + while (len) { word32 L = (WC_MD2_PAD_SIZE - md2->count) < len ? (WC_MD2_PAD_SIZE - md2->count) : len; @@ -117,9 +116,13 @@ void wc_Md2Update(wc_Md2* md2, const byte* data, word32 len) void wc_Md2Final(wc_Md2* md2, byte* hash) { byte padding[WC_MD2_BLOCK_SIZE]; - word32 padLen = WC_MD2_PAD_SIZE - md2->count; + word32 padLen; word32 i; + if (md2 == NULL || hash == NULL) + return; + + padLen = WC_MD2_PAD_SIZE - md2->count; for (i = 0; i < padLen; i++) padding[i] = (byte)padLen; diff --git a/src/wolfcrypt/src/md4.c b/src/wolfcrypt/src/md4.c index 592a0a3..53d206e 100644 --- a/src/wolfcrypt/src/md4.c +++ b/src/wolfcrypt/src/md4.c @@ -1,6 +1,6 @@ /* md4.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_MD4 @@ -39,6 +34,9 @@ void wc_InitMd4(wc_Md4* md4) { + if (md4 == NULL) + return; + md4->digest[0] = 0x67452301L; md4->digest[1] = 0xefcdab89L; md4->digest[2] = 0x98badcfeL; @@ -141,8 +139,12 @@ static WC_INLINE void AddLength(wc_Md4* md4, word32 len) void wc_Md4Update(wc_Md4* md4, const byte* data, word32 len) { /* do block size increments */ - byte* local = (byte*)md4->buffer; + byte* local; + + if (md4 == NULL || (data == NULL && len != 0)) + return; + local = (byte*)md4->buffer; while (len) { word32 add = min(len, WC_MD4_BLOCK_SIZE - md4->buffLen); XMEMCPY(&local[md4->buffLen], data, add); @@ -165,8 +167,12 @@ void wc_Md4Update(wc_Md4* md4, const byte* data, word32 len) void wc_Md4Final(wc_Md4* md4, byte* hash) { - byte* local = (byte*)md4->buffer; + byte* local; + + if (md4 == NULL || hash == NULL) + return; + local = (byte*)md4->buffer; AddLength(md4, md4->buffLen); /* before adding pads */ local[md4->buffLen++] = 0x80; /* add 1 */ diff --git a/src/wolfcrypt/src/md5.c b/src/wolfcrypt/src/md5.c index 557de7c..84f1117 100644 --- a/src/wolfcrypt/src/md5.c +++ b/src/wolfcrypt/src/md5.c @@ -1,6 +1,6 @@ /* md5.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include +#include #if !defined(NO_MD5) @@ -35,8 +29,6 @@ #else #include -#include -#include #include #ifdef NO_INLINE diff --git a/src/wolfcrypt/src/memory.c b/src/wolfcrypt/src/memory.c index 4fd648a..928dd7b 100644 --- a/src/wolfcrypt/src/memory.c +++ b/src/wolfcrypt/src/memory.c @@ -1,6 +1,6 @@ /* memory.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,20 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +/* inhibit "#undef current" in linuxkm_wc_port.h, included from wc_port.h, + * because needed in linuxkm_memory.c, included below. + */ +#define WOLFSSL_LINUXKM_NEED_LINUX_CURRENT -#ifdef HAVE_CONFIG_H - #include -#endif - -#ifdef WOLFSSL_LINUXKM - /* inhibit "#undef current" in linuxkm_wc_port.h, included from wc_port.h, - * because needed in linuxkm_memory.c, included below. - */ - #define WOLFSSL_NEED_LINUX_CURRENT -#endif - -#include -#include +#include /* Possible memory options: @@ -81,8 +73,6 @@ void *z_realloc(void *ptr, size_t size) #ifdef USE_WOLFSSL_MEMORY #include -#include -#include #if defined(WOLFSSL_DEBUG_MEMORY) && defined(WOLFSSL_DEBUG_MEMORY_PRINT) #include @@ -1764,7 +1754,7 @@ WOLFSSL_LOCAL int SAVE_VECTOR_REGISTERS2_fuzzer(void) { } (void)lrand48_r(&wc_svr_fuzzing_state, &result); if (result & 1) - return IO_FAILED_E; + return WC_NO_ERR_TRACE(IO_FAILED_E); else return 0; } @@ -1804,7 +1794,7 @@ WOLFSSL_LOCAL int SAVE_VECTOR_REGISTERS2_fuzzer(void) { balance_bit = !balance_bit; - return ((prn & 1) ^ balance_bit) ? IO_FAILED_E : 0; + return ((prn & 1) ^ balance_bit) ? WC_NO_ERR_TRACE(IO_FAILED_E) : 0; } #endif /* !HAVE_THREAD_LS */ diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index c37e2dc..98b83c7 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -1,6 +1,6 @@ /* misc.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -25,11 +25,15 @@ This module implements the arithmetic-shift right, left, byte swapping, XOR, masking and clearing memory logic. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include +#ifdef WOLFSSL_VIS_FOR_TESTS + #ifdef HAVE_CONFIG_H + #include + #endif + #include +#else + #include +#endif #ifndef WOLF_CRYPT_MISC_C #define WOLF_CRYPT_MISC_C @@ -189,6 +193,28 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in, out[i] = ByteReverseWord32(in[i]); } #ifdef WOLFSSL_USE_ALIGN + else if (((size_t)in & 0x3) == 0) { + byte *out_bytes = (byte *)out; + word32 scratch; + + byteCount &= ~0x3U; + + for (i = 0; i < byteCount; i += (word32)sizeof(word32)) { + scratch = ByteReverseWord32(*in++); + XMEMCPY(out_bytes + i, &scratch, sizeof(scratch)); + } + } + else if (((size_t)out & 0x3) == 0) { + byte *in_bytes = (byte *)in; + word32 scratch; + + byteCount &= ~0x3U; + + for (i = 0; i < byteCount; i += (word32)sizeof(word32)) { + XMEMCPY(&scratch, in_bytes + i, sizeof(scratch)); + *out++ = ByteReverseWord32(scratch); + } + } else { byte *in_bytes = (byte *)in; byte *out_bytes = (byte *)out; @@ -335,22 +361,68 @@ WC_MISC_STATIC WC_INLINE void ByteReverseWords64(word64* out, const word64* in, { word32 count = byteCount/(word32)sizeof(word64), i; - for (i = 0; i < count; i++) - out[i] = ByteReverseWord64(in[i]); +#ifdef WOLFSSL_USE_ALIGN + if ((((size_t)in & 0x7) == 0) && + (((size_t)out & 0x7) == 0)) +#endif + { + for (i = 0; i < count; i++) + out[i] = ByteReverseWord64(in[i]); + } +#ifdef WOLFSSL_USE_ALIGN + else if (((size_t)in & 0x7) == 0) { + byte *out_bytes = (byte *)out; + word64 scratch; + + byteCount &= ~0x7U; + + for (i = 0; i < byteCount; i += (word32)sizeof(word64)) { + scratch = ByteReverseWord64(*in++); + XMEMCPY(out_bytes + i, &scratch, sizeof(scratch)); + } + } + else if (((size_t)out & 0x7) == 0) { + byte *in_bytes = (byte *)in; + word64 scratch; + + byteCount &= ~0x7U; + + for (i = 0; i < byteCount; i += (word32)sizeof(word64)) { + XMEMCPY(&scratch, in_bytes + i, sizeof(scratch)); + *out++ = ByteReverseWord64(scratch); + } + } + else { + byte *in_bytes = (byte *)in; + byte *out_bytes = (byte *)out; + word64 scratch; + + byteCount &= ~0x7U; + for (i = 0; i < byteCount; i += (word32)sizeof(word64)) { + XMEMCPY(&scratch, in_bytes + i, sizeof(scratch)); + scratch = ByteReverseWord64(scratch); + XMEMCPY(out_bytes + i, &scratch, sizeof(scratch)); + } + } +#endif } #endif /* WORD64_AVAILABLE && !WOLFSSL_NO_WORD64_OPS */ #ifndef WOLFSSL_NO_XOR_OPS + +/* Leave no doubt that WOLFSSL_WORD_SIZE is a power of 2. */ +wc_static_assert((WOLFSSL_WORD_SIZE & (WOLFSSL_WORD_SIZE - 1)) == 0); + /* This routine performs a bitwise XOR operation of <*r> and <*a> for number of wolfssl_words, placing the result in <*r>. */ WC_MISC_STATIC WC_INLINE void XorWordsOut(wolfssl_word** r, const wolfssl_word** a, const wolfssl_word** b, word32 n) { - word32 i; + const wolfssl_word *e = *a + n; - for (i = 0; i < n; i++) + while (*a < e) *((*r)++) = *((*a)++) ^ *((*b)++); } @@ -360,48 +432,68 @@ counts, placing the result in <*buf>. */ WC_MISC_STATIC WC_INLINE void xorbufout(void* out, const void* buf, const void* mask, word32 count) { - word32 i; - byte* o; - const byte* b; - const byte* m; - - o = (byte*)out; - b = (const byte*)buf; - m = (const byte*)mask; - - - if (((wc_ptr_t)o) % WOLFSSL_WORD_SIZE == - ((wc_ptr_t)b) % WOLFSSL_WORD_SIZE && - ((wc_ptr_t)b) % WOLFSSL_WORD_SIZE == - ((wc_ptr_t)m) % WOLFSSL_WORD_SIZE) { - /* type-punning helpers */ - union { - byte* bp; - wolfssl_word* wp; - } tpo; - union { - const byte* bp; - const wolfssl_word* wp; - } tpb, tpm; - /* Alignment checks out. Possible to XOR words. */ - /* Move alignment so that it lines up with a - * WOLFSSL_WORD_SIZE boundary */ - while (((wc_ptr_t)b) % WOLFSSL_WORD_SIZE != 0 && count > 0) { - *(o++) = (byte)(*(b++) ^ *(m++)); + byte* o = (byte*)out; + const byte* b = (const byte*)buf; + const byte* m = (const byte*)mask; + + /* type-punning helpers */ + union { + byte* bp; + wolfssl_word* wp; + } tpo; + union { + const byte* bp; + const wolfssl_word* wp; + } tpb, tpm; + + if (((((wc_ptr_t)o) & (WOLFSSL_WORD_SIZE - 1)) == 0) && + ((((wc_ptr_t)b) & (WOLFSSL_WORD_SIZE - 1)) == 0) && + ((((wc_ptr_t)m) & (WOLFSSL_WORD_SIZE - 1)) == 0)) + { + /* All buffers are already aligned. Possible to XOR by words without + * fixup. + */ + + tpo.bp = o; + tpb.bp = b; + tpm.bp = m; + XorWordsOut(&tpo.wp, &tpb.wp, &tpm.wp, count >> WOLFSSL_WORD_SIZE_LOG2); + o = tpo.bp; + b = tpb.bp; + m = tpm.bp; + count &= (WOLFSSL_WORD_SIZE - 1); + } + else if ((((wc_ptr_t)o) & (WOLFSSL_WORD_SIZE - 1)) == + (((wc_ptr_t)b) & (WOLFSSL_WORD_SIZE - 1)) && + (((wc_ptr_t)b) & (WOLFSSL_WORD_SIZE - 1)) == + (((wc_ptr_t)m) & (WOLFSSL_WORD_SIZE - 1))) + { + /* Alignment can be fixed up to allow XOR by words. */ + + /* Perform bytewise xor until pointers are aligned to + * WOLFSSL_WORD_SIZE. + */ + while ((((wc_ptr_t)b & (WOLFSSL_WORD_SIZE - 1)) != 0) && (count > 0)) + { + *o++ = (byte)(*b++ ^ *m++); count--; } + tpo.bp = o; tpb.bp = b; tpm.bp = m; - XorWordsOut( &tpo.wp, &tpb.wp, &tpm.wp, count / WOLFSSL_WORD_SIZE); + XorWordsOut(&tpo.wp, &tpb.wp, &tpm.wp, count >> WOLFSSL_WORD_SIZE_LOG2); o = tpo.bp; b = tpb.bp; m = tpm.bp; - count %= WOLFSSL_WORD_SIZE; + count &= (WOLFSSL_WORD_SIZE - 1); + } + + while (count > 0) { + *o++ = (byte)(*b++ ^ *m++); + count--; } - for (i = 0; i < count; i++) - o[i] = (byte)(b[i] ^ m[i]); } /* This routine performs a bitwise XOR operation of <*r> and <*a> for number @@ -409,9 +501,9 @@ of wolfssl_words, placing the result in <*r>. */ WC_MISC_STATIC WC_INLINE void XorWords(wolfssl_word** r, const wolfssl_word** a, word32 n) { - word32 i; + const wolfssl_word *e = *a + n; - for (i = 0; i < n; i++) + while (*a < e) *((*r)++) ^= *((*a)++); } @@ -420,47 +512,82 @@ counts, placing the result in <*buf>. */ WC_MISC_STATIC WC_INLINE void xorbuf(void* buf, const void* mask, word32 count) { - word32 i; - byte* b; - const byte* m; - - b = (byte*)buf; - m = (const byte*)mask; - - if (((wc_ptr_t)b) % WOLFSSL_WORD_SIZE == - ((wc_ptr_t)m) % WOLFSSL_WORD_SIZE) { - /* type-punning helpers */ - union { - byte* bp; - wolfssl_word* wp; - } tpb; - union { - const byte* bp; - const wolfssl_word* wp; - } tpm; - /* Alignment checks out. Possible to XOR words. */ - /* Move alignment so that it lines up with a - * WOLFSSL_WORD_SIZE boundary */ - while (((wc_ptr_t)buf) % WOLFSSL_WORD_SIZE != 0 && count > 0) { + byte* b = (byte*)buf; + const byte* m = (const byte*)mask; + + /* type-punning helpers */ + union { + byte* bp; + wolfssl_word* wp; + } tpb; + union { + const byte* bp; + const wolfssl_word* wp; + } tpm; + + if ((((wc_ptr_t)buf & (WOLFSSL_WORD_SIZE - 1)) == 0) && + (((wc_ptr_t)mask & (WOLFSSL_WORD_SIZE - 1)) == 0)) + { + /* Both buffers are already aligned. Possible to XOR by words without + * fixup. + */ + + tpb.bp = b; + tpm.bp = m; + /* Work around false positives from linuxkm CONFIG_FORTIFY_SOURCE. */ + #if defined(WOLFSSL_LINUXKM) && defined(CONFIG_FORTIFY_SOURCE) + PRAGMA_GCC_DIAG_PUSH; + PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") + #endif + XorWords(&tpb.wp, &tpm.wp, count >> WOLFSSL_WORD_SIZE_LOG2); + #if defined(WOLFSSL_LINUXKM) && defined(CONFIG_FORTIFY_SOURCE) + PRAGMA_GCC_DIAG_POP; + #endif + b = tpb.bp; + m = tpm.bp; + count &= (WOLFSSL_WORD_SIZE - 1); + } + else if (((wc_ptr_t)buf & (WOLFSSL_WORD_SIZE - 1)) == + ((wc_ptr_t)mask & (WOLFSSL_WORD_SIZE - 1))) + { + /* Alignment can be fixed up to allow XOR by words. */ + + /* Perform bytewise xor until pointers are aligned to + * WOLFSSL_WORD_SIZE. + */ + while ((((wc_ptr_t)b & (WOLFSSL_WORD_SIZE - 1)) != 0) && (count > 0)) + { *(b++) ^= *(m++); count--; } + tpb.bp = b; tpm.bp = m; - XorWords( &tpb.wp, &tpm.wp, count / WOLFSSL_WORD_SIZE); + /* Work around false positives from linuxkm CONFIG_FORTIFY_SOURCE. */ + #if defined(WOLFSSL_LINUXKM) && defined(CONFIG_FORTIFY_SOURCE) + PRAGMA_GCC_DIAG_PUSH; + PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") + #endif + XorWords(&tpb.wp, &tpm.wp, count >> WOLFSSL_WORD_SIZE_LOG2); + #if defined(WOLFSSL_LINUXKM) && defined(CONFIG_FORTIFY_SOURCE) + PRAGMA_GCC_DIAG_POP; + #endif b = tpb.bp; m = tpm.bp; - count %= WOLFSSL_WORD_SIZE; + count &= (WOLFSSL_WORD_SIZE - 1); } - for (i = 0; i < count; i++) - b[i] ^= m[i]; + while (count > 0) { + *b++ ^= *m++; + count--; + } } -#endif + +#endif /* !WOLFSSL_NO_XOR_OPS */ #ifndef WOLFSSL_NO_FORCE_ZERO /* This routine fills the first len bytes of the memory area pointed by mem - with zeros. It ensures compiler optimizations doesn't skip it */ + with zeros. It ensures compiler optimization doesn't skip it */ WC_MISC_STATIC WC_INLINE void ForceZero(void* mem, word32 len) { volatile byte* z = (volatile byte*)mem; @@ -506,6 +633,125 @@ WC_MISC_STATIC WC_INLINE int ConstantCompare(const byte* a, const byte* b, } #endif +#ifndef WOLFSSL_NO_CT_OPS +/* Constant time - mask set when a > b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskGT(int a, int b) +{ + return (byte)((((word32)a - (word32)b - 1) >> 31) - 1); +} + +/* Constant time - mask set when a >= b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskGTE(int a, int b) +{ + return (byte)((((word32)a - (word32)b) >> 31) - 1); +} + +/* Constant time - mask set when a >= b. */ +WC_MISC_STATIC WC_INLINE int ctMaskIntGTE(int a, int b) +{ + return (int)((((word32)a - (word32)b) >> 31) - 1); +} + +#ifdef WORD64_AVAILABLE +/* Constant time - mask set when a >= b. */ +WC_MISC_STATIC WC_INLINE word32 ctMaskWord32GTE(word32 a, word32 b) +{ + return (word32)((((word64)a - (word64)b) >> 63) - 1); +} +#endif + +/* Constant time - mask set when a < b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskLT(int a, int b) +{ + return (byte)((((word32)b - (word32)a - 1) >> 31) - 1); +} + +/* Constant time - mask set when a <= b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskLTE(int a, int b) +{ + return (byte)((((word32)b - (word32)a) >> 31) - 1); +} + +/* Constant time - mask set when a == b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskEq(int a, int b) +{ + return (byte)((byte)(~ctMaskGT(a, b)) & (byte)(~ctMaskLT(a, b))); +} + +/* Constant time - sets 16 bit integer mask when a > b */ +WC_MISC_STATIC WC_INLINE word16 ctMask16GT(int a, int b) +{ + return (word16)((((word32)a - (word32)b - 1) >> 31) - 1); +} + +/* Constant time - sets 16 bit integer mask when a >= b */ +WC_MISC_STATIC WC_INLINE word16 ctMask16GTE(int a, int b) +{ + return (word16)((((word32)a - (word32)b) >> 31) - 1); +} + +/* Constant time - sets 16 bit integer mask when a < b. */ +WC_MISC_STATIC WC_INLINE word16 ctMask16LT(int a, int b) +{ + return (word16)((((word32)b - (word32)a - 1) >> 31) - 1); +} + +/* Constant time - sets 16 bit integer mask when a <= b. */ +WC_MISC_STATIC WC_INLINE word16 ctMask16LTE(int a, int b) +{ + return (word16)((((word32)b - (word32)a) >> 31) - 1); +} + +/* Constant time - sets 16 bit integer mask when a == b. */ +WC_MISC_STATIC WC_INLINE word16 ctMask16Eq(int a, int b) +{ + return (word16)((word16)(~ctMask16GT(a, b)) & (word16)(~ctMask16LT(a, b))); +} + +/* Constant time - mask set when a != b. */ +WC_MISC_STATIC WC_INLINE byte ctMaskNotEq(int a, int b) +{ + return (byte)((byte)ctMaskGT(a, b) | (byte)ctMaskLT(a, b)); +} + +/* Constant time - select a when mask is set and b otherwise. */ +WC_MISC_STATIC WC_INLINE byte ctMaskSel(byte m, byte a, byte b) +{ + return (byte)((b & ((byte)~(word32)m)) | (a & m)); +} + +/* Constant time - select integer a when mask is set and integer b otherwise. */ +WC_MISC_STATIC WC_INLINE int ctMaskSelInt(byte m, int a, int b) +{ + return (b & (~(signed int)(signed char)m)) | + (a & ( (signed int)(signed char)m)); +} + +/* Constant time - select word32 a when mask is set and word32 b otherwise. */ +WC_MISC_STATIC WC_INLINE word32 ctMaskSelWord32(byte m, word32 a, word32 b) +{ + return (((word32)b & (word32)(~(signed int)(signed char)m)) | + ((word32)a & (word32)( (signed int)(signed char)m))); +} + +/* Constant time - bit set when a <= b. */ +WC_MISC_STATIC WC_INLINE byte ctSetLTE(int a, int b) +{ + return (byte)(((word32)a - (word32)b - 1) >> 31); +} + +/* Constant time - conditionally copy size bytes from src to dst if mask is set + */ +WC_MISC_STATIC WC_INLINE void ctMaskCopy(byte mask, byte* dst, byte* src, + word16 size) +{ + int i; + for (i = 0; i < size; ++i) { + dst[i] ^= (dst[i] ^ src[i]) & mask; + } +} + +#endif /* !WOLFSSL_NO_CT_OPS */ #ifndef WOLFSSL_HAVE_MIN #define WOLFSSL_HAVE_MIN @@ -515,7 +761,12 @@ WC_MISC_STATIC WC_INLINE int ConstantCompare(const byte* a, const byte* b, /* returns the smaller of a and b */ WC_MISC_STATIC WC_INLINE word32 min(word32 a, word32 b) { +#if !defined(WOLFSSL_NO_CT_OPS) && defined(WORD64_AVAILABLE) + word32 gte_mask = (word32)ctMaskWord32GTE(a, b); + return (a & ~gte_mask) | (b & gte_mask); +#else /* WOLFSSL_NO_CT_OPS */ return a > b ? b : a; +#endif /* WOLFSSL_NO_CT_OPS */ } #endif /* !WOLFSSL_HAVE_MIN */ @@ -526,7 +777,12 @@ WC_MISC_STATIC WC_INLINE int ConstantCompare(const byte* a, const byte* b, #endif WC_MISC_STATIC WC_INLINE word32 max(word32 a, word32 b) { +#if !defined(WOLFSSL_NO_CT_OPS) && defined(WORD64_AVAILABLE) + word32 gte_mask = (word32)ctMaskWord32GTE(a, b); + return (a & gte_mask) | (b & ~gte_mask); +#else /* WOLFSSL_NO_CT_OPS */ return a > b ? a : b; +#endif /* WOLFSSL_NO_CT_OPS */ } #endif /* !WOLFSSL_HAVE_MAX */ @@ -631,8 +887,10 @@ WC_MISC_STATIC WC_INLINE signed char HexCharToByte(char ch) WC_MISC_STATIC WC_INLINE char ByteToHex(byte in) { - static const char kHexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + static ALIGN64 const char kHexChar[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; return (char)(kHexChar[in & 0xF]); } @@ -648,6 +906,11 @@ WC_MISC_STATIC WC_INLINE int ByteToHexStr(byte in, char* out) WC_MISC_STATIC WC_INLINE int CharIsWhiteSpace(char ch) { +#ifndef WOLFSSL_NO_CT_OPS + return (ctMaskEq(ch, ' ') | + ctMaskEq(ch, '\t') | + ctMaskEq(ch, '\n')) & 1; +#else /* WOLFSSL_NO_CT_OPS */ switch (ch) { case ' ': case '\t': @@ -656,120 +919,9 @@ WC_MISC_STATIC WC_INLINE int CharIsWhiteSpace(char ch) default: return 0; } +#endif /* WOLFSSL_NO_CT_OPS */ } -#ifndef WOLFSSL_NO_CT_OPS -/* Constant time - mask set when a > b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskGT(int a, int b) -{ - return (byte)((((word32)a - (word32)b - 1) >> 31) - 1); -} - -/* Constant time - mask set when a >= b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskGTE(int a, int b) -{ - return (byte)((((word32)a - (word32)b) >> 31) - 1); -} - -/* Constant time - mask set when a >= b. */ -WC_MISC_STATIC WC_INLINE int ctMaskIntGTE(int a, int b) -{ - return (int)((((word32)a - (word32)b) >> 31) - 1); -} - -/* Constant time - mask set when a < b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskLT(int a, int b) -{ - return (byte)((((word32)b - (word32)a - 1) >> 31) - 1); -} - -/* Constant time - mask set when a <= b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskLTE(int a, int b) -{ - return (byte)((((word32)b - (word32)a) >> 31) - 1); -} - -/* Constant time - mask set when a == b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskEq(int a, int b) -{ - return (byte)((byte)(~ctMaskGT(a, b)) & (byte)(~ctMaskLT(a, b))); -} - -/* Constant time - sets 16 bit integer mask when a > b */ -WC_MISC_STATIC WC_INLINE word16 ctMask16GT(int a, int b) -{ - return (word16)((((word32)a - (word32)b - 1) >> 31) - 1); -} - -/* Constant time - sets 16 bit integer mask when a >= b */ -WC_MISC_STATIC WC_INLINE word16 ctMask16GTE(int a, int b) -{ - return (word16)((((word32)a - (word32)b) >> 31) - 1); -} - -/* Constant time - sets 16 bit integer mask when a < b. */ -WC_MISC_STATIC WC_INLINE word16 ctMask16LT(int a, int b) -{ - return (word16)((((word32)b - (word32)a - 1) >> 31) - 1); -} - -/* Constant time - sets 16 bit integer mask when a <= b. */ -WC_MISC_STATIC WC_INLINE word16 ctMask16LTE(int a, int b) -{ - return (word16)((((word32)b - (word32)a) >> 31) - 1); -} - -/* Constant time - sets 16 bit integer mask when a == b. */ -WC_MISC_STATIC WC_INLINE word16 ctMask16Eq(int a, int b) -{ - return (word16)((word16)(~ctMask16GT(a, b)) & (word16)(~ctMask16LT(a, b))); -} - -/* Constant time - mask set when a != b. */ -WC_MISC_STATIC WC_INLINE byte ctMaskNotEq(int a, int b) -{ - return (byte)((byte)ctMaskGT(a, b) | (byte)ctMaskLT(a, b)); -} - -/* Constant time - select a when mask is set and b otherwise. */ -WC_MISC_STATIC WC_INLINE byte ctMaskSel(byte m, byte a, byte b) -{ - return (byte)((b & ((byte)~(word32)m)) | (a & m)); -} - -/* Constant time - select integer a when mask is set and integer b otherwise. */ -WC_MISC_STATIC WC_INLINE int ctMaskSelInt(byte m, int a, int b) -{ - return (b & (~(signed int)(signed char)m)) | - (a & ( (signed int)(signed char)m)); -} - -/* Constant time - select word32 a when mask is set and word32 b otherwise. */ -WC_MISC_STATIC WC_INLINE word32 ctMaskSelWord32(byte m, word32 a, word32 b) -{ - return (((word32)b & (word32)(~(signed int)(signed char)m)) | - ((word32)a & (word32)( (signed int)(signed char)m))); -} - -/* Constant time - bit set when a <= b. */ -WC_MISC_STATIC WC_INLINE byte ctSetLTE(int a, int b) -{ - return (byte)(((word32)a - (word32)b - 1) >> 31); -} - -/* Constant time - conditionally copy size bytes from src to dst if mask is set - */ -WC_MISC_STATIC WC_INLINE void ctMaskCopy(byte mask, byte* dst, byte* src, - word16 size) -{ - int i; - for (i = 0; i < size; ++i) { - dst[i] ^= (dst[i] ^ src[i]) & mask; - } -} - -#endif - #if defined(WOLFSSL_W64_WRAPPER) #if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_W64_WRAPPER_TEST) WC_MISC_STATIC WC_INLINE void w64Increment(w64wrapper *n) { diff --git a/src/wolfcrypt/src/pkcs12.c b/src/wolfcrypt/src/pkcs12.c index 07ff1ad..5f8b85a 100644 --- a/src/wolfcrypt/src/pkcs12.c +++ b/src/wolfcrypt/src/pkcs12.c @@ -1,6 +1,6 @@ /* pkcs12.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,11 +21,7 @@ /* PKCS#12 allows storage of key and certificates into containers */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(HAVE_PKCS12) && \ !defined(NO_ASN) && !defined(NO_PWDBASED) && !defined(NO_HMAC) && \ @@ -33,9 +29,7 @@ #include #include -#include #include -#include #ifdef NO_INLINE #include #else @@ -289,6 +283,7 @@ static int GetSafeContent(WC_PKCS12* pkcs12, const byte* input, if (wc_BerToDer(input, safe->dataSz, NULL, &pkcs12->safeDersz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { WOLFSSL_MSG("Not BER sequence"); + freeSafe(safe, pkcs12->heap); return ASN_PARSE_E; } @@ -1144,7 +1139,7 @@ static WARN_UNUSED_RESULT int freeDecCertList(WC_DerCertList** list, #ifdef ASN_BER_TO_DER /* append data to encrypted content cache in PKCS12 structure * return buffer on success, NULL on error */ -static byte* PKCS12_ConcatonateContent(WC_PKCS12* pkcs12,byte* mergedData, +static byte* PKCS12_ConcatenateContent(WC_PKCS12* pkcs12,byte* mergedData, word32* mergedSz, byte* in, word32 inSz) { byte* oldContent; @@ -1180,7 +1175,7 @@ static int PKCS12_CheckConstructedZero(byte* data, word32 dataSz, word32* idx) { word32 oid; int ret = 0; - int number, size; + int number, size = 0; byte tag = 0; if (GetSequence(data, idx, &size, dataSz) < 0) { @@ -1257,7 +1252,7 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, ret = MEMORY_E; } } - mergedData = PKCS12_ConcatonateContent(pkcs12, mergedData, + mergedData = PKCS12_ConcatenateContent(pkcs12, mergedData, &mergedSz, &data[*idx], (word32)encryptedContentSz); if (mergedData == NULL) { ret = MEMORY_E; @@ -1269,17 +1264,19 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, *idx += (word32)encryptedContentSz; } - *idx = saveIdx; - - *idx += SetLength(mergedSz, &data[*idx]); + if (ret == 0) { + *idx = saveIdx; - if (mergedSz > 0) { - /* Copy over concatenated octet strings into data buffer */ - XMEMCPY(&data[*idx], mergedData, mergedSz); + *idx += SetLength(mergedSz, &data[*idx]); - XFREE(mergedData, pkcs12->heap, DYNAMIC_TYPE_PKCS); + if (mergedSz > 0) { + /* Copy over concatenated octet strings into data buffer */ + XMEMCPY(&data[*idx], mergedData, mergedSz); + } } + XFREE(mergedData, pkcs12->heap, DYNAMIC_TYPE_PKCS); + return ret; } #endif @@ -1300,6 +1297,27 @@ static int PKCS12_CoalesceOctetStrings(WC_PKCS12* pkcs12, byte* data, int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, byte** pkey, word32* pkeySz, byte** cert, word32* certSz, WC_DerCertList** ca) +{ + return wc_PKCS12_parse_ex(pkcs12, psw, pkey, pkeySz, cert, certSz, ca, 0); +} + +/* return 0 on success and negative on failure. + * By side effect returns private key, cert, and optionally ca. + * Parses and decodes the parts of PKCS12 + * + * NOTE: can parse with USER RSA enabled but may return cert that is not the + * pair for the key when using RSA key pairs. + * + * pkcs12 : non-null WC_PKCS12 struct + * psw : password to use for PKCS12 decode + * pkey : Private key returned + * cert : x509 cert returned + * ca : optional ca returned + * keepKeyHeader : 0 removes PKCS8 header, other than 0 keeps PKCS8 header + */ +int wc_PKCS12_parse_ex(WC_PKCS12* pkcs12, const char* psw, + byte** pkey, word32* pkeySz, byte** cert, word32* certSz, + WC_DerCertList** ca, int keepKeyHeader) { ContentInfo* ci = NULL; WC_DerCertList* certList = NULL; @@ -1495,7 +1513,13 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, ERROR_OUT(MEMORY_E, exit_pk12par); } XMEMCPY(*pkey, data + idx, (size_t)size); - *pkeySz = (word32)ToTraditional_ex(*pkey, (word32)size, &algId); + if (keepKeyHeader) { + *pkeySz = (word32)size; + } + else { + *pkeySz = (word32)ToTraditional_ex(*pkey, + (word32)size, &algId); + } } #ifdef WOLFSSL_DEBUG_PKCS12 @@ -1534,10 +1558,19 @@ int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, XMEMCPY(k, data + idx, (size_t)size); /* overwrites input, be warned */ - if ((ret = ToTraditionalEnc(k, (word32)size, psw, pswSz, - &algId)) < 0) { - XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); - goto exit_pk12par; + if (keepKeyHeader) { + if ((ret = wc_DecryptPKCS8Key(k, (word32)size, psw, + pswSz)) < 0) { + XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); + goto exit_pk12par; + } + } + else { + if ((ret = ToTraditionalEnc(k, (word32)size, psw, + pswSz, &algId)) < 0) { + XFREE(k, pkcs12->heap, DYNAMIC_TYPE_PUBLIC_KEY); + goto exit_pk12par; + } } if (ret < size) { diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index a96f537..a8545ba 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -1,6 +1,6 @@ /* pkcs7.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,11 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_PKCS7 #include -#include -#include #include #ifndef NO_RSA #include @@ -88,8 +81,8 @@ struct PKCS7State { byte* content; byte* buffer; /* main internal read buffer */ - wc_HashAlg hashAlg; - int hashType; + wc_HashAlg hashAlg; + enum wc_HashType hashType; int cntIdfCnt; /* count of in-definite length in content info */ /* stack variables to store for when returning */ @@ -297,7 +290,9 @@ static int wc_PKCS7_AddDataToStream(wc_PKCS7* pkcs7, byte* in, word32 inSz, } /* check if internal buffer size needs to be increased */ - if (len + pkcs7->stream->length > pkcs7->stream->bufferSz) { + if ((len + pkcs7->stream->length > pkcs7->stream->bufferSz) || + (pkcs7->stream->buffer == NULL)) + { int ret = wc_PKCS7_GrowStream(pkcs7, expected); if (ret < 0) { return ret; @@ -376,15 +371,11 @@ static int wc_PKCS7_SetMaxStream(wc_PKCS7* pkcs7, byte* in, word32 defSz) return ret; } - #ifdef ASN_BER_TO_DER if (length == 0 && ret == 0) { idx = 0; - if ((ret = wc_BerToDer(pt, maxIdx, NULL, (word32*)&length)) - != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { - return ret; - } + WOLFSSL_MSG("PKCS7 found indef SEQ with peek"); } - #endif /* ASN_BER_TO_DER */ + pkcs7->stream->maxLen = (word32)length + idx; if (pkcs7->stream->maxLen == 0) { @@ -1733,8 +1724,8 @@ static int FlattenAttributes(wc_PKCS7* pkcs7, byte* output, EncodedAttrib* ea, } /* create array of FlatAttrib struct pointers to hold DER attribs */ - derArr = (FlatAttrib**) XMALLOC((unsigned long)eaSz * sizeof(FlatAttrib*), pkcs7->heap, - DYNAMIC_TYPE_TMP_BUFFER); + derArr = (FlatAttrib**) XMALLOC((unsigned long)eaSz * sizeof(FlatAttrib*), + pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (derArr == NULL) { return MEMORY_E; } @@ -2073,6 +2064,8 @@ static int wc_PKCS7_BuildSignedAttributes(wc_PKCS7* pkcs7, ESD* esd, cannedAttribsCount = sizeof(cannedAttribs)/sizeof(PKCS7Attrib); + XMEMSET(&cannedAttribs[idx], 0, sizeof(cannedAttribs[idx])); + if ((pkcs7->defaultSignedAttribs & WOLFSSL_CONTENT_TYPE_ATTRIBUTE) || pkcs7->defaultSignedAttribs == 0) { cannedAttribs[idx].oid = contentTypeOid; @@ -2642,21 +2635,32 @@ static int wc_PKCS7_EncodeContentStream(wc_PKCS7* pkcs7, ESD* esd, void* aes, /* check and handle octet boundary */ sz = contentDataRead; if ((int)idx + sz > BER_OCTET_LENGTH) { - sz = BER_OCTET_LENGTH - (int)idx; - contentDataRead -= sz; + int amtWritten = 0; - XMEMCPY(contentData + idx, buf, (word32)sz); - ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, - aes, encContentOut, contentData, BER_OCTET_LENGTH, out, - &outIdx, esd); - if (ret != 0) { - XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); - XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); - return ret; + /* loop over current buffer until it is empty */ + while (idx + (word32)sz > BER_OCTET_LENGTH) { + sz = BER_OCTET_LENGTH; + if (idx > 0) { /* account for previously stored data */ + sz = BER_OCTET_LENGTH - (int)idx; + } + contentDataRead -= sz; + + XMEMCPY(contentData + idx, buf, (word32)sz); + ret = wc_PKCS7_EncodeContentStreamHelper(pkcs7, cipherType, + aes, encContentOut, contentData, BER_OCTET_LENGTH, out, + &outIdx, esd); + if (ret != 0) { + XFREE(encContentOut, heap, DYNAMIC_TYPE_PKCS7); + XFREE(contentData, heap, DYNAMIC_TYPE_PKCS7); + return ret; + } + idx = 0; /* cleared out previously stored data */ + amtWritten += sz; + sz = contentDataRead; } /* copy over any remaining data */ - XMEMCPY(contentData, buf + sz, (word32)contentDataRead); + XMEMCPY(contentData, buf + amtWritten, (word32)contentDataRead); idx = (word32)contentDataRead; } else { @@ -2917,8 +2921,13 @@ static int PKCS7_EncodeSigned(wc_PKCS7* pkcs7, /* SignerIdentifier */ if (pkcs7->sidType == CMS_ISSUER_AND_SERIAL_NUMBER) { /* IssuerAndSerialNumber */ - esd->issuerSnSz = (word32)SetSerialNumber(pkcs7->issuerSn, pkcs7->issuerSnSz, + ret = SetSerialNumber(pkcs7->issuerSn, pkcs7->issuerSnSz, esd->issuerSn, MAX_SN_SZ, MAX_SN_SZ); + if (ret < 0) { + idx = ret; + goto out; + } + esd->issuerSnSz = (word32)ret; signerInfoSz += esd->issuerSnSz; esd->issuerNameSz = SetSequence(pkcs7->issuerSz, esd->issuerName); signerInfoSz += esd->issuerNameSz + pkcs7->issuerSz; @@ -5267,35 +5276,52 @@ static int wc_PKCS7_HandleOctetStrings(wc_PKCS7* pkcs7, byte* in, word32 inSz, /* got partial octet string data */ /* accumulate partial octet string to buffer */ if (keepContent) { + #ifdef ASN_BER_TO_DER + if (pkcs7->streamOutCb) { + ret = wc_HashUpdate(&pkcs7->stream->hashAlg, + pkcs7->stream->hashType, + msg + *idx, pkcs7->stream->expected); + if (ret != 0) + break; + pkcs7->streamOutCb(pkcs7, msg + *idx, + pkcs7->stream->expected, pkcs7->streamCtx); + } + else + #endif /* ASN_BER_TO_DER */ + { + /* store current content buffer temporarily */ + tempBuf = pkcs7->stream->content; + pkcs7->stream->content = NULL; - /* store current content buffer temporarily */ - tempBuf = pkcs7->stream->content; - pkcs7->stream->content = NULL; - - /* grow content buffer */ - contBufSz = pkcs7->stream->accumContSz; - pkcs7->stream->accumContSz += pkcs7->stream->expected; + /* grow content buffer */ + contBufSz = pkcs7->stream->accumContSz; + pkcs7->stream->accumContSz += pkcs7->stream->expected; - pkcs7->stream->content = - (byte*)XMALLOC(pkcs7->stream->accumContSz, - pkcs7->heap, DYNAMIC_TYPE_PKCS7); + pkcs7->stream->content = + (byte*)XMALLOC(pkcs7->stream->accumContSz, + pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (pkcs7->stream->content == NULL) { - WOLFSSL_MSG("failed to grow content buffer."); - XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - tempBuf = NULL; - ret = MEMORY_E; - break; - } - else { - /* accumulate content */ - if (tempBuf != NULL && contBufSz != 0) { - XMEMCPY(pkcs7->stream->content, tempBuf, contBufSz); + if (pkcs7->stream->content == NULL) { + WOLFSSL_MSG("failed to grow content buffer."); + if (tempBuf != NULL) { + XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + tempBuf = NULL; + } + ret = MEMORY_E; + break; + } + else { + /* accumulate content */ + if (tempBuf != NULL && contBufSz != 0) { + XMEMCPY(pkcs7->stream->content, tempBuf, contBufSz); + } + XMEMCPY(pkcs7->stream->content + contBufSz, msg + *idx, + pkcs7->stream->expected); + if (tempBuf != NULL) { + XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + tempBuf = NULL; + } } - XMEMCPY(pkcs7->stream->content + contBufSz, msg + *idx, - pkcs7->stream->expected); - XFREE(tempBuf, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - tempBuf = NULL; } } @@ -5574,7 +5600,7 @@ static int PKCS7_VerifySignedData(wc_PKCS7* pkcs7, const byte* hashBuf, ret = ASN_PARSE_E; } /* store hashType for later hashing */ - pkcs7->stream->hashType = (int)hashType; + pkcs7->stream->hashType = hashType; /* restore idx */ idx = localIdx; @@ -5915,6 +5941,16 @@ static int PKCS7_VerifySignedData(wc_PKCS7* pkcs7, const byte* hashBuf, wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_VERIFY_STAGE3); #ifndef NO_PKCS7_STREAM + #ifdef ASN_BER_TO_DER + /* setup hash struct for creating hash of content if needed */ + if (pkcs7->streamOutCb) { + ret = wc_HashInit_ex(&pkcs7->stream->hashAlg, + pkcs7->stream->hashType, pkcs7->heap, pkcs7->devId); + if (ret != 0) + break; + } + #endif /* ASN_BER_TO_DER */ + /* free pkcs7->stream->content buffer */ XFREE(pkcs7->stream->content, pkcs7->heap, DYNAMIC_TYPE_PKCS7); pkcs7->stream->content = NULL; @@ -6210,7 +6246,6 @@ static int PKCS7_VerifySignedData(wc_PKCS7* pkcs7, const byte* hashBuf, /* store current index to get the signerInfo index later */ certIdx2 = idx; - /* store certificate if needed */ if (length > 0 && in2Sz == 0) { /* free tmpCert if not NULL */ @@ -6577,8 +6612,31 @@ static int PKCS7_VerifySignedData(wc_PKCS7* pkcs7, const byte* hashBuf, pkcs7->contentSz = (word32)contentSz; if (ret == 0) { - ret = wc_PKCS7_SignedDataVerifySignature(pkcs7, sig, (word32)sigSz, - signedAttrib, (word32)signedAttribSz, + #if !defined(NO_PKCS7_STREAM) && defined(ASN_BER_TO_DER) + byte streamHash[WC_MAX_DIGEST_SIZE]; + + /* get final hash if having done hash updates while + * streaming out the content */ + if (pkcs7->streamOutCb) { + ret = wc_HashFinal(&pkcs7->stream->hashAlg, + pkcs7->stream->hashType, streamHash); + hashBuf = streamHash; + length = wc_HashGetDigestSize(pkcs7->stream->hashType); + if (length < 0) { + WOLFSSL_MSG("Error getting digest size"); + ret = ASN_PARSE_E; + } + else { + hashSz = (word32)length; + } + wc_HashFree(&pkcs7->stream->hashAlg, + pkcs7->stream->hashType); + if (ret != 0) + break; + } + #endif /* !NO_PKCS7_STREAM && ASN_BER_TO_DER */ + ret = wc_PKCS7_SignedDataVerifySignature(pkcs7, sig, + (word32)sigSz, signedAttrib, (word32)signedAttribSz, hashBuf, hashSz); } } @@ -8400,34 +8458,21 @@ static int wc_PKCS7_EncryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, } -/* decrypt content using encryptOID algo - * returns 0 on success */ -static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, - int keySz, byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, - word32 authTagSz, byte* in, int inSz, byte* out, int devId, void* heap) +static int wc_PKCS7_DecryptContentInit(wc_PKCS7* pkcs7, word32 encryptOID, + byte* key, word32 keySz, byte* iv, int ivSz, int devId, void* heap) { int ret; #ifndef NO_AES -#ifdef WOLFSSL_SMALL_STACK Aes *aes; -#else - Aes aes[1]; -#endif #endif #ifndef NO_DES3 - Des des; - Des3 des3; + Des *des; + Des3 *des3; #endif - if (iv == NULL || in == NULL || out == NULL) + if (iv == NULL) return BAD_FUNC_ARG; - if (pkcs7->decryptionCb != NULL) { - return pkcs7->decryptionCb(pkcs7, encryptOID, iv, ivSz, - aad, aadSz, authTag, authTagSz, in, - inSz, out, pkcs7->decryptionCtx); - } - if (key == NULL) return BAD_FUNC_ARG; @@ -8455,27 +8500,18 @@ static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, #endif (ivSz != WC_AES_BLOCK_SIZE) ) return BAD_FUNC_ARG; -#ifdef WOLFSSL_SMALL_STACK - if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, - DYNAMIC_TYPE_AES)) == NULL) + + pkcs7->decryptKey.aes = (Aes *)XMALLOC(sizeof *aes, NULL, + DYNAMIC_TYPE_AES); + aes = pkcs7->decryptKey.aes; + if (aes == NULL) return MEMORY_E; -#endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { ret = wc_AesSetKey(aes, key, (word32)keySz, iv, AES_DECRYPTION); - if (ret == 0) { - ret = wc_AesCbcDecrypt(aes, out, in, (word32)inSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async decrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); - #endif - } - wc_AesFree(aes); } -#ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); -#endif break; + #endif /* HAVE_AES_CBC */ #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 @@ -8489,31 +8525,15 @@ static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, #endif #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ defined(WOLFSSL_AES_256) - if (authTag == NULL) - return BAD_FUNC_ARG; - -#ifdef WOLFSSL_SMALL_STACK - if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, - DYNAMIC_TYPE_AES)) == NULL) + pkcs7->decryptKey.aes = (Aes *)XMALLOC(sizeof *aes, NULL, + DYNAMIC_TYPE_AES); + aes = pkcs7->decryptKey.aes; + if (aes == NULL) return MEMORY_E; -#endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { ret = wc_AesGcmSetKey(aes, key, (word32)keySz); - if (ret == 0) { - ret = wc_AesGcmDecrypt(aes, out, in, (word32)inSz, iv, - (word32)ivSz, authTag, authTagSz, - aad, aadSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async decrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); - #endif - } - wc_AesFree(aes); } -#ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); -#endif break; #endif #endif /* HAVE_AESGCM */ @@ -8529,31 +8549,15 @@ static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, #endif #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ defined(WOLFSSL_AES_256) - if (authTag == NULL) - return BAD_FUNC_ARG; - -#ifdef WOLFSSL_SMALL_STACK - if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL, - DYNAMIC_TYPE_AES)) == NULL) + pkcs7->decryptKey.aes = (Aes *)XMALLOC(sizeof *aes, NULL, + DYNAMIC_TYPE_AES); + aes = pkcs7->decryptKey.aes; + if (aes == NULL) return MEMORY_E; -#endif ret = wc_AesInit(aes, heap, devId); if (ret == 0) { ret = wc_AesCcmSetKey(aes, key, (word32)keySz); - if (ret == 0) { - ret = wc_AesCcmDecrypt(aes, out, in, (word32)inSz, iv, - (word32)ivSz, authTag, authTagSz, - aad, aadSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async decrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &aes->asyncDev, WC_ASYNC_FLAG_NONE); - #endif - } - wc_AesFree(aes); } -#ifdef WOLFSSL_SMALL_STACK - XFREE(aes, NULL, DYNAMIC_TYPE_AES); -#endif break; #endif #endif /* HAVE_AESCCM */ @@ -8563,26 +8567,27 @@ static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, if (keySz != DES_KEYLEN || ivSz != DES_BLOCK_SIZE) return BAD_FUNC_ARG; - ret = wc_Des_SetKey(&des, key, iv, DES_DECRYPTION); - if (ret == 0) - ret = wc_Des_CbcDecrypt(&des, out, in, (word32)inSz); - + pkcs7->decryptKey.des = (Des *)XMALLOC(sizeof *des, NULL, + DYNAMIC_TYPE_PKCS7); + des = pkcs7->decryptKey.des; + if (des == NULL) { + return MEMORY_E; + } + ret = wc_Des_SetKey(des, key, iv, DES_DECRYPTION); break; case DES3b: if (keySz != DES3_KEYLEN || ivSz != DES_BLOCK_SIZE) return BAD_FUNC_ARG; - ret = wc_Des3Init(&des3, heap, devId); + pkcs7->decryptKey.des3 = (Des3 *)XMALLOC(sizeof *des3, NULL, + DYNAMIC_TYPE_PKCS7); + des3 = pkcs7->decryptKey.des3; + if (des3 == NULL) { + return MEMORY_E; + } + ret = wc_Des3Init(des3, heap, devId); if (ret == 0) { - ret = wc_Des3_SetKey(&des3, key, iv, DES_DECRYPTION); - if (ret == 0) { - ret = wc_Des3_CbcDecrypt(&des3, out, in, (word32)inSz); - #ifdef WOLFSSL_ASYNC_CRYPT - /* async decrypt not available here, so block till done */ - ret = wc_AsyncWait(ret, &des3.asyncDev, WC_ASYNC_FLAG_NONE); - #endif - } - wc_Des3Free(&des3); + ret = wc_Des3_SetKey(des3, key, iv, DES_DECRYPTION); } break; @@ -8592,77 +8597,283 @@ static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, int encryptOID, byte* key, return ALGO_ID_E; }; -#if defined(NO_AES) || (!defined(HAVE_AESGCM) && !defined(HAVE_AESCCM)) - (void)authTag; - (void)authTagSz; - (void)aad; - (void)aadSz; -#endif - return ret; } -/* Generate random block, place in out, return 0 on success negative on error. - * Used for generation of IV, nonce, etc */ -static int wc_PKCS7_GenerateBlock(wc_PKCS7* pkcs7, WC_RNG* rng, byte* out, - word32 outSz) +/* Only does decryption of content using encryptOID algo and already set keys + * returns 0 on success */ +static int wc_PKCS7_DecryptContentEx(wc_PKCS7* pkcs7, word32 encryptOID, + byte* iv, int ivSz, byte* aad, word32 aadSz, byte* authTag, + word32 authTagSz, byte* in, int inSz, byte* out) { int ret; - WC_RNG* rnd = NULL; - if (out == NULL || outSz == 0) + if (in == NULL + #ifdef ASN_BER_TO_DER + && pkcs7->getContentCb == NULL + #endif + ) { return BAD_FUNC_ARG; + } - /* input RNG is optional, init local one if input rng is NULL */ - if (rng == NULL) { - rnd = (WC_RNG*)XMALLOC(sizeof(WC_RNG), pkcs7->heap, DYNAMIC_TYPE_RNG); - if (rnd == NULL) - return MEMORY_E; - - ret = wc_InitRng_ex(rnd, pkcs7->heap, pkcs7->devId); - if (ret != 0) { - XFREE(rnd, pkcs7->heap, DYNAMIC_TYPE_RNG); - return ret; - } + switch (encryptOID) { +#ifndef NO_AES + #ifdef HAVE_AES_CBC + #ifdef WOLFSSL_AES_128 + case AES128CBCb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192CBCb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256CBCb: + #endif + ret = wc_AesCbcDecrypt(pkcs7->decryptKey.aes, out, in, + (word32)inSz); + #ifdef WOLFSSL_ASYNC_CRYPT + /* async decrypt not available here, so block till done */ + ret = wc_AsyncWait(ret, &pkcs7->decryptKey.aes->asyncDev, + WC_ASYNC_FLAG_NONE); + #endif + break; + #endif /* HAVE_AES_CBC */ + #ifdef HAVE_AESGCM + #ifdef WOLFSSL_AES_128 + case AES128GCMb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192GCMb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256GCMb: + #endif + #if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \ + defined(WOLFSSL_AES_256) + if (authTag == NULL) + return BAD_FUNC_ARG; - } else { - rnd = rng; - } + ret = wc_AesGcmDecrypt(pkcs7->decryptKey.aes, out, in, + (word32)inSz, iv, (word32)ivSz, authTag, authTagSz, + aad, aadSz); + #ifdef WOLFSSL_ASYNC_CRYPT + /* async decrypt not available here, so block till done */ + ret = wc_AsyncWait(ret, &pkcs7->decryptKey.aes->asyncDev, + WC_ASYNC_FLAG_NONE); + #endif + break; + #endif + #endif /* HAVE_AESGCM */ + #ifdef HAVE_AESCCM + #ifdef WOLFSSL_AES_128 + case AES128CCMb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192CCMb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256CCMb: + #endif + ret = wc_AesCcmDecrypt(pkcs7->decryptKey.aes, out, in, + (word32)inSz, iv, (word32)ivSz, authTag, authTagSz, + aad, aadSz); + #ifdef WOLFSSL_ASYNC_CRYPT + /* async decrypt not available here, so block till done */ + ret = wc_AsyncWait(ret, &pkcs7->decryptKey.aes->asyncDev, + WC_ASYNC_FLAG_NONE); + #endif + break; + #endif /* HAVE_AESCCM */ +#endif /* !NO_AES */ +#ifndef NO_DES3 + case DESb: + ret = wc_Des_CbcDecrypt(pkcs7->decryptKey.des, out, in, + (word32)inSz); + break; - ret = wc_RNG_GenerateBlock(rnd, out, outSz); + case DES3b: + ret = wc_Des3_CbcDecrypt(pkcs7->decryptKey.des3, out, in, + (word32)inSz); + #ifdef WOLFSSL_ASYNC_CRYPT + /* async decrypt not available here, so block till done */ + ret = wc_AsyncWait(ret, + &pkcs7->decryptKey.des3->asyncDev, WC_ASYNC_FLAG_NONE); + #endif + break; +#endif /* !NO_DES3 */ + default: + WOLFSSL_MSG("Unsupported content cipher type"); + return ALGO_ID_E; + }; - if (rng == NULL) { - wc_FreeRng(rnd); - XFREE(rnd, pkcs7->heap, DYNAMIC_TYPE_RNG); - } +#if defined(NO_AES) || (!defined(HAVE_AESGCM) && !defined(HAVE_AESCCM)) + (void)authTag; + (void)authTagSz; + (void)aad; + (void)aadSz; +#endif return ret; } -/* Set default SignerIdentifier type to be used. Is either - * IssuerAndSerialNumber or SubjectKeyIdentifier. Encoding defaults to using - * IssuerAndSerialNumber unless set with this function or explicitly - * overridden via options when adding RecipientInfo type. - * - * Using the type DEGENERATE_SID skips over signer information. In degenerate - * cases there are no signers. - * - * pkcs7 - pointer to initialized PKCS7 structure - * type - either CMS_ISSUER_AND_SERIAL_NUMBER, CMS_SKID or DEGENERATE_SID - * - * return 0 on success, negative upon error */ -int wc_PKCS7_SetSignerIdentifierType(wc_PKCS7* pkcs7, int type) +/* clears up struct for algo used and free's memory */ +static void wc_PKCS7_DecryptContentFree(wc_PKCS7* pkcs7, word32 encryptOID, + void* heap) { - if (pkcs7 == NULL) - return BAD_FUNC_ARG; - - if (type != CMS_ISSUER_AND_SERIAL_NUMBER && - type != CMS_SKID && - type != DEGENERATE_SID) { - return BAD_FUNC_ARG; - } + switch (encryptOID) { +#ifndef NO_AES + #ifdef HAVE_AES_CBC + #ifdef WOLFSSL_AES_128 + case AES128CBCb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192CBCb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256CBCb: + #endif + #endif /* HAVE_AES_CBC */ + #ifdef HAVE_AESGCM + #ifdef WOLFSSL_AES_128 + case AES128GCMb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192GCMb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256GCMb: + #endif + #endif /* HAVE_AESGCM */ + #ifdef HAVE_AESCCM + #ifdef WOLFSSL_AES_128 + case AES128CCMb: + #endif + #ifdef WOLFSSL_AES_192 + case AES192CCMb: + #endif + #ifdef WOLFSSL_AES_256 + case AES256CCMb: + #endif + #endif /* HAVE_AESCCM */ + if (pkcs7->decryptKey.aes != NULL) { + wc_AesFree(pkcs7->decryptKey.aes); + XFREE(pkcs7->decryptKey.aes, heap, DYNAMIC_TYPE_AES); + pkcs7->decryptKey.aes = NULL; + } + break; +#endif /* !NO_AES */ +#ifndef NO_DES3 + case DESb: + if (pkcs7->decryptKey.des != NULL) { + XFREE(pkcs7->decryptKey.des, heap, DYNAMIC_TYPE_PKCS7); + pkcs7->decryptKey.des = NULL; + } + break; + case DES3b: + if (pkcs7->decryptKey.des3 != NULL) { + wc_Des3Free(pkcs7->decryptKey.des3); + XFREE(pkcs7->decryptKey.des3, heap, DYNAMIC_TYPE_PKCS7); + pkcs7->decryptKey.des3 = NULL; + } + break; +#endif /* !NO_DES3 */ + default: + WOLFSSL_MSG("Unsupported content cipher type"); + }; +} + + +/* decrypts the content in one shot, doing init / decrypt / free + * returns 0 on success + */ +static int wc_PKCS7_DecryptContent(wc_PKCS7* pkcs7, word32 encryptOID, + byte* key, word32 keySz, byte* iv, int ivSz, byte* aad, word32 aadSz, + byte* authTag, word32 authTagSz, byte* in, int inSz, byte* out, + int devId, void* heap) +{ + int ret; + + if (pkcs7->decryptionCb != NULL) { + return pkcs7->decryptionCb(pkcs7, (int)encryptOID, iv, ivSz, + aad, aadSz, authTag, authTagSz, in, + inSz, out, pkcs7->decryptionCtx); + } + + ret = wc_PKCS7_DecryptContentInit(pkcs7, encryptOID, key, keySz, iv, ivSz, + devId, heap); + + if (ret == 0) { + ret = wc_PKCS7_DecryptContentEx(pkcs7, encryptOID, iv, ivSz, aad, + aadSz, authTag, authTagSz, in, inSz, out); + } + + wc_PKCS7_DecryptContentFree(pkcs7, encryptOID, heap); + + return ret; +} + + +/* Generate random block, place in out, return 0 on success negative on error. + * Used for generation of IV, nonce, etc */ +static int wc_PKCS7_GenerateBlock(wc_PKCS7* pkcs7, WC_RNG* rng, byte* out, + word32 outSz) +{ + int ret; + WC_RNG* rnd = NULL; + + if (out == NULL || outSz == 0) + return BAD_FUNC_ARG; + + /* input RNG is optional, init local one if input rng is NULL */ + if (rng == NULL) { + rnd = (WC_RNG*)XMALLOC(sizeof(WC_RNG), pkcs7->heap, DYNAMIC_TYPE_RNG); + if (rnd == NULL) + return MEMORY_E; + + ret = wc_InitRng_ex(rnd, pkcs7->heap, pkcs7->devId); + if (ret != 0) { + XFREE(rnd, pkcs7->heap, DYNAMIC_TYPE_RNG); + return ret; + } + + } else { + rnd = rng; + } + + ret = wc_RNG_GenerateBlock(rnd, out, outSz); + + if (rng == NULL) { + wc_FreeRng(rnd); + XFREE(rnd, pkcs7->heap, DYNAMIC_TYPE_RNG); + } + + return ret; +} + + +/* Set default SignerIdentifier type to be used. Is either + * IssuerAndSerialNumber or SubjectKeyIdentifier. Encoding defaults to using + * IssuerAndSerialNumber unless set with this function or explicitly + * overridden via options when adding RecipientInfo type. + * + * Using the type DEGENERATE_SID skips over signer information. In degenerate + * cases there are no signers. + * + * pkcs7 - pointer to initialized PKCS7 structure + * type - either CMS_ISSUER_AND_SERIAL_NUMBER, CMS_SKID or DEGENERATE_SID + * + * return 0 on success, negative upon error */ +int wc_PKCS7_SetSignerIdentifierType(wc_PKCS7* pkcs7, int type) +{ + if (pkcs7 == NULL) + return BAD_FUNC_ARG; + + if (type != CMS_ISSUER_AND_SERIAL_NUMBER && + type != CMS_SKID && + type != DEGENERATE_SID) { + return BAD_FUNC_ARG; + } pkcs7->sidType = type; @@ -8697,14 +8908,10 @@ int wc_PKCS7_SetContentType(wc_PKCS7* pkcs7, byte* contentType, word32 sz) /* return size of padded data, padded to blockSz chunks, or negative on error */ int wc_PKCS7_GetPadSize(word32 inputSz, word32 blockSz) { - word32 padSz; - if (blockSz == 0) return BAD_FUNC_ARG; - padSz = blockSz - (inputSz % blockSz); - - return (int)padSz; + return (int)(blockSz - (inputSz % blockSz)); } @@ -8713,28 +8920,16 @@ int wc_PKCS7_GetPadSize(word32 inputSz, word32 blockSz) int wc_PKCS7_PadData(byte* in, word32 inSz, byte* out, word32 outSz, word32 blockSz) { - int ret; - word32 i, padSz; - if (in == NULL || inSz == 0 || - out == NULL || outSz == 0) + out == NULL || outSz == 0 || blockSz == 0) return BAD_FUNC_ARG; - ret = wc_PKCS7_GetPadSize(inSz, blockSz); - if (ret < 0) - return ret; - padSz = (word32)ret; - - if (outSz < (inSz + padSz)) + if (outSz < wc_PkcsPad(NULL, inSz, blockSz)) return BAD_FUNC_ARG; XMEMCPY(out, in, inSz); - for (i = 0; i < padSz; i++) { - out[inSz + i] = (byte)padSz; - } - - return (int)(inSz + padSz); + return (int)wc_PkcsPad(out, inSz, blockSz); } @@ -8870,10 +9065,9 @@ static int wc_PKCS7_GenerateKEK_PWRI(wc_PKCS7* pkcs7, byte* passwd, word32 pLen, /* RFC3211 (Section 2.3.1) key wrap algorithm (id-alg-PWRI-KEK). * * Returns output size on success, negative upon error */ -static int wc_PKCS7_PwriKek_KeyWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kekSz, - const byte* cek, word32 cekSz, - byte* out, word32 *outSz, - const byte* iv, word32 ivSz, int algID) +static int wc_PKCS7_PwriKek_KeyWrap(wc_PKCS7* pkcs7, const byte* kek, + word32 kekSz, const byte* cek, word32 cekSz, + byte* out, word32 *outSz, const byte* iv, word32 ivSz, int algID) { WC_RNG rng; int blockSz, outLen, ret; @@ -8926,8 +9120,8 @@ static int wc_PKCS7_PwriKek_KeyWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kek if (ret == 0) { /* encrypt, normal */ ret = wc_PKCS7_EncryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, - (byte*)iv, (int)ivSz, NULL, 0, NULL, 0, out, - outLen, out); + (byte*)iv, (int)ivSz, NULL, 0, NULL, 0, out, + outLen, out); } if (ret == 0) { @@ -8956,7 +9150,7 @@ static int wc_PKCS7_PwriKek_KeyWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kek static int wc_PKCS7_PwriKek_KeyUnWrap(wc_PKCS7* pkcs7, const byte* kek, word32 kekSz, const byte* in, word32 inSz, byte* out, word32 outSz, const byte* iv, - word32 ivSz, int algID) + word32 ivSz, word32 algID) { int blockSz, cekLen, ret; byte* tmpIv = NULL; @@ -8973,7 +9167,7 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(wc_PKCS7* pkcs7, const byte* kek, return MEMORY_E; /* get encryption algorithm block size */ - blockSz = wc_PKCS7_GetOIDBlockSize(algID); + blockSz = wc_PKCS7_GetOIDBlockSize((int)algID); if (blockSz <= 0) { XFREE(outTmp, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (blockSz < 0) @@ -8995,21 +9189,21 @@ static int wc_PKCS7_PwriKek_KeyUnWrap(wc_PKCS7* pkcs7, const byte* kek, tmpIv = lastBlock - blockSz; /* decrypt last block */ - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, tmpIv, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, tmpIv, blockSz, NULL, 0, NULL, 0, lastBlock, blockSz, outTmp + inSz - blockSz, pkcs7->devId, pkcs7->heap); if (ret == 0) { /* using last decrypted block as IV, decrypt [0 ... n-1] blocks */ lastBlock = outTmp + inSz - blockSz; - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, lastBlock, blockSz, NULL, 0, NULL, 0, (byte*)in, (int)inSz - blockSz, outTmp, pkcs7->devId, pkcs7->heap); } if (ret == 0) { /* decrypt using original kek and iv */ - ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, (int)kekSz, + ret = wc_PKCS7_DecryptContent(pkcs7, algID, (byte*)kek, kekSz, (byte*)iv, (int)ivSz, NULL, 0, NULL, 0, outTmp, (int)inSz, outTmp, pkcs7->devId, pkcs7->heap); } @@ -9224,7 +9418,8 @@ int wc_PKCS7_AddRecipient_PWRI(wc_PKCS7* pkcs7, byte* passwd, word32 pLen, totalSz += (kdfSaltOctetStrSz + saltSz); /* set KDF iteration count */ - kdfIterationsSz = (word32)SetMyVersion((word32)iterations, kdfIterations, 0); + kdfIterationsSz = (word32)SetMyVersion((word32)iterations, kdfIterations, + 0); totalSz += kdfIterationsSz; /* set KDF params SEQ */ @@ -9436,8 +9631,8 @@ int wc_PKCS7_AddRecipient_KEKRI(wc_PKCS7* pkcs7, int keyWrapOID, byte* kek, #endif encryptedKeySz = wc_PKCS7_KeyWrap(pkcs7->cek, pkcs7->cekSz, kek, kekSz, - encryptedKey, (word32)encryptedKeySz, keyWrapOID, - direction); + encryptedKey, (word32)encryptedKeySz, keyWrapOID, + direction); if (encryptedKeySz < 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -9817,8 +10012,8 @@ int wc_PKCS7_EncodeEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) return BAD_FUNC_ARG; } - encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, - encContentOctet, pkcs7->encodeStream); + encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, + (word32)encryptedOutSz, encContentOctet, pkcs7->encodeStream); encContentSeqSz = (int)SetSequenceEx((word32)(contentTypeSz + contentEncAlgoSz + ivOctetStringSz + blockSz + encContentOctetSz + encryptedOutSz), @@ -9847,18 +10042,19 @@ int wc_PKCS7_EncodeEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) /* resize encrypted content buffer */ if (encryptedContent != NULL) { - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - encryptedContent = (byte*)XMALLOC(streamSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); - if (encryptedContent == NULL) { - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - return MEMORY_E; - } + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encryptedContent = (byte*)XMALLOC(streamSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (encryptedContent == NULL) { + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + return MEMORY_E; + } } } #endif - envDataSeqSz = (int)SetSequenceEx((word32)totalSz, envDataSeq, pkcs7->encodeStream); + envDataSeqSz = (int)SetSequenceEx((word32)totalSz, envDataSeq, + pkcs7->encodeStream); totalSz += envDataSeqSz; #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { @@ -9867,7 +10063,8 @@ int wc_PKCS7_EncodeEnvelopedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) #endif /* outer content */ - outerContentSz = (int)SetExplicit(0, (word32)totalSz, outerContent, pkcs7->encodeStream); + outerContentSz = (int)SetExplicit(0, (word32)totalSz, outerContent, + pkcs7->encodeStream); #ifdef ASN_BER_TO_DER if (pkcs7->encodeStream) { totalSz += ASN_INDEF_END_SZ; @@ -10087,8 +10284,6 @@ static int wc_PKCS7_DecryptKtri(wc_PKCS7* pkcs7, byte* in, word32 inSz, ret = BUFFER_E; break; } - pkcs7->stream->expected = (pkcs7->stream->maxLen - - pkcs7->stream->totalRd) + pkcs7->stream->length; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_DECRYPT_KTRI_2); FALL_THROUGH; @@ -10127,7 +10322,7 @@ static int wc_PKCS7_DecryptKtri(wc_PKCS7* pkcs7, byte* in, word32 inSz, } pkcs7->stream->expected = (word32)sz + MAX_ALGO_SZ + ASN_TAG_SZ + - MAX_LENGTH_SZ; + MAX_LENGTH_SZ + 512; if (pkcs7->stream->length > 0 && pkcs7->stream->length < pkcs7->stream->expected) { return WC_PKCS7_WANT_READ_E; @@ -10248,7 +10443,8 @@ static int wc_PKCS7_DecryptKtri(wc_PKCS7* pkcs7, byte* in, word32 inSz, if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, idx)) != 0) { break; } - wc_PKCS7_StreamStoreVar(pkcs7, (word32)encryptedKeySz, sidType, version); + wc_PKCS7_StreamStoreVar(pkcs7, (word32)encryptedKeySz, sidType, + version); pkcs7->stream->expected = (word32)encryptedKeySz; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_DECRYPT_KTRI_3); @@ -10331,8 +10527,8 @@ static int wc_PKCS7_DecryptKtri(wc_PKCS7* pkcs7, byte* in, word32 inSz, if (encOID != RSAESOAEPk) { #endif keySz = wc_RsaPrivateDecryptInline(encryptedKey, - (word32)encryptedKeySz, &outKey, - privKey); + (word32)encryptedKeySz, &outKey, + privKey); #ifndef WC_NO_RSA_OAEP } else { @@ -10964,7 +11160,8 @@ static int wc_PKCS7_DecryptOri(wc_PKCS7* pkcs7, byte* in, word32 inSz, return PKCS7_RECIP_E; } - /* mark recipFound, since we only support one RecipientInfo for now */ + /* mark recipFound, since we only support one RecipientInfo for + * now */ *recipFound = 1; #ifndef NO_PKCS7_STREAM @@ -11120,7 +11317,8 @@ static int wc_PKCS7_DecryptPwri(wc_PKCS7* pkcs7, byte* in, word32 inSz, } if (length != blockSz) { - WOLFSSL_MSG("Incorrect IV length, must be of content alg block size"); + WOLFSSL_MSG("Incorrect IV length, must be of content alg block " + "size"); XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ASN_PARSE_E; } @@ -11175,7 +11373,7 @@ static int wc_PKCS7_DecryptPwri(wc_PKCS7* pkcs7, byte* in, word32 inSz, ret = wc_PKCS7_PwriKek_KeyUnWrap(pkcs7, kek, (word32)kekKeySz, pkiMsg + (*idx), (word32)length, cek, cekSz, tmpIv, (word32)blockSz, - (int)pwriEncAlgoId); + pwriEncAlgoId); if (ret < 0) { XFREE(salt, pkcs7->heap, DYNAMIC_TYPE_PKCS7); XFREE(kek, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11275,8 +11473,8 @@ static int wc_PKCS7_DecryptKekri(wc_PKCS7* pkcs7, byte* in, word32 inSz, localIdx = *idx; if ((*idx < kekIdSz) && GetASNTag(pkiMsg, &localIdx, &tag, pkiMsgSz) == 0 && tag == ASN_GENERALIZED_TIME) { - if (wc_GetDateInfo(pkiMsg + *idx, (int)pkiMsgSz, &datePtr, &dateFormat, - &dateLen) != 0) { + if (wc_GetDateInfo(pkiMsg + *idx, (int)pkiMsgSz, &datePtr, + &dateFormat, &dateLen) != 0) { return ASN_PARSE_E; } *idx += (word32)(dateLen + 1); @@ -11303,7 +11501,8 @@ static int wc_PKCS7_DecryptKekri(wc_PKCS7* pkcs7, byte* in, word32 inSz, } /* get KeyEncryptionAlgorithmIdentifier */ - if (GetAlgoId(pkiMsg, idx, &keyWrapOID, oidKeyWrapType, pkiMsgSz) < 0) + if (GetAlgoId(pkiMsg, idx, &keyWrapOID, oidKeyWrapType, pkiMsgSz) + < 0) return ASN_PARSE_E; /* get EncryptedKey */ @@ -11324,22 +11523,24 @@ static int wc_PKCS7_DecryptKekri(wc_PKCS7* pkcs7, byte* in, word32 inSz, /* decrypt CEK with KEK */ if (pkcs7->wrapCEKCb) { - keySz = pkcs7->wrapCEKCb(pkcs7, pkiMsg + *idx, (word32)length, keyId, - keyIdSz, NULL, 0, decryptedKey, - *decryptedKeySz, (int)keyWrapOID, - (int)PKCS7_KEKRI, direction); + keySz = pkcs7->wrapCEKCb(pkcs7, pkiMsg + *idx, (word32)length, + keyId, keyIdSz, NULL, 0, decryptedKey, + *decryptedKeySz, (int)keyWrapOID, + (int)PKCS7_KEKRI, direction); } else { - keySz = wc_PKCS7_KeyWrap(pkiMsg + *idx, (word32)length, pkcs7->privateKey, - pkcs7->privateKeySz, decryptedKey, *decryptedKeySz, - (int)keyWrapOID, direction); + keySz = wc_PKCS7_KeyWrap(pkiMsg + *idx, (word32)length, + pkcs7->privateKey, pkcs7->privateKeySz, + decryptedKey, *decryptedKeySz, + (int)keyWrapOID, direction); } if (keySz <= 0) return keySz; *decryptedKeySz = (word32)keySz; - /* mark recipFound, since we only support one RecipientInfo for now */ + /* mark recipFound, since we only support one RecipientInfo for + * now */ *recipFound = 1; *idx += (word32)length; @@ -11387,7 +11588,6 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, #ifndef NO_PKCS7_STREAM word32 tmpIdx = (idx) ? *idx : 0; #endif - WOLFSSL_ENTER("wc_PKCS7_DecryptKari"); if (pkcs7 == NULL || pkiMsg == NULL || idx == NULL || decryptedKey == NULL || decryptedKeySz == NULL) { @@ -11431,9 +11631,10 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, /* parse cert and key */ ret = wc_PKCS7_KariParseRecipCert(kari, (byte*)pkcs7->singleCert, - pkcs7->singleCertSz, pkcs7->privateKey, - pkcs7->privateKeySz); - if (ret != 0) { + pkcs7->singleCertSz, pkcs7->privateKey, + pkcs7->privateKeySz); + + if (ret != 0) { wc_PKCS7_KariFree(kari); #ifdef WOLFSSL_SMALL_STACK XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -11453,7 +11654,8 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, } /* try and remove optional UserKeyingMaterial */ - ret = wc_PKCS7_KariGetUserKeyingMaterial(kari, pkiMsg, pkiMsgSz, idx); + ret = wc_PKCS7_KariGetUserKeyingMaterial(kari, pkiMsg, pkiMsgSz, + idx); if (ret != 0) { wc_PKCS7_KariFree(kari); #ifdef WOLFSSL_SMALL_STACK @@ -11473,7 +11675,8 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, return ret; } - /* if user has not explicitly set keyAgreeOID, set from one in bundle */ + /* if user has not explicitly set keyAgreeOID, set from one in + * bundle */ if (pkcs7->keyAgreeOID == 0) pkcs7->keyAgreeOID = (int)keyAgreeOID; @@ -11528,6 +11731,10 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, ret = wc_ecc_export_x963(kari->senderKey, NULL, &tmpKeySz); PRIVATE_KEY_LOCK(); if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { + wc_PKCS7_KariFree(kari); + #ifdef WOLFSSL_SMALL_STACK + XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + #endif return ret; } @@ -11542,21 +11749,29 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, tmpKeyDer = (byte*)XMALLOC(tmpKeySz, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (tmpKeyDer == NULL) { + wc_PKCS7_KariFree(kari); + #ifdef WOLFSSL_SMALL_STACK + XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + #endif return MEMORY_E; } ret = wc_EccPublicKeyToDer(kari->senderKey, tmpKeyDer, tmpKeySz, 1); if (ret < 0) { + wc_PKCS7_KariFree(kari); + #ifdef WOLFSSL_SMALL_STACK + XFREE(encryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + #endif XFREE(tmpKeyDer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } tmpKeySz = (word32)ret; - keySz = pkcs7->wrapCEKCb(pkcs7, encryptedKey, (word32)encryptedKeySz, - rid, (word32)keyIdSize, tmpKeyDer, tmpKeySz, - decryptedKey, *decryptedKeySz, - (int)keyWrapOID, (int)PKCS7_KARI, direction); + keySz = pkcs7->wrapCEKCb(pkcs7, encryptedKey, + (word32)encryptedKeySz, rid, (word32)keyIdSize, tmpKeyDer, + tmpKeySz, decryptedKey, *decryptedKeySz, + (int)keyWrapOID, (int)PKCS7_KARI, direction); XFREE(tmpKeyDer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); if (keySz > 0) { @@ -11569,8 +11784,8 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, } else { /* create KEK */ - ret = wc_PKCS7_KariGenerateKEK(kari, pkcs7->rng, (int)keyWrapOID, - pkcs7->keyAgreeOID); + ret = wc_PKCS7_KariGenerateKEK(kari, pkcs7->rng, + (int)keyWrapOID, pkcs7->keyAgreeOID); if (ret != 0) { wc_PKCS7_KariFree(kari); #ifdef WOLFSSL_SMALL_STACK @@ -11580,9 +11795,9 @@ static int wc_PKCS7_DecryptKari(wc_PKCS7* pkcs7, byte* in, word32 inSz, } /* decrypt CEK with KEK */ - keySz = wc_PKCS7_KeyWrap(encryptedKey, (word32)encryptedKeySz, kari->kek, - kari->kekSz, decryptedKey, *decryptedKeySz, - (int)keyWrapOID, direction); + keySz = wc_PKCS7_KeyWrap(encryptedKey, (word32)encryptedKeySz, + kari->kek, kari->kekSz, decryptedKey, *decryptedKeySz, + (int)keyWrapOID, direction); } if (keySz <= 0) { wc_PKCS7_KariFree(kari); @@ -11710,7 +11925,7 @@ static int wc_PKCS7_DecryptRecipientInfos(wc_PKCS7* pkcs7, byte* in, /* when looking for next recipient, use first sequence and version to * indicate there is another, if not, move on */ - while(*recipFound == 0) { + while (*recipFound == 0) { /* remove RecipientInfo, if we don't have a SEQUENCE, back up idx to * last good saved one */ @@ -11902,7 +12117,6 @@ static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, switch (pkcs7->state) { case WC_PKCS7_INFOSET_START: - case WC_PKCS7_INFOSET_BER: case WC_PKCS7_INFOSET_STAGE1: case WC_PKCS7_INFOSET_STAGE2: case WC_PKCS7_INFOSET_END: @@ -11934,41 +12148,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, if (ret == 0 && length == 0 && pkiMsg[(*idx)-1] == 0x80) { #ifdef ASN_BER_TO_DER - word32 len; - - wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_INFOSET_BER); - FALL_THROUGH; - - /* full buffer is needed for conversion */ - case WC_PKCS7_INFOSET_BER: - #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, - pkcs7->stream->maxLen - pkcs7->stream->length, - &pkiMsg, idx)) != 0) { - return ret; - } - pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: - inSz; - #endif - - len = 0; - - ret = wc_BerToDer(pkiMsg, pkiMsgSz, NULL, &len); - if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) - return ret; - pkcs7->der = (byte*)XMALLOC(len, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (pkcs7->der == NULL) - return MEMORY_E; - ret = wc_BerToDer(pkiMsg, pkiMsgSz, pkcs7->der, &len); - if (ret < 0) - return ret; - - pkiMsg = in = pkcs7->der; - pkiMsgSz = pkcs7->derSz = inSz = len; - *idx = 0; - - if (GetSequence(pkiMsg, idx, &length, pkiMsgSz) < 0) - return ASN_PARSE_E; + pkcs7->indefDepth++; #else return BER_INDEF_E; #endif @@ -11997,7 +12177,8 @@ static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; if (ret == 0) { - if (type == ENVELOPED_DATA && contentType != ENVELOPED_DATA) { + if (type == ENVELOPED_DATA && contentType != + ENVELOPED_DATA) { WOLFSSL_MSG("PKCS#7 input not of type EnvelopedData"); ret = PKCS7_OID_E; } else if (type == AUTH_ENVELOPED_DATA && @@ -12087,7 +12268,8 @@ static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, } else { /* AuthEnvelopedData version MUST be 0 */ if (version != 0) { - WOLFSSL_MSG("PKCS#7 AuthEnvelopedData needs to be of version 0"); + WOLFSSL_MSG( + "PKCS#7 AuthEnvelopedData needs to be of version 0"); ret = ASN_VERSION_E; } } @@ -12101,6 +12283,7 @@ static int wc_PKCS7_ParseToRecipientInfoSet(wc_PKCS7* pkcs7, byte* in, break; #ifndef NO_PKCS7_STREAM + pkcs7->stream->expected = (word32)length; if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, idx)) != 0) { break; } @@ -12137,6 +12320,7 @@ WOLFSSL_API int wc_PKCS7_SetKey(wc_PKCS7* pkcs7, byte* key, word32 keySz) } +#if 0 /* append data to encrypted content cache in PKCS7 structure * return 0 on success, negative on error */ static int PKCS7_CacheEncryptedContent(wc_PKCS7* pkcs7, byte* in, word32 inSz) @@ -12170,6 +12354,7 @@ static int PKCS7_CacheEncryptedContent(wc_PKCS7* pkcs7, byte* in, word32 inSz) return 0; } +#endif /* unwrap and decrypt PKCS#7 envelopedData object, return decoded size */ @@ -12198,15 +12383,22 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, byte padLen; byte* encryptedContent = NULL; int explicitOctet = 0; - word32 localIdx; + word32 localIdx = 0; byte tag = 0; if (pkcs7 == NULL) return BAD_FUNC_ARG; - if (pkiMsg == NULL || pkiMsgSz == 0 || - output == NULL || outputSz == 0) + if (pkiMsg == NULL || pkiMsgSz == 0) + return BAD_FUNC_ARG; + + if ((output == NULL || outputSz == 0) + #ifdef ASN_BER_TO_DER + && pkcs7->streamOutCb == NULL + #endif + ) { return BAD_FUNC_ARG; + } #ifndef NO_PKCS7_STREAM (void)tmpIv; /* help out static analysis */ @@ -12220,7 +12412,6 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, switch (pkcs7->state) { case WC_PKCS7_START: case WC_PKCS7_INFOSET_START: - case WC_PKCS7_INFOSET_BER: case WC_PKCS7_INFOSET_STAGE1: case WC_PKCS7_INFOSET_STAGE2: case WC_PKCS7_INFOSET_END: @@ -12230,17 +12421,6 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, break; } - #ifdef ASN_BER_TO_DER - /* check if content was BER and has been converted to DER */ - if (pkcs7->derSz > 0) { - pkiMsg = in = pkcs7->der; - inSz = pkcs7->derSz; - #ifdef NO_PKCS7_STREAM - pkiMsgSz = pkcs7->derSz; - #endif - } - #endif - decryptedKey = (byte*)XMALLOC(MAX_ENCRYPTED_KEY_SZ, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (decryptedKey == NULL) @@ -12278,7 +12458,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, decryptedKey, &decryptedKeySz, &recipFound); if (ret == 0 && recipFound == 0) { - WOLFSSL_MSG("No recipient found in envelopedData that matches input"); + WOLFSSL_MSG( + "No recipient found in envelopedData that matches input"); ret = PKCS7_RECIP_E; } @@ -12287,6 +12468,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, #ifndef NO_PKCS7_STREAM tmpIdx = idx; pkcs7->stream->aadSz = decryptedKeySz; + pkcs7->stream->expected = MAX_LENGTH_SZ + MAX_VERSION_SZ + + ASN_TAG_SZ + MAX_LENGTH_SZ; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_ENV_3); FALL_THROUGH; @@ -12294,10 +12477,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, case WC_PKCS7_ENV_3: #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, MAX_LENGTH_SZ + - MAX_VERSION_SZ + ASN_TAG_SZ + - MAX_LENGTH_SZ, &pkiMsg, &idx)) - != 0) { + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { return ret; } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; @@ -12311,6 +12492,40 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; } + #ifndef NO_PKCS7_STREAM + if (length == 0) { + /* if indefinite length, assume worst case size + * - Content Type OID + tag/length + * - Algorithm ID structure (OID + parameters) + * - Version + */ + pkcs7->stream->expected = MAX_SEQ_SZ + /* outer sequence */ + MAX_OID_SZ + /* content type OID */ + MAX_ALGO_SZ + /* algo identifier */ + MAX_VERSION_SZ +/* version */ + ASN_TAG_SZ + /* tag */ + MAX_LENGTH_SZ; /* length */ + } + else { + /* revize expected size if known */ + pkcs7->stream->expected = (word32)length + ASN_TAG_SZ; + } + + /* Did we get enough for the expected length? */ + if (pkcs7->stream->expected > pkiMsgSz) { + localIdx = idx; + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { + return ret; + } + pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: + inSz; + if (pkcs7->stream->length > 0) { + idx = localIdx; /* account for byte used with seq read */ + } + } + #endif + if (ret == 0 && wc_GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) { ret = ASN_PARSE_E; @@ -12350,7 +12565,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, } if (ret == 0 && length != expBlockSz) { - WOLFSSL_MSG("Incorrect IV length, must be of content alg block size"); + WOLFSSL_MSG( + "Incorrect IV length, must be of content alg block size"); ret = ASN_PARSE_E; } @@ -12362,8 +12578,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, } wc_PKCS7_StreamStoreVar(pkcs7, encOID, expBlockSz, length); pkcs7->stream->contentSz = (word32)blockKeySz; - pkcs7->stream->expected = (word32)length + MAX_LENGTH_SZ + MAX_LENGTH_SZ + - ASN_TAG_SZ + ASN_TAG_SZ; + pkcs7->stream->expected = (word32)length + MAX_LENGTH_SZ + + MAX_LENGTH_SZ + ASN_TAG_SZ + ASN_TAG_SZ; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_ENV_4); FALL_THROUGH; @@ -12405,8 +12621,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, } idx++; - if (ret == 0 && GetLength(pkiMsg, &idx, &encryptedContentTotalSz, - pkiMsgSz) <= 0) { + if (ret == 0 && GetLength_ex(pkiMsg, &idx, &encryptedContentTotalSz, + pkiMsgSz, 0) < 0) { ret = ASN_PARSE_E; } @@ -12418,8 +12634,24 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, break; } pkcs7->stream->expected = (word32)encryptedContentTotalSz; + if (explicitOctet) { + pkcs7->stream->expected = MAX_OCTET_STR_SZ; + } wc_PKCS7_StreamGetVar(pkcs7, &encOID, &expBlockSz, 0); wc_PKCS7_StreamStoreVar(pkcs7, encOID, expBlockSz, explicitOctet); + + if (explicitOctet) { + /* initialize decryption state in preparation */ + if (pkcs7->decryptionCb == NULL) { + ret = wc_PKCS7_DecryptContentInit(pkcs7, encOID, + pkcs7->stream->aad, pkcs7->stream->aadSz, + pkcs7->stream->tmpIv, expBlockSz, + pkcs7->devId, pkcs7->heap); + if (ret != 0) + break; + } + } + #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_ENV_5); FALL_THROUGH; @@ -12436,6 +12668,8 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, tmpIv = pkcs7->stream->tmpIv; encryptedContentTotalSz = (int)pkcs7->stream->expected; + pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; + /* restore decrypted key */ decryptedKey = pkcs7->stream->aad; decryptedKeySz = pkcs7->stream->aadSz; @@ -12447,11 +12681,27 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, if (explicitOctet) { /* encrypted content may be fragmented into multiple * consecutive OCTET STRINGs, if so loop through - * collecting and caching encrypted content bytes */ - localIdx = idx; - while (idx < (localIdx + (word32)encryptedContentTotalSz)) { + * decrypting and outputting or caching contents until the indef + * ending tag is found */ - if (GetASNTag(pkiMsg, &idx, &tag, pkiMsgSz) < 0) { + while (1) { + encryptedContentSz = 0; + if (pkiMsgSz <= localIdx + MAX_OCTET_STR_SZ) { + #ifndef NO_PKCS7_STREAM + /* ran out of data to parse */ + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { + break; + } + pkiMsgSz = (pkcs7->stream->length > 0) ? + pkcs7->stream->length : inSz; + #else + ret = BUFFER_E; + #endif + } + + localIdx = idx; + if (GetASNTag(pkiMsg, &localIdx, &tag, pkiMsgSz) < 0) { ret = ASN_PARSE_E; } @@ -12459,61 +12709,175 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; } - if (ret == 0 && GetLength(pkiMsg, &idx, - &encryptedContentSz, pkiMsgSz) <= 0) { + if (ret == 0 && GetLength_ex(pkiMsg, &localIdx, + &encryptedContentSz, pkiMsgSz, 0) <= 0) { ret = ASN_PARSE_E; } + #ifndef NO_PKCS7_STREAM + if (ret == 0) { + /* always try to get 2 extra bytes to catch indef ending */ + pkcs7->stream->expected = (word32)encryptedContentSz + + (localIdx - idx) + ASN_INDEF_END_SZ; + } + #endif + + if (ret == 0 && + pkcs7->cachedEncryptedContentSz < + (word32)encryptedContentSz) { + if (pkcs7->cachedEncryptedContent != NULL) { + XFREE(pkcs7->cachedEncryptedContent, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + } + pkcs7->cachedEncryptedContent = (byte*)XMALLOC( + (word32)encryptedContentSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (pkcs7->cachedEncryptedContent == NULL) { + ret = MEMORY_E; + } + } + pkcs7->cachedEncryptedContentSz = + (word32)encryptedContentSz; + + /* sanity check that the buffer has all of the data */ + if (ret == 0 && (localIdx + (word32)encryptedContentSz) > + pkiMsgSz) { + #ifndef NO_PKCS7_STREAM + word32 ofsetIdx = localIdx - idx; + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &localIdx)) + != 0) { + return ret; + } + localIdx += ofsetIdx; + pkiMsgSz = (pkcs7->stream->length > 0)? + pkcs7->stream->length: inSz; + #else + ret = BUFFER_E; + #endif + } + + /* Use callback for decryption still, if set */ + if (ret == 0 && pkcs7->decryptionCb != NULL) { + ret = pkcs7->decryptionCb(pkcs7, (int)encOID, tmpIv, + expBlockSz, NULL, 0, NULL, 0, &pkiMsg[localIdx], + encryptedContentSz, pkcs7->cachedEncryptedContent, + pkcs7->decryptionCtx); + } if (ret == 0) { - ret = PKCS7_CacheEncryptedContent(pkcs7, &pkiMsg[idx], - (word32)encryptedContentSz); + ret = wc_PKCS7_DecryptContentEx(pkcs7, encOID, + tmpIv, expBlockSz, NULL, 0, NULL, 0, + &pkiMsg[localIdx], encryptedContentSz, + pkcs7->cachedEncryptedContent); } + #ifndef NO_PKCS7_STREAM if (ret != 0) { + if (ret == WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { + wc_PKCS7_StreamEndCase(pkcs7, &localIdx, &idx); + } break; } + #endif /* advance idx past encrypted content */ - idx += (word32)encryptedContentSz; + localIdx += (word32)encryptedContentSz; + + if (localIdx + ASN_INDEF_END_SZ <= pkiMsgSz) { + if (pkiMsg[localIdx] == ASN_EOC && + pkiMsg[localIdx+1] == ASN_EOC) { + /* found the end of encrypted content */ + localIdx += ASN_INDEF_END_SZ; + break; + } + } + #ifndef NO_PKCS7_STREAM + pkcs7->stream->expected = MAX_OCTET_STR_SZ; + if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &localIdx, + &localIdx)) != 0) { + break; + } + #endif + + /* save last decrypted string to handle padding (this output + * flush happens outside of the while loop in the case that + * the indef end was found) */ + if (ret == 0) { + #ifdef ASN_BER_TO_DER + if (pkcs7->streamOutCb) { + ret = pkcs7->streamOutCb(pkcs7, + pkcs7->cachedEncryptedContent, + (word32)encryptedContentSz, pkcs7->streamCtx); + } + #endif /* ASN_BER_TO_DER */ + } + + idx = localIdx; } if (ret != 0) { + if (ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { + /* free up in an error case if not looking for more + * data */ + wc_PKCS7_DecryptContentFree(pkcs7, encOID, + pkcs7->heap); + } break; } - + wc_PKCS7_DecryptContentFree(pkcs7, encOID, pkcs7->heap); } else { - /* cache encrypted content, no OCTET STRING */ - ret = PKCS7_CacheEncryptedContent(pkcs7, &pkiMsg[idx], - (word32)encryptedContentTotalSz); + pkcs7->cachedEncryptedContentSz = + (word32)encryptedContentTotalSz; + pkcs7->cachedEncryptedContent = (byte*)XMALLOC( + pkcs7->cachedEncryptedContentSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + + /* decrypt encryptedContent */ + ret = wc_PKCS7_DecryptContent(pkcs7, encOID, decryptedKey, + (word32)blockKeySz, tmpIv, expBlockSz, NULL, 0, NULL, 0, + &pkiMsg[idx], encryptedContentTotalSz, + pkcs7->cachedEncryptedContent, + pkcs7->devId, pkcs7->heap); if (ret != 0) { break; } + idx += (word32)encryptedContentTotalSz; } /* use cached content */ encryptedContent = pkcs7->cachedEncryptedContent; encryptedContentSz = (int)pkcs7->cachedEncryptedContentSz; - - /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, decryptedKey, - blockKeySz, tmpIv, expBlockSz, NULL, 0, NULL, 0, - encryptedContent, encryptedContentSz, encryptedContent, - pkcs7->devId, pkcs7->heap); - if (ret != 0) { - break; - } - padLen = encryptedContent[encryptedContentSz-1]; /* copy plaintext to output */ - if (padLen > encryptedContentSz || - (word32)(encryptedContentSz - padLen) > outputSz) { + if (padLen > encryptedContentSz) { ret = BUFFER_E; break; } - XMEMCPY(output, encryptedContent, + + #ifdef ASN_BER_TO_DER + if (pkcs7->streamOutCb) { + ret = pkcs7->streamOutCb(pkcs7, encryptedContent, + (word32)encryptedContentSz - padLen, + pkcs7->streamCtx); + if (ret != 0) { + WOLFSSL_MSG("Stream out callback returned failure"); + ret = BUFFER_E; + break; + } + } + else + #endif /* ASN_BER_TO_DER */ + { + if (output == NULL || (word32)(encryptedContentSz - padLen) > + outputSz) { + ret = BUFFER_E; + break; + } + XMEMCPY(output, encryptedContent, (word32)encryptedContentSz - padLen); + } /* free memory, zero out keys */ ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); @@ -12887,17 +13251,20 @@ int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, (int)pkcs7->unauthAttribsSz); unauthAttribsCount = pkcs7->unauthAttribsSz; - flatUnauthAttribs = (byte*)XMALLOC(unauthAttribsSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); - if (flatUnauthAttribs == NULL) { - wc_PKCS7_FreeEncodedRecipientSet(pkcs7); - XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - return MEMORY_E; + if (unauthAttribsSz > 0) { + flatUnauthAttribs = (byte*)XMALLOC(unauthAttribsSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (flatUnauthAttribs == NULL) { + wc_PKCS7_FreeEncodedRecipientSet(pkcs7); + XFREE(aadBuffer, pkcs7->heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(flatAuthAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + return MEMORY_E; + } + + FlattenAttributes(pkcs7, flatUnauthAttribs, unauthAttribs, + (int)unauthAttribsCount); } - FlattenAttributes(pkcs7, flatUnauthAttribs, unauthAttribs, - (int)unauthAttribsCount); unauthAttribsSetSz = SetImplicit(ASN_SET, 2, unauthAttribsSz, unauthAttribSet, 0); } @@ -12997,8 +13364,8 @@ int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, return BAD_FUNC_ARG; } - encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, (word32)encryptedOutSz, - encContentOctet, 0); + encContentOctetSz = (int)SetImplicit(ASN_OCTET_STRING, 0, + (word32)encryptedOutSz, encContentOctet, 0); encContentSeqSz = (int)SetSequence((word32)contentTypeSz + (word32)contentEncAlgoSz + (word32)nonceOctetStringSz + nonceSz + macIntSz + @@ -13137,19 +13504,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, int expBlockSz = 0, blockKeySz = 0; byte authTag[WC_AES_BLOCK_SIZE]; byte nonce[GCM_NONCE_MID_SZ]; /* GCM nonce is larger than CCM */ - int nonceSz = 0, authTagSz = 0, macSz = 0; - -#ifdef WOLFSSL_SMALL_STACK + int nonceSz = 0, macSz = 0; + word32 authTagSz = 0; byte* decryptedKey = NULL; -#else - byte decryptedKey[MAX_ENCRYPTED_KEY_SZ]; -#endif int encryptedContentSz = 0; int encryptedAllocSz = 0; byte* encryptedContent = NULL; int explicitOctet = 0; - byte authAttribSetByte = 0; byte* encodedAttribs = NULL; word32 encodedAttribIdx = 0, encodedAttribSz = 0; byte* authAttrib = NULL; @@ -13195,9 +13557,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, break; } #endif - #ifdef WOLFSSL_SMALL_STACK decryptedKey = (byte*)XMALLOC(MAX_ENCRYPTED_KEY_SZ, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); + DYNAMIC_TYPE_PKCS7); if (decryptedKey == NULL) { ret = MEMORY_E; break; @@ -13207,7 +13568,6 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, } #ifndef NO_PKCS7_STREAM pkcs7->stream->key = decryptedKey; - #endif #endif XMEMSET(decryptedKey, 0, MAX_ENCRYPTED_KEY_SZ); FALL_THROUGH; @@ -13221,10 +13581,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, case WC_PKCS7_DECRYPT_ORI: decryptedKeySz = MAX_ENCRYPTED_KEY_SZ; - #ifdef WOLFSSL_SMALL_STACK - #ifndef NO_PKCS7_STREAM + #ifndef NO_PKCS7_STREAM decryptedKey = pkcs7->stream->key; - #endif #endif ret = wc_PKCS7_DecryptRecipientInfos(pkcs7, in, inSz, &idx, @@ -13235,32 +13593,48 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, } if (recipFound == 0) { - WOLFSSL_MSG("No recipient found in envelopedData that matches input"); + WOLFSSL_MSG( + "No recipient found in envelopedData that matches input"); ret = PKCS7_RECIP_E; break; } #ifndef NO_PKCS7_STREAM tmpIdx = idx; + pkcs7->stream->expected = MAX_SEQ_SZ; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_AUTHENV_3); FALL_THROUGH; case WC_PKCS7_AUTHENV_3: #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, MAX_SEQ_SZ + - MAX_ALGO_SZ + MAX_ALGO_SZ + ASN_TAG_SZ, - &pkiMsg, &idx)) != 0) { + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { break; } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; #endif /* remove EncryptedContentInfo */ - if (ret == 0 && GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) { + if (ret == 0 && GetSequence_ex(pkiMsg, &idx, &length, pkiMsgSz, 0) + < 0) { ret = ASN_PARSE_E; } + #ifndef NO_PKCS7_STREAM + /* check that the expected size was accurate */ + if (ret == 0) { + if (length > (int)pkcs7->stream->expected && length > + (int)pkiMsgSz) { + pkcs7->stream->expected = (word32)length + 1; + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { + break; + } + } + } + #endif + if (ret == 0 && wc_GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) { ret = ASN_PARSE_E; @@ -13370,8 +13744,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, ret = ASN_PARSE_E; } - if (ret == 0 && GetLength(pkiMsg, &idx, &encryptedContentSz, - pkiMsgSz) <= 0) { + if (ret == 0 && GetLength_ex(pkiMsg, &idx, &encryptedContentSz, + pkiMsgSz, 0) <= 0) { ret = ASN_PARSE_E; } @@ -13411,7 +13785,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, } } - pkcs7->stream->expected = (word32)encryptedContentSz; + pkcs7->stream->expected = (word32)encryptedContentSz + + MAX_LENGTH_SZ + ASN_TAG_SZ + ASN_TAG_SZ; wc_PKCS7_StreamStoreVar(pkcs7, encOID, blockKeySz, encryptedContentSz); #endif @@ -13421,21 +13796,20 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, case WC_PKCS7_AUTHENV_5: #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, MAX_LENGTH_SZ + - ASN_TAG_SZ + ASN_TAG_SZ + pkcs7->stream->expected, - &pkiMsg, &idx)) != 0) { + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { break; } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; - encryptedContentSz = (int)pkcs7->stream->expected; + wc_PKCS7_StreamGetVar(pkcs7, &encOID, &blockKeySz, + &encryptedContentSz); #else pkiMsgSz = inSz; #endif if (expBlockSz == 0) { #ifndef NO_PKCS7_STREAM - wc_PKCS7_StreamGetVar(pkcs7, &encOID, NULL, NULL); #endif if (encOID == 0) expBlockSz = 1; @@ -13468,7 +13842,7 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, idx += (word32)encryptedContentSz; } #ifndef NO_PKCS7_STREAM - pkcs7->stream->bufferPt = encryptedContent; + pkcs7->stream->bufferPt = encryptedContent; #endif /* may have IMPLICIT [1] authenticatedAttributes */ @@ -13476,11 +13850,11 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, if (ret == 0 && GetASNTag(pkiMsg, &localIdx, &tag, pkiMsgSz) == 0 && tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)) { encodedAttribIdx = idx; - encodedAttribs = pkiMsg + idx; idx++; - if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) <= 0) + if (GetLength_ex(pkiMsg, &idx, &length, pkiMsgSz, 0) <= 0) { ret = ASN_PARSE_E; + } #ifndef NO_PKCS7_STREAM pkcs7->stream->expected = (word32)length; #endif @@ -13489,19 +13863,19 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, if (ret != 0) break; - #ifndef NO_PKCS7_STREAM if (encodedAttribSz > 0) { - pkcs7->stream->aadSz = encodedAttribSz; - pkcs7->stream->aad = (byte*)XMALLOC(encodedAttribSz, + encodedAttribs = (byte*)XMALLOC(encodedAttribSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - if (pkcs7->stream->aad == NULL) { + if (encodedAttribs == NULL) { ret = MEMORY_E; break; } - else { - XMEMCPY(pkcs7->stream->aad, encodedAttribs, - (idx - encodedAttribIdx)); - } + } + + #ifndef NO_PKCS7_STREAM + if (encodedAttribSz > 0) { + pkcs7->stream->aadSz = encodedAttribSz; + pkcs7->stream->aad = encodedAttribs; } if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { @@ -13515,7 +13889,9 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; } + pkcs7->stream->expected = MAX_LENGTH_SZ + ASN_TAG_SZ; #endif + wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_AUTHENV_ATRBEND); goto authenv_atrbend; /* jump over attribute cases */ } FALL_THROUGH; @@ -13535,7 +13911,24 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, authAttrib = &pkiMsg[idx]; authAttribSz = length; - if (ret == 0 && wc_PKCS7_ParseAttribs(pkcs7, authAttrib, authAttribSz) < 0) { + { + word32 ofst; + + /* From RFC5083, "For the purpose of constructing the + * AAD, the IMPLICIT [1] tag in the authAttrs field is + * not used for the DER encoding: rather a universal SET + * OF tag is used. */ + ofst = SetSet((word32)length, encodedAttribs); + + XMEMCPY(encodedAttribs + ofst, authAttrib, + (word32)authAttribSz); + } + + /* ignoring the size returned, we know it is + * idx - encodedAttribIdx from parsing what's given */ + + if (ret == 0 && wc_PKCS7_ParseAttribs(pkcs7, authAttrib, + authAttribSz) < 0) { WOLFSSL_MSG("Error parsing authenticated attributes"); ret = ASN_PARSE_E; break; @@ -13544,14 +13937,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, idx += (word32)length; #ifndef NO_PKCS7_STREAM - if (encodedAttribSz > 0) { - XMEMCPY(pkcs7->stream->aad + (encodedAttribSz - (word32)length), - authAttrib, (word32)authAttribSz); + if (pkcs7->stream->aadSz > 0) { + XMEMCPY(pkcs7->stream->aad + (pkcs7->stream->aadSz - + (word32)length), authAttrib, (word32)authAttribSz); } if ((ret = wc_PKCS7_StreamEndCase(pkcs7, &tmpIdx, &idx)) != 0) { break; } - + pkcs7->stream->expected = MAX_LENGTH_SZ + ASN_TAG_SZ; #endif wc_PKCS7_ChangeState(pkcs7, WC_PKCS7_AUTHENV_ATRBEND); FALL_THROUGH; @@ -13559,8 +13952,8 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, case WC_PKCS7_AUTHENV_ATRBEND: authenv_atrbend: #ifndef NO_PKCS7_STREAM - if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, MAX_LENGTH_SZ + - ASN_TAG_SZ, &pkiMsg, &idx)) != 0) { + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { return ret; } pkiMsgSz = (pkcs7->stream->length > 0)? pkcs7->stream->length: inSz; @@ -13572,34 +13965,44 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, #endif - /* get authTag OCTET STRING */ - if (ret == 0 && GetASNTag(pkiMsg, &idx, &tag, pkiMsgSz) < 0) { + localIdx = idx; + + /* Get authTag OCTET STRING */ + if (ret == 0 && pkiMsg[localIdx] != ASN_OCTET_STRING) { ret = ASN_PARSE_E; } - if (ret == 0 && tag != ASN_OCTET_STRING) { + localIdx++; /* move past ASN_OCTET_STRING */ + + if (ret == 0 && GetLength_ex(pkiMsg, &localIdx, &length, + pkiMsgSz, 0) < 0) { ret = ASN_PARSE_E; } + authTagSz = (word32)length; - if (ret == 0 && GetLength(pkiMsg, &idx, &authTagSz, pkiMsgSz) < 0) { - ret = ASN_PARSE_E; + #ifndef NO_PKCS7_STREAM + /* there might not be enough data for the auth tag too */ + if (ret == 0) { + if ((authTagSz + (localIdx - idx)) > pkcs7->stream->expected && + (authTagSz + (localIdx - idx)) > pkiMsgSz) { + pkcs7->stream->expected = authTagSz + + (localIdx - idx); + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, + pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { + return ret; + } + } } + #endif + idx = localIdx; - if (ret == 0 && authTagSz > (int)sizeof(authTag)) { + if (ret == 0 && authTagSz > (word32)sizeof(authTag)) { WOLFSSL_MSG("AuthEnvelopedData authTag too large for buffer"); ret = ASN_PARSE_E; } if (ret == 0) { - XMEMCPY(authTag, &pkiMsg[idx], (word32)authTagSz); - idx += (word32)authTagSz; - } - - if (ret == 0 && authAttrib != NULL) { - /* temporarily swap authAttribs byte[0] to SET OF instead of - * IMPLICIT [1], for aad calculation */ - authAttribSetByte = encodedAttribs[0]; - - encodedAttribs[0] = ASN_SET | ASN_CONSTRUCTED; + XMEMCPY(authTag, &pkiMsg[idx], authTagSz); + idx += authTagSz; } if (ret < 0) @@ -13615,15 +14018,15 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, /* store tag for later */ if (authTagSz > 0) { - pkcs7->stream->tagSz = (word32)authTagSz; - pkcs7->stream->tag = (byte*)XMALLOC((word32)authTagSz, + pkcs7->stream->tagSz = authTagSz; + pkcs7->stream->tag = (byte*)XMALLOC(authTagSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7); if (pkcs7->stream->tag == NULL) { ret = MEMORY_E; break; } else { - XMEMCPY(pkcs7->stream->tag, authTag, (word32)authTagSz); + XMEMCPY(pkcs7->stream->tag, authTag, authTagSz); } } @@ -13652,14 +14055,14 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, } if (pkcs7->stream->tagSz > 0) { - authTagSz = (int)pkcs7->stream->tagSz; + authTagSz = pkcs7->stream->tagSz; if (authTagSz > WC_AES_BLOCK_SIZE) { WOLFSSL_MSG("PKCS7 saved tag is too large"); ret = BUFFER_E; break; } else { - XMEMCPY(authTag, pkcs7->stream->tag, (word32)authTagSz); + XMEMCPY(authTag, pkcs7->stream->tag, authTagSz); } } @@ -13671,25 +14074,26 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, wc_PKCS7_StreamGetVar(pkcs7, &encOID, &blockKeySz, &encryptedContentSz); encryptedContent = pkcs7->stream->bufferPt; - #ifdef WOLFSSL_SMALL_STACK decryptedKey = pkcs7->stream->key; - #endif #endif /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, decryptedKey, - blockKeySz, nonce, nonceSz, encodedAttribs, encodedAttribSz, - authTag, (word32)authTagSz, encryptedContent, - encryptedContentSz, encryptedContent, pkcs7->devId, - pkcs7->heap); + ret = wc_PKCS7_DecryptContent(pkcs7, encOID, decryptedKey, + (word32)blockKeySz, nonce, nonceSz, encodedAttribs, + encodedAttribSz, authTag, authTagSz, + encryptedContent, encryptedContentSz, encryptedContent, + pkcs7->devId, pkcs7->heap); if (ret != 0) { XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); return ret; } - if (authAttrib != NULL) { - /* restore authAttrib IMPLICIT [1] */ - encodedAttribs[0] = authAttribSetByte; + if (encodedAttribs != NULL) { + XFREE(encodedAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encodedAttribs = NULL; + #ifndef NO_PKCS7_STREAM + pkcs7->stream->aad = NULL; + #endif } /* copy plaintext to output */ @@ -13700,12 +14104,10 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); encryptedContent = NULL; ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); - #ifdef WOLFSSL_SMALL_STACK XFREE(decryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); decryptedKey = NULL; - #ifndef NO_PKCS7_STREAM + #ifndef NO_PKCS7_STREAM pkcs7->stream->key = NULL; - #endif #endif ret = encryptedContentSz; #ifndef NO_PKCS7_STREAM @@ -13718,23 +14120,33 @@ WOLFSSL_API int wc_PKCS7_DecodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* in, ret = BAD_FUNC_ARG; } -#ifdef WOLFSSL_SMALL_STACK if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { if (decryptedKey != NULL) { ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); + XFREE(decryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + decryptedKey = NULL; + #ifndef NO_PKCS7_STREAM + pkcs7->stream->key = NULL; + #endif } - XFREE(decryptedKey, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - } -#else - if (ret < 0) { + if (encryptedContent != NULL) { ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); encryptedContent = NULL; + #ifndef NO_PKCS7_STREAM + pkcs7->stream->bufferPt = NULL; + #endif + } + + if (encodedAttribs != NULL) { + XFREE(encodedAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + encodedAttribs = NULL; + #ifndef NO_PKCS7_STREAM + pkcs7->stream->aad = NULL; + #endif } - ForceZero(decryptedKey, MAX_ENCRYPTED_KEY_SZ); } -#endif #ifndef NO_PKCS7_STREAM if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { @@ -13924,23 +14336,27 @@ int wc_PKCS7_EncodeEncryptedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) pkcs7->unprotectedAttribs, (int)pkcs7->unprotectedAttribsSz); - flatAttribs = (byte*)XMALLOC(attribsSz, pkcs7->heap, - DYNAMIC_TYPE_PKCS7); - if (flatAttribs == NULL) { - XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - return MEMORY_E; - } + if (attribsSz > 0) { + flatAttribs = (byte*)XMALLOC(attribsSz, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); + if (flatAttribs == NULL) { + XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + return MEMORY_E; + } - ret = FlattenAttributes(pkcs7, flatAttribs, attribs, (int)attribsCount); - if (ret != 0) { - XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - return ret; + ret = FlattenAttributes(pkcs7, flatAttribs, attribs, + (int)attribsCount); + if (ret != 0) { + XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(plain, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(flatAttribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + return ret; + } } + attribsSetSz = SetImplicit(ASN_SET, 1, attribsSz, attribSet, 0); } else { @@ -14007,8 +14423,10 @@ int wc_PKCS7_EncodeEncryptedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) if (pkcs7->unprotectedAttribsSz != 0) { XMEMCPY(output + idx, attribSet, attribsSetSz); idx += (int)attribsSetSz; - XMEMCPY(output + idx, flatAttribs, attribsSz); - idx += (int)attribsSz; + if (attribsSz > 0) { + XMEMCPY(output + idx, flatAttribs, attribsSz); + idx += (int)attribsSz; + } } XFREE(attribs, pkcs7->heap, DYNAMIC_TYPE_PKCS7); @@ -14202,7 +14620,8 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, if (ret == 0 && (ret = GetAlgoId(pkiMsg, &idx, &encOID, oidBlkType, pkiMsgSz)) < 0) ret = ASN_PARSE_E; - if (ret == 0 && (expBlockSz = wc_PKCS7_GetOIDBlockSize((int)encOID)) < 0) + if (ret == 0 && (expBlockSz = + wc_PKCS7_GetOIDBlockSize((int)encOID)) < 0) ret = expBlockSz; if (ret != 0) break; @@ -14243,7 +14662,8 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, ret = ASN_PARSE_E; if (ret == 0 && length != expBlockSz) { - WOLFSSL_MSG("Incorrect IV length, must be of content alg block size"); + WOLFSSL_MSG( + "Incorrect IV length, must be of content alg block size"); ret = ASN_PARSE_E; } @@ -14322,6 +14742,11 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, version = (int)pkcs7->stream->vers; tmpIv = pkcs7->stream->tmpIv; #endif + if (encryptedContentSz <= 0) { + ret = BUFFER_E; + break; + } + if (ret == 0 && (encryptedContent = (byte*)XMALLOC( (unsigned int)encryptedContentSz, pkcs7->heap, DYNAMIC_TYPE_PKCS7)) == NULL) { @@ -14335,8 +14760,8 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, idx += (word32)encryptedContentSz; /* decrypt encryptedContent */ - ret = wc_PKCS7_DecryptContent(pkcs7, (int)encOID, - pkcs7->encryptionKey, (int)pkcs7->encryptionKeySz, + ret = wc_PKCS7_DecryptContent(pkcs7, encOID, + pkcs7->encryptionKey, pkcs7->encryptionKeySz, tmpIv, expBlockSz, NULL, 0, NULL, 0, encryptedContent, encryptedContentSz, encryptedContent, pkcs7->devId, pkcs7->heap); @@ -14374,7 +14799,8 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, pkiMsgSz, &idx); if (ret != 0) { ForceZero(encryptedContent, (word32)encryptedContentSz); - XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); + XFREE(encryptedContent, pkcs7->heap, + DYNAMIC_TYPE_PKCS7); ret = ASN_PARSE_E; } } @@ -14384,7 +14810,8 @@ int wc_PKCS7_DecodeEncryptedData(wc_PKCS7* pkcs7, byte* in, word32 inSz, ForceZero(encryptedContent, (word32)encryptedContentSz); XFREE(encryptedContent, pkcs7->heap, DYNAMIC_TYPE_PKCS7); - /* go back and check the version now that attribs have been processed */ + /* go back and check the version now that attribs have been + * processed */ if (pkcs7->version == 3 && version != 0) { WOLFSSL_MSG("Wrong PKCS#7 FirmwareEncryptedData version"); return ASN_VERSION_E; @@ -14514,7 +14941,8 @@ int wc_PKCS7_GetNoCerts(wc_PKCS7* pkcs7) #if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) /* build PKCS#7 compressedData content type, return encrypted size */ -int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz) +int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, + word32 outputSz) { byte contentInfoSeq[MAX_SEQ_SZ]; byte contentInfoTypeOid[MAX_OID_SZ]; @@ -14625,7 +15053,8 @@ int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz */ /* ContentInfo content EXPLICIT SEQUENCE */ - contentInfoContentSeqSz = SetExplicit(0, totalSz, contentInfoContentSeq, 0); + contentInfoContentSeqSz = SetExplicit(0, totalSz, contentInfoContentSeq, + 0); totalSz += contentInfoContentSeqSz; ret = wc_SetContentType(COMPRESSED_DATA, contentInfoTypeOid, @@ -14686,8 +15115,8 @@ int wc_PKCS7_EncodeCompressedData(wc_PKCS7* pkcs7, byte* output, word32 outputSz /* unwrap and decompress PKCS#7/CMS compressedData object, * Handles content wrapped compressed data and raw compressed data packet * returned decoded size */ -int wc_PKCS7_DecodeCompressedData(wc_PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz, - byte* output, word32 outputSz) +int wc_PKCS7_DecodeCompressedData(wc_PKCS7* pkcs7, byte* pkiMsg, + word32 pkiMsgSz, byte* output, word32 outputSz) { int length, version, ret; word32 idx = 0, algOID, contentType; diff --git a/src/wolfcrypt/src/poly1305.c b/src/wolfcrypt/src/poly1305.c index 718289c..bd72a40 100644 --- a/src/wolfcrypt/src/poly1305.c +++ b/src/wolfcrypt/src/poly1305.c @@ -1,6 +1,6 @@ /* poly1305.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -36,16 +36,10 @@ and Daniel J. Bernstein * 303.004 MiB/s with and 1874.194 MiB/s without. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_POLY1305 #include -#include -#include #include #ifdef NO_INLINE #include @@ -529,6 +523,7 @@ int wc_Poly1305SetKey(Poly1305* ctx, const byte* key, word32 keySz) #endif poly1305_setkey_avx(ctx, key); RESTORE_VECTOR_REGISTERS(); + ctx->started = 0; #elif defined(POLY130564) /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ @@ -813,13 +808,49 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) printf("\n"); #endif +#if defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_ARMASM_THUMB2) && \ + !defined(WOLFSSL_ARMASM_NO_NEON) + /* handle leftover */ + if (ctx->leftover) { + size_t want = sizeof(ctx->buffer) - ctx->leftover; + if (want > bytes) + want = bytes; + + for (i = 0; i < want; i++) + ctx->buffer[ctx->leftover + i] = m[i]; + bytes -= (word32)want; + m += want; + ctx->leftover += want; + if (ctx->leftover < sizeof(ctx->buffer)) { + return 0; + } + + poly1305_blocks(ctx, ctx->buffer, sizeof(ctx->buffer)); + ctx->leftover = 0; + } + + /* process full blocks */ + if (bytes >= sizeof(ctx->buffer)) { + size_t want = bytes & ~((size_t)POLY1305_BLOCK_SIZE - 1); + + poly1305_blocks(ctx, m, want); + m += want; + bytes -= (word32)want; + } + + /* store leftover */ + if (bytes) { + for (i = 0; i < bytes; i++) + ctx->buffer[ctx->leftover + i] = m[i]; + ctx->leftover += bytes; + } +#else #ifdef USE_INTEL_POLY1305_SPEEDUP #ifdef HAVE_INTEL_AVX2 if (IS_INTEL_AVX2(intel_flags)) { SAVE_VECTOR_REGISTERS(return _svr_ret;); /* handle leftover */ - if (ctx->leftover) { size_t want = sizeof(ctx->buffer) - ctx->leftover; if (want > bytes) @@ -835,8 +866,10 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) return 0; } - if (!ctx->started) + if (!ctx->started) { poly1305_calc_powers_avx2(ctx); + ctx->started = 1; + } poly1305_blocks_avx2(ctx, ctx->buffer, sizeof(ctx->buffer)); ctx->leftover = 0; } @@ -845,8 +878,10 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) if (bytes >= sizeof(ctx->buffer)) { size_t want = bytes & ~(sizeof(ctx->buffer) - 1); - if (!ctx->started) + if (!ctx->started) { poly1305_calc_powers_avx2(ctx); + ctx->started = 1; + } poly1305_blocks_avx2(ctx, m, want); m += want; bytes -= (word32)want; @@ -902,6 +937,7 @@ int wc_Poly1305Update(Poly1305* ctx, const byte* m, word32 bytes) ctx->leftover += bytes; } } +#endif return 0; } diff --git a/src/wolfcrypt/src/port/Espressif/esp32_aes.c b/src/wolfcrypt/src/port/Espressif/esp32_aes.c index fc0fd7f..b1479de 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -1,6 +1,6 @@ /* esp32_aes.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/Espressif/esp32_mp.c b/src/wolfcrypt/src/port/Espressif/esp32_mp.c index 6d9d2ab..dbfd133 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -1,6 +1,6 @@ /* esp32_mp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/Espressif/esp32_sha.c b/src/wolfcrypt/src/port/Espressif/esp32_sha.c index 65d635d..f9f8d90 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -1,6 +1,6 @@ /* esp32_sha.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/Espressif/esp32_util.c b/src/wolfcrypt/src/port/Espressif/esp32_util.c index f133875..90b3cdc 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_util.c @@ -1,6 +1,6 @@ /* esp32_util.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -37,7 +37,9 @@ #if ESP_IDF_VERSION_MAJOR > 4 #include #include + #include #endif + /* wolfSSL */ #include /* needed to print MATH_INT_T value */ #include @@ -739,15 +741,25 @@ esp_err_t esp_DisableWatchdog(void) #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) || \ - defined(CONFIG_IDF_TARGET_ESP32H2) - ESP_LOGW(TAG, "No known rtc_wdt_protect_off for this platform."); + defined(CONFIG_IDF_TARGET_ESP32H2) || \ + defined(CONFIG_IDF_TARGET_ESP32P4) + #if ESP_IDF_VERSION_MINOR >= 3 + #if CONFIG_ESP_TASK_WDT + ret = esp_task_wdt_deinit(); + #else + /* CONFIG_ESP_TASK_WDT=y needed in sdkconfig */ + ESP_LOGW(TAG, "esp_task_wdt_deinit not available"); + #endif + #else + ESP_LOGW(TAG, "esp_task_wdt_deinit not implemented"); + #endif #else rtc_wdt_protect_off(); rtc_wdt_disable(); #endif } #else - ESP_LOGW(TAG, "esp_DisableWatchdog not implemented on ESP_OIDF v%d", + ESP_LOGW(TAG, "esp_DisableWatchdog not implemented on ESP_IDF v%d", ESP_IDF_VERSION_MAJOR); #endif #endif @@ -780,8 +792,17 @@ esp_err_t esp_EnabledWatchdog(void) #elif defined(CONFIG_IDF_TARGET_ESP32C2) || \ defined(CONFIG_IDF_TARGET_ESP32C3) || \ defined(CONFIG_IDF_TARGET_ESP32C6) || \ - defined(CONFIG_IDF_TARGET_ESP32H2) + defined(CONFIG_IDF_TARGET_ESP32H2) || \ + defined(CONFIG_IDF_TARGET_ESP32P4) + ESP_LOGW(TAG, "No known rtc_wdt_protect_off for this platform."); + esp_task_wdt_config_t twdt_config = { + .timeout_ms = 5000, /* Timeout in milliseconds */ + .trigger_panic = true, /* trigger panic on timeout */ + .idle_core_mask = (1 << 0), /* Enable on Core 0 */ + }; ESP_LOGW(TAG, "No known rtc_wdt_protect_off for this platform."); + esp_task_wdt_init(&twdt_config); + esp_task_wdt_add(NULL); #else rtc_wdt_protect_on(); rtc_wdt_enable(); diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c index 81d88a6..5bd7a64 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c @@ -1,6 +1,6 @@ /* esp_sdk_mem_lib.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c index 678de3b..036174e 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c @@ -1,6 +1,6 @@ /* esp_sdk_time_lib.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c index 9a200a9..db7c954 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c @@ -1,6 +1,6 @@ /* esp_sdk_wifi_lib.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/port/atmel/atmel.c b/src/wolfcrypt/src/port/atmel/atmel.c index 31ad98f..6aabe5d 100644 --- a/src/wolfcrypt/src/port/atmel/atmel.c +++ b/src/wolfcrypt/src/port/atmel/atmel.c @@ -1,6 +1,6 @@ /* atmel.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfcrypt/src/pwdbased.c b/src/wolfcrypt/src/pwdbased.c index 208f667..c60db6a 100644 --- a/src/wolfcrypt/src/pwdbased.c +++ b/src/wolfcrypt/src/pwdbased.c @@ -1,6 +1,6 @@ /* pwdbased.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifndef NO_PWDBASED @@ -42,7 +37,6 @@ #include #include #include -#include #ifdef NO_INLINE #include @@ -52,9 +46,6 @@ #endif #if FIPS_VERSION3_GE(6,0,0) - #ifdef DEBUG_WOLFSSL - #include - #endif const unsigned int wolfCrypt_FIPS_pbkdf_ro_sanity[2] = { 0x1a2b3c4d, 0x00000010 }; int wolfCrypt_FIPS_PBKDF_sanity(void) @@ -840,6 +831,8 @@ int wc_scrypt(byte* output, const byte* passwd, int passLen, goto end; } + XMEMSET(y, 0, (size_t)(blockSize * 128)); + /* Step 1. */ ret = wc_PBKDF2(blocks, passwd, passLen, salt, saltLen, 1, (int)blocksSz, WC_SHA256); diff --git a/src/wolfcrypt/src/random.c b/src/wolfcrypt/src/random.c index febc292..746a06b 100644 --- a/src/wolfcrypt/src/random.c +++ b/src/wolfcrypt/src/random.c @@ -1,6 +1,6 @@ /* random.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -25,15 +25,26 @@ DESCRIPTION This library contains implementation for the random number generator. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include -#include -#if defined(DEBUG_WOLFSSL) - #include -#endif +/* Possible defines: + * ENTROPY_NUM_UPDATE default: 18 + * Number of updates to perform. A hash is created and memory accessed + * based on the hash values in each update of a sample. + * More updates will result in better entropy quality but longer sample + * times. + * ENTROPY_NUM_UPDATES_BITS default: 5 + * Number of bits needed to represent ENTROPY_NUM_UPDATE. + * = upper(log2(ENTROPY_NUM_UPDATE)) + * ENTROPY_NUM_WORDS_BITS default: 14 + * State has 2^ENTROPY_NUMN_WORDS_BITS entries. Range: 8-30 + * The value should be based on the cache sizes. + * Use a value that is at least as large as the L1 cache if possible. + * The higher the value, the more likely there will be cache misses and + * better the entropy quality. + * A larger value will use more static memory. + */ + +#include /* on HPUX 11 you may need to install /dev/random see http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I @@ -87,11 +98,12 @@ This library contains implementation for the random number generator. #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ #include #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ #elif defined(HAVE_WNR) #include - #include wolfSSL_Mutex wnr_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wnr_mutex); /* global netRandom mutex */ int wnr_timeout = 0; /* entropy timeout, milliseconds */ #ifndef WOLFSSL_MUTEX_INITIALIZER @@ -794,8 +806,13 @@ static wc_Sha3 entropyHash; /* Reset the health tests. */ static void Entropy_HealthTest_Reset(void); -#if !defined(ENTROPY_MEMUSE_THREAD) && \ - (defined(__x86_64__) || defined(__i386__)) +#ifdef CUSTOM_ENTROPY_TIMEHIRES +static WC_INLINE word64 Entropy_TimeHiRes(void) +{ + return CUSTOM_ENTROPY_TIMEHIRES(); +} +#elif !defined(ENTROPY_MEMUSE_THREAD) && \ + (defined(__x86_64__) || defined(__i386__)) /* Get the high resolution time counter. * * @return 64-bit count of CPU cycles. @@ -818,7 +835,7 @@ static WC_INLINE word64 Entropy_TimeHiRes(void) */ static WC_INLINE word64 Entropy_TimeHiRes(void) { - return mach_absolute_time(); + return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW); } #elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__aarch64__) /* Get the high resolution time counter. @@ -913,7 +930,8 @@ static WC_INLINE word64 Entropy_TimeHiRes(void) * @param [in,out] args Entropy data including: counter and stop flag. * @return NULL always. */ -static THREAD_RETURN WOLFSSL_THREAD_NO_JOIN Entropy_IncCounter(void* args) +static THREAD_RETURN_NOJOIN WOLFSSL_THREAD_NO_JOIN + Entropy_IncCounter(void* args) { (void)args; @@ -926,8 +944,9 @@ static THREAD_RETURN WOLFSSL_THREAD_NO_JOIN Entropy_IncCounter(void* args) #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE fprintf(stderr, "EXITING ENTROPY COUNTER THREAD\n"); #endif + /* Exit from thread. */ - WOLFSSL_RETURN_FROM_THREAD(0); + RETURN_FROM_THREAD_NOJOIN(0); } /* Start a thread that increments counter if not one already. @@ -1031,9 +1050,18 @@ static void Entropy_StopThread(void) #elif !defined(ENTROPY_NUM_UPDATES_BITS) #define ENTROPY_NUM_UPDATES_BITS ENTROPY_BLOCK_SZ #endif -/* Amount to shift offset to get better coverage of a block */ -#define ENTROPY_OFFSET_SHIFTING \ - (ENTROPY_BLOCK_SZ / ENTROPY_NUM_UPDATES_BITS) +#ifndef ENTROPY_NUM_UPDATES_BITS + #error "ENTROPY_NUM_UPDATES_BITS must be defined - " \ + "upper(log2(ENTROPY_NUM_UPDATES))" +#endif +#if ENTROPY_NUM_UPDATES_BITS != 0 + /* Amount to shift offset to get better coverage of a block */ + #define ENTROPY_OFFSET_SHIFTING \ + (ENTROPY_BLOCK_SZ / ENTROPY_NUM_UPDATES_BITS) +#else + /* Amount to shift offset to get better coverage of a block */ + #define ENTROPY_OFFSET_SHIFTING ENTROPY_BLOCK_SZ +#endif #ifndef ENTROPY_NUM_64BIT_WORDS /* Number of 64-bit words to update - 32. */ @@ -1042,8 +1070,14 @@ static void Entropy_StopThread(void) #error "ENTROPY_NUM_64BIT_WORDS must be <= SHA3-256 digest size in bytes" #endif +#if ENTROPY_BLOCK_SZ < ENTROPY_NUM_UPDATES_BITS +#define EXTRA_ENTROPY_WORDS ENTROPY_NUM_UPDATES +#else +#define EXTRA_ENTROPY_WORDS 0 +#endif + /* State to update that is multiple cache lines long. */ -static word64 entropy_state[ENTROPY_NUM_WORDS] = {0}; +static word64 entropy_state[ENTROPY_NUM_WORDS + EXTRA_ENTROPY_WORDS] = {0}; /* Using memory will take different amount of times depending on the CPU's * caches and business. @@ -1721,16 +1755,21 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, #else ret = wc_GenerateSeed(&rng->seed, seed, seedSz); #endif /* WC_RNG_SEED_CB */ - if (ret == 0) - ret = wc_RNG_TestSeed(seed, seedSz); - else { + if (ret != 0) { #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG_EX("wc_RNG_TestSeed failed... %d", ret); + WOLFSSL_MSG_EX("Seed generation failed... %d", ret); #endif ret = DRBG_FAILURE; rng->status = DRBG_FAILED; } + if (ret == 0) + ret = wc_RNG_TestSeed(seed, seedSz); + #if defined(DEBUG_WOLFSSL) + if (ret != 0) { + WOLFSSL_MSG_EX("wc_RNG_TestSeed failed... %d", ret); + } + #endif if (ret == DRBG_SUCCESS) ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg, seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ, @@ -2184,7 +2223,7 @@ static int wc_RNG_HealthTestLocal(int reseed, void* heap, int devId) #endif #ifdef WOLFSSL_SMALL_STACK - check = (byte*)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, NULL, + check = (byte*)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER); if (check == NULL) { return MEMORY_E; @@ -2304,7 +2343,7 @@ static int wc_RNG_HealthTestLocal(int reseed, void* heap, int devId) } #ifdef WOLFSSL_SMALL_STACK - XFREE(check, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(check, heap, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; @@ -2766,7 +2805,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return ret; } -#elif defined(MICROCHIP_PIC32) +#elif defined(MICROCHIP_PIC32) || defined(MICROCHIP_MPLAB_HARMONY) #ifdef MICROCHIP_MPLAB_HARMONY #ifdef MICROCHIP_MPLAB_HARMONY_3 diff --git a/src/wolfcrypt/src/rc2.c b/src/wolfcrypt/src/rc2.c index 67dc7d6..33d2bd2 100644 --- a/src/wolfcrypt/src/rc2.c +++ b/src/wolfcrypt/src/rc2.c @@ -1,6 +1,6 @@ /* rc2.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,17 +19,14 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include + /* DESCRIPTION This library provides the interface to the RC2 encryption algorithm (RFC 2268) */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #ifdef WC_RC2 @@ -41,7 +38,6 @@ This library provides the interface to the RC2 encryption algorithm (RFC 2268) #endif #include -#include /* Table based on value of PI, defined in RFC 2268 */ static const byte pitable[256] = { diff --git a/src/wolfcrypt/src/ripemd.c b/src/wolfcrypt/src/ripemd.c index 36cca1b..7f3b6d8 100644 --- a/src/wolfcrypt/src/ripemd.c +++ b/src/wolfcrypt/src/ripemd.c @@ -1,6 +1,6 @@ /* ripemd.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_RIPEMD @@ -37,8 +31,6 @@ #include #endif -#include - int wc_InitRipeMd(RipeMd* ripemd) { if (ripemd == NULL) { diff --git a/src/wolfcrypt/src/rsa.c b/src/wolfcrypt/src/rsa.c index a3c0292..94d57bd 100644 --- a/src/wolfcrypt/src/rsa.c +++ b/src/wolfcrypt/src/rsa.c @@ -1,6 +1,6 @@ /* rsa.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -26,12 +26,8 @@ This library provides the interface to the RSA. RSA keys can be used to encrypt, decrypt, sign and verify data. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include -#include +#include #ifndef NO_RSA @@ -53,7 +49,7 @@ RSA keys can be used to encrypt, decrypt, sign and verify data. #if defined(WOLFSSL_XILINX_CRYPT_VERSAL) #include #endif -#ifdef WOLFSSL_SE050 +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) #include #endif #ifdef WOLFSSL_HAVE_SP_RSA @@ -95,7 +91,6 @@ RSA Key Size Configuration: #include -#include #ifdef WOLF_CRYPTO_CB #include #endif @@ -298,7 +293,7 @@ int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, int devId) { int ret = 0; -#ifdef WOLFSSL_SE050 +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) /* SE050 TLS users store a word32 at id, need to cast back */ word32* keyPtr = NULL; #endif @@ -312,7 +307,7 @@ int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, if (ret == 0 && id != NULL && len != 0) { XMEMCPY(key->id, id, (size_t)len); key->idLen = len; - #ifdef WOLFSSL_SE050 + #if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) /* Set SE050 ID from word32, populate RsaKey with public from SE050 */ if (len == (int)sizeof(word32)) { keyPtr = (word32*)key->id; @@ -521,7 +516,7 @@ static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e) } #endif /* WOLFSSL_CRYPTOCELL */ -#ifdef WOLFSSL_SE050 +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) /* Use specified hardware key ID with RsaKey operations. Unlike devId, * keyId is a word32 so can handle key IDs larger than an int. * @@ -646,6 +641,8 @@ static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng) ret = wc_RsaEncryptSize(key); if (ret < 0) return ret; + else if (ret == 0) + return BAD_FUNC_ARG; sigLen = (word32)ret; WOLFSSL_MSG("Doing RSA consistency test"); @@ -1756,6 +1753,7 @@ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, if (tmp == NULL) { return MEMORY_E; } + XMEMSET(tmp, 0, (size_t)maskLen); #endif if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, tmp, (word32)maskLen, @@ -3162,12 +3160,13 @@ static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out, int checkSmallCt) { int ret = 0; - (void)rng; - (void)checkSmallCt; #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD) RsaPadding padding; #endif + (void)rng; + (void)checkSmallCt; + if (key == NULL || in == NULL || inLen == 0 || out == NULL || outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) { return BAD_FUNC_ARG; @@ -3365,7 +3364,7 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, return cc310_RsaSSL_Sign(in, inLen, out, outLen, key, cc310_hashModeRSA(hash, 0)); } - #elif defined(WOLFSSL_SE050) + #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { return se050_rsa_public_encrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, @@ -3527,7 +3526,7 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, return cc310_RsaSSL_Verify(in, inLen, out, key, cc310_hashModeRSA(hash, 0)); } - #elif defined(WOLFSSL_SE050) + #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { ret = se050_rsa_private_decrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, @@ -3600,6 +3599,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, ret = wc_CryptoCb_RsaPad(in, inLen, out, &outLen, rsa_type, key, rng, &padding); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + if (ret == 0) { + ret = (int)outLen; + } break; } } @@ -4061,11 +4063,12 @@ int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig, int ret = 0; byte sigCheckBuf[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ]; byte *sigCheck = sigCheckBuf; - + int digSz; (void)bits; - if (in == NULL || sig == NULL || - inSz != (word32)wc_HashGetDigestSize(hashType)) { + digSz = wc_HashGetDigestSize(hashType); + + if (in == NULL || sig == NULL || digSz < 0 || inSz != (word32)digSz) { ret = BAD_FUNC_ARG; } @@ -4780,7 +4783,8 @@ int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz, int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { #ifndef WC_NO_RNG -#if !defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_SE050) +#if !defined(WOLFSSL_CRYPTOCELL) && \ + (!defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_NO_RSA)) #ifdef WOLFSSL_SMALL_STACK mp_int *p = NULL; mp_int *q = NULL; @@ -4823,7 +4827,7 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #if defined(WOLFSSL_CRYPTOCELL) err = cc310_RSA_GenerateKeyPair(key, size, e); goto out; -#elif defined(WOLFSSL_SE050) +#elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) err = se050_rsa_create_key(key, size, e); goto out; #else @@ -4859,17 +4863,17 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #endif { err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); - #ifndef WOLF_CRYPTO_CB_ONLY_RSA - if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) - goto out; - /* fall-through when unavailable */ - #endif - #ifdef WOLF_CRYPTO_CB_ONLY_RSA - if (err == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) + #ifdef WOLF_CRYPTO_CB_ONLY_RSA + if (err == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { err = NO_VALID_DEVID; goto out; } - #endif + #else + if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { + goto out; + } + /* fall-through when unavailable */ + #endif } #endif diff --git a/src/wolfcrypt/src/sakke.c b/src/wolfcrypt/src/sakke.c index fab1067..d428c59 100644 --- a/src/wolfcrypt/src/sakke.c +++ b/src/wolfcrypt/src/sakke.c @@ -1,6 +1,6 @@ /* sakke.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef NO_INLINE #include @@ -40,7 +34,6 @@ #ifdef WOLFCRYPT_HAVE_SAKKE -#include #include #include diff --git a/src/wolfcrypt/src/sha.c b/src/wolfcrypt/src/sha.c index 78ce918..887541a 100644 --- a/src/wolfcrypt/src/sha.c +++ b/src/wolfcrypt/src/sha.c @@ -1,6 +1,6 @@ /* sha.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,11 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef DEBUG_WOLFSSL_VERBOSE #if defined(WOLFSSL_ESPIDF) #include - #else - #include #endif #endif @@ -47,7 +40,6 @@ #endif #include -#include #include #ifdef WOLF_CRYPTO_CB @@ -110,7 +102,6 @@ #else -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/sha256.c b/src/wolfcrypt/src/sha256.c index c9c3b10..5b990a2 100644 --- a/src/wolfcrypt/src/sha256.c +++ b/src/wolfcrypt/src/sha256.c @@ -1,6 +1,6 @@ /* sha256.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -38,12 +38,7 @@ on the specific device platform. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include +#include /* * SHA256 Build Options: @@ -77,7 +72,6 @@ on the specific device platform. #endif #include -#include #include #include @@ -127,8 +121,6 @@ on the specific device platform. /* #include */ #else -#include - #ifdef NO_INLINE #include #else @@ -209,7 +201,8 @@ on the specific device platform. #define SHA256_UPDATE_REV_BYTES(ctx) (sha256->sha_method == SHA256_C) #else #define SHA256_UPDATE_REV_BYTES(ctx) \ - (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags)) + (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags) && \ + !IS_INTEL_SHA(intel_flags)) #endif #elif defined(FREESCALE_MMCAU_SHA) #define SHA256_UPDATE_REV_BYTES(ctx) 0 /* reverse not needed on update */ @@ -1652,7 +1645,8 @@ static int InitSha256(wc_Sha256* sha256) #ifdef WC_C_DYNAMIC_FALLBACK if (sha256->sha_method != SHA256_C) #else - if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags)) + if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags) || + IS_INTEL_SHA(intel_flags)) #endif #endif { @@ -2590,7 +2584,7 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) #endif #ifdef WOLFSSL_HASH_FLAGS - dst->flags |= WC_HASH_FLAG_ISCOPY; + dst->flags |= WC_HASH_FLAG_ISCOPY; #endif #if defined(WOLFSSL_HASH_KEEP) diff --git a/src/wolfcrypt/src/sha3.c b/src/wolfcrypt/src/sha3.c index 4ced66e..a9795ff 100644 --- a/src/wolfcrypt/src/sha3.c +++ b/src/wolfcrypt/src/sha3.c @@ -1,6 +1,6 @@ /* sha3.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_XILINX_CRYPT) && \ !defined(WOLFSSL_AFALG_XILINX_SHA3) @@ -40,7 +35,6 @@ #endif #include -#include #include #ifdef WOLF_CRYPTO_CB @@ -761,7 +755,9 @@ static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, byte p) if (SHA3_BLOCK == sha3_block_avx2) RESTORE_VECTOR_REGISTERS(); #endif - XMEMCPY(sha3->t, data, len); + if (len > 0) { + XMEMCPY(sha3->t, data, len); + } sha3->i = (byte)(sha3->i + len); return 0; @@ -1499,6 +1495,10 @@ int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len) { int ret; + if ((shake == NULL) || (data == NULL && len != 0)) { + return BAD_FUNC_ARG; + } + ret = Sha3Update(shake, data, len, WC_SHA3_128_COUNT); if (ret == 0) { byte hash[1]; @@ -1526,6 +1526,9 @@ int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len) */ int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) { + if ((shake == NULL) || (out == NULL && blockCnt != 0)) { + return BAD_FUNC_ARG; + } #if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) if (SHA3_BLOCK == sha3_block_avx2) SAVE_VECTOR_REGISTERS(return _svr_ret;); @@ -1644,6 +1647,10 @@ int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len) { int ret; + if ((shake == NULL) || (data == NULL && len != 0)) { + return BAD_FUNC_ARG; + } + ret = Sha3Update(shake, data, len, WC_SHA3_256_COUNT); if (ret == 0) { byte hash[1]; @@ -1664,6 +1671,9 @@ int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len) */ int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt) { + if ((shake == NULL) || (out == NULL && blockCnt != 0)) { + return BAD_FUNC_ARG; + } #if defined(WOLFSSL_LINUXKM) && defined(USE_INTEL_SPEEDUP) if (SHA3_BLOCK == sha3_block_avx2) SAVE_VECTOR_REGISTERS(return _svr_ret;); diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index 16c3c0f..73ef412 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -1,6 +1,6 @@ /* sha512.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if (defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)) && \ (!defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_ARMASM_NO_NEON)) && \ @@ -56,7 +51,6 @@ #endif #include -#include #include #include @@ -73,8 +67,6 @@ #define USE_SLOW_SHA512 #endif -#include - #ifdef NO_INLINE #include #else @@ -1402,22 +1394,16 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, size_t digestSz) { -#ifdef LITTLE_ENDIAN_ORDER - word64 digest[WC_SHA512_DIGEST_SIZE / sizeof(word64)]; -#endif - if (sha512 == NULL || hash == NULL) { return BAD_FUNC_ARG; } #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64((word64*)digest, (word64*)sha512->digest, - WC_SHA512_DIGEST_SIZE); - XMEMCPY(hash, digest, digestSz); -#else - XMEMCPY(hash, sha512->digest, digestSz); + ByteReverseWords64(sha512->digest, sha512->digest, WC_SHA512_DIGEST_SIZE); #endif + XMEMCPY(hash, sha512->digest, digestSz); + return 0; } @@ -1807,22 +1793,16 @@ int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) int wc_Sha384FinalRaw(wc_Sha384* sha384, byte* hash) { -#ifdef LITTLE_ENDIAN_ORDER - word64 digest[WC_SHA384_DIGEST_SIZE / sizeof(word64)]; -#endif - if (sha384 == NULL || hash == NULL) { return BAD_FUNC_ARG; } #ifdef LITTLE_ENDIAN_ORDER - ByteReverseWords64((word64*)digest, (word64*)sha384->digest, - WC_SHA384_DIGEST_SIZE); - XMEMCPY(hash, digest, WC_SHA384_DIGEST_SIZE); -#else - XMEMCPY(hash, sha384->digest, WC_SHA384_DIGEST_SIZE); + ByteReverseWords64(sha384->digest, sha384->digest, WC_SHA384_DIGEST_SIZE); #endif + XMEMCPY(hash, sha384->digest, WC_SHA384_DIGEST_SIZE); + return 0; } diff --git a/src/wolfcrypt/src/signature.c b/src/wolfcrypt/src/signature.c index 83c92d8..5576e2e 100644 --- a/src/wolfcrypt/src/signature.c +++ b/src/wolfcrypt/src/signature.c @@ -1,6 +1,6 @@ /* signature.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,15 +19,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #include -#include -#include #ifndef NO_ASN #include #endif diff --git a/src/wolfcrypt/src/siphash.c b/src/wolfcrypt/src/siphash.c index b7c63c3..05c2690 100644 --- a/src/wolfcrypt/src/siphash.c +++ b/src/wolfcrypt/src/siphash.c @@ -1,6 +1,6 @@ /* siphash.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,16 +19,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include +#include #include -#include #ifdef NO_INLINE #include @@ -582,7 +575,7 @@ int wc_SipHash(const unsigned char* key, const unsigned char* in, word32 inSz, return 0; } -#elif !defined(WOLFSSL_NO_ASM) && defined(__GNUC__) && defined(__aarch64__) && \ +#elif defined(WOLFSSL_ARMASM) && defined(__GNUC__) && defined(__aarch64__) && \ (WOLFSSL_SIPHASH_CROUNDS == 1 || WOLFSSL_SIPHASH_CROUNDS == 2) && \ (WOLFSSL_SIPHASH_DROUNDS == 2 || WOLFSSL_SIPHASH_DROUNDS == 4) diff --git a/src/wolfcrypt/src/sm2.c b/src/wolfcrypt/src/sm2.c index 24b8df9..b866522 100644 --- a/src/wolfcrypt/src/sm2.c +++ b/src/wolfcrypt/src/sm2.c @@ -1,6 +1,6 @@ /* sm2.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sm3.c b/src/wolfcrypt/src/sm3.c index dfbef2e..b4723d8 100644 --- a/src/wolfcrypt/src/sm3.c +++ b/src/wolfcrypt/src/sm3.c @@ -1,6 +1,6 @@ /* sm3.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM3 diff --git a/src/wolfcrypt/src/sm4.c b/src/wolfcrypt/src/sm4.c index c29cc2b..4da6f0b 100644 --- a/src/wolfcrypt/src/sm4.c +++ b/src/wolfcrypt/src/sm4.c @@ -1,6 +1,6 @@ /* sm4.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM4 diff --git a/src/wolfcrypt/src/sp_arm32.c b/src/wolfcrypt/src/sp_arm32.c index 13f5578..a70eb35 100644 --- a/src/wolfcrypt/src/sp_arm32.c +++ b/src/wolfcrypt/src/sp_arm32.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include @@ -114,9 +109,9 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -256,11 +251,18 @@ static void sp_2048_to_bin_64(sp_digit* r, byte* a) * a A single precision integer. * b A single precision integer. */ -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -2238,8 +2240,13 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3, r4, r5, r6}\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -2252,11 +2259,18 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * a A single precision integer. * b A single precision integer. */ -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #36\n\t" @@ -2592,8 +2606,13 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "sub %[r], %[r], #32\n\t" "stm %[r], {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #36\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -2606,11 +2625,18 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * a A single precision integer. * b A single precision integer. */ -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #44\n\t" @@ -2724,8 +2750,13 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "ldm sp, {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "stm lr, {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr" ); @@ -2738,11 +2769,18 @@ static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -2761,8 +2799,13 @@ static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -2773,10 +2816,16 @@ static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -2808,8 +2857,13 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -2821,11 +2875,19 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -2858,8 +2920,13 @@ static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -2935,10 +3002,16 @@ SP_NOINLINE static void sp_2048_mul_16(sp_digit* r, const sp_digit* a, * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -2998,8 +3071,13 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -3011,11 +3089,19 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -3076,8 +3162,13 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -3157,10 +3248,16 @@ SP_NOINLINE static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -3276,8 +3373,13 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -3289,11 +3391,19 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -3410,8 +3520,13 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -3492,10 +3607,16 @@ SP_NOINLINE static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -4690,8 +4811,13 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2, r3, r4, r8}\n\t" "stm %[r]!, {r2, r3, r4, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -4703,10 +4829,16 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -4934,8 +5066,13 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) "sub %[r], %[r], #32\n\t" "stm %[r], {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -4947,10 +5084,16 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -5051,8 +5194,13 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) "ldm sp, {r0, r1, r2, r3, r4, r5, r6}\n\t" "stm lr, {r0, r1, r2, r3, r4, r5, r6}\n\t" "add sp, sp, #32\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -5065,11 +5213,18 @@ static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -5087,8 +5242,13 @@ static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -5136,11 +5296,19 @@ SP_NOINLINE static void sp_2048_sqr_16(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -5172,8 +5340,13 @@ static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -5221,11 +5394,19 @@ SP_NOINLINE static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -5285,8 +5466,13 @@ static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -5336,11 +5522,19 @@ SP_NOINLINE static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -5360,8 +5554,13 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], r12\n\t" "bne L_sp_2048_add_64_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -5375,10 +5574,16 @@ static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -5397,8 +5602,13 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_2048_sub_in_pkace_64_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -5413,11 +5623,18 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x200\n\t" @@ -5600,8 +5817,13 @@ static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_2048_mul_64_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -5612,10 +5834,16 @@ static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_sqr_64(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x200\n\t" @@ -5758,8 +5986,13 @@ static void sp_2048_sqr_64(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_2048_sqr_64_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -5791,11 +6024,19 @@ static void sp_2048_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -5815,8 +6056,13 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], r12\n\t" "bne L_sp_2048_add_32_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -5830,10 +6076,16 @@ static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -5852,8 +6104,13 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_2048_sub_in_pkace_32_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -5868,11 +6125,18 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x100\n\t" @@ -6055,8 +6319,13 @@ static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_2048_mul_32_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -6067,10 +6336,16 @@ static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_sqr_32(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x100\n\t" @@ -6213,8 +6488,13 @@ static void sp_2048_sqr_32(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_2048_sqr_32_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -6250,11 +6530,17 @@ static void sp_2048_mont_setup(const sp_digit* a, sp_digit* rho) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -6335,8 +6621,13 @@ static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x100\n\t" "blt L_sp_2048_mul_d_64_word_%=\n\t" "str r3, [%[r], #256]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -6348,11 +6639,17 @@ static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -8400,8 +8697,13 @@ static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r3}\n\t" "str r4, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -8431,13 +8733,20 @@ static void sp_2048_mont_norm_32(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -8456,8 +8765,13 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x80\n\t" "blt L_sp_2048_cond_sub_32_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -8472,13 +8786,20 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -8595,8 +8916,13 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -8610,11 +8936,19 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -9576,8 +9910,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -9591,11 +9930,19 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -9872,8 +10219,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -9887,11 +10239,19 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -10078,8 +10438,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -10124,11 +10489,17 @@ SP_NOINLINE static void sp_2048_mont_sqr_32(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -10209,8 +10580,13 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x80\n\t" "blt L_sp_2048_mul_d_32_word_%=\n\t" "str r3, [%[r], #128]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -10222,11 +10598,17 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -11250,8 +11632,13 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r4}\n\t" "str r5, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -11267,11 +11654,17 @@ static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -11309,8 +11702,13 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -11326,11 +11724,17 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -11447,8 +11851,13 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -11462,10 +11871,16 @@ static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -11846,8 +12261,13 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -12257,13 +12677,20 @@ static void sp_2048_mont_norm_64(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -12282,8 +12709,13 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x100\n\t" "blt L_sp_2048_cond_sub_64_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -12298,13 +12730,20 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -12533,8 +12972,13 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -12548,11 +12992,19 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -14442,8 +14894,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -14457,11 +14914,19 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -14994,8 +15459,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -15009,11 +15479,19 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -15360,8 +15838,13 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_ "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -15406,11 +15889,19 @@ SP_NOINLINE static void sp_2048_mont_sqr_64(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -15429,8 +15920,13 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], lr\n\t" "bne L_sp_2048_sub_64_word_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -15444,11 +15940,19 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -15564,8 +16068,13 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -15582,11 +16091,17 @@ static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digi * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -15624,8 +16139,13 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -15641,11 +16161,17 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -15762,8 +16288,13 @@ static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -15881,10 +16412,16 @@ static void sp_2048_mask_64(sp_digit* r, const sp_digit* a, sp_digit m) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -16617,8 +17154,13 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -17150,13 +17692,20 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -17175,8 +17724,13 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, "cmp r12, #0x80\n\t" "blt L_sp_2048_cond_add_32_words_%=\n\t" "mov %[r], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -17191,13 +17745,20 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r8, #0\n\t" @@ -17314,8 +17875,13 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, "adcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "adc %[r], r8, r8\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; @@ -17636,11 +18202,17 @@ int sp_ModExp_2048(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef WOLFSSL_HAVE_SP_DH #ifdef HAVE_FFDHE_2048 +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_2048_lshift_64(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_2048_lshift_64(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #31\n\t" @@ -18028,8 +18600,13 @@ static void sp_2048_lshift_64(sp_digit* r_p, const sp_digit* a_p, byte n_p) "orr r6, r6, r3\n\t" "str r5, [%[r]]\n\t" "str r6, [%[r], #4]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -18317,9 +18894,9 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -18458,11 +19035,18 @@ static void sp_3072_to_bin_96(sp_digit* r, byte* a) * a A single precision integer. * b A single precision integer. */ -static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #48\n\t" @@ -23942,8 +24526,13 @@ static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3, r4, r5, r6}\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -23955,11 +24544,19 @@ static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -23985,8 +24582,13 @@ static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -23997,10 +24599,16 @@ static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -24046,8 +24654,13 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -24059,11 +24672,19 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -24110,8 +24731,13 @@ static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -24191,10 +24817,16 @@ SP_NOINLINE static void sp_3072_mul_24(sp_digit* r, const sp_digit* a, * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -24282,8 +24914,13 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -24295,11 +24932,19 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -24388,8 +25033,13 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -24469,10 +25119,16 @@ SP_NOINLINE static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -24644,8 +25300,13 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -24657,11 +25318,19 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -24834,8 +25503,13 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -24915,10 +25589,16 @@ SP_NOINLINE static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #48\n\t" @@ -27966,8 +28646,13 @@ static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2, r3, r4, r8}\n\t" "stm %[r]!, {r2, r3, r4, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -27979,11 +28664,19 @@ static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -28008,8 +28701,13 @@ static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -28057,11 +28755,19 @@ SP_NOINLINE static void sp_3072_sqr_24(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -28107,8 +28813,13 @@ static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -28156,11 +28867,19 @@ SP_NOINLINE static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -28248,8 +28967,13 @@ static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -28299,11 +29023,19 @@ SP_NOINLINE static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -28323,8 +29055,13 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], r12\n\t" "bne L_sp_3072_add_96_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -28338,10 +29075,16 @@ static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -28360,8 +29103,13 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_3072_sub_in_pkace_96_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -28376,11 +29124,18 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x300\n\t" @@ -28563,8 +29318,13 @@ static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_3072_mul_96_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -28575,10 +29335,16 @@ static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_sqr_96(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x300\n\t" @@ -28721,8 +29487,13 @@ static void sp_3072_sqr_96(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_3072_sqr_96_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -28754,11 +29525,19 @@ static void sp_3072_mask_48(sp_digit* r, const sp_digit* a, sp_digit m) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -28778,8 +29557,13 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], r12\n\t" "bne L_sp_3072_add_48_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -28793,10 +29577,16 @@ static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -28815,8 +29605,13 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_3072_sub_in_pkace_48_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -28831,11 +29626,18 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x180\n\t" @@ -29018,8 +29820,13 @@ static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_3072_mul_48_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -29030,10 +29837,16 @@ static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_sqr_48(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x180\n\t" @@ -29176,8 +29989,13 @@ static void sp_3072_sqr_48(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_3072_sqr_48_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -29213,11 +30031,17 @@ static void sp_3072_mont_setup(const sp_digit* a, sp_digit* rho) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -29298,8 +30122,13 @@ static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x180\n\t" "blt L_sp_3072_mul_d_96_word_%=\n\t" "str r3, [%[r], #384]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -29311,11 +30140,17 @@ static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -32387,8 +33222,13 @@ static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r5}\n\t" "str r3, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -32418,13 +33258,20 @@ static void sp_3072_mont_norm_48(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -32443,8 +33290,13 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0xc0\n\t" "blt L_sp_3072_cond_sub_48_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -32459,13 +33311,20 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -32638,8 +33497,13 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -32653,11 +33517,19 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -34083,8 +34955,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -34098,11 +34975,19 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -34507,8 +35392,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -34522,11 +35412,19 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -34793,8 +35691,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_ "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -34839,11 +35742,17 @@ SP_NOINLINE static void sp_3072_mont_sqr_48(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -34924,8 +35833,13 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0xc0\n\t" "blt L_sp_3072_mul_d_48_word_%=\n\t" "str r3, [%[r], #192]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -34937,11 +35851,17 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -36477,8 +37397,13 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r5}\n\t" "str r3, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -36494,11 +37419,17 @@ static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -36536,8 +37467,13 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -36553,11 +37489,17 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -36674,8 +37616,13 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -36689,10 +37636,16 @@ static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -37249,8 +38202,13 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -37660,13 +38618,20 @@ static void sp_3072_mont_norm_96(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -37685,8 +38650,13 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x180\n\t" "blt L_sp_3072_cond_sub_96_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -37701,13 +38671,20 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -38048,8 +39025,13 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -38063,11 +39045,19 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -40885,8 +41875,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -40900,11 +41895,19 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -41693,8 +42696,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -41708,11 +42716,19 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -42219,8 +43235,13 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_ "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -42265,11 +43286,19 @@ SP_NOINLINE static void sp_3072_mont_sqr_96(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -42288,8 +43317,13 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], lr\n\t" "bne L_sp_3072_sub_96_word_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -42303,11 +43337,19 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -42479,8 +43521,13 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -42497,11 +43544,17 @@ static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digi * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -42539,8 +43592,13 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -42556,11 +43614,17 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -42677,8 +43741,13 @@ static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -42796,10 +43865,16 @@ static void sp_3072_mask_96(sp_digit* r, const sp_digit* a, sp_digit m) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -42808,9 +43883,8 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) "mov r3, #-1\n\t" #ifdef WOLFSSL_SP_SMALL #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r4, #0x1\n\t" - "lsl r4, r4, #8\n\t" - "add r4, r4, #0x7c\n\t" + "mov r4, #0x7c\n\t" + "orr r4, r4, #0x100\n\t" #else "mov r4, #0x17c\n\t" #endif @@ -43890,8 +44964,13 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -44423,13 +45502,20 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -44448,8 +45534,13 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, "cmp r12, #0xc0\n\t" "blt L_sp_3072_cond_add_48_words_%=\n\t" "mov %[r], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -44464,13 +45555,20 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r8, #0\n\t" @@ -44643,8 +45741,13 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, "adcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "adc %[r], r8, r8\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; @@ -44965,11 +46068,17 @@ int sp_ModExp_3072(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef WOLFSSL_HAVE_SP_DH #ifdef HAVE_FFDHE_3072 +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_3072_lshift_96(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_3072_lshift_96(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #31\n\t" @@ -45549,8 +46658,13 @@ static void sp_3072_lshift_96(sp_digit* r_p, const sp_digit* a_p, byte n_p) "orr r4, r4, r3\n\t" "str r6, [%[r]]\n\t" "str r4, [%[r], #4]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -45838,9 +46952,9 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -45978,10 +47092,16 @@ static void sp_4096_to_bin_128(sp_digit* r, byte* a) * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -46209,8 +47329,13 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -46222,12 +47347,19 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -46456,8 +47588,13 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -46546,12 +47683,19 @@ SP_NOINLINE static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -46571,8 +47715,13 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, "cmp %[a], r12\n\t" "bne L_sp_4096_add_128_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -46586,10 +47735,16 @@ static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -46608,8 +47763,13 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_4096_sub_in_pkace_128_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -46624,11 +47784,18 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x400\n\t" @@ -46811,8 +47978,13 @@ static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_4096_mul_128_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -46823,10 +47995,16 @@ static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_4096_sqr_128(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x400\n\t" @@ -46969,8 +48147,13 @@ static void sp_4096_sqr_128(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_4096_sqr_128_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -47004,11 +48187,17 @@ static void sp_4096_mont_setup(const sp_digit* a, sp_digit* rho) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -47089,8 +48278,13 @@ static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x200\n\t" "blt L_sp_4096_mul_d_128_word_%=\n\t" "str r3, [%[r], #512]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -47102,11 +48296,17 @@ static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -51202,8 +52402,13 @@ static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r4}\n\t" "str r5, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -51234,13 +52439,20 @@ static void sp_4096_mont_norm_128(sp_digit* r, const sp_digit* m) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -51259,8 +52471,13 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x200\n\t" "blt L_sp_4096_cond_sub_128_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -51275,13 +52492,20 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -51734,8 +52958,13 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -51749,11 +52978,19 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -55499,8 +56736,13 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -55514,11 +56756,19 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -56563,8 +57813,13 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -56578,11 +57833,19 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -57249,8 +58512,13 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -57295,12 +58563,19 @@ SP_NOINLINE static void sp_4096_mont_sqr_128(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -57319,8 +58594,13 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, "cmp %[a], lr\n\t" "bne L_sp_4096_sub_128_word_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -57334,12 +58614,19 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -57567,8 +58854,13 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -57585,11 +58877,17 @@ static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -57627,8 +58925,13 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -57644,11 +58947,17 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -57765,8 +59074,13 @@ static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -57884,10 +59198,16 @@ static void sp_4096_mask_128(sp_digit* r, const sp_digit* a, sp_digit m) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -57896,9 +59216,8 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) "mov r3, #-1\n\t" #ifdef WOLFSSL_SP_SMALL #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r4, #0x1\n\t" - "lsl r4, r4, #8\n\t" - "add r4, r4, #0xfc\n\t" + "mov r4, #0xfc\n\t" + "orr r4, r4, #0x100\n\t" #else "mov r4, #0x1fc\n\t" #endif @@ -59330,8 +60649,13 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -59863,13 +61187,20 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -59888,8 +61219,13 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, "cmp r12, #0x100\n\t" "blt L_sp_4096_cond_add_64_words_%=\n\t" "mov %[r], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -59904,13 +61240,20 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r8, #0\n\t" @@ -60139,8 +61482,13 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, "adcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "adc %[r], r8, r8\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; @@ -60461,11 +61809,17 @@ int sp_ModExp_4096(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef WOLFSSL_HAVE_SP_DH #ifdef HAVE_FFDHE_4096 +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_4096_lshift_128(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_4096_lshift_128(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #31\n\t" @@ -61237,8 +62591,13 @@ static void sp_4096_lshift_128(sp_digit* r_p, const sp_digit* a_p, byte n_p) "orr r5, r5, r3\n\t" "str r4, [%[r]]\n\t" "str r5, [%[r], #4]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -61531,11 +62890,18 @@ static const sp_digit p256_b[8] = { * a A single precision integer. * b A single precision integer. */ -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x40\n\t" @@ -61718,8 +63084,13 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_256_mul_8_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -61733,11 +63104,18 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p * a A single precision integer. * b A single precision integer. */ -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -63715,8 +65093,13 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3, r4, r5, r6}\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -63729,11 +65112,18 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p * a A single precision integer. * b A single precision integer. */ -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #36\n\t" @@ -64069,8 +65459,13 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "sub %[r], %[r], #32\n\t" "stm %[r], {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #36\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -64083,11 +65478,18 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p * a A single precision integer. * b A single precision integer. */ -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #44\n\t" @@ -64201,8 +65603,13 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p "ldm sp, {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "stm lr, {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr" ); @@ -64216,10 +65623,16 @@ static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x40\n\t" @@ -64362,8 +65775,13 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_256_sqr_8_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -64376,10 +65794,16 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -65574,8 +66998,13 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2, r3, r4, r8}\n\t" "stm %[r]!, {r2, r3, r4, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -65587,10 +67016,16 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -65818,8 +67253,13 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "sub %[r], %[r], #32\n\t" "stm %[r], {r3, r4, r5, r6, r7, r8, r9, r10}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -65831,10 +67271,16 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #32\n\t" @@ -65935,8 +67381,13 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) "ldm sp, {r0, r1, r2, r3, r4, r5, r6}\n\t" "stm lr, {r0, r1, r2, r3, r4, r5, r6}\n\t" "add sp, sp, #32\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); @@ -65951,11 +67402,18 @@ static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -65975,8 +67433,13 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "cmp %[a], r12\n\t" "bne L_sp_256_add_8_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -65990,11 +67453,18 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -66013,8 +67483,13 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -66027,11 +67502,18 @@ static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* * a The number to convert. * m The modulus (prime). */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#else +static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #24\n\t" @@ -66250,12 +67732,21 @@ static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, "stm %[r], {r2, r3, r4, r5, r6, r7, r8, lr}\n\t" "mov %[r], #0\n\t" "add sp, sp, #24\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "r10" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ return (word32)(size_t)r; } @@ -66464,12 +67955,19 @@ static int sp_256_point_to_ecc_point_8(const sp_point_256* p, ecc_point* pm) * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -68567,13 +70065,26 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #64]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r12" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #elif defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) @@ -68586,12 +70097,19 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -69046,13 +70564,26 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #64]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #else @@ -69065,12 +70596,19 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x4c\n\t" @@ -69303,13 +70841,26 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #68]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x4c\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #endif @@ -69321,11 +70872,18 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -70503,13 +72061,26 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #64]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r12", "r8", "r9", "r10", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #elif defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) @@ -70520,11 +72091,18 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -70871,13 +72449,26 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #64]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #else @@ -70888,11 +72479,18 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co * m Modulus (prime). * mp Montgomery multiplier. */ -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -71113,13 +72711,26 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, co "ldr %[r], [sp, #64]\n\t" "stm %[r], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #endif @@ -71226,10 +72837,16 @@ static void sp_256_mont_inv_8(sp_digit* r, const sp_digit* a, sp_digit* td) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -71346,8 +72963,13 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -71368,13 +72990,20 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -71393,8 +73022,13 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #32\n\t" "blt L_sp_256_cond_sub_8_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -71409,13 +73043,20 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -71448,8 +73089,13 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -71466,11 +73112,19 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -71736,8 +73390,13 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -71751,11 +73410,19 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -71840,8 +73507,13 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -71855,11 +73527,19 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -71926,8 +73606,13 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -71942,9 +73627,17 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -72078,13 +73771,26 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, "ldr %[a], [sp, #64]\n\t" "stm %[a], {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" "add sp, sp, #0x44\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4) @@ -72094,12 +73800,19 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -72365,8 +74078,13 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -72380,12 +74098,19 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -72470,8 +74195,13 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -72485,12 +74215,19 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -72557,8 +74294,13 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -72614,12 +74356,19 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -72657,12 +74406,21 @@ static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r11, r11, lr, lsr #31\n\t" "sbc r12, r12, lr\n\t" "stm %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Double a Montgomery form number (r = a + a % m). @@ -72671,10 +74429,17 @@ static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a Number to double in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #0\n\t" @@ -72708,12 +74473,21 @@ static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r10, r10, r2, lsr #31\n\t" "sbc r11, r11, r2\n\t" "stm %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Triple a Montgomery form number (r = a + a + a % m). @@ -72722,10 +74496,17 @@ static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a Number to triple in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -72791,12 +74572,21 @@ static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r10, r10, r12, lsr #31\n\t" "sbc r11, r11, r12\n\t" "stm %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "r12" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Subtract two Montgomery form numbers (r = a - b % m). @@ -72806,12 +74596,19 @@ static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -72847,12 +74644,21 @@ static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "adcs r11, r11, lr, lsr #31\n\t" "adc r12, r12, lr\n\t" "stm %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Divide the number by 2 mod the modulus (prime). (r = a / 2 % m) @@ -72861,11 +74667,19 @@ static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a Number to divide. * m Modulus (prime). */ -static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r4, r5, r6, r7}\n\t" @@ -72925,8 +74739,13 @@ static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, const sp_digi "orr r10, r10, r7, lsl #31\n\t" "orr r11, r11, r3, lsl #31\n\t" "stm %[r], {r8, r9, r10, r11}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3" ); @@ -76434,9 +78253,15 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, * * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_add_one_8(sp_digit* a_p) +#else +static void sp_256_add_one_8(sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r1, r2, r3, r4}\n\t" @@ -76451,8 +78276,13 @@ static void sp_256_add_one_8(sp_digit* a_p) "adcs r3, r3, #0\n\t" "adcs r4, r4, #0\n\t" "stm %[a]!, {r1, r2, r3, r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -76491,9 +78321,9 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -76842,10 +78672,16 @@ int sp_ecc_secret_gen_256_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -76864,8 +78700,13 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_256_sub_in_pkace_8_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -76878,10 +78719,16 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -76899,8 +78746,13 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -76914,11 +78766,17 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -76999,8 +78857,13 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #32\n\t" "blt L_sp_256_mul_d_8_word_%=\n\t" "str r3, [%[r], #32]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -77012,11 +78875,17 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -77272,8 +79141,13 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r4}\n\t" "str r5, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -77289,11 +79163,17 @@ static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -77331,8 +79211,13 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -77348,11 +79233,17 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -77469,8 +79360,13 @@ static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -78130,11 +80026,18 @@ int sp_ecc_sign_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -78153,8 +80056,13 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "cmp %[a], lr\n\t" "bne L_sp_256_sub_8_word_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -78168,11 +80076,18 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -78190,18 +80105,29 @@ static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -78239,8 +80165,7 @@ static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) "strd r8, r9, [%[r], #24]\n\t" #endif #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "ldr r2, [%[a]]\n\t" - "ldr r3, [%[a], #4]\n\t" + "ldm r1, {r2, r3}\n\t" #else "ldrd r2, r3, [%[a]]\n\t" #endif @@ -78259,8 +80184,7 @@ static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) "orr r8, r8, r5, lsl #31\n\t" "orr r9, r9, r12, lsl #31\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "str r6, [%[r]]\n\t" - "str r7, [%[r], #4]\n\t" + "stm r0, {r6, r7}\n\t" #else "strd r6, r7, [%[r]]\n\t" #endif @@ -78270,8 +80194,13 @@ static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) #else "strd r8, r9, [%[r], #8]\n\t" #endif +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr", "r10" ); @@ -78283,11 +80212,18 @@ static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) * a Number to divide. * m Modulus. */ -static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -78357,8 +80293,13 @@ static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit "orr r10, r10, r7, lsl #31\n\t" "orr r11, r11, r3, lsl #31\n\t" "stm %[r], {r8, r9, r10, r11}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -78400,11 +80341,21 @@ static const byte L_sp_256_num_bits_8_table[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, }; +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_256_num_bits_8(const sp_digit* a_p) +#else +static int sp_256_num_bits_8(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register byte* L_sp_256_num_bits_8_table_c asm ("r1") = (byte*)&L_sp_256_num_bits_8_table; +#else + register byte* L_sp_256_num_bits_8_table_c = + (byte*)&L_sp_256_num_bits_8_table; + +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, %[L_sp_256_num_bits_8_table]\n\t" @@ -78716,30 +80667,36 @@ static int sp_256_num_bits_8(const sp_digit* a_p) "\n" "L_sp_256_num_bits_8_9_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [L_sp_256_num_bits_8_table] "+r" (L_sp_256_num_bits_8_table_c) : +#else + : + : [a] "r" (a), + [L_sp_256_num_bits_8_table] "r" (L_sp_256_num_bits_8_table_c) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; } #else +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_256_num_bits_8(const sp_digit* a_p) +#else +static int sp_256_num_bits_8(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r1, [%[a], #28]\n\t" "cmp r1, #0\n\t" "beq L_sp_256_num_bits_8_7_%=\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x100\n\t" -#endif "clz r12, r1\n\t" "sub r12, r2, r12\n\t" "b L_sp_256_num_bits_8_9_%=\n\t" @@ -78806,8 +80763,13 @@ static int sp_256_num_bits_8(const sp_digit* a_p) "\n" "L_sp_256_num_bits_8_9_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; @@ -79892,11 +81854,18 @@ static const sp_digit p384_b[12] = { * a A single precision integer. * b A single precision integer. */ -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x60\n\t" @@ -80079,8 +82048,13 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_384_mul_12_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -80093,11 +82067,18 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * a A single precision integer. * b A single precision integer. */ -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #48\n\t" @@ -85577,8 +87558,13 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3, r4, r5, r6}\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -85591,10 +87577,16 @@ static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x60\n\t" @@ -85737,8 +87729,13 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_384_sqr_12_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -85750,10 +87747,16 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #48\n\t" @@ -88801,8 +90804,13 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2, r3, r4, r8}\n\t" "stm %[r]!, {r2, r3, r4, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -88816,11 +90824,18 @@ static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -88840,8 +90855,13 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "cmp %[a], r12\n\t" "bne L_sp_384_add_12_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -88855,11 +90875,18 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -88885,8 +90912,13 @@ static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -89198,13 +91230,20 @@ static int sp_384_point_to_ecc_point_12(const sp_point_384* p, ecc_point* pm) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -89223,8 +91262,13 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #48\n\t" "blt L_sp_384_cond_sub_12_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -89239,13 +91283,20 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -89292,8 +91343,13 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -89309,11 +91365,19 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -89695,8 +91759,13 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -89710,11 +91779,19 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -89831,8 +91908,13 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "str r12, [%[a]]\n\t" "str lr, [%[a], #4]\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -89846,11 +91928,19 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -89937,8 +92027,13 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p "str r7, [%[a], #12]\n\t" "str r8, [%[a], #16]\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -90095,10 +92190,16 @@ static void sp_384_mont_inv_12(sp_digit* r, const sp_digit* a, sp_digit* td) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -90259,8 +92360,13 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -90319,13 +92425,20 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register const sp_digit* m asm ("r3") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ sp_digit o; @@ -90339,11 +92452,19 @@ static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a Number to double in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ sp_digit o; @@ -90357,11 +92478,19 @@ static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a Number to triple in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ sp_digit o; @@ -90378,11 +92507,18 @@ static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -90401,8 +92537,13 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "cmp %[a], lr\n\t" "bne L_sp_384_sub_12_word_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -90416,11 +92557,18 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -90445,8 +92593,13 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -90462,13 +92615,20 @@ static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -90487,8 +92647,13 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, "cmp r12, #48\n\t" "blt L_sp_384_cond_add_12_words_%=\n\t" "mov %[r], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -90503,13 +92668,20 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r8, #0\n\t" @@ -90556,8 +92728,13 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, "adcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "adc %[r], r8, r8\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; @@ -90571,13 +92748,20 @@ static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register const sp_digit* m asm ("r3") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ sp_digit o; @@ -90588,10 +92772,16 @@ static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi #ifdef WOLFSSL_SP_SMALL #else #endif /* WOLFSSL_SP_SMALL */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_rshift1_12(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_384_rshift1_12(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3}\n\t" @@ -90640,8 +92830,13 @@ static void sp_384_rshift1_12(sp_digit* r_p, const sp_digit* a_p) "lsr r4, r4, #1\n\t" "str r3, [%[r], #40]\n\t" "str r4, [%[r], #44]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4" ); } @@ -94221,9 +96416,15 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, * * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_add_one_12(sp_digit* a_p) +#else +static void sp_384_add_one_12(sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r1, r2, r3, r4}\n\t" @@ -94244,8 +96445,13 @@ static void sp_384_add_one_12(sp_digit* a_p) "adcs r3, r3, #0\n\t" "adcs r4, r4, #0\n\t" "stm %[a]!, {r1, r2, r3, r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -94284,9 +96490,9 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -94635,10 +96841,16 @@ int sp_ecc_secret_gen_384_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -94657,8 +96869,13 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_384_sub_in_pkace_12_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -94671,10 +96888,16 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -94699,8 +96922,13 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -94714,11 +96942,17 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -94799,8 +97033,13 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #48\n\t" "blt L_sp_384_mul_d_12_word_%=\n\t" "str r3, [%[r], #48]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -94812,11 +97051,17 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -95200,8 +97445,13 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r5}\n\t" "str r3, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -95217,11 +97467,17 @@ static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -95259,8 +97515,13 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -95276,11 +97537,17 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -95397,8 +97664,13 @@ static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -96028,11 +98300,19 @@ int sp_ecc_sign_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * a Number to divide. * m Modulus. */ -static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r4}\n\t" @@ -96074,8 +98354,7 @@ static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "L_sp_384_div2_mod_12_div2_%=: \n\t" "sub %[r], %[r], #48\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "ldr r8, [%[r]]\n\t" - "ldr r9, [%[r], #4]\n\t" + "ldm r0, {r8, r9}\n\t" #else "ldrd r8, r9, [%[r]]\n\t" #endif @@ -96125,8 +98404,13 @@ static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digi "orr r10, r10, r3, lsl #31\n\t" "str r9, [%[r], #40]\n\t" "str r10, [%[r], #44]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -96168,11 +98452,21 @@ static const byte L_sp_384_num_bits_12_table[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, }; +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_384_num_bits_12(const sp_digit* a_p) +#else +static int sp_384_num_bits_12(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register byte* L_sp_384_num_bits_12_table_c asm ("r1") = (byte*)&L_sp_384_num_bits_12_table; +#else + register byte* L_sp_384_num_bits_12_table_c = + (byte*)&L_sp_384_num_bits_12_table; + +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, %[L_sp_384_num_bits_12_table]\n\t" @@ -96183,9 +98477,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_11_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x78\n\t" + "mov r2, #0x78\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x178\n\t" #endif @@ -96199,9 +98492,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_11_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x70\n\t" + "mov r2, #0x70\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x170\n\t" #endif @@ -96215,9 +98507,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_11_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x68\n\t" + "mov r2, #0x68\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x168\n\t" #endif @@ -96228,9 +98519,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "L_sp_384_num_bits_12_11_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x60\n\t" + "mov r2, #0x60\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x160\n\t" #endif @@ -96246,9 +98536,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_10_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x58\n\t" + "mov r2, #0x58\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x158\n\t" #endif @@ -96262,9 +98551,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_10_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x50\n\t" + "mov r2, #0x50\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x150\n\t" #endif @@ -96278,9 +98566,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_10_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x48\n\t" + "mov r2, #0x48\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x148\n\t" #endif @@ -96291,9 +98578,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "L_sp_384_num_bits_12_10_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x40\n\t" + "mov r2, #0x40\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x140\n\t" #endif @@ -96309,9 +98595,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_9_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x38\n\t" + "mov r2, #0x38\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x138\n\t" #endif @@ -96325,9 +98610,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_9_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x30\n\t" + "mov r2, #0x30\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x130\n\t" #endif @@ -96341,9 +98625,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_9_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x28\n\t" + "mov r2, #0x28\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x128\n\t" #endif @@ -96354,9 +98637,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "L_sp_384_num_bits_12_9_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x20\n\t" + "mov r2, #0x20\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x120\n\t" #endif @@ -96372,9 +98654,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_8_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x18\n\t" + "mov r2, #0x18\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x118\n\t" #endif @@ -96388,9 +98669,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_8_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x10\n\t" + "mov r2, #0x10\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x110\n\t" #endif @@ -96404,9 +98684,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_384_num_bits_12_8_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x8\n\t" + "mov r2, #0x8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x108\n\t" #endif @@ -96416,13 +98695,7 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "\n" "L_sp_384_num_bits_12_8_1_%=: \n\t" "and r3, r1, #0xff\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x100\n\t" -#endif "ldrb r12, [lr, r3]\n\t" "add r12, r2, r12\n\t" "b L_sp_384_num_bits_12_13_%=\n\t" @@ -96736,27 +99009,38 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "\n" "L_sp_384_num_bits_12_13_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [L_sp_384_num_bits_12_table] "+r" (L_sp_384_num_bits_12_table_c) : +#else + : + : [a] "r" (a), + [L_sp_384_num_bits_12_table] "r" (L_sp_384_num_bits_12_table_c) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; } #else +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_384_num_bits_12(const sp_digit* a_p) +#else +static int sp_384_num_bits_12(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r1, [%[a], #44]\n\t" "cmp r1, #0\n\t" "beq L_sp_384_num_bits_12_11_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x80\n\t" + "mov r2, #0x80\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x180\n\t" #endif @@ -96769,9 +99053,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_384_num_bits_12_10_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x60\n\t" + "mov r2, #0x60\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x160\n\t" #endif @@ -96784,9 +99067,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_384_num_bits_12_9_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x40\n\t" + "mov r2, #0x40\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x140\n\t" #endif @@ -96799,9 +99081,8 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_384_num_bits_12_8_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x20\n\t" + "mov r2, #0x20\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x120\n\t" #endif @@ -96813,13 +99094,7 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "ldr r1, [%[a], #28]\n\t" "cmp r1, #0\n\t" "beq L_sp_384_num_bits_12_7_%=\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x100\n\t" -#endif "clz r12, r1\n\t" "sub r12, r2, r12\n\t" "b L_sp_384_num_bits_12_13_%=\n\t" @@ -96886,8 +99161,13 @@ static int sp_384_num_bits_12(const sp_digit* a_p) "\n" "L_sp_384_num_bits_12_13_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; @@ -98018,11 +100298,18 @@ static const sp_digit p521_b[17] = { * a A single precision integer. * b A single precision integer. */ -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x88\n\t" @@ -98208,8 +100495,13 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_521_mul_17_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -98222,11 +100514,18 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * a A single precision integer. * b A single precision integer. */ -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -109225,8 +111524,13 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3}\n\t" "stm %[r]!, {r3}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -109239,10 +111543,16 @@ static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_ * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x88\n\t" @@ -109388,8 +111698,13 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_521_sqr_17_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -109401,10 +111716,16 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -115261,8 +117582,13 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2}\n\t" "stm %[r]!, {r2}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -115276,11 +117602,18 @@ static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -115306,8 +117639,13 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r]!, {r4}\n\t" "mov r4, #0\n\t" "adc %[r], r4, #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -115321,11 +117659,18 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -115362,8 +117707,13 @@ static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "stm %[r]!, {r3}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -115592,13 +117942,20 @@ static int sp_521_point_to_ecc_point_17(const sp_point_521* p, ecc_point* pm) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -115617,8 +117974,13 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x44\n\t" "blt L_sp_521_cond_sub_17_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -115633,13 +117995,20 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -115705,8 +118074,13 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, "sbcs r4, r4, r6\n\t" "str r4, [%[r]]\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -115719,9 +118093,17 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x44\n\t" @@ -115793,9 +118175,8 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p "ldm %[a], {r1, r2, r3, r4, r5}\n\t" "ldm sp!, {r7, r8, r9, r10, r11}\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov lr, #0x1\n\t" - "lsl lr, lr, #8\n\t" - "add lr, lr, #0xff\n\t" + "mov lr, #0xff\n\t" + "orr lr, lr, #0x100\n\t" #else "mov lr, #0x1ff\n\t" #endif @@ -115833,13 +118214,26 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p "adcs r7, r7, #0\n\t" "adcs r8, r8, #0\n\t" "stm %[a]!, {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)mp_p; +#else + (void)mp; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4) @@ -115849,12 +118243,19 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -115872,9 +118273,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "cmp r9, #0x40\n\t" "bne L_sp_521_mont_reduce_order_17_nomask_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r7, #0x1\n\t" - "lsl r7, r7, #8\n\t" - "add r7, r7, #0xff\n\t" + "mov r7, #0xff\n\t" + "orr r7, r7, #0x100\n\t" #else "mov r7, #0x1ff\n\t" #endif @@ -116464,8 +118864,13 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "lsr r3, r4, #9\n\t" "add %[a], %[a], #4\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -116479,12 +118884,19 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -116500,9 +118912,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "cmp r9, #0x40\n\t" "bne L_sp_521_mont_reduce_order_17_nomask_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r7, #0x1\n\t" - "lsl r7, r7, #8\n\t" - "add r7, r7, #0xff\n\t" + "mov r7, #0xff\n\t" + "orr r7, r7, #0x100\n\t" #else "mov r7, #0x1ff\n\t" #endif @@ -116724,8 +119135,13 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "lsr r3, r4, #9\n\t" "add %[a], %[a], #4\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -116739,12 +119155,19 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, + const sp_digit* m, sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -116762,9 +119185,8 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "cmp r12, #0x40\n\t" "bne L_sp_521_mont_reduce_order_17_nomask_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r10, #0x1\n\t" - "lsl r10, r10, #8\n\t" - "add r10, r10, #0xff\n\t" + "mov r10, #0xff\n\t" + "orr r10, r10, #0x100\n\t" #else "mov r10, #0x1ff\n\t" #endif @@ -116939,8 +119361,13 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digi "lsr lr, r10, #9\n\t" "add %[a], %[a], #4\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -117094,10 +119521,16 @@ static void sp_521_mont_inv_17(sp_digit* r, const sp_digit* a, sp_digit* td) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -117313,8 +119746,13 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -117373,12 +119811,19 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -117414,9 +119859,8 @@ static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[b]!, {r4}\n\t" "adcs r8, r8, r4\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r12, #0x1\n\t" - "lsl r12, r12, #8\n\t" - "add r12, r12, #0xff\n\t" + "mov r12, #0xff\n\t" + "orr r12, r12, #0x100\n\t" #else "mov r12, #0x1ff\n\t" #endif @@ -117447,12 +119891,21 @@ static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[r], {r4}\n\t" "adcs r4, r4, #0\n\t" "stm %[r]!, {r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Double a Montgomery form number (r = a + a % m). @@ -117461,10 +119914,18 @@ static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a Number to double in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #0\n\t" @@ -117491,9 +119952,8 @@ static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[a]!, {r4}\n\t" "adcs r4, r4, r4\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r3, #0x1\n\t" - "lsl r3, r3, #8\n\t" - "add r3, r3, #0xff\n\t" + "mov r3, #0xff\n\t" + "orr r3, r3, #0x100\n\t" #else "mov r3, #0x1ff\n\t" #endif @@ -117524,12 +119984,21 @@ static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[r], {r4}\n\t" "adcs r4, r4, #0\n\t" "stm %[r]!, {r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Triple a Montgomery form number (r = a + a + a % m). @@ -117538,10 +120007,18 @@ static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a Number to triple in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #0\n\t" @@ -117602,9 +120079,8 @@ static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[a]!, {r8}\n\t" "adcs r4, r4, r8\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r3, #0x1\n\t" - "lsl r3, r3, #8\n\t" - "add r3, r3, #0xff\n\t" + "mov r3, #0xff\n\t" + "orr r3, r3, #0x100\n\t" #else "mov r3, #0x1ff\n\t" #endif @@ -117621,12 +120097,21 @@ static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[r], {r4}\n\t" "adcs r4, r4, #0\n\t" "stm %[r]!, {r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } /* Subtract two Montgomery form numbers (r = a - b % m). @@ -117636,12 +120121,19 @@ static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi * b Number to subtract with in Montgomery form. * m Modulus (prime). */ -static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, - const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -117677,9 +120169,8 @@ static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[b]!, {r4}\n\t" "sbcs r8, r8, r4\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r12, #0x1\n\t" - "lsl r12, r12, #8\n\t" - "add r12, r12, #0xff\n\t" + "mov r12, #0xff\n\t" + "orr r12, r12, #0x100\n\t" #else "mov r12, #0x1ff\n\t" #endif @@ -117711,18 +120202,33 @@ static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "ldm %[r], {r4}\n\t" "sbcs r4, r4, #0\n\t" "stm %[r]!, {r4}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; +#else + (void)m; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ } +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_rshift1_17(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_521_rshift1_17(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3}\n\t" @@ -117791,8 +120297,13 @@ static void sp_521_rshift1_17(sp_digit* r_p, const sp_digit* a_p) "lsr r3, r3, #1\n\t" "str r2, [%[r], #60]\n\t" "str r3, [%[r], #64]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4" ); } @@ -121994,9 +124505,15 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, * * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_add_one_17(sp_digit* a_p) +#else +static void sp_521_add_one_17(sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r1, r2, r3, r4}\n\t" @@ -122026,8 +124543,13 @@ static void sp_521_add_one_17(sp_digit* a_p) "ldm %[a], {r1}\n\t" "adcs r1, r1, #0\n\t" "stm %[a]!, {r1}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -122066,9 +124588,9 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -122410,17 +124932,22 @@ int sp_ecc_secret_gen_521_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, #endif /* HAVE_ECC_DHE */ #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #32\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "ldr r4, [%[a]]\n\t" - "ldr r5, [%[a], #4]\n\t" + "ldm r1, {r4, r5}\n\t" #else "ldrd r4, r5, [%[a]]\n\t" #endif @@ -122509,8 +125036,13 @@ static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) #else "strd r4, r5, [%[r], #60]\n\t" #endif +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -122519,11 +125051,17 @@ static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_lshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #31\n\t" @@ -122629,17 +125167,28 @@ static void sp_521_lshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) "orr r5, r5, r3\n\t" "str r4, [%[r]]\n\t" "str r5, [%[r], #4]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) +#else +static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register byte n asm ("r2") = (byte)n_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "rsb r12, %[n], #31\n\t" @@ -122847,8 +125396,13 @@ static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) "orr r6, r6, r3\n\t" "str r5, [%[r]]\n\t" "str r6, [%[r], #4]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : +#else + : + : [r] "r" (r), [a] "r" (a), [n] "r" (n) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r3", "r12" ); } @@ -122859,10 +125413,16 @@ static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -122886,8 +125446,13 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) "sbcs r2, r2, r6\n\t" "stm %[a]!, {r2}\n\t" "sbc %[a], %[a], %[a]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -122900,10 +125465,16 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -122939,8 +125510,13 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) "sbcs r2, r2, r6\n\t" "stm %[a]!, {r2}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -122954,11 +125530,17 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -123039,8 +125621,13 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x44\n\t" "blt L_sp_521_mul_d_17_word_%=\n\t" "str r3, [%[r], #68]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -123052,11 +125639,17 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -123600,8 +126193,13 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r4}\n\t" "str r5, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -123617,11 +126215,17 @@ static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -123659,8 +126263,13 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -123676,11 +126285,17 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -123797,8 +126412,13 @@ static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -124459,11 +127079,18 @@ int sp_ecc_sign_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -124487,8 +127114,13 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r3, r3, r7\n\t" "stm %[r]!, {r3}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "lr" ); @@ -124502,11 +127134,18 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -124542,8 +127181,13 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit "sbcs r3, r3, r7\n\t" "stm %[r]!, {r3}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -124556,11 +127200,19 @@ static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit * a Number to divide. * m Modulus. */ -static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) +#else +static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r4}\n\t" @@ -124617,8 +127269,7 @@ static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "L_sp_521_div2_mod_17_div2_%=: \n\t" "sub %[r], %[r], #0x44\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "ldr r8, [%[r]]\n\t" - "ldr r9, [%[r], #4]\n\t" + "ldm r0, {r8, r9}\n\t" #else "ldrd r8, r9, [%[r]]\n\t" #endif @@ -124688,8 +127339,13 @@ static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digi "orr r9, r9, r3, lsl #31\n\t" "str r8, [%[r], #60]\n\t" "str r9, [%[r], #64]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -124731,11 +127387,21 @@ static const byte L_sp_521_num_bits_17_table[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, }; +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_521_num_bits_17(const sp_digit* a_p) +#else +static int sp_521_num_bits_17(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register byte* L_sp_521_num_bits_17_table_c asm ("r1") = (byte*)&L_sp_521_num_bits_17_table; +#else + register byte* L_sp_521_num_bits_17_table_c = + (byte*)&L_sp_521_num_bits_17_table; + +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, %[L_sp_521_num_bits_17_table]\n\t" @@ -124746,9 +127412,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_16_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x18\n\t" + "mov r2, #0x18\n\t" + "orr r2, r2, #0x200\n\t" #else "mov r2, #0x218\n\t" #endif @@ -124762,9 +127427,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_16_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x10\n\t" + "mov r2, #0x10\n\t" + "orr r2, r2, #0x200\n\t" #else "mov r2, #0x210\n\t" #endif @@ -124778,9 +127442,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_16_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x8\n\t" + "mov r2, #0x8\n\t" + "orr r2, r2, #0x200\n\t" #else "mov r2, #0x208\n\t" #endif @@ -124790,13 +127453,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "\n" "L_sp_521_num_bits_17_16_1_%=: \n\t" "and r3, r1, #0xff\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x200\n\t" -#endif "ldrb r12, [lr, r3]\n\t" "add r12, r2, r12\n\t" "b L_sp_521_num_bits_17_18_%=\n\t" @@ -124809,9 +127466,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_15_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xf8\n\t" + "mov r2, #0xf8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1f8\n\t" #endif @@ -124825,9 +127481,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_15_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xf0\n\t" + "mov r2, #0xf0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1f0\n\t" #endif @@ -124841,9 +127496,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_15_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xe8\n\t" + "mov r2, #0xe8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1e8\n\t" #endif @@ -124854,9 +127508,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_15_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xe0\n\t" + "mov r2, #0xe0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1e0\n\t" #endif @@ -124872,9 +127525,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_14_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xd8\n\t" + "mov r2, #0xd8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1d8\n\t" #endif @@ -124888,9 +127540,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_14_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xd0\n\t" + "mov r2, #0xd0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1d0\n\t" #endif @@ -124904,9 +127555,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_14_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xc8\n\t" + "mov r2, #0xc8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1c8\n\t" #endif @@ -124917,9 +127567,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_14_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xc0\n\t" + "mov r2, #0xc0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1c0\n\t" #endif @@ -124935,9 +127584,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_13_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xb8\n\t" + "mov r2, #0xb8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1b8\n\t" #endif @@ -124951,9 +127599,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_13_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xb0\n\t" + "mov r2, #0xb0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1b0\n\t" #endif @@ -124967,9 +127614,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_13_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xa8\n\t" + "mov r2, #0xa8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1a8\n\t" #endif @@ -124980,9 +127626,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_13_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xa0\n\t" + "mov r2, #0xa0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1a0\n\t" #endif @@ -124998,9 +127643,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_12_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x98\n\t" + "mov r2, #0x98\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x198\n\t" #endif @@ -125014,9 +127658,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_12_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x90\n\t" + "mov r2, #0x90\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x190\n\t" #endif @@ -125030,9 +127673,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_12_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x88\n\t" + "mov r2, #0x88\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x188\n\t" #endif @@ -125043,9 +127685,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_12_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x80\n\t" + "mov r2, #0x80\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x180\n\t" #endif @@ -125061,9 +127702,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_11_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x78\n\t" + "mov r2, #0x78\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x178\n\t" #endif @@ -125077,9 +127717,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_11_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x70\n\t" + "mov r2, #0x70\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x170\n\t" #endif @@ -125093,9 +127732,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_11_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x68\n\t" + "mov r2, #0x68\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x168\n\t" #endif @@ -125106,9 +127744,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_11_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x60\n\t" + "mov r2, #0x60\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x160\n\t" #endif @@ -125124,9 +127761,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_10_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x58\n\t" + "mov r2, #0x58\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x158\n\t" #endif @@ -125140,9 +127776,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_10_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x50\n\t" + "mov r2, #0x50\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x150\n\t" #endif @@ -125156,9 +127791,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_10_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x48\n\t" + "mov r2, #0x48\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x148\n\t" #endif @@ -125169,9 +127803,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_10_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x40\n\t" + "mov r2, #0x40\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x140\n\t" #endif @@ -125187,9 +127820,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_9_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x38\n\t" + "mov r2, #0x38\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x138\n\t" #endif @@ -125203,9 +127835,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_9_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x30\n\t" + "mov r2, #0x30\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x130\n\t" #endif @@ -125219,9 +127850,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_9_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x28\n\t" + "mov r2, #0x28\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x128\n\t" #endif @@ -125232,9 +127862,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "L_sp_521_num_bits_17_9_1_%=: \n\t" "and r3, r1, #0xff\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x20\n\t" + "mov r2, #0x20\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x120\n\t" #endif @@ -125250,9 +127879,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_8_3_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x18\n\t" + "mov r2, #0x18\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x118\n\t" #endif @@ -125266,9 +127894,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_8_2_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x10\n\t" + "mov r2, #0x10\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x110\n\t" #endif @@ -125282,9 +127909,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r3, #0\n\t" "beq L_sp_521_num_bits_17_8_1_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x8\n\t" + "mov r2, #0x8\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x108\n\t" #endif @@ -125294,13 +127920,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "\n" "L_sp_521_num_bits_17_8_1_%=: \n\t" "and r3, r1, #0xff\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x100\n\t" -#endif "ldrb r12, [lr, r3]\n\t" "add r12, r2, r12\n\t" "b L_sp_521_num_bits_17_18_%=\n\t" @@ -125614,27 +128234,38 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "\n" "L_sp_521_num_bits_17_18_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [L_sp_521_num_bits_17_table] "+r" (L_sp_521_num_bits_17_table_c) : +#else + : + : [a] "r" (a), + [L_sp_521_num_bits_17_table] "r" (L_sp_521_num_bits_17_table_c) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; } #else +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static int sp_521_num_bits_17(const sp_digit* a_p) +#else +static int sp_521_num_bits_17(const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r1, [%[a], #64]\n\t" "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_16_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x20\n\t" + "mov r2, #0x20\n\t" + "orr r2, r2, #0x200\n\t" #else "mov r2, #0x220\n\t" #endif @@ -125646,13 +128277,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "ldr r1, [%[a], #60]\n\t" "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_15_%=\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x2\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x200\n\t" -#endif "clz r12, r1\n\t" "sub r12, r2, r12\n\t" "b L_sp_521_num_bits_17_18_%=\n\t" @@ -125662,9 +128287,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_14_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xe0\n\t" + "mov r2, #0xe0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1e0\n\t" #endif @@ -125677,9 +128301,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_13_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xc0\n\t" + "mov r2, #0xc0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1c0\n\t" #endif @@ -125692,9 +128315,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_12_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0xa0\n\t" + "mov r2, #0xa0\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x1a0\n\t" #endif @@ -125707,9 +128329,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_11_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x80\n\t" + "mov r2, #0x80\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x180\n\t" #endif @@ -125722,9 +128343,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_10_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x60\n\t" + "mov r2, #0x60\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x160\n\t" #endif @@ -125737,9 +128357,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_9_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x40\n\t" + "mov r2, #0x40\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x140\n\t" #endif @@ -125752,9 +128371,8 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_8_%=\n\t" #if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x20\n\t" + "mov r2, #0x20\n\t" + "orr r2, r2, #0x100\n\t" #else "mov r2, #0x120\n\t" #endif @@ -125766,13 +128384,7 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "ldr r1, [%[a], #28]\n\t" "cmp r1, #0\n\t" "beq L_sp_521_num_bits_17_7_%=\n\t" -#if defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 7) - "mov r2, #0x1\n\t" - "lsl r2, r2, #8\n\t" - "add r2, r2, #0x0\n\t" -#else "mov r2, #0x100\n\t" -#endif "clz r12, r1\n\t" "sub r12, r2, r12\n\t" "b L_sp_521_num_bits_17_18_%=\n\t" @@ -125839,8 +128451,13 @@ static int sp_521_num_bits_17(const sp_digit* a_p) "\n" "L_sp_521_num_bits_17_18_%=: \n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a) : +#else + : + : [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r1", "r2", "r3", "r12", "lr" ); return (word32)(size_t)a; @@ -126854,11 +129471,18 @@ typedef struct sp_point_1024 { * a A single precision integer. * b A single precision integer. */ -static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x40\n\t" @@ -136600,8 +139224,13 @@ static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r5, r6}\n\t" "ldm sp!, {r3, r4, r5, r6}\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12" ); @@ -136612,10 +139241,16 @@ static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x40\n\t" @@ -141833,8 +144468,13 @@ static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r2, r3, r4, r8}\n\t" "ldm sp!, {r2, r3, r4, r8}\n\t" "stm %[r]!, {r2, r3, r4, r8}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12" ); @@ -141846,11 +144486,19 @@ static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -141883,8 +144531,13 @@ static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -141895,10 +144548,16 @@ static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer and result. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3, r4, r5}\n\t" @@ -141958,8 +144617,13 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "sbcs r5, r5, r9\n\t" "stm %[a]!, {r2, r3, r4, r5}\n\t" "sbc %[a], r9, r9\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; @@ -141971,11 +144635,19 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -142036,8 +144708,13 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "stm %[r]!, {r3, r4, r5, r6}\n\t" "mov %[r], #0\n\t" "adc %[r], %[r], #0\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -142118,11 +144795,19 @@ SP_NOINLINE static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r3, r4, r5, r6}\n\t" @@ -142154,8 +144839,13 @@ static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digi "sbcs r6, r6, r10\n\t" "stm %[r]!, {r3, r4, r5, r6}\n\t" "sbc %[r], r6, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; @@ -142204,11 +144894,18 @@ SP_NOINLINE static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) * a A single precision integer. * b A single precision integer. */ -static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x100\n\t" @@ -142391,8 +145088,13 @@ static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_1024_mul_32_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -142403,10 +145105,16 @@ static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b * r A single precision integer. * a A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_sqr_32(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "sub sp, sp, #0x100\n\t" @@ -142549,8 +145257,13 @@ static void sp_1024_sqr_32(sp_digit* r_p, const sp_digit* a_p) "stm %[r]!, {r3, r4, r6, r7, r8, r9, r10, r11}\n\t" "subs r5, r5, #32\n\t" "bgt L_sp_1024_sqr_32_store_%=\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11" ); @@ -142648,10 +145361,16 @@ static const sp_point_1024 p1024_base = { * a A single precision integer. * b A single precision integer. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +#else +static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -142670,8 +145389,13 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) "cmp %[a], lr\n\t" "bne L_sp_1024_sub_in_pkace_32_word_%=\n\t" "mov %[a], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r12", "lr" ); @@ -142688,13 +145412,20 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r6, #0\n\t" @@ -142713,8 +145444,13 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, "cmp lr, #0x80\n\t" "blt L_sp_1024_cond_sub_32_words_%=\n\t" "mov %[r], r12\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -142729,13 +145465,20 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to subtract. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -142852,8 +145595,13 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, "sbcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "sbc %[r], lr, lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7" ); return (word32)(size_t)r; @@ -142867,11 +145615,19 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, * a A single precision integer. * b A single precision integer. */ -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) +#else +static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r3, #0\n\t" @@ -142891,8 +145647,13 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi "cmp %[a], r12\n\t" "bne L_sp_1024_add_32_word_%=\n\t" "mov %[r], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12" ); @@ -142907,11 +145668,17 @@ static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digi * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -142992,8 +145759,13 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) "cmp r9, #0x80\n\t" "blt L_sp_1024_mul_d_32_word_%=\n\t" "str r3, [%[r], #128]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -143005,11 +145777,17 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * a A single precision integer. * b A single precision digit. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +#else +static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register sp_digit b asm ("r2") = (sp_digit)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* A[0] * B */ @@ -144033,8 +146811,13 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) #endif "stm %[r]!, {r4}\n\t" "str r5, [%[r]]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -144050,11 +146833,17 @@ static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr r6, %[div], #16\n\t" @@ -144092,8 +146881,13 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "sub %[d0], %[d0], r3\n\t" "udiv r3, %[d0], %[div]\n\t" "add %[d1], r4, r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -144109,11 +146903,17 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) * * Note that this is an approximate div. It may give an answer 1 larger. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +#else +static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit d1 asm ("r0") = (sp_digit)d1_p; register sp_digit d0 asm ("r1") = (sp_digit)d0_p; register sp_digit div asm ("r2") = (sp_digit)div_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "lsr lr, %[div], #1\n\t" @@ -144230,8 +147030,13 @@ static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) "subs r6, %[div], r7\n\t" "sbc r6, r6, r6\n\t" "sub %[d1], r3, r6\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : +#else + : + : [d1] "r" (d1), [d0] "r" (d0), [div] "r" (div) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)d1; @@ -144275,10 +147080,16 @@ static void sp_1024_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * return -ve, 0 or +ve if a is less than, equal to or greater than b * respectively. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +#else +static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register const sp_digit* a asm ("r0") = (const sp_digit*)a_p; register const sp_digit* b asm ("r1") = (const sp_digit*)b_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r2, #-1\n\t" @@ -144659,8 +147470,13 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) "eor r2, r2, r3\n\t" #endif /*WOLFSSL_SP_SMALL */ "mov %[a], r2\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [b] "+r" (b) : +#else + : + : [a] "r" (a), [b] "r" (b) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)a; @@ -145002,11 +147818,19 @@ static int sp_1024_point_to_ecc_point_32(const sp_point_1024* p, ecc_point* pm) * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( #if !(defined(WOLFSSL_ARM_ARCH) && (WOLFSSL_ARM_ARCH < 4)) @@ -145973,8 +148797,13 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "sbc r10, r10, r10\n\t" "orr r3, r3, r10\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -145988,11 +148817,19 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldr r11, [%[m]]\n\t" @@ -146274,8 +149111,13 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "sbc r10, r10, r10\n\t" "orr r3, r3, r10\n\t" "mov %[mp], r3\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -146289,11 +149131,19 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ * m The single precision number representing the modulus. * mp The digit representing the negative inverse of m mod 2^n. */ -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) +#else +static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* a asm ("r0") = (sp_digit*)a_p; register const sp_digit* m asm ("r1") = (const sp_digit*)m_p; register sp_digit mp asm ("r2") = (sp_digit)mp_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( /* i = 0 */ @@ -146485,8 +149335,13 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_ "sbc r3, r3, r3\n\t" "orr lr, lr, r3\n\t" "mov %[mp], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : +#else + : + : [a] "r" (a), [m] "r" (m), [mp] "r" (mp) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r3", "r12", "lr", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" ); @@ -146638,13 +149493,20 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, * b Second number to add in Montgomery form. * m Modulus (prime). */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register const sp_digit* m asm ("r3") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -146799,8 +149661,13 @@ static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, "sbcs r6, r6, r10\n\t" "sbc r7, r7, r11\n\t" "stm %[r]!, {r4, r5, r6, r7}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12" ); @@ -146812,12 +149679,19 @@ static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, * a Number to double in Montgomery form. * m Modulus (prime). */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#else +static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -146956,8 +149830,13 @@ static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, "sbcs r6, r6, r10\n\t" "sbc r7, r7, r11\n\t" "stm %[r]!, {r4, r5, r6, r7}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12" ); @@ -146969,12 +149848,19 @@ static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, * a Number to triple in Montgomery form. * m Modulus (prime). */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +#else +static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, + const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* m asm ("r2") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r12, #0\n\t" @@ -147268,8 +150154,13 @@ static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, "sbcs r6, r6, r10\n\t" "sbc r7, r7, r11\n\t" "stm %[r]!, {r4, r5, r6, r7}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12" ); @@ -147282,13 +150173,20 @@ static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, * b Number to subtract with in Montgomery form. * m Modulus (prime). */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +#else +static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register const sp_digit* m asm ("r3") = (const sp_digit*)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a]!, {r4, r5, r6, r7}\n\t" @@ -147437,8 +150335,13 @@ static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, "adcs r6, r6, r10\n\t" "adc r7, r7, r11\n\t" "stm %[r]!, {r4, r5, r6, r7}\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12" ); @@ -147453,13 +150356,20 @@ static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov lr, #0\n\t" @@ -147478,8 +150388,13 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, "cmp r12, #0x80\n\t" "blt L_sp_1024_cond_add_32_words_%=\n\t" "mov %[r], lr\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6" ); return (word32)(size_t)r; @@ -147494,13 +150409,20 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, * b A single precision number to add. * m Mask value to apply. */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +#else +static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; register const sp_digit* b asm ("r2") = (const sp_digit*)b_p; register sp_digit m asm ("r3") = (sp_digit)m_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "mov r8, #0\n\t" @@ -147617,18 +150539,29 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, "adcs r5, r5, r7\n\t" "stm %[r]!, {r4, r5}\n\t" "adc %[r], r8, r8\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : +#else + : + : [r] "r" (r), [a] "r" (a), [b] "r" (b), [m] "r" (m) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r12", "lr", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } #endif /* WOLFSSL_SP_SMALL */ +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG static void sp_1024_rshift1_32(sp_digit* r_p, const sp_digit* a_p) +#else +static void sp_1024_rshift1_32(sp_digit* r, const sp_digit* a) +#endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG register sp_digit* r asm ("r0") = (sp_digit*)r_p; register const sp_digit* a asm ("r1") = (const sp_digit*)a_p; +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ __asm__ __volatile__ ( "ldm %[a], {r2, r3}\n\t" @@ -147757,8 +150690,13 @@ static void sp_1024_rshift1_32(sp_digit* r_p, const sp_digit* a_p) "lsr r3, r3, #1\n\t" "str r2, [%[r], #120]\n\t" "str r3, [%[r], #124]\n\t" +#ifndef WOLFSSL_NO_VAR_ASSIGN_REG : [r] "+r" (r), [a] "+r" (a) : +#else + : + : [r] "r" (r), [a] "r" (a) +#endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ : "memory", "cc", "r2", "r3", "r4" ); } @@ -156725,9 +159663,9 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; diff --git a/src/wolfcrypt/src/sp_arm64.c b/src/wolfcrypt/src/sp_arm64.c index 2825042..3b9bc25 100644 --- a/src/wolfcrypt/src/sp_arm64.c +++ b/src/wolfcrypt/src/sp_arm64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/sp_armthumb.c b/src/wolfcrypt/src/sp_armthumb.c index 894000e..4868f7f 100644 --- a/src/wolfcrypt/src/sp_armthumb.c +++ b/src/wolfcrypt/src/sp_armthumb.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include @@ -114,9 +109,9 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -30305,9 +30300,9 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -83399,9 +83394,9 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -103943,9 +103938,9 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -114852,9 +114847,9 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -129094,9 +129089,9 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -218537,9 +218532,9 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; diff --git a/src/wolfcrypt/src/sp_c32.c b/src/wolfcrypt/src/sp_c32.c index a1f0eb2..10d646a 100644 --- a/src/wolfcrypt/src/sp_c32.c +++ b/src/wolfcrypt/src/sp_c32.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/sp_c64.c b/src/wolfcrypt/src/sp_c64.c index 0a77db8..06dc0bd 100644 --- a/src/wolfcrypt/src/sp_c64.c +++ b/src/wolfcrypt/src/sp_c64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/sp_cortexm.c b/src/wolfcrypt/src/sp_cortexm.c index ada8bbf..fc756ff 100644 --- a/src/wolfcrypt/src/sp_cortexm.c +++ b/src/wolfcrypt/src/sp_cortexm.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include @@ -114,9 +109,9 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -257,9 +252,11 @@ static void sp_2048_to_bin_64(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -604,7 +601,8 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_d "ADD sp, sp, #0x24\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -616,9 +614,11 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_d * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -741,7 +741,8 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_d "ADD sp, sp, #0x2c\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); } @@ -753,7 +754,8 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_d * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -783,7 +785,7 @@ static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -836,7 +838,7 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -848,9 +850,11 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -892,7 +896,7 @@ static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -1038,7 +1042,7 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -1050,9 +1054,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1122,7 +1128,7 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -1328,7 +1334,7 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -1340,9 +1346,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1468,7 +1476,7 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -1787,7 +1795,8 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) "ADD sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -1904,7 +1913,8 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) "ADD sp, sp, #0x20\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -1916,7 +1926,8 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -1945,7 +1956,7 @@ static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -1993,9 +2004,11 @@ SP_NOINLINE static void sp_2048_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2036,7 +2049,7 @@ static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -2084,9 +2097,11 @@ SP_NOINLINE static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2155,7 +2170,7 @@ static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -2205,9 +2220,11 @@ SP_NOINLINE static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2246,7 +2263,8 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -2298,7 +2316,8 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -2312,7 +2331,8 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -2426,7 +2446,8 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -2543,7 +2564,8 @@ static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -2574,9 +2596,11 @@ static void sp_2048_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2615,7 +2639,8 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -2667,7 +2692,8 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -2681,7 +2707,8 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -2795,7 +2822,8 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -2912,7 +2940,8 @@ static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -2994,7 +3023,7 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #256]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -3340,7 +3369,7 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) "STR r4, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -3370,9 +3399,11 @@ static void sp_2048_mont_norm_32(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3411,7 +3442,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -3426,9 +3457,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3555,7 +3588,7 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -3570,9 +3603,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3868,7 +3903,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -3881,9 +3917,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3986,7 +4024,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -4001,9 +4040,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4209,7 +4250,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -4222,9 +4264,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4315,7 +4359,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_2048_cond_sub_32(a - 32, a, m, (sp_digit)0 - mp); } @@ -4407,7 +4452,7 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -4593,7 +4638,7 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "STR r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -4609,9 +4654,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4658,7 +4705,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -4674,9 +4721,11 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4740,7 +4789,7 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -5153,7 +5202,7 @@ static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -5562,9 +5611,11 @@ static void sp_2048_mont_norm_64(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5603,7 +5654,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -5618,9 +5669,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5859,7 +5912,7 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -5874,9 +5927,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, const sp_dig * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6428,7 +6483,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -6441,9 +6497,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6546,7 +6604,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -6561,9 +6620,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6929,7 +6990,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -6942,9 +7004,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7035,7 +7099,8 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_2048_cond_sub_64(a - 64, a, m, (sp_digit)0 - mp); } @@ -7080,9 +7145,11 @@ SP_NOINLINE static void sp_2048_mont_sqr_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7120,7 +7187,8 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -7133,9 +7201,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7260,7 +7330,7 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -7277,9 +7347,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, const sp_digit* b * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7326,7 +7398,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -7342,9 +7414,11 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7408,7 +7482,7 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -8276,7 +8350,7 @@ static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -8807,9 +8881,11 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8848,7 +8924,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -8863,9 +8939,11 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8992,7 +9070,7 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "ADC %[r], r10, r10\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -9712,7 +9790,7 @@ static void sp_2048_lshift_64(sp_digit* r, const sp_digit* a, byte n) "STR r6, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -9999,9 +10077,9 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -10141,7 +10219,8 @@ static void sp_3072_to_bin_96(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -11157,7 +11236,8 @@ static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -11168,9 +11248,11 @@ static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11205,7 +11287,7 @@ static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -11272,7 +11354,7 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -11284,9 +11366,11 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11342,7 +11426,7 @@ static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -11520,7 +11604,7 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -11532,9 +11616,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11632,7 +11718,7 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -11894,7 +11980,7 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -11906,9 +11992,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12090,7 +12178,7 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -12860,7 +12948,8 @@ static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) "STM %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -12871,9 +12960,11 @@ static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12907,7 +12998,7 @@ static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -12955,9 +13046,11 @@ SP_NOINLINE static void sp_3072_sqr_24(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13012,7 +13105,7 @@ static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -13060,9 +13153,11 @@ SP_NOINLINE static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13159,7 +13254,7 @@ static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -13209,9 +13304,11 @@ SP_NOINLINE static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13250,7 +13347,8 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -13302,7 +13400,8 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -13316,7 +13415,8 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -13430,7 +13530,8 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -13547,7 +13648,8 @@ static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -13578,9 +13680,11 @@ static void sp_3072_mask_48(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13619,7 +13723,8 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -13671,7 +13776,8 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -13685,7 +13791,8 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -13799,7 +13906,8 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -13916,7 +14024,8 @@ static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -13998,7 +14107,7 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #384]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -14504,7 +14613,7 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -14534,9 +14643,11 @@ static void sp_3072_mont_norm_48(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14575,7 +14686,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -14590,9 +14701,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14775,7 +14888,7 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -14790,9 +14903,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, const sp_dig * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15216,7 +15331,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -15229,9 +15345,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15334,7 +15452,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -15349,9 +15468,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15637,7 +15758,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -15650,9 +15772,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15743,7 +15867,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_3072_cond_sub_48(a - 48, a, m, (sp_digit)0 - mp); } @@ -15835,7 +15960,7 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #192]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -16101,7 +16226,7 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -16117,9 +16242,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16166,7 +16293,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -16182,9 +16309,11 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16248,7 +16377,7 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -16837,7 +16966,7 @@ static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -17246,9 +17375,11 @@ static void sp_3072_mont_norm_96(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17287,7 +17418,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -17302,9 +17433,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17655,7 +17788,7 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -17670,9 +17803,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, const sp_dig * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -18480,7 +18615,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -18493,9 +18629,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -18598,7 +18736,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -18613,9 +18752,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19141,7 +19282,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -19154,9 +19296,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19247,7 +19391,8 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_3072_cond_sub_96(a - 96, a, m, (sp_digit)0 - mp); } @@ -19292,9 +19437,11 @@ SP_NOINLINE static void sp_3072_mont_sqr_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19332,7 +19479,8 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -19345,9 +19493,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19528,7 +19678,7 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -19545,9 +19695,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, const sp_digit* b * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19594,7 +19746,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -19610,9 +19762,11 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19676,7 +19830,7 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -20896,7 +21050,7 @@ static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -21427,9 +21581,11 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -21468,7 +21624,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -21483,9 +21639,11 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -21668,7 +21826,7 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, const sp_dig "ADC %[r], r10, r10\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -22580,7 +22738,7 @@ static void sp_3072_lshift_96(sp_digit* r, const sp_digit* a, byte n) "STR r4, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -22867,9 +23025,9 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -23246,7 +23404,7 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -23258,9 +23416,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23498,7 +23658,7 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -23587,9 +23747,11 @@ SP_NOINLINE static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23628,7 +23790,8 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -23680,7 +23843,8 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -23694,7 +23858,8 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -23808,7 +23973,8 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -23925,7 +24091,8 @@ static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -24005,7 +24172,7 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #512]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -24671,7 +24838,7 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) "STR r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -24702,9 +24869,11 @@ static void sp_4096_mont_norm_128(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24743,7 +24912,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -24758,9 +24927,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -25223,7 +25394,7 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -25238,9 +25409,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, const sp_di * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -26304,7 +26477,8 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -26317,9 +26491,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -26422,7 +26598,8 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -26437,9 +26614,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27125,7 +27304,8 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -27138,9 +27318,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27231,7 +27413,8 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); sp_4096_cond_sub_128(a - 128, a, m, (sp_digit)0 - mp); } @@ -27276,9 +27459,11 @@ SP_NOINLINE static void sp_4096_mont_sqr_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27316,7 +27501,8 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -27329,9 +27515,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27568,7 +27756,7 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -27585,9 +27773,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, const sp_digit* * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27634,7 +27824,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -27650,9 +27840,11 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27716,7 +27908,7 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -29288,7 +29480,7 @@ static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -29819,9 +30011,11 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29860,7 +30054,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -29875,9 +30069,11 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30116,7 +30312,7 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, const sp_dig "ADC %[r], r10, r10\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -31220,7 +31416,7 @@ static void sp_4096_lshift_128(sp_digit* r, const sp_digit* a, byte n) "STR r5, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -31513,7 +31709,8 @@ static const sp_digit p256_b[8] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -31627,7 +31824,8 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -31640,9 +31838,11 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -31987,7 +32187,8 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_di "ADD sp, sp, #0x24\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -31999,9 +32200,11 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_di * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32124,7 +32327,8 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_di "ADD sp, sp, #0x2c\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); } @@ -32244,7 +32448,8 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -32494,7 +32699,8 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -32611,7 +32817,8 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) "ADD sp, sp, #0x20\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); } @@ -32625,7 +32832,8 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -32666,7 +32874,8 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -32679,7 +32888,8 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -32709,7 +32919,7 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -32722,9 +32932,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * m The modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32951,7 +33163,8 @@ static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, const sp_digit* "ADD sp, sp, #0x18\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -33167,9 +33380,11 @@ static int sp_256_point_to_ecc_point_8(const sp_point_256* p, ecc_point* pm) * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33633,7 +33848,8 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const "ADD sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -33658,9 +33874,11 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33902,7 +34120,8 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const "ADD sp, sp, #0x4c\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", "r8", "r9", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r10", "r11", "r12", "r7", + "r8", "r9", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -33926,9 +34145,11 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, const * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34283,7 +34504,8 @@ SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, const "ADD sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -34306,9 +34528,11 @@ SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, const * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34532,7 +34756,8 @@ SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, const "ADD sp, sp, #0x44\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -34786,7 +35011,7 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -34807,9 +35032,11 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34848,7 +35075,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -34863,9 +35090,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34908,7 +35137,7 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -34925,9 +35154,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, const sp_digit * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35031,7 +35262,8 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -35044,9 +35276,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35132,7 +35366,8 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -35146,9 +35381,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, + sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35289,7 +35526,8 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ "ADD sp, sp, #0x44\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -35311,9 +35549,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, sp_ * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35417,7 +35657,8 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -35430,9 +35671,11 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35518,7 +35761,8 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, const sp_digit* "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_256_cond_sub_8(a - 8, a, m, (sp_digit)0 - mp); } @@ -35573,9 +35817,11 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35622,7 +35868,8 @@ SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const "STM %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -35638,9 +35885,11 @@ SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35682,7 +35931,8 @@ SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const "STM %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -35698,9 +35948,11 @@ SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35774,7 +36026,8 @@ SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const "STM %[r], {r4, r5, r6, r7, r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3", "r12" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -35791,9 +36044,11 @@ SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35838,7 +36093,8 @@ SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const "STM %[r], {r5, r6, r7, r8, r9, r10, r11, r12}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -35854,9 +36110,11 @@ SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35905,7 +36163,8 @@ SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, const "STM %[r], {r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3" ); } @@ -39436,7 +39695,7 @@ static void sp_256_add_one_8(sp_digit* a) "STM %[a]!, {r1, r2, r3, r4}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -39474,9 +39733,9 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -39865,7 +40124,8 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -39905,7 +40165,7 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -39966,7 +40226,7 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #32]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -40032,7 +40292,7 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) "STR r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -40048,9 +40308,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40097,7 +40359,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -40113,9 +40375,11 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40179,7 +40443,7 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit di "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -40838,7 +41102,8 @@ int sp_ecc_sign_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -40878,7 +41143,8 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -40891,7 +41157,8 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -40920,7 +41187,7 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -40966,7 +41233,8 @@ static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) "STRD r8, r9, [%[r], #8]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); } @@ -40977,7 +41245,8 @@ static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -41058,7 +41327,8 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) "STM %[r], {r8, r9, r10, r11}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -41261,7 +41531,7 @@ static int sp_256_num_bits_8(const sp_digit* a) "MOV %[a], r4\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5" ); return (word32)(size_t)a; } @@ -42345,7 +42615,8 @@ static const sp_digit p384_b[12] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -42459,7 +42730,8 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -42471,7 +42743,8 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -43487,7 +43760,8 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -43606,7 +43880,8 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -44307,7 +44582,8 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) "STM %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -44320,7 +44596,8 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -44361,7 +44638,8 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -44374,7 +44652,8 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -44411,7 +44690,7 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -44723,9 +45002,11 @@ static int sp_384_point_to_ecc_point_12(const sp_point_384* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -44764,7 +45045,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -44779,9 +45060,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -44838,7 +45121,7 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -44854,9 +45137,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, const sp_digi * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -44992,7 +45277,8 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_384_cond_sub_12(a - 12, a, m, (sp_digit)0 - mp); } @@ -45005,9 +45291,11 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45113,7 +45401,8 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, sp "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_384_cond_sub_12(a - 12, a, m, (sp_digit)0 - mp); } @@ -45448,7 +45737,7 @@ static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -45507,9 +45796,11 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45532,9 +45823,11 @@ SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45556,9 +45849,11 @@ SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45583,7 +45878,8 @@ SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, const * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -45623,7 +45919,8 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "MOV %[r], r11\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -45636,7 +45933,8 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -45672,7 +45970,7 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -45688,9 +45986,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45729,7 +46029,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -45744,9 +46044,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45803,7 +46105,7 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi "ADC %[r], r10, r10\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -45817,9 +46119,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, const sp_digi * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45898,7 +46202,7 @@ static void sp_384_rshift1_12(sp_digit* r, const sp_digit* a) "STR r4, [%[r], #44]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -49508,7 +49812,7 @@ static void sp_384_add_one_12(sp_digit* a) "STM %[a]!, {r1, r2, r3, r4}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -49546,9 +49850,9 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -49937,7 +50241,8 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -49984,7 +50289,7 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -50045,7 +50350,7 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #48]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -50131,7 +50436,7 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -50147,9 +50452,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50196,7 +50503,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -50212,9 +50519,11 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50278,7 +50587,7 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit d "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -50907,9 +51216,11 @@ int sp_ecc_sign_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m) +static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -51026,7 +51337,8 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, const sp_digit* m "STR r10, [%[r], #44]\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -51329,7 +51641,7 @@ static int sp_384_num_bits_12(const sp_digit* a) "MOV %[a], r4\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5" ); return (word32)(size_t)a; } @@ -52459,7 +52771,8 @@ static const sp_digit p521_b[17] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -52576,7 +52889,8 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -52588,7 +52902,8 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -54618,7 +54933,8 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -54740,7 +55056,8 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -56025,7 +56342,8 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) "STM %[r]!, {r2}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -56038,7 +56356,8 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -56085,7 +56404,8 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC %[r], r4, #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -56098,7 +56418,8 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -56146,7 +56467,7 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -56375,9 +56696,11 @@ static int sp_521_point_to_ecc_point_17(const sp_point_521* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56416,7 +56739,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -56431,9 +56754,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56509,7 +56834,7 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -56522,9 +56847,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, const sp_digi * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56637,7 +56964,8 @@ SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, sp "STM %[a]!, {r1, r2, r3, r4, r5, r6, r7, r8}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", + "r10", "r11", "r12", "lr" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -56659,9 +56987,11 @@ SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, sp * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56924,7 +57254,8 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_521_cond_sub_17(a - 17, a, m, (sp_digit)0 - mp); } @@ -56937,9 +57268,11 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57157,7 +57490,8 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, const sp_digit* "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_521_cond_sub_17(a - 17, a, m, (sp_digit)0 - mp); } @@ -57544,7 +57878,7 @@ static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -57603,9 +57937,11 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57677,7 +58013,8 @@ SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, const "STM %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -57693,9 +58030,11 @@ SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57757,7 +58096,8 @@ SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, const "STM %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -57773,9 +58113,11 @@ SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57857,7 +58199,8 @@ SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, const "STM %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r2", "r3", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r2", "r3" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -57874,9 +58217,11 @@ SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, const * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57949,7 +58294,8 @@ SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, const "STM %[r]!, {r4}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); #ifndef WOLFSSL_NO_VAR_ASSIGN_REG (void)m_p; @@ -58038,7 +58384,7 @@ static void sp_521_rshift1_17(sp_digit* r, const sp_digit* a) "STR r3, [%[r], #64]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -62279,7 +62625,7 @@ static void sp_521_add_one_17(sp_digit* a) "STM %[a]!, {r1}\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4" ); } @@ -62317,9 +62663,9 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; @@ -62758,7 +63104,7 @@ static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) "STRD r4, r5, [%[r], #60]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -62884,7 +63230,7 @@ static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) "STR r5, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -63108,7 +63454,7 @@ static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) "STR r6, [%[r], #4]\n\t" : [r] "+r" (r), [a] "+r" (a), [n] "+r" (n) : - : "memory", "r4", "r5", "r6", "r3", "r7", "cc" + : "memory", "cc", "r4", "r5", "r6", "r3", "r7" ); } @@ -63163,7 +63509,8 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "SBC %[a], %[a], %[a]\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -63221,7 +63568,7 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -63282,7 +63629,7 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #68]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -63393,7 +63740,7 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) "STR r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -63409,9 +63756,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63458,7 +63807,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -63474,9 +63823,11 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63540,7 +63891,7 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit d "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -64200,7 +64551,8 @@ int sp_ecc_sign_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -64245,7 +64597,8 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12" ); return (word32)(size_t)r; } @@ -64258,7 +64611,8 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -64305,7 +64659,7 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -64318,9 +64672,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m) +static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -64472,7 +64828,8 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, const sp_digit* m "STR r9, [%[r], #64]\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); } @@ -64900,7 +65257,7 @@ static int sp_521_num_bits_17(const sp_digit* a) "MOV %[a], r4\n\t" : [a] "+r" (a) : - : "memory", "r1", "r2", "r3", "r4", "r5", "cc" + : "memory", "cc", "r1", "r2", "r3", "r4", "r5" ); return (word32)(size_t)a; } @@ -65913,7 +66270,8 @@ typedef struct sp_point_1024 { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -67711,7 +68069,8 @@ static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) "STM %[r]!, {r3, r4, r5, r6}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", "r12", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r11", + "r12" ); } @@ -68863,7 +69222,8 @@ static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) "STM %[r]!, {r2, r3, r4, r8}\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r12" ); } @@ -68874,9 +69234,11 @@ static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -68918,7 +69280,7 @@ static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -68999,7 +69361,7 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "SBC %[a], r9, r9\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)a; } @@ -69011,9 +69373,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69083,7 +69447,7 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "ADC %[r], %[r], #0x0\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -69164,9 +69528,11 @@ SP_NOINLINE static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69207,7 +69573,7 @@ static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, const sp_digit* b "SBC %[r], r6, r6\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -69256,7 +69622,8 @@ SP_NOINLINE static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ @@ -69370,7 +69737,8 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -69487,7 +69855,8 @@ static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) #endif : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", "r11", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr", + "r11" ); } @@ -69623,7 +69992,8 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) "MOV %[a], r10\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11" ); return (word32)(size_t)a; } @@ -69639,9 +70009,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69680,7 +70052,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r4\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -69695,9 +70067,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69824,7 +70198,7 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig "SBC %[r], r5, r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9" ); return (word32)(size_t)r; } @@ -69838,9 +70212,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, const sp_dig * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p) +static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69879,7 +70255,8 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b "MOV %[r], r3\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r3", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r3", "r12" ); return (word32)(size_t)r; } @@ -69940,7 +70317,7 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "STR r3, [%[r], #128]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); } @@ -70126,7 +70503,7 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) "STR r5, [%[r]]\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8" ); } @@ -70142,9 +70519,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70191,7 +70570,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit "ADD %[d1], r6, r3\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -70207,9 +70586,11 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, + sp_digit div_p) #else -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70273,7 +70654,7 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit "SUB %[d1], r3, r8\n\t" : [d1] "+r" (d1), [d0] "+r" (d0), [div] "+r" (div) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)d1; } @@ -70716,7 +71097,7 @@ static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) "MOV %[a], r2\n\t" : [a] "+r" (a), [b] "+r" (b) : - : "memory", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r2", "r3", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)a; } @@ -71057,9 +71438,11 @@ static int sp_1024_point_to_ecc_point_32(const sp_point_1024* p, ecc_point* pm) * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -71360,7 +71743,8 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r3\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_1024_cond_sub_32(a - 32, a, m, mp); } @@ -71373,9 +71757,11 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) +SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, + const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, sp_digit mp) +SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, + sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -71586,7 +71972,8 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, s "MOV %[mp], r5\n\t" : [a] "+r" (a), [m] "+r" (m), [mp] "+r" (mp) : - : "memory", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "lr", "cc" + : "memory", "cc", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "lr" ); sp_1024_cond_sub_32(a - 32, a, m, mp); } @@ -71737,9 +72124,11 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -71904,7 +72293,8 @@ SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, cons "STM %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r12" ); } @@ -71915,9 +72305,11 @@ SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, cons * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72065,7 +72457,8 @@ SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, cons "STM %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12", "cc" + : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", + "r12" ); } @@ -72076,9 +72469,11 @@ SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, cons * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* m_p) +SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, const sp_digit* m) +SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, + const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72381,7 +72776,8 @@ SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, cons "STM %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [m] "+r" (m) : - : "memory", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", "r12", "cc" + : "memory", "cc", "r8", "r9", "r10", "r11", "r4", "r5", "r6", "r7", + "r12" ); } @@ -72393,9 +72789,11 @@ SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, cons * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) +SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, const sp_digit* b, const sp_digit* m) +SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72554,7 +72952,8 @@ SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, cons "STM %[r]!, {r4, r5, r6, r7}\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", + "r12" ); } @@ -72568,9 +72967,11 @@ SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, cons * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72609,7 +73010,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "MOV %[r], r5\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8" ); return (word32)(size_t)r; } @@ -72624,9 +73025,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) +static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, + const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_digit* b, sp_digit m) +static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, + const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72753,7 +73156,7 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, const sp_dig "ADC %[r], r10, r10\n\t" : [r] "+r" (r), [a] "+r" (a), [b] "+r" (b), [m] "+r" (m) : - : "memory", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc" + : "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10" ); return (word32)(size_t)r; } @@ -72899,7 +73302,7 @@ static void sp_1024_rshift1_32(sp_digit* r, const sp_digit* a) "STR r3, [%[r], #124]\n\t" : [r] "+r" (r), [a] "+r" (a) : - : "memory", "r2", "r3", "r4", "cc" + : "memory", "cc", "r2", "r3", "r4" ); } @@ -81865,9 +82268,9 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) } #else switch (i) { - case 2: d[2] = a[2]; //fallthrough - case 1: d[1] = a[1]; //fallthrough - case 0: d[0] = a[0]; //fallthrough + case 2: d[i-2] = a[2]; //fallthrough + case 1: d[i-1] = a[1]; //fallthrough + case 0: d[i-0] = a[0]; //fallthrough } #endif j++; diff --git a/src/wolfcrypt/src/sp_dsp32.c b/src/wolfcrypt/src/sp_dsp32.c index e65862d..f218860 100644 --- a/src/wolfcrypt/src/sp_dsp32.c +++ b/src/wolfcrypt/src/sp_dsp32.c @@ -1,6 +1,6 @@ /* sp_cdsp_signed.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* from wolfcrypt/src/sp_c32.c */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif +/* from wolfcrypt/src/sp_c32.c */ -#include -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/sp_int.c b/src/wolfcrypt/src/sp_int.c index 00b3607..1769840 100644 --- a/src/wolfcrypt/src/sp_int.c +++ b/src/wolfcrypt/src/sp_int.c @@ -1,6 +1,6 @@ /* sp_int.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -26,12 +26,8 @@ DESCRIPTION This library provides single precision (SP) integer math functions. */ -#ifdef HAVE_CONFIG_H - #include -#endif -#include -#include +#include #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) @@ -39,12 +35,12 @@ This library provides single precision (SP) integer math functions. defined(WOLFSSL_SP_NO_MALLOC) #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(WOLFSSL_SP_NO_DYN_STACK) -#pragma GCC diagnostic push +PRAGMA_GCC_DIAG_PUSH /* We are statically declaring a variable smaller than sp_int. * We track available memory in the 'size' field. * Disable warnings of sp_int being partly outside array bounds of variable. */ -#pragma GCC diagnostic ignored "-Warray-bounds" +PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") #endif #endif @@ -353,8 +349,8 @@ while (0) "movq %%rax, %[l] \n\t" \ "movq %%rdx, %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ - : [a] "m" (va), [b] "m" (vb) \ - : "memory", "%rax", "%rdx", "cc" \ + : [a] "rm" (va), [b] "rm" (vb) \ + : "%rax", "%rdx", "cc" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -377,7 +373,7 @@ while (0) "adcq %%rdx, %[h] \n\t" \ "adcq $0 , %[o] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "%rax", "%rdx", "cc" \ ) /* Multiply va by vb and add double size result into: vh | vl */ @@ -388,7 +384,7 @@ while (0) "addq %%rax, %[l] \n\t" \ "adcq %%rdx, %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "%rax", "%rdx", "cc" \ ) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ @@ -403,7 +399,7 @@ while (0) "adcq %%rdx, %[h] \n\t" \ "adcq $0 , %[o] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "%rax", "%rdx", "cc" \ ) /* Multiply va by vb and add double size result twice into: vo | vh | vl @@ -419,7 +415,7 @@ while (0) "adcq %%rdx, %[h] \n\t" \ "adcq $0 , %[o] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "%rax", "%rdx", "cc" \ ) /* Square va and store double size result in: vh | vl */ @@ -430,8 +426,8 @@ while (0) "movq %%rax, %[l] \n\t" \ "movq %%rdx, %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ - : [a] "m" (va) \ - : "memory", "%rax", "%rdx", "cc" \ + : [a] "rm" (va) \ + : "%rax", "%rdx", "cc" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -442,7 +438,7 @@ while (0) "adcq %%rdx, %[h] \n\t" \ "adcq $0 , %[o] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "%rax", "%rdx", "cc" \ ) /* Square va and add double size result into: vh | vl */ @@ -453,7 +449,7 @@ while (0) "addq %%rax, %[l] \n\t" \ "adcq %%rdx, %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "%rax", "%rdx", "cc" \ ) /* Add va into: vh | vl */ @@ -462,10 +458,9 @@ while (0) "addq %[a], %[l] \n\t" \ "adcq $0 , %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "cc" \ ) -/* Add va, variable in a register, into: vh | vl */ #define SP_ASM_ADDC_REG(vl, vh, va) \ __asm__ __volatile__ ( \ "addq %[a], %[l] \n\t" \ @@ -480,7 +475,7 @@ while (0) "subq %[a], %[l] \n\t" \ "sbbq $0 , %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "cc" \ ) /* Sub va from: vh | vl */ @@ -703,8 +698,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "movl %%eax, %[l] \n\t" \ "movl %%edx, %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ - : [a] "m" (va), [b] "m" (vb) \ - : "memory", "eax", "edx", "cc" \ + : [a] "rm" (va), [b] "rm" (vb) \ + : "eax", "edx", "cc" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -726,8 +721,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %%eax, %[l] \n\t" \ "adcl %%edx, %[h] \n\t" \ "adcl $0 , %[o] \n\t" \ - : [l] "+rm" (vl), [h] "+rm" (vh), [o] "+rm" (vo) \ - : [a] "r" (va), [b] "r" (vb) \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "eax", "edx", "cc" \ ) /* Multiply va by vb and add double size result into: vh | vl */ @@ -738,7 +733,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %%eax, %[l] \n\t" \ "adcl %%edx, %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "eax", "edx", "cc" \ ) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ @@ -752,8 +747,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %%eax, %[l] \n\t" \ "adcl %%edx, %[h] \n\t" \ "adcl $0 , %[o] \n\t" \ - : [l] "+rm" (vl), [h] "+rm" (vh), [o] "+rm" (vo) \ - : [a] "r" (va), [b] "r" (vb) \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "eax", "edx", "cc" \ ) /* Multiply va by vb and add double size result twice into: vo | vh | vl @@ -769,7 +764,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "adcl %%edx, %[h] \n\t" \ "adcl $0 , %[o] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ - : [a] "m" (va), [b] "m" (vb) \ + : [a] "rm" (va), [b] "rm" (vb) \ : "eax", "edx", "cc" \ ) /* Square va and store double size result in: vh | vl */ @@ -780,8 +775,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "movl %%eax, %[l] \n\t" \ "movl %%edx, %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ - : [a] "m" (va) \ - : "memory", "eax", "edx", "cc" \ + : [a] "rm" (va) \ + : "eax", "edx", "cc" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -791,8 +786,8 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %%eax, %[l] \n\t" \ "adcl %%edx, %[h] \n\t" \ "adcl $0 , %[o] \n\t" \ - : [l] "+rm" (vl), [h] "+rm" (vh), [o] "+rm" (vo) \ - : [a] "m" (va) \ + : [l] "+r" (vl), [h] "+r" (vh), [o] "+r" (vo) \ + : [a] "rm" (va) \ : "eax", "edx", "cc" \ ) /* Square va and add double size result into: vh | vl */ @@ -803,7 +798,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %%eax, %[l] \n\t" \ "adcl %%edx, %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "eax", "edx", "cc" \ ) /* Add va into: vh | vl */ @@ -812,10 +807,9 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "addl %[a], %[l] \n\t" \ "adcl $0 , %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "cc" \ ) -/* Add va, variable in a register, into: vh | vl */ #define SP_ASM_ADDC_REG(vl, vh, va) \ __asm__ __volatile__ ( \ "addl %[a], %[l] \n\t" \ @@ -830,7 +824,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "subl %[a], %[l] \n\t" \ "sbbl $0 , %[h] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ - : [a] "m" (va) \ + : [a] "rm" (va) \ : "cc" \ ) /* Sub va from: vh | vl */ @@ -904,7 +898,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "umulh %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory", "cc" \ + : "cc" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -915,7 +909,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mov %[o], xzr \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "=r" (vo) \ : [a] "r" (va), [b] "r" (vb) \ - : "x8" \ + : "x8", "cc" \ ) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ @@ -978,7 +972,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "umulh %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : "cc" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -1135,7 +1129,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "umull %[l], %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -1144,7 +1137,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mov %[o], #0 \n\t" \ : [l] "+r" (vl), [h] "+r" (vh), [o] "=r" (vo) \ : [a] "r" (va), [b] "r" (vb) \ - : \ ) /* Multiply va by vb and add double size result into: vo | vh | vl */ #define SP_ASM_MUL_ADD(vl, vh, vo, va, vb) \ @@ -1163,7 +1155,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "umlal %[l], %[h], %[a], %[b] \n\t" \ : [l] "+r" (vl), [h] "+r" (vh) \ : [a] "r" (va), [b] "r" (vb) \ - : \ ) /* Multiply va by vb and add double size result twice into: vo | vh | vl */ #define SP_ASM_MUL_ADD2(vl, vh, vo, va, vb) \ @@ -1200,7 +1191,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "umull %[l], %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -1259,7 +1249,6 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "clz %[n], %[a] \n\t" \ : [n] "=r" (vn) \ : [a] "r" (va) \ - : \ ) #endif @@ -3482,7 +3471,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhdu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -3555,7 +3544,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhdu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -3630,7 +3619,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhdu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -3703,7 +3692,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhdu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -3789,7 +3778,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhwu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -3861,7 +3850,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhwu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -3935,7 +3924,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhwu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4007,7 +3996,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhwu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -4091,7 +4080,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mfhi %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory", "$lo", "$hi" \ + : "$lo", "$hi" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4194,7 +4183,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mfhi %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory", "$lo", "$hi" \ + : "$lo", "$hi" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -4292,7 +4281,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mfhi %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory", "%lo", "%hi" \ + : "%lo", "%hi" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4395,7 +4384,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mfhi %[h] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory", "%lo", "%hi" \ + : "%lo", "%hi" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -4492,7 +4481,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4589,7 +4578,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -4684,7 +4673,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhu %[h], %[a], %[b] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory" \ + : \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4781,7 +4770,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "mulhu %[h], %[a], %[a] \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory" \ + : \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -4878,7 +4867,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "lgr %[h], %%r0 \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va), [b] "r" (vb) \ - : "memory", "r0", "r1" \ + : "r0", "r1" \ ) /* Multiply va by vb and store double size result in: vo | vh | vl */ #define SP_ASM_MUL_SET(vl, vh, vo, va, vb) \ @@ -4958,7 +4947,7 @@ static WC_INLINE sp_int_digit sp_div_word(sp_int_digit hi, sp_int_digit lo, "lgr %[h], %%r0 \n\t" \ : [h] "+r" (vh), [l] "+r" (vl) \ : [a] "r" (va) \ - : "memory", "r0", "r1" \ + : "r0", "r1" \ ) /* Square va and add double size result into: vo | vh | vl */ #define SP_ASM_SQR_ADD(vl, vh, vo, va) \ @@ -5136,7 +5125,7 @@ int sp_init_size(sp_int* a, unsigned int size) int err = MP_OKAY; /* Validate parameters. Don't use size more than max compiled. */ - if ((a == NULL) || ((size <= 0) || (size > SP_INT_DIGITS))) { + if ((a == NULL) || ((size == 0) || (size > SP_INT_DIGITS))) { err = MP_VAL; } @@ -5279,6 +5268,9 @@ void sp_zero(sp_int* a) */ void sp_clear(sp_int* a) { +#ifdef HAVE_FIPS + sp_forcezero(a); +#else /* Clear when valid pointer passed in. */ if (a != NULL) { unsigned int i; @@ -5291,6 +5283,7 @@ void sp_clear(sp_int* a) _sp_zero(a); sp_free(a); } +#endif } #if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \ @@ -8016,7 +8009,7 @@ int sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) } #endif /* WOLFSSL_SP_MATH_ALL */ -/* Constant time clamping/ +/* Constant time clamping. * * @param [in, out] a SP integer to clamp. */ @@ -8027,8 +8020,20 @@ static void sp_clamp_ct(sp_int* a) sp_size_t mask = (sp_size_t)-1; for (i = (int)a->used - 1; i >= 0; i--) { - used = (sp_size_t)(used - ((a->dp[i] == 0) & mask)); - mask &= (sp_size_t)(0 - (a->dp[i] == 0)); +#if ((SP_WORD_SIZE == 64) && \ + (defined(_WIN64) || !defined(WOLFSSL_UINT128_T_DEFINED))) || \ + ((SP_WORD_SIZE == 32) && defined(NO_64BIT)) + sp_int_digit negVal = ~a->dp[i]; + sp_int_digit minusOne = a->dp[i] - 1; + sp_int_digit zeroMask = + (sp_int_digit)((sp_int_sdigit)(negVal & minusOne) >> + (SP_WORD_SIZE - 1)); +#else + sp_int_digit zeroMask = + (sp_int_digit)((((sp_int_sword)a->dp[i]) - 1) >> SP_WORD_SIZE); +#endif + mask &= (sp_size_t)zeroMask; + used = (sp_size_t)(used + mask); } a->used = used; } @@ -8216,7 +8221,7 @@ int sp_addmod_ct(const sp_int* a, const sp_int* b, const sp_int* m, sp_int* r) * @return MP_OKAY on success. */ static void _sp_submod_ct(const sp_int* a, const sp_int* b, const sp_int* m, - unsigned int max, sp_int* r) + unsigned int max_size, sp_int* r) { #ifndef SQR_MUL_ASM sp_int_sword w; @@ -8237,7 +8242,7 @@ static void _sp_submod_ct(const sp_int* a, const sp_int* b, const sp_int* m, l = 0; h = 0; #endif - for (i = 0; i < max; i++) { + for (i = 0; i < max_size; i++) { /* Values past 'used' are not initialized. */ mask_a += (i == a->used); mask_b += (i == b->used); @@ -8527,13 +8532,13 @@ int sp_rshb(const sp_int* a, int n, sp_int* r) { int err = MP_OKAY; /* Number of digits to shift down. */ - sp_size_t i = (sp_size_t)(n >> SP_WORD_SHIFT); + sp_size_t i; if ((a == NULL) || (n < 0)) { err = MP_VAL; } /* Handle case where shifting out all digits. */ - if ((err == MP_OKAY) && (i >= a->used)) { + else if ((i = (sp_size_t)(n >> SP_WORD_SHIFT)) >= a->used) { _sp_zero(r); } /* Change callers when more error cases returned. */ @@ -8876,7 +8881,7 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, if ((!done) && (err == MP_OKAY)) { #if (defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC)) && \ !defined(WOLFSSL_SP_NO_MALLOC) - int cnt = 4; + unsigned int cnt = 4; /* Reuse remainder sp_int where possible. */ if ((rem != NULL) && (rem != d) && (rem->size > a->used)) { sa = rem; @@ -8905,7 +8910,7 @@ static int _sp_div(const sp_int* a, const sp_int* d, sp_int* r, sp_int* rem, } if (tr == NULL) { tr = td[i]; - _sp_init_size(tr, a->used - d->used + 2); + _sp_init_size(tr, (unsigned int)(a->used - d->used + 2)); } #else sa = td[2]; @@ -9252,8 +9257,9 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #endif #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * (a->used + b->used), NULL, - DYNAMIC_TYPE_BIGINT); + t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * + (size_t)(a->used + b->used), NULL, + DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; } @@ -9328,8 +9334,9 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) #endif #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * (a->used + b->used), NULL, - DYNAMIC_TYPE_BIGINT); + t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * + (size_t)(a->used + b->used), NULL, + DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; } @@ -12003,9 +12010,14 @@ int sp_mul(const sp_int* a, const sp_int* b, sp_int* r) } /* Need extra digit during calculation. */ + /* NOLINTBEGIN(clang-analyzer-core.UndefinedBinaryOperatorResult) */ + /* clang-tidy falsely believes that r->size was corrupted by the _sp_copy() + * to "Copy base into working variable" in _sp_exptmod_ex(). + */ if ((err == MP_OKAY) && (a->used + b->used > r->size)) { err = MP_VAL; } + /* NOLINTEND(clang-analyzer-core.UndefinedBinaryOperatorResult) */ #if 0 if (err == MP_OKAY) { @@ -14873,7 +14885,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) t = (sp_int_digit*)XMALLOC( - sizeof(sp_int_digit) * (((a->used + 1) / 2) * 2 + 1), NULL, + sizeof(sp_int_digit) * (size_t)(((a->used + 1) / 2) * 2 + 1), NULL, DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; @@ -14987,8 +14999,9 @@ static int _sp_sqr(const sp_int* a, sp_int* r) #endif #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) - t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * (a->used * 2), NULL, - DYNAMIC_TYPE_BIGINT); + t = (sp_int_digit*)XMALLOC(sizeof(sp_int_digit) * + (size_t)(a->used * 2), NULL, + DYNAMIC_TYPE_BIGINT); if (t == NULL) { err = MP_MEM; } @@ -17613,10 +17626,9 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) h = 0; } /* Handle overflow. */ - h = o2; - SP_ASM_ADDC(l, h, a->dp[7]); + SP_ASM_ADDC(l, o2, a->dp[7]); a->dp[3] = l; - a->dp[4] = h; + a->dp[4] = o2; a->used = 5; /* Remove leading zeros. */ @@ -17679,10 +17691,9 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) h = 0; } /* Handle overflow. */ - h = o2; - SP_ASM_ADDC(l, h, a->dp[11]); + SP_ASM_ADDC(l, o2, a->dp[11]); a->dp[5] = l; - a->dp[6] = h; + a->dp[6] = o2; a->used = 7; /* Remove leading zeros. */ @@ -17718,7 +17729,7 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) h = 0; SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); l = h; - for (j = 1; j + 1 < (unsigned int)m->used - 1; j += 2) { + for (j = 1; j < (unsigned int)m->used - 2; j += 2) { h = 0; SP_ASM_ADDC(l, h, ad[j]); SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); @@ -17744,11 +17755,9 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) o = h; } /* Handle overflow. */ - l = o; - h = o2; - SP_ASM_ADDC(l, h, a->dp[m->used * 2 - 1]); - a->dp[m->used - 1] = l; - a->dp[m->used] = h; + SP_ASM_ADDC(o, o2, a->dp[m->used * 2 - 1]); + a->dp[m->used - 1] = o; + a->dp[m->used] = o2; a->used = m->used + 1; /* Remove leading zeros. */ @@ -17789,8 +17798,8 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) SP_ASM_MUL_ADD_NO(l, h, mu, *(md++)); ad[0] = l; l = h; - /* 2.4. If i == NumDigits(m)-1 and mask != 0 then mu & = mask */ - for (j = 1; j + 1 < (unsigned int)m->used - 1; j += 2) { + /* 2.4. For j = 1 up to NumDigits(m)-2 */ + for (j = 1; j < (unsigned int)m->used - 2; j += 2) { h = 0; /* 2.4.1. a += mu * DigitMask(m, j) */ SP_ASM_ADDC(l, h, ad[j + 0]); @@ -17820,11 +17829,9 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp, int ct) o = h; } /* Handle overflow. */ - l = o; - h = o2; - SP_ASM_ADDC(l, h, a->dp[m->used * 2 - 1]); - a->dp[m->used * 2 - 1] = l; - a->dp[m->used * 2] = h; + SP_ASM_ADDC(o, o2, a->dp[m->used * 2 - 1]); + a->dp[m->used * 2 - 1] = o; + a->dp[m->used * 2] = o2; a->used = (sp_size_t)(m->used * 2 + 1); } @@ -17977,9 +17984,14 @@ int sp_mont_norm(sp_int* norm, const sp_int* m) if (err == MP_OKAY) { /* Find top bit and ensure norm has enough space. */ bits = (unsigned int)sp_count_bits(m); + /* NOLINTBEGIN(clang-analyzer-core.UndefinedBinaryOperatorResult) */ + /* clang-tidy falsely believes that norm->size was corrupted by the + * _sp_copy() to "Set real working value to base." in _sp_exptmod_ex(). + */ if (bits >= (unsigned int)norm->size * SP_WORD_SIZE) { err = MP_VAL; } + /* NOLINTEND(clang-analyzer-core.UndefinedBinaryOperatorResult) */ } if (err == MP_OKAY) { /* Round up for case when m is less than a word - no advantage in using @@ -19880,7 +19892,7 @@ void sp_memzero_check(sp_int* sp) defined(WOLFSSL_SP_NO_MALLOC) #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(WOLFSSL_SP_NO_DYN_STACK) -#pragma GCC diagnostic pop +PRAGMA_GCC_DIAG_POP #endif #endif diff --git a/src/wolfcrypt/src/sp_sm2_arm32.c b/src/wolfcrypt/src/sp_sm2_arm32.c index 4dc5377..0a458bd 100644 --- a/src/wolfcrypt/src/sp_sm2_arm32.c +++ b/src/wolfcrypt/src/sp_sm2_arm32.c @@ -1,6 +1,6 @@ /* sp_sm2_arm32.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_arm64.c b/src/wolfcrypt/src/sp_sm2_arm64.c index 8f87711..db67898 100644 --- a/src/wolfcrypt/src/sp_sm2_arm64.c +++ b/src/wolfcrypt/src/sp_sm2_arm64.c @@ -1,6 +1,6 @@ /* sp_sm2_arm64.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_armthumb.c b/src/wolfcrypt/src/sp_sm2_armthumb.c index 0be6685..21e49dc 100644 --- a/src/wolfcrypt/src/sp_sm2_armthumb.c +++ b/src/wolfcrypt/src/sp_sm2_armthumb.c @@ -1,6 +1,6 @@ /* sp_sm2_armthumb.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_c32.c b/src/wolfcrypt/src/sp_sm2_c32.c index 754b80a..5aae8d2 100644 --- a/src/wolfcrypt/src/sp_sm2_c32.c +++ b/src/wolfcrypt/src/sp_sm2_c32.c @@ -1,6 +1,6 @@ /* sp_sm2_c32.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_c64.c b/src/wolfcrypt/src/sp_sm2_c64.c index 861bfe3..d848104 100644 --- a/src/wolfcrypt/src/sp_sm2_c64.c +++ b/src/wolfcrypt/src/sp_sm2_c64.c @@ -1,6 +1,6 @@ /* sp_sm2_c64.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_cortexm.c b/src/wolfcrypt/src/sp_sm2_cortexm.c index 4b1083f..4ea4b8f 100644 --- a/src/wolfcrypt/src/sp_sm2_cortexm.c +++ b/src/wolfcrypt/src/sp_sm2_cortexm.c @@ -1,6 +1,6 @@ /* sp_sm2_cortexm.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_sm2_x86_64.c b/src/wolfcrypt/src/sp_sm2_x86_64.c index 24a5b9e..fd6f0d2 100644 --- a/src/wolfcrypt/src/sp_sm2_x86_64.c +++ b/src/wolfcrypt/src/sp_sm2_x86_64.c @@ -1,6 +1,6 @@ /* sp_sm2_x86_64.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFSSL_SM2 diff --git a/src/wolfcrypt/src/sp_x86_64.c b/src/wolfcrypt/src/sp_x86_64.c index 039820d..298ec47 100644 --- a/src/wolfcrypt/src/sp_x86_64.c +++ b/src/wolfcrypt/src/sp_x86_64.c @@ -1,6 +1,6 @@ /* sp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -21,16 +21,11 @@ /* Implementation by Sean Parkinson. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH) || \ defined(WOLFSSL_HAVE_SP_ECC) -#include #include #ifdef NO_INLINE #include diff --git a/src/wolfcrypt/src/sphincs.c b/src/wolfcrypt/src/sphincs.c index 5fc054d..94be4ac 100644 --- a/src/wolfcrypt/src/sphincs.c +++ b/src/wolfcrypt/src/sphincs.c @@ -1,6 +1,6 @@ /* sphincs.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,14 +19,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* Based on dilithium.c and Reworked for Sphincs by Anthony Hu. */ - -#ifdef HAVE_CONFIG_H - #include -#endif +#include -/* in case user set HAVE_PQC there */ -#include +/* Based on dilithium.c and Reworked for Sphincs by Anthony Hu. */ #include @@ -37,7 +32,6 @@ #endif #include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/srp.c b/src/wolfcrypt/src/srp.c index b06f62a..c7f5986 100644 --- a/src/wolfcrypt/src/srp.c +++ b/src/wolfcrypt/src/srp.c @@ -1,6 +1,6 @@ /* srp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef WOLFCRYPT_HAVE_SRP #include #include -#include #ifdef NO_INLINE #include @@ -152,39 +146,39 @@ static int SrpHashFinal(SrpHash* hash, byte* digest) } } -static word32 SrpHashSize(SrpType type) +static int SrpHashSize(SrpType type) { switch (type) { case SRP_TYPE_SHA: #ifndef NO_SHA return WC_SHA_DIGEST_SIZE; #else - return 0; + return ALGO_ID_E; #endif case SRP_TYPE_SHA256: #ifndef NO_SHA256 return WC_SHA256_DIGEST_SIZE; #else - return 0; + return ALGO_ID_E; #endif case SRP_TYPE_SHA384: #ifdef WOLFSSL_SHA384 return WC_SHA384_DIGEST_SIZE; #else - return 0; + return ALGO_ID_E; #endif case SRP_TYPE_SHA512: #ifdef WOLFSSL_SHA512 return WC_SHA512_DIGEST_SIZE; #else - return 0; + return ALGO_ID_E; #endif default: - return 0; + return ALGO_ID_E; } } @@ -353,7 +347,8 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, byte digest2[SRP_MAX_DIGEST_SIZE]; byte pad = 0; int r; - word32 i, j = 0; + word32 i; + int hashSize = 0; if (!srp || !N || !g || !salt || nSz < gSz) return BAD_FUNC_ARG; @@ -361,6 +356,10 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, if (!srp->user) return SRP_CALL_ORDER_E; + hashSize = SrpHashSize(srp->type); + if (hashSize < 0) + return hashSize; + /* Set N */ if (mp_read_unsigned_bin(&srp->N, N, nSz) != MP_OKAY) return MP_READ_E; @@ -389,7 +388,7 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, srp->saltSz = saltSz; /* Set k = H(N, g) */ - r = SrpHashInit(&hash, srp->type, srp->heap); + r = SrpHashInit(&hash, srp->type, srp->heap); if (!r) r = SrpHashUpdate(&hash, (byte*) N, nSz); for (i = 0; (word32)i < nSz - gSz; i++) { if (!r) r = SrpHashUpdate(&hash, &pad, 1); @@ -414,7 +413,7 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, /* digest1 = H(N) ^ H(g) */ if (r == 0) { - for (i = 0, j = SrpHashSize(srp->type); i < j; i++) + for (i = 0; i < (word32)hashSize; i++) digest1[i] ^= digest2[i]; } @@ -425,8 +424,8 @@ int wc_SrpSetParams(Srp* srp, const byte* N, word32 nSz, SrpHashFree(&hash); /* client proof = H( H(N) ^ H(g) | H(user) | salt) */ - if (!r) r = SrpHashUpdate(&srp->client_proof, digest1, j); - if (!r) r = SrpHashUpdate(&srp->client_proof, digest2, j); + if (!r) r = SrpHashUpdate(&srp->client_proof, digest1, (word32)hashSize); + if (!r) r = SrpHashUpdate(&srp->client_proof, digest2, (word32)hashSize); if (!r) r = SrpHashUpdate(&srp->client_proof, salt, saltSz); return r; @@ -436,7 +435,7 @@ int wc_SrpSetPassword(Srp* srp, const byte* password, word32 size) { SrpHash hash; byte digest[SRP_MAX_DIGEST_SIZE]; - word32 digestSz; + int digestSz; int r; if (!srp || !password || srp->side != SRP_CLIENT_SIDE) @@ -446,6 +445,8 @@ int wc_SrpSetPassword(Srp* srp, const byte* password, word32 size) return SRP_CALL_ORDER_E; digestSz = SrpHashSize(srp->type); + if (digestSz < 0) + return digestSz; /* digest = H(username | ':' | password) */ r = SrpHashInit(&hash, srp->type, srp->heap); @@ -458,12 +459,12 @@ int wc_SrpSetPassword(Srp* srp, const byte* password, word32 size) /* digest = H(salt | H(username | ':' | password)) */ if (!r) r = SrpHashInit(&hash, srp->type, srp->heap); if (!r) r = SrpHashUpdate(&hash, srp->salt, srp->saltSz); - if (!r) r = SrpHashUpdate(&hash, digest, digestSz); + if (!r) r = SrpHashUpdate(&hash, digest, (word32)digestSz); if (!r) r = SrpHashFinal(&hash, digest); SrpHashFree(&hash); /* Set x (private key) */ - if (!r) r = mp_read_unsigned_bin(&srp->auth, digest, digestSz); + if (!r) r = mp_read_unsigned_bin(&srp->auth, digest, (word32)digestSz); ForceZero(digest, SRP_MAX_DIGEST_SIZE); @@ -572,10 +573,15 @@ int wc_SrpGetPublic(Srp* srp, byte* pub, word32* size) #endif word32 modulusSz; int r; + int hashSize; if (!srp || !pub || !size) return BAD_FUNC_ARG; + hashSize = SrpHashSize(srp->type); + if (hashSize < 0) + return hashSize; + if (mp_iszero(&srp->auth) == MP_YES) return SRP_CALL_ORDER_E; @@ -616,7 +622,7 @@ int wc_SrpGetPublic(Srp* srp, byte* pub, word32* size) { r = mp_init_multi(i, j, 0, 0, 0, 0); } - if (!r) r = mp_read_unsigned_bin(i, srp->k,SrpHashSize(srp->type)); + if (!r) r = mp_read_unsigned_bin(i, srp->k, (word32)hashSize); if (!r) r = mp_iszero(i) == MP_YES ? SRP_BAD_KEY_E : 0; if (!r) r = mp_exptmod(&srp->g, &srp->priv, &srp->N, pubkey); if (!r) r = mp_mulmod(i, &srp->auth, &srp->N, j); @@ -654,17 +660,22 @@ static int wc_SrpSetKey(Srp* srp, byte* secret, word32 size) { SrpHash hash; byte digest[SRP_MAX_DIGEST_SIZE]; - word32 i, j, digestSz = SrpHashSize(srp->type); + word32 i, j; + int digestSz; byte counter[4]; int r = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + digestSz = SrpHashSize(srp->type); + if (digestSz < 0) + return digestSz; + XMEMSET(digest, 0, SRP_MAX_DIGEST_SIZE); - srp->key = (byte*)XMALLOC(2 * digestSz, srp->heap, DYNAMIC_TYPE_SRP); + srp->key = (byte*)XMALLOC(2 * (word32)digestSz, srp->heap, DYNAMIC_TYPE_SRP); if (srp->key == NULL) return MEMORY_E; - srp->keySz = 2 * digestSz; + srp->keySz = 2 * (word32)digestSz; for (i = j = 0; j < srp->keySz; i++) { counter[0] = (byte)(i >> 24); @@ -677,7 +688,7 @@ static int wc_SrpSetKey(Srp* srp, byte* secret, word32 size) if (!r) r = SrpHashUpdate(&hash, counter, 4); if (!r) { - if (j + digestSz > srp->keySz) { + if (j + (word32)digestSz > srp->keySz) { r = SrpHashFinal(&hash, digest); XMEMCPY(srp->key + j, digest, srp->keySz - j); j = srp->keySz; @@ -685,7 +696,7 @@ static int wc_SrpSetKey(Srp* srp, byte* secret, word32 size) else { r = SrpHashFinal(&hash, srp->key + j); - j += digestSz; + j += (word32)digestSz; } } SrpHashFree(&hash); @@ -715,7 +726,8 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, mp_int u[1], s[1], temp1[1], temp2[1]; #endif byte *secret = NULL; - word32 i, secretSz, digestSz; + word32 i, secretSz; + int digestSz; byte pad = 0; int r; @@ -761,6 +773,11 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, goto out; digestSz = SrpHashSize(srp->type); + if (digestSz < 0) { + r = digestSz; + goto out; + } + secretSz = (word32)mp_unsigned_bin_size(&srp->N); if ((secretSz < clientPubKeySz) || (secretSz < serverPubKeySz)) { @@ -795,7 +812,7 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, /* set u */ if ((r = SrpHashFinal(hash, digest))) goto out; - if ((r = mp_read_unsigned_bin(u, digest, SrpHashSize(srp->type)))) + if ((r = mp_read_unsigned_bin(u, digest, (word32)digestSz))) goto out; SrpHashFree(hash); @@ -804,7 +821,7 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, if (srp->side == SRP_CLIENT_SIDE) { /* temp1 = B - k * v; rejects k == 0, B == 0 and B >= N. */ - if ((r = mp_read_unsigned_bin(temp1, srp->k, digestSz))) + if ((r = mp_read_unsigned_bin(temp1, srp->k, (word32)digestSz))) goto out; if (mp_iszero(temp1) == MP_YES) { r = SRP_BAD_KEY_E; @@ -940,11 +957,16 @@ int wc_SrpComputeKey(Srp* srp, byte* clientPubKey, word32 clientPubKeySz, int wc_SrpGetProof(Srp* srp, byte* proof, word32* size) { int r; + int hashSize; if (!srp || !proof || !size) return BAD_FUNC_ARG; - if (*size < SrpHashSize(srp->type)) + hashSize = SrpHashSize(srp->type); + if (hashSize < 0) + return ALGO_ID_E; + + if (*size < (word32)hashSize) return BUFFER_E; if ((r = SrpHashFinal(srp->side == SRP_CLIENT_SIDE @@ -952,7 +974,7 @@ int wc_SrpGetProof(Srp* srp, byte* proof, word32* size) : &srp->server_proof, proof)) != 0) return r; - *size = SrpHashSize(srp->type); + *size = (word32)hashSize; if (srp->side == SRP_CLIENT_SIDE) { /* server proof = H( A | client proof | K) */ @@ -967,11 +989,16 @@ int wc_SrpVerifyPeersProof(Srp* srp, byte* proof, word32 size) { byte digest[SRP_MAX_DIGEST_SIZE]; int r; + int hashSize; if (!srp || !proof) return BAD_FUNC_ARG; - if (size != SrpHashSize(srp->type)) + hashSize = SrpHashSize(srp->type); + if (hashSize < 0) + return ALGO_ID_E; + + if (size != (word32)hashSize) return BUFFER_E; r = SrpHashFinal(srp->side == SRP_CLIENT_SIDE ? &srp->server_proof diff --git a/src/wolfcrypt/src/tfm.c b/src/wolfcrypt/src/tfm.c index 5b16871..5bd7328 100644 --- a/src/wolfcrypt/src/tfm.c +++ b/src/wolfcrypt/src/tfm.c @@ -1,6 +1,6 @@ /* tfm.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,7 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - +#include /* * Based on public domain TomsFastMath 0.10 by Tom St Denis, tomstdenis@iahu.ca, @@ -31,13 +31,6 @@ * to fit wolfSSL's needs. */ -#ifdef HAVE_CONFIG_H - #include -#endif - -/* in case user set USE_FAST_MATH there */ -#include - #ifdef USE_FAST_MATH #ifdef NO_INLINE @@ -4575,6 +4568,9 @@ void fp_zero(fp_int *a) void fp_clear(fp_int *a) { +#ifdef HAVE_FIPS + fp_forcezero(a); +#else int size; a->used = 0; a->sign = FP_ZPOS; @@ -4585,6 +4581,7 @@ void fp_clear(fp_int *a) #endif XMEMSET(a->dp, 0, size * sizeof(fp_digit)); fp_free(a); +#endif } void fp_forcezero (mp_int * a) diff --git a/src/wolfcrypt/src/wc_dsp.c b/src/wolfcrypt/src/wc_dsp.c index c6c76c2..09c7ea1 100644 --- a/src/wolfcrypt/src/wc_dsp.c +++ b/src/wolfcrypt/src/wc_dsp.c @@ -1,6 +1,6 @@ /* wc_dsp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include -#include -#include #ifdef NO_INLINE #include #else diff --git a/src/wolfcrypt/src/wc_encrypt.c b/src/wolfcrypt/src/wc_encrypt.c index 9393a69..b1e8b82 100644 --- a/src/wolfcrypt/src/wc_encrypt.c +++ b/src/wolfcrypt/src/wc_encrypt.c @@ -1,6 +1,6 @@ /* wc_encrypt.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,23 +19,17 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include -#ifdef HAVE_CONFIG_H - #include -#endif - -#include #include #include #include #include #include #include -#include #include #include #include -#include #ifdef NO_INLINE #include @@ -455,10 +449,12 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, #if defined(WOLFSSL_AES_256) case PBE_AES256_CBC: switch(shaOid) { + #ifndef NO_SHA256 case HMAC_SHA256_OID: typeH = WC_SHA256; derivedLen = 32; break; + #endif #ifndef NO_SHA default: typeH = WC_SHA; @@ -471,10 +467,12 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, #if defined(WOLFSSL_AES_128) case PBE_AES128_CBC: switch(shaOid) { + #ifndef NO_SHA256 case HMAC_SHA256_OID: typeH = WC_SHA256; derivedLen = 16; break; + #endif #ifndef NO_SHA default: typeH = WC_SHA; diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index b2a3bf8..9de58da 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -1,6 +1,6 @@ /* wc_lms.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #if defined(WOLFSSL_HAVE_LMS) && defined(WOLFSSL_WC_LMS) #include @@ -352,14 +346,14 @@ static const wc_LmsParamsMap wc_lms_map[] = { WC_SHA256_192_DIGEST_SIZE) }, #endif #if LMS_MAX_HEIGHT >= 20 - { WC_LMS_PARM_L1_H20_W2 , "LMS/HSS_SHA256/192_L1_H20_W2", - LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W2, + { WC_LMS_PARM_SHA256_192_L1_H20_W2 , "LMS/HSS_SHA256/192_L1_H20_W2", + LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, - { WC_LMS_PARM_L1_H20_W4 , "LMS/HSS_SHA256/192_L1_H20_W4", - LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W4, + { WC_LMS_PARM_SHA256_192_L1_H20_W4 , "LMS/HSS_SHA256/192_L1_H20_W4", + LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, - { WC_LMS_PARM_L1_H20_W8 , "LMS/HSS_SHA256/192_L1_H20_W8", - LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M32_H20, LMOTS_SHA256_N32_W8, + { WC_LMS_PARM_SHA256_192_L1_H20_W8 , "LMS/HSS_SHA256/192_L1_H20_W8", + LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #endif #endif /* WOLFSSL_LMS_SHA256_192 */ @@ -1162,7 +1156,8 @@ int wc_LmsKey_ImportPubRaw(LmsKey* key, const byte* in, word32 inLen) if (ret == 0) { XMEMCPY(key->pub, in, inLen); - key->state = WC_LMS_STATE_VERIFYONLY; + if (key->state != WC_LMS_STATE_OK) + key->state = WC_LMS_STATE_VERIFYONLY; } return ret; @@ -1263,4 +1258,28 @@ int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, return ret; } +/* Get the Key ID from the raw private key data. + * + * PRIV = Q | PARAMS | SEED | I + * where I is the Key ID. + * + * @param [in] priv Private key data. + * @param [in] privSz Size of private key data. + * @param Pointer to 16 byte Key ID in the private key. + * @return NULL on failure. + */ +const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz) +{ + word32 seedSz = privSz - LMS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN - LMS_I_LEN; + + if (priv == NULL) { + return NULL; + } + if ((seedSz != WC_SHA256_192_DIGEST_SIZE) && + (seedSz != WC_SHA256_DIGEST_SIZE)) { + return NULL; + } + return priv - LMS_I_LEN; +} + #endif /* WOLFSSL_HAVE_LMS && WOLFSSL_WC_LMS */ diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c index 44bff83..47b60a6 100644 --- a/src/wolfcrypt/src/wc_lms_impl.c +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -1,6 +1,6 @@ /* wc_lms_impl.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -37,13 +37,9 @@ * Enable when memory is limited. */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include #include -#include #ifdef NO_INLINE #include @@ -1339,10 +1335,10 @@ static void wc_lmots_public_key_encode(const LmsParams* params, const byte* priv_i = priv + LMS_Q_LEN + params->hash_len; /* u32str(type) || ... || T(1) */ - c32toa(params->lmsType, pub); + c32toa(params->lmsType & LMS_H_W_MASK, pub); pub += 4; /* u32str(type) || u32str(otstype) || ... || T(1) */ - c32toa(params->lmOtsType, pub); + c32toa(params->lmOtsType & LMS_H_W_MASK, pub); pub += 4; /* u32str(type) || u32str(otstype) || I || T(1) */ XMEMCPY(pub, priv_i, LMS_I_LEN); @@ -1365,14 +1361,14 @@ static int wc_lmots_public_key_check(const LmsParams* params, const byte* pub) ato32(pub, &type); pub += 4; /* Compare with parameters. */ - if (type != params->lmsType) { + if (type != (params->lmsType & LMS_H_W_MASK)) { ret = PUBLIC_KEY_E; } if (ret == 0) { /* Get node hash and Winternitz width type. */ ato32(pub, &type); /* Compare with parameters. */ - if (type != params->lmOtsType) { + if (type != (params->lmOtsType & LMS_H_W_MASK)) { ret = PUBLIC_KEY_E; } } @@ -2097,8 +2093,10 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, #endif /* WOLFSSL_SMALL_STACK */ /* Public key, root node, is top of data stack. */ - XMEMCPY(stack, stackCache->stack, params->height * params->hash_len); - sp = stack + stackCache->offset; + if (ret == 0) { + XMEMCPY(stack, stackCache->stack, params->height * params->hash_len); + sp = stack + stackCache->offset; + } /* Compute all nodes requested. */ for (i = min_idx; (ret == 0) && (i <= max_idx); i++) { @@ -2193,7 +2191,7 @@ static int wc_lms_treehash_update(LmsState* state, LmsPrivState* privState, } } - if (!useRoot) { + if (!useRoot && (ret == 0)) { /* Copy stack back. */ XMEMCPY(stackCache->stack, stack, params->height * params->hash_len); stackCache->offset = (word32)((size_t)sp - (size_t)stack); @@ -2248,7 +2246,7 @@ static int wc_lms_sign(LmsState* state, const byte* priv, const byte* msg, s += LMS_Q_LEN; /* ots_signature = sig = u32str(type) || ... */ - c32toa(state->params->lmOtsType, s); + c32toa(state->params->lmOtsType & LMS_H_W_MASK, s); s += LMS_TYPE_LEN; /* Sign this level. * S = u32str(q) || ots_signature || ... */ @@ -2257,7 +2255,7 @@ static int wc_lms_sign(LmsState* state, const byte* priv, const byte* msg, /* Skip over ots_signature. */ s += params->hash_len + params->p * params->hash_len; /* S = u32str(q) || ots_signature || u32str(type) || ... */ - c32toa(params->lmsType, s); + c32toa(params->lmsType & LMS_H_W_MASK, s); } return ret; @@ -2278,13 +2276,13 @@ static void wc_lms_sig_copy(const LmsParams* params, const byte* y, XMEMCPY(sig, priv, LMS_Q_LEN); sig += LMS_Q_LEN; /* S = u32str(q) || ... */ - c32toa(params->lmOtsType, sig); + c32toa(params->lmOtsType & LMS_H_W_MASK, sig); sig += LMS_TYPE_LEN; /* S = u32str(q) || ots_signature || ... */ XMEMCPY(sig, y, params->hash_len + params->p * params->hash_len); sig += params->hash_len + params->p * params->hash_len; /* S = u32str(q) || ots_signature || u32str(type) || ... */ - c32toa(params->lmsType, sig); + c32toa(params->lmsType & LMS_H_W_MASK, sig); } #endif /* !WOLFSSL_WC_LMS_SMALL && !WOLFSSL_LMS_NO_SIG_CACHE */ #endif /* !WOLFSSL_LMS_VERIFY_ONLY */ @@ -3478,7 +3476,9 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, /* Build from bottom up. */ for (i = params->levels - 1; (ret == 0) && (i >= 0); i--) { byte* p = priv + i * (LMS_Q_LEN + params->hash_len + LMS_I_LEN); + #if !defined(WOLFSSL_LMS_MAX_LEVELS) || WOLFSSL_LMS_MAX_LEVELS > 1 byte* root = NULL; + #endif #ifndef WOLFSSL_LMS_NO_SIG_CACHE int store_p = 0; word32 q_32 = LMS_Q_AT_LEVEL(q, params->levels, i, @@ -3489,10 +3489,12 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, /* Move to start of next signature at this level. */ sig -= LMS_SIG_LEN(params->height, params->p, params->hash_len); + #if !defined(WOLFSSL_LMS_MAX_LEVELS) || WOLFSSL_LMS_MAX_LEVELS > 1 if (i != 0) { /* Put root node into signature at this index. */ root = sig - params->hash_len; } + #endif #ifndef WOLFSSL_LMS_NO_SIG_CACHE /* Check if we have a cached version of C and the p hashes that we @@ -3528,10 +3530,12 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, /* Copy the authentication path out of the private key. */ XMEMCPY(s, priv_key->state[i].auth_path, params->height * params->hash_len); + #if !defined(WOLFSSL_LMS_MAX_LEVELS) || WOLFSSL_LMS_MAX_LEVELS > 1 /* Copy the root node into signature unless at top. */ if (i != 0) { XMEMCPY(root, priv_key->state[i].root, params->hash_len); } + #endif } if ((ret == 0) && (i != 0)) { /* Create public data for this level if there is another. */ diff --git a/src/wolfcrypt/src/wc_mlkem.c b/src/wolfcrypt/src/wc_mlkem.c new file mode 100644 index 0000000..a370279 --- /dev/null +++ b/src/wolfcrypt/src/wc_mlkem.c @@ -0,0 +1,2070 @@ +/* wc_mlkem.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Implementation based on FIPS 203: + * https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf + * + * Original implementation based on NIST 3rd Round submission package. + * See link at: + * https://csrc.nist.gov/Projects/post-quantum-cryptography/ + * post-quantum-cryptography-standardization/round-3-submissions + */ + +/* Possible Kyber options: + * + * WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM Default: OFF + * Uses less dynamic memory to perform key generation. + * Has a small performance trade-off. + * Only usable with C implementation. + * + * WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM Default: OFF + * Uses less dynamic memory to perform encapsulation. + * Affects decapsulation too as encapsulation called. + * Has a small performance trade-off. + * Only usable with C implementation. + * + * WOLFSSL_MLKEM_NO_MAKE_KEY Default: OFF + * Disable the make key or key generation API. + * Reduces the code size. + * Turn on when only doing encapsulation. + * + * WOLFSSL_MLKEM_NO_ENCAPSULATE Default: OFF + * Disable the encapsulation API. + * Reduces the code size. + * Turn on when doing make key/decapsulation. + * + * WOLFSSL_MLKEM_NO_DECAPSULATE Default: OFF + * Disable the decapsulation API. + * Reduces the code size. + * Turn on when only doing encapsulation. + * + * WOLFSSL_MLKEM_CACHE_A Default: OFF + * Stores the matrix A during key generation for use in encapsulation when + * performing decapsulation. + * KyberKey is 8KB larger but decapsulation is significantly faster. + * Turn on when performing make key and decapsualtion with same object. + */ + +#include + +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#if defined(USE_INTEL_SPEEDUP) || \ + (defined(__aarch64__) && defined(WOLFSSL_ARMASM)) + #if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) + #error "Can't use small memory with assembly optimized code" + #endif +#endif +#if defined(WOLFSSL_MLKEM_CACHE_A) + #if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) + #error "Can't cache A with small memory code" + #endif +#endif + +#if defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \ + defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) && \ + defined(WOLFSSL_MLKEM_NO_DECAPSULATE) + #error "No ML-KEM operations to be built." +#endif + +#ifdef WOLFSSL_WC_MLKEM + +/******************************************************************************/ + +/* Use SHA3-256 to generate 32-bytes of hash. */ +#define MLKEM_HASH_H mlkem_hash256 +/* Use SHA3-512 to generate 64-bytes of hash. */ +#define MLKEM_HASH_G mlkem_hash512 +/* Use SHAKE-256 as a key derivation function (KDF). */ +#if defined(USE_INTEL_SPEEDUP) || \ + (defined(WOLFSSL_ARMASM) && defined(__aarch64__)) + #define MLKEM_KDF mlkem_kdf +#else + #define MLKEM_KDF wc_Shake256Hash +#endif + +/******************************************************************************/ + +/* Declare variable to make compiler not optimize code in mlkem_from_msg(). */ +volatile sword16 mlkem_opt_blocker = 0; + +/******************************************************************************/ + +/** + * Initialize the Kyber key. + * + * @param [in] type Type of key: + * WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024, + * KYBER512, KYBER768, KYBER1024. + * @param [out] key Kyber key object to initialize. + * @param [in] heap Dynamic memory hint. + * @param [in] devId Device Id. + * @return 0 on success. + * @return BAD_FUNC_ARG when key is NULL or type is unrecognized. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_Init(MlKemKey* key, int type, void* heap, int devId) +{ + int ret = 0; + + /* Validate key. */ + if (key == NULL) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Validate type. */ + switch (type) { + #ifndef WOLFSSL_NO_ML_KEM + case WC_ML_KEM_512: + #ifndef WOLFSSL_WC_ML_KEM_512 + /* Code not compiled in for Kyber-512. */ + ret = NOT_COMPILED_IN; + #endif + break; + case WC_ML_KEM_768: + #ifndef WOLFSSL_WC_ML_KEM_768 + /* Code not compiled in for Kyber-768. */ + ret = NOT_COMPILED_IN; + #endif + break; + case WC_ML_KEM_1024: + #ifndef WOLFSSL_WC_ML_KEM_1024 + /* Code not compiled in for Kyber-1024. */ + ret = NOT_COMPILED_IN; + #endif + break; + #endif + #ifdef WOLFSSL_MLKEM_KYBER + case KYBER512: + #ifndef WOLFSSL_KYBER512 + /* Code not compiled in for Kyber-512. */ + ret = NOT_COMPILED_IN; + #endif + break; + case KYBER768: + #ifndef WOLFSSL_KYBER768 + /* Code not compiled in for Kyber-768. */ + ret = NOT_COMPILED_IN; + #endif + break; + case KYBER1024: + #ifndef WOLFSSL_KYBER1024 + /* Code not compiled in for Kyber-1024. */ + ret = NOT_COMPILED_IN; + #endif + break; + #endif + default: + /* No other values supported. */ + ret = BAD_FUNC_ARG; + break; + } + } + if (ret == 0) { + /* Keep type for parameters. */ + key->type = type; + /* Cache heap pointer. */ + key->heap = heap; + #ifdef WOLF_CRYPTO_CB + /* Cache device id - not used in for this algorithm yet. */ + key->devId = devId; + #endif + key->flags = 0; + + /* Zero out all data. */ + XMEMSET(&key->prf, 0, sizeof(key->prf)); + + /* Initialize the hash algorithm object. */ + ret = mlkem_hash_new(&key->hash, heap, devId); + } + if (ret == 0) { + /* Initialize the PRF algorithm object. */ + ret = mlkem_prf_new(&key->prf, heap, devId); + } + if (ret == 0) { + mlkem_init(); + } + + (void)devId; + + return ret; +} + +/** + * Free the Kyber key object. + * + * @param [in, out] key Kyber key object to dispose of. + * @return 0 on success. + */ +int wc_MlKemKey_Free(MlKemKey* key) +{ + if (key != NULL) { + /* Dispose of PRF object. */ + mlkem_prf_free(&key->prf); + /* Dispose of hash object. */ + mlkem_hash_free(&key->hash); + /* Ensure all private data is zeroed. */ + ForceZero(&key->hash, sizeof(key->hash)); + ForceZero(&key->prf, sizeof(key->prf)); + ForceZero(key->priv, sizeof(key->priv)); + ForceZero(key->z, sizeof(key->z)); + } + + return 0; +} + +/******************************************************************************/ + +#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY +/** + * Make a Kyber key object using a random number generator. + * + * FIPS 203 - Algorithm 19: ML-KEM.KeyGen() + * Generates an encapsulation key and a corresponding decapsulation key. + * 1: d <- B_32 > d is 32 random bytes + * 2: z <- B_32 > z is 32 random bytes + * 3: if d == NULL or z == NULL then + * 4: return falsum + * > return an error indication if random bit generation failed + * 5: end if + * 6: (ek,dk) <- ML-KEM.KeyGen_Interal(d, z) + * > run internal key generation algorithm + * &: return (ek,dk) + * + * @param [in, out] key Kyber key object. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rng is NULL. + * @return MEMORY_E when dynamic memory allocation failed. + * @return MEMORY_E when dynamic memory allocation failed. + * @return RNG_FAILURE_E when generating random numbers failed. + * @return DRBG_CONT_FAILURE when random number generator health check fails. + */ +int wc_MlKemKey_MakeKey(MlKemKey* key, WC_RNG* rng) +{ + int ret = 0; + unsigned char rand[WC_ML_KEM_MAKEKEY_RAND_SZ]; + + /* Validate parameters. */ + if ((key == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Generate random to use with PRFs. + * Step 1: d is 32 random bytes + * Step 2: z is 32 random bytes + */ + ret = wc_RNG_GenerateBlock(rng, rand, WC_ML_KEM_SYM_SZ * 2); + /* Step 3: ret is not zero when d == NULL or z == NULL. */ + } + if (ret == 0) { + /* Make a key pair from the random. + * Step 6. run internal key generation algorithm + * Step 7. public and private key are stored in key + */ + ret = wc_KyberKey_MakeKeyWithRandom(key, rand, sizeof(rand)); + } + + /* Ensure seeds are zeroized. */ + ForceZero((void*)rand, (word32)sizeof(rand)); + + /* Step 4: return ret != 0 on falsum or internal key generation failure. */ + return ret; +} + +/** + * Make a Kyber key object using random data. + * + * FIPS 203 - Algorithm 16: ML-KEM.KeyGen_internal(d,z) + * Uses randomness to generate an encapsulation key and a corresponding + * decapsulation key. + * 1: (ek_PKE,dk_PKE) < K-PKE.KeyGen(d) > run key generation for K-PKE + * ... + * + * FIPS 203 - Algorithm 13: K-PKE.KeyGen(d) + * Uses randomness to generate an encryption key and a corresponding decryption + * key. + * 1: (rho,sigma) <- G(d||k)A + * > expand 32+1 bytes to two pseudorandom 32-byte seeds + * 2: N <- 0 + * 3-7: generate matrix A_hat + * 8-11: generate s + * 12-15: generate e + * 16-18: calculate t_hat from A_hat, s and e + * ... + * + * @param [in, out] key Kyber key ovject. + * @param [in] rand Random data. + * @param [in] len Length of random data in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or rand is NULL. + * @return BUFFER_E when length is not WC_ML_KEM_MAKEKEY_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_MakeKeyWithRandom(MlKemKey* key, const unsigned char* rand, + int len) +{ + byte buf[2 * WC_ML_KEM_SYM_SZ + 1]; + byte* rho = buf; + byte* sigma = buf + WC_ML_KEM_SYM_SZ; +#ifndef WOLFSSL_NO_MALLOC + sword16* e = NULL; +#else +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM +#ifndef WOLFSSL_MLKEM_CACHE_A + sword16 e[(WC_ML_KEM_MAX_K + 1) * WC_ML_KEM_MAX_K * MLKEM_N]; +#else + sword16 e[WC_ML_KEM_MAX_K * MLKEM_N]; +#endif +#else + sword16 e[WC_ML_KEM_MAX_K * MLKEM_N]; +#endif +#endif +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM + sword16* a = NULL; +#endif + sword16* s = NULL; + sword16* t = NULL; + int ret = 0; + int k = 0; + + /* Validate parameters. */ + if ((key == NULL) || (rand == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (len != WC_ML_KEM_MAKEKEY_RAND_SZ)) { + ret = BUFFER_E; + } + + if (ret == 0) { + key->flags = 0; + + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + +#ifndef WOLFSSL_NO_MALLOC + if (ret == 0) { + /* Allocate dynamic memory for matrix and error vector. */ +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM +#ifndef WOLFSSL_MLKEM_CACHE_A + /* e (v) | a (m) */ + e = (sword16*)XMALLOC((k + 1) * k * MLKEM_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#else + /* e (v) */ + e = (sword16*)XMALLOC(k * MLKEM_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif +#else + /* e (v) */ + e = (sword16*)XMALLOC(k * MLKEM_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + if (e == NULL) { + ret = MEMORY_E; + } + } +#endif + if (ret == 0) { + const byte* d = rand; + +#ifdef WOLFSSL_MLKEM_CACHE_A + a = key->a; +#elif !defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) + /* Matrix A allocated at end of error vector. */ + a = e + (k * MLKEM_N); +#endif + +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & MLKEM_KYBER) +#endif +#ifdef WOLFSSL_MLKEM_KYBER + { + /* Expand 32 bytes of random to 32. */ + ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, NULL, 0, buf); + } +#endif +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + buf[0] = k; + /* Expand 33 bytes of random to 32. + * Alg 13: Step 1: (rho,sigma) <- G(d||k) + */ + ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, buf, 1, buf); + } +#endif + } + if (ret == 0) { + const byte* z = rand + WC_ML_KEM_SYM_SZ; + s = key->priv; + t = key->pub; + + /* Cache the public seed for use in encapsulation and encoding public + * key. */ + XMEMCPY(key->pubSeed, rho, WC_ML_KEM_SYM_SZ); + /* Cache the z value for decapsulation and encoding private key. */ + XMEMCPY(key->z, z, sizeof(key->z)); + + /* Initialize PRF for use in noise generation. */ + mlkem_prf_init(&key->prf); +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM + /* Generate noise using PRF. + * Alg 13: Steps 8-15: generate s and e + */ + ret = mlkem_get_noise(&key->prf, k, s, e, NULL, sigma); + } + if (ret == 0) { + /* Generate the matrix A. + * Alg 13: Steps 3-7 + */ + ret = mlkem_gen_matrix(&key->prf, a, k, rho, 0); + } + if (ret == 0) { + /* Generate key pair from random data. + * Alg 13: Steps 16-18. + */ + mlkem_keygen(s, t, e, a, k); +#else + /* Generate noise using PRF. + * Alg 13: Steps 8-11: generate s + */ + ret = mlkem_get_noise(&key->prf, k, s, NULL, NULL, sigma); + } + if (ret == 0) { + /* Generate key pair from private vector and seeds. + * Alg 13: Steps 3-7: generate matrix A_hat + * Alg 13: 12-15: generate e + * Alg 13: 16-18: calculate t_hat from A_hat, s and e + */ + ret = mlkem_keygen_seeds(s, t, &key->prf, e, k, rho, sigma); + } + if (ret == 0) { +#endif + /* Private and public key are set/available. */ + key->flags |= MLKEM_FLAG_PRIV_SET | MLKEM_FLAG_PUB_SET; +#ifdef WOLFSSL_MLKEM_CACHE_A + key->flags |= MLKEM_FLAG_A_SET; +#endif + } + +#ifndef WOLFSSL_NO_MALLOC + /* Free dynamic memory allocated in function. */ + if (key != NULL) { + XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif + + return ret; +} +#endif /* !WOLFSSL_MLKEM_NO_MAKE_KEY */ + +/******************************************************************************/ + +/** + * Get the size in bytes of cipher text for key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of cipher text in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_CipherTextSize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the cipher text for the type of this key. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Size of a shared secret in bytes. Always KYBER_SS_SZ. + * + * @param [in] key Kyber key object. Not used. + * @param [out] Size of the shared secret created with a Kyber key. + * @return 0 on success. + * @return 0 to indicate success. + */ +int wc_MlKemKey_SharedSecretSize(MlKemKey* key, word32* len) +{ + (void)key; + + *len = WC_ML_KEM_SS_SZ; + + return 0; +} + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Encapsulate data and derive secret. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE, m, r) + * Uses the encryption key to encrypt a plaintext message using the randomness + * r. + * 1: N <- 0 + * 2: t_hat <- ByteDecode_12(ek_PKE[0:384k]) + * > run ByteDecode_12 k times to decode t_hat + * 3: rho <- ek_PKE[384k : 384K + 32] + * > extract 32-byte seed from ek_PKE + * 4-8: generate matrix A_hat + * 9-12: generate y + * 13-16: generate e_1 + * 17: generate e_2 + * 18-19: calculate u + * 20: mu <- Decompress_1(ByteDecode_1(m)) + * 21: calculate v + * 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) + * > run ByteEncode_d_u and Compress_d_u k times + * 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) + * 24: return c <- (c_1||c_2) + * + * @param [in] key Kyber key object. + * @param [in] m Random bytes. + * @param [in] r Seed to feed to PRF when generating y, e1 and e2. + * @param [out] c Calculated cipher text. + * @return 0 on success. + * @return NOT_COMPILED_IN when key type is not supported. + */ +static int mlkemkey_encapsulate(MlKemKey* key, const byte* m, byte* r, byte* c) +{ + int ret = 0; + sword16* a = NULL; +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM + sword16* mu = NULL; + sword16* e1 = NULL; + sword16* e2 = NULL; +#endif + unsigned int k = 0; + unsigned int compVecSz = 0; +#ifndef WOLFSSL_NO_MALLOC + sword16* y = NULL; +#else +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM + sword16 y[((WC_ML_KEM_MAX_K + 3) * WC_ML_KEM_MAX_K + 3) * MLKEM_N]; +#else + sword16 y[3 * WC_ML_KEM_MAX_K * MLKEM_N]; +#endif +#endif + sword16* u; + sword16* v; + + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER +#ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + +#ifndef WOLFSSL_NO_MALLOC + if (ret == 0) { + /* Allocate dynamic memory for all matrices, vectors and polynomials. */ +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM + y = (sword16*)XMALLOC(((k + 3) * k + 3) * MLKEM_N * sizeof(sword16), + key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#else + y = (sword16*)XMALLOC(3 * k * MLKEM_N * sizeof(sword16), key->heap, + DYNAMIC_TYPE_TMP_BUFFER); +#endif + if (y == NULL) { + ret = MEMORY_E; + } + } +#endif + +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM + if (ret == 0) { + /* Assign allocated dynamic memory to pointers. + * y (b) | a (m) | mu (p) | e1 (p) | e2 (v) | u (v) | v (p) */ + a = y + MLKEM_N * k; + mu = a + MLKEM_N * k * k; + e1 = mu + MLKEM_N; + e2 = e1 + MLKEM_N * k; + + /* Convert msg to a polynomial. + * Step 20: mu <- Decompress_1(ByteDecode_1(m)) */ + mlkem_from_msg(mu, m); + + /* Initialize the PRF for use in the noise generation. */ + mlkem_prf_init(&key->prf); + /* Generate noise using PRF. + * Steps 9-17: generate y, e_1, e_2 + */ + ret = mlkem_get_noise(&key->prf, k, y, e1, e2, r); + } + #ifdef WOLFSSL_MLKEM_CACHE_A + if ((ret == 0) && ((key->flags & MLKEM_FLAG_A_SET) != 0)) { + unsigned int i; + /* Transpose matrix. + * Steps 4-8: generate matrix A_hat (from original) */ + for (i = 0; i < k; i++) { + unsigned int j; + for (j = 0; j < k; j++) { + XMEMCPY(&a[(i * k + j) * MLKEM_N], + &key->a[(j * k + i) * MLKEM_N], + MLKEM_N * 2); + } + } + } + else + #endif /* WOLFSSL_MLKEM_CACHE_A */ + if (ret == 0) { + /* Generate the transposed matrix. + * Step 4-8: generate matrix A_hat */ + ret = mlkem_gen_matrix(&key->prf, a, k, key->pubSeed, 1); + } + if (ret == 0) { + /* Assign remaining allocated dynamic memory to pointers. + * y (v) | a (m) | mu (p) | e1 (p) | r2 (v) | u (v) | v (p)*/ + u = e2 + MLKEM_N; + v = u + MLKEM_N * k; + + /* Perform encapsulation maths. + * Steps 18-19, 21: calculate u and v */ + mlkem_encapsulate(key->pub, u, v, a, y, e1, e2, mu, k); + } +#else /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */ + if (ret == 0) { + /* Assign allocated dynamic memory to pointers. + * y (v) | a (v) | u (v) */ + a = y + MLKEM_N * k; + + /* Initialize the PRF for use in the noise generation. */ + mlkem_prf_init(&key->prf); + /* Generate noise using PRF. + * Steps 9-12: generate y */ + ret = mlkem_get_noise(&key->prf, k, y, NULL, NULL, r); + } + if (ret == 0) { + /* Assign remaining allocated dynamic memory to pointers. + * y (v) | at (v) | u (v) */ + u = a + MLKEM_N * k; + v = a; + + /* Perform encapsulation maths. + * Steps 13-17: generate e_1 and e_2 + * Steps 18-19, 21: calculate u and v */ + ret = mlkem_encapsulate_seeds(key->pub, &key->prf, u, a, y, k, m, + key->pubSeed, r); + } +#endif /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */ + + if (ret == 0) { + byte* c1 = c; + byte* c2 = c + compVecSz; + + #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if (k == WC_ML_KEM_512_K) { + /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */ + mlkem_vec_compress_10(c1, u, k); + /* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */ + mlkem_compress_4(c2, v); + /* Step 24: return c <- (c_1||c_2) */ + } + #endif + #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) + if (k == WC_ML_KEM_768_K) { + /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */ + mlkem_vec_compress_10(c1, u, k); + /* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */ + mlkem_compress_4(c2, v); + /* Step 24: return c <- (c_1||c_2) */ + } + #endif + #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) + if (k == WC_ML_KEM_1024_K) { + /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */ + mlkem_vec_compress_11(c1, u); + /* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */ + mlkem_compress_5(c2, v); + /* Step 24: return c <- (c_1||c_2) */ + } + #endif + } + +#ifndef WOLFSSL_NO_MALLOC + /* Dispose of dynamic memory allocated in function. */ + XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} +#endif + +#ifndef WOLFSSL_MLKEM_NO_ENCAPSULATE +/** + * Encapsulate with random number generator and derive secret. + * + * FIPS 203, Algorithm 20: ML-KEM.Encaps(ek) + * Uses the encapsulation key to generate a shared secret key and an associated + * ciphertext. + * 1: m <- B_32 > m is 32 random bytes + * 2: if m == NULL then + * 3: return falsum + * 4: end if + * 5: (K,c) <- ML-KEM.Encaps_internal(ek,m) + * > run internal encapsulation algorithm + * 6: return (K,c) + * + * @param [in] key Kyber key object. + * @param [out] c Cipher text. + * @param [out] k Shared secret generated. + * @param [in] rng Random number generator. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ct, ss or RNG is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_Encapsulate(MlKemKey* key, unsigned char* c, unsigned char* k, + WC_RNG* rng) +{ + int ret = 0; + unsigned char m[WC_ML_KEM_ENC_RAND_SZ]; + + /* Validate parameters. */ + if ((key == NULL) || (c == NULL) || (k == NULL) || (rng == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Generate seed for use with PRFs. + * Step 1: m is 32 random bytes + */ + ret = wc_RNG_GenerateBlock(rng, m, sizeof(m)); + /* Step 2: ret is not zero when m == NULL. */ + } + if (ret == 0) { + /* Encapsulate with the random. + * Step 5: run internal encapsulation algorithm + */ + ret = wc_KyberKey_EncapsulateWithRandom(key, c, k, m, sizeof(m)); + } + + /* Step 3: return ret != 0 on falsum or internal key generation failure. */ + return ret; +} + +/** + * Encapsulate with random data and derive secret. + * + * FIPS 203, Algorithm 17: ML-KEM.Encaps_internal(ek, m) + * Uses the encapsulation key and randomness to generate a key and an associated + * ciphertext. + * Step 1: (K,r) <- G(m||H(ek)) + * > derive shared secret key K and randomness r + * Step 2: c <- K-PPKE.Encrypt(ek, m, r) + * > encrypt m using K-PKE with randomness r + * Step 3: return (K,c) + * + * @param [out] c Cipher text. + * @param [out] k Shared secret generated. + * @param [in] m Random bytes. + * @param [in] len Length of random bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, c, k or RNG is NULL. + * @return BUFFER_E when len is not WC_ML_KEM_ENC_RAND_SZ. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_EncapsulateWithRandom(MlKemKey* key, unsigned char* c, + unsigned char* k, const unsigned char* m, int len) +{ +#ifdef WOLFSSL_MLKEM_KYBER + byte msg[KYBER_SYM_SZ]; +#endif + byte kr[2 * KYBER_SYM_SZ + 1]; + int ret = 0; +#ifdef WOLFSSL_MLKEM_KYBER + unsigned int cSz = 0; +#endif + + /* Validate parameters. */ + if ((key == NULL) || (c == NULL) || (k == NULL) || (m == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && (len != WC_ML_KEM_ENC_RAND_SZ)) { + ret = BUFFER_E; + } + +#ifdef WOLFSSL_MLKEM_KYBER + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + #endif + break; +#endif + #ifdef WOLFSSL_KYBER512 + case KYBER512: + cSz = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + cSz = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + cSz = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } +#endif + + /* If public hash (h) is not stored against key, calculate it + * (fields set explicitly instead of using decode). + * Step 1: ... H(ek)... + */ + if ((ret == 0) && ((key->flags & MLKEM_FLAG_H_SET) == 0)) { + #ifndef WOLFSSL_NO_MALLOC + byte* pubKey = NULL; + word32 pubKeyLen; + #else + byte pubKey[WC_ML_KEM_MAX_PUBLIC_KEY_SIZE]; + word32 pubKeyLen = WC_ML_KEM_MAX_PUBLIC_KEY_SIZE; + #endif + + #ifndef WOLFSSL_NO_MALLOC + /* Determine how big an encoded public key will be. */ + ret = wc_KyberKey_PublicKeySize(key, &pubKeyLen); + if (ret == 0) { + /* Allocate dynamic memory for encoded public key. */ + pubKey = (byte*)XMALLOC(pubKeyLen, key->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (pubKey == NULL) { + ret = MEMORY_E; + } + } + if (ret == 0) { + #endif + /* Encode public key - h is hash of encoded public key. */ + ret = wc_KyberKey_EncodePublicKey(key, pubKey, pubKeyLen); + #ifndef WOLFSSL_NO_MALLOC + } + /* Dispose of encoded public key. */ + XFREE(pubKey, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif + } + if ((ret == 0) && ((key->flags & MLKEM_FLAG_H_SET) == 0)) { + /* Implementation issue if h not cached and flag set. */ + ret = BAD_STATE_E; + } + +#ifdef WOLFSSL_MLKEM_KYBER + if (ret == 0) { +#ifndef WOLFSSL_NO_ML_KEM + if (key->type & MLKEM_KYBER) +#endif + { + /* Hash random to anonymize as seed data. */ + ret = MLKEM_HASH_H(&key->hash, m, WC_ML_KEM_SYM_SZ, msg); + } + } +#endif + if (ret == 0) { + /* Hash message into seed buffer. */ +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & MLKEM_KYBER) +#endif +#ifdef WOLFSSL_MLKEM_KYBER + { + ret = MLKEM_HASH_G(&key->hash, msg, WC_ML_KEM_SYM_SZ, key->h, + WC_ML_KEM_SYM_SZ, kr); + } +#endif +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + /* Step 1: (K,r) <- G(m||H(ek)) */ + ret = MLKEM_HASH_G(&key->hash, m, WC_ML_KEM_SYM_SZ, key->h, + WC_ML_KEM_SYM_SZ, kr); + } +#endif + } + + if (ret == 0) { + /* Encapsulate the message using the key and the seed. */ +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & MLKEM_KYBER) +#endif +#ifdef WOLFSSL_MLKEM_KYBER + { + ret = mlkemkey_encapsulate(key, msg, kr + WC_ML_KEM_SYM_SZ, c); + } +#endif +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + /* Step 2: c <- K-PKE.Encrypt(ek,m,r) */ + ret = mlkemkey_encapsulate(key, m, kr + WC_ML_KEM_SYM_SZ, c); + } +#endif + } + +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & MLKEM_KYBER) +#endif +#ifdef WOLFSSL_MLKEM_KYBER + { + if (ret == 0) { + /* Hash the cipher text after the seed. */ + ret = MLKEM_HASH_H(&key->hash, c, cSz, kr + WC_ML_KEM_SYM_SZ); + } + if (ret == 0) { + /* Derive the secret from the seed and hash of cipher text. */ + ret = MLKEM_KDF(kr, 2 * WC_ML_KEM_SYM_SZ, k, WC_ML_KEM_SS_SZ); + } + } +#endif +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + if (ret == 0) { + /* return (K,c) */ + XMEMCPY(k, kr, WC_ML_KEM_SS_SZ); + } + } +#endif + + return ret; +} +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE */ + +/******************************************************************************/ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +/* Decapsulate cipher text to the message using key. + * + * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE,c) + * Uses the decryption key to decrypt a ciphertext. + * 1: c1 <- c[0 : 32.d_u.k] + * 2: c2 <= c[32.d_u.k : 32(d_u.k + d_v)] + * 3: u' <= Decompress_d_u(ByteDecode_d_u(c1)) + * 4: v' <= Decompress_d_v(ByteDecode_d_v(c2)) + * ... + * 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) + * 7: m <- ByteEncode_1(Compress_1(w)) + * 8: return m + * + * @param [in] key Kyber key object. + * @param [out] m Message than was encapsulated. + * @param [in] c Cipher text. + * @return 0 on success. + * @return NOT_COMPILED_IN when key type is not supported. + * @return MEMORY_E when dynamic memory allocation failed. + */ +static MLKEM_NOINLINE int mlkemkey_decapsulate(MlKemKey* key, byte* m, + const byte* c) +{ + int ret = 0; + sword16* v; + sword16* w; + unsigned int k = 0; + unsigned int compVecSz; +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + sword16* u = NULL; +#else + sword16 u[(WC_ML_KEM_MAX_K + 1) * MLKEM_N]; +#endif + + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM +#ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER +#ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ; + break; +#endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + if (ret == 0) { + /* Allocate dynamic memory for a vector and a polynomial. */ + u = (sword16*)XMALLOC((k + 1) * MLKEM_N * sizeof(sword16), key->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (u == NULL) { + ret = MEMORY_E; + } + } +#endif + if (ret == 0) { + /* Step 1: c1 <- c[0 : 32.d_u.k] */ + const byte* c1 = c; + /* Step 2: c2 <= c[32.d_u.k : 32(d_u.k + d_v)] */ + const byte* c2 = c + compVecSz; + + /* Assign allocated dynamic memory to pointers. + * u (v) | v (p) */ + v = u + k * MLKEM_N; + w = u; + + #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if (k == WC_ML_KEM_512_K) { + /* Step 3: u' <= Decompress_d_u(ByteDecode_d_u(c1)) */ + mlkem_vec_decompress_10(u, c1, k); + /* Step 4: v' <= Decompress_d_v(ByteDecode_d_v(c2)) */ + mlkem_decompress_4(v, c2); + } + #endif + #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) + if (k == WC_ML_KEM_768_K) { + /* Step 3: u' <= Decompress_d_u(ByteDecode_d_u(c1)) */ + mlkem_vec_decompress_10(u, c1, k); + /* Step 4: v' <= Decompress_d_v(ByteDecode_d_v(c2)) */ + mlkem_decompress_4(v, c2); + } + #endif + #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) + if (k == WC_ML_KEM_1024_K) { + /* Step 3: u' <= Decompress_d_u(ByteDecode_d_u(c1)) */ + mlkem_vec_decompress_11(u, c1); + /* Step 4: v' <= Decompress_d_v(ByteDecode_d_v(c2)) */ + mlkem_decompress_5(v, c2); + } + #endif + + /* Decapsulate the cipher text into polynomial. + * Step 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) */ + mlkem_decapsulate(key->priv, w, u, v, k); + + /* Convert the polynomial into a array of bytes (message). + * Step 7: m <- ByteEncode_1(Compress_1(w)) */ + mlkem_to_msg(m, w); + /* Step 8: return m */ + } + +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + /* Dispose of dynamically memory allocated in function. */ + XFREE(u, key->heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +/** + * Decapsulate the cipher text to calculate the shared secret. + * + * Validates the cipher text by encapsulating and comparing with data passed in. + * + * FIPS 203, Algorithm 21: ML-KEM.Decaps(dk, c) + * Uses the decapsulation key to produce a shared secret key from a ciphertext. + * 1: K' <- ML-KEM.Decaps_internal(dk,c) + * > run internal decapsulation algorithm + * 2: return K' + * + * FIPS 203, Algorithm 18: ML-KEM.Decaps_internal(dk, c) + * Uses the decapsulation key to produce a shared secret key from a ciphertext. + * ... + * 1: dk_PKE <- dk[0 : 384k] + * > extract (from KEM decaps key) the PKE decryption key + * 2: ek_PKE <- dk[384k : 768l + 32] + * > extract PKE encryption key + * 3: h <- dk[768K + 32 : 768k + 64] + * > extract hash of PKE encryption key + * 4: z <- dk[768K + 64 : 768k + 96] + * > extract implicit rejection value + * 5: m' <- K-PKE.Decrypt(dk_PKE, c) > decrypt ciphertext + * 6: (K', r') <- G(m'||h) + * 7: K_bar <- J(z||c) + * 8: c' <- K-PKE.Encrypt(ek_PKE, m', r') + * > re-encrypt using the derived randomness r' + * 9: if c != c' then + * 10: K' <= K_bar + * > if ciphertexts do not match, "implicitly reject" + * 11: end if + * 12: return K' + * + * @param [in] key Kyber key object. + * @param [out] ss Shared secret. + * @param [in] ct Cipher text. + * @param [in] len Length of cipher text. + * @return 0 on success. + * @return BAD_FUNC_ARG when key, ss or cr are NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the length of cipher text for the key type. + * @return MEMORY_E when dynamic memory allocation failed. + */ +int wc_MlKemKey_Decapsulate(MlKemKey* key, unsigned char* ss, + const unsigned char* ct, word32 len) +{ + byte msg[WC_ML_KEM_SYM_SZ]; + byte kr[2 * WC_ML_KEM_SYM_SZ + 1]; + int ret = 0; + unsigned int ctSz = 0; + unsigned int i = 0; + int fail = 0; +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + byte* cmp = NULL; +#else + byte cmp[WC_ML_KEM_MAX_CIPHER_TEXT_SIZE]; +#endif + + /* Validate parameters. */ + if ((key == NULL) || (ss == NULL) || (ct == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish cipher text size based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + ctSz = WC_ML_KEM_512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + ctSz = WC_ML_KEM_768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + ctSz = WC_ML_KEM_1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + ctSz = KYBER512_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + ctSz = KYBER768_CIPHER_TEXT_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + ctSz = KYBER1024_CIPHER_TEXT_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + /* Ensure the cipher text passed in is the correct size. */ + if ((ret == 0) && (len != ctSz)) { + ret = BUFFER_E; + } + +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + if (ret == 0) { + /* Allocate memory for cipher text that is generated. */ + cmp = (byte*)XMALLOC(ctSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (cmp == NULL) { + ret = MEMORY_E; + } + } +#endif + + if (ret == 0) { + /* Decapsulate the cipher text. */ + ret = mlkemkey_decapsulate(key, msg, ct); + } + if (ret == 0) { + /* Hash message into seed buffer. */ + ret = MLKEM_HASH_G(&key->hash, msg, WC_ML_KEM_SYM_SZ, key->h, + WC_ML_KEM_SYM_SZ, kr); + } + if (ret == 0) { + /* Encapsulate the message. */ + ret = mlkemkey_encapsulate(key, msg, kr + WC_ML_KEM_SYM_SZ, cmp); + } + if (ret == 0) { + /* Compare generated cipher text with that passed in. */ + fail = mlkem_cmp(ct, cmp, ctSz); + +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + if (key->type & MLKEM_KYBER) +#endif +#ifdef WOLFSSL_MLKEM_KYBER + { + /* Hash the cipher text after the seed. */ + ret = MLKEM_HASH_H(&key->hash, ct, ctSz, kr + WC_ML_KEM_SYM_SZ); + if (ret == 0) { + /* Change seed to z on comparison failure. */ + for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) { + kr[i] ^= (kr[i] ^ key->z[i]) & fail; + } + + /* Derive the secret from the seed and hash of cipher text. */ + ret = MLKEM_KDF(kr, 2 * WC_ML_KEM_SYM_SZ, ss, WC_ML_KEM_SS_SZ); + } + } +#endif +#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM) + else +#endif +#ifndef WOLFSSL_NO_ML_KEM + { + ret = mlkem_derive_secret(&key->prf, key->z, ct, ctSz, msg); + if (ret == 0) { + /* Set secret to kr or fake secret on comparison failure. */ + for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) { + ss[i] = kr[i] ^ ((kr[i] ^ msg[i]) & fail); + } + } + } +#endif + } + +#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) + /* Dispose of dynamic memory allocated in function. */ + if (key != NULL) { + XFREE(cmp, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif + + return ret; +} +#endif /* WOLFSSL_MLKEM_NO_DECAPSULATE */ + +/******************************************************************************/ + +/** + * Get the public key and public seed from bytes. + * + * FIPS 203, Algorithm 14 K-PKE.Encrypt(ek_PKE, m, r) + * ... + * 2: t <- ByteDecode_12(ek_PKE[0 : 384k]) + * 3: rho <- ek_PKE[384k : 384k + 32] + * ... + * + * @param [out] pub Public key - vector. + * @param [out] pubSeed Public seed. + * @param [in] p Public key data. + * @param [in] k Number of polynomials in vector. + */ +static void mlkemkey_decode_public(sword16* pub, byte* pubSeed, const byte* p, + unsigned int k) +{ + unsigned int i; + + /* Decode public key that is vector of polynomials. + * Step 2: t <- ByteDecode_12(ek_PKE[0 : 384k]) */ + mlkem_from_bytes(pub, p, k); + p += k * WC_ML_KEM_POLY_SIZE; + + /* Read public key seed. + * Step 3: rho <- ek_PKE[384k : 384k + 32] */ + for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) { + pubSeed[i] = p[i]; + } +} + +/** + * Decode the private key. + * + * Private Vector | Public Key | Public Hash | Randomizer + * + * FIPS 203, Algorithm 18: ML-KEM.Decaps_internal(dk, c) + * 1: dk_PKE <- dk[0 : 384k] + * > extract (from KEM decaps key) the PKE decryption key + * 2: ek_PKE <- dk[384k : 768l + 32] + * > extract PKE encryption key + * 3: h <- dk[768K + 32 : 768k + 64] + * > extract hash of PKE encryption key + * 4: z <- dk[768K + 64 : 768k + 96] + * > extract implicit rejection value + * + * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE, c) + * ... + * 5: s_hat <= ByteDecode_12(dk_PKE) + * ... + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_MlKemKey_DecodePrivateKey(MlKemKey* key, const unsigned char* in, + word32 len) +{ + int ret = 0; + word32 privLen = 0; + word32 pubLen = 0; + unsigned int k = 0; + const unsigned char* p = in; + + /* Validate parameters. */ + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + privLen = KYBER512_PRIVATE_KEY_SIZE; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + privLen = KYBER768_PRIVATE_KEY_SIZE; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + privLen = KYBER1024_PRIVATE_KEY_SIZE; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Decode private key that is vector of polynomials. + * Alg 18 Step 1: dk_PKE <- dk[0 : 384k] + * Alg 15 Step 5: s_hat <- ByteDecode_12(dk_PKE) */ + mlkem_from_bytes(key->priv, p, k); + p += k * WC_ML_KEM_POLY_SIZE; + + /* Decode the public key that is after the private key. */ + mlkemkey_decode_public(key->pub, key->pubSeed, p, k); + p += pubLen; + + /* Copy the hash of the encoded public key that is after public key. */ + XMEMCPY(key->h, p, sizeof(key->h)); + p += WC_ML_KEM_SYM_SZ; + /* Copy the z (randomizer) that is after hash. */ + XMEMCPY(key->z, p, sizeof(key->z)); + + /* Set flags */ + key->flags |= MLKEM_FLAG_H_SET | MLKEM_FLAG_BOTH_SET; + } + + return ret; +} + +/** + * Decode public key. + * + * Public vector | Public Seed + * + * @param [in, out] key Kyber key object. + * @param [in] in Buffer holding encoded key. + * @param [in] len Length of data in buffer. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or in is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + * @return BUFFER_E when len is not the correct size. + */ +int wc_MlKemKey_DecodePublicKey(MlKemKey* key, const unsigned char* in, + word32 len) +{ + int ret = 0; + word32 pubLen = 0; + unsigned int k = 0; + const unsigned char* p = in; + + if ((key == NULL) || (in == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Establish parameters based on key type. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Ensure the data is the correct length for the key type. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + mlkemkey_decode_public(key->pub, key->pubSeed, p, k); + + /* Calculate public hash. */ + ret = MLKEM_HASH_H(&key->hash, in, len, key->h); + } + if (ret == 0) { + /* Record public key and public hash set. */ + key->flags |= MLKEM_FLAG_PUB_SET | MLKEM_FLAG_H_SET; + } + + return ret; +} + +/** + * Get the size in bytes of encoded private key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded private key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_PrivateKeySize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the encoded private key for the type of this + * key. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Get the size in bytes of encoded public key for the key. + * + * @param [in] key Kyber key object. + * @param [out] len Length of encoded public key in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or len is NULL. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_PublicKeySize(MlKemKey* key, word32* len) +{ + int ret = 0; + + /* Validate parameters. */ + if ((key == NULL) || (len == NULL)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + /* Return in 'len' size of the encoded public key for the type of this + * key. */ + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + *len = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + *len = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + *len = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + *len = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + *len = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + *len = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + + return ret; +} + +/** + * Encode the private key. + * + * Private Vector | Public Key | Public Hash | Randomizer + * + * FIPS 203, Algorithm 16: ML-KEM.KeyGen_internal(d,z) + * ... + * 3: dk <- (dk_PKE||ek||H(ek)||z) + * ... + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 20: dk_PKE <- ByteEncode_12(s_hat) + * ... + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or private/public key not + * available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_EncodePrivateKey(MlKemKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int k = 0; + unsigned int pubLen = 0; + unsigned int privLen = 0; + unsigned char* p = out; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && + ((key->flags & MLKEM_FLAG_BOTH_SET) != MLKEM_FLAG_BOTH_SET)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + privLen = KYBER512_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + privLen = KYBER768_PRIVATE_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + privLen = KYBER1024_PRIVATE_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != privLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + /* Encode private key that is vector of polynomials. */ + mlkem_to_bytes(p, key->priv, k); + p += WC_ML_KEM_POLY_SIZE * k; + + /* Encode public key. */ + ret = wc_KyberKey_EncodePublicKey(key, p, pubLen); + p += pubLen; + } + /* Ensure hash of public key is available. */ + if ((ret == 0) && ((key->flags & MLKEM_FLAG_H_SET) == 0)) { + ret = MLKEM_HASH_H(&key->hash, p - pubLen, pubLen, key->h); + } + if (ret == 0) { + /* Public hash is available. */ + key->flags |= MLKEM_FLAG_H_SET; + /* Append public hash. */ + XMEMCPY(p, key->h, sizeof(key->h)); + p += WC_ML_KEM_SYM_SZ; + /* Append z (randomizer). */ + XMEMCPY(p, key->z, sizeof(key->z)); + } + + return ret; +} + +/** + * Encode the public key. + * + * Public vector | Public Seed + * + * FIPS 203, Algorithm 16: ML-KEM.KeyGen_internal(d,z) + * ... + * 2: ek <- ek_PKE + * ... + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 19: ek_PKE <- ByteEncode_12(t_hat)||rho + * ... + * + * @param [in] key Kyber key object. + * @param [out] out Buffer to hold data. + * @param [in] len Size of buffer in bytes. + * @return 0 on success. + * @return BAD_FUNC_ARG when key or out is NULL or public key not available. + * @return NOT_COMPILED_IN when key type is not supported. + */ +int wc_MlKemKey_EncodePublicKey(MlKemKey* key, unsigned char* out, word32 len) +{ + int ret = 0; + unsigned int k = 0; + unsigned int pubLen = 0; + unsigned char* p = out; + + if ((key == NULL) || (out == NULL)) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && + ((key->flags & MLKEM_FLAG_PUB_SET) != MLKEM_FLAG_PUB_SET)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) { + switch (key->type) { +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_ML_KEM_512 + case WC_ML_KEM_512: + k = WC_ML_KEM_512_K; + pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_768 + case WC_ML_KEM_768: + k = WC_ML_KEM_768_K; + pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_WC_ML_KEM_1024 + case WC_ML_KEM_1024: + k = WC_ML_KEM_1024_K; + pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_KYBER512 + case KYBER512: + k = KYBER512_K; + pubLen = KYBER512_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER768 + case KYBER768: + k = KYBER768_K; + pubLen = KYBER768_PUBLIC_KEY_SIZE; + break; + #endif + #ifdef WOLFSSL_KYBER1024 + case KYBER1024: + k = KYBER1024_K; + pubLen = KYBER1024_PUBLIC_KEY_SIZE; + break; + #endif +#endif + default: + /* No other values supported. */ + ret = NOT_COMPILED_IN; + break; + } + } + /* Check buffer is big enough for encoding. */ + if ((ret == 0) && (len != pubLen)) { + ret = BUFFER_E; + } + + if (ret == 0) { + int i; + + /* Encode public key polynomial by polynomial. */ + mlkem_to_bytes(p, key->pub, k); + p += k * WC_ML_KEM_POLY_SIZE; + + /* Append public seed. */ + for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) { + p[i] = key->pubSeed[i]; + } + + /* Make sure public hash is set. */ + if ((key->flags & MLKEM_FLAG_H_SET) == 0) { + ret = MLKEM_HASH_H(&key->hash, out, len, key->h); + } + } + if (ret == 0) { + /* Public hash is set. */ + key->flags |= MLKEM_FLAG_H_SET; + } + + return ret; +} + +#endif /* WOLFSSL_WC_MLKEM */ diff --git a/src/wolfcrypt/src/wc_mlkem_poly.c b/src/wolfcrypt/src/wc_mlkem_poly.c new file mode 100644 index 0000000..e5f4a18 --- /dev/null +++ b/src/wolfcrypt/src/wc_mlkem_poly.c @@ -0,0 +1,5986 @@ +/* wc_mlkem_poly.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Implementation based on FIPS 203: + * https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf + * + * Original implementation based on NIST 3rd Round submission package. + * See link at: + * https://csrc.nist.gov/Projects/post-quantum-cryptography/ + * post-quantum-cryptography-standardization/round-3-submissions + */ + +/* Implementation of the functions that operate on polynomials or vectors of + * polynomials. + */ + +/* Possible Kyber options: + * + * WOLFSSL_WC_MLKEM Default: OFF + * Enables this code, wolfSSL implementation, to be built. + * + * WOLFSSL_WC_ML_KEM_512 Default: OFF + * Enables the ML-KEM 512 parameter implementations. + * WOLFSSL_WC_ML_KEM_768 Default: OFF + * Enables the ML-KEM 768 parameter implementations. + * WOLFSSL_WC_ML_KEM_1024 Default: OFF + * Enables the ML-KEM 1024 parameter implementations. + * WOLFSSL_KYBER512 Default: OFF + * Enables the KYBER512 parameter implementations. + * WOLFSSL_KYBER768 Default: OFF + * Enables the KYBER768 parameter implementations. + * WOLFSSL_KYBER1024 Default: OFF + * Enables the KYBER1024 parameter implementations. + * + * USE_INTEL_SPEEDUP Default: OFF + * Compiles in Intel x64 specific implementations that are faster. + * WOLFSSL_MLKEM_NO_LARGE_CODE Default: OFF + * Compiles smaller, fast code size with a speed trade-off. + * WOLFSSL_MLKEM_SMALL Default: OFF + * Compiles to small code size with a speed trade-off. + * WOLFSSL_SMALL_STACK Default: OFF + * Use less stack by dynamically allocating local variables. + * + * WOLFSSL_MLKEM_NTT_UNROLL Default: OFF + * Enable an alternative NTT implementation that may be faster on some + * platforms and is smaller in code size. + * WOLFSSL_MLKEM_INVNTT_UNROLL Default: OFF + * Enables an alternative inverse NTT implementation that may be faster on + * some platforms and is smaller in code size. + */ + +#include + +#include +#include + +#ifdef WOLFSSL_WC_MLKEM + +#ifdef NO_INLINE + #include +#else + #define WOLFSSL_MISC_INCLUDED + #include +#endif + +#if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) +static int mlkem_gen_matrix_i(MLKEM_PRF_T* prf, sword16* a, int k, byte* seed, + int i, int transposed); +static int mlkem_get_noise_i(MLKEM_PRF_T* prf, int k, sword16* vec2, + byte* seed, int i, int make); +static int mlkem_get_noise_eta2_c(MLKEM_PRF_T* prf, sword16* p, + const byte* seed); +#endif + +/* Declared in wc_mlkem.c to stop compiler optimizer from simplifying. */ +extern volatile sword16 mlkem_opt_blocker; + +#if defined(USE_INTEL_SPEEDUP) || (defined(__aarch64__) && \ + defined(WOLFSSL_ARMASM)) +static word32 cpuid_flags = 0; +#endif + +/* Half of Q plus one. Converted message bit value of 1. */ +#define MLKEM_Q_1_HALF ((MLKEM_Q + 1) / 2) +/* Half of Q */ +#define MLKEM_Q_HALF (MLKEM_Q / 2) + + +/* q^-1 mod 2^16 (inverse of 3329 mod 16384) */ +#define MLKEM_QINV 62209 + +/* Used in Barrett Reduction: + * r = a mod q + * => r = a - ((V * a) >> 26) * q), as V based on 2^26 + * V is the multiplier that gets the quotient after shifting. + */ +#define MLKEM_V (((1U << 26) + (MLKEM_Q / 2)) / MLKEM_Q) + +/* Used in converting to Montgomery form. + * f is the normalizer = 2^k % m. + * 16-bit value cast to sword32 in use. + */ +#define MLKEM_F ((1ULL << 32) % MLKEM_Q) + +/* Number of bytes in an output block of SHA-3-128 */ +#define SHA3_128_BYTES (WC_SHA3_128_COUNT * 8) +/* Number of bytes in an output block of SHA-3-256 */ +#define SHA3_256_BYTES (WC_SHA3_256_COUNT * 8) + +/* Number of blocks to generate for matrix. */ +#define GEN_MATRIX_NBLOCKS \ + ((12 * MLKEM_N / 8 * (1 << 12) / MLKEM_Q + XOF_BLOCK_SIZE) / XOF_BLOCK_SIZE) +/* Number of bytes to generate for matrix. */ +#define GEN_MATRIX_SIZE GEN_MATRIX_NBLOCKS * XOF_BLOCK_SIZE + + +/* Number of random bytes to generate for ETA3. */ +#define ETA3_RAND_SIZE ((3 * MLKEM_N) / 4) +/* Number of random bytes to generate for ETA2. */ +#define ETA2_RAND_SIZE ((2 * MLKEM_N) / 4) + + +/* Montgomery reduce a. + * + * @param [in] a 32-bit value to be reduced. + * @return Montgomery reduction result. + */ +#define MLKEM_MONT_RED(a) \ + (sword16)(((a) - (sword32)(((sword16)((sword16)(a) * \ + (sword16)MLKEM_QINV)) * \ + (sword32)MLKEM_Q)) >> 16) + +/* Barrett reduce a. r = a mod q. + * + * Converted division to multiplication. + * + * @param [in] a 16-bit value to be reduced to range of q. + * @return Modulo result. + */ +#define MLKEM_BARRETT_RED(a) \ + (sword16)((sword16)(a) - (sword16)((sword16)( \ + ((sword32)((sword32)MLKEM_V * (sword16)(a))) >> 26) * (word16)MLKEM_Q)) + + +/* Zetas for NTT. */ +const sword16 zetas[MLKEM_N / 2] = { + 2285, 2571, 2970, 1812, 1493, 1422, 287, 202, + 3158, 622, 1577, 182, 962, 2127, 1855, 1468, + 573, 2004, 264, 383, 2500, 1458, 1727, 3199, + 2648, 1017, 732, 608, 1787, 411, 3124, 1758, + 1223, 652, 2777, 1015, 2036, 1491, 3047, 1785, + 516, 3321, 3009, 2663, 1711, 2167, 126, 1469, + 2476, 3239, 3058, 830, 107, 1908, 3082, 2378, + 2931, 961, 1821, 2604, 448, 2264, 677, 2054, + 2226, 430, 555, 843, 2078, 871, 1550, 105, + 422, 587, 177, 3094, 3038, 2869, 1574, 1653, + 3083, 778, 1159, 3182, 2552, 1483, 2727, 1119, + 1739, 644, 2457, 349, 418, 329, 3173, 3254, + 817, 1097, 603, 610, 1322, 2044, 1864, 384, + 2114, 3193, 1218, 1994, 2455, 220, 2142, 1670, + 2144, 1799, 2051, 794, 1819, 2475, 2459, 478, + 3221, 3021, 996, 991, 958, 1869, 1522, 1628 +}; + + +#if !defined(WOLFSSL_ARMASM) +/* Number-Theoretic Transform. + * + * FIPS 203, Algorithm 9: NTT(f) + * Computes the NTT representation f_hat of the given polynomial f element of + * R_q. + * 1: f_hat <- f + * 2: i <- 1 + * 3: for (len <- 128; len >= 2; len <- len/2) + * 4: for (start <- 0; start < 256; start <- start + 2.len) + * 5: zeta <- zetas^BitRev_7(i) mod q + * 6: i <- i + 1 + * 7: for (j <- start; j < start + len; j++) + * 8: t <- zeta.f[j+len] + * 9: f_hat[j+len] <- f_hat[j] - t + * 10: f_hat[j] <- f_hat[j] - t + * 11: end for + * 12: end for + * 13: end for + * 14: return f_hat + * + * @param [in, out] r Polynomial to transform. + */ +static void mlkem_ntt(sword16* r) +{ +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + + /* Step 2 */ + k = 1; + /* Step 3 */ + for (len = MLKEM_N / 2; len >= 2; len >>= 1) { + unsigned int start; + /* Step 4 */ + for (start = 0; start < MLKEM_N; start = j + len) { + /* Step 5, 6*/ + sword16 zeta = zetas[k++]; + /* Step 7 */ + for (j = start; j < start + len; ++j) { + /* Step 8 */ + sword32 p = (sword32)zeta * r[j + len]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[j]; + /* Step 9 */ + r[j + len] = rj - t; + /* Step 10 */ + r[j] = rj + t; + } + } + } + + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < MLKEM_N; ++j) { + r[j] = MLKEM_BARRETT_RED(r[j]); + } +#elif defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + /* Take out the first iteration. */ + unsigned int len; + unsigned int k = 1; + unsigned int j; + unsigned int start; + sword16 zeta = zetas[k++]; + + for (j = 0; j < MLKEM_N / 2; ++j) { + sword32 p = (sword32)zeta * r[j + MLKEM_N / 2]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[j]; + r[j + MLKEM_N / 2] = rj - t; + r[j] = rj + t; + } + for (len = MLKEM_N / 4; len >= 2; len >>= 1) { + for (start = 0; start < MLKEM_N; start = j + len) { + zeta = zetas[k++]; + for (j = start; j < start + len; ++j) { + sword32 p = (sword32)zeta * r[j + len]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[j]; + r[j + len] = rj - t; + r[j] = rj + t; + } + } + } + + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < MLKEM_N; ++j) { + r[j] = MLKEM_BARRETT_RED(r[j]); + } +#elif defined(WOLFSSL_MLKEM_NTT_UNROLL) + /* Unroll len loop (Step 3). */ + unsigned int k = 1; + unsigned int j; + unsigned int start; + sword16 zeta = zetas[k++]; + + /* len = 128 */ + for (j = 0; j < MLKEM_N / 2; ++j) { + sword32 p = (sword32)zeta * r[j + MLKEM_N / 2]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[j]; + r[j + MLKEM_N / 2] = rj - t; + r[j] = rj + t; + } + /* len = 64 */ + for (start = 0; start < MLKEM_N; start += 2 * 64) { + zeta = zetas[k++]; + for (j = 0; j < 64; ++j) { + sword32 p = (sword32)zeta * r[start + j + 64]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 64] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 32 */ + for (start = 0; start < MLKEM_N; start += 2 * 32) { + zeta = zetas[k++]; + for (j = 0; j < 32; ++j) { + sword32 p = (sword32)zeta * r[start + j + 32]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 32] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 16 */ + for (start = 0; start < MLKEM_N; start += 2 * 16) { + zeta = zetas[k++]; + for (j = 0; j < 16; ++j) { + sword32 p = (sword32)zeta * r[start + j + 16]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 16] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 8 */ + for (start = 0; start < MLKEM_N; start += 2 * 8) { + zeta = zetas[k++]; + for (j = 0; j < 8; ++j) { + sword32 p = (sword32)zeta * r[start + j + 8]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 8] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 4 */ + for (start = 0; start < MLKEM_N; start += 2 * 4) { + zeta = zetas[k++]; + for (j = 0; j < 4; ++j) { + sword32 p = (sword32)zeta * r[start + j + 4]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 4] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 2 */ + for (start = 0; start < MLKEM_N; start += 2 * 2) { + zeta = zetas[k++]; + for (j = 0; j < 2; ++j) { + sword32 p = (sword32)zeta * r[start + j + 2]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 2] = rj - t; + r[start + j] = rj + t; + } + } + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < MLKEM_N; ++j) { + r[j] = MLKEM_BARRETT_RED(r[j]); + } +#else + /* Unroll len (2, 3, 2) and start loops. */ + unsigned int j; + sword16 t0; + sword16 t1; + sword16 t2; + sword16 t3; + + /* len = 128,64 */ + sword16 zeta128 = zetas[1]; + sword16 zeta64_0 = zetas[2]; + sword16 zeta64_1 = zetas[3]; + for (j = 0; j < MLKEM_N / 8; j++) { + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 32]; + sword16 r2 = r[j + 64]; + sword16 r3 = r[j + 96]; + sword16 r4 = r[j + 128]; + sword16 r5 = r[j + 160]; + sword16 r6 = r[j + 192]; + sword16 r7 = r[j + 224]; + + t0 = MLKEM_MONT_RED((sword32)zeta128 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta128 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta128 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta128 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta64_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta64_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta64_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta64_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } + + /* len = 32,16,8 */ + for (j = 0; j < MLKEM_N; j += 64) { + int i; + sword16 zeta32 = zetas[ 4 + j / 64 + 0]; + sword16 zeta16_0 = zetas[ 8 + j / 32 + 0]; + sword16 zeta16_1 = zetas[ 8 + j / 32 + 1]; + sword16 zeta8_0 = zetas[16 + j / 16 + 0]; + sword16 zeta8_1 = zetas[16 + j / 16 + 1]; + sword16 zeta8_2 = zetas[16 + j / 16 + 2]; + sword16 zeta8_3 = zetas[16 + j / 16 + 3]; + for (i = 0; i < 8; i++) { + sword16 r0 = r[j + i + 0]; + sword16 r1 = r[j + i + 8]; + sword16 r2 = r[j + i + 16]; + sword16 r3 = r[j + i + 24]; + sword16 r4 = r[j + i + 32]; + sword16 r5 = r[j + i + 40]; + sword16 r6 = r[j + i + 48]; + sword16 r7 = r[j + i + 56]; + + t0 = MLKEM_MONT_RED((sword32)zeta32 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta32 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta32 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta32 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta16_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta16_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta16_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta16_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta8_0 * r1); + t1 = MLKEM_MONT_RED((sword32)zeta8_1 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta8_2 * r5); + t3 = MLKEM_MONT_RED((sword32)zeta8_3 * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + /* len = 4,2 and Final reduction */ + for (j = 0; j < MLKEM_N; j += 8) { + sword16 zeta4 = zetas[32 + j / 8 + 0]; + sword16 zeta2_0 = zetas[64 + j / 4 + 0]; + sword16 zeta2_1 = zetas[64 + j / 4 + 1]; + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 1]; + sword16 r2 = r[j + 2]; + sword16 r3 = r[j + 3]; + sword16 r4 = r[j + 4]; + sword16 r5 = r[j + 5]; + sword16 r6 = r[j + 6]; + sword16 r7 = r[j + 7]; + + t0 = MLKEM_MONT_RED((sword32)zeta4 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta4 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta4 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta4 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta2_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta2_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta2_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta2_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = MLKEM_BARRETT_RED(r0); + r[j + 1] = MLKEM_BARRETT_RED(r1); + r[j + 2] = MLKEM_BARRETT_RED(r2); + r[j + 3] = MLKEM_BARRETT_RED(r3); + r[j + 4] = MLKEM_BARRETT_RED(r4); + r[j + 5] = MLKEM_BARRETT_RED(r5); + r[j + 6] = MLKEM_BARRETT_RED(r6); + r[j + 7] = MLKEM_BARRETT_RED(r7); + } +#endif +} + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Zetas for inverse NTT. */ +const sword16 zetas_inv[MLKEM_N / 2] = { + 1701, 1807, 1460, 2371, 2338, 2333, 308, 108, + 2851, 870, 854, 1510, 2535, 1278, 1530, 1185, + 1659, 1187, 3109, 874, 1335, 2111, 136, 1215, + 2945, 1465, 1285, 2007, 2719, 2726, 2232, 2512, + 75, 156, 3000, 2911, 2980, 872, 2685, 1590, + 2210, 602, 1846, 777, 147, 2170, 2551, 246, + 1676, 1755, 460, 291, 235, 3152, 2742, 2907, + 3224, 1779, 2458, 1251, 2486, 2774, 2899, 1103, + 1275, 2652, 1065, 2881, 725, 1508, 2368, 398, + 951, 247, 1421, 3222, 2499, 271, 90, 853, + 1860, 3203, 1162, 1618, 666, 320, 8, 2813, + 1544, 282, 1838, 1293, 2314, 552, 2677, 2106, + 1571, 205, 2918, 1542, 2721, 2597, 2312, 681, + 130, 1602, 1871, 829, 2946, 3065, 1325, 2756, + 1861, 1474, 1202, 2367, 3147, 1752, 2707, 171, + 3127, 3042, 1907, 1836, 1517, 359, 758, 1441 +}; + +/* Inverse Number-Theoretic Transform. + * + * FIPS 203, Algorithm 10: NTT^-1(f_hat) + * Computes the polynomial f element of R_q that corresponds to the given NTT + * representation f element of T_q. + * 1: f <- f_hat + * 2: i <- 127 + * 3: for (len <- 2; len <= 128 ; len <- 2.len) + * 4: for (start <- 0; start < 256; start <- start + 2.len) + * 5: zeta <- zetas^BitRev_7(i) mod q + * 6: i <- i - 1 + * 7: for (j <- start; j < start + len; j++) + * 8: t <- f[j] + * 9: f[j] < t + f[j + len] + * 10: f[j + len] <- zeta.(f[j+len] - t) + * 11: end for + * 12: end for + * 13: end for + * 14: f <- f.3303 mod q + * 15: return f + * + * @param [in, out] r Polynomial to transform. + */ +static void mlkem_invntt(sword16* r) +{ +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int len; + unsigned int k; + unsigned int j; + sword16 zeta; + + /* Step 2 - table reversed */ + k = 0; + /* Step 3 */ + for (len = 2; len <= MLKEM_N / 2; len <<= 1) { + unsigned int start; + /* Step 4 */ + for (start = 0; start < MLKEM_N; start = j + len) { + /* Step 5, 6 */ + zeta = zetas_inv[k++]; + /* Step 7 */ + for (j = start; j < start + len; ++j) { + sword32 p; + /* Step 8 */ + sword16 rj = r[j]; + sword16 rjl = r[j + len]; + /* Step 9 */ + sword16 t = rj + rjl; + r[j] = MLKEM_BARRETT_RED(t); + /* Step 10 */ + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j + len] = MLKEM_MONT_RED(p); + } + } + } + + /* Step 14 */ + zeta = zetas_inv[127]; + for (j = 0; j < MLKEM_N; ++j) { + sword32 p = (sword32)zeta * r[j]; + r[j] = MLKEM_MONT_RED(p); + } +#elif defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + /* Take out last iteration. */ + unsigned int len; + unsigned int k; + unsigned int j; + sword16 zeta; + sword16 zeta2; + + k = 0; + for (len = 2; len <= MLKEM_N / 4; len <<= 1) { + unsigned int start; + for (start = 0; start < MLKEM_N; start = j + len) { + zeta = zetas_inv[k++]; + for (j = start; j < start + len; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + len]; + sword16 t = rj + rjl; + r[j] = MLKEM_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j + len] = MLKEM_MONT_RED(p); + } + } + } + + zeta = zetas_inv[126]; + zeta2 = zetas_inv[127]; + for (j = 0; j < MLKEM_N / 2; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + MLKEM_N / 2]; + sword16 t = rj + rjl; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j] = t; + r[j + MLKEM_N / 2] = MLKEM_MONT_RED(p); + + p = (sword32)zeta2 * r[j]; + r[j] = MLKEM_MONT_RED(p); + p = (sword32)zeta2 * r[j + MLKEM_N / 2]; + r[j + MLKEM_N / 2] = MLKEM_MONT_RED(p); + } +#elif defined(WOLFSSL_MLKEM_INVNTT_UNROLL) + /* Unroll len loop (Step 3). */ + unsigned int k; + unsigned int j; + unsigned int start; + sword16 zeta; + sword16 zeta2; + + k = 0; + /* len = 2 */ + for (start = 0; start < MLKEM_N; start += 2 * 2) { + zeta = zetas_inv[k++]; + for (j = 0; j < 2; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 2]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 2] = MLKEM_MONT_RED(p); + } + } + /* len = 4 */ + for (start = 0; start < MLKEM_N; start += 2 * 4) { + zeta = zetas_inv[k++]; + for (j = 0; j < 4; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 4]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 4] = MLKEM_MONT_RED(p); + } + } + /* len = 8 */ + for (start = 0; start < MLKEM_N; start += 2 * 8) { + zeta = zetas_inv[k++]; + for (j = 0; j < 8; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 8]; + sword16 t = rj + rjl; + /* Reduce. */ + r[start + j] = MLKEM_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 8] = MLKEM_MONT_RED(p); + } + } + /* len = 16 */ + for (start = 0; start < MLKEM_N; start += 2 * 16) { + zeta = zetas_inv[k++]; + for (j = 0; j < 16; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 16]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 16] = MLKEM_MONT_RED(p); + } + } + /* len = 32 */ + for (start = 0; start < MLKEM_N; start += 2 * 32) { + zeta = zetas_inv[k++]; + for (j = 0; j < 32; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 32]; + sword16 t = rj + rjl; + r[start + j] = t; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 32] = MLKEM_MONT_RED(p); + } + } + /* len = 64 */ + for (start = 0; start < MLKEM_N; start += 2 * 64) { + zeta = zetas_inv[k++]; + for (j = 0; j < 64; ++j) { + sword32 p; + sword16 rj = r[start + j]; + sword16 rjl = r[start + j + 64]; + sword16 t = rj + rjl; + /* Reduce. */ + r[start + j] = MLKEM_BARRETT_RED(t); + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[start + j + 64] = MLKEM_MONT_RED(p); + } + } + /* len = 128, 256 */ + zeta = zetas_inv[126]; + zeta2 = zetas_inv[127]; + for (j = 0; j < MLKEM_N / 2; ++j) { + sword32 p; + sword16 rj = r[j]; + sword16 rjl = r[j + MLKEM_N / 2]; + sword16 t = rj + rjl; + rjl = rj - rjl; + p = (sword32)zeta * rjl; + r[j] = t; + r[j + MLKEM_N / 2] = MLKEM_MONT_RED(p); + + p = (sword32)zeta2 * r[j]; + r[j] = MLKEM_MONT_RED(p); + p = (sword32)zeta2 * r[j + MLKEM_N / 2]; + r[j + MLKEM_N / 2] = MLKEM_MONT_RED(p); + } +#else + /* Unroll len (2, 3, 3) and start loops. */ + unsigned int j; + sword16 t0; + sword16 t1; + sword16 t2; + sword16 t3; + sword16 zeta64_0; + sword16 zeta64_1; + sword16 zeta128; + sword16 zeta256; + sword32 p; + + for (j = 0; j < MLKEM_N; j += 8) { + sword16 zeta2_0 = zetas_inv[ 0 + j / 4 + 0]; + sword16 zeta2_1 = zetas_inv[ 0 + j / 4 + 1]; + sword16 zeta4 = zetas_inv[64 + j / 8 + 0]; + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 1]; + sword16 r2 = r[j + 2]; + sword16 r3 = r[j + 3]; + sword16 r4 = r[j + 4]; + sword16 r5 = r[j + 5]; + sword16 r6 = r[j + 6]; + sword16 r7 = r[j + 7]; + + p = (sword32)zeta2_0 * (sword16)(r0 - r2); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta2_0 * (sword16)(r1 - r3); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta2_1 * (sword16)(r4 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta2_1 * (sword16)(r5 - r7); + t3 = MLKEM_MONT_RED(p); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta4 * (sword16)(r0 - r4); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r1 - r5); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r2 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta4 * (sword16)(r3 - r7); + t3 = MLKEM_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + 0] = r0; + r[j + 1] = r1; + r[j + 2] = r2; + r[j + 3] = r3; + r[j + 4] = r4; + r[j + 5] = r5; + r[j + 6] = r6; + r[j + 7] = r7; + } + + for (j = 0; j < MLKEM_N; j += 64) { + int i; + sword16 zeta8_0 = zetas_inv[ 96 + j / 16 + 0]; + sword16 zeta8_1 = zetas_inv[ 96 + j / 16 + 1]; + sword16 zeta8_2 = zetas_inv[ 96 + j / 16 + 2]; + sword16 zeta8_3 = zetas_inv[ 96 + j / 16 + 3]; + sword16 zeta16_0 = zetas_inv[112 + j / 32 + 0]; + sword16 zeta16_1 = zetas_inv[112 + j / 32 + 1]; + sword16 zeta32 = zetas_inv[120 + j / 64 + 0]; + for (i = 0; i < 8; i++) { + sword16 r0 = r[j + i + 0]; + sword16 r1 = r[j + i + 8]; + sword16 r2 = r[j + i + 16]; + sword16 r3 = r[j + i + 24]; + sword16 r4 = r[j + i + 32]; + sword16 r5 = r[j + i + 40]; + sword16 r6 = r[j + i + 48]; + sword16 r7 = r[j + i + 56]; + + p = (sword32)zeta8_0 * (sword16)(r0 - r1); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta8_1 * (sword16)(r2 - r3); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta8_2 * (sword16)(r4 - r5); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta8_3 * (sword16)(r6 - r7); + t3 = MLKEM_MONT_RED(p); + r0 = MLKEM_BARRETT_RED(r0 + r1); + r2 = MLKEM_BARRETT_RED(r2 + r3); + r4 = MLKEM_BARRETT_RED(r4 + r5); + r6 = MLKEM_BARRETT_RED(r6 + r7); + r1 = t0; + r3 = t1; + r5 = t2; + r7 = t3; + + p = (sword32)zeta16_0 * (sword16)(r0 - r2); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta16_0 * (sword16)(r1 - r3); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta16_1 * (sword16)(r4 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta16_1 * (sword16)(r5 - r7); + t3 = MLKEM_MONT_RED(p); + r0 += r2; + r1 += r3; + r4 += r6; + r5 += r7; + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta32 * (sword16)(r0 - r4); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r1 - r5); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r2 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta32 * (sword16)(r3 - r7); + t3 = MLKEM_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + zeta64_0 = zetas_inv[124]; + zeta64_1 = zetas_inv[125]; + zeta128 = zetas_inv[126]; + zeta256 = zetas_inv[127]; + for (j = 0; j < MLKEM_N / 8; j++) { + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 32]; + sword16 r2 = r[j + 64]; + sword16 r3 = r[j + 96]; + sword16 r4 = r[j + 128]; + sword16 r5 = r[j + 160]; + sword16 r6 = r[j + 192]; + sword16 r7 = r[j + 224]; + + p = (sword32)zeta64_0 * (sword16)(r0 - r2); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta64_0 * (sword16)(r1 - r3); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta64_1 * (sword16)(r4 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta64_1 * (sword16)(r5 - r7); + t3 = MLKEM_MONT_RED(p); + r0 = MLKEM_BARRETT_RED(r0 + r2); + r1 = MLKEM_BARRETT_RED(r1 + r3); + r4 = MLKEM_BARRETT_RED(r4 + r6); + r5 = MLKEM_BARRETT_RED(r5 + r7); + r2 = t0; + r3 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta128 * (sword16)(r0 - r4); + t0 = MLKEM_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r1 - r5); + t1 = MLKEM_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r2 - r6); + t2 = MLKEM_MONT_RED(p); + p = (sword32)zeta128 * (sword16)(r3 - r7); + t3 = MLKEM_MONT_RED(p); + r0 += r4; + r1 += r5; + r2 += r6; + r3 += r7; + r4 = t0; + r5 = t1; + r6 = t2; + r7 = t3; + + p = (sword32)zeta256 * r0; + r0 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r1; + r1 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r2; + r2 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r3; + r3 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r4; + r4 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r5; + r5 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r6; + r6 = MLKEM_MONT_RED(p); + p = (sword32)zeta256 * r7; + r7 = MLKEM_MONT_RED(p); + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } +#endif +} +#endif + +/* Multiplication of polynomials in Zq[X]/(X^2-zeta). + * + * Used for multiplication of elements in Rq in NTT domain. + * + * FIPS 203, Algorithm 12: BaseCaseMultiply(a0, a1, b0, b1, zeta) + * Computes the product of two degree-one polynomials with respect to a + * quadratic modulus. + * 1: c0 <- a0.b0 + a1.b1.zeta + * 2: c1 <- a0.b1 + a1.b0 + * 3: return (c0, c1) + * + * @param [out] r Result polynomial. + * @param [in] a First factor. + * @param [in] b Second factor. + * @param [in] zeta Integer defining the reduction polynomial. + */ +static void mlkem_basemul(sword16* r, const sword16* a, const sword16* b, + sword16 zeta) +{ + sword16 r0; + sword16 a0 = a[0]; + sword16 a1 = a[1]; + sword16 b0 = b[0]; + sword16 b1 = b[1]; + sword32 p1; + sword32 p2; + + /* Step 1 */ + p1 = (sword32)a0 * b0; + p2 = (sword32)a1 * b1; + r0 = MLKEM_MONT_RED(p2); + p2 = (sword32)zeta * r0; + p2 += p1; + r[0] = MLKEM_MONT_RED(p2); + + /* Step 2 */ + p1 = (sword32)a0 * b1; + p2 = (sword32)a1 * b0; + p1 += p2; + r[1] = MLKEM_MONT_RED(p1); +} + +/* Multiply two polynomials in NTT domain. r = a * b. + * + * FIPS 203, Algorithm 11: MultiplyNTTs(f_hat, g_hat) + * Computes the product (in the ring T_q) of two NTT representations. + * 1: for (i <- 0; i < 128; i++) + * 2: (h_hat[2i],h_hat[2i+1]) <- + * BaseCaseMultiply(f_hat[2i],f_hat[2i+1],g_hat[2i],g_hat[2i+1], + * zetas^(BitRev_7(i)+1) + * 3: end for + * 4: return h_hat + * + * @param [out] r Result polynomial. + * @param [in] a First polynomial multiplier. + * @param [in] b Second polynomial multiplier. + */ +static void mlkem_basemul_mont(sword16* r, const sword16* a, const sword16* b) +{ + const sword16* zeta = zetas + 64; + +#if defined(WOLFSSL_MLKEM_SMALL) + /* Two multiplications per loop. */ + unsigned int i; + /* Step 1 */ + for (i = 0; i < MLKEM_N; i += 4, zeta++) { + /* Step 2 */ + mlkem_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + } +#elif defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + /* Four multiplications per loop. */ + unsigned int i; + for (i = 0; i < MLKEM_N; i += 8, zeta += 2) { + mlkem_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + mlkem_basemul(r + i + 4, a + i + 4, b + i + 4, zeta[1]); + mlkem_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); + } +#else + /* Eight multiplications per loop. */ + unsigned int i; + for (i = 0; i < MLKEM_N; i += 16, zeta += 4) { + mlkem_basemul(r + i + 0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(r + i + 2, a + i + 2, b + i + 2, -zeta[0]); + mlkem_basemul(r + i + 4, a + i + 4, b + i + 4, zeta[1]); + mlkem_basemul(r + i + 6, a + i + 6, b + i + 6, -zeta[1]); + mlkem_basemul(r + i + 8, a + i + 8, b + i + 8, zeta[2]); + mlkem_basemul(r + i + 10, a + i + 10, b + i + 10, -zeta[2]); + mlkem_basemul(r + i + 12, a + i + 12, b + i + 12, zeta[3]); + mlkem_basemul(r + i + 14, a + i + 14, b + i + 14, -zeta[3]); + } +#endif +} + +/* Multiply two polynomials in NTT domain and add to result. r += a * b. + * + * FIPS 203, Algorithm 11: MultiplyNTTs(f_hat, g_hat) + * Computes the product (in the ring T_q) of two NTT representations. + * 1: for (i <- 0; i < 128; i++) + * 2: (h_hat[2i],h_hat[2i+1]) <- + * BaseCaseMultiply(f_hat[2i],f_hat[2i+1],g_hat[2i],g_hat[2i+1], + * zetas^(BitRev_7(i)+1) + * 3: end for + * 4: return h_hat + * Add h_hat to r. + * + * @param [in, out] r Result polynomial. + * @param [in] a First polynomial multiplier. + * @param [in] b Second polynomial multiplier. + */ +static void mlkem_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b) +{ + const sword16* zeta = zetas + 64; + +#if defined(WOLFSSL_MLKEM_SMALL) + /* Two multiplications per loop. */ + unsigned int i; + for (i = 0; i < MLKEM_N; i += 4, zeta++) { + sword16 t0[2]; + sword16 t2[2]; + + mlkem_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + } +#elif defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + /* Four multiplications per loop. */ + unsigned int i; + for (i = 0; i < MLKEM_N; i += 8, zeta += 2) { + sword16 t0[2]; + sword16 t2[2]; + sword16 t4[2]; + sword16 t6[2]; + + mlkem_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + mlkem_basemul(t4, a + i + 4, b + i + 4, zeta[1]); + mlkem_basemul(t6, a + i + 6, b + i + 6, -zeta[1]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + r[i + 4] += t4[0]; + r[i + 5] += t4[1]; + r[i + 6] += t6[0]; + r[i + 7] += t6[1]; + } +#else + /* Eight multiplications per loop. */ + unsigned int i; + for (i = 0; i < MLKEM_N; i += 16, zeta += 4) { + sword16 t0[2]; + sword16 t2[2]; + sword16 t4[2]; + sword16 t6[2]; + sword16 t8[2]; + sword16 t10[2]; + sword16 t12[2]; + sword16 t14[2]; + + mlkem_basemul(t0, a + i + 0, b + i + 0, zeta[0]); + mlkem_basemul(t2, a + i + 2, b + i + 2, -zeta[0]); + mlkem_basemul(t4, a + i + 4, b + i + 4, zeta[1]); + mlkem_basemul(t6, a + i + 6, b + i + 6, -zeta[1]); + mlkem_basemul(t8, a + i + 8, b + i + 8, zeta[2]); + mlkem_basemul(t10, a + i + 10, b + i + 10, -zeta[2]); + mlkem_basemul(t12, a + i + 12, b + i + 12, zeta[3]); + mlkem_basemul(t14, a + i + 14, b + i + 14, -zeta[3]); + + r[i + 0] += t0[0]; + r[i + 1] += t0[1]; + r[i + 2] += t2[0]; + r[i + 3] += t2[1]; + r[i + 4] += t4[0]; + r[i + 5] += t4[1]; + r[i + 6] += t6[0]; + r[i + 7] += t6[1]; + r[i + 8] += t8[0]; + r[i + 9] += t8[1]; + r[i + 10] += t10[0]; + r[i + 11] += t10[1]; + r[i + 12] += t12[0]; + r[i + 13] += t12[1]; + r[i + 14] += t14[0]; + r[i + 15] += t14[1]; + } +#endif +} +#endif + +/* Pointwise multiply elements of a and b, into r, and multiply by 2^-16. + * + * @param [out] r Result polynomial. + * @param [in] a First vector polynomial to multiply with. + * @param [in] b Second vector polynomial to multiply with. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_pointwise_acc_mont(sword16* r, const sword16* a, + const sword16* b, unsigned int k) +{ + unsigned int i; + + mlkem_basemul_mont(r, a, b); +#ifdef WOLFSSL_MLKEM_SMALL + for (i = 1; i < k; ++i) { + mlkem_basemul_mont_add(r, a + i * MLKEM_N, b + i * MLKEM_N); + } +#else + for (i = 1; i < k - 1; ++i) { + mlkem_basemul_mont_add(r, a + i * MLKEM_N, b + i * MLKEM_N); + } + mlkem_basemul_mont_add(r, a + (k - 1) * MLKEM_N, b + (k - 1) * MLKEM_N); +#endif +} + +/******************************************************************************/ + +/* Initialize Kyber implementation. + */ +void mlkem_init(void) +{ +#if defined(USE_INTEL_SPEEDUP) || (defined(__aarch64__) && \ + defined(WOLFSSL_ARMASM)) + cpuid_flags = cpuid_get_flags(); +#endif +} + +/******************************************************************************/ + +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + +#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY +/* Generate a public-private key pair from randomly generated data. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 16: s_hat <- NTT(s) + * 17: e_hat <- NTT(e) + * 18: t^hat <- A_hat o s_hat + e_hat + * ... + * + * @param [in, out] s Private key vector of polynomials. + * @param [out] t Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_keygen(sword16* s, sword16* t, sword16* e, const sword16* a, int k) +{ + int i; + +#ifndef WOLFSSL_AARCH64_NO_SQRDMLSH + if (IS_AARCH64_RDM(cpuid_flags)) { + /* Transform private key. All of result used in public key calculation. + * Step 16: s_hat = NTT(s) */ + for (i = 0; i < k; ++i) { + mlkem_ntt_sqrdmlsh(s + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 17, Step 18: Calculate public from A_hat, s_hat and e_hat. */ + for (i = 0; i < k; ++i) { + /* Multiply a by private into public polynomial. + * Step 18: ... A_hat o s_hat ... */ + mlkem_pointwise_acc_mont(t + i * MLKEM_N, a + i * k * MLKEM_N, s, + k); + /* Convert public polynomial to Montgomery form. + * Step 18: ... MontRed(A_hat o s_hat) ... */ + mlkem_to_mont_sqrdmlsh(t + i * MLKEM_N); + /* Transform error values polynomial. + * Step 17: e_hat = NTT(e) */ + mlkem_ntt_sqrdmlsh(e + i * MLKEM_N); + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + mlkem_add_reduce(t + i * MLKEM_N, e + i * MLKEM_N); + } + } + else +#endif + { + /* Transform private key. All of result used in public key calculation. + * Step 16: s_hat = NTT(s) */ + for (i = 0; i < k; ++i) { + mlkem_ntt(s + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 17, Step 18: Calculate public from A_hat, s_hat and e_hat. */ + for (i = 0; i < k; ++i) { + /* Multiply a by private into public polynomial. + * Step 18: ... A_hat o s_hat ... */ + mlkem_pointwise_acc_mont(t + i * MLKEM_N, a + i * k * MLKEM_N, s, + k); + /* Convert public polynomial to Montgomery form. + * Step 18: ... MontRed(A_hat o s_hat) ... */ + mlkem_to_mont(t + i * MLKEM_N); + /* Transform error values polynomial. + * Step 17: e_hat = NTT(e) */ + mlkem_ntt(e + i * MLKEM_N); + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + mlkem_add_reduce(t + i * MLKEM_N, e + i * MLKEM_N); + } + } +} +#endif /* WOLFSSL_MLKEM_NO_MAKE_KEY */ + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Encapsulate message. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE, m, r) + * ... + * Step 18: y_hat <- NTT(y) + * Step 19: u <- InvNTT(A_hat_trans o y_hat) + e_1) + * ... + * Step 21: v <- InvNTT(t_hat_trans o y_hat) + e_2 + mu) + * ... + * + * @param [in] t Public key vector of polynomials. + * @param [out] u Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] a Array of vector of polynomials. + * @param [in] y Vector of polynomials. + * @param [in] e1 Error Vector of polynomials. + * @param [in] e2 Error polynomial. + * @param [in] m Message polynomial. + * @param [in] k Number of polynomials in vector. + * @return 0 on success. + * + */ +void mlkem_encapsulate(const sword16* t, sword16* u , sword16* v, + const sword16* a, sword16* y, const sword16* e1, const sword16* e2, + const sword16* m, int k) +{ + int i; + +#ifndef WOLFSSL_AARCH64_NO_SQRDMLSH + if (IS_AARCH64_RDM(cpuid_flags)) { + /* Transform y. All of result used in calculation of u and v. + * Step 18: y_hat <- NTT(y) */ + for (i = 0; i < k; ++i) { + mlkem_ntt_sqrdmlsh(y + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 19: u <- InvNTT(A_hat_trans o y_hat) + e_1) */ + for (i = 0; i < k; ++i) { + /* Multiply at by y into u polynomial. + * Step 19: ... A_hat_trans o y_hat ... */ + mlkem_pointwise_acc_mont(u + i * MLKEM_N, a + i * k * MLKEM_N, y, + k); + /* Inverse transform u polynomial. + * Step 19: ... InvNTT(A_hat_trans o y_hat) ... */ + mlkem_invntt_sqrdmlsh(u + i * MLKEM_N); + /* Add errors to u and reduce. + * Step 19: u <- InvNTT(A_hat_trans o y_hat) + e_1) */ + mlkem_add_reduce(u + i * MLKEM_N, e1 + i * MLKEM_N); + } + + /* Multiply public key by y into v polynomial. + * Step 21: ... t_hat_trans o y_hat ... */ + mlkem_pointwise_acc_mont(v, t, y, k); + /* Inverse transform v. + * Step 22: ... InvNTT(t_hat_trans o y_hat) ... */ + mlkem_invntt_sqrdmlsh(v); + } + else +#endif + { + /* Transform y. All of result used in calculation of u and v. + * Step 18: y_hat <- NTT(y) */ + for (i = 0; i < k; ++i) { + mlkem_ntt(y + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 19: u <- InvNTT(A_hat_trans o y_hat) + e_1) */ + for (i = 0; i < k; ++i) { + /* Multiply at by y into u polynomial. + * Step 19: ... A_hat_trans o y_hat ... */ + mlkem_pointwise_acc_mont(u + i * MLKEM_N, a + i * k * MLKEM_N, y, + k); + /* Inverse transform u polynomial. + * Step 19: ... InvNTT(A_hat_trans o y_hat) ... */ + mlkem_invntt(u + i * MLKEM_N); + /* Add errors to u and reduce. + * Step 19: u <- InvNTT(A_hat_trans o y_hat) + e_1) */ + mlkem_add_reduce(u + i * MLKEM_N, e1 + i * MLKEM_N); + } + + /* Multiply public key by y into v polynomial. + * Step 21: ... t_hat_trans o y_hat ... */ + mlkem_pointwise_acc_mont(v, t, y, k); + /* Inverse transform v. + * Step 22: ... InvNTT(t_hat_trans o y_hat) ... */ + mlkem_invntt(v); + } + /* Add errors and message to v and reduce. + * Step 21: v <- InvNTT(t_hat_trans o y_hat) + e_2 + mu) */ + mlkem_add3_reduce(v, e2, m); +} +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE || !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +/* Decapsulate message. + * + * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE,c) + * Uses the decryption key to decrypt a ciphertext. + * ... + * 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) + * ... + * + * @param [in] s Decryption key as vector of polynomials. + * @param [out] w Message polynomial. + * @param [in] u Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_decapsulate(const sword16* s, sword16* w, sword16* u, + const sword16* v, int k) +{ + int i; + +#ifndef WOLFSSL_AARCH64_NO_SQRDMLSH + if (IS_AARCH64_RDM(cpuid_flags)) { + /* Transform u. All of result used in calculation of w. + * Step 6: ... NTT(u') */ + for (i = 0; i < k; ++i) { + mlkem_ntt_sqrdmlsh(u + i * MLKEM_N); + } + + /* Multiply private key by u into w polynomial. + * Step 6: ... s_hat_trans o NTT(u') */ + mlkem_pointwise_acc_mont(w, s, u, k); + /* Inverse transform w. + * Step 6: ... InvNTT(s_hat_trans o NTT(u')) */ + mlkem_invntt_sqrdmlsh(w); + } + else +#endif + { + /* Transform u. All of result used in calculation of w. + * Step 6: ... NTT(u') */ + for (i = 0; i < k; ++i) { + mlkem_ntt(u + i * MLKEM_N); + } + + /* Multiply private key by u into w polynomial. + * Step 6: ... s_hat_trans o NTT(u') */ + mlkem_pointwise_acc_mont(w, s, u, k); + /* Inverse transform w. + * Step 6: ... InvNTT(s_hat_trans o NTT(u')) */ + mlkem_invntt(w); + } + /* Subtract errors (in w) out of v and reduce into w. + * Step 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) */ + mlkem_rsub_reduce(w, v); +} +#endif /* !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#else + +#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY + +#if !defined(WOLFSSL_MLKEM_SMALL) && !defined(WOLFSSL_MLKEM_NO_LARGE_CODE) +/* Number-Theoretic Transform. + * + * FIPS 203, Algorithm 9: NTT(f) + * Computes the NTT representation f_hat of the given polynomial f element of + * R_q. + * 1: f_hat <- f + * 2: i <- 1 + * 3: for (len <- 128; len >= 2; len <- len/2) + * 4: for (start <- 0; start < 256; start <- start + 2.len) + * 5: zeta <- zetas^BitRev_7(i) mod q + * 6: i <- i + 1 + * 7: for (j <- start; j < start + len; j++) + * 8: t <- zeta.f[j+len] + * 9: f_hat[j+len] <- f_hat[j] - t + * 10: f_hat[j] <- f_hat[j] - t + * 11: end for + * 12: end for + * 13: end for + * 14: return f_hat + * + * @param [in, out] r Polynomial to transform. + */ +static void mlkem_ntt_add_to(sword16* r, sword16* a) +{ +#if defined(WOLFSSL_MLKEM_NTT_UNROLL) + /* Unroll len loop (Step 3). */ + unsigned int k = 1; + unsigned int j; + unsigned int start; + sword16 zeta = zetas[k++]; + + /* len = 128 */ + for (j = 0; j < MLKEM_N / 2; ++j) { + sword32 p = (sword32)zeta * r[j + MLKEM_N / 2]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[j]; + r[j + MLKEM_N / 2] = rj - t; + r[j] = rj + t; + } + /* len = 64 */ + for (start = 0; start < MLKEM_N; start += 2 * 64) { + zeta = zetas[k++]; + for (j = 0; j < 64; ++j) { + sword32 p = (sword32)zeta * r[start + j + 64]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 64] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 32 */ + for (start = 0; start < MLKEM_N; start += 2 * 32) { + zeta = zetas[k++]; + for (j = 0; j < 32; ++j) { + sword32 p = (sword32)zeta * r[start + j + 32]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 32] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 16 */ + for (start = 0; start < MLKEM_N; start += 2 * 16) { + zeta = zetas[k++]; + for (j = 0; j < 16; ++j) { + sword32 p = (sword32)zeta * r[start + j + 16]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 16] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 8 */ + for (start = 0; start < MLKEM_N; start += 2 * 8) { + zeta = zetas[k++]; + for (j = 0; j < 8; ++j) { + sword32 p = (sword32)zeta * r[start + j + 8]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 8] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 4 */ + for (start = 0; start < MLKEM_N; start += 2 * 4) { + zeta = zetas[k++]; + for (j = 0; j < 4; ++j) { + sword32 p = (sword32)zeta * r[start + j + 4]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 4] = rj - t; + r[start + j] = rj + t; + } + } + /* len = 2 */ + for (start = 0; start < MLKEM_N; start += 2 * 2) { + zeta = zetas[k++]; + for (j = 0; j < 2; ++j) { + sword32 p = (sword32)zeta * r[start + j + 2]; + sword16 t = MLKEM_MONT_RED(p); + sword16 rj = r[start + j]; + r[start + j + 2] = rj - t; + r[start + j] = rj + t; + } + } + /* Reduce coefficients with quick algorithm. */ + for (j = 0; j < MLKEM_N; ++j) { + sword16 t = a[j] + r[j]; + a[j] = MLKEM_BARRETT_RED(t); + } +#else /* !WOLFSSL_MLKEM_NTT_UNROLL */ + /* Unroll len (2, 3, 2) and start loops. */ + unsigned int j; + sword16 t0; + sword16 t1; + sword16 t2; + sword16 t3; + + /* len = 128,64 */ + sword16 zeta128 = zetas[1]; + sword16 zeta64_0 = zetas[2]; + sword16 zeta64_1 = zetas[3]; + for (j = 0; j < MLKEM_N / 8; j++) { + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 32]; + sword16 r2 = r[j + 64]; + sword16 r3 = r[j + 96]; + sword16 r4 = r[j + 128]; + sword16 r5 = r[j + 160]; + sword16 r6 = r[j + 192]; + sword16 r7 = r[j + 224]; + + t0 = MLKEM_MONT_RED((sword32)zeta128 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta128 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta128 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta128 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta64_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta64_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta64_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta64_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r[j + 0] = r0; + r[j + 32] = r1; + r[j + 64] = r2; + r[j + 96] = r3; + r[j + 128] = r4; + r[j + 160] = r5; + r[j + 192] = r6; + r[j + 224] = r7; + } + + /* len = 32,16,8 */ + for (j = 0; j < MLKEM_N; j += 64) { + int i; + sword16 zeta32 = zetas[ 4 + j / 64 + 0]; + sword16 zeta16_0 = zetas[ 8 + j / 32 + 0]; + sword16 zeta16_1 = zetas[ 8 + j / 32 + 1]; + sword16 zeta8_0 = zetas[16 + j / 16 + 0]; + sword16 zeta8_1 = zetas[16 + j / 16 + 1]; + sword16 zeta8_2 = zetas[16 + j / 16 + 2]; + sword16 zeta8_3 = zetas[16 + j / 16 + 3]; + for (i = 0; i < 8; i++) { + sword16 r0 = r[j + i + 0]; + sword16 r1 = r[j + i + 8]; + sword16 r2 = r[j + i + 16]; + sword16 r3 = r[j + i + 24]; + sword16 r4 = r[j + i + 32]; + sword16 r5 = r[j + i + 40]; + sword16 r6 = r[j + i + 48]; + sword16 r7 = r[j + i + 56]; + + t0 = MLKEM_MONT_RED((sword32)zeta32 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta32 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta32 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta32 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta16_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta16_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta16_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta16_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta8_0 * r1); + t1 = MLKEM_MONT_RED((sword32)zeta8_1 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta8_2 * r5); + t3 = MLKEM_MONT_RED((sword32)zeta8_3 * r7); + r1 = r0 - t0; + r3 = r2 - t1; + r5 = r4 - t2; + r7 = r6 - t3; + r0 += t0; + r2 += t1; + r4 += t2; + r6 += t3; + + r[j + i + 0] = r0; + r[j + i + 8] = r1; + r[j + i + 16] = r2; + r[j + i + 24] = r3; + r[j + i + 32] = r4; + r[j + i + 40] = r5; + r[j + i + 48] = r6; + r[j + i + 56] = r7; + } + } + + /* len = 4,2 and Final reduction */ + for (j = 0; j < MLKEM_N; j += 8) { + sword16 zeta4 = zetas[32 + j / 8 + 0]; + sword16 zeta2_0 = zetas[64 + j / 4 + 0]; + sword16 zeta2_1 = zetas[64 + j / 4 + 1]; + sword16 r0 = r[j + 0]; + sword16 r1 = r[j + 1]; + sword16 r2 = r[j + 2]; + sword16 r3 = r[j + 3]; + sword16 r4 = r[j + 4]; + sword16 r5 = r[j + 5]; + sword16 r6 = r[j + 6]; + sword16 r7 = r[j + 7]; + + t0 = MLKEM_MONT_RED((sword32)zeta4 * r4); + t1 = MLKEM_MONT_RED((sword32)zeta4 * r5); + t2 = MLKEM_MONT_RED((sword32)zeta4 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta4 * r7); + r4 = r0 - t0; + r5 = r1 - t1; + r6 = r2 - t2; + r7 = r3 - t3; + r0 += t0; + r1 += t1; + r2 += t2; + r3 += t3; + + t0 = MLKEM_MONT_RED((sword32)zeta2_0 * r2); + t1 = MLKEM_MONT_RED((sword32)zeta2_0 * r3); + t2 = MLKEM_MONT_RED((sword32)zeta2_1 * r6); + t3 = MLKEM_MONT_RED((sword32)zeta2_1 * r7); + r2 = r0 - t0; + r3 = r1 - t1; + r6 = r4 - t2; + r7 = r5 - t3; + r0 += t0; + r1 += t1; + r4 += t2; + r5 += t3; + + r0 += a[j + 0]; + r1 += a[j + 1]; + r2 += a[j + 2]; + r3 += a[j + 3]; + r4 += a[j + 4]; + r5 += a[j + 5]; + r6 += a[j + 6]; + r7 += a[j + 7]; + + a[j + 0] = MLKEM_BARRETT_RED(r0); + a[j + 1] = MLKEM_BARRETT_RED(r1); + a[j + 2] = MLKEM_BARRETT_RED(r2); + a[j + 3] = MLKEM_BARRETT_RED(r3); + a[j + 4] = MLKEM_BARRETT_RED(r4); + a[j + 5] = MLKEM_BARRETT_RED(r5); + a[j + 6] = MLKEM_BARRETT_RED(r6); + a[j + 7] = MLKEM_BARRETT_RED(r7); + } +#endif /* !WOLFSSL_MLKEM_NTT_UNROLL */ +} +#endif /* !WOLFSSL_MLKEM_SMALL && !WOLFSSL_MLKEM_NO_LARGE_CODE */ + +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM +/* Generate a public-private key pair from randomly generated data. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 16: s_hat <- NTT(s) + * 17: e_hat <- NTT(e) + * 18: t^hat <- A_hat o s_hat + e_hat + * ... + * + * @param [in, out] s Private key vector of polynomials. + * @param [out] t Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_keygen_c(sword16* s, sword16* t, sword16* e, const sword16* a, + int k) +{ + int i; + + /* Transform private key. All of result used in public key calculation + * Step 16: s_hat = NTT(s) */ + for (i = 0; i < k; ++i) { + mlkem_ntt(s + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 17, Step 18: Calculate public from A_hat, s_hat and e_hat. */ + for (i = 0; i < k; ++i) { + unsigned int j; + + /* Multiply a by private into public polynomial. + * Step 18: ... A_hat o s_hat ... */ + mlkem_pointwise_acc_mont(t + i * MLKEM_N, a + i * k * MLKEM_N, s, k); + /* Convert public polynomial to Montgomery form. + * Step 18: ... MontRed(A_hat o s_hat) ... */ + for (j = 0; j < MLKEM_N; ++j) { + sword32 n = t[i * MLKEM_N + j] * (sword32)MLKEM_F; + t[i * MLKEM_N + j] = MLKEM_MONT_RED(n); + } + /* Transform error values polynomial. + * Step 17: e_hat = NTT(e) */ +#if defined(WOLFSSL_MLKEM_SMALL) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + mlkem_ntt(e + i * MLKEM_N); + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + for (j = 0; j < MLKEM_N; ++j) { + sword16 n = t[i * MLKEM_N + j] + e[i * MLKEM_N + j]; + t[i * MLKEM_N + j] = MLKEM_BARRETT_RED(n); + } +#else + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + mlkem_ntt_add_to(e + i * MLKEM_N, t + i * MLKEM_N); +#endif + } +} + +/* Generate a public-private key pair from randomly generated data. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 16: s_hat <- NTT(s) + * 17: e_hat <- NTT(e) + * 18: t^hat <- A_hat o s_hat + e_hat + * ... + * + * @param [in, out] s Private key vector of polynomials. + * @param [out] t Public key vector of polynomials. + * @param [in] e Error values as a vector of polynomials. Modified. + * @param [in] a Random values in an array of vectors of polynomials. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_keygen(sword16* s, sword16* t, sword16* e, const sword16* a, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if ((IS_INTEL_AVX2(cpuid_flags)) && (SAVE_VECTOR_REGISTERS2() == 0)) { + /* Alg 13: Steps 16-18 */ + mlkem_keygen_avx2(s, t, e, a, k); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + /* Alg 13: Steps 16-18 */ + mlkem_keygen_c(s, t, e, a, k); + } +} + +#else /* WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM */ + +/* Generate a public-private key pair from randomly generated data. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * 3: for (i <- 0; i < k; i++) > generate matrix A_hat + * ... (generate A[i]) + * 7: end for + * ... + * 9: s[i] <- SamplePolyCBD_eta_1(PRF_eta_1(rho, N)) + * ... + * 16: s_hat <- NTT(s) + * 17: e_hat <- NTT(e) + * 18: t^hat <- A_hat o s_hat + e_hat + * ... + * + * @param [in, out] s Private key vector of polynomials. + * @param [out] tv Public key vector of polynomials. + * @param [in] prf XOF object. + * @param [in] tv Temporary vector of polynomials. + * @param [in] k Number of polynomials in vector. + * @param [in] rho Random seed to generate matrix A from. + * @param [in] sigma Random seed to generate noise from. + */ +int mlkem_keygen_seeds(sword16* s, sword16* t, MLKEM_PRF_T* prf, + sword16* tv, int k, byte* rho, byte* sigma) +{ + int i; + int ret = 0; + sword16* ai = tv; + sword16* e = tv; + + /* Transform private key. All of result used in public key calculation + * Step 16: s_hat = NTT(s) */ + for (i = 0; i < k; ++i) { + mlkem_ntt(s + i * MLKEM_N); + } + + /* For each polynomial in the vectors. + * Step 17, Step 18: Calculate public from A_hat, s_hat and e_hat. */ + for (i = 0; i < k; ++i) { + unsigned int j; + + /* Generate a vector of matrix A. + * Steps 4-6: generate A[i] */ + ret = mlkem_gen_matrix_i(prf, ai, k, rho, i, 0); + if (ret != 0) { + break; + } + + /* Multiply a by private into public polynomial. + * Step 18: ... A_hat o s_hat ... */ + mlkem_pointwise_acc_mont(t + i * MLKEM_N, ai, s, k); + /* Convert public polynomial to Montgomery form. + * Step 18: ... MontRed(A_hat o s_hat) ... */ + for (j = 0; j < MLKEM_N; ++j) { + sword32 n = t[i * MLKEM_N + j] * (sword32)MLKEM_F; + t[i * MLKEM_N + j] = MLKEM_MONT_RED(n); + } + + /* Generate noise using PRF. + * Step 9: s[i] <- SamplePolyCBD_eta_1(PRF_eta_1(rho, N)) */ + ret = mlkem_get_noise_i(prf, k, e, sigma, i, 1); + if (ret != 0) { + break; + } + /* Transform error values polynomial. + * Step 17: e_hat = NTT(e) */ +#if defined(WOLFSSL_MLKEM_SMALL) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + mlkem_ntt(e); + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + for (j = 0; j < MLKEM_N; ++j) { + sword16 n = t[i * MLKEM_N + j] + e[j]; + t[i * MLKEM_N + j] = MLKEM_BARRETT_RED(n); + } +#else + /* Add errors to public key and reduce. + * Step 18: t_hat = BarrettRed(MontRed(A_hat o s_hat) + e_hat) */ + mlkem_ntt_add_to(e, t + i * MLKEM_N); +#endif + } + + return ret; +} + +#endif /* WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM */ +#endif /* !WOLFSSL_MLKEM_NO_MAKE_KEY */ + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM +/* Encapsulate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [out] u Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] a Array of vector of polynomials. + * @param [in] y Vector of polynomials. + * @param [in] e1 Error Vector of polynomials. + * @param [in] e2 Error polynomial. + * @param [in] m Message polynomial. + * @param [in] k Number of polynomials in vector. + * @return 0 on success. + */ +static void mlkem_encapsulate_c(const sword16* pub, sword16* u, sword16* v, + const sword16* a, sword16* y, const sword16* e1, const sword16* e2, + const sword16* m, int k) +{ + int i; + + /* Transform y. All of result used in calculation of u and v. */ + for (i = 0; i < k; ++i) { + mlkem_ntt(y + i * MLKEM_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < k; ++i) { + unsigned int j; + + /* Multiply at by y into u polynomial. */ + mlkem_pointwise_acc_mont(u + i * MLKEM_N, a + i * k * MLKEM_N, y, k); + /* Inverse transform u polynomial. */ + mlkem_invntt(u + i * MLKEM_N); + /* Add errors to u and reduce. */ +#if defined(WOLFSSL_MLKEM_SMALL) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + for (j = 0; j < MLKEM_N; ++j) { + sword16 t = u[i * MLKEM_N + j] + e1[i * MLKEM_N + j]; + u[i * MLKEM_N + j] = MLKEM_BARRETT_RED(t); + } +#else + for (j = 0; j < MLKEM_N; j += 8) { + sword16 t0 = u[i * MLKEM_N + j + 0] + e1[i * MLKEM_N + j + 0]; + sword16 t1 = u[i * MLKEM_N + j + 1] + e1[i * MLKEM_N + j + 1]; + sword16 t2 = u[i * MLKEM_N + j + 2] + e1[i * MLKEM_N + j + 2]; + sword16 t3 = u[i * MLKEM_N + j + 3] + e1[i * MLKEM_N + j + 3]; + sword16 t4 = u[i * MLKEM_N + j + 4] + e1[i * MLKEM_N + j + 4]; + sword16 t5 = u[i * MLKEM_N + j + 5] + e1[i * MLKEM_N + j + 5]; + sword16 t6 = u[i * MLKEM_N + j + 6] + e1[i * MLKEM_N + j + 6]; + sword16 t7 = u[i * MLKEM_N + j + 7] + e1[i * MLKEM_N + j + 7]; + u[i * MLKEM_N + j + 0] = MLKEM_BARRETT_RED(t0); + u[i * MLKEM_N + j + 1] = MLKEM_BARRETT_RED(t1); + u[i * MLKEM_N + j + 2] = MLKEM_BARRETT_RED(t2); + u[i * MLKEM_N + j + 3] = MLKEM_BARRETT_RED(t3); + u[i * MLKEM_N + j + 4] = MLKEM_BARRETT_RED(t4); + u[i * MLKEM_N + j + 5] = MLKEM_BARRETT_RED(t5); + u[i * MLKEM_N + j + 6] = MLKEM_BARRETT_RED(t6); + u[i * MLKEM_N + j + 7] = MLKEM_BARRETT_RED(t7); + } +#endif + } + + /* Multiply public key by y into v polynomial. */ + mlkem_pointwise_acc_mont(v, pub, y, k); + /* Inverse transform v. */ + mlkem_invntt(v); + /* Add errors and message to v and reduce. */ + for (i = 0; i < MLKEM_N; ++i) { + sword16 t = v[i] + e2[i] + m[i]; + v[i] = MLKEM_BARRETT_RED(t); + } +} + +/* Encapsulate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [out] u Vector of polynomials. + * @param [out] v Polynomial. + * @param [in] a Array of vector of polynomials. + * @param [in] y Vector of polynomials. + * @param [in] e1 Error Vector of polynomials. + * @param [in] e2 Error polynomial. + * @param [in] m Message polynomial. + * @param [in] k Number of polynomials in vector. + * @return 0 on success. + */ +void mlkem_encapsulate(const sword16* pub, sword16* u, sword16* v, + const sword16* a, sword16* y, const sword16* e1, const sword16* e2, + const sword16* m, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_encapsulate_avx2(pub, u, v, a, y, e1, e2, m, k); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_encapsulate_c(pub, u, v, a, y, e1, e2, m, k); + } +} + +#else + +/* Encapsulate message. + * + * @param [in] pub Public key vector of polynomials. + * @param [in] prf XOF object. + * @param [out] u Vector of polynomials. + * @param [in, out] tp Polynomial. + * @param [in] y Vector of polynomials. + * @param [in] k Number of polynomials in vector. + * @param [in] msg Message to encapsulate. + * @param [in] seed Random seed to generate matrix A from. + * @param [in] coins Random seed to generate noise from. + */ +int mlkem_encapsulate_seeds(const sword16* pub, MLKEM_PRF_T* prf, sword16* u, + sword16* tp, sword16* y, int k, const byte* msg, byte* seed, byte* coins) +{ + int ret = 0; + int i; + sword16* a = tp; + sword16* e1 = tp; + sword16* v = tp; + sword16* e2 = tp + MLKEM_N; + sword16* m = y; + + /* Transform y. All of result used in calculation of u and v. */ + for (i = 0; i < k; ++i) { + mlkem_ntt(y + i * MLKEM_N); + } + + /* For each polynomial in the vectors. */ + for (i = 0; i < k; ++i) { + unsigned int j; + + /* Generate a vector of matrix A. */ + ret = mlkem_gen_matrix_i(prf, a, k, seed, i, 1); + if (ret != 0) { + break; + } + + /* Multiply at by y into u polynomial. */ + mlkem_pointwise_acc_mont(u + i * MLKEM_N, a, y, k); + /* Inverse transform u polynomial. */ + mlkem_invntt(u + i * MLKEM_N); + + /* Generate noise using PRF. */ + ret = mlkem_get_noise_i(prf, k, e1, coins, i, 0); + if (ret != 0) { + break; + } + /* Add errors to u and reduce. */ +#if defined(WOLFSSL_MLKEM_SMALL) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + for (j = 0; j < MLKEM_N; ++j) { + sword16 t = u[i * MLKEM_N + j] + e1[j]; + u[i * MLKEM_N + j] = MLKEM_BARRETT_RED(t); + } +#else + for (j = 0; j < MLKEM_N; j += 8) { + sword16 t0 = u[i * MLKEM_N + j + 0] + e1[j + 0]; + sword16 t1 = u[i * MLKEM_N + j + 1] + e1[j + 1]; + sword16 t2 = u[i * MLKEM_N + j + 2] + e1[j + 2]; + sword16 t3 = u[i * MLKEM_N + j + 3] + e1[j + 3]; + sword16 t4 = u[i * MLKEM_N + j + 4] + e1[j + 4]; + sword16 t5 = u[i * MLKEM_N + j + 5] + e1[j + 5]; + sword16 t6 = u[i * MLKEM_N + j + 6] + e1[j + 6]; + sword16 t7 = u[i * MLKEM_N + j + 7] + e1[j + 7]; + u[i * MLKEM_N + j + 0] = MLKEM_BARRETT_RED(t0); + u[i * MLKEM_N + j + 1] = MLKEM_BARRETT_RED(t1); + u[i * MLKEM_N + j + 2] = MLKEM_BARRETT_RED(t2); + u[i * MLKEM_N + j + 3] = MLKEM_BARRETT_RED(t3); + u[i * MLKEM_N + j + 4] = MLKEM_BARRETT_RED(t4); + u[i * MLKEM_N + j + 5] = MLKEM_BARRETT_RED(t5); + u[i * MLKEM_N + j + 6] = MLKEM_BARRETT_RED(t6); + u[i * MLKEM_N + j + 7] = MLKEM_BARRETT_RED(t7); + } +#endif + } + + /* Multiply public key by y into v polynomial. */ + mlkem_pointwise_acc_mont(v, pub, y, k); + /* Inverse transform v. */ + mlkem_invntt(v); + + mlkem_from_msg(m, msg); + + /* Generate noise using PRF. */ + coins[WC_ML_KEM_SYM_SZ] = 2 * k; + ret = mlkem_get_noise_eta2_c(prf, e2, coins); + if (ret == 0) { + /* Add errors and message to v and reduce. */ + #if defined(WOLFSSL_MLKEM_SMALL) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) + for (i = 0; i < MLKEM_N; ++i) { + sword16 t = v[i] + e2[i] + m[i]; + v[i] = MLKEM_BARRETT_RED(t); + } + #else + for (i = 0; i < MLKEM_N; i += 8) { + sword16 t0 = v[i + 0] + e2[i + 0] + m[i + 0]; + sword16 t1 = v[i + 1] + e2[i + 1] + m[i + 1]; + sword16 t2 = v[i + 2] + e2[i + 2] + m[i + 2]; + sword16 t3 = v[i + 3] + e2[i + 3] + m[i + 3]; + sword16 t4 = v[i + 4] + e2[i + 4] + m[i + 4]; + sword16 t5 = v[i + 5] + e2[i + 5] + m[i + 5]; + sword16 t6 = v[i + 6] + e2[i + 6] + m[i + 6]; + sword16 t7 = v[i + 7] + e2[i + 7] + m[i + 7]; + v[i + 0] = MLKEM_BARRETT_RED(t0); + v[i + 1] = MLKEM_BARRETT_RED(t1); + v[i + 2] = MLKEM_BARRETT_RED(t2); + v[i + 3] = MLKEM_BARRETT_RED(t3); + v[i + 4] = MLKEM_BARRETT_RED(t4); + v[i + 5] = MLKEM_BARRETT_RED(t5); + v[i + 6] = MLKEM_BARRETT_RED(t6); + v[i + 7] = MLKEM_BARRETT_RED(t7); + } + #endif + } + + return ret; +} +#endif +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE || !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE + +/* Decapsulate message. + * + * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE,c) + * Uses the decryption key to decrypt a ciphertext. + * ... + * 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) + * ... + * + * @param [in] s Private key vector of polynomials. + * @param [out] w Message polynomial. + * @param [in] u Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_decapsulate_c(const sword16* s, sword16* w, sword16* u, + const sword16* v, int k) +{ + int i; + + /* Transform u. All of result used in calculation of w. + * Step 6: ... NTT(u') */ + for (i = 0; i < k; ++i) { + mlkem_ntt(u + i * MLKEM_N); + } + + /* Multiply private key by u into w polynomial. + * Step 6: ... s_hat_trans o NTT(u') */ + mlkem_pointwise_acc_mont(w, s, u, k); + /* Inverse transform w. + * Step 6: ... InvNTT(s_hat_trans o NTT(u')) */ + mlkem_invntt(w); + /* Subtract errors (in w) out of v and reduce into w. + * Step 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) */ + for (i = 0; i < MLKEM_N; ++i) { + sword16 t = v[i] - w[i]; + w[i] = MLKEM_BARRETT_RED(t); + } +} + +/* Decapsulate message. + * + * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE,c) + * Uses the decryption key to decrypt a ciphertext. + * ... + * 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) + * ... + * + * @param [in] s Private key vector of polynomials. + * @param [out] w Message polynomial. + * @param [in] u Vector of polynomials containing error. + * @param [in] v Encapsulated message polynomial. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_decapsulate(const sword16* s, sword16* w, sword16* u, + const sword16* v, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_decapsulate_avx2(s, w, u, v, k); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_decapsulate_c(s, w, u, v, k); + } +} + +#endif /* !WOLFSSL_MLKEM_ NO_DECAPSULATE */ +#endif + +/******************************************************************************/ + +#ifdef USE_INTEL_SPEEDUP +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k2_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + if (!transposed) { + state[4*4 + 0] = 0x1f0000 + 0x000; + state[4*4 + 1] = 0x1f0000 + 0x001; + state[4*4 + 2] = 0x1f0000 + 0x100; + state[4*4 + 3] = 0x1f0000 + 0x101; + } + else { + state[4*4 + 0] = 0x1f0000 + 0x000; + state[4*4 + 1] = 0x1f0000 + 0x100; + state[4*4 + 2] = 0x1f0000 + 0x001; + state[4*4 + 3] = 0x1f0000 + 0x101; + } + + mlkem_sha3_128_blocksx4_seed_avx2(state, seed); + mlkem_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, rand + i + 0 * GEN_MATRIX_SIZE, + rand + i + 1 * GEN_MATRIX_SIZE, rand + i + 2 * GEN_MATRIX_SIZE, + rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = mlkem_rej_uniform_n_avx2(a + 0 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = mlkem_rej_uniform_n_avx2(a + 1 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = mlkem_rej_uniform_n_avx2(a + 2 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = mlkem_rej_uniform_n_avx2(a + 3 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N) || + (ctr3 < MLKEM_N)) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += mlkem_rej_uniform_avx2(a + 0 * MLKEM_N + ctr0, MLKEM_N - ctr0, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += mlkem_rej_uniform_avx2(a + 1 * MLKEM_N + ctr1, MLKEM_N - ctr1, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += mlkem_rej_uniform_avx2(a + 2 * MLKEM_N + ctr2, MLKEM_N - ctr2, + p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += mlkem_rej_uniform_avx2(a + 3 * MLKEM_N + ctr3, MLKEM_N - ctr3, + p, XOF_BLOCK_SIZE); + } + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + for (k = 0; k < 2; k++) { + for (i = 0; i < 4; i++) { + if (!transposed) { + state[4*4 + i] = 0x1f0000 + (((k*4+i)/3) << 8) + ((k*4+i)%3); + } + else { + state[4*4 + i] = 0x1f0000 + (((k*4+i)%3) << 8) + ((k*4+i)/3); + } + } + + mlkem_sha3_128_blocksx4_seed_avx2(state, seed); + mlkem_redistribute_21_rand_avx2(state, + rand + 0 * GEN_MATRIX_SIZE, rand + 1 * GEN_MATRIX_SIZE, + rand + 2 * GEN_MATRIX_SIZE, rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, + rand + i + 0 * GEN_MATRIX_SIZE, rand + i + 1 * GEN_MATRIX_SIZE, + rand + i + 2 * GEN_MATRIX_SIZE, rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = mlkem_rej_uniform_n_avx2(a + 0 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = mlkem_rej_uniform_n_avx2(a + 1 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = mlkem_rej_uniform_n_avx2(a + 2 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = mlkem_rej_uniform_n_avx2(a + 3 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N) || + (ctr3 < MLKEM_N)) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += mlkem_rej_uniform_avx2(a + 0 * MLKEM_N + ctr0, + MLKEM_N - ctr0, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += mlkem_rej_uniform_avx2(a + 1 * MLKEM_N + ctr1, + MLKEM_N - ctr1, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += mlkem_rej_uniform_avx2(a + 2 * MLKEM_N + ctr2, + MLKEM_N - ctr2, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += mlkem_rej_uniform_avx2(a + 3 * MLKEM_N + ctr3, + MLKEM_N - ctr3, p, XOF_BLOCK_SIZE); + } + + a += 4 * MLKEM_N; + } + + readUnalignedWords64(state, seed, 4); + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (2 << 8) + 2; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = W64LIT(0x8000000000000000); + for (i = 0; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) + { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + XMEMCPY(rand + i, state, SHA3_128_BYTES); + } + ctr0 = mlkem_rej_uniform_n_avx2(a, MLKEM_N, rand, GEN_MATRIX_SIZE); + while (ctr0 < MLKEM_N) { + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) + { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + XMEMCPY(rand, state, SHA3_128_BYTES); + ctr0 += mlkem_rej_uniform_avx2(a + ctr0, MLKEM_N - ctr0, rand, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + byte rand[4 * GEN_MATRIX_SIZE + 2]; + word64 state[25 * 4]; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + unsigned int ctr3; + byte* p; + + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; + rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; + + for (k = 0; k < 4; k++) { + for (i = 0; i < 4; i++) { + if (!transposed) { + state[4*4 + i] = 0x1f0000 + (k << 8) + i; + } + else { + state[4*4 + i] = 0x1f0000 + (i << 8) + k; + } + } + + mlkem_sha3_128_blocksx4_seed_avx2(state, seed); + mlkem_redistribute_21_rand_avx2(state, + rand + 0 * GEN_MATRIX_SIZE, rand + 1 * GEN_MATRIX_SIZE, + rand + 2 * GEN_MATRIX_SIZE, rand + 3 * GEN_MATRIX_SIZE); + for (i = SHA3_128_BYTES; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, + rand + i + 0 * GEN_MATRIX_SIZE, rand + i + 1 * GEN_MATRIX_SIZE, + rand + i + 2 * GEN_MATRIX_SIZE, rand + i + 3 * GEN_MATRIX_SIZE); + } + + /* Sample random bytes to create a polynomial. */ + p = rand; + ctr0 = mlkem_rej_uniform_n_avx2(a + 0 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 = mlkem_rej_uniform_n_avx2(a + 1 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 = mlkem_rej_uniform_n_avx2(a + 2 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 = mlkem_rej_uniform_n_avx2(a + 3 * MLKEM_N, MLKEM_N, p, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N) || + (ctr3 < MLKEM_N)) { + sha3_blocksx4_avx2(state); + mlkem_redistribute_21_rand_avx2(state, rand + 0 * GEN_MATRIX_SIZE, + rand + 1 * GEN_MATRIX_SIZE, rand + 2 * GEN_MATRIX_SIZE, + rand + 3 * GEN_MATRIX_SIZE); + + p = rand; + ctr0 += mlkem_rej_uniform_avx2(a + 0 * MLKEM_N + ctr0, + MLKEM_N - ctr0, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr1 += mlkem_rej_uniform_avx2(a + 1 * MLKEM_N + ctr1, + MLKEM_N - ctr1, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr2 += mlkem_rej_uniform_avx2(a + 2 * MLKEM_N + ctr2, + MLKEM_N - ctr2, p, XOF_BLOCK_SIZE); + p += GEN_MATRIX_SIZE; + ctr3 += mlkem_rej_uniform_avx2(a + 3 * MLKEM_N + ctr3, + MLKEM_N - ctr3, p, XOF_BLOCK_SIZE); + } + + a += 4 * MLKEM_N; + } + + return 0; +} +#endif /* WOLFSSL_KYBER1024 || WOLFSSL_WC_ML_KEM_1024 */ +#elif defined(WOLFSSL_ARMASM) && defined(__aarch64__) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k2_aarch64(sword16* a, byte* seed, int transposed) +{ + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + if (!transposed) { + state[0*25 + 4] = 0x1f0000 + (0 << 8) + 0; + state[1*25 + 4] = 0x1f0000 + (0 << 8) + 1; + state[2*25 + 4] = 0x1f0000 + (1 << 8) + 0; + } + else { + state[0*25 + 4] = 0x1f0000 + (0 << 8) + 0; + state[1*25 + 4] = 0x1f0000 + (1 << 8) + 0; + state[2*25 + 4] = 0x1f0000 + (0 << 8) + 1; + } + + mlkem_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = mlkem_rej_uniform_neon(a + 0 * MLKEM_N, MLKEM_N, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = mlkem_rej_uniform_neon(a + 1 * MLKEM_N, MLKEM_N, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 = mlkem_rej_uniform_neon(a + 2 * MLKEM_N, MLKEM_N, p, XOF_BLOCK_SIZE); + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N)) { + mlkem_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += mlkem_rej_uniform_neon(a + 0 * MLKEM_N + ctr0, MLKEM_N - ctr0, + p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += mlkem_rej_uniform_neon(a + 1 * MLKEM_N + ctr1, MLKEM_N - ctr1, + p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += mlkem_rej_uniform_neon(a + 2 * MLKEM_N + ctr2, MLKEM_N - ctr2, + p, XOF_BLOCK_SIZE); + } + + a += 3 * MLKEM_N; + + readUnalignedWords64(state, seed, 4); + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (1 << 8) + 1; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = W64LIT(0x8000000000000000); + BlockSha3(state); + p = (byte*)state; + ctr0 = mlkem_rej_uniform_neon(a, MLKEM_N, p, XOF_BLOCK_SIZE); + while (ctr0 < MLKEM_N) { + BlockSha3(state); + ctr0 += mlkem_rej_uniform_neon(a + ctr0, MLKEM_N - ctr0, p, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k3_aarch64(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + for (k = 0; k < 3; k++) { + for (i = 0; i < 3; i++) { + if (!transposed) { + state[i*25 + 4] = 0x1f0000 + ((k << 8) + i); + } + else { + state[i*25 + 4] = 0x1f0000 + ((i << 8) + k); + } + } + + mlkem_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = mlkem_rej_uniform_neon(a + 0 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = mlkem_rej_uniform_neon(a + 1 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + p +=25 * 8; + ctr2 = mlkem_rej_uniform_neon(a + 2 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N)) { + mlkem_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += mlkem_rej_uniform_neon(a + 0 * MLKEM_N + ctr0, + MLKEM_N - ctr0, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += mlkem_rej_uniform_neon(a + 1 * MLKEM_N + ctr1, + MLKEM_N - ctr1, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += mlkem_rej_uniform_neon(a + 2 * MLKEM_N + ctr2, + MLKEM_N - ctr2, p, XOF_BLOCK_SIZE); + } + + a += 3 * MLKEM_N; + } + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * @param [out] a Matrix of uniform integers. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_k4_aarch64(sword16* a, byte* seed, int transposed) +{ + int i; + int k; + word64 state[3 * 25]; + word64* st = (word64*)state; + unsigned int ctr0; + unsigned int ctr1; + unsigned int ctr2; + byte* p; + + for (k = 0; k < 5; k++) { + for (i = 0; i < 3; i++) { + byte bi = ((k * 3) + i) / 4; + byte bj = ((k * 3) + i) % 4; + if (!transposed) { + state[i*25 + 4] = 0x1f0000 + (bi << 8) + bj; + } + else { + state[i*25 + 4] = 0x1f0000 + (bj << 8) + bi; + } + } + + mlkem_shake128_blocksx3_seed_neon(state, seed); + /* Sample random bytes to create a polynomial. */ + p = (byte*)st; + ctr0 = mlkem_rej_uniform_neon(a + 0 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 = mlkem_rej_uniform_neon(a + 1 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 = mlkem_rej_uniform_neon(a + 2 * MLKEM_N, MLKEM_N, p, + XOF_BLOCK_SIZE); + /* Create more blocks if too many rejected. */ + while ((ctr0 < MLKEM_N) || (ctr1 < MLKEM_N) || (ctr2 < MLKEM_N)) { + mlkem_sha3_blocksx3_neon(st); + + p = (byte*)st; + ctr0 += mlkem_rej_uniform_neon(a + 0 * MLKEM_N + ctr0, + MLKEM_N - ctr0, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr1 += mlkem_rej_uniform_neon(a + 1 * MLKEM_N + ctr1, + MLKEM_N - ctr1, p, XOF_BLOCK_SIZE); + p += 25 * 8; + ctr2 += mlkem_rej_uniform_neon(a + 2 * MLKEM_N + ctr2, + MLKEM_N - ctr2, p, XOF_BLOCK_SIZE); + } + + a += 3 * MLKEM_N; + } + + readUnalignedWords64(state, seed, 4); + /* Transposed value same as not. */ + state[4] = 0x1f0000 + (3 << 8) + 3; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[20] = W64LIT(0x8000000000000000); + BlockSha3(state); + p = (byte*)state; + ctr0 = mlkem_rej_uniform_neon(a, MLKEM_N, p, XOF_BLOCK_SIZE); + while (ctr0 < MLKEM_N) { + BlockSha3(state); + ctr0 += mlkem_rej_uniform_neon(a + ctr0, MLKEM_N - ctr0, p, + XOF_BLOCK_SIZE); + } + + return 0; +} +#endif +#endif /* USE_INTEL_SPEEDUP */ + +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) +/* Absorb the seed data for squeezing out pseudo-random data. + * + * FIPS 203, Section 4.1: + * 1. XOF.init() = SHA128.Init(). + * 2. XOF.Absorb(ctx,str) = SHAKE128.Absorb(ctx,str). + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [in] seed Data to absorb. + * @param [in] len Length of data to absorb in bytes. + * @return 0 on success always. + */ +static int mlkem_xof_absorb(wc_Shake* shake128, byte* seed, int len) +{ + int ret; + + ret = wc_InitShake128(shake128, NULL, INVALID_DEVID); + if (ret == 0) { + ret = wc_Shake128_Absorb(shake128, seed, len); + } + + return ret; +} + +/* Squeeze the state to produce pseudo-random data. + * + * FIPS 203, Section 4.1: + * 3. XOF.Absorb(ctx,l) = SHAKE128.Squeeze(ctx,8.l). + * + * @param [in, out] shake128 SHAKE-128 object. + * @param [out] out Buffer to write to. + * @param [in] blocks Number of blocks to write. + * @return 0 on success always. + */ +static int mlkem_xof_squeezeblocks(wc_Shake* shake128, byte* out, int blocks) +{ + return wc_Shake128_SqueezeBlocks(shake128, out, blocks); +} +#endif + +/* New/Initialize SHA-3 object. + * + * FIPS 203, Section 4.1: + * H(s) := SHA3-256(s) + * + * @param [in, out] hash SHA-3 object. + * @param [in] heap Dynamic memory allocator hint. + * @param [in] devId Device id. + * @return 0 on success always. + */ +int mlkem_hash_new(wc_Sha3* hash, void* heap, int devId) +{ + return wc_InitSha3_256(hash, heap, devId); +} + +/* Free SHA-3 object. + * + * FIPS 203, Section 4.1: + * H(s) := SHA3-256(s) + * + * @param [in, out] hash SHA-3 object. + */ +void mlkem_hash_free(wc_Sha3* hash) +{ + wc_Sha3_256_Free(hash); +} + +/* Hash data using SHA3-256 with SHA-3 object. + * + * FIPS 203, Section 4.1: + * H(s) := SHA3-256(s) + * + * @param [in, out] hash SHA-3 object. + * @param [io] data Data to be hashed. + * @param [in] dataLen Length of data in bytes. + * @param [out] out Hash of data. + * @return 0 on success. + */ +int mlkem_hash256(wc_Sha3* hash, const byte* data, word32 dataLen, byte* out) +{ + int ret; + + /* Process all data. */ + ret = wc_Sha3_256_Update(hash, data, dataLen); + if (ret == 0) { + /* Calculate Hash of data passed in an re-initialize. */ + ret = wc_Sha3_256_Final(hash, out); + } + + return ret; +} + +/* Hash one or two blocks of data using SHA3-512 with SHA-3 object. + * + * FIPS 203, Section 4.1: + * G(s) := SHA3-512(s) + * + * @param [in, out] hash SHA-3 object. + * @param [io] data1 First block of data to be hashed. + * @param [in] data1Len Length of first block of data in bytes. + * @param [io] data2 Second block of data to be hashed. May be NULL. + * @param [in] data2Len Length of second block of data in bytes. + * @param [out] out Hash of all data. + * @return 0 on success. + */ +int mlkem_hash512(wc_Sha3* hash, const byte* data1, word32 data1Len, + const byte* data2, word32 data2Len, byte* out) +{ + int ret; + + /* Process first block of data. */ + ret = wc_Sha3_512_Update(hash, data1, data1Len); + /* Check if there is a second block of data. */ + if ((ret == 0) && (data2Len > 0)) { + /* Process second block of data. */ + ret = wc_Sha3_512_Update(hash, data2, data2Len); + } + if (ret == 0) { + /* Calculate Hash of data passed in an re-initialize. */ + ret = wc_Sha3_512_Final(hash, out); + } + + return ret; +} + +/* Initialize SHAKE-256 object. + * + * @param [in, out] shake256 SHAKE-256 object. + */ +void mlkem_prf_init(wc_Shake* prf) +{ + XMEMSET(prf->s, 0, sizeof(prf->s)); +} + +/* New/Initialize SHAKE-256 object. + * + * FIPS 203, Section 4.1: + * PRF_eta(s,b) := SHA256(s||b,8.64.eta) + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] heap Dynamic memory allocator hint. + * @param [in] devId Device id. + * @return 0 on success always. + */ +int mlkem_prf_new(wc_Shake* prf, void* heap, int devId) +{ + return wc_InitShake256(prf, heap, devId); +} + +/* Free SHAKE-256 object. + * + * FIPS 203, Section 4.1: + * PRF_eta(s,b) := SHA256(s||b,8.64.eta) + * + * @param [in, out] shake256 SHAKE-256 object. + */ +void mlkem_prf_free(wc_Shake* prf) +{ + wc_Shake256_Free(prf); +} + +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) +/* Create pseudo-random data from the key using SHAKE-256. + * + * FIPS 203, Section 4.1: + * PRF_eta(s,b) := SHA256(s||b,8.64.eta) + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to write. + * @param [in] key Data to derive from. Must be: + * WC_ML_KEM_SYM_SZ + 1 bytes in length. + * @return 0 on success always. + */ +static int mlkem_prf(wc_Shake* shake256, byte* out, unsigned int outLen, + const byte* key) +{ +#ifdef USE_INTEL_SPEEDUP + word64 state[25]; + + (void)shake256; + + /* Put first WC_ML_KEM_SYM_SZ bytes og key into blank state. */ + readUnalignedWords64(state, key, WC_ML_KEM_SYM_SZ / sizeof(word64)); + /* Last byte in with end of content marker. */ + state[WC_ML_KEM_SYM_SZ / 8] = 0x1f00 | key[WC_ML_KEM_SYM_SZ]; + /* Set rest of state to 0. */ + XMEMSET(state + WC_ML_KEM_SYM_SZ / 8 + 1, 0, + (25 - WC_ML_KEM_SYM_SZ / 8 - 1) * sizeof(word64)); + /* ... except for rate marker. */ + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); + + /* Generate as much output as is required. */ + while (outLen > 0) { + /* Get as much of an output block as is needed. */ + unsigned int len = min(outLen, WC_SHA3_256_BLOCK_SIZE); + + /* Perform a block operation on the state for next block of output. */ + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && + (SAVE_VECTOR_REGISTERS2() == 0)) { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + + /* Copy the state as output. */ + XMEMCPY(out, state, len); + /* Update output pointer and length. */ + out += len; + outLen -= len; + } + + return 0; +#else + int ret; + + /* Process all data. */ + ret = wc_Shake256_Update(shake256, key, WC_ML_KEM_SYM_SZ + 1); + if (ret == 0) { + /* Calculate Hash of data passed in an re-initialize. */ + ret = wc_Shake256_Final(shake256, out, outLen); + } + + return ret; +#endif +} +#endif + +#ifdef WOLFSSL_MLKEM_KYBER +#ifdef USE_INTEL_SPEEDUP +/* Create pseudo-random key from the seed using SHAKE-256. + * + * @param [in] seed Data to derive from. + * @param [in] seedLen Length of data to derive from in bytes. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to derive. + * @return 0 on success always. + */ +int mlkem_kdf(byte* seed, int seedLen, byte* out, int outLen) +{ + word64 state[25]; + word32 len64 = seedLen / 8; + + readUnalignedWords64(state, seed, len64); + state[len64] = 0x1f; + XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); + + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + XMEMCPY(out, state, outLen); + + return 0; +} +#endif + +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) +/* Create pseudo-random key from the seed using SHAKE-256. + * + * @param [in] seed Data to derive from. + * @param [in] seedLen Length of data to derive from in bytes. + * @param [out] out Buffer to write to. + * @param [in] outLen Number of bytes to derive. + * @return 0 on success always. + */ +int mlkem_kdf(byte* seed, int seedLen, byte* out, int outLen) +{ + word64 state[25]; + word32 len64 = seedLen / 8; + + readUnalignedWords64(state, seed, len64); + state[len64] = 0x1f; + XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); + + BlockSha3(state); + XMEMCPY(out, state, outLen); + + return 0; +} +#endif +#endif + +#ifndef WOLFSSL_NO_ML_KEM +/* Derive the secret from z and cipher text. + * + * @param [in, out] shake256 SHAKE-256 object. + * @param [in] z Implicit rejection value. + * @param [in] ct Cipher text. + * @param [in] ctSz Length of cipher text in bytes. + * @param [out] ss Shared secret. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation failed. + * @return Other negative when a hash error occurred. + */ +int mlkem_derive_secret(wc_Shake* shake256, const byte* z, const byte* ct, + word32 ctSz, byte* ss) +{ + int ret; + +#ifdef USE_INTEL_SPEEDUP + XMEMCPY(shake256->t, z, WC_ML_KEM_SYM_SZ); + XMEMCPY(shake256->t, ct, WC_SHA3_256_COUNT * 8 - WC_ML_KEM_SYM_SZ); + shake256->i = WC_ML_KEM_SYM_SZ; + ct += WC_SHA3_256_COUNT * 8 - WC_ML_KEM_SYM_SZ; + ctSz -= WC_SHA3_256_COUNT * 8 - WC_ML_KEM_SYM_SZ; + ret = wc_Shake256_Update(shake256, ct, ctSz); + if (ret == 0) { + ret = wc_Shake256_Final(shake256, ss, WC_ML_KEM_SS_SZ); + } +#else + ret = wc_Shake256_Update(shake256, z, WC_ML_KEM_SYM_SZ); + if (ret == 0) { + ret = wc_Shake256_Update(shake256, ct, ctSz); + } + if (ret == 0) { + ret = wc_Shake256_Final(shake256, ss, WC_ML_KEM_SS_SZ); + } +#endif + + return ret; +} +#endif + +#if !defined(WOLFSSL_ARMASM) +/* Rejection sampling on uniform random bytes to generate uniform random + * integers mod q. + * + * FIPS 203, Algorithm 7: SampleNTT(B) + * Takes a 32-byte seed and two indices as input and outputs a pseudorandom + * element of T_q. + * ... + * 4: while j < 256 do + * 5: (ctx,C) <- XOF.Squeeze(ctx,3) + * 6: d1 <- C[0] + 256.(C[1] mod 16) + * 7: d2 <- lower(C[1] / 16) + 16.C[2] + * 8: if d1 < q then + * 9: a_hat[j] <- d1 + * 10: j <- j + 1 + * 11: end if + * 12: if d2 < q and j < 256 then + * 13: a_hat[j] <- d2 + * 14: j <- j + 1 + * 15: end if + * 16: end while + * ... + * + * @param [out] p Uniform random integers mod q. + * @param [in] len Maximum number of integers. + * @param [in] r Uniform random bytes buffer. + * @param [in] rLen Length of random data in buffer. + * @return Number of integers sampled. + */ +static unsigned int mlkem_rej_uniform_c(sword16* p, unsigned int len, + const byte* r, unsigned int rLen) +{ + unsigned int i; + unsigned int j; + +#if defined(WOLFSSL_MLKEM_SMALL) || !defined(WC_64BIT_CPU) || \ + defined(BIG_ENDIAN_ORDER) + /* Keep sampling until maximum number of integers reached or buffer used up. + * Step 4. */ + for (i = 0, j = 0; (i < len) && (j <= rLen - 3); j += 3) { + /* Step 5 - caller generates and now using 3 bytes of it. */ + /* Use 24 bits (3 bytes) as two 12 bits integers. */ + /* Step 6. */ + sword16 v0 = ((r[0] >> 0) | ((word16)r[1] << 8)) & 0xFFF; + /* Step 7. */ + sword16 v1 = ((r[1] >> 4) | ((word16)r[2] << 4)) & 0xFFF; + + /* Reject first 12-bit integer if greater than or equal to q. + * Step 8 */ + if (v0 < MLKEM_Q) { + /* Steps 9-10 */ + p[i++] = v0; + } + /* Check second if we don't have enough integers yet. + * Reject second 12-bit integer if greater than or equal to q. + * Step 12 */ + if ((i < len) && (v1 < MLKEM_Q)) { + /* Steps 13-14 */ + p[i++] = v1; + } + + /* Move over used bytes. */ + r += 3; + } +#else + /* Unroll loops. Minimal work per loop. */ + unsigned int minJ; + + /* Calculate minimum number of 6 byte data blocks to get all required + * numbers assuming no rejections. */ + minJ = len / 4 * 6; + if (minJ > rLen) + minJ = rLen; + i = 0; + for (j = 0; j < minJ; j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + p[i] = v0; + i += (v0 < MLKEM_Q); + p[i] = v1; + i += (v1 < MLKEM_Q); + p[i] = v2; + i += (v2 < MLKEM_Q); + p[i] = v3; + i += (v3 < MLKEM_Q); + + /* Move over used bytes. */ + r += 6; + } + /* Check whether we have all the numbers we need. */ + if (j < rLen) { + /* Keep trying until we have less than 4 numbers to find or data is used + * up. */ + for (; (i + 4 < len) && (j < rLen); j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + p[i] = v0; + i += (v0 < MLKEM_Q); + p[i] = v1; + i += (v1 < MLKEM_Q); + p[i] = v2; + i += (v2 < MLKEM_Q); + p[i] = v3; + i += (v3 < MLKEM_Q); + + /* Move over used bytes. */ + r += 6; + } + /* Keep trying until we have all the numbers we need or the data is used + * up. */ + for (; (i < len) && (j < rLen); j += 6) { + /* Use 48 bits (6 bytes) as four 12-bit integers. */ + word64 r_word = readUnalignedWord64(r); + sword16 v0 = r_word & 0xfff; + sword16 v1 = (r_word >> 12) & 0xfff; + sword16 v2 = (r_word >> 24) & 0xfff; + sword16 v3 = (r_word >> 36) & 0xfff; + + /* Reject first 12-bit integer if greater than or equal to q. */ + if (v0 < MLKEM_Q) { + p[i++] = v0; + } + /* Check second if we don't have enough integers yet. + * Reject second 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v1 < MLKEM_Q)) { + p[i++] = v1; + } + /* Check second if we don't have enough integers yet. + * Reject third 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v2 < MLKEM_Q)) { + p[i++] = v2; + } + /* Check second if we don't have enough integers yet. + * Reject fourth 12-bit integer if greater than or equal to q. */ + if ((i < len) && (v3 < MLKEM_Q)) { + p[i++] = v3; + } + + /* Move over used bytes. */ + r += 6; + } + } +#endif + + return i; +} +#endif + +#if !defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + !defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) + +#if !(defined(WOLFSSL_ARMASM) && defined(__aarch64__)) +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 3: for (i <- 0; i < k; i++) + * 4: for (j <- 0; j < k; j++) + * 5: A_hat[i,j] <- SampleNTT(rho||j||i) + * 6: end for + * 7: end for + * ... + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 4: for (i <- 0; i < k; i++) + * 5: for (j <- 0; j < k; j++) + * 6: A_hat[i,j] <- SampleNTT(rho||j||i) (Transposed is rho||i||j) + * 7: end for + * 8: end for + * ... + * FIPS 203, Algorithm 7: SampleNTT(B) + * Takes a 32-byte seed and two indices as input and outputs a pseudorandom + * element of T_q. + * 1: ctx <- XOF.init() + * 2: ctx <- XOF.Absorb(ctx,B) + * 3: j <- 0 + * 4: while j < 256 do + * 5: (ctx,C) <- XOF.Squeeze(ctx,3) + * ... + * 16: end while + * 17: return a_hat + * + * @param [in] prf XOF object. + * @param [out] a Matrix of uniform integers. + * @param [in] k Number of dimensions. k x k polynomials. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_c(MLKEM_PRF_T* prf, sword16* a, int k, byte* seed, + int transposed) +{ +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + byte* rand; +#else + byte rand[GEN_MATRIX_SIZE + 2]; +#endif + byte extSeed[WC_ML_KEM_SYM_SZ + 2]; + int ret = 0; + int i; + + /* Copy seed into buffer than has space for i and j to be appended. */ + XMEMCPY(extSeed, seed, WC_ML_KEM_SYM_SZ); + +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + /* Allocate large amount of memory to hold random bytes to be samples. */ + rand = (byte*)XMALLOC(GEN_MATRIX_SIZE + 2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (rand == NULL) { + ret = MEMORY_E; + } +#endif + +#if !defined(WOLFSSL_MLKEM_SMALL) && defined(WC_64BIT_CPU) + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + if (ret == 0) { + rand[GEN_MATRIX_SIZE+0] = 0xff; + rand[GEN_MATRIX_SIZE+1] = 0xff; + } +#endif + + /* Generate each vector of polynomials. + * Alg 13, Step 3. Alg 14, Step 4. */ + for (i = 0; (ret == 0) && (i < k); i++, a += k * MLKEM_N) { + int j; + /* Generate each polynomial in vector from seed with indices. + * Alg 13, Step 4. Alg 14, Step 5. */ + for (j = 0; (ret == 0) && (j < k); j++) { + if (transposed) { + /* Alg 14, Step 6: .. rho||i||j ... */ + extSeed[WC_ML_KEM_SYM_SZ + 0] = i; + extSeed[WC_ML_KEM_SYM_SZ + 1] = j; + } + else { + /* Alg 13, Step 5: .. rho||j||i ... */ + extSeed[WC_ML_KEM_SYM_SZ + 0] = j; + extSeed[WC_ML_KEM_SYM_SZ + 1] = i; + } + /* Absorb the index specific seed. + * Alg 7, Step 1-2 */ + ret = mlkem_xof_absorb(prf, extSeed, sizeof(extSeed)); + if (ret == 0) { + /* Create data based on the seed. + * Alg 7, Step 5. Generating enough to, on average, be able to + * get enough valid values. */ + ret = mlkem_xof_squeezeblocks(prf, rand, GEN_MATRIX_NBLOCKS); + } + if (ret == 0) { + unsigned int ctr; + + /* Sample random bytes to create a polynomial. + * Alg 7, Step 3 - implicitly counter is 0. + * Alg 7, Step 4-16. */ + ctr = mlkem_rej_uniform_c(a + j * MLKEM_N, MLKEM_N, rand, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. + * Alg 7, Step 4. */ + while (ctr < MLKEM_N) { + /* Alg 7, Step 5. */ + mlkem_xof_squeezeblocks(prf, rand, 1); + /* Alg 7, Step 4-16. */ + ctr += mlkem_rej_uniform_c(a + j * MLKEM_N + ctr, + MLKEM_N - ctr, rand, XOF_BLOCK_SIZE); + } + } + } + } + +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + /* Dispose of temporary buffer. */ + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} +#endif + +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d), Steps 3-7 + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r), Steps 4-8 + * + * @param [in] prf XOF object. + * @param [out] a Matrix of uniform integers. + * @param [in] k Number of dimensions. k x k polynomials. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +int mlkem_gen_matrix(MLKEM_PRF_T* prf, sword16* a, int k, byte* seed, + int transposed) +{ + int ret; + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if (k == WC_ML_KEM_512_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_gen_matrix_k2_aarch64(a, seed, transposed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_gen_matrix_k2_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + { + ret = mlkem_gen_matrix_c(prf, a, WC_ML_KEM_512_K, seed, transposed); + } +#endif + } + else +#endif +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) + if (k == WC_ML_KEM_768_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_gen_matrix_k3_aarch64(a, seed, transposed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_gen_matrix_k3_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + { + ret = mlkem_gen_matrix_c(prf, a, WC_ML_KEM_768_K, seed, transposed); + } +#endif + } + else +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) + if (k == WC_ML_KEM_1024_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_gen_matrix_k4_aarch64(a, seed, transposed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_gen_matrix_k4_avx2(a, seed, transposed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + { + ret = mlkem_gen_matrix_c(prf, a, WC_ML_KEM_1024_K, seed, + transposed); + } +#endif + } + else +#endif + { + ret = BAD_STATE_E; + } + + (void)prf; + + return ret; +} + +#endif + +#if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) + +/* Deterministically generate a matrix (or transpose) of uniform integers mod q. + * + * Seed used with XOF to generate random bytes. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 4: for (j <- 0; j < k; j++) + * 5: A_hat[i,j] <- SampleNTT(rho||j||i) + * 6: end for + * ... + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 5: for (j <- 0; j < k; j++) + * 6: A_hat[i,j] <- SampleNTT(rho||j||i) (Transposed is rho||i||j) + * 7: end for + * ... + * + * @param [in] prf XOF object. + * @param [out] a Matrix of uniform integers. + * @param [in] k Number of dimensions. k x k polynomials. + * @param [in] seed Bytes to seed XOF generation. + * @param [in] i Index of vector to generate. + * @param [in] transposed Whether A or A^T is generated. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. Only possible when + * WOLFSSL_SMALL_STACK is defined. + */ +static int mlkem_gen_matrix_i(MLKEM_PRF_T* prf, sword16* a, int k, byte* seed, + int i, int transposed) +{ +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + byte* rand; +#else + byte rand[GEN_MATRIX_SIZE + 2]; +#endif + byte extSeed[WC_ML_KEM_SYM_SZ + 2]; + int ret = 0; + int j; + + XMEMCPY(extSeed, seed, WC_ML_KEM_SYM_SZ); + +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + /* Allocate large amount of memory to hold random bytes to be samples. */ + rand = (byte*)XMALLOC(GEN_MATRIX_SIZE + 2, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (rand == NULL) { + ret = MEMORY_E; + } +#endif + +#if !defined(WOLFSSL_MLKEM_SMALL) && defined(WC_64BIT_CPU) + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ + if (ret == 0) { + rand[GEN_MATRIX_SIZE+0] = 0xff; + rand[GEN_MATRIX_SIZE+1] = 0xff; + } +#endif + + /* Generate each polynomial in vector from seed with indices. + * Alg 13, Step 4. Alg 14, Step 5. */ + for (j = 0; (ret == 0) && (j < k); j++) { + if (transposed) { + /* Alg 14, Step 6: .. rho||i||j ... */ + extSeed[WC_ML_KEM_SYM_SZ + 0] = i; + extSeed[WC_ML_KEM_SYM_SZ + 1] = j; + } + else { + /* Alg 13, Step 5: .. rho||j||i ... */ + extSeed[WC_ML_KEM_SYM_SZ + 0] = j; + extSeed[WC_ML_KEM_SYM_SZ + 1] = i; + } + /* Absorb the index specific seed. + * Alg 7, Step 1-2 */ + ret = mlkem_xof_absorb(prf, extSeed, sizeof(extSeed)); + if (ret == 0) { + /* Create out based on the seed. + * Alg 7, Step 5. Generating enough to, on average, be able to get + * enough valid values. */ + ret = mlkem_xof_squeezeblocks(prf, rand, GEN_MATRIX_NBLOCKS); + } + if (ret == 0) { + unsigned int ctr; + + /* Sample random bytes to create a polynomial. + * Alg 7, Step 3 - implicitly counter is 0. + * Alg 7, Step 4-16. */ + ctr = mlkem_rej_uniform_c(a + j * MLKEM_N, MLKEM_N, rand, + GEN_MATRIX_SIZE); + /* Create more blocks if too many rejected. + * Alg 7, Step 4. */ + while (ctr < MLKEM_N) { + /* Alg 7, Step 5. */ + mlkem_xof_squeezeblocks(prf, rand, 1); + /* Alg 7, Step 4-16. */ + ctr += mlkem_rej_uniform_c(a + j * MLKEM_N + ctr, + MLKEM_N - ctr, rand, XOF_BLOCK_SIZE); + } + } + } + +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + /* Dispose of temporary buffer. */ + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + +#endif + + +/******************************************************************************/ + +/* Subtract one 2 bit value from another out of a larger number. + * + * FIPS 203, Algorithm 8: SmaplePolyCBD_eta(B) + * Takes a seed as input and outputs a pseudorandom sample from the distribution + * D_eta(R_q). + * + * @param [in] d Value containing sequential 2 bit values. + * @param [in] i Start index of the two values in 2 bits each. + * @return Difference of the two values with range 0..2. + */ +#define ETA2_SUB(d, i) \ + (((sword16)(((d) >> ((i) * 4 + 0)) & 0x3)) - \ + ((sword16)(((d) >> ((i) * 4 + 2)) & 0x3))) + +/* Compute polynomial with coefficients distributed according to a centered + * binomial distribution with parameter eta2 from uniform random bytes. + * + * FIPS 203, Algorithm 8: SmaplePolyCBD_eta(B) + * Takes a seed as input and outputs a pseudorandom sample from the distribution + * D_eta(R_q). + * + * @param [out] p Polynomial computed. + * @param [in] r Random bytes. + */ +static void mlkem_cbd_eta2(sword16* p, const byte* r) +{ + unsigned int i; + +#ifndef WORD64_AVAILABLE + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + #endif + /* Take the next 4 bytes, little endian, as a 32 bit value. */ + #ifdef BIG_ENDIAN_ORDER + word32 t = ByteReverseWord32(*(word32*)r); + #else + word32 t = *(word32*)r; + #endif + word32 d; + /* Add second bits to first. */ + d = (t >> 0) & 0x55555555; + d += (t >> 1) & 0x55555555; + /* Values 0, 1 or 2 in consecutive 2 bits. + * 0 - 1/4, 1 - 2/4, 2 - 1/4. */ + + #ifdef WOLFSSL_MLKEM_SMALL + for (j = 0; j < 8; j++) { + p[i + j] = ETA2_SUB(d, j); + } + #else + p[i + 0] = ETA2_SUB(d, 0); + p[i + 1] = ETA2_SUB(d, 1); + p[i + 2] = ETA2_SUB(d, 2); + p[i + 3] = ETA2_SUB(d, 3); + p[i + 4] = ETA2_SUB(d, 4); + p[i + 5] = ETA2_SUB(d, 5); + p[i + 6] = ETA2_SUB(d, 6); + p[i + 7] = ETA2_SUB(d, 7); + #endif + /* -2 - 1/16, -1 - 4/16, 0 - 6/16, 1 - 4/16, 2 - 1/16 */ + + /* Move over used bytes. */ + r += 4; + } +#else + /* Calculate sixteen integer coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 16) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + #endif + /* Take the next 8 bytes, little endian, as a 64 bit value. */ + #ifdef BIG_ENDIAN_ORDER + word64 t = ByteReverseWord64(readUnalignedWord64(r)); + #else + word64 t = readUnalignedWord64(r); + #endif + word64 d; + /* Add second bits to first. */ + d = (t >> 0) & 0x5555555555555555L; + d += (t >> 1) & 0x5555555555555555L; + /* Values 0, 1 or 2 in consecutive 2 bits. + * 0 - 1/4, 1 - 2/4, 2 - 1/4. */ + + #ifdef WOLFSSL_MLKEM_SMALL + for (j = 0; j < 16; j++) { + p[i + j] = ETA2_SUB(d, j); + } + #else + p[i + 0] = ETA2_SUB(d, 0); + p[i + 1] = ETA2_SUB(d, 1); + p[i + 2] = ETA2_SUB(d, 2); + p[i + 3] = ETA2_SUB(d, 3); + p[i + 4] = ETA2_SUB(d, 4); + p[i + 5] = ETA2_SUB(d, 5); + p[i + 6] = ETA2_SUB(d, 6); + p[i + 7] = ETA2_SUB(d, 7); + p[i + 8] = ETA2_SUB(d, 8); + p[i + 9] = ETA2_SUB(d, 9); + p[i + 10] = ETA2_SUB(d, 10); + p[i + 11] = ETA2_SUB(d, 11); + p[i + 12] = ETA2_SUB(d, 12); + p[i + 13] = ETA2_SUB(d, 13); + p[i + 14] = ETA2_SUB(d, 14); + p[i + 15] = ETA2_SUB(d, 15); + #endif + /* -2 - 1/16, -1 - 4/16, 0 - 6/16, 1 - 4/16, 2 - 1/16 */ + + /* Move over used bytes. */ + r += 8; + } +#endif +} + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) +/* Subtract one 3 bit value from another out of a larger number. + * + * FIPS 203, Algorithm 8: SmaplePolyCBD_eta(B) + * Takes a seed as input and outputs a pseudorandom sample from the distribution + * D_eta(R_q). + * + * @param [in] d Value containing sequential 3 bit values. + * @param [in] i Start index of the two values in 3 bits each. + * @return Difference of the two values with range 0..3. + */ +#define ETA3_SUB(d, i) \ + (((sword16)(((d) >> ((i) * 6 + 0)) & 0x7)) - \ + ((sword16)(((d) >> ((i) * 6 + 3)) & 0x7))) + +/* Compute polynomial with coefficients distributed according to a centered + * binomial distribution with parameter eta3 from uniform random bytes. + * + * FIPS 203, Algorithm 8: SmaplePolyCBD_eta(B) + * Takes a seed as input and outputs a pseudorandom sample from the distribution + * D_eta(R_q). + * + * @param [out] p Polynomial computed. + * @param [in] r Random bytes. + */ +static void mlkem_cbd_eta3(sword16* p, const byte* r) +{ + unsigned int i; + +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) || \ + defined(BIG_ENDIAN_ORDER) +#ifndef WORD64_AVAILABLE + /* Calculate four integer coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 4) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + #endif + /* Take the next 3 bytes, little endian, as a 24 bit value. */ + word32 t = (((word32)(r[0])) << 0) | + (((word32)(r[1])) << 8) | + (((word32)(r[2])) << 16); + word32 d; + /* Add second and third bits to first. */ + d = (t >> 0) & 0x00249249; + d += (t >> 1) & 0x00249249; + d += (t >> 2) & 0x00249249; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + #ifdef WOLFSSL_MLKEM_SMALL + for (j = 0; j < 4; j++) { + p[i + j] = ETA3_SUB(d, j); + } + #else + p[i + 0] = ETA3_SUB(d, 0); + p[i + 1] = ETA3_SUB(d, 1); + p[i + 2] = ETA3_SUB(d, 2); + p[i + 3] = ETA3_SUB(d, 3); + #endif + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 3; + } +#else + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + #endif + /* Take the next 6 bytes, little endian, as a 48 bit value. */ + word64 t = (((word64)(r[0])) << 0) | + (((word64)(r[1])) << 8) | + (((word64)(r[2])) << 16) | + (((word64)(r[3])) << 24) | + (((word64)(r[4])) << 32) | + (((word64)(r[5])) << 40); + word64 d; + /* Add second and third bits to first. */ + d = (t >> 0) & 0x0000249249249249L; + d += (t >> 1) & 0x0000249249249249L; + d += (t >> 2) & 0x0000249249249249L; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + #ifdef WOLFSSL_MLKEM_SMALL + for (j = 0; j < 8; j++) { + p[i + j] = ETA3_SUB(d, j); + } + #else + p[i + 0] = ETA3_SUB(d, 0); + p[i + 1] = ETA3_SUB(d, 1); + p[i + 2] = ETA3_SUB(d, 2); + p[i + 3] = ETA3_SUB(d, 3); + p[i + 4] = ETA3_SUB(d, 4); + p[i + 5] = ETA3_SUB(d, 5); + p[i + 6] = ETA3_SUB(d, 6); + p[i + 7] = ETA3_SUB(d, 7); + #endif + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 6; + } +#endif /* WORD64_AVAILABLE */ +#else + /* Calculate eight integer coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 16) { + const word32* r32 = (const word32*)r; + /* Take the next 12 bytes, little endian, as 24 bit values. */ + word32 t0 = r32[0] & 0xffffff; + word32 t1 = ((r32[0] >> 24) | (r32[1] << 8)) & 0xffffff; + word32 t2 = ((r32[1] >> 16) | (r32[2] << 16)) & 0xffffff; + word32 t3 = r32[2] >> 8 ; + word32 d0; + word32 d1; + word32 d2; + word32 d3; + + /* Add second and third bits to first. */ + d0 = (t0 >> 0) & 0x00249249; + d0 += (t0 >> 1) & 0x00249249; + d0 += (t0 >> 2) & 0x00249249; + d1 = (t1 >> 0) & 0x00249249; + d1 += (t1 >> 1) & 0x00249249; + d1 += (t1 >> 2) & 0x00249249; + d2 = (t2 >> 0) & 0x00249249; + d2 += (t2 >> 1) & 0x00249249; + d2 += (t2 >> 2) & 0x00249249; + d3 = (t3 >> 0) & 0x00249249; + d3 += (t3 >> 1) & 0x00249249; + d3 += (t3 >> 2) & 0x00249249; + /* Values 0, 1, 2 or 3 in consecutive 3 bits. + * 0 - 1/8, 1 - 3/8, 2 - 3/8, 3 - 1/8. */ + + p[i + 0] = ETA3_SUB(d0, 0); + p[i + 1] = ETA3_SUB(d0, 1); + p[i + 2] = ETA3_SUB(d0, 2); + p[i + 3] = ETA3_SUB(d0, 3); + p[i + 4] = ETA3_SUB(d1, 0); + p[i + 5] = ETA3_SUB(d1, 1); + p[i + 6] = ETA3_SUB(d1, 2); + p[i + 7] = ETA3_SUB(d1, 3); + p[i + 8] = ETA3_SUB(d2, 0); + p[i + 9] = ETA3_SUB(d2, 1); + p[i + 10] = ETA3_SUB(d2, 2); + p[i + 11] = ETA3_SUB(d2, 3); + p[i + 12] = ETA3_SUB(d3, 0); + p[i + 13] = ETA3_SUB(d3, 1); + p[i + 14] = ETA3_SUB(d3, 2); + p[i + 15] = ETA3_SUB(d3, 3); + /* -3-1/64, -2-6/64, -1-15/64, 0-20/64, 1-15/64, 2-6/64, 3-1/64 */ + + /* Move over used bytes. */ + r += 12; + } +#endif /* WOLFSSL_SMALL_STACK || WOLFSSL_MLKEM_NO_LARGE_CODE || + * BIG_ENDIAN_ORDER */ +} +#endif + +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) + +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * FIPS 203, Algorithm 13: K-PKE.KeyGen(d) + * ... + * 9: s[i] <- SamplePolyCBD_eta_1(PRF_eta_1(rho, N)) + * ... + * 13: e[i] <- SamplePolyCBD_eta_1(PRF_eta_1(rho, N)) + * ... + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 10: y[i] <- SamplePolyCBD_eta_1(PRF_eta_1(r, N)) + * ... + * + * @param [in, out] prf Pseudo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @param [in] eta1 Size of noise/error integers. + * @return 0 on success. + */ +static int mlkem_get_noise_eta1_c(MLKEM_PRF_T* prf, sword16* p, + const byte* seed, byte eta1) +{ + int ret; + + (void)eta1; + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if (eta1 == MLKEM_CBD_ETA3) { + byte rand[ETA3_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = mlkem_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + /* Sample for values in range -3..3 from 3 bits of random. */ + mlkem_cbd_eta3(p, rand); + } + } + else +#endif + { + byte rand[ETA2_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = mlkem_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + /* Sample for values in range -2..2 from 2 bits of random. */ + mlkem_cbd_eta2(p, rand); + } + } + + return ret; +} + +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. Values -2..2 + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [in, out] prf Pseudo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_eta2_c(MLKEM_PRF_T* prf, sword16* p, + const byte* seed) +{ + int ret; + byte rand[ETA2_RAND_SIZE]; + + /* Calculate random bytes from seed with PRF. */ + ret = mlkem_prf(prf, rand, sizeof(rand), seed); + if (ret == 0) { + mlkem_cbd_eta2(p, rand); + } + + return ret; +} + +#endif + +#ifdef USE_INTEL_SPEEDUP +#define PRF_RAND_SZ (2 * SHA3_256_BYTES) + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) || \ + defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void mlkem_get_noise_x4_eta2_avx2(byte* rand, byte* seed, byte o) +{ + int i; + word64 state[25 * 4]; + + for (i = 0; i < 4; i++) { + state[4*4 + i] = 0x1f00 + i + o; + } + + mlkem_sha3_256_blocksx4_seed_avx2(state, seed); + mlkem_redistribute_16_rand_avx2(state, rand + 0 * ETA2_RAND_SIZE, + rand + 1 * ETA2_RAND_SIZE, rand + 2 * ETA2_RAND_SIZE, + rand + 3 * ETA2_RAND_SIZE); +} +#endif + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Get noise/error by calculating random bytes and sampling to a binomial + * distribution. Values -2..2 + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [in, out] prf Pseudo-random function object. + * @param [out] p Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_eta2_avx2(MLKEM_PRF_T* prf, sword16* p, + const byte* seed) +{ + word64 state[25]; + + (void)prf; + + /* Put first WC_ML_KEM_SYM_SZ bytes og key into blank state. */ + readUnalignedWords64(state, seed, WC_ML_KEM_SYM_SZ / sizeof(word64)); + /* Last byte in with end of content marker. */ + state[WC_ML_KEM_SYM_SZ / 8] = 0x1f00 | seed[WC_ML_KEM_SYM_SZ]; + /* Set rest of state to 0. */ + XMEMSET(state + WC_ML_KEM_SYM_SZ / 8 + 1, 0, + (25 - WC_ML_KEM_SYM_SZ / 8 - 1) * sizeof(word64)); + /* ... except for rate marker. */ + state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); + + /* Perform a block operation on the state for next block of output. */ + if (IS_INTEL_BMI2(cpuid_flags)) { + sha3_block_bmi2(state); + } + else if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + sha3_block_avx2(state); + RESTORE_VECTOR_REGISTERS(); + } + else { + BlockSha3(state); + } + mlkem_cbd_eta2_avx2(p, (byte*)state); + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void mlkem_get_noise_x4_eta3_avx2(byte* rand, byte* seed) +{ + word64 state[25 * 4]; + int i; + + state[4*4 + 0] = 0x1f00 + 0; + state[4*4 + 1] = 0x1f00 + 1; + state[4*4 + 2] = 0x1f00 + 2; + state[4*4 + 3] = 0x1f00 + 3; + + mlkem_sha3_256_blocksx4_seed_avx2(state, seed); + mlkem_redistribute_17_rand_avx2(state, rand + 0 * PRF_RAND_SZ, + rand + 1 * PRF_RAND_SZ, rand + 2 * PRF_RAND_SZ, + rand + 3 * PRF_RAND_SZ); + i = SHA3_256_BYTES; + sha3_blocksx4_avx2(state); + mlkem_redistribute_8_rand_avx2(state, rand + i + 0 * PRF_RAND_SZ, + rand + i + 1 * PRF_RAND_SZ, rand + i + 2 * PRF_RAND_SZ, + rand + i + 3 * PRF_RAND_SZ); +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Pseudo-random function object. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k2_avx2(MLKEM_PRF_T* prf, sword16* vec1, + sword16* vec2, sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[4 * PRF_RAND_SZ]; + + mlkem_get_noise_x4_eta3_avx2(rand, seed); + mlkem_cbd_eta3_avx2(vec1 , rand + 0 * PRF_RAND_SZ); + mlkem_cbd_eta3_avx2(vec1 + MLKEM_N, rand + 1 * PRF_RAND_SZ); + if (poly == NULL) { + mlkem_cbd_eta3_avx2(vec2 , rand + 2 * PRF_RAND_SZ); + mlkem_cbd_eta3_avx2(vec2 + MLKEM_N, rand + 3 * PRF_RAND_SZ); + } + else { + mlkem_cbd_eta2_avx2(vec2 , rand + 2 * PRF_RAND_SZ); + mlkem_cbd_eta2_avx2(vec2 + MLKEM_N, rand + 3 * PRF_RAND_SZ); + + seed[WC_ML_KEM_SYM_SZ] = 4; + ret = mlkem_get_noise_eta2_avx2(prf, poly, seed); + } + + return ret; +} +#endif + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k3_avx2(sword16* vec1, sword16* vec2, sword16* poly, + byte* seed) +{ + byte rand[4 * ETA2_RAND_SIZE]; + + mlkem_get_noise_x4_eta2_avx2(rand, seed, 0); + mlkem_cbd_eta2_avx2(vec1 , rand + 0 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec1 + 1 * MLKEM_N, rand + 1 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec1 + 2 * MLKEM_N, rand + 2 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec2 , rand + 3 * ETA2_RAND_SIZE); + mlkem_get_noise_x4_eta2_avx2(rand, seed, 4); + mlkem_cbd_eta2_avx2(vec2 + 1 * MLKEM_N, rand + 0 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec2 + 2 * MLKEM_N, rand + 1 * ETA2_RAND_SIZE); + if (poly != NULL) { + mlkem_cbd_eta2_avx2(poly, rand + 2 * ETA2_RAND_SIZE); + } + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Pseudo-random function object. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k4_avx2(MLKEM_PRF_T* prf, sword16* vec1, + sword16* vec2, sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[4 * ETA2_RAND_SIZE]; + + (void)prf; + + mlkem_get_noise_x4_eta2_avx2(rand, seed, 0); + mlkem_cbd_eta2_avx2(vec1 , rand + 0 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec1 + 1 * MLKEM_N, rand + 1 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec1 + 2 * MLKEM_N, rand + 2 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec1 + 3 * MLKEM_N, rand + 3 * ETA2_RAND_SIZE); + mlkem_get_noise_x4_eta2_avx2(rand, seed, 4); + mlkem_cbd_eta2_avx2(vec2 , rand + 0 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec2 + 1 * MLKEM_N, rand + 1 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec2 + 2 * MLKEM_N, rand + 2 * ETA2_RAND_SIZE); + mlkem_cbd_eta2_avx2(vec2 + 3 * MLKEM_N, rand + 3 * ETA2_RAND_SIZE); + if (poly != NULL) { + seed[WC_ML_KEM_SYM_SZ] = 8; + ret = mlkem_get_noise_eta2_avx2(prf, poly, seed); + } + + return ret; +} +#endif +#endif /* USE_INTEL_SPEEDUP */ + +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + +#define PRF_RAND_SZ (2 * SHA3_256_BYTES) + +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void mlkem_get_noise_x3_eta2_aarch64(byte* rand, byte* seed, byte o) +{ + word64* state = (word64*)rand; + + state[0*25 + 4] = 0x1f00 + 0 + o; + state[1*25 + 4] = 0x1f00 + 1 + o; + state[2*25 + 4] = 0x1f00 + 2 + o; + + mlkem_shake256_blocksx3_seed_neon(state, seed); +} + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + */ +static void mlkem_get_noise_x3_eta3_aarch64(byte* rand, byte* seed, byte o) +{ + word64 state[3 * 25]; + + state[0*25 + 4] = 0x1f00 + 0 + o; + state[1*25 + 4] = 0x1f00 + 1 + o; + state[2*25 + 4] = 0x1f00 + 2 + o; + + mlkem_shake256_blocksx3_seed_neon(state, seed); + XMEMCPY(rand + 0 * ETA3_RAND_SIZE, state + 0*25, SHA3_256_BYTES); + XMEMCPY(rand + 1 * ETA3_RAND_SIZE, state + 1*25, SHA3_256_BYTES); + XMEMCPY(rand + 2 * ETA3_RAND_SIZE, state + 2*25, SHA3_256_BYTES); + mlkem_sha3_blocksx3_neon(state); + rand += SHA3_256_BYTES; + XMEMCPY(rand + 0 * ETA3_RAND_SIZE, state + 0*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); + XMEMCPY(rand + 1 * ETA3_RAND_SIZE, state + 1*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); + XMEMCPY(rand + 2 * ETA3_RAND_SIZE, state + 2*25, + ETA3_RAND_SIZE - SHA3_256_BYTES); +} + +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + * @return 0 on success. + */ +static void mlkem_get_noise_eta3_aarch64(byte* rand, byte* seed, byte o) +{ + word64 state[25]; + + state[0] = ((word64*)seed)[0]; + state[1] = ((word64*)seed)[1]; + state[2] = ((word64*)seed)[2]; + state[3] = ((word64*)seed)[3]; + state[4] = 0x1f00 + o; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[16] = W64LIT(0x8000000000000000); + BlockSha3(state); + XMEMCPY(rand , state, SHA3_256_BYTES); + BlockSha3(state); + XMEMCPY(rand + SHA3_256_BYTES, state, ETA3_RAND_SIZE - SHA3_256_BYTES); +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k2_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[3 * 25 * 8]; + + mlkem_get_noise_x3_eta3_aarch64(rand, seed, 0); + mlkem_cbd_eta3(vec1 , rand + 0 * ETA3_RAND_SIZE); + mlkem_cbd_eta3(vec1 + MLKEM_N, rand + 1 * ETA3_RAND_SIZE); + if (poly == NULL) { + mlkem_cbd_eta3(vec2 , rand + 2 * ETA3_RAND_SIZE); + mlkem_get_noise_eta3_aarch64(rand, seed, 3); + mlkem_cbd_eta3(vec2 + MLKEM_N, rand ); + } + else { + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 2); + mlkem_cbd_eta2(vec2 , rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec2 + MLKEM_N, rand + 1 * 25 * 8); + mlkem_cbd_eta2(poly , rand + 2 * 25 * 8); + } + + return ret; +} +#endif + +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Get the noise/error by calculating random bytes. + * + * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE,m,r) + * ... + * 14: e1[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * 17: e2[i] <- SamplePolyCBD_eta_2(PRF_eta_2(r, N)) + * ... + * + * @param [out] rand Random number byte array. + * @param [in] seed Seed to generate random from. + * @param [in] o Offset of seed count. + * @return 0 on success. + */ +static void mlkem_get_noise_eta2_aarch64(byte* rand, byte* seed, byte o) +{ + word64* state = (word64*)rand; + + state[0] = ((word64*)seed)[0]; + state[1] = ((word64*)seed)[1]; + state[2] = ((word64*)seed)[2]; + state[3] = ((word64*)seed)[3]; + /* Transposed value same as not. */ + state[4] = 0x1f00 + o; + XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); + state[16] = W64LIT(0x8000000000000000); + BlockSha3(state); +} + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k3_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + byte rand[3 * 25 * 8]; + + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 0); + mlkem_cbd_eta2(vec1 , rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec1 + 1 * MLKEM_N, rand + 1 * 25 * 8); + mlkem_cbd_eta2(vec1 + 2 * MLKEM_N, rand + 2 * 25 * 8); + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 3); + mlkem_cbd_eta2(vec2 , rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec2 + 1 * MLKEM_N, rand + 1 * 25 * 8); + mlkem_cbd_eta2(vec2 + 2 * MLKEM_N, rand + 2 * 25 * 8); + if (poly != NULL) { + mlkem_get_noise_eta2_aarch64(rand, seed, 6); + mlkem_cbd_eta2(poly , rand + 0 * 25 * 8); + } + + return 0; +} +#endif + +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_k4_aarch64(sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + int ret = 0; + byte rand[3 * 25 * 8]; + + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 0); + mlkem_cbd_eta2(vec1 , rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec1 + 1 * MLKEM_N, rand + 1 * 25 * 8); + mlkem_cbd_eta2(vec1 + 2 * MLKEM_N, rand + 2 * 25 * 8); + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 3); + mlkem_cbd_eta2(vec1 + 3 * MLKEM_N, rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec2 , rand + 1 * 25 * 8); + mlkem_cbd_eta2(vec2 + 1 * MLKEM_N, rand + 2 * 25 * 8); + mlkem_get_noise_x3_eta2_aarch64(rand, seed, 6); + mlkem_cbd_eta2(vec2 + 2 * MLKEM_N, rand + 0 * 25 * 8); + mlkem_cbd_eta2(vec2 + 3 * MLKEM_N, rand + 1 * 25 * 8); + if (poly != NULL) { + mlkem_cbd_eta2(poly, rand + 2 * 25 * 8); + } + + return ret; +} +#endif +#endif /* __aarch64__ && WOLFSSL_ARMASM */ + +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Pseudo-random function object. + * @param [in] k Number of polynomials in vector. + * @param [out] vec1 First Vector of polynomials. + * @param [in] eta1 Size of noise/error integers with first vector. + * @param [out] vec2 Second Vector of polynomials. + * @param [in] eta2 Size of noise/error integers with second vector. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +static int mlkem_get_noise_c(MLKEM_PRF_T* prf, int k, sword16* vec1, int eta1, + sword16* vec2, int eta2, sword16* poly, byte* seed) +{ + int ret = 0; + int i; + + /* First noise generation has a seed with 0x00 appended. */ + seed[WC_ML_KEM_SYM_SZ] = 0; + /* Generate noise as private key. */ + for (i = 0; (ret == 0) && (i < k); i++) { + /* Generate noise for each dimension of vector. */ + ret = mlkem_get_noise_eta1_c(prf, vec1 + i * MLKEM_N, seed, eta1); + /* Increment value of appended byte. */ + seed[WC_ML_KEM_SYM_SZ]++; + } + if ((ret == 0) && (vec2 != NULL)) { + /* Generate noise for error. */ + for (i = 0; (ret == 0) && (i < k); i++) { + /* Generate noise for each dimension of vector. */ + ret = mlkem_get_noise_eta1_c(prf, vec2 + i * MLKEM_N, seed, eta2); + /* Increment value of appended byte. */ + seed[WC_ML_KEM_SYM_SZ]++; + } + } + else { + seed[WC_ML_KEM_SYM_SZ] = 2 * k; + } + if ((ret == 0) && (poly != NULL)) { + /* Generating random error polynomial. */ + ret = mlkem_get_noise_eta2_c(prf, poly, seed); + } + + return ret; +} + +#endif /* __aarch64__ && WOLFSSL_ARMASM */ + +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Pseudo-random function object. + * @param [in] k Number of polynomials in vector. + * @param [out] vec1 First Vector of polynomials. + * @param [out] vec2 Second Vector of polynomials. + * @param [out] poly Polynomial. + * @param [in] seed Seed to use when calculating random. + * @return 0 on success. + */ +int mlkem_get_noise(MLKEM_PRF_T* prf, int k, sword16* vec1, sword16* vec2, + sword16* poly, byte* seed) +{ + int ret; + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if (k == WC_ML_KEM_512_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_get_noise_k2_aarch64(vec1, vec2, poly, seed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_get_noise_k2_avx2(prf, vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + if (poly == NULL) { + ret = mlkem_get_noise_c(prf, k, vec1, MLKEM_CBD_ETA3, vec2, + MLKEM_CBD_ETA3, NULL, seed); + } + else { + ret = mlkem_get_noise_c(prf, k, vec1, MLKEM_CBD_ETA3, vec2, + MLKEM_CBD_ETA2, poly, seed); + } +#endif + } + else +#endif +#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) + if (k == WC_ML_KEM_768_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_get_noise_k3_aarch64(vec1, vec2, poly, seed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_get_noise_k3_avx2(vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + { + ret = mlkem_get_noise_c(prf, k, vec1, MLKEM_CBD_ETA2, vec2, + MLKEM_CBD_ETA2, poly, seed); + } +#endif + } + else +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) + if (k == WC_ML_KEM_1024_K) { +#if defined(WOLFSSL_ARMASM) && defined(__aarch64__) + ret = mlkem_get_noise_k4_aarch64(vec1, vec2, poly, seed); +#else + #ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + ret = mlkem_get_noise_k4_avx2(prf, vec1, vec2, poly, seed); + RESTORE_VECTOR_REGISTERS(); + } + else + #endif + { + ret = mlkem_get_noise_c(prf, k, vec1, MLKEM_CBD_ETA2, vec2, + MLKEM_CBD_ETA2, poly, seed); + } +#endif + } + else +#endif + { + ret = BAD_STATE_E; + } + + (void)prf; + + return ret; +} + +#if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \ + defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) +/* Get the noise/error by calculating random bytes and sampling to a binomial + * distribution. + * + * @param [in, out] prf Pseudo-random function object. + * @param [in] k Number of polynomials in vector. + * @param [out] vec2 Second Vector of polynomials. + * @param [in] seed Seed to use when calculating random. + * @param [in] i Index of vector to generate. + * @param [in] make Indicates generation is for making a key. + * @return 0 on success. + */ +static int mlkem_get_noise_i(MLKEM_PRF_T* prf, int k, sword16* vec2, + byte* seed, int i, int make) +{ + int ret; + + /* Initialize the PRF (generating matrix A leaves it in uninitialized + * state). */ + mlkem_prf_init(prf); + + /* Set index of polynomial of second vector into seed. */ + seed[WC_ML_KEM_SYM_SZ] = k + i; +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) + if ((k == WC_ML_KEM_512_K) && make) { + ret = mlkem_get_noise_eta1_c(prf, vec2, seed, MLKEM_CBD_ETA3); + } + else +#endif + { + ret = mlkem_get_noise_eta1_c(prf, vec2, seed, MLKEM_CBD_ETA2); + } + + (void)make; + return ret; +} +#endif + +/******************************************************************************/ + +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) +/* Compare two byte arrays of equal size. + * + * @param [in] a First array to compare. + * @param [in] b Second array to compare. + * @param [in] sz Size of arrays in bytes. + * @return 0 on success. + * @return -1 on failure. + */ +static int mlkem_cmp_c(const byte* a, const byte* b, int sz) +{ + int i; + byte r = 0; + + /* Constant time comparison of the encapsulated message and cipher text. */ + for (i = 0; i < sz; i++) { + r |= a[i] ^ b[i]; + } + return 0 - ((-(word32)r) >> 31); +} +#endif + +/* Compare two byte arrays of equal size. + * + * @param [in] a First array to compare. + * @param [in] b Second array to compare. + * @param [in] sz Size of arrays in bytes. + * @return 0 on success. + * @return -1 on failure. + */ +int mlkem_cmp(const byte* a, const byte* b, int sz) +{ +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + return mlkem_cmp_neon(a, b, sz); +#else + int fail; + +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + fail = mlkem_cmp_avx2(a, b, sz); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + fail = mlkem_cmp_c(a, b, sz); + } + + return fail; +#endif +} + +/******************************************************************************/ + +#if !defined(WOLFSSL_ARMASM) + +/* Conditional subtraction of q to each coefficient of a polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in, out] p Polynomial. + */ +static MLKEM_NOINLINE void mlkem_csubq_c(sword16* p) +{ + unsigned int i; + + for (i = 0; i < MLKEM_N; ++i) { + sword16 t = p[i] - MLKEM_Q; + /* When top bit set, -ve number - need to add q back. */ + p[i] = ((t >> 15) & MLKEM_Q) + t; + } +} + +#elif defined(__aarch64__) + +/* Conditional subtraction of q to each coefficient of a polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in, out] p Polynomial. + */ +#define mlkem_csubq_c mlkem_csubq_neon + +#elif defined(WOLFSSL_ARMASM_THUMB2) + +/* Conditional subtraction of q to each coefficient of a polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in, out] p Polynomial. + */ +#define mlkem_csubq_c mlkem_thumb2_csubq + +#else + +/* Conditional subtraction of q to each coefficient of a polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in, out] p Polynomial. + */ +#define mlkem_csubq_c mlkem_arm32_csubq + +#endif + +/******************************************************************************/ + +#if defined(CONV_WITH_DIV) || !defined(WORD64_AVAILABLE) + +/* Compress value. + * + * Uses div operator that may be slow. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] s Shift amount to apply to value being compressed. + * @param [in] m Mask to apply get the require number of bits. + * @return Compressed value. + */ +#define TO_COMP_WORD_VEC(v, i, j, k, s, m) \ + ((((word32)v[i * MLKEM_N + j + k] << s) + MLKEM_Q_HALF) / MLKEM_Q) & m + +/* Compress value to 10 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_10(v, i, j, k) \ + TO_COMP_WORD_VEC(v, i, j, k, 10, 0x3ff) + +/* Compress value to 11 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_11(v, i, j, k) \ + TO_COMP_WORD_VEC(v, i, j, k, 11, 0x7ff) + +#else + +/* Multiplier that does div q. + * ((1 << 53) + MLKEM_Q_HALF) / MLKEM_Q + */ +#define MLKEM_V53 0x275f6ed0176UL +/* Multiplier times half of q. + * MLKEM_V53 * (MLKEM_Q_HALF + 1) + */ +#define MLKEM_V53_HALF 0x10013afb768076UL + +/* Multiplier that does div q. + * ((1 << 54) + MLKEM_Q_HALF) / MLKEM_Q + */ +#define MLKEM_V54 0x4ebedda02ecUL +/* Multiplier times half of q. + * MLKEM_V54 * (MLKEM_Q_HALF + 1) + */ +#define MLKEM_V54_HALF 0x200275f6ed00ecUL + +/* Compress value to 10 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_10(v, i, j, k) \ + ((((MLKEM_V54 << 10) * (v)[(i) * MLKEM_N + (j) + (k)]) + \ + MLKEM_V54_HALF) >> 54) + +/* Compress value to 11 bits. + * + * Uses mul instead of div. + * Only works for values in range: 0..3228 + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_11(v, i, j, k) \ + ((((MLKEM_V53 << 11) * (v)[(i) * MLKEM_N + (j) + (k)]) + \ + MLKEM_V53_HALF) >> 53) + +#endif /* CONV_WITH_DIV */ + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Compress the vector of polynomials into a byte array with 10 bits each. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_vec_compress_10_c(byte* r, sword16* v, unsigned int k) +{ + unsigned int i; + unsigned int j; + + for (i = 0; i < k; i++) { + /* Reduce each coefficient to mod q. */ + mlkem_csubq_c(v + i * MLKEM_N); + /* All values are now positive. */ + } + + /* Each polynomial. */ + for (i = 0; i < k; i++) { +#if defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_MLKEM_NO_LARGE_CODE) || \ + defined(BIG_ENDIAN_ORDER) + /* Each 4 polynomial coefficients. */ + for (j = 0; j < MLKEM_N; j += 4) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int l; + sword16 t[4]; + /* Compress four polynomial values to 10 bits each. */ + for (l = 0; l < 4; l++) { + t[l] = TO_COMP_WORD_10(v, i, j, l); + } + + /* Pack four 10-bit values into byte array. */ + r[ 0] = (t[0] >> 0); + r[ 1] = (t[0] >> 8) | (t[1] << 2); + r[ 2] = (t[1] >> 6) | (t[2] << 4); + r[ 3] = (t[2] >> 4) | (t[3] << 6); + r[ 4] = (t[3] >> 2); + #else + /* Compress four polynomial values to 10 bits each. */ + sword16 t0 = TO_COMP_WORD_10(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_10(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_10(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_10(v, i, j, 3); + + /* Pack four 10-bit values into byte array. */ + r[ 0] = (t0 >> 0); + r[ 1] = (t0 >> 8) | (t1 << 2); + r[ 2] = (t1 >> 6) | (t2 << 4); + r[ 3] = (t2 >> 4) | (t3 << 6); + r[ 4] = (t3 >> 2); + #endif + + /* Move over set bytes. */ + r += 5; + } +#else + /* Each 16 polynomial coefficients. */ + for (j = 0; j < MLKEM_N; j += 16) { + /* Compress four polynomial values to 10 bits each. */ + sword16 t0 = TO_COMP_WORD_10(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_10(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_10(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_10(v, i, j, 3); + sword16 t4 = TO_COMP_WORD_10(v, i, j, 4); + sword16 t5 = TO_COMP_WORD_10(v, i, j, 5); + sword16 t6 = TO_COMP_WORD_10(v, i, j, 6); + sword16 t7 = TO_COMP_WORD_10(v, i, j, 7); + sword16 t8 = TO_COMP_WORD_10(v, i, j, 8); + sword16 t9 = TO_COMP_WORD_10(v, i, j, 9); + sword16 t10 = TO_COMP_WORD_10(v, i, j, 10); + sword16 t11 = TO_COMP_WORD_10(v, i, j, 11); + sword16 t12 = TO_COMP_WORD_10(v, i, j, 12); + sword16 t13 = TO_COMP_WORD_10(v, i, j, 13); + sword16 t14 = TO_COMP_WORD_10(v, i, j, 14); + sword16 t15 = TO_COMP_WORD_10(v, i, j, 15); + + word32* r32 = (word32*)r; + /* Pack sixteen 10-bit values into byte array. */ + r32[0] = t0 | ((word32)t1 << 10) | ((word32)t2 << 20) | + ((word32)t3 << 30); + r32[1] = (t3 >> 2) | ((word32)t4 << 8) | ((word32)t5 << 18) | + ((word32)t6 << 28); + r32[2] = (t6 >> 4) | ((word32)t7 << 6) | ((word32)t8 << 16) | + ((word32)t9 << 26); + r32[3] = (t9 >> 6) | ((word32)t10 << 4) | ((word32)t11 << 14) | + ((word32)t12 << 24); + r32[4] = (t12 >> 8) | ((word32)t13 << 2) | ((word32)t14 << 12) | + ((word32)t15 << 22); + + /* Move over set bytes. */ + r += 20; + } +#endif + } +} + +/* Compress the vector of polynomials into a byte array with 10 bits each. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_vec_compress_10(byte* r, sword16* v, unsigned int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_compress_10_avx2(r, v, k); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_vec_compress_10_c(r, v, k); + } +} +#endif + +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Compress the vector of polynomials into a byte array with 11 bits each. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + */ +static void mlkem_vec_compress_11_c(byte* r, sword16* v) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int k; +#endif + + for (i = 0; i < 4; i++) { + /* Reduce each coefficient to mod q. */ + mlkem_csubq_c(v + i * MLKEM_N); + /* All values are now positive. */ + } + + /* Each polynomial. */ + for (i = 0; i < 4; i++) { + /* Each 8 polynomial coefficients. */ + for (j = 0; j < MLKEM_N; j += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + sword16 t[8]; + /* Compress eight polynomial values to 11 bits each. */ + for (k = 0; k < 8; k++) { + t[k] = TO_COMP_WORD_11(v, i, j, k); + } + + /* Pack eight 11-bit values into byte array. */ + r[ 0] = (t[0] >> 0); + r[ 1] = (t[0] >> 8) | (t[1] << 3); + r[ 2] = (t[1] >> 5) | (t[2] << 6); + r[ 3] = (t[2] >> 2); + r[ 4] = (t[2] >> 10) | (t[3] << 1); + r[ 5] = (t[3] >> 7) | (t[4] << 4); + r[ 6] = (t[4] >> 4) | (t[5] << 7); + r[ 7] = (t[5] >> 1); + r[ 8] = (t[5] >> 9) | (t[6] << 2); + r[ 9] = (t[6] >> 6) | (t[7] << 5); + r[10] = (t[7] >> 3); + #else + /* Compress eight polynomial values to 11 bits each. */ + sword16 t0 = TO_COMP_WORD_11(v, i, j, 0); + sword16 t1 = TO_COMP_WORD_11(v, i, j, 1); + sword16 t2 = TO_COMP_WORD_11(v, i, j, 2); + sword16 t3 = TO_COMP_WORD_11(v, i, j, 3); + sword16 t4 = TO_COMP_WORD_11(v, i, j, 4); + sword16 t5 = TO_COMP_WORD_11(v, i, j, 5); + sword16 t6 = TO_COMP_WORD_11(v, i, j, 6); + sword16 t7 = TO_COMP_WORD_11(v, i, j, 7); + + /* Pack eight 11-bit values into byte array. */ + r[ 0] = (t0 >> 0); + r[ 1] = (t0 >> 8) | (t1 << 3); + r[ 2] = (t1 >> 5) | (t2 << 6); + r[ 3] = (t2 >> 2); + r[ 4] = (t2 >> 10) | (t3 << 1); + r[ 5] = (t3 >> 7) | (t4 << 4); + r[ 6] = (t4 >> 4) | (t5 << 7); + r[ 7] = (t5 >> 1); + r[ 8] = (t5 >> 9) | (t6 << 2); + r[ 9] = (t6 >> 6) | (t7 << 5); + r[10] = (t7 >> 3); + #endif + + /* Move over set bytes. */ + r += 11; + } + } +} + +/* Compress the vector of polynomials into a byte array with 11 bits each. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] v Vector of polynomials. + */ +void mlkem_vec_compress_11(byte* r, sword16* v) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_compress_11_avx2(r, v, 4); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_vec_compress_11_c(r, v); + } +} +#endif +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE || !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +/* Decompress a 10 bit value. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_10(v, i, j, k, t) \ + v[(i) * MLKEM_N + 4 * (j) + (k)] = \ + (word16)((((word32)((t) & 0x3ff) * MLKEM_Q) + 512) >> 10) + +/* Decompress an 11 bit value. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index of polynomial in vector. + * @param [in] j Index into polynomial. + * @param [in] k Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_11(v, i, j, k, t) \ + v[(i) * MLKEM_N + 8 * (j) + (k)] = \ + (word16)((((word32)((t) & 0x7ff) * MLKEM_Q) + 1024) >> 11) + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Decompress the byte array of packed 10 bits into vector of polynomials. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_vec_decompress_10_c(sword16* v, const byte* b, unsigned int k) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int l; +#endif + + /* Each polynomial. */ + for (i = 0; i < k; i++) { + /* Each 4 polynomial coefficients. */ + for (j = 0; j < MLKEM_N / 4; j++) { + #ifdef WOLFSSL_MLKEM_SMALL + word16 t[4]; + /* Extract out 4 values of 10 bits each. */ + t[0] = (b[0] >> 0) | ((word16)b[ 1] << 8); + t[1] = (b[1] >> 2) | ((word16)b[ 2] << 6); + t[2] = (b[2] >> 4) | ((word16)b[ 3] << 4); + t[3] = (b[3] >> 6) | ((word16)b[ 4] << 2); + b += 5; + + /* Decompress 4 values. */ + for (l = 0; l < 4; l++) { + DECOMP_10(v, i, j, l, t[l]); + } + #else + /* Extract out 4 values of 10 bits each. */ + sword16 t0 = (b[0] >> 0) | ((word16)b[ 1] << 8); + sword16 t1 = (b[1] >> 2) | ((word16)b[ 2] << 6); + sword16 t2 = (b[2] >> 4) | ((word16)b[ 3] << 4); + sword16 t3 = (b[3] >> 6) | ((word16)b[ 4] << 2); + b += 5; + + /* Decompress 4 values. */ + DECOMP_10(v, i, j, 0, t0); + DECOMP_10(v, i, j, 1, t1); + DECOMP_10(v, i, j, 2, t2); + DECOMP_10(v, i, j, 3, t3); + #endif + } + } +} + +/* Decompress the byte array of packed 10 bits into vector of polynomials. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_vec_decompress_10(sword16* v, const byte* b, unsigned int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_decompress_10_avx2(v, b, k); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_vec_decompress_10_c(v, b, k); + } +} +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Decompress the byte array of packed 11 bits into vector of polynomials. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + */ +static void mlkem_vec_decompress_11_c(sword16* v, const byte* b) +{ + unsigned int i; + unsigned int j; +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int l; +#endif + + /* Each polynomial. */ + for (i = 0; i < 4; i++) { + /* Each 8 polynomial coefficients. */ + for (j = 0; j < MLKEM_N / 8; j++) { + #ifdef WOLFSSL_MLKEM_SMALL + word16 t[8]; + /* Extract out 8 values of 11 bits each. */ + t[0] = (b[0] >> 0) | ((word16)b[ 1] << 8); + t[1] = (b[1] >> 3) | ((word16)b[ 2] << 5); + t[2] = (b[2] >> 6) | ((word16)b[ 3] << 2) | + ((word16)b[4] << 10); + t[3] = (b[4] >> 1) | ((word16)b[ 5] << 7); + t[4] = (b[5] >> 4) | ((word16)b[ 6] << 4); + t[5] = (b[6] >> 7) | ((word16)b[ 7] << 1) | + ((word16)b[8] << 9); + t[6] = (b[8] >> 2) | ((word16)b[ 9] << 6); + t[7] = (b[9] >> 5) | ((word16)b[10] << 3); + b += 11; + + /* Decompress 8 values. */ + for (l = 0; l < 8; l++) { + DECOMP_11(v, i, j, l, t[l]); + } + #else + /* Extract out 8 values of 11 bits each. */ + sword16 t0 = (b[0] >> 0) | ((word16)b[ 1] << 8); + sword16 t1 = (b[1] >> 3) | ((word16)b[ 2] << 5); + sword16 t2 = (b[2] >> 6) | ((word16)b[ 3] << 2) | + ((word16)b[4] << 10); + sword16 t3 = (b[4] >> 1) | ((word16)b[ 5] << 7); + sword16 t4 = (b[5] >> 4) | ((word16)b[ 6] << 4); + sword16 t5 = (b[6] >> 7) | ((word16)b[ 7] << 1) | + ((word16)b[8] << 9); + sword16 t6 = (b[8] >> 2) | ((word16)b[ 9] << 6); + sword16 t7 = (b[9] >> 5) | ((word16)b[10] << 3); + b += 11; + + /* Decompress 8 values. */ + DECOMP_11(v, i, j, 0, t0); + DECOMP_11(v, i, j, 1, t1); + DECOMP_11(v, i, j, 2, t2); + DECOMP_11(v, i, j, 3, t3); + DECOMP_11(v, i, j, 4, t4); + DECOMP_11(v, i, j, 5, t5); + DECOMP_11(v, i, j, 6, t6); + DECOMP_11(v, i, j, 7, t7); + #endif + } + } +} + +/* Decompress the byte array of packed 11 bits into vector of polynomials. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] v Vector of polynomials. + * @param [in] b Array of bytes. + */ +void mlkem_vec_decompress_11(sword16* v, const byte* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_decompress_11_avx2(v, b, 4); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_vec_decompress_11_c(v, b); + } +} +#endif +#endif /* !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifdef CONV_WITH_DIV + +/* Compress value. + * + * Uses div operator that may be slow. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] v Vector of polynomials. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] s Shift amount to apply to value being compressed. + * @param [in] m Mask to apply get the require number of bits. + * @return Compressed value. + */ +#define TO_COMP_WORD(v, i, j, s, m) \ + ((((word32)v[i + j] << s) + MLKEM_Q_HALF) / MLKEM_Q) & m + +/* Compress value to 4 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_4(p, i, j) \ + TO_COMP_WORD(p, i, j, 4, 0xf) + +/* Compress value to 5 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_5(p, i, j) \ + TO_COMP_WORD(p, i, j, 5, 0x1f) + +#else + +/* Multiplier that does div q. */ +#define MLKEM_V28 ((word32)(((1U << 28) + MLKEM_Q_HALF)) / MLKEM_Q) +/* Multiplier times half of q. */ +#define MLKEM_V28_HALF ((word32)(MLKEM_V28 * (MLKEM_Q_HALF + 1))) + +/* Multiplier that does div q. */ +#define MLKEM_V27 ((word32)(((1U << 27) + MLKEM_Q_HALF)) / MLKEM_Q) +/* Multiplier times half of q. */ +#define MLKEM_V27_HALF ((word32)(MLKEM_V27 * MLKEM_Q_HALF)) + +/* Compress value to 4 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_4(p, i, j) \ + ((((MLKEM_V28 << 4) * (p)[(i) + (j)]) + MLKEM_V28_HALF) >> 28) + +/* Compress value to 5 bits. + * + * Uses mul instead of div. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @return Compressed value. + */ +#define TO_COMP_WORD_5(p, i, j) \ + ((((MLKEM_V27 << 5) * (p)[(i) + (j)]) + MLKEM_V27_HALF) >> 27) + +#endif /* CONV_WITH_DIV */ + +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Compress a polynomial into byte array - on coefficients into 4 bits. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +static void mlkem_compress_4_c(byte* b, sword16* p) +{ + unsigned int i; +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + byte t[8]; +#endif + + /* Reduce each coefficients to mod q. */ + mlkem_csubq_c(p); + /* All values are now positive. */ + + /* Each 8 polynomial coefficients. */ + for (i = 0; i < MLKEM_N; i += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + /* Compress eight polynomial values to 4 bits each. */ + for (j = 0; j < 8; j++) { + t[j] = TO_COMP_WORD_4(p, i, j); + } + + b[0] = t[0] | (t[1] << 4); + b[1] = t[2] | (t[3] << 4); + b[2] = t[4] | (t[5] << 4); + b[3] = t[6] | (t[7] << 4); + #else + /* Compress eight polynomial values to 4 bits each. */ + byte t0 = TO_COMP_WORD_4(p, i, 0); + byte t1 = TO_COMP_WORD_4(p, i, 1); + byte t2 = TO_COMP_WORD_4(p, i, 2); + byte t3 = TO_COMP_WORD_4(p, i, 3); + byte t4 = TO_COMP_WORD_4(p, i, 4); + byte t5 = TO_COMP_WORD_4(p, i, 5); + byte t6 = TO_COMP_WORD_4(p, i, 6); + byte t7 = TO_COMP_WORD_4(p, i, 7); + + /* Pack eight 4-bit values into byte array. */ + b[0] = t0 | (t1 << 4); + b[1] = t2 | (t3 << 4); + b[2] = t4 | (t5 << 4); + b[3] = t6 | (t7 << 4); + #endif + + /* Move over set bytes. */ + b += 4; + } +} + +/* Compress a polynomial into byte array - on coefficients into 4 bits. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +void mlkem_compress_4(byte* b, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_compress_4_avx2(b, p); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_compress_4_c(b, p); + } +} +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Compress a polynomial into byte array - on coefficients into 5 bits. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +static void mlkem_compress_5_c(byte* b, sword16* p) +{ + unsigned int i; +#ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + byte t[8]; +#endif + + /* Reduce each coefficients to mod q. */ + mlkem_csubq_c(p); + /* All values are now positive. */ + + for (i = 0; i < MLKEM_N; i += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + /* Compress eight polynomial values to 5 bits each. */ + for (j = 0; j < 8; j++) { + t[j] = TO_COMP_WORD_5(p, i, j); + } + + /* Pack 5 bits into byte array. */ + b[0] = (t[0] >> 0) | (t[1] << 5); + b[1] = (t[1] >> 3) | (t[2] << 2) | (t[3] << 7); + b[2] = (t[3] >> 1) | (t[4] << 4); + b[3] = (t[4] >> 4) | (t[5] << 1) | (t[6] << 6); + b[4] = (t[6] >> 2) | (t[7] << 3); + #else + /* Compress eight polynomial values to 5 bits each. */ + byte t0 = TO_COMP_WORD_5(p, i, 0); + byte t1 = TO_COMP_WORD_5(p, i, 1); + byte t2 = TO_COMP_WORD_5(p, i, 2); + byte t3 = TO_COMP_WORD_5(p, i, 3); + byte t4 = TO_COMP_WORD_5(p, i, 4); + byte t5 = TO_COMP_WORD_5(p, i, 5); + byte t6 = TO_COMP_WORD_5(p, i, 6); + byte t7 = TO_COMP_WORD_5(p, i, 7); + + /* Pack eight 5-bit values into byte array. */ + b[0] = (t0 >> 0) | (t1 << 5); + b[1] = (t1 >> 3) | (t2 << 2) | (t3 << 7); + b[2] = (t3 >> 1) | (t4 << 4); + b[3] = (t4 >> 4) | (t5 << 1) | (t6 << 6); + b[4] = (t6 >> 2) | (t7 << 3); + #endif + + /* Move over set bytes. */ + b += 5; + } +} + +/* Compress a polynomial into byte array - on coefficients into 5 bits. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + */ +void mlkem_compress_5(byte* b, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_compress_5_avx2(b, p); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_compress_5_c(b, p); + } +} +#endif +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE || !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +/* Decompress a 4 bit value. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_4(p, i, j, t) \ + p[(i) + (j)] = ((word16)((t) * MLKEM_Q) + 8) >> 4 + +/* Decompress a 5 bit value. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [in] p Polynomial. + * @param [in] i Index into polynomial. + * @param [in] j Offset from indices. + * @param [in] t Value to decompress. + * @return Decompressed value. + */ +#define DECOMP_5(p, i, j, t) \ + p[(i) + (j)] = (((word32)((t) & 0x1f) * MLKEM_Q) + 16) >> 5 + +#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512) || \ + defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768) +/* Decompress the byte array of packed 4 bits into polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +static void mlkem_decompress_4_c(sword16* p, const byte* b) +{ + unsigned int i; + + /* 2 coefficients at a time. */ + for (i = 0; i < MLKEM_N; i += 2) { + /* 2 coefficients decompressed from one byte. */ + DECOMP_4(p, i, 0, b[0] & 0xf); + DECOMP_4(p, i, 1, b[0] >> 4); + b += 1; + } +} + +/* Decompress the byte array of packed 4 bits into polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +void mlkem_decompress_4(sword16* p, const byte* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_decompress_4_avx2(p, b); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_decompress_4_c(p, b); + } +} +#endif +#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024) +/* Decompress the byte array of packed 5 bits into polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +static void mlkem_decompress_5_c(sword16* p, const byte* b) +{ + unsigned int i; + + /* Each 8 polynomial coefficients. */ + for (i = 0; i < MLKEM_N; i += 8) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + byte t[8]; + + /* Extract out 8 values of 5 bits each. */ + t[0] = (b[0] >> 0); + t[1] = (b[0] >> 5) | (b[1] << 3); + t[2] = (b[1] >> 2); + t[3] = (b[1] >> 7) | (b[2] << 1); + t[4] = (b[2] >> 4) | (b[3] << 4); + t[5] = (b[3] >> 1); + t[6] = (b[3] >> 6) | (b[4] << 2); + t[7] = (b[4] >> 3); + b += 5; + + /* Decompress 8 values. */ + for (j = 0; j < 8; j++) { + DECOMP_5(p, i, j, t[j]); + } + #else + /* Extract out 8 values of 5 bits each. */ + byte t0 = (b[0] >> 0); + byte t1 = (b[0] >> 5) | (b[1] << 3); + byte t2 = (b[1] >> 2); + byte t3 = (b[1] >> 7) | (b[2] << 1); + byte t4 = (b[2] >> 4) | (b[3] << 4); + byte t5 = (b[3] >> 1); + byte t6 = (b[3] >> 6) | (b[4] << 2); + byte t7 = (b[4] >> 3); + b += 5; + + /* Decompress 8 values. */ + DECOMP_5(p, i, 0, t0); + DECOMP_5(p, i, 1, t1); + DECOMP_5(p, i, 2, t2); + DECOMP_5(p, i, 3, t3); + DECOMP_5(p, i, 4, t4); + DECOMP_5(p, i, 5, t5); + DECOMP_5(p, i, 6, t6); + DECOMP_5(p, i, 7, t7); + #endif + } +} + +/* Decompress the byte array of packed 5 bits into polynomial. + * + * FIPS 203, Section 4.2.1, Compression and decompression + * + * @param [out] p Polynomial. + * @param [in] b Array of bytes. + */ +void mlkem_decompress_5(sword16* p, const byte* b) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_decompress_5_avx2(p, b); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_decompress_5_c(p, b); + } +} +#endif +#endif /* !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +/******************************************************************************/ + +#if !(defined(__aarch64__) && defined(WOLFSSL_ARMASM)) +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Convert bit from byte to 0 or (MLKEM_Q + 1) / 2. + * + * Constant time implementation. + * XOR in mlkem_opt_blocker to ensure optimizer doesn't know what will be ANDed + * with MLKEM_Q_1_HALF and can't optimize to non-constant time code. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Polynomial to hold converted value. + * @param [in] msg Message to get bit from byte from. + * @param [in] i Index of byte from message. + * @param [in] j Index of bit in byte. + */ +#define FROM_MSG_BIT(p, msg, i, j) \ + ((p)[8 * (i) + (j)] = (((sword16)0 - (sword16)(((msg)[i] >> (j)) & 1)) ^ \ + mlkem_opt_blocker) & MLKEM_Q_1_HALF) + +/* Convert message to polynomial. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +static void mlkem_from_msg_c(sword16* p, const byte* msg) +{ + unsigned int i; + + /* For each byte of the message. */ + for (i = 0; i < MLKEM_N / 8; i++) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + /* For each bit of the message. */ + for (j = 0; j < 8; j++) { + FROM_MSG_BIT(p, msg, i, j); + } + #else + FROM_MSG_BIT(p, msg, i, 0); + FROM_MSG_BIT(p, msg, i, 1); + FROM_MSG_BIT(p, msg, i, 2); + FROM_MSG_BIT(p, msg, i, 3); + FROM_MSG_BIT(p, msg, i, 4); + FROM_MSG_BIT(p, msg, i, 5); + FROM_MSG_BIT(p, msg, i, 6); + FROM_MSG_BIT(p, msg, i, 7); + #endif + } +} + +/* Convert message to polynomial. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +void mlkem_from_msg(sword16* p, const byte* msg) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + mlkem_from_msg_avx2(p, msg); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_from_msg_c(p, msg); + } +} +#endif + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +#ifdef CONV_WITH_DIV + +/* Convert to value to bit. + * + * Uses div operator that may be slow. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] m Message. + * @param [in] p Polynomial. + * @param [in] i Index of byte in message. + * @param [in] j Index of bit in byte. + */ +#define TO_MSG_BIT(m, p, i, j) \ + m[i] |= (((((sword16)p[8 * i + j] << 1) + MLKEM_Q_HALF) / MLKEM_Q) & 1) << j + +#else + +/* Multiplier that does div q. */ +#define MLKEM_V31 (((1U << 31) + (MLKEM_Q / 2)) / MLKEM_Q) +/* 2 * multiplier that does div q. Only need bit 32 of result. */ +#define MLKEM_V31_2 ((word32)(MLKEM_V31 * 2)) +/* Multiplier times half of q. */ +#define MLKEM_V31_HALF ((word32)(MLKEM_V31 * MLKEM_Q_HALF)) + +/* Convert to value to bit. + * + * Uses mul instead of div. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] m Message. + * @param [in] p Polynomial. + * @param [in] i Index of byte in message. + * @param [in] j Index of bit in byte. + */ +#define TO_MSG_BIT(m, p, i, j) \ + (m)[i] |= ((word32)((MLKEM_V31_2 * (p)[8 * (i) + (j)]) + \ + MLKEM_V31_HALF) >> 31) << (j) + +#endif /* CONV_WITH_DIV */ + +/* Convert polynomial to message. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +static void mlkem_to_msg_c(byte* msg, sword16* p) +{ + unsigned int i; + + /* Reduce each coefficient to mod q. */ + mlkem_csubq_c(p); + /* All values are now in range. */ + + for (i = 0; i < MLKEM_N / 8; i++) { + #ifdef WOLFSSL_MLKEM_SMALL + unsigned int j; + msg[i] = 0; + for (j = 0; j < 8; j++) { + TO_MSG_BIT(msg, p, i, j); + } + #else + msg[i] = 0; + TO_MSG_BIT(msg, p, i, 0); + TO_MSG_BIT(msg, p, i, 1); + TO_MSG_BIT(msg, p, i, 2); + TO_MSG_BIT(msg, p, i, 3); + TO_MSG_BIT(msg, p, i, 4); + TO_MSG_BIT(msg, p, i, 5); + TO_MSG_BIT(msg, p, i, 6); + TO_MSG_BIT(msg, p, i, 7); + #endif + } +} + +/* Convert polynomial to message. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +void mlkem_to_msg(byte* msg, sword16* p) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + /* Convert the polynomial into a array of bytes (message). */ + mlkem_to_msg_avx2(msg, p); + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_to_msg_c(msg, p); + } +} +#endif /* !WOLFSSL_MLKEM_NO_DECAPSULATE */ +#else +#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \ + !defined(WOLFSSL_MLKEM_NO_DECAPSULATE) +/* Convert message to polynomial. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Polynomial. + * @param [in] msg Message as a byte array. + */ +void mlkem_from_msg(sword16* p, const byte* msg) +{ + mlkem_from_msg_neon(p, msg); +} +#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE || !WOLFSSL_MLKEM_NO_DECAPSULATE */ + +#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE +/* Convert polynomial to message. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] msg Message as a byte array. + * @param [in] p Polynomial. + */ +void mlkem_to_msg(byte* msg, sword16* p) +{ + mlkem_to_msg_neon(msg, p); +} +#endif /* WOLFSSL_MLKEM_NO_DECAPSULATE */ +#endif /* !(__aarch64__ && WOLFSSL_ARMASM) */ + +/******************************************************************************/ + +/* Convert bytes to polynomial. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in decoding private and public keys. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_from_bytes_c(sword16* p, const byte* b, int k) +{ + int i; + int j; + + for (j = 0; j < k; j++) { + for (i = 0; i < MLKEM_N / 2; i++) { + p[2 * i + 0] = ((b[3 * i + 0] >> 0) | + ((word16)b[3 * i + 1] << 8)) & 0xfff; + p[2 * i + 1] = ((b[3 * i + 1] >> 4) | + ((word16)b[3 * i + 2] << 4)) & 0xfff; + } + p += MLKEM_N; + b += WC_ML_KEM_POLY_SIZE; + } +} + +/* Convert bytes to polynomial. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in decoding private and public keys. + * + * FIPS 203, Algorithm 6: ByteDecode_d(B) + * + * @param [out] p Vector of polynomials. + * @param [in] b Array of bytes. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_from_bytes(sword16* p, const byte* b, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + int i; + + for (i = 0; i < k; i++) { + mlkem_from_bytes_avx2(p, b); + p += MLKEM_N; + b += WC_ML_KEM_POLY_SIZE; + } + + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_from_bytes_c(p, b, k); + } +} + +/* Convert polynomial to bytes. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in encoding private and public keys. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + * @param [in] k Number of polynomials in vector. + */ +static void mlkem_to_bytes_c(byte* b, sword16* p, int k) +{ + int i; + int j; + + /* Reduce each coefficient to mod q. */ + mlkem_csubq_c(p); + /* All values are now positive. */ + + for (j = 0; j < k; j++) { + for (i = 0; i < MLKEM_N / 2; i++) { + word16 t0 = p[2 * i]; + word16 t1 = p[2 * i + 1]; + b[3 * i + 0] = (t0 >> 0); + b[3 * i + 1] = (t0 >> 8) | t1 << 4; + b[3 * i + 2] = (t1 >> 4); + } + p += MLKEM_N; + b += WC_ML_KEM_POLY_SIZE; + } +} + +/* Convert polynomial to bytes. + * + * Consecutive 12 bits hold each coefficient of polynomial. + * Used in encoding private and public keys. + * + * FIPS 203, Algorithm 6: ByteEncode_d(F) + * + * @param [out] b Array of bytes. + * @param [in] p Polynomial. + * @param [in] k Number of polynomials in vector. + */ +void mlkem_to_bytes(byte* b, sword16* p, int k) +{ +#ifdef USE_INTEL_SPEEDUP + if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) { + int i; + + for (i = 0; i < k; i++) { + mlkem_to_bytes_avx2(b, p); + p += MLKEM_N; + b += WC_ML_KEM_POLY_SIZE; + } + + RESTORE_VECTOR_REGISTERS(); + } + else +#endif + { + mlkem_to_bytes_c(b, p, k); + } +} + +#endif /* WOLFSSL_WC_MLKEM */ diff --git a/src/wolfcrypt/src/wc_pkcs11.c b/src/wolfcrypt/src/wc_pkcs11.c index b3df75c..efacd74 100644 --- a/src/wolfcrypt/src/wc_pkcs11.c +++ b/src/wolfcrypt/src/wc_pkcs11.c @@ -1,6 +1,6 @@ /* wc_pkcs11.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #ifdef HAVE_PKCS11 @@ -32,9 +28,7 @@ #endif #include -#include #include -#include #ifndef NO_RSA #include #endif diff --git a/src/wolfcrypt/src/wc_port.c b/src/wolfcrypt/src/wc_port.c index 2ee85e3..a757852 100644 --- a/src/wolfcrypt/src/wc_port.c +++ b/src/wolfcrypt/src/wc_port.c @@ -1,6 +1,6 @@ /* port.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,20 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif +#include #ifdef __APPLE__ #include #endif -#include -#include -#include -#include -#include #ifdef HAVE_ECC #include #endif @@ -658,11 +650,13 @@ int wc_ReadDirFirst(ReadDirCtx* ctx, const char* path, char** name) if (name) *name = NULL; + if (ctx != NULL) + XMEMSET(ctx, 0, sizeof(ReadDirCtx)); + if (ctx == NULL || path == NULL) { return BAD_FUNC_ARG; } - XMEMSET(ctx, 0, sizeof(ReadDirCtx)); pathLen = (int)XSTRLEN(path); #ifdef USE_WINDOWS_API @@ -1041,6 +1035,15 @@ int z_fs_close(XFILE file) return ret; } +/* Rewind the file pointer to the beginning of the file */ +/* This is not a 'rewind' is not supported in Zephyr so */ +/* use fs_seek to move the file pointer to the beginning of the file */ +/* calling it z_fs_rewind to avoid future conflicts if rewind is added */ +int z_fs_rewind(XFILE file) +{ + return fs_seek(file, 0, FS_SEEK_SET); +} + #endif /* !NO_FILESYSTEM && !WOLFSSL_ZEPHYR */ #if !defined(WOLFSSL_USER_MUTEX) @@ -1657,6 +1660,99 @@ int wolfSSL_HwPkMutexUnLock(void) return 0; } +#elif defined(__WATCOMC__) + + int wc_InitMutex(wolfSSL_Mutex* m) + { + #ifdef __OS2__ + DosCreateMutexSem( NULL, m, 0, FALSE ); + #elif defined(__NT__) + InitializeCriticalSection(m); + #elif defined(__LINUX__) + if (pthread_mutex_init(m, NULL) ) + return BAD_MUTEX_E; + #endif + return 0; + } + + int wc_FreeMutex(wolfSSL_Mutex* m) + { + #ifdef __OS2__ + DosCloseMutexSem(*m); + #elif defined(__NT__) + DeleteCriticalSection(m); + #elif defined(__LINUX__) + if (pthread_mutex_destroy(m) ) + return BAD_MUTEX_E; + #endif + return 0; + } + + int wc_LockMutex(wolfSSL_Mutex* m) + { + #ifdef __OS2__ + DosRequestMutexSem(*m, SEM_INDEFINITE_WAIT); + #elif defined(__NT__) + EnterCriticalSection(m); + #elif defined(__LINUX__) + if (pthread_mutex_lock(m) ) + return BAD_MUTEX_E; + #endif + return 0; + } + + int wc_UnLockMutex(wolfSSL_Mutex* m) + { + #ifdef __OS2__ + DosReleaseMutexSem(*m); + #elif defined(__NT__) + LeaveCriticalSection(m); + #elif defined(__LINUX__) + if (pthread_mutex_unlock(m) ) + return BAD_MUTEX_E; + #endif + return 0; + } + + #if defined(WOLFSSL_USE_RWLOCK) && defined(__LINUX__) + + int wc_InitRwLock(wolfSSL_RwLock* m) + { + if (pthread_rwlock_init(m, NULL) ) + return BAD_MUTEX_E; + return 0; + } + + int wc_FreeRwLock(wolfSSL_RwLock* m) + { + if (pthread_rwlock_destroy(m) ) + return BAD_MUTEX_E; + return 0; + } + + int wc_LockRwLock_Wr(wolfSSL_RwLock* m) + { + if (pthread_rwlock_wrlock(m) ) + return BAD_MUTEX_E; + return 0; + } + + int wc_LockRwLock_Rd(wolfSSL_RwLock* m) + { + if (pthread_rwlock_rdlock(m) ) + return BAD_MUTEX_E; + return 0; + } + + int wc_UnLockRwLock(wolfSSL_RwLock* m) + { + if (pthread_rwlock_unlock(m) == 0) + return BAD_MUTEX_E; + return 0; + } + + #endif + #elif defined(FREERTOS) || defined(FREERTOS_TCP) || \ defined(FREESCALE_FREE_RTOS) @@ -2422,6 +2518,10 @@ int wolfSSL_HwPkMutexUnLock(void) int wc_InitMutex(wolfSSL_Mutex* m) { + #if (defined(HAVE_FIPS) && FIPS_VERSION_EQ(5,2)) + if (wolfCrypt_GetMode_fips() == FIPS_MODE_INIT) + return 0; + #endif if (_mutex_init(m, NULL) == MQX_EOK) return 0; else @@ -2438,6 +2538,13 @@ int wolfSSL_HwPkMutexUnLock(void) int wc_LockMutex(wolfSSL_Mutex* m) { + #if (defined(HAVE_FIPS) && FIPS_VERSION_EQ(5,2)) + if (m->VALID != MUTEX_VALID) { + if (_mutex_init(m, NULL) != MQX_EOK) + return BAD_MUTEX_E; + } + #endif + if (_mutex_lock(m) == MQX_EOK) return 0; else @@ -2446,6 +2553,13 @@ int wolfSSL_HwPkMutexUnLock(void) int wc_UnLockMutex(wolfSSL_Mutex* m) { + #if (defined(HAVE_FIPS) && FIPS_VERSION_EQ(5,2)) + if (m->VALID != MUTEX_VALID) { + if (_mutex_init(m, NULL) != MQX_EOK) + return BAD_MUTEX_E; + } + #endif + if (_mutex_unlock(m) == MQX_EOK) return 0; else @@ -2710,7 +2824,9 @@ int wolfSSL_HwPkMutexUnLock(void) #elif defined(WOLFSSL_CMSIS_RTOS) - #define CMSIS_NMUTEX 10 + #ifndef CMSIS_NMUTEX + #define CMSIS_NMUTEX 10 + #endif osMutexDef(wolfSSL_mt0); osMutexDef(wolfSSL_mt1); osMutexDef(wolfSSL_mt2); osMutexDef(wolfSSL_mt3); osMutexDef(wolfSSL_mt4); osMutexDef(wolfSSL_mt5); osMutexDef(wolfSSL_mt6); osMutexDef(wolfSSL_mt7); osMutexDef(wolfSSL_mt8); @@ -2726,6 +2842,11 @@ int wolfSSL_HwPkMutexUnLock(void) int wc_InitMutex(wolfSSL_Mutex* m) { int i; + + if(!osKernelRunning()) { + return 0; + } + for (i=0; imutex, 0, FALSE ); + DosCreateEventSem( NULL, &cond->cond, DCE_POSTONE, FALSE ); + #elif defined(__NT__) + cond->cond = CreateEventA(NULL, FALSE, FALSE, NULL); + if (cond->cond == NULL) + return MEMORY_E; + + if (wc_InitMutex(&cond->mutex) != 0) { + if (CloseHandle(cond->cond) == 0) + return MEMORY_E; + return MEMORY_E; + } + #elif defined(__LINUX__) + if (pthread_mutex_init(&cond->mutex, NULL) != 0) + return MEMORY_E; + + if (pthread_cond_init(&cond->cond, NULL) != 0) { + /* Keep compilers happy that we are using the return code */ + if (pthread_mutex_destroy(&cond->mutex) != 0) + return MEMORY_E; + return MEMORY_E; + } + #endif + return 0; + } + + int wolfSSL_CondFree(COND_TYPE* cond) + { + if (cond == NULL) + return BAD_FUNC_ARG; + #if defined(__OS2__) + DosCloseMutexSem(cond->mutex); + DosCloseEventSem(cond->cond); + #elif defined(__NT__) + if (CloseHandle(cond->cond) == 0) + return MEMORY_E; + #elif defined(__LINUX__) + if (pthread_mutex_destroy(&cond->mutex) != 0) + return MEMORY_E; + + if (pthread_cond_destroy(&cond->cond) != 0) + return MEMORY_E; + #endif + return 0; + } + + int wolfSSL_CondStart(COND_TYPE* cond) + { + if (cond == NULL) + return BAD_FUNC_ARG; + #if defined(__OS2__) + #elif defined(__NT__) + if (wc_LockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + #elif defined(__LINUX__) + if (pthread_mutex_lock(&cond->mutex) != 0) + return BAD_MUTEX_E; + #endif + return 0; + } + + int wolfSSL_CondSignal(COND_TYPE* cond) + { + if (cond == NULL) + return BAD_FUNC_ARG; + #if defined(__OS2__) + #elif defined(__NT__) + if (wc_UnLockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + + if (SetEvent(cond->cond) == 0) + return MEMORY_E; + + if (wc_LockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + #elif defined(__LINUX__) + if (pthread_cond_signal(&cond->cond) != 0) + return MEMORY_E; + #endif + return 0; + } + + int wolfSSL_CondWait(COND_TYPE* cond) + { + if (cond == NULL) + return BAD_FUNC_ARG; + #if defined(__OS2__) + #elif defined(__NT__) + if (wc_UnLockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + + if (WaitForSingleObject(cond->cond, INFINITE) == WAIT_FAILED) + return MEMORY_E; + + if (wc_LockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + #elif defined(__LINUX__) + if (pthread_cond_wait(&cond->cond, &cond->mutex) != 0) + return MEMORY_E; + #endif + return 0; + } + + int wolfSSL_CondEnd(COND_TYPE* cond) + { + if (cond == NULL) + return BAD_FUNC_ARG; + #if defined(__OS2__) + #elif defined(__NT__) + if (wc_UnLockMutex(&cond->mutex) != 0) + return BAD_MUTEX_E; + #elif defined(__LINUX__) + if (pthread_mutex_unlock(&cond->mutex) != 0) + return BAD_MUTEX_E; + #endif + return 0; + } + #endif /* WOLFSSL_COND */ + + +#elif defined(USE_WINDOWS_API) && !defined(WOLFSSL_PTHREADS) && \ !defined(_WIN32_WCE) int wolfSSL_NewThread(THREAD_TYPE* thread, THREAD_CB cb, void* arg) diff --git a/src/wolfcrypt/src/wc_xmss.c b/src/wolfcrypt/src/wc_xmss.c index 6546597..51b308b 100644 --- a/src/wolfcrypt/src/wc_xmss.c +++ b/src/wolfcrypt/src/wc_xmss.c @@ -1,6 +1,6 @@ /* wc_xmss.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,13 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #ifdef WOLFSSL_HAVE_XMSS #include diff --git a/src/wolfcrypt/src/wc_xmss_impl.c b/src/wolfcrypt/src/wc_xmss_impl.c index 80ca967..15b2184 100644 --- a/src/wolfcrypt/src/wc_xmss_impl.c +++ b/src/wolfcrypt/src/wc_xmss_impl.c @@ -1,6 +1,6 @@ /* wc_xmss_impl.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,13 +29,7 @@ * (https://ece.engr.uvic.ca/~raltawy/SAC2021/9.pdf) */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include -#include -#include +#include #include #include @@ -2653,6 +2647,9 @@ static int wc_xmss_bds_state_alloc(const XmssParams* params, BdsState** bds) if (*bds == NULL) { ret = MEMORY_E; } + else { + XMEMSET(*bds, 0, sizeof(BdsState) * cnt); + } } return ret; @@ -2675,7 +2672,7 @@ static void wc_xmss_bds_state_free(BdsState* bds) * @param [out] bds BDS states. * @param [out] wots_sigs WOTS signatures when XMSS^MT. */ -static void wc_xmss_bds_state_load(const XmssState* state, byte* sk, +static int wc_xmss_bds_state_load(const XmssState* state, byte* sk, BdsState* bds, byte** wots_sigs) { const XmssParams* params = state->params; @@ -2689,6 +2686,9 @@ static void wc_xmss_bds_state_load(const XmssState* state, byte* sk, /* Skip past standard SK = idx || wots_sk || SK_PRF || root || SEED; */ sk += params->idx_len + 4 * n; + if (2 * (int)params->d - 1 <= 0) + return WC_FAILURE; + for (i = 0; i < 2 * (int)params->d - 1; i++) { /* Set pointers into SK. */ bds[i].stack = sk; @@ -2715,6 +2715,8 @@ static void wc_xmss_bds_state_load(const XmssState* state, byte* sk, if (wots_sigs != NULL) { *wots_sigs = sk; } + + return 0; } /* Store the BDS state into the secret/private key. @@ -2723,7 +2725,7 @@ static void wc_xmss_bds_state_load(const XmssState* state, byte* sk, * @param [in, out] sk Secret/private key. * @param [in] bds BDS states. */ -static void wc_xmss_bds_state_store(const XmssState* state, byte* sk, +static int wc_xmss_bds_state_store(const XmssState* state, byte* sk, BdsState* bds) { int i; @@ -2743,15 +2745,20 @@ static void wc_xmss_bds_state_store(const XmssState* state, byte* sk, /* Ignore standard SK = idx || wots_sk || SK_PRF || root || SEED; */ sk += params->idx_len + 4 * n; + if (2 * (int)params->d - 1 <= 0) + return WC_FAILURE; + for (i = 0; i < 2 * (int)params->d - 1; i++) { /* Skip pointers into sk. */ sk += skip; /* Save values - big-endian encoded. */ - c32to24(bds[i].next, sk); + c32to24(bds[i].next, sk); /* NOLINT(clang-analyzer-core.CallAndMessage) */ sk += 3; sk[0] = bds[i].offset; sk += 1; } + + return 0; } /******************************************** @@ -2821,6 +2828,10 @@ static void wc_xmss_bds_next_idx(XmssState* state, BdsState* bds, /* HDSS, Section 4.5, 1: AUTH[h] = v[h][1], h = 0,...,H-1. * Cache left node if on authentication path. */ if ((i >> h) == 1) { + if (bds->authPath == NULL) { + state->ret = WC_FAILURE; + return; + } XMEMCPY(bds->authPath + h * n, node, n); } /* This is a right node. */ @@ -2900,8 +2911,10 @@ static void wc_xmss_bds_treehash_initial(XmssState* state, BdsState* bds, bds->offset = 0; bds->next = 0; /* Reset the hash tree status. */ - for (i = 0; i < hsk; i++) { - wc_xmss_bds_state_treehash_init(bds, i); + if (bds->treeHash != NULL) { + for (i = 0; i < hsk; i++) { + wc_xmss_bds_state_treehash_init(bds, i); + } } /* Copy hash address into local. */ @@ -3036,6 +3049,11 @@ static word8 wc_xmss_bds_treehash_updates(XmssState* state, BdsState* bds, const word8 hs = params->sub_h; const word8 hsk = params->sub_h - params->bds_k; + if (bds->treeHash == NULL) { + state->ret = WC_FAILURE; + return 0; + } + while (updates > 0) { word8 minH = hs; word8 h = hsk; @@ -3106,6 +3124,10 @@ static void wc_xmss_bds_update(XmssState* state, BdsState* bds, HashAddress addrCopy; XMSS_ADDR_OTS_SET_SUBTREE(addrCopy, addr); + if (bds->height == NULL) { + state->ret = WC_FAILURE; + return; + } wc_xmss_bds_next_idx(state, bds, sk_seed, pk_seed, addrCopy, bds->next, bds->height, &bds->offset, &sp); bds->offset++; @@ -3162,6 +3184,11 @@ static void wc_xmss_bds_auth_path(XmssState* state, BdsState* bds, byte* node = state->encMsg; word8 parent; + if ((bds->keep == NULL) || (bds->authPath == NULL)) { + state->ret = WC_FAILURE; + return; + } + /* Step 1. Find the height of first left node in authentication path. */ tau = wc_xmss_lowest_zero_bit_index(leafIdx, hs, &parent); if (tau == 0) { @@ -3297,6 +3324,10 @@ int wc_xmss_keygen(XmssState* state, const unsigned char* seed, if (ret == 0) #endif { + /* Setup pointers into sk - assumes sk is initialized to zeros. */ + ret = wc_xmss_bds_state_load(state, sk, bds, NULL); + } + if (ret == 0) { /* Offsets into seed. */ const byte* seed_priv = seed; const byte* seed_pub = seed + 2 * n; @@ -3306,9 +3337,6 @@ int wc_xmss_keygen(XmssState* state, const unsigned char* seed, /* Offsets into public key. */ byte* pk_seed = pk + n; - /* Setup pointers into sk - assumes sk is initialized to zeros. */ - wc_xmss_bds_state_load(state, sk, bds, NULL); - /* Set first index to 0 in private key. idx_len always 4. */ *sk_idx = 0; /* Set private key seed and private key for PRF in to private key. */ @@ -3333,7 +3361,7 @@ int wc_xmss_keygen(XmssState* state, const unsigned char* seed, XMEMCPY(sk_root, pk_root, 2 * n); /* Store BDS state back into secret/private key. */ - wc_xmss_bds_state_store(state, sk, bds); + ret = wc_xmss_bds_state_store(state, sk, bds); } #ifdef WOLFSSL_SMALL_STACK @@ -3412,8 +3440,9 @@ int wc_xmss_sign(XmssState* state, const unsigned char* m, word32 mlen, #endif { /* Load the BDS state from secret/private key. */ - wc_xmss_bds_state_load(state, sk, bds, NULL); - + ret = wc_xmss_bds_state_load(state, sk, bds, NULL); + } + if (ret == 0) { /* Copy the index into the signature data: Sig = idx_sig || ... */ *((word32*)sig) = *((word32*)sk); /* Read index from the secret key. */ @@ -3490,7 +3519,7 @@ int wc_xmss_sign(XmssState* state, const unsigned char* m, word32 mlen, } if (ret == 0) { /* Store BDS state back into secret/private key. */ - wc_xmss_bds_state_store(state, sk, bds); + ret = wc_xmss_bds_state_store(state, sk, bds); } #ifdef WOLFSSL_SMALL_STACK @@ -3580,14 +3609,15 @@ int wc_xmssmt_keygen(XmssState* state, const unsigned char* seed, /* Allocate memory for BDS states and tree hash instances. */ ret = wc_xmss_bds_state_alloc(params, &bds); + if (ret == 0) { + /* Load the BDS state from secret/private key. */ + ret = wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); + } if (ret == 0) { /* Offsets into seed. */ const byte* seed_priv = seed; const byte* seed_pub = seed + 2 * params->n; - /* Load the BDS state from secret/private key. */ - wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); - /* Set first index to 0 in private key. */ XMEMSET(sk, 0, params->idx_len); /* Set private key seed and private key for PRF in to private key. */ @@ -3630,7 +3660,7 @@ int wc_xmssmt_keygen(XmssState* state, const unsigned char* seed, XMEMCPY(sk_root, pk_root, 2 * n); /* Store BDS state back into secret/private key. */ - wc_xmss_bds_state_store(state, sk, bds); + ret = wc_xmss_bds_state_store(state, sk, bds); } /* Dispose of allocated data of BDS states. */ @@ -3825,10 +3855,16 @@ static int wc_xmssmt_sign_msg(XmssState* state, BdsState* bds, XmssIdx idx, } if (ret == 0) { word8 i; + byte *authPath; sig += params->wots_sig_len; /* Add authentication path. */ - XMEMCPY(sig, bds[BDS_IDX(idx, 0, hs, params->d)].authPath, hs * n); + authPath = bds[BDS_IDX(idx, 0, hs, params->d)].authPath; + if (authPath == NULL) { + state->ret = WC_FAILURE; + return state->ret; + } + XMEMCPY(sig, authPath, hs * n); sig += hs * n; /* Remaining iterations from storage. */ @@ -3838,7 +3874,12 @@ static int wc_xmssmt_sign_msg(XmssState* state, BdsState* bds, XmssIdx idx, params->wots_sig_len); sig += params->wots_sig_len; /* Add authentication path (auth) and calc new root. */ - XMEMCPY(sig, bds[BDS_IDX(idx, i, hs, params->d)].authPath, hs * n); + authPath = bds[BDS_IDX(idx, i, hs, params->d)].authPath; + if (authPath == NULL) { + state->ret = WC_FAILURE; + return state->ret; + } + XMEMCPY(sig, authPath, hs * n); sig += hs * n; } ret = state->ret; @@ -4000,8 +4041,9 @@ int wc_xmssmt_sign(XmssState* state, const unsigned char* m, word32 mlen, ret = wc_xmss_bds_state_alloc(params, &bds); if (ret == 0) { /* Load the BDS state from secret/private key. */ - wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); - + ret = wc_xmss_bds_state_load(state, sk, bds, &wots_sigs); + } + if (ret == 0) { /* Copy the index into the signature data: Sig_MT = idx_sig. */ XMEMCPY(sig_mt, sk, idx_len); @@ -4032,7 +4074,7 @@ int wc_xmssmt_sign(XmssState* state, const unsigned char* m, word32 mlen, if (ret == 0) { /* Store BDS state back into secret/private key. */ - wc_xmss_bds_state_store(state, sk, bds); + ret = wc_xmss_bds_state_store(state, sk, bds); } /* Dispose of allocated data of BDS states. */ diff --git a/src/wolfcrypt/src/wolfevent.c b/src/wolfcrypt/src/wolfevent.c index bf155c1..34d5740 100644 --- a/src/wolfcrypt/src/wolfevent.c +++ b/src/wolfcrypt/src/wolfevent.c @@ -1,6 +1,6 @@ /* wolfevent.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,18 +19,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif - -#include - +#include #ifdef HAVE_WOLF_EVENT #include #include -#include #include diff --git a/src/wolfcrypt/src/wolfmath.c b/src/wolfcrypt/src/wolfmath.c index 9a6e312..9f14d01 100644 --- a/src/wolfcrypt/src/wolfmath.c +++ b/src/wolfcrypt/src/wolfmath.c @@ -1,6 +1,6 @@ /* wolfmath.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -26,15 +26,9 @@ * NO_BIG_INT: Disable support for all multi-precision math libraries */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -/* in case user set USE_FAST_MATH there */ -#include #include -#include -#include #ifdef WOLFSSL_ASYNC_CRYPT #include diff --git a/src/wolfssl-arduino.cpp b/src/wolfssl-arduino.cpp new file mode 100644 index 0000000..3d3c787 --- /dev/null +++ b/src/wolfssl-arduino.cpp @@ -0,0 +1,33 @@ +/* wolfssl-arduino.cpp + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include "wolfssl.h" + +/* Function to allow wolfcrypt to use Arduino Serial.print for debug messages. + * See wolfssl/wolfcrypt/logging.c */ + +int wolfSSL_Arduino_Serial_Print(const char* const s) +{ + /* Reminder: Serial.print is only available in C++ */ + Serial.println(F(s)); + return 0; +}; diff --git a/src/wolfssl.h b/src/wolfssl.h index c7e39d4..8b29806 100644 --- a/src/wolfssl.h +++ b/src/wolfssl.h @@ -1,6 +1,6 @@ /* wolfssl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -22,6 +22,7 @@ /* Edit with caution. This is an Arduino-library specific header for wolfSSL */ #ifndef WOLFSSL_USER_SETTINGS + /* Should already be defined in settings.h for #if defined(ARDUINO) */ #define WOLFSSL_USER_SETTINGS #endif @@ -39,9 +40,10 @@ #include #include -int wolfSSL_Arduino_Serial_Print(const char *const s) -{ - /* See wolfssl/wolfcrypt/logging.c */ - Serial.println(F(s)); - return 0; -}; +#ifndef WOLFSSL_ARDUINO_H +#define WOLFSSL_ARDUINO_H + +/* Declare a helper function to be used in wolfssl/wolfcrypt/logging.c */ +int wolfSSL_Arduino_Serial_Print(const char* const s); + +#endif /* WOLFSSL_ARDUINO_H */ diff --git a/src/wolfssl/bio.c b/src/wolfssl/bio.c index b265456..0b52a6c 100644 --- a/src/wolfssl/bio.c +++ b/src/wolfssl/bio.c @@ -1,6 +1,6 @@ /* bio.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,11 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -#ifdef HAVE_CONFIG_H - #include -#endif +#include -#include #if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE) /* turn on GNU extensions for XVASPRINTF with wolfSSL_BIO_printf */ #define _GNU_SOURCE 1 @@ -142,7 +139,7 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) return WOLFSSL_BIO_ERROR; } - XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, sz); + XMEMCPY(buf, bio->mem_buf->data + bio->rdIdx, (size_t)sz); bio->rdIdx += sz; if (bio->rdIdx >= bio->wrSz) { @@ -167,14 +164,14 @@ static int wolfSSL_BIO_MEMORY_read(WOLFSSL_BIO* bio, void* buf, int len) /* Resize the memory so we are not taking up more than necessary. * memmove reverts internally to memcpy if areas don't overlap */ XMEMMOVE(bio->mem_buf->data, bio->mem_buf->data + bio->rdIdx, - bio->wrSz - bio->rdIdx); + (long unsigned int)bio->wrSz - (size_t)bio->rdIdx); bio->wrSz -= bio->rdIdx; bio->rdIdx = 0; /* Resize down to WOLFSSL_BIO_RESIZE_THRESHOLD for fewer * allocations. */ if (wolfSSL_BUF_MEM_resize(bio->mem_buf, - bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? bio->wrSz : - WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { + bio->wrSz > WOLFSSL_BIO_RESIZE_THRESHOLD ? + (size_t)bio->wrSz : WOLFSSL_BIO_RESIZE_THRESHOLD) == 0) { WOLFSSL_MSG("wolfSSL_BUF_MEM_resize error"); return WOLFSSL_BIO_ERROR; } @@ -389,6 +386,10 @@ int wolfSSL_BIO_read(WOLFSSL_BIO* bio, void* buf, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = 0; + break; + } /* switch */ } @@ -564,7 +565,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, WOLFSSL_MSG("Error in wolfSSL_BIO_nwrite"); return sz1; } - XMEMCPY(buf, data, sz1); + XMEMCPY(buf, data, (size_t)sz1); data = (char*)data + sz1; len -= sz1; @@ -572,7 +573,7 @@ static int wolfSSL_BIO_BIO_write(WOLFSSL_BIO* bio, const void* data, /* try again to see if maybe we wrapped around the ring buffer */ sz2 = wolfSSL_BIO_nwrite(bio, &buf, len); if (sz2 > 0) { - XMEMCPY(buf, data, sz2); + XMEMCPY(buf, data, (size_t)sz2); sz1 += sz2; if (len > sz2) bio->flags |= WOLFSSL_BIO_FLAG_WRITE|WOLFSSL_BIO_FLAG_RETRY; @@ -610,8 +611,8 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, if (len == 0) return WOLFSSL_SUCCESS; /* Return early to make logic simpler */ - if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, bio->wrSz + len, 0) - == 0) { + if (wolfSSL_BUF_MEM_grow_ex(bio->mem_buf, ((size_t)bio->wrSz) + + ((size_t)len), 0) == 0) { WOLFSSL_MSG("Error growing memory area"); return WOLFSSL_FAILURE; } @@ -621,7 +622,7 @@ static int wolfSSL_BIO_MEMORY_write(WOLFSSL_BIO* bio, const void* data, return WOLFSSL_FAILURE; } - XMEMCPY(bio->mem_buf->data + bio->wrSz, data, len); + XMEMCPY(bio->mem_buf->data + bio->wrSz, data, (size_t)len); bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; bio->num.length = bio->mem_buf->max; bio->wrSz += len; @@ -813,6 +814,10 @@ int wolfSSL_BIO_write(WOLFSSL_BIO* bio, const void* data, int len) #endif break; + case WOLFSSL_BIO_NULL: + ret = len; + break; + } /* switch */ } @@ -1138,7 +1143,7 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) ret = wolfSSL_BIO_nread(bio, &c, cSz); if (ret > 0 && ret < sz) { - XMEMCPY(buf, c, ret); + XMEMCPY(buf, c, (size_t)ret); } break; } @@ -1161,6 +1166,10 @@ int wolfSSL_BIO_gets(WOLFSSL_BIO* bio, char* buf, int sz) break; #endif /* WOLFCRYPT_ONLY */ + case WOLFSSL_BIO_NULL: + ret = 0; + break; + default: WOLFSSL_MSG("BIO type not supported yet with wolfSSL_BIO_gets"); } @@ -1256,13 +1265,13 @@ size_t wolfSSL_BIO_wpending(const WOLFSSL_BIO *bio) return 0; if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz; + return (size_t)bio->wrSz; } /* type BIO_BIO then check paired buffer */ if (bio->type == WOLFSSL_BIO_BIO && bio->pair != NULL) { WOLFSSL_BIO* pair = bio->pair; - return pair->wrIdx; + return (size_t)pair->wrIdx; } return 0; @@ -1308,12 +1317,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) #ifndef WOLFCRYPT_ONLY if (bio->type == WOLFSSL_BIO_SSL && bio->ptr.ssl != NULL) { - return (long)wolfSSL_pending(bio->ptr.ssl); + return (size_t)wolfSSL_pending(bio->ptr.ssl); } #endif if (bio->type == WOLFSSL_BIO_MEMORY) { - return bio->wrSz - bio->rdIdx; + return (size_t)(bio->wrSz - bio->rdIdx); } /* type BIO_BIO then check paired buffer */ @@ -1322,11 +1331,12 @@ size_t wolfSSL_BIO_ctrl_pending(WOLFSSL_BIO *bio) if (pair->wrIdx > 0 && pair->wrIdx <= pair->rdIdx) { /* in wrap around state where beginning of buffer is being * overwritten */ - return pair->wrSz - pair->rdIdx + pair->wrIdx; + return ((size_t)pair->wrSz) - ((size_t)pair->rdIdx) + + ((size_t)pair->wrIdx); } else { /* simple case where has not wrapped around */ - return pair->wrIdx - pair->rdIdx; + return (size_t)(pair->wrIdx - pair->rdIdx); } } return 0; @@ -1423,7 +1433,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) XFREE(bio->ptr.mem_buf_data, bio->heap, DYNAMIC_TYPE_OPENSSL); } - bio->ptr.mem_buf_data = (byte*)XMALLOC(size, bio->heap, + bio->ptr.mem_buf_data = (byte*)XMALLOC((size_t)size, bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ptr.mem_buf_data == NULL) { WOLFSSL_MSG("Memory allocation error"); @@ -1439,7 +1449,7 @@ int wolfSSL_BIO_set_write_buf_size(WOLFSSL_BIO *bio, long size) return WOLFSSL_FAILURE; } bio->wrSz = (int)size; - bio->num.length = size; + bio->num.length = (size_t)size; bio->wrIdx = 0; bio->rdIdx = 0; if (bio->mem_buf != NULL) { @@ -1908,7 +1918,7 @@ long wolfSSL_BIO_set_mem_eof_return(WOLFSSL_BIO *bio, int v) int wolfSSL_BIO_get_len(WOLFSSL_BIO *bio) { - int len; + int len = 0; #ifndef NO_FILESYSTEM long memSz = 0; XFILE file; @@ -2309,6 +2319,15 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) return &meth; } + WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_null(void) + { + static WOLFSSL_BIO_METHOD meth = + WOLFSSL_BIO_METHOD_INIT(WOLFSSL_BIO_NULL); + + WOLFSSL_ENTER("wolfSSL_BIO_s_null"); + + return &meth; + } WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_socket(void) { @@ -2353,7 +2372,6 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_dgram"); if (bio) { - bio->type = WOLFSSL_BIO_DGRAM; bio->shutdown = (byte)closeF; bio->num.fd = (SOCKET_T)fd; } @@ -2381,10 +2399,11 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) else port = str + XSTRLEN(str); /* point to null terminator */ - bio->ip = (char*)XMALLOC((port - str) + 1, /* +1 for null char */ + bio->ip = (char*)XMALLOC( + (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); if (bio->ip != NULL) { - XMEMCPY(bio->ip, str, port - str); + XMEMCPY(bio->ip, str, (size_t)(port - str)); bio->ip[port - str] = '\0'; bio->type = WOLFSSL_BIO_SOCKET; } @@ -2770,9 +2789,23 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) } else { size_t currLen = XSTRLEN(b->ip); + #ifdef WOLFSSL_NO_REALLOC + char* tmp = NULL; + #endif + if (currLen != newLen) { + #ifdef WOLFSSL_NO_REALLOC + tmp = b->ip; + b->ip = (char*)XMALLOC(newLen+1, b->heap, DYNAMIC_TYPE_OPENSSL); + if (b->ip != NULL && tmp != NULL) { + XMEMCPY(b->ip, tmp, newLen); + XFREE(tmp, b->heap, DYNAMIC_TYPE_OPENSSL); + tmp = NULL; + } + #else b->ip = (char*)XREALLOC(b->ip, newLen + 1, b->heap, DYNAMIC_TYPE_OPENSSL); + #endif if (b->ip == NULL) { WOLFSSL_MSG("Hostname realloc failed."); return WOLFSSL_FAILURE; @@ -2926,7 +2959,7 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) bio->wrSz = len; bio->ptr.mem_buf_data = (byte *)bio->mem_buf->data; if (len > 0 && bio->ptr.mem_buf_data != NULL) { - XMEMCPY(bio->ptr.mem_buf_data, buf, len); + XMEMCPY(bio->ptr.mem_buf_data, buf, (size_t)len); bio->flags |= WOLFSSL_BIO_FLAG_MEM_RDONLY; bio->wrSzReset = bio->wrSz; } @@ -3295,11 +3328,11 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) count = XVSNPRINTF(NULL, 0, format, args); if (count >= 0) { - pt = (char*)XMALLOC(count + 1, bio->heap, + pt = (char*)XMALLOC((size_t)count + 1, bio->heap, DYNAMIC_TYPE_TMP_BUFFER); if (pt != NULL) { - count = XVSNPRINTF(pt, count + 1, format, copy); + count = XVSNPRINTF(pt, (size_t)count + 1, format, copy); if (count >= 0) { ret = wolfSSL_BIO_write(bio, pt, count); @@ -3369,18 +3402,20 @@ int wolfSSL_BIO_dump(WOLFSSL_BIO *bio, const char *buf, int length) o = 7; for (i = 0; i < BIO_DUMP_LINE_LEN; i++) { if (i < length) - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%02x ", (unsigned char)buf[i]); else - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), + " "); if (i == 7) - (void)XSNPRINTF(line + o + 2, (int)sizeof(line) - (o + 2), "-"); + (void)XSNPRINTF(line + o + 2, (size_t)((int)sizeof(line) - + (o + 2)), "-"); o += 3; } - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, " "); + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), " "); o += 2; for (i = 0; (i < BIO_DUMP_LINE_LEN) && (i < length); i++) { - (void)XSNPRINTF(line + o, (int)sizeof(line) - o, "%c", + (void)XSNPRINTF(line + o, (size_t)((int)sizeof(line) - o), "%c", ((31 < buf[i]) && (buf[i] < 127)) ? buf[i] : '.'); o++; } diff --git a/src/wolfssl/callbacks.h b/src/wolfssl/callbacks.h index dc3ad89..a75e483 100644 --- a/src/wolfssl/callbacks.h +++ b/src/wolfssl/callbacks.h @@ -1,6 +1,6 @@ /* callbacks.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/crl.h b/src/wolfssl/crl.h index cdf52f3..56f5003 100644 --- a/src/wolfssl/crl.h +++ b/src/wolfssl/crl.h @@ -1,6 +1,6 @@ /* crl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/error-ssl.h b/src/wolfssl/error-ssl.h index 2d4d802..bc3e641 100644 --- a/src/wolfssl/error-ssl.h +++ b/src/wolfssl/error-ssl.h @@ -1,6 +1,6 @@ /* error-ssl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/evp.c b/src/wolfssl/evp.c index c3eb12e..7054f80 100644 --- a/src/wolfssl/evp.c +++ b/src/wolfssl/evp.c @@ -1,6 +1,6 @@ /* evp.c * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -19,12 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#include +#include #if !defined(WOLFSSL_EVP_INCLUDED) #ifndef WOLFSSL_IGNORE_FILE_WARN @@ -52,67 +47,67 @@ static const struct s_ent { const char *name; } md_tbl[] = { #ifndef NO_MD4 - {WC_HASH_TYPE_MD4, WC_NID_md4, "MD4"}, + {WC_HASH_TYPE_MD4, WC_NID_md4, WC_SN_md4}, #endif /* NO_MD4 */ #ifndef NO_MD5 - {WC_HASH_TYPE_MD5, WC_NID_md5, "MD5"}, + {WC_HASH_TYPE_MD5, WC_NID_md5, WC_SN_md5}, #endif /* NO_MD5 */ #ifndef NO_SHA - {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA1"}, + {WC_HASH_TYPE_SHA, WC_NID_sha1, WC_SN_sha1}, {WC_HASH_TYPE_SHA, WC_NID_sha1, "SHA"}, /* Leave for backwards compatibility */ #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - {WC_HASH_TYPE_SHA224, WC_NID_sha224, "SHA224"}, + {WC_HASH_TYPE_SHA224, WC_NID_sha224, WC_SN_sha224}, #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 - {WC_HASH_TYPE_SHA256, WC_NID_sha256, "SHA256"}, + {WC_HASH_TYPE_SHA256, WC_NID_sha256, WC_SN_sha256}, #endif #ifdef WOLFSSL_SHA384 - {WC_HASH_TYPE_SHA384, WC_NID_sha384, "SHA384"}, + {WC_HASH_TYPE_SHA384, WC_NID_sha384, WC_SN_sha384}, #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 - {WC_HASH_TYPE_SHA512, WC_NID_sha512, "SHA512"}, + {WC_HASH_TYPE_SHA512, WC_NID_sha512, WC_SN_sha512}, #endif /* WOLFSSL_SHA512 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, "SHA512_224"}, + {WC_HASH_TYPE_SHA512_224, WC_NID_sha512_224, WC_SN_sha512_224}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_224 */ #if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, "SHA512_256"}, + {WC_HASH_TYPE_SHA512_256, WC_NID_sha512_256, WC_SN_sha512_256}, #endif /* WOLFSSL_SHA512 && !WOLFSSL_NOSHA512_256 */ #ifndef WOLFSSL_NOSHA3_224 - {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, "SHA3_224"}, + {WC_HASH_TYPE_SHA3_224, WC_NID_sha3_224, WC_SN_sha3_224}, #endif #ifndef WOLFSSL_NOSHA3_256 - {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, "SHA3_256"}, + {WC_HASH_TYPE_SHA3_256, WC_NID_sha3_256, WC_SN_sha3_256}, #endif #ifndef WOLFSSL_NOSHA3_384 - {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, "SHA3_384"}, + {WC_HASH_TYPE_SHA3_384, WC_NID_sha3_384, WC_SN_sha3_384}, #endif #ifndef WOLFSSL_NOSHA3_512 - {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, "SHA3_512"}, + {WC_HASH_TYPE_SHA3_512, WC_NID_sha3_512, WC_SN_sha3_512}, #endif #ifdef WOLFSSL_SM3 - {WC_HASH_TYPE_SM3, WC_NID_sm3, "SM3"}, + {WC_HASH_TYPE_SM3, WC_NID_sm3, WC_SN_sm3}, #endif /* WOLFSSL_SHA512 */ #ifdef HAVE_BLAKE2 - {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, "BLAKE2B512"}, + {WC_HASH_TYPE_BLAKE2B, WC_NID_blake2b512, WC_SN_blake2b512}, #endif #ifdef HAVE_BLAKE2S - {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, "BLAKE2S256"}, + {WC_HASH_TYPE_BLAKE2S, WC_NID_blake2s256, WC_SN_blake2s256}, #endif #ifdef WOLFSSL_SHAKE128 - {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, "SHAKE128"}, + {WC_HASH_TYPE_SHAKE128, WC_NID_shake128, WC_SN_shake128}, #endif #ifdef WOLFSSL_SHAKE256 - {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, "SHAKE256"}, + {WC_HASH_TYPE_SHAKE256, WC_NID_shake256, WC_SN_shake256}, #endif {WC_HASH_TYPE_NONE, 0, NULL} }; @@ -1059,6 +1054,14 @@ int wolfSSL_EVP_CipherUpdate(WOLFSSL_EVP_CIPHER_CTX *ctx, } switch (ctx->cipherType) { + case WC_NULL_CIPHER_TYPE: + if (out == NULL) { + WOLFSSL_MSG("Bad argument"); + return WOLFSSL_FAILURE; + } + XMEMMOVE(out, in, inl); + *outl = inl; + return WOLFSSL_SUCCESS; #if !defined(NO_AES) && defined(HAVE_AESGCM) case WC_AES_128_GCM_TYPE: case WC_AES_192_GCM_TYPE: @@ -2046,6 +2049,165 @@ static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher) else return 0; } +/* Getter function for cipher type string + * + * cipherType cipherType enum value to get string for + * + * Returns string representation of the cipher type or NULL if not found + */ +const char* wolfSSL_EVP_CIPHER_type_string(unsigned int cipherType) +{ + WOLFSSL_ENTER("wolfSSL_EVP_CIPHER_type_string"); + + switch (cipherType) { +#ifndef NO_DES3 + case WC_DES_CBC_TYPE: return EVP_DES_CBC; + case WC_DES_EDE3_CBC_TYPE: return EVP_DES_EDE3_CBC; + case WC_DES_ECB_TYPE: return EVP_DES_ECB; + case WC_DES_EDE3_ECB_TYPE: return EVP_DES_EDE3_ECB; +#endif +#if !defined(NO_AES) + #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CBC_TYPE: return EVP_AES_128_CBC; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CBC_TYPE: return EVP_AES_192_CBC; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CBC_TYPE: return EVP_AES_256_CBC; + #endif + #endif /* HAVE_AES_CBC || WOLFSSL_AES_DIRECT */ + #if defined(WOLFSSL_AES_CFB) + #ifndef WOLFSSL_NO_AES_CFB_1_8 + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB1_TYPE: return EVP_AES_128_CFB1; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB1_TYPE: return EVP_AES_192_CFB1; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB1_TYPE: return EVP_AES_256_CFB1; + #endif + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB8_TYPE: return EVP_AES_128_CFB8; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB8_TYPE: return EVP_AES_192_CFB8; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB8_TYPE: return EVP_AES_256_CFB8; + #endif + #endif /* !WOLFSSL_NO_AES_CFB_1_8 */ + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CFB128_TYPE: return EVP_AES_128_CFB128; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CFB128_TYPE: return EVP_AES_192_CFB128; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CFB128_TYPE: return EVP_AES_256_CFB128; + #endif + #endif /* WOLFSSL_AES_CFB */ + #if defined(WOLFSSL_AES_OFB) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_OFB_TYPE: return EVP_AES_128_OFB; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_OFB_TYPE: return EVP_AES_192_OFB; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_OFB_TYPE: return EVP_AES_256_OFB; + #endif + #endif /* WOLFSSL_AES_OFB */ + #if defined(WOLFSSL_AES_XTS) && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_XTS_TYPE: return EVP_AES_128_XTS; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_XTS_TYPE: return EVP_AES_256_XTS; + #endif + #endif /* WOLFSSL_AES_XTS && (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) */ + #if defined(HAVE_AESGCM) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_GCM_TYPE: return EVP_AES_128_GCM; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_GCM_TYPE: return EVP_AES_192_GCM; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_GCM_TYPE: return EVP_AES_256_GCM; + #endif + #endif /* HAVE_AESGCM */ + #if defined(HAVE_AESCCM) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CCM_TYPE: return EVP_AES_128_CCM; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CCM_TYPE: return EVP_AES_192_CCM; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CCM_TYPE: return EVP_AES_256_CCM; + #endif + #endif /* HAVE_AESCCM */ + #if defined(WOLFSSL_AES_COUNTER) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_CTR_TYPE: return EVP_AES_128_CTR; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_CTR_TYPE: return EVP_AES_192_CTR; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_CTR_TYPE: return EVP_AES_256_CTR; + #endif + #endif /* WOLFSSL_AES_COUNTER */ + #if defined(HAVE_AES_ECB) + #ifdef WOLFSSL_AES_128 + case WC_AES_128_ECB_TYPE: return EVP_AES_128_ECB; + #endif + #ifdef WOLFSSL_AES_192 + case WC_AES_192_ECB_TYPE: return EVP_AES_192_ECB; + #endif + #ifdef WOLFSSL_AES_256 + case WC_AES_256_ECB_TYPE: return EVP_AES_256_ECB; + #endif + #endif /* HAVE_AES_ECB */ +#endif /* !NO_AES */ +#if defined(HAVE_ARIA) + case WC_ARIA_128_GCM_TYPE: return EVP_ARIA_128_GCM; + case WC_ARIA_192_GCM_TYPE: return EVP_ARIA_192_GCM; + case WC_ARIA_256_GCM_TYPE: return EVP_ARIA_256_GCM; +#endif /* HAVE_ARIA */ +#ifndef NO_RC4 + case WC_ARC4_TYPE: return EVP_ARC4; +#endif +#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) + case WC_CHACHA20_POLY1305_TYPE: return EVP_CHACHA20_POLY1305; +#endif +#ifdef HAVE_CHACHA + case WC_CHACHA20_TYPE: return EVP_CHACHA20; +#endif +#ifdef WOLFSSL_SM4_ECB + case WC_SM4_ECB_TYPE: return EVP_SM4_ECB; +#endif +#ifdef WOLFSSL_SM4_CBC + case WC_SM4_CBC_TYPE: return EVP_SM4_CBC; +#endif +#ifdef WOLFSSL_SM4_CTR + case WC_SM4_CTR_TYPE: return EVP_SM4_CTR; +#endif +#ifdef WOLFSSL_SM4_GCM + case WC_SM4_GCM_TYPE: return EVP_SM4_GCM; +#endif +#ifdef WOLFSSL_SM4_CCM + case WC_SM4_CCM_TYPE: return EVP_SM4_CCM; +#endif + case WC_NULL_CIPHER_TYPE: return EVP_NULL; + default: + return NULL; + } +} + int wolfSSL_EVP_CIPHER_block_size(const WOLFSSL_EVP_CIPHER *cipher) { if (cipher == NULL) @@ -2633,7 +2795,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ return WOLFSSL_FAILURE; } if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) { - if (wc_HKDF(hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, + if (wc_HKDF((int)hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, (word32)*keylen) != 0) { @@ -2642,7 +2804,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ } } else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) { - if (wc_HKDF_Extract(hkdfHashType, ctx->pkey->hkdfSalt, + if (wc_HKDF_Extract((int)hkdfHashType, ctx->pkey->hkdfSalt, ctx->pkey->hkdfSaltSz, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, key) != 0) { WOLFSSL_MSG("wc_HKDF_Extract failed."); @@ -2659,7 +2821,7 @@ int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_ } } else if (ctx->pkey->hkdfMode == WOLFSSL_EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) { - if (wc_HKDF_Expand(hkdfHashType, ctx->pkey->hkdfKey, + if (wc_HKDF_Expand((int)hkdfHashType, ctx->pkey->hkdfKey, ctx->pkey->hkdfKeySz, ctx->pkey->hkdfInfo, ctx->pkey->hkdfInfoSz, key, (word32)*keylen) != 0) { @@ -3316,14 +3478,44 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, */ int wolfSSL_EVP_PKEY_bits(const WOLFSSL_EVP_PKEY *pkey) { - int bytes; + int ret = 0; - if (pkey == NULL) return 0; - WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); - if ((bytes = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey)) ==0) return 0; - if (bytes < 0) + if (pkey == NULL) return 0; - return bytes*8; + + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_bits"); + + switch (pkey->type) { +#ifndef NO_RSA + case WC_EVP_PKEY_RSA: + ret = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(pkey->rsa)); + break; +#endif /* !NO_RSA */ + +#ifndef NO_DSA + case WC_EVP_PKEY_DSA: + if (pkey->dsa == NULL || + (!pkey->dsa->exSet && + SetDsaExternal(pkey->dsa) != WOLFSSL_SUCCESS)) + break; + ret = wolfSSL_BN_num_bytes(pkey->dsa->p); + break; +#endif + +#ifdef HAVE_ECC + case WC_EVP_PKEY_EC: + if (pkey->ecc == NULL || pkey->ecc->internal == NULL) { + WOLFSSL_MSG("No ECC key has been set"); + break; + } + ret = wc_ecc_size((ecc_key*)(pkey->ecc->internal)); + break; +#endif /* HAVE_ECC */ + + default: + break; + } + return ret > 0 ? ret * 8 : 0; } @@ -3530,12 +3722,11 @@ int wolfSSL_EVP_PKEY_keygen(WOLFSSL_EVP_PKEY_CTX *ctx, return ret; } -/* Get the size in bytes for WOLFSSL_EVP_PKEY key +/* Get the maximum suitable size for the operations that can be done with pkey * * pkey WOLFSSL_EVP_PKEY structure to get key size of * - * returns the size of a key on success which is the maximum size of a - * signature + * returns the recommended size of buffers */ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) { @@ -3563,7 +3754,7 @@ int wolfSSL_EVP_PKEY_size(WOLFSSL_EVP_PKEY *pkey) WOLFSSL_MSG("No ECC key has been set"); break; } - return wc_ecc_size((ecc_key*)(pkey->ecc->internal)); + return wc_ecc_sig_size((ecc_key*)(pkey->ecc->internal)); #endif /* HAVE_ECC */ default: @@ -3732,7 +3923,6 @@ int wolfSSL_EVP_PKEY_missing_parameters(WOLFSSL_EVP_PKEY *pkey) int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) { int ret = -1; /* failure */ - int a_sz = 0, b_sz = 0; if (a == NULL || b == NULL) return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); @@ -3745,40 +3935,47 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) switch (a->type) { #ifndef NO_RSA case WC_EVP_PKEY_RSA: - a_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)); - b_sz = (int)wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)); + if (wolfSSL_RSA_size((const WOLFSSL_RSA*)(a->rsa)) <= 0 || + wolfSSL_RSA_size((const WOLFSSL_RSA*)(b->rsa)) <= 0) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (mp_cmp(&((RsaKey*)a->rsa->internal)->n, + &((RsaKey*)b->rsa->internal)->n) != MP_EQ) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (mp_cmp(&((RsaKey*)a->rsa->internal)->e, + &((RsaKey*)b->rsa->internal)->e) != MP_EQ) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } break; #endif /* !NO_RSA */ #ifdef HAVE_ECC case WC_EVP_PKEY_EC: if (a->ecc == NULL || a->ecc->internal == NULL || - b->ecc == NULL || b->ecc->internal == NULL) { + b->ecc == NULL || b->ecc->internal == NULL || + wc_ecc_size((ecc_key*)a->ecc->internal) <= 0 || + wc_ecc_size((ecc_key*)b->ecc->internal) <= 0 || + a->ecc->group == NULL || b->ecc->group == NULL) { return ret; } - a_sz = wc_ecc_size((ecc_key*)(a->ecc->internal)); - b_sz = wc_ecc_size((ecc_key*)(b->ecc->internal)); + + /* check curve */ + if (a->ecc->group->curve_idx != b->ecc->group->curve_idx) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } + + if (wc_ecc_cmp_point(&((ecc_key*)a->ecc->internal)->pubkey, + &((ecc_key*)b->ecc->internal)->pubkey) != 0) { + return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); + } break; #endif /* HAVE_ECC */ default: return WS_RETURN_CODE(ret, -2); } /* switch (a->type) */ - /* check size */ - if (a_sz <= 0 || b_sz <= 0 || a_sz != b_sz) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - - /* check public key size */ - if (a->pkey_sz > 0 && b->pkey_sz > 0 && a->pkey_sz != b->pkey_sz) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - - /* check public key */ - if (a->pkey.ptr && b->pkey.ptr) { - if (XMEMCMP(a->pkey.ptr, b->pkey.ptr, (size_t)a->pkey_sz) != 0) { - return WS_RETURN_CODE(ret, WOLFSSL_FAILURE); - } - } #if defined(WOLFSSL_ERROR_CODE_OPENSSL) ret = 1; /* the keys match */ #else @@ -3795,18 +3992,11 @@ int wolfSSL_EVP_PKEY_cmp(const WOLFSSL_EVP_PKEY *a, const WOLFSSL_EVP_PKEY *b) static int DH_param_check(WOLFSSL_DH* dh_key) { int ret = WOLFSSL_SUCCESS; - WOLFSSL_BN_CTX* ctx = NULL; WOLFSSL_BIGNUM *num1 = NULL; WOLFSSL_BIGNUM *num2 = NULL; WOLFSSL_ENTER("DH_param_check"); - ctx = wolfSSL_BN_CTX_new(); - if (ctx == NULL) { - WOLFSSL_MSG("failed to allocate memory"); - return WOLFSSL_FAILURE; - } - num1 = wolfSSL_BN_new(); num2 = wolfSSL_BN_new(); if (num1 == NULL || num2 == NULL) { @@ -3840,7 +4030,7 @@ static int DH_param_check(WOLFSSL_DH* dh_key) dh_key->q != NULL) { if (ret == WOLFSSL_SUCCESS && - wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, ctx) + wolfSSL_BN_mod_exp(num1, dh_key->g, dh_key->q, dh_key->p, NULL) == WC_NO_ERR_TRACE(WOLFSSL_FAILURE)) { WOLFSSL_MSG("BN_mod_exp failed"); @@ -3855,7 +4045,7 @@ static int DH_param_check(WOLFSSL_DH* dh_key) #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) /* test if the number q is prime. */ if (ret == WOLFSSL_SUCCESS && - (wolfSSL_BN_is_prime_ex(dh_key->q, 64, ctx, NULL) <= 0)) { + (wolfSSL_BN_is_prime_ex(dh_key->q, 64, NULL, NULL) <= 0)) { WOLFSSL_MSG("dh_key->q is not prime or error during check."); ret = WOLFSSL_FAILURE; } /* else TODO check q div q - 1. need BN_div */ @@ -3863,7 +4053,6 @@ static int DH_param_check(WOLFSSL_DH* dh_key) } /* clean up */ - wolfSSL_BN_CTX_free(ctx); wolfSSL_BN_free(num1); wolfSSL_BN_free(num2); @@ -4043,9 +4232,13 @@ int wolfSSL_EVP_SignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sigret, pkey->ecc); if (ecdsaSig == NULL) return WOLFSSL_FAILURE; + /* get signature length only */ ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); - if (ret <= 0 || ret > (int)*siglen) + if (ret <= 0 || ret > (int)*siglen) { + wolfSSL_ECDSA_SIG_free(ecdsaSig); return WOLFSSL_FAILURE; + } + /* perform validation of signature */ ret = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sigret); wolfSSL_ECDSA_SIG_free(ecdsaSig); if (ret <= 0 || ret > (int)*siglen) @@ -4262,69 +4455,69 @@ static int wolfssl_evp_md_to_hash_type(const WOLFSSL_EVP_MD *type, int ret = 0; #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { *hashType = WC_SHA256; } else #endif #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { *hashType = WC_SHA; } else #endif /* NO_SHA */ #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { *hashType = WC_SHA224; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { *hashType = WC_SHA384; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { *hashType = WC_SHA512; } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { *hashType = WC_SHA3_224; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { *hashType = WC_SHA3_256; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { *hashType = WC_SHA3_384; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { *hashType = WC_SHA3_512; } else #endif #endif #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { *hashType = WC_SM3; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { *hashType = WC_MD5; } else @@ -4644,7 +4837,9 @@ int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *sig, ctx->pctx->pkey->ecc); if (ecdsaSig == NULL) break; - len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sig); + len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, NULL); + if (len > 0 && (size_t)len <= *siglen) + len = wolfSSL_i2d_ECDSA_SIG(ecdsaSig, &sig); wolfSSL_ECDSA_SIG_free(ecdsaSig); if (len == 0) break; @@ -4867,6 +5062,7 @@ int wolfSSL_PKCS5_PBKDF2_HMAC(const char *pass, int passlen, { const char *nostring = ""; int ret = 0; + enum wc_HashType pbkdf2HashType; if (pass == NULL) { passlen = 0; @@ -4875,8 +5071,10 @@ int wolfSSL_PKCS5_PBKDF2_HMAC(const char *pass, int passlen, passlen = (int)XSTRLEN(pass); } + pbkdf2HashType = EvpMd2MacType(digest); + ret = wc_PBKDF2((byte*)out, (byte*)pass, passlen, (byte*)salt, saltlen, - iter, keylen, EvpMd2MacType(digest)); + iter, keylen, pbkdf2HashType); if (ret == 0) return WOLFSSL_SUCCESS; else @@ -6299,14 +6497,16 @@ void wolfSSL_EVP_init(void) case WC_AES_256_OFB_TYPE: #endif wc_AesFree(&ctx->cipher.aes); - ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; + ctx->flags &= + (unsigned long)~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #if defined(WOLFSSL_AES_XTS) && \ (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3)) case WC_AES_128_XTS_TYPE: case WC_AES_256_XTS_TYPE: wc_AesXtsFree(&ctx->cipher.xts); - ctx->flags &= ~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; + ctx->flags &= + (unsigned long)~WOLFSSL_EVP_CIPH_LOW_LEVEL_INITED; break; #endif #endif /* AES */ @@ -6875,7 +7075,7 @@ void wolfSSL_EVP_init(void) ret = wc_AriaInitCrypt(&ctx->cipher.aria, MC_ALGID_ARIA_256BITKEY); break; default: - WOLFSSL_MSG("Not implemented cipherType"); + WOLFSSL_MSG("Unimplemented cipherType"); return WOLFSSL_NOT_IMPLEMENTED; /* This should never happen */ } if (ret != 0) { @@ -8258,9 +8458,9 @@ void wolfSSL_EVP_init(void) } #endif /* !NO_AES || !NO_DES3 */ - static int IsCipherTypeAEAD(unsigned char cipherType) + static int IsCipherTypeAEAD(unsigned int type) { - switch (cipherType) { + switch (type) { case WC_AES_128_GCM_TYPE: case WC_AES_192_GCM_TYPE: case WC_AES_256_GCM_TYPE: @@ -9367,22 +9567,22 @@ int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type) WOLFSSL_ENTER("wolfSSL_EVP_MD_pkey_type"); if (type != NULL) { - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { ret = WC_NID_md5WithRSAEncryption; } - else if (XSTRCMP(type, "SHA1") == 0) { + else if (XSTRCMP(type, WC_SN_sha1) == 0) { ret = WC_NID_sha1WithRSAEncryption; } - else if (XSTRCMP(type, "SHA224") == 0) { + else if (XSTRCMP(type, WC_SN_sha224) == 0) { ret = WC_NID_sha224WithRSAEncryption; } - else if (XSTRCMP(type, "SHA256") == 0) { + else if (XSTRCMP(type, WC_SN_sha256) == 0) { ret = WC_NID_sha256WithRSAEncryption; } - else if (XSTRCMP(type, "SHA384") == 0) { + else if (XSTRCMP(type, WC_SN_sha384) == 0) { ret = WC_NID_sha384WithRSAEncryption; } - else if (XSTRCMP(type, "SHA512") == 0) { + else if (XSTRCMP(type, WC_SN_sha512) == 0) { ret = WC_NID_sha512WithRSAEncryption; } } @@ -9936,54 +10136,44 @@ static const struct alias { const char *alias; } digest_alias_tbl[] = { - {"MD4", "md4"}, - {"MD5", "md5"}, - {"SHA1", "sha1"}, - {"SHA1", "SHA"}, - {"SHA224", "sha224"}, - {"SHA256", "sha256"}, - {"SHA384", "sha384"}, - {"SHA512", "sha512"}, - {"SHA512_224", "sha512_224"}, - {"SHA3_224", "sha3_224"}, - {"SHA3_256", "sha3_256"}, - {"SHA3_384", "sha3_384"}, - {"SHA3_512", "sha3_512"}, - {"SM3", "sm3"}, - {"BLAKE2B512", "blake2b512"}, - {"BLAKE2S256", "blake2s256"}, - {"SHAKE128", "shake128"}, - {"SHAKE256", "shake256"}, + {WC_SN_md4, "md4"}, + {WC_SN_md5, "md5"}, + {WC_SN_sha1, "sha1"}, + {WC_SN_sha1, "SHA"}, + {WC_SN_sha224, "sha224"}, + {WC_SN_sha256, "sha256"}, + {WC_SN_sha384, "sha384"}, + {WC_SN_sha512, "sha512"}, + {WC_SN_sha512_224, "sha512_224"}, + {WC_SN_sha3_224, "sha3_224"}, + {WC_SN_sha3_256, "sha3_256"}, + {WC_SN_sha3_384, "sha3_384"}, + {WC_SN_sha3_512, "sha3_512"}, + {WC_SN_sm3, "sm3"}, + {WC_SN_blake2b512, "blake2b512"}, + {WC_SN_blake2s256, "blake2s256"}, + {WC_SN_shake128, "shake128"}, + {WC_SN_shake256, "shake256"}, { NULL, NULL} }; const WOLFSSL_EVP_MD *wolfSSL_EVP_get_digestbyname(const char *name) { - char nameUpper[15]; /* 15 bytes should be enough for any name */ - size_t i; - const struct alias *al; const struct s_ent *ent; - for (i = 0; i < sizeof(nameUpper) && name[i] != '\0'; i++) { - nameUpper[i] = (char)XTOUPPER((unsigned char) name[i]); - } - if (i < sizeof(nameUpper)) - nameUpper[i] = '\0'; - else - return NULL; - - name = nameUpper; - for (al = digest_alias_tbl; al->name != NULL; al++) + for (al = digest_alias_tbl; al->name != NULL; al++) { if(XSTRCMP(name, al->alias) == 0) { name = al->name; break; } + } - for (ent = md_tbl; ent->name != NULL; ent++) + for (ent = md_tbl; ent->name != NULL; ent++) { if(XSTRCMP(name, ent->name) == 0) { return (WOLFSSL_EVP_MD *)ent->name; } + } return NULL; } @@ -10017,7 +10207,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md4(void) { WOLFSSL_ENTER("EVP_md4"); - return wolfSSL_EVP_get_digestbyname("MD4"); + return wolfSSL_EVP_get_digestbyname(WC_SN_md4); } #endif /* !NO_MD4 */ @@ -10028,7 +10218,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_md5(void) { WOLFSSL_ENTER("EVP_md5"); - return wolfSSL_EVP_get_digestbyname("MD5"); + return wolfSSL_EVP_get_digestbyname(WC_SN_md5); } #endif /* !NO_MD5 */ @@ -10040,8 +10230,8 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) */ const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2b512(void) { - WOLFSSL_ENTER("EVP_blake2b512"); - return wolfSSL_EVP_get_digestbyname("BLAKE2b512"); + WOLFSSL_ENTER("wolfSSL_EVP_blake2b512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_blake2b512); } #endif @@ -10080,7 +10270,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha1(void) { WOLFSSL_ENTER("EVP_sha1"); - return wolfSSL_EVP_get_digestbyname("SHA1"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha1); } #endif /* NO_SHA */ @@ -10089,7 +10279,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha224(void) { WOLFSSL_ENTER("EVP_sha224"); - return wolfSSL_EVP_get_digestbyname("SHA224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha224); } #endif /* WOLFSSL_SHA224 */ @@ -10098,7 +10288,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha256(void) { WOLFSSL_ENTER("EVP_sha256"); - return wolfSSL_EVP_get_digestbyname("SHA256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha256); } #ifdef WOLFSSL_SHA384 @@ -10106,7 +10296,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha384(void) { WOLFSSL_ENTER("EVP_sha384"); - return wolfSSL_EVP_get_digestbyname("SHA384"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha384); } #endif /* WOLFSSL_SHA384 */ @@ -10116,7 +10306,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512(void) { WOLFSSL_ENTER("EVP_sha512"); - return wolfSSL_EVP_get_digestbyname("SHA512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512); } #ifndef WOLFSSL_NOSHA512_224 @@ -10124,7 +10314,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_224(void) { WOLFSSL_ENTER("EVP_sha512_224"); - return wolfSSL_EVP_get_digestbyname("SHA512_224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512_224); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10133,7 +10323,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha512_256(void) { WOLFSSL_ENTER("EVP_sha512_256"); - return wolfSSL_EVP_get_digestbyname("SHA512_256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha512_256); } #endif /* !WOLFSSL_NOSHA512_224 */ @@ -10145,7 +10335,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_224(void) { WOLFSSL_ENTER("EVP_sha3_224"); - return wolfSSL_EVP_get_digestbyname("SHA3_224"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_224); } #endif /* WOLFSSL_NOSHA3_224 */ @@ -10154,7 +10344,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_256(void) { WOLFSSL_ENTER("EVP_sha3_256"); - return wolfSSL_EVP_get_digestbyname("SHA3_256"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_256); } #endif /* WOLFSSL_NOSHA3_256 */ @@ -10162,7 +10352,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_384(void) { WOLFSSL_ENTER("EVP_sha3_384"); - return wolfSSL_EVP_get_digestbyname("SHA3_384"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_384); } #endif /* WOLFSSL_NOSHA3_384 */ @@ -10170,7 +10360,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sha3_512(void) { WOLFSSL_ENTER("EVP_sha3_512"); - return wolfSSL_EVP_get_digestbyname("SHA3_512"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sha3_512); } #endif /* WOLFSSL_NOSHA3_512 */ @@ -10196,7 +10386,7 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) const WOLFSSL_EVP_MD* wolfSSL_EVP_sm3(void) { WOLFSSL_ENTER("EVP_sm3"); - return wolfSSL_EVP_get_digestbyname("SM3"); + return wolfSSL_EVP_get_digestbyname(WC_SN_sm3); } #endif /* WOLFSSL_SM3 */ @@ -10482,17 +10672,21 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) /* Not an error since an unused struct could be free'd or * reset. */ break; - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD4: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + wc_Shake128_Free(&ctx->hash.digest.shake); + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + wc_Shake256_Free(&ctx->hash.digest.shake); + break; #endif + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: default: ret = WOLFSSL_FAILURE; break; @@ -10526,76 +10720,92 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) XMEMSET(&ctx->hash.digest, 0, sizeof(WOLFSSL_Hasher)); } else #ifndef NO_SHA - if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, "SHA1") == 0)) { + if ((XSTRCMP(md, "SHA") == 0) || (XSTRCMP(md, WC_SN_sha1) == 0)) { ret = wolfSSL_SHA_Init(&(ctx->hash.digest.sha)); } else #endif #ifndef NO_SHA256 - if (XSTRCMP(md, "SHA256") == 0) { + if (XSTRCMP(md, WC_SN_sha256) == 0) { ret = wolfSSL_SHA256_Init(&(ctx->hash.digest.sha256)); } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(md, "SHA224") == 0) { + if (XSTRCMP(md, WC_SN_sha224) == 0) { ret = wolfSSL_SHA224_Init(&(ctx->hash.digest.sha224)); } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(md, "SHA384") == 0) { + if (XSTRCMP(md, WC_SN_sha384) == 0) { ret = wolfSSL_SHA384_Init(&(ctx->hash.digest.sha384)); } else #endif #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224) - if (XSTRCMP(md, "SHA512_224") == 0) { + if (XSTRCMP(md, WC_SN_sha512_224) == 0) { ret = wolfSSL_SHA512_224_Init(&(ctx->hash.digest.sha512)); } else #endif #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \ defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256) - if (XSTRCMP(md, "SHA512_256") == 0) { + if (XSTRCMP(md, WC_SN_sha512_256) == 0) { ret = wolfSSL_SHA512_256_Init(&(ctx->hash.digest.sha512)); } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(md, "SHA512") == 0) { + if (XSTRCMP(md, WC_SN_sha512) == 0) { ret = wolfSSL_SHA512_Init(&(ctx->hash.digest.sha512)); } else #endif #ifndef NO_MD4 - if (XSTRCMP(md, "MD4") == 0) { + if (XSTRCMP(md, WC_SN_md4) == 0) { wolfSSL_MD4_Init(&(ctx->hash.digest.md4)); } else #endif #ifndef NO_MD5 - if (XSTRCMP(md, "MD5") == 0) { + if (XSTRCMP(md, WC_SN_md5) == 0) { ret = wolfSSL_MD5_Init(&(ctx->hash.digest.md5)); } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(md, "SHA3_224") == 0) { + if (XSTRCMP(md, WC_SN_sha3_224) == 0) { ret = wolfSSL_SHA3_224_Init(&(ctx->hash.digest.sha3_224)); } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(md, "SHA3_256") == 0) { + if (XSTRCMP(md, WC_SN_sha3_256) == 0) { ret = wolfSSL_SHA3_256_Init(&(ctx->hash.digest.sha3_256)); } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(md, "SHA3_384") == 0) { + if (XSTRCMP(md, WC_SN_sha3_384) == 0) { ret = wolfSSL_SHA3_384_Init(&(ctx->hash.digest.sha3_384)); } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(md, "SHA3_512") == 0) { + if (XSTRCMP(md, WC_SN_sha3_512) == 0) { ret = wolfSSL_SHA3_512_Init(&(ctx->hash.digest.sha3_512)); } else #endif + #ifdef WOLFSSL_SHAKE128 + if (XSTRCMP(md, WC_SN_shake128) == 0) { + if (wc_InitShake128(&(ctx->hash.digest.shake), NULL, + INVALID_DEVID) != 0) { + ret = WOLFSSL_FAILURE; + } + } else + #endif + #ifdef WOLFSSL_SHAKE256 + if (XSTRCMP(md, WC_SN_shake256) == 0) { + if (wc_InitShake256(&(ctx->hash.digest.shake), NULL, + INVALID_DEVID) != 0) { + ret = WOLFSSL_FAILURE; + } + } else + #endif #endif #ifdef WOLFSSL_SM3 - if (XSTRCMP(md, "SM3") == 0) { + if (XSTRCMP(md, WC_SN_sm3) == 0) { ret = wc_InitSm3(&ctx->hash.digest.sm3, NULL, INVALID_DEVID); if (ret == 0) { ret = WOLFSSL_SUCCESS; @@ -10723,17 +10933,28 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } break; #endif - case WC_HASH_TYPE_NONE: - case WC_HASH_TYPE_MD2: - case WC_HASH_TYPE_MD5_SHA: - case WC_HASH_TYPE_BLAKE2B: - case WC_HASH_TYPE_BLAKE2S: #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + if (wc_Shake128_Update(&ctx->hash.digest.shake, + (const byte*)data, (word32)sz) == 0) { + + ret = WOLFSSL_SUCCESS; + } + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + if (wc_Shake256_Update(&ctx->hash.digest.shake, + (const byte*)data, (word32)sz) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; #endif + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: default: return WOLFSSL_FAILURE; } @@ -10742,14 +10963,11 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } /* WOLFSSL_SUCCESS on ok */ - int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, - unsigned int* s) + static int wolfSSL_EVP_DigestFinal_Common(WOLFSSL_EVP_MD_CTX* ctx, + unsigned char* md, unsigned int* s, enum wc_HashType macType) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); - enum wc_HashType macType; - WOLFSSL_ENTER("EVP_DigestFinal"); - macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); switch (macType) { case WC_HASH_TYPE_MD4: #ifndef NO_MD4 @@ -10847,23 +11065,84 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) } if (s) *s = WC_SM3_DIGEST_SIZE; break; + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + if (wc_Shake128_Final(&ctx->hash.digest.shake, md, *s) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + if (wc_Shake256_Final(&ctx->hash.digest.shake, md, *s) == 0) { + ret = WOLFSSL_SUCCESS; + } + break; #endif case WC_HASH_TYPE_NONE: case WC_HASH_TYPE_MD2: case WC_HASH_TYPE_MD5_SHA: case WC_HASH_TYPE_BLAKE2B: case WC_HASH_TYPE_BLAKE2S: + default: + return WOLFSSL_FAILURE; + } + + return ret; + } + + int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, + unsigned int* s) + { + enum wc_HashType macType; + + WOLFSSL_ENTER("wolfSSL_EVP_DigestFinal"); + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); + switch (macType) { + case WC_HASH_TYPE_MD4: + case WC_HASH_TYPE_MD5: + case WC_HASH_TYPE_SHA: + case WC_HASH_TYPE_SHA224: + case WC_HASH_TYPE_SHA256: + case WC_HASH_TYPE_SHA384: + case WC_HASH_TYPE_SHA512: + #ifndef WOLFSSL_NOSHA512_224 + case WC_HASH_TYPE_SHA512_224: + #endif /* !WOLFSSL_NOSHA512_224 */ + #ifndef WOLFSSL_NOSHA512_256 + case WC_HASH_TYPE_SHA512_256: + #endif /* !WOLFSSL_NOSHA512_256 */ + case WC_HASH_TYPE_SHA3_224: + case WC_HASH_TYPE_SHA3_256: + case WC_HASH_TYPE_SHA3_384: + case WC_HASH_TYPE_SHA3_512: + #ifdef WOLFSSL_SM3 + case WC_HASH_TYPE_SM3: + #endif + case WC_HASH_TYPE_NONE: + case WC_HASH_TYPE_MD2: + case WC_HASH_TYPE_MD5_SHA: + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + break; + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) case WC_HASH_TYPE_SHAKE128: + *s = 16; /* if mixing up XOF with plain digest 128 bit is + * default for SHAKE128 */ + break; #endif #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) case WC_HASH_TYPE_SHAKE256: + *s = 32; /* if mixing up XOF with plain digest 256 bit is + * default for SHAKE256 */ + break; #endif default: return WOLFSSL_FAILURE; } - - return ret; + return wolfSSL_EVP_DigestFinal_Common(ctx, md, s, macType); } /* WOLFSSL_SUCCESS on ok */ @@ -10874,6 +11153,46 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return wolfSSL_EVP_DigestFinal(ctx, md, s); } + + /* XOF stands for extendable-output functions. This is used for algos such + * as SHAKE256. + * + * returns 1 (WOLFSSL_SUCCESS) on success and 0 (WOLFSSL_FAILURE) on fail */ + int wolfSSL_EVP_DigestFinalXOF(WOLFSSL_EVP_MD_CTX *ctx, unsigned char *md, + size_t sz) + { + unsigned int len; + enum wc_HashType macType; + + WOLFSSL_ENTER("wolfSSL_EVP_DigestFinalXOF"); + len = (unsigned int)sz; + + macType = EvpMd2MacType(wolfSSL_EVP_MD_CTX_md(ctx)); + return wolfSSL_EVP_DigestFinal_Common(ctx, md, &len, macType); + } + + + unsigned long wolfSSL_EVP_MD_flags(const WOLFSSL_EVP_MD *md) + { + enum wc_HashType macType; + + macType = EvpMd2MacType(md); + switch ((int)macType) { + case WC_HASH_TYPE_BLAKE2B: + case WC_HASH_TYPE_BLAKE2S: + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128) + case WC_HASH_TYPE_SHAKE128: + #endif + #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256) + case WC_HASH_TYPE_SHAKE256: + #endif + return WOLFSSL_EVP_MD_FLAG_XOF; + default: + return 0; + } + } + + void wolfSSL_EVP_cleanup(void) { /* nothing to do here */ @@ -10884,6 +11203,10 @@ const WOLFSSL_EVP_MD* wolfSSL_EVP_get_digestbynid(int id) WOLFSSL_MSG("wolfSSL_get_digestbynid"); switch(id) { +#ifndef NO_MD4 + case WC_NID_md4: + return wolfSSL_EVP_md4(); +#endif #ifndef NO_MD5 case WC_NID_md5: return wolfSSL_EVP_md5(); @@ -10928,64 +11251,64 @@ int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type) } #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { return WC_SHA_BLOCK_SIZE; } else #endif #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { return WC_SHA256_BLOCK_SIZE; } else #endif #ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { + if (XSTRCMP(type, WC_SN_md4) == 0) { return WC_MD4_BLOCK_SIZE; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { return WC_MD5_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { return WC_SHA224_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { return WC_SHA384_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { return WC_SHA512_BLOCK_SIZE; } else #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { return WC_SHA3_224_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { return WC_SHA3_256_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { return WC_SHA3_384_BLOCK_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { return WC_SHA3_512_BLOCK_SIZE; - } + } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { return WC_SM3_BLOCK_SIZE; } else #endif @@ -11003,74 +11326,74 @@ int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type) } #ifndef NO_SHA - if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, "SHA1") == 0)) { + if ((XSTRCMP(type, "SHA") == 0) || (XSTRCMP(type, WC_SN_sha1) == 0)) { return WC_SHA_DIGEST_SIZE; } else #endif #ifndef NO_SHA256 - if (XSTRCMP(type, "SHA256") == 0) { + if (XSTRCMP(type, WC_SN_sha256) == 0) { return WC_SHA256_DIGEST_SIZE; } else #endif #ifndef NO_MD4 - if (XSTRCMP(type, "MD4") == 0) { + if (XSTRCMP(type, WC_SN_md4) == 0) { return WC_MD4_DIGEST_SIZE; } else #endif #ifndef NO_MD5 - if (XSTRCMP(type, "MD5") == 0) { + if (XSTRCMP(type, WC_SN_md5) == 0) { return WC_MD5_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP(type, "SHA224") == 0) { + if (XSTRCMP(type, WC_SN_sha224) == 0) { return WC_SHA224_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP(type, "SHA384") == 0) { + if (XSTRCMP(type, WC_SN_sha384) == 0) { return WC_SHA384_DIGEST_SIZE; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP(type, "SHA512") == 0) { + if (XSTRCMP(type, WC_SN_sha512) == 0) { return WC_SHA512_DIGEST_SIZE; } else #ifndef WOLFSSL_NOSHA512_224 - if (XSTRCMP(type, "SHA512_224") == 0) { + if (XSTRCMP(type, WC_SN_sha512_224) == 0) { return WC_SHA512_224_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA512_256 - if (XSTRCMP(type, "SHA512_256") == 0) { + if (XSTRCMP(type, WC_SN_sha512_256) == 0) { return WC_SHA512_256_DIGEST_SIZE; } else #endif #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP(type, "SHA3_224") == 0) { + if (XSTRCMP(type, WC_SN_sha3_224) == 0) { return WC_SHA3_224_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP(type, "SHA3_256") == 0) { + if (XSTRCMP(type, WC_SN_sha3_256) == 0) { return WC_SHA3_256_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP(type, "SHA3_384") == 0) { + if (XSTRCMP(type, WC_SN_sha3_384) == 0) { return WC_SHA3_384_DIGEST_SIZE; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP(type, "SHA3_512") == 0) { + if (XSTRCMP(type, WC_SN_sha3_512) == 0) { return WC_SHA3_512_DIGEST_SIZE; } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP(type, "SM3") == 0) { + if (XSTRCMP(type, WC_SN_sm3) == 0) { return WC_SM3_DIGEST_SIZE; } #endif @@ -12182,7 +12505,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_RSA: #if !defined(NO_RSA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyRSA( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12198,7 +12521,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_EC: #if defined(HAVE_ECC) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyEC( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12214,7 +12537,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_DSA: #if !defined(NO_DSA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyDSA( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12230,7 +12553,7 @@ int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, case WC_EVP_PKEY_DH: #if defined(WOLFSSL_DH_EXTRA) - keybits = wolfSSL_EVP_PKEY_size((WOLFSSL_EVP_PKEY*)pkey) * 8; + keybits = wolfSSL_EVP_PKEY_bits((WOLFSSL_EVP_PKEY*)pkey); res = PrintPubKeyDH( out, (byte*)(pkey->pkey.ptr), /* buffer for pkey raw data */ @@ -12263,64 +12586,64 @@ int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp, } #ifndef NO_SHA - if ((XSTRCMP("SHA", evp) == 0) || (XSTRCMP("SHA1", evp) == 0)) { + if ((XSTRCMP("SHA", evp) == 0) || (XSTRCMP(WC_SN_sha1, evp) == 0)) { hash = WC_HASH_TYPE_SHA; } else #endif #ifdef WOLFSSL_SHA224 - if (XSTRCMP("SHA224", evp) == 0) { + if (XSTRCMP(WC_SN_sha224, evp) == 0) { hash = WC_HASH_TYPE_SHA224; } else #endif #ifndef NO_SHA256 - if (XSTRCMP("SHA256", evp) == 0) { + if (XSTRCMP(WC_SN_sha256, evp) == 0) { hash = WC_HASH_TYPE_SHA256; } else #endif #ifdef WOLFSSL_SHA384 - if (XSTRCMP("SHA384", evp) == 0) { + if (XSTRCMP(WC_SN_sha384, evp) == 0) { hash = WC_HASH_TYPE_SHA384; } else #endif #ifdef WOLFSSL_SHA512 - if (XSTRCMP("SHA512", evp) == 0) { + if (XSTRCMP(WC_SN_sha512, evp) == 0) { hash = WC_HASH_TYPE_SHA512; } else #ifndef WOLFSSL_NOSHA512_224 - if (XSTRCMP("SHA512_224", evp) == 0) { + if (XSTRCMP(WC_SN_sha512_224, evp) == 0) { hash = WC_HASH_TYPE_SHA512_224; } else #endif #ifndef WOLFSSL_NOSHA512_256 - if (XSTRCMP("SHA512_256", evp) == 0) { + if (XSTRCMP(WC_SN_sha512_256, evp) == 0) { hash = WC_HASH_TYPE_SHA512_256; } else #endif #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 - if (XSTRCMP("SHA3_224", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_224, evp) == 0) { hash = WC_HASH_TYPE_SHA3_224; } else #endif #ifndef WOLFSSL_NOSHA3_256 - if (XSTRCMP("SHA3_256", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_256, evp) == 0) { hash = WC_HASH_TYPE_SHA3_256; } else #endif #ifndef WOLFSSL_NOSHA3_384 - if (XSTRCMP("SHA3_384", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_384, evp) == 0) { hash = WC_HASH_TYPE_SHA3_384; } else #endif #ifndef WOLFSSL_NOSHA3_512 - if (XSTRCMP("SHA3_512", evp) == 0) { + if (XSTRCMP(WC_SN_sha3_512, evp) == 0) { hash = WC_HASH_TYPE_SHA3_512; } else #endif #endif /* WOLFSSL_SHA3 */ #ifdef WOLFSSL_SM3 - if (XSTRCMP("SM3", evp) == 0) { + if (XSTRCMP(WC_SN_sm3, evp) == 0) { hash = WC_HASH_TYPE_SM3; } else #endif @@ -12330,12 +12653,12 @@ int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp, } else #endif #ifndef NO_MD4 - if (XSTRCMP("MD4", evp) == 0) { + if (XSTRCMP(WC_SN_md4, evp) == 0) { hash = WC_HASH_TYPE_MD4; } else #endif #ifndef NO_MD5 - if (XSTRCMP("MD5", evp) == 0) { + if (XSTRCMP(WC_SN_md5, evp) == 0) { hash = WC_HASH_TYPE_MD5; } else #endif diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index 37a381a..9cdbdb6 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -1,6 +1,6 @@ /* internal.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -151,15 +151,25 @@ #include #endif -#ifdef USE_WINDOWS_API +#ifdef __WATCOMC__ + #if defined(__OS2__) + #elif defined(__NT__) + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ + #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ + #elif defined(__LINUX__) + #ifndef SINGLE_THREADED + #define WOLFSSL_PTHREADS + #include + #endif + #endif +#elif defined(USE_WINDOWS_API) #ifdef WOLFSSL_GAME_BUILD #include "system/xtl.h" #else - #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN) - /* On WinCE winsock2.h must be included before windows.h */ - #include - #endif + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ #endif #elif defined(THREADX) #ifndef SINGLE_THREADED @@ -232,7 +242,7 @@ #endif #if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM) #ifdef FUSION_RTOS - #include + #include #else #include /* for close of BIO */ #endif @@ -1827,20 +1837,23 @@ enum Misc { SM2_SA_MAJOR = 7, /* Most significant byte for SM2 with SM3 */ SM2_SA_MINOR = 8, /* Least significant byte for SM2 with SM3 */ - PQC_SA_MAJOR = 0xFE,/* Most significant byte used with PQC sig algs */ + FALCON_SA_MAJOR = 0xFE,/* Most significant byte used with falcon sig algs */ + DILITHIUM_SA_MAJOR = 0x09,/* Most significant byte used with dilithium sig algs */ - /* These values for falcon and dilithium match what OQS has defined. */ + /* These values for falcon match what OQS has defined. */ FALCON_LEVEL1_SA_MAJOR = 0xFE, FALCON_LEVEL1_SA_MINOR = 0xAE, FALCON_LEVEL5_SA_MAJOR = 0xFE, FALCON_LEVEL5_SA_MINOR = 0xB1, - DILITHIUM_LEVEL2_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL2_SA_MINOR = 0xD0, - DILITHIUM_LEVEL3_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL3_SA_MINOR = 0xD1, - DILITHIUM_LEVEL5_SA_MAJOR = 0xFE, - DILITHIUM_LEVEL5_SA_MINOR = 0xD2, + /* these values for MLDSA (Dilithium) correspond to what is proposed in the + * IETF. */ + DILITHIUM_LEVEL2_SA_MAJOR = 0x09, + DILITHIUM_LEVEL2_SA_MINOR = 0x04, + DILITHIUM_LEVEL3_SA_MAJOR = 0x09, + DILITHIUM_LEVEL3_SA_MINOR = 0x05, + DILITHIUM_LEVEL5_SA_MAJOR = 0x09, + DILITHIUM_LEVEL5_SA_MINOR = 0x06, MIN_RSA_SHA512_PSS_BITS = 512 * 2 + 8 * 8, /* Min key size */ MIN_RSA_SHA384_PSS_BITS = 384 * 2 + 8 * 8, /* Min key size */ @@ -1893,15 +1906,17 @@ enum Misc { #define AEAD_AUTH_DATA_SZ 13 #endif -#define WOLFSSL_NAMED_GROUP_IS_FFHDE(group) \ - (MIN_FFHDE_GROUP <= (group) && (group) <= MAX_FFHDE_GROUP) -#ifdef WOLFSSL_HAVE_KYBER -#define WOLFSSL_NAMED_GROUP_IS_PQC(group) \ - ((WOLFSSL_PQC_SIMPLE_MIN <= (group) && (group) <= WOLFSSL_PQC_SIMPLE_MAX) || \ - (WOLFSSL_PQC_HYBRID_MIN <= (group) && (group) <= WOLFSSL_PQC_HYBRID_MAX)) +#define WOLFSSL_NAMED_GROUP_IS_FFDHE(group) \ + (WOLFSSL_FFDHE_START <= (group) && (group) <= WOLFSSL_FFDHE_END) +#ifdef WOLFSSL_HAVE_MLKEM +WOLFSSL_LOCAL int NamedGroupIsPqc(int group); +WOLFSSL_LOCAL int NamedGroupIsPqcHybrid(int group); +#define WOLFSSL_NAMED_GROUP_IS_PQC(group) NamedGroupIsPqc(group) +#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) NamedGroupIsPqcHybrid(group) #else -#define WOLFSSL_NAMED_GROUP_IS_PQC(group) ((void)(group), 0) -#endif /* WOLFSSL_HAVE_KYBER */ +#define WOLFSSL_NAMED_GROUP_IS_PQC(group) ((void)(group), 0) +#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) ((void)(group), 0) +#endif /* WOLFSSL_HAVE_MLKEM */ /* minimum Downgrade Minor version */ #ifndef WOLFSSL_MIN_DOWNGRADE @@ -2207,7 +2222,7 @@ WOLFSSL_LOCAL int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, WOLFSSL_LOCAL int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size, word32 totalSz, int sniff); #endif -WOLFSSL_LOCAL int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, +WOLFSSL_TEST_VIS int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff); /* TLS v1.3 needs these */ WOLFSSL_LOCAL int HandleTlsResumption(WOLFSSL* ssl, Suites* clSuites); @@ -2420,8 +2435,7 @@ typedef struct CipherSuite { #endif } CipherSuite; -/* use wolfSSL_API visibility to be able to test in tests/api.c */ -WOLFSSL_API void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have, +WOLFSSL_TEST_VIS void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have, int tls1_2, int keySz, word16* len); WOLFSSL_LOCAL int AllocateCtxSuites(WOLFSSL_CTX* ctx); WOLFSSL_LOCAL int AllocateSuites(WOLFSSL* ssl); @@ -2622,6 +2636,9 @@ struct WOLFSSL_CRL { THREAD_TYPE tid; /* monitoring thread */ wolfSSL_CRL_mfd_t mfd; int setup; /* thread is setup predicate */ +#endif +#ifdef OPENSSL_ALL + wolfSSL_Ref ref; #endif void* heap; /* heap hint for dynamic memory */ }; @@ -3099,6 +3116,7 @@ typedef struct RpkState { #endif /* HAVE_RPK */ #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) +#define ECH_ACCEPT_CONFIRMATION_SZ 8 typedef enum { ECH_TYPE_OUTER = 0, @@ -3133,11 +3151,13 @@ typedef struct WOLFSSL_EchConfig { typedef struct WOLFSSL_ECH { Hpke* hpke; + HpkeBaseContext* hpkeContext; const byte* aad; void* ephemeralKey; WOLFSSL_EchConfig* echConfig; byte* innerClientHello; byte* outerClientPayload; + byte* confBuf; EchCipherSuite cipherSuite; word16 aadLen; word16 paddingLen; @@ -3148,12 +3168,17 @@ typedef struct WOLFSSL_ECH { byte type; byte configId; byte enc[HPKE_Npk_MAX]; + byte innerCount; } WOLFSSL_ECH; WOLFSSL_LOCAL int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config); WOLFSSL_LOCAL int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen); + +WOLFSSL_LOCAL int SetEchConfigsEx(WOLFSSL_EchConfig** outputConfigs, void* heap, + const byte* echConfigs, word32 echConfigsLen); + WOLFSSL_LOCAL int GetEchConfig(WOLFSSL_EchConfig* config, byte* output, word32* outputLen); @@ -3368,9 +3393,9 @@ WOLFSSL_LOCAL int TLSX_CSR2_ForceRequest(WOLFSSL* ssl); #endif #if defined(WOLFSSL_PUBLIC_ASN) && defined(HAVE_PK_CALLBACKS) -/* Internal callback guarded by WOLFSSL_PUBLIC_ASN because of DecodedCert. */ +/* Internal callback guarded by WOLFSSL_TEST_VIS because of DecodedCert. */ typedef int (*CallbackProcessPeerCert)(WOLFSSL* ssl, DecodedCert* p_cert); -WOLFSSL_API void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx, +WOLFSSL_TEST_VIS void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx, CallbackProcessPeerCert cb); #endif /* DecodedCert && HAVE_PK_CALLBACKS */ @@ -3589,9 +3614,9 @@ typedef struct KeyShareEntry { word32 keyLen; /* Key size (bytes) */ byte* pubKey; /* Public key */ word32 pubKeyLen; /* Public key length */ -#if !defined(NO_DH) || defined(WOLFSSL_HAVE_KYBER) - byte* privKey; /* Private key - DH and PQ KEMs only */ - word32 privKeyLen;/* Only for PQ KEMs. */ +#if !defined(NO_DH) || defined(WOLFSSL_HAVE_MLKEM) + byte* privKey; /* Private key */ + word32 privKeyLen;/* Private key length - PQC only */ #endif #ifdef WOLFSSL_ASYNC_CRYPT int lastRet; @@ -4143,6 +4168,8 @@ struct WOLFSSL_CTX { CallbackGenPreMaster GenPreMasterCb; /* User generate master secret handler */ CallbackGenMasterSecret GenMasterCb; + /* User generate Extended master secret handler */ + CallbackGenExtMasterSecret GenExtMasterCb; /* User generate session key handler */ CallbackGenSessionKey GenSessionKeyCb; /* User setting encrypt keys handler */ @@ -4672,8 +4699,7 @@ WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSession( WOLFSSL* ssl, byte* masterSecret, byte restoreSessionCerts); WOLFSSL_LOCAL void SetupSession(WOLFSSL* ssl); WOLFSSL_LOCAL void AddSession(WOLFSSL* ssl); -/* use wolfSSL_API visibility to be able to test in tests/api.c */ -WOLFSSL_API int AddSessionToCache(WOLFSSL_CTX* ctx, +WOLFSSL_TEST_VIS int AddSessionToCache(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* addSession, const byte* id, byte idSz, int* sessionIndex, int side, word16 useTicket, ClientSession** clientCacheEntry); #ifndef NO_CLIENT_CACHE @@ -4689,8 +4715,7 @@ WOLFSSL_LOCAL int TlsSessionCacheGetAndRdLock(const byte *id, WOLFSSL_LOCAL int TlsSessionCacheGetAndWrLock(const byte *id, WOLFSSL_SESSION **sess, word32 *lockedRow, byte side); WOLFSSL_LOCAL void EvictSessionFromCache(WOLFSSL_SESSION* session); -/* WOLFSSL_API to test it in tests/api.c */ -WOLFSSL_API int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output); +WOLFSSL_TEST_VIS int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output); WOLFSSL_LOCAL int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session); WOLFSSL_LOCAL void wolfSSL_FreeSession(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session); @@ -4799,9 +4824,9 @@ typedef struct Buffers { buffer clearOutputBuffer; buffer sig; /* signature data */ buffer digest; /* digest data */ - int prevSent; /* previous plain text bytes sent + word32 prevSent; /* previous plain text bytes sent when got WANT_WRITE */ - int plainSz; /* plain text bytes in buffer to send + word32 plainSz; /* plain text bytes in buffer to send when got WANT_WRITE */ byte weOwnCert; /* SSL own cert flag */ byte weOwnCertChain; /* SSL own cert chain flag */ @@ -5072,7 +5097,8 @@ struct Options { word16 useDtlsCID:1; #endif /* WOLFSSL_DTLS_CID */ #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) - word16 useEch:1; /* Do we have a valid config */ + word16 useEch:1; + word16 echAccepted:1; byte disableECH:1; /* Did the user disable ech */ #endif #ifdef WOLFSSL_SEND_HRR_COOKIE @@ -5385,6 +5411,7 @@ struct WOLFSSL_X509 { byte keyUsageCrit:1; byte extKeyUsageCrit:1; byte subjKeyIdSet:1; + byte pathLengthSet:1; byte subjKeyIdCrit:1; byte basicConstSet:1; @@ -5437,6 +5464,10 @@ struct WOLFSSL_X509 { /* Alternative Signature Value */ byte *altSigValDer; int altSigValLen; + + byte sapkiCrit:1; + byte altSigAlgCrit:1; + byte altSigValCrit:1; #endif /* WOLFSSL_DUAL_ALG_CERTS */ }; @@ -5780,16 +5811,16 @@ struct WOLFSSL { WOLFSSL_CTX* initial_ctx; /* preserve session key materials */ #endif Suites* suites; /* Only need during handshake. Can be NULL when - * re-using the context's object. When WOLFSSL + * reusing the context's object. When WOLFSSL * object needs separate instance of suites use * AllocateSuites(). */ -#ifdef OPENSSL_EXTRA - const Suites* clSuites; -#endif + Suites* clSuites; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) WOLF_STACK_OF(WOLFSSL_CIPHER)* suitesStack; /* stack of available cipher * suites */ + WOLF_STACK_OF(WOLFSSL_CIPHER)* clSuitesStack; /* stack of client cipher + * suites */ #endif Arrays* arrays; #ifdef WOLFSSL_TLS13 @@ -5799,6 +5830,7 @@ struct WOLFSSL { HS_Hashes* hsHashes; #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) HS_Hashes* hsHashesEch; + HS_Hashes* hsHashesEchInner; #endif void* IOCB_ReadCtx; void* IOCB_WriteCtx; @@ -6118,12 +6150,10 @@ struct WOLFSSL { void* ocspIOCtx; byte ocspProducedDate[MAX_DATE_SZ]; int ocspProducedDateFormat; - #ifdef OPENSSL_EXTRA + #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) byte* ocspResp; int ocspRespSz; - #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) - char* url; - #endif + char* url; #endif #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST) word32 response_idx; @@ -6190,6 +6220,7 @@ struct WOLFSSL { #endif /* NO_RSA */ void* GenPreMasterCtx; /* Generate Premaster Callback Context */ void* GenMasterCtx; /* Generate Master Callback Context */ + void* GenExtMasterCtx; /* Generate Extended Master Callback Context */ void* GenSessionKeyCtx; /* Generate Session Key Callback Context */ void* EncryptKeysCtx; /* Set Encrypt keys Callback Context */ void* TlsFinishedCtx; /* Generate Tls Finished Callback Context */ @@ -6224,6 +6255,7 @@ struct WOLFSSL { #if defined(OPENSSL_EXTRA) WOLFSSL_STACK* supportedCiphers; /* Used in wolfSSL_get_ciphers_compat */ WOLFSSL_STACK* peerCertChain; /* Used in wolfSSL_get_peer_cert_chain */ + WOLFSSL_STACK* verifiedChain; /* peer cert chain to CA */ #ifdef KEEP_OUR_CERT WOLFSSL_STACK* ourCertChain; /* Used in wolfSSL_add1_chain_cert */ #endif @@ -6347,7 +6379,7 @@ WOLFSSL_LOCAL int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL int ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup); WOLFSSL_LOCAL void FreeSSL(WOLFSSL* ssl, void* heap); -WOLFSSL_API void wolfSSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ +WOLFSSL_TEST_VIS void wolfSSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ #ifndef OPENSSL_COEXIST #define SSL_ResourceFree wolfSSL_ResourceFree #endif @@ -6496,7 +6528,7 @@ WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk, WOLFSSL_LOCAL int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len); #endif /* HAVE_SESSION_TICKET */ -WOLFSSL_LOCAL int SendData(WOLFSSL* ssl, const void* data, int sz); +WOLFSSL_LOCAL int SendData(WOLFSSL* ssl, const void* data, size_t sz); #ifdef WOLFSSL_THREADED_CRYPT WOLFSSL_LOCAL int SendAsyncData(WOLFSSL* ssl); #endif @@ -6517,7 +6549,7 @@ WOLFSSL_LOCAL int SendHelloRequest(WOLFSSL* ssl); WOLFSSL_LOCAL int SendCertificateStatus(WOLFSSL* ssl); WOLFSSL_LOCAL int SendServerKeyExchange(WOLFSSL* ssl); WOLFSSL_LOCAL int SendBuffered(WOLFSSL* ssl); -WOLFSSL_LOCAL int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek); +WOLFSSL_LOCAL int ReceiveData(WOLFSSL* ssl, byte* output, size_t sz, int peek); WOLFSSL_LOCAL int SendFinished(WOLFSSL* ssl); WOLFSSL_LOCAL int RetrySendAlert(WOLFSSL* ssl); WOLFSSL_LOCAL int SendAlert(WOLFSSL* ssl, int severity, int type); @@ -6713,18 +6745,15 @@ WOLFSSL_LOCAL word32 MacSize(const WOLFSSL* ssl); #ifdef WOLFSSL_DTLS WOLFSSL_LOCAL DtlsMsg* DtlsMsgNew(word32 sz, byte tx, void* heap); WOLFSSL_LOCAL void DtlsMsgDelete(DtlsMsg* item, void* heap); - /* Use WOLFSSL_API to enable src/api.c testing */ - WOLFSSL_API void DtlsMsgListDelete(DtlsMsg* head, void* heap); + WOLFSSL_TEST_VIS void DtlsMsgListDelete(DtlsMsg* head, void* heap); WOLFSSL_LOCAL void DtlsTxMsgListClean(WOLFSSL* ssl); WOLFSSL_LOCAL int DtlsMsgSet(DtlsMsg* msg, word32 seq, word16 epoch, const byte* data, byte type, word32 fragOffset, word32 fragSz, void* heap, word32 totalLen, byte encrypted); - /* Use WOLFSSL_API to enable src/api.c testing */ - WOLFSSL_API DtlsMsg* DtlsMsgFind(DtlsMsg* head, word16 epoch, word32 seq); + WOLFSSL_TEST_VIS DtlsMsg* DtlsMsgFind(DtlsMsg* head, word16 epoch, word32 seq); - /* Use WOLFSSL_API to enable src/api.c testing */ - WOLFSSL_API void DtlsMsgStore(WOLFSSL* ssl, word16 epoch, word32 seq, + WOLFSSL_TEST_VIS void DtlsMsgStore(WOLFSSL* ssl, word16 epoch, word32 seq, const byte* data, word32 dataSz, byte type, word32 fragOffset, word32 fragSz, void* heap); @@ -6914,8 +6943,7 @@ WOLFSSL_LOCAL int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, int sizeOnly, int asyncOkay, int epochOrder); #ifdef WOLFSSL_TLS13 -/* Use WOLFSSL_API to use this function in tests/api.c */ -WOLFSSL_API int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, +WOLFSSL_TEST_VIS int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay); WOLFSSL_LOCAL int Tls13UpdateKeys(WOLFSSL* ssl); #endif @@ -6972,7 +7000,7 @@ WOLFSSL_LOCAL word32 nid2oid(int nid, int grp); #endif #ifdef WOLFSSL_DTLS -WOLFSSL_API int wolfSSL_DtlsUpdateWindow(word16 cur_hi, word32 cur_lo, +WOLFSSL_TEST_VIS int wolfSSL_DtlsUpdateWindow(word16 cur_hi, word32 cur_lo, word16* next_hi, word32* next_lo, word32 *window); WOLFSSL_LOCAL int DtlsUpdateWindow(WOLFSSL* ssl); WOLFSSL_LOCAL void DtlsResetState(WOLFSSL *ssl); @@ -6982,8 +7010,7 @@ WOLFSSL_LOCAL void DtlsSetSeqNumForReply(WOLFSSL* ssl); #ifdef WOLFSSL_DTLS13 -/* Use WOLFSSL_API to use this function in tests/api.c */ -WOLFSSL_API struct Dtls13Epoch* Dtls13GetEpoch(WOLFSSL* ssl, +WOLFSSL_TEST_VIS struct Dtls13Epoch* Dtls13GetEpoch(WOLFSSL* ssl, w64wrapper epochNumber); WOLFSSL_LOCAL void Dtls13SetOlderEpochSide(WOLFSSL* ssl, w64wrapper epochNumber, int side); @@ -7019,6 +7046,7 @@ WOLFSSL_LOCAL int Dtls13HandshakeSend(WOLFSSL* ssl, byte* output, word16 output_size, word16 length, enum HandShakeType handshake_type, int hash_output); WOLFSSL_LOCAL int Dtls13RecordRecvd(WOLFSSL* ssl); +WOLFSSL_TEST_VIS int Dtls13CheckEpoch(WOLFSSL* ssl, enum HandShakeType type); WOLFSSL_LOCAL int Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz); WOLFSSL_LOCAL int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output, @@ -7032,7 +7060,10 @@ WOLFSSL_LOCAL int Dtls13ReconstructEpochNumber(WOLFSSL* ssl, byte epochBits, w64wrapper* epoch); WOLFSSL_LOCAL int Dtls13ReconstructSeqNumber(WOLFSSL* ssl, Dtls13UnifiedHdrInfo* hdrInfo, w64wrapper* out); +WOLFSSL_TEST_VIS int Dtls13WriteAckMessage(WOLFSSL* ssl, + Dtls13RecordNumber* recordNumberList, word32* length); WOLFSSL_LOCAL int SendDtls13Ack(WOLFSSL* ssl); +WOLFSSL_TEST_VIS int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq); WOLFSSL_LOCAL int Dtls13RtxProcessingCertificate(WOLFSSL* ssl, byte* input, word32 inputSize); WOLFSSL_LOCAL int Dtls13HashHandshake(WOLFSSL* ssl, const byte* input, @@ -7073,9 +7104,8 @@ typedef struct CRYPTO_EX_cb_ctx { struct CRYPTO_EX_cb_ctx* next; } CRYPTO_EX_cb_ctx; -/* use wolfSSL_API visibility to be able to clear in tests/api.c */ -WOLFSSL_API extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session; -WOLFSSL_API void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx); +WOLFSSL_TEST_VIS extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session; +WOLFSSL_TEST_VIS void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx); WOLFSSL_LOCAL void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx, WOLFSSL_CRYPTO_EX_DATA* ex_data); WOLFSSL_LOCAL void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx, @@ -7157,6 +7187,7 @@ WOLFSSL_LOCAL int TranslateErrorToAlert(int err); #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) WOLFSSL_LOCAL void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk, WOLF_STACK_TYPE type); +WOLFSSL_LOCAL void* wolfSSL_sk_pop_node(WOLFSSL_STACK* sk, int idx); WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type); WOLFSSL_LOCAL int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj, diff --git a/src/wolfssl/ocsp.h b/src/wolfssl/ocsp.h index f2e234f..69b5c14 100644 --- a/src/wolfssl/ocsp.h +++ b/src/wolfssl/ocsp.h @@ -1,6 +1,6 @@ /* ocsp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/aes.h b/src/wolfssl/openssl/aes.h index 25110c8..4710f72 100644 --- a/src/wolfssl/openssl/aes.h +++ b/src/wolfssl/openssl/aes.h @@ -1,6 +1,6 @@ /* aes.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/asn1.h b/src/wolfssl/openssl/asn1.h index 5b4f25a..b9e2c19 100644 --- a/src/wolfssl/openssl/asn1.h +++ b/src/wolfssl/openssl/asn1.h @@ -1,6 +1,6 @@ /* asn1.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -39,6 +39,7 @@ #define d2i_ASN1_OBJECT wolfSSL_d2i_ASN1_OBJECT #define c2i_ASN1_OBJECT wolfSSL_c2i_ASN1_OBJECT +#define V_ASN1_BIT_STRING WOLFSSL_V_ASN1_BIT_STRING #define V_ASN1_INTEGER WOLFSSL_V_ASN1_INTEGER #define V_ASN1_NEG WOLFSSL_V_ASN1_NEG #define V_ASN1_NEG_INTEGER WOLFSSL_V_ASN1_NEG_INTEGER @@ -218,11 +219,11 @@ typedef struct WOLFSSL_ASN1_ITEM WOLFSSL_ASN1_ITEM; mtype##_member_data, \ sizeof(mtype##_member_data) / sizeof(WOLFSSL_ASN1_TEMPLATE), \ sizeof(mtype) ,\ - OFFSETOF(mtype, type) \ + WC_OFFSETOF(mtype, type) \ }; #define ASN1_TYPE(type, member, tag, first_byte, exp, seq) \ - OFFSETOF(type, member), tag, first_byte, exp, seq + WC_OFFSETOF(type, member), tag, first_byte, exp, seq /* Function callbacks need to be defined immediately otherwise we will * incorrectly expand the type. Ex: ASN1_INTEGER -> WOLFSSL_ASN1_INTEGER */ diff --git a/src/wolfssl/openssl/asn1t.h b/src/wolfssl/openssl/asn1t.h index e74ee26..2a52b3b 100644 --- a/src/wolfssl/openssl/asn1t.h +++ b/src/wolfssl/openssl/asn1t.h @@ -1,6 +1,6 @@ /* asn1t.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/bio.h b/src/wolfssl/openssl/bio.h index cf6571b..73214ab 100644 --- a/src/wolfssl/openssl/bio.h +++ b/src/wolfssl/openssl/bio.h @@ -1,6 +1,6 @@ /* bio.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -104,6 +104,7 @@ #endif #define BIO_int_ctrl wolfSSL_BIO_int_ctrl #define BIO_reset wolfSSL_BIO_reset +#define BIO_s_null wolfSSL_BIO_s_null #define BIO_s_file wolfSSL_BIO_s_file #define BIO_s_bio wolfSSL_BIO_s_bio #define BIO_s_socket wolfSSL_BIO_s_socket diff --git a/src/wolfssl/openssl/bn.h b/src/wolfssl/openssl/bn.h index ed8ae43..45411f5 100644 --- a/src/wolfssl/openssl/bn.h +++ b/src/wolfssl/openssl/bn.h @@ -1,6 +1,6 @@ /* bn.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -40,7 +40,7 @@ typedef struct WOLFSSL_BIGNUM { int neg; /* openssh deference */ void *internal; /* our big num */ -#if !defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH) +#if !defined(NO_BIG_INT) mp_int mpi; #endif } WOLFSSL_BIGNUM; @@ -77,8 +77,15 @@ typedef struct WOLFSSL_BIGNUM { #define WOLFSSL_BN_MAX_VAL ((BN_ULONG)-1) -typedef struct WOLFSSL_BN_CTX WOLFSSL_BN_CTX; -typedef struct WOLFSSL_BN_GENCB WOLFSSL_BN_GENCB; +struct WOLFSSL_BN_CTX_LIST { + WOLFSSL_BIGNUM* bn; + struct WOLFSSL_BN_CTX_LIST* next; +}; +typedef struct WOLFSSL_BN_CTX { + struct WOLFSSL_BN_CTX_LIST* list; +} WOLFSSL_BN_CTX; +typedef struct WOLFSSL_BN_MONT_CTX WOLFSSL_BN_MONT_CTX; +typedef struct WOLFSSL_BN_GENCB WOLFSSL_BN_GENCB; WOLFSSL_API WOLFSSL_BN_CTX* wolfSSL_BN_CTX_new(void); WOLFSSL_API void wolfSSL_BN_CTX_init(WOLFSSL_BN_CTX* ctx); @@ -151,6 +158,7 @@ WOLFSSL_API int wolfSSL_BN_lshift(WOLFSSL_BIGNUM* r, const WOLFSSL_BIGNUM* bn, WOLFSSL_API int wolfSSL_BN_add_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_sub_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_mul_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w); +WOLFSSL_API int wolfSSL_BN_div_word(WOLFSSL_BIGNUM *bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_set_bit(WOLFSSL_BIGNUM* bn, int n); WOLFSSL_API int wolfSSL_BN_clear_bit(WOLFSSL_BIGNUM* bn, int n); WOLFSSL_API int wolfSSL_BN_set_word(WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); @@ -184,6 +192,13 @@ WOLFSSL_API WOLFSSL_BIGNUM *wolfSSL_BN_mod_inverse( const WOLFSSL_BIGNUM *n, WOLFSSL_BN_CTX *ctx); +WOLFSSL_API WOLFSSL_BN_MONT_CTX* wolfSSL_BN_MONT_CTX_new(void); +WOLFSSL_API void wolfSSL_BN_MONT_CTX_free(WOLFSSL_BN_MONT_CTX *mont); +WOLFSSL_API int wolfSSL_BN_MONT_CTX_set(WOLFSSL_BN_MONT_CTX *mont, + const WOLFSSL_BIGNUM *mod, WOLFSSL_BN_CTX *ctx); +WOLFSSL_API int wolfSSL_BN_mod_exp_mont_word(WOLFSSL_BIGNUM *r, + WOLFSSL_BN_ULONG a, const WOLFSSL_BIGNUM *p, const WOLFSSL_BIGNUM *m, + WOLFSSL_BN_CTX *ctx, WOLFSSL_BN_MONT_CTX *mont); #if !defined(OPENSSL_COEXIST) && (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) @@ -194,13 +209,19 @@ WOLFSSL_API WOLFSSL_BIGNUM *wolfSSL_BN_mod_inverse( #define BN_RAND_BOTTOM_ANY WOLFSSL_BN_RAND_BOTTOM_ANY #define BN_RAND_BOTTOM_ODD WOLFSSL_BN_RAND_BOTTOM_ODD -typedef WOLFSSL_BIGNUM BIGNUM; -typedef WOLFSSL_BN_CTX BN_CTX; -typedef WOLFSSL_BN_GENCB BN_GENCB; +typedef WOLFSSL_BIGNUM BIGNUM; +typedef WOLFSSL_BN_CTX BN_CTX; +typedef WOLFSSL_BN_MONT_CTX BN_MONT_CTX; +typedef WOLFSSL_BN_GENCB BN_GENCB; +#ifndef NO_WOLFSSL_BN_CTX #define BN_CTX_new wolfSSL_BN_CTX_new #define BN_CTX_init wolfSSL_BN_CTX_init #define BN_CTX_free wolfSSL_BN_CTX_free +#else +#define BN_CTX_new() ((BN_CTX*)-1) +#define BN_CTX_free(x) ((void)(x)) +#endif #define BN_new wolfSSL_BN_new #if !defined(USE_INTEGER_HEAP_MATH) && !defined(HAVE_WOLF_BIGINT) @@ -228,6 +249,8 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_mod wolfSSL_BN_mod #define BN_mod_exp wolfSSL_BN_mod_exp +#define BN_mod_exp_mont(a,b,c,d,e,f) \ + ((void)(f), wolfSSL_BN_mod_exp((a),(b),(c),(d),(e))) #define BN_mod_mul wolfSSL_BN_mod_mul #define BN_sub wolfSSL_BN_sub #define BN_mul wolfSSL_BN_mul @@ -257,6 +280,7 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_add_word wolfSSL_BN_add_word #define BN_mul_word wolfSSL_BN_mul_word #define BN_sub_word wolfSSL_BN_sub_word +#define BN_div_word wolfSSL_BN_div_word #define BN_add wolfSSL_BN_add #define BN_mod_add wolfSSL_BN_mod_add #define BN_set_word wolfSSL_BN_set_word @@ -290,6 +314,11 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_prime_checks 0 +#define BN_MONT_CTX_new wolfSSL_BN_MONT_CTX_new +#define BN_MONT_CTX_free wolfSSL_BN_MONT_CTX_free +#define BN_MONT_CTX_set wolfSSL_BN_MONT_CTX_set +#define BN_mod_exp_mont_word wolfSSL_BN_mod_exp_mont_word + #endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ diff --git a/src/wolfssl/openssl/buffer.h b/src/wolfssl/openssl/buffer.h index c4195cf..548d744 100644 --- a/src/wolfssl/openssl/buffer.h +++ b/src/wolfssl/openssl/buffer.h @@ -1,6 +1,6 @@ /* buffer.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/camellia.h b/src/wolfssl/openssl/camellia.h index 0cad9c9..fe5b17c 100644 --- a/src/wolfssl/openssl/camellia.h +++ b/src/wolfssl/openssl/camellia.h @@ -1,6 +1,6 @@ /* camellia.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/cmac.h b/src/wolfssl/openssl/cmac.h index 120fd1d..489396c 100644 --- a/src/wolfssl/openssl/cmac.h +++ b/src/wolfssl/openssl/cmac.h @@ -1,6 +1,6 @@ /* cmac.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/cms.h b/src/wolfssl/openssl/cms.h index 7febb67..291c08d 100644 --- a/src/wolfssl/openssl/cms.h +++ b/src/wolfssl/openssl/cms.h @@ -1,6 +1,6 @@ /* cms.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/compat_types.h b/src/wolfssl/openssl/compat_types.h index 00bfde1..58113c4 100644 --- a/src/wolfssl/openssl/compat_types.h +++ b/src/wolfssl/openssl/compat_types.h @@ -1,6 +1,6 @@ /* compat_types.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/conf.h b/src/wolfssl/openssl/conf.h index 411a3e0..d2e2eb4 100644 --- a/src/wolfssl/openssl/conf.h +++ b/src/wolfssl/openssl/conf.h @@ -1,6 +1,6 @@ /* conf.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/crypto.h b/src/wolfssl/openssl/crypto.h index 33a279a..e05468e 100644 --- a/src/wolfssl/openssl/crypto.h +++ b/src/wolfssl/openssl/crypto.h @@ -1,6 +1,6 @@ /* crypto.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/des.h b/src/wolfssl/openssl/des.h index 6db0df7..9554c2a 100644 --- a/src/wolfssl/openssl/des.h +++ b/src/wolfssl/openssl/des.h @@ -1,6 +1,6 @@ /* des.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/dh.h b/src/wolfssl/openssl/dh.h index 60fe59f..70b1087 100644 --- a/src/wolfssl/openssl/dh.h +++ b/src/wolfssl/openssl/dh.h @@ -1,6 +1,6 @@ /* dh.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/dsa.h b/src/wolfssl/openssl/dsa.h index 1d24ceb..d5f64bb 100644 --- a/src/wolfssl/openssl/dsa.h +++ b/src/wolfssl/openssl/dsa.h @@ -1,6 +1,6 @@ /* dsa.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ec.h b/src/wolfssl/openssl/ec.h index 4067cff..d68217b 100644 --- a/src/wolfssl/openssl/ec.h +++ b/src/wolfssl/openssl/ec.h @@ -1,6 +1,6 @@ /* ec.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ec25519.h b/src/wolfssl/openssl/ec25519.h index 0421ce8..92cf807 100644 --- a/src/wolfssl/openssl/ec25519.h +++ b/src/wolfssl/openssl/ec25519.h @@ -1,6 +1,6 @@ /* ec25519.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ec448.h b/src/wolfssl/openssl/ec448.h index 89a9e1c..ce2cc7c 100644 --- a/src/wolfssl/openssl/ec448.h +++ b/src/wolfssl/openssl/ec448.h @@ -1,6 +1,6 @@ /* ec448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ecdh.h b/src/wolfssl/openssl/ecdh.h index 74b8c91..7fbc5a3 100644 --- a/src/wolfssl/openssl/ecdh.h +++ b/src/wolfssl/openssl/ecdh.h @@ -1,6 +1,6 @@ /* ecdh.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ecdsa.h b/src/wolfssl/openssl/ecdsa.h index f9ba1ec..12d003f 100644 --- a/src/wolfssl/openssl/ecdsa.h +++ b/src/wolfssl/openssl/ecdsa.h @@ -1,6 +1,6 @@ /* ecdsa.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ed25519.h b/src/wolfssl/openssl/ed25519.h index d4c1b1b..9d67c6f 100644 --- a/src/wolfssl/openssl/ed25519.h +++ b/src/wolfssl/openssl/ed25519.h @@ -1,6 +1,6 @@ /* ed25519.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ed448.h b/src/wolfssl/openssl/ed448.h index 3c97862..793e66f 100644 --- a/src/wolfssl/openssl/ed448.h +++ b/src/wolfssl/openssl/ed448.h @@ -1,6 +1,6 @@ /* ed448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/err.h b/src/wolfssl/openssl/err.h index 708498a..6723ded 100644 --- a/src/wolfssl/openssl/err.h +++ b/src/wolfssl/openssl/err.h @@ -1,6 +1,6 @@ /* err.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/evp.h b/src/wolfssl/openssl/evp.h index 02b5c8b..3192dbf 100644 --- a/src/wolfssl/openssl/evp.h +++ b/src/wolfssl/openssl/evp.h @@ -1,6 +1,6 @@ /* evp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -221,6 +221,9 @@ typedef union { #ifdef WOLFSSL_SM3 wc_Sm3 sm3; #endif + #if defined(WOLFSSL_SHAKE128) || defined(WOLFSSL_SHAKE256) + wc_Shake shake; + #endif } WOLFSSL_Hasher; @@ -798,6 +801,7 @@ WOLFSSL_API const WOLFSSL_EVP_MD* wolfSSL_EVP_blake2s256(void); WOLFSSL_API void wolfSSL_EVP_init(void); WOLFSSL_API int wolfSSL_EVP_MD_size(const WOLFSSL_EVP_MD* type); WOLFSSL_API int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type); +WOLFSSL_API unsigned long wolfSSL_EVP_MD_flags(const WOLFSSL_EVP_MD *md); WOLFSSL_API int wolfSSL_EVP_MD_block_size(const WOLFSSL_EVP_MD* type); WOLFSSL_API int wolfSSL_EVP_MD_pkey_type(const WOLFSSL_EVP_MD* type); @@ -823,6 +827,8 @@ WOLFSSL_API int wolfSSL_EVP_DigestFinal(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* unsigned int* s); WOLFSSL_API int wolfSSL_EVP_DigestFinal_ex(WOLFSSL_EVP_MD_CTX* ctx, unsigned char* md, unsigned int* s); +WOLFSSL_API int wolfSSL_EVP_DigestFinalXOF(WOLFSSL_EVP_MD_CTX* ctx, + unsigned char* md, size_t sz); WOLFSSL_API int wolfSSL_EVP_DigestSignUpdate(WOLFSSL_EVP_MD_CTX *ctx, const void *d, unsigned int cnt); WOLFSSL_API int wolfSSL_EVP_DigestSignFinal(WOLFSSL_EVP_MD_CTX *ctx, @@ -1096,6 +1102,7 @@ WOLFSSL_API int wolfSSL_EVP_DigestVerifyInit(WOLFSSL_EVP_MD_CTX *ctx, WOLFSSL_API int wolfSSL_EVP_Digest(const unsigned char* in, int inSz, unsigned char* out, unsigned int* outSz, const WOLFSSL_EVP_MD* evp, WOLFSSL_ENGINE* eng); +WOLFSSL_API const char* wolfSSL_EVP_CIPHER_type_string(unsigned int type); WOLFSSL_API int wolfSSL_EVP_CipherInit_ex(WOLFSSL_EVP_CIPHER_CTX* ctx, const WOLFSSL_EVP_CIPHER* type, WOLFSSL_ENGINE *impl, @@ -1144,6 +1151,7 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define WOLFSSL_EVP_CTRL_CCM_SET_TAG WOLFSSL_EVP_CTRL_AEAD_SET_TAG #define WOLFSSL_EVP_CTRL_CCM_SET_L 0x14 #define WOLFSSL_EVP_CTRL_CCM_SET_MSGLEN 0x15 +#define WOLFSSL_EVP_MD_FLAG_XOF 0x2 #define WOLFSSL_NO_PADDING_BLOCK_SIZE 1 @@ -1256,12 +1264,15 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_MD_CTX_set_flags(ctx, flags) WC_DO_NOTHING #endif +#define EVP_MD_FLAG_XOF WOLFSSL_EVP_MD_FLAG_XOF + #define EVP_Digest wolfSSL_EVP_Digest #define EVP_DigestInit wolfSSL_EVP_DigestInit #define EVP_DigestInit_ex wolfSSL_EVP_DigestInit_ex #define EVP_DigestUpdate wolfSSL_EVP_DigestUpdate #define EVP_DigestFinal wolfSSL_EVP_DigestFinal #define EVP_DigestFinal_ex wolfSSL_EVP_DigestFinal_ex +#define EVP_DigestFinalXOF wolfSSL_EVP_DigestFinalXOF #define EVP_DigestSignInit wolfSSL_EVP_DigestSignInit #define EVP_DigestSignUpdate wolfSSL_EVP_DigestSignUpdate #define EVP_DigestSignFinal wolfSSL_EVP_DigestSignFinal @@ -1311,6 +1322,7 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_get_cipherbynid wolfSSL_EVP_get_cipherbynid #define EVP_get_digestbynid wolfSSL_EVP_get_digestbynid #define EVP_MD_nid wolfSSL_EVP_MD_type +#define EVP_MD_flags wolfSSL_EVP_MD_flags #define EVP_PKEY_assign wolfSSL_EVP_PKEY_assign #define EVP_PKEY_assign_RSA wolfSSL_EVP_PKEY_assign_RSA diff --git a/src/wolfssl/openssl/fips_rand.h b/src/wolfssl/openssl/fips_rand.h index 58f21b3..4142e7e 100644 --- a/src/wolfssl/openssl/fips_rand.h +++ b/src/wolfssl/openssl/fips_rand.h @@ -1,6 +1,6 @@ /* fips_rand.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/hmac.h b/src/wolfssl/openssl/hmac.h index 1a2c304..b29d4fc 100644 --- a/src/wolfssl/openssl/hmac.h +++ b/src/wolfssl/openssl/hmac.h @@ -1,6 +1,6 @@ /* hmac.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/kdf.h b/src/wolfssl/openssl/kdf.h index 295c99f..f36aedc 100644 --- a/src/wolfssl/openssl/kdf.h +++ b/src/wolfssl/openssl/kdf.h @@ -1,6 +1,6 @@ /* kdf.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/lhash.h b/src/wolfssl/openssl/lhash.h index 4c1637a..6a86992 100644 --- a/src/wolfssl/openssl/lhash.h +++ b/src/wolfssl/openssl/lhash.h @@ -1,6 +1,6 @@ /* lhash.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/md4.h b/src/wolfssl/openssl/md4.h index 9181e8d..3d0549f 100644 --- a/src/wolfssl/openssl/md4.h +++ b/src/wolfssl/openssl/md4.h @@ -1,6 +1,6 @@ /* md4.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/md5.h b/src/wolfssl/openssl/md5.h index 452b6a4..709c03f 100644 --- a/src/wolfssl/openssl/md5.h +++ b/src/wolfssl/openssl/md5.h @@ -1,6 +1,6 @@ /* md5.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/modes.h b/src/wolfssl/openssl/modes.h index e6a584c..50342bd 100644 --- a/src/wolfssl/openssl/modes.h +++ b/src/wolfssl/openssl/modes.h @@ -1,6 +1,6 @@ /* modes.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/obj_mac.h b/src/wolfssl/openssl/obj_mac.h index b4d4013..3304158 100644 --- a/src/wolfssl/openssl/obj_mac.h +++ b/src/wolfssl/openssl/obj_mac.h @@ -1,6 +1,6 @@ /* obj_mac.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -59,6 +59,27 @@ #define NID_sect571k1 WC_NID_sect571k1 #define NID_sect571r1 WC_NID_sect571r1 +/* mapping of short names */ +#define SN_md4 WC_SN_md4 +#define SN_md5 WC_SN_md5 +#define SN_sha1 WC_SN_sha1 +#define SN_sha224 WC_SN_sha224 +#define SN_sha256 WC_SN_sha256 +#define SN_sha384 WC_SN_sha384 +#define SN_sha512 WC_SN_sha512 +#define SN_sha512_224 WC_SN_sha512_224 +#define SN_sha512_256 WC_SN_sha512_256 +#define SN_sha3_224 WC_SN_sha3_224 +#define SN_sha3_256 WC_SN_sha3_256 +#define SN_sha3_384 WC_SN_sha3_384 +#define SN_sha3_512 WC_SN_sha3_512 +#define SN_shake128 WC_SN_shake128 +#define SN_shake256 WC_SN_shake256 +#define SN_blake2s256 WC_SN_blake2s256 +#define SN_blake2s512 WC_SN_blake2s512 +#define SN_blake2b512 WC_SN_blake2b512 +#define SN_sm3 WC_SN_sm3 + #endif /* !OPENSSL_COEXIST */ /* the definition is for Qt Unit test */ diff --git a/src/wolfssl/openssl/objects.h b/src/wolfssl/openssl/objects.h index 1b6ce80..3325c83 100644 --- a/src/wolfssl/openssl/objects.h +++ b/src/wolfssl/openssl/objects.h @@ -1,6 +1,6 @@ /* objects.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,6 +29,8 @@ #include #endif /* OPENSSL_EXTRA_SSL_GUARD */ +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/wolfssl/openssl/ocsp.h b/src/wolfssl/openssl/ocsp.h index a6bae66..67ae0f1 100644 --- a/src/wolfssl/openssl/ocsp.h +++ b/src/wolfssl/openssl/ocsp.h @@ -1,6 +1,6 @@ /* ocsp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/opensslv.h b/src/wolfssl/openssl/opensslv.h index 481f74e..e643a64 100644 --- a/src/wolfssl/openssl/opensslv.h +++ b/src/wolfssl/openssl/opensslv.h @@ -1,6 +1,6 @@ /* opensslv.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ossl_typ.h b/src/wolfssl/openssl/ossl_typ.h index 8214fa3..084558d 100644 --- a/src/wolfssl/openssl/ossl_typ.h +++ b/src/wolfssl/openssl/ossl_typ.h @@ -1,6 +1,6 @@ /* ossl_typ.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/pem.h b/src/wolfssl/openssl/pem.h index 3666ab5..1cf4247 100644 --- a/src/wolfssl/openssl/pem.h +++ b/src/wolfssl/openssl/pem.h @@ -1,6 +1,6 @@ /* pem.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/pkcs12.h b/src/wolfssl/openssl/pkcs12.h index 7da2b98..a59798c 100644 --- a/src/wolfssl/openssl/pkcs12.h +++ b/src/wolfssl/openssl/pkcs12.h @@ -1,6 +1,6 @@ /* pkcs12.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/pkcs7.h b/src/wolfssl/openssl/pkcs7.h index 9a53b89..84ae285 100644 --- a/src/wolfssl/openssl/pkcs7.h +++ b/src/wolfssl/openssl/pkcs7.h @@ -1,6 +1,6 @@ /* pkcs7.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rand.h b/src/wolfssl/openssl/rand.h index 71d6810..4c41ed7 100644 --- a/src/wolfssl/openssl/rand.h +++ b/src/wolfssl/openssl/rand.h @@ -1,6 +1,6 @@ /* rand.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rc4.h b/src/wolfssl/openssl/rc4.h index fb51128..309174b 100644 --- a/src/wolfssl/openssl/rc4.h +++ b/src/wolfssl/openssl/rc4.h @@ -1,6 +1,6 @@ /* rc4.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ripemd.h b/src/wolfssl/openssl/ripemd.h index a7c4247..0e80bb3 100644 --- a/src/wolfssl/openssl/ripemd.h +++ b/src/wolfssl/openssl/ripemd.h @@ -1,6 +1,6 @@ /* ripemd.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/rsa.h b/src/wolfssl/openssl/rsa.h index c414fdf..111a89e 100644 --- a/src/wolfssl/openssl/rsa.h +++ b/src/wolfssl/openssl/rsa.h @@ -1,6 +1,6 @@ /* rsa.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/safestack.h b/src/wolfssl/openssl/safestack.h index ee1f872..e059a6e 100644 --- a/src/wolfssl/openssl/safestack.h +++ b/src/wolfssl/openssl/safestack.h @@ -1,6 +1,6 @@ /* safestack.h * - * Copyright (C) 2006-2023 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/sha.h b/src/wolfssl/openssl/sha.h index 34a1962..4644a33 100644 --- a/src/wolfssl/openssl/sha.h +++ b/src/wolfssl/openssl/sha.h @@ -1,6 +1,6 @@ /* sha.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/sha3.h b/src/wolfssl/openssl/sha3.h index c2f5535..a970bfd 100644 --- a/src/wolfssl/openssl/sha3.h +++ b/src/wolfssl/openssl/sha3.h @@ -1,6 +1,6 @@ /* sha3.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/srp.h b/src/wolfssl/openssl/srp.h index d0e6123..978e05d 100644 --- a/src/wolfssl/openssl/srp.h +++ b/src/wolfssl/openssl/srp.h @@ -1,6 +1,6 @@ /* srp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/ssl.h b/src/wolfssl/openssl/ssl.h index 959d1e6..da16168 100644 --- a/src/wolfssl/openssl/ssl.h +++ b/src/wolfssl/openssl/ssl.h @@ -1,6 +1,6 @@ /* ssl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -289,6 +289,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSLv23_client_method wolfSSLv23_client_method #define SSLv2_client_method wolfSSLv2_client_method #define SSLv2_server_method wolfSSLv2_server_method +#define SSLv3_method wolfSSLv3_method #define SSLv3_server_method wolfSSLv3_server_method #define SSLv3_client_method wolfSSLv3_client_method #define TLS_client_method wolfTLS_client_method @@ -352,7 +353,9 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_write_early_data(ssl, d, dLen, len) wolfSSL_write_early_data(ssl, d, (int)(dLen), (int *)(len)) #define SSL_write wolfSSL_write +#define SSL_write_ex wolfSSL_write_ex #define SSL_read wolfSSL_read +#define SSL_read_ex wolfSSL_read_ex #define SSL_peek wolfSSL_peek #define SSL_accept wolfSSL_accept #define SSL_CTX_free wolfSSL_CTX_free @@ -432,6 +435,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define SSL_get_version wolfSSL_get_version #define SSL_get_current_cipher wolfSSL_get_current_cipher +#define SSL_get_client_ciphers wolfSSL_get_client_ciphers /* use wolfSSL_get_cipher_name for its return format */ #define SSL_get_cipher wolfSSL_get_cipher_name @@ -461,6 +465,9 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define ASN1_BOOLEAN WOLFSSL_ASN1_BOOLEAN #define X509_get_ext wolfSSL_X509_get_ext #define X509_get_ext_by_OBJ wolfSSL_X509_get_ext_by_OBJ + #define X509_OBJECT_set1_X509 wolfSSL_X509_OBJECT_set1_X509 + #define X509_OBJECT_set1_X509_CRL wolfSSL_X509_OBJECT_set1_X509_CRL + #define sk_X509_OBJECT_deep_copy wolfSSL_sk_X509_OBJECT_deep_copy #define X509_cmp wolfSSL_X509_cmp #define X509_EXTENSION_get_object wolfSSL_X509_EXTENSION_get_object #define X509_EXTENSION_get_critical wolfSSL_X509_EXTENSION_get_critical @@ -688,6 +695,7 @@ typedef WOLFSSL_X509_NAME_ENTRY X509_NAME_ENTRY; #define X509_NAME_entry_count wolfSSL_X509_NAME_entry_count #define X509_NAME_get_entry wolfSSL_X509_NAME_get_entry +#define X509_NAME_ENTRY_set wolfSSL_X509_NAME_ENTRY_set #define X509_NAME_ENTRY_get_object wolfSSL_X509_NAME_ENTRY_get_object #define X509_NAME_ENTRY_get_data wolfSSL_X509_NAME_ENTRY_get_data #define X509_NAME_ENTRY_get_object wolfSSL_X509_NAME_ENTRY_get_object @@ -717,6 +725,9 @@ typedef WOLFSSL_X509_NAME_ENTRY X509_NAME_ENTRY; #define X509_VP_FLAG_LOCKED WOLFSSL_VPARAM_LOCKED #define X509_VP_FLAG_ONCE WOLFSSL_VPARAM_ONCE +#define X509_STORE_lock(x) 1 +#define X509_STORE_unlock(x) 1 + #define X509_STORE_CTX_get_current_cert wolfSSL_X509_STORE_CTX_get_current_cert #define X509_STORE_CTX_set_verify_cb wolfSSL_X509_STORE_CTX_set_verify_cb #define X509_STORE_CTX_new wolfSSL_X509_STORE_CTX_new @@ -779,6 +790,7 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define X509_VERIFY_PARAM_lookup wolfSSL_X509_VERIFY_PARAM_lookup #define X509_VERIFY_PARAM_inherit wolfSSL_X509_VERIFY_PARAM_inherit #define X509_STORE_load_locations wolfSSL_X509_STORE_load_locations +#define X509_STORE_set_default_paths wolfSSL_X509_STORE_set_default_paths #define X509_STORE_get0_param wolfSSL_X509_STORE_get0_param #define X509_LOOKUP_add_dir wolfSSL_X509_LOOKUP_add_dir @@ -1104,6 +1116,10 @@ wolfSSL_X509_STORE_set_verify_cb((WOLFSSL_X509_STORE *)(s), (WOLFSSL_X509_STORE_ #define SSL_CTX_set_psk_server_callback wolfSSL_CTX_set_psk_server_callback #define SSL_set_psk_server_callback wolfSSL_set_psk_server_callback +#if !defined(USE_WINDOWS_API) && !defined(INVALID_SOCKET) + #define INVALID_SOCKET (-1) +#endif + /* system file ints for ERR_put_error */ #define SYS_F_ACCEPT WOLFSSL_SYS_ACCEPT #define SYS_F_BIND WOLFSSL_SYS_BIND @@ -1430,6 +1446,11 @@ typedef WOLFSSL_SRTP_PROTECTION_PROFILE SRTP_PROTECTION_PROFILE; #define SSL3_RANDOM_SIZE 32 /* same as RAN_LEN in internal.h */ +#ifndef WOLFSSL_ALLOW_SSLV3 + #undef OPENSSL_NO_SSL3 + #define OPENSSL_NO_SSL3 +#endif + /* Used as message callback types */ #define SSL3_RT_CHANGE_CIPHER_SPEC 20 #define SSL3_RT_ALERT 21 @@ -1810,6 +1831,8 @@ typedef WOLFSSL_CONF_CTX SSL_CONF_CTX; #define SSL_CONF_cmd wolfSSL_CONF_cmd #define SSL_CONF_cmd_value_type wolfSSL_CONF_cmd_value_type +#define SSL_OP_LEGACY_SERVER_CONNECT 0 + #endif /* !OPENSSL_COEXIST && (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */ diff --git a/src/wolfssl/openssl/stack.h b/src/wolfssl/openssl/stack.h index fe697c4..16f71d3 100644 --- a/src/wolfssl/openssl/stack.h +++ b/src/wolfssl/openssl/stack.h @@ -1,6 +1,6 @@ /* stack.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/tls1.h b/src/wolfssl/openssl/tls1.h index 1f8895c..b1992fc 100644 --- a/src/wolfssl/openssl/tls1.h +++ b/src/wolfssl/openssl/tls1.h @@ -1,6 +1,6 @@ /* tls1.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/txt_db.h b/src/wolfssl/openssl/txt_db.h index b8aa56f..aa05d92 100644 --- a/src/wolfssl/openssl/txt_db.h +++ b/src/wolfssl/openssl/txt_db.h @@ -1,6 +1,6 @@ /* txt_db.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/x509.h b/src/wolfssl/openssl/x509.h index f2bfb1b..e1eb78e 100644 --- a/src/wolfssl/openssl/x509.h +++ b/src/wolfssl/openssl/x509.h @@ -1,6 +1,6 @@ /* x509.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -111,6 +111,8 @@ #define X509_V_ERR_UNABLE_TO_GET_CRL WOLFSSL_X509_V_ERR_UNABLE_TO_GET_CRL #define X509_V_ERR_CRL_HAS_EXPIRED WOLFSSL_X509_V_ERR_CRL_HAS_EXPIRED +#define X509_V_FLAG_ALLOW_PROXY_CERTS 0 +#define X509_V_FLAG_X509_STRICT 0 /* * Not all of these X509_V_ERR values are used in wolfSSL. Some are included to @@ -212,6 +214,7 @@ #define X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 93 #define X509_V_ERR_EC_KEY_EXPLICIT_PARAMS 94 #define X509_R_CERT_ALREADY_IN_HASH_TABLE 101 +#define X509_R_KEY_VALUES_MISMATCH WC_KEY_MISMATCH_E #define X509_EXTENSION_set_critical wolfSSL_X509_EXTENSION_set_critical #define X509_EXTENSION_set_object wolfSSL_X509_EXTENSION_set_object diff --git a/src/wolfssl/openssl/x509_vfy.h b/src/wolfssl/openssl/x509_vfy.h index 977e0c0..c26b94d 100644 --- a/src/wolfssl/openssl/x509_vfy.h +++ b/src/wolfssl/openssl/x509_vfy.h @@ -1,6 +1,6 @@ /* x509_vfy.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/openssl/x509v3.h b/src/wolfssl/openssl/x509v3.h index a84077d..c0ae5cc 100644 --- a/src/wolfssl/openssl/x509v3.h +++ b/src/wolfssl/openssl/x509v3.h @@ -1,6 +1,6 @@ /* x509v3.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/quic.h b/src/wolfssl/quic.h index 70ae61c..da8c50a 100644 --- a/src/wolfssl/quic.h +++ b/src/wolfssl/quic.h @@ -1,6 +1,6 @@ /* quic.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/sniffer.h b/src/wolfssl/sniffer.h index 3eabd42..929fcdc 100644 --- a/src/wolfssl/sniffer.h +++ b/src/wolfssl/sniffer.h @@ -1,6 +1,6 @@ /* sniffer.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/sniffer_error.h b/src/wolfssl/sniffer_error.h index 1794ba8..bb574b4 100644 --- a/src/wolfssl/sniffer_error.h +++ b/src/wolfssl/sniffer_error.h @@ -1,6 +1,6 @@ /* sniffer_error.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index 8b7ebed..908d5c6 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -1,6 +1,6 @@ /* ssl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -76,7 +76,7 @@ #endif #ifdef OPENSSL_ALL - #ifndef WOLFSSL_HAVE_BIO_ADDR + #if !defined(WOLFSSL_HAVE_BIO_ADDR) && !defined(WOLFSSL_NO_SOCK) #define WOLFSSL_HAVE_BIO_ADDR #endif #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DTLS_MTU) @@ -117,7 +117,6 @@ #include #include #include - #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \ FIPS_VERSION3_GE(5,2,0)) #include @@ -125,24 +124,15 @@ #include #include #include - #include #include #include - #include - #include #include #include #include #include #include - #include #include - #include - #include - #include #include - #include - #include #include #include #include @@ -152,26 +142,21 @@ #include #include #include - #include - #include #include #include #include #include - #include - #include #include #include #include #include #include #include - #if defined(HAVE_FIPS_VERSION) && FIPS_VERSION3_LT(7,0,0) + #if defined(HAVE_FIPS_VERSION) && FIPS_VERSION3_LT(6,0,0) /* clear conflicting name */ #undef RSA_PKCS1_PADDING_SIZE #endif #include - #include #include #include #include @@ -180,6 +165,26 @@ #include #include #include + + #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x30000000L + #include + #include + #include + #include + #include + #include + #include + #if OPENSSL_VERSION_NUMBER >= 0x30200000L + #include + #endif + #include + #include + #include + #include + #include + #include + #endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L */ + #endif /* !HAVE_SELFTEST && (!HAVE_FIPS || FIPS_VERSION3_GE(5,2,0)) */ #endif @@ -327,6 +332,7 @@ typedef int (*WOLFSSL_X509_STORE_CTX_get_crl_cb)(WOLFSSL_X509_STORE_CTX *, typedef int (*WOLFSSL_X509_STORE_CTX_check_crl_cb)(WOLFSSL_X509_STORE_CTX *, WOLFSSL_X509_CRL *); +#define WOLFSSL_V_ASN1_BIT_STRING 0x03 #define WOLFSSL_V_ASN1_INTEGER 0x02 #define WOLFSSL_V_ASN1_NEG 0x100 #define WOLFSSL_V_ASN1_NEG_INTEGER (2 | WOLFSSL_V_ASN1_NEG) @@ -603,7 +609,7 @@ struct WOLFSSL_EVP_PKEY { typedef struct WOLFSSL_BUFFER_INFO { unsigned char* buffer; - unsigned int length; + word32 length; } WOLFSSL_BUFFER_INFO; typedef struct WOLFSSL_BUF_MEM { @@ -706,7 +712,8 @@ enum BIO_TYPE { WOLFSSL_BIO_FILE = 6, WOLFSSL_BIO_BASE64 = 7, WOLFSSL_BIO_MD = 8, - WOLFSSL_BIO_DGRAM = 9 + WOLFSSL_BIO_DGRAM = 9, + WOLFSSL_BIO_NULL = 10 }; enum BIO_FLAGS { @@ -903,7 +910,7 @@ typedef struct WOLFSSL_ALERT_HISTORY { /* Valid Alert types from page 16/17 - * Add alert string to the function wolfSSL_alert_type_string_long in src/ssl.c + * Add alert string to the function AlertTypeToString in src/ssl.c */ enum AlertDescription { invalid_alert = -1, @@ -1174,6 +1181,12 @@ WOLFSSL_API WOLFSSL_METHOD *wolfSSLv23_method(void); WOLFSSL_API int wolfSSL_CTX_GenerateEchConfig(WOLFSSL_CTX* ctx, const char* publicName, word16 kemId, word16 kdfId, word16 aeadId); +WOLFSSL_API int wolfSSL_CTX_SetEchConfigsBase64(WOLFSSL_CTX* ctx, + const char* echConfigs64, word32 echConfigs64Len); + +WOLFSSL_API int wolfSSL_CTX_SetEchConfigs(WOLFSSL_CTX* ctx, + const byte* echConfigs, word32 echConfigsLen); + WOLFSSL_API int wolfSSL_CTX_GetEchConfigs(WOLFSSL_CTX* ctx, byte* output, word32* outputLen); @@ -1364,7 +1377,10 @@ WOLFSSL_API int wolfSSL_get_wfd(const WOLFSSL* ssl); WOLFSSL_ABI WOLFSSL_API int wolfSSL_connect(WOLFSSL* ssl); WOLFSSL_ABI WOLFSSL_API int wolfSSL_write( WOLFSSL* ssl, const void* data, int sz); +WOLFSSL_API int wolfSSL_write_ex(WOLFSSL* ssl, const void* data, size_t sz, + size_t* wr); WOLFSSL_ABI WOLFSSL_API int wolfSSL_read(WOLFSSL* ssl, void* data, int sz); +WOLFSSL_API int wolfSSL_read_ex(WOLFSSL* ssl, void* data, size_t sz, size_t* rd); WOLFSSL_API int wolfSSL_peek(WOLFSSL* ssl, void* data, int sz); WOLFSSL_ABI WOLFSSL_API int wolfSSL_accept(WOLFSSL* ssl); WOLFSSL_API int wolfSSL_inject(WOLFSSL* ssl, const void* data, int sz); @@ -1837,6 +1853,7 @@ WOLFSSL_API int wolfSSL_sk_push_node(WOLFSSL_STACK** stack, WOLFSSL_STACK* in); WOLFSSL_API WOLFSSL_STACK* wolfSSL_sk_get_node(WOLFSSL_STACK* sk, int idx); WOLFSSL_API int wolfSSL_sk_push(WOLFSSL_STACK *st, const void *data); WOLFSSL_API int wolfSSL_sk_insert(WOLFSSL_STACK *sk, const void *data, int idx); +WOLFSSL_API void* wolfSSL_sk_pop(WOLFSSL_STACK* sk); #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) WOLFSSL_API int wolfSSL_sk_ACCESS_DESCRIPTION_push( @@ -2043,6 +2060,7 @@ WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_fd(int fd, int close_flag); WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_bio(void); WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_socket(void); WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_datagram(void); +WOLFSSL_API WOLFSSL_BIO_METHOD *wolfSSL_BIO_s_null(void); WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_connect(const char *str); WOLFSSL_API WOLFSSL_BIO *wolfSSL_BIO_new_accept(const char *port); @@ -2262,9 +2280,8 @@ WOLFSSL_API WOLFSSL_X509_STORE_CTX *wolfSSL_X509_STORE_CTX_get0_parent_ctx( WOLFSSL_X509_STORE_CTX *ctx); WOLFSSL_API int wolfSSL_X509_STORE_set_flags(WOLFSSL_X509_STORE* store, unsigned long flag); -WOLFSSL_API int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE* store); -WOLFSSL_API int wolfSSL_X509_STORE_get_by_subject(WOLFSSL_X509_STORE_CTX* ctx, - int idx, WOLFSSL_X509_NAME* name, WOLFSSL_X509_OBJECT* obj); +WOLFSSL_API int wolfSSL_X509_STORE_get_by_subject(WOLFSSL_X509_STORE_CTX* ctx, + int idx, WOLFSSL_X509_NAME* name, WOLFSSL_X509_OBJECT* obj); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM *wolfSSL_X509_STORE_CTX_get0_param( WOLFSSL_X509_STORE_CTX *ctx); WOLFSSL_API int wolfSSL_X509_STORE_CTX_init(WOLFSSL_X509_STORE_CTX* ctx, @@ -2666,6 +2683,7 @@ enum { #define SSL_WRITING WOLFSSL_WRITING #define SSL_READING WOLFSSL_READING #define SSL_MAX_SSL_SESSION_ID_LENGTH WOLFSSL_MAX_SSL_SESSION_ID_LENGTH +#define SSL_MAX_SID_CTX_LENGTH WOLFSSL_MAX_SSL_SESSION_ID_LENGTH #ifdef HAVE_OCSP /* OCSP Flags */ @@ -2814,6 +2832,10 @@ WOLFSSL_API int wolfSSL_SESSION_set_cipher(WOLFSSL_SESSION* session, WOLFSSL_API int wolfSSL_is_init_finished(const WOLFSSL* ssl); WOLFSSL_API const char* wolfSSL_get_version(const WOLFSSL* ssl); +#ifdef OPENSSL_EXTRA +WOLFSSL_API WOLF_STACK_OF(WOLFSSL_CIPHER)* wolfSSL_get_client_ciphers( + WOLFSSL* ssl); +#endif WOLFSSL_API int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl); WOLFSSL_API WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl); WOLFSSL_API char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in, int len); @@ -2968,23 +2990,49 @@ enum { /* ssl Constants */ (WOLFSSL_SESS_CACHE_NO_INTERNAL_STORE | WOLFSSL_SESS_CACHE_NO_INTERNAL_LOOKUP), - /* These values match OpenSSL values for corresponding names. */ + /* These values match OpenSSL values for corresponding names.*/ WOLFSSL_ERROR_SSL = 1, + + /* Operation did not complete; call this API again.*/ WOLFSSL_ERROR_WANT_READ = 2, + + /* Operation did not complete; call this API again.*/ WOLFSSL_ERROR_WANT_WRITE = 3, + + /* Operation did not complete; callback needs this API to be called again.*/ WOLFSSL_ERROR_WANT_X509_LOOKUP = 4, + + /* Some sort of system I/O error happened.*/ WOLFSSL_ERROR_SYSCALL = 5, + + /* The connection has been closed with a closure alert.*/ WOLFSSL_ERROR_ZERO_RETURN = 6, + + /* Underlying protocol connection not started yet, call this API again.*/ WOLFSSL_ERROR_WANT_CONNECT = 7, + + /* Underlying protocol connection not started yet, call this API again.*/ WOLFSSL_ERROR_WANT_ACCEPT = 8, + /* Close notify alert was sent to the peer.*/ WOLFSSL_SENT_SHUTDOWN = 1, + + /* Close notify or fatal error was received from the peer.*/ WOLFSSL_RECEIVED_SHUTDOWN = 2, + + /* Let library know that write buffer might move to different addresses.*/ WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = 4, + /* The handshake failed. */ WOLFSSL_R_SSL_HANDSHAKE_FAILURE = 101, + + /* The issuer CA certificate is unknown. */ WOLFSSL_R_TLSV1_ALERT_UNKNOWN_CA = 102, + + /* Unable to validate the certificate. */ WOLFSSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN = 103, + + /* There was a problem parsing the certificate. */ WOLFSSL_R_SSLV3_ALERT_BAD_CERTIFICATE = 104, WOLF_PEM_BUFSIZE = 1024 @@ -4059,6 +4107,13 @@ WOLFSSL_API void wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx, WOLFSSL_API void wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx); WOLFSSL_API void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl); +typedef int (*CallbackGenExtMasterSecret)(WOLFSSL* ssl, byte* hash, + word32 hashsz, void* ctx); +WOLFSSL_API void wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx, + CallbackGenExtMasterSecret cb); +WOLFSSL_API void wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx); +WOLFSSL_API void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl); + typedef int (*CallbackGenPreMaster)(WOLFSSL* ssl, byte *premaster, word32 preSz, void* ctx); WOLFSSL_API void wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, @@ -4520,62 +4575,54 @@ enum { WOLFSSL_FFDHE_4096 = 258, WOLFSSL_FFDHE_6144 = 259, WOLFSSL_FFDHE_8192 = 260, + WOLFSSL_FFDHE_END = 511, #ifdef HAVE_PQC - /* These group numbers were taken from OQS's openssl provider, see: + +#ifdef WOLFSSL_MLKEM_KYBER + /* Old code points to keep compatibility with Kyber Round 3. + * Taken from OQS's openssl provider, see: * https://github.com/open-quantum-safe/oqs-provider/blob/main/oqs-template/ - * oqs-kem-info.md. - * - * The levels in the group name refer to the claimed NIST level of each - * parameter set. The associated parameter set name is listed as a comment - * beside the group number. Please see the NIST PQC Competition's submitted - * papers for more details. - * - * LEVEL1 means that an attack on that parameter set would require the same - * or more resources as a key search on AES 128. LEVEL3 would require the - * same or more resources as a key search on AES 192. LEVEL5 would require - * the same or more resources as a key search on AES 256. None of the - * algorithms have LEVEL2 and LEVEL4 because none of these submissions - * included them. */ - -#ifdef WOLFSSL_KYBER_ORIGINAL - WOLFSSL_PQC_MIN = 570, - WOLFSSL_PQC_SIMPLE_MIN = 570, + * oqs-kem-info.md + */ WOLFSSL_KYBER_LEVEL1 = 570, /* KYBER_512 */ WOLFSSL_KYBER_LEVEL3 = 572, /* KYBER_768 */ WOLFSSL_KYBER_LEVEL5 = 573, /* KYBER_1024 */ -#ifdef WOLFSSL_NO_ML_KEM - WOLFSSL_PQC_SIMPLE_MAX = 573, -#endif - WOLFSSL_PQC_HYBRID_MIN = 12090, WOLFSSL_P256_KYBER_LEVEL1 = 12090, WOLFSSL_P384_KYBER_LEVEL3 = 12092, WOLFSSL_P521_KYBER_LEVEL5 = 12093, -#ifdef WOLFSSL_NO_ML_KEM - WOLFSSL_PQC_HYBRID_MAX = 12093, - WOLFSSL_PQC_MAX = 12093, -#endif -#endif + WOLFSSL_X25519_KYBER_LEVEL1 = 12089, + WOLFSSL_X448_KYBER_LEVEL3 = 12176, + WOLFSSL_X25519_KYBER_LEVEL3 = 25497, + WOLFSSL_P256_KYBER_LEVEL3 = 25498, +#endif /* WOLFSSL_MLKEM_KYBER */ #ifndef WOLFSSL_NO_ML_KEM -#ifndef WOLFSSL_KYBER_ORIGINAL - WOLFSSL_PQC_MIN = 583, - WOLFSSL_PQC_SIMPLE_MIN = 583, -#endif - WOLFSSL_ML_KEM_512 = 583, /* ML-KEM 512 */ - WOLFSSL_ML_KEM_768 = 584, /* ML-KEM 768 */ - WOLFSSL_ML_KEM_1024 = 585, /* ML-KEM 1024 */ - WOLFSSL_PQC_SIMPLE_MAX = 585, - -#ifndef WOLFSSL_KYBER_ORIGINAL - WOLFSSL_PQC_HYBRID_MIN = 12103, -#endif - WOLFSSL_P256_ML_KEM_512 = 12103, - WOLFSSL_P384_ML_KEM_768 = 12104, - WOLFSSL_P521_ML_KEM_1024 = 12105, - WOLFSSL_PQC_HYBRID_MAX = 12105, - WOLFSSL_PQC_MAX = 12105, -#endif /* !WOLFSSL_NO_ML_KEM */ + /* Taken from draft-connolly-tls-mlkem-key-agreement, see: + * https://github.com/dconnolly/draft-connolly-tls-mlkem-key-agreement/ + */ + WOLFSSL_ML_KEM_512 = 512, + WOLFSSL_ML_KEM_768 = 513, + WOLFSSL_ML_KEM_1024 = 514, + + /* Taken from draft-kwiatkowski-tls-ecdhe-mlkem. see: + * https://github.com/post-quantum-cryptography/ + * draft-kwiatkowski-tls-ecdhe-mlkem/ + */ + WOLFSSL_P256_ML_KEM_768 = 4587, + WOLFSSL_X25519_ML_KEM_768 = 4588, + WOLFSSL_P384_ML_KEM_1024 = 4589, + + /* Taken from OQS's openssl provider, see: + * https://github.com/open-quantum-safe/oqs-provider/blob/main/oqs-template/ + * oqs-kem-info.md + */ + WOLFSSL_P256_ML_KEM_512 = 12107, + WOLFSSL_P384_ML_KEM_768 = 12108, + WOLFSSL_P521_ML_KEM_1024 = 12109, + WOLFSSL_X25519_ML_KEM_512 = 12214, + WOLFSSL_X448_ML_KEM_768 = 12215, +#endif /* WOLFSSL_NO_ML_KEM */ #endif /* HAVE_PQC */ WOLF_ENUM_DUMMY_LAST_ELEMENT(SSL_H) }; @@ -4968,6 +5015,10 @@ WOLFSSL_API const WOLFSSL_STACK *wolfSSL_X509_REQ_get_extensions(const WOLFSSL_X WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_get_ext(const WOLFSSL_X509* x, int loc); WOLFSSL_API int wolfSSL_X509_get_ext_by_OBJ(const WOLFSSL_X509 *x, const WOLFSSL_ASN1_OBJECT *obj, int lastpos); +WOLFSSL_API int wolfSSL_X509_OBJECT_set1_X509(WOLFSSL_X509_OBJECT *a, + WOLFSSL_X509 *obj); +WOLFSSL_API int wolfSSL_X509_OBJECT_set1_X509_CRL(WOLFSSL_X509_OBJECT *a, + WOLFSSL_X509_CRL *obj); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_set_ext(WOLFSSL_X509* x, int loc); WOLFSSL_API int wolfSSL_X509_EXTENSION_get_critical(const WOLFSSL_X509_EXTENSION* ex); WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509_EXTENSION_new(void); @@ -5109,6 +5160,7 @@ struct WOLFSSL_CONF_CTX { }; WOLFSSL_API WOLFSSL_X509_NAME_ENTRY *wolfSSL_X509_NAME_get_entry(WOLFSSL_X509_NAME *name, int loc); +WOLFSSL_API int wolfSSL_X509_NAME_ENTRY_set(const WOLFSSL_X509_NAME_ENTRY *ne); #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #if defined(OPENSSL_EXTRA) \ @@ -5280,6 +5332,12 @@ WOLFSSL_API void wolfSSL_sk_X509_OBJECT_pop_free(WOLFSSL_STACK* s, void (*f) (WOLFSSL_X509_OBJECT*)); WOLFSSL_API int wolfSSL_sk_X509_OBJECT_push(WOLFSSL_STACK* sk, WOLFSSL_X509_OBJECT* obj); +WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* + wolfSSL_sk_X509_OBJECT_deep_copy( + const WOLF_STACK_OF(WOLFSSL_X509_OBJECT)* sk, + WOLFSSL_X509_OBJECT* (*c)(const WOLFSSL_X509_OBJECT*), + void (*f)(WOLFSSL_X509_OBJECT*)); + WOLFSSL_API WOLFSSL_X509_INFO *wolfSSL_X509_INFO_new(void); WOLFSSL_API void wolfSSL_X509_INFO_free(WOLFSSL_X509_INFO* info); @@ -5729,6 +5787,7 @@ WOLFSSL_API WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(vo #define SSL_COMP_get_compression_methods WOLFSSL_COMP_get_compression_methods #endif WOLFSSL_API int wolfSSL_X509_STORE_load_locations(WOLFSSL_X509_STORE *str, const char *file, const char *dir); +WOLFSSL_API int wolfSSL_X509_STORE_set_default_paths(WOLFSSL_X509_STORE *str); WOLFSSL_API int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *ctx, WOLFSSL_X509_CRL *x); WOLFSSL_API int wolfSSL_sk_SSL_CIPHER_num(const WOLF_STACK_OF(WOLFSSL_CIPHER)* p); WOLFSSL_API int wolfSSL_sk_SSL_CIPHER_find( diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index 478a905..fa84ab0 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -1,6 +1,6 @@ /* test.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -85,11 +85,50 @@ #endif /* HAVE_ECC */ #endif /*HAVE_PK_CALLBACKS */ -#ifdef USE_WINDOWS_API +#ifdef __WATCOMC__ + #define SNPRINTF snprintf + #if defined(__NT__) + #include + #include + #include + #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */ + #include + #endif + #define SOCKET_T SOCKET + #define XSLEEP_MS(t) Sleep(t) + #elif defined(__OS2__) + #include + #include + #include + #define SOCKET_T int + #elif defined(__UNIX__) + #include + #include + #include + #ifndef WOLFSSL_NDS + #include + #endif + #include + #include + #ifdef HAVE_PTHREAD + #include + #endif + #define SOCKET_T int + #ifndef SO_NOSIGPIPE + #include /* ignore SIGPIPE */ + #endif + + #define XSLEEP_MS(m) \ + { \ + struct timespec req = { (m)/1000, ((m) % 1000) * 1000 }; \ + nanosleep( &req, NULL ); \ + } + #endif +#elif defined(USE_WINDOWS_API) #include + #include #include #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */ - #include #include #endif #define SOCKET_T SOCKET @@ -680,16 +719,6 @@ void test_wolfSSL_client_server_nofail_ex(callback_functions* client_cb, void test_wolfSSL_client_server_nofail(callback_functions* client_cb, callback_functions* server_cb); -/* Return - * tmpDir on success - * NULL on failure */ -char* create_tmp_dir(char* tmpDir, int len); -/* Remaining functions return - * 0 on success - * -1 on failure */ -int rem_dir(const char* dirName); -int rem_file(const char* fileName); -int copy_file(const char* in, const char* out); #if defined(__MACH__) || defined(__FreeBSD__) int link_file(const char* in, const char* out); @@ -1156,13 +1185,13 @@ static WC_INLINE void ShowX509Chain(WOLFSSL_X509_CHAIN* chain, int count, { int i; int length; - unsigned char buffer[3072]; + unsigned char certPem[3072]; WOLFSSL_X509* chainX509; for (i = 0; i < count; i++) { - wolfSSL_get_chain_cert_pem(chain, i, buffer, sizeof(buffer), &length); - buffer[length] = 0; - printf("\n%s: %d has length %d data = \n%s\n", hdr, i, length, buffer); + wolfSSL_get_chain_cert_pem(chain, i, certPem, sizeof(certPem), &length); + certPem[length] = 0; + printf("\n%s: %d has length %d data = \n%s\n", hdr, i, length, certPem); chainX509 = wolfSSL_get_chain_X509(chain, i); if (chainX509) @@ -1439,7 +1468,7 @@ static WC_INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp) err_sys_with_errno("socket failed\n"); } -#ifndef USE_WINDOWS_API +#if !defined(USE_WINDOWS_API) && !defined(__WATCOMC__) && !defined(__OS2__) #ifdef SO_NOSIGPIPE { int on = 1; @@ -1449,7 +1478,7 @@ static WC_INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp) err_sys_with_errno("setsockopt SO_NOSIGPIPE failed\n"); } #elif defined(WOLFSSL_MDK_ARM) || defined (WOLFSSL_TIRTOS) ||\ - defined(WOLFSSL_KEIL_TCP_NET) || defined(WOLFSSL_ZEPHYR) + defined(WOLFSSL_KEIL_TCP_NET) || defined(WOLFSSL_ZEPHYR) /* nothing to define */ #elif defined(NETOS) /* TODO: signal(SIGPIPE, SIG_IGN); */ @@ -1467,7 +1496,7 @@ static WC_INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp) err_sys_with_errno("setsockopt TCP_NODELAY failed\n"); } #endif -#endif /* USE_WINDOWS_API */ +#endif /* !defined(USE_WINDOWS_API) && !defined(__WATCOMC__) && ... */ } #if defined(WOLFSSL_WOLFSENTRY_HOOKS) && defined(WOLFSENTRY_H) @@ -1521,7 +1550,7 @@ static WC_INLINE int tcp_select_ex(SOCKET_T socketfd, int to_sec, int rx) fd_set* recvfds = NULL; fd_set* sendfds = NULL; SOCKET_T nfds = socketfd + 1; -#if !defined(__INTEGRITY) +#if !defined(__INTEGRITY) && !defined(__WATCOMC__) struct timeval timeout = {(to_sec > 0) ? to_sec : 0, 0}; #else struct timeval timeout; @@ -1538,8 +1567,9 @@ static WC_INLINE int tcp_select_ex(SOCKET_T socketfd, int to_sec, int rx) else sendfds = &fds; -#if defined(__INTEGRITY) - timeout.tv_sec = (long long)(to_sec > 0) ? to_sec : 0, 0; +#if defined(__INTEGRITY) || defined(__WATCOMC__) + timeout.tv_sec = (long long)(to_sec > 0) ? to_sec : 0; + timeout.tv_usec = 0; #endif result = select(nfds, recvfds, sendfds, &errfds, &timeout); @@ -1810,6 +1840,10 @@ static WC_INLINE void tcp_set_nonblocking(SOCKET_T* sockfd) || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS) \ || defined(WOLFSSL_ZEPHYR) /* non blocking not supported, for now */ + #elif defined(__WATCOMC__) && defined(__OS2__) + int blocking = 1; + if (ioctl(*sockfd, FIONBIO, &blocking) == -1) + err_sys_with_errno("ioctl failed"); #else int flags = fcntl(*sockfd, F_GETFL, 0); if (flags < 0) @@ -1831,6 +1865,10 @@ static WC_INLINE void tcp_set_blocking(SOCKET_T* sockfd) || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS) \ || defined(WOLFSSL_ZEPHYR) /* non blocking not supported, for now */ + #elif defined(__WATCOMC__) && defined(__OS2__) + int blocking = 0; + if (ioctl(*sockfd, FIONBIO, &blocking) == -1) + err_sys_with_errno("ioctl failed"); #else int flags = fcntl(*sockfd, F_GETFL, 0); if (flags < 0) @@ -2131,7 +2169,9 @@ static WC_INLINE unsigned int my_psk_client_cs_cb(WOLFSSL* ssl, #elif defined(USE_WINDOWS_API) #define WIN32_LEAN_AND_MEAN + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ static WC_INLINE double current_time(int reset) { @@ -2423,7 +2463,7 @@ static THREAD_LS_T int myVerifyAction = VERIFY_OVERRIDE_ERROR; static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) { - char buffer[WOLFSSL_MAX_ERROR_SZ]; + char err_buffer[WOLFSSL_MAX_ERROR_SZ]; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_X509* peer; #if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) && \ @@ -2450,7 +2490,7 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) */ fprintf(stderr, "In verification callback, error = %d, %s\n", store->error, - wolfSSL_ERR_error_string((unsigned long) store->error, buffer)); + wolfSSL_ERR_error_string((unsigned long) store->error, err_buffer)); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) peer = store->current_cert; if (peer) { @@ -4220,6 +4260,25 @@ static WC_INLINE int myGenMaster(WOLFSSL* ssl, void* ctx) return ret; } +static WC_INLINE int myGenExtMaster(WOLFSSL* ssl, byte* hash, word32 hashSz, + void* ctx) +{ + int ret; + PkCbInfo* cbInfo = (PkCbInfo*)ctx; + + (void)ssl; + (void)cbInfo; + (void)hash; + (void)hashSz; + + WOLFSSL_PKMSG("Gen Extended Master"); + /* fall through to original routine */ + ret = PROTOCOLCB_UNAVAILABLE; + WOLFSSL_PKMSG("Gen Extended Master: ret %d\n", ret); + + return ret; +} + static WC_INLINE int myGenPreMaster(WOLFSSL* ssl, byte *premaster, word32 preSz, void* ctx) { @@ -4372,6 +4431,7 @@ static WC_INLINE void SetupPkCallbacks(WOLFSSL_CTX* ctx) #ifndef NO_CERTS wolfSSL_CTX_SetGenMasterSecretCb(ctx, myGenMaster); + wolfSSL_CTX_SetGenExtMasterSecretCb(ctx, myGenExtMaster); wolfSSL_CTX_SetGenPreMasterCb(ctx, myGenPreMaster); wolfSSL_CTX_SetGenSessionKeyCb(ctx, myGenSessionKey); wolfSSL_CTX_SetEncryptKeysCb(ctx, mySetEncryptKeys); @@ -4427,6 +4487,7 @@ static WC_INLINE void SetupPkCallbackContexts(WOLFSSL* ssl, void* myCtx) #ifndef NO_CERTS wolfSSL_SetGenMasterSecretCtx(ssl, myCtx); + wolfSSL_SetGenExtMasterSecretCtx(ssl, myCtx); wolfSSL_SetGenPreMasterCtx(ssl, myCtx); wolfSSL_SetGenSessionKeyCtx(ssl, myCtx); wolfSSL_SetEncryptKeysCtx(ssl, myCtx); @@ -4487,7 +4548,7 @@ static WC_INLINE int SimulateWantWriteIOSendCb(WOLFSSL *ssl, char *buf, int sz, #endif /* USE_WOLFSSL_IO */ #if defined(__hpux__) || defined(__MINGW32__) || defined (WOLFSSL_TIRTOS) \ - || defined(_MSC_VER) + || defined(_MSC_VER) || defined(__WATCOMC__) /* HP/UX doesn't have strsep, needed by test/suites.c */ static WC_INLINE char* strsep(char **stringp, const char *delim) diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index d7a1985..c128a21 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -1,6 +1,6 @@ /* wolfssl_version.h.in * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.7.6" -#define LIBWOLFSSL_VERSION_HEX 0x05007006 +#define LIBWOLFSSL_VERSION_STRING "5.8.0" +#define LIBWOLFSSL_VERSION_HEX 0x05008000 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/aes.h b/src/wolfssl/wolfcrypt/aes.h index d1b71e5..128611c 100644 --- a/src/wolfssl/wolfcrypt/aes.h +++ b/src/wolfssl/wolfcrypt/aes.h @@ -1,6 +1,6 @@ /* aes.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -303,12 +303,21 @@ struct Aes { #endif #ifdef WOLFSSL_AESNI byte use_aesni; + #if defined(WOLFSSL_LINUXKM) || defined(WC_WANT_FLAG_DONT_USE_AESNI) + /* Note, we can't support WC_FLAG_DONT_USE_AESNI by default because we + * need to support legacy applications that call wc_AesSetKey() on + * uninited struct Aes. For details see the software implementation of + * wc_AesSetKeyLocal() (aes.c). + */ + #define WC_FLAG_DONT_USE_AESNI 2 + #endif #endif /* WOLFSSL_AESNI */ #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) byte use_aes_hw_crypto; #ifdef HAVE_AESGCM byte use_pmull_hw_crypto; + byte use_sha3_hw_crypto; #endif #endif /* __aarch64__ && WOLFSSL_ARMASM && !WOLFSSL_ARMASM_NO_HW_CRYPTO */ #ifdef WOLF_CRYPTO_CB @@ -325,7 +334,8 @@ struct Aes { WC_ASYNC_DEV asyncDev; #endif /* WOLFSSL_ASYNC_CRYPT */ #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \ - defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) + defined(WOLFSSL_AES_OFB) || defined(WOLFSSL_AES_XTS) || \ + defined(WOLFSSL_AES_CTS) word32 left; /* unused bytes left from last call */ #endif #ifdef WOLFSSL_XILINX_CRYPT @@ -416,6 +426,9 @@ struct Aes { * trackable by sanitizers. */ #endif +#ifdef WOLFSSL_AES_CTS + byte ctsBlock[WC_AES_BLOCK_SIZE * 2]; +#endif }; #ifndef WC_AES_TYPE_DEFINED @@ -587,7 +600,7 @@ WOLFSSL_API int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* iv, word32 ivSz, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz); - WOLFSSL_API int wc_AesGcmDecrypt(Aes* aes, byte* out, + WOLFSSL_API WARN_UNUSED_RESULT int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, const byte* iv, word32 ivSz, const byte* authTag, word32 authTagSz, @@ -609,8 +622,8 @@ WOLFSSL_API int wc_AesGcmDecryptInit(Aes* aes, const byte* key, word32 len, const byte* iv, word32 ivSz); WOLFSSL_API int wc_AesGcmDecryptUpdate(Aes* aes, byte* out, const byte* in, word32 sz, const byte* authIn, word32 authInSz); -WOLFSSL_API int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, - word32 authTagSz); +WOLFSSL_API WARN_UNUSED_RESULT int wc_AesGcmDecryptFinal(Aes* aes, + const byte* authTag, word32 authTagSz); #endif #ifndef WC_NO_RNG @@ -647,7 +660,7 @@ WOLFSSL_API int wc_AesGcmDecryptFinal(Aes* aes, const byte* authTag, const byte* nonce, word32 nonceSz, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz); - WOLFSSL_API int wc_AesCcmDecrypt(Aes* aes, byte* out, + WOLFSSL_API WARN_UNUSED_RESULT int wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, const byte* nonce, word32 nonceSz, const byte* authTag, word32 authTagSz, @@ -760,7 +773,7 @@ WOLFSSL_API int wc_AesSivEncrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out); -WOLFSSL_API +WOLFSSL_API WARN_UNUSED_RESULT int wc_AesSivDecrypt(const byte* key, word32 keySz, const byte* assoc, word32 assocSz, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out); @@ -769,7 +782,7 @@ WOLFSSL_API int wc_AesSivEncrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, word32 numAssoc, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out); -WOLFSSL_API +WOLFSSL_API WARN_UNUSED_RESULT int wc_AesSivDecrypt_ex(const byte* key, word32 keySz, const AesSivAssoc* assoc, word32 numAssoc, const byte* nonce, word32 nonceSz, const byte* in, word32 inSz, byte* siv, byte* out); @@ -804,7 +817,8 @@ WOLFSSL_API int wc_AesEaxEncryptAuth(const byte* key, word32 keySz, byte* out, /* input data to authenticate (header) */ const byte* authIn, word32 authInSz); -WOLFSSL_API int wc_AesEaxDecryptAuth(const byte* key, word32 keySz, byte* out, +WOLFSSL_API WARN_UNUSED_RESULT int wc_AesEaxDecryptAuth(const byte* key, + word32 keySz, byte* out, const byte* in, word32 inSz, const byte* nonce, word32 nonceSz, /* auth tag to verify against */ @@ -832,15 +846,38 @@ WOLFSSL_API int wc_AesEaxAuthDataUpdate(AesEax* eax, WOLFSSL_API int wc_AesEaxEncryptFinal(AesEax* eax, byte* authTag, word32 authTagSz); -WOLFSSL_API int wc_AesEaxDecryptFinal(AesEax* eax, +WOLFSSL_API WARN_UNUSED_RESULT int wc_AesEaxDecryptFinal(AesEax* eax, const byte* authIn, word32 authInSz); WOLFSSL_API int wc_AesEaxFree(AesEax* eax); #endif /* WOLFSSL_AES_EAX */ +#ifdef WOLFSSL_AES_CTS +/* Ciphertext stealing encryption compatible with RFC2040 and RFC3962. */ + +/* One-shot API */ +WOLFSSL_API int wc_AesCtsEncrypt(const byte* key, word32 keySz, byte* out, + const byte* in, word32 inSz, + const byte* iv); +WOLFSSL_API int wc_AesCtsDecrypt(const byte* key, word32 keySz, byte* out, + const byte* in, word32 inSz, + const byte* iv); + +/* Incremental API */ +WOLFSSL_API int wc_AesCtsEncryptUpdate(Aes* aes, byte* out, word32* outSz, + const byte* in, word32 inSz); +WOLFSSL_API int wc_AesCtsDecryptUpdate(Aes* aes, byte* out, word32* outSz, + const byte* in, word32 inSz); +WOLFSSL_API int wc_AesCtsEncryptFinal(Aes* aes, byte* out, word32* outSz); +WOLFSSL_API int wc_AesCtsDecryptFinal(Aes* aes, byte* out, word32* outSz); + + +#endif + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) && \ !defined(WOLFSSL_ARMASM_NO_HW_CRYPTO) + /* GHASH one block of data. * * XOR block into tag and GMULT with H. @@ -848,7 +885,7 @@ WOLFSSL_API int wc_AesEaxFree(AesEax* eax); * @param [in, out] aes AES GCM object. * @param [in] block Block of AAD or cipher text. */ -#define GHASH_ONE_BLOCK(aes, block) \ +#define GHASH_ONE_BLOCK_AARCH64(aes, block) \ do { \ xorbuf(AES_TAG(aes), block, WC_AES_BLOCK_SIZE); \ GMULT_AARCH64(AES_TAG(aes), aes->gcm.H); \ diff --git a/src/wolfssl/wolfcrypt/arc4.h b/src/wolfssl/wolfcrypt/arc4.h index 0dc29d3..cdddde8 100644 --- a/src/wolfssl/wolfcrypt/arc4.h +++ b/src/wolfssl/wolfcrypt/arc4.h @@ -1,6 +1,6 @@ /* arc4.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ascon.h b/src/wolfssl/wolfcrypt/ascon.h new file mode 100644 index 0000000..196a8ca --- /dev/null +++ b/src/wolfssl/wolfcrypt/ascon.h @@ -0,0 +1,109 @@ +/* ascon.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef WOLF_CRYPT_ASCON_H +#define WOLF_CRYPT_ASCON_H + +#ifdef HAVE_ASCON + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ASCON_HASH256_SZ 32 + +#define ASCON_AEAD128_KEY_SZ 16 +#define ASCON_AEAD128_NONCE_SZ 16 +#define ASCON_AEAD128_TAG_SZ 16 + +typedef union AsconState { +#ifdef WORD64_AVAILABLE + word64 s64[5]; +#endif + word32 s32[10]; + word16 s16[20]; + byte s8[40]; +} AsconState; + +typedef struct wc_AsconHash256 { + AsconState state; + byte lastBlkSz; +} wc_AsconHash256; + +enum { + ASCON_AEAD128_NOTSET = 0, + ASCON_AEAD128_ENCRYPT = 1, + ASCON_AEAD128_DECRYPT = 2 +}; + +typedef struct wc_AsconAEAD128 { + /* needed throughout both encrypt and decrypt */ +#ifdef WORD64_AVAILABLE + word64 key[ASCON_AEAD128_KEY_SZ/sizeof(word64)]; +#endif + AsconState state; + byte lastBlkSz; + byte keySet:1; /* has the key been processed */ + byte nonceSet:1; /* has the nonce been processed */ + byte adSet:1; /* has the associated data been processed */ + byte op:2; /* 0 for not set, 1 for encrypt, 2 for decrypt */ +} wc_AsconAEAD128; + +/* AsconHash API */ + +WOLFSSL_API wc_AsconHash256* wc_AsconHash256_New(void); +WOLFSSL_API void wc_AsconHash256_Free(wc_AsconHash256* a); +WOLFSSL_API int wc_AsconHash256_Init(wc_AsconHash256* a); +WOLFSSL_API void wc_AsconHash256_Clear(wc_AsconHash256* a); +WOLFSSL_API int wc_AsconHash256_Update(wc_AsconHash256* a, const byte* data, + word32 dataSz); +WOLFSSL_API int wc_AsconHash256_Final(wc_AsconHash256* a, byte* hash); + +WOLFSSL_API wc_AsconAEAD128* wc_AsconAEAD128_New(void); +WOLFSSL_API void wc_AsconAEAD128_Free(wc_AsconAEAD128* a); +WOLFSSL_API int wc_AsconAEAD128_Init(wc_AsconAEAD128* a); +WOLFSSL_API void wc_AsconAEAD128_Clear(wc_AsconAEAD128* a); + +/* AsconAEAD API */ + +WOLFSSL_API int wc_AsconAEAD128_SetKey(wc_AsconAEAD128* a, const byte* key); +WOLFSSL_API int wc_AsconAEAD128_SetNonce(wc_AsconAEAD128* a, const byte* nonce); +WOLFSSL_API int wc_AsconAEAD128_SetAD(wc_AsconAEAD128* a, const byte* ad, + word32 adSz); + +WOLFSSL_API int wc_AsconAEAD128_EncryptUpdate(wc_AsconAEAD128* a, byte* out, + const byte* in, word32 inSz); +WOLFSSL_API int wc_AsconAEAD128_EncryptFinal(wc_AsconAEAD128* a, byte* tag); + +WOLFSSL_API int wc_AsconAEAD128_DecryptUpdate(wc_AsconAEAD128* a, byte* out, + const byte* in, word32 inSz); +WOLFSSL_API int wc_AsconAEAD128_DecryptFinal(wc_AsconAEAD128* a, + const byte* tag); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* HAVE_ASCON */ + +#endif /* WOLF_CRYPT_ASCON_H */ diff --git a/src/wolfssl/wolfcrypt/asn.h b/src/wolfssl/wolfcrypt/asn.h index 12a6023..e553059 100644 --- a/src/wolfssl/wolfcrypt/asn.h +++ b/src/wolfssl/wolfcrypt/asn.h @@ -1,6 +1,6 @@ /* asn.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -853,6 +853,26 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #endif #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +/* short names */ +#define WC_SN_md4 "MD4" +#define WC_SN_md5 "MD5" +#define WC_SN_sha1 "SHA1" +#define WC_SN_sha224 "SHA224" +#define WC_SN_sha256 "SHA256" +#define WC_SN_sha384 "SHA384" +#define WC_SN_sha512 "SHA512" +#define WC_SN_sha512_224 "SHA512-224" +#define WC_SN_sha512_256 "SHA512-256" +#define WC_SN_sha3_224 "SHA3-224" +#define WC_SN_sha3_256 "SHA3-256" +#define WC_SN_sha3_384 "SHA3-384" +#define WC_SN_sha3_512 "SHA3-512" +#define WC_SN_shake128 "SHAKE128" +#define WC_SN_shake256 "SHAKE256" +#define WC_SN_blake2s256 "BLAKE2s256" +#define WC_SN_blake2s512 "BLAKE2s512" +#define WC_SN_blake2b512 "BLAKE2b512" +#define WC_SN_sm3 "SM3" /* NIDs */ #define WC_NID_netscape_cert_type WC_NID_undef @@ -1249,6 +1269,7 @@ enum Oid_Types { enum Hash_Sum { MD2h = 646, + MD4h = 648, MD5h = 649, SHAh = 88, SHA224h = 417, @@ -1403,11 +1424,165 @@ enum Extensions_Sum { enum CertificatePolicy_Sum { CP_ANY_OID = 146, /* id-ce 32 0 */ + CP_ISRG_DOMAIN_VALID = 430, /* 1.3.6.1.4.1.44947.1.1.1 */ #ifdef WOLFSSL_FPKI - CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ - CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ - CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ - CP_FPKI_PIVI_AUTH_OID = 458, /* 2.16.840.1.101.3.2.1.3.45 */ + /* Federal PKI OIDs */ + CP_FPKI_HIGH_ASSURANCE_OID = 417, /* 2.16.840.1.101.3.2.1.3.4 */ + CP_FPKI_COMMON_HARDWARE_OID = 420, /* 2.16.840.1.101.3.2.1.3.7 */ + CP_FPKI_MEDIUM_HARDWARE_OID = 425, /* 2.16.840.1.101.3.2.1.3.12 */ + CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ + CP_FPKI_COMMON_HIGH_OID = 429, /* 2.16.840.1.101.3.2.1.3.16 */ + CP_FPKI_PIVI_HARDWARE_OID = 431, /* 2.16.840.1.101.3.2.1.3.18 */ + CP_FPKI_PIVI_CONTENT_SIGNING_OID = 433, /* 2.16.840.1.101.3.2.1.3.20 */ + CP_FPKI_COMMON_DEVICES_HARDWARE_OID = 449, /* 2.16.840.1.101.3.2.1.3.36 */ + CP_FPKI_MEDIUM_DEVICE_HARDWARE_OID = 451, /* 2.16.840.1.101.3.2.1.3.38 */ + CP_FPKI_COMMON_PIV_CONTENT_SIGNING_OID = 452, /* 2.16.840.1.101.3.2.1.3.39 */ + CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ + CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ + CP_FPKI_PIVI_AUTH_OID = 458, /* 2.16.840.1.101.3.2.1.3.45 */ + CP_FPKI_COMMON_PIVI_CONTENT_SIGNING_OID = 460, /* 2.16.840.1.101.3.2.1.3.47 */ + + /* Federal PKI Test OIDs */ + CP_FPKI_AUTH_TEST_OID = 469, /* 2.16.840.1.101.3.2.1.48.11 */ + CP_FPKI_CARDAUTH_TEST_OID = 471, /* 2.16.840.1.101.3.2.1.48.13 */ + CP_FPKI_PIV_CONTENT_TEST_OID = 544, /* 2.16.840.1.101.3.2.1.48.86 */ + CP_FPKI_PIV_AUTH_DERIVED_TEST_OID = 567, /* 2.16.840.1.101.3.2.1.48.109 */ + CP_FPKI_PIV_AUTH_DERIVED_HW_TEST_OID = 568, /* 2.16.840.1.101.3.2.1.48.110 */ + + /* DoD PKI OIDs */ + CP_DOD_MEDIUM_OID = 423, /* 2.16.840.1.101.2.1.11.5 */ + CP_DOD_MEDIUM_HARDWARE_OID = 427, /* 2.16.840.1.101.2.1.11.9 */ + CP_DOD_PIV_AUTH_OID = 428, /* 2.16.840.1.101.2.1.11.10 */ + CP_DOD_MEDIUM_NPE_OID = 435, /* 2.16.840.1.101.2.1.11.17 */ + CP_DOD_MEDIUM_2048_OID = 436, /* 2.16.840.1.101.2.1.11.18 */ + CP_DOD_MEDIUM_HARDWARE_2048_OID = 437, /* 2.16.840.1.101.2.1.11.19 */ + CP_DOD_PIV_AUTH_2048_OID = 438, /* 2.16.840.1.101.2.1.11.20 */ + CP_DOD_PEER_INTEROP_OID = 100449, /* 2.16.840.1.101.2.1.11.31 */ + CP_DOD_MEDIUM_NPE_112_OID = 100454, /* 2.16.840.1.101.2.1.11.36 */ + CP_DOD_MEDIUM_NPE_128_OID = 455, /* 2.16.840.1.101.2.1.11.37 */ + CP_DOD_MEDIUM_NPE_192_OID = 456, /* 2.16.840.1.101.2.1.11.38 */ + CP_DOD_MEDIUM_112_OID = 457, /* 2.16.840.1.101.2.1.11.39 */ + CP_DOD_MEDIUM_128_OID = 100458, /* 2.16.840.1.101.2.1.11.40 */ + CP_DOD_MEDIUM_192_OID = 459, /* 2.16.840.1.101.2.1.11.41 */ + CP_DOD_MEDIUM_HARDWARE_112_OID = 100460, /* 2.16.840.1.101.2.1.11.42 */ + CP_DOD_MEDIUM_HARDWARE_128_OID = 461, /* 2.16.840.1.101.2.1.11.43 */ + CP_DOD_MEDIUM_HARDWARE_192_OID = 462, /* 2.16.840.1.101.2.1.11.44 */ + CP_DOD_ADMIN_OID = 477, /* 2.16.840.1.101.2.1.11.59 */ + CP_DOD_INTERNAL_NPE_112_OID = 478, /* 2.16.840.1.101.2.1.11.60 */ + CP_DOD_INTERNAL_NPE_128_OID = 479, /* 2.16.840.1.101.2.1.11.61 */ + CP_DOD_INTERNAL_NPE_192_OID = 480, /* 2.16.840.1.101.2.1.11.62 */ + + /* ECA PKI OIDs */ + CP_ECA_MEDIUM_OID = 100423, /* 2.16.840.1.101.3.2.1.12.1 */ + CP_ECA_MEDIUM_HARDWARE_OID = 424, /* 2.16.840.1.101.3.2.1.12.2 */ + CP_ECA_MEDIUM_TOKEN_OID = 100425, /* 2.16.840.1.101.3.2.1.12.3 */ + CP_ECA_MEDIUM_SHA256_OID = 100426, /* 2.16.840.1.101.3.2.1.12.4 */ + CP_ECA_MEDIUM_TOKEN_SHA256_OID = 100427, /* 2.16.840.1.101.3.2.1.12.5 */ + CP_ECA_MEDIUM_HARDWARE_PIVI_OID = 100428, /* 2.16.840.1.101.3.2.1.12.6 */ + CP_ECA_CONTENT_SIGNING_PIVI_OID = 100430, /* 2.16.840.1.101.3.2.1.12.8 */ + CP_ECA_MEDIUM_DEVICE_SHA256_OID = 431, /* 2.16.840.1.101.3.2.1.12.9 */ + CP_ECA_MEDIUM_HARDWARE_SHA256_OID = 432, /* 2.16.840.1.101.3.2.1.12.10 */ + + /* Department of State PKI OIDs */ + CP_STATE_BASIC_OID = 100417, /* 2.16.840.1.101.3.2.1.6.1 */ + CP_STATE_LOW_OID = 418, /* 2.16.840.1.101.3.2.1.6.2 */ + CP_STATE_MODERATE_OID = 100419, /* 2.16.840.1.101.3.2.1.6.3 */ + CP_STATE_HIGH_OID = 100420, /* 2.16.840.1.101.3.2.1.6.4 */ + CP_STATE_MEDHW_OID = 101428, /* 2.16.840.1.101.3.2.1.6.12 */ + CP_STATE_MEDDEVHW_OID = 101454, /* 2.16.840.1.101.3.2.1.6.38 */ + + /* U.S. Treasury SSP PKI OIDs */ + CP_TREAS_MEDIUMHW_OID = 419, /* 2.16.840.1.101.3.2.1.5.4 */ + CP_TREAS_HIGH_OID = 101420, /* 2.16.840.1.101.3.2.1.5.5 */ + CP_TREAS_PIVI_HW_OID = 101425, /* 2.16.840.1.101.3.2.1.5.10 */ + CP_TREAS_PIVI_CONTENT_OID = 101427, /* 2.16.840.1.101.3.2.1.5.12 */ + + /* Boeing PKI OIDs */ + CP_BOEING_MEDIUMHW_SHA256_OID = 159, /* 1.3.6.1.4.1.73.15.3.1.12 */ + CP_BOEING_MEDIUMHW_CONTENT_SHA256_OID = 164, /* 1.3.6.1.4.1.73.15.3.1.17 */ + + /* Carillon Federal Services OIDs */ + CP_CARILLON_MEDIUMHW_256_OID = 467, /* 1.3.6.1.4.1.45606.3.1.12 */ + CP_CARILLON_AIVHW_OID = 475, /* 1.3.6.1.4.1.45606.3.1.20 */ + CP_CARILLON_AIVCONTENT_OID = 100477, /* 1.3.6.1.4.1.45606.3.1.22 */ + + /* Carillon Information Security OIDs */ + CP_CIS_MEDIUMHW_256_OID = 489, /* 1.3.6.1.4.1.25054.3.1.12 */ + CP_CIS_MEDDEVHW_256_OID = 491, /* 1.3.6.1.4.1.25054.3.1.14 */ + CP_CIS_ICECAP_HW_OID = 497, /* 1.3.6.1.4.1.25054.3.1.20 */ + CP_CIS_ICECAP_CONTENT_OID = 499, /* 1.3.6.1.4.1.25054.3.1.22 */ + + /* CertiPath Bridge OIDs */ + CP_CERTIPATH_MEDIUMHW_OID = 100459, /* 1.3.6.1.4.1.24019.1.1.1.2 */ + CP_CERTIPATH_HIGHHW_OID = 101460, /* 1.3.6.1.4.1.24019.1.1.1.3 */ + CP_CERTIPATH_ICECAP_HW_OID = 464, /* 1.3.6.1.4.1.24019.1.1.1.7 */ + CP_CERTIPATH_ICECAP_CONTENT_OID = 466, /* 1.3.6.1.4.1.24019.1.1.1.9 */ + CP_CERTIPATH_VAR_MEDIUMHW_OID = 100475, /* 1.3.6.1.4.1.24019.1.1.1.18 */ + CP_CERTIPATH_VAR_HIGHHW_OID = 476, /* 1.3.6.1.4.1.24019.1.1.1.19 */ + + /* TSCP Bridge OIDs */ + CP_TSCP_MEDIUMHW_OID = 442, /* 1.3.6.1.4.1.38099.1.1.1.2 */ + CP_TSCP_PIVI_OID = 445, /* 1.3.6.1.4.1.38099.1.1.1.5 */ + CP_TSCP_PIVI_CONTENT_OID = 447, /* 1.3.6.1.4.1.38099.1.1.1.7 */ + + /* DigiCert NFI PKI OIDs */ + CP_DIGICERT_NFSSP_MEDIUMHW_OID = 796, /* 2.16.840.1.113733.1.7.23.3.1.7 */ + CP_DIGICERT_NFSSP_AUTH_OID = 802, /* 2.16.840.1.113733.1.7.23.3.1.13 */ + CP_DIGICERT_NFSSP_PIVI_HW_OID = 807, /* 2.16.840.1.113733.1.7.23.3.1.18 */ + CP_DIGICERT_NFSSP_PIVI_CONTENT_OID = 809, /* 2.16.840.1.113733.1.7.23.3.1.20 */ + CP_DIGICERT_NFSSP_MEDDEVHW_OID = 825, /* 2.16.840.1.113733.1.7.23.3.1.36 */ + + /* Entrust Managed Services NFI PKI OIDs */ + CP_ENTRUST_NFSSP_MEDIUMHW_OID = 1017, /* 2.16.840.1.114027.200.3.10.7.2 */ + CP_ENTRUST_NFSSP_MEDAUTH_OID = 1019, /* 2.16.840.1.114027.200.3.10.7.4 */ + CP_ENTRUST_NFSSP_PIVI_HW_OID = 1021, /* 2.16.840.1.114027.200.3.10.7.6 */ + CP_ENTRUST_NFSSP_PIVI_CONTENT_OID = 1024, /* 2.16.840.1.114027.200.3.10.7.9 */ + CP_ENTRUST_NFSSP_MEDDEVHW_OID = 1031, /* 2.16.840.1.114027.200.3.10.7.16 */ + + /* Exostar LLC PKI OIDs */ + CP_EXOSTAR_MEDIUMHW_SHA2_OID = 100424, /* 1.3.6.1.4.1.13948.1.1.1.6 */ + + /* IdenTrust NFI OIDs */ + CP_IDENTRUST_MEDIUMHW_SIGN_OID = 846, /* 2.16.840.1.113839.0.100.12.1 */ + CP_IDENTRUST_MEDIUMHW_ENC_OID = 847, /* 2.16.840.1.113839.0.100.12.2 */ + CP_IDENTRUST_PIVI_HW_ID_OID = 851, /* 2.16.840.1.113839.0.100.18.0 */ + CP_IDENTRUST_PIVI_HW_SIGN_OID = 852, /* 2.16.840.1.113839.0.100.18.1 */ + CP_IDENTRUST_PIVI_HW_ENC_OID = 853, /* 2.16.840.1.113839.0.100.18.2 */ + CP_IDENTRUST_PIVI_CONTENT_OID = 854, /* 2.16.840.1.113839.0.100.20.1 */ + + /* Lockheed Martin PKI OIDs */ + CP_LOCKHEED_MEDIUMHW_OID = 266, /* 1.3.6.1.4.1.103.100.1.1.3.3 */ + + /* Northrop Grumman PKI OIDs */ + CP_NORTHROP_MEDIUM_256_HW_OID = 654, /* 1.3.6.1.4.1.16334.509.2.8 */ + CP_NORTHROP_PIVI_256_HW_OID = 655, /* 1.3.6.1.4.1.16334.509.2.9 */ + CP_NORTHROP_PIVI_256_CONTENT_OID = 657, /* 1.3.6.1.4.1.16334.509.2.11 */ + CP_NORTHROP_MEDIUM_384_HW_OID = 660, /* 1.3.6.1.4.1.16334.509.2.14 */ + + /* Raytheon PKI OIDs */ + CP_RAYTHEON_MEDIUMHW_OID = 251, /* 1.3.6.1.4.1.1569.10.1.12 */ + CP_RAYTHEON_MEDDEVHW_OID = 257, /* 1.3.6.1.4.1.1569.10.1.18 */ + CP_RAYTHEON_SHA2_MEDIUMHW_OID = 433, /* 1.3.6.1.4.1.26769.10.1.12 */ + CP_RAYTHEON_SHA2_MEDDEVHW_OID = 439, /* 1.3.6.1.4.1.26769.10.1.18 */ + + /* WidePoint NFI PKI OIDs */ + CP_WIDEPOINT_MEDIUMHW_OID = 310, /* 1.3.6.1.4.1.3922.1.1.1.12 */ + CP_WIDEPOINT_PIVI_HW_OID = 316, /* 1.3.6.1.4.1.3922.1.1.1.18 */ + CP_WIDEPOINT_PIVI_CONTENT_OID = 318, /* 1.3.6.1.4.1.3922.1.1.1.20 */ + CP_WIDEPOINT_MEDDEVHW_OID = 336, /* 1.3.6.1.4.1.3922.1.1.1.38 */ + + /* Australian Defence Organisation PKI OIDs */ + CP_ADO_MEDIUM_OID = 293, /* 1.2.36.1.334.1.2.1.2 */ + CP_ADO_HIGH_OID = 294, /* 1.2.36.1.334.1.2.1.3 */ + CP_ADO_RESOURCE_MEDIUM_OID = 100294, /* 1.2.36.1.334.1.2.2.2 */ + + /* Comodo Ltd PKI OID */ + CP_COMODO_OID = 100293, /* 1.3.6.1.4.1.6449.1.2.1.3.4 */ + + /* Netherlands Ministry of Defence PKI OIDs */ + CP_NL_MOD_AUTH_OID = 496, /* 2.16.528.1.1003.1.2.5.1 */ + CP_NL_MOD_IRREFUT_OID = 100497, /* 2.16.528.1.1003.1.2.5.2 */ + CP_NL_MOD_CONFID_OID = 498, /* 2.16.528.1.1003.1.2.5.3 */ #endif /* WOLFSSL_FPKI */ WOLF_ENUM_DUMMY_LAST_ELEMENT(CertificatePolicy_Sum) }; @@ -2112,11 +2287,6 @@ struct DecodedCert { #ifdef WOLFSSL_SUBJ_INFO_ACC WC_BITFIELD extSubjInfoAccSet:1; #endif -#ifdef WOLFSSL_DUAL_ALG_CERTS - WC_BITFIELD extSapkiSet:1; - WC_BITFIELD extAltSigAlgSet:1; - WC_BITFIELD extAltSigValSet:1; -#endif /* WOLFSSL_DUAL_ALG_CERTS */ #ifdef WOLFSSL_SEP WC_BITFIELD extCertPolicyCrit:1; #endif @@ -2143,6 +2313,13 @@ struct DecodedCert { /* Alternative Signature Value */ byte *altSigValDer; int altSigValLen; + + WC_BITFIELD extSapkiSet:1; + WC_BITFIELD extAltSigAlgSet:1; + WC_BITFIELD extAltSigValSet:1; + WC_BITFIELD extSapkiCrit:1; + WC_BITFIELD extAltSigAlgCrit:1; + WC_BITFIELD extAltSigValCrit:1; #endif /* WOLFSSL_DUAL_ALG_CERTS */ }; @@ -2326,19 +2503,17 @@ WOLFSSL_LOCAL int CheckCertSignaturePubKey(const byte* cert, word32 certSz, word32 pubKeySz, int pubKeyOID); #endif /* OPENSSL_EXTRA || WOLFSSL_SMALL_CERT_VERIFY */ -#ifdef WOLFSSL_DUAL_ALG_CERTS -WOLFSSL_LOCAL int wc_ConfirmAltSignature( - const byte* buf, word32 bufSz, - const byte* key, word32 keySz, word32 keyOID, - const byte* sig, word32 sigSz, word32 sigOID, - void *heap); -#endif /* WOLFSSL_DUAL_ALG_CERTS */ #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \ (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT))) WOLFSSL_LOCAL int wc_CertGetPubKey(const byte* cert, word32 certSz, const unsigned char** pubKey, word32* pubKeySz); #endif - +WOLFSSL_LOCAL int ConfirmSignature(SignatureCtx* sigCtx, + const byte* buf, word32 bufSz, + const byte* key, word32 keySz, word32 keyOID, + const byte* sig, word32 sigSz, word32 sigOID, + const byte* sigParams, word32 sigParamsSz, + byte* rsaKeyIdx); #ifdef WOLFSSL_CERT_REQ WOLFSSL_LOCAL int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID); @@ -2355,6 +2530,7 @@ WOLFSSL_LOCAL int TryDecodeRPKToKey(DecodedCert* cert); WOLFSSL_LOCAL int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate); WOLFSSL_LOCAL const byte* OidFromId(word32 id, word32 type, word32* oidSz); +WOLFSSL_LOCAL Signer* findSignerByKeyHash(Signer *list, byte *hash); WOLFSSL_LOCAL Signer* findSignerByName(Signer *list, byte *hash); WOLFSSL_LOCAL int FillSigner(Signer* signer, DecodedCert* cert, int type, DerBuffer *der); WOLFSSL_LOCAL Signer* MakeSigner(void* heap); @@ -2687,6 +2863,14 @@ struct CertStatus { typedef struct OcspEntry OcspEntry; +#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) +#define OCSP_DIGEST WC_HASH_TYPE_SM3 +#elif defined(NO_SHA) +#define OCSP_DIGEST WC_HASH_TYPE_SHA256 +#else +#define OCSP_DIGEST WC_HASH_TYPE_SHA +#endif + #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) #define OCSP_DIGEST_SIZE WC_SM3_DIGEST_SIZE #elif defined(NO_SHA) @@ -2712,6 +2896,17 @@ struct OcspEntry WC_BITFIELD used:1; /* entry used */ }; +#define OCSP_RESPONDER_ID_KEY_SZ 20 +#if !defined(NO_SHA) +#define OCSP_RESPONDER_ID_HASH_TYPE WC_SHA +#else +#define OCSP_RESPONDER_ID_HASH_TYPE WC_SHA256 +#endif +enum responderIdType { + OCSP_RESPONDER_ID_INVALID = 0, + OCSP_RESPONDER_ID_NAME = 1, + OCSP_RESPONDER_ID_KEY = 2, +}; /* TODO: Long-term, it would be helpful if we made this struct and other OCSP structs conform to the ASN spec as described in RFC 6960. It will help with readability and with implementing OpenSSL compatibility API @@ -2723,6 +2918,12 @@ struct OcspResponse { byte* response; /* Pointer to beginning of OCSP Response */ word32 responseSz; /* length of the OCSP Response */ + enum responderIdType responderIdType; + union { + byte keyHash[OCSP_RESPONDER_ID_KEY_SZ]; + byte nameHash[KEYID_SIZE]; + } responderId ; + byte producedDate[MAX_DATE_SIZE]; /* Date at which this response was signed */ byte producedDateFormat; /* format of the producedDate */ @@ -2734,6 +2935,9 @@ struct OcspResponse { word32 sigSz; /* Length in octets for the sig */ word32 sigOID; /* OID for hash used for sig */ + byte* sigParams; + word32 sigParamsSz; + OcspEntry* single; /* chain of OCSP single responses */ byte* nonce; /* pointer to nonce inside ASN.1 response */ @@ -2742,9 +2946,6 @@ struct OcspResponse { byte* source; /* pointer to source buffer, not owned */ word32 maxIdx; /* max offset based on init size */ Signer* pendingCAs; -#ifdef OPENSSL_EXTRA - int verifyError; -#endif void* heap; }; @@ -2774,7 +2975,7 @@ WOLFSSL_LOCAL void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status, byte* source, word32 inSz, void* heap); WOLFSSL_LOCAL void FreeOcspResponse(OcspResponse* resp); WOLFSSL_LOCAL int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, - int noVerify); + int noVerifyCert, int noVerifySignature); WOLFSSL_LOCAL int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce, void* heap); @@ -2786,7 +2987,8 @@ WOLFSSL_LOCAL word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, WOLFSSL_LOCAL int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp); - +WOLFSSL_LOCAL int OcspDecodeCertID(const byte* input, word32* inOutIdx, word32 inSz, + OcspEntry* entry); #endif /* HAVE_OCSP */ diff --git a/src/wolfssl/wolfcrypt/asn_public.h b/src/wolfssl/wolfcrypt/asn_public.h index 1196c6a..08d9cc9 100644 --- a/src/wolfssl/wolfcrypt/asn_public.h +++ b/src/wolfssl/wolfcrypt/asn_public.h @@ -1,6 +1,6 @@ /* asn_public.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -182,7 +182,8 @@ enum CertType { SPHINCS_SMALL_LEVEL5_TYPE, ECC_PARAM_TYPE, CHAIN_CERT_TYPE, - PKCS7_TYPE + PKCS7_TYPE, + TRUSTED_CERT_TYPE }; @@ -526,12 +527,15 @@ typedef struct Cert { /* Subject Alternative Public Key Info */ byte *sapkiDer; int sapkiLen; + byte sapkiCrit; /* Alternative Signature Algorithm */ byte *altSigAlgDer; int altSigAlgLen; + byte altSigAlgCrit; /* Alternative Signature Value */ byte *altSigValDer; int altSigValLen; + byte altSigValCrit; #endif /* WOLFSSL_DUAL_ALG_CERTS */ #ifdef WOLFSSL_CERT_REQ char challengePw[CTC_NAME_SIZE]; @@ -550,6 +554,7 @@ typedef struct Cert { byte* der; /* Pointer to buffer of current DecodedCert cache */ void* heap; /* heap hint */ WC_BITFIELD basicConstSet:1; /* Indicator for when Basic Constraint is set */ + byte basicConstCrit; /* Indicator of criticality of Basic Constraints extension */ #ifdef WOLFSSL_ALLOW_ENCODING_CA_FALSE WC_BITFIELD isCaSet:1; /* Indicator for when isCA is set */ #endif @@ -728,6 +733,8 @@ WOLFSSL_API void wc_FreeDer(DerBuffer** pDer); word32 outputSz, byte *cipherIno, int type); #endif +WOLFSSL_API word32 wc_PkcsPad(byte* buf, word32 sz, word32 blockSz); + #ifndef NO_RSA WOLFSSL_API int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz, const byte** n, word32* nSz, const byte** e, word32* eSz); diff --git a/src/wolfssl/wolfcrypt/blake2-impl.h b/src/wolfssl/wolfcrypt/blake2-impl.h index 1a0db32..3f509c7 100644 --- a/src/wolfssl/wolfcrypt/blake2-impl.h +++ b/src/wolfssl/wolfcrypt/blake2-impl.h @@ -12,7 +12,7 @@ */ /* blake2-impl.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/blake2-int.h b/src/wolfssl/wolfcrypt/blake2-int.h index b048ca5..ec22921 100644 --- a/src/wolfssl/wolfcrypt/blake2-int.h +++ b/src/wolfssl/wolfcrypt/blake2-int.h @@ -12,7 +12,7 @@ */ /* blake2-int.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/blake2.h b/src/wolfssl/wolfcrypt/blake2.h index 1f4ac77..5d42c15 100644 --- a/src/wolfssl/wolfcrypt/blake2.h +++ b/src/wolfssl/wolfcrypt/blake2.h @@ -1,6 +1,6 @@ /* blake2.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -49,10 +49,12 @@ enum { #ifdef HAVE_BLAKE2B BLAKE2B_ID = WC_HASH_TYPE_BLAKE2B, BLAKE2B_256 = 32, /* 256 bit type, SSL default */ + WC_BLAKE2B_DIGEST_SIZE = 64, #endif #ifdef HAVE_BLAKE2S BLAKE2S_ID = WC_HASH_TYPE_BLAKE2S, - BLAKE2S_256 = 32 /* 256 bit type */ + BLAKE2S_256 = 32, /* 256 bit type */ + WC_BLAKE2S_DIGEST_SIZE = 32 #endif }; diff --git a/src/wolfssl/wolfcrypt/camellia.h b/src/wolfssl/wolfcrypt/camellia.h index efd187e..a31f764 100644 --- a/src/wolfssl/wolfcrypt/camellia.h +++ b/src/wolfssl/wolfcrypt/camellia.h @@ -27,7 +27,7 @@ /* camellia.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/chacha.h b/src/wolfssl/wolfcrypt/chacha.h index 1c6ae17..892b6ce 100644 --- a/src/wolfssl/wolfcrypt/chacha.h +++ b/src/wolfssl/wolfcrypt/chacha.h @@ -1,6 +1,6 @@ /* chacha.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/chacha20_poly1305.h b/src/wolfssl/wolfcrypt/chacha20_poly1305.h index ffa4031..7f9ac16 100644 --- a/src/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/src/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -1,6 +1,6 @@ /* chacha20_poly1305.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -95,7 +95,7 @@ int wc_ChaCha20Poly1305_Encrypt( byte* outCiphertext, byte outAuthTag[CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE]); -WOLFSSL_ABI WOLFSSL_API +WOLFSSL_ABI WOLFSSL_API WARN_UNUSED_RESULT int wc_ChaCha20Poly1305_Decrypt( const byte inKey[CHACHA20_POLY1305_AEAD_KEYSIZE], const byte inIV[CHACHA20_POLY1305_AEAD_IV_SIZE], @@ -104,7 +104,7 @@ int wc_ChaCha20Poly1305_Decrypt( const byte inAuthTag[CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE], byte* outPlaintext); -WOLFSSL_API +WOLFSSL_API WARN_UNUSED_RESULT int wc_ChaCha20Poly1305_CheckTag( const byte authTag[CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE], const byte authTagChk[CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE]); @@ -121,7 +121,7 @@ WOLFSSL_API int wc_ChaCha20Poly1305_UpdateAad(ChaChaPoly_Aead* aead, const byte* inAAD, word32 inAADLen); WOLFSSL_API int wc_ChaCha20Poly1305_UpdateData(ChaChaPoly_Aead* aead, const byte* inData, byte* outData, word32 dataLen); -WOLFSSL_API int wc_ChaCha20Poly1305_Final(ChaChaPoly_Aead* aead, +WOLFSSL_API WARN_UNUSED_RESULT int wc_ChaCha20Poly1305_Final(ChaChaPoly_Aead* aead, byte outAuthTag[CHACHA20_POLY1305_AEAD_AUTHTAG_SIZE]); #ifdef HAVE_XCHACHA @@ -140,7 +140,7 @@ WOLFSSL_API int wc_XChaCha20Poly1305_Encrypt( const byte *nonce, size_t nonce_len, const byte *key, size_t key_len); -WOLFSSL_API int wc_XChaCha20Poly1305_Decrypt( +WOLFSSL_API WARN_UNUSED_RESULT int wc_XChaCha20Poly1305_Decrypt( byte *dst, size_t dst_space, const byte *src, size_t src_len, const byte *ad, size_t ad_len, diff --git a/src/wolfssl/wolfcrypt/cmac.h b/src/wolfssl/wolfcrypt/cmac.h index 3dc6d9c..dd6e5b7 100644 --- a/src/wolfssl/wolfcrypt/cmac.h +++ b/src/wolfssl/wolfcrypt/cmac.h @@ -1,6 +1,6 @@ /* cmac.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/coding.h b/src/wolfssl/wolfcrypt/coding.h index 5aef5b1..ef87ab4 100644 --- a/src/wolfssl/wolfcrypt/coding.h +++ b/src/wolfssl/wolfcrypt/coding.h @@ -1,6 +1,6 @@ /* coding.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -36,6 +36,9 @@ WOLFSSL_API int Base64_Decode(const byte* in, word32 inLen, byte* out, word32* outLen); +WOLFSSL_API int Base64_Decode_nonCT(const byte* in, word32 inLen, byte* out, + word32* outLen); + #if defined(OPENSSL_EXTRA) || defined(SESSION_CERTS) || defined(WOLFSSL_KEY_GEN) \ || defined(WOLFSSL_CERT_GEN) || defined(HAVE_WEBSERVER) || !defined(NO_DSA) #ifndef WOLFSSL_BASE64_ENCODE diff --git a/src/wolfssl/wolfcrypt/compress.h b/src/wolfssl/wolfcrypt/compress.h index 2886b2b..c4d5c25 100644 --- a/src/wolfssl/wolfcrypt/compress.h +++ b/src/wolfssl/wolfcrypt/compress.h @@ -1,6 +1,6 @@ /* compress.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/cpuid.h b/src/wolfssl/wolfcrypt/cpuid.h index b7a5714..bb883cb 100644 --- a/src/wolfssl/wolfcrypt/cpuid.h +++ b/src/wolfssl/wolfcrypt/cpuid.h @@ -1,6 +1,6 @@ /* cpuid.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/cryptocb.h b/src/wolfssl/wolfcrypt/cryptocb.h index 976332f..f47cb0a 100644 --- a/src/wolfssl/wolfcrypt/cryptocb.h +++ b/src/wolfssl/wolfcrypt/cryptocb.h @@ -1,6 +1,6 @@ /* cryptocb.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -74,12 +74,12 @@ #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) #include #endif -#ifdef WOLFSSL_HAVE_KYBER - #include -#ifdef WOLFSSL_WC_KYBER - #include +#ifdef WOLFSSL_HAVE_MLKEM + #include +#ifdef WOLFSSL_WC_MLKEM + #include #elif defined(HAVE_LIBOQS) - #include + #include #endif #endif #if defined(HAVE_DILITHIUM) @@ -101,6 +101,38 @@ enum wc_CryptoCbCmdType { }; #endif + +#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM) +typedef struct { + Aes* aes; + byte* out; + const byte* in; + word32 sz; + const byte* nonce; + word32 nonceSz; + const byte* iv; + word32 ivSz; + byte* authTag; + word32 authTagSz; + const byte* authIn; + word32 authInSz; +} wc_CryptoCb_AesAuthEnc; +typedef struct { + Aes* aes; + byte* out; + const byte* in; + word32 sz; + const byte* nonce; + word32 nonceSz; + const byte* iv; + word32 ivSz; + const byte* authTag; + word32 authTagSz; + const byte* authIn; + word32 authInSz; +} wc_CryptoCb_AesAuthDec; +#endif + /* Crypto Information Structure for callbacks */ typedef struct wc_CryptoInfo { int algo_type; /* enum wc_AlgoType */ @@ -222,7 +254,7 @@ typedef struct wc_CryptoInfo { byte contextLen; } ed25519verify; #endif - #if defined(WOLFSSL_HAVE_KYBER) + #if defined(WOLFSSL_HAVE_MLKEM) struct { WC_RNG* rng; int size; @@ -262,6 +294,9 @@ typedef struct wc_CryptoInfo { WC_RNG* rng; void* key; int type; /* enum wc_PqcSignatureType */ + const byte* context; + byte contextLen; + word32 preHashType; /* enum wc_HashType */ } pqc_sign; struct { const byte* sig; @@ -271,6 +306,9 @@ typedef struct wc_CryptoInfo { int* res; void* key; int type; /* enum wc_PqcSignatureType */ + const byte* context; + byte contextLen; + word32 preHashType; /* enum wc_HashType */ } pqc_verify; struct { void* key; @@ -291,56 +329,12 @@ typedef struct wc_CryptoInfo { union { #endif #ifdef HAVE_AESGCM - struct { - Aes* aes; - byte* out; - const byte* in; - word32 sz; - const byte* iv; - word32 ivSz; - byte* authTag; - word32 authTagSz; - const byte* authIn; - word32 authInSz; - } aesgcm_enc; - struct { - Aes* aes; - byte* out; - const byte* in; - word32 sz; - const byte* iv; - word32 ivSz; - const byte* authTag; - word32 authTagSz; - const byte* authIn; - word32 authInSz; - } aesgcm_dec; + wc_CryptoCb_AesAuthEnc aesgcm_enc; + wc_CryptoCb_AesAuthDec aesgcm_dec; #endif /* HAVE_AESGCM */ #ifdef HAVE_AESCCM - struct { - Aes* aes; - byte* out; - const byte* in; - word32 sz; - const byte* nonce; - word32 nonceSz; - byte* authTag; - word32 authTagSz; - const byte* authIn; - word32 authInSz; - } aesccm_enc; - struct { - Aes* aes; - byte* out; - const byte* in; - word32 sz; - const byte* nonce; - word32 nonceSz; - const byte* authTag; - word32 authTagSz; - const byte* authIn; - word32 authInSz; - } aesccm_dec; + wc_CryptoCb_AesAuthEnc aesccm_enc; + wc_CryptoCb_AesAuthDec aesccm_dec; #endif /* HAVE_AESCCM */ #if defined(HAVE_AES_CBC) struct { @@ -381,7 +375,7 @@ typedef struct wc_CryptoInfo { } cipher; #endif /* !NO_AES || !NO_DES3 */ #if !defined(NO_SHA) || !defined(NO_SHA256) || \ - defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) + defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA3) struct { int type; /* enum wc_HashType */ const byte* in; @@ -550,7 +544,7 @@ WOLFSSL_LOCAL int wc_CryptoCb_Ed25519Verify(const byte* sig, word32 sigLen, const byte* context, byte contextLen); #endif /* HAVE_ED25519 */ -#if defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_HAVE_MLKEM) WOLFSSL_LOCAL int wc_CryptoCb_PqcKemGetDevId(int type, void* key); WOLFSSL_LOCAL int wc_CryptoCb_MakePqcKemKey(WC_RNG* rng, int type, @@ -563,7 +557,7 @@ WOLFSSL_LOCAL int wc_CryptoCb_PqcEncapsulate(byte* ciphertext, WOLFSSL_LOCAL int wc_CryptoCb_PqcDecapsulate(const byte* ciphertext, word32 ciphertextLen, byte* sharedSecret, word32 sharedSecretLen, int type, void* key); -#endif /* WOLFSSL_HAVE_KYBER */ +#endif /* WOLFSSL_HAVE_MLKEM */ #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) WOLFSSL_LOCAL int wc_CryptoCb_PqcSigGetDevId(int type, void* key); @@ -572,10 +566,12 @@ WOLFSSL_LOCAL int wc_CryptoCb_MakePqcSignatureKey(WC_RNG* rng, int type, int keySize, void* key); WOLFSSL_LOCAL int wc_CryptoCb_PqcSign(const byte* in, word32 inlen, byte* out, - word32 *outlen, WC_RNG* rng, int type, void* key); + word32 *outlen, const byte* context, byte contextLen, word32 preHashType, + WC_RNG* rng, int type, void* key); WOLFSSL_LOCAL int wc_CryptoCb_PqcVerify(const byte* sig, word32 siglen, - const byte* msg, word32 msglen, int* res, int type, void* key); + const byte* msg, word32 msglen, const byte* context, byte contextLen, + word32 preHashType, int* res, int type, void* key); WOLFSSL_LOCAL int wc_CryptoCb_PqcSignatureCheckPrivKey(void* key, int type, const byte* pubKey, word32 pubKeySz); diff --git a/src/wolfssl/wolfcrypt/curve25519.h b/src/wolfssl/wolfcrypt/curve25519.h index 4d18c56..f1bb574 100644 --- a/src/wolfssl/wolfcrypt/curve25519.h +++ b/src/wolfssl/wolfcrypt/curve25519.h @@ -1,6 +1,6 @@ /* curve25519.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -44,6 +44,7 @@ #define CURVE25519_KEYSIZE 32 #define CURVE25519_PUB_KEY_SIZE 32 +#define CURVE25519_MAX_KEY_TO_DER_SZ 82 /* for exported DER keys temp buffer */ #ifdef WOLFSSL_NAMES_STATIC typedef char curve25519_str[12]; @@ -91,6 +92,9 @@ struct curve25519_key { int devId; #endif void *heap; +#ifdef WOLFSSL_CURVE25519_BLINDING + WC_RNG* rng; +#endif #ifdef WOLFSSL_SE050 word32 keyId; byte keyIdSet; @@ -109,11 +113,23 @@ enum { WOLFSSL_API int wc_curve25519_make_pub(int public_size, byte* pub, int private_size, const byte* priv); +#ifdef WOLFSSL_CURVE25519_BLINDING +WOLFSSL_API +int wc_curve25519_make_pub_blind(int public_size, byte* pub, int private_size, + const byte* priv, WC_RNG* rng); +#endif WOLFSSL_API int wc_curve25519_generic(int public_size, byte* pub, int private_size, const byte* priv, int basepoint_size, const byte* basepoint); +#ifdef WOLFSSL_CURVE25519_BLINDING +WOLFSSL_API +int wc_curve25519_generic_blind(int public_size, byte* pub, + int private_size, const byte* priv, + int basepoint_size, const byte* basepoint, + WC_RNG* rng); +#endif WOLFSSL_API int wc_curve25519_make_priv(WC_RNG* rng, int keysize, byte* priv); @@ -139,13 +155,17 @@ int wc_curve25519_init_ex(curve25519_key* key, void* heap, int devId); WOLFSSL_API void wc_curve25519_free(curve25519_key* key); +#ifdef WOLFSSL_CURVE25519_BLINDING +WOLFSSL_API +int wc_curve25519_set_rng(curve25519_key* key, WC_RNG* rng); +#endif + #ifndef WC_NO_CONSTRUCTORS WOLFSSL_API curve25519_key* wc_curve25519_new(void* heap, int devId, int *result_code); WOLFSSL_API int wc_curve25519_delete(curve25519_key* key, curve25519_key** key_p); #endif -WOLFSSL_API /* raw key helpers */ WOLFSSL_API diff --git a/src/wolfssl/wolfcrypt/curve448.h b/src/wolfssl/wolfcrypt/curve448.h index b722727..756c8a3 100644 --- a/src/wolfssl/wolfcrypt/curve448.h +++ b/src/wolfssl/wolfcrypt/curve448.h @@ -1,6 +1,6 @@ /* curve448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/des3.h b/src/wolfssl/wolfcrypt/des3.h index 78a5164..2568857 100644 --- a/src/wolfssl/wolfcrypt/des3.h +++ b/src/wolfssl/wolfcrypt/des3.h @@ -1,6 +1,6 @@ /* des3.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/dh.h b/src/wolfssl/wolfcrypt/dh.h index 865baa3..81c5623 100644 --- a/src/wolfssl/wolfcrypt/dh.h +++ b/src/wolfssl/wolfcrypt/dh.h @@ -1,6 +1,6 @@ /* dh.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/dilithium.h b/src/wolfssl/wolfcrypt/dilithium.h index c43bc7e..306cef1 100644 --- a/src/wolfssl/wolfcrypt/dilithium.h +++ b/src/wolfssl/wolfcrypt/dilithium.h @@ -1,6 +1,6 @@ /* dilithium.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -117,6 +117,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE 1334 #define DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE 2588 +#define DILITHIUM_LEVEL2_BOTH_KEY_DER_SIZE 3904 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL2_BOTH_KEY_PEM_SIZE 5344 #define DILITHIUM_LEVEL3_KEY_SIZE 4032 #define DILITHIUM_LEVEL3_SIG_SIZE 3309 @@ -126,7 +130,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE 1974 #define DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE 4060 - +#define DILITHIUM_LEVEL3_BOTH_KEY_DER_SIZE 6016 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL3_BOTH_KEY_PEM_SIZE 8204 #define DILITHIUM_LEVEL5_KEY_SIZE 4896 #define DILITHIUM_LEVEL5_SIG_SIZE 4627 @@ -136,6 +143,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 #define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 +#define DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE 7520 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10239 #define ML_DSA_LEVEL2_KEY_SIZE 2560 #define ML_DSA_LEVEL2_SIG_SIZE 2420 @@ -145,6 +156,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL2_PUB_KEY_DER_SIZE DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL2_PRV_KEY_DER_SIZE DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL2_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL2_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL2_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL2_BOTH_KEY_PEM_SIZE #define ML_DSA_LEVEL3_KEY_SIZE 4032 #define ML_DSA_LEVEL3_SIG_SIZE 3309 @@ -154,6 +169,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL3_PUB_KEY_DER_SIZE DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL3_PRV_KEY_DER_SIZE DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL3_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL3_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL3_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL3_BOTH_KEY_PEM_SIZE #define ML_DSA_LEVEL5_KEY_SIZE 4896 #define ML_DSA_LEVEL5_SIG_SIZE 4627 @@ -163,6 +182,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL5_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL5_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE @@ -524,6 +547,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE 1334 #define DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE 2588 +#define DILITHIUM_LEVEL2_BOTH_KEY_DER_SIZE 3904 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL2_BOTH_KEY_PEM_SIZE 5344 #define DILITHIUM_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key #define DILITHIUM_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature @@ -533,6 +560,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE 1974 #define DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE 4060 +#define DILITHIUM_LEVEL3_BOTH_KEY_DER_SIZE 6016 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL3_BOTH_KEY_PEM_SIZE 8204 #define DILITHIUM_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key #define DILITHIUM_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature @@ -542,7 +573,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 #define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 - +#define DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE 7520 +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10239 #define ML_DSA_LEVEL2_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_secret_key #define ML_DSA_LEVEL2_SIG_SIZE OQS_SIG_ml_dsa_44_ipd_length_signature @@ -552,6 +586,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL2_PUB_KEY_DER_SIZE DILITHIUM_LEVEL2_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL2_PRV_KEY_DER_SIZE DILITHIUM_LEVEL2_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL2_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL2_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL2_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL2_BOTH_KEY_PEM_SIZE #define ML_DSA_LEVEL3_KEY_SIZE OQS_SIG_ml_dsa_65_ipd_length_secret_key #define ML_DSA_LEVEL3_SIG_SIZE OQS_SIG_ml_dsa_65_ipd_length_signature @@ -561,6 +599,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL3_PUB_KEY_DER_SIZE DILITHIUM_LEVEL3_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL3_PRV_KEY_DER_SIZE DILITHIUM_LEVEL3_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL3_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL3_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL3_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL3_BOTH_KEY_PEM_SIZE #define ML_DSA_LEVEL5_KEY_SIZE OQS_SIG_ml_dsa_87_ipd_length_secret_key #define ML_DSA_LEVEL5_SIG_SIZE OQS_SIG_ml_dsa_87_ipd_length_signature @@ -570,6 +612,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE +#define ML_DSA_LEVEL5_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define ML_DSA_LEVEL5_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE #endif @@ -580,6 +626,10 @@ /* Buffer sizes large enough to store exported DER encoded keys */ #define DILITHIUM_MAX_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define DILITHIUM_MAX_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE +#define DILITHIUM_MAX_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE +/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and + * the footer "-----END PRIVATE KEY-----" */ +#define DILITHIUM_MAX_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE #ifdef WOLF_PRIVATE_KEY_ID @@ -813,6 +863,10 @@ int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, byte* pub, word32 *pubSz); #endif +#ifndef WOLFSSL_DILITHIUM_NO_ASN1 +WOLFSSL_LOCAL int dilithium_get_oid_sum(dilithium_key* key, int* keyFormat); +#endif /* WOLFSSL_DILITHIUM_NO_ASN1 */ + #ifndef WOLFSSL_DILITHIUM_NO_ASN1 #if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) WOLFSSL_API int wc_Dilithium_PrivateKeyDecode(const byte* input, @@ -894,6 +948,13 @@ WOLFSSL_API int wc_Dilithium_PrivateKeyToDer(dilithium_key* key, byte* output, #define wc_MlDsaKey_Verify(key, sig, sigSz, msg, msgSz, res) \ wc_dilithium_verify_msg(sig, sigSz, msg, msgSz, res, key) +#define wc_MlDsaKey_PublicKeyToDer(key, output, len, withAlg) \ + wc_Dilithium_PublicKeyToDer(key, output, len, withAlg) + +#define wc_MlDsaKey_PrivateKeyToDer(key, output, len) \ + wc_Dilithium_PrivateKeyToDer(key, output, len) + + WOLFSSL_API int wc_MlDsaKey_GetPrivLen(MlDsaKey* key, int* len); WOLFSSL_API int wc_MlDsaKey_GetPubLen(MlDsaKey* key, int* len); WOLFSSL_API int wc_MlDsaKey_GetSigLen(MlDsaKey* key, int* len); diff --git a/src/wolfssl/wolfcrypt/dsa.h b/src/wolfssl/wolfcrypt/dsa.h index 1e92fd5..4ae42c3 100644 --- a/src/wolfssl/wolfcrypt/dsa.h +++ b/src/wolfssl/wolfcrypt/dsa.h @@ -1,6 +1,6 @@ /* dsa.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ecc.h b/src/wolfssl/wolfcrypt/ecc.h index 71a7a8b..04a7a66 100644 --- a/src/wolfssl/wolfcrypt/ecc.h +++ b/src/wolfssl/wolfcrypt/ecc.h @@ -1,6 +1,6 @@ /* ecc.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -287,7 +287,8 @@ typedef byte ecc_oid_t; #endif -#if !defined(WOLFSSL_ECC_CURVE_STATIC) && defined(USE_WINDOWS_API) +#if !defined(WOLFSSL_ECC_CURVE_STATIC) && defined(USE_WINDOWS_API) && \ + !defined(__WATCOMC__) /* MSC does something different with the pointers to the arrays than GCC, * and it causes the FIPS checksum to fail. In the case of windows builds, * store everything as arrays instead of pointers to strings. */ diff --git a/src/wolfssl/wolfcrypt/eccsi.h b/src/wolfssl/wolfcrypt/eccsi.h index 34e10bf..5136d13 100644 --- a/src/wolfssl/wolfcrypt/eccsi.h +++ b/src/wolfssl/wolfcrypt/eccsi.h @@ -1,6 +1,6 @@ /* eccsi.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ed25519.h b/src/wolfssl/wolfcrypt/ed25519.h index 8c660b2..f7367b5 100644 --- a/src/wolfssl/wolfcrypt/ed25519.h +++ b/src/wolfssl/wolfcrypt/ed25519.h @@ -1,6 +1,6 @@ /* ed25519.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -187,7 +187,6 @@ ed25519_key* wc_ed25519_new(void* heap, int devId, int *result_code); WOLFSSL_API int wc_ed25519_delete(ed25519_key* key, ed25519_key** key_p); #endif -WOLFSSL_API #ifdef HAVE_ED25519_KEY_IMPORT WOLFSSL_API diff --git a/src/wolfssl/wolfcrypt/ed448.h b/src/wolfssl/wolfcrypt/ed448.h index 9e2e890..e79a048 100644 --- a/src/wolfssl/wolfcrypt/ed448.h +++ b/src/wolfssl/wolfcrypt/ed448.h @@ -1,6 +1,6 @@ /* ed448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/error-crypt.h b/src/wolfssl/wolfcrypt/error-crypt.h index 5668783..f466e29 100644 --- a/src/wolfssl/wolfcrypt/error-crypt.h +++ b/src/wolfssl/wolfcrypt/error-crypt.h @@ -1,6 +1,6 @@ /* error-crypt.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -135,7 +135,8 @@ enum wolfCrypt_ErrorCodes { ED25519_KAT_FIPS_E = -163, /* Ed25519 Known answer test failure */ ED448_KAT_FIPS_E = -164, /* Ed448 Known answer test failure */ PBKDF2_KAT_FIPS_E = -165, /* PBKDF2 Known answer test failure */ - /* -166..-169 unused. */ + WC_KEY_MISMATCH_E = -166, /* Error for private/public key mismatch */ + /* -167..-169 unused. */ ECC_BAD_ARG_E = -170, /* ECC input argument of wrong type */ ASN_ECC_KEY_E = -171, /* ASN ECC bad input */ @@ -302,11 +303,12 @@ enum wolfCrypt_ErrorCodes { WC_SPAN2_FIRST_E = -1000, DEADLOCK_AVERTED_E = -1000, /* Deadlock averted -- retry the call */ + ASCON_AUTH_E = -1001, /* ASCON Authentication check failure */ - WC_SPAN2_LAST_E = -1000, /* Update to indicate last used error code */ + WC_SPAN2_LAST_E = -1001, /* Update to indicate last used error code */ WC_SPAN2_MIN_CODE_E = -1999, /* Last usable code in span 2 */ - WC_LAST_E = -1000, /* the last code used either here or in + WC_LAST_E = -1001, /* the last code used either here or in * error-ssl.h */ @@ -325,7 +327,7 @@ wc_static_assert((int)MIN_CODE_E <= (int)WC_SPAN2_MIN_CODE_E); #ifdef NO_ERROR_STRINGS #define wc_GetErrorString(error) "no support for error strings built in" #define wc_ErrorString(err, buf) \ - (void)err; XSTRNCPY((buf), wc_GetErrorString((err)), \ + (void)(err); XSTRNCPY((buf), wc_GetErrorString(err), \ WOLFSSL_MAX_ERROR_SZ); #else diff --git a/src/wolfssl/wolfcrypt/ext_lms.h b/src/wolfssl/wolfcrypt/ext_lms.h index 4120335..2c7d116 100644 --- a/src/wolfssl/wolfcrypt/ext_lms.h +++ b/src/wolfssl/wolfcrypt/ext_lms.h @@ -1,6 +1,6 @@ /* ext_lms.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ext_mlkem.h b/src/wolfssl/wolfcrypt/ext_mlkem.h new file mode 100644 index 0000000..53c6c7d --- /dev/null +++ b/src/wolfssl/wolfcrypt/ext_mlkem.h @@ -0,0 +1,74 @@ +/* ext_mlkem.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef EXT_KYBER_H +#define EXT_KYBER_H + +#ifdef WOLF_CRYPTO_CB + #include +#endif + +#ifdef WOLFSSL_HAVE_MLKEM +#include + +#if !defined(HAVE_LIBOQS) +#error "This code requires liboqs" +#endif + +#if defined(WOLFSSL_WC_MLKEM) +#error "This code is incompatible with wolfCrypt's implementation of Kyber." +#endif + +#if defined (HAVE_LIBOQS) + #include + + #ifndef WOLFSSL_NO_ML_KEM + #define EXT_KYBER_MAX_PRIV_SZ OQS_KEM_ml_kem_1024_length_secret_key + #define EXT_KYBER_MAX_PUB_SZ OQS_KEM_ml_kem_1024_length_public_key + #elif defined(WOLFSSL_MLKEM_KYBER) + #define EXT_KYBER_MAX_PRIV_SZ OQS_KEM_kyber_1024_length_secret_key + #define EXT_KYBER_MAX_PUB_SZ OQS_KEM_kyber_1024_length_public_key + #endif +#endif + +struct KyberKey { + /* Type of key: KYBER_LEVEL1 + * KYBER_LEVEL3 + * KYBER_LEVEL5 + * + * Note we don't save the variant (SHAKE vs AES) as that is decided at + * configuration time. */ + int type; + +#ifdef WOLF_CRYPTO_CB + void* devCtx; + int devId; +#endif + + byte priv[EXT_KYBER_MAX_PRIV_SZ]; + byte pub[EXT_KYBER_MAX_PUB_SZ]; +}; + +#if defined (HAVE_LIBOQS) +WOLFSSL_LOCAL int ext_mlkem_enabled(int id); +#endif +#endif /* WOLFSSL_HAVE_MLKEM */ +#endif /* EXT_KYBER_H */ diff --git a/src/wolfssl/wolfcrypt/ext_xmss.h b/src/wolfssl/wolfcrypt/ext_xmss.h index cb041bc..1c7ed35 100644 --- a/src/wolfssl/wolfcrypt/ext_xmss.h +++ b/src/wolfssl/wolfcrypt/ext_xmss.h @@ -1,6 +1,6 @@ /* ext_xmss.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/falcon.h b/src/wolfssl/wolfcrypt/falcon.h index a103034..45ae673 100644 --- a/src/wolfssl/wolfcrypt/falcon.h +++ b/src/wolfssl/wolfcrypt/falcon.h @@ -1,6 +1,6 @@ /* falcon.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/fe_448.h b/src/wolfssl/wolfcrypt/fe_448.h index 09ff150..fef9d17 100644 --- a/src/wolfssl/wolfcrypt/fe_448.h +++ b/src/wolfssl/wolfcrypt/fe_448.h @@ -1,6 +1,6 @@ /* fe448_448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -29,7 +29,8 @@ #include -#if defined(HAVE___UINT128_T) && !defined(NO_CURVED448_128BIT) +#if defined(HAVE___UINT128_T) && !defined(NO_CURVED448_128BIT) && \ + !defined(NO_INT128) #define CURVED448_128BIT #endif diff --git a/src/wolfssl/wolfcrypt/fe_operations.h b/src/wolfssl/wolfcrypt/fe_operations.h index 23928f2..dd029ec 100644 --- a/src/wolfssl/wolfcrypt/fe_operations.h +++ b/src/wolfssl/wolfcrypt/fe_operations.h @@ -1,6 +1,6 @@ /* fe_operations.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -76,6 +76,10 @@ Bounds on each t[i] vary depending on context. WOLFSSL_LOCAL void fe_init(void); WOLFSSL_LOCAL int curve25519(byte * q, const byte * n, const byte * p); +#ifdef WOLFSSL_CURVE25519_BLINDING +WOLFSSL_LOCAL int curve25519_blind(byte * q, const byte * n, const byte* mask, + const byte * p, const byte* rz); +#endif #endif /* default to be faster but take more memory */ diff --git a/src/wolfssl/wolfcrypt/fips_test.h b/src/wolfssl/wolfcrypt/fips_test.h index 6523753..16f170b 100644 --- a/src/wolfssl/wolfcrypt/fips_test.h +++ b/src/wolfssl/wolfcrypt/fips_test.h @@ -1,6 +1,6 @@ /* fips_test.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -72,7 +72,9 @@ enum FipsCastId { FIPS_CAST_ED25519 = 16, FIPS_CAST_ED448 = 17, FIPS_CAST_PBKDF2 = 18, - FIPS_CAST_COUNT = 19 + /* v7.0.0 + */ + FIPS_CAST_AES_ECB = 19, + FIPS_CAST_COUNT = 20 }; enum FipsCastStateId { diff --git a/src/wolfssl/wolfcrypt/ge_448.h b/src/wolfssl/wolfcrypt/ge_448.h index a9d4d47..82665cf 100644 --- a/src/wolfssl/wolfcrypt/ge_448.h +++ b/src/wolfssl/wolfcrypt/ge_448.h @@ -1,6 +1,6 @@ /* ge_448.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ge_operations.h b/src/wolfssl/wolfcrypt/ge_operations.h index 75d4b07..9a4d995 100644 --- a/src/wolfssl/wolfcrypt/ge_operations.h +++ b/src/wolfssl/wolfcrypt/ge_operations.h @@ -1,6 +1,6 @@ /* ge_operations.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/hash.h b/src/wolfssl/wolfcrypt/hash.h index ee001a9..02d99d4 100644 --- a/src/wolfssl/wolfcrypt/hash.h +++ b/src/wolfssl/wolfcrypt/hash.h @@ -1,6 +1,6 @@ /* hash.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -83,16 +83,6 @@ enum wc_MACAlgorithm { sm3_mac }; -enum wc_HashFlags { - WC_HASH_FLAG_NONE = 0x00000000, - WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ - WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ -#ifdef WOLFSSL_SHA3 - WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ -#endif - WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) -}; - /* hash union */ typedef union { #ifndef NO_MD5 diff --git a/src/wolfssl/wolfcrypt/hmac.h b/src/wolfssl/wolfcrypt/hmac.h index fd5d8d3..96da94c 100644 --- a/src/wolfssl/wolfcrypt/hmac.h +++ b/src/wolfssl/wolfcrypt/hmac.h @@ -1,6 +1,6 @@ /* hmac.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -124,6 +124,10 @@ typedef wc_Hashes wc_HmacHash; /* Hmac digest */ struct Hmac { wc_HmacHash hash; +#ifdef WOLFSSL_HMAC_COPY_HASH + wc_HmacHash i_hash; + wc_HmacHash o_hash; +#endif word32 ipad[WC_HMAC_BLOCK_SIZE / sizeof(word32)]; /* same block size all*/ word32 opad[WC_HMAC_BLOCK_SIZE / sizeof(word32)]; word32 innerHash[WC_MAX_DIGEST_SIZE / sizeof(word32)]; diff --git a/src/wolfssl/wolfcrypt/hpke.h b/src/wolfssl/wolfcrypt/hpke.h index 3bf61e5..cacfca6 100644 --- a/src/wolfssl/wolfcrypt/hpke.h +++ b/src/wolfssl/wolfcrypt/hpke.h @@ -1,6 +1,6 @@ /* hpke.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -120,9 +120,18 @@ WOLFSSL_API int wc_HpkeDeserializePublicKey(Hpke* hpke, void** key, const byte* in, word16 inSz); WOLFSSL_API void wc_HpkeFreeKey(Hpke* hpke, word16 kem, void* keypair, void* heap); +WOLFSSL_API int wc_HpkeInitSealContext(Hpke* hpke, HpkeBaseContext* context, + void* ephemeralKey, void* receiverKey, byte* info, word32 infoSz); +WOLFSSL_API int wc_HpkeContextSealBase(Hpke* hpke, HpkeBaseContext* context, + byte* aad, word32 aadSz, byte* plaintext, word32 ptSz, byte* out); WOLFSSL_API int wc_HpkeSealBase(Hpke* hpke, void* ephemeralKey, void* receiverKey, byte* info, word32 infoSz, byte* aad, word32 aadSz, byte* plaintext, word32 ptSz, byte* ciphertext); +WOLFSSL_API int wc_HpkeInitOpenContext(Hpke* hpke, HpkeBaseContext* context, + void* receiverKey, const byte* pubKey, word16 pubKeySz, byte* info, + word32 infoSz); +WOLFSSL_API int wc_HpkeContextOpenBase(Hpke* hpke, HpkeBaseContext* context, + byte* aad, word32 aadSz, byte* ciphertext, word32 ctSz, byte* out); WOLFSSL_API int wc_HpkeOpenBase(Hpke* hpke, void* receiverKey, const byte* pubKey, word16 pubKeySz, byte* info, word32 infoSz, byte* aad, word32 aadSz, byte* ciphertext, word32 ctSz, byte* plaintext); diff --git a/src/wolfssl/wolfcrypt/integer.h b/src/wolfssl/wolfcrypt/integer.h index e98cd35..68bda1f 100644 --- a/src/wolfssl/wolfcrypt/integer.h +++ b/src/wolfssl/wolfcrypt/integer.h @@ -1,6 +1,6 @@ /* integer.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/kdf.h b/src/wolfssl/wolfcrypt/kdf.h index 66b3a7a..d2fd388 100644 --- a/src/wolfssl/wolfcrypt/kdf.h +++ b/src/wolfssl/wolfcrypt/kdf.h @@ -1,6 +1,6 @@ /* kdf.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/libwolfssl_sources.h b/src/wolfssl/wolfcrypt/libwolfssl_sources.h new file mode 100644 index 0000000..474cbe1 --- /dev/null +++ b/src/wolfssl/wolfcrypt/libwolfssl_sources.h @@ -0,0 +1,50 @@ +/* libwolfssl_sources.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* In wolfSSL library sources, #include this file before any other #includes, to + * assure BUILDING_WOLFSSL is defined. + * + * This file also includes the common headers needed by all sources. + */ + +#ifndef LIBWOLFSSL_SOURCES_H +#define LIBWOLFSSL_SOURCES_H + +#if defined(TEST_LIBWOLFSSL_SOURCES_INCLUSION_SEQUENCE) && \ + defined(WOLF_CRYPT_SETTINGS_H) && \ + !defined(LIBWOLFSSL_SOURCES_ASM_H) + #error settings.h included before libwolfssl_sources.h. +#endif + +#ifndef BUILDING_WOLFSSL + #define BUILDING_WOLFSSL +#endif + +#if defined(HAVE_CONFIG_H) && !defined(WC_CONFIG_H_INCLUDED) + #include + #define WC_CONFIG_H_INCLUDED +#endif + +#include +#include +#include + +#endif /* LIBWOLFSSL_SOURCES_H */ diff --git a/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h b/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h new file mode 100644 index 0000000..a3d85c9 --- /dev/null +++ b/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h @@ -0,0 +1,48 @@ +/* libwolfssl_sources_asm.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* In wolfSSL library sources, #include this file before any other #includes, to + * assure BUILDING_WOLFSSL is defined. + * + * This file also includes the common headers needed by all sources. + */ + +#ifndef LIBWOLFSSL_SOURCES_ASM_H +#define LIBWOLFSSL_SOURCES_ASM_H + +#if defined(TEST_LIBWOLFSSL_SOURCES_INCLUSION_SEQUENCE) && \ + defined(WOLF_CRYPT_SETTINGS_H) && \ + !defined(LIBWOLFSSL_SOURCES_H) + #error settings.h included before libwolfssl_sources_asm.h. +#endif + +#ifndef BUILDING_WOLFSSL + #define BUILDING_WOLFSSL +#endif + +#if defined(HAVE_CONFIG_H) && !defined(WC_CONFIG_H_INCLUDED) + #include + #define WC_CONFIG_H_INCLUDED +#endif + +#include + +#endif /* LIBWOLFSSL_SOURCES_ASM_H */ diff --git a/src/wolfssl/wolfcrypt/lms.h b/src/wolfssl/wolfcrypt/lms.h index 1534fb1..ee4ccc5 100644 --- a/src/wolfssl/wolfcrypt/lms.h +++ b/src/wolfssl/wolfcrypt/lms.h @@ -1,6 +1,6 @@ /* lms.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -127,6 +127,9 @@ enum wc_LmsParm { WC_LMS_PARM_SHA256_192_L1_H10_W8 = 42, WC_LMS_PARM_SHA256_192_L1_H15_W2 = 43, WC_LMS_PARM_SHA256_192_L1_H15_W4 = 44, + WC_LMS_PARM_SHA256_192_L1_H20_W2 = 53, + WC_LMS_PARM_SHA256_192_L1_H20_W4 = 54, + WC_LMS_PARM_SHA256_192_L1_H20_W8 = 55, WC_LMS_PARM_SHA256_192_L2_H10_W2 = 45, WC_LMS_PARM_SHA256_192_L2_H10_W4 = 46, WC_LMS_PARM_SHA256_192_L2_H10_W8 = 47, @@ -183,6 +186,9 @@ WOLFSSL_API int wc_LmsKey_Verify(LmsKey * key, const byte * sig, word32 sigSz, const byte * msg, int msgSz); WOLFSSL_API const char * wc_LmsKey_ParmToStr(enum wc_LmsParm lmsParm); WOLFSSL_API const char * wc_LmsKey_RcToStr(enum wc_LmsRc lmsRc); + +WOLFSSL_API const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, + word32 privSz); #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/logging.h b/src/wolfssl/wolfcrypt/logging.h index a60f70b..49de701 100644 --- a/src/wolfssl/wolfcrypt/logging.h +++ b/src/wolfssl/wolfcrypt/logging.h @@ -1,6 +1,6 @@ /* logging.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -135,7 +135,7 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); WOLFSSL_LOCAL unsigned long wc_PeekErrorNodeLineData( const char **file, int *line, const char **data, int *flags, int (*ignore_err)(int err)); - WOLFSSL_LOCAL unsigned long wc_GetErrorNodeErr(void); + WOLFSSL_LOCAL int wc_GetErrorNodeErr(void); #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) WOLFSSL_API void wc_ERR_print_errors_fp(XFILE fp); WOLFSSL_API void wc_ERR_print_errors_cb(int (*cb)(const char *str, @@ -174,7 +174,7 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); #define WOLFSSL_STUB(m) \ WOLFSSL_MSG(WOLFSSL_LOG_CAT(wolfSSL Stub, m, not implemented)) WOLFSSL_API int WOLFSSL_IS_DEBUG_ON(void); -#if defined(XVSNPRINTF) +#if defined(XVSNPRINTF) && !defined(NO_WOLFSSL_MSG_EX) WOLFSSL_API void WOLFSSL_MSG_EX(const char* fmt, ...); #define HAVE_WOLFSSL_MSG_EX #else diff --git a/src/wolfssl/wolfcrypt/md2.h b/src/wolfssl/wolfcrypt/md2.h index 73be110..8fb5076 100644 --- a/src/wolfssl/wolfcrypt/md2.h +++ b/src/wolfssl/wolfcrypt/md2.h @@ -1,6 +1,6 @@ /* md2.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/md4.h b/src/wolfssl/wolfcrypt/md4.h index b253f8d..78c4275 100644 --- a/src/wolfssl/wolfcrypt/md4.h +++ b/src/wolfssl/wolfcrypt/md4.h @@ -1,6 +1,6 @@ /* md4.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/md5.h b/src/wolfssl/wolfcrypt/md5.h index 59d1f8d..93b906d 100644 --- a/src/wolfssl/wolfcrypt/md5.h +++ b/src/wolfssl/wolfcrypt/md5.h @@ -1,6 +1,6 @@ /* md5.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/mem_track.h b/src/wolfssl/wolfcrypt/mem_track.h index a69d1f0..205ec57 100644 --- a/src/wolfssl/wolfcrypt/mem_track.h +++ b/src/wolfssl/wolfcrypt/mem_track.h @@ -1,6 +1,6 @@ /* mem_track.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -596,7 +596,7 @@ static WC_INLINE int StackSizeCheck(struct func_args* args, thread_func tf) #endif #ifdef PTHREAD_STACK_MIN - if (stackSize < PTHREAD_STACK_MIN) + if (stackSize < (size_t)PTHREAD_STACK_MIN) stackSize = PTHREAD_STACK_MIN; #endif @@ -677,7 +677,7 @@ static WC_INLINE int StackSizeCheck_launch(struct func_args* args, struct stack_size_debug_context* shim_args; #ifdef PTHREAD_STACK_MIN - if (stackSize < PTHREAD_STACK_MIN) + if (stackSize < (size_t)PTHREAD_STACK_MIN) stackSize = PTHREAD_STACK_MIN; #endif diff --git a/src/wolfssl/wolfcrypt/memory.h b/src/wolfssl/wolfcrypt/memory.h index 179a8fd..5170a8c 100644 --- a/src/wolfssl/wolfcrypt/memory.h +++ b/src/wolfssl/wolfcrypt/memory.h @@ -1,6 +1,6 @@ /* memory.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/misc.h b/src/wolfssl/wolfcrypt/misc.h index 579c536..561c9a2 100644 --- a/src/wolfssl/wolfcrypt/misc.h +++ b/src/wolfssl/wolfcrypt/misc.h @@ -1,6 +1,6 @@ /* misc.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -134,6 +134,9 @@ WOLFSSL_LOCAL int CharIsWhiteSpace(char ch); WOLFSSL_LOCAL byte ctMaskGT(int a, int b); WOLFSSL_LOCAL byte ctMaskGTE(int a, int b); WOLFSSL_LOCAL int ctMaskIntGTE(int a, int b); +#ifdef WORD64_AVAILABLE +WOLFSSL_LOCAL word32 ctMaskWord32GTE(word32 a, word32 b); +#endif WOLFSSL_LOCAL byte ctMaskLT(int a, int b); WOLFSSL_LOCAL byte ctMaskLTE(int a, int b); WOLFSSL_LOCAL byte ctMaskEq(int a, int b); diff --git a/src/wolfssl/wolfcrypt/mlkem.h b/src/wolfssl/wolfcrypt/mlkem.h new file mode 100644 index 0000000..4a922a1 --- /dev/null +++ b/src/wolfssl/wolfcrypt/mlkem.h @@ -0,0 +1,374 @@ +/* mlkem.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/*! + \file wolfssl/wolfcrypt/mlkem.h + */ + +#ifndef WOLF_CRYPT_MLKEM_H +#define WOLF_CRYPT_MLKEM_H + +#include +#include + +#ifdef WOLFSSL_HAVE_MLKEM + +/* Number of co-efficients in polynomial. */ +#define MLKEM_N 256 + +/* Define algorithm type when not excluded. */ +#ifndef WOLFSSL_NO_ML_KEM + #if !defined(WOLFSSL_NO_ML_KEM_512) + #define WOLFSSL_WC_ML_KEM_512 + #endif + #if !defined(WOLFSSL_NO_ML_KEM_768) + #define WOLFSSL_WC_ML_KEM_768 + #endif + #if !defined(WOLFSSL_NO_ML_KEM_1024) + #define WOLFSSL_WC_ML_KEM_1024 + #endif + + #if !defined(WOLFSSL_WC_ML_KEM_512) && !defined(WOLFSSL_WC_ML_KEM_768) && \ + !defined(WOLFSSL_WC_ML_KEM_1024) + #error "No ML-KEM key size chosen." + #endif +#endif + +#ifdef WOLFSSL_MLKEM_KYBER + #ifndef WOLFSSL_NO_KYBER512 + #define WOLFSSL_KYBER512 + #define WOLFSSL_WC_ML_KEM_512 + #endif + #ifndef WOLFSSL_NO_KYBER768 + #define WOLFSSL_KYBER768 + #define WOLFSSL_WC_ML_KEM_768 + #endif + #ifndef WOLFSSL_NO_KYBER1024 + #define WOLFSSL_KYBER1024 + #define WOLFSSL_WC_ML_KEM_1024 + #endif + + #if !defined(WOLFSSL_KYBER512) && !defined(WOLFSSL_KYBER768) && \ + !defined(WOLFSSL_KYBER1024) + #error "No Kyber key size chosen." + #endif +#endif + +/* Size of a polynomial vector based on dimensions. */ +#define MLKEM_POLY_VEC_SZ(k) ((k) * WC_ML_KEM_POLY_SIZE) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define MLKEM_POLY_COMPRESSED_SZ(b) ((b) * (MLKEM_N / 8)) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define MLKEM_POLY_VEC_COMPRESSED_SZ(k, b) ((k) * ((b) * (MLKEM_N / 8))) + +#ifdef WOLFSSL_WC_ML_KEM_512 +#define WC_ML_KEM_512_K 2 +/* Size of a polynomial vector. */ +#define WC_ML_KEM_512_POLY_VEC_SZ MLKEM_POLY_VEC_SZ(WC_ML_KEM_512_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define WC_ML_KEM_512_POLY_COMPRESSED_SZ MLKEM_POLY_COMPRESSED_SZ(4) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ \ + MLKEM_POLY_VEC_COMPRESSED_SZ(WC_ML_KEM_512_K, 10) + +/* Public key size. */ +#define WC_ML_KEM_512_PUBLIC_KEY_SIZE \ + (WC_ML_KEM_512_POLY_VEC_SZ + WC_ML_KEM_SYM_SZ) +/* Private key size. */ +#define WC_ML_KEM_512_PRIVATE_KEY_SIZE \ + (WC_ML_KEM_512_POLY_VEC_SZ + WC_ML_KEM_512_PUBLIC_KEY_SIZE + \ + 2 * WC_ML_KEM_SYM_SZ) +/* Cipher text size. */ +#define WC_ML_KEM_512_CIPHER_TEXT_SIZE \ + (WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ + WC_ML_KEM_512_POLY_COMPRESSED_SZ) +#endif + +#ifdef WOLFSSL_WC_ML_KEM_768 +#define WC_ML_KEM_768_K 3 + +/* Size of a polynomial vector. */ +#define WC_ML_KEM_768_POLY_VEC_SZ MLKEM_POLY_VEC_SZ(WC_ML_KEM_768_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define WC_ML_KEM_768_POLY_COMPRESSED_SZ MLKEM_POLY_COMPRESSED_SZ(4) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ \ + MLKEM_POLY_VEC_COMPRESSED_SZ(WC_ML_KEM_768_K, 10) + +/* Public key size. */ +#define WC_ML_KEM_768_PUBLIC_KEY_SIZE \ + (WC_ML_KEM_768_POLY_VEC_SZ + WC_ML_KEM_SYM_SZ) +/* Private key size. */ +#define WC_ML_KEM_768_PRIVATE_KEY_SIZE \ + (WC_ML_KEM_768_POLY_VEC_SZ + WC_ML_KEM_768_PUBLIC_KEY_SIZE + \ + 2 * WC_ML_KEM_SYM_SZ) +/* Cipher text size. */ +#define WC_ML_KEM_768_CIPHER_TEXT_SIZE \ + (WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ + WC_ML_KEM_768_POLY_COMPRESSED_SZ) +#endif + +#ifdef WOLFSSL_WC_ML_KEM_1024 +#define WC_ML_KEM_1024_K 4 + +/* Size of a polynomial vector. */ +#define WC_ML_KEM_1024_POLY_VEC_SZ MLKEM_POLY_VEC_SZ(WC_ML_KEM_1024_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define WC_ML_KEM_1024_POLY_COMPRESSED_SZ MLKEM_POLY_COMPRESSED_SZ(5) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ \ + MLKEM_POLY_VEC_COMPRESSED_SZ(WC_ML_KEM_1024_K, 11) + +/* Public key size. */ +#define WC_ML_KEM_1024_PUBLIC_KEY_SIZE \ + (WC_ML_KEM_1024_POLY_VEC_SZ + WC_ML_KEM_SYM_SZ) +/* Private key size. */ +#define WC_ML_KEM_1024_PRIVATE_KEY_SIZE \ + (WC_ML_KEM_1024_POLY_VEC_SZ + WC_ML_KEM_1024_PUBLIC_KEY_SIZE + \ + 2 * WC_ML_KEM_SYM_SZ) +/* Cipher text size. */ +#define WC_ML_KEM_1024_CIPHER_TEXT_SIZE \ + (WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ + WC_ML_KEM_1024_POLY_COMPRESSED_SZ) +#endif + +#ifndef WC_ML_KEM_MAX_K +#ifdef WOLFSSL_WC_ML_KEM_1024 +#define WC_ML_KEM_MAX_K WC_ML_KEM_1024_K +#define WC_ML_KEM_MAX_PRIVATE_KEY_SIZE WC_ML_KEM_1024_PRIVATE_KEY_SIZE +#define WC_ML_KEM_MAX_PUBLIC_KEY_SIZE WC_ML_KEM_1024_PUBLIC_KEY_SIZE +#define WC_ML_KEM_MAX_CIPHER_TEXT_SIZE WC_ML_KEM_1024_CIPHER_TEXT_SIZE +#elif defined(WOLFSSL_WC_ML_KEM_768) +#define WC_ML_KEM_MAX_K WC_ML_KEM_768_K +#define WC_ML_KEM_MAX_PRIVATE_KEY_SIZE WC_ML_KEM_768_PRIVATE_KEY_SIZE +#define WC_ML_KEM_MAX_PUBLIC_KEY_SIZE WC_ML_KEM_768_PUBLIC_KEY_SIZE +#define WC_ML_KEM_MAX_CIPHER_TEXT_SIZE WC_ML_KEM_768_CIPHER_TEXT_SIZE +#elif defined(WOLFSSL_WC_ML_KEM_512) +#define WC_ML_KEM_MAX_K WC_ML_KEM_512_K +#define WC_ML_KEM_MAX_PRIVATE_KEY_SIZE WC_ML_KEM_512_PRIVATE_KEY_SIZE +#define WC_ML_KEM_MAX_PUBLIC_KEY_SIZE WC_ML_KEM_512_PUBLIC_KEY_SIZE +#define WC_ML_KEM_MAX_CIPHER_TEXT_SIZE WC_ML_KEM_512_CIPHER_TEXT_SIZE +#endif +#endif /* WC_ML_KEM_MAX_K */ + +#define KYBER_N MLKEM_N + +/* Size of a polynomial vector based on dimensions. */ +#define KYBER_POLY_VEC_SZ(k) ((k) * KYBER_POLY_SIZE) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define KYBER_POLY_COMPRESSED_SZ(b) ((b) * (KYBER_N / 8)) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define KYBER_POLY_VEC_COMPRESSED_SZ(k, b) ((k) * ((b) * (KYBER_N / 8))) + + +/* Kyber-512 parameters */ +/* Number of polynomials in a vector and vectors in a matrix. */ +#define KYBER512_K 2 + +/* Size of a polynomial vector. */ +#define KYBER512_POLY_VEC_SZ KYBER_POLY_VEC_SZ(KYBER512_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define KYBER512_POLY_COMPRESSED_SZ KYBER_POLY_COMPRESSED_SZ(4) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define KYBER512_POLY_VEC_COMPRESSED_SZ \ + KYBER_POLY_VEC_COMPRESSED_SZ(KYBER512_K, 10) + +/* Public key size. */ +#define KYBER512_PUBLIC_KEY_SIZE \ + (KYBER512_POLY_VEC_SZ + KYBER_SYM_SZ) +/* Private key size. */ +#define KYBER512_PRIVATE_KEY_SIZE \ + (KYBER512_POLY_VEC_SZ + KYBER512_PUBLIC_KEY_SIZE + 2 * KYBER_SYM_SZ) +/* Cipher text size. */ +#define KYBER512_CIPHER_TEXT_SIZE \ + (KYBER512_POLY_VEC_COMPRESSED_SZ + KYBER512_POLY_COMPRESSED_SZ) + +/* Kyber-768 parameters */ +/* Number of polynomials in a vector and vectors in a matrix. */ +#define KYBER768_K 3 + +/* Size of a polynomial vector. */ +#define KYBER768_POLY_VEC_SZ KYBER_POLY_VEC_SZ(KYBER768_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define KYBER768_POLY_COMPRESSED_SZ KYBER_POLY_COMPRESSED_SZ(4) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define KYBER768_POLY_VEC_COMPRESSED_SZ \ + KYBER_POLY_VEC_COMPRESSED_SZ(KYBER768_K, 10) + +/* Public key size. */ +#define KYBER768_PUBLIC_KEY_SIZE \ + (KYBER768_POLY_VEC_SZ + KYBER_SYM_SZ) +/* Private key size. */ +#define KYBER768_PRIVATE_KEY_SIZE \ + (KYBER768_POLY_VEC_SZ + KYBER768_PUBLIC_KEY_SIZE + 2 * KYBER_SYM_SZ) +/* Cipher text size. */ +#define KYBER768_CIPHER_TEXT_SIZE \ + (KYBER768_POLY_VEC_COMPRESSED_SZ + KYBER768_POLY_COMPRESSED_SZ) + +/* Kyber-1024 parameters */ +/* Number of polynomials in a vector and vectors in a matrix. */ +#define KYBER1024_K 4 + +/* Size of a polynomial vector. */ +#define KYBER1024_POLY_VEC_SZ KYBER_POLY_VEC_SZ(KYBER1024_K) +/* Size of a compressed polynomial based on bits per coefficient. */ +#define KYBER1024_POLY_COMPRESSED_SZ KYBER_POLY_COMPRESSED_SZ(5) +/* Size of a compressed vector polynomial based on dimensions and bits per + * coefficient. */ +#define KYBER1024_POLY_VEC_COMPRESSED_SZ \ + KYBER_POLY_VEC_COMPRESSED_SZ(KYBER1024_K, 11) + +/* Public key size. */ +#define KYBER1024_PUBLIC_KEY_SIZE \ + (KYBER1024_POLY_VEC_SZ + KYBER_SYM_SZ) +/* Private key size. */ +#define KYBER1024_PRIVATE_KEY_SIZE \ + (KYBER1024_POLY_VEC_SZ + KYBER1024_PUBLIC_KEY_SIZE + 2 * KYBER_SYM_SZ) +/* Cipher text size. */ +#define KYBER1024_CIPHER_TEXT_SIZE \ + (KYBER1024_POLY_VEC_COMPRESSED_SZ + KYBER1024_POLY_COMPRESSED_SZ) + + +/* Maximum dimensions and sizes of supported key types. */ +#ifdef WOLFSSL_KYBER1024 +#define KYBER_MAX_K KYBER1024_K +#define KYBER_MAX_PRIVATE_KEY_SIZE KYBER1024_PRIVATE_KEY_SIZE +#define KYBER_MAX_PUBLIC_KEY_SIZE KYBER1024_PUBLIC_KEY_SIZE +#define KYBER_MAX_CIPHER_TEXT_SIZE KYBER1024_CIPHER_TEXT_SIZE +#elif defined(WOLFSSL_KYBER768) +#define KYBER_MAX_K KYBER768_K +#define KYBER_MAX_PRIVATE_KEY_SIZE KYBER768_PRIVATE_KEY_SIZE +#define KYBER_MAX_PUBLIC_KEY_SIZE KYBER768_PUBLIC_KEY_SIZE +#define KYBER_MAX_CIPHER_TEXT_SIZE KYBER768_CIPHER_TEXT_SIZE +#elif defined(WOLFSSL_KYBER512) +#define KYBER_MAX_K KYBER512_K +#define KYBER_MAX_PRIVATE_KEY_SIZE KYBER512_PRIVATE_KEY_SIZE +#define KYBER_MAX_PUBLIC_KEY_SIZE KYBER512_PUBLIC_KEY_SIZE +#define KYBER_MAX_CIPHER_TEXT_SIZE KYBER512_CIPHER_TEXT_SIZE +#endif + +#define KYBER_SYM_SZ WC_ML_KEM_SYM_SZ +#define KYBER_SS_SZ WC_ML_KEM_SS_SZ +#define KYBER_MAKEKEY_RAND_SZ WC_ML_KEM_MAKEKEY_RAND_SZ +#define KYBER_ENC_RAND_SZ WC_ML_KEM_ENC_RAND_SZ +#define KYBER_POLY_SIZE WC_ML_KEM_POLY_SIZE + + +enum { + /* Types of Kyber keys. */ + WC_ML_KEM_512 = 0, + WC_ML_KEM_768 = 1, + WC_ML_KEM_1024 = 2, + + MLKEM_KYBER = 0x10, + KYBER512 = 0 | MLKEM_KYBER, + KYBER768 = 1 | MLKEM_KYBER, + KYBER1024 = 2 | MLKEM_KYBER, + + KYBER_LEVEL1 = KYBER512, + KYBER_LEVEL3 = KYBER768, + KYBER_LEVEL5 = KYBER1024, + + /* Symmetric data size. */ + WC_ML_KEM_SYM_SZ = 32, + /* Shared secret size. */ + WC_ML_KEM_SS_SZ = 32, + /* Size of random required for making a key. */ + WC_ML_KEM_MAKEKEY_RAND_SZ = 2 * WC_ML_KEM_SYM_SZ, + /* Size of random required for encapsulation. */ + WC_ML_KEM_ENC_RAND_SZ = WC_ML_KEM_SYM_SZ, + + /* Encoded polynomial size. */ + WC_ML_KEM_POLY_SIZE = 384, +}; + + +/* Different structures for different implementations. */ +typedef struct MlKemKey MlKemKey; + + +#ifdef __cplusplus + extern "C" { +#endif + +WOLFSSL_API int wc_MlKemKey_Init(MlKemKey* key, int type, void* heap, + int devId); +WOLFSSL_API int wc_MlKemKey_Free(MlKemKey* key); + +WOLFSSL_API int wc_MlKemKey_MakeKey(MlKemKey* key, WC_RNG* rng); +WOLFSSL_API int wc_MlKemKey_MakeKeyWithRandom(MlKemKey* key, + const unsigned char* rand, int len); + +WOLFSSL_API int wc_MlKemKey_CipherTextSize(MlKemKey* key, word32* len); +WOLFSSL_API int wc_MlKemKey_SharedSecretSize(MlKemKey* key, word32* len); + +WOLFSSL_API int wc_MlKemKey_Encapsulate(MlKemKey* key, unsigned char* ct, + unsigned char* ss, WC_RNG* rng); +WOLFSSL_API int wc_MlKemKey_EncapsulateWithRandom(MlKemKey* key, + unsigned char* ct, unsigned char* ss, const unsigned char* rand, int len); +WOLFSSL_API int wc_MlKemKey_Decapsulate(MlKemKey* key, unsigned char* ss, + const unsigned char* ct, word32 len); + +WOLFSSL_API int wc_MlKemKey_DecodePrivateKey(MlKemKey* key, + const unsigned char* in, word32 len); +WOLFSSL_API int wc_MlKemKey_DecodePublicKey(MlKemKey* key, + const unsigned char* in, word32 len); + +WOLFSSL_API int wc_MlKemKey_PrivateKeySize(MlKemKey* key, word32* len); +WOLFSSL_API int wc_MlKemKey_PublicKeySize(MlKemKey* key, word32* len); +WOLFSSL_API int wc_MlKemKey_EncodePrivateKey(MlKemKey* key, unsigned char* out, + word32 len); +WOLFSSL_API int wc_MlKemKey_EncodePublicKey(MlKemKey* key, unsigned char* out, + word32 len); + + +#define KyberKey MlKemKey + +#define wc_KyberKey_Init(type, key, heap, devId) \ + wc_MlKemKey_Init(key, type, heap, devId) +#define wc_KyberKey_Free wc_MlKemKey_Free +#define wc_KyberKey_MakeKey wc_MlKemKey_MakeKey +#define wc_KyberKey_MakeKeyWithRandom wc_MlKemKey_MakeKeyWithRandom +#define wc_KyberKey_CipherTextSize wc_MlKemKey_CipherTextSize +#define wc_KyberKey_SharedSecretSize wc_MlKemKey_SharedSecretSize +#define wc_KyberKey_Encapsulate wc_MlKemKey_Encapsulate +#define wc_KyberKey_EncapsulateWithRandom wc_MlKemKey_EncapsulateWithRandom +#define wc_KyberKey_Decapsulate wc_MlKemKey_Decapsulate +#define wc_KyberKey_DecodePrivateKey wc_MlKemKey_DecodePrivateKey +#define wc_KyberKey_DecodePublicKey wc_MlKemKey_DecodePublicKey +#define wc_KyberKey_PrivateKeySize wc_MlKemKey_PrivateKeySize +#define wc_KyberKey_PublicKeySize wc_MlKemKey_PublicKeySize +#define wc_KyberKey_EncodePrivateKey wc_MlKemKey_EncodePrivateKey +#define wc_KyberKey_EncodePublicKey wc_MlKemKey_EncodePublicKey + + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* WOLFSSL_HAVE_MLKEM */ + +#endif /* WOLF_CRYPT_MLKEM_H */ + diff --git a/src/wolfssl/wolfcrypt/mpi_class.h b/src/wolfssl/wolfcrypt/mpi_class.h index 831fae3..4879a61 100644 --- a/src/wolfssl/wolfcrypt/mpi_class.h +++ b/src/wolfssl/wolfcrypt/mpi_class.h @@ -1,6 +1,6 @@ /* mpi_class.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/mpi_superclass.h b/src/wolfssl/wolfcrypt/mpi_superclass.h index f27f61a..69dee6b 100644 --- a/src/wolfssl/wolfcrypt/mpi_superclass.h +++ b/src/wolfssl/wolfcrypt/mpi_superclass.h @@ -1,6 +1,6 @@ /* mpi_superclass.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pkcs11.h b/src/wolfssl/wolfcrypt/pkcs11.h index f252a00..36cfd9c 100644 --- a/src/wolfssl/wolfcrypt/pkcs11.h +++ b/src/wolfssl/wolfcrypt/pkcs11.h @@ -1,6 +1,6 @@ /* pkcs11.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pkcs12.h b/src/wolfssl/wolfcrypt/pkcs12.h index d7bf967..6dc6e9d 100644 --- a/src/wolfssl/wolfcrypt/pkcs12.h +++ b/src/wolfssl/wolfcrypt/pkcs12.h @@ -1,6 +1,6 @@ /* pkcs12.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -55,6 +55,9 @@ WOLFSSL_API int wc_i2d_PKCS12(WC_PKCS12* pkcs12, byte** der, int* derSz); WOLFSSL_API int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw, byte** pkey, word32* pkeySz, byte** cert, word32* certSz, WC_DerCertList** ca); +WOLFSSL_API int wc_PKCS12_parse_ex(WC_PKCS12* pkcs12, const char* psw, + byte** pkey, word32* pkeySz, byte** cert, word32* certSz, + WC_DerCertList** ca, int keepKeyHeader); WOLFSSL_LOCAL int wc_PKCS12_verify_ex(WC_PKCS12* pkcs12, const byte* psw, word32 pswSz); WOLFSSL_API WC_PKCS12* wc_PKCS12_create(char* pass, word32 passSz, diff --git a/src/wolfssl/wolfcrypt/pkcs7.h b/src/wolfssl/wolfcrypt/pkcs7.h index bc34147..efce67c 100644 --- a/src/wolfssl/wolfcrypt/pkcs7.h +++ b/src/wolfssl/wolfcrypt/pkcs7.h @@ -1,6 +1,6 @@ /* pkcs7.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -243,6 +243,7 @@ typedef int (*CallbackRsaSignRawDigest)(wc_PKCS7* pkcs7, byte* digest, int devId, int hashOID); #endif + /* Public Structure Warning: * Existing members must not be changed to maintain backwards compatibility! */ @@ -258,6 +259,7 @@ struct wc_PKCS7 { #ifdef ASN_BER_TO_DER byte* der; /* DER encoded version of message */ word32 derSz; + byte indefDepth; CallbackGetContent getContentCb; CallbackStreamOut streamOutCb; void* streamCtx; /* passed to getcontentCb and streamOutCb */ @@ -372,6 +374,19 @@ struct wc_PKCS7 { byte* customSKID; word16 customSKIDSz; + +#if !defined(NO_DES3) || !defined(NO_AES) + union { + #ifndef NO_AES + Aes* aes; + #endif + #ifndef NO_DES3 + Des* des; + Des3* des3; + #endif + } decryptKey; +#endif + /* !! NEW DATA MEMBERS MUST BE ADDED AT END !! */ }; diff --git a/src/wolfssl/wolfcrypt/poly1305.h b/src/wolfssl/wolfcrypt/poly1305.h index d4db487..c6adb0e 100644 --- a/src/wolfssl/wolfcrypt/poly1305.h +++ b/src/wolfssl/wolfcrypt/poly1305.h @@ -1,6 +1,6 @@ /* poly1305.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -98,7 +98,18 @@ typedef struct Poly1305 { word64 leftover; unsigned char buffer[POLY1305_BLOCK_SIZE]; unsigned char finished; +#elif defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_ARMASM_THUMB2) && \ + !defined(WOLFSSL_ARMASM_NO_NEON) + /* NEON implementation for ARM32 */ + word32 r[4]; + word32 h[6]; + word32 pad[4]; + word32 leftover; + unsigned char buffer[4*POLY1305_BLOCK_SIZE]; + word32 r_21[10]; + word32 r_43[10]; #elif defined(WOLFSSL_ARMASM) + /* ARM32 (non-NEON) and Thumb2 */ word32 r[4]; word32 h[5]; word32 pad[4]; @@ -173,7 +184,8 @@ void poly1305_blocks_thumb2_16(Poly1305* ctx, const unsigned char* m, void poly1305_blocks_arm32(Poly1305* ctx, const unsigned char *m, size_t bytes); void poly1305_block_arm32(Poly1305* ctx, const unsigned char *m); -void poly1305_blocks_arm32_16(Poly1305* ctx, const unsigned char* m, word32 len, +void poly1305_arm32_blocks(Poly1305* ctx, const unsigned char* m, word32 len); +void poly1305_arm32_blocks_16(Poly1305* ctx, const unsigned char* m, word32 len, int notLast); #endif void poly1305_set_key(Poly1305* ctx, const byte* key); diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h index de37936..4ae38a9 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h @@ -1,6 +1,6 @@ /* esp-sdk-lib.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index d49ef3e..ac48d97 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -1,6 +1,6 @@ /* esp32-crypt.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -216,8 +216,11 @@ enum { ** Turns on diagnostic messages for SHA mutex. Note that given verbosity, ** there may be TLS timing issues encountered. Use with caution. ** +** DEBUG_WOLFSSL_ESP32_HEAP +** Prints heap memory usage +** ** DEBUG_WOLFSSL_ESP32_UNFINISHED_HW -** This may be interesting in that HW may have been unnessearily locked +** This may be interesting in that HW may have been unnecessarily locked ** for hash that was never completed. (typically encountered at `free1` time) ** ** LOG_LOCAL_LEVEL @@ -234,11 +237,11 @@ enum { ** Shows a warning when mulm falls back for minimum number of bits. ** ** WOLFSSL_DEBUG_ESP_HW_MULTI_RSAMAX_BITS -** Shows a marning when multiplication math bits have exceeded hardware +** Shows a warning when multiplication math bits have exceeded hardware ** capabilities and will fall back to slower software. ** ** WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS -** Shows a marning when modular math bits have exceeded hardware capabilities +** Shows a warning when modular math bits have exceeded hardware capabilities ** and will fall back to slower software. ** ** NO_HW_MATH_TEST @@ -330,7 +333,7 @@ enum { #include #endif - #if ESP_IDF_VERSION_MAJOR >= 4 + #if ESP_IDF_VERSION_MAJOR == 4 || (ESP_IDF_VERSION_MAJOR == 5 && ESP_IDF_VERSION_MINOR < 4) #include #else #include @@ -375,9 +378,7 @@ enum { #include #endif - #if ESP_IDF_VERSION_MAJOR >= 4 - /* #include */ - #else + #if ESP_IDF_VERSION_MAJOR < 4 #include #endif @@ -411,9 +412,7 @@ enum { #include #endif - #if ESP_IDF_VERSION_MAJOR >= 4 - /* #include */ - #else + #if ESP_IDF_VERSION_MAJOR < 4 #include #endif @@ -447,9 +446,7 @@ enum { #include #endif - #if ESP_IDF_VERSION_MAJOR >= 4 - /* #include */ - #else + #if ESP_IDF_VERSION_MAJOR < 4 #include #endif @@ -719,24 +716,16 @@ extern "C" */ #ifndef NO_AES - #if ESP_IDF_VERSION_MAJOR >= 4 - #include "esp32/rom/aes.h" - #elif defined(CONFIG_IDF_TARGET_ESP8266) - /* no hardware includes for ESP8266*/ - #else - /* TODO: Confirm for older versions: */ - /* #include "rom/aes.h" */ - #endif + /* wolfSSL does not use Espressif rom/aes.h */ + struct Aes; /* see wolcrypt/aes.h */ - typedef enum tagES32_AES_PROCESS /* TODO what's this ? */ + typedef enum tagES32_AES_PROCESS { ESP32_AES_LOCKHW = 1, ESP32_AES_UPDATEKEY_ENCRYPT = 2, ESP32_AES_UPDATEKEY_DECRYPT = 3, ESP32_AES_UNLOCKHW = 4 } ESP32_AESPROCESS; - - struct Aes; /* see aes.h */ #if defined(WOLFSSL_HW_METRICS) WOLFSSL_LOCAL int esp_hw_show_aes_metrics(void); WOLFSSL_LOCAL int wc_esp32AesUnupportedLengthCountAdd(void); @@ -780,7 +769,14 @@ extern "C" #define SHA_CTX ETS_SHAContext - #if ESP_IDF_VERSION_MAJOR >= 4 + #if ESP_IDF_VERSION_MAJOR > 5 || (ESP_IDF_VERSION_MAJOR == 5 && ESP_IDF_VERSION_MINOR >= 4) + #include "rom/sha.h" + #if defined(CONFIG_IDF_TARGET_ESP32) + #define WC_ESP_SHA_TYPE enum SHA_TYPE + #else + #define WC_ESP_SHA_TYPE SHA_TYPE + #endif + #elif ESP_IDF_VERSION_MAJOR >= 4 #if defined(CONFIG_IDF_TARGET_ESP32) #include "esp32/rom/sha.h" #define WC_ESP_SHA_TYPE enum SHA_TYPE diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h index 6f6e203..cc8f48f 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h @@ -1,6 +1,6 @@ /* esp_crt_bundle.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/port/atmel/atmel.h b/src/wolfssl/wolfcrypt/port/atmel/atmel.h index c2f9940..d5c9458 100644 --- a/src/wolfssl/wolfcrypt/port/atmel/atmel.h +++ b/src/wolfssl/wolfcrypt/port/atmel/atmel.h @@ -1,6 +1,6 @@ /* atmel.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/pwdbased.h b/src/wolfssl/wolfcrypt/pwdbased.h index 9535b0a..9013401 100644 --- a/src/wolfssl/wolfcrypt/pwdbased.h +++ b/src/wolfssl/wolfcrypt/pwdbased.h @@ -1,6 +1,6 @@ /* pwdbased.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/random.h b/src/wolfssl/wolfcrypt/random.h index cc4c797..3b4533e 100644 --- a/src/wolfssl/wolfcrypt/random.h +++ b/src/wolfssl/wolfcrypt/random.h @@ -1,6 +1,6 @@ /* random.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/rc2.h b/src/wolfssl/wolfcrypt/rc2.h index 22b2ad1..22eb581 100644 --- a/src/wolfssl/wolfcrypt/rc2.h +++ b/src/wolfssl/wolfcrypt/rc2.h @@ -1,6 +1,6 @@ /* rc2.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/ripemd.h b/src/wolfssl/wolfcrypt/ripemd.h index d1a0e6f..54ede0d 100644 --- a/src/wolfssl/wolfcrypt/ripemd.h +++ b/src/wolfssl/wolfcrypt/ripemd.h @@ -1,6 +1,6 @@ /* ripemd.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/rsa.h b/src/wolfssl/wolfcrypt/rsa.h index dc23839..a01e18d 100644 --- a/src/wolfssl/wolfcrypt/rsa.h +++ b/src/wolfssl/wolfcrypt/rsa.h @@ -1,6 +1,6 @@ /* rsa.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sakke.h b/src/wolfssl/wolfcrypt/sakke.h index 0f7a75c..3ba7968 100644 --- a/src/wolfssl/wolfcrypt/sakke.h +++ b/src/wolfssl/wolfcrypt/sakke.h @@ -1,6 +1,6 @@ /* sakke.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/selftest.h b/src/wolfssl/wolfcrypt/selftest.h index 198013b..08b8884 100644 --- a/src/wolfssl/wolfcrypt/selftest.h +++ b/src/wolfssl/wolfcrypt/selftest.h @@ -1,6 +1,6 @@ /* selftest.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index 50eb0cb..9f4cd66 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -1,6 +1,6 @@ /* settings.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -47,6 +47,12 @@ extern "C" { #endif +#if defined(TEST_LIBWOLFSSL_SOURCES_INCLUSION_SEQUENCE) && \ + defined(BUILDING_WOLFSSL) && !defined(LIBWOLFSSL_SOURCES_H) && \ + !defined(LIBWOLFSSL_SOURCES_ASM_H) + #error settings.h included before libwolfssl_sources[_asm].h. +#endif + /* WOLFSSL_USE_OPTIONS_H directs wolfSSL to include options.h on behalf of * application code, rather than the application including it directly. This is * not defined when compiling wolfSSL library objects, which are configured @@ -438,9 +444,9 @@ /* old FIPS has only AES_BLOCK_SIZE. */ #if !defined(NO_AES) && (defined(HAVE_SELFTEST) || \ - (defined(HAVE_FIPS) && FIPS_VERSION3_LT(7,0,0))) + (defined(HAVE_FIPS) && FIPS_VERSION3_LT(6,0,0))) #define WC_AES_BLOCK_SIZE AES_BLOCK_SIZE -#endif /* !NO_AES && (HAVE_SELFTEST || FIPS_VERSION3_LT(7,0,0)) */ +#endif /* !NO_AES && (HAVE_SELFTEST || FIPS_VERSION3_LT(6,0,0)) */ #ifdef WOLFSSL_HARDEN_TLS #if WOLFSSL_HARDEN_TLS != 112 && WOLFSSL_HARDEN_TLS != 128 @@ -642,7 +648,7 @@ #define WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS #endif - #if defined(CONFIG_TLS_STACK_WOLFSSL) && (CONFIG_TLS_STACK_WOLFSSL) + #if defined(CONFIG_TLS_STACK_WOLFSSL) /* When using ESP-TLS, some old algorithms such as SHA1 are no longer * enabled in wolfSSL, except for the OpenSSL compatibility. So enable * that here: */ @@ -841,17 +847,19 @@ #endif /* ESP_ENABLE_WOLFSSH */ - /* Experimental Kyber. */ + /* ML-KEM. */ #ifdef CONFIG_ESP_WOLFSSL_ENABLE_KYBER + #define CONFIG_ESP_WOLFSSL_ENABLE_MLKEM + #endif + #ifdef CONFIG_ESP_WOLFSSL_ENABLE_MLKEM /* Kyber typically needs a minimum 10K stack */ - #define WOLFSSL_EXPERIMENTAL_SETTINGS - #define WOLFSSL_HAVE_KYBER - #define WOLFSSL_WC_KYBER + #define WOLFSSL_HAVE_MLKEM + #define WOLFSSL_WC_MLKEM #define WOLFSSL_SHA3 #if defined(CONFIG_IDF_TARGET_ESP8266) /* With limited RAM, we'll disable some of the Kyber sizes: */ - #define WOLFSSL_NO_KYBER1024 - #define WOLFSSL_NO_KYBER768 + #define WOLFSSL_NO_ML_KEM_1024 + #define WOLFSSL_NO_ML_KEM_768 #define NO_SESSION_CACHE #endif #endif @@ -1268,7 +1276,7 @@ #error "https://www.wolfssl.com/docs/porting-guide/" #endif #endif - #define WOLFSSL_USER_IO + #define HAVE_ECC #define NO_DH #define NO_SESSION_CACHE @@ -2090,13 +2098,14 @@ extern void uITRON4_free(void *p) ; #endif /* WOLFSSL_MAXQ1065 || WOLFSSL_MAXQ108X */ -#if defined(WOLFSSL_STM32F2) || defined(WOLFSSL_STM32F4) || \ - defined(WOLFSSL_STM32F7) || defined(WOLFSSL_STM32F1) || \ - defined(WOLFSSL_STM32L4) || defined(WOLFSSL_STM32L5) || \ - defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32H7) || \ - defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ - defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) || \ - defined(WOLFSSL_STM32G4) || defined(WOLFSSL_STM32MP13) +#if defined(WOLFSSL_STM32F2) || defined(WOLFSSL_STM32F4) || \ + defined(WOLFSSL_STM32F7) || defined(WOLFSSL_STM32F1) || \ + defined(WOLFSSL_STM32L4) || defined(WOLFSSL_STM32L5) || \ + defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32H7) || \ + defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ + defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) || \ + defined(WOLFSSL_STM32G4) || defined(WOLFSSL_STM32MP13) || \ + defined(WOLFSSL_STM32H7S) || defined(WOLFSSL_STM32WBA) #define SIZEOF_LONG_LONG 8 #ifndef CHAR_BIT @@ -2117,7 +2126,7 @@ extern void uITRON4_free(void *p) ; #if defined(WOLFSSL_STM32L4) || defined(WOLFSSL_STM32L5) || \ defined(WOLFSSL_STM32WB) || defined(WOLFSSL_STM32U5) || \ - defined(WOLFSSL_STM32WL) + defined(WOLFSSL_STM32WL) || defined(WOLFSSL_STM32WBA) #define NO_AES_192 /* hardware does not support 192-bit */ #endif #endif @@ -2144,6 +2153,8 @@ extern void uITRON4_free(void *p) ; #include "stm32f7xx_hal.h" #elif defined(WOLFSSL_STM32F1) #include "stm32f1xx_hal.h" + #elif defined(WOLFSSL_STM32H7S) + #include "stm32h7rsxx_hal.h" #elif defined(WOLFSSL_STM32H7) #include "stm32h7xx_hal.h" #elif defined(WOLFSSL_STM32WB) @@ -2164,6 +2175,8 @@ extern void uITRON4_free(void *p) ; #include "stm32mp13xx_hal.h" #include "stm32mp13xx_hal_conf.h" #endif + #elif defined(WOLFSSL_STM32WBA) + #include "stm32wbaxx_hal.h" #endif #if defined(WOLFSSL_CUBEMX_USE_LL) && defined(WOLFSSL_STM32L4) #include "stm32l4xx_ll_rng.h" @@ -2562,7 +2575,7 @@ extern void uITRON4_free(void *p) ; #if !defined(CONFIG_NET_SOCKETS_POSIX_NAMES) && !defined(CONFIG_POSIX_API) #define CONFIG_NET_SOCKETS_POSIX_NAMES #endif -#endif +#endif /* WOLFSSL_ZEPHYR */ #ifdef WOLFSSL_IMX6 #ifndef SIZEOF_LONG_LONG @@ -2840,6 +2853,10 @@ extern void uITRON4_free(void *p) ; /* default is SP Math. */ #define WOLFSSL_SP_MATH_ALL #endif +#elif defined(WOLFCRYPT_FIPS_RAND) + #ifndef NO_BIG_INT + #define NO_BIG_INT + #endif #else /* FIPS 140-2 or older */ /* Default to fast math (tfm.c), but allow heap math (integer.c) */ @@ -3153,6 +3170,11 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_AES_DIRECT #endif #endif + #ifdef WOLFSSL_AES_CTS + #if defined(NO_AES_CBC) || !defined(HAVE_AES_CBC) + #error "AES CTS requires AES CBC" + #endif + #endif #endif #if (defined(WOLFSSL_TLS13) && defined(WOLFSSL_NO_TLS12)) || \ @@ -3596,17 +3618,33 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_OLD_PRIME_CHECK #endif #ifndef WOLFSSL_TEST_SUBROUTINE - #define WOLFSSL_TEST_SUBROUTINE static + #ifdef LINUXKM_LKCAPI_REGISTER + #define WOLFSSL_TEST_SUBROUTINE + #else + #define WOLFSSL_TEST_SUBROUTINE static + #endif + #endif + #ifdef LINUXKM_LKCAPI_REGISTER + #define WC_TEST_EXPORT_SUBTESTS #endif #undef HAVE_PTHREAD + /* linuxkm uses linux/string.h, included by linuxkm_wc_port.h. */ #undef HAVE_STRINGS_H + /* linuxkm uses linux/limits.h, included by linuxkm_wc_port.h. */ + #undef HAVE_LIMITS_H #undef HAVE_ERRNO_H #undef HAVE_THREAD_LS #undef HAVE_ATEXIT #undef WOLFSSL_HAVE_MIN #undef WOLFSSL_HAVE_MAX - #define SIZEOF_LONG 8 - #define SIZEOF_LONG_LONG 8 + #undef WOLFSSL_HAVE_ASSERT_H + #define WOLFSSL_NO_ASSERT_H + #ifndef SIZEOF_LONG + #define SIZEOF_LONG 8 + #endif + #ifndef SIZEOF_LONG_LONG + #define SIZEOF_LONG_LONG 8 + #endif #define CHAR_BIT 8 #ifndef WOLFSSL_SP_DIV_64 #define WOLFSSL_SP_DIV_64 @@ -3617,6 +3655,40 @@ extern void uITRON4_free(void *p) ; #ifdef __PIE__ #define WC_NO_INTERNAL_FUNCTION_POINTERS #endif + + #ifndef NO_OLD_WC_NAMES + #define NO_OLD_WC_NAMES + #endif + #ifndef NO_OLD_SHA_NAMES + #define NO_OLD_SHA_NAMES + #endif + #ifndef NO_OLD_MD5_NAME + #define NO_OLD_MD5_NAME + #endif + #ifndef OPENSSL_COEXIST + #define OPENSSL_COEXIST + #endif + #ifndef NO_OLD_SSL_NAMES + #define NO_OLD_SSL_NAMES + #endif + #undef WOLFSSL_MIN_AUTH_TAG_SZ + #define WOLFSSL_MIN_AUTH_TAG_SZ 4 + + #if defined(LINUXKM_LKCAPI_REGISTER) && !defined(WOLFSSL_ASN_INT_LEAD_0_ANY) + /* kernel 5.10 crypto manager tests key(s) that fail unless leading + * bytes are tolerated in GetASN_Integer(). + */ + #define WOLFSSL_ASN_INT_LEAD_0_ANY + #endif + + #ifdef CONFIG_KASAN + #ifndef WC_SANITIZE_DISABLE + #define WC_SANITIZE_DISABLE() kasan_disable_current() + #endif + #ifndef WC_SANITIZE_ENABLE + #define WC_SANITIZE_ENABLE() kasan_enable_current() + #endif + #endif #endif @@ -4074,7 +4146,7 @@ extern void uITRON4_free(void *p) ; #endif #endif -#ifdef WOLFSSL_HAVE_KYBER +#ifdef WOLFSSL_HAVE_MLKEM #define HAVE_PQC #endif @@ -4089,23 +4161,27 @@ extern void uITRON4_free(void *p) ; #ifndef WOLFSSL_NO_SPHINCS #define HAVE_SPHINCS #endif -#ifndef WOLFSSL_HAVE_KYBER - #define WOLFSSL_HAVE_KYBER +#ifndef WOLFSSL_HAVE_MLKEM + #define WOLFSSL_HAVE_MLKEM #define WOLFSSL_KYBER512 #define WOLFSSL_KYBER768 #define WOLFSSL_KYBER1024 + #define WOLFSSL_WC_ML_KEM_512 + #define WOLFSSL_WC_ML_KEM_768 + #define WOLFSSL_WC_ML_KEM_1024 #endif #endif #if (defined(HAVE_LIBOQS) || \ defined(HAVE_LIBXMSS) || \ defined(HAVE_LIBLMS) || \ - defined(WOLFSSL_DUAL_ALG_CERTS)) && \ + defined(WOLFSSL_DUAL_ALG_CERTS) || \ + defined(HAVE_ASCON)) && \ !defined(WOLFSSL_EXPERIMENTAL_SETTINGS) #error Experimental settings without WOLFSSL_EXPERIMENTAL_SETTINGS #endif -#if defined(HAVE_PQC) && !defined(HAVE_LIBOQS) && !defined(WOLFSSL_HAVE_KYBER) +#if defined(HAVE_PQC) && !defined(HAVE_LIBOQS) && !defined(WOLFSSL_HAVE_MLKEM) #error Please do not define HAVE_PQC yourself. #endif @@ -4361,6 +4437,11 @@ extern void uITRON4_free(void *p) ; #endif #endif /* HAVE_ENTROPY_MEMUSE */ +#if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER) && \ + !defined(WOLFCRYPT_ONLY) && !defined(NO_TLS) +#error "If TLS is enabled please make sure either client or server is enabled." +#endif + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/src/wolfssl/wolfcrypt/sha.h b/src/wolfssl/wolfcrypt/sha.h index 063784e..54b0833 100644 --- a/src/wolfssl/wolfcrypt/sha.h +++ b/src/wolfssl/wolfcrypt/sha.h @@ -1,6 +1,6 @@ /* sha.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sha256.h b/src/wolfssl/wolfcrypt/sha256.h index b5534d4..7a064a0 100644 --- a/src/wolfssl/wolfcrypt/sha256.h +++ b/src/wolfssl/wolfcrypt/sha256.h @@ -1,6 +1,6 @@ /* sha256.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -264,10 +264,14 @@ struct wc_Sha256 { WOLFSSL_API int wc_InitSha256(wc_Sha256* sha); WOLFSSL_API int wc_InitSha256_ex(wc_Sha256* sha, void* heap, int devId); WOLFSSL_API int wc_Sha256Update(wc_Sha256* sha, const byte* data, word32 len); + +#if !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_AFALG_HASH) WOLFSSL_API int wc_Sha256FinalRaw(wc_Sha256* sha256, byte* hash); +#endif WOLFSSL_API int wc_Sha256Final(wc_Sha256* sha256, byte* hash); WOLFSSL_API void wc_Sha256Free(wc_Sha256* sha256); -#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) +#if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) && \ + !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_AFALG_HASH) WOLFSSL_API int wc_Sha256Transform(wc_Sha256* sha, const unsigned char* data); #endif #if defined(WOLFSSL_HAVE_LMS) && !defined(WOLFSSL_LMS_FULL_HASH) diff --git a/src/wolfssl/wolfcrypt/sha3.h b/src/wolfssl/wolfcrypt/sha3.h index 2491acd..724719a 100644 --- a/src/wolfssl/wolfcrypt/sha3.h +++ b/src/wolfssl/wolfcrypt/sha3.h @@ -1,6 +1,6 @@ /* sha3.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -225,6 +225,7 @@ WOLFSSL_LOCAL void sha3_block_n_bmi2(word64* s, const byte* data, word32 n, word64 c); WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); WOLFSSL_LOCAL void sha3_block_avx2(word64* s); +WOLFSSL_LOCAL void sha3_blocksx4_avx2(word64* s); WOLFSSL_LOCAL void BlockSha3(word64 *s); #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 diff --git a/src/wolfssl/wolfcrypt/sha512.h b/src/wolfssl/wolfcrypt/sha512.h index 5033a2c..593177e 100644 --- a/src/wolfssl/wolfcrypt/sha512.h +++ b/src/wolfssl/wolfcrypt/sha512.h @@ -1,6 +1,6 @@ /* sha512.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -224,7 +224,7 @@ struct wc_Sha512 { #endif /* HAVE_FIPS */ -#ifdef WOLFSSL_SHA512 +#if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384) #ifdef WOLFSSL_ARMASM #ifdef __aarch64__ diff --git a/src/wolfssl/wolfcrypt/signature.h b/src/wolfssl/wolfcrypt/signature.h index 51c07af..7d9a1d4 100644 --- a/src/wolfssl/wolfcrypt/signature.h +++ b/src/wolfssl/wolfcrypt/signature.h @@ -1,6 +1,6 @@ /* signature.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/siphash.h b/src/wolfssl/wolfcrypt/siphash.h index 6b75a46..26cd821 100644 --- a/src/wolfssl/wolfcrypt/siphash.h +++ b/src/wolfssl/wolfcrypt/siphash.h @@ -1,6 +1,6 @@ /* siphash.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm2.h b/src/wolfssl/wolfcrypt/sm2.h index ae9885e..fb90aaa 100644 --- a/src/wolfssl/wolfcrypt/sm2.h +++ b/src/wolfssl/wolfcrypt/sm2.h @@ -1,6 +1,6 @@ /* sm2.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm3.h b/src/wolfssl/wolfcrypt/sm3.h index b24fcf4..e7e8b0e 100644 --- a/src/wolfssl/wolfcrypt/sm3.h +++ b/src/wolfssl/wolfcrypt/sm3.h @@ -1,6 +1,6 @@ /* sm3.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sm4.h b/src/wolfssl/wolfcrypt/sm4.h index 84a8166..3cebb79 100644 --- a/src/wolfssl/wolfcrypt/sm4.h +++ b/src/wolfssl/wolfcrypt/sm4.h @@ -1,6 +1,6 @@ /* sm4.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sp.h b/src/wolfssl/wolfcrypt/sp.h index 3ede752..9e7a9c9 100644 --- a/src/wolfssl/wolfcrypt/sp.h +++ b/src/wolfssl/wolfcrypt/sp.h @@ -1,6 +1,6 @@ /* sp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/sp_int.h b/src/wolfssl/wolfcrypt/sp_int.h index dc707d2..7385e68 100644 --- a/src/wolfssl/wolfcrypt/sp_int.h +++ b/src/wolfssl/wolfcrypt/sp_int.h @@ -1,6 +1,6 @@ /* sp_int.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -210,8 +210,10 @@ extern "C" { #elif defined(WOLFSSL_SP_X86_64_ASM) || defined(WOLFSSL_SP_X86_64) #if SP_ULONG_BITS == 64 || SP_ULLONG_BITS == 64 #define SP_WORD_SIZE 64 - #define HAVE_INTEL_AVX1 - #ifndef NO_AVX2_SUPPORT + #ifndef HAVE_INTEL_AVX1 + #define HAVE_INTEL_AVX1 + #endif + #if !defined(NO_AVX2_SUPPORT) && !defined(HAVE_INTEL_AVX2) #define HAVE_INTEL_AVX2 #endif #elif SP_ULONG_BITS == 32 @@ -262,7 +264,7 @@ extern "C" { #define SP_WORD_SIZEOF (SP_WORD_SIZE / 8) /* Define the types used. */ -#ifdef HAVE___UINT128_T +#if defined(HAVE___UINT128_T) && !defined(NO_INT128) #ifdef __SIZEOF_INT128__ typedef __uint128_t sp_uint128; typedef __int128_t sp_int128; @@ -385,11 +387,11 @@ extern "C" { /* Non-blocking ECC operation context. */ typedef struct sp_ecc_ctx { #ifdef WOLFSSL_SP_521 - byte data[66*80]; /* stack data */ + XALIGNED(4) byte data[66*80]; /* stack data */ #elif defined(WOLFSSL_SP_384) - byte data[48*80]; /* stack data */ + XALIGNED(4) byte data[48*80]; /* stack data */ #else - byte data[32*80]; /* stack data */ + XALIGNED(4) byte data[32*80]; /* stack data */ #endif } sp_ecc_ctx_t; #endif @@ -702,7 +704,10 @@ typedef struct sp_ecc_ctx { do { \ int ii; \ if ((a)->used > 0) { \ - for (ii = (int)(a)->used - 1; ii >= 0 && (a)->dp[ii] == 0; ii--) { \ + for (ii = (int)(a)->used - 1; ii >= 0; ii--) { \ + if ((a)->dp[ii] != 0) { \ + break; \ + } \ } \ (a)->used = (wc_mp_size_t)(ii + 1); \ } \ diff --git a/src/wolfssl/wolfcrypt/sphincs.h b/src/wolfssl/wolfcrypt/sphincs.h index 6dd3a8e..f1487dd 100644 --- a/src/wolfssl/wolfcrypt/sphincs.h +++ b/src/wolfssl/wolfcrypt/sphincs.h @@ -1,6 +1,6 @@ /* sphincs.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/srp.h b/src/wolfssl/wolfcrypt/srp.h index d1307c7..7607765 100644 --- a/src/wolfssl/wolfcrypt/srp.h +++ b/src/wolfssl/wolfcrypt/srp.h @@ -1,6 +1,6 @@ /* srp.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/tfm.h b/src/wolfssl/wolfcrypt/tfm.h index 80b7f0f..718077c 100644 --- a/src/wolfssl/wolfcrypt/tfm.h +++ b/src/wolfssl/wolfcrypt/tfm.h @@ -1,6 +1,6 @@ /* tfm.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index f8042cf..3ff9ec5 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -1,6 +1,6 @@ /* types.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -150,9 +150,17 @@ decouple library dependencies with standard string, memory and so on. /* The C standards don't define empty aggregates, but gcc and clang do. * We need to accommodate them for one of the same reasons C++ does -- * conditionally empty aggregates, e.g. in hash.h. + * + * Nonetheless, in C++, empty aggregates wind up with size 1. If we use + * the [0] construct and the header is compiled by clang++, it warns + * "struct has size 0 in C, size 1 in C++ [-Wextern-c-compat]", despite + * the extern "C" wrapper. We sidestep this warning by recognizing + * here that C++ doesn't support truly empty aggregates. LLVM, for its part, + * deprecates compilation of C code as C++ using clang++. */ #if !defined(WOLF_C89) && defined(__GNUC__) && \ !defined(__STRICT_ANSI__) && \ + !defined(__cplusplus) && \ defined(HAVE_ANONYMOUS_INLINE_AGGREGATES) #define HAVE_EMPTY_AGGREGATES 1 #endif @@ -212,10 +220,10 @@ decouple library dependencies with standard string, memory and so on. /* try to set SIZEOF_LONG or SIZEOF_LONG_LONG if user didn't */ #if defined(_WIN32) || defined(HAVE_LIMITS_H) + #include /* make sure both SIZEOF_LONG_LONG and SIZEOF_LONG are set, * otherwise causes issues with CTC_SETTINGS */ #if !defined(SIZEOF_LONG_LONG) || !defined(SIZEOF_LONG) - #include #if !defined(SIZEOF_LONG) && defined(ULONG_MAX) && \ (ULONG_MAX == 0xffffffffUL) #define SIZEOF_LONG 4 @@ -244,7 +252,8 @@ decouple library dependencies with standard string, memory and so on. #endif #endif - #if (defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ + #if (defined(_MSC_VER) && (_MSC_VER == 1200)) || /* MSVC6 */ \ + (defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ defined(__BCPLUSPLUS__) || \ (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) /* windows types */ @@ -319,12 +328,15 @@ decouple library dependencies with standard string, memory and so on. #if defined(NO_64BIT) typedef word32 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 2 #undef WORD64_AVAILABLE #else #ifdef WC_64BIT_CPU typedef word64 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 3 #else typedef word32 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 2 #ifdef WORD64_AVAILABLE #define WOLFCRYPT_SLOW_WORD64 #endif @@ -336,12 +348,14 @@ decouple library dependencies with standard string, memory and so on. #undef WORD64_AVAILABLE #endif typedef word16 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 1 #define MP_16BIT /* for mp_int, mp_word needs to be twice as big as \ * mp_digit, no 64 bit type so make mp_digit 16 bit */ #else #undef WORD64_AVAILABLE typedef word32 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 2 #define MP_16BIT /* for mp_int, mp_word needs to be twice as big as \ * mp_digit, no 64 bit type so make mp_digit 16 bit */ #endif @@ -406,7 +420,7 @@ typedef struct w64wrapper { /* set up thread local storage if available */ #ifdef HAVE_THREAD_LS - #if defined(_MSC_VER) + #if defined(_MSC_VER) || defined(__WATCOMC__) #define THREAD_LS_T __declspec(thread) /* Thread local storage only in FreeRTOS v8.2.1 and higher */ #elif defined(FREERTOS) || defined(FREERTOS_TCP) || \ @@ -754,11 +768,13 @@ typedef struct w64wrapper { #endif #ifndef XSTRCASECMP - #if defined(MICROCHIP_PIC32) && (__XC32_VERSION >= 1000) && (__XC32_VERSION < 4000) + #if (defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32)) && \ + (__XC32_VERSION >= 1000) && (__XC32_VERSION < 4000) /* XC32 supports str[n]casecmp in version >= 1.0 through 4.0. */ #define XSTRCASECMP(s1,s2) strcasecmp((s1),(s2)) - #elif defined(MICROCHIP_PIC32) || defined(WOLFSSL_TIRTOS) || \ - defined(WOLFSSL_ZEPHYR) || defined(MICROCHIP_PIC24) + #elif defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32) || \ + defined(WOLFSSL_TIRTOS) || defined(WOLFSSL_ZEPHYR) || \ + defined(MICROCHIP_PIC24) /* XC32 version < 1.0 does not support strcasecmp. */ #define USE_WOLF_STRCASECMP #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) @@ -786,11 +802,13 @@ typedef struct w64wrapper { #endif /* !XSTRCASECMP */ #ifndef XSTRNCASECMP - #if defined(MICROCHIP_PIC32) && (__XC32_VERSION >= 1000) + #if (defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32)) && \ + (__XC32_VERSION >= 1000) /* XC32 supports str[n]casecmp in version >= 1.0. */ #define XSTRNCASECMP(s1,s2,n) strncasecmp((s1),(s2),(n)) - #elif defined(MICROCHIP_PIC32) || defined(WOLFSSL_TIRTOS) || \ - defined(WOLFSSL_ZEPHYR) || defined(MICROCHIP_PIC24) + #elif defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32) || \ + defined(WOLFSSL_TIRTOS) || defined(WOLFSSL_ZEPHYR) || \ + defined(MICROCHIP_PIC24) /* XC32 version < 1.0 does not support strncasecmp. */ #define USE_WOLF_STRNCASECMP #elif defined(USE_WINDOWS_API) || defined(FREERTOS_TCP_WINSIM) @@ -914,6 +932,13 @@ typedef struct w64wrapper { /* use only Thread Safe version of strtok */ #if defined(USE_WOLF_STRTOK) #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) + #elif defined(__WATCOMC__) + #if __WATCOMC__ < 1300 + #define USE_WOLF_STRTOK + #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) + #else + #define XSTRTOK(s1,d,ptr) strtok_r((s1),(d),(ptr)) + #endif #elif defined(USE_WINDOWS_API) || defined(INTIME_RTOS) #define XSTRTOK(s1,d,ptr) strtok_s((s1),(d),(ptr)) #else @@ -985,7 +1010,7 @@ typedef struct w64wrapper { #endif #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) #define XISALNUM(c) isalnum((c)) - #ifdef NO_STDLIB_ISASCII + #if !defined(HAVE_ISASCII) || defined(NO_STDLIB_ISASCII) #define XISASCII(c) (((c) >= 0 && (c) <= 127) ? 1 : 0) #else #define XISASCII(c) isascii((c)) @@ -996,11 +1021,14 @@ typedef struct w64wrapper { #define XTOLOWER(c) tolower((c)) #endif - #ifndef OFFSETOF + #ifndef WC_OFFSETOF #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 4)) - #define OFFSETOF(type, field) __builtin_offsetof(type, field) + #define WC_OFFSETOF(type, field) __builtin_offsetof(type, field) + #elif defined(__WATCOMC__) + #include + #define WC_OFFSETOF offsetof #else - #define OFFSETOF(type, field) ((size_t)&(((type *)0)->field)) + #define WC_OFFSETOF(type, field) ((size_t)&(((type *)0)->field)) #endif #endif @@ -1110,6 +1138,7 @@ typedef struct w64wrapper { DYNAMIC_TYPE_BIO = 102, DYNAMIC_TYPE_X509_ACERT = 103, DYNAMIC_TYPE_OS_BUF = 104, + DYNAMIC_TYPE_ASCON = 105, DYNAMIC_TYPE_SNIFFER_SERVER = 1000, DYNAMIC_TYPE_SNIFFER_SESSION = 1001, DYNAMIC_TYPE_SNIFFER_PB = 1002, @@ -1228,6 +1257,16 @@ typedef struct w64wrapper { #endif /* HAVE_SELFTEST */ }; + enum wc_HashFlags { + WC_HASH_FLAG_NONE = 0x00000000, + WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ + WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ + #ifdef WOLFSSL_SHA3 + WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ + #endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) + }; + /* cipher types */ enum wc_CipherType { WC_CIPHER_NONE = 0, @@ -1267,7 +1306,7 @@ typedef struct w64wrapper { WC_PK_TYPE_CURVE25519_KEYGEN = 16, WC_PK_TYPE_RSA_GET_SIZE = 17, #define _WC_PK_TYPE_MAX WC_PK_TYPE_RSA_GET_SIZE - #if defined(WOLFSSL_HAVE_KYBER) + #if defined(WOLFSSL_HAVE_MLKEM) WC_PK_TYPE_PQC_KEM_KEYGEN = 18, WC_PK_TYPE_PQC_KEM_ENCAPS = 19, WC_PK_TYPE_PQC_KEM_DECAPS = 20, @@ -1288,12 +1327,12 @@ typedef struct w64wrapper { WC_PK_TYPE_MAX = _WC_PK_TYPE_MAX }; -#if defined(WOLFSSL_HAVE_KYBER) +#if defined(WOLFSSL_HAVE_MLKEM) /* Post quantum KEM algorithms */ enum wc_PqcKemType { WC_PQC_KEM_TYPE_NONE = 0, #define _WC_PQC_KEM_TYPE_MAX WC_PQC_KEM_TYPE_NONE - #if defined(WOLFSSL_HAVE_KYBER) + #if defined(WOLFSSL_HAVE_MLKEM) WC_PQC_KEM_TYPE_KYBER = 1, #undef _WC_PQC_KEM_TYPE_MAX #define _WC_PQC_KEM_TYPE_MAX WC_PQC_KEM_TYPE_KYBER @@ -1475,6 +1514,47 @@ typedef struct w64wrapper { * wolfSSL_JoinThread() and wolfSSL_Cond signaling if they want. * Otherwise, those functions are omitted. */ + #elif defined(__WATCOMC__) + #if __WATCOMC__ < 1300 + #define _WCCALLBACK + #endif + #if defined(__NT__) + typedef unsigned THREAD_RETURN; + typedef uintptr_t THREAD_TYPE; + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + HANDLE cond; + } COND_TYPE; + #define WOLFSSL_COND + #define INVALID_THREAD_VAL ((THREAD_TYPE)(INVALID_HANDLE_VALUE)) + #define WOLFSSL_THREAD __stdcall + #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK + #elif defined(__OS2__) + #define WOLFSSL_THREAD_VOID_RETURN + typedef void THREAD_RETURN; + typedef TID THREAD_TYPE; + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + LHANDLE cond; + } COND_TYPE; + #define WOLFSSL_COND + #define INVALID_THREAD_VAL ((THREAD_TYPE)(-1)) + #define WOLFSSL_THREAD _WCCALLBACK + #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK + #elif defined(__LINUX__) + #include + typedef struct COND_TYPE { + pthread_mutex_t mutex; + pthread_cond_t cond; + } COND_TYPE; + typedef void* THREAD_RETURN; + typedef pthread_t THREAD_TYPE; + #define WOLFSSL_COND + #define WOLFSSL_THREAD + #ifndef HAVE_SELFTEST + #define WOLFSSL_THREAD_NO_JOIN + #endif + #endif #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) || \ defined(FREESCALE_MQX) typedef unsigned int THREAD_RETURN; @@ -1587,8 +1667,6 @@ typedef struct w64wrapper { * to check if the value is an invalid thread * WOLFSSL_THREAD - attribute that should be used to declare thread * callbacks - * WOLFSSL_THREAD_NO_JOIN - attribute that should be used to declare - * thread callbacks that don't require cleanup * WOLFSSL_COND - defined if this system supports signaling * COND_TYPE - type that should be passed into the signaling API * WOLFSSL_THREAD_VOID_RETURN - defined if the thread callback has a @@ -1596,8 +1674,16 @@ typedef struct w64wrapper { * WOLFSSL_RETURN_FROM_THREAD - define used to correctly return from a * thread callback * THREAD_CB - thread callback type for regular threading API - * THREAD_CB_NOJOIN - thread callback type for threading API that don't + * + * WOLFSSL_THREAD_NO_JOIN - attribute used to declare thread callbacks + * that do not require cleanup + * THREAD_CB_NOJOIN - thread callback type for thread APIs that do not * require cleanup + * THREAD_RETURN_NOJOIN - return type used to declare thread callbacks + * that do not require cleanup + * RETURN_FROM_THREAD_NOJOIN - define used to correctly return from + * a thread callback that do not require + * cleanup * * Other defines/types are specific for the threading implementation */ @@ -1620,8 +1706,17 @@ typedef struct w64wrapper { /* Create a thread that will be automatically cleaned up. We can't * return a handle/pointer to the new thread because there are no * guarantees for how long it will be valid. */ - typedef THREAD_RETURN (WOLFSSL_THREAD_NO_JOIN *THREAD_CB_NOJOIN) - (void* arg); + #if defined(WOLFSSL_PTHREADS) + #define THREAD_CB_NOJOIN THREAD_CB + #define THREAD_RETURN_NOJOIN THREAD_RETURN + #define RETURN_FROM_THREAD_NOJOIN(x) \ + WOLFSSL_RETURN_FROM_THREAD(x) + #else + #define THREAD_RETURN_NOJOIN void + typedef THREAD_RETURN_NOJOIN + (WOLFSSL_THREAD_NO_JOIN *THREAD_CB_NOJOIN)(void* arg); + #define RETURN_FROM_THREAD_NOJOIN(x) return + #endif WOLFSSL_API int wolfSSL_NewThreadNoJoin(THREAD_CB_NOJOIN cb, void* arg); #endif @@ -1712,21 +1807,25 @@ typedef struct w64wrapper { #define PRAGMA_DIAG_POP /* null expansion */ #endif - #define WC_CPP_CAT_(a, b) a ## b - #define WC_CPP_CAT(a, b) WC_CPP_CAT_(a, b) + #define WC_CPP_CAT4_(a, b, c, d) a ## b ## c ## d + #define WC_CPP_CAT4(a, b, c, d) WC_CPP_CAT4_(a, b, c, d) #if defined(WC_NO_STATIC_ASSERT) #define wc_static_assert(expr) struct wc_static_assert_dummy_struct #define wc_static_assert2(expr, msg) wc_static_assert(expr) #elif !defined(wc_static_assert) + #if defined(WOLFSSL_HAVE_ASSERT_H) && !defined(WOLFSSL_NO_ASSERT_H) + #include + #endif #if (defined(__cplusplus) && (__cplusplus >= 201703L)) || \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)) || \ - (defined(_MSVC_LANG) && (_MSVC_LANG >= 201103L)) + (defined(_MSVC_LANG) && (__cpp_static_assert >= 201411L)) /* native variadic static_assert() */ #define wc_static_assert static_assert #ifndef wc_static_assert2 #define wc_static_assert2 static_assert #endif - #elif defined(_MSC_VER) && (__STDC_VERSION__ >= 201112L) + #elif (defined(_MSC_VER) && (__STDC_VERSION__ >= 201112L)) || \ + (defined(_MSVC_LANG) && (__cpp_static_assert >= 200410L)) /* native 2-argument static_assert() */ #define wc_static_assert(expr) static_assert(expr, #expr) #ifndef wc_static_assert2 @@ -1746,11 +1845,16 @@ typedef struct w64wrapper { #define wc_static_assert2(expr, msg) _Static_assert(expr, msg) #endif #else - /* C89-compatible fallback */ - #define wc_static_assert(expr) \ - struct WC_CPP_CAT(wc_static_assert_dummy_struct_L, __LINE__) { \ - char t[(expr) ? 1 : -1]; \ - } + #ifdef __COUNTER__ + #define wc_static_assert(expr) \ + struct WC_CPP_CAT4(wc_static_assert_dummy_struct_L, \ + __LINE__, _, __COUNTER__) { \ + char t[(expr) ? 1 : -1]; \ + } + #else + #define wc_static_assert(expr) \ + struct wc_static_assert_dummy_struct + #endif #ifndef wc_static_assert2 #define wc_static_assert2(expr, msg) wc_static_assert(expr) #endif @@ -1783,6 +1887,13 @@ typedef struct w64wrapper { #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING #endif + #ifndef WC_SANITIZE_DISABLE + #define WC_SANITIZE_DISABLE() WC_DO_NOTHING + #endif + #ifndef WC_SANITIZE_ENABLE + #define WC_SANITIZE_ENABLE() WC_DO_NOTHING + #endif + #if FIPS_VERSION_GE(5,1) #define WC_SPKRE_F(x,y) wolfCrypt_SetPrivateKeyReadEnable_fips((x),(y)) #define PRIVATE_KEY_LOCK() WC_SPKRE_F(0,WC_KEYTYPE_ALL) diff --git a/src/wolfssl/wolfcrypt/visibility.h b/src/wolfssl/wolfcrypt/visibility.h index 30a19e2..fc7e485 100644 --- a/src/wolfssl/wolfcrypt/visibility.h +++ b/src/wolfssl/wolfcrypt/visibility.h @@ -1,6 +1,6 @@ /* visibility.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -33,7 +33,7 @@ #if defined(BUILDING_WOLFSSL) #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__) || \ - defined(_WIN32_WCE) + defined(_WIN32_WCE) || defined(__WATCOMC__) #if defined(WOLFSSL_DLL) #define WOLFSSL_API __declspec(dllexport) #else @@ -50,8 +50,21 @@ #define WOLFSSL_API #define WOLFSSL_LOCAL #endif /* HAVE_VISIBILITY */ -#else /* BUILDING_WOLFSSL */ - #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__) || \ + + #ifdef WOLFSSL_PRIVATE_TEST_VIS + #define WOLFSSL_TEST_VIS WOLFSSL_LOCAL + #else + #define WOLFSSL_TEST_VIS WOLFSSL_API + #endif +#else /* !BUILDING_WOLFSSL */ + #if defined(__WATCOMC__) + #if defined(WOLFSSL_DLL) && defined(__NT__) + #define WOLFSSL_API __declspec(dllimport) + #else + #define WOLFSSL_API + #endif + #define WOLFSSL_LOCAL + #elif defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__) || \ defined(_WIN32_WCE) #if defined(WOLFSSL_DLL) #define WOLFSSL_API __declspec(dllimport) @@ -63,7 +76,17 @@ #define WOLFSSL_API #define WOLFSSL_LOCAL #endif -#endif /* BUILDING_WOLFSSL */ + + #if defined(WOLFSSL_VIS_FOR_TESTS) + #ifdef WOLFSSL_PRIVATE_TEST_VIS + #error WOLFSSL_VIS_FOR_TESTS is unavailable in WOLFSSL_PRIVATE_TEST_VIS builds. + #endif + #define WOLFSSL_TEST_VIS WOLFSSL_API + #else + #define WOLFSSL_TEST_VIS WOLFSSL_API WC_DEPRECATED("internal use only") + #endif + +#endif /* !BUILDING_WOLFSSL */ /* WOLFSSL_ABI is used for public API symbols that must not change * their signature. This tag is used for all APIs that are a diff --git a/src/wolfssl/wolfcrypt/wc_encrypt.h b/src/wolfssl/wolfcrypt/wc_encrypt.h index e3cf9ad..4dfc84c 100644 --- a/src/wolfssl/wolfcrypt/wc_encrypt.h +++ b/src/wolfssl/wolfcrypt/wc_encrypt.h @@ -1,6 +1,6 @@ /* wc_encrypt.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index d7317ea..a4880a9 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -1,6 +1,6 @@ /* wc_lms.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -303,13 +303,13 @@ #endif /* Indicates using SHA-256 for hashing. */ -#define LMS_SHA256 0x00 +#define LMS_SHA256 0x0000 /* Indicates using SHA-256/192 for hashing. */ -#define LMS_SHA256_192 0x10 +#define LMS_SHA256_192 0x1000 /* Mask to get hashing algorithm from type. */ -#define LMS_HASH_MASK 0xf0 +#define LMS_HASH_MASK 0xf000 /* Mask to get height or Winternitz width from type. */ -#define LMS_H_W_MASK 0x0f +#define LMS_H_W_MASK 0x0fff /* LMS Parameters. */ /* SHA-256 hash, 32-bytes of hash used, tree height of 5. */ @@ -333,24 +333,24 @@ #define LMOTS_SHA256_N32_W8 0x04 /* SHA-256 hash, 32-bytes of hash used, tree height of 5. */ -#define LMS_SHA256_M24_H5 (0x05 | LMS_SHA256_192) +#define LMS_SHA256_M24_H5 (0x0a | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 10. */ -#define LMS_SHA256_M24_H10 (0x06 | LMS_SHA256_192) +#define LMS_SHA256_M24_H10 (0x0b | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 15. */ -#define LMS_SHA256_M24_H15 (0x07 | LMS_SHA256_192) +#define LMS_SHA256_M24_H15 (0x0c | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 20. */ -#define LMS_SHA256_M24_H20 (0x08 | LMS_SHA256_192) +#define LMS_SHA256_M24_H20 (0x0d | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, tree height of 25. */ -#define LMS_SHA256_M24_H25 (0x09 | LMS_SHA256_192) +#define LMS_SHA256_M24_H25 (0x0e | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 1 bit. */ -#define LMOTS_SHA256_N24_W1 (0x01 | LMS_SHA256_192) +#define LMOTS_SHA256_N24_W1 (0x05 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 2 bits. */ -#define LMOTS_SHA256_N24_W2 (0x02 | LMS_SHA256_192) +#define LMOTS_SHA256_N24_W2 (0x06 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 4 bits. */ -#define LMOTS_SHA256_N24_W4 (0x03 | LMS_SHA256_192) +#define LMOTS_SHA256_N24_W4 (0x07 | LMS_SHA256_192) /* SHA-256 hash, 32-bytes of hash used, Winternitz width of 8 bits. */ -#define LMOTS_SHA256_N24_W8 (0x04 | LMS_SHA256_192) +#define LMOTS_SHA256_N24_W8 (0x08 | LMS_SHA256_192) typedef struct LmsParams { /* Number of tree levels. */ diff --git a/src/wolfssl/wolfcrypt/wc_mlkem.h b/src/wolfssl/wolfcrypt/wc_mlkem.h new file mode 100644 index 0000000..f79e188 --- /dev/null +++ b/src/wolfssl/wolfcrypt/wc_mlkem.h @@ -0,0 +1,378 @@ +/* wc_mlkem.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/*! + \file wolfssl/wolfcrypt/wc_mlkem.h +*/ + + +#ifndef WOLF_CRYPT_WC_MLKEM_H +#define WOLF_CRYPT_WC_MLKEM_H + +#include +#include +#include +#include + +#ifdef WOLFSSL_HAVE_MLKEM + +#ifdef WOLFSSL_KYBER_NO_MAKE_KEY + #define WOLFSSL_MLKEM_NO_MAKE_KEY +#endif +#ifdef WOLFSSL_KYBER_NO_ENCAPSULATE + #define WOLFSSL_MLKEM_NO_ENCAPSULATE +#endif +#ifdef WOLFSSL_KYBER_NO_DECAPSULATE + #define WOLFSSL_MLKEM_NO_DECAPSULATE +#endif + +#ifdef noinline + #define MLKEM_NOINLINE noinline +#elif defined(_MSC_VER) + #define MLKEM_NOINLINE __declspec(noinline) +#elif defined(__GNUC__) + #define MLKEM_NOINLINE __attribute__((noinline)) +#else + #define MLKEM_NOINLINE +#endif + +enum { + /* Flags of Kyber keys. */ + MLKEM_FLAG_PRIV_SET = 0x0001, + MLKEM_FLAG_PUB_SET = 0x0002, + MLKEM_FLAG_BOTH_SET = 0x0003, + MLKEM_FLAG_H_SET = 0x0004, + MLKEM_FLAG_A_SET = 0x0008, + + /* 2 bits of random used to create noise value. */ + MLKEM_CBD_ETA2 = 2, + /* 3 bits of random used to create noise value. */ + MLKEM_CBD_ETA3 = 3, + + /* Number of bits to compress to. */ + MLKEM_COMP_4BITS = 4, + MLKEM_COMP_5BITS = 5, + MLKEM_COMP_10BITS = 10, + MLKEM_COMP_11BITS = 11, +}; + + +/* SHAKE128 rate. */ +#define XOF_BLOCK_SIZE 168 + +/* Modulus of co-efficients of polynomial. */ +#define MLKEM_Q 3329 + + +/* Kyber-512 parameters */ +#ifdef WOLFSSL_WC_ML_KEM_512 +/* Number of bits of random to create noise from. */ +#define WC_ML_KEM_512_ETA1 MLKEM_CBD_ETA3 +#endif /* WOLFSSL_WC_ML_KEM_512 */ + +/* Kyber-768 parameters */ +#ifdef WOLFSSL_WC_ML_KEM_768 +/* Number of bits of random to create noise from. */ +#define WC_ML_KEM_768_ETA1 MLKEM_CBD_ETA2 +#endif /* WOLFSSL_WC_ML_KEM_768 */ + +/* Kyber-1024 parameters */ +#ifdef WOLFSSL_WC_ML_KEM_1024 +/* Number of bits of random to create noise from. */ +#define WC_ML_KEM_1024_ETA1 MLKEM_CBD_ETA2 +#endif /* WOLFSSL_KYBER1024 */ + + + +/* The data type of the hash function. */ +#define MLKEM_HASH_T wc_Sha3 + +/* The data type of the pseudo-random function. */ +#define MLKEM_PRF_T wc_Shake + +/* ML-KEM key. */ +struct MlKemKey { + /* Type of key: WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024 */ + int type; + /* Dynamic memory allocation hint. */ + void* heap; +#if defined(WOLF_CRYPTO_CB) + /* Device Id. */ + int devId; +#endif + /* Flags indicating what is stored in the key. */ + int flags; + + /* A pseudo-random function object. */ + MLKEM_HASH_T hash; + /* A pseudo-random function object. */ + MLKEM_PRF_T prf; + + /* Private key as a vector. */ + sword16 priv[WC_ML_KEM_MAX_K * MLKEM_N]; + /* Public key as a vector. */ + sword16 pub[WC_ML_KEM_MAX_K * MLKEM_N]; + /* Public seed. */ + byte pubSeed[WC_ML_KEM_SYM_SZ]; + /* Public hash - hash of encoded public key. */ + byte h[WC_ML_KEM_SYM_SZ]; + /* Randomizer for decapsulation. */ + byte z[WC_ML_KEM_SYM_SZ]; +#ifdef WOLFSSL_MLKEM_CACHE_A + /* A matrix from key generation. */ + sword16 a[WC_ML_KEM_MAX_K * WC_ML_KEM_MAX_K * MLKEM_N]; +#endif +}; + +#ifdef __cplusplus + extern "C" { +#endif + +/* For backward compatibility */ +typedef struct MlKemKey KyberKey; + +WOLFSSL_LOCAL +void mlkem_init(void); + +#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM +WOLFSSL_LOCAL +void mlkem_keygen(sword16* priv, sword16* pub, sword16* e, const sword16* a, + int kp); +#else +WOLFSSL_LOCAL +int mlkem_keygen_seeds(sword16* priv, sword16* pub, MLKEM_PRF_T* prf, + sword16* e, int kp, byte* seed, byte* noiseSeed); +#endif +#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM +WOLFSSL_LOCAL +void mlkem_encapsulate(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp); +#else +WOLFSSL_LOCAL +int mlkem_encapsulate_seeds(const sword16* pub, MLKEM_PRF_T* prf, sword16* bp, + sword16* tp, sword16* sp, int kp, const byte* msg, byte* seed, + byte* coins); +#endif +WOLFSSL_LOCAL +void mlkem_decapsulate(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp); + +WOLFSSL_LOCAL +int mlkem_gen_matrix(MLKEM_PRF_T* prf, sword16* a, int kp, byte* seed, + int transposed); +WOLFSSL_LOCAL +int mlkem_get_noise(MLKEM_PRF_T* prf, int kp, sword16* vec1, sword16* vec2, + sword16* poly, byte* seed); + +#if defined(USE_INTEL_SPEEDUP) || \ + (defined(WOLFSSL_ARMASM) && defined(__aarch64__)) +WOLFSSL_LOCAL +int mlkem_kdf(byte* seed, int seedLen, byte* out, int outLen); +#endif +WOLFSSL_LOCAL +void mlkem_hash_init(MLKEM_HASH_T* hash); +WOLFSSL_LOCAL +int mlkem_hash_new(MLKEM_HASH_T* hash, void* heap, int devId); +WOLFSSL_LOCAL +void mlkem_hash_free(MLKEM_HASH_T* hash); +WOLFSSL_LOCAL +int mlkem_hash256(wc_Sha3* hash, const byte* data, word32 dataLen, byte* out); +WOLFSSL_LOCAL +int mlkem_hash512(wc_Sha3* hash, const byte* data1, word32 data1Len, + const byte* data2, word32 data2Len, byte* out); + +WOLFSSL_LOCAL +int mlkem_derive_secret(MLKEM_PRF_T* prf, const byte* z, const byte* ct, + word32 ctSz, byte* ss); + +WOLFSSL_LOCAL +void mlkem_prf_init(MLKEM_PRF_T* prf); +WOLFSSL_LOCAL +int mlkem_prf_new(MLKEM_PRF_T* prf, void* heap, int devId); +WOLFSSL_LOCAL +void mlkem_prf_free(MLKEM_PRF_T* prf); + +WOLFSSL_LOCAL +int mlkem_cmp(const byte* a, const byte* b, int sz); + +WOLFSSL_LOCAL +void mlkem_vec_compress_10(byte* r, sword16* v, unsigned int kp); +WOLFSSL_LOCAL +void mlkem_vec_compress_11(byte* r, sword16* v); +WOLFSSL_LOCAL +void mlkem_vec_decompress_10(sword16* v, const unsigned char* b, + unsigned int kp); +WOLFSSL_LOCAL +void mlkem_vec_decompress_11(sword16* v, const unsigned char* b); + +WOLFSSL_LOCAL +void mlkem_compress_4(byte* b, sword16* p); +WOLFSSL_LOCAL +void mlkem_compress_5(byte* b, sword16* p); +WOLFSSL_LOCAL +void mlkem_decompress_4(sword16* p, const unsigned char* b); +WOLFSSL_LOCAL +void mlkem_decompress_5(sword16* p, const unsigned char* b); + +WOLFSSL_LOCAL +void mlkem_from_msg(sword16* p, const byte* msg); +WOLFSSL_LOCAL +void mlkem_to_msg(byte* msg, sword16* p); +WOLFSSL_LOCAL +void mlkem_from_bytes(sword16* p, const byte* b, int k); +WOLFSSL_LOCAL +void mlkem_to_bytes(byte* b, sword16* p, int k); + +#ifdef USE_INTEL_SPEEDUP +WOLFSSL_LOCAL +void mlkem_keygen_avx2(sword16* priv, sword16* pub, sword16* e, + const sword16* a, int kp); +WOLFSSL_LOCAL +void mlkem_encapsulate_avx2(const sword16* pub, sword16* bp, sword16* v, + const sword16* at, sword16* sp, const sword16* ep, const sword16* epp, + const sword16* m, int kp); +WOLFSSL_LOCAL +void mlkem_decapsulate_avx2(const sword16* priv, sword16* mp, sword16* bp, + const sword16* v, int kp); + +WOLFSSL_LOCAL +unsigned int mlkem_rej_uniform_n_avx2(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); +WOLFSSL_LOCAL +unsigned int mlkem_rej_uniform_avx2(sword16* p, unsigned int len, const byte* r, + unsigned int rLen); +WOLFSSL_LOCAL +void mlkem_redistribute_21_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void mlkem_redistribute_17_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void mlkem_redistribute_16_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); +void mlkem_redistribute_8_rand_avx2(const word64* s, byte* r0, byte* r1, + byte* r2, byte* r3); + +WOLFSSL_LOCAL +void mlkem_sha3_128_blocksx4_seed_avx2(word64* s, byte* seed); +WOLFSSL_LOCAL +void mlkem_sha3_256_blocksx4_seed_avx2(word64* s, byte* seed); + +WOLFSSL_LOCAL +void mlkem_cbd_eta2_avx2(sword16* p, const byte* r); +WOLFSSL_LOCAL +void mlkem_cbd_eta3_avx2(sword16* p, const byte* r); + +WOLFSSL_LOCAL +void mlkem_from_msg_avx2(sword16* p, const byte* msg); +WOLFSSL_LOCAL +void mlkem_to_msg_avx2(byte* msg, sword16* p); + +WOLFSSL_LOCAL +void mlkem_from_bytes_avx2(sword16* p, const byte* b); +WOLFSSL_LOCAL +void mlkem_to_bytes_avx2(byte* b, sword16* p); + +WOLFSSL_LOCAL +void mlkem_compress_10_avx2(byte* r, const sword16* p, int n); +WOLFSSL_LOCAL +void mlkem_decompress_10_avx2(sword16* p, const byte* r, int n); +WOLFSSL_LOCAL +void mlkem_compress_11_avx2(byte* r, const sword16* p, int n); +WOLFSSL_LOCAL +void mlkem_decompress_11_avx2(sword16* p, const byte* r, int n); + +WOLFSSL_LOCAL +void mlkem_compress_4_avx2(byte* r, const sword16* p); +WOLFSSL_LOCAL +void mlkem_decompress_4_avx2(sword16* p, const byte* r); +WOLFSSL_LOCAL +void mlkem_compress_5_avx2(byte* r, const sword16* p); +WOLFSSL_LOCAL +void mlkem_decompress_5_avx2(sword16* p, const byte* r); + + +WOLFSSL_LOCAL +int mlkem_cmp_avx2(const byte* a, const byte* b, int sz); +#elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) +WOLFSSL_LOCAL void mlkem_ntt(sword16* r); +WOLFSSL_LOCAL void mlkem_invntt(sword16* r); +WOLFSSL_LOCAL void mlkem_ntt_sqrdmlsh(sword16* r); +WOLFSSL_LOCAL void mlkem_invntt_sqrdmlsh(sword16* r); +WOLFSSL_LOCAL void mlkem_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_add_reduce(sword16* r, const sword16* a); +WOLFSSL_LOCAL void mlkem_add3_reduce(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_rsub_reduce(sword16* r, const sword16* a); +WOLFSSL_LOCAL void mlkem_to_mont(sword16* p); +WOLFSSL_LOCAL void mlkem_to_mont_sqrdmlsh(sword16* p); +WOLFSSL_LOCAL void mlkem_sha3_blocksx3_neon(word64* state); +WOLFSSL_LOCAL void mlkem_shake128_blocksx3_seed_neon(word64* state, byte* seed); +WOLFSSL_LOCAL void mlkem_shake256_blocksx3_seed_neon(word64* state, byte* seed); +WOLFSSL_LOCAL unsigned int mlkem_rej_uniform_neon(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); +WOLFSSL_LOCAL int mlkem_cmp_neon(const byte* a, const byte* b, int sz); +WOLFSSL_LOCAL void mlkem_csubq_neon(sword16* p); +WOLFSSL_LOCAL void mlkem_from_msg_neon(sword16* p, const byte* msg); +WOLFSSL_LOCAL void mlkem_to_msg_neon(byte* msg, sword16* p); +#elif defined(WOLFSSL_ARMASM_THUMB2) && defined(WOLFSSL_ARMASM) +#define mlkem_ntt mlkem_thumb2_ntt +#define mlkem_invntt mlkem_thumb2_invntt +#define mlkem_basemul_mont mlkem_thumb2_basemul_mont +#define mlkem_basemul_mont_add mlkem_thumb2_basemul_mont_add +#define mlkem_rej_uniform_c mlkem_thumb2_rej_uniform + +WOLFSSL_LOCAL void mlkem_thumb2_ntt(sword16* r); +WOLFSSL_LOCAL void mlkem_thumb2_invntt(sword16* r); +WOLFSSL_LOCAL void mlkem_thumb2_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_thumb2_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_thumb2_csubq(sword16* p); +WOLFSSL_LOCAL unsigned int mlkem_thumb2_rej_uniform(sword16* p, + unsigned int len, const byte* r, unsigned int rLen); +#elif defined(WOLFSSL_ARMASM) +#define mlkem_ntt mlkem_arm32_ntt +#define mlkem_invntt mlkem_arm32_invntt +#define mlkem_basemul_mont mlkem_arm32_basemul_mont +#define mlkem_basemul_mont_add mlkem_arm32_basemul_mont_add +#define mlkem_rej_uniform_c mlkem_arm32_rej_uniform + +WOLFSSL_LOCAL void mlkem_arm32_ntt(sword16* r); +WOLFSSL_LOCAL void mlkem_arm32_invntt(sword16* r); +WOLFSSL_LOCAL void mlkem_arm32_basemul_mont(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_arm32_basemul_mont_add(sword16* r, const sword16* a, + const sword16* b); +WOLFSSL_LOCAL void mlkem_arm32_csubq(sword16* p); +WOLFSSL_LOCAL unsigned int mlkem_arm32_rej_uniform(sword16* p, unsigned int len, + const byte* r, unsigned int rLen); +#endif + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* WOLFSSL_HAVE_MLKEM */ + +#endif /* WOLF_CRYPT_WC_MLKEM_H */ diff --git a/src/wolfssl/wolfcrypt/wc_pkcs11.h b/src/wolfssl/wolfcrypt/wc_pkcs11.h index 0b8942b..fdc51e0 100644 --- a/src/wolfssl/wolfcrypt/wc_pkcs11.h +++ b/src/wolfssl/wolfcrypt/wc_pkcs11.h @@ -1,6 +1,6 @@ /* wc_pkcs11.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wc_port.h b/src/wolfssl/wolfcrypt/wc_port.h index 4be0502..a33fbf4 100644 --- a/src/wolfssl/wolfcrypt/wc_port.h +++ b/src/wolfssl/wolfcrypt/wc_port.h @@ -1,6 +1,6 @@ /* wc_port.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -82,6 +82,25 @@ #endif #endif /* !WC_MAYBE_UNUSED */ +#ifndef WC_DEPRECATED + #ifdef WOLFSSL_ZEPHYR + #define WC_DEPRECATED(msg) /* null expansion */ + #elif ((defined(__GNUC__) && \ + ((__GNUC__ >= 5) || \ + ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))) || \ + defined(__clang__) + #define WC_DEPRECATED(msg) __attribute__((deprecated(msg))) + #elif defined(_MSC_VER) || defined(__MINGW32__) || defined(__CYGWIN__) || \ + defined(_WIN32_WCE) || defined(__WATCOMC__) + #define WC_DEPRECATED(msg) __declspec(deprecated(msg)) + #elif (defined(__GNUC__) && (__GNUC__ >= 4)) || \ + defined(__IAR_SYSTEMS_ICC__) + #define WC_DEPRECATED(msg) __attribute__((deprecated)) + #else + #define WC_DEPRECATED(msg) /* null expansion */ + #endif +#endif /* !WC_MAYBE_UNUSED */ + /* use inlining if compiler allows */ #ifndef WC_INLINE #ifndef NO_INLINE @@ -122,6 +141,43 @@ /* THREADING/MUTEX SECTION */ #if defined(SINGLE_THREADED) && defined(NO_FILESYSTEM) /* No system headers required for build. */ +#elif defined(__WATCOMC__) + #if defined(SINGLE_THREADED) + #if defined(USE_WINDOWS_API) + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ + #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header */ + #ifndef WOLFSSL_USER_IO + #include + #include /* required for InetPton */ + #endif + #elif defined(__OS2__) + #include + #endif + #else + #if defined(USE_WINDOWS_API) + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ + #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header */ + #include + #ifndef WOLFSSL_USER_IO + #include + #include /* required for InetPton */ + #endif + #elif defined(__OS2__) + #define INCL_DOSSEMAPHORES + #define INCL_DOSPROCESS + #include + #include + #else + #ifndef WOLFSSL_USER_MUTEX + #define WOLFSSL_PTHREADS + #endif + #if defined(WOLFSSL_PTHREADS) + #include + #endif + #endif + #endif #elif defined(USE_WINDOWS_API) #if defined(WOLFSSL_PTHREADS) #include @@ -133,12 +189,11 @@ #define WIN32_LEAN_AND_MEAN #endif #if !defined(WOLFSSL_SGX) && !defined(WOLFSSL_NOT_WINDOWS_API) - #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN) - /* On WinCE winsock2.h must be included before windows.h */ - #include - #endif + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file. */ #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header */ #ifndef WOLFSSL_USER_IO + #include #include /* required for InetPton */ #endif #endif /* WOLFSSL_SGX */ @@ -284,7 +339,7 @@ #else /* MULTI_THREADED */ /* FREERTOS comes first to enable use of FreeRTOS Windows simulator only */ #if defined(FREERTOS) - #if ESP_IDF_VERSION_MAJOR >= 4 + #if defined(ESP_IDF_VERSION_MAJOR) && (ESP_IDF_VERSION_MAJOR >= 4) typedef SemaphoreHandle_t wolfSSL_Mutex; #else typedef xSemaphoreHandle wolfSSL_Mutex; @@ -371,6 +426,9 @@ /* typedef User_Mutex wolfSSL_Mutex; */ #elif defined(WOLFSSL_LINUXKM) /* definitions are in linuxkm/linuxkm_wc_port.h */ + #elif defined(__WATCOMC__) + /* OS/2 */ + typedef ULONG wolfSSL_Mutex; #else #error Need a mutex type in multithreaded mode #endif /* USE_WINDOWS_API */ @@ -395,6 +453,8 @@ #ifdef SINGLE_THREADED typedef int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) + #define WOLFSSL_ATOMIC_LOAD(x) (x) + #define WOLFSSL_ATOMIC_STORE(x, val) (x) = (val) #define WOLFSSL_ATOMIC_OPS #elif defined(HAVE_C___ATOMIC) #ifdef __cplusplus @@ -402,6 +462,8 @@ /* C++ using direct calls to compiler built-in functions */ typedef volatile int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) + #define WOLFSSL_ATOMIC_LOAD(x) __atomic_load_n(&(x), __ATOMIC_CONSUME) + #define WOLFSSL_ATOMIC_STORE(x, val) __atomic_store_n(&(x), val, __ATOMIC_RELEASE) #define WOLFSSL_ATOMIC_OPS #endif #else @@ -410,6 +472,8 @@ #include typedef atomic_int wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) + #define WOLFSSL_ATOMIC_LOAD(x) atomic_load(&(x)) + #define WOLFSSL_ATOMIC_STORE(x, val) atomic_store(&(x), val) #define WOLFSSL_ATOMIC_OPS #endif /* WOLFSSL_HAVE_ATOMIC_H */ #endif @@ -422,6 +486,8 @@ #endif typedef volatile long wolfSSL_Atomic_Int; #define WOLFSSL_ATOMIC_INITIALIZER(x) (x) + #define WOLFSSL_ATOMIC_LOAD(x) (x) + #define WOLFSSL_ATOMIC_STORE(x, val) (x) = (val) #define WOLFSSL_ATOMIC_OPS #endif #endif /* WOLFSSL_NO_ATOMICS */ @@ -757,13 +823,14 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); * make the API more POSIX like. */ XFILE z_fs_open(const char* filename, const char* mode); int z_fs_close(XFILE file); + int z_fs_rewind(XFILE file); #define XFOPEN z_fs_open #define XFCLOSE z_fs_close #define XFFLUSH fs_sync #define XFSEEK fs_seek #define XFTELL fs_tell - #define XFREWIND fs_rewind + #define XFREWIND z_fs_rewind #define XFREAD(P,S,N,F) fs_read(F, P, S*N) #define XFWRITE(P,S,N,F) fs_write(F, P, S*N) #define XSEEK_SET FS_SEEK_SET @@ -887,7 +954,25 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #if !defined(NO_WOLFSSL_DIR)\ && !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2) - #if defined(USE_WINDOWS_API) + #if defined(__WATCOMC__) + #include + #include + #define XWRITE write + #define XREAD read + #define XCLOSE close + #define XSTAT stat + #define XS_ISREG(s) S_ISREG(s) + #if defined(__UNIX__) + #include + #define SEPARATOR_CHAR ':' + #else + #include + #define SEPARATOR_CHAR ';' + #endif + #if defined(__NT__) + #define XALTHOMEVARNAME "USERPROFILE" + #endif + #elif defined(USE_WINDOWS_API) #include #include #ifndef XSTAT @@ -925,9 +1010,7 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define SEPARATOR_CHAR ':' #else - #ifndef NO_WOLFSSL_DIR - #include - #endif + #include #include #include #define XWRITE write @@ -1178,7 +1261,9 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XGMTIME(c, t) gmtime((c)) #elif defined(_WIN32_WCE) + #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ #include + #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ #include /* For file system */ time_t windows_time(time_t* timer); diff --git a/src/wolfssl/wolfcrypt/wc_xmss.h b/src/wolfssl/wolfcrypt/wc_xmss.h index 21d5fe8..e59df61 100644 --- a/src/wolfssl/wolfcrypt/wc_xmss.h +++ b/src/wolfssl/wolfcrypt/wc_xmss.h @@ -1,6 +1,6 @@ /* wc_xmss.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wolfevent.h b/src/wolfssl/wolfcrypt/wolfevent.h index cb3cb58..d6731d1 100644 --- a/src/wolfssl/wolfcrypt/wolfevent.h +++ b/src/wolfssl/wolfcrypt/wolfevent.h @@ -1,6 +1,6 @@ /* wolfevent.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfcrypt/wolfmath.h b/src/wolfssl/wolfcrypt/wolfmath.h index e012ff6..e2e8545 100644 --- a/src/wolfssl/wolfcrypt/wolfmath.h +++ b/src/wolfssl/wolfcrypt/wolfmath.h @@ -1,6 +1,6 @@ /* wolfmath.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -40,7 +40,16 @@ This library provides big integer math functions. #endif -#if defined(USE_FAST_MATH) +#if defined(NO_BIG_INT) + /* MPI globally disabled -- no PK algorithms supported. */ + #if defined(USE_FAST_MATH) || defined(USE_INTEGER_HEAP_MATH) || \ + defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) || \ + defined(HAVE_WOLF_BIGINT) || defined(WOLFSSL_EXPORT_INT) + #error Conflicting MPI settings. + #endif +#elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) + #include +#elif defined(USE_FAST_MATH) #include #elif defined(USE_INTEGER_HEAP_MATH) #include @@ -48,7 +57,7 @@ This library provides big integer math functions. #include #endif -#if !defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH) +#if !defined(NO_BIG_INT) #include #endif @@ -72,7 +81,7 @@ This library provides big integer math functions. extern const wc_ptr_t wc_off_on_addr[2]; #endif -#if !defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH) +#if !defined(NO_BIG_INT) /* common math functions */ MP_API int get_digit_count(const mp_int* a); MP_API mp_digit get_digit(const mp_int* a, int n); diff --git a/src/wolfssl/wolfcrypt/xmss.h b/src/wolfssl/wolfcrypt/xmss.h index 548700c..9944862 100644 --- a/src/wolfssl/wolfcrypt/xmss.h +++ b/src/wolfssl/wolfcrypt/xmss.h @@ -1,6 +1,6 @@ /* xmss.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * diff --git a/src/wolfssl/wolfio.h b/src/wolfssl/wolfio.h index 4d1145b..de45a18 100644 --- a/src/wolfssl/wolfio.h +++ b/src/wolfssl/wolfio.h @@ -1,6 +1,6 @@ /* io.h * - * Copyright (C) 2006-2024 wolfSSL Inc. + * Copyright (C) 2006-2025 wolfSSL Inc. * * This file is part of wolfSSL. * @@ -57,7 +57,32 @@ #include "zlib.h" #endif -#ifndef USE_WINDOWS_API +#if defined(__WATCOMC__) + #if defined(__NT__) + #elif defined(__OS2__) + #include + #include + #include + #include + #include + #include + #include + #include + #include + + typedef int socklen_t; + #elif defined(__LINUX__) + #include + #include + #include + #include + #define XFCNTL(fd, flag, block) fcntl((fd), (flag), (block)) + #include + #include + #include + #endif +#elif defined(USE_WINDOWS_API) +#else #if defined(WOLFSSL_LWIP) && !defined(WOLFSSL_APACHE_MYNEWT) /* lwIP needs to be configured to use sockets API in this mode */ /* LWIP_SOCKET 1 in lwip/opt.h or in build */ @@ -204,7 +229,40 @@ #define SOCKET_RECEIVING 1 #define SOCKET_SENDING 2 -#ifdef USE_WINDOWS_API +#ifdef __WATCOMC__ + #if defined(__NT__) + /* no epipe yet */ + #ifndef WSAEPIPE + #define WSAEPIPE -12345 + #endif + #define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK + #define SOCKET_EAGAIN WSAETIMEDOUT + #define SOCKET_ETIMEDOUT WSAETIMEDOUT + #define SOCKET_ECONNRESET WSAECONNRESET + #define SOCKET_EINTR WSAEINTR + #define SOCKET_EPIPE WSAEPIPE + #define SOCKET_ECONNREFUSED WSAENOTCONN + #define SOCKET_ECONNABORTED WSAECONNABORTED + #elif defined(__OS2__) + #define SOCKET_EWOULDBLOCK SOCEWOULDBLOCK + #define SOCKET_EAGAIN SOCEAGAIN + #define SOCKET_ETIMEDOUT SOCETIMEDOUT + #define SOCKET_ECONNRESET SOCECONNRESET + #define SOCKET_EINTR SOCEINTR + #define SOCKET_EPIPE SOCEPIPE + #define SOCKET_ECONNREFUSED SOCECONNREFUSED + #define SOCKET_ECONNABORTED SOCECONNABORTED + #elif defined(__UNIX__) + #define SOCKET_EWOULDBLOCK EWOULDBLOCK + #define SOCKET_EAGAIN EAGAIN + #define SOCKET_ETIMEDOUT ETIMEDOUT + #define SOCKET_ECONNRESET ECONNRESET + #define SOCKET_EINTR EINTR + #define SOCKET_EPIPE EPIPE + #define SOCKET_ECONNREFUSED ECONNREFUSED + #define SOCKET_ECONNABORTED ECONNABORTED + #endif +#elif defined(USE_WINDOWS_API) /* no epipe yet */ #ifndef WSAEPIPE #define WSAEPIPE -12345 @@ -836,21 +894,36 @@ WOLFSSL_API void wolfSSL_SetIOWriteFlags(WOLFSSL* ssl, int flags); #ifndef XINET_NTOP - #define XINET_NTOP(a,b,c,d) inet_ntop((a),(b),(c),(d)) - #ifdef USE_WINDOWS_API /* Windows-friendly definition */ - #undef XINET_NTOP + #if defined(__WATCOMC__) + #if defined(__OS2__) || defined(__NT__) && \ + (NTDDI_VERSION >= NTDDI_VISTA) + #define XINET_NTOP(a,b,c,d) inet_ntop((a),(b),(c),(d)) + #else + #define XINET_NTOP(a,b,c,d) \ + strncpy((c),inet_ntoa(*(unsigned *)(b)),(d)) + #endif + #elif defined(USE_WINDOWS_API) /* Windows-friendly definition */ #define XINET_NTOP(a,b,c,d) InetNtop((a),(b),(c),(d)) + #else + #define XINET_NTOP(a,b,c,d) inet_ntop((a),(b),(c),(d)) #endif #endif #ifndef XINET_PTON - #define XINET_PTON(a,b,c) inet_pton((a),(b),(c)) - #ifdef USE_WINDOWS_API /* Windows-friendly definition */ - #undef XINET_PTON + #if defined(__WATCOMC__) + #if defined(__OS2__) || defined(__NT__) && \ + (NTDDI_VERSION >= NTDDI_VISTA) + #define XINET_PTON(a,b,c) inet_pton((a),(b),(c)) + #else + #define XINET_PTON(a,b,c) *(unsigned *)(c) = inet_addr((b)) + #endif + #elif defined(USE_WINDOWS_API) /* Windows-friendly definition */ #if defined(__MINGW64__) && !defined(UNICODE) #define XINET_PTON(a,b,c) InetPton((a),(b),(c)) #else #define XINET_PTON(a,b,c) InetPton((a),(PCWSTR)(b),(c)) #endif + #else + #define XINET_PTON(a,b,c) inet_pton((a),(b),(c)) #endif #endif From c4052f6637b29160fa801050576a01e480798fce Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Wed, 7 May 2025 11:31:48 +0200 Subject: [PATCH 08/13] Apply post-release changes from https://github.com/wolfSSL/wolfssl/pull/8668 --- src/user_settings.h | 4 ++++ src/wolfssl-arduino.cpp | 26 +++++++++++++++++++++++++- src/wolfssl/wolfcrypt/settings.h | 1 + 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/user_settings.h b/src/user_settings.h index e2a0196..e8d05fa 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -90,9 +90,13 @@ #elif defined(WOLFSSL_SERVER_EXAMPLE) #define NO_WOLFSSL_CLIENT #elif defined(WOLFSSL_TEMPLATE_EXAMPLE) + #define NO_TLS + #define WOLFCRYPT_ONLY #define NO_WOLFSSL_SERVER #define NO_WOLFSSL_CLIENT #elif defined(WOLFSSL_AES_CTR_EXAMPLE) + #define NO_TLS + #define WOLFCRYPT_ONLY #define NO_WOLFSSL_SERVER #define NO_WOLFSSL_CLIENT #define WOLFSSL_AES diff --git a/src/wolfssl-arduino.cpp b/src/wolfssl-arduino.cpp index 3d3c787..19c50a6 100644 --- a/src/wolfssl-arduino.cpp +++ b/src/wolfssl-arduino.cpp @@ -25,9 +25,33 @@ /* Function to allow wolfcrypt to use Arduino Serial.print for debug messages. * See wolfssl/wolfcrypt/logging.c */ +#if defined(__AVR__) +#include /* Required for PROGMEM handling on AVR */ +#endif + int wolfSSL_Arduino_Serial_Print(const char* const s) { /* Reminder: Serial.print is only available in C++ */ - Serial.println(F(s)); + int is_progmem = 0; + +#if defined(__AVR__) + const char* t; + t = s; + + /* Safely check if `s` is in PROGMEM, 0x8000 is typical for AVR flash */ + if (reinterpret_cast(t) >= 0x8000) { + while (pgm_read_byte(t)) { + Serial.write(pgm_read_byte(t++)); + } + Serial.println(); + is_progmem = 1; + } +#endif + + /* Print normally for non-AVR boards or RAM-stored strings */ + if (!is_progmem) { + Serial.println(s); + } + return 0; }; diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index 9f4cd66..9008976 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -316,6 +316,7 @@ /* board-specific */ #if defined(__AVR__) + #define WOLFSSL_USER_IO #define WOLFSSL_NO_SOCK #define NO_WRITEV #elif defined(__arm__) From ae219196bb6199b2c15fa5f36242467b72b510e4 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Mon, 21 Jul 2025 11:47:03 -0700 Subject: [PATCH 09/13] wolfssl 5.8.2 Release for Arduino --- COPYING | 899 +++-- ChangeLog.md | 201 ++ LICENSING | 4 +- README | 400 +- README.md | 401 +- library.properties | 2 +- src/src/bio.c | 19 +- src/src/conf.c | 2 +- src/src/crl.c | 80 +- src/src/dtls.c | 4 +- src/src/dtls13.c | 17 +- src/src/internal.c | 748 +++- src/src/keys.c | 9 +- src/src/ocsp.c | 2 +- src/src/pk.c | 254 +- src/src/quic.c | 6 +- src/src/sniffer.c | 184 +- src/src/ssl.c | 403 ++- src/src/ssl_asn1.c | 2 +- src/src/ssl_bn.c | 58 +- src/src/ssl_certman.c | 4 +- src/src/ssl_crypto.c | 112 +- src/src/ssl_load.c | 202 +- src/src/ssl_misc.c | 13 +- src/src/ssl_p7p12.c | 31 +- src/src/ssl_sess.c | 12 +- src/src/tls.c | 1667 +++++---- src/src/tls13.c | 125 +- src/src/wolfio.c | 6 +- src/src/x509.c | 224 +- src/src/x509_str.c | 56 +- src/user_settings.h | 2 +- src/wolfcrypt/src/aes.c | 51 +- src/wolfcrypt/src/arc4.c | 2 +- src/wolfcrypt/src/ascon.c | 2 +- src/wolfcrypt/src/asm.c | 2 +- src/wolfcrypt/src/asn.c | 1279 +++++-- src/wolfcrypt/src/bio.c | 19 +- src/wolfcrypt/src/blake2b.c | 6 +- src/wolfcrypt/src/blake2s.c | 2 +- src/wolfcrypt/src/camellia.c | 4 +- src/wolfcrypt/src/chacha.c | 2 +- src/wolfcrypt/src/chacha20_poly1305.c | 2 +- src/wolfcrypt/src/cmac.c | 2 +- src/wolfcrypt/src/coding.c | 2 +- src/wolfcrypt/src/compress.c | 2 +- src/wolfcrypt/src/cpuid.c | 2 +- src/wolfcrypt/src/cryptocb.c | 10 +- src/wolfcrypt/src/curve25519.c | 17 +- src/wolfcrypt/src/curve448.c | 2 +- src/wolfcrypt/src/des3.c | 14 +- src/wolfcrypt/src/dh.c | 234 +- src/wolfcrypt/src/dilithium.c | 614 ++-- src/wolfcrypt/src/dsa.c | 41 +- src/wolfcrypt/src/ecc.c | 45 +- src/wolfcrypt/src/eccsi.c | 2 +- src/wolfcrypt/src/ed25519.c | 2 +- src/wolfcrypt/src/ed448.c | 2 +- src/wolfcrypt/src/error.c | 9 +- src/wolfcrypt/src/evp.c | 68 +- src/wolfcrypt/src/ext_lms.c | 11 +- src/wolfcrypt/src/ext_mlkem.c | 2 +- src/wolfcrypt/src/ext_xmss.c | 2 +- src/wolfcrypt/src/falcon.c | 2 +- src/wolfcrypt/src/fe_448.c | 2 +- src/wolfcrypt/src/fe_low_mem.c | 2 +- src/wolfcrypt/src/fe_operations.c | 8 +- src/wolfcrypt/src/ge_448.c | 2 +- src/wolfcrypt/src/ge_low_mem.c | 2 +- src/wolfcrypt/src/ge_operations.c | 2 +- src/wolfcrypt/src/hash.c | 29 +- src/wolfcrypt/src/hmac.c | 51 +- src/wolfcrypt/src/hpke.c | 17 +- src/wolfcrypt/src/integer.c | 2 +- src/wolfcrypt/src/kdf.c | 50 +- src/wolfcrypt/src/logging.c | 154 +- src/wolfcrypt/src/md2.c | 2 +- src/wolfcrypt/src/md4.c | 2 +- src/wolfcrypt/src/md5.c | 2 +- src/wolfcrypt/src/memory.c | 2 +- src/wolfcrypt/src/misc.c | 25 +- src/wolfcrypt/src/pkcs12.c | 121 +- src/wolfcrypt/src/pkcs7.c | 67 +- src/wolfcrypt/src/poly1305.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_aes.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 17 +- .../src/port/Espressif/esp_sdk_mem_lib.c | 2 +- .../src/port/Espressif/esp_sdk_time_lib.c | 13 +- .../src/port/Espressif/esp_sdk_wifi_lib.c | 2 +- src/wolfcrypt/src/port/atmel/atmel.c | 2 +- src/wolfcrypt/src/pwdbased.c | 2 +- src/wolfcrypt/src/random.c | 429 ++- src/wolfcrypt/src/rc2.c | 2 +- src/wolfcrypt/src/ripemd.c | 2 +- src/wolfcrypt/src/rsa.c | 41 +- src/wolfcrypt/src/sakke.c | 2 +- src/wolfcrypt/src/sha.c | 3 +- src/wolfcrypt/src/sha256.c | 41 +- src/wolfcrypt/src/sha3.c | 14 +- src/wolfcrypt/src/sha512.c | 2 +- src/wolfcrypt/src/signature.c | 2 +- src/wolfcrypt/src/siphash.c | 6 +- src/wolfcrypt/src/sm2.c | 2 +- src/wolfcrypt/src/sm3.c | 2 +- src/wolfcrypt/src/sm4.c | 2 +- src/wolfcrypt/src/sp_arm32.c | 1772 +++++---- src/wolfcrypt/src/sp_arm64.c | 63 +- src/wolfcrypt/src/sp_armthumb.c | 39 +- src/wolfcrypt/src/sp_c32.c | 39 +- src/wolfcrypt/src/sp_c64.c | 39 +- src/wolfcrypt/src/sp_cortexm.c | 1765 +++++---- src/wolfcrypt/src/sp_dsp32.c | 2 +- src/wolfcrypt/src/sp_int.c | 117 +- src/wolfcrypt/src/sp_sm2_arm32.c | 2 +- src/wolfcrypt/src/sp_sm2_arm64.c | 2 +- src/wolfcrypt/src/sp_sm2_armthumb.c | 2 +- src/wolfcrypt/src/sp_sm2_c32.c | 2 +- src/wolfcrypt/src/sp_sm2_c64.c | 2 +- src/wolfcrypt/src/sp_sm2_cortexm.c | 2 +- src/wolfcrypt/src/sp_sm2_x86_64.c | 2 +- src/wolfcrypt/src/sp_x86_64.c | 39 +- src/wolfcrypt/src/sphincs.c | 2 +- src/wolfcrypt/src/srp.c | 2 +- src/wolfcrypt/src/tfm.c | 59 +- src/wolfcrypt/src/wc_dsp.c | 2 +- src/wolfcrypt/src/wc_encrypt.c | 13 +- src/wolfcrypt/src/wc_lms.c | 177 +- src/wolfcrypt/src/wc_lms_impl.c | 55 +- src/wolfcrypt/src/wc_mlkem.c | 21 +- src/wolfcrypt/src/wc_mlkem_poly.c | 113 +- src/wolfcrypt/src/wc_pkcs11.c | 10 +- src/wolfcrypt/src/wc_port.c | 118 +- src/wolfcrypt/src/wc_xmss.c | 8 +- src/wolfcrypt/src/wc_xmss_impl.c | 4 +- src/wolfcrypt/src/wolfevent.c | 2 +- src/wolfcrypt/src/wolfmath.c | 64 +- src/wolfssl-arduino.cpp | 2 +- src/wolfssl.h | 2 +- src/wolfssl/bio.c | 19 +- src/wolfssl/callbacks.h | 2 +- src/wolfssl/crl.h | 2 +- src/wolfssl/error-ssl.h | 3 +- src/wolfssl/evp.c | 68 +- src/wolfssl/internal.h | 58 +- src/wolfssl/ocsp.h | 2 +- src/wolfssl/openssl/aes.h | 2 +- src/wolfssl/openssl/asn1.h | 2 +- src/wolfssl/openssl/asn1t.h | 2 +- src/wolfssl/openssl/bio.h | 2 +- src/wolfssl/openssl/bn.h | 4 +- src/wolfssl/openssl/buffer.h | 2 +- src/wolfssl/openssl/camellia.h | 2 +- src/wolfssl/openssl/cmac.h | 2 +- src/wolfssl/openssl/cms.h | 2 +- src/wolfssl/openssl/compat_types.h | 2 +- src/wolfssl/openssl/conf.h | 2 +- src/wolfssl/openssl/crypto.h | 2 +- src/wolfssl/openssl/des.h | 2 +- src/wolfssl/openssl/dh.h | 2 +- src/wolfssl/openssl/dsa.h | 2 +- src/wolfssl/openssl/ec.h | 2 +- src/wolfssl/openssl/ec25519.h | 2 +- src/wolfssl/openssl/ec448.h | 2 +- src/wolfssl/openssl/ecdh.h | 2 +- src/wolfssl/openssl/ecdsa.h | 2 +- src/wolfssl/openssl/ed25519.h | 2 +- src/wolfssl/openssl/ed448.h | 2 +- src/wolfssl/openssl/err.h | 2 +- src/wolfssl/openssl/evp.h | 12 +- src/wolfssl/openssl/fips_rand.h | 2 +- src/wolfssl/openssl/hmac.h | 3 +- src/wolfssl/openssl/kdf.h | 2 +- src/wolfssl/openssl/lhash.h | 2 +- src/wolfssl/openssl/md4.h | 2 +- src/wolfssl/openssl/md5.h | 2 +- src/wolfssl/openssl/modes.h | 2 +- src/wolfssl/openssl/obj_mac.h | 2 +- src/wolfssl/openssl/objects.h | 2 +- src/wolfssl/openssl/ocsp.h | 2 +- src/wolfssl/openssl/opensslv.h | 2 +- src/wolfssl/openssl/ossl_typ.h | 2 +- src/wolfssl/openssl/pem.h | 2 +- src/wolfssl/openssl/pkcs12.h | 2 +- src/wolfssl/openssl/pkcs7.h | 2 +- src/wolfssl/openssl/rand.h | 2 +- src/wolfssl/openssl/rc4.h | 2 +- src/wolfssl/openssl/ripemd.h | 2 +- src/wolfssl/openssl/rsa.h | 68 +- src/wolfssl/openssl/safestack.h | 2 +- src/wolfssl/openssl/sha.h | 2 +- src/wolfssl/openssl/sha3.h | 2 +- src/wolfssl/openssl/srp.h | 2 +- src/wolfssl/openssl/ssl.h | 3 +- src/wolfssl/openssl/stack.h | 2 +- src/wolfssl/openssl/tls1.h | 2 +- src/wolfssl/openssl/txt_db.h | 2 +- src/wolfssl/openssl/x509.h | 2 +- src/wolfssl/openssl/x509_vfy.h | 2 +- src/wolfssl/openssl/x509v3.h | 9 +- src/wolfssl/quic.h | 2 +- src/wolfssl/sniffer.h | 9 +- src/wolfssl/sniffer_error.h | 2 +- src/wolfssl/ssl.h | 24 +- src/wolfssl/test.h | 27 +- src/wolfssl/version.h | 6 +- src/wolfssl/wolfcrypt/aes.h | 2 +- src/wolfssl/wolfcrypt/arc4.h | 2 +- src/wolfssl/wolfcrypt/ascon.h | 2 +- src/wolfssl/wolfcrypt/asn.h | 649 +--- src/wolfssl/wolfcrypt/asn_public.h | 131 +- src/wolfssl/wolfcrypt/blake2-impl.h | 2 +- src/wolfssl/wolfcrypt/blake2-int.h | 2 +- src/wolfssl/wolfcrypt/blake2.h | 2 +- src/wolfssl/wolfcrypt/camellia.h | 2 +- src/wolfssl/wolfcrypt/chacha.h | 2 +- src/wolfssl/wolfcrypt/chacha20_poly1305.h | 2 +- src/wolfssl/wolfcrypt/cmac.h | 2 +- src/wolfssl/wolfcrypt/coding.h | 2 +- src/wolfssl/wolfcrypt/compress.h | 2 +- src/wolfssl/wolfcrypt/cpuid.h | 20 +- src/wolfssl/wolfcrypt/cryptocb.h | 14 +- src/wolfssl/wolfcrypt/curve25519.h | 2 +- src/wolfssl/wolfcrypt/curve448.h | 2 +- src/wolfssl/wolfcrypt/des3.h | 2 +- src/wolfssl/wolfcrypt/dh.h | 14 +- src/wolfssl/wolfcrypt/dilithium.h | 28 +- src/wolfssl/wolfcrypt/dsa.h | 2 +- src/wolfssl/wolfcrypt/ecc.h | 7 +- src/wolfssl/wolfcrypt/eccsi.h | 2 +- src/wolfssl/wolfcrypt/ed25519.h | 2 +- src/wolfssl/wolfcrypt/ed448.h | 2 +- src/wolfssl/wolfcrypt/error-crypt.h | 7 +- src/wolfssl/wolfcrypt/ext_lms.h | 2 +- src/wolfssl/wolfcrypt/ext_mlkem.h | 2 +- src/wolfssl/wolfcrypt/ext_xmss.h | 2 +- src/wolfssl/wolfcrypt/falcon.h | 2 +- src/wolfssl/wolfcrypt/fe_448.h | 2 +- src/wolfssl/wolfcrypt/fe_operations.h | 2 +- src/wolfssl/wolfcrypt/fips_test.h | 2 +- src/wolfssl/wolfcrypt/ge_448.h | 2 +- src/wolfssl/wolfcrypt/ge_operations.h | 2 +- src/wolfssl/wolfcrypt/hash.h | 13 +- src/wolfssl/wolfcrypt/hmac.h | 3 +- src/wolfssl/wolfcrypt/hpke.h | 2 +- src/wolfssl/wolfcrypt/integer.h | 9 +- src/wolfssl/wolfcrypt/kdf.h | 12 +- src/wolfssl/wolfcrypt/libwolfssl_sources.h | 2 +- .../wolfcrypt/libwolfssl_sources_asm.h | 2 +- src/wolfssl/wolfcrypt/lms.h | 7 +- src/wolfssl/wolfcrypt/logging.h | 100 +- src/wolfssl/wolfcrypt/md2.h | 2 +- src/wolfssl/wolfcrypt/md4.h | 2 +- src/wolfssl/wolfcrypt/md5.h | 2 +- src/wolfssl/wolfcrypt/mem_track.h | 10 +- src/wolfssl/wolfcrypt/memory.h | 47 +- src/wolfssl/wolfcrypt/misc.h | 2 +- src/wolfssl/wolfcrypt/mlkem.h | 2 +- src/wolfssl/wolfcrypt/mpi_class.h | 2 +- src/wolfssl/wolfcrypt/mpi_superclass.h | 2 +- src/wolfssl/wolfcrypt/oid_sum.h | 1903 ++++++++++ src/wolfssl/wolfcrypt/pkcs11.h | 2 +- src/wolfssl/wolfcrypt/pkcs12.h | 2 +- src/wolfssl/wolfcrypt/pkcs7.h | 22 +- src/wolfssl/wolfcrypt/poly1305.h | 2 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 2 +- .../wolfcrypt/port/Espressif/esp32-crypt.h | 2 +- .../wolfcrypt/port/Espressif/esp_crt_bundle.h | 12 +- src/wolfssl/wolfcrypt/port/atmel/atmel.h | 2 +- src/wolfssl/wolfcrypt/pwdbased.h | 2 +- src/wolfssl/wolfcrypt/random.h | 15 +- src/wolfssl/wolfcrypt/rc2.h | 2 +- src/wolfssl/wolfcrypt/ripemd.h | 2 +- src/wolfssl/wolfcrypt/rsa.h | 2 +- src/wolfssl/wolfcrypt/sakke.h | 2 +- src/wolfssl/wolfcrypt/selftest.h | 2 +- src/wolfssl/wolfcrypt/settings.h | 153 +- src/wolfssl/wolfcrypt/sha.h | 2 +- src/wolfssl/wolfcrypt/sha256.h | 2 +- src/wolfssl/wolfcrypt/sha3.h | 32 +- src/wolfssl/wolfcrypt/sha512.h | 2 +- src/wolfssl/wolfcrypt/signature.h | 2 +- src/wolfssl/wolfcrypt/siphash.h | 2 +- src/wolfssl/wolfcrypt/sm2.h | 2 +- src/wolfssl/wolfcrypt/sm3.h | 2 +- src/wolfssl/wolfcrypt/sm4.h | 2 +- src/wolfssl/wolfcrypt/sp.h | 2 +- src/wolfssl/wolfcrypt/sp_int.h | 52 +- src/wolfssl/wolfcrypt/sphincs.h | 2 +- src/wolfssl/wolfcrypt/srp.h | 2 +- src/wolfssl/wolfcrypt/tfm.h | 5 +- src/wolfssl/wolfcrypt/types.h | 3216 +++++++++-------- src/wolfssl/wolfcrypt/visibility.h | 2 +- src/wolfssl/wolfcrypt/wc_encrypt.h | 2 +- src/wolfssl/wolfcrypt/wc_lms.h | 6 +- src/wolfssl/wolfcrypt/wc_mlkem.h | 5 +- src/wolfssl/wolfcrypt/wc_pkcs11.h | 2 +- src/wolfssl/wolfcrypt/wc_port.h | 36 +- src/wolfssl/wolfcrypt/wc_xmss.h | 2 +- src/wolfssl/wolfcrypt/wolfevent.h | 2 +- src/wolfssl/wolfcrypt/wolfmath.h | 14 +- src/wolfssl/wolfcrypt/xmss.h | 2 +- src/wolfssl/wolfio.h | 2 +- 304 files changed, 13627 insertions(+), 7756 deletions(-) create mode 100644 src/wolfssl/wolfcrypt/oid_sum.h diff --git a/COPYING b/COPYING index d159169..94a9ed0 100644 --- a/COPYING +++ b/COPYING @@ -1,281 +1,622 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ChangeLog.md b/ChangeLog.md index a9cdff9..09728ee 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,204 @@ +# wolfSSL Release 5.8.2 (July 17, 2025) + +Release 5.8.2 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * wolfSSL is now GPLv3 instead of GPLv2 + * --enable-heapmath is deprecated + * MD5 is now disabled by default + + +PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. + +## Vulnerabilities + +* [Low] There is the potential for a fault injection attack on ECC and Ed25519 verify operations. In versions of wolfSSL 5.7.6 and later the --enable-faultharden option is available to help mitigate against potential fault injection attacks. The mitigation added in wolfSSL version 5.7.6 is to help harden applications relying on the results of the verify operations, such as when used with wolfBoot. If doing ECC or Ed25519 verify operations on a device at risk for fault injection attacks then --enable-faultharden could be used to help mitigate it. Thanks to Kevin from Fraunhofer AISEC for the report. + +Hardening option added in PR https://github.com/wolfSSL/wolfssl/pull/8289 + + +* [High CVE-2025-7395] When using WOLFSSL_SYS_CA_CERTS and WOLFSSL_APPLE_NATIVE_CERT_VALIDATION on an Apple platform, the native trust store verification routine overrides errors produced elsewhere in the wolfSSL certificate verification process including failures due to hostname matching/SNI, OCSP, CRL, etc. This allows any trusted cert chain to override other errors detected during chain verification that should have resulted in termination of the TLS connection. If building wolfSSL on versions after 5.7.6 and before 5.8.2 with use of the system CA support and the apple native cert validation feature enabled on Apple devices (on by default for non-macOS Apple targets when using autotools or CMake) we recommend updating to the latest version of wolfSSL. Thanks to Thomas Leong from ExpressVPN for the report. + +Fixed in PR https://github.com/wolfSSL/wolfssl/pull/8833 + + +* [Med. CVE-2025-7394] In the OpenSSL compatibility layer implementation, the function RAND_poll() was not behaving as expected and leading to the potential for predictable values returned from RAND_bytes() after fork() is called. This can lead to weak or predictable random numbers generated in applications that are both using RAND_bytes() and doing fork() operations. This only affects applications explicitly calling RAND_bytes() after fork() and does not affect any internal TLS operations. Although RAND_bytes() documentation in OpenSSL calls out not being safe for use with fork() without first calling RAND_poll(), an additional code change was also made in wolfSSL to make RAND_bytes() behave similar to OpenSSL after a fork() call without calling RAND_poll(). Now the Hash-DRBG used gets reseeded after detecting running in a new process. If making use of RAND_bytes() and calling fork() we recommend updating to the latest version of wolfSSL. Thanks to Per Allansson from Appgate for the report. + +Fixed in the following PR’s +https://github.com/wolfSSL/wolfssl/pull/8849 +https://github.com/wolfSSL/wolfssl/pull/8867 +https://github.com/wolfSSL/wolfssl/pull/8898 + + + +* [Low CVE-2025-7396] In wolfSSL 5.8.0 the option of hardening the C implementation of Curve25519 private key operations was added with the addition of blinding support (https://www.wolfssl.com/curve25519-blinding-support-added-in-wolfssl-5-8-0/). In wolfSSL release 5.8.2 that blinding support is turned on by default in applicable builds. The blinding configure option is only for the base C implementation of Curve25519. It is not needed, or available with; ARM assembly builds, Intel assembly builds, and the small Curve25519 feature. While the attack would be very difficult to execute in practice, enabling blinding provides an additional layer of protection for devices that may be more susceptible to physical access or side-channel observation. Thanks to Arnaud Varillon, Laurent Sauvage, and Allan Delautre from Telecom Paris for the report. + +Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 + + +## New Features +* Multiple sessions are now supported in the sniffer due to the removal of a cached check. (PR #8723) +* New API ssl_RemoveSession() has been implemented for sniffer cleanup operations. (PR #8768) +* The new ASN X509 API, `wc_GetSubjectPubKeyInfoDerFromCert`, has been introduced for retrieving public key information from certificates. (PR #8758) +* `wc_PKCS12_create()` has been enhanced to support PBE_AES(256|128)_CBC key and certificate encryptions. (PR #8782, PR #8822, PR #8859) +* `wc_PKCS7_DecodeEncryptedKeyPackage()` has been added for decoding encrypted key packages. (PR #8976) +* All AES, SHA, and HMAC functionality has been implemented within the Linux Kernel Module. (PR #8998) +* Additions to the compatibility layer have been introduced for X.509 extensions and RSA PSS. Adding the API i2d_PrivateKey_bio, BN_ucmp and X509v3_get_ext_by_NID. (PR #8897) +* Added support for STM32N6. (PR #8914) +* Implemented SHA-256 for PPC 32 assembly. (PR #8894) + +## Improvements / Optimizations + +### Linux Kernel Module (LinuxKM) Enhancements +* Registered DH and FFDHE for the Linux Kernel Module. (PR #8707) +* Implemented fixes for standard RNG in the Linux Kernel Module. (PR #8718) +* Added an ECDSA workaround for the Linux Kernel Module. (PR #8727) +* Added more PKCS1 pad SHA variants for RSA in the Linux Kernel Module. (PR #8730) +* Set default priority to 100000 for LKCAPI in the Linux Kernel Module. (PR #8740) +* Ensured ECDH never has FIPS enabled in the Linux Kernel Module. (PR #8751) +* Implemented further Linux Kernel Module and SP tweaks. (PR #8773) +* Added sig_alg support for Linux 6.13 RSA in the Linux Kernel Module. (PR #8796) +* Optimized wc_linuxkm_fpu_state_assoc. (PR #8828) +* Ensured DRBG is multithread-round-1 in the Linux Kernel Module. (PR #8840) +* Prevented toggling of fips_enabled in the Linux Kernel Module. (PR #8873) +* Refactored drbg_ctx clear in the Linux Kernel Module. (PR #8876) +* Set sig_alg max_size and digest_size callbacks for RSA in the Linux Kernel Module. (PR #8915) +* Added get_random_bytes for the Linux Kernel Module. (PR #8943) +* Implemented distro fix for the Linux Kernel Module. (PR #8994) +* Fixed page-flags-h in the Linux Kernel Module. (PR #9001) +* Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) +* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms +* Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) +* Backward compatibility has been implemented for ML_KEM IDs (PR #8827) +* ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) +* Building LMS with verify-only has been fixed (PR #8913) +* Parameters for LMS SHA-256_192 have been corrected (PR #8912) +* State can now be saved with the private key for LMS (PR #8836) +* Support for OpenSSL format has been added for ML-DSA/Dilithium (PR #8947) +* `dilithium_coeff_eta2[]` has been explicitly declared as signed (PR #8955) + +### Build System & Portability +* Prepared for the inclusion of v5.8.0 in the Ada Alire index. (PR #8714) +* Introduced a new build option to allow reuse of the Windows crypt provider handle. (PR #8706) +* Introduced general fixes for various build configurations. (PR #8763) +* Made improvements for portability using older GCC 4.8.2. (PR #8753) +* Macro guards updated to allow tests to build with opensslall and no server. (PR #8776) +* Added a check for STDC_NO_ATOMICS macro before use of atomics. (PR #8885) +* Introduced CMakePresets.json and CMakeSettings.json. (PR #8905) +* Added an option to not use constant time code with min/max. (PR #8830) +* Implemented proper MacOS dispatch for conditional signal/wait. (PR #8928) +* Disabled MD5 by default for both general and CMake builds. (PR #8895, PR #8948) +* Improved to allow building OPENSSL_EXTRA without KEEP_PEER_CERT. (PR #8926) +* Added introspection for Intel and ARM assembly speedups. (PR #8954) +* Fixed cURL config to set HAVE_EX_DATA and HAVE_ALPN. (PR #8973) +* Moved FREESCALE forced algorithm HAVE_ECC to IDE/MQX/user_settings.h. (PR #8977) + +### Testing & Debugging +* Fixed the exit status for testwolfcrypt. (PR #8762) +* Added WOLFSSL_DEBUG_PRINTF and WOLFSSL_DEBUG_CERTIFICATE_LOADS for improved debugging output. (PR #8769, PR #8770) +* Guarded some benchmark tests with NO_SW_BENCH. (PR #8760) +* Added an additional unit test for wolfcrypt PKCS12 file to improve code coverage. (PR #8831) +* Added an additional unit test for increased DH code coverage. (PR #8837) +* Adjusted for warnings with NO_TLS build and added GitHub actions test. (PR #8851) +* Added additional compatibility layer RAND tests. (PR #8852) +* Added an API unit test for checking domain name. (PR #8863) +* Added bind v9.18.33 testing. (PR #8888) +* Fixed issue with benchmark help options and descriptions not lining up. (PR #8957) + +### Certificates & ASN.1 +* Changed the algorithm for sum in ASN.1 OIDs. (PR #8655) +* Updated PKCS7 to use X509 STORE for internal verification. (PR #8748) +* Improved handling of temporary buffer size for X509 extension printing. (PR #8710) +* Marked IP address as WOLFSSL_V_ASN1_OCTET_STRING for ALT_NAMES_OID. (PR #8842) +* Fixed printing empty names in certificates. (PR #8880) +* Allowed CA:FALSE on wolftpm. (PR #8925) +* Fixed several inconsistent function prototype parameter names in wc/asn. (PR #8949) +* Accounted for custom extensions when creating a Cert from a WOLFSSL_X509. (PR #8960) + +### TLS/DTLS & Handshake +* Checked group correctness outside of TLS 1.3 too for TLSX_UseSupportedCurve. (PR #8785) +* Dropped records that span datagrams in DTLS. (PR #8642) +* Implemented WC_NID_netscape_cert_type. (PR #8800) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Correctly set the current peer in dtlsProcessPendingPeer. (PR #8848) +* Fixed set_groups for TLS. (PR #8824) +* Allowed trusted_ca_keys with TLSv1.3. (PR #8860) +* Moved Dtls13NewEpoch into DeriveTls13Keys. (PR #8858) +* Cleared tls1_3 on downgrade. (PR #8861) +* Always sent ACKs on detected retransmission for DTLS1.3. (PR #8882) +* Removed DTLS from echo examples. (PR #8889) +* Recalculated suites at SSL initialization. (PR #8757) +* No longer using BIO for ALPN. (PR #8969) +* Fixed wolfSSL_BIO_new_connect's handling of IPV6 addresses. (PR #8815) +* Memory Management & Optimizations +* Performed small stack refactors, improved stack size with mlkem and dilithium, and added additional tests. (PR #8779) +* Implemented FREE_MP_INT_SIZE in heap math. (PR #8881) +* Detected correct MAX_ENCODED_SIG_SZ based on max support in math lib. (PR #8931) +* Fixed improper access of sp_int_minimal using sp_int. (PR #8985) + +### Cryptography & Hash Functions +* Implemented WC_SIPHASH_NO_ASM for not using assembly optimizations with siphash. (PR #8789, PR #8791) +* Added missing DH_MAX_SIZE define for FIPS and corrected wolfssl.rc FILETYPE to VFT_DLL. (PR #8794) +* Implemented WC_SHA3_NO_ASM for not using assembly with SHA3. (PR #8817) +* Improved Aarch64 XFENCE. (PR #8832) +* Omitted frame pointer for ARM32/Thumb2/RISC-V 64 assembly. (PR #8893) +* Fixed branch instruction in ARMv7a ASM. (PR #8933) +* Enabled EVP HMAC to work with WOLFSSL_HMAC_COPY_HASH. (PR #8944) +* Platform-Specific & Hardware Integration +* Added HAVE_HKDF for wolfssl_test and explicit support for ESP32P4. (PR #8742) +* Corrected Espressif default time setting. (PR #8829) +* Made wc_tsip_* APIs public. (PR #8717) +* Improved PlatformIO Certificate Bundle Support. (PR #8847) +* Fixed the TSIP TLS example program. (PR #8857) +* Added crypto callback functions for TROPIC01 secure element. (PR #8812) +* Added Renesas RX TSIP AES CTR support. (PR #8854) +* Fixed TSIP port using crypto callback. (PR #8937) + +### General Improvements & Refactoring +* Attempted wolfssl_read_bio_file in read_bio even when XFSEEK is available. (PR #8703) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Updated libspdm from 3.3.0 to 3.7.0. (PR #8906) +* Fixed missing dashes on the end of header and footer for Falcon PEM key. (PR #8904) +* Fixed minor code typos for macos signal and types.h max block size. (PR #8934) +* Make the API wolfSSL_X509_STORE_CTX_get_error accessible to more build configurations for ease of getting the "store" error code and depth with certificate failure callback implementations. (PR #8903) + +## Bug Fixes +* Fixed issues to support _WIN32_WCE (VS 2008 with WinCE 6.0/7.0). (PR #8709) +* Fixed STM32 Hash with IRQ enabled. (PR #8705) +* Fixed raw hash when using crypto instructions on RISC-V 64-bit. (PR #8733) +* Fixed ECDH decode secret in the Linux Kernel Module. (PR #8729) +* Passed in the correct hash type to wolfSSL_RSA_verify_ex. (PR #8726) +* Fixed issues for Intel QuickAssist latest driver (4.28). (PR #8728) +* Speculative fix for CodeSonar overflow issue in ssl_certman.c. (PR #8715) +* Fixed Arduino progmem print and AVR WOLFSSL_USER_IO. (PR #8668) +* Correctly advanced the index in wc_HKDF_Expand_ex. (PR #8737) +* Fixed STM32 hash status check logic, including NO_AES_192 and NO_AES_256. (PR #8732) +* Added missing call to wolfSSL_RefFree in FreeCRL to prevent memory leaks. (PR #8750) +* Fixed sanity check on --group with unit test app and null sanity check with des decrypt. (PR #8711) +* Fixed Curve25519 and static ephemeral issue with blinding. (PR #8766) +* Fixed edge case issue with STM32 AES GCM auth padding. (PR #8745) +* Removed redefinition of MlKemKey and fixed build issue in benchmark. (PR #8755) +* Used proper heap hint when freeing CRL in error case. (PR #8713) +* Added support for no malloc with wc_CheckCertSigPubKey. (PR #8725) +* Fixed C# wrapper Release build. (PR #8802) +* Handled malformed CCS and CCS before CH in TLS1.3. (PR #8788) +* Fixed ML-DSA with WOLFSSL_DILITHIUM_NO_SIGN. (PR #8798) +* Fixed AesGcmCrypt_1 no-stream in the Linux Kernel Module. (PR #8814) +* Fixed return value usage for crypto_sig_sign in the Linux Kernel Module. (PR #8816) +* Fixed issue with CSharp and Windows CE with conversion of ASCII and Unicode. (PR #8799) +* Fixed Renesas SCE on RA6M4. (PR #8838) +* Fixed tests for different configs for ML-DSA. (PR #8865) +* Fixed bug in ParseCRL_Extensions around the size of a CRL number handled and CRL number OID. (PR #8587) +* Fixed uninitialized wc_FreeRng in prime_test. (PR #8886) +* Fixed ECC configuration issues with ECC verify only and no RNG. (PR #8901) +* Fixed issues with max size, openssl.test netcat, and clang-tidy. (PR #8909) +* Fixed for casting down and uninit issues in Dilithium/ML-DSA. (PR #8868) +* Fixed memory allocation failure testing and related unit test cases. (PR #8945, PR #8952) +* Fixed build issue with ML-DSA 44 only. (PR #8981) +* Fixed possible memory leak with X509 reference counter when using x509small. (PR #8982) + + # wolfSSL Release 5.8.0 (Apr 24, 2025) Release 5.8.0 has been developed according to wolfSSL's development and QA diff --git a/LICENSING b/LICENSING index 24407d1..cf1d098 100644 --- a/LICENSING +++ b/LICENSING @@ -1,7 +1,7 @@ wolfSSL (formerly known as CyaSSL) and wolfCrypt are either licensed for use -under the GPLv2 (or at your option any later version) or a standard commercial -license. For our users who cannot use wolfSSL under GPLv2 +under the GPLv3 (or at your option any later version) or a standard commercial +license. For our users who cannot use wolfSSL under GPLv3 (or any later version), a commercial license to wolfSSL and wolfCrypt is available. diff --git a/README b/README index 582977d..a8e5f76 100644 --- a/README +++ b/README @@ -70,215 +70,205 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.8.0 (Apr 24, 2025) +# wolfSSL Release 5.8.2 (July 17, 2025) -Release 5.8.0 has been developed according to wolfSSL's development and QA +Release 5.8.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is deprecated - -PR stands for Pull Request, and PR references a GitHub pull request - number where the code change was added. - - -## New Feature Additions -* Algorithm registration in the Linux kernel module for all supported FIPS AES, - SHA, HMAC, ECDSA, ECDH, and RSA modes, key sizes, and digest sizes. -* Implemented various fixes to support building for Open Watcom including OS/2 - support and Open Watcom 1.9 compatibility (PR 8505, 8484) -* Added support for STM32H7S (tested on NUCLEO-H7S3L8) (PR 8488) -* Added support for STM32WBA (PR 8550) -* Added Extended Master Secret Generation Callback to the --enable-pkcallbacks - build (PR 8303) -* Implement AES-CTS (configure flag --enable-aescts) in wolfCrypt (PR 8594) -* Added support for libimobiledevice commit 860ffb (PR 8373) -* Initial ASCON hash256 and AEAD128 support based on NIST SP 800-232 IPD - (PR 8307) -* Added blinding option when using a Curve25519 private key by defining the - macro WOLFSSL_CURVE25519_BLINDING (PR 8392) - - -## Linux Kernel Module -* Production-ready LKCAPI registration for cbc(aes), cfb(aes), gcm(aes), - rfc4106 (gcm(aes)), ctr(aes), ofb(aes), and ecb(aes), ECDSA with P192, P256, - P384, and P521 curves, ECDH with P192, P256, and P384 curves, and RSA with - bare and PKCS1 padding -* Various fixes for LKCAPI wrapper for AES-CBC and AES-CFB (PR 8534, 8552) -* Adds support for the legacy one-shot AES-GCM back end (PR 8614, 8567) for - compatibility with FIPS 140-3 Cert #4718. -* On kernel >=6.8, for CONFIG_FORTIFY_SOURCE, use 5-arg fortify_panic() override - macro (PR 8654) -* Update calls to scatterwalk_map() and scatterwalk_unmap() for linux commit - 7450ebd29c (merged for Linux 6.15) (PR 8667) -* Inhibit LINUXKM_LKCAPI_REGISTER_ECDH on kernel <5.13 (PR 8673) -* Fix for uninitialized build error with fedora (PR 8569) -* Register ecdsa, ecdh, and rsa for use with linux kernel crypto (PR 8637, 8663, - 8646) -* Added force zero shared secret buffer, and clear of old key with ecdh - (PR 8685) -* Update fips-check.sh script to pickup XTS streaming support on aarch64 and - disable XTS-384 as an allowed use in FIPS mode (PR 8509, 8546) - - -## Enhancements and Optimizations - -### Security & Cryptography -* Add constant-time implementation improvements for encoding functions. We thank - Zhiyuan and Gilles for sharing a new constant-time analysis tool (CT-LLVM) and - reporting several non-constant-time implementations. (PR 8396, 8617) -* Additional support for PKCS7 verify and decode with indefinite lengths - (PR 8520, 834, 8645) -* Add more PQC hybrid key exchange algorithms such as support for combinations - with X25519 and X448 enabling compatibility with the PQC key exchange support - in Chromium browsers and Mozilla Firefox (PR 7821) -* Add short-circuit comparisons to DH key validation for RFC 7919 parameters - (PR 8335) -* Improve FIPS compatibility with various build configurations for more resource - constrained builds (PR 8370) -* Added option to disable ECC public key order checking (PR 8581) -* Allow critical alt and basic constraints extensions (PR 8542) -* New codepoint for MLDSA to help with interoperability (PR 8393) -* Add support for parsing trusted PEM certs having the header - “BEGIN_TRUSTED_CERT” (PR 8400) -* Add support for parsing only of DoD certificate policy and Comodo Ltd PKI OIDs - (PR 8599, 8686) -* Update ssl code in `src/*.c` to be consistent with wolfcrypt/src/asn.c - handling of ML_DSA vs Dilithium and add dual alg. test (PR 8360, 8425) - -### Build System, Configuration, CI & Protocols -* Internal refactor for include of config.h and when building with - BUILDING_WOLFSSL macro. This refactor will give a warning of “deprecated - function” when trying to improperly use an internal API of wolfSSL in an - external application. (PR 8640, 8647, 8660, 8662, 8664) -* Add WOLFSSL_CLU option to CMakeLists.txt (PR 8548) -* Add CMake and Zephyr support for XMSS and LMS (PR 8494) -* Added GitHub CI for CMake builds (PR 8439) -* Added necessary macros when building wolfTPM Zephyr with wolfSSL (PR 8382) -* Add MSYS2 build continuous integration test (PR 8504) -* Update DevKitPro doc to list calico dependency with build commands (PR 8607) -* Conversion compiler warning fixes and additional continuous integration test - added (PR 8538) -* Enable DTLS 1.3 by default in --enable-jni builds (PR 8481) -* Enabled TLS 1.3 middlebox compatibility by default for --enable-jni builds - (PR 8526) - -### Performance Improvements -* Performance improvements AES-GCM and HMAC (in/out hash copy) (PR 8429) -* LMS fixes and improvements adding API to get Key ID from raw private key, - change to identifiers to match standard, and fix for when - WOLFSSL_LMS_MAX_LEVELS is 1 (PR 8390, 8684, 8613, 8623) -* ML-KEM/Kyber improvements and fixes; no malloc builds, small memory usage, - performance improvement, fix for big-endian (PR 8397, 8412, 8436, 8467, 8619, - 8622, 8588) -* Performance improvements for AES-GCM and when doing multiple HMAC operations - (PR 8445) - -### Assembly and Platform-Specific Enhancements -* Poly1305 arm assembly changes adding ARM32 NEON implementation and fix for - Aarch64 use (PR 8344, 8561, 8671) -* Aarch64 assembly enhancement to use more CPU features, fix for FreeBSD/OpenBSD - (PR 8325, 8348) -* Only perform ARM assembly CPUID checks if support was enabled at build time - (PR 8566) -* Optimizations for ARM32 assembly instructions on platforms less than ARMv7 - (PR 8395) -* Improve MSVC feature detection for static assert macros (PR 8440) -* Improve Espressif make and CMake for ESP8266 and ESP32 series (PR 8402) -* Espressif updates for Kconfig, ESP32P4 and adding a sample user_settings.h - (PR 8422, PR 8641) - -### OpenSSL Compatibility Layer -* Modification to the push/pop to/from in OpenSSL compatibility layer. This is - a pretty major API change in the OpenSSL compatibility stack functions. - Previously the API would push/pop from the beginning of the list but now they - operate on the tail of the list. This matters when using the sk_value with - index values. (PR 8616) -* OpenSSL Compat Layer: OCSP response improvements (PR 8408, 8498) -* Expand the OpenSSL compatibility layer to include an implementation of - BN_CTX_get (PR 8388) - -### API Additions and Modifications -* Refactor Hpke to allow multiple uses of a context instead of just one shot - mode (PR 6805) -* Add support for PSK client callback with Ada and use with Alire (thanks - @mgrojo, PR 8332, 8606) -* Change wolfSSL_CTX_GenerateEchConfig to generate multiple configs and add - functions wolfSSL_CTX_SetEchConfigs and wolfSSL_CTX_SetEchConfigsBase64 to - rotate the server's echConfigs (PR 8556) -* Added the public API wc_PkcsPad to do PKCS padding (PR 8502) -* Add NULL_CIPHER_TYPE support to wolfSSL_EVP_CipherUpdate (PR 8518) -* Update Kyber APIs to ML-KEM APIs (PR 8536) -* Add option to disallow automatic use of "default" devId using the macro - WC_NO_DEFAULT_DEVID (PR 8555) -* Detect unknown key format on ProcessBufferTryDecode() and handle RSA-PSSk - format (PR 8630) - -### Porting and Language Support -* Update Python port to support version 3.12.6 (PR 8345) -* New additions for MAXQ with wolfPKCS11 (PR 8343) -* Port to ntp 4.2.8p17 additions (PR 8324) -* Add version 0.9.14 to tested libvncserver builds (PR 8337) - -### General Improvements and Cleanups -* Cleanups for STM32 AES GCM (PR 8584) -* Improvements to isascii() and the CMake key log option (PR 8596) -* Arduino documentation updates, comments and spelling corrections (PR 8381, - 8384, 8514) -* Expanding builds with WOLFSSL_NO_REALLOC for use with --enable-opensslall and - --enable-all builds (PR 8369, 8371) - - -## Fixes -* Fix a use after free caused by an early free on error in the X509 store - (PR 8449) -* Fix to account for existing PKCS8 header with - wolfSSL_PEM_write_PKCS8PrivateKey (PR 8612) -* Fixed failing CMake build issue when standard threads support is not found in - the system (PR 8485) -* Fix segmentation fault in SHA-512 implementation for AVX512 targets built with - gcc -march=native -O2 (PR 8329) -* Fix Windows socket API compatibility warning with mingw32 build (PR 8424) -* Fix potential null pointer increments in cipher list parsing (PR 8420) -* Fix for possible stack buffer overflow read with wolfSSL_SMIME_write_PKCS7. - Thanks to the team at Code Intelligence for the report. (PR 8466) -* Fix AES ECB implementation for Aarch64 ARM assembly (PR 8379) -* Fixed building with VS2008 and .NET 3.5 (PR 8621) -* Fixed possible error case memory leaks in CRL and EVP_Sign_Final (PR 8447) -* Fixed SSL_set_mtu compatibility function return code (PR 8330) -* Fixed Renesas RX TSIP (PR 8595) -* Fixed ECC non-blocking tests (PR 8533) -* Fixed CMake on MINGW and MSYS (PR 8377) -* Fixed Watcom compiler and added new CI test (PR 8391) -* Fixed STM32 PKA ECC 521-bit support (PR 8450) -* Fixed STM32 PKA with P521 and shared secret (PR 8601) -* Fixed crypto callback macro guards with `DEBUG_CRYPTOCB` (PR 8602) -* Fix outlen return for RSA private decrypt with WOLF_CRYPTO_CB_RSA_PAD - (PR 8575) -* Additional sanity check on r and s lengths in DecodeECC_DSA_Sig_Bin (PR 8350) -* Fix compat. layer ASN1_TIME_diff to accept NULL output params (PR 8407) -* Fix CMake lean_tls build (PR 8460) -* Fix for QUIC callback failure (PR 8475) -* Fix missing alert types in AlertTypeToString for print out with debugging - enabled (PR 8572) -* Fixes for MSVS build issues with PQC configure (PR 8568) -* Fix for SE050 port and minor improvements (PR 8431, 8437) -* Fix for missing rewind function in zephyr and add missing files for compiling - with assembly optimizations (PR 8531, 8541) -* Fix for quic_record_append to return the correct code (PR 8340, 8358) -* Fixes for Bind 9.18.28 port (PR 8331) -* Fix to adhere more closely with RFC8446 Appendix D and set haveEMS when - negotiating TLS 1.3 (PR 8487) -* Fix to properly check for signature_algorithms from the client in a TLS 1.3 - server (PR 8356) -* Fix for when BIO data is less than seq buffer size. Thanks to the team at Code - Intelligence for the report (PR 8426) -* ARM32/Thumb2 fixes for WOLFSSL_NO_VAR_ASSIGN_REG and td4 variable declarations - (PR 8590, 8635) -* Fix for Intel AVX1/SSE2 assembly to not use vzeroupper instructions unless ymm - or zmm registers are used (PR 8479) -* Entropy MemUse fix for when block size less than update bits (PR 8675) - +NOTE: * wolfSSL is now GPLv3 instead of GPLv2 + * --enable-heapmath is deprecated + * MD5 is now disabled by default + + +PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. + +## Vulnerabilities + +* [Low] There is the potential for a fault injection attack on ECC and Ed25519 verify operations. In versions of wolfSSL 5.7.6 and later the --enable-faultharden option is available to help mitigate against potential fault injection attacks. The mitigation added in wolfSSL version 5.7.6 is to help harden applications relying on the results of the verify operations, such as when used with wolfBoot. If doing ECC or Ed25519 verify operations on a device at risk for fault injection attacks then --enable-faultharden could be used to help mitigate it. Thanks to Kevin from Fraunhofer AISEC for the report. + +Hardening option added in PR https://github.com/wolfSSL/wolfssl/pull/8289 + + +* [High CVE-2025-7395] When using WOLFSSL_SYS_CA_CERTS and WOLFSSL_APPLE_NATIVE_CERT_VALIDATION on an Apple platform, the native trust store verification routine overrides errors produced elsewhere in the wolfSSL certificate verification process including failures due to hostname matching/SNI, OCSP, CRL, etc. This allows any trusted cert chain to override other errors detected during chain verification that should have resulted in termination of the TLS connection. If building wolfSSL on versions after 5.7.6 and before 5.8.2 with use of the system CA support and the apple native cert validation feature enabled on Apple devices (on by default for non-macOS Apple targets when using autotools or CMake) we recommend updating to the latest version of wolfSSL. Thanks to Thomas Leong from ExpressVPN for the report. + +Fixed in PR https://github.com/wolfSSL/wolfssl/pull/8833 + + +* [Med. CVE-2025-7394] In the OpenSSL compatibility layer implementation, the function RAND_poll() was not behaving as expected and leading to the potential for predictable values returned from RAND_bytes() after fork() is called. This can lead to weak or predictable random numbers generated in applications that are both using RAND_bytes() and doing fork() operations. This only affects applications explicitly calling RAND_bytes() after fork() and does not affect any internal TLS operations. Although RAND_bytes() documentation in OpenSSL calls out not being safe for use with fork() without first calling RAND_poll(), an additional code change was also made in wolfSSL to make RAND_bytes() behave similar to OpenSSL after a fork() call without calling RAND_poll(). Now the Hash-DRBG used gets reseeded after detecting running in a new process. If making use of RAND_bytes() and calling fork() we recommend updating to the latest version of wolfSSL. Thanks to Per Allansson from Appgate for the report. + +Fixed in the following PR’s +https://github.com/wolfSSL/wolfssl/pull/8849 +https://github.com/wolfSSL/wolfssl/pull/8867 +https://github.com/wolfSSL/wolfssl/pull/8898 + + + +* [Low CVE-2025-7396] In wolfSSL 5.8.0 the option of hardening the C implementation of Curve25519 private key operations was added with the addition of blinding support (https://www.wolfssl.com/curve25519-blinding-support-added-in-wolfssl-5-8-0/). In wolfSSL release 5.8.2 that blinding support is turned on by default in applicable builds. The blinding configure option is only for the base C implementation of Curve25519. It is not needed, or available with; ARM assembly builds, Intel assembly builds, and the small Curve25519 feature. While the attack would be very difficult to execute in practice, enabling blinding provides an additional layer of protection for devices that may be more susceptible to physical access or side-channel observation. Thanks to Arnaud Varillon, Laurent Sauvage, and Allan Delautre from Telecom Paris for the report. + +Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 + + +## New Features +* Multiple sessions are now supported in the sniffer due to the removal of a cached check. (PR #8723) +* New API ssl_RemoveSession() has been implemented for sniffer cleanup operations. (PR #8768) +* The new ASN X509 API, `wc_GetSubjectPubKeyInfoDerFromCert`, has been introduced for retrieving public key information from certificates. (PR #8758) +* `wc_PKCS12_create()` has been enhanced to support PBE_AES(256|128)_CBC key and certificate encryptions. (PR #8782, PR #8822, PR #8859) +* `wc_PKCS7_DecodeEncryptedKeyPackage()` has been added for decoding encrypted key packages. (PR #8976) +* All AES, SHA, and HMAC functionality has been implemented within the Linux Kernel Module. (PR #8998) +* Additions to the compatibility layer have been introduced for X.509 extensions and RSA PSS. Adding the API i2d_PrivateKey_bio, BN_ucmp and X509v3_get_ext_by_NID. (PR #8897) +* Added support for STM32N6. (PR #8914) +* Implemented SHA-256 for PPC 32 assembly. (PR #8894) + +## Improvements / Optimizations + +### Linux Kernel Module (LinuxKM) Enhancements +* Registered DH and FFDHE for the Linux Kernel Module. (PR #8707) +* Implemented fixes for standard RNG in the Linux Kernel Module. (PR #8718) +* Added an ECDSA workaround for the Linux Kernel Module. (PR #8727) +* Added more PKCS1 pad SHA variants for RSA in the Linux Kernel Module. (PR #8730) +* Set default priority to 100000 for LKCAPI in the Linux Kernel Module. (PR #8740) +* Ensured ECDH never has FIPS enabled in the Linux Kernel Module. (PR #8751) +* Implemented further Linux Kernel Module and SP tweaks. (PR #8773) +* Added sig_alg support for Linux 6.13 RSA in the Linux Kernel Module. (PR #8796) +* Optimized wc_linuxkm_fpu_state_assoc. (PR #8828) +* Ensured DRBG is multithread-round-1 in the Linux Kernel Module. (PR #8840) +* Prevented toggling of fips_enabled in the Linux Kernel Module. (PR #8873) +* Refactored drbg_ctx clear in the Linux Kernel Module. (PR #8876) +* Set sig_alg max_size and digest_size callbacks for RSA in the Linux Kernel Module. (PR #8915) +* Added get_random_bytes for the Linux Kernel Module. (PR #8943) +* Implemented distro fix for the Linux Kernel Module. (PR #8994) +* Fixed page-flags-h in the Linux Kernel Module. (PR #9001) +* Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) +* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms +* Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) +* Backward compatibility has been implemented for ML_KEM IDs (PR #8827) +* ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) +* Building LMS with verify-only has been fixed (PR #8913) +* Parameters for LMS SHA-256_192 have been corrected (PR #8912) +* State can now be saved with the private key for LMS (PR #8836) +* Support for OpenSSL format has been added for ML-DSA/Dilithium (PR #8947) +* `dilithium_coeff_eta2[]` has been explicitly declared as signed (PR #8955) + +### Build System & Portability +* Prepared for the inclusion of v5.8.0 in the Ada Alire index. (PR #8714) +* Introduced a new build option to allow reuse of the Windows crypt provider handle. (PR #8706) +* Introduced general fixes for various build configurations. (PR #8763) +* Made improvements for portability using older GCC 4.8.2. (PR #8753) +* Macro guards updated to allow tests to build with opensslall and no server. (PR #8776) +* Added a check for STDC_NO_ATOMICS macro before use of atomics. (PR #8885) +* Introduced CMakePresets.json and CMakeSettings.json. (PR #8905) +* Added an option to not use constant time code with min/max. (PR #8830) +* Implemented proper MacOS dispatch for conditional signal/wait. (PR #8928) +* Disabled MD5 by default for both general and CMake builds. (PR #8895, PR #8948) +* Improved to allow building OPENSSL_EXTRA without KEEP_PEER_CERT. (PR #8926) +* Added introspection for Intel and ARM assembly speedups. (PR #8954) +* Fixed cURL config to set HAVE_EX_DATA and HAVE_ALPN. (PR #8973) +* Moved FREESCALE forced algorithm HAVE_ECC to IDE/MQX/user_settings.h. (PR #8977) + +### Testing & Debugging +* Fixed the exit status for testwolfcrypt. (PR #8762) +* Added WOLFSSL_DEBUG_PRINTF and WOLFSSL_DEBUG_CERTIFICATE_LOADS for improved debugging output. (PR #8769, PR #8770) +* Guarded some benchmark tests with NO_SW_BENCH. (PR #8760) +* Added an additional unit test for wolfcrypt PKCS12 file to improve code coverage. (PR #8831) +* Added an additional unit test for increased DH code coverage. (PR #8837) +* Adjusted for warnings with NO_TLS build and added GitHub actions test. (PR #8851) +* Added additional compatibility layer RAND tests. (PR #8852) +* Added an API unit test for checking domain name. (PR #8863) +* Added bind v9.18.33 testing. (PR #8888) +* Fixed issue with benchmark help options and descriptions not lining up. (PR #8957) + +### Certificates & ASN.1 +* Changed the algorithm for sum in ASN.1 OIDs. (PR #8655) +* Updated PKCS7 to use X509 STORE for internal verification. (PR #8748) +* Improved handling of temporary buffer size for X509 extension printing. (PR #8710) +* Marked IP address as WOLFSSL_V_ASN1_OCTET_STRING for ALT_NAMES_OID. (PR #8842) +* Fixed printing empty names in certificates. (PR #8880) +* Allowed CA:FALSE on wolftpm. (PR #8925) +* Fixed several inconsistent function prototype parameter names in wc/asn. (PR #8949) +* Accounted for custom extensions when creating a Cert from a WOLFSSL_X509. (PR #8960) + +### TLS/DTLS & Handshake +* Checked group correctness outside of TLS 1.3 too for TLSX_UseSupportedCurve. (PR #8785) +* Dropped records that span datagrams in DTLS. (PR #8642) +* Implemented WC_NID_netscape_cert_type. (PR #8800) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Correctly set the current peer in dtlsProcessPendingPeer. (PR #8848) +* Fixed set_groups for TLS. (PR #8824) +* Allowed trusted_ca_keys with TLSv1.3. (PR #8860) +* Moved Dtls13NewEpoch into DeriveTls13Keys. (PR #8858) +* Cleared tls1_3 on downgrade. (PR #8861) +* Always sent ACKs on detected retransmission for DTLS1.3. (PR #8882) +* Removed DTLS from echo examples. (PR #8889) +* Recalculated suites at SSL initialization. (PR #8757) +* No longer using BIO for ALPN. (PR #8969) +* Fixed wolfSSL_BIO_new_connect's handling of IPV6 addresses. (PR #8815) +* Memory Management & Optimizations +* Performed small stack refactors, improved stack size with mlkem and dilithium, and added additional tests. (PR #8779) +* Implemented FREE_MP_INT_SIZE in heap math. (PR #8881) +* Detected correct MAX_ENCODED_SIG_SZ based on max support in math lib. (PR #8931) +* Fixed improper access of sp_int_minimal using sp_int. (PR #8985) + +### Cryptography & Hash Functions +* Implemented WC_SIPHASH_NO_ASM for not using assembly optimizations with siphash. (PR #8789, PR #8791) +* Added missing DH_MAX_SIZE define for FIPS and corrected wolfssl.rc FILETYPE to VFT_DLL. (PR #8794) +* Implemented WC_SHA3_NO_ASM for not using assembly with SHA3. (PR #8817) +* Improved Aarch64 XFENCE. (PR #8832) +* Omitted frame pointer for ARM32/Thumb2/RISC-V 64 assembly. (PR #8893) +* Fixed branch instruction in ARMv7a ASM. (PR #8933) +* Enabled EVP HMAC to work with WOLFSSL_HMAC_COPY_HASH. (PR #8944) +* Platform-Specific & Hardware Integration +* Added HAVE_HKDF for wolfssl_test and explicit support for ESP32P4. (PR #8742) +* Corrected Espressif default time setting. (PR #8829) +* Made wc_tsip_* APIs public. (PR #8717) +* Improved PlatformIO Certificate Bundle Support. (PR #8847) +* Fixed the TSIP TLS example program. (PR #8857) +* Added crypto callback functions for TROPIC01 secure element. (PR #8812) +* Added Renesas RX TSIP AES CTR support. (PR #8854) +* Fixed TSIP port using crypto callback. (PR #8937) + +### General Improvements & Refactoring +* Attempted wolfssl_read_bio_file in read_bio even when XFSEEK is available. (PR #8703) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Updated libspdm from 3.3.0 to 3.7.0. (PR #8906) +* Fixed missing dashes on the end of header and footer for Falcon PEM key. (PR #8904) +* Fixed minor code typos for macos signal and types.h max block size. (PR #8934) +* Make the API wolfSSL_X509_STORE_CTX_get_error accessible to more build configurations for ease of getting the "store" error code and depth with certificate failure callback implementations. (PR #8903) + +## Bug Fixes +* Fixed issues to support _WIN32_WCE (VS 2008 with WinCE 6.0/7.0). (PR #8709) +* Fixed STM32 Hash with IRQ enabled. (PR #8705) +* Fixed raw hash when using crypto instructions on RISC-V 64-bit. (PR #8733) +* Fixed ECDH decode secret in the Linux Kernel Module. (PR #8729) +* Passed in the correct hash type to wolfSSL_RSA_verify_ex. (PR #8726) +* Fixed issues for Intel QuickAssist latest driver (4.28). (PR #8728) +* Speculative fix for CodeSonar overflow issue in ssl_certman.c. (PR #8715) +* Fixed Arduino progmem print and AVR WOLFSSL_USER_IO. (PR #8668) +* Correctly advanced the index in wc_HKDF_Expand_ex. (PR #8737) +* Fixed STM32 hash status check logic, including NO_AES_192 and NO_AES_256. (PR #8732) +* Added missing call to wolfSSL_RefFree in FreeCRL to prevent memory leaks. (PR #8750) +* Fixed sanity check on --group with unit test app and null sanity check with des decrypt. (PR #8711) +* Fixed Curve25519 and static ephemeral issue with blinding. (PR #8766) +* Fixed edge case issue with STM32 AES GCM auth padding. (PR #8745) +* Removed redefinition of MlKemKey and fixed build issue in benchmark. (PR #8755) +* Used proper heap hint when freeing CRL in error case. (PR #8713) +* Added support for no malloc with wc_CheckCertSigPubKey. (PR #8725) +* Fixed C# wrapper Release build. (PR #8802) +* Handled malformed CCS and CCS before CH in TLS1.3. (PR #8788) +* Fixed ML-DSA with WOLFSSL_DILITHIUM_NO_SIGN. (PR #8798) +* Fixed AesGcmCrypt_1 no-stream in the Linux Kernel Module. (PR #8814) +* Fixed return value usage for crypto_sig_sign in the Linux Kernel Module. (PR #8816) +* Fixed issue with CSharp and Windows CE with conversion of ASCII and Unicode. (PR #8799) +* Fixed Renesas SCE on RA6M4. (PR #8838) +* Fixed tests for different configs for ML-DSA. (PR #8865) +* Fixed bug in ParseCRL_Extensions around the size of a CRL number handled and CRL number OID. (PR #8587) +* Fixed uninitialized wc_FreeRng in prime_test. (PR #8886) +* Fixed ECC configuration issues with ECC verify only and no RNG. (PR #8901) +* Fixed issues with max size, openssl.test netcat, and clang-tidy. (PR #8909) +* Fixed for casting down and uninit issues in Dilithium/ML-DSA. (PR #8868) +* Fixed memory allocation failure testing and related unit test cases. (PR #8945, PR #8952) +* Fixed build issue with ML-DSA 44 only. (PR #8981) +* Fixed possible memory leak with X509 reference counter when using x509small. (PR #8982) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/README.md b/README.md index 7c0fd06..13265b3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.8.0 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.8.2 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -124,214 +124,205 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.8.0 (Apr 24, 2025) +# wolfSSL Release 5.8.2 (July 17, 2025) -Release 5.8.0 has been developed according to wolfSSL's development and QA +Release 5.8.2 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * --enable-heapmath is deprecated - -PR stands for Pull Request, and PR references a GitHub pull request - number where the code change was added. - - -## New Feature Additions -* Algorithm registration in the Linux kernel module for all supported FIPS AES, - SHA, HMAC, ECDSA, ECDH, and RSA modes, key sizes, and digest sizes. -* Implemented various fixes to support building for Open Watcom including OS/2 - support and Open Watcom 1.9 compatibility (PR 8505, 8484) -* Added support for STM32H7S (tested on NUCLEO-H7S3L8) (PR 8488) -* Added support for STM32WBA (PR 8550) -* Added Extended Master Secret Generation Callback to the --enable-pkcallbacks - build (PR 8303) -* Implement AES-CTS (configure flag --enable-aescts) in wolfCrypt (PR 8594) -* Added support for libimobiledevice commit 860ffb (PR 8373) -* Initial ASCON hash256 and AEAD128 support based on NIST SP 800-232 IPD - (PR 8307) -* Added blinding option when using a Curve25519 private key by defining the - macro WOLFSSL_CURVE25519_BLINDING (PR 8392) - - -## Linux Kernel Module -* Production-ready LKCAPI registration for cbc(aes), cfb(aes), gcm(aes), - rfc4106 (gcm(aes)), ctr(aes), ofb(aes), and ecb(aes), ECDSA with P192, P256, - P384, and P521 curves, ECDH with P192, P256, and P384 curves, and RSA with - bare and PKCS1 padding -* Various fixes for LKCAPI wrapper for AES-CBC and AES-CFB (PR 8534, 8552) -* Adds support for the legacy one-shot AES-GCM back end (PR 8614, 8567) for - compatibility with FIPS 140-3 Cert #4718. -* On kernel >=6.8, for CONFIG_FORTIFY_SOURCE, use 5-arg fortify_panic() override - macro (PR 8654) -* Update calls to scatterwalk_map() and scatterwalk_unmap() for linux commit - 7450ebd29c (merged for Linux 6.15) (PR 8667) -* Inhibit LINUXKM_LKCAPI_REGISTER_ECDH on kernel <5.13 (PR 8673) -* Fix for uninitialized build error with fedora (PR 8569) -* Register ecdsa, ecdh, and rsa for use with linux kernel crypto (PR 8637, 8663, - 8646) -* Added force zero shared secret buffer, and clear of old key with ecdh - (PR 8685) -* Update fips-check.sh script to pickup XTS streaming support on aarch64 and - disable XTS-384 as an allowed use in FIPS mode (PR 8509, 8546) - - -## Enhancements and Optimizations - -### Security & Cryptography -* Add constant-time implementation improvements for encoding functions. We thank - Zhiyuan and Gilles for sharing a new constant-time analysis tool (CT-LLVM) and - reporting several non-constant-time implementations. (PR 8396, 8617) -* Additional support for PKCS7 verify and decode with indefinite lengths - (PR 8520, 834, 8645) -* Add more PQC hybrid key exchange algorithms such as support for combinations - with X25519 and X448 enabling compatibility with the PQC key exchange support - in Chromium browsers and Mozilla Firefox (PR 7821) -* Add short-circuit comparisons to DH key validation for RFC 7919 parameters - (PR 8335) -* Improve FIPS compatibility with various build configurations for more resource - constrained builds (PR 8370) -* Added option to disable ECC public key order checking (PR 8581) -* Allow critical alt and basic constraints extensions (PR 8542) -* New codepoint for MLDSA to help with interoperability (PR 8393) -* Add support for parsing trusted PEM certs having the header - “BEGIN_TRUSTED_CERT” (PR 8400) -* Add support for parsing only of DoD certificate policy and Comodo Ltd PKI OIDs - (PR 8599, 8686) -* Update ssl code in `src/*.c` to be consistent with wolfcrypt/src/asn.c - handling of ML_DSA vs Dilithium and add dual alg. test (PR 8360, 8425) - -### Build System, Configuration, CI & Protocols -* Internal refactor for include of config.h and when building with - BUILDING_WOLFSSL macro. This refactor will give a warning of “deprecated - function” when trying to improperly use an internal API of wolfSSL in an - external application. (PR 8640, 8647, 8660, 8662, 8664) -* Add WOLFSSL_CLU option to CMakeLists.txt (PR 8548) -* Add CMake and Zephyr support for XMSS and LMS (PR 8494) -* Added GitHub CI for CMake builds (PR 8439) -* Added necessary macros when building wolfTPM Zephyr with wolfSSL (PR 8382) -* Add MSYS2 build continuous integration test (PR 8504) -* Update DevKitPro doc to list calico dependency with build commands (PR 8607) -* Conversion compiler warning fixes and additional continuous integration test - added (PR 8538) -* Enable DTLS 1.3 by default in --enable-jni builds (PR 8481) -* Enabled TLS 1.3 middlebox compatibility by default for --enable-jni builds - (PR 8526) - -### Performance Improvements -* Performance improvements AES-GCM and HMAC (in/out hash copy) (PR 8429) -* LMS fixes and improvements adding API to get Key ID from raw private key, - change to identifiers to match standard, and fix for when - WOLFSSL_LMS_MAX_LEVELS is 1 (PR 8390, 8684, 8613, 8623) -* ML-KEM/Kyber improvements and fixes; no malloc builds, small memory usage, - performance improvement, fix for big-endian (PR 8397, 8412, 8436, 8467, 8619, - 8622, 8588) -* Performance improvements for AES-GCM and when doing multiple HMAC operations - (PR 8445) - -### Assembly and Platform-Specific Enhancements -* Poly1305 arm assembly changes adding ARM32 NEON implementation and fix for - Aarch64 use (PR 8344, 8561, 8671) -* Aarch64 assembly enhancement to use more CPU features, fix for FreeBSD/OpenBSD - (PR 8325, 8348) -* Only perform ARM assembly CPUID checks if support was enabled at build time - (PR 8566) -* Optimizations for ARM32 assembly instructions on platforms less than ARMv7 - (PR 8395) -* Improve MSVC feature detection for static assert macros (PR 8440) -* Improve Espressif make and CMake for ESP8266 and ESP32 series (PR 8402) -* Espressif updates for Kconfig, ESP32P4 and adding a sample user_settings.h - (PR 8422, PR 8641) - -### OpenSSL Compatibility Layer -* Modification to the push/pop to/from in OpenSSL compatibility layer. This is - a pretty major API change in the OpenSSL compatibility stack functions. - Previously the API would push/pop from the beginning of the list but now they - operate on the tail of the list. This matters when using the sk_value with - index values. (PR 8616) -* OpenSSL Compat Layer: OCSP response improvements (PR 8408, 8498) -* Expand the OpenSSL compatibility layer to include an implementation of - BN_CTX_get (PR 8388) - -### API Additions and Modifications -* Refactor Hpke to allow multiple uses of a context instead of just one shot - mode (PR 6805) -* Add support for PSK client callback with Ada and use with Alire (thanks - @mgrojo, PR 8332, 8606) -* Change wolfSSL_CTX_GenerateEchConfig to generate multiple configs and add - functions wolfSSL_CTX_SetEchConfigs and wolfSSL_CTX_SetEchConfigsBase64 to - rotate the server's echConfigs (PR 8556) -* Added the public API wc_PkcsPad to do PKCS padding (PR 8502) -* Add NULL_CIPHER_TYPE support to wolfSSL_EVP_CipherUpdate (PR 8518) -* Update Kyber APIs to ML-KEM APIs (PR 8536) -* Add option to disallow automatic use of "default" devId using the macro - WC_NO_DEFAULT_DEVID (PR 8555) -* Detect unknown key format on ProcessBufferTryDecode() and handle RSA-PSSk - format (PR 8630) - -### Porting and Language Support -* Update Python port to support version 3.12.6 (PR 8345) -* New additions for MAXQ with wolfPKCS11 (PR 8343) -* Port to ntp 4.2.8p17 additions (PR 8324) -* Add version 0.9.14 to tested libvncserver builds (PR 8337) - -### General Improvements and Cleanups -* Cleanups for STM32 AES GCM (PR 8584) -* Improvements to isascii() and the CMake key log option (PR 8596) -* Arduino documentation updates, comments and spelling corrections (PR 8381, - 8384, 8514) -* Expanding builds with WOLFSSL_NO_REALLOC for use with --enable-opensslall and - --enable-all builds (PR 8369, 8371) - - -## Fixes -* Fix a use after free caused by an early free on error in the X509 store - (PR 8449) -* Fix to account for existing PKCS8 header with - wolfSSL_PEM_write_PKCS8PrivateKey (PR 8612) -* Fixed failing CMake build issue when standard threads support is not found in - the system (PR 8485) -* Fix segmentation fault in SHA-512 implementation for AVX512 targets built with - gcc -march=native -O2 (PR 8329) -* Fix Windows socket API compatibility warning with mingw32 build (PR 8424) -* Fix potential null pointer increments in cipher list parsing (PR 8420) -* Fix for possible stack buffer overflow read with wolfSSL_SMIME_write_PKCS7. - Thanks to the team at Code Intelligence for the report. (PR 8466) -* Fix AES ECB implementation for Aarch64 ARM assembly (PR 8379) -* Fixed building with VS2008 and .NET 3.5 (PR 8621) -* Fixed possible error case memory leaks in CRL and EVP_Sign_Final (PR 8447) -* Fixed SSL_set_mtu compatibility function return code (PR 8330) -* Fixed Renesas RX TSIP (PR 8595) -* Fixed ECC non-blocking tests (PR 8533) -* Fixed CMake on MINGW and MSYS (PR 8377) -* Fixed Watcom compiler and added new CI test (PR 8391) -* Fixed STM32 PKA ECC 521-bit support (PR 8450) -* Fixed STM32 PKA with P521 and shared secret (PR 8601) -* Fixed crypto callback macro guards with `DEBUG_CRYPTOCB` (PR 8602) -* Fix outlen return for RSA private decrypt with WOLF_CRYPTO_CB_RSA_PAD - (PR 8575) -* Additional sanity check on r and s lengths in DecodeECC_DSA_Sig_Bin (PR 8350) -* Fix compat. layer ASN1_TIME_diff to accept NULL output params (PR 8407) -* Fix CMake lean_tls build (PR 8460) -* Fix for QUIC callback failure (PR 8475) -* Fix missing alert types in AlertTypeToString for print out with debugging - enabled (PR 8572) -* Fixes for MSVS build issues with PQC configure (PR 8568) -* Fix for SE050 port and minor improvements (PR 8431, 8437) -* Fix for missing rewind function in zephyr and add missing files for compiling - with assembly optimizations (PR 8531, 8541) -* Fix for quic_record_append to return the correct code (PR 8340, 8358) -* Fixes for Bind 9.18.28 port (PR 8331) -* Fix to adhere more closely with RFC8446 Appendix D and set haveEMS when - negotiating TLS 1.3 (PR 8487) -* Fix to properly check for signature_algorithms from the client in a TLS 1.3 - server (PR 8356) -* Fix for when BIO data is less than seq buffer size. Thanks to the team at Code - Intelligence for the report (PR 8426) -* ARM32/Thumb2 fixes for WOLFSSL_NO_VAR_ASSIGN_REG and td4 variable declarations - (PR 8590, 8635) -* Fix for Intel AVX1/SSE2 assembly to not use vzeroupper instructions unless ymm - or zmm registers are used (PR 8479) -* Entropy MemUse fix for when block size less than update bits (PR 8675) +NOTE: * wolfSSL is now GPLv3 instead of GPLv2 + * --enable-heapmath is deprecated + * MD5 is now disabled by default + + +PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. + +## Vulnerabilities + +* [Low] There is the potential for a fault injection attack on ECC and Ed25519 verify operations. In versions of wolfSSL 5.7.6 and later the --enable-faultharden option is available to help mitigate against potential fault injection attacks. The mitigation added in wolfSSL version 5.7.6 is to help harden applications relying on the results of the verify operations, such as when used with wolfBoot. If doing ECC or Ed25519 verify operations on a device at risk for fault injection attacks then --enable-faultharden could be used to help mitigate it. Thanks to Kevin from Fraunhofer AISEC for the report. + +Hardening option added in PR https://github.com/wolfSSL/wolfssl/pull/8289 + + +* [High CVE-2025-7395] When using WOLFSSL_SYS_CA_CERTS and WOLFSSL_APPLE_NATIVE_CERT_VALIDATION on an Apple platform, the native trust store verification routine overrides errors produced elsewhere in the wolfSSL certificate verification process including failures due to hostname matching/SNI, OCSP, CRL, etc. This allows any trusted cert chain to override other errors detected during chain verification that should have resulted in termination of the TLS connection. If building wolfSSL on versions after 5.7.6 and before 5.8.2 with use of the system CA support and the apple native cert validation feature enabled on Apple devices (on by default for non-macOS Apple targets when using autotools or CMake) we recommend updating to the latest version of wolfSSL. Thanks to Thomas Leong from ExpressVPN for the report. + +Fixed in PR https://github.com/wolfSSL/wolfssl/pull/8833 + + +* [Med. CVE-2025-7394] In the OpenSSL compatibility layer implementation, the function RAND_poll() was not behaving as expected and leading to the potential for predictable values returned from RAND_bytes() after fork() is called. This can lead to weak or predictable random numbers generated in applications that are both using RAND_bytes() and doing fork() operations. This only affects applications explicitly calling RAND_bytes() after fork() and does not affect any internal TLS operations. Although RAND_bytes() documentation in OpenSSL calls out not being safe for use with fork() without first calling RAND_poll(), an additional code change was also made in wolfSSL to make RAND_bytes() behave similar to OpenSSL after a fork() call without calling RAND_poll(). Now the Hash-DRBG used gets reseeded after detecting running in a new process. If making use of RAND_bytes() and calling fork() we recommend updating to the latest version of wolfSSL. Thanks to Per Allansson from Appgate for the report. + +Fixed in the following PR’s +https://github.com/wolfSSL/wolfssl/pull/8849 +https://github.com/wolfSSL/wolfssl/pull/8867 +https://github.com/wolfSSL/wolfssl/pull/8898 + + + +* [Low CVE-2025-7396] In wolfSSL 5.8.0 the option of hardening the C implementation of Curve25519 private key operations was added with the addition of blinding support (https://www.wolfssl.com/curve25519-blinding-support-added-in-wolfssl-5-8-0/). In wolfSSL release 5.8.2 that blinding support is turned on by default in applicable builds. The blinding configure option is only for the base C implementation of Curve25519. It is not needed, or available with; ARM assembly builds, Intel assembly builds, and the small Curve25519 feature. While the attack would be very difficult to execute in practice, enabling blinding provides an additional layer of protection for devices that may be more susceptible to physical access or side-channel observation. Thanks to Arnaud Varillon, Laurent Sauvage, and Allan Delautre from Telecom Paris for the report. + +Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 + + +## New Features +* Multiple sessions are now supported in the sniffer due to the removal of a cached check. (PR #8723) +* New API ssl_RemoveSession() has been implemented for sniffer cleanup operations. (PR #8768) +* The new ASN X509 API, `wc_GetSubjectPubKeyInfoDerFromCert`, has been introduced for retrieving public key information from certificates. (PR #8758) +* `wc_PKCS12_create()` has been enhanced to support PBE_AES(256|128)_CBC key and certificate encryptions. (PR #8782, PR #8822, PR #8859) +* `wc_PKCS7_DecodeEncryptedKeyPackage()` has been added for decoding encrypted key packages. (PR #8976) +* All AES, SHA, and HMAC functionality has been implemented within the Linux Kernel Module. (PR #8998) +* Additions to the compatibility layer have been introduced for X.509 extensions and RSA PSS. Adding the API i2d_PrivateKey_bio, BN_ucmp and X509v3_get_ext_by_NID. (PR #8897) +* Added support for STM32N6. (PR #8914) +* Implemented SHA-256 for PPC 32 assembly. (PR #8894) + +## Improvements / Optimizations + +### Linux Kernel Module (LinuxKM) Enhancements +* Registered DH and FFDHE for the Linux Kernel Module. (PR #8707) +* Implemented fixes for standard RNG in the Linux Kernel Module. (PR #8718) +* Added an ECDSA workaround for the Linux Kernel Module. (PR #8727) +* Added more PKCS1 pad SHA variants for RSA in the Linux Kernel Module. (PR #8730) +* Set default priority to 100000 for LKCAPI in the Linux Kernel Module. (PR #8740) +* Ensured ECDH never has FIPS enabled in the Linux Kernel Module. (PR #8751) +* Implemented further Linux Kernel Module and SP tweaks. (PR #8773) +* Added sig_alg support for Linux 6.13 RSA in the Linux Kernel Module. (PR #8796) +* Optimized wc_linuxkm_fpu_state_assoc. (PR #8828) +* Ensured DRBG is multithread-round-1 in the Linux Kernel Module. (PR #8840) +* Prevented toggling of fips_enabled in the Linux Kernel Module. (PR #8873) +* Refactored drbg_ctx clear in the Linux Kernel Module. (PR #8876) +* Set sig_alg max_size and digest_size callbacks for RSA in the Linux Kernel Module. (PR #8915) +* Added get_random_bytes for the Linux Kernel Module. (PR #8943) +* Implemented distro fix for the Linux Kernel Module. (PR #8994) +* Fixed page-flags-h in the Linux Kernel Module. (PR #9001) +* Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) +* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms +* Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) +* Backward compatibility has been implemented for ML_KEM IDs (PR #8827) +* ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) +* Building LMS with verify-only has been fixed (PR #8913) +* Parameters for LMS SHA-256_192 have been corrected (PR #8912) +* State can now be saved with the private key for LMS (PR #8836) +* Support for OpenSSL format has been added for ML-DSA/Dilithium (PR #8947) +* `dilithium_coeff_eta2[]` has been explicitly declared as signed (PR #8955) + +### Build System & Portability +* Prepared for the inclusion of v5.8.0 in the Ada Alire index. (PR #8714) +* Introduced a new build option to allow reuse of the Windows crypt provider handle. (PR #8706) +* Introduced general fixes for various build configurations. (PR #8763) +* Made improvements for portability using older GCC 4.8.2. (PR #8753) +* Macro guards updated to allow tests to build with opensslall and no server. (PR #8776) +* Added a check for STDC_NO_ATOMICS macro before use of atomics. (PR #8885) +* Introduced CMakePresets.json and CMakeSettings.json. (PR #8905) +* Added an option to not use constant time code with min/max. (PR #8830) +* Implemented proper MacOS dispatch for conditional signal/wait. (PR #8928) +* Disabled MD5 by default for both general and CMake builds. (PR #8895, PR #8948) +* Improved to allow building OPENSSL_EXTRA without KEEP_PEER_CERT. (PR #8926) +* Added introspection for Intel and ARM assembly speedups. (PR #8954) +* Fixed cURL config to set HAVE_EX_DATA and HAVE_ALPN. (PR #8973) +* Moved FREESCALE forced algorithm HAVE_ECC to IDE/MQX/user_settings.h. (PR #8977) + +### Testing & Debugging +* Fixed the exit status for testwolfcrypt. (PR #8762) +* Added WOLFSSL_DEBUG_PRINTF and WOLFSSL_DEBUG_CERTIFICATE_LOADS for improved debugging output. (PR #8769, PR #8770) +* Guarded some benchmark tests with NO_SW_BENCH. (PR #8760) +* Added an additional unit test for wolfcrypt PKCS12 file to improve code coverage. (PR #8831) +* Added an additional unit test for increased DH code coverage. (PR #8837) +* Adjusted for warnings with NO_TLS build and added GitHub actions test. (PR #8851) +* Added additional compatibility layer RAND tests. (PR #8852) +* Added an API unit test for checking domain name. (PR #8863) +* Added bind v9.18.33 testing. (PR #8888) +* Fixed issue with benchmark help options and descriptions not lining up. (PR #8957) + +### Certificates & ASN.1 +* Changed the algorithm for sum in ASN.1 OIDs. (PR #8655) +* Updated PKCS7 to use X509 STORE for internal verification. (PR #8748) +* Improved handling of temporary buffer size for X509 extension printing. (PR #8710) +* Marked IP address as WOLFSSL_V_ASN1_OCTET_STRING for ALT_NAMES_OID. (PR #8842) +* Fixed printing empty names in certificates. (PR #8880) +* Allowed CA:FALSE on wolftpm. (PR #8925) +* Fixed several inconsistent function prototype parameter names in wc/asn. (PR #8949) +* Accounted for custom extensions when creating a Cert from a WOLFSSL_X509. (PR #8960) + +### TLS/DTLS & Handshake +* Checked group correctness outside of TLS 1.3 too for TLSX_UseSupportedCurve. (PR #8785) +* Dropped records that span datagrams in DTLS. (PR #8642) +* Implemented WC_NID_netscape_cert_type. (PR #8800) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Correctly set the current peer in dtlsProcessPendingPeer. (PR #8848) +* Fixed set_groups for TLS. (PR #8824) +* Allowed trusted_ca_keys with TLSv1.3. (PR #8860) +* Moved Dtls13NewEpoch into DeriveTls13Keys. (PR #8858) +* Cleared tls1_3 on downgrade. (PR #8861) +* Always sent ACKs on detected retransmission for DTLS1.3. (PR #8882) +* Removed DTLS from echo examples. (PR #8889) +* Recalculated suites at SSL initialization. (PR #8757) +* No longer using BIO for ALPN. (PR #8969) +* Fixed wolfSSL_BIO_new_connect's handling of IPV6 addresses. (PR #8815) +* Memory Management & Optimizations +* Performed small stack refactors, improved stack size with mlkem and dilithium, and added additional tests. (PR #8779) +* Implemented FREE_MP_INT_SIZE in heap math. (PR #8881) +* Detected correct MAX_ENCODED_SIG_SZ based on max support in math lib. (PR #8931) +* Fixed improper access of sp_int_minimal using sp_int. (PR #8985) + +### Cryptography & Hash Functions +* Implemented WC_SIPHASH_NO_ASM for not using assembly optimizations with siphash. (PR #8789, PR #8791) +* Added missing DH_MAX_SIZE define for FIPS and corrected wolfssl.rc FILETYPE to VFT_DLL. (PR #8794) +* Implemented WC_SHA3_NO_ASM for not using assembly with SHA3. (PR #8817) +* Improved Aarch64 XFENCE. (PR #8832) +* Omitted frame pointer for ARM32/Thumb2/RISC-V 64 assembly. (PR #8893) +* Fixed branch instruction in ARMv7a ASM. (PR #8933) +* Enabled EVP HMAC to work with WOLFSSL_HMAC_COPY_HASH. (PR #8944) +* Platform-Specific & Hardware Integration +* Added HAVE_HKDF for wolfssl_test and explicit support for ESP32P4. (PR #8742) +* Corrected Espressif default time setting. (PR #8829) +* Made wc_tsip_* APIs public. (PR #8717) +* Improved PlatformIO Certificate Bundle Support. (PR #8847) +* Fixed the TSIP TLS example program. (PR #8857) +* Added crypto callback functions for TROPIC01 secure element. (PR #8812) +* Added Renesas RX TSIP AES CTR support. (PR #8854) +* Fixed TSIP port using crypto callback. (PR #8937) + +### General Improvements & Refactoring +* Attempted wolfssl_read_bio_file in read_bio even when XFSEEK is available. (PR #8703) +* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) +* Updated libspdm from 3.3.0 to 3.7.0. (PR #8906) +* Fixed missing dashes on the end of header and footer for Falcon PEM key. (PR #8904) +* Fixed minor code typos for macos signal and types.h max block size. (PR #8934) +* Make the API wolfSSL_X509_STORE_CTX_get_error accessible to more build configurations for ease of getting the "store" error code and depth with certificate failure callback implementations. (PR #8903) + +## Bug Fixes +* Fixed issues to support _WIN32_WCE (VS 2008 with WinCE 6.0/7.0). (PR #8709) +* Fixed STM32 Hash with IRQ enabled. (PR #8705) +* Fixed raw hash when using crypto instructions on RISC-V 64-bit. (PR #8733) +* Fixed ECDH decode secret in the Linux Kernel Module. (PR #8729) +* Passed in the correct hash type to wolfSSL_RSA_verify_ex. (PR #8726) +* Fixed issues for Intel QuickAssist latest driver (4.28). (PR #8728) +* Speculative fix for CodeSonar overflow issue in ssl_certman.c. (PR #8715) +* Fixed Arduino progmem print and AVR WOLFSSL_USER_IO. (PR #8668) +* Correctly advanced the index in wc_HKDF_Expand_ex. (PR #8737) +* Fixed STM32 hash status check logic, including NO_AES_192 and NO_AES_256. (PR #8732) +* Added missing call to wolfSSL_RefFree in FreeCRL to prevent memory leaks. (PR #8750) +* Fixed sanity check on --group with unit test app and null sanity check with des decrypt. (PR #8711) +* Fixed Curve25519 and static ephemeral issue with blinding. (PR #8766) +* Fixed edge case issue with STM32 AES GCM auth padding. (PR #8745) +* Removed redefinition of MlKemKey and fixed build issue in benchmark. (PR #8755) +* Used proper heap hint when freeing CRL in error case. (PR #8713) +* Added support for no malloc with wc_CheckCertSigPubKey. (PR #8725) +* Fixed C# wrapper Release build. (PR #8802) +* Handled malformed CCS and CCS before CH in TLS1.3. (PR #8788) +* Fixed ML-DSA with WOLFSSL_DILITHIUM_NO_SIGN. (PR #8798) +* Fixed AesGcmCrypt_1 no-stream in the Linux Kernel Module. (PR #8814) +* Fixed return value usage for crypto_sig_sign in the Linux Kernel Module. (PR #8816) +* Fixed issue with CSharp and Windows CE with conversion of ASCII and Unicode. (PR #8799) +* Fixed Renesas SCE on RA6M4. (PR #8838) +* Fixed tests for different configs for ML-DSA. (PR #8865) +* Fixed bug in ParseCRL_Extensions around the size of a CRL number handled and CRL number OID. (PR #8587) +* Fixed uninitialized wc_FreeRng in prime_test. (PR #8886) +* Fixed ECC configuration issues with ECC verify only and no RNG. (PR #8901) +* Fixed issues with max size, openssl.test netcat, and clang-tidy. (PR #8909) +* Fixed for casting down and uninit issues in Dilithium/ML-DSA. (PR #8868) +* Fixed memory allocation failure testing and related unit test cases. (PR #8945, PR #8952) +* Fixed build issue with ML-DSA 44 only. (PR #8981) +* Fixed possible memory leak with X509 reference counter when using x509small. (PR #8982) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/library.properties b/library.properties index 16c905a..bb59f54 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.8.0 +version=5.8.2 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index 0b52a6c..ce74983 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2392,13 +2392,28 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_connect"); bio = wolfSSL_BIO_new(wolfSSL_BIO_s_socket()); if (bio) { - const char* port = XSTRSTR(str, ":"); + const char* port; +#ifdef WOLFSSL_IPV6 + const char* ipv6Start = XSTRSTR(str, "["); + const char* ipv6End = XSTRSTR(str, "]"); + + if (ipv6End) + port = XSTRSTR(ipv6End, ":"); + else +#endif + port = XSTRSTR(str, ":"); if (port != NULL) bio->port = (word16)XATOI(port + 1); else port = str + XSTRLEN(str); /* point to null terminator */ +#ifdef WOLFSSL_IPV6 + if (ipv6Start && ipv6End) { + str = ipv6Start + 1; + port = ipv6End; + } +#endif bio->ip = (char*)XMALLOC( (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); diff --git a/src/src/conf.c b/src/src/conf.c index a30be38..e0a8b03 100644 --- a/src/src/conf.c +++ b/src/src/conf.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/src/crl.c b/src/src/crl.c index 437342c..4e4700f 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -135,7 +135,10 @@ static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff, #endif dcrl->certs = NULL; crle->totalCerts = dcrl->totalCerts; - crle->crlNumber = dcrl->crlNumber; + crle->crlNumberSet = dcrl->crlNumberSet; + if (crle->crlNumberSet) { + XMEMCPY(crle->crlNumber, dcrl->crlNumber, CRL_MAX_NUM_SZ); + } crle->verified = verified; if (!verified) { crle->tbsSz = dcrl->sigIndex - dcrl->certBegin; @@ -258,6 +261,7 @@ void FreeCRL(WOLFSSL_CRL* crl, int dynamic) WOLFSSL_MSG("Couldn't lock x509 mutex"); if (!doFree) return; + wolfSSL_RefFree(&crl->ref); } #endif @@ -586,7 +590,9 @@ static void SetCrlInfo(CRL_Entry* entry, CrlInfo *info) info->nextDate = (byte *)entry->nextDate; info->nextDateMaxLen = MAX_DATE_SIZE; info->nextDateFormat = entry->nextDateFormat; - info->crlNumber = (sword32)entry->crlNumber; + info->crlNumberSet = entry->crlNumberSet; + if (info->crlNumberSet) + XMEMCPY(info->crlNumber, entry->crlNumber, CRL_MAX_NUM_SZ); } static void SetCrlInfoFromDecoded(DecodedCRL* entry, CrlInfo *info) @@ -599,10 +605,55 @@ static void SetCrlInfoFromDecoded(DecodedCRL* entry, CrlInfo *info) info->nextDate = (byte *)entry->nextDate; info->nextDateMaxLen = MAX_DATE_SIZE; info->nextDateFormat = entry->nextDateFormat; - info->crlNumber = (sword32)entry->crlNumber; + info->crlNumberSet = entry->crlNumberSet; + if (info->crlNumberSet) + XMEMCPY(info->crlNumber, entry->crlNumber, CRL_MAX_NUM_SZ); } #endif +/* Returns MP_GT if prev crlNumber is smaller + * MP_EQ if equal + * MP_LT if prev crlNumber is larger */ +static int CompareCRLnumber(CRL_Entry* prev, CRL_Entry* curr) +{ + int ret = 0; + DECL_MP_INT_SIZE_DYN(prev_num, CRL_MAX_NUM_SZ * CHAR_BIT, + CRL_MAX_NUM_SZ * CHAR_BIT); + DECL_MP_INT_SIZE_DYN(curr_num, CRL_MAX_NUM_SZ * CHAR_BIT, + CRL_MAX_NUM_SZ * CHAR_BIT); + + NEW_MP_INT_SIZE(prev_num, CRL_MAX_NUM_SZ * CHAR_BIT, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + NEW_MP_INT_SIZE(curr_num, CRL_MAX_NUM_SZ * CHAR_BIT, NULL, + DYNAMIC_TYPE_TMP_BUFFER); +#ifdef MP_INT_SIZE_CHECK_NULL + if ((prev_num == NULL) || (curr_num == NULL)) { + ret = MEMORY_E; + } +#endif + + if (ret == 0 && ((INIT_MP_INT_SIZE(prev_num, CRL_MAX_NUM_SZ * CHAR_BIT) + != MP_OKAY) || (INIT_MP_INT_SIZE(curr_num, + CRL_MAX_NUM_SZ * CHAR_BIT)) != MP_OKAY)) { + ret = MP_INIT_E; + } + + if (ret == 0 && (mp_read_radix(prev_num, (char*)prev->crlNumber, + MP_RADIX_HEX) != MP_OKAY || + mp_read_radix(curr_num, (char*)curr->crlNumber, + MP_RADIX_HEX) != MP_OKAY)) { + ret = BAD_FUNC_ARG; + } + + if (ret == 0) + ret = mp_cmp(prev_num, curr_num); + + FREE_MP_INT_SIZE(prev_num, NULL, DYNAMIC_TYPE_TMP_BUFFER); + FREE_MP_INT_SIZE(curr_num, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} + /* Add Decoded CRL, 0 on success */ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, int verified) @@ -614,6 +665,7 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, CrlInfo old; CrlInfo cnew; #endif + int ret = 0; WOLFSSL_ENTER("AddCRL"); @@ -644,12 +696,19 @@ static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff, for (curr = crl->crlList; curr != NULL; curr = curr->next) { if (XMEMCMP(curr->issuerHash, crle->issuerHash, CRL_DIGEST_SIZE) == 0) { - if (crle->crlNumber <= curr->crlNumber) { + ret = CompareCRLnumber(crle, curr); + /* Error out if the CRL we're attempting to add isn't more + * authoritative than the existing entry */ + if (ret == MP_LT || ret == MP_EQ) { WOLFSSL_MSG("Same or newer CRL entry already exists"); CRL_Entry_free(crle, crl->heap); wc_UnLockRwLock(&crl->crlLock); return BAD_FUNC_ARG; } + else if (ret < 0) { + WOLFSSL_MSG("Error comparing CRL Numbers"); + return ret; + } crle->next = curr->next; if (prev != NULL) { @@ -855,13 +914,18 @@ int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, static WOLFSSL_X509_CRL* wolfSSL_X509_crl_new(WOLFSSL_CERT_MANAGER* cm) { WOLFSSL_X509_CRL* ret; + void* heap = NULL; + + if (cm != NULL) { + heap = cm->heap; + } - ret = (WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), - cm != NULL ? cm->heap : NULL, DYNAMIC_TYPE_CRL); + ret = (WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), heap, + DYNAMIC_TYPE_CRL); if (ret != NULL) { if (InitCRL(ret, cm) < 0) { WOLFSSL_MSG("Unable to initialize new CRL structure"); - XFREE(ret, cm->heap, DYNAMIC_TYPE_CRL); + XFREE(ret, heap, DYNAMIC_TYPE_CRL); ret = NULL; } } diff --git a/src/src/dtls.c b/src/src/dtls.c index 2d3c38b..d25f66b 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -678,6 +678,8 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) ERROR_OUT(BUFFER_ERROR, dtls13_cleanup); if ((sigAlgs.size % 2) != 0) ERROR_OUT(BUFFER_ERROR, dtls13_cleanup); + if (sigAlgs.size > WOLFSSL_MAX_SIGALGO) + ERROR_OUT(BUFFER_ERROR, dtls13_cleanup); suites.hashSigAlgoSz = (word16)sigAlgs.size; XMEMCPY(suites.hashSigAlgo, sigAlgs.elements, sigAlgs.size); haveSA = 1; diff --git a/src/src/dtls13.c b/src/src/dtls13.c index 5a9b6dc..c4e2b61 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -905,7 +905,7 @@ static int Dtls13RtxMsgRecvd(WOLFSSL* ssl, enum HandShakeType hs, /* the other peer may have retransmitted because an ACK for a flight that needs explicit ACK was lost.*/ if (ssl->dtls13Rtx.seenRecords != NULL) - ssl->dtls13Rtx.sendAcks = (byte)ssl->options.dtls13SendMoreAcks; + ssl->dtls13Rtx.sendAcks = 1; } if (ssl->keys.dtls_peer_handshake_number == @@ -2618,19 +2618,16 @@ static int Dtls13RtxIsTrackedByRn(const Dtls13RtxRecord* r, w64wrapper epoch, static int Dtls13KeyUpdateAckReceived(WOLFSSL* ssl) { int ret; - w64Increment(&ssl->dtls13Epoch); - - /* Epoch wrapped up */ - if (w64IsZero(ssl->dtls13Epoch)) - return BAD_STATE_E; ret = DeriveTls13Keys(ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1); if (ret != 0) return ret; - ret = Dtls13NewEpoch(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY); - if (ret != 0) - return ret; + w64Increment(&ssl->dtls13Epoch); + + /* Epoch wrapped up */ + if (w64IsZero(ssl->dtls13Epoch)) + return BAD_STATE_E; return Dtls13SetEpochKeys(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY); } diff --git a/src/src/internal.c b/src/src/internal.c index eb2f16d..c74bcf3 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -86,6 +86,8 @@ * WOLFSSL_NO_INIT_CTX_KEY * Allows SSL objects to be created from a CTX without a loaded key/cert * pair + * WOLFSSL_DTLS_RECORDS_CAN_SPAN_DATAGRAMS: + * When defined, allows DTLS records to span across multiple datagrams. */ #ifndef WOLFCRYPT_ONLY @@ -211,7 +213,7 @@ int writeAeadAuthData(WOLFSSL* ssl, word16 sz, byte type, byte* additional, #include #include #include -static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, +static int DoAppleNativeCertValidation(WOLFSSL* ssl, const WOLFSSL_BUFFER_INFO* certs, int totalCerts); #endif /* #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */ @@ -2903,7 +2905,7 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) defined(WOLFSSL_WPAS_SMALL) wolfSSL_X509_STORE_free(ctx->x509_store_pt); #endif - #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(HAVE_LIGHTY) + #ifndef WOLFSSL_NO_CA_NAMES wolfSSL_sk_X509_NAME_pop_free(ctx->client_ca_names, NULL); ctx->client_ca_names = NULL; #endif @@ -2913,6 +2915,12 @@ void SSL_CtxResourceFree(WOLFSSL_CTX* ctx) ctx->x509Chain = NULL; } #endif + #ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + if (ctx->testTrustedCAs != NULL) { + CFRelease(ctx->testTrustedCAs); + ctx->testTrustedCAs = NULL; + } + #endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ #endif /* !NO_CERTS */ #ifdef HAVE_TLS_EXTENSIONS @@ -4841,7 +4849,7 @@ void FreeX509(WOLFSSL_X509* x509) } #endif /* WOLFSSL_DUAL_ALG_CERTS */ - #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) + #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) wolfSSL_RefFree(&x509->ref); #endif } @@ -6460,6 +6468,10 @@ int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey, WOLFSSL_ENTER("DhGenKeyPair"); + if (ssl == NULL || dhKey == NULL) { + return BAD_FUNC_ARG; + } + #ifdef WOLFSSL_ASYNC_CRYPT /* initialize event */ ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE); @@ -6920,13 +6932,36 @@ int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) /* If we are setting the ctx on an already initialized SSL object * then we possibly already have a side defined. Don't overwrite unless * the context has a well defined role. */ - if (newSSL || ctx->method->side != WOLFSSL_NEITHER_END) - ssl->options.side = (word16)(ctx->method->side); - ssl->options.downgrade = (word16)(ctx->method->downgrade); - ssl->options.minDowngrade = ctx->minDowngrade; - + if (newSSL || ctx->method->side != WOLFSSL_NEITHER_END) { + ssl->options.side = (word16)(ctx->method->side); + } + ssl->options.downgrade = (word16)(ctx->method->downgrade); + ssl->options.minDowngrade = ctx->minDowngrade; ssl->options.haveRSA = ctx->haveRSA; ssl->options.haveDH = ctx->haveDH; +#if !defined(NO_CERTS) && !defined(NO_DH) + /* Its possible that DH algorithm parameters were set in the ctx, recalc + * cipher suites. */ + if (ssl->options.haveDH && ctx->serverDH_P.buffer != NULL && + ctx->serverDH_G.buffer != NULL) { + if (ssl->suites == NULL) { + if (AllocateSuites(ssl) != 0) { + return MEMORY_E; + } + } + InitSuites(ssl->suites, ssl->version, ssl->buffers.keySz, + ssl->options.haveRSA, +#ifdef NO_PSK + 0, +#else + ctx->havePSK, +#endif + ssl->options.haveDH, + ssl->options.haveECDSAsig, ssl->options.haveECC, TRUE, + ssl->options.haveStaticECC, ssl->options.useAnon, + TRUE, TRUE, TRUE, TRUE, ssl->options.side); + } +#endif /* !NO_CERTS && !NO_DH */ ssl->options.haveECDSAsig = ctx->haveECDSAsig; ssl->options.haveECC = ctx->haveECC; ssl->options.haveStaticECC = ctx->haveStaticECC; @@ -8782,7 +8817,7 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl) wolfSSL_sk_X509_pop_free(ssl->ourCertChain, NULL); #endif #endif -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(HAVE_LIGHTY) +#ifndef WOLFSSL_NO_CA_NAMES wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL); ssl->client_ca_names = NULL; #endif @@ -11576,6 +11611,33 @@ static int MsgCheckBoundary(const WOLFSSL* ssl, byte type, #endif /* WOLFSSL_DISABLE_EARLY_SANITY_CHECKS */ +/* Extract the handshake header information. + * + * ssl The SSL/TLS object. + * input The buffer holding the message data. + * inOutIdx On entry, the index into the buffer of the handshake data. + * On exit, the start of the handshake data. + * type Type of handshake message. + * size The length of the handshake message data. + * totalSz The total size of data in the buffer. + * returns BUFFER_E if there is not enough input data and 0 on success. + */ +int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx, + byte* type, word32* size, word32 totalSz) +{ + const byte* ptr = input + *inOutIdx; + (void)ssl; + + *inOutIdx += HANDSHAKE_HEADER_SZ; + if (*inOutIdx > totalSz) + return BUFFER_E; + + *type = ptr[0]; + c24to32(&ptr[1], size); + + return 0; +} + /** * This check is performed as soon as the handshake message type becomes known. * These checks can not be delayed and need to be performed when the msg is @@ -11622,6 +11684,18 @@ int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type, word32 msgSz) return ret; } +static int RecordsCanSpanReads(WOLFSSL *ssl) +{ +#if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DTLS_RECORDS_CAN_SPAN_DATAGRAMS) + /* Only case where we return 0: DTLS mode (not SCTP) and can't span datagrams */ + if (IsDtlsNotSctpMode(ssl)) { + return 0; + } +#endif + (void)ssl; + return 1; +} + #ifdef WOLFSSL_DTLS13 static int GetInputData(WOLFSSL *ssl, word32 size); static int GetDtls13RecordHeader(WOLFSSL* ssl, word32* inOutIdx, @@ -11681,6 +11755,10 @@ static int GetDtls13RecordHeader(WOLFSSL* ssl, word32* inOutIdx, } if (readSize < ssl->dtls13CurRlLength + DTLS13_RN_MASK_SIZE) { + if (!RecordsCanSpanReads(ssl)) { + WOLFSSL_MSG("Partial record received"); + return DTLS_PARTIAL_RECORD_READ; + } /* when using DTLS over a medium that does not guarantee that a full * message is received in a single read, we may end up without the full * header and minimum ciphertext to decrypt record sequence numbers */ @@ -11773,6 +11851,10 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, /* not a unified header, check that we have at least * DTLS_RECORD_HEADER_SZ */ if (ssl->buffers.inputBuffer.length - *inOutIdx < DTLS_RECORD_HEADER_SZ) { + if (!RecordsCanSpanReads(ssl)) { + WOLFSSL_MSG("Partial record received"); + return DTLS_PARTIAL_RECORD_READ; + } ret = GetInputData(ssl, DTLS_RECORD_HEADER_SZ); /* Check if Dtls13RtxTimeout(ssl) returned socket error */ if (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) @@ -11788,6 +11870,10 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, *inOutIdx += ENUM_LEN + VERSION_SZ; ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curEpoch); + if (rh->pvMajor == DTLS_MAJOR && rh->pvMinor == DTLS_BOGUS_MINOR) { + return SEQUENCE_ERROR; + } + #ifdef WOLFSSL_DTLS_CID if (rh->type == dtls12_cid && (cidSz = DtlsGetCidRxSize(ssl)) == 0) return DTLS_CID_ERROR; @@ -12017,24 +12103,6 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, return 0; } -#ifndef WOLFSSL_NO_TLS12 -static int GetHandShakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx, - byte *type, word32 *size, word32 totalSz) -{ - const byte *ptr = input + *inOutIdx; - (void)ssl; - - *inOutIdx += HANDSHAKE_HEADER_SZ; - if (*inOutIdx > totalSz) - return BUFFER_E; - - *type = ptr[0]; - c24to32(&ptr[1], size); - - return 0; -} -#endif - #ifdef WOLFSSL_DTLS int GetDtlsHandShakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx, byte *type, word32 *size, @@ -16272,7 +16340,6 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, } #endif - if (!ssl->options.verifyNone && ssl->buffers.domainName.buffer) { #ifndef WOLFSSL_ALLOW_NO_CN_IN_SAN /* Per RFC 5280 section 4.2.1.6, "Whenever such identities @@ -16774,8 +16841,9 @@ int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, /* If we can't validate the peer cert chain against the CAs loaded * into wolfSSL, try to validate against the system certificates * using Apple's native trust APIs */ - if ((ret != 0) && (ssl->ctx->doAppleNativeCertValidationFlag)) { - if (DoAppleNativeCertValidation(args->certs, + if ((ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E)) && + (ssl->ctx->doAppleNativeCertValidationFlag)) { + if (DoAppleNativeCertValidation(ssl, args->certs, args->totalCerts)) { WOLFSSL_MSG("Apple native cert chain validation SUCCESS"); ret = 0; @@ -18096,7 +18164,7 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, byte type; word32 size; - if (GetHandShakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0) { + if (GetHandshakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0) { WOLFSSL_ERROR_VERBOSE(PARSE_ERROR); return PARSE_ERROR; } @@ -18124,7 +18192,7 @@ static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, byte type; word32 size; - if (GetHandShakeHeader(ssl, input, inOutIdx, &type, &size, + if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size, totalSz) != 0) { WOLFSSL_ERROR_VERBOSE(PARSE_ERROR); return PARSE_ERROR; @@ -19059,7 +19127,7 @@ static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, int additionalSz, /* length of additional input plus padding */ XMEMSET(padding, 0, sizeof(padding)); - padding[0] = additionalSz; + padding[0] = (byte)additionalSz; if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding, sizeof(padding))) != 0) return ret; @@ -19141,7 +19209,8 @@ int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input, } #endif - addSz = writeAeadAuthData(ssl, msgLen, type, add, 0, &seq, verifyOrder); + addSz = writeAeadAuthData(ssl, (word16)msgLen, type, add, 0, &seq, + verifyOrder); if (addSz < 0) return addSz; @@ -19336,7 +19405,8 @@ int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input, #endif - addSz = writeAeadAuthData(ssl, msgLen, no_type, add, 1, &seq, PEER_ORDER); + addSz = writeAeadAuthData(ssl, (word16)msgLen, no_type, add, 1, &seq, + PEER_ORDER); if (addSz < 0) return addSz; @@ -19583,8 +19653,8 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, #endif (void)out; - (void)input; (void)sz; + (void)type; if (input == NULL) { return BAD_FUNC_ARG; @@ -19661,8 +19731,8 @@ static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input, additionalSz = writeAeadAuthData(ssl, /* Length of the plain text minus the explicit * IV length minus the authentication tag size. */ - sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, type, - ssl->encrypt.additional, 0, NULL, CUR_ORDER); + sz - (word16)(AESGCM_EXP_IV_SZ) - ssl->specs.aead_mac_size, + type, ssl->encrypt.additional, 0, NULL, CUR_ORDER); if (additionalSz < 0) { ret = additionalSz; break; @@ -20968,6 +21038,7 @@ int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz, byte good; int ret = 0; + XMEMSET(verify, 0, WC_MAX_DIGEST_SIZE); good = MaskPadding(input, pLen, macSz); /* 4th argument has potential to underflow, ssl->hmac function should * either increment the size by (macSz + padLen + 1) before use or check on @@ -21542,9 +21613,18 @@ static int GetInputData(WOLFSSL *ssl, word32 size) return RECV_OVERFLOW_E; } + if ((word32)in < size) { + if (!RecordsCanSpanReads(ssl)) { + WOLFSSL_MSG("DTLS: Received partial record, ignoring"); +#ifdef WOLFSSL_DTLS_DROP_STATS + ssl->replayDropCount++; +#endif /* WOLFSSL_DTLS_DROP_STATS */ + continue; + } + } + ssl->buffers.inputBuffer.length += (word32)in; inSz -= in; - } while (ssl->buffers.inputBuffer.length < size); #ifdef WOLFSSL_DEBUG_TLS @@ -21601,6 +21681,7 @@ static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz, byte verify[WC_MAX_DIGEST_SIZE]; XMEMSET(verify, 0, WC_MAX_DIGEST_SIZE); + if (ssl->specs.cipher_type == block) { pad = input[msgSz - 1]; padByte = 1; @@ -21712,7 +21793,8 @@ static int DtlsShouldDrop(WOLFSSL* ssl, int retcode) if ((ssl->options.handShakeDone && retcode != 0) || retcode == WC_NO_ERR_TRACE(SEQUENCE_ERROR) - || retcode == WC_NO_ERR_TRACE(DTLS_CID_ERROR)) { + || retcode == WC_NO_ERR_TRACE(DTLS_CID_ERROR) + || retcode == WC_NO_ERR_TRACE(DTLS_PARTIAL_RECORD_READ)) { WOLFSSL_MSG_EX("Silently dropping DTLS message: %d", retcode); return 1; } @@ -21808,7 +21890,7 @@ static void dtlsProcessPendingPeer(WOLFSSL* ssl, int deprotected) else { /* Pending peer present and record deprotected. Update the peer. */ (void)wolfSSL_dtls_set_peer(ssl, - &ssl->buffers.dtlsCtx.pendingPeer.sa, + ssl->buffers.dtlsCtx.pendingPeer.sa, ssl->buffers.dtlsCtx.pendingPeer.sz); ssl->buffers.dtlsCtx.processingPendingRecord = 0; dtlsClearPeer(&ssl->buffers.dtlsCtx.pendingPeer); @@ -21818,8 +21900,139 @@ static void dtlsProcessPendingPeer(WOLFSSL* ssl, int deprotected) ssl->buffers.dtlsCtx.processingPendingRecord = 0; } } +#endif +static int DoDecrypt(WOLFSSL *ssl) +{ + int ret; + int atomicUser = 0; + bufferStatic* in = &ssl->buffers.inputBuffer; + +#ifdef ATOMIC_USER + if (ssl->ctx->DecryptVerifyCb) + atomicUser = 1; #endif + ret = SanityCheckCipherText(ssl, ssl->curSize); + if (ret < 0) { + return ret; + } + + if (atomicUser) { +#ifdef ATOMIC_USER +#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) + if (ssl->options.startedETMRead) { + ret = ssl->ctx->VerifyDecryptCb(ssl, + in->buffer + in->idx, in->buffer + in->idx, + ssl->curSize - MacSize(ssl), + ssl->curRL.type, 1, &ssl->keys.padSz, + ssl->DecryptVerifyCtx); + } + else +#endif + { + ret = ssl->ctx->DecryptVerifyCb(ssl, + in->buffer + in->idx, + in->buffer + in->idx, + ssl->curSize, ssl->curRL.type, 1, + &ssl->keys.padSz, ssl->DecryptVerifyCtx); + } +#endif /* ATOMIC_USER */ + } + else { + if (!ssl->options.tls1_3) { +#ifndef WOLFSSL_NO_TLS12 +#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) + if (ssl->options.startedETMRead) { + word32 digestSz = MacSize(ssl); + ret = DecryptTls(ssl, + in->buffer + in->idx, + in->buffer + in->idx, + ssl->curSize - (word16)digestSz); + if (ret == 0) { + byte invalid = 0; + byte padding = (byte)-1; + word32 i; + word32 off = in->idx + ssl->curSize - digestSz - 1; + + /* Last of padding bytes - indicates length. */ + ssl->keys.padSz = in->buffer[off]; + /* Constant time checking of padding - don't leak + * the length of the data. + */ + /* Compare max pad bytes or at most data + pad. */ + for (i = 1; i < MAX_PAD_SIZE && off >= i; i++) { + /* Mask on indicates this is expected to be a + * padding byte. + */ + padding &= ctMaskLTE((int)i, + (int)ssl->keys.padSz); + /* When this is a padding byte and not equal + * to length then mask is set. + */ + invalid |= padding & + ctMaskNotEq(in->buffer[off - i], + (int)ssl->keys.padSz); + } + /* If mask is set then there was an error. */ + if (invalid) { + ret = DECRYPT_ERROR; + } + ssl->keys.padSz += 1; + ssl->keys.decryptedCur = 1; + } + } + else +#endif + { + ret = DecryptTls(ssl, + in->buffer + in->idx, + in->buffer + in->idx, + ssl->curSize); + } +#else + ret = DECRYPT_ERROR; +#endif + } + else + { + #ifdef WOLFSSL_TLS13 + byte *aad = (byte*)&ssl->curRL; + word16 aad_size = RECORD_HEADER_SZ; + #ifdef WOLFSSL_DTLS13 + if (ssl->options.dtls) { + /* aad now points to the record header */ + aad = ssl->dtls13CurRL; + aad_size = ssl->dtls13CurRlLength; + } + #endif /* WOLFSSL_DTLS13 */ + /* Don't send an alert for DTLS. We will just drop it + * silently later. */ + ret = DecryptTls13(ssl, + in->buffer + in->idx, + in->buffer + in->idx, + ssl->curSize, + aad, aad_size); + #else + ret = DECRYPT_ERROR; + #endif /* WOLFSSL_TLS13 */ + } + (void)in; + } + return ret; +} + +#ifdef WOLFSSL_DTLS +static void DropAndRestartProcessReply(WOLFSSL* ssl) +{ + ssl->options.processReply = doProcessInit; + ssl->buffers.inputBuffer.length = 0; + ssl->buffers.inputBuffer.idx = 0; +#ifdef WOLFSSL_DTLS_DROP_STATS + if (ssl->options.dtls) + ssl->replayDropCount++; +#endif /* WOLFSSL_DTLS_DROP_STATS */ +} +#endif /* WOLFSSL_DTLS */ /* Process input requests. Return 0 is done, 1 is call again to complete, and negative number is error. If allowSocketErr is set, SOCKET_ERROR_E in ssl->error will be whitelisted. This is useful when the connection has been @@ -21929,6 +22142,11 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) used = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx; if (used < readSz) { + if (used > 0 && !RecordsCanSpanReads(ssl)) { + WOLFSSL_MSG("DTLS: Partial record in buffer, dropping"); + DropAndRestartProcessReply(ssl); + continue; + } if ((ret = GetInputData(ssl, (word32)readSz)) < 0) return ret; } @@ -21941,7 +22159,11 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) if ( ssl->options.side == WOLFSSL_SERVER_END && ssl->options.clientState == NULL_STATE && ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx] - != handshake) { + != handshake && + /* change_cipher_spec here is an error but we want to handle + * it correctly later */ + ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx] + != change_cipher_spec) { byte b0, b1; ssl->options.processReply = runProcessOldClientHello; @@ -22028,13 +22250,7 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) dtlsProcessPendingPeer(ssl, 0); #endif if (ssl->options.dtls && DtlsShouldDrop(ssl, ret)) { - ssl->options.processReply = doProcessInit; - ssl->buffers.inputBuffer.length = 0; - ssl->buffers.inputBuffer.idx = 0; -#ifdef WOLFSSL_DTLS_DROP_STATS - ssl->replayDropCount++; -#endif /* WOLFSSL_DTLS_DROP_STATS */ - + DropAndRestartProcessReply(ssl); #ifdef WOLFSSL_DTLS13 /* return to send ACKS and shortcut rtx timer */ if (IsAtLeastTLSv1_3(ssl->version) @@ -22096,9 +22312,15 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* read ahead may already have */ used = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx; - if (used < ssl->curSize) + if (used < ssl->curSize) { + if (!RecordsCanSpanReads(ssl)) { + WOLFSSL_MSG("Partial record received, dropping"); + DropAndRestartProcessReply(ssl); + continue; + } if ((ret = GetInputData(ssl, ssl->curSize)) < 0) return ret; + } #endif } @@ -22149,9 +22371,7 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* If in DTLS mode, if the decrypt fails for any * reason, pretend the datagram never happened. */ if (ssl->options.dtls) { - ssl->options.processReply = doProcessInit; - ssl->buffers.inputBuffer.idx = - ssl->buffers.inputBuffer.length; + DropAndRestartProcessReply(ssl); return HandleDTLSDecryptFailed(ssl); } #endif /* WOLFSSL_DTLS */ @@ -22175,118 +22395,7 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) (!IsAtLeastTLSv1_3(ssl->version) || ssl->curRL.type != change_cipher_spec)) { - bufferStatic* in = &ssl->buffers.inputBuffer; - - ret = SanityCheckCipherText(ssl, ssl->curSize); - if (ret < 0) { - #ifdef WOLFSSL_EXTRA_ALERTS - SendAlert(ssl, alert_fatal, bad_record_mac); - #endif - return ret; - } - - if (atomicUser) { - #ifdef ATOMIC_USER - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - ret = ssl->ctx->VerifyDecryptCb(ssl, - in->buffer + in->idx, in->buffer + in->idx, - ssl->curSize - MacSize(ssl), - ssl->curRL.type, 1, &ssl->keys.padSz, - ssl->DecryptVerifyCtx); - } - else - #endif - { - ret = ssl->ctx->DecryptVerifyCb(ssl, - in->buffer + in->idx, - in->buffer + in->idx, - ssl->curSize, ssl->curRL.type, 1, - &ssl->keys.padSz, ssl->DecryptVerifyCtx); - } - #endif /* ATOMIC_USER */ - } - else { - if (!ssl->options.tls1_3) { - #ifndef WOLFSSL_NO_TLS12 - #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) - if (ssl->options.startedETMRead) { - word32 digestSz = MacSize(ssl); - ret = DecryptTls(ssl, - in->buffer + in->idx, - in->buffer + in->idx, - ssl->curSize - (word16)digestSz); - if (ret == 0) { - byte invalid = 0; - byte padding = (byte)-1; - word32 i; - word32 off = in->idx + ssl->curSize - digestSz - 1; - - /* Last of padding bytes - indicates length. */ - ssl->keys.padSz = in->buffer[off]; - /* Constant time checking of padding - don't leak - * the length of the data. - */ - /* Compare max pad bytes or at most data + pad. */ - for (i = 1; i < MAX_PAD_SIZE && off >= i; i++) { - /* Mask on indicates this is expected to be a - * padding byte. - */ - padding &= ctMaskLTE((int)i, - (int)ssl->keys.padSz); - /* When this is a padding byte and not equal - * to length then mask is set. - */ - invalid |= padding & - ctMaskNotEq(in->buffer[off - i], - (int)ssl->keys.padSz); - } - /* If mask is set then there was an error. */ - if (invalid) { - ret = DECRYPT_ERROR; - } - ssl->keys.padSz += 1; - ssl->keys.decryptedCur = 1; - } - } - else - #endif - { - ret = DecryptTls(ssl, - in->buffer + in->idx, - in->buffer + in->idx, - ssl->curSize); - } - #else - ret = DECRYPT_ERROR; - #endif - } - else - { - #ifdef WOLFSSL_TLS13 - byte *aad = (byte*)&ssl->curRL; - word16 aad_size = RECORD_HEADER_SZ; - #ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) { - /* aad now points to the record header */ - aad = ssl->dtls13CurRL; - aad_size = ssl->dtls13CurRlLength; - } - #endif /* WOLFSSL_DTLS13 */ - /* Don't send an alert for DTLS. We will just drop it - * silently later. */ - ret = DecryptTls13(ssl, - in->buffer + in->idx, - in->buffer + in->idx, - ssl->curSize, - aad, aad_size); - #else - ret = DECRYPT_ERROR; - #endif /* WOLFSSL_TLS13 */ - } - (void)in; - } - + ret = DoDecrypt(ssl); #ifdef WOLFSSL_ASYNC_CRYPT if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) return ret; @@ -22315,9 +22424,7 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* If in DTLS mode, if the decrypt fails for any * reason, pretend the datagram never happened. */ if (ssl->options.dtls) { - ssl->options.processReply = doProcessInit; - ssl->buffers.inputBuffer.idx = - ssl->buffers.inputBuffer.length; + DropAndRestartProcessReply(ssl); return HandleDTLSDecryptFailed(ssl); } #endif /* WOLFSSL_DTLS */ @@ -22385,9 +22492,7 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) /* If in DTLS mode, if the decrypt fails for any * reason, pretend the datagram never happened. */ if (ssl->options.dtls) { - ssl->options.processReply = doProcessInit; - ssl->buffers.inputBuffer.idx = - ssl->buffers.inputBuffer.length; + DropAndRestartProcessReply(ssl); return HandleDTLSDecryptFailed(ssl); } #endif /* WOLFSSL_DTLS */ @@ -22674,11 +22779,18 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) } if (ssl->curSize != 1 || ssl->buffers.inputBuffer.buffer[i] != 1) { - SendAlert(ssl, alert_fatal, illegal_parameter); + SendAlert(ssl, alert_fatal, unexpected_message); WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE); return UNKNOWN_RECORD_TYPE; } ssl->buffers.inputBuffer.idx++; + if (ssl->options.side == WOLFSSL_SERVER_END && + !ssl->msgsReceived.got_client_hello) { + /* Can't appear before CH */ + SendAlert(ssl, alert_fatal, unexpected_message); + WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE); + return UNKNOWN_RECORD_TYPE; + } if (!ssl->msgsReceived.got_change_cipher) { ssl->msgsReceived.got_change_cipher = 1; } @@ -22687,6 +22799,11 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE); return UNKNOWN_RECORD_TYPE; } + if (ssl->keys.decryptedCur == 1) { + SendAlert(ssl, alert_fatal, unexpected_message); + WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE); + return UNKNOWN_RECORD_TYPE; + } break; } #endif @@ -26403,7 +26520,7 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) return "peer ip address mismatch"; case WANT_READ : - case -WOLFSSL_ERROR_WANT_READ : + case WOLFSSL_ERROR_WANT_READ_E : return "non-blocking socket wants data to be read"; case NOT_READY_ERROR : @@ -26413,17 +26530,17 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) return "record layer version error"; case WANT_WRITE : - case -WOLFSSL_ERROR_WANT_WRITE : + case WOLFSSL_ERROR_WANT_WRITE_E : return "non-blocking socket write buffer full"; - case -WOLFSSL_ERROR_WANT_CONNECT: - case -WOLFSSL_ERROR_WANT_ACCEPT: + case WOLFSSL_ERROR_WANT_CONNECT_E : + case WOLFSSL_ERROR_WANT_ACCEPT_E : return "The underlying BIO was not yet connected"; - case -WOLFSSL_ERROR_SYSCALL: + case WOLFSSL_ERROR_SYSCALL_E : return "fatal I/O error in TLS layer"; - case -WOLFSSL_ERROR_WANT_X509_LOOKUP: + case WOLFSSL_ERROR_WANT_X509_LOOKUP_E : return "application client cert callback asked to be called again"; case BUFFER_ERROR : @@ -26463,7 +26580,7 @@ const char* wolfSSL_ERR_reason_error_string(unsigned long e) return "can't decode peer key"; case ZERO_RETURN: - case -WOLFSSL_ERROR_ZERO_RETURN: + case WOLFSSL_ERROR_ZERO_RETURN_E : return "peer sent close notify alert"; case ECC_CURVETYPE_ERROR: @@ -27005,6 +27122,7 @@ void SetErrorString(int error, char* str) #endif #endif /* NO_CIPHER_SUITE_ALIASES */ +#ifndef NO_TLS static const CipherSuiteInfo cipher_names[] = { @@ -27484,6 +27602,14 @@ static const CipherSuiteInfo cipher_names[] = #endif /* WOLFSSL_NO_TLS12 */ }; +#else /* NO_TLS */ + +static const CipherSuiteInfo cipher_names[] = +{ + SUITE_INFO("NO-TLS","NO-TLS", 0, 0, 0, 0), +}; + +#endif /* NO_TLS */ /* returns the cipher_names array */ const CipherSuiteInfo* GetCipherNames(void) @@ -27495,7 +27621,11 @@ const CipherSuiteInfo* GetCipherNames(void) /* returns the number of elements in the cipher_names array */ int GetCipherNamesSize(void) { +#ifdef NO_TLS + return 0; +#else return (int)(sizeof(cipher_names) / sizeof(CipherSuiteInfo)); +#endif } @@ -35260,6 +35390,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, case WOLFSSL_P521_ML_KEM_1024: case WOLFSSL_X25519_ML_KEM_512: case WOLFSSL_X448_ML_KEM_768: +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + case WOLFSSL_P256_ML_KEM_512_OLD: + case WOLFSSL_P384_ML_KEM_768_OLD: + case WOLFSSL_P521_ML_KEM_1024_OLD: +#endif #endif #ifdef WOLFSSL_MLKEM_KYBER case WOLFSSL_P256_KYBER_LEVEL3: @@ -35616,6 +35751,9 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, (void)ssl; + if (args == NULL) + return; + #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER); args->exportBuf = NULL; @@ -35624,7 +35762,11 @@ static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx, XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE); args->verifySig = NULL; #endif - (void)args; + + if (args->input != NULL) { + XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER); + args->input = NULL; + } } /* handle generation of server_key_exchange (12) */ @@ -42644,7 +42786,122 @@ static SecCertificateRef ConvertToSecCertificateRef(const byte* derCert, return secCert; } +static int DisplaySecTrustError(CFErrorRef error, SecTrustRef trust) +{ + CFStringRef desc; + CFStringRef domain; + SecTrustResultType trustResult; + CFDictionaryRef info; + /* Description */ + desc = CFErrorCopyDescription(error); + if (desc) { + char buffer[256]; + if (CFStringGetCString(desc, buffer, sizeof(buffer), + kCFStringEncodingUTF8)) { + WOLFSSL_MSG_EX("SecTrustEvaluateWithError Error description: %s\n", + buffer); + } + CFRelease(desc); + } + + /* Domain */ + domain = CFErrorGetDomain(error); + if (domain) { + char domainStr[128]; + if (CFStringGetCString(domain, domainStr, sizeof(domainStr), + kCFStringEncodingUTF8)) { + WOLFSSL_MSG_EX("SecTrustEvaluateWithError Domain: %s\n", domainStr); + } + } + + /* Get additional trust result info */ + if (SecTrustGetTrustResult(trust, &trustResult) == errSecSuccess) { + WOLFSSL_MSG_EX("SecTrustResultType: %d\n", trustResult); + /* Optional: decode the enum */ + switch (trustResult) { + case kSecTrustResultInvalid: + WOLFSSL_MSG("TrustResult: Invalid\n"); + break; + case kSecTrustResultProceed: + WOLFSSL_MSG("TrustResult: Proceed\n"); + break; + case kSecTrustResultDeny: + WOLFSSL_MSG("TrustResult: Deny\n"); + break; + case kSecTrustResultUnspecified: + WOLFSSL_MSG("TrustResult: Unspecified (implicitly trusted)\n"); + break; + case kSecTrustResultRecoverableTrustFailure: + WOLFSSL_MSG("TrustResult: Recoverable trust failure\n"); + break; + case kSecTrustResultFatalTrustFailure: + WOLFSSL_MSG("TrustResult: Fatal trust failure\n"); + break; + case kSecTrustResultOtherError: + WOLFSSL_MSG("TrustResult: Other error\n"); + break; + default: + WOLFSSL_MSG("TrustResult: Unknown\n"); + break; + } + } + else { + WOLFSSL_MSG("SecTrustGetTrustResult failed\n"); + } + + info = CFErrorCopyUserInfo(error); + if (info) { + WOLFSSL_MSG("Trust error info dump:\n"); + CFShow(info); + CFRelease(info); + } + + return 0; +} + +#if defined(WOLFSSL_APPLE_NATIVE_CERT_VALIDATION) && \ + defined (WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION) +static int MaxValidityPeriodErrorOnly(CFErrorRef error) +{ + int multiple = 0; + + CFDictionaryRef userInfo = CFErrorCopyUserInfo(error); + if (userInfo) { + /* Get underlying error */ + CFTypeRef underlying = + CFDictionaryGetValue(userInfo, kCFErrorUnderlyingErrorKey); + if (underlying) { + /* Get underlying error value*/ + CFDictionaryRef underlyingDict = + CFErrorCopyUserInfo((CFErrorRef)underlying); + if (underlyingDict) { + char buffer[512]; + CFStringRef values = + CFDictionaryGetValue(underlyingDict, + kCFErrorLocalizedDescriptionKey); + if(CFStringGetCString(values, buffer, sizeof(buffer), + kCFStringEncodingUTF8)) { + if (XSTRSTR(buffer, "Certificate exceeds maximum " + "temporal validity period") && + (!XSTRSTR(buffer, "Certificate exceeds maximum " + "temporal validity period,") || + !XSTRSTR(buffer, ", Certificate exceeds maximum " + "temporal validity period"))) { + WOLFSSL_MSG("Maximum validity period error only"); + } else { + WOLFSSL_MSG("Found other errors"); + multiple = 1; + } + } + CFRelease(underlyingDict); + } + } + CFRelease(userInfo); + } + return multiple; +} +#endif /* * Validates a chain of certificates using the Apple system trust APIs * @@ -42660,21 +42917,23 @@ static SecCertificateRef ConvertToSecCertificateRef(const byte* derCert, * wolfSSL's built-in certificate validation mechanisms anymore. We instead * must call into the Security Framework APIs to authenticate peer certificates */ -static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, - int totalCerts) +static int DoAppleNativeCertValidation(WOLFSSL* ssl, + const WOLFSSL_BUFFER_INFO* certs, + int totalCerts) { - int i; - int ret; - OSStatus status; + int i; + int ret; + OSStatus status; CFMutableArrayRef certArray = NULL; SecCertificateRef secCert = NULL; SecTrustRef trust = NULL; - SecPolicyRef policy = NULL ; + SecPolicyRef policy = NULL; + CFStringRef hostname = NULL; + CFErrorRef error = NULL; WOLFSSL_ENTER("DoAppleNativeCertValidation"); - certArray = CFArrayCreateMutable(kCFAllocatorDefault, - totalCerts, + certArray = CFArrayCreateMutable(kCFAllocatorDefault, totalCerts, &kCFTypeArrayCallBacks); if (!certArray) { WOLFSSL_MSG("Error: can't allocate CFArray for certificates"); @@ -42683,8 +42942,8 @@ static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, } for (i = 0; i < totalCerts; i++) { - secCert = ConvertToSecCertificateRef(certs[i].buffer, - (int)certs[i].length); + secCert = + ConvertToSecCertificateRef(certs[i].buffer, (int)certs[i].length); if (!secCert) { WOLFSSL_MSG("Error: can't convert DER cert to SecCertificateRef"); ret = 0; @@ -42698,24 +42957,80 @@ static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, } /* Create trust object for SecCertifiate Ref */ - policy = SecPolicyCreateSSL(true, NULL); + if (ssl->buffers.domainName.buffer && ssl->buffers.domainName.length > 0) { + /* Create policy with specified value to require host name match */ + hostname = CFStringCreateWithCString( + kCFAllocatorDefault, (const char*)ssl->buffers.domainName.buffer, + kCFStringEncodingUTF8); + } + if (hostname != NULL) { + policy = SecPolicyCreateSSL(true, hostname); + } + else { + policy = SecPolicyCreateSSL(true, NULL); + } status = SecTrustCreateWithCertificates(certArray, policy, &trust); if (status != errSecSuccess) { WOLFSSL_MSG_EX("Error creating trust object, " - "SecTrustCreateWithCertificates returned %d",status); + "SecTrustCreateWithCertificates returned %d", + status); ret = 0; goto cleanup; } +#if defined(WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION) + /* TEST ONLY CODE: + * Set accumulated list of trusted CA certificates as trust anchors */ + WOLFSSL_MSG("Setting anchor certificates"); + if (ssl->ctx->testTrustedCAs != NULL) { + status = SecTrustSetAnchorCertificates(trust, ssl->ctx->testTrustedCAs); + if (status != errSecSuccess) { + WOLFSSL_MSG_EX("Error setting anchor certificates: %d", status); + ret = 0; + goto cleanup; + } + } +#endif + /* Evaluate the certificate's authenticity */ - if (SecTrustEvaluateWithError(trust, NULL) == 1) { - WOLFSSL_MSG("Cert chain is trusted"); - ret = 1; + WOLFSSL_MSG("Performing Apple native cert validation via " + "SecTrustEvaluateWithError"); + ret = SecTrustEvaluateWithError(trust, &error); + if (ret != 1) { + if (error) { + CFIndex code; + code = CFErrorGetCode(error); + WOLFSSL_MSG_EX("SecTrustEvaluateWithError failed with code: %ld\n", + code); + DisplaySecTrustError(error, trust); + +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + /* TEST ONLY CODE: + * wolfSSL API tests use a cert with a validity period that is too + * long for the Apple system trust APIs + * (See: https://support.apple.com/en-us/103769) + * therefore we should skip over this particular error */ + if (code == errSecCertificateValidityPeriodTooLong) { + if (MaxValidityPeriodErrorOnly(error)) { + WOLFSSL_MSG("Multiple reasons for validity period error, " + "not skipping"); + ret = 0; + } else { + WOLFSSL_MSG("Skipping certificate validity period error"); + ret = 1; + } + } +#endif + (void)code; + CFRelease(error); + } + else { + WOLFSSL_MSG( + "SecTrustEvaluateWithError failed with unknown error.\n"); + } } else { - WOLFSSL_MSG("Cert chain trust evaluation failed" - "SecTrustEvaluateWithError returned 0"); - ret = 0; + WOLFSSL_MSG("SecTrustEvaluateWithError succeeded"); } /* Cleanup */ @@ -42729,11 +43044,46 @@ static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs, if (policy) { CFRelease(policy); } + if (hostname) { + CFRelease(hostname); + } WOLFSSL_LEAVE("DoAppleNativeCertValidation", ret); return ret; } + +#if defined(WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION) +int wolfSSL_TestAppleNativeCertValidation_AppendCA(WOLFSSL_CTX* ctx, + const byte* derCert, + int derLen) +{ + SecCertificateRef certRef; + + if (derCert == NULL || derLen == 0) { + return WOLFSSL_FAILURE; + } + + /* Create the base array for trust anchors if it doesn't exist */ + if (ctx->testTrustedCAs == NULL) { + ctx->testTrustedCAs = + CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); + if (!ctx->testTrustedCAs) { + return WOLFSSL_FAILURE; + } + } + + certRef = ConvertToSecCertificateRef(derCert, derLen); + if (!certRef) { + return false; + } + + CFArrayAppendValue(ctx->testTrustedCAs, certRef); + CFRelease(certRef); + return WOLFSSL_SUCCESS; +} +#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ + #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */ #undef ERROR_OUT diff --git a/src/src/keys.c b/src/src/keys.c index 8f8d2eb..e42a6eb 100644 --- a/src/src/keys.c +++ b/src/src/keys.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -3554,6 +3554,13 @@ int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side) ret = PROTOCOLCB_UNAVAILABLE; if (ssl->ctx->EncryptKeysCb) { void* ctx = wolfSSL_GetEncryptKeysCtx(ssl); + #if defined(WOLFSSL_RENESAS_FSPSM_TLS) + FSPSM_ST* cbInfo = (FSPSM_ST*)ctx; + cbInfo->side = side; + #elif defined(WOLFSSL_RENESAS_TSIP_TLS) + TsipUserCtx* cbInfo = (TsipUserCtx*)ctx; + cbInfo->key_side = side; + #endif ret = ssl->ctx->EncryptKeysCb(ssl, ctx); } if (!ssl->ctx->EncryptKeysCb || diff --git a/src/src/ocsp.c b/src/src/ocsp.c index c90936a..f121662 100644 --- a/src/src/ocsp.c +++ b/src/src/ocsp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/src/pk.c b/src/src/pk.c index 3136cf9..7cb73d7 100644 --- a/src/src/pk.c +++ b/src/src/pk.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -360,11 +360,13 @@ static int der_write_to_file_as_pem(const unsigned char* der, int derSz, * @param [in] passedSz Size of password in bytes. * @param [out] cipherInfo PEM cipher information lines. * @param [in] maxDerSz Maximum size of DER buffer. + * @param [in] hashType Hash algorithm * @return 1 on success. * @return 0 on error. */ int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, - unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz) + unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz, + int hashType) { int ret = 0; int paddingSz = 0; @@ -433,7 +435,7 @@ int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, /* Encrypt DER buffer. */ ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz, - WC_MD5); + hashType); if (ret != 0) { WOLFSSL_MSG("encrypt key failed"); } @@ -504,6 +506,12 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, byte* tmp = NULL; byte* cipherInfo = NULL; int pemSz = 0; + int hashType = WC_HASH_TYPE_NONE; +#if !defined(NO_MD5) + hashType = WC_MD5; +#elif !defined(NO_SHA) + hashType = WC_SHA; +#endif /* Macro doesn't always use it. */ (void)heap; @@ -536,7 +544,7 @@ static int der_to_enc_pem_alloc(unsigned char* der, int derSz, /* Encrypt DER inline. */ ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz, - &cipherInfo, derSz + blockSz); + &cipherInfo, derSz + blockSz, hashType); if (ret != 1) { WOLFSSL_ERROR_MSG("EncryptDerKey failed"); } @@ -3526,9 +3534,43 @@ int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e, * RSA padding APIs */ -#if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \ - defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)) -#if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0) +#ifdef WC_RSA_PSS + +#if defined(OPENSSL_EXTRA) && !defined(HAVE_SELFTEST) && \ + (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) +static int rsa_pss_calc_salt(int saltLen, int hashLen, int emLen) +{ + /* Calculate the salt length to use for special cases. */ + switch (saltLen) { + /* Negative saltLen values are treated differently. */ + case WC_RSA_PSS_SALTLEN_DIGEST: + saltLen = hashLen; + break; + case WC_RSA_PSS_SALTLEN_MAX_SIGN: + case WC_RSA_PSS_SALTLEN_MAX: + #ifdef WOLFSSL_PSS_LONG_SALT + saltLen = emLen - hashLen - 2; + #else + saltLen = hashLen; + (void)emLen; + #endif + break; + default: + break; + } + if (saltLen < 0) { + /* log invalid salt, let wolfCrypt handle error */ + WOLFSSL_ERROR_MSG("invalid saltLen"); + saltLen = -3; /* for wolfCrypt to produce error must be < -2 */ + } + return saltLen; +} +#endif /* OPENSSL_EXTRA && !HAVE_SELFTEST */ + +#if (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \ + defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)) && \ + (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)) + /* Add PKCS#1 PSS padding to hash. * * @@ -3646,28 +3688,7 @@ int wolfSSL_RSA_padding_add_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, unsigned char *em, } if (ret == 1) { - /* Calculate the salt length to use for special cases. */ - /* TODO: use special case wolfCrypt values? */ - switch (saltLen) { - /* Negative saltLen values are treated differently. */ - case RSA_PSS_SALTLEN_DIGEST: - saltLen = hashLen; - break; - case RSA_PSS_SALTLEN_MAX_SIGN: - case RSA_PSS_SALTLEN_MAX: - #ifdef WOLFSSL_PSS_LONG_SALT - saltLen = emLen - hashLen - 2; - #else - saltLen = hashLen; - #endif - break; - default: - if (saltLen < 0) { - /* No other negative values implemented. */ - WOLFSSL_ERROR_MSG("invalid saltLen"); - ret = 0; - } - } + saltLen = rsa_pss_calc_salt(saltLen, hashLen, emLen); } if (ret == 1) { @@ -3759,31 +3780,7 @@ int wolfSSL_RSA_verify_PKCS1_PSS_mgf1(WOLFSSL_RSA *rsa, } if (ret == 1) { - /* Calculate the salt length to use for special cases. */ - switch (saltLen) { - /* Negative saltLen values are treated differently */ - case RSA_PSS_SALTLEN_DIGEST: - saltLen = hashLen; - break; - case RSA_PSS_SALTLEN_AUTO: - #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER - saltLen = RSA_PSS_SALT_LEN_DISCOVER; - break; - #endif - case RSA_PSS_SALTLEN_MAX: - #ifdef WOLFSSL_PSS_LONG_SALT - saltLen = emLen - hashLen - 2; - #else - saltLen = hashLen; - #endif - break; - default: - if (saltLen < 0) { - /* No other negative values implemented. */ - WOLFSSL_ERROR_MSG("invalid saltLen"); - ret = 0; - } - } + saltLen = rsa_pss_calc_salt(saltLen, hashLen, emLen); } if (ret == 1) { @@ -3848,18 +3845,23 @@ int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash, return wolfSSL_RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, hashAlg, NULL, em, saltLen); } -#endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */ -#endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || - * WOLFSSL_NGINX) */ +#endif /* (!HAVE_FIPS || FIPS_VERSION_GT(2,0)) && \ + (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_NGINX) */ +#endif /* WC_RSA_PSS */ /* * RSA sign/verify APIs */ -#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER - #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT +#if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \ + (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1)) + #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER + #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT + #else + #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER + #endif #else - #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER + #define DEF_PSS_SALT_LEN 0 /* not used */ #endif #if defined(OPENSSL_EXTRA) @@ -3972,6 +3974,14 @@ int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash, return ret; } +int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, + unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen, + WOLFSSL_RSA* rsa, int flag, int padding) +{ + return wolfSSL_RSA_sign_mgf(hashAlg, hash, hLen, sigRet, sigLen, rsa, flag, + padding, hashAlg, DEF_PSS_SALT_LEN); +} + /** * Sign a message hash with the chosen message digest, padding, and RSA key. * @@ -3990,12 +4000,14 @@ int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash, * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and * WC_RSA_PKCS1_PADDING are currently supported for * signing. + * @param [in] mgf1Hash MGF1 Hash NID + * @param [in] saltLen Length of RSA PSS salt * @return 1 on success. * @return 0 on failure. */ -int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, +int wolfSSL_RSA_sign_mgf(int hashAlg, const unsigned char* hash, unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen, - WOLFSSL_RSA* rsa, int flag, int padding) + WOLFSSL_RSA* rsa, int flag, int padding, int mgf1Hash, int saltLen) { int ret = 1; word32 outLen = 0; @@ -4012,8 +4024,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, #endif unsigned int encSz = 0; - - WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding"); + WOLFSSL_ENTER("wolfSSL_RSA_sign_mgf"); if (flag == 0) { /* Only encode message. */ @@ -4080,7 +4091,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, case WC_RSA_NO_PAD: if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen, (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) { - WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad"); + WOLFSSL_ERROR_MSG("Bad RSA Sign no pad"); ret = 0; } break; @@ -4089,17 +4100,20 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1)) case WC_RSA_PKCS1_PSS_PADDING: { - enum wc_HashType hType = - wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); - #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER - WOLFSSL_MSG("Using RSA-PSS with hash length salt. " - "OpenSSL uses max length by default."); - #endif + RsaKey* key = (RsaKey*)rsa->internal; + enum wc_HashType mgf1, hType; + hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); + if (mgf1Hash == WC_NID_undef) + mgf1Hash = hashAlg; + mgf1 = wc_OidGetHash((int)nid2oid(mgf1Hash, oidHashType)); + /* handle compat layer salt special cases */ + saltLen = rsa_pss_calc_salt(saltLen, wc_HashGetDigestSize(hType), + wolfSSL_RSA_size(rsa)); + /* Create RSA PSS signature. */ if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen, - hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN, - (RsaKey*)rsa->internal, rng)) <= 0) { - WOLFSSL_ERROR_MSG("Bad Rsa Sign"); + hType, wc_hash2mgf(mgf1), saltLen, key, rng)) <= 0) { + WOLFSSL_ERROR_MSG("Bad RSA PSS Sign"); ret = 0; } break; @@ -4118,13 +4132,15 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, /* Sign (private encrypt) PKCS#1 encoded signature. */ if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen, (RsaKey*)rsa->internal, rng)) <= 0) { - WOLFSSL_ERROR_MSG("Bad Rsa Sign"); + WOLFSSL_ERROR_MSG("Bad PKCS1 RSA Sign"); ret = 0; } break; } default: WOLFSSL_ERROR_MSG("Unsupported padding"); + (void)mgf1Hash; + (void)saltLen; ret = 0; break; } @@ -4145,7 +4161,7 @@ int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash, XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE); #endif - WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret); + WOLFSSL_LEAVE("wolfSSL_RSA_sign_mgf", ret); return ret; } @@ -4169,6 +4185,14 @@ int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash, WC_RSA_PKCS1_PADDING); } +int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, + unsigned int hLen, const unsigned char* sig, unsigned int sigLen, + WOLFSSL_RSA* rsa, int padding) +{ + return wolfSSL_RSA_verify_mgf(hashAlg, hash, hLen, sig, sigLen, rsa, + padding, hashAlg, DEF_PSS_SALT_LEN); +} + /** * Verify a message hash with the chosen message digest, padding, and RSA key. * @@ -4183,12 +4207,14 @@ int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash, * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and * WC_RSA_PKCS1_PADDING are currently supported for * signing. + * @param [in] mgf1Hash MGF1 Hash NID + * @param [in] saltLen Length of RSA PSS salt * @return 1 on success. * @return 0 on failure. */ -int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, +int wolfSSL_RSA_verify_mgf(int hashAlg, const unsigned char* hash, unsigned int hLen, const unsigned char* sig, unsigned int sigLen, - WOLFSSL_RSA* rsa, int padding) + WOLFSSL_RSA* rsa, int padding, int mgf1Hash, int saltLen) { int ret = 1; #ifdef WOLFSSL_SMALL_STACK @@ -4203,7 +4229,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, enum wc_HashType hType = WC_HASH_TYPE_NONE; #endif - WOLFSSL_ENTER("wolfSSL_RSA_verify"); + WOLFSSL_ENTER("wolfSSL_RSA_verify_mgf"); /* Validate parameters. */ if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) { @@ -4220,8 +4246,49 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, ret = 0; } } + if (ret == 1 && padding == WC_RSA_PKCS1_PSS_PADDING) { + #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \ + (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1)) + RsaKey* key = (RsaKey*)rsa->internal; + enum wc_HashType mgf1; + hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType)); + if (mgf1Hash == WC_NID_undef) + mgf1Hash = hashAlg; + mgf1 = wc_OidGetHash((int)nid2oid(mgf1Hash, oidHashType)); + + /* handle compat layer salt special cases */ + saltLen = rsa_pss_calc_salt(saltLen, wc_HashGetDigestSize(hType), + wolfSSL_RSA_size(rsa)); + + verLen = wc_RsaPSS_Verify_ex((byte*)sig, sigLen, sigDec, sigLen, + hType, wc_hash2mgf(mgf1), saltLen, key); + if (verLen > 0) { + /* Check PSS padding is valid. */ + if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen, + hType, saltLen, mp_count_bits(&key->n)) != 0) { + WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error"); + ret = WOLFSSL_FAILURE; + } + else { + /* Success! Free resources and return early */ + XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return WOLFSSL_SUCCESS; + } + } + else { + WOLFSSL_ERROR_MSG("wc_RsaPSS_Verify_ex failed!"); + ret = WOLFSSL_FAILURE; + } + #else + (void)mgf1Hash; + (void)saltLen; + WOLFSSL_ERROR_MSG("RSA PSS not compiled in!"); + ret = WOLFSSL_FAILURE; + #endif + } + #ifdef WOLFSSL_SMALL_STACK - if ((ret == 1) && (padding != WC_RSA_PKCS1_PSS_PADDING)) { + if (ret == 1) { /* Allocate memory for encoded signature. */ encodedSig = (unsigned char *)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -4231,7 +4298,7 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, } } #endif - if ((ret == 1) && (padding != WC_RSA_PKCS1_PSS_PADDING)) { + if (ret == 1) { /* Make encoded signature to compare with decrypted signature. */ if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len, padding) <= 0) { @@ -4258,20 +4325,6 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, #endif } if (ret == 1) { - #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \ - (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) - if (padding == WC_RSA_PKCS1_PSS_PADDING) { - /* Check PSS padding is valid. */ - if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen, - hType, DEF_PSS_SALT_LEN, - mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) { - WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error"); - ret = 0; - } - } - else - #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS || - * FIPS_VERSION >= 5.1) */ /* Compare decrypted signature to encoded signature. */ if (((int)len != verLen) || (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) { @@ -4285,6 +4338,8 @@ int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash, XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + WOLFSSL_LEAVE("wolfSSL_RSA_verify_mgf", ret); return ret; } @@ -5978,7 +6033,8 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen) { -#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM) +#if (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \ + !defined(NO_MD5) byte *derBuf, *tmp, *cipherInfo = NULL; int der_max_len = 0, derSz = 0; const int type = DSA_PRIVATEKEY_TYPE; @@ -6024,8 +6080,8 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, if (passwd != NULL && passwdSz > 0 && cipher != NULL) { int ret; - ret = EncryptDerKey(derBuf, &derSz, cipher, - passwd, passwdSz, &cipherInfo, der_max_len); + ret = EncryptDerKey(derBuf, &derSz, cipher, passwd, passwdSz, + &cipherInfo, der_max_len, WC_MD5); if (ret != 1) { WOLFSSL_MSG("EncryptDerKey failed"); XFREE(derBuf, NULL, DYNAMIC_TYPE_DER); @@ -6086,7 +6142,7 @@ int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa, (void)pem; (void)pLen; return 0; -#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */ +#endif /* (WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM) && !NO_MD5 */ } #ifndef NO_FILESYSTEM diff --git a/src/src/quic.c b/src/src/quic.c index 5791a7d..7c30cfc 100644 --- a/src/src/quic.c +++ b/src/src/quic.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -989,12 +989,16 @@ const WOLFSSL_EVP_CIPHER* wolfSSL_quic_get_aead(WOLFSSL* ssl) switch (cipher->cipherSuite) { #if !defined(NO_AES) && defined(HAVE_AESGCM) + #ifdef WOLFSSL_AES_128 case TLS_AES_128_GCM_SHA256: evp_cipher = wolfSSL_EVP_aes_128_gcm(); break; + #endif + #ifdef WOLFSSL_AES_256 case TLS_AES_256_GCM_SHA384: evp_cipher = wolfSSL_EVP_aes_256_gcm(); break; + #endif #endif #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) case TLS_CHACHA20_POLY1305_SHA256: diff --git a/src/src/sniffer.c b/src/src/sniffer.c index 4d0c8e1..2bda758 100644 --- a/src/src/sniffer.c +++ b/src/src/sniffer.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -27,6 +27,7 @@ /* Build Options: * WOLFSSL_SNIFFER_NO_RECOVERY: Do not track missed data count. + * SNIFFER_SINGLE_SESSION_CACHE: Do not cache more than one session. */ @@ -446,7 +447,6 @@ typedef struct Flags { byte serverCipherOn; /* indicates whether cipher is active */ byte clientCipherOn; /* indicates whether cipher is active */ byte resuming; /* did this session come from resumption */ - byte cached; /* have we cached this session yet */ byte clientHello; /* processed client hello yet, for SSLv2 */ byte finCount; /* get both FINs before removing */ byte fatalError; /* fatal error state */ @@ -462,6 +462,9 @@ typedef struct Flags { #ifdef WOLFSSL_ASYNC_CRYPT byte wasPolled; #endif +#ifdef SNIFFER_SINGLE_SESSION_CACHE + byte cached; /* have we cached this session yet */ +#endif } Flags; @@ -3266,25 +3269,25 @@ static int ProcessClientKeyExchange(const byte* input, int* sslBytes, static int ProcessKeyShare(KeyShareInfo* info, const byte* input, int len, word16 filter_group) { - int index = 0; - while (index < len) { + int idx = 0; + while (idx < len) { /* clear info (reset dh_key_bits and curve_id) */ XMEMSET(info, 0, sizeof(KeyShareInfo)); /* Named group and public key */ - info->named_group = (word16)((input[index] << 8) | input[index+1]); - index += OPAQUE16_LEN; + info->named_group = (word16)((input[idx] << 8) | input[idx+1]); + idx += OPAQUE16_LEN; info->key_len = 0; info->key = NULL; /* If key was provided... (a hello_retry_request will not send a key) */ - if (index + 2 <= len) { - info->key_len = (word16)((input[index] << 8) | input[index+1]); - index += OPAQUE16_LEN; - if (info->key_len == 0 || info->key_len > len - index) { + if (idx + 2 <= len) { + info->key_len = (word16)((input[idx] << 8) | input[idx+1]); + idx += OPAQUE16_LEN; + if (info->key_len == 0 || info->key_len > len - idx) { return WOLFSSL_FATAL_ERROR; } - info->key = &input[index]; - index += info->key_len; + info->key = &input[idx]; + idx += info->key_len; } switch (info->named_group) { @@ -3466,6 +3469,7 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, if (IsAtLeastTLSv1_3(ssl->version)) { /* Note: Must use server session for sessions */ #ifdef HAVE_SESSION_TICKET + WOLFSSL_SESSION* sess; if (SetTicket(session->sslServer, input, len) != 0) { SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE); return WOLFSSL_FATAL_ERROR; @@ -3474,10 +3478,11 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, /* set haveSessionId to use the wolfSession cache */ session->sslServer->options.haveSessionId = 1; + #ifdef SNIFFER_SINGLE_SESSION_CACHE /* Use the wolf Session cache to retain resumption secret */ if (session->flags.cached == 0) { - WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer, - NULL, 0); + #endif /* SNIFFER_SINGLE_SESSION_CACHE */ + sess = wolfSSL_GetSession(session->sslServer, NULL, 0); if (sess == NULL) { SetupSession(session->sslServer); AddSession(session->sslServer); /* don't re add */ @@ -3485,8 +3490,10 @@ static int ProcessSessionTicket(const byte* input, int* sslBytes, INC_STAT(SnifferStats.sslResumptionInserts); #endif } + #ifdef SNIFFER_SINGLE_SESSION_CACHE session->flags.cached = 1; } + #endif /* SNIFFER_SINGLE_SESSION_CACHE */ #endif /* HAVE_SESSION_TICKET */ } else @@ -4405,7 +4412,11 @@ static int ProcessFinished(const byte* input, int size, int* sslBytes, return ret; } - if (ret == 0 && session->flags.cached == 0) { + if (ret == 0 + #ifdef SNIFFER_SINGLE_SESSION_CACHE + && session->flags.cached == 0 + #endif + ) { if (session->sslServer->options.haveSessionId) { #ifndef NO_SESSION_CACHE WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer, NULL, 0); @@ -4416,7 +4427,9 @@ static int ProcessFinished(const byte* input, int size, int* sslBytes, INC_STAT(SnifferStats.sslResumptionInserts); #endif } - session->flags.cached = 1; + #ifdef SNIFFER_SINGLE_SESSION_CACHE + session->flags.cached = 1; + #endif #endif } } @@ -5116,6 +5129,12 @@ static void RemoveStaleSessions(void) } } +void ssl_RemoveStaleSessions(void) +{ + LOCK_SESSION(); + RemoveStaleSessions(); + UNLOCK_SESSION(); +} /* Create a new Sniffer Session */ static SnifferSession* CreateSession(IpInfo* ipInfo, TcpInfo* tcpInfo, @@ -6365,10 +6384,31 @@ static int ProcessMessage(const byte* sslFrame, SnifferSession* session, Trace(GOT_APP_DATA_STR); { word32 inOutIdx = 0; + int ivExtra = 0; ret = DoApplicationData(ssl, (byte*)sslFrame, &inOutIdx, SNIFF); if (ret == 0) { ret = ssl->buffers.clearOutputBuffer.length; + #ifndef WOLFSSL_AEAD_ONLY + if (ssl->specs.cipher_type == block) { + if (ssl->options.tls1_1) + ivExtra = ssl->specs.block_size; + } + else + #endif + if (ssl->specs.cipher_type == aead) { + if (!ssl->options.tls1_3 && + ssl->specs.bulk_cipher_algorithm != wolfssl_chacha) + ivExtra = AESGCM_EXP_IV_SZ; + } + + ret -= ivExtra;; + + #if defined(HAVE_ENCRYPT_THEN_MAC) && \ + !defined(WOLFSSL_AEAD_ONLY) + if (ssl->options.startedETMRead) + ret -= MacSize(ssl); + #endif TraceGotData(ret); if (ret) { /* may be blank message */ if (data != NULL) { @@ -7276,7 +7316,7 @@ static int addSecretNode(unsigned char* clientRandom, unsigned char* secret, char* error) { - int index = 0; + int idx = 0; int ret = 0; SecretNode* node = NULL; @@ -7286,8 +7326,8 @@ static int addSecretNode(unsigned char* clientRandom, LOCK_SECRET_LIST(); - index = secretHashFunction(clientRandom); - node = secretHashTable[index]; + idx = secretHashFunction(clientRandom); + node = secretHashTable[idx]; while(node) { /* Node already exists, so just add the requested secret */ @@ -7330,12 +7370,12 @@ static unsigned char* findSecret(unsigned char* clientRandom, int type) { unsigned char* secret = NULL; SecretNode* node = NULL; - unsigned int index = 0; + unsigned int idx = 0; LOCK_SECRET_LIST(); - index = secretHashFunction(clientRandom); - node = secretHashTable[index]; + idx = secretHashFunction(clientRandom); + node = secretHashTable[idx]; while (node != NULL) { if (XMEMCMP(node->clientRandom, @@ -7607,6 +7647,106 @@ int ssl_LoadSecretsFromKeyLogFile(const char* keylogfile, char* error) #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */ +/* + * Removes a session from the SessionTable based on client/server IP & ports + * Returns 0 if a session was found and freed, -1 otherwise + */ +int ssl_RemoveSession(const char* clientIp, int clientPort, + const char* serverIp, int serverPort, + char* error) +{ + IpAddrInfo clientAddr; + IpAddrInfo serverAddr; + IpInfo ipInfo; + TcpInfo tcpInfo; + SnifferSession* session; + int ret = -1; /* Default to not found */ + word32 row; + + if (clientIp == NULL || serverIp == NULL) { + SetError(BAD_IPVER_STR, error, NULL, 0); + return ret; + } + + /* Set up client IP address */ + clientAddr.version = IPV4; + clientAddr.ip4 = XINET_ADDR(clientIp); + if (clientAddr.ip4 == XINADDR_NONE) { + #ifdef FUSION_RTOS + if (XINET_PTON(AF_INET6, clientIp, clientAddr.ip6, + sizeof(clientAddr.ip4)) == 1) + #else + if (XINET_PTON(AF_INET6, clientIp, clientAddr.ip6) == 1) + #endif + { + clientAddr.version = IPV6; + } + else { + SetError(BAD_IPVER_STR, error, NULL, 0); + return ret; + } + } + + /* Set up server IP address */ + serverAddr.version = IPV4; + serverAddr.ip4 = XINET_ADDR(serverIp); + if (serverAddr.ip4 == XINADDR_NONE) { + #ifdef FUSION_RTOS + if (XINET_PTON(AF_INET6, serverIp, serverAddr.ip6, + sizeof(serverAddr.ip4)) == 1) + #else + if (XINET_PTON(AF_INET6, serverIp, serverAddr.ip6) == 1) + #endif + { + serverAddr.version = IPV6; + } + else { + SetError(BAD_IPVER_STR, error, NULL, 0); + return ret; + } + } + + XMEMSET(&ipInfo, 0, sizeof(ipInfo)); + XMEMSET(&tcpInfo, 0, sizeof(tcpInfo)); + + /* Set up client->server direction */ + ipInfo.src = clientAddr; + ipInfo.dst = serverAddr; + tcpInfo.srcPort = clientPort; + tcpInfo.dstPort = serverPort; + + /* Calculate the hash row for this session */ + row = SessionHash(&ipInfo, &tcpInfo); + + LOCK_SESSION(); + + /* Search only the specific row in the session table */ + session = SessionTable[row]; + + while (session) { + SnifferSession* next = session->next; + + /* Check if this session matches the specified client/server IP/port */ + if (MatchAddr(session->client, clientAddr) && + MatchAddr(session->server, serverAddr) && + session->cliPort == clientPort && + session->srvPort == serverPort) { + + /* Use RemoveSession to remove and free the session */ + RemoveSession(session, NULL, NULL, row); + ret = 0; /* Session found and freed */ + break; + } + + session = next; + } + + UNLOCK_SESSION(); + + return ret; +} + + #undef ERROR_OUT #endif /* WOLFSSL_SNIFFER */ diff --git a/src/src/ssl.c b/src/src/ssl.c index 0b74065..4191557 100644 --- a/src/src/ssl.c +++ b/src/src/ssl.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -232,8 +232,10 @@ static struct SystemCryptoPolicy crypto_policy; static WC_RNG globalRNG; static volatile int initGlobalRNG = 0; +#if defined(OPENSSL_EXTRA) || !defined(WOLFSSL_MUTEX_INITIALIZER) static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex); +#endif #ifndef WOLFSSL_MUTEX_INITIALIZER static int globalRNGMutex_valid = 0; #endif @@ -297,30 +299,36 @@ WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local); WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local) { WC_RNG* ret = NULL; +#ifdef WOLFSSL_SMALL_STACK + int freeRng = 0; - /* Assume not local until one created. */ - *local = 0; + /* Allocate RNG object . */ + if (rng == NULL) { + rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); + freeRng = 1; + } +#endif + if (rng != NULL) { + if (wc_InitRng(rng) == 0) { + ret = rng; + *local = 1; + } + else { + WOLFSSL_MSG("Bad RNG Init"); #ifdef WOLFSSL_SMALL_STACK - /* Allocate RNG object . */ - rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); + if (freeRng) { + XFREE(rng, NULL, DYNAMIC_TYPE_RNG); + rng = NULL; + } #endif - /* Check we have a local RNG object and initialize. */ - if ((rng != NULL) && (wc_InitRng(rng) == 0)) { - ret = rng; - *local = 1; + } } if (ret == NULL) { - #ifdef HAVE_GLOBAL_RNG - WOLFSSL_MSG("Bad RNG Init, trying global"); - #endif - ret = wolfssl_make_global_rng(); - } - - if (ret != rng) { -#ifdef WOLFSSL_SMALL_STACK - XFREE(rng, NULL, DYNAMIC_TYPE_RNG); +#ifdef HAVE_GLOBAL_RNG + WOLFSSL_MSG("trying global RNG"); #endif + ret = wolfssl_make_global_rng(); } return ret; @@ -1004,16 +1012,23 @@ int GetEchConfigsEx(WOLFSSL_EchConfig* configs, byte* output, word32* outputLen) WOLFSSL_EchConfig* workingConfig = NULL; byte* outputStart = output; word32 totalLen = 2; - word32 workingOutputLen; + word32 workingOutputLen = 0; - if (configs == NULL || outputLen == NULL || *outputLen < totalLen) + if (configs == NULL || outputLen == NULL || + (output != NULL && *outputLen < totalLen)) { return BAD_FUNC_ARG; + } - workingOutputLen = *outputLen - totalLen; /* skip over total length which we fill in later */ - if (output != NULL) + if (output != NULL) { + workingOutputLen = *outputLen - totalLen; output += 2; + } + else { + /* caller getting the size only, set current 2 byte length size */ + *outputLen = totalLen; + } workingConfig = configs; @@ -6148,6 +6163,12 @@ int wolfSSL_Init(void) WOLFSSL_ENTER("wolfSSL_Init"); +#if defined(LIBWOLFSSL_CMAKE_OUTPUT) + WOLFSSL_MSG(LIBWOLFSSL_CMAKE_OUTPUT); +#else + WOLFSSL_MSG("No extra wolfSSL cmake messages found"); +#endif + #ifndef WOLFSSL_MUTEX_INITIALIZER if (inits_count_mutex_valid == 0) { #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS @@ -11426,8 +11447,10 @@ const char *wolfSSL_get0_peername(WOLFSSL *ssl) { return (const char *)ssl->buffers.domainName.buffer; else if (ssl->session && ssl->session->peer) return ssl->session->peer->subjectCN; +#ifdef KEEP_PEER_CERT else if (ssl->peerCert.subjectCN[0]) return ssl->peerCert.subjectCN; +#endif else { ssl->error = NO_PEER_CERT; return NULL; @@ -12144,7 +12167,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) #endif /* !NO_BIO */ #endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) +#ifndef WOLFSSL_NO_CA_NAMES void wolfSSL_CTX_set_client_CA_list(WOLFSSL_CTX* ctx, WOLF_STACK_OF(WOLFSSL_X509_NAME)* names) { @@ -12165,8 +12188,9 @@ int wolfSSL_set_compression(WOLFSSL* ssl) ssl->client_ca_names = names; } } +#endif - #ifdef OPENSSL_EXTRA +#ifdef OPENSSL_EXTRA /* registers client cert callback, called during handshake if server requests client auth but user has not loaded client cert/key */ void wolfSSL_CTX_set_client_cert_cb(WOLFSSL_CTX *ctx, client_cert_cb cb) @@ -12378,9 +12402,7 @@ int wolfSSL_set_compression(WOLFSSL* ssl) } return ret; } - #endif /* OPENSSL_EXTRA */ - -#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || HAVE_WEBSERVER */ +#endif /* OPENSSL_EXTRA */ #ifndef WOLFSSL_NO_CA_NAMES WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list( @@ -12798,6 +12820,13 @@ int wolfSSL_set_compression(WOLFSSL* ssl) if (ssl == NULL) return 0; +#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_CLIENT) + if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls + && IsAtLeastTLSv1_3(ssl->version)) { + return ssl->options.serverState == SERVER_FINISHED_ACKED; + } +#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT */ + /* Can't use ssl->options.connectState and ssl->options.acceptState * because they differ in meaning for TLS <=1.2 and 1.3 */ if (ssl->options.handShakeState == HANDSHAKE_DONE) @@ -13538,10 +13567,12 @@ static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver) } switch (ver) { +#ifndef NO_TLS +#ifndef NO_OLD_TLS case SSL2_VERSION: WOLFSSL_MSG("wolfSSL does not support SSLv2"); return WOLFSSL_FAILURE; -#ifndef NO_TLS +#endif case SSL3_VERSION: wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1); FALL_THROUGH; @@ -13596,9 +13627,6 @@ static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver) } /* Update the method */ switch (ver) { - case SSL2_VERSION: - WOLFSSL_MSG("wolfSSL does not support SSLv2"); - return WOLFSSL_FAILURE; #ifndef NO_TLS case SSL3_VERSION: ctx->method->version.minor = SSLv3_MINOR; @@ -14608,7 +14636,7 @@ WOLF_STACK_OF(WOLFSSL_X509)* wolfSSL_set_peer_cert_chain(WOLFSSL* ssl) return sk; } - +#ifdef KEEP_PEER_CERT /** * Implemented in a similar way that ngx_ssl_ocsp_validate does it when * SSL_get0_verified_chain is not available. @@ -14669,6 +14697,7 @@ WOLF_STACK_OF(WOLFSSL_X509) *wolfSSL_get0_verified_chain(const WOLFSSL *ssl) wolfSSL_X509_STORE_CTX_free(storeCtx); return chain; } +#endif /* KEEP_PEER_CERT */ #endif /* SESSION_CERTS && OPENSSL_EXTRA */ #ifndef NO_CERTS @@ -15585,6 +15614,10 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) return "ML_KEM_512"; case WOLFSSL_P256_ML_KEM_512: return "P256_ML_KEM_512"; +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + case WOLFSSL_P256_ML_KEM_512_OLD: + return "P256_ML_KEM_512_OLD"; +#endif #ifdef HAVE_CURVE25519 case WOLFSSL_X25519_ML_KEM_512: return "X25519_ML_KEM_512"; @@ -15595,6 +15628,10 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) return "ML_KEM_768"; case WOLFSSL_P384_ML_KEM_768: return "P384_ML_KEM_768"; +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + case WOLFSSL_P384_ML_KEM_768_OLD: + return "P384_ML_KEM_768_OLD"; +#endif case WOLFSSL_P256_ML_KEM_768: return "P256_ML_KEM_768"; #ifdef HAVE_CURVE25519 @@ -15611,6 +15648,10 @@ const char* wolfSSL_get_curve_name(WOLFSSL* ssl) return "ML_KEM_1024"; case WOLFSSL_P521_ML_KEM_1024: return "P521_ML_KEM_1024"; +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + case WOLFSSL_P521_ML_KEM_1024_OLD: + return "P521_ML_KEM_1024_OLD"; +#endif case WOLFSSL_P384_ML_KEM_1024: return "P384_ML_KEM_1024"; #endif @@ -16498,6 +16539,45 @@ int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der) return wolfSSL_EVP_PKEY_get_der(key, der); } +int wolfSSL_i2d_PrivateKey_bio(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key) +{ + int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE); + int derSz = 0; + byte* der = NULL; + + if (bio == NULL || key == NULL) { + return WOLFSSL_FAILURE; + } + + derSz = wolfSSL_i2d_PrivateKey(key, NULL); + if (derSz <= 0) { + WOLFSSL_MSG("wolfSSL_i2d_PrivateKey (for getting size) failed"); + return WOLFSSL_FAILURE; + } + + der = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (!der) { + WOLFSSL_MSG("malloc failed"); + return WOLFSSL_FAILURE; + } + + derSz = wolfSSL_i2d_PrivateKey(key, &der); + if (derSz <= 0) { + WOLFSSL_MSG("wolfSSL_i2d_PrivateKey failed"); + goto cleanup; + } + + if (wolfSSL_BIO_write(bio, der, derSz) != derSz) { + goto cleanup; + } + + ret = WOLFSSL_SUCCESS; + +cleanup: + XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return ret; +} + int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY *key, unsigned char **der) { #if !defined(NO_RSA) || defined(HAVE_ECC) @@ -18367,9 +18447,8 @@ int wolfSSL_sk_SSL_COMP_num(WOLF_STACK_OF(WOLFSSL_COMP)* sk) #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ -#ifdef OPENSSL_EXTRA - -#if defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM) +#if defined(OPENSSL_EXTRA) && defined(KEEP_PEER_CERT) && \ + defined(HAVE_EX_DATA) && !defined(NO_FILESYSTEM) int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) { int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR); @@ -18440,14 +18519,13 @@ int wolfSSL_cmp_peer_cert_to_file(WOLFSSL* ssl, const char *fname) return ret; } #endif -#endif /* OPENSSL_EXTRA */ #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #ifndef NO_CERTS /* oidCertExtType */ - { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType, "basicConstraints", - "X509v3 Basic Constraints"}, + { WC_NID_basic_constraints, BASIC_CA_OID, oidCertExtType, + "basicConstraints", "X509v3 Basic Constraints"}, { WC_NID_subject_alt_name, ALT_NAMES_OID, oidCertExtType, "subjectAltName", "X509v3 Subject Alternative Name"}, { WC_NID_crl_distribution_points, CRL_DIST_OID, oidCertExtType, @@ -18493,40 +18571,48 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { "OCSPSigning", "OCSP Signing"}, /* oidCertNameType */ - { WC_NID_commonName, WC_NID_commonName, oidCertNameType, "CN", "commonName"}, + { WC_NID_commonName, WC_NAME_COMMON_NAME_OID, oidCertNameType, + "CN", "commonName"}, #if !defined(WOLFSSL_CERT_REQ) - { WC_NID_surname, WC_NID_surname, oidCertNameType, "SN", "surname"}, + { WC_NID_surname, WC_NAME_SURNAME_OID, oidCertNameType, "SN", "surname"}, #endif - { WC_NID_serialNumber, WC_NID_serialNumber, oidCertNameType, "serialNumber", - "serialNumber"}, + { WC_NID_serialNumber, WC_NAME_SERIAL_NUMBER_OID, oidCertNameType, + "serialNumber", "serialNumber"}, { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userid"}, - { WC_NID_countryName, WC_NID_countryName, oidCertNameType, "C", "countryName"}, - { WC_NID_localityName, WC_NID_localityName, oidCertNameType, "L", "localityName"}, - { WC_NID_stateOrProvinceName, WC_NID_stateOrProvinceName, oidCertNameType, "ST", - "stateOrProvinceName"}, - { WC_NID_streetAddress, WC_NID_streetAddress, oidCertNameType, "street", - "streetAddress"}, - { WC_NID_organizationName, WC_NID_organizationName, oidCertNameType, "O", - "organizationName"}, - { WC_NID_organizationalUnitName, WC_NID_organizationalUnitName, oidCertNameType, - "OU", "organizationalUnitName"}, - { WC_NID_emailAddress, WC_NID_emailAddress, oidCertNameType, "emailAddress", - "emailAddress"}, - { WC_NID_domainComponent, WC_NID_domainComponent, oidCertNameType, "DC", - "domainComponent"}, - { WC_NID_rfc822Mailbox, WC_NID_rfc822Mailbox, oidCertNameType, "rfc822Mailbox", - "rfc822Mailbox"}, - { WC_NID_favouriteDrink, WC_NID_favouriteDrink, oidCertNameType, "favouriteDrink", - "favouriteDrink"}, - { WC_NID_businessCategory, WC_NID_businessCategory, oidCertNameType, + { WC_NID_countryName, WC_NAME_COUNTRY_NAME_OID, oidCertNameType, + "C", "countryName"}, + { WC_NID_localityName, WC_NAME_LOCALITY_NAME_OID, oidCertNameType, + "L", "localityName"}, + { WC_NID_stateOrProvinceName, WC_NAME_STATE_NAME_OID, oidCertNameType, + "ST", "stateOrProvinceName"}, + { WC_NID_streetAddress, WC_NAME_STREET_ADDRESS_OID, oidCertNameType, + "street", "streetAddress"}, + { WC_NID_organizationName, WC_NAME_ORGANIZATION_NAME_OID, oidCertNameType, + "O", "organizationName"}, + { WC_NID_organizationalUnitName, WC_NAME_ORGANIZATION_UNIT_NAME_OID, + oidCertNameType, "OU", "organizationalUnitName"}, + { WC_NID_title, WC_NAME_TITLE_OID, oidCertNameType, "title", "title"}, + { WC_NID_description, WC_NAME_DESCRIPTION_OID, oidCertNameType, + "description", "description"}, + { WC_NID_emailAddress, WC_NAME_EMAIL_ADDRESS_OID, oidCertNameType, + "emailAddress", "emailAddress"}, + { WC_NID_domainComponent, WC_NAME_DOMAIN_COMPONENT_OID, oidCertNameType, + "DC", "domainComponent"}, + { WC_NID_rfc822Mailbox, WC_NAME_RFC822_MAILBOX_OID, oidCertNameType, + "rfc822Mailbox", "rfc822Mailbox"}, + { WC_NID_favouriteDrink, WC_NAME_FAVOURITE_DRINK_OID, oidCertNameType, + "favouriteDrink", "favouriteDrink"}, + { WC_NID_businessCategory, WC_NAME_BUSINESS_CATEGORY_OID, oidCertNameType, "businessCategory", "businessCategory"}, - { WC_NID_jurisdictionCountryName, WC_NID_jurisdictionCountryName, oidCertNameType, - "jurisdictionC", "jurisdictionCountryName"}, - { WC_NID_jurisdictionStateOrProvinceName, WC_NID_jurisdictionStateOrProvinceName, + { WC_NID_jurisdictionCountryName, WC_NAME_JURIS_COUNTRY_OID, + oidCertNameType, "jurisdictionC", "jurisdictionCountryName"}, + { WC_NID_jurisdictionStateOrProvinceName, WC_NAME_JURIS_STATE_PROV_OID, oidCertNameType, "jurisdictionST", "jurisdictionStateOrProvinceName"}, - { WC_NID_postalCode, WC_NID_postalCode, oidCertNameType, "postalCode", + { WC_NID_postalCode, WC_NAME_POSTAL_CODE_OID, oidCertNameType, "postalCode", "postalCode"}, - { WC_NID_userId, WC_NID_userId, oidCertNameType, "UID", "userId"}, + { WC_NID_userId, WC_NAME_USER_ID_OID, oidCertNameType, "UID", "userId"}, + { WC_NID_netscape_cert_type, NETSCAPE_CT_OID, oidCertNameType, + "nsCertType", "Netscape Cert Type"}, #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) { WC_NID_pkcs9_challengePassword, CHALLENGE_PASSWORD_OID, @@ -18535,12 +18621,12 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { oidCsrAttrType, "contentType", "contentType" }, { WC_NID_pkcs9_unstructuredName, UNSTRUCTURED_NAME_OID, oidCsrAttrType, "unstructuredName", "unstructuredName" }, - { WC_NID_name, NAME_OID, oidCsrAttrType, "name", "name" }, + { WC_NID_name, WC_NAME_NAME_OID, oidCsrAttrType, "name", "name" }, { WC_NID_surname, SURNAME_OID, oidCsrAttrType, "surname", "surname" }, - { WC_NID_givenName, GIVEN_NAME_OID, + { WC_NID_givenName, WC_NAME_GIVEN_NAME_OID, oidCsrAttrType, "givenName", "givenName" }, - { WC_NID_initials, INITIALS_OID, + { WC_NID_initials, WC_NAME_INITIALIS_OID, oidCsrAttrType, "initials", "initials" }, { WC_NID_dnQualifier, DNQUALIFIER_OID, oidCsrAttrType, "dnQualifer", "dnQualifier" }, @@ -18592,7 +18678,8 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { /* oidSigType */ #ifndef NO_DSA #ifndef NO_SHA - { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, "DSA-SHA1", "dsaWithSHA1"}, + { WC_NID_dsaWithSHA1, CTC_SHAwDSA, oidSigType, + "DSA-SHA1", "dsaWithSHA1"}, { WC_NID_dsa_with_SHA256, CTC_SHA256wDSA, oidSigType, "dsa_with_SHA256", "dsa_with_SHA256"}, #endif @@ -18611,20 +18698,20 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { "sha1WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA224 - { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, "RSA-SHA224", - "sha224WithRSAEncryption"}, + { WC_NID_sha224WithRSAEncryption, CTC_SHA224wRSA, oidSigType, + "RSA-SHA224", "sha224WithRSAEncryption"}, #endif #ifndef NO_SHA256 - { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, "RSA-SHA256", - "sha256WithRSAEncryption"}, + { WC_NID_sha256WithRSAEncryption, CTC_SHA256wRSA, oidSigType, + "RSA-SHA256", "sha256WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA384 - { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, "RSA-SHA384", - "sha384WithRSAEncryption"}, + { WC_NID_sha384WithRSAEncryption, CTC_SHA384wRSA, oidSigType, + "RSA-SHA384", "sha384WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA512 - { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, "RSA-SHA512", - "sha512WithRSAEncryption"}, + { WC_NID_sha512WithRSAEncryption, CTC_SHA512wRSA, oidSigType, + "RSA-SHA512", "sha512WithRSAEncryption"}, #endif #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 @@ -18645,7 +18732,8 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #endif #endif #ifdef WC_RSA_PSS - { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType, "RSASSA-PSS", "rsassaPss" }, + { WC_NID_rsassaPss, CTC_RSASSAPSS, oidSigType, + "RSASSA-PSS", "rsassaPss" }, #endif #endif /* NO_RSA */ #ifdef HAVE_ECC @@ -18739,22 +18827,22 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { /* oidCurveType */ #ifdef HAVE_ECC - { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, "prime192v1", - "prime192v1"}, - { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, "prime192v2", - "prime192v2"}, - { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, "prime192v3", - "prime192v3"}, - - { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, "prime239v1", - "prime239v1"}, - { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, "prime239v2", - "prime239v2"}, - { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, "prime239v3", - "prime239v3"}, - - { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, "prime256v1", - "prime256v1"}, + { WC_NID_X9_62_prime192v1, ECC_SECP192R1_OID, oidCurveType, + "prime192v1", "prime192v1"}, + { WC_NID_X9_62_prime192v2, ECC_PRIME192V2_OID, oidCurveType, + "prime192v2", "prime192v2"}, + { WC_NID_X9_62_prime192v3, ECC_PRIME192V3_OID, oidCurveType, + "prime192v3", "prime192v3"}, + + { WC_NID_X9_62_prime239v1, ECC_PRIME239V1_OID, oidCurveType, + "prime239v1", "prime239v1"}, + { WC_NID_X9_62_prime239v2, ECC_PRIME239V2_OID, oidCurveType, + "prime239v2", "prime239v2"}, + { WC_NID_X9_62_prime239v3, ECC_PRIME239V3_OID, oidCurveType, + "prime239v3", "prime239v3"}, + + { WC_NID_X9_62_prime256v1, ECC_SECP256R1_OID, oidCurveType, + "prime256v1", "prime256v1"}, { WC_NID_secp112r1, ECC_SECP112R1_OID, oidCurveType, "secp112r1", "secp112r1"}, @@ -18896,7 +18984,7 @@ const WOLFSSL_ObjectInfo wolfssl_object_info[] = { #endif #if defined(WOLFSSL_APACHE_HTTPD) /* "1.3.6.1.5.5.7.8.7" */ - { WC_NID_id_on_dnsSRV, WC_NID_id_on_dnsSRV, oidCertNameType, + { WC_NID_id_on_dnsSRV, WOLFSSL_DNS_SRV_SUM, oidCertNameType, WOLFSSL_SN_DNS_SRV, WOLFSSL_LN_DNS_SRV }, /* "1.3.6.1.4.1.311.20.2.3" */ @@ -20538,6 +20626,8 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) unsigned int sum = 0; unsigned int outSz = MAX_OID_SZ; unsigned char out[MAX_OID_SZ]; + + XMEMSET(out, 0, sizeof(out)); #endif WOLFSSL_ENTER("wolfSSL_OBJ_txt2nid"); @@ -20550,9 +20640,7 @@ void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl) ret = EncodePolicyOID(out, &outSz, s, NULL); if (ret == 0) { /* sum OID */ - for (i = 0; i < outSz; i++) { - sum += out[i]; - } + sum = wc_oid_sum(out, outSz); } #endif /* WOLFSSL_CERT_EXT */ @@ -23149,9 +23237,12 @@ const WOLF_EC_NIST_NAME kNistCurves[] = { {CURVE_NAME("K-192"), WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1}, {CURVE_NAME("K-224"), WC_NID_secp224k1, WOLFSSL_ECC_SECP224R1}, {CURVE_NAME("K-256"), WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1}, - {CURVE_NAME("B-256"), WC_NID_brainpoolP256r1, WOLFSSL_ECC_BRAINPOOLP256R1}, - {CURVE_NAME("B-384"), WC_NID_brainpoolP384r1, WOLFSSL_ECC_BRAINPOOLP384R1}, - {CURVE_NAME("B-512"), WC_NID_brainpoolP512r1, WOLFSSL_ECC_BRAINPOOLP512R1}, + {CURVE_NAME("B-256"), WC_NID_brainpoolP256r1, + WOLFSSL_ECC_BRAINPOOLP256R1}, + {CURVE_NAME("B-384"), WC_NID_brainpoolP384r1, + WOLFSSL_ECC_BRAINPOOLP384R1}, + {CURVE_NAME("B-512"), WC_NID_brainpoolP512r1, + WOLFSSL_ECC_BRAINPOOLP512R1}, #endif #ifdef HAVE_CURVE25519 {CURVE_NAME("X25519"), WC_NID_X25519, WOLFSSL_ECC_X25519}, @@ -23535,12 +23626,13 @@ int wolfSSL_CTX_set_alpn_protos(WOLFSSL_CTX *ctx, const unsigned char *p, int wolfSSL_set_alpn_protos(WOLFSSL* ssl, const unsigned char* p, unsigned int p_len) { - WOLFSSL_BIO* bio; char* pt = NULL; - + unsigned int ptIdx; unsigned int sz; unsigned int idx = 0; int alpn_opt = WOLFSSL_ALPN_CONTINUE_ON_MISMATCH; + int ret; + WOLFSSL_ENTER("wolfSSL_set_alpn_protos"); if (ssl == NULL || p_len <= 1) { @@ -23554,8 +23646,9 @@ int wolfSSL_set_alpn_protos(WOLFSSL* ssl, #endif } - bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem()); - if (bio == NULL) { + /* Replacing leading number with trailing ',' and adding '\0'. */ + pt = (char*)XMALLOC(p_len + 1, ssl->heap, DYNAMIC_TYPE_OPENSSL); + if (pt == NULL) { #if defined(WOLFSSL_ERROR_CODE_OPENSSL) /* 0 on success in OpenSSL, non-0 on failure in OpenSSL * the function reverses the return value convention. @@ -23566,6 +23659,7 @@ int wolfSSL_set_alpn_protos(WOLFSSL* ssl, #endif } + ptIdx = 0; /* convert into comma separated list */ while (idx < p_len - 1) { unsigned int i; @@ -23573,7 +23667,7 @@ int wolfSSL_set_alpn_protos(WOLFSSL* ssl, sz = p[idx++]; if (idx + sz > p_len) { WOLFSSL_MSG("Bad list format"); - wolfSSL_BIO_free(bio); + XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL); #if defined(WOLFSSL_ERROR_CODE_OPENSSL) /* 0 on success in OpenSSL, non-0 on failure in OpenSSL * the function reverses the return value convention. @@ -23585,27 +23679,30 @@ int wolfSSL_set_alpn_protos(WOLFSSL* ssl, } if (sz > 0) { for (i = 0; i < sz; i++) { - wolfSSL_BIO_write(bio, &p[idx++], 1); + pt[ptIdx++] = p[idx++]; + } + if (idx < p_len - 1) { + pt[ptIdx++] = ','; } - if (idx < p_len - 1) - wolfSSL_BIO_write(bio, ",", 1); } } - wolfSSL_BIO_write(bio, "\0", 1); + pt[ptIdx++] = '\0'; /* clears out all current ALPN extensions set */ TLSX_Remove(&ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL, ssl->heap); - if ((sz = (unsigned int)wolfSSL_BIO_get_mem_data(bio, &pt)) > 0) { - wolfSSL_UseALPN(ssl, pt, sz, (byte) alpn_opt); - } - wolfSSL_BIO_free(bio); + ret = wolfSSL_UseALPN(ssl, pt, ptIdx, (byte)alpn_opt); + XFREE(pt, ssl->heap, DYNAMIC_TYPE_OPENSSL); #if defined(WOLFSSL_ERROR_CODE_OPENSSL) /* 0 on success in OpenSSL, non-0 on failure in OpenSSL * the function reverses the return value convention. */ + if (ret != WOLFSSL_SUCCESS) + return 1; return 0; #else + if (ret != WOLFSSL_SUCCESS) + return WOLFSSL_FAILURE; return WOLFSSL_SUCCESS; #endif } @@ -24600,8 +24697,13 @@ int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr) if (der != NULL) { curve25519_key* key = (curve25519_key*)keyPtr; WOLFSSL_MSG("Using static X25519 key"); - ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key, - der->length); + + #ifdef WOLFSSL_CURVE25519_BLINDING + ret = wc_curve25519_set_rng(key, ssl->rng); + if (ret == 0) + #endif + ret = wc_Curve25519PrivateKeyDecode(der->buffer, &idx, key, + der->length); } break; #endif @@ -25458,6 +25560,13 @@ static int wolfSSL_RAND_InitMutex(void) #ifdef OPENSSL_EXTRA +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \ + ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST)) +/* In older FIPS bundles add check for reseed here since it does not exist in + * the older random.c certified files. */ +static pid_t currentRandPid = 0; +#endif + /* Checks if the global RNG has been created. If not then one is created. * * Returns WOLFSSL_SUCCESS when no error is encountered. @@ -25470,6 +25579,12 @@ int wolfSSL_RAND_Init(void) if (initGlobalRNG == 0) { ret = wc_InitRng(&globalRNG); if (ret == 0) { + #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \ + ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \ + defined(HAVE_SELFTEST)) + + currentRandPid = getpid(); + #endif initGlobalRNG = 1; ret = WOLFSSL_SUCCESS; } @@ -25904,8 +26019,8 @@ int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num) return ret; } -/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise - * WOLFSSL_FAILURE */ +/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0 + * on failure */ int wolfSSL_RAND_bytes(unsigned char* buf, int num) { int ret = 0; @@ -25947,6 +26062,27 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num) * have the lock. */ if (initGlobalRNG) { + #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \ + ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \ + defined(HAVE_SELFTEST)) + pid_t p; + + p = getpid(); + if (p != currentRandPid) { + wc_UnLockMutex(&globalRNGMutex); + if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Issue with check pid and reseed"); + ret = WOLFSSL_FAILURE; + } + + /* reclaim lock after wolfSSL_RAND_poll */ + if (wc_LockMutex(&globalRNGMutex) != 0) { + WOLFSSL_MSG("Bad Lock Mutex rng"); + return ret; + } + currentRandPid = p; + } + #endif rng = &globalRNG; used_global = 1; } @@ -26017,11 +26153,35 @@ int wolfSSL_RAND_poll(void) return WOLFSSL_FAILURE; } ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz); - if (ret != 0){ + if (ret != 0) { WOLFSSL_MSG("Bad wc_RNG_GenerateBlock"); ret = WOLFSSL_FAILURE; - }else + } + else { +#ifdef HAVE_HASHDRBG + if (wc_LockMutex(&globalRNGMutex) != 0) { + WOLFSSL_MSG("Bad Lock Mutex rng"); + return ret; + } + + ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz); + if (ret != 0) { + WOLFSSL_MSG("Error reseeding DRBG"); + ret = WOLFSSL_FAILURE; + } + else { + ret = WOLFSSL_SUCCESS; + } + wc_UnLockMutex(&globalRNGMutex); +#elif defined(HAVE_INTEL_RDRAND) + WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without " + "HAVE_HASHDRBG"); ret = WOLFSSL_SUCCESS; +#else + WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set"); + ret = WOLFSSL_FAILURE; +#endif + } return ret; } @@ -26659,4 +26819,3 @@ void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data) #endif /* !WOLFCRYPT_ONLY */ - diff --git a/src/src/ssl_asn1.c b/src/src/ssl_asn1.c index 535c672..f2ffbc6 100644 --- a/src/src/ssl_asn1.c +++ b/src/src/ssl_asn1.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/src/ssl_bn.c b/src/src/ssl_bn.c index 0d947a8..139684b 100644 --- a/src/src/ssl_bn.c +++ b/src/src/ssl_bn.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1158,6 +1158,62 @@ int wolfSSL_BN_cmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b) return ret; } +/* Same as above, but compare absolute value. */ +int wolfSSL_BN_ucmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b) +{ + int ret = 0; + int bIsNull; + + WOLFSSL_ENTER("wolfSSL_BN_ucmp"); + + /* Must know whether b is NULL. */ + bIsNull = BN_IS_NULL(b); + /* Check whether a is NULL. */ + if (BN_IS_NULL(a)) { + if (bIsNull) { + /* NULL equals NULL. */ + ret = 0; + } + else { + ret = -1; /* NULL less than not NULL. */ + } + } + else if (bIsNull) { + /* not NULL greater than NULL. */ + ret = 1; + } + else { + /* Neither are NULL; copy to new instances and switch to positive if + * required, compare, and then free. Must copy because there is + * possibility of switch to positive but they are declared const. + * wolfssl_bn_set_neg() only returns -1 if the bn is NULL, but we + * already check that so we can ignore the return code. Note for + * wolfSSL_BN_is_negative if n=1 then set to positive. */ + WOLFSSL_BIGNUM* abs_a = wolfSSL_BN_dup(a); + WOLFSSL_BIGNUM* abs_b = wolfSSL_BN_dup(b); + + if (abs_a == NULL || abs_b == NULL) { + WOLFSSL_MSG("wolfSSL_BN_dup failed"); + wolfSSL_BN_free(abs_a); + wolfSSL_BN_free(abs_b); + return WOLFSSL_FATAL_ERROR; + } + + if (wolfSSL_BN_is_negative(abs_a)) { + wolfssl_bn_set_neg(abs_a, 1); + } + + if (wolfSSL_BN_is_negative(abs_b)) { + wolfssl_bn_set_neg(abs_b, 1); + } + + ret = wolfSSL_BN_cmp(abs_a, abs_b); + wolfSSL_BN_free(abs_a); + wolfSSL_BN_free(abs_b); + } + return ret; +} + /* Indicates whether a big number is the value 0. * * Return compliant with OpenSSL. diff --git a/src/src/ssl_certman.c b/src/src/ssl_certman.c index df88acd..286831b 100644 --- a/src/src/ssl_certman.c +++ b/src/src/ssl_certman.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1525,7 +1525,7 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) WOLFSSL_ENTER("CM_MemRestoreCertCache"); /* Check memory available is bigger than cache header. */ - if (current > end) { + if ((sz < (int)sizeof(CertCacheHeader)) || (current > end)) { WOLFSSL_MSG("Cert Cache Memory buffer too small"); ret = BUFFER_E; } diff --git a/src/src/ssl_crypto.c b/src/src/ssl_crypto.c index 4744304..6ba73ab 100644 --- a/src/src/ssl_crypto.c +++ b/src/src/ssl_crypto.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1472,56 +1472,136 @@ int wolfSSL_HmacCopy(Hmac* dst, Hmac* src) #ifndef NO_MD5 case WC_MD5: rc = wc_Md5Copy(&src->hash.md5, &dst->hash.md5); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Md5Copy(&src->i_hash.md5, &dst->i_hash.md5); + } + if (rc == 0) { + rc = wc_Md5Copy(&src->o_hash.md5, &dst->o_hash.md5); + } + #endif break; #endif /* !NO_MD5 */ #ifndef NO_SHA case WC_SHA: rc = wc_ShaCopy(&src->hash.sha, &dst->hash.sha); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_ShaCopy(&src->i_hash.sha, &dst->i_hash.sha); + } + if (rc == 0) { + rc = wc_ShaCopy(&src->o_hash.sha, &dst->o_hash.sha); + } + #endif break; #endif /* !NO_SHA */ #ifdef WOLFSSL_SHA224 case WC_SHA224: rc = wc_Sha224Copy(&src->hash.sha224, &dst->hash.sha224); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha224Copy(&src->i_hash.sha224, &dst->i_hash.sha224); + } + if (rc == 0) { + rc = wc_Sha224Copy(&src->o_hash.sha224, &dst->o_hash.sha224); + } + #endif break; #endif /* WOLFSSL_SHA224 */ #ifndef NO_SHA256 case WC_SHA256: rc = wc_Sha256Copy(&src->hash.sha256, &dst->hash.sha256); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha256Copy(&src->i_hash.sha256, &dst->i_hash.sha256); + } + if (rc == 0) { + rc = wc_Sha256Copy(&src->o_hash.sha256, &dst->o_hash.sha256); + } + #endif break; #endif /* !NO_SHA256 */ #ifdef WOLFSSL_SHA384 case WC_SHA384: rc = wc_Sha384Copy(&src->hash.sha384, &dst->hash.sha384); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha384Copy(&src->i_hash.sha384, &dst->i_hash.sha384); + } + if (rc == 0) { + rc = wc_Sha384Copy(&src->o_hash.sha384, &dst->o_hash.sha384); + } + #endif break; #endif /* WOLFSSL_SHA384 */ #ifdef WOLFSSL_SHA512 case WC_SHA512: rc = wc_Sha512Copy(&src->hash.sha512, &dst->hash.sha512); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha512Copy(&src->i_hash.sha512, &dst->i_hash.sha512); + } + if (rc == 0) { + rc = wc_Sha512Copy(&src->o_hash.sha512, &dst->o_hash.sha512); + } + #endif break; #endif /* WOLFSSL_SHA512 */ #ifdef WOLFSSL_SHA3 #ifndef WOLFSSL_NOSHA3_224 case WC_SHA3_224: rc = wc_Sha3_224_Copy(&src->hash.sha3, &dst->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha3_224_Copy(&src->i_hash.sha3, &dst->i_hash.sha3); + } + if (rc == 0) { + rc = wc_Sha3_224_Copy(&src->o_hash.sha3, &dst->o_hash.sha3); + } + #endif break; #endif /* WOLFSSL_NO_SHA3_224 */ #ifndef WOLFSSL_NOSHA3_256 case WC_SHA3_256: rc = wc_Sha3_256_Copy(&src->hash.sha3, &dst->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha3_256_Copy(&src->i_hash.sha3, &dst->i_hash.sha3); + } + if (rc == 0) { + rc = wc_Sha3_256_Copy(&src->o_hash.sha3, &dst->o_hash.sha3); + } + #endif break; #endif /* WOLFSSL_NO_SHA3_256 */ #ifndef WOLFSSL_NOSHA3_384 case WC_SHA3_384: rc = wc_Sha3_384_Copy(&src->hash.sha3, &dst->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha3_384_Copy(&src->i_hash.sha3, &dst->i_hash.sha3); + } + if (rc == 0) { + rc = wc_Sha3_384_Copy(&src->o_hash.sha3, &dst->o_hash.sha3); + } + #endif break; #endif /* WOLFSSL_NO_SHA3_384 */ #ifndef WOLFSSL_NOSHA3_512 case WC_SHA3_512: rc = wc_Sha3_512_Copy(&src->hash.sha3, &dst->hash.sha3); + #ifdef WOLFSSL_HMAC_COPY_HASH + if (rc == 0) { + rc = wc_Sha3_512_Copy(&src->i_hash.sha3, &dst->i_hash.sha3); + } + if (rc == 0) { + rc = wc_Sha3_512_Copy(&src->o_hash.sha3, &dst->o_hash.sha3); + } + #endif break; #endif /* WOLFSSL_NO_SHA3_512 */ #endif /* WOLFSSL_SHA3 */ @@ -1823,13 +1903,24 @@ int wolfSSL_HMAC_Init(WOLFSSL_HMAC_CTX* ctx, const void* key, int keylen, WC_HMAC_BLOCK_SIZE); XMEMCPY((byte *)&ctx->hmac.opad, (byte *)&ctx->save_opad, WC_HMAC_BLOCK_SIZE); - /* Initialize the wolfSSL HMAC object. */ - rc = _HMAC_Init(&ctx->hmac, ctx->hmac.macType, heap); + #ifdef WOLFSSL_HMAC_COPY_HASH + rc = _HmacInitIOHashes(&ctx->hmac); if (rc != 0) { - WOLFSSL_MSG("hmac init error"); + WOLFSSL_MSG("hmac init i_hash/o_hash error"); WOLFSSL_ERROR(rc); ret = 0; } + if (ret == 1) + #endif + { + /* Initialize the wolfSSL HMAC object. */ + rc = _HMAC_Init(&ctx->hmac, ctx->hmac.macType, heap); + if (rc != 0) { + WOLFSSL_MSG("hmac init error"); + WOLFSSL_ERROR(rc); + ret = 0; + } + } } return ret; @@ -2149,8 +2240,17 @@ int wolfSSL_CMAC_Init(WOLFSSL_CMAC_CTX* ctx, const void *key, size_t keySz, ret = 0; } /* Only AES-CBC ciphers are supported. */ - if ((ret == 1) && (cipher != EVP_AES_128_CBC) && - (cipher != EVP_AES_192_CBC) && (cipher != EVP_AES_256_CBC)) { + if ((ret == 1) + #ifdef WOLFSSL_AES_128 + && (cipher != EVP_AES_128_CBC) + #endif + #ifdef WOLFSSL_AES_192 + && (cipher != EVP_AES_192_CBC) + #endif + #ifdef WOLFSSL_AES_256 + && (cipher != EVP_AES_256_CBC) + #endif + ) { WOLFSSL_MSG("wolfSSL_CMAC_Init: requested cipher is unsupported"); ret = 0; } diff --git a/src/src/ssl_load.c b/src/src/ssl_load.c index 24c8af1..d50fae9 100644 --- a/src/src/ssl_load.c +++ b/src/src/ssl_load.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -42,9 +42,14 @@ #endif #endif -#if defined(__APPLE__) && defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) +#if defined(__APPLE__) +#if defined(HAVE_SECURITY_SECTRUSTSETTINGS_H) #include -#endif +#endif /* HAVE_SECURITY_SECTRUSTSETTINGS_H */ +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION +#include +#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ +#endif /* __APPLE__ */ #endif /* WOLFSSL_SYS_CA_CERTS */ @@ -947,8 +952,8 @@ static int ProcessBufferTryDecodeDilithium(WOLFSSL_CTX* ctx, WOLFSSL* ssl, word32 idx; dilithium_key* key; int keyFormatTemp = 0; - int keyTypeTemp; - int keySizeTemp; + int keyTypeTemp = 0; + int keySizeTemp = 0; /* Allocate a Dilithium key to parse into. */ key = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap, @@ -2153,8 +2158,50 @@ static int ProcessBufferCertHandleDer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, /* CA certificate to verify with. */ if (type == CA_TYPE) { +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + /* TEST ONLY CODE: + * Store the DER encoding of the CA certificate so we can append it to + * the list of trusted CA certificates if the subsequent call to AddCA + * is successful */ + word32 derLen; + byte* derBuf; + if (ctx->doAppleNativeCertValidationFlag == 1) { + WOLFSSL_MSG("ANCV Test: copy DER CA cert"); + derLen = der->length; + derBuf = (byte*)XMALLOC(derLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (derBuf == NULL) { + return MEMORY_E; + } + XMEMCPY(derBuf, der->buffer, derLen); + } + else { + (void)derLen; + (void)derBuf; + } +#endif /* verify CA unless user set to no verify */ ret = AddCA(ctx->cm, &der, WOLFSSL_USER_CA, verify); + +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + /* TEST ONLY CODE: + * Append the DER encoded CA certificate to the list of trusted CA + * certificates so we can inject them at verification time */ + if (ret == 1 && ctx->doAppleNativeCertValidationFlag == 1) { + WOLFSSL_MSG("ANCV Test: Appending CA to cert list"); + ret = wolfSSL_TestAppleNativeCertValidation_AppendCA(ctx, derBuf, (int)derLen); + if (ret == WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ANCV Test: Clearing CA table"); + /* Clear the CA table so we can ensure they won't be used for + * verification */ + ret = wolfSSL_CertManagerUnloadCAs(ctx->cm); + if (ret == WOLFSSL_SUCCESS) { + ret = 0; + } + } + XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif /* !WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ + if (ret == 1) { ret = 0; } @@ -2352,11 +2399,13 @@ static int ProcessBufferResetSuites(WOLFSSL_CTX* ctx, WOLFSSL* ssl, int type) * @param [out] used Number of bytes consumed. * @param [in[ userChain Whether this certificate is for user's chain. * @param [in] verify How to verify certificate. + * @param [in] source_name Associated filename or other source ID. * @return 1 on success. * @return Less than 1 on failure. */ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, - int format, int type, WOLFSSL* ssl, long* used, int userChain, int verify) + int format, int type, WOLFSSL* ssl, long* used, int userChain, int verify, + const char *source_name) { DerBuffer* der = NULL; int ret = 0; @@ -2367,6 +2416,11 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, EncryptedInfo info[1]; #endif int algId = 0; +#ifdef WOLFSSL_DEBUG_CERTIFICATE_LOADS + long usedAtStart = used ? *used : 0L; +#else + (void)source_name; +#endif WOLFSSL_ENTER("ProcessBuffer"); @@ -2444,6 +2498,22 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, CLEAR_ASN_NO_PEM_HEADER_ERROR(pemErr); ret = 0; } +#ifdef WOLFSSL_DEBUG_CERTIFICATE_LOADS + if (ret < 0) { +#ifdef NO_ERROR_STRINGS + WOLFSSL_DEBUG_PRINTF( + "ERROR: ProcessUserChain: certificate from %s at offset %ld" + " rejected with code %d\n", + source_name, usedAtStart, ret); +#else + WOLFSSL_DEBUG_PRINTF( + "ERROR: ProcessUserChain: certificate from %s at offset %ld" + " rejected with code %d: %s\n", + source_name, usedAtStart, ret, + wolfSSL_ERR_reason_error_string(ret)); +#endif + } +#endif /* WOLFSSL_DEBUG_CERTIFICATE_LOADS */ } #ifdef WOLFSSL_SMALL_STACK @@ -2455,6 +2525,22 @@ int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, /* Process the different types of certificates. */ ret = ProcessBufferCertTypes(ctx, ssl, buff, sz, der, format, type, verify); +#ifdef WOLFSSL_DEBUG_CERTIFICATE_LOADS + if (ret < 0) { +#ifdef NO_ERROR_STRINGS + WOLFSSL_DEBUG_PRINTF( + "ERROR: ProcessBufferCertTypes: certificate from %s at" + " offset %ld rejected with code %d\n", + source_name, usedAtStart, ret); +#else + WOLFSSL_DEBUG_PRINTF( + "ERROR: ProcessBufferCertTypes: certificate from %s at" + " offset %ld rejected with code %d: %s\n", + source_name, usedAtStart, ret, + wolfSSL_ERR_reason_error_string(ret)); +#endif + } +#endif /* WOLFSSL_DEBUG_CERTIFICATE_LOADS */ } else { FreeDer(&der); @@ -2515,12 +2601,14 @@ static int ProcessChainBufferCRL(WOLFSSL_CTX* ctx, const unsigned char* buff, * @param [in] sz Size of data in buffer. * @param [in] type Type of data. * @param [in] verify How to verify certificate. + * @param [in] source_name Associated filename or other source ID. * @return 1 on success. * @return 0 on failure. * @return MEMORY_E when dynamic memory allocation fails. */ static int ProcessChainBuffer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, - const unsigned char* buff, long sz, int type, int verify) + const unsigned char* buff, long sz, int type, int verify, + const char *source_name) { int ret = 0; long used = 0; @@ -2529,11 +2617,11 @@ static int ProcessChainBuffer(WOLFSSL_CTX* ctx, WOLFSSL* ssl, WOLFSSL_MSG("Processing CA PEM file"); /* Keep processing file while no errors and data to parse. */ while ((ret >= 0) && (used < sz)) { - long consumed = 0; + long consumed = used; /* Process the buffer. */ ret = ProcessBuffer(ctx, buff + used, sz - used, WOLFSSL_FILETYPE_PEM, - type, ssl, &consumed, 0, verify); + type, ssl, &consumed, 0, verify, source_name); /* Memory allocation failure is fatal. */ if (ret == WC_NO_ERR_TRACE(MEMORY_E)) { gotOne = 0; @@ -2665,6 +2753,12 @@ int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, { /* Not a header that we support. */ WOLFSSL_MSG("Failed to detect certificate type"); +#ifdef WOLFSSL_DEBUG_CERTIFICATE_LOADS + WOLFSSL_DEBUG_PRINTF( + "ERROR: ProcessFile: Failed to detect certificate type" + " of \"%s\"\n", + fname); +#endif ret = WOLFSSL_BAD_CERTTYPE; } } @@ -2673,7 +2767,7 @@ int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, if (((type == CA_TYPE) || (type == TRUSTED_PEER_TYPE)) && (format == WOLFSSL_FILETYPE_PEM)) { ret = ProcessChainBuffer(ctx, ssl, content.buffer, sz, type, - verify); + verify, fname); } #ifdef HAVE_CRL else if (type == CRL_TYPE) { @@ -2690,18 +2784,18 @@ int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, long consumed = 0; ret = ProcessBuffer(ctx, content.buffer, sz, format, type, ssl, - &consumed, userChain, verify); + &consumed, userChain, verify, fname); if ((ret == 1) && (consumed < sz)) { ret = ProcessBuffer(ctx, content.buffer + consumed, sz - consumed, format, ALT_PRIVATEKEY_TYPE, ssl, NULL, 0, - verify); + verify, fname); } } #endif else { /* Load all other certificate types. */ ret = ProcessBuffer(ctx, content.buffer, sz, format, type, ssl, - NULL, userChain, verify); + NULL, userChain, verify, fname); } } @@ -2894,6 +2988,14 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, ret = 0; } +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + if (ret == 1) { + /* TEST ONLY CODE: force native cert validation on */ + WOLFSSL_MSG("ANCV Test: Loading system CA certs"); + wolfSSL_CTX_load_system_CA_certs(ctx); + } +#endif + if (ret == 1) { /* Get setting on how to verify certificates. */ verify = GET_VERIFY_SETTING_CTX(ctx); @@ -2906,19 +3008,19 @@ int wolfSSL_CTX_load_verify_locations_ex(WOLFSSL_CTX* ctx, const char* file, /* Load the PEM formatted CA file */ ret = ProcessFile(ctx, file, WOLFSSL_FILETYPE_PEM, CA_TYPE, NULL, 0, NULL, verify); - #ifndef NO_WOLFSSL_DIR +#ifndef NO_WOLFSSL_DIR if (ret == 1) { /* Include success in overall count. */ successCount++; } - #endif - #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) +#endif +#if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) /* Load CA as a trusted peer certificate. */ ret = wolfSSL_CTX_trust_peer_cert(ctx, file, WOLFSSL_FILETYPE_PEM); if (ret != 1) { WOLFSSL_MSG("wolfSSL_CTX_trust_peer_cert error"); } - #endif +#endif } } @@ -3030,7 +3132,8 @@ static int LoadSystemCaCertsWindows(WOLFSSL_CTX* ctx, byte* loaded) if (ProcessBuffer(ctx, certCtx->pbCertEncoded, certCtx->cbCertEncoded, WOLFSSL_FILETYPE_ASN1, CA_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)) == 1) { + GET_VERIFY_SETTING_CTX(ctx), + storeNames[i]) == 1) { /* * Set "loaded" as long as we've loaded one CA * cert. @@ -3105,7 +3208,8 @@ static int LoadSystemCaCertsMac(WOLFSSL_CTX* ctx, byte* loaded) if (ProcessBuffer(ctx, CFDataGetBytePtr(der), CFDataGetLength(der), WOLFSSL_FILETYPE_ASN1, CA_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)) == 1) { + GET_VERIFY_SETTING_CTX(ctx), + "MacOSX trustDomains") == 1) { /* * Set "loaded" as long as we've loaded one CA * cert. @@ -3369,6 +3473,11 @@ int wolfSSL_CTX_der_load_verify_locations(WOLFSSL_CTX* ctx, const char* file, ret = 0; } else { +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + /* TEST ONLY CODE: force native cert validation on */ + WOLFSSL_MSG("ANCV Test: loading system CA certs"); + wolfSSL_CTX_load_system_CA_certs(ctx); +#endif ret = ProcessFile(ctx, file, format, CA_TYPE, NULL, 0, NULL, GET_VERIFY_SETTING_CTX(ctx)); } @@ -3644,7 +3753,8 @@ int wolfSSL_use_certificate(WOLFSSL* ssl, WOLFSSL_X509* x509) /* Get DER encoded certificate data from X509 object. */ ret = ProcessBuffer(NULL, x509->derCert->buffer, x509->derCert->length, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, ssl, &idx, 0, - GET_VERIFY_SETTING_SSL(ssl)); + GET_VERIFY_SETTING_SSL(ssl), + "x509 buffer"); } /* Return 1 on success or 0 on failure. */ @@ -3676,7 +3786,8 @@ int wolfSSL_use_certificate_ASN1(WOLFSSL* ssl, const unsigned char* der, long idx = 0; ret = ProcessBuffer(NULL, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, - ssl, &idx, 0, GET_VERIFY_SETTING_SSL(ssl)); + ssl, &idx, 0, GET_VERIFY_SETTING_SSL(ssl), + "asn1 buffer"); } /* Return 1 on success or 0 on failure. */ @@ -3875,6 +3986,14 @@ int wolfSSL_CTX_load_verify_buffer_ex(WOLFSSL_CTX* ctx, const unsigned char* in, WOLFSSL_ENTER("wolfSSL_CTX_load_verify_buffer_ex"); +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + /* TEST ONLY CODE: force native cert validation on */ + if (ctx != NULL) { + WOLFSSL_MSG("ANCV Test: loading system CA certs"); + wolfSSL_CTX_load_system_CA_certs(ctx); + } +#endif + /* Get setting on how to verify certificates. */ verify = GET_VERIFY_SETTING_CTX(ctx); /* Overwrite setting when flag set. */ @@ -3884,12 +4003,13 @@ int wolfSSL_CTX_load_verify_buffer_ex(WOLFSSL_CTX* ctx, const unsigned char* in, /* When PEM, treat as certificate chain of CA certificates. */ if (format == WOLFSSL_FILETYPE_PEM) { - ret = ProcessChainBuffer(ctx, NULL, in, sz, CA_TYPE, verify); + ret = ProcessChainBuffer(ctx, NULL, in, sz, CA_TYPE, verify, + "PEM buffer"); } /* When DER, load the CA certificate. */ else { ret = ProcessBuffer(ctx, in, sz, format, CA_TYPE, NULL, NULL, - userChain, verify); + userChain, verify, "buffer"); } #if defined(WOLFSSL_TRUST_PEER_CERT) && defined(OPENSSL_COMPATIBLE_DEFAULTS) if (ret == 1) { @@ -3973,12 +4093,12 @@ int wolfSSL_CTX_trust_peer_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, /* When PEM, treat as certificate chain of trusted peer certificates. */ if (format == WOLFSSL_FILETYPE_PEM) { ret = ProcessChainBuffer(ctx, NULL, in, sz, TRUSTED_PEER_TYPE, - verify); + verify, "peer"); } /* When DER, load the trusted peer certificate. */ else { ret = ProcessBuffer(ctx, in, sz, format, TRUSTED_PEER_TYPE, NULL, - NULL, 0, verify); + NULL, 0, verify, "peer"); } } @@ -4004,7 +4124,7 @@ int wolfSSL_CTX_use_certificate_buffer(WOLFSSL_CTX* ctx, WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_buffer"); ret = ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 0, - GET_VERIFY_SETTING_CTX(ctx)); + GET_VERIFY_SETTING_CTX(ctx), "buffer"); WOLFSSL_LEAVE("wolfSSL_CTX_use_certificate_buffer", ret); return ret; @@ -4030,7 +4150,7 @@ int wolfSSL_CTX_use_PrivateKey_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, WOLFSSL_ENTER("wolfSSL_CTX_use_PrivateKey_buffer"); ret = ProcessBuffer(ctx, in, sz, format, PRIVATEKEY_TYPE, NULL, &consumed, - 0, GET_VERIFY_SETTING_CTX(ctx)); + 0, GET_VERIFY_SETTING_CTX(ctx), "key buffer"); #ifdef WOLFSSL_DUAL_ALG_CERTS if ((ret == 1) && (consumed < sz)) { /* When support for dual algorithm certificates is enabled, the @@ -4038,7 +4158,8 @@ int wolfSSL_CTX_use_PrivateKey_buffer(WOLFSSL_CTX* ctx, const unsigned char* in, * private key. Hence, we have to parse both of them. */ ret = ProcessBuffer(ctx, in + consumed, sz - consumed, format, - ALT_PRIVATEKEY_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + ALT_PRIVATEKEY_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx), + "key buffer"); } #endif @@ -4056,7 +4177,7 @@ int wolfSSL_CTX_use_AltPrivateKey_buffer(WOLFSSL_CTX* ctx, WOLFSSL_ENTER("wolfSSL_CTX_use_AltPrivateKey_buffer"); ret = ProcessBuffer(ctx, in, sz, format, ALT_PRIVATEKEY_TYPE, NULL, - NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + NULL, 0, GET_VERIFY_SETTING_CTX(ctx), "alt key buffer"); WOLFSSL_LEAVE("wolfSSL_CTX_use_AltPrivateKey_buffer", ret); return ret; @@ -4271,7 +4392,8 @@ static int wolfSSL_CTX_use_certificate_ex(WOLFSSL_CTX* ctx, } ret = ProcessBuffer(ctx, certData, certDataLen, certFormat, - CERT_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx)); + CERT_TYPE, NULL, NULL, 0, GET_VERIFY_SETTING_CTX(ctx), + label ? label : "cert buffer"); exit: XFREE(certData, ctx->heap, DYNAMIC_TYPE_CERT); @@ -4333,7 +4455,7 @@ int wolfSSL_CTX_use_certificate_chain_buffer_format(WOLFSSL_CTX* ctx, { WOLFSSL_ENTER("wolfSSL_CTX_use_certificate_chain_buffer_format"); return ProcessBuffer(ctx, in, sz, format, CERT_TYPE, NULL, NULL, 1, - GET_VERIFY_SETTING_CTX(ctx)); + GET_VERIFY_SETTING_CTX(ctx), "cert chain buffer"); } /* Load a PEM encoded certificate chain in a buffer into SSL context. @@ -4376,7 +4498,7 @@ int wolfSSL_use_certificate_buffer(WOLFSSL* ssl, const unsigned char* in, } else { ret = ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 0, - GET_VERIFY_SETTING_SSL(ssl)); + GET_VERIFY_SETTING_SSL(ssl), "cert buffer"); } return ret; @@ -4407,7 +4529,7 @@ int wolfSSL_use_PrivateKey_buffer(WOLFSSL* ssl, const unsigned char* in, } else { ret = ProcessBuffer(ssl->ctx, in, sz, format, PRIVATEKEY_TYPE, ssl, - &consumed, 0, GET_VERIFY_SETTING_SSL(ssl)); + &consumed, 0, GET_VERIFY_SETTING_SSL(ssl), "key buffer"); #ifdef WOLFSSL_DUAL_ALG_CERTS if ((ret == 1) && (consumed < sz)) { /* When support for dual algorithm certificates is enabled, the @@ -4415,7 +4537,8 @@ int wolfSSL_use_PrivateKey_buffer(WOLFSSL* ssl, const unsigned char* in, * private key. Hence, we have to parse both of them. */ ret = ProcessBuffer(ssl->ctx, in + consumed, sz - consumed, format, - ALT_PRIVATEKEY_TYPE, ssl, NULL, 0, GET_VERIFY_SETTING_SSL(ssl)); + ALT_PRIVATEKEY_TYPE, ssl, NULL, 0, GET_VERIFY_SETTING_SSL(ssl), + "key buffer"); } #endif } @@ -4431,7 +4554,7 @@ int wolfSSL_use_AltPrivateKey_buffer(WOLFSSL* ssl, const unsigned char* in, WOLFSSL_ENTER("wolfSSL_use_AltPrivateKey_buffer"); ret = ProcessBuffer(ssl->ctx, in, sz, format, ALT_PRIVATEKEY_TYPE, ssl, - NULL, 0, GET_VERIFY_SETTING_SSL(ssl)); + NULL, 0, GET_VERIFY_SETTING_SSL(ssl), "alt key buffer"); WOLFSSL_LEAVE("wolfSSL_use_AltPrivateKey_buffer", ret); return ret; @@ -4669,7 +4792,7 @@ int wolfSSL_use_certificate_chain_buffer_format(WOLFSSL* ssl, } else { ret = ProcessBuffer(ssl->ctx, in, sz, format, CERT_TYPE, ssl, NULL, 1, - GET_VERIFY_SETTING_SSL(ssl)); + GET_VERIFY_SETTING_SSL(ssl), "cert chain buffer"); } return ret; @@ -4826,7 +4949,7 @@ long wolfSSL_CTX_add_extra_chain_cert(WOLFSSL_CTX* ctx, WOLFSSL_X509* x509) /* Process buffer makes first certificate the leaf. */ ret = ProcessBuffer(ctx, der, derSz, WOLFSSL_FILETYPE_ASN1, CERT_TYPE, - NULL, NULL, 1, GET_VERIFY_SETTING_CTX(ctx)); + NULL, NULL, 1, GET_VERIFY_SETTING_CTX(ctx), "extra chain buffer"); if (ret != 1) { ret = 0; } @@ -5053,11 +5176,6 @@ int wolfSSL_add0_chain_cert(WOLFSSL* ssl, WOLFSSL_X509* x509) /* Push X509 object onto stack to be freed. */ ret = wolfSSL_sk_X509_push(ssl->ourCertChain, x509) > 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE; - if (ret != 1) { - /* Free it now on error. */ - wolfSSL_X509_free(x509); - x509 = NULL; - } } } return WS_RC(ret); diff --git a/src/src/ssl_misc.c b/src/src/ssl_misc.c index 56a71e8..4743ad0 100644 --- a/src/src/ssl_misc.c +++ b/src/src/ssl_misc.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -30,7 +30,6 @@ #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) #ifndef NO_BIO -#ifdef WOLFSSL_NO_FSEEK /* Amount of memory to allocate/add. */ #define READ_BIO_FILE_CHUNK 128 @@ -109,7 +108,6 @@ static int wolfssl_read_bio_file(WOLFSSL_BIO* bio, char** data) *data = mem; return ret; } -#endif /* Read exactly the required amount into a newly allocated buffer. * @@ -171,15 +169,7 @@ static int wolfssl_read_bio(WOLFSSL_BIO* bio, char** data, int* dataSz, } *memAlloced = 0; } -#ifndef WOLFSSL_NO_FSEEK /* Get pending or, when a file BIO, get length of file. */ - else if ((sz = wolfSSL_BIO_get_len(bio)) > 0) { - ret = wolfssl_read_bio_len(bio, sz, data); - if (ret > 0) { - *memAlloced = 1; - } - } -#else else if ((sz = wolfSSL_BIO_pending(bio)) > 0) { ret = wolfssl_read_bio_len(bio, sz, data); if (ret > 0) { @@ -192,7 +182,6 @@ static int wolfssl_read_bio(WOLFSSL_BIO* bio, char** data, int* dataSz, *memAlloced = 1; } } -#endif else { WOLFSSL_ERROR_MSG("No data read from bio"); *memAlloced = 0; diff --git a/src/src/ssl_p7p12.c b/src/src/ssl_p7p12.c index 00395c9..6313feb 100644 --- a/src/src/ssl_p7p12.c +++ b/src/src/ssl_p7p12.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -317,6 +317,10 @@ PKCS7* wolfSSL_d2i_PKCS7_bio(WOLFSSL_BIO* bio, PKCS7** p7) return NULL; pkcs7->len = wolfSSL_BIO_get_len(bio); + if (pkcs7->len < 0){ + wolfSSL_PKCS7_free((PKCS7*)pkcs7); + return NULL; + } pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7); if (pkcs7->data == NULL) { wolfSSL_PKCS7_free((PKCS7*)pkcs7); @@ -772,6 +776,8 @@ int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs, int contTypeLen; WOLFSSL_X509* signer = NULL; WOLFSSL_STACK* signers = NULL; + X509_STORE_CTX* ctx = NULL; + WOLFSSL_ENTER("wolfSSL_PKCS7_verify"); @@ -804,24 +810,37 @@ int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs, return WOLFSSL_FAILURE; } + ctx = X509_STORE_CTX_new(); + if (ctx == NULL) { + WOLFSSL_MSG("Error allocating X509 Store Context"); + return WOLFSSL_FAILURE; + } + signers = wolfSSL_PKCS7_get0_signers(pkcs7, certs, flags); if (signers == NULL) { WOLFSSL_MSG("No signers found to verify"); + wolfSSL_X509_STORE_CTX_free(ctx); return WOLFSSL_FAILURE; } + for (i = 0; i < wolfSSL_sk_X509_num(signers); i++) { signer = wolfSSL_sk_X509_value(signers, i); - - if (wolfSSL_CertManagerVerifyBuffer(store->cm, - signer->derCert->buffer, - signer->derCert->length, - WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) { + if (wolfSSL_X509_STORE_CTX_init(ctx, store, signer, NULL) + != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("Failed to initialize X509 STORE CTX"); + wolfSSL_sk_X509_pop_free(signers, NULL); + wolfSSL_X509_STORE_CTX_free(ctx); + return WOLFSSL_FAILURE; + } + if (wolfSSL_X509_verify_cert(ctx) != WOLFSSL_SUCCESS) { WOLFSSL_MSG("Failed to verify signer certificate"); wolfSSL_sk_X509_pop_free(signers, NULL); + wolfSSL_X509_STORE_CTX_free(ctx); return WOLFSSL_FAILURE; } } wolfSSL_sk_X509_pop_free(signers, NULL); + wolfSSL_X509_STORE_CTX_free(ctx); } if (flags & PKCS7_TEXT) { diff --git a/src/src/ssl_sess.c b/src/src/ssl_sess.c index c5e0e68..bd869d3 100644 --- a/src/src/ssl_sess.c +++ b/src/src/ssl_sess.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1178,9 +1178,6 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) byte preallocNonceUsed = 0; #endif /* WOLFSSL_TLS13 */ byte tmpBufSet = 0; -#endif -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - WOLFSSL_X509* peer = NULL; #endif byte bogusID[ID_LEN]; byte bogusIDSz = 0; @@ -1447,13 +1444,6 @@ int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output) XFREE(preallocNonce, output->heap, DYNAMIC_TYPE_SESSION_TICK); #endif /* WOLFSSL_TLS13 && WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3)*/ -#endif - -#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) - if (peer != NULL) { - wolfSSL_X509_free(peer); - peer = NULL; - } #endif return error; diff --git a/src/src/tls.c b/src/src/tls.c index 6ad21c9..c6c8111 100644 --- a/src/src/tls.c +++ b/src/src/tls.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -60,7 +60,6 @@ #ifndef NO_TLS #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES) -static int TLSX_KeyShare_IsSupported(int namedGroup); static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap); #endif @@ -477,20 +476,23 @@ int DeriveTlsKeys(WOLFSSL* ssl) return MEMORY_E; } #endif + + XMEMSET(key_dig, 0, MAX_PRF_DIG); + #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS) - ret = PROTOCOLCB_UNAVAILABLE; - if (ssl->ctx->GenSessionKeyCb) { - void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl); - ret = ssl->ctx->GenSessionKeyCb(ssl, ctx); - } - if (!ssl->ctx->GenSessionKeyCb || - ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) -#endif - ret = _DeriveTlsKeys(key_dig, (word32)key_dig_len, - ssl->arrays->masterSecret, SECRET_LEN, - ssl->arrays->serverRandom, ssl->arrays->clientRandom, - IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, - ssl->heap, ssl->devId); + ret = PROTOCOLCB_UNAVAILABLE; + if (ssl->ctx->GenSessionKeyCb) { + void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl); + ret = ssl->ctx->GenSessionKeyCb(ssl, ctx); + } + if (!ssl->ctx->GenSessionKeyCb || + ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) +#endif + ret = _DeriveTlsKeys(key_dig, (word32)key_dig_len, + ssl->arrays->masterSecret, SECRET_LEN, + ssl->arrays->serverRandom, ssl->arrays->clientRandom, + IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, + ssl->heap, ssl->devId); if (ret == 0) ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER); @@ -4454,287 +4456,555 @@ int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type, #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */ -/******************************************************************************/ -/* Supported Elliptic Curves */ -/******************************************************************************/ - -#ifdef HAVE_SUPPORTED_CURVES +#if defined(HAVE_SUPPORTED_CURVES) || \ + (defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)) -#if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \ - && !defined(HAVE_FFDHE) && !defined(WOLFSSL_HAVE_MLKEM) -#error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \ - Use --enable-ecc and/or --enable-liboqs in the configure script or \ - define HAVE_ECC. Alternatively use FFDHE for DH cipher suites. +/* Functions needed by TLSX_IsGroupSupported */ +#ifdef HAVE_LIBOQS +static int mlkem_id2type(int id, int *type); +static void findEccPqc(int *ecc, int *pqc, int *pqc_first, int group); #endif -static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name, - void* heap) -{ - if (curve == NULL) - return BAD_FUNC_ARG; - - (void)heap; - - *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap, - DYNAMIC_TYPE_TLSX); - if (*curve == NULL) - return MEMORY_E; - - (*curve)->name = name; - (*curve)->next = NULL; - - return 0; -} - -static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap) -{ - if (point == NULL) - return BAD_FUNC_ARG; - - (void)heap; - - *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap, - DYNAMIC_TYPE_TLSX); - if (*point == NULL) - return MEMORY_E; - - (*point)->format = format; - (*point)->next = NULL; - - return 0; -} - -static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap) -{ - SupportedCurve* curve; - - while ((curve = list)) { - list = curve->next; - XFREE(curve, heap, DYNAMIC_TYPE_TLSX); - } - (void)heap; -} - -static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap) -{ - PointFormat* point; - - while ((point = list)) { - list = point->next; - XFREE(point, heap, DYNAMIC_TYPE_TLSX); - } - (void)heap; -} - -static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name, - void* heap) +/* Returns whether this group is supported. + * + * namedGroup The named group to check. + * returns 1 when supported or 0 otherwise. + */ +static int TLSX_IsGroupSupported(int namedGroup) { - int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); - - while (list) { - if (list->name == name) { - ret = 0; /* curve already in use */ - break; - } - - if (list->next == NULL) { - ret = TLSX_SupportedCurve_New(&list->next, name, heap); + switch (namedGroup) { + #ifdef HAVE_FFDHE_2048 + case WOLFSSL_FFDHE_2048: break; - } - - list = list->next; - } - - return ret; -} - -static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap) -{ - int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); - - while (list) { - if (list->format == format) { - ret = 0; /* format already in use */ + #endif + #ifdef HAVE_FFDHE_3072 + case WOLFSSL_FFDHE_3072: break; - } - - if (list->next == NULL) { - ret = TLSX_PointFormat_New(&list->next, format, heap); + #endif + #ifdef HAVE_FFDHE_4096 + case WOLFSSL_FFDHE_4096: break; - } - - list = list->next; - } - - return ret; -} - -#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT) - -#if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ - defined(HAVE_CURVE448)) -static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl, - const byte* semaphore) -{ - /* If all pre-defined parameter types for key exchange are supported then - * always send SupportedGroups extension. - */ - (void)ssl; - (void)semaphore; -} -#else -static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore) -{ - word16 i; - const Suites* suites = WOLFSSL_SUITES(ssl); - - for (i = 0; i < suites->suiteSz; i += 2) { - if (suites->suites[i] == TLS13_BYTE) - return; - #ifdef BUILD_TLS_SM4_GCM_SM3 - if ((suites->suites[i] == CIPHER_BYTE) && - (suites->suites[i+1] == TLS_SM4_GCM_SM3)) - return; #endif - #ifdef BUILD_TLS_SM4_CCM_SM3 - if ((suites->suites[i] == CIPHER_BYTE) && - (suites->suites[i+1] == TLS_SM4_CCM_SM3)) - return; + #ifdef HAVE_FFDHE_6144 + case WOLFSSL_FFDHE_6144: + break; #endif - #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 - if ((suites->suites[i] == SM_BYTE) && - (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) - return; + #ifdef HAVE_FFDHE_8192 + case WOLFSSL_FFDHE_8192: + break; #endif - if ((suites->suites[i] == ECC_BYTE) || - (suites->suites[i] == ECDHE_PSK_BYTE) || - (suites->suites[i] == CHACHA_BYTE)) { - #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ - defined(HAVE_CURVE448) - return; + #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256 + #ifdef HAVE_ECC_KOBLITZ + case WOLFSSL_ECC_SECP256K1: + break; #endif - } - #ifdef HAVE_FFDHE - else { - return; - } + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP256R1: + break; + #endif /* !NO_ECC_SECP */ + #ifdef HAVE_ECC_BRAINPOOL + case WOLFSSL_ECC_BRAINPOOLP256R1: + break; #endif - } - - /* turns semaphore on to avoid sending this extension. */ - TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS)); -} -#endif - -/* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present. - */ -static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore) -{ -#ifdef HAVE_FFDHE - (void)ssl; - (void)semaphore; -#else - word16 i; - const Suites* suites = WOLFSSL_SUITES(ssl); - - if (suites == NULL) - return; - - for (i = 0; i < suites->suiteSz; i += 2) { - if (suites->suites[i] == TLS13_BYTE) - return; - #ifdef BUILD_TLS_SM4_GCM_SM3 - if ((suites->suites[i] == CIPHER_BYTE) && - (suites->suites[i+1] == TLS_SM4_GCM_SM3)) - return; + #ifdef WOLFSSL_SM2 + case WOLFSSL_ECC_SM2P256V1: + break; + #endif /* WOLFSSL_SM2 */ #endif - #ifdef BUILD_TLS_SM4_CCM_SM3 - if ((suites->suites[i] == CIPHER_BYTE) && - (suites->suites[i+1] == TLS_SM4_CCM_SM3)) - return; + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_ECC_X25519: + break; #endif - #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 - if ((suites->suites[i] == SM_BYTE) && - (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) - return; + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + case WOLFSSL_ECC_X448: + break; #endif - if ((suites->suites[i] == ECC_BYTE) || - (suites->suites[i] == ECDHE_PSK_BYTE) || - (suites->suites[i] == CHACHA_BYTE)) { - #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ - defined(HAVE_CURVE448) - return; + #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384 + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP384R1: + break; + #endif /* !NO_ECC_SECP */ + #ifdef HAVE_ECC_BRAINPOOL + case WOLFSSL_ECC_BRAINPOOLP384R1: + break; #endif - } - } - /* turns semaphore on to avoid sending this extension. */ - TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS)); -#endif -} + #endif + #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521 + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP521R1: + break; + #endif /* !NO_ECC_SECP */ + #endif + #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160 + #ifdef HAVE_ECC_KOBLITZ + case WOLFSSL_ECC_SECP160K1: + break; + #endif + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP160R1: + break; + #endif + #ifdef HAVE_ECC_SECPR2 + case WOLFSSL_ECC_SECP160R2: + break; + #endif + #endif + #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192 + #ifdef HAVE_ECC_KOBLITZ + case WOLFSSL_ECC_SECP192K1: + break; + #endif + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP192R1: + break; + #endif + #endif + #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224 + #ifdef HAVE_ECC_KOBLITZ + case WOLFSSL_ECC_SECP224K1: + break; + #endif + #ifndef NO_ECC_SECP + case WOLFSSL_ECC_SECP224R1: + break; + #endif + #endif + #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512 + #ifdef HAVE_ECC_BRAINPOOL + case WOLFSSL_ECC_BRAINPOOLP512R1: + break; + #endif + #endif +#ifdef WOLFSSL_HAVE_MLKEM +#ifndef WOLFSSL_NO_ML_KEM + #ifdef WOLFSSL_WC_MLKEM + #ifndef WOLFSSL_NO_ML_KEM_512 + case WOLFSSL_ML_KEM_512: + case WOLFSSL_P256_ML_KEM_512: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_ML_KEM_512: + #endif + #endif + #ifndef WOLFSSL_NO_ML_KEM_768 + case WOLFSSL_ML_KEM_768: + case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P256_ML_KEM_768: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_ML_KEM_768: + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + case WOLFSSL_X448_ML_KEM_768: + #endif + #endif + #ifndef WOLFSSL_NO_ML_KEM_1024 + case WOLFSSL_ML_KEM_1024: + case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_P384_ML_KEM_1024: + break; + #endif +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + case WOLFSSL_P256_ML_KEM_512_OLD: + case WOLFSSL_P384_ML_KEM_768_OLD: + case WOLFSSL_P521_ML_KEM_1024_OLD: + break; +#endif + #elif defined(HAVE_LIBOQS) + case WOLFSSL_ML_KEM_512: + case WOLFSSL_ML_KEM_768: + case WOLFSSL_ML_KEM_1024: + { + int ret; + int id; + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } -#endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */ + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } -#ifndef NO_WOLFSSL_SERVER + case WOLFSSL_P256_ML_KEM_512: + case WOLFSSL_P384_ML_KEM_768: + case WOLFSSL_P256_ML_KEM_768: + case WOLFSSL_P521_ML_KEM_1024: + case WOLFSSL_P384_ML_KEM_1024: + case WOLFSSL_X25519_ML_KEM_512: + case WOLFSSL_X448_ML_KEM_768: + case WOLFSSL_X25519_ML_KEM_768: + { + int ret; + int id; + findEccPqc(NULL, &namedGroup, NULL, namedGroup); + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } -static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore) -{ -#if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ - defined(HAVE_CURVE448) - (void)semaphore; -#endif + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } + #endif +#endif /* WOLFSSL_NO_ML_KEM */ +#ifdef WOLFSSL_MLKEM_KYBER + #ifdef WOLFSSL_WC_MLKEM + #ifdef WOLFSSL_KYBER512 + case WOLFSSL_KYBER_LEVEL1: + case WOLFSSL_P256_KYBER_LEVEL1: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_KYBER_LEVEL1: + #endif + #endif + #ifdef WOLFSSL_KYBER768 + case WOLFSSL_KYBER_LEVEL3: + case WOLFSSL_P384_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL3: + #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 + case WOLFSSL_X25519_KYBER_LEVEL3: + #endif + #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 + case WOLFSSL_X448_KYBER_LEVEL3: + #endif + #endif + #ifdef WOLFSSL_KYBER1024 + case WOLFSSL_KYBER_LEVEL5: + case WOLFSSL_P521_KYBER_LEVEL5: + #endif + break; + #elif defined(HAVE_LIBOQS) + case WOLFSSL_KYBER_LEVEL1: + case WOLFSSL_KYBER_LEVEL3: + case WOLFSSL_KYBER_LEVEL5: + { + int ret; + int id; + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } - if (ssl->options.cipherSuite0 == TLS13_BYTE) - return; -#ifdef BUILD_TLS_SM4_GCM_SM3 - if ((ssl->options.cipherSuite0 == CIPHER_BYTE) && - (ssl->options.cipherSuite == TLS_SM4_GCM_SM3)) - return; -#endif -#ifdef BUILD_TLS_SM4_CCM_SM3 - if ((ssl->options.cipherSuite0 == CIPHER_BYTE) && - (ssl->options.cipherSuite == TLS_SM4_CCM_SM3)) - return; -#endif -#ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 - if ((ssl->options.cipherSuite0 == SM_BYTE) && - (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) - return; + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } + case WOLFSSL_P256_KYBER_LEVEL1: + case WOLFSSL_P384_KYBER_LEVEL3: + case WOLFSSL_P256_KYBER_LEVEL3: + case WOLFSSL_P521_KYBER_LEVEL5: + case WOLFSSL_X25519_KYBER_LEVEL1: + case WOLFSSL_X448_KYBER_LEVEL3: + case WOLFSSL_X25519_KYBER_LEVEL3: + { + int ret; + int id; + findEccPqc(NULL, &namedGroup, NULL, namedGroup); + ret = mlkem_id2type(namedGroup, &id); + if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { + return 0; + } + + if (! ext_mlkem_enabled(id)) { + return 0; + } + break; + } + #endif #endif -#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) - if (ssl->options.cipherSuite0 == ECC_BYTE || - ssl->options.cipherSuite0 == ECDHE_PSK_BYTE || - ssl->options.cipherSuite0 == CHACHA_BYTE) { - return; +#endif /* WOLFSSL_HAVE_MLKEM */ + default: + return 0; } -#endif - /* turns semaphore on to avoid sending this extension. */ - TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS)); + return 1; } +#endif -#endif /* !NO_WOLFSSL_SERVER */ +/******************************************************************************/ +/* Supported Elliptic Curves */ +/******************************************************************************/ -#if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13) +#ifdef HAVE_SUPPORTED_CURVES -static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list) +#if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \ + && !defined(HAVE_FFDHE) && !defined(WOLFSSL_HAVE_MLKEM) +#error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \ + Use --enable-ecc and/or --enable-liboqs in the configure script or \ + define HAVE_ECC. Alternatively use FFDHE for DH cipher suites. +#endif + +static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name, + void* heap) { - SupportedCurve* curve; - word16 length = OPAQUE16_LEN; /* list length */ + if (curve == NULL) + return BAD_FUNC_ARG; - while ((curve = list)) { - list = curve->next; - length += OPAQUE16_LEN; /* curve length */ - } + (void)heap; - return length; -} + *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap, + DYNAMIC_TYPE_TLSX); + if (*curve == NULL) + return MEMORY_E; -#endif + (*curve)->name = name; + (*curve)->next = NULL; -static word16 TLSX_PointFormat_GetSize(PointFormat* list) -{ - PointFormat* point; - word16 length = ENUM_LEN; /* list length */ + return 0; +} + +static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap) +{ + if (point == NULL) + return BAD_FUNC_ARG; + + (void)heap; + + *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap, + DYNAMIC_TYPE_TLSX); + if (*point == NULL) + return MEMORY_E; + + (*point)->format = format; + (*point)->next = NULL; + + return 0; +} + +static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap) +{ + SupportedCurve* curve; + + while ((curve = list)) { + list = curve->next; + XFREE(curve, heap, DYNAMIC_TYPE_TLSX); + } + (void)heap; +} + +static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap) +{ + PointFormat* point; + + while ((point = list)) { + list = point->next; + XFREE(point, heap, DYNAMIC_TYPE_TLSX); + } + (void)heap; +} + +static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name, + void* heap) +{ + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + + while (list) { + if (list->name == name) { + ret = 0; /* curve already in use */ + break; + } + + if (list->next == NULL) { + ret = TLSX_SupportedCurve_New(&list->next, name, heap); + break; + } + + list = list->next; + } + + return ret; +} + +static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap) +{ + int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); + + while (list) { + if (list->format == format) { + ret = 0; /* format already in use */ + break; + } + + if (list->next == NULL) { + ret = TLSX_PointFormat_New(&list->next, format, heap); + break; + } + + list = list->next; + } + + return ret; +} + +#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT) + +#if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ + defined(HAVE_CURVE448)) +static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl, + const byte* semaphore) +{ + /* If all pre-defined parameter types for key exchange are supported then + * always send SupportedGroups extension. + */ + (void)ssl; + (void)semaphore; +} +#else +static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore) +{ + word16 i; + const Suites* suites = WOLFSSL_SUITES(ssl); + + for (i = 0; i < suites->suiteSz; i += 2) { + if (suites->suites[i] == TLS13_BYTE) + return; + #ifdef BUILD_TLS_SM4_GCM_SM3 + if ((suites->suites[i] == CIPHER_BYTE) && + (suites->suites[i+1] == TLS_SM4_GCM_SM3)) + return; + #endif + #ifdef BUILD_TLS_SM4_CCM_SM3 + if ((suites->suites[i] == CIPHER_BYTE) && + (suites->suites[i+1] == TLS_SM4_CCM_SM3)) + return; + #endif + #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 + if ((suites->suites[i] == SM_BYTE) && + (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) + return; + #endif + if ((suites->suites[i] == ECC_BYTE) || + (suites->suites[i] == ECDHE_PSK_BYTE) || + (suites->suites[i] == CHACHA_BYTE)) { + #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ + defined(HAVE_CURVE448) + return; + #endif + } + #ifdef HAVE_FFDHE + else { + return; + } + #endif + } + + /* turns semaphore on to avoid sending this extension. */ + TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS)); +} +#endif + +/* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present. + */ +static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore) +{ +#ifdef HAVE_FFDHE + (void)ssl; + (void)semaphore; +#else + word16 i; + const Suites* suites = WOLFSSL_SUITES(ssl); + + if (suites == NULL) + return; + + for (i = 0; i < suites->suiteSz; i += 2) { + if (suites->suites[i] == TLS13_BYTE) + return; + #ifdef BUILD_TLS_SM4_GCM_SM3 + if ((suites->suites[i] == CIPHER_BYTE) && + (suites->suites[i+1] == TLS_SM4_GCM_SM3)) + return; + #endif + #ifdef BUILD_TLS_SM4_CCM_SM3 + if ((suites->suites[i] == CIPHER_BYTE) && + (suites->suites[i+1] == TLS_SM4_CCM_SM3)) + return; + #endif + #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 + if ((suites->suites[i] == SM_BYTE) && + (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) + return; + #endif + if ((suites->suites[i] == ECC_BYTE) || + (suites->suites[i] == ECDHE_PSK_BYTE) || + (suites->suites[i] == CHACHA_BYTE)) { + #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ + defined(HAVE_CURVE448) + return; + #endif + } + } + /* turns semaphore on to avoid sending this extension. */ + TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS)); +#endif +} + +#endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */ + +#ifndef NO_WOLFSSL_SERVER + +static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore) +{ +#if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ + defined(HAVE_CURVE448) + (void)semaphore; +#endif + + if (ssl->options.cipherSuite0 == TLS13_BYTE) + return; +#ifdef BUILD_TLS_SM4_GCM_SM3 + if ((ssl->options.cipherSuite0 == CIPHER_BYTE) && + (ssl->options.cipherSuite == TLS_SM4_GCM_SM3)) + return; +#endif +#ifdef BUILD_TLS_SM4_CCM_SM3 + if ((ssl->options.cipherSuite0 == CIPHER_BYTE) && + (ssl->options.cipherSuite == TLS_SM4_CCM_SM3)) + return; +#endif +#ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 + if ((ssl->options.cipherSuite0 == SM_BYTE) && + (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)) + return; +#endif +#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) + if (ssl->options.cipherSuite0 == ECC_BYTE || + ssl->options.cipherSuite0 == ECDHE_PSK_BYTE || + ssl->options.cipherSuite0 == CHACHA_BYTE) { + return; + } +#endif + + /* turns semaphore on to avoid sending this extension. */ + TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS)); +} + +#endif /* !NO_WOLFSSL_SERVER */ + +#if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13) + +static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list) +{ + SupportedCurve* curve; + word16 length = OPAQUE16_LEN; /* list length */ + + while ((curve = list)) { + list = curve->next; + length += OPAQUE16_LEN; /* curve length */ + } + + return length; +} + +#endif + +static word16 TLSX_PointFormat_GetSize(PointFormat* list) +{ + PointFormat* point; + word16 length = ENUM_LEN; /* list length */ while ((point = list)) { list = point->next; @@ -4785,7 +5055,8 @@ int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input, { word16 offset; word16 name; - int ret; + int ret = 0; + TLSX* extension; if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) { #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT @@ -4794,57 +5065,66 @@ int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input, return BUFFER_ERROR; /* servers doesn't send this extension. */ #endif } - if (OPAQUE16_LEN > length || length % OPAQUE16_LEN) return BUFFER_ERROR; - ato16(input, &offset); - /* validating curve list length */ if (length != OPAQUE16_LEN + offset) return BUFFER_ERROR; - offset = OPAQUE16_LEN; if (offset == length) return 0; -#if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT) - if (!isRequest) { - TLSX* extension; - SupportedCurve* curve; - - extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS); - if (extension != NULL) { - /* Replace client list with server list of supported groups. */ - curve = (SupportedCurve*)extension->data; - extension->data = NULL; - TLSX_SupportedCurve_FreeAll(curve, ssl->heap); - + extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS); + if (extension == NULL) { + /* Just accept what the peer wants to use */ + for (; offset < length; offset += OPAQUE16_LEN) { ato16(input + offset, &name); - offset += OPAQUE16_LEN; - ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap); - if (ret != 0) - return ret; /* throw error */ - extension->data = (void*)curve; + ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap); + /* If it is BAD_FUNC_ARG then it is a group we do not support, but + * that is fine. */ + if (ret != WOLFSSL_SUCCESS && + ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) + break; + ret = 0; } } -#endif + else { + /* Find the intersection with what the user has set */ + SupportedCurve* commonCurves = NULL; + for (; offset < length; offset += OPAQUE16_LEN) { + SupportedCurve* foundCurve = (SupportedCurve*)extension->data; + ato16(input + offset, &name); - for (; offset < length; offset += OPAQUE16_LEN) { - ato16(input + offset, &name); + while (foundCurve != NULL && foundCurve->name != name) + foundCurve = foundCurve->next; - ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap); - /* If it is BAD_FUNC_ARG then it is a group we do not support, but - * that is fine. */ - if (ret != WOLFSSL_SUCCESS && ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { - return ret; + if (foundCurve != NULL) { + ret = commonCurves == NULL ? + TLSX_SupportedCurve_New(&commonCurves, name, ssl->heap) : + TLSX_SupportedCurve_Append(commonCurves, name, ssl->heap); + if (ret != 0) + break; + } + } + /* If no common curves return error. In TLS 1.3 we can still try to save + * this by using HRR. */ + if (ret == 0 && commonCurves == NULL && + !IsAtLeastTLSv1_3(ssl->version)) + ret = ECC_CURVE_ERROR; + if (ret == 0) { + /* Now swap out the curves in the extension */ + TLSX_SupportedCurve_FreeAll((SupportedCurve*)extension->data, + ssl->heap); + extension->data = commonCurves; + commonCurves = NULL; } + TLSX_SupportedCurve_FreeAll(commonCurves, ssl->heap); } - return 0; + return ret; } - #endif #if !defined(NO_WOLFSSL_SERVER) @@ -5159,7 +5439,7 @@ int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported) curve = (SupportedCurve*)extension->data; while (curve != NULL) { - if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name)) + if (!checkSupported || TLSX_IsGroupSupported(curve->name)) return curve->name; curve = curve->next; } @@ -5581,11 +5861,9 @@ int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap) return BAD_FUNC_ARG; } -#ifdef WOLFSSL_TLS13 - if (! TLSX_KeyShare_IsSupported(name)) { + if (! TLSX_IsGroupSupported(name)) { return BAD_FUNC_ARG; } -#endif extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS); @@ -5605,6 +5883,23 @@ int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap) heap); if (ret != 0) return ret; +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + if (name == WOLFSSL_P256_ML_KEM_512) { + ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, + WOLFSSL_P256_ML_KEM_512_OLD, heap); + } + else if (name == WOLFSSL_P384_ML_KEM_768) { + ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, + WOLFSSL_P384_ML_KEM_768_OLD, heap); + } + else if (name == WOLFSSL_P521_ML_KEM_1024) { + ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, + WOLFSSL_P521_ML_KEM_1024_OLD, heap); + } + if (ret != 0) { + return ret; + } +#endif } return WOLFSSL_SUCCESS; @@ -7743,8 +8038,11 @@ static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse) if (ret != 0) { /* Cleanup on error, otherwise data owned by key share entry */ - XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - kse->privKey = NULL; + if (kse->privKey) { + ForceZero(kse->privKey, pvtSz); + XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + kse->privKey = NULL; + } XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); kse->pubKey = NULL; } @@ -8172,6 +8470,11 @@ static const PqcHybridMapping pqc_hybrid_mapping[] = { {WOLFSSL_P256_ML_KEM_768, WOLFSSL_ECC_SECP256R1, WOLFSSL_ML_KEM_768, 0}, {WOLFSSL_P521_ML_KEM_1024, WOLFSSL_ECC_SECP521R1, WOLFSSL_ML_KEM_1024, 0}, {WOLFSSL_P384_ML_KEM_1024, WOLFSSL_ECC_SECP384R1, WOLFSSL_ML_KEM_1024, 0}, +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + {WOLFSSL_P256_ML_KEM_512_OLD, WOLFSSL_ECC_SECP256R1, WOLFSSL_ML_KEM_512, 0}, + {WOLFSSL_P384_ML_KEM_768_OLD, WOLFSSL_ECC_SECP384R1, WOLFSSL_ML_KEM_768, 0}, + {WOLFSSL_P521_ML_KEM_1024_OLD, WOLFSSL_ECC_SECP521R1, WOLFSSL_ML_KEM_1024, 0}, +#endif #ifdef HAVE_CURVE25519 {WOLFSSL_X25519_ML_KEM_512, WOLFSSL_ECC_X25519, WOLFSSL_ML_KEM_512, 1}, {WOLFSSL_X25519_ML_KEM_768, WOLFSSL_ECC_X25519, WOLFSSL_ML_KEM_768, 1}, @@ -8335,7 +8638,11 @@ static int TLSX_KeyShare_GenPqcKeyClient(WOLFSSL *ssl, KeyShareEntry* kse) XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); kse->pubKey = NULL; #ifndef WOLFSSL_TLSX_PQC_MLKEM_STORE_OBJ - XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + if (privKey) { + ForceZero(privKey, privSz); + XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + privKey = NULL; + } #else XFREE(kem, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); kse->key = NULL; @@ -8804,8 +9111,11 @@ static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry) wc_FreeDhKey(dhKey); XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH); keyShareEntry->key = NULL; - XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); - keyShareEntry->privKey = NULL; + if (keyShareEntry->privKey) { + ForceZero(keyShareEntry->privKey, keyShareEntry->keyLen); + XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY); + keyShareEntry->privKey = NULL; + } XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); keyShareEntry->pubKey = NULL; XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); @@ -10125,482 +10435,242 @@ static int TLSX_KeyShare_HandlePqcHybridKeyServer(WOLFSSL* ssl, if (ciphertext == NULL) { WOLFSSL_MSG("Ciphertext memory allocation failure."); ret = MEMORY_E; - } - } - - /* Process ECDH key share part. The generated shared secret is directly - * stored in the ssl->arrays->preMasterSecret buffer. Depending on the - * pqc_first flag, the ECDH shared secret part goes before or after the - * KEM part. */ - if (ret == 0) { - ecc_kse->keLen = len - pubSz; - ecc_kse->ke = (byte*)XMALLOC(ecc_kse->keLen, ssl->heap, - DYNAMIC_TYPE_PUBLIC_KEY); - if (ecc_kse->ke == NULL) { - WOLFSSL_MSG("ecc_kse memory allocation failure"); - ret = MEMORY_ERROR; - } - if (ret == 0) { - int pubOffset = 0; - int ssOffset = 0; - - /* Set the ECC size variable to the initial buffer size */ - ssSzEcc = ssl->arrays->preMasterSz; - - if (pqc_first) { - pubOffset = pubSz; - ssOffset = ssSzPqc; - } - - XMEMCPY(ecc_kse->ke, data + pubOffset, ecc_kse->keLen); - - #ifdef HAVE_CURVE25519 - if (ecc_group == WOLFSSL_ECC_X25519) { - ret = TLSX_KeyShare_ProcessX25519_ex(ssl, ecc_kse, - ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); - } - else - #endif - #ifdef HAVE_CURVE448 - if (ecc_group == WOLFSSL_ECC_X448) { - ret = TLSX_KeyShare_ProcessX448_ex(ssl, ecc_kse, - ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); - } - else - #endif - { - ret = TLSX_KeyShare_ProcessEcc_ex(ssl, ecc_kse, - ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); - } - } - if (ret == 0) { - if (ssSzEcc != ecc_kse->keyLen) { - WOLFSSL_MSG("Data length mismatch."); - ret = BAD_FUNC_ARG; - } - } - } - - if (ret == 0 && ssSzEcc + ssSzPqc > ENCRYPT_LEN) { - WOLFSSL_MSG("shared secret is too long."); - ret = LENGTH_ERROR; - } - - /* Process PQC KEM key share part. Depending on the pqc_first flag, the - * KEM shared secret part goes before or after the ECDH part. */ - if (ret == 0) { - int input_offset = ecc_kse->keLen; - int output_offset = ssSzEcc; - - if (pqc_first) { - input_offset = 0; - output_offset = 0; - } - - ret = TLSX_KeyShare_HandlePqcKeyServer(ssl, pqc_kse, - data + input_offset, pubSz, - ssl->arrays->preMasterSecret + output_offset, &ssSzPqc); - } - - if (ret == 0) { - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - - ssl->arrays->preMasterSz = ssSzEcc + ssSzPqc; - keyShareEntry->ke = NULL; - keyShareEntry->keLen = 0; - - /* Concatenate the ECDH public key and the PQC KEM ciphertext. Based on - * the pqc_first flag, the ECDH public key goes before or after the KEM - * ciphertext. */ - if (pqc_first) { - XMEMCPY(ciphertext, pqc_kse->pubKey, ctSz); - XMEMCPY(ciphertext + ctSz, ecc_kse->pubKey, ecc_kse->pubKeyLen); - } - else { - XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen); - XMEMCPY(ciphertext + ecc_kse->pubKeyLen, pqc_kse->pubKey, ctSz); - } - - keyShareEntry->pubKey = ciphertext; - keyShareEntry->pubKeyLen = ecc_kse->pubKeyLen + ctSz; - ciphertext = NULL; - - /* Set namedGroup so wolfSSL_get_curve_name() can function properly on - * the server side. */ - ssl->namedGroup = keyShareEntry->group; - } - - TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); - TLSX_KeyShare_FreeAll(pqc_kse, ssl->heap); - XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); - return ret; -} -#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_MLKEM_NO_ENCAPSULATE */ - -/* Use the data to create a new key share object in the extensions. - * - * ssl The SSL/TLS object. - * group The named group. - * len The length of the public key data. - * data The public key data. - * kse The new key share entry object. - * returns 0 on success and other values indicate failure. - */ -int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data, - KeyShareEntry **kse, TLSX** extensions) -{ - int ret = 0; - TLSX* extension; - KeyShareEntry* keyShareEntry = NULL; - - /* Find the KeyShare extension if it exists. */ - extension = TLSX_Find(*extensions, TLSX_KEY_SHARE); - if (extension == NULL) { - /* Push new KeyShare extension. */ - ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap); - if (ret != 0) - return ret; - - extension = TLSX_Find(*extensions, TLSX_KEY_SHARE); - if (extension == NULL) - return MEMORY_E; - } - extension->resp = 0; - - /* Try to find the key share entry with this group. */ - keyShareEntry = (KeyShareEntry*)extension->data; - while (keyShareEntry != NULL) { - if (keyShareEntry->group == group) - break; - keyShareEntry = keyShareEntry->next; - } - - /* Create a new key share entry if not found. */ - if (keyShareEntry == NULL) { - ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group, - ssl->heap, &keyShareEntry); - if (ret != 0) - return ret; - } - - -#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) - if (ssl->options.side == WOLFSSL_SERVER_END && - WOLFSSL_NAMED_GROUP_IS_PQC(group)) { - ret = TLSX_KeyShare_HandlePqcKeyServer((WOLFSSL*)ssl, - keyShareEntry, - data, len, - ssl->arrays->preMasterSecret, - &ssl->arrays->preMasterSz); - if (ret != 0) - return ret; - } - else if (ssl->options.side == WOLFSSL_SERVER_END && - WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) { - ret = TLSX_KeyShare_HandlePqcHybridKeyServer((WOLFSSL*)ssl, - keyShareEntry, - data, len); - if (ret != 0) - return ret; - } - else -#endif - if (data != NULL) { - XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); - keyShareEntry->ke = data; - keyShareEntry->keLen = len; - } - else { - /* Generate a key pair. Casting to non-const since changes inside are - * minimal but would require an extensive redesign to refactor. Also - * this path shouldn't be taken when parsing a ClientHello in stateless - * mode. */ - ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry); - if (ret != 0) - return ret; - } - - if (kse != NULL) - *kse = keyShareEntry; - - return 0; -} - -/* Set an empty Key Share extension. - * - * ssl The SSL/TLS object. - * returns 0 on success and other values indicate failure. - */ -int TLSX_KeyShare_Empty(WOLFSSL* ssl) -{ - int ret = 0; - TLSX* extension; - - /* Find the KeyShare extension if it exists. */ - extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE); - if (extension == NULL) { - /* Push new KeyShare extension. */ - ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap); - } - else if (extension->data != NULL) { - TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap); - extension->data = NULL; - } - - return ret; -} - -/* Returns whether this group is supported. - * - * namedGroup The named group to check. - * returns 1 when supported or 0 otherwise. - */ -static int TLSX_KeyShare_IsSupported(int namedGroup) -{ - switch (namedGroup) { - #ifdef HAVE_FFDHE_2048 - case WOLFSSL_FFDHE_2048: - break; - #endif - #ifdef HAVE_FFDHE_3072 - case WOLFSSL_FFDHE_3072: - break; - #endif - #ifdef HAVE_FFDHE_4096 - case WOLFSSL_FFDHE_4096: - break; - #endif - #ifdef HAVE_FFDHE_6144 - case WOLFSSL_FFDHE_6144: - break; - #endif - #ifdef HAVE_FFDHE_8192 - case WOLFSSL_FFDHE_8192: - break; - #endif - #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256 - #ifdef HAVE_ECC_KOBLITZ - case WOLFSSL_ECC_SECP256K1: - break; - #endif - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP256R1: - break; - #endif /* !NO_ECC_SECP */ - #ifdef HAVE_ECC_BRAINPOOL - case WOLFSSL_ECC_BRAINPOOLP256R1: - break; - #endif - #ifdef WOLFSSL_SM2 - case WOLFSSL_ECC_SM2P256V1: - break; - #endif /* WOLFSSL_SM2 */ - #endif - #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 - case WOLFSSL_ECC_X25519: - break; - #endif - #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 - case WOLFSSL_ECC_X448: - break; - #endif - #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384 - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP384R1: - break; - #endif /* !NO_ECC_SECP */ - #ifdef HAVE_ECC_BRAINPOOL - case WOLFSSL_ECC_BRAINPOOLP384R1: - break; - #endif - #endif - #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521 - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP521R1: - break; - #endif /* !NO_ECC_SECP */ - #endif - #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160 - #ifdef HAVE_ECC_KOBLITZ - case WOLFSSL_ECC_SECP160K1: - break; - #endif - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP160R1: - break; - #endif - #ifdef HAVE_ECC_SECPR2 - case WOLFSSL_ECC_SECP160R2: - break; - #endif - #endif - #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192 - #ifdef HAVE_ECC_KOBLITZ - case WOLFSSL_ECC_SECP192K1: - break; - #endif - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP192R1: - break; - #endif - #endif - #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224 - #ifdef HAVE_ECC_KOBLITZ - case WOLFSSL_ECC_SECP224K1: - break; - #endif - #ifndef NO_ECC_SECP - case WOLFSSL_ECC_SECP224R1: - break; - #endif - #endif - #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512 - #ifdef HAVE_ECC_BRAINPOOL - case WOLFSSL_ECC_BRAINPOOLP512R1: - break; - #endif - #endif -#ifdef WOLFSSL_HAVE_MLKEM -#ifndef WOLFSSL_NO_ML_KEM - #ifdef WOLFSSL_WC_MLKEM - #ifndef WOLFSSL_NO_ML_KEM_512 - case WOLFSSL_ML_KEM_512: - case WOLFSSL_P256_ML_KEM_512: - #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 - case WOLFSSL_X25519_ML_KEM_512: - #endif - #endif - #ifndef WOLFSSL_NO_ML_KEM_768 - case WOLFSSL_ML_KEM_768: - case WOLFSSL_P384_ML_KEM_768: - case WOLFSSL_P256_ML_KEM_768: - #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 - case WOLFSSL_X25519_ML_KEM_768: - #endif - #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 - case WOLFSSL_X448_ML_KEM_768: - #endif - #endif - #ifndef WOLFSSL_NO_ML_KEM_1024 - case WOLFSSL_ML_KEM_1024: - case WOLFSSL_P521_ML_KEM_1024: - case WOLFSSL_P384_ML_KEM_1024: - #endif - break; - #elif defined(HAVE_LIBOQS) - case WOLFSSL_ML_KEM_512: - case WOLFSSL_ML_KEM_768: - case WOLFSSL_ML_KEM_1024: - { - int ret; - int id; - ret = mlkem_id2type(namedGroup, &id); - if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { - return 0; - } - - if (! ext_mlkem_enabled(id)) { - return 0; - } - break; - } - case WOLFSSL_P256_ML_KEM_512: - case WOLFSSL_P384_ML_KEM_768: - case WOLFSSL_P256_ML_KEM_768: - case WOLFSSL_P521_ML_KEM_1024: - case WOLFSSL_P384_ML_KEM_1024: - case WOLFSSL_X25519_ML_KEM_512: - case WOLFSSL_X448_ML_KEM_768: - case WOLFSSL_X25519_ML_KEM_768: - { - int ret; - int id; - findEccPqc(NULL, &namedGroup, NULL, namedGroup); - ret = mlkem_id2type(namedGroup, &id); - if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { - return 0; - } - - if (! ext_mlkem_enabled(id)) { - return 0; - } - break; - } - #endif -#endif /* WOLFSSL_NO_ML_KEM */ -#ifdef WOLFSSL_MLKEM_KYBER - #ifdef WOLFSSL_WC_MLKEM - #ifdef WOLFSSL_KYBER512 - case WOLFSSL_KYBER_LEVEL1: - case WOLFSSL_P256_KYBER_LEVEL1: - #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 - case WOLFSSL_X25519_KYBER_LEVEL1: - #endif - #endif - #ifdef WOLFSSL_KYBER768 - case WOLFSSL_KYBER_LEVEL3: - case WOLFSSL_P384_KYBER_LEVEL3: - case WOLFSSL_P256_KYBER_LEVEL3: - #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256 - case WOLFSSL_X25519_KYBER_LEVEL3: - #endif - #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448 - case WOLFSSL_X448_KYBER_LEVEL3: - #endif - #endif - #ifdef WOLFSSL_KYBER1024 - case WOLFSSL_KYBER_LEVEL5: - case WOLFSSL_P521_KYBER_LEVEL5: - #endif - break; - #elif defined(HAVE_LIBOQS) - case WOLFSSL_KYBER_LEVEL1: - case WOLFSSL_KYBER_LEVEL3: - case WOLFSSL_KYBER_LEVEL5: - { - int ret; - int id; - ret = mlkem_id2type(namedGroup, &id); - if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { - return 0; + } + } + + /* Process ECDH key share part. The generated shared secret is directly + * stored in the ssl->arrays->preMasterSecret buffer. Depending on the + * pqc_first flag, the ECDH shared secret part goes before or after the + * KEM part. */ + if (ret == 0) { + ecc_kse->keLen = len - pubSz; + ecc_kse->ke = (byte*)XMALLOC(ecc_kse->keLen, ssl->heap, + DYNAMIC_TYPE_PUBLIC_KEY); + if (ecc_kse->ke == NULL) { + WOLFSSL_MSG("ecc_kse memory allocation failure"); + ret = MEMORY_ERROR; + } + if (ret == 0) { + int pubOffset = 0; + int ssOffset = 0; + + /* Set the ECC size variable to the initial buffer size */ + ssSzEcc = ssl->arrays->preMasterSz; + + if (pqc_first) { + pubOffset = pubSz; + ssOffset = ssSzPqc; } - if (! ext_mlkem_enabled(id)) { - return 0; + XMEMCPY(ecc_kse->ke, data + pubOffset, ecc_kse->keLen); + + #ifdef HAVE_CURVE25519 + if (ecc_group == WOLFSSL_ECC_X25519) { + ret = TLSX_KeyShare_ProcessX25519_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); + } + else + #endif + #ifdef HAVE_CURVE448 + if (ecc_group == WOLFSSL_ECC_X448) { + ret = TLSX_KeyShare_ProcessX448_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); + } + else + #endif + { + ret = TLSX_KeyShare_ProcessEcc_ex(ssl, ecc_kse, + ssl->arrays->preMasterSecret + ssOffset, &ssSzEcc); } - break; } - case WOLFSSL_P256_KYBER_LEVEL1: - case WOLFSSL_P384_KYBER_LEVEL3: - case WOLFSSL_P256_KYBER_LEVEL3: - case WOLFSSL_P521_KYBER_LEVEL5: - case WOLFSSL_X25519_KYBER_LEVEL1: - case WOLFSSL_X448_KYBER_LEVEL3: - case WOLFSSL_X25519_KYBER_LEVEL3: - { - int ret; - int id; - findEccPqc(NULL, &namedGroup, NULL, namedGroup); - ret = mlkem_id2type(namedGroup, &id); - if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) { - return 0; + if (ret == 0) { + if (ssSzEcc != ecc_kse->keyLen) { + WOLFSSL_MSG("Data length mismatch."); + ret = BAD_FUNC_ARG; } + } + } - if (! ext_mlkem_enabled(id)) { - return 0; - } + if (ret == 0 && ssSzEcc + ssSzPqc > ENCRYPT_LEN) { + WOLFSSL_MSG("shared secret is too long."); + ret = LENGTH_ERROR; + } + + /* Process PQC KEM key share part. Depending on the pqc_first flag, the + * KEM shared secret part goes before or after the ECDH part. */ + if (ret == 0) { + int input_offset = ecc_kse->keLen; + int output_offset = ssSzEcc; + + if (pqc_first) { + input_offset = 0; + output_offset = 0; + } + + ret = TLSX_KeyShare_HandlePqcKeyServer(ssl, pqc_kse, + data + input_offset, pubSz, + ssl->arrays->preMasterSecret + output_offset, &ssSzPqc); + } + + if (ret == 0) { + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + + ssl->arrays->preMasterSz = ssSzEcc + ssSzPqc; + keyShareEntry->ke = NULL; + keyShareEntry->keLen = 0; + + /* Concatenate the ECDH public key and the PQC KEM ciphertext. Based on + * the pqc_first flag, the ECDH public key goes before or after the KEM + * ciphertext. */ + if (pqc_first) { + XMEMCPY(ciphertext, pqc_kse->pubKey, ctSz); + XMEMCPY(ciphertext + ctSz, ecc_kse->pubKey, ecc_kse->pubKeyLen); + } + else { + XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen); + XMEMCPY(ciphertext + ecc_kse->pubKeyLen, pqc_kse->pubKey, ctSz); + } + + keyShareEntry->pubKey = ciphertext; + keyShareEntry->pubKeyLen = ecc_kse->pubKeyLen + ctSz; + ciphertext = NULL; + + /* Set namedGroup so wolfSSL_get_curve_name() can function properly on + * the server side. */ + ssl->namedGroup = keyShareEntry->group; + } + + TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap); + TLSX_KeyShare_FreeAll(pqc_kse, ssl->heap); + XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX); + return ret; +} +#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_MLKEM_NO_ENCAPSULATE */ + +/* Use the data to create a new key share object in the extensions. + * + * ssl The SSL/TLS object. + * group The named group. + * len The length of the public key data. + * data The public key data. + * kse The new key share entry object. + * returns 0 on success and other values indicate failure. + */ +int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data, + KeyShareEntry **kse, TLSX** extensions) +{ + int ret = 0; + TLSX* extension; + KeyShareEntry* keyShareEntry = NULL; + + /* Find the KeyShare extension if it exists. */ + extension = TLSX_Find(*extensions, TLSX_KEY_SHARE); + if (extension == NULL) { + /* Push new KeyShare extension. */ + ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap); + if (ret != 0) + return ret; + + extension = TLSX_Find(*extensions, TLSX_KEY_SHARE); + if (extension == NULL) + return MEMORY_E; + } + extension->resp = 0; + + /* Try to find the key share entry with this group. */ + keyShareEntry = (KeyShareEntry*)extension->data; + while (keyShareEntry != NULL) { +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + if ((group == WOLFSSL_P256_ML_KEM_512_OLD && + keyShareEntry->group == WOLFSSL_P256_ML_KEM_512) || + (group == WOLFSSL_P384_ML_KEM_768_OLD && + keyShareEntry->group == WOLFSSL_P384_ML_KEM_768) || + (group == WOLFSSL_P521_ML_KEM_1024_OLD && + keyShareEntry->group == WOLFSSL_P521_ML_KEM_1024)) { + keyShareEntry->group = group; break; } - #endif + else #endif -#endif /* WOLFSSL_HAVE_MLKEM */ - default: - return 0; + if (keyShareEntry->group == group) + break; + keyShareEntry = keyShareEntry->next; } - return 1; + /* Create a new key share entry if not found. */ + if (keyShareEntry == NULL) { + ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group, + ssl->heap, &keyShareEntry); + if (ret != 0) + return ret; + } + + +#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) + if (ssl->options.side == WOLFSSL_SERVER_END && + WOLFSSL_NAMED_GROUP_IS_PQC(group)) { + ret = TLSX_KeyShare_HandlePqcKeyServer((WOLFSSL*)ssl, + keyShareEntry, + data, len, + ssl->arrays->preMasterSecret, + &ssl->arrays->preMasterSz); + if (ret != 0) + return ret; + } + else if (ssl->options.side == WOLFSSL_SERVER_END && + WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) { + ret = TLSX_KeyShare_HandlePqcHybridKeyServer((WOLFSSL*)ssl, + keyShareEntry, + data, len); + if (ret != 0) + return ret; + } + else +#endif + if (data != NULL) { + XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY); + keyShareEntry->ke = data; + keyShareEntry->keLen = len; + } + else { + /* Generate a key pair. Casting to non-const since changes inside are + * minimal but would require an extensive redesign to refactor. Also + * this path shouldn't be taken when parsing a ClientHello in stateless + * mode. */ + ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry); + if (ret != 0) + return ret; + } + + if (kse != NULL) + *kse = keyShareEntry; + + return 0; } +/* Set an empty Key Share extension. + * + * ssl The SSL/TLS object. + * returns 0 on success and other values indicate failure. + */ +int TLSX_KeyShare_Empty(WOLFSSL* ssl) +{ + int ret = 0; + TLSX* extension; + + /* Find the KeyShare extension if it exists. */ + extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE); + if (extension == NULL) { + /* Push new KeyShare extension. */ + ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap); + } + else if (extension->data != NULL) { + TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap); + extension->data = NULL; + } + + return ret; +} static const word16 preferredGroup[] = { #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \ @@ -10665,7 +10735,7 @@ static const word16 preferredGroup[] = { WOLFSSL_P384_ML_KEM_1024, #endif #elif defined(HAVE_LIBOQS) - /* These require a runtime call to TLSX_KeyShare_IsSupported to use */ + /* These require a runtime call to TLSX_IsGroupSupported to use */ WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_1024, @@ -10708,7 +10778,7 @@ static const word16 preferredGroup[] = { WOLFSSL_P521_KYBER_LEVEL5, #endif #elif defined(HAVE_LIBOQS) - /* These require a runtime call to TLSX_KeyShare_IsSupported to use */ + /* These require a runtime call to TLSX_IsGroupSupported to use */ WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL5, @@ -10755,13 +10825,24 @@ static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group) } #ifdef HAVE_LIBOQS - if (!TLSX_KeyShare_IsSupported(group)) + if (!TLSX_IsGroupSupported(group)) return WOLFSSL_FATAL_ERROR; #endif - for (i = 0; i < numGroups; i++) + for (i = 0; i < numGroups; i++) { +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + if ((group == WOLFSSL_P256_ML_KEM_512_OLD && + groups[i] == WOLFSSL_P256_ML_KEM_512) || + (group == WOLFSSL_P384_ML_KEM_768_OLD && + groups[i] == WOLFSSL_P384_ML_KEM_768) || + (group == WOLFSSL_P521_ML_KEM_1024_OLD && + groups[i] == WOLFSSL_P521_ML_KEM_1024)) { + return i; + } +#endif if (groups[i] == (word16)group) return i; + } return WOLFSSL_FATAL_ERROR; } @@ -10779,6 +10860,7 @@ int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions) TLSX* extension; SupportedCurve* curve = NULL; SupportedCurve* preferredCurve = NULL; + word16 name = WOLFSSL_NAMED_GROUP_INVALID; KeyShareEntry* kse = NULL; int preferredRank = WOLFSSL_MAX_GROUP_COUNT; int rank; @@ -10786,9 +10868,10 @@ int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions) extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS); if (extension != NULL) curve = (SupportedCurve*)extension->data; - /* Use server's preference order. */ for (; curve != NULL; curve = curve->next) { - if (!TLSX_KeyShare_IsSupported(curve->name)) + /* Use server's preference order. Common group was found but key share + * was missing */ + if (!TLSX_IsGroupSupported(curve->name)) continue; if (wolfSSL_curve_is_disabled(ssl, curve->name)) continue; @@ -10804,8 +10887,26 @@ int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions) curve = preferredCurve; if (curve == NULL) { - WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA); - return BAD_KEY_SHARE_DATA; + byte i; + /* Fallback to user selected group */ + preferredRank = WOLFSSL_MAX_GROUP_COUNT; + for (i = 0; i < ssl->numGroups; i++) { + rank = TLSX_KeyShare_GroupRank(ssl, ssl->group[i]); + if (rank == -1) + continue; + if (rank < preferredRank) { + name = ssl->group[i]; + preferredRank = rank; + } + } + if (name == WOLFSSL_NAMED_GROUP_INVALID) { + /* No group selected or specified by the server */ + WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA); + return BAD_KEY_SHARE_DATA; + } + } + else { + name = curve->name; } #ifdef WOLFSSL_ASYNC_CRYPT @@ -10829,7 +10930,7 @@ int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions) /* Extension got pushed to head */ extension = *extensions; /* Push the selected curve */ - ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name, + ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, name, ssl->heap, &kse); if (ret != 0) return ret; @@ -11051,7 +11152,7 @@ int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions, if (wolfSSL_curve_is_disabled(ssl, clientKSE->group)) continue; } - if (!TLSX_KeyShare_IsSupported(clientKSE->group)) + if (!TLSX_IsGroupSupported(clientKSE->group)) continue; rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group); @@ -13100,7 +13201,7 @@ static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte msgType, byte* writeBuf, static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech, byte msgType) { int ret; - word32 size; + word32 size = 0; if (ech->state == ECH_WRITE_GREASE) { size = sizeof(ech->type) + sizeof(ech->cipherSuite) + @@ -14653,7 +14754,7 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) { if (preferredGroup[j] == ssl->group[i] #ifdef HAVE_LIBOQS - && TLSX_KeyShare_IsSupported(preferredGroup[j]) + && TLSX_IsGroupSupported(preferredGroup[j]) #endif ) { namedGroup = ssl->group[i]; @@ -14669,11 +14770,11 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) /* Choose the most preferred group. */ namedGroup = preferredGroup[0]; #ifdef HAVE_LIBOQS - if (!TLSX_KeyShare_IsSupported(namedGroup)) { + if (!TLSX_IsGroupSupported(namedGroup)) { int i = 1; for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID; i++) { - if (TLSX_KeyShare_IsSupported(preferredGroup[i])) + if (TLSX_IsGroupSupported(preferredGroup[i])) break; } namedGroup = preferredGroup[i]; @@ -16048,7 +16149,7 @@ int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType, /* RFC 8446 4.2.4 states trusted_ca_keys is not used in TLS 1.3. */ if (IsAtLeastTLSv1_3(ssl->version)) { - return EXT_NOT_ALLOWED; + break; } else #endif diff --git a/src/src/tls13.c b/src/src/tls13.c index 6efe446..b860c19 100644 --- a/src/src/tls13.c +++ b/src/src/tls13.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1623,9 +1623,42 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) goto end; if (ssl->options.dtls) { + w64wrapper epochNumber; ret = Dtls13DeriveSnKeys(ssl, provision); if (ret != 0) - return ret; + goto end; + + switch (secret) { + case early_data_key: + epochNumber = w64From32(0, DTLS13_EPOCH_EARLYDATA); + break; + case handshake_key: + epochNumber = w64From32(0, DTLS13_EPOCH_HANDSHAKE); + break; + case traffic_key: + case no_key: + epochNumber = w64From32(0, DTLS13_EPOCH_TRAFFIC0); + break; + case update_traffic_key: + if (side == ENCRYPT_SIDE_ONLY) { + epochNumber = ssl->dtls13Epoch; + } + else if (side == DECRYPT_SIDE_ONLY) { + epochNumber = ssl->dtls13PeerEpoch; + } + else { + ret = BAD_STATE_E; + goto end; + } + w64Increment(&epochNumber); + break; + default: + ret = BAD_STATE_E; + goto end; + } + ret = Dtls13NewEpoch(ssl, epochNumber, side); + if (ret != 0) + goto end; } #endif /* WOLFSSL_DTLS13 */ @@ -2236,34 +2269,6 @@ int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store) #endif /* WOLFSSL_32BIT_MILLI_TIME */ #endif /* HAVE_SESSION_TICKET || !NO_PSK */ - -/* Extract the handshake header information. - * - * ssl The SSL/TLS object. - * input The buffer holding the message data. - * inOutIdx On entry, the index into the buffer of the handshake data. - * On exit, the start of the handshake data. - * type Type of handshake message. - * size The length of the handshake message data. - * totalSz The total size of data in the buffer. - * returns BUFFER_E if there is not enough input data and 0 on success. - */ -static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx, - byte* type, word32* size, word32 totalSz) -{ - const byte* ptr = input + *inOutIdx; - (void)ssl; - - *inOutIdx += HANDSHAKE_HEADER_SZ; - if (*inOutIdx > totalSz) - return BUFFER_E; - - *type = ptr[0]; - c24to32(&ptr[1], size); - - return 0; -} - /* Add record layer header to message. * * output The buffer to write the record layer header into. @@ -4111,15 +4116,6 @@ static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx) if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) return ret; -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) { - ret = Dtls13NewEpoch( - ssl, w64From32(0x0, DTLS13_EPOCH_EARLYDATA), ENCRYPT_SIDE_ONLY); - if (ret != 0) - return ret; - } -#endif /* WOLFSSL_DTLS13 */ - } #endif @@ -5053,14 +5049,19 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, byte tls12minor; #ifdef WOLFSSL_ASYNC_CRYPT Dsh13Args* args = NULL; - WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args); #else Dsh13Args args[1]; #endif +#ifdef WOLFSSL_ASYNC_CRYPT + WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args); +#endif WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO); WOLFSSL_ENTER("DoTls13ServerHello"); + if (ssl == NULL || ssl->arrays == NULL) + return BAD_FUNC_ARG; + tls12minor = TLSv1_2_MINOR; #ifdef WOLFSSL_DTLS13 @@ -5068,10 +5069,6 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, tls12minor = DTLSv1_2_MINOR; #endif /* WOLFSSL_DTLS13 */ - - if (ssl == NULL || ssl->arrays == NULL) - return BAD_FUNC_ARG; - #ifdef WOLFSSL_ASYNC_CRYPT if (ssl->async == NULL) { ssl->async = (struct WOLFSSL_ASYNC*) @@ -5145,6 +5142,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, /* Force client hello version 1.2 to work for static RSA. */ ssl->chVersion.minor = TLSv1_2_MINOR; ssl->version.minor = TLSv1_2_MINOR; + ssl->options.tls1_3 = 0; #ifdef WOLFSSL_DTLS13 if (ssl->options.dtls) { @@ -5245,6 +5243,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->options.dtls) { ssl->chVersion.minor = DTLSv1_2_MINOR; ssl->version.minor = DTLSv1_2_MINOR; + ssl->options.tls1_3 = 0; ret = Dtls13ClientDoDowngrade(ssl); if (ret != 0) return ret; @@ -5258,6 +5257,7 @@ int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, return VERSION_ERROR; } #ifndef WOLFSSL_NO_TLS12 + ssl->options.tls1_3 = 0; return DoServerHello(ssl, input, inOutIdx, helloSz); #else SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version); @@ -5964,6 +5964,8 @@ static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, const byte* suite, int* err) WOLFSSL_ENTER("FindPsk"); + XMEMSET(foundSuite, 0, sizeof(foundSuite)); + ret = FindPskSuite(ssl, psk, ssl->arrays->psk_key, &ssl->arrays->psk_keySz, suite, &found, foundSuite); if (ret == 0 && found) { @@ -6321,17 +6323,6 @@ static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz, return ret; ssl->keys.encryptionOn = 1; - -#ifdef WOLFSSL_DTLS13 - if (ssl->options.dtls) { - ret = Dtls13NewEpoch(ssl, - w64From32(0x0, DTLS13_EPOCH_EARLYDATA), - DECRYPT_SIDE_ONLY); - if (ret != 0) - return ret; - } -#endif /* WOLFSSL_DTLS13 */ - ssl->earlyData = process_early_data; } else @@ -7629,11 +7620,6 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE); ssl->dtls13Epoch = epochHandshake; - ret = Dtls13NewEpoch( - ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE); - if (ret != 0) - return ret; - ret = Dtls13SetEpochKeys( ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE); if (ret != 0) @@ -11219,11 +11205,6 @@ static int SendTls13Finished(WOLFSSL* ssl) ssl->dtls13Epoch = epochTraffic0; ssl->dtls13PeerEpoch = epochTraffic0; - ret = Dtls13NewEpoch( - ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE); - if (ret != 0) - return ret; - ret = Dtls13SetEpochKeys( ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE); if (ret != 0) @@ -11261,11 +11242,6 @@ static int SendTls13Finished(WOLFSSL* ssl) ssl->dtls13Epoch = epochTraffic0; ssl->dtls13PeerEpoch = epochTraffic0; - ret = Dtls13NewEpoch( - ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE); - if (ret != 0) - return ret; - ret = Dtls13SetEpochKeys( ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE); if (ret != 0) @@ -11465,10 +11441,6 @@ static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx, if (ssl->options.dtls) { w64Increment(&ssl->dtls13PeerEpoch); - ret = Dtls13NewEpoch(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY); - if (ret != 0) - return ret; - ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY); if (ret != 0) return ret; @@ -12884,11 +12856,6 @@ int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, ssl->dtls13Epoch = epochHandshake; ssl->dtls13PeerEpoch = epochHandshake; - ret = Dtls13NewEpoch( - ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE); - if (ret != 0) - return ret; - ret = Dtls13SetEpochKeys( ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE); if (ret != 0) diff --git a/src/src/wolfio.c b/src/src/wolfio.c index 0809734..b3bb6a8 100644 --- a/src/src/wolfio.c +++ b/src/src/wolfio.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -182,7 +182,7 @@ static WC_INLINE int wolfSSL_LastError(int err, SOCKET_T sd) */ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) { -#ifdef _WIN32 +#if defined(_WIN32) && !defined(__WATCOMC__) && !defined(_WIN32_WCE) size_t errstr_offset; char errstr[WOLFSSL_STRERROR_BUFFER_SIZE]; #endif /* _WIN32 */ @@ -241,7 +241,7 @@ static int TranslateIoReturnCode(int err, SOCKET_T sd, int direction) return WOLFSSL_CBIO_ERR_CONN_CLOSE; } -#if defined(_WIN32) && !defined(__WATCOMC__) +#if defined(_WIN32) && !defined(__WATCOMC__) && !defined(_WIN32_WCE) strcpy_s(errstr, sizeof(errstr), "\tGeneral error: "); errstr_offset = strlen(errstr); FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, diff --git a/src/src/x509.c b/src/src/x509.c index 62e3774..323daa1 100644 --- a/src/src/x509.c +++ b/src/src/x509.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1660,6 +1660,65 @@ int wolfSSL_X509V3_EXT_add_nconf(WOLFSSL_CONF *conf, WOLFSSL_X509V3_CTX *ctx, } #endif +/* Find extension by NID in a stack of extensions. + * + * @param sk Stack of extensions + * @param nid ID to search for + * @param lastpos Start search from this position (not inclusive, -1 means start from beginning) + * @return Index of matching extension or -1 on error/not found + */ +int wolfSSL_X509v3_get_ext_by_NID(const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, + int nid, int lastpos) +{ + int i; + WOLFSSL_ENTER("wolfSSL_X509v3_get_ext_by_NID"); + + if (sk == NULL) { + WOLFSSL_MSG("Stack pointer is NULL"); + return WOLFSSL_FATAL_ERROR; + } + + if (lastpos < -1 || lastpos >= wolfSSL_sk_num(sk)) { + WOLFSSL_MSG("Invalid position argument"); + return WOLFSSL_FATAL_ERROR; + } + + for (i = lastpos + 1; i < wolfSSL_sk_num(sk); i++) { + WOLFSSL_X509_EXTENSION* ext = wolfSSL_sk_X509_EXTENSION_value(sk, i); + if (ext && ext->obj) { + if (wolfSSL_OBJ_obj2nid(ext->obj) == nid) + return i; + } + } + + /* Not found */ + return -1; +} + +/* Get extension from a stack of extensions by location. + * + * @param sk Stack of extensions + * @param loc Index of extension to retrieve + * @return Pointer to extension or NULL on error + */ +WOLFSSL_X509_EXTENSION* wolfSSL_X509v3_get_ext( + const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int loc) +{ + WOLFSSL_ENTER("wolfSSL_X509v3_get_ext"); + + if (sk == NULL) { + WOLFSSL_MSG("Stack pointer is NULL"); + return NULL; + } + + if (loc < 0 || loc >= wolfSSL_sk_num(sk)) { + WOLFSSL_MSG("Invalid location argument"); + return NULL; + } + + return wolfSSL_sk_X509_EXTENSION_value(sk, loc); +} + /* Returns crit flag in X509_EXTENSION object */ int wolfSSL_X509_EXTENSION_get_critical(const WOLFSSL_X509_EXTENSION* ex) { @@ -2349,6 +2408,15 @@ void* wolfSSL_X509_get_ext_d2i(const WOLFSSL_X509* x509, int nid, int* c, } break; + case ASN_IP_TYPE: + if (wolfSSL_ASN1_STRING_set(gn->d.iPAddress, + dns->name, dns->len) != WOLFSSL_SUCCESS) { + WOLFSSL_MSG("ASN1_STRING_set failed"); + goto err; + } + gn->d.iPAddress->type = WOLFSSL_V_ASN1_OCTET_STRING; + break; + default: if (wolfSSL_ASN1_STRING_set(gn->d.dNSName, dns->name, dns->len) != WOLFSSL_SUCCESS) { @@ -5498,7 +5566,7 @@ int wolfSSL_X509_NAME_get_text_by_NID(WOLFSSL_X509_NAME* name, WOLFSSL_EVP_PKEY* wolfSSL_X509_get_pubkey(WOLFSSL_X509* x509) { WOLFSSL_EVP_PKEY* key = NULL; - int ret; + int ret = 0; (void)ret; @@ -6414,8 +6482,7 @@ static int X509PrintSerial_ex(WOLFSSL_BIO* bio, byte* serial, int sz, scratch + scratchLen, scratchSz - scratchLen, "%02x%s", serial[i], (i < sz - 1) ? (delimiter ? ":" : "") : "\n")) - >= scratchSz - scratchLen) - { + >= scratchSz - scratchLen) { WOLFSSL_MSG("buffer overrun"); return WOLFSSL_FAILURE; } @@ -6428,10 +6495,8 @@ static int X509PrintSerial_ex(WOLFSSL_BIO* bio, byte* serial, int sz, /* if serial can fit into byte then print on the same line */ else { - if ((scratchLen = XSNPRINTF( - scratch, MAX_WIDTH, " %d (0x%x)\n", serial[0], serial[0])) - >= MAX_WIDTH) - { + if ((scratchLen = XSNPRINTF(scratch, MAX_WIDTH, " %d (0x%x)\n", + (char)serial[0], serial[0])) >= MAX_WIDTH) { WOLFSSL_MSG("buffer overrun"); return WOLFSSL_FAILURE; } @@ -6554,8 +6619,7 @@ static int X509PrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509* x509, int indent) return WOLFSSL_FAILURE; } - buf = (char*)XMALLOC(MAX_WIDTH-4-indent, x509->heap, - DYNAMIC_TYPE_TMP_BUFFER); + buf = (char*)XMALLOC(MAX_WIDTH, x509->heap, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { return WOLFSSL_FAILURE; } @@ -8871,85 +8935,135 @@ static int X509CRLPrintExtensions(WOLFSSL_BIO* bio, WOLFSSL_X509_CRL* crl, int indent) { char tmp[MAX_WIDTH]; /* buffer for XSNPRINTF */ + int ret = 0; if (XSNPRINTF(tmp, MAX_WIDTH, "%*s%s\n", indent, "", "CRL extensions:") >= MAX_WIDTH) { - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + if (ret == 0 && wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + ret = WOLFSSL_FAILURE; } - if (crl->crlList->crlNumber) { - if (XSNPRINTF(tmp, MAX_WIDTH, "%*s%s\n", indent + 4, "", + if (ret == 0 && crl->crlList->crlNumberSet) { + char dec_string[49]; /* 20 octets can express numbers up to approx + 49 decimal digits */ + int freeMp = 0; + #ifdef WOLFSSL_SMALL_STACK + mp_int* dec_num = (mp_int*)XMALLOC(sizeof(*dec_num), NULL, + DYNAMIC_TYPE_BIGINT); + if (dec_num == NULL) { + ret = MEMORY_E; + } + #else + mp_int dec_num[1]; + #endif + + if (ret == 0 && (mp_init(dec_num) != MP_OKAY)) { + ret = MP_INIT_E; + } + else if (ret == 0) { + freeMp = 1; + } + + if (ret == 0 && mp_read_radix(dec_num, (char *)crl->crlList->crlNumber, + MP_RADIX_HEX) != MP_OKAY) { + ret = WOLFSSL_FAILURE; + } + + if (ret == 0 && mp_toradix(dec_num, dec_string, MP_RADIX_DEC) + != MP_OKAY) { + ret = WOLFSSL_FAILURE; + } + + if (ret == 0 && XSNPRINTF(tmp, MAX_WIDTH, "%*s%s\n", indent + 4, "", "X509v3 CRL Number:") >= MAX_WIDTH) { - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + if (ret == 0 && wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + ret = WOLFSSL_FAILURE; } - if (XSNPRINTF(tmp, MAX_WIDTH, "%*s%d\n", indent + 8, "", - crl->crlList->crlNumber) >= MAX_WIDTH) - { - return WOLFSSL_FAILURE; + if (ret == 0 && XSNPRINTF(tmp, MAX_WIDTH, "%*s%s\n", indent + 8, "", + dec_string) >= MAX_WIDTH) { + ret = WOLFSSL_FAILURE; } - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + + if (ret == 0 && wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + ret = WOLFSSL_FAILURE; } + XMEMSET(tmp, 0, sizeof(tmp)); + + if (freeMp) { + mp_free(dec_num); + } + + #ifdef WOLFSSL_SMALL_STACK + XFREE(dec_num, NULL, DYNAMIC_TYPE_BIGINT); + #endif } #if !defined(NO_SKID) - if (crl->crlList->extAuthKeyIdSet && crl->crlList->extAuthKeyId[0] != 0) { + if (ret == 0 && crl->crlList->extAuthKeyIdSet && + crl->crlList->extAuthKeyId[0] != 0) { word32 i; char val[5]; int valSz = 5; if (XSNPRINTF(tmp, MAX_WIDTH, "%*s%s", indent + 4, "", "X509v3 Authority Key Identifier:") >= MAX_WIDTH) { - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; } - XSTRNCAT(tmp, "\n", MAX_WIDTH - XSTRLEN(tmp) - 1); + if (ret == 0) { + XSTRNCAT(tmp, "\n", MAX_WIDTH - XSTRLEN(tmp) - 1); + } - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + if (ret == 0 && wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + ret = WOLFSSL_FAILURE; } XMEMSET(tmp, 0, MAX_WIDTH); - if (XSNPRINTF(tmp, MAX_WIDTH - 1, "%*s%s", + if (ret == 0 && XSNPRINTF(tmp, MAX_WIDTH - 1, "%*s%s", indent + 8, "", "keyid") >= MAX_WIDTH) { - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; } for (i = 0; i < XSTRLEN((char*)crl->crlList->extAuthKeyId); i++) { /* check if buffer is almost full */ - if (XSTRLEN(tmp) >= sizeof(tmp) - valSz) { + if (ret == 0 && XSTRLEN(tmp) >= sizeof(tmp) - valSz) { if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; } tmp[0] = '\0'; } - if (XSNPRINTF(val, (size_t)valSz, ":%02X", - crl->crlList->extAuthKeyId[i]) >= valSz) - { + if (ret == 0 && XSNPRINTF(val, (size_t)valSz, ":%02X", + crl->crlList->extAuthKeyId[i]) >= valSz) { WOLFSSL_MSG("buffer overrun"); - return WOLFSSL_FAILURE; + ret = WOLFSSL_FAILURE; + } + if (ret == 0) { + XSTRNCAT(tmp, val, valSz); } - XSTRNCAT(tmp, val, valSz); } - XSTRNCAT(tmp, "\n", XSTRLEN("\n") + 1); - if (wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { - return WOLFSSL_FAILURE; + if (ret == 0) { + XSTRNCAT(tmp, "\n", XSTRLEN("\n") + 1); + } + if (ret == 0 && wolfSSL_BIO_write(bio, tmp, (int)XSTRLEN(tmp)) <= 0) { + ret = WOLFSSL_FAILURE; } } #endif - return WOLFSSL_SUCCESS; + if (ret == 0) { + ret = WOLFSSL_SUCCESS; + } + + return ret; } /* iterate through a CRL's Revoked Certs and print out in human @@ -9181,7 +9295,7 @@ void wolfSSL_X509_CRL_free(WOLFSSL_X509_CRL *crl) } #endif /* HAVE_CRL && (OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL) */ -#ifdef OPENSSL_EXTRA +#if defined(HAVE_CRL) && defined(OPENSSL_EXTRA) WOLFSSL_ASN1_TIME* wolfSSL_X509_CRL_get_lastUpdate(WOLFSSL_X509_CRL* crl) { if ((crl != NULL) && (crl->crlList != NULL) && @@ -9211,7 +9325,7 @@ int wolfSSL_X509_CRL_verify(WOLFSSL_X509_CRL* crl, WOLFSSL_EVP_PKEY* key) return 0; } #endif -#endif /* OPENSSL_EXTRA */ +#endif /* HAVE_CRL && OPENSSL_EXTRA */ #ifdef OPENSSL_EXTRA @@ -10682,6 +10796,26 @@ static int CertFromX509(Cert* cert, WOLFSSL_X509* x509) cert->altSigValLen = x509->altSigValLen; cert->altSigValCrit = x509->altSigValCrit; #endif /* WOLFSSL_DUAL_ALG_CERTS */ + +#if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CUSTOM_OID) && \ + defined(HAVE_OID_ENCODING) + + if ((x509->customExtCount < 0) || + (x509->customExtCount >= NUM_CUSTOM_EXT)) { + WOLFSSL_MSG("Bad value for customExtCount."); + return WOLFSSL_FAILURE; + } + + for (i = 0; i < x509->customExtCount; i++) { + if (wc_SetCustomExtension(cert, x509->custom_exts[i].crit, + x509->custom_exts[i].oid, x509->custom_exts[i].val, + x509->custom_exts[i].valSz)) + { + return WOLFSSL_FAILURE; + } + } +#endif /* WOLFSSL_ASN_TEMPLATE && WOLFSSL_CUSTOM_OID && HAVE_OID_ENCODING */ + #endif /* WOLFSSL_CERT_EXT */ #ifdef WOLFSSL_CERT_REQ @@ -13819,7 +13953,7 @@ int wolfSSL_X509_NAME_print_ex(WOLFSSL_BIO* bio, WOLFSSL_X509_NAME* name, WOLFSSL_ENTER("wolfSSL_X509_NAME_print_ex"); - if ((name == NULL) || (name->sz == 0) || (bio == NULL)) + if ((name == NULL) || (bio == NULL)) return WOLFSSL_FAILURE; XMEMSET(eqStr, 0, sizeof(eqStr)); diff --git a/src/src/x509_str.c b/src/src/x509_str.c index fedf4a0..4571b95 100644 --- a/src/src/x509_str.c +++ b/src/src/x509_str.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -405,7 +405,7 @@ static int addAllButSelfSigned(WOLF_STACK_OF(WOLFSSL_X509)*to, } /* Verifies certificate chain using WOLFSSL_X509_STORE_CTX - * returns 0 on success or < 0 on failure. + * returns 1 on success or <= 0 on failure. */ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) { @@ -577,17 +577,35 @@ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) #endif /* OPENSSL_EXTRA */ -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) - WOLFSSL_X509* wolfSSL_X509_STORE_CTX_get_current_cert( - WOLFSSL_X509_STORE_CTX* ctx) - { - WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_current_cert"); - if (ctx) - return ctx->current_cert; - return NULL; +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +WOLFSSL_X509* wolfSSL_X509_STORE_CTX_get_current_cert( + WOLFSSL_X509_STORE_CTX* ctx) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_current_cert"); + if (ctx) + return ctx->current_cert; + return NULL; +} + +/* get X509_STORE_CTX ex_data, max idx is MAX_EX_DATA */ +void* wolfSSL_X509_STORE_CTX_get_ex_data(WOLFSSL_X509_STORE_CTX* ctx, int idx) +{ + WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_ex_data"); +#ifdef HAVE_EX_DATA + if (ctx != NULL) { + return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); } +#else + (void)ctx; + (void)idx; +#endif + return NULL; +} +#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_EXTRA) int wolfSSL_X509_STORE_CTX_get_error(WOLFSSL_X509_STORE_CTX* ctx) { WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_error"); @@ -596,30 +614,14 @@ int wolfSSL_X509_verify_cert(WOLFSSL_X509_STORE_CTX* ctx) return 0; } - int wolfSSL_X509_STORE_CTX_get_error_depth(WOLFSSL_X509_STORE_CTX* ctx) { WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_error_depth"); - if(ctx) + if (ctx) return ctx->error_depth; return WOLFSSL_FATAL_ERROR; } - -/* get X509_STORE_CTX ex_data, max idx is MAX_EX_DATA */ -void* wolfSSL_X509_STORE_CTX_get_ex_data(WOLFSSL_X509_STORE_CTX* ctx, int idx) -{ - WOLFSSL_ENTER("wolfSSL_X509_STORE_CTX_get_ex_data"); -#ifdef HAVE_EX_DATA - if (ctx != NULL) { - return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx); - } -#else - (void)ctx; - (void)idx; #endif - return NULL; -} -#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */ #ifdef OPENSSL_EXTRA void wolfSSL_X509_STORE_CTX_set_verify_cb(WOLFSSL_X509_STORE_CTX *ctx, diff --git a/src/user_settings.h b/src/user_settings.h index e8d05fa..1d60188 100644 --- a/src/user_settings.h +++ b/src/user_settings.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/aes.c b/src/wolfcrypt/src/aes.c index 6e7f104..de6a428 100644 --- a/src/wolfcrypt/src/aes.c +++ b/src/wolfcrypt/src/aes.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -8345,19 +8345,22 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( } XMEMCPY(ctrInit, ctr, sizeof(ctr)); /* save off initial counter for GMAC */ - /* Authentication buffer - must be 4-byte multiple zero padded */ - authPadSz = authInSz % sizeof(word32); + /* Authentication buffer */ +#if STM_CRYPT_HEADER_WIDTH == 1 + authPadSz = 0; /* CubeHAL supports byte mode */ +#else + authPadSz = authInSz % STM_CRYPT_HEADER_WIDTH; +#endif #ifdef WOLFSSL_STM32MP13 /* STM32MP13 HAL at least v1.2 and lower has a bug with which it needs a - * minimum of 16 bytes for the auth - */ + * minimum of 16 bytes for the auth */ if ((authInSz > 0) && (authInSz < 16)) { authPadSz = 16 - authInSz; } #endif if (authPadSz != 0) { - if (authPadSz < authInSz + sizeof(word32)) { - authPadSz = authInSz + sizeof(word32) - authPadSz; + if (authPadSz < authInSz + STM_CRYPT_HEADER_WIDTH) { + authPadSz = authInSz + STM_CRYPT_HEADER_WIDTH - authPadSz; } if (authPadSz <= sizeof(authhdr)) { authInPadded = (byte*)authhdr; @@ -8385,7 +8388,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if !defined(STM_CRYPT_HEADER_WIDTH) || STM_CRYPT_HEADER_WIDTH == 4 + #if STM_CRYPT_HEADER_WIDTH == 4 /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8444,7 +8447,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmEncrypt_STM32( /* Set the CRYP parameters */ hcryp.Init.HeaderSize = authPadSz; if (authPadSz == 0) - hcryp.Init.Header = NULL; /* cannot pass pointer here when authIn == 0 */ + hcryp.Init.Header = NULL; /* cannot pass pointer when authIn == 0 */ hcryp.Init.ChainingMode = CRYP_CHAINMODE_AES_GCM_GMAC; hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT; hcryp.Init.GCMCMACPhase = CRYP_INIT_PHASE; @@ -8884,22 +8887,25 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( * For TLS blocks the authTag is after the output buffer, so save it */ XMEMCPY(tagExpected, authTag, authTagSz); - /* Authentication buffer - must be 4-byte multiple zero padded */ - authPadSz = authInSz % sizeof(word32); - if (authPadSz != 0) { - authPadSz = authInSz + sizeof(word32) - authPadSz; - } - else { - authPadSz = authInSz; - } - + /* Authentication buffer */ +#if STM_CRYPT_HEADER_WIDTH == 1 + authPadSz = 0; /* CubeHAL supports byte mode */ +#else + authPadSz = authInSz % STM_CRYPT_HEADER_WIDTH; +#endif #ifdef WOLFSSL_STM32MP13 /* STM32MP13 HAL at least v1.2 and lower has a bug with which it needs a - * minimum of 16 bytes for the auth - */ + * minimum of 16 bytes for the auth */ if ((authInSz > 0) && (authInSz < 16)) { authPadSz = 16 - authInSz; } +#else + if (authPadSz != 0) { + authPadSz = authInSz + STM_CRYPT_HEADER_WIDTH - authPadSz; + } + else { + authPadSz = authInSz; + } #endif /* for cases where hardware cannot be used for authTag calculate it */ @@ -8909,7 +8915,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( /* or hardware that does not support partial block */ || sz == 0 || partial != 0 #endif - #if !defined(STM_CRYPT_HEADER_WIDTH) || STM_CRYPT_HEADER_WIDTH == 4 + #if STM_CRYPT_HEADER_WIDTH == 4 /* or authIn is not a multiple of 4 */ || authPadSz != authInSz #endif @@ -8949,6 +8955,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( if (ret != 0) { return ret; } + #ifdef WOLFSSL_STM32_CUBEMX hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr; hcryp.Init.Header = (STM_CRYPT_TYPE*)authInPadded; @@ -8956,7 +8963,6 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( #if defined(STM32_HAL_V2) hcryp.Init.Algorithm = CRYP_AES_GCM; hcryp.Init.HeaderSize = authPadSz / STM_CRYPT_HEADER_WIDTH; - #ifdef CRYP_KEYIVCONFIG_ONCE /* allows repeated calls to HAL_CRYP_Decrypt */ hcryp.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE; @@ -8966,6 +8972,7 @@ static WARN_UNUSED_RESULT int wc_AesGcmDecrypt_STM32( HAL_CRYP_Init(&hcryp); #ifndef CRYP_KEYIVCONFIG_ONCE + /* GCM payload phase - can handle partial blocks */ status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, (blocks * WC_AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT); #else diff --git a/src/wolfcrypt/src/arc4.c b/src/wolfcrypt/src/arc4.c index a877d8b..da997f6 100644 --- a/src/wolfcrypt/src/arc4.c +++ b/src/wolfcrypt/src/arc4.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ascon.c b/src/wolfcrypt/src/ascon.c index 248d06a..4ddbcfc 100644 --- a/src/wolfcrypt/src/ascon.c +++ b/src/wolfcrypt/src/ascon.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/asm.c b/src/wolfcrypt/src/asm.c index a724114..b061bb3 100644 --- a/src/wolfcrypt/src/asm.c +++ b/src/wolfcrypt/src/asm.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/asn.c b/src/wolfcrypt/src/asn.c index af74678..ec34c95 100644 --- a/src/wolfcrypt/src/asn.c +++ b/src/wolfcrypt/src/asn.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -359,6 +359,30 @@ WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output) return i; } +#ifdef WC_ASN_RUNTIME_DATE_CHECK_CONTROL +static int AsnSkipDateCheck = 0; +int wc_AsnSetSkipDateCheck(int skip_p) +{ + AsnSkipDateCheck = (skip_p != 0); + return 0; +} +int wc_AsnGetSkipDateCheck(void) +{ + return AsnSkipDateCheck; +} +#else +#define AsnSkipDateCheck 0 +int wc_AsnSetSkipDateCheck(int skip_p) +{ + (void)skip_p; + return NOT_COMPILED_IN; +} +int wc_AsnGetSkipDateCheck(void) +{ + return 0; +} +#endif + #ifdef WOLFSSL_ASN_TEMPLATE /* Calculate the size of a DER encoded length value. * @@ -3252,22 +3276,35 @@ int SetShortInt(byte* output, word32* inOutIdx, word32 number, word32 maxIdx) word32 idx = *inOutIdx; word32 len; int i; + word32 extraByte = 0; if (number == 0) len = 1; else len = BytePrecision(number); + /* clarify the len range to prepare for the next right bit shifting */ + if (len < 1 || len > sizeof(number)) { + return ASN_PARSE_E; + } + if (number >> (WOLFSSL_BIT_SIZE * len - 1)) { + /* Need one byte of zero value not to be negative number */ + extraByte = 1; + } + /* check for room for type and length bytes. */ - if ((idx + 2 + len) > maxIdx) + if ((idx + 2 + extraByte + len) > maxIdx) return BUFFER_E; /* check that MAX_SHORT_SZ allows this size of ShortInt. */ - if (2 + len > MAX_SHORT_SZ) + if (2 + extraByte + len > MAX_SHORT_SZ) return ASN_PARSE_E; output[idx++] = ASN_INTEGER; - output[idx++] = (byte)len; + output[idx++] = (byte)(len + extraByte); + if (extraByte) { + output[idx++] = 0x00; + } for (i = (int)len - 1; i >= 0; --i) output[idx++] = (byte)(number >> (i * WOLFSSL_BIT_SIZE)); @@ -6670,6 +6707,7 @@ static int DumpOID(const byte* oidData, word32 oidSz, word32 oid, } #endif /* ASN_DUMP_OID */ +#ifdef WOLFSSL_OLD_OID_SUM #ifdef WOLFSSL_FPKI /* Handles the large number of collisions from FPKI certificate policy * OID sums. Returns a special value (100000 + actual sum) if a @@ -6831,8 +6869,39 @@ static word32 fpkiCertPolOid(const byte* oid, word32 oidSz, word32 oidSum) { return 0; } +#endif +#endif /* WOLFSSL_OLD_OID_SUM */ + +word32 wc_oid_sum(const byte* input, int length) +{ + int i; + word32 oid = 0; +#ifndef WOLFSSL_OLD_OID_SUM + int shift = 0; +#endif + + /* Check for valid input. */ + if (input == NULL || length > MAX_OID_SZ) { + WOLFSSL_MSG("wc_oid_sum: invalid args"); + return 0; + } + + /* Sum it up for now. */ + for (i = 0; i < length; i++) { + #ifdef WOLFSSL_OLD_OID_SUM + oid += (word32)input[i]; + #else + oid ^= ((word32)(~input[i])) << shift; + shift = (shift + 8) & 0x1f; + #endif + } +#ifndef WOLFSSL_OLD_OID_SUM + oid &= 0x7fffffff; #endif + return oid; +} + /* Get the OID data and verify it is of the type specified when compiled in. * * @param [in] input Buffer holding OID. @@ -6858,8 +6927,10 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, const byte* checkOid = NULL; word32 checkOidSz; #endif /* NO_VERIFY_OID */ +#ifdef WOLFSSL_OLD_OID_SUM #if defined(HAVE_SPHINCS) || defined(WOLFSSL_FPKI) word32 found_collision = 0; +#endif #endif (void)oidType; *oid = 0; @@ -6870,6 +6941,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, actualOidSz = (word32)length; #endif /* NO_VERIFY_OID */ +#ifdef WOLFSSL_OLD_OID_SUM #if defined(HAVE_SPHINCS) /* Since we are summing it up, there could be collisions...and indeed there * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3. @@ -6885,14 +6957,12 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, found_collision = SPHINCS_FAST_LEVEL3k; } #endif /* HAVE_SPHINCS */ +#endif - /* Sum it up for now. */ - while (length--) { - /* odd HC08 compiler behavior here when input[idx++] */ - *oid += (word32)input[idx]; - idx++; - } + *oid = wc_oid_sum(actualOid, (int)actualOidSz); + idx += actualOidSz; +#ifdef WOLFSSL_OLD_OID_SUM #ifdef WOLFSSL_FPKI /* Due to the large number of OIDs for FPKI certificate policy, there are multiple collsisions. Handle them in a dedicated function, @@ -6907,6 +6977,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, *oid = found_collision; } #endif /* HAVE_SPHINCS */ +#endif /* Return the index after the OID data. */ *inOutIdx = idx; @@ -6917,6 +6988,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, /* Get the OID data for the id-type. */ checkOid = OidFromId(*oid, oidType, &checkOidSz); +#ifdef WOLFSSL_OLD_OID_SUM #if defined(WOLFSSL_FPKI) /* Handle OID sum collision of AES256CBCb (454) 2.16.840.1.101.3.4.1.42 @@ -6932,6 +7004,7 @@ static int GetOID(const byte* input, word32* inOutIdx, word32* oid, } #endif /* HAVE_AES_CBC */ #endif /* WOLFSSL_FPKI */ +#endif #ifdef ASN_DUMP_OID /* Dump out the data for debug. */ @@ -8310,11 +8383,16 @@ int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, ret = BAD_FUNC_ARG; } +#ifndef WOLFSSL_NO_ASN_STRICT /* Sanity check: make sure key doesn't have PKCS #8 header. */ if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) { (void)tmpAlgId; ret = ASN_PARSE_E; } +#else + (void)keyIdx; + (void)tmpAlgId; +#endif CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length-1, ret, NULL); @@ -9501,10 +9579,10 @@ static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id, return ret; } -int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, +int wc_EncryptPKCS8Key_ex(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int pbeOid, - int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, - void* heap) + int encAlgId, byte* salt, word32 saltSz, int itt, int hmacOid, + WC_RNG* rng, void* heap) { #ifdef WOLFSSL_SMALL_STACK byte* saltTmp = NULL; @@ -9528,10 +9606,14 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, byte cbcIv[MAX_IV_SIZE]; word32 idx = 0; word32 encIdx = 0; + const byte* hmacOidBuf = NULL; + word32 hmacOidBufSz = 0; + byte tmpShort[MAX_SHORT_SZ]; + word32 tmpIdx = 0; (void)heap; - WOLFSSL_ENTER("wc_EncryptPKCS8Key"); + WOLFSSL_ENTER("wc_EncryptPKCS8Key_ex"); if (key == NULL || outSz == NULL || password == NULL) { ret = BAD_FUNC_ARG; @@ -9550,15 +9632,25 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, if (ret == 0) { padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) & (blockSz - 1)); - /* inner = OCT salt INT itt */ - innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3)); - + ret = SetShortInt(tmpShort, &tmpIdx, (word32)itt, MAX_SHORT_SZ); + if (ret > 0) { + /* inner = OCT salt INT itt */ + innerLen = 2 + saltSz + (word32)ret; + ret = 0; + } + } + if (ret == 0) { if (version != PKCS5v2) { pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz); /* pbe = OBJ pbse1 SEQ [ inner ] */ pbeLen = 2 + pbeOidBufSz + 2 + innerLen; } else { + if (hmacOid > 0) { + hmacOidBuf = OidFromId((word32)hmacOid, oidHmacType, + &hmacOidBufSz); + innerLen += 2 + 2 + hmacOidBufSz; + } pbeOidBuf = pbes2; pbeOidBufSz = sizeof(pbes2); /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */ @@ -9615,7 +9707,7 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, } if (ret == 0) { ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId, - out + encIdx, (int)keySz, version, cbcIv, 1, 0); + out + encIdx, (int)keySz, version, cbcIv, 1, hmacOid); } if (ret == 0) { if (version != PKCS5v2) { @@ -9645,6 +9737,14 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, ret = SetShortInt(out, &idx, (word32)itt, *outSz); if (ret > 0) ret = 0; + if (version == PKCS5v2) { + if (hmacOid > 0) { + idx += SetSequence(2+hmacOidBufSz, out + idx); + idx += (word32)SetObjectId((int)hmacOidBufSz, out + idx); + XMEMCPY(out + idx, hmacOidBuf, hmacOidBufSz); + idx += (word32)hmacOidBufSz; + } + } } if (ret == 0) { if (version == PKCS5v2) { @@ -9669,11 +9769,20 @@ int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER); #endif - WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret); + WOLFSSL_LEAVE("wc_EncryptPKCS8Key_ex", ret); return ret; } +int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, + const char* password, int passwordSz, int vPKCS, int pbeOid, + int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, + void* heap) +{ + return wc_EncryptPKCS8Key_ex(key, keySz, out, outSz, password, passwordSz, + vPKCS, pbeOid, encAlgId, salt, saltSz, itt, 0, rng, heap); +} + int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password, int passwordSz) { @@ -9716,10 +9825,10 @@ int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password, * encrypted key. If out is not NULL, it will hold the encrypted key. If it's * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out * buffer size. */ -int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, +int TraditionalEnc_ex(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int vAlgo, - int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, - void* heap) + int encAlgId, byte* salt, word32 saltSz, int itt, int hmacOid, + WC_RNG* rng, void* heap) { int ret = 0; byte *pkcs8Key = NULL; @@ -9759,8 +9868,9 @@ int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, } #endif if (ret == 0) { - ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password, - passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap); + ret = wc_EncryptPKCS8Key_ex(pkcs8Key, pkcs8KeySz, out, outSz, password, + passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, hmacOid, rng, + heap); } if (pkcs8Key != NULL) { @@ -9773,6 +9883,20 @@ int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, return ret; } +/* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8 + * encrypted key. If out is not NULL, it will hold the encrypted key. If it's + * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out + * buffer size. */ +int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, + const char* password, int passwordSz, int vPKCS, int vAlgo, + int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, + void* heap) +{ + return TraditionalEnc_ex(key, keySz, out, outSz, password, passwordSz, + vPKCS, vAlgo, encAlgId, salt, saltSz, itt, 0, rng, heap); + +} + /* Same as TraditionalEnc, but in the public API. */ int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, @@ -10131,6 +10255,214 @@ int ToTraditionalEnc(byte* input, word32 sz, const char* password, #ifdef HAVE_PKCS12 +#ifdef WOLFSSL_ASN_TEMPLATE +/* ASN.1 template for PKCS #8 encrypted key with PBES2 parameters. + * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo + * PKCS #5: RFC 8018, A.4 - PBES2 + */ +static const ASNItem p8EncPbes2ASN[] = { +/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 }, +/* ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 }, + /* PBE algorithm */ +/* ALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALGO_PARAMS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 }, +/* ALGO_PARAMS_KDF_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 }, + /* PBKDF2 */ +/* ALGO_PARAMS_KDF_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALGO_PARAMS_PBKDF2_SEQ */ { 4, ASN_SEQUENCE, 1, 1, 0 }, + /* Salt */ +/* ALGO_PARAMS_PBKDF2_SALT */ { 5, ASN_OCTET_STRING, 0, 0, 0 }, + /* Iteration count */ +/* ALGO_PARAMS_PBKDF2_ITER */ { 5, ASN_INTEGER, 0, 0, 0 }, + /* Key length */ +/* ALGO_PARAMS_PBKDF2_KEYLEN */ { 5, ASN_INTEGER, 0, 0, 1 }, + /* PRF - default is HMAC-SHA1 */ +/* ALGO_PARAMS_PBKDF2_PRF */ { 5, ASN_SEQUENCE, 1, 1, 1 }, +/* ALGO_PARAMS_PBKDF2_PRF_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 }, +/* ALGO_PARAMS_PBKDF2_PRF_NULL */ { 6, ASN_TAG_NULL, 0, 0, 1 }, +/* ALGO_ENCS_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 }, + /* Encryption algorithm */ +/* ALGO_ENCS_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 }, + /* IV for CBC */ +/* ALGO_ENCS_PARAMS */ { 4, ASN_OCTET_STRING, 0, 0, 0 }, +/* ENCDATA */ { 1, (ASN_CONTEXT_SPECIFIC | 0), 0, 0, 0 }, +}; +enum { + P8ENCPBES2ASN_IDX_SEQ = 0, + P8ENCPBES2ASN_IDX_ALGO_SEQ, + P8ENCPBES2ASN_IDX_ALGO_OID, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_SEQ, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_KDF_SEQ, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_KDF_OID, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_SEQ, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_SALT, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_ITER, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_KEYLEN, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF_OID, + P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF_NULL, + P8ENCPBES2ASN_IDX_ALGO_ENCS_SEQ, + P8ENCPBES2ASN_IDX_ALGO_ENCS_OID, + P8ENCPBES2ASN_IDX_ALGO_ENCS_PARAMS, + P8ENCPBES2ASN_IDX_ENCDATA +}; + +#define p8EncPbes2ASN_Length (sizeof(p8EncPbes2ASN) / sizeof(ASNItem)) +#endif /* WOLFSSL_ASN_TEMPLATE */ + +static int EncryptContentPBES2(byte* input, word32 inputSz, byte* out, + word32* outSz, const char* password, int passwordSz, int encAlgId, + byte* salt, word32 saltSz, int itt, int hmacOid, WC_RNG* rng, + void* heap) +{ + int ret = 0; +#ifndef WOLFSSL_ASN_TEMPLATE + (void)input; + (void)inputSz; + (void)out; + (void)outSz; + (void)password; + (void)passwordSz; + (void)encAlgId; + (void)salt; + (void)saltSz; + (void)itt; + (void)hmacOid; + (void)rng; + (void)heap; + ret = ASN_VERSION_E; +#else /* WOLFSSL_ASN_TEMPLATE */ + /* PBES2 is only supported when enabling the ASN template */ + + DECL_ASNSETDATA(dataASN, p8EncPbes2ASN_Length); + const byte* blkOidBuf = NULL; + int blkOidSz = 0; + int pbesId = -1; + int blockSz = 0; + int asnSz = 0; + word32 pkcs8Sz = 0; + byte* cbcIv = NULL; + byte* saltEnc = NULL; + int genSalt = (salt == NULL || saltSz == 0); + + WOLFSSL_ENTER("EncryptContentPBES2"); + + /* Must have a output size to return or check. */ + if (outSz == NULL) { + ret = BAD_FUNC_ARG; + } + if ((ret == 0) && genSalt) { + salt = NULL; + saltSz = PKCS5V2_SALT_SZ; + /* Salt generated into encoding below. */ + } + /* Check salt size is valid. */ + if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) { + ret = ASN_PARSE_E; + } + if ((ret == 0) && GetAlgoV2(encAlgId, &blkOidBuf, &blkOidSz, &pbesId, + &blockSz) < 0) { + ret = ASN_INPUT_E; + } + CALLOC_ASNSETDATA(dataASN, p8EncPbes2ASN_Length, ret, heap); + + if (ret == 0) { + /* Setup data to go into encoding including PBE algorithm, salt, + * iteration count, and padded key length. */ + SetASN_OID(&dataASN[P8ENCPBES2ASN_IDX_ALGO_OID], (word32)PBES2, + oidPBEType); + SetASN_Buffer(&dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_KDF_OID], + pbkdf2Oid, sizeof(pbkdf2Oid)); + SetASN_Buffer(&dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_SALT], NULL, + saltSz); + SetASN_Int16Bit(&dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_ITER], + (word16)itt); + dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_KEYLEN].noOut = 1; + if (hmacOid > 0) { + const byte* hmacOidBuf = NULL; + word32 hmacOidSz = 0; + hmacOidBuf = OidFromId((word32)hmacOid, oidHmacType, &hmacOidSz); + if (hmacOidBuf == NULL) { + ret = ASN_PARSE_E; + } + if (ret == 0) { + SetASN_Buffer( + &dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF_OID], + hmacOidBuf, hmacOidSz); + } + } + else { + /* SHA1 will be used as default without PRF parameters */ + dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF].noOut = 1; + dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF_OID].noOut = 1; + dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_PRF_NULL].noOut = 1; + } + SetASN_Buffer(&dataASN[P8ENCPBES2ASN_IDX_ALGO_ENCS_OID], blkOidBuf, + blkOidSz); + SetASN_Buffer(&dataASN[P8ENCPBES2ASN_IDX_ALGO_ENCS_PARAMS], NULL, + blockSz); + pkcs8Sz = wc_PkcsPad(NULL, inputSz, (word32)blockSz); + SetASN_Buffer(&dataASN[P8ENCPBES2ASN_IDX_ENCDATA], NULL, pkcs8Sz); + + /* Calculate size of encoding. */ + ret = SizeASN_Items(p8EncPbes2ASN + P8ENCPBES2ASN_IDX_ALGO_SEQ, + dataASN + P8ENCPBES2ASN_IDX_ALGO_SEQ, + (int)(p8EncPbes2ASN_Length - P8ENCPBES2ASN_IDX_ALGO_SEQ), + &asnSz); + } + /* Return size when no output buffer. */ + if ((ret == 0) && (out == NULL)) { + *outSz = (word32)asnSz; + ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E); + } + /* Check output buffer is big enough for encoded data. */ + if ((ret == 0) && (asnSz > (int)*outSz)) { + ret = BAD_FUNC_ARG; + } + if (ret == 0) { + /* Encode PKCS#8 key. */ + SetASN_Items(p8EncPbes2ASN + P8ENCPBES2ASN_IDX_ALGO_SEQ, + dataASN + P8ENCPBES2ASN_IDX_ALGO_SEQ, + (int)(p8EncPbes2ASN_Length - P8ENCPBES2ASN_IDX_ALGO_SEQ), + out); + + saltEnc = (byte*) + dataASN[P8ENCPBES2ASN_IDX_ALGO_PARAMS_PBKDF2_SALT].data.buffer.data; + if (genSalt) { + /* Generate salt into encoding. */ + ret = wc_RNG_GenerateBlock(rng, saltEnc, saltSz); + } + else { + XMEMCPY(saltEnc, salt, saltSz); + } + } + if (ret == 0) { + cbcIv = (byte*) + dataASN[P8ENCPBES2ASN_IDX_ALGO_ENCS_PARAMS].data.buffer.data; + ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz); + } + if (ret == 0) { + /* Store PKCS#8 key in output buffer. */ + byte* pkcs8 = (byte*) + dataASN[P8ENCPBES2ASN_IDX_ENCDATA].data.buffer.data; + XMEMCPY(pkcs8, input, inputSz); + (void)wc_PkcsPad(pkcs8, inputSz, (word32)blockSz); + + /* Encrypt PKCS#8 key inline. */ + ret = wc_CryptKey(password, passwordSz, saltEnc, (int)saltSz, itt, + pbesId, pkcs8, (int)pkcs8Sz, PKCS5v2, cbcIv, 1, hmacOid); + } + if (ret == 0) { + /* Returning size on success. */ + ret = asnSz; + } + + FREE_ASNSETDATA(dataASN, heap); + (void)heap; +#endif /* WOLFSSL_ASN_TEMPLATE */ + return ret; +} + #ifdef WOLFSSL_ASN_TEMPLATE /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo @@ -10159,7 +10491,7 @@ enum { }; #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem)) -#endif +#endif /* WOLFSSL_ASN_TEMPLATE */ /* Wrap a private key in PKCS#8 and encrypt. * @@ -10180,9 +10512,11 @@ enum { * @param [in] passwordSz Length of password in bytes. * @param [in] vPKCS First byte used to determine PBE algorithm. * @param [in] vAlgo Second byte used to determine PBE algorithm. + * @param [in] encAlgId Encryption Algorithm for PBES2. * @param [in] salt Salt to use with KDF. * @param [in] saltSz Length of salt in bytes. * @param [in] itt Number of iterations to use in KDF. + * @param [in] hmacOid HMAC Algorithm for PBES2. * @param [in] rng Random number generator to use to generate salt. * @param [in] heap Dynamic memory allocator hint. * @return The size of encrypted data on success @@ -10195,7 +10529,8 @@ enum { */ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int vAlgo, - byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap) + int encAlgId, byte* salt, word32 saltSz, int itt, int hmacOid, + WC_RNG* rng, void* heap) { #ifndef WOLFSSL_ASN_TEMPLATE word32 sz; @@ -10219,8 +10554,12 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, word32 algoSz; const byte* algoName; + (void)encAlgId; + (void)hmacOid; (void)heap; + (void)EncryptContentPBES2; + WOLFSSL_ENTER("EncryptContent"); if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) @@ -10375,7 +10714,9 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, (void)rng; return (int)(inOutIdx + sz); -#else +#else /* WOLFSSL_ASN_TEMPLATE */ + /* PBES2 is only supported when enabling the ASN template */ + DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length); int ret = 0; int sz = 0; @@ -10402,7 +10743,8 @@ int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz, } /* Check PKCS #5 version - only PBSE1 parameters supported. */ if ((ret == 0) && (version == PKCS5v2)) { - ret = BAD_FUNC_ARG; + return EncryptContentPBES2(input, inputSz, out, outSz, password, + passwordSz, encAlgId, salt, saltSz, itt, hmacOid, rng, heap); } CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap); @@ -13970,8 +14312,15 @@ static int GetHashId(const byte* id, int length, byte* hash, int hashAlg) *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val) /* Get the string of a name component from the subject name. */ -#define GetCertNameSubjectStr(id) \ - (certNameSubject[(id) - 3].str) +#ifdef WOLFSSL_NAMES_STATIC + #define GetCertNameSubjectStr(id) \ + ((certNameSubject[(id) - 3].strLen) ? \ + (certNameSubject[(id) - 3].str) : \ + NULL) +#else + #define GetCertNameSubjectStr(id) \ + (certNameSubject[(id) - 3].str) +#endif /* Get the string length of a name component from the subject name. */ #define GetCertNameSubjectStrLen(id) \ (certNameSubject[(id) - 3].strLen) @@ -13997,7 +14346,15 @@ static int GetHashId(const byte* id, int length, byte* hash, int hashAlg) /* Mapping of certificate name component to useful information. */ typedef struct CertNameData { /* Type string of name component. */ +#ifdef WOLFSSL_NAMES_STATIC + const char str[20]; /* large enough for largest string in certNameSubject[] + * below + */ + #define EMPTY_STR { 0 } +#else const char* str; + #define EMPTY_STR NULL +#endif /* Length of type string of name component. */ byte strLen; #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) @@ -14179,7 +14536,7 @@ static const CertNameData certNameSubject[] = { }, /* Title */ { - NULL, 0, + EMPTY_STR, 0, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) 0, 0, @@ -14196,7 +14553,7 @@ static const CertNameData certNameSubject[] = { }, /* Undefined */ { - NULL, 0, + EMPTY_STR, 0, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) 0, 0, @@ -14213,7 +14570,7 @@ static const CertNameData certNameSubject[] = { }, /* Undefined */ { - NULL, 0, + EMPTY_STR, 0, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) 0, 0, @@ -14247,7 +14604,7 @@ static const CertNameData certNameSubject[] = { }, /* Undefined */ { - NULL, 0, + EMPTY_STR, 0, #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT) 0, 0, @@ -16515,6 +16872,7 @@ static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx) #ifndef NO_ASN_TIME_CHECK if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE && + (! AsnSkipDateCheck) && !XVALIDATE_DATE(date, format, dateType)) { if (dateType == ASN_BEFORE) { WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E); @@ -17466,14 +17824,20 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) if (sigCtx == NULL) return; +#ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST); sigCtx->digest = NULL; -#if !(defined(NO_RSA) && defined(NO_DSA)) +#if !defined(NO_RSA) || !defined(NO_DSA) XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE); sigCtx->sigCpy = NULL; #endif +#endif + #ifndef NO_ASN_CRYPT - if (sigCtx->key.ptr) { +#ifndef WOLFSSL_NO_MALLOC + if (sigCtx->key.ptr) +#endif + { switch (sigCtx->keyOID) { #ifndef NO_RSA #ifdef WC_RSA_PSS @@ -17481,15 +17845,19 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) #endif case RSAk: wc_FreeRsaKey(sigCtx->key.rsa); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA); sigCtx->key.rsa = NULL; + #endif break; #endif /* !NO_RSA */ #ifndef NO_DSA case DSAk: wc_FreeDsaKey(sigCtx->key.dsa); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA); sigCtx->key.dsa = NULL; + #endif break; #endif #ifdef HAVE_ECC @@ -17506,31 +17874,38 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW && WC_ASYNC_ENABLE_ECC */ wc_ecc_free(sigCtx->key.ecc); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC); sigCtx->key.ecc = NULL; + #endif break; #endif /* HAVE_ECC */ #ifdef HAVE_ED25519 case ED25519k: wc_ed25519_free(sigCtx->key.ed25519); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519); sigCtx->key.ed25519 = NULL; + #endif break; #endif /* HAVE_ED25519 */ #ifdef HAVE_ED448 case ED448k: wc_ed448_free(sigCtx->key.ed448); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448); sigCtx->key.ed448 = NULL; + #endif break; #endif /* HAVE_ED448 */ #if defined(HAVE_FALCON) case FALCON_LEVEL1k: case FALCON_LEVEL5k: wc_falcon_free(sigCtx->key.falcon); - XFREE(sigCtx->key.falcon, sigCtx->heap, - DYNAMIC_TYPE_FALCON); + #ifndef WOLFSSL_NO_MALLOC + XFREE(sigCtx->key.falcon, sigCtx->heap, DYNAMIC_TYPE_FALCON); sigCtx->key.falcon = NULL; + #endif break; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) @@ -17543,9 +17918,11 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) case ML_DSA_LEVEL3k: case ML_DSA_LEVEL5k: wc_dilithium_free(sigCtx->key.dilithium); + #ifndef WOLFSSL_NO_MALLOC XFREE(sigCtx->key.dilithium, sigCtx->heap, - DYNAMIC_TYPE_DILITHIUM); + DYNAMIC_TYPE_DILITHIUM); sigCtx->key.dilithium = NULL; + #endif break; #endif /* HAVE_DILITHIUM */ #if defined(HAVE_SPHINCS) @@ -17556,17 +17933,20 @@ void FreeSignatureCtx(SignatureCtx* sigCtx) case SPHINCS_SMALL_LEVEL3k: case SPHINCS_SMALL_LEVEL5k: wc_sphincs_free(sigCtx->key.sphincs); - XFREE(sigCtx->key.sphincs, sigCtx->heap, - DYNAMIC_TYPE_SPHINCS); + #ifndef WOLFSSL_NO_MALLOC + XFREE(sigCtx->key.sphincs, sigCtx->heap, DYNAMIC_TYPE_SPHINCS); sigCtx->key.sphincs = NULL; + #endif break; #endif /* HAVE_SPHINCS */ default: break; } /* switch (keyOID) */ + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.ptr = NULL; + #endif } -#endif +#endif /* !NO_ASN_CRYPT */ /* reset state, we are done */ sigCtx->state = SIG_STATE_BEGIN; @@ -17752,6 +18132,68 @@ static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID, } #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */ +#if !defined(NO_DSA) && !defined(HAVE_SELFTEST) +/* Try to parse as ASN.1 bitstring */ +static int DecodeDsaAsn1Sig(const byte* sig, word32 sigSz, byte* sigCpy, + void* heap) +{ + int ret = 0; + int rSz = 0, sSz = 0, mpinit = 0; +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + mp_int* r = NULL; + mp_int* s = NULL; +#else + mp_int r[1]; + mp_int s[1]; +#endif + +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + r = (mp_int*)XMALLOC(sizeof(*r), heap, DYNAMIC_TYPE_TMP_BUFFER); + s = (mp_int*)XMALLOC(sizeof(*s), heap, DYNAMIC_TYPE_TMP_BUFFER); + if (r == NULL || s == NULL) { + ret = MEMORY_E; + } +#endif + if (ret == 0) { + ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL); + } + if (ret == 0) { + mpinit = 1; + + if (DecodeECC_DSA_Sig(sig, sigSz, r, s) != 0) { + WOLFSSL_MSG("DSA sig decode ASN.1 failed!"); + ret = ASN_SIG_CONFIRM_E; + } + } + if (ret == 0) { + rSz = mp_unsigned_bin_size(r); + sSz = mp_unsigned_bin_size(s); + if (rSz + sSz > (int)sigSz) { + WOLFSSL_MSG("DSA sig size invalid"); + ret = ASN_SIG_CONFIRM_E; + } + } + if (ret == 0) { + if (mp_to_unsigned_bin(r, sigCpy) != MP_OKAY || + mp_to_unsigned_bin(s, sigCpy + rSz) != MP_OKAY) { + WOLFSSL_MSG("DSA sig to unsigned bin failed!"); + ret = ASN_SIG_CONFIRM_E; + } + } + + if (mpinit) { + mp_free(r); + mp_free(s); + } +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + XFREE(r, heap, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(s, heap, DYNAMIC_TYPE_TMP_BUFFER); +#endif + (void)heap; + return ret; +} +#endif + /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */ int ConfirmSignature(SignatureCtx* sigCtx, const byte* buf, word32 bufSz, @@ -17761,6 +18203,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, byte* rsaKeyIdx) { int ret = WC_NO_ERR_TRACE(ASN_SIG_CONFIRM_E); /* default to failure */ + #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) CertAttribute* certatt = NULL; #endif @@ -17798,11 +18241,13 @@ int ConfirmSignature(SignatureCtx* sigCtx, { sigCtx->keyOID = keyOID; /* must set early for cleanup */ +#ifndef WOLFSSL_NO_MALLOC sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap, DYNAMIC_TYPE_DIGEST); if (sigCtx->digest == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } +#endif #if !defined(NO_RSA) && defined(WC_RSA_PSS) /* RSA PSS Defaults */ @@ -17867,20 +18312,24 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), sigCtx->heap, DYNAMIC_TYPE_RSA); if (sigCtx->key.rsa == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap, sigCtx->devId)) != 0) { goto exit_cs; } + #ifndef WOLFSSL_NO_MALLOC sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE); if (sigCtx->sigCpy == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if (sigSz > MAX_ENCODED_SIG_SZ) { WOLFSSL_MSG("Verify Signature is too big"); ERROR_OUT(BUFFER_E, exit_cs); @@ -17909,20 +18358,24 @@ int ConfirmSignature(SignatureCtx* sigCtx, WOLFSSL_MSG("Verify Signature is too small"); ERROR_OUT(BUFFER_E, exit_cs); } + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey), sigCtx->heap, DYNAMIC_TYPE_DSA); if (sigCtx->key.dsa == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) { WOLFSSL_MSG("wc_InitDsaKey_h error"); goto exit_cs; } + #ifndef WOLFSSL_NO_MALLOC sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE); if (sigCtx->sigCpy == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa, keySz)) != 0) { WOLFSSL_MSG("ASN Key decode error DSA"); @@ -17930,80 +18383,9 @@ int ConfirmSignature(SignatureCtx* sigCtx, goto exit_cs; } if (sigSz != DSA_160_SIG_SIZE && - sigSz != DSA_256_SIG_SIZE) { - /* Try to parse it as the contents of a bitstring */ - #ifdef WOLFSSL_SMALL_STACK - mp_int* r; - mp_int* s; - #else - mp_int r[1]; - mp_int s[1]; - #endif - int rSz; - int sSz; - - #ifdef WOLFSSL_SMALL_STACK - r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (r == NULL) { - ERROR_OUT(MEMORY_E, exit_cs); - } - s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (s == NULL) { - XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - ERROR_OUT(MEMORY_E, exit_cs); - } - #endif - if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) { - goto exit_cs; - } - - idx = 0; - if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s) - != 0) { - WOLFSSL_MSG("DSA Sig is in unrecognized or " - "incorrect format"); - mp_free(r); - mp_free(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - #endif - ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs); - } - rSz = mp_unsigned_bin_size(r); - sSz = mp_unsigned_bin_size(s); - if (rSz + sSz > (int)sigSz) { - WOLFSSL_MSG("DSA Sig is in unrecognized or " - "incorrect format"); - mp_free(r); - mp_free(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - #endif - ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs); - } - if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY || - mp_to_unsigned_bin(s, - sigCtx->sigCpy + rSz) != MP_OKAY) { - WOLFSSL_MSG("DSA Sig is in unrecognized or " - "incorrect format"); - mp_free(r); - mp_free(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - #endif - ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs); - } - mp_free(r); - mp_free(s); - #ifdef WOLFSSL_SMALL_STACK - XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); - #endif + sigSz != DSA_256_SIG_SIZE) { + ret = DecodeDsaAsn1Sig(sig, sigSz, sigCtx->sigCpy, + sigCtx->heap); } else { XMEMCPY(sigCtx->sigCpy, sig, sigSz); @@ -18025,11 +18407,13 @@ int ConfirmSignature(SignatureCtx* sigCtx, WC_ASYNC_ENABLE_ECC */ sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), sigCtx->heap, DYNAMIC_TYPE_ECC); if (sigCtx->key.ecc == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; @@ -18041,12 +18425,12 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (nbCtx == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } - else { - ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx); - if (ret != 0) { - goto exit_cs; - } + + ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx); + if (ret != 0) { + goto exit_cs; } + #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW && WC_ASYNC_ENABLE_ECC */ ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc, @@ -18066,12 +18450,14 @@ int ConfirmSignature(SignatureCtx* sigCtx, case ED25519k: { sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.ed25519 = (ed25519_key*)XMALLOC( sizeof(ed25519_key), sigCtx->heap, DYNAMIC_TYPE_ED25519); if (sigCtx->key.ed25519 == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519, sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; @@ -18092,12 +18478,14 @@ int ConfirmSignature(SignatureCtx* sigCtx, case ED448k: { sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.ed448 = (ed448_key*)XMALLOC( sizeof(ed448_key), sigCtx->heap, DYNAMIC_TYPE_ED448); if (sigCtx->key.ed448 == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) { goto exit_cs; } @@ -18118,6 +18506,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.falcon = (falcon_key*)XMALLOC(sizeof(falcon_key), sigCtx->heap, @@ -18125,6 +18514,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.falcon == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_falcon_init_ex(sigCtx->key.falcon, sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; @@ -18145,6 +18535,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.falcon = (falcon_key*)XMALLOC(sizeof(falcon_key), sigCtx->heap, @@ -18152,6 +18543,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.falcon == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_falcon_init_ex(sigCtx->key.falcon, sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; @@ -18208,12 +18600,14 @@ int ConfirmSignature(SignatureCtx* sigCtx, goto exit_cs; } sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.dilithium = (dilithium_key*)XMALLOC( sizeof(dilithium_key), sigCtx->heap, DYNAMIC_TYPE_DILITHIUM); if (sigCtx->key.dilithium == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium, sigCtx->heap, sigCtx->devId)) < 0) { goto exit_cs; @@ -18235,6 +18629,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18242,6 +18637,8 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif + if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18261,6 +18658,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18268,6 +18666,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18287,6 +18686,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18294,6 +18694,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18313,6 +18714,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18320,6 +18722,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18339,6 +18742,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18346,6 +18750,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18365,6 +18770,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, { word32 idx = 0; sigCtx->verify = 0; + #ifndef WOLFSSL_NO_MALLOC sigCtx->key.sphincs = (sphincs_key*)XMALLOC(sizeof(sphincs_key), sigCtx->heap, @@ -18372,6 +18778,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, if (sigCtx->key.sphincs == NULL) { ERROR_OUT(MEMORY_E, exit_cs); } + #endif if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) { goto exit_cs; } @@ -18648,7 +19055,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, defined(WOLFSSL_RENESAS_FSPSM_TLS) if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break; #endif - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); if (encodedSig == NULL) { @@ -18675,7 +19082,7 @@ int ConfirmSignature(SignatureCtx* sigCtx, WOLFSSL_ERROR_VERBOSE(ret); } - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif break; @@ -22746,10 +23153,10 @@ static const ASNItem RPKCertASN[] = { /* Algorithm OBJECT IDENTIFIER */ /* TBS_SPUBKEYINFO_ALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 }, /* parameters ANY defined by algorithm OPTIONAL */ - /* TBS_SPUBKEYINFO_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 }, - /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 }, + /* TBS_SPUBKEYINFO_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 }, + /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 1 }, #ifdef WC_RSA_PSS - /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 2 }, + /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 }, #endif /* subjectPublicKey BIT STRING */ /* TBS_SPUBKEYINFO_PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 }, @@ -22919,7 +23326,7 @@ static int CheckDate(ASNGetData *dataASN, int dateType) #ifndef NO_ASN_TIME_CHECK /* Check date is a valid string and ASN_BEFORE or ASN_AFTER now. */ - if (ret == 0) { + if ((ret == 0) && (! AsnSkipDateCheck)) { if (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType)) { if (dateType == ASN_BEFORE) { ret = ASN_BEFORE_DATE_E; @@ -22946,7 +23353,8 @@ static int CheckDate(ASNGetData *dataASN, int dateType) * @param [out] badDateRet Bad date return code. * @param [in] stopAtPubKey Stop parsing before subjectPublicKeyInfo. * @param [in] stopAfterPubKey Stop parsing after subjectPublicKeyInfo. - * @return 0 on success. + * @return 0 on success if of the stop arguments is not set, otherwise set to + * the corresponding byte offset at which the parsing stopped. * @return ASN_CRIT_EXT_E when a critical extension was not recognized. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time. * @return ASN_DATE_SZ_E when time data is not supported. @@ -22989,6 +23397,20 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, oidCurveType); ret = GetASN_Items(RPKCertASN, RPKdataASN, RPKCertASN_Length, 1, cert->source, &cert->srcIdx, cert->maxIdx); + + if (ret == 0) { + if (( RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_NULL].length && + RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID].length) +#ifdef WC_RSA_PSS + || ( RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_P_SEQ].length && + ( RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_NULL].length || + RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID].length)) +#endif + ) { + WOLFSSL_MSG("Multiple RPK algorithm parameters set."); + ret = ASN_PARSE_E; + } + } if (ret == 0) { cert->keyOID = RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID].data.oid.sum; @@ -23083,7 +23505,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT; if ((CheckDate(&dataASN[i], ASN_BEFORE) < 0) && (verify != NO_VERIFY) && - (verify != VERIFY_SKIP_DATE)) { + (verify != VERIFY_SKIP_DATE) && (! AsnSkipDateCheck)) { badDate = ASN_BEFORE_DATE_E; } /* Store reference to ASN_BEFORE date. */ @@ -23095,7 +23517,7 @@ static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt, ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT; if ((CheckDate(&dataASN[i], ASN_AFTER) < 0) && (verify != NO_VERIFY) && - (verify != VERIFY_SKIP_DATE)) { + (verify != VERIFY_SKIP_DATE) && (! AsnSkipDateCheck)) { badDate = ASN_AFTER_DATE_E; } /* Store reference to ASN_AFTER date. */ @@ -23880,7 +24302,7 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req) { #ifndef WOLFSSL_ASN_TEMPLATE -#ifndef WOLFSSL_SMALL_STACK +#if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC) SignatureCtx sigCtx[1]; #else SignatureCtx* sigCtx; @@ -23912,7 +24334,7 @@ static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap, return BAD_FUNC_ARG; } -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE); if (sigCtx == NULL) return MEMORY_E; @@ -24573,6 +24995,96 @@ int wc_CertGetPubKey(const byte* cert, word32 certSz, return ret; } #endif + +/* + * @brief Export the SubjectPublicKeyInfo from an X.509 certificate + * + * This function extracts the SubjectPublicKeyInfo (SPKI) section from an X.509 + * certificate in DER format. The SPKI contains the public key algorithm and + * the public key itself. + * + * @param certDer [in] Pointer to the DER encoded certificate + * @param certSz [in] Size of the DER encoded certificate + * @param pubKeyDer [out] Buffer to hold the extracted SPKI (can be NULL to + * get size) + * @param pubKeyDerSz [in,out] On input, size of pubKeyDer buffer + * On output, actual size of the SPKI + * + * @return 0 on success, negative on error + * @return BAD_FUNC_ARG if certDer is NULL, certSz is 0, or pubKeyDerSz is NULL + * @return BUFFER_E if the provided buffer is too small + */ +WOLFSSL_API int wc_GetSubjectPubKeyInfoDerFromCert(const byte* certDer, + word32 certDerSz, + byte* pubKeyDer, + word32* pubKeyDerSz) +{ +#ifdef WOLFSSL_SMALL_STACK + DecodedCert* cert; +#else + DecodedCert cert[1]; +#endif + int ret; + word32 startIdx; + word32 idx; + word32 length; + int badDate; + + if (certDer == NULL || certDerSz == 0 || pubKeyDerSz == NULL) { + return BAD_FUNC_ARG; + } + +#ifdef WOLFSSL_SMALL_STACK + cert = (DecodedCert*)XMALLOC(sizeof(*cert), NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (cert == NULL) + return MEMORY_E; +#endif + + length = 0; + badDate = 0; + + wc_InitDecodedCert(cert, certDer, certDerSz, NULL); + + /* Parse up to the SubjectPublicKeyInfo */ + ret = wc_GetPubX509(cert, 0, &badDate); + if (ret >= 0) { + /* Save the starting index of SubjectPublicKeyInfo */ + startIdx = cert->srcIdx; + + /* Get the length of the SubjectPublicKeyInfo sequence */ + idx = startIdx; + ret = GetSequence(certDer, &idx, (int*)&length, certDerSz); + if (ret >= 0) { + /* Calculate total length including sequence header */ + length += (idx - startIdx); + + /* Copy the SubjectPublicKeyInfo if buffer provided */ + if (pubKeyDer != NULL) { + if (*pubKeyDerSz < (word32)length) { + ret = BUFFER_E; + } + else { + XMEMCPY(pubKeyDer, &certDer[startIdx], length); + } + } + } + } + + if (ret >= 0) { + ret = 0; + } + + *pubKeyDerSz = length; + wc_FreeDecodedCert(cert); + +#ifdef WOLFSSL_SMALL_STACK + XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + + return ret; +} + + #ifdef HAVE_OCSP Signer* findSignerByKeyHash(Signer *list, byte *hash) { @@ -24630,7 +25142,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) || ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { cert->badDate = ret; - if (verify == VERIFY_SKIP_DATE) + if ((verify == VERIFY_SKIP_DATE) || AsnSkipDateCheck) ret = 0; } else @@ -24881,7 +25393,7 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm, if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) || ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) { cert->badDate = ret; - if (verify == VERIFY_SKIP_DATE) + if ((verify == VERIFY_SKIP_DATE) || AsnSkipDateCheck) ret = 0; } else if (ret < 0) { @@ -25677,102 +26189,101 @@ void wc_FreeDer(DerBuffer** pDer) /* Note: If items added make sure MAX_X509_HEADER_SZ is updated to reflect maximum length and pem_struct_min_sz to reflect minimum size */ -wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; -wcchar END_CERT = "-----END CERTIFICATE-----"; +static wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; +static wcchar END_CERT = "-----END CERTIFICATE-----"; #ifdef WOLFSSL_CERT_REQ - wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----"; - wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----"; + static wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----"; + static wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----"; #endif #if defined(WOLFSSL_ACERT) - wcchar BEGIN_ACERT = "-----BEGIN ATTRIBUTE CERTIFICATE-----"; - wcchar END_ACERT = "-----END ATTRIBUTE CERTIFICATE-----"; + static wcchar BEGIN_ACERT = "-----BEGIN ATTRIBUTE CERTIFICATE-----"; + static wcchar END_ACERT = "-----END ATTRIBUTE CERTIFICATE-----"; #endif /* WOLFSSL_ACERT */ #ifndef NO_DH - wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----"; - wcchar END_DH_PARAM = "-----END DH PARAMETERS-----"; - wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----"; - wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----"; + static wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----"; + static wcchar END_DH_PARAM = "-----END DH PARAMETERS-----"; + static wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----"; + static wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----"; #endif #ifndef NO_DSA - wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----"; - wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----"; -#endif -wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----"; -wcchar END_X509_CRL = "-----END X509 CRL-----"; -wcchar BEGIN_TRUSTED_CERT = "-----BEGIN TRUSTED CERTIFICATE-----"; -wcchar END_TRUSTED_CERT = "-----END TRUSTED CERTIFICATE-----"; -wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----"; -wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----"; -wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----"; -wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----"; -wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----"; -wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----"; -wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; -wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----"; + static wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----"; + static wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----"; +#endif +static wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----"; +static wcchar END_X509_CRL = "-----END X509 CRL-----"; +static wcchar BEGIN_TRUSTED_CERT = "-----BEGIN TRUSTED CERTIFICATE-----"; +static wcchar END_TRUSTED_CERT = "-----END TRUSTED CERTIFICATE-----"; +static wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----"; +static wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----"; +static wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----"; +static wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----"; +static wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----"; +static wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----"; +static wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; +static wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----"; #ifdef HAVE_ECC - wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----"; - wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----"; + static wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----"; + static wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----"; #ifdef OPENSSL_EXTRA - wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----"; - wcchar END_EC_PARAM = "-----END EC PARAMETERS-----"; + static wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----"; + static wcchar END_EC_PARAM = "-----END EC PARAMETERS-----"; #endif #endif #ifdef HAVE_PKCS7 -wcchar BEGIN_PKCS7 = "-----BEGIN PKCS7-----"; -wcchar END_PKCS7 = "-----END PKCS7-----"; +static wcchar BEGIN_PKCS7 = "-----BEGIN PKCS7-----"; +static wcchar END_PKCS7 = "-----END PKCS7-----"; #endif -#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ - !defined(NO_DSA) - wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----"; - wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----"; +#if defined(HAVE_ECC) || !defined(NO_DSA) + static wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----"; + static wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----"; #endif #ifdef OPENSSL_EXTRA - const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN"; - const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----"; - const char END_PRIV_KEY_PREFIX[] = "-----END"; + static wcchar BEGIN_PRIV_KEY_PREFIX = "-----BEGIN"; + static wcchar PRIV_KEY_SUFFIX = "PRIVATE KEY-----"; + static wcchar END_PRIV_KEY_PREFIX = "-----END"; #endif -wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----"; -wcchar END_PUB_KEY = "-----END PUBLIC KEY-----"; +static wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----"; +static wcchar END_PUB_KEY = "-----END PUBLIC KEY-----"; #if defined(HAVE_ED25519) || defined(HAVE_ED448) - wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----"; - wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----"; + static wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----"; + static wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----"; #endif #if defined(HAVE_FALCON) - wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----"; - wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----"; - wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----"; - wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----"; + static wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----"; + static wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----"; + static wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----"; + static wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_FALCON */ #if defined(HAVE_DILITHIUM) #ifdef WOLFSSL_DILITHIUM_FIPS204_DRAFT - wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----"; - wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----"; - wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----"; - wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----"; - wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----"; - wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----"; - #endif - wcchar BEGIN_ML_DSA_LEVEL2_PRIV = "-----BEGIN ML_DSA_LEVEL2 PRIVATE KEY-----"; - wcchar END_ML_DSA_LEVEL2_PRIV = "-----END ML_DSA_LEVEL2 PRIVATE KEY-----"; - wcchar BEGIN_ML_DSA_LEVEL3_PRIV = "-----BEGIN ML_DSA_LEVEL3 PRIVATE KEY-----"; - wcchar END_ML_DSA_LEVEL3_PRIV = "-----END ML_DSA_LEVEL3 PRIVATE KEY-----"; - wcchar BEGIN_ML_DSA_LEVEL5_PRIV = "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----"; - wcchar END_ML_DSA_LEVEL5_PRIV = "-----END ML_DSA_LEVEL5 PRIVATE KEY-----"; + static wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----"; + static wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----"; + static wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----"; + static wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----"; + static wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----"; + static wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----"; + #endif + static wcchar BEGIN_ML_DSA_LEVEL2_PRIV = "-----BEGIN ML_DSA_LEVEL2 PRIVATE KEY-----"; + static wcchar END_ML_DSA_LEVEL2_PRIV = "-----END ML_DSA_LEVEL2 PRIVATE KEY-----"; + static wcchar BEGIN_ML_DSA_LEVEL3_PRIV = "-----BEGIN ML_DSA_LEVEL3 PRIVATE KEY-----"; + static wcchar END_ML_DSA_LEVEL3_PRIV = "-----END ML_DSA_LEVEL3 PRIVATE KEY-----"; + static wcchar BEGIN_ML_DSA_LEVEL5_PRIV = "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----"; + static wcchar END_ML_DSA_LEVEL5_PRIV = "-----END ML_DSA_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_DILITHIUM */ #if defined(HAVE_SPHINCS) - wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----"; - wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----"; - wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----"; - wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----"; - wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----"; - wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----"; - - wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----"; - wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----"; - wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----"; - wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----"; - wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; - wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; + static wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----"; + static wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----"; + static wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----"; + static wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----"; + static wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----"; + static wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----"; + + static wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----"; + static wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----"; + static wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----"; + static wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----"; + static wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; + static wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----"; #endif /* HAVE_SPHINCS */ const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----" @@ -26153,7 +26664,7 @@ int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN)); /* get cipher name */ - if (NAME_SZ < (finish - start)) /* buffer size of info->name */ + if (NAME_SZ <= (finish - start)) /* buffer size of info->name */ return BUFFER_E; if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL) return BUFFER_E; @@ -26390,6 +26901,14 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #ifdef OPENSSL_EXTRA char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */ char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */ +#endif +#ifdef WOLFSSL_ENCRYPTED_KEYS + int hashType = WC_HASH_TYPE_NONE; +#if !defined(NO_MD5) + hashType = WC_MD5; +#elif !defined(NO_SHA) + hashType = WC_SHA; +#endif #endif WOLFSSL_ENTER("PemToDer"); @@ -26756,7 +27275,7 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #endif ret = wc_BufferKeyDecrypt(info, der->buffer, der->length, - (byte*)password, passwordSz, WC_MD5); + (byte*)password, passwordSz, hashType); #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD #ifndef NO_DES3 @@ -27537,13 +28056,13 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) int ret = 0, i; int mpSz; word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0; - word32 sizes[RSA_INTS]; byte seq[MAX_SEQ_SZ]; byte ver[MAX_VERSION_SZ]; mp_int* keyInt; #ifndef WOLFSSL_NO_MALLOC word32 rawLen; byte* tmps[RSA_INTS]; + word32 sizes[RSA_INTS]; #endif if (key == NULL) @@ -27583,7 +28102,9 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen) ret = mpSz; break; } + #ifndef WOLFSSL_NO_MALLOC sizes[i] = (word32)mpSz; + #endif intTotalLen += (word32)mpSz; } @@ -31216,11 +31737,13 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, case CERTSIGN_STATE_DIGEST: certSignCtx->state = CERTSIGN_STATE_DIGEST; + #ifndef WOLFSSL_NO_MALLOC certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER); if (certSignCtx->digest == NULL) { ret = MEMORY_E; goto exit_ms; } + #endif ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest, &typeH, &digestSz, 0); @@ -31234,11 +31757,13 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, case CERTSIGN_STATE_ENCODE: #ifndef NO_RSA if (rsaKey) { + #ifndef WOLFSSL_NO_MALLOC certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap, DYNAMIC_TYPE_TMP_BUFFER); if (certSignCtx->encSig == NULL) { ret = MEMORY_E; goto exit_ms; } + #endif /* signature */ certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig, @@ -31251,7 +31776,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, certSignCtx->state = CERTSIGN_STATE_DO; ret = -1; /* default to error, reassigned to ALGO_ID_E below. */ - #ifndef NO_RSA + #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) if (rsaKey) { /* signature */ ret = wc_RsaSSL_Sign(certSignCtx->encSig, @@ -31299,7 +31824,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, ret = outSz; } #endif /* HAVE_FALCON */ - #if defined(HAVE_DILITHIUM) + #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey && dilithiumKey) { word32 outSz = sigSz; @@ -31321,7 +31846,7 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, ret = outSz; } } - #endif /* HAVE_DILITHIUM */ + #endif /* HAVE_DILITHIUM && !WOLFSSL_DILITHIUM_NO_SIGN */ #if defined(HAVE_SPHINCS) if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey && !dilithiumKey && sphincsKey) { @@ -31346,14 +31871,17 @@ static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz, } #endif +#ifndef WOLFSSL_NO_MALLOC #ifndef NO_RSA if (rsaKey) { XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER); + certSignCtx->encSig = NULL; } #endif /* !NO_RSA */ XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER); certSignCtx->digest = NULL; +#endif /* !WOLFSSL_NO_MALLOC */ /* reset state */ certSignCtx->state = CERTSIGN_STATE_BEGIN; @@ -33120,12 +33648,14 @@ static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz, #endif /* HAVE_ECC */ } +#ifndef WOLFSSL_NO_MALLOC if (certSignCtx->sig == NULL) { certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap, DYNAMIC_TYPE_TMP_BUFFER); if (certSignCtx->sig == NULL) return MEMORY_E; } +#endif sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig, MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, @@ -33146,8 +33676,10 @@ static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz, sType); } +#ifndef WOLFSSL_NO_MALLOC XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER); certSignCtx->sig = NULL; +#endif return sigSz; } @@ -33254,12 +33786,14 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, #endif /* HAVE_ECC */ } +#ifndef WOLFSSL_NO_MALLOC if (certSignCtx->sig == NULL) { certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap, DYNAMIC_TYPE_TMP_BUFFER); if (certSignCtx->sig == NULL) return MEMORY_E; } +#endif ret = MakeSignature(certSignCtx, buf, (word32)bufSz, certSignCtx->sig, MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, @@ -33273,8 +33807,10 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, #endif if (ret <= 0) { + #ifndef WOLFSSL_NO_MALLOC XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER); certSignCtx->sig = NULL; + #endif return ret; } @@ -33289,8 +33825,10 @@ int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf, ret += headerSz; } +#ifndef WOLFSSL_NO_MALLOC XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER); certSignCtx->sig = NULL; +#endif return ret; } #endif /* WOLFSSL_DUAL_ALG_CERTS */ @@ -33849,6 +34387,8 @@ int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx, byte oid[CTC_MAX_EKU_OID_SZ]; word32 oidSz = CTC_MAX_EKU_OID_SZ; + XMEMSET(oid, 0, sizeof(oid)); + if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) { WOLFSSL_MSG("Either idx or sz was too large"); return BAD_FUNC_ARG; @@ -33876,6 +34416,8 @@ int wc_SetCustomExtension(Cert *cert, int critical, const char *oid, word32 encodedOidSz = MAX_OID_SZ; int ret; + XMEMSET(encodedOid, 0, sizeof(encodedOid)); + if (cert == NULL || oid == NULL || der == NULL || derSz == 0) { return BAD_FUNC_ARG; } @@ -35199,25 +35741,25 @@ static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz, #else if (ret == 0) { /* Base X-ordinate */ - DataToHexString(base + 1, (word32)curve->size, curve->Gx); + DataToHexString(base + 1, (word32)curve->size, (char *)curve->Gx); /* Base Y-ordinate */ - DataToHexString(base + 1 + curve->size, (word32)curve->size, curve->Gy); + DataToHexString(base + 1 + curve->size, (word32)curve->size, (char *)curve->Gy); /* Prime */ DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data, dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length, - curve->prime); + (char *)curve->prime); /* Parameter A */ DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data, dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length, - curve->Af); + (char *)curve->Af); /* Parameter B */ DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data, dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length, - curve->Bf); + (char *)curve->Bf); /* Order of curve */ DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data, dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length, - curve->order); + (char *)curve->order); } #endif /* WOLFSSL_ECC_CURVE_STATIC */ @@ -36388,7 +36930,8 @@ static const ASNItem edKeyASN[] = { /* privateKey */ /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 }, /* CurvePrivateKey */ -/* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 }, +/* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 2 }, +/* PKEY_MLDSASEQ */ { 2, ASN_SEQUENCE, 1, 0, 2 }, /* attributes */ /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 }, /* publicKey */ @@ -36401,6 +36944,7 @@ enum { EDKEYASN_IDX_PKEYALGO_OID, EDKEYASN_IDX_PKEY, EDKEYASN_IDX_PKEY_CURVEPKEY, + EDKEYASN_IDX_PKEY_MLDSASEQ, EDKEYASN_IDX_ATTRS, EDKEYASN_IDX_PUBKEY }; @@ -36466,8 +37010,15 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, if (GetOctetString(input, inOutIdx, &length, inSz) < 0) return ASN_PARSE_E; - if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0) - return ASN_PARSE_E; + if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0) { + if (oid != ML_DSA_LEVEL2k && oid != ML_DSA_LEVEL3k && + oid != ML_DSA_LEVEL5k) { + return ASN_PARSE_E; + } + if (GetSequence(input, inOutIdx, &privSz, inSz) < 0) { + return ASN_PARSE_E; + } + } priv = input + *inOutIdx; *inOutIdx += (word32)privSz; @@ -36545,11 +37096,24 @@ int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx, word32 inSz, (int)dataASN[EDKEYASN_IDX_PKEYALGO_OID].data.oid.sum; } } - if (ret == 0) { + if (ret == 0 && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length != 0) { /* Import private value. */ *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length; *privKey = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data; } + else if (ret == 0 && + dataASN[EDKEYASN_IDX_PKEY_MLDSASEQ].data.ref.length != 0) { + if (*inOutKeyType != ML_DSA_LEVEL2k && + *inOutKeyType != ML_DSA_LEVEL3k && + *inOutKeyType != ML_DSA_LEVEL5k) { + ret = ASN_PARSE_E; + } + else { + /* Import private value. */ + *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_MLDSASEQ].data.ref.length; + *privKey = dataASN[EDKEYASN_IDX_PKEY_MLDSASEQ].data.ref.data; + } + } if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) { /* Set public length to 0 as not seen. */ if (pubKeyLen != NULL) @@ -36973,6 +37537,8 @@ int SetAsymKeyDer(const byte* privKey, word32 privKeyLen, SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen); /* Don't write out attributes. */ dataASN[EDKEYASN_IDX_ATTRS].noOut = 1; + /* Don't write sequence. */ + dataASN[EDKEYASN_IDX_PKEY_MLDSASEQ].noOut = 1; if (pubKey) { /* Leave space for public key. */ SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen); @@ -37613,7 +38179,7 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, #ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK - if (!XVALIDATE_DATE(single->status->thisDate, + if ((! AsnSkipDateCheck) && !XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, ASN_BEFORE)) return ASN_BEFORE_DATE_E; #endif @@ -37650,7 +38216,9 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, #ifndef NO_ASN_TIME_CHECK #ifndef WOLFSSL_NO_OCSP_DATE_CHECK - if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, ASN_AFTER)) + if ((! AsnSkipDateCheck) && + !XVALIDATE_DATE(single->status->nextDate, + single->status->nextDateFormat, ASN_AFTER)) return ASN_AFTER_DATE_E; #endif #endif @@ -37723,7 +38291,9 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, cs->thisDateFormat = ASN_GENERALIZED_TIME; #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) /* Check date is a valid string and ASN_BEFORE now. */ - if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, ASN_BEFORE)) { + if ((! AsnSkipDateCheck) && + !XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, ASN_BEFORE)) + { ret = ASN_BEFORE_DATE_E; } #endif /* !NO_ASN_TIME_CHECK && !WOLFSSL_NO_OCSP_DATE_CHECK */ @@ -37746,7 +38316,9 @@ static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size, cs->nextDateFormat = ASN_GENERALIZED_TIME; #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK) /* Check date is a valid string and ASN_AFTER now. */ - if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, ASN_AFTER)) { + if ((! AsnSkipDateCheck) && + !XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, ASN_AFTER)) + { ret = ASN_AFTER_DATE_E; } #endif /* !NO_ASN_TIME_CHECK && !WOLFSSL_NO_OCSP_DATE_CHECK */ @@ -39832,6 +40404,7 @@ static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl, { #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK) if (verify != NO_VERIFY && + (! AsnSkipDateCheck) && !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL after date is no longer valid"); WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR); @@ -40026,50 +40599,39 @@ static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, return ret; } else { - if (length > 1) { - int i; - #ifdef WOLFSSL_SMALL_STACK - mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL, - DYNAMIC_TYPE_BIGINT); - if (m == NULL) { - return MEMORY_E; - } - #else - mp_int m[1]; - #endif + DECL_MP_INT_SIZE_DYN(m, CRL_MAX_NUM_SZ * CHAR_BIT, + CRL_MAX_NUM_SZ * CHAR_BIT); + NEW_MP_INT_SIZE(m, CRL_MAX_NUM_SZ * CHAR_BIT, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + #ifdef MP_INT_SIZE_CHECK_NULL + if (m == NULL) { + ret = MEMORY_E; + } + #endif - if (mp_init(m) != MP_OKAY) { - ret = MP_INIT_E; - } + if (ret == 0 && ((ret = INIT_MP_INT_SIZE(m, CRL_MAX_NUM_SZ + * CHAR_BIT)) != MP_OKAY)) { + ret = MP_INIT_E; + } - if (ret == 0) - ret = mp_read_unsigned_bin(m, buf + idx, length); - if (ret != MP_OKAY) - ret = BUFFER_E; + if (ret == MP_OKAY) + ret = mp_read_unsigned_bin(m, buf + idx, length); - if (ret == 0) { - dcrl->crlNumber = 0; - for (i = 0; i < (int)(*m).used; ++i) { - if (i > (CHAR_BIT * - (int)sizeof(word32) / DIGIT_BIT)) { - break; - } - dcrl->crlNumber |= ((word32)(*m).dp[i]) << - (DIGIT_BIT * i); - } - } + if (ret != MP_OKAY) + ret = BUFFER_E; - mp_free(m); - #ifdef WOLFSSL_SMALL_STACK - XFREE(m, NULL, DYNAMIC_TYPE_BIGINT); - #endif + if (ret == MP_OKAY && mp_toradix(m, (char*)dcrl->crlNumber, + MP_RADIX_HEX) != MP_OKAY) + ret = BUFFER_E; - if (ret != 0) - return ret; - } - else if (length == 1) { - dcrl->crlNumber = buf[idx]; + if (ret == MP_OKAY) { + dcrl->crlNumberSet = 1; } + + FREE_MP_INT_SIZE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + if (ret != MP_OKAY) + return ret; } } } @@ -40096,6 +40658,9 @@ static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx, { DECL_ASNGETDATA(dataASN, certExtASN_Length); int ret = 0; + /* Track if we've seen these extensions already */ + word32 seenAuthKey = 0; + word32 seenCrlNum = 0; ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap); @@ -40112,48 +40677,77 @@ static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx, ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx, maxIdx); if (ret == 0) { + word32 localIdx = idx; /* OID in extension. */ word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum; /* Length of extension data. */ int length = (int)dataASN[CERTEXTASN_IDX_VAL].length; - if (oid == AUTH_KEY_OID) { - #ifndef NO_SKID - /* Parse Authority Key Id extension. - * idx is at start of OCTET_STRING data. */ - ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl); - if (ret != 0) { - WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension"); - } - #endif + /* Check for duplicate extension. RFC 5280 Section 4.2 states that + * a certificate must not include more than one instance of a + * particular extension. Note that the same guidance does not appear + * for CRLs but the same reasoning should apply. */ + if ((oid == AUTH_KEY_OID && seenAuthKey) || + (oid == CRL_NUMBER_OID && seenCrlNum)) { + WOLFSSL_MSG("Duplicate CRL extension found"); + /* Gating !WOLFSSL_NO_ASN_STRICT will allow wolfCLU to have same + * behaviour as OpenSSL */ +#ifndef WOLFSSL_NO_ASN_STRICT + ret = ASN_PARSE_E; +#endif } - else if (oid == CRL_NUMBER_OID) { - #ifdef WOLFSSL_SMALL_STACK - mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL, - DYNAMIC_TYPE_BIGINT); - if (m == NULL) { - ret = MEMORY_E; + + /* Track this extension if no duplicate found */ + if (ret == 0) { + if (oid == AUTH_KEY_OID) + seenAuthKey = 1; + else if (oid == CRL_NUMBER_OID) + seenCrlNum = 1; + } + + if (ret == 0) { + if (oid == AUTH_KEY_OID) { + #ifndef NO_SKID + /* Parse Authority Key Id extension. + * idx is at start of OCTET_STRING data. */ + ret = ParseCRL_AuthKeyIdExt(buf + localIdx, length, dcrl); + if (ret != 0) { + WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension"); + } + #endif } - #else - mp_int m[1]; - #endif + else if (oid == CRL_NUMBER_OID) { + DECL_MP_INT_SIZE_DYN(m, CRL_MAX_NUM_SZ * CHAR_BIT, + CRL_MAX_NUM_SZ * CHAR_BIT); + NEW_MP_INT_SIZE(m, CRL_MAX_NUM_SZ * CHAR_BIT, NULL, + DYNAMIC_TYPE_TMP_BUFFER); - if (ret == 0) { - if (mp_init(m) != MP_OKAY) { + #ifdef MP_INT_SIZE_CHECK_NULL + if (m == NULL) { + ret = MEMORY_E; + } + #endif + + if (ret == 0 && (INIT_MP_INT_SIZE(m, CRL_MAX_NUM_SZ * + CHAR_BIT) != MP_OKAY)) { ret = MP_INIT_E; } - } - if (ret == 0) { - ret = GetInt(m, buf, &idx, maxIdx); - } - if (ret == 0) { - dcrl->crlNumber = (int)m->dp[0]; - } - mp_free(m); - #ifdef WOLFSSL_SMALL_STACK - XFREE(m, NULL, DYNAMIC_TYPE_BIGINT); - #endif + if (ret == 0) { + ret = GetInt(m, buf, &localIdx, maxIdx); + } + + if (ret == 0 && mp_toradix(m, (char*)dcrl->crlNumber, + MP_RADIX_HEX) != MP_OKAY) + ret = BUFFER_E; + + if (ret == 0) { + dcrl->crlNumberSet = 1; + } + + mp_free(m); + FREE_MP_INT_SIZE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } } /* TODO: check criticality */ /* Move index on to next extension. */ @@ -40472,6 +41066,7 @@ int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz, if (dcrl->nextDateFormat != 0) { /* Next date was set, so validate it. */ if (verify != NO_VERIFY && + (! AsnSkipDateCheck) && !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, ASN_AFTER)) { WOLFSSL_MSG("CRL after date is no longer valid"); ret = CRL_CERT_DATE_ERR; @@ -41195,6 +41790,75 @@ int wc_Asn1_SetFile(Asn1* asn1, XFILE file) return ret; } +/* Set the OID name callback to use when printing. + * + * @param [in, out] asn1 ASN.1 parse object. + * @param [in] nameCb OID name callback. + * @return 0 on success. + * @return BAD_FUNC_ARG when asn1 is NULL. + * @return BAD_FUNC_ARG when nameCb is NULL. + */ +int wc_Asn1_SetOidToNameCb(Asn1* asn1, Asn1OidToNameCb nameCb) +{ + int ret = 0; + + if ((asn1 == NULL) || (nameCb == NULL)) { + ret = BAD_FUNC_ARG; + } + else { + asn1->nameCb = nameCb; + } + + return ret; +} + +/* Encode dotted form of OID into byte array version. + * + * @param [in] in Byte array containing OID. + * @param [in] inSz Size of OID in bytes. + * @param [in] out Array to hold dotted form of OID. + * @param [in, out] outSz On in, number of elements in array. + * On out, count of numbers in dotted form. + * @return 0 on success + * @return BAD_FUNC_ARG when in or outSz is NULL. + * @return BUFFER_E when dotted form buffer too small. + */ +static int EncodedDottedForm(const byte* in, word32 inSz, word32* out, + word32* outSz) +{ + int x = 0, y = 0; + word32 t = 0; + + /* check args */ + if (in == NULL || outSz == NULL) { + return BAD_FUNC_ARG; + } + + /* decode bytes */ + while (inSz--) { + t = (t << 7) | (in[x] & 0x7F); + if (!(in[x] & 0x80)) { + if (y >= (int)*outSz) { + return BUFFER_E; + } + if (y == 0) { + out[0] = (word16)(t / 40); + out[1] = (word16)(t % 40); + y = 2; + } + else { + out[y++] = t; + } + t = 0; /* reset tmp */ + } + x++; + } + + /* return length */ + *outSz = (word32)y; + + return 0; +} /* Print OID in dotted form or as hex bytes. * * @param [in] file File pointer to write to. @@ -41203,12 +41867,12 @@ int wc_Asn1_SetFile(Asn1* asn1, XFILE file) */ static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len) { - word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ]; + word32 dotted_nums[ASN1_OID_DOTTED_MAX_SZ]; word32 num = ASN1_OID_DOTTED_MAX_SZ; word32 i; /* Decode OBJECT_ID into dotted form array. */ - if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) { + if (EncodedDottedForm(oid, len, dotted_nums, &num) == 0) { /* Print out each number of dotted form. */ for (i = 0; i < num; i++) { XFPRINTF(file, "%d", dotted_nums[i]); @@ -41295,11 +41959,11 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) int nid; #endif const char* ln = NULL; - word32 i = 0; + word32 idx = 0; int known = 1; /* Get the OID value for the OBJECT_ID. */ - if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType, + if (GetObjectId(asn1->data + asn1->offset, &idx, &oid, oidIgnoreType, asn1->item.len + 2) == WC_NO_ERR_TRACE(ASN_PARSE_E)) { known = 0; } @@ -41313,12 +41977,17 @@ static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts) else #endif /* Lookup long name for extra known OID values. */ - if (!Oid2LongName(oid, &ln)) { + if (Oid2LongName(oid, &ln) != 0) { + } + else if ((asn1->nameCb != NULL) && (idx >= 2) && + ((ln = asn1->nameCb(asn1->data + asn1->offset + 2, + idx - 2))) != NULL) { + } + else { /* Unknown OID value. */ ln = NULL; known = 0; } - XFPRINTF(asn1->file, ":"); /* Show OID value if not known or asked to. */ if ((!known) || opts->show_oid) { @@ -42611,7 +43280,9 @@ int ParseX509Acert(DecodedAcert* acert, int verify) /* check BEFORE date. */ idx = ACERT_IDX_ACINFO_VALIDITY_NOTB_GT; if (CheckDate(&dataASN[idx], BEFORE) < 0) { - if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { + if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE) && + (! AsnSkipDateCheck)) + { badDate = ASN_BEFORE_DATE_E; } } @@ -42623,7 +43294,9 @@ int ParseX509Acert(DecodedAcert* acert, int verify) /* check AFTER date. */ idx = ACERT_IDX_ACINFO_VALIDITY_NOTA_GT; if (CheckDate(&dataASN[idx], AFTER) < 0) { - if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE)) { + if ((verify != NO_VERIFY) && (verify != VERIFY_SKIP_DATE) && + (! AsnSkipDateCheck)) + { badDate = ASN_BEFORE_DATE_E; } } diff --git a/src/wolfcrypt/src/bio.c b/src/wolfcrypt/src/bio.c index 0b52a6c..ce74983 100644 --- a/src/wolfcrypt/src/bio.c +++ b/src/wolfcrypt/src/bio.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2392,13 +2392,28 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_connect"); bio = wolfSSL_BIO_new(wolfSSL_BIO_s_socket()); if (bio) { - const char* port = XSTRSTR(str, ":"); + const char* port; +#ifdef WOLFSSL_IPV6 + const char* ipv6Start = XSTRSTR(str, "["); + const char* ipv6End = XSTRSTR(str, "]"); + + if (ipv6End) + port = XSTRSTR(ipv6End, ":"); + else +#endif + port = XSTRSTR(str, ":"); if (port != NULL) bio->port = (word16)XATOI(port + 1); else port = str + XSTRLEN(str); /* point to null terminator */ +#ifdef WOLFSSL_IPV6 + if (ipv6Start && ipv6End) { + str = ipv6Start + 1; + port = ipv6End; + } +#endif bio->ip = (char*)XMALLOC( (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); diff --git a/src/wolfcrypt/src/blake2b.c b/src/wolfcrypt/src/blake2b.c index c1f3e7a..b28e9c0 100644 --- a/src/wolfcrypt/src/blake2b.c +++ b/src/wolfcrypt/src/blake2b.c @@ -18,7 +18,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -356,7 +356,9 @@ int blake2b_final( blake2b_state *S, byte *out, byte outlen ) } S->buflen -= BLAKE2B_BLOCKBYTES; - XMEMCPY( S->buf, S->buf + BLAKE2B_BLOCKBYTES, (wolfssl_word)S->buflen ); + if ( S->buflen > BLAKE2B_BLOCKBYTES ) + return BAD_LENGTH_E; + XMEMMOVE( S->buf, S->buf + BLAKE2B_BLOCKBYTES, (wolfssl_word)S->buflen ); } blake2b_increment_counter( S, S->buflen ); diff --git a/src/wolfcrypt/src/blake2s.c b/src/wolfcrypt/src/blake2s.c index 7f9d3ff..5f264cd 100644 --- a/src/wolfcrypt/src/blake2s.c +++ b/src/wolfcrypt/src/blake2s.c @@ -18,7 +18,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/camellia.c b/src/wolfcrypt/src/camellia.c index c1ff47e..9a15ba0 100644 --- a/src/wolfcrypt/src/camellia.c +++ b/src/wolfcrypt/src/camellia.c @@ -33,7 +33,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1022,7 +1022,7 @@ static int camellia_setup256(const unsigned char *key, u32 *subkey) static int camellia_setup192(const unsigned char *key, u32 *subkey) { unsigned char kk[32]; - u32 krll, krlr, krrl,krrr; + u32 krll = 0, krlr = 0, krrl = 0, krrr = 0; XMEMCPY(kk, key, 24); XMEMCPY((unsigned char *)&krll, key+16,4); diff --git a/src/wolfcrypt/src/chacha.c b/src/wolfcrypt/src/chacha.c index 1a1d676..d42186e 100644 --- a/src/wolfcrypt/src/chacha.c +++ b/src/wolfcrypt/src/chacha.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/chacha20_poly1305.c b/src/wolfcrypt/src/chacha20_poly1305.c index 09d522d..d87325d 100644 --- a/src/wolfcrypt/src/chacha20_poly1305.c +++ b/src/wolfcrypt/src/chacha20_poly1305.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/cmac.c b/src/wolfcrypt/src/cmac.c index b83214c..0c7274f 100644 --- a/src/wolfcrypt/src/cmac.c +++ b/src/wolfcrypt/src/cmac.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/coding.c b/src/wolfcrypt/src/coding.c index 739fde5..2b0a4b2 100644 --- a/src/wolfcrypt/src/coding.c +++ b/src/wolfcrypt/src/coding.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/compress.c b/src/wolfcrypt/src/compress.c index e3c42cc..f2e8b3e 100644 --- a/src/wolfcrypt/src/compress.c +++ b/src/wolfcrypt/src/compress.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/cpuid.c b/src/wolfcrypt/src/cpuid.c index 37fe855..978cbf5 100644 --- a/src/wolfcrypt/src/cpuid.c +++ b/src/wolfcrypt/src/cpuid.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/cryptocb.c b/src/wolfcrypt/src/cryptocb.c index a83e529..801916e 100644 --- a/src/wolfcrypt/src/cryptocb.c +++ b/src/wolfcrypt/src/cryptocb.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -577,6 +577,7 @@ int wc_CryptoCb_RsaGetSize(const RsaKey* key, int* keySize) #endif /* !NO_RSA */ #ifdef HAVE_ECC +#ifdef HAVE_ECC_DHE int wc_CryptoCb_MakeEccKey(WC_RNG* rng, int keySize, ecc_key* key, int curveId) { int ret = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE); @@ -629,7 +630,9 @@ int wc_CryptoCb_Ecdh(ecc_key* private_key, ecc_key* public_key, return wc_CryptoCb_TranslateErrorCode(ret); } +#endif +#ifdef HAVE_ECC_SIGN int wc_CryptoCb_EccSign(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { @@ -658,7 +661,9 @@ int wc_CryptoCb_EccSign(const byte* in, word32 inlen, byte* out, return wc_CryptoCb_TranslateErrorCode(ret); } +#endif +#ifdef HAVE_ECC_VERIFY int wc_CryptoCb_EccVerify(const byte* sig, word32 siglen, const byte* hash, word32 hashlen, int* res, ecc_key* key) { @@ -687,7 +692,9 @@ int wc_CryptoCb_EccVerify(const byte* sig, word32 siglen, return wc_CryptoCb_TranslateErrorCode(ret); } +#endif +#ifdef HAVE_ECC_CHECK_KEY int wc_CryptoCb_EccCheckPrivKey(ecc_key* key, const byte* pubKey, word32 pubKeySz) { @@ -713,6 +720,7 @@ int wc_CryptoCb_EccCheckPrivKey(ecc_key* key, const byte* pubKey, return wc_CryptoCb_TranslateErrorCode(ret); } +#endif #endif /* HAVE_ECC */ #ifdef HAVE_CURVE25519 diff --git a/src/wolfcrypt/src/curve25519.c b/src/wolfcrypt/src/curve25519.c index ae2a6b4..1b383e7 100644 --- a/src/wolfcrypt/src/curve25519.c +++ b/src/wolfcrypt/src/curve25519.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -24,6 +24,10 @@ #include +#ifdef NO_CURVED25519_X64 + #undef USE_INTEL_SPEEDUP +#endif + #ifdef HAVE_CURVE25519 #include @@ -194,11 +198,11 @@ static int curve25519_smul_blind(byte* rp, const byte* n, const byte* p, if (ret < 0) { return ret; } - for (i = CURVE25519_KEYSIZE; i > 0; i--) { + for (i = CURVE25519_KEYSIZE - 1; i >= 0; i--) { if (rz[i] != 0xff) break; } - if ((i != 0) || (rz[0] <= 0xec)) { + if ((i >= 0) || (rz[0] <= 0xec)) { break; } } @@ -212,11 +216,11 @@ static int curve25519_smul_blind(byte* rp, const byte* n, const byte* p, return ret; a[CURVE25519_KEYSIZE-1] &= 0x7f; /* k' = k ^ 2k ^ a */ - n_a[0] = n[0] ^ (n[0] << 1) ^ a[0]; + n_a[0] = n[0] ^ (byte)(n[0] << 1) ^ a[0]; for (i = 1; i < CURVE25519_KEYSIZE; i++) { byte b1, b2, b3; b1 = n[i] ^ a[i]; - b2 = (n[i] << 1) ^ a[i]; + b2 = (byte)(n[i] << 1) ^ a[i]; b3 = (n[i-1] >> 7) ^ a[i]; n_a[i] = b1 ^ b2 ^ b3; } @@ -422,6 +426,9 @@ int wc_curve25519_make_key(WC_RNG* rng, int keysize, curve25519_key* key) ret = wc_curve25519_make_pub_blind((int)sizeof(key->p.point), key->p.point, (int)sizeof(key->k), key->k, rng); + if (ret == 0) { + ret = wc_curve25519_set_rng(key, rng); + } #else ret = wc_curve25519_make_pub((int)sizeof(key->p.point), key->p.point, (int)sizeof(key->k), key->k); diff --git a/src/wolfcrypt/src/curve448.c b/src/wolfcrypt/src/curve448.c index f3cf9f3..74e2cee 100644 --- a/src/wolfcrypt/src/curve448.c +++ b/src/wolfcrypt/src/curve448.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/des3.c b/src/wolfcrypt/src/des3.c index 7a9ba3b..d38fa40 100644 --- a/src/wolfcrypt/src/des3.c +++ b/src/wolfcrypt/src/des3.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1677,7 +1677,7 @@ static void DesProcessBlock(Des* des, const byte* in, byte* out) { - word32 l, r; + word32 l = 0, r = 0; XMEMCPY(&l, in, sizeof(l)); XMEMCPY(&r, in + sizeof(l), sizeof(r)); @@ -1700,7 +1700,7 @@ static void Des3ProcessBlock(Des3* des, const byte* in, byte* out) { - word32 l, r; + word32 l = 0, r = 0; XMEMCPY(&l, in, sizeof(l)); XMEMCPY(&r, in + sizeof(l), sizeof(r)); @@ -1727,6 +1727,10 @@ { word32 blocks = sz / DES_BLOCK_SIZE; + if (des == NULL || out == NULL || in == NULL) { + return BAD_FUNC_ARG; + } + while (blocks--) { xorbuf((byte*)des->reg, in, DES_BLOCK_SIZE); DesProcessBlock(des, (byte*)des->reg, (byte*)des->reg); @@ -1742,6 +1746,10 @@ { word32 blocks = sz / DES_BLOCK_SIZE; + if (des == NULL || out == NULL || in == NULL) { + return BAD_FUNC_ARG; + } + while (blocks--) { XMEMCPY(des->tmp, in, DES_BLOCK_SIZE); DesProcessBlock(des, (byte*)des->tmp, out); diff --git a/src/wolfcrypt/src/dh.c b/src/wolfcrypt/src/dh.c index 8869c03..a88259e 100644 --- a/src/wolfcrypt/src/dh.c +++ b/src/wolfcrypt/src/dh.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1373,6 +1373,38 @@ static int GeneratePublicDh(DhKey* key, byte* priv, word32 privSz, return ret; } +#if defined(WOLFSSL_DH_GEN_PUB) +/** + * Given a DhKey with set params and a priv key, generate the corresponding + * public key. If fips, does pub key validation. + * */ +WOLFSSL_API int wc_DhGeneratePublic(DhKey* key, byte* priv, word32 privSz, + byte* pub, word32* pubSz) +{ + int ret = 0; + + if (key == NULL || priv == NULL || privSz == 0 || + pub == NULL || pubSz == NULL) { + return BAD_FUNC_ARG; + } + + SAVE_VECTOR_REGISTERS(return _svr_ret;); + + ret = GeneratePublicDh(key, priv, privSz, pub, pubSz); + + #if FIPS_VERSION_GE(5,0) || defined(WOLFSSL_VALIDATE_DH_KEYGEN) + if (ret == 0) + ret = _ffc_validate_public_key(key, pub, *pubSz, NULL, 0, 0); + if (ret == 0) + ret = _ffc_pairwise_consistency_test(key, pub, *pubSz, priv, privSz); + #endif /* FIPS V5 or later || WOLFSSL_VALIDATE_DH_KEYGEN */ + + RESTORE_VECTOR_REGISTERS(); + + return ret; +} +#endif /* WOLFSSL_DH_GEN_PUB */ + static int wc_DhGenerateKeyPair_Sync(DhKey* key, WC_RNG* rng, byte* priv, word32* privSz, byte* pub, word32* pubSz) { @@ -2026,44 +2058,19 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #endif #ifdef WOLFSSL_HAVE_SP_DH + if (0 #ifndef WOLFSSL_SP_NO_2048 - if (mp_count_bits(&key->p) == 2048) { - if (mp_init(y) != MP_OKAY) - ret = MP_INIT_E; - - if (ret == 0) { - SAVE_VECTOR_REGISTERS(ret = _svr_ret;); - - if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) - ret = MP_READ_E; - - if (ret == 0) - ret = sp_DhExp_2048(y, priv, privSz, &key->p, agree, agreeSz); - - mp_clear(y); - - RESTORE_VECTOR_REGISTERS(); - } - - /* make sure agree is > 1 (SP800-56A, 5.7.1.1) */ - if ((ret == 0) && - ((*agreeSz == 0) || ((*agreeSz == 1) && (agree[0] == 1)))) - { - ret = MP_VAL; - } - - #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) - #if !defined(WOLFSSL_SP_MATH) - XFREE(z, key->heap, DYNAMIC_TYPE_DH); - XFREE(x, key->heap, DYNAMIC_TYPE_DH); - #endif - XFREE(y, key->heap, DYNAMIC_TYPE_DH); - #endif - return ret; - } + || mp_count_bits(&key->p) == 2048 #endif #ifndef WOLFSSL_SP_NO_3072 - if (mp_count_bits(&key->p) == 3072) { + || mp_count_bits(&key->p) == 3072 +#endif +#ifdef WOLFSSL_SP_4096 + || mp_count_bits(&key->p) == 4096 +#endif + ) { + int i = (int)*agreeSz - 1; + if (mp_init(y) != MP_OKAY) ret = MP_INIT_E; @@ -2073,8 +2080,26 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) ret = MP_READ_E; - if (ret == 0) - ret = sp_DhExp_3072(y, priv, privSz, &key->p, agree, agreeSz); + if (ret == 0) { + #ifndef WOLFSSL_SP_NO_2048 + if (mp_count_bits(&key->p) == 2048) { + ret = sp_DhExp_2048(y, priv, privSz, &key->p, agree, + agreeSz); + } + #endif + #ifndef WOLFSSL_SP_NO_3072 + if (mp_count_bits(&key->p) == 3072) { + ret = sp_DhExp_3072(y, priv, privSz, &key->p, agree, + agreeSz); + } + #endif + #ifdef WOLFSSL_SP_4096 + if (mp_count_bits(&key->p) == 4096) { + ret = sp_DhExp_4096(y, priv, privSz, &key->p, agree, + agreeSz); + } + #endif + } mp_clear(y); @@ -2088,40 +2113,16 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, ret = MP_VAL; } - #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) - #if !defined(WOLFSSL_SP_MATH) - XFREE(z, key->heap, DYNAMIC_TYPE_DH); - XFREE(x, key->heap, DYNAMIC_TYPE_DH); - #endif - XFREE(y, key->heap, DYNAMIC_TYPE_DH); - #endif - return ret; - } -#endif -#ifdef WOLFSSL_SP_4096 - if (mp_count_bits(&key->p) == 4096) { - if (mp_init(y) != MP_OKAY) - ret = MP_INIT_E; - - if (ret == 0) { - SAVE_VECTOR_REGISTERS(ret = _svr_ret;); - - if (ret == 0 && mp_read_unsigned_bin(y, otherPub, pubSz) != MP_OKAY) - ret = MP_READ_E; + if ((ret == 0) && ct) { + word16 mask = 0xff; + sword16 o = (sword16)(*agreeSz - 1); - if (ret == 0) - ret = sp_DhExp_4096(y, priv, privSz, &key->p, agree, agreeSz); - - mp_clear(y); - - RESTORE_VECTOR_REGISTERS(); - } - - /* make sure agree is > 1 (SP800-56A, 5.7.1.1) */ - if ((ret == 0) && - ((*agreeSz == 0) || ((*agreeSz == 1) && (agree[0] == 1)))) - { - ret = MP_VAL; + *agreeSz = (word32)(i + 1); + for (; i >= 0 ; i--) { + agree[i] = agree[o] & (byte)mask; + mask = ctMask16LT(0, (int)o); + o = (sword16)(o + (sword16)mask); + } } #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) @@ -2134,16 +2135,8 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, return ret; } #endif -#endif #if !defined(WOLFSSL_SP_MATH) - if (ct) { - /* for the constant-time variant, we will probably use more bits in x for - * the modexp than we read from the private key, and those extra bits need - * to be zeroed. - */ - XMEMSET(x, 0, sizeof *x); - } if (mp_init_multi(x, y, z, 0, 0, 0) != MP_OKAY) { #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(z, key->heap, DYNAMIC_TYPE_DH); @@ -2152,6 +2145,14 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, #endif return MP_INIT_E; } +#if defined(WOLFSSL_SP_MATH_ALL) + if (ct) { + /* TFM and Integer implementations keep high words zero. + * SP math implementation needs all words set to zero as it doesn't + * ensure unused words are zero. */ + mp_forcezero(x); + } +#endif SAVE_VECTOR_REGISTERS(ret = _svr_ret;); @@ -2166,12 +2167,24 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, ret = MP_READ_E; if (ret == 0) { - if (ct) - ret = mp_exptmod_ex(y, x, - ((int)*agreeSz + DIGIT_BIT - 1) / DIGIT_BIT, + if (ct) { + int bits; + + /* x is mod q but if q not available, use p (> q). */ + if (mp_iszero(&key->q) == MP_NO) { + bits = mp_count_bits(&key->q); + } + else { + bits = mp_count_bits(&key->p); + } + /* Exponentiate to the maximum words of a valid x to ensure a + * constant time operation. */ + ret = mp_exptmod_ex(y, x, (bits + DIGIT_BIT - 1) / DIGIT_BIT, &key->p, z); - else + } + else { ret = mp_exptmod(y, x, &key->p, z); + } if (ret != MP_OKAY) ret = MP_EXPTMOD_E; } @@ -2187,6 +2200,7 @@ static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz, if (ret == 0) { if (ct) { + /* Put the secret into a buffer in constant time. */ ret = mp_to_unsigned_bin_len_ct(z, agree, (int)*agreeSz); } else { @@ -2284,7 +2298,8 @@ int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv, #else #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_DH) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_DH) { - ret = wc_DhAgree_Async(key, agree, agreeSz, priv, privSz, otherPub, pubSz); + ret = wc_DhAgree_Async(key, agree, agreeSz, priv, privSz, otherPub, + pubSz); } else #endif @@ -2300,56 +2315,21 @@ int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv, int wc_DhAgree_ct(DhKey* key, byte* agree, word32 *agreeSz, const byte* priv, word32 privSz, const byte* otherPub, word32 pubSz) { - int ret; word32 requested_agreeSz; -#ifndef WOLFSSL_NO_MALLOC - byte *agree_buffer = NULL; -#else - byte agree_buffer[DH_MAX_SIZE / 8]; -#endif if (key == NULL || agree == NULL || agreeSz == NULL || priv == NULL || otherPub == NULL) { return BAD_FUNC_ARG; } - requested_agreeSz = *agreeSz; - -#ifndef WOLFSSL_NO_MALLOC - agree_buffer = (byte *)XMALLOC(requested_agreeSz, key->heap, - DYNAMIC_TYPE_DH); - if (agree_buffer == NULL) - return MEMORY_E; -#endif - - XMEMSET(agree_buffer, 0, requested_agreeSz); - - ret = wc_DhAgree_Sync(key, agree_buffer, agreeSz, priv, privSz, otherPub, - pubSz, 1); - - if (ret == 0) { - /* Arrange for correct fixed-length, right-justified key, even if the - * crypto back end doesn't support it. This assures that the key is - * unconditionally agreed correctly. With some crypto back ends, - * e.g. heapmath, there are no provisions for actual constant time, but - * with others the key computation and clamping is constant time, and - * the unclamping here is also constant time. - */ - byte *agree_src = agree_buffer + *agreeSz - 1, - *agree_dst = agree + requested_agreeSz - 1; - while (agree_dst >= agree) { - word32 mask = (agree_src >= agree_buffer) - 1U; - agree_src += (mask & requested_agreeSz); - *agree_dst-- = *agree_src--; - } - *agreeSz = requested_agreeSz; + requested_agreeSz = (word32)mp_unsigned_bin_size(&key->p); + if (requested_agreeSz > *agreeSz) { + return BUFFER_E; } + *agreeSz = requested_agreeSz; -#ifndef WOLFSSL_NO_MALLOC - XFREE(agree_buffer, key->heap, DYNAMIC_TYPE_DH); -#endif - - return ret; + return wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz, + 1); } #ifdef WOLFSSL_DH_EXTRA @@ -2501,8 +2481,8 @@ int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz, #endif /* WOLFSSL_DH_EXTRA */ static int _DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g, - word32 gSz, const byte* q, word32 qSz, int trusted, - WC_RNG* rng) + word32 gSz, const byte* q, word32 qSz, int trusted, + WC_RNG* rng) { int ret = 0; mp_int* keyP = NULL; diff --git a/src/wolfcrypt/src/dilithium.c b/src/wolfcrypt/src/dilithium.c index 1aa2750..ac8e5d8 100644 --- a/src/wolfcrypt/src/dilithium.c +++ b/src/wolfcrypt/src/dilithium.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -502,11 +502,12 @@ static int dilithium_get_hash_oid(int hash, byte* oidBuffer, word32* oidLen) #ifndef WOLFSSL_DILITHIUM_NO_ASN1 - oid = OidFromId(wc_HashGetOID((enum wc_HashType)hash), oidHashType, oidLen); + oid = OidFromId((word32)wc_HashGetOID((enum wc_HashType)hash), oidHashType, + oidLen); if ((oid != NULL) && (*oidLen <= DILITHIUM_HASH_OID_LEN - 2)) { #ifndef WOLFSSL_DILITHIUM_REVERSE_HASH_OID - oidBuffer[0] = 0x06; /* ObjectID */ - oidBuffer[1] = *oidLen; /* ObjectID */ + oidBuffer[0] = 0x06; /* ObjectID */ + oidBuffer[1] = (byte)*oidLen; /* ObjectID */ oidBuffer += 2; XMEMCPY(oidBuffer, oid, *oidLen); #else @@ -733,19 +734,19 @@ static void dilthium_vec_encode_eta_bits(const sword32* s, byte d, byte eta, * 8 numbers become 3 bytes. (8 * 3 bits = 3 * 8 bits) */ for (j = 0; j < DILITHIUM_N; j += 8) { /* Make value a positive integer. */ - byte s0 = 2 - s[j + 0]; - byte s1 = 2 - s[j + 1]; - byte s2 = 2 - s[j + 2]; - byte s3 = 2 - s[j + 3]; - byte s4 = 2 - s[j + 4]; - byte s5 = 2 - s[j + 5]; - byte s6 = 2 - s[j + 6]; - byte s7 = 2 - s[j + 7]; + byte s0 = (byte)(2 - s[j + 0]); + byte s1 = (byte)(2 - s[j + 1]); + byte s2 = (byte)(2 - s[j + 2]); + byte s3 = (byte)(2 - s[j + 3]); + byte s4 = (byte)(2 - s[j + 4]); + byte s5 = (byte)(2 - s[j + 5]); + byte s6 = (byte)(2 - s[j + 6]); + byte s7 = (byte)(2 - s[j + 7]); /* Pack 8 3-bit values into 3 bytes. */ - p[0] = (s0 >> 0) | (s1 << 3) | (s2 << 6); - p[1] = (s2 >> 2) | (s3 << 1) | (s4 << 4) | (s5 << 7); - p[2] = (s5 >> 1) | (s6 << 2) | (s7 << 5); + p[0] = (byte)((s0 >> 0) | (s1 << 3) | (s2 << 6)); + p[1] = (byte)((s2 >> 2) | (s3 << 1) | (s4 << 4) | (s5 << 7)); + p[2] = (byte)((s5 >> 1) | (s6 << 2) | (s7 << 5)); /* Move to next place to encode into. */ p += DILITHIUM_ETA_2_BITS; } @@ -774,14 +775,14 @@ static void dilthium_vec_encode_eta_bits(const sword32* s, byte d, byte eta, * 8 numbers become 4 bytes. (8 * 4 bits = 4 * 8 bits) */ for (j = 0; j < DILITHIUM_N / 2; j += 4) { /* Make values positive and pack 2 4-bit values into 1 byte. */ - p[j + 0] = (((byte)(4 - s[j * 2 + 0])) << 0) | - (((byte)(4 - s[j * 2 + 1])) << 4); - p[j + 1] = (((byte)(4 - s[j * 2 + 2])) << 0) | - (((byte)(4 - s[j * 2 + 3])) << 4); - p[j + 2] = (((byte)(4 - s[j * 2 + 4])) << 0) | - (((byte)(4 - s[j * 2 + 5])) << 4); - p[j + 3] = (((byte)(4 - s[j * 2 + 6])) << 0) | - (((byte)(4 - s[j * 2 + 7])) << 4); + p[j + 0] = (byte)((((byte)(4 - s[j * 2 + 0])) << 0) | + (((byte)(4 - s[j * 2 + 1])) << 4)); + p[j + 1] = (byte)((((byte)(4 - s[j * 2 + 2])) << 0) | + (((byte)(4 - s[j * 2 + 3])) << 4)); + p[j + 2] = (byte)((((byte)(4 - s[j * 2 + 4])) << 0) | + (((byte)(4 - s[j * 2 + 5])) << 4)); + p[j + 3] = (byte)((((byte)(4 - s[j * 2 + 6])) << 0) | + (((byte)(4 - s[j * 2 + 7])) << 4)); } #endif /* Move to next place to encode into. */ @@ -993,31 +994,39 @@ static void dilithium_vec_encode_t0_t1(sword32* t, byte d, byte* t0, byte* t1) * Do all polynomial values - 8 at a time. */ for (j = 0; j < DILITHIUM_N; j += 8) { /* Take 8 values of t and take top bits and make positive. */ - word16 n1_0 = (t[j + 0] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_1 = (t[j + 1] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_2 = (t[j + 2] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_3 = (t[j + 3] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_4 = (t[j + 4] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_5 = (t[j + 5] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_6 = (t[j + 6] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; - word16 n1_7 = (t[j + 7] + DILITHIUM_D_MAX_HALF - 1) >> DILITHIUM_D; + word16 n1_0 = (word16)((t[j + 0] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_1 = (word16)((t[j + 1] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_2 = (word16)((t[j + 2] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_3 = (word16)((t[j + 3] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_4 = (word16)((t[j + 4] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_5 = (word16)((t[j + 5] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_6 = (word16)((t[j + 6] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); + word16 n1_7 = (word16)((t[j + 7] + DILITHIUM_D_MAX_HALF - 1) >> + DILITHIUM_D); /* Take 8 values of t and take bottom bits and make positive. */ - word16 n0_0 = DILITHIUM_D_MAX_HALF - - (t[j + 0] - (n1_0 << DILITHIUM_D)); - word16 n0_1 = DILITHIUM_D_MAX_HALF - - (t[j + 1] - (n1_1 << DILITHIUM_D)); - word16 n0_2 = DILITHIUM_D_MAX_HALF - - (t[j + 2] - (n1_2 << DILITHIUM_D)); - word16 n0_3 = DILITHIUM_D_MAX_HALF - - (t[j + 3] - (n1_3 << DILITHIUM_D)); - word16 n0_4 = DILITHIUM_D_MAX_HALF - - (t[j + 4] - (n1_4 << DILITHIUM_D)); - word16 n0_5 = DILITHIUM_D_MAX_HALF - - (t[j + 5] - (n1_5 << DILITHIUM_D)); - word16 n0_6 = DILITHIUM_D_MAX_HALF - - (t[j + 6] - (n1_6 << DILITHIUM_D)); - word16 n0_7 = DILITHIUM_D_MAX_HALF - - (t[j + 7] - (n1_7 << DILITHIUM_D)); + word16 n0_0 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 0] - (n1_0 << DILITHIUM_D))); + word16 n0_1 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 1] - (n1_1 << DILITHIUM_D))); + word16 n0_2 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 2] - (n1_2 << DILITHIUM_D))); + word16 n0_3 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 3] - (n1_3 << DILITHIUM_D))); + word16 n0_4 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 4] - (n1_4 << DILITHIUM_D))); + word16 n0_5 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 5] - (n1_5 << DILITHIUM_D))); + word16 n0_6 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 6] - (n1_6 << DILITHIUM_D))); + word16 n0_7 = (word16)(DILITHIUM_D_MAX_HALF - + (t[j + 7] - (n1_7 << DILITHIUM_D))); /* 13 bits per number. * 8 numbers become 13 bytes. (8 * 13 bits = 13 * 8 bits) */ @@ -1031,20 +1040,20 @@ static void dilithium_vec_encode_t0_t1(sword32* t, byte d, byte* t0, byte* t1) tp[2] = (n0_4 >> 12) | ((word32)n0_5 << 1) | ((word32)n0_6 << 14) | ((word32)n0_7 << 27); #else - t0[ 0] = (n0_0 << 0); - t0[ 1] = (n0_0 >> 8) | (n0_1 << 5); - t0[ 2] = (n0_1 >> 3) ; - t0[ 3] = (n0_1 >> 11) | (n0_2 << 2); - t0[ 4] = (n0_2 >> 6) | (n0_3 << 7); - t0[ 5] = (n0_3 >> 1) ; - t0[ 6] = (n0_3 >> 9) | (n0_4 << 4); - t0[ 7] = (n0_4 >> 4) ; - t0[ 8] = (n0_4 >> 12) | (n0_5 << 1); - t0[ 9] = (n0_5 >> 7) | (n0_6 << 6); - t0[10] = (n0_6 >> 2) ; - t0[11] = (n0_6 >> 10) | (n0_7 << 3); + t0[ 0] = (byte)( (n0_0 << 0)); + t0[ 1] = (byte)((n0_0 >> 8) | (n0_1 << 5)); + t0[ 2] = (byte)((n0_1 >> 3) ); + t0[ 3] = (byte)((n0_1 >> 11) | (n0_2 << 2)); + t0[ 4] = (byte)((n0_2 >> 6) | (n0_3 << 7)); + t0[ 5] = (byte)((n0_3 >> 1) ); + t0[ 6] = (byte)((n0_3 >> 9) | (n0_4 << 4)); + t0[ 7] = (byte)((n0_4 >> 4) ); + t0[ 8] = (byte)((n0_4 >> 12) | (n0_5 << 1)); + t0[ 9] = (byte)((n0_5 >> 7) | (n0_6 << 6)); + t0[10] = (byte)((n0_6 >> 2) ); + t0[11] = (byte)((n0_6 >> 10) | (n0_7 << 3)); #endif - t0[12] = (n0_7 >> 5) ; + t0[12] = (byte)((n0_7 >> 5) ); /* 10 bits per number. * 8 bytes become 10 bytes. (8 * 10 bits = 10 * 8 bits) */ @@ -1055,17 +1064,17 @@ static void dilithium_vec_encode_t0_t1(sword32* t, byte d, byte* t0, byte* t1) tp[1] = (n1_3 >> 2) | ((word32)n1_4 << 8) | ((word32)n1_5 << 18) | ((word32)n1_6 << 28); #else - t1[0] = (n1_0 << 0); - t1[1] = (n1_0 >> 8) | (n1_1 << 2); - t1[2] = (n1_1 >> 6) | (n1_2 << 4); - t1[3] = (n1_2 >> 4) | (n1_3 << 6); - t1[4] = (n1_3 >> 2) ; - t1[5] = (n1_4 << 0); - t1[6] = (n1_4 >> 8) | (n1_5 << 2); - t1[7] = (n1_5 >> 6) | (n1_6 << 4); + t1[0] = (byte)( (n1_0 << 0)); + t1[1] = (byte)((n1_0 >> 8) | (n1_1 << 2)); + t1[2] = (byte)((n1_1 >> 6) | (n1_2 << 4)); + t1[3] = (byte)((n1_2 >> 4) | (n1_3 << 6)); + t1[4] = (byte)((n1_3 >> 2) ); + t1[5] = (byte)( (n1_4 << 0)); + t1[6] = (byte)((n1_4 >> 8) | (n1_5 << 2)); + t1[7] = (byte)((n1_5 >> 6) | (n1_6 << 4)); #endif - t1[8] = (n1_6 >> 4) | (n1_7 << 6); - t1[9] = (n1_7 >> 2) ; + t1[8] = (byte)((n1_6 >> 4) | (n1_7 << 6)); + t1[9] = (byte)((n1_7 >> 2) ); /* Move to next place to encode bottom bits to. */ t0 += DILITHIUM_D; @@ -1106,7 +1115,7 @@ static void dilithium_decode_t0(const byte* t0, sword32* t) t[j + 1] = DILITHIUM_D_MAX_HALF - ((t64 >> 13) & 0x1fff); t[j + 2] = DILITHIUM_D_MAX_HALF - ((t64 >> 26) & 0x1fff); t[j + 3] = DILITHIUM_D_MAX_HALF - ((t64 >> 39) & 0x1fff); - t[j + 4] = DILITHIUM_D_MAX_HALF - + t[j + 4] = DILITHIUM_D_MAX_HALF - (sword32) ((t64 >> 52) | ((t32_2 & 0x0001) << 12)); #else word32 t32_0 = ((const word32*)t0)[0]; @@ -1115,18 +1124,18 @@ static void dilithium_decode_t0(const byte* t0, sword32* t) ( t32_0 & 0x1fff); t[j + 1] = DILITHIUM_D_MAX_HALF - ((t32_0 >> 13) & 0x1fff); - t[j + 2] = DILITHIUM_D_MAX_HALF - + t[j + 2] = DILITHIUM_D_MAX_HALF - (sword32) (( t32_0 >> 26 ) | ((t32_1 & 0x007f) << 6)); t[j + 3] = DILITHIUM_D_MAX_HALF - ((t32_1 >> 7) & 0x1fff); - t[j + 4] = DILITHIUM_D_MAX_HALF - + t[j + 4] = DILITHIUM_D_MAX_HALF - (sword32) (( t32_1 >> 20 ) | ((t32_2 & 0x0001) << 12)); #endif t[j + 5] = DILITHIUM_D_MAX_HALF - ((t32_2 >> 1) & 0x1fff); t[j + 6] = DILITHIUM_D_MAX_HALF - ((t32_2 >> 14) & 0x1fff); - t[j + 7] = DILITHIUM_D_MAX_HALF - + t[j + 7] = DILITHIUM_D_MAX_HALF - (sword32) (( t32_2 >> 27 ) | ((word32)t0[12] ) << 5 ); #else t[j + 0] = DILITHIUM_D_MAX_HALF - @@ -1216,7 +1225,8 @@ static void dilithium_decode_t1(const byte* t1, sword32* t) t[j+3] = (sword32)( ((t64 >> 30) & 0x03ff) << DILITHIUM_D); t[j+4] = (sword32)( ((t64 >> 40) & 0x03ff) << DILITHIUM_D); t[j+5] = (sword32)( ((t64 >> 50) & 0x03ff) << DILITHIUM_D); - t[j+6] = (sword32)((((t64 >> 60)| (t16 << 4)) & 0x03ff) << DILITHIUM_D); + t[j+6] = (sword32)((((t64 >> 60) | + (word64)(t16 << 4)) & 0x03ff) << DILITHIUM_D); t[j+7] = (sword32)( ((t16 >> 6) & 0x03ff) << DILITHIUM_D); #else word32 t32 = *((const word32*)t1); @@ -1311,10 +1321,10 @@ static void dilithium_encode_gamma1_17_bits(const sword32* z, byte* s) /* Step 3. Get 18 bits as a number. */ for (j = 0; j < DILITHIUM_N; j += 4) { - word32 z0 = DILITHIUM_GAMMA1_17 - z[j + 0]; - word32 z1 = DILITHIUM_GAMMA1_17 - z[j + 1]; - word32 z2 = DILITHIUM_GAMMA1_17 - z[j + 2]; - word32 z3 = DILITHIUM_GAMMA1_17 - z[j + 3]; + word32 z0 = (word32)(DILITHIUM_GAMMA1_17 - z[j + 0]); + word32 z1 = (word32)(DILITHIUM_GAMMA1_17 - z[j + 1]); + word32 z2 = (word32)(DILITHIUM_GAMMA1_17 - z[j + 2]); + word32 z3 = (word32)(DILITHIUM_GAMMA1_17 - z[j + 3]); /* 18 bits per number. * 8 numbers become 9 bytes. (8 * 9 bits = 9 * 8 bits) */ @@ -1329,16 +1339,16 @@ static void dilithium_encode_gamma1_17_bits(const sword32* z, byte* s) s32p[1] = (z1 >> 14) | (z2 << 4) | (z3 << 22); #endif #else - s[0] = z0 ; - s[1] = z0 >> 8 ; - s[2] = (z0 >> 16) | (z1 << 2); - s[3] = z1 >> 6 ; - s[4] = (z1 >> 14) | (z2 << 4); - s[5] = z2 >> 4 ; - s[6] = (z2 >> 12) | (z3 << 6); - s[7] = z3 >> 2 ; -#endif - s[8] = z3 >> 10 ; + s[0] = (byte)( z0 ); + s[1] = (byte)( z0 >> 8 ); + s[2] = (byte)((z0 >> 16) | (z1 << 2)); + s[3] = (byte)( z1 >> 6 ); + s[4] = (byte)((z1 >> 14) | (z2 << 4)); + s[5] = (byte)( z2 >> 4 ); + s[6] = (byte)((z2 >> 12) | (z3 << 6)); + s[7] = (byte)( z3 >> 2 ); +#endif + s[8] = (byte)( z3 >> 10 ); /* Move to next place to encode to. */ s += DILITHIUM_GAMMA1_17_ENC_BITS / 2; } @@ -1372,14 +1382,14 @@ static void dilithium_encode_gamma1_19_bits(const sword32* z, byte* s) word16* s16p = (word16*)s; #ifdef WC_64BIT_CPU word64* s64p = (word64*)s; - s64p[0] = z0 | ((word64)z1 << 20) | + s64p[0] = (word64)z0 | ((word64)z1 << 20) | ((word64)z2 << 40) | ((word64)z3 << 60); #else word32* s32p = (word32*)s; - s32p[0] = z0 | (z1 << 20) ; - s32p[1] = (z1 >> 12) | (z2 << 8) | (z3 << 28); + s32p[0] = (word32)( z0 | (z1 << 20) ); + s32p[1] = (word32)((z1 >> 12) | (z2 << 8) | (z3 << 28)); #endif - s16p[4] = (z3 >> 4) ; + s16p[4] = (word16)((z3 >> 4) ); #else s[0] = z0 ; s[1] = (z0 >> 8) ; @@ -1525,69 +1535,69 @@ static void dilithium_decode_gamma1(const byte* s, int bits, sword32* z) #ifdef WC_64BIT_CPU word64 s64_0 = *(const word64*)(s+0); word64 s64_1 = *(const word64*)(s+9); - z[i+0] = (word32)DILITHIUM_GAMMA1_17 - - ( s64_0 & 0x3ffff ); - z[i+1] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_0 >> 18) & 0x3ffff ); - z[i+2] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_0 >> 36) & 0x3ffff ); - z[i+3] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_0 >> 54) | (((word32)s[8]) << 10)); - z[i+4] = (word32)DILITHIUM_GAMMA1_17 - - ( s64_1 & 0x3ffff ); - z[i+5] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_1 >> 18) & 0x3ffff ); - z[i+6] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_1 >> 36) & 0x3ffff ); - z[i+7] = (word32)DILITHIUM_GAMMA1_17 - - ((s64_1 >> 54) | (((word32)s[17]) << 10)); + z[i+0] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s64_0 & 0x3ffff )); + z[i+1] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 18) & 0x3ffff )); + z[i+2] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 36) & 0x3ffff )); + z[i+3] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_0 >> 54) | (((word32)s[8]) << 10))); + z[i+4] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s64_1 & 0x3ffff )); + z[i+5] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 18) & 0x3ffff )); + z[i+6] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 36) & 0x3ffff )); + z[i+7] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s64_1 >> 54) | (((word32)s[17]) << 10))); #else word32 s32_0 = ((const word32*)(s+0))[0]; word32 s32_1 = ((const word32*)(s+0))[1]; word32 s32_2 = ((const word32*)(s+9))[0]; word32 s32_3 = ((const word32*)(s+9))[1]; - z[i+0] = (word32)DILITHIUM_GAMMA1_17 - - ( s32_0 & 0x3ffff ); - z[i+1] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_0 >> 18) | (((s32_1 & 0x0000f) << 14))); - z[i+2] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_1 >> 4) & 0x3ffff); - z[i+3] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_1 >> 22) | (((word32)s[8]) << 10 )); - z[i+4] = (word32)DILITHIUM_GAMMA1_17 - - ( s32_2 & 0x3ffff ); - z[i+5] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_2 >> 18) | (((s32_3 & 0x0000f) << 14))); - z[i+6] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_3 >> 4) & 0x3ffff); - z[i+7] = (word32)DILITHIUM_GAMMA1_17 - - ((s32_3 >> 22) | (((word32)s[17]) << 10 )); + z[i+0] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s32_0 & 0x3ffff )); + z[i+1] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_0 >> 18) | (((s32_1 & 0x0000f) << 14)))); + z[i+2] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 4) & 0x3ffff )); + z[i+3] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_1 >> 22) | (((word32)s[8]) << 10 ))); + z[i+4] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s32_2 & 0x3ffff )); + z[i+5] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_2 >> 18) | (((s32_3 & 0x0000f) << 14)))); + z[i+6] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_3 >> 4) & 0x3ffff )); + z[i+7] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s32_3 >> 22) | (((word32)s[17]) << 10 ))); #endif #else - z[i+0] = DILITHIUM_GAMMA1_17 - - ( s[ 0] | ((sword32)(s[ 1] << 8) | - (sword32)(s[ 2] & 0x03) << 16)); - z[i+1] = DILITHIUM_GAMMA1_17 - - ((s[ 2] >> 2) | ((sword32)(s[ 3] << 6) | - (sword32)(s[ 4] & 0x0f) << 14)); - z[i+2] = DILITHIUM_GAMMA1_17 - - ((s[ 4] >> 4) | ((sword32)(s[ 5] << 4) | - (sword32)(s[ 6] & 0x3f) << 12)); - z[i+3] = DILITHIUM_GAMMA1_17 - - ((s[ 6] >> 6) | ((sword32)(s[ 7] << 2) | - (sword32)(s[ 8] ) << 10)); - z[i+4] = DILITHIUM_GAMMA1_17 - - ( s[ 9] | ((sword32)(s[10] << 8) | - (sword32)(s[11] & 0x03) << 16)); - z[i+5] = DILITHIUM_GAMMA1_17 - - ((s[11] >> 2) | ((sword32)(s[12] << 6) | - (sword32)(s[13] & 0x0f) << 14)); - z[i+6] = DILITHIUM_GAMMA1_17 - - ((s[13] >> 4) | ((sword32)(s[14] << 4) | - (sword32)(s[15] & 0x3f) << 12)); - z[i+7] = DILITHIUM_GAMMA1_17 - - ((s[15] >> 6) | ((sword32)(s[16] << 2) | - (sword32)(s[17] ) << 10)); + z[i+0] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s[ 0] | ((sword32)(s[ 1] << 8) | + (sword32)(s[ 2] & 0x03) << 16))); + z[i+1] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[ 2] >> 2) | ((sword32)(s[ 3] << 6) | + (sword32)(s[ 4] & 0x0f) << 14))); + z[i+2] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[ 4] >> 4) | ((sword32)(s[ 5] << 4) | + (sword32)(s[ 6] & 0x3f) << 12))); + z[i+3] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[ 6] >> 6) | ((sword32)(s[ 7] << 2) | + (sword32)(s[ 8] ) << 10))); + z[i+4] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ( s[ 9] | ((sword32)(s[10] << 8) | + (sword32)(s[11] & 0x03) << 16))); + z[i+5] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[11] >> 2) | ((sword32)(s[12] << 6) | + (sword32)(s[13] & 0x0f) << 14))); + z[i+6] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[13] >> 4) | ((sword32)(s[14] << 4) | + (sword32)(s[15] & 0x3f) << 12))); + z[i+7] = (sword32)((word32)DILITHIUM_GAMMA1_17 - + ((s[15] >> 6) | ((sword32)(s[16] << 2) | + (sword32)(s[17] ) << 10))); #endif /* Move to next place to decode from. */ s += DILITHIUM_GAMMA1_17_ENC_BITS; @@ -1646,16 +1656,24 @@ static void dilithium_decode_gamma1(const byte* s, int bits, sword32* z) #ifdef WC_64BIT_CPU word64 s64_0 = *(const word64*)(s+0); word64 s64_1 = *(const word64*)(s+10); - z[i+0] = DILITHIUM_GAMMA1_19 - ( s64_0 & 0xfffff) ; - z[i+1] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 20) & 0xfffff) ; - z[i+2] = DILITHIUM_GAMMA1_19 - ( (s64_0 >> 40) & 0xfffff) ; - z[i+3] = DILITHIUM_GAMMA1_19 - (((s64_0 >> 60) & 0xfffff) | - ((sword32)s16_0 << 4)); - z[i+4] = DILITHIUM_GAMMA1_19 - ( s64_1 & 0xfffff) ; - z[i+5] = DILITHIUM_GAMMA1_19 - ( (s64_1 >> 20) & 0xfffff) ; - z[i+6] = DILITHIUM_GAMMA1_19 - ( (s64_1 >> 40) & 0xfffff) ; - z[i+7] = DILITHIUM_GAMMA1_19 - (((s64_1 >> 60) & 0xfffff) | - ((sword32)s16_1 << 4)); + z[i+0] = DILITHIUM_GAMMA1_19 - + ((sword32)( s64_0 & 0xfffff)) ; + z[i+1] = DILITHIUM_GAMMA1_19 - + ((sword32)( (s64_0 >> 20) & 0xfffff)) ; + z[i+2] = DILITHIUM_GAMMA1_19 - + ((sword32)( (s64_0 >> 40) & 0xfffff)) ; + z[i+3] = DILITHIUM_GAMMA1_19 - + ((sword32)(((s64_0 >> 60) & 0xfffff)) | + ((sword32)s16_0 << 4)); + z[i+4] = DILITHIUM_GAMMA1_19 - + ((sword32)( s64_1 & 0xfffff)) ; + z[i+5] = DILITHIUM_GAMMA1_19 - + ((sword32)( (s64_1 >> 20) & 0xfffff)) ; + z[i+6] = DILITHIUM_GAMMA1_19 - + ((sword32)( (s64_1 >> 40) & 0xfffff)) ; + z[i+7] = DILITHIUM_GAMMA1_19 - + ((sword32)(((s64_1 >> 60) & 0xfffff)) | + ((sword32)s16_1 << 4)); #else word32 s32_0 = ((const word32*)(s+ 0))[0]; word32 s32_1 = ((const word32*)(s+ 0))[1]; @@ -1767,28 +1785,28 @@ static void dilithium_encode_w1_88(const sword32* w1, byte* w1e) * 16 numbers in 12 bytes. (16 * 6 bits = 12 * 8 bits) */ #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 4) word32* w1e32 = (word32*)w1e; - w1e32[0] = w1[j+ 0] | (w1[j+ 1] << 6) | - (w1[j+ 2] << 12) | (w1[j+ 3] << 18) | - (w1[j+ 4] << 24) | (w1[j+ 5] << 30); - w1e32[1] = (w1[j+ 5] >> 2) | (w1[j+ 6] << 4) | - (w1[j+ 7] << 10) | (w1[j+ 8] << 16) | - (w1[j+ 9] << 22) | (w1[j+10] << 28); - w1e32[2] = (w1[j+10] >> 4) | (w1[j+11] << 2) | - (w1[j+12] << 8) | (w1[j+13] << 14) | - (w1[j+14] << 20) | (w1[j+15] << 26); + w1e32[0] = (word32)( w1[j+ 0] | (w1[j+ 1] << 6) | + (w1[j+ 2] << 12) | (w1[j+ 3] << 18) | + (w1[j+ 4] << 24) | (w1[j+ 5] << 30)); + w1e32[1] = (word32)((w1[j+ 5] >> 2) | (w1[j+ 6] << 4) | + (w1[j+ 7] << 10) | (w1[j+ 8] << 16) | + (w1[j+ 9] << 22) | (w1[j+10] << 28)); + w1e32[2] = (word32)((w1[j+10] >> 4) | (w1[j+11] << 2) | + (w1[j+12] << 8) | (w1[j+13] << 14) | + (w1[j+14] << 20) | (w1[j+15] << 26)); #else - w1e[ 0] = w1[j+ 0] | (w1[j+ 1] << 6); - w1e[ 1] = (w1[j+ 1] >> 2) | (w1[j+ 2] << 4); - w1e[ 2] = (w1[j+ 2] >> 4) | (w1[j+ 3] << 2); - w1e[ 3] = w1[j+ 4] | (w1[j+ 5] << 6); - w1e[ 4] = (w1[j+ 5] >> 2) | (w1[j+ 6] << 4); - w1e[ 5] = (w1[j+ 6] >> 4) | (w1[j+ 7] << 2); - w1e[ 6] = w1[j+ 8] | (w1[j+ 9] << 6); - w1e[ 7] = (w1[j+ 9] >> 2) | (w1[j+10] << 4); - w1e[ 8] = (w1[j+10] >> 4) | (w1[j+11] << 2); - w1e[ 9] = w1[j+12] | (w1[j+13] << 6); - w1e[10] = (w1[j+13] >> 2) | (w1[j+14] << 4); - w1e[11] = (w1[j+14] >> 4) | (w1[j+15] << 2); + w1e[ 0] = (byte)( w1[j+ 0] | (w1[j+ 1] << 6)); + w1e[ 1] = (byte)((w1[j+ 1] >> 2) | (w1[j+ 2] << 4)); + w1e[ 2] = (byte)((w1[j+ 2] >> 4) | (w1[j+ 3] << 2)); + w1e[ 3] = (byte)( w1[j+ 4] | (w1[j+ 5] << 6)); + w1e[ 4] = (byte)((w1[j+ 5] >> 2) | (w1[j+ 6] << 4)); + w1e[ 5] = (byte)((w1[j+ 6] >> 4) | (w1[j+ 7] << 2)); + w1e[ 6] = (byte)( w1[j+ 8] | (w1[j+ 9] << 6)); + w1e[ 7] = (byte)((w1[j+ 9] >> 2) | (w1[j+10] << 4)); + w1e[ 8] = (byte)((w1[j+10] >> 4) | (w1[j+11] << 2)); + w1e[ 9] = (byte)( w1[j+12] | (w1[j+13] << 6)); + w1e[10] = (byte)((w1[j+13] >> 2) | (w1[j+14] << 4)); + w1e[11] = (byte)((w1[j+14] >> 4) | (w1[j+15] << 2)); #endif /* Move to next place to encode to. */ w1e += DILITHIUM_Q_HI_88_ENC_BITS * 2; @@ -1819,23 +1837,23 @@ static void dilithium_encode_w1_32(const sword32* w1, byte* w1e) * 16 numbers in 8 bytes. (16 * 4 bits = 8 * 8 bits) */ #if defined(LITTLE_ENDIAN_ORDER) && (WOLFSSL_DILITHIUM_ALIGNMENT <= 8) word32* w1e32 = (word32*)w1e; - w1e32[0] = (w1[j + 0] << 0) | (w1[j + 1] << 4) | - (w1[j + 2] << 8) | (w1[j + 3] << 12) | - (w1[j + 4] << 16) | (w1[j + 5] << 20) | - (w1[j + 6] << 24) | (w1[j + 7] << 28); - w1e32[1] = (w1[j + 8] << 0) | (w1[j + 9] << 4) | - (w1[j + 10] << 8) | (w1[j + 11] << 12) | - (w1[j + 12] << 16) | (w1[j + 13] << 20) | - (w1[j + 14] << 24) | (w1[j + 15] << 28); + w1e32[0] = (word32)((w1[j + 0] << 0) | (w1[j + 1] << 4) | + (w1[j + 2] << 8) | (w1[j + 3] << 12) | + (w1[j + 4] << 16) | (w1[j + 5] << 20) | + (w1[j + 6] << 24) | (w1[j + 7] << 28)); + w1e32[1] = (word32)((w1[j + 8] << 0) | (w1[j + 9] << 4) | + (w1[j + 10] << 8) | (w1[j + 11] << 12) | + (w1[j + 12] << 16) | (w1[j + 13] << 20) | + (w1[j + 14] << 24) | (w1[j + 15] << 28)); #else - w1e[0] = w1[j + 0] | (w1[j + 1] << 4); - w1e[1] = w1[j + 2] | (w1[j + 3] << 4); - w1e[2] = w1[j + 4] | (w1[j + 5] << 4); - w1e[3] = w1[j + 6] | (w1[j + 7] << 4); - w1e[4] = w1[j + 8] | (w1[j + 9] << 4); - w1e[5] = w1[j + 10] | (w1[j + 11] << 4); - w1e[6] = w1[j + 12] | (w1[j + 13] << 4); - w1e[7] = w1[j + 14] | (w1[j + 15] << 4); + w1e[0] = (byte)(w1[j + 0] | (w1[j + 1] << 4)); + w1e[1] = (byte)(w1[j + 2] | (w1[j + 3] << 4)); + w1e[2] = (byte)(w1[j + 4] | (w1[j + 5] << 4)); + w1e[3] = (byte)(w1[j + 6] | (w1[j + 7] << 4)); + w1e[4] = (byte)(w1[j + 8] | (w1[j + 9] << 4)); + w1e[5] = (byte)(w1[j + 10] | (w1[j + 11] << 4)); + w1e[6] = (byte)(w1[j + 12] | (w1[j + 13] << 4)); + w1e[7] = (byte)(w1[j + 14] | (w1[j + 15] << 4)); #endif /* Move to next place to encode to. */ w1e += DILITHIUM_Q_HI_32_ENC_BITS * 2; @@ -2289,7 +2307,7 @@ static int dilithium_expand_a(wc_Shake* shake128, const byte* pub_seed, byte k, #define DILITHIUM_COEFF_S_VALID_ETA2(b) \ ((b) < DILITHIUM_ETA_2_MOD) -static const char dilithium_coeff_eta2[] = { +static const signed char dilithium_coeff_eta2[] = { 2, 1, 0, -1, -2, 2, 1, 0, -1, -2, 2, 1, 0, -1, -2 @@ -2802,10 +2820,12 @@ static int dilithium_sample_in_ball_ex(int level, wc_Shake* shake256, const byte* seed, word32 seedLen, byte tau, sword32* c, byte* block) { int ret = 0; - unsigned int k; - unsigned int i; - unsigned int s; byte signs[DILITHIUM_SIGN_BYTES]; + unsigned int i; + /* Step 1: Initialize sign bit index. */ + unsigned int s = 0; + /* Step 2: First 8 bytes are used for sign. */ + unsigned int k = DILITHIUM_SIGN_BYTES; if (ret == 0) { /* Set polynomial to all zeros. */ @@ -2828,10 +2848,6 @@ static int dilithium_sample_in_ball_ex(int level, wc_Shake* shake256, if (ret == 0) { /* Copy first 8 bytes of first hash block as random sign bits. */ XMEMCPY(signs, block, DILITHIUM_SIGN_BYTES); - /* Step 1: Initialize sign bit index. */ - s = 0; - /* Step 2: First 8 bytes are used for sign. */ - k = DILITHIUM_SIGN_BYTES; } /* Step 3: Put in TAU +/- 1s. */ @@ -3354,7 +3370,7 @@ static int dilithium_make_hint_32(const sword32* s, const sword32* w1, * return Falsam of -1 when too many hints. */ static int dilithium_make_hint(const sword32* s, const sword32* w1, byte k, - word32 gamma2, byte omega, byte* h) + sword32 gamma2, byte omega, byte* h) { unsigned int i; byte idx = 0; @@ -3509,12 +3525,12 @@ static void dilithium_use_hint_88(sword32* w1, const byte* h, unsigned int i, w1[j] = r1 + hint; /* Fix up w1 to not be 44 but 0. */ - w1[j] &= 0 - (((word32)(w1[j] - 44)) >> 31); + w1[j] &= (sword32)(0 - (((word32)(w1[j] - 44)) >> 31)); /* Hint may have reduced 0 to -1 which is actually 43. */ - w1[j] += (0 - (((word32)w1[j]) >> 31)) & 44; + w1[j] += (sword32)((0 - (((word32)w1[j]) >> 31)) & 44); #else /* Convert value to positive only range. */ - r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + r = w1[j] + (sword32)((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); /* Decompose value into low and high parts. */ dilithium_decompose_q88(r, &r0, &r1); /* Check for hint. */ @@ -3570,11 +3586,11 @@ static void dilithium_use_hint_32(sword32* w1, const byte* h, byte omega, /* Increment hint offset if this index has hint. */ o += hint; /* Convert value to positive only range. */ - r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + r = w1[j] + (sword32)((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); /* Decompose value into low and high parts. */ dilithium_decompose_q32(r, &r0, &r1); /* Make hint positive or negative based on sign of r0. */ - hint = (1 - (2 * (((word32)r0) >> 31))) & (0 - hint); + hint = (sword32)((1 - (2 * (((word32)r0) >> 31))) & (0 - hint)); /* Make w1 only the top part plus the hint. */ w1[j] = r1 + hint; @@ -3582,13 +3598,13 @@ static void dilithium_use_hint_32(sword32* w1, const byte* h, byte omega, w1[j] &= 0xf; #else /* Convert value to positive only range. */ - r = w1[j] + ((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); + r = w1[j] + (sword32)((0 - (((word32)w1[j]) >> 31)) & DILITHIUM_Q); /* Decompose value into low and high parts. */ dilithium_decompose_q32(r, &r0, &r1); /* Check for hint. */ if ((o < h[omega + i]) && (h[o] == (byte)j)) { /* Add or subtract hint based on sign of r0. */ - r1 += 1 - (2 * (((word32)r0) >> 31)); + r1 += (sword32)(1 - (2 * (((word32)r0) >> 31))); /* Go to next hint offset. */ o++; } @@ -3616,7 +3632,7 @@ static void dilithium_use_hint_32(sword32* w1, const byte* h, byte omega, * @param [in] omega Max number of hints. Hint counts after this index. * @param [in] h Hints to apply. In signature encoding. */ -static void dilithium_vec_use_hint(sword32* w1, byte k, word32 gamma2, +static void dilithium_vec_use_hint(sword32* w1, byte k, sword32 gamma2, byte omega, const byte* h) { unsigned int i; @@ -3883,7 +3899,7 @@ static void dilithium_ntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta32 = zetas[ 4 + j / 64 + 0]; sword32 zeta160 = zetas[ 8 + j / 32 + 0]; sword32 zeta161 = zetas[ 8 + j / 32 + 1]; @@ -3915,7 +3931,7 @@ static void dilithium_ntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 16) { - int i; + unsigned int i; sword32 zeta8 = zetas[16 + j / 16]; sword32 zeta40 = zetas[32 + j / 8 + 0]; sword32 zeta41 = zetas[32 + j / 8 + 1]; @@ -4031,7 +4047,7 @@ static void dilithium_ntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta32 = zetas[ 4 + j / 64 + 0]; sword32 zeta160 = zetas[ 8 + j / 32 + 0]; sword32 zeta161 = zetas[ 8 + j / 32 + 1]; @@ -4254,7 +4270,7 @@ static void dilithium_ntt_small(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta32 = zetas[ 4 + j / 64 + 0]; sword32 zeta160 = zetas[ 8 + j / 32 + 0]; sword32 zeta161 = zetas[ 8 + j / 32 + 1]; @@ -4286,7 +4302,7 @@ static void dilithium_ntt_small(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 16) { - int i; + unsigned int i; sword32 zeta8 = zetas[16 + j / 16]; sword32 zeta40 = zetas[32 + j / 8 + 0]; sword32 zeta41 = zetas[32 + j / 8 + 1]; @@ -4398,7 +4414,7 @@ static void dilithium_ntt_small(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta32 = zetas[ 4 + j / 64 + 0]; sword32 zeta160 = zetas[ 8 + j / 32 + 0]; sword32 zeta161 = zetas[ 8 + j / 32 + 1]; @@ -4686,7 +4702,7 @@ static void dilithium_invntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 16) { - int i; + unsigned int i; sword32 zeta40 = zetas_inv[192 + j / 8 + 0]; sword32 zeta41 = zetas_inv[192 + j / 8 + 1]; sword32 zeta8 = zetas_inv[224 + j / 16 + 0]; @@ -4718,7 +4734,7 @@ static void dilithium_invntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta160 = zetas_inv[240 + j / 32 + 0]; sword32 zeta161 = zetas_inv[240 + j / 32 + 1]; sword32 zeta32 = zetas_inv[248 + j / 64 + 0]; @@ -4858,7 +4874,7 @@ static void dilithium_invntt(sword32* r) } for (j = 0; j < DILITHIUM_N; j += 64) { - int i; + unsigned int i; sword32 zeta80 = zetas_inv[224 + j / 16 + 0]; sword32 zeta81 = zetas_inv[224 + j / 16 + 1]; sword32 zeta82 = zetas_inv[224 + j / 16 + 2]; @@ -6152,7 +6168,11 @@ static int dilithium_sign_with_seed_mu(dilithium_key* key, /* Step 11: Start rejection sampling loop */ do { +#ifdef WOLFSSL_SMALL_STACK + byte *w1e = NULL; +#else byte w1e[DILITHIUM_MAX_W1_ENC_SZ]; +#endif sword32* w = w1; sword32* y_ntt = z; sword32* cs2 = ct0; @@ -6182,11 +6202,20 @@ static int dilithium_sign_with_seed_mu(dilithium_key* key, if (valid) { #endif /* Step 15: Encode w1. */ - dilithium_vec_encode_w1(w1, params->k, params->gamma2, w1e); - /* Step 15: Hash mu and encoded w1. - * Step 32: Hash is stored in signature. */ - ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, - w1e, params->w1EncSz, commit, params->lambda / 4); +#ifdef WOLFSSL_SMALL_STACK + w1e = (byte *)XMALLOC(DILITHIUM_MAX_W1_ENC_SZ, key->heap, + DYNAMIC_TYPE_DILITHIUM); + if (w1e == NULL) + ret = MEMORY_E; + if (ret == 0) +#endif + { + dilithium_vec_encode_w1(w1, params->k, params->gamma2, w1e); + /* Step 15: Hash mu and encoded w1. + * Step 32: Hash is stored in signature. */ + ret = dilithium_hash256(&key->shake, mu, DILITHIUM_MU_SZ, + w1e, params->w1EncSz, commit, params->lambda / 4); + } if (ret == 0) { /* Step 17: Compute c from first 256 bits of commit. */ ret = dilithium_sample_in_ball(params->level, &key->shake, @@ -6237,6 +6266,10 @@ static int dilithium_sign_with_seed_mu(dilithium_key* key, params->gamma2, params->omega, h) >= 0); } } + +#ifdef WOLFSSL_SMALL_STACK + XFREE(w1e, key->heap, DYNAMIC_TYPE_DILITHIUM); +#endif } if (!valid) { @@ -6649,7 +6682,6 @@ static int dilithium_sign_with_seed_mu(dilithium_key* key, ze += DILITHIUM_GAMMA1_17_ENC_BITS / 2 * DILITHIUM_N / 4; } - else #endif #if !defined(WOLFSSL_NO_ML_DSA_65) || \ !defined(WOLFSSL_NO_ML_DSA_87) @@ -7049,7 +7081,7 @@ static int dilithium_sign_ctx_hash_with_seed(dilithium_key* key, byte seedMu[DILITHIUM_RND_SZ + DILITHIUM_MU_SZ]; byte* mu = seedMu + DILITHIUM_RND_SZ; byte oidMsgHash[DILITHIUM_HASH_OID_LEN + WC_MAX_DIGEST_SIZE]; - word32 oidMsgHashLen; + word32 oidMsgHashLen = 0; if ((ret == 0) && (hashLen > WC_MAX_DIGEST_SIZE)) { ret = BUFFER_E; @@ -7632,7 +7664,7 @@ static int dilithium_verify_ctx_msg(dilithium_key* key, const byte* ctx, if (ret == 0) { /* Step 6. Calculate mu. */ ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 0, - ctx, ctxLen, msg, msgLen, mu, DILITHIUM_MU_SZ); + ctx, (byte)ctxLen, msg, msgLen, mu, DILITHIUM_MU_SZ); } if (ret == 0) { ret = dilithium_verify_mu(key, mu, sig, sigLen, res); @@ -7710,7 +7742,7 @@ static int dilithium_verify_ctx_hash(dilithium_key* key, const byte* ctx, byte tr[DILITHIUM_TR_SZ]; byte* mu = tr; byte oidMsgHash[DILITHIUM_HASH_OID_LEN + WC_MAX_DIGEST_SIZE]; - word32 oidMsgHashLen; + word32 oidMsgHashLen = 0; if (key == NULL) { ret = BAD_FUNC_ARG; @@ -7730,7 +7762,7 @@ static int dilithium_verify_ctx_hash(dilithium_key* key, const byte* ctx, /* Step 6. Calculate mu. */ ret = dilithium_hash256_ctx_msg(&key->shake, tr, DILITHIUM_TR_SZ, 1, - ctx, ctxLen, oidMsgHash, oidMsgHashLen, mu, DILITHIUM_MU_SZ); + ctx, (byte)ctxLen, oidMsgHash, oidMsgHashLen, mu, DILITHIUM_MU_SZ); } if (ret == 0) { ret = dilithium_verify_mu(key, mu, sig, sigLen, res); @@ -8917,7 +8949,7 @@ int wc_dilithium_check_key(dilithium_key* key) { int ret = 0; #ifdef WOLFSSL_WC_DILITHIUM - const wc_dilithium_params* params; + const wc_dilithium_params* params = NULL; sword32* a = NULL; sword32* s1 = NULL; sword32* s2 = NULL; @@ -9474,7 +9506,7 @@ int wc_dilithium_export_private(dilithium_key* key, byte* out, word32* outLen) { int ret = 0; - word32 inLen; + word32 inLen = 0; /* Validate parameters. */ if ((key == NULL) || (out == NULL) || (outLen == NULL)) { @@ -9567,7 +9599,7 @@ int wc_dilithium_export_key(dilithium_key* key, byte* priv, word32 *privSz, #ifndef WOLFSSL_DILITHIUM_NO_ASN1 /* Maps ASN.1 OID to wolfCrypt security level macros */ -static int mapOidToSecLevel(word32 oid) +static int mapOidToSecLevel(int oid) { switch (oid) { case ML_DSA_LEVEL2k: @@ -9627,6 +9659,31 @@ int dilithium_get_oid_sum(dilithium_key* key, int* keyFormat) { #if defined(WOLFSSL_DILITHIUM_PRIVATE_KEY) +/* OCT OCT */ +#define ALT_PRIV_DER_PREFIX (2 + 32 + 4) +/* SEQ [ OCT OCT ] */ +#define ALT_PRIV_DER_PREFIX_SEQ (4 + 2 + 32 + 4) + +/* Get the private only key size for the ML-DSA level/parameter id. + * + * @param [in] level Level of the ML-DSA key. + * @return Private key only encoding size for key level on success. + * @return 0 on failure. + */ +static word32 dilithium_get_priv_size(int level) +{ + switch (level) { + case WC_ML_DSA_44: + return ML_DSA_LEVEL2_KEY_SIZE; + case WC_ML_DSA_65: + return ML_DSA_LEVEL3_KEY_SIZE; + case WC_ML_DSA_87: + return ML_DSA_LEVEL5_KEY_SIZE; + default: + return 0; + } +} + /* Decode the DER encoded Dilithium key. * * @param [in] input Array holding DER encoded data. @@ -9655,7 +9712,7 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, const byte* pubKey = NULL; word32 privKeyLen = 0; word32 pubKeyLen = 0; - int keytype = 0; + int keyType = 0; /* Validate parameters. */ if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) { @@ -9667,30 +9724,30 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, if (key->level == 0) { /* Check first, because key->params will be NULL * when key->level = 0 */ /* Level not set by caller, decode from DER */ - keytype = ANONk; + keyType = ANONk; } #if defined(WOLFSSL_DILITHIUM_FIPS204_DRAFT) else if (key->params == NULL) { ret = BAD_FUNC_ARG; } else if (key->params->level == WC_ML_DSA_44_DRAFT) { - keytype = DILITHIUM_LEVEL2k; + keyType = DILITHIUM_LEVEL2k; } else if (key->params->level == WC_ML_DSA_65_DRAFT) { - keytype = DILITHIUM_LEVEL3k; + keyType = DILITHIUM_LEVEL3k; } else if (key->params->level == WC_ML_DSA_87_DRAFT) { - keytype = DILITHIUM_LEVEL5k; + keyType = DILITHIUM_LEVEL5k; } #endif else if (key->level == WC_ML_DSA_44) { - keytype = ML_DSA_LEVEL2k; + keyType = ML_DSA_LEVEL2k; } else if (key->level == WC_ML_DSA_65) { - keytype = ML_DSA_LEVEL3k; + keyType = ML_DSA_LEVEL3k; } else if (key->level == WC_ML_DSA_87) { - keytype = ML_DSA_LEVEL5k; + keyType = ML_DSA_LEVEL5k; } else { ret = BAD_FUNC_ARG; @@ -9701,16 +9758,29 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, /* Decode the asymmetric key and get out private and public key data. */ ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &privKey, &privKeyLen, - &pubKey, &pubKeyLen, &keytype); + &pubKey, &pubKeyLen, &keyType); if (ret == 0 #ifdef WOLFSSL_WC_DILITHIUM && key->params == NULL #endif ) { /* Set the security level based on the decoded key. */ - ret = mapOidToSecLevel(keytype); + ret = mapOidToSecLevel(keyType); if (ret > 0) { - ret = wc_dilithium_set_level(key, ret); + ret = wc_dilithium_set_level(key, (byte)ret); + } + } + /* If it failed to decode try alternative DER encoding. */ + else if (ret != 0) { + word32 levelSize = dilithium_get_priv_size(key->level); + privKey = input + *inOutIdx; + privKeyLen = inSz - *inOutIdx; + + /* Check for an alternative DER encoding. */ + if (privKeyLen == ALT_PRIV_DER_PREFIX_SEQ + levelSize) { + privKey += ALT_PRIV_DER_PREFIX_SEQ; + privKeyLen -= ALT_PRIV_DER_PREFIX_SEQ; + ret = 0; } } } @@ -9758,6 +9828,14 @@ int wc_Dilithium_PrivateKeyDecode(const byte* input, word32* inOutIdx, pubKeyLen = ML_DSA_LEVEL5_PUB_KEY_SIZE; privKeyLen -= ML_DSA_LEVEL5_PUB_KEY_SIZE; } + else { + word32 levelSize = dilithium_get_priv_size(key->level); + + if (privKeyLen == ALT_PRIV_DER_PREFIX + levelSize) { + privKey += ALT_PRIV_DER_PREFIX; + privKeyLen -= ALT_PRIV_DER_PREFIX; + } + } } if (ret == 0) { @@ -9924,7 +10002,7 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, dilithium_key* key, word32 inSz) { int ret = 0; - const byte* pubKey; + const byte* pubKey = NULL; word32 pubKeyLen = 0; /* Validate parameters. */ @@ -9937,7 +10015,7 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, ret = wc_dilithium_import_public(input, inSz, key); if (ret != 0) { #if !defined(WOLFSSL_DILITHIUM_NO_ASN1) - int keytype = 0; + int keyType = 0; #else int length; unsigned char* oid; @@ -9955,43 +10033,43 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, ret = BAD_FUNC_ARG; } else if (key->params->level == WC_ML_DSA_44_DRAFT) { - keytype = DILITHIUM_LEVEL2k; + keyType = DILITHIUM_LEVEL2k; } else if (key->params->level == WC_ML_DSA_65_DRAFT) { - keytype = DILITHIUM_LEVEL3k; + keyType = DILITHIUM_LEVEL3k; } else if (key->params->level == WC_ML_DSA_87_DRAFT) { - keytype = DILITHIUM_LEVEL5k; + keyType = DILITHIUM_LEVEL5k; } else #endif if (key->level == WC_ML_DSA_44) { - keytype = ML_DSA_LEVEL2k; + keyType = ML_DSA_LEVEL2k; } else if (key->level == WC_ML_DSA_65) { - keytype = ML_DSA_LEVEL3k; + keyType = ML_DSA_LEVEL3k; } else if (key->level == WC_ML_DSA_87) { - keytype = ML_DSA_LEVEL5k; + keyType = ML_DSA_LEVEL5k; } else { /* Level not set by caller, decode from DER */ - keytype = ANONk; /* 0, not a valid key type in this situation*/ + keyType = ANONk; /* 0, not a valid key type in this situation*/ } if (ret == 0) { /* Decode the asymmetric key and get out public key data. */ ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKey, &pubKeyLen, - &keytype); + &keyType); if (ret == 0 #ifdef WOLFSSL_WC_DILITHIUM && key->params == NULL #endif ) { /* Set the security level based on the decoded key. */ - ret = mapOidToSecLevel(keytype); + ret = mapOidToSecLevel(keyType); if (ret > 0) { - ret = wc_dilithium_set_level(key, ret); + ret = wc_dilithium_set_level(key, (byte)ret); } } } @@ -10091,6 +10169,8 @@ int wc_Dilithium_PublicKeyDecode(const byte* input, word32* inOutIdx, /* This is the raw point data compressed or uncompressed. */ pubKeyLen = (word32)length; pubKey = input + idx; + + *inOutIdx += idx; } #endif if (ret == 0) { @@ -10121,8 +10201,8 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, int withAlg) { int ret = 0; - int keytype = 0; - int pubKeyLen = 0; + int keyType = 0; + word32 pubKeyLen = 0; /* Validate parameters. */ if (key == NULL) { @@ -10140,29 +10220,29 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, ret = BAD_FUNC_ARG; } else if (key->params->level == WC_ML_DSA_44_DRAFT) { - keytype = DILITHIUM_LEVEL2k; + keyType = DILITHIUM_LEVEL2k; pubKeyLen = DILITHIUM_LEVEL2_PUB_KEY_SIZE; } else if (key->params->level == WC_ML_DSA_65_DRAFT) { - keytype = DILITHIUM_LEVEL3k; + keyType = DILITHIUM_LEVEL3k; pubKeyLen = DILITHIUM_LEVEL3_PUB_KEY_SIZE; } else if (key->params->level == WC_ML_DSA_87_DRAFT) { - keytype = DILITHIUM_LEVEL5k; + keyType = DILITHIUM_LEVEL5k; pubKeyLen = DILITHIUM_LEVEL5_PUB_KEY_SIZE; } else #endif if (key->level == WC_ML_DSA_44) { - keytype = ML_DSA_LEVEL2k; + keyType = ML_DSA_LEVEL2k; pubKeyLen = ML_DSA_LEVEL2_PUB_KEY_SIZE; } else if (key->level == WC_ML_DSA_65) { - keytype = ML_DSA_LEVEL3k; + keyType = ML_DSA_LEVEL3k; pubKeyLen = ML_DSA_LEVEL3_PUB_KEY_SIZE; } else if (key->level == WC_ML_DSA_87) { - keytype = ML_DSA_LEVEL5k; + keyType = ML_DSA_LEVEL5k; pubKeyLen = ML_DSA_LEVEL5_PUB_KEY_SIZE; } else { @@ -10172,7 +10252,7 @@ int wc_Dilithium_PublicKeyToDer(dilithium_key* key, byte* output, word32 len, } if (ret == 0) { - ret = SetAsymKeyDerPublic(key->p, pubKeyLen, output, len, keytype, + ret = SetAsymKeyDerPublic(key->p, pubKeyLen, output, len, keyType, withAlg); } diff --git a/src/wolfcrypt/src/dsa.c b/src/wolfcrypt/src/dsa.c index 5be431a..cc45548 100644 --- a/src/wolfcrypt/src/dsa.c +++ b/src/wolfcrypt/src/dsa.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -141,12 +141,13 @@ static int CheckDsaLN(int modLen, int divLen) * return 0 on success, negative on error */ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) { - byte* cBuf; int qSz, pSz, cSz, err; -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) mp_int *tmpQ = NULL; + byte* cBuf = NULL; #else mp_int tmpQ[1]; + byte cBuf[(3072+64)/WOLFSSL_BIT_SIZE ]; #endif if (rng == NULL || dsa == NULL) @@ -161,15 +162,22 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) /* generate extra 64 bits so that bias from mod function is negligible */ cSz = qSz + (64 / WOLFSSL_BIT_SIZE); +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) cBuf = (byte*)XMALLOC((size_t)cSz, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); if (cBuf == NULL) { return MEMORY_E; } +#else + if (sizeof(cBuf) < (size_t)cSz) { + return BUFFER_E; + } +#endif SAVE_VECTOR_REGISTERS(;); -#ifdef WOLFSSL_SMALL_STACK - if ((tmpQ = (mp_int *)XMALLOC(sizeof(*tmpQ), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) + if ((tmpQ = (mp_int *)XMALLOC(sizeof(*tmpQ), NULL, + DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) err = MEMORY_E; else err = MP_OKAY; @@ -223,9 +231,8 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) mp_clear(&dsa->y); } +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(cBuf, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); - -#ifdef WOLFSSL_SMALL_STACK if (tmpQ != NULL) { mp_clear(tmpQ); XFREE(tmpQ, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -239,19 +246,20 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa) return err; } - /* modulus_size in bits */ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) { -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) mp_int *tmp = NULL, *tmp2 = NULL; + unsigned char *buf = NULL; #else mp_int tmp[1], tmp2[1]; + unsigned char buf[(3072/WOLFSSL_BIT_SIZE)-32]; #endif int err, msize, qsize, loop_check_prime = 0, check_prime = MP_NO; - unsigned char *buf; + if (rng == NULL || dsa == NULL) return BAD_FUNC_ARG; @@ -278,17 +286,25 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) /* modulus size in bytes */ msize = modulus_size / WOLFSSL_BIT_SIZE; +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) /* allocate ram */ buf = (unsigned char *)XMALLOC((size_t)(msize - qsize), dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { return MEMORY_E; } +#else + if (sizeof(buf) < (size_t)(msize - qsize)) { + return BUFFER_E; + } +#endif /* make a random string that will be multiplied against q */ err = wc_RNG_GenerateBlock(rng, buf, (word32)(msize - qsize)); if (err != MP_OKAY) { + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(buf, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); + #endif return err; } @@ -298,7 +314,7 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) /* force even */ buf[msize - qsize - 1] &= (unsigned char)~1; -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) if (((tmp = (mp_int *)XMALLOC(sizeof(*tmp), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) || ((tmp2 = (mp_int *)XMALLOC(sizeof(*tmp2), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL)) err = MEMORY_E; @@ -380,9 +396,8 @@ int wc_MakeDsaParameters(WC_RNG *rng, int modulus_size, DsaKey *dsa) #endif } +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(buf, dsa->heap, DYNAMIC_TYPE_TMP_BUFFER); - -#ifdef WOLFSSL_SMALL_STACK if (tmp != NULL) { mp_clear(tmp); XFREE(tmp, NULL, DYNAMIC_TYPE_WOLF_BIGINT); diff --git a/src/wolfcrypt/src/ecc.c b/src/wolfcrypt/src/ecc.c index 6d4cd4d..03eaf13 100644 --- a/src/wolfcrypt/src/ecc.c +++ b/src/wolfcrypt/src/ecc.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2054,7 +2054,7 @@ static int _ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, } if (err == MP_OKAY) { if ( (mp_cmp(P->x, Q->x) == MP_EQ) && - (get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && + (mp_get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && (mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, t1) == MP_EQ)) { mp_clear(t1); mp_clear(t2); @@ -2990,7 +2990,7 @@ static int ecc_mulmod(const mp_int* k, ecc_point* tG, ecc_point* R, mode = 0; bitcnt = 1; buf = 0; - digidx = get_digit_count(k) - 1; + digidx = mp_get_digit_count(k) - 1; bitcpy = bitbuf = 0; first = 1; @@ -3001,7 +3001,7 @@ static int ecc_mulmod(const mp_int* k, ecc_point* tG, ecc_point* R, if (digidx == -1) { break; } - buf = get_digit(k, digidx); + buf = mp_get_digit(k, digidx); bitcnt = (int) DIGIT_BIT; --digidx; } @@ -3250,10 +3250,8 @@ static int ecc_mulmod(const mp_int* k, ecc_point* P, ecc_point* Q, #else /* Swap R[0] and R[1] if other index is needed. */ swap ^= (int)b; - if (err == MP_OKAY) { - err = mp_cond_swap_ct_ex(R[0]->x, R[1]->x, (int)modulus->used, swap, - tmp); - } + err = mp_cond_swap_ct_ex(R[0]->x, R[1]->x, (int)modulus->used, swap, + tmp); if (err == MP_OKAY) { err = mp_cond_swap_ct_ex(R[0]->y, R[1]->y, (int)modulus->used, swap, tmp); @@ -3917,7 +3915,7 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, #endif int i, err; #ifdef WOLFSSL_SMALL_STACK_CACHE - ecc_key key; + ecc_key *key = NULL; #endif mp_digit mp; @@ -3944,10 +3942,13 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, XMEMSET(M, 0, sizeof(M)); #ifdef WOLFSSL_SMALL_STACK_CACHE - err = ecc_key_tmp_init(&key, heap); + key = (ecc_key *)XMALLOC(sizeof(*key), heap, DYNAMIC_TYPE_ECC); + if (key == NULL) + return MEMORY_E; + err = ecc_key_tmp_init(key, heap); if (err != MP_OKAY) goto exit; - R->key = &key; + R->key = key; #endif /* WOLFSSL_SMALL_STACK_CACHE */ /* alloc ram for window temps */ @@ -3960,7 +3961,7 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, goto exit; } #ifdef WOLFSSL_SMALL_STACK_CACHE - M[i]->key = &key; + M[i]->key = key; #endif } @@ -4002,7 +4003,8 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point* G, ecc_point* R, mp_int* a, } #ifdef WOLFSSL_SMALL_STACK_CACHE R->key = NULL; - ecc_key_tmp_final(&key, heap); + ecc_key_tmp_final(key, heap); + XFREE(key, heap, DYNAMIC_TYPE_ECC); #endif /* WOLFSSL_SMALL_STACK_CACHE */ return err; @@ -5393,6 +5395,7 @@ static WC_INLINE void wc_ecc_reset(ecc_key* key) key->state = ECC_STATE_NONE; } + /* create the public ECC key from a private key * * key an initialized private key to generate public part from @@ -5678,7 +5681,7 @@ static int _ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, #endif key->flags = (byte)flags; -#ifdef WOLF_CRYPTO_CB +#if defined(WOLF_CRYPTO_CB) && defined(HAVE_ECC_DHE) #ifndef WOLF_CRYPTO_CB_FIND if (key->devId != INVALID_DEVID) #endif @@ -7645,8 +7648,12 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, /* 3.2 c. Set K = 0x00 0x00 ... */ XMEMSET(K, 0x00, KSz); - mp_init(z1); /* always init z1 and free z1 */ - ret = mp_to_unsigned_bin_len(priv, x, (int)qLen); + if (ret == 0) { + ret = mp_init(z1); /* always init z1 and free z1 */ + } + if (ret == 0) { + ret = mp_to_unsigned_bin_len(priv, x, (int)qLen); + } if (ret == 0) { #ifdef WOLFSSL_CHECK_MEM_ZERO wc_MemZero_Add("wc_ecc_gen_deterministic_k x", x, qLen); @@ -7690,7 +7697,7 @@ int wc_ecc_gen_deterministic_k(const byte* hash, word32 hashSz, #endif { /* use original hash and keep leading 0's */ - mp_to_unsigned_bin_len(z1, h1, (int)h1len); + ret = mp_to_unsigned_bin_len(z1, h1, (int)h1len); } } mp_free(z1); @@ -10257,7 +10264,7 @@ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) * (!WOLFSSL_SP_MATH && WOLFSSL_VALIDATE_ECC_IMPORT) */ #if (FIPS_VERSION_GE(5,0) || defined(WOLFSSL_VALIDATE_ECC_KEYGEN)) && \ - !defined(WOLFSSL_KCAPI_ECC) + !defined(WOLFSSL_KCAPI_ECC) && defined(HAVE_ECC_DHE) /* check privkey generator helper, creates prime needed */ static int ecc_check_privkey_gen_helper(ecc_key* key) @@ -10372,7 +10379,7 @@ static int _ecc_pairwise_consistency_test(ecc_key* key, WC_RNG* rng) return err; } #endif /* (FIPS v5 or later || WOLFSSL_VALIDATE_ECC_KEYGEN) && \ - !WOLFSSL_KCAPI_ECC */ + !WOLFSSL_KCAPI_ECC && HAVE_ECC_DHE */ #ifndef WOLFSSL_SP_MATH /* validate order * pubkey = point at infinity, 0 on success */ diff --git a/src/wolfcrypt/src/eccsi.c b/src/wolfcrypt/src/eccsi.c index 537e64c..2717607 100644 --- a/src/wolfcrypt/src/eccsi.c +++ b/src/wolfcrypt/src/eccsi.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ed25519.c b/src/wolfcrypt/src/ed25519.c index 85f7f8a..7cc029b 100644 --- a/src/wolfcrypt/src/ed25519.c +++ b/src/wolfcrypt/src/ed25519.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ed448.c b/src/wolfcrypt/src/ed448.c index a5e63a1..be8582f 100644 --- a/src/wolfcrypt/src/ed448.c +++ b/src/wolfcrypt/src/ed448.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/error.c b/src/wolfcrypt/src/error.c index af5ba36..014345a 100644 --- a/src/wolfcrypt/src/error.c +++ b/src/wolfcrypt/src/error.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -182,10 +182,10 @@ const char* wc_GetErrorString(int error) return "ASN date error, bad size"; case ASN_BEFORE_DATE_E : - return "ASN date error, current date before"; + return "ASN date error, current date is before start of validity"; case ASN_AFTER_DATE_E : - return "ASN date error, current date after"; + return "ASN date error, current date is after expiration"; case ASN_SIG_OID_E : return "ASN signature error, mismatched oid"; @@ -647,6 +647,9 @@ const char* wc_GetErrorString(int error) case ASCON_AUTH_E: return "ASCON Authentication check fail"; + case WC_ACCEL_INHIBIT_E: + return "Crypto acceleration is currently inhibited"; + case MAX_CODE_E: case WC_SPAN1_MIN_CODE_E: case MIN_CODE_E: diff --git a/src/wolfcrypt/src/evp.c b/src/wolfcrypt/src/evp.c index 7054f80..5c9ac3e 100644 --- a/src/wolfcrypt/src/evp.c +++ b/src/wolfcrypt/src/evp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2538,9 +2538,11 @@ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_E if (ctx == NULL) return NULL; XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_PKEY_CTX)); ctx->pkey = pkey; -#if !defined(NO_RSA) +#ifndef NO_RSA ctx->padding = WC_RSA_PKCS1_PADDING; ctx->md = NULL; + ctx->mgf1_md = NULL; + ctx->saltlen = 0; #endif #ifdef HAVE_ECC if (pkey->ecc && pkey->ecc->group) { @@ -2593,6 +2595,42 @@ int wolfSSL_EVP_PKEY_CTX_set_signature_md(WOLFSSL_EVP_PKEY_CTX *ctx, return WOLFSSL_SUCCESS; } +int wolfSSL_EVP_PKEY_CTX_set_rsa_oaep_md(WOLFSSL_EVP_PKEY_CTX *ctx, + const WOLFSSL_EVP_MD *md) +{ + wolfSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, WC_RSA_PKCS1_OAEP_PADDING); + return wolfSSL_EVP_PKEY_CTX_set_signature_md(ctx, md); +} + +int wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen(WOLFSSL_EVP_PKEY_CTX *ctx, + int saltlen) +{ + if (ctx == NULL) return 0; + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen"); + wolfSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, WC_RSA_PKCS1_PSS_PADDING); +#ifndef NO_RSA + ctx->saltlen = saltlen; +#else + (void)saltlen; +#endif + return WOLFSSL_SUCCESS; +} + +int wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md(WOLFSSL_EVP_PKEY_CTX *ctx, + const WOLFSSL_EVP_MD *md) +{ + if (ctx == NULL) return 0; + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md"); +#ifndef NO_RSA + /* Hash digest algorithm used with Mask Generation Function 1 (MGF1) for + * RSA-PSS and RSA-OAEP. */ + ctx->mgf1_md = md; +#else + (void)md; +#endif + return WOLFSSL_SUCCESS; +} + /* create a PKEY context and return it */ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new_id(int id, WOLFSSL_ENGINE *e) { @@ -3278,7 +3316,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, (void)tbslen; switch (ctx->pkey->type) { -#if !defined(NO_RSA) +#ifndef NO_RSA case WC_EVP_PKEY_RSA: { unsigned int usiglen = (unsigned int)*siglen; if (!sig) { @@ -3291,17 +3329,17 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, *siglen = (size_t)len; return WOLFSSL_SUCCESS; } - /* wolfSSL_RSA_sign_generic_padding performs a check that the output - * sig buffer is large enough */ - if (wolfSSL_RSA_sign_generic_padding(wolfSSL_EVP_MD_type(ctx->md), tbs, - (unsigned int)tbslen, sig, &usiglen, ctx->pkey->rsa, 1, - ctx->padding) != WOLFSSL_SUCCESS) { + + if (wolfSSL_RSA_sign_mgf(wolfSSL_EVP_MD_type(ctx->md), tbs, + (unsigned int)tbslen, sig, &usiglen, ctx->pkey->rsa, 1, + ctx->padding, wolfSSL_EVP_MD_type(ctx->mgf1_md), ctx->saltlen + ) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } *siglen = (size_t)usiglen; return WOLFSSL_SUCCESS; } -#endif /* NO_RSA */ +#endif /* !NO_RSA */ #ifndef NO_DSA case WC_EVP_PKEY_DSA: { @@ -3434,12 +3472,12 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, return WOLFSSL_FAILURE; switch (ctx->pkey->type) { -#if !defined(NO_RSA) +#ifndef NO_RSA case WC_EVP_PKEY_RSA: - return wolfSSL_RSA_verify_ex(WC_HASH_TYPE_NONE, tbs, + return wolfSSL_RSA_verify_mgf(wolfSSL_EVP_MD_type(ctx->md), tbs, (unsigned int)tbslen, sig, (unsigned int)siglen, ctx->pkey->rsa, - ctx->padding); -#endif /* NO_RSA */ + ctx->padding, wolfSSL_EVP_MD_type(ctx->mgf1_md), ctx->saltlen); +#endif /* !NO_RSA */ #ifndef NO_DSA case WC_EVP_PKEY_DSA: { @@ -10193,8 +10231,8 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return WC_NID_undef; } - for( ent = md_tbl; ent->name != NULL; ent++){ - if(XSTRCMP((const char *)type, ent->name) == 0) { + for (ent = md_tbl; ent->name != NULL; ent++) { + if (XSTRCMP((const char *)type, ent->name) == 0) { return ent->nid; } } diff --git a/src/wolfcrypt/src/ext_lms.c b/src/wolfcrypt/src/ext_lms.c index 00a3e55..2486a42 100644 --- a/src/wolfcrypt/src/ext_lms.c +++ b/src/wolfcrypt/src/ext_lms.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1043,6 +1043,15 @@ int wc_LmsKey_Verify(LmsKey * key, const byte * sig, word32 sigSz, return 0; } +int wc_LmsKey_GetKid(LmsKey * key, const byte ** kid, word32* kidSz) +{ + if ((key == NULL) || (kid == NULL) || (kidSz == NULL)) { + return BAD_FUNC_ARG; + } + + return NOT_COMPILED_IN; +} + const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz) { if ((priv == NULL) || (privSz < 16)) { diff --git a/src/wolfcrypt/src/ext_mlkem.c b/src/wolfcrypt/src/ext_mlkem.c index 3a9ccee..0a9bd9b 100644 --- a/src/wolfcrypt/src/ext_mlkem.c +++ b/src/wolfcrypt/src/ext_mlkem.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ext_xmss.c b/src/wolfcrypt/src/ext_xmss.c index 48912a3..f1bc422 100644 --- a/src/wolfcrypt/src/ext_xmss.c +++ b/src/wolfcrypt/src/ext_xmss.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/falcon.c b/src/wolfcrypt/src/falcon.c index 6562a80..7200018 100644 --- a/src/wolfcrypt/src/falcon.c +++ b/src/wolfcrypt/src/falcon.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/fe_448.c b/src/wolfcrypt/src/fe_448.c index 8cf0245..9d8308d 100644 --- a/src/wolfcrypt/src/fe_448.c +++ b/src/wolfcrypt/src/fe_448.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/fe_low_mem.c b/src/wolfcrypt/src/fe_low_mem.c index febc123..d2b2d8a 100644 --- a/src/wolfcrypt/src/fe_low_mem.c +++ b/src/wolfcrypt/src/fe_low_mem.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/fe_operations.c b/src/wolfcrypt/src/fe_operations.c index 135d703..6ae70e7 100644 --- a/src/wolfcrypt/src/fe_operations.c +++ b/src/wolfcrypt/src/fe_operations.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -192,7 +192,7 @@ int curve25519_blind(byte* q, const byte* n, const byte* mask, const byte* p, fe z3 = {0}; fe tmp0 = {0}; fe tmp1 = {0}; - int pos = 0; + unsigned int pos; unsigned int b; fe_frombytes(x1,p); @@ -208,7 +208,7 @@ int curve25519_blind(byte* q, const byte* n, const byte* mask, const byte* p, fe_cswap(x2,x3,(int)b); fe_cswap(z2,z3,(int)b); for (pos = 255;pos >= 1;--pos) { - b = n[pos / 8] >> (pos & 7); + b = (unsigned int)n[pos / 8] >> (pos & 7); b &= 1; fe_cswap(x2,x3,(int)b); fe_cswap(z2,z3,(int)b); @@ -233,7 +233,7 @@ int curve25519_blind(byte* q, const byte* n, const byte* mask, const byte* p, fe_mul(z3,x1,z2); fe_mul(z2,tmp1,tmp0); - b = mask[(pos-1) / 8] >> ((pos-1) & 7); + b = (unsigned int)mask[(pos-1) / 8] >> ((pos-1) & 7); b &= 1; fe_cswap(x2,x3,(int)b); fe_cswap(z2,z3,(int)b); diff --git a/src/wolfcrypt/src/ge_448.c b/src/wolfcrypt/src/ge_448.c index a09a92d..3e3ba9d 100644 --- a/src/wolfcrypt/src/ge_448.c +++ b/src/wolfcrypt/src/ge_448.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ge_low_mem.c b/src/wolfcrypt/src/ge_low_mem.c index c0a952b..308e73a 100644 --- a/src/wolfcrypt/src/ge_low_mem.c +++ b/src/wolfcrypt/src/ge_low_mem.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ge_operations.c b/src/wolfcrypt/src/ge_operations.c index bde5a06..184c54e 100644 --- a/src/wolfcrypt/src/ge_operations.c +++ b/src/wolfcrypt/src/ge_operations.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/hash.c b/src/wolfcrypt/src/hash.c index c709fa3..c3bae41 100644 --- a/src/wolfcrypt/src/hash.c +++ b/src/wolfcrypt/src/hash.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -37,27 +37,6 @@ #endif -#ifdef NO_ASN -enum Hash_Sum { - MD2h = 646, - MD5h = 649, - SHAh = 88, - SHA224h = 417, - SHA256h = 414, - SHA384h = 415, - SHA512h = 416, - SHA512_224h = 418, - SHA512_256h = 419, - SHA3_224h = 420, - SHA3_256h = 421, - SHA3_384h = 422, - SHA3_512h = 423, - SHAKE128h = 424, - SHAKE256h = 425, - SM3h = 640 /* 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x83,0x11 */ -}; -#endif /* !NO_ASN */ - #if !defined(NO_PWDBASED) || !defined(NO_ASN) /* function converts int hash type to enum */ enum wc_HashType wc_HashTypeConvert(int hashType) @@ -1498,13 +1477,13 @@ int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) void* heap, int devId) { int ret = 0; - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) wc_Sha256* sha256; #else wc_Sha256 sha256[1]; #endif - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) sha256 = (wc_Sha256*)XMALLOC(sizeof(wc_Sha256), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (sha256 == NULL) @@ -1525,7 +1504,7 @@ int wc_HashGetFlags(wc_HashAlg* hash, enum wc_HashType type, word32* flags) } - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) XFREE(sha256, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif diff --git a/src/wolfcrypt/src/hmac.c b/src/wolfcrypt/src/hmac.c index 912b26d..fdbe30f 100644 --- a/src/wolfcrypt/src/hmac.c +++ b/src/wolfcrypt/src/hmac.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -400,6 +400,32 @@ static int HmacKeyHashUpdate(byte macType, wc_HmacHash* hash, byte* pad) return ret; } +#ifdef WOLFSSL_HMAC_COPY_HASH +int _HmacInitIOHashes(Hmac* hmac) +{ + int ret; +#ifdef WOLF_CRYPTO_CB + int devId = hmac->devId; +#else + int devId = INVALID_DEVID; +#endif + + ret = HmacKeyInitHash(&hmac->i_hash, hmac->macType, hmac->heap, devId); + if (ret == 0) { + ret = HmacKeyInitHash(&hmac->o_hash, hmac->macType, hmac->heap, devId); + } + if (ret == 0) { + ret = HmacKeyHashUpdate(hmac->macType, &hmac->i_hash, + (byte*)hmac->ipad); + } + if (ret == 0) { + ret = HmacKeyHashUpdate(hmac->macType, &hmac->o_hash, + (byte*)hmac->opad); + } + + return ret; +} +#endif int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, int allowFlag) @@ -761,25 +787,8 @@ int wc_HmacSetKey_ex(Hmac* hmac, int type, const byte* key, word32 length, } #ifdef WOLFSSL_HMAC_COPY_HASH - if ( ret == 0) { - #ifdef WOLF_CRYPTO_CB - int devId = hmac->devId; - #else - int devId = INVALID_DEVID; - #endif - - ret = HmacKeyInitHash(&hmac->i_hash, hmac->macType, heap, devId); - if (ret != 0) - return ret; - ret = HmacKeyInitHash(&hmac->o_hash, hmac->macType, heap, devId); - if (ret != 0) - return ret; - ret = HmacKeyHashUpdate(hmac->macType, &hmac->i_hash, ip); - if (ret != 0) - return ret; - ret = HmacKeyHashUpdate(hmac->macType, &hmac->o_hash, op); - if (ret != 0) - return ret; + if (ret == 0) { + ret = _HmacInitIOHashes(hmac); } #endif @@ -1581,7 +1590,7 @@ int wolfSSL_GetHmacMaxSize(void) left = min(left, hashSz); XMEMCPY(out+outIdx, tmp, left); - outIdx += hashSz; + outIdx += left; n++; } diff --git a/src/wolfcrypt/src/hpke.c b/src/wolfcrypt/src/hpke.c index 8ce209f..848b53a 100644 --- a/src/wolfcrypt/src/hpke.c +++ b/src/wolfcrypt/src/hpke.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -987,7 +987,7 @@ static int wc_HpkeDecap(Hpke* hpke, void* receiverKey, const byte* pubKey, word16 pubKeySz, byte* sharedSecret) { int ret; -#ifdef ECC_TIMING_RESISTANT +#if defined(ECC_TIMING_RESISTANT) || defined(WOLFSSL_CURVE25519_BLINDING) WC_RNG* rng; #endif word32 dh_len; @@ -1052,9 +1052,22 @@ static int wc_HpkeDecap(Hpke* hpke, void* receiverKey, const byte* pubKey, #endif #if defined(HAVE_CURVE25519) case DHKEM_X25519_HKDF_SHA256: + #ifdef WOLFSSL_CURVE25519_BLINDING + rng = wc_rng_new(NULL, 0, hpke->heap); + + if (rng == NULL) { + ret = RNG_FAILURE_E; + break; + } + + wc_curve25519_set_rng((curve25519_key*)receiverKey, rng); + #endif ret = wc_curve25519_shared_secret_ex( (curve25519_key*)receiverKey, (curve25519_key*)ephemeralKey, dh, &dh_len, EC25519_LITTLE_ENDIAN); + #ifdef WOLFSSL_CURVE25519_BLINDING + wc_rng_free(rng); + #endif break; #endif case DHKEM_X448_HKDF_SHA512: diff --git a/src/wolfcrypt/src/integer.c b/src/wolfcrypt/src/integer.c index 341d99d..418df6d 100644 --- a/src/wolfcrypt/src/integer.c +++ b/src/wolfcrypt/src/integer.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/kdf.c b/src/wolfcrypt/src/kdf.c index 0e092dd..ce278d0 100644 --- a/src/wolfcrypt/src/kdf.c +++ b/src/wolfcrypt/src/kdf.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -902,12 +902,12 @@ int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz, * @param [in] saltSz Size of random value in bytes. * @param [in] kdrIdx Key derivation rate. kdr = 0 when -1, otherwise * kdr = 2^kdrIdx. - * @param [in] index Index value to XOR in. - * @param [in] indexSz Size of index value in bytes. + * @param [in] idx Index value to XOR in. + * @param [in] idxSz Size of index value in bytes. * @param [out] block First block to encrypt. */ static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx, - const byte* index, int indexSz, unsigned char* block) + const byte* idx, int idxSz, unsigned char* block) { int i; @@ -924,21 +924,21 @@ static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx, /* Get the number of bits to shift index by. */ word32 bits = kdrIdx & 0x7; /* Reduce index size by number of bytes to remove. */ - indexSz -= kdrIdx >> 3; + idxSz -= kdrIdx >> 3; if ((kdrIdx & 0x7) == 0) { /* Just XOR in as no bit shifting. */ - for (i = 0; i < indexSz; i++) { - block[i + WC_SRTP_MAX_SALT - indexSz] ^= index[i]; + for (i = 0; i < idxSz; i++) { + block[i + WC_SRTP_MAX_SALT - idxSz] ^= idx[i]; } } else { /* XOR in as bit shifted index. */ - block[WC_SRTP_MAX_SALT - indexSz] ^= (byte)(index[0] >> bits); - for (i = 1; i < indexSz; i++) { - block[i + WC_SRTP_MAX_SALT - indexSz] ^= - (byte)((index[i-1] << (8 - bits)) | - (index[i+0] >> bits )); + block[WC_SRTP_MAX_SALT - idxSz] ^= (byte)(idx[0] >> bits); + for (i = 1; i < idxSz; i++) { + block[i + WC_SRTP_MAX_SALT - idxSz] ^= + (byte)((idx[i-1] << (8 - bits)) | + (idx[i+0] >> bits )); } } } @@ -955,7 +955,7 @@ static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx, * @param [in] aes AES object to encrypt with. * @return 0 on success. */ -static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, +static int wc_srtp_kdf_derive_key(byte* block, int idxSz, byte label, byte* key, word32 keySz, Aes* aes) { int i; @@ -964,7 +964,7 @@ static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, int blocks = (int)(keySz / WC_AES_BLOCK_SIZE); /* XOR in label. */ - block[WC_SRTP_MAX_SALT - indexSz - 1] ^= label; + block[WC_SRTP_MAX_SALT - idxSz - 1] ^= label; for (i = 0; (ret == 0) && (i < blocks); i++) { /* Set counter. */ block[15] = (byte)i; @@ -988,7 +988,7 @@ static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, } } /* XOR out label. */ - block[WC_SRTP_MAX_SALT - indexSz - 1] ^= label; + block[WC_SRTP_MAX_SALT - idxSz - 1] ^= label; return ret; } @@ -1018,7 +1018,7 @@ static int wc_srtp_kdf_derive_key(byte* block, int indexSz, byte label, * @return 0 on success. */ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, - int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, + int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz) { int ret = 0; @@ -1056,7 +1056,7 @@ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, /* Calculate first block that can be used in each derivation. */ if (ret == 0) { - wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, WC_SRTP_INDEX_LEN, + wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTP_INDEX_LEN, block); } @@ -1109,7 +1109,7 @@ int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, * @return 0 on success. */ int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 saltSz, - int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, + int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator) { int ret = 0; @@ -1156,7 +1156,7 @@ int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 salt /* Calculate first block that can be used in each derivation. */ if (ret == 0) { - wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, idxLen, block); + wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, idxLen, block); } /* Calculate first key if required. */ @@ -1184,11 +1184,11 @@ int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 salt } int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, - int kdrIdx, const byte* index, byte* key1, word32 key1Sz, byte* key2, + int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz) { /* The default 32-bit IDX expected by many implementations */ - return wc_SRTCP_KDF_ex(key, keySz, salt, saltSz, kdrIdx, index, + return wc_SRTCP_KDF_ex(key, keySz, salt, saltSz, kdrIdx, idx, key1, key1Sz, key2, key2Sz, key3, key3Sz, WC_SRTCP_32BIT_IDX); } @@ -1214,7 +1214,7 @@ int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz, * @return 0 on success. */ int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, - word32 saltSz, int kdrIdx, const byte* index, byte label, byte* outKey, + word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey, word32 outKeySz) { int ret = 0; @@ -1253,7 +1253,7 @@ int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, /* Calculate first block that can be used in each derivation. */ if (ret == 0) { - wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, WC_SRTP_INDEX_LEN, + wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTP_INDEX_LEN, block); } if (ret == 0) { @@ -1293,7 +1293,7 @@ int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt, * @return 0 on success. */ int wc_SRTCP_KDF_label(const byte* key, word32 keySz, const byte* salt, - word32 saltSz, int kdrIdx, const byte* index, byte label, byte* outKey, + word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey, word32 outKeySz) { int ret = 0; @@ -1332,7 +1332,7 @@ int wc_SRTCP_KDF_label(const byte* key, word32 keySz, const byte* salt, /* Calculate first block that can be used in each derivation. */ if (ret == 0) { - wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, index, WC_SRTCP_INDEX_LEN, + wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTCP_INDEX_LEN, block); } if (ret == 0) { diff --git a/src/wolfcrypt/src/logging.c b/src/wolfcrypt/src/logging.c index 29b9221..98fcb35 100644 --- a/src/wolfcrypt/src/logging.c +++ b/src/wolfcrypt/src/logging.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -230,42 +230,6 @@ void WOLFSSL_TIME(int count) #ifdef DEBUG_WOLFSSL -#if defined(ARDUINO) - /* see Arduino wolfssl.h for wolfSSL_Arduino_Serial_Print */ -#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) - /* see wc_port.h for fio.h and nio.h includes */ -#elif defined(WOLFSSL_SGX) - /* Declare sprintf for ocall */ - int sprintf(char* buf, const char *fmt, ...); -#elif defined(WOLFSSL_DEOS) -#elif defined(MICRIUM) - #if (BSP_SER_COMM_EN == DEF_ENABLED) - #include - #endif -#elif defined(WOLFSSL_USER_LOG) - /* user includes their own headers */ -#elif defined(WOLFSSL_ESPIDF) - #include "esp_types.h" - #include "esp_log.h" -#elif defined(WOLFSSL_TELIT_M2MB) - #include - #include "m2m_log.h" -#elif defined(WOLFSSL_ANDROID_DEBUG) - #include -#elif defined(WOLFSSL_XILINX) - #include "xil_printf.h" -#elif defined(WOLFSSL_LINUXKM) - /* the requisite linux/kernel.h is included in wc_port.h, with incompatible warnings masked out. */ -#elif defined(FUSION_RTOS) - #include - #define fprintf FCL_FPRINTF -#else - #include /* for default printf stuff */ -#endif - -#if defined(THREADX) && !defined(THREADX_NO_DC_PRINTF) - int dc_log_printf(char*, ...); -#endif #ifdef HAVE_STACK_SIZE_VERBOSE #include @@ -281,106 +245,40 @@ static void wolfssl_log(const int logLevel, const char* const file_name, else { #if defined(WOLFSSL_USER_LOG) WOLFSSL_USER_LOG(logMessage); -#elif defined(ARDUINO) - wolfSSL_Arduino_Serial_Print(logMessage); -#elif defined(WOLFSSL_LOG_PRINTF) - if (file_name != NULL) - printf("[%s L %d] %s\n", file_name, line_number, logMessage); - else - printf("%s\n", logMessage); -#elif defined(THREADX) && !defined(THREADX_NO_DC_PRINTF) - if (file_name != NULL) - dc_log_printf("[%s L %d] %s\n", file_name, line_number, logMessage); - else - dc_log_printf("%s\n", logMessage); -#elif defined(WOLFSSL_DEOS) - if (file_name != NULL) - printf("[%s L %d] %s\r\n", file_name, line_number, logMessage); - else - printf("%s\r\n", logMessage); -#elif defined(MICRIUM) - if (file_name != NULL) - BSP_Ser_Printf("[%s L %d] %s\r\n", - file_name, line_number, logMessage); - else - BSP_Ser_Printf("%s\r\n", logMessage); -#elif defined(WOLFSSL_MDK_ARM) - fflush(stdout) ; - if (file_name != NULL) - printf("[%s L %d] %s\n", file_name, line_number, logMessage); - else - printf("%s\n", logMessage); - fflush(stdout) ; -#elif defined(WOLFSSL_UTASKER) - fnDebugMsg((char*)logMessage); - fnDebugMsg("\r\n"); -#elif defined(MQX_USE_IO_OLD) - if (file_name != NULL) - fprintf(_mqxio_stderr, "[%s L %d] %s\n", - file_name, line_number, logMessage); - else - fprintf(_mqxio_stderr, "%s\n", logMessage); -#elif defined(WOLFSSL_APACHE_MYNEWT) - if (file_name != NULL) - LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "[%s L %d] %s\n", - file_name, line_number, logMessage); - else - LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "%s\n", logMessage); -#elif defined(WOLFSSL_ESPIDF) - if (file_name != NULL) - ESP_LOGI("wolfssl", "[%s L %d] %s", - file_name, line_number, logMessage); - else - ESP_LOGI("wolfssl", "%s", logMessage); -#elif defined(WOLFSSL_ZEPHYR) - if (file_name != NULL) - printk("[%s L %d] %s\n", file_name, line_number, logMessage); - else - printk("%s\n", logMessage); -#elif defined(WOLFSSL_TELIT_M2MB) - if (file_name != NULL) - M2M_LOG_INFO("[%s L %d] %s\n", file_name, line_number, logMessage); - else - M2M_LOG_INFO("%s\n", logMessage); -#elif defined(WOLFSSL_ANDROID_DEBUG) - if (file_name != NULL) - __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "[%s L %d] %s", - file_name, line_number, logMessage); - else - __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "%s", - logMessage); -#elif defined(WOLFSSL_XILINX) - if (file_name != NULL) - xil_printf("[%s L %d] %s\r\n", file_name, line_number, logMessage); - else - xil_printf("%s\r\n", logMessage); -#elif defined(WOLFSSL_LINUXKM) - if (file_name != NULL) - printk("[%s L %d] %s\n", file_name, line_number, logMessage); - else - printk("%s\n", logMessage); -#elif defined(WOLFSSL_RENESAS_RA6M4) - if (file_name != NULL) - myprintf("[%s L %d] %s\n", file_name, line_number, logMessage); - else - myprintf("%s\n", logMessage); -#elif defined(STACK_SIZE_CHECKPOINT_MSG) && \ - defined(HAVE_STACK_SIZE_VERBOSE) && defined(HAVE_STACK_SIZE_VERBOSE_LOG) - STACK_SIZE_CHECKPOINT_MSG(logMessage); -#else +#elif defined(WOLFSSL_DEBUG_PRINTF_FN) + #ifdef WOLFSSL_MDK_ARM + fflush(stdout); + #endif if (log_prefix != NULL) { if (file_name != NULL) - fprintf(stderr, "[%s]: [%s L %d] %s\n", + WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS + "[%s]: [%s L %d] %s\n", log_prefix, file_name, line_number, logMessage); else - fprintf(stderr, "[%s]: %s\n", log_prefix, logMessage); + WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS + "[%s]: %s\n", log_prefix, logMessage); } else { if (file_name != NULL) - fprintf(stderr, "[%s L %d] %s\n", + WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS + "[%s L %d] %s\n", file_name, line_number, logMessage); else - fprintf(stderr, "%s\n", logMessage); + WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS + "%s\n", logMessage); } + #ifdef WOLFSSL_MDK_ARM + fflush(stdout); + #endif +#elif defined(ARDUINO) + wolfSSL_Arduino_Serial_Print(logMessage); +#elif defined(WOLFSSL_UTASKER) + fnDebugMsg((char*)logMessage); + fnDebugMsg("\r\n"); +#elif defined(STACK_SIZE_CHECKPOINT_MSG) && \ + defined(HAVE_STACK_SIZE_VERBOSE) && defined(HAVE_STACK_SIZE_VERBOSE_LOG) + STACK_SIZE_CHECKPOINT_MSG(logMessage); +#else + #error No log method defined. #endif } } diff --git a/src/wolfcrypt/src/md2.c b/src/wolfcrypt/src/md2.c index 89cec62..d6a7e56 100644 --- a/src/wolfcrypt/src/md2.c +++ b/src/wolfcrypt/src/md2.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/md4.c b/src/wolfcrypt/src/md4.c index 53d206e..e7342d6 100644 --- a/src/wolfcrypt/src/md4.c +++ b/src/wolfcrypt/src/md4.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/md5.c b/src/wolfcrypt/src/md5.c index 84f1117..e62a841 100644 --- a/src/wolfcrypt/src/md5.c +++ b/src/wolfcrypt/src/md5.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/memory.c b/src/wolfcrypt/src/memory.c index 928dd7b..17663b3 100644 --- a/src/wolfcrypt/src/memory.c +++ b/src/wolfcrypt/src/memory.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/misc.c b/src/wolfcrypt/src/misc.c index 98b83c7..e681d2b 100644 --- a/src/wolfcrypt/src/misc.c +++ b/src/wolfcrypt/src/misc.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -633,7 +633,13 @@ WC_MISC_STATIC WC_INLINE int ConstantCompare(const byte* a, const byte* b, } #endif -#ifndef WOLFSSL_NO_CT_OPS + +#if defined(WOLFSSL_NO_CT_OPS) && (!defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)) +/* constant time operations with mask are required for RSA and TLS operations */ +#warning constant time operations required unless using NO_RSA & WOLFCRYPT_ONLY +#endif + +#if !defined(WOLFSSL_NO_CT_OPS) || !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY) /* Constant time - mask set when a > b. */ WC_MISC_STATIC WC_INLINE byte ctMaskGT(int a, int b) { @@ -761,7 +767,8 @@ WC_MISC_STATIC WC_INLINE void ctMaskCopy(byte mask, byte* dst, byte* src, /* returns the smaller of a and b */ WC_MISC_STATIC WC_INLINE word32 min(word32 a, word32 b) { -#if !defined(WOLFSSL_NO_CT_OPS) && defined(WORD64_AVAILABLE) +#if !defined(WOLFSSL_NO_CT_OPS) && !defined(WOLFSSL_NO_CT_MAX_MIN) && \ + defined(WORD64_AVAILABLE) word32 gte_mask = (word32)ctMaskWord32GTE(a, b); return (a & ~gte_mask) | (b & gte_mask); #else /* WOLFSSL_NO_CT_OPS */ @@ -777,7 +784,8 @@ WC_MISC_STATIC WC_INLINE void ctMaskCopy(byte mask, byte* dst, byte* src, #endif WC_MISC_STATIC WC_INLINE word32 max(word32 a, word32 b) { -#if !defined(WOLFSSL_NO_CT_OPS) && defined(WORD64_AVAILABLE) +#if !defined(WOLFSSL_NO_CT_OPS) && !defined(WOLFSSL_NO_CT_MAX_MIN) && \ + defined(WORD64_AVAILABLE) word32 gte_mask = (word32)ctMaskWord32GTE(a, b); return (a & gte_mask) | (b & ~gte_mask); #else /* WOLFSSL_NO_CT_OPS */ @@ -1001,9 +1009,12 @@ WC_MISC_STATIC WC_INLINE void ato64(const byte *in, w64wrapper *w64) #ifdef BIG_ENDIAN_ORDER XMEMCPY(&w64->n, in, sizeof(w64->n)); #else - word64 _in; - XMEMCPY(&_in, in, sizeof(_in)); - w64->n = ByteReverseWord64(_in); + union { + word64 w; + byte b[sizeof(word64)]; + } _in; + XMEMCPY(_in.b, in, sizeof(_in)); + w64->n = ByteReverseWord64(_in.w); #endif /* BIG_ENDIAN_ORDER */ } diff --git a/src/wolfcrypt/src/pkcs12.c b/src/wolfcrypt/src/pkcs12.c index 5f8b85a..8739354 100644 --- a/src/wolfcrypt/src/pkcs12.c +++ b/src/wolfcrypt/src/pkcs12.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -44,16 +44,6 @@ #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; } enum { - WC_PKCS12_KeyBag = 667, - WC_PKCS12_ShroudedKeyBag = 668, - WC_PKCS12_CertBag = 669, - WC_PKCS12_CertBag_Type1 = 675, - WC_PKCS12_CrlBag = 670, - WC_PKCS12_SecretBag = 671, - WC_PKCS12_SafeContentsBag = 672, - WC_PKCS12_DATA = 651, - WC_PKCS12_ENCRYPTED_DATA = 656, - WC_PKCS12_DATA_OBJ_SZ = 11, WC_PKCS12_MAC_SALT_SZ = 8 }; @@ -1770,6 +1760,51 @@ int wc_PKCS12_parse_ex(WC_PKCS12* pkcs12, const char* psw, } +/* Helper function to get parameters for key and cert encryptions */ +static int wc_PKCS12_get_enc_params(int inAlgo, int* vPKCS, int* outAlgo, + int* blkOid, int* hmacOid) +{ + int ret = 0; + + if (inAlgo == PBE_SHA1_RC4_128) { + *vPKCS = 1; /* PKCS#12 */ + *outAlgo = PBE_SHA1_RC4_128; + *blkOid = 0; /* Unused */ + *hmacOid = 0; /* Use SHA1 as default */ + } + else if (inAlgo == PBE_SHA1_DES) { + *vPKCS = PKCS5; + *outAlgo = PBES1_SHA1_DES; + *blkOid = 0; /* Unused */ + *hmacOid = 0; /* Use SHA1 as default */ + } + else if (inAlgo == PBE_SHA1_DES3) { + *vPKCS = 1; /* PKCS#12 */ + *outAlgo = PBE_SHA1_DES3; + *blkOid = 0; /* Unused */ + *hmacOid = 0; /* Use SHA1 as default */ + } + else if (inAlgo == PBE_AES256_CBC) { + *vPKCS = PKCS5; + *outAlgo = PBES2; + *blkOid = AES256CBCb; + *hmacOid = HMAC_SHA256_OID; + } + else if (inAlgo == PBE_AES128_CBC) { + *vPKCS = PKCS5; + *outAlgo = PBES2; + *blkOid = AES128CBCb; + *hmacOid = HMAC_SHA256_OID; + } + else { + WOLFSSL_MSG("Unsupported algorithm for PKCS12 encryption"); + ret = ALGO_ID_E; + } + + return ret; +} + + /* Helper function to shroud keys. * * pkcs12 structure to use with shrouding key @@ -1791,11 +1826,17 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, { void* heap; word32 tmpIdx = 0; - int vPKCS = 1; /* PKCS#12 default set to 1 */ word32 sz; word32 totalSz = 0; int ret; byte* pkcs8Key = NULL; + byte salt[PKCS5V2_SALT_SZ]; /* PKCS5V2_SALT_SZ > PKCS5_SALT_SZ */ + word32 saltSz = 0; + + int vPKCS = -1; + int outAlgo = -1; + int blkOid = 0; + int hmacOid = 0; if (outSz == NULL || pkcs12 == NULL || rng == NULL || key == NULL || pass == NULL) { @@ -1832,13 +1873,17 @@ static int wc_PKCS12_shroud_key(WC_PKCS12* pkcs12, WC_RNG* rng, else { WOLFSSL_MSG("creating PKCS12 Shrouded Key Bag"); - if (vAlgo == PBE_SHA1_DES) { - vPKCS = PKCS5; - vAlgo = 10; + if ((ret = wc_PKCS12_get_enc_params(vAlgo, &vPKCS, &outAlgo, &blkOid, + &hmacOid)) < 0) { + return ret; + } + saltSz = (outAlgo != PBES2) ? PKCS5_SALT_SZ : PKCS5V2_SALT_SZ; + if ((ret = wc_RNG_GenerateBlock(rng, salt, saltSz)) < 0) { + return ret; } - ret = UnTraditionalEnc(key, keySz, pkcs8Key, &sz, pass, passSz, - vPKCS, vAlgo, NULL, 0, itt, rng, heap); + ret = TraditionalEnc_ex(key, keySz, pkcs8Key, &sz, pass, passSz, + vPKCS, outAlgo, blkOid, salt, saltSz, itt, hmacOid, rng, heap); } if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { *outSz = sz + MAX_LENGTH_SZ + 1; @@ -2078,7 +2123,6 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, const char* pass, int passSz, int iter, int type) { void* heap; - int vPKCS = 1; /* PKCS#12 is always set to 1 */ int ret; byte* tmp; word32 idx = 0; @@ -2087,6 +2131,11 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, word32 tmpSz; word32 encSz; + int vPKCS = -1; + int outAlgo = -1; + int blkOid = 0; + int hmacOid = 0; + byte seq[MAX_SEQ_SZ]; WOLFSSL_MSG("encrypting PKCS12 content"); @@ -2103,9 +2152,15 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, if (type == WC_PKCS12_ENCRYPTED_DATA) { word32 outerSz = 0; + if ((ret = wc_PKCS12_get_enc_params(vAlgo, &vPKCS, &outAlgo, &blkOid, + &hmacOid)) < 0) { + return ret; + } + encSz = contentSz; if ((ret = EncryptContent(NULL, contentSz, NULL, &encSz, - pass, passSz, vPKCS, vAlgo, NULL, 0, iter, rng, heap)) < 0) { + pass, passSz, vPKCS, outAlgo, blkOid, NULL, 0, iter, hmacOid, + rng, heap)) < 0) { if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) { return ret; } @@ -2157,7 +2212,8 @@ static int wc_PKCS12_encrypt_content(WC_PKCS12* pkcs12, WC_RNG* rng, } if ((ret = EncryptContent(content, contentSz, tmp, &encSz, - pass, passSz, vPKCS, vAlgo, NULL, 0, iter, rng, heap)) < 0) { + pass, passSz, vPKCS, outAlgo, blkOid, NULL, 0, iter, hmacOid, + rng, heap)) < 0) { XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } @@ -2271,6 +2327,7 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, heap = wc_PKCS12_GetHeap(pkcs12); *keyCiSz = 0; switch (nidKey) { + /* supported key encryptions */ case PBE_SHA1_RC4_128: algo = 1; break; @@ -2283,8 +2340,15 @@ static byte* PKCS12_create_key_content(WC_PKCS12* pkcs12, int nidKey, algo = 3; break; - /* no encryption */ - case -1: + case PBE_AES256_CBC: + algo = PBE_AES256_CBC; + break; + + case PBE_AES128_CBC: + algo = PBE_AES128_CBC; + break; + + case -1: /* no encryption */ algo = -1; break; @@ -2391,6 +2455,7 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, heap = wc_PKCS12_GetHeap(pkcs12); switch (nidCert) { + /* supported certificate encryptions */ case PBE_SHA1_RC4_128: type = WC_PKCS12_ENCRYPTED_DATA; algo = 1; @@ -2406,7 +2471,17 @@ static byte* PKCS12_create_cert_content(WC_PKCS12* pkcs12, int nidCert, algo = 3; break; - case -1: + case PBE_AES256_CBC: + type = WC_PKCS12_ENCRYPTED_DATA; + algo = PBE_AES256_CBC; + break; + + case PBE_AES128_CBC: + type = WC_PKCS12_ENCRYPTED_DATA; + algo = PBE_AES128_CBC; + break; + + case -1: /* no encryption */ type = WC_PKCS12_DATA; algo = -1; break; diff --git a/src/wolfcrypt/src/pkcs7.c b/src/wolfcrypt/src/pkcs7.c index a8545ba..1b4fcf6 100644 --- a/src/wolfcrypt/src/pkcs7.c +++ b/src/wolfcrypt/src/pkcs7.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -12659,8 +12659,13 @@ WOLFSSL_API int wc_PKCS7_DecodeEnvelopedData(wc_PKCS7* pkcs7, byte* in, case WC_PKCS7_ENV_5: #ifndef NO_PKCS7_STREAM + if ((ret = wc_PKCS7_AddDataToStream(pkcs7, in, inSz, pkcs7->stream->expected, &pkiMsg, &idx)) != 0) { + if (ret != WC_NO_ERR_TRACE(WC_PKCS7_WANT_READ_E)) { + wc_PKCS7_StreamGetVar(pkcs7, &encOID, NULL, NULL); + wc_PKCS7_DecryptContentFree(pkcs7, encOID, pkcs7->heap); + } return ret; } @@ -13106,11 +13111,9 @@ int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, #ifdef HAVE_AESGCM #ifdef WOLFSSL_AES_128 case AES128GCMb: - FALL_THROUGH; #endif #ifdef WOLFSSL_AES_192 case AES192GCMb: - FALL_THROUGH; #endif #ifdef WOLFSSL_AES_256 case AES256GCMb: @@ -13125,11 +13128,9 @@ int wc_PKCS7_EncodeAuthEnvelopedData(wc_PKCS7* pkcs7, byte* output, #ifdef HAVE_AESCCM #ifdef WOLFSSL_AES_128 case AES128CCMb: - FALL_THROUGH; #endif #ifdef WOLFSSL_AES_192 case AES192CCMb: - FALL_THROUGH; #endif #ifdef WOLFSSL_AES_256 case AES256CCMb: @@ -14877,6 +14878,62 @@ int wc_PKCS7_SetDecodeEncryptedCtx(wc_PKCS7* pkcs7, void* ctx) #endif /* NO_PKCS7_ENCRYPTED_DATA */ +/* Unwrap and decrypt PKCS#7/CMS EncryptedKeyPackage object, return the + * decoded size. */ +int wc_PKCS7_DecodeEncryptedKeyPackage(wc_PKCS7 * pkcs7, + byte * pkiMsg, word32 pkiMsgSz, byte * output, word32 outputSz) +{ + int ret = 0; + word32 pkiIndex = 0; + word32 contentType = 0; + int length = 0; + + if (pkiMsg == NULL) { + ret = BAD_FUNC_ARG; + } + /* Expect a SEQUENCE header to start the EncryptedKeyPackage + * ContentInfo. */ + else if (GetSequence_ex(pkiMsg, &pkiIndex, &length, pkiMsgSz, 1) < 0) { + ret = ASN_PARSE_E; + } + /* Validate the EncryptedKeyPackage OBJECT IDENTIFIER. */ + else if (wc_GetContentType(pkiMsg, &pkiIndex, &contentType, pkiMsgSz) < 0) { + ret = ASN_PARSE_E; + } + else if (contentType != ENCRYPTED_KEY_PACKAGE) { + WOLFSSL_MSG("PKCS#7 input not of type EncryptedKeyPackage"); + ret = PKCS7_OID_E; + } + /* Expect content [0] tag */ + else if (GetASNHeader(pkiMsg, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, + &pkiIndex, &length, pkiMsgSz) < 0) { + ret = ASN_PARSE_E; + } + /* Check for an EncryptedKeyPackage explicit CHOICE [0] tag, indicating + * an EnvelopedData subtype. */ + else if (GetASNHeader(pkiMsg, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, + &pkiIndex, &length, pkiMsgSz) >= 0) { + /* An explicit CHOICE [0] tag was found. pkiIndex now should point + * to the EnvelopedData ContentInfo object within the + * EncryptedKeyPackage. */ + ret = wc_PKCS7_DecodeEnvelopedData(pkcs7, &pkiMsg[pkiIndex], + pkiMsgSz - pkiIndex, output, outputSz); + } + else { +#ifndef NO_PKCS7_ENCRYPTED_DATA + /* An explicit CHOICE [0] tag was not found. Check if we have an + * EncryptedData blob. */ + ret = wc_PKCS7_DecodeEncryptedData(pkcs7, &pkiMsg[pkiIndex], + pkiMsgSz - pkiIndex, output, outputSz); +#else + ret = ASN_PARSE_E; +#endif + } + + return ret; +} + + /* set stream mode for encoding and signing * returns 0 on success */ int wc_PKCS7_SetStreamMode(wc_PKCS7* pkcs7, byte flag, diff --git a/src/wolfcrypt/src/poly1305.c b/src/wolfcrypt/src/poly1305.c index bd72a40..f8e230f 100644 --- a/src/wolfcrypt/src/poly1305.c +++ b/src/wolfcrypt/src/poly1305.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/Espressif/esp32_aes.c b/src/wolfcrypt/src/port/Espressif/esp32_aes.c index b1479de..4eed1d8 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/Espressif/esp32_mp.c b/src/wolfcrypt/src/port/Espressif/esp32_mp.c index dbfd133..9092f77 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/Espressif/esp32_sha.c b/src/wolfcrypt/src/port/Espressif/esp32_sha.c index f9f8d90..6722a93 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_sha.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_sha.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/Espressif/esp32_util.c b/src/wolfcrypt/src/port/Espressif/esp32_util.c index 90b3cdc..c7db477 100644 --- a/src/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/src/wolfcrypt/src/port/Espressif/esp32_util.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -31,6 +31,11 @@ #include "sdkconfig.h" /* programmatically generated from sdkconfig */ #include +#if HAVE_LIBWOLFSSL_OUTPUT_HEADER + /* see wolfssl component CMakeLists.txt that may have generated this: */ + #include "libwolfssl_output.h" +#endif + /* Espressif */ #include #include @@ -647,6 +652,16 @@ int ShowExtendedSystemInfo(void) LIBWOLFSSL_VERSION_HEX); #endif +#if defined(LIBWOLFSSL_CMAKE_OUTPUT) + /* For some environments such as PlatformIO that may hide CMake output, + * we can have important messages propagated to the app: */ + ESP_LOGI(TAG, "----------------------------------------------------------"); + ESP_LOGI(TAG, "LIBWOLFSSL_CMAKE_OUTPUT:%s", LIBWOLFSSL_CMAKE_OUTPUT); + ESP_LOGI(TAG, "----------------------------------------------------------"); +#else + ESP_LOGW(TAG, "LIBWOLFSSL_CMAKE_OUTPUT: No cmake messages detected"); +#endif + /* some interesting settings are target specific (ESP32, -C3, -S3, etc */ #if defined(CONFIG_IDF_TARGET_ESP32) /* ESP_RSA_MULM_BITS should be set to at least 16 for ESP32 */ diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c index 5bd7a64..d1e51a5 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_mem_lib.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c index 036174e..7f27a2d 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -181,10 +181,15 @@ int set_fixed_default_time(void) { /* ideally, we'd like to set time from network, * but let's set a default time, just in case */ + + ESP_LOGV(TAG, "Default Date %s", __DATE__); + ESP_LOGV(TAG, "YEAR %d", YEAR); + ESP_LOGV(TAG, "MONTH %d", MONTH); + ESP_LOGV(TAG, "DAY %d", DAY); struct tm timeinfo = { - .tm_year = YEAR, - .tm_mon = MONTH, /* Month, where 0 = Jan */ - .tm_mday = DAY, /* Numeric decimal day of the month */ + .tm_year = YEAR - 1900, /* years since 1900 */ + .tm_mon = MONTH - 1, /* Month, where 0 = Jan */ + .tm_mday = DAY - 1, /* Numeric decimal day of the month */ .tm_hour = 13, .tm_min = 1, .tm_sec = 5 diff --git a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c index db7c954..b3c62e9 100644 --- a/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c +++ b/src/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/port/atmel/atmel.c b/src/wolfcrypt/src/port/atmel/atmel.c index 6aabe5d..386a8f4 100644 --- a/src/wolfcrypt/src/port/atmel/atmel.c +++ b/src/wolfcrypt/src/port/atmel/atmel.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/pwdbased.c b/src/wolfcrypt/src/pwdbased.c index c60db6a..8c7c64c 100644 --- a/src/wolfcrypt/src/pwdbased.c +++ b/src/wolfcrypt/src/pwdbased.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/random.c b/src/wolfcrypt/src/random.c index 746a06b..f8107d0 100644 --- a/src/wolfcrypt/src/random.c +++ b/src/wolfcrypt/src/random.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -147,12 +147,13 @@ This library contains implementation for the random number generator. #elif defined(WOLFSSL_IMXRT1170_CAAM) #elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) #include "cyhal_trng.h" /* Infineon/Cypress HAL RNG implementation */ -#elif defined(WOLFSSL_GETRANDOM) - #include - #include #elif defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) #include "wolfssl/wolfcrypt/port/maxim/max3266x.h" #else + #if defined(WOLFSSL_GETRANDOM) || defined(HAVE_GETRANDOM) + #include + #include + #endif /* include headers that may be needed to get good seed */ #include #ifndef EBSNET @@ -188,8 +189,7 @@ This library contains implementation for the random number generator. { intel_flags = cpuid_get_flags(); } - #if (defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)) && \ - !defined(WOLFSSL_LINUXKM) + #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz); #endif #ifdef HAVE_INTEL_RDRAND @@ -231,7 +231,6 @@ This library contains implementation for the random number generator. #define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE) #define MAX_REQUEST_LEN (0x10000) -#define RESEED_INTERVAL WC_RESEED_INTERVAL /* The security strength for the RNG is the target number of bits of @@ -254,7 +253,12 @@ This library contains implementation for the random number generator. #endif #elif defined(HAVE_AMD_RDSEED) /* This will yield a SEED_SZ of 16kb. Since nonceSz will be 0, - * we'll add an additional 8kb on top. */ + * we'll add an additional 8kb on top. + * + * See "AMD RNG ESV Public Use Document". Version 0.7 of October 24, + * 2024 specifies 0.656 to 1.312 bits of entropy per 128 bit block of + * RDSEED output, depending on CPU family. + */ #define ENTROPY_SCALE_FACTOR (512) #elif defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) /* The value of 2 applies to Intel's RDSEED which provides about @@ -306,7 +310,11 @@ This library contains implementation for the random number generator. #ifdef WC_RNG_SEED_CB +#ifndef HAVE_FIPS +static wc_RngSeed_Cb seedCb = wc_GenerateSeed; +#else static wc_RngSeed_Cb seedCb = NULL; +#endif int wc_SetSeed_Cb(wc_RngSeed_Cb cb) { @@ -365,7 +373,7 @@ static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type, #else wc_Sha256 sha[1]; #endif -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_LINUXKM) byte* digest; #else byte digest[WC_SHA256_DIGEST_SIZE]; @@ -375,7 +383,7 @@ static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type, return DRBG_FAILURE; } -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_LINUXKM) digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap, DYNAMIC_TYPE_DIGEST); if (digest == NULL) @@ -436,7 +444,7 @@ static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type, ForceZero(digest, WC_SHA256_DIGEST_SIZE); -#ifdef WOLFSSL_SMALL_STACK +#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_LINUXKM) XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); #endif @@ -634,26 +642,31 @@ static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz) wc_Sha256 sha[1]; #endif byte type; +#ifdef WORD64_AVAILABLE + word64 reseedCtr; +#else word32 reseedCtr; +#endif if (drbg == NULL) { return DRBG_FAILURE; } - if (drbg->reseedCtr == RESEED_INTERVAL) { -#if FIPS_VERSION3_GE(6,0,0) - printf("Reseed triggered\n"); -#endif + if (drbg->reseedCtr >= WC_RESEED_INTERVAL) { + #if defined(DEBUG_WOLFSSL) || defined(DEBUG_DRBG_RESEEDS) + printf("DRBG reseed triggered, reseedCtr == %lu", + (unsigned long)drbg->reseedCtr); + #endif return DRBG_NEED_RESEED; } else { - #ifndef WOLFSSL_SMALL_STACK - byte digest[WC_SHA256_DIGEST_SIZE]; - #else + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_LINUXKM) byte* digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap, DYNAMIC_TYPE_DIGEST); if (digest == NULL) return DRBG_FAILURE; + #else + byte digest[WC_SHA256_DIGEST_SIZE]; #endif type = drbgGenerateH; @@ -683,7 +696,11 @@ static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz) array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE); array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C)); #ifdef LITTLE_ENDIAN_ORDER + #ifdef WORD64_AVAILABLE + reseedCtr = ByteReverseWord64(reseedCtr); + #else reseedCtr = ByteReverseWord32(reseedCtr); + #endif #endif array_add(drbg->V, sizeof(drbg->V), (byte*)&reseedCtr, sizeof(reseedCtr)); @@ -692,7 +709,7 @@ static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz) drbg->reseedCtr++; } ForceZero(digest, WC_SHA256_DIGEST_SIZE); - #ifdef WOLFSSL_SMALL_STACK + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_LINUXKM) XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); #endif } @@ -1124,6 +1141,16 @@ static word64 Entropy_GetSample(void) word64 now; word64 ret; +#ifdef HAVE_FIPS + /* First sample must be disregard when in FIPS. */ + if (entropy_last_time == 0) { + /* Get sample which triggers CAST in FIPS mode. */ + Entropy_MemUse(); + /* Start entropy time after CASTs. */ + entropy_last_time = Entropy_TimeHiRes(); + } +#endif + /* Use memory such that it will take an unpredictable amount of time. */ Entropy_MemUse(); @@ -1225,6 +1252,7 @@ static int Entropy_HealthTest_Repetition(byte noise) if (!rep_have_prev) { rep_prev_noise = noise; rep_have_prev = 1; + rep_cnt = 1; } /* Check whether this sample matches last. */ else if (noise == rep_prev_noise) { @@ -1258,7 +1286,7 @@ static int Entropy_HealthTest_Repetition(byte noise) /* SP800-90b 4.4.2 - Adaptive Proportion Test * Note 10 * C = 1 + CRITBINOM(W, power(2,( -H)),1-alpha) - * alpa = 2^-30 = POWER(2,-30), H = 1, W = 512 + * alpha = 2^-30 = POWER(2,-30), H = 1, W = 512 * C = 1 + CRITBINOM(512, 0.5, 1-POWER(2,-30)) = 1 + 324 = 325 */ #define PROP_CUTOFF 325 @@ -1308,8 +1336,9 @@ static int Entropy_HealthTest_Proportion(byte noise) { int ret = 0; - /* Need at least 512-1 samples to test with. */ - if (prop_total < PROP_WINDOW_SIZE - 1) { + /* Need minimum samples in queue to test with - keep adding while we have + * less. */ + if (prop_total < PROP_CUTOFF - 1) { /* Store sample at last position in circular queue. */ prop_samples[prop_last++] = noise; /* Update count of seen value based on new sample. */ @@ -1318,27 +1347,36 @@ static int Entropy_HealthTest_Proportion(byte noise) prop_total++; } else { - /* Get first value in queue - value to test. */ - byte val = (byte)prop_samples[prop_first]; - /* Store new sample in queue. */ + /* We have at least a minimum set of samples in queue. */ + /* Store new sample at end of queue. */ prop_samples[prop_last] = noise; - /* Update first index now that we have removed in from the queue. */ - prop_first = (prop_first + 1) % PROP_WINDOW_SIZE; /* Update last index now that we have added new sample to queue. */ prop_last = (prop_last + 1) % PROP_WINDOW_SIZE; - /* Removed sample from queue - remove count. */ - prop_cnt[val]--; /* Added sample to queue - add count. */ prop_cnt[noise]++; - /* Check whether removed value has too many repetitions in queue. */ - if (prop_cnt[val] >= PROP_CUTOFF) { + /* Update count of store values. */ + prop_total++; + + /* Check whether first value has too many repetitions in queue. */ + if (prop_cnt[noise] >= PROP_CUTOFF) { #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE - fprintf(stderr, "PROPORTION FAILED: %d %d\n", val, prop_cnt[val]); + fprintf(stderr, "PROPORTION FAILED: %d %d\n", val, prop_cnt[noise]); #endif Entropy_HealthTest_Proportion_Reset(); /* Error code returned. */ ret = ENTROPY_APT_E; } + else if (prop_total == PROP_WINDOW_SIZE) { + /* Return to 511 samples in queue. */ + /* Get first value in queue - value to test. */ + byte val = (byte)prop_samples[prop_first]; + /* Update first index to remove first sample from the queue. */ + prop_first = (prop_first + 1) % PROP_WINDOW_SIZE; + /* Removed first sample from queue - remove count. */ + prop_cnt[val]--; + /* Update count of store values. */ + prop_total--; + } } return ret; @@ -1371,6 +1409,10 @@ static int Entropy_HealthTest_Startup(void) #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE fprintf(stderr, "STARTUP HEALTH TEST\n"); #endif + + /* Reset cached values before testing. */ + Entropy_HealthTest_Reset(); + /* Fill initial sample buffer with noise. */ Entropy_GetNoise(initial, ENTROPY_INITIAL_COUNT); /* Health check initial noise. */ @@ -1452,13 +1494,23 @@ static wolfSSL_Mutex entropy_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(entropy_mute int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len) { int ret = 0; +#ifdef WOLFSSL_SMALL_STACK + byte *noise = NULL; +#else byte noise[MAX_NOISE_CNT]; +#endif /* Noise length is the number of 8 byte samples required to get the bits of * entropy requested. */ int noise_len = (bits + ENTROPY_EXTRA) / ENTROPY_MIN; +#ifdef WOLFSSL_SMALL_STACK + noise = (byte *)XMALLOC(MAX_NOISE_CNT, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (noise == NULL) + return MEMORY_E; +#endif + /* Lock the mutex as collection uses globals. */ - if (wc_LockMutex(&entropy_mutex) != 0) { + if ((ret == 0) && (wc_LockMutex(&entropy_mutex) != 0)) { ret = BAD_MUTEX_E; } @@ -1516,6 +1568,10 @@ int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len) wc_UnLockMutex(&entropy_mutex); } +#ifdef WOLFSSL_SMALL_STACK + XFREE(noise, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return ret; } @@ -1537,8 +1593,6 @@ int wc_Entropy_OnDemandTest(void) } if (ret == 0) { - /* Reset health test state for startup test. */ - Entropy_HealthTest_Reset(); /* Perform startup tests. */ ret = Entropy_HealthTest_Startup(); } @@ -1640,6 +1694,9 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, #else rng->heap = heap; #endif +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) + rng->pid = getpid(); +#endif #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) rng->devId = devId; #if defined(WOLF_CRYPTO_CB) @@ -1895,6 +1952,63 @@ int wc_InitRngNonce_ex(WC_RNG* rng, byte* nonce, word32 nonceSz, return _InitRng(rng, nonce, nonceSz, heap, devId); } +#ifdef HAVE_HASHDRBG +static int PollAndReSeed(WC_RNG* rng) +{ + int ret = DRBG_NEED_RESEED; + int devId = INVALID_DEVID; +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) + devId = rng->devId; +#endif + if (wc_RNG_HealthTestLocal(1, rng->heap, devId) == 0) { + #ifndef WOLFSSL_SMALL_STACK + byte newSeed[SEED_SZ + SEED_BLOCK_SZ]; + ret = DRBG_SUCCESS; + #else + byte* newSeed = (byte*)XMALLOC(SEED_SZ + SEED_BLOCK_SZ, rng->heap, + DYNAMIC_TYPE_SEED); + ret = (newSeed == NULL) ? MEMORY_E : DRBG_SUCCESS; + #endif + if (ret == DRBG_SUCCESS) { + #ifdef WC_RNG_SEED_CB + if (seedCb == NULL) { + ret = DRBG_NO_SEED_CB; + } + else { + ret = seedCb(&rng->seed, newSeed, SEED_SZ + SEED_BLOCK_SZ); + if (ret != 0) { + ret = DRBG_FAILURE; + } + } + #else + ret = wc_GenerateSeed(&rng->seed, newSeed, + SEED_SZ + SEED_BLOCK_SZ); + #endif + if (ret != 0) + ret = DRBG_FAILURE; + } + if (ret == DRBG_SUCCESS) + ret = wc_RNG_TestSeed(newSeed, SEED_SZ + SEED_BLOCK_SZ); + + if (ret == DRBG_SUCCESS) + ret = Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, + newSeed + SEED_BLOCK_SZ, SEED_SZ); + #ifdef WOLFSSL_SMALL_STACK + if (newSeed != NULL) { + ForceZero(newSeed, SEED_SZ + SEED_BLOCK_SZ); + } + XFREE(newSeed, rng->heap, DYNAMIC_TYPE_SEED); + #else + ForceZero(newSeed, sizeof(newSeed)); + #endif + } + else { + ret = DRBG_CONT_FAILURE; + } + + return ret; +} +#endif /* place a generated block in output */ WOLFSSL_ABI @@ -1954,60 +2068,22 @@ int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) if (rng->status != DRBG_OK) return RNG_FAILURE_E; +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) + if (rng->pid != getpid()) { + rng->pid = getpid(); + ret = PollAndReSeed(rng); + if (ret != DRBG_SUCCESS) { + rng->status = DRBG_FAILED; + return RNG_FAILURE_E; + } + } +#endif + ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz); if (ret == DRBG_NEED_RESEED) { - int devId = INVALID_DEVID; - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - devId = rng->devId; - #endif - if (wc_RNG_HealthTestLocal(1, rng->heap, devId) == 0) { - #ifndef WOLFSSL_SMALL_STACK - byte newSeed[SEED_SZ + SEED_BLOCK_SZ]; - ret = DRBG_SUCCESS; - #else - byte* newSeed = (byte*)XMALLOC(SEED_SZ + SEED_BLOCK_SZ, rng->heap, - DYNAMIC_TYPE_SEED); - ret = (newSeed == NULL) ? MEMORY_E : DRBG_SUCCESS; - #endif - if (ret == DRBG_SUCCESS) { - #ifdef WC_RNG_SEED_CB - if (seedCb == NULL) { - ret = DRBG_NO_SEED_CB; - } - else { - ret = seedCb(&rng->seed, newSeed, SEED_SZ + SEED_BLOCK_SZ); - if (ret != 0) { - ret = DRBG_FAILURE; - } - } - #else - ret = wc_GenerateSeed(&rng->seed, newSeed, - SEED_SZ + SEED_BLOCK_SZ); - #endif - if (ret != 0) - ret = DRBG_FAILURE; - } - if (ret == DRBG_SUCCESS) - ret = wc_RNG_TestSeed(newSeed, SEED_SZ + SEED_BLOCK_SZ); - - if (ret == DRBG_SUCCESS) - ret = Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, - newSeed + SEED_BLOCK_SZ, SEED_SZ); - if (ret == DRBG_SUCCESS) - ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz); - - #ifdef WOLFSSL_SMALL_STACK - if (newSeed != NULL) { - ForceZero(newSeed, SEED_SZ + SEED_BLOCK_SZ); - } - XFREE(newSeed, rng->heap, DYNAMIC_TYPE_SEED); - #else - ForceZero(newSeed, sizeof(newSeed)); - #endif - } - else { - ret = DRBG_CONT_FAILURE; - } + ret = PollAndReSeed(rng); + if (ret == DRBG_SUCCESS) + ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz); } if (ret == DRBG_SUCCESS) { @@ -2523,7 +2599,6 @@ static WC_INLINE int IntelRDseed64_r(word64* rnd) return -1; } -#ifndef WOLFSSL_LINUXKM /* return 0 on success */ static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz) { @@ -2554,7 +2629,6 @@ static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz) return 0; } -#endif #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ @@ -2711,6 +2785,34 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #elif defined(USE_WINDOWS_API) +#ifdef WIN_REUSE_CRYPT_HANDLE +/* shared crypt handle for RNG use */ +static ProviderHandle gHandle = 0; + +int wc_WinCryptHandleInit(void) +{ + int ret = 0; + if (gHandle == 0) { + if(!CryptAcquireContext(&gHandle, 0, 0, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT)) { + DWORD dw = GetLastError(); + WOLFSSL_MSG("CryptAcquireContext failed!"); + WOLFSSL_ERROR((int)dw); + ret = WINCRYPT_E; + } + } + return ret; +} + +void wc_WinCryptHandleCleanup(void) +{ + if (gHandle != 0) { + CryptReleaseContext(gHandle, 0); + gHandle = 0; + } +} +#endif /* WIN_REUSE_CRYPT_HANDLE */ + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { #ifdef WOLF_CRYPTO_CB @@ -2741,14 +2843,27 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } #endif /* HAVE_INTEL_RDSEED */ - if(!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL, - CRYPT_VERIFYCONTEXT)) +#ifdef WIN_REUSE_CRYPT_HANDLE + /* Check that handle was initialized. + * Note: initialization should be done through: + * wolfSSL_Init -> wolfCrypt_Init -> wc_WinCryptHandleInit + */ + if (wc_WinCryptHandleInit() != 0) { return WINCRYPT_E; - - if (!CryptGenRandom(os->handle, sz, output)) + } + if (!CryptGenRandom(gHandle, sz, output)) return CRYPTGEN_E; - +#else + if (!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT)) { + return WINCRYPT_E; + } + if (!CryptGenRandom(os->handle, sz, output)) { + return CRYPTGEN_E; + } CryptReleaseContext(os->handle, 0); + os->handle = 0; +#endif return 0; } @@ -3687,16 +3802,69 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif /* end WOLFSSL_ESPIDF */ #elif defined(WOLFSSL_LINUXKM) + + /* When registering the kernel default DRBG with a native/intrinsic entropy + * source, fallback to get_random_bytes() isn't allowed because we replace + * it with our DRBG. + */ + + #if defined(HAVE_ENTROPY_MEMUSE) && \ + defined(LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT) + + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + (void)os; + return wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz); + } + + #elif (defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)) && \ + defined(LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT) + + int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) + { + (void)os; + return wc_GenerateSeed_IntelRD(NULL, output, sz); + } + + #else /* !((HAVE_ENTROPY_MEMUSE || HAVE_*_RDSEED) && LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT) */ + #include int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { (void)os; + int ret; - get_random_bytes(output, sz); + #ifdef HAVE_ENTROPY_MEMUSE + ret = wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz); + if (ret == 0) { + return 0; + } + #ifdef ENTROPY_MEMUSE_FORCE_FAILURE + /* Don't fallback to /dev/urandom. */ + return ret; + #endif + #endif + #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) + if (IS_INTEL_RDSEED(intel_flags)) { + ret = wc_GenerateSeed_IntelRD(NULL, output, sz); + #ifndef FORCE_FAILURE_RDSEED + if (ret == 0) + #endif + { + return ret; + } + } + #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ + + (void)ret; + + get_random_bytes(output, sz); return 0; } + #endif /* !(HAVE_*_RDSEED && LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT) */ + #elif defined(WOLFSSL_RENESAS_TSIP) int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) @@ -3908,37 +4076,6 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) return wc_MXC_TRNG_Random(output, sz); } -#elif defined(WOLFSSL_GETRANDOM) - - /* getrandom() was added to the Linux kernel in version 3.17. - * Added to glibc in version 2.25. */ - int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) - { - int ret = 0; - (void)os; - - while (sz) { - int len; - - errno = 0; - len = (int)getrandom(output, sz, 0); - if (len == -1) { - if (errno == EINTR) { - /* interrupted, call getrandom again */ - continue; - } - else { - ret = READ_RAN_E; - } - break; - } - - sz -= len; - output += len; - } - return ret; - } - #elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) /* Infineon/Cypress HAL RNG implementation */ @@ -4074,6 +4211,43 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ + #if defined(WOLFSSL_GETRANDOM) || defined(HAVE_GETRANDOM) + { + word32 grSz = sz; + byte* grOutput = output; + + while (grSz) { + ssize_t len; + + errno = 0; + len = getrandom(grOutput, grSz, 0); + if (len == -1) { + if (errno == EINTR) { + /* interrupted, call getrandom again */ + continue; + } + else { + ret = READ_RAN_E; + } + break; + } + + grSz -= (word32)len; + grOutput += len; + } + if (ret == 0) + return ret; + #ifdef FORCE_FAILURE_GETRANDOM + /* don't fallback to /dev/urandom */ + return ret; + #else + /* reset error and fallback to using /dev/urandom */ + ret = 0; + #endif + } + #endif + +#ifndef NO_FILESYSTEM #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ os->fd = open("/dev/urandom", O_RDONLY); #if defined(DEBUG_WOLFSSL) @@ -4113,6 +4287,9 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) } } close(os->fd); +#else + ret = NOT_COMPILED_IN; +#endif /* NO_FILESYSTEM */ return ret; } diff --git a/src/wolfcrypt/src/rc2.c b/src/wolfcrypt/src/rc2.c index 33d2bd2..a754139 100644 --- a/src/wolfcrypt/src/rc2.c +++ b/src/wolfcrypt/src/rc2.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/ripemd.c b/src/wolfcrypt/src/ripemd.c index 7f3b6d8..73e9d32 100644 --- a/src/wolfcrypt/src/ripemd.c +++ b/src/wolfcrypt/src/ripemd.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/rsa.c b/src/wolfcrypt/src/rsa.c index 94d57bd..78c0c9e 100644 --- a/src/wolfcrypt/src/rsa.c +++ b/src/wolfcrypt/src/rsa.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2551,7 +2551,7 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng) if (ret == 0) { /* blind */ - ret = mp_rand(rnd, get_digit_count(&key->n), rng); + ret = mp_rand(rnd, mp_get_digit_count(&key->n), rng); } if (ret == 0) { /* rndi = 1/rnd mod n */ @@ -2924,7 +2924,8 @@ static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out, } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */ -#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) +#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || \ + defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* Performs direct RSA computation without padding. The input and output must * match the key size (ex: 2048-bits = 256 bytes). Returns the size of the * output on success or negative value on failure. */ @@ -3010,7 +3011,8 @@ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, return ret; } -#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ +#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING || OPENSSL_EXTRA || \ + * OPENSSL_EXTRA_X509_SMALL */ #if defined(WOLFSSL_CRYPTOCELL) static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, @@ -3761,6 +3763,9 @@ int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key) WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -3782,6 +3787,9 @@ int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out, WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -3802,6 +3810,9 @@ int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out, WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -3823,6 +3834,9 @@ int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out, WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -3843,6 +3857,9 @@ int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -3856,7 +3873,7 @@ int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) } #endif -#ifndef WOLFSSL_RSA_VERIFY_ONLY +#ifndef WOLFSSL_RSA_VERIFY_INLINE int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { @@ -3951,6 +3968,9 @@ int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out, WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -4006,6 +4026,9 @@ int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen, WC_RNG* rng; int ret; #ifdef WC_RSA_BLINDING + if (key == NULL) { + return BAD_FUNC_ARG; + } rng = key->rng; #else rng = NULL; @@ -4192,6 +4215,9 @@ int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out, saltLen = hLen; #ifdef WOLFSSL_SHA512 + if (key == NULL) { + return BAD_FUNC_ARG; + } /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) @@ -4238,6 +4264,9 @@ int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen, saltLen = hLen; #ifdef WOLFSSL_SHA512 + if (key == NULL) { + return BAD_FUNC_ARG; + } /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) @@ -5063,7 +5092,7 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) /* Blind the inverse operation with a value that is invertable */ if (err == MP_OKAY) { do { - err = mp_rand(&key->p, get_digit_count(tmp3), rng); + err = mp_rand(&key->p, mp_get_digit_count(tmp3), rng); if (err == MP_OKAY) err = mp_set_bit(&key->p, 0); if (err == MP_OKAY) diff --git a/src/wolfcrypt/src/sakke.c b/src/wolfcrypt/src/sakke.c index d428c59..3e8db92 100644 --- a/src/wolfcrypt/src/sakke.c +++ b/src/wolfcrypt/src/sakke.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sha.c b/src/wolfcrypt/src/sha.c index 887541a..8dc9662 100644 --- a/src/wolfcrypt/src/sha.c +++ b/src/wolfcrypt/src/sha.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -780,6 +780,7 @@ int wc_ShaFinalRaw(wc_Sha* sha, byte* hash) { #ifdef LITTLE_ENDIAN_ORDER word32 digest[WC_SHA_DIGEST_SIZE / sizeof(word32)]; + XMEMSET(digest, 0, sizeof(digest)); #endif if (sha == NULL || hash == NULL) { diff --git a/src/wolfcrypt/src/sha256.c b/src/wolfcrypt/src/sha256.c index 5b990a2..08434c9 100644 --- a/src/wolfcrypt/src/sha256.c +++ b/src/wolfcrypt/src/sha256.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -206,6 +206,8 @@ on the specific device platform. #endif #elif defined(FREESCALE_MMCAU_SHA) #define SHA256_UPDATE_REV_BYTES(ctx) 0 /* reverse not needed on update */ +#elif defined(WOLFSSL_PPC32_ASM) + #define SHA256_UPDATE_REV_BYTES(ctx) 0 #else #define SHA256_UPDATE_REV_BYTES(ctx) SHA256_REV_BYTES(ctx) #endif @@ -1067,6 +1069,35 @@ static int InitSha256(wc_Sha256* sha256) #elif defined(WOLFSSL_RENESAS_RX64_HASH) /* implemented in wolfcrypt/src/port/Renesas/renesas_rx64_hw_sha.c */ +#elif defined(WOLFSSL_PPC32_ASM) + +extern void Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, + word32 len); + +int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) +{ + int ret = 0; + + if (sha256 == NULL) + return BAD_FUNC_ARG; + ret = InitSha256(sha256); + if (ret != 0) + return ret; + + sha256->heap = heap; + (void)devId; + + return ret; +} + +static int Transform_Sha256(wc_Sha256* sha256, const byte* data) +{ + Transform_Sha256_Len(sha256, data, WC_SHA256_BLOCK_SIZE); + return 0; +} + +#define XTRANSFORM Transform_Sha256 +#define XTRANSFORM_LEN Transform_Sha256_Len #else #define NEED_SOFT_SHA256 @@ -1171,7 +1202,7 @@ static int InitSha256(wc_Sha256* sha256) word32 S[8], t0, t1; int i; - #ifdef WOLFSSL_SMALL_STACK_CACHE + #if defined(WOLFSSL_SMALL_STACK_CACHE) && !defined(WOLFSSL_NO_MALLOC) word32* W = sha256->W; if (W == NULL) { W = (word32*)XMALLOC(sizeof(word32) * WC_SHA256_BLOCK_SIZE, NULL, @@ -1180,7 +1211,7 @@ static int InitSha256(wc_Sha256* sha256) return MEMORY_E; sha256->W = W; } - #elif defined(WOLFSSL_SMALL_STACK) + #elif defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC) word32* W; W = (word32*)XMALLOC(sizeof(word32) * WC_SHA256_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -1221,7 +1252,8 @@ static int InitSha256(wc_Sha256* sha256) sha256->digest[i] += S[i]; } - #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) + #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) &&\ + !defined(WOLFSSL_NO_MALLOC) ForceZero(W, sizeof(word32) * WC_SHA256_BLOCK_SIZE); XFREE(W, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif @@ -1683,6 +1715,7 @@ static int InitSha256(wc_Sha256* sha256) { #ifdef LITTLE_ENDIAN_ORDER word32 digest[WC_SHA256_DIGEST_SIZE / sizeof(word32)]; + XMEMSET(digest, 0, sizeof(digest)); #endif if (sha256 == NULL || hash == NULL) { diff --git a/src/wolfcrypt/src/sha3.c b/src/wolfcrypt/src/sha3.c index a9795ff..145c666 100644 --- a/src/wolfcrypt/src/sha3.c +++ b/src/wolfcrypt/src/sha3.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -21,6 +21,12 @@ #include +#ifdef WC_SHA3_NO_ASM + #undef USE_INTEL_SPEEDUP + #undef WOLFSSL_ARMASM + #undef WOLFSSL_RISCV_ASM +#endif + #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_XILINX_CRYPT) && \ !defined(WOLFSSL_AFALG_XILINX_SHA3) @@ -242,9 +248,6 @@ while (0) * * s The state. */ -#ifndef USE_INTEL_SPEEDUP -static -#endif void BlockSha3(word64* s) { byte i, x, y; @@ -535,9 +538,6 @@ while (0) * * s The state. */ -#ifndef USE_INTEL_SPEEDUP -static -#endif void BlockSha3(word64* s) { word64 n[25]; diff --git a/src/wolfcrypt/src/sha512.c b/src/wolfcrypt/src/sha512.c index 73ef412..b0ca4c2 100644 --- a/src/wolfcrypt/src/sha512.c +++ b/src/wolfcrypt/src/sha512.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/signature.c b/src/wolfcrypt/src/signature.c index 5576e2e..4a403c8 100644 --- a/src/wolfcrypt/src/signature.c +++ b/src/wolfcrypt/src/signature.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/siphash.c b/src/wolfcrypt/src/siphash.c index 05c2690..67e26a1 100644 --- a/src/wolfcrypt/src/siphash.c +++ b/src/wolfcrypt/src/siphash.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -21,6 +21,10 @@ #include +#if defined(WC_SIPHASH_NO_ASM) && !defined(WOLFSSL_NO_ASM) + #define WOLFSSL_NO_ASM +#endif + #include #ifdef NO_INLINE diff --git a/src/wolfcrypt/src/sm2.c b/src/wolfcrypt/src/sm2.c index b866522..18612c0 100644 --- a/src/wolfcrypt/src/sm2.c +++ b/src/wolfcrypt/src/sm2.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sm3.c b/src/wolfcrypt/src/sm3.c index b4723d8..e5e294b 100644 --- a/src/wolfcrypt/src/sm3.c +++ b/src/wolfcrypt/src/sm3.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sm4.c b/src/wolfcrypt/src/sm4.c index 4da6f0b..8001d4e 100644 --- a/src/wolfcrypt/src/sm4.c +++ b/src/wolfcrypt/src/sm4.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_arm32.c b/src/wolfcrypt/src/sp_arm32.c index a70eb35..ed50bff 100644 --- a/src/wolfcrypt/src/sp_arm32.c +++ b/src/wolfcrypt/src/sp_arm32.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -252,10 +252,11 @@ static void sp_2048_to_bin_64(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2260,10 +2261,11 @@ static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2626,10 +2628,11 @@ static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2770,10 +2773,11 @@ static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2817,9 +2821,11 @@ static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_16(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2876,11 +2882,11 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3003,9 +3009,11 @@ SP_NOINLINE static void sp_2048_mul_16(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3090,11 +3098,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3249,9 +3257,11 @@ SP_NOINLINE static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3392,11 +3402,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3608,9 +3618,10 @@ SP_NOINLINE static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4830,9 +4841,10 @@ static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5085,9 +5097,10 @@ static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5214,10 +5227,11 @@ static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5297,11 +5311,11 @@ SP_NOINLINE static void sp_2048_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5395,11 +5409,11 @@ SP_NOINLINE static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5523,11 +5537,11 @@ SP_NOINLINE static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5575,9 +5589,11 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5624,10 +5640,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5835,9 +5852,10 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_64(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_64(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6025,11 +6043,11 @@ static void sp_2048_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6077,9 +6095,11 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6126,10 +6146,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6337,9 +6358,10 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6531,9 +6553,11 @@ static void sp_2048_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6640,9 +6664,11 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8734,11 +8760,11 @@ static void sp_2048_mont_norm_32(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8787,11 +8813,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8937,11 +8963,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -9931,11 +9957,11 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -10240,11 +10266,11 @@ static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -10490,9 +10516,11 @@ SP_NOINLINE static void sp_2048_mont_sqr_32(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -10599,9 +10627,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11655,9 +11685,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_32(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11725,9 +11757,11 @@ static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_32(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11872,9 +11906,11 @@ static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, sp_digit div) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_32(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12678,11 +12714,11 @@ static void sp_2048_mont_norm_64(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12731,11 +12767,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12993,11 +13029,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14915,11 +14951,11 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15480,11 +15516,11 @@ static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15890,11 +15926,11 @@ SP_NOINLINE static void sp_2048_mont_sqr_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15941,11 +15977,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16092,9 +16128,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_64(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16162,9 +16200,11 @@ static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_64(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16413,9 +16453,11 @@ static void sp_2048_mask_64(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_64(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17693,11 +17735,11 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17746,11 +17788,11 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -18203,9 +18245,11 @@ int sp_ModExp_2048(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_2048 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_lshift_64(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_2048_lshift_64(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_2048_lshift_64(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_2048_lshift_64(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19036,10 +19080,11 @@ static void sp_3072_to_bin_96(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24545,11 +24590,11 @@ static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24600,9 +24645,11 @@ static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_24(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24673,11 +24720,11 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_24(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_24(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24818,9 +24865,11 @@ SP_NOINLINE static void sp_3072_mul_24(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24933,11 +24982,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -25120,9 +25169,11 @@ SP_NOINLINE static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -25319,11 +25370,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -25590,9 +25641,10 @@ SP_NOINLINE static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -28665,11 +28717,11 @@ static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -28756,11 +28808,11 @@ SP_NOINLINE static void sp_3072_sqr_24(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_24(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_24(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -28868,11 +28920,11 @@ SP_NOINLINE static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29024,11 +29076,11 @@ SP_NOINLINE static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29076,9 +29128,11 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29125,10 +29179,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29336,9 +29391,10 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_96(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_96(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29526,11 +29582,11 @@ static void sp_3072_mask_48(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29578,9 +29634,11 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29627,10 +29685,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -29838,9 +29897,10 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_48(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_48(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30032,9 +30092,11 @@ static void sp_3072_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30141,9 +30203,11 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33259,11 +33323,11 @@ static void sp_3072_mont_norm_48(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33312,11 +33376,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33518,11 +33582,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34976,11 +35040,11 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35413,11 +35477,11 @@ static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35743,9 +35807,11 @@ SP_NOINLINE static void sp_3072_mont_sqr_48(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35852,9 +35918,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -37420,9 +37488,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_48(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -37490,9 +37560,11 @@ static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_48(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -37637,9 +37709,11 @@ static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, sp_digit div) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_48(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -38619,11 +38693,11 @@ static void sp_3072_mont_norm_96(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -38672,11 +38746,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -39046,11 +39120,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41896,11 +41970,11 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -42717,11 +42791,11 @@ static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43287,11 +43361,11 @@ SP_NOINLINE static void sp_3072_mont_sqr_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43338,11 +43412,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43545,9 +43619,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_96(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43615,9 +43691,11 @@ static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_96(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43866,9 +43944,11 @@ static void sp_3072_mask_96(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_96(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45503,11 +45583,11 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45556,11 +45636,11 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -46069,9 +46149,11 @@ int sp_ModExp_3072(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_3072 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_lshift_96(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_3072_lshift_96(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_3072_lshift_96(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_3072_lshift_96(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47093,9 +47175,11 @@ static void sp_4096_to_bin_128(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47348,11 +47432,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47684,11 +47768,11 @@ SP_NOINLINE static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47736,9 +47820,11 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47785,10 +47871,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -47996,9 +48083,11 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_sqr_128(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_4096_sqr_128(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_4096_sqr_128(sp_digit* r, + const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -48188,9 +48277,11 @@ static void sp_4096_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -48297,9 +48388,11 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -52440,11 +52533,11 @@ static void sp_4096_mont_norm_128(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -52493,11 +52586,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -52979,11 +53072,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56757,11 +56850,11 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57834,11 +57927,11 @@ static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58564,11 +58657,11 @@ SP_NOINLINE static void sp_4096_mont_sqr_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58615,11 +58708,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58878,9 +58971,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_4096_word_128(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_4096_word_128(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58948,9 +59043,11 @@ static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_4096_word_128(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_4096_word_128(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -59199,9 +59296,11 @@ static void sp_4096_mask_128(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_4096_cmp_128(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -61188,11 +61287,11 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -61241,11 +61340,11 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -61810,9 +61909,11 @@ int sp_ModExp_4096(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_4096 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_lshift_128(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_4096_lshift_128(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_4096_lshift_128(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_4096_lshift_128(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -62834,11 +62935,13 @@ static const sp_digit p256_order[8] = { 0x00000000,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[8] = { 0xfc63254f,0xf3b9cac2,0xa7179e84,0xbce6faad,0xffffffff,0xffffffff, 0x00000000,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[8] = { @@ -62876,7 +62979,8 @@ static const sp_point_256 p256_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[8] = { 0x27d2604b,0x3bce3c3e,0xcc53b0f6,0x651d06b0,0x769886bc,0xb3ebbd55, 0xaa3a93e7,0x5ac635d8 @@ -62891,10 +62995,11 @@ static const sp_digit p256_b[8] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63105,10 +63210,11 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -65113,10 +65219,11 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -65479,10 +65586,11 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -65624,9 +65732,10 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -65795,9 +65904,10 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67017,9 +67127,10 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67272,9 +67383,10 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67403,10 +67515,11 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67454,10 +67567,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67503,11 +67617,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * m The modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static int sp_256_mod_mul_norm_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static int sp_256_mod_mul_norm_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -67956,11 +68070,12 @@ static int sp_256_point_to_ecc_point_8(const sp_point_256* p, ecc_point* pm) * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, + sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70098,11 +70213,12 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, + sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70597,11 +70713,12 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, + sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70873,11 +70990,11 @@ static SP_NOINLINE void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, + const sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72092,11 +72209,11 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, + const sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72480,11 +72597,11 @@ static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_sqr_8(sp_digit* r, + const sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72838,9 +72955,11 @@ static void sp_256_mont_inv_8(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_256_cmp_8(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_256_cmp_8(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72991,11 +73110,11 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73044,11 +73163,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73113,11 +73232,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73411,11 +73530,11 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73528,11 +73647,11 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73628,11 +73747,11 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73801,11 +73920,11 @@ static SP_NOINLINE void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74099,11 +74218,11 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74216,11 +74335,11 @@ static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_256_mont_reduce_order_8(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_256_mont_reduce_order_8( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74357,11 +74476,11 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_mont_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_mont_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74430,10 +74549,11 @@ static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_mont_dbl_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_mont_dbl_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74497,10 +74617,11 @@ static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_mont_tpl_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_mont_tpl_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74597,11 +74718,11 @@ static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, const sp_digit* m) * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_mont_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_mont_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -74668,11 +74789,11 @@ static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_mont_div2_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_mont_div2_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -78249,14 +78370,15 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_add_one_8(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_add_one_8(sp_digit* a_p) #else -static void sp_256_add_one_8(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_add_one_8(sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -78287,6 +78409,7 @@ static void sp_256_add_one_8(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -78673,9 +78796,11 @@ int sp_ecc_secret_gen_256_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -78720,9 +78845,11 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -78767,9 +78894,11 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, + sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -78876,9 +79005,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, + sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -79164,9 +79295,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_256_word_8(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -79234,9 +79367,11 @@ static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_256_word_8(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80027,10 +80162,11 @@ int sp_ecc_sign_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80077,10 +80213,11 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80119,9 +80256,11 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_rshift1_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_rshift1_8(sp_digit* r, + const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80213,10 +80352,11 @@ static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_div2_mod_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_div2_mod_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80342,9 +80482,9 @@ static const byte L_sp_256_num_bits_8_table[] = { }; #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_num_bits_8(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a_p) #else -static int sp_256_num_bits_8(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -80683,9 +80823,9 @@ static int sp_256_num_bits_8(const sp_digit* a) #else #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_num_bits_8(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a_p) #else -static int sp_256_num_bits_8(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -81217,7 +81357,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -81786,7 +81926,7 @@ static const sp_digit p384_norm_mod[12] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x00000001; +static const sp_digit p384_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -81795,11 +81935,13 @@ static const sp_digit p384_order[12] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[12] = { 0xccc52971,0xecec196a,0x48b0a77a,0x581a0db2,0xf4372ddf,0xc7634d81, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[12] = { @@ -81809,7 +81951,7 @@ static const sp_digit p384_norm_order[12] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0xe88fdc45; +static const sp_digit p384_mp_order = 0xe88fdc45; #endif /* The base point of curve P384. */ static const sp_point_384 p384_base = { @@ -81840,7 +81982,8 @@ static const sp_point_384 p384_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[12] = { 0xd3ec2aef,0x2a85c8ed,0x8a2ed19d,0xc656398d,0x5013875a,0x0314088f, 0xfe814112,0x181d9c6e,0xe3f82d19,0x988e056b,0xe23ee7e4,0xb3312fa7 @@ -81855,10 +81998,11 @@ static const sp_digit p384_b[12] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -82068,10 +82212,11 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -87578,9 +87723,10 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -87748,9 +87894,10 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -90825,10 +90972,11 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -90876,10 +91024,11 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -91231,11 +91380,11 @@ static int sp_384_point_to_ecc_point_12(const sp_point_384* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -91284,11 +91433,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -91366,11 +91515,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -91780,11 +91929,11 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -91929,11 +92078,11 @@ static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_384_mont_reduce_12(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92191,9 +92340,11 @@ static void sp_384_mont_inv_12(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_384_cmp_12(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_384_cmp_12(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92426,11 +92577,11 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_mont_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_mont_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92453,11 +92604,11 @@ static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_mont_dbl_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_mont_dbl_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92479,11 +92630,11 @@ static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_mont_tpl_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_mont_tpl_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92508,10 +92659,11 @@ static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92558,10 +92710,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92616,11 +92769,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92669,11 +92822,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92749,11 +92902,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_mont_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_mont_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -92773,9 +92926,11 @@ static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, #else #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_rshift1_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_rshift1_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_rshift1_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_rshift1_12(sp_digit* r, + const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -96412,14 +96567,15 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_add_one_12(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_add_one_12(sp_digit* a_p) #else -static void sp_384_add_one_12(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_add_one_12(sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -96456,6 +96612,7 @@ static void sp_384_add_one_12(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -96842,9 +96999,11 @@ int sp_ecc_secret_gen_384_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -96889,9 +97048,11 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -96943,9 +97104,11 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -97052,9 +97215,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -97468,9 +97633,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_384_word_12(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -97538,9 +97705,11 @@ static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_384_word_12(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -98301,11 +98470,11 @@ int sp_ecc_sign_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_div2_mod_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_div2_mod_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -98453,9 +98622,9 @@ static const byte L_sp_384_num_bits_12_table[] = { }; #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_384_num_bits_12(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a_p) #else -static int sp_384_num_bits_12(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -99025,9 +99194,9 @@ static int sp_384_num_bits_12(const sp_digit* a) #else #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_384_num_bits_12(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a_p) #else -static int sp_384_num_bits_12(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -99619,7 +99788,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -100220,7 +100389,7 @@ static const sp_digit p521_norm_mod[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x00000001; +static const sp_digit p521_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -100230,12 +100399,14 @@ static const sp_digit p521_order[17] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[17] = { 0x91386407,0xbb6fb71e,0x899c47ae,0x3bb5c9b8,0xf709a5d0,0x7fcc0148, 0xbf2f966b,0x51868783,0xfffffffa,0xffffffff,0xffffffff,0xffffffff, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[17] = { @@ -100246,7 +100417,7 @@ static const sp_digit p521_norm_order[17] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x79a995c7; +static const sp_digit p521_mp_order = 0x79a995c7; #endif /* The base point of curve P521. */ static const sp_point_521 p521_base = { @@ -100283,7 +100454,8 @@ static const sp_point_521 p521_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[17] = { 0x6b503f00,0xef451fd4,0x3d2c34f1,0x3573df88,0x3bb1bf07,0x1652c0bd, 0xec7e937b,0x56193951,0x8ef109e1,0xb8b48991,0x99b315f3,0xa2da725b, @@ -100299,10 +100471,11 @@ static const sp_digit p521_b[17] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -100515,10 +100688,11 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -111544,9 +111718,10 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -111717,9 +111892,10 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -117603,10 +117779,11 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -117660,10 +117837,11 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -117943,11 +118121,11 @@ static int sp_521_point_to_ecc_point_17(const sp_point_521* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -117996,11 +118174,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -118094,11 +118272,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -118244,11 +118422,11 @@ static SP_NOINLINE void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -118885,11 +119063,11 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -119156,11 +119334,11 @@ static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_521_mont_reduce_order_17(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_521_mont_reduce_order_17( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -119522,9 +119700,11 @@ static void sp_521_mont_inv_17(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_521_cmp_17(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_521_cmp_17(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -119812,11 +119992,11 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_mont_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_mont_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -119915,11 +120095,11 @@ static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_mont_dbl_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_mont_dbl_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -120008,11 +120188,11 @@ static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_mont_tpl_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_mont_tpl_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -120122,11 +120302,11 @@ static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_mont_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_mont_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -120220,9 +120400,11 @@ static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_rshift1_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_rshift1_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_rshift1_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_rshift1_17(sp_digit* r, + const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -124501,14 +124683,15 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_add_one_17(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_add_one_17(sp_digit* a_p) #else -static void sp_521_add_one_17(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_add_one_17(sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -124554,6 +124737,7 @@ static void sp_521_add_one_17(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -124933,9 +125117,11 @@ int sp_ecc_secret_gen_521_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_rshift_17(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_rshift_17(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125052,9 +125238,11 @@ static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_lshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_17(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_17(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125179,9 +125367,11 @@ static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_34(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_34(sp_digit* r, + const sp_digit* a, byte n) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125414,9 +125604,11 @@ static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125466,9 +125658,11 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125531,9 +125725,11 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -125640,9 +125836,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -126216,9 +126414,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_521_word_17(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -126286,9 +126486,11 @@ static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_521_word_17(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -127080,10 +127282,11 @@ int sp_ecc_sign_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -127135,10 +127338,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -127201,11 +127405,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_div2_mod_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_div2_mod_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -127388,9 +127592,9 @@ static const byte L_sp_521_num_bits_17_table[] = { }; #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_521_num_bits_17(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a_p) #else -static int sp_521_num_bits_17(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -128250,9 +128454,9 @@ static int sp_521_num_bits_17(const sp_digit* a) #else #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_521_num_bits_17(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a_p) #else -static int sp_521_num_bits_17(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -128921,7 +129125,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -129472,10 +129676,11 @@ typedef struct sp_point_1024 { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -139242,9 +139447,10 @@ static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_16(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -144487,11 +144693,11 @@ static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -144549,9 +144755,11 @@ static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -144636,11 +144844,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -144796,11 +145004,11 @@ SP_NOINLINE static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -144895,10 +145103,11 @@ SP_NOINLINE static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145106,9 +145315,10 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_sqr_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145362,9 +145572,11 @@ static const sp_point_1024 p1024_base = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145413,11 +145625,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145466,11 +145678,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145616,11 +145828,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145669,9 +145881,11 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -145778,9 +145992,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -146834,9 +147050,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_1024_word_32(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -146904,9 +147122,11 @@ static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, sp_digit div_p) +WC_OMIT_FRAME_POINTER static sp_digit div_1024_word_32(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, sp_digit div) +WC_OMIT_FRAME_POINTER static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, + sp_digit div) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -147081,9 +147301,11 @@ static void sp_1024_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_1024_cmp_32(const sp_digit* a, + const sp_digit* b) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -147819,11 +148041,11 @@ static int sp_1024_point_to_ecc_point_32(const sp_point_1024* p, ecc_point* pm) * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -148818,11 +149040,11 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -149132,11 +149354,11 @@ static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -static SP_NOINLINE void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER static SP_NOINLINE void sp_1024_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -149494,11 +149716,11 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -149680,11 +149902,11 @@ static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_dbl_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_dbl_32(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -149849,11 +150071,11 @@ static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_tpl_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_tpl_32(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -150174,11 +150396,11 @@ static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_1024_mont_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -150357,11 +150579,11 @@ static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -150410,11 +150632,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -150553,9 +150775,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_rshift1_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_rshift1_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_rshift1_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_rshift1_32(sp_digit* r, + const sp_digit* a) #endif /* WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -159628,7 +159852,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. diff --git a/src/wolfcrypt/src/sp_arm64.c b/src/wolfcrypt/src/sp_arm64.c index 3b9bc25..f34b598 100644 --- a/src/wolfcrypt/src/sp_arm64.c +++ b/src/wolfcrypt/src/sp_arm64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -93,7 +93,7 @@ static void sp_2048_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -3351,7 +3351,7 @@ SP_NOINLINE static void sp_2048_mont_reduce_16(sp_digit* a, const sp_digit* m, "adc x3, x3, xzr\n\t" "subs x4, x4, 1\n\t" "add %[a], %[a], 8\n\t" - "bne 1b\n\t" + "b.ne 1b\n\t" "# Create mask\n\t" "neg x3, x3\n\t" "mov x9, %[a]\n\t" @@ -6980,7 +6980,7 @@ static void sp_3072_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -16577,7 +16577,7 @@ static void sp_4096_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -21745,11 +21745,13 @@ static const sp_digit p256_order[4] = { 0xffffffff00000000L }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[4] = { 0xf3b9cac2fc63254fL,0xbce6faada7179e84L,0xffffffffffffffffL, 0xffffffff00000000L }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[4] = { @@ -21786,7 +21788,8 @@ static const sp_point_256 p256_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[4] = { 0x3bce3c3e27d2604bL,0x651d06b0cc53b0f6L,0xb3ebbd55769886bcL, 0x5ac635d8aa3a93e7L @@ -39614,6 +39617,7 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -39636,6 +39640,7 @@ static void sp_256_add_one_4(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -39654,7 +39659,7 @@ static void sp_256_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -42051,7 +42056,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Add two Montgomery form numbers (r = a + b % m). * * r Result of addition. @@ -42664,7 +42669,7 @@ static const sp_digit p384_norm_mod[6] = { 0x0000000000000000L,0x0000000000000000L,0x0000000000000000L }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x0000000100000001; +static const sp_digit p384_mp_mod = 0x0000000100000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -42673,11 +42678,13 @@ static const sp_digit p384_order[6] = { 0xffffffffffffffffL,0xffffffffffffffffL,0xffffffffffffffffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[6] = { 0xecec196accc52971L,0x581a0db248b0a77aL,0xc7634d81f4372ddfL, 0xffffffffffffffffL,0xffffffffffffffffL,0xffffffffffffffffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[6] = { @@ -42687,7 +42694,7 @@ static const sp_digit p384_norm_order[6] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0x6ed46089e88fdc45L; +static const sp_digit p384_mp_order = 0x6ed46089e88fdc45L; #endif #ifdef WOLFSSL_SP_SMALL /* The base point of curve P384. */ @@ -42717,7 +42724,8 @@ static const sp_point_384 p384_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[6] = { 0x2a85c8edd3ec2aefL,0xc656398d8a2ed19dL,0x0314088f5013875aL, 0x181d9c6efe814112L,0x988e056be3f82d19L,0xb3312fa7e23ee7e4L @@ -43857,7 +43865,7 @@ SP_NOINLINE static void sp_384_mont_reduce_order_6(sp_digit* a, const sp_digit* "adc x3, x3, xzr\n\t" "subs x4, x4, 1\n\t" "add %[a], %[a], 8\n\t" - "bne 1b\n\t" + "b.ne 1b\n\t" "# Create mask\n\t" "neg x3, x3\n\t" "mov x9, %[a]\n\t" @@ -66354,6 +66362,7 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -66380,6 +66389,7 @@ static void sp_384_add_one_6(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -66398,7 +66408,7 @@ static void sp_384_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -68152,7 +68162,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -68753,7 +68763,7 @@ static const sp_digit p521_norm_mod[9] = { 0x0000000000000000L,0x0000000000000000L,0x0000000000000000L }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x0000000000000001; +static const sp_digit p521_mp_mod = 0x0000000000000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -68763,12 +68773,14 @@ static const sp_digit p521_order[9] = { 0xffffffffffffffffL,0xffffffffffffffffL,0x00000000000001ffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[9] = { 0xbb6fb71e91386407L,0x3bb5c9b8899c47aeL,0x7fcc0148f709a5d0L, 0x51868783bf2f966bL,0xfffffffffffffffaL,0xffffffffffffffffL, 0xffffffffffffffffL,0xffffffffffffffffL,0x00000000000001ffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[9] = { @@ -68779,7 +68791,7 @@ static const sp_digit p521_norm_order[9] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x1d2f5ccd79a995c7L; +static const sp_digit p521_mp_order = 0x1d2f5ccd79a995c7L; #endif #ifdef WOLFSSL_SP_SMALL /* The base point of curve P521. */ @@ -68812,7 +68824,8 @@ static const sp_point_521 p521_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[9] = { 0xef451fd46b503f00L,0x3573df883d2c34f1L,0x1652c0bd3bb1bf07L, 0x56193951ec7e937bL,0xb8b489918ef109e1L,0xa2da725b99b315f3L, @@ -72225,7 +72238,7 @@ SP_NOINLINE static void sp_521_mont_reduce_9(sp_digit* a, const sp_digit* m, "# mu = a[i] * mp\n\t" "mul x9, %[mp], x13\n\t" "cmp x4, #1\n\t" - "bne L_521_mont_reduce_9_nomask\n\t" + "b.ne L_521_mont_reduce_9_nomask\n\t" "and x9, x9, #0x1ff\n\t" "L_521_mont_reduce_9_nomask:\n\t" "# a[i+0] += m[0] * mu\n\t" @@ -72299,7 +72312,7 @@ SP_NOINLINE static void sp_521_mont_reduce_9(sp_digit* a, const sp_digit* m, "adc x3, x3, xzr\n\t" "subs x4, x4, 1\n\t" "add %[a], %[a], 8\n\t" - "bne 1b\n\t" + "b.ne 1b\n\t" "extr x12, x13, x12, 9\n\t" "extr x13, x14, x13, 9\n\t" "extr x14, x15, x14, 9\n\t" @@ -111488,6 +111501,7 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -111522,6 +111536,7 @@ static void sp_521_add_one_9(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -111540,7 +111555,7 @@ static void sp_521_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" @@ -113074,7 +113089,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -115978,7 +115993,7 @@ SP_NOINLINE static void sp_1024_mont_reduce_16(sp_digit* a, const sp_digit* m, "adc x3, x3, xzr\n\t" "subs x4, x4, 1\n\t" "add %[a], %[a], 8\n\t" - "bne 1b\n\t" + "b.ne 1b\n\t" "# Create mask\n\t" "subs x11, x10, x28\n\t" "neg x3, x3\n\t" @@ -125109,7 +125124,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -125128,7 +125143,7 @@ static void sp_1024_from_bin(sp_digit* r, int size, const byte* a, int n) "sub x4, x4, 8\n\t" "subs x6, %[n], 8\n\t" "mov x7, xzr\n\t" - "blt 2f\n\t" + "b.lt 2f\n\t" /* Put in multiples of 8 bytes. */ "1:\n\t" "ldr x8, [x4], -8\n\t" diff --git a/src/wolfcrypt/src/sp_armthumb.c b/src/wolfcrypt/src/sp_armthumb.c index 4868f7f..76c85f9 100644 --- a/src/wolfcrypt/src/sp_armthumb.c +++ b/src/wolfcrypt/src/sp_armthumb.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -96690,11 +96690,13 @@ static const sp_digit p256_order[8] = { 0x00000000,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[8] = { 0xfc63254f,0xf3b9cac2,0xa7179e84,0xbce6faad,0xffffffff,0xffffffff, 0x00000000,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[8] = { @@ -96732,7 +96734,8 @@ static const sp_point_256 p256_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[8] = { 0x27d2604b,0x3bce3c3e,0xcc53b0f6,0x651d06b0,0x769886bc,0xb3ebbd55, 0xaa3a93e7,0x5ac635d8 @@ -103819,6 +103822,7 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -103904,6 +103908,7 @@ SP_NOINLINE static void sp_256_add_one_8(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -107681,7 +107686,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -108250,7 +108255,7 @@ static const sp_digit p384_norm_mod[12] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x00000001; +static const sp_digit p384_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -108259,11 +108264,13 @@ static const sp_digit p384_order[12] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[12] = { 0xccc52971,0xecec196a,0x48b0a77a,0x581a0db2,0xf4372ddf,0xc7634d81, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[12] = { @@ -108273,7 +108280,7 @@ static const sp_digit p384_norm_order[12] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0xe88fdc45; +static const sp_digit p384_mp_order = 0xe88fdc45; #endif /* The base point of curve P384. */ static const sp_point_384 p384_base = { @@ -108304,7 +108311,8 @@ static const sp_point_384 p384_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[12] = { 0xd3ec2aef,0x2a85c8ed,0x8a2ed19d,0xc656398d,0x5013875a,0x0314088f, 0xfe814112,0x181d9c6e,0xe3f82d19,0x988e056b,0xe23ee7e4,0xb3312fa7 @@ -114692,6 +114700,7 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -114813,6 +114822,7 @@ SP_NOINLINE static void sp_384_add_one_12(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -118866,7 +118876,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -119467,7 +119477,7 @@ static const sp_digit p521_norm_mod[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x00000001; +static const sp_digit p521_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -119477,12 +119487,14 @@ static const sp_digit p521_order[17] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[17] = { 0x91386407,0xbb6fb71e,0x899c47ae,0x3bb5c9b8,0xf709a5d0,0x7fcc0148, 0xbf2f966b,0x51868783,0xfffffffa,0xffffffff,0xffffffff,0xffffffff, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[17] = { @@ -119493,7 +119505,7 @@ static const sp_digit p521_norm_order[17] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x79a995c7; +static const sp_digit p521_mp_order = 0x79a995c7; #endif /* The base point of curve P521. */ static const sp_point_521 p521_base = { @@ -119530,7 +119542,8 @@ static const sp_point_521 p521_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[17] = { 0x6b503f00,0xef451fd4,0x3d2c34f1,0x3573df88,0x3bb1bf07,0x1652c0bd, 0xec7e937b,0x56193951,0x8ef109e1,0xb8b48991,0x99b315f3,0xa2da725b, @@ -128889,6 +128902,7 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. @@ -129055,6 +129069,7 @@ SP_NOINLINE static void sp_521_add_one_17(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -135798,7 +135813,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -218497,7 +218512,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. diff --git a/src/wolfcrypt/src/sp_c32.c b/src/wolfcrypt/src/sp_c32.c index 10d646a..6edd9f4 100644 --- a/src/wolfcrypt/src/sp_c32.c +++ b/src/wolfcrypt/src/sp_c32.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -19973,11 +19973,13 @@ static const sp_digit p256_order[9] = { 0x0003ffff,0x1fe00000,0x00ffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[9] = { 0x1c63254f,0x1dce5617,0x05e7a13c,0x0df55b4e,0x1ffffbce,0x1fffffff, 0x0003ffff,0x1fe00000,0x00ffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[9] = { @@ -20015,7 +20017,8 @@ static const sp_point_256 p256_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[9] = { 0x07d2604b,0x1e71e1f1,0x14ec3d8e,0x1a0d6198,0x086bc651,0x1eaabb4c, 0x0f9ecfae,0x1b154752,0x005ac635 @@ -24790,6 +24793,7 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -24801,6 +24805,7 @@ SP_NOINLINE static void sp_256_add_one_9(sp_digit* a) sp_256_norm_9(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -26467,7 +26472,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -27038,7 +27043,7 @@ static const sp_digit p384_norm_mod[15] = { 0x0000000 }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x000001; +static const sp_digit p384_mp_mod = 0x000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -27048,12 +27053,14 @@ static const sp_digit p384_order[15] = { 0x00fffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[15] = { 0x0c52971,0x3065ab3,0x277aece,0x2c922c2,0x3581a0d,0x10dcb77,0x234d81f, 0x3ffff1d,0x3ffffff,0x3ffffff,0x3ffffff,0x3ffffff,0x3ffffff,0x3ffffff, 0x00fffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[15] = { @@ -27064,7 +27071,7 @@ static const sp_digit p384_norm_order[15] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0x8fdc45; +static const sp_digit p384_mp_order = 0x8fdc45; #endif /* The base point of curve P384. */ static const sp_point_384 p384_base = { @@ -27098,7 +27105,8 @@ static const sp_point_384 p384_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[15] = { 0x3ec2aef,0x1723b74,0x119d2a8,0x23628bb,0x2c65639,0x004e1d6,0x14088f5, 0x104480c,0x06efe81,0x2460767,0x23f82d1,0x23815af,0x2e7e498,0x3e9f88f, @@ -32831,6 +32839,7 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -32842,6 +32851,7 @@ SP_NOINLINE static void sp_384_add_one_15(sp_digit* a) sp_384_norm_15(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -34523,7 +34533,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -35124,7 +35134,7 @@ static const sp_digit p521_norm_mod[21] = { 0x0000000,0x0000000,0x0000000,0x0000000,0x0000000,0x0000000,0x0000000 }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x000001; +static const sp_digit p521_mp_mod = 0x000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -35134,12 +35144,14 @@ static const sp_digit p521_order[21] = { 0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x01fffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[21] = { 0x1386407,0x1db8f48,0x1ebaedb,0x1113388,0x1bb5c9b,0x04d2e81,0x00523dc, 0x0d6ff98,0x1bf2f96,0x0c343c1,0x1fffe94,0x1ffffff,0x1ffffff,0x1ffffff, 0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x1ffffff,0x01fffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[21] = { @@ -35150,7 +35162,7 @@ static const sp_digit p521_norm_order[21] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x1a995c7; +static const sp_digit p521_mp_order = 0x1a995c7; #endif /* The base point of curve P521. */ static const sp_point_521 p521_base = { @@ -35190,7 +35202,8 @@ static const sp_point_521 p521_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[21] = { 0x1503f00,0x08fea35,0x13c7bd1,0x107a586,0x1573df8,0x18df839,0x102f4ee, 0x0f62ca5,0x1ec7e93,0x10c9ca8,0x0427855,0x13231de,0x13b8b48,0x0cd98af, @@ -40920,6 +40933,7 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -40931,6 +40945,7 @@ SP_NOINLINE static void sp_521_add_one_21(sp_digit* a) sp_521_norm_21(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -42673,7 +42688,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -54491,7 +54506,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. diff --git a/src/wolfcrypt/src/sp_c64.c b/src/wolfcrypt/src/sp_c64.c index 06dc0bd..56d8083 100644 --- a/src/wolfcrypt/src/sp_c64.c +++ b/src/wolfcrypt/src/sp_c64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -21122,11 +21122,13 @@ static const sp_digit p256_order[5] = { 0x0ffffffff0000L }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[5] = { 0x9cac2fc63254fL,0xada7179e84f3bL,0xfffffffbce6faL,0x0000fffffffffL, 0x0ffffffff0000L }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[5] = { @@ -21161,7 +21163,8 @@ static const sp_point_256 p256_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[5] = { 0xe3c3e27d2604bL,0xb0cc53b0f63bcL,0x69886bc651d06L,0x93e7b3ebbd557L, 0x05ac635d8aa3aL @@ -25686,6 +25689,7 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -25697,6 +25701,7 @@ SP_NOINLINE static void sp_256_add_one_5(sp_digit* a) sp_256_norm_5(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -27350,7 +27355,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -27919,7 +27924,7 @@ static const sp_digit p384_norm_mod[7] = { 0x00000000000000L,0x00000000000000L,0x00000000000000L }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x0000100000001; +static const sp_digit p384_mp_mod = 0x0000100000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -27928,11 +27933,13 @@ static const sp_digit p384_order[7] = { 0x7fffffffffffffL,0x7fffffffffffffL,0x3fffffffffffffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[7] = { 0x6c196accc52971L,0x1b6491614ef5d9L,0x07d0dcb77d6068L,0x7ffffffe3b1a6cL, 0x7fffffffffffffL,0x7fffffffffffffL,0x3fffffffffffffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[7] = { @@ -27942,7 +27949,7 @@ static const sp_digit p384_norm_order[7] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0x546089e88fdc45L; +static const sp_digit p384_mp_order = 0x546089e88fdc45L; #endif /* The base point of curve P384. */ static const sp_point_384 p384_base = { @@ -27970,7 +27977,8 @@ static const sp_point_384 p384_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[7] = { 0x05c8edd3ec2aefL,0x731b145da33a55L,0x3d404e1d6b1958L,0x740a089018a044L, 0x02d19181d9c6efL,0x7c9311c0ad7c7fL,0x2ccc4be9f88fb9L @@ -33152,6 +33160,7 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -33163,6 +33172,7 @@ SP_NOINLINE static void sp_384_add_one_7(sp_digit* a) sp_384_norm_7(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -34793,7 +34803,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -35394,7 +35404,7 @@ static const sp_digit p521_norm_mod[9] = { 0x000000000000000L }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x00000000000001; +static const sp_digit p521_mp_mod = 0x00000000000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -35404,12 +35414,14 @@ static const sp_digit p521_order[9] = { 0x1ffffffffffffffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[9] = { 0x36fb71e91386407L,0x1726e226711ebaeL,0x0148f709a5d03bbL,0x20efcbe59adff30L, 0x3fffffffa518687L,0x3ffffffffffffffL,0x3ffffffffffffffL,0x3ffffffffffffffL, 0x1ffffffffffffffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[9] = { @@ -35420,7 +35432,7 @@ static const sp_digit p521_norm_order[9] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x12f5ccd79a995c7L; +static const sp_digit p521_mp_order = 0x12f5ccd79a995c7L; #endif /* The base point of curve P521. */ static const sp_point_521 p521_base = { @@ -35451,7 +35463,8 @@ static const sp_point_521 p521_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[9] = { 0x3451fd46b503f00L,0x0f7e20f4b0d3c7bL,0x00bd3bb1bf07357L,0x147b1fa4dec594bL, 0x18ef109e1561939L,0x26cc57cee2d2264L,0x0540eea2da725b9L,0x2687e4a688682daL, @@ -40569,6 +40582,7 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * r A single precision integer. @@ -40580,6 +40594,7 @@ SP_NOINLINE static void sp_521_add_one_9(sp_digit* a) sp_521_norm_9(a); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -42253,7 +42268,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -53064,7 +53079,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. diff --git a/src/wolfcrypt/src/sp_cortexm.c b/src/wolfcrypt/src/sp_cortexm.c index fc756ff..bb4937e 100644 --- a/src/wolfcrypt/src/sp_cortexm.c +++ b/src/wolfcrypt/src/sp_cortexm.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -252,11 +252,11 @@ static void sp_2048_to_bin_64(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -614,11 +614,11 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -754,10 +754,11 @@ SP_NOINLINE static void sp_2048_mul_8(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -796,9 +797,11 @@ static sp_digit sp_2048_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_16(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_16(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -850,11 +853,11 @@ static sp_digit sp_2048_sub_in_place_16(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -972,9 +975,11 @@ SP_NOINLINE static void sp_2048_mul_16(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1054,11 +1059,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1208,9 +1213,11 @@ SP_NOINLINE static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1346,11 +1353,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1557,9 +1564,11 @@ SP_NOINLINE static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1807,9 +1816,11 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -1926,10 +1937,11 @@ SP_NOINLINE static void sp_2048_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2004,11 +2016,11 @@ SP_NOINLINE static void sp_2048_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2097,11 +2109,11 @@ SP_NOINLINE static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2220,11 +2232,11 @@ SP_NOINLINE static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2277,9 +2289,11 @@ static sp_digit sp_2048_add_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_64(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2331,10 +2345,11 @@ static sp_digit sp_2048_sub_in_place_64(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2457,9 +2472,10 @@ static void sp_2048_mul_64(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_64(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_64(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_64(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2596,11 +2612,11 @@ static void sp_2048_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2653,9 +2669,11 @@ static sp_digit sp_2048_add_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2707,10 +2725,11 @@ static sp_digit sp_2048_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2833,9 +2852,10 @@ static void sp_2048_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_sqr_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_2048_sqr_32(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -2976,9 +2996,11 @@ static void sp_2048_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3035,9 +3057,11 @@ static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_64(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_64(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_64(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3399,11 +3423,11 @@ static void sp_2048_mont_norm_32(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3457,11 +3481,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3603,11 +3627,11 @@ static sp_digit sp_2048_cond_sub_32(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -3917,11 +3941,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4040,11 +4064,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4264,11 +4288,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4405,9 +4429,11 @@ SP_NOINLINE static void sp_2048_mont_sqr_32(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4464,9 +4490,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_2048_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4654,11 +4682,11 @@ static void sp_2048_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_32( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4721,11 +4749,11 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_32( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -4803,9 +4831,11 @@ SP_NOINLINE static sp_digit div_2048_word_32(sp_digit d1, sp_digit d0, * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_32(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_2048_cmp_32(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_32(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5611,11 +5641,11 @@ static void sp_2048_mont_norm_64(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5669,11 +5699,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -5927,11 +5957,11 @@ static sp_digit sp_2048_cond_sub_64(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6497,11 +6527,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -6620,11 +6650,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7004,11 +7034,11 @@ SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_2048_mont_reduce_64(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_2048_mont_reduce_64( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7145,11 +7175,11 @@ SP_NOINLINE static void sp_2048_mont_sqr_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7201,11 +7231,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_sub_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_sub_64(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7347,11 +7377,11 @@ static sp_digit sp_2048_sub_64(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_64( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7414,11 +7444,11 @@ SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_64( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_2048_word_64(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -7599,9 +7629,11 @@ static void sp_2048_mask_64(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_64(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_2048_cmp_64(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_2048_cmp_64(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8881,11 +8913,11 @@ int sp_RsaPublic_2048(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -8939,11 +8971,11 @@ static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_2048_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_2048_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_2048_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -9391,9 +9423,11 @@ int sp_ModExp_2048(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_2048 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_2048_lshift_64(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_2048_lshift_64(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_2048_lshift_64(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_2048_lshift_64(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -10219,10 +10253,11 @@ static void sp_3072_to_bin_96(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11248,11 +11283,11 @@ static void sp_3072_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11298,9 +11333,11 @@ static sp_digit sp_3072_add_12(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_24(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_24(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11366,11 +11403,11 @@ static sp_digit sp_3072_sub_in_place_24(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_24(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_24(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_24(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_24(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11506,9 +11543,11 @@ SP_NOINLINE static void sp_3072_mul_24(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11616,11 +11655,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11798,9 +11837,11 @@ SP_NOINLINE static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -11992,11 +12033,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12258,9 +12299,10 @@ SP_NOINLINE static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -12960,11 +13002,11 @@ static void sp_3072_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13046,11 +13088,11 @@ SP_NOINLINE static void sp_3072_sqr_24(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_24(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_24(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_24(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_24(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13153,11 +13195,11 @@ SP_NOINLINE static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13304,11 +13346,11 @@ SP_NOINLINE static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13361,9 +13403,11 @@ static sp_digit sp_3072_add_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_96(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13415,10 +13459,11 @@ static sp_digit sp_3072_sub_in_place_96(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13541,9 +13586,10 @@ static void sp_3072_mul_96(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_96(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_96(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_96(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13680,11 +13726,11 @@ static void sp_3072_mask_48(sp_digit* r, const sp_digit* a, sp_digit m) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13737,9 +13783,11 @@ static sp_digit sp_3072_add_48(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_in_place_48(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13791,10 +13839,11 @@ static sp_digit sp_3072_sub_in_place_48(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -13917,9 +13966,10 @@ static void sp_3072_mul_48(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_sqr_48(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_48(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_3072_sqr_48(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14060,9 +14110,11 @@ static void sp_3072_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14119,9 +14171,11 @@ static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_96(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_96(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_96(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14643,11 +14697,11 @@ static void sp_3072_mont_norm_48(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14701,11 +14755,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -14903,11 +14957,11 @@ static sp_digit sp_3072_cond_sub_48(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15345,11 +15399,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15468,11 +15522,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15772,11 +15826,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_48(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_48( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15913,9 +15967,11 @@ SP_NOINLINE static void sp_3072_mont_sqr_48(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -15972,9 +16028,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_mul_d_48(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_3072_mul_d_48(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16242,11 +16300,11 @@ static void sp_3072_mul_d_48(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_48( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16309,11 +16367,11 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_48( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -16391,9 +16449,11 @@ SP_NOINLINE static sp_digit div_3072_word_48(sp_digit d1, sp_digit d0, * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_48(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_3072_cmp_48(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_48(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17375,11 +17435,11 @@ static void sp_3072_mont_norm_96(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17433,11 +17493,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -17803,11 +17863,11 @@ static sp_digit sp_3072_cond_sub_96(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -18629,11 +18689,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -18752,11 +18812,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19296,11 +19356,11 @@ SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_3072_mont_reduce_96(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_3072_mont_reduce_96( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19437,11 +19497,11 @@ SP_NOINLINE static void sp_3072_mont_sqr_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19493,11 +19553,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_sub_96(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_sub_96(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19695,11 +19755,11 @@ static sp_digit sp_3072_sub_96(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_96( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19762,11 +19822,11 @@ SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_96( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_3072_word_96(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -19947,9 +20007,11 @@ static void sp_3072_mask_96(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_96(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_3072_cmp_96(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_3072_cmp_96(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -21581,11 +21643,11 @@ int sp_RsaPublic_3072(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -21639,11 +21701,11 @@ static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_3072_cond_add_48(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_3072_cond_add_48(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_3072_cond_add_48(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -22147,9 +22209,11 @@ int sp_ModExp_3072(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_3072 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_3072_lshift_96(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_3072_lshift_96(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_3072_lshift_96(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_3072_lshift_96(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23166,9 +23230,11 @@ static void sp_4096_to_bin_128(sp_digit* r, byte* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23416,11 +23482,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23747,11 +23813,11 @@ SP_NOINLINE static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_add_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_add_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23804,9 +23870,11 @@ static sp_digit sp_4096_add_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_in_place_128(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23858,10 +23926,11 @@ static sp_digit sp_4096_sub_in_place_128(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -23984,9 +24053,11 @@ static void sp_4096_mul_128(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_sqr_128(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_4096_sqr_128(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_4096_sqr_128(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_4096_sqr_128(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24125,9 +24196,11 @@ static void sp_4096_mont_setup(const sp_digit* a, sp_digit* rho) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24184,9 +24257,11 @@ static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_mul_d_128(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_4096_mul_d_128(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_4096_mul_d_128(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24869,11 +24944,11 @@ static void sp_4096_mont_norm_128(sp_digit* r, const sp_digit* m) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -24927,11 +25002,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -25409,11 +25484,11 @@ static sp_digit sp_4096_cond_sub_128(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -26491,11 +26566,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -26614,11 +26689,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27318,11 +27393,11 @@ SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_4096_mont_reduce_128(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_4096_mont_reduce_128( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27459,11 +27534,11 @@ SP_NOINLINE static void sp_4096_mont_sqr_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27515,11 +27590,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_sub_128(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_sub_128(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27773,11 +27848,11 @@ static sp_digit sp_4096_sub_128(sp_digit* r, const sp_digit* a, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_4096_word_128( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -27840,11 +27915,11 @@ SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_4096_word_128( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_4096_word_128(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -28025,9 +28100,11 @@ static void sp_4096_mask_128(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_4096_cmp_128(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_4096_cmp_128(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_4096_cmp_128(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30011,11 +30088,11 @@ int sp_RsaPublic_4096(const byte* in, word32 inLen, const mp_int* em, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30069,11 +30146,11 @@ static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_4096_cond_add_64(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_4096_cond_add_64(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_4096_cond_add_64(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -30633,9 +30710,11 @@ int sp_ModExp_4096(const mp_int* base, const mp_int* exp, const mp_int* mod, #ifdef HAVE_FFDHE_4096 #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_4096_lshift_128(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_4096_lshift_128(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_4096_lshift_128(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_4096_lshift_128(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -31652,11 +31731,13 @@ static const sp_digit p256_order[8] = { 0x00000000,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[8] = { 0xfc63254f,0xf3b9cac2,0xa7179e84,0xbce6faad,0xffffffff,0xffffffff, 0x00000000,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[8] = { @@ -31694,7 +31775,8 @@ static const sp_point_256 p256_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[8] = { 0x27d2604b,0x3bce3c3e,0xcc53b0f6,0x651d06b0,0x769886bc,0xb3ebbd55, 0xaa3a93e7,0x5ac635d8 @@ -31709,10 +31791,11 @@ static const sp_digit p256_b[8] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_8(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -31838,11 +31921,11 @@ static void sp_256_mul_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32200,11 +32283,11 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32341,9 +32424,10 @@ SP_NOINLINE static void sp_256_mul_8(sp_digit* r, const sp_digit* a, * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32461,9 +32545,11 @@ static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32711,9 +32797,11 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_sqr_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_sqr_8(sp_digit* r_p, + const sp_digit* a_p) #else -SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32832,10 +32920,11 @@ SP_NOINLINE static void sp_256_sqr_8(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32888,10 +32977,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -32932,11 +33022,11 @@ static sp_digit sp_256_add_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * m The modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_mod_mul_norm_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static int sp_256_mod_mul_norm_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static int sp_256_mod_mul_norm_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static int sp_256_mod_mul_norm_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33380,11 +33470,12 @@ static int sp_256_point_to_ecc_point_8(const sp_point_256* p, ecc_point* pm) * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, + sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -33874,11 +33965,12 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p, + sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34145,11 +34237,11 @@ SP_NOINLINE static void sp_256_mont_mul_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, + const sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34528,11 +34620,11 @@ SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, * mp Montgomery multiplier. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, const sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sqr_8(sp_digit* r, + const sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -34876,9 +34968,11 @@ static void sp_256_mont_inv_8(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_256_cmp_8(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_256_cmp_8(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_256_cmp_8(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35032,11 +35126,11 @@ static sp_int32 sp_256_cmp_8(const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35090,11 +35184,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_cond_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_cond_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35154,11 +35248,11 @@ static sp_digit sp_256_cond_sub_8(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35276,11 +35370,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35381,11 +35475,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a_p, const sp_digit* m_p, - sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35549,11 +35643,11 @@ SP_NOINLINE static void sp_256_mont_reduce_8(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_order_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_order_8( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35671,11 +35765,11 @@ SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_order_8( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_256_mont_reduce_order_8(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_reduce_order_8( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35817,11 +35911,11 @@ static void sp_256_map_8(sp_point_256* r, const sp_point_256* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35885,11 +35979,11 @@ SP_NOINLINE static void sp_256_mont_add_8(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -35948,11 +36042,11 @@ SP_NOINLINE static void sp_256_mont_dbl_8(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -36044,11 +36138,11 @@ SP_NOINLINE static void sp_256_mont_tpl_8(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -36110,11 +36204,11 @@ SP_NOINLINE static void sp_256_mont_sub_8(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_256_mont_div2_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -39666,14 +39760,15 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_add_one_8(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_add_one_8(sp_digit* a_p) #else -static void sp_256_add_one_8(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_add_one_8(sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -39699,6 +39794,7 @@ static void sp_256_add_one_8(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -40085,9 +40181,11 @@ int sp_ecc_secret_gen_256_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40137,9 +40235,11 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_in_place_8(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40179,9 +40279,11 @@ static sp_digit sp_256_sub_in_place_8(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, + sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40238,9 +40340,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_mul_d_8(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, + sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40308,11 +40412,11 @@ static void sp_256_mul_d_8(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -40375,11 +40479,11 @@ SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_256_word_8(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41102,10 +41206,11 @@ int sp_ecc_sign_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41157,10 +41262,11 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_256_sub_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_256_sub_8(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41194,9 +41300,11 @@ static sp_digit sp_256_sub_8(sp_digit* r, const sp_digit* a, const sp_digit* b) #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_rshift1_8(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_256_rshift1_8(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_256_rshift1_8(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41245,10 +41353,11 @@ static void sp_256_rshift1_8(sp_digit* r, const sp_digit* a) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_256_div2_mod_8(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_256_div2_mod_8(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_256_div2_mod_8(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41333,9 +41442,9 @@ static void sp_256_div2_mod_8(sp_digit* r, const sp_digit* a, const sp_digit* m) } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_256_num_bits_8(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a_p) #else -static int sp_256_num_bits_8(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_256_num_bits_8(const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -41977,7 +42086,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -42546,7 +42655,7 @@ static const sp_digit p384_norm_mod[12] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x00000001; +static const sp_digit p384_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -42555,11 +42664,13 @@ static const sp_digit p384_order[12] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[12] = { 0xccc52971,0xecec196a,0x48b0a77a,0x581a0db2,0xf4372ddf,0xc7634d81, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff,0xffffffff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[12] = { @@ -42569,7 +42680,7 @@ static const sp_digit p384_norm_order[12] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0xe88fdc45; +static const sp_digit p384_mp_order = 0xe88fdc45; #endif /* The base point of curve P384. */ static const sp_point_384 p384_base = { @@ -42600,7 +42711,8 @@ static const sp_point_384 p384_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[12] = { 0xd3ec2aef,0x2a85c8ed,0x8a2ed19d,0xc656398d,0x5013875a,0x0314088f, 0xfe814112,0x181d9c6e,0xe3f82d19,0x988e056b,0xe23ee7e4,0xb3312fa7 @@ -42615,10 +42727,11 @@ static const sp_digit p384_b[12] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -42743,10 +42856,11 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_12(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43773,9 +43887,10 @@ static void sp_384_mul_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -43892,9 +44007,10 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_sqr_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -44596,10 +44712,11 @@ static void sp_384_sqr_12(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -44652,10 +44769,11 @@ static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_add_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45002,11 +45120,11 @@ static int sp_384_point_to_ecc_point_12(const sp_point_384* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45060,11 +45178,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45137,11 +45255,11 @@ static sp_digit sp_384_cond_sub_12(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_reduce_12( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45291,11 +45409,11 @@ SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_reduce_12( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_reduce_12(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45558,9 +45676,11 @@ static void sp_384_mont_inv_12(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_384_cmp_12(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_384_cmp_12(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_384_cmp_12(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_384_cmp_12(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45796,11 +45916,11 @@ static void sp_384_map_12(sp_point_384* r, const sp_point_384* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45823,11 +45943,11 @@ SP_NOINLINE static void sp_384_mont_add_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45849,11 +45969,11 @@ SP_NOINLINE static void sp_384_mont_dbl_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45878,10 +45998,11 @@ SP_NOINLINE static void sp_384_mont_tpl_12(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45933,10 +46054,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -45986,11 +46108,11 @@ static sp_digit sp_384_sub_12(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -46044,11 +46166,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_cond_add_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_cond_add_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -46119,11 +46241,11 @@ static sp_digit sp_384_cond_add_12(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -46143,9 +46265,11 @@ SP_NOINLINE static void sp_384_mont_sub_12(sp_digit* r, const sp_digit* a, #else #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_rshift1_12(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_rshift1_12(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_384_rshift1_12(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_rshift1_12(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -49777,14 +49901,15 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_add_one_12(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_384_add_one_12(sp_digit* a_p) #else -static void sp_384_add_one_12(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_384_add_one_12(sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -49816,6 +49941,7 @@ static void sp_384_add_one_12(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -50202,9 +50328,11 @@ int sp_ecc_secret_gen_384_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50254,9 +50382,11 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_384_sub_in_place_12(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50303,9 +50433,11 @@ static sp_digit sp_384_sub_in_place_12(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50362,9 +50494,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_mul_d_12(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_384_mul_d_12(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50452,11 +50586,11 @@ static void sp_384_mul_d_12(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -50519,11 +50653,11 @@ SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_384_word_12(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -51216,11 +51350,11 @@ int sp_ecc_sign_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_384_div2_mod_12(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_384_div2_mod_12(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_384_div2_mod_12(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -51343,9 +51477,9 @@ static void sp_384_div2_mod_12(sp_digit* r, const sp_digit* a, } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_384_num_bits_12(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a_p) #else -static int sp_384_num_bits_12(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_384_num_bits_12(const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -52091,7 +52225,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -52692,7 +52826,7 @@ static const sp_digit p521_norm_mod[17] = { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000 }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x00000001; +static const sp_digit p521_mp_mod = 0x00000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -52702,12 +52836,14 @@ static const sp_digit p521_order[17] = { 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[17] = { 0x91386407,0xbb6fb71e,0x899c47ae,0x3bb5c9b8,0xf709a5d0,0x7fcc0148, 0xbf2f966b,0x51868783,0xfffffffa,0xffffffff,0xffffffff,0xffffffff, 0xffffffff,0xffffffff,0xffffffff,0xffffffff,0x000001ff }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[17] = { @@ -52718,7 +52854,7 @@ static const sp_digit p521_norm_order[17] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x79a995c7; +static const sp_digit p521_mp_order = 0x79a995c7; #endif /* The base point of curve P521. */ static const sp_point_521 p521_base = { @@ -52755,7 +52891,8 @@ static const sp_point_521 p521_base = { /* infinity */ 0 }; -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[17] = { 0x6b503f00,0xef451fd4,0x3d2c34f1,0x3573df88,0x3bb1bf07,0x1652c0bd, 0xec7e937b,0x56193951,0x8ef109e1,0xb8b48991,0x99b315f3,0xa2da725b, @@ -52771,10 +52908,11 @@ static const sp_digit p521_b[17] = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -52902,10 +53040,11 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_17(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -54946,9 +55085,10 @@ static void sp_521_mul_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -55068,9 +55208,10 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_sqr_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56356,10 +56497,11 @@ static void sp_521_sqr_17(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56418,10 +56560,11 @@ static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_add_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56696,11 +56839,11 @@ static int sp_521_point_to_ecc_point_17(const sp_point_521* p, ecc_point* pm) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56754,11 +56897,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_cond_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_cond_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56847,11 +56990,11 @@ static sp_digit sp_521_cond_sub_17(sp_digit* r, const sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, + const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -56987,11 +57130,11 @@ SP_NOINLINE static void sp_521_mont_reduce_17(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_order_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_order_17( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57268,11 +57411,11 @@ SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_order_17( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_521_mont_reduce_order_17(sp_digit* a, - const sp_digit* m, sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_reduce_order_17( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57644,9 +57787,11 @@ static void sp_521_mont_inv_17(sp_digit* r, const sp_digit* a, sp_digit* td) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_521_cmp_17(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_521_cmp_17(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_521_cmp_17(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_521_cmp_17(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -57937,11 +58082,11 @@ static void sp_521_map_17(sp_point_521* r, const sp_point_521* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58030,11 +58175,11 @@ SP_NOINLINE static void sp_521_mont_add_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58113,11 +58258,11 @@ SP_NOINLINE static void sp_521_mont_dbl_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58217,11 +58362,11 @@ SP_NOINLINE static void sp_521_mont_tpl_17(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -58305,9 +58450,11 @@ SP_NOINLINE static void sp_521_mont_sub_17(sp_digit* r, const sp_digit* a, } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_rshift1_17(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_rshift1_17(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_521_rshift1_17(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_rshift1_17(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -62581,14 +62728,15 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG /* Add 1 to a. (a = a + 1) * * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_add_one_17(sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_521_add_one_17(sp_digit* a_p) #else -static void sp_521_add_one_17(sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_521_add_one_17(sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -62629,6 +62777,7 @@ static void sp_521_add_one_17(sp_digit* a) ); } +#endif /* Read big endian unsigned byte array into r. * * r A single precision integer. @@ -63008,9 +63157,11 @@ int sp_ecc_secret_gen_521_nb(sp_ecc_ctx_t* sp_ctx, const mp_int* priv, #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_rshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_rshift_17(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_rshift_17(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63113,9 +63264,11 @@ static void sp_521_rshift_17(sp_digit* r, const sp_digit* a, byte n) #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_lshift_17(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_17(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_17(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63235,9 +63388,11 @@ static void sp_521_lshift_17(sp_digit* r, const sp_digit* a, byte n) } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_lshift_34(sp_digit* r_p, const sp_digit* a_p, byte n_p) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_34(sp_digit* r_p, + const sp_digit* a_p, byte n_p) #else -static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) +WC_OMIT_FRAME_POINTER static void sp_521_lshift_34(sp_digit* r, + const sp_digit* a, byte n) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63465,9 +63620,11 @@ static void sp_521_lshift_34(sp_digit* r, const sp_digit* a, byte n) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63522,9 +63679,11 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_in_place_17(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63582,9 +63741,11 @@ static sp_digit sp_521_sub_in_place_17(sp_digit* a, const sp_digit* b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63641,9 +63802,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_mul_d_17(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_521_mul_d_17(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63756,11 +63919,11 @@ static void sp_521_mul_d_17(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -63823,11 +63986,11 @@ SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1_p, + sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_521_word_17(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -64551,10 +64714,11 @@ int sp_ecc_sign_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, word32 hashLen, W * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -64611,10 +64775,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_521_sub_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_521_sub_17(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -64672,11 +64837,11 @@ static sp_digit sp_521_sub_17(sp_digit* r, const sp_digit* a, const sp_digit* b) * m Modulus. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_521_div2_mod_17(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER static void sp_521_div2_mod_17(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER static void sp_521_div2_mod_17(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -64834,9 +64999,9 @@ static void sp_521_div2_mod_17(sp_digit* r, const sp_digit* a, } #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static int sp_521_num_bits_17(const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a_p) #else -static int sp_521_num_bits_17(const sp_digit* a) +WC_OMIT_FRAME_POINTER static int sp_521_num_bits_17(const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -65719,7 +65884,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -66270,10 +66435,11 @@ typedef struct sp_point_1024 { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -68080,9 +68246,10 @@ static void sp_1024_mul_16(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_sqr_16(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_16(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69234,11 +69401,11 @@ static void sp_1024_sqr_16(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69291,9 +69458,11 @@ static sp_digit sp_1024_add_16(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69373,11 +69542,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69528,11 +69697,11 @@ SP_NOINLINE static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_16(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_16(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_sub_16(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_16(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69622,10 +69791,11 @@ SP_NOINLINE static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69748,9 +69918,10 @@ static void sp_1024_mul_32(sp_digit* r, const sp_digit* a, const sp_digit* b) * a A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_sqr_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_sqr_32(sp_digit* r, const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -69953,9 +70124,11 @@ static const sp_point_1024 p1024_base = { * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a_p, + const sp_digit* b_p) #else -static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_sub_in_place_32(sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70009,11 +70182,11 @@ static sp_digit sp_1024_sub_in_place_32(sp_digit* a, const sp_digit* b) * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70067,11 +70240,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70212,11 +70385,11 @@ static sp_digit sp_1024_cond_sub_32(sp_digit* r, const sp_digit* a, * b A single precision integer. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p) #else -static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70270,9 +70443,11 @@ static sp_digit sp_1024_add_32(sp_digit* r, const sp_digit* a, * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70329,9 +70504,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * b A single precision digit. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_mul_d_32(sp_digit* r_p, const sp_digit* a_p, sp_digit b_p) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r_p, + const sp_digit* a_p, sp_digit b_p) #else -static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) +WC_OMIT_FRAME_POINTER static void sp_1024_mul_d_32(sp_digit* r, + const sp_digit* a, sp_digit b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70519,11 +70696,11 @@ static void sp_1024_mul_d_32(sp_digit* r, const sp_digit* a, sp_digit b) * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_1024_word_32( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70586,11 +70763,11 @@ SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, * Note that this is an approximate div. It may give an answer 1 larger. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1_p, sp_digit d0_p, - sp_digit div_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_1024_word_32( + sp_digit d1_p, sp_digit d0_p, sp_digit div_p) #else -SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, sp_digit d0, - sp_digit div) +WC_OMIT_FRAME_POINTER SP_NOINLINE static sp_digit div_1024_word_32(sp_digit d1, + sp_digit d0, sp_digit div) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -70698,9 +70875,11 @@ static void sp_1024_mask_32(sp_digit* r, const sp_digit* a, sp_digit m) * respectively. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, const sp_digit* b_p) +WC_OMIT_FRAME_POINTER static sp_int32 sp_1024_cmp_32(const sp_digit* a_p, + const sp_digit* b_p) #else -static sp_int32 sp_1024_cmp_32(const sp_digit* a, const sp_digit* b) +WC_OMIT_FRAME_POINTER static sp_int32 sp_1024_cmp_32(const sp_digit* a, + const sp_digit* b) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -71438,11 +71617,11 @@ static int sp_1024_point_to_ecc_point_32(const sp_point_1024* p, ecc_point* pm) * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -71757,11 +71936,11 @@ SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, * mp The digit representing the negative inverse of m mod 2^n. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a_p, - const sp_digit* m_p, sp_digit mp_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_reduce_32( + sp_digit* a_p, const sp_digit* m_p, sp_digit mp_p) #else -SP_NOINLINE static void sp_1024_mont_reduce_32(sp_digit* a, const sp_digit* m, - sp_digit mp) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_reduce_32( + sp_digit* a, const sp_digit* m, sp_digit mp) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72124,11 +72303,11 @@ static void sp_1024_map_32(sp_point_1024* r, const sp_point_1024* p, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72305,11 +72484,11 @@ SP_NOINLINE static void sp_1024_mont_add_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72469,11 +72648,11 @@ SP_NOINLINE static void sp_1024_mont_dbl_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, - const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, + const sp_digit* a, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72789,11 +72968,11 @@ SP_NOINLINE static void sp_1024_mont_tpl_32(sp_digit* r, const sp_digit* a, * m Modulus (prime). */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, const sp_digit* m_p) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, const sp_digit* m_p) #else -SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, const sp_digit* m) +WC_OMIT_FRAME_POINTER SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, const sp_digit* m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -72967,11 +73146,11 @@ SP_NOINLINE static void sp_1024_mont_sub_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73025,11 +73204,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, * m Mask value to apply. */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static sp_digit sp_1024_cond_add_32(sp_digit* r_p, const sp_digit* a_p, - const sp_digit* b_p, sp_digit m_p) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r_p, + const sp_digit* a_p, const sp_digit* b_p, sp_digit m_p) #else -static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, - const sp_digit* b, sp_digit m) +WC_OMIT_FRAME_POINTER static sp_digit sp_1024_cond_add_32(sp_digit* r, + const sp_digit* a, const sp_digit* b, sp_digit m) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -73163,9 +73342,11 @@ static sp_digit sp_1024_cond_add_32(sp_digit* r, const sp_digit* a, #endif /* WOLFSSL_SP_SMALL */ #ifndef WOLFSSL_NO_VAR_ASSIGN_REG -static void sp_1024_rshift1_32(sp_digit* r_p, const sp_digit* a_p) +WC_OMIT_FRAME_POINTER static void sp_1024_rshift1_32(sp_digit* r_p, + const sp_digit* a_p) #else -static void sp_1024_rshift1_32(sp_digit* r, const sp_digit* a) +WC_OMIT_FRAME_POINTER static void sp_1024_rshift1_32(sp_digit* r, + const sp_digit* a) #endif /* !WOLFSSL_NO_VAR_ASSIGN_REG */ { #ifndef WOLFSSL_NO_VAR_ASSIGN_REG @@ -82233,7 +82414,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, } #endif /* WOLFSSL_SP_SMALL */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Read big endian unsigned byte array into r. * * r A single precision integer. diff --git a/src/wolfcrypt/src/sp_dsp32.c b/src/wolfcrypt/src/sp_dsp32.c index f218860..b47c57f 100644 --- a/src/wolfcrypt/src/sp_dsp32.c +++ b/src/wolfcrypt/src/sp_dsp32.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_int.c b/src/wolfcrypt/src/sp_int.c index 1769840..ebccf39 100644 --- a/src/wolfcrypt/src/sp_int.c +++ b/src/wolfcrypt/src/sp_int.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -31,19 +31,6 @@ This library provides single precision (SP) integer math functions. #if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) -#if (!defined(WOLFSSL_SMALL_STACK) && !defined(SP_ALLOC)) || \ - defined(WOLFSSL_SP_NO_MALLOC) -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) -PRAGMA_GCC_DIAG_PUSH -/* We are statically declaring a variable smaller than sp_int. - * We track available memory in the 'size' field. - * Disable warnings of sp_int being partly outside array bounds of variable. - */ -PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") -#endif -#endif - #ifdef NO_INLINE #include #else @@ -112,6 +99,15 @@ PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") #include +#ifdef WOLFSSL_SP_DYN_STACK +/* We are statically declaring a variable smaller than sp_int. + * We track available memory in the 'size' field. + * Disable warnings of sp_int being partly outside array bounds of variable. + */ + PRAGMA_GCC_DIAG_PUSH + PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") +#endif + #if defined(WOLFSSL_LINUXKM) && !defined(WOLFSSL_SP_ASM) /* force off unneeded vector register save/restore. */ #undef SAVE_VECTOR_REGISTERS @@ -127,11 +123,10 @@ PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") #define DECL_SP_INT(n, s) \ sp_int* n = NULL #else - #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) + #ifdef WOLFSSL_SP_DYN_STACK /* Declare a variable on the stack with the required data size. */ - #define DECL_SP_INT(n, s) \ - byte n##d[MP_INT_SIZEOF(s)]; \ + #define DECL_SP_INT(n, s) \ + sp_int_digit n##d[MP_INT_SIZEOF_DIGITS(s)]; \ sp_int* (n) = (sp_int*)n##d #else /* Declare a variable on the stack. */ @@ -218,11 +213,10 @@ PRAGMA_GCC("GCC diagnostic ignored \"-Warray-bounds\"") /* Declare a variable that will be assigned a value on XMALLOC. */ #define DECL_SP_INT_ARRAY(n, s, c) \ DECL_DYN_SP_INT_ARRAY(n, s, c) -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) /* Declare a variable on the stack with the required data size. */ - #define DECL_SP_INT_ARRAY(n, s, c) \ - byte n##d[MP_INT_SIZEOF(s) * (c)]; \ + #define DECL_SP_INT_ARRAY(n, s, c) \ + sp_int_digit n##d[MP_INT_SIZEOF_DIGITS(s) * (c)]; \ sp_int* (n)[c] = { NULL, } #else /* Declare a variable on the stack. */ @@ -264,8 +258,7 @@ while (0) !defined(WOLFSSL_SP_NO_MALLOC) #define ALLOC_SP_INT_ARRAY(n, s, c, err, h) \ ALLOC_DYN_SP_INT_ARRAY(n, s, c, err, h) -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) /* Data declared on stack that supports multiple sp_ints of the * required size. Use pointers into data to make up array and set sizes. */ @@ -5109,7 +5102,7 @@ static void _sp_init_size(sp_int* a, unsigned int size) #endif _sp_zero((sp_int*)am); - a->size = (sp_size_t)size; + am->size = (sp_size_t)size; } /* Initialize the multi-precision number to be zero with a given max size. @@ -5248,7 +5241,7 @@ int sp_grow(sp_int* a, int l) #endif /* (!NO_RSA && !WOLFSSL_RSA_VERIFY_ONLY) || !NO_DH || HAVE_ECC */ #if (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ - defined(HAVE_ECC) + defined(HAVE_ECC) || defined(WOLFSSL_PUBLIC_MP) /* Set the multi-precision number to zero. * * @param [out] a SP integer to set to zero. @@ -5329,10 +5322,10 @@ static void _sp_copy(const sp_int* a, sp_int* r) XMEMCPY(r->dp, a->dp, a->used * (word32)SP_WORD_SIZEOF); } /* Set number of used words in result. */ - r->used = a->used; + r->used = a->used;/* // NOLINT(clang-analyzer-core.uninitialized.Assign) */ #ifdef WOLFSSL_SP_INT_NEGATIVE /* Set sign of result. */ - r->sign = a->sign; + r->sign = a->sign;/* // NOLINT(clang-analyzer-core.uninitialized.Assign) */ #endif } @@ -5833,7 +5826,7 @@ int sp_cmp_ct(const sp_int* a, const sp_int* b, unsigned int n) #if (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY)) || \ ((defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_SM2)) && \ - defined(HAVE_ECC)) || defined(OPENSSL_EXTRA) + defined(HAVE_ECC)) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_PUBLIC_MP) /* Check if a bit is set * * When a is NULL, result is 0. @@ -7607,7 +7600,7 @@ static void _sp_add_off(const sp_int* a, const sp_int* b, sp_int* r, int o) * @param [in] o Number of digits to offset b. */ static void _sp_sub_off(const sp_int* a, const sp_int* b, sp_int* r, - unsigned int o) + sp_size_t o) { sp_size_t i = 0; sp_size_t j; @@ -7625,7 +7618,7 @@ static void _sp_sub_off(const sp_int* a, const sp_int* b, sp_int* r, } } else { - i = (sp_size_t)o; + i = o; } /* Index to add at is the offset now. */ @@ -7909,28 +7902,30 @@ static int _sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, unsigned int used = ((a->used >= m->used) ? ((a->used >= b->used) ? (a->used + 1U) : (b->used + 1U)) : ((b->used >= m->used)) ? (b->used + 1U) : (m->used + 1U)); - DECL_SP_INT_ARRAY(t, used, 2); + DECL_SP_INT(t0, used); + DECL_SP_INT(t1, used); - ALLOC_SP_INT_ARRAY(t, used, 2, err, NULL); + ALLOC_SP_INT_SIZE(t0, used, err, NULL); + ALLOC_SP_INT_SIZE(t1, used, err, NULL); if (err == MP_OKAY) { /* Reduce a to less than m. */ if (_sp_cmp(a, m) != MP_LT) { - err = sp_mod(a, m, t[0]); - a = t[0]; + err = sp_mod(a, m, t0); + a = t0; } } if (err == MP_OKAY) { /* Reduce b to less than m. */ if (_sp_cmp(b, m) != MP_LT) { - err = sp_mod(b, m, t[1]); - b = t[1]; + err = sp_mod(b, m, t1); + b = t1; } } if (err == MP_OKAY) { /* Add m to a if a smaller than b. */ if (_sp_cmp(a, b) == MP_LT) { - err = sp_add(a, m, t[0]); - a = t[0]; + err = sp_add(a, m, t0); + a = t0; } } if (err == MP_OKAY) { @@ -7938,7 +7933,8 @@ static int _sp_submod(const sp_int* a, const sp_int* b, const sp_int* m, err = sp_sub(a, b, r); } - FREE_SP_INT_ARRAY(t, NULL); + FREE_SP_INT(t0, NULL); + FREE_SP_INT(t1, NULL); #else /* WOLFSSL_SP_INT_NEGATIVE */ sp_size_t used = ((a->used >= b->used) ? a->used + 1 : b->used + 1); DECL_SP_INT(t, used); @@ -8029,8 +8025,8 @@ static void sp_clamp_ct(sp_int* a) (sp_int_digit)((sp_int_sdigit)(negVal & minusOne) >> (SP_WORD_SIZE - 1)); #else - sp_int_digit zeroMask = - (sp_int_digit)((((sp_int_sword)a->dp[i]) - 1) >> SP_WORD_SIZE); + sp_size_t zeroMask = + (sp_size_t)((((sp_int_sword)a->dp[i]) - 1) >> SP_WORD_SIZE); #endif mask &= (sp_size_t)zeroMask; used = (sp_size_t)(used + mask); @@ -9172,8 +9168,7 @@ static int _sp_mul_nxn(const sp_int* a, const sp_int* b, sp_int* r) unsigned int k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) sp_int_digit t[a->used]; #else sp_int_digit t[SP_INT_DIGITS / 2]; @@ -9249,8 +9244,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) sp_int_digit t[a->used + b->used]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -9326,8 +9320,7 @@ static int _sp_mul(const sp_int* a, const sp_int* b, sp_int* r) sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) sp_int_digit t[a->used + b->used]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -14876,8 +14869,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) sp_int_digit t[((a->used + 1) / 2) * 2 + 1]; #else sp_int_digit t[(SP_INT_DIGITS + 1) / 2]; @@ -14991,8 +14983,7 @@ static int _sp_sqr(const sp_int* a, sp_int* r) sp_size_t k; #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SP_NO_MALLOC) sp_int_digit* t = NULL; -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#elif defined(WOLFSSL_SP_DYN_STACK) sp_int_digit t[a->used * 2]; #else sp_int_digit t[SP_INT_DIGITS]; @@ -19280,18 +19271,15 @@ static int _sp_prime_trials(const sp_int* a, int trials, int* result) { int err = MP_OKAY; int i; - sp_int* n1; - sp_int* r; - DECL_SP_INT_ARRAY(t, a->used + 1, 2); + DECL_SP_INT(n1, a->used + 1); + DECL_SP_INT(r, a->used + 1); DECL_SP_INT(b, a->used * 2 + 1); - ALLOC_SP_INT_ARRAY(t, a->used + 1, 2, err, NULL); + ALLOC_SP_INT(n1, a->used + 1, err, NULL); + ALLOC_SP_INT(r, a->used + 1, err, NULL); /* Allocate number that will hold modular exponentiation result. */ ALLOC_SP_INT(b, a->used * 2 + 1, err, NULL); if (err == MP_OKAY) { - n1 = t[0]; - r = t[1]; - _sp_init_size(n1, a->used + 1U); _sp_init_size(r, a->used + 1U); _sp_init_size(b, (sp_size_t)(a->used * 2U + 1U)); @@ -19314,7 +19302,8 @@ static int _sp_prime_trials(const sp_int* a, int trials, int* result) /* Free allocated temporary. */ FREE_SP_INT(b, NULL); - FREE_SP_INT_ARRAY(t, NULL); + FREE_SP_INT(r, NULL); + FREE_SP_INT(n1, NULL); return err; } @@ -19888,12 +19877,8 @@ void sp_memzero_check(sp_int* sp) } #endif /* WOLFSSL_CHECK_MEM_ZERO */ -#if (!defined(WOLFSSL_SMALL_STACK) && !defined(SP_ALLOC)) || \ - defined(WOLFSSL_SP_NO_MALLOC) -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) -PRAGMA_GCC_DIAG_POP -#endif +#ifdef WOLFSSL_SP_DYN_STACK + PRAGMA_GCC_DIAG_POP #endif #endif /* WOLFSSL_SP_MATH || WOLFSSL_SP_MATH_ALL */ diff --git a/src/wolfcrypt/src/sp_sm2_arm32.c b/src/wolfcrypt/src/sp_sm2_arm32.c index 0a458bd..aad6a42 100644 --- a/src/wolfcrypt/src/sp_sm2_arm32.c +++ b/src/wolfcrypt/src/sp_sm2_arm32.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_arm64.c b/src/wolfcrypt/src/sp_sm2_arm64.c index db67898..772a7df 100644 --- a/src/wolfcrypt/src/sp_sm2_arm64.c +++ b/src/wolfcrypt/src/sp_sm2_arm64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_armthumb.c b/src/wolfcrypt/src/sp_sm2_armthumb.c index 21e49dc..d26a45f 100644 --- a/src/wolfcrypt/src/sp_sm2_armthumb.c +++ b/src/wolfcrypt/src/sp_sm2_armthumb.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_c32.c b/src/wolfcrypt/src/sp_sm2_c32.c index 5aae8d2..4106669 100644 --- a/src/wolfcrypt/src/sp_sm2_c32.c +++ b/src/wolfcrypt/src/sp_sm2_c32.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_c64.c b/src/wolfcrypt/src/sp_sm2_c64.c index d848104..4dafb8e 100644 --- a/src/wolfcrypt/src/sp_sm2_c64.c +++ b/src/wolfcrypt/src/sp_sm2_c64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_cortexm.c b/src/wolfcrypt/src/sp_sm2_cortexm.c index 4ea4b8f..722f20a 100644 --- a/src/wolfcrypt/src/sp_sm2_cortexm.c +++ b/src/wolfcrypt/src/sp_sm2_cortexm.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_sm2_x86_64.c b/src/wolfcrypt/src/sp_sm2_x86_64.c index fd6f0d2..2ba3cb0 100644 --- a/src/wolfcrypt/src/sp_sm2_x86_64.c +++ b/src/wolfcrypt/src/sp_sm2_x86_64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/sp_x86_64.c b/src/wolfcrypt/src/sp_x86_64.c index 298ec47..f8bf541 100644 --- a/src/wolfcrypt/src/sp_x86_64.c +++ b/src/wolfcrypt/src/sp_x86_64.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -8021,11 +8021,13 @@ static const sp_digit p256_order[4] = { 0xffffffff00000000L }; #endif +#ifndef WC_NO_RNG /* The order of the curve P256 minus 2. */ static const sp_digit p256_order2[4] = { 0xf3b9cac2fc63254fL,0xbce6faada7179e84L,0xffffffffffffffffL, 0xffffffff00000000L }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P256. */ static const sp_digit p256_norm_order[4] = { @@ -8062,7 +8064,8 @@ static const sp_point_256 p256_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p256_b[4] = { 0x3bce3c3e27d2604bL,0x651d06b0cc53b0f6L,0xb3ebbd55769886bcL, 0x5ac635d8aa3a93e7L @@ -24510,6 +24513,7 @@ int sp_ecc_mulmod_base_add_256(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG #ifdef __cplusplus extern "C" { #endif @@ -24517,6 +24521,7 @@ extern void sp_256_add_one_4(sp_digit* a); #ifdef __cplusplus } #endif +#endif #ifdef __cplusplus extern "C" { #endif @@ -26433,7 +26438,7 @@ int sp_ecc_verify_256_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -27098,7 +27103,7 @@ static const sp_digit p384_norm_mod[6] = { 0x0000000000000000L,0x0000000000000000L,0x0000000000000000L }; /* The Montgomery multiplier for modulus of the curve P384. */ -static sp_digit p384_mp_mod = 0x0000000100000001; +static const sp_digit p384_mp_mod = 0x0000000100000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P384. */ @@ -27107,11 +27112,13 @@ static const sp_digit p384_order[6] = { 0xffffffffffffffffL,0xffffffffffffffffL,0xffffffffffffffffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P384 minus 2. */ static const sp_digit p384_order2[6] = { 0xecec196accc52971L,0x581a0db248b0a77aL,0xc7634d81f4372ddfL, 0xffffffffffffffffL,0xffffffffffffffffL,0xffffffffffffffffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P384. */ static const sp_digit p384_norm_order[6] = { @@ -27121,7 +27128,7 @@ static const sp_digit p384_norm_order[6] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P384. */ -static sp_digit p384_mp_order = 0x6ed46089e88fdc45L; +static const sp_digit p384_mp_order = 0x6ed46089e88fdc45L; #endif #ifdef WOLFSSL_SP_SMALL /* The base point of curve P384. */ @@ -27151,7 +27158,8 @@ static const sp_point_384 p384_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p384_b[6] = { 0x2a85c8edd3ec2aefL,0xc656398d8a2ed19dL,0x0314088f5013875aL, 0x181d9c6efe814112L,0x988e056be3f82d19L,0xb3312fa7e23ee7e4L @@ -49544,6 +49552,7 @@ int sp_ecc_mulmod_base_add_384(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG #ifdef __cplusplus extern "C" { #endif @@ -49551,6 +49560,7 @@ extern void sp_384_add_one_6(sp_digit* a); #ifdef __cplusplus } #endif +#endif #ifdef __cplusplus extern "C" { #endif @@ -51408,7 +51418,7 @@ int sp_ecc_verify_384_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -52130,7 +52140,7 @@ static const sp_digit p521_norm_mod[9] = { 0x0000000000000000L,0x0000000000000000L,0x0000000000000000L }; /* The Montgomery multiplier for modulus of the curve P521. */ -static sp_digit p521_mp_mod = 0x0000000000000001; +static const sp_digit p521_mp_mod = 0x0000000000000001; #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) /* The order of the curve P521. */ @@ -52140,12 +52150,14 @@ static const sp_digit p521_order[9] = { 0xffffffffffffffffL,0xffffffffffffffffL,0x00000000000001ffL }; #endif +#ifndef WC_NO_RNG /* The order of the curve P521 minus 2. */ static const sp_digit p521_order2[9] = { 0xbb6fb71e91386407L,0x3bb5c9b8899c47aeL,0x7fcc0148f709a5d0L, 0x51868783bf2f966bL,0xfffffffffffffffaL,0xffffffffffffffffL, 0xffffffffffffffffL,0xffffffffffffffffL,0x00000000000001ffL }; +#endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery normalizer for order of the curve P521. */ static const sp_digit p521_norm_order[9] = { @@ -52156,7 +52168,7 @@ static const sp_digit p521_norm_order[9] = { #endif #if defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY) /* The Montgomery multiplier for order of the curve P521. */ -static sp_digit p521_mp_order = 0x1d2f5ccd79a995c7L; +static const sp_digit p521_mp_order = 0x1d2f5ccd79a995c7L; #endif #ifdef WOLFSSL_SP_SMALL /* The base point of curve P521. */ @@ -52189,7 +52201,8 @@ static const sp_point_521 p521_base = { 0 }; #endif /* WOLFSSL_SP_SMALL */ -#if defined(HAVE_ECC_CHECK_KEY) || defined(HAVE_COMP_KEY) +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) || \ + defined(HAVE_COMP_KEY) static const sp_digit p521_b[9] = { 0xef451fd46b503f00L,0x3573df883d2c34f1L,0x1652c0bd3bb1bf07L, 0x56193951ec7e937bL,0xb8b489918ef109e1L,0xa2da725b99b315f3L, @@ -90637,6 +90650,7 @@ int sp_ecc_mulmod_base_add_521(const mp_int* km, const ecc_point* am, #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || defined(HAVE_ECC_SIGN) || \ defined(HAVE_ECC_VERIFY) #endif /* WOLFSSL_VALIDATE_ECC_KEYGEN | HAVE_ECC_SIGN | HAVE_ECC_VERIFY */ +#ifndef WC_NO_RNG #ifdef __cplusplus extern "C" { #endif @@ -90644,6 +90658,7 @@ extern void sp_521_add_one_9(sp_digit* a); #ifdef __cplusplus } #endif +#endif #ifdef __cplusplus extern "C" { #endif @@ -92575,7 +92590,7 @@ int sp_ecc_verify_521_nb(sp_ecc_ctx_t* sp_ctx, const byte* hash, #endif /* WOLFSSL_SP_NONBLOCK */ #endif /* HAVE_ECC_VERIFY */ -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) /* Check that the x and y ordinates are a valid point on the curve. * * point EC point. @@ -105446,7 +105461,7 @@ int sp_Pairing_precomp_1024(const ecc_point* pm, const ecc_point* qm, mp_int* re return err; } -#ifdef HAVE_ECC_CHECK_KEY +#if defined(HAVE_ECC_CHECK_KEY) || !defined(NO_ECC_CHECK_PUBKEY_ORDER) #ifdef __cplusplus extern "C" { #endif diff --git a/src/wolfcrypt/src/sphincs.c b/src/wolfcrypt/src/sphincs.c index 94be4ac..c8510b4 100644 --- a/src/wolfcrypt/src/sphincs.c +++ b/src/wolfcrypt/src/sphincs.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/srp.c b/src/wolfcrypt/src/srp.c index c7f5986..5ea5a25 100644 --- a/src/wolfcrypt/src/srp.c +++ b/src/wolfcrypt/src/srp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/tfm.c b/src/wolfcrypt/src/tfm.c index 5bd7328..1f07d8e 100644 --- a/src/wolfcrypt/src/tfm.c +++ b/src/wolfcrypt/src/tfm.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -4198,6 +4198,58 @@ int fp_to_unsigned_bin(fp_int *a, unsigned char *b) return FP_OKAY; } +int fp_to_unsigned_bin_len_ct(fp_int *a, unsigned char *out, int outSz) +{ + int err = MP_OKAY; + + /* Validate parameters. */ + if ((a == NULL) || (out == NULL) || (outSz < 0)) { + err = MP_VAL; + } + +#if DIGIT_BIT > 8 + if (err == MP_OKAY) { + /* Start at the end of the buffer - least significant byte. */ + int j; + unsigned int i; + fp_digit mask = (fp_digit)-1; + fp_digit d; + + /* Put each digit in. */ + i = 0; + for (j = outSz - 1; j >= 0; ) { + unsigned int b; + d = a->dp[i]; + /* Place each byte of a digit into the buffer. */ + for (b = 0; (j >= 0) && (b < (DIGIT_BIT / 8)); b++) { + out[j--] = (byte)(d & mask); + d >>= 8; + } + mask &= (fp_digit)0 - (i < (unsigned int)a->used - 1); + i += (unsigned int)(1 & mask); + } + } +#else + if ((err == MP_OKAY) && ((unsigned int)outSz < a->used)) { + err = MP_VAL; + } + if (err == MP_OKAY) { + unsigned int i; + int j; + fp_digit mask = (fp_digit)-1; + + i = 0; + for (j = outSz - 1; j >= 0; j--) { + out[j] = a->dp[i] & mask; + mask &= (fp_digit)0 - (i < (unsigned int)a->used - 1); + i += (unsigned int)(1 & mask); + } + } +#endif + + return err; +} + int fp_to_unsigned_bin_len(fp_int *a, unsigned char *b, int c) { #if DIGIT_BIT == 64 || DIGIT_BIT == 32 || DIGIT_BIT == 16 @@ -4823,6 +4875,11 @@ int mp_to_unsigned_bin (mp_int * a, unsigned char *b) return fp_to_unsigned_bin(a,b); } +int mp_to_unsigned_bin_len_ct(mp_int * a, unsigned char *b, int c) +{ + return fp_to_unsigned_bin_len_ct(a, b, c); +} + int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c) { return fp_to_unsigned_bin_len(a, b, c); diff --git a/src/wolfcrypt/src/wc_dsp.c b/src/wolfcrypt/src/wc_dsp.c index 09c7ea1..856245b 100644 --- a/src/wolfcrypt/src/wc_dsp.c +++ b/src/wolfcrypt/src/wc_dsp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/wc_encrypt.c b/src/wolfcrypt/src/wc_encrypt.c index b1e8b82..dca1640 100644 --- a/src/wolfcrypt/src/wc_encrypt.c +++ b/src/wolfcrypt/src/wc_encrypt.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -512,8 +512,10 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, switch (version) { #ifndef NO_HMAC case PKCS5v2: + PRIVATE_KEY_UNLOCK(); ret = wc_PBKDF2(key, (byte*)password, passwordSz, salt, saltSz, iterations, (int)derivedLen, typeH); + PRIVATE_KEY_LOCK(); break; #endif #ifndef NO_SHA @@ -636,10 +638,14 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, break; } #endif - #if !defined(NO_AES) && defined(HAVE_AES_CBC) + #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \ + (defined(WOLFSSL_AES_256) || defined(WOLFSSL_AES_128)) #ifdef WOLFSSL_AES_256 case PBE_AES256_CBC: + #endif /* WOLFSSL_AES_256 */ + #ifdef WOLFSSL_AES_128 case PBE_AES128_CBC: + #endif /* WOLFSSL_AES_128 */ { int free_aes; @@ -686,8 +692,7 @@ int wc_CryptKey(const char* password, int passwordSz, byte* salt, #endif break; } - #endif /* WOLFSSL_AES_256 */ - #endif /* !NO_AES && HAVE_AES_CBC */ + #endif /* !NO_AES && HAVE_AES_CBC && (WOLFSSL_AES_256 || WOLFSSL_AES_128) */ #ifdef WC_RC2 case PBE_SHA1_40RC2_CBC: { diff --git a/src/wolfcrypt/src/wc_lms.c b/src/wolfcrypt/src/wc_lms.c index 9de58da..d4f2963 100644 --- a/src/wolfcrypt/src/wc_lms.c +++ b/src/wolfcrypt/src/wc_lms.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -281,79 +281,79 @@ static const wc_LmsParamsMap wc_lms_map[] = { #ifdef WOLFSSL_LMS_SHA256_192 #if LMS_MAX_HEIGHT >= 15 { WC_LMS_PARM_SHA256_192_L1_H15_W2, "LMS/HSS_SHA256/192 L1_H15_W2", - LMS_PARAMS(1, 15, 2, 1, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W2, + LMS_PARAMS(1, 15, 2, 2, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H15_W4, "LMS/HSS_SHA256/192 L1_H15_W4", - LMS_PARAMS(1, 15, 4, 2, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W4, + LMS_PARAMS(1, 15, 4, 3, LMS_SHA256_M24_H15, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, #endif #if LMS_MAX_LEVELS >= 2 #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_SHA256_192_L2_H10_W2, "LMS/HSS SHA256/192 L2_H10_W2", - LMS_PARAMS(2, 10, 2, 1, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, + LMS_PARAMS(2, 10, 2, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L2_H10_W4, "LMS/HSS SHA256/192 L2_H10_W4", - LMS_PARAMS(2, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + LMS_PARAMS(2, 10, 4, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L2_H10_W8, "LMS/HSS SHA256/192 L2_H10_W8", - LMS_PARAMS(2, 10, 8, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, + LMS_PARAMS(2, 10, 8, 4, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 3 { WC_LMS_PARM_SHA256_192_L3_H5_W2 , "LMS/HSS_SHA256/192 L3_H5_W2" , - LMS_PARAMS(3, 5, 2, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, + LMS_PARAMS(3, 5, 2, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L3_H5_W4 , "LMS/HSS_SHA256/192 L3_H5_W4" , - LMS_PARAMS(3, 5, 4, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, + LMS_PARAMS(3, 5, 4, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L3_H5_W8 , "LMS/HSS_SHA256/192 L3_H5_W8" , - LMS_PARAMS(3, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + LMS_PARAMS(3, 5, 8, 4, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_SHA256_192_L3_H10_W4, "LMS/HSS_SHA256/192 L3_H10_W4", - LMS_PARAMS(3, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + LMS_PARAMS(3, 10, 4, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, #endif #endif #if LMS_MAX_LEVELS >= 4 { WC_LMS_PARM_SHA256_192_L4_H5_W8 , "LMS/HSS_SHA256/192 L4_H5_W8" , - LMS_PARAMS(4, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + LMS_PARAMS(4, 5, 8, 4, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #endif { WC_LMS_PARM_SHA256_192_L1_H5_W1 , "LMS/HSS_SHA256/192_L1_H5_W1" , - LMS_PARAMS(1, 5, 1, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W1, + LMS_PARAMS(1, 5, 1, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W1, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H5_W2 , "LMS/HSS_SHA256/192_L1_H5_W2" , - LMS_PARAMS(1, 5, 2, 1, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, + LMS_PARAMS(1, 5, 2, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H5_W4 , "LMS/HSS_SHA256/192_L1_H5_W4" , - LMS_PARAMS(1, 5, 4, 2, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, + LMS_PARAMS(1, 5, 4, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H5_W8 , "LMS/HSS_SHA256/192_L1_H5_W8" , - LMS_PARAMS(1, 5, 8, 3, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, + LMS_PARAMS(1, 5, 8, 4, LMS_SHA256_M24_H5 , LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #if LMS_MAX_HEIGHT >= 10 { WC_LMS_PARM_SHA256_192_L1_H10_W2 , "LMS/HSS_SHA256/192_L1_H10_W2", - LMS_PARAMS(1, 10, 2, 1, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, + LMS_PARAMS(1, 10, 2, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H10_W4 , "LMS/HSS_SHA256/192_L1_H10_W4", - LMS_PARAMS(1, 10, 4, 2, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, + LMS_PARAMS(1, 10, 4, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H10_W8 , "LMS/HSS_SHA256/192_L1_H10_W8", - LMS_PARAMS(1, 10, 8, 3, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, + LMS_PARAMS(1, 10, 8, 4, LMS_SHA256_M24_H10, LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #endif #if LMS_MAX_HEIGHT >= 20 { WC_LMS_PARM_SHA256_192_L1_H20_W2 , "LMS/HSS_SHA256/192_L1_H20_W2", - LMS_PARAMS(1, 20, 2, 1, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W2, + LMS_PARAMS(1, 20, 2, 2, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W2, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H20_W4 , "LMS/HSS_SHA256/192_L1_H20_W4", - LMS_PARAMS(1, 20, 4, 2, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W4, + LMS_PARAMS(1, 20, 4, 3, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W4, WC_SHA256_192_DIGEST_SIZE) }, { WC_LMS_PARM_SHA256_192_L1_H20_W8 , "LMS/HSS_SHA256/192_L1_H20_W8", - LMS_PARAMS(1, 20, 8, 3, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W8, + LMS_PARAMS(1, 20, 8, 4, LMS_SHA256_M24_H20, LMOTS_SHA256_N24_W8, WC_SHA256_192_DIGEST_SIZE) }, #endif #endif /* WOLFSSL_LMS_SHA256_192 */ @@ -586,11 +586,14 @@ void wc_LmsKey_Free(LmsKey* key) #ifndef WOLFSSL_LMS_VERIFY_ONLY if (key->priv_data != NULL) { const LmsParams* params = key->params; - - ForceZero(key->priv_data, LMS_PRIV_DATA_LEN(params->levels, + int priv_data_len = LMS_PRIV_DATA_LEN(params->levels, params->height, params->p, params->rootLevels, - params->cacheBits, params->hash_len)); + params->cacheBits, params->hash_len); +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + priv_data_len += HSS_PRIVATE_KEY_LEN(key->params->hash_len); +#endif + ForceZero(key->priv_data, priv_data_len); XFREE(key->priv_data, key->heap, DYNAMIC_TYPE_LMS); } #endif @@ -717,6 +720,7 @@ int wc_LmsKey_SetContext(LmsKey* key, void* context) int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) { int ret = 0; + int priv_data_len = 0; /* Validate parameters. */ if ((key == NULL) || (rng == NULL)) { @@ -738,17 +742,26 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) ret = BAD_FUNC_ARG; } - if ((ret == 0) && (key->priv_data == NULL)) { + if (ret == 0) { const LmsParams* params = key->params; + priv_data_len = LMS_PRIV_DATA_LEN(params->levels, params->height, + params->p, params->rootLevels, params->cacheBits, params->hash_len); +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + priv_data_len += HSS_PRIVATE_KEY_LEN(key->params->hash_len); +#endif + } + if ((ret == 0) && (key->priv_data == NULL)) { /* Allocate memory for the private key data. */ - key->priv_data = (byte *)XMALLOC(LMS_PRIV_DATA_LEN(params->levels, - params->height, params->p, params->rootLevels, params->cacheBits, - params->hash_len), key->heap, DYNAMIC_TYPE_LMS); + key->priv_data = (byte *)XMALLOC(priv_data_len, key->heap, + DYNAMIC_TYPE_LMS); /* Check pointer is valid. */ if (key->priv_data == NULL) { ret = MEMORY_E; } +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + XMEMSET(key->priv_data, 0, priv_data_len); +#endif } if (ret == 0) { #ifdef WOLFSSL_SMALL_STACK @@ -759,7 +772,8 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -781,9 +795,18 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) } } if (ret == 0) { + int rv; /* Write private key to storage. */ - int rv = key->write_private_key(key->priv_raw, +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + XMEMCPY(key->priv_data + priv_data_len - + HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->priv_raw, + HSS_PRIVATE_KEY_LEN(key->params->hash_len)); + rv = key->write_private_key(key->priv_data, priv_data_len, + key->context); +#else + rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); +#endif if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { ret = IO_FAILED_E; } @@ -816,6 +839,7 @@ int wc_LmsKey_MakeKey(LmsKey* key, WC_RNG* rng) int wc_LmsKey_Reload(LmsKey* key) { int ret = 0; + int priv_data_len = 0; /* Validate parameter. */ if (key == NULL) { @@ -837,25 +861,46 @@ int wc_LmsKey_Reload(LmsKey* key) ret = BAD_FUNC_ARG; } - if ((ret == 0) && (key->priv_data == NULL)) { + if (ret == 0) { const LmsParams* params = key->params; + priv_data_len = LMS_PRIV_DATA_LEN(params->levels, params->height, + params->p, params->rootLevels, params->cacheBits, params->hash_len); +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + priv_data_len += HSS_PRIVATE_KEY_LEN(params->hash_len); +#endif + } + if ((ret == 0) && (key->priv_data == NULL)) { /* Allocate memory for the private key data. */ - key->priv_data = (byte *)XMALLOC(LMS_PRIV_DATA_LEN(params->levels, - params->height, params->p, params->rootLevels, params->cacheBits, - params->hash_len), key->heap, DYNAMIC_TYPE_LMS); + key->priv_data = (byte *)XMALLOC(priv_data_len, key->heap, + DYNAMIC_TYPE_LMS); /* Check pointer is valid. */ if (key->priv_data == NULL) { ret = MEMORY_E; } } if (ret == 0) { + int rv; + /* Load private key. */ - int rv = key->read_private_key(key->priv_raw, +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + const LmsParams* params = key->params; + + rv = key->read_private_key(key->priv_data, priv_data_len, key->context); +#else + rv = key->read_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); +#endif if (rv != WC_LMS_RC_READ_TO_MEMORY) { ret = IO_FAILED_E; } +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + if (ret == 0) { + XMEMCPY(key->priv_raw, key->priv_data + priv_data_len - + HSS_PRIVATE_KEY_LEN(params->hash_len), + HSS_PRIVATE_KEY_LEN(params->hash_len)); + } +#endif } /* Double check the key actually has signatures left. */ @@ -874,7 +919,8 @@ int wc_LmsKey_Reload(LmsKey* key) #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -972,7 +1018,8 @@ int wc_LmsKey_Sign(LmsKey* key, byte* sig, word32* sigSz, const byte* msg, #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -997,9 +1044,24 @@ int wc_LmsKey_Sign(LmsKey* key, byte* sig, word32* sigSz, const byte* msg, *sigSz = (word32)key->params->sig_len; } if (ret == 0) { + int rv; + /* Write private key to storage. */ - int rv = key->write_private_key(key->priv_raw, +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + const LmsParams* params = key->params; + int priv_data_len = LMS_PRIV_DATA_LEN(params->levels, params->height, + params->p, params->rootLevels, params->cacheBits, + params->hash_len) + HSS_PRIVATE_KEY_LEN(key->params->hash_len); + + XMEMCPY(key->priv_data + priv_data_len - + HSS_PRIVATE_KEY_LEN(params->hash_len), key->priv_raw, + HSS_PRIVATE_KEY_LEN(params->hash_len)); + rv = key->write_private_key(key->priv_data, priv_data_len, + key->context); +#else + rv = key->write_private_key(key->priv_raw, HSS_PRIVATE_KEY_LEN(key->params->hash_len), key->context); +#endif if (rv != WC_LMS_RC_SAVED_TO_NV_MEMORY) { ret = IO_FAILED_E; } @@ -1234,7 +1296,8 @@ int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, #ifdef WOLFSSL_SMALL_STACK /* Allocate memory for working state. */ - state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, DYNAMIC_TYPE_TMP_BUFFER); + state = (LmsState*)XMALLOC(sizeof(LmsState), NULL, + DYNAMIC_TYPE_TMP_BUFFER); if (state == NULL) { ret = MEMORY_E; } @@ -1258,6 +1321,36 @@ int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, return ret; } +#ifndef WOLFSSL_LMS_VERIFY_ONLY + +/* Get the Key ID from the LMS key. + * + * PRIV = Q | PARAMS | SEED | I + * where I is the Key ID. + * + * @param [in] key LMS key. + * @param [out] kid Key ID data. + * @param [out] kidSz Size of key ID. + * @return 0 on success. + * @return BAD_FUNC_ARG when a key, kid or kidSz is NULL. + */ +int wc_LmsKey_GetKid(LmsKey * key, const byte ** kid, word32* kidSz) +{ + word32 offset; + + if ((key == NULL) || (kid == NULL) || (kidSz == NULL)) { + return BAD_FUNC_ARG; + } + + /* SEED length is hash length. */ + offset = HSS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN + key->params->hash_len; + *kid = key->priv_raw + offset; + *kidSz = HSS_PRIVATE_KEY_LEN(key->params->hash_len) - offset; + + return 0; +} + + /* Get the Key ID from the raw private key data. * * PRIV = Q | PARAMS | SEED | I @@ -1270,7 +1363,7 @@ int wc_LmsKey_Verify(LmsKey* key, const byte* sig, word32 sigSz, */ const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz) { - word32 seedSz = privSz - LMS_Q_LEN + HSS_PRIV_KEY_PARAM_SET_LEN - LMS_I_LEN; + word32 seedSz = privSz - HSS_Q_LEN - HSS_PRIV_KEY_PARAM_SET_LEN - LMS_I_LEN; if (priv == NULL) { return NULL; @@ -1279,7 +1372,9 @@ const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz) (seedSz != WC_SHA256_DIGEST_SIZE)) { return NULL; } - return priv - LMS_I_LEN; + return priv + privSz - LMS_I_LEN; } +#endif + #endif /* WOLFSSL_HAVE_LMS && WOLFSSL_WC_LMS */ diff --git a/src/wolfcrypt/src/wc_lms_impl.c b/src/wolfcrypt/src/wc_lms_impl.c index 47b60a6..5defb10 100644 --- a/src/wolfcrypt/src/wc_lms_impl.c +++ b/src/wolfcrypt/src/wc_lms_impl.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -3208,7 +3208,7 @@ static void wc_hss_priv_data_store(const LmsParams* params, HssPrivKey* key, int wc_hss_reload_key(LmsState* state, const byte* priv_raw, HssPrivKey* priv_key, byte* priv_data, byte* pub_root) { - int ret; + int ret = 0; (void)pub_root; @@ -3217,27 +3217,34 @@ int wc_hss_reload_key(LmsState* state, const byte* priv_raw, priv_key->inited = 0; #endif - /* Expand the raw private key into the private key data. */ - ret = wc_hss_expand_private_key(state, priv_key->priv, priv_raw, 0); -#ifndef WOLFSSL_WC_LMS_SMALL - if ((ret == 0) && (!priv_key->inited)) { - /* Initialize the authentication paths and caches for all trees. */ - ret = wc_hss_init_auth_path(state, priv_key, pub_root); - #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING - if (ret == 0) { - ret = wc_hss_next_subtrees_init(state, priv_key); - } - #endif - #if !defined(WOLFSSL_LMS_NO_SIG_CACHE) && (LMS_MAX_LEVELS > 1) - if (ret == 0) { - /* Calculate signatures for trees not at bottom. */ - ret = wc_hss_presign(state, priv_key); +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + if (pub_root != NULL) +#endif + { + /* Expand the raw private key into the private key data. */ + ret = wc_hss_expand_private_key(state, priv_key->priv, priv_raw, 0); + #ifndef WOLFSSL_WC_LMS_SMALL + if ((ret == 0) && (!priv_key->inited)) { + /* Initialize the authentication paths and caches for all trees. */ + ret = wc_hss_init_auth_path(state, priv_key, pub_root); + #ifndef WOLFSSL_LMS_NO_SIGN_SMOOTHING + if (ret == 0) { + ret = wc_hss_next_subtrees_init(state, priv_key); + } + #endif + #if !defined(WOLFSSL_LMS_NO_SIG_CACHE) && (LMS_MAX_LEVELS > 1) + if (ret == 0) { + /* Calculate signatures for trees not at bottom. */ + ret = wc_hss_presign(state, priv_key); + } + #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ } - #endif /* !WOLFSSL_LMS_NO_SIG_CACHE */ - /* Set initialized flag. */ - priv_key->inited = (ret == 0); + #endif /* WOLFSSL_WC_LMS_SMALL */ } -#endif /* WOLFSSL_WC_LMS_SMALL */ +#ifndef WOLFSSL_WC_LMS_SMALL + /* Set initialized flag. */ + priv_key->inited = (ret == 0); +#endif return ret; } @@ -3301,6 +3308,10 @@ int wc_hss_make_key(LmsState* state, WC_RNG* rng, byte* priv_raw, wc_lmots_public_key_encode(params, priv_key->priv, pub); } +#ifdef WOLFSSL_WC_LMS_SERIALIZE_STATE + wc_hss_priv_data_store(state->params, priv_key, priv_data); +#endif + return ret; } @@ -3581,7 +3592,7 @@ static int wc_hss_sign_build_sig(LmsState* state, byte* priv_raw, * * @param [in, out] state LMS state. * @param [in, out] priv_raw Raw private key bytes. - * @param [in, out] priv_key Private key data. + * @param [in, out] priv_key Private key. * @param [in, out] priv_data Private key data. * @param [in] msg Message to sign. * @param [in] msgSz Length of message in bytes. diff --git a/src/wolfcrypt/src/wc_mlkem.c b/src/wolfcrypt/src/wc_mlkem.c index a370279..cebdc00 100644 --- a/src/wolfcrypt/src/wc_mlkem.c +++ b/src/wolfcrypt/src/wc_mlkem.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -65,6 +65,12 @@ #include +#ifdef WC_MLKEM_NO_ASM + #undef USE_INTEL_SPEEDUP + #undef WOLFSSL_ARMASM + #undef WOLFSSL_RISCV_ASM +#endif + #include #include #include @@ -668,8 +674,8 @@ static int mlkemkey_encapsulate(MlKemKey* key, const byte* m, byte* r, byte* c) sword16 y[3 * WC_ML_KEM_MAX_K * MLKEM_N]; #endif #endif - sword16* u; - sword16* v; + sword16* u = 0; + sword16* v = 0; /* Establish parameters based on key type. */ switch (key->type) { @@ -1144,7 +1150,8 @@ static MLKEM_NOINLINE int mlkemkey_decapsulate(MlKemKey* key, byte* m, sword16* w; unsigned int k = 0; unsigned int compVecSz; -#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) || \ + (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC)) sword16* u = NULL; #else sword16 u[(WC_ML_KEM_MAX_K + 1) * MLKEM_N]; @@ -1198,7 +1205,8 @@ static MLKEM_NOINLINE int mlkemkey_decapsulate(MlKemKey* key, byte* m, break; } -#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) || \ + (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC)) if (ret == 0) { /* Allocate dynamic memory for a vector and a polynomial. */ u = (sword16*)XMALLOC((k + 1) * MLKEM_N * sizeof(sword16), key->heap, @@ -1254,7 +1262,8 @@ static MLKEM_NOINLINE int mlkemkey_decapsulate(MlKemKey* key, byte* m, /* Step 8: return m */ } -#if !defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC) +#if defined(WOLFSSL_SMALL_STACK) || \ + (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC)) /* Dispose of dynamically memory allocated in function. */ XFREE(u, key->heap, DYNAMIC_TYPE_TMP_BUFFER); #endif diff --git a/src/wolfcrypt/src/wc_mlkem_poly.c b/src/wolfcrypt/src/wc_mlkem_poly.c index e5f4a18..e2e1849 100644 --- a/src/wolfcrypt/src/wc_mlkem_poly.c +++ b/src/wolfcrypt/src/wc_mlkem_poly.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -69,6 +69,12 @@ #include +#ifdef WC_MLKEM_NO_ASM + #undef USE_INTEL_SPEEDUP + #undef WOLFSSL_ARMASM + #undef WOLFSSL_RISCV_ASM +#endif + #include #include @@ -2274,14 +2280,31 @@ void mlkem_decapsulate(const sword16* s, sword16* w, sword16* u, static int mlkem_gen_matrix_k2_avx2(sword16* a, byte* seed, int transposed) { int i; +#ifdef WOLFSSL_SMALL_STACK + byte *rand = NULL; + word64 *state = NULL; +#else byte rand[4 * GEN_MATRIX_SIZE + 2]; word64 state[25 * 4]; +#endif unsigned int ctr0; unsigned int ctr1; unsigned int ctr2; unsigned int ctr3; byte* p; +#ifdef WOLFSSL_SMALL_STACK + rand = (byte*)XMALLOC(4 * GEN_MATRIX_SIZE + 2, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + state = (word64*)XMALLOC(sizeof(word64) * 25 * 4, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if ((rand == NULL) || (state == NULL)) { + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return MEMORY_E; + } +#endif + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; @@ -2345,6 +2368,11 @@ static int mlkem_gen_matrix_k2_avx2(sword16* a, byte* seed, int transposed) p, XOF_BLOCK_SIZE); } +#ifdef WOLFSSL_SMALL_STACK + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return 0; } #endif @@ -2365,14 +2393,31 @@ static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) { int i; int k; +#ifdef WOLFSSL_SMALL_STACK + byte *rand = NULL; + word64 *state = NULL; +#else byte rand[4 * GEN_MATRIX_SIZE + 2]; word64 state[25 * 4]; +#endif unsigned int ctr0; unsigned int ctr1; unsigned int ctr2; unsigned int ctr3; byte* p; +#ifdef WOLFSSL_SMALL_STACK + rand = (byte*)XMALLOC(4 * GEN_MATRIX_SIZE + 2, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + state = (word64*)XMALLOC(sizeof(word64) * 25 * 4, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if ((rand == NULL) || (state == NULL)) { + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return MEMORY_E; + } +#endif + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; @@ -2442,6 +2487,7 @@ static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) XMEMSET(state + 5, 0, sizeof(*state) * (25 - 5)); state[20] = W64LIT(0x8000000000000000); for (i = 0; i < GEN_MATRIX_SIZE; i += SHA3_128_BYTES) { +#ifndef WC_SHA3_NO_ASM if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } @@ -2450,13 +2496,16 @@ static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) sha3_block_avx2(state); RESTORE_VECTOR_REGISTERS(); } - else { + else +#endif /* !WC_SHA3_NO_ASM */ + { BlockSha3(state); } XMEMCPY(rand + i, state, SHA3_128_BYTES); } ctr0 = mlkem_rej_uniform_n_avx2(a, MLKEM_N, rand, GEN_MATRIX_SIZE); while (ctr0 < MLKEM_N) { +#ifndef WC_SHA3_NO_ASM if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } @@ -2465,7 +2514,9 @@ static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) sha3_block_avx2(state); RESTORE_VECTOR_REGISTERS(); } - else { + else +#endif /* !WC_SHA3_NO_ASM */ + { BlockSha3(state); } XMEMCPY(rand, state, SHA3_128_BYTES); @@ -2473,6 +2524,11 @@ static int mlkem_gen_matrix_k3_avx2(sword16* a, byte* seed, int transposed) XOF_BLOCK_SIZE); } +#ifdef WOLFSSL_SMALL_STACK + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return 0; } #endif @@ -2492,14 +2548,31 @@ static int mlkem_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) { int i; int k; +#ifdef WOLFSSL_SMALL_STACK + byte *rand = NULL; + word64 *state = NULL; +#else byte rand[4 * GEN_MATRIX_SIZE + 2]; word64 state[25 * 4]; +#endif unsigned int ctr0; unsigned int ctr1; unsigned int ctr2; unsigned int ctr3; byte* p; +#ifdef WOLFSSL_SMALL_STACK + rand = (byte*)XMALLOC(4 * GEN_MATRIX_SIZE + 2, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + state = (word64*)XMALLOC(sizeof(word64) * 25 * 4, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if ((rand == NULL) || (state == NULL)) { + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return MEMORY_E; + } +#endif + /* Loading 64 bits, only using 48 bits. Loading 2 bytes more than used. */ rand[4 * GEN_MATRIX_SIZE + 0] = 0xff; rand[4 * GEN_MATRIX_SIZE + 1] = 0xff; @@ -2563,6 +2636,11 @@ static int mlkem_gen_matrix_k4_avx2(sword16* a, byte* seed, int transposed) a += 4 * MLKEM_N; } +#ifdef WOLFSSL_SMALL_STACK + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(state, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return 0; } #endif /* WOLFSSL_KYBER1024 || WOLFSSL_WC_ML_KEM_1024 */ @@ -2988,6 +3066,7 @@ static int mlkem_prf(wc_Shake* shake256, byte* out, unsigned int outLen, unsigned int len = min(outLen, WC_SHA3_256_BLOCK_SIZE); /* Perform a block operation on the state for next block of output. */ +#ifndef WC_SHA3_NO_ASM if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } @@ -2996,7 +3075,9 @@ static int mlkem_prf(wc_Shake* shake256, byte* out, unsigned int outLen, sha3_block_avx2(state); RESTORE_VECTOR_REGISTERS(); } - else { + else +#endif /* !WC_SHA3_NO_ASM */ + { BlockSha3(state); } @@ -3043,6 +3124,7 @@ int mlkem_kdf(byte* seed, int seedLen, byte* out, int outLen) XMEMSET(state + len64 + 1, 0, (25 - len64 - 1) * sizeof(word64)); state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); +#ifndef WC_SHA3_NO_ASM if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } @@ -3050,7 +3132,9 @@ int mlkem_kdf(byte* seed, int seedLen, byte* out, int outLen) sha3_block_avx2(state); RESTORE_VECTOR_REGISTERS(); } - else { + else +#endif + { BlockSha3(state); } XMEMCPY(out, state, outLen); @@ -4055,6 +4139,7 @@ static int mlkem_get_noise_eta2_avx2(MLKEM_PRF_T* prf, sword16* p, state[WC_SHA3_256_COUNT - 1] = W64LIT(0x8000000000000000); /* Perform a block operation on the state for next block of output. */ +#ifndef WC_SHA3_NO_ASM if (IS_INTEL_BMI2(cpuid_flags)) { sha3_block_bmi2(state); } @@ -4062,7 +4147,9 @@ static int mlkem_get_noise_eta2_avx2(MLKEM_PRF_T* prf, sword16* p, sha3_block_avx2(state); RESTORE_VECTOR_REGISTERS(); } - else { + else +#endif /* !WC_SHA3_NO_ASM */ + { BlockSha3(state); } mlkem_cbd_eta2_avx2(p, (byte*)state); @@ -4120,7 +4207,17 @@ static int mlkem_get_noise_k2_avx2(MLKEM_PRF_T* prf, sword16* vec1, sword16* vec2, sword16* poly, byte* seed) { int ret = 0; +#ifdef WOLFSSL_SMALL_STACK + byte *rand; +#else byte rand[4 * PRF_RAND_SZ]; +#endif + +#ifdef WOLFSSL_SMALL_STACK + rand = (byte*)XMALLOC(4 * PRF_RAND_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (rand == NULL) + return MEMORY_E; +#endif mlkem_get_noise_x4_eta3_avx2(rand, seed); mlkem_cbd_eta3_avx2(vec1 , rand + 0 * PRF_RAND_SZ); @@ -4137,6 +4234,10 @@ static int mlkem_get_noise_k2_avx2(MLKEM_PRF_T* prf, sword16* vec1, ret = mlkem_get_noise_eta2_avx2(prf, poly, seed); } +#ifdef WOLFSSL_SMALL_STACK + XFREE(rand, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return ret; } #endif diff --git a/src/wolfcrypt/src/wc_pkcs11.c b/src/wolfcrypt/src/wc_pkcs11.c index efacd74..d8a2916 100644 --- a/src/wolfcrypt/src/wc_pkcs11.c +++ b/src/wolfcrypt/src/wc_pkcs11.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -535,7 +535,7 @@ static int Pkcs11Slot_FindByTokenName(Pkcs11Dev* dev, CK_RV rv; CK_ULONG slotCnt = 0; CK_TOKEN_INFO tinfo; - int index = -1; + int idx = -1; CK_SLOT_ID* slot = NULL; rv = dev->func->C_GetSlotList(CK_TRUE, NULL, &slotCnt); @@ -547,12 +547,12 @@ static int Pkcs11Slot_FindByTokenName(Pkcs11Dev* dev, rv = dev->func->C_GetSlotList(CK_TRUE, slot, &slotCnt); if (rv != CKR_OK) goto out; - for (index = 0; index < (int)slotCnt; index++) { - rv = dev->func->C_GetTokenInfo(slot[index], &tinfo); + for (idx = 0; idx < (int)slotCnt; idx++) { + rv = dev->func->C_GetTokenInfo(slot[idx], &tinfo); PKCS11_RV("C_GetTokenInfo", rv); if (rv == CKR_OK && XMEMCMP(tinfo.label, tokenName, tokenNameSz) == 0) { - ret = (int)slot[index]; + ret = (int)slot[idx]; break; } } diff --git a/src/wolfcrypt/src/wc_port.c b/src/wolfcrypt/src/wc_port.c index a757852..3c63d26 100644 --- a/src/wolfcrypt/src/wc_port.c +++ b/src/wolfcrypt/src/wc_port.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -25,6 +25,10 @@ #include #endif +#include +#ifdef HAVE_ENTROPY_MEMUSE + #include +#endif #ifdef HAVE_ECC #include #endif @@ -68,6 +72,10 @@ #include #endif +#if defined(WOLFSSL_TROPIC01) + #include +#endif + #if (defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)) \ && !defined(WOLFCRYPT_ONLY) #include @@ -145,6 +153,10 @@ /* prevent multiple mutex initializations */ static volatile int initRefCount = 0; +#if defined(__aarch64__) && defined(WOLFSSL_ARMASM_BARRIER_DETECT) +int aarch64_use_sb = 0; +#endif + /* Used to initialize state for wolfcrypt return 0 on success */ @@ -155,6 +167,10 @@ int wolfCrypt_Init(void) if (initRefCount == 0) { WOLFSSL_ENTER("wolfCrypt_Init"); + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM_BARRIER_DETECT) + aarch64_use_sb = IS_AARCH64_SB(cpuid_get_flags()); + #endif + #ifdef WOLFSSL_CHECK_MEM_ZERO /* Initialize the mutex for access to the list of memory locations that * must be freed. */ @@ -285,7 +301,13 @@ int wolfCrypt_Init(void) #if defined(WOLFSSL_STSAFEA100) stsafe_interface_init(); #endif - + #if defined(WOLFSSL_TROPIC01) + ret = Tropic01_Init(); + if (ret != 0) { + WOLFSSL_MSG("Tropic01 init failed"); + return ret; + } + #endif #if defined(WOLFSSL_PSOC6_CRYPTO) ret = psoc6_crypto_port_init(); if (ret != 0) { @@ -339,13 +361,20 @@ int wolfCrypt_Init(void) return ret; #endif -#ifdef HAVE_ENTROPY_MEMUSE - ret = Entropy_Init(); - if (ret != 0) { - WOLFSSL_MSG("Error initializing entropy"); - return ret; - } -#endif + #if defined(USE_WINDOWS_API) && defined(WIN_REUSE_CRYPT_HANDLE) + /* A failure here should not happen, but if it does the actual RNG seed + * call will fail. This init is for a shared crypt provider handle for + * RNG */ + (void)wc_WinCryptHandleInit(); + #endif + + #ifdef HAVE_ENTROPY_MEMUSE + ret = Entropy_Init(); + if (ret != 0) { + WOLFSSL_MSG("Error initializing entropy"); + return ret; + } + #endif #ifdef HAVE_ECC #ifdef FP_ECC @@ -498,6 +527,9 @@ int wolfCrypt_Cleanup(void) #ifdef WOLFSSL_SILABS_SE_ACCEL ret = sl_se_deinit(); #endif + #if defined(WOLFSSL_TROPIC01) + Tropic01_Deinit(); + #endif #if defined(WOLFSSL_RENESAS_TSIP) tsip_Close(); #endif @@ -516,6 +548,10 @@ int wolfCrypt_Cleanup(void) Entropy_Final(); #endif + #if defined(USE_WINDOWS_API) && defined(WIN_REUSE_CRYPT_HANDLE) + wc_WinCryptHandleCleanup(); + #endif + #ifdef WOLF_CRYPTO_CB wc_CryptoCb_Cleanup(); #endif @@ -2177,32 +2213,7 @@ int wolfSSL_HwPkMutexUnLock(void) } #elif defined(WOLFSSL_LINUXKM) - /* Linux kernel mutex routines are voids, alas. */ - - int wc_InitMutex(wolfSSL_Mutex* m) - { - mutex_init(m); - return 0; - } - - int wc_FreeMutex(wolfSSL_Mutex* m) - { - mutex_destroy(m); - return 0; - } - - int wc_LockMutex(wolfSSL_Mutex* m) - { - mutex_lock(m); - return 0; - } - - - int wc_UnLockMutex(wolfSSL_Mutex* m) - { - mutex_unlock(m); - return 0; - } + /* defined as inlines in linuxkm/linuxkm_wc_port.h */ #elif defined(WOLFSSL_VXWORKS) @@ -3929,7 +3940,21 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) { if (cond == NULL) return BAD_FUNC_ARG; - #if defined(__OS2__) + #if defined(__MACH__) + cond->cond = dispatch_semaphore_create(0); + if (cond->cond == NULL) + return MEMORY_E; + + /* dispatch_release() fails hard, with Trace/BPT trap signal, if the + * sem's internal count is less than the value passed in with + * dispatch_semaphore_create(). work around this by initializing + * with 0, then incrementing it afterwards. + */ + if (dispatch_semaphore_signal(s->sem) < 0) { + dispatch_release(s->sem); + return MEMORY_E; + } + #elif defined(__OS2__) DosCreateMutexSem( NULL, &cond->mutex, 0, FALSE ); DosCreateEventSem( NULL, &cond->cond, DCE_POSTONE, FALSE ); #elif defined(__NT__) @@ -3960,7 +3985,9 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) { if (cond == NULL) return BAD_FUNC_ARG; - #if defined(__OS2__) + #if defined(__MACH__) + dispatch_release(cond->cond); + #elif defined(__OS2__) DosCloseMutexSem(cond->mutex); DosCloseEventSem(cond->cond); #elif defined(__NT__) @@ -3980,7 +4007,8 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) { if (cond == NULL) return BAD_FUNC_ARG; - #if defined(__OS2__) + #if defined(__MACH__) + #elif defined(__OS2__) #elif defined(__NT__) if (wc_LockMutex(&cond->mutex) != 0) return BAD_MUTEX_E; @@ -3995,7 +4023,9 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) { if (cond == NULL) return BAD_FUNC_ARG; - #if defined(__OS2__) + #if defined(__MACH__) + dispatch_semaphore_signal(cond->cond); + #elif defined(__OS2__) #elif defined(__NT__) if (wc_UnLockMutex(&cond->mutex) != 0) return BAD_MUTEX_E; @@ -4016,7 +4046,9 @@ char* mystrnstr(const char* s1, const char* s2, unsigned int n) { if (cond == NULL) return BAD_FUNC_ARG; - #if defined(__OS2__) + #if defined(__MACH__) + dispatch_semaphore_wait(cond->cond, DISPATCH_TIME_FOREVER); + #elif defined(__OS2__) #elif defined(__NT__) if (wc_UnLockMutex(&cond->mutex) != 0) return BAD_MUTEX_E; @@ -4599,4 +4631,10 @@ noinstr void my__alt_cb_patch_nops(struct alt_instr *alt, __le32 *origptr, return (wolfssl_linuxkm_get_pie_redirect_table()-> alt_cb_patch_nops)(alt, origptr, updptr, nr_inst); } + +void my__queued_spin_lock_slowpath(struct qspinlock *lock, u32 val) +{ + return (wolfssl_linuxkm_get_pie_redirect_table()-> + queued_spin_lock_slowpath)(lock, val); +} #endif diff --git a/src/wolfcrypt/src/wc_xmss.c b/src/wolfcrypt/src/wc_xmss.c index 51b308b..6957471 100644 --- a/src/wolfcrypt/src/wc_xmss.c +++ b/src/wolfcrypt/src/wc_xmss.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -149,7 +149,13 @@ static WC_INLINE void wc_xmss_state_free(XmssState* state) */ typedef struct wc_XmssString { /* Name of algorithm as a string. */ +#ifdef WOLFSSL_NAMES_STATIC + const char str[32]; /* large enough for largest string in wc_xmss_alg[] or + * wc_xmssmt_alg[] + */ +#else const char* str; +#endif /* OID for algorithm. */ word32 oid; /* XMSS parameters. */ diff --git a/src/wolfcrypt/src/wc_xmss_impl.c b/src/wolfcrypt/src/wc_xmss_impl.c index 15b2184..720cfb2 100644 --- a/src/wolfcrypt/src/wc_xmss_impl.c +++ b/src/wolfcrypt/src/wc_xmss_impl.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2590,7 +2590,7 @@ static void wc_xmss_bds_state_treehash_set_next_idx(BdsState* bds, int i, static void wc_xmss_bds_state_treehash_complete(BdsState* bds, int i) { byte* sk = bds->treeHash + i * 4; - sk[3] |= 1 << 7; + sk[3] |= 1 << 7; /* // NOLINT(clang-analyzer-core.NullDereference) */ } /* Get the tree hash data at specified index for the BDS state. diff --git a/src/wolfcrypt/src/wolfevent.c b/src/wolfcrypt/src/wolfevent.c index 34d5740..5f3818f 100644 --- a/src/wolfcrypt/src/wolfevent.c +++ b/src/wolfcrypt/src/wolfevent.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfcrypt/src/wolfmath.c b/src/wolfcrypt/src/wolfmath.c index 9f14d01..c29e294 100644 --- a/src/wolfcrypt/src/wolfmath.c +++ b/src/wolfcrypt/src/wolfmath.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -85,7 +85,7 @@ void mp_reverse(unsigned char *s, int len) } } -int get_digit_count(const mp_int* a) +int mp_get_digit_count(const mp_int* a) { if (a == NULL) return 0; @@ -93,7 +93,7 @@ int get_digit_count(const mp_int* a) return (int)a->used; } -mp_digit get_digit(const mp_int* a, int n) +mp_digit mp_get_digit(const mp_int* a, int n) { if (a == NULL) return 0; @@ -135,13 +135,13 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) * When mask all set, b ^ b ^ a = a */ /* Conditionally copy all digits and then number of used digits. - * get_digit() returns 0 when index greater than available digit. + * mp_get_digit() returns 0 when index greater than available digit. */ for (i = 0; i < a->used; i++) { - b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; + b->dp[i] ^= (mp_get_digit(a, (int)i) ^ mp_get_digit(b, (int)i)) & mask; } for (; i < b->used; i++) { - b->dp[i] ^= (get_digit(a, (int)i) ^ get_digit(b, (int)i)) & mask; + b->dp[i] ^= (mp_get_digit(a, (int)i) ^ mp_get_digit(b, (int)i)) & mask; } b->used ^= (a->used ^ b->used) & (wc_mp_size_t)mask; #if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \ @@ -156,7 +156,7 @@ int mp_cond_copy(mp_int* a, int copy, mp_int* b) #ifndef WC_NO_RNG -int get_rand_digit(WC_RNG* rng, mp_digit* d) +int mp_get_rand_digit(WC_RNG* rng, mp_digit* d) { return wc_RNG_GenerateBlock(rng, (byte*)d, sizeof(mp_digit)); } @@ -205,7 +205,7 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng) #endif /* ensure top digit is not zero */ while ((ret == MP_OKAY) && (a->dp[a->used - 1] == 0)) { - ret = get_rand_digit(rng, &a->dp[a->used - 1]); + ret = mp_get_rand_digit(rng, &a->dp[a->used - 1]); #ifdef USE_INTEGER_HEAP_MATH a->dp[a->used - 1] &= MP_MASK; #endif @@ -511,6 +511,54 @@ const char *wc_GetMathInfo(void) " no-malloc" #endif #endif + + /* ARM Assembly speedups */ + #if defined(WOLFSSL_ARMASM) || defined(USE_INTEL_SPEEDUP) + "\n\tAssembly Speedups:" + + #ifdef WOLFSSL_ARMASM + " ARMASM" + #ifdef WOLFSSL_ARMASM_THUMB2 + " THUMB2" + #endif + #ifdef WOLFSSL_ARMASM_INLINE + " INLINE" + #endif + #ifdef WOLFSSL_ARMASM_NO_HW_CRYPTO + " NO_HW_CRYPTO" + #endif + #ifdef WOLFSSL_ARMASM_NO_NEON + " NO_NEON" + #endif + #ifdef WOLFSSL_ARM_ARCH + " ARM ARCH=" WC_STRINGIFY(WOLFSSL_ARM_ARCH) + #endif + #endif + + #ifdef USE_INTEL_SPEEDUP + " INTELASM" + #ifdef USE_INTEL_SPEEDUP_FOR_AES + " AES" + #endif + #endif + + #ifdef WOLFSSL_USE_ALIGN + " ALIGN" + #endif + #ifdef HAVE_INTEL_RDRAND + " INTEL_RDRAND" + #endif + #ifdef HAVE_AMD_RDSEED + " AMD_RDSEED" + #endif + #ifdef WOLFSSL_X86_64_BUILD + " X86_64_BUILD" + #endif + #ifdef WOLFSSL_X86_BUILD + " X86_BUILD" + #endif + #endif + ; } #endif /* HAVE_WC_INTROSPECTION */ diff --git a/src/wolfssl-arduino.cpp b/src/wolfssl-arduino.cpp index 19c50a6..a047eff 100644 --- a/src/wolfssl-arduino.cpp +++ b/src/wolfssl-arduino.cpp @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl.h b/src/wolfssl.h index 8b29806..85f2bf5 100644 --- a/src/wolfssl.h +++ b/src/wolfssl.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/bio.c b/src/wolfssl/bio.c index 0b52a6c..ce74983 100644 --- a/src/wolfssl/bio.c +++ b/src/wolfssl/bio.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2392,13 +2392,28 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) WOLFSSL_ENTER("wolfSSL_BIO_new_connect"); bio = wolfSSL_BIO_new(wolfSSL_BIO_s_socket()); if (bio) { - const char* port = XSTRSTR(str, ":"); + const char* port; +#ifdef WOLFSSL_IPV6 + const char* ipv6Start = XSTRSTR(str, "["); + const char* ipv6End = XSTRSTR(str, "]"); + + if (ipv6End) + port = XSTRSTR(ipv6End, ":"); + else +#endif + port = XSTRSTR(str, ":"); if (port != NULL) bio->port = (word16)XATOI(port + 1); else port = str + XSTRLEN(str); /* point to null terminator */ +#ifdef WOLFSSL_IPV6 + if (ipv6Start && ipv6End) { + str = ipv6Start + 1; + port = ipv6End; + } +#endif bio->ip = (char*)XMALLOC( (size_t)(port - str) + 1, /* +1 for null char */ bio->heap, DYNAMIC_TYPE_OPENSSL); diff --git a/src/wolfssl/callbacks.h b/src/wolfssl/callbacks.h index a75e483..4d58676 100644 --- a/src/wolfssl/callbacks.h +++ b/src/wolfssl/callbacks.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/crl.h b/src/wolfssl/crl.h index 56f5003..059edee 100644 --- a/src/wolfssl/crl.h +++ b/src/wolfssl/crl.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/error-ssl.h b/src/wolfssl/error-ssl.h index bc3e641..3873b25 100644 --- a/src/wolfssl/error-ssl.h +++ b/src/wolfssl/error-ssl.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -220,6 +220,7 @@ enum wolfSSL_ErrorCodes { POST_HAND_AUTH_ERROR = -504, /* client won't do post-hand auth */ HRR_COOKIE_ERROR = -505, /* HRR msg cookie mismatch */ UNSUPPORTED_CERTIFICATE = -506, /* unsupported certificate type */ + DTLS_PARTIAL_RECORD_READ = -455, /* received a partial record in a datagram */ /* PEM and EVP errors */ WOLFSSL_PEM_R_NO_START_LINE_E = -507, diff --git a/src/wolfssl/evp.c b/src/wolfssl/evp.c index 7054f80..5c9ac3e 100644 --- a/src/wolfssl/evp.c +++ b/src/wolfssl/evp.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -2538,9 +2538,11 @@ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new(WOLFSSL_EVP_PKEY *pkey, WOLFSSL_E if (ctx == NULL) return NULL; XMEMSET(ctx, 0, sizeof(WOLFSSL_EVP_PKEY_CTX)); ctx->pkey = pkey; -#if !defined(NO_RSA) +#ifndef NO_RSA ctx->padding = WC_RSA_PKCS1_PADDING; ctx->md = NULL; + ctx->mgf1_md = NULL; + ctx->saltlen = 0; #endif #ifdef HAVE_ECC if (pkey->ecc && pkey->ecc->group) { @@ -2593,6 +2595,42 @@ int wolfSSL_EVP_PKEY_CTX_set_signature_md(WOLFSSL_EVP_PKEY_CTX *ctx, return WOLFSSL_SUCCESS; } +int wolfSSL_EVP_PKEY_CTX_set_rsa_oaep_md(WOLFSSL_EVP_PKEY_CTX *ctx, + const WOLFSSL_EVP_MD *md) +{ + wolfSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, WC_RSA_PKCS1_OAEP_PADDING); + return wolfSSL_EVP_PKEY_CTX_set_signature_md(ctx, md); +} + +int wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen(WOLFSSL_EVP_PKEY_CTX *ctx, + int saltlen) +{ + if (ctx == NULL) return 0; + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen"); + wolfSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, WC_RSA_PKCS1_PSS_PADDING); +#ifndef NO_RSA + ctx->saltlen = saltlen; +#else + (void)saltlen; +#endif + return WOLFSSL_SUCCESS; +} + +int wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md(WOLFSSL_EVP_PKEY_CTX *ctx, + const WOLFSSL_EVP_MD *md) +{ + if (ctx == NULL) return 0; + WOLFSSL_ENTER("wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md"); +#ifndef NO_RSA + /* Hash digest algorithm used with Mask Generation Function 1 (MGF1) for + * RSA-PSS and RSA-OAEP. */ + ctx->mgf1_md = md; +#else + (void)md; +#endif + return WOLFSSL_SUCCESS; +} + /* create a PKEY context and return it */ WOLFSSL_EVP_PKEY_CTX *wolfSSL_EVP_PKEY_CTX_new_id(int id, WOLFSSL_ENGINE *e) { @@ -3278,7 +3316,7 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, (void)tbslen; switch (ctx->pkey->type) { -#if !defined(NO_RSA) +#ifndef NO_RSA case WC_EVP_PKEY_RSA: { unsigned int usiglen = (unsigned int)*siglen; if (!sig) { @@ -3291,17 +3329,17 @@ int wolfSSL_EVP_PKEY_sign(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *sig, *siglen = (size_t)len; return WOLFSSL_SUCCESS; } - /* wolfSSL_RSA_sign_generic_padding performs a check that the output - * sig buffer is large enough */ - if (wolfSSL_RSA_sign_generic_padding(wolfSSL_EVP_MD_type(ctx->md), tbs, - (unsigned int)tbslen, sig, &usiglen, ctx->pkey->rsa, 1, - ctx->padding) != WOLFSSL_SUCCESS) { + + if (wolfSSL_RSA_sign_mgf(wolfSSL_EVP_MD_type(ctx->md), tbs, + (unsigned int)tbslen, sig, &usiglen, ctx->pkey->rsa, 1, + ctx->padding, wolfSSL_EVP_MD_type(ctx->mgf1_md), ctx->saltlen + ) != WOLFSSL_SUCCESS) { return WOLFSSL_FAILURE; } *siglen = (size_t)usiglen; return WOLFSSL_SUCCESS; } -#endif /* NO_RSA */ +#endif /* !NO_RSA */ #ifndef NO_DSA case WC_EVP_PKEY_DSA: { @@ -3434,12 +3472,12 @@ int wolfSSL_EVP_PKEY_verify(WOLFSSL_EVP_PKEY_CTX *ctx, const unsigned char *sig, return WOLFSSL_FAILURE; switch (ctx->pkey->type) { -#if !defined(NO_RSA) +#ifndef NO_RSA case WC_EVP_PKEY_RSA: - return wolfSSL_RSA_verify_ex(WC_HASH_TYPE_NONE, tbs, + return wolfSSL_RSA_verify_mgf(wolfSSL_EVP_MD_type(ctx->md), tbs, (unsigned int)tbslen, sig, (unsigned int)siglen, ctx->pkey->rsa, - ctx->padding); -#endif /* NO_RSA */ + ctx->padding, wolfSSL_EVP_MD_type(ctx->mgf1_md), ctx->saltlen); +#endif /* !NO_RSA */ #ifndef NO_DSA case WC_EVP_PKEY_DSA: { @@ -10193,8 +10231,8 @@ int wolfSSL_EVP_MD_type(const WOLFSSL_EVP_MD* type) return WC_NID_undef; } - for( ent = md_tbl; ent->name != NULL; ent++){ - if(XSTRCMP((const char *)type, ent->name) == 0) { + for (ent = md_tbl; ent->name != NULL; ent++) { + if (XSTRCMP((const char *)type, ent->name) == 0) { return ent->nid; } } diff --git a/src/wolfssl/internal.h b/src/wolfssl/internal.h index 9cdbdb6..07b75f2 100644 --- a/src/wolfssl/internal.h +++ b/src/wolfssl/internal.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -249,8 +249,8 @@ #endif #endif -#if !defined(CHAR_BIT) || (defined(OPENSSL_EXTRA) && !defined(INT_MAX)) - /* Needed for DTLS without big math and INT_MAX */ +#if !defined(WOLFCRYPT_ONLY) && !defined(INT_MAX) + /* Needed for TLS/DTLS limit checking (Added in 91aad90c59 Jan 24, 2025) */ #include #endif @@ -300,6 +300,10 @@ #include #endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */ +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + #include +#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ + #ifdef __cplusplus extern "C" { #endif @@ -532,12 +536,13 @@ #endif #if defined(HAVE_ANON) && !defined(NO_TLS) && !defined(NO_DH) && \ - !defined(NO_AES) && !defined(NO_SHA) && defined(WOLFSSL_AES_128) - #ifdef HAVE_AES_CBC + !defined(NO_AES) + #if !defined(NO_SHA) && defined(HAVE_AES_CBC) && \ + defined(WOLFSSL_AES_128) #define BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA #endif - - #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) + #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) && \ + defined(WOLFSSL_AES_256) #define BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384 #endif #endif @@ -1085,13 +1090,17 @@ #undef WSSL_HARDEN_TLS -#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(HAVE_LIGHTY) -#define SSL_CA_NAMES(ssl) ((ssl)->client_ca_names != NULL ? (ssl)->client_ca_names : \ +/* Client CA Names feature */ +#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA) + #define SSL_CA_NAMES(ssl) ((ssl)->client_ca_names != NULL ? \ + (ssl)->client_ca_names : \ (ssl)->ctx->client_ca_names) #else -#define WOLFSSL_NO_CA_NAMES + #undef WOLFSSL_NO_CA_NAMES + #define WOLFSSL_NO_CA_NAMES #endif + /* actual cipher values, 2nd byte */ enum { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x16, @@ -2547,6 +2556,8 @@ typedef struct CRL_Entry CRL_Entry; #error CRL_MAX_REVOKED_CERTS too big, max is 22000 #endif #endif + +#ifdef HAVE_CRL /* Complete CRL */ struct CRL_Entry { byte* toBeSigned; @@ -2559,6 +2570,7 @@ struct CRL_Entry { /* DupCRL_Entry copies data after the `verifyMutex` member. Using the mutex * as the marker because clang-tidy doesn't like taking the sizeof a * pointer. */ + byte crlNumber[CRL_MAX_NUM_SZ]; /* CRL number extension */ byte issuerHash[CRL_DIGEST_SIZE]; /* issuer hash */ /* byte crlHash[CRL_DIGEST_SIZE]; raw crl data hash */ /* restore the hash here if needed for optimized comparisons */ @@ -2586,10 +2598,10 @@ struct CRL_Entry { byte* sigParams; /* buffer with signature parameters */ #endif #if !defined(NO_SKID) && !defined(NO_ASN) - byte extAuthKeyIdSet; byte extAuthKeyId[KEYID_SIZE]; + byte extAuthKeyIdSet:1; /* Auth key identifier set indicator */ #endif - int crlNumber; /* CRL number extension */ + byte crlNumberSet:1; /* CRL number set indicator */ }; @@ -2642,6 +2654,7 @@ struct WOLFSSL_CRL { #endif void* heap; /* heap hint for dynamic memory */ }; +#endif #ifdef NO_ASN @@ -4233,6 +4246,10 @@ struct WOLFSSL_CTX { #if defined(WOLFSSL_SYS_CRYPTO_POLICY) int secLevel; /* The security level of system-wide crypto policy. */ #endif /* WOLFSSL_SYS_CRYPTO_POLICY */ + +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + CFMutableArrayRef testTrustedCAs; +#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ }; WOLFSSL_LOCAL @@ -4269,6 +4286,13 @@ int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, #endif #endif +#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION + WOLFSSL_API + int wolfSSL_TestAppleNativeCertValidation_AppendCA(WOLFSSL_CTX* ctx, + const byte* derCert, + int derLen); +#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */ + /* All cipher suite related info * Keep as a constant size (no ifdefs) for session export */ typedef struct CipherSpecs { @@ -6389,7 +6413,8 @@ WOLFSSL_TEST_VIS void wolfSSL_ResourceFree(WOLFSSL* ssl); /* Micrium uses */ WOLFSSL_LOCAL int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff, long sz, int format, int type, WOLFSSL* ssl, - long* used, int userChain, int verify); + long* used, int userChain, int verify, + const char *source_name); WOLFSSL_LOCAL int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format, int type, WOLFSSL* ssl, int userChain, WOLFSSL_CRL* crl, int verify); @@ -6707,6 +6732,8 @@ WOLFSSL_LOCAL int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength); WOLFSSL_LOCAL int MsgCheckEncryption(WOLFSSL* ssl, byte type, byte encrypted); WOLFSSL_LOCAL int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type, word32 msgSz); +WOLFSSL_LOCAL int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, + word32* inOutIdx, byte* type, word32* size, word32 totalSz); #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) WOLFSSL_LOCAL void DoCertFatalAlert(WOLFSSL* ssl, int ret); #endif @@ -7122,8 +7149,9 @@ WOLFSSL_LOCAL WC_RNG* wolfssl_make_global_rng(void); #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA) #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER) -WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz, const WOLFSSL_EVP_CIPHER* cipher, - unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz); +WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz, + const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz, + byte **cipherInfo, int maxDerSz, int hashType); #endif #endif diff --git a/src/wolfssl/ocsp.h b/src/wolfssl/ocsp.h index 69b5c14..a887299 100644 --- a/src/wolfssl/ocsp.h +++ b/src/wolfssl/ocsp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/aes.h b/src/wolfssl/openssl/aes.h index 4710f72..9a644ac 100644 --- a/src/wolfssl/openssl/aes.h +++ b/src/wolfssl/openssl/aes.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/asn1.h b/src/wolfssl/openssl/asn1.h index b9e2c19..5ec5486 100644 --- a/src/wolfssl/openssl/asn1.h +++ b/src/wolfssl/openssl/asn1.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/asn1t.h b/src/wolfssl/openssl/asn1t.h index 2a52b3b..47aba84 100644 --- a/src/wolfssl/openssl/asn1t.h +++ b/src/wolfssl/openssl/asn1t.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/bio.h b/src/wolfssl/openssl/bio.h index 73214ab..a9db325 100644 --- a/src/wolfssl/openssl/bio.h +++ b/src/wolfssl/openssl/bio.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/bn.h b/src/wolfssl/openssl/bn.h index 45411f5..3fea539 100644 --- a/src/wolfssl/openssl/bn.h +++ b/src/wolfssl/openssl/bn.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -132,6 +132,7 @@ WOLFSSL_API int wolfSSL_BN_is_negative(const WOLFSSL_BIGNUM* bn); WOLFSSL_API int wolfSSL_BN_is_word(const WOLFSSL_BIGNUM* bn, WOLFSSL_BN_ULONG w); WOLFSSL_API int wolfSSL_BN_cmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b); +WOLFSSL_API int wolfSSL_BN_ucmp(const WOLFSSL_BIGNUM* a, const WOLFSSL_BIGNUM* b); WOLFSSL_API int wolfSSL_BN_bn2bin(const WOLFSSL_BIGNUM* bn, unsigned char* r); WOLFSSL_API WOLFSSL_BIGNUM* wolfSSL_BN_bin2bn(const unsigned char* str, int len, @@ -243,6 +244,7 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_is_word wolfSSL_BN_is_word #define BN_cmp wolfSSL_BN_cmp +#define BN_ucmp wolfSSL_BN_ucmp #define BN_bn2bin wolfSSL_BN_bn2bin #define BN_bin2bn wolfSSL_BN_bin2bn diff --git a/src/wolfssl/openssl/buffer.h b/src/wolfssl/openssl/buffer.h index 548d744..fa9bf3e 100644 --- a/src/wolfssl/openssl/buffer.h +++ b/src/wolfssl/openssl/buffer.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/camellia.h b/src/wolfssl/openssl/camellia.h index fe5b17c..b3d7c83 100644 --- a/src/wolfssl/openssl/camellia.h +++ b/src/wolfssl/openssl/camellia.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/cmac.h b/src/wolfssl/openssl/cmac.h index 489396c..cadf514 100644 --- a/src/wolfssl/openssl/cmac.h +++ b/src/wolfssl/openssl/cmac.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/cms.h b/src/wolfssl/openssl/cms.h index 291c08d..88c4f82 100644 --- a/src/wolfssl/openssl/cms.h +++ b/src/wolfssl/openssl/cms.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/compat_types.h b/src/wolfssl/openssl/compat_types.h index 58113c4..2fb133e 100644 --- a/src/wolfssl/openssl/compat_types.h +++ b/src/wolfssl/openssl/compat_types.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/conf.h b/src/wolfssl/openssl/conf.h index d2e2eb4..d059c59 100644 --- a/src/wolfssl/openssl/conf.h +++ b/src/wolfssl/openssl/conf.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/crypto.h b/src/wolfssl/openssl/crypto.h index e05468e..9673d55 100644 --- a/src/wolfssl/openssl/crypto.h +++ b/src/wolfssl/openssl/crypto.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/des.h b/src/wolfssl/openssl/des.h index 9554c2a..ae569dc 100644 --- a/src/wolfssl/openssl/des.h +++ b/src/wolfssl/openssl/des.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/dh.h b/src/wolfssl/openssl/dh.h index 70b1087..d723451 100644 --- a/src/wolfssl/openssl/dh.h +++ b/src/wolfssl/openssl/dh.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/dsa.h b/src/wolfssl/openssl/dsa.h index d5f64bb..055d97b 100644 --- a/src/wolfssl/openssl/dsa.h +++ b/src/wolfssl/openssl/dsa.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ec.h b/src/wolfssl/openssl/ec.h index d68217b..f1d76aa 100644 --- a/src/wolfssl/openssl/ec.h +++ b/src/wolfssl/openssl/ec.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ec25519.h b/src/wolfssl/openssl/ec25519.h index 92cf807..9757935 100644 --- a/src/wolfssl/openssl/ec25519.h +++ b/src/wolfssl/openssl/ec25519.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ec448.h b/src/wolfssl/openssl/ec448.h index ce2cc7c..11aab35 100644 --- a/src/wolfssl/openssl/ec448.h +++ b/src/wolfssl/openssl/ec448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ecdh.h b/src/wolfssl/openssl/ecdh.h index 7fbc5a3..5f72bcf 100644 --- a/src/wolfssl/openssl/ecdh.h +++ b/src/wolfssl/openssl/ecdh.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ecdsa.h b/src/wolfssl/openssl/ecdsa.h index 12d003f..35989d8 100644 --- a/src/wolfssl/openssl/ecdsa.h +++ b/src/wolfssl/openssl/ecdsa.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ed25519.h b/src/wolfssl/openssl/ed25519.h index 9d67c6f..2a6aabb 100644 --- a/src/wolfssl/openssl/ed25519.h +++ b/src/wolfssl/openssl/ed25519.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ed448.h b/src/wolfssl/openssl/ed448.h index 793e66f..cf4b54c 100644 --- a/src/wolfssl/openssl/ed448.h +++ b/src/wolfssl/openssl/ed448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/err.h b/src/wolfssl/openssl/err.h index 6723ded..864070a 100644 --- a/src/wolfssl/openssl/err.h +++ b/src/wolfssl/openssl/err.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/evp.h b/src/wolfssl/openssl/evp.h index 3192dbf..0d9cf86 100644 --- a/src/wolfssl/openssl/evp.h +++ b/src/wolfssl/openssl/evp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -752,7 +752,9 @@ struct WOLFSSL_EVP_PKEY_CTX { #endif #ifndef NO_RSA const WOLFSSL_EVP_MD* md; -#endif + const WOLFSSL_EVP_MD* mgf1_md; + int saltlen; +#endif /* !NO_RSA */ }; struct WOLFSSL_ASN1_PCTX { @@ -947,6 +949,9 @@ WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_rsa_padding(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_signature_md(WOLFSSL_EVP_PKEY_CTX *ctx, const WOLFSSL_EVP_MD* md); WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_rsa_keygen_bits(WOLFSSL_EVP_PKEY_CTX *ctx, int bits); +WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen(WOLFSSL_EVP_PKEY_CTX *ctx, int saltlen); +WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md(WOLFSSL_EVP_PKEY_CTX *ctx, const WOLFSSL_EVP_MD *md); +WOLFSSL_API int wolfSSL_EVP_PKEY_CTX_set_rsa_oaep_md(WOLFSSL_EVP_PKEY_CTX *ctx, const WOLFSSL_EVP_MD *md); WOLFSSL_API int wolfSSL_EVP_PKEY_derive_init(WOLFSSL_EVP_PKEY_CTX *ctx); WOLFSSL_API int wolfSSL_EVP_PKEY_derive_set_peer(WOLFSSL_EVP_PKEY_CTX *ctx, WOLFSSL_EVP_PKEY *peer); @@ -1363,6 +1368,9 @@ WOLFSSL_API int wolfSSL_EVP_SignInit_ex(WOLFSSL_EVP_MD_CTX* ctx, #define EVP_PKEY_CTX_set_signature_md wolfSSL_EVP_PKEY_CTX_set_signature_md #define EVP_PKEY_CTX_new_id wolfSSL_EVP_PKEY_CTX_new_id #define EVP_PKEY_CTX_set_rsa_keygen_bits wolfSSL_EVP_PKEY_CTX_set_rsa_keygen_bits +#define EVP_PKEY_CTX_set_rsa_mgf1_md wolfSSL_EVP_PKEY_CTX_set_rsa_mgf1_md +#define EVP_PKEY_CTX_set_rsa_pss_saltlen wolfSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen +#define EVP_PKEY_CTX_set_rsa_oaep_md wolfSSL_EVP_PKEY_CTX_set_rsa_oaep_md #define EVP_PKEY_derive_init wolfSSL_EVP_PKEY_derive_init #define EVP_PKEY_derive_set_peer wolfSSL_EVP_PKEY_derive_set_peer #define EVP_PKEY_derive wolfSSL_EVP_PKEY_derive diff --git a/src/wolfssl/openssl/fips_rand.h b/src/wolfssl/openssl/fips_rand.h index 4142e7e..ab6f44d 100644 --- a/src/wolfssl/openssl/fips_rand.h +++ b/src/wolfssl/openssl/fips_rand.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/hmac.h b/src/wolfssl/openssl/hmac.h index b29d4fc..09d9901 100644 --- a/src/wolfssl/openssl/hmac.h +++ b/src/wolfssl/openssl/hmac.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -42,6 +42,7 @@ extern "C" { #endif +#define HMAC_MAX_MD_CBLOCK WC_MAX_BLOCK_SIZE WOLFSSL_API unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key, int key_len, diff --git a/src/wolfssl/openssl/kdf.h b/src/wolfssl/openssl/kdf.h index f36aedc..a618eb2 100644 --- a/src/wolfssl/openssl/kdf.h +++ b/src/wolfssl/openssl/kdf.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/lhash.h b/src/wolfssl/openssl/lhash.h index 6a86992..33f22de 100644 --- a/src/wolfssl/openssl/lhash.h +++ b/src/wolfssl/openssl/lhash.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/md4.h b/src/wolfssl/openssl/md4.h index 3d0549f..3babc18 100644 --- a/src/wolfssl/openssl/md4.h +++ b/src/wolfssl/openssl/md4.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/md5.h b/src/wolfssl/openssl/md5.h index 709c03f..6738106 100644 --- a/src/wolfssl/openssl/md5.h +++ b/src/wolfssl/openssl/md5.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/modes.h b/src/wolfssl/openssl/modes.h index 50342bd..8458db8 100644 --- a/src/wolfssl/openssl/modes.h +++ b/src/wolfssl/openssl/modes.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/obj_mac.h b/src/wolfssl/openssl/obj_mac.h index 3304158..d0eb3d3 100644 --- a/src/wolfssl/openssl/obj_mac.h +++ b/src/wolfssl/openssl/obj_mac.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/objects.h b/src/wolfssl/openssl/objects.h index 3325c83..d9e1a14 100644 --- a/src/wolfssl/openssl/objects.h +++ b/src/wolfssl/openssl/objects.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ocsp.h b/src/wolfssl/openssl/ocsp.h index 67ae0f1..588bbd5 100644 --- a/src/wolfssl/openssl/ocsp.h +++ b/src/wolfssl/openssl/ocsp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/opensslv.h b/src/wolfssl/openssl/opensslv.h index e643a64..8d72cd5 100644 --- a/src/wolfssl/openssl/opensslv.h +++ b/src/wolfssl/openssl/opensslv.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ossl_typ.h b/src/wolfssl/openssl/ossl_typ.h index 084558d..743779f 100644 --- a/src/wolfssl/openssl/ossl_typ.h +++ b/src/wolfssl/openssl/ossl_typ.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/pem.h b/src/wolfssl/openssl/pem.h index 1cf4247..41c3524 100644 --- a/src/wolfssl/openssl/pem.h +++ b/src/wolfssl/openssl/pem.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/pkcs12.h b/src/wolfssl/openssl/pkcs12.h index a59798c..e202aa9 100644 --- a/src/wolfssl/openssl/pkcs12.h +++ b/src/wolfssl/openssl/pkcs12.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/pkcs7.h b/src/wolfssl/openssl/pkcs7.h index 84ae285..9f2a9c0 100644 --- a/src/wolfssl/openssl/pkcs7.h +++ b/src/wolfssl/openssl/pkcs7.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/rand.h b/src/wolfssl/openssl/rand.h index 4c41ed7..7971642 100644 --- a/src/wolfssl/openssl/rand.h +++ b/src/wolfssl/openssl/rand.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/rc4.h b/src/wolfssl/openssl/rc4.h index 309174b..524fdbc 100644 --- a/src/wolfssl/openssl/rc4.h +++ b/src/wolfssl/openssl/rc4.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ripemd.h b/src/wolfssl/openssl/ripemd.h index 0e80bb3..57ffb81 100644 --- a/src/wolfssl/openssl/ripemd.h +++ b/src/wolfssl/openssl/ripemd.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/rsa.h b/src/wolfssl/openssl/rsa.h index 111a89e..2b81525 100644 --- a/src/wolfssl/openssl/rsa.h +++ b/src/wolfssl/openssl/rsa.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -42,6 +42,17 @@ #define WC_RSA_PKCS1_OAEP_PADDING 1 #define WC_RSA_PKCS1_PSS_PADDING 2 +/* RSA PSS Salt special cases */ +/* Salt length same as digest length */ +#define WC_RSA_PSS_SALTLEN_DIGEST (-1) +/* Old max salt length */ +#define WC_RSA_PSS_SALTLEN_MAX_SIGN (-2) +/* Verification only value to indicate to discover salt length. */ +#define WC_RSA_PSS_SALTLEN_AUTO (-2) +/* Max salt length */ +#define WC_RSA_PSS_SALTLEN_MAX (-3) + + #ifndef OPENSSL_COEXIST /* Padding types */ @@ -60,14 +71,10 @@ #define RSA_FLAG_NO_BLINDING (1 << 7) #define RSA_FLAG_NO_CONSTTIME (1 << 8) -/* Salt length same as digest length */ -#define RSA_PSS_SALTLEN_DIGEST (-1) -/* Old max salt length */ -#define RSA_PSS_SALTLEN_MAX_SIGN (-2) -/* Verification only value to indicate to discover salt length. */ -#define RSA_PSS_SALTLEN_AUTO (-2) -/* Max salt length */ -#define RSA_PSS_SALTLEN_MAX (-3) +#define RSA_PSS_SALTLEN_DIGEST WC_RSA_PSS_SALTLEN_DIGEST +#define RSA_PSS_SALTLEN_MAX_SIGN WC_RSA_PSS_SALTLEN_MAX_SIGN +#define RSA_PSS_SALTLEN_AUTO WC_RSA_PSS_SALTLEN_AUTO +#define RSA_PSS_SALTLEN_MAX WC_RSA_PSS_SALTLEN_MAX #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */ #endif /* !OPENSSL_COEXIST */ @@ -140,21 +147,34 @@ WOLFSSL_API int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa); WOLFSSL_API int wolfSSL_RSA_sign(int type, const unsigned char* m, unsigned int mLen, unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa); -WOLFSSL_API int wolfSSL_RSA_sign_ex(int type, const unsigned char* m, - unsigned int mLen, unsigned char* sigRet, - unsigned int* sigLen, WOLFSSL_RSA* rsa, - int flag); -WOLFSSL_API int wolfSSL_RSA_sign_generic_padding(int type, const unsigned char* m, - unsigned int mLen, unsigned char* sigRet, - unsigned int* sigLen, WOLFSSL_RSA* rsa, int flag, - int padding); -WOLFSSL_API int wolfSSL_RSA_verify(int type, const unsigned char* m, - unsigned int mLen, const unsigned char* sig, - unsigned int sigLen, WOLFSSL_RSA* rsa); -WOLFSSL_API int wolfSSL_RSA_verify_ex(int type, const unsigned char* m, - unsigned int mLen, const unsigned char* sig, - unsigned int sigLen, WOLFSSL_RSA* rsa, - int padding); +WOLFSSL_API int wolfSSL_RSA_sign_ex(int hashAlg, + const unsigned char* hash, unsigned int hLen, + unsigned char* sigRet, unsigned int* sigLen, + WOLFSSL_RSA* rsa, int flag); +WOLFSSL_API int wolfSSL_RSA_sign_generic_padding(int hashAlg, + const unsigned char* hash, unsigned int hLen, + unsigned char* sigRet, unsigned int* sigLen, + WOLFSSL_RSA* rsa, int flag, int padding); + +WOLFSSL_LOCAL int wolfSSL_RSA_sign_mgf(int hashAlg, + const unsigned char* hash, unsigned int hLen, + unsigned char* sigRet, unsigned int* sigLen, + WOLFSSL_RSA* rsa, int flag, int padding, + int mgf1Hash, int saltLen); + +WOLFSSL_API int wolfSSL_RSA_verify(int hashAlg, + const unsigned char* hash, unsigned int hLen, + const unsigned char* sig, unsigned int sigLen, + WOLFSSL_RSA* rsa); +WOLFSSL_API int wolfSSL_RSA_verify_ex(int hashAlg, + const unsigned char* hash, unsigned int hLen, + const unsigned char* sig, unsigned int sigLen, + WOLFSSL_RSA* rsa, int padding); +WOLFSSL_LOCAL int wolfSSL_RSA_verify_mgf(int hashAlg, + const unsigned char* hash, unsigned int hLen, + const unsigned char* sig, unsigned int sigLen, + WOLFSSL_RSA* rsa, int padding, + int mgf1Hash, int saltLen); WOLFSSL_API int wolfSSL_RSA_public_decrypt(int flen, const unsigned char* from, unsigned char* to, WOLFSSL_RSA* rsa, int padding); WOLFSSL_API int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa); diff --git a/src/wolfssl/openssl/safestack.h b/src/wolfssl/openssl/safestack.h index e059a6e..7126af0 100644 --- a/src/wolfssl/openssl/safestack.h +++ b/src/wolfssl/openssl/safestack.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/sha.h b/src/wolfssl/openssl/sha.h index 4644a33..5c1802d 100644 --- a/src/wolfssl/openssl/sha.h +++ b/src/wolfssl/openssl/sha.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/sha3.h b/src/wolfssl/openssl/sha3.h index a970bfd..d3a2c4c 100644 --- a/src/wolfssl/openssl/sha3.h +++ b/src/wolfssl/openssl/sha3.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/srp.h b/src/wolfssl/openssl/srp.h index 978e05d..bd4e154 100644 --- a/src/wolfssl/openssl/srp.h +++ b/src/wolfssl/openssl/srp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/ssl.h b/src/wolfssl/openssl/ssl.h index da16168..326f0fd 100644 --- a/src/wolfssl/openssl/ssl.h +++ b/src/wolfssl/openssl/ssl.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -505,6 +505,7 @@ typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; #define PEM_X509_INFO_read wolfSSL_PEM_X509_INFO_read #define i2d_PrivateKey wolfSSL_i2d_PrivateKey #define i2d_PublicKey wolfSSL_i2d_PublicKey +#define i2d_PrivateKey_bio wolfSSL_i2d_PrivateKey_bio #define i2d_X509_REQ wolfSSL_i2d_X509_REQ #define d2i_X509_REQ wolfSSL_d2i_X509_REQ diff --git a/src/wolfssl/openssl/stack.h b/src/wolfssl/openssl/stack.h index 16f71d3..56b54f3 100644 --- a/src/wolfssl/openssl/stack.h +++ b/src/wolfssl/openssl/stack.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/tls1.h b/src/wolfssl/openssl/tls1.h index b1992fc..20a0459 100644 --- a/src/wolfssl/openssl/tls1.h +++ b/src/wolfssl/openssl/tls1.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/txt_db.h b/src/wolfssl/openssl/txt_db.h index aa05d92..8ad0b18 100644 --- a/src/wolfssl/openssl/txt_db.h +++ b/src/wolfssl/openssl/txt_db.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/x509.h b/src/wolfssl/openssl/x509.h index e1eb78e..c61fbbb 100644 --- a/src/wolfssl/openssl/x509.h +++ b/src/wolfssl/openssl/x509.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/x509_vfy.h b/src/wolfssl/openssl/x509_vfy.h index c26b94d..8cbc0c5 100644 --- a/src/wolfssl/openssl/x509_vfy.h +++ b/src/wolfssl/openssl/x509_vfy.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/openssl/x509v3.h b/src/wolfssl/openssl/x509v3.h index c0ae5cc..123a9e3 100644 --- a/src/wolfssl/openssl/x509v3.h +++ b/src/wolfssl/openssl/x509v3.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -132,6 +132,11 @@ WOLFSSL_API int wolfSSL_X509V3_EXT_print(WOLFSSL_BIO *out, WOLFSSL_X509_EXTENSION *ext, unsigned long flag, int indent); WOLFSSL_API int wolfSSL_X509V3_EXT_add_nconf(WOLFSSL_CONF *conf, WOLFSSL_X509V3_CTX *ctx, const char *section, WOLFSSL_X509 *cert); +WOLFSSL_API WOLFSSL_X509_EXTENSION* wolfSSL_X509v3_get_ext( + const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int loc); +WOLFSSL_API int wolfSSL_X509v3_get_ext_by_NID( + const WOLF_STACK_OF(WOLFSSL_X509_EXTENSION)* sk, int nid, int lastpos); + WOLFSSL_API WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa); #ifndef OPENSSL_COEXIST @@ -218,6 +223,8 @@ typedef struct WOLFSSL_ACCESS_DESCRIPTION ACCESS_DESCRIPTION; #define X509V3_set_ctx_test(ctx) wolfSSL_X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, CTX_TEST) #define X509V3_set_ctx_nodb wolfSSL_X509V3_set_ctx_nodb #define X509v3_get_ext_count wolfSSL_sk_num +#define X509v3_get_ext_by_NID wolfSSL_X509v3_get_ext_by_NID +#define X509v3_get_ext wolfSSL_X509v3_get_ext #endif /* !OPENSSL_COEXIST */ diff --git a/src/wolfssl/quic.h b/src/wolfssl/quic.h index da8c50a..e1dab03 100644 --- a/src/wolfssl/quic.h +++ b/src/wolfssl/quic.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/sniffer.h b/src/wolfssl/sniffer.h index 929fcdc..f91ee66 100644 --- a/src/wolfssl/sniffer.h +++ b/src/wolfssl/sniffer.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -150,6 +150,8 @@ SSL_SNIFFER_API void ssl_InitSniffer_ex2(int threadNum); WOLFSSL_API SSL_SNIFFER_API void ssl_FreeSniffer(void); +WOLFSSL_API +SSL_SNIFFER_API void ssl_RemoveStaleSessions(void); /* ssl_SetPrivateKey typeKs */ enum { @@ -343,6 +345,11 @@ typedef int (*SSLSnifferSecretCb)(unsigned char* client_random, #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */ +WOLFSSL_API +SSL_SNIFFER_API int ssl_RemoveSession(const char* clientIp, int clientPort, + const char* serverIp, int serverPort, + char* error); + #ifdef __cplusplus } /* extern "C" */ diff --git a/src/wolfssl/sniffer_error.h b/src/wolfssl/sniffer_error.h index bb574b4..e6a1852 100644 --- a/src/wolfssl/sniffer_error.h +++ b/src/wolfssl/sniffer_error.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/ssl.h b/src/wolfssl/ssl.h index 908d5c6..3e6865b 100644 --- a/src/wolfssl/ssl.h +++ b/src/wolfssl/ssl.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -1841,6 +1841,12 @@ WOLFSSL_API const char* wolfSSL_ERR_func_error_string(unsigned long e); WOLFSSL_API const char* wolfSSL_ERR_lib_error_string(unsigned long e); /* -------- EXTRAS BEGIN -------- */ +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_EXTRA) +WOLFSSL_API int wolfSSL_X509_STORE_CTX_get_error(WOLFSSL_X509_STORE_CTX* ctx); +WOLFSSL_API int wolfSSL_X509_STORE_CTX_get_error_depth(WOLFSSL_X509_STORE_CTX* ctx); +#endif + #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_API void wolfSSL_ERR_print_errors(WOLFSSL_BIO *bio); @@ -2144,9 +2150,6 @@ WOLFSSL_API int wolfSSL_num_locks(void); WOLFSSL_API WOLFSSL_X509* wolfSSL_X509_STORE_CTX_get_current_cert( WOLFSSL_X509_STORE_CTX* ctx); -WOLFSSL_API int wolfSSL_X509_STORE_CTX_get_error(WOLFSSL_X509_STORE_CTX* ctx); -WOLFSSL_API int wolfSSL_X509_STORE_CTX_get_error_depth(WOLFSSL_X509_STORE_CTX* ctx); - WOLFSSL_API void wolfSSL_X509_STORE_CTX_set_verify_cb(WOLFSSL_X509_STORE_CTX *ctx, WOLFSSL_X509_STORE_CTX_verify_cb verify_cb); WOLFSSL_API void wolfSSL_X509_STORE_set_verify_cb(WOLFSSL_X509_STORE *st, @@ -2323,6 +2326,8 @@ WOLFSSL_API int wolfSSL_i2d_PrivateKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der); WOLFSSL_API int wolfSSL_i2d_PublicKey(const WOLFSSL_EVP_PKEY* key, unsigned char** der); +WOLFSSL_API int wolfSSL_i2d_PrivateKey_bio(WOLFSSL_BIO* bio, + WOLFSSL_EVP_PKEY* key); #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY) WOLFSSL_API int wolfSSL_EVP_PKEY_print_public(WOLFSSL_BIO* out, const WOLFSSL_EVP_PKEY* pkey, @@ -2407,6 +2412,8 @@ WOLFSSL_API void wolfSSL_ASN1_TIME_free(WOLFSSL_ASN1_TIME* t); #endif WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_load_client_CA_file(const char* fname); + +#ifndef WOLFSSL_NO_CA_NAMES WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_CTX_get_client_CA_list( const WOLFSSL_CTX *ctx); /* deprecated function name */ @@ -2418,6 +2425,7 @@ WOLFSSL_API void wolfSSL_set_client_CA_list(WOLFSSL* ssl, WOLF_STACK_OF(WOLFSSL_X509_NAME)*); WOLFSSL_API WOLF_STACK_OF(WOLFSSL_X509_NAME)* wolfSSL_get_client_CA_list( const WOLFSSL* ssl); +#endif /* !WOLFSSL_NO_CA_NAMES */ typedef int (*client_cert_cb)(WOLFSSL *ssl, WOLFSSL_X509 **x509, WOLFSSL_EVP_PKEY **pkey); @@ -3749,6 +3757,7 @@ typedef int (*CbCrlIO)(WOLFSSL_CRL* crl, const char* url, int urlSz); #ifdef HAVE_CRL_UPDATE_CB typedef struct CrlInfo { + byte crlNumber[CRL_MAX_NUM_SZ]; byte *issuerHash; word32 issuerHashLen; byte *lastDate; @@ -3757,7 +3766,7 @@ typedef struct CrlInfo { byte *nextDate; word32 nextDateMaxLen; byte nextDateFormat; - sword32 crlNumber; + byte crlNumberSet:1; } CrlInfo; typedef void (*CbUpdateCRL)(CrlInfo* old, CrlInfo* cnew); @@ -4617,6 +4626,11 @@ enum { * https://github.com/open-quantum-safe/oqs-provider/blob/main/oqs-template/ * oqs-kem-info.md */ +#ifdef WOLFSSL_ML_KEM_USE_OLD_IDS + WOLFSSL_P256_ML_KEM_512_OLD = 12103, + WOLFSSL_P384_ML_KEM_768_OLD = 12104, + WOLFSSL_P521_ML_KEM_1024_OLD = 12105, +#endif WOLFSSL_P256_ML_KEM_512 = 12107, WOLFSSL_P384_ML_KEM_768 = 12108, WOLFSSL_P521_ML_KEM_1024 = 12109, diff --git a/src/wolfssl/test.h b/src/wolfssl/test.h index fa84ab0..ecce217 100644 --- a/src/wolfssl/test.h +++ b/src/wolfssl/test.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -527,6 +527,7 @@ err_sys_with_errno(const char* msg) #define cliEd448CertFile "certs/ed448/client-ed448.pem" #define cliEd448KeyFile "certs/ed448/client-ed448-priv.pem" #define caEd448CertFile "certs/ed448/ca-ed448.pem" +#define noIssuerCertFile "certs/empty-issuer-cert.pem" #define caCertFolder "certs/" #ifdef HAVE_WNR /* Whitewood netRandom default config file */ @@ -590,6 +591,7 @@ err_sys_with_errno(const char* msg) #define cliEd448CertFile "./certs/ed448/client-ed448.pem" #define cliEd448KeyFile "./certs/ed448/client-ed448-priv.pem" #define caEd448CertFile "./certs/ed448/ca-ed448.pem" +#define noIssuerCertFile "./certs/empty-issuer-cert.pem" #define caCertFolder "./certs/" #ifdef HAVE_WNR /* Whitewood netRandom default config file */ @@ -2084,6 +2086,7 @@ static WC_INLINE int my_psk_use_session_cb(WOLFSSL* ssl, numCiphers = sk_num(supportedCiphers); for (i = 0; i < numCiphers; ++i) { + XMEMSET(buf, 0, sizeof(buf)); if ((cipher = (const WOLFSSL_CIPHER*)sk_value(supportedCiphers, i))) { SSL_CIPHER_description(cipher, buf, sizeof(buf)); @@ -2464,14 +2467,14 @@ static THREAD_LS_T int myVerifyAction = VERIFY_OVERRIDE_ERROR; static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) { char err_buffer[WOLFSSL_MAX_ERROR_SZ]; + int err; #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) WOLFSSL_X509* peer; -#if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) && \ - !defined(OPENSSL_EXTRA_X509_SMALL) +#endif +#if defined(OPENSSL_EXTRA) && defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) WOLFSSL_BIO* bio = NULL; WOLFSSL_STACK* sk = NULL; X509* x509 = NULL; -#endif #endif /* Verify Callback Arguments: @@ -2489,10 +2492,17 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) will be discarded (only with SESSION_CERTS) */ - fprintf(stderr, "In verification callback, error = %d, %s\n", store->error, - wolfSSL_ERR_error_string((unsigned long) store->error, err_buffer)); +#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \ + defined(WOLFSSL_EXTRA) + err = wolfSSL_X509_STORE_CTX_get_error(store); +#else + err = store->error; +#endif + + fprintf(stderr, "In verification callback, error = %d, %s\n", err, + wolfSSL_ERR_error_string((unsigned long) err, err_buffer)); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - peer = store->current_cert; + peer = wolfSSL_X509_STORE_CTX_get_current_cert(store); if (peer) { char* issuer = wolfSSL_X509_NAME_oneline( wolfSSL_X509_get_issuer_name(peer), 0, 0); @@ -2512,8 +2522,7 @@ static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store) XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL); XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL); -#if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) && \ - !defined(OPENSSL_EXTRA_X509_SMALL) +#if defined(OPENSSL_EXTRA) && defined(SHOW_CERTS) && !defined(NO_FILESYSTEM) /* avoid printing duplicate certs */ if (store->depth == 1) { int i; diff --git a/src/wolfssl/version.h b/src/wolfssl/version.h index c128a21..656a12e 100644 --- a/src/wolfssl/version.h +++ b/src/wolfssl/version.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -28,8 +28,8 @@ extern "C" { #endif -#define LIBWOLFSSL_VERSION_STRING "5.8.0" -#define LIBWOLFSSL_VERSION_HEX 0x05008000 +#define LIBWOLFSSL_VERSION_STRING "5.8.2" +#define LIBWOLFSSL_VERSION_HEX 0x05008002 #ifdef __cplusplus } diff --git a/src/wolfssl/wolfcrypt/aes.h b/src/wolfssl/wolfcrypt/aes.h index 128611c..90c9f47 100644 --- a/src/wolfssl/wolfcrypt/aes.h +++ b/src/wolfssl/wolfcrypt/aes.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/arc4.h b/src/wolfssl/wolfcrypt/arc4.h index cdddde8..f26f488 100644 --- a/src/wolfssl/wolfcrypt/arc4.h +++ b/src/wolfssl/wolfcrypt/arc4.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ascon.h b/src/wolfssl/wolfcrypt/ascon.h index 196a8ca..e67d995 100644 --- a/src/wolfssl/wolfcrypt/ascon.h +++ b/src/wolfssl/wolfcrypt/ascon.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/asn.h b/src/wolfssl/wolfcrypt/asn.h index e553059..03ebfd3 100644 --- a/src/wolfssl/wolfcrypt/asn.h +++ b/src/wolfssl/wolfcrypt/asn.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -44,12 +44,37 @@ that can be serialized and deserialized in a cross-platform way. #include +#ifdef WOLFSSL_ASYNC_CRYPT + #include +#endif + #ifndef NO_DH #include #endif #ifndef NO_DSA #include #endif +#ifndef NO_RSA + #include +#endif +#ifdef HAVE_ECC + #include +#endif +#ifdef HAVE_ED25519 + #include +#endif +#ifdef HAVE_ED448 + #include +#endif +#ifdef HAVE_SPHINCS + #include +#endif +#ifdef HAVE_FALCON + #include +#endif +#ifdef HAVE_DILITHIUM + #include +#endif #ifndef NO_SHA #include #endif @@ -327,7 +352,7 @@ WOLFSSL_LOCAL int SizeASN_Items(const ASNItem* asn, ASNSetData *data, WOLFSSL_LOCAL int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output); WOLFSSL_LOCAL int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, - int complete, const byte* input, word32* inOutIdx, word32 maxIdx); + int complete, const byte* input, word32* inOutIdx, word32 length); #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK WOLFSSL_LOCAL void GetASN_Int8Bit(ASNGetData *dataASN, byte* num); @@ -789,13 +814,14 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; /* otherName strings */ #define WOLFSSL_SN_MS_UPN "msUPN" #define WOLFSSL_LN_MS_UPN "Microsoft User Principal Name" - #define WOLFSSL_MS_UPN_SUM 265 + #define WOLFSSL_MS_UPN_SUM UPN_OID #define WOLFSSL_SN_DNS_SRV "id-on-dnsSRV" #define WOLFSSL_LN_DNS_SRV "SRVName" + #define WOLFSSL_DNS_SRV_SUM DNS_SRV_OID /* TLS features extension strings */ #define WOLFSSL_SN_TLS_FEATURE "tlsfeature" #define WOLFSSL_LN_TLS_FEATURE "TLS Feature" - #define WOLFSSL_TLS_FEATURE_SUM 92 + #define WOLFSSL_TLS_FEATURE_SUM TLS_FEATURE_OID #endif /* Maximum number of allowed subject alternative names in a certificate. @@ -875,7 +901,7 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WC_SN_sm3 "SM3" /* NIDs */ -#define WC_NID_netscape_cert_type WC_NID_undef +#define WC_NID_netscape_cert_type 71 #define WC_NID_des 66 #define WC_NID_des3 67 #define WC_NID_sha256 672 @@ -898,23 +924,23 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WC_NID_initials 101 /* 2.5.4.43 */ #define WC_NID_title 106 #define WC_NID_description 107 -#define WC_NID_basic_constraints 133 -#define WC_NID_key_usage 129 /* 2.5.29.15 */ -#define WC_NID_ext_key_usage 151 /* 2.5.29.37 */ -#define WC_NID_subject_key_identifier 128 -#define WC_NID_authority_key_identifier 149 -#define WC_NID_private_key_usage_period 130 /* 2.5.29.16 */ -#define WC_NID_subject_alt_name 131 -#define WC_NID_issuer_alt_name 132 -#define WC_NID_info_access 69 -#define WC_NID_sinfo_access 79 /* id-pe 11 */ -#define WC_NID_name_constraints 144 /* 2.5.29.30 */ -#define WC_NID_crl_distribution_points 145 /* 2.5.29.31 */ -#define WC_NID_certificate_policies 146 -#define WC_NID_policy_mappings 147 -#define WC_NID_policy_constraints 150 -#define WC_NID_inhibit_any_policy 168 /* 2.5.29.54 */ -#define WC_NID_tlsfeature 1020 /* id-pe 24 */ +#define WC_NID_basic_constraints BASIC_CA_OID +#define WC_NID_key_usage KEY_USAGE_OID /* 2.5.29.15 */ +#define WC_NID_ext_key_usage EXT_KEY_USAGE_OID /* 2.5.29.37 */ +#define WC_NID_subject_key_identifier SUBJ_KEY_OID +#define WC_NID_authority_key_identifier AUTH_KEY_OID +#define WC_NID_private_key_usage_period PRIV_KEY_USAGE_PERIOD_OID +#define WC_NID_subject_alt_name ALT_NAMES_OID +#define WC_NID_issuer_alt_name ISSUE_ALT_NAMES_OID +#define WC_NID_info_access AUTH_INFO_OID +#define WC_NID_sinfo_access SUBJ_INFO_ACC_OID /* id-pe 11 */ +#define WC_NID_name_constraints NAME_CONS_OID /* 2.5.29.30 */ +#define WC_NID_crl_distribution_points CRL_DIST_OID /* 2.5.29.31 */ +#define WC_NID_certificate_policies CERT_POLICY_OID +#define WC_NID_policy_mappings POLICY_MAP_OID +#define WC_NID_policy_constraints POLICY_CONST_OID +#define WC_NID_inhibit_any_policy INHIBIT_ANY_OID /* 2.5.29.54 */ +#define WC_NID_tlsfeature TLS_FEATURE_OID /* id-pe 24 */ #define WC_NID_buildingName 1494 #define WC_NID_dnQualifier 174 /* 2.5.4.46 */ @@ -940,7 +966,7 @@ extern const WOLFSSL_ObjectInfo wolfssl_object_info[]; #define WC_NID_registeredAddress 870 #define WC_NID_emailAddress 0x30 /* emailAddress */ #define WC_NID_id_on_dnsSRV 82 /* 1.3.6.1.5.5.7.8.7 */ -#define WC_NID_ms_upn 265 /* 1.3.6.1.4.1.311.20.2.3 */ +#define WC_NID_ms_upn UPN_OID /* 1.3.6.1.4.1.311.20.2.3 */ #define WC_NID_X9_62_prime_field 406 /* 1.2.840.10045.1.1 */ @@ -1081,8 +1107,6 @@ enum ECC_TYPES #endif enum Misc_ASN { - MAX_SALT_SIZE = 64, /* MAX PKCS Salt length */ - MAX_IV_SIZE = 64, /* MAX PKCS Iv length */ ASN_BOOL_SIZE = 2, /* including type */ ASN_ECC_HEADER_SZ = 2, /* String type + 1 byte len */ ASN_ECC_CONTEXT_SZ = 2, /* Content specific type + 1 byte len */ @@ -1103,60 +1127,10 @@ enum Misc_ASN { , DSA_PARAM_INTS = 3, /* DSA parameter ints */ RSA_PUB_INTS = 2, /* RSA ints in public key */ - DSA_PUB_INTS = 4, /* DSA ints in public key */ - DSA_INTS = 5, /* DSA ints in private key */ MIN_DATE_SIZE = 12, MAX_DATE_SIZE = 32, ASN_GEN_TIME_SZ = 15, /* 7 numbers * 2 + Zulu tag */ -#ifdef HAVE_SPHINCS - MAX_ENCODED_SIG_SZ = 51200, -#elif defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - MAX_ENCODED_SIG_SZ = 5120, -#elif !defined(NO_RSA) -#ifdef WOLFSSL_HAPROXY - MAX_ENCODED_SIG_SZ = 1024, /* Supports 8192 bit keys */ -#else - MAX_ENCODED_SIG_SZ = 512, /* Supports 4096 bit keys */ -#endif -#elif defined(HAVE_ECC) - MAX_ENCODED_SIG_SZ = 140, -#elif defined(HAVE_CURVE448) - MAX_ENCODED_SIG_SZ = 114, -#else - MAX_ENCODED_SIG_SZ = 64, -#endif - MAX_SIG_SZ = 256, - MAX_ALGO_SZ = 20, - MAX_LENGTH_SZ = WOLFSSL_ASN_MAX_LENGTH_SZ, /* Max length size for DER encoding */ - MAX_SHORT_SZ = (1 + MAX_LENGTH_SZ), /* asn int + byte len + 4 byte length */ - MAX_SEQ_SZ = (1 + MAX_LENGTH_SZ), /* enum(seq | con) + length(5) */ - MAX_SET_SZ = (1 + MAX_LENGTH_SZ), /* enum(set | con) + length(5) */ - MAX_OCTET_STR_SZ = (1 + MAX_LENGTH_SZ), /* enum(set | con) + length(5) */ - MAX_EXP_SZ = (1 + MAX_LENGTH_SZ), /* enum(contextspec|con|exp) + length(5) */ - MAX_PRSTR_SZ = (1 + MAX_LENGTH_SZ), /* enum(prstr) + length(5) */ - MAX_VERSION_SZ = 5, /* enum + id + version(byte) + (header(2))*/ - MAX_ENCODED_DIG_ASN_SZ = (5 + MAX_LENGTH_SZ), /* enum(bit or octet) + length(5) */ - MAX_ENCODED_DIG_SZ = 64 + MAX_ENCODED_DIG_ASN_SZ, /* asn header + sha512 */ - MAX_RSA_INT_SZ = (512 + 1 + MAX_LENGTH_SZ), /* RSA raw sz 4096 for bits + tag + len(5) */ - MAX_DSA_INT_SZ = (384 + 1 + MAX_LENGTH_SZ), /* DSA raw sz 3072 for bits + tag + len(5) */ - MAX_DSA_PUBKEY_SZ = (DSA_PUB_INTS * MAX_DSA_INT_SZ) + (2 * MAX_SEQ_SZ) + - 2 + MAX_LENGTH_SZ, /* Maximum size of a DSA public - key taken from wc_SetDsaPublicKey. */ - MAX_DSA_PRIVKEY_SZ = (DSA_INTS * MAX_DSA_INT_SZ) + MAX_SEQ_SZ + - MAX_VERSION_SZ, /* Maximum size of a DSA Private - key taken from DsaKeyIntsToDer. */ -#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - MAX_PQC_PUBLIC_KEY_SZ = 2592, /* Maximum size of a Dilithium public key. */ -#endif - MAX_RSA_E_SZ = 16, /* Max RSA public e size */ - MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */ - MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */ - MAX_DER_DIGEST_SZ = MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, - /* Maximum DER digest size */ - MAX_DER_DIGEST_ASN_SZ = MAX_ENCODED_DIG_ASN_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, - /* Maximum DER digest ASN header size */ - /* Max X509 header length indicates the max length + 2 ('\n', '\0') */ - MAX_X509_HEADER_SZ = (37 + 2), /* Maximum PEM Header/Footer Size */ + #ifdef WOLFSSL_CERT_GEN #ifdef WOLFSSL_CERT_REQ /* Max encoded cert req attributes length */ @@ -1169,12 +1143,14 @@ enum Misc_ASN { #else MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + MAX_CA_SZ, #endif - /* Max total extensions, id + len + others */ + /* Max total extensions, id + len + others */ +#endif +#ifndef MAX_OID_SZ + MAX_OID_SZ = 32, /* Max DER length of OID*/ #endif #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \ defined(HAVE_PKCS7) || defined(OPENSSL_EXTRA_X509_SMALL) || \ defined(HAVE_OID_DECODING) || defined(HAVE_OID_ENCODING) - MAX_OID_SZ = 32, /* Max DER length of OID*/ MAX_OID_STRING_SZ = 64, /* Max string length representation of OID*/ #endif #ifdef WOLFSSL_CERT_EXT @@ -1194,16 +1170,6 @@ enum Misc_ASN { OCSP_NONCE_EXT_SZ = 35, /* OCSP Nonce Extension size */ MAX_OCSP_EXT_SZ = 58, /* Max OCSP Extension length */ MAX_OCSP_NONCE_SZ = 16, /* OCSP Nonce size */ -#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) - MAX_PUBLIC_KEY_SZ = MAX_PQC_PUBLIC_KEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, -#else - MAX_PUBLIC_KEY_SZ = MAX_DSA_PUBKEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, -#endif -#ifdef WOLFSSL_ENCRYPTED_KEYS - HEADER_ENCRYPTED_KEY_SIZE = 88,/* Extra header size for encrypted key */ -#else - HEADER_ENCRYPTED_KEY_SIZE = 0, -#endif TRAILING_ZERO = 1, /* Used for size of zero pad */ ASN_TAG_SZ = 1, /* single byte ASN.1 tag */ ASN_INDEF_END_SZ = 2, /* 0x00 0x00 at end of indef */ @@ -1220,6 +1186,7 @@ enum Misc_ASN { #endif PKCS5_SALT_SZ = 8, + PKCS5V2_SALT_SZ = 16, PEM_LINE_SZ = 64, /* Length of Base64 encoded line, not including new line */ PEM_LINE_LEN = PEM_LINE_SZ + 12, /* PEM line max + fudge */ @@ -1267,375 +1234,6 @@ enum Oid_Types { }; -enum Hash_Sum { - MD2h = 646, - MD4h = 648, - MD5h = 649, - SHAh = 88, - SHA224h = 417, - SHA256h = 414, - SHA384h = 415, - SHA512h = 416, - SHA512_224h = 418, - SHA512_256h = 419, - SHA3_224h = 420, - SHA3_256h = 421, - SHA3_384h = 422, - SHA3_512h = 423, - SHAKE128h = 424, - SHAKE256h = 425, - SM3h = 640 -}; - -#if !defined(NO_DES3) || !defined(NO_AES) -enum Block_Sum { -#ifdef WOLFSSL_AES_128 - AES128CBCb = 414, - AES128GCMb = 418, - AES128CCMb = 419, -#endif -#ifdef WOLFSSL_AES_192 - AES192CBCb = 434, - AES192GCMb = 438, - AES192CCMb = 439, -#endif -#ifdef WOLFSSL_AES_256 - AES256CBCb = 454, - AES256GCMb = 458, - AES256CCMb = 459, -#endif -#ifndef NO_DES3 - DESb = 69, - DES3b = 652 -#endif -}; -#endif /* !NO_DES3 || !NO_AES */ - - -enum Key_Sum { - ANONk = 0, - DSAk = 515, - RSAk = 645, - RSAPSSk = 654, - RSAESOAEPk = 651, /* 1.2.840.113549.1.1.7 */ - ECDSAk = 518, - SM2k = 667, - ED25519k = 256, /* 1.3.101.112 */ - X25519k = 254, /* 1.3.101.110 */ - ED448k = 257, /* 1.3.101.113 */ - X448k = 255, /* 1.3.101.111 */ - DHk = 647, /* dhKeyAgreement OID: 1.2.840.113549.1.3.1 */ - FALCON_LEVEL1k = 273, /* 1.3.9999.3.6 */ - FALCON_LEVEL5k = 276, /* 1.3.9999.3.9 */ - DILITHIUM_LEVEL2k = 218, /* 1.3.6.1.4.1.2.267.12.4.4 */ - DILITHIUM_LEVEL3k = 221, /* 1.3.6.1.4.1.2.267.12.6.5 */ - DILITHIUM_LEVEL5k = 225, /* 1.3.6.1.4.1.2.267.12.8.7 */ - ML_DSA_LEVEL2k = 431, /* 2.16.840.1.101.3.4.3.17 */ - ML_DSA_LEVEL3k = 432, /* 2.16.840.1.101.3.4.3.18 */ - ML_DSA_LEVEL5k = 433, /* 2.16.840.1.101.3.4.3.19 */ - SPHINCS_FAST_LEVEL1k = 281, /* 1 3 9999 6 7 4 */ - SPHINCS_FAST_LEVEL3k = 283, /* 1 3 9999 6 8 3 + 2 (See GetOID() in asn.c) */ - SPHINCS_FAST_LEVEL5k = 282, /* 1 3 9999 6 9 3 */ - SPHINCS_SMALL_LEVEL1k = 287, /* 1 3 9999 6 7 10 */ - SPHINCS_SMALL_LEVEL3k = 285, /* 1 3 9999 6 8 7 */ - SPHINCS_SMALL_LEVEL5k = 286 /* 1 3 9999 6 9 7 */ -}; - -#if !defined(NO_AES) || defined(HAVE_PKCS7) -enum KeyWrap_Sum { -#ifdef WOLFSSL_AES_128 - AES128_WRAP = 417, -#endif -#ifdef WOLFSSL_AES_192 - AES192_WRAP = 437, -#endif -#ifdef WOLFSSL_AES_256 - AES256_WRAP = 457, -#endif -#ifdef HAVE_PKCS7 - PWRI_KEK_WRAP = 680 /*id-alg-PWRI-KEK, 1.2.840.113549.1.9.16.3.9 */ -#endif -}; -#endif /* !NO_AES || PKCS7 */ - -enum Key_Agree { - dhSinglePass_stdDH_sha1kdf_scheme = 464, - dhSinglePass_stdDH_sha224kdf_scheme = 188, - dhSinglePass_stdDH_sha256kdf_scheme = 189, - dhSinglePass_stdDH_sha384kdf_scheme = 190, - dhSinglePass_stdDH_sha512kdf_scheme = 191 -}; - - - -enum KDF_Sum { - PBKDF2_OID = 660, - MGF1_OID = 652 -}; - - -enum HMAC_Sum { - HMAC_SHA224_OID = 652, - HMAC_SHA256_OID = 653, - HMAC_SHA384_OID = 654, - HMAC_SHA512_OID = 655, - HMAC_SHA3_224_OID = 426, - HMAC_SHA3_256_OID = 427, - HMAC_SHA3_384_OID = 428, - HMAC_SHA3_512_OID = 429 -}; - - -enum Extensions_Sum { - BASIC_CA_OID = 133, /* 2.5.29.19 */ - ALT_NAMES_OID = 131, /* 2.5.29.17 */ - CRL_DIST_OID = 145, /* 2.5.29.31 */ - AUTH_INFO_OID = 69, /* 1.3.6.1.5.5.7.1.1 */ - AUTH_KEY_OID = 149, /* 2.5.29.35 */ - SUBJ_KEY_OID = 128, /* 2.5.29.14 */ - CERT_POLICY_OID = 146, /* 2.5.29.32 */ - CRL_NUMBER_OID = 134, /* 2.5.29.20 */ - KEY_USAGE_OID = 129, /* 2.5.29.15 */ - INHIBIT_ANY_OID = 168, /* 2.5.29.54 */ - EXT_KEY_USAGE_OID = 151, /* 2.5.29.37 */ - NAME_CONS_OID = 144, /* 2.5.29.30 */ - PRIV_KEY_USAGE_PERIOD_OID = 130, /* 2.5.29.16 */ - SUBJ_INFO_ACC_OID = 79, /* 1.3.6.1.5.5.7.1.11 */ - POLICY_MAP_OID = 147, /* 2.5.29.33 */ - POLICY_CONST_OID = 150, /* 2.5.29.36 */ - ISSUE_ALT_NAMES_OID = 132, /* 2.5.29.18 */ - TLS_FEATURE_OID = 92, /* 1.3.6.1.5.5.7.1.24 */ - NETSCAPE_CT_OID = 753, /* 2.16.840.1.113730.1.1 */ - OCSP_NOCHECK_OID = 121, /* 1.3.6.1.5.5.7.48.1.5 - id-pkix-ocsp-nocheck */ - SUBJ_DIR_ATTR_OID = 123, /* 2.5.29.9 */ - - AKEY_PACKAGE_OID = 1048, /* 2.16.840.1.101.2.1.2.78.5 - RFC 5958 - Asymmetric Key Packages */ - FASCN_OID = 419, /* 2.16.840.1.101.3.6.6 Federal PKI Policy FASC-N */ - UPN_OID = 265, /* 1.3.6.1.4.1.311.20.2.3 UPN */ -#ifdef WOLFSSL_DUAL_ALG_CERTS - SUBJ_ALT_PUB_KEY_INFO_OID = 186, /* 2.5.29.72 subject alt public key info */ - ALT_SIG_ALG_OID = 187, /* 2.5.29.73 alt sig alg */ - ALT_SIG_VAL_OID = 188, /* 2.5.29.74 alt sig val */ -#endif - WOLF_ENUM_DUMMY_LAST_ELEMENT(Extensions_Sum) -}; - -enum CertificatePolicy_Sum { - CP_ANY_OID = 146, /* id-ce 32 0 */ - CP_ISRG_DOMAIN_VALID = 430, /* 1.3.6.1.4.1.44947.1.1.1 */ -#ifdef WOLFSSL_FPKI - /* Federal PKI OIDs */ - CP_FPKI_HIGH_ASSURANCE_OID = 417, /* 2.16.840.1.101.3.2.1.3.4 */ - CP_FPKI_COMMON_HARDWARE_OID = 420, /* 2.16.840.1.101.3.2.1.3.7 */ - CP_FPKI_MEDIUM_HARDWARE_OID = 425, /* 2.16.840.1.101.3.2.1.3.12 */ - CP_FPKI_COMMON_AUTH_OID = 426, /* 2.16.840.1.101.3.2.1.3.13 */ - CP_FPKI_COMMON_HIGH_OID = 429, /* 2.16.840.1.101.3.2.1.3.16 */ - CP_FPKI_PIVI_HARDWARE_OID = 431, /* 2.16.840.1.101.3.2.1.3.18 */ - CP_FPKI_PIVI_CONTENT_SIGNING_OID = 433, /* 2.16.840.1.101.3.2.1.3.20 */ - CP_FPKI_COMMON_DEVICES_HARDWARE_OID = 449, /* 2.16.840.1.101.3.2.1.3.36 */ - CP_FPKI_MEDIUM_DEVICE_HARDWARE_OID = 451, /* 2.16.840.1.101.3.2.1.3.38 */ - CP_FPKI_COMMON_PIV_CONTENT_SIGNING_OID = 452, /* 2.16.840.1.101.3.2.1.3.39 */ - CP_FPKI_PIV_AUTH_OID = 453, /* 2.16.840.1.101.3.2.1.3.40 */ - CP_FPKI_PIV_AUTH_HW_OID = 454, /* 2.16.840.1.101.3.2.1.3.41 */ - CP_FPKI_PIVI_AUTH_OID = 458, /* 2.16.840.1.101.3.2.1.3.45 */ - CP_FPKI_COMMON_PIVI_CONTENT_SIGNING_OID = 460, /* 2.16.840.1.101.3.2.1.3.47 */ - - /* Federal PKI Test OIDs */ - CP_FPKI_AUTH_TEST_OID = 469, /* 2.16.840.1.101.3.2.1.48.11 */ - CP_FPKI_CARDAUTH_TEST_OID = 471, /* 2.16.840.1.101.3.2.1.48.13 */ - CP_FPKI_PIV_CONTENT_TEST_OID = 544, /* 2.16.840.1.101.3.2.1.48.86 */ - CP_FPKI_PIV_AUTH_DERIVED_TEST_OID = 567, /* 2.16.840.1.101.3.2.1.48.109 */ - CP_FPKI_PIV_AUTH_DERIVED_HW_TEST_OID = 568, /* 2.16.840.1.101.3.2.1.48.110 */ - - /* DoD PKI OIDs */ - CP_DOD_MEDIUM_OID = 423, /* 2.16.840.1.101.2.1.11.5 */ - CP_DOD_MEDIUM_HARDWARE_OID = 427, /* 2.16.840.1.101.2.1.11.9 */ - CP_DOD_PIV_AUTH_OID = 428, /* 2.16.840.1.101.2.1.11.10 */ - CP_DOD_MEDIUM_NPE_OID = 435, /* 2.16.840.1.101.2.1.11.17 */ - CP_DOD_MEDIUM_2048_OID = 436, /* 2.16.840.1.101.2.1.11.18 */ - CP_DOD_MEDIUM_HARDWARE_2048_OID = 437, /* 2.16.840.1.101.2.1.11.19 */ - CP_DOD_PIV_AUTH_2048_OID = 438, /* 2.16.840.1.101.2.1.11.20 */ - CP_DOD_PEER_INTEROP_OID = 100449, /* 2.16.840.1.101.2.1.11.31 */ - CP_DOD_MEDIUM_NPE_112_OID = 100454, /* 2.16.840.1.101.2.1.11.36 */ - CP_DOD_MEDIUM_NPE_128_OID = 455, /* 2.16.840.1.101.2.1.11.37 */ - CP_DOD_MEDIUM_NPE_192_OID = 456, /* 2.16.840.1.101.2.1.11.38 */ - CP_DOD_MEDIUM_112_OID = 457, /* 2.16.840.1.101.2.1.11.39 */ - CP_DOD_MEDIUM_128_OID = 100458, /* 2.16.840.1.101.2.1.11.40 */ - CP_DOD_MEDIUM_192_OID = 459, /* 2.16.840.1.101.2.1.11.41 */ - CP_DOD_MEDIUM_HARDWARE_112_OID = 100460, /* 2.16.840.1.101.2.1.11.42 */ - CP_DOD_MEDIUM_HARDWARE_128_OID = 461, /* 2.16.840.1.101.2.1.11.43 */ - CP_DOD_MEDIUM_HARDWARE_192_OID = 462, /* 2.16.840.1.101.2.1.11.44 */ - CP_DOD_ADMIN_OID = 477, /* 2.16.840.1.101.2.1.11.59 */ - CP_DOD_INTERNAL_NPE_112_OID = 478, /* 2.16.840.1.101.2.1.11.60 */ - CP_DOD_INTERNAL_NPE_128_OID = 479, /* 2.16.840.1.101.2.1.11.61 */ - CP_DOD_INTERNAL_NPE_192_OID = 480, /* 2.16.840.1.101.2.1.11.62 */ - - /* ECA PKI OIDs */ - CP_ECA_MEDIUM_OID = 100423, /* 2.16.840.1.101.3.2.1.12.1 */ - CP_ECA_MEDIUM_HARDWARE_OID = 424, /* 2.16.840.1.101.3.2.1.12.2 */ - CP_ECA_MEDIUM_TOKEN_OID = 100425, /* 2.16.840.1.101.3.2.1.12.3 */ - CP_ECA_MEDIUM_SHA256_OID = 100426, /* 2.16.840.1.101.3.2.1.12.4 */ - CP_ECA_MEDIUM_TOKEN_SHA256_OID = 100427, /* 2.16.840.1.101.3.2.1.12.5 */ - CP_ECA_MEDIUM_HARDWARE_PIVI_OID = 100428, /* 2.16.840.1.101.3.2.1.12.6 */ - CP_ECA_CONTENT_SIGNING_PIVI_OID = 100430, /* 2.16.840.1.101.3.2.1.12.8 */ - CP_ECA_MEDIUM_DEVICE_SHA256_OID = 431, /* 2.16.840.1.101.3.2.1.12.9 */ - CP_ECA_MEDIUM_HARDWARE_SHA256_OID = 432, /* 2.16.840.1.101.3.2.1.12.10 */ - - /* Department of State PKI OIDs */ - CP_STATE_BASIC_OID = 100417, /* 2.16.840.1.101.3.2.1.6.1 */ - CP_STATE_LOW_OID = 418, /* 2.16.840.1.101.3.2.1.6.2 */ - CP_STATE_MODERATE_OID = 100419, /* 2.16.840.1.101.3.2.1.6.3 */ - CP_STATE_HIGH_OID = 100420, /* 2.16.840.1.101.3.2.1.6.4 */ - CP_STATE_MEDHW_OID = 101428, /* 2.16.840.1.101.3.2.1.6.12 */ - CP_STATE_MEDDEVHW_OID = 101454, /* 2.16.840.1.101.3.2.1.6.38 */ - - /* U.S. Treasury SSP PKI OIDs */ - CP_TREAS_MEDIUMHW_OID = 419, /* 2.16.840.1.101.3.2.1.5.4 */ - CP_TREAS_HIGH_OID = 101420, /* 2.16.840.1.101.3.2.1.5.5 */ - CP_TREAS_PIVI_HW_OID = 101425, /* 2.16.840.1.101.3.2.1.5.10 */ - CP_TREAS_PIVI_CONTENT_OID = 101427, /* 2.16.840.1.101.3.2.1.5.12 */ - - /* Boeing PKI OIDs */ - CP_BOEING_MEDIUMHW_SHA256_OID = 159, /* 1.3.6.1.4.1.73.15.3.1.12 */ - CP_BOEING_MEDIUMHW_CONTENT_SHA256_OID = 164, /* 1.3.6.1.4.1.73.15.3.1.17 */ - - /* Carillon Federal Services OIDs */ - CP_CARILLON_MEDIUMHW_256_OID = 467, /* 1.3.6.1.4.1.45606.3.1.12 */ - CP_CARILLON_AIVHW_OID = 475, /* 1.3.6.1.4.1.45606.3.1.20 */ - CP_CARILLON_AIVCONTENT_OID = 100477, /* 1.3.6.1.4.1.45606.3.1.22 */ - - /* Carillon Information Security OIDs */ - CP_CIS_MEDIUMHW_256_OID = 489, /* 1.3.6.1.4.1.25054.3.1.12 */ - CP_CIS_MEDDEVHW_256_OID = 491, /* 1.3.6.1.4.1.25054.3.1.14 */ - CP_CIS_ICECAP_HW_OID = 497, /* 1.3.6.1.4.1.25054.3.1.20 */ - CP_CIS_ICECAP_CONTENT_OID = 499, /* 1.3.6.1.4.1.25054.3.1.22 */ - - /* CertiPath Bridge OIDs */ - CP_CERTIPATH_MEDIUMHW_OID = 100459, /* 1.3.6.1.4.1.24019.1.1.1.2 */ - CP_CERTIPATH_HIGHHW_OID = 101460, /* 1.3.6.1.4.1.24019.1.1.1.3 */ - CP_CERTIPATH_ICECAP_HW_OID = 464, /* 1.3.6.1.4.1.24019.1.1.1.7 */ - CP_CERTIPATH_ICECAP_CONTENT_OID = 466, /* 1.3.6.1.4.1.24019.1.1.1.9 */ - CP_CERTIPATH_VAR_MEDIUMHW_OID = 100475, /* 1.3.6.1.4.1.24019.1.1.1.18 */ - CP_CERTIPATH_VAR_HIGHHW_OID = 476, /* 1.3.6.1.4.1.24019.1.1.1.19 */ - - /* TSCP Bridge OIDs */ - CP_TSCP_MEDIUMHW_OID = 442, /* 1.3.6.1.4.1.38099.1.1.1.2 */ - CP_TSCP_PIVI_OID = 445, /* 1.3.6.1.4.1.38099.1.1.1.5 */ - CP_TSCP_PIVI_CONTENT_OID = 447, /* 1.3.6.1.4.1.38099.1.1.1.7 */ - - /* DigiCert NFI PKI OIDs */ - CP_DIGICERT_NFSSP_MEDIUMHW_OID = 796, /* 2.16.840.1.113733.1.7.23.3.1.7 */ - CP_DIGICERT_NFSSP_AUTH_OID = 802, /* 2.16.840.1.113733.1.7.23.3.1.13 */ - CP_DIGICERT_NFSSP_PIVI_HW_OID = 807, /* 2.16.840.1.113733.1.7.23.3.1.18 */ - CP_DIGICERT_NFSSP_PIVI_CONTENT_OID = 809, /* 2.16.840.1.113733.1.7.23.3.1.20 */ - CP_DIGICERT_NFSSP_MEDDEVHW_OID = 825, /* 2.16.840.1.113733.1.7.23.3.1.36 */ - - /* Entrust Managed Services NFI PKI OIDs */ - CP_ENTRUST_NFSSP_MEDIUMHW_OID = 1017, /* 2.16.840.1.114027.200.3.10.7.2 */ - CP_ENTRUST_NFSSP_MEDAUTH_OID = 1019, /* 2.16.840.1.114027.200.3.10.7.4 */ - CP_ENTRUST_NFSSP_PIVI_HW_OID = 1021, /* 2.16.840.1.114027.200.3.10.7.6 */ - CP_ENTRUST_NFSSP_PIVI_CONTENT_OID = 1024, /* 2.16.840.1.114027.200.3.10.7.9 */ - CP_ENTRUST_NFSSP_MEDDEVHW_OID = 1031, /* 2.16.840.1.114027.200.3.10.7.16 */ - - /* Exostar LLC PKI OIDs */ - CP_EXOSTAR_MEDIUMHW_SHA2_OID = 100424, /* 1.3.6.1.4.1.13948.1.1.1.6 */ - - /* IdenTrust NFI OIDs */ - CP_IDENTRUST_MEDIUMHW_SIGN_OID = 846, /* 2.16.840.1.113839.0.100.12.1 */ - CP_IDENTRUST_MEDIUMHW_ENC_OID = 847, /* 2.16.840.1.113839.0.100.12.2 */ - CP_IDENTRUST_PIVI_HW_ID_OID = 851, /* 2.16.840.1.113839.0.100.18.0 */ - CP_IDENTRUST_PIVI_HW_SIGN_OID = 852, /* 2.16.840.1.113839.0.100.18.1 */ - CP_IDENTRUST_PIVI_HW_ENC_OID = 853, /* 2.16.840.1.113839.0.100.18.2 */ - CP_IDENTRUST_PIVI_CONTENT_OID = 854, /* 2.16.840.1.113839.0.100.20.1 */ - - /* Lockheed Martin PKI OIDs */ - CP_LOCKHEED_MEDIUMHW_OID = 266, /* 1.3.6.1.4.1.103.100.1.1.3.3 */ - - /* Northrop Grumman PKI OIDs */ - CP_NORTHROP_MEDIUM_256_HW_OID = 654, /* 1.3.6.1.4.1.16334.509.2.8 */ - CP_NORTHROP_PIVI_256_HW_OID = 655, /* 1.3.6.1.4.1.16334.509.2.9 */ - CP_NORTHROP_PIVI_256_CONTENT_OID = 657, /* 1.3.6.1.4.1.16334.509.2.11 */ - CP_NORTHROP_MEDIUM_384_HW_OID = 660, /* 1.3.6.1.4.1.16334.509.2.14 */ - - /* Raytheon PKI OIDs */ - CP_RAYTHEON_MEDIUMHW_OID = 251, /* 1.3.6.1.4.1.1569.10.1.12 */ - CP_RAYTHEON_MEDDEVHW_OID = 257, /* 1.3.6.1.4.1.1569.10.1.18 */ - CP_RAYTHEON_SHA2_MEDIUMHW_OID = 433, /* 1.3.6.1.4.1.26769.10.1.12 */ - CP_RAYTHEON_SHA2_MEDDEVHW_OID = 439, /* 1.3.6.1.4.1.26769.10.1.18 */ - - /* WidePoint NFI PKI OIDs */ - CP_WIDEPOINT_MEDIUMHW_OID = 310, /* 1.3.6.1.4.1.3922.1.1.1.12 */ - CP_WIDEPOINT_PIVI_HW_OID = 316, /* 1.3.6.1.4.1.3922.1.1.1.18 */ - CP_WIDEPOINT_PIVI_CONTENT_OID = 318, /* 1.3.6.1.4.1.3922.1.1.1.20 */ - CP_WIDEPOINT_MEDDEVHW_OID = 336, /* 1.3.6.1.4.1.3922.1.1.1.38 */ - - /* Australian Defence Organisation PKI OIDs */ - CP_ADO_MEDIUM_OID = 293, /* 1.2.36.1.334.1.2.1.2 */ - CP_ADO_HIGH_OID = 294, /* 1.2.36.1.334.1.2.1.3 */ - CP_ADO_RESOURCE_MEDIUM_OID = 100294, /* 1.2.36.1.334.1.2.2.2 */ - - /* Comodo Ltd PKI OID */ - CP_COMODO_OID = 100293, /* 1.3.6.1.4.1.6449.1.2.1.3.4 */ - - /* Netherlands Ministry of Defence PKI OIDs */ - CP_NL_MOD_AUTH_OID = 496, /* 2.16.528.1.1003.1.2.5.1 */ - CP_NL_MOD_IRREFUT_OID = 100497, /* 2.16.528.1.1003.1.2.5.2 */ - CP_NL_MOD_CONFID_OID = 498, /* 2.16.528.1.1003.1.2.5.3 */ -#endif /* WOLFSSL_FPKI */ - WOLF_ENUM_DUMMY_LAST_ELEMENT(CertificatePolicy_Sum) -}; - -enum SepHardwareName_Sum { - HW_NAME_OID = 79 /* 1.3.6.1.5.5.7.8.4 from RFC 4108*/ -}; - -enum AuthInfo_Sum { - AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1, id-ad-ocsp */ - AIA_CA_ISSUER_OID = 117, /* 1.3.6.1.5.5.7.48.2, id-ad-caIssuers */ - #ifdef WOLFSSL_SUBJ_INFO_ACC - AIA_CA_REPO_OID = 120, /* 1.3.6.1.5.5.7.48.5, id-ad-caRepository */ - #endif /* WOLFSSL_SUBJ_INFO_ACC */ - WOLF_ENUM_DUMMY_LAST_ELEMENT(AuthInfo_Sum) -}; - -#define ID_PKIX(num) (67+(num)) /* 1.3.6.1.5.5.7.num, id-pkix num */ -#define ID_KP(num) (ID_PKIX(3)+(num)) /* 1.3.6.1.5.5.7.3.num, id-kp num */ -enum ExtKeyUsage_Sum { /* From RFC 5280 */ - EKU_ANY_OID = 151, /* 2.5.29.37.0, anyExtendedKeyUsage */ - EKU_SERVER_AUTH_OID = 71, /* 1.3.6.1.5.5.7.3.1, id-kp-serverAuth */ - EKU_CLIENT_AUTH_OID = 72, /* 1.3.6.1.5.5.7.3.2, id-kp-clientAuth */ - EKU_CODESIGNING_OID = 73, /* 1.3.6.1.5.5.7.3.3, id-kp-codeSigning */ - EKU_EMAILPROTECT_OID = 74, /* 1.3.6.1.5.5.7.3.4, id-kp-emailProtection */ - EKU_TIMESTAMP_OID = 78, /* 1.3.6.1.5.5.7.3.8, id-kp-timeStamping */ - EKU_OCSP_SIGN_OID = 79, /* 1.3.6.1.5.5.7.3.9, id-kp-OCSPSigning */ - - /* From RFC 6187: X.509v3 Certificates for Secure Shell Authentication */ - EKU_SSH_CLIENT_AUTH_OID = ID_KP(21), /* id-kp-secureShellClient */ - EKU_SSH_MSCL_OID = 264, - /* 1.3.6.1.4.1.311.20.2.2, MS Smart Card Logon */ - EKU_SSH_KP_CLIENT_AUTH_OID = 64 - /* 1.3.6.1.5.2.3.4, id-pkinit-KPClientAuth*/ -}; - -#ifdef WOLFSSL_SUBJ_DIR_ATTR -#define ID_PDA(num) (ID_PKIX(9)+(num)) /* 1.3.6.1.5.5.7.9.num, id-pda num */ -enum SubjDirAttr_Sum { /* From RFC 3739, section 3.3.2 */ - SDA_DOB_OID = ID_PDA(1), /* id-pda-dateOfBirth */ - SDA_POB_OID = ID_PDA(2), /* id-pda-placeOfBirth */ - SDA_GENDER_OID = ID_PDA(3), /* id-pda-gender */ - SDA_COC_OID = ID_PDA(4), /* id-pda-countryOfCitizenship */ - SDA_COR_OID = ID_PDA(5) /* id-pda-countryOfResidence */ -}; -#endif /* WOLFSSL_SUBJ_DIR_ATTR */ - -#ifdef HAVE_LIBZ -enum CompressAlg_Sum { - ZLIBc = 679 /* 1.2.840.113549.1.9.16.3.8, id-alg-zlibCompress */ -}; -#endif - enum VerifyType { NO_VERIFY = 0, VERIFY = 1, @@ -1653,22 +1251,6 @@ enum KeyIdType { }; #endif -#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_NAME_ALL) -enum CsrAttrType { - UNSTRUCTURED_NAME_OID = 654, - PKCS9_CONTENT_TYPE_OID = 655, - CHALLENGE_PASSWORD_OID = 659, - SERIAL_NUMBER_OID = 94, - EXTENSION_REQUEST_OID = 666, - USER_ID_OID = 865, - DNQUALIFIER_OID = 135, - INITIALS_OID = 132, - SURNAME_OID = 93, - NAME_OID = 130, - GIVEN_NAME_OID = 131 -}; -#endif - /* Key usage extension bits (based on RFC 5280) */ #define KEYUSE_DIGITAL_SIG 0x0080 #define KEYUSE_CONTENT_COMMIT 0x0040 @@ -1791,12 +1373,20 @@ typedef struct tagCertAttribute { struct SignatureCtx { void* heap; + #ifdef WOLFSSL_NO_MALLOC + byte digest[WC_MAX_DIGEST_SIZE]; + #else byte* digest; + #endif #ifndef NO_RSA byte* out; #endif -#if !(defined(NO_RSA) && defined(NO_DSA)) +#if !defined(NO_RSA) || !defined(NO_DSA) + #ifdef WOLFSSL_NO_MALLOC + byte sigCpy[MAX_SIG_SZ]; + #else byte* sigCpy; + #endif #endif #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \ !defined(NO_DSA) || defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) || \ @@ -1805,30 +1395,64 @@ struct SignatureCtx { #endif union { #ifndef NO_RSA + #ifdef WOLFSSL_NO_MALLOC + struct RsaKey rsa[1]; + #else struct RsaKey* rsa; + #endif #endif #ifndef NO_DSA + #ifdef WOLFSSL_NO_MALLOC + struct DsaKey dsa[1]; + #else struct DsaKey* dsa; + #endif #endif #ifdef HAVE_ECC + #ifdef WOLFSSL_NO_MALLOC + struct ecc_key ecc[1]; + #else struct ecc_key* ecc; + #endif #endif #ifdef HAVE_ED25519 + #ifdef WOLFSSL_NO_MALLOC + struct ed25519_key ed25519[1]; + #else struct ed25519_key* ed25519; + #endif #endif #ifdef HAVE_ED448 + #ifdef WOLFSSL_NO_MALLOC + struct ed448_key ed448[1]; + #else struct ed448_key* ed448; + #endif #endif - #if defined(HAVE_FALCON) + #ifdef HAVE_FALCON + #ifdef WOLFSSL_NO_MALLOC + struct falcon_key falcon[1]; + #else struct falcon_key* falcon; + #endif #endif - #if defined(HAVE_DILITHIUM) + #ifdef HAVE_DILITHIUM + #ifdef WOLFSSL_NO_MALLOC + struct dilithium_key dilithium[1]; + #else struct dilithium_key* dilithium; + #endif #endif - #if defined(HAVE_SPHINCS) + #ifdef HAVE_SPHINCS + #ifdef WOLFSSL_NO_MALLOC + struct sphincs_key sphincs[1]; + #else struct sphincs_key* sphincs; + #endif #endif + #ifndef WOLFSSL_NO_MALLOC void* ptr; + #endif } key; int devId; int state; @@ -1863,23 +1487,6 @@ struct SignatureCtx { #endif }; -enum CertSignState { - CERTSIGN_STATE_BEGIN, - CERTSIGN_STATE_DIGEST, - CERTSIGN_STATE_ENCODE, - CERTSIGN_STATE_DO -}; - -struct CertSignCtx { - byte* sig; - byte* digest; - #ifndef NO_RSA - byte* encSig; - int encSigSz; - #endif - int state; /* enum CertSignState */ -}; - #define DOMAIN_COMPONENT_MAX 10 struct DecodedName { @@ -1961,7 +1568,6 @@ typedef struct Signer Signer; typedef struct TrustedPeerCert TrustedPeerCert; #endif /* WOLFSSL_TRUST_PEER_CERT */ typedef struct SignatureCtx SignatureCtx; -typedef struct CertSignCtx CertSignCtx; #ifdef WC_ASN_UNKNOWN_EXT_CB typedef int (*wc_UnknownExtCallback)(const word16* oid, word32 oidSz, int crit, @@ -2544,29 +2150,33 @@ WOLFSSL_LOCAL void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap); #endif /* WOLFSSL_TRUST_PEER_CERT */ -WOLFSSL_ASN_API int ToTraditional(byte* buffer, word32 length); -WOLFSSL_ASN_API int ToTraditional_ex(byte* buffer, word32 length, - word32* algId); +WOLFSSL_ASN_API int ToTraditional(byte* input, word32 sz); +WOLFSSL_ASN_API int ToTraditional_ex(byte* input, word32 sz, word32* algId); WOLFSSL_LOCAL int ToTraditionalInline(const byte* input, word32* inOutIdx, - word32 length); + word32 sz); WOLFSSL_LOCAL int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, - word32 length, word32* algId); + word32 sz, word32* algId); WOLFSSL_LOCAL int ToTraditionalInline_ex2(const byte* input, word32* inOutIdx, - word32 length, word32* algId, + word32 sz, word32* algId, word32* eccOid); WOLFSSL_LOCAL int ToTraditionalEnc(byte* input, word32 sz, const char* password, int passwordSz, word32* algId); WOLFSSL_ASN_API int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int vAlgo, byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap); +WOLFSSL_ASN_API int TraditionalEnc_ex(byte* key, word32 keySz, byte* out, + word32* outSz, const char* password, int passwordSz, int vPKCS, + int vAlgo, int encAlgId, byte* salt, word32 saltSz, int itt, + int hmacOid, WC_RNG* rng, void* heap); WOLFSSL_ASN_API int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int vAlgo, int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap); -WOLFSSL_LOCAL int DecryptContent(byte* input, word32 sz,const char* psw,int pswSz); +WOLFSSL_LOCAL int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz); WOLFSSL_LOCAL int EncryptContent(byte* input, word32 sz, byte* out, word32* outSz, - const char* password,int passwordSz, int vPKCS, int vAlgo, - byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap); + const char* password,int passwordSz, int vPKCS, int vAlgo, int encAlgId, + byte* salt, word32 saltSz, int itt, int hmacOid, WC_RNG* rng, + void* heap); WOLFSSL_LOCAL int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz, int* algoID, void* heap); @@ -2583,6 +2193,8 @@ WOLFSSL_LOCAL int ExtractDate(const unsigned char* date, unsigned char format, wolfssl_tm* certTime, int* idx); WOLFSSL_LOCAL int DateGreaterThan(const struct tm* a, const struct tm* b); WOLFSSL_LOCAL int wc_ValidateDate(const byte* date, byte format, int dateType); +WOLFSSL_TEST_VIS int wc_AsnSetSkipDateCheck(int skip_p); +WOLFSSL_LOCAL int wc_AsnGetSkipDateCheck(void); /* ASN.1 helper functions */ #ifdef WOLFSSL_CERT_GEN @@ -2593,7 +2205,7 @@ WOLFSSL_LOCAL byte GetCertNameId(int idx); #endif WOLFSSL_LOCAL int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx); -WOLFSSL_LOCAL int SetShortInt(byte* input, word32* inOutIdx, word32 number, +WOLFSSL_TEST_VIS int SetShortInt(byte* output, word32* inOutIdx, word32 number, word32 maxIdx); WOLFSSL_LOCAL const char* GetSigName(int oid); @@ -2622,6 +2234,8 @@ WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, WOLFSSL_ASN_API int GetASNInt(const byte* input, word32* inOutIdx, int* len, word32 maxIdx); +WOLFSSL_LOCAL word32 wc_oid_sum(const byte* input, int length); + #ifdef HAVE_OID_ENCODING WOLFSSL_API int wc_EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz); @@ -2642,8 +2256,8 @@ WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx); WOLFSSL_LOCAL int GetAlgoIdEx(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx, byte *absentParams); -WOLFSSL_ASN_API int GetASNTag(const byte* input, word32* idx, byte* tag, - word32 inputSz); +WOLFSSL_ASN_API int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, + word32 maxIdx); WOLFSSL_LOCAL int GetASN_BitString(const byte* input, word32 idx, int length); WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output); @@ -2741,9 +2355,9 @@ WOLFSSL_LOCAL int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, WOLFSSL_LOCAL int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer, size_t bufSz); -WOLFSSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type, +WOLFSSL_LOCAL int PemToDer(const unsigned char* buff, long longSz, int type, DerBuffer** pDer, void* heap, EncryptedInfo* info, - int* eccKey); + int* keyFormat); WOLFSSL_LOCAL int AllocDer(DerBuffer** der, word32 length, int type, void* heap); WOLFSSL_LOCAL int AllocCopyDer(DerBuffer** der, const unsigned char* buff, @@ -2818,11 +2432,6 @@ enum Ocsp_Cert_Status { }; -enum Ocsp_Sums { - OCSP_BASIC_OID = 117, - OCSP_NONCE_OID = 118 -}; - #ifdef OPENSSL_EXTRA enum Ocsp_Verify_Error { OCSP_VERIFY_ERROR_NONE = 0, @@ -3006,6 +2615,11 @@ struct RevokedCert { byte revDateFormat; }; +#ifndef CRL_MAX_NUM_SZ +#define CRL_MAX_NUM_SZ 20 /* RFC5280 states that CRL number can be up to 20 */ +#endif /* octets long */ + + typedef struct DecodedCRL DecodedCRL; struct DecodedCRL { @@ -3018,6 +2632,7 @@ struct DecodedCRL { word32 sigParamsLength; /* length of signature parameters */ #endif byte* signature; /* pointer into raw source, not owned */ + byte crlNumber[CRL_MAX_NUM_SZ]; /* CRL number extension */ byte issuerHash[SIGNER_DIGEST_SIZE]; /* issuer name hash */ byte crlHash[SIGNER_DIGEST_SIZE]; /* raw crl data hash */ byte lastDate[MAX_DATE_SIZE]; /* last date updated */ @@ -3033,10 +2648,10 @@ struct DecodedCRL { int version; /* version of cert */ void* heap; #ifndef NO_SKID - byte extAuthKeyIdSet; - byte extAuthKeyId[SIGNER_DIGEST_SIZE]; /* Authority Key ID */ + byte extAuthKeyId[SIGNER_DIGEST_SIZE]; /* Authority Key ID */ + WC_BITFIELD extAuthKeyIdSet:1; /* Auth key identifier set indicator */ #endif - int crlNumber; /* CRL number extension */ + WC_BITFIELD crlNumberSet:1; /* CRL number set indicator */ }; WOLFSSL_LOCAL void InitDecodedCRL(DecodedCRL* dcrl, void* heap); diff --git a/src/wolfssl/wolfcrypt/asn_public.h b/src/wolfssl/wolfcrypt/asn_public.h index 08d9cc9..3bf071d 100644 --- a/src/wolfssl/wolfcrypt/asn_public.h +++ b/src/wolfssl/wolfcrypt/asn_public.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -32,7 +32,9 @@ This library defines the interface APIs for X509 certificates. #define WOLF_CRYPT_ASN_PUBLIC_H #include -#include +#ifndef NO_DSA + #include +#endif #include #ifdef __cplusplus @@ -81,42 +83,6 @@ This library defines the interface APIs for X509 certificates. #define WC_SPHINCSKEY_TYPE_DEFINED #endif -enum Ecc_Sum { - ECC_SECP112R1_OID = 182, - ECC_SECP112R2_OID = 183, - ECC_SECP128R1_OID = 204, - ECC_SECP128R2_OID = 205, - ECC_SECP160R1_OID = 184, - ECC_SECP160R2_OID = 206, - ECC_SECP160K1_OID = 185, - ECC_BRAINPOOLP160R1_OID = 98, - ECC_SECP192R1_OID = 520, - ECC_PRIME192V2_OID = 521, - ECC_PRIME192V3_OID = 522, - ECC_SECP192K1_OID = 207, - ECC_BRAINPOOLP192R1_OID = 100, - ECC_SECP224R1_OID = 209, - ECC_SECP224K1_OID = 208, - ECC_BRAINPOOLP224R1_OID = 102, - ECC_PRIME239V1_OID = 523, - ECC_PRIME239V2_OID = 524, - ECC_PRIME239V3_OID = 525, - ECC_SECP256R1_OID = 526, - ECC_SECP256K1_OID = 186, - ECC_BRAINPOOLP256R1_OID = 104, - ECC_SM2P256V1_OID = 667, - ECC_X25519_OID = 365, - ECC_ED25519_OID = 256, - ECC_BRAINPOOLP320R1_OID = 106, - ECC_X448_OID = 362, - ECC_ED448_OID = 257, - ECC_SECP384R1_OID = 210, - ECC_BRAINPOOLP384R1_OID = 108, - ECC_BRAINPOOLP512R1_OID = 110, - ECC_SECP521R1_OID = 211 -}; - - enum EncPkcs8Types { ENC_PKCS8_VER_PKCS12 = 1, ENC_PKCS8_VER_PKCS5 = 5, @@ -187,58 +153,6 @@ enum CertType { }; -/* Signature type, by OID sum */ -enum Ctc_SigType { - CTC_SHAwDSA = 517, - CTC_SHA256wDSA = 416, - CTC_MD2wRSA = 646, - CTC_MD5wRSA = 648, - CTC_SHAwRSA = 649, - CTC_SHAwECDSA = 520, - CTC_SHA224wRSA = 658, - CTC_SHA224wECDSA = 523, - CTC_SHA256wRSA = 655, - CTC_SHA256wECDSA = 524, - CTC_SHA384wRSA = 656, - CTC_SHA384wECDSA = 525, - CTC_SHA512wRSA = 657, - CTC_SHA512wECDSA = 526, - - /* https://csrc.nist.gov/projects/computer-security-objects-register/algorithm-registration */ - CTC_SHA3_224wECDSA = 423, - CTC_SHA3_256wECDSA = 424, - CTC_SHA3_384wECDSA = 425, - CTC_SHA3_512wECDSA = 426, - CTC_SHA3_224wRSA = 427, - CTC_SHA3_256wRSA = 428, - CTC_SHA3_384wRSA = 429, - CTC_SHA3_512wRSA = 430, - - CTC_RSASSAPSS = 654, - - CTC_SM3wSM2 = 740, /* 1.2.156.10197.1.501 */ - - CTC_ED25519 = 256, - CTC_ED448 = 257, - - CTC_FALCON_LEVEL1 = 273, - CTC_FALCON_LEVEL5 = 276, - - CTC_DILITHIUM_LEVEL2 = 218, - CTC_DILITHIUM_LEVEL3 = 221, - CTC_DILITHIUM_LEVEL5 = 225, - CTC_ML_DSA_LEVEL2 = 431, - CTC_ML_DSA_LEVEL3 = 432, - CTC_ML_DSA_LEVEL5 = 433, - - CTC_SPHINCS_FAST_LEVEL1 = 281, - CTC_SPHINCS_FAST_LEVEL3 = 283, - CTC_SPHINCS_FAST_LEVEL5 = 282, - CTC_SPHINCS_SMALL_LEVEL1 = 287, - CTC_SPHINCS_SMALL_LEVEL3 = 285, - CTC_SPHINCS_SMALL_LEVEL5 = 286 -}; - enum Ctc_Encoding { CTC_UTF8 = 0x0c, /* utf8 */ CTC_PRINTABLE = 0x13 /* printable */ @@ -728,9 +642,9 @@ WOLFSSL_API void wc_FreeDer(DerBuffer** pDer); #ifdef WOLFSSL_DER_TO_PEM WOLFSSL_ABI WOLFSSL_API int wc_DerToPem(const byte* der, word32 derSz, byte* output, - word32 outputSz, int type); + word32 outSz, int type); WOLFSSL_API int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, - word32 outputSz, byte *cipherIno, int type); + word32 outSz, byte *cipher_info, int type); #endif WOLFSSL_API word32 wc_PkcsPad(byte* buf, word32 sz, word32 blockSz); @@ -806,25 +720,6 @@ WOLFSSL_API int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz); WOLFSSL_API int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve); #endif -/* RFC 5958 (Asymmetric Key Packages) */ -#if !defined(WC_ENABLE_ASYM_KEY_EXPORT) && \ - ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)) || \ - (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)) || \ - (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)) || \ - (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)) || \ - (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS))) - #define WC_ENABLE_ASYM_KEY_EXPORT -#endif - -#if !defined(WC_ENABLE_ASYM_KEY_IMPORT) && \ - ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) || \ - (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) || \ - (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) || \ - (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) || \ - (defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS))) - #define WC_ENABLE_ASYM_KEY_IMPORT -#endif - #ifdef HAVE_ED25519 #ifdef HAVE_ED25519_KEY_IMPORT WOLFSSL_API int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx, @@ -903,6 +798,10 @@ WOLFSSL_API int wc_GetPkcs8TraditionalOffset(byte* input, WOLFSSL_API int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz, int algoID, const byte* curveOID, word32 oidSz); +WOLFSSL_API int wc_EncryptPKCS8Key_ex(byte* key, word32 keySz, byte* out, + word32* outSz, const char* password, int passwordSz, int vPKCS, + int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt, + int hmacOid, WC_RNG* rng, void* heap); WOLFSSL_API int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz, const char* password, int passwordSz, int vPKCS, int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng, @@ -967,6 +866,10 @@ WOLFSSL_API int wc_ParseCert( WOLFSSL_API int wc_GetPubKeyDerFromCert(struct DecodedCert* cert, byte* derKey, word32* derKeySz); +WOLFSSL_API int wc_GetSubjectPubKeyInfoDerFromCert(const byte* certDer, + word32 certDerSz, + byte* pubKeyDer, + word32* pubKeyDerSz); #ifdef WOLFSSL_FPKI WOLFSSL_API int wc_GetUUIDFromCert(struct DecodedCert* cert, @@ -1058,6 +961,8 @@ typedef struct Asn1Item { /* Maximum supported depth of ASN.1 items. */ #define ASN_MAX_DEPTH 16 +typedef const char* (*Asn1OidToNameCb)(unsigned char* oid, word32 len); + /* ASN.1 parsing state. */ typedef struct Asn1 { /* ASN.1 item data. */ @@ -1080,6 +985,9 @@ typedef struct Asn1 { /* File pointer to print to. */ XFILE file; + + /* Callback to get a name for an hex OID. */ + Asn1OidToNameCb nameCb; } Asn1; WOLFSSL_API int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts); @@ -1088,6 +996,7 @@ WOLFSSL_API int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, WOLFSSL_API int wc_Asn1_Init(Asn1* asn1); WOLFSSL_API int wc_Asn1_SetFile(Asn1* asn1, XFILE file); +WOLFSSL_API int wc_Asn1_SetOidToNameCb(Asn1* asn1, Asn1OidToNameCb nameCb); WOLFSSL_API int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data, word32 len); diff --git a/src/wolfssl/wolfcrypt/blake2-impl.h b/src/wolfssl/wolfcrypt/blake2-impl.h index 3f509c7..debfc3f 100644 --- a/src/wolfssl/wolfcrypt/blake2-impl.h +++ b/src/wolfssl/wolfcrypt/blake2-impl.h @@ -18,7 +18,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/blake2-int.h b/src/wolfssl/wolfcrypt/blake2-int.h index ec22921..1dcb1fd 100644 --- a/src/wolfssl/wolfcrypt/blake2-int.h +++ b/src/wolfssl/wolfcrypt/blake2-int.h @@ -18,7 +18,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/blake2.h b/src/wolfssl/wolfcrypt/blake2.h index 5d42c15..760ddef 100644 --- a/src/wolfssl/wolfcrypt/blake2.h +++ b/src/wolfssl/wolfcrypt/blake2.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/camellia.h b/src/wolfssl/wolfcrypt/camellia.h index a31f764..99709c9 100644 --- a/src/wolfssl/wolfcrypt/camellia.h +++ b/src/wolfssl/wolfcrypt/camellia.h @@ -33,7 +33,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/chacha.h b/src/wolfssl/wolfcrypt/chacha.h index 892b6ce..19a224b 100644 --- a/src/wolfssl/wolfcrypt/chacha.h +++ b/src/wolfssl/wolfcrypt/chacha.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/chacha20_poly1305.h b/src/wolfssl/wolfcrypt/chacha20_poly1305.h index 7f9ac16..ca57545 100644 --- a/src/wolfssl/wolfcrypt/chacha20_poly1305.h +++ b/src/wolfssl/wolfcrypt/chacha20_poly1305.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/cmac.h b/src/wolfssl/wolfcrypt/cmac.h index dd6e5b7..42795f9 100644 --- a/src/wolfssl/wolfcrypt/cmac.h +++ b/src/wolfssl/wolfcrypt/cmac.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/coding.h b/src/wolfssl/wolfcrypt/coding.h index ef87ab4..0e1d087 100644 --- a/src/wolfssl/wolfcrypt/coding.h +++ b/src/wolfssl/wolfcrypt/coding.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/compress.h b/src/wolfssl/wolfcrypt/compress.h index c4d5c25..4f401a6 100644 --- a/src/wolfssl/wolfcrypt/compress.h +++ b/src/wolfssl/wolfcrypt/compress.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/cpuid.h b/src/wolfssl/wolfcrypt/cpuid.h index bb883cb..e6b7eb6 100644 --- a/src/wolfssl/wolfcrypt/cpuid.h +++ b/src/wolfssl/wolfcrypt/cpuid.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -70,14 +70,15 @@ #elif defined(HAVE_CPUID_AARCH64) - #define CPUID_AES 0x0001 - #define CPUID_PMULL 0x0002 - #define CPUID_SHA256 0x0004 - #define CPUID_SHA512 0x0008 - #define CPUID_RDM 0x0010 - #define CPUID_SHA3 0x0020 - #define CPUID_SM3 0x0040 - #define CPUID_SM4 0x0080 + #define CPUID_AES 0x0001 /* AES enc/dec */ + #define CPUID_PMULL 0x0002 /* Carryless multiplication */ + #define CPUID_SHA256 0x0004 /* SHA-256 digest */ + #define CPUID_SHA512 0x0008 /* SHA-512 digest */ + #define CPUID_RDM 0x0010 /* SQRDMLAH and SQRDMLSH */ + #define CPUID_SHA3 0x0020 /* SHA-3 digest */ + #define CPUID_SM3 0x0040 /* SM3 digest */ + #define CPUID_SM4 0x0080 /* SM4 enc/dec */ + #define CPUID_SB 0x0100 /* Speculation barrier */ #define IS_AARCH64_AES(f) ((f) & CPUID_AES) #define IS_AARCH64_PMULL(f) ((f) & CPUID_PMULL) @@ -87,6 +88,7 @@ #define IS_AARCH64_SHA3(f) ((f) & CPUID_SHA3) #define IS_AARCH64_SM3(f) ((f) & CPUID_SM3) #define IS_AARCH64_SM4(f) ((f) & CPUID_SM4) + #define IS_AARCH64_SB(f) ((f) & CPUID_SB) #endif diff --git a/src/wolfssl/wolfcrypt/cryptocb.h b/src/wolfssl/wolfcrypt/cryptocb.h index f47cb0a..af5f912 100644 --- a/src/wolfssl/wolfcrypt/cryptocb.h +++ b/src/wolfssl/wolfcrypt/cryptocb.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -176,6 +176,7 @@ typedef struct wc_CryptoInfo { } rsa_get_size; #endif #ifdef HAVE_ECC + #ifdef HAVE_ECC_DHE struct { WC_RNG* rng; int size; @@ -188,6 +189,8 @@ typedef struct wc_CryptoInfo { byte* out; word32* outlen; } ecdh; + #endif + #ifdef HAVE_ECC_SIGN struct { const byte* in; word32 inlen; @@ -196,6 +199,8 @@ typedef struct wc_CryptoInfo { WC_RNG* rng; ecc_key* key; } eccsign; + #endif + #ifdef HAVE_ECC_VERIFY struct { const byte* sig; word32 siglen; @@ -204,12 +209,15 @@ typedef struct wc_CryptoInfo { int* res; ecc_key* key; } eccverify; + #endif + #ifdef HAVE_ECC_CHECK_KEY struct { ecc_key* key; const byte* pubKey; word32 pubKeySz; } ecc_check; - #endif + #endif + #endif /* HAVE_ECC */ #ifdef HAVE_CURVE25519 struct { WC_RNG* rng; @@ -466,7 +474,7 @@ typedef struct wc_CryptoInfo { } wc_CryptoInfo; -typedef int (*CryptoDevCallbackFunc)(int devId, wc_CryptoInfo* info, void* ctx); +typedef int (*CryptoDevCallbackFunc)(int devId, struct wc_CryptoInfo* info, void* ctx); WOLFSSL_LOCAL void wc_CryptoCb_Init(void); WOLFSSL_LOCAL void wc_CryptoCb_Cleanup(void); diff --git a/src/wolfssl/wolfcrypt/curve25519.h b/src/wolfssl/wolfcrypt/curve25519.h index f1bb574..a791d67 100644 --- a/src/wolfssl/wolfcrypt/curve25519.h +++ b/src/wolfssl/wolfcrypt/curve25519.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/curve448.h b/src/wolfssl/wolfcrypt/curve448.h index 756c8a3..bb9b15c 100644 --- a/src/wolfssl/wolfcrypt/curve448.h +++ b/src/wolfssl/wolfcrypt/curve448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/des3.h b/src/wolfssl/wolfcrypt/des3.h index 2568857..5473d30 100644 --- a/src/wolfssl/wolfcrypt/des3.h +++ b/src/wolfssl/wolfcrypt/des3.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/dh.h b/src/wolfssl/wolfcrypt/dh.h index 81c5623..bbb2536 100644 --- a/src/wolfssl/wolfcrypt/dh.h +++ b/src/wolfssl/wolfcrypt/dh.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -145,7 +145,6 @@ WOLFSSL_API const DhParams* wc_Dh_ffdhe8192_Get(void); WOLFSSL_API int wc_InitDhKey(DhKey* key); WOLFSSL_API int wc_InitDhKey_ex(DhKey* key, void* heap, int devId); WOLFSSL_API int wc_FreeDhKey(DhKey* key); - WOLFSSL_API int wc_DhGenerateKeyPair(DhKey* key, WC_RNG* rng, byte* priv, word32* privSz, byte* pub, word32* pubSz); WOLFSSL_API int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, @@ -173,6 +172,17 @@ WOLFSSL_API int wc_DhCmpNamedKey(int name, int noQ, WOLFSSL_API int wc_DhCopyNamedKey(int name, byte* p, word32* pSz, byte* g, word32* gSz, byte* q, word32* qSz); +#ifndef WOLFSSL_NO_DH_GEN_PUB + #if defined(WOLFSSL_DH_EXTRA) && !defined(WOLFSSL_DH_GEN_PUB) + #define WOLFSSL_DH_GEN_PUB + #endif + #ifdef WOLFSSL_DH_GEN_PUB + WOLFSSL_API int wc_DhGeneratePublic(DhKey* key, byte* priv, + word32 privSz, byte* pub, + word32* pubSz); + #endif /* WOLFSSL_DH_GEN_PUB */ +#endif /* !WOLFSSL_NO_DH_GEN_PUB */ + #ifdef WOLFSSL_DH_EXTRA WOLFSSL_API int wc_DhImportKeyPair(DhKey* key, const byte* priv, word32 privSz, const byte* pub, word32 pubSz); diff --git a/src/wolfssl/wolfcrypt/dilithium.h b/src/wolfssl/wolfcrypt/dilithium.h index 306cef1..faa4e92 100644 --- a/src/wolfssl/wolfcrypt/dilithium.h +++ b/src/wolfssl/wolfcrypt/dilithium.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -144,9 +144,9 @@ #define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 #define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 #define DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE 7520 -/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and - * the footer "-----END PRIVATE KEY-----" */ -#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10239 +/* PEM size with the header "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----" and + * the footer "-----END ML_DSA_LEVEL5 PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10267 #define ML_DSA_LEVEL2_KEY_SIZE 2560 #define ML_DSA_LEVEL2_SIG_SIZE 2420 @@ -183,8 +183,8 @@ #define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL5_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE -/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and - * the footer "-----END PRIVATE KEY-----" */ +/* PEM size with the header "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----" and + * the footer "-----END ML_DSA_LEVEL5 PRIVATE KEY-----" */ #define ML_DSA_LEVEL5_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE @@ -574,9 +574,9 @@ #define DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE 2614 #define DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE 4924 #define DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE 7520 -/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and - * the footer "-----END PRIVATE KEY-----" */ -#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10239 +/* PEM size with the header "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----" and + * the footer "-----END ML_DSA_LEVEL5 PRIVATE KEY-----" */ +#define DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE 10267 #define ML_DSA_LEVEL2_KEY_SIZE OQS_SIG_ml_dsa_44_ipd_length_secret_key #define ML_DSA_LEVEL2_SIG_SIZE OQS_SIG_ml_dsa_44_ipd_length_signature @@ -613,8 +613,8 @@ #define ML_DSA_LEVEL5_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define ML_DSA_LEVEL5_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE #define ML_DSA_LEVEL5_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE -/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and - * the footer "-----END PRIVATE KEY-----" */ +/* PEM size with the header "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----" and + * the footer "-----END ML_DSA_LEVEL5 PRIVATE KEY-----" */ #define ML_DSA_LEVEL5_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE #endif @@ -627,8 +627,8 @@ #define DILITHIUM_MAX_PUB_KEY_DER_SIZE DILITHIUM_LEVEL5_PUB_KEY_DER_SIZE #define DILITHIUM_MAX_PRV_KEY_DER_SIZE DILITHIUM_LEVEL5_PRV_KEY_DER_SIZE #define DILITHIUM_MAX_BOTH_KEY_DER_SIZE DILITHIUM_LEVEL5_BOTH_KEY_DER_SIZE -/* PEM size with the header "-----BEGIN PRIVATE KEY-----" and - * the footer "-----END PRIVATE KEY-----" */ +/* PEM size with the header "-----BEGIN ML_DSA_LEVEL5 PRIVATE KEY-----" and + * the footer "-----END ML_DSA_LEVEL5 PRIVATE KEY-----" */ #define DILITHIUM_MAX_BOTH_KEY_PEM_SIZE DILITHIUM_LEVEL5_BOTH_KEY_PEM_SIZE @@ -651,7 +651,7 @@ typedef struct wc_dilithium_params { byte omega; word16 lambda; byte gamma1_bits; - word32 gamma2; + sword32 gamma2; word32 w1EncSz; word16 aSz; word16 s1Sz; diff --git a/src/wolfssl/wolfcrypt/dsa.h b/src/wolfssl/wolfcrypt/dsa.h index 4ae42c3..ba56f0c 100644 --- a/src/wolfssl/wolfcrypt/dsa.h +++ b/src/wolfssl/wolfcrypt/dsa.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ecc.h b/src/wolfssl/wolfcrypt/ecc.h index 04a7a66..b188fa1 100644 --- a/src/wolfssl/wolfcrypt/ecc.h +++ b/src/wolfssl/wolfcrypt/ecc.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -215,7 +215,7 @@ enum { #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \ defined(HAVE_CURVE448) || defined(WOLFCRYPT_HAVE_SAKKE) /* Curve Types */ -typedef enum ecc_curve_id { +enum ecc_curve_ids { ECC_CURVE_INVALID = -1, ECC_CURVE_DEF = 0, /* NIST or SECP */ @@ -272,7 +272,8 @@ typedef enum ecc_curve_id { ECC_CURVE_CUSTOM, #endif ECC_CURVE_MAX -} ecc_curve_id; +}; +typedef enum ecc_curve_ids ecc_curve_id; #endif #ifdef HAVE_ECC diff --git a/src/wolfssl/wolfcrypt/eccsi.h b/src/wolfssl/wolfcrypt/eccsi.h index 5136d13..1e5a77c 100644 --- a/src/wolfssl/wolfcrypt/eccsi.h +++ b/src/wolfssl/wolfcrypt/eccsi.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ed25519.h b/src/wolfssl/wolfcrypt/ed25519.h index f7367b5..1abba3a 100644 --- a/src/wolfssl/wolfcrypt/ed25519.h +++ b/src/wolfssl/wolfcrypt/ed25519.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ed448.h b/src/wolfssl/wolfcrypt/ed448.h index e79a048..d56ac4a 100644 --- a/src/wolfssl/wolfcrypt/ed448.h +++ b/src/wolfssl/wolfcrypt/ed448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/error-crypt.h b/src/wolfssl/wolfcrypt/error-crypt.h index f466e29..d95e527 100644 --- a/src/wolfssl/wolfcrypt/error-crypt.h +++ b/src/wolfssl/wolfcrypt/error-crypt.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -304,11 +304,12 @@ enum wolfCrypt_ErrorCodes { DEADLOCK_AVERTED_E = -1000, /* Deadlock averted -- retry the call */ ASCON_AUTH_E = -1001, /* ASCON Authentication check failure */ + WC_ACCEL_INHIBIT_E = -1002, /* Crypto acceleration is currently inhibited */ - WC_SPAN2_LAST_E = -1001, /* Update to indicate last used error code */ + WC_SPAN2_LAST_E = -1002, /* Update to indicate last used error code */ WC_SPAN2_MIN_CODE_E = -1999, /* Last usable code in span 2 */ - WC_LAST_E = -1001, /* the last code used either here or in + WC_LAST_E = -1002, /* the last code used either here or in * error-ssl.h */ diff --git a/src/wolfssl/wolfcrypt/ext_lms.h b/src/wolfssl/wolfcrypt/ext_lms.h index 2c7d116..18e1221 100644 --- a/src/wolfssl/wolfcrypt/ext_lms.h +++ b/src/wolfssl/wolfcrypt/ext_lms.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ext_mlkem.h b/src/wolfssl/wolfcrypt/ext_mlkem.h index 53c6c7d..bd6cd5c 100644 --- a/src/wolfssl/wolfcrypt/ext_mlkem.h +++ b/src/wolfssl/wolfcrypt/ext_mlkem.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ext_xmss.h b/src/wolfssl/wolfcrypt/ext_xmss.h index 1c7ed35..8183f08 100644 --- a/src/wolfssl/wolfcrypt/ext_xmss.h +++ b/src/wolfssl/wolfcrypt/ext_xmss.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/falcon.h b/src/wolfssl/wolfcrypt/falcon.h index 45ae673..904a68c 100644 --- a/src/wolfssl/wolfcrypt/falcon.h +++ b/src/wolfssl/wolfcrypt/falcon.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/fe_448.h b/src/wolfssl/wolfcrypt/fe_448.h index fef9d17..46a9717 100644 --- a/src/wolfssl/wolfcrypt/fe_448.h +++ b/src/wolfssl/wolfcrypt/fe_448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/fe_operations.h b/src/wolfssl/wolfcrypt/fe_operations.h index dd029ec..844d938 100644 --- a/src/wolfssl/wolfcrypt/fe_operations.h +++ b/src/wolfssl/wolfcrypt/fe_operations.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/fips_test.h b/src/wolfssl/wolfcrypt/fips_test.h index 16f170b..709a5db 100644 --- a/src/wolfssl/wolfcrypt/fips_test.h +++ b/src/wolfssl/wolfcrypt/fips_test.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ge_448.h b/src/wolfssl/wolfcrypt/ge_448.h index 82665cf..df9a450 100644 --- a/src/wolfssl/wolfcrypt/ge_448.h +++ b/src/wolfssl/wolfcrypt/ge_448.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ge_operations.h b/src/wolfssl/wolfcrypt/ge_operations.h index 9a4d995..879cc72 100644 --- a/src/wolfssl/wolfcrypt/ge_operations.h +++ b/src/wolfssl/wolfcrypt/ge_operations.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/hash.h b/src/wolfssl/wolfcrypt/hash.h index 02d99d4..9ac6cff 100644 --- a/src/wolfssl/wolfcrypt/hash.h +++ b/src/wolfssl/wolfcrypt/hash.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -40,7 +40,7 @@ #if defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) #include #endif -#ifdef HAVE_BLAKE2 +#if defined(HAVE_BLAKE2) || defined(HAVE_BLAKE2S) #include #endif #ifdef WOLFSSL_SHA3 @@ -52,9 +52,6 @@ #ifdef WOLFSSL_MD2 #include #endif -#if defined(HAVE_BLAKE2) || defined(HAVE_BLAKE2S) - #include -#endif #ifdef WOLFSSL_SM3 #include #endif @@ -122,11 +119,15 @@ typedef struct { } wc_HashAlg; #endif /* !NO_HASH_WRAPPER */ + /* Find largest possible digest size Note if this gets up to the size of 80 or over check smallstack build */ +#undef WC_MAX_DIGEST_SIZE +#undef WC_MAX_BLOCK_SIZE #if defined(WOLFSSL_SHA3) + /* note: SHA3-224 has the largest block size */ #define WC_MAX_DIGEST_SIZE WC_SHA3_512_DIGEST_SIZE - #define WC_MAX_BLOCK_SIZE WC_SHA3_224_BLOCK_SIZE /* 224 is the largest block size */ + #define WC_MAX_BLOCK_SIZE WC_SHA3_224_BLOCK_SIZE #elif defined(WOLFSSL_SHA512) #define WC_MAX_DIGEST_SIZE WC_SHA512_DIGEST_SIZE #define WC_MAX_BLOCK_SIZE WC_SHA512_BLOCK_SIZE diff --git a/src/wolfssl/wolfcrypt/hmac.h b/src/wolfssl/wolfcrypt/hmac.h index 96da94c..90b04fa 100644 --- a/src/wolfssl/wolfcrypt/hmac.h +++ b/src/wolfssl/wolfcrypt/hmac.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -194,6 +194,7 @@ WOLFSSL_API void wc_HmacFree(Hmac* hmac); WOLFSSL_API int wolfSSL_GetHmacMaxSize(void); WOLFSSL_LOCAL int _InitHmac(Hmac* hmac, int type, void* heap); +WOLFSSL_LOCAL int _HmacInitIOHashes(Hmac* hmac); #ifdef HAVE_HKDF diff --git a/src/wolfssl/wolfcrypt/hpke.h b/src/wolfssl/wolfcrypt/hpke.h index cacfca6..735df81 100644 --- a/src/wolfssl/wolfcrypt/hpke.h +++ b/src/wolfssl/wolfcrypt/hpke.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/integer.h b/src/wolfssl/wolfcrypt/integer.h index 68bda1f..7d3f6ea 100644 --- a/src/wolfssl/wolfcrypt/integer.h +++ b/src/wolfssl/wolfcrypt/integer.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -205,7 +205,12 @@ typedef int mp_err; #define NEW_MP_INT_SIZE(name, bits, heap, type) \ XMEMSET(name, 0, sizeof(mp_int)) /* Dispose of static mp_int. */ -#define FREE_MP_INT_SIZE(name, heap, type) WC_DO_NOTHING +#define FREE_MP_INT_SIZE(name, heap, type) \ + do { \ + if ((name) != NULL) { \ + mp_free(name); \ + } \ + } while (0) /* Initialize an mp_int. */ #define INIT_MP_INT_SIZE(name, bits) \ mp_init(name) diff --git a/src/wolfssl/wolfcrypt/kdf.h b/src/wolfssl/wolfcrypt/kdf.h index d2fd388..0421d82 100644 --- a/src/wolfssl/wolfcrypt/kdf.h +++ b/src/wolfssl/wolfcrypt/kdf.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -147,19 +147,19 @@ enum { #define WC_SRTP_MAX_SALT 14 WOLFSSL_API int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, - word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, + word32 saltSz, int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz); WOLFSSL_API int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, - word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, + word32 saltSz, int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz); WOLFSSL_API int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, - word32 saltSz, int kdrIdx, const byte* index, byte* key1, word32 key1Sz, + word32 saltSz, int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2, word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator); WOLFSSL_API int wc_SRTP_KDF_label(const byte* key, word32 keySz, - const byte* salt, word32 saltSz, int kdrIdx, const byte* index, byte label, + const byte* salt, word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey, word32 outKeySz); WOLFSSL_API int wc_SRTCP_KDF_label(const byte* key, word32 keySz, - const byte* salt, word32 saltSz, int kdrIdx, const byte* index, byte label, + const byte* salt, word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey, word32 outKeySz); WOLFSSL_API int wc_SRTP_KDF_kdr_to_idx(word32 kdr); diff --git a/src/wolfssl/wolfcrypt/libwolfssl_sources.h b/src/wolfssl/wolfcrypt/libwolfssl_sources.h index 474cbe1..a5d6972 100644 --- a/src/wolfssl/wolfcrypt/libwolfssl_sources.h +++ b/src/wolfssl/wolfcrypt/libwolfssl_sources.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h b/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h index a3d85c9..5ecd092 100644 --- a/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h +++ b/src/wolfssl/wolfcrypt/libwolfssl_sources_asm.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/lms.h b/src/wolfssl/wolfcrypt/lms.h index ee4ccc5..c9324cc 100644 --- a/src/wolfssl/wolfcrypt/lms.h +++ b/src/wolfssl/wolfcrypt/lms.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -31,6 +31,9 @@ #ifdef WOLFSSL_HAVE_LMS +/* Length of the Key ID. */ +#define WC_LMS_I_LEN 16 + typedef struct LmsKey LmsKey; /* Private key write and read callbacks. */ @@ -187,6 +190,8 @@ WOLFSSL_API int wc_LmsKey_Verify(LmsKey * key, const byte * sig, word32 sigSz, WOLFSSL_API const char * wc_LmsKey_ParmToStr(enum wc_LmsParm lmsParm); WOLFSSL_API const char * wc_LmsKey_RcToStr(enum wc_LmsRc lmsRc); +WOLFSSL_API int wc_LmsKey_GetKid(LmsKey * key, const byte ** kid, + word32* kidSz); WOLFSSL_API const byte * wc_LmsKey_GetKidFromPrivRaw(const byte * priv, word32 privSz); #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/logging.h b/src/wolfssl/wolfcrypt/logging.h index 49de701..f7ccf95 100644 --- a/src/wolfssl/wolfcrypt/logging.h +++ b/src/wolfssl/wolfcrypt/logging.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -89,11 +89,6 @@ enum wc_FuncNum { }; #endif -#if defined(ARDUINO) -/* implemented in Arduino wolfssl.h */ -extern WOLFSSL_API int wolfSSL_Arduino_Serial_Print(const char* const s); -#endif /* ARDUINO */ - typedef void (*wolfSSL_Logging_cb)(const int logLevel, const char *const logMessage); @@ -268,6 +263,99 @@ WOLFSSL_API void wolfSSL_SetLoggingPrefix(const char* prefix); extern WOLFSSL_API THREAD_LS_T void *StackSizeCheck_stackOffsetPointer; #endif +/* Port-specific includes and printf methods: */ + +#if defined(ARDUINO) + /* implemented in Arduino wolfssl.h */ + extern WOLFSSL_API int wolfSSL_Arduino_Serial_Print(const char* const s); +#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) + /* see wc_port.h for fio.h and nio.h includes */ +#elif defined(WOLFSSL_SGX) + /* Declare sprintf for ocall */ + int sprintf(char* buf, const char *fmt, ...); +#elif defined(WOLFSSL_DEOS) +#elif defined(MICRIUM) + #if (BSP_SER_COMM_EN == DEF_ENABLED) + #include + #endif +#elif defined(WOLFSSL_USER_LOG) + /* user includes their own headers */ +#elif defined(WOLFSSL_ESPIDF) + #include "esp_types.h" + #include "esp_log.h" +#elif defined(WOLFSSL_TELIT_M2MB) + #include + #include "m2m_log.h" +#elif defined(WOLFSSL_ANDROID_DEBUG) + #include +#elif defined(WOLFSSL_XILINX) + #include "xil_printf.h" +#elif defined(WOLFSSL_LINUXKM) + /* the requisite linux/kernel.h is included in linuxkm_wc_port.h, with + * incompatible warnings masked out. + */ +#elif defined(FUSION_RTOS) + #include + #define fprintf FCL_FPRINTF +#else + #include /* for default printf stuff */ +#endif + +#if defined(THREADX) && !defined(THREADX_NO_DC_PRINTF) + int dc_log_printf(char*, ...); +#endif + +#ifdef WOLFSSL_DEBUG_PRINTF_FN + /* user-supplied definition */ +#elif defined(ARDUINO) + /* ARDUINO only has print and sprintf, no printf. */ +#elif defined(WOLFSSL_LOG_PRINTF) || defined(WOLFSSL_DEOS) + #define WOLFSSL_DEBUG_PRINTF_FN printf +#elif defined(THREADX) && !defined(THREADX_NO_DC_PRINTF) + #define WOLFSSL_DEBUG_PRINTF_FN dc_log_printf +#elif defined(MICRIUM) + #define WOLFSSL_DEBUG_PRINTF_FN BSP_Ser_Printf +#elif defined(WOLFSSL_MDK_ARM) + #define WOLFSSL_DEBUG_PRINTF_FN printf +#elif defined(WOLFSSL_UTASKER) + /* WOLFSSL_UTASKER only has fnDebugMsg and related primitives, no printf. */ +#elif defined(MQX_USE_IO_OLD) + #define WOLFSSL_DEBUG_PRINTF_FN fprintf + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS _mqxio_stderr, +#elif defined(WOLFSSL_APACHE_MYNEWT) + #define WOLFSSL_DEBUG_PRINTF_FN LOG_DEBUG + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS &mynewt_log, LOG_MODULE_DEFAULT, +#elif defined(WOLFSSL_ESPIDF) + #define WOLFSSL_DEBUG_PRINTF_FN ESP_LOGI + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS "wolfssl", +#elif defined(WOLFSSL_ZEPHYR) + #define WOLFSSL_DEBUG_PRINTF_FN printk +#elif defined(WOLFSSL_TELIT_M2MB) + #define WOLFSSL_DEBUG_PRINTF_FN M2M_LOG_INFO +#elif defined(WOLFSSL_ANDROID_DEBUG) + #define WOLFSSL_DEBUG_PRINTF_FN __android_log_print + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS ANDROID_LOG_VERBOSE, "[wolfSSL]" +#elif defined(WOLFSSL_XILINX) + #define WOLFSSL_DEBUG_PRINTF_FN xil_printf +#elif defined(WOLFSSL_LINUXKM) + #define WOLFSSL_DEBUG_PRINTF_FN printk +#elif defined(WOLFSSL_RENESAS_RA6M4) + #define WOLFSSL_DEBUG_PRINTF_FN myprintf +#else + #define WOLFSSL_DEBUG_PRINTF_FN fprintf + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS stderr, +#endif + +#ifndef WOLFSSL_DEBUG_PRINTF_FIRST_ARGS + #define WOLFSSL_DEBUG_PRINTF_FIRST_ARGS +#endif + +#if defined(WOLFSSL_DEBUG_PRINTF_FN) && !defined(WOLFSSL_DEBUG_PRINTF) && \ + !defined(WOLF_NO_VARIADIC_MACROS) + #define WOLFSSL_DEBUG_PRINTF(...) \ + WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS __VA_ARGS__) +#endif + #ifdef __cplusplus } #endif diff --git a/src/wolfssl/wolfcrypt/md2.h b/src/wolfssl/wolfcrypt/md2.h index 8fb5076..b77fa65 100644 --- a/src/wolfssl/wolfcrypt/md2.h +++ b/src/wolfssl/wolfcrypt/md2.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/md4.h b/src/wolfssl/wolfcrypt/md4.h index 78c4275..b536f60 100644 --- a/src/wolfssl/wolfcrypt/md4.h +++ b/src/wolfssl/wolfcrypt/md4.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/md5.h b/src/wolfssl/wolfcrypt/md5.h index 93b906d..56c306a 100644 --- a/src/wolfssl/wolfcrypt/md5.h +++ b/src/wolfssl/wolfcrypt/md5.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/mem_track.h b/src/wolfssl/wolfcrypt/mem_track.h index 205ec57..6a0d5aa 100644 --- a/src/wolfssl/wolfcrypt/mem_track.h +++ b/src/wolfssl/wolfcrypt/mem_track.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -177,7 +177,7 @@ static WC_INLINE void* TrackMalloc(size_t sz) (void)line; #endif #endif -#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) +#if !defined(SINGLE_THREADED) && (defined(DO_MEM_LIST) || defined(DO_MEM_STATS)) if (pthread_mutex_lock(&memLock) == 0) { #endif @@ -223,7 +223,7 @@ static WC_INLINE void* TrackMalloc(size_t sz) ourMemList.tail = header; /* add to the end either way */ ourMemList.count++; #endif -#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) +#if !defined(SINGLE_THREADED) && (defined(DO_MEM_LIST) || defined(DO_MEM_STATS)) pthread_mutex_unlock(&memLock); } #endif /* DO_MEM_LIST */ @@ -250,7 +250,7 @@ static WC_INLINE void TrackFree(void* ptr) header = &mt->u.hint; sz = header->thisSize; -#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) +#if !defined(SINGLE_THREADED) && (defined(DO_MEM_LIST) || defined(DO_MEM_STATS)) if (pthread_mutex_lock(&memLock) == 0) { #endif @@ -284,7 +284,7 @@ static WC_INLINE void TrackFree(void* ptr) ourMemList.count--; #endif -#if defined(DO_MEM_LIST) || defined(DO_MEM_STATS) +#if !defined(SINGLE_THREADED) && (defined(DO_MEM_LIST) || defined(DO_MEM_STATS)) pthread_mutex_unlock(&memLock); } #endif diff --git a/src/wolfssl/wolfcrypt/memory.h b/src/wolfssl/wolfcrypt/memory.h index 5170a8c..fa8e5d0 100644 --- a/src/wolfssl/wolfcrypt/memory.h +++ b/src/wolfssl/wolfcrypt/memory.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -133,7 +133,18 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, #ifndef LARGEST_MEM_BUCKET #ifndef SESSION_CERTS - #define LARGEST_MEM_BUCKET 16128 + #ifdef HAVE_DILITHIUM + #if defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_VERIFY_ONLY) + #define LARGEST_MEM_BUCKET 14000 /* Dilithium low mem */ + #else + #define LARGEST_MEM_BUCKET 131072 /* Dilithium full mem */ + #endif + #else + #define LARGEST_MEM_BUCKET 16128 + #endif #elif defined(OPENSSL_EXTRA) #ifdef WOLFSSL_TLS13 #define LARGEST_MEM_BUCKET 30400 @@ -151,9 +162,24 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, #ifndef WOLFMEM_BUCKETS #ifndef SESSION_CERTS - /* default size of chunks of memory to separate into */ - #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3456,4544,\ - LARGEST_MEM_BUCKET + #ifdef HAVE_DILITHIUM + #if defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_VERIFY_ONLY) + /* default size of chunks of memory to separate into */ + #define WOLFMEM_BUCKETS 64,128,256,512,1024,2048,4096,\ + 8192,LARGEST_MEM_BUCKET + #else + /* default size of chunks of memory to separate into */ + #define WOLFMEM_BUCKETS 64,128,256,512,1024,8192,32768,\ + 65536,LARGEST_MEM_BUCKET + #endif + #else + /* default size of chunks of memory to separate into */ + #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3456,4544,\ + LARGEST_MEM_BUCKET + #endif #elif defined(OPENSSL_EXTRA) /* extra storage in structs for multiple attributes and order */ #define WOLFMEM_BUCKETS 64,128,256,512,1024,2432,3360,4480,\ @@ -168,7 +194,16 @@ WOLFSSL_API int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf, #endif #ifndef WOLFMEM_DIST - #ifndef WOLFSSL_STATIC_MEMORY_SMALL + #ifdef HAVE_DILITHIUM + #if defined(WOLFSSL_DILITHIUM_VERIFY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_SIGN_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_MAKE_KEY_SMALL_MEM) && \ + defined(WOLFSSL_DILITHIUM_VERIFY_ONLY) + #define WOLFMEM_DIST 20,8,6,10,8,6,4,2,1 + #else + #define WOLFMEM_DIST 30,10,8,15,8,10,8,5,1 + #endif + #elif !defined(WOLFSSL_STATIC_MEMORY_SMALL) #define WOLFMEM_DIST 49,10,6,14,5,6,9,1,1 #else /* Low resource and not RSA */ diff --git a/src/wolfssl/wolfcrypt/misc.h b/src/wolfssl/wolfcrypt/misc.h index 561c9a2..096f3dd 100644 --- a/src/wolfssl/wolfcrypt/misc.h +++ b/src/wolfssl/wolfcrypt/misc.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/mlkem.h b/src/wolfssl/wolfcrypt/mlkem.h index 4a922a1..f4ad34e 100644 --- a/src/wolfssl/wolfcrypt/mlkem.h +++ b/src/wolfssl/wolfcrypt/mlkem.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/mpi_class.h b/src/wolfssl/wolfcrypt/mpi_class.h index 4879a61..c540aaa 100644 --- a/src/wolfssl/wolfcrypt/mpi_class.h +++ b/src/wolfssl/wolfcrypt/mpi_class.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/mpi_superclass.h b/src/wolfssl/wolfcrypt/mpi_superclass.h index 69dee6b..a9f2f9a 100644 --- a/src/wolfssl/wolfcrypt/mpi_superclass.h +++ b/src/wolfssl/wolfcrypt/mpi_superclass.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/oid_sum.h b/src/wolfssl/wolfcrypt/oid_sum.h new file mode 100644 index 0000000..2c6eadc --- /dev/null +++ b/src/wolfssl/wolfcrypt/oid_sum.h @@ -0,0 +1,1903 @@ +/* oid_sum.h + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Generated using (from wolfssl): + * ./scripts/asn1_oid_sum.pl > wolfssl/wolfcrypt/oid_sum.h + */ + +#ifndef WOLF_CRYPT_OID_SUM_H +#define WOLF_CRYPT_OID_SUM_H + +enum Hash_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02 */ + MD2h = 646, /* 1.2.840.113549.2.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x04 */ + MD4h = 648, /* 1.2.840.113549.2.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x05 */ + MD5h = 649, /* 1.2.840.113549.2.5 */ + /* 0x2b,0x0e,0x03,0x02,0x1a */ + SHAh = 88, /* 1.3.14.3.2.26 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x04 */ + SHA224h = 417, /* 2.16.840.1.101.3.4.2.4 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x01 */ + SHA256h = 414, /* 2.16.840.1.101.3.4.2.1 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x02 */ + SHA384h = 415, /* 2.16.840.1.101.3.4.2.2 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x03 */ + SHA512h = 416, /* 2.16.840.1.101.3.4.2.3 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x05 */ + SHA512_224h = 418, /* 2.16.840.1.101.3.4.2.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x06 */ + SHA512_256h = 419, /* 2.16.840.1.101.3.4.2.6 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x07 */ + SHA3_224h = 420, /* 2.16.840.1.101.3.4.2.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x08 */ + SHA3_256h = 421, /* 2.16.840.1.101.3.4.2.8 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x09 */ + SHA3_384h = 422, /* 2.16.840.1.101.3.4.2.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0a */ + SHA3_512h = 423, /* 2.16.840.1.101.3.4.2.10 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0b */ + SHAKE128h = 424, /* 2.16.840.1.101.3.4.2.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0c */ + SHAKE256h = 425, /* 2.16.840.1.101.3.4.2.12 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x83,0x11 */ + SM3h = 640 /* 1.2.156.10197.1.401 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02 */ + MD2h = 0x044a8bdd, /* 1.2.840.113549.2.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x04 */ + MD4h = 0x024a8bdd, /* 1.2.840.113549.2.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x05 */ + MD5h = 0x034a8bdd, /* 1.2.840.113549.2.5 */ + /* 0x2b,0x0e,0x03,0x02,0x1a */ + SHAh = 0x7d03f131, /* 1.3.14.3.2.26 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x04 */ + SHA224h = 0x7cb37afe, /* 2.16.840.1.101.3.4.2.4 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x01 */ + SHA256h = 0x7cb37afb, /* 2.16.840.1.101.3.4.2.1 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x02 */ + SHA384h = 0x7cb37af8, /* 2.16.840.1.101.3.4.2.2 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x03 */ + SHA512h = 0x7cb37af9, /* 2.16.840.1.101.3.4.2.3 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x05 */ + SHA512_224h = 0x7cb37aff, /* 2.16.840.1.101.3.4.2.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x06 */ + SHA512_256h = 0x7cb37afc, /* 2.16.840.1.101.3.4.2.6 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x07 */ + SHA3_224h = 0x7cb37afd, /* 2.16.840.1.101.3.4.2.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x08 */ + SHA3_256h = 0x7cb37af2, /* 2.16.840.1.101.3.4.2.8 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x09 */ + SHA3_384h = 0x7cb37af3, /* 2.16.840.1.101.3.4.2.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0a */ + SHA3_512h = 0x7cb37af0, /* 2.16.840.1.101.3.4.2.10 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0b */ + SHAKE128h = 0x7cb37af1, /* 2.16.840.1.101.3.4.2.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0c */ + SHAKE256h = 0x7cb37af6, /* 2.16.840.1.101.3.4.2.12 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x83,0x11 */ + SM3h = 0x5e9f807f /* 1.2.156.10197.1.401 */ +#endif +}; + +enum Block_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x02 */ + AES128CBCb = 414, /* 2.16.840.1.101.3.4.1.2 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x06 */ + AES128GCMb = 418, /* 2.16.840.1.101.3.4.1.6 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x07 */ + AES128CCMb = 419, /* 2.16.840.1.101.3.4.1.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x16 */ + AES192CBCb = 434, /* 2.16.840.1.101.3.4.1.22 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x1a */ + AES192GCMb = 438, /* 2.16.840.1.101.3.4.1.26 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x1b */ + AES192CCMb = 439, /* 2.16.840.1.101.3.4.1.27 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2a */ + AES256CBCb = 454, /* 2.16.840.1.101.3.4.1.42 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2e */ + AES256GCMb = 458, /* 2.16.840.1.101.3.4.1.46 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2f */ + AES256CCMb = 459, /* 2.16.840.1.101.3.4.1.47 */ + /* 0x2b,0x0e,0x03,0x02,0x07 */ + DESb = 69, /* 1.3.14.3.2.7 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x03,0x07 */ + DES3b = 652 /* 1.2.840.113549.3.7 */ +#else + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x02 */ + AES128CBCb = 0x7fb37af8, /* 2.16.840.1.101.3.4.1.2 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x06 */ + AES128GCMb = 0x7fb37afc, /* 2.16.840.1.101.3.4.1.6 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x07 */ + AES128CCMb = 0x7fb37afd, /* 2.16.840.1.101.3.4.1.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x16 */ + AES192CBCb = 0x7fb37aec, /* 2.16.840.1.101.3.4.1.22 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x1a */ + AES192GCMb = 0x7fb37ae0, /* 2.16.840.1.101.3.4.1.26 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x1b */ + AES192CCMb = 0x7fb37ae1, /* 2.16.840.1.101.3.4.1.27 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2a */ + AES256CBCb = 0x7fb37ad0, /* 2.16.840.1.101.3.4.1.42 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2e */ + AES256GCMb = 0x7fb37ad4, /* 2.16.840.1.101.3.4.1.46 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2f */ + AES256CCMb = 0x7fb37ad5, /* 2.16.840.1.101.3.4.1.47 */ + /* 0x2b,0x0e,0x03,0x02,0x07 */ + DESb = 0x7d03f12c, /* 1.3.14.3.2.7 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x03,0x07 */ + DES3b = 0x014b8bdd /* 1.2.840.113549.3.7 */ +#endif +}; + +enum Key_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x00 */ + ANONk = 0, /* 0.0 */ + /* 0x2a,0x86,0x48,0xce,0x38,0x04,0x01 */ + DSAk = 515, /* 1.2.840.10040.4.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01 */ + RSAk = 645, /* 1.2.840.113549.1.1.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0a */ + RSAPSSk = 654, /* 1.2.840.113549.1.1.10 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x07 */ + RSAESOAEPk = 651, /* 1.2.840.113549.1.1.7 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01 */ + ECDSAk = 518, /* 1.2.840.10045.2.1 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x82,0x2d */ + SM2k = 667, /* 1.2.156.10197.1.301 */ + /* 0x2b,0x65,0x70 */ + ED25519k = 256, /* 1.3.101.112 */ + /* 0x2b,0x65,0x6e */ + X25519k = 254, /* 1.3.101.110 */ + /* 0x2b,0x65,0x71 */ + ED448k = 257, /* 1.3.101.113 */ + /* 0x2b,0x65,0x6f */ + X448k = 255, /* 1.3.101.111 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x03,0x01 */ + DHk = 647, /* 1.2.840.113549.1.3.1 */ + /* 0x2b,0xce,0x0f,0x03,0x06 */ + FALCON_LEVEL1k = 273, /* 1.3.9999.3.6 */ + /* 0x2b,0xce,0x0f,0x03,0x09 */ + FALCON_LEVEL5k = 276, /* 1.3.9999.3.9 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x04,0x04 */ + DILITHIUM_LEVEL2k = 218, /* 1.3.6.1.4.1.2.267.12.4.4 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x06,0x05 */ + DILITHIUM_LEVEL3k = 221, /* 1.3.6.1.4.1.2.267.12.6.5 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x08,0x07 */ + DILITHIUM_LEVEL5k = 225, /* 1.3.6.1.4.1.2.267.12.8.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x11 */ + ML_DSA_LEVEL2k = 431, /* 2.16.840.1.101.3.4.3.17 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x12 */ + ML_DSA_LEVEL3k = 432, /* 2.16.840.1.101.3.4.3.18 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x13 */ + ML_DSA_LEVEL5k = 433, /* 2.16.840.1.101.3.4.3.19 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x04 */ + SPHINCS_FAST_LEVEL1k = 281, /* 1.3.9999.6.7.4 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x03 */ + SPHINCS_FAST_LEVEL3k = 283, /* 1.3.9999.6.8.3 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x03 */ + SPHINCS_FAST_LEVEL5k = 282, /* 1.3.9999.6.9.3 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x0a */ + SPHINCS_SMALL_LEVEL1k = 287, /* 1.3.9999.6.7.10 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x07 */ + SPHINCS_SMALL_LEVEL3k = 285, /* 1.3.9999.6.8.7 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x07 */ + SPHINCS_SMALL_LEVEL5k = 286 /* 1.3.9999.6.9.7 */ +#else + /* 0x00 */ + ANONk = 0x7fffffff, /* 0.0 */ + /* 0x2a,0x86,0x48,0xce,0x38,0x04,0x01 */ + DSAk = 0x31498212, /* 1.2.840.10040.4.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01 */ + RSAk = 0x78b67423, /* 1.2.840.113549.1.1.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0a */ + RSAPSSk = 0x78b67428, /* 1.2.840.113549.1.1.10 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x07 */ + RSAESOAEPk = 0x78b67425, /* 1.2.840.113549.1.1.7 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01 */ + ECDSAk = 0x31498417, /* 1.2.840.10045.2.1 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x82,0x2d */ + SM2k = 0x629e807f, /* 1.2.156.10197.1.301 */ + /* 0x2b,0x65,0x70 */ + ED25519k = 0x7f8f65d4, /* 1.3.101.112 */ + /* 0x2b,0x65,0x6e */ + X25519k = 0x7f9165d4, /* 1.3.101.110 */ + /* 0x2b,0x65,0x71 */ + ED448k = 0x7f8e65d4, /* 1.3.101.113 */ + /* 0x2b,0x65,0x6f */ + X448k = 0x7f9065d4, /* 1.3.101.111 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x03,0x01 */ + DHk = 0x7ab67423, /* 1.2.840.113549.1.3.1 */ + /* 0x2b,0xce,0x0f,0x03,0x06 */ + FALCON_LEVEL1k = 0x7c0f312d, /* 1.3.9999.3.6 */ + /* 0x2b,0xce,0x0f,0x03,0x09 */ + FALCON_LEVEL5k = 0x7c0f3122, /* 1.3.9999.3.9 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x04,0x04 */ + DILITHIUM_LEVEL2k = 0x707800d9, /* 1.3.6.1.4.1.2.267.12.4.4 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x06,0x05 */ + DILITHIUM_LEVEL3k = 0x707902d9, /* 1.3.6.1.4.1.2.267.12.6.5 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x08,0x07 */ + DILITHIUM_LEVEL5k = 0x707b0cd9, /* 1.3.6.1.4.1.2.267.12.8.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x11 */ + ML_DSA_LEVEL2k = 0x7db37aeb, /* 2.16.840.1.101.3.4.3.17 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x12 */ + ML_DSA_LEVEL3k = 0x7db37ae8, /* 2.16.840.1.101.3.4.3.18 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x13 */ + ML_DSA_LEVEL5k = 0x7db37ae9, /* 2.16.840.1.101.3.4.3.19 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x04 */ + SPHINCS_FAST_LEVEL1k = 0x06f0ca2c, /* 1.3.9999.6.7.4 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x03 */ + SPHINCS_FAST_LEVEL3k = 0x06f0cd23, /* 1.3.9999.6.8.3 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x03 */ + SPHINCS_FAST_LEVEL5k = 0x06f0cd22, /* 1.3.9999.6.9.3 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x0a */ + SPHINCS_SMALL_LEVEL1k = 0x06f0c42c, /* 1.3.9999.6.7.10 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x07 */ + SPHINCS_SMALL_LEVEL3k = 0x06f0c923, /* 1.3.9999.6.8.7 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x07 */ + SPHINCS_SMALL_LEVEL5k = 0x06f0c922 /* 1.3.9999.6.9.7 */ +#endif +}; + +enum KeyWrap_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x05 */ + AES128_WRAP = 417, /* 2.16.840.1.101.3.4.1.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x19 */ + AES192_WRAP = 437, /* 2.16.840.1.101.3.4.1.25 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2d */ + AES256_WRAP = 457, /* 2.16.840.1.101.3.4.1.45 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x03,0x09 */ + PWRI_KEK_WRAP = 680 /* 1.2.840.113549.1.9.16.3.9 */ +#else + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x05 */ + AES128_WRAP = 0x7fb37aff, /* 2.16.840.1.101.3.4.1.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x19 */ + AES192_WRAP = 0x7fb37ae3, /* 2.16.840.1.101.3.4.1.25 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2d */ + AES256_WRAP = 0x7fb37ad7, /* 2.16.840.1.101.3.4.1.45 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x03,0x09 */ + PWRI_KEK_WRAP = 0x70bf8832 /* 1.2.840.113549.1.9.16.3.9 */ +#endif +}; + +enum Key_Agree { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x81,0x05,0x10,0x86,0x48,0x3f,0x00,0x02 */ + /* 1.3.133.16.840.63.0.2 */ + dhSinglePass_stdDH_sha1kdf_scheme = 464, + /* 0x2b,0x81,0x04,0x01,0x0b,0x00 */ + /* 1.3.132.1.11.0 */ + dhSinglePass_stdDH_sha224kdf_scheme = 188, + /* 0x2b,0x81,0x04,0x01,0x0b,0x01 */ + /* 1.3.132.1.11.1 */ + dhSinglePass_stdDH_sha256kdf_scheme = 189, + /* 0x2b,0x81,0x04,0x01,0x0b,0x02 */ + /* 1.3.132.1.11.2 */ + dhSinglePass_stdDH_sha384kdf_scheme = 190, + /* 0x2b,0x81,0x04,0x01,0x0b,0x03 */ + /* 1.3.132.1.11.3 */ + dhSinglePass_stdDH_sha512kdf_scheme = 191 +#else + /* 0x2b,0x81,0x05,0x10,0x86,0x48,0x3f,0x00,0x02 */ + /* 1.3.133.16.840.63.0.2 */ + dhSinglePass_stdDH_sha1kdf_scheme = 0x6fc53650, + /* 0x2b,0x81,0x04,0x01,0x0b,0x00 */ + /* 1.3.132.1.11.0 */ + dhSinglePass_stdDH_sha224kdf_scheme = 0x01fb8120, + /* 0x2b,0x81,0x04,0x01,0x0b,0x01 */ + /* 1.3.132.1.11.1 */ + dhSinglePass_stdDH_sha256kdf_scheme = 0x01fb8020, + /* 0x2b,0x81,0x04,0x01,0x0b,0x02 */ + /* 1.3.132.1.11.2 */ + dhSinglePass_stdDH_sha384kdf_scheme = 0x01fb8320, + /* 0x2b,0x81,0x04,0x01,0x0b,0x03 */ + /* 1.3.132.1.11.3 */ + dhSinglePass_stdDH_sha512kdf_scheme = 0x01fb8220 +#endif +}; + +enum KDF_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x05,0x0c */ + PBKDF2_OID = 660, /* 1.2.840.113549.1.5.12 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x08 */ + MGF1_OID = 652 /* 1.2.840.113549.1.1.8 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x05,0x0c */ + PBKDF2_OID = 0x7cb6742e, /* 1.2.840.113549.1.5.12 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x08 */ + MGF1_OID = 0x78b6742a /* 1.2.840.113549.1.1.8 */ +#endif +}; + +enum HMAC_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x08 */ + HMAC_SHA224_OID = 652, /* 1.2.840.113549.2.8 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x09 */ + HMAC_SHA256_OID = 653, /* 1.2.840.113549.2.9 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x0a */ + HMAC_SHA384_OID = 654, /* 1.2.840.113549.2.10 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x0b */ + HMAC_SHA512_OID = 655, /* 1.2.840.113549.2.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0d */ + HMAC_SHA3_224_OID = 426, /* 2.16.840.1.101.3.4.2.13 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0e */ + HMAC_SHA3_256_OID = 427, /* 2.16.840.1.101.3.4.2.14 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0f */ + HMAC_SHA3_384_OID = 428, /* 2.16.840.1.101.3.4.2.15 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x10 */ + HMAC_SHA3_512_OID = 429 /* 2.16.840.1.101.3.4.2.16 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x08 */ + HMAC_SHA224_OID = 0x0e4a8bdd, /* 1.2.840.113549.2.8 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x09 */ + HMAC_SHA256_OID = 0x0f4a8bdd, /* 1.2.840.113549.2.9 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x0a */ + HMAC_SHA384_OID = 0x0c4a8bdd, /* 1.2.840.113549.2.10 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x0b */ + HMAC_SHA512_OID = 0x0d4a8bdd, /* 1.2.840.113549.2.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0d */ + HMAC_SHA3_224_OID = 0x7cb37af7, /* 2.16.840.1.101.3.4.2.13 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0e */ + HMAC_SHA3_256_OID = 0x7cb37af4, /* 2.16.840.1.101.3.4.2.14 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0f */ + HMAC_SHA3_384_OID = 0x7cb37af5, /* 2.16.840.1.101.3.4.2.15 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x10 */ + HMAC_SHA3_512_OID = 0x7cb37aea /* 2.16.840.1.101.3.4.2.16 */ +#endif +}; + +enum Extensions_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x55,0x1d,0x13 */ + BASIC_CA_OID = 133, /* 2.5.29.19 */ + /* 0x55,0x1d,0x11 */ + ALT_NAMES_OID = 131, /* 2.5.29.17 */ + /* 0x55,0x1d,0x1f */ + CRL_DIST_OID = 145, /* 2.5.29.31 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x01 */ + AUTH_INFO_OID = 69, /* 1.3.6.1.5.5.7.1.1 */ + /* 0x55,0x1d,0x23 */ + AUTH_KEY_OID = 149, /* 2.5.29.35 */ + /* 0x55,0x1d,0x0e */ + SUBJ_KEY_OID = 128, /* 2.5.29.14 */ + /* 0x55,0x1d,0x20 */ + CERT_POLICY_OID = 146, /* 2.5.29.32 */ + /* 0x55,0x1d,0x14 */ + CRL_NUMBER_OID = 134, /* 2.5.29.20 */ + /* 0x55,0x1d,0x0f */ + KEY_USAGE_OID = 129, /* 2.5.29.15 */ + /* 0x55,0x1d,0x36 */ + INHIBIT_ANY_OID = 168, /* 2.5.29.54 */ + /* 0x55,0x1d,0x25 */ + EXT_KEY_USAGE_OID = 151, /* 2.5.29.37 */ + /* 0x55,0x1d,0x1e */ + NAME_CONS_OID = 144, /* 2.5.29.30 */ + /* 0x55,0x1d,0x10 */ + PRIV_KEY_USAGE_PERIOD_OID = 130, /* 2.5.29.16 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x0b */ + SUBJ_INFO_ACC_OID = 79, /* 1.3.6.1.5.5.7.1.11 */ + /* 0x55,0x1d,0x21 */ + POLICY_MAP_OID = 147, /* 2.5.29.33 */ + /* 0x55,0x1d,0x24 */ + POLICY_CONST_OID = 150, /* 2.5.29.36 */ + /* 0x55,0x1d,0x12 */ + ISSUE_ALT_NAMES_OID = 132, /* 2.5.29.18 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x18 */ + TLS_FEATURE_OID = 92, /* 1.3.6.1.5.5.7.1.24 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x08,0x07 */ + DNS_SRV_OID = 82, /* 1.3.6.1.5.5.7.8.7 */ + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x01 */ + NETSCAPE_CT_OID = 753, /* 2.16.840.1.113730.1.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x05 */ + OCSP_NOCHECK_OID = 121, /* 1.3.6.1.5.5.7.48.1.5 */ + /* 0x55,0x1d,0x09 */ + SUBJ_DIR_ATTR_OID = 123, /* 2.5.29.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x02,0x4e,0x05 */ + AKEY_PACKAGE_OID = 492, /* 2.16.840.1.101.2.1.2.78.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x06,0x06 */ + FASCN_OID = 419, /* 2.16.840.1.101.3.6.6 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x14,0x02,0x03 */ + UPN_OID = 265, /* 1.3.6.1.4.1.311.20.2.3 */ + /* 0x55,0x1d,0x48 */ + SUBJ_ALT_PUB_KEY_INFO_OID = 186, /* 2.5.29.72 */ + /* 0x55,0x1d,0x49 */ + ALT_SIG_ALG_OID = 187, /* 2.5.29.73 */ + /* 0x55,0x1d,0x4a */ + ALT_SIG_VAL_OID = 188 /* 2.5.29.74 */ +#else + /* 0x55,0x1d,0x13 */ + BASIC_CA_OID = 0x7fec1daa, /* 2.5.29.19 */ + /* 0x55,0x1d,0x11 */ + ALT_NAMES_OID = 0x7fee1daa, /* 2.5.29.17 */ + /* 0x55,0x1d,0x1f */ + CRL_DIST_OID = 0x7fe01daa, /* 2.5.29.31 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x01 */ + AUTH_INFO_OID = 0x0400012e, /* 1.3.6.1.5.5.7.1.1 */ + /* 0x55,0x1d,0x23 */ + AUTH_KEY_OID = 0x7fdc1daa, /* 2.5.29.35 */ + /* 0x55,0x1d,0x0e */ + SUBJ_KEY_OID = 0x7ff11daa, /* 2.5.29.14 */ + /* 0x55,0x1d,0x20 */ + CERT_POLICY_OID = 0x7fdf1daa, /* 2.5.29.32 */ + /* 0x55,0x1d,0x14 */ + CRL_NUMBER_OID = 0x7feb1daa, /* 2.5.29.20 */ + /* 0x55,0x1d,0x0f */ + KEY_USAGE_OID = 0x7ff01daa, /* 2.5.29.15 */ + /* 0x55,0x1d,0x36 */ + INHIBIT_ANY_OID = 0x7fc91daa, /* 2.5.29.54 */ + /* 0x55,0x1d,0x25 */ + EXT_KEY_USAGE_OID = 0x7fda1daa, /* 2.5.29.37 */ + /* 0x55,0x1d,0x1e */ + NAME_CONS_OID = 0x7fe11daa, /* 2.5.29.30 */ + /* 0x55,0x1d,0x10 */ + PRIV_KEY_USAGE_PERIOD_OID = 0x7fef1daa, /* 2.5.29.16 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x0b */ + SUBJ_INFO_ACC_OID = 0x0e00012e, /* 1.3.6.1.5.5.7.1.11 */ + /* 0x55,0x1d,0x21 */ + POLICY_MAP_OID = 0x7fde1daa, /* 2.5.29.33 */ + /* 0x55,0x1d,0x24 */ + POLICY_CONST_OID = 0x7fdb1daa, /* 2.5.29.36 */ + /* 0x55,0x1d,0x12 */ + ISSUE_ALT_NAMES_OID = 0x7fed1daa, /* 2.5.29.18 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x01,0x18 */ + TLS_FEATURE_OID = 0x1d00012e, /* 1.3.6.1.5.5.7.1.24 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x08,0x07 */ + DNS_SRV_OID = 0x0209012e, /* 1.3.6.1.5.5.7.8.7 */ + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x01 */ + NETSCAPE_CT_OID = 0x7ff58118, /* 2.16.840.1.113730.1.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x05 */ + OCSP_NOCHECK_OID = 0x7bcefed4, /* 1.3.6.1.5.5.7.48.1.5 */ + /* 0x55,0x1d,0x09 */ + SUBJ_DIR_ATTR_OID = 0x7ff61daa, /* 2.5.29.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x02,0x4e,0x05 */ + AKEY_PACKAGE_OID = 0x034981b4, /* 2.16.840.1.101.2.1.2.78.5 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x06,0x06 */ + FASCN_OID = 0x074e8505, /* 2.16.840.1.101.3.6.6 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x14,0x02,0x03 */ + UPN_OID = 0x103687d7, /* 1.3.6.1.4.1.311.20.2.3 */ + /* 0x55,0x1d,0x48 */ + SUBJ_ALT_PUB_KEY_INFO_OID = 0x7fb71daa, /* 2.5.29.72 */ + /* 0x55,0x1d,0x49 */ + ALT_SIG_ALG_OID = 0x7fb61daa, /* 2.5.29.73 */ + /* 0x55,0x1d,0x4a */ + ALT_SIG_VAL_OID = 0x7fb51daa /* 2.5.29.74 */ +#endif +}; + +enum CertificatePolicy_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x55,0x1d,0x20,0x00 */ + /* 2.5.29.32.0 */ + CP_ANY_OID = 146, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xdf,0x13,0x01,0x01,0x01 */ + /* 1.3.6.1.4.1.44947.1.1.1 */ + CP_ISRG_DOMAIN_VALID = 430, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x04 */ + /* 2.16.840.1.101.3.2.1.3.4 */ + CP_FPKI_HIGH_ASSURANCE_OID = 417, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x07 */ + /* 2.16.840.1.101.3.2.1.3.7 */ + CP_FPKI_COMMON_HARDWARE_OID = 420, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x0c */ + /* 2.16.840.1.101.3.2.1.3.12 */ + CP_FPKI_MEDIUM_HARDWARE_OID = 425, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x0d */ + /* 2.16.840.1.101.3.2.1.3.13 */ + CP_FPKI_COMMON_AUTH_OID = 426, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x10 */ + /* 2.16.840.1.101.3.2.1.3.16 */ + CP_FPKI_COMMON_HIGH_OID = 429, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x12 */ + /* 2.16.840.1.101.3.2.1.3.18 */ + CP_FPKI_PIVI_HARDWARE_OID = 431, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x14 */ + /* 2.16.840.1.101.3.2.1.3.20 */ + CP_FPKI_PIVI_CONTENT_SIGNING_OID = 433, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x24 */ + /* 2.16.840.1.101.3.2.1.3.36 */ + CP_FPKI_COMMON_DEVICES_HARDWARE_OID = 449, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x26 */ + /* 2.16.840.1.101.3.2.1.3.38 */ + CP_FPKI_MEDIUM_DEVICE_HARDWARE_OID = 451, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x27 */ + /* 2.16.840.1.101.3.2.1.3.39 */ + CP_FPKI_COMMON_PIV_CONTENT_SIGNING_OID = 452, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x28 */ + /* 2.16.840.1.101.3.2.1.3.40 */ + CP_FPKI_PIV_AUTH_OID = 453, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x29 */ + /* 2.16.840.1.101.3.2.1.3.41 */ + CP_FPKI_PIV_AUTH_HW_OID = 454, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x2d */ + /* 2.16.840.1.101.3.2.1.3.45 */ + CP_FPKI_PIVI_AUTH_OID = 458, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x2f */ + /* 2.16.840.1.101.3.2.1.3.47 */ + CP_FPKI_COMMON_PIVI_CONTENT_SIGNING_OID = 460, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x0b */ + /* 2.16.840.1.101.3.2.1.48.11 */ + CP_FPKI_AUTH_TEST_OID = 469, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x0d */ + /* 2.16.840.1.101.3.2.1.48.13 */ + CP_FPKI_CARDAUTH_TEST_OID = 471, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x56 */ + /* 2.16.840.1.101.3.2.1.48.86 */ + CP_FPKI_PIV_CONTENT_TEST_OID = 544, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x6d */ + /* 2.16.840.1.101.3.2.1.48.109 */ + CP_FPKI_PIV_AUTH_DERIVED_TEST_OID = 567, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x6e */ + /* 2.16.840.1.101.3.2.1.48.110 */ + CP_FPKI_PIV_AUTH_DERIVED_HW_TEST_OID = 568, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x05 */ + /* 2.16.840.1.101.2.1.11.5 */ + CP_DOD_MEDIUM_OID = 423, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x09 */ + /* 2.16.840.1.101.2.1.11.9 */ + CP_DOD_MEDIUM_HARDWARE_OID = 427, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x0a */ + /* 2.16.840.1.101.2.1.11.10 */ + CP_DOD_PIV_AUTH_OID = 428, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x11 */ + /* 2.16.840.1.101.2.1.11.17 */ + CP_DOD_MEDIUM_NPE_OID = 435, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x12 */ + /* 2.16.840.1.101.2.1.11.18 */ + CP_DOD_MEDIUM_2048_OID = 436, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x13 */ + /* 2.16.840.1.101.2.1.11.19 */ + CP_DOD_MEDIUM_HARDWARE_2048_OID = 437, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x14 */ + /* 2.16.840.1.101.2.1.11.20 */ + CP_DOD_PIV_AUTH_2048_OID = 438, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x1f */ + /* 2.16.840.1.101.2.1.11.31 */ + CP_DOD_PEER_INTEROP_OID = 100449, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x24 */ + /* 2.16.840.1.101.2.1.11.36 */ + CP_DOD_MEDIUM_NPE_112_OID = 100454, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x25 */ + /* 2.16.840.1.101.2.1.11.37 */ + CP_DOD_MEDIUM_NPE_128_OID = 455, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x26 */ + /* 2.16.840.1.101.2.1.11.38 */ + CP_DOD_MEDIUM_NPE_192_OID = 456, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x27 */ + /* 2.16.840.1.101.2.1.11.39 */ + CP_DOD_MEDIUM_112_OID = 457, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x28 */ + /* 2.16.840.1.101.2.1.11.40 */ + CP_DOD_MEDIUM_128_OID = 100458, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x29 */ + /* 2.16.840.1.101.2.1.11.41 */ + CP_DOD_MEDIUM_192_OID = 459, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2a */ + /* 2.16.840.1.101.2.1.11.42 */ + CP_DOD_MEDIUM_HARDWARE_112_OID = 100460, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2b */ + /* 2.16.840.1.101.2.1.11.43 */ + CP_DOD_MEDIUM_HARDWARE_128_OID = 461, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2c */ + /* 2.16.840.1.101.2.1.11.44 */ + CP_DOD_MEDIUM_HARDWARE_192_OID = 462, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3b */ + /* 2.16.840.1.101.2.1.11.59 */ + CP_DOD_ADMIN_OID = 477, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3c */ + /* 2.16.840.1.101.2.1.11.60 */ + CP_DOD_INTERNAL_NPE_112_OID = 478, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3d */ + /* 2.16.840.1.101.2.1.11.61 */ + CP_DOD_INTERNAL_NPE_128_OID = 479, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3e */ + /* 2.16.840.1.101.2.1.11.62 */ + CP_DOD_INTERNAL_NPE_192_OID = 480, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x01 */ + /* 2.16.840.1.101.3.2.1.12.1 */ + CP_ECA_MEDIUM_OID = 100423, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x02 */ + /* 2.16.840.1.101.3.2.1.12.2 */ + CP_ECA_MEDIUM_HARDWARE_OID = 424, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x03 */ + /* 2.16.840.1.101.3.2.1.12.3 */ + CP_ECA_MEDIUM_TOKEN_OID = 100425, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x04 */ + /* 2.16.840.1.101.3.2.1.12.4 */ + CP_ECA_MEDIUM_SHA256_OID = 100426, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x05 */ + /* 2.16.840.1.101.3.2.1.12.5 */ + CP_ECA_MEDIUM_TOKEN_SHA256_OID = 100427, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x06 */ + /* 2.16.840.1.101.3.2.1.12.6 */ + CP_ECA_MEDIUM_HARDWARE_PIVI_OID = 100428, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x08 */ + /* 2.16.840.1.101.3.2.1.12.8 */ + CP_ECA_CONTENT_SIGNING_PIVI_OID = 100430, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x09 */ + /* 2.16.840.1.101.3.2.1.12.9 */ + CP_ECA_MEDIUM_DEVICE_SHA256_OID = 431, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x0a */ + /* 2.16.840.1.101.3.2.1.12.10 */ + CP_ECA_MEDIUM_HARDWARE_SHA256_OID = 432, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x01 */ + /* 2.16.840.1.101.3.2.1.6.1 */ + CP_STATE_BASIC_OID = 100417, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x02 */ + /* 2.16.840.1.101.3.2.1.6.2 */ + CP_STATE_LOW_OID = 418, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x03 */ + /* 2.16.840.1.101.3.2.1.6.3 */ + CP_STATE_MODERATE_OID = 100419, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x04 */ + /* 2.16.840.1.101.3.2.1.6.4 */ + CP_STATE_HIGH_OID = 100420, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x0c */ + /* 2.16.840.1.101.3.2.1.6.12 */ + CP_STATE_MEDHW_OID = 101428, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x26 */ + /* 2.16.840.1.101.3.2.1.6.38 */ + CP_STATE_MEDDEVHW_OID = 101454, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x04 */ + /* 2.16.840.1.101.3.2.1.5.4 */ + CP_TREAS_MEDIUMHW_OID = 419, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x05 */ + /* 2.16.840.1.101.3.2.1.5.5 */ + CP_TREAS_HIGH_OID = 101420, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x0a */ + /* 2.16.840.1.101.3.2.1.5.10 */ + CP_TREAS_PIVI_HW_OID = 101425, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x0c */ + /* 2.16.840.1.101.3.2.1.5.12 */ + CP_TREAS_PIVI_CONTENT_OID = 101427, + /* 0x2b,0x06,0x01,0x04,0x01,0x49,0x0f,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.73.15.3.1.12 */ + CP_BOEING_MEDIUMHW_SHA256_OID = 159, + /* 0x2b,0x06,0x01,0x04,0x01,0x49,0x0f,0x03,0x01,0x11 */ + /* 1.3.6.1.4.1.73.15.3.1.17 */ + CP_BOEING_MEDIUMHW_CONTENT_SHA256_OID = 164, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.45606.3.1.12 */ + CP_CARILLON_MEDIUMHW_256_OID = 467, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x14 */ + /* 1.3.6.1.4.1.45606.3.1.20 */ + CP_CARILLON_AIVHW_OID = 475, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x16 */ + /* 1.3.6.1.4.1.45606.3.1.22 */ + CP_CARILLON_AIVCONTENT_OID = 100477, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.25054.3.1.12 */ + CP_CIS_MEDIUMHW_256_OID = 489, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x0e */ + /* 1.3.6.1.4.1.25054.3.1.14 */ + CP_CIS_MEDDEVHW_256_OID = 491, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x14 */ + /* 1.3.6.1.4.1.25054.3.1.20 */ + CP_CIS_ICECAP_HW_OID = 497, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x16 */ + /* 1.3.6.1.4.1.25054.3.1.22 */ + CP_CIS_ICECAP_CONTENT_OID = 499, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x02 */ + /* 1.3.6.1.4.1.24019.1.1.1.2 */ + CP_CERTIPATH_MEDIUMHW_OID = 100459, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x03 */ + /* 1.3.6.1.4.1.24019.1.1.1.3 */ + CP_CERTIPATH_HIGHHW_OID = 101460, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x07 */ + /* 1.3.6.1.4.1.24019.1.1.1.7 */ + CP_CERTIPATH_ICECAP_HW_OID = 464, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x09 */ + /* 1.3.6.1.4.1.24019.1.1.1.9 */ + CP_CERTIPATH_ICECAP_CONTENT_OID = 466, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x12 */ + /* 1.3.6.1.4.1.24019.1.1.1.18 */ + CP_CERTIPATH_VAR_MEDIUMHW_OID = 100475, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x13 */ + /* 1.3.6.1.4.1.24019.1.1.1.19 */ + CP_CERTIPATH_VAR_HIGHHW_OID = 476, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x02 */ + /* 1.3.6.1.4.1.38099.1.1.1.2 */ + CP_TSCP_MEDIUMHW_OID = 442, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x05 */ + /* 1.3.6.1.4.1.38099.1.1.1.5 */ + CP_TSCP_PIVI_OID = 445, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x07 */ + /* 1.3.6.1.4.1.38099.1.1.1.7 */ + CP_TSCP_PIVI_CONTENT_OID = 447, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x07 */ + /* 2.16.840.1.113733.1.7.23.3.1.7 */ + CP_DIGICERT_NFSSP_MEDIUMHW_OID = 796, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x0d */ + /* 2.16.840.1.113733.1.7.23.3.1.13 */ + CP_DIGICERT_NFSSP_AUTH_OID = 802, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x12 */ + /* 2.16.840.1.113733.1.7.23.3.1.18 */ + CP_DIGICERT_NFSSP_PIVI_HW_OID = 807, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x14 */ + /* 2.16.840.1.113733.1.7.23.3.1.20 */ + CP_DIGICERT_NFSSP_PIVI_CONTENT_OID = 809, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x24 */ + /* 2.16.840.1.113733.1.7.23.3.1.36 */ + CP_DIGICERT_NFSSP_MEDDEVHW_OID = 825, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x02 */ + /* 2.16.840.1.114027.200.3.10.7.2 */ + CP_ENTRUST_NFSSP_MEDIUMHW_OID = 1017, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x04 */ + /* 2.16.840.1.114027.200.3.10.7.4 */ + CP_ENTRUST_NFSSP_MEDAUTH_OID = 1019, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x06 */ + /* 2.16.840.1.114027.200.3.10.7.6 */ + CP_ENTRUST_NFSSP_PIVI_HW_OID = 1021, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x09 */ + /* 2.16.840.1.114027.200.3.10.7.9 */ + CP_ENTRUST_NFSSP_PIVI_CONTENT_OID = 1024, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x10 */ + /* 2.16.840.1.114027.200.3.10.7.16 */ + CP_ENTRUST_NFSSP_MEDDEVHW_OID = 1031, + /* 0x2b,0x06,0x01,0x04,0x01,0xec,0x7c,0x01,0x01,0x01,0x06 */ + /* 1.3.6.1.4.1.13948.1.1.1.6 */ + CP_EXOSTAR_MEDIUMHW_SHA2_OID = 100424, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x0c,0x01 */ + /* 2.16.840.1.113839.0.100.12.1 */ + CP_IDENTRUST_MEDIUMHW_SIGN_OID = 846, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x0c,0x02 */ + /* 2.16.840.1.113839.0.100.12.2 */ + CP_IDENTRUST_MEDIUMHW_ENC_OID = 847, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x00 */ + /* 2.16.840.1.113839.0.100.18.0 */ + CP_IDENTRUST_PIVI_HW_ID_OID = 851, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x01 */ + /* 2.16.840.1.113839.0.100.18.1 */ + CP_IDENTRUST_PIVI_HW_SIGN_OID = 852, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x02 */ + /* 2.16.840.1.113839.0.100.18.2 */ + CP_IDENTRUST_PIVI_HW_ENC_OID = 853, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x14,0x01 */ + /* 2.16.840.1.113839.0.100.20.1 */ + CP_IDENTRUST_PIVI_CONTENT_OID = 854, + /* 0x2b,0x06,0x01,0x04,0x01,0x67,0x64,0x01,0x01,0x03,0x03 */ + /* 1.3.6.1.4.1.103.100.1.1.3.3 */ + CP_LOCKHEED_MEDIUMHW_OID = 266, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x08 */ + /* 1.3.6.1.4.1.16334.509.2.8 */ + CP_NORTHROP_MEDIUM_256_HW_OID = 654, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x09 */ + /* 1.3.6.1.4.1.16334.509.2.9 */ + CP_NORTHROP_PIVI_256_HW_OID = 655, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x0b */ + /* 1.3.6.1.4.1.16334.509.2.11 */ + CP_NORTHROP_PIVI_256_CONTENT_OID = 657, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x0e */ + /* 1.3.6.1.4.1.16334.509.2.14 */ + CP_NORTHROP_MEDIUM_384_HW_OID = 660, + /* 0x2b,0x06,0x01,0x04,0x01,0x8c,0x21,0x0a,0x01,0x0c */ + /* 1.3.6.1.4.1.1569.10.1.12 */ + CP_RAYTHEON_MEDIUMHW_OID = 251, + /* 0x2b,0x06,0x01,0x04,0x01,0x8c,0x21,0x0a,0x01,0x12 */ + /* 1.3.6.1.4.1.1569.10.1.18 */ + CP_RAYTHEON_MEDDEVHW_OID = 257, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xd1,0x11,0x0a,0x01,0x0c */ + /* 1.3.6.1.4.1.26769.10.1.12 */ + CP_RAYTHEON_SHA2_MEDIUMHW_OID = 433, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xd1,0x11,0x0a,0x01,0x12 */ + /* 1.3.6.1.4.1.26769.10.1.18 */ + CP_RAYTHEON_SHA2_MEDDEVHW_OID = 439, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x0c */ + /* 1.3.6.1.4.1.3922.1.1.1.12 */ + CP_WIDEPOINT_MEDIUMHW_OID = 310, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x12 */ + /* 1.3.6.1.4.1.3922.1.1.1.18 */ + CP_WIDEPOINT_PIVI_HW_OID = 316, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x14 */ + /* 1.3.6.1.4.1.3922.1.1.1.20 */ + CP_WIDEPOINT_PIVI_CONTENT_OID = 318, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x26 */ + /* 1.3.6.1.4.1.3922.1.1.1.38 */ + CP_WIDEPOINT_MEDDEVHW_OID = 336, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x01,0x02 */ + /* 1.2.36.1.334.1.2.1.2 */ + CP_ADO_MEDIUM_OID = 293, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x01,0x03 */ + /* 1.2.36.1.334.1.2.1.3 */ + CP_ADO_HIGH_OID = 294, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x02,0x02 */ + /* 1.2.36.1.334.1.2.2.2 */ + CP_ADO_RESOURCE_MEDIUM_OID = 100294, + /* 0x2b,0x06,0x01,0x04,0x01,0xb2,0x31,0x01,0x02,0x01,0x03,0x04 */ + /* 1.3.6.1.4.1.6449.1.2.1.3.4 */ + CP_COMODO_OID = 100293, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x01 */ + /* 2.16.528.1.1003.1.2.5.1 */ + CP_NL_MOD_AUTH_OID = 496, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x02 */ + /* 2.16.528.1.1003.1.2.5.2 */ + CP_NL_MOD_IRREFUT_OID = 100497, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x03 */ + /* 2.16.528.1.1003.1.2.5.3 */ + CP_NL_MOD_CONFID_OID = 498 +#else + /* 0x55,0x1d,0x20,0x00 */ + /* 2.5.29.32.0 */ + CP_ANY_OID = 0x00df1daa, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xdf,0x13,0x01,0x01,0x01 */ + /* 1.3.6.1.4.1.44947.1.1.1 */ + CP_ISRG_DOMAIN_VALID = 0x682085d4, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x04 */ + /* 2.16.840.1.101.3.2.1.3.4 */ + CP_FPKI_HIGH_ASSURANCE_OID = 0x004a81f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x07 */ + /* 2.16.840.1.101.3.2.1.3.7 */ + CP_FPKI_COMMON_HARDWARE_OID = 0x004a82f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x0c */ + /* 2.16.840.1.101.3.2.1.3.12 */ + CP_FPKI_MEDIUM_HARDWARE_OID = 0x004a89f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x0d */ + /* 2.16.840.1.101.3.2.1.3.13 */ + CP_FPKI_COMMON_AUTH_OID = 0x004a88f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x10 */ + /* 2.16.840.1.101.3.2.1.3.16 */ + CP_FPKI_COMMON_HIGH_OID = 0x004a95f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x12 */ + /* 2.16.840.1.101.3.2.1.3.18 */ + CP_FPKI_PIVI_HARDWARE_OID = 0x004a97f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x14 */ + /* 2.16.840.1.101.3.2.1.3.20 */ + CP_FPKI_PIVI_CONTENT_SIGNING_OID = 0x004a91f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x24 */ + /* 2.16.840.1.101.3.2.1.3.36 */ + CP_FPKI_COMMON_DEVICES_HARDWARE_OID = 0x004aa1f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x26 */ + /* 2.16.840.1.101.3.2.1.3.38 */ + CP_FPKI_MEDIUM_DEVICE_HARDWARE_OID = 0x004aa3f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x27 */ + /* 2.16.840.1.101.3.2.1.3.39 */ + CP_FPKI_COMMON_PIV_CONTENT_SIGNING_OID = 0x004aa2f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x28 */ + /* 2.16.840.1.101.3.2.1.3.40 */ + CP_FPKI_PIV_AUTH_OID = 0x004aadf9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x29 */ + /* 2.16.840.1.101.3.2.1.3.41 */ + CP_FPKI_PIV_AUTH_HW_OID = 0x004aacf9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x2d */ + /* 2.16.840.1.101.3.2.1.3.45 */ + CP_FPKI_PIVI_AUTH_OID = 0x004aa8f9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x03,0x2f */ + /* 2.16.840.1.101.3.2.1.3.47 */ + CP_FPKI_COMMON_PIVI_CONTENT_SIGNING_OID = 0x004aaaf9, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x0b */ + /* 2.16.840.1.101.3.2.1.48.11 */ + CP_FPKI_AUTH_TEST_OID = 0x004a8eca, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x0d */ + /* 2.16.840.1.101.3.2.1.48.13 */ + CP_FPKI_CARDAUTH_TEST_OID = 0x004a88ca, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x56 */ + /* 2.16.840.1.101.3.2.1.48.86 */ + CP_FPKI_PIV_CONTENT_TEST_OID = 0x004ad3ca, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x6d */ + /* 2.16.840.1.101.3.2.1.48.109 */ + CP_FPKI_PIV_AUTH_DERIVED_TEST_OID = 0x004ae8ca, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x30,0x6e */ + /* 2.16.840.1.101.3.2.1.48.110 */ + CP_FPKI_PIV_AUTH_DERIVED_HW_TEST_OID = 0x004aebca, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x05 */ + /* 2.16.840.1.101.2.1.11.5 */ + CP_DOD_MEDIUM_OID = 0x75b67bff, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x09 */ + /* 2.16.840.1.101.2.1.11.9 */ + CP_DOD_MEDIUM_HARDWARE_OID = 0x75b67bf3, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x0a */ + /* 2.16.840.1.101.2.1.11.10 */ + CP_DOD_PIV_AUTH_OID = 0x75b67bf0, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x11 */ + /* 2.16.840.1.101.2.1.11.17 */ + CP_DOD_MEDIUM_NPE_OID = 0x75b67beb, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x12 */ + /* 2.16.840.1.101.2.1.11.18 */ + CP_DOD_MEDIUM_2048_OID = 0x75b67be8, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x13 */ + /* 2.16.840.1.101.2.1.11.19 */ + CP_DOD_MEDIUM_HARDWARE_2048_OID = 0x75b67be9, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x14 */ + /* 2.16.840.1.101.2.1.11.20 */ + CP_DOD_PIV_AUTH_2048_OID = 0x75b67bee, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x1f */ + /* 2.16.840.1.101.2.1.11.31 */ + CP_DOD_PEER_INTEROP_OID = 0x75b67be5, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x24 */ + /* 2.16.840.1.101.2.1.11.36 */ + CP_DOD_MEDIUM_NPE_112_OID = 0x75b67bde, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x25 */ + /* 2.16.840.1.101.2.1.11.37 */ + CP_DOD_MEDIUM_NPE_128_OID = 0x75b67bdf, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x26 */ + /* 2.16.840.1.101.2.1.11.38 */ + CP_DOD_MEDIUM_NPE_192_OID = 0x75b67bdc, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x27 */ + /* 2.16.840.1.101.2.1.11.39 */ + CP_DOD_MEDIUM_112_OID = 0x75b67bdd, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x28 */ + /* 2.16.840.1.101.2.1.11.40 */ + CP_DOD_MEDIUM_128_OID = 0x75b67bd2, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x29 */ + /* 2.16.840.1.101.2.1.11.41 */ + CP_DOD_MEDIUM_192_OID = 0x75b67bd3, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2a */ + /* 2.16.840.1.101.2.1.11.42 */ + CP_DOD_MEDIUM_HARDWARE_112_OID = 0x75b67bd0, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2b */ + /* 2.16.840.1.101.2.1.11.43 */ + CP_DOD_MEDIUM_HARDWARE_128_OID = 0x75b67bd1, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x2c */ + /* 2.16.840.1.101.2.1.11.44 */ + CP_DOD_MEDIUM_HARDWARE_192_OID = 0x75b67bd6, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3b */ + /* 2.16.840.1.101.2.1.11.59 */ + CP_DOD_ADMIN_OID = 0x75b67bc1, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3c */ + /* 2.16.840.1.101.2.1.11.60 */ + CP_DOD_INTERNAL_NPE_112_OID = 0x75b67bc6, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3d */ + /* 2.16.840.1.101.2.1.11.61 */ + CP_DOD_INTERNAL_NPE_128_OID = 0x75b67bc7, + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x0b,0x3e */ + /* 2.16.840.1.101.2.1.11.62 */ + CP_DOD_INTERNAL_NPE_192_OID = 0x75b67bc4, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x01 */ + /* 2.16.840.1.101.3.2.1.12.1 */ + CP_ECA_MEDIUM_OID = 0x004a84f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x02 */ + /* 2.16.840.1.101.3.2.1.12.2 */ + CP_ECA_MEDIUM_HARDWARE_OID = 0x004a87f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x03 */ + /* 2.16.840.1.101.3.2.1.12.3 */ + CP_ECA_MEDIUM_TOKEN_OID = 0x004a86f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x04 */ + /* 2.16.840.1.101.3.2.1.12.4 */ + CP_ECA_MEDIUM_SHA256_OID = 0x004a81f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x05 */ + /* 2.16.840.1.101.3.2.1.12.5 */ + CP_ECA_MEDIUM_TOKEN_SHA256_OID = 0x004a80f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x06 */ + /* 2.16.840.1.101.3.2.1.12.6 */ + CP_ECA_MEDIUM_HARDWARE_PIVI_OID = 0x004a83f6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x08 */ + /* 2.16.840.1.101.3.2.1.12.8 */ + CP_ECA_CONTENT_SIGNING_PIVI_OID = 0x004a8df6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x09 */ + /* 2.16.840.1.101.3.2.1.12.9 */ + CP_ECA_MEDIUM_DEVICE_SHA256_OID = 0x004a8cf6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x0c,0x0a */ + /* 2.16.840.1.101.3.2.1.12.10 */ + CP_ECA_MEDIUM_HARDWARE_SHA256_OID = 0x004a8ff6, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x01 */ + /* 2.16.840.1.101.3.2.1.6.1 */ + CP_STATE_BASIC_OID = 0x004a84fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x02 */ + /* 2.16.840.1.101.3.2.1.6.2 */ + CP_STATE_LOW_OID = 0x004a87fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x03 */ + /* 2.16.840.1.101.3.2.1.6.3 */ + CP_STATE_MODERATE_OID = 0x004a86fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x04 */ + /* 2.16.840.1.101.3.2.1.6.4 */ + CP_STATE_HIGH_OID = 0x004a81fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x0c */ + /* 2.16.840.1.101.3.2.1.6.12 */ + CP_STATE_MEDHW_OID = 0x004a89fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x06,0x26 */ + /* 2.16.840.1.101.3.2.1.6.38 */ + CP_STATE_MEDDEVHW_OID = 0x004aa3fc, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x04 */ + /* 2.16.840.1.101.3.2.1.5.4 */ + CP_TREAS_MEDIUMHW_OID = 0x004a81ff, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x05 */ + /* 2.16.840.1.101.3.2.1.5.5 */ + CP_TREAS_HIGH_OID = 0x004a80ff, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x0a */ + /* 2.16.840.1.101.3.2.1.5.10 */ + CP_TREAS_PIVI_HW_OID = 0x004a8fff, + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x02,0x01,0x05,0x0c */ + /* 2.16.840.1.101.3.2.1.5.12 */ + CP_TREAS_PIVI_CONTENT_OID = 0x004a89ff, + /* 0x2b,0x06,0x01,0x04,0x01,0x49,0x0f,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.73.15.3.1.12 */ + CP_BOEING_MEDIUMHW_SHA256_OID = 0x070e43d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x49,0x0f,0x03,0x01,0x11 */ + /* 1.3.6.1.4.1.73.15.3.1.17 */ + CP_BOEING_MEDIUMHW_CONTENT_SHA256_OID = 0x070e5ed4, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.45606.3.1.12 */ + CP_CARILLON_MEDIUMHW_256_OID = 0x5d1685d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x14 */ + /* 1.3.6.1.4.1.45606.3.1.20 */ + CP_CARILLON_AIVHW_OID = 0x5d0e85d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xe4,0x26,0x03,0x01,0x16 */ + /* 1.3.6.1.4.1.45606.3.1.22 */ + CP_CARILLON_AIVCONTENT_OID = 0x5d0c85d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x0c */ + /* 1.3.6.1.4.1.25054.3.1.12 */ + CP_CIS_MEDIUMHW_256_OID = 0x253186d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x0e */ + /* 1.3.6.1.4.1.25054.3.1.14 */ + CP_CIS_MEDDEVHW_256_OID = 0x253386d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x14 */ + /* 1.3.6.1.4.1.25054.3.1.20 */ + CP_CIS_ICECAP_HW_OID = 0x252986d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xc3,0x5e,0x03,0x01,0x16 */ + /* 1.3.6.1.4.1.25054.3.1.22 */ + CP_CIS_ICECAP_CONTENT_OID = 0x252b86d6, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x02 */ + /* 1.3.6.1.4.1.24019.1.1.1.2 */ + CP_CERTIPATH_MEDIUMHW_OID = 0x554486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x03 */ + /* 1.3.6.1.4.1.24019.1.1.1.3 */ + CP_CERTIPATH_HIGHHW_OID = 0x544486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x07 */ + /* 1.3.6.1.4.1.24019.1.1.1.7 */ + CP_CERTIPATH_ICECAP_HW_OID = 0x504486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x09 */ + /* 1.3.6.1.4.1.24019.1.1.1.9 */ + CP_CERTIPATH_ICECAP_CONTENT_OID = 0x5e4486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x12 */ + /* 1.3.6.1.4.1.24019.1.1.1.18 */ + CP_CERTIPATH_VAR_MEDIUMHW_OID = 0x454486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xbb,0x53,0x01,0x01,0x01,0x13 */ + /* 1.3.6.1.4.1.24019.1.1.1.19 */ + CP_CERTIPATH_VAR_HIGHHW_OID = 0x444486d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x02 */ + /* 1.3.6.1.4.1.38099.1.1.1.2 */ + CP_TSCP_MEDIUMHW_OID = 0x555685d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x05 */ + /* 1.3.6.1.4.1.38099.1.1.1.5 */ + CP_TSCP_PIVI_OID = 0x525685d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0xa9,0x53,0x01,0x01,0x01,0x07 */ + /* 1.3.6.1.4.1.38099.1.1.1.7 */ + CP_TSCP_PIVI_CONTENT_OID = 0x505685d4, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x07 */ + /* 2.16.840.1.113733.1.7.23.3.1.7 */ + CP_DIGICERT_NFSSP_MEDIUMHW_OID = 0x7e0e96e6, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x0d */ + /* 2.16.840.1.113733.1.7.23.3.1.13 */ + CP_DIGICERT_NFSSP_AUTH_OID = 0x7e0e96ec, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x12 */ + /* 2.16.840.1.113733.1.7.23.3.1.18 */ + CP_DIGICERT_NFSSP_PIVI_HW_OID = 0x7e0e96f3, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x14 */ + /* 2.16.840.1.113733.1.7.23.3.1.20 */ + CP_DIGICERT_NFSSP_PIVI_CONTENT_OID = 0x7e0e96f5, + /* 0x60,0x86,0x48,0x01,0x86,0xf8,0x45,0x01,0x07,0x17,0x03,0x01,0x24 */ + /* 2.16.840.1.113733.1.7.23.3.1.36 */ + CP_DIGICERT_NFSSP_MEDDEVHW_OID = 0x7e0e96c5, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x02 */ + /* 2.16.840.1.114027.200.3.10.7.2 */ + CP_ENTRUST_NFSSP_MEDIUMHW_OID = 0x782980ac, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x04 */ + /* 2.16.840.1.114027.200.3.10.7.4 */ + CP_ENTRUST_NFSSP_MEDAUTH_OID = 0x782980aa, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x06 */ + /* 2.16.840.1.114027.200.3.10.7.6 */ + CP_ENTRUST_NFSSP_PIVI_HW_OID = 0x782980a8, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x09 */ + /* 2.16.840.1.114027.200.3.10.7.9 */ + CP_ENTRUST_NFSSP_PIVI_CONTENT_OID = 0x782980a7, + /* 0x60,0x86,0x48,0x01,0x86,0xfa,0x6b,0x81,0x48,0x03,0x0a,0x07,0x10 */ + /* 2.16.840.1.114027.200.3.10.7.16 */ + CP_ENTRUST_NFSSP_MEDDEVHW_OID = 0x782980be, + /* 0x2b,0x06,0x01,0x04,0x01,0xec,0x7c,0x01,0x01,0x01,0x06 */ + /* 1.3.6.1.4.1.13948.1.1.1.6 */ + CP_EXOSTAR_MEDIUMHW_SHA2_OID = 0x7a84ebd4, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x0c,0x01 */ + /* 2.16.840.1.113839.0.100.12.1 */ + CP_IDENTRUST_MEDIUMHW_SIGN_OID = 0x7e99737d, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x0c,0x02 */ + /* 2.16.840.1.113839.0.100.12.2 */ + CP_IDENTRUST_MEDIUMHW_ENC_OID = 0x7e9a737d, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x00 */ + /* 2.16.840.1.113839.0.100.18.0 */ + CP_IDENTRUST_PIVI_HW_ID_OID = 0x7e986d7d, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x01 */ + /* 2.16.840.1.113839.0.100.18.1 */ + CP_IDENTRUST_PIVI_HW_SIGN_OID = 0x7e996d7d, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x12,0x02 */ + /* 2.16.840.1.113839.0.100.18.2 */ + CP_IDENTRUST_PIVI_HW_ENC_OID = 0x7e9a6d7d, + /* 0x60,0x86,0x48,0x01,0x86,0xf9,0x2f,0x00,0x64,0x14,0x01 */ + /* 2.16.840.1.113839.0.100.20.1 */ + CP_IDENTRUST_PIVI_CONTENT_OID = 0x7e996b7d, + /* 0x2b,0x06,0x01,0x04,0x01,0x67,0x64,0x01,0x01,0x03,0x03 */ + /* 1.3.6.1.4.1.103.100.1.1.3.3 */ + CP_LOCKHEED_MEDIUMHW_OID = 0x7a9962d4, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x08 */ + /* 1.3.6.1.4.1.16334.509.2.8 */ + CP_NORTHROP_MEDIUM_256_HW_OID = 0x78b8fba8, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x09 */ + /* 1.3.6.1.4.1.16334.509.2.9 */ + CP_NORTHROP_PIVI_256_HW_OID = 0x78b9fba8, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x0b */ + /* 1.3.6.1.4.1.16334.509.2.11 */ + CP_NORTHROP_PIVI_256_CONTENT_OID = 0x78bbfba8, + /* 0x2b,0x06,0x01,0x04,0x01,0xff,0x4e,0x83,0x7d,0x02,0x0e */ + /* 1.3.6.1.4.1.16334.509.2.14 */ + CP_NORTHROP_MEDIUM_384_HW_OID = 0x78befba8, + /* 0x2b,0x06,0x01,0x04,0x01,0x8c,0x21,0x0a,0x01,0x0c */ + /* 1.3.6.1.4.1.1569.10.1.12 */ + CP_RAYTHEON_MEDIUMHW_OID = 0x0e2086d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x8c,0x21,0x0a,0x01,0x12 */ + /* 1.3.6.1.4.1.1569.10.1.18 */ + CP_RAYTHEON_MEDDEVHW_OID = 0x0e2098d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xd1,0x11,0x0a,0x01,0x0c */ + /* 1.3.6.1.4.1.26769.10.1.12 */ + CP_RAYTHEON_SHA2_MEDIUMHW_OID = 0x6a2386df, + /* 0x2b,0x06,0x01,0x04,0x01,0x81,0xd1,0x11,0x0a,0x01,0x12 */ + /* 1.3.6.1.4.1.26769.10.1.18 */ + CP_RAYTHEON_SHA2_MEDDEVHW_OID = 0x6a3d86df, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x0c */ + /* 1.3.6.1.4.1.3922.1.1.1.12 */ + CP_WIDEPOINT_MEDIUMHW_OID = 0x7aa099d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x12 */ + /* 1.3.6.1.4.1.3922.1.1.1.18 */ + CP_WIDEPOINT_PIVI_HW_OID = 0x7abe99d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x14 */ + /* 1.3.6.1.4.1.3922.1.1.1.20 */ + CP_WIDEPOINT_PIVI_CONTENT_OID = 0x7ab899d4, + /* 0x2b,0x06,0x01,0x04,0x01,0x9e,0x52,0x01,0x01,0x01,0x26 */ + /* 1.3.6.1.4.1.3922.1.1.1.38 */ + CP_WIDEPOINT_MEDDEVHW_OID = 0x7a8a99d4, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x01,0x02 */ + /* 1.2.36.1.334.1.2.1.2 */ + CP_ADO_MEDIUM_OID = 0x7cfcda99, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x01,0x03 */ + /* 1.2.36.1.334.1.2.1.3 */ + CP_ADO_HIGH_OID = 0x7cfcda98, + /* 0x2a,0x24,0x01,0x82,0x4e,0x01,0x02,0x02,0x02 */ + /* 1.2.36.1.334.1.2.2.2 */ + CP_ADO_RESOURCE_MEDIUM_OID = 0x7ffcda99, + /* 0x2b,0x06,0x01,0x04,0x01,0xb2,0x31,0x01,0x02,0x01,0x03,0x04 */ + /* 1.3.6.1.4.1.6449.1.2.1.3.4 */ + CP_COMODO_OID = 0x01ccb5d7, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x01 */ + /* 2.16.528.1.1003.1.2.5.1 */ + CP_NL_MOD_AUTH_OID = 0x0311ee1d, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x02 */ + /* 2.16.528.1.1003.1.2.5.2 */ + CP_NL_MOD_IRREFUT_OID = 0x0311ed1d, + /* 0x60,0x84,0x10,0x01,0x87,0x6b,0x01,0x02,0x05,0x03 */ + /* 2.16.528.1.1003.1.2.5.3 */ + CP_NL_MOD_CONFID_OID = 0x0311ec1d +#endif +}; + +enum SepHardwareName_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x08,0x04 */ + HW_NAME_OID = 79 /* 1.3.6.1.5.5.7.8.4 */ +#else + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x08,0x04 */ + HW_NAME_OID = 0x0109012e /* 1.3.6.1.5.5.7.8.4 */ +#endif +}; + +enum AuthInfo_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01 */ + AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x02 */ + AIA_CA_ISSUER_OID = 117, /* 1.3.6.1.5.5.7.48.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x05 */ + AIA_CA_REPO_OID = 120 /* 1.3.6.1.5.5.7.48.5 */ +#else + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01 */ + AIA_OCSP_OID = 0x0431012e, /* 1.3.6.1.5.5.7.48.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x02 */ + AIA_CA_ISSUER_OID = 0x0731012e, /* 1.3.6.1.5.5.7.48.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x05 */ + AIA_CA_REPO_OID = 0x0031012e /* 1.3.6.1.5.5.7.48.5 */ +#endif +}; + +enum ExtKeyUsage_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x55,0x1d,0x25,0x00 */ + EKU_ANY_OID = 151, /* 2.5.29.37.0 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x01 */ + EKU_SERVER_AUTH_OID = 71, /* 1.3.6.1.5.5.7.3.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x02 */ + EKU_CLIENT_AUTH_OID = 72, /* 1.3.6.1.5.5.7.3.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x03 */ + EKU_CODESIGNING_OID = 73, /* 1.3.6.1.5.5.7.3.3 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x04 */ + EKU_EMAILPROTECT_OID = 74, /* 1.3.6.1.5.5.7.3.4 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x08 */ + EKU_TIMESTAMP_OID = 78, /* 1.3.6.1.5.5.7.3.8 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x09 */ + EKU_OCSP_SIGN_OID = 79, /* 1.3.6.1.5.5.7.3.9 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x15 */ + EKU_SSH_CLIENT_AUTH_OID = 91, /* 1.3.6.1.5.5.7.3.21 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x14,0x02,0x02 */ + EKU_SSH_MSCL_OID = 264, /* 1.3.6.1.4.1.311.20.2.2 */ + /* 0x2b,0x06,0x01,0x05,0x02,0x03,0x04 */ + EKU_SSH_KP_CLIENT_AUTH_OID = 64 /* 1.3.6.1.5.2.3.4 */ +#else + /* 0x55,0x1d,0x25,0x00 */ + EKU_ANY_OID = 0x00da1daa, /* 2.5.29.37.0 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x01 */ + EKU_SERVER_AUTH_OID = 0x0402012e, /* 1.3.6.1.5.5.7.3.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x02 */ + EKU_CLIENT_AUTH_OID = 0x0702012e, /* 1.3.6.1.5.5.7.3.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x03 */ + EKU_CODESIGNING_OID = 0x0602012e, /* 1.3.6.1.5.5.7.3.3 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x04 */ + EKU_EMAILPROTECT_OID = 0x0102012e, /* 1.3.6.1.5.5.7.3.4 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x08 */ + EKU_TIMESTAMP_OID = 0x0d02012e, /* 1.3.6.1.5.5.7.3.8 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x09 */ + EKU_OCSP_SIGN_OID = 0x0c02012e, /* 1.3.6.1.5.5.7.3.9 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x03,0x15 */ + EKU_SSH_CLIENT_AUTH_OID = 0x1002012e, /* 1.3.6.1.5.5.7.3.21 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x14,0x02,0x02 */ + EKU_SSH_MSCL_OID = 0x103686d7, /* 1.3.6.1.4.1.311.20.2.2 */ + /* 0x2b,0x06,0x01,0x05,0x02,0x03,0x04 */ + EKU_SSH_KP_CLIENT_AUTH_OID = 0x7a050529 /* 1.3.6.1.5.2.3.4 */ +#endif +}; + +enum SubjDirAttr_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x01 */ + SDA_DOB_OID = 77, /* 1.3.6.1.5.5.7.9.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x02 */ + SDA_POB_OID = 78, /* 1.3.6.1.5.5.7.9.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x03 */ + SDA_GENDER_OID = 79, /* 1.3.6.1.5.5.7.9.3 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x04 */ + SDA_COC_OID = 80, /* 1.3.6.1.5.5.7.9.4 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x05 */ + SDA_COR_OID = 81 /* 1.3.6.1.5.5.7.9.5 */ +#else + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x01 */ + SDA_DOB_OID = 0x0408012e, /* 1.3.6.1.5.5.7.9.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x02 */ + SDA_POB_OID = 0x0708012e, /* 1.3.6.1.5.5.7.9.2 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x03 */ + SDA_GENDER_OID = 0x0608012e, /* 1.3.6.1.5.5.7.9.3 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x04 */ + SDA_COC_OID = 0x0108012e, /* 1.3.6.1.5.5.7.9.4 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x09,0x05 */ + SDA_COR_OID = 0x0008012e /* 1.3.6.1.5.5.7.9.5 */ +#endif +}; + +enum CompressAlg_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x03,0x08 */ + ZLIBc = 679 /* 1.2.840.113549.1.9.16.3.8 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x03,0x08 */ + ZLIBc = 0x70be8832 /* 1.2.840.113549.1.9.16.3.8 */ +#endif +}; + +enum CsrAttrType { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x02 */ + UNSTRUCTURED_NAME_OID = 654, /* 1.2.840.113549.1.9.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x03 */ + PKCS9_CONTENT_TYPE_OID = 655, /* 1.2.840.113549.1.9.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x07 */ + CHALLENGE_PASSWORD_OID = 659, /* 1.2.840.113549.1.9.7 */ + /* 0x55,0x04,0x05 */ + SERIAL_NUMBER_OID = 94, /* 2.5.4.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x0e */ + EXTENSION_REQUEST_OID = 666, /* 1.2.840.113549.1.9.14 */ + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x01 */ + USER_ID_OID = 865, /* 0.9.2342.19200300.100.1.1 */ + /* 0x55,0x04,0x2e */ + DNQUALIFIER_OID = 135, /* 2.5.4.46 */ + /* 0x55,0x04,0x2b */ + INITIALS_OID = 132, /* 2.5.4.43 */ + /* 0x55,0x04,0x04 */ + SURNAME_OID = 93, /* 2.5.4.4 */ + /* 0x55,0x04,0x29 */ + NAME_OID = 130, /* 2.5.4.41 */ + /* 0x55,0x04,0x2a */ + GIVEN_NAME_OID = 131 /* 2.5.4.42 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x02 */ + UNSTRUCTURED_NAME_OID = 0x70b67420, /* 1.2.840.113549.1.9.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x03 */ + PKCS9_CONTENT_TYPE_OID = 0x70b67421, /* 1.2.840.113549.1.9.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x07 */ + CHALLENGE_PASSWORD_OID = 0x70b67425, /* 1.2.840.113549.1.9.7 */ + /* 0x55,0x04,0x05 */ + SERIAL_NUMBER_OID = 0x7ffa04aa, /* 2.5.4.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x0e */ + EXTENSION_REQUEST_OID = 0x70b6742c, /* 1.2.840.113549.1.9.14 */ + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x01 */ + USER_ID_OID = 0x6d0a6164, /* 0.9.2342.19200300.100.1.1 */ + /* 0x55,0x04,0x2e */ + DNQUALIFIER_OID = 0x7fd104aa, /* 2.5.4.46 */ + /* 0x55,0x04,0x2b */ + INITIALS_OID = 0x7fd404aa, /* 2.5.4.43 */ + /* 0x55,0x04,0x04 */ + SURNAME_OID = 0x7ffb04aa, /* 2.5.4.4 */ + /* 0x55,0x04,0x29 */ + NAME_OID = 0x7fd604aa, /* 2.5.4.41 */ + /* 0x55,0x04,0x2a */ + GIVEN_NAME_OID = 0x7fd504aa /* 2.5.4.42 */ +#endif +}; + +enum Ocsp_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x01 */ + OCSP_BASIC_OID = 117, /* 1.3.6.1.5.5.7.48.1.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x02 */ + OCSP_NONCE_OID = 118 /* 1.3.6.1.5.5.7.48.1.2 */ +#else + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x01 */ + OCSP_BASIC_OID = 0x7bcefed0, /* 1.3.6.1.5.5.7.48.1.1 */ + /* 0x2b,0x06,0x01,0x05,0x05,0x07,0x30,0x01,0x02 */ + OCSP_NONCE_OID = 0x7bcefed3 /* 1.3.6.1.5.5.7.48.1.2 */ +#endif +}; + +enum Ecc_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2b,0x81,0x04,0x00,0x06 */ + ECC_SECP112R1_OID = 182, /* 1.3.132.0.6 */ + /* 0x2b,0x81,0x04,0x00,0x07 */ + ECC_SECP112R2_OID = 183, /* 1.3.132.0.7 */ + /* 0x2b,0x81,0x04,0x00,0x1c */ + ECC_SECP128R1_OID = 204, /* 1.3.132.0.28 */ + /* 0x2b,0x81,0x04,0x00,0x1d */ + ECC_SECP128R2_OID = 205, /* 1.3.132.0.29 */ + /* 0x2b,0x81,0x04,0x00,0x08 */ + ECC_SECP160R1_OID = 184, /* 1.3.132.0.8 */ + /* 0x2b,0x81,0x04,0x00,0x1e */ + ECC_SECP160R2_OID = 206, /* 1.3.132.0.30 */ + /* 0x2b,0x81,0x04,0x00,0x09 */ + ECC_SECP160K1_OID = 185, /* 1.3.132.0.9 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01 */ + ECC_BRAINPOOLP160R1_OID = 98, /* 1.3.36.3.3.2.8.1.1.1 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x01 */ + ECC_SECP192R1_OID = 520, /* 1.2.840.10045.3.1.1 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x02 */ + ECC_PRIME192V2_OID = 521, /* 1.2.840.10045.3.1.2 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x03 */ + ECC_PRIME192V3_OID = 522, /* 1.2.840.10045.3.1.3 */ + /* 0x2b,0x81,0x04,0x00,0x1f */ + ECC_SECP192K1_OID = 207, /* 1.3.132.0.31 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03 */ + ECC_BRAINPOOLP192R1_OID = 100, /* 1.3.36.3.3.2.8.1.1.3 */ + /* 0x2b,0x81,0x04,0x00,0x21 */ + ECC_SECP224R1_OID = 209, /* 1.3.132.0.33 */ + /* 0x2b,0x81,0x04,0x00,0x20 */ + ECC_SECP224K1_OID = 208, /* 1.3.132.0.32 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05 */ + ECC_BRAINPOOLP224R1_OID = 102, /* 1.3.36.3.3.2.8.1.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x04 */ + ECC_PRIME239V1_OID = 523, /* 1.2.840.10045.3.1.4 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x05 */ + ECC_PRIME239V2_OID = 524, /* 1.2.840.10045.3.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x06 */ + ECC_PRIME239V3_OID = 525, /* 1.2.840.10045.3.1.6 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07 */ + ECC_SECP256R1_OID = 526, /* 1.2.840.10045.3.1.7 */ + /* 0x2b,0x81,0x04,0x00,0x0a */ + ECC_SECP256K1_OID = 186, /* 1.3.132.0.10 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07 */ + ECC_BRAINPOOLP256R1_OID = 104, /* 1.3.36.3.3.2.8.1.1.7 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x82,0x2d */ + ECC_SM2P256V1_OID = 667, /* 1.2.156.10197.1.301 */ + /* 0x2b,0x65,0x6e */ + ECC_X25519_OID = 254, /* 1.3.101.110 */ + /* 0x2b,0x65,0x70 */ + ECC_ED25519_OID = 256, /* 1.3.101.112 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09 */ + ECC_BRAINPOOLP320R1_OID = 106, /* 1.3.36.3.3.2.8.1.1.9 */ + /* 0x2b,0x65,0x6f */ + ECC_X448_OID = 255, /* 1.3.101.111 */ + /* 0x2b,0x65,0x71 */ + ECC_ED448_OID = 257, /* 1.3.101.113 */ + /* 0x2b,0x81,0x04,0x00,0x22 */ + ECC_SECP384R1_OID = 210, /* 1.3.132.0.34 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0b */ + ECC_BRAINPOOLP384R1_OID = 108, /* 1.3.36.3.3.2.8.1.1.11 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0d */ + ECC_BRAINPOOLP512R1_OID = 110, /* 1.3.36.3.3.2.8.1.1.13 */ + /* 0x2b,0x81,0x04,0x00,0x23 */ + ECC_SECP521R1_OID = 211 /* 1.3.132.0.35 */ +#else + /* 0x2b,0x81,0x04,0x00,0x06 */ + ECC_SECP112R1_OID = 0x7f047e2d, /* 1.3.132.0.6 */ + /* 0x2b,0x81,0x04,0x00,0x07 */ + ECC_SECP112R2_OID = 0x7f047e2c, /* 1.3.132.0.7 */ + /* 0x2b,0x81,0x04,0x00,0x1c */ + ECC_SECP128R1_OID = 0x7f047e37, /* 1.3.132.0.28 */ + /* 0x2b,0x81,0x04,0x00,0x1d */ + ECC_SECP128R2_OID = 0x7f047e36, /* 1.3.132.0.29 */ + /* 0x2b,0x81,0x04,0x00,0x08 */ + ECC_SECP160R1_OID = 0x7f047e23, /* 1.3.132.0.8 */ + /* 0x2b,0x81,0x04,0x00,0x1e */ + ECC_SECP160R2_OID = 0x7f047e35, /* 1.3.132.0.30 */ + /* 0x2b,0x81,0x04,0x00,0x09 */ + ECC_SECP160K1_OID = 0x7f047e22, /* 1.3.132.0.9 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01 */ + ECC_BRAINPOOLP160R1_OID = 0x7dfdd3d7, /* 1.3.36.3.3.2.8.1.1.1 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x01 */ + ECC_SECP192R1_OID = 0x4f498517, /* 1.2.840.10045.3.1.1 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x02 */ + ECC_PRIME192V2_OID = 0x4c498517, /* 1.2.840.10045.3.1.2 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x03 */ + ECC_PRIME192V3_OID = 0x4d498517, /* 1.2.840.10045.3.1.3 */ + /* 0x2b,0x81,0x04,0x00,0x1f */ + ECC_SECP192K1_OID = 0x7f047e34, /* 1.3.132.0.31 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03 */ + ECC_BRAINPOOLP192R1_OID = 0x7dfdd3d5, /* 1.3.36.3.3.2.8.1.1.3 */ + /* 0x2b,0x81,0x04,0x00,0x21 */ + ECC_SECP224R1_OID = 0x7f047e0a, /* 1.3.132.0.33 */ + /* 0x2b,0x81,0x04,0x00,0x20 */ + ECC_SECP224K1_OID = 0x7f047e0b, /* 1.3.132.0.32 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05 */ + ECC_BRAINPOOLP224R1_OID = 0x7dfdd3d3, /* 1.3.36.3.3.2.8.1.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x04 */ + ECC_PRIME239V1_OID = 0x4a498517, /* 1.2.840.10045.3.1.4 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x05 */ + ECC_PRIME239V2_OID = 0x4b498517, /* 1.2.840.10045.3.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x06 */ + ECC_PRIME239V3_OID = 0x48498517, /* 1.2.840.10045.3.1.6 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07 */ + ECC_SECP256R1_OID = 0x49498517, /* 1.2.840.10045.3.1.7 */ + /* 0x2b,0x81,0x04,0x00,0x0a */ + ECC_SECP256K1_OID = 0x7f047e21, /* 1.3.132.0.10 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07 */ + ECC_BRAINPOOLP256R1_OID = 0x7dfdd3d1, /* 1.3.36.3.3.2.8.1.1.7 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x82,0x2d */ + ECC_SM2P256V1_OID = 0x629e807f, /* 1.2.156.10197.1.301 */ + /* 0x2b,0x65,0x6e */ + ECC_X25519_OID = 0x7f9165d4, /* 1.3.101.110 */ + /* 0x2b,0x65,0x70 */ + ECC_ED25519_OID = 0x7f8f65d4, /* 1.3.101.112 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09 */ + ECC_BRAINPOOLP320R1_OID = 0x7dfdd3df, /* 1.3.36.3.3.2.8.1.1.9 */ + /* 0x2b,0x65,0x6f */ + ECC_X448_OID = 0x7f9065d4, /* 1.3.101.111 */ + /* 0x2b,0x65,0x71 */ + ECC_ED448_OID = 0x7f8e65d4, /* 1.3.101.113 */ + /* 0x2b,0x81,0x04,0x00,0x22 */ + ECC_SECP384R1_OID = 0x7f047e09, /* 1.3.132.0.34 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0b */ + ECC_BRAINPOOLP384R1_OID = 0x7dfdd3dd, /* 1.3.36.3.3.2.8.1.1.11 */ + /* 0x2b,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0d */ + ECC_BRAINPOOLP512R1_OID = 0x7dfdd3db, /* 1.3.36.3.3.2.8.1.1.13 */ + /* 0x2b,0x81,0x04,0x00,0x23 */ + ECC_SECP521R1_OID = 0x7f047e08 /* 1.3.132.0.35 */ +#endif +}; + +enum Ctc_SigType { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0xce,0x38,0x04,0x03 */ + CTC_SHAwDSA = 517, /* 1.2.840.10040.4.3 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x02 */ + CTC_SHA256wDSA = 416, /* 2.16.840.1.101.3.4.3.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x02 */ + CTC_MD2wRSA = 646, /* 1.2.840.113549.1.1.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x04 */ + CTC_MD5wRSA = 648, /* 1.2.840.113549.1.1.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05 */ + CTC_SHAwRSA = 649, /* 1.2.840.113549.1.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x01 */ + CTC_SHAwECDSA = 520, /* 1.2.840.10045.4.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0e */ + CTC_SHA224wRSA = 658, /* 1.2.840.113549.1.1.14 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x01 */ + CTC_SHA224wECDSA = 523, /* 1.2.840.10045.4.3.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0b */ + CTC_SHA256wRSA = 655, /* 1.2.840.113549.1.1.11 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x02 */ + CTC_SHA256wECDSA = 524, /* 1.2.840.10045.4.3.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0c */ + CTC_SHA384wRSA = 656, /* 1.2.840.113549.1.1.12 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x03 */ + CTC_SHA384wECDSA = 525, /* 1.2.840.10045.4.3.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0d */ + CTC_SHA512wRSA = 657, /* 1.2.840.113549.1.1.13 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x04 */ + CTC_SHA512wECDSA = 526, /* 1.2.840.10045.4.3.4 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x09 */ + CTC_SHA3_224wECDSA = 423, /* 2.16.840.1.101.3.4.3.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0a */ + CTC_SHA3_256wECDSA = 424, /* 2.16.840.1.101.3.4.3.10 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0b */ + CTC_SHA3_384wECDSA = 425, /* 2.16.840.1.101.3.4.3.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0c */ + CTC_SHA3_512wECDSA = 426, /* 2.16.840.1.101.3.4.3.12 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0d */ + CTC_SHA3_224wRSA = 427, /* 2.16.840.1.101.3.4.3.13 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0e */ + CTC_SHA3_256wRSA = 428, /* 2.16.840.1.101.3.4.3.14 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0f */ + CTC_SHA3_384wRSA = 429, /* 2.16.840.1.101.3.4.3.15 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x10 */ + CTC_SHA3_512wRSA = 430, /* 2.16.840.1.101.3.4.3.16 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0a */ + CTC_RSASSAPSS = 654, /* 1.2.840.113549.1.1.10 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x83,0x75 */ + CTC_SM3wSM2 = 740, /* 1.2.156.10197.1.501 */ + /* 0x2b,0x65,0x70 */ + CTC_ED25519 = 256, /* 1.3.101.112 */ + /* 0x2b,0x65,0x71 */ + CTC_ED448 = 257, /* 1.3.101.113 */ + /* 0x2b,0xce,0x0f,0x03,0x06 */ + CTC_FALCON_LEVEL1 = 273, /* 1.3.9999.3.6 */ + /* 0x2b,0xce,0x0f,0x03,0x09 */ + CTC_FALCON_LEVEL5 = 276, /* 1.3.9999.3.9 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x04,0x04 */ + CTC_DILITHIUM_LEVEL2 = 218, /* 1.3.6.1.4.1.2.267.12.4.4 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x06,0x05 */ + CTC_DILITHIUM_LEVEL3 = 221, /* 1.3.6.1.4.1.2.267.12.6.5 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x08,0x07 */ + CTC_DILITHIUM_LEVEL5 = 225, /* 1.3.6.1.4.1.2.267.12.8.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x11 */ + CTC_ML_DSA_LEVEL2 = 431, /* 2.16.840.1.101.3.4.3.17 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x12 */ + CTC_ML_DSA_LEVEL3 = 432, /* 2.16.840.1.101.3.4.3.18 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x13 */ + CTC_ML_DSA_LEVEL5 = 433, /* 2.16.840.1.101.3.4.3.19 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x04 */ + CTC_SPHINCS_FAST_LEVEL1 = 281, /* 1.3.9999.6.7.4 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x03 */ + CTC_SPHINCS_FAST_LEVEL3 = 283, /* 1.3.9999.6.8.3 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x03 */ + CTC_SPHINCS_FAST_LEVEL5 = 282, /* 1.3.9999.6.9.3 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x0a */ + CTC_SPHINCS_SMALL_LEVEL1 = 287, /* 1.3.9999.6.7.10 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x07 */ + CTC_SPHINCS_SMALL_LEVEL3 = 285, /* 1.3.9999.6.8.7 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x07 */ + CTC_SPHINCS_SMALL_LEVEL5 = 286 /* 1.3.9999.6.9.7 */ +#else + /* 0x2a,0x86,0x48,0xce,0x38,0x04,0x03 */ + CTC_SHAwDSA = 0x314b8212, /* 1.2.840.10040.4.3 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x02 */ + CTC_SHA256wDSA = 0x7db37af8, /* 2.16.840.1.101.3.4.3.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x02 */ + CTC_MD2wRSA = 0x78b67420, /* 1.2.840.113549.1.1.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x04 */ + CTC_MD5wRSA = 0x78b67426, /* 1.2.840.113549.1.1.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05 */ + CTC_SHAwRSA = 0x78b67427, /* 1.2.840.113549.1.1.5 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x01 */ + CTC_SHAwECDSA = 0x31498217, /* 1.2.840.10045.4.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0e */ + CTC_SHA224wRSA = 0x78b6742c, /* 1.2.840.113549.1.1.14 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x01 */ + CTC_SHA224wECDSA = 0x4f4b8217, /* 1.2.840.10045.4.3.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0b */ + CTC_SHA256wRSA = 0x78b67429, /* 1.2.840.113549.1.1.11 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x02 */ + CTC_SHA256wECDSA = 0x4c4b8217, /* 1.2.840.10045.4.3.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0c */ + CTC_SHA384wRSA = 0x78b6742e, /* 1.2.840.113549.1.1.12 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x03 */ + CTC_SHA384wECDSA = 0x4d4b8217, /* 1.2.840.10045.4.3.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0d */ + CTC_SHA512wRSA = 0x78b6742f, /* 1.2.840.113549.1.1.13 */ + /* 0x2a,0x86,0x48,0xce,0x3d,0x04,0x03,0x04 */ + CTC_SHA512wECDSA = 0x4a4b8217, /* 1.2.840.10045.4.3.4 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x09 */ + CTC_SHA3_224wECDSA = 0x7db37af3, /* 2.16.840.1.101.3.4.3.9 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0a */ + CTC_SHA3_256wECDSA = 0x7db37af0, /* 2.16.840.1.101.3.4.3.10 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0b */ + CTC_SHA3_384wECDSA = 0x7db37af1, /* 2.16.840.1.101.3.4.3.11 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0c */ + CTC_SHA3_512wECDSA = 0x7db37af6, /* 2.16.840.1.101.3.4.3.12 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0d */ + CTC_SHA3_224wRSA = 0x7db37af7, /* 2.16.840.1.101.3.4.3.13 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0e */ + CTC_SHA3_256wRSA = 0x7db37af4, /* 2.16.840.1.101.3.4.3.14 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0f */ + CTC_SHA3_384wRSA = 0x7db37af5, /* 2.16.840.1.101.3.4.3.15 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x10 */ + CTC_SHA3_512wRSA = 0x7db37aea, /* 2.16.840.1.101.3.4.3.16 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0a */ + CTC_RSASSAPSS = 0x78b67428, /* 1.2.840.113549.1.1.10 */ + /* 0x2a,0x81,0x1c,0xcf,0x55,0x01,0x83,0x75 */ + CTC_SM3wSM2 = 0x3a9f807f, /* 1.2.156.10197.1.501 */ + /* 0x2b,0x65,0x70 */ + CTC_ED25519 = 0x7f8f65d4, /* 1.3.101.112 */ + /* 0x2b,0x65,0x71 */ + CTC_ED448 = 0x7f8e65d4, /* 1.3.101.113 */ + /* 0x2b,0xce,0x0f,0x03,0x06 */ + CTC_FALCON_LEVEL1 = 0x7c0f312d, /* 1.3.9999.3.6 */ + /* 0x2b,0xce,0x0f,0x03,0x09 */ + CTC_FALCON_LEVEL5 = 0x7c0f3122, /* 1.3.9999.3.9 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x04,0x04 */ + CTC_DILITHIUM_LEVEL2 = 0x707800d9, /* 1.3.6.1.4.1.2.267.12.4.4 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x06,0x05 */ + CTC_DILITHIUM_LEVEL3 = 0x707902d9, /* 1.3.6.1.4.1.2.267.12.6.5 */ + /* 0x2b,0x06,0x01,0x04,0x01,0x02,0x82,0x0b,0x0c,0x08,0x07 */ + CTC_DILITHIUM_LEVEL5 = 0x707b0cd9, /* 1.3.6.1.4.1.2.267.12.8.7 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x11 */ + CTC_ML_DSA_LEVEL2 = 0x7db37aeb, /* 2.16.840.1.101.3.4.3.17 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x12 */ + CTC_ML_DSA_LEVEL3 = 0x7db37ae8, /* 2.16.840.1.101.3.4.3.18 */ + /* 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x13 */ + CTC_ML_DSA_LEVEL5 = 0x7db37ae9, /* 2.16.840.1.101.3.4.3.19 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x04 */ + CTC_SPHINCS_FAST_LEVEL1 = 0x06f0ca2c, /* 1.3.9999.6.7.4 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x03 */ + CTC_SPHINCS_FAST_LEVEL3 = 0x06f0cd23, /* 1.3.9999.6.8.3 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x03 */ + CTC_SPHINCS_FAST_LEVEL5 = 0x06f0cd22, /* 1.3.9999.6.9.3 */ + /* 0x2b,0xce,0x0f,0x06,0x07,0x0a */ + CTC_SPHINCS_SMALL_LEVEL1 = 0x06f0c42c, /* 1.3.9999.6.7.10 */ + /* 0x2b,0xce,0x0f,0x06,0x08,0x07 */ + CTC_SPHINCS_SMALL_LEVEL3 = 0x06f0c923, /* 1.3.9999.6.8.7 */ + /* 0x2b,0xce,0x0f,0x06,0x09,0x07 */ + CTC_SPHINCS_SMALL_LEVEL5 = 0x06f0c922 /* 1.3.9999.6.9.7 */ +#endif +}; + +enum PKCS7_TYPES { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07 */ + PKCS7_MSG = 650, /* 1.2.840.113549.1.7 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x01 */ + DATA = 651, /* 1.2.840.113549.1.7.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x02 */ + SIGNED_DATA = 652, /* 1.2.840.113549.1.7.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x03 */ + ENVELOPED_DATA = 653, /* 1.2.840.113549.1.7.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x04 */ + SIGNED_AND_ENVELOPED_DATA = 654, /* 1.2.840.113549.1.7.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x05 */ + DIGESTED_DATA = 655, /* 1.2.840.113549.1.7.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x09 */ + COMPRESSED_DATA = 678, /* 1.2.840.113549.1.9.16.1.9 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x06 */ + ENCRYPTED_DATA = 656, /* 1.2.840.113549.1.7.6 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x10 */ + FIRMWARE_PKG_DATA = 685, /* 1.2.840.113549.1.9.16.1.16 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x17 */ + AUTH_ENVELOPED_DATA = 692, /* 1.2.840.113549.1.9.16.1.23 */ + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x02,0x4E,0x02 */ + ENCRYPTED_KEY_PACKAGE = 489 /* 2.16.840.1.101.2.1.2.78.2 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07 */ + PKCS7_MSG = 0x01498bdd, /* 1.2.840.113549.1.7 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x01 */ + DATA = 0x7eb67423, /* 1.2.840.113549.1.7.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x02 */ + SIGNED_DATA = 0x7eb67420, /* 1.2.840.113549.1.7.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x03 */ + ENVELOPED_DATA = 0x7eb67421, /* 1.2.840.113549.1.7.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x04 */ + SIGNED_AND_ENVELOPED_DATA = 0x7eb67426, /* 1.2.840.113549.1.7.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x05 */ + DIGESTED_DATA = 0x7eb67427, /* 1.2.840.113549.1.7.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x09 */ + COMPRESSED_DATA = 0x70bf8a32, /* 1.2.840.113549.1.9.16.1.9 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x06 */ + ENCRYPTED_DATA = 0x7eb67424, /* 1.2.840.113549.1.7.6 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x10 */ + FIRMWARE_PKG_DATA = 0x70a68a32, /* 1.2.840.113549.1.9.16.1.16 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x10,0x01,0x17 */ + AUTH_ENVELOPED_DATA = 0x70a18a32, /* 1.2.840.113549.1.9.16.1.23 */ + /* 0x60,0x86,0x48,0x01,0x65,0x02,0x01,0x02,0x4E,0x02 */ + ENCRYPTED_KEY_PACKAGE = 0x034986B4 /* 2.16.840.1.101.2.1.2.78.2 */ +#endif +}; + +enum PKCS12_TYPES { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x01 */ + WC_PKCS12_KeyBag = 667, /* 1.2.840.113549.1.12.10.1.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x02 */ + WC_PKCS12_ShroudedKeyBag = 668, /* 1.2.840.113549.1.12.10.1.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x03 */ + WC_PKCS12_CertBag = 669, /* 1.2.840.113549.1.12.10.1.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x16,0x01 */ + WC_PKCS12_CertBag_Type1 = 675, /* 1.2.840.113549.1.9.22.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x04 */ + WC_PKCS12_CrlBag = 670, /* 1.2.840.113549.1.12.10.1.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x05 */ + WC_PKCS12_SecretBag = 671, /* 1.2.840.113549.1.12.10.1.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x06 */ + WC_PKCS12_SafeContentsBag = 672, /* 1.2.840.113549.1.12.10.1.6 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x01 */ + WC_PKCS12_DATA = 651, /* 1.2.840.113549.1.7.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x06 */ + WC_PKCS12_ENCRYPTED_DATA = 656 /* 1.2.840.113549.1.7.6 */ +#else + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x01 */ + WC_PKCS12_KeyBag = 0x75b78a28, /* 1.2.840.113549.1.12.10.1.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x02 */ + WC_PKCS12_ShroudedKeyBag = 0x75b48a28, /* 1.2.840.113549.1.12.10.1.2 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x03 */ + WC_PKCS12_CertBag = 0x75b58a28, /* 1.2.840.113549.1.12.10.1.3 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x16,0x01 */ + WC_PKCS12_CertBag_Type1 = 0x0f498a34, /* 1.2.840.113549.1.9.22.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x04 */ + WC_PKCS12_CrlBag = 0x75b28a28, /* 1.2.840.113549.1.12.10.1.4 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x05 */ + WC_PKCS12_SecretBag = 0x75b38a28, /* 1.2.840.113549.1.12.10.1.5 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x0c,0x0a,0x01,0x06 */ + WC_PKCS12_SafeContentsBag = 0x75b08a28, /* 1.2.840.113549.1.12.10.1.6 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x01 */ + WC_PKCS12_DATA = 0x7eb67423, /* 1.2.840.113549.1.7.1 */ + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x07,0x06 */ + WC_PKCS12_ENCRYPTED_DATA = 0x7eb67424 /* 1.2.840.113549.1.7.6 */ +#endif +}; + +enum CertName_Sum { +#ifdef WOLFSSL_OLD_OID_SUM + /* 0x55,0x04,0x03 */ + /* 2.5.4.3 */ + WC_NAME_COMMON_NAME_OID = 92, + /* 0x55,0x04,0x04 */ + /* 2.5.4.4 */ + WC_NAME_SURNAME_OID = 93, + /* 0x55,0x04,0x05 */ + /* 2.5.4.5 */ + WC_NAME_SERIAL_NUMBER_OID = 94, + /* 0x55,0x04,0x06 */ + /* 2.5.4.6 */ + WC_NAME_COUNTRY_NAME_OID = 95, + /* 0x55,0x04,0x07 */ + /* 2.5.4.7 */ + WC_NAME_LOCALITY_NAME_OID = 96, + /* 0x55,0x04,0x08 */ + /* 2.5.4.8 */ + WC_NAME_STATE_NAME_OID = 97, + /* 0x55,0x04,0x09 */ + /* 2.5.4.9 */ + WC_NAME_STREET_ADDRESS_OID = 98, + /* 0x55,0x04,0x0a */ + /* 2.5.4.10 */ + WC_NAME_ORGANIZATION_NAME_OID = 99, + /* 0x55,0x04,0x0b */ + /* 2.5.4.11 */ + WC_NAME_ORGANIZATION_UNIT_NAME_OID = 100, + /* 0x55,0x04,0x09,0x0c */ + /* 2.5.4.9.12 */ + WC_NAME_TITLE_OID = 110, + /* 0x55,0x04,0x0d */ + /* 2.5.4.13 */ + WC_NAME_DESCRIPTION_OID = 102, + /* 0x55,0x04,0x0f */ + /* 2.5.4.15 */ + WC_NAME_BUSINESS_CATEGORY_OID = 104, + /* 0x55,0x04,0x11 */ + /* 2.5.4.17 */ + WC_NAME_POSTAL_CODE_OID = 106, + /* 0x55,0x04,0x29 */ + /* 2.5.4.41 */ + WC_NAME_NAME_OID = 130, + /* 0x55,0x04,0x2a */ + /* 2.5.4.42 */ + WC_NAME_GIVEN_NAME_OID = 131, + /* 0x55,0x04,0x2b */ + /* 2.5.4.43 */ + WC_NAME_INITIALIS_OID = 132, + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x01 */ + /* 1.2.840.113549.1.9.1 */ + WC_NAME_EMAIL_ADDRESS_OID = 653, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x01 */ + /* 0.9.2342.19200300.100.1.1 */ + WC_NAME_USER_ID_OID = 865, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x03 */ + /* 0.9.2342.19200300.100.1.3 */ + WC_NAME_RFC822_MAILBOX_OID = 867, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x05 */ + /* 0.9.2342.19200300.100.1.5 */ + WC_NAME_FAVOURITE_DRINK_OID = 869, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x19 */ + /* 0.9.2342.19200300.100.1.25 */ + WC_NAME_DOMAIN_COMPONENT_OID = 889, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x3c,0x02,0x01,0x02 */ + /* 1.3.6.1.4.1.311.60.2.1.2 */ + WC_NAME_JURIS_STATE_PROV_OID = 305, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x3c,0x02,0x01,0x03 */ + /* 1.3.6.1.4.1.311.60.2.1.3 */ + WC_NAME_JURIS_COUNTRY_OID = 306 +#else + /* 0x55,0x04,0x03 */ + /* 2.5.4.3 */ + WC_NAME_COMMON_NAME_OID = 0x7ffc04aa, + /* 0x55,0x04,0x04 */ + /* 2.5.4.4 */ + WC_NAME_SURNAME_OID = 0x7ffb04aa, + /* 0x55,0x04,0x05 */ + /* 2.5.4.5 */ + WC_NAME_SERIAL_NUMBER_OID = 0x7ffa04aa, + /* 0x55,0x04,0x06 */ + /* 2.5.4.6 */ + WC_NAME_COUNTRY_NAME_OID = 0x7ff904aa, + /* 0x55,0x04,0x07 */ + /* 2.5.4.7 */ + WC_NAME_LOCALITY_NAME_OID = 0x7ff804aa, + /* 0x55,0x04,0x08 */ + /* 2.5.4.8 */ + WC_NAME_STATE_NAME_OID = 0x7ff704aa, + /* 0x55,0x04,0x09 */ + /* 2.5.4.9 */ + WC_NAME_STREET_ADDRESS_OID = 0x7ff604aa, + /* 0x55,0x04,0x0a */ + /* 2.5.4.10 */ + WC_NAME_ORGANIZATION_NAME_OID = 0x7ff504aa, + /* 0x55,0x04,0x0b */ + /* 2.5.4.11 */ + WC_NAME_ORGANIZATION_UNIT_NAME_OID = 0x7ff404aa, + /* 0x55,0x04,0x09,0x0c */ + /* 2.5.4.9.12 */ + WC_NAME_TITLE_OID = 0x0cf604aa, + /* 0x55,0x04,0x0d */ + /* 2.5.4.13 */ + WC_NAME_DESCRIPTION_OID = 0x7ff204aa, + /* 0x55,0x04,0x0f */ + /* 2.5.4.15 */ + WC_NAME_BUSINESS_CATEGORY_OID = 0x7ff004aa, + /* 0x55,0x04,0x11 */ + /* 2.5.4.17 */ + WC_NAME_POSTAL_CODE_OID = 0x7fee04aa, + /* 0x55,0x04,0x29 */ + /* 2.5.4.41 */ + WC_NAME_NAME_OID = 0x7fd604aa, + /* 0x55,0x04,0x2a */ + /* 2.5.4.42 */ + WC_NAME_GIVEN_NAME_OID = 0x7fd504aa, + /* 0x55,0x04,0x2b */ + /* 2.5.4.43 */ + WC_NAME_INITIALIS_OID = 0x7fd404aa, + /* 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x09,0x01 */ + /* 1.2.840.113549.1.9.1 */ + WC_NAME_EMAIL_ADDRESS_OID = 0x70b67423, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x01 */ + /* 0.9.2342.19200300.100.1.1 */ + WC_NAME_USER_ID_OID = 0x6d0a6164, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x03 */ + /* 0.9.2342.19200300.100.1.3 */ + WC_NAME_RFC822_MAILBOX_OID = 0x6d0a6364, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x05 */ + /* 0.9.2342.19200300.100.1.5 */ + WC_NAME_FAVOURITE_DRINK_OID = 0x6d0a6564, + /* 0x09,0x92,0x26,0x89,0x93,0xf2,0x2c,0x64,0x01,0x19 */ + /* 0.9.2342.19200300.100.1.25 */ + WC_NAME_DOMAIN_COMPONENT_OID = 0x6d0a7964, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x3c,0x02,0x01,0x02 */ + /* 1.3.6.1.4.1.311.60.2.1.2 */ + WC_NAME_JURIS_STATE_PROV_OID = 0x47cb85d7, + /* 0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x3c,0x02,0x01,0x03 */ + /* 1.3.6.1.4.1.311.60.2.1.3 */ + WC_NAME_JURIS_COUNTRY_OID = 0x47ca85d7 +#endif +}; + +#endif /* !WOLF_CRYPT_OID_SUM_H */ diff --git a/src/wolfssl/wolfcrypt/pkcs11.h b/src/wolfssl/wolfcrypt/pkcs11.h index 36cfd9c..4d36e36 100644 --- a/src/wolfssl/wolfcrypt/pkcs11.h +++ b/src/wolfssl/wolfcrypt/pkcs11.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/pkcs12.h b/src/wolfssl/wolfcrypt/pkcs12.h index 6dc6e9d..ce22c40 100644 --- a/src/wolfssl/wolfcrypt/pkcs12.h +++ b/src/wolfssl/wolfcrypt/pkcs12.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/pkcs7.h b/src/wolfssl/wolfcrypt/pkcs7.h index efce67c..011fec9 100644 --- a/src/wolfssl/wolfcrypt/pkcs7.h +++ b/src/wolfssl/wolfcrypt/pkcs7.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -81,22 +81,6 @@ #define WOLFSSL_SIGNING_TIME_ATTRIBUTE 0x4 #define WOLFSSL_MESSAGE_DIGEST_ATTRIBUTE 0x8 -/* PKCS#7 content types, ref RFC 2315 (Section 14) */ -enum PKCS7_TYPES { - PKCS7_MSG = 650, /* 1.2.840.113549.1.7 */ - DATA = 651, /* 1.2.840.113549.1.7.1 */ - SIGNED_DATA = 652, /* 1.2.840.113549.1.7.2 */ - ENVELOPED_DATA = 653, /* 1.2.840.113549.1.7.3 */ - SIGNED_AND_ENVELOPED_DATA = 654, /* 1.2.840.113549.1.7.4 */ - DIGESTED_DATA = 655, /* 1.2.840.113549.1.7.5 */ - ENCRYPTED_DATA = 656, /* 1.2.840.113549.1.7.6 */ -#if defined(HAVE_LIBZ) && !defined(NO_PKCS7_COMPRESSED_DATA) - COMPRESSED_DATA = 678, /* 1.2.840.113549.1.9.16.1.9, RFC 3274 */ -#endif - FIRMWARE_PKG_DATA = 685, /* 1.2.840.113549.1.9.16.1.16, RFC 4108 */ - AUTH_ENVELOPED_DATA = 692 /* 1.2.840.113549.1.9.16.1.23, RFC 5083 */ -}; - enum PKCS7_STATE { WC_PKCS7_START = 0, @@ -546,6 +530,10 @@ WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCb(wc_PKCS7* pkcs7, WOLFSSL_API int wc_PKCS7_SetDecodeEncryptedCtx(wc_PKCS7* pkcs7, void* ctx); #endif /* NO_PKCS7_ENCRYPTED_DATA */ +/* CMS/PKCS#7 EncryptedKeyPackage */ +WOLFSSL_API int wc_PKCS7_DecodeEncryptedKeyPackage(wc_PKCS7 * pkcs7, + byte * pkiMsg, word32 pkiMsgSz, byte * output, word32 outputSz); + /* stream and certs */ WOLFSSL_LOCAL int wc_PKCS7_WriteOut(wc_PKCS7* pkcs7, byte* output, const byte* input, word32 inputSz); diff --git a/src/wolfssl/wolfcrypt/poly1305.h b/src/wolfssl/wolfcrypt/poly1305.h index c6adb0e..c27fd44 100644 --- a/src/wolfssl/wolfcrypt/poly1305.h +++ b/src/wolfssl/wolfcrypt/poly1305.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h index 4ae38a9..829e9b1 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp-sdk-lib.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h index ac48d97..15c27bd 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp32-crypt.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h index cc8f48f..ee746a1 100644 --- a/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h +++ b/src/wolfssl/wolfcrypt/port/Espressif/esp_crt_bundle.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -90,6 +90,16 @@ extern "C" { #define WOLFSSL_X509_VERIFY_CALLBACK (void *, WOLFSSL_X509 *, int, uint32_t *) #include +#if defined(CONFIG_WOLFSSL_DEBUG_CERT_BUNDLE) || \ + defined( WOLFSSL_DEBUG_CERT_BUNDLE) + /* Default WOLFSSL_MAX_ERROR_SZ assigned in settings.h or user_settings.h */ + extern char last_esp_crt_bundle_error[WOLFSSL_MAX_ERROR_SZ]; + #define SHOW_WOLFSSL_BUNDLE_ERROR(THIS_ERR) \ + { \ + wc_ErrorString(THIS_ERR, last_esp_crt_bundle_error); \ + ESP_LOGE(TAG,"%s", last_esp_crt_bundle_error); \ + } +#endif typedef struct wolfssl_ssl_config wolfssl_ssl_config; struct wolfssl_ssl_config diff --git a/src/wolfssl/wolfcrypt/port/atmel/atmel.h b/src/wolfssl/wolfcrypt/port/atmel/atmel.h index d5c9458..515c5f4 100644 --- a/src/wolfssl/wolfcrypt/port/atmel/atmel.h +++ b/src/wolfssl/wolfcrypt/port/atmel/atmel.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/pwdbased.h b/src/wolfssl/wolfcrypt/pwdbased.h index 9013401..efce730 100644 --- a/src/wolfssl/wolfcrypt/pwdbased.h +++ b/src/wolfssl/wolfcrypt/pwdbased.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/random.h b/src/wolfssl/wolfcrypt/random.h index 3b4533e..b7759ae 100644 --- a/src/wolfssl/wolfcrypt/random.h +++ b/src/wolfssl/wolfcrypt/random.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -133,6 +133,12 @@ #else typedef unsigned long ProviderHandle; #endif + + #ifdef WIN_REUSE_CRYPT_HANDLE + /* called from wolfCrypt_Init() and wolfCrypt_Cleanup() */ + WOLFSSL_LOCAL int wc_WinCryptHandleInit(void); + WOLFSSL_LOCAL void wc_WinCryptHandleCleanup(void); + #endif #endif #ifndef WC_RNG_TYPE_DEFINED /* guard on redeclaration */ @@ -158,7 +164,11 @@ struct OS_Seed { #ifdef HAVE_HASHDRBG struct DRBG_internal { + #ifdef WORD64_AVAILABLE + word64 reseedCtr; + #else word32 reseedCtr; + #endif byte V[DRBG_SEED_LEN]; byte C[DRBG_SEED_LEN]; void* heap; @@ -183,6 +193,9 @@ struct WC_RNG { #endif byte status; #endif +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) + pid_t pid; +#endif #ifdef WOLFSSL_ASYNC_CRYPT WC_ASYNC_DEV asyncDev; #endif diff --git a/src/wolfssl/wolfcrypt/rc2.h b/src/wolfssl/wolfcrypt/rc2.h index 22eb581..ab5cdbb 100644 --- a/src/wolfssl/wolfcrypt/rc2.h +++ b/src/wolfssl/wolfcrypt/rc2.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/ripemd.h b/src/wolfssl/wolfcrypt/ripemd.h index 54ede0d..bb2db34 100644 --- a/src/wolfssl/wolfcrypt/ripemd.h +++ b/src/wolfssl/wolfcrypt/ripemd.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/rsa.h b/src/wolfssl/wolfcrypt/rsa.h index a01e18d..ff959d6 100644 --- a/src/wolfssl/wolfcrypt/rsa.h +++ b/src/wolfssl/wolfcrypt/rsa.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sakke.h b/src/wolfssl/wolfcrypt/sakke.h index 3ba7968..37db5a1 100644 --- a/src/wolfssl/wolfcrypt/sakke.h +++ b/src/wolfssl/wolfcrypt/sakke.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/selftest.h b/src/wolfssl/wolfcrypt/selftest.h index 08b8884..11758e3 100644 --- a/src/wolfssl/wolfcrypt/selftest.h +++ b/src/wolfssl/wolfcrypt/selftest.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/settings.h b/src/wolfssl/wolfcrypt/settings.h index 9008976..fc08d66 100644 --- a/src/wolfssl/wolfcrypt/settings.h +++ b/src/wolfssl/wolfcrypt/settings.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -455,6 +455,10 @@ #endif #endif +/* Important build-time configuration messages may be saved. + * Enable DEBUG_WOLFSSL and see wolfSSL_Init() for display. */ +#define LIBWOLFSSL_CMAKE_OUTPUT "" + /* --------------------------------------------------------------------------- * Dual Algorithm Certificate Required Features. * --------------------------------------------------------------------------- @@ -1270,11 +1274,11 @@ #define TIME_OVERRIDES #ifndef XTIME #error "Must define XTIME externally see porting guide" - #error "https://www.wolfssl.com/docs/porting-guide/" + /* https://www.wolfssl.com/docs/porting-guide/ */ #endif #ifndef XGMTIME #error "Must define XGMTIME externally see porting guide" - #error "https://www.wolfssl.com/docs/porting-guide/" + /* https://www.wolfssl.com/docs/porting-guide/ */ #endif #endif @@ -1897,21 +1901,6 @@ extern void uITRON4_free(void *p) ; #define TFM_TIMING_RESISTANT #define ECC_TIMING_RESISTANT - #undef HAVE_ECC - #ifndef WOLFCRYPT_FIPS_RAND - #define HAVE_ECC - #endif - #ifndef NO_AES - #undef HAVE_AESCCM - #define HAVE_AESCCM - #undef HAVE_AESGCM - #define HAVE_AESGCM - #undef WOLFSSL_AES_COUNTER - #define WOLFSSL_AES_COUNTER - #undef WOLFSSL_AES_DIRECT - #define WOLFSSL_AES_DIRECT - #endif - #ifdef FREESCALE_KSDK_1_3 #include "fsl_device_registers.h" #elif !defined(FREESCALE_MQX) @@ -2106,7 +2095,8 @@ extern void uITRON4_free(void *p) ; defined(WOLFSSL_STM32G0) || defined(WOLFSSL_STM32U5) || \ defined(WOLFSSL_STM32H5) || defined(WOLFSSL_STM32WL) || \ defined(WOLFSSL_STM32G4) || defined(WOLFSSL_STM32MP13) || \ - defined(WOLFSSL_STM32H7S) || defined(WOLFSSL_STM32WBA) + defined(WOLFSSL_STM32H7S) || defined(WOLFSSL_STM32WBA) || \ + defined(WOLFSSL_STM32N6) #define SIZEOF_LONG_LONG 8 #ifndef CHAR_BIT @@ -2170,6 +2160,8 @@ extern void uITRON4_free(void *p) ; #include "stm32u5xx_hal.h" #elif defined(WOLFSSL_STM32H5) #include "stm32h5xx_hal.h" + #elif defined(WOLFSSL_STM32N6) + #include "stm32n6xx_hal.h" #elif defined(WOLFSSL_STM32MP13) /* HAL headers error on our ASM files */ #ifndef __ASSEMBLER__ @@ -2795,14 +2787,15 @@ extern void uITRON4_free(void *p) ; #endif #if defined(__mips) || defined(__mips64) || \ - defined(WOLFSSL_SP_MIPS64) || defined(WOLFSSL_SP_MIPS) - #undef WOLFSSL_SP_INT_DIGIT_ALIGN - #define WOLFSSL_SP_INT_DIGIT_ALIGN -#endif -#if defined(__sparc) + defined(WOLFSSL_SP_MIPS64) || defined(WOLFSSL_SP_MIPS) || \ + defined(__sparc) || defined(__arm__) || defined(__aarch64__) + /* This setting currently only affects big endian targets, currently + * only in sp_read_unsigned_bin(). + */ #undef WOLFSSL_SP_INT_DIGIT_ALIGN #define WOLFSSL_SP_INT_DIGIT_ALIGN #endif + #if defined(__APPLE__) || defined(WOLF_C89) #define WOLFSSL_SP_NO_DYN_STACK #endif @@ -2896,7 +2889,7 @@ extern void uITRON4_free(void *p) ; /* Determine when mp_read_radix with a radix of 10 is required. */ #if (defined(WOLFSSL_SP_MATH_ALL) && !defined(NO_RSA) && \ !defined(WOLFSSL_RSA_VERIFY_ONLY)) || defined(HAVE_ECC) || \ - !defined(NO_DSA) || defined(OPENSSL_EXTRA) + !defined(NO_DSA) || defined(OPENSSL_EXTRA) || defined(WOLFSSL_PUBLIC_MP) #define WOLFSSL_SP_READ_RADIX_16 #endif @@ -2909,7 +2902,7 @@ extern void uITRON4_free(void *p) ; /* Determine when mp_invmod is required. */ #if defined(HAVE_ECC) || !defined(NO_DSA) || defined(OPENSSL_EXTRA) || \ (!defined(NO_RSA) && !defined(WOLFSSL_RSA_VERIFY_ONLY) && \ - !defined(WOLFSSL_RSA_PUBLIC_ONLY)) + !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || defined(OPENSSL_EXTRA) #define WOLFSSL_SP_INVMOD #endif @@ -3119,6 +3112,29 @@ extern void uITRON4_free(void *p) ; #endif #endif /* HAVE_ED448 */ + +/* RFC 5958 (Asymmetric Key Packages) */ +#if !defined(WC_ENABLE_ASYM_KEY_EXPORT) && \ + ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)) || \ + (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)) || \ + (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)) || \ + (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)) || \ + defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || \ + defined(HAVE_SPHINCS) || defined(HAVE_LIBOQS)) + #define WC_ENABLE_ASYM_KEY_EXPORT +#endif + +#if !defined(WC_ENABLE_ASYM_KEY_IMPORT) && \ + ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) || \ + (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) || \ + (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) || \ + (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) || \ + defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || \ + defined(HAVE_SPHINCS) || defined(HAVE_LIBOQS)) + #define WC_ENABLE_ASYM_KEY_IMPORT +#endif + + /* FIPS does not support CFB1 or CFB8 */ #if !defined(WOLFSSL_NO_AES_CFB_1_8) && \ (defined(HAVE_SELFTEST) || \ @@ -3584,6 +3600,13 @@ extern void uITRON4_free(void *p) ; #endif #endif +#ifdef WOLFSSL_PYTHON + /* Need to use old OID sum algorithm until OSP patches, in particular to + * tests, for all versions reflect the new OID sum value. */ + #undef WOLFSSL_OLD_OID_SUM + #define WOLFSSL_OLD_OID_SUM +#endif + /* Linux Kernel Module */ #ifdef WOLFSSL_LINUXKM @@ -3640,6 +3663,9 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_HAVE_MAX #undef WOLFSSL_HAVE_ASSERT_H #define WOLFSSL_NO_ASSERT_H + #ifndef WOLFSSL_NO_GETPID + #define WOLFSSL_NO_GETPID + #endif /* WOLFSSL_NO_GETPID */ #ifndef SIZEOF_LONG #define SIZEOF_LONG 8 #endif @@ -3653,8 +3679,13 @@ extern void uITRON4_free(void *p) ; #ifndef WOLFSSL_SP_DIV_WORD_HALF #define WOLFSSL_SP_DIV_WORD_HALF #endif - #ifdef __PIE__ + + #ifdef HAVE_LINUXKM_PIE_SUPPORT #define WC_NO_INTERNAL_FUNCTION_POINTERS + #define WOLFSSL_ECC_CURVE_STATIC + #define WOLFSSL_NAMES_STATIC + #define WOLFSSL_NO_PUBLIC_FFDHE + #undef HAVE_PUBLIC_FFDHE #endif #ifndef NO_OLD_WC_NAMES @@ -3677,7 +3708,7 @@ extern void uITRON4_free(void *p) ; #if defined(LINUXKM_LKCAPI_REGISTER) && !defined(WOLFSSL_ASN_INT_LEAD_0_ANY) /* kernel 5.10 crypto manager tests key(s) that fail unless leading - * bytes are tolerated in GetASN_Integer(). + * zero bytes are tolerated in GetASN_Integer(). */ #define WOLFSSL_ASN_INT_LEAD_0_ANY #endif @@ -3690,6 +3721,14 @@ extern void uITRON4_free(void *p) ; #define WC_SANITIZE_ENABLE() kasan_enable_current() #endif #endif + + #if !defined(WC_RESEED_INTERVAL) && defined(LINUXKM_LKCAPI_REGISTER) + /* If installing handlers, use the maximum reseed interval allowed by + * NIST SP 800-90A Rev. 1, to avoid unnecessary delays in DRBG + * generation. + */ + #define WC_RESEED_INTERVAL (((word64)1UL)<<48UL) + #endif #endif @@ -3793,6 +3832,14 @@ extern void uITRON4_free(void *p) ; #define WOLFSSL_ALERT_COUNT_MAX 5 #endif +/* Enable blinding by default for C-only, non-small curve25519 implementation */ +#if defined(HAVE_CURVE25519) && !defined(CURVE25519_SMALL) && \ + !defined(FREESCALE_LTC_ECC) && !defined(WOLFSSL_ARMASM) && \ + (!defined(USE_INTEL_SPEEDUP) || defined(NO_CURVED25519_X64)) && \ + !defined(WOLFSSL_CURVE25519_BLINDING) && !defined(NO_CURVE25519_BLINDING) + #define WOLFSSL_CURVE25519_BLINDING +#endif + /* warning for not using harden build options (default with ./configure) */ /* do not warn if big integer support is disabled */ #if !defined(WC_NO_HARDEN) && !defined(NO_BIG_INT) @@ -3867,7 +3914,7 @@ extern void uITRON4_free(void *p) ; /* Parts of the openssl compatibility layer require peer certs */ #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \ defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \ - defined(HAVE_LIGHTY)) && !defined(NO_CERTS) + defined(HAVE_LIGHTY)) && !defined(NO_CERTS) && !defined(NO_KEEP_PEER_CERT) #undef KEEP_PEER_CERT #define KEEP_PEER_CERT #endif @@ -3940,12 +3987,6 @@ extern void uITRON4_free(void *p) ; #undef HAVE_XCHACHA #endif -#if !defined(WOLFSSL_SHA384) && !defined(WOLFSSL_SHA512) && defined(NO_AES) && \ - !defined(WOLFSSL_SHA3) - #undef WOLFSSL_NO_WORD64_OPS - #define WOLFSSL_NO_WORD64_OPS -#endif - #if !defined(WOLFCRYPT_ONLY) && \ (!defined(WOLFSSL_NO_TLS12) || defined(HAVE_KEYING_MATERIAL)) #undef WOLFSSL_HAVE_PRF @@ -4038,7 +4079,6 @@ extern void uITRON4_free(void *p) ; #if defined(__IAR_SYSTEMS_ICC__) && defined(__ROPI__) #define WOLFSSL_ECC_CURVE_STATIC #define WOLFSSL_NAMES_STATIC - #define WOLFSSL_NO_CONSTCHARCONST #endif /* FIPS v1 does not support TLS v1.3 (requires RSA PSS and HKDF) */ @@ -4089,6 +4129,32 @@ extern void uITRON4_free(void *p) ; #undef WOLFSSL_DH_EXTRA #endif +/* FIPS 140-3 does not have this definition in wolfCrypt dh.h, but OpenSSL dh.h depends on it. + * Define it here as well if needed, as we want to avoid modifying dh.h in FIPS. */ +#ifndef DH_MAX_SIZE + #ifdef USE_FAST_MATH + /* FP implementation support numbers up to FP_MAX_BITS / 2 bits. */ + #define DH_MAX_SIZE (FP_MAX_BITS / 2) + #if defined(WOLFSSL_MYSQL_COMPATIBLE) && DH_MAX_SIZE < 8192 + #error "MySQL needs FP_MAX_BITS at least at 16384" + #endif + #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH) + /* SP implementation supports numbers of SP_INT_BITS bits. */ + #define DH_MAX_SIZE (((SP_INT_BITS + 7) / 8) * 8) + #if defined(WOLFSSL_MYSQL_COMPATIBLE) && DH_MAX_SIZE < 8192 + #error "MySQL needs SP_INT_BITS at least at 8192" + #endif + #else + #ifdef WOLFSSL_MYSQL_COMPATIBLE + /* Integer maths is dynamic but we only go up to 8192 bits. */ + #define DH_MAX_SIZE 8192 + #else + /* Integer maths is dynamic but we only go up to 4096 bits. */ + #define DH_MAX_SIZE 4096 + #endif + #endif +#endif + /* wc_Sha512.devId isn't available before FIPS 5.1 */ #if defined(HAVE_FIPS) && FIPS_VERSION_LT(5,1) #define NO_SHA2_CRYPTO_CB @@ -4186,6 +4252,12 @@ extern void uITRON4_free(void *p) ; #error Please do not define HAVE_PQC yourself. #endif +/* If no malloc then make sure the valid Dilithium settings are used */ +#if defined(HAVE_DILITHIUM) && defined(WOLFSSL_NO_MALLOC) + #undef WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC + #define WOLFSSL_DILITHIUM_VERIFY_NO_MALLOC +#endif + #if defined(HAVE_PQC) && defined(WOLFSSL_DTLS13) && \ !defined(WOLFSSL_DTLS_CH_FRAG) #warning "Using DTLS 1.3 + pqc without WOLFSSL_DTLS_CH_FRAG will probably" \ @@ -4339,14 +4411,17 @@ extern void uITRON4_free(void *p) ; #ifdef WOLFSSL_HARDEN_TLS #if defined(HAVE_TRUNCATED_HMAC) && !defined(WOLFSSL_HARDEN_TLS_ALLOW_TRUNCATED_HMAC) - #error "Truncated HMAC Extension not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.6" + #error "Truncated HMAC Extension not allowed" + /* https://www.rfc-editor.org/rfc/rfc9325#section-4.6 */ #endif #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_HARDEN_TLS_ALLOW_OLD_TLS) - #error "TLS < 1.2 protocol versions not allowed https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1" + #error "TLS < 1.2 protocol versions not allowed" + /* https://www.rfc-editor.org/rfc/rfc9325#section-3.1.1 */ #endif #if !defined(WOLFSSL_NO_TLS12) && !defined(HAVE_SECURE_RENEGOTIATION) && \ !defined(HAVE_SERVER_RENEGOTIATION_INFO) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK) - #error "TLS 1.2 requires at least HAVE_SERVER_RENEGOTIATION_INFO to send the secure renegotiation extension https://www.rfc-editor.org/rfc/rfc9325#section-3.5" + #error "TLS 1.2 requires at least HAVE_SERVER_RENEGOTIATION_INFO to send the secure renegotiation extension" + /* https://www.rfc-editor.org/rfc/rfc9325#section-3.5 */ #endif #if !defined(WOLFSSL_EXTRA_ALERTS) || !defined(WOLFSSL_CHECK_ALERT_ON_ERR) #error "RFC9325 requires some additional alerts to be sent" diff --git a/src/wolfssl/wolfcrypt/sha.h b/src/wolfssl/wolfcrypt/sha.h index 54b0833..9a42e87 100644 --- a/src/wolfssl/wolfcrypt/sha.h +++ b/src/wolfssl/wolfcrypt/sha.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sha256.h b/src/wolfssl/wolfcrypt/sha256.h index 7a064a0..f203dad 100644 --- a/src/wolfssl/wolfcrypt/sha256.h +++ b/src/wolfssl/wolfcrypt/sha256.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sha3.h b/src/wolfssl/wolfcrypt/sha3.h index 724719a..1c0348c 100644 --- a/src/wolfssl/wolfcrypt/sha3.h +++ b/src/wolfssl/wolfcrypt/sha3.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -220,21 +220,25 @@ WOLFSSL_API int wc_Shake256_Copy(wc_Shake* src, wc_Sha3* dst); WOLFSSL_API int wc_Sha3_GetFlags(wc_Sha3* sha3, word32* flags); #endif -#ifdef USE_INTEL_SPEEDUP -WOLFSSL_LOCAL void sha3_block_n_bmi2(word64* s, const byte* data, word32 n, - word64 c); -WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); -WOLFSSL_LOCAL void sha3_block_avx2(word64* s); -WOLFSSL_LOCAL void sha3_blocksx4_avx2(word64* s); WOLFSSL_LOCAL void BlockSha3(word64 *s); + +#ifdef WC_SHA3_NO_ASM + /* asm speedups disabled */ + #if defined(USE_INTEL_SPEEDUP) && !defined(WC_MLKEM_NO_ASM) + /* native ML-KEM uses this directly. */ + WOLFSSL_LOCAL void sha3_blocksx4_avx2(word64* s); + #endif +#elif defined(USE_INTEL_SPEEDUP) + WOLFSSL_LOCAL void sha3_block_n_bmi2(word64* s, const byte* data, word32 n, + word64 c); + WOLFSSL_LOCAL void sha3_block_bmi2(word64* s); + WOLFSSL_LOCAL void sha3_block_avx2(word64* s); + WOLFSSL_LOCAL void sha3_blocksx4_avx2(word64* s); #elif defined(__aarch64__) && defined(WOLFSSL_ARMASM) -#ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 -WOLFSSL_LOCAL void BlockSha3_crypto(word64 *s); -#endif -WOLFSSL_LOCAL void BlockSha3_base(word64 *s); -WOLFSSL_LOCAL void BlockSha3(word64 *s); -#elif defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) -WOLFSSL_LOCAL void BlockSha3(word64 *s); + #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3 + WOLFSSL_LOCAL void BlockSha3_crypto(word64 *s); + #endif + WOLFSSL_LOCAL void BlockSha3_base(word64 *s); #endif #ifdef __cplusplus diff --git a/src/wolfssl/wolfcrypt/sha512.h b/src/wolfssl/wolfcrypt/sha512.h index 593177e..b90e2b2 100644 --- a/src/wolfssl/wolfcrypt/sha512.h +++ b/src/wolfssl/wolfcrypt/sha512.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/signature.h b/src/wolfssl/wolfcrypt/signature.h index 7d9a1d4..a78e627 100644 --- a/src/wolfssl/wolfcrypt/signature.h +++ b/src/wolfssl/wolfcrypt/signature.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/siphash.h b/src/wolfssl/wolfcrypt/siphash.h index 26cd821..db2d954 100644 --- a/src/wolfssl/wolfcrypt/siphash.h +++ b/src/wolfssl/wolfcrypt/siphash.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sm2.h b/src/wolfssl/wolfcrypt/sm2.h index fb90aaa..e4f0307 100644 --- a/src/wolfssl/wolfcrypt/sm2.h +++ b/src/wolfssl/wolfcrypt/sm2.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sm3.h b/src/wolfssl/wolfcrypt/sm3.h index e7e8b0e..bbd24ff 100644 --- a/src/wolfssl/wolfcrypt/sm3.h +++ b/src/wolfssl/wolfcrypt/sm3.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sm4.h b/src/wolfssl/wolfcrypt/sm4.h index 3cebb79..96d091e 100644 --- a/src/wolfssl/wolfcrypt/sm4.h +++ b/src/wolfssl/wolfcrypt/sm4.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sp.h b/src/wolfssl/wolfcrypt/sp.h index 9e7a9c9..c116cb0 100644 --- a/src/wolfssl/wolfcrypt/sp.h +++ b/src/wolfssl/wolfcrypt/sp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/sp_int.h b/src/wolfssl/wolfcrypt/sp_int.h index 7385e68..eb42d80 100644 --- a/src/wolfssl/wolfcrypt/sp_int.h +++ b/src/wolfssl/wolfcrypt/sp_int.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -260,9 +260,6 @@ extern "C" { #endif #endif -/* Number of bytes in each word. */ -#define SP_WORD_SIZEOF (SP_WORD_SIZE / 8) - /* Define the types used. */ #if defined(HAVE___UINT128_T) && !defined(NO_INT128) #ifdef __SIZEOF_INT128__ @@ -285,6 +282,8 @@ extern "C" { #endif #if SP_WORD_SIZE == 8 + #define SP_WORD_SIZEOF 1 + typedef sp_uint8 sp_int_digit; typedef sp_int8 sp_int_sdigit; typedef sp_uint16 sp_int_word; @@ -292,6 +291,8 @@ extern "C" { #define SP_MASK 0xffU #elif SP_WORD_SIZE == 16 + #define SP_WORD_SIZEOF 2 + typedef sp_uint16 sp_int_digit; typedef sp_int16 sp_int_sdigit; typedef sp_uint32 sp_int_word; @@ -299,6 +300,8 @@ extern "C" { #define SP_MASK 0xffffU #elif SP_WORD_SIZE == 32 + #define SP_WORD_SIZEOF 4 + typedef sp_uint32 sp_int_digit; typedef sp_int32 sp_int_sdigit; typedef sp_uint64 sp_int_word; @@ -306,6 +309,8 @@ extern "C" { #define SP_MASK 0xffffffffU #elif SP_WORD_SIZE == 64 + #define SP_WORD_SIZEOF 8 + typedef sp_uint64 sp_int_digit; typedef sp_int64 sp_int_sdigit; #if (defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)) && \ @@ -788,11 +793,19 @@ typedef struct sp_ecc_ctx { #define MP_INT_NEXT(t, cnt) \ (sp_int*)(((byte*)(t)) + MP_INT_SIZEOF(cnt)) +#define MP_INT_SIZEOF_DIGITS(cnt) (MP_INT_SIZEOF(cnt) / sizeof(sp_int_digit)) /* Calculate the number of words required to support a number of bits. */ #define MP_BITS_CNT(bits) \ ((unsigned int)(((((bits) + SP_WORD_SIZE - 1) / SP_WORD_SIZE) * 2 + 1))) +#if !defined(WOLFSSL_SP_NO_DYN_STACK) && defined(__STDC_VERSION__) && \ + (__STDC_VERSION__ >= 199901L) && \ + (defined(WOLFSSL_SP_NO_MALLOC) || \ + !(defined(WOLFSSL_SMALL_STACK) || defined(SP_ALLOC))) + #define WOLFSSL_SP_DYN_STACK +#endif + #ifdef WOLFSSL_SMALL_STACK /* * Dynamic memory allocation of mp_int. @@ -823,26 +836,25 @@ while (0) /* * Static allocation of mp_int. */ -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(WOLFSSL_SP_NO_DYN_STACK) +#ifdef WOLFSSL_SP_DYN_STACK /* Declare a dynamically allocated mp_int. */ -#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ - unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + sp_int_digit name##d[MP_INT_SIZEOF_DIGITS(MP_BITS_CNT(bits))]; \ sp_int* (name) = (sp_int*)name##d #elif defined(__cplusplus) /* C++ doesn't tolerate parentheses around "name" (-Wparentheses) */ -#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ - unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(max))]; \ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + sp_int_digit name##d[MP_INT_SIZEOF_DIGITS(MP_BITS_CNT(max))]; \ sp_int* name = (sp_int*)name##d #else /* Declare a dynamically allocated mp_int. */ -#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ - unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(max))]; \ +#define DECL_MP_INT_SIZE_DYN(name, bits, max) \ + sp_int_digit name##d[MP_INT_SIZEOF_DIGITS(MP_BITS_CNT(max))]; \ sp_int* (name) = (sp_int*)name##d #endif /* Declare a statically allocated mp_int. */ -#define DECL_MP_INT_SIZE(name, bits) \ - unsigned char name##d[MP_INT_SIZEOF(MP_BITS_CNT(bits))]; \ +#define DECL_MP_INT_SIZE(name, bits) \ + sp_int_digit name##d[MP_INT_SIZEOF_DIGITS(MP_BITS_CNT(bits))]; \ sp_int* (name) = (sp_int*)name##d /* Zero out mp_int of minimal size. */ #define NEW_MP_INT_SIZE(name, bits, heap, type) \ @@ -910,7 +922,7 @@ typedef struct sp_int { struct WC_BIGINT raw; #endif /** Data of number. */ - sp_int_digit dp[SP_INT_DIGITS]; + XALIGNED(SP_WORD_SIZEOF) sp_int_digit dp[SP_INT_DIGITS]; } sp_int; typedef struct sp_int_minimal { @@ -920,16 +932,22 @@ typedef struct sp_int_minimal { sp_size_t size; #ifdef WOLFSSL_SP_INT_NEGATIVE /** Indicates whether number is 0/positive or negative. */ - sp_uint8 sign; + sp_sign_t sign; #endif #ifdef HAVE_WOLF_BIGINT /** Unsigned binary (big endian) representation of number. */ struct WC_BIGINT raw; #endif /** First digit of number. */ - sp_int_digit dp[1]; + XALIGNED(SP_WORD_SIZEOF) sp_int_digit dp[1]; } sp_int_minimal; +/* MP_INT_SIZEOF_DIGITS() requires that sizeof(sp_int) is a multiple of + * sizeof(sp_int_digit). + */ +wc_static_assert(sizeof(struct sp_int) % sizeof(sp_int_digit) == 0); +wc_static_assert(sizeof(struct sp_int_minimal) % sizeof(sp_int_digit) == 0); + /* Multi-precision integer type is SP integer type. */ typedef sp_int mp_int; /* Multi-precision integer digit type is SP integer digit type. diff --git a/src/wolfssl/wolfcrypt/sphincs.h b/src/wolfssl/wolfcrypt/sphincs.h index f1487dd..06928aa 100644 --- a/src/wolfssl/wolfcrypt/sphincs.h +++ b/src/wolfssl/wolfcrypt/sphincs.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/srp.h b/src/wolfssl/wolfcrypt/srp.h index 7607765..b83933b 100644 --- a/src/wolfssl/wolfcrypt/srp.h +++ b/src/wolfssl/wolfcrypt/srp.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/tfm.h b/src/wolfssl/wolfcrypt/tfm.h index 718077c..d439250 100644 --- a/src/wolfssl/wolfcrypt/tfm.h +++ b/src/wolfssl/wolfcrypt/tfm.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -725,6 +725,7 @@ int fp_leading_bit(fp_int *a); int fp_unsigned_bin_size(const fp_int *a); int fp_read_unsigned_bin(fp_int *a, const unsigned char *b, int c); int fp_to_unsigned_bin(fp_int *a, unsigned char *b); +int fp_to_unsigned_bin_len_ct(fp_int *a, unsigned char *out, int outSz); int fp_to_unsigned_bin_len(fp_int *a, unsigned char *b, int c); int fp_to_unsigned_bin_at_pos(int x, fp_int *t, unsigned char *b); @@ -847,7 +848,7 @@ MP_API int mp_unsigned_bin_size(const mp_int * a); MP_API int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c); MP_API int mp_to_unsigned_bin_at_pos(int x, mp_int *t, unsigned char *b); MP_API int mp_to_unsigned_bin (mp_int * a, unsigned char *b); -#define mp_to_unsigned_bin_len_ct mp_to_unsigned_bin_len +MP_API int mp_to_unsigned_bin_len_ct(mp_int * a, unsigned char *b, int c); MP_API int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c); MP_API int mp_sub_d(fp_int *a, fp_digit b, fp_int *c); diff --git a/src/wolfssl/wolfcrypt/types.h b/src/wolfssl/wolfcrypt/types.h index 3ff9ec5..01ca1b7 100644 --- a/src/wolfssl/wolfcrypt/types.h +++ b/src/wolfssl/wolfcrypt/types.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -31,277 +31,280 @@ decouple library dependencies with standard string, memory and so on. #ifndef WOLF_CRYPT_TYPES_H #define WOLF_CRYPT_TYPES_H - #include - #include +#include +#include +#include - #if defined(EXTERNAL_OPTS_OPENVPN) && defined(BUILDING_WOLFSSL) - #error EXTERNAL_OPTS_OPENVPN should not be defined in compiled wolfssl library files. - #endif +#if defined(EXTERNAL_OPTS_OPENVPN) && defined(BUILDING_WOLFSSL) + #error EXTERNAL_OPTS_OPENVPN should not be defined in compiled wolfssl \ +library files. +#endif - #ifdef __APPLE__ - #include - #endif +#ifdef __APPLE__ + #include +#endif - #ifdef __cplusplus - extern "C" { - #endif +#ifdef __cplusplus + extern "C" { +#endif - /* - * This struct is used multiple time by other structs and - * needs to be defined somewhere that all structs can import - * (with minimal dependencies). - */ - #ifdef HAVE_EX_DATA +/* + * This struct is used multiple time by other structs and + * needs to be defined somewhere that all structs can import + * (with minimal dependencies). + */ +#ifdef HAVE_EX_DATA + #ifdef HAVE_EX_DATA_CLEANUP_HOOKS + typedef void (*wolfSSL_ex_data_cleanup_routine_t)(void *data); + #endif + typedef struct WOLFSSL_CRYPTO_EX_DATA { + void* ex_data[MAX_EX_DATA]; #ifdef HAVE_EX_DATA_CLEANUP_HOOKS - typedef void (*wolfSSL_ex_data_cleanup_routine_t)(void *data); + wolfSSL_ex_data_cleanup_routine_t + ex_data_cleanup_routines[MAX_EX_DATA]; #endif - typedef struct WOLFSSL_CRYPTO_EX_DATA { - void* ex_data[MAX_EX_DATA]; - #ifdef HAVE_EX_DATA_CLEANUP_HOOKS - wolfSSL_ex_data_cleanup_routine_t - ex_data_cleanup_routines[MAX_EX_DATA]; - #endif - } WOLFSSL_CRYPTO_EX_DATA; - typedef void (WOLFSSL_CRYPTO_EX_new)(void* p, void* ptr, - WOLFSSL_CRYPTO_EX_DATA* a, int idx, long argValue, void* arg); - typedef int (WOLFSSL_CRYPTO_EX_dup)(WOLFSSL_CRYPTO_EX_DATA* out, - const WOLFSSL_CRYPTO_EX_DATA* in, void* inPtr, int idx, - long argV, void* arg); - typedef void (WOLFSSL_CRYPTO_EX_free)(void* p, void* ptr, - WOLFSSL_CRYPTO_EX_DATA* a, int idx, long argValue, void* arg); - #endif + } WOLFSSL_CRYPTO_EX_DATA; + typedef void (WOLFSSL_CRYPTO_EX_new)(void* p, void* ptr, + WOLFSSL_CRYPTO_EX_DATA* a, int idx, long argValue, void* arg); + typedef int (WOLFSSL_CRYPTO_EX_dup)(WOLFSSL_CRYPTO_EX_DATA* out, + const WOLFSSL_CRYPTO_EX_DATA* in, void* inPtr, int idx, + long argV, void* arg); + typedef void (WOLFSSL_CRYPTO_EX_free)(void* p, void* ptr, + WOLFSSL_CRYPTO_EX_DATA* a, int idx, long argValue, void* arg); +#endif - #if defined(WORDS_BIGENDIAN) - #define BIG_ENDIAN_ORDER - #endif +#if defined(WORDS_BIGENDIAN) + #define BIG_ENDIAN_ORDER +#endif - #ifndef BIG_ENDIAN_ORDER - #define LITTLE_ENDIAN_ORDER - #endif +#ifndef BIG_ENDIAN_ORDER + #define LITTLE_ENDIAN_ORDER +#endif - #ifndef WOLFSSL_TYPES - #define WOLFSSL_TYPES - #ifndef byte - /* If using C++ C17 or later and getting: - * "error: reference to 'byte' is ambiguous", this is caused by - * cstddef conflict with "std::byte" in - * "enum class byte : unsigned char {};". - * This can occur if the user application is using "std" as the - * default namespace before including wolfSSL headers. - * Workarounds: https://github.com/wolfSSL/wolfssl/issues/5400 - */ - typedef unsigned char byte; - #endif - typedef signed char sword8; - typedef unsigned char word8; - #ifdef WC_16BIT_CPU - typedef int sword16; - typedef unsigned int word16; - typedef long sword32; - typedef unsigned long word32; - #else - typedef short sword16; - typedef unsigned short word16; - typedef int sword32; - typedef unsigned int word32; - #endif - typedef byte word24[3]; +#ifndef WOLFSSL_TYPES + #define WOLFSSL_TYPES + #ifndef byte + /* If using C++ C17 or later and getting: + * "error: reference to 'byte' is ambiguous", this is caused by + * cstddef conflict with "std::byte" in + * "enum class byte : unsigned char {};". + * This can occur if the user application is using "std" as the + * default namespace before including wolfSSL headers. + * Workarounds: https://github.com/wolfSSL/wolfssl/issues/5400 + */ + typedef unsigned char byte; + #endif + typedef signed char sword8; + typedef unsigned char word8; + #ifdef WC_16BIT_CPU + typedef int sword16; + typedef unsigned int word16; + typedef long sword32; + typedef unsigned long word32; + #else + typedef short sword16; + typedef unsigned short word16; + typedef int sword32; + typedef unsigned int word32; #endif + typedef byte word24[3]; +#endif +typedef const char wcchar[]; - /* constant pointer to a constant char */ - #ifdef WOLFSSL_NO_CONSTCHARCONST - typedef const char* wcchar; +#ifndef WC_BITFIELD + #ifdef WOLF_C89 + #define WC_BITFIELD unsigned #else - typedef const char* const wcchar; - #endif - - #ifndef WC_BITFIELD - #ifdef WOLF_C89 - #define WC_BITFIELD unsigned - #else - #define WC_BITFIELD byte - #endif + #define WC_BITFIELD byte #endif +#endif - #ifndef HAVE_ANONYMOUS_INLINE_AGGREGATES - /* if a version is available, pivot on the version, otherwise guess it's - * disallowed, subject to override. - */ - #if !defined(WOLF_C89) && (!defined(__STDC__) \ - || (!defined(__STDC_VERSION__) && !defined(__cplusplus)) \ - || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201101L)) \ - || (defined(__cplusplus) && (__cplusplus >= 201103L))) - #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 - #endif - #elif ~(~HAVE_ANONYMOUS_INLINE_AGGREGATES + 1) == 1 - /* forced on with empty value -- remap to 1 */ - #undef HAVE_ANONYMOUS_INLINE_AGGREGATES +#ifndef HAVE_ANONYMOUS_INLINE_AGGREGATES + /* if a version is available, pivot on the version, otherwise guess it's + * disallowed, subject to override. + */ + #if !defined(WOLF_C89) && (!defined(__STDC__) \ + || (!defined(__STDC_VERSION__) && !defined(__cplusplus)) \ + || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201101L)) \ + || (defined(__cplusplus) && (__cplusplus >= 201103L))) #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 - #elif HAVE_ANONYMOUS_INLINE_AGGREGATES - /* forced on with explicit nonzero value -- leave as-is. */ - #else - /* forced off with explicit zero value -- remap to undef. */ - #undef HAVE_ANONYMOUS_INLINE_AGGREGATES #endif +#elif ~(~HAVE_ANONYMOUS_INLINE_AGGREGATES + 1) == 1 + /* forced on with empty value -- remap to 1 */ + #undef HAVE_ANONYMOUS_INLINE_AGGREGATES + #define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 +#elif HAVE_ANONYMOUS_INLINE_AGGREGATES + /* forced on with explicit nonzero value -- leave as-is. */ +#else + /* forced off with explicit zero value -- remap to undef. */ + #undef HAVE_ANONYMOUS_INLINE_AGGREGATES +#endif - #ifndef HAVE_EMPTY_AGGREGATES - /* The C standards don't define empty aggregates, but gcc and clang do. - * We need to accommodate them for one of the same reasons C++ does -- - * conditionally empty aggregates, e.g. in hash.h. - * - * Nonetheless, in C++, empty aggregates wind up with size 1. If we use - * the [0] construct and the header is compiled by clang++, it warns - * "struct has size 0 in C, size 1 in C++ [-Wextern-c-compat]", despite - * the extern "C" wrapper. We sidestep this warning by recognizing - * here that C++ doesn't support truly empty aggregates. LLVM, for its part, - * deprecates compilation of C code as C++ using clang++. - */ - #if !defined(WOLF_C89) && defined(__GNUC__) && \ - !defined(__STRICT_ANSI__) && \ - !defined(__cplusplus) && \ - defined(HAVE_ANONYMOUS_INLINE_AGGREGATES) - #define HAVE_EMPTY_AGGREGATES 1 - #endif - #elif ~(~HAVE_EMPTY_AGGREGATES + 1) == 1 - /* forced on with empty value -- remap to 1 */ - #undef HAVE_EMPTY_AGGREGATES +#ifndef HAVE_EMPTY_AGGREGATES + /* The C standards don't define empty aggregates, but gcc and clang do. + * We need to accommodate them for one of the same reasons C++ does -- + * conditionally empty aggregates, e.g. in hash.h. + * + * Nonetheless, in C++, empty aggregates wind up with size 1. If we use + * the [0] construct and the header is compiled by clang++, it warns + * "struct has size 0 in C, size 1 in C++ [-Wextern-c-compat]", despite + * the extern "C" wrapper. We sidestep this warning by recognizing + * here that C++ doesn't support truly empty aggregates. LLVM, for its + * part, deprecates compilation of C code as C++ using clang++. + */ + #if !defined(WOLF_C89) && defined(__GNUC__) && \ + !defined(__STRICT_ANSI__) && \ + !defined(__cplusplus) && \ + defined(HAVE_ANONYMOUS_INLINE_AGGREGATES) #define HAVE_EMPTY_AGGREGATES 1 - #elif HAVE_EMPTY_AGGREGATES - /* forced on with explicit nonzero value -- leave as-is. */ - #else - /* forced off with explicit zero value -- remap to undef. */ - #undef HAVE_EMPTY_AGGREGATES #endif +#elif ~(~HAVE_EMPTY_AGGREGATES + 1) == 1 + /* forced on with empty value -- remap to 1 */ + #undef HAVE_EMPTY_AGGREGATES + #define HAVE_EMPTY_AGGREGATES 1 +#elif HAVE_EMPTY_AGGREGATES + /* forced on with explicit nonzero value -- leave as-is. */ +#else + /* forced off with explicit zero value -- remap to undef. */ + #undef HAVE_EMPTY_AGGREGATES +#endif - #define _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) a ## b ## c - #define _WOLF_AGG_DUMMY_MEMBER_HELPER(a, b, c) _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) - #ifdef HAVE_EMPTY_AGGREGATES - /* swallow the semicolon with a zero-sized array (language extension - * specific to gcc/clang). - */ - #define WOLF_AGG_DUMMY_MEMBER \ - struct { \ - PRAGMA_GCC_DIAG_PUSH \ - PRAGMA_GCC("GCC diagnostic ignored \"-Wpedantic\"") \ - PRAGMA_CLANG_DIAG_PUSH \ - PRAGMA_CLANG("clang diagnostic ignored \"-Wzero-length-array\"") \ - byte _WOLF_AGG_DUMMY_MEMBER_HELPER(_wolf_L, __LINE__, _agg_dummy_member)[0]; \ - PRAGMA_CLANG_DIAG_POP \ - PRAGMA_GCC_DIAG_POP \ - } - #else - /* Use a single byte with a constructed name as a dummy member -- these - * are the standard semantics of an empty structure in C++. - */ - #define WOLF_AGG_DUMMY_MEMBER char _WOLF_AGG_DUMMY_MEMBER_HELPER(_wolf_L, __LINE__, _agg_dummy_member) - #endif +#define _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) a ## b ## c +#define _WOLF_AGG_DUMMY_MEMBER_HELPER(a, b, c) \ + _WOLF_AGG_DUMMY_MEMBER_HELPER2(a, b, c) +#ifdef HAVE_EMPTY_AGGREGATES + /* swallow the semicolon with a zero-sized array (language extension + * specific to gcc/clang). + */ + #define WOLF_AGG_DUMMY_MEMBER \ + struct { \ + PRAGMA_GCC_DIAG_PUSH \ + PRAGMA_GCC("GCC diagnostic ignored \"-Wpedantic\"") \ + PRAGMA_CLANG_DIAG_PUSH \ + PRAGMA_CLANG("clang diagnostic ignored \"-Wzero-length-array\"") \ + byte _WOLF_AGG_DUMMY_MEMBER_HELPER(_wolf_L, __LINE__, \ + _agg_dummy_member)[0]; \ + PRAGMA_CLANG_DIAG_POP \ + PRAGMA_GCC_DIAG_POP \ + } +#else + /* Use a single byte with a constructed name as a dummy member -- these + * are the standard semantics of an empty structure in C++. + */ + #define WOLF_AGG_DUMMY_MEMBER char _WOLF_AGG_DUMMY_MEMBER_HELPER( \ + _wolf_L, __LINE__, _agg_dummy_member) +#endif - /* helpers for stringifying the expanded value of a macro argument rather - * than its literal text: - */ - #define _WC_STRINGIFY_L2(str) #str - #define WC_STRINGIFY(str) _WC_STRINGIFY_L2(str) - - /* With a true C89-dialect compiler (simulate with gcc -std=c89 -Wall - * -Wextra -pedantic), a trailing comma on the last value in an enum - * definition is a syntax error. We use this macro to accommodate that - * without disrupting clean flow/syntax when some enum values are - * preprocessor-gated. - */ - #if defined(WOLF_C89) || defined(WOLF_NO_TRAILING_ENUM_COMMAS) - #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) a ## b ## c ## d ## e - #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(a, b, c, d, e) _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) - #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(_wolf_, prefix, _L, __LINE__, _enum_dummy_last_element) - #else - #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) /* null expansion */ - #endif +/* helpers for stringifying the expanded value of a macro argument rather + * than its literal text: + */ +#define _WC_STRINGIFY_L2(str) #str +#define WC_STRINGIFY(str) _WC_STRINGIFY_L2(str) + +/* With a true C89-dialect compiler (simulate with gcc -std=c89 -Wall + * -Wextra -pedantic), a trailing comma on the last value in an enum + * definition is a syntax error. We use this macro to accommodate that + * without disrupting clean flow/syntax when some enum values are + * preprocessor-gated. + */ +#if defined(WOLF_C89) || defined(WOLF_NO_TRAILING_ENUM_COMMAS) + #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) \ + a ## b ## c ## d ## e + #define _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(a, b, c, d, e) \ + _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER2(a, b, c, d, e) + #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) \ + _WOLF_ENUM_DUMMY_LAST_ELEMENT_HELPER(_wolf_, prefix, _L, __LINE__, \ + _enum_dummy_last_element) +#else + #define WOLF_ENUM_DUMMY_LAST_ELEMENT(prefix) /* null expansion */ +#endif - /* try to set SIZEOF_LONG or SIZEOF_LONG_LONG if user didn't */ - #if defined(_WIN32) || defined(HAVE_LIMITS_H) - #include - /* make sure both SIZEOF_LONG_LONG and SIZEOF_LONG are set, - * otherwise causes issues with CTC_SETTINGS */ - #if !defined(SIZEOF_LONG_LONG) || !defined(SIZEOF_LONG) - #if !defined(SIZEOF_LONG) && defined(ULONG_MAX) && \ - (ULONG_MAX == 0xffffffffUL) - #define SIZEOF_LONG 4 - #endif - #if !defined(SIZEOF_LONG_LONG) && defined(ULLONG_MAX) && \ - (ULLONG_MAX == 0xffffffffffffffffULL) - #define SIZEOF_LONG_LONG 8 - #endif +/* try to set SIZEOF_LONG or SIZEOF_LONG_LONG if user didn't */ +#if defined(_WIN32) || defined(HAVE_LIMITS_H) + #include + /* make sure both SIZEOF_LONG_LONG and SIZEOF_LONG are set, + * otherwise causes issues with CTC_SETTINGS */ + #if !defined(SIZEOF_LONG_LONG) || !defined(SIZEOF_LONG) + #if !defined(SIZEOF_LONG) && defined(ULONG_MAX) && \ + (ULONG_MAX == 0xffffffffUL) + #define SIZEOF_LONG 4 #endif - #elif !defined(__BCPLUSPLUS__) && !defined(__EMSCRIPTEN__) - #if !defined(SIZEOF_LONG_LONG) && !defined(SIZEOF_LONG) - #if (defined(__alpha__) || defined(__ia64__) || \ - defined(_ARCH_PPC64) || defined(__ppc64__) || \ - defined(__x86_64__) || defined(__s390x__ ) || \ - ((defined(sun) || defined(__sun)) && \ - (defined(LP64) || defined(_LP64))) || \ - (defined(__riscv_xlen) && (__riscv_xlen == 64)) || \ - defined(__aarch64__) || defined(__mips64) || \ - (defined(__DCC__) && (defined(__LP64) || defined(__LP64__)))) - /* long should be 64bit */ - #define SIZEOF_LONG 8 - #elif defined(__i386__) || defined(__CORTEX_M3__) || defined(__ppc__) - /* long long should be 64bit */ - #define SIZEOF_LONG_LONG 8 - #endif - #endif - #endif - - #if (defined(_MSC_VER) && (_MSC_VER == 1200)) || /* MSVC6 */ \ - (defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ - defined(__BCPLUSPLUS__) || \ - (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) - /* windows types */ - #define WORD64_AVAILABLE - #define W64LIT(x) x##ui64 - #define SW64LIT(x) x##i64 - typedef __int64 sword64; - typedef unsigned __int64 word64; - #elif defined(__EMSCRIPTEN__) - #define WORD64_AVAILABLE - #define W64LIT(x) x##ull - #define SW64LIT(x) x##ll - typedef long long sword64; - typedef unsigned long long word64; - #elif defined(SIZEOF_LONG) && SIZEOF_LONG == 8 - #define WORD64_AVAILABLE - #ifdef WOLF_C89 - #define W64LIT(x) x##UL - #define SW64LIT(x) x##L - #else - #define W64LIT(x) x##ULL - #define SW64LIT(x) x##LL + #if !defined(SIZEOF_LONG_LONG) && defined(ULLONG_MAX) && \ + (ULLONG_MAX == 0xffffffffffffffffULL) + #define SIZEOF_LONG_LONG 8 #endif - typedef long sword64; - typedef unsigned long word64; - #elif defined(SIZEOF_LONG_LONG) && SIZEOF_LONG_LONG == 8 - #define WORD64_AVAILABLE - #ifdef WOLF_C89 - #define W64LIT(x) x##UL - #define SW64LIT(x) x##L - #else - #define W64LIT(x) x##ULL - #define SW64LIT(x) x##LL + #endif +#elif !defined(__BCPLUSPLUS__) && !defined(__EMSCRIPTEN__) + #if !defined(SIZEOF_LONG_LONG) && !defined(SIZEOF_LONG) + #if (defined(__alpha__) || defined(__ia64__) || \ + defined(_ARCH_PPC64) || defined(__ppc64__) || \ + defined(__x86_64__) || defined(__s390x__ ) || \ + ((defined(sun) || defined(__sun)) && \ + (defined(LP64) || defined(_LP64))) || \ + (defined(__riscv_xlen) && (__riscv_xlen == 64)) || \ + defined(__aarch64__) || defined(__mips64) || \ + (defined(__DCC__) && (defined(__LP64) || defined(__LP64__)))) + /* long should be 64bit */ + #define SIZEOF_LONG 8 + #elif defined(__i386__) || defined(__CORTEX_M3__) || defined(__ppc__) + /* long long should be 64bit */ + #define SIZEOF_LONG_LONG 8 #endif - typedef long long sword64; - typedef unsigned long long word64; - #elif defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 8 - #define WORD64_AVAILABLE - #ifdef WOLF_C89 - #define W64LIT(x) x##UL - #define SW64LIT(x) x##L - #else - #define W64LIT(x) x##ULL - #define SW64LIT(x) x##LL #endif - typedef long long sword64; - typedef unsigned long long word64; +#endif + +#if (defined(_MSC_VER) && (_MSC_VER == 1200)) || /* MSVC6 */ \ + (defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ + defined(__BCPLUSPLUS__) || \ + (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) + /* windows types */ + #define WORD64_AVAILABLE + #define W64LIT(x) x##ui64 + #define SW64LIT(x) x##i64 + typedef __int64 sword64; + typedef unsigned __int64 word64; +#elif defined(__EMSCRIPTEN__) + #define WORD64_AVAILABLE + #define W64LIT(x) x##ull + #define SW64LIT(x) x##ll + typedef long long sword64; + typedef unsigned long long word64; +#elif defined(SIZEOF_LONG) && SIZEOF_LONG == 8 + #define WORD64_AVAILABLE + #ifdef WOLF_C89 + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L + #else + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL + #endif + typedef long sword64; + typedef unsigned long word64; +#elif defined(SIZEOF_LONG_LONG) && SIZEOF_LONG_LONG == 8 + #define WORD64_AVAILABLE + #ifdef WOLF_C89 + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L + #else + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL + #endif + typedef long long sword64; + typedef unsigned long long word64; +#elif defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 8 + #define WORD64_AVAILABLE + #ifdef WOLF_C89 + #define W64LIT(x) x##UL + #define SW64LIT(x) x##L + #else + #define W64LIT(x) x##ULL + #define SW64LIT(x) x##LL #endif + typedef long long sword64; + typedef unsigned long long word64; +#endif #if defined(WORD64_AVAILABLE) && !defined(WC_16BIT_CPU) /* These platforms have 64-bit CPU registers. */ @@ -347,17 +350,17 @@ decouple library dependencies with standard string, memory and so on. #ifndef MICROCHIP_PIC24 #undef WORD64_AVAILABLE #endif - typedef word16 wolfssl_word; - #define WOLFSSL_WORD_SIZE_LOG2 1 - #define MP_16BIT /* for mp_int, mp_word needs to be twice as big as \ - * mp_digit, no 64 bit type so make mp_digit 16 bit */ + typedef word16 wolfssl_word; + #define WOLFSSL_WORD_SIZE_LOG2 1 + #define MP_16BIT /* for mp_int, mp_word needs to be twice as big as \ + * mp_digit, no 64 bit type so make mp_digit 16 bit */ #else #undef WORD64_AVAILABLE typedef word32 wolfssl_word; #define WOLFSSL_WORD_SIZE_LOG2 2 #define MP_16BIT /* for mp_int, mp_word needs to be twice as big as \ - * mp_digit, no 64 bit type so make mp_digit 16 bit */ + * mp_digit, no 64 bit type so make mp_digit 16 bit */ #endif typedef struct w64wrapper { @@ -378,396 +381,439 @@ typedef struct w64wrapper { typedef size_t wc_ptr_t; #endif - enum { - WOLFSSL_WORD_SIZE = sizeof(wolfssl_word), - WOLFSSL_BIT_SIZE = 8, - WOLFSSL_WORD_BITS = WOLFSSL_WORD_SIZE * WOLFSSL_BIT_SIZE - }; +enum { + WOLFSSL_WORD_SIZE = sizeof(wolfssl_word), + WOLFSSL_BIT_SIZE = 8, + WOLFSSL_WORD_BITS = WOLFSSL_WORD_SIZE * WOLFSSL_BIT_SIZE +}; - #define WOLFSSL_MAX_8BIT 0xffU - #define WOLFSSL_MAX_16BIT 0xffffU - #define WOLFSSL_MAX_32BIT 0xffffffffU - - #ifndef WC_DO_NOTHING - #define WC_DO_NOTHING do {} while (0) - #ifdef _MSC_VER - /* disable buggy MSC warning around while(0), - *"warning C4127: conditional expression is constant" - */ - #pragma warning(disable: 4127) - #endif +#define WOLFSSL_MAX_8BIT 0xffU +#define WOLFSSL_MAX_16BIT 0xffffU +#define WOLFSSL_MAX_32BIT 0xffffffffU + +#ifndef WC_DO_NOTHING + #define WC_DO_NOTHING do {} while (0) + #ifdef _MSC_VER + /* disable buggy MSC warning around while(0), + *"warning C4127: conditional expression is constant" + */ + #pragma warning(disable: 4127) #endif +#endif - #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) - #define INLINE WC_INLINE +#if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) + #define INLINE WC_INLINE +#endif + +/* set up rotate style */ +#if ((defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ + defined(__BCPLUSPLUS__)) && !defined(WOLFSSL_SGX) && \ + !defined(INTIME_RTOS) + #define INTEL_INTRINSICS + #define FAST_ROTATE +#elif defined(__MWERKS__) && TARGET_CPU_PPC + #define PPC_INTRINSICS + #define FAST_ROTATE +#elif defined(__CCRX__) + #define FAST_ROTATE +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + /* GCC does peephole optimizations which should result in using rotate + instructions */ + #define FAST_ROTATE +#endif + +/* set up thread local storage if available */ +#ifdef HAVE_THREAD_LS + #if defined(_MSC_VER) || defined(__WATCOMC__) + #define THREAD_LS_T __declspec(thread) + /* Thread local storage only in FreeRTOS v8.2.1 and higher */ + #elif defined(FREERTOS) || defined(FREERTOS_TCP) || \ + defined(WOLFSSL_ZEPHYR) + #define THREAD_LS_T + #else + #define THREAD_LS_T __thread #endif +#else + #define THREAD_LS_T +#endif - /* set up rotate style */ - #if ((defined(_MSC_VER) && !defined(WOLFSSL_NOT_WINDOWS_API)) || \ - defined(__BCPLUSPLUS__)) && !defined(WOLFSSL_SGX) && !defined(INTIME_RTOS) - #define INTEL_INTRINSICS - #define FAST_ROTATE - #elif defined(__MWERKS__) && TARGET_CPU_PPC - #define PPC_INTRINSICS - #define FAST_ROTATE - #elif defined(__CCRX__) - #define FAST_ROTATE - #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) - /* GCC does peephole optimizations which should result in using rotate - instructions */ - #define FAST_ROTATE +#ifndef FALL_THROUGH + /* GCC 7 has new switch() fall-through detection */ + #if defined(__GNUC__) + #if defined(fallthrough) + #define FALL_THROUGH fallthrough + #elif ((__GNUC__ > 7) || ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 1))) + #define FALL_THROUGH ; __attribute__ ((fallthrough)) + #elif defined(__clang__) && defined(__clang_major__) && \ + (__clang_major__ >= 12) + #define FALL_THROUGH ; __attribute__ ((fallthrough)) + #endif #endif +#endif /* FALL_THROUGH */ +#if !defined(FALL_THROUGH) || defined(__XC32) + /* use stub for fall through by default or for Microchip compiler */ + #undef FALL_THROUGH + #define FALL_THROUGH +#endif - /* set up thread local storage if available */ - #ifdef HAVE_THREAD_LS - #if defined(_MSC_VER) || defined(__WATCOMC__) - #define THREAD_LS_T __declspec(thread) - /* Thread local storage only in FreeRTOS v8.2.1 and higher */ - #elif defined(FREERTOS) || defined(FREERTOS_TCP) || \ - defined(WOLFSSL_ZEPHYR) - #define THREAD_LS_T +#define XSTR_SIZEOF(x) (sizeof(x) - 1) /* -1 to not count the null char */ + +#define XELEM_CNT(x) (sizeof((x))/sizeof(*(x))) + +#define WC_SAFE_SUM_WORD32(in1, in2, out) ((in2) <= 0xffffffffU - (in1) ? \ + ((out) = (in1) + (in2), 1) : ((out) = 0xffffffffU, 0)) + +#if defined(HAVE_IO_POOL) + WOLFSSL_API void* XMALLOC(size_t n, void* heap, int type); + WOLFSSL_API void* XREALLOC(void *p, size_t n, void* heap, int type); + WOLFSSL_API void XFREE(void *p, void* heap, int type); +#elif (defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_INTEL_QA)) || \ + defined(HAVE_INTEL_QA_SYNC) + #ifndef HAVE_INTEL_QA_SYNC + #include + #undef USE_WOLFSSL_MEMORY + #ifdef WOLFSSL_DEBUG_MEMORY + #define XMALLOC(s, h, t) \ + IntelQaMalloc((s), (h), (t), __func__, __LINE__) + #define XFREE(p, h, t) \ + IntelQaFree((p), (h), (t), __func__, __LINE__) + #define XREALLOC(p, n, h, t) \ + IntelQaRealloc((p), (n), (h), (t), __func__, __LINE__) #else - #define THREAD_LS_T __thread - #endif + #define XMALLOC(s, h, t) IntelQaMalloc((s), (h), (t)) + #define XFREE(p, h, t) IntelQaFree((p), (h), (t)) + #define XREALLOC(p, n, h, t) IntelQaRealloc((p), (n), (h), (t)) + #endif /* WOLFSSL_DEBUG_MEMORY */ #else - #define THREAD_LS_T + #include + #undef USE_WOLFSSL_MEMORY + #ifdef WOLFSSL_DEBUG_MEMORY + #define XMALLOC(s, h, t) \ + wc_CryptoCb_IntelQaMalloc((s), (h), (t), __func__, __LINE__) + #define XFREE(p, h, t) \ + wc_CryptoCb_IntelQaFree((p), (h), (t), __func__, __LINE__) + #define XREALLOC(p, n, h, t) \ + wc_CryptoCb_IntelQaRealloc((p), (n), (h), (t), __func__, \ + __LINE__) + #else + #define XMALLOC(s, h, t) \ + wc_CryptoCb_IntelQaMalloc((s), (h), (t)) + #define XFREE(p, h, t) \ + wc_CryptoCb_IntelQaFree((p), (h), (t)) + #define XREALLOC(p, n, h, t) \ + wc_CryptoCb_IntelQaRealloc((p), (n), (h), (t)) + #endif /* WOLFSSL_DEBUG_MEMORY */ + #endif +#elif defined(XMALLOC_USER) + /* prototypes for user heap override functions */ + #include /* for size_t */ + extern void *XMALLOC(size_t n, void* heap, int type); + extern void *XREALLOC(void *p, size_t n, void* heap, int type); + extern void XFREE(void *p, void* heap, int type); +#elif defined(WOLFSSL_MEMORY_LOG) + #define XMALLOC(n, h, t) xmalloc(n, h, t, __func__, __FILE__, __LINE__) + #define XREALLOC(p, n, h, t) \ + xrealloc(p, n, h, t, __func__, __FILE__, __LINE__) + #define XFREE(p, h, t) xfree(p, h, t, __func__, __FILE__, __LINE__) + + /* prototypes for user heap override functions */ + #include /* for size_t */ + #include + WOLFSSL_API void *xmalloc(size_t n, void* heap, int type, + const char* func, const char* file, unsigned int line); + WOLFSSL_API void *xrealloc(void *p, size_t n, void* heap, int type, + const char* func, const char* file, unsigned int line); + WOLFSSL_API void xfree(void *p, void* heap, int type, const char* func, + const char* file, unsigned int line); +#elif defined(XMALLOC_OVERRIDE) + /* override the XMALLOC, XFREE and XREALLOC macros */ +#elif defined(WOLFSSL_TELIT_M2MB) + /* Telit M2MB SDK requires use m2mb_os API's, not std malloc/free */ + /* Use of malloc/free will cause CPU reboot */ + #define XMALLOC(s, h, t) ((void)(h), (void)(t), \ + m2mb_os_malloc((s))) + #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK + #define XFREE(p, h, t) m2mb_os_free(xp) + #else + #define XFREE(p, h, t) do { void* xp = (p); if (xp) \ + m2mb_os_free(xp); } while (0) #endif + #define XREALLOC(p, n, h, t) m2mb_os_realloc((p), (n)) - #ifndef FALL_THROUGH - /* GCC 7 has new switch() fall-through detection */ - #if defined(__GNUC__) - #if defined(fallthrough) - #define FALL_THROUGH fallthrough - #elif ((__GNUC__ > 7) || ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 1))) - #define FALL_THROUGH ; __attribute__ ((fallthrough)) - #elif defined(__clang__) && defined(__clang_major__) && \ - (__clang_major__ >= 12) - #define FALL_THROUGH ; __attribute__ ((fallthrough)) - #endif +#elif defined(NO_WOLFSSL_MEMORY) + #ifdef WOLFSSL_NO_MALLOC + /* this platform does not support heap use */ + #ifdef WOLFSSL_SMALL_STACK + #error WOLFSSL_SMALL_STACK requires a heap implementation. #endif - #endif /* FALL_THROUGH */ - #if !defined(FALL_THROUGH) || defined(__XC32) - /* use stub for fall through by default or for Microchip compiler */ - #undef FALL_THROUGH - #define FALL_THROUGH - #endif - - #define XSTR_SIZEOF(x) (sizeof(x) - 1) /* -1 to not count the null char */ - - #define XELEM_CNT(x) (sizeof((x))/sizeof(*(x))) - - #define WC_SAFE_SUM_WORD32(in1, in2, out) ((in2) <= 0xffffffffU - (in1) ? \ - ((out) = (in1) + (in2), 1) : ((out) = 0xffffffffU, 0)) - - #if defined(HAVE_IO_POOL) - WOLFSSL_API void* XMALLOC(size_t n, void* heap, int type); - WOLFSSL_API void* XREALLOC(void *p, size_t n, void* heap, int type); - WOLFSSL_API void XFREE(void *p, void* heap, int type); - #elif (defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_INTEL_QA)) || \ - defined(HAVE_INTEL_QA_SYNC) - #ifndef HAVE_INTEL_QA_SYNC - #include - #undef USE_WOLFSSL_MEMORY - #ifdef WOLFSSL_DEBUG_MEMORY - #define XMALLOC(s, h, t) IntelQaMalloc((s), (h), (t), __func__, __LINE__) - #define XFREE(p, h, t) IntelQaFree((p), (h), (t), __func__, __LINE__) - #define XREALLOC(p, n, h, t) IntelQaRealloc((p), (n), (h), (t), __func__, __LINE__) - #else - #define XMALLOC(s, h, t) IntelQaMalloc((s), (h), (t)) - #define XFREE(p, h, t) IntelQaFree((p), (h), (t)) - #define XREALLOC(p, n, h, t) IntelQaRealloc((p), (n), (h), (t)) - #endif /* WOLFSSL_DEBUG_MEMORY */ + #ifndef WC_NO_CONSTRUCTORS + #define WC_NO_CONSTRUCTORS + #endif + #ifdef WOLFSSL_MALLOC_CHECK + #ifndef NO_STDIO_FILESYSTEM + #include + #endif + static inline void* malloc_check(size_t sz) { + fprintf(stderr, "wolfSSL_malloc failed"); + return NULL; + }; + #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc_check((s))) + #define XFREE(p, h, t) do { (void)(h); (void)(t); } while (0) + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), NULL) #else - #include - #undef USE_WOLFSSL_MEMORY - #ifdef WOLFSSL_DEBUG_MEMORY - #define XMALLOC(s, h, t) wc_CryptoCb_IntelQaMalloc((s), (h), (t), __func__, __LINE__) - #define XFREE(p, h, t) wc_CryptoCb_IntelQaFree((p), (h), (t), __func__, __LINE__) - #define XREALLOC(p, n, h, t) wc_CryptoCb_IntelQaRealloc((p), (n), (h), (t), __func__, __LINE__) - #else - #define XMALLOC(s, h, t) wc_CryptoCb_IntelQaMalloc((s), (h), (t)) - #define XFREE(p, h, t) wc_CryptoCb_IntelQaFree((p), (h), (t)) - #define XREALLOC(p, n, h, t) wc_CryptoCb_IntelQaRealloc((p), (n), (h), (t)) - #endif /* WOLFSSL_DEBUG_MEMORY */ + #define XMALLOC(s, h, t) ((void)(s), (void)(h), (void)(t), NULL) + #define XFREE(p, h, t) do { (void)(p); (void)(h); (void)(t); } while(0) + #define XREALLOC(p, n, h, t) ((void)(p), (void)(n), (void)(h), (void)(t), NULL) #endif - #elif defined(XMALLOC_USER) - /* prototypes for user heap override functions */ - #include /* for size_t */ - extern void *XMALLOC(size_t n, void* heap, int type); - extern void *XREALLOC(void *p, size_t n, void* heap, int type); - extern void XFREE(void *p, void* heap, int type); - #elif defined(WOLFSSL_MEMORY_LOG) - #define XMALLOC(n, h, t) xmalloc(n, h, t, __func__, __FILE__, __LINE__) - #define XREALLOC(p, n, h, t) xrealloc(p, n, h, t, __func__, __FILE__, __LINE__) - #define XFREE(p, h, t) xfree(p, h, t, __func__, __FILE__, __LINE__) - - /* prototypes for user heap override functions */ - #include /* for size_t */ + #else + /* just use plain C stdlib stuff if desired */ #include - WOLFSSL_API void *xmalloc(size_t n, void* heap, int type, - const char* func, const char* file, unsigned int line); - WOLFSSL_API void *xrealloc(void *p, size_t n, void* heap, int type, - const char* func, const char* file, unsigned int line); - WOLFSSL_API void xfree(void *p, void* heap, int type, const char* func, - const char* file, unsigned int line); - #elif defined(XMALLOC_OVERRIDE) - /* override the XMALLOC, XFREE and XREALLOC macros */ - #elif defined(WOLFSSL_TELIT_M2MB) - /* Telit M2MB SDK requires use m2mb_os API's, not std malloc/free */ - /* Use of malloc/free will cause CPU reboot */ - #define XMALLOC(s, h, t) ((void)(h), (void)(t), m2mb_os_malloc((s))) + #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc((size_t)(s))) /* native heap */ #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) m2mb_os_free(xp) + #define XFREE(p, h, t) do { (void)(h); (void)(t); free(p); } while (0) /* native heap */ #else - #define XFREE(p, h, t) do { void* xp = (p); if (xp) m2mb_os_free(xp); } while (0) + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); if (xp) free(xp); } while (0) /* native heap */ #endif - #define XREALLOC(p, n, h, t) m2mb_os_realloc((p), (n)) + #define XREALLOC(p, n, h, t) \ + ((void)(h), (void)(t), realloc((p), (size_t)(n))) /* native heap */ + #endif + +#elif defined(WOLFSSL_LINUXKM) + + /* definitions are in linuxkm/linuxkm_wc_port.h */ - #elif defined(NO_WOLFSSL_MEMORY) - #ifdef WOLFSSL_NO_MALLOC - /* this platform does not support heap use */ - #ifdef WOLFSSL_SMALL_STACK - #error WOLFSSL_SMALL_STACK requires a heap implementation. +#elif !defined(MICRIUM_MALLOC) && !defined(EBSNET) \ + && !defined(WOLFSSL_SAFERTOS) && !defined(FREESCALE_MQX) \ + && !defined(FREESCALE_KSDK_MQX) && !defined(FREESCALE_FREE_RTOS) \ + && !defined(WOLFSSL_LEANPSK) && !defined(WOLFSSL_uITRON4) + /* default C runtime, can install different routines at runtime via cbs */ + #ifndef WOLFSSL_MEMORY_H + #include + #endif + #ifdef WOLFSSL_STATIC_MEMORY + #ifdef WOLFSSL_DEBUG_MEMORY + #define XMALLOC(s, h, t) \ + wolfSSL_Malloc((s), (h), (t), __func__, __LINE__) + #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK + #define XFREE(p, h, t) \ + wolfSSL_Free(xp, h, t, __func__, __LINE__) + #else + #define XFREE(p, h, t) do { void* xp = (p); if (xp) \ + wolfSSL_Free(xp, h, t, __func__, __LINE__); } while (0) #endif - #ifndef WC_NO_CONSTRUCTORS - #define WC_NO_CONSTRUCTORS + #define XREALLOC(p, n, h, t) \ + wolfSSL_Realloc((p), (n), (h), (t), __func__, __LINE__) + #else + #define XMALLOC(s, h, t) wolfSSL_Malloc((s), (h), (t)) + #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK + #define XFREE(p, h, t) wolfSSL_Free(xp, h, t) + #else + #define XFREE(p, h, t) do { void* xp = (p); if (xp) \ + wolfSSL_Free(xp, h, t); } while (0) #endif - #ifdef WOLFSSL_MALLOC_CHECK - #ifndef NO_STDIO_FILESYSTEM - #include - #endif - static inline void* malloc_check(size_t sz) { - fprintf(stderr, "wolfSSL_malloc failed"); - return NULL; - }; - #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc_check((s))) - #define XFREE(p, h, t) do { (void)(h); (void)(t); } while (0) - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), NULL) + #define XREALLOC(p, n, h, t) wolfSSL_Realloc((p), (n), (h), (t)) + #endif /* WOLFSSL_DEBUG_MEMORY */ + #elif defined(WOLFSSL_EMBOS) && !defined(XMALLOC_USER) \ + && !defined(NO_WOLFSSL_MEMORY) \ + && !defined(WOLFSSL_STATIC_MEMORY) + /* settings.h solve this case already. Avoid redefinition. */ + #elif (!defined(FREERTOS) && !defined(FREERTOS_TCP)) || \ + defined(WOLFSSL_TRACK_MEMORY) + #ifdef WOLFSSL_DEBUG_MEMORY + #define XMALLOC(s, h, t) ((void)(h), (void)(t), \ + wolfSSL_Malloc((s), __func__, __LINE__)) + #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK + #define XFREE(p, h, t) do { (void)(h); (void)(t); \ + wolfSSL_Free(xp, __func__, __LINE__); } while (0) #else - #define XMALLOC(s, h, t) ((void)(s), (void)(h), (void)(t), NULL) - #define XFREE(p, h, t) do { (void)(p); (void)(h); (void)(t); } while(0) - #define XREALLOC(p, n, h, t) ((void)(p), (void)(n), (void)(h), (void)(t), NULL) + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); \ + (void)(t); if (xp) wolfSSL_Free(xp, __func__, __LINE__); \ + } while (0) #endif + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), \ + wolfSSL_Realloc((p), (n), __func__, __LINE__)) #else - /* just use plain C stdlib stuff if desired */ - #include - #define XMALLOC(s, h, t) ((void)(h), (void)(t), malloc((size_t)(s))) /* native heap */ + #define XMALLOC(s, h, t) ((void)(h), (void)(t), \ + wolfSSL_Malloc((s))) #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) do { (void)(h); (void)(t); free(p); } while (0) /* native heap */ + #define XFREE(p, h, t) do { (void)(h); (void)(t); \ + wolfSSL_Free(p); } while (0) #else - #define XFREE(p, h, t) do { void* xp = (p); (void)(h); if (xp) free(xp); } while (0) /* native heap */ + #define XFREE(p, h, t) do { void* xp = (p); (void)(h); \ + (void)(t); if (xp) wolfSSL_Free(xp); } while (0) #endif - #define XREALLOC(p, n, h, t) \ - ((void)(h), (void)(t), realloc((p), (size_t)(n))) /* native heap */ - #endif - - #elif defined(WOLFSSL_LINUXKM) - - /* definitions are in linuxkm/linuxkm_wc_port.h */ + #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), \ + wolfSSL_Realloc((p), (n))) + #endif /* WOLFSSL_DEBUG_MEMORY */ + #endif /* WOLFSSL_STATIC_MEMORY */ +#endif - #elif !defined(MICRIUM_MALLOC) && !defined(EBSNET) \ - && !defined(WOLFSSL_SAFERTOS) && !defined(FREESCALE_MQX) \ - && !defined(FREESCALE_KSDK_MQX) && !defined(FREESCALE_FREE_RTOS) \ - && !defined(WOLFSSL_LEANPSK) && !defined(WOLFSSL_uITRON4) - /* default C runtime, can install different routines at runtime via cbs */ - #ifndef WOLFSSL_MEMORY_H - #include - #endif - #ifdef WOLFSSL_STATIC_MEMORY - #ifdef WOLFSSL_DEBUG_MEMORY - #define XMALLOC(s, h, t) wolfSSL_Malloc((s), (h), (t), __func__, __LINE__) - #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) wolfSSL_Free(xp, h, t, __func__, __LINE__) - #else - #define XFREE(p, h, t) do { void* xp = (p); if (xp) wolfSSL_Free(xp, h, t, __func__, __LINE__); } while (0) - #endif - #define XREALLOC(p, n, h, t) wolfSSL_Realloc((p), (n), (h), (t), __func__, __LINE__) - #else - #define XMALLOC(s, h, t) wolfSSL_Malloc((s), (h), (t)) - #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) wolfSSL_Free(xp, h, t) - #else - #define XFREE(p, h, t) do { void* xp = (p); if (xp) wolfSSL_Free(xp, h, t); } while (0) - #endif - #define XREALLOC(p, n, h, t) wolfSSL_Realloc((p), (n), (h), (t)) - #endif /* WOLFSSL_DEBUG_MEMORY */ - #elif defined(WOLFSSL_EMBOS) && !defined(XMALLOC_USER) \ - && !defined(NO_WOLFSSL_MEMORY) \ - && !defined(WOLFSSL_STATIC_MEMORY) - /* settings.h solve this case already. Avoid redefinition. */ - #elif (!defined(FREERTOS) && !defined(FREERTOS_TCP)) || defined(WOLFSSL_TRACK_MEMORY) - #ifdef WOLFSSL_DEBUG_MEMORY - #define XMALLOC(s, h, t) ((void)(h), (void)(t), wolfSSL_Malloc((s), __func__, __LINE__)) - #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) do { (void)(h); (void)(t); wolfSSL_Free(xp, __func__, __LINE__); } while (0) - #else - #define XFREE(p, h, t) do { void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp, __func__, __LINE__); } while (0) - #endif - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), wolfSSL_Realloc((p), (n), __func__, __LINE__)) - #else - #define XMALLOC(s, h, t) ((void)(h), (void)(t), wolfSSL_Malloc((s))) - #ifdef WOLFSSL_XFREE_NO_NULLNESS_CHECK - #define XFREE(p, h, t) do { (void)(h); (void)(t); wolfSSL_Free(p); } while (0) - #else - #define XFREE(p, h, t) do { void* xp = (p); (void)(h); (void)(t); if (xp) wolfSSL_Free(xp); } while (0) - #endif - #define XREALLOC(p, n, h, t) ((void)(h), (void)(t), wolfSSL_Realloc((p), (n))) - #endif /* WOLFSSL_DEBUG_MEMORY */ - #endif /* WOLFSSL_STATIC_MEMORY */ - #endif +#if defined(WOLFSSL_SMALL_STACK) && defined(WC_NO_CONSTRUCTORS) + #error WOLFSSL_SMALL_STACK requires constructors. +#endif - #if defined(WOLFSSL_SMALL_STACK) && defined(WC_NO_CONSTRUCTORS) - #error WOLFSSL_SMALL_STACK requires constructors. - #endif +#include - #include +/* declare/free variable handling for async and smallstack */ +#ifndef WC_ALLOC_DO_ON_FAILURE + #define WC_ALLOC_DO_ON_FAILURE() WC_DO_NOTHING +#endif - /* declare/free variable handling for async and smallstack */ - #ifndef WC_ALLOC_DO_ON_FAILURE - #define WC_ALLOC_DO_ON_FAILURE() WC_DO_NOTHING - #endif +#define WC_DECLARE_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + VAR_TYPE* VAR_NAME[VAR_ITEMS] = { NULL, }; \ + int idx##VAR_NAME = 0, inner_idx_##VAR_NAME +#define WC_HEAP_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ + VAR_TYPE* VAR_NAME[VAR_ITEMS] +#define WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + for (idx##VAR_NAME=0; idx##VAR_NAME<(VAR_ITEMS); idx##VAR_NAME++) { \ + (VAR_NAME)[idx##VAR_NAME] = (VAR_TYPE*)XMALLOC(VAR_SIZE, (HEAP), \ + DYNAMIC_TYPE_TMP_BUFFER); \ + if ((VAR_NAME)[idx##VAR_NAME] == NULL) { \ + for (inner_idx_##VAR_NAME = 0; \ + inner_idx_##VAR_NAME < idx##VAR_NAME; \ + inner_idx_##VAR_NAME++) { \ + XFREE((VAR_NAME)[inner_idx_##VAR_NAME], (HEAP), \ + DYNAMIC_TYPE_TMP_BUFFER); \ + (VAR_NAME)[inner_idx_##VAR_NAME] = NULL; \ + } \ + for (inner_idx_##VAR_NAME = idx##VAR_NAME + 1; \ + inner_idx_##VAR_NAME < (VAR_ITEMS); \ + inner_idx_##VAR_NAME++) { \ + (VAR_NAME)[inner_idx_##VAR_NAME] = NULL; \ + } \ + idx##VAR_NAME = 0; \ + WC_ALLOC_DO_ON_FAILURE(); \ + break; \ + } \ + } +#define WC_CALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + do { \ + WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP); \ + if (idx##VAR_NAME != 0) { \ + for (idx##VAR_NAME=0; \ + idx##VAR_NAME<(VAR_ITEMS); \ + idx##VAR_NAME++) { \ + XMEMSET((VAR_NAME)[idx##VAR_NAME], 0, VAR_SIZE); \ + } \ + } \ + } while (0) +#define WC_HEAP_ARRAY_OK(VAR_NAME) (idx##VAR_NAME != 0) +#define WC_FREE_HEAP_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) \ + if (WC_HEAP_ARRAY_OK(VAR_NAME)) { \ + for (idx##VAR_NAME=0; idx##VAR_NAME<(VAR_ITEMS); idx##VAR_NAME++) { \ + XFREE((VAR_NAME)[idx##VAR_NAME], (HEAP), DYNAMIC_TYPE_TMP_BUFFER); \ + } \ + idx##VAR_NAME = 0; \ + } + +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_SMALL_STACK) + #define WC_DECLARE_VAR_IS_HEAP_ALLOC + #define WC_DECLARE_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ + VAR_TYPE* VAR_NAME = NULL + #define WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ + do { \ + (VAR_NAME) = (VAR_TYPE*)XMALLOC(sizeof(VAR_TYPE) * (VAR_SIZE), \ + (HEAP), DYNAMIC_TYPE_WOLF_BIGINT); \ + if ((VAR_NAME) == NULL) { \ + WC_ALLOC_DO_ON_FAILURE(); \ + } \ + } while (0) + #define WC_CALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ + do { \ + WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP); \ + XMEMSET(VAR_NAME, 0, sizeof(VAR_TYPE) * (VAR_SIZE)); \ + } while (0) + #define WC_FREE_VAR(VAR_NAME, HEAP) \ + XFREE(VAR_NAME, (HEAP), DYNAMIC_TYPE_WOLF_BIGINT) + #define WC_DECLARE_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + WC_DECLARE_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) + #define WC_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ + WC_HEAP_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) + #define WC_ALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) + #define WC_CALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + WC_CALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) + #define WC_ARRAY_OK(VAR_NAME) WC_HEAP_ARRAY_OK(VAR_NAME) + #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) \ + WC_FREE_HEAP_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) +#else + #undef WC_DECLARE_VAR_IS_HEAP_ALLOC + #define WC_DECLARE_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ + VAR_TYPE VAR_NAME[VAR_SIZE] + #define WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) WC_DO_NOTHING + #define WC_CALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ + XMEMSET(VAR_NAME, 0, sizeof(var)) + #define WC_FREE_VAR(VAR_NAME, HEAP) WC_DO_NOTHING \ + /* nothing to free, its stack */ + #define WC_DECLARE_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + VAR_TYPE VAR_NAME[VAR_ITEMS][(VAR_SIZE) / sizeof(VAR_TYPE)] /* // NOLINT(bugprone-sizeof-expression) */ + #define WC_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ + VAR_TYPE VAR_NAME[VAR_ITEMS][(VAR_SIZE) / sizeof(VAR_TYPE)] /* // NOLINT(bugprone-sizeof-expression) */ + #define WC_ALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + WC_DO_NOTHING + #define WC_CALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ + XMEMSET(VAR_NAME, 0, sizeof(VAR_NAME)) + #define WC_ARRAY_OK(VAR_NAME) 1 + #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) WC_DO_NOTHING \ + /* nothing to free, its stack */ +#endif - #define WC_DECLARE_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - VAR_TYPE* VAR_NAME[VAR_ITEMS] = { NULL, }; \ - int idx##VAR_NAME = 0, inner_idx_##VAR_NAME - #define WC_HEAP_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ - VAR_TYPE* VAR_NAME[VAR_ITEMS] - #define WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - for (idx##VAR_NAME=0; idx##VAR_NAME<(VAR_ITEMS); idx##VAR_NAME++) { \ - (VAR_NAME)[idx##VAR_NAME] = (VAR_TYPE*)XMALLOC(VAR_SIZE, (HEAP), DYNAMIC_TYPE_TMP_BUFFER); \ - if ((VAR_NAME)[idx##VAR_NAME] == NULL) { \ - for (inner_idx_##VAR_NAME = 0; inner_idx_##VAR_NAME < idx##VAR_NAME; inner_idx_##VAR_NAME++) { \ - XFREE((VAR_NAME)[inner_idx_##VAR_NAME], (HEAP), DYNAMIC_TYPE_TMP_BUFFER); \ - (VAR_NAME)[inner_idx_##VAR_NAME] = NULL; \ - } \ - for (inner_idx_##VAR_NAME = idx##VAR_NAME + 1; inner_idx_##VAR_NAME < (VAR_ITEMS); inner_idx_##VAR_NAME++) { \ - (VAR_NAME)[inner_idx_##VAR_NAME] = NULL; \ - } \ - idx##VAR_NAME = 0; \ - WC_ALLOC_DO_ON_FAILURE(); \ - break; \ - } \ - } - #define WC_CALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - do { \ - WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP); \ - if (idx##VAR_NAME != 0) { \ - for (idx##VAR_NAME=0; idx##VAR_NAME<(VAR_ITEMS); idx##VAR_NAME++) { \ - XMEMSET((VAR_NAME)[idx##VAR_NAME], 0, VAR_SIZE); \ - } \ - } \ - } while (0) - #define WC_HEAP_ARRAY_OK(VAR_NAME) (idx##VAR_NAME != 0) - #define WC_FREE_HEAP_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) \ - if (WC_HEAP_ARRAY_OK(VAR_NAME)) { \ - for (idx##VAR_NAME=0; idx##VAR_NAME<(VAR_ITEMS); idx##VAR_NAME++) { \ - XFREE((VAR_NAME)[idx##VAR_NAME], (HEAP), DYNAMIC_TYPE_TMP_BUFFER); \ - } \ - idx##VAR_NAME = 0; \ - } +#if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) + /* These are here for the FIPS code that can't be changed. + * New definitions don't need to be added here. */ + #define DECLARE_VAR WC_DECLARE_VAR + #define DECLARE_ARRAY WC_DECLARE_ARRAY + #define FREE_VAR WC_FREE_VAR + #define FREE_ARRAY WC_FREE_ARRAY + #define DECLARE_ARRAY_DYNAMIC_DEC WC_DECLARE_HEAP_ARRAY + #define DECLARE_ARRAY_DYNAMIC_EXE WC_ALLOC_HEAP_ARRAY + #define FREE_ARRAY_DYNAMIC WC_FREE_HEAP_ARRAY +#endif /* HAVE_FIPS */ + +#if !defined(USE_WOLF_STRTOK) && \ + ((defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) || \ + defined(WOLFSSL_TIRTOS) || defined(WOLF_C99)) + #define USE_WOLF_STRTOK +#endif +#if !defined(USE_WOLF_STRSEP) && (defined(WOLF_C89) || defined(WOLF_C99)) + #define USE_WOLF_STRSEP +#endif +#if !defined(XSTRLCPY) && !defined(USE_WOLF_STRLCPY) + #define USE_WOLF_STRLCPY +#endif +#if !defined(XSTRLCAT) && !defined(USE_WOLF_STRLCAT) + #define USE_WOLF_STRLCAT +#endif - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_SMALL_STACK) - #define WC_DECLARE_VAR_IS_HEAP_ALLOC - #define WC_DECLARE_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ - VAR_TYPE* VAR_NAME = NULL - #define WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ - do { \ - (VAR_NAME) = (VAR_TYPE*)XMALLOC(sizeof(VAR_TYPE) * (VAR_SIZE), (HEAP), DYNAMIC_TYPE_WOLF_BIGINT); \ - if ((VAR_NAME) == NULL) { \ - WC_ALLOC_DO_ON_FAILURE(); \ - } \ - } while (0) - #define WC_CALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ - do { \ - WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP); \ - XMEMSET(VAR_NAME, 0, sizeof(VAR_TYPE) * (VAR_SIZE)); \ - } while (0) - #define WC_FREE_VAR(VAR_NAME, HEAP) \ - XFREE(VAR_NAME, (HEAP), DYNAMIC_TYPE_WOLF_BIGINT) - #define WC_DECLARE_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - WC_DECLARE_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) - #define WC_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ - WC_HEAP_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) - #define WC_ALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - WC_ALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) - #define WC_CALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - WC_CALLOC_HEAP_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) - #define WC_ARRAY_OK(VAR_NAME) WC_HEAP_ARRAY_OK(VAR_NAME) - #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) \ - WC_FREE_HEAP_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) +#ifndef STRING_USER + #if defined(WOLFSSL_LINUXKM) + #include #else - #undef WC_DECLARE_VAR_IS_HEAP_ALLOC - #define WC_DECLARE_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ - VAR_TYPE VAR_NAME[VAR_SIZE] - #define WC_ALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) WC_DO_NOTHING - #define WC_CALLOC_VAR(VAR_NAME, VAR_TYPE, VAR_SIZE, HEAP) \ - XMEMSET(VAR_NAME, 0, sizeof(var)) - #define WC_FREE_VAR(VAR_NAME, HEAP) WC_DO_NOTHING /* nothing to free, its stack */ - #define WC_DECLARE_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) \ - VAR_TYPE VAR_NAME[VAR_ITEMS][(VAR_SIZE) / sizeof(VAR_TYPE)] /* // NOLINT(bugprone-sizeof-expression) */ - #define WC_ARRAY_ARG(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE) \ - VAR_TYPE VAR_NAME[VAR_ITEMS][(VAR_SIZE) / sizeof(VAR_TYPE)] /* // NOLINT(bugprone-sizeof-expression) */ - #define WC_ALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) WC_DO_NOTHING - #define WC_CALLOC_ARRAY(VAR_NAME, VAR_TYPE, VAR_ITEMS, VAR_SIZE, HEAP) XMEMSET(VAR_NAME, 0, sizeof(VAR_NAME)) - #define WC_ARRAY_OK(VAR_NAME) 1 - #define WC_FREE_ARRAY(VAR_NAME, VAR_ITEMS, HEAP) WC_DO_NOTHING /* nothing to free, its stack */ + #include #endif - #if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) - /* These are here for the FIPS code that can't be changed. New definitions don't need to be added here. */ - #define DECLARE_VAR WC_DECLARE_VAR - #define DECLARE_ARRAY WC_DECLARE_ARRAY - #define FREE_VAR WC_FREE_VAR - #define FREE_ARRAY WC_FREE_ARRAY - #define DECLARE_ARRAY_DYNAMIC_DEC WC_DECLARE_HEAP_ARRAY - #define DECLARE_ARRAY_DYNAMIC_EXE WC_ALLOC_HEAP_ARRAY - #define FREE_ARRAY_DYNAMIC WC_FREE_HEAP_ARRAY - #endif /* HAVE_FIPS */ - - #if !defined(USE_WOLF_STRTOK) && \ - ((defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) || \ - defined(WOLFSSL_TIRTOS) || defined(WOLF_C99)) - #define USE_WOLF_STRTOK - #endif - #if !defined(USE_WOLF_STRSEP) && (defined(WOLF_C89) || defined(WOLF_C99)) - #define USE_WOLF_STRSEP - #endif - #if !defined(XSTRLCPY) && !defined(USE_WOLF_STRLCPY) - #define USE_WOLF_STRLCPY - #endif - #if !defined(XSTRLCAT) && !defined(USE_WOLF_STRLCAT) - #define USE_WOLF_STRLCAT - #endif + #define XMEMCPY(d,s,l) memcpy((d),(s),(l)) + #define XMEMSET(b,c,l) memset((b),(c),(l)) + #define XMEMCMP(s1,s2,n) memcmp((s1),(s2),(n)) + #define XMEMMOVE(d,s,l) memmove((d),(s),(l)) - #ifndef STRING_USER - #if defined(WOLFSSL_LINUXKM) - #include - #else - #include - #endif + #define XSTRLEN(s1) strlen((s1)) + #define XSTRNCPY(s1,s2,n) strncpy((s1),(s2),(n)) + /* strstr, strncmp, strcmp, and strncat only used by wolfSSL proper, + * not required for wolfCrypt only */ + #define XSTRSTR(s1,s2) strstr((s1),(s2)) + #define XSTRNSTR(s1,s2,n) mystrnstr((s1),(s2),(n)) + #define XSTRNCMP(s1,s2,n) strncmp((s1),(s2),(n)) + #define XSTRCMP(s1,s2) strcmp((s1),(s2)) + #define XSTRNCAT(s1,s2,n) strncat((s1),(s2),(n)) - #define XMEMCPY(d,s,l) memcpy((d),(s),(l)) - #define XMEMSET(b,c,l) memset((b),(c),(l)) - #define XMEMCMP(s1,s2,n) memcmp((s1),(s2),(n)) - #define XMEMMOVE(d,s,l) memmove((d),(s),(l)) - - #define XSTRLEN(s1) strlen((s1)) - #define XSTRNCPY(s1,s2,n) strncpy((s1),(s2),(n)) - /* strstr, strncmp, strcmp, and strncat only used by wolfSSL proper, - * not required for wolfCrypt only */ - #define XSTRSTR(s1,s2) strstr((s1),(s2)) - #define XSTRNSTR(s1,s2,n) mystrnstr((s1),(s2),(n)) - #define XSTRNCMP(s1,s2,n) strncmp((s1),(s2),(n)) - #define XSTRCMP(s1,s2) strcmp((s1),(s2)) - #define XSTRNCAT(s1,s2,n) strncat((s1),(s2),(n)) - - #ifdef USE_WOLF_STRSEP - #define XSTRSEP(s1,d) wc_strsep((s1),(d)) - #else - #define XSTRSEP(s1,d) strsep((s1),(d)) - #endif + #ifdef USE_WOLF_STRSEP + #define XSTRSEP(s1,d) wc_strsep((s1),(d)) + #else + #define XSTRSEP(s1,d) strsep((s1),(d)) + #endif - #ifndef XSTRCASECMP + #ifndef XSTRCASECMP #if (defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32)) && \ (__XC32_VERSION >= 1000) && (__XC32_VERSION < 4000) /* XC32 supports str[n]casecmp in version >= 1.0 through 4.0. */ @@ -799,9 +845,9 @@ typedef struct w64wrapper { #undef XSTRCASECMP #define XSTRCASECMP(s1,s2) wc_strcasecmp((s1), (s2)) #endif - #endif /* !XSTRCASECMP */ + #endif /* !XSTRCASECMP */ - #ifndef XSTRNCASECMP + #ifndef XSTRNCASECMP #if (defined(MICROCHIP_MPLAB_HARMONY) || defined(MICROCHIP_PIC32)) && \ (__XC32_VERSION >= 1000) /* XC32 supports str[n]casecmp in version >= 1.0. */ @@ -833,39 +879,39 @@ typedef struct w64wrapper { #undef XSTRNCASECMP #define XSTRNCASECMP(s1,s2,n) wc_strncasecmp((s1),(s2),(n)) #endif - #endif /* !XSTRNCASECMP */ + #endif /* !XSTRNCASECMP */ - /* snprintf is used in asn.c for GetTimeString, PKCS7 test, and when - debugging is turned on */ - #ifndef XSNPRINTF + /* snprintf is used in asn.c for GetTimeString, PKCS7 test, and when + * debugging is turned on */ + #ifndef XSNPRINTF #ifndef USE_WINDOWS_API #if defined(WOLFSSL_ESPIDF) && \ (!defined(NO_ASN_TIME) && defined(HAVE_PKCS7)) - #include - /* later gcc than 7.1 introduces -Wformat-truncation */ - /* In cases when truncation is expected the caller needs*/ - /* to check the return value from the function so that */ - /* compiler doesn't complain. */ - /* xtensa-esp32-elf v8.2.0 warns truncation at */ - /* GetAsnTimeString() */ - static WC_INLINE - int _xsnprintf_(char *s, size_t n, const char *format, ...) - { - va_list ap; - int ret; - - if ((int)n <= 0) return -1; - - va_start(ap, format); - - ret = XVSNPRINTF(s, n, format, ap); - if (ret < 0) - ret = -1; - - va_end(ap); - - return ret; - } + #include + /* later gcc than 7.1 introduces -Wformat-truncation */ + /* In cases when truncation is expected the caller needs*/ + /* to check the return value from the function so that */ + /* compiler doesn't complain. */ + /* xtensa-esp32-elf v8.2.0 warns truncation at */ + /* GetAsnTimeString() */ + static WC_INLINE + int _xsnprintf_(char *s, size_t n, const char *format, ...) + { + va_list ap; + int ret; + + if ((int)n <= 0) return -1; + + va_start(ap, format); + + ret = XVSNPRINTF(s, n, format, ap); + if (ret < 0) + ret = -1; + + va_end(ap); + + return ret; + } #define XSNPRINTF _xsnprintf_ #elif defined(FREESCALE_MQX) /* see wc_port.h for fio.h and nio.h includes. MQX does not @@ -878,7 +924,8 @@ typedef struct w64wrapper { #define XSPRINTF sprintf /* snprintf not available for C89, so remap using macro */ #ifdef WOLF_NO_VARIADIC_MACROS - #error WOLF_NO_VARIADIC_MACROS requires user-supplied binding for XSNPRINTF + #error WOLF_NO_VARIADIC_MACROS requires user-supplied \ +binding for XSNPRINTF #else #define XSNPRINTF(f, len, ...) sprintf(f, __VA_ARGS__) #endif @@ -924,408 +971,408 @@ typedef struct w64wrapper { #define XSNPRINTF snprintf #endif /* _MSC_VER */ #endif /* USE_WINDOWS_API */ - #endif /* !XSNPRINTF */ - - #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \ - defined(HAVE_ALPN) || defined(WOLFSSL_SNIFFER) || \ - defined(WOLFSSL_ASN_PARSE_KEYUSAGE) - /* use only Thread Safe version of strtok */ - #if defined(USE_WOLF_STRTOK) + #endif /* !XSNPRINTF */ + + #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \ + defined(HAVE_ALPN) || defined(WOLFSSL_SNIFFER) || \ + defined(WOLFSSL_ASN_PARSE_KEYUSAGE) + /* use only Thread Safe version of strtok */ + #if defined(USE_WOLF_STRTOK) + #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) + #elif defined(__WATCOMC__) + #if __WATCOMC__ < 1300 + #define USE_WOLF_STRTOK #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) - #elif defined(__WATCOMC__) - #if __WATCOMC__ < 1300 - #define USE_WOLF_STRTOK - #define XSTRTOK(s1,d,ptr) wc_strtok((s1),(d),(ptr)) - #else - #define XSTRTOK(s1,d,ptr) strtok_r((s1),(d),(ptr)) - #endif - #elif defined(USE_WINDOWS_API) || defined(INTIME_RTOS) - #define XSTRTOK(s1,d,ptr) strtok_s((s1),(d),(ptr)) #else #define XSTRTOK(s1,d,ptr) strtok_r((s1),(d),(ptr)) #endif + #elif defined(USE_WINDOWS_API) || defined(INTIME_RTOS) + #define XSTRTOK(s1,d,ptr) strtok_s((s1),(d),(ptr)) + #else + #define XSTRTOK(s1,d,ptr) strtok_r((s1),(d),(ptr)) #endif + #endif - #if defined(WOLFSSL_CERT_EXT) || defined(HAVE_OCSP) || \ - defined(HAVE_CRL_IO) || defined(HAVE_HTTP_CLIENT) || \ - !defined(NO_CRYPT_BENCHMARK) || defined(OPENSSL_EXTRA) + #if defined(WOLFSSL_CERT_EXT) || defined(HAVE_OCSP) || \ + defined(HAVE_CRL_IO) || defined(HAVE_HTTP_CLIENT) || \ + !defined(NO_CRYPT_BENCHMARK) || defined(OPENSSL_EXTRA) - #ifndef XATOI /* if custom XATOI is not already defined */ - #include - #define XATOI(s) atoi((s)) - #endif + #ifndef XATOI /* if custom XATOI is not already defined */ + #include + #define XATOI(s) atoi((s)) #endif #endif +#endif /* STRING_USER */ - #ifdef USE_WOLF_STRTOK - WOLFSSL_API char* wc_strtok(char *str, const char *delim, char **nextp); - #endif - #ifdef USE_WOLF_STRSEP - WOLFSSL_API char* wc_strsep(char **stringp, const char *delim); - #endif - - #ifdef USE_WOLF_STRLCPY - WOLFSSL_API size_t wc_strlcpy(char *dst, const char *src, size_t dstSize); - #define XSTRLCPY(s1,s2,n) wc_strlcpy((s1),(s2),(n)) - #endif - #ifdef USE_WOLF_STRLCAT - WOLFSSL_API size_t wc_strlcat(char *dst, const char *src, size_t dstSize); - #define XSTRLCAT(s1,s2,n) wc_strlcat((s1),(s2),(n)) - #endif - #ifdef USE_WOLF_STRCASECMP - WOLFSSL_API int wc_strcasecmp(const char *s1, const char *s2); - #endif - #ifdef USE_WOLF_STRNCASECMP - WOLFSSL_API int wc_strncasecmp(const char *s1, const char *s2, size_t n); - #endif +#ifdef USE_WOLF_STRTOK + WOLFSSL_API char* wc_strtok(char *str, const char *delim, char **nextp); +#endif +#ifdef USE_WOLF_STRSEP + WOLFSSL_API char* wc_strsep(char **stringp, const char *delim); +#endif - #if !defined(XSTRDUP) && !defined(USE_WOLF_STRDUP) - #define USE_WOLF_STRDUP - #endif - #ifdef USE_WOLF_STRDUP - WOLFSSL_LOCAL char* wc_strdup_ex(const char *src, int memType); - #define wc_strdup(src) wc_strdup_ex(src, DYNAMIC_TYPE_TMP_BUFFER) - #define XSTRDUP(src) wc_strdup(src) - #endif +#ifdef USE_WOLF_STRLCPY + WOLFSSL_API size_t wc_strlcpy(char *dst, const char *src, size_t dstSize); + #define XSTRLCPY(s1,s2,n) wc_strlcpy((s1),(s2),(n)) +#endif +#ifdef USE_WOLF_STRLCAT + WOLFSSL_API size_t wc_strlcat(char *dst, const char *src, size_t dstSize); + #define XSTRLCAT(s1,s2,n) wc_strlcat((s1),(s2),(n)) +#endif +#ifdef USE_WOLF_STRCASECMP + WOLFSSL_API int wc_strcasecmp(const char *s1, const char *s2); +#endif +#ifdef USE_WOLF_STRNCASECMP + WOLFSSL_API int wc_strncasecmp(const char *s1, const char *s2, size_t n); +#endif - #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) - #ifndef XGETENV - #ifdef NO_GETENV - #define XGETENV(x) (NULL) - #else - #include - #define XGETENV getenv - #endif - #endif - #endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */ +#if !defined(XSTRDUP) && !defined(USE_WOLF_STRDUP) + #define USE_WOLF_STRDUP +#endif +#ifdef USE_WOLF_STRDUP + WOLFSSL_LOCAL char* wc_strdup_ex(const char *src, int memType); + #define wc_strdup(src) wc_strdup_ex(src, DYNAMIC_TYPE_TMP_BUFFER) + #define XSTRDUP(src) wc_strdup(src) +#endif - #ifndef CTYPE_USER - #ifndef WOLFSSL_LINUXKM - #include - #endif - #if defined(HAVE_ECC) || defined(HAVE_OCSP) || \ - defined(WOLFSSL_KEY_GEN) || !defined(NO_DSA) || \ - defined(OPENSSL_EXTRA) - #define XTOUPPER(c) toupper((c)) - #endif - #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) - #define XISALNUM(c) isalnum((c)) - #if !defined(HAVE_ISASCII) || defined(NO_STDLIB_ISASCII) - #define XISASCII(c) (((c) >= 0 && (c) <= 127) ? 1 : 0) +#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) + #ifndef XGETENV + #ifdef NO_GETENV + #define XGETENV(x) (NULL) #else - #define XISASCII(c) isascii((c)) - #endif - #define XISSPACE(c) isspace((c)) + #include + #define XGETENV getenv #endif - /* needed by wolfSSL_check_domain_name() */ - #define XTOLOWER(c) tolower((c)) #endif +#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */ - #ifndef WC_OFFSETOF - #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 4)) - #define WC_OFFSETOF(type, field) __builtin_offsetof(type, field) - #elif defined(__WATCOMC__) - #include - #define WC_OFFSETOF offsetof - #else - #define WC_OFFSETOF(type, field) ((size_t)&(((type *)0)->field)) - #endif +#ifndef CTYPE_USER + #ifndef WOLFSSL_LINUXKM + #include #endif - - - /* memory allocation types for user hints */ - enum { - DYNAMIC_TYPE_CA = 1, - DYNAMIC_TYPE_CERT = 2, - DYNAMIC_TYPE_KEY = 3, - DYNAMIC_TYPE_FILE = 4, - DYNAMIC_TYPE_SUBJECT_CN = 5, - DYNAMIC_TYPE_PUBLIC_KEY = 6, - DYNAMIC_TYPE_SIGNER = 7, - DYNAMIC_TYPE_NONE = 8, - DYNAMIC_TYPE_BIGINT = 9, - DYNAMIC_TYPE_RSA = 10, - DYNAMIC_TYPE_METHOD = 11, - DYNAMIC_TYPE_OUT_BUFFER = 12, - DYNAMIC_TYPE_IN_BUFFER = 13, - DYNAMIC_TYPE_INFO = 14, - DYNAMIC_TYPE_DH = 15, - DYNAMIC_TYPE_DOMAIN = 16, - DYNAMIC_TYPE_SSL = 17, - DYNAMIC_TYPE_CTX = 18, - DYNAMIC_TYPE_WRITEV = 19, - DYNAMIC_TYPE_OPENSSL = 20, - DYNAMIC_TYPE_DSA = 21, - DYNAMIC_TYPE_CRL = 22, - DYNAMIC_TYPE_REVOKED = 23, - DYNAMIC_TYPE_CRL_ENTRY = 24, - DYNAMIC_TYPE_CERT_MANAGER = 25, - DYNAMIC_TYPE_CRL_MONITOR = 26, - DYNAMIC_TYPE_OCSP_STATUS = 27, - DYNAMIC_TYPE_OCSP_ENTRY = 28, - DYNAMIC_TYPE_ALTNAME = 29, - DYNAMIC_TYPE_SUITES = 30, - DYNAMIC_TYPE_CIPHER = 31, - DYNAMIC_TYPE_RNG = 32, - DYNAMIC_TYPE_ARRAYS = 33, - DYNAMIC_TYPE_DTLS_POOL = 34, - DYNAMIC_TYPE_SOCKADDR = 35, - DYNAMIC_TYPE_LIBZ = 36, - DYNAMIC_TYPE_ECC = 37, - DYNAMIC_TYPE_TMP_BUFFER = 38, - DYNAMIC_TYPE_DTLS_MSG = 39, - DYNAMIC_TYPE_X509 = 40, - DYNAMIC_TYPE_TLSX = 41, - DYNAMIC_TYPE_OCSP = 42, - DYNAMIC_TYPE_SIGNATURE = 43, - DYNAMIC_TYPE_HASHES = 44, - DYNAMIC_TYPE_SRP = 45, - DYNAMIC_TYPE_COOKIE_PWD = 46, - DYNAMIC_TYPE_USER_CRYPTO = 47, - DYNAMIC_TYPE_OCSP_REQUEST = 48, - DYNAMIC_TYPE_X509_EXT = 49, - DYNAMIC_TYPE_X509_STORE = 50, - DYNAMIC_TYPE_X509_CTX = 51, - DYNAMIC_TYPE_URL = 52, - DYNAMIC_TYPE_DTLS_FRAG = 53, - DYNAMIC_TYPE_DTLS_BUFFER = 54, - DYNAMIC_TYPE_SESSION_TICK = 55, - DYNAMIC_TYPE_PKCS = 56, - DYNAMIC_TYPE_MUTEX = 57, - DYNAMIC_TYPE_PKCS7 = 58, - DYNAMIC_TYPE_AES_BUFFER = 59, - DYNAMIC_TYPE_WOLF_BIGINT = 60, - DYNAMIC_TYPE_ASN1 = 61, - DYNAMIC_TYPE_LOG = 62, - DYNAMIC_TYPE_WRITEDUP = 63, - DYNAMIC_TYPE_PRIVATE_KEY = 64, - DYNAMIC_TYPE_HMAC = 65, - DYNAMIC_TYPE_ASYNC = 66, - DYNAMIC_TYPE_ASYNC_NUMA = 67, - DYNAMIC_TYPE_ASYNC_NUMA64 = 68, - DYNAMIC_TYPE_CURVE25519 = 69, - DYNAMIC_TYPE_ED25519 = 70, - DYNAMIC_TYPE_SECRET = 71, - DYNAMIC_TYPE_DIGEST = 72, - DYNAMIC_TYPE_RSA_BUFFER = 73, - DYNAMIC_TYPE_DCERT = 74, - DYNAMIC_TYPE_STRING = 75, - DYNAMIC_TYPE_PEM = 76, - DYNAMIC_TYPE_DER = 77, - DYNAMIC_TYPE_CERT_EXT = 78, - DYNAMIC_TYPE_ALPN = 79, - DYNAMIC_TYPE_ENCRYPTEDINFO= 80, - DYNAMIC_TYPE_DIRCTX = 81, - DYNAMIC_TYPE_HASHCTX = 82, - DYNAMIC_TYPE_SEED = 83, - DYNAMIC_TYPE_SYMMETRIC_KEY= 84, - DYNAMIC_TYPE_ECC_BUFFER = 85, - DYNAMIC_TYPE_SALT = 87, - DYNAMIC_TYPE_HASH_TMP = 88, - DYNAMIC_TYPE_BLOB = 89, - DYNAMIC_TYPE_NAME_ENTRY = 90, - DYNAMIC_TYPE_CURVE448 = 91, - DYNAMIC_TYPE_ED448 = 92, - DYNAMIC_TYPE_AES = 93, - DYNAMIC_TYPE_CMAC = 94, - DYNAMIC_TYPE_FALCON = 95, - DYNAMIC_TYPE_SESSION = 96, - DYNAMIC_TYPE_DILITHIUM = 97, - DYNAMIC_TYPE_SPHINCS = 98, - DYNAMIC_TYPE_SM4_BUFFER = 99, - DYNAMIC_TYPE_DEBUG_TAG = 100, - DYNAMIC_TYPE_LMS = 101, - DYNAMIC_TYPE_BIO = 102, - DYNAMIC_TYPE_X509_ACERT = 103, - DYNAMIC_TYPE_OS_BUF = 104, - DYNAMIC_TYPE_ASCON = 105, - DYNAMIC_TYPE_SNIFFER_SERVER = 1000, - DYNAMIC_TYPE_SNIFFER_SESSION = 1001, - DYNAMIC_TYPE_SNIFFER_PB = 1002, - DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, - DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, - DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, - DYNAMIC_TYPE_SNIFFER_KEY = 1006, - DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE = 1007, - DYNAMIC_TYPE_SNIFFER_CHAIN_BUFFER = 1008, - DYNAMIC_TYPE_AES_EAX = 1009 - }; - - /* max error buffer string size */ - #ifndef WOLFSSL_MAX_ERROR_SZ - #define WOLFSSL_MAX_ERROR_SZ 80 + #if defined(HAVE_ECC) || defined(HAVE_OCSP) || \ + defined(WOLFSSL_KEY_GEN) || !defined(NO_DSA) || \ + defined(OPENSSL_EXTRA) + #define XTOUPPER(c) toupper((c)) #endif + #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) + #define XISALNUM(c) isalnum((c)) + #if !defined(HAVE_ISASCII) || defined(NO_STDLIB_ISASCII) + #define XISASCII(c) (((c) >= 0 && (c) <= 127) ? 1 : 0) + #else + #define XISASCII(c) isascii((c)) + #endif + #define XISSPACE(c) isspace((c)) + #endif + /* needed by wolfSSL_check_domain_name() */ + #define XTOLOWER(c) tolower((c)) +#endif - /* stack protection */ - enum { - MIN_STACK_BUFFER = 8 - }; - +#ifndef WC_OFFSETOF + #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 4)) + #define WC_OFFSETOF(type, field) __builtin_offsetof(type, field) + #elif defined(__WATCOMC__) + #include + #define WC_OFFSETOF offsetof + #else + #define WC_OFFSETOF(type, field) ((size_t)&(((type *)0)->field)) + #endif +#endif - /* Algorithm Types */ - enum wc_AlgoType { - WC_ALGO_TYPE_NONE = 0, - WC_ALGO_TYPE_HASH = 1, - WC_ALGO_TYPE_CIPHER = 2, - WC_ALGO_TYPE_PK = 3, - WC_ALGO_TYPE_RNG = 4, - WC_ALGO_TYPE_SEED = 5, - WC_ALGO_TYPE_HMAC = 6, - WC_ALGO_TYPE_CMAC = 7, - WC_ALGO_TYPE_CERT = 8, - WC_ALGO_TYPE_MAX = WC_ALGO_TYPE_CERT - }; +/* memory allocation types for user hints */ +enum { + DYNAMIC_TYPE_CA = 1, + DYNAMIC_TYPE_CERT = 2, + DYNAMIC_TYPE_KEY = 3, + DYNAMIC_TYPE_FILE = 4, + DYNAMIC_TYPE_SUBJECT_CN = 5, + DYNAMIC_TYPE_PUBLIC_KEY = 6, + DYNAMIC_TYPE_SIGNER = 7, + DYNAMIC_TYPE_NONE = 8, + DYNAMIC_TYPE_BIGINT = 9, + DYNAMIC_TYPE_RSA = 10, + DYNAMIC_TYPE_METHOD = 11, + DYNAMIC_TYPE_OUT_BUFFER = 12, + DYNAMIC_TYPE_IN_BUFFER = 13, + DYNAMIC_TYPE_INFO = 14, + DYNAMIC_TYPE_DH = 15, + DYNAMIC_TYPE_DOMAIN = 16, + DYNAMIC_TYPE_SSL = 17, + DYNAMIC_TYPE_CTX = 18, + DYNAMIC_TYPE_WRITEV = 19, + DYNAMIC_TYPE_OPENSSL = 20, + DYNAMIC_TYPE_DSA = 21, + DYNAMIC_TYPE_CRL = 22, + DYNAMIC_TYPE_REVOKED = 23, + DYNAMIC_TYPE_CRL_ENTRY = 24, + DYNAMIC_TYPE_CERT_MANAGER = 25, + DYNAMIC_TYPE_CRL_MONITOR = 26, + DYNAMIC_TYPE_OCSP_STATUS = 27, + DYNAMIC_TYPE_OCSP_ENTRY = 28, + DYNAMIC_TYPE_ALTNAME = 29, + DYNAMIC_TYPE_SUITES = 30, + DYNAMIC_TYPE_CIPHER = 31, + DYNAMIC_TYPE_RNG = 32, + DYNAMIC_TYPE_ARRAYS = 33, + DYNAMIC_TYPE_DTLS_POOL = 34, + DYNAMIC_TYPE_SOCKADDR = 35, + DYNAMIC_TYPE_LIBZ = 36, + DYNAMIC_TYPE_ECC = 37, + DYNAMIC_TYPE_TMP_BUFFER = 38, + DYNAMIC_TYPE_DTLS_MSG = 39, + DYNAMIC_TYPE_X509 = 40, + DYNAMIC_TYPE_TLSX = 41, + DYNAMIC_TYPE_OCSP = 42, + DYNAMIC_TYPE_SIGNATURE = 43, + DYNAMIC_TYPE_HASHES = 44, + DYNAMIC_TYPE_SRP = 45, + DYNAMIC_TYPE_COOKIE_PWD = 46, + DYNAMIC_TYPE_USER_CRYPTO = 47, + DYNAMIC_TYPE_OCSP_REQUEST = 48, + DYNAMIC_TYPE_X509_EXT = 49, + DYNAMIC_TYPE_X509_STORE = 50, + DYNAMIC_TYPE_X509_CTX = 51, + DYNAMIC_TYPE_URL = 52, + DYNAMIC_TYPE_DTLS_FRAG = 53, + DYNAMIC_TYPE_DTLS_BUFFER = 54, + DYNAMIC_TYPE_SESSION_TICK = 55, + DYNAMIC_TYPE_PKCS = 56, + DYNAMIC_TYPE_MUTEX = 57, + DYNAMIC_TYPE_PKCS7 = 58, + DYNAMIC_TYPE_AES_BUFFER = 59, + DYNAMIC_TYPE_WOLF_BIGINT = 60, + DYNAMIC_TYPE_ASN1 = 61, + DYNAMIC_TYPE_LOG = 62, + DYNAMIC_TYPE_WRITEDUP = 63, + DYNAMIC_TYPE_PRIVATE_KEY = 64, + DYNAMIC_TYPE_HMAC = 65, + DYNAMIC_TYPE_ASYNC = 66, + DYNAMIC_TYPE_ASYNC_NUMA = 67, + DYNAMIC_TYPE_ASYNC_NUMA64 = 68, + DYNAMIC_TYPE_CURVE25519 = 69, + DYNAMIC_TYPE_ED25519 = 70, + DYNAMIC_TYPE_SECRET = 71, + DYNAMIC_TYPE_DIGEST = 72, + DYNAMIC_TYPE_RSA_BUFFER = 73, + DYNAMIC_TYPE_DCERT = 74, + DYNAMIC_TYPE_STRING = 75, + DYNAMIC_TYPE_PEM = 76, + DYNAMIC_TYPE_DER = 77, + DYNAMIC_TYPE_CERT_EXT = 78, + DYNAMIC_TYPE_ALPN = 79, + DYNAMIC_TYPE_ENCRYPTEDINFO= 80, + DYNAMIC_TYPE_DIRCTX = 81, + DYNAMIC_TYPE_HASHCTX = 82, + DYNAMIC_TYPE_SEED = 83, + DYNAMIC_TYPE_SYMMETRIC_KEY= 84, + DYNAMIC_TYPE_ECC_BUFFER = 85, + DYNAMIC_TYPE_SALT = 87, + DYNAMIC_TYPE_HASH_TMP = 88, + DYNAMIC_TYPE_BLOB = 89, + DYNAMIC_TYPE_NAME_ENTRY = 90, + DYNAMIC_TYPE_CURVE448 = 91, + DYNAMIC_TYPE_ED448 = 92, + DYNAMIC_TYPE_AES = 93, + DYNAMIC_TYPE_CMAC = 94, + DYNAMIC_TYPE_FALCON = 95, + DYNAMIC_TYPE_SESSION = 96, + DYNAMIC_TYPE_DILITHIUM = 97, + DYNAMIC_TYPE_SPHINCS = 98, + DYNAMIC_TYPE_SM4_BUFFER = 99, + DYNAMIC_TYPE_DEBUG_TAG = 100, + DYNAMIC_TYPE_LMS = 101, + DYNAMIC_TYPE_BIO = 102, + DYNAMIC_TYPE_X509_ACERT = 103, + DYNAMIC_TYPE_OS_BUF = 104, + DYNAMIC_TYPE_ASCON = 105, + DYNAMIC_TYPE_SNIFFER_SERVER = 1000, + DYNAMIC_TYPE_SNIFFER_SESSION = 1001, + DYNAMIC_TYPE_SNIFFER_PB = 1002, + DYNAMIC_TYPE_SNIFFER_PB_BUFFER = 1003, + DYNAMIC_TYPE_SNIFFER_TICKET_ID = 1004, + DYNAMIC_TYPE_SNIFFER_NAMED_KEY = 1005, + DYNAMIC_TYPE_SNIFFER_KEY = 1006, + DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE = 1007, + DYNAMIC_TYPE_SNIFFER_CHAIN_BUFFER = 1008, + DYNAMIC_TYPE_AES_EAX = 1009 +}; + +/* max error buffer string size */ +#ifndef WOLFSSL_MAX_ERROR_SZ + #define WOLFSSL_MAX_ERROR_SZ 80 +#endif - /* hash types */ - enum wc_HashType { - #if defined(HAVE_SELFTEST) || (defined(HAVE_FIPS) && \ - ((! defined(HAVE_FIPS_VERSION)) || \ - defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION <= 2))) - /* In selftest build, WC_* types are not mapped to WC_HASH_TYPE types. - * Values here are based on old selftest hmac.h enum, with additions. - * These values are fixed for backwards FIPS compatibility */ - WC_HASH_TYPE_NONE = 15, - WC_HASH_TYPE_MD2 = 16, - WC_HASH_TYPE_MD4 = 17, - WC_HASH_TYPE_MD5 = 0, - WC_HASH_TYPE_SHA = 1, /* SHA-1 (not old SHA-0) */ - WC_HASH_TYPE_SHA224 = 8, - WC_HASH_TYPE_SHA256 = 2, - WC_HASH_TYPE_SHA384 = 5, - WC_HASH_TYPE_SHA512 = 4, - WC_HASH_TYPE_MD5_SHA = 18, - WC_HASH_TYPE_SHA3_224 = 10, - WC_HASH_TYPE_SHA3_256 = 11, - WC_HASH_TYPE_SHA3_384 = 12, - WC_HASH_TYPE_SHA3_512 = 13, - WC_HASH_TYPE_BLAKE2B = 14, - WC_HASH_TYPE_BLAKE2S = 19, - WC_HASH_TYPE_MAX = WC_HASH_TYPE_BLAKE2S, - #ifndef WOLFSSL_NOSHA512_224 - #define WOLFSSL_NOSHA512_224 - #endif - #ifndef WOLFSSL_NOSHA512_256 - #define WOLFSSL_NOSHA512_256 - #endif - #else - WC_HASH_TYPE_NONE = 0, - WC_HASH_TYPE_MD2 = 1, - WC_HASH_TYPE_MD4 = 2, - WC_HASH_TYPE_MD5 = 3, - WC_HASH_TYPE_SHA = 4, /* SHA-1 (not old SHA-0) */ - WC_HASH_TYPE_SHA224 = 5, - WC_HASH_TYPE_SHA256 = 6, - WC_HASH_TYPE_SHA384 = 7, - WC_HASH_TYPE_SHA512 = 8, - WC_HASH_TYPE_MD5_SHA = 9, - WC_HASH_TYPE_SHA3_224 = 10, - WC_HASH_TYPE_SHA3_256 = 11, - WC_HASH_TYPE_SHA3_384 = 12, - WC_HASH_TYPE_SHA3_512 = 13, - WC_HASH_TYPE_BLAKE2B = 14, - WC_HASH_TYPE_BLAKE2S = 15, - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_BLAKE2S - #ifndef WOLFSSL_NOSHA512_224 - WC_HASH_TYPE_SHA512_224 = 16, - #undef _WC_HASH_TYPE_MAX - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHA512_224 - #endif - #ifndef WOLFSSL_NOSHA512_256 - WC_HASH_TYPE_SHA512_256 = 17, - #undef _WC_HASH_TYPE_MAX - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHA512_256 - #endif - #ifdef WOLFSSL_SHAKE128 - WC_HASH_TYPE_SHAKE128 = 18, - #undef _WC_HASH_TYPE_MAX - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHAKE128 - #endif - #ifdef WOLFSSL_SHAKE256 - WC_HASH_TYPE_SHAKE256 = 19, - #undef _WC_HASH_TYPE_MAX - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHAKE256 - #endif - #ifdef WOLFSSL_SM3 - WC_HASH_TYPE_SM3 = 20, - #undef _WC_HASH_TYPE_MAX - #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SM3 - #endif - WC_HASH_TYPE_MAX = _WC_HASH_TYPE_MAX +/* stack protection */ +enum { + MIN_STACK_BUFFER = 8 +}; + + +/* Algorithm Types */ +enum wc_AlgoType { + WC_ALGO_TYPE_NONE = 0, + WC_ALGO_TYPE_HASH = 1, + WC_ALGO_TYPE_CIPHER = 2, + WC_ALGO_TYPE_PK = 3, + WC_ALGO_TYPE_RNG = 4, + WC_ALGO_TYPE_SEED = 5, + WC_ALGO_TYPE_HMAC = 6, + WC_ALGO_TYPE_CMAC = 7, + WC_ALGO_TYPE_CERT = 8, + + WC_ALGO_TYPE_MAX = WC_ALGO_TYPE_CERT +}; + +/* hash types */ +enum wc_HashType { +#if defined(HAVE_SELFTEST) || (defined(HAVE_FIPS) && \ + ((! defined(HAVE_FIPS_VERSION)) || \ + defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION <= 2))) + /* In selftest build, WC_* types are not mapped to WC_HASH_TYPE types. + * Values here are based on old selftest hmac.h enum, with additions. + * These values are fixed for backwards FIPS compatibility */ + WC_HASH_TYPE_NONE = 15, + WC_HASH_TYPE_MD2 = 16, + WC_HASH_TYPE_MD4 = 17, + WC_HASH_TYPE_MD5 = 0, + WC_HASH_TYPE_SHA = 1, /* SHA-1 (not old SHA-0) */ + WC_HASH_TYPE_SHA224 = 8, + WC_HASH_TYPE_SHA256 = 2, + WC_HASH_TYPE_SHA384 = 5, + WC_HASH_TYPE_SHA512 = 4, + WC_HASH_TYPE_MD5_SHA = 18, + WC_HASH_TYPE_SHA3_224 = 10, + WC_HASH_TYPE_SHA3_256 = 11, + WC_HASH_TYPE_SHA3_384 = 12, + WC_HASH_TYPE_SHA3_512 = 13, + WC_HASH_TYPE_BLAKE2B = 14, + WC_HASH_TYPE_BLAKE2S = 19, + WC_HASH_TYPE_MAX = WC_HASH_TYPE_BLAKE2S, + #ifndef WOLFSSL_NOSHA512_224 + #define WOLFSSL_NOSHA512_224 + #endif + #ifndef WOLFSSL_NOSHA512_256 + #define WOLFSSL_NOSHA512_256 + #endif +#else + WC_HASH_TYPE_NONE = 0, + WC_HASH_TYPE_MD2 = 1, + WC_HASH_TYPE_MD4 = 2, + WC_HASH_TYPE_MD5 = 3, + WC_HASH_TYPE_SHA = 4, /* SHA-1 (not old SHA-0) */ + WC_HASH_TYPE_SHA224 = 5, + WC_HASH_TYPE_SHA256 = 6, + WC_HASH_TYPE_SHA384 = 7, + WC_HASH_TYPE_SHA512 = 8, + WC_HASH_TYPE_MD5_SHA = 9, + WC_HASH_TYPE_SHA3_224 = 10, + WC_HASH_TYPE_SHA3_256 = 11, + WC_HASH_TYPE_SHA3_384 = 12, + WC_HASH_TYPE_SHA3_512 = 13, + WC_HASH_TYPE_BLAKE2B = 14, + WC_HASH_TYPE_BLAKE2S = 15, + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_BLAKE2S + #ifndef WOLFSSL_NOSHA512_224 + WC_HASH_TYPE_SHA512_224 = 16, #undef _WC_HASH_TYPE_MAX - - #endif /* HAVE_SELFTEST */ - }; - - enum wc_HashFlags { - WC_HASH_FLAG_NONE = 0x00000000, - WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ - WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ - #ifdef WOLFSSL_SHA3 - WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHA512_224 #endif - WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) - }; - - /* cipher types */ - enum wc_CipherType { - WC_CIPHER_NONE = 0, - WC_CIPHER_AES = 1, - WC_CIPHER_AES_CBC = 2, - WC_CIPHER_AES_GCM = 3, - WC_CIPHER_AES_CTR = 4, - WC_CIPHER_AES_XTS = 5, - WC_CIPHER_AES_CFB = 6, - WC_CIPHER_AES_CCM = 12, - WC_CIPHER_AES_ECB = 13, - WC_CIPHER_DES3 = 7, - WC_CIPHER_DES = 8, - WC_CIPHER_CHACHA = 9, - - WC_CIPHER_MAX = WC_CIPHER_AES_CCM - }; - - /* PK=public key (asymmetric) based algorithms */ - enum wc_PkType { - WC_PK_TYPE_NONE = 0, - WC_PK_TYPE_RSA = 1, - WC_PK_TYPE_DH = 2, - WC_PK_TYPE_ECDH = 3, - WC_PK_TYPE_ECDSA_SIGN = 4, - WC_PK_TYPE_ECDSA_VERIFY = 5, - WC_PK_TYPE_ED25519_SIGN = 6, - WC_PK_TYPE_CURVE25519 = 7, - WC_PK_TYPE_RSA_KEYGEN = 8, - WC_PK_TYPE_EC_KEYGEN = 9, - WC_PK_TYPE_RSA_CHECK_PRIV_KEY = 10, - WC_PK_TYPE_EC_CHECK_PRIV_KEY = 11, - WC_PK_TYPE_ED448 = 12, - WC_PK_TYPE_CURVE448 = 13, - WC_PK_TYPE_ED25519_VERIFY = 14, - WC_PK_TYPE_ED25519_KEYGEN = 15, - WC_PK_TYPE_CURVE25519_KEYGEN = 16, - WC_PK_TYPE_RSA_GET_SIZE = 17, - #define _WC_PK_TYPE_MAX WC_PK_TYPE_RSA_GET_SIZE - #if defined(WOLFSSL_HAVE_MLKEM) - WC_PK_TYPE_PQC_KEM_KEYGEN = 18, - WC_PK_TYPE_PQC_KEM_ENCAPS = 19, - WC_PK_TYPE_PQC_KEM_DECAPS = 20, - #undef _WC_PK_TYPE_MAX - #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_KEM_DECAPS + #ifndef WOLFSSL_NOSHA512_256 + WC_HASH_TYPE_SHA512_256 = 17, + #undef _WC_HASH_TYPE_MAX + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHA512_256 #endif - #if defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) - WC_PK_TYPE_PQC_SIG_KEYGEN = 21, - WC_PK_TYPE_PQC_SIG_SIGN = 22, - WC_PK_TYPE_PQC_SIG_VERIFY = 23, - WC_PK_TYPE_PQC_SIG_CHECK_PRIV_KEY = 24, - #undef _WC_PK_TYPE_MAX - #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_SIG_CHECK_PRIV_KEY + #ifdef WOLFSSL_SHAKE128 + WC_HASH_TYPE_SHAKE128 = 18, + #undef _WC_HASH_TYPE_MAX + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHAKE128 #endif - WC_PK_TYPE_RSA_PKCS = 25, - WC_PK_TYPE_RSA_PSS = 26, - WC_PK_TYPE_RSA_OAEP = 27, - WC_PK_TYPE_MAX = _WC_PK_TYPE_MAX - }; + #ifdef WOLFSSL_SHAKE256 + WC_HASH_TYPE_SHAKE256 = 19, + #undef _WC_HASH_TYPE_MAX + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SHAKE256 + #endif + #ifdef WOLFSSL_SM3 + WC_HASH_TYPE_SM3 = 20, + #undef _WC_HASH_TYPE_MAX + #define _WC_HASH_TYPE_MAX WC_HASH_TYPE_SM3 + #endif + WC_HASH_TYPE_MAX = _WC_HASH_TYPE_MAX + #undef _WC_HASH_TYPE_MAX + +#endif /* HAVE_SELFTEST */ +}; + +enum wc_HashFlags { + WC_HASH_FLAG_NONE = 0x00000000, + WC_HASH_FLAG_WILLCOPY = 0x00000001, /* flag to indicate hash will be copied */ + WC_HASH_FLAG_ISCOPY = 0x00000002, /* hash is copy */ +#ifdef WOLFSSL_SHA3 + WC_HASH_SHA3_KECCAK256 =0x00010000, /* Older KECCAK256 */ +#endif + WOLF_ENUM_DUMMY_LAST_ELEMENT(WC_HASH) +}; + +/* cipher types */ +enum wc_CipherType { + WC_CIPHER_NONE = 0, + WC_CIPHER_AES = 1, + WC_CIPHER_AES_CBC = 2, + WC_CIPHER_AES_GCM = 3, + WC_CIPHER_AES_CTR = 4, + WC_CIPHER_AES_XTS = 5, + WC_CIPHER_AES_CFB = 6, + WC_CIPHER_AES_CCM = 12, + WC_CIPHER_AES_ECB = 13, + WC_CIPHER_DES3 = 7, + WC_CIPHER_DES = 8, + WC_CIPHER_CHACHA = 9, + + WC_CIPHER_MAX = WC_CIPHER_AES_CCM +}; + +/* PK=public key (asymmetric) based algorithms */ +enum wc_PkType { + WC_PK_TYPE_NONE = 0, + WC_PK_TYPE_RSA = 1, + WC_PK_TYPE_DH = 2, + WC_PK_TYPE_ECDH = 3, + WC_PK_TYPE_ECDSA_SIGN = 4, + WC_PK_TYPE_ECDSA_VERIFY = 5, + WC_PK_TYPE_ED25519_SIGN = 6, + WC_PK_TYPE_CURVE25519 = 7, + WC_PK_TYPE_RSA_KEYGEN = 8, + WC_PK_TYPE_EC_KEYGEN = 9, + WC_PK_TYPE_RSA_CHECK_PRIV_KEY = 10, + WC_PK_TYPE_EC_CHECK_PRIV_KEY = 11, + WC_PK_TYPE_ED448 = 12, + WC_PK_TYPE_CURVE448 = 13, + WC_PK_TYPE_ED25519_VERIFY = 14, + WC_PK_TYPE_ED25519_KEYGEN = 15, + WC_PK_TYPE_CURVE25519_KEYGEN = 16, + WC_PK_TYPE_RSA_GET_SIZE = 17, + #define _WC_PK_TYPE_MAX WC_PK_TYPE_RSA_GET_SIZE +#if defined(WOLFSSL_HAVE_MLKEM) + WC_PK_TYPE_PQC_KEM_KEYGEN = 18, + WC_PK_TYPE_PQC_KEM_ENCAPS = 19, + WC_PK_TYPE_PQC_KEM_DECAPS = 20, + #undef _WC_PK_TYPE_MAX + #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_KEM_DECAPS +#endif +#if defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) + WC_PK_TYPE_PQC_SIG_KEYGEN = 21, + WC_PK_TYPE_PQC_SIG_SIGN = 22, + WC_PK_TYPE_PQC_SIG_VERIFY = 23, + WC_PK_TYPE_PQC_SIG_CHECK_PRIV_KEY = 24, + #undef _WC_PK_TYPE_MAX + #define _WC_PK_TYPE_MAX WC_PK_TYPE_PQC_SIG_CHECK_PRIV_KEY +#endif + WC_PK_TYPE_RSA_PKCS = 25, + WC_PK_TYPE_RSA_PSS = 26, + WC_PK_TYPE_RSA_OAEP = 27, + WC_PK_TYPE_MAX = _WC_PK_TYPE_MAX +}; #if defined(WOLFSSL_HAVE_MLKEM) /* Post quantum KEM algorithms */ @@ -1360,253 +1407,171 @@ typedef struct w64wrapper { }; #endif - /* settings detection for compile vs runtime math incompatibilities */ - enum { - #if !defined(USE_FAST_MATH) && !defined(SIZEOF_LONG) && !defined(SIZEOF_LONG_LONG) - CTC_SETTINGS = 0x0 - #elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG) && (SIZEOF_LONG == 8) - CTC_SETTINGS = 0x1 - #elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 8) - CTC_SETTINGS = 0x2 - #elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 4) - CTC_SETTINGS = 0x4 - #elif defined(USE_FAST_MATH) && !defined(SIZEOF_LONG) && !defined(SIZEOF_LONG_LONG) - CTC_SETTINGS = 0x8 - #elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG) && (SIZEOF_LONG == 8) - CTC_SETTINGS = 0x10 - #elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 8) - CTC_SETTINGS = 0x20 - #elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 4) - CTC_SETTINGS = 0x40 - #else - #error "bad math long / long long settings" - #endif - }; +/* settings detection for compile vs runtime math incompatibilities */ +enum { +#if !defined(USE_FAST_MATH) && !defined(SIZEOF_LONG) && !defined(SIZEOF_LONG_LONG) + CTC_SETTINGS = 0x0 +#elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG) && (SIZEOF_LONG == 8) + CTC_SETTINGS = 0x1 +#elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 8) + CTC_SETTINGS = 0x2 +#elif !defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 4) + CTC_SETTINGS = 0x4 +#elif defined(USE_FAST_MATH) && !defined(SIZEOF_LONG) && !defined(SIZEOF_LONG_LONG) + CTC_SETTINGS = 0x8 +#elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG) && (SIZEOF_LONG == 8) + CTC_SETTINGS = 0x10 +#elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 8) + CTC_SETTINGS = 0x20 +#elif defined(USE_FAST_MATH) && defined(SIZEOF_LONG_LONG) && (SIZEOF_LONG_LONG == 4) + CTC_SETTINGS = 0x40 +#else + #error "bad math long / long long settings" +#endif +}; - WOLFSSL_API word32 CheckRunTimeSettings(void); - /* If user uses RSA, DH, DSA, or ECC math lib directly then fast math and long - types need to match at compile time and run time, CheckCtcSettings will - return 1 if a match otherwise 0 */ - #define CheckCtcSettings() (CTC_SETTINGS == CheckRunTimeSettings()) +WOLFSSL_API word32 CheckRunTimeSettings(void); - /* invalid device id */ - #define INVALID_DEVID (-2) +/* If user uses RSA, DH, DSA, or ECC math lib directly then fast math and long + * types need to match at compile time and run time, CheckCtcSettings will + * return 1 if a match otherwise 0 */ +#define CheckCtcSettings() (CTC_SETTINGS == CheckRunTimeSettings()) - #if defined(HAVE_FIPS) && FIPS_VERSION_LT(5,3) - #ifdef XASM_LINK - #error User-supplied XASM_LINK is not compatible with this FIPS version. - #else - /* use version in FIPS <=5.2 aes.c */ - #endif - #elif defined(XASM_LINK) - /* keep user-supplied definition */ - #elif defined(WOLFSSL_NO_ASM) - #define XASM_LINK(f) /* null expansion */ - #elif defined(_MSC_VER) - #define XASM_LINK(f) /* null expansion */ - #elif defined(__APPLE__) - #define XASM_LINK(f) asm("_" f) - #elif defined(__GNUC__) - /* use alternate keyword for compatibility with -std=c99 */ - #define XASM_LINK(f) __asm__(f) +/* invalid device id */ +#define INVALID_DEVID (-2) + +#if defined(HAVE_FIPS) && FIPS_VERSION_LT(5,3) + #ifdef XASM_LINK + #error User-supplied XASM_LINK is not compatible with this FIPS version. #else - #define XASM_LINK(f) asm(f) - #endif + /* use version in FIPS <=5.2 aes.c */ + #endif +#elif defined(XASM_LINK) + /* keep user-supplied definition */ +#elif defined(WOLFSSL_NO_ASM) + #define XASM_LINK(f) /* null expansion */ +#elif defined(_MSC_VER) + #define XASM_LINK(f) /* null expansion */ +#elif defined(__APPLE__) + #define XASM_LINK(f) asm("_" f) +#elif defined(__GNUC__) + /* use alternate keyword for compatibility with -std=c99 */ + #define XASM_LINK(f) __asm__(f) +#else + #define XASM_LINK(f) asm(f) +#endif - /* AESNI requires alignment and ARMASM gains some performance from it. - * Xilinx RSA operations require alignment. - */ - #if defined(WOLFSSL_AESNI) || defined(WOLFSSL_ARMASM) || \ - defined(USE_INTEL_SPEEDUP) || defined(WOLFSSL_AFALG_XILINX) || \ - defined(WOLFSSL_XILINX) - #ifndef WOLFSSL_USE_ALIGN - #define WOLFSSL_USE_ALIGN - #endif - #endif /* WOLFSSL_AESNI || WOLFSSL_ARMASM || USE_INTEL_SPEEDUP || \ - * WOLFSSL_AFALG_XILINX */ - - /* Helpers for memory alignment */ - #ifndef XALIGNED - #if defined(__GNUC__) || defined(__llvm__) || \ - defined(__IAR_SYSTEMS_ICC__) - #define XALIGNED(x) __attribute__ ( (aligned (x))) - #elif defined(__KEIL__) - #define XALIGNED(x) __align(x) - #elif defined(_MSC_VER) - /* disable align warning, we want alignment ! */ - #pragma warning(disable: 4324) - #define XALIGNED(x) __declspec (align (x)) - #else - #define XALIGNED(x) /* null expansion */ +/* AESNI requires alignment and ARMASM gains some performance from it. + * Xilinx RSA operations require alignment. + */ +#if defined(WOLFSSL_AESNI) || defined(WOLFSSL_ARMASM) || \ + defined(USE_INTEL_SPEEDUP) || defined(WOLFSSL_AFALG_XILINX) || \ + defined(WOLFSSL_XILINX) + #ifndef WOLFSSL_USE_ALIGN + #define WOLFSSL_USE_ALIGN #endif +#endif /* WOLFSSL_AESNI || WOLFSSL_ARMASM || USE_INTEL_SPEEDUP || \ + * WOLFSSL_AFALG_XILINX */ + +/* Helpers for memory alignment */ +#ifndef XALIGNED + #if defined(__GNUC__) || defined(__llvm__) || \ + defined(__IAR_SYSTEMS_ICC__) + #define XALIGNED(x) __attribute__ ( (aligned (x))) + #elif defined(__KEIL__) + #define XALIGNED(x) __align(x) + #elif defined(_MSC_VER) + /* disable align warning, we want alignment ! */ + #pragma warning(disable: 4324) + #define XALIGNED(x) __declspec (align (x)) + #else + #define XALIGNED(x) /* null expansion */ #endif +#endif - /* Only use alignment in wolfSSL/wolfCrypt if WOLFSSL_USE_ALIGN is set */ - #ifdef WOLFSSL_USE_ALIGN - /* For IAR ARM the maximum variable alignment on stack is 8-bytes. - * Variables declared outside stack (like static globals) can have - * higher alignment. */ - #if defined(__ICCARM__) - #define WOLFSSL_ALIGN(x) XALIGNED(8) - #else - #define WOLFSSL_ALIGN(x) XALIGNED(x) - #endif +/* Only use alignment in wolfSSL/wolfCrypt if WOLFSSL_USE_ALIGN is set */ +#ifdef WOLFSSL_USE_ALIGN + /* For IAR ARM the maximum variable alignment on stack is 8-bytes. + * Variables declared outside stack (like static globals) can have + * higher alignment. */ + #if defined(__ICCARM__) + #define WOLFSSL_ALIGN(x) XALIGNED(8) #else - #define WOLFSSL_ALIGN(x) /* null expansion */ + #define WOLFSSL_ALIGN(x) XALIGNED(x) #endif +#else + #define WOLFSSL_ALIGN(x) /* null expansion */ +#endif - #ifndef ALIGN8 - #define ALIGN8 WOLFSSL_ALIGN(8) - #endif - #ifndef ALIGN16 - #define ALIGN16 WOLFSSL_ALIGN(16) - #endif - #ifndef ALIGN32 - #define ALIGN32 WOLFSSL_ALIGN(32) - #endif - #ifndef ALIGN64 - #define ALIGN64 WOLFSSL_ALIGN(64) - #endif - #ifndef ALIGN128 - #define ALIGN128 WOLFSSL_ALIGN(128) - #endif - #ifndef ALIGN256 - #define ALIGN256 WOLFSSL_ALIGN(256) - #endif +#ifndef ALIGN8 + #define ALIGN8 WOLFSSL_ALIGN(8) +#endif +#ifndef ALIGN16 + #define ALIGN16 WOLFSSL_ALIGN(16) +#endif +#ifndef ALIGN32 + #define ALIGN32 WOLFSSL_ALIGN(32) +#endif +#ifndef ALIGN64 + #define ALIGN64 WOLFSSL_ALIGN(64) +#endif +#ifndef ALIGN128 + #define ALIGN128 WOLFSSL_ALIGN(128) +#endif +#ifndef ALIGN256 + #define ALIGN256 WOLFSSL_ALIGN(256) +#endif - #if !defined(PEDANTIC_EXTENSION) - #if defined(__GNUC__) - #define PEDANTIC_EXTENSION __extension__ - #else - #define PEDANTIC_EXTENSION - #endif - #endif /* !PEDANTIC_EXTENSION */ +#if !defined(PEDANTIC_EXTENSION) + #if defined(__GNUC__) + #define PEDANTIC_EXTENSION __extension__ + #else + #define PEDANTIC_EXTENSION + #endif +#endif /* !PEDANTIC_EXTENSION */ - #ifndef TRUE - #define TRUE 1 - #endif - #ifndef FALSE - #define FALSE 0 - #endif +#ifndef TRUE + #define TRUE 1 +#endif +#ifndef FALSE + #define FALSE 0 +#endif - #ifdef SINGLE_THREADED - #if defined(WC_32BIT_CPU) || defined(HAVE_STACK_SIZE) - typedef void* THREAD_RETURN; - #else - typedef unsigned int THREAD_RETURN; - #endif - typedef void* THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(WOLFSSL_USER_THREADING) - /* User can define user specific threading types - * THREAD_RETURN - * TREAD_TYPE - * WOLFSSL_THREAD - * e.g. - * typedef unsigned int THREAD_RETURN; - * typedef size_t THREAD_TYPE; - * #define WOLFSSL_THREAD void - * - * User can also implement their own wolfSSL_NewThread(), - * wolfSSL_JoinThread() and wolfSSL_Cond signaling if they want. - * Otherwise, those functions are omitted. - */ - #elif defined(__WATCOMC__) - #if __WATCOMC__ < 1300 - #define _WCCALLBACK - #endif - #if defined(__NT__) - typedef unsigned THREAD_RETURN; - typedef uintptr_t THREAD_TYPE; - typedef struct COND_TYPE { - wolfSSL_Mutex mutex; - HANDLE cond; - } COND_TYPE; - #define WOLFSSL_COND - #define INVALID_THREAD_VAL ((THREAD_TYPE)(INVALID_HANDLE_VALUE)) - #define WOLFSSL_THREAD __stdcall - #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK - #elif defined(__OS2__) - #define WOLFSSL_THREAD_VOID_RETURN - typedef void THREAD_RETURN; - typedef TID THREAD_TYPE; - typedef struct COND_TYPE { - wolfSSL_Mutex mutex; - LHANDLE cond; - } COND_TYPE; - #define WOLFSSL_COND - #define INVALID_THREAD_VAL ((THREAD_TYPE)(-1)) - #define WOLFSSL_THREAD _WCCALLBACK - #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK - #elif defined(__LINUX__) - #include - typedef struct COND_TYPE { - pthread_mutex_t mutex; - pthread_cond_t cond; - } COND_TYPE; - typedef void* THREAD_RETURN; - typedef pthread_t THREAD_TYPE; - #define WOLFSSL_COND - #define WOLFSSL_THREAD - #ifndef HAVE_SELFTEST - #define WOLFSSL_THREAD_NO_JOIN - #endif - #endif - #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) || \ - defined(FREESCALE_MQX) - typedef unsigned int THREAD_RETURN; - typedef int THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(WOLFSSL_NUCLEUS) - typedef unsigned int THREAD_RETURN; - typedef intptr_t THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(WOLFSSL_TIRTOS) - typedef void THREAD_RETURN; - #define WOLFSSL_THREAD_VOID_RETURN - typedef Task_Handle THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(WOLFSSL_ZEPHYR) - typedef void THREAD_RETURN; - #define WOLFSSL_THREAD_VOID_RETURN - typedef struct { - /* Zephyr k_thread can be large, > 128 bytes. */ - struct k_thread* tid; - k_thread_stack_t* threadStack; - } THREAD_TYPE; - #define WOLFSSL_THREAD - extern void* wolfsslThreadHeapHint; - #elif defined(NETOS) - typedef UINT THREAD_RETURN; - typedef struct { - TX_THREAD tid; - void* threadStack; - } THREAD_TYPE; - #define WOLFSSL_THREAD - #define INFINITE TX_WAIT_FOREVER - #define WAIT_OBJECT_0 TX_NO_WAIT - #elif defined(WOLFSSL_LINUXKM) - typedef unsigned int THREAD_RETURN; - typedef size_t THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(WOLFSSL_PTHREADS) - #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 \ - && !defined(__ppc__) - #include - typedef struct COND_TYPE { - wolfSSL_Mutex mutex; - dispatch_semaphore_t cond; - } COND_TYPE; - #else - #include - typedef struct COND_TYPE { - pthread_mutex_t mutex; - pthread_cond_t cond; - } COND_TYPE; - #endif +#ifdef SINGLE_THREADED + #if defined(WC_32BIT_CPU) || defined(HAVE_STACK_SIZE) + typedef void* THREAD_RETURN; + #else + typedef unsigned int THREAD_RETURN; + #endif + typedef void* THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(WOLFSSL_USER_THREADING) + /* User can define user specific threading types + * THREAD_RETURN + * TREAD_TYPE + * WOLFSSL_THREAD + * e.g. + * typedef unsigned int THREAD_RETURN; + * typedef size_t THREAD_TYPE; + * #define WOLFSSL_THREAD void + * + * User can also implement their own wolfSSL_NewThread(), + * wolfSSL_JoinThread() and wolfSSL_Cond signaling if they want. + * Otherwise, those functions are omitted. + */ +#elif defined(__WATCOMC__) + #if __WATCOMC__ < 1300 + #define _WCCALLBACK + #endif + #if defined(__MACH__) + #include + #include + typedef struct COND_TYPE { + dispatch_semaphore_t cond; + } COND_TYPE; typedef void* THREAD_RETURN; typedef pthread_t THREAD_TYPE; #define WOLFSSL_COND @@ -1614,15 +1579,7 @@ typedef struct w64wrapper { #ifndef HAVE_SELFTEST #define WOLFSSL_THREAD_NO_JOIN #endif - #elif defined(FREERTOS) && defined(WOLFSSL_ESPIDF) - typedef void* THREAD_RETURN; - typedef pthread_t THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(FREERTOS) - typedef unsigned int THREAD_RETURN; - typedef TaskHandle_t THREAD_TYPE; - #define WOLFSSL_THREAD - #elif defined(USE_WINDOWS_API) + #elif defined(__NT__) typedef unsigned THREAD_RETURN; typedef uintptr_t THREAD_TYPE; typedef struct COND_TYPE { @@ -1632,302 +1589,555 @@ typedef struct w64wrapper { #define WOLFSSL_COND #define INVALID_THREAD_VAL ((THREAD_TYPE)(INVALID_HANDLE_VALUE)) #define WOLFSSL_THREAD __stdcall - #if !defined(__MINGW32__) - #define WOLFSSL_THREAD_NO_JOIN __cdecl - #endif - #elif defined(THREADX) - typedef unsigned int THREAD_RETURN; - typedef TX_THREAD THREAD_TYPE; + #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK + #elif defined(__OS2__) + #define WOLFSSL_THREAD_VOID_RETURN + typedef void THREAD_RETURN; + typedef TID THREAD_TYPE; + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + LHANDLE cond; + } COND_TYPE; + #define WOLFSSL_COND + #define INVALID_THREAD_VAL ((THREAD_TYPE)(-1)) + #define WOLFSSL_THREAD _WCCALLBACK + #define WOLFSSL_THREAD_NO_JOIN _WCCALLBACK + #elif defined(__LINUX__) + #include + typedef struct COND_TYPE { + pthread_mutex_t mutex; + pthread_cond_t cond; + } COND_TYPE; + typedef void* THREAD_RETURN; + typedef pthread_t THREAD_TYPE; + #define WOLFSSL_COND #define WOLFSSL_THREAD + #ifndef HAVE_SELFTEST + #define WOLFSSL_THREAD_NO_JOIN + #endif + #endif +#elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) || \ + defined(FREESCALE_MQX) + typedef unsigned int THREAD_RETURN; + typedef int THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(WOLFSSL_NUCLEUS) + typedef unsigned int THREAD_RETURN; + typedef intptr_t THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(WOLFSSL_TIRTOS) + typedef void THREAD_RETURN; + #define WOLFSSL_THREAD_VOID_RETURN + typedef Task_Handle THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(WOLFSSL_ZEPHYR) + typedef void THREAD_RETURN; + #define WOLFSSL_THREAD_VOID_RETURN + typedef struct { + /* Zephyr k_thread can be large, > 128 bytes. */ + struct k_thread* tid; + k_thread_stack_t* threadStack; + } THREAD_TYPE; + #define WOLFSSL_THREAD + extern void* wolfsslThreadHeapHint; +#elif defined(NETOS) + typedef UINT THREAD_RETURN; + typedef struct { + TX_THREAD tid; + void* threadStack; + } THREAD_TYPE; + #define WOLFSSL_THREAD + #define INFINITE TX_WAIT_FOREVER + #define WAIT_OBJECT_0 TX_NO_WAIT +#elif defined(WOLFSSL_LINUXKM) + typedef unsigned int THREAD_RETURN; + typedef size_t THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(WOLFSSL_PTHREADS) + #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 \ + && !defined(__ppc__) + #include + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + dispatch_semaphore_t cond; + } COND_TYPE; #else - typedef unsigned int THREAD_RETURN; - typedef size_t THREAD_TYPE; - #define WOLFSSL_THREAD __stdcall + #include + typedef struct COND_TYPE { + pthread_mutex_t mutex; + pthread_cond_t cond; + } COND_TYPE; #endif + typedef void* THREAD_RETURN; + typedef pthread_t THREAD_TYPE; + #define WOLFSSL_COND + #define WOLFSSL_THREAD + #ifndef HAVE_SELFTEST + #define WOLFSSL_THREAD_NO_JOIN + #endif +#elif defined(FREERTOS) && defined(WOLFSSL_ESPIDF) + typedef void* THREAD_RETURN; + typedef pthread_t THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(FREERTOS) + typedef unsigned int THREAD_RETURN; + typedef TaskHandle_t THREAD_TYPE; + #define WOLFSSL_THREAD +#elif defined(_WIN32_WCE) + typedef unsigned THREAD_RETURN; + typedef size_t THREAD_TYPE; + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + HANDLE cond; + } COND_TYPE; + #define WOLFSSL_COND + #define INVALID_THREAD_VAL ((THREAD_TYPE)(INVALID_HANDLE_VALUE)) + #define WOLFSSL_THREAD __stdcall + #define WOLFSSL_THREAD_NO_JOIN __cdecl +#elif defined(USE_WINDOWS_API) + typedef unsigned THREAD_RETURN; + typedef uintptr_t THREAD_TYPE; + typedef struct COND_TYPE { + wolfSSL_Mutex mutex; + HANDLE cond; + } COND_TYPE; + #define WOLFSSL_COND + #define INVALID_THREAD_VAL ((THREAD_TYPE)(INVALID_HANDLE_VALUE)) + #define WOLFSSL_THREAD __stdcall + #if !defined(__MINGW32__) + #define WOLFSSL_THREAD_NO_JOIN __cdecl + #endif +#elif defined(THREADX) + typedef unsigned int THREAD_RETURN; + typedef TX_THREAD THREAD_TYPE; + #define WOLFSSL_THREAD +#else + typedef unsigned int THREAD_RETURN; + typedef size_t THREAD_TYPE; + #define WOLFSSL_THREAD __stdcall +#endif - #ifndef SINGLE_THREADED - /* Necessary headers should already be included. */ - - #ifndef INVALID_THREAD_VAL - #define INVALID_THREAD_VAL ((THREAD_TYPE)(-1)) - #endif - - #ifndef WOLFSSL_THREAD_VOID_RETURN - #define WOLFSSL_RETURN_FROM_THREAD(x) return (THREAD_RETURN)(x) - #else - #define WOLFSSL_RETURN_FROM_THREAD(x) \ - do { (void)(x); return; } while(0) - #endif - - /* List of defines/types and what they mean: - * THREAD_RETURN - return type of a thread callback - * THREAD_TYPE - type that should be passed into thread handling API - * INVALID_THREAD_VAL - a value that THREAD_TYPE can be checked against - * to check if the value is an invalid thread - * WOLFSSL_THREAD - attribute that should be used to declare thread - * callbacks - * WOLFSSL_COND - defined if this system supports signaling - * COND_TYPE - type that should be passed into the signaling API - * WOLFSSL_THREAD_VOID_RETURN - defined if the thread callback has a - * void return - * WOLFSSL_RETURN_FROM_THREAD - define used to correctly return from a - * thread callback - * THREAD_CB - thread callback type for regular threading API - * - * WOLFSSL_THREAD_NO_JOIN - attribute used to declare thread callbacks - * that do not require cleanup - * THREAD_CB_NOJOIN - thread callback type for thread APIs that do not - * require cleanup - * THREAD_RETURN_NOJOIN - return type used to declare thread callbacks - * that do not require cleanup - * RETURN_FROM_THREAD_NOJOIN - define used to correctly return from - * a thread callback that do not require - * cleanup - * - * Other defines/types are specific for the threading implementation - */ - - /* Internal wolfSSL threading interface. It does NOT need to be ported - * during initial porting efforts. This is a very basic interface. Some - * areas don't use this interface on purpose as they need more control - * over threads. - * - * It is currently used for: - * - CRL monitor - * - Testing - * - Entropy generation */ - - /* We don't support returns from threads */ - typedef THREAD_RETURN (WOLFSSL_THREAD *THREAD_CB)(void* arg); - WOLFSSL_API int wolfSSL_NewThread(THREAD_TYPE* thread, - THREAD_CB cb, void* arg); - #ifdef WOLFSSL_THREAD_NO_JOIN - /* Create a thread that will be automatically cleaned up. We can't - * return a handle/pointer to the new thread because there are no - * guarantees for how long it will be valid. */ - #if defined(WOLFSSL_PTHREADS) - #define THREAD_CB_NOJOIN THREAD_CB - #define THREAD_RETURN_NOJOIN THREAD_RETURN - #define RETURN_FROM_THREAD_NOJOIN(x) \ - WOLFSSL_RETURN_FROM_THREAD(x) - #else - #define THREAD_RETURN_NOJOIN void - typedef THREAD_RETURN_NOJOIN - (WOLFSSL_THREAD_NO_JOIN *THREAD_CB_NOJOIN)(void* arg); - #define RETURN_FROM_THREAD_NOJOIN(x) return - #endif - WOLFSSL_API int wolfSSL_NewThreadNoJoin(THREAD_CB_NOJOIN cb, - void* arg); - #endif - WOLFSSL_API int wolfSSL_JoinThread(THREAD_TYPE thread); - - #ifdef WOLFSSL_COND - WOLFSSL_API int wolfSSL_CondInit(COND_TYPE* cond); - WOLFSSL_API int wolfSSL_CondFree(COND_TYPE* cond); - WOLFSSL_API int wolfSSL_CondSignal(COND_TYPE* cond); - WOLFSSL_API int wolfSSL_CondWait(COND_TYPE* cond); - WOLFSSL_API int wolfSSL_CondStart(COND_TYPE* cond); - WOLFSSL_API int wolfSSL_CondEnd(COND_TYPE* cond); - #endif - #else - #define WOLFSSL_RETURN_FROM_THREAD(x) return (THREAD_RETURN)(x) - #endif /* SINGLE_THREADED */ +#ifndef SINGLE_THREADED + /* Necessary headers should already be included. */ - #if defined(HAVE_STACK_SIZE) - #define EXIT_TEST(ret) return (THREAD_RETURN)((size_t)(ret)) - #else - #define EXIT_TEST(ret) return ret + #ifndef INVALID_THREAD_VAL + #define INVALID_THREAD_VAL ((THREAD_TYPE)(-1)) #endif - - #if (defined(__IAR_SYSTEMS_ICC__) && (__IAR_SYSTEMS_ICC__ > 8)) || \ - defined(__GNUC__) - #define WOLFSSL_PACK __attribute__ ((packed)) + #ifndef WOLFSSL_THREAD_VOID_RETURN + #define WOLFSSL_RETURN_FROM_THREAD(x) return (THREAD_RETURN)(x) #else - #define WOLFSSL_PACK - #endif + #define WOLFSSL_RETURN_FROM_THREAD(x) \ + do { (void)(x); return; } while(0) + #endif + + /* List of defines/types and what they mean: + * THREAD_RETURN - return type of a thread callback + * THREAD_TYPE - type that should be passed into thread handling API + * INVALID_THREAD_VAL - a value that THREAD_TYPE can be checked against + * to check if the value is an invalid thread + * WOLFSSL_THREAD - attribute that should be used to declare thread + * callbacks + * WOLFSSL_COND - defined if this system supports signaling + * COND_TYPE - type that should be passed into the signaling API + * WOLFSSL_THREAD_VOID_RETURN - defined if the thread callback has a + * void return + * WOLFSSL_RETURN_FROM_THREAD - define used to correctly return from a + * thread callback + * THREAD_CB - thread callback type for regular threading API + * + * WOLFSSL_THREAD_NO_JOIN - attribute used to declare thread callbacks + * that do not require cleanup + * THREAD_CB_NOJOIN - thread callback type for thread APIs that do not + * require cleanup + * THREAD_RETURN_NOJOIN - return type used to declare thread callbacks + * that do not require cleanup + * RETURN_FROM_THREAD_NOJOIN - define used to correctly return from + * a thread callback that do not require + * cleanup + * + * Other defines/types are specific for the threading implementation + */ - #ifndef __GNUC_PREREQ - #if defined(__GNUC__) && defined(__GNUC_MINOR__) - #define __GNUC_PREREQ(maj, min) \ - ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) + /* Internal wolfSSL threading interface. It does NOT need to be ported + * during initial porting efforts. This is a very basic interface. Some + * areas don't use this interface on purpose as they need more control + * over threads. + * + * It is currently used for: + * - CRL monitor + * - Testing + * - Entropy generation */ + + /* We don't support returns from threads */ + typedef THREAD_RETURN (WOLFSSL_THREAD *THREAD_CB)(void* arg); + WOLFSSL_API int wolfSSL_NewThread(THREAD_TYPE* thread, + THREAD_CB cb, void* arg); + #ifdef WOLFSSL_THREAD_NO_JOIN + /* Create a thread that will be automatically cleaned up. We can't + * return a handle/pointer to the new thread because there are no + * guarantees for how long it will be valid. */ + #if defined(WOLFSSL_PTHREADS) + #define THREAD_CB_NOJOIN THREAD_CB + #define THREAD_RETURN_NOJOIN THREAD_RETURN + #define RETURN_FROM_THREAD_NOJOIN(x) \ + WOLFSSL_RETURN_FROM_THREAD(x) #else - #define __GNUC_PREREQ(maj, min) (0) /* not GNUC */ + #define THREAD_RETURN_NOJOIN void + typedef THREAD_RETURN_NOJOIN + (WOLFSSL_THREAD_NO_JOIN *THREAD_CB_NOJOIN)(void* arg); + #define RETURN_FROM_THREAD_NOJOIN(x) return #endif + WOLFSSL_API int wolfSSL_NewThreadNoJoin(THREAD_CB_NOJOIN cb, + void* arg); #endif + WOLFSSL_API int wolfSSL_JoinThread(THREAD_TYPE thread); - #if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) - #define WC_NORETURN __attribute__((noreturn)) - #else - #define WC_NORETURN + #ifdef WOLFSSL_COND + WOLFSSL_API int wolfSSL_CondInit(COND_TYPE* cond); + WOLFSSL_API int wolfSSL_CondFree(COND_TYPE* cond); + WOLFSSL_API int wolfSSL_CondSignal(COND_TYPE* cond); + WOLFSSL_API int wolfSSL_CondWait(COND_TYPE* cond); + WOLFSSL_API int wolfSSL_CondStart(COND_TYPE* cond); + WOLFSSL_API int wolfSSL_CondEnd(COND_TYPE* cond); #endif +#else + #define WOLFSSL_RETURN_FROM_THREAD(x) return (THREAD_RETURN)(x) +#endif /* SINGLE_THREADED */ - #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) || \ - defined(WOLFSSL_DEBUG_MATH) || defined(DEBUG_WOLFSSL) || \ - defined(WOLFSSL_PUBLIC_MP) || defined(OPENSSL_EXTRA) || \ - (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) - #undef WC_MP_TO_RADIX - #define WC_MP_TO_RADIX - #endif +#if defined(HAVE_STACK_SIZE) + #define EXIT_TEST(ret) return (THREAD_RETURN)((size_t)(ret)) +#else + #define EXIT_TEST(ret) return ret +#endif - #if defined(__GNUC__) && __GNUC__ > 5 - #define PRAGMA_GCC_DIAG_PUSH _Pragma("GCC diagnostic push") - #define PRAGMA_GCC(str) _Pragma(str) - #define PRAGMA_GCC_DIAG_POP _Pragma("GCC diagnostic pop") - #define PRAGMA_DIAG_PUSH PRAGMA_GCC_DIAG_PUSH - #define PRAGMA(str) PRAGMA_GCC(str) - #define PRAGMA_DIAG_POP PRAGMA_GCC_DIAG_POP - #else - #define PRAGMA_GCC_DIAG_PUSH /* null expansion */ - #define PRAGMA_GCC(str) /* null expansion */ - #define PRAGMA_GCC_DIAG_POP /* null expansion */ - #endif - #ifdef __clang__ - #define PRAGMA_CLANG_DIAG_PUSH _Pragma("clang diagnostic push") - #define PRAGMA_CLANG(str) _Pragma(str) - #define PRAGMA_CLANG_DIAG_POP _Pragma("clang diagnostic pop") - #define PRAGMA_DIAG_PUSH PRAGMA_CLANG_DIAG_PUSH - #define PRAGMA(str) PRAGMA_CLANG(str) - #define PRAGMA_DIAG_POP PRAGMA_CLANG_DIAG_POP +#if (defined(__IAR_SYSTEMS_ICC__) && (__IAR_SYSTEMS_ICC__ > 8)) || \ + defined(__GNUC__) + #define WOLFSSL_PACK __attribute__ ((packed)) +#else + #define WOLFSSL_PACK +#endif + +#ifndef __GNUC_PREREQ + #if defined(__GNUC__) && defined(__GNUC_MINOR__) + #define __GNUC_PREREQ(maj, min) \ + ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else - #define PRAGMA_CLANG_DIAG_PUSH /* null expansion */ - #define PRAGMA_CLANG(str) /* null expansion */ - #define PRAGMA_CLANG_DIAG_POP /* null expansion */ + #define __GNUC_PREREQ(maj, min) (0) /* not GNUC */ #endif +#endif - #ifndef PRAGMA_DIAG_PUSH - #define PRAGMA_DIAG_PUSH /* null expansion */ - #endif - #ifndef PRAGMA - #define PRAGMA(str) /* null expansion */ - #endif - #ifndef PRAGMA_DIAG_POP - #define PRAGMA_DIAG_POP /* null expansion */ - #endif +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) + #define WC_NORETURN __attribute__((noreturn)) +#else + #define WC_NORETURN +#endif - #define WC_CPP_CAT4_(a, b, c, d) a ## b ## c ## d - #define WC_CPP_CAT4(a, b, c, d) WC_CPP_CAT4_(a, b, c, d) - #if defined(WC_NO_STATIC_ASSERT) - #define wc_static_assert(expr) struct wc_static_assert_dummy_struct - #define wc_static_assert2(expr, msg) wc_static_assert(expr) - #elif !defined(wc_static_assert) - #if defined(WOLFSSL_HAVE_ASSERT_H) && !defined(WOLFSSL_NO_ASSERT_H) - #include +#if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) || \ + defined(WOLFSSL_DEBUG_MATH) || defined(DEBUG_WOLFSSL) || \ + defined(WOLFSSL_PUBLIC_MP) || defined(OPENSSL_EXTRA) || \ + (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) + #undef WC_MP_TO_RADIX + #define WC_MP_TO_RADIX +#endif + +#if defined(__GNUC__) && __GNUC__ > 5 + #define PRAGMA_GCC_DIAG_PUSH _Pragma("GCC diagnostic push") + #define PRAGMA_GCC(str) _Pragma(str) + #define PRAGMA_GCC_DIAG_POP _Pragma("GCC diagnostic pop") + #define PRAGMA_DIAG_PUSH PRAGMA_GCC_DIAG_PUSH + #define PRAGMA(str) PRAGMA_GCC(str) + #define PRAGMA_DIAG_POP PRAGMA_GCC_DIAG_POP +#else + #define PRAGMA_GCC_DIAG_PUSH /* null expansion */ + #define PRAGMA_GCC(str) /* null expansion */ + #define PRAGMA_GCC_DIAG_POP /* null expansion */ +#endif + +#ifdef __clang__ + #define PRAGMA_CLANG_DIAG_PUSH _Pragma("clang diagnostic push") + #define PRAGMA_CLANG(str) _Pragma(str) + #define PRAGMA_CLANG_DIAG_POP _Pragma("clang diagnostic pop") + #define PRAGMA_DIAG_PUSH PRAGMA_CLANG_DIAG_PUSH + #define PRAGMA(str) PRAGMA_CLANG(str) + #define PRAGMA_DIAG_POP PRAGMA_CLANG_DIAG_POP +#else + #define PRAGMA_CLANG_DIAG_PUSH /* null expansion */ + #define PRAGMA_CLANG(str) /* null expansion */ + #define PRAGMA_CLANG_DIAG_POP /* null expansion */ +#endif + +#ifndef PRAGMA_DIAG_PUSH + #define PRAGMA_DIAG_PUSH /* null expansion */ +#endif +#ifndef PRAGMA + #define PRAGMA(str) /* null expansion */ +#endif +#ifndef PRAGMA_DIAG_POP + #define PRAGMA_DIAG_POP /* null expansion */ +#endif + +#define WC_CPP_CAT4_(a, b, c, d) a ## b ## c ## d +#define WC_CPP_CAT4(a, b, c, d) WC_CPP_CAT4_(a, b, c, d) +#if defined(WC_NO_STATIC_ASSERT) + #define wc_static_assert(expr) struct wc_static_assert_dummy_struct + #define wc_static_assert2(expr, msg) wc_static_assert(expr) +#elif !defined(wc_static_assert) + #if defined(WOLFSSL_HAVE_ASSERT_H) && !defined(WOLFSSL_NO_ASSERT_H) + #include + #endif + #if (defined(__cplusplus) && (__cplusplus >= 201703L)) || \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)) || \ + (defined(_MSVC_LANG) && (__cpp_static_assert >= 201411L)) + /* native variadic static_assert() */ + #define wc_static_assert static_assert + #ifndef wc_static_assert2 + #define wc_static_assert2 static_assert #endif - #if (defined(__cplusplus) && (__cplusplus >= 201703L)) || \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)) || \ - (defined(_MSVC_LANG) && (__cpp_static_assert >= 201411L)) - /* native variadic static_assert() */ - #define wc_static_assert static_assert - #ifndef wc_static_assert2 - #define wc_static_assert2 static_assert - #endif - #elif (defined(_MSC_VER) && (__STDC_VERSION__ >= 201112L)) || \ - (defined(_MSVC_LANG) && (__cpp_static_assert >= 200410L)) - /* native 2-argument static_assert() */ - #define wc_static_assert(expr) static_assert(expr, #expr) - #ifndef wc_static_assert2 - #define wc_static_assert2(expr, msg) static_assert(expr, msg) - #endif - #elif !defined(__cplusplus) && \ - !defined(__STRICT_ANSI__) && \ - !defined(WOLF_C89) && \ - defined(__STDC_VERSION__) && \ - (__STDC_VERSION__ >= 201112L) && \ - ((defined(__GNUC__) && \ - (__GNUC__ >= 5)) || \ - defined(__clang__)) - /* native 2-argument _Static_assert() */ - #define wc_static_assert(expr) _Static_assert(expr, #expr) - #ifndef wc_static_assert2 - #define wc_static_assert2(expr, msg) _Static_assert(expr, msg) - #endif + #elif (defined(_MSC_VER) && (__STDC_VERSION__ >= 201112L)) || \ + (defined(_MSVC_LANG) && (__cpp_static_assert >= 200410L)) + /* native 2-argument static_assert() */ + #define wc_static_assert(expr) static_assert(expr, #expr) + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) static_assert(expr, msg) + #endif + #elif !defined(__cplusplus) && \ + !defined(__STRICT_ANSI__) && \ + !defined(WOLF_C89) && \ + defined(__STDC_VERSION__) && \ + (__STDC_VERSION__ >= 201112L) && \ + ((defined(__GNUC__) && \ + (__GNUC__ >= 5)) || \ + defined(__clang__)) + /* native 2-argument _Static_assert() */ + #define wc_static_assert(expr) _Static_assert(expr, #expr) + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) _Static_assert(expr, msg) + #endif + #else + #ifdef __COUNTER__ + #define wc_static_assert(expr) \ + struct WC_CPP_CAT4(wc_static_assert_dummy_struct_L, \ + __LINE__, _, __COUNTER__) { \ + char t[(expr) ? 1 : -1]; \ + } #else - #ifdef __COUNTER__ - #define wc_static_assert(expr) \ - struct WC_CPP_CAT4(wc_static_assert_dummy_struct_L, \ - __LINE__, _, __COUNTER__) { \ - char t[(expr) ? 1 : -1]; \ - } - #else - #define wc_static_assert(expr) \ - struct wc_static_assert_dummy_struct - #endif - #ifndef wc_static_assert2 - #define wc_static_assert2(expr, msg) wc_static_assert(expr) - #endif + #define wc_static_assert(expr) \ + struct wc_static_assert_dummy_struct + #endif + #ifndef wc_static_assert2 + #define wc_static_assert2(expr, msg) wc_static_assert(expr) #endif - #elif !defined(wc_static_assert2) - #define wc_static_assert2(expr, msg) wc_static_assert(expr) #endif +#elif !defined(wc_static_assert2) + #define wc_static_assert2(expr, msg) wc_static_assert(expr) +#endif - #ifndef SAVE_VECTOR_REGISTERS - #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING - #endif - #ifndef SAVE_VECTOR_REGISTERS2 - #define SAVE_VECTOR_REGISTERS2() 0 - #define SAVE_VECTOR_REGISTERS2_DOES_NOTHING - #endif - #ifndef CAN_SAVE_VECTOR_REGISTERS - #define CAN_SAVE_VECTOR_REGISTERS() 1 - #define CAN_SAVE_VECTOR_REGISTERS_ALWAYS_TRUE - #endif - #ifndef WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL - #define WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL(x) WC_DO_NOTHING - #endif - #ifndef ASSERT_SAVED_VECTOR_REGISTERS - #define ASSERT_SAVED_VECTOR_REGISTERS() WC_DO_NOTHING - #endif - #ifndef ASSERT_RESTORED_VECTOR_REGISTERS - #define ASSERT_RESTORED_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING +#ifndef SAVE_VECTOR_REGISTERS + #define SAVE_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING +#endif +#ifndef SAVE_VECTOR_REGISTERS2 + #define SAVE_VECTOR_REGISTERS2() 0 + #define SAVE_VECTOR_REGISTERS2_DOES_NOTHING +#endif +#ifndef CAN_SAVE_VECTOR_REGISTERS + #define CAN_SAVE_VECTOR_REGISTERS() 1 + #define CAN_SAVE_VECTOR_REGISTERS_ALWAYS_TRUE +#endif +#ifndef WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL + #define WC_DEBUG_SET_VECTOR_REGISTERS_RETVAL(x) WC_DO_NOTHING +#endif +#ifndef ASSERT_SAVED_VECTOR_REGISTERS + #define ASSERT_SAVED_VECTOR_REGISTERS() WC_DO_NOTHING +#endif +#ifndef ASSERT_RESTORED_VECTOR_REGISTERS + #define ASSERT_RESTORED_VECTOR_REGISTERS(fail_clause) WC_DO_NOTHING +#endif +#ifndef RESTORE_VECTOR_REGISTERS + #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING +#endif +#ifdef WOLFSSL_NO_ASM + /* We define fallback no-op definitions for these only if asm is disabled, + * otherwise the using code must detect that these macros are undefined and + * provide its own non-vector implementation paths. + * + * Currently these macros are only used in WOLFSSL_LINUXKM code paths, which + * are always compiled either with substantive definitions from + * linuxkm_wc_port.h, or with WOLFSSL_NO_ASM defined. + */ + #ifndef DISABLE_VECTOR_REGISTERS + #define DISABLE_VECTOR_REGISTERS() 0 #endif - #ifndef RESTORE_VECTOR_REGISTERS - #define RESTORE_VECTOR_REGISTERS() WC_DO_NOTHING + #ifndef REENABLE_VECTOR_REGISTERS + #define REENABLE_VECTOR_REGISTERS() WC_DO_NOTHING #endif +#endif - #ifndef WC_SANITIZE_DISABLE - #define WC_SANITIZE_DISABLE() WC_DO_NOTHING - #endif - #ifndef WC_SANITIZE_ENABLE - #define WC_SANITIZE_ENABLE() WC_DO_NOTHING - #endif +#ifndef WC_SANITIZE_DISABLE + #define WC_SANITIZE_DISABLE() WC_DO_NOTHING +#endif +#ifndef WC_SANITIZE_ENABLE + #define WC_SANITIZE_ENABLE() WC_DO_NOTHING +#endif - #if FIPS_VERSION_GE(5,1) - #define WC_SPKRE_F(x,y) wolfCrypt_SetPrivateKeyReadEnable_fips((x),(y)) - #define PRIVATE_KEY_LOCK() WC_SPKRE_F(0,WC_KEYTYPE_ALL) - #define PRIVATE_KEY_UNLOCK() WC_SPKRE_F(1,WC_KEYTYPE_ALL) - #else - #define PRIVATE_KEY_LOCK() WC_DO_NOTHING - #define PRIVATE_KEY_UNLOCK() WC_DO_NOTHING - #endif +#if FIPS_VERSION_GE(5,1) + #define WC_SPKRE_F(x,y) wolfCrypt_SetPrivateKeyReadEnable_fips((x),(y)) + #define PRIVATE_KEY_LOCK() WC_SPKRE_F(0,WC_KEYTYPE_ALL) + #define PRIVATE_KEY_UNLOCK() WC_SPKRE_F(1,WC_KEYTYPE_ALL) +#else + #define PRIVATE_KEY_LOCK() WC_DO_NOTHING + #define PRIVATE_KEY_UNLOCK() WC_DO_NOTHING +#endif - #ifdef _MSC_VER - /* disable buggy MSC warning (incompatible with clang-tidy - * readability-avoid-const-params-in-decls) - * "warning C4028: formal parameter x different from declaration" - */ - #pragma warning(disable: 4028) - #endif +#ifdef _MSC_VER + /* disable buggy MSC warning (incompatible with clang-tidy + * readability-avoid-const-params-in-decls) + * "warning C4028: formal parameter x different from declaration" + */ + #pragma warning(disable: 4028) +#endif + + +/* opaque math variable type */ +#if defined(USE_FAST_MATH) + struct fp_int; + #define MATH_INT_T struct fp_int +#elif defined(USE_INTEGER_HEAP_MATH) + struct mp_int; + #define MATH_INT_T struct mp_int +#else + struct sp_int; + #define MATH_INT_T struct sp_int +#endif + + +/* Maximum ASN sizes */ +#ifndef WOLFSSL_ASN_MAX_LENGTH_SZ + #define WOLFSSL_ASN_MAX_LENGTH_SZ 5 /* 1 byte length + 4 bytes of number */ +#endif + +enum Max_ASN { + DSA_PUB_INTS = 4, /* DSA ints in public key */ + DSA_INTS = 5, /* DSA ints in private key */ + MAX_SALT_SIZE = 64, /* MAX PKCS Salt length */ + MAX_IV_SIZE = 64, /* MAX PKCS Iv length */ +#ifdef HAVE_SPHINCS + MAX_ENCODED_SIG_SZ = 51200, +#elif defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + MAX_ENCODED_SIG_SZ = 5120, +#elif !defined(NO_RSA) +#if defined(USE_FAST_MATH) && defined(FP_MAX_BITS) + MAX_ENCODED_SIG_SZ = FP_MAX_BITS / 8, +#elif (defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)) && \ + defined(SP_INT_BITS) + MAX_ENCODED_SIG_SZ = (SP_INT_BITS + 7) / 8, +#elif defined(WOLFSSL_HAPROXY) + MAX_ENCODED_SIG_SZ = 1024, /* Supports 8192 bit keys */ +#else + MAX_ENCODED_SIG_SZ = 512, /* Supports 4096 bit keys */ +#endif +#elif defined(HAVE_ECC) + MAX_ENCODED_SIG_SZ = 140, +#elif defined(HAVE_CURVE448) + MAX_ENCODED_SIG_SZ = 114, +#else + MAX_ENCODED_SIG_SZ = 64, +#endif + MAX_SIG_SZ = 256, + MAX_ALGO_SZ = 20, + MAX_LENGTH_SZ = WOLFSSL_ASN_MAX_LENGTH_SZ, /* Max length size for DER encoding */ + MAX_SHORT_SZ = (1 + 1 + 5), /* asn int + byte len + 5 byte length */ + MAX_SEQ_SZ = (1 + MAX_LENGTH_SZ), /* enum(seq | con) + length(5) */ + MAX_SET_SZ = (1 + MAX_LENGTH_SZ), /* enum(set | con) + length(5) */ + MAX_OCTET_STR_SZ = (1 + MAX_LENGTH_SZ), /* enum(set | con) + length(5) */ + MAX_EXP_SZ = (1 + MAX_LENGTH_SZ), /* enum(contextspec|con|exp) + length(5) */ + MAX_PRSTR_SZ = (1 + MAX_LENGTH_SZ), /* enum(prstr) + length(5) */ + MAX_VERSION_SZ = 5, /* enum + id + version(byte) + (header(2))*/ + MAX_ENCODED_DIG_ASN_SZ = (5 + MAX_LENGTH_SZ), /* enum(bit or octet) + length(5) */ + MAX_ENCODED_DIG_SZ = 64 + MAX_ENCODED_DIG_ASN_SZ, /* asn header + sha512 */ + MAX_RSA_INT_SZ = (512 + 1 + MAX_LENGTH_SZ), /* RSA raw sz 4096 for bits + tag + len(5) */ + MAX_DSA_INT_SZ = (384 + 1 + MAX_LENGTH_SZ), /* DSA raw sz 3072 for bits + tag + len(5) */ + MAX_DSA_PUBKEY_SZ = (DSA_PUB_INTS * MAX_DSA_INT_SZ) + (2 * MAX_SEQ_SZ) + + 2 + MAX_LENGTH_SZ, /* Maximum size of a DSA public + key taken from wc_SetDsaPublicKey. */ + MAX_DSA_PRIVKEY_SZ = (DSA_INTS * MAX_DSA_INT_SZ) + MAX_SEQ_SZ + + MAX_VERSION_SZ, /* Maximum size of a DSA Private + key taken from DsaKeyIntsToDer. */ +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + MAX_PQC_PUBLIC_KEY_SZ = 2592, /* Maximum size of a Dilithium public key. */ +#endif + MAX_RSA_E_SZ = 16, /* Max RSA public e size */ + MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */ + MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */ + MAX_DER_DIGEST_SZ = MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, + /* Maximum DER digest size */ + MAX_DER_DIGEST_ASN_SZ = MAX_ENCODED_DIG_ASN_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, + /* Maximum DER digest ASN header size */ + /* Max X509 header length indicates the + * max length + 2 ('\n', '\0') */ +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS) + MAX_X509_HEADER_SZ = (48 + 2), /* Maximum PEM Header/Footer Size */ +#else + MAX_X509_HEADER_SZ = (37 + 2), /* Maximum PEM Header/Footer Size */ +#endif + +#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM) + MAX_PUBLIC_KEY_SZ = MAX_PQC_PUBLIC_KEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, +#else + MAX_PUBLIC_KEY_SZ = MAX_DSA_PUBKEY_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, +#endif +#ifdef WOLFSSL_ENCRYPTED_KEYS + HEADER_ENCRYPTED_KEY_SIZE = 88 /* Extra header size for encrypted key */ +#else + HEADER_ENCRYPTED_KEY_SIZE = 0 +#endif +}; +#ifndef WC_MAX_DIGEST_SIZE +#define WC_MAX_DIGEST_SIZE 64 +#endif +#ifndef WC_MAX_BLOCK_SIZE +#define WC_MAX_BLOCK_SIZE 128 +#endif + +#ifdef WOLFSSL_CERT_GEN + /* Used in asn.c MakeSignature for ECC and RSA non-blocking/async */ + enum CertSignState { + CERTSIGN_STATE_BEGIN, + CERTSIGN_STATE_DIGEST, + CERTSIGN_STATE_ENCODE, + CERTSIGN_STATE_DO + }; - /* opaque math variable type */ - #if defined(USE_FAST_MATH) - struct fp_int; - #define MATH_INT_T struct fp_int - #elif defined(USE_INTEGER_HEAP_MATH) - struct mp_int; - #define MATH_INT_T struct mp_int + typedef struct CertSignCtx { + #ifdef WOLFSSL_NO_MALLOC + byte sig[MAX_ENCODED_SIG_SZ]; + byte digest[WC_MAX_DIGEST_SIZE]; + #ifndef NO_RSA + byte encSig[MAX_DER_DIGEST_SZ]; + #endif #else - struct sp_int; - #define MATH_INT_T struct sp_int + byte* sig; + byte* digest; + #ifndef NO_RSA + byte* encSig; + #endif #endif + #ifndef NO_RSA + int encSigSz; + #endif + int state; /* enum CertSignState */ + } CertSignCtx; - #ifdef __cplusplus - } /* extern "C" */ - #endif +#endif /* WOLFSSL_CERT_GEN */ + + +#ifdef __cplusplus + } /* extern "C" */ +#endif #endif /* WOLF_CRYPT_TYPES_H */ diff --git a/src/wolfssl/wolfcrypt/visibility.h b/src/wolfssl/wolfcrypt/visibility.h index fc7e485..b8499bd 100644 --- a/src/wolfssl/wolfcrypt/visibility.h +++ b/src/wolfssl/wolfcrypt/visibility.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/wc_encrypt.h b/src/wolfssl/wolfcrypt/wc_encrypt.h index 4dfc84c..00175e2 100644 --- a/src/wolfssl/wolfcrypt/wc_encrypt.h +++ b/src/wolfssl/wolfcrypt/wc_encrypt.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/wc_lms.h b/src/wolfssl/wolfcrypt/wc_lms.h index a4880a9..5c3e4a2 100644 --- a/src/wolfssl/wolfcrypt/wc_lms.h +++ b/src/wolfssl/wolfcrypt/wc_lms.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -384,7 +384,11 @@ typedef struct wc_LmsParamsMap { /* Identifier of parameters. */ enum wc_LmsParm id; /* String representation of identifier of parameters. */ +#ifdef WOLFSSL_NAMES_STATIC + const char str[32]; /* large enough for largest string in wc_lms_map[] */ +#else const char* str; +#endif /* LMS parameter set. */ LmsParams params; } wc_LmsParamsMap; diff --git a/src/wolfssl/wolfcrypt/wc_mlkem.h b/src/wolfssl/wolfcrypt/wc_mlkem.h index f79e188..649a73d 100644 --- a/src/wolfssl/wolfcrypt/wc_mlkem.h +++ b/src/wolfssl/wolfcrypt/wc_mlkem.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -146,9 +146,6 @@ struct MlKemKey { extern "C" { #endif -/* For backward compatibility */ -typedef struct MlKemKey KyberKey; - WOLFSSL_LOCAL void mlkem_init(void); diff --git a/src/wolfssl/wolfcrypt/wc_pkcs11.h b/src/wolfssl/wolfcrypt/wc_pkcs11.h index fdc51e0..803a1a6 100644 --- a/src/wolfssl/wolfcrypt/wc_pkcs11.h +++ b/src/wolfssl/wolfcrypt/wc_pkcs11.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/wc_port.h b/src/wolfssl/wolfcrypt/wc_port.h index a33fbf4..c0fd47f 100644 --- a/src/wolfssl/wolfcrypt/wc_port.h +++ b/src/wolfssl/wolfcrypt/wc_port.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -138,6 +138,15 @@ #endif #endif +#ifndef WC_OMIT_FRAME_POINTER + #if defined(__GNUC__) + #define WC_OMIT_FRAME_POINTER \ + __attribute__((optimize("-fomit-frame-pointer"))) + #else + #define WC_OMIT_FRAME_POINTER + #endif +#endif + /* THREADING/MUTEX SECTION */ #if defined(SINGLE_THREADED) && defined(NO_FILESYSTEM) /* No system headers required for build. */ @@ -268,6 +277,9 @@ #if !defined(CONFIG_PTHREAD_IPC) && !defined(CONFIG_POSIX_THREADS) #error "Threading needs CONFIG_PTHREAD_IPC / CONFIG_POSIX_THREADS" #endif + #ifdef max + #undef max + #endif #if KERNEL_VERSION_NUMBER >= 0x30100 #include #include @@ -277,6 +289,7 @@ #include #include #endif + #define max MAX #endif #elif defined(WOLFSSL_TELIT_M2MB) @@ -1520,7 +1533,8 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #ifndef WOLFSSL_NO_FENCE #ifdef XFENCE /* use user-supplied XFENCE definition. */ - #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) + #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(__STDC_NO_ATOMICS__) #include #define XFENCE() atomic_thread_fence(memory_order_seq_cst) #elif defined(__GNUC__) && (__GNUC__ == 4) && \ @@ -1532,8 +1546,24 @@ WOLFSSL_ABI WOLFSSL_API int wolfCrypt_Cleanup(void); #define XFENCE() WC_DO_NOTHING #elif defined (__i386__) || defined(__x86_64__) #define XFENCE() XASM_VOLATILE("lfence") - #elif (defined (__arm__) && (__ARM_ARCH > 6)) || defined(__aarch64__) + #elif defined (__arm__) && (__ARM_ARCH > 6) #define XFENCE() XASM_VOLATILE("isb") + #elif defined(__aarch64__) + /* Change ".inst 0xd50330ff" to "sb" when compilers support it. */ + #ifdef WOLFSSL_ARMASM_BARRIER_SB + #define XFENCE() XASM_VOLATILE(".inst 0xd50330ff") + #elif defined(WOLFSSL_ARMASM_BARRIER_DETECT) + extern int aarch64_use_sb; + #define XFENCE() \ + do { \ + if (aarch64_use_sb) \ + XASM_VOLATILE(".inst 0xd50330ff"); \ + else \ + XASM_VOLATILE("isb"); \ + } while (0) + #else + #define XFENCE() XASM_VOLATILE("isb") + #endif #elif defined(__riscv) #define XFENCE() XASM_VOLATILE("fence") #elif defined(__PPC__) || defined(__POWERPC__) diff --git a/src/wolfssl/wolfcrypt/wc_xmss.h b/src/wolfssl/wolfcrypt/wc_xmss.h index e59df61..68cedaf 100644 --- a/src/wolfssl/wolfcrypt/wc_xmss.h +++ b/src/wolfssl/wolfcrypt/wc_xmss.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/wolfevent.h b/src/wolfssl/wolfcrypt/wolfevent.h index d6731d1..04dbceb 100644 --- a/src/wolfssl/wolfcrypt/wolfevent.h +++ b/src/wolfssl/wolfcrypt/wolfevent.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfcrypt/wolfmath.h b/src/wolfssl/wolfcrypt/wolfmath.h index e2e8545..638a0b9 100644 --- a/src/wolfssl/wolfcrypt/wolfmath.h +++ b/src/wolfssl/wolfcrypt/wolfmath.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -83,11 +83,17 @@ This library provides big integer math functions. #if !defined(NO_BIG_INT) /* common math functions */ -MP_API int get_digit_count(const mp_int* a); -MP_API mp_digit get_digit(const mp_int* a, int n); -MP_API int get_rand_digit(WC_RNG* rng, mp_digit* d); +MP_API int mp_get_digit_count(const mp_int* a); +MP_API mp_digit mp_get_digit(const mp_int* a, int n); +MP_API int mp_get_rand_digit(WC_RNG* rng, mp_digit* d); WOLFSSL_LOCAL void mp_reverse(unsigned char *s, int len); +#if defined(HAVE_FIPS) || defined(HAVE_SELFTEST) +#define get_digit_count mp_get_digit_count +#define get_digit mp_get_digit +#define get_rand_digit mp_get_rand_digit +#endif + WOLFSSL_API int mp_cond_copy(mp_int* a, int copy, mp_int* b); WOLFSSL_API int mp_rand(mp_int* a, int digits, WC_RNG* rng); #endif diff --git a/src/wolfssl/wolfcrypt/xmss.h b/src/wolfssl/wolfcrypt/xmss.h index 9944862..2f7d7a8 100644 --- a/src/wolfssl/wolfcrypt/xmss.h +++ b/src/wolfssl/wolfcrypt/xmss.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/src/wolfssl/wolfio.h b/src/wolfssl/wolfio.h index de45a18..0673b88 100644 --- a/src/wolfssl/wolfio.h +++ b/src/wolfssl/wolfio.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, From e2c842881124a8feb315f4e88e00cfedab174434 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Fri, 15 Aug 2025 14:12:24 -0700 Subject: [PATCH 10/13] Improve Arduino Examples --- .github/SECURITY.md | 12 ++ .github/workflows/arduino.yml | 307 ++++++++++++++++++++++++++++++++++ .gitignore | 23 +-- 3 files changed, 331 insertions(+), 11 deletions(-) create mode 100644 .github/SECURITY.md create mode 100644 .github/workflows/arduino.yml diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..2bab9b6 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,12 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a vulnerability, please report it to support@wolfssl.com + + 1. Include a detailed description + 2. Include method to reproduce and/or method of discovery + 3. We will evaluate the report promptly and respond to you with findings. + 4. We will credit you with the report if you would like. + +**Please keep the vulnerability private** until a fix has been released. diff --git a/.github/workflows/arduino.yml b/.github/workflows/arduino.yml new file mode 100644 index 0000000..1f1b669 --- /dev/null +++ b/.github/workflows/arduino.yml @@ -0,0 +1,307 @@ +name: Arduino CI Build (4 of 4) Arduino-wolfSSL + +# +# Test local Arduino examples with LATEST github master branch wolfssl +# +# These 4 workflows across 3 repos are interdependent for the current $REPO_OWNER: +# +# Arduino CI Build 1: https://github.com/$REPO_OWNER/wolfssl # /.github/workflows/arduino.yml +# - Builds Arduino library from local clone of wolfssl master branch +# - Fetches examples from https://github.com/$REPO_OWNER/wolfssl-examples +# +# Arduino CI Build 2: https://github.com/$REPO_OWNER/wolfssl-examples # /.github/workflows/arduino-release.yml +# - Tests examples based on latest published release of Arduino library, NOT latest on wolfssl github. +# - Should be identical to Arduino CI Build 3 in every way but wolfssl install. +# - Copies only compile script from wolfssl-examples +# - Builds local examples +# - No other repos used +# +# Arduino CI Build 3: https://github.com/$REPO_OWNER/wolfssl-examples # /.github/workflows/arduino.yml +# - Fetches current wolfSSL from https://github.com/$REPO_OWNER/wolfssl +# - Creates an updated Arduino library +# - Compiles local examples +# - Contains the source of `compile-all-examples.sh` and respective board-list.txt +# +# THIS Arduino CI Build 4: https://github.com/$REPO_OWNER/Arduino-wolfssl # /.github/workflows/arduino.yml +# - Assembles and installs an updated Arduino wolfssl library from LOCAL Arduino-wolfSSL repo master (main) source +# - Copies only compile script and board list from wolfssl-examples (no examples copied) +# - Builds local examples +# - No other repos used +# +# +# ** NOTE TO MAINTAINERS ** +# +# Consider using winmerge or similar tool to keep the 4 arduino[-release].yml files in relative sync. +# Although there are some specific differences, most of the contents are otherwise identical. +# +# See https://github.com/wolfSSL/Arduino-wolfSSL +# +# To test locally: +# cd [your WOLFSSL_ROOT], e.g. cd /mnt/c/workspace/wolfssl-$USER +# [optional checkout] e.g. git checkout tags/v5.8.2-stable +# pushd ./IDE/ARDUINO +# export ARDUINO_ROOT="$HOME/Arduino/libraries" +# ./wolfssl-arduino.sh INSTALL +# cd [your WOLFSSL_EXAMPLES_ROOT] e.g. /mnt/c/workspace/wolfssl-examples-$USER +# + +# START OF COMMON SECTION +on: + push: + branches: [ '**', 'master', 'main', 'release/**' ] + + pull_request: + branches: [ '**' ] + + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +# END OF COMMON SECTION + +jobs: + build: + # if: github.repository_owner == 'wolfssl' + runs-on: ubuntu-latest + env: + REPO_OWNER: ${{ github.repository_owner }} + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Install Arduino CLI + run: | + # Script to fetch and run install.sh from arduino/arduino-cli + + # The install script will test to see if the recently installed apps in in the path + # So set it up in advance: + mkdir -p "${PWD}/bin" + echo "${PWD}/bin" >> $GITHUB_PATH + + # Sets the install directory to a consistent path at the repo root. + ROOT_BIN="$GITHUB_WORKSPACE/bin" + + # Ensures that BINDIR exists before the installer runs + mkdir -p "$ROOT_BIN" + + # Save as a lobal environment variable + echo "$ROOT_BIN" >> "$GITHUB_PATH" + + # Download and run install script from Arduino: + # -S show errors; -L follow redirects; -v Verbose + set +e # don't abort on error + set -o pipefail + + curl -vSL --retry 5 --retry-delay 10 \ + https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh \ + | sh -x + rc=$? + c_rc=${PIPESTATUS[0]} # curl's exit code + s_rc=${PIPESTATUS[1]} # sh's exit code + + set -e # restore default abort-on-error + + # If there was a curl error, we have our own local copy that is more reliable and can add our own debugging + if [ "$rc" -ne 0 ]; then + echo "Primary install failed: curl=$c_rc, sh=$s_rc. Falling back..." >&2 + echo "Using local copy of arduino_install.sh" + pushd ./Arduino/sketches + chmod +x ./arduino_install.sh + + # Mimic curl install, does not use current directory: + BINDIR="$ROOT_BIN" sh -x ./arduino_install.sh + popd + else + echo "Alternative install script not needed." + fi + + - name: Confirm Arduino CLI install + run: arduino-cli version + + - name: Setup Arduino CLI + run: | + arduino-cli config init + arduino-cli core update-index + arduino-cli config add board_manager.additional_urls https://www.pjrc.com/teensy/package_teensy_index.json + arduino-cli core update-index + arduino-cli config add board_manager.additional_urls https://arduino.esp8266.com/stable/package_esp8266com_index.json + arduino-cli core update-index + arduino-cli core install esp32:esp32 # ESP32 + arduino-cli core install arduino:avr # Arduino Uno, Mega, Nano + arduino-cli core install arduino:sam # Arduino Due + arduino-cli core install arduino:samd # Arduino Zero + arduino-cli core install teensy:avr # PJRC Teensy + arduino-cli core install esp8266:esp8266 # ESP8266 + arduino-cli core install arduino:mbed_nano # nanorp2040connect + arduino-cli core install arduino:mbed_portenta # portenta_h7_m7 + arduino-cli core install arduino:mbed_edge + # sudo "/home/$USER/.arduino15/packages/arduino/hardware/mbed_nano/4.2.4/post_install.sh" + arduino-cli core install arduino:renesas_uno + arduino-cli lib install "ArduinoJson" # Example dependency + arduino-cli lib install "WiFiNINA" # ARDUINO_SAMD_NANO_33_IOT + arduino-cli lib install "Ethernet" # Install Ethernet library + arduino-cli lib install "Bridge" # Pseudo-network for things like arduino:samd:tian + + - name: Set job environment variables + run: | + # Script to assign some common environment variables after everything is installed + + ICON_OK=$(printf "\xE2\x9C\x85") + ICON_FAIL=$(printf "\xE2\x9D\x8C") + + echo "GITHUB_WORK=$(realpath "$GITHUB_WORKSPACE/../..")" >> "$GITHUB_ENV" + echo "ARDUINO_ROOT=$(realpath "$HOME/Arduino/libraries")" >> "$GITHUB_ENV" + + # Show predefined summary: + echo "GITHUB_WORKSPACE = $GITHUB_WORKSPACE" + + # Show assigned build:env values (e.g. "wolfssl", "gojimmpi" or other owners): + echo "REPO_OWNER = $REPO_OWNER" + + echo "GITHUB_ENV=$GITHUB_ENV" + + # Show our custom values: + echo "GITHUB_WORK = $GITHUB_WORK" + echo "ARDUINO_ROOT = $ARDUINO_ROOT" + + # WOLFSSL_EXAMPLES_ROOT is the report root, not example location + # echo "WOLFSSL_EXAMPLES_ROOT = $WOLFSSL_EXAMPLES_ROOT" + + # - name: Show wolfssl-examples + # (not used, as wolfssl source is already here in ARduino-wolfSSL) + + # end Show wolfssl-examples + + # - name: Shallow clone wolfssl + # (not used, as wolfssl source is already here in Arduino-wolfSSL) + # + + # ** END ** Set job environment variables + + - name: Get wolfssl-examples + run: | + # The wolfSSL examples should already be installed in this Arduino-wolfssl/examples directory + + echo "Current pwd for wolfssl-examples clone fetch: $(pwd)" + echo "Examples found:" + find ./examples -type f | sort + + # ** END ** Get wolfssl-examples + + - name: Install wolfSSL Arduino library + run: | + # Script for installing wolfssl from this Arduino-wolfssl library repository + # + # Steps are equivalent of: + # + # arduino-cli lib install "wolfSSL" + # + # But using the current repo as the source: + mkdir -p "$ARDUINO_ROOT/wolfssl" + + # Methods of installing Arduino library: + # 1) arduino-cli lib install "wolfSSL" + # 2) manual copy of files (typical of the Arduino-wolfssl repo) + # 3) run ./wolfssl-arduino.sh INSTALL (typical of the wolfssl repo) + + # Copy all file in current directory as root of the wolfssl library + echo "cp [root files] \"$ARDUINO_ROOT/wolfssl/src\"" + for f in ./*; do + if [ -f "$f" ]; then + cp "$f" "$ARDUINO_ROOT/wolfssl/" + fi + done + + # Only 2 directories are needed in the Arduino library: `src` and [optional] `examples`: + echo "cp -r \"./src\" \"$ARDUINO_ROOT/wolfssl/src\"" + cp -r ./src "$ARDUINO_ROOT/wolfssl/src" + + echo "cp -r \"./examples\" \"$ARDUINO_ROOT/wolfssl/examples\"" + cp -r ./examples "$ARDUINO_ROOT/wolfssl/examples" + + # ** END ** Install wolfSSL Arduino library + + - name: List installed Arduino libraries + run: arduino-cli lib list + + - name: Get compile-all-examples.sh + run: | + # Fetch compile script FROM THE CURRENT OWNER. + # This repo is Arduino-wolfssl; we'll fetch the script from the wolfssl-examples for the same repository owner. + echo "Respository owner: $REPO_OWNER" + echo "Current directory: $PWD" + echo "Current pwd for wolfssl-examples clone fetch: $PWD" + WOLFSSL_EXAMPLES_DIRECTORY="$ARDUINO_ROOT/wolfssl/examples" + echo "WOLFSSL_EXAMPLES_DIRECTORY=$WOLFSSL_EXAMPLES_DIRECTORY" + + # Fetch script and board list into WOLFSSL_EXAMPLES_DIRECTORY + # TODO edit PR branch path: + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/examples_dev/Arduino/sketches/board_list_v5.8.2.txt" -o "$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" + + # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. + FILE="$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" + + # Ensure the file exists + if [[ ! -f "$FILE" ]]; then + echo "File not found: $FILE" + exit 1 + fi + + # Check if the first line is "404: Not Found" + if [[ $(head -n 1 "$FILE") == "404: Not Found" ]]; then + echo "The first line is '404: Not Found'" + exit 1 + fi + + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/examples_dev/Arduino/sketches/compile-all-examples.sh" -o "$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" + + # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. + FILE="$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" + + # Ensure the file exists + if [[ ! -f "$FILE" ]]; then + echo "File not found: $FILE" + exit 1 + fi + + # Check if the first line is "404: Not Found" + if [[ $(head -n 1 "$FILE") == "404: Not Found" ]]; then + echo "The first line is '404: Not Found'" + exit 1 + fi + + pushd "$WOLFSSL_EXAMPLES_DIRECTORY" + echo "Current directory: $PWD" + + echo "Current directory $PWD" + echo "Contents:" + ls -al + find ./ -type f | sort + + # ensure we can execute the script here (permissions lost during curl fetch) + chmod +x ./compile-all-examples.sh + echo "Found compile script: $(ls -al ./compile-all-examples.sh)" + popd + + # ** END ** Get compile-all-examples.sh + + # This will fail with Arduino published wolfSSL v5.7.6 and older + # as the examples moved. See https://github.com/wolfSSL/wolfssl/pull/8514 + # + - name: Compile Arduino Sketches for Various Boards + run: | + # Call the compile-all-examples.sh script to compile all the examples for each of the fqbn names in the local copy of board_list.txt + + echo "Current directory: $PWD" + echo "ARDUINO_ROOT: $ARDUINO_ROOT" + WOLFSSL_EXAMPLES_DIRECTORY="$ARDUINO_ROOT/wolfssl/examples" + echo "WOLFSSL_EXAMPLES_DIRECTORY: $WOLFSSL_EXAMPLES_DIRECTORY" + + echo "Change directory to Arduino examples..." + pushd "$WOLFSSL_EXAMPLES_DIRECTORY" + echo "Current directory: $PWD" + echo "Calling ./compile-all-examples.sh" + bash ./compile-all-examples.sh + popd + # End Compile Arduino Sketches for Various Boards diff --git a/.gitignore b/.gitignore index 436e3ed..1c295c7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,12 @@ -################################################################################ -# This .gitignore file was automatically created by Microsoft(R) Visual Studio. -################################################################################ - -/.vs -/src/wolfcrypt/src/fips.c -/src/wolfcrypt/src/fips_test.c -/src/wolfcrypt/src/selftest.c -/src/wolfcrypt/src/wolfcrypt_first.c -/src/wolfcrypt/src/wolfcrypt_last.c -/src/wolfssl/wolfcrypt/fips.h +################################################################################ +# This .gitignore file was automatically created by Microsoft(R) Visual Studio. +################################################################################ + +/.vs +/src/wolfcrypt/src/fips.c +/src/wolfcrypt/src/fips_test.c +/src/wolfcrypt/src/selftest.c +/src/wolfcrypt/src/wolfcrypt_first.c +/src/wolfcrypt/src/wolfcrypt_last.c +/src/wolfssl/wolfcrypt/fips.h +/**/*.bak From 5e9321d8663cab5c71c46070e63dfec891908fa5 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Wed, 3 Sep 2025 07:54:35 -0700 Subject: [PATCH 11/13] Correct wolfssl-examples script fetch branch --- .github/workflows/arduino.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/arduino.yml b/.github/workflows/arduino.yml index 1f1b669..9df1a40 100644 --- a/.github/workflows/arduino.yml +++ b/.github/workflows/arduino.yml @@ -237,7 +237,7 @@ jobs: # Fetch script and board list into WOLFSSL_EXAMPLES_DIRECTORY # TODO edit PR branch path: - curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/examples_dev/Arduino/sketches/board_list_v5.8.2.txt" -o "$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/board_list_v5.8.2.txt" -o "$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. FILE="$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" @@ -254,7 +254,7 @@ jobs: exit 1 fi - curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/examples_dev/Arduino/sketches/compile-all-examples.sh" -o "$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/compile-all-examples.sh" -o "$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. FILE="$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" From 05ab92c46f3b571dec64f810c13f6bf147926e68 Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Mon, 17 Nov 2025 09:17:12 -0800 Subject: [PATCH 12/13] Update Arduino workflow with parameterized matrix --- .github/workflows/arduino.yml | 160 ++++++++++++++++++++++++++++------ 1 file changed, 131 insertions(+), 29 deletions(-) diff --git a/.github/workflows/arduino.yml b/.github/workflows/arduino.yml index 9df1a40..982814a 100644 --- a/.github/workflows/arduino.yml +++ b/.github/workflows/arduino.yml @@ -38,7 +38,7 @@ name: Arduino CI Build (4 of 4) Arduino-wolfSSL # # To test locally: # cd [your WOLFSSL_ROOT], e.g. cd /mnt/c/workspace/wolfssl-$USER -# [optional checkout] e.g. git checkout tags/v5.8.2-stable +# [optional checkout] e.g. git checkout tags/v5.8.4-stable # pushd ./IDE/ARDUINO # export ARDUINO_ROOT="$HOME/Arduino/libraries" # ./wolfssl-arduino.sh INSTALL @@ -56,16 +56,63 @@ on: workflow_dispatch: concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + # Same branch push cancels other jobs. Other PR branches untouched + + group: ${{ github.workflow }}-${{ github.ref_name }} cancel-in-progress: true + # END OF COMMON SECTION jobs: build: + name: Compile (${{ matrix.fqbn }}) + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # if: github.repository_owner == 'wolfssl' + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + fqbn: + # When editing this list, be sure to also edit file: board_list.txt + # The compile-all-examples.sh optionally takes a FQBN parameter to + # optionally compile all examples ONLY for the respective fully qualified board name. + # See https://github.com/wolfSSL/wolfssl-examples/blob/master/Arduino/sketches/board_list.txt + + - arduino:avr:ethernet + - arduino:avr:leonardoeth + - arduino:avr:mega + - arduino:avr:nano + - arduino:avr:uno + - arduino:avr:yun + - arduino:samd:mkrwifi1010 + - arduino:samd:mkr1000 + - arduino:samd:mkrfox1200 + - arduino:mbed_edge:edge_control + - arduino:mbed_nano:nanorp2040connect + - arduino:mbed_portenta:envie_m7 + - arduino:mbed_portenta:portenta_x8 + - arduino:renesas_uno:unor4wifi + - arduino:sam:arduino_due_x + - arduino:samd:arduino_zero_native + - arduino:samd:tian + - esp32:esp32:esp32 + - esp32:esp32:esp32s2 + - esp32:esp32:esp32s3 + - esp32:esp32:esp32c3 + - esp32:esp32:esp32c6 + - esp32:esp32:esp32h2 + - esp8266:esp8266:generic + - teensy:avr:teensy40 + + # Not yet supported, not in standard library + # - esp32:esp32:nano_nora + + # End strategy matrix env: REPO_OWNER: ${{ github.repository_owner }} + steps: - name: Checkout Repository uses: actions/checkout@v4 @@ -74,7 +121,7 @@ jobs: run: | # Script to fetch and run install.sh from arduino/arduino-cli - # The install script will test to see if the recently installed apps in in the path + # The install script will test to see if the recently installed apps in the path # So set it up in advance: mkdir -p "${PWD}/bin" echo "${PWD}/bin" >> $GITHUB_PATH @@ -85,7 +132,7 @@ jobs: # Ensures that BINDIR exists before the installer runs mkdir -p "$ROOT_BIN" - # Save as a lobal environment variable + # Save as a global environment variable echo "$ROOT_BIN" >> "$GITHUB_PATH" # Download and run install script from Arduino: @@ -116,34 +163,53 @@ jobs: echo "Alternative install script not needed." fi - - name: Confirm Arduino CLI install + - name: Confirm Arduino CLI Install run: arduino-cli version + - name: Derive CORE_ID (vendor:arch from FQBN) + run: | + CORE_ID="$(echo '${{ matrix.fqbn }}' | cut -d: -f1-2)" + echo "CORE_ID=$CORE_ID" >> "$GITHUB_ENV" + - name: Setup Arduino CLI run: | arduino-cli config init - arduino-cli core update-index + + # wait 10 minutes for big downloads (or use 0 for no limit) + arduino-cli config set network.connection_timeout 600s + arduino-cli config add board_manager.additional_urls https://www.pjrc.com/teensy/package_teensy_index.json - arduino-cli core update-index arduino-cli config add board_manager.additional_urls https://arduino.esp8266.com/stable/package_esp8266com_index.json arduino-cli core update-index - arduino-cli core install esp32:esp32 # ESP32 - arduino-cli core install arduino:avr # Arduino Uno, Mega, Nano - arduino-cli core install arduino:sam # Arduino Due - arduino-cli core install arduino:samd # Arduino Zero - arduino-cli core install teensy:avr # PJRC Teensy - arduino-cli core install esp8266:esp8266 # ESP8266 - arduino-cli core install arduino:mbed_nano # nanorp2040connect - arduino-cli core install arduino:mbed_portenta # portenta_h7_m7 - arduino-cli core install arduino:mbed_edge + + echo "CORE_ID: $CORE_ID" + arduino-cli core install "$CORE_ID" + + # The above is instead of: + # arduino-cli core install esp32:esp32 # ESP32 + # arduino-cli core install arduino:avr # Arduino Uno, Mega, Nano + # arduino-cli core install arduino:sam # Arduino Due + # arduino-cli core install arduino:samd # Arduino Zero + # arduino-cli core install teensy:avr # PJRC Teensy + # arduino-cli core install esp8266:esp8266 # ESP8266 + # arduino-cli core install arduino:mbed_nano # nanorp2040connect + # arduino-cli core install arduino:mbed_portenta # portenta_h7_m7 + # arduino-cli core install arduino:mbed_edge + # arduino-cli core install arduino:renesas_uno + + # For reference: + + # mbed nano not yet tested # sudo "/home/$USER/.arduino15/packages/arduino/hardware/mbed_nano/4.2.4/post_install.sh" - arduino-cli core install arduino:renesas_uno + + # Always install networking (not part of FQBN matrix) + # The first one also creates directory: /home/runner/Arduino/libraries arduino-cli lib install "ArduinoJson" # Example dependency arduino-cli lib install "WiFiNINA" # ARDUINO_SAMD_NANO_33_IOT arduino-cli lib install "Ethernet" # Install Ethernet library arduino-cli lib install "Bridge" # Pseudo-network for things like arduino:samd:tian - - name: Set job environment variables + - name: Set Job Environment Variables run: | # Script to assign some common environment variables after everything is installed @@ -166,10 +232,42 @@ jobs: echo "ARDUINO_ROOT = $ARDUINO_ROOT" # WOLFSSL_EXAMPLES_ROOT is the report root, not example location - # echo "WOLFSSL_EXAMPLES_ROOT = $WOLFSSL_EXAMPLES_ROOT" + echo "WOLFSSL_EXAMPLES_ROOT = $WOLFSSL_EXAMPLES_ROOT" + + - name: Compute cache key parts + id: parts + shell: bash + run: | + # From FQBN "vendor:arch:board" get "vendor:arch" + CORE_ID="$(echo "${{ matrix.fqbn }}" | awk -F: '{print $1 ":" $2}')" + echo "CORE_ID=$CORE_ID" >> "$GITHUB_OUTPUT" + + # Also expose vendor only for broad fallbacks + VENDOR="$(echo "$CORE_ID" | cut -d: -f1)" + echo "VENDOR=$VENDOR" >> "$GITHUB_OUTPUT" + + - name: Cache Arduino packages + uses: actions/cache@v4 + with: + path: | + ~/.arduino15 + ~/.cache/arduino + ~/.arduino15/staging + + # Arduino libraries + # Specific to Arduino CI Build (2 of 4) Arduinbo Release wolfSSL for Local Examples + # Include all libraries, as the latest Arduino-wolfSSL will only change upon release. + ~/Arduino/libraries + # Ensure wolfssl is not cached, we're always using the latest. See separate cache. + !~/Arduino/libraries/wolfssl + key: arduino-${{ runner.os }}-${{ env.CORE_ID }}-${{ hashFiles('Arduino/sketches/board_list.txt') }} + + restore-keys: | + arduino-${{ runner.os }}-${{ env.CORE_ID }}- + arduino-${{ runner.os }}- # - name: Show wolfssl-examples - # (not used, as wolfssl source is already here in ARduino-wolfSSL) + # (not used, as wolfssl source is already here in Arduino-wolfSSL) # end Show wolfssl-examples @@ -177,7 +275,7 @@ jobs: # (not used, as wolfssl source is already here in Arduino-wolfSSL) # - # ** END ** Set job environment variables + # ** END ** Shallow clone wolfssl - name: Get wolfssl-examples run: | @@ -197,7 +295,8 @@ jobs: # # arduino-cli lib install "wolfSSL" # - # But using the current repo as the source: + # But using the current repo as the source (delete for matrix cache): + rm -rf "$ARDUINO_ROOT/wolfssl" mkdir -p "$ARDUINO_ROOT/wolfssl" # Methods of installing Arduino library: @@ -236,25 +335,26 @@ jobs: echo "WOLFSSL_EXAMPLES_DIRECTORY=$WOLFSSL_EXAMPLES_DIRECTORY" # Fetch script and board list into WOLFSSL_EXAMPLES_DIRECTORY - # TODO edit PR branch path: - curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/board_list_v5.8.2.txt" -o "$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" + # TODO edit board list name upon release and publish of wolfSSL 5.8.4 in Arduino-wolfSSL: + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/board_list_v5.8.2.txt" \ + -o "$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" - # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. FILE="$WOLFSSL_EXAMPLES_DIRECTORY/board_list.txt" - # Ensure the file exists + # Ensure the board list file exists if [[ ! -f "$FILE" ]]; then echo "File not found: $FILE" exit 1 fi - # Check if the first line is "404: Not Found" + # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. if [[ $(head -n 1 "$FILE") == "404: Not Found" ]]; then echo "The first line is '404: Not Found'" exit 1 fi - curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/compile-all-examples.sh" -o "$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" + curl -L "https://raw.githubusercontent.com/$REPO_OWNER/wolfssl-examples/master/Arduino/sketches/compile-all-examples.sh" \ + -o "$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" # Check if the first line is "404: Not Found" - which would indicate the curl path above is bad. FILE="$WOLFSSL_EXAMPLES_DIRECTORY/compile-all-examples.sh" @@ -297,11 +397,13 @@ jobs: echo "ARDUINO_ROOT: $ARDUINO_ROOT" WOLFSSL_EXAMPLES_DIRECTORY="$ARDUINO_ROOT/wolfssl/examples" echo "WOLFSSL_EXAMPLES_DIRECTORY: $WOLFSSL_EXAMPLES_DIRECTORY" + echo "FQBN = ${{ matrix.fqbn }}" echo "Change directory to Arduino examples..." pushd "$WOLFSSL_EXAMPLES_DIRECTORY" echo "Current directory: $PWD" + ls -al echo "Calling ./compile-all-examples.sh" - bash ./compile-all-examples.sh + bash ./compile-all-examples.sh ./board_list.txt "${{ matrix.fqbn }}" popd # End Compile Arduino Sketches for Various Boards From 66cf9f46a9594ec5af7bb9f6d6a5610c87a4a99c Mon Sep 17 00:00:00 2001 From: gojimmypi Date: Sat, 22 Nov 2025 08:45:20 -0800 Subject: [PATCH 13/13] wolfssl 5.8.4 Release for Arduino --- ChangeLog.md | 84 +- LICENSING | 25 +- README | 259 +- README.md | 340 +- examples/template/template.ino | 9 +- examples/template/wolfssl_helper.c | 36 +- examples/template/wolfssl_helper.h | 2 +- examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino | 25 +- examples/wolfssl_client/wolfssl_client.ino | 92 +- examples/wolfssl_client_dtls/README.md | 28 + .../wolfssl_client_dtls.ino | 950 +++ examples/wolfssl_server/wolfssl_server.ino | 88 +- examples/wolfssl_server_dtls/README.md | 140 + .../wolfssl_server_dtls.ino | 984 ++++ examples/wolfssl_version/wolfssl_version.ino | 9 +- library.properties | 2 +- src/src/bio.c | 20 +- src/src/crl.c | 129 +- src/src/dtls.c | 12 +- src/src/dtls13.c | 4 +- src/src/internal.c | 3486 +++++------ src/src/keys.c | 66 +- src/src/ocsp.c | 107 +- src/src/pk.c | 327 +- src/src/quic.c | 9 +- src/src/sniffer.c | 125 +- src/src/ssl.c | 2556 +++------ src/src/ssl_asn1.c | 22 +- src/src/ssl_bn.c | 43 +- src/src/ssl_certman.c | 173 +- src/src/ssl_crypto.c | 152 +- src/src/ssl_load.c | 267 +- src/src/ssl_misc.c | 10 + src/src/ssl_p7p12.c | 32 +- src/src/ssl_sess.c | 18 +- src/src/ssl_sk.c | 1251 ++++ src/src/tls.c | 725 +-- src/src/tls13.c | 423 +- src/src/wolfio.c | 210 +- src/src/x509.c | 1248 ++-- src/src/x509_str.c | 148 +- src/user_settings.h | 164 +- src/wolfcrypt/src/aes.c | 2132 +++++-- src/wolfcrypt/src/asn.c | 1618 +++--- src/wolfcrypt/src/bio.c | 20 +- src/wolfcrypt/src/blake2b.c | 12 +- src/wolfcrypt/src/blake2s.c | 12 +- src/wolfcrypt/src/camellia.c | 12 +- src/wolfcrypt/src/chacha.c | 69 +- src/wolfcrypt/src/chacha20_poly1305.c | 38 +- src/wolfcrypt/src/cmac.c | 12 +- src/wolfcrypt/src/coding.c | 16 +- src/wolfcrypt/src/cpuid.c | 247 +- src/wolfcrypt/src/cryptocb.c | 249 +- src/wolfcrypt/src/curve25519.c | 6 +- src/wolfcrypt/src/des3.c | 4 +- src/wolfcrypt/src/dh.c | 15 +- src/wolfcrypt/src/dilithium.c | 2710 ++++++++- src/wolfcrypt/src/dsa.c | 6 +- src/wolfcrypt/src/ecc.c | 364 +- src/wolfcrypt/src/eccsi.c | 6 +- src/wolfcrypt/src/ed25519.c | 16 +- src/wolfcrypt/src/ed448.c | 20 +- src/wolfcrypt/src/error.c | 6 + src/wolfcrypt/src/evp.c | 131 +- src/wolfcrypt/src/fe_448.c | 581 +- src/wolfcrypt/src/fe_operations.c | 221 +- src/wolfcrypt/src/ge_448.c | 1592 ++--- src/wolfcrypt/src/ge_operations.c | 87 +- src/wolfcrypt/src/hash.c | 249 +- src/wolfcrypt/src/hmac.c | 79 +- src/wolfcrypt/src/hpke.c | 179 +- src/wolfcrypt/src/integer.c | 103 +- src/wolfcrypt/src/kdf.c | 389 +- src/wolfcrypt/src/logging.c | 316 +- src/wolfcrypt/src/md2.c | 17 +- src/wolfcrypt/src/memory.c | 57 +- src/wolfcrypt/src/misc.c | 55 +- src/wolfcrypt/src/pkcs12.c | 10 +- src/wolfcrypt/src/pkcs7.c | 1037 ++-- src/wolfcrypt/src/poly1305.c | 93 +- src/wolfcrypt/src/port/Espressif/esp32_mp.c | 2 +- src/wolfcrypt/src/port/Espressif/esp32_sha.c | 28 +- src/wolfcrypt/src/port/Espressif/esp32_util.c | 5 + .../src/port/Espressif/esp_sdk_mem_lib.c | 119 +- src/wolfcrypt/src/pwdbased.c | 70 +- src/wolfcrypt/src/random.c | 145 +- src/wolfcrypt/src/rsa.c | 149 +- src/wolfcrypt/src/sakke.c | 6 +- src/wolfcrypt/src/sha.c | 74 +- src/wolfcrypt/src/sha256.c | 285 +- src/wolfcrypt/src/sha3.c | 484 +- src/wolfcrypt/src/sha512.c | 430 +- src/wolfcrypt/src/sp_arm32.c | 3318 +++-------- src/wolfcrypt/src/sp_arm64.c | 3131 +++------- src/wolfcrypt/src/sp_armthumb.c | 2946 ++-------- src/wolfcrypt/src/sp_c32.c | 4681 +++------------ src/wolfcrypt/src/sp_c64.c | 5107 +++-------------- src/wolfcrypt/src/sp_cortexm.c | 3295 +++-------- src/wolfcrypt/src/sp_int.c | 66 +- src/wolfcrypt/src/sp_x86_64.c | 3611 +++--------- src/wolfcrypt/src/srp.c | 30 +- src/wolfcrypt/src/tfm.c | 821 +-- src/wolfcrypt/src/wc_encrypt.c | 140 +- src/wolfcrypt/src/wc_lms.c | 84 +- src/wolfcrypt/src/wc_lms_impl.c | 115 +- src/wolfcrypt/src/wc_mlkem.c | 90 + src/wolfcrypt/src/wc_mlkem_poly.c | 88 +- src/wolfcrypt/src/wc_pkcs11.c | 228 +- src/wolfcrypt/src/wc_port.c | 426 +- src/wolfcrypt/src/wc_xmss.c | 70 +- src/wolfcrypt/src/wc_xmss_impl.c | 12 +- src/wolfcrypt/src/wolfmath.c | 49 +- src/wolfssl/bio.c | 20 +- src/wolfssl/certs_test.h | 1062 ++-- src/wolfssl/certs_test_sm.h | 2913 ++++++++++ src/wolfssl/error-ssl.h | 2 +- src/wolfssl/evp.c | 131 +- src/wolfssl/internal.h | 233 +- src/wolfssl/ocsp.h | 8 + src/wolfssl/openssl/ec.h | 3 + src/wolfssl/openssl/evp.h | 2 +- src/wolfssl/openssl/opensslv.h | 10 +- src/wolfssl/openssl/ssl.h | 16 +- src/wolfssl/quic.h | 4 +- src/wolfssl/ssl.h | 185 +- src/wolfssl/test.h | 156 +- src/wolfssl/version.h | 4 +- src/wolfssl/wolfcrypt/aes.h | 227 +- src/wolfssl/wolfcrypt/ascon.h | 4 +- src/wolfssl/wolfcrypt/asn.h | 81 +- src/wolfssl/wolfcrypt/asn_public.h | 6 +- src/wolfssl/wolfcrypt/blake2.h | 14 +- src/wolfssl/wolfcrypt/chacha.h | 21 +- src/wolfssl/wolfcrypt/coding.h | 16 +- src/wolfssl/wolfcrypt/cpuid.h | 90 +- src/wolfssl/wolfcrypt/cryptocb.h | 84 +- src/wolfssl/wolfcrypt/dh.h | 22 +- src/wolfssl/wolfcrypt/dilithium.h | 84 + src/wolfssl/wolfcrypt/ecc.h | 9 + src/wolfssl/wolfcrypt/ed25519.h | 16 +- src/wolfssl/wolfcrypt/ed448.h | 16 +- src/wolfssl/wolfcrypt/error-crypt.h | 33 +- src/wolfssl/wolfcrypt/ext_xmss.h | 2 +- src/wolfssl/wolfcrypt/fe_operations.h | 19 +- src/wolfssl/wolfcrypt/ge_operations.h | 14 +- src/wolfssl/wolfcrypt/hash.h | 3 + src/wolfssl/wolfcrypt/hmac.h | 10 +- src/wolfssl/wolfcrypt/integer.h | 14 +- src/wolfssl/wolfcrypt/kdf.h | 18 + src/wolfssl/wolfcrypt/logging.h | 259 +- src/wolfssl/wolfcrypt/md5.h | 7 +- src/wolfssl/wolfcrypt/mem_track.h | 173 +- src/wolfssl/wolfcrypt/memory.h | 6 +- src/wolfssl/wolfcrypt/misc.h | 4 +- src/wolfssl/wolfcrypt/mlkem.h | 3 + src/wolfssl/wolfcrypt/oid_sum.h | 4 + src/wolfssl/wolfcrypt/pkcs11.h | 1 + src/wolfssl/wolfcrypt/pkcs7.h | 19 +- src/wolfssl/wolfcrypt/poly1305.h | 31 +- .../wolfcrypt/port/Espressif/esp-sdk-lib.h | 15 + src/wolfssl/wolfcrypt/pwdbased.h | 12 +- src/wolfssl/wolfcrypt/random.h | 23 +- src/wolfssl/wolfcrypt/rsa.h | 25 +- src/wolfssl/wolfcrypt/settings.h | 345 +- src/wolfssl/wolfcrypt/sha.h | 14 +- src/wolfssl/wolfcrypt/sha256.h | 23 +- src/wolfssl/wolfcrypt/sha3.h | 24 + src/wolfssl/wolfcrypt/sha512.h | 28 +- src/wolfssl/wolfcrypt/sp.h | 2 +- src/wolfssl/wolfcrypt/sp_int.h | 150 +- src/wolfssl/wolfcrypt/tfm.h | 11 +- src/wolfssl/wolfcrypt/types.h | 314 +- src/wolfssl/wolfcrypt/wc_mlkem.h | 5 - src/wolfssl/wolfcrypt/wc_port.h | 299 +- src/wolfssl/wolfcrypt/wolfmath.h | 9 + src/wolfssl/wolfio.h | 86 +- 177 files changed, 30966 insertions(+), 34169 deletions(-) create mode 100644 examples/wolfssl_client_dtls/README.md create mode 100644 examples/wolfssl_client_dtls/wolfssl_client_dtls.ino create mode 100644 examples/wolfssl_server_dtls/README.md create mode 100644 examples/wolfssl_server_dtls/wolfssl_server_dtls.ino create mode 100644 src/src/ssl_sk.c create mode 100644 src/wolfssl/certs_test_sm.h diff --git a/ChangeLog.md b/ChangeLog.md index 09728ee..ed7c9a8 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,76 @@ +# wolfSSL Release 5.8.4 (Nov. 20, 2025) + +Release 5.8.4 has been developed according to wolfSSL's development and QA +process (see link below) and successfully passed the quality criteria. +https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance + +NOTE: * --enable-heapmath is deprecated + * MD5 is now disabled by default + +PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. + +## Vulnerabilities +* [Low CVE-2025-12888] Vulnerability in X25519 constant-time cryptographic implementations due to timing side channels introduced by compiler optimizations and CPU architecture limitations, specifically with the Xtensa-based ESP32 chips. If targeting Xtensa it is recommended to use the low memory implementations of X25519, which is now turned on as the default for Xtensa. Thanks to Adrian Cinal for the report. Fixed in PR 9275. + + +* [Med. CVE-2025-11936] Potential DoS vulnerability due to a memory leak through multiple KeyShareEntry with the same group in malicious TLS 1.3 ClientHello messages. This affects users who are running wolfSSL on the server side with TLS 1.3. Thanks to Jaehun Lee and Kyungmin Bae, Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9117. + +* [Low CVE-2025-11935] PSK with PFS (Perfect Forward Secrecy) downgrades to PSK without PFS during TLS 1.3 handshake. If the client sends a ClientHello that has a key share extension and the server responds with a ServerHello that does not have a key share extension the connection would previously continue on without using PFS. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9112. + +* [Low CVE-2025-11934] Signature Algorithm downgrade from ECDSA P521 to P256 during TLS 1.3 handshake. When a client sends ECDSA P521 as the supported signature algorithm the server previously could respond as ECDSA P256 being the accepted signature algorithm and the connection would continue with using ECDSA P256. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9113. + + +* [Low CVE-2025-11933] DoS Vulnerability in wolfSSL TLS 1.3 CKS extension parsing. Previously duplicate CKS extensions were not rejected leading to a potential memory leak when processing a ClientHello. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9132. + + +* [Low CVE-2025-11931] Integer Underflow Leads to Out-of-Bounds Access in XChaCha20-Poly1305 Decrypt. This issue is hit specifically with a call to the function wc_XChaCha20Poly1305_Decrypt() which is not used with TLS connections, only from direct calls from an application. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. + +* [Low CVE-2025-11932] Timing Side-Channel in PSK Binder Verification. The server previously verified the TLS 1.3 PSK binder using a non-constant time method which could potentially leak information about the PSK binder. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. + +* [Low CVE-2025-12889] With TLS 1.2 connections a client can use any digest, specifically a weaker digest, rather than those in the CertificateRequest. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9395 + +## New Features +* New ML-KEM / ML-DSA APIs and seed/import PKCS8 support; added _new/_delete APIs for ML-KEM/ML-DSA. (PR 9039, 9000, 9049) +* Initial wolfCrypt FreeBSD kernel module support (PR 9392) +* Expanded PKCS7/CMS capabilities: decode SymmetricKeyPackage / OneSymmetricKey, add wc_PKCS7_GetEnvelopedDataKariRid, and allow PKCS7 builds with AES keywrap unset. (PR 9018, 9029, 9032) +* Add custom AES key wrap/unwrap callbacks and crypto callback copy/free operations. (PR 9002, 9309) +* Add support for certificate_authorities extension in ClientHello and certificate manager CA-type selection/unloading. (PR 9209, 9046) +* Large expansion of Rust wrapper modules: random, aes, rsa, ecc, dh, sha, hmac, cmac, ed25519/ed448, pbkdf2/PKCS#12, kdf/prf, SRTP KDFs, and conditional compilation options. (PR 9191, 9212, 9273, 9306, 9320, 9328, 9368, 9389, 9357, 9433) +* Rust: support optional heap and dev_id parameters and enable conditional compilation based on C build options. (PR 9407, 9433) +* STM32 fixes (benchmarking and platform fixes) and PSoC6 hardware acceleration additions. (PR 9228, 9256, 9185) +* STM32U5 added support for SAES and DHUK. (PR 9087) +* Add --enable-curl=tiny option for a smaller build when used with cURL. (PR 9174) + +## Improvements / Optimizations +* Regression test fixes and expansion: TLS 1.3/1.2 tests, ARDUINO examples, libssh2 tests, hostap workflows, and nightly test improvements. (PR 9096, 9141, 9091, 9122, 9388) +* Improved test ordering and CI test stability (random tests run order changes, FIPS test fixes). (PR 9204, 9257) +* Docs and readme fixes, docstring updates, AsconAEAD comment placement, and example certificate renewals. (PR 9131, 9293, 9262, 9429) +* Updated GPL exception lists (GPLv2 and GPLv3 exception updates: add Fetchmail and OpenVPN). (PR 9398, 9413) +* Introduced WOLFSSL_DEBUG_CERTS and additional debug/logging refinements. (PR 8902, 9055) +* Expanded crypto-callback support (SHA family, HKDF, SHA-224, sha512_family digest selection) and improved crypto-only build cases. (PR 9070, 9252, 9271, 9100, 9194) +* AES & HW offload improvements including AES-CTR support in PKCS11 driver and AES ECB offload sizing fix. (PR 9277, 9364) +* ESP32: PSRAM allocator support and SHA HW fixes for ESP-IDF v6/v5. (PR 8987, 9225, 9264) +* Renesas FSP / RA examples updated and security-module TLS context improvements. (PR 9047, 9010, 9158, 9150) +* Broad configure/CMake/Autotools workflow improvements (Apple options tracking, Watcom pinning, Debian packaging, ESP-IDF pinning). (PR 9037, 9167, 9161, 9264) +* New assembly introspection / performance helpers for RISC-V and PPC32; benchmarking enhancements (cycle counts). (PR 9101, 9317) +* Update to SGX build for using assembly optimizations. (PR 8463, 9138) +* Testing with Fil-C compiler version to 0.674 (PR 9396) +* Refactors and compressing of small stack code (PR 9153) + +## Bug Fixes +* Removed the test feature using popen when defining the macro WOLFSSL_USE_POPEN_HOST and not having HAVE_GETADDRINFO defined, along with having the macro HAVE_HTTP_CLIENT set. There was the potential for vulnerable behavior with the use of popen when the API wolfSSL_BIO_new_connect() was called with this specific build. This exact build configuration is only intended for testing with QEMU and is not enabled with any autoconf/cmake flags. Thanks to linraymond2006 for the report. (PR 9038) +* Fix for C# wrapper Ed25519 potential crash and heap overwrite with raw public key import when using the API Ed25519ImportPublic.This was a broken API with the C# wrapper that would crash on use. Thanks to Luigino Camastra from Aisle Research for the bug report. (PR 9291) +* Coverity, cppcheck, MISRA, clang-tidy, ZeroPath and other static-analysis driven fixes across the codebase. (PR 9006, 9078, 9068, 9265, 9324) +* TLS 1.2/DTLS improvements: client message order checks, DTLS cookie/exchange and replay protections, better DTLS early-data handling. (PR 9387, 9253, 9205, 9367) +* Improved X.509 & cert handling: allow larger pathLen in Basic Constraints, restore inner server name for ECH, retrying cert candidate chains. (PR 8890, 9234, 8692) +* Sniffer robustness: fix infinite recursion, better handling of OOO appData and partial overlaps, and improved retransmission detection. (PR 9051, 9106, 9140, 9094) +* Numerous linuxkm (kernel-mode) fixes, relocation/PIE normalization, and FIPS-related build tweaks across many iterations. (PR 9025, 9035, 9067, 9111, 9121) +* ML-KEM/Kyber and ML-DSA fixes for out-of-bounds and seed-import correctness; multiple ML-related safety fixes. (PR 9142, 9105, 9439) +* Avoid uninitialized-variable and GCC warnings; several fixes for undefined-shift/overflow issues. (PR 9020, 9372, 9195) +* Memory & leak fixes in X509 verification and various struct sizing fixes for WOLFSSL_NO_MALLOC usage. (PR 9258, 9036) +* Fixed RSA / signing / verify-only warnings allowing WOLFSSL_NO_CT_OPS when WOLFSSL_RSA_VERIFY_ONLY is used and API cleanups for using const. (PR 9031, 9263) + + # wolfSSL Release 5.8.2 (July 17, 2025) Release 5.8.2 has been developed according to wolfSSL's development and QA @@ -9,7 +82,7 @@ NOTE: * wolfSSL is now GPLv3 instead of GPLv2 * MD5 is now disabled by default -PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. +PR stands for Pull Request, and PR (NUMBER) references a GitHub pull request number where the code change was added. ## Vulnerabilities @@ -68,7 +141,8 @@ Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 * Implemented distro fix for the Linux Kernel Module. (PR #8994) * Fixed page-flags-h in the Linux Kernel Module. (PR #9001) * Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) -* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms + +### Post-Quantum Cryptography (PQC) & Asymmetric Algorithms * Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) * Backward compatibility has been implemented for ML_KEM IDs (PR #8827) * ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) @@ -207,7 +281,7 @@ https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assur NOTE: * --enable-heapmath is deprecated -PR stands for Pull Request, and PR references a GitHub pull request +PR stands for Pull Request, and PR (NUMBER) references a GitHub pull request number where the code change was added. @@ -423,7 +497,7 @@ NOTE: user_settings.h. -PR stands for Pull Request, and PR references a GitHub pull request +PR stands for Pull Request, and PR (NUMBER) references a GitHub pull request number where the code change was added. @@ -543,7 +617,7 @@ https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assur NOTE: * --enable-heapmath is being deprecated and will be removed by end of 2024 -PR stands for Pull Request, and PR references a GitHub pull request +PR stands for Pull Request, and PR (NUMBER) references a GitHub pull request number where the code change was added. diff --git a/LICENSING b/LICENSING index cf1d098..14b0801 100644 --- a/LICENSING +++ b/LICENSING @@ -1,9 +1,24 @@ +The wolfSSL, Inc. software (“wolfSSL Software”) to which this text is appended +is made available under the GNU General Public License version 3 (“GPLv3”) with +the following exception: When this wolfSSL Software is combined with the +software listed below (“Exception Software”), licensee may elect to license +this wolfSSL Software under the GNU General Public License version 2 (“GPLv2”) +instead of GPLv3. -wolfSSL (formerly known as CyaSSL) and wolfCrypt are either licensed for use -under the GPLv3 (or at your option any later version) or a standard commercial -license. For our users who cannot use wolfSSL under GPLv3 -(or any later version), a commercial license to wolfSSL and wolfCrypt is -available. +Exception Software: + +MariaDB Server + +MariaDB Client Libraries + +OpenVPN-NL + +Fetchmail + +OpenVPN + +For our users who cannot use wolfSSL under GPLv3, a commercial license to +wolfSSL and wolfCrypt is available. Please contact wolfSSL Inc. directly at: diff --git a/README b/README index a8e5f76..6a0e29a 100644 --- a/README +++ b/README @@ -29,24 +29,29 @@ of the wolfSSL manual. (https://www.wolfssl.com/docs/wolfssl-manual/ch4/) *** Notes, Please read *** Note 1) -wolfSSL as of 3.6.6 no longer enables SSLv3 by default. wolfSSL also no longer -supports static key cipher suites with PSK, RSA, or ECDH. This means if you -plan to use TLS cipher suites you must enable DH (DH is on by default), or -enable ECC (ECC is on by default), or you must enable static key cipher suites -with - - WOLFSSL_STATIC_DH - WOLFSSL_STATIC_RSA - or - WOLFSSL_STATIC_PSK - -though static key cipher suites are deprecated and will be removed from future -versions of TLS. They also lower your security by removing PFS. - -When compiling ssl.c, wolfSSL will now issue a compiler error if no cipher +wolfSSL as of 3.6.6 no longer enables SSLv3 by default. By default, wolfSSL +disables static key cipher suites that use PSK, RSA, or ECDH without ephemeral +key exchange. Instead, wolfSSL enables cipher suites that provide perfect +forward secrecy (PFS) using ephemeral Diffie-Hellman (DH) or Elliptic Curve +(ECC) key exchange, both of which are enabled by default. + +If you need to support legacy systems that require static key cipher suites, +you can enable them using one or more of these defines: + +WOLFSSL_STATIC_DH +WOLFSSL_STATIC_RSA +WOLFSSL_STATIC_PSK + +Important: Static key cipher suites reduce security by eliminating perfect +forward secrecy. These cipher suites reuse the same long-term private key for +all session key exchanges. In contrast, PFS-enabled cipher suites (the wolfSSL +default) generate a new ephemeral key for each session, ensuring that +compromising a long-term key cannot decrypt past sessions. + +When compiling `ssl.c`, wolfSSL will now issue a compiler error if no cipher suites are available. You can remove this error by defining -WOLFSSL_ALLOW_NO_SUITES in the event that you desire that, i.e., you're not -using TLS cipher suites. +`WOLFSSL_ALLOW_NO_SUITES` in the event that you desire that, i.e., you're +not using TLS cipher suites. Note 2) wolfSSL takes a different approach to certificate verification than OpenSSL @@ -70,205 +75,77 @@ should be used for the enum name. *** end Notes *** -# wolfSSL Release 5.8.2 (July 17, 2025) +# wolfSSL Release 5.8.4 (Nov. 20, 2025) -Release 5.8.2 has been developed according to wolfSSL's development and QA +Release 5.8.4 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * wolfSSL is now GPLv3 instead of GPLv2 - * --enable-heapmath is deprecated +NOTE: * --enable-heapmath is deprecated * MD5 is now disabled by default - PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. ## Vulnerabilities +* [Low CVE-2025-12888] Vulnerability in X25519 constant-time cryptographic implementations due to timing side channels introduced by compiler optimizations and CPU architecture limitations, specifically with the Xtensa-based ESP32 chips. If targeting Xtensa it is recommended to use the low memory implementations of X25519, which is now turned on as the default for Xtensa. Thanks to Adrian Cinal for the report. Fixed in PR 9275. -* [Low] There is the potential for a fault injection attack on ECC and Ed25519 verify operations. In versions of wolfSSL 5.7.6 and later the --enable-faultharden option is available to help mitigate against potential fault injection attacks. The mitigation added in wolfSSL version 5.7.6 is to help harden applications relying on the results of the verify operations, such as when used with wolfBoot. If doing ECC or Ed25519 verify operations on a device at risk for fault injection attacks then --enable-faultharden could be used to help mitigate it. Thanks to Kevin from Fraunhofer AISEC for the report. -Hardening option added in PR https://github.com/wolfSSL/wolfssl/pull/8289 +* [Med. CVE-2025-11936] Potential DoS vulnerability due to a memory leak through multiple KeyShareEntry with the same group in malicious TLS 1.3 ClientHello messages. This affects users who are running wolfSSL on the server side with TLS 1.3. Thanks to Jaehun Lee and Kyungmin Bae, Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9117. +* [Low CVE-2025-11935] PSK with PFS (Perfect Forward Secrecy) downgrades to PSK without PFS during TLS 1.3 handshake. If the client sends a ClientHello that has a key share extension and the server responds with a ServerHello that does not have a key share extension the connection would previously continue on without using PFS. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9112. -* [High CVE-2025-7395] When using WOLFSSL_SYS_CA_CERTS and WOLFSSL_APPLE_NATIVE_CERT_VALIDATION on an Apple platform, the native trust store verification routine overrides errors produced elsewhere in the wolfSSL certificate verification process including failures due to hostname matching/SNI, OCSP, CRL, etc. This allows any trusted cert chain to override other errors detected during chain verification that should have resulted in termination of the TLS connection. If building wolfSSL on versions after 5.7.6 and before 5.8.2 with use of the system CA support and the apple native cert validation feature enabled on Apple devices (on by default for non-macOS Apple targets when using autotools or CMake) we recommend updating to the latest version of wolfSSL. Thanks to Thomas Leong from ExpressVPN for the report. +* [Low CVE-2025-11934] Signature Algorithm downgrade from ECDSA P521 to P256 during TLS 1.3 handshake. When a client sends ECDSA P521 as the supported signature algorithm the server previously could respond as ECDSA P256 being the accepted signature algorithm and the connection would continue with using ECDSA P256. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9113. -Fixed in PR https://github.com/wolfSSL/wolfssl/pull/8833 +* [Low CVE-2025-11933] DoS Vulnerability in wolfSSL TLS 1.3 CKS extension parsing. Previously duplicate CKS extensions were not rejected leading to a potential memory leak when processing a ClientHello. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9132. -* [Med. CVE-2025-7394] In the OpenSSL compatibility layer implementation, the function RAND_poll() was not behaving as expected and leading to the potential for predictable values returned from RAND_bytes() after fork() is called. This can lead to weak or predictable random numbers generated in applications that are both using RAND_bytes() and doing fork() operations. This only affects applications explicitly calling RAND_bytes() after fork() and does not affect any internal TLS operations. Although RAND_bytes() documentation in OpenSSL calls out not being safe for use with fork() without first calling RAND_poll(), an additional code change was also made in wolfSSL to make RAND_bytes() behave similar to OpenSSL after a fork() call without calling RAND_poll(). Now the Hash-DRBG used gets reseeded after detecting running in a new process. If making use of RAND_bytes() and calling fork() we recommend updating to the latest version of wolfSSL. Thanks to Per Allansson from Appgate for the report. -Fixed in the following PR’s -https://github.com/wolfSSL/wolfssl/pull/8849 -https://github.com/wolfSSL/wolfssl/pull/8867 -https://github.com/wolfSSL/wolfssl/pull/8898 +* [Low CVE-2025-11931] Integer Underflow Leads to Out-of-Bounds Access in XChaCha20-Poly1305 Decrypt. This issue is hit specifically with a call to the function wc_XChaCha20Poly1305_Decrypt() which is not used with TLS connections, only from direct calls from an application. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. +* [Low CVE-2025-11932] Timing Side-Channel in PSK Binder Verification. The server previously verified the TLS 1.3 PSK binder using a non-constant time method which could potentially leak information about the PSK binder. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. - -* [Low CVE-2025-7396] In wolfSSL 5.8.0 the option of hardening the C implementation of Curve25519 private key operations was added with the addition of blinding support (https://www.wolfssl.com/curve25519-blinding-support-added-in-wolfssl-5-8-0/). In wolfSSL release 5.8.2 that blinding support is turned on by default in applicable builds. The blinding configure option is only for the base C implementation of Curve25519. It is not needed, or available with; ARM assembly builds, Intel assembly builds, and the small Curve25519 feature. While the attack would be very difficult to execute in practice, enabling blinding provides an additional layer of protection for devices that may be more susceptible to physical access or side-channel observation. Thanks to Arnaud Varillon, Laurent Sauvage, and Allan Delautre from Telecom Paris for the report. - -Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 - +* [Low CVE-2025-12889] With TLS 1.2 connections a client can use any digest, specifically a weaker digest, rather than those in the CertificateRequest. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9395 ## New Features -* Multiple sessions are now supported in the sniffer due to the removal of a cached check. (PR #8723) -* New API ssl_RemoveSession() has been implemented for sniffer cleanup operations. (PR #8768) -* The new ASN X509 API, `wc_GetSubjectPubKeyInfoDerFromCert`, has been introduced for retrieving public key information from certificates. (PR #8758) -* `wc_PKCS12_create()` has been enhanced to support PBE_AES(256|128)_CBC key and certificate encryptions. (PR #8782, PR #8822, PR #8859) -* `wc_PKCS7_DecodeEncryptedKeyPackage()` has been added for decoding encrypted key packages. (PR #8976) -* All AES, SHA, and HMAC functionality has been implemented within the Linux Kernel Module. (PR #8998) -* Additions to the compatibility layer have been introduced for X.509 extensions and RSA PSS. Adding the API i2d_PrivateKey_bio, BN_ucmp and X509v3_get_ext_by_NID. (PR #8897) -* Added support for STM32N6. (PR #8914) -* Implemented SHA-256 for PPC 32 assembly. (PR #8894) +* New ML-KEM / ML-DSA APIs and seed/import PKCS8 support; added _new/_delete APIs for ML-KEM/ML-DSA. (PR 9039, 9000, 9049) +* Initial wolfCrypt FreeBSD kernel module support (PR 9392) +* Expanded PKCS7/CMS capabilities: decode SymmetricKeyPackage / OneSymmetricKey, add wc_PKCS7_GetEnvelopedDataKariRid, and allow PKCS7 builds with AES keywrap unset. (PR 9018, 9029, 9032) +* Add custom AES key wrap/unwrap callbacks and crypto callback copy/free operations. (PR 9002, 9309) +* Add support for certificate_authorities extension in ClientHello and certificate manager CA-type selection/unloading. (PR 9209, 9046) +* Large expansion of Rust wrapper modules: random, aes, rsa, ecc, dh, sha, hmac, cmac, ed25519/ed448, pbkdf2/PKCS#12, kdf/prf, SRTP KDFs, and conditional compilation options. (PR 9191, 9212, 9273, 9306, 9320, 9328, 9368, 9389, 9357, 9433) +* Rust: support optional heap and dev_id parameters and enable conditional compilation based on C build options. (PR 9407, 9433) +* STM32 fixes (benchmarking and platform fixes) and PSoC6 hardware acceleration additions. (PR 9228, 9256, 9185) +* STM32U5 added support for SAES and DHUK. (PR 9087) +* Add --enable-curl=tiny option for a smaller build when used with cURL. (PR 9174) ## Improvements / Optimizations - -### Linux Kernel Module (LinuxKM) Enhancements -* Registered DH and FFDHE for the Linux Kernel Module. (PR #8707) -* Implemented fixes for standard RNG in the Linux Kernel Module. (PR #8718) -* Added an ECDSA workaround for the Linux Kernel Module. (PR #8727) -* Added more PKCS1 pad SHA variants for RSA in the Linux Kernel Module. (PR #8730) -* Set default priority to 100000 for LKCAPI in the Linux Kernel Module. (PR #8740) -* Ensured ECDH never has FIPS enabled in the Linux Kernel Module. (PR #8751) -* Implemented further Linux Kernel Module and SP tweaks. (PR #8773) -* Added sig_alg support for Linux 6.13 RSA in the Linux Kernel Module. (PR #8796) -* Optimized wc_linuxkm_fpu_state_assoc. (PR #8828) -* Ensured DRBG is multithread-round-1 in the Linux Kernel Module. (PR #8840) -* Prevented toggling of fips_enabled in the Linux Kernel Module. (PR #8873) -* Refactored drbg_ctx clear in the Linux Kernel Module. (PR #8876) -* Set sig_alg max_size and digest_size callbacks for RSA in the Linux Kernel Module. (PR #8915) -* Added get_random_bytes for the Linux Kernel Module. (PR #8943) -* Implemented distro fix for the Linux Kernel Module. (PR #8994) -* Fixed page-flags-h in the Linux Kernel Module. (PR #9001) -* Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) -* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms -* Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) -* Backward compatibility has been implemented for ML_KEM IDs (PR #8827) -* ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) -* Building LMS with verify-only has been fixed (PR #8913) -* Parameters for LMS SHA-256_192 have been corrected (PR #8912) -* State can now be saved with the private key for LMS (PR #8836) -* Support for OpenSSL format has been added for ML-DSA/Dilithium (PR #8947) -* `dilithium_coeff_eta2[]` has been explicitly declared as signed (PR #8955) - -### Build System & Portability -* Prepared for the inclusion of v5.8.0 in the Ada Alire index. (PR #8714) -* Introduced a new build option to allow reuse of the Windows crypt provider handle. (PR #8706) -* Introduced general fixes for various build configurations. (PR #8763) -* Made improvements for portability using older GCC 4.8.2. (PR #8753) -* Macro guards updated to allow tests to build with opensslall and no server. (PR #8776) -* Added a check for STDC_NO_ATOMICS macro before use of atomics. (PR #8885) -* Introduced CMakePresets.json and CMakeSettings.json. (PR #8905) -* Added an option to not use constant time code with min/max. (PR #8830) -* Implemented proper MacOS dispatch for conditional signal/wait. (PR #8928) -* Disabled MD5 by default for both general and CMake builds. (PR #8895, PR #8948) -* Improved to allow building OPENSSL_EXTRA without KEEP_PEER_CERT. (PR #8926) -* Added introspection for Intel and ARM assembly speedups. (PR #8954) -* Fixed cURL config to set HAVE_EX_DATA and HAVE_ALPN. (PR #8973) -* Moved FREESCALE forced algorithm HAVE_ECC to IDE/MQX/user_settings.h. (PR #8977) - -### Testing & Debugging -* Fixed the exit status for testwolfcrypt. (PR #8762) -* Added WOLFSSL_DEBUG_PRINTF and WOLFSSL_DEBUG_CERTIFICATE_LOADS for improved debugging output. (PR #8769, PR #8770) -* Guarded some benchmark tests with NO_SW_BENCH. (PR #8760) -* Added an additional unit test for wolfcrypt PKCS12 file to improve code coverage. (PR #8831) -* Added an additional unit test for increased DH code coverage. (PR #8837) -* Adjusted for warnings with NO_TLS build and added GitHub actions test. (PR #8851) -* Added additional compatibility layer RAND tests. (PR #8852) -* Added an API unit test for checking domain name. (PR #8863) -* Added bind v9.18.33 testing. (PR #8888) -* Fixed issue with benchmark help options and descriptions not lining up. (PR #8957) - -### Certificates & ASN.1 -* Changed the algorithm for sum in ASN.1 OIDs. (PR #8655) -* Updated PKCS7 to use X509 STORE for internal verification. (PR #8748) -* Improved handling of temporary buffer size for X509 extension printing. (PR #8710) -* Marked IP address as WOLFSSL_V_ASN1_OCTET_STRING for ALT_NAMES_OID. (PR #8842) -* Fixed printing empty names in certificates. (PR #8880) -* Allowed CA:FALSE on wolftpm. (PR #8925) -* Fixed several inconsistent function prototype parameter names in wc/asn. (PR #8949) -* Accounted for custom extensions when creating a Cert from a WOLFSSL_X509. (PR #8960) - -### TLS/DTLS & Handshake -* Checked group correctness outside of TLS 1.3 too for TLSX_UseSupportedCurve. (PR #8785) -* Dropped records that span datagrams in DTLS. (PR #8642) -* Implemented WC_NID_netscape_cert_type. (PR #8800) -* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) -* Correctly set the current peer in dtlsProcessPendingPeer. (PR #8848) -* Fixed set_groups for TLS. (PR #8824) -* Allowed trusted_ca_keys with TLSv1.3. (PR #8860) -* Moved Dtls13NewEpoch into DeriveTls13Keys. (PR #8858) -* Cleared tls1_3 on downgrade. (PR #8861) -* Always sent ACKs on detected retransmission for DTLS1.3. (PR #8882) -* Removed DTLS from echo examples. (PR #8889) -* Recalculated suites at SSL initialization. (PR #8757) -* No longer using BIO for ALPN. (PR #8969) -* Fixed wolfSSL_BIO_new_connect's handling of IPV6 addresses. (PR #8815) -* Memory Management & Optimizations -* Performed small stack refactors, improved stack size with mlkem and dilithium, and added additional tests. (PR #8779) -* Implemented FREE_MP_INT_SIZE in heap math. (PR #8881) -* Detected correct MAX_ENCODED_SIG_SZ based on max support in math lib. (PR #8931) -* Fixed improper access of sp_int_minimal using sp_int. (PR #8985) - -### Cryptography & Hash Functions -* Implemented WC_SIPHASH_NO_ASM for not using assembly optimizations with siphash. (PR #8789, PR #8791) -* Added missing DH_MAX_SIZE define for FIPS and corrected wolfssl.rc FILETYPE to VFT_DLL. (PR #8794) -* Implemented WC_SHA3_NO_ASM for not using assembly with SHA3. (PR #8817) -* Improved Aarch64 XFENCE. (PR #8832) -* Omitted frame pointer for ARM32/Thumb2/RISC-V 64 assembly. (PR #8893) -* Fixed branch instruction in ARMv7a ASM. (PR #8933) -* Enabled EVP HMAC to work with WOLFSSL_HMAC_COPY_HASH. (PR #8944) -* Platform-Specific & Hardware Integration -* Added HAVE_HKDF for wolfssl_test and explicit support for ESP32P4. (PR #8742) -* Corrected Espressif default time setting. (PR #8829) -* Made wc_tsip_* APIs public. (PR #8717) -* Improved PlatformIO Certificate Bundle Support. (PR #8847) -* Fixed the TSIP TLS example program. (PR #8857) -* Added crypto callback functions for TROPIC01 secure element. (PR #8812) -* Added Renesas RX TSIP AES CTR support. (PR #8854) -* Fixed TSIP port using crypto callback. (PR #8937) - -### General Improvements & Refactoring -* Attempted wolfssl_read_bio_file in read_bio even when XFSEEK is available. (PR #8703) -* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) -* Updated libspdm from 3.3.0 to 3.7.0. (PR #8906) -* Fixed missing dashes on the end of header and footer for Falcon PEM key. (PR #8904) -* Fixed minor code typos for macos signal and types.h max block size. (PR #8934) -* Make the API wolfSSL_X509_STORE_CTX_get_error accessible to more build configurations for ease of getting the "store" error code and depth with certificate failure callback implementations. (PR #8903) +* Regression test fixes and expansion: TLS 1.3/1.2 tests, ARDUINO examples, libssh2 tests, hostap workflows, and nightly test improvements. (PR 9096, 9141, 9091, 9122, 9388) +* Improved test ordering and CI test stability (random tests run order changes, FIPS test fixes). (PR 9204, 9257) +* Docs and readme fixes, docstring updates, AsconAEAD comment placement, and example certificate renewals. (PR 9131, 9293, 9262, 9429) +* Updated GPL exception lists (GPLv2 and GPLv3 exception updates: add Fetchmail and OpenVPN). (PR 9398, 9413) +* Introduced WOLFSSL_DEBUG_CERTS and additional debug/logging refinements. (PR 8902, 9055) +* Expanded crypto-callback support (SHA family, HKDF, SHA-224, sha512_family digest selection) and improved crypto-only build cases. (PR 9070, 9252, 9271, 9100, 9194) +* AES & HW offload improvements including AES-CTR support in PKCS11 driver and AES ECB offload sizing fix. (PR 9277, 9364) +* ESP32: PSRAM allocator support and SHA HW fixes for ESP-IDF v6/v5. (PR 8987, 9225, 9264) +* Renesas FSP / RA examples updated and security-module TLS context improvements. (PR 9047, 9010, 9158, 9150) +* Broad configure/CMake/Autotools workflow improvements (Apple options tracking, Watcom pinning, Debian packaging, ESP-IDF pinning). (PR 9037, 9167, 9161, 9264) +* New assembly introspection / performance helpers for RISC-V and PPC32; benchmarking enhancements (cycle counts). (PR 9101, 9317) +* Update to SGX build for using assembly optimizations. (PR 8463, 9138) +* Testing with Fil-C compiler version to 0.674 (PR 9396) +* Refactors and compressing of small stack code (PR 9153) ## Bug Fixes -* Fixed issues to support _WIN32_WCE (VS 2008 with WinCE 6.0/7.0). (PR #8709) -* Fixed STM32 Hash with IRQ enabled. (PR #8705) -* Fixed raw hash when using crypto instructions on RISC-V 64-bit. (PR #8733) -* Fixed ECDH decode secret in the Linux Kernel Module. (PR #8729) -* Passed in the correct hash type to wolfSSL_RSA_verify_ex. (PR #8726) -* Fixed issues for Intel QuickAssist latest driver (4.28). (PR #8728) -* Speculative fix for CodeSonar overflow issue in ssl_certman.c. (PR #8715) -* Fixed Arduino progmem print and AVR WOLFSSL_USER_IO. (PR #8668) -* Correctly advanced the index in wc_HKDF_Expand_ex. (PR #8737) -* Fixed STM32 hash status check logic, including NO_AES_192 and NO_AES_256. (PR #8732) -* Added missing call to wolfSSL_RefFree in FreeCRL to prevent memory leaks. (PR #8750) -* Fixed sanity check on --group with unit test app and null sanity check with des decrypt. (PR #8711) -* Fixed Curve25519 and static ephemeral issue with blinding. (PR #8766) -* Fixed edge case issue with STM32 AES GCM auth padding. (PR #8745) -* Removed redefinition of MlKemKey and fixed build issue in benchmark. (PR #8755) -* Used proper heap hint when freeing CRL in error case. (PR #8713) -* Added support for no malloc with wc_CheckCertSigPubKey. (PR #8725) -* Fixed C# wrapper Release build. (PR #8802) -* Handled malformed CCS and CCS before CH in TLS1.3. (PR #8788) -* Fixed ML-DSA with WOLFSSL_DILITHIUM_NO_SIGN. (PR #8798) -* Fixed AesGcmCrypt_1 no-stream in the Linux Kernel Module. (PR #8814) -* Fixed return value usage for crypto_sig_sign in the Linux Kernel Module. (PR #8816) -* Fixed issue with CSharp and Windows CE with conversion of ASCII and Unicode. (PR #8799) -* Fixed Renesas SCE on RA6M4. (PR #8838) -* Fixed tests for different configs for ML-DSA. (PR #8865) -* Fixed bug in ParseCRL_Extensions around the size of a CRL number handled and CRL number OID. (PR #8587) -* Fixed uninitialized wc_FreeRng in prime_test. (PR #8886) -* Fixed ECC configuration issues with ECC verify only and no RNG. (PR #8901) -* Fixed issues with max size, openssl.test netcat, and clang-tidy. (PR #8909) -* Fixed for casting down and uninit issues in Dilithium/ML-DSA. (PR #8868) -* Fixed memory allocation failure testing and related unit test cases. (PR #8945, PR #8952) -* Fixed build issue with ML-DSA 44 only. (PR #8981) -* Fixed possible memory leak with X509 reference counter when using x509small. (PR #8982) +* Removed the test feature using popen when defining the macro WOLFSSL_USE_POPEN_HOST and not having HAVE_GETADDRINFO defined, along with having the macro HAVE_HTTP_CLIENT set. There was the potential for vulnerable behavior with the use of popen when the API wolfSSL_BIO_new_connect() was called with this specific build. This exact build configuration is only intended for testing with QEMU and is not enabled with any autoconf/cmake flags. Thanks to linraymond2006 for the report. (PR 9038) +* Fix for C# wrapper Ed25519 potential crash and heap overwrite with raw public key import when using the API Ed25519ImportPublic.This was a broken API with the C# wrapper that would crash on use. Thanks to Luigino Camastra from Aisle Research for the bug report. (PR 9291) +* Coverity, cppcheck, MISRA, clang-tidy, ZeroPath and other static-analysis driven fixes across the codebase. (PR 9006, 9078, 9068, 9265, 9324) +* TLS 1.2/DTLS improvements: client message order checks, DTLS cookie/exchange and replay protections, better DTLS early-data handling. (PR 9387, 9253, 9205, 9367) +* Improved X.509 & cert handling: allow larger pathLen in Basic Constraints, restore inner server name for ECH, retrying cert candidate chains. (PR 8890, 9234, 8692) +* Sniffer robustness: fix infinite recursion, better handling of OOO appData and partial overlaps, and improved retransmission detection. (PR 9051, 9106, 9140, 9094) +* Numerous linuxkm (kernel-mode) fixes, relocation/PIE normalization, and FIPS-related build tweaks across many iterations. (PR 9025, 9035, 9067, 9111, 9121) +* ML-KEM/Kyber and ML-DSA fixes for out-of-bounds and seed-import correctness; multiple ML-related safety fixes. (PR 9142, 9105, 9439) +* Avoid uninitialized-variable and GCC warnings; several fixes for undefined-shift/overflow issues. (PR 9020, 9372, 9195) +* Memory & leak fixes in X509 verification and various struct sizing fixes for WOLFSSL_NO_MALLOC usage. (PR 9258, 9036) +* Fixed RSA / signing / verify-only warnings allowing WOLFSSL_NO_CT_OPS when WOLFSSL_RSA_VERIFY_ONLY is used and API cleanups for using const. (PR 9031, 9263) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ diff --git a/README.md b/README.md index 13265b3..905411a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Arduino wolfSSL Library -This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.8.2 for the Arduino platform. +This library is restructured from [wolfSSL](https://github.com/wolfSSL/wolfssl/) Release 5.8.4 for the Arduino platform. The Official wolfSSL Arduino Library is found in [The Library Manager index](http://downloads.arduino.cc/libraries/library_index.json). @@ -40,13 +40,10 @@ Additional wolfSSL examples can be found at: ## Arduino Releases -This release of wolfSSL is version [5.7.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.7.6-stable). - See GitHub for [all Arduino wolfSSL releases](https://github.com/wolfSSL/Arduino-wolfSSL/releases). -The first Official wolfSSL Arduino Library was `5.6.6-Arduino.1`: a slightly modified, post [release 5.6.6](https://github.com/wolfSSL/wolfssl/releases/tag/v5.6.6-stable) version update. - The `./wolfssl-arduino.sh INSTALL` [script](https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO) can be used to install specific GitHub versions as needed. + # wolfSSL Embedded SSL/TLS Library The [wolfSSL embedded SSL library](https://www.wolfssl.com/products/wolfssl/) @@ -82,19 +79,24 @@ of the wolfSSL manual. ## Notes, Please Read ### Note 1 -wolfSSL as of 3.6.6 no longer enables SSLv3 by default. wolfSSL also no longer -supports static key cipher suites with PSK, RSA, or ECDH. This means if you -plan to use TLS cipher suites you must enable DH (DH is on by default), or -enable ECC (ECC is on by default), or you must enable static key cipher suites -with one or more of the following defines: +wolfSSL as of 3.6.6 no longer enables SSLv3 by default. By default, wolfSSL +disables static key cipher suites that use PSK, RSA, or ECDH without ephemeral +key exchange. Instead, wolfSSL enables cipher suites that provide perfect +forward secrecy (PFS) using ephemeral Diffie-Hellman (DH) or Elliptic Curve +(ECC) key exchange, both of which are enabled by default. -``` -WOLFSSL_STATIC_DH -WOLFSSL_STATIC_RSA -WOLFSSL_STATIC_PSK -``` -Though static key cipher suites are deprecated and will be removed from future -versions of TLS. They also lower your security by removing PFS. +If you need to support legacy systems that require static key cipher suites, +you can enable them using one or more of these defines: + +* `WOLFSSL_STATIC_DH` +* `WOLFSSL_STATIC_RSA` +* `WOLFSSL_STATIC_PSK` + +**Important:** Static key cipher suites reduce security by eliminating perfect +forward secrecy. These cipher suites reuse the same long-term private key for +all session key exchanges. In contrast, PFS-enabled cipher suites (the wolfSSL +default) generate a new ephemeral key for each session, ensuring that +compromising a long-term key cannot decrypt past sessions. When compiling `ssl.c`, wolfSSL will now issue a compiler error if no cipher suites are available. You can remove this error by defining @@ -124,205 +126,77 @@ single call hash function. Instead the name `WC_SHA`, `WC_SHA256`, `WC_SHA384` a `WC_SHA512` should be used for the enum name. -# wolfSSL Release 5.8.2 (July 17, 2025) +# wolfSSL Release 5.8.4 (Nov. 20, 2025) -Release 5.8.2 has been developed according to wolfSSL's development and QA +Release 5.8.4 has been developed according to wolfSSL's development and QA process (see link below) and successfully passed the quality criteria. https://www.wolfssl.com/about/wolfssl-software-development-process-quality-assurance -NOTE: * wolfSSL is now GPLv3 instead of GPLv2 - * --enable-heapmath is deprecated +NOTE: * --enable-heapmath is deprecated * MD5 is now disabled by default - PR stands for Pull Request, and PR references a GitHub pull request number where the code change was added. ## Vulnerabilities +* [Low CVE-2025-12888] Vulnerability in X25519 constant-time cryptographic implementations due to timing side channels introduced by compiler optimizations and CPU architecture limitations, specifically with the Xtensa-based ESP32 chips. If targeting Xtensa it is recommended to use the low memory implementations of X25519, which is now turned on as the default for Xtensa. Thanks to Adrian Cinal for the report. Fixed in PR 9275. -* [Low] There is the potential for a fault injection attack on ECC and Ed25519 verify operations. In versions of wolfSSL 5.7.6 and later the --enable-faultharden option is available to help mitigate against potential fault injection attacks. The mitigation added in wolfSSL version 5.7.6 is to help harden applications relying on the results of the verify operations, such as when used with wolfBoot. If doing ECC or Ed25519 verify operations on a device at risk for fault injection attacks then --enable-faultharden could be used to help mitigate it. Thanks to Kevin from Fraunhofer AISEC for the report. - -Hardening option added in PR https://github.com/wolfSSL/wolfssl/pull/8289 +* [Med. CVE-2025-11936] Potential DoS vulnerability due to a memory leak through multiple KeyShareEntry with the same group in malicious TLS 1.3 ClientHello messages. This affects users who are running wolfSSL on the server side with TLS 1.3. Thanks to Jaehun Lee and Kyungmin Bae, Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9117. -* [High CVE-2025-7395] When using WOLFSSL_SYS_CA_CERTS and WOLFSSL_APPLE_NATIVE_CERT_VALIDATION on an Apple platform, the native trust store verification routine overrides errors produced elsewhere in the wolfSSL certificate verification process including failures due to hostname matching/SNI, OCSP, CRL, etc. This allows any trusted cert chain to override other errors detected during chain verification that should have resulted in termination of the TLS connection. If building wolfSSL on versions after 5.7.6 and before 5.8.2 with use of the system CA support and the apple native cert validation feature enabled on Apple devices (on by default for non-macOS Apple targets when using autotools or CMake) we recommend updating to the latest version of wolfSSL. Thanks to Thomas Leong from ExpressVPN for the report. +* [Low CVE-2025-11935] PSK with PFS (Perfect Forward Secrecy) downgrades to PSK without PFS during TLS 1.3 handshake. If the client sends a ClientHello that has a key share extension and the server responds with a ServerHello that does not have a key share extension the connection would previously continue on without using PFS. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9112. -Fixed in PR https://github.com/wolfSSL/wolfssl/pull/8833 +* [Low CVE-2025-11934] Signature Algorithm downgrade from ECDSA P521 to P256 during TLS 1.3 handshake. When a client sends ECDSA P521 as the supported signature algorithm the server previously could respond as ECDSA P256 being the accepted signature algorithm and the connection would continue with using ECDSA P256. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9113. -* [Med. CVE-2025-7394] In the OpenSSL compatibility layer implementation, the function RAND_poll() was not behaving as expected and leading to the potential for predictable values returned from RAND_bytes() after fork() is called. This can lead to weak or predictable random numbers generated in applications that are both using RAND_bytes() and doing fork() operations. This only affects applications explicitly calling RAND_bytes() after fork() and does not affect any internal TLS operations. Although RAND_bytes() documentation in OpenSSL calls out not being safe for use with fork() without first calling RAND_poll(), an additional code change was also made in wolfSSL to make RAND_bytes() behave similar to OpenSSL after a fork() call without calling RAND_poll(). Now the Hash-DRBG used gets reseeded after detecting running in a new process. If making use of RAND_bytes() and calling fork() we recommend updating to the latest version of wolfSSL. Thanks to Per Allansson from Appgate for the report. +* [Low CVE-2025-11933] DoS Vulnerability in wolfSSL TLS 1.3 CKS extension parsing. Previously duplicate CKS extensions were not rejected leading to a potential memory leak when processing a ClientHello. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9132. -Fixed in the following PR’s -https://github.com/wolfSSL/wolfssl/pull/8849 -https://github.com/wolfSSL/wolfssl/pull/8867 -https://github.com/wolfSSL/wolfssl/pull/8898 +* [Low CVE-2025-11931] Integer Underflow Leads to Out-of-Bounds Access in XChaCha20-Poly1305 Decrypt. This issue is hit specifically with a call to the function wc_XChaCha20Poly1305_Decrypt() which is not used with TLS connections, only from direct calls from an application. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. +* [Low CVE-2025-11932] Timing Side-Channel in PSK Binder Verification. The server previously verified the TLS 1.3 PSK binder using a non-constant time method which could potentially leak information about the PSK binder. Thanks to Luigino Camastra from Aisle Research for the report. Fixed in PR 9223. -* [Low CVE-2025-7396] In wolfSSL 5.8.0 the option of hardening the C implementation of Curve25519 private key operations was added with the addition of blinding support (https://www.wolfssl.com/curve25519-blinding-support-added-in-wolfssl-5-8-0/). In wolfSSL release 5.8.2 that blinding support is turned on by default in applicable builds. The blinding configure option is only for the base C implementation of Curve25519. It is not needed, or available with; ARM assembly builds, Intel assembly builds, and the small Curve25519 feature. While the attack would be very difficult to execute in practice, enabling blinding provides an additional layer of protection for devices that may be more susceptible to physical access or side-channel observation. Thanks to Arnaud Varillon, Laurent Sauvage, and Allan Delautre from Telecom Paris for the report. - -Blinding enabled by default in PR https://github.com/wolfSSL/wolfssl/pull/8736 - +* [Low CVE-2025-12889] With TLS 1.2 connections a client can use any digest, specifically a weaker digest, rather than those in the CertificateRequest. Thanks to Jaehun Lee from Pohang University of Science and Technology (POSTECH) for the report. Fixed in PR 9395 ## New Features -* Multiple sessions are now supported in the sniffer due to the removal of a cached check. (PR #8723) -* New API ssl_RemoveSession() has been implemented for sniffer cleanup operations. (PR #8768) -* The new ASN X509 API, `wc_GetSubjectPubKeyInfoDerFromCert`, has been introduced for retrieving public key information from certificates. (PR #8758) -* `wc_PKCS12_create()` has been enhanced to support PBE_AES(256|128)_CBC key and certificate encryptions. (PR #8782, PR #8822, PR #8859) -* `wc_PKCS7_DecodeEncryptedKeyPackage()` has been added for decoding encrypted key packages. (PR #8976) -* All AES, SHA, and HMAC functionality has been implemented within the Linux Kernel Module. (PR #8998) -* Additions to the compatibility layer have been introduced for X.509 extensions and RSA PSS. Adding the API i2d_PrivateKey_bio, BN_ucmp and X509v3_get_ext_by_NID. (PR #8897) -* Added support for STM32N6. (PR #8914) -* Implemented SHA-256 for PPC 32 assembly. (PR #8894) +* New ML-KEM / ML-DSA APIs and seed/import PKCS8 support; added _new/_delete APIs for ML-KEM/ML-DSA. (PR 9039, 9000, 9049) +* Initial wolfCrypt FreeBSD kernel module support (PR 9392) +* Expanded PKCS7/CMS capabilities: decode SymmetricKeyPackage / OneSymmetricKey, add wc_PKCS7_GetEnvelopedDataKariRid, and allow PKCS7 builds with AES keywrap unset. (PR 9018, 9029, 9032) +* Add custom AES key wrap/unwrap callbacks and crypto callback copy/free operations. (PR 9002, 9309) +* Add support for certificate_authorities extension in ClientHello and certificate manager CA-type selection/unloading. (PR 9209, 9046) +* Large expansion of Rust wrapper modules: random, aes, rsa, ecc, dh, sha, hmac, cmac, ed25519/ed448, pbkdf2/PKCS#12, kdf/prf, SRTP KDFs, and conditional compilation options. (PR 9191, 9212, 9273, 9306, 9320, 9328, 9368, 9389, 9357, 9433) +* Rust: support optional heap and dev_id parameters and enable conditional compilation based on C build options. (PR 9407, 9433) +* STM32 fixes (benchmarking and platform fixes) and PSoC6 hardware acceleration additions. (PR 9228, 9256, 9185) +* STM32U5 added support for SAES and DHUK. (PR 9087) +* Add --enable-curl=tiny option for a smaller build when used with cURL. (PR 9174) ## Improvements / Optimizations - -### Linux Kernel Module (LinuxKM) Enhancements -* Registered DH and FFDHE for the Linux Kernel Module. (PR #8707) -* Implemented fixes for standard RNG in the Linux Kernel Module. (PR #8718) -* Added an ECDSA workaround for the Linux Kernel Module. (PR #8727) -* Added more PKCS1 pad SHA variants for RSA in the Linux Kernel Module. (PR #8730) -* Set default priority to 100000 for LKCAPI in the Linux Kernel Module. (PR #8740) -* Ensured ECDH never has FIPS enabled in the Linux Kernel Module. (PR #8751) -* Implemented further Linux Kernel Module and SP tweaks. (PR #8773) -* Added sig_alg support for Linux 6.13 RSA in the Linux Kernel Module. (PR #8796) -* Optimized wc_linuxkm_fpu_state_assoc. (PR #8828) -* Ensured DRBG is multithread-round-1 in the Linux Kernel Module. (PR #8840) -* Prevented toggling of fips_enabled in the Linux Kernel Module. (PR #8873) -* Refactored drbg_ctx clear in the Linux Kernel Module. (PR #8876) -* Set sig_alg max_size and digest_size callbacks for RSA in the Linux Kernel Module. (PR #8915) -* Added get_random_bytes for the Linux Kernel Module. (PR #8943) -* Implemented distro fix for the Linux Kernel Module. (PR #8994) -* Fixed page-flags-h in the Linux Kernel Module. (PR #9001) -* Added MODULE_LICENSE for the Linux Kernel Module. (PR #9005) -* Post-Quantum Cryptography (PQC) & Asymmetric Algorithms -* Kyber has been updated to the MLKEM ARM file for Zephyr (PR #8781) -* Backward compatibility has been implemented for ML_KEM IDs (PR #8827) -* ASN.1 is now ensured to be enabled when only building PQ algorithms (PR #8884) -* Building LMS with verify-only has been fixed (PR #8913) -* Parameters for LMS SHA-256_192 have been corrected (PR #8912) -* State can now be saved with the private key for LMS (PR #8836) -* Support for OpenSSL format has been added for ML-DSA/Dilithium (PR #8947) -* `dilithium_coeff_eta2[]` has been explicitly declared as signed (PR #8955) - -### Build System & Portability -* Prepared for the inclusion of v5.8.0 in the Ada Alire index. (PR #8714) -* Introduced a new build option to allow reuse of the Windows crypt provider handle. (PR #8706) -* Introduced general fixes for various build configurations. (PR #8763) -* Made improvements for portability using older GCC 4.8.2. (PR #8753) -* Macro guards updated to allow tests to build with opensslall and no server. (PR #8776) -* Added a check for STDC_NO_ATOMICS macro before use of atomics. (PR #8885) -* Introduced CMakePresets.json and CMakeSettings.json. (PR #8905) -* Added an option to not use constant time code with min/max. (PR #8830) -* Implemented proper MacOS dispatch for conditional signal/wait. (PR #8928) -* Disabled MD5 by default for both general and CMake builds. (PR #8895, PR #8948) -* Improved to allow building OPENSSL_EXTRA without KEEP_PEER_CERT. (PR #8926) -* Added introspection for Intel and ARM assembly speedups. (PR #8954) -* Fixed cURL config to set HAVE_EX_DATA and HAVE_ALPN. (PR #8973) -* Moved FREESCALE forced algorithm HAVE_ECC to IDE/MQX/user_settings.h. (PR #8977) - -### Testing & Debugging -* Fixed the exit status for testwolfcrypt. (PR #8762) -* Added WOLFSSL_DEBUG_PRINTF and WOLFSSL_DEBUG_CERTIFICATE_LOADS for improved debugging output. (PR #8769, PR #8770) -* Guarded some benchmark tests with NO_SW_BENCH. (PR #8760) -* Added an additional unit test for wolfcrypt PKCS12 file to improve code coverage. (PR #8831) -* Added an additional unit test for increased DH code coverage. (PR #8837) -* Adjusted for warnings with NO_TLS build and added GitHub actions test. (PR #8851) -* Added additional compatibility layer RAND tests. (PR #8852) -* Added an API unit test for checking domain name. (PR #8863) -* Added bind v9.18.33 testing. (PR #8888) -* Fixed issue with benchmark help options and descriptions not lining up. (PR #8957) - -### Certificates & ASN.1 -* Changed the algorithm for sum in ASN.1 OIDs. (PR #8655) -* Updated PKCS7 to use X509 STORE for internal verification. (PR #8748) -* Improved handling of temporary buffer size for X509 extension printing. (PR #8710) -* Marked IP address as WOLFSSL_V_ASN1_OCTET_STRING for ALT_NAMES_OID. (PR #8842) -* Fixed printing empty names in certificates. (PR #8880) -* Allowed CA:FALSE on wolftpm. (PR #8925) -* Fixed several inconsistent function prototype parameter names in wc/asn. (PR #8949) -* Accounted for custom extensions when creating a Cert from a WOLFSSL_X509. (PR #8960) - -### TLS/DTLS & Handshake -* Checked group correctness outside of TLS 1.3 too for TLSX_UseSupportedCurve. (PR #8785) -* Dropped records that span datagrams in DTLS. (PR #8642) -* Implemented WC_NID_netscape_cert_type. (PR #8800) -* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) -* Correctly set the current peer in dtlsProcessPendingPeer. (PR #8848) -* Fixed set_groups for TLS. (PR #8824) -* Allowed trusted_ca_keys with TLSv1.3. (PR #8860) -* Moved Dtls13NewEpoch into DeriveTls13Keys. (PR #8858) -* Cleared tls1_3 on downgrade. (PR #8861) -* Always sent ACKs on detected retransmission for DTLS1.3. (PR #8882) -* Removed DTLS from echo examples. (PR #8889) -* Recalculated suites at SSL initialization. (PR #8757) -* No longer using BIO for ALPN. (PR #8969) -* Fixed wolfSSL_BIO_new_connect's handling of IPV6 addresses. (PR #8815) -* Memory Management & Optimizations -* Performed small stack refactors, improved stack size with mlkem and dilithium, and added additional tests. (PR #8779) -* Implemented FREE_MP_INT_SIZE in heap math. (PR #8881) -* Detected correct MAX_ENCODED_SIG_SZ based on max support in math lib. (PR #8931) -* Fixed improper access of sp_int_minimal using sp_int. (PR #8985) - -### Cryptography & Hash Functions -* Implemented WC_SIPHASH_NO_ASM for not using assembly optimizations with siphash. (PR #8789, PR #8791) -* Added missing DH_MAX_SIZE define for FIPS and corrected wolfssl.rc FILETYPE to VFT_DLL. (PR #8794) -* Implemented WC_SHA3_NO_ASM for not using assembly with SHA3. (PR #8817) -* Improved Aarch64 XFENCE. (PR #8832) -* Omitted frame pointer for ARM32/Thumb2/RISC-V 64 assembly. (PR #8893) -* Fixed branch instruction in ARMv7a ASM. (PR #8933) -* Enabled EVP HMAC to work with WOLFSSL_HMAC_COPY_HASH. (PR #8944) -* Platform-Specific & Hardware Integration -* Added HAVE_HKDF for wolfssl_test and explicit support for ESP32P4. (PR #8742) -* Corrected Espressif default time setting. (PR #8829) -* Made wc_tsip_* APIs public. (PR #8717) -* Improved PlatformIO Certificate Bundle Support. (PR #8847) -* Fixed the TSIP TLS example program. (PR #8857) -* Added crypto callback functions for TROPIC01 secure element. (PR #8812) -* Added Renesas RX TSIP AES CTR support. (PR #8854) -* Fixed TSIP port using crypto callback. (PR #8937) - -### General Improvements & Refactoring -* Attempted wolfssl_read_bio_file in read_bio even when XFSEEK is available. (PR #8703) -* Refactored GetHandshakeHeader/GetHandShakeHeader into one function. (PR #8787) -* Updated libspdm from 3.3.0 to 3.7.0. (PR #8906) -* Fixed missing dashes on the end of header and footer for Falcon PEM key. (PR #8904) -* Fixed minor code typos for macos signal and types.h max block size. (PR #8934) -* Make the API wolfSSL_X509_STORE_CTX_get_error accessible to more build configurations for ease of getting the "store" error code and depth with certificate failure callback implementations. (PR #8903) +* Regression test fixes and expansion: TLS 1.3/1.2 tests, ARDUINO examples, libssh2 tests, hostap workflows, and nightly test improvements. (PR 9096, 9141, 9091, 9122, 9388) +* Improved test ordering and CI test stability (random tests run order changes, FIPS test fixes). (PR 9204, 9257) +* Docs and readme fixes, docstring updates, AsconAEAD comment placement, and example certificate renewals. (PR 9131, 9293, 9262, 9429) +* Updated GPL exception lists (GPLv2 and GPLv3 exception updates: add Fetchmail and OpenVPN). (PR 9398, 9413) +* Introduced WOLFSSL_DEBUG_CERTS and additional debug/logging refinements. (PR 8902, 9055) +* Expanded crypto-callback support (SHA family, HKDF, SHA-224, sha512_family digest selection) and improved crypto-only build cases. (PR 9070, 9252, 9271, 9100, 9194) +* AES & HW offload improvements including AES-CTR support in PKCS11 driver and AES ECB offload sizing fix. (PR 9277, 9364) +* ESP32: PSRAM allocator support and SHA HW fixes for ESP-IDF v6/v5. (PR 8987, 9225, 9264) +* Renesas FSP / RA examples updated and security-module TLS context improvements. (PR 9047, 9010, 9158, 9150) +* Broad configure/CMake/Autotools workflow improvements (Apple options tracking, Watcom pinning, Debian packaging, ESP-IDF pinning). (PR 9037, 9167, 9161, 9264) +* New assembly introspection / performance helpers for RISC-V and PPC32; benchmarking enhancements (cycle counts). (PR 9101, 9317) +* Update to SGX build for using assembly optimizations. (PR 8463, 9138) +* Testing with Fil-C compiler version to 0.674 (PR 9396) +* Refactors and compressing of small stack code (PR 9153) ## Bug Fixes -* Fixed issues to support _WIN32_WCE (VS 2008 with WinCE 6.0/7.0). (PR #8709) -* Fixed STM32 Hash with IRQ enabled. (PR #8705) -* Fixed raw hash when using crypto instructions on RISC-V 64-bit. (PR #8733) -* Fixed ECDH decode secret in the Linux Kernel Module. (PR #8729) -* Passed in the correct hash type to wolfSSL_RSA_verify_ex. (PR #8726) -* Fixed issues for Intel QuickAssist latest driver (4.28). (PR #8728) -* Speculative fix for CodeSonar overflow issue in ssl_certman.c. (PR #8715) -* Fixed Arduino progmem print and AVR WOLFSSL_USER_IO. (PR #8668) -* Correctly advanced the index in wc_HKDF_Expand_ex. (PR #8737) -* Fixed STM32 hash status check logic, including NO_AES_192 and NO_AES_256. (PR #8732) -* Added missing call to wolfSSL_RefFree in FreeCRL to prevent memory leaks. (PR #8750) -* Fixed sanity check on --group with unit test app and null sanity check with des decrypt. (PR #8711) -* Fixed Curve25519 and static ephemeral issue with blinding. (PR #8766) -* Fixed edge case issue with STM32 AES GCM auth padding. (PR #8745) -* Removed redefinition of MlKemKey and fixed build issue in benchmark. (PR #8755) -* Used proper heap hint when freeing CRL in error case. (PR #8713) -* Added support for no malloc with wc_CheckCertSigPubKey. (PR #8725) -* Fixed C# wrapper Release build. (PR #8802) -* Handled malformed CCS and CCS before CH in TLS1.3. (PR #8788) -* Fixed ML-DSA with WOLFSSL_DILITHIUM_NO_SIGN. (PR #8798) -* Fixed AesGcmCrypt_1 no-stream in the Linux Kernel Module. (PR #8814) -* Fixed return value usage for crypto_sig_sign in the Linux Kernel Module. (PR #8816) -* Fixed issue with CSharp and Windows CE with conversion of ASCII and Unicode. (PR #8799) -* Fixed Renesas SCE on RA6M4. (PR #8838) -* Fixed tests for different configs for ML-DSA. (PR #8865) -* Fixed bug in ParseCRL_Extensions around the size of a CRL number handled and CRL number OID. (PR #8587) -* Fixed uninitialized wc_FreeRng in prime_test. (PR #8886) -* Fixed ECC configuration issues with ECC verify only and no RNG. (PR #8901) -* Fixed issues with max size, openssl.test netcat, and clang-tidy. (PR #8909) -* Fixed for casting down and uninit issues in Dilithium/ML-DSA. (PR #8868) -* Fixed memory allocation failure testing and related unit test cases. (PR #8945, PR #8952) -* Fixed build issue with ML-DSA 44 only. (PR #8981) -* Fixed possible memory leak with X509 reference counter when using x509small. (PR #8982) +* Removed the test feature using popen when defining the macro WOLFSSL_USE_POPEN_HOST and not having HAVE_GETADDRINFO defined, along with having the macro HAVE_HTTP_CLIENT set. There was the potential for vulnerable behavior with the use of popen when the API wolfSSL_BIO_new_connect() was called with this specific build. This exact build configuration is only intended for testing with QEMU and is not enabled with any autoconf/cmake flags. Thanks to linraymond2006 for the report. (PR 9038) +* Fix for C# wrapper Ed25519 potential crash and heap overwrite with raw public key import when using the API Ed25519ImportPublic.This was a broken API with the C# wrapper that would crash on use. Thanks to Luigino Camastra from Aisle Research for the bug report. (PR 9291) +* Coverity, cppcheck, MISRA, clang-tidy, ZeroPath and other static-analysis driven fixes across the codebase. (PR 9006, 9078, 9068, 9265, 9324) +* TLS 1.2/DTLS improvements: client message order checks, DTLS cookie/exchange and replay protections, better DTLS early-data handling. (PR 9387, 9253, 9205, 9367) +* Improved X.509 & cert handling: allow larger pathLen in Basic Constraints, restore inner server name for ECH, retrying cert candidate chains. (PR 8890, 9234, 8692) +* Sniffer robustness: fix infinite recursion, better handling of OOO appData and partial overlaps, and improved retransmission detection. (PR 9051, 9106, 9140, 9094) +* Numerous linuxkm (kernel-mode) fixes, relocation/PIE normalization, and FIPS-related build tweaks across many iterations. (PR 9025, 9035, 9067, 9111, 9121) +* ML-KEM/Kyber and ML-DSA fixes for out-of-bounds and seed-import correctness; multiple ML-related safety fixes. (PR 9142, 9105, 9439) +* Avoid uninitialized-variable and GCC warnings; several fixes for undefined-shift/overflow issues. (PR 9020, 9372, 9195) +* Memory & leak fixes in X509 verification and various struct sizing fixes for WOLFSSL_NO_MALLOC usage. (PR 9258, 9036) +* Fixed RSA / signing / verify-only warnings allowing WOLFSSL_NO_CT_OPS when WOLFSSL_RSA_VERIFY_ONLY is used and API cleanups for using const. (PR 9031, 9263) For additional vulnerability information visit the vulnerability page at: https://www.wolfssl.com/docs/security-vulnerabilities/ @@ -356,46 +230,46 @@ More info can be found on-line at: https://wolfssl.com/wolfSSL/Docs.html ``` -├── certs [Certificates used in tests and examples] -├── cmake [Cmake build utilities] -├── debian [Debian packaging files] -├── doc [Documentation for wolfSSL (Doxygen)] -├── Docker [Prebuilt Docker environments] -├── examples [wolfSSL examples] -│   ├── asn1 [ASN.1 printing example] -│   ├── async [Asynchronous Cryptography example] -│   ├── benchmark [TLS benchmark example] -│   ├── client [Client example] -│   ├── configs [Example build configurations] -│   ├── echoclient [Echoclient example] -│   ├── echoserver [Echoserver example] -│   ├── pem [Example for convert between PEM and DER] -│   ├── sctp [Servers and clients that demonstrate wolfSSL's DTLS-SCTP support] -│   └── server [Server example] -├── IDE [Contains example projects for various development environments] -├── linuxkm [Linux Kernel Module implementation] -├── m4 [Autotools utilities] -├── mcapi [wolfSSL MPLAB X Project Files] -├── mplabx [wolfSSL MPLAB X Project Files] -├── mqx [wolfSSL Freescale CodeWarrior Project Files] -├── rpm [RPM packaging metadata] -├── RTOS -│   └── nuttx [Port of wolfSSL for NuttX] -├── scripts [Testing scripts] -├── src [wolfSSL source code] -├── sslSniffer [wolfSSL sniffer can be used to passively sniff SSL traffic] -├── support [Contains the pkg-config file] -├── tests [Unit and configuration testing] -├── testsuite [Test application that orchestrates tests] -├── tirtos [Port of wolfSSL for TI RTOS] -├── wolfcrypt [The wolfCrypt component] -│   ├── benchmark [Cryptography benchmarking application] -│   ├── src [wolfCrypt source code] -│   │   └── port [Supported hardware acceleration ports] -│   └── test [Cryptography testing application] -├── wolfssl [Header files] -│   ├── openssl [Compatibility layer headers] -│   └── wolfcrypt [Header files] -├── wrapper [wolfSSL language wrappers] -└── zephyr [Port of wolfSSL for Zephyr RTOS] +├── certs [Certificates used in tests and examples] +├── cmake [Cmake build utilities] +├── debian [Debian packaging files] +├── doc [Documentation for wolfSSL (Doxygen)] +├── Docker [Prebuilt Docker environments] +├── examples [wolfSSL examples] +│   ├── asn1 [ASN.1 printing example] +│   ├── async [Asynchronous Cryptography example] +│   ├── benchmark [TLS benchmark example] +│   ├── client [Client example] +│   ├── configs [Example build configurations] +│   ├── echoclient [Echoclient example] +│   ├── echoserver [Echoserver example] +│   ├── pem [Example for convert between PEM and DER] +│   ├── sctp [Servers and clients that demonstrate wolfSSL's DTLS-SCTP support] +│   └── server [Server example] +├── IDE [Contains example projects for various development environments] +├── linuxkm [Linux Kernel Module implementation] +├── m4 [Autotools utilities] +├── mcapi [wolfSSL MPLAB X Project Files] +├── mplabx [wolfSSL MPLAB X Project Files] +├── mqx [wolfSSL Freescale CodeWarrior Project Files] +├── rpm [RPM packaging metadata] +├── RTOS +│   └── nuttx [Port of wolfSSL for NuttX] +├── scripts [Testing scripts] +├── src [wolfSSL source code] +├── sslSniffer [wolfSSL sniffer can be used to passively sniff SSL traffic] +├── support [Contains the pkg-config file] +├── tests [Unit and configuration testing] +├── testsuite [Test application that orchestrates tests] +├── tirtos [Port of wolfSSL for TI RTOS] +├── wolfcrypt [The wolfCrypt component] +│   ├── benchmark [Cryptography benchmarking application] +│   ├── src [wolfCrypt source code] +│   │   └── port [Supported hardware acceleration ports] +│   └── test [Cryptography testing application] +├── wolfssl [Header files] +│   ├── openssl [Compatibility layer headers] +│   └── wolfcrypt [Header files] +├── wrapper [wolfSSL language wrappers] +└── zephyr [Port of wolfSSL for Zephyr RTOS] ``` diff --git a/examples/template/template.ino b/examples/template/template.ino index 8998976..0d0f8d8 100644 --- a/examples/template/template.ino +++ b/examples/template/template.ino @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -21,6 +21,13 @@ #include +#if defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include +#endif + /* wolfSSL user_settings.h must be included from settings.h * Make all configurations changes in user_settings.h * Do not edit wolfSSL `settings.h` or `config.h` files. diff --git a/examples/template/wolfssl_helper.c b/examples/template/wolfssl_helper.c index f4eeb57..c6dcd39 100644 --- a/examples/template/wolfssl_helper.c +++ b/examples/template/wolfssl_helper.c @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -26,10 +26,36 @@ * Be sure to include these files in all libraries that reference * wolfssl in this order: */ -#include -/* settings.h is typically included in wolfssl.h, but here as a reminder: */ -#include -#include +#if defined(ARDUINO_PORTENTA_X8) + /* This file is purposely a c and not .cpp file for testing. + * On Portenta X8 the core headers assume C++, and things like A6, + * PIN_SPI_MOSI, etc. - rely on C++-only constructs. + * So don't include Arduino.h here for Portenta. */ + + #include + #include /* The ssl.h usually included by wolfssl.h */ + + #ifdef __cplusplus + extern "C" { + #endif + + /* Sample source code is C, but Arduino is compiling with C++ + * Declare a helper function to be used in wolfssl/wolfcrypt/logging.c */ + int wolfSSL_Arduino_Serial_Print(const char* const s); + + #ifdef __cplusplus + } + #endif +#else + /* Assume all other target boards would want to include Arduino.h in a + * helper such as this one. Not needed in this wolfssl_helper.c example. */ + #include + + /* settings.h is typically included in wolfssl.h, but here as a reminder: */ + #include + #include /* The wolfssl core Arduino library file */ +#endif + #include "wolfssl_helper.h" diff --git a/examples/template/wolfssl_helper.h b/examples/template/wolfssl_helper.h index 844f022..1291dbe 100644 --- a/examples/template/wolfssl_helper.h +++ b/examples/template/wolfssl_helper.h @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, diff --git a/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino b/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino index 31ef797..a47d096 100644 --- a/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino +++ b/examples/wolfssl_AES_CTR/wolfssl_AES_CTR.ino @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -19,6 +19,15 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include + +#if defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include +#endif + /* The Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001. @@ -50,7 +59,21 @@ Teensy 4.1 (ARM Cortex M7) */ #define WOLFSSL_AES_CTR_EXAMPLE +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ #include + + /* settings.h is included from Arduino `wolfssl.h`, but a good practice to + * include before any other wolfssl headers. As a reminder here: */ +#include + #include #if defined(NO_AES) or !defined(WOLFSSL_AES_COUNTER) or !defined(WOLFSSL_AES_128) diff --git a/examples/wolfssl_client/wolfssl_client.ino b/examples/wolfssl_client/wolfssl_client.ino index 8af1eaf..c56de7f 100644 --- a/examples/wolfssl_client/wolfssl_client.ino +++ b/examples/wolfssl_client/wolfssl_client.ino @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -39,6 +39,18 @@ Tested with: /* If you have a private include, define it here, otherwise edit WiFi params */ /* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ +#if defined(ARDUINO) && defined(ESP8266) + #warning "This example is not yet supported on Arduino ESP8266" +#endif + +#if defined(DEBUG_WOLFSSL) + /* Optionally enabled verbose wolfSSL debugging */ + #define DEBUG_WOLFSSL_MESSAGES_ON +#else + /* DEBUG_WOLFSSL needs to be enabled */ + #undef DEBUG_WOLFSSL_MESSAGES_ON +#endif + /* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ #define REPEAT_CONNECTION 0 @@ -68,12 +80,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; - static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - static const char ssid[] PROGMEM = "your_SSID"; - static const char password[] PROGMEM = "your_PASSWORD"; + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -132,6 +144,10 @@ Tested with: #elif defined(ESP8266) #define USING_WIFI #include + /* Ensure the F() flash macro is defined */ + #ifndef F + #define F + #endif WiFiClient client; #elif defined(ARDUINO_SAM_DUE) @@ -140,7 +156,10 @@ Tested with: /* Needs "Ethernet by Various" library to be installed. Tested with V2.0.2 */ #include EthernetClient client; - +#elif defined(ARDUINO_AVR_ETHERNET) || defined(ARDUINO_AVR_LEONARDO_ETH) + /* Boards such as arduino:avr:ethernet and arduino:avr:leonardoeth */ + #include + EthernetClient client; #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define USING_WIFI #include @@ -153,6 +172,36 @@ Tested with: #include WiFiClient client; +#elif defined(ARDUINO_SAMD_TIAN) + #include + #include + HttpClient client; + /* Arduino Tian does not support network shields like the standard Ethernet or Wi-Fi shields. */ + #error "HttpClient cannot be used for this example" +#elif defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include + + /* ----No - network placeholders(compile - only) ---- */ + #include + struct X8NoNetClient { + int write(const uint8_t*, size_t) { return -1; } + int available() { return 0; } + int read() { return -1; } + void stop() {} + bool connected() { return false; } + IPAddress remoteIP() { return IPAddress(0, 0, 0, 0); } + }; + struct X8NoNetServer { + explicit X8NoNetServer(uint16_t) {} + void begin() {} + X8NoNetClient available() { return X8NoNetClient(); } + }; + + X8NoNetClient client; + X8NoNetServer server(WOLFSSL_PORT); #elif defined(USING_WIFI) #define USING_WIFI #include @@ -205,7 +254,10 @@ static char errBuf[80]; static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); static int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx); static int reconnect = RECONNECT_ATTEMPTS; +#if 0 +/* optional showPeerEx, currently disabled */ static int lng_index PROGMEM = 0; /* 0 = English */ +#endif #if defined(__arm__) #include @@ -462,7 +514,8 @@ int setup_network(void) { /*****************************************************************************/ /* Arduino setup_wolfssl() */ /*****************************************************************************/ -int setup_wolfssl(void) { +int setup_wolfssl(void) +{ int ret = 0; WOLFSSL_METHOD* method; @@ -482,8 +535,14 @@ int setup_wolfssl(void) { #endif #if defined(DEBUG_WOLFSSL) - wolfSSL_Debugging_ON(); - Serial.println(F("wolfSSL Debugging is On!")); + Serial.println(F("wolfSSL Debugging is available! (DEBUG_WOLFSSL)")); + #if defined(DEBUG_WOLFSSL_MESSAGES_ON) + Serial.println(F("Enabling verbose messages wolfSSL_Debugging_ON")); + wolfSSL_Debugging_ON(); + #else + Serial.println(F("Enable verbose messages with wolfSSL_Debugging_ON")); + Serial.println(F("or define DEBUG_WOLFSSL_MESSAGES_ON")); + #endif #else Serial.println(F("wolfSSL Debugging is Off! (enable with DEBUG_WOLFSSL)")); #endif @@ -509,6 +568,7 @@ int setup_wolfssl(void) { * It is best on embedded devices to choose a TLS session cache size. */ #endif + /* Initialize wolfSSL before assigning ctx */ ret = wolfSSL_Init(); if (ret == WOLFSSL_SUCCESS) { Serial.println("Successfully called wolfSSL_Init"); @@ -543,7 +603,8 @@ int setup_wolfssl(void) { /*****************************************************************************/ /* Arduino setup_certificates() */ /*****************************************************************************/ -int setup_certificates(void) { +int setup_certificates(void) +{ int ret = 0; Serial.println(F("Initializing certificates...")); @@ -609,7 +670,8 @@ int setup_certificates(void) { /* Arduino setup() */ /*****************************************************************************/ /*****************************************************************************/ -void setup(void) { +void setup(void) +{ int i = 0; Serial.begin(SERIAL_BAUD); while (!Serial && (i < 10)) { @@ -650,13 +712,17 @@ void setup(void) { wolfSSL_SetIOSend(ctx, EthernetSend); wolfSSL_SetIORecv(ctx, EthernetReceive); +#if defined THIS_USER_SETTINGS_VERSION + Serial.print(F("This user_settings.h version:")) + Serial.println(THIS_USER_SETTINGS_VERSION) +#endif + Serial.println(F("Completed Arduino setup!")); /* See companion wolfssl_server.ino code; server begins listening here * https://github.com/wolfSSL/wolfssl/tree/master/IDE/ARDUINO/sketches/wolfssl_server * Any other server will work. See also: * https://github.com/wolfSSL/wolfssl/tree/master/examples/client */ - /* See companion wolfssl_server.ino code */ return; } /* Arduino setup */ @@ -731,7 +797,7 @@ int error_check_ssl(WOLFSSL* ssl, int this_ret, bool halt_on_error, } return err; -} +} /* error_check_ssl */ /*****************************************************************************/ /*****************************************************************************/ diff --git a/examples/wolfssl_client_dtls/README.md b/examples/wolfssl_client_dtls/README.md new file mode 100644 index 0000000..924225b --- /dev/null +++ b/examples/wolfssl_client_dtls/README.md @@ -0,0 +1,28 @@ +# Arduino Basic DTLS Listening Client + +Open the [wolfssl_client_dtls.ino](./wolfssl_client_dtls.ino) file in the Arduino IDE. + +If using WiFi, be sure to set `ssid` and `password` values. + +May need "Ethernet by Various" library to be installed. Tested with v2.0.2 and v2.8.1. + +See the `#define WOLFSSL_TLS_SERVER_HOST` to set your own server address. + +Other IDE products are also supported, such as: + +- [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) +- [VisualGDB](https://visualgdb.com/tutorials/arduino/) +- [VisualMicro](https://www.visualmicro.com/) + +For examples on other platforms, see the [IDE directory](https://github.com/wolfssl/wolfssl/tree/master/IDE). +Additional examples can be found on [wolfSSL/wolfssl-examples](https://github.com/wolfSSL/wolfssl-examples/). + + +### Troubleshooting + +When encountering odd errors such as `undefined reference to ``_impure_ptr'`, try cleaning the Arduino +cache directories. For Windows, that's typically in: + +```text +C:\Users\%USERNAME%\AppData\Local\Temp\arduino\sketches +``` diff --git a/examples/wolfssl_client_dtls/wolfssl_client_dtls.ino b/examples/wolfssl_client_dtls/wolfssl_client_dtls.ino new file mode 100644 index 0000000..e4e8fec --- /dev/null +++ b/examples/wolfssl_client_dtls/wolfssl_client_dtls.ino @@ -0,0 +1,950 @@ +/* + * client-dtls13.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + *============================================================================= + * + * Bare-bones example of a DTLS 1.3 client for instructional/learning purposes. + * This example uses blocking sockets for simplicity. + * + * Define USE_DTLS12 to use DTLS 1.2 instead of DTLS 1.3 +/* +Tested with: + +1) Intel Galileo acting as the Client, with a laptop acting as a server using + the server example provided in examples/server. + Legacy Arduino v1.86 was used to compile and program the Galileo + +2) Espressif ESP32 WiFi + +3) Arduino Due, Nano33 IoT, Nano RP-2040 +*/ + +/* + * Note to code editors: the Arduino client and server examples are edited in + * parallel for side-by-side comparison between examples. + */ + +/* If you have a private include, define it here, otherwise edit WiFi params */ +/* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ + +#if defined(ARDUINO) && defined(ESP8266) + #warning "This example is not yet supported on Arduino ESP8266" +#endif + +#if defined(DEBUG_WOLFSSL) + /* Optionally enabled verbose wolfSSL debugging */ + #define DEBUG_WOLFSSL_MESSAGES_ON +#else + /* DEBUG_WOLFSSL needs to be enabled */ + #undef DEBUG_WOLFSSL_MESSAGES_ON +#endif + +/* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ +#define REPEAT_CONNECTION 0 + +/* Edit this with your other DTLS host server address to connect to: */ +#define WOLFSSL_DTLS_SERVER_HOST "192.168.1.107" + +/* wolfssl TLS examples communicate on port 11111 */ +#define WOLFSSL_PORT 11111 + +/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ +#define SERIAL_BAUD 115200 + +/* We'll wait up to 2000 milliseconds to properly shut down connection */ +#define SHUTDOWN_DELAY_MS 2000 + +/* Number of times to retry connection. */ +#define RECONNECT_ATTEMPTS 20 + +/* Number of DTLS messages to send. Use -1 for continual messages. */ +#define DTLS_MESSAGE_CT 42 + +/* Assume bad socket until proven otherwise */ +#define INVALID_SOCKET -1 + +/* Maximum size in bytes of buffer to send and receive */ +#define MAXLINE 128 + +/* Optional stress test. Define to consume memory until exhausted: */ +/* #define MEMORY_STRESS_TEST */ + +/* Choose client or server example, not both. */ +#define WOLFSSL_CLIENT_EXAMPLE +/* #define WOLFSSL_SERVER_EXAMPLE */ + +#if defined(MY_PRIVATE_CONFIG) + /* the /workspace directory may contain a private config + * excluded from GitHub with items such as WiFi passwords */ + #include MY_PRIVATE_CONFIG + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; +#else + /* when using WiFi capable boards: */ + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; +#endif + +#define BROADCAST_ADDRESS "255.255.255.255" + +/* There's an optional 3rd party NTPClient library by Fabrice Weinberg. + * If it is installed, uncomment define USE_NTP_LIB here: */ +/* #define USE_NTP_LIB */ +#ifdef USE_NTP_LIB + #include +#endif + +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ +#include +/* Important: make sure settings.h appears before any other wolfSSL headers */ +#include +/* Reminder: settings.h includes user_settings.h + * For ALL project wolfSSL settings, see: + * [your path]/Arduino\libraries\wolfSSL\src\user_settings.h */ +#include +#include +#include + +#ifndef WOLFSSL_DTLS + /* Support for DTLS by default was added after wolfSSL v5.8.2 release */ + #error "This example requires WOLFSSL_DTLS. See user_settings.h in the Arduino wolfssl library" +#endif + +/* Define DEBUG_WOLFSSL in user_settings.h for more verbose logging. */ +#if defined(DEBUG_WOLFSSL) + #define PROGRESS_DOT F("") +#else + #define PROGRESS_DOT F(".") +#endif + +/* Convert a macro to a string */ +#define xstr(x) str(x) +#define str(x) #x + +/* optional board-specific networking includes */ +#if defined(ESP32) + #define USING_WIFI + #include + #include + #ifdef USE_NTP_LIB + WiFiUDP ntpUDP; + #endif + /* Ensure the F() flash macro is defined */ + #ifndef F + #define F + #endif + WiFiClient client; + +#elif defined(ESP8266) + #define USING_WIFI + #include + WiFiClient client; + +#elif defined(ARDUINO_SAM_DUE) + #include + /* There's no WiFi/Ethernet on the Due. Requires Ethernet Shield. + /* Needs "Ethernet by Various" library to be installed. Tested with V2.0.2 */ + #include + EthernetClient client; +#elif defined(ARDUINO_AVR_ETHERNET) || defined(ARDUINO_AVR_LEONARDO_ETH) + /* Boards such as arduino:avr:ethernet and arduino:avr:leonardoeth */ + #include + EthernetClient client; + +#elif defined(ARDUINO_SAMD_NANO_33_IOT) + #define USING_WIFI + #include + #include /* Needs Arduino WiFiNINA library installed manually */ + WiFiClient client; + +#elif defined(ARDUINO_ARCH_RP2040) + #define USING_WIFI + #include + #include + WiFiClient client; + +#elif defined(ARDUINO_SAMD_TIAN) + #include + #include + HttpClient client; + /* Arduino Tian does not support network shields like the standard Ethernet or Wi-Fi shields. */ + #error "HttpClient cannot be used for this example" +#elif defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include + + /* ----No - network placeholders(compile - only) ---- */ + #include + struct X8NoNetClient { + int write(const uint8_t*, size_t) { return -1; } + int available() { return 0; } + int read() { return -1; } + void stop() {} + bool connected() { return false; } + IPAddress remoteIP() { return IPAddress(0, 0, 0, 0); } + }; + struct X8NoNetServer { + explicit X8NoNetServer(uint16_t) {} + void begin() {} + X8NoNetClient available() { return X8NoNetClient(); } + }; + + X8NoNetClient client; + X8NoNetServer server(WOLFSSL_PORT); +#elif defined(USING_WIFI) + #define USING_WIFI + #include + #include + #ifdef USE_NTP_LIB + WiFiUDP ntpUDP; + #endif + WiFiClient client; + +/* TODO +#elif defined(OTHER_BOARD) +*/ +#else + /* assume all other boards using WiFi library. Edit as needed: */ + #include + #define USING_WIFI + WiFiClient client; +#endif + +/* Only for syntax highlighters to show interesting options enabled: */ +#if defined(HAVE_SNI) \ + || defined(HAVE_MAX_FRAGMENT) \ + || defined(HAVE_TRUSTED_CA) \ + || defined(HAVE_TRUNCATED_HMAC) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) \ + || defined(HAVE_SUPPORTED_CURVES) \ + || defined(HAVE_ALPN) \ + || defined(HAVE_SESSION_TICKET) \ + || defined(HAVE_SECURE_RENEGOTIATION) \ + || defined(HAVE_SERVER_RENEGOTIATION_INFO) +#endif + +static const char host[] PROGMEM = WOLFSSL_DTLS_SERVER_HOST; /* server to connect to */ +static const int port PROGMEM = WOLFSSL_PORT; /* port on server to connect to */ + +static WOLFSSL_CTX* ctx = NULL; +static WOLFSSL* ssl = NULL; +static char* wc_error_message = (char*)malloc(80 + 1); +static char errBuf[80]; + +#if defined(MEMORY_STRESS_TEST) + #define MEMORY_STRESS_ITERATIONS 100 + #define MEMORY_STRESS_BLOCK_SIZE 1024 + #define MEMORY_STRESS_INITIAL (4*1024) + static char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ + static int mem_ctr = 0; +#endif + +static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); +static int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx); +static int reconnect = RECONNECT_ATTEMPTS; +#if 0 +/* optional showPeerEx, currently disabled */ +static int lng_index PROGMEM = 0; /* 0 = English */ +#endif + +#if defined(__arm__) + #include + extern char _end; + extern "C" char *sbrk(int i); + static char *ramstart=(char *)0x20070000; + static char *ramend=(char *)0x20088000; +#endif + +/*****************************************************************************/ +/* fail_wait - in case of unrecoverable error */ +/*****************************************************************************/ +int fail_wait(void) { + show_memory(); + + Serial.println(F("Failed. Halt.")); + while (1) { + delay(1000); + } + return 0; +} + +/*****************************************************************************/ +/* show_memory() to optionally view during debugging. */ +/*****************************************************************************/ +int show_memory(void) +{ +#if defined(__arm__) + struct mallinfo mi = mallinfo(); + + char *heapend=sbrk(0); + register char * stack_ptr asm("sp"); + #if defined(DEBUG_WOLFSSL_VERBOSE) + Serial.print(" arena="); + Serial.println(mi.arena); + Serial.print(" ordblks="); + Serial.println(mi.ordblks); + Serial.print(" uordblks="); + Serial.println(mi.uordblks); + Serial.print(" fordblks="); + Serial.println(mi.fordblks); + Serial.print(" keepcost="); + Serial.println(mi.keepcost); + #endif + + #if defined(DEBUG_WOLFSSL) || defined(MEMORY_STRESS_TEST) + Serial.print("Estimated free memory: "); + Serial.print(stack_ptr - heapend + mi.fordblks); + Serial.println(F(" bytes")); + #endif + + #if (0) + /* Experimental: not supported on all devices: */ + Serial.print("RAM Start %lx\n", (unsigned long)ramstart); + Serial.print("Data/Bss end %lx\n", (unsigned long)&_end); + Serial.print("Heap End %lx\n", (unsigned long)heapend); + Serial.print("Stack Ptr %lx\n",(unsigned long)stack_ptr); + Serial.print("RAM End %lx\n", (unsigned long)ramend); + + Serial.print("Heap RAM Used: ",mi.uordblks); + Serial.print("Program RAM Used ",&_end - ramstart); + Serial.print("Stack RAM Used ",ramend - stack_ptr); + + Serial.print("Estimated Free RAM: %d\n\n",stack_ptr - heapend + mi.fordblks); + #endif +#else + Serial.println(F("show_memory() not implemented for this platform")); +#endif + return 0; +} + +/*****************************************************************************/ +/* Arduino setup_hardware() */ +/*****************************************************************************/ +int setup_hardware(void) { + int ret = 0; + +#if defined(ARDUINO_SAMD_NANO_33_IOT) + Serial.println(F("Detected known tested and working Arduino Nano 33 IoT")); +#elif defined(ARDUINO_ARCH_RP2040) + Serial.println(F("Detected known tested and working Arduino RP-2040")); +#elif defined(__arm__) && defined(ID_TRNG) && defined(TRNG) + /* need to manually turn on random number generator on Arduino Due, etc. */ + pmc_enable_periph_clk(ID_TRNG); + trng_enable(TRNG); + Serial.println(F("Enabled ARM TRNG")); +#endif + + show_memory(); + randomSeed(analogRead(0)); + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_datetime() */ +/* The device needs to have a valid date within the valid range of certs. */ +/*****************************************************************************/ +int setup_datetime(void) { + int ret = 0; + int ntp_tries = 20; + + /* we need a date in the range of cert expiration */ +#ifdef USE_NTP_LIB + #if defined(ESP32) + NTPClient timeClient(ntpUDP, "pool.ntp.org"); + + timeClient.begin(); + timeClient.update(); + delay(1000); + while (!timeClient.isTimeSet() && (ntp_tries > 0)) { + timeClient.forceUpdate(); + Serial.println(F("Waiting for NTP update")); + delay(2000); + ntp_tries--; + } + if (ntp_tries <= 0) { + Serial.println(F("Warning: gave up waiting on NTP")); + } + Serial.println(timeClient.getFormattedTime()); + Serial.println(timeClient.getEpochTime()); + #endif +#endif + +#if defined(ESP32) + /* see esp32-hal-time.c */ + ntp_tries = 5; + /* Replace "pool.ntp.org" with your preferred NTP server */ + configTime(0, 0, "pool.ntp.org"); + + /* Wait for time to be set */ + while ((time(nullptr) <= 100000) && ntp_tries > 0) { + Serial.println(F("Waiting for time to be set...")); + delay(2000); + ntp_tries--; + } +#endif + + return ret; +} /* setup_datetime */ + +/*****************************************************************************/ +/* Arduino setup_network() */ +/*****************************************************************************/ +int setup_network(void) { + int ret = 0; + +#if defined(USING_WIFI) + int status = WL_IDLE_STATUS; + + /* The ESP8266 & ESP32 support both AP and STA. We'll use STA: */ + #if defined(ESP8266) || defined(ESP32) + WiFi.mode(WIFI_STA); + #else + String fv; + if (WiFi.status() == WL_NO_MODULE) { + Serial.println("Communication with WiFi module failed!"); + /* don't continue if no network */ + while (true) ; + } + + fv = WiFi.firmwareVersion(); + if (fv < WIFI_FIRMWARE_LATEST_VERSION) { + Serial.println("Please upgrade the firmware"); + } + #endif + + Serial.print(F("Connecting to WiFi ")); + Serial.print(ssid); + status = WiFi.begin(ssid, password); + while (status != WL_CONNECTED) { + delay(1000); + Serial.print(F(".")); + Serial.print(status); + status = WiFi.status(); + } + + Serial.println(F(" Connected!")); +#else + /* Newer Ethernet shields have a + * MAC address printed on a sticker on the shield */ + byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + IPAddress ip(192, 168, 1, 42); + IPAddress myDns(192, 168, 1, 1); + Ethernet.init(10); /* Most Arduino shields */ + /* Ethernet.init(5); * MKR ETH Shield */ + /* Ethernet.init(0); * Teensy 2.0 */ + /* Ethernet.init(20); * Teensy++ 2.0 */ + /* Ethernet.init(15); * ESP8266 with Adafruit FeatherWing Ethernet */ + /* Ethernet.init(33); * ESP32 with Adafruit FeatherWing Ethernet */ + Serial.println(F("Initialize Ethernet with DHCP:")); + if (Ethernet.begin(mac) == 0) { + Serial.println(F("Failed to configure Ethernet using DHCP")); + /* Check for Ethernet hardware present */ + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println(F("Ethernet shield was not found.")); + while (true) { + delay(1); /* do nothing */ + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println(F("Ethernet cable is not connected.")); + } + /* try to configure using IP address instead of DHCP : */ + Ethernet.begin(mac, ip, myDns); + } + else { + Serial.print(F(" DHCP assigned IP ")); + Serial.println(Ethernet.localIP()); + } + /* We'll assume the Ethernet connection is ready to go. */ +#endif + + Serial.println(F("********************************************************")); + Serial.print(F(" wolfSSL Example Client IP = ")); +#if defined(USING_WIFI) + Serial.println(WiFi.localIP()); +#else + Serial.println(Ethernet.localIP()); +#endif + Serial.print(F(" Configured Server Host to connect to: ")); + Serial.println(host); + Serial.println(F("********************************************************")); + Serial.println(F("Setup network complete.")); + + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_wolfssl() */ +/*****************************************************************************/ +int setup_wolfssl(void) +{ + int ret = 0; + WOLFSSL_METHOD* method; + + /* Show a revision of wolfssl user_settings.h file in use when available: */ +#if defined(WOLFSSL_USER_SETTINGS_ID) + Serial.print(F("WOLFSSL_USER_SETTINGS_ID: ")); + Serial.println(F(WOLFSSL_USER_SETTINGS_ID)); +#else + Serial.println(F("No WOLFSSL_USER_SETTINGS_ID found.")); +#endif + +#if defined(NO_WOLFSSL_SERVER) + Serial.println(F("wolfSSL server code disabled to save space.")); +#endif +#if defined(NO_WOLFSSL_CLIENT) + Serial.println(F("wolfSSL client code disabled to save space.")); +#endif + +#if defined(DEBUG_WOLFSSL) + Serial.println(F("wolfSSL Debugging is available! (DEBUG_WOLFSSL)")); + #if defined(DEBUG_WOLFSSL_MESSAGES_ON) + Serial.println(F("Enabling verbose messages wolfSSL_Debugging_ON")); + wolfSSL_Debugging_ON(); + #else + Serial.println(F("Enable verbose messages with wolfSSL_Debugging_ON")); + Serial.println(F("or define DEBUG_WOLFSSL_MESSAGES_ON")); + #endif +#else + Serial.println(F("wolfSSL Debugging is Off! (enable with DEBUG_WOLFSSL)")); +#endif + + /* See ssl.c for TLS cache settings. Larger cache = use more RAM. */ +#if defined(NO_SESSION_CACHE) + Serial.println(F("wolfSSL TLS NO_SESSION_CACHE")); +#elif defined(MICRO_SESSION_CACHEx) + Serial.println(F("wolfSSL TLS MICRO_SESSION_CACHE")); +#elif defined(SMALL_SESSION_CACHE) + Serial.println(F("wolfSSL TLS SMALL_SESSION_CACHE")); +#elif defined(MEDIUM_SESSION_CACHE) + Serial.println(F("wolfSSL TLS MEDIUM_SESSION_CACHE")); +#elif defined(BIG_SESSION_CACHE) + Serial.println(F("wolfSSL TLS BIG_SESSION_CACHE")); +#elif defined(HUGE_SESSION_CACHE) + Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE")); +#elif defined(HUGE_SESSION_CACHE) + Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE")); +#else + Serial.println(F("WARNING: Unknown or no TLS session cache setting.")); + /* See wolfssl/src/ssl.c for amount of memory used. + * It is best on embedded devices to choose a TLS session cache size. */ +#endif + + /* Initialize wolfSSL before assigning ctx */ + ret = wolfSSL_Init(); + if (ret == WOLFSSL_SUCCESS) { + Serial.println("Successfully called wolfSSL_Init"); + } + else { + Serial.println("ERROR: wolfSSL_Init failed"); + } + + /* See companion server example with wolfSSLv23_server_method here. + * method = wolfSSLv23_client_method()); SSL 3.0 - TLS 1.3. + * method = wolfTLSv1_2_client_method(); only TLS 1.2 + * method = wolfTLSv1_3_client_method(); only TLS 1.3 + * + * see Arduino\libraries\wolfssl\src\user_settings.h */ + + Serial.println("Here we go!"); + +#ifdef WOLFSSL_DTLS13 + Serial.println(F("Setting wolfDTLSv1_3_client_method")); + method = wolfDTLSv1_3_client_method(); +#else + Serial.println(F("Setting wolfDTLSv1_2_client_method")); + method = wolfDTLSv1_2_client_method(); +#endif + ctx = wolfSSL_CTX_new(method); + if (ctx == NULL) { + fail_wait(); + } + + if (method == NULL) { + Serial.println(F("Unable to get wolfssl client method")); + fail_wait(); + } + + ctx = wolfSSL_CTX_new(method); + if (ctx == NULL) { + Serial.println(F("unable to get ctx")); + fail_wait(); + } + + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_certificates() */ +/*****************************************************************************/ +int setup_certificates(void) +{ + int ret = 0; + + /* See user_settings.h that should have included wolfssl/certs_test.h */ + + Serial.println(F("Initializing certificates...")); + show_memory(); + + /* Use built-in validation, No verification callback function: */ + wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, 0); + + /* Certificate */ + Serial.println("Initializing certificates..."); + ret = wolfSSL_CTX_use_certificate_buffer(ctx, + CTX_CLIENT_CERT, + CTX_CLIENT_CERT_SIZE, + CTX_CLIENT_CERT_TYPE); + if (ret == WOLFSSL_SUCCESS) { + Serial.print("Success: use certificate: "); + Serial.println(xstr(CTX_SERVER_CERT)); + } + else { + Serial.println(F("Error: wolfSSL_CTX_use_certificate_buffer failed: ")); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + /* Setup private client key */ + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, + CTX_CLIENT_KEY, + CTX_CLIENT_KEY_SIZE, + CTX_CLIENT_KEY_TYPE); + if (ret == WOLFSSL_SUCCESS) { + Serial.print("Success: use private key buffer: "); + Serial.println(xstr(CTX_SERVER_KEY)); + } + else { + Serial.println(F("Error: wolfSSL_CTX_use_PrivateKey_buffer failed: ")); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + ret = wolfSSL_CTX_load_verify_buffer(ctx, + CTX_CA_CERT, + CTX_CA_CERT_SIZE, + CTX_CA_CERT_TYPE); + if (ret == WOLFSSL_SUCCESS) { + Serial.println(F("Success: load_verify CTX_CA_CERT")); + } + else { + Serial.println(F("Error: wolfSSL_CTX_load_verify_buffer failed: ")); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + return ret; +} /* Arduino setup */ + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino setup() */ +/*****************************************************************************/ +/*****************************************************************************/ +void setup(void) { + int i = 0; + Serial.begin(SERIAL_BAUD); + while (!Serial && (i < 10)) { + /* wait for serial port to connect. Needed for native USB port only */ + delay(1000); + i++; + } + Serial.println(F("")); + Serial.println(F("")); + Serial.println(F("wolfSSL DTLS Client Example Startup.")); + + /* Optionally pre-allocate a large block of memory for testing */ +#if defined(MEMORY_STRESS_TEST) + Serial.println(F("WARNING: Memory Stress Test Active!")); + Serial.print(F("Allocating extra memory: ")); + Serial.print(MEMORY_STRESS_INITIAL); + Serial.println(F(" bytes...")); + memory_stress[mem_ctr] = (char*)malloc(MEMORY_STRESS_INITIAL); + show_memory(); +#endif + + setup_hardware(); + + setup_network(); + + setup_datetime(); + + setup_wolfssl(); + + setup_certificates(); + +#if defined THIS_USER_SETTINGS_VERSION + Serial.print(F("This user_settings.h version:")) + Serial.println(THIS_USER_SETTINGS_VERSION) +#endif + + Serial.println(F("Completed Arduino setup!")); + /* See companion wolfssl_server_dtls.ino code; server begins listening here + * https://github.com/wolfSSL/wolfssl-examples/tree/master/Arduino/sketches/wolfssl_server_dtls + * Any other DTLS server will work. See also: + * https://github.com/wolfSSL/wolfssl/tree/master/examples/client + */ + return; +} /* Arduino setup */ + +/*****************************************************************************/ +/* wolfSSL error_check() */ +/*****************************************************************************/ +int error_check(int this_ret, bool halt_on_error, + const __FlashStringHelper* message) { + int ret = 0; + if (this_ret == WOLFSSL_SUCCESS) { + Serial.print(F("Success: ")); + Serial.println(message); + } + else { + Serial.print(F("ERROR: return = ")); + Serial.print(this_ret); + Serial.print(F(": ")); + Serial.println(message); + Serial.println(wc_GetErrorString(this_ret)); + if (halt_on_error) { + fail_wait(); + } + } + show_memory(); + + return ret; +} /* error_check */ + +/*****************************************************************************/ +/* wolfSSL error_check_ssl */ +/* Parameters: */ +/* ssl is the current WOLFSSL object pointer */ +/* halt_on_error set to true to suspend operations for critical error */ +/* message is expected to be a memory-efficient F("") macro string */ +/*****************************************************************************/ +int error_check_ssl(WOLFSSL* ssl, int this_ret, bool halt_on_error, + const __FlashStringHelper* message) { + int err = 0; + + if (ssl == NULL) { + Serial.println(F("ssl is Null; Unable to allocate SSL object?")); +#ifndef DEBUG_WOLFSSL + Serial.println(F("Define DEBUG_WOLFSSL in user_settings.h for more.")); +#else + Serial.println(F("See wolfssl/wolfcrypt/error-crypt.h for codes.")); +#endif + Serial.print(F("ERROR: ")); + Serial.println(message); + show_memory(); + if (halt_on_error) { + fail_wait(); + } + } + else { + err = wolfSSL_get_error(ssl, this_ret); + if (err == WOLFSSL_SUCCESS) { + Serial.print(F("Success m: ")); + Serial.println(message); + } + else { + if (err < 0) { + wolfSSL_ERR_error_string(err, errBuf); + Serial.print(F("WOLFSSL Error: ")); + Serial.print(err); + Serial.print(F("; ")); + Serial.println(errBuf); + } + else { + Serial.println(F("Success: ssl object.")); + } + } + } + + return err; +} /* error_check_ssl */ + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino loop() */ +/*****************************************************************************/ +/*****************************************************************************/ +void loop() +{ + /* standard variables used in a dtls client */ + char sendLine[MAXLINE] = "Hello DTLS wolfSSL!"; + char recvLine[MAXLINE - 1]; + struct sockaddr_in servAddr; + const char* cipherName; + int msg_ct = 0; + int n = 0; + int sockfd = INVALID_SOCKET; + int err; + int ret; + int exitVal = 1; + + /* Assign ssl variable */ + ssl = wolfSSL_new(ctx); + if (ssl == NULL) { + Serial.println(F("unable to get ssl object\n")); + goto cleanup; + } + + /* servAddr setup */ + memset(&servAddr, 0, sizeof(servAddr)); + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(WOLFSSL_PORT); + if (inet_pton(AF_INET, WOLFSSL_DTLS_SERVER_HOST, &servAddr.sin_addr) < 1) { + perror("inet_pton()"); + goto cleanup; + } + + if (wolfSSL_dtls_set_peer(ssl, &servAddr, sizeof(servAddr)) + != WOLFSSL_SUCCESS) { + Serial.println(F("wolfSSL_dtls_set_peer failed\n")); + goto cleanup; + } + + if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { + perror("socket()"); + goto cleanup; + } + + /* Set the file descriptor for ssl */ + if (wolfSSL_set_fd(ssl, sockfd) != WOLFSSL_SUCCESS) { + Serial.println(F("cannot set socket file descriptor\n")); + goto cleanup; + } + + Serial.print(F("Connecting to wolfSSL DTLS Secure Server...")); + do { + reconnect--; + err = 0; /* reset error */ + Serial.println(F("wolfSSL_connect ...")); + ret = wolfSSL_connect(ssl); + if ((ret != WOLFSSL_SUCCESS) && (ret != WC_PENDING_E)) { + Serial.println(F("Failed connection, checking error.")); + err = error_check_ssl(ssl, ret, true, + F("Create WOLFSSL object from ctx")); + Serial.print("err ="); + Serial.println(err); + } + else { + Serial.print(PROGRESS_DOT); + } + } while ((err == WC_PENDING_E) && (reconnect > 0)); + + Serial.println(); + Serial.println(F("Connected!")); + Serial.print(F("SSL version is ")); + Serial.println(wolfSSL_get_version(ssl)); + + cipherName = wolfSSL_get_cipher(ssl); + Serial.print(F("SSL cipher suite is ")); + Serial.println(cipherName); + +/*****************************************************************************/ +/* Code for sending datagram to server */ +/*****************************************************************************/ + Serial.println(F("Begin DTLS Loop...")); + msg_ct = 0; + while (msg_ct < DTLS_MESSAGE_CT || (DTLS_MESSAGE_CT == -1)) { + msg_ct++; + + /* Send sendLine to the server */ + Serial.print(F("Sending Message #")); + Serial.print(msg_ct); + Serial.print(F(": \"")); + Serial.print(F(sendLine)); + Serial.println(F("\" ... ")); + if (wolfSSL_write(ssl, sendLine, strlen(sendLine)) != strlen(sendLine)) { + err = error_check_ssl(ssl, ret, true, + F("Create WOLFSSL object from ctx")); + Serial.print("err ="); + Serial.println(err); + goto cleanup; + } + + /* n is the # of bytes received */ + Serial.println(F("Reading Message...")); + n = wolfSSL_read(ssl, recvLine, sizeof(recvLine)-1); + + if (n > 0) { + /* Add a terminating character to the generic server message */ + recvLine[n] = '\0'; + Serial.println(F("Got Message...")); + printf("%s\n", recvLine); + } + else { + err = error_check_ssl(ssl, ret, true, + F("Create WOLFSSL object from ctx")); + Serial.print("err ="); + Serial.println(err); + goto cleanup; + } + + } /* (msg_ct > DTLS_MESSAGE_CT || (DTLS_MESSAGE_CT == -1)) */ + + exitVal = 0; +cleanup: + if (ssl != NULL) { + /* Attempt a full shutdown */ + ret = wolfSSL_shutdown(ssl); + if (ret == WOLFSSL_SHUTDOWN_NOT_DONE) { + Serial.println("Not done... Try again wolfSSL_shutdown"); + ret = wolfSSL_shutdown(ssl); + } + + if (ret != WOLFSSL_SUCCESS) { + err = error_check_ssl(ssl, ret, true, + F("Create WOLFSSL object from ctx")); + Serial.print("err ="); + Serial.println(err); + Serial.println(F("wolfSSL_shutdown failed\n")); + } + wolfSSL_free(ssl); + } + if (sockfd != INVALID_SOCKET) { + close(sockfd); + } + if (ctx != NULL) { + wolfSSL_CTX_free(ctx); + } + wolfSSL_Cleanup(); + + Serial.print(F("Reset to start over.")); + Serial.print(F("Done!")); + + while (1) { + delay(1000); + } +} /* Arduino loop */ + diff --git a/examples/wolfssl_server/wolfssl_server.ino b/examples/wolfssl_server/wolfssl_server.ino index 1b9d4ed..7f75bcc 100644 --- a/examples/wolfssl_server/wolfssl_server.ino +++ b/examples/wolfssl_server/wolfssl_server.ino @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -39,6 +39,18 @@ Tested with: /* If you have a private include, define it here, otherwise edit WiFi params */ /* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ +#if defined(ARDUINO) && defined(ESP8266) + #warning "This example is not yet supported on Arduino ESP8266" +#endif + +#if defined(DEBUG_WOLFSSL) + /* Optionally enabled verbose wolfSSL debugging */ + #define DEBUG_WOLFSSL_MESSAGES_ON +#else + /* DEBUG_WOLFSSL needs to be enabled */ + #undef DEBUG_WOLFSSL_MESSAGES_ON +#endif + /* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ #define REPEAT_CONNECTION 1 @@ -68,12 +80,12 @@ Tested with: /* the /workspace directory may contain a private config * excluded from GitHub with items such as WiFi passwords */ #include MY_PRIVATE_CONFIG - static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; - static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; #else /* when using WiFi capable boards: */ - static const char ssid[] PROGMEM = "your_SSID"; - static const char password[] PROGMEM = "your_PASSWORD"; + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; #endif #define BROADCAST_ADDRESS "255.255.255.255" @@ -132,6 +144,10 @@ Tested with: #elif defined(ESP8266) #define USING_WIFI #include + /* Ensure the F() flash macro is defined */ + #ifndef F + #define F + #endif WiFiClient client; WiFiServer server(WOLFSSL_PORT); #elif defined(ARDUINO_SAM_DUE) @@ -140,7 +156,12 @@ Tested with: /* Needs "Ethernet by Various" library to be installed. Tested with V2.0.2 */ #include EthernetClient client; - EthernetClient server(WOLFSSL_PORT); + EthernetServer server(WOLFSSL_PORT); +#elif defined(ARDUINO_AVR_ETHERNET) || defined(ARDUINO_AVR_LEONARDO_ETH) + /* Boards such as arduino:avr:ethernet and arduino:avr:leonardoeth */ + #include + EthernetClient client; + EthernetServer server(WOLFSSL_PORT); #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define USING_WIFI #include @@ -153,6 +174,36 @@ Tested with: #include WiFiClient client; WiFiServer server(WOLFSSL_PORT); +#elif defined(ARDUINO_SAMD_TIAN) + #include + #include + HttpClient client; + /* Arduino Tian does not support network shields like the standard Ethernet or Wi-Fi shields. */ + #error "HttpClient cannot be used for this example" +#elif defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include + + /* ----No - network placeholders(compile - only) ---- */ + #include + struct X8NoNetClient { + int write(const uint8_t*, size_t) { return -1; } + int available() { return 0; } + int read() { return -1; } + void stop() {} + bool connected() { return false; } + IPAddress remoteIP() { return IPAddress(0, 0, 0, 0); } + }; + struct X8NoNetServer { + explicit X8NoNetServer(uint16_t) {} + void begin() {} + X8NoNetClient available() { return X8NoNetClient(); } + }; + + X8NoNetClient client; + X8NoNetServer server(WOLFSSL_PORT); #elif defined(USING_WIFI) #define USING_WIFI #include @@ -206,7 +257,10 @@ static char errBuf[80]; static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); static int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx); static int reconnect = RECONNECT_ATTEMPTS; +#if 0 +/* optional showPeerEx, currently disabled */ static int lng_index PROGMEM = 0; /* 0 = English */ +#endif #if defined(__arm__) #include @@ -463,7 +517,8 @@ int setup_network(void) { /*****************************************************************************/ /* Arduino setup_wolfssl() */ /*****************************************************************************/ -int setup_wolfssl(void) { +int setup_wolfssl(void) +{ int ret = 0; WOLFSSL_METHOD* method; @@ -483,8 +538,14 @@ int setup_wolfssl(void) { #endif #if defined(DEBUG_WOLFSSL) - wolfSSL_Debugging_ON(); - Serial.println(F("wolfSSL Debugging is On!")); + Serial.println(F("wolfSSL Debugging is available! (DEBUG_WOLFSSL)")); + #if defined(DEBUG_WOLFSSL_MESSAGES_ON) + Serial.println(F("Enabling verbose messages wolfSSL_Debugging_ON")); + wolfSSL_Debugging_ON(); + #else + Serial.println(F("Enable verbose messages with wolfSSL_Debugging_ON")); + Serial.println(F("or define DEBUG_WOLFSSL_MESSAGES_ON")); + #endif #else Serial.println(F("wolfSSL Debugging is Off! (enable with DEBUG_WOLFSSL)")); #endif @@ -510,6 +571,7 @@ int setup_wolfssl(void) { * It is best on embedded devices to choose a TLS session cache size. */ #endif + /* Initialize wolfSSL before assigning ctx */ ret = wolfSSL_Init(); if (ret == WOLFSSL_SUCCESS) { Serial.println("Successfully called wolfSSL_Init"); @@ -544,7 +606,8 @@ int setup_wolfssl(void) { /*****************************************************************************/ /* Arduino setup_certificates() */ /*****************************************************************************/ -int setup_certificates(void) { +int setup_certificates(void) +{ int ret = 0; Serial.println(F("Initializing certificates...")); @@ -594,7 +657,8 @@ int setup_certificates(void) { /* Arduino setup() */ /*****************************************************************************/ /*****************************************************************************/ -void setup(void) { +void setup(void) +{ int i = 0; Serial.begin(SERIAL_BAUD); while (!Serial && (i < 10)) { @@ -725,7 +789,7 @@ int error_check_ssl(WOLFSSL* ssl, int this_ret, bool halt_on_error, } return err; -} +} /* error_check_ssl */ /*****************************************************************************/ /*****************************************************************************/ diff --git a/examples/wolfssl_server_dtls/README.md b/examples/wolfssl_server_dtls/README.md new file mode 100644 index 0000000..43deb7e --- /dev/null +++ b/examples/wolfssl_server_dtls/README.md @@ -0,0 +1,140 @@ +# Arduino Basic TLS Server + +Open the [wolfssl_server_dtls.ino](./wolfssl_server_dtls.ino) file in the Arduino IDE. + +If using WiFi, be sure to set `ssid` and `password` values. + +May need "Ethernet by Various" library to be installed. Tested with v2.0.2 and v2.8.1. + +See the `#define WOLFSSL_TLS_SERVER_HOST` to set your own server address. + +Other IDE products are also supported, such as: + +- [PlatformIO in VS Code](https://docs.platformio.org/en/latest/frameworks/arduino.html) +- [VisualGDB](https://visualgdb.com/tutorials/arduino/) +- [VisualMicro](https://www.visualmicro.com/) + +For examples on other platforms, see the [IDE directory](https://github.com/wolfssl/wolfssl/tree/master/IDE). +Additional examples can be found on [wolfSSL/wolfssl-examples](https://github.com/wolfSSL/wolfssl-examples/). + +## Connect with an Arduino Sketch + +See the companion [Arduino Sketch Client](../wolfssl_client/wolfssl_client_dtls.ino). + +## Connect with Linux Client + +See also the [wolfSSL Example TLS Client](https://github.com/wolfSSL/wolfssl/tree/master/examples/client) +and [wolfSSL Example TLS Server](https://github.com/wolfSSL/wolfssl/tree/master/examples/server). + +Assuming a listening [Arduino Sketch Server](./wolfssl_server.ino) at `192.168.1.38` on port `11111`, +connect with the `client` executable: + +``` +./examples/client/client -h 192.168.1.38 -p 11111 -v 3 +``` + +## wolfSSL Error -308 wolfSSL_connect error state on socket + +When using a wired Ethernet connection, and this error is encountered, simply +press the reset button or power cycle the Arduino before making a connection. + +Here's one possible script to test the server from a command-line client: + +```bash +#!/usr/bin/env bash +echo "client log " > client_log.txt +counter=1 +THIS_ERR=0 +while [ $THIS_ERR -eq 0 ]; do + ./examples/client/client -h 192.168.1.38 -p 11111 -v 3 >> client_log.txt + + THIS_ERR=$? + if [ $? -ne 0 ]; then + echo "Failed!" + exit 1 + fi + echo "Iteration $counter" + echo "Iteration $counter" >> client_log.txt + ((counter++)) +done +``` + +Output expected from the `client` command: + +``` +$ ./examples/client/client -h 192.168.1.38 -p 11111 -v 3 +Alternate cert chain used + issuer : /C=US/ST=Montana/L=Bozeman/O=Sawtooth/OU=Consulting/CN=www.wolfssl.com/emailAddress=info@wolfssl.com + subject: /C=US/ST=Montana/L=Bozeman/O=wolfSSL/OU=Support/CN=www.wolfssl.com/emailAddress=info@wolfssl.com + altname = example.com + altname = 127.0.0.1 + serial number:01 +SSL version is TLSv1.2 +SSL cipher suite is ECDHE-RSA-AES128-GCM-SHA256 +SSL curve name is SECP256R1 +--- +Server certificate +-----BEGIN CERTIFICATE----- +MIIE6DCCA9CgAwIBAgIBATANBgkqhkiG9w0BAQsFADCBlDELMAkGA1UEBhMCVVMx +EDAOBgNVBAgMB01vbnRhbmExEDAOBgNVBAcMB0JvemVtYW4xETAPBgNVBAoMCFNh +d3Rvb3RoMRMwEQYDVQQLDApDb25zdWx0aW5nMRgwFgYDVQQDDA93d3cud29sZnNz +bC5jb20xHzAdBgkqhkiG9w0BCQEWEGluZm9Ad29sZnNzbC5jb20wHhcNMjMxMjEz +MjIxOTI4WhcNMjYwOTA4MjIxOTI4WjCBkDELMAkGA1UEBhMCVVMxEDAOBgNVBAgM +B01vbnRhbmExEDAOBgNVBAcMB0JvemVtYW4xEDAOBgNVBAoMB3dvbGZTU0wxEDAO +BgNVBAsMB1N1cHBvcnQxGDAWBgNVBAMMD3d3dy53b2xmc3NsLmNvbTEfMB0GCSqG +SIb3DQEJARYQaW5mb0B3b2xmc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAMCVCOFXQfJxbbfSRUEnAWXGRa7yvCQwuJXOL07W9hyIvHyf+6hn +f/5cnFF194rKB+c1L4/hvXvAL3yrZKgX/Mpde7rgIeVyLm8uhtiVc9qsG1O5Xz/X +GQ0lT+FjY1GLC2Q/rUO4pRxcNLOuAKBjxfZ/C1loeHOmjBipAm2vwxkBLrgQ48bM +QLRpo0YzaYduxLsXpvPo3a1zvHsvIbX9ZlEMvVSz4W1fHLwjc9EJA4kU0hC5ZMMq +0KGWSrzh1Bpbx6DAwWN4D0Q3MDKWgDIjlaF3uhPSl3PiXSXJag3DOWCktLBpQkIJ +6dgIvDMgs1gip6rrxOHmYYPF0pbf2dBPrdcCAwEAAaOCAUUwggFBMB0GA1UdDgQW +BBSzETLJkpiE4sn40DtuA0LKHw6OPDCB1AYDVR0jBIHMMIHJgBQnjmcRdMMmHT/t +M2OzpNgdMOXo1aGBmqSBlzCBlDELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB01vbnRh +bmExEDAOBgNVBAcMB0JvemVtYW4xETAPBgNVBAoMCFNhd3Rvb3RoMRMwEQYDVQQL +DApDb25zdWx0aW5nMRgwFgYDVQQDDA93d3cud29sZnNzbC5jb20xHzAdBgkqhkiG +9w0BCQEWEGluZm9Ad29sZnNzbC5jb22CFDNEGqhsAez2YPJwUQpM0RT6vOlEMAwG +A1UdEwQFMAMBAf8wHAYDVR0RBBUwE4ILZXhhbXBsZS5jb22HBH8AAAEwHQYDVR0l +BBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQBK/7nl +hZvaU2Z/ByK/thnqQuukEQdi/zlfMzc6hyZxPROyyrhkOHuKmUgOpaRrsZlu4EZR +vRlSrbymfip6fCOnzNteQ31rBMi33ZWt8JGAWcUZkSYnkbhIHOtVtqp9pDjxA7xs +i6qU1jwFepbFBvEmFC51+93lNbMBLLOtYlohmgi+Vvz5okKHhuWpxZnPrhS+4LkI +JA0dXNYU4UyfQLOp6S1Si0y/rEQxZ8GNBoXsD+SZ10t7IQZm1OT1nf+O8IY5WB2k +W+Jj73zJGIeoAiUQPoco+fXvR56lgAgRkGj+0aOoUbk3/9XKfId/a7wsEsjFhYv8 +DMa5hrjJBMNRN9JP +-----END CERTIFICATE----- +Session timeout set to 500 seconds +Client Random : 56A0BB9647B064D3F20947032B74B31FDB4C93DBAC9460BA8AEA213A2B2DD4A8 +SSL-Session: + Protocol : TLSv1.2 + Cipher : TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + Session-ID: 3255404E997FA9C27ECB4F1A20A70E722E4AA504B63A945FC175434D1907EC31 + Session-ID-ctx: + Master-Key: 67F22168BBADD678643BBA76B398277270C29788AC18FD05B57F6B715F49A7BCEEF75BEAF7FE266B0CC058534AF76C1F + TLS session ticket: NONE + Start Time: 1705533296 + Timeout : 500 (sec) + Extended master secret: no +I hear you fa shizzle! +``` + +### Troubleshooting + +When encountering odd errors such as `undefined reference to ``_impure_ptr'`, such as this: + +```text +c:/users/gojimmypi/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: C:\Users\gojimmypi\AppData\Local\Temp\arduino\sketches\EAB8D79A02D1ECF107884802D893914E\libraries\wolfSSL\wolfcrypt\src\logging.c.o:(.literal.wolfssl_log+0x8): undefined reference to `_impure_ptr' +collect2.exe: error: ld returned 1 exit status + +exit status 1 + +Compilation error: exit status 1 +``` + +Try cleaning the Arduino cache directories. For Windows, that's typically in: + +```text +C:\Users\%USERNAME%\AppData\Local\Temp\arduino\sketches +``` + +Remove all other boards from other serial ports, leaving one the one being programmed. diff --git a/examples/wolfssl_server_dtls/wolfssl_server_dtls.ino b/examples/wolfssl_server_dtls/wolfssl_server_dtls.ino new file mode 100644 index 0000000..38e9148 --- /dev/null +++ b/examples/wolfssl_server_dtls/wolfssl_server_dtls.ino @@ -0,0 +1,984 @@ +/* server-dtls13.c + * + * Copyright (C) 2006-2025 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + *============================================================================= + * + * Bare-bones example of a DTLS 1.3 server for instructional/learning purposes. + * This example can only accept one connection at a time. + * + * Define USE_DTLS12 to use DTLS 1.2 instead of DTLS 1.3 +/* +Tested with: + +1) Intel Galileo acting as the Client, with a laptop acting as a server using + the server example provided in examples/server. + Legacy Arduino v1.86 was used to compile and program the Galileo + +2) Espressif ESP32 WiFi + +3) Arduino Due, Nano33 IoT, Nano RP-2040 +*/ + +/* + * Note to code editors: the Arduino client and server examples are edited in + * parallel for side-by-side comparison between examples. + */ + +/* If you have a private include, define it here, otherwise edit WiFi params */ +/* #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h" */ + +#if defined(ARDUINO) && defined(ESP8266) + #warning "This example is not yet supported on Arduino ESP8266" +#endif + +#if defined(DEBUG_WOLFSSL) + /* Optionally enabled verbose wolfSSL debugging */ + #define DEBUG_WOLFSSL_MESSAGES_ON +#else + /* DEBUG_WOLFSSL needs to be enabled */ + #undef DEBUG_WOLFSSL_MESSAGES_ON +#endif + +/* set REPEAT_CONNECTION to a non-zero value to continually run the example. */ +#define REPEAT_CONNECTION 0 + +/* Edit this with your other TLS host server address to connect to: */ +/* #define WOLFSSL_TLS_SERVER_HOST "192.168.1.39" */ + +/* wolfssl TLS examples communicate on port 11111 */ +#define WOLFSSL_PORT 11111 + +/* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */ +#define SERIAL_BAUD 115200 + +/* We'll wait up to 2000 milliseconds to properly shut down connection */ +#define SHUTDOWN_DELAY_MS 2000 + +/* Number of times to retry connection. */ +#define RECONNECT_ATTEMPTS 20 + +/* Assume bad socket until proven otherwise */ +#define INVALID_SOCKET -1 + +/* Maximum size in bytes of buffer to send and receive */ +#define MAXLINE 128 + +/* Optional stress test. Define to consume memory until exhausted: */ +/* #define MEMORY_STRESS_TEST */ + +/* Choose client or server example, not both. */ +/* #define WOLFSSL_CLIENT_EXAMPLE */ +#define WOLFSSL_SERVER_EXAMPLE + +#if defined(MY_PRIVATE_CONFIG) + /* the /workspace directory may contain a private config + * excluded from GitHub with items such as WiFi passwords */ + #include MY_PRIVATE_CONFIG + static const char ssid[] PROGMEM = MY_ARDUINO_WIFI_SSID; + static const char password[] PROGMEM = MY_ARDUINO_WIFI_PASSWORD; +#else + /* when using WiFi capable boards: */ + static const char ssid[] PROGMEM = "your_SSID"; + static const char password[] PROGMEM = "your_PASSWORD"; +#endif + +#define BROADCAST_ADDRESS "255.255.255.255" + +/* There's an optional 3rd party NTPClient library by Fabrice Weinberg. + * If it is installed, uncomment define USE_NTP_LIB here: */ +/* #define USE_NTP_LIB */ +#ifdef USE_NTP_LIB + #include +#endif + +/* wolfSSL user_settings.h must be included from settings.h + * Make all configurations changes in user_settings.h + * Do not edit wolfSSL `settings.h` or `config.h` files. + * Do not explicitly include user_settings.h in any source code. + * Each Arduino sketch that uses wolfSSL must have: #include "wolfssl.h" + * C/C++ source files can use: #include + * The wolfSSL "settings.h" must be included in each source file using wolfSSL. + * The wolfSSL "settings.h" must appear before any other wolfSSL include. + */ +#include +/* Important: make sure settings.h appears before any other wolfSSL headers */ +#include +/* Reminder: settings.h includes user_settings.h + * For ALL project wolfSSL settings, see: + * [your path]/Arduino\libraries\wolfSSL\src\user_settings.h */ +#include +#include +#include + +#ifndef WOLFSSL_DTLS + /* Support for DTLS by default was added after wolfSSL v5.8.2 release */ + #error "This example requires WOLFSSL_DTLS. See user_settings.h in the Arduino wolfssl library" +#endif + +/* Define DEBUG_WOLFSSL in user_settings.h for more verbose logging. */ +#if defined(DEBUG_WOLFSSL) + #define PROGRESS_DOT F("") +#else + #define PROGRESS_DOT F(".") +#endif + +/* Convert a macro to a string */ +#define xstr(x) str(x) +#define str(x) #x + +/* optional board-specific networking includes */ +#if defined(ESP32) + #define USING_WIFI + #include + #include + #ifdef USE_NTP_LIB + WiFiUDP ntpUDP; + #endif + /* Ensure the F() flash macro is defined */ + #ifndef F + #define F + #endif + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +#elif defined(ESP8266) + #define USING_WIFI + #include + /* Ensure the F() flash macro is defined */ + #ifndef F + #define F + #endif + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +#elif defined(ARDUINO_SAM_DUE) + #include + /* There's no WiFi/Ethernet on the Due. Requires Ethernet Shield. + /* Needs "Ethernet by Various" library to be installed. Tested with V2.0.2 */ + #include + EthernetClient client; + EthernetClient server(WOLFSSL_PORT); +#elif defined(ARDUINO_AVR_ETHERNET) || defined(ARDUINO_AVR_LEONARDO_ETH) + /* Boards such as arduino:avr:ethernet and arduino:avr:leonardoeth */ + #include + EthernetClient client; + + EthernetClient server(WOLFSSL_PORT); +#elif defined(ARDUINO_SAMD_NANO_33_IOT) + #define USING_WIFI + #include + #include /* Needs Arduino WiFiNINA library installed manually */ + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +#elif defined(ARDUINO_ARCH_RP2040) + #define USING_WIFI + #include + #include + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +#elif defined(ARDUINO_SAMD_TIAN) + #include + #include + HttpClient client; + /* Arduino Tian does not support network shields like the standard Ethernet or Wi-Fi shields. */ + #error "HttpClient cannot be used for this example" +#elif defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include + + /* ----No - network placeholders(compile - only) ---- */ + #include + struct X8NoNetClient { + int write(const uint8_t*, size_t) { return -1; } + int available() { return 0; } + int read() { return -1; } + void stop() {} + bool connected() { return false; } + IPAddress remoteIP() { return IPAddress(0, 0, 0, 0); } + }; + struct X8NoNetServer { + explicit X8NoNetServer(uint16_t) {} + void begin() {} + X8NoNetClient available() { return X8NoNetClient(); } + }; + + X8NoNetClient client; + X8NoNetServer server(WOLFSSL_PORT); +#elif defined(USING_WIFI) + #define USING_WIFI + #include + #include + #ifdef USE_NTP_LIB + WiFiUDP ntpUDP; + #endif + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +/* TODO +#elif defined(OTHER_BOARD) +*/ +#else + /* assume all other boards using WiFi library. Edit as needed: */ + #include + #define USING_WIFI + WiFiClient client; + WiFiServer server(WOLFSSL_PORT); +#endif + +/* Only for syntax highlighters to show interesting options enabled: */ +#if defined(HAVE_SNI) \ + || defined(HAVE_MAX_FRAGMENT) \ + || defined(HAVE_TRUSTED_CA) \ + || defined(HAVE_TRUNCATED_HMAC) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST) \ + || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) \ + || defined(HAVE_SUPPORTED_CURVES) \ + || defined(HAVE_ALPN) \ + || defined(HAVE_SESSION_TICKET) \ + || defined(HAVE_SECURE_RENEGOTIATION) \ + || defined(HAVE_SERVER_RENEGOTIATION_INFO) +#endif + +static const int port PROGMEM = WOLFSSL_PORT; /* port on server to connect to */ + +static WOLFSSL_CTX* ctx = NULL; +static WOLFSSL* ssl = NULL; +static char* wc_error_message = (char*)malloc(80 + 1); +static char errBuf[80]; + +#if defined(MEMORY_STRESS_TEST) + #define MEMORY_STRESS_ITERATIONS 100 + #define MEMORY_STRESS_BLOCK_SIZE 1024 + #define MEMORY_STRESS_INITIAL (4*1024) + static char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */ + static int mem_ctr = 0; +#endif + +static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx); +static int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx); +static int reconnect = RECONNECT_ATTEMPTS; +#if 0 +/* optional showPeerEx, currently disabled */ +static int lng_index PROGMEM = 0; /* 0 = English */ +#endif +static int listenfd = INVALID_SOCKET; /* Initialize our socket */ + +#if defined(__arm__) + #include + extern char _end; + extern "C" char *sbrk(int i); + static char *ramstart=(char *)0x20070000; + static char *ramend=(char *)0x20088000; +#endif + +/*****************************************************************************/ +/* fail_wait - in case of unrecoverable error */ +/*****************************************************************************/ +int fail_wait(void) { + show_memory(); + + Serial.println(F("Failed. Halt.")); + while (1) { + delay(1000); + } + return 0; +} + +/*****************************************************************************/ +/* show_memory() to optionally view during debugging. */ +/*****************************************************************************/ +int show_memory(void) +{ +#if defined(__arm__) + struct mallinfo mi = mallinfo(); + + char *heapend=sbrk(0); + register char * stack_ptr asm("sp"); + #if defined(DEBUG_WOLFSSL_VERBOSE) + Serial.print(" arena="); + Serial.println(mi.arena); + Serial.print(" ordblks="); + Serial.println(mi.ordblks); + Serial.print(" uordblks="); + Serial.println(mi.uordblks); + Serial.print(" fordblks="); + Serial.println(mi.fordblks); + Serial.print(" keepcost="); + Serial.println(mi.keepcost); + #endif + + #if defined(DEBUG_WOLFSSL) || defined(MEMORY_STRESS_TEST) + Serial.print("Estimated free memory: "); + Serial.print(stack_ptr - heapend + mi.fordblks); + Serial.println(F(" bytes")); + #endif + + #if (0) + /* Experimental: not supported on all devices: */ + Serial.print("RAM Start %lx\n", (unsigned long)ramstart); + Serial.print("Data/Bss end %lx\n", (unsigned long)&_end); + Serial.print("Heap End %lx\n", (unsigned long)heapend); + Serial.print("Stack Ptr %lx\n",(unsigned long)stack_ptr); + Serial.print("RAM End %lx\n", (unsigned long)ramend); + + Serial.print("Heap RAM Used: ",mi.uordblks); + Serial.print("Program RAM Used ",&_end - ramstart); + Serial.print("Stack RAM Used ",ramend - stack_ptr); + + Serial.print("Estimated Free RAM: %d\n\n",stack_ptr - heapend + mi.fordblks); + #endif +#else + Serial.println(F("show_memory() not implemented for this platform")); +#endif + return 0; +} + +/*****************************************************************************/ +/* Arduino setup_hardware() */ +/*****************************************************************************/ +int setup_hardware(void) { + int ret = 0; + +#if defined(ARDUINO_SAMD_NANO_33_IOT) + Serial.println(F("Detected known tested and working Arduino Nano 33 IoT")); +#elif defined(ARDUINO_ARCH_RP2040) + Serial.println(F("Detected known tested and working Arduino RP-2040")); +#elif defined(__arm__) && defined(ID_TRNG) && defined(TRNG) + /* need to manually turn on random number generator on Arduino Due, etc. */ + pmc_enable_periph_clk(ID_TRNG); + trng_enable(TRNG); + Serial.println(F("Enabled ARM TRNG")); +#endif + + show_memory(); + randomSeed(analogRead(0)); + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_datetime() */ +/* The device needs to have a valid date within the valid range of certs. */ +/*****************************************************************************/ +int setup_datetime(void) { + int ret = 0; + int ntp_tries = 20; + + /* we need a date in the range of cert expiration */ +#ifdef USE_NTP_LIB + #if defined(ESP32) + NTPClient timeClient(ntpUDP, "pool.ntp.org"); + + timeClient.begin(); + timeClient.update(); + delay(1000); + while (!timeClient.isTimeSet() && (ntp_tries > 0)) { + timeClient.forceUpdate(); + Serial.println(F("Waiting for NTP update")); + delay(2000); + ntp_tries--; + } + if (ntp_tries <= 0) { + Serial.println(F("Warning: gave up waiting on NTP")); + } + Serial.println(timeClient.getFormattedTime()); + Serial.println(timeClient.getEpochTime()); + #endif +#endif + +#if defined(ESP32) + /* see esp32-hal-time.c */ + ntp_tries = 5; + /* Replace "pool.ntp.org" with your preferred NTP server */ + configTime(0, 0, "pool.ntp.org"); + + /* Wait for time to be set */ + while ((time(nullptr) <= 100000) && ntp_tries > 0) { + Serial.println(F("Waiting for time to be set...")); + delay(2000); + ntp_tries--; + } +#endif + + return ret; +} /* setup_datetime */ + +/*****************************************************************************/ +/* Arduino setup_network() */ +/*****************************************************************************/ +int setup_network(void) { + int ret = 0; + +#if defined(USING_WIFI) + int status = WL_IDLE_STATUS; + + /* The ESP8266 & ESP32 support both AP and STA. We'll use STA: */ + #if defined(ESP8266) || defined(ESP32) + WiFi.mode(WIFI_STA); + #else + String fv; + if (WiFi.status() == WL_NO_MODULE) { + Serial.println("Communication with WiFi module failed!"); + /* don't continue if no network */ + while (true) ; + } + + fv = WiFi.firmwareVersion(); + if (fv < WIFI_FIRMWARE_LATEST_VERSION) { + Serial.println("Please upgrade the firmware"); + } + #endif + + Serial.print(F("Connecting to WiFi ")); + Serial.print(ssid); + status = WiFi.begin(ssid, password); + while (status != WL_CONNECTED) { + delay(1000); + Serial.print(F(".")); + Serial.print(status); + status = WiFi.status(); + } + + Serial.println(F(" Connected!")); +#else + /* Newer Ethernet shields have a + * MAC address printed on a sticker on the shield */ + byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + IPAddress ip(192, 168, 1, 42); + IPAddress myDns(192, 168, 1, 1); + Ethernet.init(10); /* Most Arduino shields */ + /* Ethernet.init(5); * MKR ETH Shield */ + /* Ethernet.init(0); * Teensy 2.0 */ + /* Ethernet.init(20); * Teensy++ 2.0 */ + /* Ethernet.init(15); * ESP8266 with Adafruit FeatherWing Ethernet */ + /* Ethernet.init(33); * ESP32 with Adafruit FeatherWing Ethernet */ + Serial.println(F("Initialize Ethernet with DHCP:")); + if (Ethernet.begin(mac) == 0) { + Serial.println(F("Failed to configure Ethernet using DHCP")); + /* Check for Ethernet hardware present */ + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println(F("Ethernet shield was not found.")); + while (true) { + delay(1); /* do nothing */ + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println(F("Ethernet cable is not connected.")); + } + /* try to configure using IP address instead of DHCP : */ + Ethernet.begin(mac, ip, myDns); + } + else { + Serial.print(F(" DHCP assigned IP ")); + Serial.println(Ethernet.localIP()); + } + /* We'll assume the Ethernet connection is ready to go. */ +#endif + + Serial.println(F("********************************************************")); + Serial.print(F(" wolfSSL Example Server IP = ")); +#if defined(USING_WIFI) + Serial.println(WiFi.localIP()); +#else + Serial.println(Ethernet.localIP()); +#endif + /* In server mode, there's no host definition. */ + /* See companion example: wolfssl_client.ino */ + Serial.println(F("********************************************************")); + Serial.println(F("Setup network complete.")); + + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_wolfssl() */ +/*****************************************************************************/ +int setup_wolfssl(void) +{ + int ret = 0; + WOLFSSL_METHOD* method; + + /* Show a revision of wolfssl user_settings.h file in use when available: */ +#if defined(WOLFSSL_USER_SETTINGS_ID) + Serial.print(F("WOLFSSL_USER_SETTINGS_ID: ")); + Serial.println(F(WOLFSSL_USER_SETTINGS_ID)); +#else + Serial.println(F("No WOLFSSL_USER_SETTINGS_ID found.")); +#endif + +#if defined(NO_WOLFSSL_SERVER) + Serial.println(F("wolfSSL server code disabled to save space.")); +#endif +#if defined(NO_WOLFSSL_CLIENT) + Serial.println(F("wolfSSL client code disabled to save space.")); +#endif + +#if defined(DEBUG_WOLFSSL) + Serial.println(F("wolfSSL Debugging is available! (DEBUG_WOLFSSL)")); + #if defined(DEBUG_WOLFSSL_MESSAGES_ON) + Serial.println(F("Enabling verbose messages wolfSSL_Debugging_ON")); + wolfSSL_Debugging_ON(); + #else + Serial.println(F("Enable verbose messages with wolfSSL_Debugging_ON")); + Serial.println(F("or define DEBUG_WOLFSSL_MESSAGES_ON")); + #endif +#else + Serial.println(F("wolfSSL Debugging is Off! (enable with DEBUG_WOLFSSL)")); +#endif + + /* See ssl.c for TLS cache settings. Larger cache = use more RAM. */ +#if defined(NO_SESSION_CACHE) + Serial.println(F("wolfSSL TLS NO_SESSION_CACHE")); +#elif defined(MICRO_SESSION_CACHEx) + Serial.println(F("wolfSSL TLS MICRO_SESSION_CACHE")); +#elif defined(SMALL_SESSION_CACHE) + Serial.println(F("wolfSSL TLS SMALL_SESSION_CACHE")); +#elif defined(MEDIUM_SESSION_CACHE) + Serial.println(F("wolfSSL TLS MEDIUM_SESSION_CACHE")); +#elif defined(BIG_SESSION_CACHE) + Serial.println(F("wolfSSL TLS BIG_SESSION_CACHE")); +#elif defined(HUGE_SESSION_CACHE) + Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE")); +#elif defined(HUGE_SESSION_CACHE) + Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE")); +#else + Serial.println(F("WARNING: Unknown or no TLS session cache setting.")); + /* See wolfssl/src/ssl.c for amount of memory used. + * It is best on embedded devices to choose a TLS session cache size. */ +#endif + + /* Initialize wolfSSL before assigning ctx */ + ret = wolfSSL_Init(); + if (ret == WOLFSSL_SUCCESS) { + Serial.println("Successfully called wolfSSL_Init"); + } + else { + Serial.println("ERROR: wolfSSL_Init failed"); + } + + /* See companion server example with wolfSSLv23_server_method here. + * method = wolfSSLv23_client_method()); SSL 3.0 - TLS 1.3. + * method = wolfTLSv1_2_client_method(); only TLS 1.2 + * method = wolfTLSv1_3_client_method(); only TLS 1.3 + * + * see Arduino\libraries\wolfssl\src\user_settings.h */ + + Serial.println("Here we go!"); + +#ifdef WOLFSSL_DTLS13 + Serial.println(F("Setting wolfDTLSv1_3_client_method")); + method = wolfDTLSv1_3_server_method(); +#else + Serial.println(F("Setting wolfDTLSv1_2_client_method")); + method = wolfDTLSv1_2_servert_method(); +#endif + ctx = wolfSSL_CTX_new(method); + if (ctx == NULL) { + fail_wait(); + } + + if (method == NULL) { + Serial.println(F("Unable to get wolfssl client method")); + fail_wait(); + } + + ctx = wolfSSL_CTX_new(method); + if (ctx == NULL) { + Serial.println(F("unable to get ctx")); + fail_wait(); + } + + return ret; +} + +/*****************************************************************************/ +/* Arduino setup_certificates() */ +/*****************************************************************************/ +int setup_certificates(void) +{ + int ret = 0; + +/* See user_settings.h that should have included wolfssl/certs_test.h */ + +Serial.println(F("Initializing certificates...")); +show_memory(); + + /* Load CA certificates */ + if (ret == WOLFSSL_SUCCESS) { + /* caCertLoc[] = "../certs/ca-cert.pem"; */ + ret = wolfSSL_CTX_load_verify_buffer(ctx, + CTX_CA_CERT, + CTX_CA_CERT_SIZE, + CTX_SERVER_CERT_TYPE); + } + + /* If successful, Load server certificates */ + Serial.println("Initializing certificates..."); + ret = wolfSSL_CTX_use_certificate_buffer(ctx, + CTX_SERVER_CERT, + CTX_SERVER_CERT_SIZE, + CTX_CA_CERT_TYPE); + + if (ret == WOLFSSL_SUCCESS) { + Serial.print("Success: use certificate: "); + Serial.println(xstr(CTX_SERVER_CERT)); + } + else { + Serial.print("Error: wolfSSL_CTX_use_certificate_buffer failed: "); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + /* Setup private server key */ + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, + CTX_SERVER_KEY, + CTX_SERVER_KEY_SIZE, + CTX_SERVER_KEY_TYPE); + if (ret == WOLFSSL_SUCCESS) { + Serial.print("Success: use private key buffer: "); + Serial.println(xstr(CTX_SERVER_KEY)); + } + else { + Serial.print("Error: wolfSSL_CTX_use_PrivateKey_buffer failed: "); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + /* Setup private server key */ + ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, + CTX_SERVER_KEY, + CTX_SERVER_KEY_SIZE, + CTX_SERVER_KEY_TYPE); + + if (ret == WOLFSSL_SUCCESS) { + Serial.print("Success: use private key buffer: "); + Serial.println(xstr(CTX_SERVER_KEY)); + } + else { + Serial.print("Error: wolfSSL_CTX_use_PrivateKey_buffer failed: "); + wc_ErrorString(ret, wc_error_message); + Serial.println(wc_error_message); + fail_wait(); + } + + return ret; +} /* Arduino setup */ + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino setup() */ +/*****************************************************************************/ +/*****************************************************************************/ +void setup(void) +{ + int i = 0; + Serial.begin(SERIAL_BAUD); + while (!Serial && (i < 10)) { + /* wait for serial port to connect. Needed for native USB port only */ + delay(1000); + i++; + } + + Serial.println(F("")); + Serial.println(F("")); + Serial.println(F("wolfSSL DTLS Server Example Startup.")); + + /* Optionally pre-allocate a large block of memory for testing */ +#if defined(MEMORY_STRESS_TEST) + Serial.println(F("WARNING: Memory Stress Test Active!")); + Serial.print(F("Allocating extra memory: ")); + Serial.print(MEMORY_STRESS_INITIAL); + Serial.println(F(" bytes...")); + memory_stress[mem_ctr] = (char*)malloc(MEMORY_STRESS_INITIAL); + show_memory(); +#endif + + setup_hardware(); + + setup_network(); + + setup_datetime(); + + setup_wolfssl(); + + setup_certificates(); + +#if defined THIS_USER_SETTINGS_VERSION + Serial.print(F("This user_settings.h version:")) + Serial.println(THIS_USER_SETTINGS_VERSION) +#endif + + /* Start the server + * See https://www.arduino.cc/reference/en/libraries/ethernet/server.begin/ + */ + + Serial.println(F("Completed Arduino setup()")); + + server.begin(); + Serial.println("Begin Server... (waiting for remote client to connect)"); + + /* See companion wolfssl_client.ino code */ + return; +} /* Arduino setup */ + +/*****************************************************************************/ +/* wolfSSL error_check() */ +/*****************************************************************************/ +int error_check(int this_ret, bool halt_on_error, + const __FlashStringHelper* message) { + int ret = 0; + if (this_ret == WOLFSSL_SUCCESS) { + Serial.print(F("Success: ")); + Serial.println(message); + } + else { + Serial.print(F("ERROR: return = ")); + Serial.print(this_ret); + Serial.print(F(": ")); + Serial.println(message); + Serial.println(wc_GetErrorString(this_ret)); + if (halt_on_error) { + fail_wait(); + } + } + show_memory(); + + return ret; +} /* error_check */ + +/*****************************************************************************/ +/* wolfSSL error_check_ssl */ +/* Parameters: */ +/* ssl is the current WOLFSSL object pointer */ +/* halt_on_error set to true to suspend operations for critical error */ +/* message is expected to be a memory-efficient F("") macro string */ +/*****************************************************************************/ +int error_check_ssl(WOLFSSL* ssl, int this_ret, bool halt_on_error, + const __FlashStringHelper* message) { + int err = 0; + + if (ssl == NULL) { + Serial.println(F("ssl is Null; Unable to allocate SSL object?")); +#ifndef DEBUG_WOLFSSL + Serial.println(F("Define DEBUG_WOLFSSL in user_settings.h for more.")); +#else + Serial.println(F("See wolfssl/wolfcrypt/error-crypt.h for codes.")); +#endif + Serial.print(F("ERROR: ")); + Serial.println(message); + show_memory(); + if (halt_on_error) { + fail_wait(); + } + } + else { + err = wolfSSL_get_error(ssl, this_ret); + if (err == WOLFSSL_SUCCESS) { + Serial.print(F("Success m: ")); + Serial.println(message); + } + else { + if (err < 0) { + wolfSSL_ERR_error_string(err, errBuf); + Serial.print(F("WOLFSSL Error: ")); + Serial.print(err); + Serial.print(F("; ")); + Serial.println(errBuf); + } + else { + Serial.println(F("Success: ssl object.")); + } + } + } + + return err; +} /* error_check_ssl */ + +static void sig_handler(const int sig); +static void free_resources(void); + +/*****************************************************************************/ +/*****************************************************************************/ +/* Arduino loop() */ +/*****************************************************************************/ +/*****************************************************************************/ +void loop() +{ + int exitVal = 1; + struct sockaddr_in servAddr; /* our server's address */ + struct sockaddr_in cliaddr; /* the client's address */ + int ret; + int err; + int recvLen = 0; /* length of message */ + socklen_t cliLen; + char buff[MAXLINE]; /* the incoming message */ + char ack[] = "I hear you fashizzle!\n"; + + /* Initialize wolfSSL before assigning ctx */ + if (wolfSSL_Init() != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_Init error.\n"); + fail_wait(); + } + + /* No-op when debugging is not compiled in */ + wolfSSL_Debugging_ON(); + + + /* Create a UDP/IP socket */ + if ((listenfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { + perror("socket()"); + goto cleanup; + } + printf("Socket allocated\n"); + memset((char *)&servAddr, 0, sizeof(servAddr)); + /* host-to-network-long conversion (htonl) */ + /* host-to-network-short conversion (htons) */ + servAddr.sin_family = AF_INET; + servAddr.sin_addr.s_addr = htonl(INADDR_ANY); + servAddr.sin_port = htons(WOLFSSL_PORT); + + /* Bind Socket */ + if (bind(listenfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0) { + perror("bind()"); + goto cleanup; + } + + // signal(SIGINT, sig_handler); + + while (1) { + printf("Awaiting client connection on port %d\n", WOLFSSL_PORT); + + cliLen = sizeof(cliaddr); + ret = (int)recvfrom(listenfd, (char *)&buff, sizeof(buff), MSG_PEEK, + (struct sockaddr*)&cliaddr, &cliLen); + + if (ret < 0) { + perror("recvfrom()"); + goto cleanup; + } + else if (ret == 0) { + fprintf(stderr, "recvfrom zero return\n"); + goto cleanup; + } + + /* Create the WOLFSSL Object */ + if ((ssl = wolfSSL_new(ctx)) == NULL) { + fprintf(stderr, "wolfSSL_new error.\n"); + goto cleanup; + } + + if (wolfSSL_dtls_set_peer(ssl, &cliaddr, cliLen) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_set_peer error.\n"); + goto cleanup; + } + + if (wolfSSL_set_fd(ssl, listenfd) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_set_fd error.\n"); + break; + } + + if (wolfSSL_accept(ssl) != WOLFSSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "error = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "SSL_accept failed.\n"); + goto cleanup; + } + + while (1) { + if ((recvLen = wolfSSL_read(ssl, buff, sizeof(buff)-1)) > 0) { + printf("heard %d bytes\n", recvLen); + + buff[recvLen] = '\0'; + printf("I heard this: \"%s\"\n", buff); + } + else if (recvLen <= 0) { + err = wolfSSL_get_error(ssl, 0); + if (err == WOLFSSL_ERROR_ZERO_RETURN) /* Received shutdown */ + break; + fprintf(stderr, "error = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "SSL_read failed.\n"); + goto cleanup; + } + printf("Sending reply.\n"); + if (wolfSSL_write(ssl, ack, sizeof(ack)) < 0) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "error = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_write failed.\n"); + goto cleanup; + } + } + + printf("reply sent \"%s\"\n", ack); + + /* Attempt a full shutdown */ + ret = wolfSSL_shutdown(ssl); + if (ret == WOLFSSL_SHUTDOWN_NOT_DONE) + ret = wolfSSL_shutdown(ssl); + if (ret != WOLFSSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_shutdown failed\n"); + } + wolfSSL_free(ssl); + ssl = NULL; + + printf("Awaiting new connection\n"); + } + + exitVal = 0; +cleanup: + free_resources(); + wolfSSL_Cleanup(); + + Serial.println(F("Done!")); + while (1) { + delay(1000); + } +} + + +static void sig_handler(const int sig) +{ + (void)sig; + free_resources(); + wolfSSL_Cleanup(); +} + +static void free_resources(void) +{ + if (ssl != NULL) { + wolfSSL_shutdown(ssl); + wolfSSL_free(ssl); + ssl = NULL; + } + if (ctx != NULL) { + wolfSSL_CTX_free(ctx); + ctx = NULL; + } + if (listenfd != INVALID_SOCKET) { + close(listenfd); + listenfd = INVALID_SOCKET; + } +} + diff --git a/examples/wolfssl_version/wolfssl_version.ino b/examples/wolfssl_version/wolfssl_version.ino index 12be948..ac34124 100644 --- a/examples/wolfssl_version/wolfssl_version.ino +++ b/examples/wolfssl_version/wolfssl_version.ino @@ -6,7 +6,7 @@ * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, @@ -21,6 +21,13 @@ #include +#if defined(ARDUINO_PORTENTA_X8) + /* The Portenta is a Linux device. See wolfSSL examples: + * https://github.com/wolfSSL/wolfssl/tree/master/examples + * By default Serial is disabled and mapped to ErrorSerial */ + #include +#endif + /* wolfSSL user_settings.h must be included from settings.h * Make all configurations changes in user_settings.h * Do not edit wolfSSL `settings.h` or `config.h` files. diff --git a/library.properties b/library.properties index bb59f54..05d11ef 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=wolfssl -version=5.8.2 +version=5.8.4 author=wolfSSL Inc. maintainer=wolfSSL inc sentence=A lightweight SSL/TLS library written in ANSI C and targeted for embedded, RTOS, and resource-constrained environments. diff --git a/src/src/bio.c b/src/src/bio.c index ce74983..8321dab 100644 --- a/src/src/bio.c +++ b/src/src/bio.c @@ -1404,7 +1404,7 @@ long wolfSSL_BIO_get_mem_ptr(WOLFSSL_BIO *bio, WOLFSSL_BUF_MEM **ptr) } #endif -WOLFSSL_API long wolfSSL_BIO_int_ctrl(WOLFSSL_BIO *bp, int cmd, long larg, int iarg) +long wolfSSL_BIO_int_ctrl(WOLFSSL_BIO *bp, int cmd, long larg, int iarg) { (void) bp; (void) cmd; @@ -2440,9 +2440,21 @@ int wolfSSL_BIO_flush(WOLFSSL_BIO* bio) { WOLFSSL_BIO *bio; WOLFSSL_ENTER("wolfSSL_BIO_new_accept"); + + if (port == NULL) { + return NULL; + } + bio = wolfSSL_BIO_new(wolfSSL_BIO_s_socket()); if (bio) { - bio->port = (word16)XATOI(port); + const char* portStr = port; +#ifdef WOLFSSL_IPV6 + const char* ipv6End = XSTRSTR(port, "]"); + if (ipv6End) { + portStr = XSTRSTR(ipv6End, ":"); + } +#endif + bio->port = (word16)XATOI(portStr); bio->type = WOLFSSL_BIO_SOCKET; } return bio; @@ -3327,7 +3339,7 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) /* In Visual Studio versions prior to Visual Studio 2013, the va_* symbols aren't defined. If using Visual Studio 2013 or later, define HAVE_VA_COPY. */ - #if !defined(_WIN32) || defined(HAVE_VA_COPY) + #if defined(XVSNPRINTF) && (!defined(_WIN32) || defined(HAVE_VA_COPY)) case WOLFSSL_BIO_SSL: { int count; @@ -3358,7 +3370,7 @@ int wolfSSL_BIO_vprintf(WOLFSSL_BIO* bio, const char* format, va_list args) va_end(copy); } break; - #endif /* !_WIN32 || HAVE_VA_COPY */ + #endif /* XVSNPRINTF && (!_WIN32 || HAVE_VA_COPY) */ default: WOLFSSL_MSG("Unsupported WOLFSSL_BIO type for wolfSSL_BIO_printf"); diff --git a/src/src/crl.c b/src/src/crl.c index 4e4700f..9056bd1 100644 --- a/src/src/crl.c +++ b/src/src/crl.c @@ -39,8 +39,9 @@ CRL Options: #include #include +#include -#ifndef WOLFSSL_LINUXKM +#ifndef NO_STRING_H #include #endif @@ -209,20 +210,23 @@ static CRL_Entry* CRL_Entry_new(void* heap) /* Free all CRL Entry resources */ static void CRL_Entry_free(CRL_Entry* crle, void* heap) { -#ifdef CRL_STATIC_REVOKED_LIST - if (crle != NULL) { - XMEMSET(crle->certs, 0, CRL_MAX_REVOKED_CERTS*sizeof(RevokedCert)); + WOLFSSL_ENTER("CRL_Entry_free"); + if (crle == NULL) { + WOLFSSL_MSG("CRL Entry is null"); + return; } +#ifdef CRL_STATIC_REVOKED_LIST + XMEMSET(crle->certs, 0, CRL_MAX_REVOKED_CERTS*sizeof(RevokedCert)); #else - RevokedCert* tmp = crle->certs; - RevokedCert* next; + { + RevokedCert* tmp; + RevokedCert* next; - WOLFSSL_ENTER("FreeCRL_Entry"); + for (tmp = crle->certs; tmp != NULL; tmp = next) { + next = tmp->next; + XFREE(tmp, heap, DYNAMIC_TYPE_REVOKED); + } - while (tmp != NULL) { - next = tmp->next; - XFREE(tmp, heap, DYNAMIC_TYPE_REVOKED); - tmp = next; } #endif XFREE(crle->signature, heap, DYNAMIC_TYPE_CRL_ENTRY); @@ -753,11 +757,7 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, int ret = WOLFSSL_SUCCESS; const byte* myBuffer = buff; /* if DER ok, otherwise switch */ DerBuffer* der = NULL; -#ifdef WOLFSSL_SMALL_STACK - DecodedCRL* dcrl; -#else - DecodedCRL dcrl[1]; -#endif + WC_DECLARE_VAR(dcrl, DecodedCRL, 1, 0); WOLFSSL_ENTER("BufferLoadCRL"); @@ -791,10 +791,8 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, crl->currentEntry = CRL_Entry_new(crl->heap); if (crl->currentEntry == NULL) { - WOLFSSL_MSG("alloc CRL Entry failed"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); - #endif + WOLFSSL_MSG_CERT_LOG("alloc CRL Entry failed"); + WC_FREE_VAR_EX(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); FreeDer(&der); return MEMORY_E; } @@ -802,9 +800,11 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, InitDecodedCRL(dcrl, crl->heap); ret = ParseCRL(crl->currentEntry->certs, dcrl, myBuffer, (word32)sz, verify, crl->cm); + if (ret != 0 && !(ret == WC_NO_ERR_TRACE(ASN_CRL_NO_SIGNER_E) && verify == NO_VERIFY)) { - WOLFSSL_MSG("ParseCRL error"); + WOLFSSL_MSG_CERT_LOG("ParseCRL error"); + WOLFSSL_MSG_CERT_EX("ParseCRL verify = %d, ret = %d", verify, ret); CRL_Entry_free(crl->currentEntry, crl->heap); crl->currentEntry = NULL; } @@ -812,16 +812,14 @@ int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type, ret = AddCRL(crl, dcrl, myBuffer, ret != WC_NO_ERR_TRACE(ASN_CRL_NO_SIGNER_E)); if (ret != 0) { - WOLFSSL_MSG("AddCRL error"); + WOLFSSL_MSG_CERT_LOG("AddCRL error"); crl->currentEntry = NULL; } } FreeDecodedCRL(dcrl); -#ifdef WOLFSSL_SMALL_STACK - XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); FreeDer(&der); @@ -837,11 +835,7 @@ int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, const byte* myBuffer = buff; /* if DER ok, otherwise switch */ DerBuffer* der = NULL; CRL_Entry* crle = NULL; -#ifdef WOLFSSL_SMALL_STACK - DecodedCRL* dcrl; -#else - DecodedCRL dcrl[1]; -#endif + WC_DECLARE_VAR(dcrl, DecodedCRL, 1, 0); WOLFSSL_ENTER("GetCRLInfo"); @@ -877,9 +871,7 @@ int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, crle = CRL_Entry_new(crl->heap); if (crle == NULL) { WOLFSSL_MSG("alloc CRL Entry failed"); - #ifdef WOLFSSL_SMALL_STACK - XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); - #endif + WC_FREE_VAR_EX(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); FreeDer(&der); return MEMORY_E; } @@ -898,9 +890,7 @@ int GetCRLInfo(WOLFSSL_CRL* crl, CrlInfo* info, const byte* buff, FreeDecodedCRL(dcrl); -#ifdef WOLFSSL_SMALL_STACK - XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER); FreeDer(&der); CRL_Entry_free(crle, crl->heap); @@ -1248,23 +1238,14 @@ static int SwapLists(WOLFSSL_CRL* crl) { int ret; CRL_Entry* newList; -#ifdef WOLFSSL_SMALL_STACK - WOLFSSL_CRL* tmp; -#else - WOLFSSL_CRL tmp[1]; -#endif + WC_DECLARE_VAR(tmp, WOLFSSL_CRL, 1, 0); -#ifdef WOLFSSL_SMALL_STACK - tmp = (WOLFSSL_CRL*)XMALLOC(sizeof(WOLFSSL_CRL), NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (tmp == NULL) - return MEMORY_E; -#endif + WC_ALLOC_VAR_EX(tmp, WOLFSSL_CRL, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER, + return MEMORY_E); if (InitCRL(tmp, crl->cm) < 0) { WOLFSSL_MSG("Init tmp CRL failed"); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FATAL_ERROR; } @@ -1273,9 +1254,7 @@ static int SwapLists(WOLFSSL_CRL* crl) if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("PEM LoadCRL on dir change failed"); FreeCRL(tmp, 0); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FATAL_ERROR; } } @@ -1285,9 +1264,7 @@ static int SwapLists(WOLFSSL_CRL* crl) if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("DER LoadCRL on dir change failed"); FreeCRL(tmp, 0); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FATAL_ERROR; } } @@ -1295,9 +1272,7 @@ static int SwapLists(WOLFSSL_CRL* crl) if (wc_LockRwLock_Wr(&crl->crlLock) != 0) { WOLFSSL_MSG("wc_LockRwLock_Wr failed"); FreeCRL(tmp, 0); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return WOLFSSL_FATAL_ERROR; } @@ -1311,9 +1286,7 @@ static int SwapLists(WOLFSSL_CRL* crl) FreeCRL(tmp, 0); -#ifdef WOLFSSL_SMALL_STACK - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); return 0; } @@ -1499,11 +1472,7 @@ static THREAD_RETURN WOLFSSL_THREAD DoMonitor(void* arg) int notifyFd; int wd = -1; WOLFSSL_CRL* crl = (WOLFSSL_CRL*)arg; -#ifdef WOLFSSL_SMALL_STACK - char* buff; -#else - char buff[8192]; -#endif + WC_DECLARE_VAR(buff, char, 8192, 0); WOLFSSL_ENTER("DoMonitor"); @@ -1608,9 +1577,7 @@ static THREAD_RETURN WOLFSSL_THREAD DoMonitor(void* arg) } } -#ifdef WOLFSSL_SMALL_STACK - XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (wd > 0) { if (inotify_rm_watch(notifyFd, wd) < 0) @@ -1636,7 +1603,7 @@ static int StopMonitor(wolfSSL_CRL_mfd_t mfd) #ifdef DEBUG_WOLFSSL #define SHOW_WINDOWS_ERROR() do { \ - LPVOID lpMsgBuf; \ + LPVOID lpMsgBuf = NULL; \ DWORD dw = GetLastError(); \ FormatMessageA( \ FORMAT_MESSAGE_ALLOCATE_BUFFER | \ @@ -1820,22 +1787,14 @@ int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor) { int ret = WOLFSSL_SUCCESS; char* name = NULL; -#ifdef WOLFSSL_SMALL_STACK - ReadDirCtx* readCtx = NULL; -#else - ReadDirCtx readCtx[1]; -#endif + WC_DECLARE_VAR(readCtx, ReadDirCtx, 1, 0); WOLFSSL_ENTER("LoadCRL"); if (crl == NULL) return BAD_FUNC_ARG; -#ifdef WOLFSSL_SMALL_STACK - readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), crl->heap, - DYNAMIC_TYPE_TMP_BUFFER); - if (readCtx == NULL) - return MEMORY_E; -#endif + WC_ALLOC_VAR_EX(readCtx, ReadDirCtx, 1, crl->heap, + DYNAMIC_TYPE_TMP_BUFFER, return MEMORY_E); /* try to load each regular file in path */ ret = wc_ReadDirFirst(readCtx, path, &name); @@ -1867,9 +1826,7 @@ int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor) if (ret != WOLFSSL_SUCCESS) { WOLFSSL_MSG("CRL file load failed"); wc_ReadDirClose(readCtx); - #ifdef WOLFSSL_SMALL_STACK - XFREE(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER); - #endif + WC_FREE_VAR_EX(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } } @@ -1882,9 +1839,7 @@ int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor) /* load failures not reported, for backwards compat */ ret = WOLFSSL_SUCCESS; -#ifdef WOLFSSL_SMALL_STACK - XFREE(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER); -#endif + WC_FREE_VAR_EX(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER); if (monitor & WOLFSSL_CRL_MONITOR) { #ifdef HAVE_CRL_MONITOR diff --git a/src/src/dtls.c b/src/src/dtls.c index d25f66b..dff1ffa 100644 --- a/src/src/dtls.c +++ b/src/src/dtls.c @@ -732,8 +732,13 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) /* Ask the user for the ciphersuite matching this identity */ if (TLSX_PreSharedKey_Parse_ClientHello(&parsedExts, - tlsx.elements, (word16)tlsx.size, ssl->heap) == 0) + tlsx.elements, (word16)tlsx.size, ssl->heap) == 0) { + /* suites only needs to be refined when searching for a PSK. + * MatchSuite_ex handles refining internally. */ + refineSuites(WOLFSSL_SUITES(ssl), &suites, &suites, + ssl->options.useClientOrder); FindPskSuiteFromExt(ssl, parsedExts, &pskInfo, &suites); + } /* Revert to full handshake if PSK parsing failed */ if (pskInfo.isValid) { @@ -753,8 +758,9 @@ static int SendStatelessReplyDtls13(const WOLFSSL* ssl, WolfSSL_CH* ch) ERROR_OUT(PSK_KEY_ERROR, dtls13_cleanup); doKE = 1; } - else if ((modes & (1 << PSK_KE)) == 0) { - ERROR_OUT(PSK_KEY_ERROR, dtls13_cleanup); + else if ((modes & (1 << PSK_KE)) == 0 || + ssl->options.onlyPskDheKe) { + ERROR_OUT(PSK_KEY_ERROR, dtls13_cleanup); } usePSK = 1; } diff --git a/src/src/dtls13.c b/src/src/dtls13.c index c4e2b61..9c729fa 100644 --- a/src/src/dtls13.c +++ b/src/src/dtls13.c @@ -255,7 +255,7 @@ static int Dtls13GetRnMask(WOLFSSL* ssl, const byte* ciphertext, byte* mask, return BAD_STATE_E; #if !defined(HAVE_SELFTEST) && \ (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) \ - || defined(WOLFSSL_LINUXKM)) + || defined(WOLFSSL_KERNEL_MODE)) return wc_AesEncryptDirect(c->aes, mask, ciphertext); #else wc_AesEncryptDirect(c->aes, mask, ciphertext); @@ -1898,11 +1898,11 @@ static int _Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32 size, ret = DoTls13HandShakeMsgType(ssl, input, &idx, handshakeType, messageLength, size); + *processedSize = idx; if (ret != 0) return ret; Dtls13MsgWasProcessed(ssl, (enum HandShakeType)handshakeType); - *processedSize = idx; /* check if we have buffered some message */ if (Dtls13NextMessageComplete(ssl)) diff --git a/src/src/internal.c b/src/src/internal.c index c74bcf3..30c27fb 100644 --- a/src/src/internal.c +++ b/src/src/internal.c @@ -293,12 +293,32 @@ int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key, DerBuffer** mask) return ret; } -void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) +void wolfssl_priv_der_blind_toggle(DerBuffer* key, const DerBuffer* mask) { - if (key != NULL) { + if ((key != NULL) && (mask != NULL)) { xorbuf(key->buffer, mask->buffer, mask->length); } } + +DerBuffer *wolfssl_priv_der_unblind(const DerBuffer* key, const DerBuffer* mask) +{ + DerBuffer *ret; + if ((key == NULL) || (mask == NULL)) + return NULL; + if (mask->length > key->length) + return NULL; + if (AllocDer(&ret, key->length, key->type, key->heap) != 0) + return NULL; + xorbufout(ret->buffer, key->buffer, mask->buffer, mask->length); + return ret; +} + +void wolfssl_priv_der_unblind_free(DerBuffer* key) +{ + if (key != NULL) + FreeDer(&key); +} + #endif /* !NO_CERT && WOLFSSL_BLIND_PRIVATE_KEY */ @@ -315,69 +335,47 @@ void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask) const unsigned char* secret, int secretSz, void* ctx); #endif - - /* Label string for client random. */ - #define SSC_CR "CLIENT_RANDOM" - /* * This function builds up string for key-logging then call user's - * key-log-callback to pass the string for TLS1.2 and older. + * key-log-callback to pass the string. * The user's key-logging callback has been set via * wolfSSL_CTX_set_keylog_callback function. The logging string format is: - * "CLIENT_RANDOM " + * "